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/docs/api/events.md
CHANGED
|
@@ -1,11 +1,15 @@
|
|
|
1
1
|
# engine.events (Events) — engine.events: the event bus; modules "shout" and whoever cares listens
|
|
2
2
|
|
|
3
|
+
- `events.traceFocus(id: string | null)` — Verbose trace for one object (needs traceSize > 0): perception queries and state checks that name `obj` === id are recorded in full (misses too), the rest of the world only records what changed. null clears. For "why did this guard not see me": traceFocus('guard-1'), play, then read trace('sight'). Example: `engine.events.traceSize = 300; engine.events.traceFocus('guard-1');`
|
|
4
|
+
- `events.note(name: string, info?: { code?, obj?, data?, verbose?, parent? }) → string | null` — Add one entry to the cause trace (no-op while traceSize is 0; check `events.traceSize > 0` first to skip building info). Returns its parent id (`ev:<n>`) to pass as info.parent of follow-ups, or null. info: code (failure code), obj (world record id it is about), data (small plain values), verbose (true = only recorded while traceFocus(obj)), parent (default: the event or op running now). The engine notes failed ops (`op:<name>`), collision.lineClear (`sight`) and NPC state changes (`npc:state`); a game's behaviors can note their own, e.g. 'npc:mode' patrol -> investigate. Example: `if (e.events.traceSize > 0) e.events.note('npc:mode', { obj: rec.id, data: { from: 'patrol', to: 'investigate' } });`
|
|
5
|
+
- `events.trace(name?: string) → { id, tick, name, parent, chain, code?, … }[]` — Cause chains (needs traceSize > 0): each emitted event is recorded with parent = the event (`ev:<id>`) or op (`op:<name>#<seq>`) whose handler emitted it, null when it came from outside any. chain lists the causes from the nearest to the root (as far as the ring still holds). For "why did this fire". Example: `engine.events.traceSize = 200; engine.ops.run('shop.buy', { item: 'bread' }); engine.events.trace('item:add').at(-1).chain; // ['op:shop.buy#12']`
|
|
3
6
|
- `events.recent(name?: string) → { tick, name, data }[]` — Recent events (old -> new); with name, only that kind: { tick = which fixed step, name, data = summary (simple values only; objects become '…') }. For "why did it not fire", first check whether it happened at all. Example: `engine.events.recent('item:add');`
|
|
4
7
|
- `events.on(name: K, fn: (args) => void) → Handle` — Listen to an event; returns a handle { remove() }. Example: `const h = engine.events.on('item:add', ({ id, count }) => console.log(id, count)); h.remove();`
|
|
5
8
|
- `events.once(name: K, fn: (args) => void) → Handle` — Listen once; returns a handle { remove() } (can be removed before it fires)
|
|
6
9
|
- `events.emit(name: K, ...args: EventArgs<K & string>)` — Emit an event. Example: `engine.events.emit('item:add', { id: 'fish', count: 1 });`
|
|
7
10
|
- Properties:
|
|
8
11
|
- `historySize: number` How many history entries to keep, default 200; 0 records nothing
|
|
12
|
+
- `traceSize: number` Cause trace ring size, default 0 = off (no cost). Set e.g. 200 in dev to record which event or op caused which follow-up event; read with trace()
|
|
9
13
|
|
|
10
14
|
## Event table (engine.events.on(name, (args…) => …), the [] lists the callback arguments)
|
|
11
15
|
- `engine:ready` [] Loading finished; the world is playable
|
|
@@ -74,7 +78,7 @@
|
|
|
74
78
|
- `net:open` [{}] Client (net): connected to the host (the first snapshot follows)
|
|
75
79
|
- `net:close` [{}] Client (net): connection lost
|
|
76
80
|
- `net:sync` [{ tick: number; full: boolean }] Client (net): host state applied (full: a whole snapshot, else a diff); redraw UI from state here
|
|
77
|
-
- `net:result` [{ seq: number; name: string; ok: boolean;
|
|
81
|
+
- `net:result` [{ seq: number; name: string; ok: boolean; code: string | null; value… Client (net): the host's answer to an op request (seq from ops.run's return value; tick is the host's), sent after the state it caused
|
|
78
82
|
- `engine:error` [EngineError] A gameplay error in development / testing; gameplay is frozen (error severity levels, see engine.error)
|
|
79
83
|
- `module:disabled` [{ name: string; message: string }] A presentation module errored and was disabled (the game continues)
|
|
80
84
|
- `vehicle:enter` [{ character: Character; vehicle: Vehicle }] A character boarded a vehicle
|
package/docs/api/post.md
CHANGED
|
@@ -1,9 +1,10 @@
|
|
|
1
1
|
# engine.post (PostFX)
|
|
2
2
|
|
|
3
|
-
- `post.add(
|
|
4
|
-
- `post.get(name: string) → PostHandle | undefined` — (experimental)
|
|
5
|
-
- `post.enable(
|
|
3
|
+
- `post.add(_effect: PostEffect, _opts?: { slot?, order?, enabled? }) → never` — (experimental) Renamed in 0.2: throws and names the new call (engine.look.post.patch / engine.look.post.replace, recipes/52-look.md)
|
|
4
|
+
- `post.get(name: string) → PostHandle | undefined` — (experimental) Read-only record of an added effect (name, slot, order, enabled, params), or undefined. Change one with engine.look.post.set({ 'bloom.strength': 0.6 })
|
|
5
|
+
- `post.enable(_name: string, _on: boolean) → never` — (experimental) Renamed in 0.2: throws and names the new call (engine.look.post.set({ 'bloom.enabled': on }); MSAA: engine.post.setAntialias(on))
|
|
6
|
+
- `post.setAntialias(on: boolean)` — (experimental) Turn MSAA (antialiasing of the post chain) on or off. It is a render target setting, not a look part. Example: `engine.post.setAntialias(false);`
|
|
6
7
|
- `post.list() → { name, slot, order, enabled }[]` — (experimental) Effects in render order: [{ name, slot, order, enabled }]
|
|
7
8
|
- Properties:
|
|
8
|
-
- `antialias: boolean` MSAA on (read-only; switch with post.
|
|
9
|
+
- `antialias: boolean` MSAA on (read-only; switch with post.setAntialias(on))
|
|
9
10
|
- `active: boolean` Whether any post work runs (antialias or an enabled effect)
|
package/docs/api/saves.md
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
# engine.saves (Saves) — engine.saves handles saving
|
|
2
2
|
|
|
3
|
-
- `saves.register(key: string, provider: SaveProvider)` — Register "how to save and load"; key is this part's name in the save. Parts with first: true load first (the level); a load returning a Promise makes later parts wait. version (default 1): raise it by 1 whenever what save() returns changes shape, and add migrate[oldVersion] = data => newData; load sees only the current shape. A save whose part is newer than this build's version is refused as a whole (load returns false, the save is kept). A part registered after a save was loaded (a module installed later) is handed its data from that save at once. Example: `engine.saves.register('garden', { save: () => garden.toJSON(), load: d => garden.fromJSON(d) }); // later the format gains beds: version 2, and a step that upgrades version-1 data engine.saves.register('garden', { version: 2, migrate: { 1: d => ({ ...d, beds: [] }) }, save: () => garden.toJSON(), load: d => garden.fromJSON(d) });`
|
|
3
|
+
- `saves.register(key: string, provider: SaveProvider)` — Register "how to save and load"; key is this part's name in the save. Parts with first: true load first (the level); a load returning a Promise makes later parts wait. version (default 1): raise it by 1 whenever what save() returns changes shape, and add migrate[oldVersion] = data => newData; load sees only the current shape. A save whose part is newer than this build's version is refused as a whole (load returns false, the save is kept). A part registered after a save was loaded (a module installed later) is handed its data from that save at once. atomic: true joins this part to atomic ops: it is copied before an atomic op runs and put back if the op fails (plain data only; afterLoad does not run on rollback). Example: `engine.saves.register('garden', { save: () => garden.toJSON(), load: d => garden.fromJSON(d) }); // later the format gains beds: version 2, and a step that upgrades version-1 data engine.saves.register('garden', { version: 2, migrate: { 1: d => ({ ...d, beds: [] }) }, save: () => garden.toJSON(), load: d => garden.fromJSON(d) });`
|
|
4
4
|
- `saves.queue(fn: () => Promise<T>) → Promise<T>` — Queue a disk write (runs in call order once storage is ready; flush waits for it; used by attachments such as photos).
|
|
5
5
|
- `saves.flush() → Promise<void>` — Wait for all queued disk writes to finish (for tests and before the page closes)
|
|
6
6
|
- `saves.collect() → { format, savedAt, versions, parts }` — Collect the data of every part (does not write to the browser): { format, savedAt, versions, parts }. A part whose save() throws is left out and reported (engine.error in dev); save() instead refuses to write such a save.
|
|
@@ -27,5 +27,6 @@
|
|
|
27
27
|
- `save: () => any`
|
|
28
28
|
- `load: (data: any) => void | Promise<void>`
|
|
29
29
|
- `first?: boolean` Load before the other parts (such as the level)
|
|
30
|
+
- `atomic?: boolean` Join atomic ops: copied before an atomic op runs, put back if it fails (plain data; afterLoad does not run on rollback)
|
|
30
31
|
- `version?: number` This part's format version, default 1: raise it by 1 when what save() returns changes shape. A save with a newer version is refused
|
|
31
32
|
- `migrate?: Record<number, (data: any, save: { parts: Record<string, an…` Upgrade steps: old version -> data => data in the next version's shape, e.g. { 1: d => ({ ...d, beds: [] }) }. The second argument is the whole save as read ({ parts, versions }, read only), for a step that depends on another part
|
package/docs/api/sky.md
CHANGED
|
@@ -19,9 +19,9 @@ Sky, day/night, calendar (sky() module)
|
|
|
19
19
|
- `sky.between(from: string | number, to: string | number, opts: SkyBetweenOptions) → Handle` — Time-range switch: on() while clock time is in [from, to), otherwise off() (from > to wraps midnight). Aligns once immediately on registration, new game, load, applying a scenario and time rewind; afterwards it calls on/off when crossing a boundary. Example: `engine.sky.between('18:00', '06:00', { on: () => lamp.on(), off: () => lamp.off() })`
|
|
20
20
|
- `sky.daily(fn: (day: number) => void, opts?: SkyAtOptions) → Handle` — Call fn(day) at the start of each day (00:00)
|
|
21
21
|
- `sky.onSeason(name: string, fn: (season: string) => void) → Handle` — Call fn(seasonName) on entering season name
|
|
22
|
-
- `sky.setShadow(
|
|
22
|
+
- `sky.setShadow(_opts?: Partial<SkyShadowParams>) → never` — Renamed in 0.2: throws and names the new call, engine.look.shadow.set(opts) (fields: bias, normalBias, updateEvery, snap, ahead, type, radius, blurSamples, cascades; recipes/45)
|
|
23
23
|
- `sky.setShadowMapSize(n: number)` — Change shadow resolution (raise temporarily for photo mode)
|
|
24
|
-
- `sky.setEnvironment(
|
|
24
|
+
- `sky.setEnvironment(_opts?: { source?, intensity?, rotation?, interval? } | null) → never` — Renamed in 0.2: throws and names the new call, engine.look.env.replace(source) then engine.look.env.set({ intensity, rotation, interval })
|
|
25
25
|
- Properties:
|
|
26
26
|
- `timeOfDay: number` Sky time of day: 0-1 (0 midnight, 0.25 6am, 0.5 noon, 0.75 6pm); one day = dayLength game seconds (the unit of engine.clock.now). Fixed-step seconds (unaffected by timeScale) are engine.elapsed
|
|
27
27
|
- `dayLength: number` Game seconds per day (1 sky hour = dayLength / 24 game seconds; at timeScale 1 game seconds equal fixed-step seconds); Infinity = the time of day never moves
|
|
@@ -33,7 +33,7 @@ Sky, day/night, calendar (sky() module)
|
|
|
33
33
|
- `sun: any` Sun directional light (engine.lights.sun driven by the sky; moonlight at night, shadows live on it)
|
|
34
34
|
- `sunDir: THREE.Vector3` Sun direction (unit vector toward the sun)
|
|
35
35
|
- `orbit: { tilt: number; sway: number; distance: number }` Sun orbit: tilt = north-south tilt, sway = east-west swing, distance = light distance (meters)
|
|
36
|
-
- `shadow: SkyShadowParams` Current shadow params (change via
|
|
36
|
+
- `shadow: SkyShadowParams` Current shadow params (change via look.shadow.set)
|
|
37
37
|
- `csm: any` three's CSM (addons/csm) while shadow.cascades > 1, else null; its lights[0] is sun (recipes/45)
|
|
38
38
|
- `hoursPerDay: number` Hours per day
|
|
39
39
|
- `modifiers: SkyModifiers` Composite of all modifier layers (read-only; use modify to adjust brightness)
|
package/docs/api/style.md
CHANGED
|
@@ -2,8 +2,8 @@
|
|
|
2
2
|
|
|
3
3
|
- **Style** fields (all optional):
|
|
4
4
|
- `name?: string` Style pack name
|
|
5
|
-
- `exposure?: number | number[][] | ((sky: any) => number)` Exposure, default 1 (lowpoly: 1.05): a number, or over the day [[time 0-1, exposure], ...] (sorted, wraps across midnight) or (sky) => number, evaluated by the sky module every frame. engine.
|
|
6
|
-
- `toneMapping?: Loose<'aces' | 'agx' | 'neutral' | 'none'>` Tone mapping
|
|
5
|
+
- `exposure?: number | number[][] | ((sky: any) => number)` Exposure, default 1 (lowpoly: 1.05): a number, or over the day [[time 0-1, exposure], ...] (sorted, wraps across midnight) or (sky) => number, evaluated by the sky module every frame. engine.look.tone.set changes it at run time. Example: `exposure: [[0, 1.6], [0.3, 1], [0.75, 1.1]] // brighter nights`
|
|
6
|
+
- `toneMapping?: Loose<'aces' | 'agx' | 'neutral' | 'none'>` Tone mapping. Engine default 'none' (no style pack, no tone mapping); the style pack picks the look (lowpoly: 'aces')
|
|
7
7
|
- `background?: ColorLike` Background color (when there is no sky module)
|
|
8
8
|
- `post?: (Omit<import('./generate… & { slot? })[]` Post effects registered at startup, in any order (slot and order decide where each runs), e.g. [outline({ enabled: true }), bloom()] from '@threedog/post-effects'
|
|
9
9
|
- `materials?: Record<string, MaterialSpec | import('three').Material | ((…` Material per role (default, terrain, vegetation, character, water, building, pickup…): a spec, a three.js Material instance (cloned per use), or a function (params, purpose) => Material
|
|
@@ -43,7 +43,7 @@
|
|
|
43
43
|
- `clouds?: StyleSkyClouds` Clouds in the sky (cloud cover follows the weather); see StyleSkyClouds
|
|
44
44
|
- `skybox?: string` Panorama (equirectangular) replacing the gradient sky, asset name or path
|
|
45
45
|
- `shadow?: StyleShadow` Shadows: mapSize resolution (pixels), extent coverage (meters), etc., see StyleShadow
|
|
46
|
-
- `environment?: StyleEnvironment` Environment lighting (scene.environment), off unless a source is given; see
|
|
46
|
+
- `environment?: StyleEnvironment` Environment lighting (scene.environment), off unless a source is given; see engine.look.env. A pack can give defaults, sky({ environment }) overrides
|
|
47
47
|
- `fog?: StyleFog` Fog model and color (default: linear fog in the horizon color); see StyleFog
|
|
48
48
|
- `layers?: StyleSkyLayer[]` Extra dome layers drawn after the clouds and stars (rainbow, aurora), default none; see StyleSkyLayer
|
|
49
49
|
- **StyleShadow**
|
package/docs/api/tools.md
CHANGED
|
@@ -12,6 +12,8 @@
|
|
|
12
12
|
- `EASINGS: Record<EaseName, (t: number) => number>` — All easing functions: name -> function
|
|
13
13
|
- `ease(e: Ease) → (t: number) => number` — Name or function -> easing function
|
|
14
14
|
- `checkOptions(where: string, opts: object | null | undefined, known: string[], flags?: { loose?: boolean })` — Warn (once, in development) about unknown keys in an options object, with a "did you mean" hint. For your own modules. where names the call ('stamina()'); known lists the keys your code reads; loose only warns on near-misses (data with game-specific fields).
|
|
15
|
+
- `readParams(where: string, schema: Record<string, ParamSpec>, opts?: object) → T` — Module options read through a params schema: unknown keys and wrong types throw in dev with the fix, defaults are filled in. Also put params / options on the module definition so engine.catalog(name) shows them (recipes/51-capability-catalog.md).
|
|
16
|
+
- `defineLookPart(engine: any, spec: { id, group?, module?, object?, params?, style?, … }) → LookPart` — Register a module's own look part: engine.look.<id> with set / patch / replace, engine.catalog('look.<id>') and describe().look (recipes/52-look.md). Every param needs a default; a default that changes the picture also needs why and off (or neutral: true).
|
|
15
17
|
- `createTerrain(cfg?: Partial<TerrainConfig>) → TerrainGen` — Pure terrain computation (no engine needed), for previewing heights before start: createTerrain({ seed, ...terrainPreset() }).surface(x, z)
|
|
16
18
|
- `terrainMaterial(base?: THREE.Material | null, engine?: { style: any; assets: any }) → THREE.Material` — Terrain material: base (default the style's 'terrain' role with vertex colors) + cloud shadows + season tint + optional detail texture (style.terrain.detail). Pass the engine so its style pack and assets are used.
|
|
17
19
|
- `mergeColored(parts: [THREE.BufferGeometry, ColorLike][], { flat }?: { flat?: boolean }) → THREE.BufferGeometry` — Merge several geometries into one vertex-colored geometry (a tree = trunk + canopy in one draw call): [[geometry, color], ...]. flat (default true): one normal per triangle, the faceted low-poly look; false keeps each part's own (smooth) normals. UVs are kept when every part has them, so the merged model can still take a texture.
|
package/docs/api/weather.md
CHANGED
|
@@ -13,7 +13,7 @@ Weather (weather() module, needs sky)
|
|
|
13
13
|
- `area?: number` Rain / snow coverage (meters)
|
|
14
14
|
|
|
15
15
|
## Methods and properties
|
|
16
|
-
- `weather.define(
|
|
16
|
+
- `weather.define(_field: string, _spec?: import("../../../style").StyleWeath…) → never` — Renamed in 0.2: throws and names the new call, engine.look.weather.replace({ [field]: spec }) (recipes/44-water-weather-look-hooks.md)
|
|
17
17
|
- `weather.setAuto(on: boolean)` — Automatic weather on/off
|
|
18
18
|
- `weather.set(name: WeatherName, seconds?: number)` — Switch weather. seconds: transition seconds, default 15
|
|
19
19
|
- `weather.label(name?: string) → string` — Display name of a weather (string table weather.<name>, falls back to the name itself); defaults to the current weather
|
package/docs/recipes/02-npc.md
CHANGED
|
@@ -138,6 +138,22 @@ engine.npcs.avoid.set(false); // turn off (ghosts, cro
|
|
|
138
138
|
- Behaviors you write are not avoided automatically: after your own `character.move`, call `engine.npcs.avoid.push(rec, npc.character, dt)` once
|
|
139
139
|
(inside `near`, before writing back to the data).
|
|
140
140
|
|
|
141
|
+
|
|
142
|
+
## A guard you build yourself (`Character` + `walkTo`)
|
|
143
|
+
|
|
144
|
+
For a one-off (guard, pet, follower) that `schedule` / `wander` do not cover: `new Character(engine, { rig })` takes a ready body (same shape as
|
|
145
|
+
`style.character.create` returns: `{ root, body?, head?, limbs?, joints? }`) instead of the style pack's; call `character.animate(dt)` each frame.
|
|
146
|
+
`character.walkTo(target, { speed, arrive, turnRate, run })` follows `characters.findPath` on fixed steps (turns at `turnRate` rad/s, skips passed
|
|
147
|
+
points, re-plans when it makes no progress for `stuckSeconds`, up to `maxRepaths`). It returns a promise of `{ status }`: `'arrived'` | `'noPath'` |
|
|
148
|
+
`'stuck'` | `'cancelled'` (never rejects), with `remove()` to cancel.
|
|
149
|
+
|
|
150
|
+
```js
|
|
151
|
+
const guard = new Character(engine, { rig: { root: myGuardMesh } }).addTo();
|
|
152
|
+
guard.placeAt(post);
|
|
153
|
+
const walk = guard.walkTo(player.position, { arrive: 1.5 });
|
|
154
|
+
if ((await walk).status === 'noPath') guard.face(player); // walk.remove() cancels
|
|
155
|
+
```
|
|
156
|
+
|
|
141
157
|
## 3. Verify
|
|
142
158
|
- `npm run check`: content validation catches "dialogue id does not exist", "bad clock-time format", "node next points to a missing node". After
|
|
143
159
|
`npm run map` it shows up in the NPC table and dialogue graph of GAMEMAP.md.
|
|
@@ -39,7 +39,7 @@ changing level and coming back they are still picked up.
|
|
|
39
39
|
|
|
40
40
|
## 2. In code (dynamic drops, custom models)
|
|
41
41
|
```js
|
|
42
|
-
engine.inventory.define('gem', { name: '宝石', icon: '💎', color: 0x66ccff });
|
|
42
|
+
engine.inventory.define('gem', { name: '宝石', icon: '💎', color: 0x66ccff }); // shape: add mesh: (item, { color, size }, e) => Object3D | geometry, or model: 'generatorName', to set it on the item (wins over style.pickup.model; spawnPickup { mesh } wins over both)
|
|
43
43
|
const gem = engine.inventory.spawnPickup('gem', engine.player.position, { count: 1, respawnSeconds: 0 }); // returns a handle; gem.remove() deletes data and model together
|
|
44
44
|
// handle: { id: item, worldId: id in world, object: current model (null when far), remove() }; opts.id lets you write a stable id (spawning again with the same id reuses the existing one)
|
|
45
45
|
engine.inventory.add('coin', 2); // give directly; returns the entry key ('coin'), false if it doesn't fit
|
|
@@ -92,6 +92,13 @@ What catches up, and how:
|
|
|
92
92
|
- `timeScale = 0` skips as if at 1x. The jump itself is the op `time.skip { seconds }` (logged and replayable; it refuses `seconds <= 0`).
|
|
93
93
|
- A module that keeps its own time implements the hook `skip(dt, e, done)` (called once per segment; `done` on the last one).
|
|
94
94
|
|
|
95
|
+
### Order inside one frame
|
|
96
|
+
Each rendered frame runs: input poll -> the fixed steps due (`commits` applied first, then `onFixed`, module `fixed` hooks, clock timers) -> `onFrame`
|
|
97
|
+
callbacks **in the order they were registered** -> module `frame` hooks -> stream / jobs / batching -> render -> `afterRender` hooks. The animation of a model
|
|
98
|
+
from `engine.assets.animate` (and a Character's model) is itself an `onFrame` callback registered when the animator was created, so your `onFrame` runs
|
|
99
|
+
before it if you registered first (you see last frame's pose) and after it if you registered later. To read or override a pose after animation, register
|
|
100
|
+
the callback after the model is created, or use an `afterRender` hook.
|
|
101
|
+
|
|
95
102
|
## 3. Verify
|
|
96
103
|
- Without waiting real time: in a test or the console, `engine.sky.timeOfDay = parseClock('17:59'); engine.step(5)`, then look at the result (`step`
|
|
97
104
|
returns the describe).
|
|
@@ -101,4 +108,10 @@ What catches up, and how:
|
|
|
101
108
|
scale is not 1, divide by `timeScale` as well.
|
|
102
109
|
- Reproduce a scenario: `npm run shot -- / --time 17:58 --wait 10 --describe-only`, then look at the time (18:0x) and your effect (lamps, NPCs, items).
|
|
103
110
|
- After `npm run map`, the "timed events" section of GAMEMAP.md lists every `sky.at/between/daily/onSeason` and `clock.after/every`.
|
|
111
|
+
- Is skip the same as living through it? `const r = await engine.checkSkip(600)` skips 600 game seconds, rewinds, steps the same span and compares the
|
|
112
|
+
saved state: `{ ok, diffs: [{ path, a, b }] }` (refuses with `reason: 'frozen'` / `'timeScale0'` while gameplay is frozen or the clock stopped; pending background results are applied first) (a = skip, b = step; `{ ignore: ['parts.world', 'parts.random'] }` drops paths). Skip does not run near simulation (the weather module has a skip hook, so its timers do advance), so a moving player/NPC
|
|
113
|
+
always differs: ignore those parts and read the rest. It leaves the world at the stepped state, so run
|
|
114
|
+
it on a scratch playthrough or in a test. A diff usually means a module with its own time lacks a `skip` hook. `await engine.checkSave()` does the same
|
|
115
|
+
for save -> load (a diff names a save part whose `load` does not restore what `save` wrote).
|
|
116
|
+
- Why did it fire (or not)? `engine.events.traceSize = 200` records each event with the event or op that caused it: `events.trace('item:add').at(-1).chain`. Failed ops, sight queries and NPC state changes are entries too (with `code`); `events.note(name, { obj, code, data })` adds your own and `events.traceFocus(id)` makes one object verbose (the ring is bounded; size 0 costs nothing). Details: recipe 23 section 12.
|
|
104
117
|
- Related tests: `npm test -- 游戏时钟 SKIP`.
|
|
@@ -32,6 +32,10 @@ state when the menu closes; without flow it calls `engine.freeze('settings')` di
|
|
|
32
32
|
Stopped while frozen: the fixed step (movement, physics), module `fixed`, the game clock `clock`, quest checks (they run in the fixed step), timeline
|
|
33
33
|
`wait` / tweens / camera / paths. Still running: rendering, UI, `onFrame`, the fade-to-black `fadeScreen`.
|
|
34
34
|
|
|
35
|
+
Restarting a run from a UI button (retry, "play again"): do not reset positions, health and spawns inside the click handler or an `onFrame` callback; that is
|
|
36
|
+
mid-frame and can leave half the world on the old tick. Apply it on a fixed tick: `engine.nextFixed(resetRun)`
|
|
37
|
+
(runs at the start of the next fixed step, in a stable order), or set a flag in the handler and reset in `onFixed`.
|
|
38
|
+
|
|
35
39
|
### Back key (Esc): the UI focus stack
|
|
36
40
|
Windows (inventory, quests, settings), dialogue and cutscenes are pushed onto the stack in the order they open (`uiFocus(engine)` in `ui/Focus.js`),
|
|
37
41
|
and Esc goes **only to the top one**:
|
|
@@ -52,7 +52,7 @@ sky({ seasons: [{ name: 'wet', days: 10 }, { name: 'dry', days: 20 }], dayLength
|
|
|
52
52
|
**Don't modify directly** `sky.sun.intensity / color`, `sky.hemi`, `scene.fog`: the sky recomputes them every frame and overwrites your change (the
|
|
53
53
|
console warns about it during development).
|
|
54
54
|
To darken or tint everything (a cave, a horror segment), write a modifier layer of your own; it stacks with the weather's 'weather' layer without
|
|
55
|
-
overwriting it:
|
|
55
|
+
overwriting it (multiplier layers vs `look.lights` overrides: [recipe 52](52-look.md#skymodify-vs-looklights)):
|
|
56
56
|
```js
|
|
57
57
|
engine.sky.modify('cave', { sun: 0.3, ambient: 0.4, fog: 0.5 }); // enter the cave: layers multiply
|
|
58
58
|
engine.sky.modify('cave', { tint: 0x402030, tintAmount: 0.5 }); // changes only the given fields (this layer's sun/ambient stay)
|
|
@@ -170,9 +170,9 @@ import { LUTPass } from 'three/addons/postprocessing/LUTPass.js';
|
|
|
170
170
|
const toon = { name: 'toon', post: [outline({ enabled: true, thickness: 1.5 }), bloom({ strength: 0.2 }),
|
|
171
171
|
{ name: 'lut', slot: 'ldr', params: { lut: myLut }, create: ({ params }) => new LUTPass({ lut: params.lut }) }] };
|
|
172
172
|
// at runtime (settings, photo mode, a game's own effect):
|
|
173
|
-
engine.post.
|
|
174
|
-
engine.post.
|
|
175
|
-
|
|
173
|
+
engine.look.post.set({ 'bloom.strength': 0.6 });
|
|
174
|
+
engine.look.post.set({ 'outline.enabled': false }); // MSAA: engine.post.setAntialias(false)
|
|
175
|
+
engine.look.post.patch('vignette', { glsl: 'color.rgb *= 0.9;', slot: 'ldr', order: 10 }); // patch('vignette', null) removes it
|
|
176
176
|
```
|
|
177
177
|
An effect that reads scene depth (`needsDepth: true`, e.g. `outline`) must run before any pass that swaps buffers (a `ShaderPass`, a scene-slot
|
|
178
178
|
`RenderPixelatedPass`, the tone-mapping output): only the buffer the scene render wrote holds scene depth. A chain that breaks this throws when the
|
|
@@ -191,8 +191,8 @@ until `enabled: true`.
|
|
|
191
191
|
```js
|
|
192
192
|
import { vignette, grain, lut } from '@threedog/post-effects';
|
|
193
193
|
createEngine({ canvas, style: [lowpoly, postAdd(lut({ saturation: 1.1, temperature: 0.15 }), vignette(), grain({ amount: 0.04 }))] });
|
|
194
|
-
engine.post.
|
|
195
|
-
engine.post.
|
|
194
|
+
engine.look.post.set({ 'vignette.enabled': true }); // photo mode, settings...
|
|
195
|
+
engine.look.post.set({ 'grain.amount': 0.1 }); // updates in place
|
|
196
196
|
```
|
|
197
197
|
`fuse` is how a light color effect avoids a fullscreen pass of its own: instead of `create()` it carries a GLSL snippet
|
|
198
198
|
`fuse: { uniforms: { uMyAmount: 'float' }, values: p => ({ uMyAmount: p.amount }), glsl: 'color.rgb *= 1.0 - uMyAmount * length(vUv - 0.5);' }`.
|
|
@@ -55,3 +55,25 @@ engine.characters.pathsPerStep = 64; // requests sent per fixed step (
|
|
|
55
55
|
`createEngine({ movement: { radius, height, maxSlope, stepHeight } })` sets it once; read it as `engine.movement`. Collision, the Rapier capsule, the
|
|
56
56
|
navmesh, A* and level steps all read it, so a module never writes its own 0.4 or 0.45. A character's position belongs to its mover: other systems
|
|
57
57
|
request movement (`placeAt`, `move`, vehicle `enter`) and never set `player.position`.
|
|
58
|
+
|
|
59
|
+
## Fences and rivers (collision)
|
|
60
|
+
|
|
61
|
+
Walls and water that are not meshes: `engine.collision.addSegment(a, b, { thickness })` is a thin wall along a line; `addBlocked(fn)` marks ground impassable where `fn(x, z)` is true. Both return `{ remove() }` and are free when unused.
|
|
62
|
+
|
|
63
|
+
```js
|
|
64
|
+
// A river along x 5..9 with a bridge at z -1..1: the bridge is just a hole in the blocked function
|
|
65
|
+
engine.collision.addBlocked((x, z) => x > 5 && x < 9 && !(z > -1 && z < 1), { bounds: { minX: 5, maxX: 9, minZ: -50, maxZ: 50 } });
|
|
66
|
+
// A fence with a gate: two segments, the gap between them is the gate
|
|
67
|
+
engine.collision.addSegment([-18, 0, -12], [-18, 0, -4]);
|
|
68
|
+
engine.collision.addSegment([-18, 0, 0], [-18, 0, 12], { thickness: 0.4 });
|
|
69
|
+
```
|
|
70
|
+
|
|
71
|
+
Walkers stop at the edge and slide along it; `collision.walkable()` and A* pathing, sync and async, see both. `fn` must be pure and deterministic (no clock, no random). Async paths cannot send a function to the worker, so `fn` is sampled into the 1 m ground raster instead (re-sampled when you add or remove a field): give `bounds`, or every requested tile is sampled in full. Navmesh mode (`nav()` installed) does not see `addBlocked`; use `addSegment` or bake the river into the mesh there.
|
|
72
|
+
|
|
73
|
+
## Line of sight and straight-line checks: collision.lineClear
|
|
74
|
+
`engine.collision.lineClear(a, b, { radius })` answers "is anything solid between a and b?" for a 3D segment: boxes, circles and terrain trees, with heights (a 1 m wall does not block a sight line 3 m above it; a collider's `y` / `height` count). It is a boolean; `addBlocked` water is ignored. Give eye heights in `a` / `b`; `radius` fattens the line (pass the character radius for "can I walk straight there").
|
|
75
|
+
```js
|
|
76
|
+
const sees = engine.collision.lineClear([guard.x, 1.6, guard.z], [player.x, 1.6, player.z]); // true = clear view
|
|
77
|
+
const straight = engine.collision.lineClear(me.position, goal, { radius: engine.movement.radius });
|
|
78
|
+
```
|
|
79
|
+
The A* fallback smooths paths with the same idea: it samples each shortcut at most one character radius apart (so a thin fence cannot be skipped), starts from the character's real position, and its cell size follows `radius` (1-2 m) unless you pass `step`.
|
|
@@ -133,6 +133,9 @@ engine.onFixed(() => { // one call
|
|
|
133
133
|
Use `anim:end` only for presentation (change an expression, play the next clip). Native objects: `anim.mixer` (AnimationMixer), `anim.actions` (clip
|
|
134
134
|
name -> AnimationAction). Things without a skeleton that only move/rotate as a whole use `engine.timeline.tween`, not an Animator.
|
|
135
135
|
|
|
136
|
+
Bones after the pose: `const h = player.onPose((c, dt) => { sword.position.copy(hand.getWorldPosition(v)); })` runs every frame right after the character's pose is
|
|
137
|
+
applied (clips or procedural rig); `h.remove()` stops it. Presentation only.
|
|
138
|
+
|
|
136
139
|
## 6. Verify
|
|
137
140
|
- `anim.describe()` -> `{ state, clip, time, progress, driven, t, weights }` (clip seconds, 0-1 progress, whether sync drives it, the last gameplay t,
|
|
138
141
|
each fading state's share); the player's is in `describe().player.anim`.
|
package/docs/recipes/15-perf.md
CHANGED
|
@@ -52,7 +52,7 @@ and they get timed.
|
|
|
52
52
|
| Symptom | Fix |
|
|
53
53
|
|---|---|
|
|
54
54
|
| Many draw calls | Use `vegetation` / InstancedMesh for repeated objects; install `hlod()` for a block of buildings; share geometry and materials between copies of a model (`assets.model` shares by default) |
|
|
55
|
-
| Expensive shadows | Style pack `sky.shadow.updateEvery: 3` (update every 3 frames), reduce `mapSize`/`extent`; filter `createEngine({ shadowType: 'basic' })` (hard edge, cheapest) / `'pcf'` (default) / `'vsm'` (softest, costliest), switch live with `engine.
|
|
55
|
+
| Expensive shadows | Style pack `sky.shadow.updateEvery: 3` (update every 3 frames), reduce `mapSize`/`extent`; filter `createEngine({ shadowType: 'basic' })` (hard edge, cheapest) / `'pcf'` (default) / `'vsm'` (softest, costliest), switch live with `engine.look.shadow.set({ type: 'vsm', radius: 3 })` (radius: pcf and vsm only; blurSamples: vsm only; a switch recompiles materials, so avoid doing it every frame); the vegetation species option `shadowRing` (default 1) sets within how many chunk rings it casts shadows; change it while playing with `engine.vegetation.setShadowRing('tree', 0)` |
|
|
56
56
|
| Stutter while walking | Put generation work in `engine.jobs.add(function* () { ...; yield; })` or `engine.stream.add`; chunk upload budget `engine.terrain.applyBudgetMs` |
|
|
57
57
|
| Slow start | Look at which is slowest in `engine.startup.modules`; `npm run bake` for large models; preload only the necessary assets |
|
|
58
58
|
| Slow physics | Keep dynamic rigid bodies within a few hundred (the `rigidBodies` budget); `rigid({ terrainRing: 1 })` |
|
|
@@ -19,32 +19,35 @@ game only advances on step); once you open the page in a browser, commands go to
|
|
|
19
19
|
| `describe` | One-line scene summary: position / time and weather / nearby / quest | `player (4.0, 7.0) in forest · 07:11 day 1 · clear` |
|
|
20
20
|
| `describe --full` | The state as text, summary first (`engine.describeText()`: at most 30 lines, the nearest things, one line per module with its key counts, and a last line on how to expand). Details: `describe <path>` for one part, `engine.describeText({ full: true })` for everything | `quests: active[1], done=0, failed=0` |
|
|
21
21
|
| `describe --all` | Everything: every nearby thing and every module's full data (`describeText({ full: true })`); large, prefer a path | |
|
|
22
|
+
| `describe render` | How the picture is set: tone mapping, exposure, shadow filter, post effects with params, default lights, each tagged `engine` (default), `style` or `game` (changed after). Also the `renderer:` lines of `describe --full`. Information only, never warns | `{ "toneMapping": { "value": "aces", "by": "style" }, ... }` |
|
|
22
23
|
| `describe player.position` | Player coordinates { x, y, z } (numbers) | `{ "x": 4, "y": 1.2, "z": 7 }` |
|
|
23
24
|
| `describe player.state` | Just one item of `engine.describe()` (dotted path, `--max characters`) | `"idle"` |
|
|
24
25
|
| `step 2` | Advance 2 game seconds (deterministic; a real-time page is paused first) | `✓ Stepped 2 s · player (4.0, 7.0) in forest · 07:20 day 1` |
|
|
25
|
-
| `press interact` | Press an action name or key once (`KeyE`, `e`, `Escape`). **It advances game time**: 0.1 s held + one rendered frame of 1/60 s, about 0.117 s in total;
|
|
26
|
+
| `press interact` | Press an action name or key once (`KeyE`, `e`, `Escape`). **It advances game time**: 0.1 s held + one rendered frame of 1/60 s, about 0.117 s in total; shorten the hold with `--for 0.02` when timing matters | `✓ Pressed menu (Escape) · … · window open: settings` |
|
|
26
27
|
| `hold moveForward 1.5` | Hold for 1.5 seconds | `✓ Held moveForward (KeyW) for 1.5 s · player (-0.6, 3.0) …` |
|
|
28
|
+
| `skip to=06:00` / `skip seconds=600` | Jump the clock like sleeping (`engine.skip`) | `✓ Skipped to 06:00 → 21600 · … 06:00 day 2` |
|
|
27
29
|
| `ops` | What the player can do now: every op offer checked with `can` (`recipes/23-ops.md`) | `✓ shop.buy item=bread · ✗ shop.buy item=cake (soldOut)` |
|
|
28
|
-
| `op shop.buy shop=bakery item=bread n=2` | Run a game op (source `bridge`, **no time passes**). Values follow the op's `args` shape
|
|
29
|
-
| `inspect` / `inspect npc_3` / `inspect 10,-4` | What is around the player
|
|
30
|
-
| `pick 480,270` | What is at that screen pixel
|
|
31
|
-
| `explain op barter.buy shop=fisher-basket item=berry` / `explain quest first-light` | Why an op cannot run now (the reason and the op's note on fixing it first; `--full` adds the last attempt and
|
|
32
|
-
| `explain op name key=value --full` | Adds the detail: the op's last attempt and the events around it | |
|
|
30
|
+
| `op shop.buy shop=bakery item=bread n=2` | Run a game op (source `bridge`, **no time passes**). Values follow the op's `args` shape (`n=2` a number, `position=3,0,-2` an array). **Change state with this, not `js`**: `js` writes skip the op log | `✓ shop.buy → 2 · Bag gold×2 bread×2` / `✗ shop.buy: noMoney (Not enough gold)` |
|
|
31
|
+
| `inspect` / `inspect npc_3` / `inspect 10,-4` | What is around the player and which ops it can do now, with reasons (`engine.inspect`, recipes/23-ops.md section 8) | `player at (4, 7) · near: 老渔夫 1 m` / `✗ barter.buy shop=fisher-basket item=feather (soldOut: …)` |
|
|
32
|
+
| `pick 480,270` | What is at that screen pixel: record id, kind, template, the content file and line that defines it, its fields (recipes/30-templates.md section 5) | `✓ chest-home (kind chest, template chest) …` / `defined in content/props.js:14: edit it there …` |
|
|
33
|
+
| `explain op barter.buy shop=fisher-basket item=berry` / `explain quest first-light` | Why an op cannot run now (the reason and the op's note on fixing it first; `--full` adds the last attempt and events around it), or where a quest is stuck (`engine.explain`) | `✗ barter.buy {...} cannot run now: noFilm (Not enough film)` |
|
|
33
34
|
| `scenario barter` | Run `tests/scenarios/barter.json` (recipes/23-ops.md section 7); prints failed checks, leaves it paused | `✓ barter: 6 checks passed` |
|
|
34
35
|
| `state time=18:30 weather=rain pos=40,-20` | Set the scene (like URL parameters: time weather pos save wait cutscene state) | `✓ Set · 18:30 day 1 · rain` |
|
|
35
|
-
| `js "engine.sky.timeOfDay"` (alias `eval`) | Evaluate an expression in the page; `engine` is available directly and `await` works inside; multi-line statements need their own `return` (e.g. `js "const p = engine.player.position; return p.x + p.z"`).
|
|
36
|
+
| `js "engine.sky.timeOfDay"` (alias `eval`) | Evaluate an expression in the page; `engine` is available directly and `await` works inside; multi-line statements need their own `return` (e.g. `js "const p = engine.player.position; return p.x + p.z"`). Long scripts: `js --file script.js` | `✓ 0.77` |
|
|
36
37
|
| `snap name` | Screenshot to `.threedog/shots/name.png` | `✓ Screenshot .threedog/shots/t1.png (163 KB)` |
|
|
37
38
|
| `snap-describe save` / `snap-describe diff` + name | Describe snapshot instead of a screenshot: save the gameplay part of `describe()` as a baseline, or print how the running page differs from it (section 7) | `✗ describe "market" differs from the baseline in 1 place:` |
|
|
38
|
-
| `errors` | Page errors added since last time (
|
|
39
|
-
| `loading` / `loading hero` | What loading waits for, what failed (file, HTTP status, fallback) and whether it blocks the start;
|
|
39
|
+
| `errors` | Page errors added since last time (full log: `.threedog/errors.log`). Known classes get a cause + recipe line (section 8) | `✗ 1 new error` / `✗ 3 new errors` / `✓ No new errors` |
|
|
40
|
+
| `loading` / `loading hero` | What loading waits for, what failed (file, HTTP status, fallback) and whether it blocks the start; works while `start()` is stuck. With a name: that task with its manifest and path (`recipes/05-props-bake.md` section 3) | `… waiting: decoding model "hero" (…)` / `✗ Loading finished, 4/5 ok, 1 failed` |
|
|
40
41
|
| `reload` / `resume` | Reload the page / resume real-time running | |
|
|
41
42
|
|
|
42
43
|
## 2. Notes
|
|
43
|
-
- **Smallest scenario** (`tests/scenarios/coins.json
|
|
44
|
+
- **Smallest scenario** (`tests/scenarios/coins.json` <!-- r18-ignore-line -->, then `npx threedog verify coins` or `scenario coins`; `verify` with no file says "Have: none"):
|
|
44
45
|
`{ "name": "coins", "url": "/", "state": { "pos": "6,4" }, "steps": [ { "step": 1 }, { "expect": { "inventory.items.coin": 1 } } ] }`
|
|
45
46
|
- **Teleport + `step 1` collects `auto` pickups** (`state pos=`, `player.placeAt`): the pickup check runs in the fixed step after any move.
|
|
46
|
-
- **`shot` always starts a fresh game** (
|
|
47
|
-
- **`step` / `press` pause the real page
|
|
47
|
+
- **`shot` always starts a fresh game** (`?save=slot1` loads one); after playing use `snap name`. `shot --keep` adds a timestamp to the file name (no overwrite); `shot --look` prints mean luminance / saturation and the share of overexposed (>=250) and dark (<=20) pixels.
|
|
48
|
+
- **`step` / `press` pause the real page**; resume with `npx threedog resume` when done (they pause as owner `threedog`, so a game's own pause stays). A headless page only advances on step anyway.
|
|
49
|
+
- **Run state** is printed after `step` / `press` / `skip` / `resume` and by `npx threedog status`: `running`, `title-frozen` (title screen waiting for start), `test-paused` (only the bridge paused it), `paused(by owners)` (every `pause` / `freeze` owner, e.g. `ui-inventory`) or `loading`. The same object is `engine.runState` and `describe().time.run`: `{ state, by, blockedBy }`, where `blockedBy` lists what keeps input from driving the game (opaque input contexts such as `win-settings`, `ui-title`, `dialogue`, `cutscene`, plus `error` and `loading`); the bridge and the MCP tools copy it as-is. A test that pauses passes `pause(owner, { kind: 'test' })` to read as `test-paused`.
|
|
50
|
+
- **Who holds what**: `describe().time.heldBy` lists every pause, freeze, camera and debug-view holder in one shape `[{ owner, at }]` (`at` = file:line of the first take), so a stuck pause or a camera nobody gave back has a name.
|
|
48
51
|
- **`snap` on a real page captures only the canvas** (not the HTML UI); on a headless page it captures the whole page. To see UI state use `describe`
|
|
49
52
|
(`ui.windows`, dialogue).
|
|
50
53
|
- **Keys go through `engine.input` like a real keyboard**: action names are translated to keyboard keys (gamepad buttons are ignored); when a window
|
|
@@ -53,7 +56,7 @@ game only advances on step); once you open the page in a browser, commands go to
|
|
|
53
56
|
works with `engine.step`): `engine.input.simulate('jump'); engine.step(1 / 60); engine.input.simulate('jump', false)`. Never call `_keyDown` /
|
|
54
57
|
`_keyUp` (internal).
|
|
55
58
|
- `describe` by default gives only the 3 nearest things and the first quest; for detail use a path (`quests.active`, `nearby`, `world`) or `--full`;
|
|
56
|
-
|
|
59
|
+
|
|
57
60
|
- Several pages: `--page /<page>.html` picks the path; `-w name` picks the workspace.
|
|
58
61
|
- To change the port: `npm run dev -- my-game --port 5000`; the CLI finds the port from `.threedog/dev.json`, so you don't need to specify it again.
|
|
59
62
|
- If a command never becomes ready: most likely `main.js` doesn't set `window.engine = engine;` (it must come before `await engine.start()`). Under
|
|
@@ -61,6 +64,20 @@ game only advances on step); once you open the page in a browser, commands go to
|
|
|
61
64
|
has `window.engine`, `engine.ready`, and the latest page errors.
|
|
62
65
|
- Error messages give the cause and the next step, e.g. "no running dev server -> run npm run dev first".
|
|
63
66
|
|
|
67
|
+
## 2b. A scripted playthrough, and three kinds of check
|
|
68
|
+
```
|
|
69
|
+
npx threedog state pos=0,0 time=12:00 # known start
|
|
70
|
+
npx threedog hold moveForward 1.5 # walk (real key path, advances 1.5 s)
|
|
71
|
+
npx threedog press interact # one key press (~0.117 s)
|
|
72
|
+
npx threedog step 2 # let things happen
|
|
73
|
+
npx threedog js "engine.player.position.x > 1" # state assertion: read the ✓ true / false
|
|
74
|
+
npx threedog snap after-walk # only now look at pixels
|
|
75
|
+
```
|
|
76
|
+
The same steps as a file: `tests/scenarios/<name>.json` with `{ "press": … }`, `{ "step": … }`, `{ "expect": { path: value } }` (section 9; no `hold` there).
|
|
77
|
+
- **State checks** (`op`, `expect`, `describe`, `js`): fast and exact, but they skip input. They prove rules, not that the player can reach them.
|
|
78
|
+
- **Simulated-input checks** (`press`, `hold`, `engine.input.simulate`): bridge key events through the game's input path, never a physical keyboard/mouse. `verify` prints `Layers: direct N, simulated-input N, real-browser-input 0 (not verified), visual 0`, then an **Evidence** block (each check's layer and what it asserted), a fixed **NOT proven** line (pointer lock and mouse look, real GPU/visuals, real FPS) and **Coverage** (ops run vs defined, refused ops counted as run and marked; modules in three groups: tested = an op ran, indirect = no op but describe section compared / save part changed / events fired, untested; lists capped at 10 with "+N more"; uses `engine.catalog()`). `threedog scenario` prints the same Coverage block; the full lists are in `--json` (`data.evidence.coverage`, `data.coverage`). Not yet covered: content ids (defined vs touched).
|
|
79
|
+
- **Visual checks** (`snap`, `shot --look`): the only ones that see the look (exposure, color, UI overlap). Slowest; take them last.
|
|
80
|
+
|
|
64
81
|
## 3. Windows / PowerShell notes
|
|
65
82
|
- **Quote commas**: PowerShell splits `pos=1,-8` into two arguments and the coordinates become NaN. Write `npx threedog state "pos=1,-8"` (the bridge
|
|
66
83
|
reports an error and shows this tip when pos is not two numbers).
|
|
@@ -71,6 +88,21 @@ game only advances on step); once you open the page in a browser, commands go to
|
|
|
71
88
|
- Some terminal sandboxes (Bash) block commands containing the word `eval`: use `js`, not `eval`.
|
|
72
89
|
- Paths containing Chinese characters are fine; inside the game folder you can omit `-w`.
|
|
73
90
|
|
|
91
|
+
## 3b. Speed, a session, and checks in one call
|
|
92
|
+
|
|
93
|
+
Why a command used to take seconds: `npx` itself costs about 2.5 s on Windows (npm starts, resolves the bin) before threedog runs at all; threedog added a second node process (about 0.25 s) and a cold first request. Measured on the engine example, per command: `npx threedog describe` 3.2 s; `node node_modules/@threedog/tools/bin/threedog.mjs describe` 0.83 s before, 0.50 s now (one process, lazy imports); with a session 0.4 s (node start alone is 0.27 s).
|
|
94
|
+
|
|
95
|
+
- For a many-step test call the bin directly (`node node_modules/@threedog/tools/bin/threedog.mjs ...`, or `node_modules/.bin/threedog`) instead of `npx`.
|
|
96
|
+
- `npx threedog session` starts a background process that serves later commands; it exits after 10 idle minutes (`--minutes N`), `session stop` ends it. Commands behave identically with or without it.
|
|
97
|
+
- `threedog js --file steps.js`: put the whole test in one file and run it once. Inside: `assert(cond, msg)`, `expect(v).toBe(x)` (also `toEqual`, `toBeCloseTo(x, tol)`, `toBeGreaterThan`), `step(seconds)`, `log(...)`, and `engine`. The output is only the failures and one summary line, exit code 1 on failure, so ten steps cost one round trip and a few tokens:
|
|
98
|
+
|
|
99
|
+
```js
|
|
100
|
+
step(2);
|
|
101
|
+
const before = engine.tick;
|
|
102
|
+
step(1);
|
|
103
|
+
expect(engine.tick).toBeGreaterThan(before, 'time advanced');
|
|
104
|
+
```
|
|
105
|
+
|
|
74
106
|
## 4. Let describe see the game's own state
|
|
75
107
|
A game's own state (score, number of targets, crops) is not in `describe` by default. **Small games use this**: register it in one line, no module needed:
|
|
76
108
|
```js
|
|
@@ -126,10 +158,11 @@ data, duplicate ids, unknown option / name, module order, asset 404, ...) get th
|
|
|
126
158
|
combination so tests and scenarios reuse it.
|
|
127
159
|
|
|
128
160
|
## 10. MCP server: Claude Code, Cursor and other MCP clients
|
|
129
|
-
`npx threedog mcp` runs the dev bridge as an MCP server over stdio. Each command becomes a tool (`describe`, `step`, `press`, `hold`, `state`, `ops`,
|
|
130
|
-
`op`, `inspect`, `pick`, `explain`, `errors`, `loading`, `snap`, `snap_describe`, `scenario`, `reload`, `resume
|
|
131
|
-
|
|
132
|
-
|
|
161
|
+
`npx threedog mcp` runs the dev bridge as an MCP server over stdio. Each command becomes a tool (`play`, `status`, `describe`, `step`, `press`, `hold`, `skip`, `state`, `ops`,
|
|
162
|
+
`op`, `catalog`, `inspect`, `scene`, `pick`, `thing`, `explain`, `errors`, `loading`, `snap`, `snap_describe`, `scenario`, `verify`, `reload`, `resume`;
|
|
163
|
+
tests/mcp.mjs fails when this list and the server's tools differ) and returns the same text as the
|
|
164
|
+
command line; `snap` also returns the PNG as an image. It finds the dev server through `.threedog/dev.json` like the CLI; with none running, call the `play` tool (it starts the server and waits for the bridge)
|
|
165
|
+
(or start `npm run dev` yourself; a tool call without a server answers with that fix). It is only a local client of the bridge and opens no port; every check in section 5 still applies. As
|
|
133
166
|
with the command line, the `op` and `step` tools change the current session and its saves; the level itself changes only by editing content files.
|
|
134
167
|
|
|
135
168
|
Claude Code (in the game folder; in the engine repository add `-w name` after `mcp`):
|
|
@@ -141,6 +174,7 @@ Cursor, `.cursor/mcp.json` in the game folder: <!-- r18-ignore-line -->
|
|
|
141
174
|
{ "mcpServers": { "threedog": { "command": "npx", "args": ["threedog", "mcp"] } } }
|
|
142
175
|
```
|
|
143
176
|
On native Windows, wrap npx in cmd: `claude mcp add threedog -- cmd /c npx threedog mcp` (Cursor: `"command": "cmd", "args": ["/c", "npx", "threedog", "mcp"]`).
|
|
177
|
+
Faster and the same on every OS: point it at the installed bin with plain node, from the project folder: `claude mcp add threedog -- node node_modules/@threedog/tools/bin/threedog.mjs mcp` (the server starts once per session, so npx only costs at start, but node also avoids `cmd /c`). `npm run new-game` writes a `.mcp.json` like this into the new game, so opening the game folder in Claude Code picks it up.
|
|
144
178
|
|
|
145
179
|
The `js` tool (arbitrary code in the page) is off by default; `threedog mcp --allow-js` enables it, for development only. Other options: `-w name`
|
|
146
180
|
(workspace), `--page /<page>.html` (page path).
|
|
@@ -41,7 +41,7 @@ engine.setCamera?.('follow', { distance: 8, pitch: 0.3 });
|
|
|
41
41
|
- **Teleport, then lookAt**: `await engine.stream.teleport(p); engine.cameraRig.lookAt(target);` works in that order: `lookAt` aims from the body's
|
|
42
42
|
current position, not from the last drawn frame. Call it after the move (the angles do not follow later moves).
|
|
43
43
|
- **Player movement direction follows the camera**: `engine.cameraRig.forward()` / `right()` change automatically after switching.
|
|
44
|
-
- **Cutscene takeover**: while `engine.cameraOverride` is not null the camera module leaves the camera alone; see
|
|
44
|
+
- **Cutscene takeover**: while anyone holds `engine.takeCamera(owner)` (`engine.cameraOverride` is not null) the camera module leaves the camera alone; see [the engine API](../api/engine.md).
|
|
45
45
|
- **Shooting games**: bind first-person firing to a mouse-button action, see `19-shooting-picking.md`.
|
|
46
46
|
|
|
47
47
|
## 4. Over the shoulder, lock-on framing, mouse lock (follow camera)
|
|
@@ -51,7 +51,7 @@ engine.cameraRig.shoulder = -0.7; // switch shoulders at any time (plain p
|
|
|
51
51
|
engine.cameraRig.frame(enemy.object); // lock-on: turn to "behind the player, looking at the enemy"; frame(null) lets go
|
|
52
52
|
```
|
|
53
53
|
- **`shoulder`**: meters the aim point (and so the camera) moves to the right along `right()`; negative = left, 0 = centered (default).
|
|
54
|
-
- **`pointerLock`** (default false): a click on the canvas locks the mouse, so moving it turns the view with no dragging; Esc releases. Not on phones.
|
|
54
|
+
- **`pointerLock`** (default false): a click on the canvas locks the mouse, so moving it turns the view with no dragging; Esc releases. Not on phones. If the browser refuses the lock the camera falls back to dragging; `describe().camera.pointerLock` is a state machine: `state` is `off` / `unsupported` / `waiting-click` / `requesting` / `locked` / `refused`, plus `covered` (what sits on the canvas centre and eats the click), `cameraOverride` (a takeover blocks locking) and `lastFailure { reason, agoSec }`; the text line shows the same.
|
|
55
55
|
The press that locks is swallowed (no `Mouse0`, no click) so it cannot attack or fire; `swallowLockClick: false` delivers it.
|
|
56
56
|
Leave it off when the mouse buttons are for UI or clicking the ground.
|
|
57
57
|
- **`yaw` means which side of the player the camera is on**: `camera = focus + (sin yaw, cos yaw) * distance`, so the camera looks along
|
|
@@ -102,3 +102,52 @@ engine.onFixed(dt => {
|
|
|
102
102
|
- The engine already calls `player.animate(dt)` every frame; a module with its own loop over characters must skip the player, or the walk cycle runs
|
|
103
103
|
twice as fast.
|
|
104
104
|
- Test without a keyboard: `engine.input.simulate('lockOn'); engine.step(1 / 60); engine.input.simulate('lockOn', false)`.
|
|
105
|
+
|
|
106
|
+
## 6. Orthographic view, and taking the camera over yourself
|
|
107
|
+
|
|
108
|
+
**Orthographic (isometric / 2.5D) with the built-in rigs.** `projection: 'orthographic'` plus `size` (world units of view height) on the fixed and follow cameras.
|
|
109
|
+
The default stays perspective. On resize the view height stays `size` and the width follows the aspect.
|
|
110
|
+
|
|
111
|
+
```js
|
|
112
|
+
// one fixed isometric shot (shorthand for a single shot named 'main')
|
|
113
|
+
engine.setCamera('fixed', { position: [14, 14, 14], lookAt: [0, 0, 0], projection: 'orthographic', size: 16 });
|
|
114
|
+
// per shot: shots: { hall: { position, lookAt, projection: 'orthographic', size: 12 }, yard: { position, lookAt } } // yard stays perspective
|
|
115
|
+
// follow the player from a fixed angle
|
|
116
|
+
engine.setCamera('follow', { pitch: 0.6, yaw: 0.8, distance: 20, projection: 'orthographic', size: 14 });
|
|
117
|
+
```
|
|
118
|
+
|
|
119
|
+
- `engine.camera` stays the one object everything holds (render, post, shadows, sky); it is flipped to an orthographic matrix, so `camera.isOrthographicCamera`
|
|
120
|
+
is true, `camera.left/right/top/bottom` are set, and `camera.zoom` still zooms. `camera.fov` is ignored while it is on.
|
|
121
|
+
- Blends between two orthographic shots blend `size`; a perspective/orthographic mix switches to the target's mode at once. Switching rig kinds returns to perspective.
|
|
122
|
+
- Limits: on the follow camera the mouse wheel changes `size` (clamped to the `minDistance`/`maxDistance` ratio of the starting `distance`).
|
|
123
|
+
The `fov` slider in the settings menu has no effect. Cascaded shadows, `dof` and `outline` handle orthographic depth; a custom post pass that assumes perspective depth must do the same.
|
|
124
|
+
|
|
125
|
+
**Placing the camera yourself (cutscene, photo mode, your own rig).** Take it with `engine.takeCamera(owner, { focus })`; the camera module leaves the camera alone until you `remove()` the handle.
|
|
126
|
+
Several holders can take it (a cutscene, then a named view on top): the latest is in charge, and removing it hands the camera back to the previous one, not to nobody.
|
|
127
|
+
|
|
128
|
+
```js
|
|
129
|
+
let t = 0;
|
|
130
|
+
const cam = engine.takeCamera('my-orbit', { focus: engine.player.position }); // focus (optional): where the world loads around
|
|
131
|
+
const frame = engine.onFrame(dt => {
|
|
132
|
+
t += dt; engine.camera.position.set(Math.cos(t) * 12, 8, Math.sin(t) * 12); engine.camera.lookAt(0, 1, 0);
|
|
133
|
+
});
|
|
134
|
+
// done: frame.remove(); cam.remove(); // the rig resumes from its own state
|
|
135
|
+
```
|
|
136
|
+
|
|
137
|
+
To use your own `THREE.OrthographicCamera` instead of flipping `engine.camera`:
|
|
138
|
+
|
|
139
|
+
```js
|
|
140
|
+
const original = engine.camera, size = 12;
|
|
141
|
+
const ortho = new THREE.OrthographicCamera(-1, 1, 1, -1, 0.1, 500);
|
|
142
|
+
function fit() { // the engine only updates engine.camera.aspect on resize, so keep your own camera's aspect here
|
|
143
|
+
const s = engine.renderer.getSize(new THREE.Vector2()), a = s.x / s.y;
|
|
144
|
+
ortho.left = -size * a / 2; ortho.right = size * a / 2; ortho.top = size / 2; ortho.bottom = -size / 2; ortho.updateProjectionMatrix();
|
|
145
|
+
}
|
|
146
|
+
const cam = engine.takeCamera('my-ortho');
|
|
147
|
+
engine.camera = ortho; // the plain render path, cascaded shadows and modules read engine.camera live
|
|
148
|
+
ortho.position.set(10, 10, 10); ortho.lookAt(0, 0, 0); fit(); addEventListener('resize', fit);
|
|
149
|
+
// give it back: removeEventListener('resize', fit); engine.camera = original; cam.remove();
|
|
150
|
+
```
|
|
151
|
+
|
|
152
|
+
Swapping the object only works while no post effect is active: the post chain's scene pass keeps the camera it was built with. With post effects, use
|
|
153
|
+
`projection: 'orthographic'` above instead.
|