Print.pm 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377
  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 diff_pl);
  15. use Slic3r::Print::State ':steps';
  16. use Slic3r::Surface qw(S_TYPE_BOTTOM);
  17. our $status_cb;
  18. sub set_status_cb {
  19. my ($class, $cb) = @_;
  20. $status_cb = $cb;
  21. }
  22. sub status_cb {
  23. return $status_cb // sub {};
  24. }
  25. # this value is not supposed to be compared with $layer->id
  26. # since they have different semantics
  27. sub total_layer_count {
  28. my $self = shift;
  29. return max(map $_->total_layer_count, @{$self->objects});
  30. }
  31. sub size {
  32. my $self = shift;
  33. return $self->bounding_box->size;
  34. }
  35. sub process {
  36. my ($self) = @_;
  37. ### No need to call this as we call it as part of prepare_infill()
  38. ### until we fix the idempotency issue.
  39. ###$self->status_cb->(20, "Generating perimeters");
  40. ###$_->make_perimeters for @{$self->objects};
  41. $self->status_cb->(70, "Infilling layers");
  42. $_->infill for @{$self->objects};
  43. $_->generate_support_material for @{$self->objects};
  44. $self->make_skirt;
  45. $self->make_brim; # must come after make_skirt
  46. # time to make some statistics
  47. if (0) {
  48. eval "use Devel::Size";
  49. print "MEMORY USAGE:\n";
  50. printf " meshes = %.1fMb\n", List::Util::sum(map Devel::Size::total_size($_->meshes), @{$self->objects})/1024/1024;
  51. printf " layer slices = %.1fMb\n", List::Util::sum(map Devel::Size::total_size($_->slices), map @{$_->layers}, @{$self->objects})/1024/1024;
  52. printf " region slices = %.1fMb\n", List::Util::sum(map Devel::Size::total_size($_->slices), map @{$_->regions}, map @{$_->layers}, @{$self->objects})/1024/1024;
  53. printf " perimeters = %.1fMb\n", List::Util::sum(map Devel::Size::total_size($_->perimeters), map @{$_->regions}, map @{$_->layers}, @{$self->objects})/1024/1024;
  54. printf " fills = %.1fMb\n", List::Util::sum(map Devel::Size::total_size($_->fills), map @{$_->regions}, map @{$_->layers}, @{$self->objects})/1024/1024;
  55. printf " print object = %.1fMb\n", Devel::Size::total_size($self)/1024/1024;
  56. }
  57. if (0) {
  58. eval "use Slic3r::Test::SectionCut";
  59. Slic3r::Test::SectionCut->new(print => $self)->export_svg("section_cut.svg");
  60. }
  61. }
  62. sub export_gcode {
  63. my $self = shift;
  64. my %params = @_;
  65. # prerequisites
  66. $self->process;
  67. # output everything to a G-code file
  68. my $output_file = $self->output_filepath($params{output_file} // '');
  69. $self->status_cb->(90, "Exporting G-code" . ($output_file ? " to $output_file" : ""));
  70. {
  71. # open output gcode file if we weren't supplied a file-handle
  72. my ($fh, $tempfile);
  73. if ($params{output_fh}) {
  74. $fh = $params{output_fh};
  75. } else {
  76. $tempfile = "$output_file.tmp";
  77. Slic3r::open(\$fh, ">", $tempfile)
  78. or die "Failed to open $tempfile for writing\n";
  79. # enable UTF-8 output since user might have entered Unicode characters in fields like notes
  80. binmode $fh, ':utf8';
  81. }
  82. Slic3r::Print::GCode->new(
  83. print => $self,
  84. fh => $fh,
  85. )->export;
  86. # close our gcode file
  87. close $fh;
  88. if ($tempfile) {
  89. my $renamed = 0;
  90. for my $i (1..5) {
  91. last if $renamed = rename Slic3r::encode_path($tempfile), Slic3r::encode_path($output_file);
  92. # Wait for 1/4 seconds and try to rename once again.
  93. select(undef, undef, undef, 0.25);
  94. }
  95. Slic3r::debugf "Failed to remove the output G-code file from $tempfile to $output_file. Is $tempfile locked?\n"
  96. if !$renamed;
  97. }
  98. }
  99. # run post-processing scripts
  100. if (@{$self->config->post_process}) {
  101. $self->status_cb->(95, "Running post-processing scripts");
  102. $self->config->setenv;
  103. for my $script (@{$self->config->post_process}) {
  104. Slic3r::debugf " '%s' '%s'\n", $script, $output_file;
  105. # -x doesn't return true on Windows except for .exe files
  106. if (($^O eq 'MSWin32') ? !(-e $script) : !(-x $script)) {
  107. die "The configured post-processing script is not executable: check permissions. ($script)\n";
  108. }
  109. system($script, $output_file);
  110. }
  111. }
  112. }
  113. # Export SVG slices for the offline SLA printing.
  114. sub export_svg {
  115. my $self = shift;
  116. my %params = @_;
  117. $_->slice for @{$self->objects};
  118. my $fh = $params{output_fh};
  119. if (!$fh) {
  120. my $output_file = $self->output_filepath($params{output_file});
  121. $output_file =~ s/\.gcode$/.svg/i;
  122. Slic3r::open(\$fh, ">", $output_file) or die "Failed to open $output_file for writing\n";
  123. print "Exporting to $output_file..." unless $params{quiet};
  124. }
  125. my $print_bb = $self->bounding_box;
  126. my $print_size = $print_bb->size;
  127. print $fh sprintf <<"EOF", unscale($print_size->[X]), unscale($print_size->[Y]);
  128. <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
  129. <!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.0//EN" "http://www.w3.org/TR/2001/REC-SVG-20010904/DTD/svg10.dtd">
  130. <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">
  131. <!--
  132. Generated using Slic3r $Slic3r::VERSION
  133. http://slic3r.org/
  134. -->
  135. EOF
  136. my $print_polygon = sub {
  137. my ($polygon, $type) = @_;
  138. printf $fh qq{ <polygon slic3r:type="%s" points="%s" style="fill: %s" />\n},
  139. $type, (join ' ', map { join ',', map unscale $_, @$_ } @$polygon),
  140. ($type eq 'contour' ? 'white' : 'black');
  141. };
  142. my @layers = sort { $a->print_z <=> $b->print_z }
  143. map { @{$_->layers}, @{$_->support_layers} }
  144. @{$self->objects};
  145. my $layer_id = -1;
  146. my @previous_layer_slices = ();
  147. for my $layer (@layers) {
  148. $layer_id++;
  149. if ($layer->slice_z == -1) {
  150. printf $fh qq{ <g id="layer%d">\n}, $layer_id;
  151. } else {
  152. printf $fh qq{ <g id="layer%d" slic3r:z="%s">\n}, $layer_id, unscale($layer->slice_z);
  153. }
  154. my @current_layer_slices = ();
  155. # sort slices so that the outermost ones come first
  156. my @slices = sort { $a->contour->contains_point($b->contour->first_point) ? 0 : 1 } @{$layer->slices};
  157. foreach my $copy (@{$layer->object->_shifted_copies}) {
  158. foreach my $slice (@slices) {
  159. my $expolygon = $slice->clone;
  160. $expolygon->translate(@$copy);
  161. $expolygon->translate(-$print_bb->x_min, -$print_bb->y_min);
  162. $print_polygon->($expolygon->contour, 'contour');
  163. $print_polygon->($_, 'hole') for @{$expolygon->holes};
  164. push @current_layer_slices, $expolygon;
  165. }
  166. }
  167. # generate support material
  168. if ($self->has_support_material && $layer->id > 0) {
  169. my (@supported_slices, @unsupported_slices) = ();
  170. foreach my $expolygon (@current_layer_slices) {
  171. my $intersection = intersection_ex(
  172. [ map @$_, @previous_layer_slices ],
  173. [ @$expolygon ],
  174. );
  175. @$intersection
  176. ? push @supported_slices, $expolygon
  177. : push @unsupported_slices, $expolygon;
  178. }
  179. my @supported_points = map @$_, @$_, @supported_slices;
  180. foreach my $expolygon (@unsupported_slices) {
  181. # look for the nearest point to this island among all
  182. # supported points
  183. my $contour = $expolygon->contour;
  184. my $support_point = $contour->first_point->nearest_point(\@supported_points)
  185. or next;
  186. my $anchor_point = $support_point->nearest_point([ @$contour ]);
  187. printf $fh qq{ <line x1="%s" y1="%s" x2="%s" y2="%s" style="stroke-width: 2; stroke: white" />\n},
  188. map @$_, $support_point, $anchor_point;
  189. }
  190. }
  191. print $fh qq{ </g>\n};
  192. @previous_layer_slices = @current_layer_slices;
  193. }
  194. print $fh "</svg>\n";
  195. close $fh;
  196. print "Done.\n" unless $params{quiet};
  197. }
  198. sub make_skirt {
  199. my $self = shift;
  200. # prerequisites
  201. $_->make_perimeters for @{$self->objects};
  202. $_->infill for @{$self->objects};
  203. $_->generate_support_material for @{$self->objects};
  204. return if $self->step_done(STEP_SKIRT);
  205. $self->set_step_started(STEP_SKIRT);
  206. # since this method must be idempotent, we clear skirt paths *before*
  207. # checking whether we need to generate them
  208. $self->skirt->clear;
  209. if (!$self->has_skirt) {
  210. $self->set_step_done(STEP_SKIRT);
  211. return;
  212. }
  213. $self->status_cb->(88, "Generating skirt");
  214. # First off we need to decide how tall the skirt must be.
  215. # The skirt_height option from config is expressed in layers, but our
  216. # object might have different layer heights, so we need to find the print_z
  217. # of the highest layer involved.
  218. # Note that unless has_infinite_skirt() == true
  219. # the actual skirt might not reach this $skirt_height_z value since the print
  220. # order of objects on each layer is not guaranteed and will not generally
  221. # include the thickest object first. It is just guaranteed that a skirt is
  222. # prepended to the first 'n' layers (with 'n' = skirt_height).
  223. # $skirt_height_z in this case is the highest possible skirt height for safety.
  224. my $skirt_height_z = -1;
  225. foreach my $object (@{$self->objects}) {
  226. my $skirt_height = $self->has_infinite_skirt
  227. ? $object->layer_count
  228. : min($self->config->skirt_height, $object->layer_count);
  229. my $highest_layer = $object->get_layer($skirt_height - 1);
  230. $skirt_height_z = max($skirt_height_z, $highest_layer->print_z);
  231. }
  232. # collect points from all layers contained in skirt height
  233. my @points = ();
  234. foreach my $object (@{$self->objects}) {
  235. my @object_points = ();
  236. # get object layers up to $skirt_height_z
  237. foreach my $layer (@{$object->layers}) {
  238. last if $layer->print_z > $skirt_height_z;
  239. push @object_points, map @$_, map @$_, @{$layer->slices};
  240. }
  241. # get support layers up to $skirt_height_z
  242. foreach my $layer (@{$object->support_layers}) {
  243. last if $layer->print_z > $skirt_height_z;
  244. push @object_points, map @{$_->polyline}, @{$layer->support_fills} if $layer->support_fills;
  245. push @object_points, map @{$_->polyline}, @{$layer->support_interface_fills} if $layer->support_interface_fills;
  246. }
  247. # repeat points for each object copy
  248. foreach my $copy (@{$object->_shifted_copies}) {
  249. my @copy_points = map $_->clone, @object_points;
  250. $_->translate(@$copy) for @copy_points;
  251. push @points, @copy_points;
  252. }
  253. }
  254. return if @points < 3; # at least three points required for a convex hull
  255. # find out convex hull
  256. my $convex_hull = convex_hull(\@points);
  257. my @extruded_length = (); # for each extruder
  258. # skirt may be printed on several layers, having distinct layer heights,
  259. # but loops must be aligned so can't vary width/spacing
  260. # TODO: use each extruder's own flow
  261. my $first_layer_height = $self->skirt_first_layer_height;
  262. my $flow = $self->skirt_flow;
  263. my $spacing = $flow->spacing;
  264. my $mm3_per_mm = $flow->mm3_per_mm;
  265. my @extruders_e_per_mm = ();
  266. my $extruder_idx = 0;
  267. my $skirts = $self->config->skirts;
  268. $skirts ||= 1 if $self->has_infinite_skirt;
  269. # draw outlines from outside to inside
  270. # loop while we have less skirts than required or any extruder hasn't reached the min length if any
  271. my $distance = scale max($self->config->skirt_distance, $self->config->brim_width);
  272. for (my $i = $skirts; $i > 0; $i--) {
  273. $distance += scale $spacing;
  274. my $loop = offset([$convex_hull], $distance, 1, JT_ROUND, scale(0.1))->[0];
  275. my $eloop = Slic3r::ExtrusionLoop->new_from_paths(
  276. Slic3r::ExtrusionPath->new(
  277. polyline => Slic3r::Polygon->new(@$loop)->split_at_first_point,
  278. role => EXTR_ROLE_SKIRT,
  279. mm3_per_mm => $mm3_per_mm, # this will be overridden at G-code export time
  280. width => $flow->width,
  281. height => $first_layer_height, # this will be overridden at G-code export time
  282. ),
  283. );
  284. $eloop->role(EXTRL_ROLE_SKIRT);
  285. $self->skirt->append($eloop);
  286. if ($self->config->min_skirt_length > 0) {
  287. $extruded_length[$extruder_idx] ||= 0;
  288. if (!$extruders_e_per_mm[$extruder_idx]) {
  289. my $config = Slic3r::Config::GCode->new;
  290. $config->apply_static($self->config);
  291. my $extruder = Slic3r::Extruder->new($extruder_idx, $config);
  292. $extruders_e_per_mm[$extruder_idx] = $extruder->e_per_mm($mm3_per_mm);
  293. }
  294. $extruded_length[$extruder_idx] += unscale $loop->length * $extruders_e_per_mm[$extruder_idx];
  295. $i++ if defined first { ($extruded_length[$_] // 0) < $self->config->min_skirt_length } 0 .. $#{$self->extruders};
  296. if ($extruded_length[$extruder_idx] >= $self->config->min_skirt_length) {
  297. if ($extruder_idx < $#{$self->extruders}) {
  298. $extruder_idx++;
  299. next;
  300. }
  301. }
  302. }
  303. }
  304. $self->skirt->reverse;
  305. $self->set_step_done(STEP_SKIRT);
  306. }
  307. sub make_brim {
  308. my $self = shift;
  309. # prerequisites
  310. $_->make_perimeters for @{$self->objects};
  311. $_->infill for @{$self->objects};
  312. $_->generate_support_material for @{$self->objects};
  313. $self->make_skirt;
  314. $self->status_cb->(88, "Generating brim");
  315. $self->_make_brim;
  316. }
  317. # Wrapper around the C++ Slic3r::Print::validate()
  318. # to produce a Perl exception without a hang-up on some Strawberry perls.
  319. sub validate
  320. {
  321. my $self = shift;
  322. my $err = $self->_validate;
  323. die $err . "\n" if (defined($err) && $err ne '');
  324. }
  325. 1;