Print.pm 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480
  1. # The slicing work horse.
  2. # Extends C++ class Slic3r::Print
  3. package Slic3r::Print;
  4. use strict;
  5. use warnings;
  6. use File::Basename qw(basename fileparse);
  7. use File::Spec;
  8. use List::Util qw(min max first sum);
  9. use Slic3r::ExtrusionLoop ':roles';
  10. use Slic3r::ExtrusionPath ':roles';
  11. use Slic3r::Flow ':roles';
  12. use Slic3r::Geometry qw(X Y Z X1 Y1 X2 Y2 MIN MAX PI scale unscale convex_hull);
  13. use Slic3r::Geometry::Clipper qw(diff_ex union_ex intersection_ex intersection offset
  14. offset2 union union_pt_chained JT_ROUND JT_SQUARE);
  15. use Slic3r::Print::State ':steps';
  16. our $status_cb;
  17. sub set_status_cb {
  18. my ($class, $cb) = @_;
  19. $status_cb = $cb;
  20. }
  21. sub status_cb {
  22. return $status_cb // sub {};
  23. }
  24. # this value is not supposed to be compared with $layer->id
  25. # since they have different semantics
  26. sub total_layer_count {
  27. my $self = shift;
  28. return max(map $_->total_layer_count, @{$self->objects});
  29. }
  30. sub size {
  31. my $self = shift;
  32. return $self->bounding_box->size;
  33. }
  34. # Slicing process, running at a background thread.
  35. sub process {
  36. my ($self) = @_;
  37. $self->status_cb->(20, "Generating perimeters");
  38. $_->make_perimeters for @{$self->objects};
  39. $self->status_cb->(70, "Infilling layers");
  40. $_->infill for @{$self->objects};
  41. $_->generate_support_material for @{$self->objects};
  42. $self->make_skirt;
  43. $self->make_brim; # must come after make_skirt
  44. # time to make some statistics
  45. if (0) {
  46. eval "use Devel::Size";
  47. print "MEMORY USAGE:\n";
  48. printf " meshes = %.1fMb\n", List::Util::sum(map Devel::Size::total_size($_->meshes), @{$self->objects})/1024/1024;
  49. printf " layer slices = %.1fMb\n", List::Util::sum(map Devel::Size::total_size($_->slices), map @{$_->layers}, @{$self->objects})/1024/1024;
  50. printf " region slices = %.1fMb\n", List::Util::sum(map Devel::Size::total_size($_->slices), map @{$_->regions}, map @{$_->layers}, @{$self->objects})/1024/1024;
  51. printf " perimeters = %.1fMb\n", List::Util::sum(map Devel::Size::total_size($_->perimeters), map @{$_->regions}, map @{$_->layers}, @{$self->objects})/1024/1024;
  52. printf " fills = %.1fMb\n", List::Util::sum(map Devel::Size::total_size($_->fills), map @{$_->regions}, map @{$_->layers}, @{$self->objects})/1024/1024;
  53. printf " print object = %.1fMb\n", Devel::Size::total_size($self)/1024/1024;
  54. }
  55. if (0) {
  56. eval "use Slic3r::Test::SectionCut";
  57. Slic3r::Test::SectionCut->new(print => $self)->export_svg("section_cut.svg");
  58. }
  59. }
  60. sub export_gcode {
  61. my $self = shift;
  62. my %params = @_;
  63. # prerequisites
  64. $self->process;
  65. # output everything to a G-code file
  66. my $output_file = $self->expanded_output_filepath($params{output_file});
  67. $self->status_cb->(90, "Exporting G-code" . ($output_file ? " to $output_file" : ""));
  68. $self->write_gcode($params{output_fh} || $output_file);
  69. # run post-processing scripts
  70. if (@{$self->config->post_process}) {
  71. $self->status_cb->(95, "Running post-processing scripts");
  72. $self->config->setenv;
  73. for my $script (@{$self->config->post_process}) {
  74. Slic3r::debugf " '%s' '%s'\n", $script, $output_file;
  75. # -x doesn't return true on Windows except for .exe files
  76. if (($^O eq 'MSWin32') ? !(-e $script) : !(-x $script)) {
  77. die "The configured post-processing script is not executable: check permissions. ($script)\n";
  78. }
  79. system($script, $output_file);
  80. }
  81. }
  82. }
  83. # Export SVG slices for the offline SLA printing.
  84. sub export_svg {
  85. my $self = shift;
  86. my %params = @_;
  87. $_->slice for @{$self->objects};
  88. my $fh = $params{output_fh};
  89. if (!$fh) {
  90. my $output_file = $self->expanded_output_filepath($params{output_file});
  91. $output_file =~ s/\.gcode$/.svg/i;
  92. Slic3r::open(\$fh, ">", $output_file) or die "Failed to open $output_file for writing\n";
  93. print "Exporting to $output_file..." unless $params{quiet};
  94. }
  95. my $print_bb = $self->bounding_box;
  96. my $print_size = $print_bb->size;
  97. print $fh sprintf <<"EOF", unscale($print_size->[X]), unscale($print_size->[Y]);
  98. <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
  99. <!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.0//EN" "http://www.w3.org/TR/2001/REC-SVG-20010904/DTD/svg10.dtd">
  100. <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">
  101. <!--
  102. Generated using Slic3r $Slic3r::VERSION
  103. http://slic3r.org/
  104. -->
  105. EOF
  106. my $print_polygon = sub {
  107. my ($polygon, $type) = @_;
  108. printf $fh qq{ <polygon slic3r:type="%s" points="%s" style="fill: %s" />\n},
  109. $type, (join ' ', map { join ',', map unscale $_, @$_ } @$polygon),
  110. ($type eq 'contour' ? 'white' : 'black');
  111. };
  112. my @layers = sort { $a->print_z <=> $b->print_z }
  113. map { @{$_->layers}, @{$_->support_layers} }
  114. @{$self->objects};
  115. my $layer_id = -1;
  116. my @previous_layer_slices = ();
  117. for my $layer (@layers) {
  118. $layer_id++;
  119. if ($layer->slice_z == -1) {
  120. printf $fh qq{ <g id="layer%d">\n}, $layer_id;
  121. } else {
  122. printf $fh qq{ <g id="layer%d" slic3r:z="%s">\n}, $layer_id, unscale($layer->slice_z);
  123. }
  124. my @current_layer_slices = ();
  125. # sort slices so that the outermost ones come first
  126. my @slices = sort { $a->contour->contains_point($b->contour->first_point) ? 0 : 1 } @{$layer->slices};
  127. foreach my $copy (@{$layer->object->_shifted_copies}) {
  128. foreach my $slice (@slices) {
  129. my $expolygon = $slice->clone;
  130. $expolygon->translate(@$copy);
  131. $expolygon->translate(-$print_bb->x_min, -$print_bb->y_min);
  132. $print_polygon->($expolygon->contour, 'contour');
  133. $print_polygon->($_, 'hole') for @{$expolygon->holes};
  134. push @current_layer_slices, $expolygon;
  135. }
  136. }
  137. # generate support material
  138. if ($self->has_support_material && $layer->id > 0) {
  139. my (@supported_slices, @unsupported_slices) = ();
  140. foreach my $expolygon (@current_layer_slices) {
  141. my $intersection = intersection_ex(
  142. [ map @$_, @previous_layer_slices ],
  143. [ @$expolygon ],
  144. );
  145. @$intersection
  146. ? push @supported_slices, $expolygon
  147. : push @unsupported_slices, $expolygon;
  148. }
  149. my @supported_points = map @$_, @$_, @supported_slices;
  150. foreach my $expolygon (@unsupported_slices) {
  151. # look for the nearest point to this island among all
  152. # supported points
  153. my $contour = $expolygon->contour;
  154. my $support_point = $contour->first_point->nearest_point(\@supported_points)
  155. or next;
  156. my $anchor_point = $support_point->nearest_point([ @$contour ]);
  157. printf $fh qq{ <line x1="%s" y1="%s" x2="%s" y2="%s" style="stroke-width: 2; stroke: white" />\n},
  158. map @$_, $support_point, $anchor_point;
  159. }
  160. }
  161. print $fh qq{ </g>\n};
  162. @previous_layer_slices = @current_layer_slices;
  163. }
  164. print $fh "</svg>\n";
  165. close $fh;
  166. print "Done.\n" unless $params{quiet};
  167. }
  168. sub make_skirt {
  169. my $self = shift;
  170. # prerequisites
  171. $_->make_perimeters for @{$self->objects};
  172. $_->infill for @{$self->objects};
  173. $_->generate_support_material for @{$self->objects};
  174. return if $self->step_done(STEP_SKIRT);
  175. $self->set_step_started(STEP_SKIRT);
  176. # since this method must be idempotent, we clear skirt paths *before*
  177. # checking whether we need to generate them
  178. $self->skirt->clear;
  179. if (!$self->has_skirt) {
  180. $self->set_step_done(STEP_SKIRT);
  181. return;
  182. }
  183. $self->status_cb->(88, "Generating skirt");
  184. # First off we need to decide how tall the skirt must be.
  185. # The skirt_height option from config is expressed in layers, but our
  186. # object might have different layer heights, so we need to find the print_z
  187. # of the highest layer involved.
  188. # Note that unless has_infinite_skirt() == true
  189. # the actual skirt might not reach this $skirt_height_z value since the print
  190. # order of objects on each layer is not guaranteed and will not generally
  191. # include the thickest object first. It is just guaranteed that a skirt is
  192. # prepended to the first 'n' layers (with 'n' = skirt_height).
  193. # $skirt_height_z in this case is the highest possible skirt height for safety.
  194. my $skirt_height_z = -1;
  195. foreach my $object (@{$self->objects}) {
  196. my $skirt_height = $self->has_infinite_skirt
  197. ? $object->layer_count
  198. : min($self->config->skirt_height, $object->layer_count);
  199. my $highest_layer = $object->get_layer($skirt_height - 1);
  200. $skirt_height_z = max($skirt_height_z, $highest_layer->print_z);
  201. }
  202. # collect points from all layers contained in skirt height
  203. my @points = ();
  204. foreach my $object (@{$self->objects}) {
  205. my @object_points = ();
  206. # get object layers up to $skirt_height_z
  207. foreach my $layer (@{$object->layers}) {
  208. last if $layer->print_z > $skirt_height_z;
  209. push @object_points, map @$_, map @$_, @{$layer->slices};
  210. }
  211. # get support layers up to $skirt_height_z
  212. foreach my $layer (@{$object->support_layers}) {
  213. last if $layer->print_z > $skirt_height_z;
  214. push @object_points, map @{$_->polyline}, @{$layer->support_fills} if $layer->support_fills;
  215. push @object_points, map @{$_->polyline}, @{$layer->support_interface_fills} if $layer->support_interface_fills;
  216. }
  217. # repeat points for each object copy
  218. foreach my $copy (@{$object->_shifted_copies}) {
  219. my @copy_points = map $_->clone, @object_points;
  220. $_->translate(@$copy) for @copy_points;
  221. push @points, @copy_points;
  222. }
  223. }
  224. return if @points < 3; # at least three points required for a convex hull
  225. # find out convex hull
  226. my $convex_hull = convex_hull(\@points);
  227. my @extruded_length = (); # for each extruder
  228. # skirt may be printed on several layers, having distinct layer heights,
  229. # but loops must be aligned so can't vary width/spacing
  230. # TODO: use each extruder's own flow
  231. my $first_layer_height = $self->skirt_first_layer_height;
  232. my $flow = $self->skirt_flow;
  233. my $spacing = $flow->spacing;
  234. my $mm3_per_mm = $flow->mm3_per_mm;
  235. my @extruders_e_per_mm = ();
  236. my $extruder_idx = 0;
  237. my $skirts = $self->config->skirts;
  238. $skirts ||= 1 if $self->has_infinite_skirt;
  239. # draw outlines from outside to inside
  240. # loop while we have less skirts than required or any extruder hasn't reached the min length if any
  241. my $distance = scale max($self->config->skirt_distance, $self->config->brim_width);
  242. for (my $i = $skirts; $i > 0; $i--) {
  243. $distance += scale $spacing;
  244. my $loop = offset([$convex_hull], $distance, JT_ROUND, scale(0.1))->[0];
  245. my $eloop = Slic3r::ExtrusionLoop->new_from_paths(
  246. Slic3r::ExtrusionPath->new(
  247. polyline => Slic3r::Polygon->new(@$loop)->split_at_first_point,
  248. role => EXTR_ROLE_SKIRT,
  249. mm3_per_mm => $mm3_per_mm, # this will be overridden at G-code export time
  250. width => $flow->width,
  251. height => $first_layer_height, # this will be overridden at G-code export time
  252. ),
  253. );
  254. $eloop->role(EXTRL_ROLE_SKIRT);
  255. $self->skirt->append($eloop);
  256. if ($self->config->min_skirt_length > 0) {
  257. $extruded_length[$extruder_idx] ||= 0;
  258. if (!$extruders_e_per_mm[$extruder_idx]) {
  259. my $config = Slic3r::Config::GCode->new;
  260. $config->apply_static($self->config);
  261. my $extruder = Slic3r::Extruder->new($extruder_idx, $config);
  262. $extruders_e_per_mm[$extruder_idx] = $extruder->e_per_mm($mm3_per_mm);
  263. }
  264. $extruded_length[$extruder_idx] += unscale $loop->length * $extruders_e_per_mm[$extruder_idx];
  265. $i++ if defined first { ($extruded_length[$_] // 0) < $self->config->min_skirt_length } 0 .. $#{$self->extruders};
  266. if ($extruded_length[$extruder_idx] >= $self->config->min_skirt_length) {
  267. if ($extruder_idx < $#{$self->extruders}) {
  268. $extruder_idx++;
  269. next;
  270. }
  271. }
  272. }
  273. }
  274. $self->skirt->reverse;
  275. $self->set_step_done(STEP_SKIRT);
  276. }
  277. sub make_brim {
  278. my $self = shift;
  279. # prerequisites
  280. $_->make_perimeters for @{$self->objects};
  281. $_->infill for @{$self->objects};
  282. $_->generate_support_material for @{$self->objects};
  283. $self->make_skirt;
  284. return if $self->step_done(STEP_BRIM);
  285. $self->set_step_started(STEP_BRIM);
  286. # since this method must be idempotent, we clear brim paths *before*
  287. # checking whether we need to generate them
  288. $self->brim->clear;
  289. if ($self->config->brim_width == 0) {
  290. $self->set_step_done(STEP_BRIM);
  291. return;
  292. }
  293. $self->status_cb->(88, "Generating brim");
  294. # brim is only printed on first layer and uses perimeter extruder
  295. my $first_layer_height = $self->skirt_first_layer_height;
  296. my $flow = $self->brim_flow;
  297. my $mm3_per_mm = $flow->mm3_per_mm;
  298. my $grow_distance = $flow->scaled_width / 2;
  299. my @islands = (); # array of polygons
  300. foreach my $obj_idx (0 .. ($self->object_count - 1)) {
  301. my $object = $self->objects->[$obj_idx];
  302. my $layer0 = $object->get_layer(0);
  303. my @object_islands = (
  304. (map $_->contour, @{$layer0->slices}),
  305. );
  306. if (@{ $object->support_layers }) {
  307. my $support_layer0 = $object->support_layers->[0];
  308. push @object_islands,
  309. (map @{$_->polyline->grow($grow_distance)}, @{$support_layer0->support_fills})
  310. if $support_layer0->support_fills;
  311. push @object_islands,
  312. (map @{$_->polyline->grow($grow_distance)}, @{$support_layer0->support_interface_fills})
  313. if $support_layer0->support_interface_fills;
  314. }
  315. foreach my $copy (@{$object->_shifted_copies}) {
  316. push @islands, map { $_->translate(@$copy); $_ } map $_->clone, @object_islands;
  317. }
  318. }
  319. my @loops = ();
  320. my $num_loops = sprintf "%.0f", $self->config->brim_width / $flow->width;
  321. for my $i (reverse 1 .. $num_loops) {
  322. # JT_SQUARE ensures no vertex is outside the given offset distance
  323. # -0.5 because islands are not represented by their centerlines
  324. # (first offset more, then step back - reverse order than the one used for
  325. # perimeters because here we're offsetting outwards)
  326. push @loops, @{offset2(\@islands, ($i + 0.5) * $flow->scaled_spacing, -1.0 * $flow->scaled_spacing, JT_SQUARE)};
  327. }
  328. $self->brim->append(map Slic3r::ExtrusionLoop->new_from_paths(
  329. Slic3r::ExtrusionPath->new(
  330. polyline => Slic3r::Polygon->new(@$_)->split_at_first_point,
  331. role => EXTR_ROLE_SKIRT,
  332. mm3_per_mm => $mm3_per_mm,
  333. width => $flow->width,
  334. height => $first_layer_height,
  335. ),
  336. ), reverse @{union_pt_chained(\@loops)});
  337. $self->set_step_done(STEP_BRIM);
  338. }
  339. sub write_gcode {
  340. my $self = shift;
  341. my ($file) = @_;
  342. my $tempfile;
  343. # open output gcode file if we weren't supplied a file-handle
  344. my $fh;
  345. if (ref $file eq 'IO::Scalar') {
  346. $fh = $file;
  347. } else {
  348. $tempfile = "$file.tmp";
  349. Slic3r::open(\$fh, ">", $tempfile)
  350. or die "Failed to open $tempfile for writing\n";
  351. # enable UTF-8 output since user might have entered Unicode characters in fields like notes
  352. binmode $fh, ':utf8';
  353. }
  354. my $exporter = Slic3r::Print::GCode->new(
  355. print => $self,
  356. fh => $fh,
  357. );
  358. $exporter->export;
  359. # close our gcode file
  360. close $fh;
  361. if ($tempfile) {
  362. my $i;
  363. for ($i = 0; $i < 5; $i += 1) {
  364. last if (rename Slic3r::encode_path($tempfile), Slic3r::encode_path($file));
  365. # Wait for 1/4 seconds and try to rename once again.
  366. select(undef, undef, undef, 0.25);
  367. }
  368. Slic3r::debugf "Failed to remove the output G-code file from $tempfile to $file. Is $tempfile locked?\n" if ($i == 5);
  369. }
  370. }
  371. # this method will return the supplied input file path after expanding its
  372. # format variables with their values
  373. sub expanded_output_filepath {
  374. my $self = shift;
  375. my ($path) = @_;
  376. return undef if !@{$self->objects};
  377. my $input_file = first { defined $_ } map $_->model_object->input_file, @{$self->objects};
  378. return undef if !defined $input_file;
  379. my $filename = my $filename_base = basename($input_file);
  380. $filename_base =~ s/\.[^.]+$//; # without suffix
  381. # set filename in placeholder parser so that it's available also in custom G-code
  382. $self->placeholder_parser->set(input_filename => $filename);
  383. $self->placeholder_parser->set(input_filename_base => $filename_base);
  384. # set other variables from model object
  385. $self->placeholder_parser->set_multiple(
  386. scale => [ map $_->model_object->instances->[0]->scaling_factor * 100 . "%", @{$self->objects} ],
  387. );
  388. if ($path && -d $path) {
  389. # if output path is an existing directory, we take that and append
  390. # the specified filename format
  391. $path = File::Spec->join($path, $self->config->output_filename_format);
  392. } elsif (!$path) {
  393. # if no explicit output file was defined, we take the input
  394. # file directory and append the specified filename format
  395. $path = (fileparse($input_file))[1] . $self->config->output_filename_format;
  396. } else {
  397. # path is a full path to a file so we use it as it is
  398. }
  399. # make sure we use an up-to-date timestamp
  400. $self->placeholder_parser->update_timestamp;
  401. return $self->placeholder_parser->process($path);
  402. }
  403. # Wrapper around the C++ Slic3r::Print::validate()
  404. # to produce a Perl exception without a hang-up on some Strawberry perls.
  405. sub validate
  406. {
  407. my $self = shift;
  408. my $err = $self->_validate;
  409. die $err . "\n" if (defined($err) && $err ne '');
  410. }
  411. 1;