@typeonce/ritmo-math 0.13.0 → 0.15.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.
Files changed (113) hide show
  1. package/CHANGELOG.md +149 -0
  2. package/README.md +18 -13
  3. package/dist/Angle.d.ts +44 -0
  4. package/dist/Angle.d.ts.map +1 -0
  5. package/dist/Angle.js +62 -0
  6. package/dist/Angle.js.map +1 -0
  7. package/dist/Box2.d.ts +16 -4
  8. package/dist/Box2.d.ts.map +1 -1
  9. package/dist/Box2.js +16 -1
  10. package/dist/Box2.js.map +1 -1
  11. package/dist/Collide2.d.ts +59 -15
  12. package/dist/Collide2.d.ts.map +1 -1
  13. package/dist/Collide2.js +156 -18
  14. package/dist/Collide2.js.map +1 -1
  15. package/dist/FlowField.d.ts +24 -38
  16. package/dist/FlowField.d.ts.map +1 -1
  17. package/dist/FlowField.js +18 -5
  18. package/dist/FlowField.js.map +1 -1
  19. package/dist/Scalar.d.ts +19 -166
  20. package/dist/Scalar.d.ts.map +1 -1
  21. package/dist/Scalar.js +51 -51
  22. package/dist/Scalar.js.map +1 -1
  23. package/dist/Segment2.d.ts +56 -0
  24. package/dist/Segment2.d.ts.map +1 -0
  25. package/dist/Segment2.js +32 -0
  26. package/dist/Segment2.js.map +1 -0
  27. package/dist/Vec2.d.ts +47 -7
  28. package/dist/Vec2.d.ts.map +1 -1
  29. package/dist/Vec2.js +56 -8
  30. package/dist/Vec2.js.map +1 -1
  31. package/dist/index.d.ts +10 -21
  32. package/dist/index.d.ts.map +1 -1
  33. package/dist/index.js +10 -21
  34. package/dist/index.js.map +1 -1
  35. package/package.json +3 -3
  36. package/src/Angle.ts +60 -0
  37. package/src/Box2.ts +20 -4
  38. package/src/Collide2.ts +171 -24
  39. package/src/FlowField.ts +34 -10
  40. package/src/Scalar.ts +43 -165
  41. package/src/Segment2.ts +71 -0
  42. package/src/Vec2.ts +58 -8
  43. package/src/index.ts +10 -21
  44. package/dist/Aabb.d.ts +0 -182
  45. package/dist/Aabb.d.ts.map +0 -1
  46. package/dist/Aabb.js +0 -109
  47. package/dist/Aabb.js.map +0 -1
  48. package/dist/InputAxis.d.ts +0 -44
  49. package/dist/InputAxis.d.ts.map +0 -1
  50. package/dist/InputAxis.js +0 -71
  51. package/dist/InputAxis.js.map +0 -1
  52. package/dist/Ops.d.ts +0 -209
  53. package/dist/Ops.d.ts.map +0 -1
  54. package/dist/Ops.js +0 -210
  55. package/dist/Ops.js.map +0 -1
  56. package/dist/Random.d.ts +0 -124
  57. package/dist/Random.d.ts.map +0 -1
  58. package/dist/Random.js +0 -126
  59. package/dist/Random.js.map +0 -1
  60. package/dist/Size2.d.ts +0 -118
  61. package/dist/Size2.d.ts.map +0 -1
  62. package/dist/Size2.js +0 -54
  63. package/dist/Size2.js.map +0 -1
  64. package/dist/SpatialGrid.d.ts +0 -68
  65. package/dist/SpatialGrid.d.ts.map +0 -1
  66. package/dist/SpatialGrid.js +0 -112
  67. package/dist/SpatialGrid.js.map +0 -1
  68. package/dist/Vector2.d.ts +0 -214
  69. package/dist/Vector2.d.ts.map +0 -1
  70. package/dist/Vector2.js +0 -134
  71. package/dist/Vector2.js.map +0 -1
  72. package/dist/internal/aabb.d.ts +0 -27
  73. package/dist/internal/aabb.d.ts.map +0 -1
  74. package/dist/internal/aabb.js +0 -52
  75. package/dist/internal/aabb.js.map +0 -1
  76. package/dist/internal/codec.d.ts +0 -9
  77. package/dist/internal/codec.d.ts.map +0 -1
  78. package/dist/internal/codec.js +0 -16
  79. package/dist/internal/codec.js.map +0 -1
  80. package/dist/internal/fdlibm.d.ts +0 -43
  81. package/dist/internal/fdlibm.d.ts.map +0 -1
  82. package/dist/internal/fdlibm.js +0 -1291
  83. package/dist/internal/fdlibm.js.map +0 -1
  84. package/dist/internal/inputAxis.d.ts +0 -11
  85. package/dist/internal/inputAxis.d.ts.map +0 -1
  86. package/dist/internal/inputAxis.js +0 -13
  87. package/dist/internal/inputAxis.js.map +0 -1
  88. package/dist/internal/scalar.d.ts +0 -11
  89. package/dist/internal/scalar.d.ts.map +0 -1
  90. package/dist/internal/scalar.js +0 -68
  91. package/dist/internal/scalar.js.map +0 -1
  92. package/dist/internal/size2.d.ts +0 -22
  93. package/dist/internal/size2.d.ts.map +0 -1
  94. package/dist/internal/size2.js +0 -38
  95. package/dist/internal/size2.js.map +0 -1
  96. package/dist/internal/vector2.d.ts +0 -39
  97. package/dist/internal/vector2.d.ts.map +0 -1
  98. package/dist/internal/vector2.js +0 -78
  99. package/dist/internal/vector2.js.map +0 -1
  100. package/src/Aabb.ts +0 -180
  101. package/src/InputAxis.ts +0 -81
  102. package/src/Ops.ts +0 -232
  103. package/src/Random.ts +0 -225
  104. package/src/Size2.ts +0 -122
  105. package/src/SpatialGrid.ts +0 -172
  106. package/src/Vector2.ts +0 -216
  107. package/src/internal/aabb.ts +0 -81
  108. package/src/internal/codec.ts +0 -21
  109. package/src/internal/fdlibm.ts +0 -1256
  110. package/src/internal/inputAxis.ts +0 -21
  111. package/src/internal/scalar.ts +0 -104
  112. package/src/internal/size2.ts +0 -54
  113. package/src/internal/vector2.ts +0 -121
