@wildshard/shard-format 0.14.0 → 0.16.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.
@@ -0,0 +1,568 @@
1
+ /* oxlint-disable capitalized-comments, complexity, curly, id-length, import/exports-last, import/group-exports, import/no-namespace, init-declarations, max-lines, max-lines-per-function, max-params, max-statements, no-implicit-coercion, no-magic-numbers, no-negated-condition, no-nested-ternary, no-plusplus, oxc/erasing-op, sort-vars, typescript/explicit-function-return-type, typescript/no-unsafe-type-assertion, typescript/prefer-readonly-parameter-types, unicorn/max-nested-calls, unicorn/no-negated-condition, unicorn/no-nested-ternary, unicorn/no-zero-fractions, unicorn/number-literal-case, unicorn/numeric-separators-style, unicorn/prefer-modern-math-apis, unicorn/switch-case-braces -- verbatim port of the engine's law and three's arithmetic (SDK-SPLIT SP4); bit-exact output is pinned by golden vectors, so it keeps their form */
2
+ /**
3
+ * SDK-SPLIT SP4e2 (Q35): collider rows and how a pose places them, moved from engine `client/engine/models/colliders.ts`
4
+ * without three.js. The row grammar (`readColliderRows`) is verbatim; `poseOf` and `placeCollider` run three's own
5
+ * Matrix4 / Quaternion / Vector3 arithmetic, written out in the same operation order, so a placed collider is bit for bit
6
+ * the engine's (golden vectors). A pose's matrix is 16 numbers, column-major as three's `Matrix4.elements`. The engine keeps
7
+ * the geometry half (`poseGeometry`, the drawn hulls) and wraps these for its `THREE.Matrix4` placements.
8
+ */
9
+ import * as val from 'valibot'
10
+
11
+ interface Vec3 {
12
+ x: number
13
+ y: number
14
+ z: number
15
+ }
16
+ interface Quat {
17
+ x: number
18
+ y: number
19
+ z: number
20
+ w: number
21
+ }
22
+
23
+ /** How a collider is placed: a centre, and either a turn about +Y (three's convention) or a full rotation. */
24
+ interface Placed<S extends string> {
25
+ x: number
26
+ y: number
27
+ z: number
28
+ yaw?: number
29
+ rot?: Quat
30
+ surface?: S
31
+ }
32
+
33
+ /** A collider as engine-neutral data (the engine's registry `ColliderDesc`), over the host's surface names. */
34
+ export type ColliderDesc<S extends string = string> =
35
+ /** a box: half-extents along its own axes */
36
+ | (Placed<S> & { kind: 'box'; hx: number; hy: number; hz: number })
37
+ /** an upright capsule (or tilted by `rot`): the straight part's half-height, the radius */
38
+ | (Placed<S> & { kind: 'capsule'; halfHeight: number; radius: number })
39
+ | (Placed<S> & { kind: 'ball'; radius: number })
40
+ /** a convex hull of points given relative to (x, y, z) */
41
+ | (Placed<S> & { kind: 'hull'; points: Float32Array })
42
+ /** a triangle mesh relative to (x, y, z) — only where you walk inside or over irregular geometry */
43
+ | (Placed<S> & {
44
+ kind: 'trimesh'
45
+ vertices: Float32Array
46
+ indices: Uint32Array
47
+ })
48
+ /**
49
+ * a stair: `count` boxes rising `rise` each from `from` (the foot of the first tread) toward `to` (the top edge,
50
+ * at from.y + count × rise), `width` across — built as treads, never as a ramp (PHYSICS.md: autostep climbs them).
51
+ */
52
+ | {
53
+ kind: 'treads'
54
+ from: Vec3
55
+ to: Vec3
56
+ width: number
57
+ count: number
58
+ surface?: S
59
+ }
60
+
61
+ function finiteLaneValue(value: unknown): number {
62
+ if (typeof value !== 'number' || !Number.isFinite(value))
63
+ throw new Error('Collider values must be finite')
64
+ return value
65
+ }
66
+ function copyLane<T extends Float32Array | Uint32Array>(
67
+ values: readonly unknown[],
68
+ Storage: new (length: number) => T,
69
+ read: (value: unknown) => number,
70
+ ): T {
71
+ const count = values.length
72
+ if (!Number.isSafeInteger(count) || count < 0 || count > 6_000_000)
73
+ throw new Error('Collider geometry must be a bounded array')
74
+ const owned = new Storage(count)
75
+ // Use indexed facts, never a caller's custom iterator or a changing length.
76
+ for (let i = 0; i < count; i++) owned[i] = read(values[i])
77
+ return owned
78
+ }
79
+ function indexLaneValue(value: unknown): number {
80
+ if (
81
+ typeof value !== 'number' ||
82
+ !Number.isInteger(value) ||
83
+ value < 0 ||
84
+ value > 0xffff_ffff
85
+ )
86
+ throw new Error('Collider indices must fit Uint32')
87
+ return value
88
+ }
89
+
90
+ // H4: cache only the grammar, never admitted rows or caller-owned geometry.
91
+ // Compare surface values so mutation or a different policy cannot reuse a stale picklist.
92
+ function colliderSchema(surfaces: readonly string[]) {
93
+ const finite = val.pipe(
94
+ val.number('Collider values must be finite'),
95
+ val.finite('Collider values must be finite'),
96
+ )
97
+ const point = val.strictObject(
98
+ { x: finite, y: finite, z: finite },
99
+ 'Collider lacks an endpoint',
100
+ )
101
+ const surface = val.exactOptional(val.picklist(surfaces))
102
+ const at = {
103
+ x: finite,
104
+ y: finite,
105
+ z: finite,
106
+ yaw: val.exactOptional(finite),
107
+ rot: val.exactOptional(
108
+ val.strictObject({ x: finite, y: finite, z: finite, w: finite }),
109
+ ),
110
+ surface,
111
+ }
112
+ // Borrow bounded storage, then validate each value while copying it once.
113
+ // A lane accessor cannot change a checked value before its owned conversion.
114
+ const lane = val.custom<unknown[]>(
115
+ input => Array.isArray(input) && input.length <= 6_000_000,
116
+ 'Collider geometry must be a bounded array',
117
+ )
118
+ return val.variant('kind', [
119
+ val.strictObject({
120
+ kind: val.literal('box'),
121
+ ...at,
122
+ hx: finite,
123
+ hy: finite,
124
+ hz: finite,
125
+ }),
126
+ val.strictObject({
127
+ kind: val.literal('capsule'),
128
+ ...at,
129
+ halfHeight: finite,
130
+ radius: finite,
131
+ }),
132
+ val.strictObject({ kind: val.literal('ball'), ...at, radius: finite }),
133
+ val.strictObject({ kind: val.literal('hull'), ...at, points: lane }),
134
+ val.strictObject({
135
+ kind: val.literal('trimesh'),
136
+ ...at,
137
+ vertices: lane,
138
+ indices: lane,
139
+ }),
140
+ val.strictObject({
141
+ kind: val.literal('treads'),
142
+ from: point,
143
+ to: point,
144
+ width: finite,
145
+ count: val.pipe(finite, val.integer(), val.minValue(1)),
146
+ surface,
147
+ }),
148
+ ])
149
+ }
150
+ let recentGrammar:
151
+ | { surfaces: readonly string[]; schema: ReturnType<typeof colliderSchema> }
152
+ | undefined
153
+ function colliderGrammar(
154
+ surfaces: readonly string[],
155
+ ): ReturnType<typeof colliderSchema> {
156
+ const previous = recentGrammar
157
+ if (
158
+ previous !== undefined &&
159
+ surfaces.length === previous.surfaces.length &&
160
+ surfaces.every((surface, index) => surface === previous.surfaces[index])
161
+ )
162
+ return previous.schema
163
+ const owned = [...surfaces],
164
+ schema = colliderSchema(owned)
165
+ recentGrammar = { surfaces: owned, schema }
166
+ return schema
167
+ }
168
+
169
+ /** Decode fresh registry descriptors from serialized facts. Callers explicitly admit shape kinds and surfaces;
170
+ * absent surfaces stay absent, unless requireSurface is true. No physics objects are created here.
171
+ * At most 65,536 rows and 6,000,000 values per geometry lane are admitted; indices must fit Uint32. */
172
+ export function readColliderRows<S extends string>(
173
+ rows: readonly unknown[],
174
+ policy: {
175
+ readonly kinds: readonly ColliderDesc['kind'][]
176
+ readonly surfaces: readonly S[]
177
+ readonly requireSurface?: boolean
178
+ },
179
+ ): ColliderDesc<S>[] {
180
+ if (rows.length > 65_536) throw new Error('Collider row bound exceeded')
181
+ // Collision-free model copies need no shape grammar or policy traversal.
182
+ if (rows.length === 0) return []
183
+ const schema = colliderGrammar(policy.surfaces)
184
+ return rows.map(raw => {
185
+ if (
186
+ typeof raw !== 'object' ||
187
+ raw === null ||
188
+ !('kind' in raw) ||
189
+ !policy.kinds.some(kind => kind === raw.kind)
190
+ )
191
+ throw new Error('Unexpected collider shape')
192
+ const actual = 'surface' in raw ? raw.surface : undefined
193
+ if (
194
+ (actual === undefined && policy.requireSurface === true) ||
195
+ (actual !== undefined &&
196
+ !policy.surfaces.some(allowed => allowed === actual))
197
+ )
198
+ throw new Error('Unexpected collider surface')
199
+ // the picklist admitted only the policy's surfaces, so the row's surface is an S
200
+ const row = val.parse(schema, raw) as ColliderDescRow<S>
201
+ if (row.kind === 'hull')
202
+ return {
203
+ ...row,
204
+ points: copyLane(row.points, Float32Array, finiteLaneValue),
205
+ }
206
+ if (row.kind === 'trimesh')
207
+ return {
208
+ ...row,
209
+ vertices: copyLane(row.vertices, Float32Array, finiteLaneValue),
210
+ indices: copyLane(row.indices, Uint32Array, indexLaneValue),
211
+ }
212
+ return row
213
+ })
214
+ }
215
+ /** a parsed row before its lanes are copied into owned typed storage */
216
+ type ColliderDescRow<S extends string> =
217
+ | Exclude<ColliderDesc<S>, { kind: 'hull' | 'trimesh' }>
218
+ | (Placed<S> & { kind: 'hull'; points: unknown[] })
219
+ | (Placed<S> & { kind: 'trimesh'; vertices: unknown[]; indices: unknown[] })
220
+
221
+ /** A placement's pose: scale, yaw, lean X, lean Z, then the position; or a full matrix (column-major, three's
222
+ * `Matrix4.elements`) whose translation is x, y, z. */
223
+ export interface PosePlacement {
224
+ readonly x: number
225
+ readonly y: number
226
+ readonly z: number
227
+ readonly yaw?: number
228
+ readonly leanX?: number
229
+ readonly leanZ?: number
230
+ readonly scale?: number
231
+ readonly matrix?: ArrayLike<number>
232
+ }
233
+
234
+ /** one copy's transform: the matrix, and its rotation and uniform scale taken apart once */
235
+ export interface Pose {
236
+ readonly x: number
237
+ readonly y: number
238
+ readonly z: number
239
+ /** column-major, as three's `Matrix4.elements` */
240
+ readonly matrix: Float64Array
241
+ readonly quat: Quat
242
+ readonly scale: number
243
+ /** no rotation at all (the colliders keep their own yaw exactly) */
244
+ readonly upright: boolean
245
+ }
246
+
247
+ type M4 = Float64Array
248
+ /** three's `Matrix4.set`: row-major arguments into column-major elements */
249
+ function set(
250
+ te: M4,
251
+ n11: number,
252
+ n12: number,
253
+ n13: number,
254
+ n14: number,
255
+ n21: number,
256
+ n22: number,
257
+ n23: number,
258
+ n24: number,
259
+ n31: number,
260
+ n32: number,
261
+ n33: number,
262
+ n34: number,
263
+ n41: number,
264
+ n42: number,
265
+ n43: number,
266
+ n44: number,
267
+ ): M4 {
268
+ te[0] = n11
269
+ te[4] = n12
270
+ te[8] = n13
271
+ te[12] = n14
272
+ te[1] = n21
273
+ te[5] = n22
274
+ te[9] = n23
275
+ te[13] = n24
276
+ te[2] = n31
277
+ te[6] = n32
278
+ te[10] = n33
279
+ te[14] = n34
280
+ te[3] = n41
281
+ te[7] = n42
282
+ te[11] = n43
283
+ te[15] = n44
284
+ return te
285
+ }
286
+ function rotationX(te: M4, theta: number): M4 {
287
+ const c = Math.cos(theta),
288
+ s = Math.sin(theta)
289
+ return set(te, 1, 0, 0, 0, 0, c, -s, 0, 0, s, c, 0, 0, 0, 0, 1)
290
+ }
291
+ function rotationY(te: M4, theta: number): M4 {
292
+ const c = Math.cos(theta),
293
+ s = Math.sin(theta)
294
+ return set(te, c, 0, s, 0, 0, 1, 0, 0, -s, 0, c, 0, 0, 0, 0, 1)
295
+ }
296
+ function rotationZ(te: M4, theta: number): M4 {
297
+ const c = Math.cos(theta),
298
+ s = Math.sin(theta)
299
+ return set(te, c, -s, 0, 0, s, c, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1)
300
+ }
301
+ /** three's `Matrix4.premultiply(m)` (`multiplyMatrices(m, this)`): te = ae × te */
302
+ function premultiply(te: M4, ae: M4): void {
303
+ const be = te
304
+ const a11 = ae[0] ?? 0,
305
+ a12 = ae[4] ?? 0,
306
+ a13 = ae[8] ?? 0,
307
+ a14 = ae[12] ?? 0
308
+ const a21 = ae[1] ?? 0,
309
+ a22 = ae[5] ?? 0,
310
+ a23 = ae[9] ?? 0,
311
+ a24 = ae[13] ?? 0
312
+ const a31 = ae[2] ?? 0,
313
+ a32 = ae[6] ?? 0,
314
+ a33 = ae[10] ?? 0,
315
+ a34 = ae[14] ?? 0
316
+ const a41 = ae[3] ?? 0,
317
+ a42 = ae[7] ?? 0,
318
+ a43 = ae[11] ?? 0,
319
+ a44 = ae[15] ?? 0
320
+ const b11 = be[0] ?? 0,
321
+ b12 = be[4] ?? 0,
322
+ b13 = be[8] ?? 0,
323
+ b14 = be[12] ?? 0
324
+ const b21 = be[1] ?? 0,
325
+ b22 = be[5] ?? 0,
326
+ b23 = be[9] ?? 0,
327
+ b24 = be[13] ?? 0
328
+ const b31 = be[2] ?? 0,
329
+ b32 = be[6] ?? 0,
330
+ b33 = be[10] ?? 0,
331
+ b34 = be[14] ?? 0
332
+ const b41 = be[3] ?? 0,
333
+ b42 = be[7] ?? 0,
334
+ b43 = be[11] ?? 0,
335
+ b44 = be[15] ?? 0
336
+ te[0] = a11 * b11 + a12 * b21 + a13 * b31 + a14 * b41
337
+ te[4] = a11 * b12 + a12 * b22 + a13 * b32 + a14 * b42
338
+ te[8] = a11 * b13 + a12 * b23 + a13 * b33 + a14 * b43
339
+ te[12] = a11 * b14 + a12 * b24 + a13 * b34 + a14 * b44
340
+ te[1] = a21 * b11 + a22 * b21 + a23 * b31 + a24 * b41
341
+ te[5] = a21 * b12 + a22 * b22 + a23 * b32 + a24 * b42
342
+ te[9] = a21 * b13 + a22 * b23 + a23 * b33 + a24 * b43
343
+ te[13] = a21 * b14 + a22 * b24 + a23 * b34 + a24 * b44
344
+ te[2] = a31 * b11 + a32 * b21 + a33 * b31 + a34 * b41
345
+ te[6] = a31 * b12 + a32 * b22 + a33 * b32 + a34 * b42
346
+ te[10] = a31 * b13 + a32 * b23 + a33 * b33 + a34 * b43
347
+ te[14] = a31 * b14 + a32 * b24 + a33 * b34 + a34 * b44
348
+ te[3] = a41 * b11 + a42 * b21 + a43 * b31 + a44 * b41
349
+ te[7] = a41 * b12 + a42 * b22 + a43 * b32 + a44 * b42
350
+ te[11] = a41 * b13 + a42 * b23 + a43 * b33 + a44 * b43
351
+ te[15] = a41 * b14 + a42 * b24 + a43 * b34 + a44 * b44
352
+ }
353
+ /** three's `Quaternion.setFromRotationMatrix` (the upper 3x3 a pure rotation) */
354
+ function quatOfRotation(te: M4): Quat {
355
+ const m11 = te[0] ?? 0,
356
+ m12 = te[4] ?? 0,
357
+ m13 = te[8] ?? 0,
358
+ m21 = te[1] ?? 0,
359
+ m22 = te[5] ?? 0,
360
+ m23 = te[9] ?? 0,
361
+ m31 = te[2] ?? 0,
362
+ m32 = te[6] ?? 0,
363
+ m33 = te[10] ?? 0,
364
+ trace = m11 + m22 + m33
365
+ if (trace > 0) {
366
+ const s = 0.5 / Math.sqrt(trace + 1.0)
367
+ return {
368
+ x: (m32 - m23) * s,
369
+ y: (m13 - m31) * s,
370
+ z: (m21 - m12) * s,
371
+ w: 0.25 / s,
372
+ }
373
+ } else if (m11 > m22 && m11 > m33) {
374
+ const s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33)
375
+ return {
376
+ x: 0.25 * s,
377
+ y: (m12 + m21) / s,
378
+ z: (m13 + m31) / s,
379
+ w: (m32 - m23) / s,
380
+ }
381
+ } else if (m22 > m33) {
382
+ const s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33)
383
+ return {
384
+ x: (m12 + m21) / s,
385
+ y: 0.25 * s,
386
+ z: (m23 + m32) / s,
387
+ w: (m13 - m31) / s,
388
+ }
389
+ }
390
+ const s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22)
391
+ return {
392
+ x: (m13 + m31) / s,
393
+ y: (m23 + m32) / s,
394
+ z: 0.25 * s,
395
+ w: (m21 - m12) / s,
396
+ }
397
+ }
398
+ /** three's `Matrix4.decompose`: the rotation and the x scale (the position is the caller's) */
399
+ function decompose(te: M4): { quat: Quat; sx: number } {
400
+ const n11 = te[0] ?? 0,
401
+ n12 = te[4] ?? 0,
402
+ n13 = te[8] ?? 0
403
+ const n21 = te[1] ?? 0,
404
+ n22 = te[5] ?? 0,
405
+ n23 = te[9] ?? 0
406
+ const n31 = te[2] ?? 0,
407
+ n32 = te[6] ?? 0,
408
+ n33 = te[10] ?? 0
409
+ const det =
410
+ n11 * (n22 * n33 - n23 * n32) -
411
+ n12 * (n21 * n33 - n23 * n31) +
412
+ n13 * (n21 * n32 - n22 * n31)
413
+ if (det === 0) return { quat: { x: 0, y: 0, z: 0, w: 1 }, sx: 1 }
414
+ let sx = Math.sqrt(n11 * n11 + n21 * n21 + n31 * n31)
415
+ const sy = Math.sqrt(n12 * n12 + n22 * n22 + n32 * n32)
416
+ const sz = Math.sqrt(n13 * n13 + n23 * n23 + n33 * n33)
417
+ // if determinant is negative, we need to invert one scale
418
+ if (det < 0) sx = -sx
419
+ const m = Float64Array.from(te)
420
+ const invSX = 1 / sx,
421
+ invSY = 1 / sy,
422
+ invSZ = 1 / sz
423
+ m[0] = n11 * invSX
424
+ m[1] = n21 * invSX
425
+ m[2] = n31 * invSX
426
+ m[4] = n12 * invSY
427
+ m[5] = n22 * invSY
428
+ m[6] = n32 * invSY
429
+ m[8] = n13 * invSZ
430
+ m[9] = n23 * invSZ
431
+ m[10] = n33 * invSZ
432
+ return { quat: quatOfRotation(m), sx }
433
+ }
434
+ /** three's `Vector3.applyMatrix4`: the point (x, y, z) through the matrix, with the perspective divide */
435
+ function applyMatrix4(x: number, y: number, z: number, e: M4): Vec3 {
436
+ const w =
437
+ 1 / ((e[3] ?? 0) * x + (e[7] ?? 0) * y + (e[11] ?? 0) * z + (e[15] ?? 0))
438
+ return {
439
+ x: ((e[0] ?? 0) * x + (e[4] ?? 0) * y + (e[8] ?? 0) * z + (e[12] ?? 0)) * w,
440
+ y: ((e[1] ?? 0) * x + (e[5] ?? 0) * y + (e[9] ?? 0) * z + (e[13] ?? 0)) * w,
441
+ z:
442
+ ((e[2] ?? 0) * x + (e[6] ?? 0) * y + (e[10] ?? 0) * z + (e[14] ?? 0)) * w,
443
+ }
444
+ }
445
+ /** three's `Quaternion.multiplyQuaternions(a, b)` */
446
+ function multiplyQuaternions(a: Quat, b: Quat): Quat {
447
+ const qax = a.x,
448
+ qay = a.y,
449
+ qaz = a.z,
450
+ qaw = a.w
451
+ const qbx = b.x,
452
+ qby = b.y,
453
+ qbz = b.z,
454
+ qbw = b.w
455
+ return {
456
+ x: qax * qbw + qaw * qbx + qay * qbz - qaz * qby,
457
+ y: qay * qbw + qaw * qby + qaz * qbx - qax * qbz,
458
+ z: qaz * qbw + qaw * qbz + qax * qby - qay * qbx,
459
+ w: qaw * qbw - qax * qbx - qay * qby - qaz * qbz,
460
+ }
461
+ }
462
+
463
+ /** The pose of a placement: scale, yaw, lean X, lean Z, then the position (or its matrix). */
464
+ export function poseOf(pl: PosePlacement): Pose {
465
+ const matrix = new Float64Array(16),
466
+ m = new Float64Array(16)
467
+ if (pl.matrix === undefined) {
468
+ const s = pl.scale ?? 1
469
+ set(matrix, s, 0, 0, 0, 0, s, 0, 0, 0, 0, s, 0, 0, 0, 0, 1)
470
+ if (pl.yaw !== undefined) premultiply(matrix, rotationY(m, pl.yaw))
471
+ if (pl.leanX !== undefined) premultiply(matrix, rotationX(m, pl.leanX))
472
+ if (pl.leanZ !== undefined) premultiply(matrix, rotationZ(m, pl.leanZ))
473
+ premultiply(
474
+ matrix,
475
+ set(m, 1, 0, 0, pl.x, 0, 1, 0, pl.y, 0, 0, 1, pl.z, 0, 0, 0, 1),
476
+ )
477
+ } else for (let i = 0; i < 16; i++) matrix[i] = pl.matrix[i] ?? 0
478
+ const { quat, sx } = decompose(matrix)
479
+ const upright =
480
+ pl.matrix === undefined
481
+ ? (pl.yaw ?? 0) === 0 && (pl.leanX ?? 0) === 0 && (pl.leanZ ?? 0) === 0
482
+ : Math.abs(quat.w) > 1 - 1e-12
483
+ return { x: pl.x, y: pl.y, z: pl.z, matrix, quat, scale: sx, upright }
484
+ }
485
+
486
+ const scaled = (a: Float32Array, s: number): Float32Array =>
487
+ s === 1 ? a : a.map(v => v * s)
488
+
489
+ /** one own-space collider at a copy's pose, in world space */
490
+ export function placeCollider<S extends string>(
491
+ d: ColliderDesc<S>,
492
+ pose: Pose,
493
+ ): ColliderDesc<S> {
494
+ const s = pose.scale
495
+ if (d.kind === 'treads') {
496
+ const from = applyMatrix4(d.from.x, d.from.y, d.from.z, pose.matrix)
497
+ const to = applyMatrix4(d.to.x, d.to.y, d.to.z, pose.matrix)
498
+ return { ...d, from, to, width: d.width * s }
499
+ }
500
+ const at = applyMatrix4(d.x, d.y, d.z, pose.matrix)
501
+ // the rotation: the pose's, then the collider's own (its `rot`, or its `yaw`; three's setFromAxisAngle about +Y)
502
+ let turn: { yaw?: number; rot?: Quat }
503
+ if (pose.upright)
504
+ turn =
505
+ d.rot === undefined
506
+ ? d.yaw === undefined
507
+ ? {}
508
+ : { yaw: d.yaw }
509
+ : { rot: d.rot }
510
+ else {
511
+ let own: Quat
512
+ if (d.rot !== undefined)
513
+ own = { x: d.rot.x, y: d.rot.y, z: d.rot.z, w: d.rot.w }
514
+ else {
515
+ const halfAngle = (d.yaw ?? 0) / 2,
516
+ sin = Math.sin(halfAngle)
517
+ own = { x: 0 * sin, y: 1 * sin, z: 0 * sin, w: Math.cos(halfAngle) }
518
+ }
519
+ const q = multiplyQuaternions(pose.quat, own)
520
+ turn =
521
+ Math.abs(q.x) < 1e-9 && Math.abs(q.z) < 1e-9
522
+ ? { yaw: 2 * Math.atan2(q.y, q.w) }
523
+ : { rot: { x: q.x, y: q.y, z: q.z, w: q.w } }
524
+ }
525
+ const surface = d.surface === undefined ? {} : { surface: d.surface }
526
+ switch (d.kind) {
527
+ case 'box':
528
+ return {
529
+ kind: 'box',
530
+ ...at,
531
+ hx: d.hx * s,
532
+ hy: d.hy * s,
533
+ hz: d.hz * s,
534
+ ...turn,
535
+ ...surface,
536
+ }
537
+ case 'capsule':
538
+ return {
539
+ kind: 'capsule',
540
+ ...at,
541
+ halfHeight: d.halfHeight * s,
542
+ radius: d.radius * s,
543
+ ...turn,
544
+ ...surface,
545
+ }
546
+ case 'ball':
547
+ return { kind: 'ball', ...at, radius: d.radius * s, ...turn, ...surface }
548
+ case 'hull':
549
+ return {
550
+ kind: 'hull',
551
+ ...at,
552
+ points: scaled(d.points, s),
553
+ ...turn,
554
+ ...surface,
555
+ }
556
+ case 'trimesh':
557
+ return {
558
+ kind: 'trimesh',
559
+ ...at,
560
+ vertices: scaled(d.vertices, s),
561
+ indices: d.indices,
562
+ ...turn,
563
+ ...surface,
564
+ }
565
+ default:
566
+ return d
567
+ }
568
+ }
@@ -14,6 +14,12 @@ export const GRID_CELL_COUNT: number = (2 * GRID_RADIUS + 1) ** 2;
14
14
  export const ENTRY_WIDTH = 8;
