threedog 0.7.0 → 1.0.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 (593) hide show
  1. package/CHANGELOG.md +411 -1
  2. package/README.md +8 -11
  3. package/core/{Animator.js → assets/Animator.js} +30 -18
  4. package/core/{Assets.js → assets/Assets.js} +131 -56
  5. package/core/{Baked.js → assets/Baked.js} +4 -4
  6. package/core/assets/assetEntry.js +302 -0
  7. package/core/{assetHot.js → assets/assetHot.js} +9 -7
  8. package/core/{assetLoad.js → assets/assetLoad.js} +55 -16
  9. package/core/assets/assetLod.js +113 -0
  10. package/core/{assetManifest.js → assets/assetManifest.js} +19 -11
  11. package/core/{assetReport.js → assets/assetReport.js} +7 -14
  12. package/core/{namedModel.js → assets/namedModel.js} +17 -13
  13. package/core/{Audio.js → audio/Audio.js} +47 -25
  14. package/core/{audioRules.js → audio/audioRules.js} +8 -5
  15. package/core/{audioVoice.js → audio/audioVoice.js} +17 -30
  16. package/core/{Events.js → base/Events.js} +3 -3
  17. package/core/{I18n.js → base/I18n.js} +15 -12
  18. package/core/{Random.js → base/Random.js} +7 -4
  19. package/core/{Vars.js → base/Vars.js} +14 -4
  20. package/core/{easing.js → base/easing.js} +1 -1
  21. package/core/{errorCodes.js → base/errorCodes.js} +151 -125
  22. package/core/{errorHints.js → base/errorHints.js} +17 -10
  23. package/core/{errors.js → base/errors.js} +12 -10
  24. package/core/{events.generated.js → base/events.generated.js} +11 -0
  25. package/core/base/follows.js +26 -0
  26. package/core/base/math.js +66 -0
  27. package/core/{params.js → base/params.js} +5 -6
  28. package/core/base/saveValues.js +81 -0
  29. package/core/base/sections.js +97 -0
  30. package/core/base/spelling.js +32 -0
  31. package/core/base/util.js +32 -0
  32. package/core/{validate.js → base/validate.js} +34 -34
  33. package/core/{Engine.js → engine/Engine.js} +137 -91
  34. package/core/{Loading.js → engine/Loading.js} +34 -5
  35. package/core/{copies.js → engine/copies.js} +4 -4
  36. package/core/{headlessLoad.js → engine/headlessLoad.js} +32 -15
  37. package/core/{lifecycle.js → engine/lifecycle.js} +41 -34
  38. package/core/{loop.js → engine/loop.js} +88 -49
  39. package/core/engine/moduleSlots.js +176 -0
  40. package/core/{moduleTypes.js → engine/moduleTypes.js} +26 -14
  41. package/core/engine/modules.js +503 -0
  42. package/core/{page.js → engine/page.js} +59 -29
  43. package/core/{plugins.js → engine/plugins.js} +21 -12
  44. package/core/{services.js → engine/services.js} +50 -40
  45. package/core/{startup.js → engine/startup.js} +66 -54
  46. package/core/{Input.js → input/Input.js} +67 -39
  47. package/core/{inputContext.js → input/inputContext.js} +14 -5
  48. package/core/input/inputKeyboard.js +39 -0
  49. package/core/{inputPad.js → input/inputPad.js} +24 -3
  50. package/core/{inputPointer.js → input/inputPointer.js} +11 -3
  51. package/core/input/inputSeat.js +66 -0
  52. package/core/{inputTouch.js → input/inputTouch.js} +24 -7
  53. package/core/{Budget.js → inspect/Budget.js} +21 -20
  54. package/core/{DebugOverrides.js → inspect/DebugOverrides.js} +43 -18
  55. package/core/{Describe.js → inspect/Describe.js} +34 -26
  56. package/core/{Inspect.js → inspect/Inspect.js} +39 -10
  57. package/core/{InspectMaterials.js → inspect/InspectMaterials.js} +7 -8
  58. package/core/{InspectPerf.js → inspect/InspectPerf.js} +19 -13
  59. package/core/{InspectScene.js → inspect/InspectScene.js} +8 -5
  60. package/core/{MaterialInfo.js → inspect/MaterialInfo.js} +3 -2
  61. package/core/{UrlState.js → inspect/UrlState.js} +60 -24
  62. package/core/{catalog.js → inspect/catalog.js} +15 -8
  63. package/core/{checks.js → inspect/checks.js} +7 -5
  64. package/core/{debugView.js → inspect/debugView.js} +4 -4
  65. package/core/{describeRender.js → inspect/describeRender.js} +24 -22
  66. package/core/{describeText.js → inspect/describeText.js} +17 -8
  67. package/core/inspect/geometryWatch.js +38 -0
  68. package/core/{lightWatch.js → inspect/lightWatch.js} +8 -8
  69. package/core/inspect/metadata.generated.js +4140 -0
  70. package/core/{pictureWriters.js → inspect/pictureWriters.js} +130 -47
  71. package/core/{shaderCost.js → inspect/shaderCost.js} +1 -1
  72. package/core/inspect/toolDoor.js +21 -0
  73. package/core/inspect/valueHistory.js +35 -0
  74. package/core/{Ops.js → ops/Ops.js} +44 -14
  75. package/core/{control.js → ops/control.js} +57 -31
  76. package/core/ops/holds.js +140 -0
  77. package/core/{opsAtomic.js → ops/opsAtomic.js} +18 -5
  78. package/core/{opsCheck.js → ops/opsCheck.js} +11 -10
  79. package/core/{opsFail.js → ops/opsFail.js} +5 -7
  80. package/core/{opsGuard.js → ops/opsGuard.js} +3 -3
  81. package/core/{opsRun.js → ops/opsRun.js} +9 -6
  82. package/core/{owned.js → ops/owned.js} +33 -19
  83. package/core/{sharedPoint.js → ops/sharedPoint.js} +13 -16
  84. package/core/{stackFrames.js → ops/stackFrames.js} +2 -2
  85. package/core/{stacks.js → ops/stacks.js} +34 -15
  86. package/core/{wrap.js → ops/wrap.js} +8 -6
  87. package/core/{SaveStore.js → saves/SaveStore.js} +53 -27
  88. package/core/{Saves.js → saves/Saves.js} +171 -54
  89. package/core/saves/saveApply.js +312 -0
  90. package/core/{saveFiles.js → saves/saveFiles.js} +45 -38
  91. package/core/{saveVersions.js → saves/saveVersions.js} +24 -23
  92. package/core/saves/session.js +231 -0
  93. package/core/saves/stateReplace.js +184 -0
  94. package/core/{Rays.js → scene/Rays.js} +44 -30
  95. package/core/{Views.js → scene/Views.js} +16 -8
  96. package/core/{adaptive.js → scene/adaptive.js} +19 -9
  97. package/core/{canvasBox.js → scene/canvasBox.js} +4 -3
  98. package/core/scene/compositeGround.js +72 -0
  99. package/core/scene/floor.js +17 -0
  100. package/core/{gameLights.js → scene/gameLights.js} +17 -7
  101. package/core/{grayMap.js → scene/grayMap.js} +8 -2
  102. package/core/{grid.js → scene/grid.js} +6 -4
  103. package/core/{gridLoad.js → scene/gridLoad.js} +1 -1
  104. package/core/scene/ground.contract.js +14 -0
  105. package/core/scene/ground.js +139 -0
  106. package/core/{movement.js → scene/movement.js} +3 -3
  107. package/core/{pictureSlots.js → scene/pictureSlots.js} +2 -2
  108. package/core/scene/pixel.js +154 -0
  109. package/core/scene/pixelRatio.js +167 -0
  110. package/core/{sceneDelta.js → scene/sceneDelta.js} +5 -5
  111. package/core/{sceneMethods.js → scene/sceneMethods.js} +43 -15
  112. package/core/scene/stepPoses.js +60 -0
  113. package/core/{targeting.js → scene/targeting.js} +4 -5
  114. package/core/{thingExplain.js → scene/thingExplain.js} +7 -6
  115. package/core/{thingOps.js → scene/thingOps.js} +25 -16
  116. package/core/{things.js → scene/things.js} +18 -5
  117. package/core/{threePatches.js → scene/threePatches.js} +1 -1
  118. package/core/{tier.js → scene/tier.js} +10 -0
  119. package/core/scene/view.js +161 -0
  120. package/core/{Batching.js → stream/Batching.js} +85 -28
  121. package/core/{Stream.js → stream/Stream.js} +80 -38
  122. package/core/{batchGroups.js → stream/batchGroups.js} +11 -9
  123. package/core/{chunkStream.js → stream/chunkStream.js} +40 -0
  124. package/core/{scatter.js → stream/scatter.js} +7 -4
  125. package/core/{streamSources.js → stream/streamSources.js} +14 -8
  126. package/core/{Commits.js → threads/Commits.js} +17 -11
  127. package/core/{Jobs.js → threads/Jobs.js} +25 -13
  128. package/core/{Threads.js → threads/Threads.js} +21 -18
  129. package/core/{threadPure.js → threads/threadPure.js} +7 -5
  130. package/core/{threadServe.js → threads/threadServe.js} +3 -3
  131. package/core/{Clock.js → time/Clock.js} +20 -11
  132. package/core/{dayTime.js → time/dayTime.js} +5 -1
  133. package/core/{skip.js → time/skip.js} +28 -21
  134. package/core/{time.js → time/time.js} +32 -20
  135. package/core/{uiClock.js → time/uiClock.js} +4 -4
  136. package/docs/AI.md +92 -72
  137. package/docs/API.md +33 -28
  138. package/docs/CODEMAP.md +121 -200
  139. package/docs/COMMANDS.md +77 -70
  140. package/docs/CONVENTIONS.md +167 -24
  141. package/docs/MIGRATING-0.8.md +171 -0
  142. package/docs/MIGRATING-1.0.md +101 -0
  143. package/docs/THREE.md +140 -38
  144. package/docs/api/assets.md +12 -13
  145. package/docs/api/audio.md +6 -5
  146. package/docs/api/budget.md +4 -4
  147. package/docs/api/calendar.md +10 -11
  148. package/docs/api/cameraRig.md +32 -29
  149. package/docs/api/characters.md +35 -24
  150. package/docs/api/clock.md +1 -1
  151. package/docs/api/collider3d.md +9 -0
  152. package/docs/api/collision.md +12 -9
  153. package/docs/api/content.md +18 -17
  154. package/docs/api/dialogue.md +5 -4
  155. package/docs/api/engine.md +58 -54
  156. package/docs/api/events.md +17 -6
  157. package/docs/api/flow.md +1 -1
  158. package/docs/api/grids.md +1 -1
  159. package/docs/api/ground.md +6 -7
  160. package/docs/api/hud.md +2 -2
  161. package/docs/api/i18n.md +6 -6
  162. package/docs/api/input.md +9 -8
  163. package/docs/api/interactions.md +5 -5
  164. package/docs/api/inventory.md +10 -10
  165. package/docs/api/jobs.md +5 -5
  166. package/docs/api/level.md +10 -9
  167. package/docs/api/lightPool.md +1 -6
  168. package/docs/api/music.md +3 -3
  169. package/docs/api/nav.md +14 -12
  170. package/docs/api/openWorld.md +1 -1
  171. package/docs/api/particles.md +10 -7
  172. package/docs/api/photo.md +4 -2
  173. package/docs/api/pickups.md +3 -3
  174. package/docs/api/post.md +21 -5
  175. package/docs/api/quests.md +7 -5
  176. package/docs/api/rays.md +7 -7
  177. package/docs/api/rigid.md +29 -19
  178. package/docs/api/saves.md +13 -11
  179. package/docs/api/settings.md +9 -8
  180. package/docs/api/sky.md +8 -7
  181. package/docs/api/stream.md +8 -9
  182. package/docs/api/swarm.md +34 -0
  183. package/docs/api/terrain.md +6 -8
  184. package/docs/api/terrainDraw.md +2 -2
  185. package/docs/api/timeline.md +4 -4
  186. package/docs/api/tools.md +27 -22
  187. package/docs/api/triggers.md +2 -0
  188. package/docs/api/vars.md +1 -1
  189. package/docs/api/vegetation.md +4 -3
  190. package/docs/api/vegetationDraw.md +2 -2
  191. package/docs/api/water.md +7 -3
  192. package/docs/api/weather.md +27 -12
  193. package/docs/api/weatherDraw.md +4 -4
  194. package/docs/api/world.md +6 -6
  195. package/docs/recipes/01-new-game.md +28 -43
  196. package/docs/recipes/02-npc.md +21 -23
  197. package/docs/recipes/03-items-pickups.md +37 -53
  198. package/docs/recipes/04-quests.md +5 -4
  199. package/docs/recipes/05-props-bake.md +34 -44
  200. package/docs/recipes/06-clock-events.md +31 -22
  201. package/docs/recipes/07-flow-scenes-pause.md +30 -32
  202. package/docs/recipes/08-weather-sky.md +91 -37
  203. package/docs/recipes/09-materials-lights-models.md +25 -39
  204. package/docs/recipes/10-blender-level.md +22 -11
  205. package/docs/recipes/11-vehicles.md +44 -24
  206. package/docs/recipes/12-navmesh.md +60 -15
  207. package/docs/recipes/13-animation.md +70 -22
  208. package/docs/recipes/14-custom-module.md +33 -20
  209. package/docs/recipes/15-perf.md +51 -28
  210. package/docs/recipes/16-dev-bridge.md +39 -58
  211. package/docs/recipes/18-world.md +49 -28
  212. package/docs/recipes/19-shooting-picking.md +7 -4
  213. package/docs/recipes/20-content-actions-save.md +55 -40
  214. package/docs/recipes/21-camera.md +47 -25
  215. package/docs/recipes/22-shop-gold.md +21 -16
  216. package/docs/recipes/23-ops.md +28 -24
  217. package/docs/recipes/26-ui-parts.md +25 -14
  218. package/docs/recipes/27-net.md +3 -5
  219. package/docs/recipes/28-terrain.md +119 -23
  220. package/docs/recipes/29-grid.md +3 -3
  221. package/docs/recipes/30-templates.md +63 -30
  222. package/docs/recipes/31-audio.md +7 -7
  223. package/docs/recipes/32-action-game.md +21 -11
  224. package/docs/recipes/33-stream-sources.md +6 -3
  225. package/docs/recipes/34-environment-lighting.md +72 -25
  226. package/docs/recipes/35-picture-from-reference.md +20 -23
  227. package/docs/recipes/36-ground-plants.md +106 -0
  228. package/docs/recipes/40-scene.md +18 -21
  229. package/docs/recipes/43-shader-patches-surfaces.md +27 -48
  230. package/docs/recipes/44-water-weather-hooks.md +56 -50
  231. package/docs/recipes/45-cascaded-shadows.md +41 -20
  232. package/docs/recipes/46-blender-art-route.md +9 -10
  233. package/docs/recipes/49-game-module-contract.md +7 -6
  234. package/docs/recipes/50-own-renderer.md +3 -2
  235. package/docs/recipes/51-capability-catalog.md +14 -8
  236. package/docs/recipes/52-around-the-picture.md +56 -100
  237. package/docs/recipes/53-ground-up-close.md +61 -24
  238. package/docs/recipes/55-mods-time-wrap.md +17 -20
  239. package/docs/recipes/56-webgpu-tsl.md +28 -15
  240. package/docs/recipes/57-control.md +39 -12
  241. package/docs/recipes/58-input.md +15 -2
  242. package/docs/recipes/59-depth-post-effects.md +1 -1
  243. package/docs/recipes/60-judge-the-picture.md +30 -25
  244. package/docs/recipes/62-picture-code.md +129 -39
  245. package/docs/recipes/63-third-person-start.md +19 -5
  246. package/docs/recipes/64-particles.md +54 -5
  247. package/docs/recipes/65-swarm.md +140 -0
  248. package/docs/recipes/66-common-tasks.md +313 -0
  249. package/examples/action/.threedog/content-index.json +1 -1
  250. package/examples/action/GAMEMAP.md +5 -5
  251. package/examples/perf-island/.threedog/content-index.json +1 -0
  252. package/examples/{sheepisland → perf-island}/GAMEMAP.md +15 -14
  253. package/examples/{sheepisland → perf-island}/assets.js +1 -1
  254. package/examples/{sheepisland → perf-island}/main.js +8 -8
  255. package/examples/{sheepisland → perf-island}/models.js +1 -1
  256. package/examples/{sheepisland → perf-island}/params.js +1 -1
  257. package/examples/{sheepisland → perf-island}/picture/index.js +1 -1
  258. package/examples/{sheepisland → perf-island}/picture/palette.js +2 -2
  259. package/examples/{sheepisland → perf-island}/views.js +1 -1
  260. package/examples/plain-picture/GAMEMAP.md +4 -1
  261. package/examples/rc2d/GAMEMAP.md +4 -3
  262. package/examples/rc2d/main.js +1 -3
  263. package/examples/rc2d/rc2d.js +1 -1
  264. package/examples/styletest/.threedog/content-index.json +1 -1
  265. package/examples/styletest/GAMEMAP.md +6 -5
  266. package/examples/techniques/contact-shadows/contactShadows.js +1 -1
  267. package/examples/techniques/contact-shadows/main.js +1 -1
  268. package/examples/techniques/interior-light/main.js +1 -1
  269. package/examples/techniques/modular-building/README.md +7 -6
  270. package/examples/techniques/outlines-and-rim/picture/post.js +1 -1
  271. package/examples/techniques/procedural-animation/README.md +1 -1
  272. package/examples/webgpu-tsl/GAMEMAP.md +2 -1
  273. package/examples/world/.threedog/content-index.json +1 -1
  274. package/examples/world/GAMEMAP.md +9 -7
  275. package/examples/world/main.js +3 -3
  276. package/examples/world/picture/sky.js +1 -1
  277. package/index.d.ts +16 -12
  278. package/index.js +53 -32
  279. package/llms.txt +11 -14
  280. package/modules/ambience/Ambience.js +16 -11
  281. package/modules/calendar/Calendar.js +19 -19
  282. package/modules/calendar/index.js +18 -16
  283. package/modules/calendar/schedule.js +11 -6
  284. package/modules/calendar/seasons.js +7 -7
  285. package/modules/camera/FirstPersonCamera.js +5 -5
  286. package/modules/camera/FixedCamera.js +43 -30
  287. package/modules/camera/FollowCamera.js +24 -15
  288. package/modules/camera/RtsCamera.js +12 -11
  289. package/modules/camera/common.js +72 -37
  290. package/modules/camera/contract.js +1 -0
  291. package/modules/camera/pixelSnap.js +62 -0
  292. package/modules/characters/Character.js +166 -70
  293. package/modules/characters/NPC.js +84 -44
  294. package/modules/characters/assetModel.js +16 -12
  295. package/modules/characters/astar.js +48 -27
  296. package/modules/characters/behaviors.js +4 -5
  297. package/modules/characters/character.contract.js +21 -0
  298. package/modules/characters/contract.js +17 -3
  299. package/modules/characters/index.js +240 -226
  300. package/modules/characters/moveHelpers.js +88 -12
  301. package/modules/characters/mover.contract.js +14 -0
  302. package/modules/characters/movers/common.js +22 -18
  303. package/modules/characters/movers/manual.js +1 -1
  304. package/modules/characters/movers/rapier.js +18 -10
  305. package/modules/characters/movers/simple.js +26 -13
  306. package/modules/characters/movers/support.js +24 -13
  307. package/modules/characters/npcAvoid.js +19 -16
  308. package/modules/characters/npcSim.js +88 -32
  309. package/modules/characters/npcView.js +19 -11
  310. package/modules/characters/pathAsync.js +81 -29
  311. package/modules/characters/pathJob.js +38 -21
  312. package/modules/characters/pathWorker.js +1 -1
  313. package/modules/characters/player.js +120 -0
  314. package/modules/characters/playerStrings.js +2 -2
  315. package/modules/characters/proceduralRig.js +2 -2
  316. package/modules/characters/seat.js +56 -0
  317. package/modules/characters/useModel.js +3 -3
  318. package/modules/characters/vehicle.contract.js +8 -5
  319. package/modules/characters/walkTo.js +40 -33
  320. package/modules/collision/Collision.js +69 -45
  321. package/modules/collision/contract.js +15 -0
  322. package/modules/collision/grid.js +6 -1
  323. package/modules/content/explain.js +2 -3
  324. package/modules/content/fields.js +24 -3
  325. package/modules/content/ids.js +5 -3
  326. package/modules/content/index.js +132 -114
  327. package/modules/content/loader.js +117 -140
  328. package/modules/content/markers.js +25 -0
  329. package/modules/content/models.js +54 -17
  330. package/modules/content/packs.js +5 -4
  331. package/modules/content/parts.js +2 -2
  332. package/modules/content/places.js +36 -0
  333. package/modules/content/props.js +22 -17
  334. package/modules/content/rules.js +47 -61
  335. package/modules/content/stages.js +7 -7
  336. package/modules/content/templates.js +80 -49
  337. package/modules/content/words.js +47 -0
  338. package/modules/debug/DebugPanel.js +14 -45
  339. package/modules/flow/contract.js +2 -1
  340. package/modules/flow/index.js +30 -16
  341. package/modules/gameplay/Container.js +17 -13
  342. package/modules/gameplay/Containers.js +23 -6
  343. package/modules/gameplay/Dialogue.js +93 -34
  344. package/modules/gameplay/Interactions.js +93 -51
  345. package/modules/gameplay/Inventory.js +64 -22
  346. package/modules/gameplay/Quests.js +146 -30
  347. package/modules/gameplay/boxOps.js +8 -1
  348. package/modules/gameplay/dialogueBubbles.js +16 -12
  349. package/modules/gameplay/inventoryOps.js +11 -8
  350. package/modules/gameplay/pickups.js +63 -37
  351. package/modules/gameplay/questLog.js +4 -2
  352. package/modules/gameplay/questSave.js +9 -4
  353. package/modules/gameplay/quests.contract.js +1 -1
  354. package/modules/grid/Grid.js +2 -2
  355. package/modules/grid/Layer.js +12 -8
  356. package/modules/grid/index.js +28 -23
  357. package/modules/grid/ops.js +43 -46
  358. package/modules/grid/preview.js +7 -7
  359. package/modules/grid/tiles.js +6 -6
  360. package/modules/hlod/index.js +42 -57
  361. package/modules/hud/index.js +22 -14
  362. package/modules/hud/parts.js +8 -8
  363. package/modules/level/contract.js +16 -0
  364. package/modules/level/heightfield.js +29 -31
  365. package/modules/level/index.js +113 -161
  366. package/modules/level/load.js +196 -0
  367. package/modules/level/meshes.js +65 -0
  368. package/modules/level/nodes.js +40 -23
  369. package/modules/lights/index.js +33 -183
  370. package/modules/lights/slots.js +93 -0
  371. package/modules/lights/sources.js +90 -0
  372. package/modules/music/Music.js +34 -28
  373. package/modules/music/rules.js +1 -1
  374. package/modules/nav/contract.js +16 -0
  375. package/modules/nav/index.js +180 -49
  376. package/modules/nav/navPath.js +45 -10
  377. package/modules/net/Client.js +7 -7
  378. package/modules/net/Host.js +7 -7
  379. package/modules/net/Net.js +1 -1
  380. package/modules/net/index.js +6 -5
  381. package/modules/net/sync.js +2 -2
  382. package/modules/net/transports.js +2 -2
  383. package/modules/particles/Particles.js +95 -29
  384. package/modules/particles/effect.js +86 -32
  385. package/modules/particles/shaders.js +19 -1
  386. package/modules/photo/Photo.js +23 -23
  387. package/modules/rigid/RigidBodies.js +255 -89
  388. package/modules/rigid/Vehicles.js +17 -8
  389. package/modules/rigid/collider3d.contract.js +26 -0
  390. package/modules/rigid/ragdoll.js +298 -0
  391. package/modules/rigid/ragdollBones.js +209 -0
  392. package/modules/rigid/refresh.js +10 -0
  393. package/modules/rigid/sync.js +51 -20
  394. package/modules/settings/Settings.js +177 -61
  395. package/modules/settings/apply.js +20 -13
  396. package/modules/settings/sections.js +19 -14
  397. package/modules/settings/strings.js +2 -2
  398. package/modules/settings/view.js +3 -3
  399. package/modules/sky/Sky.js +29 -22
  400. package/modules/sky/clouds.js +7 -7
  401. package/modules/sky/dome.js +33 -20
  402. package/modules/sky/domeLayers.js +9 -9
  403. package/modules/sky/environment.js +6 -6
  404. package/modules/sky/frame.js +19 -10
  405. package/modules/sky/season.js +7 -1
  406. package/modules/sky/shader.js +24 -25
  407. package/modules/sky/skyModule.js +17 -28
  408. package/modules/sky/tint.js +1 -1
  409. package/modules/swarm/Swarm.js +356 -0
  410. package/modules/swarm/draw.js +68 -0
  411. package/modules/swarm/grid.js +63 -0
  412. package/modules/terrain/ChunkManager.js +71 -59
  413. package/modules/terrain/chunkQueries.js +7 -24
  414. package/modules/terrain/chunkWorker.js +1 -1
  415. package/modules/terrain/draw.js +14 -11
  416. package/modules/terrain/index.js +42 -42
  417. package/modules/terrain/terrainColorMap.js +6 -3
  418. package/modules/terrain/terrainDefaults.js +2 -1
  419. package/modules/terrain/terrainEdit.js +45 -29
  420. package/modules/terrain/terrainGen.js +19 -12
  421. package/modules/terrain/terrainIsland.js +2 -2
  422. package/modules/terrain/terrainMesh.js +7 -6
  423. package/modules/terrain/terrainShape.js +8 -10
  424. package/modules/terrain/terrainShapeMain.js +3 -3
  425. package/modules/timeline/Timeline.js +83 -43
  426. package/modules/timeline/Tween.js +25 -19
  427. package/modules/timeline/shots.js +24 -17
  428. package/modules/triggers/index.js +95 -28
  429. package/modules/vegetation/Vegetation.js +34 -26
  430. package/modules/vegetation/densityMap.js +4 -7
  431. package/modules/vegetation/draw.js +39 -18
  432. package/modules/vegetation/groundChunks.js +21 -38
  433. package/modules/vegetation/index.js +37 -12
  434. package/modules/vegetation/modelGeometry.js +3 -6
  435. package/modules/vegetation/nearFade.js +1 -1
  436. package/modules/water/Water.js +20 -16
  437. package/modules/water/surface.js +3 -3
  438. package/modules/weather/Weather.js +52 -40
  439. package/modules/weather/particles.js +8 -8
  440. package/modules/weather/weatherDraw.js +28 -23
  441. package/modules/world/World.js +28 -15
  442. package/modules/world/explain.js +1 -1
  443. package/modules/world/index.js +30 -17
  444. package/modules/world/persist.js +90 -27
  445. package/modules/world/pos.js +5 -5
  446. package/modules/world/records.js +37 -11
  447. package/modules/world/sim.js +78 -27
  448. package/modules/world/simFar.js +2 -2
  449. package/modules/world/state.js +43 -11
  450. package/modules/world/thingSource.js +20 -5
  451. package/modules/world/views.js +27 -14
  452. package/package.json +48 -7
  453. package/presets.js +1 -3
  454. package/render/PostFX.js +83 -53
  455. package/render/backend.js +31 -33
  456. package/render/cascades.js +17 -12
  457. package/render/cascades.tsl.js +5 -8
  458. package/render/daylight.js +20 -3
  459. package/render/detail.js +8 -7
  460. package/render/effects.js +28 -25
  461. package/render/fuse.js +3 -3
  462. package/render/fx/cloudShadow.tsl.js +3 -3
  463. package/render/fx/detail.tsl.js +1 -1
  464. package/render/fx/index.js +5 -10
  465. package/render/fx/library.tsl.js +11 -0
  466. package/render/fx/lighting.tsl.js +2 -1
  467. package/render/fx/nodeErrors.tsl.js +2 -2
  468. package/render/fx/objectOrigin.tsl.js +1 -2
  469. package/render/fx/particles.tsl.js +8 -6
  470. package/render/fx/patchNodes.tsl.js +5 -15
  471. package/render/fx/postWebGPU.tsl.js +30 -26
  472. package/render/fx/sky.tsl.js +15 -17
  473. package/render/fx/uniforms.tsl.js +4 -4
  474. package/render/fx/wind.tsl.js +1 -1
  475. package/render/fxNumbers.js +3 -0
  476. package/render/layers.js +2 -2
  477. package/render/lighting.js +5 -3
  478. package/render/lightmap.js +41 -21
  479. package/render/lights.js +6 -6
  480. package/render/lit.js +24 -0
  481. package/render/materials.js +8 -7
  482. package/render/mergeCommon.js +22 -0
  483. package/render/modeling.js +2 -2
  484. package/render/occlusion.js +62 -15
  485. package/render/ownFrame.js +4 -4
  486. package/render/patches.js +15 -15
  487. package/render/postWebGL.js +15 -12
  488. package/render/probes.js +41 -19
  489. package/render/recordSweep.js +117 -0
  490. package/render/shaderErrors.js +10 -9
  491. package/render/shadowCache.tsl.js +107 -0
  492. package/render/shadowTypes.js +9 -0
  493. package/{core → render}/shadows.js +59 -13
  494. package/render/slots.js +7 -7
  495. package/render/terms.js +22 -24
  496. package/render/uniformDecl.js +1 -1
  497. package/types/core.d.ts +336 -202
  498. package/types/gameplay.d.ts +254 -130
  499. package/types/generated/core/{Audio.d.ts → audio/Audio.d.ts} +22 -7
  500. package/types/generated/core/{audioVoice.d.ts → audio/audioVoice.d.ts} +2 -2
  501. package/types/generated/core/{Events.d.ts → base/Events.d.ts} +4 -4
  502. package/types/generated/core/{I18n.d.ts → base/I18n.d.ts} +8 -16
  503. package/types/generated/core/{Random.d.ts → base/Random.d.ts} +4 -3
  504. package/types/generated/core/{page.d.ts → engine/page.d.ts} +8 -9
  505. package/types/generated/core/{Input.d.ts → input/Input.d.ts} +28 -10
  506. package/types/generated/core/input/inputSeat.d.ts +26 -0
  507. package/types/generated/core/{Budget.d.ts → inspect/Budget.d.ts} +36 -26
  508. package/types/generated/core/{DebugOverrides.d.ts → inspect/DebugOverrides.d.ts} +17 -3
  509. package/types/generated/core/{Ops.d.ts → ops/Ops.d.ts} +6 -4
  510. package/types/generated/core/{control.d.ts → ops/control.d.ts} +14 -10
  511. package/types/generated/core/{Saves.d.ts → saves/Saves.d.ts} +62 -18
  512. package/types/generated/core/{session.d.ts → saves/session.d.ts} +3 -2
  513. package/types/generated/core/{Rays.d.ts → scene/Rays.d.ts} +8 -27
  514. package/types/generated/core/{Views.d.ts → scene/Views.d.ts} +2 -2
  515. package/types/generated/core/{Batching.d.ts → stream/Batching.d.ts} +7 -7
  516. package/types/generated/core/{Stream.d.ts → stream/Stream.d.ts} +22 -18
  517. package/types/generated/core/{Commits.d.ts → threads/Commits.d.ts} +1 -1
  518. package/types/generated/core/{Jobs.d.ts → threads/Jobs.d.ts} +6 -6
  519. package/types/generated/core/{Threads.d.ts → threads/Threads.d.ts} +4 -4
  520. package/types/generated/modules/calendar/Calendar.d.ts +10 -11
  521. package/types/generated/modules/debug/DebugPanel.d.ts +1 -9
  522. package/types/generated/modules/grid/Grid.d.ts +1 -0
  523. package/types/generated/modules/grid/Layer.d.ts +1 -1
  524. package/types/generated/modules/grid/index.d.ts +3 -3
  525. package/types/generated/modules/music/Music.d.ts +7 -5
  526. package/types/generated/modules/particles/Particles.d.ts +5 -4
  527. package/types/generated/modules/sky/Sky.d.ts +21 -10
  528. package/types/generated/modules/swarm/Swarm.d.ts +80 -0
  529. package/types/generated/modules/timeline/Timeline.d.ts +7 -5
  530. package/types/generated/modules/water/Water.d.ts +1 -0
  531. package/types/generated/modules/weather/Weather.d.ts +14 -16
  532. package/types/generated/modules/weather/weatherDraw.d.ts +3 -3
  533. package/types/generated/modules/world/World.d.ts +11 -7
  534. package/types/generated/render/PostFX.d.ts +21 -23
  535. package/types/generated/render/materials.d.ts +1 -0
  536. package/types/generated/render/occlusion.d.ts +9 -0
  537. package/types/generated/render/patches.d.ts +1 -0
  538. package/types/generated/ui/Focus.d.ts +1 -0
  539. package/types/generated/ui/UI.d.ts +1 -0
  540. package/types/nav.d.ts +47 -15
  541. package/types/physics.d.ts +150 -73
  542. package/types/pixel.d.ts +75 -0
  543. package/types/tsl.d.ts +37 -4
  544. package/types/world.d.ts +48 -75
  545. package/ui/Focus.js +10 -9
  546. package/ui/Parts.js +13 -5
  547. package/ui/UI.js +7 -7
  548. package/ui/defaults.js +3 -2
  549. package/ui/theme.js +7 -5
  550. package/core/assetEntry.js +0 -109
  551. package/core/engineCamera.js +0 -32
  552. package/core/ground.js +0 -104
  553. package/core/holds.js +0 -134
  554. package/core/math.js +0 -48
  555. package/core/moduleSlots.js +0 -100
  556. package/core/modules.js +0 -314
  557. package/core/saveApply.js +0 -210
  558. package/core/saveValues.js +0 -46
  559. package/core/session.js +0 -174
  560. package/core/shadowTypes.js +0 -16
  561. package/core/util.js +0 -17
  562. package/core/view.js +0 -43
  563. package/docs/MIGRATING-0.3.md +0 -248
  564. package/docs/MIGRATING-0.4.md +0 -320
  565. package/docs/MIGRATING-0.5.md +0 -68
  566. package/docs/MIGRATING-0.6.md +0 -126
  567. package/docs/PERF.md +0 -245
  568. package/docs/recipes/36-sky-ground-plants.md +0 -158
  569. package/docs/recipes/37-terrain-hooks.md +0 -115
  570. package/docs/recipes/38-environment-hooks.md +0 -67
  571. package/docs/recipes/42-terrain-shape.md +0 -64
  572. package/docs/recipes/47-island-snow-backdrop.md +0 -43
  573. package/docs/recipes/54-three-idioms.md +0 -88
  574. package/examples/plain-picture/FINDINGS.md +0 -53
  575. package/examples/sheepisland/.threedog/content-index.json +0 -1
  576. package/modules/camera/projection.js +0 -21
  577. /package/core/{mulberry32.js → base/mulberry32.js} +0 -0
  578. /package/core/{inputDefaults.js → input/inputDefaults.js} +0 -0
  579. /package/core/{textureBytes.js → inspect/textureBytes.js} +0 -0
  580. /package/core/{actor.js → ops/actor.js} +0 -0
  581. /package/core/{opsHistory.js → ops/opsHistory.js} +0 -0
  582. /package/core/{saveIds.js → saves/saveIds.js} +0 -0
  583. /package/core/{screenToGround.js → scene/screenToGround.js} +0 -0
  584. /package/core/{cells.js → stream/cells.js} +0 -0
  585. /package/core/{streamCells.js → stream/streamCells.js} +0 -0
  586. /package/core/{pureWorker.js → threads/pureWorker.js} +0 -0
  587. /package/examples/{sheepisland → perf-island}/content/index.js +0 -0
  588. /package/examples/{sheepisland → perf-island}/content/props.js +0 -0
  589. /package/examples/{sheepisland → perf-island}/content/templates.js +0 -0
  590. /package/examples/{sheepisland → perf-island}/content/vegetation.js +0 -0
  591. /package/examples/{sheepisland → perf-island}/picture/lights.js +0 -0
  592. /package/examples/{sheepisland → perf-island}/picture/materials.js +0 -0
  593. /package/examples/{sheepisland → perf-island}/picture/sky.js +0 -0
