~ubuntu-branches/ubuntu/utopic/slic3r/utopic

« back to all changes in this revision

Viewing changes to lib/Slic3r/Print.pm

  • Committer: Package Import Robot
  • Author(s): Chow Loong Jin
  • Date: 2014-06-17 01:27:26 UTC
  • Revision ID: package-import@ubuntu.com-20140617012726-2wrs4zdo251nr4vg
Tags: upstream-1.1.4+dfsg
ImportĀ upstreamĀ versionĀ 1.1.4+dfsg

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
package Slic3r::Print;
 
2
use Moo;
 
3
 
 
4
use File::Basename qw(basename fileparse);
 
5
use File::Spec;
 
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
 
10
    convex_hull);
 
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';
 
14
 
 
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 });
 
25
 
 
26
# ordered collection of extrusion paths to build skirt loops
 
27
has 'skirt' => (is => 'rw', default => sub { Slic3r::ExtrusionPath::Collection->new });
 
28
 
 
29
# ordered collection of extrusion paths to build a brim
 
30
has 'brim' => (is => 'rw', default => sub { Slic3r::ExtrusionPath::Collection->new });
 
31
 
 
32
sub apply_config {
 
33
    my ($self, $config) = @_;
 
34
    
 
35
    $config = $config->clone;
 
36
    $config->normalize;
 
37
    
 
38
    # apply variables to placeholder parser
 
39
    $self->placeholder_parser->apply_config($config);
 
40
    
 
41
    # handle changes to print config
 
42
    my $print_diff = $self->config->diff($config);
 
43
    if (@$print_diff) {
 
44
        $self->config->apply_dynamic($config);
 
45
        
 
46
        # TODO: only invalidate changed steps
 
47
        $self->_state->invalidate_all;
 
48
    }
 
49
    
 
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;
 
56
        
 
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);
 
61
        
 
62
        # check whether the new config is different from the current one
 
63
        my $diff = $object->config->diff($new);
 
64
        if (@$diff) {
 
65
            $object->config->apply($new);
 
66
            # TODO: only invalidate changed steps
 
67
            $object->_state->invalidate_all;
 
68
        }
 
69
    }
 
70
    
 
71
    # handle changes to regions config defaults
 
72
    $self->default_region_config->apply_dynamic($config);
 
73
    
 
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];
 
81
                
 
82
                my $new = $self->default_region_config->clone;
 
83
                {
 
84
                    my $model_object_config = $object->model_object->config->clone;
 
85
                    $model_object_config->normalize;
 
86
                    $new->apply_dynamic($model_object_config);
 
87
                }
 
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);
 
92
                }
 
93
                if (!$new->equals($self->regions->[$region_id]->config)) {
 
94
                    $rearrange_regions = 1;
 
95
                    last REGION;
 
96
                }
 
97
            }
 
98
        }
 
99
    }
 
100
    
 
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;
 
110
    }
 
111
}
 
112
 
 
113
sub has_support_material {
 
114
    my $self = shift;
 
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});
 
118
}
 
119
 
 
120
# caller is responsible for supplying models whose objects don't collide
 
121
# and have explicit instance positions
 
122
sub add_model_object {
 
123
    my $self = shift;
 
124
    my ($object, $obj_idx) = @_;
 
125
    
 
126
    my $object_config = $object->config->clone;
 
127
    $object_config->normalize;
 
128
    
 
129
    my %volumes = ();           # region_id => [ volume_id, ... ]
 
130
    foreach my $volume_id (0..$#{$object->volumes}) {
 
131
        my $volume = $object->volumes->[$volume_id];
 
132
        
 
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);
 
136
        
 
137
        # override the defaults with per-object config and then with per-material config
 
138
        $config->apply_dynamic($object_config);
 
139
        
 
140
        if (defined $volume->material_id) {
 
141
            my $material_config = $volume->material->config->clone;
 
142
            $material_config->normalize;
 
143
            $config->apply_dynamic($material_config);
 
144
        }
 
145
        
 
146
        # find an existing print region with the same config
 
147
        my $region_id;
 
148
        foreach my $i (0..$#{$self->regions}) {
 
149
            my $region = $self->regions->[$i];
 
150
            if ($config->equals($region->config)) {
 
151
                $region_id = $i;
 
152
                last;
 
153
            }
 
154
        }
 
155
        
 
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(
 
159
                print  => $self,
 
160
            );
 
161
            $r->config->apply($config);
 
162
            $region_id = $#{$self->regions};
 
163
        }
 