15
15
  /** Asphalt reserved inside each midpoint entry in metres. */
16
16
  export const ENTRY_ASPHALT = 15;
17
+ /** The entry road's width at each edge midpoint in metres (SDK-SPLIT SP4a: was the engine's core/config). */
18
+ // oxlint-disable-next-line import/group-exports, import/exports-last -- one more grid constant beside its siblings (SDK-SPLIT SP4a)
19
+ export const ROAD_WIDTH = 15;
20
+ /** How far the entry road runs into the cell in metres; at least 50 (SDK-SPLIT SP4a: was the engine's core/config). */
21
+ // oxlint-disable-next-line import/group-exports, import/exports-last -- one more grid constant beside its siblings (SDK-SPLIT SP4a)
22
+ export const ROAD_LENGTH = 60;
17
23
  /** Total cell height in metres. */
18
24
  export const CELL_HEIGHT = 500; // metres, bottom to top
19
25
  /** Cell depth below the highway in metres. */
@@ -59,7 +59,8 @@ const phase = v.pipe(finite, v.minValue(-2 * Math.PI), v.maxValue(2 * Math.PI));
59
59
  /** Seconds after its death that a spawn's body comes back at its `at` (TEMPLATE-E2E TC-E2); absent, it stays dead. */
60
60
  const RESPAWN_MAX = 3600, RESPAWN_MIN = 1;
