@typeonce/ritmo-math 0.14.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 (108) hide show
  1. package/CHANGELOG.md +104 -0
  2. package/README.md +17 -12
  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 +11 -1
  12. package/dist/Collide2.d.ts.map +1 -1
  13. package/dist/Collide2.js +16 -1
  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/Vec2.d.ts +47 -7
  24. package/dist/Vec2.d.ts.map +1 -1
  25. package/dist/Vec2.js +56 -8
  26. package/dist/Vec2.js.map +1 -1
  27. package/dist/index.d.ts +9 -22
  28. package/dist/index.d.ts.map +1 -1
  29. package/dist/index.js +9 -22
  30. package/dist/index.js.map +1 -1
  31. package/package.json +3 -3
  32. package/src/Angle.ts +60 -0
  33. package/src/Box2.ts +20 -4
  34. package/src/Collide2.ts +18 -2
  35. package/src/FlowField.ts +34 -10
  36. package/src/Scalar.ts +43 -165
  37. package/src/Vec2.ts +58 -8
  38. package/src/index.ts +9 -22
  39. package/dist/Aabb.d.ts +0 -182
  40. package/dist/Aabb.d.ts.map +0 -1
  41. package/dist/Aabb.js +0 -109
  42. package/dist/Aabb.js.map +0 -1
  43. package/dist/InputAxis.d.ts +0 -44
  44. package/dist/InputAxis.d.ts.map +0 -1
  45. package/dist/InputAxis.js +0 -71
  46. package/dist/InputAxis.js.map +0 -1
  47. package/dist/Ops.d.ts +0 -209
  48. package/dist/Ops.d.ts.map +0 -1
  49. package/dist/Ops.js +0 -210
  50. package/dist/Ops.js.map +0 -1
  51. package/dist/Random.d.ts +0 -124
  52. package/dist/Random.d.ts.map +0 -1
  53. package/dist/Random.js +0 -126
  54. package/dist/Random.js.map +0 -1
  55. package/dist/Size2.d.ts +0 -118
  56. package/dist/Size2.d.ts.map +0 -1
  57. package/dist/Size2.js +0 -54
  58. package/dist/Size2.js.map +0 -1
  59. package/dist/SpatialGrid.d.ts +0 -68
  60. package/dist/SpatialGrid.d.ts.map +0 -1
  61. package/dist/SpatialGrid.js +0 -112
  62. package/dist/SpatialGrid.js.map +0 -1
  63. package/dist/Vector2.d.ts +0 -214
  64. package/dist/Vector2.d.ts.map +0 -1
  65. package/dist/Vector2.js +0 -134
  66. package/dist/Vector2.js.map +0 -1
  67. package/dist/internal/aabb.d.ts +0 -27
  68. package/dist/internal/aabb.d.ts.map +0 -1
  69. package/dist/internal/aabb.js +0 -52
  70. package/dist/internal/aabb.js.map +0 -1
  71. package/dist/internal/codec.d.ts +0 -9
  72. package/dist/internal/codec.d.ts.map +0 -1
  73. package/dist/internal/codec.js +0 -16
  74. package/dist/internal/codec.js.map +0 -1
  75. package/dist/internal/fdlibm.d.ts +0 -43
  76. package/dist/internal/fdlibm.d.ts.map +0 -1
  77. package/dist/internal/fdlibm.js +0 -1291
  78. package/dist/internal/fdlibm.js.map +0 -1
  79. package/dist/internal/inputAxis.d.ts +0 -11
  80. package/dist/internal/inputAxis.d.ts.map +0 -1
  81. package/dist/internal/inputAxis.js +0 -13
  82. package/dist/internal/inputAxis.js.map +0 -1
  83. package/dist/internal/scalar.d.ts +0 -11
  84. package/dist/internal/scalar.d.ts.map +0 -1
  85. package/dist/internal/scalar.js +0 -68
  86. package/dist/internal/scalar.js.map +0 -1
  87. package/dist/internal/size2.d.ts +0 -22
  88. package/dist/internal/size2.d.ts.map +0 -1
  89. package/dist/internal/size2.js +0 -38
  90. package/dist/internal/size2.js.map +0 -1
  91. package/dist/internal/vector2.d.ts +0 -39
  92. package/dist/internal/vector2.d.ts.map +0 -1
  93. package/dist/internal/vector2.js +0 -78
  94. package/dist/internal/vector2.js.map +0 -1
  95. package/src/Aabb.ts +0 -180
  96. package/src/InputAxis.ts +0 -81
  97. package/src/Ops.ts +0 -232
  98. package/src/Random.ts +0 -225
  99. package/src/Size2.ts +0 -122
  100. package/src/SpatialGrid.ts +0 -172
  101. package/src/Vector2.ts +0 -216
  102. package/src/internal/aabb.ts +0 -81
  103. package/src/internal/codec.ts +0 -21
  104. package/src/internal/fdlibm.ts +0 -1256
  105. package/src/internal/inputAxis.ts +0 -21
  106. package/src/internal/scalar.ts +0 -104
  107. package/src/internal/size2.ts +0 -54
  108. package/src/internal/vector2.ts +0 -121