package/dist/index.d.ts CHANGED
@@ -1,30 +1,19 @@
1
1
  /**
2
- * Math for game code.
2
+ * The 2D helpers most games would otherwise rewrite, as plain data in and
3
+ * plain data out, built on `Ops` so they replay the same on every engine.
3
4
  *
4
- * Validated values (`Scalar`, `Vector2`, `Size2`, `Aabb`) expose
5
- * Result-returning constructors, a guard (`is`), and one `codec` each, so
6
- * they plug into `Descriptor.ConstructedComponent(Vector2.codec)` /
7
- * `ConstructedResource(Random.codec)` and are validated once at the boundary. `InputAxis` normalizes directional input.
8
- *
9
- * Hot-path helpers work on plain numbers every frame: `Vec2` arithmetic,
10
- * `Box2` edges, `Collide2` swept circle collision, a `SpatialGrid` broad
11
- * phase, a `FlowField` for finding the way around walls, and a deterministic
12
- * `Random` whose state is one integer.
13
- *
14
- * `Ops` holds the math functions engines are allowed to approximate (`sin`,
15
- * `cos`, `atan2`, `exp`, `pow`, `hypot`, ...) as ports that return the same
16
- * bits everywhere: use them in simulation code instead of `Math`'s.
5
+ * `Vec2` arithmetic and angles of vectors, `Angle` for headings, `Scalar` for
6
+ * numbers moving toward a target, `Box2` edge boxes and `Segment2` walls at
7
+ * any angle, `Collide2` swept circle collision against both that slides
8
+ * along walls and never tunnels, and a `FlowField` that leads bodies around
9
+ * walls. Values are validated by the game's own schema when they enter the
10
+ * world; `Ops` and `Random` are in `@typeonce/ritmo`.
17
11
  */
18
- export * as Aabb from "./Aabb.ts";
12
+ export * as Angle from "./Angle.ts";
19
13
  export * as Box2 from "./Box2.ts";
20
14
  export * as Collide2 from "./Collide2.ts";
21
15
  export * as FlowField from "./FlowField.ts";
22
- export * as InputAxis from "./InputAxis.ts";
23
- export * as Ops from "./Ops.ts";
24
- export * as Random from "./Random.ts";
25
16
  export * as Scalar from "./Scalar.ts";
26
- export * as Size2 from "./Size2.ts";
27
- export * as SpatialGrid from "./SpatialGrid.ts";
17
+ export * as Segment2 from "./Segment2.ts";
28
18
  export * as Vec2 from "./Vec2.ts";