164
        
 
165
        # assign volume to region
 
166
        $volumes{$region_id} //= [];
 
167
        push @{ $volumes{$region_id} }, $volume_id;
 
168
    }
 
169
    
 
170
    # initialize print object
 
171
    my $o = Slic3r::Print::Object->new(
 
172
        print               => $self,
 
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,
 
177
    );
 
178
    
 
179
    # apply config to print object
 
180
    $o->config->apply($self->default_object_config);
 
181
    $o->config->apply_dynamic($object_config);
 
182
    
 
183
    # store print object at the given position
 
184
    if (defined $obj_idx) {
 
185
        splice @{$self->objects}, $obj_idx, 0, $o;
 
186
    } else {
 
187
        push @{$self->objects}, $o;
 
188
    }
 
189
    
 
190
    $self->_state->invalidate(STEP_SKIRT);
 
191
    $self->_state->invalidate(STEP_BRIM);
 
192
}
 
193
 
 
194
sub delete_object {
 
195
    my ($self, $obj_idx) = @_;
 
196
    
 
197
    splice @{$self->objects}, $obj_idx, 1;
 
198
    # TODO: purge unused regions
 
199
    
 
200
    $self->_state->invalidate(STEP_SKIRT);
 
201
    $self->_state->invalidate(STEP_BRIM);
 
202
}
 
203
 
 
204
sub clear_objects {
 
205
    my ($self) = @_;
 
206
    
 
207
    @{$self->objects} = ();
 
208
    @{$self->regions} = ();
 
209
    
 
210
    $self->_state->invalidate(STEP_SKIRT);
 
211
    $self->_state->invalidate(STEP_BRIM);
 
212
}
 
213
 
 
214
sub reload_object {
 
215
    my ($self, $obj_idx) = @_;
 
216
    
 
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.
 
222
    
 
223
    my @models_objects = map $_->model_object, @{$self->objects};
 
224
    $self->clear_objects;
 
225
    $self->add_model_object($_) for @models_objects;
 
226
}
 
227
 
 
228
sub validate {
 
229
    my $self = shift;
 
230
    
 
231
    if ($self->config->complete_objects) {
 
232
        # check horizontal clearance
 
233
        {
 
234
            my @a = ();
 
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,
 
238
                    map @$_,
 
239
                    grep defined $_,
 
240
                    @{$object->region_volumes};
 
241
                
 
242
                # make a single convex hull for all of them
 
243
                my $convex_hull = convex_hull([ map @$_, @mesh_convex_hulls ]);
 
244
                
 
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);
 
247
        
 
248
                # align object to Z = 0 and apply XY shift
 
249
                $convex_hull->translate(@{$object->_copies_shift});
 
250
                
 
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))};
 
253
                
 
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;
 
257
                    
 
258
                    $p->translate(@$copy);
 
259
                    if (@{ intersection(\@a, [$p]) }) {
 
260
                        die "Some objects are too close; your extruder will collide with them.\n";
 
261
                    }
 
262
                    @a = @{union([@a, $p])};
 
263
                }
 
264
            }
 
265
        }
 
266
        
 
267
        # check vertical clearance
 
