threedog 0.0.0-stage → 0.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 (506) hide show
  1. package/CHANGELOG.md +5 -0
  2. package/LICENSE +21 -0
  3. package/README.md +39 -2
  4. package/core/Animator.js +268 -0
  5. package/core/Assets.js +256 -0
  6. package/core/Audio.js +267 -0
  7. package/core/Baked.js +72 -0
  8. package/core/Batching.js +247 -0
  9. package/core/Budget.js +221 -0
  10. package/core/Clock.js +94 -0
  11. package/core/Commits.js +77 -0
  12. package/core/DebugOverrides.js +143 -0
  13. package/core/Describe.js +145 -0
  14. package/core/Engine.js +184 -0
  15. package/core/Events.js +153 -0
  16. package/core/I18n.js +94 -0
  17. package/core/Input.js +245 -0
  18. package/core/Inspect.js +77 -0
  19. package/core/InspectScene.js +191 -0
  20. package/core/Jobs.js +146 -0
  21. package/core/Loading.js +149 -0
  22. package/core/MaterialInfo.js +32 -0
  23. package/core/Ops.js +256 -0
  24. package/core/Random.js +52 -0
  25. package/core/Rays.js +160 -0
  26. package/core/SaveStore.js +85 -0
  27. package/core/Saves.js +254 -0
  28. package/core/Stream.js +279 -0
  29. package/core/Threads.js +158 -0
  30. package/core/UrlState.js +94 -0
  31. package/core/Vars.js +35 -0
  32. package/core/Views.js +49 -0
  33. package/core/actor.js +23 -0
  34. package/core/assetEntry.js +89 -0
  35. package/core/assetLoad.js +190 -0
  36. package/core/assetManifest.js +35 -0
  37. package/core/assetReport.js +83 -0
  38. package/core/audioRules.js +121 -0
  39. package/core/audioVoice.js +225 -0
  40. package/core/batchGroups.js +116 -0
  41. package/core/canvasBox.js +63 -0
  42. package/core/catalog.js +169 -0
  43. package/core/checks.js +67 -0
  44. package/core/claims.js +51 -0
  45. package/core/dayTime.js +15 -0
  46. package/core/debugView.js +76 -0
  47. package/core/describeRender.js +45 -0
  48. package/core/describeText.js +143 -0
  49. package/core/easing.js +34 -0
  50. package/core/errorCodes.js +205 -0
  51. package/core/errorHints.js +208 -0
  52. package/core/errors.js +40 -0
  53. package/core/events.generated.js +84 -0
  54. package/core/ground.js +102 -0
  55. package/core/holds.js +106 -0
  56. package/core/inputContext.js +69 -0
  57. package/core/inputDefaults.js +22 -0
  58. package/core/inputPad.js +35 -0
  59. package/core/inputPointer.js +48 -0
  60. package/core/inputTouch.js +48 -0
  61. package/core/lifecycle.js +69 -0
  62. package/core/lightWatch.js +56 -0
  63. package/core/look/coreParts.js +112 -0
  64. package/core/look/layers.js +136 -0
  65. package/core/look/part.js +173 -0
  66. package/core/look/report.js +79 -0
  67. package/core/look/write.js +86 -0
  68. package/core/loop.js +200 -0
  69. package/core/math.js +33 -0
  70. package/core/modules.js +196 -0
  71. package/core/movement.js +19 -0
  72. package/core/mulberry32.js +14 -0
  73. package/core/opsAtomic.js +31 -0
  74. package/core/opsCheck.js +97 -0
  75. package/core/opsFail.js +20 -0
  76. package/core/opsGuard.js +26 -0
  77. package/core/opsHistory.js +27 -0
  78. package/core/opsRun.js +77 -0
  79. package/core/page.js +78 -0
  80. package/core/params.js +132 -0
  81. package/core/pureWorker.js +5 -0
  82. package/core/renamed.js +21 -0
  83. package/core/saveApply.js +128 -0
  84. package/core/saveFiles.js +139 -0
  85. package/core/saveIds.js +53 -0
  86. package/core/saveVersions.js +97 -0
  87. package/core/scatter.js +92 -0
  88. package/core/sceneMethods.js +100 -0
  89. package/core/screenToGround.js +39 -0
  90. package/core/services.js +73 -0
  91. package/core/session.js +171 -0
  92. package/core/shadowTypes.js +15 -0
  93. package/core/skip.js +104 -0
  94. package/core/startup.js +135 -0
  95. package/core/streamCells.js +24 -0
  96. package/core/streamSources.js +73 -0
  97. package/core/styleParts.js +96 -0
  98. package/core/targeting.js +64 -0
  99. package/core/thingExplain.js +68 -0
  100. package/core/thingOps.js +168 -0
  101. package/core/things.js +212 -0
  102. package/core/threadPure.js +120 -0
  103. package/core/threadServe.js +25 -0
  104. package/core/tier.js +11 -0
  105. package/core/util.js +11 -0
  106. package/core/validate.js +204 -0
  107. package/docs/AI.md +123 -0
  108. package/docs/API.md +83 -0
  109. package/docs/CODEMAP.md +347 -0
  110. package/docs/COMMANDS.md +108 -0
  111. package/docs/CONVENTIONS.md +145 -0
  112. package/docs/PERF.md +217 -0
  113. package/docs/THREE.md +86 -0
  114. package/docs/api/ambience.md +15 -0
  115. package/docs/api/assets.md +62 -0
  116. package/docs/api/audio.md +53 -0
  117. package/docs/api/budget.md +40 -0
  118. package/docs/api/cameraRig.md +120 -0
  119. package/docs/api/characters.md +144 -0
  120. package/docs/api/clock.md +7 -0
  121. package/docs/api/collision.md +39 -0
  122. package/docs/api/content.md +64 -0
  123. package/docs/api/dialogue.md +39 -0
  124. package/docs/api/engine.md +199 -0
  125. package/docs/api/entities.md +61 -0
  126. package/docs/api/events.md +95 -0
  127. package/docs/api/flow.md +27 -0
  128. package/docs/api/grids.md +11 -0
  129. package/docs/api/ground.md +16 -0
  130. package/docs/api/hlod.md +34 -0
  131. package/docs/api/hud.md +31 -0
  132. package/docs/api/i18n.md +10 -0
  133. package/docs/api/input.md +24 -0
  134. package/docs/api/interactions.md +31 -0
  135. package/docs/api/inventory.md +66 -0
  136. package/docs/api/jobs.md +10 -0
  137. package/docs/api/level.md +41 -0
  138. package/docs/api/lightPool.md +56 -0
  139. package/docs/api/music.md +34 -0
  140. package/docs/api/nav.md +26 -0
  141. package/docs/api/net.md +14 -0
  142. package/docs/api/openWorld.md +24 -0
  143. package/docs/api/particles.md +41 -0
  144. package/docs/api/photo.md +15 -0
  145. package/docs/api/post.md +10 -0
  146. package/docs/api/quests.md +36 -0
  147. package/docs/api/rays.md +26 -0
  148. package/docs/api/rigid.md +84 -0
  149. package/docs/api/saves.md +32 -0
  150. package/docs/api/settings.md +36 -0
  151. package/docs/api/sky.md +58 -0
  152. package/docs/api/stream.md +31 -0
  153. package/docs/api/style.md +134 -0
  154. package/docs/api/terrain.md +34 -0
  155. package/docs/api/timeline.md +39 -0
  156. package/docs/api/tools.md +57 -0
  157. package/docs/api/triggers.md +56 -0
  158. package/docs/api/vars.md +9 -0
  159. package/docs/api/vegetation.md +52 -0
  160. package/docs/api/water.md +48 -0
  161. package/docs/api/weather.md +29 -0
  162. package/docs/api/world.md +30 -0
  163. package/docs/recipes/01-new-game.md +148 -0
  164. package/docs/recipes/02-npc.md +167 -0
  165. package/docs/recipes/03-items-pickups.md +158 -0
  166. package/docs/recipes/04-quests.md +83 -0
  167. package/docs/recipes/05-props-bake.md +159 -0
  168. package/docs/recipes/06-clock-events.md +117 -0
  169. package/docs/recipes/07-flow-scenes-pause.md +132 -0
  170. package/docs/recipes/08-weather-sky.md +74 -0
  171. package/docs/recipes/09-style-pack.md +234 -0
  172. package/docs/recipes/10-blender-level.md +67 -0
  173. package/docs/recipes/11-vehicles.md +55 -0
  174. package/docs/recipes/12-navmesh.md +79 -0
  175. package/docs/recipes/13-animation.md +149 -0
  176. package/docs/recipes/14-custom-module.md +91 -0
  177. package/docs/recipes/15-perf.md +78 -0
  178. package/docs/recipes/16-dev-bridge.md +180 -0
  179. package/docs/recipes/18-world.md +185 -0
  180. package/docs/recipes/19-shooting-picking.md +76 -0
  181. package/docs/recipes/20-content-actions-save.md +176 -0
  182. package/docs/recipes/21-camera.md +153 -0
  183. package/docs/recipes/22-shop-gold.md +107 -0
  184. package/docs/recipes/23-ops.md +175 -0
  185. package/docs/recipes/26-ui-parts.md +138 -0
  186. package/docs/recipes/27-net.md +96 -0
  187. package/docs/recipes/28-terrain.md +80 -0
  188. package/docs/recipes/29-grid.md +87 -0
  189. package/docs/recipes/30-templates.md +131 -0
  190. package/docs/recipes/31-audio.md +126 -0
  191. package/docs/recipes/32-action-game.md +33 -0
  192. package/docs/recipes/33-stream-sources.md +37 -0
  193. package/docs/recipes/34-environment-lighting.md +36 -0
  194. package/docs/recipes/35-style-from-reference.md +89 -0
  195. package/docs/recipes/36-sky-ground-plant-looks.md +116 -0
  196. package/docs/recipes/37-terrain-look-hooks.md +97 -0
  197. package/docs/recipes/38-environment-look-hooks.md +83 -0
  198. package/docs/recipes/40-scene.md +108 -0
  199. package/docs/recipes/41-thing-registry.md +93 -0
  200. package/docs/recipes/42-terrain-shape.md +64 -0
  201. package/docs/recipes/43-shader-patches-surface-looks.md +120 -0
  202. package/docs/recipes/44-water-weather-look-hooks.md +135 -0
  203. package/docs/recipes/45-cascaded-shadows.md +51 -0
  204. package/docs/recipes/46-blender-art-route.md +114 -0
  205. package/docs/recipes/47-island-snow-backdrop.md +44 -0
  206. package/docs/recipes/48-make-material.md +70 -0
  207. package/docs/recipes/49-game-module-contract.md +71 -0
  208. package/docs/recipes/50-own-renderer.md +12 -0
  209. package/docs/recipes/51-capability-catalog.md +63 -0
  210. package/docs/recipes/52-look.md +108 -0
  211. package/examples/action/DESIGN.md +3 -0
  212. package/examples/action/GAMEMAP.md +127 -0
  213. package/examples/action/content/actions.js +8 -0
  214. package/examples/action/content/audio.js +9 -0
  215. package/examples/action/content/index.js +10 -0
  216. package/examples/action/content/items.js +4 -0
  217. package/examples/action/content/places.js +4 -0
  218. package/examples/action/content/props.js +11 -0
  219. package/examples/action/content/templates.js +10 -0
  220. package/examples/action/content/views.js +6 -0
  221. package/examples/action/look.js +5 -0
  222. package/examples/action/main.js +137 -0
  223. package/examples/action/models.js +25 -0
  224. package/examples/sheepisland/GAMEMAP.md +107 -0
  225. package/examples/sheepisland/content/index.js +6 -0
  226. package/examples/sheepisland/content/props.js +19 -0
  227. package/examples/sheepisland/content/templates.js +5 -0
  228. package/examples/sheepisland/content/vegetation.js +8 -0
  229. package/examples/sheepisland/main.js +71 -0
  230. package/examples/sheepisland/params.js +25 -0
  231. package/examples/sheepisland/style/index.js +79 -0
  232. package/examples/sheepisland/style/models.js +59 -0
  233. package/examples/sheepisland/views.js +9 -0
  234. package/examples/styletest/GAMEMAP.md +135 -0
  235. package/examples/styletest/content/index.js +9 -0
  236. package/examples/styletest/content/items.js +8 -0
  237. package/examples/styletest/content/npcs.js +8 -0
  238. package/examples/styletest/content/places.js +5 -0
  239. package/examples/styletest/content/props.js +16 -0
  240. package/examples/styletest/content/templates.js +9 -0
  241. package/examples/styletest/content/vegetation.js +31 -0
  242. package/examples/styletest/look.js +11 -0
  243. package/examples/styletest/main.js +95 -0
  244. package/examples/styletest/models.js +87 -0
  245. package/examples/styletest/overrides.js +33 -0
  246. package/examples/styletest/panel.js +135 -0
  247. package/examples/styletest/params.js +32 -0
  248. package/examples/styletest/views.js +31 -0
  249. package/examples/world/DESIGN.md +5 -0
  250. package/examples/world/GAMEMAP.md +171 -0
  251. package/examples/world/content/actions.js +8 -0
  252. package/examples/world/content/audio.js +25 -0
  253. package/examples/world/content/bodies.js +12 -0
  254. package/examples/world/content/containers.js +4 -0
  255. package/examples/world/content/dialogues.js +33 -0
  256. package/examples/world/content/index.js +17 -0
  257. package/examples/world/content/items.js +10 -0
  258. package/examples/world/content/npcs.js +14 -0
  259. package/examples/world/content/pickups.js +11 -0
  260. package/examples/world/content/places.js +6 -0
  261. package/examples/world/content/props.js +12 -0
  262. package/examples/world/content/quests.js +15 -0
  263. package/examples/world/content/rules.js +23 -0
  264. package/examples/world/content/templates.js +5 -0
  265. package/examples/world/content/vegetation.js +32 -0
  266. package/examples/world/main.js +168 -0
  267. package/examples/world/models.js +28 -0
  268. package/index.d.ts +306 -0
  269. package/index.js +122 -0
  270. package/llms.txt +61 -0
  271. package/modules/ambience/Ambience.js +186 -0
  272. package/modules/camera/FirstPersonCamera.js +131 -0
  273. package/modules/camera/FixedCamera.js +162 -0
  274. package/modules/camera/FollowCamera.js +91 -0
  275. package/modules/camera/RtsCamera.js +132 -0
  276. package/modules/camera/common.js +182 -0
  277. package/modules/camera/index.js +11 -0
  278. package/modules/camera/projection.js +34 -0
  279. package/modules/characters/Character.js +235 -0
  280. package/modules/characters/NPC.js +242 -0
  281. package/modules/characters/assetModel.js +42 -0
  282. package/modules/characters/astar.js +66 -0
  283. package/modules/characters/behaviors.js +72 -0
  284. package/modules/characters/footsteps.js +13 -0
  285. package/modules/characters/index.js +215 -0
  286. package/modules/characters/moveHelpers.js +29 -0
  287. package/modules/characters/movers/common.js +62 -0
  288. package/modules/characters/movers/rapier.js +74 -0
  289. package/modules/characters/movers/simple.js +43 -0
  290. package/modules/characters/npcAvoid.js +129 -0
  291. package/modules/characters/npcSim.js +150 -0
  292. package/modules/characters/npcView.js +42 -0
  293. package/modules/characters/pathAsync.js +113 -0
  294. package/modules/characters/pathJob.js +62 -0
  295. package/modules/characters/pathWorker.js +7 -0
  296. package/modules/characters/playerStrings.js +12 -0
  297. package/modules/characters/proceduralRig.js +58 -0
  298. package/modules/characters/useModel.js +22 -0
  299. package/modules/characters/walkTo.js +58 -0
  300. package/modules/collision/Collision.js +274 -0
  301. package/modules/collision/grid.js +63 -0
  302. package/modules/content/explain.js +13 -0
  303. package/modules/content/ids.js +95 -0
  304. package/modules/content/index.js +154 -0
  305. package/modules/content/loader.js +190 -0
  306. package/modules/content/models.js +69 -0
  307. package/modules/content/packs.js +69 -0
  308. package/modules/content/props.js +89 -0
  309. package/modules/content/rules.js +134 -0
  310. package/modules/content/templates.js +189 -0
  311. package/modules/debug/DebugPanel.js +174 -0
  312. package/modules/entities/Entities.js +243 -0
  313. package/modules/entities/build.js +25 -0
  314. package/modules/entities/index.js +4 -0
  315. package/modules/flow/index.js +101 -0
  316. package/modules/gameplay/Container.js +227 -0
  317. package/modules/gameplay/Containers.js +89 -0
  318. package/modules/gameplay/Dialogue.js +219 -0
  319. package/modules/gameplay/Interactions.js +253 -0
  320. package/modules/gameplay/Inventory.js +224 -0
  321. package/modules/gameplay/Quests.js +205 -0
  322. package/modules/gameplay/boxOps.js +60 -0
  323. package/modules/gameplay/dialogueBox.js +48 -0
  324. package/modules/gameplay/interactionPrompt.js +28 -0
  325. package/modules/gameplay/inventoryOps.js +137 -0
  326. package/modules/gameplay/pickups.js +115 -0
  327. package/modules/gameplay/questLog.js +54 -0
  328. package/modules/gameplay/questSave.js +71 -0
  329. package/modules/grid/Grid.js +184 -0
  330. package/modules/grid/Layer.js +142 -0
  331. package/modules/grid/index.js +236 -0
  332. package/modules/grid/ops.js +73 -0
  333. package/modules/grid/preview.js +85 -0
  334. package/modules/grid/tiles.js +79 -0
  335. package/modules/hlod/index.js +167 -0
  336. package/modules/hud/index.js +167 -0
  337. package/modules/hud/parts.js +80 -0
  338. package/modules/level/geometry.js +46 -0
  339. package/modules/level/heightfield.js +160 -0
  340. package/modules/level/index.js +233 -0
  341. package/modules/level/nodes.js +84 -0
  342. package/modules/lights/index.js +227 -0
  343. package/modules/music/Music.js +294 -0
  344. package/modules/music/index.js +2 -0
  345. package/modules/music/rules.js +28 -0
  346. package/modules/nav/index.js +156 -0
  347. package/modules/nav/navPath.js +17 -0
  348. package/modules/net/Client.js +137 -0
  349. package/modules/net/Host.js +117 -0
  350. package/modules/net/Net.js +49 -0
  351. package/modules/net/index.js +77 -0
  352. package/modules/net/sync.js +114 -0
  353. package/modules/net/transports.js +118 -0
  354. package/modules/particles/Particles.js +179 -0
  355. package/modules/particles/effect.js +112 -0
  356. package/modules/particles/shaders.js +28 -0
  357. package/modules/photo/Photo.js +146 -0
  358. package/modules/rigid/RigidBodies.js +265 -0
  359. package/modules/rigid/Vehicles.js +97 -0
  360. package/modules/rigid/sync.js +158 -0
  361. package/modules/settings/Settings.js +297 -0
  362. package/modules/settings/apply.js +21 -0
  363. package/modules/settings/index.js +3 -0
  364. package/modules/settings/sections.js +156 -0
  365. package/modules/settings/strings.js +53 -0
  366. package/modules/settings/view.js +65 -0
  367. package/modules/sky/Sky.js +259 -0
  368. package/modules/sky/calendar.js +80 -0
  369. package/modules/sky/cascades.js +125 -0
  370. package/modules/sky/clouds.js +79 -0
  371. package/modules/sky/domeLayers.js +33 -0
  372. package/modules/sky/environment.js +141 -0
  373. package/modules/sky/fog.js +139 -0
  374. package/modules/sky/frame.js +77 -0
  375. package/modules/sky/layers.js +69 -0
  376. package/modules/sky/look.js +51 -0
  377. package/modules/sky/lookFog.js +80 -0
  378. package/modules/sky/lookShadow.js +50 -0
  379. package/modules/sky/lookSky.js +108 -0
  380. package/modules/sky/schedule.js +80 -0
  381. package/modules/sky/shader.js +96 -0
  382. package/modules/sky/shadow.js +74 -0
  383. package/modules/sky/skyModule.js +60 -0
  384. package/modules/terrain/ChunkManager.js +260 -0
  385. package/modules/terrain/chunkJob.js +19 -0
  386. package/modules/terrain/chunkLevels.js +40 -0
  387. package/modules/terrain/chunkQueries.js +42 -0
  388. package/modules/terrain/chunkWorker.js +5 -0
  389. package/modules/terrain/index.js +118 -0
  390. package/modules/terrain/lookGround.js +61 -0
  391. package/modules/terrain/mountTerrain.js +32 -0
  392. package/modules/terrain/terrainColorMap.js +41 -0
  393. package/modules/terrain/terrainDefaults.js +39 -0
  394. package/modules/terrain/terrainEdit.js +139 -0
  395. package/modules/terrain/terrainGen.js +155 -0
  396. package/modules/terrain/terrainIsland.js +131 -0
  397. package/modules/terrain/terrainMesh.js +92 -0
  398. package/modules/terrain/terrainShape.js +108 -0
  399. package/modules/terrain/terrainShapeMain.js +41 -0
  400. package/modules/terrain/terrainTexture.js +44 -0
  401. package/modules/timeline/Timeline.js +253 -0
  402. package/modules/timeline/Tween.js +114 -0
  403. package/modules/timeline/letterbox.js +24 -0
  404. package/modules/timeline/shots.js +90 -0
  405. package/modules/triggers/index.js +268 -0
  406. package/modules/vegetation/Vegetation.js +256 -0
  407. package/modules/vegetation/groundChunks.js +177 -0
  408. package/modules/vegetation/index.js +43 -0
  409. package/modules/vegetation/lookWind.js +37 -0
  410. package/modules/vegetation/modelGeometry.js +21 -0
  411. package/modules/water/Water.js +160 -0
  412. package/modules/water/look.js +80 -0
  413. package/modules/water/surface.js +88 -0
  414. package/modules/weather/Weather.js +242 -0
  415. package/modules/weather/look.js +75 -0
  416. package/modules/weather/particles.js +92 -0
  417. package/modules/weather/shaders.js +49 -0
  418. package/modules/weather/strings.js +15 -0
  419. package/modules/world/World.js +231 -0
  420. package/modules/world/cells.js +42 -0
  421. package/modules/world/explain.js +11 -0
  422. package/modules/world/index.js +71 -0
  423. package/modules/world/persist.js +107 -0
  424. package/modules/world/pos.js +20 -0
  425. package/modules/world/records.js +89 -0
  426. package/modules/world/sim.js +175 -0
  427. package/modules/world/simFar.js +82 -0
  428. package/modules/world/state.js +115 -0
  429. package/modules/world/thingSource.js +44 -0
  430. package/modules/world/views.js +182 -0
  431. package/package.json +66 -4
  432. package/presets.js +96 -0
  433. package/render/PostFX.js +240 -0
  434. package/render/detail.js +105 -0
  435. package/render/effects.js +144 -0
  436. package/render/engineUniforms.js +23 -0
  437. package/render/fuse.js +84 -0
  438. package/render/lighting.js +100 -0
  439. package/render/lights.js +18 -0
  440. package/render/lookSurface.js +161 -0
  441. package/render/materials.js +220 -0
  442. package/render/patches.js +252 -0
  443. package/render/postLook.js +86 -0
  444. package/render/surface.js +69 -0
  445. package/render/uniformDecl.js +29 -0
  446. package/types/common.d.ts +34 -0
  447. package/types/core.d.ts +1965 -0
  448. package/types/gameplay.d.ts +1822 -0
  449. package/types/generated/core/Audio.d.ts +200 -0
  450. package/types/generated/core/Batching.d.ts +47 -0
  451. package/types/generated/core/Budget.d.ts +90 -0
  452. package/types/generated/core/Commits.d.ts +31 -0
  453. package/types/generated/core/DebugOverrides.d.ts +52 -0
  454. package/types/generated/core/Events.d.ts +89 -0
  455. package/types/generated/core/I18n.d.ts +30 -0
  456. package/types/generated/core/Input.d.ts +118 -0
  457. package/types/generated/core/Jobs.d.ts +41 -0
  458. package/types/generated/core/Ops.d.ts +203 -0
  459. package/types/generated/core/Random.d.ts +49 -0
  460. package/types/generated/core/Rays.d.ts +49 -0
  461. package/types/generated/core/Saves.d.ts +162 -0
  462. package/types/generated/core/Stream.d.ts +93 -0
  463. package/types/generated/core/Threads.d.ts +82 -0
  464. package/types/generated/core/Views.d.ts +33 -0
  465. package/types/generated/core/audioVoice.d.ts +47 -0
  466. package/types/generated/core/page.d.ts +18 -0
  467. package/types/generated/core/session.d.ts +48 -0
  468. package/types/generated/modules/ambience/Ambience.d.ts +48 -0
  469. package/types/generated/modules/debug/DebugPanel.d.ts +24 -0
  470. package/types/generated/modules/flow/index.d.ts +10 -0
  471. package/types/generated/modules/grid/Grid.d.ts +151 -0
  472. package/types/generated/modules/grid/Layer.d.ts +65 -0
  473. package/types/generated/modules/grid/index.d.ts +86 -0
  474. package/types/generated/modules/hlod/index.d.ts +11 -0
  475. package/types/generated/modules/hud/index.d.ts +10 -0
  476. package/types/generated/modules/lights/index.d.ts +13 -0
  477. package/types/generated/modules/music/Music.d.ts +111 -0
  478. package/types/generated/modules/net/Net.d.ts +34 -0
  479. package/types/generated/modules/net/index.d.ts +53 -0
  480. package/types/generated/modules/net/transports.d.ts +58 -0
  481. package/types/generated/modules/particles/Particles.d.ts +69 -0
  482. package/types/generated/modules/sky/Sky.d.ts +145 -0
  483. package/types/generated/modules/sky/skyModule.d.ts +10 -0
  484. package/types/generated/modules/timeline/Timeline.d.ts +51 -0
  485. package/types/generated/modules/water/Water.d.ts +29 -0
  486. package/types/generated/modules/weather/Weather.d.ts +62 -0
  487. package/types/generated/modules/world/World.d.ts +242 -0
  488. package/types/generated/modules/world/index.d.ts +15 -0
  489. package/types/generated/render/PostFX.d.ts +125 -0
  490. package/types/generated/render/materials.d.ts +100 -0
  491. package/types/generated/render/patches.d.ts +41 -0
  492. package/types/generated/ui/Focus.d.ts +11 -0
  493. package/types/generated/ui/LoadingScreen.d.ts +2 -0
  494. package/types/generated/ui/UI.d.ts +57 -0
  495. package/types/nav.d.ts +52 -0
  496. package/types/physics.d.ts +592 -0
  497. package/types/style.d.ts +638 -0
  498. package/types/worker.d.ts +11 -0
  499. package/types/world.d.ts +772 -0
  500. package/ui/Focus.js +51 -0
  501. package/ui/LoadingScreen.js +42 -0
  502. package/ui/Parts.js +199 -0
  503. package/ui/UI.js +167 -0
  504. package/ui/defaults.js +85 -0
  505. package/ui/theme.js +124 -0
  506. package/ui/touchPart.js +49 -0
