Skip to content

packages/core/src/features/physics/lib/2d/collision/casts.ts

Read as Markdown

This is the source snapshot used to build these API details. View this revision on GitHub.

Back to reference

1 import type {
2   PibblPhysicsDistance2D,
3   PibblPhysicsPose2D,
4   PibblPhysicsRay2D,
5   PibblPhysicsShape2D,
6   PibblPhysicsShapeHit2D,
7   PibblPhysicsVector2,
8 } from '../../../2d-geometry.js';
9 import {
10   copyFiniteVector2,
11   requireNonnegativeNumber,
12 } from '../../shared/validation.js';
13 import {
14   IDENTITY_POSE_2D,
15   composePose2D,
16   copyPose2D,
17   transformPointInto,
18   type InternalPose2D,
19 } from '../math.js';
20 import { GEOMETRY_EPSILON } from '../numeric-policy.js';
21 import {
22   createShape2D,
23   requireShapeRecord2D,
24   type CircleLeaf2D,
25   type ConvexLeaf2D,
26   type ShapeRecord2D,
27 } from '../shape-records.js';
28 import { distancePointToSegment2D } from './analytic.js';
29 import {
30   containsPointInShape2D,
31   distanceBetweenPreparedShapes2D,
32 } from './pairs.js';
33 
34 const CAST_MAX_ITERATIONS = 32;
35 const CAST_REFINEMENT_ITERATIONS = 64;
36 const CAST_HIT_TOLERANCE = 1e-7;
37 const CAST_TIME_TOLERANCE = 1e-12;
38 
39 interface CastCandidate2D {
40   readonly leafKey: readonly [number, number];
41   readonly pointX: number;
42   readonly pointY: number;
43   readonly normalX: number;
44   readonly normalY: number;
45   readonly distance: number;
46   readonly timeOfImpact: number;
47 }
48 
49 interface PreparedCastShape2D {
50   readonly record: ShapeRecord2D;
51   readonly pose: InternalPose2D;
52 }
53 
54 /**
55  * Casts a ray against one posed shape and returns its first hit or null.
56  *
57  * @param shape - Shape to intersect. See {@link PibblPhysicsShape2D}.
58  * @param publicPose - Target shape pose. See {@link PibblPhysicsPose2D}.
59  * @param ray - Ray origin, direction, and travel limit. See {@link PibblPhysicsRay2D}.
60  * @param options - Whether initial overlap counts as a hit.
61  * @returns The first shape hit, or null when there is no hit. See {@link PibblPhysicsShapeHit2D}.
62  *
63  * @see {@link PibblPhysicsShape2D}
64  * @see {@link PibblPhysicsPose2D}
65  * @see {@link PibblPhysicsRay2D}
66  * @see {@link PibblPhysicsShapeHit2D}
67  */
68 export function raycastShape2D(
69   shape: PibblPhysicsShape2D,
70   publicPose: PibblPhysicsPose2D,
71   ray: PibblPhysicsRay2D,
72   options?: Readonly<{ includeInitialOverlap?: boolean }>,
73 ): PibblPhysicsShapeHit2D | null {
74   const prepared = prepareShape(shape, publicPose, 'pose');
75   const origin = copyFiniteVector2(ray.origin, 'ray.origin');
76   const sourceDirection = copyFiniteVector2(ray.direction, 'ray.direction');
77   const directionScale = Math.max(
78     Math.abs(sourceDirection[0]),
79     Math.abs(sourceDirection[1]),
80   );
81   if (directionScale === 0) {
82     throw new RangeError('ray.direction must be non-zero.');
83   }
84   const maxDistance = requireNonnegativeNumber(ray.maxDistance, 'ray.maxDistance');
85   const scaledDirectionX = sourceDirection[0] / directionScale;
86   const scaledDirectionY = sourceDirection[1] / directionScale;
87   const scaledDirectionLength = Math.hypot(scaledDirectionX, scaledDirectionY);
88   const directionX = scaledDirectionX / scaledDirectionLength;
89   const directionY = scaledDirectionY / scaledDirectionLength;
90   let selected: CastCandidate2D | null = null;
91 
92   for (const leaf of prepared.record.leaves) {
93     const leafShape = shapeForLeaf(leaf);
94     const initiallyOverlapping = containsPointInShape2D(
95       leafShape,
96       internalPoseAsPublic(prepared.pose),
97       origin,
98     );
99     let candidate: CastCandidate2D | null;
100     if (initiallyOverlapping) {
101       candidate = options?.includeInitialOverlap === true
102         ? {
103             leafKey: [0, leaf.canonicalLeafIndex],
104             pointX: origin[0],
105             pointY: origin[1],
106             normalX: -directionX,
107             normalY: -directionY,
108             distance: 0,
109             timeOfImpact: 0,
110           }
111         : null;
112     } else if (maxDistance === 0) {
113       candidate = null;
114     } else {
115       candidate = raycastLeaf(
116         leaf,
117         leafShape,
118         prepared.pose,
119         origin[0],
120         origin[1],
121         directionX,
122         directionY,
123         maxDistance,
124       );
125     }
126     if (candidate !== null && isEarlierCandidate(candidate, selected)) {
127       selected = candidate;
128     }
129   }
130 
131   return selected === null ? null : publicHit(selected);
132 }
133 
134 /**
135  * Sweeps a posed shape along a translation against another posed shape and returns a hit or null.
136  *
137  * @param moving - Shape to sweep. See {@link PibblPhysicsShape2D}.
138  * @param publicFrom - Initial pose of the moving shape. See {@link PibblPhysicsPose2D}.
139  * @param publicTranslation - Translation vector for the sweep. See {@link PibblPhysicsVector2}.
140  * @param target - Stationary shape to test against. See {@link PibblPhysicsShape2D}.
141  * @param publicTargetPose - Pose of the stationary shape. See {@link PibblPhysicsPose2D}.
142  * @param options - Whether initial overlap counts as a hit.
143  * @returns The first sweep hit, or null when there is no hit. See {@link PibblPhysicsShapeHit2D}.
144  *
145  * @see {@link PibblPhysicsShape2D}
146  * @see {@link PibblPhysicsPose2D}
147  * @see {@link PibblPhysicsVector2}
148  * @see {@link PibblPhysicsShapeHit2D}
149  */
150 export function shapeCastAgainstShape2D(
151   moving: PibblPhysicsShape2D,
152   publicFrom: PibblPhysicsPose2D,
153   publicTranslation: PibblPhysicsVector2,
154   target: PibblPhysicsShape2D,
155   publicTargetPose: PibblPhysicsPose2D,
156   options?: Readonly<{ includeInitialOverlap?: boolean }>,
157 ): PibblPhysicsShapeHit2D | null {
158   const preparedMoving = prepareShape(moving, publicFrom, 'from');
159   const translation = copyFiniteVector2(publicTranslation, 'translation');
160   const preparedTarget = prepareShape(target, publicTargetPose, 'targetPose');
161   const translationLength = Math.hypot(translation[0], translation[1]);
162   if (!Number.isFinite(translationLength)) {
163     throw new RangeError('translation magnitude must be finite.');
164   }
165   let selected: CastCandidate2D | null = null;
166 
167   for (const movingLeaf of preparedMoving.record.leaves) {
168     const movingLeafShape = shapeForLeaf(movingLeaf);
169     for (const targetLeaf of preparedTarget.record.leaves) {
170       const targetLeafShape = shapeForLeaf(targetLeaf);
171       const leafKey = pairLeafKey(movingLeaf, targetLeaf);
172       const candidate = movingLeaf.kind === 'circle' && targetLeaf.kind === 'circle'
173         ? castCircleAgainstCircle(
174             movingLeaf,
175             preparedMoving.pose,
176             translation[0],
177             translation[1],
178             translationLength,
179             targetLeaf,
180             preparedTarget.pose,
181             leafKey,
182             options?.includeInitialOverlap === true,
183           )
184         : conservativelyCastLeafPair(
185             movingLeafShape,
186             preparedMoving.pose,
187             translation[0],
188             translation[1],
189             translationLength,
190             targetLeafShape,
191             preparedTarget.pose,
192             leafKey,
193             options?.includeInitialOverlap === true,
194           );
195       if (candidate !== null && isEarlierCandidate(candidate, selected)) {
196         selected = candidate;
197       }
198     }
199   }
200 
201   return selected === null ? null : publicHit(selected);
202 }
203 
204 function raycastLeaf(
205   leaf: ConvexLeaf2D,
206   leafShape: PibblPhysicsShape2D,
207   pose: InternalPose2D,
208   originX: number,
209   originY: number,
210   directionX: number,
211   directionY: number,
212   maxDistance: number,
213 ): CastCandidate2D | null {
214   switch (leaf.kind) {
215     case 'circle':
216       return raycastCircle(
217         leaf,
218         pose,
219         originX,
220         originY,
221         directionX,
222         directionY,
223         maxDistance,
224       );
225     case 'capsule':
226       return raycastCapsule(
227         leaf,
228         pose,
229         originX,
230         originY,
231         directionX,
232         directionY,
233         maxDistance,
234       );
235     case 'segment':
236       return raycastSegment(
237         leaf,
238         pose,
239         originX,
240         originY,
241         directionX,
242         directionY,
243         maxDistance,
244       );
245     default: {
246       const pointShape = shapeForPoint();
247       return conservativelyCastLeafPair(
248         pointShape,
249         { x: originX, y: originY, rotationRadians: 0 },
250         directionX * maxDistance,
251         directionY * maxDistance,
252         maxDistance,
253         leafShape,
254         pose,
255         [0, leaf.canonicalLeafIndex],
256         false,
257       );
258     }
259   }
260 }
261 
262 function raycastCircle(
263   leaf: CircleLeaf2D,
264   pose: InternalPose2D,
265   originX: number,
266   originY: number,
267   directionX: number,
268   directionY: number,
269   maxDistance: number,
270 ): CastCandidate2D | null {
271   const center = new Float64Array(2);
272   transformPointInto(center, 0, leaf.center[0]!, leaf.center[1]!, pose);
273   const hit = rayCircleDistance(
274     originX,
275     originY,
276     directionX,
277     directionY,
278     center[0]!,
279     center[1]!,
280     leaf.radius,
281     maxDistance,
282   );
283   if (hit === null) return null;
284   const pointX = originX + directionX * hit;
285   const pointY = originY + directionY * hit;
286   const normal = unitAgainstMotion(
287     pointX - center[0]!,
288     pointY - center[1]!,
289     directionX,
290     directionY,
291   );
292   return {
293     leafKey: [0, leaf.canonicalLeafIndex],
294     pointX,
295     pointY,
296     normalX: normal[0],
297     normalY: normal[1],
298     distance: hit,
299     timeOfImpact: hit / maxDistance,
300   };
301 }
302 
303 function raycastCapsule(
304   leaf: Extract<ConvexLeaf2D, { kind: 'capsule' }>,
305   pose: InternalPose2D,
306   originX: number,
307   originY: number,
308   directionX: number,
309   directionY: number,
310   maxDistance: number,
311 ): CastCandidate2D | null {
312   const endpoints = new Float64Array(4);
313   transformPointInto(endpoints, 0, leaf.start[0]!, leaf.start[1]!, pose);
314   transformPointInto(endpoints, 2, leaf.end[0]!, leaf.end[1]!, pose);
315   const startX = endpoints[0]!;
316   const startY = endpoints[1]!;
317   const endX = endpoints[2]!;
318   const endY = endpoints[3]!;
319   const segmentX = endX - startX;
320   const segmentY = endY - startY;
321   const segmentLength = Math.hypot(segmentX, segmentY);
322   if (segmentLength <= GEOMETRY_EPSILON) {
323     return raycastCircle(
324       { ...leaf, kind: 'circle', center: new Float64Array([leaf.start[0]!, leaf.start[1]!]) },
325       pose,
326       originX,
327       originY,
328       directionX,
329       directionY,
330       maxDistance,
331     );
332   }
333 
334   const tangentX = segmentX / segmentLength;
335   const tangentY = segmentY / segmentLength;
336   const sideNormalX = -tangentY;
337   const sideNormalY = tangentX;
338   const relativeX = originX - startX;
339   const relativeY = originY - startY;
340   const alongOrigin = relativeX * tangentX + relativeY * tangentY;
341   const acrossOrigin = relativeX * sideNormalX + relativeY * sideNormalY;
342   const alongDirection = directionX * tangentX + directionY * tangentY;
343   const acrossDirection = directionX * sideNormalX + directionY * sideNormalY;
344   const distances: number[] = [];
345   if (Math.abs(acrossDirection) > GEOMETRY_EPSILON) {
346     for (let side = -1; side <= 1; side += 2) {
347       const distance = (side * leaf.radius - acrossOrigin) / acrossDirection;
348       const along = alongOrigin + distance * alongDirection;
349       if (
350         distance >= -CAST_TIME_TOLERANCE &&
351         distance <= maxDistance + CAST_TIME_TOLERANCE &&
352         along >= -CAST_HIT_TOLERANCE &&
353         along <= segmentLength + CAST_HIT_TOLERANCE
354       ) {
355         distances.push(Math.max(0, distance));
356       }
357     }
358   }
359   for (let endpoint = 0; endpoint < 2; endpoint++) {
360     const centerX = endpoint === 0 ? startX : endX;
361     const centerY = endpoint === 0 ? startY : endY;
362     const distance = rayCircleDistance(
363       originX,
364       originY,
365       directionX,
366       directionY,
367       centerX,
368       centerY,
369       leaf.radius,
370       maxDistance,
371     );
372     if (distance !== null) distances.push(distance);
373   }
374   distances.sort((first, second) => first - second);
375   for (const distance of distances) {
376     const pointX = originX + directionX * distance;
377     const pointY = originY + directionY * distance;
378     const closest = distancePointToSegment2D(
379       pointX,
380       pointY,
381       startX,
382       startY,
383       endX,
384       endY,
385     );
386     if (Math.abs(closest.separation - leaf.radius) > CAST_HIT_TOLERANCE * 8) continue;
387     const normal = unitAgainstMotion(
388       pointX - closest.secondX,
389       pointY - closest.secondY,
390       directionX,
391       directionY,
392     );
393     if (normal[0] * directionX + normal[1] * directionY > CAST_HIT_TOLERANCE) continue;
394     return {
395       leafKey: [0, leaf.canonicalLeafIndex],
396       pointX,
397       pointY,
398       normalX: normal[0],
399       normalY: normal[1],
400       distance,
401       timeOfImpact: distance / maxDistance,
402     };
403   }
404   return null;
405 }
406 
407 function raycastSegment(
408   leaf: Extract<ConvexLeaf2D, { kind: 'segment' }>,
409   pose: InternalPose2D,
410   originX: number,
411   originY: number,
412   directionX: number,
413   directionY: number,
414   maxDistance: number,
415 ): CastCandidate2D | null {
416   const endpoints = new Float64Array(4);
417   transformPointInto(endpoints, 0, leaf.start[0]!, leaf.start[1]!, pose);
418   transformPointInto(endpoints, 2, leaf.end[0]!, leaf.end[1]!, pose);
419   const startX = endpoints[0]!;
420   const startY = endpoints[1]!;
421   const segmentX = endpoints[2]! - startX;
422   const segmentY = endpoints[3]! - startY;
423   const relativeX = startX - originX;
424   const relativeY = startY - originY;
425   const denominator = cross(directionX, directionY, segmentX, segmentY);
426   let distance: number;
427   if (Math.abs(denominator) > GEOMETRY_EPSILON) {
428     distance = cross(relativeX, relativeY, segmentX, segmentY) / denominator;
429     const segmentTime = cross(relativeX, relativeY, directionX, directionY) / denominator;
430     if (
431       distance < -CAST_TIME_TOLERANCE ||
432       distance > maxDistance + CAST_TIME_TOLERANCE ||
433       segmentTime < -CAST_TIME_TOLERANCE ||
434       segmentTime > 1 + CAST_TIME_TOLERANCE
435     ) {
436       return null;
437     }
438   } else {
439     if (Math.abs(cross(relativeX, relativeY, directionX, directionY)) > GEOMETRY_EPSILON) {
440       return null;
441     }
442     const first = relativeX * directionX + relativeY * directionY;
443     const second = first + segmentX * directionX + segmentY * directionY;
444     distance = Math.min(first, second);
445     if (distance < -CAST_TIME_TOLERANCE) distance = Math.max(first, second);
446     if (distance < -CAST_TIME_TOLERANCE || distance > maxDistance + CAST_TIME_TOLERANCE) {
447       return null;
448     }
449   }
450   distance = Math.max(0, Math.min(maxDistance, distance));
451   const pointX = originX + directionX * distance;
452   const pointY = originY + directionY * distance;
453   const normal = segmentNormalAgainstMotion(segmentX, segmentY, directionX, directionY);
454   return {
455     leafKey: [0, leaf.canonicalLeafIndex],
456     pointX,
457     pointY,
458     normalX: normal[0],
459     normalY: normal[1],
460     distance,
461     timeOfImpact: distance / maxDistance,
462   };
463 }
464 
465 function castCircleAgainstCircle(
466   moving: CircleLeaf2D,
467   movingPose: InternalPose2D,
468   translationX: number,
469   translationY: number,
470   translationLength: number,
471   target: CircleLeaf2D,
472   targetPose: InternalPose2D,
473   leafKey: readonly [number, number],
474   includeInitialOverlap: boolean,
475 ): CastCandidate2D | null {
476   const centers = new Float64Array(4);
477   transformPointInto(centers, 0, moving.center[0]!, moving.center[1]!, movingPose);
478   transformPointInto(centers, 2, target.center[0]!, target.center[1]!, targetPose);
479   const relativeX = centers[0]! - centers[2]!;
480   const relativeY = centers[1]! - centers[3]!;
481   const radius = moving.radius + target.radius;
482   if (relativeX * relativeX + relativeY * relativeY <= radius * radius) {
483     if (!includeInitialOverlap) return null;
484     const normal = unitAgainstMotion(relativeX, relativeY, translationX, translationY);
485     return {
486       leafKey,
487       pointX: centers[2]! + normal[0] * target.radius,
488       pointY: centers[3]! + normal[1] * target.radius,
489       normalX: normal[0],
490       normalY: normal[1],
491       distance: 0,
492       timeOfImpact: 0,
493     };
494   }
495   if (translationLength === 0) return null;
496   const a = translationX * translationX + translationY * translationY;
497   const b = 2 * (relativeX * translationX + relativeY * translationY);
498   const c = relativeX * relativeX + relativeY * relativeY - radius * radius;
499   const discriminant = b * b - 4 * a * c;
500   if (discriminant < -GEOMETRY_EPSILON) return null;
501   const time = (-b - Math.sqrt(Math.max(0, discriminant))) / (2 * a);
502   if (time < -CAST_TIME_TOLERANCE || time > 1 + CAST_TIME_TOLERANCE) return null;
503   const timeOfImpact = Math.max(0, Math.min(1, time));
504   const movingX = centers[0]! + translationX * timeOfImpact;
505   const movingY = centers[1]! + translationY * timeOfImpact;
506   const normal = unitAgainstMotion(
507     movingX - centers[2]!,
508     movingY - centers[3]!,
509     translationX,
510     translationY,
511   );
512   return {
513     leafKey,
514     pointX: centers[2]! + normal[0] * target.radius,
515     pointY: centers[3]! + normal[1] * target.radius,
516     normalX: normal[0],
517     normalY: normal[1],
518     distance: translationLength * timeOfImpact,
519     timeOfImpact,
520   };
521 }
522 
523 function conservativelyCastLeafPair(
524   moving: PibblPhysicsShape2D,
525   from: InternalPose2D,
526   translationX: number,
527   translationY: number,
528   translationLength: number,
529   target: PibblPhysicsShape2D,
530   targetPose: InternalPose2D,
531   leafKey: readonly [number, number],
532   includeInitialOverlap: boolean,
533 ): CastCandidate2D | null {
534   let time = 0;
535   for (let iteration = 0; iteration < CAST_MAX_ITERATIONS; iteration += 1) {
536     const movingPose = {
537       x: from.x + translationX * time,
538       y: from.y + translationY * time,
539       rotationRadians: from.rotationRadians,
540     };
541     const distance = samplePairDistance(moving, movingPose, target, targetPose);
542     if (distance === null) return null;
543     if (distance.separation <= (time === 0 ? 0 : CAST_HIT_TOLERANCE)) {
544       if (time === 0 && !includeInitialOverlap) return null;
545       const normal = unitAgainstMotion(
546         distance.normal[0],
547         distance.normal[1],
548         translationX,
549         translationY,
550       );
551       return {
552         leafKey,
553         pointX: distance.pointOnSecond[0],
554         pointY: distance.pointOnSecond[1],
555         normalX: normal[0],
556         normalY: normal[1],
557         distance: translationLength * time,
558         timeOfImpact: time,
559       };
560     }
561     if (translationLength === 0) return null;
562     const closingSpeed = -(
563       distance.normal[0] * translationX +
564       distance.normal[1] * translationY
565     );
566     if (!Number.isFinite(closingSpeed) || closingSpeed <= 0) break;
567     const step = distance.separation / closingSpeed;
568     if (!Number.isFinite(step) || step <= CAST_TIME_TOLERANCE) break;
569     const nextTime = time + step;
570     if (!Number.isFinite(nextTime)) return null;
571     if (nextTime <= time) break;
572     if (nextTime > 1 + CAST_TIME_TOLERANCE) break;
573     time = Math.min(1, nextTime);
574   }
575   return refineBoundedTangent(
576     moving,
577     from,
578     translationX,
579     translationY,
580     translationLength,
581     target,
582     targetPose,
583     leafKey,
584   );
585 }
586 
587 function refineBoundedTangent(
588   moving: PibblPhysicsShape2D,
589   from: InternalPose2D,
590   translationX: number,
591   translationY: number,
592   translationLength: number,
593   target: PibblPhysicsShape2D,
594   targetPose: InternalPose2D,
595   leafKey: readonly [number, number],
596 ): CastCandidate2D | null {
597   let minimumTime = 0;
598   let maximumTime = 1;
599   let tangentTime = 0;
600   let tangent = sampleTranslatedDistance(
601     moving,
602     from,
603     translationX,
604     translationY,
605     tangentTime,
606     target,
607     targetPose,
608   );
609   if (tangent === null) return null;
610   for (let iteration = 0; iteration < CAST_REFINEMENT_ITERATIONS; iteration += 1) {
611     const middleTime = (minimumTime + maximumTime) / 2;
612     const middle = sampleTranslatedDistance(
613       moving,
614       from,
615       translationX,
616       translationY,
617       middleTime,
618       target,
619       targetPose,
620     );
621     if (middle === null) return null;
622     if (middle.separation < tangent.separation) {
623       tangentTime = middleTime;
624       tangent = middle;
625     }
626     const derivative =
627       middle.normal[0] * translationX + middle.normal[1] * translationY;
628     if (!Number.isFinite(derivative)) return null;
629     if (derivative < 0) {
630       minimumTime = middleTime;
631     } else {
632       maximumTime = middleTime;
633     }
634   }
635   if (tangent.separation > CAST_HIT_TOLERANCE) return null;
636 
637   let impactTime = tangentTime;
638   if (tangent.separation < 0) {
639     let separatedTime = 0;
640     for (let iteration = 0; iteration < CAST_REFINEMENT_ITERATIONS; iteration += 1) {
641       const middleTime = (separatedTime + impactTime) / 2;
642       const middle = sampleTranslatedDistance(
643         moving,
644         from,
645         translationX,
646         translationY,
647         middleTime,
648         target,
649         targetPose,
650       );
651       if (middle === null) return null;
652       if (middle.separation <= CAST_HIT_TOLERANCE) {
653         impactTime = middleTime;
654         tangent = middle;
655       } else {
656         separatedTime = middleTime;
657       }
658     }
659   }
660   const normal = unitAgainstMotion(
661     tangent.normal[0],
662     tangent.normal[1],
663     translationX,
664     translationY,
665   );
666   return {
667     leafKey,
668     pointX: tangent.pointOnSecond[0],
669     pointY: tangent.pointOnSecond[1],
670     normalX: normal[0],
671     normalY: normal[1],
672     distance: translationLength * impactTime,
673     timeOfImpact: impactTime,
674   };
675 }
676 
677 function sampleTranslatedDistance(
678   moving: PibblPhysicsShape2D,
679   from: InternalPose2D,
680   translationX: number,
681   translationY: number,
682   time: number,
683   target: PibblPhysicsShape2D,
684   targetPose: InternalPose2D,
685 ): PibblPhysicsDistance2D | null {
686   return samplePairDistance(
687     moving,
688     {
689       x: from.x + translationX * time,
690       y: from.y + translationY * time,
691       rotationRadians: from.rotationRadians,
692     },
693     target,
694     targetPose,
695   );
696 }
697 
698 function samplePairDistance(
699   moving: PibblPhysicsShape2D,
700   movingPose: InternalPose2D,
701   target: PibblPhysicsShape2D,
702   targetPose: InternalPose2D,
703 ): PibblPhysicsDistance2D | null {
704   try {
705     const distance = distanceBetweenPreparedShapes2D(
706       moving,
707       internalPoseAsPublic(movingPose),
708       target,
709       internalPoseAsPublic(targetPose),
710     );
711     return isFiniteDistance(distance) ? distance : null;
712   } catch {
713     return null;
714   }
715 }
716 
717 function prepareShape(
718   shape: PibblPhysicsShape2D,
719   publicPose: PibblPhysicsPose2D,
720   posePath: string,
721 ): PreparedCastShape2D {
722   const record = requireShapeRecord2D(shape);
723   const pose = composePose2D(copyPose2D(publicPose, posePath), record.localPose);
724   return { record, pose };
725 }
726 
727 function shapeForLeaf(leaf: ConvexLeaf2D): PibblPhysicsShape2D {
728   return createShape2D({
729     leaves: Object.freeze([leaf]),
730     localPose: IDENTITY_POSE_2D,
731     localBounds: new Float64Array(4),
732     area: 0,
733     centroidX: 0,
734     centroidY: 0,
735     unitInertia: 0,
736   });
737 }
738 
739 function shapeForPoint(): PibblPhysicsShape2D {
740   return shapeForLeaf(Object.freeze({
741     kind: 'segment',
742     start: new Float64Array(2),
743     end: new Float64Array(2),
744     canonicalLeafIndex: 0,
745   }));
746 }
747 
748 function rayCircleDistance(
749   originX: number,
750   originY: number,
751   directionX: number,
752   directionY: number,
753   centerX: number,
754   centerY: number,
755   radius: number,
756   maxDistance: number,
757 ): number | null {
758   const relativeX = originX - centerX;
759   const relativeY = originY - centerY;
760   const projection = relativeX * directionX + relativeY * directionY;
761   const discriminant = projection * projection -
762     (relativeX * relativeX + relativeY * relativeY - radius * radius);
763   if (discriminant < -GEOMETRY_EPSILON) return null;
764   const distance = -projection - Math.sqrt(Math.max(0, discriminant));
765   if (distance < -CAST_TIME_TOLERANCE || distance > maxDistance + CAST_TIME_TOLERANCE) {
766     return null;
767   }
768   return Math.max(0, Math.min(maxDistance, distance));
769 }
770 
771 function unitAgainstMotion(
772   x: number,
773   y: number,
774   motionX: number,
775   motionY: number,
776 ): readonly [number, number] {
777   const length = Math.hypot(x, y);
778   if (length > GEOMETRY_EPSILON) {
779     const unitX = x / length;
780     const unitY = y / length;
781     return unitX * motionX + unitY * motionY > 0
782       ? [-unitX, -unitY]
783       : [unitX, unitY];
784   }
785   const motionLength = Math.hypot(motionX, motionY);
786   return motionLength > 0
787     ? [-motionX / motionLength, -motionY / motionLength]
788     : [1, 0];
789 }
790 
791 function segmentNormalAgainstMotion(
792   segmentX: number,
793   segmentY: number,
794   motionX: number,
795   motionY: number,
796 ): readonly [number, number] {
797   const length = Math.hypot(segmentX, segmentY);
798   if (length <= GEOMETRY_EPSILON) {
799     return unitAgainstMotion(0, 0, motionX, motionY);
800   }
801   let normalX = -segmentY / length;
802   let normalY = segmentX / length;
803   if (normalX * motionX + normalY * motionY > 0) {
804     normalX = -normalX;
805     normalY = -normalY;
806   }
807   return [normalX, normalY];
808 }
809 
810 function internalPoseAsPublic(pose: InternalPose2D): PibblPhysicsPose2D {
811   return {
812     position: [pose.x, pose.y],
813     rotationDegrees: pose.rotationRadians * 180 / Math.PI,
814   };
815 }
816 
817 function pairLeafKey(
818   first: ConvexLeaf2D,
819   second: ConvexLeaf2D,
820 ): readonly [number, number] {
821   return [first.canonicalLeafIndex, second.canonicalLeafIndex];
822 }
823 
824 function isEarlierCandidate(
825   candidate: CastCandidate2D,
826   selected: CastCandidate2D | null,
827 ): boolean {
828   if (selected === null) return true;
829   const timeDifference = candidate.timeOfImpact - selected.timeOfImpact;
830   return Math.abs(timeDifference) > CAST_TIME_TOLERANCE
831     ? timeDifference < 0
832     : candidate.leafKey[0] < selected.leafKey[0] ||
833         (candidate.leafKey[0] === selected.leafKey[0] &&
834           candidate.leafKey[1] < selected.leafKey[1]);
835 }
836 
837 function isFiniteDistance(distance: Readonly<{
838   separation: number;
839   pointOnFirst: PibblPhysicsVector2;
840   pointOnSecond: PibblPhysicsVector2;
841   normal: PibblPhysicsVector2;
842 }>): boolean {
843   return Number.isFinite(distance.separation) &&
844     Number.isFinite(distance.pointOnFirst[0]) &&
845     Number.isFinite(distance.pointOnFirst[1]) &&
846     Number.isFinite(distance.pointOnSecond[0]) &&
847     Number.isFinite(distance.pointOnSecond[1]) &&
848     Number.isFinite(distance.normal[0]) &&
849     Number.isFinite(distance.normal[1]);
850 }
851 
852 function publicHit(candidate: CastCandidate2D): PibblPhysicsShapeHit2D {
853   return Object.freeze({
854     point: freezeVector(candidate.pointX, candidate.pointY),
855     normal: freezeVector(candidate.normalX, candidate.normalY),
856     distance: cleanZero(candidate.distance),
857     timeOfImpact: cleanZero(candidate.timeOfImpact),
858   });
859 }
860 
861 function freezeVector(x: number, y: number): PibblPhysicsVector2 {
862   return Object.freeze([cleanZero(x), cleanZero(y)] as const);
863 }
864 
865 function cleanZero(value: number): number {
866   return Object.is(value, -0) || Math.abs(value) <= Number.EPSILON ? 0 : value;
867 }
868 
869 function cross(ax: number, ay: number, bx: number, by: number): number {
870   return ax * by - ay * bx;
871 }
872 

Documentation built with @pibbl/core 0.0.2, revision a1dcf8e. ALPHA — NOT FOR PRODUCTION USE.