Geometry.pm 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723
  1. package Slic3r::Geometry;
  2. use strict;
  3. use warnings;
  4. require Exporter;
  5. our @ISA = qw(Exporter);
  6. our @EXPORT_OK = qw(
  7. PI X Y Z A B X1 Y1 X2 Y2 Z1 Z2 MIN MAX epsilon slope
  8. line_point_belongs_to_segment points_coincide distance_between_points
  9. normalize tan move_points_3D
  10. point_in_polygon point_in_segment segment_in_segment
  11. polyline_lines polygon_lines
  12. point_along_segment polygon_segment_having_point polygon_has_subsegment
  13. deg2rad rad2deg
  14. rotate_points move_points
  15. dot perp
  16. line_intersection bounding_box bounding_box_intersect
  17. angle3points
  18. chained_path chained_path_from collinear scale unscale
  19. rad2deg_dir bounding_box_center line_intersects_any douglas_peucker
  20. polyline_remove_short_segments normal triangle_normal polygon_is_convex
  21. scaled_epsilon bounding_box_3D size_3D size_2D
  22. convex_hull directions_parallel directions_parallel_within
  23. );
  24. use constant PI => 4 * atan2(1, 1);
  25. use constant A => 0;
  26. use constant B => 1;
  27. use constant X => 0;
  28. use constant Y => 1;
  29. use constant Z => 2;
  30. use constant X1 => 0;
  31. use constant Y1 => 1;
  32. use constant X2 => 2;
  33. use constant Y2 => 3;
  34. use constant Z1 => 4;
  35. use constant Z2 => 5;
  36. use constant MIN => 0;
  37. use constant MAX => 1;
  38. our $parallel_degrees_limit = abs(deg2rad(0.1));
  39. sub epsilon () { 1E-4 }
  40. sub scaled_epsilon () { epsilon / &Slic3r::SCALING_FACTOR }
  41. sub scale ($) { $_[0] / &Slic3r::SCALING_FACTOR }
  42. sub unscale ($) { $_[0] * &Slic3r::SCALING_FACTOR }
  43. sub tan {
  44. my ($angle) = @_;
  45. return (sin $angle) / (cos $angle);
  46. }
  47. sub slope {
  48. my ($line) = @_;
  49. return undef if abs($line->[B][X] - $line->[A][X]) < epsilon; # line is vertical
  50. return ($line->[B][Y] - $line->[A][Y]) / ($line->[B][X] - $line->[A][X]);
  51. }
  52. # this subroutine checks whether a given point may belong to a given
  53. # segment given the hypothesis that it belongs to the line containing
  54. # the segment
  55. sub line_point_belongs_to_segment {
  56. my ($point, $segment) = @_;
  57. #printf " checking whether %f,%f may belong to segment %f,%f - %f,%f\n",
  58. # @$point, map @$_, @$segment;
  59. my @segment_extents = (
  60. [ sort { $a <=> $b } map $_->[X], @$segment ],
  61. [ sort { $a <=> $b } map $_->[Y], @$segment ],
  62. );
  63. return 0 if $point->[X] < ($segment_extents[X][0] - epsilon) || $point->[X] > ($segment_extents[X][1] + epsilon);
  64. return 0 if $point->[Y] < ($segment_extents[Y][0] - epsilon) || $point->[Y] > ($segment_extents[Y][1] + epsilon);
  65. return 1;
  66. }
  67. sub points_coincide {
  68. my ($p1, $p2) = @_;
  69. return 1 if abs($p2->[X] - $p1->[X]) < epsilon && abs($p2->[Y] - $p1->[Y]) < epsilon;
  70. return 0;
  71. }
  72. sub distance_between_points {
  73. my ($p1, $p2) = @_;
  74. return sqrt((($p1->[X] - $p2->[X])**2) + ($p1->[Y] - $p2->[Y])**2);
  75. }
  76. # this will check whether a point is in a polygon regardless of polygon orientation
  77. sub point_in_polygon {
  78. my ($point, $polygon) = @_;
  79. my ($x, $y) = @$point;
  80. my $n = @$polygon;
  81. my @x = map $_->[X], @$polygon;
  82. my @y = map $_->[Y], @$polygon;
  83. # Derived from the comp.graphics.algorithms FAQ,
  84. # courtesy of Wm. Randolph Franklin
  85. my ($i, $j);
  86. my $side = 0; # 0 = outside; 1 = inside
  87. for ($i = 0, $j = $n - 1; $i < $n; $j = $i++) {
  88. if (
  89. # If the y is between the (y-) borders...
  90. ($y[$i] <= $y && $y < $y[$j]) || ($y[$j] <= $y && $y < $y[$i])
  91. and
  92. # ...the (x,y) to infinity line crosses the edge
  93. # from the ith point to the jth point...
  94. ($x < ($x[$j] - $x[$i]) * ($y - $y[$i]) / ($y[$j] - $y[$i]) + $x[$i])
  95. ) {
  96. $side = not $side; # Jump the fence
  97. }
  98. }
  99. # if point is not in polygon, let's check whether it belongs to the contour
  100. if (!$side && 0) {
  101. return 1 if polygon_segment_having_point($polygon, $point);
  102. }
  103. return $side;
  104. }
  105. sub point_in_segment {
  106. my ($point, $line) = @_;
  107. my ($x, $y) = @$point;
  108. my $line_p = $line->pp;
  109. my @line_x = sort { $a <=> $b } $line_p->[A][X], $line_p->[B][X];
  110. my @line_y = sort { $a <=> $b } $line_p->[A][Y], $line_p->[B][Y];
  111. # check whether the point is in the segment bounding box
  112. return 0 unless $x >= ($line_x[0] - epsilon) && $x <= ($line_x[1] + epsilon)
  113. && $y >= ($line_y[0] - epsilon) && $y <= ($line_y[1] + epsilon);
  114. # if line is vertical, check whether point's X is the same as the line
  115. if ($line_p->[A][X] == $line_p->[B][X]) {
  116. return abs($x - $line_p->[A][X]) < epsilon ? 1 : 0;
  117. }
  118. # calculate the Y in line at X of the point
  119. my $y3 = $line_p->[A][Y] + ($line_p->[B][Y] - $line_p->[A][Y])
  120. * ($x - $line_p->[A][X]) / ($line_p->[B][X] - $line_p->[A][X]);
  121. return abs($y3 - $y) < epsilon ? 1 : 0;
  122. }
  123. sub segment_in_segment {
  124. my ($needle, $haystack) = @_;
  125. # a segment is contained in another segment if its endpoints are contained
  126. return point_in_segment($needle->[A], $haystack) && point_in_segment($needle->[B], $haystack);
  127. }
  128. sub polyline_lines {
  129. my ($polyline) = @_;
  130. my @points = @$polyline;
  131. return map Slic3r::Line->new(@points[$_, $_+1]), 0 .. $#points-1;
  132. }
  133. sub polygon_lines {
  134. my ($polygon) = @_;
  135. return polyline_lines([ @$polygon, $polygon->[0] ]);
  136. }
  137. # given a segment $p1-$p2, get the point at $distance from $p1 along segment
  138. sub point_along_segment {
  139. my ($p1, $p2, $distance) = @_;
  140. my $point = [ @$p1 ];
  141. my $line_length = sqrt( (($p2->[X] - $p1->[X])**2) + (($p2->[Y] - $p1->[Y])**2) );
  142. for (X, Y) {
  143. if ($p1->[$_] != $p2->[$_]) {
  144. $point->[$_] = $p1->[$_] + ($p2->[$_] - $p1->[$_]) * $distance / $line_length;
  145. }
  146. }
  147. return Slic3r::Point->new(@$point);
  148. }
  149. # given a $polygon, return the (first) segment having $point
  150. sub polygon_segment_having_point {
  151. my ($polygon, $point) = @_;
  152. foreach my $line (@{ $polygon->lines }) {
  153. return $line if point_in_segment($point, $line);
  154. }
  155. return undef;
  156. }
  157. # return true if the given segment is contained in any edge of the polygon
  158. sub polygon_has_subsegment {
  159. my ($polygon, $segment) = @_;
  160. foreach my $line (polygon_lines($polygon)) {
  161. return 1 if segment_in_segment($segment, $line);
  162. }
  163. return 0;
  164. }
  165. # polygon must be simple (non complex) and ccw
  166. sub polygon_is_convex {
  167. my ($points) = @_;
  168. for (my $i = 0; $i <= $#$points; $i++) {
  169. my $angle = angle3points($points->[$i-1], $points->[$i-2], $points->[$i]);
  170. return 0 if $angle < PI;
  171. }
  172. return 1;
  173. }
  174. sub rotate_points {
  175. my ($radians, $center, @points) = @_;
  176. $center //= [0,0];
  177. return map {
  178. [
  179. $center->[X] + cos($radians) * ($_->[X] - $center->[X]) - sin($radians) * ($_->[Y] - $center->[Y]),
  180. $center->[Y] + cos($radians) * ($_->[Y] - $center->[Y]) + sin($radians) * ($_->[X] - $center->[X]),
  181. ]
  182. } @points;
  183. }
  184. sub move_points {
  185. my ($shift, @points) = @_;
  186. return map {
  187. my @p = @$_;
  188. Slic3r::Point->new($shift->[X] + $p[X], $shift->[Y] + $p[Y]);
  189. } @points;
  190. }
  191. sub move_points_3D {
  192. my ($shift, @points) = @_;
  193. return map [
  194. $shift->[X] + $_->[X],
  195. $shift->[Y] + $_->[Y],
  196. $shift->[Z] + $_->[Z],
  197. ], @points;
  198. }
  199. sub normal {
  200. my ($line1, $line2) = @_;
  201. return [
  202. ($line1->[Y] * $line2->[Z]) - ($line1->[Z] * $line2->[Y]),
  203. -($line2->[Z] * $line1->[X]) + ($line2->[X] * $line1->[Z]),
  204. ($line1->[X] * $line2->[Y]) - ($line1->[Y] * $line2->[X]),
  205. ];
  206. }
  207. sub triangle_normal {
  208. my ($v1, $v2, $v3) = @_;
  209. my $u = [ map +($v2->[$_] - $v1->[$_]), (X,Y,Z) ];
  210. my $v = [ map +($v3->[$_] - $v1->[$_]), (X,Y,Z) ];
  211. return normal($u, $v);
  212. }
  213. sub normalize {
  214. my ($line) = @_;
  215. my $len = sqrt( ($line->[X]**2) + ($line->[Y]**2) + ($line->[Z]**2) )
  216. or return [0, 0, 0]; # to avoid illegal division by zero
  217. return [ map $_ / $len, @$line ];
  218. }
  219. # 2D dot product
  220. sub dot {
  221. my ($u, $v) = @_;
  222. return $u->[X] * $v->[X] + $u->[Y] * $v->[Y];
  223. }
  224. # 2D perp product
  225. sub perp {
  226. my ($u, $v) = @_;
  227. return $u->[X] * $v->[Y] - $u->[Y] * $v->[X];
  228. }
  229. sub line_intersects_any {
  230. my ($line, $lines) = @_;
  231. for (@$lines) {
  232. return 1 if line_intersection($line, $_, 1);
  233. }
  234. return 0;
  235. }
  236. sub line_intersection {
  237. my ($line1, $line2, $require_crossing) = @_;
  238. $require_crossing ||= 0;
  239. my $intersection = _line_intersection(map @$_, @$line1, @$line2);
  240. return (ref $intersection && $intersection->[1] == $require_crossing)
  241. ? $intersection->[0]
  242. : undef;
  243. }
  244. sub collinear {
  245. my ($line1, $line2, $require_overlapping) = @_;
  246. my $intersection = _line_intersection(map @$_, @$line1, @$line2);
  247. return 0 unless !ref($intersection)
  248. && ($intersection eq 'parallel collinear'
  249. || ($intersection eq 'parallel vertical' && abs($line1->[A][X] - $line2->[A][X]) < epsilon));
  250. if ($require_overlapping) {
  251. my @box_a = bounding_box([ $line1->[0], $line1->[1] ]);
  252. my @box_b = bounding_box([ $line2->[0], $line2->[1] ]);
  253. return 0 unless bounding_box_intersect( 2, @box_a, @box_b );
  254. }
  255. return 1;
  256. }
  257. sub _line_intersection {
  258. my ( $x0, $y0, $x1, $y1, $x2, $y2, $x3, $y3 ) = @_;
  259. my ($x, $y); # The as-yet-undetermined intersection point.
  260. my $dy10 = $y1 - $y0; # dyPQ, dxPQ are the coordinate differences
  261. my $dx10 = $x1 - $x0; # between the points P and Q.
  262. my $dy32 = $y3 - $y2;
  263. my $dx32 = $x3 - $x2;
  264. my $dy10z = abs( $dy10 ) < epsilon; # Is the difference $dy10 "zero"?
  265. my $dx10z = abs( $dx10 ) < epsilon;
  266. my $dy32z = abs( $dy32 ) < epsilon;
  267. my $dx32z = abs( $dx32 ) < epsilon;
  268. my $dyx10; # The slopes.
  269. my $dyx32;
  270. $dyx10 = $dy10 / $dx10 unless $dx10z;
  271. $dyx32 = $dy32 / $dx32 unless $dx32z;
  272. # Now we know all differences and the slopes;
  273. # we can detect horizontal/vertical special cases.
  274. # E.g., slope = 0 means a horizontal line.
  275. unless ( defined $dyx10 or defined $dyx32 ) {
  276. return "parallel vertical";
  277. }
  278. elsif ( $dy10z and not $dy32z ) { # First line horizontal.
  279. $y = $y0;
  280. $x = $x2 + ( $y - $y2 ) * $dx32 / $dy32;
  281. }
  282. elsif ( not $dy10z and $dy32z ) { # Second line horizontal.
  283. $y = $y2;
  284. $x = $x0 + ( $y - $y0 ) * $dx10 / $dy10;
  285. }
  286. elsif ( $dx10z and not $dx32z ) { # First line vertical.
  287. $x = $x0;
  288. $y = $y2 + $dyx32 * ( $x - $x2 );
  289. }
  290. elsif ( not $dx10z and $dx32z ) { # Second line vertical.
  291. $x = $x2;
  292. $y = $y0 + $dyx10 * ( $x - $x0 );
  293. }
  294. elsif ( abs( $dyx10 - $dyx32 ) < epsilon ) {
  295. # The slopes are suspiciously close to each other.
  296. # Either we have parallel collinear or just parallel lines.
  297. # The bounding box checks have already weeded the cases
  298. # "parallel horizontal" and "parallel vertical" away.
  299. my $ya = $y0 - $dyx10 * $x0;
  300. my $yb = $y2 - $dyx32 * $x2;
  301. return "parallel collinear" if abs( $ya - $yb ) < epsilon;
  302. return "parallel";
  303. }
  304. else {
  305. # None of the special cases matched.
  306. # We have a "honest" line intersection.
  307. $x = ($y2 - $y0 + $dyx10*$x0 - $dyx32*$x2)/($dyx10 - $dyx32);
  308. $y = $y0 + $dyx10 * ($x - $x0);
  309. }
  310. my $h10 = $dx10 ? ($x - $x0) / $dx10 : ($dy10 ? ($y - $y0) / $dy10 : 1);
  311. my $h32 = $dx32 ? ($x - $x2) / $dx32 : ($dy32 ? ($y - $y2) / $dy32 : 1);
  312. return [Slic3r::Point->new($x, $y), $h10 >= 0 && $h10 <= 1 && $h32 >= 0 && $h32 <= 1];
  313. }
  314. # http://paulbourke.net/geometry/lineline2d/
  315. sub _line_intersection2 {
  316. my ($line1, $line2) = @_;
  317. my $denom = ($line2->[B][Y] - $line2->[A][Y]) * ($line1->[B][X] - $line1->[A][X])
  318. - ($line2->[B][X] - $line2->[A][X]) * ($line1->[B][Y] - $line1->[A][Y]);
  319. my $numerA = ($line2->[B][X] - $line2->[A][X]) * ($line1->[A][Y] - $line2->[A][Y])
  320. - ($line2->[B][Y] - $line2->[A][Y]) * ($line1->[A][X] - $line2->[A][X]);
  321. my $numerB = ($line1->[B][X] - $line1->[A][X]) * ($line1->[A][Y] - $line2->[A][Y])
  322. - ($line1->[B][Y] - $line1->[A][Y]) * ($line1->[A][X] - $line2->[A][X]);
  323. # are the lines coincident?
  324. if (abs($numerA) < epsilon && abs($numerB) < epsilon && abs($denom) < epsilon) {
  325. return Slic3r::Point->new(
  326. ($line1->[A][X] + $line1->[B][X]) / 2,
  327. ($line1->[A][Y] + $line1->[B][Y]) / 2,
  328. );
  329. }
  330. # are the lines parallel?
  331. if (abs($denom) < epsilon) {
  332. return undef;
  333. }
  334. # is the intersection along the segments?
  335. my $muA = $numerA / $denom;
  336. my $muB = $numerB / $denom;
  337. if ($muA < 0 || $muA > 1 || $muB < 0 || $muB > 1) {
  338. return undef;
  339. }
  340. return Slic3r::Point->new(
  341. $line1->[A][X] + $muA * ($line1->[B][X] - $line1->[A][X]),
  342. $line1->[A][Y] + $muA * ($line1->[B][Y] - $line1->[A][Y]),
  343. );
  344. }
  345. # 2D
  346. sub bounding_box {
  347. my ($points) = @_;
  348. my @x = map $_->x, @$points;
  349. my @y = map $_->y, @$points; #,,
  350. my @bb = (undef, undef, undef, undef);
  351. for (0..$#x) {
  352. $bb[X1] = $x[$_] if !defined $bb[X1] || $x[$_] < $bb[X1];
  353. $bb[X2] = $x[$_] if !defined $bb[X2] || $x[$_] > $bb[X2];
  354. $bb[Y1] = $y[$_] if !defined $bb[Y1] || $y[$_] < $bb[Y1];
  355. $bb[Y2] = $y[$_] if !defined $bb[Y2] || $y[$_] > $bb[Y2];
  356. }
  357. return @bb[X1,Y1,X2,Y2];
  358. }
  359. sub bounding_box_center {
  360. my ($bounding_box) = @_;
  361. return Slic3r::Point->new(
  362. ($bounding_box->[X2] + $bounding_box->[X1]) / 2,
  363. ($bounding_box->[Y2] + $bounding_box->[Y1]) / 2,
  364. );
  365. }
  366. sub size_2D {
  367. my @bounding_box = bounding_box(@_);
  368. return (
  369. ($bounding_box[X2] - $bounding_box[X1]),
  370. ($bounding_box[Y2] - $bounding_box[Y1]),
  371. );
  372. }
  373. # bounding_box_intersect($d, @a, @b)
  374. # Return true if the given bounding boxes @a and @b intersect
  375. # in $d dimensions. Used by line_intersection().
  376. sub bounding_box_intersect {
  377. my ( $d, @bb ) = @_; # Number of dimensions and box coordinates.
  378. my @aa = splice( @bb, 0, 2 * $d ); # The first box.
  379. # (@bb is the second one.)
  380. # Must intersect in all dimensions.
  381. for ( my $i_min = 0; $i_min < $d; $i_min++ ) {
  382. my $i_max = $i_min + $d; # The index for the maximum.
  383. return 0 if ( $aa[ $i_max ] + epsilon ) < $bb[ $i_min ];
  384. return 0 if ( $bb[ $i_max ] + epsilon ) < $aa[ $i_min ];
  385. }
  386. return 1;
  387. }
  388. # 3D
  389. sub bounding_box_3D {
  390. my ($points) = @_;
  391. my @extents = (map [undef, undef], X,Y,Z);
  392. foreach my $point (@$points) {
  393. for (X,Y,Z) {
  394. $extents[$_][MIN] = $point->[$_] if !defined $extents[$_][MIN] || $point->[$_] < $extents[$_][MIN];
  395. $extents[$_][MAX] = $point->[$_] if !defined $extents[$_][MAX] || $point->[$_] > $extents[$_][MAX];
  396. }
  397. }
  398. return @extents;
  399. }
  400. sub size_3D {
  401. my ($points) = @_;
  402. my @extents = bounding_box_3D($points);
  403. return map $extents[$_][MAX] - $extents[$_][MIN], (X,Y,Z);
  404. }
  405. # this assumes a CCW rotation from $p2 to $p3 around $p1
  406. sub angle3points {
  407. my ($p1, $p2, $p3) = @_;
  408. # p1 is the center
  409. my $angle = atan2($p2->[X] - $p1->[X], $p2->[Y] - $p1->[Y])
  410. - atan2($p3->[X] - $p1->[X], $p3->[Y] - $p1->[Y]);
  411. # we only want to return only positive angles
  412. return $angle <= 0 ? $angle + 2*PI() : $angle;
  413. }
  414. sub polyline_remove_short_segments {
  415. my ($points, $min_length, $isPolygon) = @_;
  416. for (my $i = $isPolygon ? 0 : 1; $i < $#$points; $i++) {
  417. if (distance_between_points($points->[$i-1], $points->[$i]) < $min_length) {
  418. # we can remove $points->[$i]
  419. splice @$points, $i, 1;
  420. $i--;
  421. }
  422. }
  423. }
  424. sub douglas_peucker {
  425. my ($points, $tolerance) = @_;
  426. no warnings "recursion";
  427. my $results = [];
  428. my $dmax = 0;
  429. my $index = 0;
  430. for my $i (1..$#$points) {
  431. my $d = $points->[$i]->distance_to(Slic3r::Line->new($points->[0], $points->[-1]));
  432. if ($d > $dmax) {
  433. $index = $i;
  434. $dmax = $d;
  435. }
  436. }
  437. if ($dmax >= $tolerance) {
  438. my $dp1 = douglas_peucker([ @$points[0..$index] ], $tolerance);
  439. $results = [
  440. @$dp1[0..($#$dp1-1)],
  441. @{douglas_peucker([ @$points[$index..$#$points] ], $tolerance)},
  442. ];
  443. } else {
  444. $results = [ $points->[0], $points->[-1] ];
  445. }
  446. return $results;
  447. }
  448. sub douglas_peucker2 {
  449. my ($points, $tolerance) = @_;
  450. my $anchor = 0;
  451. my $floater = $#$points;
  452. my @stack = ();
  453. my %keep = ();
  454. push @stack, [$anchor, $floater];
  455. while (@stack) {
  456. ($anchor, $floater) = @{pop @stack};
  457. # initialize line segment
  458. my ($anchor_x, $anchor_y, $seg_len);
  459. if (grep $points->[$floater][$_] != $points->[$anchor][$_], X, Y) {
  460. $anchor_x = $points->[$floater][X] - $points->[$anchor][X];
  461. $anchor_y = $points->[$floater][Y] - $points->[$anchor][Y];
  462. $seg_len = sqrt(($anchor_x ** 2) + ($anchor_y ** 2));
  463. # get the unit vector
  464. $anchor_x /= $seg_len;
  465. $anchor_y /= $seg_len;
  466. } else {
  467. $anchor_x = $anchor_y = $seg_len = 0;
  468. }
  469. # inner loop:
  470. my $max_dist = 0;
  471. my $farthest = $anchor + 1;
  472. for my $i (($anchor + 1) .. $floater) {
  473. my $dist_to_seg = 0;
  474. # compare to anchor
  475. my $vecX = $points->[$i][X] - $points->[$anchor][X];
  476. my $vecY = $points->[$i][Y] - $points->[$anchor][Y];
  477. $seg_len = sqrt(($vecX ** 2) + ($vecY ** 2));
  478. # dot product:
  479. my $proj = $vecX * $anchor_x + $vecY * $anchor_y;
  480. if ($proj < 0) {
  481. $dist_to_seg = $seg_len;
  482. } else {
  483. # compare to floater
  484. $vecX = $points->[$i][X] - $points->[$floater][X];
  485. $vecY = $points->[$i][Y] - $points->[$floater][Y];
  486. $seg_len = sqrt(($vecX ** 2) + ($vecY ** 2));
  487. # dot product:
  488. $proj = $vecX * (-$anchor_x) + $vecY * (-$anchor_y);
  489. if ($proj < 0) {
  490. $dist_to_seg = $seg_len
  491. } else { # calculate perpendicular distance to line (pythagorean theorem):
  492. $dist_to_seg = sqrt(abs(($seg_len ** 2) - ($proj ** 2)));
  493. }
  494. if ($max_dist < $dist_to_seg) {
  495. $max_dist = $dist_to_seg;
  496. $farthest = $i;
  497. }
  498. }
  499. }
  500. if ($max_dist <= $tolerance) { # use line segment
  501. $keep{$_} = 1 for $anchor, $floater;
  502. } else {
  503. push @stack, [$anchor, $farthest];
  504. push @stack, [$farthest, $floater];
  505. }
  506. }
  507. return [ map $points->[$_], sort keys %keep ];
  508. }
  509. sub arrange {
  510. my ($total_parts, $partx, $party, $dist, $bb) = @_;
  511. my $linint = sub {
  512. my ($value, $oldmin, $oldmax, $newmin, $newmax) = @_;
  513. return ($value - $oldmin) * ($newmax - $newmin) / ($oldmax - $oldmin) + $newmin;
  514. };
  515. # use actual part size (the largest) plus separation distance (half on each side) in spacing algorithm
  516. $partx += $dist;
  517. $party += $dist;
  518. my ($areax, $areay);
  519. if (defined $bb) {
  520. my $size = $bb->size;
  521. ($areax, $areay) = @$size[X,Y];
  522. } else {
  523. # bogus area size, large enough not to trigger the error below
  524. $areax = $partx * $total_parts;
  525. $areay = $party * $total_parts;
  526. }
  527. # this is how many cells we have available into which to put parts
  528. my $cellw = int(($areax + $dist) / $partx);
  529. my $cellh = int(($areay + $dist) / $party);
  530. die "$total_parts parts won't fit in your print area!\n" if $total_parts > ($cellw * $cellh);
  531. # width and height of space used by cells
  532. my $w = $cellw * $partx;
  533. my $h = $cellh * $party;
  534. # left and right border positions of space used by cells
  535. my $l = ($areax - $w) / 2;
  536. my $r = $l + $w;
  537. # top and bottom border positions
  538. my $t = ($areay - $h) / 2;
  539. my $b = $t + $h;
  540. # list of cells, sorted by distance from center
  541. my @cellsorder;
  542. # work out distance for all cells, sort into list
  543. for my $i (0..$cellw-1) {
  544. for my $j (0..$cellh-1) {
  545. my $cx = $linint->($i + 0.5, 0, $cellw, $l, $r);
  546. my $cy = $linint->($j + 0.5, 0, $cellh, $t, $b);
  547. my $xd = abs(($areax / 2) - $cx);
  548. my $yd = abs(($areay / 2) - $cy);
  549. my $c = {
  550. location => [$cx, $cy],
  551. index => [$i, $j],
  552. distance => $xd * $xd + $yd * $yd - abs(($cellw / 2) - ($i + 0.5)),
  553. };
  554. BINARYINSERTIONSORT: {
  555. my $index = $c->{distance};
  556. my $low = 0;
  557. my $high = @cellsorder;
  558. while ($low < $high) {
  559. my $mid = ($low + (($high - $low) / 2)) | 0;
  560. my $midval = $cellsorder[$mid]->[0];
  561. if ($midval < $index) {
  562. $low = $mid + 1;
  563. } elsif ($midval > $index) {
  564. $high = $mid;
  565. } else {
  566. splice @cellsorder, $mid, 0, [$index, $c];
  567. last BINARYINSERTIONSORT;
  568. }
  569. }
  570. splice @cellsorder, $low, 0, [$index, $c];
  571. }
  572. }
  573. }
  574. # the extents of cells actually used by objects
  575. my ($lx, $ty, $rx, $by) = (0, 0, 0, 0);
  576. # now find cells actually used by objects, map out the extents so we can position correctly
  577. for my $i (1..$total_parts) {
  578. my $c = $cellsorder[$i - 1];
  579. my $cx = $c->[1]->{index}->[0];
  580. my $cy = $c->[1]->{index}->[1];
  581. if ($i == 1) {
  582. $lx = $rx = $cx;
  583. $ty = $by = $cy;
  584. } else {
  585. $rx = $cx if $cx > $rx;
  586. $lx = $cx if $cx < $lx;
  587. $by = $cy if $cy > $by;
  588. $ty = $cy if $cy < $ty;
  589. }
  590. }
  591. # now we actually place objects into cells, positioned such that the left and bottom borders are at 0
  592. my @positions = ();
  593. for (1..$total_parts) {
  594. my $c = shift @cellsorder;
  595. my $cx = $c->[1]->{index}->[0] - $lx;
  596. my $cy = $c->[1]->{index}->[1] - $ty;
  597. push @positions, [$cx * $partx, $cy * $party];
  598. }
  599. if (defined $bb) {
  600. $_->[X] += $bb->x_min for @positions;
  601. $_->[Y] += $bb->y_min for @positions;
  602. }
  603. return @positions;
  604. }
  605. 1;