29
- export * as Vector2 from "./Vector2.ts";
30
19
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;GAgBG;AACH,OAAO,KAAK,IAAI,MAAM,WAAW,CAAA;AACjC,OAAO,KAAK,IAAI,MAAM,WAAW,CAAA;AACjC,OAAO,KAAK,QAAQ,MAAM,eAAe,CAAA;AACzC,OAAO,KAAK,SAAS,MAAM,gBAAgB,CAAA;AAC3C,OAAO,KAAK,SAAS,MAAM,gBAAgB,CAAA;AAC3C,OAAO,KAAK,GAAG,MAAM,UAAU,CAAA;AAC/B,OAAO,KAAK,MAAM,MAAM,aAAa,CAAA;AACrC,OAAO,KAAK,MAAM,MAAM,aAAa,CAAA;AACrC,OAAO,KAAK,KAAK,MAAM,YAAY,CAAA;AACnC,OAAO,KAAK,WAAW,MAAM,kBAAkB,CAAA;AAC/C,OAAO,KAAK,IAAI,MAAM,WAAW,CAAA;AACjC,OAAO,KAAK,OAAO,MAAM,cAAc,CAAA"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AACH,OAAO,KAAK,KAAK,MAAM,YAAY,CAAA;AACnC,OAAO,KAAK,IAAI,MAAM,WAAW,CAAA;AACjC,OAAO,KAAK,QAAQ,MAAM,eAAe,CAAA;AACzC,OAAO,KAAK,SAAS,MAAM,gBAAgB,CAAA;AAC3C,OAAO,KAAK,MAAM,MAAM,aAAa,CAAA;AACrC,OAAO,KAAK,QAAQ,MAAM,eAAe,CAAA;AACzC,OAAO,KAAK,IAAI,MAAM,WAAW,CAAA"}
package/dist/index.js CHANGED
@@ -1,30 +1,19 @@
1
1
  /**
2
- * Math for game code.
2
+ * The 2D helpers most games would otherwise rewrite, as plain data in and
3
+ * plain data out, built on `Ops` so they replay the same on every engine.
3
4
  *
4
- * Validated values (`Scalar`, `Vector2`, `Size2`, `Aabb`) expose
5
- * Result-returning constructors, a guard (`is`), and one `codec` each, so
6
- * they plug into `Descriptor.ConstructedComponent(Vector2.codec)` /
7
- * `ConstructedResource(Random.codec)` and are validated once at the boundary. `InputAxis` normalizes directional input.
8
- *
9
- * Hot-path helpers work on plain numbers every frame: `Vec2` arithmetic,
10
- * `Box2` edges, `Collide2` swept circle collision, a `SpatialGrid` broad
11
- * phase, a `FlowField` for finding the way around walls, and a deterministic
12
- * `Random` whose state is one integer.
13
- *
14
- * `Ops` holds the math functions engines are allowed to approximate (`sin`,
15
- * `cos`, `atan2`, `exp`, `pow`, `hypot`, ...) as ports that return the same
16
- * bits everywhere: use them in simulation code instead of `Math`'s.
5
+ * `Vec2` arithmetic and angles of vectors, `Angle` for headings, `Scalar` for
6
+ * numbers moving toward a target, `Box2` edge boxes and `Segment2` walls at
7
+ * any angle, `Collide2` swept circle collision against both that slides
8
+ * along walls and never tunnels, and a `FlowField` that leads bodies around
9
+ * walls. Values are validated by the game's own schema when they enter the
10
+ * world; `Ops` and `Random` are in `@typeonce/ritmo`.
17
11
  */
18
- export * as Aabb from "./Aabb.js";
12
+ export * as Angle from "./Angle.js";
19
13
  export * as Box2 from "./Box2.js";
20
14
  export * as Collide2 from "./Collide2.js";
21
15
  export * as FlowField from "./FlowField.js";
22
- export * as InputAxis from "./InputAxis.js";
23
- export * as Ops from "./Ops.js";
24
- export * as Random from "./Random.js";
25
16
  export * as Scalar from "./Scalar.js";
26
- export * as Size2 from "./Size2.js";
27
- export * as SpatialGrid from "./SpatialGrid.js";
17
+ export * as Segment2 from "./Segment2.js";
28
18
  export * as Vec2 from "./Vec2.js";
29
- export * as Vector2 from "./Vector2.js";
30
19
  //# sourceMappingURL=index.js.map
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;GAgBG;AACH,OAAO,KAAK,IAAI,MAAM,WAAW,CAAA;AACjC,OAAO,KAAK,IAAI,MAAM,WAAW,CAAA;AACjC,OAAO,KAAK,QAAQ,MAAM,eAAe,CAAA;AACzC,OAAO,KAAK,SAAS,MAAM,gBAAgB,CAAA;AAC3C,OAAO,KAAK,SAAS,MAAM,gBAAgB,CAAA;AAC3C,OAAO,KAAK,GAAG,MAAM,UAAU,CAAA;AAC/B,OAAO,KAAK,MAAM,MAAM,aAAa,CAAA;AACrC,OAAO,KAAK,MAAM,MAAM,aAAa,CAAA;AACrC,OAAO,KAAK,KAAK,MAAM,YAAY,CAAA;AACnC,OAAO,KAAK,WAAW,MAAM,kBAAkB,CAAA;AAC/C,OAAO,KAAK,IAAI,MAAM,WAAW,CAAA;AACjC,OAAO,KAAK,OAAO,MAAM,cAAc,CAAA"}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AACH,OAAO,KAAK,KAAK,MAAM,YAAY,CAAA;AACnC,OAAO,KAAK,IAAI,MAAM,WAAW,CAAA;AACjC,OAAO,KAAK,QAAQ,MAAM,eAAe,CAAA;AACzC,OAAO,KAAK,SAAS,MAAM,gBAAgB,CAAA;AAC3C,OAAO,KAAK,MAAM,MAAM,aAAa,CAAA;AACrC,OAAO,KAAK,QAAQ,MAAM,eAAe,CAAA;AACzC,OAAO,KAAK,IAAI,MAAM,WAAW,CAAA"}
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@typeonce/ritmo-math",
3
- "version": "0.13.0",
4
- "description": "Validated math values and hot-path game helpers (collision, spatial grid, flow field, random) for Ritmo games",
3
+ "version": "0.15.0",
4
+ "description": "The 2D helpers most Ritmo games would otherwise rewrite (vectors, angles, swept collision, flow field), plain data in and out, built on Ops so they replay the same on every engine",
5
5
  "author": "Sandro Maglione",
6
6
  "license": "MIT",
