4
use File::Basename qw(basename fileparse);
6
use List::Util qw(min max first sum);
7
use Slic3r::ExtrusionPath ':roles';
8
use Slic3r::Flow ':roles';
9
use Slic3r::Geometry qw(X Y Z X1 Y1 X2 Y2 MIN MAX PI scale unscale move_points chained_path
11
use Slic3r::Geometry::Clipper qw(diff_ex union_ex union_pt intersection_ex intersection offset
12
offset2 union union_pt_chained JT_ROUND JT_SQUARE);
13
use Slic3r::Print::State ':steps';
15
has 'config' => (is => 'ro', default => sub { Slic3r::Config::Print->new });
16
has 'default_object_config' => (is => 'ro', default => sub { Slic3r::Config::PrintObject->new });
17
has 'default_region_config' => (is => 'ro', default => sub { Slic3r::Config::PrintRegion->new });
18
has 'placeholder_parser' => (is => 'rw', default => sub { Slic3r::GCode::PlaceholderParser->new });
19
has 'objects' => (is => 'rw', default => sub {[]});
20
has 'status_cb' => (is => 'rw');
21
has 'regions' => (is => 'rw', default => sub {[]});
22
has 'total_used_filament' => (is => 'rw');
23
has 'total_extruded_volume' => (is => 'rw');
24
has '_state' => (is => 'ro', default => sub { Slic3r::Print::State->new });
26
# ordered collection of extrusion paths to build skirt loops
27
has 'skirt' => (is => 'rw', default => sub { Slic3r::ExtrusionPath::Collection->new });
29
# ordered collection of extrusion paths to build a brim
30
has 'brim' => (is => 'rw', default => sub { Slic3r::ExtrusionPath::Collection->new });
33
my ($self, $config) = @_;
35
$config = $config->clone;
38
# apply variables to placeholder parser
39
$self->placeholder_parser->apply_config($config);
41
# handle changes to print config
42
my $print_diff = $self->config->diff($config);
44
$self->config->apply_dynamic($config);
46
# TODO: only invalidate changed steps
47
$self->_state->invalidate_all;
50
# handle changes to object config defaults
51
$self->default_object_config->apply_dynamic($config);
52
foreach my $object (@{$self->objects}) {
53
# we don't assume that $config contains a full ObjectConfig,
54
# so we base it on the current print-wise default
55
my $new = $self->default_object_config->clone;
57
# we override the new config with object-specific options
58
my $model_object_config = $object->model_object->config->clone;
59
$model_object_config->normalize;
60
$new->apply_dynamic($model_object_config);
62
# check whether the new config is different from the current one
63
my $diff = $object->config->diff($new);
65
$object->config->apply($new);
66
# TODO: only invalidate changed steps
67
$object->_state->invalidate_all;
71
# handle changes to regions config defaults
72
$self->default_region_config->apply_dynamic($config);
74
# All regions now have distinct settings.
75
# Check whether applying the new region config defaults we'd get different regions.
76
my $rearrange_regions = 0;
77
REGION: foreach my $region_id (0..$#{$self->regions}) {
78
foreach my $object (@{$self->objects}) {
79
foreach my $volume_id (@{ $object->region_volumes->[$region_id] }) {
80
my $volume = $object->model_object->volumes->[$volume_id];
82
my $new = $self->default_region_config->clone;
84
my $model_object_config = $object->model_object->config->clone;
85
$model_object_config->normalize;
86
$new->apply_dynamic($model_object_config);
88
if (defined $volume->material_id) {
89
my $material_config = $object->model_object->model->get_material($volume->material_id)->config->clone;
90
$material_config->normalize;
91
$new->apply_dynamic($material_config);
93
if (!$new->equals($self->regions->[$region_id]->config)) {
94
$rearrange_regions = 1;
101
# Some optimization is possible: if the volumes-regions mappings don't change
102
# but still region configs are changed somehow, we could just apply the diff
103
# and invalidate the affected steps.
104
if ($rearrange_regions) {
105
# the current subdivision of regions does not make sense anymore.
106
# we need to remove all objects and re-add them
107
my @model_objects = map $_->model_object, @{$self->objects};
108
$self->clear_objects;
109
$self->add_model_object($_) for @model_objects;
113
sub has_support_material {
115
return (first { $_->config->support_material } @{$self->objects})
116
|| (first { $_->config->raft_layers > 0 } @{$self->objects})
117
|| (first { $_->config->support_material_enforce_layers > 0 } @{$self->objects});
120
# caller is responsible for supplying models whose objects don't collide
121
# and have explicit instance positions
122
sub add_model_object {
124
my ($object, $obj_idx) = @_;
126
my $object_config = $object->config->clone;
127
$object_config->normalize;
129
my %volumes = (); # region_id => [ volume_id, ... ]
130
foreach my $volume_id (0..$#{$object->volumes}) {
131
my $volume = $object->volumes->[$volume_id];
133
# get the config applied to this volume: start from our global defaults
134
my $config = Slic3r::Config::PrintRegion->new;
135
$config->apply($self->default_region_config);
137
# override the defaults with per-object config and then with per-material config
138
$config->apply_dynamic($object_config);
140
if (defined $volume->material_id) {
141
my $material_config = $volume->material->config->clone;
142
$material_config->normalize;
143
$config->apply_dynamic($material_config);
146
# find an existing print region with the same config
148
foreach my $i (0..$#{$self->regions}) {
149
my $region = $self->regions->[$i];
150
if ($config->equals($region->config)) {
156
# if no region exists with the same config, create a new one
157
if (!defined $region_id) {
158
push @{$self->regions}, my $r = Slic3r::Print::Region->new(
161
$r->config->apply($config);
162
$region_id = $#{$self->regions};
165
# assign volume to region
166
$volumes{$region_id} //= [];
167
push @{ $volumes{$region_id} }, $volume_id;
170
# initialize print object
171
my $o = Slic3r::Print::Object->new(
173
model_object => $object,
174
region_volumes => [ map $volumes{$_}, 0..$#{$self->regions} ],
175
copies => [ map Slic3r::Point->new_scale(@{ $_->offset }), @{ $object->instances } ],
176
layer_height_ranges => $object->layer_height_ranges,
179
# apply config to print object
180
$o->config->apply($self->default_object_config);
181
$o->config->apply_dynamic($object_config);
183
# store print object at the given position
184
if (defined $obj_idx) {
185
splice @{$self->objects}, $obj_idx, 0, $o;
187
push @{$self->objects}, $o;
190
$self->_state->invalidate(STEP_SKIRT);
191
$self->_state->invalidate(STEP_BRIM);
195
my ($self, $obj_idx) = @_;
197
splice @{$self->objects}, $obj_idx, 1;
198
# TODO: purge unused regions
200
$self->_state->invalidate(STEP_SKIRT);
201
$self->_state->invalidate(STEP_BRIM);
207
@{$self->objects} = ();
208
@{$self->regions} = ();
210
$self->_state->invalidate(STEP_SKIRT);
211
$self->_state->invalidate(STEP_BRIM);
215
my ($self, $obj_idx) = @_;
217
# TODO: this method should check whether the per-object config and per-material configs
218
# have changed in such a way that regions need to be rearranged or we can just apply
219
# the diff and invalidate something. Same logic as apply_config()
220
# For now we just re-add all objects since we haven't implemented this incremental logic yet.
221
# This should also check whether object volumes (parts) have changed.
223
my @models_objects = map $_->model_object, @{$self->objects};
224
$self->clear_objects;
225
$self->add_model_object($_) for @models_objects;
231
if ($self->config->complete_objects) {
232
# check horizontal clearance
235
foreach my $object (@{$self->objects}) {
236
# get convex hulls of all meshes assigned to this print object
237
my @mesh_convex_hulls = map $object->model_object->volumes->[$_]->mesh->convex_hull,
240
@{$object->region_volumes};
242
# make a single convex hull for all of them
243
my $convex_hull = convex_hull([ map @$_, @mesh_convex_hulls ]);
245
# apply the same transformations we apply to the actual meshes when slicing them
246
$object->model_object->instances->[0]->transform_polygon($convex_hull, 1);
248
# align object to Z = 0 and apply XY shift
249
$convex_hull->translate(@{$object->_copies_shift});
251
# grow convex hull with the clearance margin
252
($convex_hull) = @{offset([$convex_hull], scale $self->config->extruder_clearance_radius / 2, 1, JT_ROUND, scale(0.1))};
254
# now we need that no instance of $convex_hull does not intersect any of the previously checked object instances
255
for my $copy (@{$object->_shifted_copies}) {
256
my $p = $convex_hull->clone;
258
$p->translate(@$copy);
259
if (@{ intersection(\@a, [$p]) }) {
260
die "Some objects are too close; your extruder will collide with them.\n";
262
@a = @{union([@a, $p])};
267
# check vertical clearance
269
my @object_height = ();
270
foreach my $object (@{$self->objects}) {
271
my $height = $object->size->z;
272
push @object_height, $height for @{$object->copies};
274
@object_height = sort { $a <=> $b } @object_height;
275
# ignore the tallest *copy* (this is why we repeat height for all of them):
276
# it will be printed as last one so its height doesn't matter
278
if (@object_height && max(@object_height) > scale $self->config->extruder_clearance_height) {
279
die "Some objects are too tall and cannot be printed without extruder collisions.\n";
284
if ($self->config->spiral_vase) {
285
if ((map @{$_->copies}, @{$self->objects}) > 1) {
286
die "The Spiral Vase option can only be used when printing a single object.\n";
288
if (@{$self->regions} > 1) {
289
die "The Spiral Vase option can only be used when printing single material objects.\n";
294
# 0-based indices of used extruders
298
# initialize all extruder(s) we need
299
my @used_extruders = ();
300
foreach my $region (@{$self->regions}) {
301
push @used_extruders,
302
map $region->config->get("${_}_extruder")-1,
303
qw(perimeter infill);
305
foreach my $object (@{$self->objects}) {
306
push @used_extruders,
307
map $object->config->get("${_}_extruder")-1,
308
qw(support_material support_material_interface);
311
my %h = map { $_ => 1 } @used_extruders;
312
return [ sort keys %h ];
318
# enforce tall skirt if using ooze_prevention
319
# FIXME: this is not idempotent (i.e. switching ooze_prevention off will not revert skirt settings)
320
if ($self->config->ooze_prevention && @{$self->extruders} > 1) {
321
$self->config->set('skirt_height', -1);
322
$self->config->set('skirts', 1) if $self->config->skirts == 0;
326
# this value is not supposed to be compared with $layer->id
327
# since they have different semantics
330
return max(map $_->layer_count, @{$self->objects});
335
return scalar @{$self->regions};
342
foreach my $object (@{$self->objects}) {
343
foreach my $copy (@{$object->_shifted_copies}) {
345
[ $copy->[X], $copy->[Y] ],
346
[ $copy->[X] + $object->size->[X], $copy->[Y] + $object->size->[Y] ];
349
return Slic3r::Geometry::BoundingBox->new_from_points([ map Slic3r::Point->new(@$_), @points ]);
354
return $self->bounding_box->size;
357
sub _simplify_slices {
361
foreach my $layer (map @{$_->layers}, @{$self->objects}) {
362
$layer->slices->simplify($distance);
363
$_->slices->simplify($distance) for @{$layer->regions};
370
my $status_cb = $self->status_cb // sub {};
372
my $print_step = sub {
373
my ($step, $cb) = @_;
374
if (!$self->_state->done($step)) {
375
$self->_state->set_started($step);
377
### Re-enable this for step-based slicing:
378
### $self->_state->set_done($step);
381
my $object_step = sub {
382
my ($step, $cb) = @_;
383
for my $obj_idx (0..$#{$self->objects}) {
384
my $object = $self->objects->[$obj_idx];
385
if (!$object->_state->done($step)) {
386
$object->_state->set_started($step);
388
### Re-enable this for step-based slicing:
389
### $object->_state->set_done($step);
394
# STEP_INIT_EXTRUDERS
395
$print_step->(STEP_INIT_EXTRUDERS, sub {
396
$self->init_extruders;
400
# skein the STL into layers
401
# each layer has surfaces with holes
402
$status_cb->(10, "Processing triangulated mesh");
403
$object_step->(STEP_SLICE, sub {
404
$self->objects->[$_[0]]->slice;
407
die "No layers were detected. You might want to repair your STL file(s) or check their size and retry.\n"
408
if !grep @{$_->layers}, @{$self->objects};
411
# this will add a set of extrusion loops to each layer
412
# as well as generate infill boundaries
413
$status_cb->(20, "Generating perimeters");
414
$object_step->(STEP_PERIMETERS, sub {
415
$self->objects->[$_[0]]->make_perimeters;
418
$status_cb->(30, "Preparing infill");
419
$object_step->(STEP_PREPARE_INFILL, sub {
420
my $object = $self->objects->[$_[0]];
422
# this will assign a type (top/bottom/internal) to $layerm->slices
423
# and transform $layerm->fill_surfaces from expolygon
424
# to typed top/bottom/internal surfaces;
425
$object->detect_surfaces_type;
427
# decide what surfaces are to be filled
428
$_->prepare_fill_surfaces for map @{$_->regions}, @{$object->layers};
430
# this will detect bridges and reverse bridges
431
# and rearrange top/bottom/internal surfaces
432
$object->process_external_surfaces;
434
# detect which fill surfaces are near external layers
435
# they will be split in internal and internal-solid surfaces
436
$object->discover_horizontal_shells;
437
$object->clip_fill_surfaces;
439
# the following step needs to be done before combination because it may need
440
# to remove only half of the combined infill
441
$object->bridge_over_infill;
443
# combine fill surfaces to honor the "infill every N layers" option
444
$object->combine_infill;
447
# this will generate extrusion paths for each layer
448
$status_cb->(70, "Infilling layers");
449
$object_step->(STEP_INFILL, sub {
450
my $object = $self->objects->[$_[0]];
453
threads => $self->config->threads,
455
my @items = (); # [layer_id, region_id]
456
for my $region_id (0 .. ($self->regions_count-1)) {
457
push @items, map [$_, $region_id], 0..$#{$object->layers};
463
while (defined (my $obj_layer = $q->dequeue)) {
464
my ($i, $region_id) = @$obj_layer;
465
my $layerm = $object->layers->[$i]->regions->[$region_id];
466
$layerm->fills->append( $object->fill_maker->make_fill($layerm) );
469
collect_cb => sub {},
470
no_threads_cb => sub {
471
foreach my $layerm (map @{$_->regions}, @{$object->layers}) {
472
$layerm->fills->append($object->fill_maker->make_fill($layerm));
477
### we could free memory now, but this would make this step not idempotent
478
### $_->fill_surfaces->clear for map @{$_->regions}, @{$object->layers};
481
# generate support material
482
$status_cb->(85, "Generating support material") if $self->has_support_material;
483
$object_step->(STEP_SUPPORTMATERIAL, sub {
484
$self->objects->[$_[0]]->generate_support_material;
488
$status_cb->(88, "Generating skirt/brim");
489
$print_step->(STEP_SKIRT, sub {
492
$print_step->(STEP_BRIM, sub {
493
$self->make_brim; # must come after make_skirt
496
# time to make some statistics
498
eval "use Devel::Size";
499
print "MEMORY USAGE:\n";
500
printf " meshes = %.1fMb\n", List::Util::sum(map Devel::Size::total_size($_->meshes), @{$self->objects})/1024/1024;
501
printf " layer slices = %.1fMb\n", List::Util::sum(map Devel::Size::total_size($_->slices), map @{$_->layers}, @{$self->objects})/1024/1024;
502
printf " region slices = %.1fMb\n", List::Util::sum(map Devel::Size::total_size($_->slices), map @{$_->regions}, map @{$_->layers}, @{$self->objects})/1024/1024;
503
printf " perimeters = %.1fMb\n", List::Util::sum(map Devel::Size::total_size($_->perimeters), map @{$_->regions}, map @{$_->layers}, @{$self->objects})/1024/1024;
504
printf " fills = %.1fMb\n", List::Util::sum(map Devel::Size::total_size($_->fills), map @{$_->regions}, map @{$_->layers}, @{$self->objects})/1024/1024;
505
printf " print object = %.1fMb\n", Devel::Size::total_size($self)/1024/1024;
508
eval "use Slic3r::Test::SectionCut";
509
Slic3r::Test::SectionCut->new(print => $self)->export_svg("section_cut.svg");
517
my $status_cb = $self->status_cb // sub {};
519
# output everything to a G-code file
520
my $output_file = $self->expanded_output_filepath($params{output_file});
521
$status_cb->(90, "Exporting G-code" . ($output_file ? " to $output_file" : ""));
522
$self->write_gcode($params{output_fh} || $output_file);
524
# run post-processing scripts
525
if (@{$self->config->post_process}) {
526
$status_cb->(95, "Running post-processing scripts");
527
$self->config->setenv;
528
for (@{$self->config->post_process}) {
529
Slic3r::debugf " '%s' '%s'\n", $_, $output_file;
530
system($_, $output_file);
540
$self->init_extruders;
542
$_->slice for @{$self->objects};
544
my $fh = $params{output_fh};
546
my $output_file = $self->expanded_output_filepath($params{output_file});
547
$output_file =~ s/\.gcode$/.svg/i;
548
Slic3r::open(\$fh, ">", $output_file) or die "Failed to open $output_file for writing\n";
549
print "Exporting to $output_file..." unless $params{quiet};
552
my $print_size = $self->size;
553
print $fh sprintf <<"EOF", unscale($print_size->[X]), unscale($print_size->[Y]);
554
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
555
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.0//EN" "http://www.w3.org/TR/2001/REC-SVG-20010904/DTD/svg10.dtd">
556
<svg width="%s" height="%s" xmlns="http://www.w3.org/2000/svg" xmlns:svg="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" xmlns:slic3r="http://slic3r.org/namespaces/slic3r">
558
Generated using Slic3r $Slic3r::VERSION
563
my $print_polygon = sub {
564
my ($polygon, $type) = @_;
565
printf $fh qq{ <polygon slic3r:type="%s" points="%s" style="fill: %s" />\n},
566
$type, (join ' ', map { join ',', map unscale $_, @$_ } @$polygon),
567
($type eq 'contour' ? 'white' : 'black');
570
my @layers = sort { $a->print_z <=> $b->print_z }
571
map { @{$_->layers}, @{$_->support_layers} }
575
my @previous_layer_slices = ();
576
for my $layer (@layers) {
578
# TODO: remove slic3r:z for raft layers
579
printf $fh qq{ <g id="layer%d" slic3r:z="%s">\n}, $layer_id, unscale($layer->slice_z);
581
my @current_layer_slices = ();
582
# sort slices so that the outermost ones come first
583
my @slices = sort { $a->contour->contains_point($b->contour->[0]) ? 0 : 1 } @{$layer->slices};
584
foreach my $copy (@{$layer->object->copies}) {
585
foreach my $slice (@slices) {
586
my $expolygon = $slice->clone;
587
$expolygon->translate(@$copy);
588
$print_polygon->($expolygon->contour, 'contour');
589
$print_polygon->($_, 'hole') for @{$expolygon->holes};
590
push @current_layer_slices, $expolygon;
593
# generate support material
594
if ($self->has_support_material && $layer->id > 0) {
595
my (@supported_slices, @unsupported_slices) = ();
596
foreach my $expolygon (@current_layer_slices) {
597
my $intersection = intersection_ex(
598
[ map @$_, @previous_layer_slices ],
602
? push @supported_slices, $expolygon
603
: push @unsupported_slices, $expolygon;
605
my @supported_points = map @$_, @$_, @supported_slices;
606
foreach my $expolygon (@unsupported_slices) {
607
# look for the nearest point to this island among all
609
my $contour = $expolygon->contour;
610
my $support_point = $contour->first_point->nearest_point(\@supported_points)
612
my $anchor_point = $support_point->nearest_point([ @$contour ]);
613
printf $fh qq{ <line x1="%s" y1="%s" x2="%s" y2="%s" style="stroke-width: 2; stroke: white" />\n},
614
map @$_, $support_point, $anchor_point;
617
print $fh qq{ </g>\n};
618
@previous_layer_slices = @current_layer_slices;
621
print $fh "</svg>\n";
623
print "Done.\n" unless $params{quiet};
629
# since this method must be idempotent, we clear skirt paths *before*
630
# checking whether we need to generate them
633
return unless $self->config->skirts > 0
634
|| ($self->config->ooze_prevention && @{$self->extruders} > 1);
636
# First off we need to decide how tall the skirt must be.
637
# The skirt_height option from config is expressed in layers, but our
638
# object might have different layer heights, so we need to find the print_z
639
# of the highest layer involved.
640
# Note that unless skirt_height == -1 (which means it's printed on all layers)
641
# the actual skirt might not reach this $skirt_height_z value since the print
642
# order of objects on each layer is not guaranteed and will not generally
643
# include the thickest object first. It is just guaranteed that a skirt is
644
# prepended to the first 'n' layers (with 'n' = skirt_height).
645
# $skirt_height_z in this case is the highest possible skirt height for safety.
646
my $skirt_height_z = -1;
647
foreach my $object (@{$self->objects}) {
648
my $skirt_height = ($self->config->skirt_height == -1)
649
? scalar(@{$object->layers})
650
: min($self->config->skirt_height, scalar(@{$object->layers}));
652
my $highest_layer = $object->layers->[$skirt_height-1];
653
$skirt_height_z = max($skirt_height_z, $highest_layer->print_z);
656
# collect points from all layers contained in skirt height
658
foreach my $object (@{$self->objects}) {
659
my @object_points = ();
661
# get object layers up to $skirt_height_z
662
foreach my $layer (@{$object->layers}) {
663
last if $layer->print_z > $skirt_height_z;
664
push @object_points, map @$_, map @$_, @{$layer->slices};
667
# get support layers up to $skirt_height_z
668
foreach my $layer (@{$object->support_layers}) {
669
last if $layer->print_z > $skirt_height_z;
670
push @object_points, map @{$_->polyline}, @{$layer->support_fills} if $layer->support_fills;
671
push @object_points, map @{$_->polyline}, @{$layer->support_interface_fills} if $layer->support_interface_fills;
674
# repeat points for each object copy
675
foreach my $copy (@{$object->_shifted_copies}) {
676
my @copy_points = map $_->clone, @object_points;
677
$_->translate(@$copy) for @copy_points;
678
push @points, @copy_points;
681
return if @points < 3; # at least three points required for a convex hull
683
# find out convex hull
684
my $convex_hull = convex_hull(\@points);
686
my @extruded_length = (); # for each extruder
688
# skirt may be printed on several layers, having distinct layer heights,
689
# but loops must be aligned so can't vary width/spacing
690
# TODO: use each extruder's own flow
691
my $first_layer_height = $self->objects->[0]->config->get_value('first_layer_height');
692
my $flow = Slic3r::Flow->new_from_width(
693
width => ($self->config->first_layer_extrusion_width || $self->regions->[0]->config->perimeter_extrusion_width),
694
role => FLOW_ROLE_PERIMETER,
695
nozzle_diameter => $self->config->nozzle_diameter->[0],
696
layer_height => $first_layer_height,
697
bridge_flow_ratio => 0,
699
my $spacing = $flow->spacing;
700
my $mm3_per_mm = $flow->mm3_per_mm($first_layer_height);
702
my @extruders_e_per_mm = ();
703
my $extruder_idx = 0;
705
# draw outlines from outside to inside
706
# loop while we have less skirts than required or any extruder hasn't reached the min length if any
707
my $distance = scale $self->config->skirt_distance;
708
for (my $i = $self->config->skirts; $i > 0; $i--) {
709
$distance += scale $spacing;
710
my $loop = offset([$convex_hull], $distance, 1, JT_ROUND, scale(0.1))->[0];
711
$self->skirt->append(Slic3r::ExtrusionLoop->new_from_paths(
712
Slic3r::ExtrusionPath->new(
713
polyline => Slic3r::Polygon->new(@$loop)->split_at_first_point,
714
role => EXTR_ROLE_SKIRT,
715
mm3_per_mm => $mm3_per_mm,
716
width => $flow->width,
717
height => $first_layer_height,
721
if ($self->config->min_skirt_length > 0) {
722
$extruded_length[$extruder_idx] ||= 0;
723
if (!$extruders_e_per_mm[$extruder_idx]) {
724
my $extruder = Slic3r::Extruder->new($extruder_idx, $self->config);
725
$extruders_e_per_mm[$extruder_idx] = $extruder->e_per_mm($mm3_per_mm);
727
$extruded_length[$extruder_idx] += unscale $loop->length * $extruders_e_per_mm[$extruder_idx];
728
$i++ if defined first { ($extruded_length[$_] // 0) < $self->config->min_skirt_length } 0 .. $#{$self->extruders};
729
if ($extruded_length[$extruder_idx] >= $self->config->min_skirt_length) {
730
if ($extruder_idx < $#{$self->extruders}) {
738
$self->skirt->reverse;
744
# since this method must be idempotent, we clear brim paths *before*
745
# checking whether we need to generate them
748
return unless $self->config->brim_width > 0;
750
# brim is only printed on first layer and uses support material extruder
751
my $first_layer_height = $self->objects->[0]->config->get_abs_value('first_layer_height');
752
my $flow = Slic3r::Flow->new_from_width(
753
width => ($self->config->first_layer_extrusion_width || $self->regions->[0]->config->perimeter_extrusion_width),
754
role => FLOW_ROLE_PERIMETER,
755
nozzle_diameter => $self->config->get_at('nozzle_diameter', $self->objects->[0]->config->support_material_extruder-1),
756
layer_height => $first_layer_height,
757
bridge_flow_ratio => 0,
759
my $mm3_per_mm = $flow->mm3_per_mm($first_layer_height);
761
my $grow_distance = $flow->scaled_width / 2;
762
my @islands = (); # array of polygons
763
foreach my $obj_idx (0 .. $#{$self->objects}) {
764
my $object = $self->objects->[$obj_idx];
765
my $layer0 = $object->layers->[0];
766
my @object_islands = (
767
(map $_->contour, @{$layer0->slices}),
769
if (@{ $object->support_layers }) {
770
my $support_layer0 = $object->support_layers->[0];
771
push @object_islands,
772
(map @{$_->polyline->grow($grow_distance)}, @{$support_layer0->support_fills})
773
if $support_layer0->support_fills;
774
push @object_islands,
775
(map @{$_->polyline->grow($grow_distance)}, @{$support_layer0->support_interface_fills})
776
if $support_layer0->support_interface_fills;
778
foreach my $copy (@{$object->_shifted_copies}) {
779
push @islands, map { $_->translate(@$copy); $_ } map $_->clone, @object_islands;
783
# if brim touches skirt, make it around skirt too
784
# TODO: calculate actual skirt width (using each extruder's flow in multi-extruder setups)
785
if ($self->config->skirt_distance + (($self->config->skirts - 1) * $flow->spacing) <= $self->config->brim_width) {
786
push @islands, map @{$_->polygon->split_at_first_point->grow($grow_distance)}, @{$self->skirt};
790
my $num_loops = sprintf "%.0f", $self->config->brim_width / $flow->width;
791
for my $i (reverse 1 .. $num_loops) {
792
# JT_SQUARE ensures no vertex is outside the given offset distance
793
# -0.5 because islands are not represented by their centerlines
794
# (first offset more, then step back - reverse order than the one used for
795
#Ā perimeters because here we're offsetting outwards)
796
push @loops, @{offset2(\@islands, ($i + 0.5) * $flow->scaled_spacing, -1.0 * $flow->scaled_spacing, 100000, JT_SQUARE)};
799
$self->brim->append(map Slic3r::ExtrusionLoop->new_from_paths(
800
Slic3r::ExtrusionPath->new(
801
polyline => Slic3r::Polygon->new(@$_)->split_at_first_point,
802
role => EXTR_ROLE_SKIRT,
803
mm3_per_mm => $mm3_per_mm,
804
width => $flow->width,
805
height => $first_layer_height,
807
), reverse @{union_pt_chained(\@loops)});
814
# open output gcode file if we weren't supplied a file-handle
816
if (ref $file eq 'IO::Scalar') {
819
Slic3r::open(\$fh, ">", $file)
820
or die "Failed to open $file for writing\n";
822
# enable UTF-8 output since user might have entered Unicode characters in fields like notes
823
binmode $fh, ':utf8';
827
# write some information
829
printf $fh "; generated by Slic3r $Slic3r::VERSION on %04d-%02d-%02d at %02d:%02d:%02d\n\n",
830
$lt[5] + 1900, $lt[4]+1, $lt[3], $lt[2], $lt[1], $lt[0];
832
print $fh "; $_\n" foreach split /\R/, $self->config->notes;
833
print $fh "\n" if $self->config->notes;
835
my $first_object = $self->objects->[0];
836
my $layer_height = $first_object->config->layer_height;
837
for my $region_id (0..$#{$self->regions}) {
838
printf $fh "; perimeters extrusion width = %.2fmm\n",
839
$self->regions->[$region_id]->flow(FLOW_ROLE_PERIMETER, $layer_height, 0, 0, undef, $first_object)->width;
840
printf $fh "; infill extrusion width = %.2fmm\n",
841
$self->regions->[$region_id]->flow(FLOW_ROLE_INFILL, $layer_height, 0, 0, undef, $first_object)->width;
842
printf $fh "; solid infill extrusion width = %.2fmm\n",
843
$self->regions->[$region_id]->flow(FLOW_ROLE_SOLID_INFILL, $layer_height, 0, 0, undef, $first_object)->width;
844
printf $fh "; top infill extrusion width = %.2fmm\n",
845
$self->regions->[$region_id]->flow(FLOW_ROLE_TOP_SOLID_INFILL, $layer_height, 0, 0, undef, $first_object)->width;
846
printf $fh "; support material extrusion width = %.2fmm\n",
847
$self->objects->[0]->support_material_flow->width
848
if $self->has_support_material;
849
printf $fh "; first layer extrusion width = %.2fmm\n",
850
$self->regions->[$region_id]->flow(FLOW_ROLE_PERIMETER, $layer_height, 0, 1, undef, $self->objects->[0])->width
851
if $self->regions->[$region_id]->config->first_layer_extrusion_width;
855
#Ā prepare the helper object for replacing placeholders in custom G-code and output filename
856
$self->placeholder_parser->update_timestamp;
858
# estimate the total number of layer changes
859
# TODO: only do this when M73 is enabled
861
if ($self->config->complete_objects) {
862
$layer_count = sum(map { $_->layer_count * @{$_->copies} } @{$self->objects});
864
# if sequential printing is not enable, all copies of the same object share the same layer change command(s)
865
$layer_count = sum(map { $_->layer_count } @{$self->objects});
868
# set up our helper object
869
my $gcodegen = Slic3r::GCode->new(
870
placeholder_parser => $self->placeholder_parser,
871
layer_count => $layer_count,
873
$gcodegen->config->apply_print_config($self->config);
874
$gcodegen->set_extruders($self->extruders, $self->config);
876
print $fh "G21 ; set units to millimeters\n" if $self->config->gcode_flavor ne 'makerware';
877
print $fh $gcodegen->set_fan(0, 1) if $self->config->cooling && $self->config->disable_fan_first_layers;
879
# set bed temperature
880
if ((my $temp = $self->config->first_layer_bed_temperature) && $self->config->start_gcode !~ /M(?:190|140)/i) {
881
printf $fh $gcodegen->set_bed_temperature($temp, 1);
884
# set extruder(s) temperature before and after start G-code
885
my $print_first_layer_temperature = sub {
888
return if $self->config->start_gcode =~ /M(?:109|104)/i;
889
for my $t (@{$self->extruders}) {
890
my $temp = $self->config->get_at('first_layer_temperature', $t);
891
$temp += $self->config->standby_temperature_delta if $self->config->ooze_prevention;
892
printf $fh $gcodegen->set_temperature($temp, $wait, $t) if $temp > 0;
895
$print_first_layer_temperature->(0);
896
printf $fh "%s\n", $gcodegen->placeholder_parser->process($self->config->start_gcode);
897
$print_first_layer_temperature->(1);
899
# set other general things
900
print $fh "G90 ; use absolute coordinates\n" if $self->config->gcode_flavor ne 'makerware';
901
if ($self->config->gcode_flavor =~ /^(?:reprap|teacup)$/) {
902
printf $fh $gcodegen->reset_e;
903
if ($self->config->use_relative_e_distances) {
904
print $fh "M83 ; use relative distances for extrusion\n";
906
print $fh "M82 ; use absolute distances for extrusion\n";
910
# initialize a motion planner for object-to-object travel moves
911
if ($self->config->avoid_crossing_perimeters) {
912
my $distance_from_objects = 1;
913
# compute the offsetted convex hull for each object and repeat it for each copy.
915
foreach my $obj_idx (0 .. $#{$self->objects}) {
916
my $convex_hull = convex_hull([
917
map @{$_->contour}, map @{$_->slices}, @{$self->objects->[$obj_idx]->layers},
919
# discard layers only containing thin walls (offset would fail on an empty polygon)
921
my $expolygon = Slic3r::ExPolygon->new($convex_hull);
922
my @island = @{$expolygon->offset_ex(scale $distance_from_objects, 1, JT_SQUARE)};
923
foreach my $copy (@{ $self->objects->[$obj_idx]->_shifted_copies }) {
924
push @islands, map { my $c = $_->clone; $c->translate(@$copy); $c } @island;
928
$gcodegen->external_mp(Slic3r::GCode::MotionPlanner->new(
929
islands => union_ex([ map @$_, @islands ]),
934
# calculate wiping points if needed
935
if ($self->config->ooze_prevention) {
936
my @skirt_points = map @$_, map @$_, @{$self->skirt};
938
my $outer_skirt = convex_hull(\@skirt_points);
940
foreach my $extruder_id (@{$self->extruders}) {
941
push @skirts, my $s = $outer_skirt->clone;
942
$s->translate(map scale($_), @{$self->config->get_at('extruder_offset', $extruder_id)});
944
my $convex_hull = convex_hull([ map @$_, @skirts ]);
945
$gcodegen->standby_points([ map $_->clone, map @$_, map $_->subdivide(scale 10), @{offset([$convex_hull], scale 3)} ]);
949
# prepare the layer processor
950
my $layer_gcode = Slic3r::GCode::Layer->new(
952
gcodegen => $gcodegen,
955
# set initial extruder only after custom start G-code
956
print $fh $gcodegen->set_extruder($self->extruders->[0]);
958
# do all objects for each layer
959
if ($self->config->complete_objects) {
960
# print objects from the smallest to the tallest to avoid collisions
961
# when moving onto next object starting point
962
my @obj_idx = sort { $self->objects->[$a]->size->[Z] <=> $self->objects->[$b]->size->[Z] } 0..$#{$self->objects};
964
my $finished_objects = 0;
965
for my $obj_idx (@obj_idx) {
966
my $object = $self->objects->[$obj_idx];
967
for my $copy (@{ $self->objects->[$obj_idx]->_shifted_copies }) {
968
# move to the origin position for the copy we're going to print.
969
# this happens before Z goes down to layer 0 again, so that
970
# no collision happens hopefully.
971
if ($finished_objects > 0) {
972
$gcodegen->set_shift(map unscale $copy->[$_], X,Y);
973
print $fh $gcodegen->retract;
974
print $fh $gcodegen->G0($object->_copies_shift->negative, undef, 0, $gcodegen->config->travel_speed*60, 'move to origin position for next object');
977
my $buffer = Slic3r::GCode::CoolingBuffer->new(
978
config => $self->config,
979
gcodegen => $gcodegen,
982
my @layers = sort { $a->print_z <=> $b->print_z } @{$object->layers}, @{$object->support_layers};
983
for my $layer (@layers) {
984
# if we are printing the bottom layer of an object, and we have already finished
985
# another one, set first layer temperatures. this happens before the Z move
986
# is triggered, so machine has more time to reach such temperatures
987
if ($layer->id == 0 && $finished_objects > 0) {
988
printf $fh $gcodegen->set_bed_temperature($self->config->first_layer_bed_temperature),
989
if $self->config->first_layer_bed_temperature;
990
$print_first_layer_temperature->();
992
print $fh $buffer->append(
993
$layer_gcode->process_layer($layer, [$copy]),
999
print $fh $buffer->flush;
1000
$finished_objects++;
1004
# order objects using a nearest neighbor search
1005
my @obj_idx = @{chained_path([ map Slic3r::Point->new(@{$_->_shifted_copies->[0]}), @{$self->objects} ])};
1008
my %layers = (); # print_z => [ [layers], [layers], [layers] ] by obj_idx
1009
foreach my $obj_idx (0 .. $#{$self->objects}) {
1010
my $object = $self->objects->[$obj_idx];
1011
foreach my $layer (@{$object->layers}, @{$object->support_layers}) {
1012
$layers{ $layer->print_z } ||= [];
1013
$layers{ $layer->print_z }[$obj_idx] ||= [];
1014
push @{$layers{ $layer->print_z }[$obj_idx]}, $layer;
1018
my $buffer = Slic3r::GCode::CoolingBuffer->new(
1019
config => $self->config,
1020
gcodegen => $gcodegen,
1022
foreach my $print_z (sort { $a <=> $b } keys %layers) {
1023
foreach my $obj_idx (@obj_idx) {
1024
foreach my $layer (@{ $layers{$print_z}[$obj_idx] // [] }) {
1025
print $fh $buffer->append(
1026
$layer_gcode->process_layer($layer, $layer->object->_shifted_copies),
1027
$layer->object . ref($layer), # differentiate $obj_id between normal layers and support layers
1034
print $fh $buffer->flush;
1037
# write end commands to file
1038
print $fh $gcodegen->retract if $gcodegen->extruder; # empty prints don't even set an extruder
1039
print $fh $gcodegen->set_fan(0);
1040
printf $fh "%s\n", $gcodegen->placeholder_parser->process($self->config->end_gcode);
1042
$self->total_used_filament(0);
1043
$self->total_extruded_volume(0);
1044
foreach my $extruder_id (@{$self->extruders}) {
1045
my $extruder = $gcodegen->extruders->{$extruder_id};
1046
# the final retraction doesn't really count as "used filament"
1047
my $used_filament = $extruder->absolute_E + $extruder->retract_length;
1048
my $extruded_volume = $extruder->extruded_volume($used_filament);
1050
printf $fh "; filament used = %.1fmm (%.1fcm3)\n",
1051
$used_filament, $extruded_volume/1000;
1053
$self->total_used_filament($self->total_used_filament + $used_filament);
1054
$self->total_extruded_volume($self->total_extruded_volume + $extruded_volume);
1057
# append full config
1059
foreach my $config ($self->config, $self->default_object_config, $self->default_region_config) {
1060
foreach my $opt_key (sort @{$config->get_keys}) {
1061
next if $Slic3r::Config::Options->{$opt_key}{shortcut};
1062
printf $fh "; %s = %s\n", $opt_key, $config->serialize($opt_key);
1066
# close our gcode file
1070
# this method will return the supplied input file path after expanding its
1071
# format variables with their values
1072
sub expanded_output_filepath {
1076
return undef if !@{$self->objects};
1077
my $input_file = first { defined $_ } map $_->model_object->input_file, @{$self->objects};
1078
return undef if !defined $input_file;
1080
my $filename = my $filename_base = basename($input_file);
1081
$filename_base =~ s/\.[^.]+$//; # without suffix
1083
input_filename => $filename,
1084
input_filename_base => $filename_base,
1087
if ($path && -d $path) {
1088
# if output path is an existing directory, we take that and append
1089
# the specified filename format
1090
$path = File::Spec->join($path, $self->config->output_filename_format);
1092
# if no explicit output file was defined, we take the input
1093
# file directory and append the specified filename format
1094
$path = (fileparse($input_file))[1] . $self->config->output_filename_format;
1096
# path is a full path to a file so we use it as it is
1099
# make sure we use an up-to-date timestamp
1100
$self->placeholder_parser->update_timestamp;
1101
return $self->placeholder_parser->process($path, $extra);
1104
sub invalidate_step {
1105
my ($self, $step, $obj_idx) = @_;
1107
# invalidate $step in the correct state object
1108
if ($Slic3r::Print::State::print_step->{$step}) {
1109
$self->_state->invalidate($step);
1112
if (defined $obj_idx) {
1113
$self->objects->[$obj_idx]->_state->invalidate($step);
1115
$_->_state->invalidate($step) for @{$self->objects};
1119
# recursively invalidate steps depending on $step
1120
$self->invalidate_step($_)
1121
for grep { grep { $_ == $step } @{$Slic3r::Print::State::prereqs{$_}} }
1122
keys %Slic3r::Print::State::prereqs;
1125
# This method assigns extruders to the volumes having a material
1126
# but not having extruders set in the material config.
1127
sub auto_assign_extruders {
1128
my ($self, $model_object) = @_;
1130
# only assign extruders if object has more than one volume
1131
return if @{$model_object->volumes} == 1;
1133
my $extruders = scalar @{ $self->config->nozzle_diameter };
1134
foreach my $i (0..$#{$model_object->volumes}) {
1135
my $volume = $model_object->volumes->[$i];
1136
if (defined $volume->material_id) {
1137
my $material = $model_object->model->get_material($volume->material_id);
1138
my $config = $material->config;
1139
my $extruder_id = $i + 1;
1140
$config->set_ifndef('extruder', $extruder_id);