@wildshard/shard-format 0.15.0 → 0.17.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,541 @@
1
+ /* oxlint-disable capitalized-comments, complexity, curly, id-length, import/consistent-type-specifier-style, import/exports-last, import/group-exports, max-lines, max-lines-per-function, max-statements, no-inline-comments, no-magic-numbers, prefer-destructuring, sort-vars, typescript/explicit-function-return-type, typescript/prefer-readonly-parameter-types, unicorn/no-array-callback-reference, unicorn/no-null, unicorn/numeric-separators-style, unicorn/switch-case-braces -- verbatim port of the engine's law (SDK-SPLIT SP4); golden vectors pin it, so it keeps the engine's form */
2
+ /** SDK-SPLIT SP4f2 (Q35): the interact table's data half moved from engine `shared/engine/world/interact/types.ts` (its three.js
3
+ * looks, props and live interactables stay engine), and `compileQuestTable` from `shared/game/plugin/quests.ts`. */
4
+ import {
5
+ parseInteractionRows,
6
+ type InteractionRowsData,
7
+ } from './questInteractions.ts'
8
+ /**
9
+ * Interactables kit — the DATA schema (A2, project/archive/2026-09-23-driftwood-remaster.md). Every chest, key, door, lever, pressure
10
+ * plate, barrel, pickup, beacon, bench and altar on a shard is one plain-JSON row of an `InteractTable`; nothing is code
11
+ * per placement. The rows talk to each other (and to quests) only through FLAGS — plain strings in a `Flags` store:
12
+ *
13
+ * automatic flags an interactable raises what raises it
14
+ * `open:<id>` a chest / door opened
15
+ * `taken:<id>` a pickup / key taken
16
+ * `lever:<id>` a lever is pulled (toggles)
17
+ * `plate:<id>` a plate is pressed right now (transient, never persisted)
18
+ * `lit:<id>` a beacon lit
19
+ * `used:<id>` a bench sat on / an altar used
20
+ * `key:<keyId>` you hold that key (a key pickup, or a chest's contents)
21
+ * anything in `sets` the row's own extra flag(s), raised with the automatic one
22
+ *
23
+ * and they react through CONDITIONS (`Cond`): `{ all?, any?, none? }` over flags. A door with `opensWhen` opens by
24
+ * itself (plates, levers); `requires` gates the E action (a locked-away strongbox, the altar's three shards); `showWhen`
25
+ * hides a row until its condition holds (a key that appears where the sailor fell). Flags a row reads but nothing in the
26
+ * table raises (`dead:sailor`, `talked:castaway`) are declared in `external` — `validateTable` (validate.ts) proves every
27
+ * flag read is raised by something, every lock has a key, every id is unique: the shape a chunk upload would be checked
28
+ * against before the server loads it as config.
29
+ *
30
+ * Placement: `at` is a point in a POI's local frame (`poi` + local x / z, `yaw` in the same frame; world = POI origin +
31
+ * R_y(POI rotation) · local), or `poi: 'world'` for world
32
+ * coordinates. `anchor` names a model-supplied point (`wreck.holdDoor`) that wins over x / z when the model exports it.
33
+ * y comes from the walkable floor there (platforms, else the terrain) unless `y` pins it (absolute) or `dy` lifts it.
34
+ */
35
+
36
+ /** Frozen compatibility vocabulary: remove with legacy shards (NEXT N5).
37
+ * Live placement rows use QuestPlace and authored frame records instead. */
38
+ export type PoiId =
39
+ | 'world'
40
+ | 'hut'
41
+ | 'lookout'
42
+ | 'wreck'
43
+ | 'shrine'
44
+ | 'cave'
45
+ | 'pier'
46
+ /** Generic authored placement; `world` selects untransformed coordinates. */
47
+ export interface QuestPlace {
48
+ poi: string
49
+ x: number
50
+ z: number
51
+ /** facing in the POI's frame (radians about +Y; 0 = the model's front faces +Z) */
52
+ yaw?: number
53
+ /** absolute world y — skips the floor lookup */
54
+ y?: number
55
+ /** metres above the floor found at (x, z) */
56
+ dy?: number
57
+ /** a model anchor name (`<poi>.<name>`, e.g. `wreck.holdDoor`); used instead of x / z / yaw when the model exports it */
58
+ anchor?: string
59
+ }
60
+
61
+ /** Frozen compatibility placement: remove with legacy shards (NEXT N5). */
62
+ export interface Place extends QuestPlace {
63
+ poi: PoiId
64
+ }
65
+
66
+ /** A borrowed world-space quest anchor; an explicit height bypasses floor lookup. */
67
+ export interface QuestPlaceAnchor {
68
+ readonly x: number
69
+ readonly z: number
70
+ readonly y?: number
71
+ readonly yaw?: number
72
+ }
73
+ /** Existing terrain, walkable floors and model anchors lent to a quest placement resolver. */
74
+ export interface QuestPlacementPorts {
75
+ readonly terrain: (x: number, z: number) => number
76
+ readonly platforms?: readonly ((x: number, z: number) => number | undefined)[]
77
+ readonly registry?: {
78
+ readonly floorAt: (x: number, z: number) => number | undefined
79
+ }
80
+ /** Strict height difference above the current floor; omitted accepts any higher registered floor. */
81
+ readonly registryReach?: number
82
+ readonly frames?: Readonly<
83
+ Record<
84
+ string,
85
+ { readonly x: number; readonly z: number; readonly rot: number }
86
+ >
87
+ >
88
+ readonly pois?: Readonly<Record<string, object | null>>
89
+ }
90
+ const questNumber = (value: number): number => {
91
+ if (!Number.isFinite(value) || Math.abs(value) > 1000000)
92
+ throw new RangeError('Invalid quest placement coordinate')
93
+ return value
94
+ }
95
+ const questKey = (value: string): string => {
96
+ if (
97
+ value.length === 0 ||
98
+ value.length > 256 ||
99
+ value
100
+ .split('.')
101
+ .some(
102
+ key =>
103
+ key === '__proto__' || key === 'prototype' || key === 'constructor',
104
+ )
105
+ )
106
+ throw new Error('Invalid quest anchor path')
107
+ return value
108
+ }
109
+ function questAnchor(raw: unknown): QuestPlaceAnchor {
110
+ if (
111
+ typeof raw !== 'object' ||
112
+ raw === null ||
113
+ !('x' in raw) ||
114
+ !('z' in raw) ||
115
+ typeof raw.x !== 'number' ||
116
+ typeof raw.z !== 'number'
117
+ )
118
+ throw new Error('Invalid borrowed quest anchor')
119
+ const y = 'y' in raw ? raw.y : undefined,
120
+ yaw = 'yaw' in raw ? raw.yaw : undefined
121
+ if (
122
+ (y !== undefined && typeof y !== 'number') ||
123
+ (yaw !== undefined && typeof yaw !== 'number')
124
+ )
125
+ throw new Error('Invalid quest anchor height or yaw')
126
+ return {
127
+ x: questNumber(raw.x),
128
+ z: questNumber(raw.z),
129
+ ...(y === undefined ? {} : { y: questNumber(y) }),
130
+ ...(yaw === undefined ? {} : { yaw: questNumber(yaw) }),
131
+ }
132
+ }
133
+ /** Resolve bounded quest placements in their authored frames, with live borrowed floors.
134
+ * Explicit quest anchors precede model anchors; the former ignore dy, while model
135
+ * anchors add dy only when their height is omitted. No prompt, registry or save is owned.
136
+ */
137
+ export function createQuestPlacements(ports: QuestPlacementPorts): {
138
+ readonly floorAt: (x: number, z: number) => number
139
+ readonly place: (at: QuestPlace) => {
140
+ x: number
141
+ y: number
142
+ z: number
143
+ yaw: number
144
+ }
145
+ readonly setAnchor: (name: string, anchor: QuestPlaceAnchor) => void
146
+ /** Borrow current validated anchors without introducing a second placement owner. */
147
+ readonly anchors: ReadonlyMap<string, Readonly<QuestPlaceAnchor>>
148
+ } {
149
+ if (
150
+ ports.registryReach !== undefined &&
151
+ (!Number.isFinite(ports.registryReach) || ports.registryReach <= 0)
152
+ )
153
+ throw new RangeError('Invalid quest registry reach')
154
+ if ((ports.platforms?.length ?? 0) > 4096)
155
+ throw new RangeError('Too many quest floors')
156
+ if (Object.keys(ports.frames ?? {}).length > 4096)
157
+ throw new RangeError('Too many quest frames')
158
+ for (const [id, frame] of Object.entries(ports.frames ?? {})) {
159
+ questKey(id)
160
+ questNumber(frame.x)
161
+ questNumber(frame.z)
162
+ questNumber(frame.rot)
163
+ }
164
+ const own = new Map<string, QuestPlaceAnchor>()
165
+ const floorAt = (x: number, z: number): number => {
166
+ questNumber(x)
167
+ questNumber(z)
168
+ let y = questNumber(ports.terrain(x, z))
169
+ for (const floor of ports.platforms ?? []) {
170
+ const f = floor(x, z)
171
+ if (f !== undefined && questNumber(f) > y) y = f
172
+ }
173
+ const registered = ports.registry?.floorAt(x, z)
174
+ if (
175
+ registered !== undefined &&
176
+ questNumber(registered) > y &&
177
+ (ports.registryReach === undefined ||
178
+ registered - y < ports.registryReach)
179
+ )
180
+ y = registered
181
+ return y
182
+ }
183
+ return {
184
+ anchors: own,
185
+ floorAt,
186
+ setAnchor: (name, anchor) => {
187
+ questKey(name)
188
+ if (!own.has(name) && own.size >= 4096)
189
+ throw new RangeError('Too many quest anchors')
190
+ own.set(name, questAnchor(anchor))
191
+ },
192
+ place: p => {
193
+ questKey(p.poi)
194
+ questNumber(p.x)
195
+ questNumber(p.z)
196
+ const dy = p.dy === undefined ? 0 : questNumber(p.dy)
197
+ if (p.anchor !== undefined) {
198
+ questKey(p.anchor)
199
+ const override = own.get(p.anchor)
200
+ if (override !== undefined)
201
+ return {
202
+ x: override.x,
203
+ z: override.z,
204
+ y: override.y ?? floorAt(override.x, override.z),
205
+ yaw: override.yaw ?? 0,
206
+ }
207
+ const [poi, name] = p.anchor.split('.')
208
+ const model: unknown =
209
+ poi === undefined ? undefined : Reflect.get(ports.pois ?? {}, poi)
210
+ if (
211
+ name !== undefined &&
212
+ typeof model === 'object' &&
213
+ model !== null &&
214
+ 'anchors' in model &&
215
+ typeof model.anchors === 'object' &&
216
+ model.anchors !== null &&
217
+ Object.hasOwn(model.anchors, name)
218
+ ) {
219
+ const a = questAnchor(Reflect.get(model.anchors, name))
220
+ return {
221
+ x: a.x,
222
+ z: a.z,
223
+ y: a.y ?? floorAt(a.x, a.z) + dy,
224
+ yaw: a.yaw ?? 0,
225
+ }
226
+ }
227
+ }
228
+ let x = p.x,
229
+ z = p.z,
230
+ yaw = p.yaw === undefined ? 0 : questNumber(p.yaw)
231
+ if (p.poi !== 'world') {
232
+ const frame = Object.hasOwn(ports.frames ?? {}, p.poi)
233
+ ? ports.frames?.[p.poi]
234
+ : undefined
235
+ if (frame === undefined) throw new Error(`Missing quest frame ${p.poi}`)
236
+ const c = Math.cos(frame.rot),
237
+ sin = Math.sin(frame.rot)
238
+ x = frame.x + p.x * c + p.z * sin
239
+ z = frame.z - p.x * sin + p.z * c
240
+ yaw += frame.rot
241
+ }
242
+ return {
243
+ x: questNumber(x),
244
+ z: questNumber(z),
245
+ y: p.y === undefined ? floorAt(x, z) + dy : questNumber(p.y),
246
+ yaw,
247
+ }
248
+ },
249
+ }
250
+ }
251
+
252
+ export interface Cond {
253
+ all?: string[]
254
+ any?: string[]
255
+ none?: string[]
256
+ }
257
+
258
+ /** what a chest hands out */
259
+ export type ChestItem =
260
+ | { item: string; n?: number }
261
+ | { key: string; label: string }
262
+ | { flag: string; label: string }
263
+
264
+ interface Base {
265
+ /** unique within the table, persisted (flags are named after it) */
266
+ id: string
267
+ at: Place
268
+ /** the E action is refused (the prompt shows `lockedLabel`) until this holds */
269
+ requires?: Cond
270
+ lockedLabel?: string
271
+ /** the row is not there at all (no mesh, no prompt, no collider) until this holds */
272
+ showWhen?: Cond
273
+ /** extra flags raised when the row fires (with its automatic flag) */
274
+ sets?: string[]
275
+ /** a toast when it fires */
276
+ toast?: string
277
+ /** "[E]" reach in metres from the eye (default 2.5) — short for a dive treasure, so it has to be swum down to */
278
+ reach?: number
279
+ }
280
+
281
+ export interface ChestDef extends Base {
282
+ kind: 'chest'
283
+ /** a key id; the chest is locked without `key:<lock>` */ lock?: string
284
+ contents: ChestItem[]
285
+ /** 'crate' (plain) | 'chest' (banded) | 'strongbox' (iron, small) */ look?:
286
+ | 'chest'
287
+ | 'strongbox'
288
+ | 'treasure'
289
+ }
290
+ export interface KeyDef extends Base {
291
+ kind: 'key'
292
+ key: string
293
+ label: string
294
+ }
295
+ export interface DoorDef extends Base {
296
+ kind: 'door'
297
+ /** clear opening, metres */
298
+ w: number
299
+ h: number
300
+ look: 'plank' | 'grate' | 'sluice'
301
+ lock?: string
302
+ /** opens by itself while this holds (plates / levers); closes again when it stops holding unless `latch` */
303
+ opensWhen?: Cond
304
+ latch?: boolean
305
+ }
306
+ export interface LeverDef extends Base {
307
+ kind: 'lever'
308
+ label?: string
309
+ /** once pulled it stays pulled (a puzzle step that is done) */ latch?: boolean
310
+ }
311
+ export interface PlateDef extends Base {
312
+ kind: 'plate'
313
+ /** square side, metres */ size: number
314
+ by: 'player' | 'barrel' | 'any'
315
+ }
316
+ export interface BarrelDef extends Base {
317
+ kind: 'barrel'
318
+ /** the barrel is returned here if it strays further than this (m) from its start */ leash: number
319
+ }
320
+ interface PickupDef extends Base {
321
+ kind: 'pickup'
322
+ /** a registered pickup look's id (registerPickupLook: the kit's flint, coin, resin, token…) */
323
+ look: string
324
+ /** an inventory item id to add (Inventory.ts ItemId) */
325
+ item?: string
326
+ label: string
327
+ /** walk into it (feet within 1.1 m) instead of pressing E */
328
+ touch?: boolean
329
+ /** tint for the glow looks (hex) */
330
+ color?: string
331
+ }
332
+ export interface BeaconDef extends Base {
333
+ kind: 'beacon'
334
+ label: string
335
+ }
336
+ export interface BenchDef extends Base {
337
+ kind: 'bench'
338
+ label: string
339
+ }
340
+ export interface AltarDef extends Base {
341
+ kind: 'altar'
342
+ label: string
343
+ /** how many sockets to draw; socket i is filled while `fills[i]` is set */ fills: string[]
344
+ /** the pickup look that fills a socket */ socketLook: string
345
+ }
346
+
347
+ export type InteractDef =
348
+ | ChestDef
349
+ | KeyDef
350
+ | DoorDef
351
+ | LeverDef
352
+ | PlateDef
353
+ | BarrelDef
354
+ | PickupDef
355
+ | BeaconDef
356
+ | BenchDef
357
+ | AltarDef
358
+
359
+ export interface InteractTable {
360
+ /** flags raised outside the table (quest dialogue, enemy deaths) that rows may read */
361
+ external: string[]
362
+ rows: InteractDef[]
363
+ }
364
+
365
+ /** An authored world-space rest placement. Prompts and laws stay in the table. */
366
+ export interface InteractPlacement {
367
+ readonly id: string
368
+ readonly kind: string
369
+ readonly x: number
370
+ readonly y: number
371
+ readonly z: number
372
+ readonly yaw: number
373
+ }
374
+ /** Admit bounded finite placement rows before geometry, registry or prompt effects. */
375
+ export function readInteractPlacements(
376
+ input: unknown,
377
+ ): readonly InteractPlacement[] {
378
+ if (!Array.isArray(input) || input.length > 4096)
379
+ throw new Error('Invalid interactable placement rows')
380
+ const ids = new Set<string>()
381
+ return input.map((raw: unknown): InteractPlacement => {
382
+ if (
383
+ typeof raw !== 'object' ||
384
+ raw === null ||
385
+ !('id' in raw) ||
386
+ !('kind' in raw) ||
387
+ !('x' in raw) ||
388
+ !('y' in raw) ||
389
+ !('z' in raw) ||
390
+ !('yaw' in raw)
391
+ )
392
+ throw new Error('Invalid interactable placement')
393
+ const { id, kind, x, y, z, yaw } = raw
394
+ if (
395
+ typeof id !== 'string' ||
396
+ id.length === 0 ||
397
+ id.length > 256 ||
398
+ ids.has(id) ||
399
+ typeof kind !== 'string' ||
400
+ kind.length === 0 ||
401
+ kind.length > 64 ||
402
+ typeof x !== 'number' ||
403
+ typeof y !== 'number' ||
404
+ typeof z !== 'number' ||
405
+ typeof yaw !== 'number' ||
406
+ ![x, y, z, yaw].every(Number.isFinite) ||
407
+ Math.max(Math.abs(x), Math.abs(y), Math.abs(z)) > 1000000 ||
408
+ Math.abs(yaw) > 1000000
409
+ )
410
+ throw new Error('Invalid or duplicate interactable placement')
411
+ ids.add(id)
412
+ return { id, kind, x, y, z, yaw }
413
+ })
414
+ }
415
+ /** Bind each authored rest placement to the same table row, in original order.
416
+ * Missing, foreign or mismatched rows refuse before a table can build. Moving
417
+ * keys and barrel/body state retain their existing runtime owners afterward.
418
+ */
419
+ export function bindInteractPlacements(
420
+ table: InteractTable,
421
+ input: unknown,
422
+ ): InteractTable {
423
+ const placements = new Map(
424
+ readInteractPlacements(input).map(row => [row.id, row]),
425
+ )
426
+ if (
427
+ placements.size !== table.rows.length ||
428
+ new Set(table.rows.map(row => row.id)).size !== table.rows.length
429
+ )
430
+ throw new Error('Incomplete interactable placements')
431
+ const rows = table.rows.map(row => {
432
+ const at = placements.get(row.id)
433
+ if (at === undefined || at.kind !== row.kind)
434
+ throw new Error(`Unknown interactable placement ${row.id}`)
435
+ return {
436
+ ...row,
437
+ at: { poi: 'world' as const, x: at.x, y: at.y, z: at.z, yaw: at.yaw },
438
+ }
439
+ })
440
+ return { ...table, rows }
441
+ }
442
+
443
+ /** the automatic flag each kind raises when it fires */
444
+ export function autoFlag(d: InteractDef): string | null {
445
+ switch (d.kind) {
446
+ case 'chest':
447
+ case 'door':
448
+ return `open:${d.id}`
449
+ case 'key':
450
+ case 'pickup':
451
+ return `taken:${d.id}`
452
+ case 'lever':
453
+ return `lever:${d.id}`
454
+ case 'plate':
455
+ return `plate:${d.id}`
456
+ case 'beacon':
457
+ return `lit:${d.id}`
458
+ case 'bench':
459
+ case 'altar':
460
+ return `used:${d.id}`
461
+ case 'barrel':
462
+ return null
463
+ default:
464
+ return null
465
+ }
466
+ }
467
+
468
+ /** every flag a row can raise: its automatic flag, `sets`, a key's `key:`, a chest's key / flag contents */
469
+ export function flagsRaised(d: InteractDef): string[] {
470
+ const out: string[] = []
471
+ const a = autoFlag(d)
472
+ if (a !== null) out.push(a)
473
+ if (d.sets) out.push(...d.sets)
474
+ if (d.kind === 'key') out.push(`key:${d.key}`)
475
+ if (d.kind === 'chest')
476
+ for (const l of d.contents) {
477
+ if ('key' in l) out.push(`key:${l.key}`)
478
+ else if ('flag' in l) out.push(l.flag)
479
+ }
480
+ return out
481
+ }
482
+
483
+ /** every flag a row reads */
484
+ export function flagsRead(d: InteractDef): string[] {
485
+ const out: string[] = []
486
+ const add = (c: Cond | undefined) => {
487
+ if (c) out.push(...(c.all ?? []), ...(c.any ?? []), ...(c.none ?? []))
488
+ }
489
+ add(d.requires)
490
+ add(d.showWhen)
491
+ if (d.kind === 'door') add(d.opensWhen)
492
+ if (d.kind === 'altar') out.push(...d.fills)
493
+ if ((d.kind === 'chest' || d.kind === 'door') && d.lock !== undefined)
494
+ out.push(`key:${d.lock}`)
495
+ return out
496
+ }
497
+
498
+ /** flags that describe a moment, not progress — never persisted */
499
+ export const TRANSIENT_PREFIXES: string[] = ['plate:']
500
+
501
+ /** Compile authored quest-table actions (a pickup, a bench, a latched lever) into declared interaction rows.
502
+
503
+ * Each binding names one row; the row's automatic flag gates it once and is raised with its `sets`. */
504
+ export function compileQuestTable(
505
+ table: InteractTable,
506
+ bindings: readonly { readonly id: string; readonly act: number }[],
507
+ ): InteractionRowsData {
508
+ return parseInteractionRows({
509
+ marks: [],
510
+ rows: bindings.map(binding => {
511
+ const matches = table.rows.filter(row => row.id === binding.id),
512
+ row = matches[0]
513
+ if (
514
+ matches.length !== 1 ||
515
+ row === undefined ||
516
+ !(
517
+ row.kind === 'pickup' ||
518
+ row.kind === 'bench' ||
519
+ (row.kind === 'lever' && row.latch === true)
520
+ )
521
+ ) {
522
+ throw new Error(`Unsupported quest table action ${binding.id}`)
523
+ }
524
+ const flag = autoFlag(row)
525
+ if (flag === null)
526
+ throw new Error(`Missing quest table flag ${binding.id}`)
527
+ const needs = [
528
+ ...(row.showWhen === undefined ? [] : [row.showWhen]),
529
+ ...(row.requires === undefined ? [] : [row.requires]),
530
+ ...(row.kind === 'bench' ? [] : [{ none: [flag] }]),
531
+ ]
532
+ return {
533
+ id: row.id,
534
+ act: binding.act,
535
+ at: row.id,
536
+ needs,
537
+ sets: [flag, ...(row.kind === 'lever' ? [] : (row.sets ?? []))],
538
+ }
539
+ }),
540
+ })
541
+ }