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
package/docs/recipes/23-ops.md
CHANGED
|
@@ -23,11 +23,11 @@ engine.ops.define('shop.buy', {
|
|
|
23
23
|
},
|
|
24
24
|
offers: (e, ctx) => [{ shop: 'shop-bakery', item: 'bread' }], // optional: arg sets possible now (ops list / dev bridge `ops`)
|
|
25
25
|
reasons: { soldOut: 'Shelf is empty', noMoney: 'Not enough gold' }, // optional developer notes
|
|
26
|
-
// optional: undo(e, args, value, ctx) reverses a finished run; engine.ops.undo('shop.buy', args, r.value) calls it ({ ok: false,
|
|
26
|
+
// optional: undo(e, args, value, ctx) reverses a finished run; engine.ops.undo('shop.buy', args, r.value) calls it ({ ok: false, code: 'noUndo', facts: { op } } without one)
|
|
27
27
|
});
|
|
28
28
|
|
|
29
29
|
const r = engine.ops.run('shop.buy', { shop: 'shop-bakery', item: 'bread' });
|
|
30
|
-
// r = { ok: true, value: 1 } or { ok: false,
|
|
30
|
+
// r = { ok: true, value: 1 } or { ok: false, code: 'noMoney', facts, nextActions }
|
|
31
31
|
const { ok } = engine.ops.can('shop.buy', { shop: 'shop-bakery', item: 'bread' }); // ask only: grey out a button
|
|
32
32
|
```
|
|
33
33
|
Rules that keep ops replayable and network-ready:
|
|
@@ -37,9 +37,9 @@ Rules that keep ops replayable and network-ready:
|
|
|
37
37
|
- **Args are plain data and self-contained**: no three.js objects (pass `[x, y, z]`), and anything not in world data (aim direction, a clicked build
|
|
38
38
|
position) goes in the args. Pass a fresh object each call; in dev the args are frozen because the history keeps them.
|
|
39
39
|
- **All "may I" checks live in `can`**, so `run` never stops halfway. A failure always has a reason (camelCase English). Show it to the player through
|
|
40
|
-
i18n (`e.t('op.shop.buy.' + r.
|
|
40
|
+
i18n (`e.t('op.shop.buy.' + r.code)`); the engine shows nothing itself.
|
|
41
41
|
- An op may call another op inside `run` (logged with `depth`); `can` must not call `run` or change state.
|
|
42
|
-
- Name ops `noun.verb`. A dot means "asking to do"; events (`noun:action`) mean "already happened". `run`
|
|
42
|
+
- Name ops `noun.verb`. A dot means "asking to do"; events (`noun:action`) mean "already happened". `run` emits your own domain events itself.
|
|
43
43
|
|
|
44
44
|
## 2. Who calls it, and when
|
|
45
45
|
| Caller | How | History `phase` / `source` |
|
|
@@ -70,11 +70,11 @@ returns `'halted'`.
|
|
|
70
70
|
|
|
71
71
|
## 4. Read the log
|
|
72
72
|
```js
|
|
73
|
-
engine.ops.recent('shop.buy'); // [{ seq, tick, phase, name, args, source, actor, ok,
|
|
73
|
+
engine.ops.recent('shop.buy'); // [{ seq, tick, phase, name, args, source, actor, ok, code, depth, count }] old -> new
|
|
74
74
|
engine.ops.list(); // defined ops [{ name, desc, args }]
|
|
75
|
-
engine.ops.list({ available: true }); // each offer checked with can [{ name, args, ok,
|
|
75
|
+
engine.ops.list({ available: true }); // each offer checked with can [{ name, args, ok, code }]
|
|
76
76
|
```
|
|
77
|
-
Consecutive identical failures (same actor, op and
|
|
77
|
+
Consecutive identical failures (same actor, op and code, e.g. `cooldown` while the trigger is held) merge into one entry with `count`.
|
|
78
78
|
The ring keeps `engine.ops.historySize` entries (256). A save load writes a `(load)` entry: what follows happened in the loaded world.
|
|
79
79
|
A thrown `run` freezes gameplay in dev / tests and `engine.error` names `ops.run('name')` plus the last 5 ops.
|
|
80
80
|
|
|
@@ -92,7 +92,7 @@ of each writing method, and wrap writes that are allowed anyway (loading your sa
|
|
|
92
92
|
A test runs the op directly instead of walking, pressing keys and waiting for typing:
|
|
93
93
|
```js
|
|
94
94
|
engine.ops.run('shop.buy', { shop: 'shop-bakery', item: 'bread', n: 2 }, { source: 'test' });
|
|
95
|
-
// check engine.inventory.count('bread'), and engine.ops.recent('shop.buy').at(-1).
|
|
95
|
+
// check engine.inventory.count('bread'), and engine.ops.recent('shop.buy').at(-1).code on failure
|
|
96
96
|
```
|
|
97
97
|
Keep one `press` test per key to prove "key -> op" itself works (the history shows `interaction.use` after `press interact`).
|
|
98
98
|
|
|
@@ -112,7 +112,7 @@ Put `<workspace>/tests/scenarios/<name>.json` in the engine package or a game; `
|
|
|
112
112
|
```
|
|
113
113
|
- `state` is `engine.applyState` params; `"pos": "@id"` stands 1 m beside a world record. The page is paused first, so game time moves only in `step`
|
|
114
114
|
(seconds) and `press`.
|
|
115
|
-
- `op` steps run with `source: 'test'` (`actor` optional); `expect` is `"ok"` (default) or the
|
|
115
|
+
- `op` steps run with `source: 'test'` (`actor` optional); `expect` is `"ok"` (default) or the failure code. A failure prints the `engine.explain` sentence.
|
|
116
116
|
- `expect` maps `describe()` paths to values (`nearby[0].name` works; numbers within 0.01; `null` = absent). `snapshot` compares with
|
|
117
117
|
`tests/snapshots/<name>.describe.json` (`only` / `ignore` / `tolerance`; write it with `threedog test <name> --update-snapshots`).
|
|
118
118
|
- Before any step runs, every op name and step field is checked; a typo fails with "did you mean". The run stops at the first failed step.
|
|
@@ -120,7 +120,7 @@ Put `<workspace>/tests/scenarios/<name>.json` in the engine package or a game; `
|
|
|
120
120
|
|
|
121
121
|
## 8. Inspect and explain
|
|
122
122
|
```js
|
|
123
|
-
engine.inspect(); // { actor: 'player', at, near: [...nearby], ops: [{ op, args, ok,
|
|
123
|
+
engine.inspect(); // { actor: 'player', at, near: [...nearby], ops: [{ op, args, ok, code?, why? }] }: what is around and possible now
|
|
124
124
|
engine.inspect('npc_3'); // the same as another actor; engine.inspect([x, z]) around a spot
|
|
125
125
|
engine.explain({ op: 'shop.buy', args: { shop: 'bakery', item: 'bread' } }).text;
|
|
126
126
|
// text: 'shop.buy {...} cannot run now: noMoney (Not enough gold)'; detail: 'last attempt at tick 812 (player, player): noMoney' (+ recent, events)
|
|
@@ -129,6 +129,10 @@ engine.explain({ quest: 'first-light' }).text; // 'quest ... waits on step 2/3
|
|
|
129
129
|
Other keys come from modules: add `explain: { myKey(e, value, query) { return { ok, text }; } }` to the module definition. Dev bridge: `npx threedog
|
|
130
130
|
inspect [id | x,z]`, `npx threedog explain op shop.buy shop=bakery item=bread`, `npx threedog explain quest first-light`.
|
|
131
131
|
|
|
132
|
+
Why did this event fire? In dev set `engine.events.traceSize = 200` (default 0 = off, no cost). Every emitted event then records its cause: `engine.events.trace('item:add').at(-1)`
|
|
133
|
+
is `{ id, tick, name, parent: 'op:shop.buy#12', chain: ['op:shop.buy#12'] }`; a parent is `ev:<id>` (a handler of that event emitted it) or `op:<name>#<seq>` (the
|
|
134
|
+
op's `run` emitted it, seq is the history seq); `chain` walks up to the root as far as the ring holds.
|
|
135
|
+
|
|
132
136
|
## 9. Randomness
|
|
133
137
|
Gameplay randomness uses `engine.random` (`next / range / int / pick / chance`): it is saved with the game and `createEngine({ seed })` fixes it, so a
|
|
134
138
|
scenario replays the same. `Math.random` breaks both.
|
|
@@ -137,3 +141,35 @@ scenario replays the same. `Math.random` breaks both.
|
|
|
137
141
|
The engine repository's `Properties` specs (fast-check, a devDependency) runs random sequences of ops / saves / newGame inside the page in one `ev()` and checks the state rules (item totals kept, a refused op changes nothing, save then load is identical, newGame leaves nothing behind, a failed `engine.use` batch changes nothing).
|
|
138
142
|
A failure prints the shrunk minimal sequence and the seed. Replay: `FC_SEED=<seed> npm test -- "Properties: random op"`; more cases: `FC_RUNS=300` (default 25). Without fast-check installed the specs skip and say why.
|
|
139
143
|
To check a new rule, add a step kind to `stepArb` and a check in `pageRun`; turn every found sequence into a fixed regression spec.
|
|
144
|
+
|
|
145
|
+
## 11. Structured failures, nextFixed, and who paused
|
|
146
|
+
`can` may return a reason string (`'noMoney'`) or a structured failure. Every failed result from `run` / `can` / `undo` has `{ ok: false, code, facts, nextActions }`; a string failure becomes `code = that string`, `facts = {}`, `nextActions = []`, so read `.code` without checking the shape. `engine.inspect()`, `ops.list({ available: true })`, `engine.describe()` actions and `engine.explain({ op })` carry `facts` / `nextActions` too.
|
|
147
|
+
```js
|
|
148
|
+
engine.ops.define('shop.buy', {
|
|
149
|
+
can: (e, a, ctx) => gold(ctx) >= 5 || { code: 'noMoney', facts: { need: 5, have: gold(ctx) }, nextActions: [{ op: 'job.work', args: {} }] },
|
|
150
|
+
run: (e, a, ctx) => { /* ... */ },
|
|
151
|
+
});
|
|
152
|
+
const r = engine.ops.run('shop.buy', {}); // r.ok === false, r.code === 'noMoney', r.facts.need === 5, r.nextActions[0].op === 'job.work'
|
|
153
|
+
```
|
|
154
|
+
`engine.nextFixed(fn)` runs `fn` at the start of the next fixed step and returns a Promise of its value, so a UI click or a promise callback can safely write gameplay state: `await engine.nextFixed(() => engine.ops.run('door.open', { id: 'gate' }))`. It is built on `engine.commits` and waits while frozen or loading.
|
|
155
|
+
|
|
156
|
+
Tests that call `engine.pause(owner)` / `engine.resume(owner)` name themselves (default `'game'`). The loop stays paused until every owner has resumed; `resume('b')` while only `'a'` paused is ignored with a dev warning (`pause-owner`), so one helper cannot unpause another's pause.
|
|
157
|
+
|
|
158
|
+
## 12. Failing in run, atomic ops, revision
|
|
159
|
+
`run` can fail like `can`: return or throw `{ ok: false, code, facts, nextActions }` (a value that merely has a `code` field is not a failure; `ok: false` is required). `facts` is an object (`{ need: 5 }`) or a list of `{ id, field, actual, expected? }` naming the record and field that were wrong. The engine never invents `nextActions`; only the op definition declares them. Every result carries `revision` (`engine.ops.revision`), a counter bumped once per committed op: "did anything change since I looked" is one compare.
|
|
160
|
+
```js
|
|
161
|
+
engine.ops.define('craft.bread', {
|
|
162
|
+
atomic: true, // every part declared atomic (world, inventory, containers, vars, quests, grids, random, scene) is undone if run fails or throws
|
|
163
|
+
run(e, { oven }, ctx) {
|
|
164
|
+
e.inventory.container(ctx.actor).remove('flour', 2);
|
|
165
|
+
if (e.world.get(oven).heat < 3) return { ok: false, code: 'ovenCold', facts: [{ id: oven, field: 'heat', actual: e.world.get(oven).heat, expected: 3 }], nextActions: [{ op: 'oven.light', args: { oven } }] };
|
|
166
|
+
e.inventory.add('bread');
|
|
167
|
+
},
|
|
168
|
+
after: (e) => e.audio.sfx('ding'), // sound / animation: runs only after the op committed
|
|
169
|
+
});
|
|
170
|
+
```
|
|
171
|
+
What atomic covers, honestly: it copies the save parts that declared `saves.register(key, { atomic: true })` (the built-ins above; a game's own part can opt in) before `run` and loads them back on failure, so it costs one save of those per run (fine for a craft op, wrong for a per-frame op in a huge world). Events already emitted, sound, animation and any other module's state are not undone; keep such effects in `after`. Ops called from an atomic run join it (their `after` hooks wait for the outermost commit, and a rolled-back outer also takes back their revision). `ops.list()` and `engine.explain({ op })` report `atomic`.
|
|
172
|
+
|
|
173
|
+
Causal trace (`events.traceSize > 0`, recipe 06): failed ops are noted as `op:<name>` with their `code`; `collision.lineClear(a, b, { who })` as `sight` (blocked lines always, clear ones for the focused object only); NPC state changes as `npc:state`. A game's behavior notes its own mode switch with `engine.events.note('npc:mode', { obj: rec.id, data: { from: 'patrol', to: 'investigate' } })`; `events.traceFocus('guard-1')` makes one object verbose.
|
|
174
|
+
|
|
175
|
+
Atomic details: a rolled-back run still bumps `ops.revision` (it only goes up, never back to an old number) and its committed nested ops show in `ops.recent()` as `ok: false` with code `rolledBack`. `after` hooks run in commit order (nested first, then the outer op) once the outermost atomic op ends. The rollback does not run `afterLoad` and mutes the events its loads would emit, so atomic state must be plain data. Failed results have no `reason`: reading it throws `renamed-api` and points to `code`.
|
package/docs/recipes/27-net.md
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
# Co-op multiplayer: net() (host authority + state sync)
|
|
2
2
|
|
|
3
|
-
**What it is**: an optional module for slow, cooperative games (
|
|
3
|
+
**What it is**: an optional module for slow, cooperative games (a shared base or farm, a co-op puzzle, a turn-based board, trading). One player's browser is the **host** and
|
|
4
4
|
owns the game state; friends are **clients** that mirror it and ask for changes through ops. Not installed = no cost.
|
|
5
5
|
**What it is not (yet)**: action netcode. There is no client prediction or rollback, so a client's attack / roll / shot waits one round trip.
|
|
6
6
|
Souls-like and shooter games need that later step; the rules below (ops with self-contained args, state only changed in fixed steps and ops,
|
|
@@ -11,7 +11,7 @@ The same game code runs on every machine; only `role` and the transport differ.
|
|
|
11
11
|
```js
|
|
12
12
|
import { net, webSocket } from 'threedog';
|
|
13
13
|
|
|
14
|
-
const room = 'ws://192.168.1.5:8787/
|
|
14
|
+
const room = 'ws://192.168.1.5:8787/my-game';
|
|
15
15
|
const hosting = new URLSearchParams(location.search).has('host');
|
|
16
16
|
engine.use(net(hosting
|
|
17
17
|
? { role: 'host', transport: webSocket(room, { host: true }) }
|
|
@@ -77,7 +77,7 @@ On a client `engine.ops.run` returns `{ ok: true, pending: true, seq }` after th
|
|
|
77
77
|
real result comes later:
|
|
78
78
|
```js
|
|
79
79
|
engine.events.on('net:sync', () => redrawBag()); // state changed (snapshot or diff)
|
|
80
|
-
engine.events.on('net:result', r => { if (!r.ok) hint(engine.t('op.' + r.name + '.' + r.
|
|
80
|
+
engine.events.on('net:result', r => { if (!r.ok) hint(engine.t('op.' + r.name + '.' + r.code)); }); // after the state it caused
|
|
81
81
|
```
|
|
82
82
|
Single-player gets the same events from your own domain events, so writing "react to state" now means nothing changes when net() is added. Other
|
|
83
83
|
events: `net:join` / `net:leave` (host), `net:open` / `net:close` (client). `engine.net.reconnect(webSocket(url, { key }))` reconnects with the same
|
|
@@ -16,7 +16,7 @@ engine.use(openWorld({ camera: 'follow', seed: 7, terrain: terrainPreset({ shape
|
|
|
16
16
|
const preview = createTerrain({ seed: 7, ...terrainPreset() }); // same heights before the engine starts
|
|
17
17
|
const dry = (x, z) => riverAt(x, z, preview.noise) === 0;
|
|
18
18
|
```
|
|
19
|
-
Its ground types are `beach snow rock riverbank wetland savanna forest highland meadow`;
|
|
19
|
+
Its ground types are `beach snow rock riverbank wetland savanna forest highland meadow`; a style pack colors them (`terrain.colors`)
|
|
20
20
|
(`style.terrain.biomeColors`), and `terrainStrings` names them for `describe()`. Other options:
|
|
21
21
|
`heightScale mountains rivers riverWidth biomes noise island canyon` (types in the package's `index.d.ts`).
|
|
22
22
|
|
|
@@ -72,7 +72,7 @@ engine.ops.define('path.sand', { args: { at: 'position' }, // a sandy path; a
|
|
|
72
72
|
Read the ground with `engine.surface(x, z)` (also `slope`, `groundType`, `waterAt`) and put an object on it with `engine.snapToGround(obj)`. Don't
|
|
73
73
|
raycast the terrain for this: the height function is exact and works before the chunk has a mesh.
|
|
74
74
|
|
|
75
|
-
|
|
75
|
+
Crisp ground color borders, triangle cut, normals, bounds margin, height from a grid: `37-terrain-look-hooks.md`.
|
|
76
76
|
|
|
77
77
|
## 5. Where the ground ends: `shape`
|
|
78
78
|
|
package/docs/recipes/29-grid.md
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
|
-
# Grid placement:
|
|
1
|
+
# Grid placement: towers, furniture, buildings, crops
|
|
2
2
|
|
|
3
3
|
Requires module `grids()` and `world()` (`openWorld()` includes world; grids is opt-in and costs nothing when not installed). The API list is in
|
|
4
4
|
`../api/grids.md`.
|
|
5
5
|
A grid turns world positions into cells. Things placed on it are ordinary `engine.world` records; per-cell state that is not a thing (tilled soil, wet
|
|
6
|
-
soil, a painted floor) lives in **layers**.
|
|
6
|
+
soil, creep on a board, a painted floor) lives in **layers**. Per-cell gameplay state always goes here; `terrain.edit({ paint })` is only for landscape ground types (roads, sand),
|
|
7
7
|
see `28-terrain.md`.
|
|
8
8
|
Works on any ground: procedural terrain, a Blender level, an indoor floor. Heights come from `engine.surface`, ground types from `engine.groundType`.
|
|
9
9
|
|
|
@@ -11,77 +11,97 @@ Works on any ground: procedural terrain, a Blender level, an indoor floor. Heigh
|
|
|
11
11
|
```js
|
|
12
12
|
import { grids, toast } from 'threedog';
|
|
13
13
|
engine.use(grids());
|
|
14
|
-
const
|
|
15
|
-
const room = engine.grids.add('room', { cell: 0.5, origin: [-3, -3], size: [12, 12], zone: 'house' });
|
|
14
|
+
const board = engine.grids.add('board', { cell: 1, origin: [0, 0], size: [16, 12] }); // several grids may exist: a tower-defense board,
|
|
15
|
+
const room = engine.grids.add('room', { cell: 0.5, origin: [-3, -3], size: [12, 12], zone: 'house' }); // a dungeon or house room,
|
|
16
|
+
const plot = engine.grids.add('plot', { cell: 1, origin: [20, 0], size: [8, 8] }); // a garden plot
|
|
16
17
|
|
|
18
|
+
engine.grids.define('tower', { size: [2, 2], kind: 'tower', fields: { level: 1 } }); // 2x2 cells on the board
|
|
17
19
|
engine.grids.define('crop', { layer: { soil: 'tilled' }, fields: { plantedAt: 0 } }); // only on cells whose soil layer has tilled
|
|
18
20
|
engine.grids.define('bed', { size: [2, 1], kind: 'furniture', fields: { model: 'bed' } }); // 2x1 cells; world record kind 'furniture'
|
|
19
21
|
engine.grids.define('shed', { size: [3, 2], ground: ['grass', 'dirt'], flat: 0.2 }); // engine.groundType must match; max 0.2 m height difference
|
|
20
22
|
engine.grids.define('crate', { size: [1, 1], can: (e, { cell }) => (cell[1] > 2 ? true : 'tooCloseToRoad') }); // your own rule
|
|
21
23
|
```
|
|
22
|
-
Coordinates: `
|
|
23
|
-
`
|
|
24
|
+
Coordinates: `board.toCell(pos)` -> `[i, j]`, `board.toWorld(cell, size?, rotation?)` -> footprint center on the ground, `board.snap(pos)`,
|
|
25
|
+
`board.inside(cell)`, `board.footprint(cell, size, rotation)`.
|
|
24
26
|
Cell `[0, 0]` starts at `origin`. A footprint is anchored at its min corner; `rotation` is quarter turns (0-3), odd turns swap width and depth.
|
|
25
27
|
|
|
26
28
|
## 2. Place, pick up, move: always ops
|
|
27
29
|
```js
|
|
28
|
-
engine.ops.run('grid.place', { grid: '
|
|
30
|
+
engine.ops.run('grid.place', { grid: 'room', item: 'bed', cell: [4, 4], rotation: 1 }); // { ok, value: record id } or { ok: false, code, facts, nextActions }
|
|
29
31
|
engine.ops.run('grid.move', { id: 'furniture-3', cell: [6, 2], rotation: 0 }); // its own cells do not block it; grid: 'room' moves it to another grid
|
|
30
32
|
engine.ops.run('grid.remove', { id: 'furniture-3' }); // value { item, kind }: put it back in the bag yourself
|
|
31
|
-
|
|
33
|
+
board.can('tower', [3, 5]); // ask only: true or a reason string
|
|
32
34
|
```
|
|
33
|
-
|
|
35
|
+
Failure codes: `outOfBounds` `occupied` `wrongGround` `notFlat` `not<Field>` (from a layer rule: `notTilled`) `noGrid` `idTaken` `unknown` `notPlaced`, or
|
|
34
36
|
your `can` reason.
|
|
35
|
-
Show them through i18n (`engine.t('grid.' + r.
|
|
37
|
+
Show them through i18n (`engine.t('grid.' + r.code)`; `grid.can()` returns the same names as a plain string); `engine.explain({ grid: { grid: 'room', item: 'bed', cell: [4, 4] } }).text` says which cell
|
|
36
38
|
and which record is in the way.
|
|
37
|
-
A placed record looks like `{ id, kind, position, rot, ...fields, grid: { id: '
|
|
39
|
+
A placed record looks like `{ id, kind, position, rot, ...fields, grid: { id: 'room', cell: [4, 4], size: [2, 1], rotation: 1, item: 'bed' } }`. Give
|
|
38
40
|
it a look with `world.present(kind, ...)` as usual (`rot` is the yaw in radians).
|
|
39
41
|
To build several things at once, call `grid.place` from your own op (`build.wall`), so each placement is still checked.
|
|
40
42
|
|
|
41
|
-
**Occupancy is not saved separately.** `
|
|
43
|
+
**Occupancy is not saved separately.** `room.at(cell)` / `room.area(cell, size)` read an index built from the world records' `grid` field, so a save
|
|
42
44
|
holds every placed thing once and can never disagree with itself.
|
|
43
45
|
**Don't go around it** (dev): the `grid` field of a placed record is frozen (editing it in place throws); `world.set / add` outside an op trigger the
|
|
44
46
|
ops guard; a record added by hand that overlaps another is reported and the cell stays with the first.
|
|
45
47
|
|
|
46
|
-
## 3. Layers: per-cell state (
|
|
48
|
+
## 3. Layers: per-cell state (soil, creep, paint)
|
|
47
49
|
```js
|
|
48
|
-
const soil =
|
|
49
|
-
engine.ops.define('
|
|
50
|
-
can: (e, { cell }) => (!
|
|
50
|
+
const soil = plot.layer('soil'); // created on first use; saved with the game (only cells that differ from content)
|
|
51
|
+
engine.ops.define('plot.till', { args: { cell: 'any' },
|
|
52
|
+
can: (e, { cell }) => (!plot.inside(cell) ? 'outOfBounds' : plot.at(cell) ? 'occupied' : true),
|
|
51
53
|
run: (e, { cell }) => soil.set(cell, { tilled: true }) });
|
|
52
|
-
engine.ops.define('
|
|
54
|
+
engine.ops.define('plot.water', { args: { cell: 'any' },
|
|
53
55
|
can: (e, { cell }) => (soil.get(cell)?.tilled ? true : 'notTilled'),
|
|
54
56
|
run: (e, { cell }) => soil.set(cell, { watered: true }) });
|
|
55
|
-
engine.ops.define('
|
|
56
|
-
engine.sky.at('06:00', () => engine.ops.run('
|
|
57
|
+
engine.ops.define('plot.dry', { run: () => soil.updateAll(d => { delete d.watered; }) }); // bulk change; return null from fn to clear a cell
|
|
58
|
+
engine.sky.at('06:00', () => engine.ops.run('plot.dry')); // daily reset is the game's job
|
|
57
59
|
```
|
|
58
60
|
`get(cell)`, `set(cell, patch)` (merge; a field set to null is deleted), `clear(cell)`, `query(cell?, size?)` -> `[{ cell, data }]`, `updateAll(fn)`, `count`.
|
|
59
61
|
Writes are saved gameplay state: do them inside an op or a fixed step (the guard reports anything else). Data must be plain values.
|
|
60
62
|
Cells that exist from the start go in content: `content/grids.js` <!-- r18-ignore-line -->
|
|
61
|
-
`
|
|
63
|
+
`plot: { cell: 1, origin: [20, 0], size: [8, 8], layers: { soil: [[3, 5, { tilled: true }]] } }` <!-- r18-ignore-line -->
|
|
62
64
|
(or `grids.add(name, { layers })`). They are the baseline: a save keeps only cells changed from it, so editing the content later still reaches old saves.
|
|
63
65
|
|
|
64
|
-
**Tiles.** The game gives a layer its colors: `
|
|
66
|
+
**Tiles.** The game gives a layer its colors: `plot.layer('soil', { tiles: { look: d => d.watered ? 0x5b3d2a : d.tilled ? 0x8a6243 : null } })`
|
|
65
67
|
(what the data means is gameplay, so no style pack ships these). A layer with tiles shows crisp per-cell quads just above the ground, following its
|
|
66
68
|
height (slopes, ramps, level meshes).
|
|
67
|
-
`
|
|
69
|
+
`tiles: { colors: { watered: 0x5b3d2a, tilled: 0x8a6243 } }` is the same as `look` from a table (first truthy field wins) and wins over a style pack's `style.grid.tiles`; `plot.layer('soil', { tiles: false })` turns them off; `{ tiles: true }` draws every non-empty cell gray; `lift` raises them; `{ tiles:
|
|
68
70
|
(engine, layer) => ({ update(cells), dispose() }) }` is your own view. Options are read when the layer is first created.
|
|
69
71
|
|
|
70
72
|
## 4. Preview
|
|
71
73
|
```js
|
|
72
74
|
engine.input.define('place', ['Mouse0'], 'Place'); // gameplay reads input actions, not pointer.clicked (recipe 26)
|
|
73
|
-
const pv = engine.grids.preview({ grid: '
|
|
75
|
+
const pv = engine.grids.preview({ grid: 'board', item: 'tower', ...presets.keys.gridRotate }); // under the pointer; from: 'front' = the cell in front of the player
|
|
74
76
|
engine.onFrame(() => {
|
|
75
|
-
if (engine.input.pressed('place')) { const r = pv.place(); if (!r.ok) toast(engine, engine.t('grid.' + r.reason)); }
|
|
77
|
+
if (engine.input.pressed('place')) { const r = pv.place(); if (!r.ok) toast(engine, engine.t('grid.' + (r.code ?? r.reason))); } // reason only for 'noTarget'
|
|
76
78
|
});
|
|
77
79
|
pv.remove(); // leave build mode
|
|
78
80
|
```
|
|
79
81
|
The engine binds no key: `...presets.keys.gridRotate` (or `rotateKeys: ['KeyR']`) defines the action `rotate` on R, or bind that action yourself with
|
|
80
82
|
`input.define`; pass `rotate: 'myAction'` to read another one, `false` for none. Without a binding the preview warns once and only `pv.rotate()` turns
|
|
81
|
-
it. `pv.cell`, `pv.rotation`, `pv.ok`, `pv.reason`
|
|
83
|
+
it. `pv.cell`, `pv.rotation`, `pv.ok`, `pv.reason` (the `can` answer)
|
|
82
84
|
are readable every frame.
|
|
83
85
|
Colors come from `style.grid.ok / bad / previewOpacity`. `look: false` hides the default box; `look: (engine) => ({ update(view), hide(), dispose()
|
|
84
86
|
})` draws your own (`view = { cells, center, size, rotation, ok, reason }`).
|
|
85
87
|
|
|
86
|
-
## 5.
|
|
87
|
-
|
|
88
|
+
## 5. Baked data vs state the player changes
|
|
89
|
+
Anything the player can change in play must be runtime state, never baked into generated height or ground-type data: a tilled plot (farming), a dug or mined
|
|
90
|
+
tile (survival), a road or placed floor (city builder), a painted tile (puzzle), a breakable wall (action). Bake only what never changes: the landform (hills,
|
|
91
|
+
valleys, coast). Runtime state is a grid cell (`layer`), a `terrain.edit` (lower / raise / paint a ground type) or a world record (`grid.place`); all three are
|
|
92
|
+
saved, while a baked version cannot be changed in game and is not saved. A save keeps only what differs from the generated base.
|
|
93
|
+
```js
|
|
94
|
+
engine.use(terrain({ height: (x, z) => 3 + Math.sin(x * 0.05) * 2 }), world(), grids()); // generated: the landform only
|
|
95
|
+
engine.grids.add('plots', { cell: 4, origin: [8, 16], size: [4, 4] });
|
|
96
|
+
engine.ops.define('plot.dig', { args: { cell: 'any' },
|
|
97
|
+
can: (e, { cell }) => (e.grids.get('plots').inside(cell) ? true : 'outOfBounds'),
|
|
98
|
+
run: (e, { cell }) => {
|
|
99
|
+
const [x, z] = [8 + cell[0] * 4 + 2, 16 + cell[1] * 4 + 2]; // cell centre
|
|
100
|
+
e.terrain.edit({ x, z }, { shape: 'square', radius: 2, lower: 0.5, paint: 'dug' }); // ground shape and type
|
|
101
|
+
e.grids.get('plots').layer('state').set(cell, { dug: true }); // per-cell game state
|
|
102
|
+
} });
|
|
103
|
+
```
|
|
104
|
+
Undo with `paint: null` and `raise`. The test "player-changed ground" (`tests/specs/terrain-edit.mjs`) runs this pattern: save, then load into a fresh engine.
|
|
105
|
+
|
|
106
|
+
## 6. Verify
|
|
107
|
+
`engine.describe().grids` -> `{ room: { occupied, items: { bed: 1 }, layers: {} }, plot: { ..., layers: { soil: 30 } } }`. Tests: `npx threedog test "grid:"`.
|
|
@@ -1,24 +1,25 @@
|
|
|
1
1
|
# Environment lighting
|
|
2
2
|
|
|
3
|
-
The engine gives the mechanism and sets nothing: `scene.environment` is `null` until a style pack or the game asks for one, so the
|
|
4
|
-
|
|
3
|
+
The engine gives the mechanism and sets nothing: `scene.environment` is `null` until a style pack or the game asks for one, so the default look
|
|
4
|
+
(lit by the sun and hemisphere lights only) is unchanged. The background (the sky dome or `sky.skybox`) and the environment lighting are two separate fields.
|
|
5
5
|
|
|
6
6
|
```js
|
|
7
|
-
engine.
|
|
8
|
-
engine.
|
|
9
|
-
engine.
|
|
10
|
-
engine.
|
|
7
|
+
engine.look.env.replace('sky'); // lit by the procedural sky; follows the time of day
|
|
8
|
+
engine.look.env.set({ intensity: 0.8 });
|
|
9
|
+
engine.look.env.replace('hdr/studio.hdr'); engine.look.env.set({ intensity: 1, rotation: Math.PI / 2 }); // an HDR / panorama asset (equirectangular)
|
|
10
|
+
engine.look.env.set({ intensity: 0.5 }); // fields given change, the rest stay
|
|
11
|
+
engine.look.env.replace(false); // off, GPU memory released
|
|
11
12
|
engine.sky.environment; // { source, intensity, rotation, interval, builds } or null
|
|
12
13
|
```
|
|
13
|
-
A pack gives defaults in `sky.environment` (same fields, plus `low`), the game overrides with `sky({ environment: {...} })` or
|
|
14
|
-
`
|
|
14
|
+
A pack gives defaults in `sky.environment` (same fields, plus `low`), the game overrides with `sky({ environment: {...} })` or at run time with
|
|
15
|
+
`look.env.replace(...)` / `look.env.set(...)`. `low: false` turns it off on low-tier devices; any other `low` object replaces fields there.
|
|
15
16
|
|
|
16
17
|
## Sources
|
|
17
18
|
- `'sky'`: the dome is rendered into a cube and prefiltered with `PMREMGenerator`. It is rebuilt only when the sky colors, sun direction or cloud
|
|
18
19
|
cover actually changed AND at least `interval` seconds (default 1, low tier 4x) passed since the last check, never every frame. A fixed time of
|
|
19
20
|
day builds once. The first build waits for the first frame so it uses real colors. With `sky.skybox` use the skybox asset name as `source`.
|
|
20
21
|
- an asset name or path: `.hdr` loads through three's `HDRLoader` (float, linear), `.jpg` / `.png` / `.ktx2` as ordinary textures. The asset system
|
|
21
|
-
owns the texture; the engine owns only the prefiltered copy and disposes it on `
|
|
22
|
+
owns the texture; the engine owns only the prefiltered copy and disposes it on `look.env.replace(false)`, on a new source and on `engine.dispose()`.
|
|
22
23
|
- The cube is at least 256 px per face (PMREMGenerator's floor in 0.187), so a low tier saves time by rebuilding less often or by turning it off, not
|
|
23
24
|
by a smaller cube.
|
|
24
25
|
|
|
@@ -30,6 +31,6 @@ A pack gives defaults in `sky.environment` (same fields, plus `low`), the game o
|
|
|
30
31
|
reflections from the scene environment (use a Standard / Physical material for that).
|
|
31
32
|
- Intensity is `scene.environmentIntensity`, direction offset is `scene.environmentRotation` (Y only here).
|
|
32
33
|
- The hemisphere light stays and adds on top. When you turn the environment on, lower the ambient column of `sky.keyframes` (or
|
|
33
|
-
`sky.modify('env', { ambient: 0.5 })
|
|
34
|
+
`sky.modify('env', { ambient: 0.5 })`, [recipe 52](52-look.md#skymodify-vs-looklights)) so shadows do not wash out.
|
|
34
35
|
- The first frame with an environment recompiles every Lambert program once (the program key gains the env map); do it at start-up, not mid-game.
|
|
35
36
|
- Toon, Basic and ShaderMaterial surfaces ignore it.
|
|
@@ -1,9 +1,24 @@
|
|
|
1
1
|
# Making a new look from a reference picture
|
|
2
2
|
|
|
3
|
-
For an AI that is given one picture ("make it look like this") and has to turn it into a style pack.
|
|
4
|
-
`
|
|
5
|
-
|
|
6
|
-
|
|
3
|
+
For an AI that is given one picture ("make it look like this") and has to turn it into a style pack. The tools keep the work measurable: `threedog style palette`
|
|
4
|
+
and `style compare` measure pictures, `npm run new-style` makes the pack, `threedog style check` finds mistakes before you look at pixels. They never say which
|
|
5
|
+
colors are right; the taste is yours. What a style is and the composing rules are in `09-style-pack.md`; this page is the order of work.
|
|
6
|
+
|
|
7
|
+
## The loop (every round, in this order)
|
|
8
|
+
Looping "edit, screenshot, read the image" costs the most tokens and fixes the least. Numbers come first, pictures last.
|
|
9
|
+
1. **Measure the reference once** (step 2 below): `style palette <ref> --average`, then `style compare <ref> <your shot>`.
|
|
10
|
+
2. **Change one family of values** (colors, then materials, then post).
|
|
11
|
+
3. **Shoot small and compare to the previous shot**: `threedog shot styletest --view overview --size 480x270 --keep --compare <previous.png>`. It prints the
|
|
12
|
+
pixel diff and the look differences. Through MCP the `snap` tool is 480 px wide by default; `style_compare` gives the numbers.
|
|
13
|
+
4. **Read the numbers first, then at most one image per round.** Name the biggest remaining difference and fix only that.
|
|
14
|
+
5. **Wrong in a way the numbers do not explain?** Diagnose before guessing: `engine.debug.view('albedo' | 'lighting' | 'shadow' | 'normals')` shows which
|
|
15
|
+
layer is off, `engine.describe().look` shows who set each value and where (recipe 52). Nothing drawn: `threedog scene --hidden` (reasons per mesh).
|
|
16
|
+
6. **After two rounds without reaching the reference, take the next exit** and tell the user which and why: `look.surface.patch('detail' | 'lighting', glsl)`
|
|
17
|
+
-> painted textures (`map`, `normalMap`) -> `look.materials.replace` -> plain three.js (recipe 40 section 8). Never call it "close" to stop tuning.
|
|
18
|
+
7. **Every few rounds show the user the shot and the numbers.**
|
|
19
|
+
|
|
20
|
+
The loop is the same for every art direction; only what you measure and which value you move differ: flat (palette share, hard edges, no shading), painterly
|
|
21
|
+
(soft edges, texture, low contrast), low-poly (few flat colors, faceted light), realistic (exposure, tone mapping, lighting, material roughness). None is the default.
|
|
7
22
|
|
|
8
23
|
## What a style can change, and what it cannot
|
|
9
24
|
Can change (all in the style pack): colors (`palette`, `terrain.colors`, `background`, `water.color`, season tints), material types per role
|
|
@@ -18,57 +33,37 @@ world (a canyon instead of hills), say so instead of faking it with colors.
|
|
|
18
33
|
|
|
19
34
|
## Steps
|
|
20
35
|
1. **Keep the picture.** Put it in the game's `art/reference/` (one file per look, with a few lines of notes beside it on what to copy:
|
|
21
|
-
palette, mood, line work, light direction).
|
|
22
|
-
2. **Measure it.** `threedog style palette art/reference/ref.png --n 8` prints JSON (colors with share, hue, saturation,
|
|
23
|
-
largest block = ground / environment candidate, brightest = highlight / sky candidate, most saturated = accent candidate,
|
|
24
|
-
outline candidate) and one summary line such as `warm colors, mostly sand, low saturation, medium brightness, weak light/dark contrast`.
|
|
25
|
-
reads pixels in a headless browser (png, jpg, webp, gif, svg).
|
|
26
|
-
|
|
27
|
-
`--ignore-ui` (cuts a flat frame around the picture) or `--region x,y,w,h` (only that rectangle), `--crop cut.png` to save exactly what was
|
|
28
|
-
measured and open it, and `--average` for the overall mean color (HSL). The output says what area was measured.
|
|
36
|
+
palette, mood, line work, light direction). Use the highest-resolution picture you have: a small or compressed one gives wrong detail and brightness numbers.
|
|
37
|
+
2. **Measure it.** `threedog style palette art/reference/ref.png --n 8 --average` (MCP: `style_palette`) prints JSON (colors with share, hue, saturation,
|
|
38
|
+
brightness, and role hints: largest block = ground / environment candidate, brightest = highlight / sky candidate, most saturated = accent candidate,
|
|
39
|
+
darkest = shadow or outline candidate) and one summary line such as `warm colors, mostly sand, low saturation, medium brightness, weak light/dark contrast`.
|
|
40
|
+
It reads pixels in a headless browser (png, jpg, webp, gif, svg). The overall mean (`--average`) sets exposure and tint; the clusters pick the named
|
|
41
|
+
palette entries. A phone screenshot with a dark UI frame needs `--ignore-ui` or `--region x,y,w,h`; `--crop cut.png` saves exactly what was measured.
|
|
29
42
|
3. **Make the pack.** `npm run new-style sand-dune` creates `packages/styles/sand-dune` from a clean template (gray neutral materials, a sky, one
|
|
30
43
|
palette, no post effects, one palette-colored example model) and links it as `@threedog/style-sand-dune`. Import it in the game:
|
|
31
44
|
`import style, { assets } from '@threedog/style-sand-dune'`, `createEngine({ canvas, style })`, `engine.assets.manifest(assets)`.
|
|
32
|
-
To start from another pack's strengths instead, compose: `style: [
|
|
45
|
+
To start from another pack's strengths instead, compose: `style: [basePack, sandDune]` (later parts win key by key).
|
|
33
46
|
4. **Fill it in, in this order** (each step changes the picture most for the least work): `sky` and `background` (light and mood), `exposure` and
|
|
34
|
-
`toneMapping`, `palette` and `terrain.colors` / `biomeColors` (the measured colors, snapped to a few named ones
|
|
35
|
-
|
|
36
|
-
|
|
47
|
+
`toneMapping`, `palette` and `terrain.colors` / `biomeColors` (the measured colors, snapped to a few named ones; a reference usually has 5 to 8 that
|
|
48
|
+
matter), `materials` (`lambert` matte, `toon` banded, `phong` shiny, `standard` PBR, `basic` unlit), `post`, then `ui`. The first frame should already be close:
|
|
49
|
+
if it is far from the reference, fix sky, exposure, palette and material type before adding anything.
|
|
37
50
|
5. **Check.** `threedog style check sand-dune` (or the folder / file of a game's own style). It checks the final merged style, not each part:
|
|
38
51
|
unknown fields (with "did you mean"), world-state fields, palette keys a model reads but the style does not define, color formats (`'ff8800'`
|
|
39
52
|
without `#`, a float, a string `'0xff8800'`), post-effect conflicts (same name twice, two `scene` effects, a depth reader after a buffer-swapping
|
|
40
53
|
effect, `dof` ordered after `outline`), misspelled material roles and types, and asset names the pack does not register. `--json` gives the same list for
|
|
41
54
|
tools, `--assets file.js` adds another pack's names. Exit code 1 on errors. It is static: it cannot prove a pack holds no gameplay logic, only
|
|
42
55
|
the patterns R34 can see (`npm run check` runs R34).
|
|
43
|
-
6. **Look.** Take pictures with the same arguments every round so only the style differs
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
score (there is deliberately no "similarity %"); it turns "looks dirty / fragmented / too dark" into something you can change and re-measure.
|
|
51
|
-
7. **Iterate.** Change one family of values per round (colors, then materials, then post), re-run `style check`, shoot again. Stop when the
|
|
52
|
-
biggest remaining difference is a silhouette or a world rule: that is the asset pack or the game, not the style.
|
|
53
|
-
|
|
54
|
-
## Method lessons (from matching a reference picture)
|
|
55
|
-
- **Measure first, then build.** Run `style palette --average` and `style compare` before touching values; guessing by eye and getting "close" rejected
|
|
56
|
-
several times costs more than ten minutes of measuring.
|
|
57
|
-
- **Take the overall average, not clustered colors.** The tone of a picture is its mean (`--average`), not the 8 colors a median cut finds; a few
|
|
58
|
-
bright accents can dominate the clusters and say little about the look. Use clusters for picking named palette entries, the mean for exposure and tint.
|
|
59
|
-
- **Use the highest-resolution reference you have**, and crop away phone UI (`--ignore-ui` / `--region`). A small, compressed or UI-framed picture
|
|
60
|
-
gives wrong fine-detail and brightness numbers.
|
|
61
|
-
- **Restraint: an effect the reference does not show is not added.** Smudge filters, AO and tone changes stacked together made a picture worse with every
|
|
62
|
-
layer. Start with no post effects, add one only for a visible difference you named, and measure again after each one. `style check` warns when more than 2 are on.
|
|
63
|
-
- **The first frame should already be close.** Get sky, exposure, palette and material type right in the first round; if the first screenshot is far
|
|
64
|
-
from the reference, fix that (one family of values at a time) before adding anything.
|
|
65
|
-
- **Quantify "dirty / fragmented / dark".** Dirty = lower saturation or an off hue (average color), fragmented = fine detail ratio well above 1,
|
|
66
|
-
dark or flat = brightness and contrast. Change one thing, run `style compare` again, keep it if the number moved toward the reference and the picture looks better.
|
|
67
|
-
- **Nothing drawn?** Do not bisect with screenshots: `threedog scene --hidden` lists every mesh that exists but is not drawn and why (hidden parent, layers, scale 0,
|
|
68
|
-
empty geometry, behind the camera...). A mesh that is drawn but far too small is not an error there, but its position and bounding radius are listed:
|
|
69
|
-
compare them with what you meant (`scene` without `--hidden`).
|
|
56
|
+
6. **Look: the loop above.** Take pictures with the same arguments every round so only the style differs, and use the style test page's named camera
|
|
57
|
+
views (below), not free `--pos` shots. `threedog style compare art/reference/ref.png .threedog/shots/styletest.png [--region x,y,w,h]` prints brightness,
|
|
58
|
+
saturation, contrast, fine detail, average and main color of both and one sentence such as "the screenshot is 18% darker and 2.3x more broken up". There is
|
|
59
|
+
deliberately no "similarity %": the numbers turn "looks dirty / fragmented / too dark" into something you can change and re-measure. Dirty = lower
|
|
60
|
+
saturation or an off hue, fragmented = fine detail ratio well above 1, dark or flat = brightness and contrast. Keep a change if its number moved toward
|
|
61
|
+
the reference and the picture looks better. A phone UI frame in the screenshot skews the numbers: compare a `--region`.
|
|
62
|
+
7. **Stop** when the biggest remaining difference is a silhouette or a world rule: that is the asset pack or the game, not the style.
|
|
70
63
|
|
|
71
64
|
## Guard rails
|
|
65
|
+
- Restraint: an effect the reference does not show is not added. Start with no post effects, add one only for a visible difference you named, and measure
|
|
66
|
+
again after each one. `style check` warns when more than 2 are on.
|
|
72
67
|
- Never put gameplay or world values in the pack to match a picture; `style check` reports them as errors.
|
|
73
68
|
- Fonts and textures are asset-pack entries; the style names them (`ui.fonts: ['pixel']`, `terrain.detail.texture`), it does not carry files.
|
|
74
69
|
- Keep `npm run check` at 0 errors; a new pack adds no warnings.
|
|
@@ -78,12 +73,12 @@ world (a canyon instead of hills), say so instead of faking it with colors.
|
|
|
78
73
|
a shadow receiver, wood / stone / metal surfaces, a lit room (outside and inside) and the UI parts. Same arguments, same picture, so only the style differs.
|
|
79
74
|
- `threedog shot styletest --view <name> [--time day|dusk|night] [--weather clear|rain|snow]`; the same words work as URL parameters
|
|
80
75
|
(`?view=room&time=dusk&weather=rain`; also `style=none` for the engine's gray placeholders, `env=1` for environment lighting from the sky).
|
|
81
|
-
- Views: `overview` (everything
|
|
76
|
+
- Views: `overview` (everything: overall brightness, ground color, shadow darkness), `character` (close-up: character colors, outline, shadow on
|
|
82
77
|
the ground), `water` (water color, shore, fog at distance), `room` (the lamp and window light against the dark corners: ambient level, `ao`, bloom),
|
|
83
78
|
`path` (the camera moves along a fixed line at 2.5 m/s: with `--wait 4` the shot is the same frame every time; in a browser look for grass blades
|
|
84
79
|
and shadow edges that flicker or crawl), `ui` (HUD, dialogue line, bag window: the `ui` colors).
|
|
85
|
-
- Per round: shoot `overview`, `room` at `--time dusk`, and `character
|
|
80
|
+
- Per round: shoot `overview`, `room` at `--time dusk`, and `character`.
|
|
86
81
|
- `?panel=1` opens the workbench (needs the dev package `tweakpane`, installed with the repository's `npm install`; without it the page says so).
|
|
87
82
|
Live sliders change exposure, sky time, environment lighting, water color, post effects and UI colors at once; palette, terrain and wave values
|
|
88
83
|
are marked "needs rebuild" and only apply after "apply and rebuild". "export overrides" prints an object literal to paste into
|
|
89
|
-
`style: [
|
|
84
|
+
`style: [yourPack, { ... }]`; the original pack is never written, so the paste is the one place the change becomes real.
|
|
@@ -2,13 +2,13 @@
|
|
|
2
2
|
|
|
3
3
|
For an AI turning a reference picture into a style pack and hitting "the engine draws it this way". Colors and materials are in `09-style-pack.md`, the
|
|
4
4
|
order of work in `35-style-from-reference.md`. This page lists the places where the *shape* of a look was fixed in engine code and is now a style
|
|
5
|
-
setting.
|
|
5
|
+
setting. Each table lists the engine default; a style that sets nothing here gets those defaults. Style packs hold looks only
|
|
6
6
|
(rule R34): none of these settings move a hill, a river or a species list.
|
|
7
7
|
|
|
8
8
|
## Sky clouds: `style.sky.clouds`
|
|
9
9
|
| Key | Meaning | Default |
|
|
10
10
|
|---|---|---|
|
|
11
|
-
| `color`, `shade`, `coverage`, `scale`, `speed` |
|
|
11
|
+
| `color`, `shade`, `coverage`, `scale`, `speed` | lit color, shaded color, cover (multiplies the weather's cloud amount), size, drift speed | |
|
|
12
12
|
| `kind` | `'plane'` cheap, 3 noise samples. `'cumulus'` billowy, 8 noise samples per cloudy sky pixel, flatter projection (clouds fill the whole sky instead of crowding at the horizon), the sun side of each cloud is lit and the underside shaded | `'plane'` |
|
|
13
13
|
| `horizon` | added to `dir.y` before projecting; smaller = clouds shrink and crowd more towards the horizon | plane 0.08, cumulus 0.5 |
|
|
14
14
|
| `fade` | `[from, to]` in `dir.y`: invisible below `from`, full above `to` | plane `[0, 0.18]`, cumulus `[0, 0.12]` |
|
|
@@ -37,14 +37,14 @@ vec4 threedogClouds(vec3 dir, float time, vec3 sunDir, float night, vec3 lit, ve
|
|
|
37
37
|
```
|
|
38
38
|
In scope: the GLSL noise helpers `float threedogHash(vec2 p)` and `float threedogNoise(vec2 p)`, the built-in cloud uniforms (`uCloudScale`, `uCloudSpeed`, `uCloudHorizon`, `uCloudFade`...) and
|
|
39
39
|
your `clouds.uniforms` (declared for you; number, `THREE.Color`, `THREE.Vector2/3/4`, array of 2-4 numbers, or `THREE.Texture`). Change one later
|
|
40
|
-
with `engine.sky.dome.material.uniforms.
|
|
41
|
-
|
|
40
|
+
with `engine.sky.dome.material.uniforms.uEdge.value = 0.1`. A bad `kind`, a `glsl` without the function, or an unsupported uniform value throws with the fix.
|
|
41
|
+
Flat painted cloud blobs with a hard edge, multiplied by a texture:
|
|
42
42
|
```js
|
|
43
43
|
clouds: { color: 0xfff1dc, shade: 0x9aa8c4, uniforms: { uPaper: paperTexture, uEdge: 0.06 }, // paperTexture: any THREE.Texture, repeat wrapping
|
|
44
44
|
glsl: `vec4 threedogClouds(vec3 d, float time, vec3 sunDir, float night, vec3 lit, vec3 shade, float cover){
|
|
45
45
|
vec2 p = d.xz / (d.y + 0.5) * 0.4 + vec2(0.004, 0.002) * time;
|
|
46
46
|
float n = threedogNoise(p) * 0.65 + threedogNoise(p * 2.3 + 5.0) * 0.35;
|
|
47
|
-
float a = smoothstep(1.0 - cover, 1.0 - cover + uEdge, n); // hard
|
|
47
|
+
float a = smoothstep(1.0 - cover, 1.0 - cover + uEdge, n); // hard edge
|
|
48
48
|
float up = clamp(0.5 + (n - threedogNoise(p + sunDir.xz * 0.1)) * 6.0, 0.0, 1.0); // sun side
|
|
49
49
|
vec3 c = mix(shade, lit, up) * texture2D(uPaper, p * 3.0).rgb * (0.35 + 0.65 * (1.0 - night));
|
|
50
50
|
return vec4(c, a * smoothstep(0.0, 0.1, d.y));
|
|
@@ -52,36 +52,38 @@ clouds: { color: 0xfff1dc, shade: 0x9aa8c4, uniforms: { uPaper: paperTexture, uE
|
|
|
52
52
|
```
|
|
53
53
|
|
|
54
54
|
## Ground color: `style.terrain.variation`
|
|
55
|
-
Terrain colors are baked
|
|
56
|
-
|
|
55
|
+
Terrain colors are baked by the (worker) generator from the palette: two palette colors blended by a noise, a small brightness grain, and an
|
|
56
|
+
optional layer of large patches. The defaults are shown (plain data, so it travels to the workers; unknown keys throw):
|
|
57
57
|
```js
|
|
58
58
|
terrain: { colors: { ... }, biomeColors: { ... },
|
|
59
59
|
variation: {
|
|
60
60
|
blend: { size: 33, strength: 1 }, // wavelength in m of the two-color noise; strength > 1 = harder contrast, < 1 = flatter
|
|
61
61
|
jitter: { size: 0.33, min: 0.92, range: 0.12 }, // grain cell in m; darkest multiplier; how much brighter it can get (0 range = no grain)
|
|
62
|
-
patches: { size: 90, strength: 0.15, levels: 0, tint: 0xb59a5a }, // optional second, large layer
|
|
62
|
+
patches: { size: 90, strength: 0.15, levels: 0, tint: 0xb59a5a }, // optional (example values): a second, large layer of color blocks
|
|
63
63
|
} }
|
|
64
64
|
```
|
|
65
|
-
`patches` is off unless given. It is a noise much larger than `blend`; `levels: 4` snaps it to 4 flat steps (
|
|
66
|
-
|
|
67
|
-
interpolate across a chunk cell (4 m at the default resolution), so blocks smaller than that blur; for crisp
|
|
65
|
+
`patches` is off unless given. It is a noise much larger than `blend`; `levels: 4` snaps it to 4 flat steps (hard-edged color blocks instead of a
|
|
66
|
+
soft blend); without `tint` it lightens and darkens the ground, with `tint` it pulls the color towards the tint where the noise is high. Vertex colors
|
|
67
|
+
interpolate across a chunk cell (4 m at the default resolution), so blocks smaller than that blur; for crisp blocks use `shading: 'texture'`
|
|
68
|
+
(recipe 37) or a texture (next). Which combination fits which look, and ground that looks wrong up close: recipe 53.
|
|
68
69
|
|
|
69
|
-
###
|
|
70
|
+
### Your own ground material
|
|
70
71
|
`style.terrain.material` (a Material or `(engine) => Material`) replaces the ground material. Chunk geometry has `uv = world xz / chunk size`, continuous
|
|
71
72
|
across chunk borders (checked by `tests/specs/appearance.mjs`), so a repeating texture is seamless whatever chunk it lands in; cloud shadows and
|
|
72
73
|
season tint are added to your material. `texture.repeat.set(8, 8)` = 8 tiles per chunk. Without UVs (steep sides stretch a top-down map), project
|
|
73
74
|
from the world position in a patch instead (`needs.patches: ['world']` gives `vThreedogWorld`):
|
|
74
75
|
```js
|
|
75
76
|
material: engine => applyEffects(new THREE.MeshLambertMaterial({ vertexColors: true }), { clouds: false, patches: [{
|
|
76
|
-
name: 'triplanar', needs: { patches: ['world'] }, uniforms: {
|
|
77
|
-
glsl: { fragment: { pars: 'uniform sampler2D
|
|
77
|
+
name: 'triplanar', needs: { patches: ['world'] }, uniforms: { uTex: { value: groundTexture }, uTexScale: { value: 0.1 } }, // groundTexture: repeat wrapping
|
|
78
|
+
glsl: { fragment: { pars: 'uniform sampler2D uTex; uniform float uTexScale;',
|
|
78
79
|
color_fragment: `vec3 n = abs(normalize(cross(dFdx(vThreedogWorld), dFdy(vThreedogWorld)))); n /= n.x + n.y + n.z;
|
|
79
|
-
diffuseColor.rgb *= texture2D(
|
|
80
|
-
+ texture2D(
|
|
80
|
+
diffuseColor.rgb *= texture2D(uTex, vThreedogWorld.zy * uTexScale).rgb * n.x + texture2D(uTex, vThreedogWorld.xz * uTexScale).rgb * n.y
|
|
81
|
+
+ texture2D(uTex, vThreedogWorld.xy * uTexScale).rgb * n.z;` } } }] })
|
|
81
82
|
```
|
|
82
83
|
A procedural noise texture is a `THREE.DataTexture` filled in a loop (`wrapS = wrapT = THREE.RepeatWrapping`, `colorSpace = THREE.SRGBColorSpace`,
|
|
83
|
-
`needsUpdate = true`)
|
|
84
|
-
`detail`
|
|
84
|
+
`needsUpdate = true`). The lighter alternative is a detail layer, `style.terrain.detail` / `look.ground.set({ detail })`: the same object as a
|
|
85
|
+
material spec's `detail` (`noise: 'grain' | 'paper' | 'stroke' | 'dabs'`, or `texture: 'name'`, or your own `glsl`; `scale`, `strength`, `fade`
|
|
86
|
+
...; keys in recipe 43), with no material of your own. Which to pick: recipe 53.
|
|
85
87
|
|
|
86
88
|
## Plants and wind
|
|
87
89
|
Audit of what the vegetation code fixes, split into mechanism (stays) and look (made a setting):
|
|
@@ -92,11 +94,11 @@ Audit of what the vegetation code fixes, split into mechanism (stays) and look (
|
|
|
92
94
|
| `GroundChunks`, `Vegetation.levelOf` | one InstancedMesh per species per chunk; rings decide LOD swap, draw distance, shadow distance; 3 ms placement budget; collision lag | mechanism, stays |
|
|
93
95
|
| wind sway shape | two sines (speed `1.2 + 0.6*uWind` and `2.9`, spatial phase from the instance origin), height-weighted, lean with wind strength | look: **`style.wind.glsl`** replaces it |
|
|
94
96
|
| wind speed | `uWindFreq` | already `style.wind.frequency` |
|
|
95
|
-
| season tint | `diffuseColor.rgb *= tint` (default) or a blend towards the tint; colors from `style.seasons` | look, both settings: `style.seasons.mode: 'multiply' \| 'mix'` (+ `strength`); see recipe
|
|
97
|
+
| season tint | `diffuseColor.rgb *= tint` (default) or a blend towards the tint; colors from `style.seasons` | look, both settings: `style.seasons.mode: 'multiply' \| 'mix'` (+ `strength`); see recipe 43 |
|
|
96
98
|
| defaults | `castShadow` = not `nearOnly`, `shadowRing` 1, `lodRing` 1 | per-species options, set them in the species |
|
|
97
99
|
|
|
98
100
|
```js
|
|
99
|
-
wind: { frequency: 1, uniforms: { uSteps: 3 }, //
|
|
101
|
+
wind: { frequency: 1, uniforms: { uSteps: 3 }, // stepped sway: plants snap between 3 poses instead of a smooth sine
|
|
100
102
|
glsl: `void threedogWind(inout vec3 transformed, vec3 ip, vec3 position){
|
|
101
103
|
float s = floor(sin(uTime * uWindFreq + ip.x * 0.3 + ip.z * 0.2) * uSteps) / uSteps;
|
|
102
104
|
transformed.x += s * max(position.y, 0.0) * THREEDOG_WIND_AMP * uWind;
|