threedog 0.1.0 → 0.2.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/core/Animator.js +1 -0
- package/core/Assets.js +16 -0
- package/core/DebugOverrides.js +143 -0
- package/core/Describe.js +14 -3
- package/core/Engine.js +32 -69
- package/core/Events.js +59 -1
- package/core/I18n.js +2 -2
- package/core/Inspect.js +12 -32
- package/core/InspectScene.js +7 -3
- package/core/MaterialInfo.js +32 -0
- package/core/Ops.js +43 -59
- package/core/Saves.js +5 -4
- package/core/UrlState.js +3 -2
- package/core/Vars.js +1 -0
- package/core/Views.js +49 -0
- package/core/actor.js +2 -2
- package/core/assetReport.js +83 -0
- package/core/catalog.js +169 -0
- package/core/checks.js +67 -0
- package/core/claims.js +51 -0
- package/core/debugView.js +76 -0
- package/core/describeRender.js +45 -0
- package/core/describeText.js +11 -4
- package/core/errorCodes.js +33 -0
- package/core/errorHints.js +6 -1
- package/core/holds.js +106 -0
- package/core/lifecycle.js +1 -0
- package/core/lightWatch.js +23 -3
- package/core/look/coreParts.js +112 -0
- package/core/look/layers.js +136 -0
- package/core/look/part.js +173 -0
- package/core/look/report.js +79 -0
- package/core/look/write.js +86 -0
- package/core/loop.js +15 -14
- package/core/modules.js +19 -5
- package/core/opsAtomic.js +31 -0
- package/core/opsCheck.js +25 -14
- package/core/opsFail.js +20 -0
- package/core/opsHistory.js +6 -6
- package/core/opsRun.js +77 -0
- package/core/params.js +132 -0
- package/core/renamed.js +21 -0
- package/core/saveApply.js +2 -2
- package/core/sceneMethods.js +9 -34
- package/core/services.js +73 -0
- package/core/startup.js +3 -1
- package/core/styleParts.js +2 -2
- package/core/thingExplain.js +68 -0
- package/core/thingOps.js +35 -24
- package/core/things.js +15 -1
- package/core/util.js +11 -0
- package/core/validate.js +23 -7
- package/docs/AI.md +83 -109
- package/docs/API.md +7 -8
- package/docs/CODEMAP.md +63 -51
- package/docs/COMMANDS.md +17 -5
- package/docs/CONVENTIONS.md +17 -6
- package/docs/THREE.md +3 -3
- package/docs/api/assets.md +2 -0
- package/docs/api/characters.md +2 -0
- package/docs/api/collision.md +4 -0
- package/docs/api/content.md +1 -0
- package/docs/api/engine.md +20 -11
- package/docs/api/events.md +5 -1
- package/docs/api/post.md +5 -4
- package/docs/api/saves.md +2 -1
- package/docs/api/sky.md +3 -3
- package/docs/api/style.md +3 -3
- package/docs/api/tools.md +2 -0
- package/docs/api/weather.md +1 -1
- package/docs/recipes/02-npc.md +16 -0
- package/docs/recipes/03-items-pickups.md +1 -1
- package/docs/recipes/06-clock-events.md +13 -0
- package/docs/recipes/07-flow-scenes-pause.md +4 -0
- package/docs/recipes/08-weather-sky.md +1 -1
- package/docs/recipes/09-style-pack.md +5 -5
- package/docs/recipes/12-navmesh.md +22 -0
- package/docs/recipes/13-animation.md +3 -0
- package/docs/recipes/15-perf.md +1 -1
- package/docs/recipes/16-dev-bridge.md +51 -17
- package/docs/recipes/21-camera.md +51 -2
- package/docs/recipes/23-ops.md +45 -9
- package/docs/recipes/27-net.md +1 -1
- package/docs/recipes/29-grid.md +1 -1
- package/docs/recipes/34-environment-lighting.md +9 -8
- package/docs/recipes/38-environment-look-hooks.md +8 -6
- package/docs/recipes/40-scene.md +29 -0
- package/docs/recipes/41-thing-registry.md +29 -0
- package/docs/recipes/43-shader-patches-surface-looks.md +2 -0
- package/docs/recipes/44-water-weather-look-hooks.md +6 -4
- package/docs/recipes/45-cascaded-shadows.md +1 -1
- package/docs/recipes/46-blender-art-route.md +22 -0
- package/docs/recipes/48-make-material.md +70 -0
- package/docs/recipes/49-game-module-contract.md +71 -0
- package/docs/recipes/50-own-renderer.md +12 -0
- package/docs/recipes/51-capability-catalog.md +63 -0
- package/docs/recipes/52-look.md +108 -0
- package/examples/action/GAMEMAP.md +5 -5
- package/examples/action/content/index.js +2 -1
- package/examples/action/content/views.js +6 -0
- package/examples/sheepisland/GAMEMAP.md +2 -3
- package/examples/styletest/GAMEMAP.md +3 -3
- package/examples/styletest/main.js +1 -1
- package/examples/styletest/panel.js +3 -3
- package/examples/world/GAMEMAP.md +3 -3
- package/index.d.ts +27 -0
- package/index.js +3 -1
- package/llms.txt +5 -0
- package/modules/ambience/Ambience.js +5 -2
- package/modules/camera/FirstPersonCamera.js +3 -5
- package/modules/camera/FixedCamera.js +19 -12
- package/modules/camera/FollowCamera.js +14 -8
- package/modules/camera/RtsCamera.js +3 -5
- package/modules/camera/common.js +40 -10
- package/modules/camera/index.js +1 -1
- package/modules/camera/projection.js +34 -0
- package/modules/characters/Character.js +29 -17
- package/modules/characters/astar.js +14 -7
- package/modules/characters/index.js +6 -3
- package/modules/characters/movers/simple.js +6 -1
- package/modules/characters/npcSim.js +8 -2
- package/modules/characters/pathAsync.js +12 -6
- package/modules/characters/pathJob.js +2 -1
- package/modules/characters/proceduralRig.js +5 -1
- package/modules/characters/useModel.js +22 -0
- package/modules/characters/walkTo.js +58 -0
- package/modules/collision/Collision.js +102 -4
- package/modules/content/explain.js +13 -0
- package/modules/content/index.js +2 -0
- package/modules/content/loader.js +3 -0
- package/modules/content/rules.js +1 -0
- package/modules/debug/DebugPanel.js +11 -5
- package/modules/entities/Entities.js +6 -2
- package/modules/flow/index.js +5 -2
- package/modules/gameplay/Dialogue.js +5 -2
- package/modules/gameplay/Interactions.js +12 -2
- package/modules/gameplay/Inventory.js +21 -11
- package/modules/gameplay/Quests.js +13 -3
- package/modules/gameplay/pickups.js +5 -3
- package/modules/grid/Layer.js +1 -1
- package/modules/grid/index.js +1 -1
- package/modules/grid/tiles.js +9 -5
- package/modules/hlod/index.js +5 -2
- package/modules/hud/index.js +5 -2
- package/modules/level/index.js +5 -3
- package/modules/lights/index.js +5 -2
- package/modules/music/Music.js +6 -2
- package/modules/nav/index.js +5 -3
- package/modules/net/Client.js +4 -3
- package/modules/net/Host.js +2 -2
- package/modules/net/index.js +5 -3
- package/modules/particles/Particles.js +1 -1
- package/modules/photo/Photo.js +10 -7
- package/modules/rigid/RigidBodies.js +5 -2
- package/modules/settings/Settings.js +6 -3
- package/modules/settings/apply.js +2 -1
- package/modules/sky/Sky.js +21 -19
- package/modules/sky/cascades.js +6 -6
- package/modules/sky/domeLayers.js +1 -1
- package/modules/sky/environment.js +39 -13
- package/modules/sky/fog.js +9 -6
- package/modules/sky/frame.js +4 -3
- package/modules/sky/look.js +3 -2
- package/modules/sky/lookFog.js +80 -0
- package/modules/sky/lookShadow.js +50 -0
- package/modules/sky/lookSky.js +108 -0
- package/modules/sky/shader.js +2 -2
- package/modules/sky/shadow.js +4 -10
- package/modules/sky/skyModule.js +4 -3
- package/modules/terrain/ChunkManager.js +2 -33
- package/modules/terrain/chunkLevels.js +40 -0
- package/modules/terrain/index.js +10 -2
- package/modules/terrain/lookGround.js +61 -0
- package/modules/timeline/Timeline.js +7 -3
- package/modules/timeline/Tween.js +3 -7
- package/modules/timeline/shots.js +6 -4
- package/modules/triggers/index.js +9 -2
- package/modules/vegetation/Vegetation.js +2 -1
- package/modules/vegetation/index.js +6 -3
- package/modules/vegetation/lookWind.js +37 -0
- package/modules/water/Water.js +19 -3
- package/modules/water/look.js +80 -0
- package/modules/weather/Weather.js +22 -31
- package/modules/weather/look.js +75 -0
- package/modules/weather/particles.js +1 -1
- package/modules/weather/strings.js +15 -0
- package/modules/world/explain.js +11 -0
- package/modules/world/index.js +11 -4
- package/modules/world/thingSource.js +44 -0
- package/package.json +1 -1
- package/render/PostFX.js +48 -51
- package/render/effects.js +4 -2
- package/render/fuse.js +12 -0
- package/render/lights.js +4 -2
- package/render/lookSurface.js +161 -0
- package/render/materials.js +27 -10
- package/render/postLook.js +86 -0
- package/render/surface.js +3 -1
- package/types/core.d.ts +216 -24
- package/types/gameplay.d.ts +10 -0
- package/types/generated/core/DebugOverrides.d.ts +52 -0
- package/types/generated/core/Events.d.ts +43 -0
- package/types/generated/core/Ops.d.ts +62 -21
- package/types/generated/core/Saves.d.ts +1 -0
- package/types/generated/core/Views.d.ts +33 -0
- package/types/generated/modules/debug/DebugPanel.d.ts +2 -2
- package/types/generated/modules/grid/Layer.d.ts +1 -0
- package/types/generated/modules/sky/Sky.d.ts +10 -17
- package/types/generated/modules/weather/Weather.d.ts +5 -15
- package/types/generated/render/PostFX.d.ts +20 -23
- package/types/generated/render/materials.d.ts +10 -0
- package/types/physics.d.ts +8 -0
- package/types/style.d.ts +16 -6
- package/ui/Parts.js +6 -2
- package/ui/UI.js +1 -1
- package/ui/defaults.js +1 -1
- package/docs/api/debug.md +0 -10
package/core/params.js
ADDED
|
@@ -0,0 +1,132 @@
|
|
|
1
|
+
// Param schemas: one plain-object description per field, shared by op args (ops.define args) and module params (readParams).
|
|
2
|
+
// Why one shape for both: the same schema validates the call, fills its defaults and is what engine.catalog() shows, so code,
|
|
3
|
+
// catalog and the dev bridge cannot disagree about a field (no second copy in docs or TypeScript).
|
|
4
|
+
// short form: 'int' / 'int?' (type, ? = optional)
|
|
5
|
+
// full form: { type: 'int', default: 1, min: 1, max: 99, values: [...], desc: 'how many', optional: true } (default implies optional)
|
|
6
|
+
import { closest, fmt, DEV, warnOnce, unknownOptionText } from './validate.js';
|
|
7
|
+
import { codedError, coded } from './errorHints.js';
|
|
8
|
+
|
|
9
|
+
/** Types an op arg may use: plain data only. Two meanings of 'id' on purpose: as a module param it is any string; as an op arg it must also be a world record id (checked in dev by opsCheck) */
|
|
10
|
+
export const OP_TYPES = ['string', 'number', 'int', 'bool', 'position', 'id', 'any'];
|
|
11
|
+
export const TYPES = ['string', 'number', 'int', 'bool', 'position', 'id', 'any', 'object', 'array', 'function'];
|
|
12
|
+
const SPEC_KEYS = ['type', 'default', 'min', 'max', 'values', 'desc', 'optional'];
|
|
13
|
+
const isPos = v => Array.isArray(v) && (v.length === 2 || v.length === 3) && v.every(Number.isFinite);
|
|
14
|
+
/** type name -> value check (op args use the first seven: plain data only) */
|
|
15
|
+
export const CHECK = {
|
|
16
|
+
string: v => typeof v === 'string', number: v => Number.isFinite(v), int: v => Number.isInteger(v), bool: v => typeof v === 'boolean',
|
|
17
|
+
position: isPos, id: v => typeof v === 'string', any: () => true, object: v => !!v && typeof v === 'object' && !Array.isArray(v),
|
|
18
|
+
array: Array.isArray, function: v => typeof v === 'function',
|
|
19
|
+
};
|
|
20
|
+
const STRINGS = {
|
|
21
|
+
badType: "{where}: {key} has type '{type}'; use one of {list} (add ? for optional, e.g. 'int?', or { type: 'int', default: 1 })",
|
|
22
|
+
badSpec: '{where}: {key} has unknown schema field {field}{hint}; schema fields: ' + SPEC_KEYS.join(', '),
|
|
23
|
+
badDefault: '{where}: the default of {key} ({got}) does not fit its own schema: {why}',
|
|
24
|
+
wrong: '{where}: {key} {why}',
|
|
25
|
+
};
|
|
26
|
+
|
|
27
|
+
/** Parse one field spec ('int?' or { type, default, ... }) into { type, optional, default?, min?, max?, values?, desc? }; throws on a bad spec */
|
|
28
|
+
export function parseSpec(where, key, spec, err = codedError.bind(null, 'engine-misuse')) {
|
|
29
|
+
const s = typeof spec === 'string' ? { type: spec.replace(/\?$/, ''), optional: spec.endsWith('?') } : { ...spec };
|
|
30
|
+
if (typeof spec !== 'string') {
|
|
31
|
+
for (const f of Object.keys(s)) if (!SPEC_KEYS.includes(f)) {
|
|
32
|
+
const c = closest(f, SPEC_KEYS);
|
|
33
|
+
throw err(fmt(STRINGS.badSpec, { where, key, field: f, hint: c ? ` (did you mean ${c}?)` : '' }));
|
|
34
|
+
}
|
|
35
|
+
s.optional = !!s.optional || 'default' in s;
|
|
36
|
+
}
|
|
37
|
+
if (!TYPES.includes(s.type)) throw err(fmt(STRINGS.badType, { where, key, type: String(s.type ?? spec), list: TYPES.join(' ') }));
|
|
38
|
+
if ('default' in s) { const why = whyBad(s, s.default); if (why) throw err(fmt(STRINGS.badDefault, { where, key, got: JSON.stringify(s.default), why })); }
|
|
39
|
+
return s;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/** Parse a whole schema ({ key: spec }) -> { key: parsed } (null when there is none) */
|
|
43
|
+
export function parseSchema(where, schema, err) {
|
|
44
|
+
if (!schema) return null;
|
|
45
|
+
const out = {};
|
|
46
|
+
for (const key in schema) out[key] = parseSpec(where, key, schema[key], err);
|
|
47
|
+
return out;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/** Why v does not fit the parsed spec s (type, range, allowed values), or null when it does */
|
|
51
|
+
export function whyBad(s, v) {
|
|
52
|
+
if (!CHECK[s.type](v)) return `should be ${s.type === 'position' ? '[x, y, z]' : s.type}, got ${JSON.stringify(v) ?? typeof v}`;
|
|
53
|
+
if (s.min != null && v < s.min) return `must be >= ${s.min}, got ${v}`;
|
|
54
|
+
if (s.max != null && v > s.max) return `must be <= ${s.max}, got ${v}`;
|
|
55
|
+
if (s.values && !s.values.includes(v)) return `must be one of ${s.values.map(x => JSON.stringify(x)).join(', ')}, got ${JSON.stringify(v)}`;
|
|
56
|
+
return null;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/** { key: default } of the fields that declare one, or null when none do (so callers skip the copy) */
|
|
60
|
+
export function defaultsOf(shape) {
|
|
61
|
+
let out = null;
|
|
62
|
+
for (const key in shape || {}) if ('default' in shape[key]) (out ??= {})[key] = shape[key].default;
|
|
63
|
+
return out;
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/** args with the missing fields filled from defaults (a new object; args itself may be frozen) */
|
|
67
|
+
export function withDefaults(defaults, args) {
|
|
68
|
+
if (!defaults) return args;
|
|
69
|
+
const out = { ...args };
|
|
70
|
+
for (const k in defaults) if (out[k] === undefined) out[k] = defaults[k];
|
|
71
|
+
return out;
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/** Shape as plain data for engine.catalog() and the dev bridge: functions and undefined fields left out */
|
|
75
|
+
export function schemaInfo(shape) {
|
|
76
|
+
if (!shape) return null;
|
|
77
|
+
const out = {};
|
|
78
|
+
for (const key in shape) {
|
|
79
|
+
const s = shape[key], o = { type: s.type };
|
|
80
|
+
if (s.optional) o.optional = true;
|
|
81
|
+
for (const f of ['default', 'min', 'max', 'values', 'desc']) if (s[f] !== undefined && typeof s[f] !== 'function') o[f] = s[f];
|
|
82
|
+
out[key] = o;
|
|
83
|
+
}
|
|
84
|
+
return out;
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/**
|
|
88
|
+
* Module options read through a params schema: unknown keys and wrong types throw (with the fix), defaults are filled in.
|
|
89
|
+
* Put the schema on the module definition too (`params`, `options`), so engine.catalog(name) shows every option, its default and the value in use.
|
|
90
|
+
* @param {string} where who reads them, for the error text (the module name)
|
|
91
|
+
* @param {Record<string, string | { type: string, default?: any, min?: number, max?: number, values?: any[], desc?: string, optional?: boolean }>} schema
|
|
92
|
+
* @param {object} [opts] what the game passed
|
|
93
|
+
* @returns {object} opts with defaults filled in
|
|
94
|
+
* @example
|
|
95
|
+
* const PARAMS = { radius: { type: 'number', default: 2, min: 0, desc: 'pickup reach in m' }, sound: 'string?' };
|
|
96
|
+
* export const magnet = (opts) => {
|
|
97
|
+
* const o = readParams('magnet', PARAMS, opts);
|
|
98
|
+
* return { name: 'magnet', params: PARAMS, options: o, install(e) { return { radius: o.radius }; } };
|
|
99
|
+
* };
|
|
100
|
+
*/
|
|
101
|
+
export function readParams(where, schema, opts = {}) {
|
|
102
|
+
const shape = parseSchema(where, schema), err = msg => codedError('module-params', msg);
|
|
103
|
+
const out = withDefaults(defaultsOf(shape), opts ?? {}); // checked in every build: it runs once per factory call, and a wrong option is a bug anywhere
|
|
104
|
+
const keys = Object.keys(shape);
|
|
105
|
+
for (const key of Object.keys(out)) if (!shape[key]) {
|
|
106
|
+
const msg = unknownOptionText(where, key, keys); // one rule with checkOptions (validate.js)
|
|
107
|
+
if (DEV) throw err(msg); // an option typo: dev throws, a release build warns once and ignores it (decision 2026-11-01), so a shipped game never dies on a typo
|
|
108
|
+
warnOnce(coded('module-params', msg));
|
|
109
|
+
}
|
|
110
|
+
for (const key of keys) {
|
|
111
|
+
const v = out[key];
|
|
112
|
+
if (v === undefined) { if (!shape[key].optional) throw err(fmt(STRINGS.wrong, { where, key, why: 'is required' })); continue; }
|
|
113
|
+
const why = whyBad(shape[key], v);
|
|
114
|
+
if (why) throw err(fmt(STRINGS.wrong, { where, key, why }));
|
|
115
|
+
}
|
|
116
|
+
return out;
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
/**
|
|
120
|
+
* Schema for a module whose options are a key list (and maybe a defaults object): every key is `any` (nothing about the value is checked
|
|
121
|
+
* beyond the spelling of the key), and a key present in `defaults` shows that default in engine.catalog(). Why `any`: these modules' options
|
|
122
|
+
* accept several shapes (number | [x, z], preset name | object), and their own code already checks the values; the schema is for the key
|
|
123
|
+
* list, the catalog and R06. Pass `specs` ({ key: 'int?' | { type, ... } }) to give a key a real type; it wins over the generic one.
|
|
124
|
+
* @param {string[]} keys
|
|
125
|
+
* @param {Record<string, any>} [defaults] defaults shown in the catalog (not applied: the module's own code still does that)
|
|
126
|
+
* @param {Record<string, any>} [specs]
|
|
127
|
+
*/
|
|
128
|
+
export function keysSchema(keys, defaults = {}, specs = {}) {
|
|
129
|
+
const out = {};
|
|
130
|
+
for (const k of keys) out[k] = specs[k] ?? (defaults[k] !== undefined ? { type: 'any', default: defaults[k] } : 'any?');
|
|
131
|
+
return out;
|
|
132
|
+
}
|
package/core/renamed.js
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
// The ONE list of names renamed in 0.2: plain data with no imports (errorHints.js re-exports it for the stubs; rule R39 reads it through 'threedog/error-hints').
|
|
2
|
+
/**
|
|
3
|
+
* The ONE list of names renamed in 0.2 (recipes/52-look.md "Renamed in 0.2"): key -> { old call, new call, find = a regex source that spots a
|
|
4
|
+
* use of the old name in source text }. The throwing stubs read `old` / `now` through renamed(key); rule R39 reads `find` to keep the old names out of the repo.
|
|
5
|
+
* `find: null` = no safe text pattern (the old name is a field name shared with unrelated objects).
|
|
6
|
+
* @type {Record<string, { old: string, now: string, find: string | null }>}
|
|
7
|
+
*/
|
|
8
|
+
export const RENAMED = {
|
|
9
|
+
setExposure: { old: 'engine.setExposure(v)', now: 'engine.look.tone.set({ exposure: v })', find: '\\bsetExposure\\b' },
|
|
10
|
+
setToneMapping: { old: 'engine.setToneMapping(kind)', now: "engine.look.tone.set({ mapping: 'aces' })", find: '\\bsetToneMapping\\b' },
|
|
11
|
+
setEnvironment: { old: 'engine.sky.setEnvironment(o)', now: "engine.look.env.replace('sky') then engine.look.env.set({ intensity, rotation }); engine.look.env.replace(false) turns it off", find: '\\bsetEnvironment\\b' },
|
|
12
|
+
setShadow: { old: 'engine.sky.setShadow(o)', now: 'engine.look.shadow.set(o)', find: '\\bsetShadow\\b' },
|
|
13
|
+
weatherDefine: { old: 'engine.weather.define(field, spec)', now: 'engine.look.weather.replace({ [field]: spec })', find: '\\bweather\\??\\.define\\b' },
|
|
14
|
+
postAdd: { old: 'engine.post.add(effect)', now: 'engine.look.post.add(effect, { owner }) for one pass (returns { remove() }), patch(name, { glsl }) for a color effect, or replace([...effects]) for the whole chain', find: '(?<!look\\.)\\bpost\\??\\.add\\b' },
|
|
15
|
+
postEnable: { old: 'engine.post.enable(name, on)', now: "engine.look.post.set({ 'bloom.enabled': on }); MSAA: engine.post.setAntialias(on)", find: '\\bpost\\??\\.enable\\b' },
|
|
16
|
+
postHandle: { old: 'engine.post.get(name).set / .enable / .remove', now: "engine.look.post.set({ 'bloom.strength': 0.6 }); read with engine.post.get(name)", find: '\\bpost\\??\\.get\\([^)]*\\)\\??\\.(set|enable|remove)\\b' },
|
|
17
|
+
lookClouds: { old: 'engine.look.clouds', now: 'engine.look.cloudShadow', find: '\\blook\\.clouds\\b' },
|
|
18
|
+
cameraOverride: { old: 'engine.cameraOverride = {...}', now: "const cam = engine.takeCamera('owner', { focus }); cam.remove() releases it", find: '\\bcameraOverride\\s*=(?!=)' },
|
|
19
|
+
viewsPos: { old: "views.define(name, { pos })", now: 'views.define(name, { position: [x, y, z] })', find: null },
|
|
20
|
+
reason: { old: 'result.reason (ops.run / can / undo failures), ops.recent() / catalog(op).last / net:result .reason', now: 'result.code (the same name in history, catalog and net:result)', find: null },
|
|
21
|
+
};
|
package/core/saveApply.js
CHANGED
|
@@ -113,8 +113,8 @@ export function loadSlot(s, slot, base) {
|
|
|
113
113
|
export async function afterLoad(e) {
|
|
114
114
|
const hooks = [...e.modules.values()].filter(m => m.afterLoad);
|
|
115
115
|
if (!hooks.length) return;
|
|
116
|
-
e.freeze('load');
|
|
117
|
-
try { await Promise.all(hooks.map(m => m.afterLoad(e))); } finally { e.unfreeze('load'); }
|
|
116
|
+
e.freeze('threedog:load'); // a namespaced owner: a game's own freeze('load') must not be released by (or release) the engine's
|
|
117
|
+
try { await Promise.all(hooks.map(m => m.afterLoad(e))); } finally { e.unfreeze('threedog:load'); }
|
|
118
118
|
}
|
|
119
119
|
|
|
120
120
|
/** Collect every part: { data, failed: [[key, error]] }. Parts of the loaded save that no module owns are carried along. */
|
package/core/sceneMethods.js
CHANGED
|
@@ -2,32 +2,12 @@
|
|
|
2
2
|
// tone mapping and exposure.
|
|
3
3
|
// add registers each root in the thing registry (things.js) so engine.thing / hit.thing can say what it is and what a save keeps; engine.scene.add
|
|
4
4
|
// stays the plain three.js way in, with no registration.
|
|
5
|
-
import * as THREE from 'three';
|
|
6
5
|
import { DEV } from './validate.js';
|
|
7
|
-
import { codedError } from './errorHints.js';
|
|
6
|
+
import { codedError, renamed } from './errorHints.js';
|
|
8
7
|
import { thing } from './thingOps.js';
|
|
9
|
-
import {
|
|
8
|
+
import { TONE, exposureDriver } from './look/coreParts.js';
|
|
10
9
|
|
|
11
|
-
|
|
12
|
-
export const TONE = { aces: THREE.ACESFilmicToneMapping, agx: THREE.AgXToneMapping, neutral: THREE.NeutralToneMapping, none: THREE.NoToneMapping };
|
|
13
|
-
|
|
14
|
-
/**
|
|
15
|
-
* Exposure over the day: [[time 0-1, exposure], ...] sorted by time, wrapping across midnight (after the last row it blends back to the first),
|
|
16
|
-
* or (sky) => number. Returns the per-frame function, null for a plain number (set once)
|
|
17
|
-
*/
|
|
18
|
-
function exposureDriver(v) {
|
|
19
|
-
if (typeof v === 'number') return null;
|
|
20
|
-
if (typeof v === 'function') return v;
|
|
21
|
-
const ok = Array.isArray(v) && v.length > 0 && v.every((k, i) => Array.isArray(k) && typeof k[0] === 'number' && typeof k[1] === 'number' && k[0] >= 0 && k[0] <= 1 && (i === 0 || k[0] > v[i - 1][0]));
|
|
22
|
-
if (!ok) throw new Error(`exposure must be a number, [[time 0-1, exposure], ...] sorted by time (e.g. [[0, 1.6], [0.5, 1], [0.8, 1.3]]) or (sky) => number; got ${JSON.stringify(v)}`);
|
|
23
|
-
return sky => {
|
|
24
|
-
const t = sky.timeOfDay, n = v.length;
|
|
25
|
-
let i = -1; for (let k = 0; k < n; k++) if (v[k][0] <= t) i = k;
|
|
26
|
-
const a = v[i < 0 ? n - 1 : i], b = v[(i + 1) % n]; // before the first row or after the last: the segment across midnight
|
|
27
|
-
const span = (b[0] - a[0] + 1) % 1 || 1, f = ((t - a[0] + 1) % 1) / span;
|
|
28
|
-
return a[1] + (b[1] - a[1]) * f;
|
|
29
|
-
};
|
|
30
|
-
}
|
|
10
|
+
export { TONE } from './look/coreParts.js'; // style.toneMapping names -> three constants (kept here for older imports)
|
|
31
11
|
|
|
32
12
|
/** A short stack for "added at main.js:50" (dev): 4 frames are enough (this, add, its caller) and keep the cost low; it is formatted only when read */
|
|
33
13
|
function captureStack() {
|
|
@@ -51,7 +31,7 @@ export const sceneMethods = {
|
|
|
51
31
|
if (opts?.id != null && objs.length > 1) throw codedError('thing-id', `engine.add(a, b, …, { id: '${opts.id}' }): an id names one object; add the others in their own call`);
|
|
52
32
|
const T = this._things, stack = DEV && !opts?.owner && T.wantStack() ? captureStack() : null;
|
|
53
33
|
if (DEV && opts?.owner !== 'world') for (const o of objs) {
|
|
54
|
-
const rid = this.
|
|
34
|
+
const rid = this._things.idOf(o);
|
|
55
35
|
if (rid) throw codedError('thing-owned', `engine.add(): this object is the model of world record '${rid}' (world builds, places and tears it down). Change the record instead: ops.run('thing.set', { id: '${rid}', position }) or world.set / world.move`);
|
|
56
36
|
}
|
|
57
37
|
this.scene.add(...objs);
|
|
@@ -67,7 +47,7 @@ export const sceneMethods = {
|
|
|
67
47
|
* @param {string | import('three').Object3D} idOrObj
|
|
68
48
|
* @returns {import('../types/core').Thing}
|
|
69
49
|
*/
|
|
70
|
-
thing(idOrObj) { return thing(this, idOrObj
|
|
50
|
+
thing(idOrObj) { return thing(this, idOrObj); },
|
|
71
51
|
/** @internal Dev: a module found two systems managing one object; listed in describe().scene.conflicts and warned once (code thing-owned) */
|
|
72
52
|
thingConflict(text) { this._things.conflict(text); },
|
|
73
53
|
/** Detach from the parent only (no GPU release; use when you will add it back). Use remove for objects you are done with */
|
|
@@ -113,13 +93,8 @@ export const sceneMethods = {
|
|
|
113
93
|
if (this.scene.fog) { this.scene.fog.far = d; this.scene.fog.near = d * 0.3; }
|
|
114
94
|
this.camera.far = d + 150; this.camera.updateProjectionMatrix();
|
|
115
95
|
},
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
}
|
|
120
|
-
setExposure(v) {
|
|
121
|
-
// keyframes / a function become exposureDriver, which a time-of-day module (sky) evaluates each frame; core knows no time of day
|
|
122
|
-
this.exposureDriver = exposureDriver(v);
|
|
123
|
-
if (typeof v === 'number') this.renderer.toneMappingExposure = v;
|
|
124
|
-
}
|
|
96
|
+
/** Renamed in 0.2: throws and names the new call, engine.look.tone.set({ mapping }). @param {string} _kind @returns {never} */
|
|
97
|
+
setToneMapping(_kind) { return renamed('setToneMapping'); },
|
|
98
|
+
/** Renamed in 0.2: throws and names the new call, engine.look.tone.set({ exposure }). @param {any} _v @returns {never} */
|
|
99
|
+
setExposure(_v) { return renamed('setExposure'); }
|
|
125
100
|
};
|
package/core/services.js
ADDED
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
// Engine services: the objects every engine owns besides rendering (events, i18n, saves, input, audio, assets, clock, ops, jobs, streaming...).
|
|
2
|
+
// Split out of the Engine constructor so it stays readable; the order below matters (later services read earlier ones), do not reorder.
|
|
3
|
+
import { Events } from './Events.js';
|
|
4
|
+
import { I18n } from './I18n.js';
|
|
5
|
+
import { Saves } from './Saves.js';
|
|
6
|
+
import { Session } from './session.js';
|
|
7
|
+
import { Input } from './Input.js';
|
|
8
|
+
import { Audio } from './Audio.js';
|
|
9
|
+
import { Assets } from './Assets.js';
|
|
10
|
+
import { Clock } from './Clock.js';
|
|
11
|
+
import { Vars } from './Vars.js';
|
|
12
|
+
import { Budget } from './Budget.js';
|
|
13
|
+
import { Rays } from './Rays.js';
|
|
14
|
+
import { Random } from './Random.js';
|
|
15
|
+
import { UrlState } from './UrlState.js';
|
|
16
|
+
import { Jobs } from './Jobs.js';
|
|
17
|
+
import { Threads } from './Threads.js';
|
|
18
|
+
import { Commits } from './Commits.js';
|
|
19
|
+
import { Ops } from './Ops.js';
|
|
20
|
+
import { Views } from './Views.js';
|
|
21
|
+
import { Stream } from './Stream.js';
|
|
22
|
+
import { Batching } from './Batching.js';
|
|
23
|
+
import { claims } from './claims.js';
|
|
24
|
+
import { DebugOverrides } from './DebugOverrides.js';
|
|
25
|
+
import { describeApi } from './Describe.js';
|
|
26
|
+
import { reportListenerError } from './errors.js';
|
|
27
|
+
import { defineSkipOp } from './skip.js';
|
|
28
|
+
import { installThings } from './thingOps.js';
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* Create the engine services on `engine` (called once from the Engine constructor, after the renderer, scene and uniforms exist).
|
|
32
|
+
* @param engine the engine under construction
|
|
33
|
+
* @param o the createEngine options these services read, already defaulted by the constructor
|
|
34
|
+
*/
|
|
35
|
+
export function createServices(engine, { canvas, validate, locale, strings, saveKey, joystick, bindings, padBindings, audio, decoders, budget, seed, headless, urlState, threads, batching }) {
|
|
36
|
+
engine.events = new Events({ check: import.meta.env?.DEV && validate !== false, // event-name spelling check runs in development only
|
|
37
|
+
onError: (name, err) => reportListenerError(engine, name, err), now: () => engine.tick }); // listener errors are handled by severity (errors.js)
|
|
38
|
+
engine.i18n = new I18n(engine, { locale, strings });
|
|
39
|
+
engine.saves = new Saves(engine, { prefix: saveKey + '-' });
|
|
40
|
+
engine.session = new Session(engine); // new game / continue / back to title from a clean slate (session.js)
|
|
41
|
+
engine.input = new Input(engine, canvas, { joystick, bindings, padBindings });
|
|
42
|
+
engine.events.on('ui:open', id => engine.openWindows.add(id));
|
|
43
|
+
engine.events.on('ui:close', id => engine.openWindows.delete(id));
|
|
44
|
+
engine.audio = new Audio(engine, audio);
|
|
45
|
+
engine.decoders = decoders;
|
|
46
|
+
engine.assets = new Assets(engine);
|
|
47
|
+
engine.clock = new Clock(engine); // game clock (game seconds, timers)
|
|
48
|
+
engine.vars = new Vars(engine); // story flags and counters
|
|
49
|
+
engine.budget = new Budget(engine); // performance budget (default off)
|
|
50
|
+
if (budget) engine.budget.enable(budget);
|
|
51
|
+
engine.rays = new Rays(engine); // ray registry: engine.raycast / pick
|
|
52
|
+
Object.assign(engine, describeApi(engine)); // describe / describeText / inspect / explain, see Describe.js
|
|
53
|
+
engine.random = new Random(seed ?? (headless ? 1 : Date.now())); // wall-clock: differs per run when no seed is given
|
|
54
|
+
engine.saves.register('random', { atomic: true, save: () => engine.random.toJSON(), load: d => engine.random.fromJSON(d) });
|
|
55
|
+
engine._urlState = new UrlState(engine, { fromUrl: urlState });
|
|
56
|
+
// who holds the engine still, one claims() each (claims.js: same owner rules for all, owners() in describe); pause / freeze / takeCamera in holds.js
|
|
57
|
+
const now = () => engine.elapsed ?? 0;
|
|
58
|
+
engine._freezers = claims({ what: 'engine.freeze', now }); // who froze gameplay
|
|
59
|
+
engine._pausers = claims({ what: 'engine.pause', now }); // who paused the loop; it resumes only when empty
|
|
60
|
+
engine._cameraClaims = claims({ what: 'engine.takeCamera', now }); // who holds the camera; the latest is in charge (cameraOverride)
|
|
61
|
+
engine.tick = 0; // fixed-step count (the gameplay timeline: commits, event history and input records use it; stops while frozen)
|
|
62
|
+
engine.commits = new Commits(engine); // background results that affect gameplay take effect on a fixed tick (see Commits.js)
|
|
63
|
+
engine.ops = new Ops(engine); // one entry point for actions (define / run / can / list / recent), see Ops.js
|
|
64
|
+
engine.views = new Views(engine); // named fixed camera views for repeatable screenshots (Views.js)
|
|
65
|
+
defineSkipOp(engine); // 'time.skip', behind engine.skip (skip.js)
|
|
66
|
+
installThings(engine); // engine.add registry, thing.set / remove, 'scene' save part
|
|
67
|
+
engine.debug = new DebugOverrides(engine); // diagnostic overrides and view modes, all core; the debug() panel module adds engine.debug.panel (DebugOverrides.js)
|
|
68
|
+
engine.jobs = new Jobs(engine); // frame-spread job scheduler
|
|
69
|
+
engine.threads = new Threads(threads); // worker pool (see Threads.js); workers start only when a lane is used
|
|
70
|
+
// spatial stream-in and the stream sources (where the world is loaded: stream, models, terrain, colliders read them)
|
|
71
|
+
engine.stream = new Stream(engine);
|
|
72
|
+
engine.batching = new Batching(engine, batching); // repeated static models drawn as InstancedMesh batches (Batching.js)
|
|
73
|
+
}
|
package/core/startup.js
CHANGED
|
@@ -3,6 +3,7 @@
|
|
|
3
3
|
// A critical asset (manifest critical: true) that fails stops start() with the reason instead of starting a broken game.
|
|
4
4
|
|
|
5
5
|
import { reportError } from './errors.js';
|
|
6
|
+
import { catalogSnap, catalogClaim } from './catalog.js';
|
|
6
7
|
import { codedError } from './errorHints.js';
|
|
7
8
|
import { touchStart } from './inputTouch.js';
|
|
8
9
|
import { Loading, failureText } from './Loading.js';
|
|
@@ -47,7 +48,8 @@ export const startupMethods = {
|
|
|
47
48
|
ls?.update({ progress: 0.1, text: this.t('common.preparing', { name: this.moduleName(m) }) });
|
|
48
49
|
const t = performance.now(); // measure
|
|
49
50
|
this._setModState(m, 'initializing'); // no hooks until init succeeded (modules.js)
|
|
50
|
-
|
|
51
|
+
const snap = catalogSnap(this); // what init registers belongs to this module in engine.catalog()
|
|
52
|
+
try { await m.init(this); catalogClaim(this, m.name, snap); L._done(task); this._setModState(m, 'running'); }
|
|
51
53
|
catch (e) {
|
|
52
54
|
L._fail(task, e); this._setModState(m, 'failed');
|
|
53
55
|
// a critical module stops start() with the reason (below); any other failure is reported by severity and start() goes on
|
package/core/styleParts.js
CHANGED
|
@@ -10,8 +10,8 @@
|
|
|
10
10
|
// Zero cost when unused: a single object (not a list) is used as it is, engine.style === that object.
|
|
11
11
|
// Looks only: a style never holds world state (water level, sea, terrain shape); checkStyleLooks throws in dev.
|
|
12
12
|
import { DEV } from './validate.js';
|
|
13
|
+
import { isPlainObject as plain, getPath } from './util.js';
|
|
13
14
|
|
|
14
|
-
const plain = v => v !== null && typeof v === 'object' && !Array.isArray(v) && [Object.prototype, null].includes(Object.getPrototypeOf(v));
|
|
15
15
|
|
|
16
16
|
// A post edit is a function carrying this mark: mergeInto calls it with the list built so far instead of replacing the list
|
|
17
17
|
const EDIT = Symbol('threedog.postEdit');
|
|
@@ -83,7 +83,7 @@ const WORLD = [
|
|
|
83
83
|
];
|
|
84
84
|
function checkStyleLooks(style) {
|
|
85
85
|
for (const [path, isWorld, where] of WORLD) {
|
|
86
|
-
const obj =
|
|
86
|
+
const obj = getPath(style, path);
|
|
87
87
|
if (!obj || typeof obj !== 'object') continue;
|
|
88
88
|
for (const k of Object.keys(obj))
|
|
89
89
|
if (isWorld(k)) throw new Error(`style.${path}.${k} is world state, not a look: swapping the style would change the map or the rules. Set it where the world is made: ${where}`);
|
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
// engine.thing(id).explain(): everything known about one id in one plain object (JSON-able, same for the CLI `threedog thing <id>`, MCP and tests).
|
|
2
|
+
// Why one object: an AI asked "why is this crate here, blocking me, and how do I change it?" otherwise joins thing(), world.origin, material info, the
|
|
3
|
+
// template, collision settings and the op list by hand. Each part reads an existing source; nothing here is stored or changes any state.
|
|
4
|
+
import { materialInfo } from './MaterialInfo.js';
|
|
5
|
+
|
|
6
|
+
const MAT_MAX = 8;
|
|
7
|
+
const safe = f => { try { return f(); } catch { return null; } };
|
|
8
|
+
|
|
9
|
+
/** Unique materials under obj with role / name / where the spec came from */
|
|
10
|
+
function materialsOf(obj) {
|
|
11
|
+
const seen = new Set(), out = [];
|
|
12
|
+
obj?.traverse?.(o => {
|
|
13
|
+
for (const m of [o.material].flat()) {
|
|
14
|
+
if (!m || seen.has(m)) continue;
|
|
15
|
+
seen.add(m);
|
|
16
|
+
if (out.length < MAT_MAX) { const i = materialInfo(m, o); out.push({ role: i.role, name: m.name || null, from: i.from, keys: i.keys, type: i.type, color: i.color, mesh: o.name || null }); }
|
|
17
|
+
}
|
|
18
|
+
});
|
|
19
|
+
if (seen.size > MAT_MAX) out.push({ more: seen.size - MAT_MAX });
|
|
20
|
+
return out;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/** Ops whose definition says (targets) they are for this id, kind or template; thing.set / thing.remove target '*' */
|
|
24
|
+
function opsFor(e, t) {
|
|
25
|
+
const keys = new Set([t.id, t.kind, t.template].filter(Boolean));
|
|
26
|
+
return [...e.ops.defs.values()].filter(d => d.targets != null && [d.targets].flat().some(x => x === '*' || keys.has(x)))
|
|
27
|
+
.map(d => ({ op: d.name, desc: d.desc ?? null, args: d.args ?? null }));
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/** What core knows about how the thing takes part in movement / picking: the size of its model. Template and record rules come from a module's explainer (below) */
|
|
31
|
+
function rulesOf(e, t, obj) {
|
|
32
|
+
const out = {};
|
|
33
|
+
if (obj) {
|
|
34
|
+
const T = e.THREE, size = new T.Box3().setFromObject(obj).getSize(new T.Vector3());
|
|
35
|
+
if (isFinite(size.y)) out.height = Math.round(size.y * 100) / 100;
|
|
36
|
+
}
|
|
37
|
+
return out;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/**
|
|
41
|
+
* @param {any} e @param {any} t the thing (engine.thing result) @internal
|
|
42
|
+
*/
|
|
43
|
+
export function explainThing(e, t) {
|
|
44
|
+
const obj = t.object, T = e._things;
|
|
45
|
+
const over = e.debug.overridesOn(obj);
|
|
46
|
+
const state = obj ? { position: obj.position.toArray().map(v => Math.round(v * 100) / 100), visible: obj.visible, scale: obj.scale.toArray() } : {};
|
|
47
|
+
const saved = { tier: t.saved, keeps: t.keeps, loses: t.loses, ...(t.saved === 'code' && { overridden: T.over.has(t.id), removed: T.removed.has(t.id) }) };
|
|
48
|
+
const out = {
|
|
49
|
+
id: t.id, kind: t.kind, owner: t.owner,
|
|
50
|
+
definition: { at: t.definedAt ?? t.at ?? null, template: t.template ?? null, templateAt: t.templateAt ?? null, ...(t.level && { level: t.level, node: t.node }), ...(t.spawned && { spawned: t.spawned }) },
|
|
51
|
+
model: t.model ?? null,
|
|
52
|
+
materials: materialsOf(obj),
|
|
53
|
+
state,
|
|
54
|
+
rules: rulesOf(e, t, obj),
|
|
55
|
+
ops: opsFor(e, t),
|
|
56
|
+
saved,
|
|
57
|
+
change: {
|
|
58
|
+
runtime: `game state changes through ops: engine.ops.run('<op>', { id: '${t.id}' }); thing.set / thing.remove move, show or remove it (undoable)`,
|
|
59
|
+
permanent: t.edit ?? 'no source known: edit the code or content line that creates it, then reload',
|
|
60
|
+
diagnostic: `engine.debug.override(owner, '${t.id}', { visible, material: 'flat' | 'wire' }) changes the screen only (never saved); engine.debug.clear(owner) removes it`,
|
|
61
|
+
},
|
|
62
|
+
...(over.length && { overrides: over, warning: 'diagnostic overrides are active on this thing: what is drawn is not its real state' }),
|
|
63
|
+
};
|
|
64
|
+
// Explain contributions (arch #6): a module that owns records or templates adds to the object with e._things.explainers.push((e, t, out) => { ... }),
|
|
65
|
+
// so core never reads their shapes. A throwing explainer is skipped: explain is a diagnostic and must not fail because of one part.
|
|
66
|
+
for (const f of T.explainers) safe(() => f(e, t, out));
|
|
67
|
+
return out;
|
|
68
|
+
}
|
package/core/thingOps.js
CHANGED
|
@@ -6,6 +6,7 @@
|
|
|
6
6
|
import { Things, snap, write } from './things.js';
|
|
7
7
|
import { closest } from './validate.js';
|
|
8
8
|
import { codedError } from './errorHints.js';
|
|
9
|
+
import { explainThing } from './thingExplain.js';
|
|
9
10
|
|
|
10
11
|
const SAY = {
|
|
11
12
|
record: { keeps: ['record fields and position (world save part)'], loses: ['the built model itself: it is rebuilt from its template / present after a load'] },
|
|
@@ -25,40 +26,43 @@ function editText(en, tier, rec) {
|
|
|
25
26
|
return `made during play${en.op ? ` by op ${en.op}` : ''}${at}: to keep it, make it a template and create it inside the op with engine.spawn(name, at)`;
|
|
26
27
|
}
|
|
27
28
|
|
|
29
|
+
/** thing.explain(): the whole story of the id in one object (thingExplain.js); a method, not a field, so the thing stays small */
|
|
30
|
+
const withExplain = (e, t) => Object.defineProperty(t, 'explain', { value: () => explainThing(e, t), enumerable: false });
|
|
31
|
+
|
|
28
32
|
/** A registered plain object as a thing (same shape as hit.thing); `object` is a non-enumerable getter so the result stays JSON-able */
|
|
29
33
|
function nativeThing(e, en, root) {
|
|
30
34
|
const tier = e._things.tier(en), say = SAY[tier];
|
|
31
35
|
const out = { id: en.id, kind: root.type, owner: en.owner, at: en.at, phase: en.phase, ...(en.op && { op: en.op, tick: en.tick }), saved: tier,
|
|
32
36
|
keeps: say.keeps, loses: say.loses, edit: editText(en, tier), removed: e._things.gone.has(en.id),
|
|
33
37
|
template: null, definedAt: null, model: null, fields: {} };
|
|
34
|
-
return Object.defineProperty(out, 'object', { get: () => root, enumerable: false });
|
|
38
|
+
return withExplain(e, Object.defineProperty(out, 'object', { get: () => root, enumerable: false }));
|
|
35
39
|
}
|
|
36
40
|
|
|
37
41
|
/**
|
|
38
|
-
* The thing for a
|
|
42
|
+
* The thing for a record id (from a source, see Things.addSource), a registered id / name, or any Object3D (its
|
|
39
43
|
* registered ancestor). null when nothing matches.
|
|
40
44
|
* @internal
|
|
41
45
|
*/
|
|
42
|
-
export function findThing(e, q
|
|
46
|
+
export function findThing(e, q) {
|
|
43
47
|
const T = e._things;
|
|
44
48
|
if (typeof q === 'string') {
|
|
45
|
-
if (
|
|
49
|
+
if (T.source(q)) return recordAsThing(e, q);
|
|
46
50
|
const o = T.live(q) ?? e.scene.getObjectByName(q);
|
|
47
51
|
return native(e, o && T.entryOf(o));
|
|
48
52
|
}
|
|
49
53
|
if (!q?.isObject3D) return null;
|
|
50
|
-
const id =
|
|
51
|
-
return id ? recordAsThing(e, id
|
|
54
|
+
const id = T.idOf(q);
|
|
55
|
+
return id ? recordAsThing(e, id) : native(e, T.entryOf(q));
|
|
52
56
|
}
|
|
53
57
|
/** A world-owned entry that world no longer answers for is a torn-down model (template models are only detached): not a thing */
|
|
54
58
|
const native = (e, hit) => hit && hit[0].owner !== 'world' ? nativeThing(e, hit[0], hit[1]) : null;
|
|
55
|
-
function recordAsThing(e, id
|
|
56
|
-
const
|
|
59
|
+
function recordAsThing(e, id) {
|
|
60
|
+
const src = e._things.source(id), r = src.explain(id);
|
|
57
61
|
const out = { ...r, owner: 'world', at: r.definedAt ?? null, phase: r.spawned ? 'play' : 'setup', saved: 'record', ...SAY.record, edit: editText(null, 'record', r.edit) };
|
|
58
|
-
return Object.defineProperty(out, 'object', { get: () =>
|
|
62
|
+
return withExplain(e, Object.defineProperty(out, 'object', { get: () => src.view(id), enumerable: false }));
|
|
59
63
|
}
|
|
60
64
|
/** Every id engine.thing knows (for "did you mean") */
|
|
61
|
-
function thingIds(e) { return [...
|
|
65
|
+
function thingIds(e) { return [...e._things.recordIds(), ...e._things.byId.keys()]; }
|
|
62
66
|
export const hintThing = (e, id) => { const c = closest(String(id), thingIds(e)); return c ? ` (did you mean '${c}'?)` : ''; };
|
|
63
67
|
|
|
64
68
|
/** Normalise thing.set args into a patch of arrays (rotation as a number = yaw; scale as a number = uniform) */
|
|
@@ -77,26 +81,32 @@ const uni = s => typeof s === 'number' ? s : s[0];
|
|
|
77
81
|
/** Register the registry, engine.thing's ops, the 'scene' save part and the session:start setup window (called once by the Engine constructor) */
|
|
78
82
|
export function installThings(e) {
|
|
79
83
|
const T = e._things = new Things(e);
|
|
84
|
+
T.explainers = []; // explain contributions from modules (see thingExplain.js)
|
|
85
|
+
/**
|
|
86
|
+
* Add a contribution to engine.thing(id).explain(): fn(engine, thing, out) may fill out.state / out.rules (or add keys) for the things its module owns.
|
|
87
|
+
* For module authors: core never reads another module's record or template shape, the module hands it over here. A throwing fn is skipped.
|
|
88
|
+
* @param {(e: any, t: any, out: any) => void} fn
|
|
89
|
+
* @example engine.explainWith((e, t, out) => { const r = e.myRecords.get(t.id); if (r) out.state = { ...r }; });
|
|
90
|
+
*/
|
|
91
|
+
e.explainWith = fn => { T.explainers.push(fn); };
|
|
80
92
|
// content() replaces this; without it a bare "spawn is not a function" would not say which module to install
|
|
81
93
|
e.spawn = () => { throw new Error("engine.spawn needs the content module: add content() to engine.use(...) (import { content } from 'threedog')"); };
|
|
82
|
-
e.saves.register('scene', { save: () => T.save(), load: d => T.load(d) });
|
|
83
|
-
const kindOf = id =>
|
|
94
|
+
e.saves.register('scene', { atomic: true, save: () => T.save(), load: d => T.load(d) });
|
|
95
|
+
const kindOf = id => T.source(id) ? 'record' : T.live(id) ? T.tier(T.byObj.get(T.live(id))) : null;
|
|
84
96
|
const reasons = {
|
|
85
97
|
noThing: 'no world record or engine.add object has this id (engine.thing(id) suggests the closest one)',
|
|
86
98
|
engineOwned: 'an engine module manages this object (water, particles, physics…); change it through that module',
|
|
87
99
|
recordVisible: 'a world record has no visible flag: hide its model with present({ show: rec => … }) and a field set by world.set',
|
|
88
100
|
};
|
|
89
101
|
e.ops.define('thing.set', {
|
|
102
|
+
targets: '*',
|
|
90
103
|
desc: 'Move / turn / scale / show or hide a thing: a world record (via world.set / move) or an engine.add object (saved as an override when it has an id)',
|
|
91
104
|
args: { id: 'string', position: 'any?', rotation: 'any?', scale: 'any?', visible: 'bool?' },
|
|
92
105
|
can: (_, a) => { const k = kindOf(a.id); return !k ? 'noThing' : k === 'engine' ? 'engineOwned' : k === 'record' && a.visible != null ? 'recordVisible' : true; },
|
|
93
106
|
run(eng, a) {
|
|
94
107
|
if (kindOf(a.id) === 'record') {
|
|
95
|
-
// rot / scale are the template instance fields (templates.js); a record without them reads as rot 0, scale 1
|
|
96
|
-
const rec = eng.world.get(a.id), before = { position: { ...rec.position }, ...(a.rotation != null && { rot: rec.rot ?? 0 }), ...(a.scale != null && { scale: rec.scale ?? 1 }) };
|
|
97
108
|
const patch = { ...(a.position && { position: xyz(a.position) }), ...(a.rotation != null && { rot: yaw(a.rotation) }), ...(a.scale != null && { scale: uni(a.scale) }) };
|
|
98
|
-
|
|
99
|
-
return { record: true, before };
|
|
109
|
+
return { record: true, before: T.source(a.id).set(a.id, patch) };
|
|
100
110
|
}
|
|
101
111
|
const obj = T.live(a.id), p = patchOf(obj, a);
|
|
102
112
|
if (T.tier(T.byObj.get(obj)) === 'code') return T.override(a.id, obj, p);
|
|
@@ -105,7 +115,7 @@ export function installThings(e) {
|
|
|
105
115
|
return before;
|
|
106
116
|
},
|
|
107
117
|
undo(eng, a, v) {
|
|
108
|
-
if (v.record) {
|
|
118
|
+
if (v.record) { T.source(a.id).set(a.id, v.before); return; }
|
|
109
119
|
const obj = T.live(a.id); if (!obj) return;
|
|
110
120
|
write(obj, v.patch);
|
|
111
121
|
if (v.session) return;
|
|
@@ -114,21 +124,21 @@ export function installThings(e) {
|
|
|
114
124
|
reasons,
|
|
115
125
|
});
|
|
116
126
|
e.ops.define('thing.remove', {
|
|
127
|
+
targets: '*',
|
|
117
128
|
desc: 'Remove a thing (undoable): a world record via world.remove, or an engine.add object (detached and kept; saved when it has an id)',
|
|
118
129
|
args: { id: 'string' },
|
|
119
130
|
can: (_, a) => { const k = kindOf(a.id); return !k || T.gone.has(a.id) ? 'noThing' : k === 'engine' ? 'engineOwned' : true; },
|
|
120
131
|
run(eng, a) {
|
|
121
132
|
if (kindOf(a.id) === 'record') {
|
|
122
|
-
const
|
|
123
|
-
|
|
124
|
-
return { record: rec, authored };
|
|
133
|
+
const src = T.source(a.id);
|
|
134
|
+
return { record: src.remove(a.id), src };
|
|
125
135
|
}
|
|
126
136
|
T.hide(a.id, T.live(a.id), T.tier(T.byObj.get(T.live(a.id))) === 'code');
|
|
127
137
|
return {};
|
|
128
138
|
},
|
|
129
139
|
undo(eng, a, v) {
|
|
130
140
|
if (!v.record) { T.unhide(a.id); return; }
|
|
131
|
-
|
|
141
|
+
v.src.restore(v.record);
|
|
132
142
|
},
|
|
133
143
|
reasons,
|
|
134
144
|
});
|
|
@@ -142,15 +152,16 @@ export function describeScene(e) {
|
|
|
142
152
|
const en = T.byObj.get(o), tier = T.tier(en);
|
|
143
153
|
if (en.owner === 'game') { n.game++; n[tier]++; } else if (tier === 'record') { if (o.parent) n.world++; } else n.engine++;
|
|
144
154
|
}
|
|
145
|
-
const
|
|
155
|
+
const ov = e.debug.overrides();
|
|
156
|
+
const out = { ...n, ...(ov.length && { overrides: ov, overridesNote: 'diagnostic: the screen differs from the real state until engine.debug.clear(owner)' }), unsaved: T.lost().map(en => `${en.id} (${en.at ? en.at + ', ' : ''}${en.phase === 'play' ? 'made during play' : 'no stable id'}${en.op ? ` by op ${en.op}` : ''})`),
|
|
146
157
|
conflicts: [...T.conflicts], orphans: T.orphans() };
|
|
147
158
|
if (T.atCapped) out.atCapped = true; // dev stacks stopped: later objects have at: null
|
|
148
159
|
return out;
|
|
149
160
|
}
|
|
150
161
|
|
|
151
162
|
/** engine.thing(idOrObj): throws with the closest id when nothing matches @internal */
|
|
152
|
-
export function thing(e, q
|
|
153
|
-
const t = findThing(e, q
|
|
163
|
+
export function thing(e, q) {
|
|
164
|
+
const t = findThing(e, q);
|
|
154
165
|
if (t) return t;
|
|
155
166
|
const what = typeof q === 'string' ? `'${q}'` : q?.isObject3D ? `an unregistered ${q.type}` : JSON.stringify(q);
|
|
156
167
|
throw codedError('thing-id', `engine.thing(${what}): nothing has this id or name${typeof q === 'string' ? hintThing(e, q) : ''}. Pass a world record id, the id given to engine.add(obj, { id }), an object name or any Object3D added with engine.add (engine.scene.add does not register)`);
|
package/core/things.js
CHANGED
|
@@ -47,7 +47,7 @@ const pick = (o, keys) => Object.fromEntries(keys.filter(k => k in o).map(k => [
|
|
|
47
47
|
export function claimId(e, id, obj = null) {
|
|
48
48
|
const T = e._things, who = obj ? `engine.add(obj, { id: '${id}' })` : `world.add({ id: '${id}' })`;
|
|
49
49
|
if (obj && (typeof id !== 'string' || !id || id.includes('#'))) throw codedError('thing-id', `engine.add(obj, { id: ${JSON.stringify(id)} }): an id is a non-empty string without '#' ('#' marks runtime ids such as obj#3), e.g. { id: 'windmill' }`);
|
|
50
|
-
if (obj &&
|
|
50
|
+
if (obj && T.source(id)) throw codedError('thing-id', `${who}: '${id}' is a world record id (engine.thing('${id}') shows it). Ids are shared with world records: pick another`);
|
|
51
51
|
const other = T.live(id);
|
|
52
52
|
if (other && other !== obj && T.byObj.get(other).owner !== 'world') {
|
|
53
53
|
const at = T.byObj.get(other).at;
|
|
@@ -59,6 +59,7 @@ export function claimId(e, id, obj = null) {
|
|
|
59
59
|
export class Things {
|
|
60
60
|
constructor(e) {
|
|
61
61
|
this.e = e;
|
|
62
|
+
this.sources = []; // record stores (world) registered with addSource; core knows only their shape
|
|
62
63
|
this.byObj = new WeakMap();
|
|
63
64
|
this.byId = new Map(); // id -> WeakRef(root)
|
|
64
65
|
this.n = 0; // session ids obj#n
|
|
@@ -72,6 +73,19 @@ export class Things {
|
|
|
72
73
|
this.conflicts = []; // dev: "two systems manage one object" findings, newest last
|
|
73
74
|
e.events.on('session:start', () => { this.setup = true; queueMicrotask(() => { this.setup = false; }); });
|
|
74
75
|
}
|
|
76
|
+
/**
|
|
77
|
+
* A store of records that share the id space with engine.add objects (the world module registers itself at install). The shape core uses:
|
|
78
|
+
* { has(id), get(id) -> { position, ... }, ids(), idOf(obj) -> id | null (model -> record), view(id) -> Object3D | null,
|
|
79
|
+
* explain(id) -> the record as a thing, set(id, patch) -> undo values, remove(id) -> restore token, restore(token) }
|
|
80
|
+
* @param {any} src @returns {{ remove(): void }}
|
|
81
|
+
*/
|
|
82
|
+
addSource(src) { this.sources.push(src); return { remove: () => { this.sources = this.sources.filter(s => s !== src); } }; }
|
|
83
|
+
/** The source that has a record under id, else null */
|
|
84
|
+
source(id) { return this.sources.find(s => s.has(id)) ?? null; }
|
|
85
|
+
/** The record id whose model is obj, else null */
|
|
86
|
+
idOf(obj) { for (const s of this.sources) { const id = s.idOf?.(obj); if (id) return id; } return null; }
|
|
87
|
+
/** Every record id (for "did you mean") */
|
|
88
|
+
recordIds() { return this.sources.flatMap(s => s.ids?.() ?? []); }
|
|
75
89
|
/** Whether a dev stack should be taken for this add (cap reached = no) */
|
|
76
90
|
wantStack() { return this.stacks < STACK_CAP && ++this.stacks > 0; }
|
|
77
91
|
get atCapped() { return this.stacks >= STACK_CAP; }
|
package/core/util.js
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
// Small helpers several core files need. One definition each, so "what counts as a plain object" and "how a dotted path is read" cannot drift apart.
|
|
2
|
+
|
|
3
|
+
/** A plain data object: { } or Object.create(null); not an array, class instance, three.js object or function */
|
|
4
|
+
export const isPlainObject = v => v !== null && typeof v === 'object' && !Array.isArray(v) && [Object.prototype, null].includes(Object.getPrototypeOf(v));
|
|
5
|
+
|
|
6
|
+
/** Read a dotted path ('look.fog.color'); undefined as soon as a step is missing @param {any} obj @param {string} path */
|
|
7
|
+
export function getPath(obj, path) {
|
|
8
|
+
let v = obj;
|
|
9
|
+
for (const k of path.split('.')) v = v?.[k];
|
|
10
|
+
return v;
|
|
11
|
+
}
|