threedog 0.8.0 → 1.0.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/CHANGELOG.md +219 -4
- package/README.md +6 -6
- package/core/assets/Animator.js +2 -0
- package/core/assets/Assets.js +44 -13
- package/core/assets/assetEntry.js +87 -22
- package/core/assets/assetHot.js +2 -1
- package/core/assets/assetReport.js +1 -2
- package/core/audio/Audio.js +24 -5
- package/core/base/I18n.js +6 -3
- package/core/base/Random.js +3 -1
- package/core/base/Vars.js +14 -4
- package/core/base/errorCodes.js +54 -16
- package/core/base/errorHints.js +12 -1
- package/core/base/errors.js +6 -4
- package/core/base/events.generated.js +10 -0
- package/core/base/follows.js +26 -0
- package/core/base/math.js +15 -8
- package/core/base/params.js +2 -2
- package/core/{saves → base}/saveValues.js +24 -6
- package/core/base/sections.js +97 -0
- package/core/base/spelling.js +32 -0
- package/core/base/validate.js +8 -29
- package/core/engine/Engine.js +61 -18
- package/core/engine/Loading.js +30 -3
- package/core/engine/copies.js +1 -1
- package/core/engine/headlessLoad.js +30 -13
- package/core/engine/lifecycle.js +30 -25
- package/core/engine/loop.js +22 -4
- package/core/engine/moduleSlots.js +91 -15
- package/core/engine/moduleTypes.js +13 -0
- package/core/engine/modules.js +248 -62
- package/core/engine/page.js +25 -8
- package/core/engine/plugins.js +15 -3
- package/core/engine/services.js +3 -0
- package/core/engine/startup.js +46 -36
- package/core/input/Input.js +39 -19
- package/core/input/inputKeyboard.js +39 -0
- package/core/input/inputPad.js +23 -2
- package/core/input/inputPointer.js +3 -1
- package/core/input/inputSeat.js +66 -0
- package/core/input/inputTouch.js +23 -6
- package/core/inspect/DebugOverrides.js +13 -2
- package/core/inspect/Describe.js +10 -6
- package/core/inspect/Inspect.js +31 -4
- package/core/inspect/UrlState.js +14 -10
- package/core/inspect/catalog.js +12 -5
- package/core/inspect/describeRender.js +3 -2
- package/core/inspect/describeText.js +6 -2
- package/core/inspect/metadata.generated.js +4140 -0
- package/core/inspect/pictureWriters.js +117 -33
- package/core/inspect/toolDoor.js +21 -0
- package/core/inspect/valueHistory.js +35 -0
- package/core/ops/Ops.js +32 -7
- package/core/ops/control.js +48 -23
- package/core/ops/holds.js +4 -3
- package/core/ops/opsAtomic.js +18 -6
- package/core/ops/opsCheck.js +7 -5
- package/core/ops/opsFail.js +5 -7
- package/core/ops/opsRun.js +2 -2
- package/core/ops/owned.js +20 -3
- package/core/ops/sharedPoint.js +7 -10
- package/core/ops/stacks.js +22 -1
- package/core/saves/SaveStore.js +52 -26
- package/core/saves/Saves.js +122 -27
- package/core/saves/saveApply.js +159 -61
- package/core/saves/saveFiles.js +30 -25
- package/core/saves/saveVersions.js +20 -6
- package/core/saves/session.js +76 -33
- package/core/saves/stateReplace.js +184 -0
- package/core/scene/Rays.js +21 -5
- package/core/scene/Views.js +6 -6
- package/core/scene/adaptive.js +13 -10
- package/core/scene/canvasBox.js +2 -0
- package/core/scene/compositeGround.js +72 -0
- package/core/scene/floor.js +17 -0
- package/core/scene/grid.js +2 -0
- package/core/scene/ground.contract.js +14 -0
- package/core/scene/ground.js +52 -17
- package/core/scene/pixel.js +154 -0
- package/core/scene/pixelRatio.js +167 -0
- package/core/scene/sceneDelta.js +3 -3
- package/core/scene/sceneMethods.js +11 -6
- package/core/scene/stepPoses.js +6 -1
- package/core/scene/thingExplain.js +1 -1
- package/core/scene/thingOps.js +22 -14
- package/core/scene/things.js +1 -1
- package/core/scene/tier.js +10 -0
- package/core/scene/view.js +126 -9
- package/core/stream/Batching.js +0 -1
- package/core/stream/Stream.js +24 -12
- package/core/stream/batchGroups.js +1 -0
- package/core/stream/scatter.js +5 -2
- package/core/stream/streamSources.js +2 -1
- package/core/threads/Commits.js +12 -7
- package/core/threads/Jobs.js +15 -5
- package/core/threads/Threads.js +5 -2
- package/core/time/Clock.js +3 -1
- package/core/time/skip.js +10 -4
- package/core/time/time.js +16 -10
- package/docs/AI.md +89 -72
- package/docs/API.md +18 -14
- package/docs/CODEMAP.md +68 -40
- package/docs/COMMANDS.md +22 -23
- package/docs/CONVENTIONS.md +120 -17
- package/docs/MIGRATING-0.8.md +2 -0
- package/docs/MIGRATING-1.0.md +101 -0
- package/docs/THREE.md +65 -12
- package/docs/api/cameraRig.md +3 -0
- package/docs/api/characters.md +13 -7
- package/docs/api/collider3d.md +9 -0
- package/docs/api/content.md +16 -15
- package/docs/api/dialogue.md +2 -1
- package/docs/api/engine.md +18 -16
- package/docs/api/events.md +14 -4
- package/docs/api/ground.md +2 -2
- package/docs/api/i18n.md +1 -1
- package/docs/api/input.md +2 -1
- package/docs/api/interactions.md +1 -1
- package/docs/api/inventory.md +1 -1
- package/docs/api/level.md +3 -2
- package/docs/api/nav.md +4 -2
- package/docs/api/particles.md +8 -5
- package/docs/api/pickups.md +1 -1
- package/docs/api/post.md +3 -4
- package/docs/api/quests.md +4 -2
- package/docs/api/rays.md +2 -0
- package/docs/api/rigid.md +3 -2
- package/docs/api/saves.md +8 -7
- package/docs/api/stream.md +4 -5
- package/docs/api/terrain.md +3 -4
- package/docs/api/terrainDraw.md +1 -1
- package/docs/api/timeline.md +2 -2
- package/docs/api/tools.md +3 -1
- package/docs/api/triggers.md +2 -0
- package/docs/api/vegetationDraw.md +1 -1
- package/docs/api/water.md +6 -2
- package/docs/api/weather.md +19 -4
- package/docs/api/weatherDraw.md +1 -1
- package/docs/api/world.md +1 -1
- package/docs/recipes/01-new-game.md +3 -3
- package/docs/recipes/02-npc.md +3 -4
- package/docs/recipes/03-items-pickups.md +11 -11
- package/docs/recipes/04-quests.md +2 -0
- package/docs/recipes/05-props-bake.md +9 -9
- package/docs/recipes/06-clock-events.md +6 -6
- package/docs/recipes/07-flow-scenes-pause.md +18 -15
- package/docs/recipes/08-weather-sky.md +5 -5
- package/docs/recipes/09-materials-lights-models.md +3 -3
- package/docs/recipes/10-blender-level.md +16 -4
- package/docs/recipes/11-vehicles.md +18 -6
- package/docs/recipes/12-navmesh.md +52 -8
- package/docs/recipes/13-animation.md +34 -8
- package/docs/recipes/14-custom-module.md +20 -8
- package/docs/recipes/15-perf.md +4 -4
- package/docs/recipes/16-dev-bridge.md +9 -8
- package/docs/recipes/18-world.md +13 -5
- package/docs/recipes/19-shooting-picking.md +3 -2
- package/docs/recipes/20-content-actions-save.md +26 -6
- package/docs/recipes/21-camera.md +17 -23
- package/docs/recipes/22-shop-gold.md +21 -12
- package/docs/recipes/23-ops.md +19 -15
- package/docs/recipes/26-ui-parts.md +3 -2
- package/docs/recipes/27-net.md +3 -3
- package/docs/recipes/28-terrain.md +3 -3
- package/docs/recipes/29-grid.md +1 -1
- package/docs/recipes/30-templates.md +10 -13
- package/docs/recipes/31-audio.md +2 -2
- package/docs/recipes/32-action-game.md +6 -5
- package/docs/recipes/33-stream-sources.md +4 -1
- package/docs/recipes/34-environment-lighting.md +7 -8
- package/docs/recipes/35-picture-from-reference.md +13 -9
- package/docs/recipes/36-ground-plants.md +3 -2
- package/docs/recipes/40-scene.md +11 -10
- package/docs/recipes/43-shader-patches-surfaces.md +7 -7
- package/docs/recipes/44-water-weather-hooks.md +9 -8
- package/docs/recipes/45-cascaded-shadows.md +3 -4
- package/docs/recipes/46-blender-art-route.md +3 -3
- package/docs/recipes/49-game-module-contract.md +2 -1
- package/docs/recipes/50-own-renderer.md +1 -0
- package/docs/recipes/51-capability-catalog.md +14 -8
- package/docs/recipes/52-around-the-picture.md +4 -4
- package/docs/recipes/55-mods-time-wrap.md +5 -4
- package/docs/recipes/56-webgpu-tsl.md +12 -1
- package/docs/recipes/57-control.md +30 -10
- package/docs/recipes/58-input.md +13 -0
- package/docs/recipes/60-judge-the-picture.md +1 -1
- package/docs/recipes/62-picture-code.md +106 -48
- package/docs/recipes/63-third-person-start.md +2 -1
- package/docs/recipes/64-particles.md +53 -4
- package/docs/recipes/65-swarm.md +2 -2
- package/docs/recipes/66-common-tasks.md +313 -0
- package/examples/action/.threedog/content-index.json +1 -1
- package/examples/action/GAMEMAP.md +3 -3
- package/examples/perf-island/.threedog/content-index.json +1 -1
- package/examples/perf-island/GAMEMAP.md +3 -3
- package/examples/perf-island/main.js +2 -2
- package/examples/plain-picture/GAMEMAP.md +3 -1
- package/examples/rc2d/GAMEMAP.md +1 -1
- package/examples/rc2d/rc2d.js +1 -1
- package/examples/styletest/.threedog/content-index.json +1 -1
- package/examples/styletest/GAMEMAP.md +3 -3
- package/examples/webgpu-tsl/GAMEMAP.md +1 -1
- package/examples/world/.threedog/content-index.json +1 -1
- package/examples/world/GAMEMAP.md +5 -4
- package/examples/world/main.js +3 -3
- package/index.d.ts +8 -5
- package/index.js +22 -1
- package/llms.txt +2 -1
- package/modules/ambience/Ambience.js +5 -3
- package/modules/calendar/index.js +7 -5
- package/modules/camera/FirstPersonCamera.js +3 -3
- package/modules/camera/FixedCamera.js +34 -20
- package/modules/camera/FollowCamera.js +20 -11
- package/modules/camera/RtsCamera.js +1 -0
- package/modules/camera/common.js +33 -22
- package/modules/camera/pixelSnap.js +62 -0
- package/modules/characters/Character.js +136 -43
- package/modules/characters/NPC.js +60 -28
- package/modules/characters/assetModel.js +2 -2
- package/modules/characters/astar.js +47 -28
- package/modules/characters/character.contract.js +21 -0
- package/modules/characters/contract.js +17 -3
- package/modules/characters/index.js +94 -34
- package/modules/characters/moveHelpers.js +80 -15
- package/modules/characters/mover.contract.js +14 -0
- package/modules/characters/movers/common.js +6 -4
- package/modules/characters/movers/rapier.js +12 -5
- package/modules/characters/movers/simple.js +25 -12
- package/modules/characters/movers/support.js +18 -7
- package/modules/characters/npcAvoid.js +15 -12
- package/modules/characters/npcSim.js +75 -25
- package/modules/characters/npcView.js +13 -6
- package/modules/characters/pathAsync.js +74 -24
- package/modules/characters/pathJob.js +38 -21
- package/modules/characters/player.js +59 -47
- package/modules/characters/seat.js +56 -0
- package/modules/characters/vehicle.contract.js +8 -5
- package/modules/characters/walkTo.js +31 -18
- package/modules/collision/Collision.js +44 -26
- package/modules/collision/contract.js +2 -2
- package/modules/collision/grid.js +6 -1
- package/modules/content/explain.js +1 -1
- package/modules/content/fields.js +3 -3
- package/modules/content/ids.js +3 -1
- package/modules/content/index.js +83 -27
- package/modules/content/loader.js +110 -130
- package/modules/content/markers.js +1 -1
- package/modules/content/models.js +48 -14
- package/modules/content/packs.js +2 -1
- package/modules/content/places.js +5 -4
- package/modules/content/props.js +8 -6
- package/modules/content/rules.js +29 -47
- package/modules/content/templates.js +66 -35
- package/modules/content/words.js +19 -6
- package/modules/debug/DebugPanel.js +4 -2
- package/modules/flow/contract.js +1 -0
- package/modules/flow/index.js +24 -14
- package/modules/gameplay/Container.js +5 -2
- package/modules/gameplay/Containers.js +9 -1
- package/modules/gameplay/Dialogue.js +82 -25
- package/modules/gameplay/Interactions.js +61 -32
- package/modules/gameplay/Inventory.js +56 -13
- package/modules/gameplay/Quests.js +133 -24
- package/modules/gameplay/boxOps.js +7 -0
- package/modules/gameplay/dialogueBubbles.js +14 -9
- package/modules/gameplay/inventoryOps.js +11 -7
- package/modules/gameplay/pickups.js +43 -16
- package/modules/gameplay/questLog.js +4 -2
- package/modules/gameplay/questSave.js +6 -1
- package/modules/gameplay/quests.contract.js +1 -1
- package/modules/grid/Grid.js +1 -1
- package/modules/grid/Layer.js +8 -4
- package/modules/grid/index.js +21 -15
- package/modules/grid/ops.js +43 -46
- package/modules/grid/tiles.js +1 -1
- package/modules/hlod/index.js +6 -3
- package/modules/hud/index.js +6 -4
- package/modules/hud/parts.js +4 -4
- package/modules/level/contract.js +2 -2
- package/modules/level/heightfield.js +17 -21
- package/modules/level/index.js +83 -26
- package/modules/level/load.js +165 -48
- package/modules/level/nodes.js +34 -16
- package/modules/lights/index.js +6 -3
- package/modules/lights/sources.js +3 -1
- package/modules/music/Music.js +4 -2
- package/modules/nav/contract.js +7 -5
- package/modules/nav/index.js +174 -44
- package/modules/nav/navPath.js +45 -10
- package/modules/net/index.js +1 -1
- package/modules/particles/Particles.js +85 -22
- package/modules/particles/effect.js +80 -28
- package/modules/particles/shaders.js +17 -0
- package/modules/photo/Photo.js +12 -10
- package/modules/rigid/RigidBodies.js +200 -57
- package/modules/rigid/Vehicles.js +15 -5
- package/modules/rigid/collider3d.contract.js +26 -0
- package/modules/rigid/ragdoll.js +55 -44
- package/modules/rigid/ragdollBones.js +83 -33
- package/modules/rigid/refresh.js +10 -0
- package/modules/rigid/sync.js +46 -15
- package/modules/settings/Settings.js +84 -37
- package/modules/settings/apply.js +15 -8
- package/modules/settings/sections.js +7 -4
- package/modules/settings/strings.js +2 -2
- package/modules/sky/skyModule.js +3 -1
- package/modules/swarm/Swarm.js +16 -6
- package/modules/terrain/ChunkManager.js +10 -16
- package/modules/terrain/index.js +17 -11
- package/modules/terrain/terrainEdit.js +13 -2
- package/modules/terrain/terrainGen.js +5 -3
- package/modules/terrain/terrainShape.js +1 -1
- package/modules/timeline/Timeline.js +58 -26
- package/modules/timeline/Tween.js +19 -13
- package/modules/timeline/shots.js +19 -10
- package/modules/triggers/index.js +87 -20
- package/modules/vegetation/Vegetation.js +4 -3
- package/modules/vegetation/draw.js +16 -0
- package/modules/vegetation/groundChunks.js +10 -7
- package/modules/vegetation/index.js +30 -7
- package/modules/water/Water.js +6 -2
- package/modules/weather/Weather.js +16 -15
- package/modules/weather/weatherDraw.js +7 -6
- package/modules/world/World.js +20 -7
- package/modules/world/explain.js +1 -1
- package/modules/world/index.js +13 -6
- package/modules/world/persist.js +23 -8
- package/modules/world/pos.js +4 -4
- package/modules/world/records.js +13 -7
- package/modules/world/sim.js +74 -23
- package/modules/world/simFar.js +2 -2
- package/modules/world/state.js +31 -6
- package/modules/world/thingSource.js +16 -3
- package/modules/world/views.js +19 -8
- package/package.json +7 -1
- package/render/PostFX.js +47 -29
- package/render/backend.js +5 -1
- package/render/fx/particles.tsl.js +8 -6
- package/render/fx/postWebGPU.tsl.js +3 -3
- package/render/layers.js +1 -1
- package/render/lightmap.js +23 -3
- package/render/occlusion.js +43 -12
- package/render/patches.js +2 -2
- package/render/postWebGL.js +4 -3
- package/render/probes.js +25 -0
- package/render/shadows.js +2 -2
- package/types/core.d.ts +142 -55
- package/types/gameplay.d.ts +92 -40
- package/types/generated/core/base/I18n.d.ts +2 -2
- package/types/generated/core/input/Input.d.ts +16 -2
- package/types/generated/core/input/inputSeat.d.ts +26 -0
- package/types/generated/core/inspect/DebugOverrides.d.ts +15 -1
- package/types/generated/core/ops/Ops.d.ts +2 -1
- package/types/generated/core/ops/control.d.ts +12 -2
- package/types/generated/core/saves/Saves.d.ts +26 -6
- package/types/generated/core/saves/session.d.ts +1 -1
- package/types/generated/core/scene/Views.d.ts +1 -1
- package/types/generated/core/stream/Stream.d.ts +6 -4
- package/types/generated/modules/grid/Grid.d.ts +1 -0
- package/types/generated/modules/particles/Particles.d.ts +4 -3
- package/types/generated/modules/timeline/Timeline.d.ts +5 -4
- package/types/generated/modules/weather/Weather.d.ts +1 -7
- package/types/generated/modules/world/World.d.ts +6 -4
- package/types/generated/render/PostFX.d.ts +6 -14
- package/types/nav.d.ts +36 -4
- package/types/physics.d.ts +55 -7
- package/types/pixel.d.ts +75 -0
- package/types/world.d.ts +14 -8
- package/ui/Parts.js +9 -2
- package/ui/theme.js +2 -2
- package/core/scene/engineCamera.js +0 -32
- package/modules/camera/projection.js +0 -21
package/docs/recipes/15-perf.md
CHANGED
|
@@ -43,7 +43,7 @@ const engine = createEngine({ canvas, budget: { drawCalls: 250, fps: 55, low1: 3
|
|
|
43
43
|
const r = engine.budget.report(); // { ok, over: [{ category, value, limit, top }] }; going over also prints one console hint
|
|
44
44
|
```
|
|
45
45
|
`top` lists the biggest draw-call users grouped by an object's `userData.budgetTag`. Tag your own things to see who it is:
|
|
46
|
-
```js
|
|
46
|
+
```js fragment
|
|
47
47
|
house.userData.budgetTag = 'houses'; // children inherit the parent's tag; untagged ones count as 'other'
|
|
48
48
|
engine.budget.byTag(); // [{ tag, drawCalls, triangles }...], largest first
|
|
49
49
|
engine.budget.metric('fishCount', () => fish.length, { limit: 50 }); // a module's own category
|
|
@@ -89,7 +89,7 @@ Four tools lower the cost of distant things, and each owns a different case. Pic
|
|
|
89
89
|
| A static level seen from far off | `engine.hlod` | Draw calls, by merging per cell | Same triangles unless a node `xxx_LOD1` exists |
|
|
90
90
|
| Plants by the thousand | `engine.vegetation` with `lodGeometry` | Both, per chunk ring | Plants only |
|
|
91
91
|
|
|
92
|
-
```js
|
|
92
|
+
```js fragment
|
|
93
93
|
// 1. once: writes public/optimized/tower.lod1.glb, .lod2.glb and lists them in assets.optimized.js
|
|
94
94
|
// threedog assets optimize --lod (--lod-shares 0.5,0.2 sets the triangle share of each level)
|
|
95
95
|
// 2. one line in the game; without it no level is ever downloaded
|
|
@@ -120,8 +120,8 @@ tower.levels[1].object; // a plain THREE.LOD: read, replace, tower.addLevel(..
|
|
|
120
120
|
refresh). The first 3 s after ready and frames that compile shaders are not judged, and a display or power mode locked at 30 Hz is not overload. The first
|
|
121
121
|
time it lowers, dev builds warn once: `render scale X -> Y because frames cost N ms ...; turn off with adaptiveResolution: false`. It is the only thing
|
|
122
122
|
lowered automatically (shadows and post are never traded first). `engine.setPixelRatio(p)` sets the top it climbs back to, so a ratio the game chose stays; a direct
|
|
123
|
-
`renderer.setPixelRatio` stops it altogether.
|
|
124
|
-
- `describe().render.scale`: `{ current, devicePixelRatio, upscaled, autoLowered, adaptive, floor, max }`. `upscaled: true` means current < devicePixelRatio, the picture
|
|
123
|
+
`renderer.setPixelRatio` stops it altogether, and so does `pixelSize` (recipe 62 section 4b).
|
|
124
|
+
- `describe().render.scale`: `{ current, devicePixelRatio, upscaled, pixelSize, autoLowered, adaptive, floor, max }`. `upscaled: true` means current < devicePixelRatio, the picture
|
|
125
125
|
is softer than the screen: if that looks wrong in a screenshot, check this before the style. Fixed quality: `pixelRatio: n` plus `adaptiveResolution: false`.
|
|
126
126
|
|
|
127
127
|
## 5. Verify (once before and once after, under the same conditions)
|
|
@@ -31,7 +31,7 @@ Every command and its options are in `../COMMANDS.md`. What each does to the gam
|
|
|
31
31
|
- `op shop.buy shop=trader item=medkit n=2` runs as source `bridge`. 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.
|
|
32
32
|
- `ops` lists every offer checked with `can`; `inspect [id | x,z]` adds what is around, with reasons (recipes/23-ops.md section 8); `explain op ...` / `explain quest ...` says why one cannot run or where a quest is stuck (`--full` adds the last attempt and events around it).
|
|
33
33
|
- `state time=18:30 weather=rain pos=40,-20` sets the scene like URL parameters (`engine.applyState`). A weather name must be in the game's table (`describe weather`; `weather({ types: presets.weather.temperate })`, which `--open-world` games start with): what could not be applied fails with the reason and exit 1.
|
|
34
|
-
- `js "engine.calendar.timeOfDay"
|
|
34
|
+
- `js "engine.calendar.timeOfDay"`: `engine` is available directly and `await` works inside; multi-line statements need their own `return` (`js "const p = engine.player.position; return p.x + p.z"`). Long scripts: `js --file script.js`.
|
|
35
35
|
- `scenario barter` runs `tests/scenarios/barter.json` (recipes/23-ops.md section 7), prints failed checks and leaves the loop halted.
|
|
36
36
|
|
|
37
37
|
## 2. Notes
|
|
@@ -71,11 +71,13 @@ threedog step 2 # let things happen
|
|
|
71
71
|
threedog js "engine.player.position.x > 1" # state assertion: read the ✓ true / false
|
|
72
72
|
threedog snap after-walk # only now look at pixels
|
|
73
73
|
```
|
|
74
|
-
The same steps as a file: `tests/scenarios/<name>.json` with `{ "press": … }`, `{ "step": … }`, `{ "expect": { path: value } }` (section 9; no `hold` there).
|
|
74
|
+
The same steps as a file: `tests/scenarios/<name>.json` with `{ "press": … }`, `{ "step": … }`, `{ "until": …, "within": s }`, `{ "expect": { path: value } }` (section 9; no `hold` there).
|
|
75
75
|
- **State checks** (`op`, `expect`, `describe`, `js`): fast and exact, but they skip input. They prove rules, not that the player can reach them.
|
|
76
76
|
- **Simulated-input checks** (`press`, `hold`, `engine.input.simulate`): bridge key events through the game's input path, never a physical keyboard/mouse. `verify` prints which layer each check ran on, what it did **not** prove (pointer lock and mouse look, real GPU/visuals, real FPS) and coverage (ops run vs defined; modules tested, indirect or untested; uses `engine.catalog()`); `scenario` prints the same coverage, and `--json` has the full lists.
|
|
77
77
|
- **Visual checks** (`snap`, `shot`): the only ones that see the picture (exposure, color, UI overlap). Slowest; take them last.
|
|
78
78
|
|
|
79
|
+
**Script the failures, not only the win.** A run that only wins says nothing about the routes a player takes after a mistake. Every end state gets a scenario: lose, die and respawn, retry, reload mid-run (`threedog reload` between bridge commands; a scenario file has no reload step). After each run, read `ops never run` in the `verify` report: each op there is a rule no script reached. Then check what the player stands in after the failure: a respawn point the level has since closed off, a hit that lands the step after a blow that should have ended the contact, a timer or lock left over from the last attempt.
|
|
80
|
+
|
|
79
81
|
Playing a game through from a script, the five things that cost the most time:
|
|
80
82
|
- **Start clean.** Enter on a title picks Continue when a save exists, so a rerun by keys plays the last autosave. `state fresh=1` deletes the saves and
|
|
81
83
|
goes back to the title, `play=1` starts the run; `?fresh&play` does the same in a URL. `session.newGame()` alone leaves the title open.
|
|
@@ -89,7 +91,7 @@ Playing a game through from a script, the five things that cost the most time:
|
|
|
89
91
|
## 3. Windows / PowerShell notes
|
|
90
92
|
- **Quote commas**: PowerShell splits `pos=1,-8` into two arguments and the coordinates become NaN. Write `threedog state "pos=1,-8"` (the bridge
|
|
91
93
|
reports an error and shows this tip when pos is not two numbers).
|
|
92
|
-
- Wrap the whole js
|
|
94
|
+
- Wrap the whole `js` expression in **double quotes** and use single quotes for strings inside: `threedog js "engine.vars.counter('score')"`.
|
|
93
95
|
PowerShell expands `$variables` inside double quotes; to pass `$` literally wrap the whole thing in single quotes.
|
|
94
96
|
- **Write a command on a single line**: a multi-line here-string passed to a native command often silently returns nothing in PowerShell. Put several
|
|
95
97
|
statements on one line separated by semicolons, or write them to a file and use `threedog js --file script.js` (no quoting or newline worries).
|
|
@@ -101,7 +103,7 @@ The bin called directly is the fastest route (COMMANDS.md, first lines); `threed
|
|
|
101
103
|
|
|
102
104
|
- `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:
|
|
103
105
|
|
|
104
|
-
```js
|
|
106
|
+
```js fragment
|
|
105
107
|
step(2);
|
|
106
108
|
const before = engine.time.tick;
|
|
107
109
|
step(1);
|
|
@@ -159,9 +161,8 @@ combination so tests and scenarios reuse it.
|
|
|
159
161
|
|
|
160
162
|
## 10. MCP server: Claude Code, Cursor and other MCP clients
|
|
161
163
|
`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`, `picture_palette`, `picture_compare`, `scenario`, `verify`, `reload`, `resume`, and the static `how`, `check`, `art_list` and `lib_list
|
|
163
|
-
|
|
164
|
-
command line (every default answer fits in about 4 KB, `tests/tool-output-sizes.mjs` guards it; a `data` payload over 3 KB keeps its small fields and names `threedog <cmd> --json` for the rest); `snap` also returns the PNG as an image, 480 px wide by default (`size` for more; the full file is saved). `picture_palette` and `picture_compare` need no game (recipe 35). 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)
|
|
164
|
+
`op`, `catalog`, `inspect`, `scene`, `pick`, `thing`, `explain`, `errors`, `loading`, `snap`, `snap_describe`, `picture_palette`, `picture_compare`, `scenario`, `verify`, `reload`, `resume`, and the static `how`, `check`, `art_list` and `lib_list`) and returns the same text as the
|
|
165
|
+
command line (every default answer fits in about 4 KB; a `data` payload over 3 KB keeps its small fields and names `threedog <cmd> --json` for the rest); `snap` also returns the PNG as an image, 480 px wide by default (`size` for more; the full file is saved). `picture_palette` and `picture_compare` need no game (recipe 35). 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
166
|
(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
|
|
166
167
|
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.
|
|
167
168
|
|
|
@@ -182,7 +183,7 @@ The `js` tool (arbitrary code in the page) is off by default; `threedog mcp --al
|
|
|
182
183
|
Tools: MCP, or `node node_modules/@threedog/tools/bin/threedog.mjs <cmd>` (`COMMANDS.md`). Errors: `.threedog/errors.log`, **read first when something breaks**.
|
|
183
184
|
- Not sure the engine has X -> `threedog how "<task>"`, `threedog catalog [id]`.
|
|
184
185
|
- An action failed -> its `code`, `facts`, `nextActions`.
|
|
185
|
-
- What is this object, why can't I click it -> `thing
|
|
186
|
+
- What is this object, why can't I click it -> `explain({ thing: id })`.
|
|
186
187
|
- Stuck, or a value is not what you set -> `describe().holds` / `.shared` / `.control`.
|
|
187
188
|
- What caused this -> `events.trace(name)`, `traceFocus(id)`.
|
|
188
189
|
- Placeholders (gray picture, capsule, boxes) -> the picture is not made yet: `picture/` (recipes 62, 09), code models (05), tuning (35).
|
package/docs/recipes/18-world.md
CHANGED
|
@@ -13,7 +13,7 @@ player planted, the player itself) is one **plain data record** in `engine.world
|
|
|
13
13
|
just how it looks when the camera is near; unloading a chunk / level tears down only the model and never loses the data; a save stores only data; far
|
|
14
14
|
away, with no model, the data is still simulated.
|
|
15
15
|
A decorative rock is a props entry in `content/props.js` (an authored record, saved only if play moves or removes it); `engine.add(mesh)` is for
|
|
16
|
-
transient effects. Everything placed in a level comes from content, so a new game equals the content
|
|
16
|
+
transient effects. Everything placed in a level comes from content, so a new game equals the content.
|
|
17
17
|
Many copies of one interactive object (chests, beds, campfires) with the same model, interaction and container: define it once as a content template
|
|
18
18
|
and place instances (recipe 30-templates.md); the template is the shared read-only definition, the record holds only the instance state.
|
|
19
19
|
|
|
@@ -49,8 +49,8 @@ W.simulate('zombie', {
|
|
|
49
49
|
- Both ways are saved (a save compares contents, it does not rely on events). `move` emits no event: if the picture needs to follow position, compare in
|
|
50
50
|
`update`.
|
|
51
51
|
- Don't hold a rec object for long: loading a save replaces it with a new object. Keep the id and call `W.get(id)` when you need it.
|
|
52
|
-
- Position forms: Vector3 / object / `[x, y, z]` / `{ x, z }` (a missing y keeps the old one).
|
|
53
|
-
throws immediately.
|
|
52
|
+
- Position forms: Vector3 / object / `[x, y, z]` / `{ x, z }` (a missing y keeps the old one). NaN or an array with only two numbers
|
|
53
|
+
throws immediately, in release too, and writes nothing.
|
|
54
54
|
|
|
55
55
|
## 3. Example: a crop grows on the calendar, press E to harvest when ripe
|
|
56
56
|
The key idea: **don't accumulate every step; record the time it was planted, `plantedAt = clock.now`, and growth = now - planted time**. Whether the
|
|
@@ -164,8 +164,12 @@ function wander(rec, dt) {
|
|
|
164
164
|
on the camera. For a top-down strategy game centered on a base, set `W.anchor = baseObject`; set it back to `null` to restore the default.
|
|
165
165
|
- **The player is a record too**: the id and kind added by `createPlayer` are both `'player'`; position, facing, motion state (vx, vz, vy, facing,
|
|
166
166
|
grounded...) and which vehicle it is on (vehicle) live in the record and are saved, and it is never torn down by walking away. Only the character's
|
|
167
|
-
mover changes the position and then writes it back to the record
|
|
168
|
-
|
|
167
|
+
mover changes the position and then writes it back to the record. `world.move`, `world.set` and `thing.set` on a live character (the player, an NPC with
|
|
168
|
+
a model) are its `placeAt`: it goes there, standing on what is there, and the record says where it stands. A seated rider gets out to go there; undo of that `thing.set`
|
|
169
|
+
seats it again, and answers `ownerRefuses` with the reason if the seat is gone or taken or it sits elsewhere. A ragdoll goes there whole and at rest, still limp. `rot` and `scale` on its record (`world.set`, `thing.set` `rotation` / `scale`) go to the character too: `rot` is its
|
|
170
|
+
facing, kept in its motion (written with no model, it waits for the model), `scale` sizes `root` and stays on the record, so a rebuild and a load keep it. It
|
|
171
|
+
is the picture: radius and height stay. A tilt about x or z, or a turn while seated (the seat turns its rider), is refused by name. On load the player is
|
|
172
|
+
put back from the record.
|
|
169
173
|
- **Models are built around the stream sources** (`33-stream-sources.md`): by default the player (`engine.stream.player`, follows
|
|
170
174
|
`world.anchor`) and the camera
|
|
171
175
|
focus (`engine.stream.camera`). Built inside the radius of any source, torn down beyond 1.25x of all of them, with an error of at most 8 meters; at
|
|
@@ -173,11 +177,15 @@ function wander(rec, dt) {
|
|
|
173
177
|
never touches its record.
|
|
174
178
|
- `positionFrom: 'view'` (the model moves itself, for example an NPC driven by the character mover): near simulation builds the model on the spot and
|
|
175
179
|
copies the model position back to the data at the end of every fixed step; when not simulated near, the data decides and the model follows the data.
|
|
180
|
+
A write to the record (`world.move`, `world.set`, `thing.set`, or `rec.position` itself, seen at the end of the step) moves the model, and a rigid body on
|
|
181
|
+
that model goes along at rest, however the body was made. `rot` and `scale` on a template with a `body` build a new body where the record stands; with your
|
|
182
|
+
own `present` they are your fields, so read them there.
|
|
176
183
|
A model moved by a physics body saves its position, not the physics solver state: after a load, resting bodies settle again and can differ by ~0.01
|
|
177
184
|
mm, so replays that must match exactly should not depend on physics props.
|
|
178
185
|
- Radius: present / simulate each take their own `radius` (meters or a function); without it they follow `world.radius` (default 60).
|
|
179
186
|
|
|
180
187
|
## 7. Time and ordering rules (nothing lost, nothing doubled, loading a save is bit-identical)
|
|
188
|
+
- A kind on a channel owes what it lived through: a far `dt` that spans a slowdown is the sum of each stretch at its own speed, and it survives a save.
|
|
181
189
|
- The dt of both near and far is accumulated fixed-step seconds (real seconds: not multiplied by `clock.rate`; with `simulate(kind, { channel: 'enemies' })` both are multiplied by that time channel's speed). For one record, whether near, far, or
|
|
182
190
|
alternating, the dts add up to the elapsed time: on the step going from far to near, `far` first catches up the owed time, then `near` runs.
|
|
183
191
|
- **Kinds that only define far** (crops) are not split into near and far; even when you stand next to them they advance at the far pace. **Kinds that
|
|
@@ -14,7 +14,8 @@ import { terrainPreset } from '@threedog/terrain-noise';
|
|
|
14
14
|
|
|
15
15
|
const engine = createEngine({ canvas: document.getElementById('view'), lights: false, saveKey: 'range' });
|
|
16
16
|
engine.use(openWorld({ seed: 7, terrain: terrainPreset(), camera: 'firstPerson' }), hud()); // camera (required): 'follow' | 'firstPerson' | 'rts' | 'fixed', or pass a module like firstPersonCamera({ height: 1.7 })
|
|
17
|
-
|
|
17
|
+
engine.use(createPicture());
|
|
18
|
+
const { picture } = engine;
|
|
18
19
|
engine.input.action('shoot', { label: 'Shoot', keys: ['Mouse0', 'KeyF'] }); // the left mouse button is a key too (Mouse0 / Mouse1 / Mouse2); either it or KeyF works
|
|
19
20
|
engine.characters.createPlayer({ ...presets.player.aim, spawn: engine.characters.findSpawn([0, 0, 0], { minH: 3, maxH: 14 }) });
|
|
20
21
|
Object.assign(window, { engine, picture });
|
|
@@ -69,7 +70,7 @@ engine.onFixed(() => { // firing is gameplay:
|
|
|
69
70
|
`hud.counter` again to sync the display.
|
|
70
71
|
|
|
71
72
|
## 3. Testing
|
|
72
|
-
```js
|
|
73
|
+
```js fragment
|
|
73
74
|
engine.haltLoop();
|
|
74
75
|
engine.input.simulate('shoot'); engine.step(0.1); engine.input.simulate('shoot', false); // simulate a click on the action bound to Mouse0 (use your action name)
|
|
75
76
|
// To hit a specific target: first aim the camera at it with engine.cameraRig.lookAt(target), then click
|
|
@@ -13,6 +13,7 @@ ops, used from content as `{ op: ['noun.verb', { args }] }` / `{ can: [...] }` (
|
|
|
13
13
|
- Conditions are used in: quest step `done`, dialogue choice `if`, line variant `if`. Several entries in one object = all must hold; an array = every
|
|
14
14
|
item must hold.
|
|
15
15
|
- Effects are used in: dialogue `do`, quest `reward`, trigger zone `onEnter / onExit`. Several entries in one object, or an array, run in order.
|
|
16
|
+
- Every word runs even when one fails. `content.run` answers `{ ok: true }` or a failure with `facts.failed` (`{ word, code, facts }`); an op returning it fails with it. Dialogue `do` and triggers: listen to `content:failed`.
|
|
16
17
|
- Content validation (content-check inside `threedog check` / `threedog map`) checks the word names and how the values are written.
|
|
17
18
|
|
|
18
19
|
### A game's own data kinds (enemies, recipes, loot tables, waves…)
|
|
@@ -53,9 +54,18 @@ imports itself, or `engine.i18n.add()` when it is text the UI fetches with `engi
|
|
|
53
54
|
against its table (a misspelled `scael` names `scale`), and `engine.content.fields(name)` returns the same table for tools such as an editor panel.
|
|
54
55
|
|
|
55
56
|
## 1b. Content packs: several data sets in one load
|
|
57
|
+
A pack with a `level` commits when its file is here. If a newer `level.load`, save load or unload comes first, the newest level stands and only the pack's `level` gives way: the rest goes in once that load has ended, on the level that won. A place only the pack's level had fails with `content-place`, as any unknown place does, and the pack goes back whole.
|
|
58
|
+
|
|
59
|
+
`content.load` answers for its own load. Bad data throws on the line. The Promise it returns resolves once the pack committed, and rejects when it failed, after the old level and registrations are back; saves and loads asked meanwhile wait for that. If the old level could not come back, `err.notRestored` lists why. A load nobody awaits is reported all the same.
|
|
60
|
+
|
|
61
|
+
```js fragment
|
|
62
|
+
try { await engine.content.load(dlc); }
|
|
63
|
+
catch (err) { showError(err.notRestored ? 'reload the game' : 'this pack is broken'); }
|
|
64
|
+
```
|
|
65
|
+
|
|
56
66
|
A content pack is the same object `content/index.js` exports (`{ items, templates, props, quests, ... }`, optional `name` for messages), shipped as a
|
|
57
67
|
folder or an npm package: data only, assets by name (never a path or a function; `npm run check` and a dev warning report both). Load several together:
|
|
58
|
-
```js
|
|
68
|
+
```js fragment
|
|
59
69
|
import base from './content/index.js';
|
|
60
70
|
import forest from 'forest-content'; // its props name templates from base and models from the forest asset pack
|
|
61
71
|
import packs from './assets.js'; // export default [forestAssets, ...]: the asset packs ({ name, base, models, textures, sounds, fonts })
|
|
@@ -112,7 +122,7 @@ engine.interactions.pickMode = 'aim'; // switch at runtime (enter
|
|
|
112
122
|
```
|
|
113
123
|
One object with two verbs = two interactions with different key actions; each key picks among its own action, and `engine.interactions.options` lists
|
|
114
124
|
one `{ action, id, label }` per key for a prompt that shows both:
|
|
115
|
-
```js
|
|
125
|
+
```js fragment
|
|
116
126
|
engine.input.action('take', { label: 'Take', keys: ['KeyF'] });
|
|
117
127
|
engine.interactions.add(thing, { label: 'Inspect', onUse: inspect }); // E
|
|
118
128
|
engine.interactions.add(thing, { label: 'Take', action: 'take', enabled: () => ready, onUse: take }); // F
|
|
@@ -123,7 +133,7 @@ when the key is released, the actor leaves the radius, `enabled()` turns false o
|
|
|
123
133
|
`approach: true` walks the player there first (`walkTo`, stops 1.2 m away) and uses it on arrival; with `radius: Infinity` it is usable from anywhere
|
|
124
134
|
(point-and-click, "talk to the clerk across the shop"). The op `interaction.use` is the completed use in both cases (tests and the dev bridge
|
|
125
135
|
skip the hold; an approach returns `{ approaching }`, a promise of onUse's result).
|
|
126
|
-
```js
|
|
136
|
+
```js fragment
|
|
127
137
|
engine.interactions.add(well, { label: 'Pump', hold: 1.5, onUse: fill });
|
|
128
138
|
engine.interactions.add(shell, { id: 'shell-1', label: 'Pick up', once: true, counter: 'shells' }); // mesh gone after E, counted: recipe 03 "Pick and count"
|
|
129
139
|
engine.interactions.add(clerk, { label: 'Talk', radius: Infinity, approach: true, onUse: talk });
|
|
@@ -136,7 +146,7 @@ The actor is handed down, never assumed: `label / enabled / onUse` get `(object,
|
|
|
136
146
|
peer, an NPC); trigger callbacks get `(t, who, id)` and the events carry `id` (`who` may list actor ids: `who: () => [e.actor, ...peerIds]`); content
|
|
137
147
|
`has / lacks / give / take` use the bag of the running op's actor (else `engine.actor`), and `engine.content.run(effect, { actor })` /
|
|
138
148
|
`content.test(cond, { actor })` name one explicitly; trigger `onEnter / onExit` effects act for whoever crossed the zone.
|
|
139
|
-
```js
|
|
149
|
+
```js fragment
|
|
140
150
|
engine.interactions.add(door, { label: (o, { actor }) => keyOf(actor) ? 'Open' : 'Locked', onUse: (o, { actor }) => engine.ops.run('door.open', { id: o.name }, { actor }) });
|
|
141
151
|
engine.triggers.add({ position: gate, who: () => [engine.actor, ...guards], onEnter: (t, who, id) => engine.ops.run('gate.alarm', { by: id }) });
|
|
142
152
|
```
|
|
@@ -150,6 +160,8 @@ if (engine.saves.check('auto') === null) await engine.session.load('auto'); //
|
|
|
150
160
|
- `engine.session.load(slot)` and `engine.session.newGame()` both return `Promise<boolean>`: always `await`. `session.load` starts from the new-game
|
|
151
161
|
state and puts the save on top, so a part the save lacks (a module added in a later version) starts fresh instead of keeping the current run's
|
|
152
162
|
state. `engine.saves.load(slot)` is a quick load onto the running playthrough; never build Continue from it.
|
|
163
|
+
- A running cutscene and an open conversation are not saved: any load ends them without their remaining steps. Save at a point the game can continue from: a save taken inside a
|
|
164
|
+
cutscene whose last step sets the flag a quest waits for comes back without that flag.
|
|
153
165
|
- Loading restores the player, the view (the camera rig's yaw and pitch: a first-person game needs no save code for it), world data (world changes and deletions), inventory, quests, clock and random state; initial data in content files
|
|
154
166
|
(`initial`) is the same whether it is loaded before or after the save, so ignore the order.
|
|
155
167
|
- A load rebuilds the props and other world records: an Object3D your code kept from before (a door mesh, a lamp) is gone afterwards. Keep the
|
|
@@ -176,6 +188,14 @@ const addLap = time => { const r = records(); r.laps.push(time); localStorage.se
|
|
|
176
188
|
- A part whose `save()` throws makes the whole save fail (`false`, the slot keeps its previous save); a part whose `load()` throws rolls the game back
|
|
177
189
|
to how it was before the load (`false`). So does a listener of an event the load emits (`world:load`) or a module's `afterLoad` that throws. Both go
|
|
178
190
|
through the error tiers (`engine.error` in dev, code `save-part-threw` / `save-load-threw`).
|
|
191
|
+
- One replacement at a time: `saves.apply`, `saves.load` and `session.newGame` / `load` / `quit` wait their turn in the order asked, so the end state is
|
|
192
|
+
always one whole save, and a load that fails rolls back to the whole state before it. Idle, a save with only synchronous parts applies at once. While
|
|
193
|
+
a replacement runs ops return `'loading'`.
|
|
194
|
+
- A `load()` or `afterLoad` may change level or load a pack, before or after an await. It is handed the turn of its replacement; pass it on, and the call goes at once:
|
|
195
|
+
`async load(d, turn) { await fetchRoute(d); await engine.level.load(d.level, { turn }); }`. Without the turn the call counts as an outside request and waits for this load to end, so awaiting
|
|
196
|
+
it would wait for itself (dev says so after 3 s, `save-nested`). A new `saves.apply` / `load` / `save` or `session.*` starts after the running one: ask for it without awaiting it, or from a
|
|
197
|
+
`save:loaded` or `session:start` listener.
|
|
198
|
+
- A part registered while a load runs gets its data right after that load, whole, unless a newer load replaced the state first; idle it gets it before `register` returns.
|
|
179
199
|
- A save edited by hand or damaged: a `null` part makes it `'corrupt'` (a `save()` returning `null` is simply left out); a world record whose
|
|
180
200
|
position is not three finite numbers is refused and rolled back (`save-bad-record`, no gameplay error); a bad number of the clock, time
|
|
181
201
|
channels, random state or item counts is clamped or dropped with one `save-value` warning per part, and the rest loads.
|
|
@@ -194,8 +214,8 @@ A save is one envelope; `engine.saves.collect()` returns it and `export` / `expo
|
|
|
194
214
|
parts: { world: {...}, quests: {...}, clock: {...}, vars: {...} } } // each saves.register part's data, by key
|
|
195
215
|
```
|
|
196
216
|
- **Parts and versions**: each `engine.saves.register(key, { version, migrate, save, load })` owns one part. `load` takes one argument, the data: `load: data => …`, never `load(engine, data)`, the shape of a module hook (`npm run check` warns, rule R33). When `save()` changes shape, raise
|
|
197
|
-
`version` by 1 and add `migrate[oldVersion] = data => newData`; load runs the steps in order on a copy, so `load` only sees the current shape.
|
|
198
|
-
|
|
217
|
+
`version` by 1 and add `migrate[oldVersion] = data => newData`; load runs the steps in order on a copy, so `load` only sees the current shape.
|
|
218
|
+
This is how a game's own saved data migrates across its releases (there is no other system): keep one saved file per released game version, never edit it, and load each in a test with `engine.saves.apply(sample)` (the engine does the same for its own parts in `tests/specs/save-compat.mjs`).
|
|
199
219
|
- **Parts nobody owns are kept**: a part in the loaded save whose module is not installed in this run (a feature turned off for a version) is written
|
|
200
220
|
back unchanged on every save, and handed to the module if it registers later. Only a new game drops it.
|
|
201
221
|
- **Authored baseline + per-id diff**: everything placed in a level comes from content (props, template instances, pickups, NPCs, grid items in
|
|
@@ -50,7 +50,7 @@ engine.setCamera('follow', { distance: 8, pitch: 0.3 });
|
|
|
50
50
|
- **Shooting games**: bind first-person firing to a mouse-button action, see `19-shooting-picking.md`.
|
|
51
51
|
|
|
52
52
|
## 4. Over the shoulder, lock-on framing, mouse lock (follow camera)
|
|
53
|
-
```js
|
|
53
|
+
```js fragment
|
|
54
54
|
engine.use(followCamera({ distance: 3, shoulder: 0.7, pitch: 0.15, pointerLock: true })); // shooter / action-adventure view
|
|
55
55
|
engine.cameraRig.shoulder = -0.7; // switch shoulders at any time (plain property)
|
|
56
56
|
engine.cameraRig.frame(enemy.root); // lock-on: turn to "behind the player, looking at the enemy"; frame(null) lets go
|
|
@@ -94,7 +94,7 @@ engine.use(followCamera({ minPitch: -0.9, ground: 'shorten' })); // or the sam
|
|
|
94
94
|
|
|
95
95
|
## 4c. Chase camera behind a car
|
|
96
96
|
`addWheeled({ camera })` sets the follow camera's distance and height while seated, but the camera keeps its own yaw, so nothing swings the view behind the car. A racing view is a few lines of game code with `followCamera({ mouseLook: false })`:
|
|
97
|
-
```js
|
|
97
|
+
```js fragment
|
|
98
98
|
let yaw = null;
|
|
99
99
|
engine.onFrame(dt => {
|
|
100
100
|
const q = car.body.rotation(); // car: what addWheeled returned
|
|
@@ -109,7 +109,7 @@ engine.onFrame(dt => {
|
|
|
109
109
|
The engine has no default here: `createPlayer` needs `control` (a preset such as `presets.player.thirdPerson` gives keys relative to the camera, Shift
|
|
110
110
|
run, Space jump, turning toward where it walks and `cameraFollow: true`). Each piece below replaces one part and keeps the rest (world record, saving,
|
|
111
111
|
`describe().player`).
|
|
112
|
-
```js
|
|
112
|
+
```js fragment
|
|
113
113
|
import { pickTarget, switchTarget } from 'threedog';
|
|
114
114
|
|
|
115
115
|
// how the input steers the player: 'camera' (keys relative to the camera) | (player, input, dt) => ({ x, z, run? }) | null (stand still)
|
|
@@ -154,7 +154,7 @@ function steer(player, input, dt) { // called once per fixed
|
|
|
154
154
|
**Orthographic (isometric / 2.5D) with the built-in rigs.** `projection: 'orthographic'` plus `size` (world units of view height) on the fixed and follow cameras.
|
|
155
155
|
The default stays perspective. On resize the view height stays `size` and the width follows the aspect.
|
|
156
156
|
|
|
157
|
-
```js
|
|
157
|
+
```js fragment
|
|
158
158
|
// one fixed isometric shot (shorthand for a single shot named 'main')
|
|
159
159
|
engine.setCamera('fixed', { position: [14, 14, 14], lookAt: [0, 0, 0], projection: 'orthographic', size: 16 });
|
|
160
160
|
// per shot: shots: { hall: { position, lookAt, projection: 'orthographic', size: 12 }, yard: { position, lookAt } } // yard stays perspective
|
|
@@ -162,7 +162,7 @@ engine.setCamera('fixed', { position: [14, 14, 14], lookAt: [0, 0, 0], projectio
|
|
|
162
162
|
engine.setCamera('follow', { pitch: 0.6, yaw: 0.8, distance: 20, projection: 'orthographic', size: 14, mouseLook: false, ground: 'none' });
|
|
163
163
|
```
|
|
164
164
|
**A view that pans at a fixed angle** (isometric, tactics, city builders) is that follow camera, not a fixed shot. `mouseLook: false` stops the drag and the wheel from moving the view, and `ground: 'none'` stops hills from tilting it. It follows the player, or with no player any object the game moves:
|
|
165
|
-
```js
|
|
165
|
+
```js fragment
|
|
166
166
|
const view = new THREE.Object3D(); // the point the view is centered on
|
|
167
167
|
engine.cameraRig.follow(view); // again on 'session:start': a new playthrough follows the player or nothing
|
|
168
168
|
engine.onFrame(dt => { view.position.x += engine.input.axis.x * 12 * dt; view.position.z -= engine.input.axis.y * 12 * dt; });
|
|
@@ -171,8 +171,7 @@ engine.onFrame(dt => { view.position.x += engine.input.axis.x * 12 * dt; view.po
|
|
|
171
171
|
|
|
172
172
|
A `setCamera` before play (boot code, or with the title up) is the camera every playthrough starts from, the same as passing the options to the camera module. During play it is a switch: a new playthrough goes back.
|
|
173
173
|
|
|
174
|
-
- `engine.camera
|
|
175
|
-
is true, `camera.left/right/top/bottom` are set, and `camera.zoom` still zooms. `camera.fov` is ignored while it is on.
|
|
174
|
+
- The option is a short way to the real thing below: the rig puts a real `THREE.OrthographicCamera` in `engine.camera`, and the next perspective view brings the camera it replaced back. Pose, `near`, `far`, `zoom`, layers, the parent and anything hung on the camera go with the view. So read `engine.camera` where you use it, and do not keep a copy across a switch.
|
|
176
175
|
- 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.
|
|
177
176
|
- Limits: on the follow camera the mouse wheel changes `size` (clamped to the `minDistance`/`maxDistance` ratio of the starting `distance`).
|
|
178
177
|
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.
|
|
@@ -180,7 +179,7 @@ A `setCamera` before play (boot code, or with the title up) is the camera every
|
|
|
180
179
|
**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.
|
|
181
180
|
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.
|
|
182
181
|
|
|
183
|
-
```js
|
|
182
|
+
```js fragment
|
|
184
183
|
let t = 0;
|
|
185
184
|
const cam = engine.takeCamera('my-orbit', { focus: engine.player.position }); // focus (optional): where the world loads around
|
|
186
185
|
const frame = engine.onFrame(dt => {
|
|
@@ -189,26 +188,21 @@ const frame = engine.onFrame(dt => {
|
|
|
189
188
|
// done: frame.remove(); cam.remove(); // the rig resumes from its own state
|
|
190
189
|
```
|
|
191
190
|
|
|
192
|
-
To
|
|
191
|
+
To draw through your own three.js camera, assign it. A real `THREE.PerspectiveCamera` or `THREE.OrthographicCamera` is taken as it is, and any other class, a subclass too, is refused:
|
|
193
192
|
|
|
194
|
-
```js
|
|
195
|
-
const original = engine.camera
|
|
196
|
-
const ortho = new THREE.OrthographicCamera(-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
}
|
|
201
|
-
const cam = engine.takeCamera('my-ortho');
|
|
202
|
-
engine.camera = ortho; // the plain render path, cascaded shadows and modules read engine.camera live
|
|
203
|
-
ortho.position.set(10, 10, 10); ortho.lookAt(0, 0, 0); fit(); addEventListener('resize', fit);
|
|
204
|
-
// give it back: removeEventListener('resize', fit); engine.camera = original; cam.remove();
|
|
193
|
+
```js fragment
|
|
194
|
+
const original = engine.camera;
|
|
195
|
+
const ortho = new THREE.OrthographicCamera(-16, 16, 9, -9, 0.1, 500);
|
|
196
|
+
ortho.position.set(10, 10, 10); ortho.lookAt(0, 0, 0);
|
|
197
|
+
engine.camera = ortho; // rendering, post, picking, shadows, audio and the camera module go on with it
|
|
198
|
+
// give it back: engine.camera = original;
|
|
205
199
|
```
|
|
206
200
|
|
|
207
|
-
|
|
208
|
-
`projection: 'orthographic'`
|
|
201
|
+
The aspect follows the canvas, on assignment and on every resize: an orthographic camera keeps its height and its width follows. `engine.autoView.manual('aspect')` before assigning keeps your own frustum. The engine leaves `far` and `fov` of a real orthographic camera alone.
|
|
202
|
+
A camera module goes on placing the camera you assigned, and a camera you assign during a shot stays until the next view is asked for. `projection: 'orthographic', size` sets the height of a real orthographic camera; on a real perspective one the rig's own orthographic camera stands in until the next perspective view, which brings yours back. `pixelSnap` writes the height it needs. A chain taken with `engine.post.own()` is yours to point at the new camera, and a `pixelGrid` you made yourself keeps the camera you gave it.
|
|
209
203
|
|
|
210
204
|
**Side view (side-scroller).** `presets.player.sideScroller` moves the player along world X only (A / D, `z` stays) and turns it toward the move. Face the camera along -Z with `yaw: 0`, so +X is screen right (`yaw: Math.PI` looks from the far side and flips left and right), on `followCamera`:
|
|
211
|
-
```js
|
|
205
|
+
```js fragment
|
|
212
206
|
engine.use(followCamera({ projection: 'orthographic', size: 15, yaw: 0, pitch: 0, lockPitch: true, distance: 40, ground: 'none', mouseLook: false }));
|
|
213
207
|
```
|
|
214
208
|
|
|
@@ -30,13 +30,15 @@ Import it in `content/index.js` and put it in the exported object (`containers`)
|
|
|
30
30
|
|
|
31
31
|
## 3. Buy, sell / consign (two ops + dialogue choices)
|
|
32
32
|
Buying and selling are things the player decides to do, so they are ops (`recipes/23-ops.md`): define them once in `main.js`, and every caller
|
|
33
|
-
(dialogue choice, a shop window button, the dev bridge, a test) runs the same `can` / `run`.
|
|
34
|
-
|
|
33
|
+
(dialogue choice, a shop window button, the dev bridge, a test) runs the same `can` / `run`. A trade is one whole step, so both are `atomic: true` (recipe 23 section 12): `run` frees room
|
|
34
|
+
first, and when the other side cannot take its part it returns `{ ok: false, code }` and the engine puts the bag and the shelf back. **Buy** needs stock on the shelf and the money.
|
|
35
35
|
**Consign**: the player puts something on the shelf, and the shelf pays when it accepts it.
|
|
36
36
|
```js
|
|
37
37
|
// main.js (after engine.use(...inventory()...))
|
|
38
38
|
const price = (e, item) => e.inventory.item(item).price ?? 1;
|
|
39
|
+
const payout = (e, item) => Math.max(1, Math.floor(price(e, item) * 0.6)); // add and remove take 1 or more, never 0
|
|
39
40
|
engine.ops.define('shop.buy', {
|
|
41
|
+
atomic: true,
|
|
40
42
|
args: { shop: 'string', item: 'string' },
|
|
41
43
|
can(e, { shop, item }, ctx) {
|
|
42
44
|
if (!e.inventory.container(shop).has(item)) return 'soldOut';
|
|
@@ -44,23 +46,30 @@ engine.ops.define('shop.buy', {
|
|
|
44
46
|
return true;
|
|
45
47
|
},
|
|
46
48
|
run(e, { shop, item }, ctx) {
|
|
47
|
-
|
|
48
|
-
e.inventory.
|
|
49
|
-
return got;
|
|
49
|
+
e.inventory.container(ctx.actor).remove('gold', price(e, item)); // first: the last coins free their slot for the goods
|
|
50
|
+
return e.inventory.transfer(shop, ctx.actor, item, 1) || { ok: false, code: 'bagFull' };
|
|
50
51
|
},
|
|
51
|
-
reasons: { soldOut: 'Shelf is empty', noMoney: 'Not enough gold' },
|
|
52
|
+
reasons: { soldOut: 'Shelf is empty', noMoney: 'Not enough gold', bagFull: 'No room in the bag' },
|
|
52
53
|
});
|
|
53
54
|
engine.ops.define('shop.sell', {
|
|
55
|
+
atomic: true,
|
|
54
56
|
args: { shop: 'string', item: 'string' },
|
|
55
|
-
can
|
|
57
|
+
can(e, { shop, item }, ctx) {
|
|
58
|
+
if (!e.inventory.container(ctx.actor).has(item)) return 'notInBag';
|
|
59
|
+
return e.inventory.container(shop).room(item) > 0 || 'shelfFull';
|
|
60
|
+
},
|
|
56
61
|
run(e, { shop, item }, ctx) {
|
|
57
|
-
const
|
|
58
|
-
e.inventory.
|
|
59
|
-
return
|
|
62
|
+
const bag = e.inventory.container(ctx.actor), pay = payout(e, item);
|
|
63
|
+
e.inventory.transfer(ctx.actor, shop, item, 1); // first: the last piece frees its slot for the gold
|
|
64
|
+
if (bag.room('gold') < pay) return { ok: false, code: 'bagFull' };
|
|
65
|
+
bag.add('gold', pay, { silent: true });
|
|
66
|
+
return 1;
|
|
60
67
|
},
|
|
68
|
+
reasons: { notInBag: 'Nothing to sell', shelfFull: 'The shelf is full', bagFull: 'No room for the gold' },
|
|
61
69
|
});
|
|
62
70
|
```
|
|
63
|
-
In the dialogue, `if: { can: [...] }` shows a choice only when
|
|
71
|
+
In the dialogue, `if: { can: [...] }` shows a choice only when `can` passes, and `do: { op: [...] }` runs it. `bagFull` comes back from `run`
|
|
72
|
+
(`r.code`), not `can`: it is only known once the goods have moved:
|
|
64
73
|
```js
|
|
65
74
|
// content/dialogues.js
|
|
66
75
|
const buyKit = ['shop.buy', { shop: 'shop-trader', item: 'medkit' }];
|
|
@@ -83,7 +92,7 @@ export default {
|
|
|
83
92
|
```
|
|
84
93
|
- The shelf id (`'shop-trader'`: a market stall, a ship's store, a vending machine) is any string, and the shelf contents are saved. A "shop window" is your own UI drawn from `shelf.list()`; its
|
|
85
94
|
buttons call `engine.ops.run('shop.buy', { shop, item })` and grey out with `engine.ops.can(...)`.
|
|
86
|
-
- Prices live on the item (`price` in items.js above), read with `e.inventory.item('medkit').price`; an item without one costs 1 here.
|
|
95
|
+
- Prices live on the item (`price` in items.js above), read with `e.inventory.item('medkit').price`; an item without one costs 1 here. A price is a whole number of 1 or more.
|
|
87
96
|
- Items with their own data (a used sword with `durability`, recipe 03): pass the entry key as `item` (`'sword#3'`, from `shelf.list()[i].key`);
|
|
88
97
|
`transfer` moves exactly that piece with its data, and `e.inventory.container(shop).get(item)` reads the data for a price
|
|
89
98
|
(`def.price * data.durability / 100`).
|
package/docs/recipes/23-ops.md
CHANGED
|
@@ -14,6 +14,7 @@ in a module's `fixed` or `world.simulate`. Low-level functions such as `inventor
|
|
|
14
14
|
const PRICE = { bread: 5 };
|
|
15
15
|
engine.ops.define('shop.buy', {
|
|
16
16
|
desc: 'Buy from a shop shelf',
|
|
17
|
+
atomic: true, // a failed run puts everything back (section 12)
|
|
17
18
|
args: { shop: 'string', item: 'string', n: 'int?' }, // types: string number int bool position id any; ? = optional
|
|
18
19
|
can(e, { shop, item, n = 1 }, ctx) { // read-only: return true or a reason string
|
|
19
20
|
if (!e.inventory.container(shop).has(item, n)) return 'soldOut';
|
|
@@ -21,12 +22,12 @@ engine.ops.define('shop.buy', {
|
|
|
21
22
|
return true;
|
|
22
23
|
},
|
|
23
24
|
run(e, { shop, item, n = 1 }, ctx) { // runs only after can passed
|
|
24
|
-
|
|
25
|
-
e.inventory.
|
|
26
|
-
return
|
|
25
|
+
e.inventory.container(ctx.actor).remove('gold', PRICE[item] * n);
|
|
26
|
+
if (e.inventory.transfer(shop, ctx.actor, item, n) < n) return { ok: false, code: 'bagFull' };
|
|
27
|
+
return n; // plain data; becomes r.value
|
|
27
28
|
},
|
|
28
29
|
offers: (e, ctx) => [{ shop: 'shop-bakery', item: 'bread' }], // optional: arg sets possible now (ops list / dev bridge `ops`)
|
|
29
|
-
reasons: { soldOut: 'Shelf is empty', noMoney: 'Not enough gold' }, // optional developer notes
|
|
30
|
+
reasons: { soldOut: 'Shelf is empty', noMoney: 'Not enough gold', bagFull: 'No room in the bag' }, // optional developer notes
|
|
30
31
|
// optional: undo(e, args, value, ctx) reverses a finished run; engine.ops.undo('shop.buy', args, r.value) calls it ({ ok: false, code: 'noUndo', facts: { op } } without one)
|
|
31
32
|
});
|
|
32
33
|
|
|
@@ -37,7 +38,7 @@ const { ok } = engine.ops.can('shop.buy', { shop: 'shop-bakery', item: 'bread' }
|
|
|
37
38
|
Rules that keep ops replayable and network-ready:
|
|
38
39
|
- **Use `ctx.actor`, never `engine.player`.** `ctx.actor` is the world record id of whoever acts (default `engine.actor`, which is `'player'` — also
|
|
39
40
|
the player's container id — unless the game hands control to a vehicle or squad member). NPCs run the same op with `{ actor: 'npc_3' }`; where an
|
|
40
|
-
actor stands is `engine.actorPosition(ctx.actor)`.
|
|
41
|
+
actor stands is `engine.actorPosition(ctx.actor)`. `ctx` also has `source`, `tick` and `frozen`; a nested op inherits source and actor.
|
|
41
42
|
- **Args are plain data and self-contained**: no three.js objects (pass `[x, y, z]`), and anything not in world data (aim direction, a clicked build
|
|
42
43
|
position) goes in the args. Pass a fresh object each call; in dev the args are frozen because the history keeps them.
|
|
43
44
|
- **All "may I" checks live in `can`**, so `run` never stops halfway. A failure always has a reason (camelCase English). Show it to the player through
|
|
@@ -56,7 +57,8 @@ Rules that keep ops replayable and network-ready:
|
|
|
56
57
|
|
|
57
58
|
`run` is synchronous and returns at once. Between fixed steps it counts as "after step N", which replays the same. Ops still run while gameplay is
|
|
58
59
|
frozen by a menu (`ctx.frozen` is true; return `'paused'` from `can` for things that must wait); after a gameplay error (`engine.error`) every op
|
|
59
|
-
returns `'halted'`.
|
|
60
|
+
returns `'halted'`. While a save replaces the state (reading it, its parts, `afterLoad`, a rollback) every op returns
|
|
61
|
+
`'loading'` and changes nothing; try again after the load.
|
|
60
62
|
|
|
61
63
|
## 3. Built-in ops (installed with their modules)
|
|
62
64
|
| Op | Args | Reasons |
|
|
@@ -68,7 +70,7 @@ returns `'halted'`.
|
|
|
68
70
|
| `inventory.trade` | `{ take, give, takeN?, giveN?, container? }` (all or nothing in `ctx.actor`'s container; reversible with `engine.ops.undo`, recipe 03) | `noContainer` `notEnough` `full` |
|
|
69
71
|
| `inventory.use` | `{ item }` (from `ctx.actor`'s container; runs the item's `use`, see recipe 03) | `notEnough` `notUsable` or the item's `canUse` reason |
|
|
70
72
|
| `inventory.drop` | `{ item, n? }` (a pickup at the actor's feet, data kept) | `notEnough` `noWorld` `noPosition` |
|
|
71
|
-
| `thing.set` | `{ id, position?, rotation?, scale?, visible? }` (core; a world record via `world.set` / `move`, an `engine.add` object saved as an override when it has an id; undoable, recipe 40) | `noThing` `engineOwned` `recordVisible` |
|
|
73
|
+
| `thing.set` | `{ id, position?, rotation?, scale?, visible? }` (core; a world record via `world.set` / `move`, so a live character is placed with its `placeAt`, an `engine.add` object saved as an override when it has an id; undoable, recipe 40) | `noThing` `engineOwned` `recordVisible` |
|
|
72
74
|
| `thing.remove` | `{ id }` (core; undoable: an `engine.add` object is detached and kept, a record re-added) | `noThing` `engineOwned` |
|
|
73
75
|
| `pickup.take` | `{ id }` (the item goes into `ctx.actor`'s container, or its give function runs) | `unknown` `respawning` `noPosition` `tooFar` and more; `ops.list()` has them all |
|
|
74
76
|
| `npc.talk` | `{ npc, script?, channel? }` (`channel` `main` locks input, `bubble` shows lines over the NPC) | `noDialogue` `unknown` |
|
|
@@ -127,10 +129,11 @@ Put `<workspace>/tests/scenarios/<name>.json` in the engine package or a game; `
|
|
|
127
129
|
`tests/snapshots/<name>.describe.json` (`only` / `ignore` / `tolerance`; write it with `threedog test <name> --update-snapshots`).
|
|
128
130
|
- A file has 120 s under `threedog test`; a long one sets `"timeout"` at the top, in milliseconds, as a spec does.
|
|
129
131
|
- Before any step runs, every op name and step field is checked; a typo fails with "did you mean". The run stops at the first failed step.
|
|
130
|
-
-
|
|
132
|
+
- `{ "until": { path: value }, "within": seconds }` reaches a state by a deadline, however the game freezes on the way; check the end with `expect`. A missed deadline, an error or a stuck load each name themselves. `step` stays strict: a `step` that moved less than asked fails, a freeze the game raised itself included: when a win window opens 0.4 s into `{ "step": 0.6 }`, the failure says how far it got and which window froze the game, and the scenario asks for that much.
|
|
133
|
+
- Use `press` only for the one test per key that proves "key -> op".
|
|
131
134
|
|
|
132
135
|
## 8. Inspect and explain
|
|
133
|
-
```js
|
|
136
|
+
```js fragment
|
|
134
137
|
engine.inspect(); // { actor: 'player', at, near: [...nearby], ops: [{ op, args, ok, code?, why? }] }: what is around and possible now
|
|
135
138
|
engine.inspect('npc_3'); // the same as another actor; engine.inspect([x, z]) around a spot
|
|
136
139
|
engine.explain({ op: 'shop.buy', args: { shop: 'bakery', item: 'bread' } }).text;
|
|
@@ -151,21 +154,22 @@ scenario replays the same. `Math.random` breaks both.
|
|
|
151
154
|
## 11. Structured failures, nextFixed, and who halted the loop
|
|
152
155
|
`can` may return a reason string (`'noMoney'`) or a structured failure. Every failed result from `run` / `can` / `undo` has `{ ok: false, code, facts, nextActions }`; a string failure becomes `code = that string`, `facts = {}`, `nextActions = []`, so read `.code` without checking the shape. `engine.inspect()`, `ops.list({ available: true })`, `engine.describe()` actions and `engine.explain({ op })` carry `facts` / `nextActions` too.
|
|
153
156
|
```js
|
|
154
|
-
engine.
|
|
157
|
+
const gold = ctx => engine.inventory.container(ctx.actor).count('gold');
|
|
158
|
+
engine.ops.define('shop.rent', {
|
|
155
159
|
can: (e, a, ctx) => gold(ctx) >= 5 || { code: 'noMoney', facts: { need: 5, have: gold(ctx) }, nextActions: [{ op: 'job.work', args: {} }] },
|
|
156
160
|
run: (e, a, ctx) => { /* ... */ },
|
|
157
161
|
});
|
|
158
|
-
const r = engine.ops.run('shop.
|
|
162
|
+
const r = engine.ops.run('shop.rent', {}); // r.ok === false, r.code === 'noMoney', r.facts.need === 5, r.nextActions[0].op === 'job.work'
|
|
159
163
|
```
|
|
160
164
|
`engine.nextFixed(fn)` runs `fn` at the start of the next fixed step and returns a Promise of its value, so a UI click or a promise callback can safely write gameplay state: `await engine.nextFixed(() => engine.ops.run('door.open', { id: 'gate' }))`. It is built on `engine.commits` and waits while frozen or loading.
|
|
161
165
|
|
|
162
166
|
Tests that halt the loop name themselves (default `'game'`) and end their own halt with the handle: `const h = engine.haltLoop('my-test'); ... h.remove()`. The loop stays halted until every owner has removed theirs, so one helper cannot end another's halt.
|
|
163
167
|
|
|
164
168
|
## 12. Failing in run, atomic ops, revision
|
|
165
|
-
`run` can fail like `can`: return or throw `{ ok: false, code, facts, nextActions }` (
|
|
169
|
+
`run` can fail like `can`: return or throw `{ ok: false, code, facts, nextActions }` (`ok: false` is required). `facts` is an object (`{ need: 5 }`) or a list of `{ id, field, actual, expected? }` naming the record and field that were wrong. Every result carries `revision` (`engine.ops.revision`), a counter bumped once per committed op.
|
|
166
170
|
```js
|
|
167
171
|
engine.ops.define('craft.bread', {
|
|
168
|
-
atomic: true, // every part declared atomic
|
|
172
|
+
atomic: true, // every save part declared atomic is undone if run fails or throws
|
|
169
173
|
run(e, { oven }, ctx) {
|
|
170
174
|
e.inventory.container(ctx.actor).remove('flour', 2);
|
|
171
175
|
if (e.world.get(oven).heat < 3) return { ok: false, code: 'ovenCold', facts: [{ id: oven, field: 'heat', actual: e.world.get(oven).heat, expected: 3 }], nextActions: [{ op: 'oven.light', args: { oven } }] };
|
|
@@ -174,8 +178,8 @@ engine.ops.define('craft.bread', {
|
|
|
174
178
|
after: (e) => e.audio.sfx('ding'), // sound / animation: runs only after the op committed
|
|
175
179
|
});
|
|
176
180
|
```
|
|
177
|
-
What atomic covers: it copies the save parts that declared `saves.register(key, { atomic: true })` (
|
|
181
|
+
What atomic covers: it copies the save parts that declared `saves.register(key, { atomic: true })` (a game's own part can opt in) before `run` and loads them back on failure, so it costs one save of those per run (wrong for a per-frame op in a huge world). Events already emitted, sound, animation and any other module's state are not undone; keep such effects in `after`. Ops called from an atomic run join it (their `after` hooks run, nested first, at the outermost commit; a rolled-back outer takes back their revision). `ops.list()` and `engine.explain({ op })` report `atomic`.
|
|
178
182
|
|
|
179
183
|
Causal trace (`events.traceSize > 0`, recipe 06): failed ops are noted as `op:<name>` with their `code`; `collision.lineClear(a, b, { who })` as `sight` (blocked lines always, clear ones for the focused object only); NPC state changes as `npc:state`. A game's behavior notes its own mode switch with `engine.events.note('npc:mode', { obj: rec.id, data: { from: 'patrol', to: 'investigate' } })`; `events.traceFocus('guard-1')` makes one object verbose.
|
|
180
184
|
|
|
181
|
-
Atomic details: a rolled-back run still bumps `ops.revision` (it only goes up, never back to an old number) and its committed nested ops show in `ops.recent()` as `ok: false` with code `rolledBack`.
|
|
185
|
+
Atomic details: a rolled-back run still bumps `ops.revision` (it only goes up, never back to an old number) and its committed nested ops show in `ops.recent()` as `ok: false` with code `rolledBack`. The rollback does not run `afterLoad` and mutes the events its loads would emit, so atomic state must be plain data.
|
|
@@ -143,7 +143,7 @@ Every entry of the UI focus stack (dialogue, `engine.ui.open` parts, `makeWindow
|
|
|
143
143
|
the view locks again). A window that ends something, win or lose, takes `closable: false`: no close button and Esc does nothing, so the player cannot slip back into the
|
|
144
144
|
game past it and only your buttons end it. Nothing else closes a window: a game that restarts by another road (a new game from the title, a load) closes it on `session:start`. Its picture is your `ui.css` /
|
|
145
145
|
`ui.templates[id]`. A level clear, a match score, a day's earnings or a run summary are all this:
|
|
146
|
-
```js
|
|
146
|
+
```js fragment
|
|
147
147
|
import { makeWindow } from 'threedog';
|
|
148
148
|
const results = makeWindow(engine, {
|
|
149
149
|
id: 'results', title: () => 'Run complete',
|
|
@@ -202,11 +202,12 @@ engine.settings.addSection('gameplay', {
|
|
|
202
202
|
A row that switches off an effect of your own (a post effect, a picture value): name the shared value it limits, and it works like the
|
|
203
203
|
built-in shadows row. Off holds the value off on the settings layer, so a later scene, weather or cutscene cannot turn it back on; on
|
|
204
204
|
allows whatever the scene chose. A number row from 0 to 1 is a factor on a number value. Define the row after the effect exists. `bloom` and `ao` already have rows of their own (limiting `post.bloom.enabled` / `post.ao.enabled`), so `settings.define('bloom', ...)` throws: switch them with `engine.settings.set('bloom', false)`, or in a preset.
|
|
205
|
-
```js
|
|
205
|
+
```js fragment
|
|
206
206
|
engine.post.add(volFog); // post.volFog.enabled now exists
|
|
207
207
|
engine.settings.define('volFog', true, { limits: 'post.volFog.enabled' }); // add apply: v => ... too if the game reacts in code
|
|
208
208
|
engine.settings.define('flashCap', 1, { limits: 'sky.flash' }); // 0.5 = half of any lightning flash
|
|
209
209
|
settings({ presets: { low: { volFog: false } } }); // a preset can switch the row like any other key
|
|
210
|
+
settings({ presets: { low: { viewChunks: 0.5, density: 0.25 } } }); // viewChunks and density in a preset: shares (0 to 1) of the game's own value; the top preset lets everything through
|
|
210
211
|
settings({ presets: { low: { pixelRatio: 0.5 } } }); // pixelRatio in a preset: a share (0 to 1) of the ratio the engine picked for this device
|
|
211
212
|
```
|
|
212
213
|
`engine.describe().shared['post.volFog.enabled']` shows the settings entry and what the scene wanted underneath.
|
package/docs/recipes/27-net.md
CHANGED
|
@@ -20,7 +20,8 @@ Run the relay on any machine both can reach: `threedog relay 8787` (no dependenc
|
|
|
20
20
|
and a reconnect key.
|
|
21
21
|
For tests and offline demos use the in-process network instead (latency, jitter and loss adjustable; `manual: true` delivers only on `advance(ms)`):
|
|
22
22
|
```js
|
|
23
|
-
import { fakeNetwork, net } from 'threedog';
|
|
23
|
+
import { createEngine, fakeNetwork, net } from 'threedog';
|
|
24
|
+
const [host, guest] = [1, 2].map(() => createEngine({ canvas: document.createElement('canvas') })); // two games on one page
|
|
24
25
|
const wire = fakeNetwork({ latency: 80, jitter: 30, loss: 0.05 });
|
|
25
26
|
host.use(net({ role: 'host', transport: wire.host() }));
|
|
26
27
|
guest.use(net({ role: 'client', transport: wire.connect() }));
|
|
@@ -73,8 +74,7 @@ world records, containers, `vars`, and every other save part (quests, clock, sky
|
|
|
73
74
|
On a client the mirror is applied at the next fixed step; `world.simulate` does not run there (the host simulates). Other players glide between
|
|
74
75
|
updates (kinds in `interpolate`, default `['player']`). The client moves its own avatar and reports its position; the host clamps it to `maxSpeed`
|
|
75
76
|
(m/s, default 15).
|
|
76
|
-
A character another machine drives is held by net for good ([57-control](57-control.md))
|
|
77
|
-
each peer's avatar. A local `walkTo`, cutscene or `engine.control.take` on one is `[control-net]`; change it with an op the host runs.
|
|
77
|
+
A character another machine drives is held by net for good: a local `walkTo`, cutscene or `engine.control.take` on one is `[control-net]` ([57-control](57-control.md)).
|
|
78
78
|
|
|
79
79
|
## 5. Write the UI from state, not from run's return value
|
|
80
80
|
On a client `engine.ops.run` returns `{ ok: true, pending: true, seq }` after the local `can` passed (so a "no money" refusal is still instant). The
|