GCode.pm 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733
  1. package Slic3r::Print::GCode;
  2. use Moo;
  3. has 'print' => (is => 'ro', required => 1, handles => [qw(objects placeholder_parser config)]);
  4. has 'fh' => (is => 'ro', required => 1);
  5. has '_gcodegen' => (is => 'rw');
  6. has '_cooling_buffer' => (is => 'rw');
  7. has '_spiral_vase' => (is => 'rw');
  8. has '_vibration_limit' => (is => 'rw');
  9. has '_arc_fitting' => (is => 'rw');
  10. has '_pressure_regulator' => (is => 'rw');
  11. has '_skirt_done' => (is => 'rw', default => sub { {} }); # print_z => 1
  12. has '_brim_done' => (is => 'rw');
  13. has '_second_layer_things_done' => (is => 'rw');
  14. has '_last_obj_copy' => (is => 'rw');
  15. has '_autospeed' => (is => 'rw', default => sub { 0 }); # boolean
  16. use List::Util qw(first sum min max);
  17. use Slic3r::ExtrusionPath ':roles';
  18. use Slic3r::Flow ':roles';
  19. use Slic3r::Geometry qw(X Y scale unscale chained_path convex_hull);
  20. use Slic3r::Geometry::Clipper qw(JT_SQUARE union_ex offset);
  21. sub BUILD {
  22. my ($self) = @_;
  23. {
  24. # estimate the total number of layer changes
  25. # TODO: only do this when M73 is enabled
  26. my $layer_count;
  27. if ($self->config->complete_objects) {
  28. $layer_count = sum(map { $_->total_layer_count * @{$_->copies} } @{$self->objects});
  29. } else {
  30. # if sequential printing is not enable, all copies of the same object share the same layer change command(s)
  31. $layer_count = sum(map { $_->total_layer_count } @{$self->objects});
  32. }
  33. # set up our helper object: This is a C++ Slic3r::GCode instance.
  34. my $gcodegen = Slic3r::GCode->new;
  35. $self->_gcodegen($gcodegen);
  36. $gcodegen->set_placeholder_parser($self->placeholder_parser);
  37. $gcodegen->set_layer_count($layer_count);
  38. $gcodegen->set_enable_cooling_markers(1);
  39. $gcodegen->apply_print_config($self->config);
  40. $gcodegen->set_extruders($self->print->extruders);
  41. }
  42. $self->_cooling_buffer(Slic3r::GCode::CoolingBuffer->new($self->_gcodegen));
  43. $self->_spiral_vase(Slic3r::GCode::SpiralVase->new($self->config))
  44. if $self->config->spiral_vase;
  45. $self->_vibration_limit(Slic3r::GCode::VibrationLimit->new(config => $self->config))
  46. if $self->config->vibration_limit != 0;
  47. $self->_arc_fitting(Slic3r::GCode::ArcFitting->new(config => $self->config))
  48. if $self->config->gcode_arcs;
  49. $self->_pressure_regulator(Slic3r::GCode::PressureRegulator->new(config => $self->config))
  50. if $self->config->pressure_advance > 0;
  51. }
  52. # Export a G-code for the complete print.
  53. sub export {
  54. my ($self) = @_;
  55. my $fh = $self->fh;
  56. my $gcodegen = $self->_gcodegen;
  57. # Write information on the generator.
  58. my @lt = localtime;
  59. printf $fh "; generated by Slic3r $Slic3r::VERSION on %04d-%02d-%02d at %02d:%02d:%02d\n\n",
  60. $lt[5] + 1900, $lt[4]+1, $lt[3], $lt[2], $lt[1], $lt[0];
  61. # Write notes (content of all Settings tabs -> Notes)
  62. print $fh $gcodegen->notes;
  63. # Write some terse information on the slicing parameters.
  64. my $first_object = $self->objects->[0];
  65. my $layer_height = $first_object->config->layer_height;
  66. for my $region_id (0..$#{$self->print->regions}) {
  67. my $region = $self->print->regions->[$region_id];
  68. {
  69. my $flow = $region->flow(FLOW_ROLE_EXTERNAL_PERIMETER, $layer_height, 0, 0, -1, $first_object);
  70. my $vol_speed = $flow->mm3_per_mm * $region->config->get_abs_value('external_perimeter_speed');
  71. $vol_speed = min($vol_speed, $self->config->max_volumetric_speed) if $self->config->max_volumetric_speed > 0;
  72. printf $fh "; external perimeters extrusion width = %.2fmm (%.2fmm^3/s)\n",
  73. $flow->width, $vol_speed;
  74. }
  75. {
  76. my $flow = $region->flow(FLOW_ROLE_PERIMETER, $layer_height, 0, 0, -1, $first_object);
  77. my $vol_speed = $flow->mm3_per_mm * $region->config->get_abs_value('perimeter_speed');
  78. $vol_speed = min($vol_speed, $self->config->max_volumetric_speed) if $self->config->max_volumetric_speed > 0;
  79. printf $fh "; perimeters extrusion width = %.2fmm (%.2fmm^3/s)\n",
  80. $flow->width, $vol_speed;
  81. }
  82. {
  83. my $flow = $region->flow(FLOW_ROLE_INFILL, $layer_height, 0, 0, -1, $first_object);
  84. my $vol_speed = $flow->mm3_per_mm * $region->config->get_abs_value('infill_speed');
  85. $vol_speed = min($vol_speed, $self->config->max_volumetric_speed) if $self->config->max_volumetric_speed > 0;
  86. printf $fh "; infill extrusion width = %.2fmm (%.2fmm^3/s)\n",
  87. $flow->width, $vol_speed;
  88. }
  89. {
  90. my $flow = $region->flow(FLOW_ROLE_SOLID_INFILL, $layer_height, 0, 0, -1, $first_object);
  91. my $vol_speed = $flow->mm3_per_mm * $region->config->get_abs_value('solid_infill_speed');
  92. $vol_speed = min($vol_speed, $self->config->max_volumetric_speed) if $self->config->max_volumetric_speed > 0;
  93. printf $fh "; solid infill extrusion width = %.2fmm (%.2fmm^3/s)\n",
  94. $flow->width, $vol_speed;
  95. }
  96. {
  97. my $flow = $region->flow(FLOW_ROLE_TOP_SOLID_INFILL, $layer_height, 0, 0, -1, $first_object);
  98. my $vol_speed = $flow->mm3_per_mm * $region->config->get_abs_value('top_solid_infill_speed');
  99. $vol_speed = min($vol_speed, $self->config->max_volumetric_speed) if $self->config->max_volumetric_speed > 0;
  100. printf $fh "; top infill extrusion width = %.2fmm (%.2fmm^3/s)\n",
  101. $flow->width, $vol_speed;
  102. }
  103. if ($self->print->has_support_material) {
  104. my $object0 = $self->objects->[0];
  105. my $flow = $object0->support_material_flow;
  106. my $vol_speed = $flow->mm3_per_mm * $object0->config->get_abs_value('support_material_speed');
  107. $vol_speed = min($vol_speed, $self->config->max_volumetric_speed) if $self->config->max_volumetric_speed > 0;
  108. printf $fh "; support material extrusion width = %.2fmm (%.2fmm^3/s)\n",
  109. $flow->width, $vol_speed;
  110. }
  111. printf $fh "; first layer extrusion width = %.2fmm (%.2fmm^3/s)\n",
  112. $region->flow(FLOW_ROLE_PERIMETER, $layer_height, 0, 1, -1, $self->objects->[0])->width
  113. if $region->config->first_layer_extrusion_width;
  114. print $fh "\n";
  115. }
  116. # prepare the helper object for replacing placeholders in custom G-code and output filename
  117. $self->placeholder_parser->update_timestamp;
  118. # GCode sets this automatically whenever we call change_layer(),
  119. # but we need it for skirt/brim too
  120. $gcodegen->set_first_layer(1);
  121. # disable fan
  122. print $fh $gcodegen->writer->set_fan(0, 1)
  123. if $self->config->cooling && $self->config->disable_fan_first_layers;
  124. # set bed temperature
  125. if ($self->config->has_heatbed && (my $temp = $self->config->first_layer_bed_temperature) && $self->config->start_gcode !~ /M(?:190|140)/i) {
  126. printf $fh $gcodegen->writer->set_bed_temperature($temp, 1);
  127. }
  128. # set extruder(s) temperature before and after start G-code
  129. my $include_start_extruder_temp = $self->config->start_gcode !~ /M(?:109|104)/i;
  130. foreach my $start_gcode (@{ $self->config->start_filament_gcode }) { # process filament gcode in order
  131. $include_start_extruder_temp = $include_start_extruder_temp && ($start_gcode !~ /M(?:109|104)/i);
  132. }
  133. $self->_print_first_layer_temperature(0)
  134. if $include_start_extruder_temp;
  135. printf $fh "%s\n", Slic3r::ConditionalGCode::apply_math($gcodegen->placeholder_parser->process($self->config->start_gcode));
  136. foreach my $start_gcode (@{ $self->config->start_filament_gcode }) { # process filament gcode in order
  137. printf $fh "%s\n", Slic3r::ConditionalGCode::apply_math($gcodegen->placeholder_parser->process($start_gcode));
  138. }
  139. $self->_print_first_layer_temperature(1)
  140. if $include_start_extruder_temp;
  141. # set other general things
  142. print $fh $gcodegen->preamble;
  143. # initialize a motion planner for object-to-object travel moves
  144. if ($self->config->avoid_crossing_perimeters) {
  145. my $distance_from_objects = scale 1;
  146. # compute the offsetted convex hull for each object and repeat it for each copy.
  147. my @islands_p = ();
  148. foreach my $object (@{$self->objects}) {
  149. # discard objects only containing thin walls (offset would fail on an empty polygon)
  150. my @polygons = map $_->contour, map @{$_->slices}, @{$object->layers};
  151. next if !@polygons;
  152. # translate convex hull for each object copy and append it to the islands array
  153. foreach my $copy (@{ $object->_shifted_copies }) {
  154. my @copy_islands_p = map $_->clone, @polygons;
  155. $_->translate(@$copy) for @copy_islands_p;
  156. push @islands_p, @copy_islands_p;
  157. }
  158. }
  159. $gcodegen->avoid_crossing_perimeters->init_external_mp(union_ex(\@islands_p));
  160. }
  161. # calculate wiping points if needed
  162. if ($self->config->ooze_prevention && (my @extruders = @{$self->print->extruders}) > 1) {
  163. my @skirt_points = map @$_, map @$_, @{$self->print->skirt};
  164. if (@skirt_points) {
  165. my $outer_skirt = convex_hull(\@skirt_points);
  166. my @skirts = ();
  167. foreach my $extruder_id (@extruders) {
  168. my $extruder_offset = $self->config->get_at('extruder_offset', $extruder_id);
  169. push @skirts, my $s = $outer_skirt->clone;
  170. $s->translate(-scale($extruder_offset->x), -scale($extruder_offset->y)); #)
  171. }
  172. my $convex_hull = convex_hull([ map @$_, @skirts ]);
  173. $gcodegen->ooze_prevention->set_enable(1);
  174. $gcodegen->ooze_prevention->set_standby_points(
  175. [ map @{$_->equally_spaced_points(scale 10)}, @{offset([$convex_hull], scale 3)} ]
  176. );
  177. if (0) {
  178. require "Slic3r/SVG.pm";
  179. Slic3r::SVG::output(
  180. "ooze_prevention.svg",
  181. red_polygons => \@skirts,
  182. polygons => [$outer_skirt],
  183. points => $gcodegen->ooze_prevention->standby_points,
  184. );
  185. }
  186. }
  187. }
  188. # set initial extruder only after custom start G-code
  189. print $fh $gcodegen->set_extruder($self->print->extruders->[0]);
  190. # do all objects for each layer
  191. if ($self->config->complete_objects) {
  192. # print objects from the smallest to the tallest to avoid collisions
  193. # when moving onto next object starting point
  194. my @obj_idx = sort { $self->objects->[$a]->config->sequential_print_priority <=> $self->objects->[$b]->config->sequential_print_priority or $self->objects->[$a]->size->z <=> $self->objects->[$b]->size->z} 0..($self->print->object_count - 1);
  195. my $finished_objects = 0;
  196. for my $obj_idx (@obj_idx) {
  197. my $object = $self->objects->[$obj_idx];
  198. for my $copy (@{ $self->objects->[$obj_idx]->_shifted_copies }) {
  199. # move to the origin position for the copy we're going to print.
  200. # this happens before Z goes down to layer 0 again, so that
  201. # no collision happens hopefully.
  202. if ($finished_objects > 0) {
  203. $gcodegen->set_origin(Slic3r::Pointf->new(map unscale $copy->[$_], X,Y));
  204. $gcodegen->set_enable_cooling_markers(0); # we're not filtering these moves through CoolingBuffer
  205. $gcodegen->avoid_crossing_perimeters->set_use_external_mp_once(1);
  206. print $fh $gcodegen->retract;
  207. print $fh $gcodegen->travel_to(
  208. Slic3r::Point->new(0,0),
  209. EXTR_ROLE_NONE,
  210. 'move to origin position for next object',
  211. );
  212. $gcodegen->set_enable_cooling_markers(1);
  213. # disable motion planner when traveling to first object point
  214. $gcodegen->avoid_crossing_perimeters->set_disable_once(1);
  215. }
  216. my @layers = sort { $a->print_z <=> $b->print_z } @{$object->layers}, @{$object->support_layers};
  217. for my $layer (@layers) {
  218. # if we are printing the bottom layer of an object, and we have already finished
  219. # another one, set first layer temperatures. this happens before the Z move
  220. # is triggered, so machine has more time to reach such temperatures
  221. if ($layer->id == 0 && $finished_objects > 0) {
  222. printf $fh $gcodegen->writer->set_bed_temperature($self->config->first_layer_bed_temperature),
  223. if $self->config->first_layer_bed_temperature
  224. && $self->config->has_heatbed
  225. && $self->config->between_objects_gcode !~ /M(?:190|140)/i;
  226. $self->_print_first_layer_temperature(0)
  227. if $self->config->between_objects_gcode !~ /M(?:109|104)/i;
  228. printf $fh "%s\n", Slic3r::ConditionalGCode::apply_math($gcodegen->placeholder_parser->process($self->config->between_objects_gcode));
  229. }
  230. $self->process_layer($layer, [$copy]);
  231. }
  232. $self->flush_filters;
  233. $finished_objects++;
  234. $self->_second_layer_things_done(0);
  235. }
  236. }
  237. } else {
  238. # order objects using a nearest neighbor search
  239. my @obj_idx = @{chained_path([ map Slic3r::Point->new(@{$_->_shifted_copies->[0]}), @{$self->objects} ])};
  240. # sort layers by Z
  241. my %layers = (); # print_z => [ [layers], [layers], [layers] ] by obj_idx
  242. foreach my $obj_idx (0 .. ($self->print->object_count - 1)) {
  243. my $object = $self->objects->[$obj_idx];
  244. foreach my $layer (@{$object->layers}, @{$object->support_layers}) {
  245. $layers{ $layer->print_z } ||= [];
  246. $layers{ $layer->print_z }[$obj_idx] ||= [];
  247. push @{$layers{ $layer->print_z }[$obj_idx]}, $layer;
  248. }
  249. }
  250. foreach my $print_z (sort { $a <=> $b } keys %layers) {
  251. foreach my $obj_idx (@obj_idx) {
  252. foreach my $layer (@{ $layers{$print_z}[$obj_idx] // [] }) {
  253. $self->process_layer($layer, $layer->object->_shifted_copies);
  254. }
  255. }
  256. }
  257. $self->flush_filters;
  258. }
  259. # write end commands to file
  260. print $fh $gcodegen->retract; # TODO: process this retract through PressureRegulator in order to discharge fully
  261. print $fh $gcodegen->writer->set_fan(0);
  262. foreach my $end_gcode (@{ $self->config->end_filament_gcode }) { # Process filament-specific gcode in extruder order.
  263. printf $fh "%s\n", Slic3r::ConditionalGCode::apply_math($gcodegen->placeholder_parser->process($end_gcode));
  264. }
  265. printf $fh "%s\n", Slic3r::ConditionalGCode::apply_math($gcodegen->placeholder_parser->process($self->config->end_gcode));
  266. print $fh $gcodegen->writer->update_progress($gcodegen->layer_count, $gcodegen->layer_count, 1); # 100%
  267. print $fh $gcodegen->writer->postamble;
  268. # get filament stats
  269. $self->print->clear_filament_stats;
  270. $self->print->total_used_filament(0);
  271. $self->print->total_extruded_volume(0);
  272. $self->print->total_weight(0);
  273. $self->print->total_cost(0);
  274. foreach my $extruder (@{$gcodegen->writer->extruders}) {
  275. my $used_filament = $extruder->used_filament;
  276. my $extruded_volume = $extruder->extruded_volume;
  277. my $filament_weight = $extruded_volume * $extruder->filament_density / 1000;
  278. my $filament_cost = $filament_weight * ($extruder->filament_cost / 1000);
  279. $self->print->set_filament_stats($extruder->id, $used_filament);
  280. printf $fh "; filament used = %.1fmm (%.1fcm3)\n",
  281. $used_filament, $extruded_volume/1000;
  282. if ($filament_weight > 0) {
  283. $self->print->total_weight($self->print->total_weight + $filament_weight);
  284. printf $fh "; filament used = %.1fg\n",
  285. $filament_weight;
  286. if ($filament_cost > 0) {
  287. $self->print->total_cost($self->print->total_cost + $filament_cost);
  288. printf $fh "; filament cost = %.1f\n",
  289. $filament_cost;
  290. }
  291. }
  292. $self->print->total_used_filament($self->print->total_used_filament + $used_filament);
  293. $self->print->total_extruded_volume($self->print->total_extruded_volume + $extruded_volume);
  294. }
  295. printf $fh "; total filament cost = %.1f\n",
  296. $self->print->total_cost;
  297. # append full config
  298. print $fh "\n";
  299. foreach my $config ($self->print->config, $self->print->default_object_config, $self->print->default_region_config) {
  300. foreach my $opt_key (sort @{$config->get_keys}) {
  301. next if $Slic3r::Config::Options->{$opt_key}{shortcut};
  302. printf $fh "; %s = %s\n", $opt_key, $config->serialize($opt_key);
  303. }
  304. }
  305. }
  306. sub _print_first_layer_temperature {
  307. my ($self, $wait) = @_;
  308. for my $t (@{$self->print->extruders}) {
  309. my $temp = $self->config->get_at('first_layer_temperature', $t);
  310. $temp += $self->config->standby_temperature_delta if $self->config->ooze_prevention;
  311. printf {$self->fh} $self->_gcodegen->writer->set_temperature($temp, $wait, $t) if $temp > 0;
  312. }
  313. }
  314. # Called per object's layer.
  315. # First a $gcode string is collected,
  316. # then filtered and finally written to a file $fh.
  317. sub process_layer {
  318. my $self = shift;
  319. my ($layer, $object_copies) = @_;
  320. my $gcode = "";
  321. my $object = $layer->object;
  322. $self->_gcodegen->config->apply_static($object->config);
  323. # check whether we're going to apply spiralvase logic
  324. if (defined $self->_spiral_vase) {
  325. $self->_spiral_vase->set_enable(
  326. $layer->id > 0
  327. && ($self->print->config->skirts == 0
  328. || ($layer->id >= $self->print->config->skirt_height && !$self->print->has_infinite_skirt))
  329. && !defined(first { $_->region->config->bottom_solid_layers > $layer->id } @{$layer->regions})
  330. && !defined(first { $_->perimeters->items_count > 1 } @{$layer->regions})
  331. && !defined(first { $_->fills->items_count > 0 } @{$layer->regions})
  332. );
  333. }
  334. # if we're going to apply spiralvase to this layer, disable loop clipping
  335. $self->_gcodegen->set_enable_loop_clipping(!defined $self->_spiral_vase || !$self->_spiral_vase->enable);
  336. # initialize autospeed
  337. {
  338. # get the minimum cross-section used in the layer
  339. my @mm3_per_mm = ();
  340. foreach my $region_id (0..$#{$self->print->regions}) {
  341. my $region = $self->print->get_region($region_id);
  342. my $layerm = $layer->region($region_id);
  343. if ($region->config->get_abs_value('perimeter_speed') == 0
  344. || $region->config->get_abs_value('small_perimeter_speed') == 0
  345. || $region->config->get_abs_value('external_perimeter_speed') == 0
  346. || $region->config->get_abs_value('bridge_speed') == 0) {
  347. push @mm3_per_mm, $layerm->perimeters->min_mm3_per_mm;
  348. }
  349. if ($region->config->get_abs_value('infill_speed') == 0
  350. || $region->config->get_abs_value('solid_infill_speed') == 0
  351. || $region->config->get_abs_value('top_solid_infill_speed') == 0
  352. || $region->config->get_abs_value('bridge_speed') == 0
  353. || $region->config->get_abs_value('gap_fill_speed') == 0) {
  354. push @mm3_per_mm, $layerm->fills->min_mm3_per_mm;
  355. }
  356. }
  357. if ($layer->isa('Slic3r::Layer::Support')) {
  358. if ($object->config->get_abs_value('support_material_speed') == 0
  359. || $object->config->get_abs_value('support_material_interface_speed') == 0) {
  360. push @mm3_per_mm, $layer->support_fills->min_mm3_per_mm;
  361. push @mm3_per_mm, $layer->support_interface_fills->min_mm3_per_mm;
  362. }
  363. }
  364. # ignore too thin segments
  365. @mm3_per_mm = grep $_ > 0.01, @mm3_per_mm;
  366. if (@mm3_per_mm) {
  367. my $min_mm3_per_mm = min(@mm3_per_mm);
  368. # In order to honor max_print_speed we need to find a target volumetric
  369. # speed that we can use throughout the print. So we define this target
  370. # volumetric speed as the volumetric speed produced by printing the
  371. # smallest cross-section at the maximum speed: any larger cross-section
  372. # will need slower feedrates.
  373. my $volumetric_speed = $min_mm3_per_mm * $self->config->max_print_speed;
  374. # limit such volumetric speed with max_volumetric_speed if set
  375. if ($self->config->max_volumetric_speed > 0) {
  376. $volumetric_speed = min(
  377. $volumetric_speed,
  378. $self->config->max_volumetric_speed,
  379. );
  380. }
  381. $self->_gcodegen->set_volumetric_speed($volumetric_speed);
  382. }
  383. }
  384. if (!$self->_second_layer_things_done && $layer->id == 1) {
  385. for my $extruder (@{$self->_gcodegen->writer->extruders}) {
  386. my $temperature = $self->config->get_at('temperature', $extruder->id);
  387. $gcode .= $self->_gcodegen->writer->set_temperature($temperature, 0, $extruder->id)
  388. if $temperature && $temperature != $self->config->get_at('first_layer_temperature', $extruder->id);
  389. }
  390. $gcode .= $self->_gcodegen->writer->set_bed_temperature($self->print->config->bed_temperature)
  391. if $self->config->has_heatbed && $self->print->config->first_layer_bed_temperature && $self->print->config->bed_temperature != $self->print->config->first_layer_bed_temperature;
  392. $self->_second_layer_things_done(1);
  393. }
  394. # set new layer - this will change Z and force a retraction if retract_layer_change is enabled
  395. if ($self->print->config->before_layer_gcode) {
  396. my $pp = $self->_gcodegen->placeholder_parser->clone;
  397. $pp->set('layer_num' => $self->_gcodegen->layer_index + 1);
  398. $pp->set('layer_z' => $layer->print_z);
  399. $pp->set('current_retraction' => $self->_gcodegen->writer->extruder->retracted);
  400. $gcode .= Slic3r::ConditionalGCode::apply_math($pp->process($self->print->config->before_layer_gcode) . "\n");
  401. }
  402. $gcode .= $self->_gcodegen->change_layer($layer->as_layer); # this will increase $self->_gcodegen->layer_index
  403. if ($self->print->config->layer_gcode) {
  404. my $pp = $self->_gcodegen->placeholder_parser->clone;
  405. $pp->set('layer_num' => $self->_gcodegen->layer_index);
  406. $pp->set('layer_z' => $layer->print_z);
  407. $pp->set('current_retraction' => $self->_gcodegen->writer->extruder->retracted);
  408. $gcode .= Slic3r::ConditionalGCode::apply_math($pp->process($self->print->config->layer_gcode) . "\n");
  409. }
  410. # extrude skirt along raft layers and normal object layers
  411. # (not along interlaced support material layers)
  412. if (((values %{$self->_skirt_done}) < $self->print->config->skirt_height || $self->print->has_infinite_skirt)
  413. && !$self->_skirt_done->{$layer->print_z}
  414. && (!$layer->isa('Slic3r::Layer::Support') || $layer->id < $object->config->raft_layers)) {
  415. $self->_gcodegen->set_origin(Slic3r::Pointf->new(0,0));
  416. $self->_gcodegen->avoid_crossing_perimeters->set_use_external_mp(1);
  417. my @extruder_ids = map { $_->id } @{$self->_gcodegen->writer->extruders};
  418. $gcode .= $self->_gcodegen->set_extruder($extruder_ids[0]);
  419. # skip skirt if we have a large brim
  420. if ($layer->id < $self->print->config->skirt_height || $self->print->has_infinite_skirt) {
  421. my $skirt_flow = $self->print->skirt_flow;
  422. # distribute skirt loops across all extruders
  423. my @skirt_loops = @{$self->print->skirt};
  424. for my $i (0 .. $#skirt_loops) {
  425. # when printing layers > 0 ignore 'min_skirt_length' and
  426. # just use the 'skirts' setting; also just use the current extruder
  427. last if ($layer->id > 0) && ($i >= $self->print->config->skirts);
  428. my $extruder_id = $extruder_ids[($i/@extruder_ids) % @extruder_ids];
  429. $gcode .= $self->_gcodegen->set_extruder($extruder_id)
  430. if $layer->id == 0;
  431. # adjust flow according to this layer's layer height
  432. my $loop = $skirt_loops[$i]->clone;
  433. {
  434. my $layer_skirt_flow = $skirt_flow->clone;
  435. $layer_skirt_flow->set_height($layer->height);
  436. my $mm3_per_mm = $layer_skirt_flow->mm3_per_mm;
  437. foreach my $path (@$loop) {
  438. $path->height($layer->height);
  439. $path->mm3_per_mm($mm3_per_mm);
  440. }
  441. }
  442. $gcode .= $self->_gcodegen->extrude_loop($loop, 'skirt', $object->config->support_material_speed);
  443. }
  444. }
  445. $self->_skirt_done->{$layer->print_z} = 1;
  446. $self->_gcodegen->avoid_crossing_perimeters->set_use_external_mp(0);
  447. # allow a straight travel move to the first object point if this is the first layer
  448. # (but don't in next layers)
  449. if ($layer->id == 0) {
  450. $self->_gcodegen->avoid_crossing_perimeters->set_disable_once(1);
  451. }
  452. }
  453. # extrude brim
  454. if (!$self->_brim_done) {
  455. $gcode .= $self->_gcodegen->set_extruder($self->print->brim_extruder-1);
  456. $self->_gcodegen->set_origin(Slic3r::Pointf->new(0,0));
  457. $self->_gcodegen->avoid_crossing_perimeters->set_use_external_mp(1);
  458. $gcode .= $self->_gcodegen->extrude($_, 'brim', $object->config->support_material_speed)
  459. for @{$self->print->brim};
  460. $self->_brim_done(1);
  461. $self->_gcodegen->avoid_crossing_perimeters->set_use_external_mp(0);
  462. # allow a straight travel move to the first object point
  463. $self->_gcodegen->avoid_crossing_perimeters->set_disable_once(1);
  464. }
  465. for my $copy (@$object_copies) {
  466. # when starting a new object, use the external motion planner for the first travel move
  467. $self->_gcodegen->avoid_crossing_perimeters->set_use_external_mp_once(1) if ($self->_last_obj_copy // '') ne "$copy";
  468. $self->_last_obj_copy("$copy");
  469. $self->_gcodegen->set_origin(Slic3r::Pointf->new(map unscale $copy->[$_], X,Y));
  470. # extrude support material before other things because it might use a lower Z
  471. # and also because we avoid travelling on other things when printing it
  472. if ($layer->isa('Slic3r::Layer::Support')) {
  473. if ($layer->support_interface_fills->count > 0) {
  474. $gcode .= $self->_gcodegen->set_extruder($object->config->support_material_interface_extruder-1);
  475. $gcode .= $self->_gcodegen->extrude_path($_, 'support material interface', $object->config->get_abs_value('support_material_interface_speed'))
  476. for @{$layer->support_interface_fills->chained_path_from($self->_gcodegen->last_pos, 0)};
  477. }
  478. if ($layer->support_fills->count > 0) {
  479. $gcode .= $self->_gcodegen->set_extruder($object->config->support_material_extruder-1);
  480. $gcode .= $self->_gcodegen->extrude_path($_, 'support material', $object->config->get_abs_value('support_material_speed'))
  481. for @{$layer->support_fills->chained_path_from($self->_gcodegen->last_pos, 0)};
  482. }
  483. }
  484. # We now define a strategy for building perimeters and fills. The separation
  485. # between regions doesn't matter in terms of printing order, as we follow
  486. # another logic instead:
  487. # - we group all extrusions by extruder so that we minimize toolchanges
  488. # - we start from the last used extruder
  489. # - for each extruder, we group extrusions by island
  490. # - for each island, we extrude perimeters first, unless user set the infill_first
  491. # option
  492. # (Still, we have to keep track of regions because we need to apply their config)
  493. # group extrusions by extruder and then by island
  494. my %by_extruder = (); # extruder_id => [ { perimeters => \@perimeters, infill => \@infill } ]
  495. # cache bounding boxes of layer slices
  496. my @layer_slices_bb = map $_->contour->bounding_box, @{$layer->slices};
  497. my $point_inside_surface = sub {
  498. my ($i, $point) = @_;
  499. my $bbox = $layer_slices_bb[$i];
  500. return $layer_slices_bb[$i]->contains_point($point)
  501. && $layer->slices->[$i]->contour->contains_point($point);
  502. };
  503. my $n_slices = $layer->slices->count - 1;
  504. foreach my $region_id (0..($self->print->region_count-1)) {
  505. my $layerm = $layer->regions->[$region_id] or next;
  506. my $region = $self->print->get_region($region_id);
  507. # process perimeters
  508. {
  509. my $extruder_id = $region->config->perimeter_extruder-1;
  510. foreach my $perimeter_coll (@{$layerm->perimeters}) {
  511. next if $perimeter_coll->empty; # this shouldn't happen but first_point() would fail
  512. # init by_extruder item only if we actually use the extruder
  513. $by_extruder{$extruder_id} //= [];
  514. # $perimeter_coll is an ExtrusionPath::Collection object representing a single slice
  515. for my $i (0 .. $n_slices) {
  516. if (
  517. # $perimeter_coll->first_point does not fit inside any slice
  518. $i == $n_slices
  519. # $perimeter_coll->first_point fits inside ith slice
  520. || $point_inside_surface->($i, $perimeter_coll->first_point)) {
  521. $by_extruder{$extruder_id}[$i] //= { perimeters => {} };
  522. $by_extruder{$extruder_id}[$i]{perimeters}{$region_id} //= [];
  523. push @{ $by_extruder{$extruder_id}[$i]{perimeters}{$region_id} }, @$perimeter_coll;
  524. last;
  525. }
  526. }
  527. }
  528. }
  529. # process infill
  530. # $layerm->fills is a collection of ExtrusionPath::Collection objects, each one containing
  531. # the ExtrusionPath objects of a certain infill "group" (also called "surface"
  532. # throughout the code). We can redefine the order of such Collections but we have to
  533. # do each one completely at once.
  534. foreach my $fill (@{$layerm->fills}) {
  535. next if $fill->empty; # this shouldn't happen but first_point() would fail
  536. # init by_extruder item only if we actually use the extruder
  537. my $extruder_id = $fill->[0]->is_solid_infill
  538. ? $region->config->solid_infill_extruder-1
  539. : $region->config->infill_extruder-1;
  540. $by_extruder{$extruder_id} //= [];
  541. # $fill is an ExtrusionPath::Collection object
  542. for my $i (0 .. $n_slices) {
  543. if ($i == $n_slices
  544. || $point_inside_surface->($i, $fill->first_point)) {
  545. $by_extruder{$extruder_id}[$i] //= { infill => {} };
  546. $by_extruder{$extruder_id}[$i]{infill}{$region_id} //= [];
  547. push @{ $by_extruder{$extruder_id}[$i]{infill}{$region_id} }, $fill;
  548. last;
  549. }
  550. }
  551. }
  552. }
  553. # tweak extruder ordering to save toolchanges
  554. my @extruders = sort { $a <=> $b } keys %by_extruder;
  555. if (@extruders > 1) {
  556. my $last_extruder_id = $self->_gcodegen->writer->extruder->id;
  557. if (exists $by_extruder{$last_extruder_id}) {
  558. @extruders = (
  559. $last_extruder_id,
  560. grep $_ != $last_extruder_id, @extruders,
  561. );
  562. }
  563. }
  564. foreach my $extruder_id (@extruders) {
  565. $gcode .= $self->_gcodegen->set_extruder($extruder_id);
  566. foreach my $island (@{ $by_extruder{$extruder_id} }) {
  567. if ($self->print->config->infill_first) {
  568. $gcode .= $self->_extrude_infill($island->{infill} // {});
  569. $gcode .= $self->_extrude_perimeters($island->{perimeters} // {});
  570. } else {
  571. $gcode .= $self->_extrude_perimeters($island->{perimeters} // {});
  572. $gcode .= $self->_extrude_infill($island->{infill} // {});
  573. }
  574. }
  575. }
  576. }
  577. # apply spiral vase post-processing if this layer contains suitable geometry
  578. # (we must feed all the G-code into the post-processor, including the first
  579. # bottom non-spiral layers otherwise it will mess with positions)
  580. # we apply spiral vase at this stage because it requires a full layer
  581. $gcode = $self->_spiral_vase->process_layer($gcode)
  582. if defined $self->_spiral_vase;
  583. # apply cooling logic; this may alter speeds
  584. $gcode = $self->_cooling_buffer->append(
  585. $gcode,
  586. $layer->object->ptr . ref($layer), # differentiate $obj_id between normal layers and support layers
  587. $layer->id,
  588. $layer->print_z,
  589. ) if defined $self->_cooling_buffer;
  590. print {$self->fh} $self->filter($gcode);
  591. }
  592. # Extrude perimeters: Decide where to put seams (hide or align seams).
  593. sub _extrude_perimeters {
  594. my ($self, $entities_by_region) = @_;
  595. my $gcode = "";
  596. foreach my $region_id (sort keys %$entities_by_region) {
  597. $self->_gcodegen->config->apply_static($self->print->get_region($region_id)->config);
  598. $gcode .= $self->_gcodegen->extrude($_, 'perimeter', -1)
  599. for @{ $entities_by_region->{$region_id} };
  600. }
  601. return $gcode;
  602. }
  603. # Chain the paths hierarchically by a greedy algorithm to minimize a travel distance.
  604. sub _extrude_infill {
  605. my ($self, $entities_by_region) = @_;
  606. my $gcode = "";
  607. foreach my $region_id (sort keys %$entities_by_region) {
  608. $self->_gcodegen->config->apply_static($self->print->get_region($region_id)->config);
  609. my $collection = Slic3r::ExtrusionPath::Collection->new(@{ $entities_by_region->{$region_id} });
  610. for my $fill (@{$collection->chained_path_from($self->_gcodegen->last_pos, 0)}) {
  611. if ($fill->isa('Slic3r::ExtrusionPath::Collection')) {
  612. $gcode .= $self->_gcodegen->extrude($_, 'infill', -1)
  613. for @{$fill->chained_path_from($self->_gcodegen->last_pos, 0)};
  614. } else {
  615. $gcode .= $self->_gcodegen->extrude($fill, 'infill', -1) ;
  616. }
  617. }
  618. }
  619. return $gcode;
  620. }
  621. sub flush_filters {
  622. my ($self) = @_;
  623. print {$self->fh} $self->filter($self->_cooling_buffer->flush, 1);
  624. }
  625. sub filter {
  626. my ($self, $gcode, $flush) = @_;
  627. # apply vibration limit if enabled;
  628. # this injects pauses according to time (thus depends on actual speeds)
  629. $gcode = $self->_vibration_limit->process($gcode)
  630. if defined $self->_vibration_limit;
  631. # apply pressure regulation if enabled;
  632. # this depends on actual speeds
  633. $gcode = $self->_pressure_regulator->process($gcode, $flush)
  634. if defined $self->_pressure_regulator;
  635. # apply arc fitting if enabled;
  636. # this does not depend on speeds but changes G1 XY commands into G2/G2 IJ
  637. $gcode = $self->_arc_fitting->process($gcode)
  638. if defined $self->_arc_fitting;
  639. return $gcode;
  640. }
  641. 1;