@immugio/three-math-extensions 0.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/.eslintrc.json ADDED
@@ -0,0 +1,32 @@
1
+ {
2
+ "env": {
3
+ "browser": true,
4
+ "es2020": true
5
+ },
6
+ "extends": [
7
+ "eslint:recommended",
8
+ "plugin:@typescript-eslint/recommended"
9
+ ],
10
+ "parser": "@typescript-eslint/parser",
11
+ "parserOptions": {
12
+ "ecmaVersion": 11,
13
+ "sourceType": "module"
14
+ },
15
+ "plugins": [
16
+ "@typescript-eslint"
17
+ ],
18
+ "rules": {
19
+ "linebreak-style": [
20
+ "error",
21
+ "windows"
22
+ ],
23
+ "quotes": [
24
+ "error",
25
+ "double"
26
+ ],
27
+ "semi": [
28
+ "error",
29
+ "always"
30
+ ]
31
+ }
32
+ }
package/README ADDED
@@ -0,0 +1 @@
1
+ Set of utilities for 2d and 3d line math built on top of threejs
package/cjs/Line2D.js ADDED
@@ -0,0 +1,527 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.Line2D = void 0;
4
+ const three_1 = require("three");
5
+ const Vec2_1 = require("./Vec2");
6
+ class Line2D {
7
+ start;
8
+ end;
9
+ index;
10
+ constructor(start, end, index = 0) {
11
+ this.start = start;
12
+ this.end = end;
13
+ this.index = index;
14
+ }
15
+ static fromCoordinates(x1, y1, x2, y2, index = 0) {
16
+ return new Line2D(new Vec2_1.Vec2(x1, y1), new Vec2_1.Vec2(x2, y2), index);
17
+ }
18
+ static fromPoints(p1, p2, index = 0) {
19
+ return new Line2D(new Vec2_1.Vec2(p1.x, p1.y), new Vec2_1.Vec2(p2.x, p2.y), index);
20
+ }
21
+ static fromPolygon(polygon) {
22
+ if (polygon[0].x === polygon[polygon.length - 1].x && polygon[0].y === polygon[polygon.length - 1].y) {
23
+ polygon = polygon.slice(0, polygon.length - 1);
24
+ }
25
+ return polygon.map((p, i) => {
26
+ const next = polygon[(i + 1) % polygon.length];
27
+ return Line2D.fromPoints(p, next, i);
28
+ });
29
+ }
30
+ static fromLength(length) {
31
+ return Line2D.fromCoordinates(-length / 2, 0, length / 2, 0);
32
+ }
33
+ get center() {
34
+ return new Vec2_1.Vec2((this.start.x + this.end.x) / 2, (this.start.y + this.end.y) / 2);
35
+ }
36
+ /**
37
+ * Set the center of the line to the provided point. Length and direction remain unchanged.
38
+ * Modifies this line.
39
+ * @param value
40
+ */
41
+ set center(value) {
42
+ const current = this.center;
43
+ const diffX = current.x - value.x;
44
+ const diffY = current.y - value.y;
45
+ this.start.x -= diffX;
46
+ this.start.y -= diffY;
47
+ this.end.x -= diffX;
48
+ this.end.y -= diffY;
49
+ }
50
+ /**
51
+ * Set the center of the line to the provided point. Length and direction remain unchanged.
52
+ * Modifies this line.
53
+ * @param value
54
+ */
55
+ setCenter(value) {
56
+ this.center = value;
57
+ return this;
58
+ }
59
+ /*
60
+ * Extends or reduces the line by the given length while keeping the center of the line constant.
61
+ * Modifies this line.
62
+ */
63
+ resize(amount) {
64
+ this.moveStartPoint(amount / 2);
65
+ this.moveEndPoint(amount / 2);
66
+ return this;
67
+ }
68
+ /*
69
+ * Moves start point on the line by the given amount. Plus values move the point further away from the center.
70
+ * Modifies this line.
71
+ */
72
+ moveStartPoint(amount) {
73
+ const p1 = this.movePointOnThisLine(this.start, amount);
74
+ this.start.copy(p1);
75
+ return this;
76
+ }
77
+ /**
78
+ * Moves end point on the line by the given amount. Plus values move the point further away from the center.
79
+ * Modifies this line.
80
+ */
81
+ moveEndPoint(amount) {
82
+ const p2 = this.movePointOnThisLine(this.end, amount);
83
+ this.end.copy(p2);
84
+ return this;
85
+ }
86
+ movePointOnThisLine(point, amount) {
87
+ const vec = new three_1.Vector2(this.center.x - point.x, this.center.y - point.y);
88
+ const length = vec.length();
89
+ vec.normalize().multiplyScalar(length + amount);
90
+ return new Vec2_1.Vec2(this.center.x - vec.x, this.center.y - vec.y);
91
+ }
92
+ /**
93
+ * Set the length of this line. Center and direction remain unchanged.
94
+ * Modifies this line.
95
+ * @param l
96
+ */
97
+ set length(l) {
98
+ const length = this.length;
99
+ this.resize(l - length);
100
+ }
101
+ get length() {
102
+ return this.start.distanceTo(this.end);
103
+ }
104
+ /**
105
+ * Returns the start and end points of the line as an array.
106
+ * Endpoints are not cloned.
107
+ */
108
+ get endpoints() {
109
+ return [this.start, this.end];
110
+ }
111
+ /**
112
+ * Returns the direction of this line.
113
+ */
114
+ get direction() {
115
+ return this.end.clone().sub(this.start).normalize();
116
+ }
117
+ /**
118
+ * Inverts the direction of the line.
119
+ * Modifies this line.
120
+ */
121
+ flip() {
122
+ const temp = this.start.clone();
123
+ this.start.copy(this.end);
124
+ this.end.copy(temp);
125
+ return this;
126
+ }
127
+ /**
128
+ * Rotates the line around the center by the given angle in radians.
129
+ * Modifies this line.
130
+ * @param radians Positive values rotate counter-clockwise.
131
+ * @param center
132
+ */
133
+ rotate(radians, center = this.center) {
134
+ this.start.rotateAround(center, radians);
135
+ this.end.rotateAround(center, radians);
136
+ return this;
137
+ }
138
+ /**
139
+ * Move the line by the given vector.
140
+ * Modifies this line.
141
+ */
142
+ translate(value) {
143
+ this.start.x += value.x;
144
+ this.start.y += value.y;
145
+ this.end.x += value.x;
146
+ this.end.y += value.y;
147
+ return this;
148
+ }
149
+ /**
150
+ * Move the line to its left by the given amount.
151
+ * Modifies this line.
152
+ */
153
+ translateLeft(amount) {
154
+ const translation = this.direction.rotateAround(new Vec2_1.Vec2(), -Math.PI / 2).multiplyScalar(amount);
155
+ return this.translate(translation);
156
+ }
157
+ /**
158
+ * Move the line to its right by the given amount.
159
+ * Modifies this line.
160
+ */
161
+ translateRight(amount) {
162
+ const translation = this.direction.rotateAround(new Vec2_1.Vec2(), Math.PI / 2).multiplyScalar(amount);
163
+ return this.translate(translation);
164
+ }
165
+ /**
166
+ * Returns true when the point is actually inside the (finite) line segment.
167
+ * https://jsfiddle.net/c06zdxtL/2/
168
+ * https://stackoverflow.com/questions/6865832/detecting-if-a-point-is-of-a-line-segment/6877674
169
+ * @param point: Point2
170
+ */
171
+ isPointOnLineSection(point) {
172
+ if (!this.isPointOnInfiniteLine(point)) {
173
+ return false;
174
+ }
175
+ return this.isPointBesideLineSection(point);
176
+ }
177
+ /**
178
+ * Returns true when the point is beside the line **segment** and within the maxDistance.
179
+ * @param point
180
+ * @param maxDistance
181
+ */
182
+ isPointCloseToAndBesideLineSection(point, maxDistance) {
183
+ const distance = this.distanceToPointOnInfiniteLine(point);
184
+ return distance <= maxDistance && this.isPointBesideLineSection(point);
185
+ }
186
+ /**
187
+ * Returns true when the point is beside the line **segment**
188
+ * @param point
189
+ */
190
+ isPointBesideLineSection(point) {
191
+ const l2 = (((this.end.x - this.start.x) * (this.end.x - this.start.x)) + ((this.end.y - this.start.y) * (this.end.y - this.start.y)));
192
+ if (l2 == 0)
193
+ return false;
194
+ const r = (((point.x - this.start.x) * (this.end.x - this.start.x)) + ((point.y - this.start.y) * (this.end.y - this.start.y))) / l2;
195
+ return (0 <= r) && (r <= 1);
196
+ }
197
+ /**
198
+ * Returns true when the point is on the **infinite** line.
199
+ * @param point
200
+ */
201
+ isPointOnInfiniteLine(point) {
202
+ return (point.y - this.start.y) * (this.end.x - this.start.x) === (this.end.y - this.start.y) * (point.x - this.start.x);
203
+ }
204
+ /**
205
+ * Returns true if other line is collinear and overlaps or at least touching this line.
206
+ * @param other
207
+ */
208
+ isCollinearWithTouchOrOverlap(other) {
209
+ if (!this.isPointOnInfiniteLine(other.start) || !this.isPointOnInfiniteLine(other.end)) {
210
+ return false;
211
+ }
212
+ return this.isPointOnLineSection(other.start) || this.isPointOnLineSection(other.end) ||
213
+ other.isPointOnLineSection(this.start) || other.isPointOnLineSection(this.end);
214
+ }
215
+ /**
216
+ * Returns true if there is any overlap between this line and the @other line section.
217
+ */
218
+ overlaps(other) {
219
+ if (!this.isCollinearWithTouchOrOverlap(other)) {
220
+ return false;
221
+ }
222
+ if (this.start.equals(other.start) && this.end.equals(other.end)) {
223
+ return true;
224
+ }
225
+ return !this.start.equals(other.end) && !this.end.equals(other.start);
226
+ }
227
+ /**
228
+ * Logical AND of this and the other line section.
229
+ * @param other
230
+ */
231
+ getOverlap(other) {
232
+ if (!this.overlaps(other)) {
233
+ return null;
234
+ }
235
+ if (this.equals(other)) {
236
+ return this.clone();
237
+ }
238
+ const points = [
239
+ [this.start, this.end].filter(thisPoint => other.isPointOnLineSection(thisPoint)),
240
+ [other.start, other.end].filter(otherPoint => this.isPointOnLineSection(otherPoint))
241
+ ].flat();
242
+ if (points.length !== 2) {
243
+ return null;
244
+ }
245
+ const overlap = Line2D.fromPoints(points[0], points[1]);
246
+ if (overlap.direction.manhattanDistanceTo(this.direction) > Number.EPSILON) {
247
+ overlap.flip();
248
+ }
249
+ return overlap;
250
+ }
251
+ /**
252
+ * Joins a copy of @line with the @other line.
253
+ * Other must be parallel to this line.
254
+ * Returns null if there is no overlap
255
+ * Clones the line, does not modify.
256
+ * @param line
257
+ * @param other
258
+ */
259
+ static joinLine(line, other) {
260
+ if (!line.isCollinearWithTouchOrOverlap(other)) {
261
+ return null;
262
+ }
263
+ const p1 = !line.isPointOnLineSection(other.start) ? other.start : line.start;
264
+ const p2 = !line.isPointOnLineSection(other.end) ? other.end : line.end;
265
+ return new Line2D(p1.clone(), p2.clone(), line.index);
266
+ }
267
+ /**
268
+ * Joins provided lines into several joined lines.
269
+ * Lines must be parallel for joining.
270
+ * Clone the lines, does not modify.
271
+ * @param lines
272
+ */
273
+ static joinLines(lines) {
274
+ if (lines.length < 2) {
275
+ return lines.map(x => x.clone());
276
+ }
277
+ const toProcess = lines.slice();
278
+ const result = [];
279
+ while (toProcess.length > 0) {
280
+ const current = toProcess.pop();
281
+ let joined = false;
282
+ for (let i = 0; i < result.length; i++) {
283
+ const other = result[i];
284
+ const joinedLine = Line2D.joinLine(current, other);
285
+ if (joinedLine) {
286
+ result[i] = joinedLine;
287
+ joined = true;
288
+ break;
289
+ }
290
+ }
291
+ if (!joined) {
292
+ result.push(current.clone());
293
+ }
294
+ }
295
+ return result;
296
+ }
297
+ /**
298
+ * Divides the Line3D into a number of segments of the given length.
299
+ * Clone the line, does not modify.
300
+ * @param maxSegmentLength number
301
+ */
302
+ chunk(maxSegmentLength) {
303
+ const source = this.clone();
304
+ const result = [];
305
+ while (source.length > maxSegmentLength) {
306
+ const chunk = source.clone();
307
+ chunk.moveEndPoint(-(chunk.length - maxSegmentLength));
308
+ result.push(chunk);
309
+ source.start = chunk.end.clone();
310
+ }
311
+ result.push(source);
312
+ return result;
313
+ }
314
+ /**
315
+ * Returns the closest point parameter on the **infinite** line to the given point.
316
+ * @param point
317
+ */
318
+ closestPointToPointParameterOnInfiniteLine(point) {
319
+ const startP = new Vec2_1.Vec2().subVectors(point, this.start);
320
+ const startEnd = new Vec2_1.Vec2().subVectors(this.end, this.start);
321
+ const startEnd2 = startEnd.dot(startEnd);
322
+ const startEnd_startP = startEnd.dot(startP);
323
+ return startEnd_startP / startEnd2;
324
+ }
325
+ /**
326
+ * Returns the closest point on the **infinite** line to the given point.
327
+ * @param point
328
+ */
329
+ closestPointOnInfiniteLine(point) {
330
+ const t = this.closestPointToPointParameterOnInfiniteLine(point);
331
+ return new Vec2_1.Vec2().subVectors(this.end, this.start).multiplyScalar(t).add(this.start);
332
+ }
333
+ /**
334
+ * Returns the closest point on the line **section** to the given point.
335
+ * @param point
336
+ */
337
+ closestPointOnLine(point) {
338
+ const closestPoint = this.closestPointOnInfiniteLine(point);
339
+ if (this.isPointOnLineSection(closestPoint)) {
340
+ return closestPoint;
341
+ }
342
+ return closestPoint.distanceTo(this.start) < closestPoint.distanceTo(this.end) ? this.start : this.end;
343
+ }
344
+ /**
345
+ * Returns the distance between the **infinite** line and the point.
346
+ * @param point
347
+ */
348
+ distanceToPointOnInfiniteLine(point) {
349
+ const l2 = (((this.end.x - this.start.x) * (this.end.x - this.start.x)) + ((this.end.y - this.start.y) * (this.end.y - this.start.y)));
350
+ if (l2 == 0)
351
+ return Infinity;
352
+ const s = (((this.start.y - point.y) * (this.end.x - this.start.x)) - ((this.start.x - point.x) * (this.end.y - this.start.y))) / l2;
353
+ return Math.abs(s) * Math.sqrt(l2);
354
+ }
355
+ /**
356
+ * Returns lines that are the result of clipping @source line by the @clips.
357
+ * Clips must be parallel to this line.
358
+ * Clones the line, does not modify this.
359
+ * @param source
360
+ * @param clips
361
+ */
362
+ static clipLines(source, clips) {
363
+ if (!clips || clips.length === 0)
364
+ return [source];
365
+ clips = clips.map(c => {
366
+ const copy = c.clone();
367
+ if (copy.direction.manhattanDistanceTo(source.direction) > Number.EPSILON) {
368
+ copy.flip();
369
+ }
370
+ return copy;
371
+ });
372
+ const free = [];
373
+ const sources = [source];
374
+ while (sources.length > 0) {
375
+ let isFree = true;
376
+ const tested = sources.pop();
377
+ for (const cover of clips) {
378
+ if (tested.overlaps(cover)) {
379
+ isFree = false;
380
+ const subtracted = this.subtractSingle(tested, cover);
381
+ sources.push(...subtracted);
382
+ break;
383
+ }
384
+ }
385
+ if (isFree)
386
+ free.push(tested);
387
+ }
388
+ return this.order(source, free);
389
+ }
390
+ /**
391
+ * Returns the original line section split into two parts, if the line **sections** overlap, otherwise null
392
+ */
393
+ splitAtIntersection(other, tolerance = 0) {
394
+ const intersection = this.intersect(other);
395
+ if (intersection) {
396
+ if (this.isPointCloseToAndBesideLineSection(intersection, tolerance) && other.isPointCloseToAndBesideLineSection(intersection, tolerance)) {
397
+ return [
398
+ Line2D.fromPoints(this.start, intersection),
399
+ Line2D.fromPoints(intersection, this.end)
400
+ ];
401
+ }
402
+ }
403
+ return null;
404
+ }
405
+ /**
406
+ * If lines **sections** overlap, returns the original line section split into two parts, sorted by length
407
+ * Else, if the **infinite** lines intersect, returns a new line extended to the intersection point
408
+ * Otherwise, null if the lines are parallel and do not intersect
409
+ */
410
+ splitAtOrExtendToIntersection(other) {
411
+ const intersection = this.intersect(other);
412
+ if (intersection) {
413
+ return [
414
+ Line2D.fromPoints(this.start, intersection),
415
+ Line2D.fromPoints(intersection, this.end)
416
+ ].filter(x => x.length > Number.EPSILON).sort((a, b) => a.length - b.length);
417
+ }
418
+ return null;
419
+ }
420
+ static order(source, lines) {
421
+ if (source.start.x < source.end.x) {
422
+ lines.sort((a, b) => a.start.x - b.start.x);
423
+ }
424
+ else if (source.start.x > source.end.x) {
425
+ lines.sort((a, b) => b.start.x - a.start.x);
426
+ }
427
+ if (source.start.y < source.end.y) {
428
+ lines.sort((a, b) => a.start.y - b.start.y);
429
+ }
430
+ else if (source.start.y > source.end.y) {
431
+ lines.sort((a, b) => b.start.y - a.start.y);
432
+ }
433
+ return lines;
434
+ }
435
+ static subtractSingle(source, cover) {
436
+ const left = source.clone();
437
+ left.end.copy(cover.start);
438
+ const right = source.clone();
439
+ right.start.copy(cover.end);
440
+ return [left, right].filter(x => x.length > 1 && x.direction.manhattanDistanceTo(source.direction) < Number.EPSILON);
441
+ }
442
+ /**
443
+ * If other line is not contained within this line, the excess is trimmed.
444
+ * Does not create a copy. Provided line is modified.
445
+ * @param lineToTrim
446
+ */
447
+ trimExcess(lineToTrim) {
448
+ if (!this.isCollinearWithTouchOrOverlap(lineToTrim)) {
449
+ return;
450
+ }
451
+ if (!this.isPointOnLineSection(lineToTrim.start)) {
452
+ const closest = this.closestPointOnLine(lineToTrim.start);
453
+ lineToTrim.start.copy(closest);
454
+ }
455
+ if (!this.isPointOnLineSection(lineToTrim.end)) {
456
+ const closest = this.closestPointOnLine(lineToTrim.end);
457
+ lineToTrim.end.copy(closest);
458
+ }
459
+ }
460
+ /**
461
+ * If other line is shorter than this, endpoints are moved to extend other
462
+ * Does not create a copy. Provided line is modified.
463
+ * @param lineToExtend
464
+ * @param tolerance
465
+ */
466
+ extendToEnds(lineToExtend, tolerance) {
467
+ if (!this.isCollinearWithTouchOrOverlap(lineToExtend)) {
468
+ console.log("Can't clip, lines that are not collinear with touch or overlap");
469
+ return;
470
+ }
471
+ if (this.start.distanceTo(lineToExtend.start) <= tolerance) {
472
+ lineToExtend.start.copy(this.start);
473
+ }
474
+ if (this.end.distanceTo(lineToExtend.end) <= tolerance) {
475
+ lineToExtend.end.copy(this.end);
476
+ }
477
+ }
478
+ /**
479
+ * Returns the intersection point of two lines. The lines are assumed to be infinite.
480
+ */
481
+ intersect(other) {
482
+ // Check if none of the lines are of length 0
483
+ if ((this.start.x === this.end.x && this.start.y === this.end.y) || (other.start.x === other.end.x && other.start.y === other.end.y)) {
484
+ return null;
485
+ }
486
+ const denominator = ((other.end.y - other.start.y) * (this.end.x - this.start.x) - (other.end.x - other.start.x) * (this.end.y - this.start.y));
487
+ // Lines are parallel
488
+ if (denominator === 0) {
489
+ return null;
490
+ }
491
+ const ua = ((other.end.x - other.start.x) * (this.start.y - other.start.y) - (other.end.y - other.start.y) * (this.start.x - other.start.x)) / denominator;
492
+ // Return an object with the x and y coordinates of the intersection
493
+ const x = this.start.x + ua * (this.end.x - this.start.x);
494
+ const y = this.start.y + ua * (this.end.y - this.start.y);
495
+ return new Vec2_1.Vec2(x, y);
496
+ }
497
+ /**
498
+ * Check that the infinite lines intersect and that they are in the specified angle to each other
499
+ * @param other Line
500
+ * @param expectedAngleInRads number
501
+ */
502
+ hasIntersectionWithAngle(other, expectedAngleInRads) {
503
+ const angle = this.direction.angle();
504
+ const otherAngle = other.direction.angle();
505
+ const actualAngle = Math.abs(angle - otherAngle);
506
+ if (Math.abs(actualAngle - expectedAngleInRads) < Number.EPSILON) {
507
+ const intersection = this.intersect(other);
508
+ if (intersection && this.isPointOnLineSection(intersection) && other.isPointOnLineSection(intersection)) {
509
+ return intersection;
510
+ }
511
+ }
512
+ return null;
513
+ }
514
+ /**
515
+ * Deep clone of this line
516
+ */
517
+ clone() {
518
+ return new Line2D(this.start.clone(), this.end.clone(), this.index);
519
+ }
520
+ toString() {
521
+ return `Line(${this.start.x}, ${this.start.y}, ${this.end.x}, ${this.end.y})`;
522
+ }
523
+ equals(other) {
524
+ return !!other && this.start.equals(other.start) && this.end.equals(other.end);
525
+ }
526
+ }
527
+ exports.Line2D = Line2D;