7
7
  "repository": {
@@ -47,7 +47,7 @@
47
47
  "provenance": true
48
48
  },
49
49
  "dependencies": {
50
- "@typeonce/ritmo": "^0.13.0"
50
+ "@typeonce/ritmo": "^0.15.0"
51
51
  },
52
52
  "engines": {
53
53
  "node": ">=20"
package/src/Angle.ts ADDED
@@ -0,0 +1,60 @@
1
+ /**
2
+ * Angles in radians, for headings a system stores as one number: a turret's
3
+ * aim, a body's facing.
4
+ *
5
+ * Angles wrap: 350° and -10° are the same heading, so comparing or turning
6
+ * them needs the wrap first. `wrap` brings any angle into [-π, π), and the
7
+ * difference between two headings is `wrap(to - from)`, the short way round.
8
+ * Both helpers are exact (`%` and `+ -` only), so they replay the same on
9
+ * every engine. For the angle of a vector use `Vec2.angle`, for the unit
10
+ * vector of an angle `Vec2.fromAngle`.
11
+ *
12
+ * @example
13
+ * ```ts
14
+ * // Turn a turret toward its target at a capped rate.
15
+ * const wanted = Vec2.angle(Vec2.subtract(target, turret.position))
16
+ * const aim = Angle.turnToward(turret.aim, wanted, turnRate * dt)
17
+ * ```
18
+ *
19
+ * @module Angle
20
+ * @docGroup helpers
21
+ *
22
+ * @categoryDescription Operations
23
+ * Wrapping and turning angles.
24
+ */
25
+
26
+ const TAU = 2 * Math.PI
27
+
28
+ /**
29
+ * `angle` brought into [-π, π) by whole turns: π and -π both give -π. Use it
30
+ * to keep a stored heading bounded, and for the signed short-way difference
31
+ * between two headings, `wrap(to - from)`. Exact on every engine.
32
+ *
33
+ * @category Operations
34
+ */
35
+ export const wrap = (angle: number): number => {
36
+ // `%` is exact, and so is adding or removing one turn from a value within
37
+ // one turn of it, so the result is the exact remainder.
38
+ let wrapped = angle % TAU
39
+ if (wrapped >= Math.PI) wrapped -= TAU
40
+ else if (wrapped < -Math.PI) wrapped += TAU
41
+ return wrapped === 0 ? 0 : wrapped
42
+ }
43
+
44
+ /**
45
+ * `angle` turned toward `target` the short way by at most `maxStep` radians,
46
+ * never overshooting: `wrap(target)` once it is within `maxStep`, and
47
+ * `wrap(angle)` when `maxStep` is 0 or less. Headings exactly half a turn
48
+ * apart turn the negative way. For a capped turn rate (a turret, a homing
49
+ * shot); for plain numbers use `Scalar.moveToward`, for points
50
+ * `Vec2.moveToward`.
51
+ *
52
+ * @category Operations
53
+ */
54
+ export const turnToward = (angle: number, target: number, maxStep: number): number => {
55
+ const from = wrap(angle)
56
+ if (!(maxStep > 0)) return from
57
+ const gap = wrap(target - from)
58
+ if (Math.abs(gap) <= maxStep) return wrap(target)
59
+ return wrap(gap > 0 ? from + maxStep : from - maxStep)
60
+ }
package/src/Box2.ts CHANGED
@@ -1,9 +1,9 @@
1
1
  /**
2
2
  * Plain axis-aligned boxes stored by their edges, for hot-path collision.
3
3
  *
4
- * `Aabb` is the validated, centered box for authored and stored values;
5
4
  * `Box2` is the edge form the collision helpers (`Collide2`, `FlowField`)
6
- * read every frame, built once from whatever the game stores.
5
+ * read every frame, built once from whatever the game stores (a center and a
6
+ * size, a tile's corner).
7
7
  *
8
8
  * @example
9
9
  * ```ts
@@ -18,7 +18,7 @@
18
18
  * The structural box shape.
19
19
  *
20
20
  * @categoryDescription Operations
21
- * Building boxes and testing them against circles.
21
+ * Building boxes, testing them against circles, and the closest point.
22
22
  */
23
23
  import type { Vec2 } from "./Vec2.ts"
24
24
 
@@ -49,7 +49,9 @@ export const around = (x: number, y: number, halfWidth: number, halfHeight: numb
49
49
  })
50
50
 
51
51
  /**
52
- * Whether a circle overlaps (or touches) the box.
52
+ * Whether a circle overlaps (or touches) the box. For two circles use
53
+ * `Collide2.overlapsCircleCircle`, for a wall at any angle
54
+ * `Segment2.overlapsCircle`.
53
55
  *
54
56
  * @category Operations
55
57
  */
@@ -58,3 +60,17 @@ export const overlapsCircle = (box: Box2, center: Vec2, radius: number): boolean
58
60
  const dy = center.y - Math.max(box.minY, Math.min(center.y, box.maxY))
59
61
  return dx * dx + dy * dy <= radius * radius
60
62
  }
