@typeonce/ritmo-math 0.21.0 → 0.23.0

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/src/Collide2.ts CHANGED
@@ -86,7 +86,8 @@ export interface MoveResult {
86
86
 
87
87
  /**
88
88
  * The distance `pushOut` and `moveCircle` keep from walls after a contact
89
- * (in world units), so the next sweep starts outside the wall.
89
+ * (in world units), so the next sweep starts outside the wall. Where another
90
+ * wall leaves no room for it (a corner, a gap), `moveCircle` stays touching.
90
91
  *
91
92
  * @category Movement
92
93
  */
@@ -319,75 +320,207 @@ export const overlapsCircleCircle = (center: Vec2, radius: number, other: Vec2,
319
320
  return dx * dx + dy * dy <= r * r
320
321
  }
321
322
 
323
+ // How far into a wall still counts as touching it: rounding, not overlap.
324
+ const hair = 1e-9
325
+
326
+ // The way out of a wall that `boxDepth` and `segmentDepth` found, read right
327
+ // after the call: module state, so testing every wall on every step
328
+ // allocates nothing.
329
+ const wayOut = { x: 0, y: 0 }
330
+
322
331
  /**
323
- * Pushes a circle out of every wall it overlaps, boxes first and then
324
- * segments, each in order, leaving `skin` between it and each wall. Returns
325
- * the corrected center. A center inside a box leaves through the nearest
326
- * side; a center exactly on a segment leaves along the segment's left normal.
327
- *
328
- * @category Movement
332
+ * How far a circle of `radius` at (`x`, `y`) is inside `box` (0 when it does
333
+ * not overlap it), with the unit way out in `wayOut`. A center inside the box
334
+ * leaves through the nearest side.
329
335
  */
330
- export const pushOut = (center: Vec2, radius: number, walls: Walls, skin: number = defaultSkin): Vec2 => {
331
- let x = center.x
332
- let y = center.y
333
- for (const box of walls.boxes ?? noBoxes) {
334
- const closestX = Math.max(box.minX, Math.min(x, box.maxX))
335
- const closestY = Math.max(box.minY, Math.min(y, box.maxY))
336
- const dx = x - closestX
337
- const dy = y - closestY
338
- const distanceSquared = dx * dx + dy * dy
339
- if (distanceSquared >= radius * radius) continue
340
- if (distanceSquared > 1e-12) {
341
- const distance = Math.sqrt(distanceSquared)
342
- x = closestX + (dx / distance) * (radius + skin)
343
- y = closestY + (dy / distance) * (radius + skin)
344
- } else {
345
- // Center inside the box: leave through the nearest side.
346
- const left = x - box.minX
347
- const right = box.maxX - x
348
- const top = y - box.minY
349
- const bottom = box.maxY - y
350
- const nearest = Math.min(left, right, top, bottom)
351
- if (nearest === left) x = box.minX - radius - skin
352
- else if (nearest === right) x = box.maxX + radius + skin
353
- else if (nearest === top) y = box.minY - radius - skin
354
- else y = box.maxY + radius + skin
336
+ const boxDepth = (x: number, y: number, radius: number, box: Box2): number => {
337
+ const closestX = Math.max(box.minX, Math.min(x, box.maxX))
338
+ const closestY = Math.max(box.minY, Math.min(y, box.maxY))
339
+ const dx = x - closestX
340
+ const dy = y - closestY
341
+ const distanceSquared = dx * dx + dy * dy
342
+ if (distanceSquared >= radius * radius) return 0
343
+ if (distanceSquared > 1e-12) {
344
+ const distance = Math.sqrt(distanceSquared)
345
+ wayOut.x = dx / distance
346
+ wayOut.y = dy / distance
347
+ return radius - distance
348
+ }
349
+ const left = x - box.minX
350
+ const right = box.maxX - x
351
+ const top = y - box.minY
352
+ const bottom = box.maxY - y
353
+ const nearest = Math.min(left, right, top, bottom)
354
+ wayOut.x = nearest === left ? -1 : nearest === right ? 1 : 0
355
+ wayOut.y = wayOut.x !== 0 ? 0 : nearest === top ? -1 : 1
356
+ return radius + nearest
357
+ }
358
+
359
+ /**
360
+ * How far a circle of `radius` at (`x`, `y`) is inside `segment` (0 when it
361
+ * does not overlap it), with the unit way out in `wayOut`. A center on the
362
+ * segment leaves along its left normal, one on a round post along +x.
363
+ */
364
+ const segmentDepth = (x: number, y: number, radius: number, segment: Segment2): number => {
365
+ const ex = segment.bx - segment.ax
366
+ const ey = segment.by - segment.ay
367
+ const lengthSquared = ex * ex + ey * ey
368
+ const along = lengthSquared > 1e-12 ? Math.max(0, Math.min(1, ((x - segment.ax) * ex + (y - segment.ay) * ey) / lengthSquared)) : 0
369
+ const dx = x - (segment.ax + ex * along)
370
+ const dy = y - (segment.ay + ey * along)
371
+ const distanceSquared = dx * dx + dy * dy
372
+ if (distanceSquared >= radius * radius) return 0
373
+ if (distanceSquared > 1e-12) {
374
+ const distance = Math.sqrt(distanceSquared)
375
+ wayOut.x = dx / distance
376
+ wayOut.y = dy / distance
377
+ return radius - distance
378
+ }
379
+ if (lengthSquared > 1e-12) {
380
+ const length = Math.sqrt(lengthSquared)
381
+ wayOut.x = -ey / length
382
+ wayOut.y = ex / length
383
+ } else {
384
+ wayOut.x = 1
385
+ wayOut.y = 0
386
+ }
387
+ return radius
388
+ }
389
+
390
+ /** Whether a circle of `radius` at (`x`, `y`) overlaps none of the walls (touching is clear). */
391
+ const clear = (x: number, y: number, radius: number, boxes: ReadonlyArray<Box2>, segments: ReadonlyArray<Segment2>): boolean => {
392
+ for (const box of boxes) if (boxDepth(x, y, radius, box) > hair) return false
393
+ for (const segment of segments) if (segmentDepth(x, y, radius, segment) > hair) return false
394
+ return true
395
+ }
396
+
397
+ /**
398
+ * How far a circle of `radius` whose center is inside `box` must go to leave
399
+ * it, through the nearest side where it then overlaps none of the walls (the
400
+ * nearest side when none has room), with the way out in `wayOut`.
401
+ */
402
+ const exitBox = (x: number, y: number, radius: number, box: Box2, boxes: ReadonlyArray<Box2>, segments: ReadonlyArray<Segment2>, skin: number): number => {
403
+ let nearest = Infinity
404
+ let nx = 0
405
+ let ny = 0
406
+ let room = false
407
+ for (let side = 0; side < 4; side++) {
408
+ const distance = side === 0 ? x - box.minX : side === 1 ? box.maxX - x : side === 2 ? y - box.minY : box.maxY - y
409
+ const sx = side === 0 ? -1 : side === 1 ? 1 : 0
410
+ const sy = side === 2 ? -1 : side === 3 ? 1 : 0
411
+ const open = clear(x + sx * (distance + radius + skin), y + sy * (distance + radius + skin), radius, boxes, segments)
412
+ if ((open && !room) || (open === room && distance < nearest)) {
413
+ nearest = distance
414
+ nx = sx
415
+ ny = sy
416
+ room = open
355
417
  }
356
418
  }
357
- for (const segment of walls.segments ?? noSegments) {
358
- const ex = segment.bx - segment.ax
359
- const ey = segment.by - segment.ay
360
- const lengthSquared = ex * ex + ey * ey
361
- const along = lengthSquared > 1e-12 ? Math.max(0, Math.min(1, ((x - segment.ax) * ex + (y - segment.ay) * ey) / lengthSquared)) : 0
362
- const closestX = segment.ax + ex * along
363
- const closestY = segment.ay + ey * along
364
- const dx = x - closestX
365
- const dy = y - closestY
366
- const distanceSquared = dx * dx + dy * dy
367
- if (distanceSquared >= radius * radius) continue
368
- if (distanceSquared > 1e-12) {
369
- const distance = Math.sqrt(distanceSquared)
370
- x = closestX + (dx / distance) * (radius + skin)
371
- y = closestY + (dy / distance) * (radius + skin)
372
- } else if (lengthSquared > 1e-12) {
373
- // Center on the segment: leave along its left normal.
374
- const length = Math.sqrt(lengthSquared)
375
- x = closestX - (ey / length) * (radius + skin)
376
- y = closestY + (ex / length) * (radius + skin)
419
+ wayOut.x = nx
420
+ wayOut.y = ny
421
+ return radius + nearest
422
+ }
423
+
424
+ /** Pushes the circle at `at` out of the walls in place: {@link pushOut} without allocating. */
425
+ const separate = (at: { x: number; y: number }, radius: number, boxes: ReadonlyArray<Box2>, segments: ReadonlyArray<Segment2>, skin: number): void => {
426
+ for (let pass = 0; pass < 8; pass++) {
427
+ // The deepest wall the circle is in: the one to leave first.
428
+ let depth = hair
429
+ let nx = 0
430
+ let ny = 0
431
+ let deepest: Box2 | Segment2 | undefined
432
+ let inside: Box2 | undefined
433
+ for (const box of boxes) {
434
+ const found = boxDepth(at.x, at.y, radius, box)
435
+ if (found <= depth) continue
436
+ depth = found
437
+ nx = wayOut.x
438
+ ny = wayOut.y
439
+ deepest = box
440
+ // Only a center inside the box is a radius or more deep.
441
+ inside = found >= radius ? box : undefined
442
+ }
443
+ for (const segment of segments) {
444
+ const found = segmentDepth(at.x, at.y, radius, segment)
445
+ if (found <= depth) continue
446
+ depth = found
447
+ nx = wayOut.x
448
+ ny = wayOut.y
449
+ deepest = segment
450
+ inside = undefined
451
+ }
452
+ if (deepest === undefined) return
453
+ if (inside !== undefined) {
454
+ depth = exitBox(at.x, at.y, radius, inside, boxes, segments, skin)
455
+ nx = wayOut.x
456
+ ny = wayOut.y
457
+ }
458
+ // The wall that way out pushes deepest into, facing back across an
459
+ // acute corner: leaving one of the two alone pushes into the other, so
460
+ // leave both at once. Each wall is measured from the start, so the side
461
+ // the circle is on stays the side it leaves to.
462
+ const out = depth + skin
463
+ let landing = hair
464
+ let across = 0
465
+ let fx = 0
466
+ let fy = 0
467
+ for (const box of boxes) {
468
+ // How deep it is now (below 0: that far clear), and once pushed.
469
+ const now = boxDepth(at.x, at.y, radius + out, box) - out
470
+ const facing = wayOut.x * nx + wayOut.y * ny
471
+ if (box === deepest || now <= -out || facing >= 0 || now - out * facing <= landing) continue
472
+ landing = now - out * facing
473
+ across = now + skin
474
+ fx = wayOut.x
475
+ fy = wayOut.y
476
+ }
477
+ for (const segment of segments) {
478
+ const now = segmentDepth(at.x, at.y, radius + out, segment) - out
479
+ const facing = wayOut.x * nx + wayOut.y * ny
480
+ if (segment === deepest || now <= -out || facing >= 0 || now - out * facing <= landing) continue
481
+ landing = now - out * facing
482
+ across = now + skin
483
+ fx = wayOut.x
484
+ fy = wayOut.y
485
+ }
486
+ // Walls face to face (a gap narrower than the circle) have no corner to leave by.
487
+ const det = nx * fy - ny * fx
488
+ if (landing > hair && Math.abs(det) > 1e-6) {
489
+ at.x += (out * fy - across * ny) / det
490
+ at.y += (across * nx - out * fx) / det
377
491
  } else {
378
- // Center on a round post: leave along +x.
379
- x = closestX + radius + skin
492
+ at.x += nx * out
493
+ at.y += ny * out
380
494
  }
381
495
  }
382
- return { x, y }
496
+ }
497
+
498
+ /**
499
+ * Pushes a circle out of every wall it overlaps, the deepest first, leaving
500
+ * `skin` between it and each wall, and returns the corrected center. The two
501
+ * walls of an acute corner are left at once, since leaving one alone pushes
502
+ * into the other. Only walls with no room between them (a gap narrower than
503
+ * the circle) can leave it overlapping. A center inside a box leaves through
504
+ * the nearest side with room; a center exactly on a segment leaves along the
505
+ * segment's left normal.
506
+ *
507
+ * @category Movement
508
+ */
509
+ export const pushOut = (center: Vec2, radius: number, walls: Walls, skin: number = defaultSkin): Vec2 => {
510
+ const corrected = { x: center.x, y: center.y }
511
+ separate(corrected, radius, walls.boxes ?? noBoxes, walls.segments ?? noSegments, skin)
512
+ return corrected
383
513
  }
384
514
 
385
515
  /**
386
516
  * Moves a circle by `delta`, stopping at walls and sliding along them (up to
387
517
  * four contacts per call). The whole path is swept, so no displacement can
388
- * tunnel through a wall. A circle that starts inside a wall is pushed out
389
- * first. A circle meeting a box's corner or a segment's end dead-on goes
390
- * around it rather than stopping against it.
518
+ * tunnel through a wall: a circle that starts outside every wall ends outside
519
+ * every wall, also where walls close in on it (an acute corner, a gap
520
+ * narrower than it), stopping there when nothing is left to slide along. A
521
+ * circle that starts inside a wall is pushed out first. A circle meeting a
522
+ * box's corner or a segment's end dead-on goes around it rather than stopping
523
+ * against it.
391
524
  *
392
525
  * `blocked` says the move touched a wall, not which one, nor whether the
393
526
  * circle stands on one now (a circle resting on a floor and not moving into
@@ -420,60 +553,106 @@ export const pushOut = (center: Vec2, radius: number, walls: Walls, skin: number
420
553
  * @category Movement
421
554
  */
422
555
  export const moveCircle = (start: Vec2, delta: Vec2, radius: number, walls: Walls, skin: number = defaultSkin): MoveResult => {
423
- let position = pushOut(start, radius, walls, skin)
424
- let rx = delta.x
425
- let ry = delta.y
556
+ const boxes = walls.boxes ?? noBoxes
557
+ const segments = walls.segments ?? noSegments
558
+ // The circle's place and the movement left, changed in place as it slides
559
+ // (the sweeps read them), so a move allocates only its result and hits.
560
+ const position = { x: start.x, y: start.y }
561
+ separate(position, radius, boxes, segments, skin)
562
+ const step = { x: delta.x, y: delta.y }
563
+ // Within a hair of a wall counts as touching it, so a circle left
564
+ // touching cannot slip in where the sweeps round the other way.
565
+ const touching = radius + hair
426
566
  let blocked = false
427
567
  for (let iteration = 0; iteration < 4; iteration++) {
428
- if (rx * rx + ry * ry < 1e-12) break
429
- const step = { x: rx, y: ry }
430
- // The first contact, and whether it is round (a box's corner or a
431
- // segment's end) rather than a flat side.
432
- let hit: Hit | undefined
568
+ if (step.x * step.x + step.y * step.y < 1e-12) break
569
+ // The first contact: when, its normal, and whether it is round (a box's
570
+ // corner or a segment's end) rather than a flat side.
571
+ let time = Infinity
572
+ let nx = 0
573
+ let ny = 0
433
574
  let round = false
434
- for (const box of walls.boxes ?? noBoxes) {
435
- const found = sweepCircleBox(position, step, radius, box)
436
- if (found === undefined || (hit !== undefined && found.time >= hit.time)) continue
437
- hit = found
438
- round = found.nx !== 0 && found.ny !== 0
575
+ // The bounds of the swept circle: a wall outside them is not in the way.
576
+ const minX = Math.min(position.x, position.x + step.x) - touching
577
+ const minY = Math.min(position.y, position.y + step.y) - touching
578
+ const maxX = Math.max(position.x, position.x + step.x) + touching
579
+ const maxY = Math.max(position.y, position.y + step.y) + touching
580
+ // A wall the circle touches or is already inside (by a rounding error,
581
+ // or a push out with no room) may not be reported by the sweeps, so test
582
+ // it first: moving into it is a contact now, moving out of it is free.
583
+ for (const box of boxes) {
584
+ if (box.minX > maxX || box.maxX < minX || box.minY > maxY || box.maxY < minY) continue
585
+ if (boxDepth(position.x, position.y, touching, box) > 0) {
586
+ if (time === 0 || step.x * wayOut.x + step.y * wayOut.y >= 0) continue
587
+ time = 0
588
+ nx = wayOut.x
589
+ ny = wayOut.y
590
+ } else {
591
+ const hit = sweepCircleBox(position, step, radius, box)
592
+ if (hit === undefined || hit.time >= time) continue
593
+ time = hit.time
594
+ nx = hit.nx
595
+ ny = hit.ny
596
+ }
597
+ round = nx !== 0 && ny !== 0
439
598
  }
440
- for (const segment of walls.segments ?? noSegments) {
441
- const found = sweepCircleSegment(position, step, radius, segment)
442
- if (found === undefined || (hit !== undefined && found.time >= hit.time)) continue
443
- hit = found
599
+ for (const segment of segments) {
600
+ if (
601
+ Math.min(segment.ax, segment.bx) > maxX || Math.max(segment.ax, segment.bx) < minX ||
602
+ Math.min(segment.ay, segment.by) > maxY || Math.max(segment.ay, segment.by) < minY
603
+ ) continue
604
+ if (segmentDepth(position.x, position.y, touching, segment) > 0) {
605
+ if (time === 0 || step.x * wayOut.x + step.y * wayOut.y >= 0) continue
606
+ time = 0
607
+ nx = wayOut.x
608
+ ny = wayOut.y
609
+ } else {
610
+ const hit = sweepCircleSegment(position, step, radius, segment)
611
+ if (hit === undefined || hit.time >= time) continue
612
+ time = hit.time
613
+ nx = hit.nx
614
+ ny = hit.ny
615
+ }
444
616
  const ex = segment.bx - segment.ax
445
617
  const ey = segment.by - segment.ay
446
618
  const lengthSquared = ex * ex + ey * ey
447
- const along = found.nx * ex + found.ny * ey
619
+ const along = nx * ex + ny * ey
448
620
  // A flat side's normal is perpendicular to the segment.
449
621
  round = lengthSquared < 1e-12 || along * along > 1e-18 * lengthSquared
450
622
  }
451
- if (hit === undefined) {
452
- position = { x: position.x + rx, y: position.y + ry }
623
+ if (time === Infinity) {
624
+ position.x += step.x
625
+ position.y += step.y
453
626
  break
454
627
  }
455
628
  blocked = true
456
- position = {
457
- x: position.x + rx * hit.time + hit.nx * skin,
458
- y: position.y + ry * hit.time + hit.ny * skin
629
+ position.x += step.x * time
630
+ position.y += step.y * time
631
+ // Keep `skin` off the wall, unless that would put the circle inside
632
+ // another one (in a corner or a gap narrower than it): then stay touching.
633
+ if (clear(position.x + nx * skin, position.y + ny * skin, radius, boxes, segments)) {
634
+ position.x += nx * skin
635
+ position.y += ny * skin
459
636
  }
460
637
  // Slide: keep the remaining movement tangent to the contact.
461
- const remaining = 1 - hit.time
462
- rx *= remaining
463
- ry *= remaining
464
- const into = rx * hit.nx + ry * hit.ny
638
+ const remaining = 1 - time
639
+ let rx = step.x * remaining
640
+ let ry = step.y * remaining
641
+ const into = rx * nx + ry * ny
465
642
  if (into < 0) {
466
- rx -= into * hit.nx
467
- ry -= into * hit.ny
643
+ rx -= into * nx
644
+ ry -= into * ny
468
645
  // Dead-on into a rounded corner or end (as an exact diagonal meets an
469
646
  // axis-aligned box) nothing is left to slide along: go around it
470
647
  // instead of stopping against it.
471
648
  if (round && rx * rx + ry * ry < 1e-12 * into * into) {
472
- const side = rx * -hit.ny + ry * hit.nx < 0 ? -1 : 1
473
- rx = -hit.ny * -into * side
474
- ry = hit.nx * -into * side
649
+ const side = rx * -ny + ry * nx < 0 ? -1 : 1
650
+ rx = -ny * -into * side
651
+ ry = nx * -into * side
475
652
  }
476
653
  }
654
+ step.x = rx
655
+ step.y = ry
477
656
  }
478
657
  return { position, blocked }
479
658
  }