268
        {
 
269
            my @object_height = ();
 
270
            foreach my $object (@{$self->objects}) {
 
271
                my $height = $object->size->z;
 
272
                push @object_height, $height for @{$object->copies};
 
273
            }
 
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
 
277
            pop @object_height;
 
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";
 
280
            }
 
281
        }
 
282
    }
 
283
    
 
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";
 
287
        }
 
288
        if (@{$self->regions} > 1) {
 
289
            die "The Spiral Vase option can only be used when printing single material objects.\n";
 
290
        }
 
291
    }
 
292
}
 
293
 
 
294
# 0-based indices of used extruders
 
295
sub extruders {
 
296
    my ($self) = @_;
 
297
    
 
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);
 
304
    }
 
305
    foreach my $object (@{$self->objects}) {
 
306
        push @used_extruders,
 
307
            map $object->config->get("${_}_extruder")-1,
 
308
            qw(support_material support_material_interface);
 
309
    }
 
310
    
 
311
    my %h = map { $_ => 1 } @used_extruders;
 
312
    return [ sort keys %h ];
 
313
}
 
314
 
 
315
sub init_extruders {
 
316
    my $self = shift;
 
317
    
 
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;
 
323
    }
 
324
}
 
325
 
 
326
# this value is not supposed to be compared with $layer->id
 
327
# since they have different semantics
 
328
sub layer_count {
 
329
    my $self = shift;
 
330
    return max(map $_->layer_count, @{$self->objects});
 
331
}
 
332
 
 
333
sub regions_count {
 
334
    my $self = shift;
 
335
    return scalar @{$self->regions};
 
336
}
 
337
 
 
338
sub bounding_box {
 
339
    my $self = shift;
 
340
    
 
341
    my @points = ();
 
342
    foreach my $object (@{$self->objects}) {
 
343
        foreach my $copy (@{$object->_shifted_copies}) {
 
344
            push @points,
 
345
                [ $copy->[X], $copy->[Y] ],
 
346
                [ $copy->[X] + $object->size->[X], $copy->[Y] + $object->size->[Y] ];
 
347
        }
 
348
    }
 
349
    return Slic3r::Geometry::BoundingBox->new_from_points([ map Slic3r::Point->new(@$_), @points ]);
 
350
}
 
351
 
 
352
sub size {
 
353
    my $self = shift;
 
354
    return $self->bounding_box->size;
 
355
}
 
356
 
 
357
sub _simplify_slices {
 
358
    my $self = shift;
 
359
    my ($distance) = @_;
 
360
    
 
361
    foreach my $layer (map @{$_->layers}, @{$self->objects}) {
 
362
        $layer->slices->simplify($distance);
 
363
        $_->slices->simplify($distance) for @{$layer->regions};
 
364
    }
 
365
}
 
366
 
 
367
sub process {
 
368
    my ($self) = @_;
 
369
    
 
370
    my $status_cb = $self->status_cb // sub {};
 
371
    
 
372
    my $print_step = sub {
 
373
        my ($step, $cb) = @_;
 
374
        if (!$self->_state->done($step)) {
 
375
            $self->_state->set_started($step);
 
376
            $cb->();
 
377
            ### Re-enable this for step-based slicing:
 
378
            ### $self->_state->set_done($step);
 
379
        }
 
380
    };
 
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);
 
387
                $cb->($obj_idx);
 
388
                ### Re-enable this for step-based slicing:
 
389
                ### $object->_state->set_done($step);
 
390
            }
 
391
        }
 
392
    };
 
393
    
 
394
    # STEP_INIT_EXTRUDERS
 
395
    $print_step->(STEP_INIT_EXTRUDERS, sub {
 
396
        $self->init_extruders;
 
397
    });
 
398
    
 
399
    # STEP_SLICE
 
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;
 
405
    });
 
406
    
 
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};
 
409
    
 
410
    # make perimeters
 
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;
 
416
    });
 
417
    
 
418
    $status_cb->(30, "Preparing infill");
 