63
+
64
+ /**
65
+ * The point of `box` closest to `point`: `point` clamped to the box's edges.
66
+ * A point inside the box comes back unchanged, so this keeps a body inside an
67
+ * arena, or gives the direction from an obstacle to a body outside it
68
+ * (`Vec2.subtract(body, closestPoint(box, body))`). To push a circle out of
69
+ * walls it overlaps, use `Collide2.pushOut`.
70
+ *
71
+ * @category Operations
72
+ */
73
+ export const closestPoint = (box: Box2, point: Vec2): Vec2 => ({
74
+ x: Math.max(box.minX, Math.min(point.x, box.maxX)),
75
+ y: Math.max(box.minY, Math.min(point.y, box.maxY))
76
+ })
package/src/Collide2.ts CHANGED
@@ -1,10 +1,12 @@
1
1
  /**
2
- * Continuous collision for moving circles against static boxes and circles.
2
+ * Continuous collision for moving circles against static walls (axis-aligned
3
+ * boxes and line segments) and circles.
3
4
  *
4
- * Movement is swept, not sampled: `sweepCircleBox` finds the first time of
5
+ * Movement is swept, not sampled: `sweepCircle` finds the first time of
5
6
  * contact along the whole displacement, so fast movers (dashes, projectiles)
6
7
  * cannot skip over a wall between two steps. `moveCircle` stops at walls and
7
- * slides along them.
8
+ * slides along them. Walls are passed as {@link Walls}: `Box2` boxes for a
9
+ * grid of rooms, `Segment2` segments for walls at any angle, or both.
8
10
  *
9
11
  * Every query returns `undefined` for "no contact", never throws, and
10
12
  * allocates only its result. Inputs are expected to be finite.
@@ -12,7 +14,7 @@
12
14
  * @example
13
15
  * ```ts
14
16
  * // Move a body by its velocity this step, sliding along the walls.
15
- * const moved = Collide2.moveCircle(position, Vec2.scale(velocity, dt), radius, walls)
17
+ * const moved = Collide2.moveCircle(position, Vec2.scale(velocity, dt), radius, { boxes: walls })
16
18
  * if (moved.blocked) bumpedWall()
17
19
  * ```
18
20
  *
@@ -23,13 +25,14 @@
23
25
  * Contacts and movement results.
24
26
  *
25
27
  * @categoryDescription Queries
26
- * First-contact sweeps and overlap resolution.
28
+ * First-contact sweeps and overlap tests.
27
29
  *
28
30
  * @categoryDescription Movement
29
31
  * Moving a circle through walls with sliding.
30
32
  */
31
33
  import type { Box2 } from "./Box2.ts"
32
- import * as Ops from "./Ops.ts"
34
+ import * as Ops from "@typeonce/ritmo/Ops"
35
+ import type { Segment2 } from "./Segment2.ts"
33
36
  import type { Vec2 } from "./Vec2.ts"
34
37
 
35
38
  /**
@@ -40,11 +43,27 @@ import type { Vec2 } from "./Vec2.ts"
40
43
  export interface Hit {
41
44
  /** Fraction of the displacement travelled before contact, in [0, 1]. */
42
45
  readonly time: number
43
- /** Unit contact normal, pointing away from the box. */
46
+ /** Unit contact normal, pointing away from the wall. */
44
47
  readonly nx: number
45
48
  readonly ny: number
46
49
  }
47
50
 