package/docs/api/world.md CHANGED
@@ -4,12 +4,12 @@ World data (world() module): things that must be saved, survive level changes an
4
4
 
5
5
 
6
6
  ## Methods and properties
7
- - `world.add(def: { kind, id?, position?, … }, opts?: { initial?, save? }) → WorldRecord | null` — Add a record and return it (a plain object). kind is required; without id one is numbered automatically (kind#1, kind#2…, saved; `#` never appears in an authored id, so the two can never collide). opts.initial: initial record written in content (needs an id); saves only keep its changes and removal; if the id already exists the existing one is returned (content may load twice); returns null if the save removed it (it is not added back). opts.save: false: not saved (temporary things). Example: `engine.world.add({ id: 'shop_owner', kind: 'npc', position: [12, 0, -30], name: '店主', mood: 'calm' }, { initial: true })`
7
+ - `world.add(def: { kind, id?, position?, … }, opts?: { initial?, save? }) → WorldRecord | null` — Add a record and return it (a plain object). kind is required; without id one is numbered automatically (kind#1, kind#2…, saved; `#` never appears in an authored id, so the two can never collide). opts.initial: initial record written in content (needs an id); saves only keep its changes and removal; if the id already exists the existing one is returned (content may load twice), after taking a new position / rot from the content unless play moved it; returns null if the save removed it (it is not added back). opts.save: false: not saved (temporary things). Example: `engine.world.add({ id: 'shop_owner', kind: 'npc', position: [12, 0, -30], name: '店主', mood: 'calm' }, { initial: true })`
8
8
  - `world.origin(id: string) → { definedAt?, level?, node?, template?, spawned? } | null | …` — Where a record comes from (filled in dev and test builds; null in release): { definedAt: 'content/props.js:14' } for a content entry, { level, node } for a level-model node, { template } when it is a template instance, { spawned: { op, tick } } for a record created during play. engine.inspect(id) and engine.pick(...).thing show it, so you know which file to edit to change the level for good. Example: `engine.world.origin('chest-home') // { definedAt: 'content/props.js:14', template: 'chest' }`
9
- - `world.idOf(obj: any) → string | null` — The id of the record whose model contains obj (obj itself or one of its parents is a built model), else null. A ray hit on a model names its record this way. Example: `const h = engine.pick(0, 0); const id = h && engine.world.idOf(h.object);`
9
+ - `world.idOf(obj: any) → string | null` — (experimental) The id of the record whose model contains obj (obj itself or one of its parents is a built model), else null. A ray hit on a model names its record this way. Example: `const h = engine.pick(0, 0); const id = h && engine.world.idOf(h.object);`
10
10
  - `world.get(id: string) → WorldRecord | undefined` — Get a record by id (undefined if missing, like a Map)
11
11
  - `world.set(id: string, patch: Record<string, any>) → WorldRecord` — Merge fields into a record and emit the world:change event; a position in patch also moves it. Returns the record. For discrete changes (chest opened, growth stage, picked up); if present has show, it is re-evaluated after the change. id / kind cannot be changed. Example: `engine.world.set('crate_1', { opened: true })`
12
- - `world.move(id: string, position: any)` — Move a record (no event; use it in simulate for things that move every step); still saved (saves diff against content). The model of a positionFrom 'record' (default) record follows this frame; to do something else with the position in presentation, compare in update. Example: `engine.world.move(rec.id, { x: rec.position.x + 1, z: rec.position.z })`
12
+ - `world.move(id: string, position: any)` — Move a record (no event; use it in simulate for things that move every step); still saved (saves diff against content). The model of a positionFrom 'record' (default) record follows this frame; to do something else with the position in presentation, compare in update. On a live character (the player, an NPC with a model) this is its placeAt: the character owns its position, so it goes there and the record says where it stands. A seated rider gets out to go there (placeAt ends a ride); a write equal to where it sits only follows the seat. Example: `engine.world.move(rec.id, { x: rec.position.x + 1, z: rec.position.z })`
13
13
  - `world.remove(id: string)` — Remove a record (its model is torn down too) and emit the world:remove event. Does nothing if the id does not exist. Removing an initial record is saved, so it stays gone after loading
14
14
  - `world.query(opts?: { kind?, near?, radius?, where?, zone? }) → WorldRecord[]` — Query records; returns an array. With near only nearby cells are scanned and results are sorted nearest first (radius defaults to 30 m); where filters further. For neighbor queries every step use forEachNear. Example: `engine.world.query({ kind: 'zombie', near: engine.player, radius: 30, where: z => !z.dead })`
15
15
  - `world.forEachNear(center: any, radius: number, fn: (rec, d2) => void)` — Call fn(rec, d2) for each record within radius meters (horizontal distance) of center; d2 is the squared distance. Unsorted, no allocation: use it for per-step neighbor queries (hundreds of zombies avoiding each other). Don't add / remove / move in the callback (moving into a cell not yet visited visits it again): record the change and apply it after the loop. Example: `engine.world.forEachNear(rec.position, 5, (o, d2) => { if (o !== rec && o.kind === 'zombie') n++; })`
@@ -17,9 +17,9 @@ World data (world() module): things that must be saved, survive level changes an
17
17
  - `world.view(id: string) → any` — The current model of this record (only exists nearby; null if not built yet or far away)
18
18
  - `world.refresh()` — Build / tear down models for the stream sources right now (normally automatic every frame, with a per-frame limit). Use it right after add when you need the model: sync builds are available via view(id) after the call, for async ones also await world.whenReady. Example: `engine.world.add({ id: 'gate', kind: 'gate', position: p }); engine.world.refresh(); engine.world.view('gate')`
19
19
  - `world.simulate(kind: string, opts: { near?, far?, farEvery?, radius?, fullRadius?, nearEvery?, … }) → { remove(): void }` — Register how a kind of thing changes (gameplay logic goes here, runs in the fixed step); near / far is split by distance from world.anchor (default: the player): near(rec, dt, obj): within radius, once per fixed step (obj is the model, may be null if not built yet; gameplay must not depend on it); far(rec, dt): farther away, once every farEvery seconds; dt is the seconds accumulated since the last simulation (can catch up a long time at once); on the far → near step, far runs first to pay back the owed time. With only far (crops), near also advances via far; with only near, far records are not simulated and owed time is not made up. Both dt are accumulated real (fixed-step) seconds (not multiplied by clock.rate). For things measured in game clock (grows over days) store engine.clock.now and compare. Example: `engine.world.simulate('zombie', { near: (rec, dt) => chase(rec, dt), far: (rec, dt) => wander(rec, dt), farEvery: 2 })`
20
- - `world.pauseSimulation() → { remove(): void }` — Stop running simulate() handlers on this machine until remove(): a multiplayer client lets the host simulate and only receives the records. Public so net() needs no world internals.
20
+ - `world.pauseSimulation() → { remove(): void }` — (experimental) Stop running simulate() handlers on this machine until remove(): a multiplayer client lets the host simulate and only receives the records. Public so net() needs no world internals.
21
21
  - Properties:
22
- - `records: Map<string, WorldRecord>` All records: id → record (read-only; use set to change fields, move to change position)
22
+ - `records: Map<string, WorldRecord>` (experimental) All records: id → record (read-only; use set to change fields, move to change position)
23
23
  - `radius: number` Default distance (meters) for building models and counting as near; present / simulate can override it. Changing it at runtime affects those without their own radius
24
24
  - `farEvery: number` Default interval (seconds) between far simulations, same unit as dt
25
25
  - `farMaxPerTick: number` Max far simulations per fixed step; the rest queue for the next step (dt accumulates, no time is lost). Counted by records, not milliseconds, so results do not depend on machine speed
@@ -28,4 +28,4 @@ World data (world() module): things that must be saved, survive level changes an
28
28
  - `zone: string | null` Current zone (e.g. level name, set by the level module on level change): once set, records of another zone get no model and no near simulation; null = no zoning
29
29
  - `ready: boolean` All models that should exist near the stream sources are built (async ones too; failed builds do not count as pending). The loading screen waits for it; to wait yourself, await world.whenReady
30
30
  - `whenReady: Promise<void>` Promise that resolves when ready becomes true
31
- - `steps: number` Number of fixed steps simulated
31
+ - `steps: number` (experimental) Number of fixed steps simulated
@@ -1,9 +1,10 @@
1
- # Starting a new game (a workspace under games/)
1
+ # Starting a new game
2
2
 
3
- **In this recipe**: 0. One-command setup · 1. Creating the files by hand · 2. Verify · 3. Preset parts · 4. Feel presets · 5. Canvas size
3
+ **In this recipe**: 0. One-command setup · 1. Creating the files by hand · 2. Verify · 3. Feel presets · 4. Canvas size
4
4
 
5
- Goal: create `games/my-game/` (pick your own name) with its own page, modules, content data and tests, independent of other games. Start from the
6
- template (`threedog new-game my-game`, section 0); the engine's own example is `examples/world/` in the package.
5
+ Goal: a game with its own page, modules, content data and tests. The engine's own example is `examples/world/` in the package.
6
+
7
+ In a folder of your own, installed from npm: run `npx threedog init` (add `--open-world` for the second form below), then `npm install`. In the engine repository: `npm run new-game -- my-game` creates `games/my-game/`. The rest of this page uses the repository form; read `games/my-game/` as your folder and `new-game` as `init`.
7
8
 
8
9
  ## 0. One-command setup (preferred)
9
10
  ```
@@ -18,37 +19,34 @@ The name may only contain lowercase letters, digits and dashes; an existing dire
18
19
  2. Creates the `node_modules/my-game` link (the path npm gives a workspace named `my-game`). It builds nothing and leaves `package-lock.json` alone; it runs `npm install` only when a dependency of the template is not installed yet, and says so.
19
20
  3. Runs `map` (generates GAMEMAP.md) and `check`. Any failing step stops and says why. The smoke test (`threedog test -w games/my-game`) builds, so it is left to you.
20
21
 
21
- The default game has no genre: `world()` + `content()`, what nearly every game needs (a start screen with Continue / Start, autosave, Esc = pause + settings menu; delete a line if the game does not want it), the engine's camera placed by hand (a plain `THREE.PerspectiveCamera`) and the gray
22
- starting picture in `picture/` (a sun, an ambient light, the tone curve, written by the game); no ground, sky, player or camera rig, because which of those a game needs depends on its genre (a character walking around a place you built: recipe 63, about twenty lines)
23
- (a card table, a puzzle room, a side-scroller and an open world start differently). Content files are empty arrays / objects (each
24
- has one comment line saying what goes there and which recipe teaches it), and `picture/`: `index.js` (wiring), `palette.js` (colors and key values), `lights.js`, `materials.js`, plain three.js
25
- that is yours to change or replace (recipe 62). `CLAUDE.md` says "This game has no gameplay yet; build what DESIGN.md describes".
22
+ The default game has no genre: `world()` + `content()`, what nearly every game needs (a start screen with Continue / Start, autosave, Esc = pause + settings menu; delete a line if the game does not want it), a plain `THREE.PerspectiveCamera` placed by hand and the gray starting picture. No ground, sky, player or camera rig: a card table, a puzzle room, a side-scroller and an open world start differently (a character walking around a place you built: recipe 63, about twenty lines).
23
+ Content files start empty, a comment in each saying what goes there, except `props.js`, whose `marker-1` shows the shape. `picture/` (`index.js` wiring, `palette.js`, `lights.js`, `materials.js`) is plain three.js, yours to change or replace (recipe 62).
26
24
  `--open-world` swaps `main.js` for `openWorld` (generated terrain from `@threedog/terrain-noise`, vegetation, a day/night sky, weather, water, collision, a
27
25
  follow camera) and a player at a flat spot, with `sky()` giving the signals and `picture/` writing the lights; it adds `@threedog/terrain-noise` to `package.json`. `spawn` and `places` take any `{ x, z }` (or `{ x, y, z }`); `findSpawn` is only for generated terrain.
28
- In an open-world start, to change the camera: `openWorld({ camera: 'firstPerson' })` (`follow` / `firstPerson` / `rts` / `fixed`, or pass a camera module directly; there is
29
- no default).
26
+ The canvas is the one you gave `createEngine({ canvas })`, also `engine.renderer.domElement`; the engine keeps no canvas property of its own.
27
+
30
28
  - The comments in `main.js` list further gameplay modules you can add; usage is in `../api/<module>.md`.
31
29
  - To change the starting point of new games, edit the real files in `packages/tools/templates/game/` (`templates/openworld/` for `--open-world`).
32
- - `DESIGN.md` is an empty template: write your gameplay ideas there. `CLAUDE.md` only points the way (read `node_modules/threedog/docs/AI.md` first,
33
- then GAMEMAP, DESIGN) and does not copy engine rules.
34
- - There is no `tests/`: when `tests/specs/` does not exist, `npm test -w games/my-game` runs a smoke test automatically.
30
+ - `DESIGN.md` is a form to fill in with the game's design, `STATUS.md` holds progress, and `CLAUDE.md` holds the working rules, a table cut from AI.md and the reading order.
31
+ - There is no `tests/`: a smoke test runs until you add `tests/specs/`.
35
32
 
36
33
  ## 1. Creating the files by hand (to learn what each file is, or when the template doesn't fit)
37
34
  | File | Content |
38
35
  |---|---|
39
- | `games/my-game/package.json` | Copy `package.json` from the game template (or run `threedog new-game my-game`) and set `name` to `my-game` (the plain game name, in this repository and in a game repo of its own; `@threedog/` is the engine's packages; dependencies `threedog`, `@threedog/tools`, plus `@threedog/terrain-noise` only for an open-world start, and your style (and `@threedog/post-effects` if the pack uses it) only when `main.js` imports it; the game's picture is its own `picture/` folder; scripts dev/build/preview/test/check/map) |
36
+ | `games/my-game/package.json` | Copy the template's and set `name` to `my-game` (the plain game name; `@threedog/` is the engine's packages). Dependencies `threedog`, `@threedog/tools`, plus `@threedog/terrain-noise` only for an open-world start and `@threedog/post-effects` only when the game imports it |
40
37
  | `games/my-game/vite.config.js` | One line: `export default gameConfig(import.meta.dirname)` (imported from `@threedog/tools/vite`); *.html files in the directory are bundled automatically, no `input` needed. Without `@threedog/tools`, a plain vite config needs `worker: { format: 'es' }` (the engine's Workers are ES modules) or `vite build` fails; `threedog dev / build` on a folder with no vite config uses the preset |
41
- | `games/my-game/index.html` | The page: one `<canvas id="view">` with a CSS size + `/main.js` (for more pages put `xxx.html` in the same directory); see §5 for embedding |
42
- | `games/my-game/main.js` | Install modules, compute places, `content.load`, game-specific logic |
38
+ | `games/my-game/index.html` | The page: one `<canvas id="view">` with a CSS size + `/main.js` (for more pages put `xxx.html` in the same directory); see §4 for embedding |
39
+ | `games/my-game/main.js` | Install modules, compute places, `content.load`, wire the game's systems (template `CLAUDE.md`, "Content vs code") |
43
40
  | `games/my-game/content/index.js` | Combines the content files into one object |
44
- | `games/my-game/content/*.js` | Only these names are read: items pickups containers npcs dialogues quests actions places triggers level vegetation props templates audio grids renames rules, plus the game's own kinds (rules.js) |
45
- | `games/my-game/DESIGN.md` | Hand-written design decisions (a few lines of `- **decision**: reason`), copied into GAMEMAP.md |
46
- | `games/my-game/CLAUDE.md` | A few lines: read `node_modules/threedog/docs/AI.md`, then this directory's GAMEMAP.md and DESIGN.md (copy the template's) |
47
- | `games/my-game/public/` | This game's art assets (URL `/models/...`); keep Blender source files in `games/my-game/art/models/`, `npm run assets -- -w my-game` compresses them into `public/optimized/` |
41
+ | `games/my-game/content/*.js` | Only these names are read: items pickups containers npcs dialogues quests actions places triggers level vegetation props templates audio views grids renames rules, plus the game's own kinds (rules.js) |
42
+ | `games/my-game/DESIGN.md` | The design as a form (copy the template's), copied into GAMEMAP.md |
43
+ | `games/my-game/STATUS.md` | Progress and what comes next (copy the template's) |
44
+ | `games/my-game/CLAUDE.md` | Working rules and reading order (copy the template's) |
45
+ | `games/my-game/public/` | This game's art assets (URL `/models/...`); keep Blender source files in `games/my-game/art/models/`, `npm run assets -- optimize -w my-game` compresses them into `public/optimized/` |
48
46
 
49
47
  After creating them, run `npm install` once at the repository root (this links the new game into the workspaces so `threedog` can find it).
50
48
 
51
- Outside the engine repository, a game installs `threedog` and `three` (plus your style, `@threedog/post-effects` / `@threedog/terrain-noise` if it imports them,
49
+ Outside the engine repository, a game installs `threedog` and `three` (plus `@threedog/post-effects` / `@threedog/terrain-noise` if it imports them,
52
50
  and `@threedog/tools` as a dev dependency for the CLI and the vite preset). To use an engine folder on disk instead of npm, install it with
53
51
  `npm install --install-links <folder>`: a plain link skips the engine's own dependencies (Rapier, Recast) and the build cannot resolve them.
54
52
 
@@ -58,18 +56,11 @@ In a game's own repository, `threedog check`, `types` and `map` read only the ga
58
56
  The template's `tsconfig.json` checks the game files only (`checkJs`), with `lib` ESNext + DOM (dependency typings such as Rapier's use
59
57
  `Symbol.dispose`) and `skipLibCheck: true`; without a tsconfig, `threedog types` writes the same settings to `.threedog/tsconfig.types.json`.
60
58
 
61
- `games/my-game/index.html` (minimal; the template's `index.html` has the same page with loading styles):
62
- ```html
63
- <!doctype html>
64
- <html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
65
- <title>My game</title><style>html,body{height:100%;margin:0;overflow:hidden;background:#141a17}#view{position:fixed;inset:0;width:100%;height:100%;display:block;outline:none}</style>
66
- </head><body><canvas id="view" tabindex="0"></canvas><script type="module" src="/main.js"></script></body></html>
67
- ```
68
59
 
69
60
  `games/my-game/main.js`: the opening lines are written out once, in [recipe 63](63-third-person-start.md) §1 (the blank template's `main.js` has the same opening with `world(), content(), settings()` and the camera placed by hand). What an open-world game with a few gameplay modules changes in it:
70
61
  ```js
71
62
  // my-game: ... (this first comment line appears in the file table of GAMEMAP.md)
72
- // The opening stays as in recipe 63 §1: createEngine({ canvas, lights: false, ui, saveKey, bindings }), createPicture(engine) after engine.use,
63
+ // The opening stays as in recipe 63 §1: createEngine({ canvas, lights: false, ui, saveKey, bindings }), engine.use(createPicture()) after engine.use,
73
64
  // Object.assign(window, { engine, picture }) (tests, screenshots and the console rely on it), await engine.start().
74
65
  import { presets, openWorld, interactions, dialogue, inventory, pickups, quests, content } from 'threedog';
75
66
  import { terrainPreset } from '@threedog/terrain-noise'; // optional terrain generator (nor a world shape)
@@ -85,7 +76,7 @@ engine.use(openWorld({ camera: 'follow', seed: 42, terrain: terrainPreset(), tim
85
76
  // the terrain is generated: find flat ground as "home" at the start (give your own height range to avoid beach and peaks)
86
77
  const home = engine.characters.findSpawn([0, 0, 0], { minH: 3, maxH: 14 });
87
78
  engine.characters.createPlayer({ ...presets.player.thirdPerson, spawn: home });
88
- engine.content.load(data, { places: { ...data.places, home } }); // content/places.js names + this one; content uses { place: 'home', x, z }, quests target: 'home'
79
+ engine.content.load(data, { places: { home } }); // on top of the names in content/places.js; content uses { place: 'home', x, z }, quests target: 'home'
89
80
  ```
90
81
  Every `openWorld` part takes `false` (leave it out) or its module's own options object, so you never have to drop the preset for one setting:
91
82
  `openWorld({ seed: 42, camera: 'follow', calendar: { seasons: ['wet', 'dry'], daysPerSeason: 28 }, characters: { npcs: false }, rigid: false, ambience:
@@ -102,7 +93,7 @@ engine.setGround({ height: (x, z) => 0 }); // what walking, placing and the ca
102
93
  ```
103
94
  Walls and obstacles are `engine.collision.addBox(obj, { halfWidth, halfDepth })`; a Blender level brings its own ground (`level()`, next paragraph).
104
95
  `saveKey` must differ per game, otherwise saves overwrite each other. The UI language follows the player's browser (Chinese browser -> Chinese,
105
- otherwise English) unless you set `createEngine({ locale: 'zh-CN' })` (`'zh'` and `'en-US'` match too; a language with no strings warns). A game without terrain (the city test page in the engine repository does this): register
96
+ otherwise English) unless you set `createEngine({ locale: 'zh-CN' })` (`'zh'` and `'en-US'` match too; a language with no strings warns). A game on a level built in code: register
106
97
  the level generator function under `models` in `engine.assets.manifest({ name, models })`, use `level({ url: name })` and pick your own modules, then
107
98
  create the player and install content in `level:loaded`.
108
99
 
@@ -112,7 +103,7 @@ import items, { startItems } from './items.js';
112
103
  import places from './places.js';
113
104
  export default { items, startItems, places };
114
105
  ```
115
- `content/places.js`: `export default { home: 'flat ground found at the start (coordinates computed in main.js)' };`
106
+ `content/places.js`: `export default { farm: { x: 12, z: -4 }, home: 'flat ground found at the start' };`. `content.load` reads a place written with coordinates from the data; a text entry only declares the name for `threedog check` and waits for `content.load(data, { places })`.
116
107
 
117
108
  ## 2. Verify
118
109
  1. `npm run map` -> generates `games/my-game/GAMEMAP.md`; check the "engine modules" and "page /" sections.
@@ -123,28 +114,22 @@ export default { items, startItems, places };
123
114
  5. To see the picture: `npm run shot -- -w my-game /` (one image in `games/my-game/.threedog/shots/`); while developing run `npm run dev -w games/my-game` (or
124
115
  `npm run dev -- my-game`) and open the printed address; read errors in `games/my-game/.threedog/errors.log`.
125
116
 
126
- ## 3. Preset parts
127
- Every `openWorld()` part takes `false` or its module's options object, for example
128
- `openWorld({ camera: 'follow', calendar: { seasons: ['wet', 'dry'], daysPerSeason: 28 }, debug: false })`. Gameplay modules (interactions, dialogue,
129
- inventory, quests) are not in the preset: add them with `engine.use`. The debug panel is dev-only by default.
130
117
 
131
- ## 4. Feel presets (opt-in)
118
+ ## 3. Feel presets (opt-in)
132
119
  The engine applies no gameplay feel by itself: `weather()` alone has only a calm `clear`, `sky()` has no seasons, and the calls that need a feel
133
120
  refuse to guess: `createPlayer()` throws `[player-control]` without `control`, `interactions()` throws `[interaction-setup]` without `pick` and keys,
134
121
  `openWorld()` throws `[open-world-camera]` without `camera`. The core key table holds only movement and menu confirm / cancel; run, jump and interact
135
122
  keys come from the game. `presets` holds named option objects a game picks on purpose; each only bundles options you could write yourself, so spread
136
123
  and override:
137
- ```js
124
+ ```js fragment
138
125
  import { presets, weather, calendar, sky, followCamera, interactions } from 'threedog';
139
126
  engine.use(calendar(presets.calendar.fourSeasons), sky(), weather({ ...presets.weather.temperate, autoPool: ['clear', 'rain'] }), followCamera(presets.camera.overShoulder));
140
127
  engine.use(interactions({ ...presets.interactions.facing })); // nearest / facing / aim, each with E
141
128
  const player = engine.characters.createPlayer({ ...presets.player.lockOn, faceTarget: boss }); // none / thirdPerson / lockOn / aim / sideScroller
142
129
  ```
143
- `presets.player.thirdPerson` is `{ control: 'camera', faceMode: 'move', cameraFollow: true }`; the run / jump keys are
144
- `presets.bindings.walk` (`{ run: ['ShiftLeft', 'ShiftRight', 'PadLB'], jump: ['Space', 'PadA'] }`). No module or preset takes keys: every key
145
- comes from `createEngine({ bindings })` or `engine.input.bind(...)`.
130
+ The run / jump keys are `presets.bindings.walk`. No module or preset takes keys: every key comes from `createEngine({ bindings })` or `engine.input.bind(...)`.
146
131
 
147
- ## 5. Canvas size: full window, a page section, a split layout or an editor panel
132
+ ## 4. Canvas size: full window, a page section, a split layout or an editor panel
148
133
  The engine follows the canvas's own CSS box (a `ResizeObserver` on the canvas), not the window: renderer size, camera aspect, `input.pointer` (`x / y`
149
134
  pixels and `ndcX / ndcY` relative to the canvas), `engine.pick`, `screenToGround`, `worldToScreen` and the HUD all use that box, and the engine's UI
150
135
  root is laid exactly over it. So the layout decides:
@@ -1,10 +1,11 @@
1
1
  # Adding an NPC (schedule + dialogue)
2
2
 
3
+ **In this recipe**: 1. Write data · 2. Add in code · NPC data and model · Custom behavior · Avoidance · A guard you build yourself · Dialogue choices · 3. Verify · Bubbles
4
+
3
5
  Modules needed: `characters()` (NPCs on by default), `interactions({ ...presets.interactions.nearest })`, `dialogue()`; clock-time schedules need
4
- `sky()` with a day cycle (`dayLength`, e.g. `presets.calendar.cycle`: without one the clock never moves and the NPC keeps to one stop). The
5
- `openWorld()` preset already installs `characters()` and `sky()` but not `interactions({ ...presets.interactions.nearest })` or `dialogue()`, so add
6
- them yourself: `engine.use(openWorld({ camera: 'follow', calendar: presets.calendar.cycle, ...}), interactions({ ...presets.interactions.nearest }),
7
- dialogue(), content())`.
6
+ `calendar()` with a day cycle (`dayLength`, e.g. `presets.calendar.cycle`: without one the clock never moves and the NPC keeps to one stop). `openWorld()`
7
+ installs `characters()` and the calendar but not the other two: `engine.use(openWorld({ camera: 'follow', calendar: presets.calendar.cycle, ...}),
8
+ interactions({ ...presets.interactions.nearest }), dialogue(), content())`.
8
9
 
9
10
  ## 1. Write data (recommended)
10
11
  `games/<game>/content/npcs.js`:
@@ -12,7 +13,7 @@ dialogue(), content())`.
12
13
  export default {
13
14
  guard: {
14
15
  name: 'Gate guard',
15
- colors: { body: 0xc89a5a, legs: 0x5b4a3a, hair: 0x3a2a1a }, // omit to use the style's default colors
16
+ colors: { body: 0xc89a5a, legs: 0x5b4a3a, hair: 0x3a2a1a }, // omit to use the default colors
16
17
  start: { place: 'home', x: 6, z: -3 }, // starting position; omitted = the first stop of the schedule
17
18
  schedule: [ // at is a clock time 'HH:MM'; at that time the NPC walks there (pathfinding is automatic)
18
19
  { at: '07:00', place: 'home', x: 6, z: -3 },
@@ -52,10 +53,10 @@ export default {
52
53
  },
53
54
  };
54
55
  ```
55
- The words usable in conditions / effects are in the comment at the top of `modules/content/rules.js` (flag notFlag has lacks counter can / setFlag
56
+ The words usable in conditions / effects are in the last section of `../api/content.md` (flag notFlag has lacks counter can / setFlag
56
57
  give take bump startQuest toast particles marker clearMarker op). A game's own action is an op, always written as a pair `[name, args]` (a bare
57
58
  name string is rejected): `do: { op: ['delivery.done', { parcel: 'p1' }] }` (`23-ops.md`).
58
- The items used (coin, pass) must be defined in `items.js`, otherwise validation fails. A `place` name comes from `content.load(data, { places })` or
59
+ The items used (coin, pass) must be defined in `items.js`, otherwise validation fails. A `place` name comes from `content/places.js`, `content.load(data, { places })` or
59
60
  from a level marker (such as `npc_guard`). Add a new content file to `content/index.js`.
60
61
 
61
62
  ## 2. Add in code (temporary NPCs, dynamic schedules)
@@ -98,8 +99,7 @@ The behavior name and `mind` (the behavior's parameters and memory) are in the N
98
99
  carries on with the new behavior. A wrong behavior name throws and lists the registered ones. NPCs in content can also write `behavior` + `mind`
99
100
  directly (see the cat above); to change behavior at runtime use `npc.setBehavior`.
100
101
 
101
- **An enemy that chases the player**: the `chase` behavior below is the example; in `near`, after your own `character.move`, call
102
- `engine.npcs.avoid.push(rec, npc.character, dt)` once so several enemies don't pile into one clump (see "Avoidance" below). Things that are not NPCs
102
+ **An enemy that chases the player**: the `chase` behavior below is the example; the push in "Avoidance" below keeps several from piling into one clump. Things that are not NPCs
103
103
  (monsters, crops) are written as world data, see recipe 18 section 5.
104
104
 
105
105
  To write your own: `engine.npcs.behavior(name, { near(rec, dt, npc), far(rec, dt) })`, with the same rules as `world.simulate`: `near` is called once
@@ -119,26 +119,24 @@ engine.npcs.behavior('chase', {
119
119
  npc.setBehavior('chase');
120
120
  ```
121
121
  To path around obstacles, use `engine.characters.findPath(from, to)` to get waypoints and walk them one by one (the schedule behavior does exactly
122
- this, see `goTo` in `modules/characters/npcSim.js`).
122
+ this).
123
123
 
124
124
  ## Avoidance (NPCs don't clump or pass through each other)
125
125
  NPCs with models nearby avoid each other by default: when closer than the sum of two radii (`engine.movement.radius` x 2, about 0.8 meters) they push
126
126
  each other apart, harder the more they overlap, at most 3 meters per second; the player counts as an obstacle that only NPCs yield to, and the
127
127
  player's position is never pushed. After pushing, `engine.collision` (if installed) constrains them back to walkable ground, so they are not pushed
128
128
  into walls. The built-in `schedule` and `wander` both avoid.
129
- - Deterministic and cheap: done only in the fixed step, no random numbers, neighbors computed from "the positions at the start of this step", so after
130
- save and load, or with a different `frameEvery`, positions are identical bit for bit; 400 NPCs with models cost less than 1 ms per step (a tight
131
- clump only a few ms).
129
+ - Deterministic: done only in the fixed step, no random numbers, neighbors computed from the positions at the start of the step, so a load or a different
130
+ `frameEvery` gives identical positions.
132
131
  - Tune or turn off:
133
132
  ```js
134
133
  engine.npcs.avoid.set({ radius: 0.6, strength: 2 }); // stand sparser (radius in meters), push slower (strength in meters/second)
135
134
  engine.npcs.avoid.set(false); // turn off (ghosts, crowds passing through); set(true) turns it on again
136
135
  ```
137
136
  - Far away (no model) NPCs are simulated from data without per-NPC avoidance; a few steps after a model is built on approach they get pushed apart.
138
- - Difference from `nav({ crowd: true })`: when crowd is installed the Recast crowd agents take over and this is not applied on top. Crowd routes more
139
- cleverly (around obstacles along the navmesh, yields to others) but does not guarantee identical results after loading; the simple push here does
140
- not route around anything and only keeps NPCs from overlapping, with results identical after loading. For save replay and determinism use this; for
141
- crowds going around big obstacles use crowd.
137
+ - `nav({ crowd: true })` replaces this push with Recast crowd agents: they route around obstacles along the navmesh but do not guarantee identical
138
+ results after a load, and the player is no agent, so crowd NPCs walk through the player. The push routes around nothing and only keeps NPCs from overlapping. For replays and saves use the push; for crowds going
139
+ around big obstacles use crowd.
142
140
  - Behaviors you write are not avoided automatically: after your own `character.move`, call `engine.npcs.avoid.push(rec, npc.character, dt)` once
143
141
  (inside `near`, before writing back to the data).
144
142
 
@@ -146,7 +144,7 @@ engine.npcs.avoid.set(false); // turn off (ghosts, cro
146
144
  ## A guard you build yourself (`Character` + `walkTo`)
147
145
 
148
146
  For a one-off (guard, pet, follower) that `schedule` / `wander` do not cover: `new Character(engine, { rig })` takes a ready body
149
- (`{ root, body?, head?, limbs?, joints? }`), or `{ model: 'humanoid' }` picks a body asset like any character ([13-animation](13-animation.md)); call `character.animate(dt)` each frame.
147
+ (`{ root, body?, head?, limbs?, joints? }`), or `{ model: 'villager' }` / `{ model: ['villager', 0xcc8844] }` names a body your own asset pack registers (none ships with the engine; `humanoid` in other pages is such a name) like any character ([13-animation](13-animation.md)); call `character.animate(dt)` each frame.
150
148
  `character.walkTo(target, { speed, arrive, turnRate, run })` follows `characters.findPath` on fixed steps (turns at `turnRate` rad/s, skips passed
151
149
  points, re-plans when it makes no progress for `stuckSeconds`, up to `maxRepaths`). It returns a promise of `{ status }`: `'arrived'` | `'noPath'` |
152
150
  `'stuck'` | `'cancelled'` (never rejects), with `remove()` to cancel.
@@ -154,8 +152,9 @@ A walk holds the character's control on layer `script` ([57-control](57-control.
154
152
  walk, and an escort quest that wants the same NPC takes control itself (`engine.control.take(npc, { owner: 'escort', step })`) instead of
155
153
  editing its record.
156
154
 
157
- ```js
158
- const guard = new Character(engine, { rig: { root: myGuardMesh } }).addTo();
155
+ ```js fragment
156
+ const guard = new Character(engine, { rig: { root: myGuardMesh } });
157
+ engine.add(guard.root);
159
158
  guard.placeAt(post);
160
159
  const walk = guard.walkTo(player.position, { arrive: 1.5 });
161
160
  if ((await walk).status === 'noPath') guard.face(player); // walk.remove() cancels
@@ -172,12 +171,11 @@ The dialogue's keys go through two ops, so code, tests and the dev bridge drive
172
171
  `npm run map` it shows up in the NPC table and dialogue graph of GAMEMAP.md.
173
172
  - State: `npm run shot -- / --time 13:10 --wait 20 --describe-only`; the "nearby" list has an entry for `Gate guard` tagged as an NPC with its distance in
174
173
  meters (only listed within 30 meters; add `--pos x,z` to stand by the tower).
175
- - Console / tests: `engine.npcs.get('guard').position`, `.currentStop()`; during a dialogue `engine.describe().ui.dialogue` = `{ speaker, text, typing, choices: [labels], lock }` (absent when no dialogue runs; the text version prints it as a `Dialogue:` line). `describe` does NOT expose the node id or the NPC id: `speaker` is the display name; to inspect the node, read the content file or listen to `engine.events.on("dialogue:line", ({ script, node, speaker, text }) => ...)` (also `dialogue:start` / `dialogue:end`).
174
+ - Console / tests: `engine.npcs.get('guard').position`, `.currentStop()`; during a dialogue `engine.describe().ui.dialogue` = `{ speaker, text, typing, choices: [labels], selected, advance }`. `describe` shows no node or NPC id: to inspect the node, listen to `engine.events.on("dialogue:line", ({ script, node, speaker, text }) => ...)` (also `dialogue:start` / `dialogue:end`).
175
+ - E opens a conversation; only confirm (Space / Enter) advances it, unless `dialogue({ advanceActions })` adds a key. `describe().ui.dialogue.advance` names the keys. While it is open game input is locked, so E on anything else does nothing: the press is logged as a refused `interaction.use` (`inputLocked`) in `engine.ops.recent()` and `threedog test` prints it under a failed spec.
176
176
  - Advancing a dialogue in a headless test (typing and "keys ignored right after opening" both run on game time): press E when near -> `engine.step(1)`
177
177
  to finish typing -> press a number key or run `engine.ops.run('dialogue.choose', { index: i })` (while typing it completes the sentence first) ->
178
178
  `engine.step(0.3)`. No real-time waiting.
179
- - Related tests: `npm test -- 小城` (the shopkeeper's schedule and dialogue), `npm test -- "S1 NPC"` (far-away simulation, changing level, saving,
180
- identical results after loading).
181
179
 
182
180
  ## Talking in a bubble instead of a conversation
183
181
  `interact: { op: 'npc.talk', args: { channel: 'bubble' } }` (code or content) makes the interact key play the NPC's script as bubble lines over its head while the player keeps
@@ -5,13 +5,13 @@
5
5
 
6
6
  ## Pick and count: meshes you built, no bag
7
7
  Shells on a beach, four kinds of flowers, letters to collect: things the player takes and a number goes up. `interactions()`, `hud()` and a key (`createEngine({ bindings: presets.bindings.interact })`: E) are enough:
8
- ```js
8
+ ```js fragment
9
9
  engine.hud.counter('shells', { label: 'Shells', value: 0, max: 4 }); // at setup, not on session:start
10
10
  shells.forEach((shell, i) => engine.interactions.add(shell, { id: `shell-${i}`, label: 'Pick up', once: true, counter: 'shells', onUse: () => engine.audio.sfx('pick') }));
11
11
  ```
12
- `once` hides the mesh after a use (`onUse` returning `{ ok: false }` leaves it); `counter` adds 1 through `engine.hud.add(name, n)`, and does nothing without
13
- `hud()`. Both are saved and go back on a new game. The save knows a thing by `id`, else `mesh.name`: development throws when it has neither, or shares one with another once item.
14
- A hidden mesh is only hidden: a collider it had is yours to remove in `onUse`. To add up without a thing to take, call `engine.hud.add('score', 10)` yourself.
12
+ `once` hides the mesh after a use (`onUse` returning `{ ok: false }` leaves it; an async `onUse` is judged when it settles, and a throw leaves it too); `counter` adds 1 through `engine.hud.bump(name, n)`, and does nothing without
13
+ `hud()`. Both are saved and go back on a new game. The save knows a thing by `id`, else `mesh.name`: `interactions.add` throws when it has neither, or shares one with another once item.
14
+ A hidden mesh is only hidden: a collider it had is yours to remove in `onUse`. To add up without a thing to take, call `engine.hud.bump('score', 10)` yourself.
15
15
 
16
16
  | Use | When |
17
17
  |---|---|
@@ -19,10 +19,9 @@ A hidden mesh is only hidden: a collider it had is yours to remove in `onUse`. T
19
19
  | `pickups.spawn` (below) | it goes in a bag, respawns, is taken by walking into it (`auto`), is laid out in `content/`, or a net host must decide who got it |
20
20
 
21
21
  ## Items and pickups
22
- Modules needed: `inventory()` (inventory; the window is the UI part `inventory`, opened with the key the game gives:
23
- `inventory()`; its open key is the game's: `presets.bindings.inventory` is I / gamepad Y, `inventory: []` none; no module binds a key by itself) +
24
- `pickups()` (things lying on the ground; needs `world()`, which `openWorld()` includes) + `interactions({ ...presets.interactions.nearest })` (walk up
25
- to a pickup and press E). "Already picked up / how long until it grows back" is data in world and is saved with the game.
22
+ Modules needed: `inventory()` (its window is the UI part `inventory`; the open key is the game's: `presets.bindings.inventory` is I / gamepad Y,
23
+ `inventory: []` none) + `pickups()` (things lying on the ground; needs `world()`, which `openWorld()` includes) +
24
+ `interactions({ ...presets.interactions.nearest })` (walk up to a pickup and press E). "Already picked up / how long until it grows back" is data in world and is saved with the game.
26
25
 
27
26
  **Every actor has its own bag**: the container whose id is the actor's id (`inventory.of(actor)`): `'player'` for the local user, each net peer's actor
28
27
  id on the host, an NPC's id. "The player inventory" (`inventory.add / count / list ...`) is the bag of `engine.actor`. Whoever takes a pickup gets it in
@@ -42,7 +41,7 @@ export const startItems = { coin: 3 }; // what the inventory holds at t
42
41
  `content/pickups.js` (a list):
43
42
  ```js
44
43
  export default [
45
- { item: 'mushroom', place: 'home', x: 8, z: 3, respawn: 120 }, // respawn: after how many game seconds it grows back (omitted = never again)
44
+ { item: 'mushroom', place: 'home', x: 8, z: 3, respawn: 120 }, // respawn: after how many calendar seconds it grows back (omitted = never again)
46
45
  { item: 'coin', x: 40, z: -12, count: 5, auto: true }, // without place it is a world coordinate; count = how many at once; auto = taken by walking into it
47
46
  { item: 'sword', x: 12, z: 4, data: { durability: 60 } }, // data = this piece's own data (see "Single pieces"); radius = reach in meters (default 2)
48
47
  ];
@@ -51,29 +50,22 @@ Remember to `import items, { startItems } from './items.js'` and `import pickups
51
50
 
52
51
  **Data and stable ids**: each pickup is a plain `kind: 'pickup'` record in `engine.world` (needs `world()`, which `openWorld()` includes); the model
53
52
  is built only near the player and removed when far.
54
- Id: if you write an `id` it is used; otherwise it is `pickup:<item>:<index in the pickups array>`, the same every time for the same content, and
55
- distinguishes the same item placed at the same coordinates. **Write an `id` if the content will keep changing** (inserting a new one in the middle
56
- shifts the later indices).
57
- When picked up, the record is removed from world; one with `respawn` stays and gets an `until` (respawn time, game seconds); while waiting it has no
58
- model, and at that time (also when far away with no model) `until` is cleared and it returns to the ground.
59
- Pickups in content are the world's **initial data**: the save records only what was picked up and what is waiting to respawn; it makes no difference
60
- whether `content.load` runs before or after loading, and picked-up items do not reappear; positions that use a level marker carry a `zone`, so after
61
- changing level and coming back they are still picked up.
53
+ Id: write an `id`; without one it is `pickup:<item>:<index in the pickups array>`, which moves when an entry is inserted above it (recipe 30, "Ids").
54
+ When picked up, the record is removed from world; one with `respawn` stays and gets an `until` (calendar seconds); while waiting it has no model,
55
+ and at that time (also when far away with no model) it returns to the ground. Pickups in content are initial data, like props (recipe 18 §4).
62
56
  `engine.world.remove(id)` deletes one directly.
63
57
 
64
58
  ## 2. In code (dynamic drops, custom models, instant effects)
65
- ```js
59
+ ```js fragment
66
60
  engine.inventory.define('gem', { name: 'Gem', icon: '💎', color: 0x66ccff }); // shape: model: 'gemModel' (an asset name), else an asset named 'pickup:gem' / 'pickup', else a gray box (spawn { mesh } puts one object of the game's own down instead)
67
61
  const gem = engine.pickups.spawn(engine.player.position, { give: 'gem', count: 1 }); // returns a handle; gem.remove() deletes data and model together
68
- // handle: { id: id in world, give, object: current model (null when far), remove() }; opts.id lets you write a stable id (spawning again with the same id reuses the existing one)
69
- engine.inventory.add('coin', 2); // give directly to the local bag; returns the entry key ('coin'), false if it doesn't fit
70
- engine.inventory.remove('coin', 1); // returns false if there isn't enough
71
- engine.inventory.has('coin', 2); // at least 2?
62
+ // opts.id writes a stable id (spawning again with the same id reuses the existing one)
63
+ engine.inventory.add('coin', 2); // the local bag; { ok: true, key: 'coin', added: 2 }, or { ok: false, code: 'full' } if none fit
72
64
  engine.pickups.spawn([8, 0, 2], { give: 'ammo', count: 30, auto: true, radius: 1.2 }); // taken on touch by whoever touches it (pickups.takers), no key, no prompt
73
65
  engine.pickups.spawn(p, { give: (e, { actor }) => e.ops.run('hp.heal', { n: 25 }, { actor }), name: 'Medkit', model: 'medkit', auto: true }); // instant effect, no inventory needed
74
66
  engine.events.on('pickup:take', ({ actor, x, z }) => engine.particles?.emit('dust', { x, y: engine.surface(x, z), z }, { count: 10 })); // also item:add / item:remove (with container, actor) / item:use
75
67
  ```
76
- The default reach is `pickups({ radius: 2 })`; each pickup can set its own `radius`. Taking one is the op `pickup.take { id }` (net: `'peer'`): the
68
+ The default reach is `pickups({ radius: 2 })`; each pickup can set its own `radius`. Reach is a sphere around the pickup, so a coin on a ledge less than `radius` above the player is taken from under it: give it a smaller `radius`. Taking one is the op `pickup.take { id }` (net: `'peer'`): the
77
69
  interact key, auto pickups, a net client's press (sent to the host, which puts the item into that peer's bag) and tests all run it as `ctx.actor`.
78
70
  A give function is not saved data: code that spawns one spawns it again on load (content and setup code do); a runtime drop gives an item id.
79
71
 
@@ -85,23 +77,21 @@ also takes a key.
85
77
  ```js
86
78
  const I = engine.inventory;
87
79
  I.define('sword', { name: 'Sword', stack: 1 });
88
- const key = /** @type {string} */ (I.add('sword', 1, { data: { durability: 80, level: 3 } })); // 'sword#7' (add returns false when it does not fit)
89
- I.count('sword'); // every sword, with or without data
90
- I.get(key); // { key, id: 'sword', count: 1, data: { durability: 80, level: 3 }, def }
91
- I.list(); // every entry: [{ key, id, count, data, def }] for your own UI
80
+ const { key } = I.add('sword', 1, { data: { durability: 80, level: 3 } }); // 'sword#7' (add returns { ok: false, code: 'full' } when it does not fit)
92
81
  // change it inside an op or fixed step (data objects are frozen: always pass a new one; the key stays the same)
93
82
  const s = I.get(key); I.setData(key, { ...s.data, durability: s.data.durability - 1 });
83
+ I.container('chest-1', { capacity: 8 });
94
84
  I.transfer('player', 'chest-1', key); // exactly this sword; it keeps its data and key
95
- I.remove(key); // exactly this one; I.remove('sword') takes plain ones first, then the oldest
96
- I.add('tomato', 5, { data: { quality: 2 } }); // stackable: equal data joins the same entry
97
- I.setData('tomato#4', { quality: 1 }, 2); // only 2 of that stack change: they split off under a new key (returned)
85
+ I.container('chest-1').remove(key); // exactly this one; I.remove('sword') takes plain ones first, then the oldest
86
+ I.define('tomato', { name: 'Tomato' });
87
+ const t = I.add('tomato', 5, { data: { quality: 2 } }); // stackable: equal data joins the same entry
88
+ I.setData(t.key, { quality: 1 }, 2); // only 2 of that stack change: they split off under a new key (returned)
98
89
  ```
99
90
  Data and keys are saved with the container. Which piece a player means is chosen by key (a click on a row of `list()`), so ops take `item` as an id or a key.
100
91
 
101
92
  ## Limits (all optional, none by default)
102
93
  `inventory({ capacity, maxWeight })` for the player and `inventory.container(id, { capacity, maxWeight })` for others:
103
- `capacity` = slots (an entry uses `ceil(count / stack)`), `maxWeight` = sum of item `weight` × count. `room(item)` says how many more fit; `weight`
104
- and `slotsUsed` read the totals. Locks, prices and "only one equipped" are game rules: check them in your op's `can`.
94
+ `capacity` = slots (an entry uses `ceil(count / stack)`), `maxWeight` = sum of item `weight` × count.
105
95
 
106
96
  ## Using and dropping (ops)
107
97
  ```js
@@ -113,7 +103,7 @@ Both act on `ctx.actor`'s container (`'player'` by default).
113
103
 
114
104
  **Replace an item when the bag is full**: `inventory.trade` takes A and gives B as one all-or-nothing step (it checks that B fits once A is gone), and
115
105
  can be undone.
116
- ```js
106
+ ```js fragment
117
107
  const r = engine.ops.run('inventory.trade', { take: 'rusty_key', give: 'gold_key' }); // also takeN / giveN; take may be an entry key ('sword#3')
118
108
  if (!r.ok) say(r.code); // 'notEnough' (A missing) | 'full' (B does not fit even after A leaves)
119
109
  engine.ops.undo('inventory.trade', { take: 'rusty_key', give: 'gold_key' }, r.value); // gives A back (with its data), takes B away
@@ -131,19 +121,17 @@ The window is a UI part (recipe 26): the engine opens and closes it (the bound `
131
121
  ```js
132
122
  engine.ui.set('inventory', false); // no window at all (the key does nothing, no DOM)
133
123
  engine.ui.set('inventory', { drop: true }); // default window plus a Drop button per row (Use appears for items with use)
134
- engine.ui.set('inventory', (engine) => { // your own: grid, drag and drop, anything
124
+ engine.ui.set('inventory', (engine) => { // your own: grid, drag and drop, anything; buttons run ops with an entry's key
135
125
  const el = document.createElement('div'); engine.uiRoot.appendChild(el);
136
- el.onclick = ev => { const key = ev.target.dataset.key; if (key) engine.ops.run('inventory.use', { item: key }); }; // buttons run ops
137
- return { show: d => { el.hidden = false; el.innerHTML = d.items.map(i => `<button data-key="${i.key}">${i.def.name} ×${i.count}</button>`).join(''); },
138
- update: d => { el.innerHTML = d.items.map(i => `<button data-key="${i.key}">${i.def.name} ×${i.count}</button>`).join(''); },
139
- hide: () => { el.hidden = true; }, dispose: () => el.remove() };
126
+ el.onclick = ev => { const key = ev.target.dataset.key; if (key) engine.ops.run('inventory.use', { item: key }); };
127
+ const draw = d => { el.innerHTML = d.items.map(i => `<button data-key="${i.key}">${i.def.name} ×${i.count}</button>`).join(''); };
128
+ return { show: d => { el.hidden = false; draw(d); }, update: draw, hide: () => { el.hidden = true; }, dispose: () => el.remove() };
140
129
  });
141
130
  engine.ui.open('inventory'); engine.ui.close('inventory'); // open / close from code
142
131
  ```
143
- The shape of an item on the ground is a model name from an asset pack, built through the same path as content props and templates (one build per
144
- name, cached / baked, the same shadow rule): the item's `model`, else a model named `pickup:<item id>`, else one named `pickup`, else a neutral gray
145
- box. A generator that returns bare geometry is drawn with `engine.pickups.material` in the item's own `color` (a coin, a gem, a medkit or a paper
146
- note are all just models).
132
+ The shape of an item on the ground is a model name from an asset pack, built through the same path as content props (recipe 05 §1): the item's `model`,
133
+ else a model named `pickup:<item id>`, else one named `pickup`, else a neutral gray box. A generator that returns bare geometry is drawn with
134
+ `engine.pickups.material` in the item's own `color`.
147
135
  ```js
148
136
  engine.use(pickups({ color: 0xd8c070, size: 0.3, lift: 0.5 })); // default color, placeholder box, height above the ground
149
137
  engine.pickups.material = new THREE.MeshStandardMaterial({ metalness: 0.8, roughness: 0.3 }); // swaps every box and geometry-only model; used as given
@@ -154,13 +142,12 @@ To give / take items in content use the effect words: `{ give: { coin: 2 } }`, `
154
142
  `{ has: { mushroom: 3 } }`, `{ lacks: { coin: 1 } }`.
155
143
 
156
144
  ## Chests / corpses / shelves (multiple containers)
157
- The player inventory is just one container (the bag of `engine.actor`, id `'player'` locally). Chests, corpses, shelves and ammo boxes all use `inventory.container(id, { capacity })` to
158
- get or create one (calling again with the same id returns the same one); limits as above. A container has the same
159
- `add / remove / count / has / get / list / setData` as the inventory, plus `room(id)` (how many more fit) and `on('add' | 'remove', fn)` (returns a handle).
145
+ The player inventory is just one container (the bag of `engine.actor`). Chests, corpses, shelves and ammo boxes use `inventory.container(id, { capacity })`
146
+ to get or create one (the same id returns the same one); it has the inventory's methods plus `room(id)` and `on('add' | 'remove', fn)`.
160
147
  ```js
161
148
  const I = engine.inventory;
162
149
  const chest = I.container('chest-1', { capacity: 8 });
163
- chest.add('bandage', 2); // returns false if it doesn't fit (if part fits, that part is added)
150
+ chest.add('bandage', 2); // { ok: false, code: 'full' } if none fit; if part fits, that part goes in and `added` says how many
164
151
  I.transfer(chest, 'player', 'bandage', 1); // a container or a container id both work; returns how many were actually moved (fewer / 0 if the inventory is full)
165
152
  I.transfer('player', chest, 'coin', 5); // shelves and money boxes work the same way
166
153
  chest.on('remove', ({ id, count, actor }) => console.log(actor, 'took', id, count)); // every container emits item:add / item:remove with { container, actor, id, key, count, total }
@@ -170,13 +157,10 @@ chest.on('remove', ({ id, count, actor }) => console.log(actor, 'took', id, coun
170
157
  initial goods). Loading creates the containers first, and a later `container(id, { capacity })` in code just fills in the slot count, in either order.
171
158
  - **Deleting a world record does not delete its container automatically** (whether to keep a searched corpse is up to the game). To clear both:
172
159
  `engine.events.on('world:remove', ({ id }) => I.removeContainer(id))`.
173
- - **Pre-filled contents (initial semantics)**: goods are placed only the **first** time; on load the save wins, and a searched-empty container is not
174
- refilled after loading. Write `content/containers.js` in content (`export default { 'chest-1': { capacity: 8, items: { bandage: 2 } } }`, and put it
175
- in the export of `content/index.js`), or in code `I.container('chest-1', { capacity: 8, items: { bandage: 2 } })`. For an already existing container
176
- (created first by loading, or already created this session) `items` is not placed again; a container that was given goods goes into the save even
177
- when searched empty (`{}`), so after a refresh and load it is empty and not refilled. Don't fill with `container(id).add(...)` at startup: a
178
- container with nothing in it is not saved, so after a refresh it would be treated as new and filled again. A container id is any string and all are
179
- saved ('shop-bakery' and 'prop:chest:3' alike).
160
+ - **Pre-filled contents**: goods are placed only the **first** time; on load the save wins, and a searched-empty container is not refilled. Write
161
+ `content/containers.js` (`export default { 'chest-1': { capacity: 8, items: { bandage: 2 } } }`, exported from `content/index.js`), or in code
162
+ `I.container('chest-1', { capacity: 8, items: { bandage: 2 } })`. Don't fill with `container(id).add(...)` at startup: a container with nothing in it is
163
+ not saved, so after a refresh it would be treated as new and filled again.
180
164
  - **UI**: the engine only makes the player inventory window; for a chest UI draw `chest.list()` yourself, and clicking an entry runs
181
165
  `engine.ops.run('inventory.transfer', { from: 'chest-1', to: 'player', item: entry.key })`.
182
166
  - Non-empty containers appear in `describe()` under `inventory.containers`.
@@ -23,7 +23,7 @@ export default {
23
23
  },
24
24
  };
25
25
  ```
26
- `target` forms: a place name (its coordinates come from `engine.content.load(data, { places })` or a level marker, recipe 01), `{ place, x, z }`, `{ x, z }` (world coordinates; any of these may add `floor` / `y` for a storey on multi-layer ground,
26
+ `target` forms: a place name (its coordinates come from `content/places.js`, `engine.content.load(data, { places })` or a level marker, recipe 01), `{ place, x, z }`, `{ x, z }` (world coordinates; any of these may add `floor` / `y` for a storey on multi-layer ground,
27
27
  as in props), `{ npc: 'id in npcs.js' }`, `{ nearest: 'itemId' }` (the closest not-yet-picked-up pickup of that kind to the player; hidden
28
28
  automatically once picked up).
29
29
  In code you can also write a function `target: () => target or null` (evaluated every frame); to change the target of a manual marker use
@@ -69,6 +69,8 @@ engine.quests.start('slimes3');
69
69
  engine.vars.bump('slimes'); // each time one is defeated
70
70
  engine.events.on('quest:done', ({ id }) => { /* quest completed */ }); // there are also quest:start, quest:step, quest:part and quest:fail
71
71
  ```
72
+ A failed reward (full bag, refused `{ op }`, a function returning `{ ok: false, code }`) still finishes the quest and fires `quest:unpaid`. Items that did not fit stay owed (`quests.list()`, saved) until there is room, unless the game decides itself with `onUnpaid` (effect words, or `(e, answer) => ...`).
73
+
72
74
  To turn off automatic markers: `hud({ questMarkers: false })`. To add a marker by hand: `const m = engine.hud.marker('gate', { label: 'Gate' }); m.remove();`;
73
75
  content effects can add them too: `{ marker: 'gate' }` / `{ clearMarker: 'gate' }`. A counter in the screen corner:
74
76
  `engine.hud.counter('slimes', { label: 'Slimes', value: 2, max: 3 })`; `anchor: 'top-right'` (or `top`, `bottom`, `bottom-left`...) puts a counter
@@ -81,10 +83,9 @@ or bar in that screen column.
81
83
  `quests: {...}` line).
82
84
  In more detail: `engine.quests.list()` (each step has `current/done/target`), `engine.quests.isActive(id)`; story flags in `engine.vars.flags`.
83
85
  - Objective markers: `describe().hud.markers` has `{ label: quest title, distance: meters, onScreen }`; counters are in `describe().hud.counters`.
84
- - After advancing a condition you don't have to wait: `engine.quests.check()` checks immediately. Related test: `npm test -- 目标指示`.
86
+ - After advancing a condition you don't have to wait: `engine.quests.check()` checks immediately.
85
87
 
86
88
  ## Reading and moving progress from code
87
- `engine.quests.state(id)` gives `{ step, steps, done, failed, active }` (or null before it starts): a copy, so read it, never write it.
88
- A step the game finishes from its own code (a cutscene ended, a boss fell) can skip its condition: `engine.quests.advance(id)` moves to the next step
89
+ A step the game finishes from its own code (a cutscene ended, a fight was won) can skip its condition: `engine.quests.advance(id)` moves to the next step
89
90
  and completes the quest after the last one (reward, `quest:done`); call it from an op or a fixed step. A replacement quests module meets
90
91
  `modules/gameplay/quests.contract.js` (define / start / advance / state / list, events quest:start / quest:step / quest:done, save key quests).