threedog 0.1.0 → 0.2.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +4 -4
- package/core/Animator.js +1 -0
- package/core/Assets.js +28 -0
- package/core/DebugOverrides.js +143 -0
- package/core/Describe.js +14 -3
- package/core/Engine.js +44 -72
- package/core/Events.js +59 -1
- package/core/I18n.js +2 -2
- package/core/Inspect.js +12 -32
- package/core/InspectScene.js +7 -3
- package/core/MaterialInfo.js +32 -0
- package/core/Ops.js +43 -59
- package/core/Saves.js +5 -4
- package/core/UrlState.js +3 -2
- package/core/Vars.js +1 -0
- package/core/Views.js +49 -0
- package/core/actor.js +2 -2
- package/core/assetReport.js +83 -0
- package/core/catalog.js +169 -0
- package/core/checks.js +67 -0
- package/core/claims.js +51 -0
- package/core/debugView.js +76 -0
- package/core/describeRender.js +51 -0
- package/core/describeText.js +11 -4
- package/core/errorCodes.js +33 -0
- package/core/errorHints.js +6 -1
- package/core/grid.js +127 -0
- package/core/gridLoad.js +19 -0
- package/core/holds.js +106 -0
- package/core/lifecycle.js +1 -0
- package/core/lightWatch.js +23 -3
- package/core/look/coreParts.js +112 -0
- package/core/look/layers.js +136 -0
- package/core/look/part.js +173 -0
- package/core/look/report.js +79 -0
- package/core/look/write.js +86 -0
- package/core/loop.js +22 -16
- package/core/modules.js +19 -5
- package/core/opsAtomic.js +31 -0
- package/core/opsCheck.js +25 -14
- package/core/opsFail.js +20 -0
- package/core/opsHistory.js +6 -6
- package/core/opsRun.js +77 -0
- package/core/params.js +132 -0
- package/core/renamed.js +22 -0
- package/core/saveApply.js +2 -2
- package/core/sceneMethods.js +9 -34
- package/core/services.js +73 -0
- package/core/startup.js +3 -1
- package/core/styleParts.js +11 -9
- package/core/thingExplain.js +68 -0
- package/core/thingOps.js +35 -24
- package/core/things.js +15 -1
- package/core/util.js +11 -0
- package/core/validate.js +23 -7
- package/docs/AI.md +93 -114
- package/docs/API.md +8 -9
- package/docs/CODEMAP.md +67 -53
- package/docs/COMMANDS.md +21 -7
- package/docs/CONVENTIONS.md +22 -11
- package/docs/THREE.md +3 -3
- package/docs/api/assets.md +3 -0
- package/docs/api/characters.md +5 -2
- package/docs/api/collision.md +4 -0
- package/docs/api/content.md +1 -0
- package/docs/api/engine.md +23 -14
- package/docs/api/events.md +5 -1
- package/docs/api/post.md +5 -4
- package/docs/api/saves.md +2 -1
- package/docs/api/sky.md +3 -3
- package/docs/api/style.md +8 -8
- package/docs/api/tools.md +5 -2
- package/docs/api/vegetation.md +1 -0
- package/docs/api/weather.md +1 -1
- package/docs/recipes/01-new-game.md +41 -43
- package/docs/recipes/02-npc.md +38 -22
- package/docs/recipes/03-items-pickups.md +4 -4
- package/docs/recipes/04-quests.md +23 -23
- package/docs/recipes/05-props-bake.md +5 -5
- package/docs/recipes/06-clock-events.md +13 -0
- package/docs/recipes/07-flow-scenes-pause.md +6 -2
- package/docs/recipes/08-weather-sky.md +6 -6
- package/docs/recipes/09-style-pack.md +35 -100
- package/docs/recipes/12-navmesh.md +22 -0
- package/docs/recipes/13-animation.md +25 -6
- package/docs/recipes/14-custom-module.md +6 -7
- package/docs/recipes/15-perf.md +9 -1
- package/docs/recipes/16-dev-bridge.md +52 -18
- package/docs/recipes/18-world.md +5 -2
- package/docs/recipes/19-shooting-picking.md +9 -8
- package/docs/recipes/20-content-actions-save.md +10 -10
- package/docs/recipes/21-camera.md +51 -2
- package/docs/recipes/22-shop-gold.md +16 -16
- package/docs/recipes/23-ops.md +46 -10
- package/docs/recipes/27-net.md +3 -3
- package/docs/recipes/28-terrain.md +2 -2
- package/docs/recipes/29-grid.md +47 -27
- package/docs/recipes/34-environment-lighting.md +11 -10
- package/docs/recipes/35-style-from-reference.md +41 -46
- package/docs/recipes/36-sky-ground-plant-looks.md +22 -20
- package/docs/recipes/37-terrain-look-hooks.md +34 -13
- package/docs/recipes/38-environment-look-hooks.md +49 -42
- package/docs/recipes/40-scene.md +29 -0
- package/docs/recipes/41-thing-registry.md +29 -0
- package/docs/recipes/42-terrain-shape.md +1 -1
- package/docs/recipes/43-shader-patches-surface-looks.md +37 -20
- package/docs/recipes/44-water-weather-look-hooks.md +11 -9
- package/docs/recipes/45-cascaded-shadows.md +2 -2
- package/docs/recipes/46-blender-art-route.md +26 -4
- package/docs/recipes/47-island-snow-backdrop.md +4 -3
- package/docs/recipes/48-make-material.md +70 -0
- package/docs/recipes/49-game-module-contract.md +71 -0
- package/docs/recipes/50-own-renderer.md +12 -0
- package/docs/recipes/51-capability-catalog.md +63 -0
- package/docs/recipes/52-look.md +146 -0
- package/docs/recipes/53-ground-up-close.md +58 -0
- package/examples/action/GAMEMAP.md +7 -7
- package/examples/action/content/index.js +2 -1
- package/examples/action/content/views.js +6 -0
- package/examples/action/main.js +3 -2
- package/examples/sheepisland/GAMEMAP.md +3 -4
- package/examples/styletest/GAMEMAP.md +3 -3
- package/examples/styletest/content/npcs.js +1 -1
- package/examples/styletest/main.js +2 -2
- package/examples/styletest/panel.js +3 -3
- package/examples/world/GAMEMAP.md +3 -3
- package/examples/world/content/npcs.js +1 -1
- package/examples/world/main.js +1 -1
- package/index.d.ts +35 -2
- package/index.js +6 -3
- package/llms.txt +13 -7
- package/modules/ambience/Ambience.js +5 -2
- package/modules/camera/FirstPersonCamera.js +3 -5
- package/modules/camera/FixedCamera.js +19 -12
- package/modules/camera/FollowCamera.js +14 -8
- package/modules/camera/RtsCamera.js +3 -5
- package/modules/camera/common.js +40 -10
- package/modules/camera/index.js +1 -1
- package/modules/camera/projection.js +34 -0
- package/modules/characters/Character.js +45 -31
- package/modules/characters/assetModel.js +35 -7
- package/modules/characters/astar.js +14 -7
- package/modules/characters/index.js +6 -3
- package/modules/characters/movers/simple.js +6 -1
- package/modules/characters/npcSim.js +8 -2
- package/modules/characters/pathAsync.js +12 -6
- package/modules/characters/pathJob.js +2 -1
- package/modules/characters/proceduralRig.js +50 -11
- package/modules/characters/useModel.js +22 -0
- package/modules/characters/walkTo.js +58 -0
- package/modules/collision/Collision.js +102 -4
- package/modules/content/explain.js +13 -0
- package/modules/content/index.js +3 -1
- package/modules/content/loader.js +3 -0
- package/modules/content/rules.js +1 -0
- package/modules/debug/DebugPanel.js +11 -5
- package/modules/entities/Entities.js +6 -2
- package/modules/flow/index.js +5 -2
- package/modules/gameplay/Dialogue.js +5 -2
- package/modules/gameplay/Interactions.js +12 -2
- package/modules/gameplay/Inventory.js +21 -11
- package/modules/gameplay/Quests.js +13 -3
- package/modules/gameplay/pickups.js +6 -4
- package/modules/grid/Layer.js +1 -1
- package/modules/grid/index.js +1 -1
- package/modules/grid/tiles.js +9 -5
- package/modules/hlod/index.js +5 -2
- package/modules/hud/index.js +5 -2
- package/modules/level/index.js +5 -3
- package/modules/lights/index.js +5 -2
- package/modules/music/Music.js +6 -2
- package/modules/nav/index.js +5 -3
- package/modules/net/Client.js +4 -3
- package/modules/net/Host.js +2 -2
- package/modules/net/index.js +5 -3
- package/modules/particles/Particles.js +1 -1
- package/modules/photo/Photo.js +10 -7
- package/modules/rigid/RigidBodies.js +5 -2
- package/modules/settings/Settings.js +6 -3
- package/modules/settings/apply.js +2 -1
- package/modules/sky/Sky.js +21 -19
- package/modules/sky/cascades.js +6 -6
- package/modules/sky/domeLayers.js +1 -1
- package/modules/sky/environment.js +39 -13
- package/modules/sky/fog.js +9 -6
- package/modules/sky/frame.js +4 -3
- package/modules/sky/look.js +3 -2
- package/modules/sky/lookFog.js +80 -0
- package/modules/sky/lookShadow.js +50 -0
- package/modules/sky/lookSky.js +108 -0
- package/modules/sky/shader.js +2 -2
- package/modules/sky/shadow.js +4 -10
- package/modules/sky/skyModule.js +4 -3
- package/modules/terrain/ChunkManager.js +2 -33
- package/modules/terrain/chunkLevels.js +40 -0
- package/modules/terrain/index.js +10 -2
- package/modules/terrain/lookGround.js +61 -0
- package/modules/timeline/Timeline.js +7 -3
- package/modules/timeline/Tween.js +3 -7
- package/modules/timeline/shots.js +6 -4
- package/modules/triggers/index.js +9 -2
- package/modules/vegetation/Vegetation.js +17 -4
- package/modules/vegetation/index.js +7 -4
- package/modules/vegetation/lookWind.js +37 -0
- package/modules/vegetation/nearFade.js +39 -0
- package/modules/water/Water.js +19 -3
- package/modules/water/look.js +80 -0
- package/modules/weather/Weather.js +22 -31
- package/modules/weather/look.js +75 -0
- package/modules/weather/particles.js +1 -1
- package/modules/weather/strings.js +15 -0
- package/modules/world/explain.js +11 -0
- package/modules/world/index.js +11 -4
- package/modules/world/thingSource.js +44 -0
- package/package.json +2 -1
- package/render/PostFX.js +48 -51
- package/render/detail.js +39 -15
- package/render/effects.js +4 -2
- package/render/fuse.js +12 -0
- package/render/lights.js +4 -2
- package/render/lookSurface.js +161 -0
- package/render/materials.js +27 -10
- package/render/postLook.js +86 -0
- package/render/surface.js +3 -1
- package/types/core.d.ts +223 -29
- package/types/gameplay.d.ts +22 -6
- package/types/generated/core/DebugOverrides.d.ts +52 -0
- package/types/generated/core/Events.d.ts +43 -0
- package/types/generated/core/Ops.d.ts +62 -21
- package/types/generated/core/Saves.d.ts +1 -0
- package/types/generated/core/Views.d.ts +33 -0
- package/types/generated/modules/debug/DebugPanel.d.ts +2 -2
- package/types/generated/modules/grid/Layer.d.ts +1 -0
- package/types/generated/modules/sky/Sky.d.ts +10 -17
- package/types/generated/modules/weather/Weather.d.ts +5 -15
- package/types/generated/render/PostFX.d.ts +20 -23
- package/types/generated/render/materials.d.ts +10 -0
- package/types/physics.d.ts +8 -0
- package/types/style.d.ts +35 -20
- package/types/world.d.ts +7 -1
- package/ui/Parts.js +6 -2
- package/ui/UI.js +1 -1
- package/ui/defaults.js +1 -1
- package/docs/api/debug.md +0 -10
|
@@ -55,3 +55,25 @@ engine.characters.pathsPerStep = 64; // requests sent per fixed step (
|
|
|
55
55
|
`createEngine({ movement: { radius, height, maxSlope, stepHeight } })` sets it once; read it as `engine.movement`. Collision, the Rapier capsule, the
|
|
56
56
|
navmesh, A* and level steps all read it, so a module never writes its own 0.4 or 0.45. A character's position belongs to its mover: other systems
|
|
57
57
|
request movement (`placeAt`, `move`, vehicle `enter`) and never set `player.position`.
|
|
58
|
+
|
|
59
|
+
## Fences and rivers (collision)
|
|
60
|
+
|
|
61
|
+
Walls and water that are not meshes: `engine.collision.addSegment(a, b, { thickness })` is a thin wall along a line; `addBlocked(fn)` marks ground impassable where `fn(x, z)` is true. Both return `{ remove() }` and are free when unused.
|
|
62
|
+
|
|
63
|
+
```js
|
|
64
|
+
// A river along x 5..9 with a bridge at z -1..1: the bridge is just a hole in the blocked function
|
|
65
|
+
engine.collision.addBlocked((x, z) => x > 5 && x < 9 && !(z > -1 && z < 1), { bounds: { minX: 5, maxX: 9, minZ: -50, maxZ: 50 } });
|
|
66
|
+
// A fence with a gate: two segments, the gap between them is the gate
|
|
67
|
+
engine.collision.addSegment([-18, 0, -12], [-18, 0, -4]);
|
|
68
|
+
engine.collision.addSegment([-18, 0, 0], [-18, 0, 12], { thickness: 0.4 });
|
|
69
|
+
```
|
|
70
|
+
|
|
71
|
+
Walkers stop at the edge and slide along it; `collision.walkable()` and A* pathing, sync and async, see both. `fn` must be pure and deterministic (no clock, no random). Async paths cannot send a function to the worker, so `fn` is sampled into the 1 m ground raster instead (re-sampled when you add or remove a field): give `bounds`, or every requested tile is sampled in full. Navmesh mode (`nav()` installed) does not see `addBlocked`; use `addSegment` or bake the river into the mesh there.
|
|
72
|
+
|
|
73
|
+
## Line of sight and straight-line checks: collision.lineClear
|
|
74
|
+
`engine.collision.lineClear(a, b, { radius })` answers "is anything solid between a and b?" for a 3D segment: boxes, circles and terrain trees, with heights (a 1 m wall does not block a sight line 3 m above it; a collider's `y` / `height` count). It is a boolean; `addBlocked` water is ignored. Give eye heights in `a` / `b`; `radius` fattens the line (pass the character radius for "can I walk straight there").
|
|
75
|
+
```js
|
|
76
|
+
const sees = engine.collision.lineClear([guard.x, 1.6, guard.z], [player.x, 1.6, player.z]); // true = clear view
|
|
77
|
+
const straight = engine.collision.lineClear(me.position, goal, { radius: engine.movement.radius });
|
|
78
|
+
```
|
|
79
|
+
The A* fallback smooths paths with the same idea: it samples each shortcut at most one character radius apart (so a thin fence cannot be skipped), starts from the character's real position, and its cell size follows `radius` (1-2 m) unless you pass `step`.
|
|
@@ -59,17 +59,33 @@ engine.characters.createPlayer({ ...presets.player.thirdPerson, model: hero, ani
|
|
|
59
59
|
```
|
|
60
60
|
The default transition time comes from the style pack's `style.character.animation.fade`.
|
|
61
61
|
|
|
62
|
-
**By asset name.** `model` also takes the name of a registered model asset,
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
registered names; a failed load keeps the placeholder and warns once; a character disposed before loading ends never gets the model.
|
|
62
|
+
**By asset name.** `model` also takes the name of a registered model asset: a file model, or a procedural builder. The character is built at once
|
|
63
|
+
with a gray capsule; when the asset loads, a skeleton-correct copy replaces it under the same root, so position, facing, state, collision and the
|
|
64
|
+
world view stay. Then `ready` turns true, `whenReady` settles and `character:model` is emitted. A name no model asset has throws with the registered
|
|
65
|
+
names; a failed load keeps the capsule and warns once; a character disposed before loading ends never gets the model.
|
|
67
66
|
```js
|
|
68
67
|
engine.assets.manifest({ models: { hero: '/models/hero.glb' } });
|
|
69
|
-
const p = engine.characters.createPlayer({ ...presets.player.thirdPerson, model: 'hero' }); //
|
|
68
|
+
const p = engine.characters.createPlayer({ ...presets.player.thirdPerson, model: 'hero' }); // capsule now, the hero once loaded
|
|
70
69
|
await p.whenReady; // p.anim is set from here (unless the load failed)
|
|
71
70
|
```
|
|
72
71
|
|
|
72
|
+
## 3b. Procedural bodies are assets too (`model: 'humanoid'`)
|
|
73
|
+
Character bodies are assets, never style: every character picks one with `model`, the same path for a GLB and a procedural builder. an asset
|
|
74
|
+
pack can supply a code-built humanoid (e.g. box limbs, swung by the engine while walking, running, swimming, jumping); a builder is built at once, so its joints
|
|
75
|
+
(`player.armL`, `legR`...) exist right after `createPlayer`. Without `model` (and without `rig`) a character is a gray capsule, warned once.
|
|
76
|
+
```js
|
|
77
|
+
import { assets } from './assets.js'; // an asset pack of yours (or a published one) with a 'humanoid' builder
|
|
78
|
+
engine.assets.manifest(assets);
|
|
79
|
+
engine.characters.createPlayer({ ...presets.player.thirdPerson, model: 'humanoid' });
|
|
80
|
+
engine.npcs.add({ id: 'fisher', model: 'humanoid', colors: { body: 0x4f6d8f } }); // per-character part colors
|
|
81
|
+
```
|
|
82
|
+
- **Colors**: the humanoid's parts use material roles `cloth`, `skin`, `trousers`, `hair`, so any style pack tints every humanoid
|
|
83
|
+
(`style: [basePack, { materials: { cloth: { color: 0x3a6ea5 } } }]`); `colors: { body, skin, legs, hair }` recolors one character.
|
|
84
|
+
- **Your own procedural body**: a builder that returns an Object3D with `root.userData.rig = { body: 'hips', head: 'head', joints: ['armL'],
|
|
85
|
+
limbs: [{ joint: 'legL', offset: 0, amp: 0.9, kind: 'leg' }] }` (object names, so it survives copies and baking) animates like the humanoid; mark
|
|
86
|
+
meshes `userData.part = 'body'` for `colors`. A hand-built one-off passes `{ rig }` instead ([02-npc](02-npc.md)).
|
|
87
|
+
- The old `style.character.create` / `.model` / `.colors` throw `renamed-api` ([52-look](52-look.md#renamed-in-02)).
|
|
88
|
+
|
|
73
89
|
## 4. Non-character objects (a dog, a windmill, a door)
|
|
74
90
|
```js
|
|
75
91
|
const dog = await engine.assets.model('dog'); engine.add(dog);
|
|
@@ -133,6 +149,9 @@ engine.onFixed(() => { // one call
|
|
|
133
149
|
Use `anim:end` only for presentation (change an expression, play the next clip). Native objects: `anim.mixer` (AnimationMixer), `anim.actions` (clip
|
|
134
150
|
name -> AnimationAction). Things without a skeleton that only move/rotate as a whole use `engine.timeline.tween`, not an Animator.
|
|
135
151
|
|
|
152
|
+
Bones after the pose: `const h = player.onPose((c, dt) => { sword.position.copy(hand.getWorldPosition(v)); })` runs every frame right after the character's pose is
|
|
153
|
+
applied (clips or procedural rig); `h.remove()` stops it. Presentation only.
|
|
154
|
+
|
|
136
155
|
## 6. Verify
|
|
137
156
|
- `anim.describe()` -> `{ state, clip, time, progress, driven, t, weights }` (clip seconds, 0-1 progress, whether sync drives it, the last gameplay t,
|
|
138
157
|
each fading state's share); the player's is in `describe().player.anim`.
|
|
@@ -1,7 +1,8 @@
|
|
|
1
1
|
# Custom module
|
|
2
2
|
|
|
3
|
-
When to write a module: a "mechanic" that has its own state, per-frame logic and saving,
|
|
4
|
-
|
|
3
|
+
When to write a module: a "mechanic" that has its own state, per-frame logic and saving (stamina, a heat meter, wave spawning, oxygen, a combo
|
|
4
|
+
counter). The contracts every module should follow (state, game time, skip, describe, ops) and a second copyable module are in
|
|
5
|
+
`49-game-module-contract.md`; this page is the template and the hook cheat sheet. Something that belongs to one game only goes in `games/<game>/`;
|
|
5
6
|
a general one goes in `modules/<name>/index.js` inside the engine and is exported from the engine's `index.js` (then the three hard rules apply: no
|
|
6
7
|
hard-coded art or text, no importing another module's internal files).
|
|
7
8
|
|
|
@@ -20,7 +21,7 @@ export function stamina(opts = {}) {
|
|
|
20
21
|
restore(n) { api.value = Math.min(max, api.value + n); },
|
|
21
22
|
};
|
|
22
23
|
return {
|
|
23
|
-
name: 'stamina', label: '
|
|
24
|
+
name: 'stamina', label: 'Stamina', requires: ['characters'], optional: ['hud'], stage: 'gameplay', // once installed, engine.stamina === api
|
|
24
25
|
install(engine) {
|
|
25
26
|
e = engine;
|
|
26
27
|
e.i18n.add({ 'zh-CN': { 'stamina.label': '体力' }, en: { 'stamina.label': 'Stamina' } }); // don't hard-code UI text
|
|
@@ -49,7 +50,7 @@ Install it: `engine.use(openWorld({ camera: 'follow', ...}), stamina({ max: 80 }
|
|
|
49
50
|
what the loaded state needs nearby, with gameplay frozen until it resolves.
|
|
50
51
|
- `fixed(dt, e)` movement, timing, gameplay keys (`input.pressed` read in fixed is this step's snapshot, independent of frame rate); `frame(dt, e)`
|
|
51
52
|
animation, camera, UI (it reads this frame's latest input); `afterRender(dt, e)` after rendering.
|
|
52
|
-
- `describe(e, ctx)`:
|
|
53
|
+
- `describe(e, ctx)`: see recipe 49 contract 4; `ctx.near(object or {x,z}, { name, kind })` reports things nearby. `skip(dt, e, done)`: recipe 49 contract 3.
|
|
53
54
|
- `applyState(e, p)`: called by `engine.applyState` / URL parameters; it only receives the keys `time`, `weather` and `cutscene`.
|
|
54
55
|
- `stage`: when the hooks run (first -> last): `control` timeline, camera -> `world` terrain, level -> `environment` weather, sky, water -> `gameplay`
|
|
55
56
|
interactions, dialogue, entities -> `presentation` particles, objective markers -> `late` (the default) characters, physics -> `audio` music. Within
|
|
@@ -69,9 +70,7 @@ Install it: `engine.use(openWorld({ camera: 'follow', ...}), stamina({ max: 80 }
|
|
|
69
70
|
`document.body`).
|
|
70
71
|
The `dispose(e)` hook only collects what the core can't, such as Workers, the physics world and real-time timers, and is called in reverse install order.
|
|
71
72
|
- While frozen (`engine.freeze`, flow pause) `fixed` is skipped entirely and `frame` still runs: check `e.frozen` before gameplay decisions.
|
|
72
|
-
- Changing what a saved part looks like:
|
|
73
|
-
`e.saves.register('stamina', { version: 2, migrate: { 1: v => ({ value: v }) }, save, load })`. `load` only ever sees the current shape; a save
|
|
74
|
-
written by a newer build is refused (load returns false, the save is kept).
|
|
73
|
+
- Changing what a saved part looks like: `version` + `migrate` (recipe 49 contract 1). A save written by a newer build is refused (load returns false).
|
|
75
74
|
- Saved state the module writes joins the ops guard (experimental): `e.ops.guard('stamina.set')` in each writing method (a no-op in production builds,
|
|
76
75
|
no DEV check needed), `e.ops.allow(fn)` around writes that are allowed anyway (recipe 23 section 5).
|
|
77
76
|
- **Per-playthrough state** (one hook for every module): state that is not a save part but belongs to the current playthrough (an open dialogue, a
|
package/docs/recipes/15-perf.md
CHANGED
|
@@ -52,7 +52,7 @@ and they get timed.
|
|
|
52
52
|
| Symptom | Fix |
|
|
53
53
|
|---|---|
|
|
54
54
|
| Many draw calls | Use `vegetation` / InstancedMesh for repeated objects; install `hlod()` for a block of buildings; share geometry and materials between copies of a model (`assets.model` shares by default) |
|
|
55
|
-
| Expensive shadows | Style pack `sky.shadow.updateEvery: 3` (update every 3 frames), reduce `mapSize`/`extent`; filter `createEngine({ shadowType: 'basic' })` (hard edge, cheapest) / `'pcf'` (default) / `'vsm'` (softest, costliest), switch live with `engine.
|
|
55
|
+
| Expensive shadows | Style pack `sky.shadow.updateEvery: 3` (update every 3 frames), reduce `mapSize`/`extent`; filter `createEngine({ shadowType: 'basic' })` (hard edge, cheapest) / `'pcf'` (default) / `'vsm'` (softest, costliest), switch live with `engine.look.shadow.set({ type: 'vsm', radius: 3 })` (radius: pcf and vsm only; blurSamples: vsm only; a switch recompiles materials, so avoid doing it every frame); the vegetation species option `shadowRing` (default 1) sets within how many chunk rings it casts shadows; change it while playing with `engine.vegetation.setShadowRing('tree', 0)` |
|
|
56
56
|
| Stutter while walking | Put generation work in `engine.jobs.add(function* () { ...; yield; })` or `engine.stream.add`; chunk upload budget `engine.terrain.applyBudgetMs` |
|
|
57
57
|
| Slow start | Look at which is slowest in `engine.startup.modules`; `npm run bake` for large models; preload only the necessary assets |
|
|
58
58
|
| Slow physics | Keep dynamic rigid bodies within a few hundred (the `rigidBodies` budget); `rigid({ terrainRing: 1 })` |
|
|
@@ -72,6 +72,14 @@ false = all on the main thread, same results.
|
|
|
72
72
|
- `engine.threads.pure(fn)` / `world.simulate(..., { worker: true })`: the function is recompiled from its source, so it cannot capture outside
|
|
73
73
|
variables or imports; put constants inside it. A bad outside variable is reported by name on the first call.
|
|
74
74
|
|
|
75
|
+
## 4b. Render scale (resolution) is never lowered silently
|
|
76
|
+
- 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.
|
|
77
|
+
- Adaptive resolution (`createEngine({ adaptiveResolution, targetFps })`, default on, floor 0.6) lowers the scale by 0.1 per second under the target fps. The first
|
|
78
|
+
time it does, dev builds warn once: `render scale X -> Y because fps Z ...; turn off with adaptiveResolution: false`. It is the only thing lowered automatically
|
|
79
|
+
(shadows and post are never traded first).
|
|
80
|
+
- `describe().render.scale`: `{ current, devicePixelRatio, upscaled, autoLowered, adaptive, floor, max }`. `upscaled: true` means current < devicePixelRatio, the picture
|
|
81
|
+
is softer than the screen: if that looks wrong in a screenshot, check this before the style. Fixed quality: `pixelRatio: n` plus `adaptiveResolution: false`.
|
|
82
|
+
|
|
75
83
|
## 5. Verify (once before and once after, under the same conditions)
|
|
76
84
|
- `npm run perf` (native vs engine vs per-module cost of openWorld), compared with the tables in `../PERF.md`; differences under 10-30% are noise.
|
|
77
85
|
- Compare a specific scenario: `npm run shot -- / --pos x,z --time 12:00 --describe-only` to see draw calls and triangles.
|
|
@@ -19,32 +19,35 @@ game only advances on step); once you open the page in a browser, commands go to
|
|
|
19
19
|
| `describe` | One-line scene summary: position / time and weather / nearby / quest | `player (4.0, 7.0) in forest · 07:11 day 1 · clear` |
|
|
20
20
|
| `describe --full` | The state as text, summary first (`engine.describeText()`: at most 30 lines, the nearest things, one line per module with its key counts, and a last line on how to expand). Details: `describe <path>` for one part, `engine.describeText({ full: true })` for everything | `quests: active[1], done=0, failed=0` |
|
|
21
21
|
| `describe --all` | Everything: every nearby thing and every module's full data (`describeText({ full: true })`); large, prefer a path | |
|
|
22
|
+
| `describe render` | How the picture is set: tone mapping, exposure, shadow filter, post effects with params, default lights, each tagged `engine` (default), `style` or `game` (changed after). Also the `renderer:` lines of `describe --full`. Information only, never warns | `{ "toneMapping": { "value": "aces", "by": "style" }, ... }` |
|
|
22
23
|
| `describe player.position` | Player coordinates { x, y, z } (numbers) | `{ "x": 4, "y": 1.2, "z": 7 }` |
|
|
23
24
|
| `describe player.state` | Just one item of `engine.describe()` (dotted path, `--max characters`) | `"idle"` |
|
|
24
25
|
| `step 2` | Advance 2 game seconds (deterministic; a real-time page is paused first) | `✓ Stepped 2 s · player (4.0, 7.0) in forest · 07:20 day 1` |
|
|
25
|
-
| `press interact` | Press an action name or key once (`KeyE`, `e`, `Escape`). **It advances game time**: 0.1 s held + one rendered frame of 1/60 s, about 0.117 s in total;
|
|
26
|
+
| `press interact` | Press an action name or key once (`KeyE`, `e`, `Escape`). **It advances game time**: 0.1 s held + one rendered frame of 1/60 s, about 0.117 s in total; shorten the hold with `--for 0.02` when timing matters | `✓ Pressed menu (Escape) · … · window open: settings` |
|
|
26
27
|
| `hold moveForward 1.5` | Hold for 1.5 seconds | `✓ Held moveForward (KeyW) for 1.5 s · player (-0.6, 3.0) …` |
|
|
27
|
-
| `
|
|
28
|
-
| `
|
|
29
|
-
| `
|
|
30
|
-
| `
|
|
31
|
-
| `
|
|
32
|
-
| `explain op
|
|
28
|
+
| `skip to=06:00` / `skip seconds=600` | Jump the clock like sleeping (`engine.skip`) | `✓ Skipped to 06:00 → 21600 · … 06:00 day 2` |
|
|
29
|
+
| `ops` | What the player can do now: every op offer checked with `can` (`recipes/23-ops.md`) | `✓ shop.buy item=medkit · ✗ shop.buy item=ammo (soldOut)` |
|
|
30
|
+
| `op shop.buy shop=trader item=medkit n=2` | Run a game op (source `bridge`, **no time passes**). Values follow the op's `args` shape (`n=2` a number, `position=3,0,-2` an array). **Change state with this, not `js`**: `js` writes skip the op log | `✓ shop.buy → 2 · Bag gold×2 medkit×2` / `✗ shop.buy: noMoney (Not enough gold)` |
|
|
31
|
+
| `inspect` / `inspect npc_3` / `inspect 10,-4` | What is around the player and which ops it can do now, with reasons (`engine.inspect`, recipes/23-ops.md section 8) | `player at (4, 7) · near: guard 1 m` / `✗ shop.buy shop=trader item=ammo (soldOut: …)` |
|
|
32
|
+
| `pick 480,270` | What is at that screen pixel: record id, kind, template, the content file and line that defines it, its fields (recipes/30-templates.md section 5) | `✓ chest-home (kind chest, template chest) …` / `defined in content/props.js:14: edit it there …` |
|
|
33
|
+
| `explain op shop.buy shop=trader item=ammo` / `explain quest my-quest` | Why an op cannot run now (the reason and the op's note on fixing it first; `--full` adds the last attempt and events around it), or where a quest is stuck (`engine.explain`) | `✗ shop.buy {...} cannot run now: noMoney (Not enough gold)` |
|
|
33
34
|
| `scenario barter` | Run `tests/scenarios/barter.json` (recipes/23-ops.md section 7); prints failed checks, leaves it paused | `✓ barter: 6 checks passed` |
|
|
34
35
|
| `state time=18:30 weather=rain pos=40,-20` | Set the scene (like URL parameters: time weather pos save wait cutscene state) | `✓ Set · 18:30 day 1 · rain` |
|
|
35
|
-
| `js "engine.sky.timeOfDay"` (alias `eval`) | Evaluate an expression in the page; `engine` is available directly and `await` works inside; multi-line statements need their own `return` (e.g. `js "const p = engine.player.position; return p.x + p.z"`).
|
|
36
|
+
| `js "engine.sky.timeOfDay"` (alias `eval`) | Evaluate an expression in the page; `engine` is available directly and `await` works inside; multi-line statements need their own `return` (e.g. `js "const p = engine.player.position; return p.x + p.z"`). Long scripts: `js --file script.js` | `✓ 0.77` |
|
|
36
37
|
| `snap name` | Screenshot to `.threedog/shots/name.png` | `✓ Screenshot .threedog/shots/t1.png (163 KB)` |
|
|
37
38
|
| `snap-describe save` / `snap-describe diff` + name | Describe snapshot instead of a screenshot: save the gameplay part of `describe()` as a baseline, or print how the running page differs from it (section 7) | `✗ describe "market" differs from the baseline in 1 place:` |
|
|
38
|
-
| `errors` | Page errors added since last time (
|
|
39
|
-
| `loading` / `loading hero` | What loading waits for, what failed (file, HTTP status, fallback) and whether it blocks the start;
|
|
39
|
+
| `errors` | Page errors added since last time (full log: `.threedog/errors.log`). Known classes get a cause + recipe line (section 8) | `✗ 1 new error` / `✗ 3 new errors` / `✓ No new errors` |
|
|
40
|
+
| `loading` / `loading hero` | What loading waits for, what failed (file, HTTP status, fallback) and whether it blocks the start; works while `start()` is stuck. With a name: that task with its manifest and path (`recipes/05-props-bake.md` section 3) | `… waiting: decoding model "hero" (…)` / `✗ Loading finished, 4/5 ok, 1 failed` |
|
|
40
41
|
| `reload` / `resume` | Reload the page / resume real-time running | |
|
|
41
42
|
|
|
42
43
|
## 2. Notes
|
|
43
|
-
- **Smallest scenario** (`tests/scenarios/coins.json
|
|
44
|
+
- **Smallest scenario** (`tests/scenarios/coins.json` <!-- r18-ignore-line -->, then `npx threedog verify coins` or `scenario coins`; `verify` with no file says "Have: none"):
|
|
44
45
|
`{ "name": "coins", "url": "/", "state": { "pos": "6,4" }, "steps": [ { "step": 1 }, { "expect": { "inventory.items.coin": 1 } } ] }`
|
|
45
46
|
- **Teleport + `step 1` collects `auto` pickups** (`state pos=`, `player.placeAt`): the pickup check runs in the fixed step after any move.
|
|
46
|
-
- **`shot` always starts a fresh game** (
|
|
47
|
-
- **`step` / `press` pause the real page
|
|
47
|
+
- **`shot` always starts a fresh game** (`?save=slot1` loads one); after playing use `snap name`. `shot --keep` adds a timestamp to the file name (no overwrite); `shot --look` prints mean luminance / saturation and the share of overexposed (>=250) and dark (<=20) pixels.
|
|
48
|
+
- **`step` / `press` pause the real page**; resume with `npx threedog resume` when done (they pause as owner `threedog`, so a game's own pause stays). A headless page only advances on step anyway.
|
|
49
|
+
- **Run state** is printed after `step` / `press` / `skip` / `resume` and by `npx threedog status`: `running`, `title-frozen` (title screen waiting for start), `test-paused` (only the bridge paused it), `paused(by owners)` (every `pause` / `freeze` owner, e.g. `ui-inventory`) or `loading`. The same object is `engine.runState` and `describe().time.run`: `{ state, by, blockedBy }`, where `blockedBy` lists what keeps input from driving the game (opaque input contexts such as `win-settings`, `ui-title`, `dialogue`, `cutscene`, plus `error` and `loading`); the bridge and the MCP tools copy it as-is. A test that pauses passes `pause(owner, { kind: 'test' })` to read as `test-paused`.
|
|
50
|
+
- **Who holds what**: `describe().time.heldBy` lists every pause, freeze, camera and debug-view holder in one shape `[{ owner, at }]` (`at` = file:line of the first take), so a stuck pause or a camera nobody gave back has a name.
|
|
48
51
|
- **`snap` on a real page captures only the canvas** (not the HTML UI); on a headless page it captures the whole page. To see UI state use `describe`
|
|
49
52
|
(`ui.windows`, dialogue).
|
|
50
53
|
- **Keys go through `engine.input` like a real keyboard**: action names are translated to keyboard keys (gamepad buttons are ignored); when a window
|
|
@@ -53,7 +56,7 @@ game only advances on step); once you open the page in a browser, commands go to
|
|
|
53
56
|
works with `engine.step`): `engine.input.simulate('jump'); engine.step(1 / 60); engine.input.simulate('jump', false)`. Never call `_keyDown` /
|
|
54
57
|
`_keyUp` (internal).
|
|
55
58
|
- `describe` by default gives only the 3 nearest things and the first quest; for detail use a path (`quests.active`, `nearby`, `world`) or `--full`;
|
|
56
|
-
|
|
59
|
+
|
|
57
60
|
- Several pages: `--page /<page>.html` picks the path; `-w name` picks the workspace.
|
|
58
61
|
- To change the port: `npm run dev -- my-game --port 5000`; the CLI finds the port from `.threedog/dev.json`, so you don't need to specify it again.
|
|
59
62
|
- If a command never becomes ready: most likely `main.js` doesn't set `window.engine = engine;` (it must come before `await engine.start()`). Under
|
|
@@ -61,6 +64,20 @@ game only advances on step); once you open the page in a browser, commands go to
|
|
|
61
64
|
has `window.engine`, `engine.ready`, and the latest page errors.
|
|
62
65
|
- Error messages give the cause and the next step, e.g. "no running dev server -> run npm run dev first".
|
|
63
66
|
|
|
67
|
+
## 2b. A scripted playthrough, and three kinds of check
|
|
68
|
+
```
|
|
69
|
+
npx threedog state pos=0,0 time=12:00 # known start
|
|
70
|
+
npx threedog hold moveForward 1.5 # walk (real key path, advances 1.5 s)
|
|
71
|
+
npx threedog press interact # one key press (~0.117 s)
|
|
72
|
+
npx threedog step 2 # let things happen
|
|
73
|
+
npx threedog js "engine.player.position.x > 1" # state assertion: read the ✓ true / false
|
|
74
|
+
npx threedog snap after-walk # only now look at pixels
|
|
75
|
+
```
|
|
76
|
+
The same steps as a file: `tests/scenarios/<name>.json` with `{ "press": … }`, `{ "step": … }`, `{ "expect": { path: value } }` (section 9; no `hold` there).
|
|
77
|
+
- **State checks** (`op`, `expect`, `describe`, `js`): fast and exact, but they skip input. They prove rules, not that the player can reach them.
|
|
78
|
+
- **Simulated-input checks** (`press`, `hold`, `engine.input.simulate`): bridge key events through the game's input path, never a physical keyboard/mouse. `verify` prints `Layers: direct N, simulated-input N, real-browser-input 0 (not verified), visual 0`, then an **Evidence** block (each check's layer and what it asserted), a fixed **NOT proven** line (pointer lock and mouse look, real GPU/visuals, real FPS) and **Coverage** (ops run vs defined, refused ops counted as run and marked; modules in three groups: tested = an op ran, indirect = no op but describe section compared / save part changed / events fired, untested; lists capped at 10 with "+N more"; uses `engine.catalog()`). `threedog scenario` prints the same Coverage block; the full lists are in `--json` (`data.evidence.coverage`, `data.coverage`). Not yet covered: content ids (defined vs touched).
|
|
79
|
+
- **Visual checks** (`snap`, `shot --look`): the only ones that see the look (exposure, color, UI overlap). Slowest; take them last.
|
|
80
|
+
|
|
64
81
|
## 3. Windows / PowerShell notes
|
|
65
82
|
- **Quote commas**: PowerShell splits `pos=1,-8` into two arguments and the coordinates become NaN. Write `npx threedog state "pos=1,-8"` (the bridge
|
|
66
83
|
reports an error and shows this tip when pos is not two numbers).
|
|
@@ -71,6 +88,21 @@ game only advances on step); once you open the page in a browser, commands go to
|
|
|
71
88
|
- Some terminal sandboxes (Bash) block commands containing the word `eval`: use `js`, not `eval`.
|
|
72
89
|
- Paths containing Chinese characters are fine; inside the game folder you can omit `-w`.
|
|
73
90
|
|
|
91
|
+
## 3b. Speed, a session, and checks in one call
|
|
92
|
+
|
|
93
|
+
Where the time goes: `npx` itself costs about 2.5 s on Windows (npm starts, resolves the bin) before threedog runs. Measured on the engine example, per command: `npx threedog describe` 3.2 s; `node node_modules/@threedog/tools/bin/threedog.mjs describe` 0.5 s; with a session 0.4 s (node start alone is 0.27 s).
|
|
94
|
+
|
|
95
|
+
- For a many-step test call the bin directly (`node node_modules/@threedog/tools/bin/threedog.mjs ...`, or `node_modules/.bin/threedog`) instead of `npx`.
|
|
96
|
+
- `npx threedog session` starts a background process that serves later commands; it exits after 10 idle minutes (`--minutes N`), `session stop` ends it. Commands behave identically with or without it.
|
|
97
|
+
- `threedog js --file steps.js`: put the whole test in one file and run it once. Inside: `assert(cond, msg)`, `expect(v).toBe(x)` (also `toEqual`, `toBeCloseTo(x, tol)`, `toBeGreaterThan`), `step(seconds)`, `log(...)`, and `engine`. The output is only the failures and one summary line, exit code 1 on failure, so ten steps cost one round trip and a few tokens:
|
|
98
|
+
|
|
99
|
+
```js
|
|
100
|
+
step(2);
|
|
101
|
+
const before = engine.tick;
|
|
102
|
+
step(1);
|
|
103
|
+
expect(engine.tick).toBeGreaterThan(before, 'time advanced');
|
|
104
|
+
```
|
|
105
|
+
|
|
74
106
|
## 4. Let describe see the game's own state
|
|
75
107
|
A game's own state (score, number of targets, crops) is not in `describe` by default. **Small games use this**: register it in one line, no module needed:
|
|
76
108
|
```js
|
|
@@ -126,10 +158,11 @@ data, duplicate ids, unknown option / name, module order, asset 404, ...) get th
|
|
|
126
158
|
combination so tests and scenarios reuse it.
|
|
127
159
|
|
|
128
160
|
## 10. MCP server: Claude Code, Cursor and other MCP clients
|
|
129
|
-
`npx threedog mcp` runs the dev bridge as an MCP server over stdio. Each command becomes a tool (`describe`, `step`, `press`, `hold`, `state`, `ops`,
|
|
130
|
-
`op`, `inspect`, `pick`, `explain`, `errors`, `loading`, `snap`, `snap_describe`, `scenario`, `reload`, `resume
|
|
131
|
-
|
|
132
|
-
|
|
161
|
+
`npx threedog mcp` runs the dev bridge as an MCP server over stdio. Each command becomes a tool (`play`, `status`, `describe`, `step`, `press`, `hold`, `skip`, `state`, `ops`,
|
|
162
|
+
`op`, `catalog`, `inspect`, `scene`, `pick`, `thing`, `explain`, `errors`, `loading`, `snap`, `snap_describe`, `style_palette`, `style_compare`, `scenario`, `verify`, `reload`, `resume`;
|
|
163
|
+
tests/mcp.mjs fails when this list and the server's tools differ) and returns the same text as the
|
|
164
|
+
command line; `snap` also returns the PNG as an image, 480 px wide by default (`size` for more; the full file is saved). `style_palette` and `style_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
|
+
(or start `npm run dev` yourself; a tool call without a server answers with that fix). It is only a local client of the bridge and opens no port; every check in section 5 still applies. As
|
|
133
166
|
with the command line, the `op` and `step` tools change the current session and its saves; the level itself changes only by editing content files.
|
|
134
167
|
|
|
135
168
|
Claude Code (in the game folder; in the engine repository add `-w name` after `mcp`):
|
|
@@ -141,6 +174,7 @@ Cursor, `.cursor/mcp.json` in the game folder: <!-- r18-ignore-line -->
|
|
|
141
174
|
{ "mcpServers": { "threedog": { "command": "npx", "args": ["threedog", "mcp"] } } }
|
|
142
175
|
```
|
|
143
176
|
On native Windows, wrap npx in cmd: `claude mcp add threedog -- cmd /c npx threedog mcp` (Cursor: `"command": "cmd", "args": ["/c", "npx", "threedog", "mcp"]`).
|
|
177
|
+
Faster and the same on every OS: point it at the installed bin with plain node, from the project folder: `claude mcp add threedog -- node node_modules/@threedog/tools/bin/threedog.mjs mcp` (the server starts once per session, so npx only costs at start, but node also avoids `cmd /c`). `npm run new-game` writes a `.mcp.json` like this into the new game, so opening the game folder in Claude Code picks it up.
|
|
144
178
|
|
|
145
179
|
The `js` tool (arbitrary code in the page) is off by default; `threedog mcp --allow-js` enables it, for development only. Other options: `-w name`
|
|
146
180
|
(workspace), `--page /<page>.html` (page path).
|
package/docs/recipes/18-world.md
CHANGED
|
@@ -60,7 +60,7 @@ engine.world.present('crop', {
|
|
|
60
60
|
build(rec) {
|
|
61
61
|
const m = new THREE.Mesh(geo, makeMaterial('prop', { color: 0x6aa84f }));
|
|
62
62
|
m.castShadow = true;
|
|
63
|
-
m.userData.use = engine.interactions.add(m, { label: '
|
|
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
|
|
64
64
|
return m;
|
|
65
65
|
},
|
|
66
66
|
update(rec, obj) { // grows bigger, changes color when ripe
|
|
@@ -80,6 +80,9 @@ function plant(x, z) { // the player plants one
|
|
|
80
80
|
return engine.world.add({ kind: 'crop', position: { x, y: engine.surface(x, z), z }, plantedAt: engine.clock.now });
|
|
81
81
|
}
|
|
82
82
|
```
|
|
83
|
+
The same "store when, derive the rest" pattern fits any timed thing: an enemy camp that respawns (`clearedAt`), a turret or machine cooldown
|
|
84
|
+
(`usedAt`), a door that shuts again (`openedAt`):
|
|
85
|
+
`const ready = rec => engine.clock.now - rec.usedAt >= rec.cooldown; // no per-step counter, correct after skip and load`
|
|
83
86
|
Test: `plant(2, 2)` -> `engine.step(130)` (fast-forward 130 game seconds) -> the player walks next to it -> `engine.ops.run('interaction.use')` ->
|
|
84
87
|
`engine.inventory.count('carrot')`.
|
|
85
88
|
|
|
@@ -157,7 +160,7 @@ function wander(rec, dt) {
|
|
|
157
160
|
depend on how fast the machine is.
|
|
158
161
|
- 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
|
|
159
162
|
however many fixed steps run per frame. For things measured by game clock (grows in a few days, respawns at a time), record `engine.clock.now` and compare.
|
|
160
|
-
- **Far in workers** (many far records, e.g. thousands of crops): `W.simulate('crop', { far, worker: true })`. Each step's far batch is copied and run
|
|
163
|
+
- **Far in workers** (many far records, e.g. thousands of crops, spawners or machines): `W.simulate('crop', { far, worker: true })`. Each step's far batch is copied and run
|
|
161
164
|
in `engine.threads` workers, then written back 4 fixed steps later through `engine.commits`; if a reply is late the same function runs on the main
|
|
162
165
|
thread, so threads on / off / slow give **bit-identical** records. Only fields far changed are written back (gameplay changes to other fields during
|
|
163
166
|
those 4 steps are kept). `far` must be self-contained: it is recompiled from source and sees only `(rec, dt)` and globals like `Math`; an outside
|
|
@@ -1,6 +1,7 @@
|
|
|
1
|
-
# Shooting and picking (
|
|
1
|
+
# Shooting and picking (cast a ray from the screen center or the mouse position, with any camera)
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Works with any camera (`follow`, `firstPerson`, `rts`, `fixed`): a click-to-select strategy game, a puzzle that taps tiles or a first-person shooter all
|
|
4
|
+
use the same ray. The example below is the first-person case; a score display needs `hud()`.
|
|
4
5
|
The ray API is `engine.pick(ndcX, ndcY, opts)`: screen coordinates -1..1 (0, 0 is the screen center, which is also the first-person crosshair); it
|
|
5
6
|
returns the nearest hit `{ point, distance, object, ... }` or null. **If you only want to hit your own targets, pass `targets: [array of objects]`; no
|
|
6
7
|
ray registration is needed.**
|
|
@@ -8,12 +9,12 @@ ray registration is needed.**
|
|
|
8
9
|
## 1. A first-person shooting range (copy it and it runs)
|
|
9
10
|
```js
|
|
10
11
|
import { createEngine, presets, openWorld, hud, THREE, makeMaterial } from 'threedog';
|
|
11
|
-
import
|
|
12
|
+
import style from './style/index.js'; // the game's own style pack
|
|
12
13
|
import { terrainPreset } from '@threedog/terrain-noise';
|
|
13
14
|
|
|
14
|
-
const engine = createEngine({ canvas: document.getElementById('view'), style
|
|
15
|
+
const engine = createEngine({ canvas: document.getElementById('view'), style, saveKey: 'range' });
|
|
15
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 })
|
|
16
|
-
engine.input.define('shoot', ['Mouse0', 'KeyF'], '
|
|
17
|
+
engine.input.define('shoot', ['Mouse0', 'KeyF'], 'Shoot'); // the left mouse button is a key too (Mouse0 / Mouse1 / Mouse2); either it or KeyF works
|
|
17
18
|
engine.characters.createPlayer({ ...presets.player.aim, spawn: engine.characters.findSpawn([0, 0, 0], { minH: 3, maxH: 14 }) });
|
|
18
19
|
await engine.start(); // place targets after the terrain is generated
|
|
19
20
|
|
|
@@ -29,7 +30,7 @@ const p0 = engine.player.position;
|
|
|
29
30
|
for (let i = 0; i < 6; i++) addTarget(p0.x + (i - 2.5) * 3, p0.z - 15);
|
|
30
31
|
|
|
31
32
|
let score = 0;
|
|
32
|
-
engine.hud.counter('score', { label: '
|
|
33
|
+
engine.hud.counter('score', { label: 'Hits', value: 0 });
|
|
33
34
|
engine.describe.add('range', () => ({ score, targets: targets.length })); // visible with the dev bridge: threedog describe range
|
|
34
35
|
|
|
35
36
|
engine.onFixed(() => { // firing is gameplay: read it in fixed so the result is independent of frame rate
|
|
@@ -51,8 +52,8 @@ engine.onFixed(() => { // firing is gameplay:
|
|
|
51
52
|
- **The first click**: on desktop, first person by default needs one click on the canvas to lock the mouse. That press only locks: it is not delivered
|
|
52
53
|
as `Mouse0` and not as a click, so it cannot fire (every later click after Esc and a re-lock behaves the same). `swallowLockClick: false` on the
|
|
53
54
|
camera delivers it too.
|
|
54
|
-
- **Adding a gamepad button**: `engine.input.define('shoot', ['Mouse0', 'KeyF', 'PadRT'], '
|
|
55
|
-
UI prompts. A touch tap does not count as `Mouse0` (give phones a button: `engine.input.touchButton('shoot', '
|
|
55
|
+
- **Adding a gamepad button**: `engine.input.define('shoot', ['Mouse0', 'KeyF', 'PadRT'], 'Shoot')`; the key names go into the settings key table and the
|
|
56
|
+
UI prompts. A touch tap does not count as `Mouse0` (give phones a button: `engine.input.touchButton('shoot', 'Shoot')`).
|
|
56
57
|
- To hit terrain / houses / registered static objects, don't pass `targets` (the default hits what was registered with `rays.addStatic`); to hit rigid
|
|
57
58
|
bodies too, pass `targets: 'all'`.
|
|
58
59
|
|
|
@@ -62,15 +62,15 @@ are not core keys either: they come from the game (`presets.player.*`, `interact
|
|
|
62
62
|
```js
|
|
63
63
|
// content/actions.js
|
|
64
64
|
export default {
|
|
65
|
-
kick: { keys: ['KeyF'], label: '
|
|
66
|
-
save: { keys: ['KeyK'], label: '
|
|
67
|
-
load: { keys: ['KeyL'], label: '
|
|
65
|
+
kick: { keys: ['KeyF'], label: 'Push / kick' },
|
|
66
|
+
save: { keys: ['KeyK'], label: 'Save' },
|
|
67
|
+
load: { keys: ['KeyL'], label: 'Load' },
|
|
68
68
|
};
|
|
69
69
|
```
|
|
70
70
|
Don't forget to add it to the exports in `content/index.js` (`export default { ..., actions }`), otherwise `engine.content.load(data)` will not load
|
|
71
71
|
it (it calls `engine.input.define(name, keys, label)`). What happens on press is written in main.js, read inside a fixed step so it lands on a tick:
|
|
72
72
|
`engine.onFixed(() => { if (engine.input.pressed('kick')) engine.ops.run('ball.kick', {}, { source: 'player' }); })` (a gameplay action is an op,
|
|
73
|
-
recipes/23-ops.md). A game that does not use content calls `engine.input.define('kick', 'KeyF', '
|
|
73
|
+
recipes/23-ops.md). A game that does not use content calls `engine.input.define('kick', 'KeyF', 'Push / kick')` directly.
|
|
74
74
|
|
|
75
75
|
**The engine does not perform the `save` / `load` actions for you**: they only register the keys; after the press you call the engine yourself in
|
|
76
76
|
main.js. Saving and loading are async (`Promise<boolean>`): await them, and say "saved" only on `true` (on `false` the engine already showed why).
|
|
@@ -78,8 +78,8 @@ Loading a slot to keep playing from it is `engine.session.load`, which leaves no
|
|
|
78
78
|
```js
|
|
79
79
|
import { toast } from 'threedog';
|
|
80
80
|
engine.onFixed(() => { // read keys in the fixed step like every gameplay key; the async work runs after it
|
|
81
|
-
if (engine.input.pressed('save')) engine.saves.save('slot1').then(ok => ok && toast(engine, '
|
|
82
|
-
if (engine.input.pressed('load')) engine.session.load('slot1').then(ok => !ok && toast(engine, '
|
|
81
|
+
if (engine.input.pressed('save')) engine.saves.save('slot1').then(ok => ok && toast(engine, 'Saved'));
|
|
82
|
+
if (engine.input.pressed('load')) engine.session.load('slot1').then(ok => !ok && toast(engine, 'No save yet'));
|
|
83
83
|
});
|
|
84
84
|
engine.saves.autosave(3); // autosave to 'auto' every 3 minutes of play (waits while paused, on the title screen and during newGame / load)
|
|
85
85
|
```
|
|
@@ -97,9 +97,9 @@ engine.interactions.pickMode = 'aim'; // switch at runtime (enter
|
|
|
97
97
|
One object with two verbs = two interactions with different key actions; each key picks among its own action, and `engine.interactions.options` lists
|
|
98
98
|
one `{ action, id, label }` per key for a prompt that shows both:
|
|
99
99
|
```js
|
|
100
|
-
engine.input.define('
|
|
101
|
-
engine.interactions.add(
|
|
102
|
-
engine.interactions.add(
|
|
100
|
+
engine.input.define('take', 'KeyF', 'Take');
|
|
101
|
+
engine.interactions.add(thing, { label: 'Inspect', onUse: inspect }); // E
|
|
102
|
+
engine.interactions.add(thing, { label: 'Take', action: 'take', enabled: () => ready, onUse: take }); // F
|
|
103
103
|
```
|
|
104
104
|
**Who acts** is `engine.actor` (a world record id, default `'player'`). Interactions, trigger zones, objective-marker distances, the world simulation
|
|
105
105
|
center and the default `ctx.actor` of ops all measure from `engine.actorPosition()`. To let the user drive a boat or switch squad members, set
|
|
@@ -163,7 +163,7 @@ A save is one envelope; `engine.saves.collect()` returns it and `export` / `expo
|
|
|
163
163
|
it loads, together with the owed time, container goods and fields that name them; only ids the counter could have made are touched (own kind, `n` up
|
|
164
164
|
to the saved counter, each `n` once), so an authored `crate-2` stays as it is. A migrate step that needs another part gets the whole save as its
|
|
165
165
|
second argument: `migrate: { 1: (data, save) => … }`. <!-- r18-ignore-line -->
|
|
166
|
-
- **Grid layers diff too**: cells authored in `content/grids.js` (`
|
|
166
|
+
- **Grid layers diff too**: cells authored in `content/grids.js` (`plot: { …, layers: { soil: [[i, j, { tilled: true }]] } }`) are the baseline;
|
|
167
167
|
the <!-- r18-ignore-line -->
|
|
168
168
|
`grids` part (version 2) stores only changed cells (`set`) and emptied authored ones (`clear`), and keeps a diff for a grid the run does not
|
|
169
169
|
have. <!-- r18-ignore-line -->
|
|
@@ -41,7 +41,7 @@ engine.setCamera?.('follow', { distance: 8, pitch: 0.3 });
|
|
|
41
41
|
- **Teleport, then lookAt**: `await engine.stream.teleport(p); engine.cameraRig.lookAt(target);` works in that order: `lookAt` aims from the body's
|
|
42
42
|
current position, not from the last drawn frame. Call it after the move (the angles do not follow later moves).
|
|
43
43
|
- **Player movement direction follows the camera**: `engine.cameraRig.forward()` / `right()` change automatically after switching.
|
|
44
|
-
- **Cutscene takeover**: while `engine.cameraOverride` is not null the camera module leaves the camera alone; see
|
|
44
|
+
- **Cutscene takeover**: while anyone holds `engine.takeCamera(owner)` (`engine.cameraOverride` is not null) the camera module leaves the camera alone; see [the engine API](../api/engine.md).
|
|
45
45
|
- **Shooting games**: bind first-person firing to a mouse-button action, see `19-shooting-picking.md`.
|
|
46
46
|
|
|
47
47
|
## 4. Over the shoulder, lock-on framing, mouse lock (follow camera)
|
|
@@ -51,7 +51,7 @@ engine.cameraRig.shoulder = -0.7; // switch shoulders at any time (plain p
|
|
|
51
51
|
engine.cameraRig.frame(enemy.object); // lock-on: turn to "behind the player, looking at the enemy"; frame(null) lets go
|
|
52
52
|
```
|
|
53
53
|
- **`shoulder`**: meters the aim point (and so the camera) moves to the right along `right()`; negative = left, 0 = centered (default).
|
|
54
|
-
- **`pointerLock`** (default false): a click on the canvas locks the mouse, so moving it turns the view with no dragging; Esc releases. Not on phones.
|
|
54
|
+
- **`pointerLock`** (default false): a click on the canvas locks the mouse, so moving it turns the view with no dragging; Esc releases. Not on phones. If the browser refuses the lock the camera falls back to dragging; `describe().camera.pointerLock` is a state machine: `state` is `off` / `unsupported` / `waiting-click` / `requesting` / `locked` / `refused`, plus `covered` (what sits on the canvas centre and eats the click), `cameraOverride` (a takeover blocks locking) and `lastFailure { reason, agoSec }`; the text line shows the same.
|
|
55
55
|
The press that locks is swallowed (no `Mouse0`, no click) so it cannot attack or fire; `swallowLockClick: false` delivers it.
|
|
56
56
|
Leave it off when the mouse buttons are for UI or clicking the ground.
|
|
57
57
|
- **`yaw` means which side of the player the camera is on**: `camera = focus + (sin yaw, cos yaw) * distance`, so the camera looks along
|
|
@@ -102,3 +102,52 @@ engine.onFixed(dt => {
|
|
|
102
102
|
- The engine already calls `player.animate(dt)` every frame; a module with its own loop over characters must skip the player, or the walk cycle runs
|
|
103
103
|
twice as fast.
|
|
104
104
|
- Test without a keyboard: `engine.input.simulate('lockOn'); engine.step(1 / 60); engine.input.simulate('lockOn', false)`.
|
|
105
|
+
|
|
106
|
+
## 6. Orthographic view, and taking the camera over yourself
|
|
107
|
+
|
|
108
|
+
**Orthographic (isometric / 2.5D) with the built-in rigs.** `projection: 'orthographic'` plus `size` (world units of view height) on the fixed and follow cameras.
|
|
109
|
+
The default stays perspective. On resize the view height stays `size` and the width follows the aspect.
|
|
110
|
+
|
|
111
|
+
```js
|
|
112
|
+
// one fixed isometric shot (shorthand for a single shot named 'main')
|
|
113
|
+
engine.setCamera('fixed', { position: [14, 14, 14], lookAt: [0, 0, 0], projection: 'orthographic', size: 16 });
|
|
114
|
+
// per shot: shots: { hall: { position, lookAt, projection: 'orthographic', size: 12 }, yard: { position, lookAt } } // yard stays perspective
|
|
115
|
+
// follow the player from a fixed angle
|
|
116
|
+
engine.setCamera('follow', { pitch: 0.6, yaw: 0.8, distance: 20, projection: 'orthographic', size: 14 });
|
|
117
|
+
```
|
|
118
|
+
|
|
119
|
+
- `engine.camera` stays the one object everything holds (render, post, shadows, sky); it is flipped to an orthographic matrix, so `camera.isOrthographicCamera`
|
|
120
|
+
is true, `camera.left/right/top/bottom` are set, and `camera.zoom` still zooms. `camera.fov` is ignored while it is on.
|
|
121
|
+
- Blends between two orthographic shots blend `size`; a perspective/orthographic mix switches to the target's mode at once. Switching rig kinds returns to perspective.
|
|
122
|
+
- Limits: on the follow camera the mouse wheel changes `size` (clamped to the `minDistance`/`maxDistance` ratio of the starting `distance`).
|
|
123
|
+
The `fov` slider in the settings menu has no effect. Cascaded shadows, `dof` and `outline` handle orthographic depth; a custom post pass that assumes perspective depth must do the same.
|
|
124
|
+
|
|
125
|
+
**Placing the camera yourself (cutscene, photo mode, your own rig).** Take it with `engine.takeCamera(owner, { focus })`; the camera module leaves the camera alone until you `remove()` the handle.
|
|
126
|
+
Several holders can take it (a cutscene, then a named view on top): the latest is in charge, and removing it hands the camera back to the previous one, not to nobody.
|
|
127
|
+
|
|
128
|
+
```js
|
|
129
|
+
let t = 0;
|
|
130
|
+
const cam = engine.takeCamera('my-orbit', { focus: engine.player.position }); // focus (optional): where the world loads around
|
|
131
|
+
const frame = engine.onFrame(dt => {
|
|
132
|
+
t += dt; engine.camera.position.set(Math.cos(t) * 12, 8, Math.sin(t) * 12); engine.camera.lookAt(0, 1, 0);
|
|
133
|
+
});
|
|
134
|
+
// done: frame.remove(); cam.remove(); // the rig resumes from its own state
|
|
135
|
+
```
|
|
136
|
+
|
|
137
|
+
To use your own `THREE.OrthographicCamera` instead of flipping `engine.camera`:
|
|
138
|
+
|
|
139
|
+
```js
|
|
140
|
+
const original = engine.camera, size = 12;
|
|
141
|
+
const ortho = new THREE.OrthographicCamera(-1, 1, 1, -1, 0.1, 500);
|
|
142
|
+
function fit() { // the engine only updates engine.camera.aspect on resize, so keep your own camera's aspect here
|
|
143
|
+
const s = engine.renderer.getSize(new THREE.Vector2()), a = s.x / s.y;
|
|
144
|
+
ortho.left = -size * a / 2; ortho.right = size * a / 2; ortho.top = size / 2; ortho.bottom = -size / 2; ortho.updateProjectionMatrix();
|
|
145
|
+
}
|
|
146
|
+
const cam = engine.takeCamera('my-ortho');
|
|
147
|
+
engine.camera = ortho; // the plain render path, cascaded shadows and modules read engine.camera live
|
|
148
|
+
ortho.position.set(10, 10, 10); ortho.lookAt(0, 0, 0); fit(); addEventListener('resize', fit);
|
|
149
|
+
// give it back: removeEventListener('resize', fit); engine.camera = original; cam.remove();
|
|
150
|
+
```
|
|
151
|
+
|
|
152
|
+
Swapping the object only works while no post effect is active: the post chain's scene pass keeps the camera it was built with. With post effects, use
|
|
153
|
+
`projection: 'orthographic'` above instead.
|
|
@@ -16,15 +16,15 @@ The rest is written for A.
|
|
|
16
16
|
`content/items.js`:
|
|
17
17
|
```js
|
|
18
18
|
export default {
|
|
19
|
-
gold: { name: '
|
|
20
|
-
|
|
19
|
+
gold: { name: 'Gold', icon: '🪙', stack: 99999 }, // currency: one slot however much
|
|
20
|
+
medkit: { name: 'Medkit', price: 5 }, // price: read by the shop ops below
|
|
21
21
|
};
|
|
22
22
|
export const startItems = { gold: 12 };
|
|
23
23
|
```
|
|
24
24
|
`content/containers.js` (the shelf. `items` is the initial stock, placed only the first time; a shelf that was emptied by looting / selling stays
|
|
25
25
|
empty after loading, see recipe 03):
|
|
26
26
|
```js
|
|
27
|
-
export default { 'shop-
|
|
27
|
+
export default { 'shop-trader': { capacity: 6, items: { medkit: 3 } } };
|
|
28
28
|
```
|
|
29
29
|
Import it in `content/index.js` and put it in the exported object (`containers`).
|
|
30
30
|
|
|
@@ -63,38 +63,38 @@ engine.ops.define('shop.sell', {
|
|
|
63
63
|
In the dialogue, `if: { can: [...] }` shows a choice only when the op would succeed, and `do: { op: [...] }` runs it:
|
|
64
64
|
```js
|
|
65
65
|
// content/dialogues.js
|
|
66
|
-
const
|
|
67
|
-
const
|
|
66
|
+
const buyKit = ['shop.buy', { shop: 'shop-trader', item: 'medkit' }];
|
|
67
|
+
const sellKit = ['shop.sell', { shop: 'shop-trader', item: 'medkit' }];
|
|
68
68
|
export default {
|
|
69
|
-
|
|
70
|
-
speaker: '
|
|
69
|
+
trader: {
|
|
70
|
+
speaker: 'Trader',
|
|
71
71
|
nodes: {
|
|
72
72
|
start: {
|
|
73
|
-
text: '
|
|
73
|
+
text: 'What do you need?',
|
|
74
74
|
choices: [
|
|
75
|
-
{ text: '
|
|
76
|
-
{ text: '
|
|
77
|
-
{ text: '
|
|
75
|
+
{ text: 'Buy a medkit (5 gold)', next: 'start', if: { can: buyKit }, do: { op: buyKit } },
|
|
76
|
+
{ text: 'Sell a medkit (3 gold)', next: 'start', if: { can: sellKit }, do: { op: sellKit } },
|
|
77
|
+
{ text: 'Bye', next: 'end' },
|
|
78
78
|
],
|
|
79
79
|
},
|
|
80
80
|
},
|
|
81
81
|
},
|
|
82
82
|
};
|
|
83
83
|
```
|
|
84
|
-
- The shelf id (`'shop-
|
|
84
|
+
- 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
85
|
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('
|
|
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.
|
|
87
87
|
- 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
88
|
`transfer` moves exactly that piece with its data, and `e.inventory.container(shop).get(item)` reads the data for a price
|
|
89
89
|
(`def.price * data.durability / 100`).
|
|
90
|
-
- Show a failure reason to the player through your own i18n string (`e.t('shop.' + r.
|
|
91
|
-
- `npx threedog ops` lists what can be bought right now if you add `offers` (see recipe 23); `npx threedog op shop.buy shop=shop-
|
|
90
|
+
- Show a failure reason to the player through your own i18n string (`e.t('shop.' + r.code)`); the engine shows nothing itself.
|
|
91
|
+
- `npx threedog ops` lists what can be bought right now if you add `offers` (see recipe 23); `npx threedog op shop.buy shop=shop-trader item=medkit`
|
|
92
92
|
buys from the terminal.
|
|
93
93
|
|
|
94
94
|
## 4. Gold HUD
|
|
95
95
|
Calling `hud.counter` again with the same id = update, and it leaves the DOM alone when the value is unchanged, so calling it every frame is cheap:
|
|
96
96
|
```js
|
|
97
|
-
engine.onFrame(() => engine.hud.counter('gold', { icon: '🪙', label: '
|
|
97
|
+
engine.onFrame(() => engine.hud.counter('gold', { icon: '🪙', label: 'Gold', value: engine.inventory.count('gold') }));
|
|
98
98
|
```
|
|
99
99
|
Loading a save replaces the whole inventory, and refreshing every frame follows naturally; no event listener is needed.
|
|
100
100
|
|