package/src/InputAxis.ts DELETED
@@ -1,81 +0,0 @@
1
- /**
2
- * Pure helpers for normalizing boolean directional input into typed axes and
3
- * movement vectors.
4
- *
5
- * This module is runtime-agnostic: it does not know about keyboard events,
6
- * gamepads, or host APIs. It only translates already-sampled booleans into the
7
- * compact movement values that systems consume.
8
- *
9
- * Reach for it in the gap between host input sampling and ECS simulation:
10
- * capture raw button state in the host, normalize it here, then write the
11
- * resulting axes or vectors into resources/components for systems to consume.
12
- * With `@typeonce/ritmo-browser`, bind movement as a vector action instead
13
- * (`Keyboard.vector`, `Gamepad.vector`), which already reports the merged
14
- * vector; use this module for booleans from another source.
15
- *
16
- * @example
17
- * ```ts
18
- * // Normalize one sampled host input snapshot into a movement vector.
19
- * const movement = InputAxis.vectorFromAxes({
20
- * left: false,
21
- * right: true,
22
- * up: false,
23
- * down: false
24
- * })
25
- * ```
26
- *
27
- * @module InputAxis
28
- * @docGroup helpers
29
- *
30
- * @categoryDescription Input Types
31
- * Small shared types that describe normalized axis values.
32
- *
33
- * @categoryDescription Axis Helpers
34
- * Pure helpers that reduce opposing booleans to one explicit signed movement axis.
35
- *
36
- * @categoryDescription Vector Helpers
37
- * Runtime-agnostic helpers that derive branded movement vectors from normalized input.
38
- */
39
- import * as internal from "./internal/inputAxis.ts"
40
- import type * as Vector2 from "./Vector2.ts"
41
-
42
- /**
43
- * Canonical one-dimensional movement axis.
44
- *
45
- * @category Input Types
46
- */
47
- export type Axis = -1 | 0 | 1
48
-
49
- /**
50
- * Derives one signed axis from two opposing booleans.
51
- *
52
- * @category Axis Helpers
53
- */
54
- export const axis: (negativePressed: boolean, positivePressed: boolean) => Axis = internal.axis
55
- /**
56
- * Builds a normalized movement vector from four directional booleans, in
57
- * screen coordinates: `up` is negative `y`, `right` positive `x`. Opposite
58
- * presses cancel, and diagonals have length 1.
59
- *
60
- * @example
61
- * ```ts
62
- * const direction = InputAxis.vectorFromAxes({
63
- * left: false,
64
- * right: true,
65
- * up: false,
66
- * down: true
67
- * })
68
- * ```
69
- *
70
- * @category Vector Helpers
71
- */
72
- export const vectorFromAxes: (
73
- input: { readonly left: boolean; readonly right: boolean; readonly up: boolean; readonly down: boolean }
74
- ) => Vector2.Vector2 = internal.vectorFromAxes
75
- /**
76
- * Builds a normalized movement vector from two explicit axis values
77
- * (diagonals have length 1).
78
- *
79
- * @category Vector Helpers
80
- */
81
- export const vectorFromAxisValues: (horizontal: Axis, vertical: Axis) => Vector2.Vector2 = internal.vectorFromAxisValues
package/src/Ops.ts DELETED
@@ -1,232 +0,0 @@
1
- /**
2
- * Math functions that return the same bits on every JavaScript engine and
3
- * CPU, so a simulation replays exactly on any device.
4
- *
5
- * The spec lets engines approximate `Math.sin`, `cos`, `tan`, `asin`, `acos`,
6
- * `atan`, `atan2`, `exp`, `expm1`, `log`, `log2`, `log10`, `log1p`, `sinh`,
7
- * `cosh`, `tanh`, `asinh`, `acosh`, `atanh`, `cbrt`, `pow`, `hypot`, and
8
- * `a ** b`, and they do: Chrome, Safari, macOS, and Linux disagree in the
9
- * last bit, and a simulation grows that bit into a different run. Use these
10
- * in simulation code instead; each is a pure-JavaScript port of fdlibm (musl
11
- * libm) built only from operations every engine rounds exactly.
12
- *
13
- * Keep using `Math.abs`, `sign`, `min`, `max`, `floor`, `ceil`, `round`,
14
- * `trunc`, `sqrt`, `imul`, `fround`, `+ - * /`, and `x ** 2`: they are
15
- * already exact everywhere. Use `Random` for randomness and `Clock` for time.
16
- * Code that only draws (rendering, effects) can use `Math` freely. The
17
- * `ritmo/use-ops-for-math` rule (`@typeonce/oxlint-plugin-ritmo`) points
18
- * simulation code here.
19
- *
20
- * @example
21
- * ```ts
22
- * // Inside a system: aim, then move along the heading.
23
- * const heading = Ops.atan2(target.y - position.y, target.x - position.x)
24
- * const step = { x: Ops.cos(heading) * speed * dt, y: Ops.sin(heading) * speed * dt }
25
- * const damping = Ops.exp(-friction * dt)
26
- * ```
27
- *
28
- * @module Ops
29
- * @docGroup helpers
30
- *
31
- * @categoryDescription Trigonometry
32
- * Sine, cosine, tangent, and their inverses, in radians.
33
- *
34
- * @categoryDescription Exponentials
35
- * Exponentials, logarithms, powers, and roots.
36
- *
37
- * @categoryDescription Hyperbolic
38
- * Hyperbolic functions and their inverses.
39
- *
40
- * @categoryDescription Lengths
41
- * Euclidean length without overflow.
42
- */
43
-
44
- import * as fdlibm from "./internal/fdlibm.ts"
45
-
46
- /**
47
- * Sine of `x` radians. Same bits on every engine (within 1 ulp of the exact
48
- * value); use instead of `Math.sin` in simulation code.
49
- *
50
- * @category Trigonometry
51
- */
52
- export const sin: (x: number) => number = fdlibm.sin
53
-
54
- /**
55
- * Cosine of `x` radians. Same bits on every engine (within 1 ulp of the
56
- * exact value); use instead of `Math.cos` in simulation code.
57
- *
58
- * @category Trigonometry
59
- */
60
- export const cos: (x: number) => number = fdlibm.cos
61
-
62
- /**
63
- * Tangent of `x` radians. Same bits on every engine (within 1 ulp of the
64
- * exact value); use instead of `Math.tan` in simulation code.
65
- *
66
- * @category Trigonometry
67
- */
68
- export const tan: (x: number) => number = fdlibm.tan
69
-
70
- /**
71
- * Arcsine of `x` in radians, in [-π/2, π/2]; NaN outside [-1, 1]. Same bits
72
- * on every engine; use instead of `Math.asin` in simulation code.
73
- *
74
- * @category Trigonometry
75
- */
76
- export const asin: (x: number) => number = fdlibm.asin
77
-
78
- /**
79
- * Arccosine of `x` in radians, in [0, π]; NaN outside [-1, 1]. Same bits on
80
- * every engine; use instead of `Math.acos` in simulation code.
81
- *
82
- * @category Trigonometry
83
- */
84
- export const acos: (x: number) => number = fdlibm.acos
85
-
86
- /**
87
- * Arctangent of `x` in radians, in (-π/2, π/2). Same bits on every engine;
88
- * use instead of `Math.atan` in simulation code. For the angle of a vector,
89
- * use `atan2`.
90
- *
91
- * @category Trigonometry
92
- */
93
- export const atan: (x: number) => number = fdlibm.atan
94
-
95
- /**
96
- * The angle of the vector (x, y) in radians, in [-π, π] (note the argument
97
- * order: `y` first, like `Math.atan2`). Same bits on every engine; use
98
- * instead of `Math.atan2` in simulation code.
99
- *
100
- * @category Trigonometry
101
- */
102
- export const atan2: (y: number, x: number) => number = fdlibm.atan2
103
-
104
- /**
105
- * e raised to `x`. Same bits on every engine (within 1 ulp of the exact
106
- * value); use instead of `Math.exp` in simulation code, for example for
107
- * frame-rate independent damping `exp(-rate * dt)`.
108
- *
109
- * @category Exponentials
110
- */
111
- export const exp: (x: number) => number = fdlibm.exp
112
-
113
- /**
114
- * Hyperbolic tangent of `x`, in [-1, 1]. Same bits on every engine (within 2
115
- * ulp of the exact value, like the native one); use instead of `Math.tanh` in
116
- * simulation code.
117
- *
118
- * @category Hyperbolic
119
- */
120
- export const tanh: (x: number) => number = fdlibm.tanh
121
-
122
- /**
123
- * e raised to `x`, minus 1, accurate for `x` near 0 (where `exp(x) - 1` loses
124
- * digits). Same bits on every engine; use instead of `Math.expm1` in
125
- * simulation code.
126
- *
127
- * @category Exponentials
128
- */
129
- export const expm1: (x: number) => number = fdlibm.expm1
130
-
131
- /**
132
- * Natural logarithm of `x`: -Infinity at 0, NaN below 0. Same bits on every
133
- * engine (within 1 ulp of the exact value); use instead of `Math.log` in
134
- * simulation code.
135
- *
136
- * @category Exponentials
137
- */
138
- export const log: (x: number) => number = fdlibm.log
139
-
140
- /**
141
- * Base-2 logarithm of `x`: -Infinity at 0, NaN below 0, exact for powers of
142
- * two. Same bits on every engine; use instead of `Math.log2` in simulation
143
- * code.
144
- *
145
- * @category Exponentials
146
- */
147
- export const log2: (x: number) => number = fdlibm.log2
148
-
149
- /**
150
- * Base-10 logarithm of `x`: -Infinity at 0, NaN below 0. Same bits on every
151
- * engine; use instead of `Math.log10` in simulation code.
152
- *
153
- * @category Exponentials
154
- */
155
- export const log10: (x: number) => number = fdlibm.log10
156
-
157
- /**
158
- * Natural logarithm of `1 + x`, accurate for `x` near 0 (where `log(1 + x)`
159
- * loses digits). Same bits on every engine; use instead of `Math.log1p` in
160
- * simulation code.
161
- *
162
- * @category Exponentials
163
- */
164
- export const log1p: (x: number) => number = fdlibm.log1p
165
-
166
- /**
167
- * Cube root of `x`, negative for negative `x`. Same bits on every engine;
168
- * use instead of `Math.cbrt` and `x ** (1 / 3)` in simulation code.
169
- *
170
- * @category Exponentials
171
- */
172
- export const cbrt: (x: number) => number = fdlibm.cbrt
173
-
174
- /**
175
- * `base` raised to `exponent`, with the results of `base ** exponent` for
176
- * every special case (NaN, zeros, infinities, negative bases). Same bits on
177
- * every engine (within 1 ulp of the exact value); use instead of `Math.pow`
178
- * and `**` in simulation code. `x * x` and `x ** 2` are already exact.
179
- *
180
- * @category Exponentials
181
- */
182
- export const pow: (base: number, exponent: number) => number = fdlibm.pow
183
-
184
- /**
185
- * Hyperbolic sine of `x`. Same bits on every engine (within 1 ulp of the
186
- * exact value); use instead of `Math.sinh` in simulation code.
187
- *
188
- * @category Hyperbolic
189
- */
190
- export const sinh: (x: number) => number = fdlibm.sinh
191
-
192
- /**
193
- * Hyperbolic cosine of `x`, at least 1. Same bits on every engine (within 1
194
- * ulp of the exact value); use instead of `Math.cosh` in simulation code.
195
- *
196
- * @category Hyperbolic
197
- */
198
- export const cosh: (x: number) => number = fdlibm.cosh
199
-
200
- /**
201
- * Inverse hyperbolic sine of `x`. Same bits on every engine; use instead of
202
- * `Math.asinh` in simulation code.
203
- *
204
- * @category Hyperbolic
205
- */
206
- export const asinh: (x: number) => number = fdlibm.asinh
207
-
208
- /**
209
- * Inverse hyperbolic cosine of `x`: NaN below 1. Same bits on every engine;
210
- * use instead of `Math.acosh` in simulation code.
211
- *
212
- * @category Hyperbolic
213
- */
214
- export const acosh: (x: number) => number = fdlibm.acosh
215
-
216
- /**
217
- * Inverse hyperbolic tangent of `x`: ±Infinity at ±1, NaN beyond. Same bits
218
- * on every engine; use instead of `Math.atanh` in simulation code.
219
- *
220
- * @category Hyperbolic
221
- */
222
- export const atanh: (x: number) => number = fdlibm.atanh
223
-
224
- /**
225
- * The length of the vector (x, y), `sqrt(x² + y²)` without overflow or
226
- * underflow. Same bits on every engine (within 1 ulp of the exact value);
227
- * use instead of `Math.hypot` in simulation code. Takes exactly two numbers;
228
- * for vectors use `Vec2.length` and `Vec2.distance`.
229
- *
230
- * @category Lengths
231
- */
232
- export const hypot: (x: number, y: number) => number = fdlibm.hypot
package/src/Random.ts DELETED
@@ -1,225 +0,0 @@
1
- /**
2
- * Deterministic random numbers (mulberry32) whose whole state is one 32-bit
3
- * integer.
4
- *
5
- * Keep the state in a resource, so a run replays exactly and saves with the
6
- * world: declare it with `Random.codec` as its schema, start it with
7
- * `seed`, and draw in systems through `draw` over its write cell, which writes
8
- * every draw back (rolled back with a failed system). Two generators made
9
- * from the same state draw the same sequence on every platform. `make` is for
10
- * a state that lives outside the world (a level generator seeded once).
11
- *
12
- * @example
13
- * ```ts
14
- * const Rng = Descriptor.ConstructedResource(Random.codec)("Game/Rng")
15
- * const runtime = Game.Runtime.make({ services, resources: { Rng: Random.seed(0x5eed) } })
16
- *
17
- * Game.System("Game/Spawn", { resources: { rng: Game.System.writeResource(Rng) } }, ({ resources }) => {
18
- * const random = Random.draw(resources.rng)
19
- * const angle = random.range(0, Math.PI * 2)
20
- * const kind = random.pick(kinds) ?? "grunt"
21
- * })
22
- * ```
23
- *
24
- * @module Random
25
- * @docGroup helpers
26
- *
27
- * @categoryDescription Random Types
28
- * The generator interface.
29
- *
30
- * @categoryDescription Construction
31
- * Making a generator from a stored state.
32
- *
33
- * @categoryDescription Resource
34
- * Keeping the state in a world resource.
35
- */
36
- import type * as Brand from "@typeonce/ritmo/Brand"
37
- import type { WriteCell } from "@typeonce/ritmo/Query"
38
- import type { StandardSchema } from "@typeonce/ritmo/Descriptor"
39
- import * as Result from "@typeonce/ritmo/Result"
40
- import { codecOf } from "./internal/codec.ts"
41
-
42
- /**
43
- * A generator. Every draw advances `state`.
44
- *
45
- * @category Random Types
46
- */
47
- export interface Random {
48
- /** The current state: an unsigned 32-bit integer. Store it to continue the sequence later. */
49
- readonly state: number
50
- /** Uniform in [0, 1). */
51
- next(): number
52
- /** Uniform in [min, max), or `min` when they are equal. Throws when `min > max` or a bound is not finite. */
53
- range(min: number, max: number): number
54
- /** A uniform integer in [min, maxExclusive). Throws unless both bounds are integers with min < maxExclusive. */
55
- integer(min: number, maxExclusive: number): number
56
- /** A uniform element of `items`, or `undefined` when it is empty (no draw is made then). */
57
- pick<A>(items: ReadonlyArray<A>): A | undefined
58
- /** A shuffled copy of `items` (Fisher–Yates). */
59
- shuffle<A>(items: ReadonlyArray<A>): Array<A>
60
- /**
61
- * An element of `items` chosen with probability proportional to `weight`,
62
- * or `undefined` when no element has a positive finite weight (no draw is
63
- * made then). Elements with zero, negative, or non-finite weight are never
64
- * chosen. `weight` is called once per element.
65
- */
66
- weighted<A>(items: ReadonlyArray<A>, weight: (item: A) => number): A | undefined
67
- }
68
-
69
- const usable = (weight: number): boolean => weight > 0 && weight < Infinity
70
-
71
- class Mulberry32 implements Random {
72
- state: number
73
-
74
- constructor(state: number) {
75
- this.state = state >>> 0
76
- }
77
-
78
- next(): number {
79
- this.state = (this.state + 0x6d2b79f5) >>> 0
80
- let t = this.state
81
- t = Math.imul(t ^ (t >>> 15), t | 1)
82
- t ^= t + Math.imul(t ^ (t >>> 7), t | 61)
83
- return ((t ^ (t >>> 14)) >>> 0) / 4294967296
84
- }
85
-
86
- range(min: number, max: number): number {
87
- if (!(Number.isFinite(min) && Number.isFinite(max) && min <= max)) {
88
- throw new Error(`Random.range needs finite bounds with min <= max, got [${min}, ${max})`)
89
- }
90
- return min + (max - min) * this.next()
91
- }
92
-
93
- integer(min: number, maxExclusive: number): number {
94
- if (!(Number.isSafeInteger(min) && Number.isSafeInteger(maxExclusive) && min < maxExclusive)) {
95
- throw new Error(`Random.integer needs whole bounds with min below maxExclusive, got [${min}, ${maxExclusive})`)
96
- }
97
- return min + Math.floor(this.next() * (maxExclusive - min))
98
- }
99
-
100
- pick<A>(items: ReadonlyArray<A>): A | undefined {
101
- return items.length === 0 ? undefined : items[Math.floor(this.next() * items.length)]
102
- }
103
-
104
- shuffle<A>(items: ReadonlyArray<A>): Array<A> {
105
- const shuffled = items.slice()
106
- for (let index = shuffled.length - 1; index > 0; index--) {
107
- const other = Math.floor(this.next() * (index + 1))
108
- const swap = shuffled[index]!
109
- shuffled[index] = shuffled[other]!
110
- shuffled[other] = swap
111
- }
112
- return shuffled
113
- }
114
-
115
- weighted<A>(items: ReadonlyArray<A>, weight: (item: A) => number): A | undefined {
116
- // `weight` is called once per item: it may be costly or not pure.
117
- const weights = items.map(weight)
118
- let total = 0
119
- for (const value of weights) {
120
- if (usable(value)) total += value
121
- }
122
- if (!usable(total)) return undefined
123
- let roll = this.next() * total
124
- let last: A | undefined
125
- for (let index = 0; index < items.length; index++) {
126
- const value = weights[index]!
127
- if (!usable(value)) continue
128
- last = items[index]
129
- roll -= value
130
- if (roll < 0) return items[index]
131
- }
132
- // Rounding can leave a sliver of the roll past the last bucket.
133
- return last
134
- }
135
- }
136
-
137
- /**
138
- * A generator continuing from `state`. Any number is accepted and reduced to
139
- * an unsigned 32-bit integer (`state >>> 0`), so a stored state round-trips
140
- * exactly.
141
- *
142
- * @category Construction
143
- */
144
- export const make = (state: number): Random => new Mulberry32(state)
145
-
146
- /**
147
- * A generator's state as a resource holds it: an unsigned 32-bit integer.
148
- * Only `seed`, `result`, and `codec` make one, so `draw` takes the cell of a
149
- * random resource and nothing else.
150
- *
151
- * @category Resource
152
- */
153
- export type State = Brand.Branded<number, "Random/State">
154
-
155
- /** Why a value is not a generator state. @category Resource */
156
- export interface InvalidState {
157
- readonly _tag: "InvalidRandomState"
158
- readonly value: unknown
159
- }
160
-
161
- const isState = (value: unknown): value is State =>
162
- typeof value === "number" && Number.isInteger(value) && value >= 0 && value <= 0xffffffff
163
-
164
- /**
165
- * Validates a state, for game code that builds one from a number.
166
- *
167
- * @category Resource
168
- */
169
- export const result = (raw: number): Result.Result<State, InvalidState> =>
170
- isState(raw) ? Result.success(raw) : Result.failure({ _tag: "InvalidRandomState", value: raw })
171
-
172
- /**
173
- * Whether any value is a generator state: a guard, also for building a
174
- * state field in your own schema (`Schema.declare(Random.is)`).
175
- *
176
- * @category Resource
177
- */
178
- export const is = (raw: unknown): raw is State => isState(raw)
179
-
180
- /**
181
- * The codec of a random resource's state (a Standard Schema, see
182
- * `Descriptor.Codec`): `Descriptor.ConstructedResource(Random.codec)`. Its
183
- * saved form is the number itself, so it needs no `encode`.
184
- *
185
- * @category Resource
186
- */
187
- export const codec: StandardSchema<number, State> = codecOf<number, State>(
188
- (raw) => isState(raw) ? Result.success(raw) : Result.failure({ _tag: "InvalidRandomState", value: raw }),
189
- "a generator state: an unsigned 32-bit integer"
190
- )
191
-
192
- /**
193
- * The starting state for a seed, reduced to an unsigned 32-bit integer like
194
- * `make`: the value to give a random resource in `Game.Runtime.make`.
195
- *
196
- * @category Resource
197
- */
198
- export const seed = (value: number): State => (value >>> 0) as State
199
-
200
- class CellRandom extends Mulberry32 {
201
- readonly #cell: WriteCell<State>
202
-
203
- constructor(cell: WriteCell<State>) {
204
- super(cell.get())
205
- this.#cell = cell
206
- }
207
-
208
- override next(): number {
209
- // Read the cell each time, so two generators over one cell share one sequence.
210
- this.state = this.#cell.get()
211
- const value = super.next()
212
- this.#cell.set(this.state as State)
213
- return value
214
- }
215
- }
216
-
217
- /**
218
- * A generator over a random resource's write cell: every draw continues from
219
- * the stored state and writes the new one back, so the system needs no
220
- * `set` of its own, a failed run rolls the draws back, and generators made
221
- * from the same cell in one run continue one sequence.
222
- *
223
- * @category Resource
224
- */
225
- export const draw = (cell: WriteCell<State>): Random => new CellRandom(cell)
package/src/Size2.ts DELETED
@@ -1,122 +0,0 @@
1
- /**
2
- * Branded two-dimensional sizes with explicit validation.
3
- *
4
- * Sizes model non-negative width/height pairs and are commonly used for
5
- * colliders, viewports, and AABB dimensions.
6
- *
7
- * Reach for this module when authored or host-provided dimensions should be
8
- * validated once and then carried through gameplay code, runtime bootstrap, or
9
- * geometry helpers without repeating non-negative checks everywhere.
10
- *
11
- * @example
12
- * ```ts
13
- * // Validate raw viewport dimensions before storing or reusing them.
14
- * const viewport = Size2.result({ width: 800, height: 600 })
15
- * if (!viewport.ok) return
16
- *
17
- * // Read the branded size later without rechecking width/height validity.
18
- * const width = Size2.width(viewport.value)
19
- * ```
20
- *
21
- * @module Size2
22
- * @docGroup data-structures
23
- *
24
- * @categoryDescription Size Types
25
- * Raw, branded, and error shapes for validated two-dimensional sizes.
26
- *
27
- * @categoryDescription Construction
28
- * Non-throwing constructor boundaries that validate raw width and height input.
29
- *
30
- * @categoryDescription Accessors
31
- * Pure readers and raw views over already-validated size values.
32
- */
33
- import type * as Brand from "@typeonce/ritmo/Brand"
34
- import type { StandardSchema } from "@typeonce/ritmo/Descriptor"
35
- import * as internal from "./internal/size2.ts"
36
- import type * as Result from "@typeonce/ritmo/Result"
37
- import type * as Scalar from "./Scalar.ts"
38
-
39
- /**
40
- * Raw size input accepted by the public constructors.
41
- *
42
- * @category Size Types
43
- */
44
- export type Raw = {
45
- readonly width: number
46
- readonly height: number
47
- }
48
-
49
- /**
50
- * Validated non-negative width/height pair.
51
- *
52
- * @category Size Types
53
- */
54
- export type Size2 = Brand.Branded<{
55
- readonly width: Scalar.NonNegative
56
- readonly height: Scalar.NonNegative
57
- }, "Size2">
58
-
59
- /**
60
- * Structured size-construction failure.
61
- *
62
- * @category Size Types
63
- */
64
- export type Error = {
65
- readonly tag: "Size2/Invalid"
66
- readonly width: Scalar.Error | null
67
- readonly height: Scalar.Error | null
68
- readonly input: Raw
69
- }
70
-
71
- /**
72
- * Validates one raw size and returns an explicit result.
73
- *
74
- * @category Construction
75
- */
76
- export const result: (raw: Raw) => Result.Result<Size2, Error> = internal.result
77
- /**
78
- * The codec of `Size2` (a Standard Schema, see `Descriptor.Codec`): give it to
79
- * `Descriptor.ConstructedComponent(...)` so raw input and saves are validated.
80
- * Its saved form is the raw shape, so it needs no `encode`. To put a `Size2`
81
- * inside your own object schema, use {@link is} with your library's guard
82
- * schema (`Schema.declare`, `z.custom`).
83
- *
84
- * @example
85
- * ```ts
86
- * const Position = Descriptor.ConstructedComponent(Size2.codec)("Game/Position")
87
- * ```
88
- *
89
- * @category Construction
90
- */
91
- export const codec: StandardSchema<Raw, Size2> = internal.codec
92
- /**
93
- * Validates one raw size and returns `null` on failure.
94
- *
95
- * @category Construction
96
- */
97
- export const option: (raw: Raw) => Size2 | null = internal.option
98
- /**
99
- * Whether any value is a valid `Size2`: a guard, also for building a
100
- * `Size2` field in your own schema (`Schema.declare(Size2.is)`).
101
- *
102
- * @category Construction
103
- */
104
- export const is: (raw: unknown) => raw is Size2 = internal.is
105
- /**
106
- * Converts one branded size back to a fresh raw object.
107
- *
108
- * @category Accessors
109
- */
110
- export const toRaw: (size: Size2) => Raw = internal.toRaw
111
- /**
112
- * Reads the width component of one branded size.
113
- *
114
- * @category Accessors
115
- */
116
- export const width: (size: Size2) => Scalar.NonNegative = internal.width
117
- /**
118
- * Reads the height component of one branded size.
119
- *
120
- * @category Accessors
121
- */
122
- export const height: (size: Size2) => Scalar.NonNegative = internal.height