419
    $object_step->(STEP_PREPARE_INFILL, sub {
 
420
        my $object = $self->objects->[$_[0]];
 
421
        
 
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;
 
426
    
 
427
        # decide what surfaces are to be filled
 
428
        $_->prepare_fill_surfaces for map @{$_->regions}, @{$object->layers};
 
429
    
 
430
        # this will detect bridges and reverse bridges
 
431
        # and rearrange top/bottom/internal surfaces
 
432
        $object->process_external_surfaces;
 
433
    
 
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;
 
438
        
 
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;
 
442
    
 
443
        # combine fill surfaces to honor the "infill every N layers" option
 
444
        $object->combine_infill;
 
445
    });
 
446
    
 
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]];
 
451
        
 
452
        Slic3r::parallelize(
 
453
            threads => $self->config->threads,
 
454
            items => sub {
 
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};
 
458
                }
 
459
                @items;
 
460
            },
 
461
            thread_cb => sub {
 
462
                my $q = shift;
 
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) );
 
467
                }
 
468
            },
 
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));
 
473
                }
 
474
            },
 
475
        );
 
476
    
 
477
        ### we could free memory now, but this would make this step not idempotent
 
478
        ### $_->fill_surfaces->clear for map @{$_->regions}, @{$object->layers};
 
479
    });
 
480
    
 
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;
 
485
    });
 
486
    
 
487
    # make skirt
 
488
    $status_cb->(88, "Generating skirt/brim");
 
489
    $print_step->(STEP_SKIRT, sub {
 
490
        $self->make_skirt;
 
491
    });
 
492
    $print_step->(STEP_BRIM, sub {
 
493
        $self->make_brim;  # must come after make_skirt
 
494
    });
 
495
    
 
496
    # time to make some statistics
 
497
    if (0) {
 
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;
 
506
    }
 
507
    if (0) {
 
508
        eval "use Slic3r::Test::SectionCut";
 
509
        Slic3r::Test::SectionCut->new(print => $self)->export_svg("section_cut.svg");
 
510
    }
 
511
}
 
512
 
 
513
sub export_gcode {
 
514
    my $self = shift;
 
515
    my %params = @_;
 
516
    
 
517
    my $status_cb = $self->status_cb // sub {};
 
518
    
 
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);
 
523
    
 
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);
 
531
        }
 
532
    }
 
533
}
 
534
 
 
535
sub export_svg {
 
536
    my $self = shift;
 
537
    my %params = @_;
 
538
    
 
539
    # is this needed?
 
540
    $self->init_extruders;
 
541
    
 
542
    $_->slice for @{$self->objects};
 
543
    
 
544
    my $fh = $params{output_fh};
 
545
    if (!$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};
 
550
    }
 
551
    
 
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">
 
557
  <!-- 
 
558
  Generated using Slic3r $Slic3r::VERSION
 
559
  http://slic3r.org/
 
560
   -->
 
561
EOF
 
562
    
 
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');
 
568
    };
 
569
    
 
570
    my @layers = sort { $a->print_z <=> $b->print_z }
 
571
        map { @{$_->layers}, @{$_->support_layers} }
 
572
        @{$self->objects};
 
573
    
 
574
    my $layer_id = -1;
 
575
    my @previous_layer_slices = ();
 
576
    for my $layer (@layers) {
 
577
        $layer_id++;
 
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);
 
580
        
 
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;
 
591
            }
 
592
        }
 
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 ],
 
599
                    $expolygon,
 
600
                );
 
601
                @$intersection
 
602
                    ? push @supported_slices, $expolygon
 
603
                    : push @unsupported_slices, $expolygon;
 
604
            }
 
605
            my @supported_points = map @$_, @$_, @supported_slices;
 
606
            foreach my $expolygon (@unsupported_slices) {
 
607
                # look for the nearest point to this island among all
 
608
                # supported points
 
609
                my $contour = $expolygon->contour;
 
610
                my $support_point = $contour->first_point->nearest_point(\@supported_points)
 
611
                    or next;
 
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;
 
615
            }
 
