threedog 0.2.1 → 0.7.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 (725) hide show
  1. package/CHANGELOG.md +371 -1
  2. package/README.md +21 -12
  3. package/core/Animator.js +15 -12
  4. package/core/Assets.js +92 -26
  5. package/core/Audio.js +45 -38
  6. package/core/Baked.js +30 -15
  7. package/core/Batching.js +102 -15
  8. package/core/Budget.js +40 -19
  9. package/core/Clock.js +40 -80
  10. package/core/DebugOverrides.js +75 -25
  11. package/core/Describe.js +105 -45
  12. package/core/Engine.js +203 -75
  13. package/core/Events.js +4 -1
  14. package/core/I18n.js +25 -13
  15. package/core/Input.js +175 -80
  16. package/core/Inspect.js +8 -5
  17. package/core/InspectMaterials.js +84 -0
  18. package/core/InspectPerf.js +68 -0
  19. package/core/InspectScene.js +13 -2
  20. package/core/Loading.js +2 -1
  21. package/core/MaterialInfo.js +7 -5
  22. package/core/Ops.js +50 -9
  23. package/core/Random.js +9 -2
  24. package/core/Rays.js +12 -7
  25. package/core/SaveStore.js +41 -9
  26. package/core/Saves.js +71 -15
  27. package/core/Stream.js +13 -10
  28. package/core/Threads.js +26 -7
  29. package/core/UrlState.js +69 -13
  30. package/core/Views.js +10 -6
  31. package/core/actor.js +1 -1
  32. package/core/adaptive.js +93 -0
  33. package/core/assetEntry.js +27 -7
  34. package/core/assetHot.js +176 -0
  35. package/core/assetLoad.js +44 -19
  36. package/core/assetManifest.js +53 -11
  37. package/core/assetReport.js +5 -5
  38. package/core/audioRules.js +13 -11
  39. package/core/audioVoice.js +69 -42
  40. package/core/batchGroups.js +9 -1
  41. package/core/canvasBox.js +1 -2
  42. package/core/catalog.js +21 -5
  43. package/core/cells.js +62 -0
  44. package/core/checks.js +10 -8
  45. package/core/chunkStream.js +87 -0
  46. package/core/control.js +149 -0
  47. package/core/copies.js +32 -0
  48. package/core/dayTime.js +12 -6
  49. package/core/debugView.js +85 -18
  50. package/core/describeRender.js +117 -21
  51. package/core/describeText.js +41 -21
  52. package/core/engineCamera.js +32 -0
  53. package/core/errorCodes.js +478 -32
  54. package/core/errorHints.js +41 -142
  55. package/core/errors.js +31 -8
  56. package/core/events.generated.js +13 -7
  57. package/core/gameLights.js +69 -0
  58. package/core/grayMap.js +20 -0
  59. package/core/grid.js +14 -13
  60. package/core/gridLoad.js +2 -1
  61. package/core/ground.js +6 -4
  62. package/core/headlessLoad.js +55 -0
  63. package/core/holds.js +78 -50
  64. package/core/inputContext.js +11 -7
  65. package/core/inputDefaults.js +24 -21
  66. package/core/inputPad.js +1 -1
  67. package/core/inputPointer.js +1 -1
  68. package/core/inputTouch.js +2 -2
  69. package/core/lifecycle.js +46 -12
  70. package/core/lightWatch.js +9 -5
  71. package/core/loop.js +109 -43
  72. package/core/math.js +18 -3
  73. package/core/moduleSlots.js +100 -0
  74. package/core/moduleTypes.js +86 -0
  75. package/core/modules.js +147 -29
  76. package/core/movement.js +2 -2
  77. package/core/namedModel.js +74 -0
  78. package/core/opsCheck.js +3 -3
  79. package/core/opsFail.js +15 -6
  80. package/core/opsGuard.js +4 -4
  81. package/core/opsRun.js +4 -3
  82. package/core/owned.js +171 -0
  83. package/core/page.js +44 -10
  84. package/core/params.js +30 -8
  85. package/core/pictureSlots.js +33 -0
  86. package/core/pictureWriters.js +343 -0
  87. package/core/plugins.js +245 -0
  88. package/core/saveApply.js +99 -17
  89. package/core/saveFiles.js +8 -6
  90. package/core/saveValues.js +46 -0
  91. package/core/saveVersions.js +20 -3
  92. package/core/scatter.js +48 -19
  93. package/core/sceneDelta.js +211 -0
  94. package/core/sceneMethods.js +31 -33
  95. package/core/screenToGround.js +1 -1
  96. package/core/services.js +27 -11
  97. package/core/session.js +28 -25
  98. package/core/shaderCost.js +78 -0
  99. package/core/shadowTypes.js +3 -2
  100. package/core/shadows.js +405 -0
  101. package/core/sharedPoint.js +303 -0
  102. package/core/skip.js +36 -28
  103. package/core/stackFrames.js +45 -0
  104. package/core/stacks.js +166 -0
  105. package/core/startup.js +153 -13
  106. package/core/streamSources.js +0 -11
  107. package/core/targeting.js +1 -1
  108. package/core/textureBytes.js +20 -0
  109. package/core/thingExplain.js +3 -3
  110. package/core/thingOps.js +29 -6
  111. package/core/things.js +22 -12
  112. package/core/threadPure.js +7 -3
  113. package/core/threePatches.js +47 -0
  114. package/core/tier.js +21 -10
  115. package/core/time.js +236 -0
  116. package/core/uiClock.js +25 -0
  117. package/core/util.js +8 -2
  118. package/core/validate.js +66 -87
  119. package/core/view.js +43 -0
  120. package/core/wrap.js +106 -0
  121. package/docs/AI.md +95 -104
  122. package/docs/API.md +35 -31
  123. package/docs/CODEMAP.md +231 -176
  124. package/docs/COMMANDS.md +63 -39
  125. package/docs/CONVENTIONS.md +99 -31
  126. package/docs/MIGRATING-0.3.md +248 -0
  127. package/docs/MIGRATING-0.4.md +320 -0
  128. package/docs/MIGRATING-0.5.md +68 -0
  129. package/docs/MIGRATING-0.6.md +126 -0
  130. package/docs/MIGRATING-0.7.md +39 -0
  131. package/docs/PERF.md +35 -7
  132. package/docs/THREE.md +82 -28
  133. package/docs/api/ambience.md +0 -1
  134. package/docs/api/assets.md +15 -11
  135. package/docs/api/audio.md +10 -14
  136. package/docs/api/budget.md +4 -0
  137. package/docs/api/calendar.md +41 -0
  138. package/docs/api/cameraRig.md +16 -5
  139. package/docs/api/characters.md +41 -24
  140. package/docs/api/clock.md +6 -5
  141. package/docs/api/collision.md +10 -7
  142. package/docs/api/content.md +6 -4
  143. package/docs/api/dialogue.md +9 -9
  144. package/docs/api/engine.md +95 -65
  145. package/docs/api/events.md +20 -14
  146. package/docs/api/grids.md +10 -3
  147. package/docs/api/ground.md +1 -1
  148. package/docs/api/hud.md +5 -2
  149. package/docs/api/i18n.md +1 -1
  150. package/docs/api/input.md +13 -7
  151. package/docs/api/interactions.md +10 -6
  152. package/docs/api/inventory.md +17 -17
  153. package/docs/api/level.md +0 -2
  154. package/docs/api/lightPool.md +3 -1
  155. package/docs/api/music.md +1 -1
  156. package/docs/api/nav.md +3 -0
  157. package/docs/api/occlusion.md +5 -0
  158. package/docs/api/openWorld.md +2 -1
  159. package/docs/api/particles.md +6 -3
  160. package/docs/api/photo.md +0 -2
  161. package/docs/api/pickups.md +21 -0
  162. package/docs/api/post.md +8 -5
  163. package/docs/api/quests.md +2 -3
  164. package/docs/api/rigid.md +16 -14
  165. package/docs/api/saves.md +6 -4
  166. package/docs/api/settings.md +2 -3
  167. package/docs/api/sky.md +18 -49
  168. package/docs/api/stream.md +1 -1
  169. package/docs/api/terrain.md +16 -7
  170. package/docs/api/terrainDraw.md +12 -0
  171. package/docs/api/timeline.md +3 -4
  172. package/docs/api/tools.md +32 -15
  173. package/docs/api/triggers.md +7 -10
  174. package/docs/api/vegetation.md +17 -9
  175. package/docs/api/vegetationDraw.md +10 -0
  176. package/docs/api/water.md +9 -21
  177. package/docs/api/weather.md +10 -15
  178. package/docs/api/weatherDraw.md +10 -0
  179. package/docs/api/world.md +3 -2
  180. package/docs/recipes/01-new-game.md +52 -42
  181. package/docs/recipes/02-npc.md +24 -7
  182. package/docs/recipes/03-items-pickups.md +57 -22
  183. package/docs/recipes/04-quests.md +12 -5
  184. package/docs/recipes/05-props-bake.md +174 -22
  185. package/docs/recipes/06-clock-events.md +100 -52
  186. package/docs/recipes/07-flow-scenes-pause.md +50 -10
  187. package/docs/recipes/08-weather-sky.md +134 -37
  188. package/docs/recipes/09-materials-lights-models.md +185 -0
  189. package/docs/recipes/10-blender-level.md +16 -4
  190. package/docs/recipes/11-vehicles.md +67 -10
  191. package/docs/recipes/13-animation.md +23 -9
  192. package/docs/recipes/14-custom-module.md +63 -29
  193. package/docs/recipes/15-perf.md +31 -10
  194. package/docs/recipes/16-dev-bridge.md +74 -40
  195. package/docs/recipes/18-world.md +26 -14
  196. package/docs/recipes/19-shooting-picking.md +12 -10
  197. package/docs/recipes/20-content-actions-save.md +60 -18
  198. package/docs/recipes/21-camera.md +55 -17
  199. package/docs/recipes/22-shop-gold.md +3 -3
  200. package/docs/recipes/23-ops.md +17 -11
  201. package/docs/recipes/26-ui-parts.md +86 -13
  202. package/docs/recipes/27-net.md +11 -5
  203. package/docs/recipes/28-terrain.md +36 -3
  204. package/docs/recipes/29-grid.md +46 -19
  205. package/docs/recipes/30-templates.md +72 -15
  206. package/docs/recipes/31-audio.md +20 -12
  207. package/docs/recipes/32-action-game.md +51 -4
  208. package/docs/recipes/34-environment-lighting.md +108 -21
  209. package/docs/recipes/35-picture-from-reference.md +147 -0
  210. package/docs/recipes/36-sky-ground-plants.md +158 -0
  211. package/docs/recipes/{37-terrain-look-hooks.md → 37-terrain-hooks.md} +9 -12
  212. package/docs/recipes/38-environment-hooks.md +67 -0
  213. package/docs/recipes/40-scene.md +114 -32
  214. package/docs/recipes/42-terrain-shape.md +2 -2
  215. package/docs/recipes/43-shader-patches-surfaces.md +206 -0
  216. package/docs/recipes/44-water-weather-hooks.md +191 -0
  217. package/docs/recipes/45-cascaded-shadows.md +130 -23
  218. package/docs/recipes/46-blender-art-route.md +17 -20
  219. package/docs/recipes/47-island-snow-backdrop.md +13 -15
  220. package/docs/recipes/49-game-module-contract.md +30 -17
  221. package/docs/recipes/50-own-renderer.md +4 -4
  222. package/docs/recipes/51-capability-catalog.md +3 -3
  223. package/docs/recipes/52-around-the-picture.md +181 -0
  224. package/docs/recipes/53-ground-up-close.md +12 -12
  225. package/docs/recipes/54-three-idioms.md +88 -0
  226. package/docs/recipes/55-mods-time-wrap.md +124 -0
  227. package/docs/recipes/56-webgpu-tsl.md +303 -0
  228. package/docs/recipes/57-control.md +104 -0
  229. package/docs/recipes/58-input.md +60 -0
  230. package/docs/recipes/59-depth-post-effects.md +83 -0
  231. package/docs/recipes/60-judge-the-picture.md +70 -0
  232. package/docs/recipes/61-deploy.md +27 -0
  233. package/docs/recipes/62-picture-code.md +244 -0
  234. package/docs/recipes/63-third-person-start.md +77 -0
  235. package/docs/recipes/64-particles.md +35 -0
  236. package/examples/action/.threedog/content-index.json +1 -0
  237. package/examples/action/GAMEMAP.md +20 -14
  238. package/examples/action/assets.js +8 -0
  239. package/examples/action/content/actions.js +1 -1
  240. package/examples/action/content/audio.js +5 -5
  241. package/examples/action/main.js +12 -15
  242. package/examples/action/models.js +23 -24
  243. package/examples/action/picture/index.js +13 -0
  244. package/examples/action/picture/lights.js +35 -0
  245. package/examples/action/picture/materials.js +8 -0
  246. package/examples/action/picture/palette.js +33 -0
  247. package/examples/plain-picture/.threedog/content-index.json +1 -0
  248. package/examples/plain-picture/FINDINGS.md +53 -0
  249. package/examples/plain-picture/GAMEMAP.md +90 -0
  250. package/examples/plain-picture/main.js +48 -0
  251. package/examples/plain-picture/picture/index.js +21 -0
  252. package/examples/plain-picture/picture/lights.js +54 -0
  253. package/examples/plain-picture/picture/materials.js +24 -0
  254. package/examples/plain-picture/picture/palette.js +16 -0
  255. package/examples/plain-picture/picture/sky.js +37 -0
  256. package/examples/pullable.json +133 -0
  257. package/examples/rc2d/.threedog/content-index.json +1 -0
  258. package/examples/rc2d/GAMEMAP.md +88 -0
  259. package/examples/rc2d/README.md +57 -0
  260. package/examples/rc2d/main.js +55 -0
  261. package/examples/rc2d/picture/index.js +18 -0
  262. package/examples/rc2d/picture/lights.js +11 -0
  263. package/examples/rc2d/picture/materials.js +18 -0
  264. package/examples/rc2d/picture/palette.js +15 -0
  265. package/examples/rc2d/picture/post.js +11 -0
  266. package/examples/rc2d/rc2d.js +187 -0
  267. package/examples/rc2d/shaders.js +144 -0
  268. package/examples/sheepisland/.threedog/content-index.json +1 -0
  269. package/examples/sheepisland/GAMEMAP.md +22 -17
  270. package/examples/sheepisland/assets.js +5 -0
  271. package/examples/sheepisland/content/templates.js +1 -1
  272. package/examples/sheepisland/content/vegetation.js +3 -1
  273. package/examples/sheepisland/main.js +29 -18
  274. package/examples/sheepisland/{style/models.js → models.js} +13 -24
  275. package/examples/sheepisland/picture/index.js +20 -0
  276. package/examples/sheepisland/picture/lights.js +34 -0
  277. package/examples/sheepisland/picture/materials.js +61 -0
  278. package/examples/sheepisland/picture/palette.js +60 -0
  279. package/examples/sheepisland/picture/sky.js +20 -0
  280. package/examples/sheepisland/views.js +1 -1
  281. package/examples/styletest/.threedog/content-index.json +1 -0
  282. package/examples/styletest/GAMEMAP.md +25 -22
  283. package/examples/styletest/assets.js +6 -0
  284. package/examples/styletest/content/templates.js +1 -1
  285. package/examples/styletest/content/vegetation.js +1 -1
  286. package/examples/styletest/main.js +25 -34
  287. package/examples/styletest/models.js +30 -30
  288. package/examples/styletest/params.js +2 -5
  289. package/examples/styletest/picture/env.js +38 -0
  290. package/examples/styletest/picture/index.js +16 -0
  291. package/examples/styletest/picture/lights.js +9 -0
  292. package/examples/styletest/picture/materials.js +28 -0
  293. package/examples/styletest/picture/palette.js +22 -0
  294. package/examples/techniques/contact-shadows/README.md +91 -0
  295. package/examples/techniques/contact-shadows/contactShadows.js +67 -0
  296. package/examples/techniques/contact-shadows/main.js +55 -0
  297. package/examples/techniques/contact-shadows/picture/index.js +14 -0
  298. package/examples/techniques/contact-shadows/picture/lights.js +34 -0
  299. package/examples/techniques/contact-shadows/picture/materials.js +12 -0
  300. package/examples/techniques/contact-shadows/picture/palette.js +17 -0
  301. package/examples/techniques/day-night-grade/README.md +83 -0
  302. package/examples/techniques/day-night-grade/main.js +41 -0
  303. package/examples/techniques/day-night-grade/picture/index.js +20 -0
  304. package/examples/techniques/day-night-grade/picture/lights.js +45 -0
  305. package/examples/techniques/day-night-grade/picture/materials.js +15 -0
  306. package/examples/techniques/day-night-grade/picture/palette.js +59 -0
  307. package/examples/techniques/day-night-grade/picture/post.js +25 -0
  308. package/examples/techniques/day-night-grade/picture/sky.js +33 -0
  309. package/examples/techniques/interior-light/README.md +106 -0
  310. package/examples/techniques/interior-light/interiorLight.js +47 -0
  311. package/examples/techniques/interior-light/main.js +87 -0
  312. package/examples/techniques/interior-light/picture/index.js +24 -0
  313. package/examples/techniques/interior-light/picture/lights.js +52 -0
  314. package/examples/techniques/interior-light/picture/materials.js +13 -0
  315. package/examples/techniques/interior-light/picture/palette.js +32 -0
  316. package/examples/techniques/interior-light/picture/sky.js +40 -0
  317. package/examples/techniques/modular-building/README.md +126 -0
  318. package/examples/techniques/modular-building/kit.js +426 -0
  319. package/examples/techniques/modular-building/main.js +39 -0
  320. package/examples/techniques/modular-building/picture/index.js +17 -0
  321. package/examples/techniques/modular-building/picture/lights.js +26 -0
  322. package/examples/techniques/modular-building/picture/materials.js +13 -0
  323. package/examples/techniques/modular-building/picture/palette.js +23 -0
  324. package/examples/techniques/night-lights/README.md +95 -0
  325. package/examples/techniques/night-lights/main.js +47 -0
  326. package/examples/techniques/night-lights/nightLights.js +95 -0
  327. package/examples/techniques/night-lights/picture/index.js +18 -0
  328. package/examples/techniques/night-lights/picture/lights.js +44 -0
  329. package/examples/techniques/night-lights/picture/materials.js +15 -0
  330. package/examples/techniques/night-lights/picture/palette.js +34 -0
  331. package/examples/techniques/night-lights/picture/post.js +9 -0
  332. package/examples/techniques/night-lights/picture/sky.js +36 -0
  333. package/examples/techniques/outlines-and-rim/README.md +59 -0
  334. package/examples/techniques/outlines-and-rim/main.js +61 -0
  335. package/examples/techniques/outlines-and-rim/outlines.js +64 -0
  336. package/examples/techniques/outlines-and-rim/picture/index.js +16 -0
  337. package/examples/techniques/outlines-and-rim/picture/lights.js +18 -0
  338. package/examples/techniques/outlines-and-rim/picture/materials.js +11 -0
  339. package/examples/techniques/outlines-and-rim/picture/palette.js +16 -0
  340. package/examples/techniques/outlines-and-rim/picture/post.js +10 -0
  341. package/examples/techniques/procedural-animation/README.md +79 -0
  342. package/examples/techniques/procedural-animation/creature.js +44 -0
  343. package/examples/techniques/procedural-animation/main.js +47 -0
  344. package/examples/techniques/procedural-animation/picture/index.js +15 -0
  345. package/examples/techniques/procedural-animation/picture/lights.js +35 -0
  346. package/examples/techniques/procedural-animation/picture/materials.js +10 -0
  347. package/examples/techniques/procedural-animation/picture/palette.js +16 -0
  348. package/examples/techniques/procedural-animation/picture/sky.js +31 -0
  349. package/examples/techniques/procedural-animation/proceduralAnim.js +118 -0
  350. package/examples/techniques/procedural-surface/README.md +69 -0
  351. package/examples/techniques/procedural-surface/main.js +65 -0
  352. package/examples/techniques/procedural-surface/picture/index.js +14 -0
  353. package/examples/techniques/procedural-surface/picture/lights.js +18 -0
  354. package/examples/techniques/procedural-surface/picture/materials.js +34 -0
  355. package/examples/techniques/procedural-surface/picture/palette.js +15 -0
  356. package/examples/techniques/procedural-surface/surface.js +120 -0
  357. package/examples/techniques/stylized-shading/README.md +74 -0
  358. package/examples/techniques/stylized-shading/main.js +62 -0
  359. package/examples/techniques/stylized-shading/picture/index.js +14 -0
  360. package/examples/techniques/stylized-shading/picture/lights.js +23 -0
  361. package/examples/techniques/stylized-shading/picture/materials.js +18 -0
  362. package/examples/techniques/stylized-shading/picture/palette.js +19 -0
  363. package/examples/techniques/stylized-shading/shading.js +131 -0
  364. package/examples/techniques/sun-and-key-light/README.md +133 -0
  365. package/examples/techniques/sun-and-key-light/keyLight.js +71 -0
  366. package/examples/techniques/sun-and-key-light/main.js +51 -0
  367. package/examples/techniques/sun-and-key-light/picture/index.js +13 -0
  368. package/examples/techniques/sun-and-key-light/picture/lights.js +33 -0
  369. package/examples/techniques/sun-and-key-light/picture/materials.js +9 -0
  370. package/examples/techniques/sun-and-key-light/picture/palette.js +29 -0
  371. package/examples/techniques/sun-and-key-light/picture/sky.js +16 -0
  372. package/examples/techniques/three-looks/README.md +21 -0
  373. package/examples/techniques/three-looks/main.js +58 -0
  374. package/examples/techniques/three-looks/picture/cartoon.js +23 -0
  375. package/examples/techniques/three-looks/picture/cinematic.js +27 -0
  376. package/examples/techniques/three-looks/picture/comic.js +27 -0
  377. package/examples/techniques/three-looks/picture/index.js +14 -0
  378. package/examples/techniques/three-looks/picture/sun.js +23 -0
  379. package/examples/techniques/wet-road/README.md +102 -0
  380. package/examples/techniques/wet-road/main.js +48 -0
  381. package/examples/techniques/wet-road/picture/index.js +17 -0
  382. package/examples/techniques/wet-road/picture/lights.js +57 -0
  383. package/examples/techniques/wet-road/picture/materials.js +16 -0
  384. package/examples/techniques/wet-road/picture/palette.js +24 -0
  385. package/examples/techniques/wet-road/picture/sky.js +46 -0
  386. package/examples/techniques/wet-road/wetRoad.js +209 -0
  387. package/examples/webgpu-tsl/.threedog/content-index.json +1 -0
  388. package/examples/webgpu-tsl/GAMEMAP.md +89 -0
  389. package/examples/webgpu-tsl/README.md +45 -0
  390. package/examples/webgpu-tsl/main.js +44 -0
  391. package/examples/webgpu-tsl/picture/index.js +18 -0
  392. package/examples/webgpu-tsl/picture/lights.js +25 -0
  393. package/examples/webgpu-tsl/picture/materials.js +36 -0
  394. package/examples/webgpu-tsl/picture/palette.js +23 -0
  395. package/examples/webgpu-tsl/picture/post.js +16 -0
  396. package/examples/webgpu-tsl/picture/sky.js +30 -0
  397. package/examples/world/.threedog/content-index.json +1 -0
  398. package/examples/world/GAMEMAP.md +31 -21
  399. package/examples/world/art/humanoid.js +38 -0
  400. package/examples/world/art/index.js +11 -0
  401. package/examples/world/art/models.js +57 -0
  402. package/examples/world/art/shapes.js +9 -0
  403. package/examples/world/assets.js +6 -0
  404. package/examples/world/content/audio.js +5 -5
  405. package/examples/world/content/items.js +1 -1
  406. package/examples/world/content/npcs.js +1 -1
  407. package/examples/world/content/props.js +1 -1
  408. package/examples/world/content/rules.js +1 -1
  409. package/examples/world/content/templates.js +1 -1
  410. package/examples/world/content/vegetation.js +1 -1
  411. package/examples/world/main.js +22 -18
  412. package/examples/world/models.js +17 -7
  413. package/examples/world/picture/index.js +20 -0
  414. package/examples/world/picture/lights.js +41 -0
  415. package/examples/world/picture/materials.js +34 -0
  416. package/examples/world/picture/palette.js +74 -0
  417. package/examples/world/picture/post.js +9 -0
  418. package/examples/world/picture/sky.js +39 -0
  419. package/index.d.ts +44 -54
  420. package/index.js +29 -25
  421. package/llms.txt +24 -15
  422. package/modules/ambience/Ambience.js +34 -23
  423. package/modules/calendar/Calendar.js +163 -0
  424. package/modules/calendar/contract.js +21 -0
  425. package/modules/calendar/index.js +82 -0
  426. package/modules/{sky → calendar}/schedule.js +17 -16
  427. package/modules/calendar/seasons.js +55 -0
  428. package/modules/camera/FirstPersonCamera.js +6 -15
  429. package/modules/camera/FixedCamera.js +33 -15
  430. package/modules/camera/FollowCamera.js +90 -16
  431. package/modules/camera/RtsCamera.js +18 -17
  432. package/modules/camera/common.js +73 -20
  433. package/modules/camera/contract.js +17 -0
  434. package/modules/camera/projection.js +11 -24
  435. package/modules/characters/Character.js +188 -48
  436. package/modules/characters/NPC.js +92 -41
  437. package/modules/characters/assetModel.js +8 -16
  438. package/modules/characters/behaviors.js +2 -1
  439. package/modules/characters/contract.js +13 -0
  440. package/modules/characters/footsteps.js +1 -1
  441. package/modules/characters/index.js +112 -49
  442. package/modules/characters/moveHelpers.js +4 -5
  443. package/modules/characters/movers/common.js +102 -19
  444. package/modules/characters/movers/manual.js +23 -0
  445. package/modules/characters/movers/rapier.js +19 -16
  446. package/modules/characters/movers/simple.js +14 -11
  447. package/modules/characters/movers/support.js +186 -0
  448. package/modules/characters/npcAvoid.js +47 -42
  449. package/modules/characters/npcSim.js +17 -9
  450. package/modules/characters/npcView.js +44 -16
  451. package/modules/characters/pathAsync.js +7 -3
  452. package/modules/characters/playerStrings.js +4 -3
  453. package/modules/characters/proceduralRig.js +19 -4
  454. package/modules/characters/useModel.js +2 -2
  455. package/modules/characters/vehicle.contract.js +21 -0
  456. package/modules/characters/walkTo.js +21 -7
  457. package/modules/collision/Collision.js +69 -27
  458. package/modules/collision/grid.js +8 -6
  459. package/modules/content/explain.js +2 -2
  460. package/modules/content/fields.js +102 -0
  461. package/modules/content/ids.js +8 -6
  462. package/modules/content/index.js +104 -27
  463. package/modules/content/loader.js +45 -33
  464. package/modules/content/models.js +58 -42
  465. package/modules/content/packs.js +6 -5
  466. package/modules/content/parts.js +41 -0
  467. package/modules/content/props.js +20 -11
  468. package/modules/content/rules.js +66 -0
  469. package/modules/content/stages.js +80 -0
  470. package/modules/content/templates.js +123 -30
  471. package/modules/debug/DebugPanel.js +24 -17
  472. package/modules/flow/contract.js +16 -0
  473. package/modules/flow/index.js +21 -15
  474. package/modules/gameplay/Container.js +41 -32
  475. package/modules/gameplay/Containers.js +30 -15
  476. package/modules/gameplay/Dialogue.js +113 -55
  477. package/modules/gameplay/Interactions.js +273 -72
  478. package/modules/gameplay/Inventory.js +72 -76
  479. package/modules/gameplay/Quests.js +75 -39
  480. package/modules/gameplay/boxOps.js +3 -3
  481. package/modules/gameplay/dialogue.contract.js +21 -0
  482. package/modules/gameplay/dialogueBox.js +4 -2
  483. package/modules/gameplay/dialogueBubbles.js +116 -0
  484. package/modules/gameplay/interactionPrompt.js +4 -1
  485. package/modules/gameplay/interactions.contract.js +16 -0
  486. package/modules/gameplay/inventory.contract.js +23 -0
  487. package/modules/gameplay/inventoryOps.js +19 -17
  488. package/modules/gameplay/pickups.js +306 -85
  489. package/modules/gameplay/questLog.js +6 -6
  490. package/modules/gameplay/quests.contract.js +17 -0
  491. package/modules/grid/Grid.js +92 -50
  492. package/modules/grid/Layer.js +27 -13
  493. package/modules/grid/index.js +96 -43
  494. package/modules/grid/ops.js +20 -18
  495. package/modules/grid/preview.js +37 -29
  496. package/modules/grid/strings.js +12 -0
  497. package/modules/grid/tiles.js +19 -22
  498. package/modules/hlod/index.js +52 -19
  499. package/modules/hud/index.js +48 -20
  500. package/modules/hud/parts.js +28 -13
  501. package/modules/level/heightfield.js +3 -1
  502. package/modules/level/index.js +49 -23
  503. package/modules/level/nodes.js +4 -3
  504. package/modules/lights/index.js +47 -19
  505. package/modules/music/Music.js +38 -21
  506. package/modules/music/rules.js +1 -1
  507. package/modules/nav/index.js +48 -42
  508. package/modules/net/Client.js +13 -6
  509. package/modules/net/Host.js +19 -5
  510. package/modules/net/Net.js +2 -1
  511. package/modules/net/index.js +13 -8
  512. package/modules/net/sync.js +9 -8
  513. package/modules/net/transports.js +77 -27
  514. package/modules/particles/Particles.js +58 -28
  515. package/modules/particles/contract.js +17 -0
  516. package/modules/particles/effect.js +54 -11
  517. package/modules/photo/Photo.js +56 -38
  518. package/modules/rigid/RigidBodies.js +194 -32
  519. package/modules/rigid/Vehicles.js +18 -15
  520. package/modules/rigid/sync.js +62 -17
  521. package/modules/settings/Settings.js +60 -55
  522. package/modules/settings/apply.js +38 -3
  523. package/modules/settings/sections.js +5 -3
  524. package/modules/settings/strings.js +3 -2
  525. package/modules/settings/view.js +5 -3
  526. package/modules/sky/Sky.js +132 -205
  527. package/modules/sky/clouds.js +37 -23
  528. package/modules/sky/dome.js +100 -0
  529. package/modules/sky/domeLayers.js +30 -15
  530. package/modules/sky/environment.js +45 -99
  531. package/modules/sky/fog.js +9 -139
  532. package/modules/sky/frame.js +60 -56
  533. package/modules/sky/season.js +21 -0
  534. package/modules/sky/shader.js +63 -35
  535. package/modules/sky/skyModule.js +52 -37
  536. package/modules/sky/tint.js +59 -0
  537. package/modules/terrain/ChunkManager.js +194 -110
  538. package/modules/terrain/chunkJob.js +1 -1
  539. package/modules/terrain/chunkQueries.js +6 -4
  540. package/modules/terrain/draw.js +154 -0
  541. package/modules/terrain/index.js +87 -54
  542. package/modules/terrain/terrainDefaults.js +2 -2
  543. package/modules/terrain/terrainEdit.js +18 -20
  544. package/modules/terrain/terrainGen.js +6 -4
  545. package/modules/terrain/terrainIsland.js +5 -4
  546. package/modules/terrain/terrainShape.js +12 -12
  547. package/modules/terrain/terrainShapeMain.js +8 -7
  548. package/modules/terrain/terrainTexture.js +21 -19
  549. package/modules/timeline/Timeline.js +95 -43
  550. package/modules/timeline/Tween.js +18 -10
  551. package/modules/timeline/letterbox.js +2 -2
  552. package/modules/timeline/shots.js +5 -1
  553. package/modules/triggers/index.js +111 -76
  554. package/modules/vegetation/Vegetation.js +229 -112
  555. package/modules/vegetation/densityMap.js +62 -0
  556. package/modules/vegetation/draw.js +191 -0
  557. package/modules/vegetation/groundChunks.js +52 -58
  558. package/modules/vegetation/index.js +32 -11
  559. package/modules/vegetation/modelGeometry.js +3 -2
  560. package/modules/vegetation/nearFade.js +8 -2
  561. package/modules/water/Water.js +157 -72
  562. package/modules/water/surface.js +86 -47
  563. package/modules/weather/Weather.js +96 -103
  564. package/modules/weather/particles.js +37 -14
  565. package/modules/weather/shaders.js +1 -1
  566. package/modules/weather/strings.js +2 -2
  567. package/modules/weather/weatherDraw.js +141 -0
  568. package/modules/world/World.js +26 -9
  569. package/modules/world/explain.js +1 -1
  570. package/modules/world/index.js +18 -4
  571. package/modules/world/persist.js +62 -2
  572. package/modules/world/pos.js +3 -2
  573. package/modules/world/records.js +8 -6
  574. package/modules/world/sim.js +60 -20
  575. package/modules/world/simFar.js +4 -3
  576. package/modules/world/state.js +3 -2
  577. package/modules/world/thingSource.js +1 -1
  578. package/modules/world/views.js +8 -6
  579. package/package.json +8 -3
  580. package/presets.js +43 -29
  581. package/render/PostFX.js +318 -135
  582. package/render/backend.js +486 -0
  583. package/render/cascades.js +195 -0
  584. package/render/cascades.tsl.js +96 -0
  585. package/render/daylight.js +39 -0
  586. package/render/detail.js +122 -41
  587. package/render/effects.js +155 -48
  588. package/render/engineUniforms.js +10 -1
  589. package/render/fuse.js +5 -4
  590. package/render/fx/cel.tsl.js +42 -0
  591. package/render/fx/cloudShadow.tsl.js +16 -0
  592. package/render/fx/detail.tsl.js +66 -0
  593. package/render/fx/index.js +28 -0
  594. package/render/fx/lighting.tsl.js +28 -0
  595. package/render/fx/nodeErrors.tsl.js +68 -0
  596. package/render/fx/noise.tsl.js +12 -0
  597. package/render/fx/objectOrigin.tsl.js +42 -0
  598. package/render/fx/particles.tsl.js +139 -0
  599. package/render/fx/patchNodes.tsl.js +403 -0
  600. package/render/fx/postWebGPU.tsl.js +181 -0
  601. package/render/fx/season.tsl.js +13 -0
  602. package/render/fx/sky.tsl.js +187 -0
  603. package/render/fx/uniforms.tsl.js +67 -0
  604. package/render/fx/water.tsl.js +53 -0
  605. package/render/fx/wind.tsl.js +22 -0
  606. package/render/fxNumbers.js +36 -0
  607. package/render/hotGlsl.js +24 -0
  608. package/render/layers.js +14 -0
  609. package/render/lighting.js +71 -18
  610. package/render/lightmap.js +142 -0
  611. package/render/lights.js +47 -6
  612. package/render/materials.js +55 -152
  613. package/render/modeling.js +73 -0
  614. package/render/neutral.js +23 -0
  615. package/render/occlusion.js +184 -0
  616. package/render/ownFrame.js +76 -0
  617. package/render/patches.js +317 -35
  618. package/render/postWebGL.js +205 -0
  619. package/render/probes.js +288 -0
  620. package/render/shaderErrors.js +154 -0
  621. package/render/slots.js +165 -0
  622. package/render/terms.js +163 -0
  623. package/render/uniformDecl.js +4 -3
  624. package/types/common.d.ts +2 -2
  625. package/types/core.d.ts +757 -346
  626. package/types/gameplay.d.ts +539 -330
  627. package/types/generated/core/Audio.d.ts +26 -42
  628. package/types/generated/core/Batching.d.ts +6 -2
  629. package/types/generated/core/Budget.d.ts +2 -8
  630. package/types/generated/core/DebugOverrides.d.ts +58 -9
  631. package/types/generated/core/I18n.d.ts +2 -2
  632. package/types/generated/core/Input.d.ts +110 -32
  633. package/types/generated/core/Ops.d.ts +31 -0
  634. package/types/generated/core/Random.d.ts +2 -2
  635. package/types/generated/core/Saves.d.ts +10 -2
  636. package/types/generated/core/Stream.d.ts +1 -1
  637. package/types/generated/core/Threads.d.ts +4 -1
  638. package/types/generated/core/Views.d.ts +0 -1
  639. package/types/generated/core/audioVoice.d.ts +17 -9
  640. package/types/generated/core/control.d.ts +55 -0
  641. package/types/generated/core/page.d.ts +9 -2
  642. package/types/generated/core/session.d.ts +2 -1
  643. package/types/generated/modules/ambience/Ambience.d.ts +0 -9
  644. package/types/generated/modules/calendar/Calendar.d.ts +84 -0
  645. package/types/generated/modules/calendar/index.d.ts +10 -0
  646. package/types/generated/modules/debug/DebugPanel.d.ts +2 -2
  647. package/types/generated/modules/grid/Grid.d.ts +61 -25
  648. package/types/generated/modules/grid/Layer.d.ts +13 -5
  649. package/types/generated/modules/grid/index.d.ts +56 -20
  650. package/types/generated/modules/music/Music.d.ts +5 -3
  651. package/types/generated/modules/net/index.d.ts +3 -3
  652. package/types/generated/modules/net/transports.d.ts +12 -3
  653. package/types/generated/modules/particles/Particles.d.ts +13 -6
  654. package/types/generated/modules/sky/Sky.d.ts +85 -110
  655. package/types/generated/modules/sky/skyModule.d.ts +1 -1
  656. package/types/generated/modules/timeline/Timeline.d.ts +8 -6
  657. package/types/generated/modules/water/Water.d.ts +50 -3
  658. package/types/generated/modules/weather/Weather.d.ts +44 -15
  659. package/types/generated/modules/weather/weatherDraw.d.ts +11 -0
  660. package/types/generated/modules/world/World.d.ts +20 -5
  661. package/types/generated/render/PostFX.d.ts +109 -29
  662. package/types/generated/render/lighting.d.ts +29 -0
  663. package/types/generated/render/materials.d.ts +31 -50
  664. package/types/generated/render/modeling.d.ts +30 -0
  665. package/types/generated/render/occlusion.d.ts +13 -0
  666. package/types/generated/render/patches.d.ts +16 -2
  667. package/types/generated/ui/UI.d.ts +6 -3
  668. package/types/nav.d.ts +6 -0
  669. package/types/physics.d.ts +140 -45
  670. package/types/tsl.d.ts +94 -0
  671. package/types/world.d.ts +489 -122
  672. package/ui/Focus.js +35 -14
  673. package/ui/LoadingScreen.js +3 -3
  674. package/ui/Parts.js +35 -15
  675. package/ui/UI.js +27 -17
  676. package/ui/cursor.js +115 -0
  677. package/ui/defaults.js +15 -11
  678. package/ui/theme.js +36 -27
  679. package/ui/touchPart.js +2 -2
  680. package/core/claims.js +0 -51
  681. package/core/look/coreParts.js +0 -112
  682. package/core/look/layers.js +0 -136
  683. package/core/look/part.js +0 -173
  684. package/core/look/report.js +0 -79
  685. package/core/look/write.js +0 -86
  686. package/core/renamed.js +0 -22
  687. package/core/styleParts.js +0 -98
  688. package/docs/api/entities.md +0 -61
  689. package/docs/api/style.md +0 -134
  690. package/docs/recipes/09-style-pack.md +0 -169
  691. package/docs/recipes/35-style-from-reference.md +0 -84
  692. package/docs/recipes/36-sky-ground-plant-looks.md +0 -118
  693. package/docs/recipes/38-environment-look-hooks.md +0 -88
  694. package/docs/recipes/41-thing-registry.md +0 -93
  695. package/docs/recipes/43-shader-patches-surface-looks.md +0 -135
  696. package/docs/recipes/44-water-weather-look-hooks.md +0 -135
  697. package/docs/recipes/48-make-material.md +0 -70
  698. package/docs/recipes/52-look.md +0 -146
  699. package/examples/action/look.js +0 -5
  700. package/examples/sheepisland/style/index.js +0 -79
  701. package/examples/styletest/look.js +0 -11
  702. package/examples/styletest/overrides.js +0 -33
  703. package/examples/styletest/panel.js +0 -135
  704. package/modules/entities/Entities.js +0 -243
  705. package/modules/entities/build.js +0 -25
  706. package/modules/entities/index.js +0 -4
  707. package/modules/sky/calendar.js +0 -80
  708. package/modules/sky/cascades.js +0 -125
  709. package/modules/sky/layers.js +0 -69
  710. package/modules/sky/look.js +0 -51
  711. package/modules/sky/lookFog.js +0 -80
  712. package/modules/sky/lookShadow.js +0 -50
  713. package/modules/sky/lookSky.js +0 -108
  714. package/modules/sky/shadow.js +0 -74
  715. package/modules/terrain/chunkLevels.js +0 -40
  716. package/modules/terrain/lookGround.js +0 -61
  717. package/modules/terrain/mountTerrain.js +0 -32
  718. package/modules/vegetation/lookWind.js +0 -37
  719. package/modules/water/look.js +0 -80
  720. package/modules/weather/look.js +0 -75
  721. package/modules/world/cells.js +0 -42
  722. package/render/lookSurface.js +0 -161
  723. package/render/postLook.js +0 -86
  724. package/render/surface.js +0 -69
  725. package/types/style.d.ts +0 -643