61
61
  const respawn = v.pipe(finite, v.minValue(RESPAWN_MIN), v.maxValue(RESPAWN_MAX));
62
- const spawn = v.strictObject({ phaseOffset: v.optional(phase), home: v.optional(CreatureHomeSchema), respawn: v.optional(respawn), id, species: id, variant: id, brain: v.nullable(id), strike: v.nullable(id), seed: v.pipe(finite, v.integer(), v.minValue(0), v.maxValue(0xffffffff)), scale: v.pipe(finite, v.minValue(0.1), v.maxValue(10)), at: v.tuple([coord, coord, coord]), yaw: finite });
62
+ /** Social membership names no controller; the species temperament owns assistance. */
63
+ const spawn = v.strictObject({ group: v.exactOptional(id), phaseOffset: v.optional(phase), home: v.optional(CreatureHomeSchema), respawn: v.optional(respawn), id, species: id, variant: id, brain: v.nullable(id), strike: v.nullable(id), seed: v.pipe(finite, v.integer(), v.minValue(0), v.maxValue(0xffffffff)), scale: v.pipe(finite, v.minValue(0.1), v.maxValue(10)), at: v.tuple([coord, coord, coord]), yaw: finite });
63
64
  /** Pure-data creature archetypes and stable spawn layouts, expanded before the local sim boots. */
