threedog 1.0.1 → 1.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (364) hide show
  1. package/CHANGELOG.md +90 -0
  2. package/README.md +1 -1
  3. package/core/assets/Animator.js +41 -3
  4. package/core/assets/Assets.js +100 -24
  5. package/core/assets/assetEntry.js +73 -20
  6. package/core/assets/assetHot.js +68 -16
  7. package/core/assets/assetLoad.js +6 -6
  8. package/core/assets/assetLod.js +9 -2
  9. package/core/assets/assetManifest.js +12 -2
  10. package/core/assets/assetPart.js +54 -0
  11. package/core/assets/ik.js +271 -0
  12. package/core/assets/modelNeeds.js +37 -0
  13. package/core/assets/namedModel.js +102 -29
  14. package/core/assets/nodeVisibility.js +15 -0
  15. package/core/audio/Audio.js +36 -4
  16. package/core/audio/audioReverb.js +99 -0
  17. package/core/audio/audioRules.js +1 -1
  18. package/core/audio/audioVoice.js +1 -1
  19. package/core/base/Events.js +14 -4
  20. package/core/base/Random.js +1 -1
  21. package/core/base/Vars.js +1 -1
  22. package/core/base/docRef.js +51 -0
  23. package/core/base/errorCodes.js +178 -126
  24. package/core/base/errorHints.js +9 -7
  25. package/core/base/errors.js +25 -10
  26. package/core/base/events.generated.js +2 -0
  27. package/core/base/freeParts.js +76 -0
  28. package/core/base/math.js +28 -0
  29. package/core/base/sections.js +5 -5
  30. package/core/base/validate.js +31 -3
  31. package/core/engine/Engine.js +16 -6
  32. package/core/engine/Loading.js +5 -3
  33. package/core/engine/copies.js +1 -1
  34. package/core/engine/headlessLoad.js +4 -1
  35. package/core/engine/lifecycle.js +32 -16
  36. package/core/engine/loop.js +71 -27
  37. package/core/engine/moduleSlots.js +2 -2
  38. package/core/engine/moduleTypes.js +3 -3
  39. package/core/engine/modules.js +65 -39
  40. package/core/engine/page.js +6 -3
  41. package/core/engine/services.js +6 -5
  42. package/core/engine/startup.js +5 -5
  43. package/core/input/Input.js +28 -14
  44. package/core/input/inputContext.js +28 -16
  45. package/core/input/inputKeyboard.js +31 -3
  46. package/core/input/inputPad.js +4 -0
  47. package/core/input/inputPointer.js +2 -1
  48. package/core/input/inputSeat.js +1 -1
  49. package/core/inspect/Budget.js +109 -19
  50. package/core/inspect/DebugOverrides.js +28 -4
  51. package/core/inspect/Describe.js +17 -9
  52. package/core/inspect/Inspect.js +4 -2
  53. package/core/inspect/InspectMaterials.js +3 -1
  54. package/core/inspect/InspectPerf.js +19 -9
  55. package/core/inspect/InspectScene.js +32 -7
  56. package/core/inspect/MaterialInfo.js +19 -2
  57. package/core/inspect/UrlState.js +46 -27
  58. package/core/inspect/catalog.js +28 -9
  59. package/core/inspect/debugView.js +2 -1
  60. package/core/inspect/describeRender.js +25 -13
  61. package/core/inspect/describeText.js +14 -6
  62. package/core/inspect/lightWatch.js +1 -1
  63. package/core/inspect/metadata.generated.js +35 -17
  64. package/core/inspect/pictureChecks.js +148 -0
  65. package/core/inspect/pictureMenu.js +84 -0
  66. package/core/inspect/pictureWriters.js +26 -6
  67. package/core/inspect/textureBytes.js +12 -2
  68. package/core/inspect/toolDoor.js +2 -4
  69. package/core/ops/Ops.js +11 -4
  70. package/core/ops/holds.js +27 -10
  71. package/core/ops/opsAtomic.js +15 -7
  72. package/core/ops/opsGuard.js +2 -2
  73. package/core/ops/opsRun.js +8 -7
  74. package/core/ops/sharedPoint.js +72 -21
  75. package/core/ops/stacks.js +56 -16
  76. package/core/saves/SaveStore.js +9 -3
  77. package/core/saves/Saves.js +32 -23
  78. package/core/saves/saveApply.js +96 -44
  79. package/core/saves/saveIds.js +1 -1
  80. package/core/saves/saveVersions.js +7 -5
  81. package/core/saves/session.js +17 -8
  82. package/core/saves/stateReplace.js +34 -15
  83. package/core/scene/Rays.js +52 -10
  84. package/core/scene/Views.js +13 -7
  85. package/core/scene/adaptive.js +144 -21
  86. package/core/scene/drawOnly.js +17 -0
  87. package/core/scene/gameLights.js +44 -3
  88. package/core/scene/sceneMethods.js +13 -11
  89. package/core/scene/stepPoses.js +11 -3
  90. package/core/scene/targeting.js +5 -3
  91. package/core/scene/thingOps.js +1 -1
  92. package/core/scene/tier.js +15 -0
  93. package/core/stream/Batching.js +30 -7
  94. package/core/stream/Stream.js +26 -7
  95. package/core/stream/batchGroups.js +2 -2
  96. package/core/stream/chunkStream.js +7 -5
  97. package/core/stream/prepare.js +77 -0
  98. package/core/time/skip.js +3 -1
  99. package/core/time/time.js +4 -2
  100. package/docs/AI.md +82 -83
  101. package/docs/API.md +16 -16
  102. package/docs/CODEMAP.md +16 -11
  103. package/docs/COMMANDS.md +31 -33
  104. package/docs/CONVENTIONS.md +37 -49
  105. package/docs/MIGRATING-0.8.md +2 -2
  106. package/docs/MIGRATING-1.0.md +2 -2
  107. package/docs/THREE.md +28 -35
  108. package/docs/api/assets.md +3 -1
  109. package/docs/api/audio.md +4 -2
  110. package/docs/api/budget.md +5 -0
  111. package/docs/api/cameraRig.md +2 -2
  112. package/docs/api/characters.md +10 -8
  113. package/docs/api/collision.md +6 -4
  114. package/docs/api/engine.md +16 -16
  115. package/docs/api/events.md +3 -2
  116. package/docs/api/ground.md +6 -5
  117. package/docs/api/hud.md +4 -2
  118. package/docs/api/input.md +5 -5
  119. package/docs/api/particles.md +2 -1
  120. package/docs/api/photo.md +3 -0
  121. package/docs/api/post.md +7 -4
  122. package/docs/api/quests.md +2 -2
  123. package/docs/api/rays.md +1 -2
  124. package/docs/api/saves.md +7 -7
  125. package/docs/api/settings.md +2 -2
  126. package/docs/api/tools.md +3 -1
  127. package/docs/api/vars.md +1 -1
  128. package/docs/api/vegetation.md +4 -2
  129. package/docs/api/world.md +1 -1
  130. package/docs/recipes/01-new-game.md +16 -17
  131. package/docs/recipes/02-npc.md +22 -18
  132. package/docs/recipes/03-items-pickups.md +37 -35
  133. package/docs/recipes/04-quests.md +15 -10
  134. package/docs/recipes/05-props-bake.md +101 -95
  135. package/docs/recipes/06-clock-events.md +28 -28
  136. package/docs/recipes/07-flow-scenes-pause.md +29 -26
  137. package/docs/recipes/08-weather-sky.md +52 -64
  138. package/docs/recipes/09-materials-lights-models.md +26 -17
  139. package/docs/recipes/10-blender-level.md +15 -10
  140. package/docs/recipes/11-vehicles.md +12 -7
  141. package/docs/recipes/12-navmesh.md +44 -26
  142. package/docs/recipes/13-animation.md +56 -45
  143. package/docs/recipes/14-custom-module.md +21 -18
  144. package/docs/recipes/15-perf.md +61 -55
  145. package/docs/recipes/16-dev-bridge.md +23 -33
  146. package/docs/recipes/18-world.md +36 -42
  147. package/docs/recipes/19-shooting-picking.md +20 -15
  148. package/docs/recipes/20-content-actions-save.md +48 -56
  149. package/docs/recipes/21-camera.md +45 -54
  150. package/docs/recipes/22-shop-gold.md +12 -7
  151. package/docs/recipes/23-ops.md +25 -23
  152. package/docs/recipes/26-ui-parts.md +67 -47
  153. package/docs/recipes/27-net.md +12 -7
  154. package/docs/recipes/28-terrain.md +24 -21
  155. package/docs/recipes/29-grid.md +32 -27
  156. package/docs/recipes/30-templates.md +21 -20
  157. package/docs/recipes/31-audio.md +39 -22
  158. package/docs/recipes/32-action-game.md +19 -14
  159. package/docs/recipes/33-stream-sources.md +15 -11
  160. package/docs/recipes/34-environment-lighting.md +126 -70
  161. package/docs/recipes/35-picture-from-reference.md +8 -8
  162. package/docs/recipes/36-ground-plants.md +27 -21
  163. package/docs/recipes/40-scene.md +19 -28
  164. package/docs/recipes/43-shader-patches-surfaces.md +15 -12
  165. package/docs/recipes/44-water-weather-hooks.md +34 -31
  166. package/docs/recipes/45-cascaded-shadows.md +35 -26
  167. package/docs/recipes/46-blender-art-route.md +6 -1
  168. package/docs/recipes/49-game-module-contract.md +13 -8
  169. package/docs/recipes/50-own-renderer.md +6 -2
  170. package/docs/recipes/51-capability-catalog.md +15 -8
  171. package/docs/recipes/52-around-the-picture.md +34 -32
  172. package/docs/recipes/53-ground-up-close.md +6 -1
  173. package/docs/recipes/55-mods-time-wrap.md +27 -19
  174. package/docs/recipes/56-webgpu-tsl.md +74 -43
  175. package/docs/recipes/57-control.md +18 -13
  176. package/docs/recipes/58-input.md +26 -16
  177. package/docs/recipes/59-depth-post-effects.md +8 -3
  178. package/docs/recipes/60-judge-the-picture.md +9 -8
  179. package/docs/recipes/61-deploy.md +5 -0
  180. package/docs/recipes/62-picture-code.md +70 -79
  181. package/docs/recipes/63-third-person-start.md +47 -45
  182. package/docs/recipes/64-particles.md +22 -10
  183. package/docs/recipes/65-swarm.md +18 -13
  184. package/docs/recipes/66-common-tasks.md +38 -35
  185. package/examples/action/GAMEMAP.md +2 -3
  186. package/examples/action/main.js +3 -3
  187. package/examples/action/picture/lights.js +3 -1
  188. package/examples/perf-island/GAMEMAP.md +3 -3
  189. package/examples/perf-island/picture/lights.js +2 -1
  190. package/examples/plain-picture/GAMEMAP.md +1 -1
  191. package/examples/rc2d/GAMEMAP.md +1 -1
  192. package/examples/styletest/GAMEMAP.md +2 -2
  193. package/examples/styletest/main.js +1 -1
  194. package/examples/techniques/interior-light/README.md +3 -3
  195. package/examples/techniques/interior-light/interiorLight.js +2 -4
  196. package/examples/techniques/interior-light/picture/lights.js +2 -1
  197. package/examples/techniques/modular-building/picture/lights.js +3 -1
  198. package/examples/techniques/outlines-and-rim/picture/lights.js +3 -1
  199. package/examples/techniques/procedural-animation/README.md +1 -1
  200. package/examples/techniques/procedural-animation/main.js +1 -1
  201. package/examples/webgpu-tsl/GAMEMAP.md +1 -1
  202. package/examples/world/GAMEMAP.md +2 -3
  203. package/examples/world/art/humanoid.js +1 -1
  204. package/examples/world/main.js +6 -3
  205. package/index.d.ts +2 -2
  206. package/llms.txt +101 -0
  207. package/modules/ambience/Ambience.js +21 -5
  208. package/modules/calendar/index.js +9 -5
  209. package/modules/calendar/schedule.js +23 -8
  210. package/modules/camera/FirstPersonCamera.js +3 -1
  211. package/modules/camera/FollowCamera.js +10 -5
  212. package/modules/camera/RtsCamera.js +4 -3
  213. package/modules/camera/common.js +70 -8
  214. package/modules/camera/contract.js +1 -1
  215. package/modules/characters/Character.js +16 -10
  216. package/modules/characters/NPC.js +31 -19
  217. package/modules/characters/assetModel.js +14 -9
  218. package/modules/characters/astar.js +6 -1
  219. package/modules/characters/contract.js +2 -2
  220. package/modules/characters/index.js +34 -22
  221. package/modules/characters/movers/manual.js +1 -1
  222. package/modules/characters/movers/rapier.js +17 -2
  223. package/modules/characters/movers/simple.js +1 -1
  224. package/modules/characters/movers/support.js +16 -7
  225. package/modules/characters/npcAvoid.js +2 -2
  226. package/modules/characters/npcSim.js +3 -2
  227. package/modules/characters/pathAsync.js +24 -8
  228. package/modules/characters/pathJob.js +1 -1
  229. package/modules/characters/player.js +10 -9
  230. package/modules/characters/playerStrings.js +5 -5
  231. package/modules/characters/proceduralRig.js +5 -5
  232. package/modules/characters/useModel.js +6 -0
  233. package/modules/characters/walkTo.js +1 -1
  234. package/modules/collision/Collision.js +29 -18
  235. package/modules/collision/grid.js +22 -4
  236. package/modules/content/index.js +3 -1
  237. package/modules/content/loader.js +1 -1
  238. package/modules/content/models.js +82 -33
  239. package/modules/content/props.js +2 -1
  240. package/modules/content/rules.js +11 -5
  241. package/modules/content/templates.js +3 -3
  242. package/modules/content/words.js +2 -2
  243. package/modules/debug/DebugPanel.js +9 -9
  244. package/modules/flow/index.js +9 -6
  245. package/modules/gameplay/Dialogue.js +34 -20
  246. package/modules/gameplay/Interactions.js +19 -15
  247. package/modules/gameplay/Inventory.js +9 -4
  248. package/modules/gameplay/Quests.js +12 -10
  249. package/modules/gameplay/pickups.js +23 -11
  250. package/modules/grid/index.js +1 -1
  251. package/modules/grid/preview.js +2 -2
  252. package/modules/grid/tiles.js +1 -1
  253. package/modules/hlod/index.js +4 -1
  254. package/modules/hud/index.js +47 -10
  255. package/modules/hud/parts.js +28 -9
  256. package/modules/level/geometry.js +8 -3
  257. package/modules/level/index.js +10 -5
  258. package/modules/level/load.js +4 -2
  259. package/modules/lights/sources.js +1 -1
  260. package/modules/music/Music.js +22 -4
  261. package/modules/nav/index.js +20 -10
  262. package/modules/particles/Particles.js +31 -14
  263. package/modules/particles/effect.js +20 -5
  264. package/modules/particles/lit.js +72 -0
  265. package/modules/photo/Photo.js +72 -28
  266. package/modules/photo/pathTrace.js +106 -0
  267. package/modules/rigid/RigidBodies.js +23 -14
  268. package/modules/rigid/Vehicles.js +3 -13
  269. package/modules/rigid/sync.js +2 -1
  270. package/modules/settings/Settings.js +52 -20
  271. package/modules/settings/apply.js +23 -9
  272. package/modules/settings/sections.js +39 -6
  273. package/modules/settings/strings.js +2 -0
  274. package/modules/settings/view.js +19 -3
  275. package/modules/sky/dome.js +15 -3
  276. package/modules/sky/environment.js +28 -12
  277. package/modules/sky/fog.js +1 -1
  278. package/modules/sky/frame.js +6 -1
  279. package/modules/sky/shader.js +4 -3
  280. package/modules/sky/skyModule.js +8 -4
  281. package/modules/swarm/Swarm.js +1 -1
  282. package/modules/terrain/ChunkManager.js +61 -15
  283. package/modules/terrain/chunkJob.js +2 -2
  284. package/modules/terrain/index.js +20 -5
  285. package/modules/terrain/terrainEdit.js +8 -4
  286. package/modules/terrain/terrainTexture.js +4 -2
  287. package/modules/timeline/Timeline.js +4 -3
  288. package/modules/timeline/Tween.js +3 -0
  289. package/modules/timeline/letterbox.js +1 -0
  290. package/modules/triggers/index.js +36 -17
  291. package/modules/vegetation/Vegetation.js +81 -19
  292. package/modules/vegetation/densityMap.js +13 -8
  293. package/modules/vegetation/draw.js +147 -24
  294. package/modules/vegetation/groundChunks.js +20 -5
  295. package/modules/vegetation/index.js +3 -3
  296. package/modules/vegetation/modelGeometry.js +9 -4
  297. package/modules/water/Water.js +11 -8
  298. package/modules/weather/Weather.js +7 -2
  299. package/modules/weather/shaders.js +25 -5
  300. package/modules/weather/weatherDraw.js +20 -6
  301. package/modules/world/World.js +2 -1
  302. package/modules/world/index.js +2 -2
  303. package/modules/world/persist.js +6 -2
  304. package/modules/world/views.js +15 -2
  305. package/package.json +4 -1
  306. package/presets.js +5 -5
  307. package/render/PostFX.js +84 -41
  308. package/render/backend.js +137 -16
  309. package/render/cascades.js +3 -1
  310. package/render/cascades.tsl.js +2 -0
  311. package/render/daylight.js +7 -1
  312. package/render/detail.js +7 -4
  313. package/render/effects.js +27 -8
  314. package/render/fogLook.js +24 -0
  315. package/render/fuse.js +5 -2
  316. package/render/fx/detail.tsl.js +9 -7
  317. package/render/fx/index.js +7 -2
  318. package/render/fx/library.tsl.js +1 -0
  319. package/render/fx/lightShaft.tsl.js +114 -0
  320. package/render/fx/noise.tsl.js +25 -8
  321. package/render/fx/objectOrigin.tsl.js +39 -10
  322. package/render/fx/particles.tsl.js +23 -6
  323. package/render/fx/patchNodes.tsl.js +17 -12
  324. package/render/fx/pcss.tsl.js +51 -0
  325. package/render/fx/postWebGPU.tsl.js +89 -29
  326. package/render/fx/sky.tsl.js +3 -9
  327. package/render/fxNumbers.js +10 -4
  328. package/render/impostor.tsl.js +107 -0
  329. package/render/lighting.js +33 -1
  330. package/render/lightmap.js +42 -28
  331. package/render/lights.js +19 -3
  332. package/render/materials.js +6 -4
  333. package/render/mergeCommon.js +4 -1
  334. package/render/occlusion.js +14 -4
  335. package/render/patches.js +79 -41
  336. package/render/postRuns.js +32 -0
  337. package/render/postWebGL.js +97 -10
  338. package/render/probes.js +10 -14
  339. package/render/shaderErrors.js +2 -1
  340. package/render/shadowCache.tsl.js +33 -5
  341. package/render/shadows.js +42 -16
  342. package/render/slots.js +8 -5
  343. package/render/vertexInputs.js +52 -0
  344. package/types/core.d.ts +114 -46
  345. package/types/gameplay.d.ts +56 -23
  346. package/types/generated/core/audio/Audio.d.ts +27 -1
  347. package/types/generated/core/base/Random.d.ts +1 -1
  348. package/types/generated/core/input/Input.d.ts +6 -8
  349. package/types/generated/core/input/inputSeat.d.ts +1 -1
  350. package/types/generated/core/inspect/Budget.d.ts +26 -0
  351. package/types/generated/core/inspect/DebugOverrides.d.ts +0 -2
  352. package/types/generated/core/saves/Saves.d.ts +10 -7
  353. package/types/generated/core/saves/session.d.ts +8 -2
  354. package/types/generated/core/scene/Rays.d.ts +1 -3
  355. package/types/generated/modules/particles/Particles.d.ts +1 -1
  356. package/types/generated/modules/world/World.d.ts +2 -1
  357. package/types/generated/render/PostFX.d.ts +35 -9
  358. package/types/physics.d.ts +43 -11
  359. package/types/pixel.d.ts +1 -1
  360. package/types/tsl.d.ts +62 -1
  361. package/types/world.d.ts +12 -3
  362. package/ui/Focus.js +7 -5
  363. package/ui/Parts.js +1 -1
  364. package/ui/touchPart.js +6 -3