@@ -1,55 +1,76 @@
1
- // Chunk streaming: chunks around the engine.stream sources (player, camera focus, teleport destination...) are generated on engine.threads workers,
2
- // uploaded to the GPU when in view, released when far from all sources.
1
+ // Terrain data part: chunk streaming. Chunks around the engine.stream sources (player, camera focus, teleport destination...) are generated on
2
+ // engine.threads workers, kept while near a source, released when far from all.
3
3
  // LOD is split by ring from the nearest source: the chunk a source stands in plus the one ring around it is ring 1, and so on.
4
- // Visuals and gameplay take effect separately: a finished model is uploaded and shown at once; tree collision (forEachCollider, chunkCollision) only takes
5
- // effect at the tick set by engine.commits (c.solid),
6
- // and is generated on the main thread on the spot if not done by then -- machine speed never changes whether the player bumps into a tree (see
7
- // core/Commits.js).
4
+ // Visuals and gameplay take effect separately: a generated chunk is handed to the looks at once; collision (forEachCollider, chunkCollision) only takes
5
+ // effect at the tick set by engine.commits (c.solid), and is generated on the main thread on the spot if not done by then -- machine speed never
6
+ // changes whether the player bumps into a tree (see core/Commits.js).
7
+ // Data only: this file makes no mesh and touches no material. Each generated chunk keeps its arrays in c.data (pos, nor, col, uv, tex, top...),
8
+ // collision and queries read them, and draw parts subscribe with view({ add, change, remove, show }) (terrain/draw.js is the engine's own).
9
+ // Vegetation plugs in as the chunk planter (its data part sets terrain.plants): this file never reads engine.vegetation.
8
10
  import * as THREE from 'three';