616
        }
 
617
        print $fh qq{  </g>\n};
 
618
        @previous_layer_slices = @current_layer_slices;
 
619
    }
 
620
    
 
621
    print $fh "</svg>\n";
 
622
    close $fh;
 
623
    print "Done.\n" unless $params{quiet};
 
624
}
 
625
 
 
626
sub make_skirt {
 
627
    my $self = shift;
 
628
    
 
629
    # since this method must be idempotent, we clear skirt paths *before*
 
630
    # checking whether we need to generate them
 
631
    $self->skirt->clear;
 
632
    
 
633
    return unless $self->config->skirts > 0
 
634
        || ($self->config->ooze_prevention && @{$self->extruders} > 1);
 
635
    
 
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}));
 
651
        
 
652
        my $highest_layer = $object->layers->[$skirt_height-1];
 
653
        $skirt_height_z = max($skirt_height_z, $highest_layer->print_z);
 
654
    }
 
655
    
 
656
    # collect points from all layers contained in skirt height
 
657
    my @points = ();
 
658
    foreach my $object (@{$self->objects}) {
 
659
        my @object_points = ();
 
660
        
 
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};
 
665
        }
 
666
        
 
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;
 
672
        }
 
673
        
 
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;
 
679
        }
 
680
    }
 
681
    return if @points < 3;  # at least three points required for a convex hull
 
682
    
 
683
    # find out convex hull
 
684
    my $convex_hull = convex_hull(\@points);
 
685
    
 
686
    my @extruded_length = ();  # for each extruder
 
687
    
 
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,
 
698
    );
 
699
    my $spacing = $flow->spacing;
 
700
    my $mm3_per_mm = $flow->mm3_per_mm($first_layer_height);
 
701
    
 
702
    my @extruders_e_per_mm = ();
 
703
    my $extruder_idx = 0;
 
704
    
 
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,
 
718
            ),
 
719
        ));
 
720
        
 
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);
 
726
            }
 
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}) {
 
731
                    $extruder_idx++;
 
732
                    next;
 
733
                }
 
734
            }
 
735
        }
 
736
    }
 
737
    
 
738
    $self->skirt->reverse;
 
739
}
 
740
 
 
741
sub make_brim {
 
742
    my $self = shift;
 
743
    
 
744
    # since this method must be idempotent, we clear brim paths *before*
 
745
    # checking whether we need to generate them
 
746
    $self->brim->clear;
 
747
    
 
748
    return unless $self->config->brim_width > 0;
 
749
    
 
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,
 
758
    );
 
759
    my $mm3_per_mm = $flow->mm3_per_mm($first_layer_height);
 
760
    
 
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}),
 
768
        );
 
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;
 
777
        }
 
778
        foreach my $copy (@{$object->_shifted_copies}) {
 
779
            push @islands, map { $_->translate(@$copy); $_ } map $_->clone, @object_islands;
 
780
        }
 
781
    }
 
782
    
 
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};
 
787
    }
 
788
    
 
789
    my @loops = ();
 
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)};
 
797
    }
 
798
    
 
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,
 
806
        ),
 
807
    ), reverse @{union_pt_chained(\@loops)});
 
808
}
 
809
 
 
810
sub write_gcode {
 
811
    my $self = shift;
 
812
    my ($file) = @_;
 
813
    
 
814
    # open output gcode file if we weren't supplied a file-handle
 
815
    my $fh;
 
816
    if (ref $file eq 'IO::Scalar') {
 
817
        $fh = $file;
 
818
    } else {
 
819
        Slic3r::open(\$fh, ">", $file)
 
820
            or die "Failed to open $file for writing\n";
 
821
        
 
822
        # enable UTF-8 output since user might have entered Unicode characters in fields like notes
 
823
        binmode $fh, ':utf8';
 
824
    }
 
825
    
 
826
    
 
827
    # write some information
 
828
    my @lt = localtime;
 
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];
 
