source: node_modules/d3-geo/src/clip/rejoin.js@ e4c61dd

Last change on this file since e4c61dd was e4c61dd, checked in by istevanoska <ilinastevanoska@…>, 6 months ago

Prototype 1.1

  • Property mode set to 100644
File size: 2.7 KB
Line 
1import pointEqual from "../pointEqual.js";
2import {epsilon} from "../math.js";
3
4function Intersection(point, points, other, entry) {
5 this.x = point;
6 this.z = points;
7 this.o = other; // another intersection
8 this.e = entry; // is an entry?
9 this.v = false; // visited
10 this.n = this.p = null; // next & previous
11}
12
13// A generalized polygon clipping algorithm: given a polygon that has been cut
14// into its visible line segments, and rejoins the segments by interpolating
15// along the clip edge.
16export default function(segments, compareIntersection, startInside, interpolate, stream) {
17 var subject = [],
18 clip = [],
19 i,
20 n;
21
22 segments.forEach(function(segment) {
23 if ((n = segment.length - 1) <= 0) return;
24 var n, p0 = segment[0], p1 = segment[n], x;
25
26 if (pointEqual(p0, p1)) {
27 if (!p0[2] && !p1[2]) {
28 stream.lineStart();
29 for (i = 0; i < n; ++i) stream.point((p0 = segment[i])[0], p0[1]);
30 stream.lineEnd();
31 return;
32 }
33 // handle degenerate cases by moving the point
34 p1[0] += 2 * epsilon;
35 }
36
37 subject.push(x = new Intersection(p0, segment, null, true));
38 clip.push(x.o = new Intersection(p0, null, x, false));
39 subject.push(x = new Intersection(p1, segment, null, false));
40 clip.push(x.o = new Intersection(p1, null, x, true));
41 });
42
43 if (!subject.length) return;
44
45 clip.sort(compareIntersection);
46 link(subject);
47 link(clip);
48
49 for (i = 0, n = clip.length; i < n; ++i) {
50 clip[i].e = startInside = !startInside;
51 }
52
53 var start = subject[0],
54 points,
55 point;
56
57 while (1) {
58 // Find first unvisited intersection.
59 var current = start,
60 isSubject = true;
61 while (current.v) if ((current = current.n) === start) return;
62 points = current.z;
63 stream.lineStart();
64 do {
65 current.v = current.o.v = true;
66 if (current.e) {
67 if (isSubject) {
68 for (i = 0, n = points.length; i < n; ++i) stream.point((point = points[i])[0], point[1]);
69 } else {
70 interpolate(current.x, current.n.x, 1, stream);
71 }
72 current = current.n;
73 } else {
74 if (isSubject) {
75 points = current.p.z;
76 for (i = points.length - 1; i >= 0; --i) stream.point((point = points[i])[0], point[1]);
77 } else {
78 interpolate(current.x, current.p.x, -1, stream);
79 }
80 current = current.p;
81 }
82 current = current.o;
83 points = current.z;
84 isSubject = !isSubject;
85 } while (!current.v);
86 stream.lineEnd();
87 }
88}
89
90function link(array) {
91 if (!(n = array.length)) return;
92 var n,
93 i = 0,
94 a = array[0],
95 b;
96 while (++i < n) {
97 a.n = b = array[i];
98 b.p = a;
99 a = b;
100 }
101 a.n = b = array[0];
102 b.p = a;
103}
Note: See TracBrowser for help on using the repository browser.