@adatechnology/game-interactables 0.6.11 → 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -181,6 +181,16 @@ Specs carry tags for the shared destruction SDK, `@adatechnology/game-destructio
181
181
 
182
182
  The host builds SDK parts from the tags and routes hits, fire and blasts to the SDK. `DamageSpec` and `world.damage` are deprecated: they keep working, but get no new features.
183
183
 
184
+ ## Controls of one object (`createObjectControls`)
185
+
186
+ For a host that moves the object's parts itself (a test room plays the parts' clips): `createObjectControls({ spec, locale, strings })` gives the
187
+ `ItemControls` of `@adatechnology/game-contracts` for one object, from its data only. Its devices, fixtures, burners and fuel run in a world of their own fed by
188
+ the mains (a socket at each plug, a tank behind every fixture); a part the world moves (a tap's handle, a flush button) is asked of the host (`setPart`).
189
+ `ObjectSpec.uses` add what the object does with the hand or on its own time: `program` (a wash that runs for its seconds with the door shut), `put_in` (what
190
+ the hand holds goes in when the access is open and it fits the inside, `fitsInVolume`), `empty`, `fill` (a bowl from the hand: the food it accepts, water poured)
191
+ and `relieve` (a basin soiled, washed by the flush whose fixture `cleans` it). `state()` says what to draw (screens on and their channel, bowl levels, soil,
192
+ fires); `createControlsView` of game-interactables-three draws it.
193
+
184
194
  ## Português
185
195
 
186
196
  Runtime sem renderer para objetos interativos do mundo: portas, gavetas e tampas que se movem, recipientes com itens e loot determinístico por
package/dist/index.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { CarryHands, Thumbnail } from '@adatechnology/game-contracts';
1
+ import { CarryHands, Thumbnail, ItemControls } from '@adatechnology/game-contracts';
2
2
  import { BodyId, SeamWorld, JointId, Vec3 as Vec3$1, Quat } from '@adatechnology/game-physics';
3
3
 
4
4
  /** A movable part (door, drawer, lid) moved by a physics engine instead of by `t` stepping at `Motion.speed`. */
@@ -145,6 +145,15 @@ interface PartDestruction {
145
145
  spacing: number;
146
146
  diameter: number;
147
147
  };
148
+ /**
149
+ * Masonry laid in units (a brick barbecue, a fireplace): the size of one unit (length, height, depth in metres), its bond and the SDK material of the joints. A host
150
+ * gives the masonry its units (`PartSpec.units` of the destruction SDK), so a hit knocks bricks out where it lands and the part breaks into bricks and rubble, not into blocks.
151
+ */
152
+ units?: {
153
+ size: [number, number, number];
154
+ bond: 'running' | 'stack';
155
+ mortar: string;
156
+ };
148
157
  }
149
158
  /** One stack of items. `type` is an id from the content pack's item catalog. */
150
159
  interface ItemStack {
@@ -246,6 +255,12 @@ interface DeviceSpec {
246
255
  * The fixture is driven by the device: it gets no interaction of its own.
247
256
  */
248
257
  fixture?: string;
258
+ /** For screens: the lit face, object-local (its centre, width and height; it faces +z), where a host draws the picture of the channel. */
259
+ display?: {
260
+ center: Vec3;
261
+ w: number;
262
+ h: number;
263
+ };
249
264
  }
250
265
  interface FuelSourceSpec {
251
266
  id: string;
@@ -295,6 +310,8 @@ interface FixtureSpec {
295
310
  tank?: string | 'auto';
296
311
  /** Needs power too (electric shower heats; still flows cold without power). */
297
312
  heater?: string;
313
+ /** A flush washes this basin (`BasinSpec.id`) clean once its water runs. */
314
+ cleans?: string;
298
315
  }
299
316
  type SeatPose = 'sit' | 'lie';
300
317
  interface SeatSpec {
@@ -363,7 +380,60 @@ interface BasinSpec {
363
380
  to: Vec3;
364
381
  /** `'round'` for a round bowl (a toilet's): the liquid is the upright cylinder inside the box, as wide as its narrower side. Default `'box'`. */
365
382
  shape?: 'box' | 'round';
383
+ /** What a body leaves in it (a toilet's): the `relieve` uses soil it, the flush that `cleans` it washes it. */
384
+ soils?: boolean;
385
+ }
386
+ /** A bowl of food or water (a dog's), filled from the hand. Object-local: the middle of its floor, the inside radius and depth. */
387
+ interface BowlSpec {
388
+ id: string;
389
+ holds: 'food' | 'water';
390
+ /** Catalogue ids of what fills a food bowl (`dog_food`); a water bowl takes any water the hand pours. */
391
+ accepts?: string[];
392
+ /** kg of food or litres of water it holds full. */
393
+ capacity: number;
394
+ /** At start. Default 0 (empty). */
395
+ level?: number;
396
+ center: Vec3;
397
+ radius: number;
398
+ depth: number;
366
399
  }
400
+ /**
401
+ * Something the object does with the player's hand or on its own time, beyond its parts, devices, fixtures and burners (`ObjectSpec.uses`). `label` is a locale key.
402
+ * - `program`: the device runs on its own for `seconds` (a wash, a spin-dry), then stops; started with the `access` part closed (a washing machine's door).
403
+ * - `put_in`: what the hand holds goes into the container, when its access is open and the thing fits its inside.
404
+ * - `empty`: everything in the container goes out (a bin taken to the street).
405
+ * - `fill`: the bowl is filled from the hand (food it accepts, or water poured).
406
+ * - `relieve`: a body leaves `kind` in the basin (a toilet), which a flush washes away.
407
+ */
408
+ type UseSpec = {
409
+ id: string;
410
+ do: 'program';
411
+ device: string;
412
+ seconds: number;
413
+ label: string;
414
+ access?: string;
415
+ } | {
416
+ id: string;
417
+ do: 'put_in';
418
+ container: string;
419
+ label: string;
420
+ } | {
421
+ id: string;
422
+ do: 'empty';
423
+ container: string;
424
+ label: string;
425
+ } | {
426
+ id: string;
427
+ do: 'fill';
428
+ bowl: string;
429
+ label: string;
430
+ } | {
431
+ id: string;
432
+ do: 'relieve';
433
+ basin: string;
434
+ kind: 'urine' | 'feces';
435
+ label: string;
436
+ };
367
437
  interface MirrorSpec {
368
438
  id: string;
369
439
  center: Vec3;
@@ -477,6 +547,10 @@ interface ObjectSpec {
477
547
  emitters?: EmitterSpec[];
478
548
  /** What holds water in it (a sink's basin, a toilet bowl). */
479
549
  basins?: BasinSpec[];
550
+ /** Bowls of food or water filled from the hand. */
551
+ bowls?: BowlSpec[];
552
+ /** What the object does with the hand or on its own time (see `UseSpec`). */
553
+ uses?: UseSpec[];
480
554
  mirrors?: MirrorSpec[];
481
555
  colliders?: ColliderSpec[];
482
556
  /** @deprecated Use the destruction SDK; see `DamageSpec`. */
@@ -988,4 +1062,62 @@ declare function disposeChain(world: SeamWorld, chain: Chain): void;
988
1062
  /** The two ends of every link now, as a polyline (x, y, z per point) for a host that draws the cord: the points a chain was built from, moved. */
989
1063
  declare function chainPoints(world: SeamWorld, chain: Chain, out: Float64Array): void;
990
1064
 
991
- export { type Action, type ActiveEmitter, type BasinSpec, type BurnerSpec, type Chain, type ChainSpec, type ColliderOptions, type ColliderSpec, type ContainerSpec, type DamageKind, type DamageSpec, type DestructionDelegate, type DestructionJoint, type DeviceKind, type DeviceSpec, type EmitterBowl, type EmitterKind, type EmitterSpec, type EnginePartDriver, type EnginePartOptions, type EnginePartPhysics, FLUSH_RUN_SECONDS, type FixtureEmitters, type FixtureKind, type FixtureSpec, type FuelSourceSpec, type Interactable, type InteractablesLocale, type InteractionSpec, type ItemCatalog, type ItemDef, type ItemStack, type LootEntry, type LootTable, type LootTables, type MirrorSpec, type Motion, type MotionKind, type ObjectSpec, type PartDestruction, type PartDriver, type PartPhysics, type PartSpec, type Pose, type Rect, type RunningEmitter, type SeatPose, type SeatResult, type SeatSpec, type SlotSpec, type SocketSpec, type SoftDriver, type SoftSpec, type Strings, type SwitchSpec, type TankSpec, type TargetOptions, type Transform, type Vec3, type World, type WorldCollider, type WorldEvent, type WorldObject, type WorldOptions, type WorldState, alignY, buildChain, chainPoints, createEnginePartPhysics, createFixtureEmitters, createWorld, disposeChain, fitsSize, fitsSlot, format, generateLoot, hashString, localToWorld, locales, mergeColliders, pickLocale, poseOf, resolveStrings, rng, rotY, rotateAxis, worldToLocal };
1065
+ /**
1066
+ * What an object does with the player's hand or on its own time (`ObjectSpec.uses`), for `createObjectControls`: a device's program that runs for its seconds, what
1067
+ * the hand holds put inside when it fits, a container emptied, a bowl filled from the hand, a basin soiled and washed by its flush. The rules are the data's: the
1068
+ * container's inside, the bowl's capacity and what it accepts, the access part that must be open (or closed, for a program).
1069
+ */
1070
+
1071
+ /** What a basin holds, worst last: a flush washes it back to clean. */
1072
+ type Soil = 'clean' | 'urine' | 'feces';
1073
+ interface UsesState {
1074
+ /** kg of food or litres of water in each bowl. */
1075
+ readonly bowls: Readonly<Record<string, number>>;
1076
+ readonly soil: Readonly<Record<string, Soil>>;
1077
+ /** The program running, with its seconds left. */
1078
+ readonly program: {
1079
+ readonly use: string;
1080
+ readonly device: string;
1081
+ readonly left: number;
1082
+ } | null;
1083
+ }
1084
+
1085
+ /**
1086
+ * The controls of one object for a host that moves the object's parts itself (a test room plays the parts' clips, a game its own animation): what the object's spec
1087
+ * says it does (its devices, fixtures, burners and fuel, run by an interactables world of its own fed by the mains), plus what it does with the player's hand or on
1088
+ * its own time (`ObjectSpec.uses`: a program, putting in, emptying, filling a bowl, relieving oneself). Data-driven: nothing here knows a TV from a toilet. Pure: no
1089
+ * three.js; the drawing of what the state shows (a screen's picture, a bowl's level, a fire) reads `state()`.
1090
+ */
1091
+
1092
+ /** The id the object has in its own world. */
1093
+ declare const CONTROLLED_OBJECT = "object";
1094
+ interface ObjectControlsOptions {
1095
+ readonly spec: ObjectSpec;
1096
+ readonly locale?: string;
1097
+ /** The content pack's strings (`Household.strings`). */
1098
+ readonly strings?: Partial<Record<InteractablesLocale, Strings>>;
1099
+ /** Whether the mains give power and water. Default both: a piece standing on its own in a test room is plugged in and piped. */
1100
+ readonly mains?: {
1101
+ readonly power?: boolean;
1102
+ readonly water?: boolean;
1103
+ };
1104
+ }
1105
+ /** What the object shows now, for its drawing. */
1106
+ interface ObjectControlsState extends UsesState {
1107
+ /** Screens on and powered, with their channel. */
1108
+ readonly screens: ReadonlyArray<{
1109
+ readonly device: string;
1110
+ readonly channel: number;
1111
+ }>;
1112
+ /** Fires and smoke of its burners, object-local (the water runs from the parts the host moves). */
1113
+ readonly emitters: readonly ActiveEmitter[];
1114
+ }
1115
+ interface ObjectControls extends ItemControls {
1116
+ state(): ObjectControlsState;
1117
+ }
1118
+ declare function createObjectControls(options: ObjectControlsOptions): ObjectControls;
1119
+
1120
+ /** Whether a thing of `size` (any turn of it) goes into a box of `half` sizes: each of its sides, longest first, against the box's, longest first. */
1121
+ declare function fitsInVolume(size: readonly [number, number, number], half: Vec3): boolean;
1122
+
1123
+ export { type Action, type ActiveEmitter, type BasinSpec, type BowlSpec, type BurnerSpec, CONTROLLED_OBJECT, type Chain, type ChainSpec, type ColliderOptions, type ColliderSpec, type ContainerSpec, type DamageKind, type DamageSpec, type DestructionDelegate, type DestructionJoint, type DeviceKind, type DeviceSpec, type EmitterBowl, type EmitterKind, type EmitterSpec, type EnginePartDriver, type EnginePartOptions, type EnginePartPhysics, FLUSH_RUN_SECONDS, type FixtureEmitters, type FixtureKind, type FixtureSpec, type FuelSourceSpec, type Interactable, type InteractablesLocale, type InteractionSpec, type ItemCatalog, type ItemDef, type ItemStack, type LootEntry, type LootTable, type LootTables, type MirrorSpec, type Motion, type MotionKind, type ObjectControls, type ObjectControlsOptions, type ObjectControlsState, type ObjectSpec, type PartDestruction, type PartDriver, type PartPhysics, type PartSpec, type Pose, type Rect, type RunningEmitter, type SeatPose, type SeatResult, type SeatSpec, type SlotSpec, type SocketSpec, type SoftDriver, type SoftSpec, type Soil, type Strings, type SwitchSpec, type TankSpec, type TargetOptions, type Transform, type UseSpec, type UsesState, type Vec3, type World, type WorldCollider, type WorldEvent, type WorldObject, type WorldOptions, type WorldState, alignY, buildChain, chainPoints, createEnginePartPhysics, createFixtureEmitters, createObjectControls, createWorld, disposeChain, fitsInVolume, fitsSize, fitsSlot, format, generateLoot, hashString, localToWorld, locales, mergeColliders, pickLocale, poseOf, resolveStrings, rng, rotY, rotateAxis, worldToLocal };
@@ -21,14 +21,17 @@ var GameInteractables = (() => {
21
21
  // src/index.ts
22
22
  var index_exports = {};
23
23
  __export(index_exports, {
24
+ CONTROLLED_OBJECT: () => CONTROLLED_OBJECT,
24
25
  FLUSH_RUN_SECONDS: () => FLUSH_RUN_SECONDS,
25
26
  alignY: () => alignY,
26
27
  buildChain: () => buildChain,
27
28
  chainPoints: () => chainPoints,
28
29
  createEnginePartPhysics: () => createEnginePartPhysics,
29
30
  createFixtureEmitters: () => createFixtureEmitters,
31
+ createObjectControls: () => createObjectControls,
30
32
  createWorld: () => createWorld,
31
33
  disposeChain: () => disposeChain,
34
+ fitsInVolume: () => fitsInVolume,
32
35
  fitsSize: () => fitsSize,
33
36
  fitsSlot: () => fitsSlot,
34
37
  format: () => format,
@@ -242,7 +245,31 @@ var GameInteractables = (() => {
242
245
  needs_ignition: "Light it first",
243
246
  turn_on_first: "Turn it on first",
244
247
  empty: "Empty",
245
- full: "Full"
248
+ full: "Full",
249
+ "use.put_in": "Put {item} in {name}",
250
+ "use.put_in.none": "Put what you hold in {name}",
251
+ "use.empty": "Empty {name}",
252
+ "use.fill": "Fill the {bowl} bowl",
253
+ "use.program.stop": "Stop {name} ({left} left)",
254
+ "use.relieve.urine": "Pee",
255
+ "use.relieve.feces": "Poo",
256
+ "bowl.food": "food",
257
+ "bowl.water": "water",
258
+ hand_empty: "Your hand is empty",
259
+ not_fit: "{item} does not fit in {name}",
260
+ not_accepted: "{item} does not go in the {bowl} bowl",
261
+ bowl_full: "The {bowl} bowl is already full",
262
+ needs_closed: "Close it first",
263
+ already_soiled: "Flush first",
264
+ done_put_in: "{item} went into {name}",
265
+ done_empty: "{name} emptied ({n} things)",
266
+ done_fill: "The {bowl} bowl is full",
267
+ done_program: "{name}: {program} started ({time})",
268
+ done_program_end: "{name}: {program} finished",
269
+ done_program_stop: "{name} stopped",
270
+ done_relieve_urine: "You peed in {name}",
271
+ done_relieve_feces: "You pooed in {name}",
272
+ done_clean: "{name} flushed clean"
246
273
  },
247
274
  "pt-BR": {
248
275
  "prompt.open": "Abrir {name}",
@@ -269,7 +296,31 @@ var GameInteractables = (() => {
269
296
  needs_ignition: "Acenda primeiro",
270
297
  turn_on_first: "Ligue primeiro",
271
298
  empty: "Vazio",
272
- full: "Cheio"
299
+ full: "Cheio",
300
+ "use.put_in": "P\xF4r {item} em {name}",
301
+ "use.put_in.none": "P\xF4r o que est\xE1 na m\xE3o em {name}",
302
+ "use.empty": "Esvaziar {name}",
303
+ "use.fill": "Encher o pote de {bowl}",
304
+ "use.program.stop": "Parar {name} (faltam {left})",
305
+ "use.relieve.urine": "Fazer xixi (1)",
306
+ "use.relieve.feces": "Fazer coc\xF4 (2)",
307
+ "bowl.food": "ra\xE7\xE3o",
308
+ "bowl.water": "\xE1gua",
309
+ hand_empty: "A m\xE3o est\xE1 vazia",
310
+ not_fit: "{item} n\xE3o cabe em {name}",
311
+ not_accepted: "{item} n\xE3o vai no pote de {bowl}",
312
+ bowl_full: "O pote de {bowl} j\xE1 est\xE1 cheio",
313
+ needs_closed: "Feche primeiro",
314
+ already_soiled: "D\xEA a descarga primeiro",
315
+ done_put_in: "{item} foi para dentro de {name}",
316
+ done_empty: "{name} esvaziado ({n} coisas)",
317
+ done_fill: "O pote de {bowl} est\xE1 cheio",
318
+ done_program: "{name}: {program} come\xE7ou ({time})",
319
+ done_program_end: "{name}: {program} terminou",
320
+ done_program_stop: "{name} parou",
321
+ done_relieve_urine: "Voc\xEA fez xixi em {name}",
322
+ done_relieve_feces: "Voc\xEA fez coc\xF4 em {name}",
323
+ done_clean: "Descarga dada: {name} limpo"
273
324
  }
274
325
  };
275
326
  function pickLocale(locale) {
@@ -2284,6 +2335,236 @@ var GameInteractables = (() => {
2284
2335
  );
2285
2336
  return createLeafDriver({ world, leaf, frame, ownsFrame, joint, onDispose: request.onDispose, drive: { isHinge, axis, pivot, centre, range, speed, base: rotation } });
2286
2337
  }
2338
+
2339
+ // src/fits-volume.ts
2340
+ function fitsInVolume(size, half) {
2341
+ const thing = [...size].sort((a, b) => b - a);
2342
+ const room = half.map((h) => h * 2).sort((a, b) => b - a);
2343
+ return thing.every((side, i) => side <= (room[i] ?? 0));
2344
+ }
2345
+
2346
+ // src/object-uses.ts
2347
+ var OPEN = 0.5;
2348
+ var PREFIX = "use.";
2349
+ var SOIL_RANK = { clean: 0, urine: 1, feces: 2 };
2350
+ var clock = (seconds) => {
2351
+ const s = Math.max(0, Math.ceil(seconds));
2352
+ return `${Math.floor(s / 60)}:${String(s % 60).padStart(2, "0")}`;
2353
+ };
2354
+ var accepts = (bowl, hand) => (bowl.accepts ?? []).some((id) => hand.itemId === id || hand.itemId.endsWith(`_${id}`));
2355
+ var YES = { available: true };
2356
+ var no = (reason) => ({ available: false, reason });
2357
+ function createUses(options) {
2358
+ const { spec, world, objectId } = options;
2359
+ const all = spec.uses ?? [];
2360
+ const containers = new Map((spec.containers ?? []).map((c) => [c.id, c]));
2361
+ const bowls = new Map((spec.bowls ?? []).map((b) => [b.id, b]));
2362
+ const level = new Map((spec.bowls ?? []).map((b) => [b.id, Math.min(b.capacity, b.level ?? 0)]));
2363
+ const soil = new Map((spec.basins ?? []).filter((b) => b.soils).map((b) => [b.id, "clean"]));
2364
+ const cleans = new Map((spec.fixtures ?? []).flatMap((f) => f.cleans ? [[f.id, f.cleans]] : []));
2365
+ let program = null;
2366
+ let lastHost = null;
2367
+ const typeKey = `type.${spec.type}`;
2368
+ const name = () => {
2369
+ const text = world.t(typeKey);
2370
+ return text === typeKey ? spec.type.replace(/_/g, " ") : text.charAt(0).toLowerCase() + text.slice(1);
2371
+ };
2372
+ const accessOpen = (host, part) => !part || host.partOpening(part) >= OPEN;
2373
+ const verdict = (use, host) => {
2374
+ const hand = host.hand();
2375
+ switch (use.do) {
2376
+ case "program":
2377
+ if (!world.power.isPowered(objectId, use.device)) return no("no_power");
2378
+ return use.access && host.partOpening(use.access) >= OPEN ? no("needs_closed") : YES;
2379
+ case "put_in": {
2380
+ const c = containers.get(use.container);
2381
+ if (!hand) return no("hand_empty");
2382
+ if (!c || !accessOpen(host, c.access)) return no("requires_open");
2383
+ return fitsInVolume(hand.size, c.volume.half) ? YES : no("not_fit");
2384
+ }
2385
+ case "empty":
2386
+ return accessOpen(host, containers.get(use.container)?.access) ? YES : no("requires_open");
2387
+ case "fill": {
2388
+ const bowl = bowls.get(use.bowl);
2389
+ if (!bowl) return no("empty");
2390
+ if ((level.get(bowl.id) ?? 0) >= bowl.capacity - 1e-6) return no("bowl_full");
2391
+ if (!hand) return no("hand_empty");
2392
+ if (bowl.holds === "water" && hand.liquid?.kind === "water" && hand.liquid.closed) return no("requires_open");
2393
+ const fits = bowl.holds === "water" ? hand.liquid?.kind === "water" && hand.liquid.litres > 0 : accepts(bowl, hand);
2394
+ return fits ? YES : no("not_accepted");
2395
+ }
2396
+ case "relieve":
2397
+ return YES;
2398
+ }
2399
+ };
2400
+ const textVars = (use, host) => ({
2401
+ name: name(),
2402
+ item: host.hand()?.name ?? "",
2403
+ bowl: world.t(`bowl.${use.do === "fill" ? bowls.get(use.bowl)?.holds ?? "food" : "food"}`)
2404
+ });
2405
+ const labelOf = (use, host) => world.t(use.do === "put_in" && !host.hand() ? "use.put_in.none" : use.label, textVars(use, host));
2406
+ const runUse = (use, host) => {
2407
+ const vars = textVars(use, host);
2408
+ switch (use.do) {
2409
+ case "program": {
2410
+ world.setDevice(objectId, use.device, true);
2411
+ program = { use, left: use.seconds };
2412
+ return { ok: true, text: world.t("done_program", { ...vars, program: world.t(use.label), time: clock(use.seconds) }) };
2413
+ }
2414
+ case "put_in": {
2415
+ const c = containers.get(use.container);
2416
+ return host.placeHand(c.volume.center) ? { ok: true, text: world.t("done_put_in", vars) } : { ok: false, text: world.t("not_fit", vars) };
2417
+ }
2418
+ case "empty": {
2419
+ const c = containers.get(use.container);
2420
+ const [cx, cy, cz] = c.volume.center;
2421
+ const [hx, hy, hz] = c.volume.half;
2422
+ const n = host.emptyInside([cx - hx, cy - hy, cz - hz], [cx + hx, cy + hy, cz + hz]);
2423
+ return { ok: n > 0, text: world.t(n > 0 ? "done_empty" : "empty", { ...vars, n }) };
2424
+ }
2425
+ case "fill":
2426
+ return fill(bowls.get(use.bowl), host, vars);
2427
+ case "relieve": {
2428
+ const now = soil.get(use.basin) ?? "clean";
2429
+ soil.set(use.basin, SOIL_RANK[use.kind] > SOIL_RANK[now] ? use.kind : now);
2430
+ return { ok: true, text: world.t(`done_relieve_${use.kind}`, vars) };
2431
+ }
2432
+ }
2433
+ };
2434
+ const fill = (bowl, host, vars) => {
2435
+ const now = level.get(bowl.id) ?? 0;
2436
+ const added = bowl.holds === "water" ? host.pourHand(bowl.capacity - now) : bowl.capacity - now;
2437
+ level.set(bowl.id, Math.min(bowl.capacity, now + added));
2438
+ return { ok: added > 0, text: world.t(added > 0 ? "done_fill" : "not_accepted", vars) };
2439
+ };
2440
+ const stopProgram = () => {
2441
+ if (!program) return "";
2442
+ world.setDevice(objectId, program.use.device, false);
2443
+ program = null;
2444
+ return world.t("done_program_stop", { name: name() });
2445
+ };
2446
+ const visible = (use) => use.do !== "program" || program === null;
2447
+ return {
2448
+ has: (id) => id.startsWith(PREFIX),
2449
+ list(host) {
2450
+ lastHost = host;
2451
+ const entries = [];
2452
+ if (program) entries.push({ id: `${PREFIX}stop`, label: world.t("use.program.stop", { name: name(), left: clock(program.left) }), available: true });
2453
+ for (const use of all.filter(visible)) {
2454
+ const v = verdict(use, host);
2455
+ entries.push({ id: `${PREFIX}${use.id}`, label: labelOf(use, host), available: v.available, ...v.available ? {} : { reason: world.t(v.reason, textVars(use, host)) } });
2456
+ }
2457
+ return entries;
2458
+ },
2459
+ run(id, host) {
2460
+ lastHost = host;
2461
+ if (id === `${PREFIX}stop`) return { ok: program !== null, text: stopProgram() };
2462
+ const use = all.find((u) => `${PREFIX}${u.id}` === id);
2463
+ if (!use || !visible(use)) return { ok: false, text: "" };
2464
+ const v = verdict(use, host);
2465
+ return v.available ? runUse(use, host) : { ok: false, text: world.t(v.reason, textVars(use, host)) };
2466
+ },
2467
+ update(dt) {
2468
+ if (!program) return;
2469
+ program.left -= dt;
2470
+ if (program.left > 0) return;
2471
+ const done = world.t("done_program_end", { name: name(), program: world.t(program.use.label) });
2472
+ world.setDevice(objectId, program.use.device, false);
2473
+ program = null;
2474
+ lastHost?.say(done);
2475
+ },
2476
+ flushed(fixture) {
2477
+ const basin = cleans.get(fixture);
2478
+ if (!basin || soil.get(basin) === "clean") return;
2479
+ soil.set(basin, "clean");
2480
+ lastHost?.say(world.t("done_clean", { name: name() }));
2481
+ },
2482
+ state: () => ({
2483
+ bowls: Object.fromEntries(level),
2484
+ soil: Object.fromEntries(soil),
2485
+ program: program ? { use: program.use.id, device: program.use.device, left: program.left } : null
2486
+ })
2487
+ };
2488
+ }
2489
+
2490
+ // src/object-controls.ts
2491
+ var CONTROLLED_OBJECT = "object";
2492
+ var MAINS = "mains";
2493
+ var MAINS_TANK = "water";
2494
+ var HOST_KINDS = /* @__PURE__ */ new Set(["toggle_part", "open_container", "take", "read", "sit", "toggle_breaker"]);
2495
+ var PLUG_FALLBACK = [0, 0.3, 0];
2496
+ function mainsSpec(spec) {
2497
+ const plugged = (spec.devices ?? []).filter((d) => d.socket !== void 0 && !d.circuit);
2498
+ return { type: MAINS, sockets: plugged.map((d, i) => ({ id: `socket_${i}`, pos: d.plug ?? PLUG_FALLBACK })), tanks: [{ id: MAINS_TANK, capacity: 1e9 }] };
2499
+ }
2500
+ function createObjectControls(options) {
2501
+ const { spec } = options;
2502
+ const forwarded = /* @__PURE__ */ new Map();
2503
+ const said = [];
2504
+ let host = null;
2505
+ const world = createWorld({
2506
+ locale: options.locale ?? "en",
2507
+ ...options.strings ? { strings: options.strings } : {},
2508
+ grid: options.mains?.power ?? true,
2509
+ takeContents: false,
2510
+ onEvent: (event) => {
2511
+ if (event.type === "message") said.push(event.text);
2512
+ if (event.type === "part" && event.object === CONTROLLED_OBJECT) forwardPart(event.part, event.target >= 0.5);
2513
+ if (event.type === "fixture" && event.object === CONTROLLED_OBJECT && event.flowing) uses.flushed(event.fixture);
2514
+ }
2515
+ });
2516
+ const forwardPart = (part, open) => {
2517
+ if (forwarded.get(part) === open) return;
2518
+ forwarded.set(part, open);
2519
+ host?.setPart(part, open);
2520
+ };
2521
+ world.add(MAINS, mainsSpec(spec), { x: 0, y: 0, z: 0, ry: 0 });
2522
+ if (options.mains?.water ?? true) world.water.setDefaultTank(`${MAINS}:${MAINS_TANK}`);
2523
+ world.add(CONTROLLED_OBJECT, spec, { x: 0, y: 0, z: 0, ry: 0 });
2524
+ const uses = createUses({ spec, world, objectId: CONTROLLED_OBJECT });
2525
+ const programmedDevices = new Set((spec.uses ?? []).flatMap((u) => u.do === "program" ? [u.device] : []));
2526
+ const switchesOf = (device) => [
2527
+ `device.${device}`,
2528
+ ...(spec.interactions ?? []).flatMap((i) => i.action.do === "toggle_device" && i.action.device === device ? [i.id] : [])
2529
+ ];
2530
+ const programmed = new Set([...programmedDevices].flatMap(switchesOf).map((id) => `${CONTROLLED_OBJECT}:${id}`));
2531
+ const own = (i) => i.object === CONTROLLED_OBJECT && !HOST_KINDS.has(i.kind) && !programmed.has(i.id);
2532
+ const interactions = () => world.interactables().filter(own);
2533
+ const lend = (lent) => {
2534
+ host = lent;
2535
+ };
2536
+ return {
2537
+ list(lent) {
2538
+ lend(lent);
2539
+ const fromWorld = interactions().map((i) => ({ id: i.id, label: i.label, available: i.available, ...i.reason ? { reason: world.t(i.reason) } : {} }));
2540
+ return [...fromWorld, ...uses.list(lent)];
2541
+ },
2542
+ run(id, lent) {
2543
+ lend(lent);
2544
+ if (uses.has(id)) return uses.run(id, lent);
2545
+ const found = interactions().find((i) => i.id === id);
2546
+ if (!found) return { ok: false, text: "" };
2547
+ said.length = 0;
2548
+ const ok = world.act(id);
2549
+ return { ok, text: said.length > 0 ? said.join(" \xB7 ") : found.label };
2550
+ },
2551
+ update(dt, lent) {
2552
+ lend(lent);
2553
+ world.update(dt);
2554
+ uses.update(dt);
2555
+ },
2556
+ state() {
2557
+ const screens = (spec.devices ?? []).filter((d) => d.kind === "screen" && world.power.isOn(CONTROLLED_OBJECT, d.id) && world.power.isPowered(CONTROLLED_OBJECT, d.id)).map((d) => ({ device: d.id, channel: world.power.channel(CONTROLLED_OBJECT, d.id) }));
2558
+ const emitters = world.emitters().filter((e) => e.object === CONTROLLED_OBJECT && e.kind !== "water");
2559
+ return { ...uses.state(), screens, emitters };
2560
+ },
2561
+ dispose() {
2562
+ host = null;
2563
+ world.remove(CONTROLLED_OBJECT);
2564
+ world.remove(MAINS);
2565
+ }
2566
+ };
2567
+ }
2287
2568
  return __toCommonJS(index_exports);
2288
2569
  })();
2289
2570
  //# sourceMappingURL=index.global.js.map