51
+ /**
52
+ * The static walls a circle collides with: axis-aligned `boxes`, line
53
+ * `segments`, or both. A missing list is no walls of that kind.
54
+ *
55
+ * @category Collision Types
56
+ */
57
+ export interface Walls {
58
+ readonly boxes?: ReadonlyArray<Box2>
59
+ readonly segments?: ReadonlyArray<Segment2>
60
+ /** Not a setting: an array of walls is passed by kind. */
61
+ readonly length?: "pass walls by kind: { boxes: walls } or { segments: walls }"
62
+ }
63
+
64
+ const noBoxes: ReadonlyArray<Box2> = []
65
+ const noSegments: ReadonlyArray<Segment2> = []
66
+
48
67
  /**
49
68
  * Where a moved circle ended up.
50
69
  *
@@ -170,7 +189,61 @@ export const sweepCircleBox = (origin: Vec2, delta: Vec2, radius: number, box: B
170
189
  }
171
190
 
172
191
  /**
173
- * First contact of a moving circle with any of `boxes`, or `undefined`.
192
+ * First contact of a circle of `radius` at `origin` moving by `delta` with
193
+ * `segment`, or `undefined`. Contact is computed against the segment
194
+ * thickened by the radius with round ends (the exact Minkowski sum), so the
195
+ * circle slides along it and around its ends. A circle that starts exactly
196
+ * touching it and moves into it hits at time 0. A circle that starts
197
+ * overlapping the segment is not reported; resolve it with `pushOut` first.
198
+ *
199
+ * @category Queries
200
+ */
201
+ export const sweepCircleSegment = (origin: Vec2, delta: Vec2, radius: number, segment: Segment2): Hit | undefined => {
202
+ const ex = segment.bx - segment.ax
203
+ const ey = segment.by - segment.ay
204
+ const lengthSquared = ex * ex + ey * ey
205
+ if (lengthSquared > 1e-12) {
206
+ // The flat side facing the circle, `radius` away from the segment's line.
207
+ const length = Math.sqrt(lengthSquared)
208
+ let nx = -ey / length
209
+ let ny = ex / length
210
+ let side = (origin.x - segment.ax) * nx + (origin.y - segment.ay) * ny
211
+ if (side < 0) {
212
+ nx = -nx
213
+ ny = -ny
214
+ side = -side
215
+ }
216
+ if (side < radius) {
217
+ // Beside the line: overlapping when level with the segment, otherwise
218
+ // only its ends are in the way.
219
+ const along = ((origin.x - segment.ax) * ex + (origin.y - segment.ay) * ey) / lengthSquared
220
+ if (along >= 0 && along <= 1) return undefined
221
+ } else {
222
+ const into = delta.x * nx + delta.y * ny
223
+ if (into < 0) {
224
+ // `0 +` turns a -0 (touching at the start) into 0.
225
+ const time = 0 + (radius - side) / into
226
+ if (time <= 1) {
227
+ const along = ((origin.x + delta.x * time - segment.ax) * ex + (origin.y + delta.y * time - segment.ay) * ey) / lengthSquared
228
+ // The thickened segment is convex, so entering through its flat side is the first contact.
229
+ if (along >= 0 && along <= 1) return { time, nx, ny }
230
+ }
231
+ }
232
+ }
233
+ }
234
+ const atA = rayCircle(origin.x, origin.y, delta.x, delta.y, segment.ax, segment.ay, radius)
235
+ const atB = lengthSquared > 1e-12 ? rayCircle(origin.x, origin.y, delta.x, delta.y, segment.bx, segment.by, radius) : undefined
236
+ if (atA === undefined && atB === undefined) return undefined
237
+ const fromA = atB === undefined || (atA !== undefined && atA <= atB)
238
+ const time = fromA ? atA! : atB
239
+ const cx = origin.x + delta.x * time - (fromA ? segment.ax : segment.bx)
240
+ const cy = origin.y + delta.y * time - (fromA ? segment.ay : segment.by)
241
+ const length = Ops.hypot(cx, cy) || 1
242
+ return { time, nx: cx / length, ny: cy / length }
243
+ }
244
+
245
+ /**
246
+ * First contact of a moving circle with any of `walls`, or `undefined`.
174
247
  *
175
248
  * With a `radius` of 0 the circle is a point and the sweep is a segment, so
176
249
  * this is also line of sight: `undefined` means nothing blocks the line from
@@ -179,17 +252,21 @@ export const sweepCircleBox = (origin: Vec2, delta: Vec2, radius: number, box: B
179
252
  *
180
253
  * @example
181
254
  * ```ts
182
- * const sees = Collide2.sweepCircleBoxes(eye, Vec2.subtract(target, eye), 0, walls) === undefined
255
+ * const sees = Collide2.sweepCircle(eye, Vec2.subtract(target, eye), 0, { boxes: walls }) === undefined
183
256
  * ```
184
257
  *
185
258
  * @category Queries
186
259
  */
