Region.pm 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533
  1. package Slic3r::Layer::Region;
  2. use Moo;
  3. use Math::Clipper ':all';
  4. use Slic3r::ExtrusionPath ':roles';
  5. use Slic3r::Geometry qw(scale shortest_path);
  6. use Slic3r::Geometry::Clipper qw(safety_offset union_ex diff_ex intersection_ex);
  7. use Slic3r::Surface ':types';
  8. has 'layer' => (
  9. is => 'ro',
  10. weak_ref => 1,
  11. required => 1,
  12. handles => [qw(id slice_z print_z height flow)],
  13. );
  14. has 'region' => (is => 'ro', required => 1);
  15. has 'perimeter_flow' => (is => 'lazy');
  16. has 'infill_flow' => (is => 'lazy');
  17. # collection of spare segments generated by slicing the original geometry;
  18. # these need to be merged in continuos (closed) polylines
  19. has 'lines' => (is => 'rw', default => sub { [] });
  20. # collection of surfaces generated by slicing the original geometry
  21. has 'slices' => (is => 'rw', default => sub { [] });
  22. # collection of polygons or polylines representing thin walls contained
  23. # in the original geometry
  24. has 'thin_walls' => (is => 'rw', default => sub { [] });
  25. # collection of polygons or polylines representing thin infill regions that
  26. # need to be filled with a medial axis
  27. has 'thin_fills' => (is => 'rw', default => sub { [] });
  28. # collection of expolygons generated by offsetting the innermost perimeter(s)
  29. # they represent boundaries of areas to fill, typed (top/bottom/internal)
  30. has 'surfaces' => (is => 'rw', default => sub { [] });
  31. # collection of surfaces for infill generation. the difference between surfaces
  32. # fill_surfaces is that this one honors fill_density == 0 and turns small internal
  33. # surfaces into solid ones
  34. has 'fill_surfaces' => (is => 'rw', default => sub { [] });
  35. # ordered collection of extrusion paths/loops to build all perimeters
  36. has 'perimeters' => (is => 'rw', default => sub { [] });
  37. # ordered collection of extrusion paths to fill surfaces
  38. has 'fills' => (is => 'rw', default => sub { [] });
  39. sub _build_perimeter_flow {
  40. my $self = shift;
  41. return $self->id == 0
  42. ? $self->region->first_layer_flows->{perimeter}
  43. : $self->region->flows->{perimeter}
  44. }
  45. sub _build_infill_flow {
  46. my $self = shift;
  47. return $self->id == 0
  48. ? $self->region->first_layer_flows->{infill}
  49. : $self->region->flows->{infill}
  50. }
  51. # build polylines from lines
  52. sub make_surfaces {
  53. my $self = shift;
  54. my ($loops) = @_;
  55. return if !@$loops;
  56. {
  57. my $safety_offset = scale 0.1;
  58. # merge everything
  59. my $expolygons = [ map $_->offset_ex(-$safety_offset), @{union_ex(safety_offset($loops, $safety_offset))} ];
  60. Slic3r::debugf " %d surface(s) having %d holes detected from %d polylines\n",
  61. scalar(@$expolygons), scalar(map $_->holes, @$expolygons), scalar(@$loops);
  62. $self->slices([
  63. map Slic3r::Surface->new(expolygon => $_, surface_type => S_TYPE_INTERNAL),
  64. @$expolygons
  65. ]);
  66. }
  67. # the contours must be offsetted by half extrusion width inwards
  68. {
  69. my $distance = scale $self->perimeter_flow->width / 2;
  70. my @surfaces = @{$self->slices};
  71. @{$self->slices} = ();
  72. foreach my $surface (@surfaces) {
  73. push @{$self->slices}, map Slic3r::Surface->new
  74. (expolygon => $_, surface_type => S_TYPE_INTERNAL),
  75. map $_->offset_ex(+$distance),
  76. $surface->expolygon->offset_ex(-2*$distance);
  77. }
  78. # now detect thin walls by re-outgrowing offsetted surfaces and subtracting
  79. # them from the original slices
  80. my $outgrown = Math::Clipper::offset([ map $_->p, @{$self->slices} ], $distance);
  81. my $diff = diff_ex(
  82. [ map $_->p, @surfaces ],
  83. $outgrown,
  84. 1,
  85. );
  86. $self->thin_walls([]);
  87. if (@$diff) {
  88. my $area_threshold = scale($self->perimeter_flow->spacing) ** 2;
  89. @$diff = grep $_->area > ($area_threshold), @$diff;
  90. @{$self->thin_walls} = map $_->medial_axis(scale $self->perimeter_flow->width), @$diff;
  91. Slic3r::debugf " %d thin walls detected\n", scalar(@{$self->thin_walls}) if @{$self->thin_walls};
  92. }
  93. }
  94. if (0) {
  95. require "Slic3r/SVG.pm";
  96. Slic3r::SVG::output(undef, "surfaces.svg",
  97. polygons => [ map $_->contour, @{$self->slices} ],
  98. red_polygons => [ map $_->p, map @{$_->holes}, @{$self->slices} ],
  99. );
  100. }
  101. }
  102. sub make_perimeters {
  103. my $self = shift;
  104. my $gap_area_threshold = scale($self->perimeter_flow->width)** 2;
  105. # this array will hold one arrayref per original surface (island);
  106. # each item of this arrayref is an arrayref representing a depth (from outer
  107. # perimeters to inner); each item of this arrayref is an ExPolygon:
  108. # @perimeters = (
  109. # [ # first island
  110. # [ Slic3r::ExPolygon, Slic3r::ExPolygon... ], #depth 0: outer loop
  111. # [ Slic3r::ExPolygon, Slic3r::ExPolygon... ], #depth 1: inner loop
  112. # ],
  113. # [ # second island
  114. # ...
  115. # ]
  116. # )
  117. my @perimeters = (); # one item per depth; each item
  118. # organize islands using a shortest path search
  119. my @surfaces = @{shortest_path([
  120. map [ $_->contour->[0], $_ ], @{$self->slices},
  121. ])};
  122. $self->perimeters([]);
  123. $self->surfaces([]);
  124. $self->thin_fills([]);
  125. # for each island:
  126. foreach my $surface (@surfaces) {
  127. my @last_offsets = ($surface->expolygon);
  128. # experimental hole compensation (see ArcCompensation in the RepRap wiki)
  129. if (0) {
  130. foreach my $hole ($last_offsets[0]->holes) {
  131. my $circumference = abs($hole->length);
  132. next unless $circumference <= &Slic3r::SMALL_PERIMETER_LENGTH;
  133. # this compensation only works for circular holes, while it would
  134. # overcompensate for hexagons and other shapes having straight edges.
  135. # so we require a minimum number of vertices.
  136. next unless $circumference / @$hole >= scale 3 * $Slic3r::flow->width;
  137. # revert the compensation done in make_surfaces() and get the actual radius
  138. # of the hole
  139. my $radius = ($circumference / PI / 2) - scale $self->perimeter_flow->spacing/2;
  140. my $new_radius = (scale($self->perimeter_flow->width) + sqrt((scale($self->perimeter_flow->width)**2) + (4*($radius**2)))) / 2;
  141. # holes are always turned to contours, so reverse point order before and after
  142. $hole->reverse;
  143. my @offsetted = $hole->offset(+ ($new_radius - $radius));
  144. # skip arc compensation when hole is not round (thus leads to multiple offsets)
  145. @$hole = map Slic3r::Point->new($_), @{ $offsetted[0] } if @offsetted == 1;
  146. $hole->reverse;
  147. }
  148. }
  149. my $distance = scale $self->perimeter_flow->spacing;
  150. my @gaps = ();
  151. # generate perimeters inwards (loop 0 is the external one)
  152. my $loop_number = $Slic3r::Config->perimeters + ($surface->additional_inner_perimeters || 0);
  153. push @perimeters, [[@last_offsets]];
  154. for (my $loop = 1; $loop < $loop_number; $loop++) {
  155. # offsetting a polygon can result in one or many offset polygons
  156. my @new_offsets = ();
  157. foreach my $expolygon (@last_offsets) {
  158. my @offsets = map $_->offset_ex(+0.5*$distance), $expolygon->offset_ex(-1.5*$distance);
  159. push @new_offsets, @offsets;
  160. my $diff = diff_ex(
  161. [ map @$_, $expolygon->offset_ex(-$distance) ],
  162. [ map @$_, @offsets ],
  163. );
  164. push @gaps, grep $_->area >= $gap_area_threshold, @$diff;
  165. }
  166. @last_offsets = @new_offsets;
  167. last if !@last_offsets;
  168. push @{ $perimeters[-1] }, [@last_offsets];
  169. }
  170. # create one more offset to be used as boundary for fill
  171. {
  172. my @fill_boundaries = map $_->offset_ex(-$distance), @last_offsets;
  173. $_->simplify(scale &Slic3r::RESOLUTION) for @fill_boundaries;
  174. push @{ $self->surfaces }, @fill_boundaries;
  175. # detect the small gaps that we need to treat like thin polygons,
  176. # thus generating the skeleton and using it to fill them
  177. push @{ $self->thin_fills },
  178. map $_->medial_axis(scale $self->perimeter_flow->width),
  179. @gaps;
  180. Slic3r::debugf " %d gaps filled\n", scalar @{ $self->thin_fills }
  181. if @{ $self->thin_fills };
  182. }
  183. }
  184. # process one island (original surface) at time
  185. foreach my $island (@perimeters) {
  186. # do holes starting from innermost one
  187. my @holes = ();
  188. my %is_external = ();
  189. my @hole_depths = map [ map $_->holes, @$_ ], @$island;
  190. # organize the outermost hole loops using a shortest path search
  191. @{$hole_depths[0]} = @{shortest_path([
  192. map [ $_->[0], $_ ], @{$hole_depths[0]},
  193. ])};
  194. CYCLE: while (map @$_, @hole_depths) {
  195. shift @hole_depths while !@{$hole_depths[0]};
  196. # take first available hole
  197. push @holes, shift @{$hole_depths[0]};
  198. $is_external{$#holes} = 1;
  199. my $current_depth = 0;
  200. while (1) {
  201. $current_depth++;
  202. # look for the hole containing this one if any
  203. next CYCLE if !$hole_depths[$current_depth];
  204. my $parent_hole;
  205. for (@{$hole_depths[$current_depth]}) {
  206. if ($_->encloses_point($holes[-1]->[0])) {
  207. $parent_hole = $_;
  208. last;
  209. }
  210. }
  211. next CYCLE if !$parent_hole;
  212. # look for other holes contained in such parent
  213. for (@{$hole_depths[$current_depth-1]}) {
  214. if ($parent_hole->encloses_point($_->[0])) {
  215. # we have a sibling, so let's move onto next iteration
  216. next CYCLE;
  217. }
  218. }
  219. push @holes, $parent_hole;
  220. @{$hole_depths[$current_depth]} = grep $_ ne $parent_hole, @{$hole_depths[$current_depth]};
  221. }
  222. }
  223. # do holes, then contours starting from innermost one
  224. $self->_add_perimeter($holes[$_], $is_external{$_} ? EXTR_ROLE_EXTERNAL_PERIMETER : undef)
  225. for reverse 0 .. $#holes;
  226. for my $depth (reverse 0 .. $#$island) {
  227. my $role = $depth == $#$island ? EXTR_ROLE_CONTOUR_INTERNAL_PERIMETER
  228. : $depth == 0 ? EXTR_ROLE_EXTERNAL_PERIMETER
  229. : EXTR_ROLE_PERIMETER;
  230. $self->_add_perimeter($_, $role) for map $_->contour, @{$island->[$depth]};
  231. }
  232. }
  233. # add thin walls as perimeters
  234. {
  235. my @thin_paths = ();
  236. my %properties = (
  237. role => EXTR_ROLE_EXTERNAL_PERIMETER,
  238. flow_spacing => $self->perimeter_flow->spacing,
  239. );
  240. for (@{ $self->thin_walls }) {
  241. push @thin_paths, $_->isa('Slic3r::Polygon')
  242. ? Slic3r::ExtrusionLoop->pack(polygon => $_, %properties)
  243. : Slic3r::ExtrusionPath->pack(polyline => $_, %properties);
  244. }
  245. my $collection = Slic3r::ExtrusionPath::Collection->new(paths => \@thin_paths);
  246. push @{ $self->perimeters }, $collection->shortest_path;
  247. }
  248. }
  249. sub _add_perimeter {
  250. my $self = shift;
  251. my ($polygon, $role) = @_;
  252. return unless $polygon->is_printable($self->perimeter_flow->width);
  253. push @{ $self->perimeters }, Slic3r::ExtrusionLoop->pack(
  254. polygon => $polygon,
  255. role => (abs($polygon->length) <= &Slic3r::SMALL_PERIMETER_LENGTH) ? EXTR_ROLE_SMALLPERIMETER : ($role // EXTR_ROLE_PERIMETER), #/
  256. flow_spacing => $self->perimeter_flow->spacing,
  257. );
  258. }
  259. sub prepare_fill_surfaces {
  260. my $self = shift;
  261. my @surfaces = @{$self->surfaces};
  262. # if no solid layers are requested, turn top/bottom surfaces to internal
  263. # note that this modifies $self->surfaces in place
  264. if ($Slic3r::Config->solid_layers == 0) {
  265. $_->surface_type(S_TYPE_INTERNAL) for grep $_->surface_type != S_TYPE_INTERNAL, @surfaces;
  266. }
  267. # if hollow object is requested, remove internal surfaces
  268. if ($Slic3r::Config->fill_density == 0) {
  269. @surfaces = grep $_->surface_type != S_TYPE_INTERNAL, @surfaces;
  270. }
  271. # remove unprintable regions (they would slow down the infill process and also cause
  272. # some weird failures during bridge neighbor detection)
  273. {
  274. my $distance = scale $self->infill_flow->spacing / 2;
  275. @surfaces = map {
  276. my $surface = $_;
  277. # offset inwards
  278. my @offsets = $surface->expolygon->offset_ex(-$distance);
  279. @offsets = @{union_ex(Math::Clipper::offset([ map @$_, @offsets ], $distance, 100, JT_MITER))};
  280. map Slic3r::Surface->new(
  281. expolygon => $_,
  282. surface_type => $surface->surface_type,
  283. ), @offsets;
  284. } @surfaces;
  285. }
  286. # turn too small internal regions into solid regions
  287. {
  288. my $min_area = scale scale $Slic3r::Config->solid_infill_below_area; # scaling an area requires two calls!
  289. my @small = grep $_->surface_type == S_TYPE_INTERNAL && $_->expolygon->contour->area <= $min_area, @surfaces;
  290. $_->surface_type(S_TYPE_INTERNALSOLID) for @small;
  291. Slic3r::debugf "identified %d small solid surfaces at layer %d\n", scalar(@small), $self->id if @small > 0;
  292. }
  293. $self->fill_surfaces([@surfaces]);
  294. }
  295. # make bridges printable
  296. sub process_bridges {
  297. my $self = shift;
  298. # no bridges are possible if we have no internal surfaces
  299. return if $Slic3r::Config->fill_density == 0;
  300. my @bridges = ();
  301. # a bottom surface on a layer > 0 is either a bridge or a overhang
  302. # or a combination of both; any top surface is a candidate for
  303. # reverse bridge processing
  304. my @solid_surfaces = grep {
  305. ($_->surface_type == S_TYPE_BOTTOM && $self->id > 0) || $_->surface_type == S_TYPE_TOP
  306. } @{$self->fill_surfaces} or return;
  307. my @internal_surfaces = grep { $_->surface_type == S_TYPE_INTERNAL || $_->surface_type == S_TYPE_INTERNALSOLID } @{$self->slices};
  308. SURFACE: foreach my $surface (@solid_surfaces) {
  309. my $expolygon = $surface->expolygon->safety_offset;
  310. my $description = $surface->surface_type == S_TYPE_BOTTOM ? 'bridge/overhang' : 'reverse bridge';
  311. # offset the contour and intersect it with the internal surfaces to discover
  312. # which of them has contact with our bridge
  313. my @supporting_surfaces = ();
  314. my ($contour_offset) = $expolygon->contour->offset(scale $self->flow->spacing * sqrt(2));
  315. foreach my $internal_surface (@internal_surfaces) {
  316. my $intersection = intersection_ex([$contour_offset], [$internal_surface->p]);
  317. if (@$intersection) {
  318. push @supporting_surfaces, $internal_surface;
  319. }
  320. }
  321. if (0) {
  322. require "Slic3r/SVG.pm";
  323. Slic3r::SVG::output(undef, "bridge_surfaces.svg",
  324. green_polygons => [ map $_->p, @supporting_surfaces ],
  325. red_polygons => [ @$expolygon ],
  326. );
  327. }
  328. Slic3r::debugf "Found $description on layer %d with %d support(s)\n",
  329. $self->id, scalar(@supporting_surfaces);
  330. next SURFACE unless @supporting_surfaces;
  331. my $bridge_angle = undef;
  332. if ($surface->surface_type == S_TYPE_BOTTOM) {
  333. # detect optimal bridge angle
  334. my $bridge_over_hole = 0;
  335. my @edges = (); # edges are POLYLINES
  336. foreach my $supporting_surface (@supporting_surfaces) {
  337. my @surface_edges = map $_->clip_with_polygon($contour_offset),
  338. ($supporting_surface->contour, $supporting_surface->holes);
  339. if (@supporting_surfaces == 1 && @surface_edges == 1
  340. && @{$supporting_surface->contour} == @{$surface_edges[0]}) {
  341. $bridge_over_hole = 1;
  342. }
  343. push @edges, grep { @$_ } @surface_edges;
  344. }
  345. Slic3r::debugf " Bridge is supported on %d edge(s)\n", scalar(@edges);
  346. Slic3r::debugf " and covers a hole\n" if $bridge_over_hole;
  347. if (0) {
  348. require "Slic3r/SVG.pm";
  349. Slic3r::SVG::output(undef, "bridge_edges.svg",
  350. polylines => [ map $_->p, @edges ],
  351. );
  352. }
  353. if (@edges == 2) {
  354. my @chords = map Slic3r::Line->new($_->[0], $_->[-1]), @edges;
  355. my @midpoints = map $_->midpoint, @chords;
  356. my $line_between_midpoints = Slic3r::Line->new(@midpoints);
  357. $bridge_angle = Slic3r::Geometry::rad2deg_dir($line_between_midpoints->direction);
  358. } elsif (@edges == 1) {
  359. # TODO: this case includes both U-shaped bridges and plain overhangs;
  360. # we need a trapezoidation algorithm to detect the actual bridged area
  361. # and separate it from the overhang area.
  362. # in the mean time, we're treating as overhangs all cases where
  363. # our supporting edge is a straight line
  364. if (@{$edges[0]} > 2) {
  365. my $line = Slic3r::Line->new($edges[0]->[0], $edges[0]->[-1]);
  366. $bridge_angle = Slic3r::Geometry::rad2deg_dir($line->direction);
  367. }
  368. } elsif (@edges) {
  369. my $center = Slic3r::Geometry::bounding_box_center([ map @$_, @edges ]);
  370. my $x = my $y = 0;
  371. foreach my $point (map @$, @edges) {
  372. my $line = Slic3r::Line->new($center, $point);
  373. my $dir = $line->direction;
  374. my $len = $line->length;
  375. $x += cos($dir) * $len;
  376. $y += sin($dir) * $len;
  377. }
  378. $bridge_angle = Slic3r::Geometry::rad2deg_dir(atan2($y, $x));
  379. }
  380. Slic3r::debugf " Optimal infill angle of bridge on layer %d is %d degrees\n",
  381. $self->id, $bridge_angle if defined $bridge_angle;
  382. }
  383. # now, extend our bridge by taking a portion of supporting surfaces
  384. {
  385. # offset the bridge by the specified amount of mm (minimum 3)
  386. my $bridge_overlap = scale 3;
  387. my ($bridge_offset) = $expolygon->contour->offset($bridge_overlap);
  388. # calculate the new bridge
  389. my $intersection = intersection_ex(
  390. [ @$expolygon, map $_->p, @supporting_surfaces ],
  391. [ $bridge_offset ],
  392. );
  393. push @bridges, map Slic3r::Surface->new(
  394. expolygon => $_,
  395. surface_type => $surface->surface_type,
  396. bridge_angle => $bridge_angle,
  397. ), @$intersection;
  398. }
  399. }
  400. # now we need to merge bridges to avoid overlapping
  401. {
  402. # build a list of unique bridge types
  403. my @surface_groups = Slic3r::Surface->group(@bridges);
  404. # merge bridges of the same type, removing any of the bridges already merged;
  405. # the order of @surface_groups determines the priority between bridges having
  406. # different surface_type or bridge_angle
  407. @bridges = ();
  408. foreach my $surfaces (@surface_groups) {
  409. my $union = union_ex([ map $_->p, @$surfaces ]);
  410. my $diff = diff_ex(
  411. [ map @$_, @$union ],
  412. [ map $_->p, @bridges ],
  413. );
  414. push @bridges, map Slic3r::Surface->new(
  415. expolygon => $_,
  416. surface_type => $surfaces->[0]->surface_type,
  417. bridge_angle => $surfaces->[0]->bridge_angle,
  418. ), @$union;
  419. }
  420. }
  421. # apply bridges to layer
  422. {
  423. my @surfaces = @{$self->fill_surfaces};
  424. @{$self->fill_surfaces} = ();
  425. # intersect layer surfaces with bridges to get actual bridges
  426. foreach my $bridge (@bridges) {
  427. my $actual_bridge = intersection_ex(
  428. [ map $_->p, @surfaces ],
  429. [ $bridge->p ],
  430. );
  431. push @{$self->fill_surfaces}, map Slic3r::Surface->new(
  432. expolygon => $_,
  433. surface_type => $bridge->surface_type,
  434. bridge_angle => $bridge->bridge_angle,
  435. ), @$actual_bridge;
  436. }
  437. # difference between layer surfaces and bridges are the other surfaces
  438. foreach my $group (Slic3r::Surface->group(@surfaces)) {
  439. my $difference = diff_ex(
  440. [ map $_->p, @$group ],
  441. [ map $_->p, @bridges ],
  442. );
  443. push @{$self->fill_surfaces}, map Slic3r::Surface->new(
  444. expolygon => $_,
  445. surface_type => $group->[0]->surface_type), @$difference;
  446. }
  447. }
  448. }
  449. 1;