-
Notifications
You must be signed in to change notification settings - Fork 22
/
utils.ts
445 lines (387 loc) · 10.2 KB
/
utils.ts
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
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
import {
BBox,
Body,
BodyGroup,
BodyOptions,
BodyType,
InTest,
PotentialVector,
SATPolygon,
SATTest,
Vector,
} from "./model";
import {
Response,
Vector as SATVector,
testCircleCircle,
testCirclePolygon,
testPolygonCircle,
testPolygonPolygon,
} from "sat";
import {
circleInCircle,
circleInPolygon,
polygonInCircle,
polygonInPolygon,
} from "./intersect";
import { forEach, map } from "./optimized";
import { Point as DecompPoint } from "poly-decomp-es";
import { Polygon } from "./bodies/polygon";
/* helpers for faster getSATTest() and checkAInB() */
const testMap = {
satCircleCircle: testCircleCircle,
satCirclePolygon: testCirclePolygon,
satPolygonCircle: testPolygonCircle,
satPolygonPolygon: testPolygonPolygon,
inCircleCircle: circleInCircle,
inCirclePolygon: circleInPolygon,
inPolygonCircle: polygonInCircle,
inPolygonPolygon: polygonInPolygon,
};
function createArray<T = SATTest | InTest>(
bodyType: BodyType.Circle | BodyType.Polygon,
testType: "sat" | "in",
): T[] {
const arrayResult: T[] = [];
const bodyGroups = Object.values(BodyGroup).filter(
(value) => typeof value === "number",
);
forEach(bodyGroups, (bodyGroup: BodyGroup) => {
arrayResult[bodyGroup] = (
bodyGroup === BodyGroup.Circle
? testMap[`${testType}${bodyType}Circle`]
: testMap[`${testType}${bodyType}Polygon`]
) as T;
});
return arrayResult;
}
const circleSATFunctions = createArray<SATTest>(BodyType.Circle, "sat");
const circleInFunctions = createArray<InTest>(BodyType.Circle, "in");
const polygonSATFunctions = createArray<SATTest>(BodyType.Polygon, "sat");
const polygonInFunctions = createArray<InTest>(BodyType.Polygon, "in");
export const DEG2RAD = Math.PI / 180;
export const RAD2DEG = 180 / Math.PI;
/**
* convert from degrees to radians
*/
export function deg2rad(degrees: number) {
return degrees * DEG2RAD;
}
/**
* convert from radians to degrees
*/
export function rad2deg(radians: number) {
return radians * RAD2DEG;
}
/**
* creates ellipse-shaped polygon based on params
*/
export function createEllipse(
radiusX: number,
radiusY: number = radiusX,
step = 1,
): SATVector[] {
const steps: number = Math.PI * Math.hypot(radiusX, radiusY) * 2;
const length: number = Math.max(8, Math.ceil(steps / Math.max(1, step)));
const ellipse: SATVector[] = [];
for (let index = 0; index < length; index++) {
const value: number = (index / length) * 2 * Math.PI;
const x: number = Math.cos(value) * radiusX;
const y: number = Math.sin(value) * radiusY;
ellipse.push(new SATVector(x, y));
}
return ellipse;
}
/**
* creates box shaped polygon points
*/
export function createBox(width: number, height: number): SATVector[] {
return [
new SATVector(0, 0),
new SATVector(width, 0),
new SATVector(width, height),
new SATVector(0, height),
];
}
/**
* ensure SATVector type point result
*/
export function ensureVectorPoint(point: PotentialVector = {}): SATVector {
return point instanceof SATVector
? point
: new SATVector(point.x || 0, point.y || 0);
}
/**
* ensure Vector points (for polygon) in counter-clockwise order
*/
export function ensurePolygonPoints(
points: PotentialVector[] = [],
): SATVector[] {
const polygonPoints: SATVector[] = map(points, ensureVectorPoint);
return clockwise(polygonPoints) ? polygonPoints.reverse() : polygonPoints;
}
/**
* get distance between two Vector points
*/
export function distance(bodyA: Vector, bodyB: Vector): number {
const xDiff = bodyA.x - bodyB.x;
const yDiff = bodyA.y - bodyB.y;
return Math.hypot(xDiff, yDiff);
}
/**
* check [is clockwise] direction of polygon
*/
export function clockwise(points: Vector[]): boolean {
const length = points.length;
let sum = 0;
forEach(points, (v1, index) => {
const v2 = points[(index + 1) % length];
sum += (v2.x - v1.x) * (v2.y + v1.y);
});
return sum > 0;
}
/**
* used for all types of bodies in constructor
*/
export function extendBody(body: Body, options: BodyOptions = {}): void {
body.isStatic = !!options.isStatic;
body.isTrigger = !!options.isTrigger;
body.padding = options.padding || 0;
body.group = options.group ?? 0x7fffffff;
if (body.typeGroup !== BodyGroup.Circle && options.isCentered) {
body.isCentered = true;
}
if (options.angle) {
body.setAngle(options.angle);
}
}
/**
* check if body moved outside of its padding
*/
export function bodyMoved(body: Body): boolean {
const { bbox, minX, minY, maxX, maxY } = body;
return (
bbox.minX < minX || bbox.minY < minY || bbox.maxX > maxX || bbox.maxY > maxY
);
}
/**
* returns true if two boxes not intersect
*/
export function notIntersectAABB(bodyA: BBox, bodyB: BBox): boolean {
return (
bodyB.minX > bodyA.maxX ||
bodyB.minY > bodyA.maxY ||
bodyB.maxX < bodyA.minX ||
bodyB.maxY < bodyA.minY
);
}
/**
* checks if two boxes intersect
*/
export function intersectAABB(bodyA: BBox, bodyB: BBox): boolean {
return !notIntersectAABB(bodyA, bodyB);
}
/**
* checks if two bodies can interact (for collision filtering)
*
* @param bodyA
* @param bodyB
*/
export function canInteract(
{ group: groupA }: Body,
{ group: groupB }: Body,
): boolean {
return (
// most common case
groupA === groupB ||
// otherwise do some binary magick
(((groupA >> 16) & (groupB & 0xffff)) !== 0 &&
((groupB >> 16) & (groupA & 0xffff)) !== 0)
);
}
/**
* checks if body a is in body b
*/
export function checkAInB(bodyA: Body, bodyB: Body): boolean {
const check =
bodyA.typeGroup === BodyGroup.Circle
? circleInFunctions
: polygonInFunctions;
return check[bodyB.typeGroup](bodyA, bodyB);
}
/**
* clone sat vector points array into vector points array
*/
export function clonePointsArray(points: SATVector[]): Vector[] {
return map(points, ({ x, y }: Vector) => ({ x, y }));
}
/**
* change format from SAT.js to poly-decomp
*
* @param position
*/
export function mapVectorToArray(
{ x, y }: Vector = { x: 0, y: 0 },
): DecompPoint {
return [x, y];
}
/**
* change format from poly-decomp to SAT.js
*
* @param positionAsArray
*/
export function mapArrayToVector([x, y]: DecompPoint = [0, 0]): Vector {
return { x, y };
}
/**
* given 2 bodies calculate vector of bounce assuming equal mass and they are circles
*/
export function getBounceDirection(body: Vector, collider: Vector): SATVector {
const v2 = new SATVector(collider.x - body.x, collider.y - body.y);
const v1 = new SATVector(body.x - collider.x, body.y - collider.y);
const len = v1.dot(v2.normalize()) * 2;
return new SATVector(v2.x * len - v1.x, v2.y * len - v1.y).normalize();
}
/**
* returns correct sat.js testing function based on body types
*/
export function getSATTest(bodyA: Body, bodyB: Body): SATTest {
const check =
bodyA.typeGroup === BodyGroup.Circle
? circleSATFunctions
: polygonSATFunctions;
return check[bodyB.typeGroup];
}
/**
* draws dashed line on canvas context
*/
export function dashLineTo(
context: CanvasRenderingContext2D,
fromX: number,
fromY: number,
toX: number,
toY: number,
dash = 2,
gap = 4,
): void {
const xDiff = toX - fromX;
const yDiff = toY - fromY;
const arc = Math.atan2(yDiff, xDiff);
const offsetX = Math.cos(arc);
const offsetY = Math.sin(arc);
let posX = fromX;
let posY = fromY;
let dist = Math.hypot(xDiff, yDiff);
while (dist > 0) {
const step = Math.min(dist, dash);
context.moveTo(posX, posY);
context.lineTo(posX + offsetX * step, posY + offsetY * step);
posX += offsetX * (dash + gap);
posY += offsetY * (dash + gap);
dist -= dash + gap;
}
}
/**
* draw polygon
*
* @param context
* @param polygon
* @param isTrigger
*/
export function drawPolygon(
context: CanvasRenderingContext2D,
{
pos,
calcPoints,
}: Pick<Polygon | SATPolygon, "calcPoints"> & { pos: Vector },
isTrigger = false,
): void {
const lastPoint = calcPoints[calcPoints.length - 1];
const fromX = pos.x + lastPoint.x;
const fromY = pos.y + lastPoint.y;
if (calcPoints.length === 1) {
context.arc(fromX, fromY, 1, 0, Math.PI * 2);
} else {
context.moveTo(fromX, fromY);
}
forEach(calcPoints, (point, index) => {
const toX = pos.x + point.x;
const toY = pos.y + point.y;
if (isTrigger) {
const prev = calcPoints[index - 1] || lastPoint;
dashLineTo(context, pos.x + prev.x, pos.y + prev.y, toX, toY);
} else {
context.lineTo(toX, toY);
}
});
}
/**
* draw body bounding body box
*/
export function drawBVH(context: CanvasRenderingContext2D, body: Body) {
drawPolygon(context, {
pos: { x: body.minX, y: body.minY },
calcPoints: createBox(body.maxX - body.minX, body.maxY - body.minY),
});
}
/**
* clone response object returning new response with previous ones values
*/
export function cloneResponse(response: Response) {
const clone = new Response();
const { a, b, overlap, overlapN, overlapV, aInB, bInA } = response;
clone.a = a;
clone.b = b;
clone.overlap = overlap;
clone.overlapN = overlapN.clone();
clone.overlapV = overlapV.clone();
clone.aInB = aInB;
clone.bInA = bInA;
return clone;
}
/**
* dummy fn used as default, for optimization
*/
export function returnTrue() {
return true;
}
/**
* for groups
*/
export function getGroup(group: number): number {
return Math.max(0, Math.min(group, 0x7fffffff));
}
/**
* binary string to decimal number
*/
export function bin2dec(binary: string): number {
return Number(`0b${binary}`.replace(/\s/g, ""));
}
/**
* helper for groupBits()
*
* @param input - number or binary string
*/
export function ensureNumber(input: number | string): number {
return typeof input === "number" ? input : bin2dec(input);
}
/**
* create group bits from category and mask
*
* @param category - category bits
* @param mask - mask bits (default: category)
*/
export function groupBits(
category: number | string,
mask: number | string = category,
) {
return (ensureNumber(category) << 16) | ensureNumber(mask);
}
export function move(body: Body, speed = 1, updateNow = true) {
if (!speed) {
return;
}
const moveX = Math.cos(body.angle) * speed;
const moveY = Math.sin(body.angle) * speed;
body.setPosition(body.x + moveX, body.y + moveY, updateNow);
}