-
Notifications
You must be signed in to change notification settings - Fork 89
Expand file tree
/
Copy pathContour.java
More file actions
422 lines (371 loc) · 13.3 KB
/
Contour.java
File metadata and controls
422 lines (371 loc) · 13.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
package nodebox.graphics;
import java.awt.*;
import java.awt.geom.GeneralPath;
import java.util.ArrayList;
public class Contour extends AbstractGeometry {
private static final BasicStroke DEFAULT_STROKE = new BasicStroke(1f);
private static final int SEGMENT_ACCURACY = 20;
private ArrayList<Point> points;
private boolean closed;
private transient ArrayList<Float> segmentLengths;
private transient float length = -1;
public Contour() {
points = new ArrayList<Point>();
closed = false;
}
public Contour(Contour other) {
points = new ArrayList<Point>(other.points.size());
for (Point p : other.points) {
points.add(p.clone());
}
closed = other.closed;
}
//// Point operations ////
public int getPointCount() {
return points.size();
}
public java.util.List<Point> getPoints() {
return points;
}
public void addPoint(Point pt) {
points.add(pt.clone());
invalidate();
}
public void addPoint(float x, float y) {
points.add(new Point(x, y));
invalidate();
}
//// Close ////
public boolean isClosed() {
return closed;
}
public void setClosed(boolean closed) {
this.closed = closed;
invalidate();
}
public void close() {
this.closed = true;
invalidate();
}
//// Geometric queries ////
public boolean isEmpty() {
return points.isEmpty();
}
public Rect getBounds() {
if (points.isEmpty()) {
return new Rect();
}
float minX = Float.MAX_VALUE;
float minY = Float.MAX_VALUE;
float maxX = Float.MIN_VALUE;
float maxY = Float.MIN_VALUE;
float px, py;
for (Point p : points) {
px = p.getX();
py = p.getY();
if (px < minX) minX = px;
if (py < minY) minY = py;
if (px > maxX) maxX = px;
if (py > maxY) maxY = py;
}
return new Rect(minX, minY, maxX - minX, maxY - minY);
}
/**
* Invalidates the cache. Querying the contour length or calling makePoints/resample will an up-to-date result.
* <p/>
* Cache invalidation happens automatically when using the Contour methods, such as addPoint/close. You should
* invalidate the cache only after manually changing the point positions.
* <p/>
* Invalidating the cache is a lightweight operation; it doesn't recalculate anything. Only when querying the
* new length will the values be recalculated.
*/
public void invalidate() {
segmentLengths = null;
}
public float updateSegmentLengths() {
java.util.List<Point> points = getPoints();
segmentLengths = new ArrayList<Float>();
float totalLength = 0;
// We cannot form a line or curve with the first point.
// Since the algorithm looks back at previous points, we
// start looking from the first useful point, which is
// the second (index of 1).
for (int pi = 1; pi < points.size(); pi++) {
Point pt = points.get(pi);
if (pt.isLineTo()) {
Point pt0 = points.get(pi - 1);
float length = Path.lineLength(pt0.x, pt0.y, pt.x, pt.y);
segmentLengths.add(length);
totalLength += length;
} else if (pt.isCurveTo()) {
Point pt0 = points.get(pi - 3);
Point c1 = points.get(pi - 2);
Point c2 = points.get(pi - 1);
float length = Path.curveLength(pt0.x, pt0.y,
c1.x, c1.y,
c2.x, c2.y,
pt.x, pt.y, SEGMENT_ACCURACY);
segmentLengths.add(length);
totalLength += length;
}
}
// If the path is closed, add the closing segment.
if (closed && !points.isEmpty()) {
Point pt0 = points.get(points.size() - 1);
Point pt1 = points.get(0);
float length = Path.lineLength(pt0.x, pt0.y, pt1.x, pt1.y);
segmentLengths.add(length);
totalLength += length;
}
this.length = totalLength;
return totalLength;
}
/**
* Calculate the length of the contour. This is not the number of segments, but rather the sum of all segment lengths.
*
* @return the length of the contour
*/
public float getLength() {
if (segmentLengths == null)
updateSegmentLengths();
assert (length != -1);
return length;
}
/**
* Returns coordinates for point at t on the path.
* <p/>
* Gets the length of the path, based on the length
* of each curve and line in the path.
* Determines in what segment t falls.
* Gets the point on that segment.
*
* @param t relative coordinate of the point (between 0.0 and 1.0)
* Results outside of this range are undefined.
* @return coordinates for point at t.
*/
public Point pointAt(float t) {
if (segmentLengths == null)
updateSegmentLengths();
// Check if there is a path.
if (points.isEmpty())
throw new NodeBoxError("The path is empty.");
// If the path has no length, return the position of the first point.
if (length == 0)
return points.get(0).clone();
// Since t is relative, convert it to the absolute length.
float absT = t * length;
// The resT is what remains of t after we traversed all segments.
float resT = t;
// Find the segment that contains t.
int segnum = -1;
for (Float seglength : segmentLengths) {
segnum++;
if (absT <= seglength || segnum == segmentLengths.size() - 1)
break;
absT -= seglength;
resT -= seglength / length;
}
resT /= (segmentLengths.get(segnum) / length);
// Find the point index for the segment.
int pi = pointIndexForSegment(segnum + 1);
Point pt1 = points.get(pi);
// If the path is closed, the point index is set to zero.
// Set the index to the last point to get the one-but-last point for pt0.
if (pi == 0) {
pi = points.size();
}
if (pt1.isLineTo()) {
Point pt0 = points.get(pi - 1);
return Path.linePoint(resT, pt0.x, pt0.y, pt1.x, pt1.y);
} else if (pt1.isCurveTo()) {
Point pt0 = points.get(pi - 3);
Point c1 = points.get(pi - 2);
Point c2 = points.get(pi - 1);
return Path.curvePoint(resT,
pt0.x, pt0.y,
c1.x, c1.y,
c2.x, c2.y,
pt1.x, pt1.y);
} else {
throw new AssertionError("Incorrect point.");
}
}
/**
* Same as pointAt(t).
* <p/>
* This method is here for compatibility with NodeBox 1.
*
* @param t relative coordinate of the point.
* @return coordinates for point at t.
* @see #pointAt(float)
*/
public Point point(float t) {
return pointAt(t);
}
/**
* Calculate the point index for the segment number. Segments lie between points. The first point of the segment
* is returned. The point index will be a valid index, even if the segment number doesn't exist.
*
* @param segnum the segment index
* @return the index of the point.
*/
private int pointIndexForSegment(int segnum) {
int pointIndex = 0;
for (Point pt : points) {
if (pt.isCurveTo() || pt.isLineTo()) {
if (segnum == 0) break;
segnum--;
}
pointIndex++;
}
int pointCount = points.size();
if (pointIndex < pointCount) {
return pointIndex;
} else if (closed) {
return 0;
} else {
return pointCount - 1;
}
}
//// Geometric operations ////
/**
* Make new points along the contours of the existing path.
*
* @param amount the number of points to create.
* @return a list with "amount" points or zero points if the contour is empty.
*/
public Point[] makePoints(int amount) {
// If the contour is empty, pointAt will fail. Return an empty array.
if (points.isEmpty()) return new Point[0];
Point[] points = new Point[amount];
float delta = 1;
if (closed) {
if (amount > 0) {
delta = 1f / amount;
}
} else {
// The delta value is divided by amount - 1, because we also want the last point (t=1.0)
// If I wouldn't use amount - 1, I fall one point short of the end.
// E.g. if amount = 4, I want point at t 0.0, 0.33, 0.66 and 1.0,
// if amount = 2, I want point at t 0.0 and t 1.0
if (amount > 2) {
delta = 1f / (amount - 1f);
}
}
for (int i = 0; i < amount; i++) {
points[i] = pointAt(delta * i);
}
return points;
}
/**
* Make new points along the contours of the existing path.
*
* @param amount the amount of points to distribute.
* @param perContour this parameter was added to comply with the IGeometry interface, but is ignored since
* we're at the contour level.
* @return a list with "amount" points or zero points if the contour is empty.
*/
public Point[] makePoints(int amount, boolean perContour) {
return makePoints(amount);
}
/**
* Generate new geometry with the given amount of points along the shape of the original geometry.
* <p/>
* The length of each segment is not given and will be determined based on the required number of points.
*
* @param amount the number of points to generate.
* @param perContour this parameter is ignored since we're at the contour level.
* @return a new Contour with the given number of points.
*/
public Contour resampleByAmount(int amount, boolean perContour) {
return resampleByAmount(amount);
}
/**
* Generate new geometry with the given amount of points along the shape of the original geometry.
* <p/>
* The length of each segment is not given and will be determined based on the required number of points.
*
* @param amount the number of points to generate.
* @return a new Contour with the given number of points.
*/
public Contour resampleByAmount(int amount) {
Contour c = new Contour();
c.extend(makePoints(amount));
c.closed = closed;
return c;
}
/**
* Generate new geometry with points along the shape of the original geometry, spaced at the given length.
* <p/>
* The number of points is not given and will be determined by the system based on the segment length.
* Note that the last segment may be shorter than the given segment length.
*
* @param segmentLength the maximum length of each resampled segment.
* @return a new Contour with segments of the given length.
*/
public Contour resampleByLength(float segmentLength) {
if (segmentLength <= 0.0000001f) {
throw new IllegalArgumentException("Segment length must be greater than zero.");
}
float contourLength = getLength();
int amount = (int) Math.ceil(contourLength / segmentLength);
if (closed) {
return resampleByAmount(amount);
} else {
return resampleByAmount(amount + 1);
}
}
public void flatten() {
throw new UnsupportedOperationException();
}
public IGeometry flattened() {
throw new UnsupportedOperationException();
}
//// Graphics ////
public void draw(Graphics2D g) {
if (getPointCount() < 2) return;
// Since a contour has no fill or stroke information, draw it in black.
// We save the current color so as not to disrupt the context.
java.awt.Color savedColor = g.getColor();
Stroke savedStroke = g.getStroke();
GeneralPath gp = new GeneralPath(GeneralPath.WIND_EVEN_ODD, getPointCount());
_extendPath(gp);
g.setColor(java.awt.Color.BLACK);
g.setStroke(DEFAULT_STROKE);
g.draw(gp);
g.setColor(savedColor);
g.setStroke(savedStroke);
}
/* package private */
void _extendPath(GeneralPath gp) {
if (points.size() == 0) return;
Point pt = points.get(0);
Point ctrl1, ctrl2;
gp.moveTo(pt.x, pt.y);
int pointCount = getPointCount();
for (int i = 1; i < pointCount; i++) {
pt = points.get(i);
if (pt.isLineTo()) {
gp.lineTo(pt.x, pt.y);
} else if (pt.isCurveTo()) {
ctrl1 = points.get(i - 2);
ctrl2 = points.get(i - 1);
gp.curveTo(ctrl1.x, ctrl1.y, ctrl2.x, ctrl2.y, pt.x, pt.y);
}
}
if (closed)
gp.closePath();
}
public void transform(Transform t) {
t.map(getPoints());
invalidate();
}
//// Conversions ////
public Path toPath() {
return new Path(this);
}
//// Object operations ////
public Contour clone() {
return new Contour(this);
}
}