831
 
 
832
    print $fh "; $_\n" foreach split /\R/, $self->config->notes;
 
833
    print $fh "\n" if $self->config->notes;
 
834
    
 
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;
 
852
        print  $fh "\n";
 
853
    }
 
854
    
 
855
    #Ā prepare the helper object for replacing placeholders in custom G-code and output filename
 
856
    $self->placeholder_parser->update_timestamp;
 
857
    
 
858
    # estimate the total number of layer changes
 
859
    # TODO: only do this when M73 is enabled
 
860
    my $layer_count;
 
861
    if ($self->config->complete_objects) {
 
862
        $layer_count = sum(map { $_->layer_count * @{$_->copies} } @{$self->objects});
 
863
    } else {
 
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});
 
866
    }
 
867
    
 
868
    # set up our helper object
 
869
    my $gcodegen = Slic3r::GCode->new(
 
870
        placeholder_parser  => $self->placeholder_parser,
 
871
        layer_count         => $layer_count,
 
872
    );
 
873
    $gcodegen->config->apply_print_config($self->config);
 
874
    $gcodegen->set_extruders($self->extruders, $self->config);
 
875
    
 
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;
 
878
    
 
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);
 
882
    }
 
883
    
 
884
    # set extruder(s) temperature before and after start G-code
 
885
    my $print_first_layer_temperature = sub {
 
886
        my ($wait) = @_;
 
887
        
 
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;
 
893
        }
 
894
    };
 
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);
 
898
    
 
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";
 
905
        } else {
 
906
            print $fh "M82 ; use absolute distances for extrusion\n";
 
907
        }
 
908
    }
 
909
    
 
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.
 
914
        my @islands = ();
 
915
        foreach my $obj_idx (0 .. $#{$self->objects}) {
 
916
            my $convex_hull = convex_hull([
 
917
                map @{$_->contour}, map @{$_->slices}, @{$self->objects->[$obj_idx]->layers},
 
918
            ]);
 
919
            # discard layers only containing thin walls (offset would fail on an empty polygon)
 
920
            if (@$convex_hull) {
 
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;
 
925
                }
 
926
            }
 
927
        }
 
928
        $gcodegen->external_mp(Slic3r::GCode::MotionPlanner->new(
 
929
            islands     => union_ex([ map @$_, @islands ]),
 
930
            internal    => 0,
 
931
        ));
 
932
    }
 
933
    
 
934
    # calculate wiping points if needed
 
935
    if ($self->config->ooze_prevention) {
 
936
        my @skirt_points = map @$_, map @$_, @{$self->skirt};
 
937
        if (@skirt_points) {
 
938
            my $outer_skirt = convex_hull(\@skirt_points);
 
939
            my @skirts = ();
 
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)});
 
943
            }
 
944
            my $convex_hull = convex_hull([ map @$_, @skirts ]);
 
945
            $gcodegen->standby_points([ map $_->clone, map @$_, map $_->subdivide(scale 10), @{offset([$convex_hull], scale 3)} ]);
 
946
        }
 
947
    }
 
948
    
 
949
    # prepare the layer processor
 
950
    my $layer_gcode = Slic3r::GCode::Layer->new(
 
951
        print       => $self,
 
952
        gcodegen    => $gcodegen,
 
953
    );
 
954
    
 
955
    # set initial extruder only after custom start G-code
 
956
    print $fh $gcodegen->set_extruder($self->extruders->[0]);
 
957
    
 
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};
 
963
        
 
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');
 
975
                }
 
976
                
 
977
                my $buffer = Slic3r::GCode::CoolingBuffer->new(
 
978
                    config      => $self->config,
 
979
                    gcodegen    => $gcodegen,
 
980
                );
 