187
- export const sweepCircleBoxes = (origin: Vec2, delta: Vec2, radius: number, boxes: ReadonlyArray<Box2>): Hit | undefined => {
260
+ export const sweepCircle = (origin: Vec2, delta: Vec2, radius: number, walls: Walls): Hit | undefined => {
188
261
  let first: Hit | undefined
189
- for (const box of boxes) {
262
+ for (const box of walls.boxes ?? noBoxes) {
190
263
  const hit = sweepCircleBox(origin, delta, radius, box)
191
264
  if (hit !== undefined && (first === undefined || hit.time < first.time)) first = hit
192
265
  }
266
+ for (const segment of walls.segments ?? noSegments) {
267
+ const hit = sweepCircleSegment(origin, delta, radius, segment)
268
+ if (hit !== undefined && (first === undefined || hit.time < first.time)) first = hit
269
+ }
193
270
  return first
194
271
  }
195
272
 
@@ -215,15 +292,33 @@ export const sweepCircleCircle = (
215
292
  }
216
293
 
217
294
  /**
218
- * Pushes a circle out of every box it overlaps, in order, leaving `skin`
219
- * between it and each wall. Returns the corrected center.
295
+ * Whether a circle of `radius` at `center` overlaps (or touches) a circle of
296
+ * `otherRadius` at `other`, without a square root. Touching counts, as in
297
+ * `Box2.overlapsCircle` and `Segment2.overlapsCircle`. For a pickup or a hit
298
+ * between bodies that have already moved; when one moves fast enough to pass
299
+ * through the other in one step, use {@link sweepCircleCircle}.
300
+ *
301
+ * @category Queries
302
+ */
303
+ export const overlapsCircleCircle = (center: Vec2, radius: number, other: Vec2, otherRadius: number): boolean => {
304
+ const r = radius + otherRadius
305
+ const dx = center.x - other.x
306
+ const dy = center.y - other.y
307
+ return dx * dx + dy * dy <= r * r
308
+ }
309
+
310
+ /**
311
+ * Pushes a circle out of every wall it overlaps, boxes first and then
312
+ * segments, each in order, leaving `skin` between it and each wall. Returns
313
+ * the corrected center. A center inside a box leaves through the nearest
314
+ * side; a center exactly on a segment leaves along the segment's left normal.
220
315
  *
221
316
  * @category Movement
222
317
  */
223
- export const pushOut = (center: Vec2, radius: number, boxes: ReadonlyArray<Box2>, skin: number = defaultSkin): Vec2 => {
318
+ export const pushOut = (center: Vec2, radius: number, walls: Walls, skin: number = defaultSkin): Vec2 => {
224
319
  let x = center.x
225
320
  let y = center.y
226
- for (const box of boxes) {
321
+ for (const box of walls.boxes ?? noBoxes) {
227
322
  const closestX = Math.max(box.minX, Math.min(x, box.maxX))
228
323
  const closestY = Math.max(box.minY, Math.min(y, box.maxY))
229
324
  const dx = x - closestX
@@ -247,6 +342,31 @@ export const pushOut = (center: Vec2, radius: number, boxes: ReadonlyArray<Box2>
247
342
  else y = box.maxY + radius + skin
248
343
  }
249
344
  }
345
+ for (const segment of walls.segments ?? noSegments) {
346
+ const ex = segment.bx - segment.ax
347
+ const ey = segment.by - segment.ay
348
+ const lengthSquared = ex * ex + ey * ey
349
+ const along = lengthSquared > 1e-12 ? Math.max(0, Math.min(1, ((x - segment.ax) * ex + (y - segment.ay) * ey) / lengthSquared)) : 0
350
+ const closestX = segment.ax + ex * along
351
+ const closestY = segment.ay + ey * along
352
+ const dx = x - closestX
353
+ const dy = y - closestY
354
+ const distanceSquared = dx * dx + dy * dy
355
+ if (distanceSquared >= radius * radius) continue
356
+ if (distanceSquared > 1e-12) {
357
+ const distance = Math.sqrt(distanceSquared)
358
+ x = closestX + (dx / distance) * (radius + skin)
359
+ y = closestY + (dy / distance) * (radius + skin)
360
+ } else if (lengthSquared > 1e-12) {
361
+ // Center on the segment: leave along its left normal.
362
+ const length = Math.sqrt(lengthSquared)
363
+ x = closestX - (ey / length) * (radius + skin)
364
+ y = closestY + (ex / length) * (radius + skin)
365
+ } else {
366
+ // Center on a round post: leave along +x.
367
+ x = closestX + radius + skin
368
+ }
369
+ }
250
370
  return { x, y }
251
371
  }
252
372
 
@@ -254,19 +374,46 @@ export const pushOut = (center: Vec2, radius: number, boxes: ReadonlyArray<Box2>
254
374
  * Moves a circle by `delta`, stopping at walls and sliding along them (up to
255
375
  * four contacts per call). The whole path is swept, so no displacement can
256
376
  * tunnel through a wall. A circle that starts inside a wall is pushed out
257
- * first. A circle meeting a box's corner dead-on goes around it rather than
258
- * stopping against it.
377
+ * first. A circle meeting a box's corner or a segment's end dead-on goes
378
+ * around it rather than stopping against it.
379
+ *
380
+ * @example
381
+ * ```ts
382
+ * // A map traced from survey data: every wall is a segment.
383
+ * const moved = Collide2.moveCircle(position, delta, radius, { segments: nearbyWalls })
384
+ * ```
259
385
  *
260
386
  * @category Movement
261
387
  */
262
- export const moveCircle = (start: Vec2, delta: Vec2, radius: number, boxes: ReadonlyArray<Box2>, skin: number = defaultSkin): MoveResult => {
263
- let position = pushOut(start, radius, boxes, skin)
388
+ export const moveCircle = (start: Vec2, delta: Vec2, radius: number, walls: Walls, skin: number = defaultSkin): MoveResult => {
389
+ let position = pushOut(start, radius, walls, skin)
264
390
  let rx = delta.x
265
391
  let ry = delta.y
266
392
  let blocked = false
267
393
  for (let iteration = 0; iteration < 4; iteration++) {
268
394
  if (rx * rx + ry * ry < 1e-12) break
269
- const hit = sweepCircleBoxes(position, { x: rx, y: ry }, radius, boxes)
395
+ const step = { x: rx, y: ry }
396
+ // The first contact, and whether it is round (a box's corner or a
397
+ // segment's end) rather than a flat side.
398
+ let hit: Hit | undefined
399
+ let round = false
400
+ for (const box of walls.boxes ?? noBoxes) {
401
+ const found = sweepCircleBox(position, step, radius, box)
402
+ if (found === undefined || (hit !== undefined && found.time >= hit.time)) continue
403
+ hit = found
404
+ round = found.nx !== 0 && found.ny !== 0
405
+ }
406
+ for (const segment of walls.segments ?? noSegments) {
407
+ const found = sweepCircleSegment(position, step, radius, segment)
408
+ if (found === undefined || (hit !== undefined && found.time >= hit.time)) continue
409
+ hit = found
410
+ const ex = segment.bx - segment.ax
411
+ const ey = segment.by - segment.ay
412
+ const lengthSquared = ex * ex + ey * ey
413
+ const along = found.nx * ex + found.ny * ey
414
+ // A flat side's normal is perpendicular to the segment.
415
+ round = lengthSquared < 1e-12 || along * along > 1e-18 * lengthSquared
416
+ }
270
417
  if (hit === undefined) {
271
418
  position = { x: position.x + rx, y: position.y + ry }
272
419
  break
@@ -284,10 +431,10 @@ export const moveCircle = (start: Vec2, delta: Vec2, radius: number, boxes: Read
284
431
  if (into < 0) {
285
432
  rx -= into * hit.nx
286
433
  ry -= into * hit.ny
287
- // Dead-on into a rounded corner (as an exact diagonal meets an
288
- // axis-aligned box) nothing is left to slide along: go around the
289
- // corner instead of stopping against it.
290
- if (hit.nx !== 0 && hit.ny !== 0 && rx * rx + ry * ry < 1e-12 * into * into) {
434
+ // Dead-on into a rounded corner or end (as an exact diagonal meets an
435
+ // axis-aligned box) nothing is left to slide along: go around it
436
+ // instead of stopping against it.
437
+ if (round && rx * rx + ry * ry < 1e-12 * into * into) {
291
438
  const side = rx * -hit.ny + ry * hit.nx < 0 ? -1 : 1
292
439
  rx = -hit.ny * -into * side
293
440
  ry = hit.nx * -into * side
package/src/FlowField.ts CHANGED
@@ -14,7 +14,9 @@
14
14
  *
15
15
  * @example
16
16
  * ```ts
17
- * const paths = FlowField.make(cellSize)
17
+ * const made = FlowField.make(cellSize)
18
+ * if (!made.ok) return made
19
+ * const paths = made.value
18
20
  * // Each step:
19
21
  * paths.setWalls(walls, bodyRadius)
20
22
  * paths.setGoal(player)
@@ -30,9 +32,9 @@
30
32
  * @categoryDescription Construction
31
33
  * Making a flow field.
32
34
  */
35
+ import * as Ops from "@typeonce/ritmo/Ops"
36
+ import * as Result from "@typeonce/ritmo/Result"
33
37
  import { type Box2, overlapsCircle } from "./Box2.ts"
34
- import * as Ops from "./Ops.ts"
35
- import type * as Scalar from "./Scalar.ts"
36
38
  import type { Vec2 } from "./Vec2.ts"
37
39
 
38
40
  /**
@@ -41,8 +43,8 @@ import type { Vec2 } from "./Vec2.ts"
41
43
  * @category Field Types
42
44
  */
43
45
  export interface FlowField {
44
- /** The side of one square cell, in world units. */
45
- readonly cellSize: Scalar.Positive
46
+ /** The side of one square cell, in world units: finite and above 0. */
47
+ readonly cellSize: number
46
48
  /**
47
49
  * Takes `boxes` as the walls, blocking every cell whose center is within
48
50
  * `clearance` of one, over the area the walls span. Does nothing when the
@@ -72,7 +74,7 @@ const stepY = Int8Array.of(0, 0, 1, -1, 1, -1, 1, -1)
72
74
  const stepCost = Float64Array.of(1, 1, 1, 1, Math.SQRT2, Math.SQRT2, Math.SQRT2, Math.SQRT2)
73
75
 
74
76
  class Field implements FlowField {
75
- readonly cellSize: Scalar.Positive
77
+ readonly cellSize: number
76
78
  private columns = 0
77
79
  private rows = 0
78
80
  private originX = 0
@@ -90,7 +92,7 @@ class Field implements FlowField {
90
92
  private keys = new Float64Array(0)
91
93
  private queued = 0
92
94
 
93
- constructor(cellSize: Scalar.Positive) {
95
+ constructor(cellSize: number) {
94
96
  this.cellSize = cellSize
95
97
  }
96
98
 
@@ -269,11 +271,33 @@ class Field implements FlowField {
269
271
  }
270
272
  }
271
273
 
274
+ /**
275
+ * Why {@link make} made no flow field: `value`, the cell size it was given,
276
+ * is not a finite number above 0.
277
+ *
278
+ * @category Construction
279
+ */
280
+ export interface InvalidCellSize {
281
+ readonly _tag: "InvalidCellSize"
282
+ readonly value: number
283
+ }
284
+
272
285
  /**
273
286
  * An empty flow field (no walls, no goal) with square cells of `cellSize`
274
- * world units. Smaller cells follow walls more closely and cost more to
275
- * search; around a body's diameter is a good start.
287
+ * world units, or `InvalidCellSize` when `cellSize` is not a finite number
288
+ * above 0. Smaller cells follow walls more closely and cost more to search;
289
+ * around a body's diameter is a good start. Make it once (in a service or a
290
+ * system's setup) and reuse it every step.
291
+ *
292
+ * @example
293
+ * ```ts
294
+ * const paths = FlowField.make(30)
295
+ * if (!paths.ok) throw new Error(`bad cell size ${paths.error.value}`)
296
+ * ```
276
297
  *
277
298
  * @category Construction
278
299
  */
279
- export const make = (cellSize: Scalar.Positive): FlowField => new Field(cellSize)
300
+ export const make = (cellSize: number): Result.Result<FlowField, InvalidCellSize> =>
301
+ cellSize > 0 && cellSize < Infinity
302
+ ? Result.success(new Field(cellSize))
303
+ : Result.failure({ _tag: "InvalidCellSize", value: cellSize })