@@ -1,5 +1,10 @@
1
1
  # Shop and gold: buy, sell / consign, gold HUD, saving
2
2
 
3
+ > **Covers:** gold as an item, buying and selling as two ops, a gold counter, saving.
4
+ > **Use when:** a shop, a trader, a currency.
5
+ > **Shortest:** `gold: { name: 'Gold', stack: 99999 }` in the items content.
6
+ > **Sections:** 1 Where to keep · 2 Data · 3 Buy, sell / · 4 Gold HUD · 5 Saving
7
+
3
8
  Requires modules `inventory()` + `dialogue()` + `content()` (the gold HUD needs `hud()`). The engine has no "shop"
4
9
  module: gold is an ordinary item, a shelf is an ordinary container, and buying and selling are two small ops that dialogue choices (or your own shop
5
10
  window) run.
@@ -16,8 +21,8 @@ The rest is written for A.
16
21
  `content/items.js`:
17
22
  ```js
18
23
  export default {
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
24
+ gold: { name: 'Gold', icon: '🪙', stack: 99999 }, // currency: one slot however much
25
+ medkit: { name: 'Medkit', price: 5 }, // price: read by the shop ops below
21
26
  };
22
27
  export const startItems = { gold: 12 };
23
28
  ```
@@ -36,7 +41,7 @@ first, and when the other side cannot take its part it returns `{ ok: false, cod
36
41
  ```js