9
11
  import { createTerrain } from './terrainGen.js';
10
12
  import { chunkHandler } from './chunkJob.js';
11
13
  import { TerrainEdits } from './terrainEdit.js';
12
- import { terrainMaterial } from '../../render/materials.js';
13
- import { chunkRing } from '../../core/streamSources.js';
14
+ import { ChunkStream } from '../../core/chunkStream.js';
14
15
  import { chunkQueries } from './chunkQueries.js';
15
- import { chunkLevels, NO_VEG } from './chunkLevels.js';
16
- import { mountTerrain } from './mountTerrain.js';
17
- import { disposeColorMap } from './terrainTexture.js';
16
+ import { reportError } from '../../core/errors.js';
17
+ import { codedError } from '../../core/errorHints.js';
18
18
 
19
+ /** Planter stand-in while no vegetation is installed (the vegetation data part replaces it) */
20
+ const NO_VEG = { baseNames: () => [], nearNames: () => [], list: () => [], get: () => null, mount() {}, unmount() {}, drop() {} };
21
+ // A failed ground job is sent again up to this many times in all (a worker that crashed or ran out of memory usually passes next time); then the
22
+ // chunk is marked failed and reported. Before, it sat in 'pending' for ever and the loading screen waited without a word.
23
+ const MAX_TRIES = 3;
19
24
  const COLLIDER_LAG = 30; // base delay before chunk collision takes effect (fixed steps, 30 = 0.5 s), multiplied by (1 + ring)