981
                
 
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->();
 
991
                    }
 
992
                    print $fh $buffer->append(
 
993
                        $layer_gcode->process_layer($layer, [$copy]),
 
994
                        $layer->object."",
 
995
                        $layer->id,
 
996
                        $layer->print_z,
 
997
                    );
 
998
                }
 
999
                print $fh $buffer->flush;
 
1000
                $finished_objects++;
 
1001
            }
 
1002
        }
 
1003
    } else {
 
1004
        # order objects using a nearest neighbor search
 
1005
        my @obj_idx = @{chained_path([ map Slic3r::Point->new(@{$_->_shifted_copies->[0]}), @{$self->objects} ])};
 
1006
        
 
1007
        # sort layers by Z
 
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;
 
1015
            }
 
1016
        }
 
1017
        
 
1018
        my $buffer = Slic3r::GCode::CoolingBuffer->new(
 
1019
            config      => $self->config,
 
1020
            gcodegen    => $gcodegen,
 
1021
        );
 
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
 
1028
                        $layer->id,
 
1029
                        $layer->print_z,
 
1030
                    );
 
1031
                }
 
1032
            }
 
1033
        }
 
1034
        print $fh $buffer->flush;
 
1035
    }
 
1036
    
 
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);
 
1041
    
 
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);
 
1049
        
 
1050
        printf $fh "; filament used = %.1fmm (%.1fcm3)\n",
 
1051
            $used_filament, $extruded_volume/1000;
 
1052
        
 
1053
        $self->total_used_filament($self->total_used_filament + $used_filament);
 
1054
        $self->total_extruded_volume($self->total_extruded_volume + $extruded_volume);
 
1055
    }
 
1056
    
 
1057
    # append full config
 
1058
    print $fh "\n";
 
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);
 
1063
        }
 
1064
    }
 
1065
    
 
1066
    # close our gcode file
 
1067
    close $fh;
 
1068
}
 
1069
 
 
1070
# this method will return the supplied input file path after expanding its
 
1071
# format variables with their values
 
1072
sub expanded_output_filepath {
 
1073
    my $self = shift;
 
1074
    my ($path) = @_;
 
1075
    
 
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;
 
1079
    
 
1080
    my $filename = my $filename_base = basename($input_file);
 
1081
    $filename_base =~ s/\.[^.]+$//;  # without suffix
 
1082
    my $extra = {
 
1083
        input_filename      => $filename,
 
1084
        input_filename_base => $filename_base,
 
1085
    };
 
1086
    
 
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);
 
1091
    } elsif (!$path) {
 
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;
 
1095
    } else {
 
1096
        # path is a full path to a file so we use it as it is
 
1097
    }
 
1098
    
 
1099
    # make sure we use an up-to-date timestamp
 
1100
    $self->placeholder_parser->update_timestamp;
 
1101
    return $self->placeholder_parser->process($path, $extra);
 
1102
}
 
1103
 
 
1104
sub invalidate_step {
 
1105
    my ($self, $step, $obj_idx) = @_;
 
1106
    
 
1107
    # invalidate $step in the correct state object
 
1108
    if ($Slic3r::Print::State::print_step->{$step}) {
 
1109
        $self->_state->invalidate($step);
 
1110
    } else {
 
1111
        # object step
 
1112
        if (defined $obj_idx) {
 
1113
            $self->objects->[$obj_idx]->_state->invalidate($step);
 
1114
        } else {
 
1115
            $_->_state->invalidate($step) for @{$self->objects};
 
1116
        }
 
1117
    }
 
1118
    
 
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;
 
1123
}
 
1124
 
 
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) = @_;
 
1129
    
 
1130
    # only assign extruders if object has more than one volume
 
1131
    return if @{$model_object->volumes} == 1;
 
1132
    
 
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);
 
1141
        }
 
1142
    }
 
1143
}
 
1144
 
 
1145
1;