threedog 1.1.0 → 1.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/CHANGELOG.md +879 -798
- package/README.md +1 -1
- package/core/assets/Animator.js +41 -3
- package/core/assets/Assets.js +100 -24
- package/core/assets/assetEntry.js +73 -20
- package/core/assets/assetHot.js +68 -16
- package/core/assets/assetLoad.js +6 -6
- package/core/assets/assetLod.js +9 -2
- package/core/assets/assetManifest.js +12 -2
- package/core/assets/assetPart.js +54 -0
- package/core/assets/ik.js +271 -0
- package/core/assets/modelNeeds.js +37 -0
- package/core/assets/namedModel.js +102 -29
- package/core/assets/nodeVisibility.js +15 -0
- package/core/audio/Audio.js +36 -4
- package/core/audio/audioReverb.js +99 -0
- package/core/audio/audioRules.js +1 -1
- package/core/audio/audioVoice.js +1 -1
- package/core/base/Events.js +14 -4
- package/core/base/Random.js +1 -1
- package/core/base/Vars.js +1 -1
- package/core/base/docRef.js +51 -0
- package/core/base/errorCodes.js +178 -126
- package/core/base/errorHints.js +9 -7
- package/core/base/errors.js +25 -10
- package/core/base/events.generated.js +2 -0
- package/core/base/freeParts.js +76 -0
- package/core/base/math.js +28 -0
- package/core/base/sections.js +5 -5
- package/core/base/validate.js +31 -3
- package/core/engine/Engine.js +16 -6
- package/core/engine/Loading.js +5 -3
- package/core/engine/copies.js +1 -1
- package/core/engine/headlessLoad.js +4 -1
- package/core/engine/lifecycle.js +32 -16
- package/core/engine/loop.js +71 -27
- package/core/engine/moduleSlots.js +2 -2
- package/core/engine/moduleTypes.js +3 -3
- package/core/engine/modules.js +65 -39
- package/core/engine/page.js +6 -3
- package/core/engine/services.js +6 -5
- package/core/engine/startup.js +5 -5
- package/core/input/Input.js +28 -14
- package/core/input/inputContext.js +28 -16
- package/core/input/inputKeyboard.js +31 -3
- package/core/input/inputPad.js +4 -0
- package/core/input/inputPointer.js +2 -1
- package/core/input/inputSeat.js +1 -1
- package/core/inspect/Budget.js +109 -19
- package/core/inspect/DebugOverrides.js +28 -4
- package/core/inspect/Describe.js +17 -9
- package/core/inspect/Inspect.js +4 -2
- package/core/inspect/InspectMaterials.js +3 -1
- package/core/inspect/InspectPerf.js +19 -9
- package/core/inspect/InspectScene.js +32 -7
- package/core/inspect/MaterialInfo.js +19 -2
- package/core/inspect/UrlState.js +46 -27
- package/core/inspect/catalog.js +28 -9
- package/core/inspect/debugView.js +2 -1
- package/core/inspect/describeRender.js +25 -13
- package/core/inspect/describeText.js +14 -6
- package/core/inspect/lightWatch.js +1 -1
- package/core/inspect/metadata.generated.js +35 -17
- package/core/inspect/pictureChecks.js +148 -0
- package/core/inspect/pictureMenu.js +84 -0
- package/core/inspect/pictureWriters.js +26 -6
- package/core/inspect/textureBytes.js +12 -2
- package/core/inspect/toolDoor.js +2 -4
- package/core/ops/Ops.js +11 -4
- package/core/ops/holds.js +27 -10
- package/core/ops/opsAtomic.js +15 -7
- package/core/ops/opsGuard.js +2 -2
- package/core/ops/opsRun.js +8 -7
- package/core/ops/sharedPoint.js +72 -21
- package/core/ops/stacks.js +56 -16
- package/core/saves/SaveStore.js +9 -3
- package/core/saves/Saves.js +32 -23
- package/core/saves/saveApply.js +96 -44
- package/core/saves/saveIds.js +1 -1
- package/core/saves/saveVersions.js +7 -5
- package/core/saves/session.js +17 -8
- package/core/saves/stateReplace.js +34 -15
- package/core/scene/Rays.js +52 -10
- package/core/scene/Views.js +13 -7
- package/core/scene/adaptive.js +144 -21
- package/core/scene/drawOnly.js +17 -0
- package/core/scene/gameLights.js +44 -3
- package/core/scene/sceneMethods.js +13 -11
- package/core/scene/stepPoses.js +11 -3
- package/core/scene/targeting.js +5 -3
- package/core/scene/thingOps.js +1 -1
- package/core/scene/tier.js +15 -0
- package/core/stream/Batching.js +30 -7
- package/core/stream/Stream.js +26 -7
- package/core/stream/batchGroups.js +2 -2
- package/core/stream/chunkStream.js +7 -5
- package/core/stream/prepare.js +77 -0
- package/core/time/skip.js +3 -1
- package/core/time/time.js +4 -2
- package/docs/AI.md +82 -83
- package/docs/API.md +16 -16
- package/docs/CODEMAP.md +16 -11
- package/docs/COMMANDS.md +139 -142
- package/docs/CONVENTIONS.md +37 -49
- package/docs/MIGRATING-0.8.md +2 -2
- package/docs/MIGRATING-1.0.md +2 -2
- package/docs/THREE.md +28 -35
- package/docs/api/assets.md +3 -1
- package/docs/api/audio.md +4 -2
- package/docs/api/budget.md +5 -0
- package/docs/api/characters.md +10 -8
- package/docs/api/collision.md +6 -4
- package/docs/api/engine.md +16 -16
- package/docs/api/events.md +3 -2
- package/docs/api/ground.md +6 -5
- package/docs/api/hud.md +4 -2
- package/docs/api/input.md +5 -5
- package/docs/api/particles.md +2 -1
- package/docs/api/photo.md +3 -0
- package/docs/api/post.md +7 -4
- package/docs/api/quests.md +2 -2
- package/docs/api/rays.md +1 -2
- package/docs/api/saves.md +7 -7
- package/docs/api/settings.md +2 -2
- package/docs/api/tools.md +3 -1
- package/docs/api/vars.md +1 -1
- package/docs/api/vegetation.md +4 -2
- package/docs/api/world.md +1 -1
- package/docs/recipes/01-new-game.md +16 -17
- package/docs/recipes/02-npc.md +22 -18
- package/docs/recipes/03-items-pickups.md +37 -35
- package/docs/recipes/04-quests.md +15 -10
- package/docs/recipes/05-props-bake.md +101 -95
- package/docs/recipes/06-clock-events.md +28 -28
- package/docs/recipes/07-flow-scenes-pause.md +29 -26
- package/docs/recipes/08-weather-sky.md +52 -64
- package/docs/recipes/09-materials-lights-models.md +26 -17
- package/docs/recipes/10-blender-level.md +15 -10
- package/docs/recipes/11-vehicles.md +12 -7
- package/docs/recipes/12-navmesh.md +44 -26
- package/docs/recipes/13-animation.md +56 -45
- package/docs/recipes/14-custom-module.md +21 -18
- package/docs/recipes/15-perf.md +61 -55
- package/docs/recipes/16-dev-bridge.md +23 -33
- package/docs/recipes/18-world.md +36 -42
- package/docs/recipes/19-shooting-picking.md +20 -15
- package/docs/recipes/20-content-actions-save.md +48 -56
- package/docs/recipes/21-camera.md +45 -54
- package/docs/recipes/22-shop-gold.md +12 -7
- package/docs/recipes/23-ops.md +25 -23
- package/docs/recipes/26-ui-parts.md +67 -47
- package/docs/recipes/27-net.md +12 -7
- package/docs/recipes/28-terrain.md +24 -21
- package/docs/recipes/29-grid.md +32 -27
- package/docs/recipes/30-templates.md +21 -20
- package/docs/recipes/31-audio.md +39 -22
- package/docs/recipes/32-action-game.md +19 -14
- package/docs/recipes/33-stream-sources.md +15 -11
- package/docs/recipes/34-environment-lighting.md +126 -70
- package/docs/recipes/35-picture-from-reference.md +8 -8
- package/docs/recipes/36-ground-plants.md +27 -21
- package/docs/recipes/40-scene.md +19 -28
- package/docs/recipes/43-shader-patches-surfaces.md +15 -12
- package/docs/recipes/44-water-weather-hooks.md +34 -31
- package/docs/recipes/45-cascaded-shadows.md +35 -26
- package/docs/recipes/46-blender-art-route.md +6 -1
- package/docs/recipes/49-game-module-contract.md +13 -8
- package/docs/recipes/50-own-renderer.md +6 -2
- package/docs/recipes/51-capability-catalog.md +15 -8
- package/docs/recipes/52-around-the-picture.md +34 -32
- package/docs/recipes/53-ground-up-close.md +6 -1
- package/docs/recipes/55-mods-time-wrap.md +27 -19
- package/docs/recipes/56-webgpu-tsl.md +74 -43
- package/docs/recipes/57-control.md +18 -13
- package/docs/recipes/58-input.md +26 -16
- package/docs/recipes/59-depth-post-effects.md +8 -3
- package/docs/recipes/60-judge-the-picture.md +9 -8
- package/docs/recipes/61-deploy.md +5 -0
- package/docs/recipes/62-picture-code.md +70 -79
- package/docs/recipes/63-third-person-start.md +47 -45
- package/docs/recipes/64-particles.md +22 -10
- package/docs/recipes/65-swarm.md +18 -13
- package/docs/recipes/66-common-tasks.md +38 -35
- package/examples/action/GAMEMAP.md +2 -3
- package/examples/action/main.js +3 -3
- package/examples/action/picture/lights.js +3 -1
- package/examples/perf-island/GAMEMAP.md +3 -3
- package/examples/perf-island/picture/lights.js +2 -1
- package/examples/plain-picture/GAMEMAP.md +1 -1
- package/examples/rc2d/GAMEMAP.md +1 -1
- package/examples/styletest/GAMEMAP.md +2 -2
- package/examples/styletest/main.js +1 -1
- package/examples/techniques/interior-light/README.md +3 -3
- package/examples/techniques/interior-light/interiorLight.js +2 -4
- package/examples/techniques/interior-light/picture/lights.js +2 -1
- package/examples/techniques/modular-building/picture/lights.js +3 -1
- package/examples/techniques/outlines-and-rim/picture/lights.js +3 -1
- package/examples/techniques/procedural-animation/README.md +1 -1
- package/examples/techniques/procedural-animation/main.js +1 -1
- package/examples/webgpu-tsl/GAMEMAP.md +1 -1
- package/examples/world/GAMEMAP.md +2 -3
- package/examples/world/art/humanoid.js +1 -1
- package/examples/world/main.js +6 -3
- package/index.d.ts +2 -2
- package/llms.txt +101 -0
- package/modules/ambience/Ambience.js +21 -5
- package/modules/calendar/index.js +9 -5
- package/modules/calendar/schedule.js +23 -8
- package/modules/camera/FirstPersonCamera.js +3 -1
- package/modules/camera/FollowCamera.js +10 -5
- package/modules/camera/RtsCamera.js +4 -3
- package/modules/camera/common.js +70 -8
- package/modules/camera/contract.js +1 -1
- package/modules/characters/Character.js +16 -10
- package/modules/characters/NPC.js +31 -19
- package/modules/characters/assetModel.js +14 -9
- package/modules/characters/astar.js +6 -1
- package/modules/characters/contract.js +2 -2
- package/modules/characters/index.js +34 -22
- package/modules/characters/movers/manual.js +1 -1
- package/modules/characters/movers/rapier.js +17 -2
- package/modules/characters/movers/simple.js +1 -1
- package/modules/characters/movers/support.js +16 -7
- package/modules/characters/npcAvoid.js +2 -2
- package/modules/characters/npcSim.js +3 -2
- package/modules/characters/pathAsync.js +24 -8
- package/modules/characters/pathJob.js +1 -1
- package/modules/characters/player.js +10 -9
- package/modules/characters/playerStrings.js +5 -5
- package/modules/characters/proceduralRig.js +5 -5
- package/modules/characters/useModel.js +6 -0
- package/modules/characters/walkTo.js +1 -1
- package/modules/collision/Collision.js +29 -18
- package/modules/collision/grid.js +22 -4
- package/modules/content/index.js +3 -1
- package/modules/content/loader.js +1 -1
- package/modules/content/models.js +82 -33
- package/modules/content/props.js +2 -1
- package/modules/content/rules.js +11 -5
- package/modules/content/templates.js +3 -3
- package/modules/content/words.js +2 -2
- package/modules/debug/DebugPanel.js +9 -9
- package/modules/flow/index.js +9 -6
- package/modules/gameplay/Dialogue.js +34 -20
- package/modules/gameplay/Interactions.js +19 -15
- package/modules/gameplay/Inventory.js +9 -4
- package/modules/gameplay/Quests.js +12 -10
- package/modules/gameplay/pickups.js +23 -11
- package/modules/grid/index.js +1 -1
- package/modules/grid/preview.js +2 -2
- package/modules/grid/tiles.js +1 -1
- package/modules/hlod/index.js +4 -1
- package/modules/hud/index.js +47 -10
- package/modules/hud/parts.js +28 -9
- package/modules/level/geometry.js +8 -3
- package/modules/level/index.js +10 -5
- package/modules/level/load.js +4 -2
- package/modules/lights/sources.js +1 -1
- package/modules/music/Music.js +22 -4
- package/modules/nav/index.js +20 -10
- package/modules/particles/Particles.js +31 -14
- package/modules/particles/effect.js +20 -5
- package/modules/particles/lit.js +72 -0
- package/modules/photo/Photo.js +72 -28
- package/modules/photo/pathTrace.js +106 -0
- package/modules/rigid/RigidBodies.js +23 -14
- package/modules/rigid/Vehicles.js +3 -13
- package/modules/rigid/sync.js +2 -1
- package/modules/settings/Settings.js +52 -20
- package/modules/settings/apply.js +23 -9
- package/modules/settings/sections.js +39 -6
- package/modules/settings/strings.js +2 -0
- package/modules/settings/view.js +19 -3
- package/modules/sky/dome.js +15 -3
- package/modules/sky/environment.js +28 -12
- package/modules/sky/fog.js +1 -1
- package/modules/sky/frame.js +6 -1
- package/modules/sky/shader.js +4 -3
- package/modules/sky/skyModule.js +8 -4
- package/modules/swarm/Swarm.js +1 -1
- package/modules/terrain/ChunkManager.js +61 -15
- package/modules/terrain/chunkJob.js +2 -2
- package/modules/terrain/index.js +20 -5
- package/modules/terrain/terrainEdit.js +8 -4
- package/modules/terrain/terrainTexture.js +4 -2
- package/modules/timeline/Timeline.js +4 -3
- package/modules/timeline/Tween.js +3 -0
- package/modules/timeline/letterbox.js +1 -0
- package/modules/triggers/index.js +36 -17
- package/modules/vegetation/Vegetation.js +81 -19
- package/modules/vegetation/densityMap.js +13 -8
- package/modules/vegetation/draw.js +147 -24
- package/modules/vegetation/groundChunks.js +20 -5
- package/modules/vegetation/index.js +3 -3
- package/modules/vegetation/modelGeometry.js +9 -4
- package/modules/water/Water.js +11 -8
- package/modules/weather/Weather.js +7 -2
- package/modules/weather/shaders.js +25 -5
- package/modules/weather/weatherDraw.js +20 -6
- package/modules/world/World.js +2 -1
- package/modules/world/index.js +2 -2
- package/modules/world/persist.js +6 -2
- package/modules/world/views.js +15 -2
- package/package.json +4 -1
- package/presets.js +5 -5
- package/render/PostFX.js +84 -41
- package/render/backend.js +137 -16
- package/render/cascades.js +3 -1
- package/render/cascades.tsl.js +2 -0
- package/render/daylight.js +7 -1
- package/render/detail.js +7 -4
- package/render/effects.js +27 -8
- package/render/fogLook.js +24 -0
- package/render/fuse.js +5 -2
- package/render/fx/detail.tsl.js +9 -7
- package/render/fx/index.js +7 -2
- package/render/fx/library.tsl.js +1 -0
- package/render/fx/lightShaft.tsl.js +114 -0
- package/render/fx/noise.tsl.js +25 -8
- package/render/fx/objectOrigin.tsl.js +39 -10
- package/render/fx/particles.tsl.js +23 -6
- package/render/fx/patchNodes.tsl.js +17 -12
- package/render/fx/pcss.tsl.js +51 -0
- package/render/fx/postWebGPU.tsl.js +89 -29
- package/render/fx/sky.tsl.js +3 -9
- package/render/fxNumbers.js +10 -4
- package/render/impostor.tsl.js +107 -0
- package/render/lighting.js +33 -1
- package/render/lightmap.js +42 -28
- package/render/lights.js +19 -3
- package/render/materials.js +6 -4
- package/render/mergeCommon.js +4 -1
- package/render/occlusion.js +14 -4
- package/render/patches.js +79 -41
- package/render/postRuns.js +32 -0
- package/render/postWebGL.js +97 -10
- package/render/probes.js +10 -14
- package/render/shaderErrors.js +2 -1
- package/render/shadowCache.tsl.js +33 -5
- package/render/shadows.js +42 -16
- package/render/slots.js +8 -5
- package/render/vertexInputs.js +52 -0
- package/types/core.d.ts +114 -46
- package/types/gameplay.d.ts +56 -23
- package/types/generated/core/audio/Audio.d.ts +27 -1
- package/types/generated/core/base/Random.d.ts +1 -1
- package/types/generated/core/input/Input.d.ts +6 -8
- package/types/generated/core/input/inputSeat.d.ts +1 -1
- package/types/generated/core/inspect/Budget.d.ts +26 -0
- package/types/generated/core/inspect/DebugOverrides.d.ts +0 -2
- package/types/generated/core/saves/Saves.d.ts +10 -7
- package/types/generated/core/saves/session.d.ts +8 -2
- package/types/generated/core/scene/Rays.d.ts +1 -3
- package/types/generated/modules/particles/Particles.d.ts +1 -1
- package/types/generated/modules/world/World.d.ts +2 -1
- package/types/generated/render/PostFX.d.ts +35 -9
- package/types/physics.d.ts +796 -764
- package/types/pixel.d.ts +1 -1
- package/types/tsl.d.ts +62 -1
- package/types/world.d.ts +12 -3
- package/ui/Focus.js +7 -5
- package/ui/Parts.js +1 -1
- package/ui/touchPart.js +6 -3
package/docs/recipes/15-perf.md
CHANGED
|
@@ -1,69 +1,74 @@
|
|
|
1
1
|
# Performance investigation (F3, budget, profile, describe().perf)
|
|
2
2
|
|
|
3
|
-
**
|
|
3
|
+
> **Covers:** finding what makes the game slow, limits that warn, baselines, common fixes, less detail far away.
|
|
4
|
+
> **Use when:** the game is slow or you want limits that warn.
|
|
5
|
+
> **Shortest:** `createEngine({ budget: { drawCalls: 250, fps: 55 } })`, then `engine.budget.report()`.
|
|
6
|
+
> **Sections:** 1 Where things stand · 2 Set a budget · 2a Slower than before · 3 Whose CPU is · 4 Common fixes · 4a Less detail far · 4b Render scale and · 5 Verify once before
|
|
4
7
|
|
|
5
|
-
Order:
|
|
6
|
-
|
|
7
|
-
Which renderer measures: `threedog shot`, `perf`, `stress` and `gallery --shots` use the hardware GPU when headless can reach it (`threedog doctor` says whether it can; COMMANDS.md, `--gpu`). On a machine without one, ask the user to press F3 in the browser (bound by `createEngine({ bindings: { ...presets.bindings.debug } })`; the open-world template does).
|
|
8
|
+
Order: numbers first (which category is over: fps, draw calls, CPU, startup?), then who takes the most; after a change compare the same way (section 5).
|
|
9
|
+
Which renderer measures: `threedog shot`, `perf`, `stress` and `gallery --shots` use the hardware GPU when headless can reach it (`threedog doctor` says; `--gpu`). On a machine without one, ask the user to press F3 in the browser (bound by `createEngine({ bindings: { ...presets.bindings.debug } })`; the open-world template does).
|
|
8
10
|
What this machine can carry: `threedog stress` (COMMANDS.md) prints where 16.7 / 33 ms are crossed for each kind of load. Turn the row for your target machine into `engine.budget` limits (section 2).
|
|
9
11
|
|
|
10
12
|
## 1. Where things stand
|
|
11
|
-
- **One report with verdicts**: `engine.inspect.perf()` / `threedog inspect perf
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
`
|
|
16
|
-
- **
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
and `engine.debug.viewModes()` lists every mode. `engine.debug.panel` is the F3 panel (dev builds; null without the `debug()` module).
|
|
21
|
-
- **F3 panel** (`debug()` module; `openWorld` installs it in dev builds only, collapsed; the action `debugPanel` opens it, `presets.bindings.debug` binds F3): frame rate, CPU ms/frame, draw calls, triangles,
|
|
22
|
-
chunks, vegetation instances, time of day; with a budget set also over-limit items and startup time.
|
|
13
|
+
- **One report with verdicts**: `engine.inspect.perf()` / `threedog inspect perf`: draw calls (shadow and post passes included), triangles, programs,
|
|
14
|
+
texture memory (estimate), JS ms per phase, the dearest modules, compile stalls during play (`startup.compileMs`), the costliest programs, one line per budget
|
|
15
|
+
(`✗` with the next call; your `engine.budget` limits, else a desktop 60 fps reference, not enforced). Plain three.js: `renderer.info`. Textures: `engine.inspect.materials()`.
|
|
16
|
+
- **Which materials cost**: `engine.debug.view('shaderCost')` colors materials green -> red by compiled program cost (gray = not compiled yet);
|
|
17
|
+
`engine.debug.view('overdraw')` shows pixels drawn many times over. `'off'` restores. Real GPU timings: `threedog capture` (Spector.js) or the browser's GPU profiler.
|
|
18
|
+
- **Other view modes**: `debug.view('triggers')` shows hidden zones (`triggers({ debugColor, debugOpacity })` colors them); modules add their own (`engine.debug.defineView(name, { what, apply })`);
|
|
19
|
+
`engine.debug.viewModes()` lists them.
|
|
20
|
+
- **F3 panel** (`engine.debug.panel`; `debug()` module, dev builds, null without it; action `debugPanel`): frame rate, CPU ms, draw calls, triangles,
|
|
21
|
+
chunks, vegetation instances, time of day; with a budget set, over-limit items and startup time.
|
|
23
22
|
- **Text**: `engine.describe().perf` =
|
|
24
|
-
`{ fps, cpuMs, cpu, apply, drawCalls, triangles, pixelRatio, budget, startup, stream, batching, jobs, commits, chunks?, vegetation? }
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
- **
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
23
|
+
`{ fps, cpuMs, cpuFrames, cpu, apply, drawCalls, triangles, pixelRatio, gpuMemory, budget, notice, startup, stream, batching, jobs, commits, chunks?, vegetation? }`
|
|
24
|
+
(`cpuMs`: median of `cpuFrames` frames, as in `inspect.perf()` and F3; `cpu`: last frame by phase);
|
|
25
|
+
also the Perf line of `threedog shot --describe-only` (headless: fps and cpu are `-`).
|
|
26
|
+
- **One line when something is off**: `engine.budget.notice()` (`describe().perf.notice`, printed by `describeText`, `shot`, `verify`), null when all is fine:
|
|
27
|
+
`Perf: over budget drawCalls 312 (limit 250, +25%); slower than baseline: ...; spiky: ...; lowered automatically: reflections cheaper, resolution 1.5 -> 1.2 (...)`, against your own limits and baseline (2, 2a).
|
|
28
|
+
- **CPU time of a frame**: `engine.inspect.perf().cpuMs`, main thread from input to the afterRender hooks (no GPU time); `cpuPhases` splits it:
|
|
29
|
+
`fixed` (input + fixed steps), `frame` (frame hooks, stream, jobs), `render` (draw submission, uploads, shader compiles), `afterRender`.
|
|
30
|
+
`npm run perf -- --only=stream` measures the stream-in numbers below.
|
|
31
|
+
- **Applying background results** (`engine.budget.cost.report()`, `describe().perf.apply`, budget categories `applyBuildMs` ...): what the main thread
|
|
32
|
+
pays for chunks, vegetation, colliders and stream builds, in stages `transit` (worker round trip minus its compute, approximate), `build` (three.js
|
|
33
|
+
objects), `collider`, `upload` (readying streamed textures and shaders, plus the extra render time of frames that first draw new objects), `stream` (sync part of a `stream.add` build).
|
|
34
|
+
Per stage: `n`, `totalMs`, `maxMs`, smoothed `frameMs`, `bytes` (transit).
|
|
34
35
|
- **Startup**: `engine.startup` = `{ totalMs, startMs, preloadMs, streamMs, compileMs, firstFrameMs, phases, modules: { name: { init, ready } } }`. `firstFrameMs` is page open to the first frame drawn after the loading screen, and `phases`
|
|
35
36
|
splits it into parts that add up to it: `script` (page open until `createEngine`), `construct`, `setup` (game code until `start()`), `init` (saves,
|
|
36
37
|
renderer, module init), `preload`, `world` (nearby builds), `compile` (shaders + hidden warm-up frame), `draw`. `inspect.perf().text` prints the line.
|
|
37
38
|
|
|
38
39
|
## 2. Set a budget (so going over reports itself)
|
|
39
|
-
Off by default and costs nothing.
|
|
40
|
+
Off by default and costs nothing. Only the categories given are checked; `gpuMemoryMB` is three's own byte count (WebGPU only, not driver VRAM):
|
|
40
41
|
```js
|
|
41
|
-
const engine = createEngine({ canvas, budget: { drawCalls: 250, fps: 55, low1: 30, triangles: 600000,
|
|
42
|
+
const engine = createEngine({ canvas, budget: { drawCalls: 250, fps: 55, low1: 30, triangles: 600000, gpuMemoryMB: 512, rigidBodies: 300, startupMs: 5000 } });
|
|
42
43
|
// or at runtime: engine.budget.enable({ drawCalls: 200 });
|
|
43
|
-
const r = engine.budget.report();
|
|
44
|
+
const r = engine.budget.report(); // { ok, over: [{ category, value, limit, top }] }; going over also prints one console hint
|
|
44
45
|
```
|
|
45
46
|
`top` lists the biggest draw-call users grouped by an object's `userData.budgetTag`. Tag your own things to see who it is:
|
|
46
47
|
```js fragment
|
|
47
|
-
house.userData.budgetTag = 'houses';
|
|
48
|
-
engine.budget.byTag();
|
|
49
|
-
engine.budget.metric('fishCount', () => fish.length, { limit: 50 });
|
|
48
|
+
house.userData.budgetTag = 'houses'; // children inherit the parent's tag; untagged ones count as 'other'
|
|
49
|
+
engine.budget.byTag(); // [{ tag, drawCalls, triangles }...], largest first
|
|
50
|
+
engine.budget.metric('fishCount', () => fish.length, { limit: 50 }); // a module's own category
|
|
51
|
+
engine.budget.enable({ modules: { terrain: 1.5, vegetation: 2 } }); // ms per frame of one module (median of engine.profile(), section 3; a fixed-step module counts its dearest single step, catch-up steps are not added)
|
|
50
52
|
```
|
|
51
53
|
|
|
54
|
+
## 2a. Slower than before (a baseline on this machine)
|
|
55
|
+
`threedog shot --save-baseline` (or `verify <name> --save-baseline`) writes `engine.budget.record()` (draw calls, triangles, module ms, live `cpuMs`) to
|
|
56
|
+
`.threedog/perf-baseline.json`, keyed by GPU, canvas size, pixel ratio, headless or live, camera pose. Runs with that key load it into `engine.budget.baseline`
|
|
57
|
+
and name what got slower (times +20% and +0.2 ms, new ones past 0.2 ms; counts +5%). Local to this machine, do not commit; save again after a change you accept.
|
|
58
|
+
|
|
52
59
|
## 3. Whose CPU is slow
|
|
53
60
|
```js
|
|
54
|
-
engine.profile(
|
|
55
|
-
|
|
56
|
-
engine.profile(); // { terrain: 0.06, rigid: 0.23, ... } average milliseconds per rendered frame; cleared after reading
|
|
57
|
-
engine.profile(false);
|
|
61
|
+
engine.profile(); // { terrain: { ms: 0.1, mean: 0.12, p95: 0.4 } } per frame, last 300 (ms: median); on in dev
|
|
62
|
+
engine.profile(true); // production: on (afresh); false: off
|
|
58
63
|
```
|
|
59
|
-
`
|
|
60
|
-
|
|
64
|
+
Only the module's own hooks count, not what it hands to `engine.jobs` or `engine.stream` loaders. Fixed hooks count one fixed step per frame, the dearest one: a slow frame runs several catch-up steps, and that is the frame's cost (`cpuMs`), not a spike of the physics module. `threedog inspect perf` lists the five dearest.
|
|
65
|
+
Browsers round time to 0.1 ms. `onFrame/onFixed` are not timed; to time one, make it a small module (`14-custom-module.md`).
|
|
61
66
|
|
|
62
67
|
## 4. Common fixes
|
|
63
68
|
| Symptom | Fix |
|
|
64
69
|
|---|---|
|
|
65
70
|
| 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) |
|
|
66
|
-
| Expensive shadows | `engine.shadows.budget(light, { every: 3 })` (update every 3 frames), reduce `light.shadow.mapSize` / the box's `extent`; filter `renderer.shadowMap.type
|
|
71
|
+
| Expensive shadows | `engine.shadows.budget(light, { every: 3 })` (update every 3 frames), reduce `light.shadow.mapSize` / the box's `extent`; filter `renderer.shadowMap.type`: Basic cheapest, PCF default, VSM softest and dearest (switching recompiles); vegetation `shadowRing` (default 1) is how many chunk rings cast (culled per camera: a shadow box or cascade draws only chunks inside it), `engine.vegetation.setShadowRing('tree', 0)` while playing; grass-scale species: `castShadow: false` (`content check` hints) |
|
|
67
72
|
| Stutter while walking | Put generation work in `engine.jobs.add(function* () { ...; yield; })` or `engine.stream.add`; chunk upload budget `engine.terrain.applyBudgetMs` |
|
|
68
73
|
| Slow start | Look at which is slowest in `engine.startup.modules`; `npm run bake` for large models; preload only the necessary assets |
|
|
69
74
|
| Slow physics | Keep dynamic rigid bodies within a few hundred (the `rigidBodies` budget); `rigid({ terrainRing: 1 })` |
|
|
@@ -74,9 +79,9 @@ false = all on the main thread, same results.
|
|
|
74
79
|
- Many far records: `world.simulate(kind, { far, worker: true })` (recipe 18 section 7).
|
|
75
80
|
- Many paths per step (NPC crowds, AI squads): `engine.characters.findPathAsync(from, to, done)` (recipe 12 section 4); built-in NPCs already use it.
|
|
76
81
|
- Your own worker script: `engine.threads.lane({ create: () => new Worker(new URL('./w.js', import.meta.url), { type: 'module' }), local: makeHandler })`;
|
|
77
|
-
the worker file is `serve(makeHandler())` from `threedog/worker`. Results that change gameplay go through `
|
|
82
|
+
the worker file is `serve(makeHandler())` from `threedog/worker`. Results that change gameplay go through `ctx.commits`.
|
|
78
83
|
|
|
79
|
-
**Two worker limits**, with examples in `../CONVENTIONS.md`, "Worker limits": `
|
|
84
|
+
**Two worker limits**, with examples in `../CONVENTIONS.md`, "Worker limits": `ctx.commits` runs your `fallback()` when the worker is late and does not clear pending requests on a load or level change, so give each a `valid()`; `threads.pure` functions are recompiled from source and capture nothing.
|
|
80
85
|
|
|
81
86
|
## 4a. Less detail far away: which tool for which job
|
|
82
87
|
|
|
@@ -93,10 +98,10 @@ Four tools lower the cost of distant things, and each owns a different case. Pic
|
|
|
93
98
|
// 1. once: writes public/optimized/tower.lod1.glb, .lod2.glb and lists them in assets.optimized.js
|
|
94
99
|
// threedog assets optimize --lod (--lod-shares 0.5,0.2 sets the triangle share of each level)
|
|
95
100
|
// 2. one line in the game; without it no level is ever downloaded
|
|
96
|
-
const tower = await engine.assets.lod('tower');
|
|
97
|
-
const gate = await engine.assets.lod('gate', { distances: [40, 120] });
|
|
101
|
+
const tower = await engine.assets.lod('tower'); // distances follow the model's size
|
|
102
|
+
const gate = await engine.assets.lod('gate', { distances: [40, 120] }); // or your own, in meters
|
|
98
103
|
// content/props.js: { model: 'tower', x: 10, z: 4, collide: 'box', lod: true } // or lod: [40, 120]; also on a template
|
|
99
|
-
tower.levels[1].object;
|
|
104
|
+
tower.levels[1].object; // a plain THREE.LOD: read, replace, tower.addLevel(...), tower.autoUpdate = false
|
|
100
105
|
```
|
|
101
106
|
|
|
102
107
|
- **Batching:** instances share one geometry, so a copy cannot change level alone. A LOD object is never batched, which means `lod` on a model placed many times can
|
|
@@ -107,24 +112,25 @@ tower.levels[1].object; // a plain THREE.LOD: read, replace, tower.addLevel(..
|
|
|
107
112
|
- **Skipped by the tool, with the reason in its report:** skinned, morphing and animated models, and models under 1000 triangles. `assets.lod` still works on them: one level, and a
|
|
108
113
|
dev warning.
|
|
109
114
|
- **The level follows `engine.camera`** only, so a shadow pass does not change it. `delete tower.update`, while level 0 shows, restores the plain method; far rays then miss the full model.
|
|
110
|
-
- **A narrow lens:** `camera.zoom` counts towards the distance, `camera.fov` does not
|
|
115
|
+
- **A narrow lens:** `camera.zoom` counts towards the distance, `camera.fov` does not: a scope narrowing `fov` shows the far level, so zoom, or set
|
|
111
116
|
`tower.autoUpdate = false` while scoped.
|
|
112
117
|
- **Check the last level up close once:** a low level can lose round details (a dial, a dome) that a few dozen pixels hide and a scope shows. If it shows, raise `--lod-shares` or move the distance out.
|
|
113
|
-
- **Popping:**
|
|
118
|
+
- **Popping:** no crossfade (only `hysteresis`); if a switch shows, move the distance out.
|
|
114
119
|
- **Scale:** default distances follow a prop's `scale`. On `assets.lod` they follow the model as loaded, so give `distances` when you scale it yourself.
|
|
115
120
|
|
|
116
|
-
## 4b. Render scale
|
|
121
|
+
## 4b. Render scale and effects are never lowered silently
|
|
117
122
|
- Default render scale: `min(devicePixelRatio, 1.5)`; the low tier uses at least 0.75 x devicePixelRatio (a 2x laptop screen gets 1.5, not 1), never above 1.5.
|
|
118
|
-
- Adaptive
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
123
|
+
- Adaptive quality (`createEngine({ adaptiveResolution, targetFps })`, default on) lowers one step a second while frames cost more than the target allows
|
|
124
|
+
(CPU + GPU time where timed, else fps unless locked to the display); the first 3 s, compile frames and a 30 Hz lock are not judged.
|
|
125
|
+
Dev warns once; the perf notice (section 1) names what stays lowered. 4 s of cheap frames raise the last one back.
|
|
126
|
+
- `engine.adaptive.steps`, first lowered first. Default `null`: effects' own `cheaper` params (in place, no recompile), the resolution (0.1 a step, floor 0.6),
|
|
127
|
+
then `skipOnLowTier` effects held off (a rebuild, so last; one that drops straight back waits longer). Your own knob: `{ name, down, up }`
|
|
128
|
+
(down: false at its floor). `['resolution']` = scale only, `[]` = nothing.
|
|
129
|
+
Only downward: what the game or player has off is no step, settings stay above it, `adaptive.on = false` puts every effect back.
|
|
130
|
+
- `engine.setPixelRatio(p)` = the top it climbs back to; a direct `renderer.setPixelRatio` drops the resolution step; `pixelSize` stops it all (recipe 62 4b).
|
|
124
131
|
- `describe().render.scale`: `{ current, devicePixelRatio, upscaled, pixelSize, autoLowered, adaptive, floor, max }`. `upscaled: true` means current < devicePixelRatio, the picture
|
|
125
132
|
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
133
|
|
|
127
134
|
## 5. Verify (once before and once after, under the same conditions)
|
|
128
135
|
- `npm run perf` (native vs engine vs per-module cost of openWorld), run before and after on the same machine; differences under 10-30% are noise.
|
|
129
|
-
-
|
|
130
|
-
- Attach the before/after numbers when reporting.
|
|
136
|
+
- One spot: `threedog shot --pos x,z --save-baseline` before, the same shot after (2a). Attach the numbers.
|
|
@@ -1,12 +1,11 @@
|
|
|
1
1
|
# Dev bridge: operate the running game from the terminal (threedog describe / step / press / op...)
|
|
2
2
|
|
|
3
|
-
**
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
11
|
|
3
|
+
> **Covers:** driving the running game from the terminal: describe, step, press, state, scenarios, snapshots, MCP.
|
|
4
|
+
> **Use when:** checking a change without a screenshot or a browser script.
|
|
5
|
+
> **Shortest:** `threedog describe -w my-game`.
|
|
6
|
+
> **Sections:** 1 Usage · 2 Notes · 2b A scripted playthrough · 3 Windows / PowerShell · 3b Speed, a session · 4 Let describe see · 5 Safety · 6 Reuse in scenario · 7 Describe snapshots instead · 8 Errors carry a · 9 Reusable scenarios · 10 MCP server Claude · 11 When something happens
|
|
7
7
|
|
|
8
|
-
|
|
9
|
-
keys, change state. Output is English, three lines or fewer, to save tokens.
|
|
8
|
+
After changing code, ask the running game instead of writing a playwright script or taking a screenshot: look, advance time, press keys, change state. Output is a few English lines.
|
|
10
9
|
|
|
11
10
|
What the bridge changes lives in this session only: `op`, `step`, `state` and `js` alter the running game and its saves, never the level. To change
|
|
12
11
|
the level, edit `content/*.js` (templates, props, npcs…) or the level model and reload the page.
|
|
@@ -25,7 +24,7 @@ Every command and its options are in `../COMMANDS.md`. What each does to the gam
|
|
|
25
24
|
|---|---|---|
|
|
26
25
|
| `step`, `press`, `hold`, `skip`, and `scenario` / `verify`, which use them | `op`, `state` (only its `wait=` moves the clock), `js` | `describe`, `ops`, `inspect`, `pick`, `explain`, `errors`, `loading`, `snap`, `snap-describe` |
|
|
27
26
|
|
|
28
|
-
- `describe` is one line: position, time and weather, nearby, quest. `describe player.position` or any dotted path of `engine.describe()` reads one item (`--max characters`). `describe --full` is the state as text in at most 30 lines (`engine.describeText()`:
|
|
27
|
+
- `describe` is one line: position, time and weather, nearby, quest. `describe player.position` or any dotted path of `engine.describe()` reads one item (`--max characters`). `describe --full` is the state as text in at most 30 lines (`engine.describeText()`: nearest things, the game's `describe.add` sections, one line per module, engine tables as one count line, how to expand); `--all` is large, prefer a path. In code: `engine.describe('picture')`, `describe({ only: ['picture', 'shared'] })`. `describe render` lists how the picture is set; it informs and never warns.
|
|
29
28
|
- `step 2` is deterministic; a real-time page is halted first.
|
|
30
29
|
- `press interact` takes an action name or key (`KeyE`, `e`, `Escape`). **It advances game time**: 0.1 s held + one rendered frame of 1/60 s, about 0.117 s; shorten the hold with `--for 0.02` when timing matters.
|
|
31
30
|
- `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.
|
|
@@ -38,28 +37,23 @@ Every command and its options are in `../COMMANDS.md`. What each does to the gam
|
|
|
38
37
|
- **Smallest scenario** (`tests/scenarios/coins.json` <!-- r18-ignore-line -->, then `threedog verify coins` or `scenario coins`; `verify` with no file says "Have: none"):
|
|
39
38
|
`{ "name": "coins", "url": "/", "state": { "pos": "6,4" }, "steps": [ { "step": 1 }, { "expect": { "inventory.items.coin": 1 } } ] }`
|
|
40
39
|
- **Position formats**: `pos=x,z` (state, shot, `applyState`) is two numbers on the ground plane, and the height is looked up; an op argument such as `position=3,0,-2` is `x,y,z`. Both are meters, north is -z. `describe` reports the player as `{ x, y, z }` (`describe player.position`).
|
|
41
|
-
- **Teleport the player**: `threedog state "pos=40,-20"
|
|
42
|
-
|
|
43
|
-
game itself it belongs in an op (a teleporter pad). `step 1` after it collects `auto` pickups: the pickup check runs in the fixed step after any move.
|
|
40
|
+
- **Teleport the player**: `threedog state "pos=40,-20"`, or `await engine.applyState({ pos: '40,-20' })` in a test or `js` (both wait for the ground to load). A bare
|
|
41
|
+
`player.placeAt` outside an op prints the ops-guard warning. `step 1` after it collects `auto` pickups.
|
|
44
42
|
- **Ops with a reach** (`interaction.use`, `pickup.take`) check the player's distance as a key press would, also from the bridge: put the player next
|
|
45
43
|
to the thing first (`threedog state "pos=x,z"`), then `threedog op interaction.use id=gate`. A `tooFar` result carries `facts: { distance, radius, at }`.
|
|
46
44
|
- **`shot` always starts a fresh game** (`?save=slot1` loads one); after playing use `snap name`. Every shot prints the picture numbers and hints (recipes/35 "Picture check after every shot").
|
|
47
45
|
- **`step` / `press` halt the real page's loop**; resume with `threedog resume` when done (they halt as owner `threedog`, so nothing of the game's is touched). A headless page only advances on step anyway.
|
|
48
|
-
- **Run state** is printed after `step` / `press` / `skip` / `resume` and by `threedog status`: `running`, `title-frozen` (title screen waiting for start), `halted` (
|
|
49
|
-
- **Who holds what**: `describe().holds` lists every holder in one place: `halt / freeze / camera / debugView` as `[{ owner, at }]` (`at` = game clock time of the take, `engine.clock.now
|
|
46
|
+
- **Run state** is printed after `step` / `press` / `skip` / `resume` and by `threedog status`: `running`, `title-frozen` (title screen waiting for start), `halted` (loop stopped by the bridge, a test or a headless page), `frozen(by owners)` (every `freeze` owner, e.g. `ui-inventory` or `page`) or `loading`. The same object is `engine.runState` and `describe().time.run`: `{ state, owners, 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.
|
|
47
|
+
- **Who holds what**: `describe().holds` lists every holder in one place: `halt / freeze / camera / debugView` as `[{ owner, at }]` (`at` = game clock time of the take, `engine.clock.now`), `input` (pushed contexts `[{ context, owner, pass }]`), `gates` (`input.gate` owners by action) and `stacks` (every other `engine.mod` quantity), so a stuck pause, jump or camera has a name.
|
|
50
48
|
- **`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`
|
|
51
49
|
(`ui.windows`, dialogue).
|
|
52
50
|
- **Keys go through `engine.input` like a real keyboard**: action names are translated to keyboard keys (gamepad buttons are ignored); when a window
|
|
53
51
|
locks input, menu-type actions (`pressedRaw`) are still received.
|
|
54
|
-
- **In your own page scripts and tests
|
|
55
|
-
works with `engine.step`): `engine.input.simulate('jump'); engine.step(1 / 60); engine.input.simulate('jump', false)`. Never call `_keyDown` /
|
|
56
|
-
`_keyUp` (internal).
|
|
52
|
+
- **In your own page scripts and tests use `engine.input.simulate(action, down = true)`** (the same path as `press`): `engine.input.simulate('jump'); engine.step(1 / 60); engine.input.simulate('jump', false)`.
|
|
57
53
|
- `describe` by default gives only the 3 nearest things and the first quest; for detail use a path (`quests.active`, `nearby`, `world`) or `--full`.
|
|
58
54
|
- Several pages: `--page /<page>.html` picks the path; `-w name` picks the workspace.
|
|
59
|
-
-
|
|
60
|
-
-
|
|
61
|
-
the dev server `engine.start()` attaches it automatically, but the bundled build used by npm test does not; the timeout error says whether the page
|
|
62
|
-
has `window.engine`, `engine.ready`, and the latest page errors.
|
|
55
|
+
- Another port (`npm run dev -- my-game --port 5000`) is found through `.threedog/dev.json`.
|
|
56
|
+
- Never ready: the dev server attaches `window.engine` itself, but a bundled build (npm test) needs `window.engine = engine;` before `await engine.start()`; the timeout error says which is missing.
|
|
63
57
|
|
|
64
58
|
## 2b. A scripted playthrough, and three kinds of check
|
|
65
59
|
```
|
|
@@ -73,10 +67,10 @@ threedog snap after-walk # only now look at pixels
|
|
|
73
67
|
```
|
|
74
68
|
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
69
|
- **State checks** (`op`, `expect`, `describe`, `js`): fast and exact, but they skip input. They prove rules, not that the player can reach them.
|
|
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;
|
|
70
|
+
- **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; from `engine.catalog()`); `scenario` prints the same, `--json` the full lists.
|
|
77
71
|
- **Visual checks** (`snap`, `shot`): the only ones that see the picture (exposure, color, UI overlap). Slowest; take them last.
|
|
78
72
|
|
|
79
|
-
**Script the failures, not only the win.**
|
|
73
|
+
**Script the failures, not only the win.** 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). Read `ops never run` in the `verify` report (rules no script reached), then check what the player stands in after the failure: a closed-off respawn point, a hit landing after the blow that should end contact, a timer or lock left from the last attempt.
|
|
80
74
|
|
|
81
75
|
Playing a game through from a script, the five things that cost the most time:
|
|
82
76
|
- **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
|
|
@@ -93,15 +87,14 @@ Playing a game through from a script, the five things that cost the most time:
|
|
|
93
87
|
reports an error and shows this tip when pos is not two numbers).
|
|
94
88
|
- Wrap the whole `js` expression in **double quotes** and use single quotes for strings inside: `threedog js "engine.vars.counter('score')"`.
|
|
95
89
|
PowerShell expands `$variables` inside double quotes; to pass `$` literally wrap the whole thing in single quotes.
|
|
96
|
-
- **Write a command on a single line
|
|
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).
|
|
90
|
+
- **Write a command on a single line** (a multi-line here-string to a native command often returns nothing): separate statements with semicolons, or use `threedog js --file script.js`.
|
|
98
91
|
- Some terminal sandboxes (Bash) block commands containing the word `eval`: use `js`, not `eval`.
|
|
99
92
|
|
|
100
93
|
## 3b. Speed, a session, and checks in one call
|
|
101
94
|
|
|
102
95
|
The bin called directly is the fastest route (COMMANDS.md, first lines); `threedog session` saves a little more per command. Commands behave identically with or without it.
|
|
103
96
|
|
|
104
|
-
- `threedog js --file steps.js`:
|
|
97
|
+
- `threedog js --file steps.js`: the whole test in one file, one round trip. Inside: `assert(cond, msg)`, `expect(v).toBe(x)` (also `toEqual`, `toBeCloseTo(x, tol)`, `toBeGreaterThan`), `step(seconds)`, `log(...)`, and `engine`. It prints the failures and one summary line, exit code 1 on failure:
|
|
105
98
|
|
|
106
99
|
```js fragment
|
|
107
100
|
step(2);
|
|
@@ -113,12 +106,10 @@ expect(engine.time.tick).toBeGreaterThan(before, 'time advanced');
|
|
|
113
106
|
## 4. Let describe see the game's own state
|
|
114
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:
|
|
115
108
|
```js
|
|
116
|
-
engine.describe.add('range', () => ({ score, targets: targets.length }));
|
|
109
|
+
engine.describe.add('range', () => ({ score, targets: targets.length })); // the returned handle's .remove() cancels it
|
|
117
110
|
```
|
|
118
|
-
After that `threedog describe range` shows it, and `describeText()`
|
|
119
|
-
|
|
120
|
-
**Large games write their systems as modules** (see 14-custom-module.md) and use the module's `describe(e, ctx)` hook: the return value likewise goes
|
|
121
|
-
into `describe().<module name>`, and `ctx.near()` can report "things nearby".
|
|
111
|
+
After that `threedog describe range` shows it, and `describeText()` lists it before the module lines. The name must not collide with a core field or a module name;
|
|
112
|
+
a callback that throws shows `{ error }` for this item only. **Large games use modules** (14-custom-module.md): the module's `describe(e, ctx)` hook goes into `describe().<module name>`.
|
|
122
113
|
|
|
123
114
|
## 5. Safety
|
|
124
115
|
The bridge exists only in the dev server (`apply: 'serve'`); built and preview output contains no bridge code. The command entry point `POST /__threedog/cmd` accepts only local connections, requires the random token in `.threedog/dev.json`, the Host must
|
|
@@ -142,11 +133,10 @@ Options: `--only a,b.c` (compare just these fields; dotted paths allowed), `--ig
|
|
|
142
133
|
|
|
143
134
|
In a test, one line (the page must already be in the state to freeze; use `engine.haltLoop()` and `engine.step()` first):
|
|
144
135
|
```
|
|
145
|
-
import { expectDescribe } from '@threedog/tools/describe-snapshot';
|
|
136
|
+
import { expectDescribe } from '@threedog/tools/describe-snapshot'; // in the engine's own specs: '../../../tools/describe-snapshot.mjs'
|
|
146
137
|
await expectDescribe({ check, ev }, 'market-noon', { only: ['player', 'quests', 'nearby'], tolerance: { default: 0.5, player: 1 } });
|
|
147
138
|
```
|
|
148
|
-
Update after an intended change: `threedog test <name> --update-snapshots`
|
|
149
|
-
Review the JSON diff in git before committing. Take a screenshot only when the picture changed.
|
|
139
|
+
Update after an intended change: `threedog test <name> --update-snapshots` or `threedog snap-describe save <name>`, and review the JSON diff before committing.
|
|
150
140
|
|
|
151
141
|
## 8. Errors carry a code, a fix and a doc page
|
|
152
142
|
Every error and warning the engine raises carries a stable **code**: `err.code`, `err.fix` (what to do) and `err.docs` (pages to read), and its message
|
|
@@ -174,7 +164,7 @@ Cursor, `.cursor/mcp.json` in the game folder: <!-- r18-ignore-line -->
|
|
|
174
164
|
```
|
|
175
165
|
{ "mcpServers": { "threedog": { "command": "node", "args": ["node_modules/@threedog/tools/bin/threedog.mjs", "mcp"] } } }
|
|
176
166
|
```
|
|
177
|
-
Plain node is the same on every OS
|
|
167
|
+
Plain node is the same on every OS. `npm run new-game` writes a `.mcp.json` like this into the new game, so Claude Code picks it up.
|
|
178
168
|
|
|
179
169
|
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`
|
|
180
170
|
(workspace), `--page /<page>.html` (page path).
|
package/docs/recipes/18-world.md
CHANGED
|
@@ -1,85 +1,79 @@
|
|
|
1
1
|
# World data: things that must be saved, grow, and keep changing while far away
|
|
2
2
|
|
|
3
|
-
**
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
`interactions({ ...presets.interactions.nearest })
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
away, with no model, the data is still simulated.
|
|
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.
|
|
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
|
-
and place instances (recipe 30-templates.md); the template is the shared read-only definition, the record holds only the instance state.
|
|
3
|
+
> **Covers:** world records: things that are saved, grow and change while far away.
|
|
4
|
+
> **Use when:** an object must live on outside the view or across levels.
|
|
5
|
+
> **Shortest:** `engine.world.add({ id, kind, position })`.
|
|
6
|
+
> **Sections:** 1 Three steps data · 2 How to change · 3 Example a crop · 4 Data written in · 4b One object from · 5 Example something that · 6 Near, far, camera · 7 Time and ordering · 8 Querying nearby things · 9 zone and data
|
|
7
|
+
|
|
8
|
+
Requires `world()` (part of `openWorld()`); the examples also use `interactions({ ...presets.interactions.nearest })` and `inventory()`. API: `../api/world.md`.
|
|
9
|
+
|
|
10
|
+
Anything that must remember its state, survive level changes and keep changing while far away (chests, NPCs, crops, the player itself) is one **plain data
|
|
11
|
+
record** in `engine.world`: a stable id, a kind, a position, plus your own fields. The model is only how it looks when near; unloading tears down the model,
|
|
12
|
+
never the data; a save stores only data; far away the data is still simulated. A decorative rock is a props entry (recipe 05); many copies of one interactive
|
|
13
|
+
object are a content template with instances (recipe 30-templates.md), whose records hold only the instance state.
|
|
19
14
|
|
|
20
15
|
## 1. Three steps: data, picture, change
|
|
21
16
|
```js
|
|
22
17
|
const W = engine.world;
|
|
23
|
-
W.add({ id: 'zombie_1', kind: 'zombie', position: [10, 0, -4], hp: 10 });
|
|
18
|
+
W.add({ id: 'zombie_1', kind: 'zombie', position: [10, 0, -4], hp: 10 }); // fields must be plain values; without an id one is numbered automatically (saved)
|
|
24
19
|
W.present('zombie', {
|
|
25
|
-
build: rec => new THREE.Mesh(zombieGeo, zombieMat),
|
|
26
|
-
update: (rec, obj, dt) => { obj.visible = rec.hp > 0; },
|
|
27
|
-
dispose: (rec, obj) => engine.remove(obj),
|
|
28
|
-
show: rec => rec.hp > 0,
|
|
29
|
-
radius: 40,
|
|
20
|
+
build: rec => new THREE.Mesh(zombieGeo, zombieMat), // required: built when the camera is near (may be async); world adds it to the scene at rec.position
|
|
21
|
+
update: (rec, obj, dt) => { obj.visible = rec.hp > 0; }, // optional: called every frame for records that have a model; change the picture from the data
|
|
22
|
+
dispose: (rec, obj) => engine.remove(obj), // optional: first argument is the data, second the model; this is the default
|
|
23
|
+
show: rec => rec.hp > 0, // optional: false = this record has no model right now (picked up, waiting to respawn)
|
|
24
|
+
radius: 40, // optional: how near to build the model (meters or a function); default world.radius (60)
|
|
30
25
|
});
|
|
31
26
|
W.simulate('zombie', {
|
|
32
|
-
near: (rec, dt, obj) => { W.move(rec.id, { x: rec.position.x + dt, z: rec.position.z }); },
|
|
33
|
-
far: (rec, dt) => { rec.hp = Math.min(10, rec.hp + dt * 0.1); },
|
|
27
|
+
near: (rec, dt, obj) => { W.move(rec.id, { x: rec.position.x + dt, z: rec.position.z }); }, // near the player: every fixed step; obj may not be built yet (null), gameplay must not depend on it
|
|
28
|
+
far: (rec, dt) => { rec.hp = Math.min(10, rec.hp + dt * 0.1); }, // far away: once every farEvery seconds; dt is accumulated seconds (it can catch up a long time at once)
|
|
34
29
|
});
|
|
35
30
|
```
|
|
36
31
|
- If `build` throws, fails, or returns something that is not an object, the error is reported once and does not block the loading screen
|
|
37
32
|
(`world.ready`); it retries when you walk away and come back.
|
|
38
33
|
- `show` is re-evaluated when `world.set` changes data of that kind. Calling `present` again for the same kind tears down old models with the old
|
|
39
34
|
dispose and rebuilds them with the new one.
|
|
40
|
-
-
|
|
41
|
-
on its record, so picture-only motion written there stays: `update: (rec, obj, dt) => { obj.getObjectByName('legL').rotation.x = Math.sin(rec.walk * 9) * 0.5;
|
|
35
|
+
- Per-frame picture work (animation, particles) goes in `present.update`, which runs after world placed the model, so motion written there stays: `update: (rec, obj, dt) => { obj.getObjectByName('legL').rotation.x = Math.sin(rec.walk * 9) * 0.5;
|
|
42
36
|
obj.position.x += rec.stagger * 0.1; }` (a leg swing, a stagger offset). Moving the model from anywhere else is put back next frame, with a warning.
|
|
37
|
+
- world places only the position of a model your `build` returns: apply `rec.rot` / `rec.scale` yourself (your units, on the root or a child),
|
|
38
|
+
and again in `update` to follow later writes. Content props and templates turn and size theirs.
|
|
43
39
|
|
|
44
40
|
## 2. How to change data
|
|
45
41
|
- Discrete changes (open a chest, switch growth stage, get picked up, change direction) use `W.set(id, { opened: true })`: it emits `world:change` and
|
|
46
42
|
re-evaluates `show`. Don't `set` every step. id / kind cannot be changed (to change the kind, remove then add).
|
|
47
43
|
- Things that change every step (position, timers, pathfinding state) are changed directly on the rec's fields inside simulate, and position with
|
|
48
44
|
`W.move`: no event, cheap.
|
|
49
|
-
- Both ways are saved (a save compares contents
|
|
50
|
-
`update`.
|
|
45
|
+
- Both ways are saved (a save compares contents). `move` emits no event: a picture that follows position compares in `update`.
|
|
51
46
|
- 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
47
|
- 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
48
|
throws immediately, in release too, and writes nothing.
|
|
54
49
|
|
|
55
50
|
## 3. Example: a crop grows on the calendar, press E to harvest when ripe
|
|
56
|
-
The key idea: **
|
|
57
|
-
player walked away, loaded a save, or fast-forwarded with `engine.step(60)`, the result is right, and no simulate is needed.
|
|
51
|
+
The key idea: **record `plantedAt = clock.now` and compute growth = now - planted time** instead of accumulating every step: right after walking away, a save load or `engine.step(60)`, with no simulate.
|
|
58
52
|
```js
|
|
59
53
|
import { presets, THREE } from 'threedog';
|
|
60
54
|
|
|
61
|
-
const GROW = 120;
|
|
62
|
-
const growth = rec => Math.min(1, (engine.clock.now - rec.plantedAt) / GROW);
|
|
55
|
+
const GROW = 120; // ripe after 120 calendar seconds (the unit of clock.now)
|
|
56
|
+
const growth = rec => Math.min(1, (engine.clock.now - rec.plantedAt) / GROW); // 0..1
|
|
63
57
|
const geo = new THREE.ConeGeometry(0.25, 0.8, 6);
|
|
64
58
|
|
|
65
59
|
engine.world.present('crop', {
|
|
66
60
|
build(rec) {
|
|
67
61
|
const m = new THREE.Mesh(geo, new THREE.MeshLambertMaterial({ color: 0x6aa84f }));
|
|
68
62
|
m.castShadow = true;
|
|
69
|
-
m.userData.use = engine.interactions.add(m, { label: 'Harvest', radius: 2, enabled: () => growth(rec) >= 1, onUse: () => harvest(rec) });
|
|
63
|
+
m.userData.use = engine.interactions.add(m, { label: 'Harvest', radius: 2, enabled: () => growth(rec) >= 1, onUse: () => harvest(rec) }); // can be harvested only when ripe
|
|
70
64
|
return m;
|
|
71
65
|
},
|
|
72
|
-
update(rec, obj) {
|
|
66
|
+
update(rec, obj) { // grows bigger, changes color when ripe
|
|
73
67
|
const g = growth(rec);
|
|
74
68
|
obj.scale.setScalar(0.3 + 0.7 * g);
|
|
75
69
|
obj.material.color.setHex(g >= 1 ? 0xe8a33d : 0x6aa84f);
|
|
76
70
|
},
|
|
77
|
-
dispose(rec, obj) { obj.userData.use.remove(); engine.remove(obj); },
|
|
71
|
+
dispose(rec, obj) { obj.userData.use.remove(); engine.remove(obj); }, // an interaction you registered yourself must be removed yourself
|
|
78
72
|
});
|
|
79
73
|
|
|
80
74
|
function harvest(rec) {
|
|
81
75
|
engine.inventory.add('carrot', 2);
|
|
82
|
-
engine.world.remove(rec.id);
|
|
76
|
+
engine.world.remove(rec.id); // delete the data after harvesting (the model goes with it). To "grow back after a while": world.set(rec.id, { plantedAt: engine.clock.now }); to hide temporarily: return false from show
|
|
83
77
|
}
|
|
84
78
|
|
|
85
79
|
// the player plants one: an op, because saved state changes only in a fixed step or an op (recipe 23 §5); a key, a button or a test runs it
|
|
@@ -147,8 +141,8 @@ avoidance), see recipe 02 "Changing behavior / custom behavior"; below is the pu
|
|
|
147
141
|
```js
|
|
148
142
|
engine.world.present('chicken', { build: rec => makeChicken() });
|
|
149
143
|
engine.world.simulate('chicken', {
|
|
150
|
-
near: (rec, dt) => wander(rec, dt),
|
|
151
|
-
far: (rec, dt) => wander(rec, dt),
|
|
144
|
+
near: (rec, dt) => wander(rec, dt), // near: a small step every fixed step
|
|
145
|
+
far: (rec, dt) => wander(rec, dt), // far: catch up once every farEvery seconds
|
|
152
146
|
farEvery: 2,
|
|
153
147
|
});
|
|
154
148
|
function wander(rec, dt) {
|
|
@@ -162,7 +156,7 @@ function wander(rec, dt) {
|
|
|
162
156
|
- **Near / far is decided by the gameplay anchor `world.anchor`**: by default the position of the player record (`engine.focus` when there is no
|
|
163
157
|
player). A cutscene or photo mode moves the camera away, but the player's surroundings are still simulated as near: gameplay results do not depend
|
|
164
158
|
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
|
-
- **The player is a record too**: the id and kind added by `
|
|
159
|
+
- **The player is a record too**: the id and kind added by `addPlayer` are both `'player'`; position, facing, motion state (vx, vz, vy, facing,
|
|
166
160
|
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
161
|
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
162
|
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`
|
|
@@ -179,7 +173,7 @@ function wander(rec, dt) {
|
|
|
179
173
|
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
174
|
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
175
|
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
|
+
own `present` and `positionFrom: 'view'` they are your fields, so read them there.
|
|
183
177
|
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
|
|
184
178
|
mm, so replays that must match exactly should not depend on physics props.
|
|
185
179
|
- Radius: present / simulate each take their own `radius` (meters or a function); without it they follow `world.radius` (default 60).
|
|
@@ -201,14 +195,14 @@ function wander(rec, dt) {
|
|
|
201
195
|
- The owed time and the simulation step count are saved: after loading they are caught up the same way, and the same save gives the same result
|
|
202
196
|
however many fixed steps run per frame. For things measured on the calendar (grows in a few days, respawns at a time), record `engine.clock.now` and compare.
|
|
203
197
|
- **Far in workers** (thousands of crops, spawners or machines): `W.simulate('crop', { far, worker: true })`. Each step's far batch runs in `engine.threads` workers and is written
|
|
204
|
-
back 4 fixed steps later through `
|
|
198
|
+
back 4 fixed steps later through `ctx.commits`; a late reply runs on the main thread, so threads on / off / slow give **bit-identical** records, and only fields far changed are written
|
|
205
199
|
back. `far` must be self-contained: it is recompiled from source and sees only `(rec, dt)` and globals like `Math`; an outside variable throws (also with `threads: false`, so you find
|
|
206
200
|
it in development). Limit: a save taken while a batch is in flight re-simulates that stretch after loading (equal within float tolerance, not bit-identical).
|
|
207
201
|
|
|
208
202
|
## 8. Querying nearby things
|
|
209
203
|
```js
|
|
210
204
|
let crowd = 0;
|
|
211
|
-
engine.world.forEachNear(engine.player, 5, (rec, d2) => { if (rec.kind === 'zombie') crowd++; });
|
|
205
|
+
engine.world.forEachNear(engine.player, 5, (rec, d2) => { if (rec.kind === 'zombie') crowd++; }); // no allocation, no sorting; world.query sorts nearest first and returns an array
|
|
212
206
|
```
|
|
213
207
|
For things that query neighbors every step (hundreds of zombies avoiding each other) use `forEachNear`; inside the callback don't add / remove / move,
|
|
214
208
|
note them down and change them after the loop.
|