20
25
 
21
26
  export class ChunkManager {
22
- constructor(engine, terrainCfg, material = null) {
27
+ constructor(engine, terrainCfg) {
23
28
  this.engine = engine;
24
29
  this.T = createTerrain(terrainCfg); // main-thread copy: height queries for the character and camera
25
30
  this.chunks = new Map();
26
31
  this.viewChunks = 4; // unit: chunks
27
32
  this.density = 1;
28
- this.applyBudgetMs = 3; // max ms per frame spent uploading results to the GPU
33
+ this.applyBudgetMs = 3; // max ms per frame spent taking worker results
29
34
  this.maxInFlight = 4;
30
35
  this.inFlight = 0;
31
36
  this.ready = [];
32
37
  this._want = []; // chunks not yet dispatched (nearest first)
33
- // +1 when the chunk table is cleared / deleted from (update uses it to decide whether to rebuild the pending list)
34
- this._ver = 0;
35
- this._wantFor = [-1, -1]; // view distance and _ver the pending list was last built for
36
38
  this.gen = 0;
37
- this.stats = { builtThisFrame: 0, applyMs: 0, queued: 0 };
38
- this.terrainMat = terrainMaterial(typeof material === 'function' ? material(engine) : material, engine);
39
- this.centers = []; // stream sources in chunk units: { cx, cz, R, simple } (set by update)
40
- this.sideMat = null; // shape.side.material: island sides and bottoms
39
+ this.vgen = 0; // +1 on a density change: plants placed with the old density are asked again
40
+ this.stats = { builtThisFrame: 0, applyMs: 0, queued: 0, failed: 0 };
41
+ /** @internal the draw parts drawing these chunks (view()) */ this.views = new Set();
42
+ /** @internal the vegetation data part, or NO_VEG */ this.plants = NO_VEG;
43
+ /** @internal the engine's terrain drawing (draw.js), null when a game's picture holds the slot */ this.drawPart = null;
41
44
  this.lowest = 0; // lowest island point loaded (default voidY)
42
- this._frustum = new THREE.Frustum();
43
- this._m = new THREE.Matrix4();
45
+ // which chunks the sources need, ring, culling: shared with vegetation's own-ground chunks (core/chunkStream.js)
46
+ this._stream = new ChunkStream(this, { show: (c, v) => this._emit('show', c, v), level: (c, ring) => this._setLevel(c, ring),
47
+ count: c => { let n = 0; for (const k in c.plants) n += c.plants[k].n; return n; } });
44
48
 
45
- // one lane of chunk workers (engine.threads); with threads: false or no Worker the same handler runs on the main thread, and a crashed worker falls back to
46
- // it
49
+ // one lane of chunk workers (engine.threads); with threads: false or no Worker the same handler runs on the main thread, and a crashed worker
50
+ // falls back to it
47
51
  this.lane = engine.threads.lane({ create: () => new Worker(new URL('./chunkWorker.js', import.meta.url), { type: 'module' }), local: chunkHandler });
48
52
  this.lane.broadcast({ type: 'init', terrain: terrainCfg, species: {} }, 'init');
49
53
  /** @internal edit records (saved with the save) */ this.edits = new TerrainEdits(engine, this);
50
54
  }
51
55
 
52
56
  get CHUNK() { return this.T.CHUNK; }
57
+ // the draw part's entries, here because engine.terrain is where a game looks for them; this file stays data only
58
+ /** @internal */
59
+ _drawPart() { return this.drawPart ?? (() => { throw codedError('terrain-option', "the engine's terrain drawing is not installed: a draw part that replaces 'terrain-draw' draws the ground its own way"); })(); }
60
+ /** Ground material (see TerrainDraw): get the one in use (null under a replaced draw part), set one to swap it on every chunk, drawn as given */
61
+ get material() { return this.drawPart?.material ?? null; }
62
+ set material(m) { this._drawPart().material = m; }
63
+ /** The engine's ground patches (world, clouds, season, detail): applyEffects(myMaterial, { patches: engine.terrain.patches }) */
64
+ get patches() { return this.drawPart?.patches ?? []; }
65
+ /** The detail layer's { value } uniforms, live ({} without a detail layer) */
66
+ get uniforms() { return this.drawPart?.uniforms ?? {}; }
67
+ /**
68
+ * Change at run time what terrain({...}) baked in; colors, biomeColors, steep, variation, shading, normals rebuild every chunk, detail only the material
69
+ * @example engine.terrain.recolor({ colors: { grass: 0x6a8a3a }, biomeColors: { meadow: ['grass'] } });
70
+ * @param {any} o
71
+ * @returns {void}
72
+ */
73
+ recolor(o) { this._drawPart().recolor(o); }
53
74
  /**
54
75
  * Below it the player or a moving body fell out of the world (terrain:void): shape.voidY, else 50 m under the lowest island
55
76
  * chunk loaded (at most -50); -Infinity without a shape
@@ -62,7 +83,7 @@ export class ChunkManager {
62
83
  * Change the ground: dig, raise, flatten, or paint the ground type. Call it from an op or a fixed step (it is saved gameplay state).
63
84
  * Heights snap to grid points and paint to cells (cellSize); the nearest one is taken when the shape is smaller than a cell.
64
85
  * engine.surface / slope / groundType, collision, paths and vegetation (what grew there is removed) follow at once; it is saved,
65
- * and a chunk unloaded and generated again comes back edited. Paint colors come from biomeColors[type] (gray when the game's style has none).
86
+ * and a chunk unloaded and generated again comes back edited. Paint colors come from biomeColors[type] (gray when the game gave none).
66
87
  * @param {import('three').Vector3 | {x:number,z:number} | number[]} position
67
88
  * @param {{ radius?: number, shape?: 'circle' | 'square', raise?: number, lower?: number, flatten?: number, paint?: string | null }} opts
68
89
  * radius meters (default half a cell); one of raise / lower (meters) / flatten (target height); paint a type name, null gives back the generated type
@@ -75,12 +96,43 @@ export class ChunkManager {
75
96
  */
76
97
  edit(position, opts) { return this.edits.edit(position, opts); }
77
98
 
78
- /** @internal vegetation plumbing */
99
+ /**
100
+ * Draw these chunks. Hooks: add(c) (generated: c.data holds the arrays pos / nor / col / uv / tex, c.cx / c.cz the chunk), change(c) (an edit
101
+ * rewrote c.data, same vertex count), remove(c) (released), show(c, visible) (in the camera view or not). Chunks already loaded are added at
102
+ * once. This is how a draw part that replaces 'terrain-draw' draws the ground. Returns { remove() } (ctx.track it).
103
+ * @example ctx.track(engine.terrain.view({ add(c) { draw(c) }, remove(c) { undraw(c) } }))
104
+ * @param {{ add?: (c: any) => void, change?: (c: any) => void, remove?: (c: any) => void, show?: (c: any, visible: boolean) => void }} v
105
+ * @returns {{ remove(): void }}
106
+ */
107
+ /**
108
+ * Hand the terrain its planter (the vegetation data part calls this): it is told when chunks mount, unmount and drop. Returns a handle;
109
+ * remove() puts the empty planter back if this one is still set.
110
+ * @param {object} planter
111
+ * @returns {{ remove(): void }}
112
+ */
113
+ setPlanter(planter) {
114
+ this.plants = planter;
115
+ return { remove: () => { if (this.plants === planter) this.plants = NO_VEG; } };
116
+ }
117
+
118
+ view(v) {
119
+ this.views.add(v);
120
+ for (const c of this.chunks.values()) if (c.state === 'ready') v.add?.(c);
121
+ return { remove: () => { if (!this.views.delete(v)) return; for (const c of this.chunks.values()) if (c.state === 'ready') v.remove?.(c); } };
122
+ }
123
+ /** @internal tell every view */
124
+ _emit(k, c, a) { for (const v of this.views) v[k]?.(c, a); }
125
+
126
+ /**
127
+ * @internal vegetation plumbing: a species was added or defined again. Only its plants are placed again on the loaded chunks; the ground,
128
+ * its collision and the other species stay (before, the whole terrain was dropped: about 1 s with no ground collision and no trees)
129
+ */
79
130
  registerSpecies(name, rule) {
80
131
  this.lane.broadcast({ type: 'species', name, rule }, 'species:' + name);
81
- this.rebuild();
132
+ if (!this.plants.get(name)?.nearOnly) this._regrow([name]);
133
+ else for (const c of this.chunks.values()) { c.detailDone.delete(name); c.level = -1; }
82
134
  }
83
- /** Replace the terrain config in every worker (height map loaded); species is the full rule table */
135
+ /** Replace the terrain config in every worker (height map loaded, recolor); species is the full rule table */
84
136
  reinit(terrainCfg, species) {
85
137
  this.T = createTerrain(terrainCfg);
86
138
  this.edits.attach();
@@ -92,42 +144,75 @@ export class ChunkManager {
92
144
  _send(job) {
93
145
  this.inFlight++;
94
146
  const t0 = performance.now(); // measure
95
- this.lane.run(job).then(r => { this.inFlight--; this.engine.budget.cost.transit(t0, r); this.ready.push(r); this._pump(); });
147
+ this.lane.run(job).then(r => { this.inFlight--; this.engine.budget.cost.transit(t0, r); this.ready.push(r); this._pump(); },
148
+ err => { this.inFlight--; this._failed(job, err); this._pump(); });
149
+ }
150
+ // A job that threw or whose worker died. Its slot is freed here (otherwise maxInFlight failures stop streaming for good). A ground job is
151
+ // queued again until MAX_TRIES; after that the chunk is 'failed', counted in describe().perf.chunks.failed, emitted as terrain:chunkFailed and
152
+ // reported with the chunk and the cause. A plants-only job marks its species done so the LOD pass does not ask again every ring change.
153
+ _failed(job, err) {
154
+ const key = job.cx + ',' + job.cz, c = this.chunks.get(key);
155
+ if (!c || job.gen !== this.gen) return;
156
+ if (!job.terrain) {
157
+ if (job.regrow) c.regrow--;
158
+ c.pendingDetail = false; for (const name of job.species || []) c.detailDone.add(name);
159
+ reportError(this.engine, err, 'terrain chunk worker job'); // one key: a broken rule fails every chunk, report it once
160
+ return;
161
+ }
162
+ if (c.state !== 'pending') return;
163
+ c.tries = (c.tries ?? 0) + 1;
164
+ if (c.tries < MAX_TRIES) { c.state = 'queued'; this._want.unshift(c); return; }
165
+ c.state = 'failed'; this.stats.failed++;
166
+ this.engine.events.emit('terrain:chunkFailed', { cx: c.cx, cz: c.cz, error: err });
167
+ reportError(this.engine, codedError('terrain-chunk-failed', `terrain chunk ${key} failed ${c.tries} times and stays empty (no ground, no collision there): `
168
+ + `${err?.message ?? err}. Usually the game's height / groundType / placement rule throws at that spot; engine.terrain.retry() sends failed chunks again`),
169
+ 'terrain chunk ' + key);
170
+ }
171
+ /** Send failed chunks (terrain:chunkFailed) again, e.g. after fixing what their rule reads. Returns how many were queued */
172
+ retry() {
173
+ let n = 0;
174
+ for (const c of this.chunks.values()) if (c.state === 'failed') { c.state = 'queued'; c.tries = 0; this._want.unshift(c); n++; }
175
+ this.stats.failed -= n;
176
+ return n;
96
177
  }
97
178
 
98
179
  /**
99
- * View distance (in chunks). Also moves the camera far plane out to it; the fog distance follows only with terrain({ viewFog: true }) (the game's fog is its
100
- * own)
180
+ * View distance (in chunks). Also moves the camera far plane out to it; with terrain({ viewFog: true }) the signal uViewDistance follows too (the drawing half
181
+ * writes it, see viewFogFar; the game's fog is its own)
101
182
  */
102
183
  setViewChunks(n) {
103
184
  this.viewChunks = n;
104
- const d = (n - 0.3) * this.T.CHUNK, e = this.engine;
105
- if (this.viewFog) e.setFogFar(d);
106
- else if (e.camera.far < d + 150) { e.camera.far = d + 150; e.camera.updateProjectionMatrix(); } // chunks in view must not be clipped
185
+ const e = this.engine, d = (n - 0.3) * this.T.CHUNK;
186
+ e.viewFar(d + 150); // chunks in view must not be clipped (unless the game owns camera.far)
187
+ }
188
+ /** The view distance the signal uViewDistance gets with terrain({ viewFog: true }) (meters), else null; never scene.fog itself */
189
+ get viewFogFar() { return this.viewFog ? (this.viewChunks - 0.3) * this.T.CHUNK : null; }
190
+ /** Vegetation density multiplier: plants are placed again on the loaded chunks; the ground and its collision stay, old trees block until the new ones are in */
191
+ setDensity(d) { this.density = d; this.vgen++; this._regrow(this.plants.baseNames()); }
192
+ // plants-only jobs for every loaded chunk (the ground, its collision and the near-only detail stay). c.regrow counts the ones not yet
193
+ // mounted: isReadyAround is false until they are, so a headless page (core/headlessLoad.js) keeps running loading frames and stateApplied
194
+ // waits for the new plants, as it did when a species dropped the whole terrain
195
+ _regrow(names) {
196
+ if (!names.length) return;
197
+ for (const c of this.chunks.values()) if (c.state === 'ready') { c.regrow = (c.regrow ?? 0) + 1; this._send({ ...this._job(c, false, names), regrow: true }); }
107
198
  }
108
- /** Vegetation density multiplier (rebuilds all chunks) */
109
- setDensity(d) { this.density = d; this.rebuild(); }
110
199
 
111
200
  rebuild() {
112
- for (const c of this.chunks.values()) this._dispose(c);
113
- this.chunks.clear();
201
+ this._stream.drop();
114
202
  this.ready = [];
115
- this._want = [];
116
- this.gen++; this._ver++;
203
+ this.gen++;
117
204
  }
118
205
 
119
- /** Ring of a chunk from the nearest stream source; a 'simple' source counts as the outer ring (far look, no near detail) */
120
- _ring(c) { return chunkRing(c.cx, c.cz, this.centers, this.viewChunks); }
206
+ /** Ring of a chunk from the nearest stream source; a 'simple' source counts as the outer ring (far picture, no near detail) */
207
+ _ring(c) { return this._stream.ring(c); }
121
208
 
122
209
  /**
123
- * Build a queued chunk entry and register the tick when its collision takes effect. Registered when the chunk is first needed (decided by stream source
124
- * positions),
125
- * not when actually sent to the worker (which depends on how busy the worker is) -- so the effect time depends on gameplay only.
126
- * Effect delay: ring 1, which the loading screen waits for, takes effect the moment play starts (lag 0); farther rings get more worker time, so on-the-spot
127
- * generation is rarely needed
210
+ * Build a queued chunk entry and register the tick when its collision takes effect. Registered when the chunk is first needed (decided by stream
211
+ * source positions), not when actually sent to the worker (which depends on how busy the worker is) -- so the effect time depends on gameplay only.
212
+ * Ring 1, which the loading screen waits for, takes effect the moment play starts (lag 0); farther rings get more worker time
128
213
  */
129
214
  _queue(cx, cz, key) {
130
- const c = { cx, cz, key, state: 'queued', group: null, veg: {}, colliders: {}, pendingDetail: false, detailDone: new Set(), level: -1, sphere: null, solid: false, gen: this.gen };
215
+ const c = { cx, cz, key, state: 'queued', data: null, plants: {}, colliders: {}, inView: true, pendingDetail: false, detailDone: new Set(), level: -1, sphere: null, solid: false, gen: this.gen };
131
216
  this.chunks.set(key, c);
132
217
  const ring = this._ring(c);
133
218
  c.ticket = this.engine.commits.request({
@@ -140,11 +225,11 @@ export class ChunkManager {
140
225
  return c;
141
226
  }
142
227
  /**
143
- * Dispatch tasks from the queue until maxInFlight are running; while the loading screen is up send all of them (a main-thread frame is long, waiting for
144
- * replies would idle the worker)
228
+ * Dispatch tasks from the queue until maxInFlight are running; while the loading screen is up send all of them (a main-thread frame is long,
229
+ * waiting for replies would idle the worker)
145
230
  */
146
231
  _pump() {
147
- const species = (this.engine.vegetation || NO_VEG).baseNames(), max = this.engine.ready ? Math.max(this.maxInFlight, 2 * this.lane.size) : Infinity;
232
+ const species = this.plants.baseNames(), max = this.engine.ready ? Math.max(this.maxInFlight, 2 * this.lane.size) : Infinity;
148
233
  while (this.inFlight < max && this._want.length) {
149
234
  const c = this._want.shift();
150
235
  if (c.state !== 'queued' || this.chunks.get(c.key) !== c) continue; // already generated on the spot, or released
@@ -155,80 +240,45 @@ export class ChunkManager {
155
240
 
156
241
  /** sources: engine.stream.sources() (every stream source; a source radius caps the view distance) */
157
242
  update(sources, camera) {
158
- const CH = this.T.CHUNK, V = this.viewChunks;
159
- // centers are reused objects compared field by field: nothing is allocated on a frame where no source changed chunk
160
- const C = this.centers;
161
- let changed = C.length !== sources.length || this._wantFor[0] !== V || this._wantFor[1] !== this._ver;
162
- C.length = sources.length;
163
- for (let i = 0; i < sources.length; i++) {
164
- const s = sources[i], cx = Math.floor(s.x / CH), cz = Math.floor(s.z / CH), simple = s.detail === 'simple';
165
- const R = s.radius == null ? V : Math.min(V, Math.max(1, Math.ceil(s.radius / CH))), c = C[i] ??= { cx: NaN, cz: 0, R: 0, simple: false };
166
- if (c.cx !== cx || c.cz !== cz || c.R !== R || c.simple !== simple) { c.cx = cx; c.cz = cz; c.R = R; c.simple = simple; changed = true; }
167
- }
168
-
169
- // 1. queue chunks any source needs; release those far from all.
170
- // Skip when source chunks, view distance and chunk table are unchanged (don't rebuild lists and key strings every frame)
171
- if (changed) {
172
- this._wantFor[0] = V; this._wantFor[1] = this._ver;
173
- const d2 = c => { let m = Infinity; for (const s of this.centers) m = Math.min(m, (c.cx - s.cx) ** 2 + (c.cz - s.cz) ** 2); return m; };
174
- const want = new Map();
175
- for (const s of this.centers) {
176
- const R = s.R, lim = R * R + R;
177
- for (let dz = -R; dz <= R; dz++) for (let dx = -R; dx <= R; dx++) {
178
- const cx = s.cx + dx, cz = s.cz + dz, key = cx + ',' + cz;
179
- if (dx * dx + dz * dz <= lim && !this.chunks.has(key)) want.set(key, { cx, cz, key });
180
- }
181
- }
182
- // re-sort queued chunks (not released) plus new ones by distance to the nearest source: nearest first
183
- const fresh = [...want.values()].sort((a, b) => d2(a) - d2(b)).map(w => this._queue(w.cx, w.cz, w.key));
184
- this._want = this._want.filter(c => c.state === 'queued' && this.chunks.get(c.key) === c).concat(fresh).sort((a, b) => d2(a) - d2(b));
185
- const kept = c => this.centers.some(s => (c.cx - s.cx) ** 2 + (c.cz - s.cz) ** 2 <= (s.R + 1) * (s.R + 1) + s.R + 1);
186
- for (const [key, c] of this.chunks) if (!kept(c)) { this._dispose(c); this.chunks.delete(key); }
187
- }
243
+ this._stream.follow(sources, this.T.CHUNK, this.viewChunks); // queue what a source needs, release what is far from all
188
244
  this._pump();
189
245
  this.stats.queued = this._want.length;
190
246
 
191
- // 2. upload worker results within the time budget; while the loading screen is up, first-screen chunks (the ring around the player) ignore the budget and
192
- // all upload in one frame
247
+ // 2. take worker results within the time budget; while the loading screen is up, first-screen chunks (the ring around the player) ignore the
248
+ // budget and all come in one frame
193
249
  const t0 = performance.now(), loading = !this.engine.ready, later = []; // measure: upload budget
194
250
  let built = 0;
195
251
  for (const r of this.ready) {
196
252
  const c = this.chunks.get(r.cx + ',' + r.cz);
197
- if (!c || r.gen !== this.gen || this._stale(c, r)) continue;
253
+ if (!c || r.gen !== this.gen) continue;
254
+ if (this._stale(c, r)) { if (r.regrow) c.regrow--; continue; }
198
255
  if (built > 0 && performance.now() - t0 >= this.applyBudgetMs // measure
199
256
  && !(loading && this._ring(c) <= 1)) { later.push(r); continue; }
200
257
  if (r.terrain) { if (c.state === 'ready') continue; this._applyTerrain(c, r.terrain); c.ticket?.resolve(true); }
201
258
  else if (c.state !== 'ready') continue;
202
- for (const name in r.veg) this._applyVeg(c, name, r.veg[name]);
203
- if (!r.terrain) { c.pendingDetail = false; for (const name in r.veg) c.detailDone.add(name); }
259
+ if (r.vgen !== this.vgen) { // placed with an old density: keep the ground, ask for these plants again
260
+ if (!r.terrain) c.pendingDetail = false;
261
+ this._send({ ...this._job(c, false, Object.keys(r.veg)), regrow: !!r.regrow }); // a regrow stays counted until its plants are in
262
+ } else {
263
+ for (const name in r.veg) this.plants.mount(c, name, r.veg[name]);
264
+ if (r.regrow) c.regrow--;
265
+ if (!r.terrain) { c.pendingDetail = false; for (const name in r.veg) c.detailDone.add(name); }
266
+ }
204
267
  c.level = -1; built++;
205
268
  }
206
269
  this.ready = later;
207
270
  this.stats.builtThisFrame = built;
208
271
  this.stats.applyMs += ((performance.now() - t0) - this.stats.applyMs) * 0.1; // measure
209
272
 
210
- // 3. LOD + frustum culling
211
- camera.updateMatrixWorld();
212
- this._m.multiplyMatrices(camera.projectionMatrix, camera.matrixWorldInverse);
213
- this._frustum.setFromProjectionMatrix(this._m);
214
- let visible = 0, instances = 0;
215
- for (const c of this.chunks.values()) {
216
- if (c.state !== 'ready') continue;
217
- const ring = this._ring(c);
218
- this._setLevel(c, ring);
219
- const v = ring <= 1 || this._frustum.intersectsSphere(c.sphere);
220
- c.group.visible = v;
221
- if (v) { visible++; for (const n in c.veg) if (c.veg[n].visible) instances += c.veg[n].count; }
222
- }
273
+ // 3. LOD + frustum (the draw parts get show(c, visible) when it changes)
274
+ const { visible, instances } = this._stream.cull(camera);
223
275
  this.stats.visible = visible; this.stats.loaded = this.chunks.size; this.stats.instances = instances;
224
276
  return built;
225
277
  }
226
278
 
227
- /** Due but chunk not ready: if the worker result already arrived, upload it now, else generate on the main thread (same code as the worker, same result) */
228
-
229
279
  _job(c, terrain, species) {
230
280
  const ev = this.edits.version(c.key), edits = this.edits.forChunk(c.cx, c.cz);
231
- return { type: 'job', cx: c.cx, cz: c.cz, terrain, species, density: this.density, gen: this.gen, ev, edits };
281
+ return { type: 'job', cx: c.cx, cz: c.cz, terrain, species, density: this.density, gen: this.gen, vgen: this.vgen, ev, edits };
232
282
  }
233
283
  // result built before a later edit near this chunk: drop it and ask again (a loaded chunk was already rebuilt by the edit)
234
284
  _stale(c, r) {
@@ -238,11 +288,47 @@ export class ChunkManager {
238
288
  return true;
239
289
  }
240
290
 
241
- _applyTerrain(c, t) { mountTerrain(this, c, t); }
291
+ // a generated chunk: keep its arrays and bounds, tell the draw parts
292
+ _applyTerrain(c, t) {
293
+ c.data = t;
294
+ if (t.top != null) { c.solidCount = t.solid; this.lowest = Math.min(this.lowest, t.minH); } // island: collision takes top and sides, not the bottom
295
+ c.sphere = new THREE.Sphere(new THREE.Vector3(t.sphere[0], t.sphere[1], t.sphere[2]), t.sphere[3]);
296
+ c.state = 'ready';
297
+ this._emit('add', c);
298
+ }
242
299
 
243
- // the InstancedMesh of one species in a chunk is built by vegetation (the same code builds its chunks on any other ground)
244
- _applyVeg(c, name, r) { this.engine.vegetation.mount(c, name, r); }
300
+ // due but not ready: if the worker result already arrived take it now, else generate on the main thread (same code, same result).
301
+ // A failed chunk is not tried here (it was reported; the main thread would throw the same error at every commit)
302
+ _forceReady(c) {
303
+ if (c.state === 'ready' || c.state === 'failed') return true;
304
+ const i = this.ready.findIndex(r => r.terrain && r.cx === c.cx && r.cz === c.cz && r.gen === c.gen && r.ev === this.edits.version(c.key));
305
+ let r = i >= 0 ? this.ready.splice(i, 1)[0] : null;
306
+ if (!r || r.vgen !== this.vgen) {
307
+ r = { terrain: r?.terrain ?? this.T.buildChunk(c.cx, c.cz), veg: {} };
308
+ for (const name of this.plants.baseNames()) r.veg[name] = this.T.place(c.cx, c.cz, this.plants.get(name).rule, this.density);
309
+ }
310
+ this._applyTerrain(c, r.terrain);
311
+ for (const name in r.veg) this.plants.mount(c, name, r.veg[name]);
312
+ c.level = -1;
313
+ return true;
314
+ }
245
315
 
316
+ // near-only species are placed when a chunk comes within their ring and dropped past it; the vegetation drawing picks its own LOD (plants.ring)
317
+ _setLevel(c, ring) {
318
+ if (c.level === ring) return;
319
+ c.level = ring;
320
+ const P = this.plants;
321
+ for (const sp of P.list()) {
322
+ if (!sp.nearOnly) continue;
323
+ const has = !!c.plants[sp.name];
324
+ // detailDone: this species was already placed here and came back empty; without it the empty result would reset the level and re-ask forever
325
+ if (ring <= sp.maxRing && !has && !c.pendingDetail && !c.detailDone.has(sp.name)) {
326
+ c.pendingDetail = true;
327
+ this._send(this._job(c, false, P.nearNames()));
328
+ } else if (ring > sp.maxRing + 1 && has) { P.unmount(c, sp.name); c.detailDone.delete(sp.name); }
329
+ }
330
+ P.ring?.(c, ring);
331
+ }
246
332
 
247
333
  /** Stop the chunk workers (called by terrain dispose; in-flight results are discarded) */
248
334
  dispose() { this.lane.dispose(); this.ready.length = 0; }
@@ -251,10 +337,8 @@ export class ChunkManager {
251
337
 
252
338
  _dispose(c) {
253
339
  if (c.state !== 'ready') return;
254
- this.engine.scene.remove(c.group);
255
- c.terrain.geometry.dispose();
256
- disposeColorMap(c);
257
- for (const n in c.veg) c.veg[n].dispose();
340
+ this.plants.drop(c);
341
+ this._emit('remove', c);
258
342
  }
259
343
  }
260
- Object.assign(ChunkManager.prototype, chunkQueries, chunkLevels);
344
+ Object.assign(ChunkManager.prototype, chunkQueries);
@@ -10,7 +10,7 @@ export function chunkHandler() {
10
10
  if (d.type === 'species') { species[d.name] = d.rule; return null; }
11
11
  const t0 = performance.now(); // measure
12
12
  T.setEdits(d.edits); // only the edits around this chunk travel with the job (null when there are none)
13
- const out = { gen: d.gen, ev: d.ev, cx: d.cx, cz: d.cz, terrain: d.terrain ? T.buildChunk(d.cx, d.cz) : null, veg: {}, ms: 0 };
13
+ const out = { regrow: !!d.regrow, gen: d.gen, vgen: d.vgen, ev: d.ev, cx: d.cx, cz: d.cz, terrain: d.terrain ? T.buildChunk(d.cx, d.cz) : null, veg: {}, ms: 0 };
14
14
  for (const name of d.species) out.veg[name] = T.place(d.cx, d.cz, species[name], d.density);
15
15
  // compute time: the main thread subtracts it from the round trip to get the transit cost (Budget.js ApplyCost)
16
16
  out.ms = performance.now() - t0; // measure
@@ -8,7 +8,7 @@ export const chunkQueries = {
8
8
  const [x, z] = xzOf(position), CH = this.T.CHUNK, pcx = Math.floor(x / CH), pcz = Math.floor(z / CH);
9
9
  for (let dz = -rings; dz <= rings; dz++) for (let dx = -rings; dx <= rings; dx++) {
10
10
  const c = this.chunks.get((pcx + dx) + ',' + (pcz + dz));
11
- if (!c || c.state !== 'ready' || solid && !c.solid) return false;
11
+ if (!c || c.state !== 'ready' || c.regrow > 0 || solid && !c.solid) return false; // regrow: plants of a species added later still on the way
12
12
  }
13
13
  return true;
14
14
  },
@@ -30,13 +30,15 @@ export const chunkQueries = {
30
30
  },
31
31
 
32
32
  /** @internal Collision data of a chunk (for the physics module): terrain triangles (chunk-local coordinates) + vegetation collision circles. Returns null if not generated.
33
- * token tells whether the chunk was regenerated */
33
+ * token tells whether the ground was regenerated, treeToken whether its tree circles changed */
34
34
  chunkCollision(cx, cz) {
35
35
  const c = this.chunks.get(cx + ',' + cz);
36
36
  if (!c || c.state !== 'ready' || !c.solid) return null; // collision's effective tick not reached yet
37
37
  // when the token changes the physics module rebuilds this chunk's collision; edits such as felling a tree issue a new colToken
38
38
  // an island chunk (terrain({ shape })) leaves out its bottom: a body falls past the underside instead of landing on it from below
39
- const p = c.terrain.geometry.attributes.position.array, positions = c.solidCount == null ? p : p.subarray(0, c.solidCount * 3);
40
- return { token: c.colToken ?? c, positions, ox: cx * this.T.CHUNK, oz: cz * this.T.CHUNK, circles: Object.values(c.colliders) };
39
+ const p = c.data.pos, positions = c.solidCount == null ? p : p.subarray(0, c.solidCount * 3);
40
+ // treeToken: only the tree circles changed (density, a felled tree): physics rebuilds the trunks, not the ground triangles
41
+ const token = c.colToken ?? c;
42
+ return { token, treeToken: c.treeToken ?? token, positions, ox: cx * this.T.CHUNK, oz: cz * this.T.CHUNK, circles: Object.values(c.colliders) };
41
43
  },
42
44
  };
@@ -0,0 +1,154 @@
1
+ // Terrain drawing: draws the chunks the terrain data part (ChunkManager) generated. One mesh per chunk from the chunk's arrays (c.data: pos, nor,
2
+ // col, uv, tex), the ground material (terrain({ material }) / engine.terrain.material), the per-chunk color map of shading 'texture',
3
+ // island side material, and frustum visibility. Installed by terrain() as its own module 'terrainDraw' holding the slot 'terrain-draw'.
4
+ // engine.terrain.material / .patches / .uniforms / .recolor() end up here (ChunkManager hands them on, it is data only).
5
+ //
6
+ // Why a separate module: collision, paths, engine.surface and vegetation read only the data part, so a game can swap the whole picture
7
+ // (engine.use(myGround, { replaces: 'terrain-draw' })) and keep everything that plays. A replacement draw part does what this file does:
8
+ // install(e, ctx) { ctx.track(e.terrain.view({ add(c) {...c.data.pos...}, change(c) {...}, remove(c) {...}, show(c, visible) {...} })); }
9
+ // This file never changes chunk data; it only reads it.
10
+ import { engineOwned } from '../../core/things.js';
11
+ import * as THREE from 'three';
12
+ import { terrainMaterial } from '../../render/materials.js';
13
+ import { patchesOf, unpatchMaterial } from '../../render/patches.js';
14
+ import { readParams, keysSchema } from '../../core/params.js';
15
+ import { codedError } from '../../core/errorHints.js';
16
+ import { mountColorMap, updateColorMap, disposeColorMap } from './terrainTexture.js';
17
+
18
+ // what the workers bake into each chunk: a change rebuilds every chunk
19
+ const BAKED = ['colors', 'biomeColors', 'steep', 'variation', 'shading', 'normals'];
20
+ const RECOLOR_KEYS = [...BAKED, 'detail'];
21
+ const SHADINGS = ['smooth', 'flat', 'texture'], NORMALS = ['smooth', 'flat'];
22
+
23
+ /** Check the picture values terrain({...}) and engine.terrain.recolor take; null is "none" for each @param {string} where @param {any} o */
24
+ export function checkGround(where, o) {
25
+ const bad = (k, want) => codedError('terrain-option', `${where}: ${k} ${want}; got ${JSON.stringify(o[k])}`);
26
+ for (const k of ['colors', 'biomeColors', 'variation', 'detail']) if (o[k] != null && typeof o[k] !== 'object') throw bad(k, 'must be an object');
27
+ if (o.steep != null && !Array.isArray(o.steep)) throw bad('steep', 'must be an array [{ maxNormalY, colors }]');
28
+ if (o.shading != null && !SHADINGS.includes(o.shading)) throw bad('shading', `must be ${SHADINGS.join(' | ')}`);
29
+ if (o.normals != null && !NORMALS.includes(o.normals)) throw bad('normals', `must be ${NORMALS.join(' | ')} or null`);
30
+ const v = o.variation;
31
+ if (v) {
32
+ readParams(`${where} variation`, keysSchema(['blend', 'jitter', 'patches']), v);
33
+ readParams(`${where} variation.blend`, keysSchema(['size', 'strength']), v.blend || {});
34
+ readParams(`${where} variation.jitter`, keysSchema(['size', 'min', 'range']), v.jitter || {});
35
+ readParams(`${where} variation.patches`, keysSchema(['size', 'strength', 'levels', 'tint']), v.patches || {});
36
+ }
37
+ }
38
+
39
+ export class TerrainDraw {
40
+ /**
41
+ * @param {any} e @param {any} w the terrain data part (engine.terrain)
42
+ * @param {{ material?: any, effects?: boolean, detail?: any, sideMat?: any, config: { get(): any, set(c: any): void, species(): any } }} o config: the current worker config, shared with the data half
43
+ */
44
+ constructor(e, w, { material = null, effects = true, detail = null, sideMat = null, config }) {
45
+ this.engine = e; this.w = w;
46
+ /** @internal */ this._config = config;
47
+ /** @internal shading null in recolor goes back to this */ this._shading = config.get().shading;
48
+ /** @internal effects: false means the material given at the start stays as given, so detail never reaches it */ this._effects = effects;
49
+ /** @internal the material the engine dressed: the neutral one, or terrain({ material }) */
50
+ this._own = terrainMaterial(typeof material === 'function' ? material(e) : material, e, { effects, detail });
51
+ /** @internal the material the chunks draw with */ this._material = this._own;
52
+ /** shape.side.material: island sides and bottoms (null: the ground material) */
53
+ this.sideMat = typeof sideMat === 'function' ? sideMat(e) : sideMat;
54
+ this.meshes = new Map(); // chunk record -> { group, mesh, colorTex, colorMat }
55
+ this._view = w.view(this);
56
+ }
57
+
58
+ /** @internal view hook: a chunk was generated (or regenerated after a full rebuild) */
59
+ add(c) {
60
+ const t0 = performance.now(); // measure: the 'build' stage of engine.budget.cost
61
+ const t = c.data, CH = this.w.CHUNK, g = new THREE.BufferGeometry();
62
+ g.setAttribute('position', new THREE.BufferAttribute(t.pos, 3));
63
+ g.setAttribute('normal', new THREE.BufferAttribute(t.nor, 3));
64
+ g.setAttribute('color', new THREE.BufferAttribute(t.col, 3));
65
+ g.setAttribute('uv', new THREE.BufferAttribute(t.uv, 2));
66
+ const rec = { group: new THREE.Group(), mesh: null, colorTex: null, colorMat: null };
67
+ const mesh = rec.mesh = new THREE.Mesh(g, this._materialFor(rec, c));
68
+ if (t.top != null) { // island chunk (terrain({ shape })): vertices are top, side, bottom
69
+ const rest = t.pos.length / 3 - t.top;
70
+ if (rest) { g.addGroup(0, t.top, 0); g.addGroup(t.top, rest, 1); }
71
+ }
72
+ mesh.receiveShadow = true; mesh.frustumCulled = false; mesh.matrixAutoUpdate = false;
73
+ rec.group.userData.budgetTag = 'terrain';
74
+ rec.group.position.set(c.cx * CH, 0, c.cz * CH);
75
+ rec.group.add(mesh); rec.group.updateMatrixWorld(true);
76
+ rec.group.visible = c.inView !== false;
77
+ this.meshes.set(c, rec);
78
+ this.engine.scene.add(engineOwned('terrain', rec.group));
79
+ this.engine.budget.cost.end('build', t0);
80
+ }
81
+ /** @internal view hook: an edit rebuilt the chunk's arrays (same vertex count) */
82
+ change(c) {
83
+ const rec = this.meshes.get(c); if (!rec) return;
84
+ const g = rec.mesh.geometry, t = c.data;
85
+ for (const [n, a] of [['position', t.pos], ['normal', t.nor], ['color', t.col], ['uv', t.uv]]) { g.attributes[n].array.set(a); g.attributes[n].needsUpdate = true; }
86
+ if (t.tex && rec.colorTex) updateColorMap(rec, t.tex);
87
+ g.computeBoundingSphere(); g.boundingBox = null;
88
+ }
89
+ /** @internal view hook: the chunk was released */
90
+ remove(c) {
91
+ const rec = this.meshes.get(c); if (!rec) return;
92
+ this.meshes.delete(c);
93
+ this.engine.scene.remove(rec.group);
94
+ rec.mesh.geometry.dispose();
95
+ disposeColorMap(rec);
96
+ }
97
+ /** @internal view hook: in view or not (ring 1 is always in view, farther chunks by the camera frustum) */
98
+ show(c, visible) { const rec = this.meshes.get(c); if (rec) rec.group.visible = visible; }
99
+
100
+ /**
101
+ * The ground material every chunk draws with (a texture-shaded chunk draws a clone carrying its color map). Setting swaps it on every loaded chunk at once, draws it as
102
+ * given (no engine patch) and regenerates nothing
103
+ * @type {any}
104
+ */
105
+ get material() { return this._material; }
106
+ set material(m) {
107
+ if (!m?.isMaterial) throw codedError('terrain-option', `engine.terrain.material takes a three.js Material, got ${m}; e.g. engine.terrain.material = applyEffects(new THREE.MeshStandardMaterial({ vertexColors: true }), { patches: engine.terrain.patches })`);
108
+ const was = this._material;
109
+ if (m === was) return;
110
+ this._material = m;
111
+ this._remount();
112
+ if (was === this._own) was.dispose(); // only its GPU program: setting it back compiles it again
113
+ }
114
+ /** The patches on the engine's material (world, clouds, season, detail), so a game material keeps them through applyEffects(m, { patches }) */
115
+ get patches() { return patchesOf(this._own); }
116
+ /** The detail layer's uniforms ({} without one), written directly and live: uDetailStrength, uDetailScale, uDetailTint... */
117
+ get uniforms() { return this.patches.find(p => p.name === 'detail')?.uniforms ?? {}; }
118
+
119
+ /**
120
+ * What terrain({...}) baked in, changed at run time. colors / biomeColors / steep / variation / shading / normals: every chunk is rebuilt (edits stay); each is given
121
+ * whole, null takes it out. detail: the detail layer on the engine's material, no chunk rebuilt; a game's material is the game's to patch
122
+ * @param {any} o
123
+ */
124
+ recolor(o = {}) {
125
+ readParams('engine.terrain.recolor', keysSchema(RECOLOR_KEYS), o);
126
+ checkGround('engine.terrain.recolor', o);
127
+ if ('detail' in o && this._effects) {
128
+ terrainMaterial(unpatchMaterial(this._own, 'detail'), this.engine, { detail: o.detail });
129
+ if (this._material === this._own) this._remount();
130
+ }
131
+ const baked = BAKED.filter(k => k in o);
132
+ if (!baked.length) return;
133
+ const next = { ...this._config.get() };
134
+ for (const k of baked) if (o[k] == null) delete next[k]; else next[k] = o[k];
135
+ next.shading ??= this._shading;
136
+ this._config.set(next);
137
+ this.w.reinit(next, this._config.species());
138
+ }
139
+
140
+ /** Every loaded chunk draws the current material: no chunk is regenerated, collision is untouched @internal */
141
+ _remount() {
142
+ for (const [c, rec] of this.meshes) { disposeColorMap(rec); rec.colorTex = rec.colorMat = null; rec.mesh.material = this._materialFor(rec, c); }
143
+ }
144
+
145
+ // texture shading: a material with this chunk's color map. Island sides keep vertex colors (the map is sampled by world xz and would smear down them)
146
+ _materialFor(rec, c) {
147
+ const t = c.data, CH = this.w.CHUNK;
148
+ const mat = t.tex ? mountColorMap(this.engine, this.material, rec, t.tex, c.cx * CH, c.cz * CH, CH) : this.material;
149
+ const rest = t.top != null ? t.pos.length / 3 - t.top : 0;
150
+ return rest && (t.tex || this.sideMat) ? [mat, this.sideMat ?? this.material] : mat;
151
+ }
152
+
153
+ dispose() { this._view.remove(); }
154
+ }