37
42
  // main.js (after engine.use(...inventory()...))
38
43
  const price = (e, item) => e.inventory.item(item).price ?? 1;
39
- const payout = (e, item) => Math.max(1, Math.floor(price(e, item) * 0.6)); // add and remove take 1 or more, never 0
44
+ const payout = (e, item) => Math.max(1, Math.floor(price(e, item) * 0.6)); // add and remove take 1 or more, never 0
40
45
  engine.ops.define('shop.buy', {
41
46
  atomic: true,
42
47
  args: { shop: 'string', item: 'string' },
@@ -46,7 +51,7 @@ engine.ops.define('shop.buy', {
46
51
  return true;
47
52
  },
48
53
  run(e, { shop, item }, ctx) {
49
- e.inventory.container(ctx.actor).remove('gold', price(e, item)); // first: the last coins free their slot for the goods
54
+ e.inventory.container(ctx.actor).remove('gold', price(e, item)); // first: the last coins free their slot for the goods
50
55
  return e.inventory.transfer(shop, ctx.actor, item, 1) || { ok: false, code: 'bagFull' };
51
56
  },
52
57
  reasons: { soldOut: 'Shelf is empty', noMoney: 'Not enough gold', bagFull: 'No room in the bag' },
@@ -60,7 +65,7 @@ engine.ops.define('shop.sell', {
60
65
  },
61
66
  run(e, { shop, item }, ctx) {
62
67
  const bag = e.inventory.container(ctx.actor), pay = payout(e, item);
63
- e.inventory.transfer(ctx.actor, shop, item, 1); // first: the last piece frees its slot for the gold
68
+ e.inventory.transfer(ctx.actor, shop, item, 1); // first: the last piece frees its slot for the gold
64
69
  if (bag.room('gold') < pay) return { ok: false, code: 'bagFull' };
65
70
  bag.add('gold', pay, { silent: true });
66
71
  return 1;
@@ -101,9 +106,9 @@ export default {
101
106
  buys from the terminal.
102
107
 
103
108
  ## 4. Gold HUD
104
- 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:
109
+ Calling `hud.addCounter` again with the same id = update, and it leaves the DOM alone when the value is unchanged, so calling it every frame is cheap:
105
110
  ```js
106
- engine.onFrame(() => engine.hud.counter('gold', { icon: '🪙', label: 'Gold', value: engine.inventory.count('gold') }));
111
+ engine.onFrame(() => engine.hud.addCounter('gold', { icon: '🪙', label: 'Gold', value: engine.inventory.count('gold') }));
107
112
  ```
108
113
  Loading a save replaces the whole inventory, and refreshing every frame follows naturally; no event listener is needed.
109
114
 
@@ -1,8 +1,9 @@
1
1
  # Ops: one entry point for what players and NPCs do (engine.ops)
2
2
 
3
- **In this recipe**: 1. Define and run · 2. Who calls it, and when · 3. Built-in ops · 4. Read the log · 5. The guard · 6. Testing ·
4
- 7. Scenario tests · 8. Inspect and explain · 9. Randomness · 11. Structured failures, nextFixed, and who halted the loop ·
5
- 12. Failing in run, atomic ops, revision
3
+ > **Covers:** ops: one entry for what players and NPCs do, the log, the guard, tests, explain.
4
+ > **Use when:** any discrete act (buy, talk, attack, build) that keys, UI and tests share.
5
+ > **Shortest:** `engine.ops.define('shop.buy', { can, run })`.
6
+ > **Sections:** 1 Define and run · 2 Who calls it · 3 Built-in ops installed · 4 Read the log · 5 The guard dev) · 6 Testing · 7 Scenario tests a · 8 Inspect and explain · 9 Randomness · 11 Structured failures, nextFixed · 12 Failing in run
6
7
 
7
8
  **What is an op**: one discrete thing an actor decides to do: buy, talk, attack, roll, fire, reload, craft, build, demolish. Write one with
8
9
  `engine.ops.define`; every caller (key press, UI button, dialogue choice, dev bridge, test, later replay and network peers) runs it with `engine.ops.run`.
@@ -14,26 +15,26 @@ in a module's `fixed` or `world.simulate`. Low-level functions such as `inventor
14
15
  const PRICE = { bread: 5 };
15
16
  engine.ops.define('shop.buy', {
16
17
  desc: 'Buy from a shop shelf',
17
- atomic: true, // a failed run puts everything back (section 12)
18
- args: { shop: 'string', item: 'string', n: 'int?' }, // types: string number int bool position id any; ? = optional
19
- can(e, { shop, item, n = 1 }, ctx) { // read-only: return true or a reason string
18
+ atomic: true, // a failed run puts everything back (section 12)
19
+ args: { shop: 'string', item: 'string', n: 'int?' }, // types: string number int bool position id any; ? = optional
20
+ can(e, { shop, item, n = 1 }, ctx) { // read-only: return true or a reason string
20
21
  if (!e.inventory.container(shop).has(item, n)) return 'soldOut';
21
22
  if (e.inventory.container(ctx.actor).count('gold') < PRICE[item] * n) return 'noMoney';
22
23
  return true;
23
24
  },
24
- run(e, { shop, item, n = 1 }, ctx) { // runs only after can passed
25
+ run(e, { shop, item, n = 1 }, ctx) { // runs only after can passed
25
26
  e.inventory.container(ctx.actor).remove('gold', PRICE[item] * n);
26
27
  if (e.inventory.transfer(shop, ctx.actor, item, n) < n) return { ok: false, code: 'bagFull' };
27
- return n; // plain data; becomes r.value
28
+ return n; // plain data; becomes r.value
28
29
  },
29
- offers: (e, ctx) => [{ shop: 'shop-bakery', item: 'bread' }], // optional: arg sets possible now (ops list / dev bridge `ops`)
30
- reasons: { soldOut: 'Shelf is empty', noMoney: 'Not enough gold', bagFull: 'No room in the bag' }, // optional developer notes
30
+ offers: (e, ctx) => [{ shop: 'shop-bakery', item: 'bread' }], // optional: arg sets possible now (ops list / dev bridge `ops`)
31
+ reasons: { soldOut: 'Shelf is empty', noMoney: 'Not enough gold', bagFull: 'No room in the bag' }, // optional developer notes
31
32
  // 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)
32
33
  });
33
34
 
34
35
  const r = engine.ops.run('shop.buy', { shop: 'shop-bakery', item: 'bread' });
35
36
  // r = { ok: true, value: 1 } or { ok: false, code: 'noMoney', facts, nextActions }
36
- const { ok } = engine.ops.can('shop.buy', { shop: 'shop-bakery', item: 'bread' }); // ask only: grey out a button
37
+ const { ok } = engine.ops.can('shop.buy', { shop: 'shop-bakery', item: 'bread' }); // ask only: grey out a button
37
38
  ```
38
39
  Rules that keep ops replayable and network-ready:
39
40
  - **Use `ctx.actor`, never `engine.player`.** `ctx.actor` is the world record id of whoever acts (default `engine.actor`, which is `'player'` — also
@@ -77,12 +78,13 @@ returns `'halted'`. While a save replaces the state (reading it, its parts, `aft
77
78
  | `grid.place` · `grid.remove` · `grid.move` | `{ grid, item, cell, rotation?, level?, fields?, id? }` · `{ id }` · `{ id, cell, rotation?, grid?, level? }` (recipe 29) | `noGrid` `unknown` `notPlaced` and more; `ops.list()` has them all |
78
79
  | `time.skip` | `{ seconds }` (core; timers, calendar events and far simulation catch up in order) | `notForward` |
79
80
  | `photo.take` | none (`r.value` is the shot; can = `photo.canTake()`, the key emits `photo:denied { reason }`) | `denied` or yours |
81
+ | `photo.trace` | `{ samples?, seconds? }` (`r.value`: Promise of the shot) | `noTracer` `webgl2` `tracing` `denied` |
80
82
 
81
83
  ## 4. Read the log
82
84
  ```js
83
- engine.ops.recent('shop.buy'); // [{ seq, tick, phase, name, args, source, actor, ok, code, depth, count }] old -> new
84
- engine.ops.list(); // defined ops [{ name, desc, args }]
85
- engine.ops.list({ available: true }); // each offer checked with can [{ name, args, ok, code }]
85
+ engine.ops.recent('shop.buy'); // [{ seq, tick, phase, name, args, source, actor, ok, code, depth, count }] old -> new
86
+ engine.ops.list(); // defined ops [{ name, desc, args }]
87
+ engine.ops.list({ available: true }); // each offer checked with can [{ name, args, ok, code }]
86
88
  ```
87
89
  Consecutive identical failures (same actor, op and code, e.g. `cooldown` while the trigger is held) merge into one entry with `count`.
88
90
  The ring keeps `engine.ops.historySize` entries (256). A save load writes a `(load)` entry: what follows happened in the loaded world.
@@ -129,16 +131,16 @@ Put `<workspace>/tests/scenarios/<name>.json` in the engine package or a game; `
129
131
  `tests/snapshots/<name>.describe.json` (`only` / `ignore` / `tolerance`; write it with `threedog test <name> --update-snapshots`).
130
132
  - A file has 120 s under `threedog test`; a long one sets `"timeout"` at the top, in milliseconds, as a spec does.
131
133
  - 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.
132
- - `{ "until": { path: value }, "within": seconds }` reaches a state by a deadline, however the game freezes on the way; check the end with `expect`. A missed deadline, an error or a stuck load each name themselves. `step` stays strict: a `step` that moved less than asked fails, a freeze the game raised itself included: when a win window opens 0.4 s into `{ "step": 0.6 }`, the failure says how far it got and which window froze the game, and the scenario asks for that much.
134
+ - `{ "until": { path: value }, "within": seconds }` reaches a state by a deadline, however the game freezes on the way; check the end with `expect`. A missed deadline, an error or a stuck load each name themselves. `step` stays strict: one that moved less than asked fails, a freeze the game raised itself included (a win window opening 0.4 s into `{ "step": 0.6 }`: the failure says how far it got and which window froze the game).
133
135
  - Use `press` only for the one test per key that proves "key -> op".
134
136
 
135
137
  ## 8. Inspect and explain
136
138
  ```js fragment
137
- engine.inspect(); // { actor: 'player', at, near: [...nearby], ops: [{ op, args, ok, code?, why? }] }: what is around and possible now
138
- engine.inspect('npc_3'); // the same as another actor; engine.inspect([x, z]) around a spot
139
+ engine.inspect(); // { actor: 'player', at, near: [...nearby], ops: [{ op, args, ok, code?, why? }] }: what is around and possible now
140
+ engine.inspect('npc_3'); // the same as another actor; engine.inspect([x, z]) around a spot
139
141
  engine.explain({ op: 'shop.buy', args: { shop: 'bakery', item: 'bread' } }).text;
140
142
  // text: 'shop.buy {...} cannot run now: noMoney (Not enough gold)'; detail: 'last attempt at tick 812 (player, player): noMoney' (+ recent, events)
141
- engine.explain({ quest: 'first-light' }).text; // 'quest ... waits on step 2/3 "...": its done() returns false'
143
+ engine.explain({ quest: 'first-light' }).text; // 'quest ... waits on step 2/3 "...": its done() returns false'
142
144
  ```
143
145
  Other keys come from modules: add `explain: { myKey(e, value, query) { return { ok, text }; } }` to the module definition. Dev bridge: `threedog
144
146
  inspect [id | x,z]`, `threedog explain op shop.buy shop=bakery item=bread`, `threedog explain quest first-light`.
@@ -159,7 +161,7 @@ engine.ops.define('shop.rent', {
159
161
  can: (e, a, ctx) => gold(ctx) >= 5 || { code: 'noMoney', facts: { need: 5, have: gold(ctx) }, nextActions: [{ op: 'job.work', args: {} }] },
160
162
  run: (e, a, ctx) => { /* ... */ },
161
163
  });
162
- const r = engine.ops.run('shop.rent', {}); // r.ok === false, r.code === 'noMoney', r.facts.need === 5, r.nextActions[0].op === 'job.work'
164
+ const r = engine.ops.run('shop.rent', {}); // r.ok === false, r.code === 'noMoney', r.facts.need === 5, r.nextActions[0].op === 'job.work'
163
165
  ```
164
166
  `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.
165
167
 
@@ -169,17 +171,17 @@ Tests that halt the loop name themselves (default `'game'`) and end their own ha
169
171
  `run` can fail like `can`: return or throw `{ ok: false, code, facts, nextActions }` (`ok: false` is required). `facts` is an object (`{ need: 5 }`) or a list of `{ id, field, actual, expected? }` naming the record and field that were wrong. Every result carries `revision` (`engine.ops.revision`), a counter bumped once per committed op.
170
172
  ```js
171
173
  engine.ops.define('craft.bread', {
172
- atomic: true, // every save part declared atomic is undone if run fails or throws
174
+ atomic: true, // every save part declared atomic is undone if run fails or throws
173
175
  run(e, { oven }, ctx) {
174
176
  e.inventory.container(ctx.actor).remove('flour', 2);
175
177
  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 } }] };
176
178
  e.inventory.add('bread');
177
179
  },
178
- after: (e) => e.audio.sfx('ding'), // sound / animation: runs only after the op committed
180
+ after: (e) => e.audio.sfx('ding'), // sound / animation: runs only after the op committed
179
181
  });
180
182
  ```
181
- What atomic covers: it copies the save parts that declared `saves.register(key, { atomic: true })` (a game's own part can opt in) before `run` and loads them back on failure, so it costs one save of those per run (wrong for a per-frame op in a huge world). Events already emitted, sound, animation and any other module's state are not undone; keep such effects in `after`. Ops called from an atomic run join it (their `after` hooks run, nested first, at the outermost commit; a rolled-back outer takes back their revision). `ops.list()` and `engine.explain({ op })` report `atomic`.
183
+ What atomic covers: it copies the save parts declared `saves.define(key, { atomic: true })` before `run` and loads them back on failure, so it costs one save of those per run (wrong for a per-frame op in a huge world). Emitted events, sound, animation and other modules' state are not undone; keep such effects in `after`. Ops called from an atomic run join it (their `after` hooks run, nested first, at the outermost commit; a rolled-back outer takes back their revision). `ops.list()` and `engine.explain({ op })` report `atomic`.
182
184
 
183
185
  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.
184
186
 
185
- Atomic details: a rolled-back run still bumps `ops.revision` (it only goes up, never back to an old number) and its committed nested ops show in `ops.recent()` as `ok: false` with code `rolledBack`. The rollback does not run `afterLoad` and mutes the events its loads would emit, so atomic state must be plain data.
187
+ Atomic details: a rolled-back run still bumps `ops.revision` (it never goes back) and its committed nested ops show in `ops.recent()` as `ok: false`, code `rolledBack`. The rollback skips `afterLoad` and mutes the events its loads would emit, so atomic state must be plain data. It is synchronous like `run`: `saves.define` refuses an atomic part with an async `load`, and a `load()` that returns a Promise anyway is reported at rollback (`engine-misuse`) and not waited for.
@@ -1,43 +1,47 @@
1
1
  # UI parts: replace or turn off any piece of the engine's screen UI
2
2
 
3
- **In this recipe**: Reskin · 1. Pick at start · 2. Your own part · 3. Toasts · 4. Dialogue box · The choice cursor · 5. Title screen · 6. Settings menu · 7. Keys, UI that follows the world
3
+ > **Covers:** every piece of the engine's screen UI as a replaceable part, themes, toasts, the dialogue box.
4
+ > **Use when:** restyling or replacing the HUD, menus or dialogue.
5
+ > **Shortest:** a `theme` object of colors and fonts (§"Reskin").
6
+ > **Sections:** Reskin your picture on · 1 Pick at start · 2 Your own part · 3 Toasts filter instead · 4 Dialogue box your · The choice cursor windows · 5 Title screen and · 6 Settings menu only · 7 Keys, and UI
4
7
 
5
8
  Every piece of UI the engine draws is a named **part** with a plain default:
6
9
  `loading`, `toast`, `title` (off by default), `touch` (on-screen stick and buttons),
7
- `hud.marker`, `hud.counter`, `hud.bar`, `dialogue`, `prompt` ("E · Talk"), `questLog`, `inventory` (with the inventory module).
10
+ `hud.marker`, `hud.counter`, `hud.bar`, `hud.button`, `dialogue`, `prompt` ("E · Talk"), `questLog`, `inventory` (with the inventory module).
8
11
  The engine keeps the behavior (when to show, the UI focus stack and Esc, input lock, i18n); a part only draws the data it gets.
9
12
  Each name takes one value: `false` off · `true` default · `{ ...options }` default with options ·
10
13
  `(engine, options) => ({ show, update, hide, dispose })` your own (any verb may be omitted).
14
+ An end screen is a flow state (`engine.flow.define('gameOver', { freeze: true, lockInput: true })`, recipe 07 §1) showing a window with `closable: false` ("A window: results, game over", below).
11
15
  Only want different colors / layout? Use "Reskin" below, not a new part.
12
16
 
13
17
  ## Reskin: your picture on every default part, in one place
14
- The default parts are neutral gray on purpose. About ten lines give all of them the game's picture; do this before writing a dialogue box or HUD of your own:
18
+ The default parts are neutral gray on purpose. About ten lines give all of them the game's picture; do this before writing your own dialogue box or HUD:
15
19
  ```js
16
- const theme = { // picture/ui.js
17
- bg: 'rgba(38,28,20,.94)', // panels: dialogue, prompt, toast, windows; the HUD uses it slightly see-through
18
- fg: '#f4e8d0', muted: '#b8a88c', // text, secondary text
19
- accent: '#e8a13a', good: '#9ccf6a', // names, cursor, toast border, HUD bars; "done"
20
- line: 'rgba(244,232,208,.25)', // borders, dividers
21
- font: '"Georgia", serif', // a font file: ui.fonts: ['name'] (recipe 05, fonts)
22
- radius: '4px', radiusSmall: '2px', // windows and dialogue; buttons, prompts, toasts, HUD counters
23
- loadingBg: '#1c140e', // loading and title screens, cutscene bars
20
+ const theme = { // picture/ui.js
21
+ bg: 'rgba(38,28,20,.94)', // panels: dialogue, prompt, toast, windows; the HUD uses it slightly see-through
22
+ fg: '#f4e8d0', muted: '#b8a88c', // text, secondary text
23
+ accent: '#e8a13a', good: '#9ccf6a', // names, cursor, toast border, HUD bars; "done"
24
+ line: 'rgba(244,232,208,.25)', // borders, dividers
25
+ font: '"Georgia", serif', // a font file: ui.fonts: ['name'] (recipe 05, fonts)
26
+ radius: '4px', radiusSmall: '2px', // windows and dialogue; buttons, prompts, toasts, HUD counters
27
+ loadingBg: '#1c140e', // loading and title screens, cutscene bars
24
28
  };
25
- const engine = createEngine({ canvas, ui: { theme } }); // the same ui option as the parts below
29
+ const engine = createEngine({ canvas, ui: { theme } }); // the same ui option as the parts below
26
30
  ```
27
31
  Each key becomes the CSS variable `--threedog-<key>` (`radiusSmall` -> `--threedog-radius-small`) on `engine.uiRoot`, and no default rule has a color or corner of
28
32
  its own. Also there: `shadow` (windows), `shadowSmall` (bubbles, marker labels), `fadeBg` (scene fades), and `hudBg` / `hudFg` / `hudAccent`,
29
33
  which follow the main ones unless set. Your own part can read the same variables. Further steps, beside `theme` in the same `ui`: `css` is placed after every default, so it
30
34
  overrides the `.threedog-*` classes (sizes, layout); `templates.<window>` replaces a window's HTML (`engine.ui.templates` is the same object, written directly); `fonts` lists
31
- font assets. Every other key of `ui` is a part name (§1). How high the prompt floats is `interactions({ promptHeight })`. Different behavior, not colors: a part of your own (§2).
35
+ font assets. How high the prompt floats is `interactions({ promptHeight })`.
32
36
 
33
37
  ## 1. Pick at start (copy it)
34
38
  ```js
35
39
  const engine = createEngine({
36
40
  canvas,
37
41
  ui: {
38
- loading: { title: 'My Game' }, // default loading screen with a title
39
- title: { title: 'My Game' }, // turn on the title screen: Continue (when a save exists) / Start / Settings
40
- toast: false, // no pop-up messages at all
42
+ loading: { title: 'My Game' }, // default loading screen with a title
43
+ title: { title: 'My Game' }, // turn on the title screen: Continue (when a save exists) / Start / Settings
44
+ toast: false, // no pop-up messages at all
41
45
  },
42
46
  });
43
47
  ```
@@ -46,14 +50,14 @@ A misspelled name throws at `start()` and lists the names that exist.
46
50
 
47
51
  ## 2. Your own part (DOM, canvas, a UI library: anything)
48
52
  ```js
49
- engine.ui.set('hud.bar', (engine) => { // called once per bar
50
- const el = document.createElement('progress'); el.max = 1; engine.uiRoot.appendChild(el); // build under engine.uiRoot: dispose cleans it up
53
+ engine.ui.set('hud.bar', (engine) => { // called once per bar
54
+ const el = document.createElement('progress'); el.max = 1; engine.uiRoot.appendChild(el); // build under engine.uiRoot: dispose cleans it up
51
55
  return {
52
56
  update: d => { el.value = d.value / (d.max ?? 1); el.title = d.label ?? d.id; },
53
57
  dispose: () => el.remove(),
54
58
  };
55
59
  });
56
- engine.hud.bar('hp', { value: 80, max: 100, label: 'HP' }); // game code does not change
60
+ engine.hud.bar('hp', { value: 80, max: 100, label: 'HP' }); // game code does not change
57
61
  ```
58
62
  What each part receives:
59
63
  | Part | Created | Calls |
@@ -64,6 +68,8 @@ What each part receives:
64
68
  | `hud.marker` | per marker | `update({ x, y, onScreen, arrow, angle, label, icon, distance })` every frame · `hide()` · `dispose()` |
65
69
  | `hud.counter` | per counter | `update({ id, label, icon, value, max })` · `dispose()` |
66
70
  | `hud.bar` | per bar | `update({ id, label, value, max })` · `dispose()` |
71
+ | `hud.button` | per button | `update({ id, label, icon, run, key? })` · `dispose()` (call `run()` on click; `label` goes through `engine.t`) |
72
+ | `hud.hint` | per key hint | `update({ id, label, key })` · `dispose()` (shows `key · label` like `prompt`, e.g. `Space · Jump`; `key` = `input.label(action)` or `input.noKey`, kept current) |
67
73
  | `inventory` | once (on first open; opened by the bound `inventory` key or `engine.ui.open('inventory')`) | `show(d)` · `update(d)` while open · `hide()`; `d = { title, hint, items: [{ key, id, count, data, def }], capacity, used, weight, maxWeight }`; buttons run `inventory.use / drop / transfer` ops (recipe 03) |
68
74
  | `touch` | once, if wanted (1) | `show(view)` · `update(view)` (buttons or language changed) |
69
75
  | `prompt` | once | `update({ id, action, key, label, text, x, y, onScreen, use(), options })` every frame in reach · `hide()` |
@@ -81,9 +87,9 @@ With every part off (`false`) the engine draws no DOM at all and the logic keeps
81
87
 
82
88
  ## 3. Toasts: filter instead of all-or-nothing
83
89
  ```js
84
- toast(engine, 'Saved', { kind: 'save' }); // your own message (the engine comes first)
90
+ toast(engine, 'Saved', { kind: 'save' }); // your own message (the engine comes first)
85
91
  engine.ui.set('toast', (engine) => ({ show: ({ text, kind }) => { if (kind !== 'quest') myBanner(text); } }));
86
- engine.use(quests({ notify: false })); // or only silence quest messages; notify: ({ type, id, text }) => ... shows them your way
92
+ engine.use(quests({ notify: false })); // or only silence quest messages; notify: ({ type, id, text }) => ... shows them your way
87
93
  ```
88
94
 
89
95
  ## 4. Dialogue box: your own picture, your own fields
@@ -92,7 +98,7 @@ The part draws `view` and answers with `view.advance()` / `view.choose(i)`, whic
92
98
  `view = { script, node, speaker, text (typed so far), full, typing, choices: [{ text, key, data }], hint, data, lock, advance(), choose(i) }`
93
99
  ```js
94
100
  engine.dialogue.define('fisher', {
95
- start: { text: 'Quiet day.', data: { portrait: 'fisher.png', mood: 'tired' }, next: 'ask' }, // your own fields go in data
101
+ start: { text: 'Quiet day.', data: { portrait: 'fisher.png', mood: 'tired' }, next: 'ask' }, // your own fields go in data
96
102
  ask: { text: 'Here for photos?', choices: [{ text: 'Yes', next: 'end', data: { icon: '📷' } }] },
97
103
  });
98
104
  engine.ui.set('dialogue', (engine) => {
@@ -147,68 +153,82 @@ game past it and only your buttons end it. Nothing else closes a window: a game
147
153
  import { makeWindow } from 'threedog';
148
154
  const results = makeWindow(engine, {
149
155
  id: 'results', title: () => 'Run complete',
150
- data: () => ({ score: run.score, best: run.best }), // read on every refresh(), so it shows the current values
156
+ data: () => ({ score: run.score, best: run.best }), // read on every refresh(), so it shows the current values
151
157
  render: (d, { esc }) => `<p>${esc(d.score)} / ${esc(d.best)}</p><button class="threedog-btn" data-act="again">Again</button>`,
152
- closable: false, // a run summary ends the run; for a window Esc may leave, drop this (onCancel changes what Esc does)
158
+ closable: false, // a run summary ends the run; for a window Esc may leave, drop this (onCancel changes what Esc does)
153
159
  });
154
- results.el.addEventListener('click', ev => { // one listener: refresh() rewrites the content, not this
155
- if (ev.target.closest('[data-act="again"]')) { results.toggle(false); startRun(); } // a click, Enter or pad A on the cursor
160
+ results.el.addEventListener('click', ev => { // one listener: refresh() rewrites the content, not this
161
+ if (ev.target.closest('[data-act="again"]')) { results.toggle(false); startRun(); } // a click, Enter or pad A on the cursor
156
162
  });
157
- let held = null; // stop gameplay behind it (the picture keeps drawing)
163
+ let held = null; // stop gameplay behind it (the picture keeps drawing)
158
164
  engine.events.on('ui:open', id => { if (id === 'results') held = engine.freeze('results'); });
159
165
  engine.events.on('ui:close', id => { if (id === 'results') { held?.remove(); held = null; } });
160
- engine.events.on('session:start', () => results.toggle(false)); // a new run or a load, however it was started
161
- results.toggle(true); // when the run ends; results.refresh() after the data changes
166
+ engine.events.on('session:start', () => results.toggle(false)); // a new run or a load, however it was started
167
+ results.toggle(true); // when the run ends; results.refresh() after the data changes
162
168
  ```
163
169
 
164
170
  ## 5. Title screen and "back to title"
165
171
  ```js
166
172
  createEngine({ canvas, ui: { title: { title: 'My Game', items: ['continue', 'start', { label: 'Credits', run: e => showCredits() }] } } });
167
- engine.events.on('ui:close', id => { if (id === 'title') startIntro(); }); // the player left the title screen
168
- engine.ui.open('title'); // show it again (the settings 'game' tab has a "Back to title" button)
173
+ engine.events.on('ui:close', id => { if (id === 'title') startIntro(); }); // the player left the title screen
174
+ engine.ui.open('title'); // show it again (the settings 'game' tab has a "Back to title" button)
169
175
  ```
170
176
  While the title is open gameplay is frozen, input is locked, and Esc goes to it (the settings menu does not open).
171
177
 
172
- **A custom item closes the title itself.** The built-in `continue` / `start` call `e.ui.close('title')` after they load; an item you write does not, so `flow` can reach `playing` with the title still on top and no warning. End every item that leaves the title with `e.ui.close('title')`:
178
+ **A custom item closes the title itself.** The built-in `continue` / `start` call `e.ui.close('title')` after loading; yours does not, so `flow` can reach `playing` with the title still on top, no warning. End every item that leaves the title with `e.ui.close('title')`:
173
179
  ```js fragment
174
180
  { label: 'Tutorial', run: async e => { await e.session.newGame(); e.ui.close('title'); } }
175
181
  ```
176
182
 
177
183
  ### Photo mode: the picture without the interface, and hiding the interface
178
- `engine.photo.take()` (op `photo.take`) draws one frame of the game canvas at a higher pixel ratio and reads it back, so the picture never contains DOM: HUD, toasts and windows are not in it (a HUD drawn into the canvas by your own render code is). To hide the interface on screen for a photo mode, hide the engine's UI root, one element that holds every part:
184
+ `engine.photo.take()` (op `photo.take`) reads back one canvas frame at a higher pixel ratio, so no DOM (HUD, toasts, windows) is in it. To hide the interface on screen, hide the engine's UI root:
179
185
  ```js
180
- const photoMode = on => { engine.uiRoot.style.display = on ? 'none' : ''; }; // engine ui: hud, toasts, windows, title
181
- engine.photo.take(); // shot.url is the picture, the album keeps it; the DOM was never in it
182
- photoMode(true); // the player's screen without interface, e.g. while a photo mode is framing
186
+ const photoMode = on => { engine.uiRoot.style.display = on ? 'none' : ''; }; // hud, toasts, windows, title
187
+ engine.photo.take(); // shot.url is the picture, the album keeps it
188
+ photoMode(true); // while the player frames a shot
189
+ ```
190
+ ```js fragment
191
+ engine.use(photo({ pathTracer: () => import('three-gpu-pathtracer/webgpu') })); // after npm i -D three-gpu-pathtracer three-mesh-bvh
192
+ const still = await engine.photo.trace({ samples: 128 }); // still.pathTraced.untraced: what differs
183
193
  ```
184
194
  HUD text follows the engine locale (`createEngine({ locale })`, default `'auto'` = the browser language): a game written in English sets `locale: 'en'`, or distance labels read `50 米` on a Chinese browser.
185
195
 
186
196
  ## 6. Settings menu: only the tabs the game needs
187
197
  ```js
188
- engine.use(settings({ sections: ['game', 'graphics', 'audio', 'controls', 'camera'] })); // default: graphics, audio, controls, language, saves
198
+ engine.use(settings({ sections: ['game', 'graphics', 'audio', 'controls', 'camera'] })); // default: graphics, audio, controls, language, saves
189
199
  // optional built-ins by name: 'game' (resume / load / back to title), 'camera' (sensitivity, invert Y, field of view; re-applied on 'camera:change')
190
200
  engine.settings.addSection('camera');
191
201
  // leave graphics rows out: the entry { id: 'graphics', omit } in the list; an omitted row stays the game's value, and no preset or stored value moves it
192
202
  settings({ sections: [{ id: 'graphics', omit: ['pixelRatio', 'antialias', 'adaptive'] }, 'audio', 'controls', 'language', 'saves'] });
193
203
 
194
- // a tab of your own: render gets tools with the control helpers (row / toggle / range / segmented) already bound
195
- engine.settings.define('subtitles', true, on => { document.body.dataset.subtitles = String(on); });
204
+ // a setting of your own is a menu row the engine draws, in the 'options' tab unless menu names another tab
205
+ // (true/false: a switch; a number: a slider from min to max; options: buttons). label: an i18n key or text, else the key
206
+ engine.settings.define('subtitles', true, { label: 'my.subtitles', apply: on => { document.body.dataset.subtitles = String(on); } });
207
+ engine.settings.define('lampShadows', true, { menu: 'graphics', apply: on => { lamp.castShadow = on; } });
208
+ engine.settings.define('difficulty', 'normal', { options: ['easy', 'normal', 'hard'], apply: d => game.setDifficulty(d) });
209
+ engine.settings.define('hudScale', 1, { min: 0.5, max: 2, step: 0.1, apply: v => hud.scale(v) });
210
+
211
+ // a tab of your own: render gets tools with the control helpers (row / toggle / range / segmented) already bound;
212
+ // the rows it draws itself say menu: false, or the engine draws them a second time (it warns once when it sees that)
213
+ engine.settings.define('vibration', true, { menu: false, apply: on => { game.vibration = on; } });
196
214
  engine.settings.addSection('gameplay', {
197
215
  title: 'Gameplay',
198
- render: (tools, e, s) => tools.row('Subtitles', tools.toggle('subtitles', s.get('subtitles'))),
216
+ render: (tools, e, s) => tools.row('Vibration', tools.toggle('vibration', s.get('vibration'))),
199
217
  order: 50,
200
218
  });
201
219
  ```
220
+ `settings.define` draws the row itself, in the 'options' tab (`menu: '<tab>'` picks another tab), labelled by `label` (text, or an i18n key such as `settings.subtitles` in `strings`). With `menu: false` it draws nothing: the row is what your own tab's `render` returns, labelled by the first argument of `tools.row` (text, or `e.t('settings.subtitles')`).
221
+
202
222
  A row that switches off an effect of your own (a post effect, a picture value): name the shared value it limits, and it works like the
203
223
  built-in shadows row. Off holds the value off on the settings layer, so a later scene, weather or cutscene cannot turn it back on; on
204
224
  allows whatever the scene chose. A number row from 0 to 1 is a factor on a number value. Define the row after the effect exists. `bloom` and `ao` already have rows of their own (limiting `post.bloom.enabled` / `post.ao.enabled`), so `settings.define('bloom', ...)` throws: switch them with `engine.settings.set('bloom', false)`, or in a preset.
205
225
  ```js fragment
206
- engine.post.add(volFog); // post.volFog.enabled now exists
207
- engine.settings.define('volFog', true, { limits: 'post.volFog.enabled' }); // add apply: v => ... too if the game reacts in code
208
- engine.settings.define('flashCap', 1, { limits: 'sky.flash' }); // 0.5 = half of any lightning flash
209
- settings({ presets: { low: { volFog: false } } }); // a preset can switch the row like any other key
210
- settings({ presets: { low: { viewChunks: 0.5, density: 0.25 } } }); // viewChunks and density in a preset: shares (0 to 1) of the game's own value; the top preset lets everything through
211
- settings({ presets: { low: { pixelRatio: 0.5 } } }); // pixelRatio in a preset: a share (0 to 1) of the ratio the engine picked for this device
226
+ engine.post.add(volFog); // post.volFog.enabled now exists
227
+ engine.settings.define('volFog', true, { limits: 'post.volFog.enabled' }); // add apply: v => ... too if the game reacts in code
228
+ engine.settings.define('flashCap', 1, { limits: 'sky.flash' }); // 0.5 = half of any lightning flash
229
+ settings({ presets: { low: { volFog: false } } }); // a preset can switch the row like any other key
230
+ settings({ presets: { low: { viewChunks: 0.5, density: 0.25 } } }); // viewChunks and density in a preset: shares (0 to 1) of the game's own value; the top preset lets everything through
231
+ settings({ presets: { low: { pixelRatio: 0.5 } } }); // pixelRatio in a preset: a share (0 to 1) of the ratio the engine picked for this device
212
232
  ```
213
233
  `engine.describe().shared['post.volFog.enabled']` shows the settings entry and what the scene wanted underneath.
214
234
 
@@ -217,6 +237,6 @@ A completely different menu: don't install `settings()`; open your own with `uiF
217
237
  Check what is in use: `engine.ui.describe()` → `{ loading: 'default', toast: 'off', 'hud.bar': 'custom', ... }`.
218
238
 
219
239
  ## 7. Keys, and UI that follows the world
220
- - Bind keys and read them by action name (recipe 58): gameplay keys (attack, jump) in the fixed step, UI keys in the frame hook. Never `addEventListener('keydown')`, and never read `pointer.clicked` for gameplay; bind a `Mouse0` action instead.
240
+ - Read keys by bound action name (recipe 58): gameplay keys in the fixed step, UI keys in the frame hook; no `keydown` listeners, no `pointer.clicked` for gameplay (bind `Mouse0`).
221
241
  - A label over a world position: `worldToScreen(engine, pos)` gives screen coordinates for an HTML element.
222
242
  - A counter bound to an item count: recipe 22 section 4.
@@ -1,5 +1,10 @@
1
1
  # Co-op multiplayer: net() (host authority + state sync)
2
2
 
3
+ > **Covers:** co-op over the network: host authority, actors, what is synced, security.
4
+ > **Use when:** two or more players in one game.
5
+ > **Shortest:** `engine.use(net({ role: 'host', transport: webSocket(room, { host: true }) }))`.
6
+ > **Sections:** 1 Install · 2 Mark the ops · 3 Who is who · 4 What is synced · 5 Write the UI · 6 Security notes
7
+
3
8
  **What it is**: co-op, host-authoritative, not for competitive play. An optional module for slow, cooperative games (a shared base, a co-op
4
9
  puzzle, a turn-based board, trading). One player's browser is the **host** and
5
10
  owns the game state; friends are **clients** that mirror it and ask for changes through ops. Not installed = no cost.
@@ -21,7 +26,7 @@ and a reconnect key.
21
26
  For tests and offline demos use the in-process network instead (latency, jitter and loss adjustable; `manual: true` delivers only on `advance(ms)`):
22
27
  ```js
23
28
  import { createEngine, fakeNetwork, net } from 'threedog';
24
- const [host, guest] = [1, 2].map(() => createEngine({ canvas: document.createElement('canvas') })); // two games on one page
29
+ const [host, guest] = [1, 2].map(() => createEngine({ canvas: document.createElement('canvas') })); // two games on one page
25
30
  const wire = fakeNetwork({ latency: 80, jitter: 30, loss: 0.05 });
26
31
  host.use(net({ role: 'host', transport: wire.host() }));
27
32
  guest.use(net({ role: 'client', transport: wire.connect() }));
@@ -36,17 +41,17 @@ Default deny: a client may only request ops defined with `net: 'peer'`. Everythi
36
41
  again on the host.
37
42
  ```js
38
43
  engine.ops.define('chest.take', {
39
- net: 'peer', // friends may ask for this
40
- args: { chest: 'id', item: 'string', n: 'int?' }, // the host always checks peers' args against this shape ('badArgs')
44
+ net: 'peer', // friends may ask for this
45
+ args: { chest: 'id', item: 'string', n: 'int?' }, // the host always checks peers' args against this shape ('badArgs')
41
46
  can: (e, { chest, item, n = 1 }) => e.inventory.container(chest).has(item, n) || 'empty',
42
47
  run: (e, { chest, item, n = 1 }, ctx) => e.inventory.transfer(chest, ctx.actor, item, n),
43
48
  });
44
49
  engine.ops.define('plot.water', {
45
50
  net: 'peer', args: { id: 'id' },
46
- owner: a => a.id, // the record a.id must have owner === the requesting actor, else 'notOwner'
51
+ owner: a => a.id, // the record a.id must have owner === the requesting actor, else 'notOwner'
47
52
  run: (e, { id }) => e.world.set(id, { water: (e.world.get(id)?.water ?? 0) + 1 }),
48
53
  });
49
- engine.ops.define('cheat.gold', { args: { n: 'int' }, run: (e, { n }, ctx) => e.inventory.container(ctx.actor).add('gold', n) }); // host only
54
+ engine.ops.define('cheat.gold', { args: { n: 'int' }, run: (e, { n }, ctx) => e.inventory.container(ctx.actor).add('gold', n) }); // host only
50
55
  ```
51
56
  | Mark | Who can run it | Use for |
52
57
  |---|---|---|
@@ -80,8 +85,8 @@ A character another machine drives is held by net for good: a local `walkTo`, cu
80
85
  On a client `engine.ops.run` returns `{ ok: true, pending: true, seq }` after the local `can` passed (so a "no money" refusal is still instant). The
81
86
  real result comes later:
82
87
  ```js
83
- engine.events.on('net:sync', () => redrawBag()); // state changed (snapshot or diff)
84
- engine.events.on('net:result', r => { if (!r.ok) hint(engine.t('op.' + r.name + '.' + r.code)); }); // after the state it caused
88
+ engine.events.on('net:sync', () => redrawBag()); // state changed (snapshot or diff)
89
+ engine.events.on('net:result', r => { if (!r.ok) hint(engine.t('op.' + r.name + '.' + r.code)); }); // after the state it caused
85
90
  ```
86
91
  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
87
92
  events: `net:join` / `net:leave` (host), `net:open` / `net:close` (client). `engine.net.reconnect(webSocket(url, { key }))` reconnects with the same
@@ -1,6 +1,9 @@
1
1
  # Terrain: your own generator, digging, raising and painting the ground, islands
2
2
 
3
- **In this recipe**: 0. Noise preset · 1. Your own generator · 2. Changing the ground · 3. Farming soil and ground types · 4. Height and snapping · 5. Where the ground ends: `shape` · 6. Replace the picture, keep play · 7. A chunk that fails · 8. Triangle cut and bounds margin · 9. Height from a grid or image
3
+ > **Covers:** terrain: generators, digging and raising, soil and ground types, height, roads, islands.
4
+ > **Use when:** a ground of your own, generated or shaped by play.
5
+ > **Shortest:** `openWorld({ terrain: terrainPreset() })`.
6
+ > **Sections:** 0 A ready-made generator · 1 Your own generator · 2 Changing the ground · 3 Farming soil and · 4 Height and snapping · 4b A road laid · 5 Where the ground · 6 Drawing the ground · 7 A chunk that · 8 Triangle cut and · 9 Height from a
4
7
 
5
8
  Requires module `terrain()` (in the `openWorld()` preset). The API list is in `../api/terrain.md`.
6
9
 
@@ -13,9 +16,9 @@ Flat island (no noise): `terrain({ height: () => 2, shape: { mask: (x, z) => 25
13
16
  ## 0. A ready-made generator: the noise preset
14
17
  ```js
15
18
  import { openWorld, createTerrain } from 'threedog';
16
- import { terrainPreset, riverAt } from '@threedog/terrain-noise'; // optional package: noise hills, rivers, biomes
17
- engine.use(openWorld({ camera: 'follow', seed: 7, terrain: terrainPreset({ shape: 'island' }) })); // 'hills' (default) | 'island' | 'canyon' | 'flat'
18
- const preview = createTerrain({ seed: 7, ...terrainPreset() }); // same heights before the engine starts
19
+ import { terrainPreset, riverAt } from '@threedog/terrain-noise'; // optional package: noise hills, rivers, biomes
20
+ engine.use(openWorld({ camera: 'follow', seed: 7, terrain: terrainPreset({ shape: 'island' }) })); // 'hills' (default) | 'island' | 'canyon' | 'flat'
21
+ const preview = createTerrain({ seed: 7, ...terrainPreset() }); // same heights before the engine starts
19
22
  const dry = (x, z) => riverAt(x, z, preview.noise) === 0;
20
23
  ```
21
24
  Its ground types are `beach snow rock riverbank wetland savanna forest highland meadow`; the game colors them (`terrain({ colors, biomeColors })`),
@@ -31,7 +34,7 @@ terrain({
31
34
  height: (x, z, n) => 4 + 30 * n.fbm(x * 0.004, z * 0.004) - 8 * Math.abs(Math.sin(x * 0.01)),
32
35
  // a ground type name (null = 'default'); its colors come from biomeColors[type]
33
36
  groundType: (x, z, h, slope) => slope > 0.8 ? 'rock' : h < 1 ? 'beach' : 'grass',
34
- waterLevel: 0, // a sea at y = 0; leave it out for no water (the default is -Infinity; terrainPreset() sets 0)
37
+ waterLevel: 0, // a sea at y = 0; leave it out for no water (the default is -Infinity; terrainPreset() sets 0)
35
38
  });
36
39
  ```
37
40
  The terrain moves the camera's far plane out to its view distance and leaves the fog to the game; `terrain({ viewFog: true })` (on in `openWorld()`) writes that
@@ -43,10 +46,10 @@ Both functions run in workers, so they are **pure**: they see only their paramet
43
46
 
44
47
  ## 2. Changing the ground: `engine.terrain.edit`
45
48
  ```js
46
- const at = [12, 0, 20]; // an op's 'position' argument is [x, y, z]
49
+ const at = [12, 0, 20]; // an op's 'position' argument is [x, y, z]
47
50
  engine.ops.define('ground.dig', { args: { at: 'position' }, run(e, a) { e.terrain?.edit(a.at, { radius: 3, lower: 1.5 }); } });
48
51
  engine.ops.define('ground.level', { args: { at: 'position' }, run(e, a) {
49
- e.terrain?.edit(a.at, { shape: 'square', radius: 6, flatten: e.surface(a.at) }); // a flat foundation at the height of its center
52
+ e.terrain?.edit(a.at, { shape: 'square', radius: 6, flatten: e.surface(a.at) }); // a flat foundation at the height of its center
50
53
  } });
51
54
  engine.ops.run('ground.dig', { at });
52
55
  ```
@@ -65,7 +68,7 @@ saved, works on levels and indoors, and draws its own tiles. See `recipes/29-gri
65
68
  types and gives them colors in its own style object: `terrain.colors` + `terrain.biomeColors`). `engine.groundType(pos)` reads the painted type
66
69
  (footsteps, `can` checks):
67
70
  ```js
68
- engine.ops.define('path.sand', { args: { at: 'position' }, // a sandy path; a new type name needs biomeColors (section 1)
71
+ engine.ops.define('path.sand', { args: { at: 'position' }, // a sandy path; a new type name needs biomeColors (section 1)
69
72
  run(e, a) { e.terrain?.edit(a.at, { shape: 'square', radius: (e.terrain.cellSize ?? 4) / 2, paint: 'beach' }); } });
70
73
  ```
71
74
 
@@ -78,7 +81,7 @@ raycast the terrain for this: the height function is exact and works before the
78
81
  The road and the height function must read the same data, or the road floats or sinks wherever they disagree. Write the road's shape once as plain numbers and hand them over with `terrain({ params })`. The height function runs in workers and sees only `n.params`, so it works out the centre line itself: a formula or a small table of numbers, never a curve object. Near the line it returns the road's level, and it blends to the hills further out.
79
82
 
80
83
  ```js
81
- const ROAD = { R: 130, wobble: 24, level: 14, flat: 10, blend: 40 }; // the one copy of the road's shape
84
+ const ROAD = { R: 130, wobble: 24, level: 14, flat: 10, blend: 40 }; // the one copy of the road's shape
82
85
 
83
86
  function height(x, z, n) {
84
87
  const p = n.params, t = Math.atan2(z, x);
@@ -110,19 +113,19 @@ where `mask > 0`; the rim is cut through the cells in straight lines, walls hang
110
113
  import { createEngine, openWorld } from 'threedog';
111
114
 
112
115
  const engine = createEngine({ canvas: document.querySelector('canvas') });
113
- engine.use(openWorld({ camera: 'follow', water: false, terrain: { // water: false -- a floating island has no sea under it
116
+ engine.use(openWorld({ camera: 'follow', water: false, terrain: { // water: false -- a floating island has no sea under it
114
117
  height: (x, z, n) => 4 + 6 * n.fbm(x * 0.02, z * 0.02),
115
118
  shape: {
116
- mask: (x, z) => 60 - Math.hypot(x, z), // > 0 ground: a 60 m disc (meters read best)
117
- edge: { noise: 8, size: 20, jitter: 0.6, round: 1.5 }, // ragged outline, jagged rim, top bends down 1.5 m at the edge
118
- side: { depth: 3, ground: 'cliff' }, // 3 m of cliff band, colored by biomeColors.cliff
119
- bottom: { depth: (x, z, n, m) => 2 + m * 0.5 + 4 * n.fbm(x * 0.1, z * 0.1), ground: 'rock' }, // hangs lower inland (m grows inward)
119
+ mask: (x, z) => 60 - Math.hypot(x, z), // > 0 ground: a 60 m disc (meters read best)
120
+ edge: { noise: 8, size: 20, jitter: 0.6, round: 1.5 }, // ragged outline, jagged rim, top bends down 1.5 m at the edge
121
+ side: { depth: 3, ground: 'cliff' }, // 3 m of cliff band, colored by biomeColors.cliff
122
+ bottom: { depth: (x, z, n, m) => 2 + m * 0.5 + 4 * n.fbm(x * 0.1, z * 0.1), ground: 'rock' }, // hangs lower inland (m grows inward)
120
123
  },
121
124
  } }));
122
125
  await engine.start();
123
126
 
124
127
  const home = { x: 0, z: 0 };
125
- engine.events.on('terrain:void', ({ who }) => { // fell off: the game decides (the engine never respawns)
128
+ engine.events.on('terrain:void', ({ who }) => { // fell off: the game decides (the engine never respawns)
126
129
  if (who === engine.player) engine.player.placeAt(home);
127
130
  });
128
131
  ```
@@ -160,7 +163,7 @@ engine.use({ name: 'myGround', type: 'picture', provides: ['terrain-draw'], inst
160
163
  const meshes = new Map();
161
164
  ctx.track(e.terrain.view({
162
165
  add(c) { const m = buildMesh(c.data.pos, c.data.nor, c.data.col); m.position.set(c.cx * e.terrain.chunkSize, 0, c.cz * e.terrain.chunkSize); e.scene.add(m); meshes.set(c, m); },
163
- change(c) { refill(meshes.get(c), c.data); }, // terrain.edit rewrote the arrays (the count can differ on an 'adaptive' rim)
166
+ change(c) { refill(meshes.get(c), c.data); }, // terrain.edit rewrote the arrays (the count can differ on an 'adaptive' rim)
164
167
  remove(c) { e.scene.remove(meshes.get(c)); meshes.delete(c); },
165
168
  show(c, visible) { meshes.get(c).visible = visible; },
166
169
  }));
@@ -178,7 +181,7 @@ and `describe().perf.chunks.failed` counts it. Fix the rule, then `engine.terrai
178
181
 
179
182
  ## 8. Triangle cut and bounds margin
180
183
  ```js
181
- terrain({ diagonal: 'adaptive' }) // 'fixed' (default) | 'adaptive' | 'alternate'
184
+ terrain({ diagonal: 'adaptive' }) // 'fixed' (default) | 'adaptive' | 'alternate'
182
185
  ```
183
186
  `fixed` cuts every cell the same way. `adaptive` cuts along the diagonal with the smaller height difference, which removes
184
187
  the zigzag ridges a fixed cut leaves on a slope; `alternate` flips every other cell (no directional bias on flat low-poly facets). `engine.surface`,
@@ -197,11 +200,11 @@ ground-type weight, spawn density, a walkable mask, danger, travel cost.
197
200
  `'cubic'` for slopes without cell creases, which can overshoot beside a sharp step (`clamp: true` keeps it inside the four corner values).
198
201
 
199
202
  ```js fragment
200
- const g = await engine.assets.gridFromImage('/maps/height16.png', { range: [-5, 60] }); // meters, 16-bit file
203
+ const g = await engine.assets.gridFromImage('/maps/height16.png', { range: [-5, 60] }); // meters, 16-bit file
201
204
  const heightAt = sampleGrid(g.data, { ...g, size: [512, 512], origin: [-256, -256], interp: 'cubic', clamp: true });
202
- heightAt(10, 20); // gameplay side: where to put a camp, a mine, a lighthouse
203
- const wet = sampleGrid(moisture, { width: 32, height: 32, cellSize: 8 }); // a hand-made field: wetter ground grows reeds, rice, moss
204
- const walk = sampleGrid(mask, { width: 64, height: 64, cellSize: 1, interp: 'nearest', outside: 0 }); // 0 / 1 per tile; off the map: not walkable
205
+ heightAt(10, 20); // gameplay side: where to put a camp, a mine, a lighthouse
206
+ const wet = sampleGrid(moisture, { width: 32, height: 32, cellSize: 8 }); // a hand-made field: wetter ground grows reeds, rice, moss
207
+ const walk = sampleGrid(mask, { width: 64, height: 64, cellSize: 1, interp: 'nearest', outside: 0 }); // 0 / 1 per tile; off the map: not walkable
205
208
  ```
206
209
  A terrain `height` function is recompiled in a worker and cannot capture `heightAt`, so the terrain reads the same image through its own
207
210
  `heightmap` (bilinear, centered on `center`): `terrain({ heightmap: { ...g, size: [512, 512], min: -5, max: 60 } })` with `g` from `gridFromImage`