@@ -0,0 +1,175 @@
1
+ # Ops: one entry point for what players and NPCs do (engine.ops)
2
+
3
+ **What is an op**: one discrete thing an actor decides to do: buy, talk, attack, roll, fire, reload, craft, build, demolish. Write one with
4
+ `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`.
5
+ **What is not an op**: continuous input (stick, look, aim while moving) and simulation (hunger, crop growth, burning, bullets in flight). Those stay
6
+ in a module's `fixed` or `world.simulate`. Low-level functions such as `inventory.transfer` and `world.set` are not wrapped either: an op's `run` calls them.
7
+
8
+ ## 1. Define and run
9
+ ```js
10
+ const PRICE = { bread: 5 };
11
+ engine.ops.define('shop.buy', {
12
+ desc: 'Buy from a shop shelf',
13
+ args: { shop: 'string', item: 'string', n: 'int?' }, // types: string number int bool position id any; ? = optional
14
+ can(e, { shop, item, n = 1 }, ctx) { // read-only: return true or a reason string
15
+ if (!e.inventory.container(shop).has(item, n)) return 'soldOut';
16
+ if (e.inventory.container(ctx.actor).count('gold') < PRICE[item] * n) return 'noMoney';
17
+ return true;
18
+ },
19
+ run(e, { shop, item, n = 1 }, ctx) { // runs only after can passed
20
+ const got = e.inventory.transfer(shop, ctx.actor, item, n);
21
+ e.inventory.container(ctx.actor).remove('gold', PRICE[item] * got);
22
+ return got; // plain data; becomes r.value
23
+ },
24
+ offers: (e, ctx) => [{ shop: 'shop-bakery', item: 'bread' }], // optional: arg sets possible now (ops list / dev bridge `ops`)
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, code: 'noUndo', facts: { op } } without one)
27
+ });
28
+
29
+ const r = engine.ops.run('shop.buy', { shop: 'shop-bakery', item: 'bread' });
30
+ // r = { ok: true, value: 1 } or { ok: false, code: 'noMoney', facts, nextActions }
31
+ const { ok } = engine.ops.can('shop.buy', { shop: 'shop-bakery', item: 'bread' }); // ask only: grey out a button
32
+ ```
33
+ Rules that keep ops replayable and network-ready:
34
+ - **Use `ctx.actor`, never `engine.player`.** `ctx.actor` is the world record id of whoever acts (default `engine.actor`, which is `'player'` — also
35
+ the player's container id — unless the game hands control to a vehicle or squad member). NPCs run the same op with `{ actor: 'npc_3' }`; where an
36
+ actor stands is `engine.actorPosition(ctx.actor)`.
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
+ position) goes in the args. Pass a fresh object each call; in dev the args are frozen because the history keeps them.
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.code)`); the engine shows nothing itself.
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` keeps emitting your domain events as before.
43
+
44
+ ## 2. Who calls it, and when
45
+ | Caller | How | History `phase` / `source` |
46
+ |---|---|---|
47
+ | A key in a module's `fixed` (attack, roll, fire) | `e.ops.run('combat.roll', { dir }, { source: 'player' })` | `fixed` / `player` |
48
+ | A UI button or click | `engine.ops.run('shop.buy', args)` | `between` / `player` |
49
+ | Dialogue choices, triggers, quest rewards in content | `do: { op: ['shop.buy', { shop: 'shop-bakery', item: 'bread' }] }`, `if: { can: ['shop.buy', {...}] }` | inherits the caller |
50
+ | Dev bridge | `npx threedog op shop.buy shop=shop-bakery item=bread` / `npx threedog ops` | `between` / `bridge` |
51
+ | Enemy AI in `world.simulate` | `e.ops.run('combat.attack', { kind: 'light' }, { actor: rec.id })` | `fixed` / `game` |
52
+
53
+ `run` is synchronous and returns at once. Between fixed steps it counts as "after step N", which replays the same. Ops still run while gameplay is
54
+ frozen by a menu (`ctx.frozen` is true; return `'paused'` from `can` for things that must wait); after a gameplay error (`engine.error`) every op
55
+ returns `'halted'`.
56
+
57
+ ## 3. Built-in ops (installed with their modules)
58
+ | Op | Args | Reasons |
59
+ |---|---|---|
60
+ | `interaction.use` | `{ id?, action? }` (interaction id from `interactions.add(target, { id })`, default the world record id it was built for; omit it to use the one the actor would pick now by `interactions({ pick })`, optionally only among one key action) | `unknown` `nothingNear` `disabled` `tooFar` `inputLocked` |
61
+ | `dialogue.advance` | none | `noDialogue` |
62
+ | `dialogue.choose` | `{ index }` (0-based among visible choices) | `noDialogue` `noChoice` |
63
+ | `inventory.transfer` | `{ from, to, item, n? }` (item = item id or entry key `sword#3`) | `noContainer` `notEnough` `full` |
64
+ | `inventory.trade` | `{ take, give, takeN?, giveN?, container? }` (all or nothing in `ctx.actor`'s container; reversible with `engine.ops.undo`, recipe 03) | `noContainer` `notEnough` `full` |
65
+ | `inventory.use` | `{ item }` (from `ctx.actor`'s container; runs the item's `use`, see recipe 03) | `notEnough` `notUsable` or the item's `canUse` reason |
66
+ | `inventory.drop` | `{ item, n? }` (a pickup at the actor's feet, data kept) | `notEnough` `noWorld` `noPosition` |
67
+ | `thing.set` | `{ id, position?, rotation?, scale?, visible? }` (core; a world record via `world.set` / `move`, an `engine.add` object saved as an override when it has an id; undoable, recipe 41) | `noThing` `engineOwned` `recordVisible` |
68
+ | `thing.remove` | `{ id }` (core; undoable: an `engine.add` object is detached and kept, a record re-added) | `noThing` `engineOwned` |
69
+ | `photo.take` | none (`r.value` is the shot; can = `photo.canTake()`, the key emits `photo:denied { reason }`) | `denied` or yours |
70
+
71
+ ## 4. Read the log
72
+ ```js
73
+ engine.ops.recent('shop.buy'); // [{ seq, tick, phase, name, args, source, actor, ok, code, depth, count }] old -> new
74
+ engine.ops.list(); // defined ops [{ name, desc, args }]
75
+ engine.ops.list({ available: true }); // each offer checked with can [{ name, args, ok, code }]
76
+ ```
77
+ Consecutive identical failures (same actor, op and code, e.g. `cooldown` while the trigger is held) merge into one entry with `count`.
78
+ The ring keeps `engine.ops.historySize` entries (256). A save load writes a `(load)` entry: what follows happened in the loaded world.
79
+ A thrown `run` freezes gameplay in dev / tests and `engine.error` names `ops.run('name')` plus the last 5 ops.
80
+
81
+ ## 5. The guard (dev)
82
+ Saved gameplay state (`world.add/set/move/remove`, containers and the inventory, `vars`, quest start / advance) may change only while loading, inside
83
+ a fixed step, inside an op, during `saves.load` or `applyState`. Anywhere else (a UI callback, `onFrame`, `setTimeout`, `npx threedog js`) prints once
84
+ per place:
85
+ `[engine] gameplay state changed outside a fixed step or an op: world.set, called at ...`. Fix: turn the write into an op and `engine.ops.run` it, or
86
+ move simulation into `fixed`. `npm test` lists every place in `.threedog/ops-guard.log`.
87
+
88
+ A module that owns its own saved state joins the guard (experimental): call `engine.ops.guard('store.set')` (a no-op in production builds) at the top
89
+ of each writing method, and wrap writes that are allowed anyway (loading your save part) in `engine.ops.allow(() => ...)`.
90
+
91
+ ## 6. Testing
92
+ A test runs the op directly instead of walking, pressing keys and waiting for typing:
93
+ ```js
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).code on failure
96
+ ```
97
+ Keep one `press` test per key to prove "key -> op" itself works (the history shows `interaction.use` after `press interact`).
98
+
99
+ ## 7. Scenario tests: a test written as data
100
+ Put `<workspace>/tests/scenarios/<name>.json` in the engine package or a game; `npx threedog test` runs each file as the item `scenario: <name>`, and
101
+ `npx threedog scenario <name>` runs one on the page under `npm run dev`.
102
+ ```json
103
+ { "name": "barter: buy until sold out", "url": "/", "state": { "pos": "@fisher", "cutscene": "skip" },
104
+ "steps": [
105
+ { "op": "barter.buy", "args": { "shop": "fisher-basket", "item": "berry" } },
106
+ { "op": "barter.buy", "args": { "shop": "fisher-basket", "item": "berry" }, "expect": "soldOut" },
107
+ { "step": 0.5 },
108
+ { "press": "interact" },
109
+ { "expect": { "inventory.items.berry": 1, "ui.dialogue": null } },
110
+ { "snapshot": "after-barter", "only": ["inventory"] }
111
+ ] }
112
+ ```
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
+ (seconds) and `press`.
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
+ - `expect` maps `describe()` paths to values (`nearby[0].name` works; numbers within 0.01; `null` = absent). `snapshot` compares with
117
+ `tests/snapshots/<name>.describe.json` (`only` / `ignore` / `tolerance`; write it with `threedog test <name> --update-snapshots`).
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.
119
+ - Use `press` only for the one test per key that proves "key -> op". Examples in the engine repository: `packages/engine/tests/scenarios/`.
120
+
121
+ ## 8. Inspect and explain
122
+ ```js
123
+ engine.inspect(); // { actor: 'player', at, near: [...nearby], ops: [{ op, args, ok, code?, why? }] }: what is around and possible now
124
+ engine.inspect('npc_3'); // the same as another actor; engine.inspect([x, z]) around a spot
125
+ engine.explain({ op: 'shop.buy', args: { shop: 'bakery', item: 'bread' } }).text;
126
+ // text: 'shop.buy {...} cannot run now: noMoney (Not enough gold)'; detail: 'last attempt at tick 812 (player, player): noMoney' (+ recent, events)
127
+ engine.explain({ quest: 'first-light' }).text; // 'quest ... waits on step 2/3 "...": its done() returns false'
128
+ ```
129
+ Other keys come from modules: add `explain: { myKey(e, value, query) { return { ok, text }; } }` to the module definition. Dev bridge: `npx threedog
130
+ inspect [id | x,z]`, `npx threedog explain op shop.buy shop=bakery item=bread`, `npx threedog explain quest first-light`.
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
+
136
+ ## 9. Randomness
137
+ Gameplay randomness uses `engine.random` (`next / range / int / pick / chance`): it is saved with the game and `createEngine({ seed })` fixes it, so a
138
+ scenario replays the same. `Math.random` breaks both.
139
+
140
+ ## 10. Property tests: random op sequences
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).
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.
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. `reason` is a deprecated alias of `code` on failed results, kept until 1.0.
@@ -0,0 +1,138 @@
1
+ # UI parts: replace or turn off any piece of the engine's screen UI
2
+
3
+ Every piece of UI the engine draws is a named **part** with a plain default:
4
+ `loading`, `toast`, `title` (off by default), `touch` (on-screen stick and buttons),
5
+ `hud.marker`, `hud.counter`, `hud.bar`, `dialogue`, `prompt` ("E · Talk"), `questLog`, `inventory` (with the inventory module).
6
+ 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.
7
+ Each name takes one value: `false` off · `true` default · `{ ...options }` default with options ·
8
+ `(engine, options) => ({ show, update, hide, dispose })` your own (any verb may be omitted).
9
+ Only want different colors / layout? Use the style pack (`style.ui` colors, `style.ui.css`, `style.ui.templates.*`), not a new part.
10
+
11
+ ## 1. Pick at start (copy it)
12
+ ```js
13
+ const engine = createEngine({
14
+ canvas,
15
+ ui: {
16
+ loading: { title: 'My Game' }, // default loading screen with a title
17
+ title: { title: 'My Game' }, // turn on the title screen: Continue (when a save exists) / Start / Settings
18
+ toast: false, // no pop-up messages at all
19
+ },
20
+ });
21
+ ```
22
+ `loading` can only be set here (it shows while the engine is built). The others may also be set with `engine.ui.set(name, value)` before `engine.start()`.
23
+ A misspelled name throws at `start()` and lists the names that exist.
24
+
25
+ ## 2. Your own part (DOM, canvas, a UI library: anything)
26
+ ```js
27
+ engine.ui.set('hud.bar', (engine) => { // called once per bar
28
+ const el = document.createElement('progress'); el.max = 1; engine.uiRoot.appendChild(el); // build under engine.uiRoot: dispose cleans it up
29
+ return {
30
+ update: d => { el.value = d.value / (d.max ?? 1); el.title = d.label ?? d.id; },
31
+ dispose: () => el.remove(),
32
+ };
33
+ });
34
+ engine.hud.bar('hp', { value: 80, max: 100, label: 'HP' }); // game code does not change
35
+ ```
36
+ What each part receives:
37
+ | Part | Created | Calls |
38
+ |---|---|---|
39
+ | `loading` | once | `show({ title })` · `update({ progress 0-1, text })` · `hide()` |
40
+ | `toast` | once | `show({ text, kind, ms })`; kind is `'info' 'quest' 'item' 'save' 'error'` |
41
+ | `title` | once | `show({ title, items: [{ id, label, run() }] })` · `hide()` (call `item.run()` on click) |
42
+ | `hud.marker` | per marker | `update({ x, y, onScreen, arrow, angle, label, icon, distance })` every frame · `hide()` · `dispose()` |
43
+ | `hud.counter` | per counter | `update({ id, label, icon, value, max })` · `dispose()` |
44
+ | `hud.bar` | per bar | `update({ id, label, value, max })` · `dispose()` |
45
+ | `inventory` | once (on first open; opened by the key from `inventory({ keys })` 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) |
46
+ | `touch` | once, if wanted (1) | `show(view)` · `update(view)` (buttons or language changed) |
47
+ | `prompt` | once | `update({ id, action, key, label, text, x, y, onScreen, use(), options })` every frame in reach · `hide()` |
48
+ | `questLog` | once, full screen (2) | `show(view)` · `update(view)` (quests changed while open) · `hide()` |
49
+ | `dialogue` | once | `show()` · `update(view)` per line, typed character, choices (section 4) · `hide()` |
50
+
51
+ (1) Only when a stick (`createEngine({ joystick })`: `'auto'` on touch devices, `true` always) or a touch button is wanted.
52
+ `view = { stick, buttons: [{ action, label }], move(x, y), press(action), release(action) }`.
53
+ (2) The quest key (`quests({ keys })`, e.g. `...presets.keys.quests`) opens it, Esc and the key close it.
54
+ `view = { title, key, quests: engine.quests.list(), close() }`.
55
+
56
+ Every view hands back functions (`advance`, `choose`, `use`, `close`, `move`, `press`...) instead of making your part call engine internals:
57
+ they run the same ops and input path as keys, so tests, the dev bridge and replays see one path.
58
+ With every part off (`false`) the engine draws no DOM at all and the logic keeps running (`describe()`, ops, quests).
59
+
60
+ ## 3. Toasts: filter instead of all-or-nothing
61
+ ```js
62
+ toast(engine, 'Saved', { kind: 'save' }); // your own message (the engine comes first)
63
+ engine.ui.set('toast', (engine) => ({ show: ({ text, kind }) => { if (kind !== 'quest') myBanner(text); } }));
64
+ engine.use(quests({ ...presets.keys.quests, notify: false })); // or only silence quest messages; notify: ({ type, id, text }) => ... shows them your way
65
+ ```
66
+
67
+ ## 4. Dialogue box: your own look, your own fields
68
+ The engine keeps the dialogue logic (typing on game time, input lock, Esc, number keys, conditions).
69
+ The part draws `view` and answers with `view.advance()` / `view.choose(i)`, which run the ops `dialogue.advance` / `dialogue.choose`.
70
+ `view = { script, node, speaker, text (typed so far), full, typing, choices: [{ text, key, data }], hint, data, lock, advance(), choose(i) }`
71
+ ```js
72
+ engine.dialogue.define('fisher', {
73
+ start: { text: 'Quiet day.', data: { portrait: 'fisher.png', mood: 'tired' }, next: 'ask' }, // your own fields go in data
74
+ ask: { text: 'Here for photos?', choices: [{ text: 'Yes', next: 'end', data: { icon: '📷' } }] },
75
+ });
76
+ engine.ui.set('dialogue', (engine) => {
77
+ const el = document.createElement('div'); el.className = 'my-dlg'; el.hidden = true; engine.uiRoot.appendChild(el);
78
+ let view = null;
79
+ el.onclick = (ev) => { const i = ev.target.dataset?.i; i != null ? view.choose(+i) : view.advance(); };
80
+ return {
81
+ show: () => { el.hidden = false; },
82
+ update: (v) => {
83
+ view = v;
84
+ el.innerHTML = `<img src="${v.data.portrait ?? ''}"><b>${v.speaker}</b><p>${v.text}</p>`
85
+ + v.choices.map((c, i) => `<button data-i="${i}">${c.data.icon ?? ''} ${c.text}</button>`).join('');
86
+ },
87
+ hide: () => { el.hidden = true; },
88
+ dispose: () => el.remove(),
89
+ };
90
+ });
91
+ // voice / portraits / camera shots without replacing the box:
92
+ engine.events.on('dialogue:line', ({ speaker, data }) => { if (data.voice) playVoice(data.voice); });
93
+ ```
94
+ Any other unknown node key is reported as a typo (a misspelled `next` would silently end the dialogue), so extra fields always go in `data`.
95
+ - **Talk while playing** (barks, radio): `engine.dialogue.say('Reloading!', { speaker: 'Mira', lock: false })`
96
+ or `start(name, 'start', null, { lock: false })`. Input stays with the game, Esc is untouched,
97
+ the line moves on by itself `holdSeconds` after it is typed, and it never cuts into a dialogue the player is reading.
98
+ - **Options**: `dialogue({ charsPerSecond: 40, advanceActions: ['confirm', 'interact'], choiceKeys: true, holdSeconds: 2 })`.
99
+ `charsPerSecond: 0` shows the whole line at once; `choiceKeys: false` drops the 1-9 keys (click / op only).
100
+ The choice keys are the actions `choice1`...`choice9` (rebind with `createEngine({ bindings })`), read only while a locking dialogue runs.
101
+
102
+ ## 5. Title screen and "back to title"
103
+ ```js
104
+ createEngine({ canvas, ui: { title: { title: 'My Game', items: ['continue', 'start', { label: 'Credits', run: e => showCredits() }] } } });
105
+ engine.events.on('ui:close', id => { if (id === 'title') startIntro(); }); // the player left the title screen
106
+ engine.ui.open('title'); // show it again (the settings 'game' tab has a "Back to title" button)
107
+ ```
108
+ While the title is open gameplay is frozen, input is locked, and Esc goes to it (the settings menu does not open).
109
+
110
+ ## 6. Settings menu: only the tabs the game needs
111
+ ```js
112
+ engine.use(settings({ sections: ['game', 'graphics', 'audio', 'controls', 'camera'] })); // default: graphics, audio, controls, language, saves
113
+ // optional built-ins by name: 'game' (resume / load / back to title), 'camera' (sensitivity, invert Y, field of view; re-applied on 'camera:change')
114
+ engine.settings.addSection('camera');
115
+ engine.settings.removeSection('saves');
116
+
117
+ // a tab of your own: render gets tools with the control helpers (row / toggle / range / segmented) already bound
118
+ engine.settings.define('subtitles', true, on => { document.body.dataset.subtitles = String(on); });
119
+ engine.settings.addSection('gameplay', {
120
+ title: 'Gameplay',
121
+ render: (tools, e, s) => tools.row('Subtitles', tools.toggle('subtitles', s.get('subtitles'))),
122
+ order: 50,
123
+ });
124
+ ```
125
+ A completely different menu: don't install `settings()`; open your own with `uiFocus(engine).setRoot(() => myMenu.open())` so Esc on an empty stack reaches it.
126
+
127
+ Check what is in use: `engine.ui.describe()` → `{ loading: 'default', toast: 'off', 'hud.bar': 'custom', ... }`.
128
+
129
+ ## 7. Keys, and UI that follows the world
130
+ - Declare keys once with `input.define('action', keys, 'label', { pad })` (or content `actions`) and read them by action name: gameplay keys (attack,
131
+ jump) in the fixed step, UI keys in the frame hook. Never `addEventListener('keydown')`, and never read `pointer.clicked` for gameplay; bind a
132
+ `Mouse0` action instead.
133
+ - A menu, vehicle or build mode that takes over keys pushes an input context: `const h = engine.input.push('menu')` (opaque) or
134
+ `push('vehicle', { pass: true })`, then `h.remove()`. Tests and the dev bridge press keys with `engine.input.simulate(action, down)`.
135
+ - A label over a world position: `worldToScreen(engine, pos)` gives screen coordinates for an HTML element.
136
+
137
+
138
+ Bind a counter to an item count (coins): `engine.onFrame(() => engine.hud.counter('coins', { icon: '🪙', label: 'Coins', value: engine.inventory.count('coin') }));`. Same id = update, unchanged value touches no DOM, and a loaded save follows automatically (recipe 22 section 4).
@@ -0,0 +1,96 @@
1
+ # Co-op multiplayer: net() (host authority + state sync)
2
+
3
+ **What it is**: an optional module for slow, cooperative games (farming together, shared chests, trading). One player's browser is the **host** and
4
+ owns the game state; friends are **clients** that mirror it and ask for changes through ops. Not installed = no cost.
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
+ 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,
7
+ snapshot-able world data) are what it will build on.
8
+
9
+ ## 1. Install
10
+ The same game code runs on every machine; only `role` and the transport differ.
11
+ ```js
12
+ import { net, webSocket } from 'threedog';
13
+
14
+ const room = 'ws://192.168.1.5:8787/farm';
15
+ const hosting = new URLSearchParams(location.search).has('host');
16
+ engine.use(net(hosting
17
+ ? { role: 'host', transport: webSocket(room, { host: true }) }
18
+ : { role: 'client', transport: webSocket(room) }));
19
+ ```
20
+ Run the relay on any machine both can reach: `npx threedog relay 8787` (no dependencies). The relay only forwards; it assigns peer ids
21
+ and a reconnect key.
22
+ For tests and offline demos use the in-process network instead (latency, jitter and loss adjustable; `manual: true` delivers only on `advance(ms)`):
23
+ ```js
24
+ import { fakeNetwork, net } from 'threedog';
25
+ const wire = fakeNetwork({ latency: 80, jitter: 30, loss: 0.05 });
26
+ host.use(net({ role: 'host', transport: wire.host() }));
27
+ guest.use(net({ role: 'client', transport: wire.connect() }));
28
+ ```
29
+ Other carriers (Colyseus room, WebRTC data channel, your own server) only need `send(msg, to?)`, `on(type, fn)` and `close()`; see the top of
30
+ `modules/net/transports.js`.
31
+ Example: the co-op test page in the engine repository, tests/coop/ (host + two guests in one page, shared chest, shop, plots; open
32
+ /tests/coop/index.html with `npm run dev`).
33
+
34
+ ## 2. Mark the ops friends may request: `net: 'peer'`
35
+ Default deny: a client may only request ops defined with `net: 'peer'`. Everything else is refused with `'notAllowed'`, on the client at once and
36
+ again on the host.
37
+ ```js
38
+ 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')
41
+ can: (e, { chest, item, n = 1 }) => e.inventory.container(chest).has(item, n) || 'empty',
42
+ run: (e, { chest, item, n = 1 }, ctx) => e.inventory.transfer(chest, ctx.actor, item, n),
43
+ });
44
+ engine.ops.define('plot.water', {
45
+ net: 'peer', args: { id: 'id' },
46
+ owner: a => a.id, // the record a.id must have owner === the requesting actor, else 'notOwner'
47
+ run: (e, { id }) => e.world.set(id, { water: (e.world.get(id)?.water ?? 0) + 1 }),
48
+ });
49
+ engine.ops.define('cheat.gold', { args: { n: 'int' }, run: (e, { n }, ctx) => e.inventory.container(ctx.actor).add('gold', n) }); // host only
50
+ ```
51
+ | Mark | Who can run it | Use for |
52
+ |---|---|---|
53
+ | (nothing) | host only | cheats, debug, admin, anything a friend must not trigger |
54
+ | `net: 'peer'` | host, and clients by request | buy, sell, give, take, build, water, talk choices that change state |
55
+ | `net: 'local'` | every machine on its own | ops that only touch this machine (UI, dialogue, camera); peer ops they call are still sent to the host |
56
+
57
+ ## 3. Who is who: actors
58
+ - On the host, a friend is an **actor** id taken from the connection (`'guest-1'`, change with `net({ actorFor: peerId => ... })`), never from the
59
+ message. Ops see it as `ctx.actor`; that is why ops must use `ctx.actor`, not `engine.player`.
60
+ - By default the host gives each friend a world record `{ id: actor, kind: 'player' }` (not saved) and a container with the actor id (their bag).
61
+ `onJoin(e, peer)` / `onLeave(e, peer)` add your own setup (starting gold, spawn point). `avatar: false` turns the defaults off.
62
+ - **Every machine calls itself `'player'`.** A client's own record and bag are `'player'` locally (so characters, inventory windows and interactions
63
+ work unchanged), and the host's own avatar and bag show up as `'host'`. String args equal to `'player'` / `'host'` are translated on the way to the
64
+ host. Record fields that hold actor ids are translated too when listed in `actorFields` (default `['owner']`).
65
+ - Draw other players with one presenter that skips yourself: `engine.world.present('player', { show: r => r.id !== 'player', build: ... })`.
66
+
67
+ ## 4. What is synced
68
+ The host sends a full snapshot when a client joins (or after a lost message), then diffs every `syncEvery` fixed steps (default 3, 20 per second):
69
+ world records, containers, `vars`, and every other save part (quests, clock, sky, weather...) except `random` and `level`. Choose explicitly with
70
+ `sync: ['world', 'containers', 'vars', 'quests']`.
71
+ On a client the mirror is applied at the next fixed step; `world.simulate` does not run there (the host simulates). Other players glide between
72
+ updates (kinds in `interpolate`, default `['player']`). The client moves its own avatar and reports its position; the host clamps it to `maxSpeed`
73
+ (m/s, default 15).
74
+
75
+ ## 5. Write the UI from state, not from run's return value
76
+ 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
77
+ real result comes later:
78
+ ```js
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.code)); }); // after the state it caused
81
+ ```
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
+ events: `net:join` / `net:leave` (host), `net:open` / `net:close` (client). `engine.net.reconnect(webSocket(url, { key }))` reconnects with the same
84
+ actor (read `transport.key` after `open` and keep it, e.g. in localStorage).
85
+
86
+ ## 6. Security notes
87
+ - The host checks, in order: rate (`rate` requests per second per peer, default 20, burst `burst`) -> op exists -> `net: 'peer'` -> args shape
88
+ (always, also in production) -> `owner` -> the op's `can`. Refusals are logged in `engine.ops.recent()` with `source: 'net'` and the actor.
89
+ - `can` is the real gate. Anything a friend must not do (take from someone else's chest, buy without gold) must be refused in `can` or by `owner`; the
90
+ client-side `can` is only for instant feedback and a hacked client can skip it.
91
+ - Ops get plain JSON args; never `eval` or index into functions with them. Return values sent back are plain data.
92
+ - Client guard (dev): on a client, writing shared state anywhere except the host's sync (a UI callback calling `inventory.add`, a module's fixed step)
93
+ prints `[engine] net client changed shared state locally`. Turn it into an op request.
94
+ - The relay has no accounts or TLS; put it behind `wss://` for anything public. The room name is the only secret. Own-avatar movement is client-driven
95
+ (only speed is clamped), which is fine for co-op and not for competitive games.
96
+ - Perf: the host compares JSON of every synced entry each sync. Hundreds of records are fine; for tens of thousands raise `syncEvery` or narrow `sync`.
@@ -0,0 +1,80 @@
1
+ # Terrain: your own generator, digging, raising and painting the ground
2
+
3
+ Requires module `terrain()` (in the `openWorld()` preset). The API list is in `../api/terrain.md`.
4
+
5
+ The engine always does the chunks, streaming, workers, collision and vegetation. It has **no built-in landform**: `terrain()` without a generator is
6
+ flat gray ground at y = 0, with a dev warning. The height and ground type come from your own two functions or a preset, and the player can change the
7
+ ground during play.
8
+
9
+ Flat island (no noise): `terrain({ height: () => 2, shape: { mask: (x, z) => 25 - Math.hypot(x, z) } })`; inside `openWorld` the same object goes under `terrain:`.
10
+
11
+ ## 0. A ready-made generator: the noise preset
12
+ ```js
13
+ import { openWorld, createTerrain } from 'threedog';
14
+ import { terrainPreset, riverAt } from '@threedog/terrain-noise'; // optional package: noise hills, rivers, biomes
15
+ engine.use(openWorld({ camera: 'follow', seed: 7, terrain: terrainPreset({ shape: 'island' }) })); // 'hills' (default) | 'island' | 'canyon' | 'flat'
16
+ const preview = createTerrain({ seed: 7, ...terrainPreset() }); // same heights before the engine starts
17
+ const dry = (x, z) => riverAt(x, z, preview.noise) === 0;
18
+ ```
19
+ Its ground types are `beach snow rock riverbank wetland savanna forest highland meadow`; the lowpoly style pack colors them
20
+ (`style.terrain.biomeColors`), and `terrainStrings` names them for `describe()`. Other options:
21
+ `heightScale mountains rivers riverWidth biomes noise island canyon` (types in the package's `index.d.ts`).
22
+
23
+ ## 1. Your own generator
24
+ ```js
25
+ import { terrain } from 'threedog';
26
+ terrain({
27
+ // meters at (x, z); n = { fbm(x, z, octaves), noise(x, z), hash(x, z, salt), seed, waterLevel, params }
28
+ height: (x, z, n) => 4 + 30 * n.fbm(x * 0.004, z * 0.004) - 8 * Math.abs(Math.sin(x * 0.01)),
29
+ // a ground type name (null = 'default'); its colors come from biomeColors[type]
30
+ groundType: (x, z, h, slope) => slope > 0.8 ? 'rock' : h < 1 ? 'beach' : 'grass',
31
+ waterLevel: 0, // a sea at y = 0; leave it out for no water (the default is -Infinity; terrainPreset() sets 0)
32
+ });
33
+ ```
34
+ The terrain moves the camera's far plane out to its view distance but leaves the fog to the game; `terrain({ viewFog: true })` makes the fog end where
35
+ the chunks end so the edge fades out (`openWorld()` turns it on).
36
+ Both functions run in workers, so they are **pure**: they see only their parameters and globals like `Math`. Reading a variable from outside
37
+ (`(x, z) => x * scale`) throws at `terrain()` and names the variable; put the number inside the function, or pass settings as plain data in
38
+ `terrain({ params })` and read them as `n.params`. `flatten` plots still apply on top. A new type name needs colors:
39
+ `terrain({ biomeColors: { lava: ['lavaA', 'lavaB'] }, colors: { lavaA: 0xd04010, lavaB: 0xa03008 } })`.
40
+
41
+ ## 2. Changing the ground: `engine.terrain.edit`
42
+ ```js
43
+ const at = { x: 12, z: 20 };
44
+ engine.ops.define('ground.dig', { args: { at: 'position' }, run(e, a) { e.terrain?.edit(a.at, { radius: 3, lower: 1.5 }); } });
45
+ engine.ops.define('ground.level', { args: { at: 'position' }, run(e, a) {
46
+ e.terrain?.edit(a.at, { shape: 'square', radius: 6, flatten: e.surface(a.at) }); // a flat foundation at the height of its center
47
+ } });
48
+ engine.ops.run('ground.dig', { at });
49
+ ```
50
+ - One of `raise` / `lower` (meters) / `flatten` (target height), and / or `paint` (a ground type, `null` gives back the generated type). `shape` is
51
+ `'circle'` (default) or `'square'`, `radius` in meters.
52
+ - Edits snap to the terrain grid: heights to grid points, paint to whole cells of `engine.terrain.cellSize` meters (`chunkSize / resolution`, default
53
+ 4). A shape smaller than a cell takes the nearest one. For finer paint use a higher `terrain({ resolution })` (64 gives 1 m cells); per-cell
54
+ gameplay state belongs in a grid layer (section 3).
55
+ - It is saved gameplay state: call it from an op or a fixed step (in development a call from a plain button handler warns).
56
+ - Everything follows at once: the mesh, `engine.surface / slope / groundType`, character and physics collision, path rasters (`ground:change` event),
57
+ and vegetation (trees and grass on edited cells are removed). Edits are saved with the save, and a chunk that unloads and comes back is generated
58
+ edited (workers get the edits, so threads on and off build the same chunk).
59
+
60
+ ## 3. Farming soil and ground types
61
+ Gameplay soil state (tilled, watered, crops) is **not** terrain paint: keep it in a grid layer (`grids()`, `farm.layer('soil')`), which is per cell,
62
+ saved, works on levels and indoors, and draws its own tiles. See `recipes/29-grid.md` section 3.
63
+ `terrain.edit({ paint })` is for landscape ground types: roads, sand, a coarse visual layer (a painted type with no color is gray; the game names its
64
+ types and gives them colors in its own style object: `terrain.colors` + `terrain.biomeColors`). `engine.groundType(pos)` reads the painted type
65
+ (footsteps, `can` checks):
66
+ ```js
67
+ engine.ops.define('path.sand', { args: { at: 'position' }, // a sandy path; a new type name needs biomeColors (section 1)
68
+ run(e, a) { e.terrain?.edit(a.at, { shape: 'square', radius: (e.terrain.cellSize ?? 4) / 2, paint: 'beach' }); } });
69
+ ```
70
+
71
+ ## 4. Height and snapping
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
+ raycast the terrain for this: the height function is exact and works before the chunk has a mesh.
74
+
75
+ Look open points (color map shading, triangle cut, normals, bounds margin): `37-terrain-look-hooks.md`.
76
+
77
+ ## 5. Where the ground ends: `shape`
78
+
79
+ `terrain({ shape: { mask, edge, side, bottom } })` keeps ground only where `mask > 0` (an island, a floating rock): off it `engine.surface` is
80
+ `-Infinity` and `engine.ground.has(x, z)` is false, and falls emit `terrain:void`. Without `shape` nothing changes. See `42-terrain-shape.md`.
@@ -0,0 +1,87 @@
1
+ # Grid placement: farming, furniture, crates, building
2
+
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
+ `../api/grids.md`.
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**. Farming soil always goes here; `terrain.edit({ paint })` is only for landscape ground types (roads, sand),
7
+ see `28-terrain.md`.
8
+ Works on any ground: procedural terrain, a Blender level, an indoor floor. Heights come from `engine.surface`, ground types from `engine.groundType`.
9
+
10
+ ## 1. Grids and items
11
+ ```js
12
+ import { grids, toast } from 'threedog';
13
+ engine.use(grids());
14
+ const farm = engine.grids.add('farm', { cell: 1, origin: [0, 0], size: [16, 12] }); // several grids may exist
15
+ const room = engine.grids.add('room', { cell: 0.5, origin: [-3, -3], size: [12, 12], zone: 'house' });
16
+
17
+ engine.grids.define('crop', { layer: { soil: 'tilled' }, fields: { plantedAt: 0 } }); // only on cells whose soil layer has tilled
18
+ engine.grids.define('bed', { size: [2, 1], kind: 'furniture', fields: { model: 'bed' } }); // 2x1 cells; world record kind 'furniture'
19
+ engine.grids.define('shed', { size: [3, 2], ground: ['grass', 'dirt'], flat: 0.2 }); // engine.groundType must match; max 0.2 m height difference
20
+ engine.grids.define('crate', { size: [1, 1], can: (e, { cell }) => (cell[1] > 2 ? true : 'tooCloseToRoad') }); // your own rule
21
+ ```
22
+ Coordinates: `farm.toCell(pos)` -> `[i, j]`, `farm.toWorld(cell, size?, rotation?)` -> footprint center on the ground, `farm.snap(pos)`,
23
+ `farm.inside(cell)`, `farm.footprint(cell, size, rotation)`.
24
+ 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
+
26
+ ## 2. Place, pick up, move: always ops
27
+ ```js
28
+ engine.ops.run('grid.place', { grid: 'farm', item: 'bed', cell: [4, 4], rotation: 1 }); // { ok, value: record id } or { ok: false, reason }
29
+ 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
+ engine.ops.run('grid.remove', { id: 'furniture-3' }); // value { item, kind }: put it back in the bag yourself
31
+ farm.can('crop', [3, 5]); // ask only: true or a reason
32
+ ```
33
+ Reasons: `outOfBounds` `occupied` `wrongGround` `notFlat` `not<Field>` (from a layer rule: `notTilled`) `noGrid` `idTaken` `unknown` `notPlaced`, or
34
+ your `can` reason.
35
+ Show them through i18n (`engine.t('grid.' + r.reason)`); `engine.explain({ grid: { grid: 'farm', item: 'bed', cell: [4, 4] } }).text` says which cell
36
+ and which record is in the way.
37
+ A placed record looks like `{ id, kind, position, rot, ...fields, grid: { id: 'farm', cell: [4, 4], size: [2, 1], rotation: 1, item: 'bed' } }`. Give
38
+ it a look with `world.present(kind, ...)` as usual (`rot` is the yaw in radians).
39
+ To build several things at once, call `grid.place` from your own op (`build.wall`), so each placement is still checked.
40
+
41
+ **Occupancy is not saved separately.** `farm.at(cell)` / `farm.area(cell, size)` read an index built from the world records' `grid` field, so a save
42
+ holds every placed thing once and can never disagree with itself.
43
+ **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
+ ops guard; a record added by hand that overlaps another is reported and the cell stays with the first.
45
+
46
+ ## 3. Layers: per-cell state (Stardew-style soil)
47
+ ```js
48
+ const soil = farm.layer('soil'); // created on first use; saved with the game (only cells that differ from content)
49
+ engine.ops.define('farm.till', { args: { cell: 'any' },
50
+ can: (e, { cell }) => (!farm.inside(cell) ? 'outOfBounds' : farm.at(cell) ? 'occupied' : true),
51
+ run: (e, { cell }) => soil.set(cell, { tilled: true }) });
52
+ engine.ops.define('farm.water', { args: { cell: 'any' },
53
+ can: (e, { cell }) => (soil.get(cell)?.tilled ? true : 'notTilled'),
54
+ run: (e, { cell }) => soil.set(cell, { watered: true }) });
55
+ engine.ops.define('farm.dry', { run: () => soil.updateAll(d => { delete d.watered; }) }); // bulk change; return null from fn to clear a cell
56
+ engine.sky.at('06:00', () => engine.ops.run('farm.dry')); // daily reset is the game's job
57
+ ```
58
+ `get(cell)`, `set(cell, patch)` (merge; a field set to null is deleted), `clear(cell)`, `query(cell?, size?)` -> `[{ cell, data }]`, `updateAll(fn)`, `count`.
59
+ 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
+ Cells that exist from the start go in content: `content/grids.js` <!-- r18-ignore-line -->
61
+ `farm: { cell: 1, origin: [0, 0], size: [16, 12], layers: { soil: [[3, 5, { tilled: true }]] } }` <!-- r18-ignore-line -->
62
+ (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
+
64
+ **Tiles.** The game gives a layer its colors: `farm.layer('soil', { tiles: { look: d => d.watered ? 0x5b3d2a : d.tilled ? 0x8a6243 : null } })`
65
+ (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
+ height (slopes, ramps, level meshes).
67
+ `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`; `farm.layer('soil', { tiles: false })` turns them off; `{ tiles: true }` draws every non-empty cell gray; `lift` raises them; `{ tiles:
68
+ (engine, layer) => ({ update(cells), dispose() }) }` is your own view. Options are read when the layer is first created.
69
+
70
+ ## 4. Preview
71
+ ```js
72
+ engine.input.define('place', ['Mouse0'], 'Place'); // gameplay reads input actions, not pointer.clicked (recipe 26)
73
+ const pv = engine.grids.preview({ grid: 'farm', item: 'bed', ...presets.keys.gridRotate }); // under the pointer; from: 'front' = the cell in front of the player
74
+ engine.onFrame(() => {
75
+ if (engine.input.pressed('place')) { const r = pv.place(); if (!r.ok) toast(engine, engine.t('grid.' + r.reason)); }
76
+ });
77
+ pv.remove(); // leave build mode
78
+ ```
79
+ The engine binds no key: `...presets.keys.gridRotate` (or `rotateKeys: ['KeyR']`) defines the action `rotate` on R, or bind that action yourself with
80
+ `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`
82
+ are readable every frame.
83
+ Colors come from `style.grid.ok / bad / previewOpacity`. `look: false` hides the default box; `look: (engine) => ({ update(view), hide(), dispose()
84
+ })` draws your own (`view = { cells, center, size, rotation, ok, reason }`).
85
+
86
+ ## 5. Verify
87
+ `engine.describe().grids` -> `{ farm: { occupied, items: { bed: 1 }, layers: { soil: 30 } } }`. Tests: `npx threedog test "grid:"`.