64
65
  export const CreaturesSchema: v.GenericSchema<ShardCreaturesInput, ShardCreatures> = v.pipe(v.strictObject({ brains: v.pipe(v.array(v.variant('kind', [brain, SkirmisherSchema, GuardianSchema, PerchHunterSchema, ScriptBrainSchema, RamGrazerSchema, ChallengeGrazerSchema, OrbitDiverSchema, PatrolDiverSchema, BurstFlyerSchema, GrazerSchema, DiverSchema, GuardianPatternsSchema, StalkerSchema])), v.maxLength(64)), groups: v.optional(v.pipe(v.array(GroupBrainSchema), v.maxLength(64)), []), spawns: v.pipe(v.array(spawn), v.maxLength(10000)) }),
65
66
  v.check((c) => creatureRules(c).length === 0, 'creature reference rules'));
@@ -164,8 +165,8 @@ export interface CreatureMemoryActionsRows { stateKey: string; states: (string)[
164
165
  export interface CreatureBodyRecipeRowsInput { actions?: CreatureMemoryActionsRowsInput; offset?: { field: string; from: number; to: number; }; kind: 'animal'; motion: 'ground' | 'flight'; attack: 'keeper' | 'unlimited'; stunned: 'none' | 'look-hold'; contact: ({ kind: 'environment'; halfArc: number; }) | ({ kind: 'actor'; halfArc: number; move: string; }); }
165
166
  export interface CreatureBodyRecipeRows { actions?: CreatureMemoryActionsRows; offset?: { field: string; from: number; to: number; }; kind: 'animal'; motion: 'ground' | 'flight'; attack: 'keeper' | 'unlimited'; stunned: 'none' | 'look-hold'; contact: ({ kind: 'environment'; halfArc: number; }) | ({ kind: 'actor'; halfArc: number; move: string; }); }
166
167
  // oxlint-disable-next-line typescript/consistent-type-definitions -- Valibot's readonly defaults need the alias's implicit dictionary compatibility.
167
- export type ShardCreaturesInput = { brains: (({ id: string; kind: 'pursue'; awareRadius: number; leashRadius: number; speed: number; returnSpeed: number; stopDistance: number; turnRate: number; thinkDivisor: number; attackCooldownTicks: number; wanderRadius: number; wanderEveryTicks: number; }) | (v.InferInput<typeof SkirmisherSchema>) | (v.InferInput<typeof GuardianSchema>) | (v.InferInput<typeof PerchHunterSchema>) | (v.InferInput<typeof ScriptBrainSchema>) | (v.InferInput<typeof RamGrazerSchema>) | (v.InferInput<typeof ChallengeGrazerSchema>) | (v.InferInput<typeof OrbitDiverSchema>) | (v.InferInput<typeof PatrolDiverSchema>) | (v.InferInput<typeof BurstFlyerSchema>) | (v.InferInput<typeof GrazerSchema>) | (v.InferInput<typeof DiverSchema>) | (v.InferInput<typeof GuardianPatternsSchema>) | (v.InferInput<typeof StalkerSchema>))[]; groups?: (v.InferInput<typeof GroupBrainSchema>)[] | undefined; spawns: ({ phaseOffset?: number | undefined; respawn?: number | undefined; home?: ShardCreatureHomeInput | undefined; id: string; species: string; variant: string; brain: (string) | null; strike: (string) | null; seed: number; scale: number; at: [number, number, number]; yaw: number; })[]; };
168
- export interface ShardCreatures { brains: (({ id: string; kind: 'pursue'; awareRadius: number; leashRadius: number; speed: number; returnSpeed: number; stopDistance: number; turnRate: number; thinkDivisor: number; attackCooldownTicks: number; wanderRadius: number; wanderEveryTicks: number; }) | (v.InferOutput<typeof SkirmisherSchema>) | (v.InferOutput<typeof GuardianSchema>) | (v.InferOutput<typeof PerchHunterSchema>) | (v.InferOutput<typeof ScriptBrainSchema>) | (v.InferOutput<typeof RamGrazerSchema>) | (v.InferOutput<typeof ChallengeGrazerSchema>) | (v.InferOutput<typeof OrbitDiverSchema>) | (v.InferOutput<typeof PatrolDiverSchema>) | (v.InferOutput<typeof BurstFlyerSchema>) | (v.InferOutput<typeof GrazerSchema>) | (v.InferOutput<typeof DiverSchema>) | (v.InferOutput<typeof GuardianPatternsSchema>) | (v.InferOutput<typeof StalkerSchema>))[]; groups: (v.InferOutput<typeof GroupBrainSchema>)[]; spawns: ({ phaseOffset?: number | undefined; respawn?: number | undefined; home?: ShardCreatureHome | undefined; id: string; species: string; variant: string; brain: (string) | null; strike: (string) | null; seed: number; scale: number; at: [number, number, number]; yaw: number; })[]; }
168
+ export type ShardCreaturesInput = { brains: (({ id: string; kind: 'pursue'; awareRadius: number; leashRadius: number; speed: number; returnSpeed: number; stopDistance: number; turnRate: number; thinkDivisor: number; attackCooldownTicks: number; wanderRadius: number; wanderEveryTicks: number; }) | (v.InferInput<typeof SkirmisherSchema>) | (v.InferInput<typeof GuardianSchema>) | (v.InferInput<typeof PerchHunterSchema>) | (v.InferInput<typeof ScriptBrainSchema>) | (v.InferInput<typeof RamGrazerSchema>) | (v.InferInput<typeof ChallengeGrazerSchema>) | (v.InferInput<typeof OrbitDiverSchema>) | (v.InferInput<typeof PatrolDiverSchema>) | (v.InferInput<typeof BurstFlyerSchema>) | (v.InferInput<typeof GrazerSchema>) | (v.InferInput<typeof DiverSchema>) | (v.InferInput<typeof GuardianPatternsSchema>) | (v.InferInput<typeof StalkerSchema>))[]; groups?: (v.InferInput<typeof GroupBrainSchema>)[] | undefined; spawns: ({ group?: string; phaseOffset?: number | undefined; respawn?: number | undefined; home?: ShardCreatureHomeInput | undefined; id: string; species: string; variant: string; brain: (string) | null; strike: (string) | null; seed: number; scale: number; at: [number, number, number]; yaw: number; })[]; };
169
+ export interface ShardCreatures { brains: (({ id: string; kind: 'pursue'; awareRadius: number; leashRadius: number; speed: number; returnSpeed: number; stopDistance: number; turnRate: number; thinkDivisor: number; attackCooldownTicks: number; wanderRadius: number; wanderEveryTicks: number; }) | (v.InferOutput<typeof SkirmisherSchema>) | (v.InferOutput<typeof GuardianSchema>) | (v.InferOutput<typeof PerchHunterSchema>) | (v.InferOutput<typeof ScriptBrainSchema>) | (v.InferOutput<typeof RamGrazerSchema>) | (v.InferOutput<typeof ChallengeGrazerSchema>) | (v.InferOutput<typeof OrbitDiverSchema>) | (v.InferOutput<typeof PatrolDiverSchema>) | (v.InferOutput<typeof BurstFlyerSchema>) | (v.InferOutput<typeof GrazerSchema>) | (v.InferOutput<typeof DiverSchema>) | (v.InferOutput<typeof GuardianPatternsSchema>) | (v.InferOutput<typeof StalkerSchema>))[]; groups: (v.InferOutput<typeof GroupBrainSchema>)[]; spawns: ({ group?: string; phaseOffset?: number | undefined; respawn?: number | undefined; home?: ShardCreatureHome | undefined; id: string; species: string; variant: string; brain: (string) | null; strike: (string) | null; seed: number; scale: number; at: [number, number, number]; yaw: number; })[]; }
169
170
  export type CreatureStrikeRowsInput = CreatureStrikeRows;
170
171
  export interface CreatureStrikeRows { debris?: StrikeDebrisPolicy; id: string; shape: ({ kind: 'arc'; radius: number; halfAngle: number; yawOffset?: number; }) | ({ kind: 'lane'; length: number; width: number; }) | ({ kind: 'ring'; inner: number; outer: number; }) | ({ kind: 'wedge'; length: number; halfAngle: number; }) | ({ kind: 'point'; radius: number; exclusive?: boolean; }) | ({ kind: 'sphere'; radius: number; }); windup: number; active: number; recover: number; cooldown: number; range: (number) | null; damage: number; tags: (`${string}.${string}`)[]; weight: ({ kind: 'constant'; value: number; }) | ({ kind: 'horizontal-distance'; above: number; far: number; near: number; }); units?: 'world' | 'actor'; alternatives?: (({ kind: 'arc'; radius: number; halfAngle: number; yawOffset?: number; }) | ({ kind: 'lane'; length: number; width: number; }) | ({ kind: 'ring'; inner: number; outer: number; }) | ({ kind: 'wedge'; length: number; halfAngle: number; }) | ({ kind: 'point'; radius: number; exclusive?: boolean; }) | ({ kind: 'sphere'; radius: number; }))[]; motion?: { speed?: number; delay?: number; track?: 'none' | 'lead' | 'follow'; overshoot?: number; skid?: number; }; eligibility?: { maxDy?: number; jumpDodges?: boolean; }; }
171
172
  export type CreatureStrikesInput = unknown;