PrusaSlicer-NonPlainar/lib/Slic3r/Print.pm

527 lines
21 KiB
Perl
Raw Normal View History

2011-09-01 19:06:28 +00:00
package Slic3r::Print;
use Moo;
2011-09-01 19:06:28 +00:00
2011-11-13 17:41:12 +00:00
use Math::ConvexHull 1.0.4 qw(convex_hull);
use Slic3r::Geometry qw(X Y Z PI scale unscale move_points);
use Slic3r::Geometry::Clipper qw(diff_ex union_ex offset JT_ROUND);
has 'objects' => (is => 'rw', default => sub {[]});
has 'copies' => (is => 'rw', default => sub {[]}); # obj_idx => [copies...]
has 'total_x_length' => (is => 'rw'); # including duplicates
has 'total_y_length' => (is => 'rw'); # including duplicates
has 'total_extrusion_length' => (is => 'rw');
2011-09-03 18:47:38 +00:00
# ordered collection of extrusion paths to build skirt loops
has 'skirt' => (
2011-09-01 19:06:28 +00:00
is => 'rw',
#isa => 'ArrayRef[Slic3r::ExtrusionLoop]',
2011-09-01 19:06:28 +00:00
default => sub { [] },
);
sub add_object_from_mesh {
my $self = shift;
my ($mesh) = @_;
$mesh->rotate($Slic3r::rotate);
$mesh->scale($Slic3r::scale / $Slic3r::scaling_factor);
$mesh->align_to_origin;
# initialize print object
my @size = $mesh->size;
my $object = Slic3r::Print::Object->new(
x_length => $size[X],
y_length => $size[Y],
);
# process facets
2012-04-09 10:29:47 +00:00
{
my $apply_lines = sub {
my $lines = shift;
foreach my $layer_id (keys %$lines) {
my $layer = $object->layer($layer_id);
2012-04-09 10:29:47 +00:00
$layer->add_line($_) for @{ $lines->{$layer_id} };
}
};
Slic3r::parallelize(
disable => ($#{$mesh->facets} < 500), # don't parallelize when too few facets
items => [ 0..$#{$mesh->facets} ],
thread_cb => sub {
my $q = shift;
my $result_lines = {};
while (defined (my $facet_id = $q->dequeue)) {
my $lines = $mesh->slice_facet($object, $facet_id);
2012-04-09 10:29:47 +00:00
foreach my $layer_id (keys %$lines) {
$result_lines->{$layer_id} ||= [];
push @{ $result_lines->{$layer_id} }, @{ $lines->{$layer_id} };
}
}
return $result_lines;
},
collect_cb => sub {
$apply_lines->($_[0]);
},
no_threads_cb => sub {
for (0..$#{$mesh->facets}) {
my $lines = $mesh->slice_facet($object, $_);
2012-04-09 10:29:47 +00:00
$apply_lines->($lines);
}
},
);
}
die "Invalid input file\n" if !@{$object->layers};
# remove last layer if empty
# (we might have created it because of the $max_layer = ... + 1 code below)
pop @{$object->layers} if !@{$object->layers->[-1]->surfaces} && !@{$object->layers->[-1]->lines};
foreach my $layer (@{ $object->layers }) {
Slic3r::debugf "Making surfaces for layer %d (slice z = %f):\n",
$layer->id, unscale $layer->slice_z if $Slic3r::debug;
# layer currently has many lines representing intersections of
# model facets with the layer plane. there may also be lines
# that we need to ignore (for example, when two non-horizontal
# facets share a common edge on our plane, we get a single line;
# however that line has no meaning for our layer as it's enclosed
# inside a closed polyline)
# build surfaces from sparse lines
$layer->make_surfaces($mesh->make_loops($layer));
2012-01-28 20:52:31 +00:00
# free memory
$layer->lines(undef);
}
# detect slicing errors
my $warning_thrown = 0;
for my $i (0 .. $#{$object->layers}) {
my $layer = $object->layers->[$i];
next unless $layer->slicing_errors;
if (!$warning_thrown) {
warn "The model has overlapping or self-intersecting facets. I tried to repair it, "
. "however you might want to check the results or repair the input file and retry.\n";
$warning_thrown = 1;
}
# try to repair the layer surfaces by merging all contours and all holes from
# neighbor layers
Slic3r::debugf "Attempting to repair layer %d\n", $i;
my (@upper_surfaces, @lower_surfaces);
for (my $j = $i+1; $j <= $#{$object->layers}; $j++) {
if (!$object->layers->[$j]->slicing_errors) {
@upper_surfaces = @{$object->layers->[$j]->slices};
last;
}
}
for (my $j = $i-1; $j >= 0; $j--) {
if (!$object->layers->[$j]->slicing_errors) {
@lower_surfaces = @{$object->layers->[$j]->slices};
last;
}
}
my $union = union_ex([
map $_->expolygon->contour, @upper_surfaces, @lower_surfaces,
]);
my $diff = diff_ex(
[ map @$_, @$union ],
[ map $_->expolygon->holes, @upper_surfaces, @lower_surfaces, ],
);
@{$layer->slices} = map Slic3r::Surface->new
(expolygon => $_, surface_type => 'internal'),
@$diff;
}
# remove empty layers from bottom
while (@{$object->layers} && !@{$object->layers->[0]->slices} && !@{$object->layers->[0]->thin_walls}) {
shift @{$object->layers};
for (my $i = 0; $i <= $#{$object->layers}; $i++) {
$object->layers->[$i]->id($i);
}
}
2012-01-21 10:34:03 +00:00
warn "No layers were detected. You might want to repair your STL file and retry.\n"
if !@{$object->layers};
2012-01-21 10:34:03 +00:00
push @{$self->objects}, $object;
return $object;
}
sub layer_count {
my $self = shift;
my $count = 0;
foreach my $object (@{$self->objects}) {
$count = @{$object->layers} if @{$object->layers} > $count;
}
return $count;
}
sub arrange_objects {
my $self = shift;
my $dist = scale $Slic3r::duplicate_distance;
if ($Slic3r::duplicate_grid->[X] > 1 || $Slic3r::duplicate_grid->[Y] > 1) {
if (@{$self->objects} > 1) {
die "Grid duplication is not supported with multiple objects\n";
}
my $object = $self->objects->[0];
$self->total_x_length($object->x_length * $Slic3r::duplicate_grid->[X] + $dist * ($Slic3r::duplicate_grid->[X] - 1));
$self->total_y_length($object->y_length * $Slic3r::duplicate_grid->[Y] + $dist * ($Slic3r::duplicate_grid->[Y] - 1));
# generate offsets for copies
push @{$self->copies}, [];
for my $x_copy (1..$Slic3r::duplicate_grid->[X]) {
for my $y_copy (1..$Slic3r::duplicate_grid->[Y]) {
push @{$self->copies->[0]}, [
($self->x_length + $dist) * ($x_copy-1),
($self->y_length + $dist) * ($y_copy-1),
];
}
}
} elsif ($Slic3r::duplicate > 1 || @{$self->objects} > 1) {
my $total_parts = @{$self->objects} * $Slic3r::duplicate;
my $linint = sub {
my ($value, $oldmin, $oldmax, $newmin, $newmax) = @_;
return ($value - $oldmin) * ($newmax - $newmin) / ($oldmax - $oldmin) + $newmin;
};
# use actual part size (the largest) plus separation distance (half on each side) in spacing algorithm
my $partx = my $party = 0;
foreach my $object (@{$self->objects}) {
$partx = $object->x_length if $object->x_length > $partx;
$party = $object->y_length if $object->y_length > $party;
}
$partx = unscale($partx) + $Slic3r::duplicate_distance;
$party = unscale($party) + $Slic3r::duplicate_distance;
# margin needed for the skirt
my $skirt_margin;
if ($Slic3r::skirts > 0) {
$skirt_margin = ($Slic3r::flow_spacing * $Slic3r::skirts + $Slic3r::skirt_distance) * 2;
} else {
$skirt_margin = 0;
}
# this is how many cells we have available into which to put parts
my $cellw = int(($Slic3r::bed_size->[X] - $skirt_margin + $Slic3r::duplicate_distance) / $partx);
my $cellh = int(($Slic3r::bed_size->[Y] - $skirt_margin + $Slic3r::duplicate_distance) / $party);
die "$total_parts parts won't fit in your print area!\n" if $total_parts > ($cellw * $cellh);
# width and height of space used by cells
my $w = $cellw * $partx;
my $h = $cellh * $party;
# left and right border positions of space used by cells
2012-04-11 14:30:58 +00:00
my $l = ($Slic3r::bed_size->[X] - $w) / 2;
my $r = $l + $w;
# top and bottom border positions
2012-04-11 14:30:58 +00:00
my $t = ($Slic3r::bed_size->[Y] - $h) / 2;
my $b = $t + $h;
# list of cells, sorted by distance from center
my @cellsorder;
# work out distance for all cells, sort into list
for my $i (0..$cellw-1) {
for my $j (0..$cellh-1) {
my $cx = $linint->($i + 0.5, 0, $cellw, $l, $r);
my $cy = $linint->($j + 0.5, 0, $cellh, $t, $b);
2012-04-11 14:30:58 +00:00
my $xd = abs(($Slic3r::bed_size->[X] / 2) - $cx);
my $yd = abs(($Slic3r::bed_size->[Y] / 2) - $cy);
my $c = {
location => [$cx, $cy],
index => [$i, $j],
distance => $xd * $xd + $yd * $yd - abs(($cellw / 2) - ($i + 0.5)),
};
BINARYINSERTIONSORT: {
my $index = $c->{distance};
my $low = 0;
my $high = @cellsorder;
while ($low < $high) {
my $mid = ($low + (($high - $low) / 2)) | 0;
my $midval = $cellsorder[$mid]->[0];
if ($midval < $index) {
$low = $mid + 1;
} elsif ($midval > $index) {
$high = $mid;
} else {
splice @cellsorder, $mid, 0, [$index, $c];
last BINARYINSERTIONSORT;
}
}
splice @cellsorder, $low, 0, [$index, $c];
}
}
}
# the extents of cells actually used by objects
my ($lx, $ty, $rx, $by) = (0, 0, 0, 0);
# now find cells actually used by objects, map out the extents so we can position correctly
for my $i (1..$total_parts) {
my $c = $cellsorder[$i - 1];
my $cx = $c->[1]->{index}->[0];
my $cy = $c->[1]->{index}->[1];
if ($i == 1) {
$lx = $rx = $cx;
$ty = $by = $cy;
} else {
$rx = $cx if $cx > $rx;
$lx = $cx if $cx < $lx;
$by = $cy if $cy > $by;
$ty = $cy if $cy < $ty;
}
}
# now we actually place objects into cells, positioned such that the left and bottom borders are at 0
for (0..$#{$self->objects}) {
my @copies = ();
for (1..$Slic3r::duplicate) {
my $c = shift @cellsorder;
my $cx = $c->[1]->{index}->[0] - $lx;
my $cy = $c->[1]->{index}->[1] - $ty;
push @copies, [scale($cx * $partx), scale($cy * $party)];
}
push @{$self->copies}, [@copies];
}
2012-04-11 17:30:15 +00:00
# save size of area used
$self->total_x_length(scale(($rx - $lx + 1) * $partx - $Slic3r::duplicate_distance));
$self->total_y_length(scale(($by - $ty + 1) * $party - $Slic3r::duplicate_distance));
} else {
$self->total_x_length($self->objects->[0]->x_length);
$self->total_y_length($self->objects->[0]->y_length);
push @{$self->copies}, [[0, 0]];
}
}
sub max_length {
my $self = shift;
return ($self->total_x_length > $self->total_y_length) ? $self->total_x_length : $self->total_y_length;
}
sub make_skirt {
2011-11-13 17:41:12 +00:00
my $self = shift;
return unless $Slic3r::skirts > 0;
# collect points from all layers contained in skirt height
my $skirt_height = $Slic3r::skirt_height;
$skirt_height = $self->layer_count if $skirt_height > $self->layer_count;
my @points = ();
foreach my $obj_idx (0 .. $#{$self->objects}) {
my @layers = map $self->objects->[$obj_idx]->layer($_), 0..($skirt_height-1);
my @layer_points = (
(map @$_, map @{$_->expolygon}, map @{$_->slices}, @layers),
(map @$_, map @{$_->thin_walls}, @layers),
(map @{$_->polyline}, map @{$_->support_fills->paths}, grep $_->support_fills, @layers),
);
push @points, map move_points($_, @layer_points), @{$self->copies->[$obj_idx]};
}
return if @points < 3; # at least three points required for a convex hull
2011-11-13 17:41:12 +00:00
# find out convex hull
my $convex_hull = convex_hull(\@points);
2011-11-13 17:41:12 +00:00
# draw outlines from outside to inside
my @skirt = ();
2011-11-13 17:41:12 +00:00
for (my $i = $Slic3r::skirts - 1; $i >= 0; $i--) {
my $distance = scale ($Slic3r::skirt_distance + ($Slic3r::flow_spacing * $i));
my $outline = offset([$convex_hull], $distance, $Slic3r::scaling_factor * 100, JT_ROUND);
push @skirt, Slic3r::ExtrusionLoop->new(
polygon => Slic3r::Polygon->new(@{$outline->[0]}),
role => 'skirt',
);
2011-11-13 17:41:12 +00:00
}
push @{$self->skirt}, @skirt;
2012-02-19 11:03:36 +00:00
}
2011-09-03 18:47:38 +00:00
sub export_gcode {
my $self = shift;
my ($file) = @_;
# open output gcode file
open my $fh, ">", $file
or die "Failed to open $file for writing\n";
# write some information
my @lt = localtime;
2011-12-20 13:20:39 +00:00
printf $fh "; generated by Slic3r $Slic3r::VERSION on %02d-%02d-%02d at %02d:%02d:%02d\n\n",
2011-12-30 17:57:58 +00:00
$lt[5] + 1900, $lt[4]+1, $lt[3], $lt[2], $lt[1], $lt[0];
print $fh "; $_\n" foreach split /\R/, $Slic3r::notes;
print $fh "\n" if $Slic3r::notes;
for (qw(layer_height perimeters solid_layers fill_density nozzle_diameter filament_diameter
extrusion_multiplier perimeter_speed infill_speed travel_speed extrusion_width_ratio scale)) {
printf $fh "; %s = %s\n", $_, Slic3r::Config->get($_);
}
printf $fh "; single wall width = %.2fmm\n", $Slic3r::flow_width;
print $fh "\n";
2011-09-03 18:47:38 +00:00
# write start commands to file
printf $fh "M%s %s%d ; set bed temperature\n",
($Slic3r::gcode_flavor eq 'makerbot' ? '109' : '190'),
($Slic3r::gcode_flavor eq 'mach3' ? 'P' : 'S'), $Slic3r::first_layer_bed_temperature
if $Slic3r::first_layer_bed_temperature && $Slic3r::start_gcode !~ /M190/i;
printf $fh "M104 %s%d ; set temperature\n",
2012-02-26 13:54:38 +00:00
($Slic3r::gcode_flavor eq 'mach3' ? 'P' : 'S'), $Slic3r::first_layer_temperature
if $Slic3r::first_layer_temperature;
printf $fh "%s\n", Slic3r::Config->replace_options($Slic3r::start_gcode);
printf $fh "M109 %s%d ; wait for temperature to be reached\n",
($Slic3r::gcode_flavor eq 'mach3' ? 'P' : 'S'), $Slic3r::first_layer_temperature
if $Slic3r::first_layer_temperature && $Slic3r::gcode_flavor ne 'makerbot'
&& $Slic3r::start_gcode !~ /M109/i;
2011-09-03 18:47:38 +00:00
print $fh "G90 ; use absolute coordinates\n";
print $fh "G21 ; set units to millimeters\n";
if ($Slic3r::gcode_flavor =~ /^(?:reprap|teacup)$/) {
2012-04-16 18:06:53 +00:00
printf $fh "G92 %s0 ; reset extrusion distance\n", $Slic3r::extrusion_axis if $Slic3r::extrusion_axis;
if ($Slic3r::gcode_flavor =~ /^(?:reprap|makerbot)$/) {
if ($Slic3r::use_relative_e_distances) {
print $fh "M83 ; use relative distances for extrusion\n";
} else {
print $fh "M82 ; use absolute distances for extrusion\n";
}
}
2011-09-03 18:47:38 +00:00
}
# calculate X,Y shift to center print around specified origin
my @shift = (
$Slic3r::print_center->[X] - (unscale $self->total_x_length / 2),
$Slic3r::print_center->[Y] - (unscale $self->total_y_length / 2),
);
2011-09-05 10:21:27 +00:00
# set up our extruder object
my $extruder = Slic3r::Extruder->new;
2012-02-25 20:01:00 +00:00
my $min_print_speed = 60 * $Slic3r::min_print_speed;
my $dec = $extruder->dec;
2012-02-19 16:02:49 +00:00
if ($Slic3r::support_material && $Slic3r::support_material_tool > 0) {
print $fh $extruder->set_tool(0);
}
print $fh $extruder->set_fan(0, 1) if $Slic3r::cooling && $Slic3r::disable_fan_first_layers;
2011-09-03 18:47:38 +00:00
# write gcode commands layer by layer
my @layers = (); # [ $obj_idx, $layer ]
for my $layer_id (0..$self->layer_count) {
push @layers, map [ $_, $self->objects->[$_]->layers->[$layer_id] ], 0..$#{$self->objects};
}
foreach my $obj_layer (grep $_->[1], @layers) {
my ($obj_idx, $layer) = @$obj_layer;
2012-02-26 13:54:38 +00:00
if ($layer->id == 1) {
printf $fh "M104 %s%d ; set temperature\n",
($Slic3r::gcode_flavor eq 'mach3' ? 'P' : 'S'), $Slic3r::temperature
if $Slic3r::temperature && $Slic3r::temperature != $Slic3r::first_layer_temperature;
printf $fh "M140 %s%d ; set bed temperature\n",
($Slic3r::gcode_flavor eq 'mach3' ? 'P' : 'S'), $Slic3r::bed_temperature
if $Slic3r::bed_temperature && $Slic3r::bed_temperature != $Slic3r::first_layer_bed_temperature;
2012-02-26 13:54:38 +00:00
}
2011-09-03 18:47:38 +00:00
# go to layer
my $layer_gcode = $extruder->change_layer($layer);
2012-02-25 20:01:00 +00:00
$extruder->elapsed_time(0);
# extrude skirt
$extruder->shift_x($shift[X]);
$extruder->shift_y($shift[Y]);
2012-02-25 20:01:00 +00:00
$layer_gcode .= $extruder->set_acceleration($Slic3r::perimeter_acceleration);
if ($layer->id < $Slic3r::skirt_height) {
$layer_gcode .= $extruder->extrude_loop($_, 'skirt') for @{$self->skirt};
}
2011-09-05 18:00:59 +00:00
for my $copy (@{ $self->copies->[$obj_idx] }) {
# retract explicitely because changing the shift_[xy] properties below
# won't always trigger the automatic retraction
$layer_gcode .= $extruder->retract;
$extruder->shift_x($shift[X] + unscale $copy->[X]);
$extruder->shift_y($shift[Y] + unscale $copy->[Y]);
# extrude perimeters
2012-02-25 20:01:00 +00:00
$layer_gcode .= $extruder->extrude($_, 'perimeter') for @{ $layer->perimeters };
# extrude fills
2012-02-25 20:01:00 +00:00
$layer_gcode .= $extruder->set_acceleration($Slic3r::infill_acceleration);
for my $fill (@{ $layer->fills }) {
2012-02-25 20:01:00 +00:00
$layer_gcode .= $extruder->extrude_path($_, 'fill')
for $fill->shortest_path($extruder->last_pos);
}
2012-02-19 11:03:36 +00:00
# extrude support material
if ($layer->support_fills) {
2012-02-25 20:01:00 +00:00
$layer_gcode .= $extruder->set_tool($Slic3r::support_material_tool)
2012-02-19 16:02:49 +00:00
if $Slic3r::support_material_tool > 0;
2012-02-25 20:01:00 +00:00
$layer_gcode .= $extruder->extrude_path($_, 'support material')
2012-02-19 11:03:36 +00:00
for $layer->support_fills->shortest_path($extruder->last_pos);
2012-02-25 20:01:00 +00:00
$layer_gcode .= $extruder->set_tool(0)
2012-02-19 16:02:49 +00:00
if $Slic3r::support_material_tool > 0;
2012-02-19 11:03:36 +00:00
}
2011-09-26 08:52:58 +00:00
}
2012-02-25 20:01:00 +00:00
last if !$layer_gcode;
2012-03-03 21:21:30 +00:00
my $fan_speed = $Slic3r::fan_always_on ? $Slic3r::min_fan_speed : 0;
2012-02-25 20:01:00 +00:00
my $speed_factor = 1;
if ($Slic3r::cooling) {
my $layer_time = $extruder->elapsed_time;
Slic3r::debugf "Layer %d estimated printing time: %d seconds\n", $layer->id, $layer_time;
if ($layer_time < $Slic3r::slowdown_below_layer_time) {
$fan_speed = $Slic3r::max_fan_speed;
$speed_factor = $layer_time / $Slic3r::slowdown_below_layer_time;
} elsif ($layer_time < $Slic3r::fan_below_layer_time) {
$fan_speed = $Slic3r::max_fan_speed - ($Slic3r::max_fan_speed - $Slic3r::min_fan_speed)
* ($layer_time - $Slic3r::slowdown_below_layer_time)
/ ($Slic3r::fan_below_layer_time - $Slic3r::slowdown_below_layer_time); #/
2012-02-25 20:01:00 +00:00
}
Slic3r::debugf " fan = %d%%, speed = %d%%\n", $fan_speed, $speed_factor * 100;
if ($speed_factor < 1) {
2012-04-03 12:22:18 +00:00
$layer_gcode =~ s/^(?=.*? [XY])(?=.*? E)(G1 .*?F)(\d+(?:\.\d+)?)/
my $new_speed = $2 * $speed_factor;
$1 . sprintf("%.${dec}f", $new_speed < $min_print_speed ? $min_print_speed : $new_speed)
/gexm;
}
$fan_speed = 0 if $layer->id < $Slic3r::disable_fan_first_layers;
2012-02-25 20:01:00 +00:00
}
2012-03-03 21:21:30 +00:00
$layer_gcode = $extruder->set_fan($fan_speed) . $layer_gcode;
2012-02-25 20:01:00 +00:00
# bridge fan speed
if (!$Slic3r::cooling || $Slic3r::bridge_fan_speed == 0 || $layer->id < $Slic3r::disable_fan_first_layers) {
$layer_gcode =~ s/^;_BRIDGE_FAN_(?:START|END)\n//gm;
2012-02-25 20:01:00 +00:00
} else {
$layer_gcode =~ s/^;_BRIDGE_FAN_START\n/ $extruder->set_fan($Slic3r::bridge_fan_speed, 1) /gmex;
$layer_gcode =~ s/^;_BRIDGE_FAN_END\n/ $extruder->set_fan($fan_speed, 1) /gmex;
2012-02-25 20:01:00 +00:00
}
print $fh $layer_gcode;
2011-09-03 18:47:38 +00:00
}
# save statistic data
$self->total_extrusion_length($extruder->total_extrusion_length);
2011-09-03 18:47:38 +00:00
# write end commands to file
2012-01-20 13:48:51 +00:00
print $fh $extruder->retract;
2012-02-25 20:01:00 +00:00
print $fh $extruder->set_fan(0);
print $fh "M501 ; reset acceleration\n" if $Slic3r::acceleration;
printf $fh "%s\n", Slic3r::Config->replace_options($Slic3r::end_gcode);
2011-09-03 18:47:38 +00:00
printf $fh "; filament used = %.1fmm (%.1fcm3)\n",
$self->total_extrusion_length, $self->total_extrusion_volume;
2011-09-03 18:47:38 +00:00
# close our gcode file
close $fh;
}
sub total_extrusion_volume {
my $self = shift;
return $self->total_extrusion_length * ($Slic3r::filament_diameter**2) * PI/4 / 1000;
}
2011-09-01 19:06:28 +00:00
1;