threedog 1.1.0 → 1.3.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 (370) hide show
  1. package/CHANGELOG.md +893 -798
  2. package/README.md +1 -1
  3. package/core/assets/Animator.js +41 -3
  4. package/core/assets/Assets.js +100 -24
  5. package/core/assets/assetEntry.js +73 -20
  6. package/core/assets/assetHot.js +68 -16
  7. package/core/assets/assetLoad.js +6 -6
  8. package/core/assets/assetLod.js +9 -2
  9. package/core/assets/assetManifest.js +12 -2
  10. package/core/assets/assetPart.js +54 -0
  11. package/core/assets/ik.js +271 -0
  12. package/core/assets/modelNeeds.js +37 -0
  13. package/core/assets/namedModel.js +102 -29
  14. package/core/assets/nodeVisibility.js +15 -0
  15. package/core/audio/Audio.js +36 -4
  16. package/core/audio/audioReverb.js +99 -0
  17. package/core/audio/audioRules.js +1 -1
  18. package/core/audio/audioVoice.js +1 -1
  19. package/core/base/Events.js +14 -4
  20. package/core/base/Random.js +1 -1
  21. package/core/base/Vars.js +1 -1
  22. package/core/base/docRef.js +51 -0
  23. package/core/base/errorCodes.js +187 -126
  24. package/core/base/errorHints.js +9 -7
  25. package/core/base/errors.js +25 -10
  26. package/core/base/events.generated.js +2 -0
  27. package/core/base/freeParts.js +76 -0
  28. package/core/base/math.js +28 -0
  29. package/core/base/sections.js +5 -5
  30. package/core/base/validate.js +31 -3
  31. package/core/engine/Engine.js +17 -7
  32. package/core/engine/Loading.js +5 -3
  33. package/core/engine/copies.js +1 -1
  34. package/core/engine/headlessLoad.js +4 -1
  35. package/core/engine/lifecycle.js +32 -16
  36. package/core/engine/loop.js +71 -27
  37. package/core/engine/moduleSlots.js +2 -2
  38. package/core/engine/moduleTypes.js +3 -3
  39. package/core/engine/modules.js +65 -39
  40. package/core/engine/page.js +6 -3
  41. package/core/engine/services.js +6 -5
  42. package/core/engine/startup.js +8 -7
  43. package/core/input/Input.js +28 -14
  44. package/core/input/inputContext.js +28 -16
  45. package/core/input/inputKeyboard.js +31 -3
  46. package/core/input/inputPad.js +4 -0
  47. package/core/input/inputPointer.js +2 -1
  48. package/core/input/inputSeat.js +1 -1
  49. package/core/inspect/Budget.js +109 -19
  50. package/core/inspect/DebugOverrides.js +28 -4
  51. package/core/inspect/Describe.js +17 -9
  52. package/core/inspect/Inspect.js +4 -2
  53. package/core/inspect/InspectMaterials.js +3 -1
  54. package/core/inspect/InspectPerf.js +19 -9
  55. package/core/inspect/InspectScene.js +32 -7
  56. package/core/inspect/MaterialInfo.js +19 -2
  57. package/core/inspect/UrlState.js +50 -28
  58. package/core/inspect/catalog.js +28 -9
  59. package/core/inspect/debugView.js +2 -1
  60. package/core/inspect/describeRender.js +25 -13
  61. package/core/inspect/describeText.js +14 -6
  62. package/core/inspect/lightWatch.js +1 -1
  63. package/core/inspect/metadata.generated.js +35 -17
  64. package/core/inspect/pictureChecks.js +148 -0
  65. package/core/inspect/pictureMenu.js +84 -0
  66. package/core/inspect/pictureWriters.js +26 -6
  67. package/core/inspect/textureBytes.js +12 -2
  68. package/core/inspect/toolDoor.js +2 -4
  69. package/core/ops/Ops.js +11 -4
  70. package/core/ops/holds.js +27 -10
  71. package/core/ops/opsAtomic.js +15 -7
  72. package/core/ops/opsGuard.js +2 -2
  73. package/core/ops/opsRun.js +8 -7
  74. package/core/ops/sharedPoint.js +72 -21
  75. package/core/ops/stacks.js +56 -16
  76. package/core/saves/SaveStore.js +9 -3
  77. package/core/saves/Saves.js +32 -23
  78. package/core/saves/saveApply.js +96 -44
  79. package/core/saves/saveIds.js +1 -1
  80. package/core/saves/saveVersions.js +7 -5
  81. package/core/saves/session.js +17 -8
  82. package/core/saves/stateReplace.js +34 -15
  83. package/core/scene/Rays.js +52 -10
  84. package/core/scene/Views.js +36 -15
  85. package/core/scene/adaptive.js +144 -21
  86. package/core/scene/drawOnly.js +17 -0
  87. package/core/scene/gameLights.js +47 -4
  88. package/core/scene/sceneMethods.js +13 -11
  89. package/core/scene/stepPoses.js +11 -3
  90. package/core/scene/targeting.js +5 -3
  91. package/core/scene/thingOps.js +1 -1
  92. package/core/scene/tier.js +15 -0
  93. package/core/stream/Batching.js +30 -7
  94. package/core/stream/Stream.js +26 -7
  95. package/core/stream/batchGroups.js +2 -2
  96. package/core/stream/chunkStream.js +7 -5
  97. package/core/stream/prepare.js +77 -0
  98. package/core/time/skip.js +3 -1
  99. package/core/time/time.js +4 -2
  100. package/docs/AI.md +82 -83
  101. package/docs/API.md +16 -16
  102. package/docs/CODEMAP.md +17 -11
  103. package/docs/COMMANDS.md +139 -142
  104. package/docs/CONVENTIONS.md +37 -49
  105. package/docs/MIGRATING-0.8.md +2 -2
  106. package/docs/MIGRATING-1.0.md +2 -2
  107. package/docs/THREE.md +30 -35
  108. package/docs/api/assets.md +3 -1
  109. package/docs/api/audio.md +4 -2
  110. package/docs/api/budget.md +5 -0
  111. package/docs/api/characters.md +10 -8
  112. package/docs/api/collision.md +6 -4
  113. package/docs/api/engine.md +16 -16
  114. package/docs/api/events.md +3 -2
  115. package/docs/api/ground.md +6 -5
  116. package/docs/api/hud.md +4 -2
  117. package/docs/api/input.md +5 -5
  118. package/docs/api/particles.md +2 -1
  119. package/docs/api/photo.md +3 -0
  120. package/docs/api/post.md +7 -4
  121. package/docs/api/quests.md +2 -2
  122. package/docs/api/rays.md +1 -2
  123. package/docs/api/saves.md +7 -7
  124. package/docs/api/settings.md +2 -2
  125. package/docs/api/tools.md +3 -1
  126. package/docs/api/vars.md +1 -1
  127. package/docs/api/vegetation.md +4 -2
  128. package/docs/api/world.md +1 -1
  129. package/docs/recipes/01-new-game.md +16 -17
  130. package/docs/recipes/02-npc.md +22 -18
  131. package/docs/recipes/03-items-pickups.md +37 -35
  132. package/docs/recipes/04-quests.md +15 -10
  133. package/docs/recipes/05-props-bake.md +101 -95
  134. package/docs/recipes/06-clock-events.md +28 -28
  135. package/docs/recipes/07-flow-scenes-pause.md +29 -26
  136. package/docs/recipes/08-weather-sky.md +52 -64
  137. package/docs/recipes/09-materials-lights-models.md +26 -17
  138. package/docs/recipes/10-blender-level.md +15 -10
  139. package/docs/recipes/11-vehicles.md +12 -7
  140. package/docs/recipes/12-navmesh.md +44 -26
  141. package/docs/recipes/13-animation.md +56 -45
  142. package/docs/recipes/14-custom-module.md +21 -18
  143. package/docs/recipes/15-perf.md +61 -55
  144. package/docs/recipes/16-dev-bridge.md +24 -33
  145. package/docs/recipes/18-world.md +36 -42
  146. package/docs/recipes/19-shooting-picking.md +20 -15
  147. package/docs/recipes/20-content-actions-save.md +48 -56
  148. package/docs/recipes/21-camera.md +45 -54
  149. package/docs/recipes/22-shop-gold.md +12 -7
  150. package/docs/recipes/23-ops.md +25 -23
  151. package/docs/recipes/26-ui-parts.md +67 -47
  152. package/docs/recipes/27-net.md +12 -7
  153. package/docs/recipes/28-terrain.md +24 -21
  154. package/docs/recipes/29-grid.md +32 -27
  155. package/docs/recipes/30-templates.md +21 -20
  156. package/docs/recipes/31-audio.md +39 -22
  157. package/docs/recipes/32-action-game.md +19 -14
  158. package/docs/recipes/33-stream-sources.md +15 -11
  159. package/docs/recipes/34-environment-lighting.md +126 -70
  160. package/docs/recipes/35-picture-from-reference.md +8 -8
  161. package/docs/recipes/36-ground-plants.md +27 -21
  162. package/docs/recipes/40-scene.md +19 -28
  163. package/docs/recipes/43-shader-patches-surfaces.md +15 -12
  164. package/docs/recipes/44-water-weather-hooks.md +34 -31
  165. package/docs/recipes/45-cascaded-shadows.md +35 -26
  166. package/docs/recipes/46-blender-art-route.md +7 -2
  167. package/docs/recipes/49-game-module-contract.md +13 -8
  168. package/docs/recipes/50-own-renderer.md +6 -2
  169. package/docs/recipes/51-capability-catalog.md +15 -8
  170. package/docs/recipes/52-around-the-picture.md +34 -32
  171. package/docs/recipes/53-ground-up-close.md +6 -1
  172. package/docs/recipes/55-mods-time-wrap.md +27 -19
  173. package/docs/recipes/56-webgpu-tsl.md +75 -43
  174. package/docs/recipes/57-control.md +18 -13
  175. package/docs/recipes/58-input.md +26 -16
  176. package/docs/recipes/59-depth-post-effects.md +8 -3
  177. package/docs/recipes/60-judge-the-picture.md +10 -9
  178. package/docs/recipes/61-deploy.md +5 -0
  179. package/docs/recipes/62-picture-code.md +72 -79
  180. package/docs/recipes/63-third-person-start.md +48 -45
  181. package/docs/recipes/64-particles.md +22 -10
  182. package/docs/recipes/65-swarm.md +18 -13
  183. package/docs/recipes/66-common-tasks.md +38 -35
  184. package/examples/action/.threedog/content-index.json +1 -1
  185. package/examples/action/GAMEMAP.md +2 -3
  186. package/examples/action/main.js +3 -3
  187. package/examples/action/picture/lights.js +3 -1
  188. package/examples/perf-island/.threedog/content-index.json +1 -1
  189. package/examples/perf-island/GAMEMAP.md +3 -3
  190. package/examples/perf-island/picture/lights.js +2 -1
  191. package/examples/plain-picture/GAMEMAP.md +1 -1
  192. package/examples/rc2d/GAMEMAP.md +1 -1
  193. package/examples/styletest/.threedog/content-index.json +1 -1
  194. package/examples/styletest/GAMEMAP.md +2 -2
  195. package/examples/styletest/main.js +1 -1
  196. package/examples/techniques/interior-light/README.md +3 -3
  197. package/examples/techniques/interior-light/interiorLight.js +2 -4
  198. package/examples/techniques/interior-light/picture/lights.js +2 -1
  199. package/examples/techniques/modular-building/picture/lights.js +3 -1
  200. package/examples/techniques/outlines-and-rim/picture/lights.js +3 -1
  201. package/examples/techniques/procedural-animation/README.md +1 -1
  202. package/examples/techniques/procedural-animation/main.js +1 -1
  203. package/examples/webgpu-tsl/GAMEMAP.md +1 -1
  204. package/examples/world/.threedog/content-index.json +1 -1
  205. package/examples/world/GAMEMAP.md +2 -3
  206. package/examples/world/art/humanoid.js +1 -1
  207. package/examples/world/main.js +6 -3
  208. package/index.d.ts +2 -2
  209. package/llms.txt +101 -0
  210. package/modules/ambience/Ambience.js +21 -5
  211. package/modules/calendar/index.js +9 -5
  212. package/modules/calendar/schedule.js +23 -8
  213. package/modules/camera/FirstPersonCamera.js +3 -1
  214. package/modules/camera/FollowCamera.js +10 -5
  215. package/modules/camera/RtsCamera.js +4 -3
  216. package/modules/camera/common.js +70 -8
  217. package/modules/camera/contract.js +1 -1
  218. package/modules/characters/Character.js +16 -10
  219. package/modules/characters/NPC.js +31 -19
  220. package/modules/characters/assetModel.js +14 -9
  221. package/modules/characters/astar.js +6 -1
  222. package/modules/characters/contract.js +2 -2
  223. package/modules/characters/index.js +34 -22
  224. package/modules/characters/movers/manual.js +1 -1
  225. package/modules/characters/movers/rapier.js +17 -2
  226. package/modules/characters/movers/simple.js +1 -1
  227. package/modules/characters/movers/support.js +16 -7
  228. package/modules/characters/npcAvoid.js +2 -2
  229. package/modules/characters/npcSim.js +3 -2
  230. package/modules/characters/pathAsync.js +24 -8
  231. package/modules/characters/pathJob.js +1 -1
  232. package/modules/characters/player.js +10 -9
  233. package/modules/characters/playerStrings.js +5 -5
  234. package/modules/characters/proceduralRig.js +5 -5
  235. package/modules/characters/useModel.js +6 -0
  236. package/modules/characters/walkTo.js +1 -1
  237. package/modules/collision/Collision.js +29 -18
  238. package/modules/collision/grid.js +22 -4
  239. package/modules/content/index.js +3 -1
  240. package/modules/content/loader.js +1 -1
  241. package/modules/content/models.js +82 -33
  242. package/modules/content/props.js +2 -1
  243. package/modules/content/rules.js +11 -5
  244. package/modules/content/templates.js +3 -3
  245. package/modules/content/words.js +2 -2
  246. package/modules/debug/DebugPanel.js +9 -9
  247. package/modules/flow/index.js +9 -6
  248. package/modules/gameplay/Dialogue.js +34 -20
  249. package/modules/gameplay/Interactions.js +19 -15
  250. package/modules/gameplay/Inventory.js +9 -4
  251. package/modules/gameplay/Quests.js +12 -10
  252. package/modules/gameplay/pickups.js +23 -11
  253. package/modules/grid/index.js +1 -1
  254. package/modules/grid/preview.js +2 -2
  255. package/modules/grid/tiles.js +1 -1
  256. package/modules/hlod/index.js +4 -1
  257. package/modules/hud/index.js +47 -10
  258. package/modules/hud/parts.js +28 -9
  259. package/modules/level/geometry.js +8 -3
  260. package/modules/level/index.js +10 -5
  261. package/modules/level/load.js +4 -2
  262. package/modules/lights/sources.js +1 -1
  263. package/modules/music/Music.js +22 -4
  264. package/modules/nav/index.js +20 -10
  265. package/modules/particles/Particles.js +31 -14
  266. package/modules/particles/effect.js +20 -5
  267. package/modules/particles/lit.js +72 -0
  268. package/modules/photo/Photo.js +72 -28
  269. package/modules/photo/pathTrace.js +106 -0
  270. package/modules/rigid/RigidBodies.js +23 -14
  271. package/modules/rigid/Vehicles.js +3 -13
  272. package/modules/rigid/sync.js +2 -1
  273. package/modules/settings/Settings.js +52 -20
  274. package/modules/settings/apply.js +23 -9
  275. package/modules/settings/sections.js +39 -6
  276. package/modules/settings/strings.js +2 -0
  277. package/modules/settings/view.js +19 -3
  278. package/modules/sky/dome.js +15 -3
  279. package/modules/sky/environment.js +28 -12
  280. package/modules/sky/fog.js +1 -1
  281. package/modules/sky/frame.js +6 -1
  282. package/modules/sky/shader.js +4 -3
  283. package/modules/sky/skyModule.js +8 -4
  284. package/modules/swarm/Swarm.js +1 -1
  285. package/modules/terrain/ChunkManager.js +61 -15
  286. package/modules/terrain/chunkJob.js +2 -2
  287. package/modules/terrain/index.js +20 -5
  288. package/modules/terrain/terrainEdit.js +8 -4
  289. package/modules/terrain/terrainTexture.js +4 -2
  290. package/modules/timeline/Timeline.js +4 -3
  291. package/modules/timeline/Tween.js +3 -0
  292. package/modules/timeline/letterbox.js +1 -0
  293. package/modules/triggers/index.js +36 -17
  294. package/modules/vegetation/Vegetation.js +81 -19
  295. package/modules/vegetation/densityMap.js +13 -8
  296. package/modules/vegetation/draw.js +147 -24
  297. package/modules/vegetation/groundChunks.js +20 -5
  298. package/modules/vegetation/index.js +3 -3
  299. package/modules/vegetation/modelGeometry.js +9 -4
  300. package/modules/water/Water.js +11 -8
  301. package/modules/weather/Weather.js +7 -2
  302. package/modules/weather/shaders.js +25 -5
  303. package/modules/weather/weatherDraw.js +20 -6
  304. package/modules/world/World.js +2 -1
  305. package/modules/world/index.js +2 -2
  306. package/modules/world/persist.js +6 -2
  307. package/modules/world/views.js +15 -2
  308. package/package.json +5 -1
  309. package/presets.js +5 -5
  310. package/render/PostFX.js +102 -42
  311. package/render/backend.js +142 -16
  312. package/render/bindingLimits.js +59 -0
  313. package/render/cascades.js +3 -1
  314. package/render/cascades.tsl.js +2 -0
  315. package/render/daylight.js +7 -1
  316. package/render/detail.js +7 -4
  317. package/render/effects.js +27 -8
  318. package/render/fogLook.js +24 -0
  319. package/render/fuse.js +5 -2
  320. package/render/fx/compareLevel.tsl.js +23 -0
  321. package/render/fx/detail.tsl.js +9 -7
  322. package/render/fx/index.js +9 -2
  323. package/render/fx/library.tsl.js +1 -0
  324. package/render/fx/lightShaft.tsl.js +114 -0
  325. package/render/fx/noise.tsl.js +25 -8
  326. package/render/fx/objectOrigin.tsl.js +39 -10
  327. package/render/fx/particles.tsl.js +23 -6
  328. package/render/fx/patchNodes.tsl.js +17 -12
  329. package/render/fx/pcss.tsl.js +51 -0
  330. package/render/fx/postWebGPU.tsl.js +104 -29
  331. package/render/fx/sky.tsl.js +3 -9
  332. package/render/fxNumbers.js +10 -4
  333. package/render/impostor.tsl.js +107 -0
  334. package/render/lighting.js +33 -1
  335. package/render/lightmap.js +42 -28
  336. package/render/lights.js +19 -3
  337. package/render/materials.js +6 -4
  338. package/render/mergeCommon.js +4 -1
  339. package/render/occlusion.js +14 -4
  340. package/render/patches.js +79 -41
  341. package/render/postRuns.js +32 -0
  342. package/render/postWebGL.js +97 -10
  343. package/render/probes.js +10 -14
  344. package/render/shaderErrors.js +44 -7
  345. package/render/shadowCache.tsl.js +33 -5
  346. package/render/shadows.js +42 -16
  347. package/render/slots.js +8 -5
  348. package/render/vertexInputs.js +52 -0
  349. package/types/core.d.ts +115 -47
  350. package/types/gameplay.d.ts +56 -23
  351. package/types/generated/core/audio/Audio.d.ts +27 -1
  352. package/types/generated/core/base/Random.d.ts +1 -1
  353. package/types/generated/core/input/Input.d.ts +6 -8
  354. package/types/generated/core/input/inputSeat.d.ts +1 -1
  355. package/types/generated/core/inspect/Budget.d.ts +26 -0
  356. package/types/generated/core/inspect/DebugOverrides.d.ts +0 -2
  357. package/types/generated/core/saves/Saves.d.ts +10 -7
  358. package/types/generated/core/saves/session.d.ts +8 -2
  359. package/types/generated/core/scene/Rays.d.ts +1 -3
  360. package/types/generated/core/scene/Views.d.ts +17 -3
  361. package/types/generated/modules/particles/Particles.d.ts +1 -1
  362. package/types/generated/modules/world/World.d.ts +2 -1
  363. package/types/generated/render/PostFX.d.ts +35 -9
  364. package/types/physics.d.ts +796 -764
  365. package/types/pixel.d.ts +1 -1
  366. package/types/tsl.d.ts +62 -1
  367. package/types/world.d.ts +12 -3
  368. package/ui/Focus.js +7 -5
  369. package/ui/Parts.js +1 -1
  370. package/ui/touchPart.js +6 -3
@@ -5,6 +5,7 @@ import { resolveClouds, cloudUniforms, CLOUD_UNIFORM_DECL } from './clouds.js';
5
5
  import { codedError } from '../../core/base/errorHints.js';
6
6
  import { SKY as K, glslFloat as f } from '../../render/fxNumbers.js';
7
7
  import { isWebGPU, webgpuPart } from '../../render/backend.js';
8
+ import { drawOnly } from '../../core/scene/drawOnly.js';
8
9
 
9
10
  // Keyframes: [time 0-1, zenith color, horizon color (= fog color), sun color, ambient intensity]
10
11
  // Neutral fallback with no keyframes: pure gray (no hue), only brightness changes with time. Night holds from 19:12 to 04:48 (rows 0.2 / 0.8):
@@ -63,6 +64,7 @@ export function makeDome(uniforms, st, extra, engine) {
63
64
  const dome = new THREE.Mesh(new THREE.SphereGeometry(1, 32, 16), nodes ? nodes.domeMaterial(uniforms, st, cl.kind, engine, { layers: extra.layers })
64
65
  : new THREE.ShaderMaterial({ vertexShader: vert, fragmentShader: domeFragment(cl, extra), uniforms, side: THREE.BackSide, depthWrite: false, depthTest: false }));
65
66
  dome.frustumCulled = false; dome.renderOrder = -1000; dome.userData.budgetTag = 'sky';
67
+ drawOnly('sky dome (left out: the tracer shows scene.environment and scene.background)', dome);
66
68
  dome.onBeforeRender = (r, sc, cam) => {
67
69
  dome.position.copy(cam.position); dome.scale.setScalar(/** @type {THREE.PerspectiveCamera} */ (cam).far * 0.9); dome.updateMatrixWorld();
68
70
  };
@@ -93,10 +95,9 @@ export const domeFragment = (cl, x) => `uniform vec3 uTop; uniform vec3 uHorizon
93
95
  uniform float uSunSize; uniform float uSunGlow; uniform float uSunBrightness; uniform float uMoonBrightness; uniform float uMoonSize; uniform vec3 uMoonColor; uniform float uStars; uniform float uStarCloudDim; uniform float uStarScale; uniform float uSkyCurve;
94
96
  uniform float uTime; uniform float uWeatherCloud; uniform float uCloudCover; uniform float uSkyCloudScale; uniform vec2 uSkyCloudSpeed; uniform vec3 uCloudColor; uniform vec3 uCloudShade;
95
97
  ${CLOUD_UNIFORM_DECL}
98
+ ${NOISE_GLSL}
96
99
  ${cl.decl}${x.decl ? '\n' + x.decl : ''}
97
100
  varying vec3 vDir;
98
- float h3(vec3 p){ p = fract(p * ${f(K.starMul)} + ${f(K.starAdd)}); p *= ${f(K.starScale)}; return fract(p.x*p.y*p.z*(p.x+p.y+p.z)); }
99
- ${NOISE_GLSL}
100
101
  ${cl.glsl}
101
102
  void main(){
102
103
  vec3 d = normalize(vDir);
@@ -116,7 +117,7 @@ void main(){
116
117
  // Stars sit behind the clouds (hidden where a cloud is drawn) and dim with the weather's cloud cover (uWeatherCloud): a rainy / overcast night has
117
118
  // no clear sky between the drawn clouds either, and a picture with sparse cloud art must not show a starry sky in a storm. Relative to the
118
119
  // weather value, no extra constant: uWeatherCloud 0 = every star, 1 = none. engine.sky.dim.stars false (uStarCloudDim 0) keeps them through the cover
119
- col += vec3(step(1.0 - uStars, h3(g)) * uNight * smoothstep(0.0, ${f(K.starFade)}, d.y) * (1.0 - clA) * (1.0 - clamp(uWeatherCloud, 0.0, 1.0) * uStarCloudDim));${x.body}
120
+ col += vec3(step(1.0 - uStars, threedogHash(vec2(g.x + g.z * ${f(K.starZ)}, g.y))) * uNight * smoothstep(0.0, ${f(K.starFade)}, d.y) * (1.0 - clA) * (1.0 - clamp(uWeatherCloud, 0.0, 1.0) * uStarCloudDim));${x.body}
120
121
  gl_FragColor = vec4(col, 1.0);
121
122
  #include <tonemapping_fragment>
122
123
  #include <colorspace_fragment>
@@ -2,6 +2,7 @@
2
2
  // timers and saves are the calendar's (modules/calendar); the sky reads engine.calendar each frame to draw.
3
3
  // Usage and the engine.sky API are documented in Sky.js.
4
4
  import { Sky } from './Sky.js';
5
+ import { resetSignals } from '../../render/effects.js';
5
6
  import { dropOwned } from '../../core/ops/owned.js';
6
7
  import { readParams, keysSchema } from '../../core/base/params.js';
7
8
  import { parseClock } from '../../core/time/dayTime.js';
@@ -15,9 +16,12 @@ import { warnOnce } from '../../core/base/validate.js';
15
16
  const SKY_OPTIONS = ['time', 'clouds', 'backdrop', 'keyframes', 'sunSize', 'sunGlow', 'sunBrightness', 'moonColor', 'moonBrightness',
16
17
  'starDensity', 'dim'];
17
18
  const SKY_PARAMS = keysSchema(SKY_OPTIONS); // keys only: the values take several shapes (time: 'HH:MM' | 0-1), Sky checks them
19
+ // Signals the sky rewrites every frame: handed back to neutral on removal. The rest go back only if this sky last wrote them and nobody took them since:
20
+ // the season / cover tint when it was painted (_seasoned / _covered: a game may write the tint itself), the sun direction when the engine still owns it (_oSun)
21
+ const SKY_SIGNALS = ['uSunColor', 'uSkyTop', 'uSkyHorizon', 'uGroundCover'];
22
+ const TINT_SIGNALS = ['uFoliageTint', 'uGroundTint', 'uFoliageMix', 'uGroundMix'];
18
23
  const STRINGS = {
19
- timeTwice: "sky({ time }) is the fixed time drawn without a calendar, but calendar() is installed, so the sky draws the calendar's time; " +
20
- 'start the day with calendar({ time }) and drop sky({ time })',
24
+ timeTwice: 'calendar owns the time of day while it is installed, so sky({ time }) is unused. Move the starting time to calendar({ time }) and remove sky({ time })',
21
25
  noSeason: "applyState({ season }): seasons are the calendar's; install calendar({ seasons: [...] }) (sky alone draws one fixed time)",
22
26
  };
23
27
 
@@ -37,7 +41,7 @@ export function sky(opts = {}) {
37
41
  optional: ['weather', 'calendar'],
38
42
  install(e, ctx) { e.i18n.add({ 'zh-CN': { 'module.sky': '天空' }, en: { 'module.sky': 'sky' } });
39
43
  // a time given while a calendar draws sits unused: say so, the game still runs and the calendar's time is drawn
40
- if (opts.time != null && e.calendar) warnOnce(coded('sky-option', STRINGS.timeTwice), 'sky-time-calendar');
44
+ if (opts.time != null && e.calendar) warnOnce(coded('time-owner-conflict', STRINGS.timeTwice), 'sky-time-calendar');
41
45
  s = new Sky(e, opts);
42
46
  // without a calendar the drawn sun tells day from night (night glow reads the measure); a calendar installed later registers its own over it
43
47
  const measures = [['daylight', () => s.daylight], ['timeOfDay', () => s.drawnTime]];
@@ -48,7 +52,7 @@ export function sky(opts = {}) {
48
52
  // a calendar removed mid-game takes its measures with it: the sky takes the signals back at once, or uDaylight / uTimeOfDay would freeze
49
53
  frame(dt) { own(); s.update(); s._envFrame(dt); },
50
54
  // the dome goes too: a sky swapped with replaces must not leave the old dome drawn behind the new one
51
- dispose() { s._shadowOff(); s._swap.remove(); s._envOff(); s._entries.dispose(); dropOwned(s.engine, s._owned); s.dome.removeFromParent(); s.dome.geometry.dispose(); s.dome.material.dispose(); },
55
+ dispose(e) { resetSignals(e, SKY_SIGNALS); if (s._seasoned || s._covered) resetSignals(e, TINT_SIGNALS); if (s._oSun.on) resetSignals(e, ['uSunDir']); s._shadowOff(); s._swap.remove(); s._envOff(); s._entries.dispose(); dropOwned(s.engine, s._owned); s.dome.removeFromParent(); s.dome.geometry.dispose(); s.dome.material.dispose(); },
52
56
  // scenario params time / season go to the calendar when there is one (its own applyState); without it time sets the fixed time drawn
53
57
  stateKeys: ['time', 'season'],
54
58
  applyState(e, { time, season }) {
@@ -319,7 +319,7 @@ export function swarm() {
319
319
  // onRender and not frame: step(render: false) skips the matrices, only drawn frames write them
320
320
  ctx.track(e.onRender(() => { for (const s of list) if (s.mesh) writeMesh(s, e.stepBlend); }));
321
321
  // one save part for all swarms: a load or new game also empties swarms not in saves, or last round's bullets stay on the field
322
- ctx.saves.register('swarm', { notAtomic: 'simulated in bulk each step: one copy per atomic run would cost more than the op', version: 1,
322
+ ctx.saves.define('swarm', { notAtomic: 'simulated in bulk each step: one copy per atomic run would cost more than the op', version: 1,
323
323
  save: () => ({ ...pending, ...Object.fromEntries(list.filter(s => s.saved).map(s => [s.name, s._save()])) }), // pending: swarms of the loaded save not made yet stay in the next save
324
324
  load: d => {
325
325
  pending = { ...d };
@@ -11,13 +11,13 @@ import * as THREE from 'three';
11
11
  import { createTerrain } from './terrainGen.js';
12
12
  import { chunkHandler } from './chunkJob.js';
13
13
  import { TerrainEdits } from './terrainEdit.js';
14
- import { ChunkStream, bookCollision } from '../../core/stream/chunkStream.js';
14
+ import { ChunkStream, bookCollision, colliderLag } from '../../core/stream/chunkStream.js';
15
15
  import { chunkQueries } from './chunkQueries.js';
16
16
  import { reportError } from '../../core/base/errors.js';
17
17
  import { codedError } from '../../core/base/errorHints.js';
18
18
 
19
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() {} };
20
+ const NO_VEG = { baseNames: () => [], nearNames: () => [], list: () => [], get: () => null, mount() {}, unmount() {}, release() {}, drop() {} };
21
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
22
  // chunk is marked failed and reported. Before, it sat in 'pending' for ever and the loading screen waited without a word.
23
23
  const MAX_TRIES = 3;
@@ -34,6 +34,8 @@ export class ChunkManager {
34
34
  this.ready = [];
35
35
  this._want = []; // chunks not yet dispatched (nearest first)
36
36
  this.gen = 0;
37
+ this._bookDue = false; // book the near-only collider tickets in the next update (_bookNear)
38
+ this._cid = 0; // chunk identity counter: a chunk released and made again at the same coordinate is another chunk
37
39
  this.vgen = 0; // +1 on a density or species change: plants placed before it are asked again
38
40
  this.stats = { builtThisFrame: 0, applyMs: 0, queued: 0, failed: 0 };
39
41
  /** @internal the draw parts drawing these chunks (view()) */ this.views = new Set();
@@ -103,7 +105,14 @@ export class ChunkManager {
103
105
  */
104
106
  setPlanter(planter) {
105
107
  this.plants = planter;
106
- return { remove: () => { if (this.plants === planter) this.plants = NO_VEG; } };
108
+ return { remove: () => {
109
+ if (this.plants !== planter) return;
110
+ this.plants = NO_VEG;
111
+ // everything it put into the terrain goes with it: the rules in the workers, the jobs in flight (a newer vgen sends their results back), the colliders' tickets
112
+ this.vgen++;
113
+ for (const sp of planter.list()) this.lane.broadcast({ type: 'species', name: sp.name, rule: null }, 'species:' + sp.name);
114
+ for (const c of this.chunks.values()) for (const n in c.near) this._cancelNear(c, n);
115
+ } };
107
116
  }
108
117
 
109
118
  /**
@@ -128,6 +137,7 @@ export class ChunkManager {
128
137
  */
129
138
  registerSpecies(name, rule) {
130
139
  this.lane.broadcast({ type: 'species', name, rule }, 'species:' + name);
140
+ this._bookDue = true;
131
141
  this.vgen++; // a chunk already on its way carries the old species list: update() asks again when it arrives
132
142
  if (!this.plants.get(name)?.nearOnly) this._regrow([name]);
133
143
  else this._regrowNear([name]);
@@ -152,10 +162,10 @@ export class ChunkManager {
152
162
  // 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
163
  _failed(job, err) {
154
164
  const key = job.cx + ',' + job.cz, c = this.chunks.get(key);
155
- if (!c || job.gen !== this.gen) return;
165
+ if (!c || job.gen !== this.gen || job.cid !== c.id) return; // gen: the table; cid: this chunk, not an older one at the same coordinate
156
166
  if (!job.terrain) {
157
167
  if (job.regrow) this._regrown(c);
158
- c.pendingDetail = false; for (const name of job.species || []) c.detailDone.add(name);
168
+ c.pendingDetail = false; for (const name of job.species || []) { c.detailDone.add(name); this._cancelNear(c, name); }
159
169
  reportError(this.engine, err, 'terrain chunk worker job'); // one key: a broken rule fails every chunk, report it once
160
170
  return;
161
171
  }
@@ -201,7 +211,8 @@ export class ChunkManager {
201
211
  _regrown(c) { if (c.regrow > 0) c.regrow--; }
202
212
  // near-only species: dropped here, and the LOD pass places them again on the chunks within their ring (never on the far ones _regrow would reach)
203
213
  _regrowNear(names) {
204
- for (const c of this.chunks.values()) { for (const n of names) { this.plants.unmount(c, n); c.detailDone.delete(n); } c.level = -1; }
214
+ for (const c of this.chunks.values()) { for (const n of names) this._unplantNear(c, n); c.level = -1; }
215
+ this._bookDue = true;
205
216
  }
206
217
 
207
218
  rebuild() {
@@ -219,7 +230,7 @@ export class ChunkManager {
219
230
  * Ring 1, which the loading screen waits for, takes effect the moment play starts (lag 0); farther rings get more worker time
220
231
  */
221
232
  _queue(cx, cz, key) {
222
- 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, regrow: 0 };
233
+ const c = { cx, cz, key, id: ++this._cid, near: {}, state: 'queued', data: null, plants: {}, colliders: {}, inView: true, pendingDetail: false, detailDone: new Set(), level: -1, sphere: null, solid: false, gen: this.gen, regrow: 0 };
223
234
  this.chunks.set(key, c);
224
235
  bookCollision(this, c, this._ring(c), {
225
236
  // collision counts from this step on (a new token makes the physics module build this chunk's collision)
@@ -245,9 +256,10 @@ export class ChunkManager {
245
256
 
246
257
  /** sources: engine.stream.sources() (every stream source; a source radius caps the view distance) */
247
258
  update(sources, camera) {
248
- this._stream.follow(sources, this.generator.CHUNK, this.viewChunks); // queue what a source needs, release what is far from all
259
+ if (this._stream.follow(sources, this.generator.CHUNK, this.viewChunks)) this._bookDue = true; // queue what a source needs, release what is far from all
249
260
  this._pump();
250
261
  this.stats.queued = this._want.length;
262
+ if (this._bookDue) { this._bookDue = false; this._bookNear(); }
251
263
 
252
264
  // 2. take worker results within the time budget; while the loading screen is up, first-screen chunks (the ring around the player) ignore the
253
265
  // budget and all come in one frame
@@ -255,7 +267,7 @@ export class ChunkManager {
255
267
  let built = 0;
256
268
  for (const r of this.ready) {
257
269
  const c = this.chunks.get(r.cx + ',' + r.cz);
258
- if (!c || r.gen !== this.gen) continue;
270
+ if (!c || r.gen !== this.gen || r.cid !== c.id) continue;
259
271
  if (this._stale(c, r)) { if (r.regrow) this._regrown(c); continue; }
260
272
  if (built > 0 && performance.now() - t0 >= this.applyBudgetMs // measure
261
273
  && !(loading && this._ring(c) <= 1)) { later.push(r); continue; }
@@ -264,9 +276,11 @@ export class ChunkManager {
264
276
  if (r.vgen !== this.vgen) { // placed with an old density or species list: keep the ground, ask for the plants again
265
277
  if (r.terrain) c.regrow++; else c.pendingDetail = false;
266
278
  // a regrow stays counted until its plants are in; a new chunk asks for today's species, not the list it left with
267
- this._send({ ...this._job(c, false, r.terrain ? this.plants.baseNames() : Object.keys(r.veg)), regrow: !!(r.regrow || r.terrain) });
279
+ const names = r.terrain ? this.plants.baseNames() : Object.keys(r.veg).filter(n => this.plants.get(n)); // only species the planter still knows
280
+ if (r.terrain || names.length) this._send({ ...this._job(c, false, names), regrow: !!(r.regrow || r.terrain) });
281
+ else if (r.regrow) this._regrown(c);
268
282
  } else {
269
- for (const name in r.veg) this.plants.mount(c, name, r.veg[name]);
283
+ for (const name in r.veg) this._mountPlants(c, name, r.veg[name]);
270
284
  if (r.regrow) this._regrown(c);
271
285
  if (!r.terrain) { c.pendingDetail = false; for (const name in r.veg) c.detailDone.add(name); }
272
286
  }
@@ -284,7 +298,7 @@ export class ChunkManager {
284
298
 
285
299
  _job(c, terrain, species) {
286
300
  const ev = this.edits.version(c.key), edits = this.edits.forChunk(c.cx, c.cz);
287
- return { type: 'job', cx: c.cx, cz: c.cz, terrain, species, density: this.density, gen: this.gen, vgen: this.vgen, ev, edits };
301
+ return { type: 'job', cx: c.cx, cz: c.cz, terrain, species, density: this.density, gen: this.gen, cid: c.id, vgen: this.vgen, ev, edits };
288
302
  }
289
303
  // result built before a later edit near this chunk: drop it and ask again (a loaded chunk was already rebuilt by the edit)
290
304
  _stale(c, r) {
@@ -312,7 +326,7 @@ export class ChunkManager {
312
326
  // A failed chunk is not tried here (it was reported; the main thread would throw the same error at every commit)
313
327
  _forceReady(c) {
314
328
  if (c.state === 'ready' || c.state === 'failed') return true;
315
- 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));
329
+ const i = this.ready.findIndex(r => r.terrain && r.cx === c.cx && r.cz === c.cz && r.gen === c.gen && r.cid === c.id && r.ev === this.edits.version(c.key));
316
330
  let r = i >= 0 ? this.ready.splice(i, 1)[0] : null;
317
331
  if (!r || r.vgen !== this.vgen) {
318
332
  r = { terrain: r?.terrain ?? this.generator.buildChunk(c.cx, c.cz), veg: {} };
@@ -335,11 +349,43 @@ export class ChunkManager {
335
349
  // detailDone: this species was already placed here and came back empty; without it the empty result would reset the level and re-ask forever
336
350
  if (ring <= sp.maxRing && !has && !c.pendingDetail && !c.detailDone.has(sp.name)) {
337
351
  c.pendingDetail = true;
338
- this._send(this._job(c, false, P.nearNames()));
339
- } else if (ring > sp.maxRing + 1 && has) { P.unmount(c, sp.name); c.detailDone.delete(sp.name); }
352
+ const names = P.nearNames();
353
+ this._send(this._job(c, false, names));
354
+ } else if (ring > sp.maxRing + 1 && has) this._unplantNear(c, sp.name);
340
355
  }
341
356
  P.ring?.(c, ring);
342
357
  }
358
+ // A near-only species with a collider is gameplay (it blocks), so its colliders take effect on a tick booked from where the sources stand, not when the
359
+ // worker answers: a fast and a slow machine block the same spot at the same step. The fallback places it on the main thread when due (the same
360
+ // code as the worker), as the chunk's own collision does (_forceReady). Booked for every chunk, ready or not, in the frame a source changes chunk
361
+ // (the stream planned: _bookDue), a species changes or a record is withdrawn; the chunk's own ticket (same lag, booked earlier) is due first
362
+ _bookNear() {
363
+ for (const sp of this.plants.list()) if (sp.nearOnly && sp.rule.collider) for (const c of this.chunks.values()) this._book(c, sp);
364
+ }
365
+ /** @internal book one chunk's near-only collider ticket if its ring wants the species and none is booked */
366
+ _book(c, sp) {
367
+ const name = sp.name, ring = this._ring(c);
368
+ if (c.state === 'failed' || ring > sp.maxRing || c.near[name] || c.detailDone.has(name)) return;
369
+ const e = c.near[name] = { mounted: false, done: false, ticket: null };
370
+ e.ticket = this.engine.commits.request({
371
+ lag: colliderLag(this, ring),
372
+ apply: r => {
373
+ if (this._forceReady(c), c.state !== 'ready') return; // a source came closer after the chunk was booked: its ground first
374
+ e.done = true;
375
+ if (e.mounted) this.plants.release(c, name); else this.plants.mount(c, name, r);
376
+ },
377
+ fallback: () => this.generator.place(c.cx, c.cz, sp.rule, this.density),
378
+ valid: () => this.chunks.get(c.key) === c && c.near[name] === e,
379
+ });
380
+ }
381
+ /** @internal the one way plants of a chunk are mounted (job result, terrain edit): a near-only collider species waits for its ticket, then it is plain */
382
+ _mountPlants(c, name, r) {
383
+ const e = c.near[name], held = !!e && !e.done;
384
+ if (held) { e.mounted = true; e.ticket.resolve(r); }
385
+ this.plants.mount(c, name, r, held);
386
+ }
387
+ _cancelNear(c, name) { const e = c.near[name]; if (e) { e.ticket.remove(); delete c.near[name]; this._bookDue = true; } }
388
+ _unplantNear(c, name) { this.plants.unmount(c, name); this._cancelNear(c, name); c.detailDone.delete(name); }
343
389
 
344
390
  /** Stop the chunk workers and release the chunks with their commit tickets (called by terrain dispose; in-flight results are discarded) */
345
391
  dispose() { this.lane.dispose(); this.rebuild(); }
@@ -7,10 +7,10 @@ export function chunkHandler() {
7
7
  let T = null, species = {};
8
8
  return d => {
9
9
  if (d.type === 'init') { T = createTerrain(d.terrain); species = d.species || {}; return null; }
10
- if (d.type === 'species') { species[d.name] = d.rule; return null; }
10
+ if (d.type === 'species') { if (d.rule == null) delete species[d.name]; else 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 = { 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 };
13
+ const out = { regrow: !!d.regrow, gen: d.gen, cid: d.cid, 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
@@ -30,6 +30,7 @@ import { loadGray } from '../../core/scene/grayMap.js';
30
30
  import { prepareShape, voidWatcher } from './terrainShapeMain.js';
31
31
  import { TerrainDraw, checkGround } from './draw.js';
32
32
  import { codedError } from '../../core/base/errorHints.js';
33
+ import { onTierChange } from '../../core/scene/tier.js';
33
34
 
34
35
  const NO_HEIGHT = 'terrain(): no height function or height map was given, so the ground is flat gray at y = 0 (a placeholder, not a picture). '
35
36
  + 'Pass terrain({ height, groundType }) or a preset, e.g. terrain({ ...terrainPreset() }) with terrainPreset from @threedog/terrain-noise';
@@ -38,7 +39,8 @@ export { createTerrain, DEFAULT_TERRAIN } from './terrainGen.js';
38
39
 
39
40
  const VIEW = { viewChunks: 4, density: 1 };
40
41
  /** The rows this ground offers the settings menu; a preset's share is of the value the game gave it. Writing density places plants again, so an unchanged value stays unwritten */
41
- const offerGroundRows = (e, T) => e.settings?.define('viewChunks', T.viewChunks, v => { if (T.viewChunks !== v) T.viewChunks = v; }).define('density', T.density, v => { if (T.density !== v) T.density = v; });
42
+ // menu: false: the graphics tab draws these two itself (its slider ends follow the game's value)
43
+ const offerGroundRows = (e, T) => e.settings?.define('viewChunks', T.viewChunks, { menu: false, apply: v => { if (T.viewChunks !== v) T.viewChunks = v; } }).define('density', T.density, { menu: false, apply: v => { if (T.density !== v) T.density = v; } });
42
44
  const TERRAIN_PARAMS = keysSchema(['viewChunks', 'density', 'material', 'effects', 'detail', 'variation', 'viewFog', 'part', ...Object.keys(DEFAULT_TERRAIN)], { ...DEFAULT_TERRAIN, ...VIEW, viewFog: false }); // defaults shown in the catalog; createTerrain applies the real ones
43
45
 
44
46
  export function terrain(opts = {}) {
@@ -105,10 +107,12 @@ export function terrain(opts = {}) {
105
107
  const hm = state.cfg.heightmap, mk = state.cfg.shape?.mask;
106
108
  const needH = hm?.url && !hm.data, needM = mk?.url && !mk.data;
107
109
  if (!needH && !needM) return;
108
- const cfg2 = state.cfg = { ...state.cfg }; // recolor rebuilds from the current config
109
- if (needH) cfg2.heightmap = { ...hm, ...await loadGray(hm.url), url: undefined };
110
- if (needM) cfg2.shape = { ...cfg2.shape, mask: { ...mk, ...await loadGray(mk.url), url: undefined } };
111
- w.reinit(cfg2, speciesRules(w));
110
+ // the live object, edited in place and never swapped for a copy: the tier listener (terrainDraw install) edits colorResolution on the same object while the images
111
+ // load, and a copy taken before the await would reinit the workers at the old resolution
112
+ const live = state.cfg;
113
+ if (needH) live.heightmap = { ...hm, ...await loadGray(hm.url), url: undefined };
114
+ if (needM) live.shape = { ...live.shape, mask: { ...mk, ...await loadGray(mk.url), url: undefined } };
115
+ w.reinit(live, speciesRules(w));
112
116
  },
113
117
  isReady(e) { return e.stream.sources().every(s => w.readyAt(s)); },
114
118
  dispose() { w.dispose(); },
@@ -122,6 +126,17 @@ export function terrain(opts = {}) {
122
126
  // the colors the workers bake into each chunk: no chunk is generated before the first frame, so this reinit only swaps the config
123
127
  state.cfg = { ...state.cfg, ...drawConfig(e, cfg) };
124
128
  w.reinit(state.cfg, speciesRules(w));
129
+ // the low-tier color map follows the tier (a stored preset arrives after this install). A resolution the game gave in terrain({}) stays; recolor cannot set one
130
+ // (it is not in recolor's keys), so the only other writer is this listener. Followed by reinit, the path recolor takes too: every chunk is generated again, which is
131
+ // fine at a settings change (and before the first frame it is free). Only colorResolution is changed, on the live object: init above may still be loading images into it
132
+ ctx.track(onTierChange(e, () => {
133
+ const c = state.cfg;
134
+ if (cfg.colorResolution != null) return;
135
+ const want = drawConfig(e, { ...c, colorResolution: undefined }).colorResolution;
136
+ if (want === c.colorResolution) return;
137
+ if (want == null) delete c.colorResolution; else c.colorResolution = want; // a key holding undefined would hide createTerrain's default
138
+ w.reinit(c, speciesRules(w));
139
+ }));
125
140
  // effects false (terrain({ material, effects: false })): the game's material is drawn untouched
126
141
  drawPart = w.drawPart = new TerrainDraw(e, w, { material, effects: material == null || effects !== false, detail, sideMat,
127
142
  config: { get: () => state.cfg, set: c => { state.cfg = c; }, species: () => speciesRules(w) } });
@@ -33,7 +33,7 @@ export class TerrainEdits {
33
33
  this.t = new Map(); // cell key -> ground type of cell [i, i + 1) x [j, j + 1)
34
34
  this.ver = new Map(); // chunk key 'cx,cz' -> edit version (jobs carry it; an older result is stale)
35
35
  this.attach();
36
- ctx.saves.register('terrain', { notAtomic: 'height data is too large to copy for each atomic run, and its load rebuilds meshes', save: () => this.save(), load: d => this.load(d) });
36
+ ctx.saves.define('terrain', { notAtomic: 'height data is too large to copy for each atomic run, and its load rebuilds meshes', save: () => this.save(), load: d => this.load(d) });
37
37
  }
38
38
  /** Point the main-thread generator at the edit maps (again after the generator is rebuilt, e.g. a height map finished loading) */
39
39
  attach() { this.mgr.generator.useEdits(this.h, this.t); }
@@ -119,12 +119,16 @@ export class TerrainEdits {
119
119
  m._adopt(c, t); // data only: each draw part copies the new arrays in its change(c) hook
120
120
  m._emit('change', c);
121
121
  const P = m.plants;
122
+ c.detailDone.clear(); // edits can change what grows here, so near-only species are asked again
122
123
  for (const sp of P.list()) {
123
- if (sp.nearOnly && !c.plants[sp.name]) continue; // detail not loaded here; when it is, its job carries the edits
124
- P.mount(c, sp.name, T.place(c.cx, c.cz, sp.rule, m.density)); // an empty result drops the old plants inside vegetation.mount
124
+ const e = c.near[sp.name], here = !!c.plants[sp.name];
125
+ // a near-only collider ticket not yet applied (or an empty answer already applied) is booked again from this edit: the same tick whether or not the job had answered
126
+ if (e && (!e.done || !here)) { m._cancelNear(c, sp.name); m._book(c, sp); }
127
+ if (sp.nearOnly && !here) continue; // detail not loaded here; when it is, its job carries the edits
128
+ m._mountPlants(c, sp.name, T.place(c.cx, c.cz, sp.rule, m.density)); // an empty result drops the old plants inside vegetation.mount
125
129
  }
126
130
  // new token: the physics module rebuilds this chunk's collision; edits can change what grows here, so near-only species are asked again
127
- c.colToken = {}; c.level = -1; c.detailDone.clear();
131
+ c.colToken = {}; c.level = -1;
128
132
  }
129
133
 
130
134
  save() {
@@ -4,7 +4,7 @@
4
4
  // The map is sampled by world xz (the 'world' patch), not by uv, so the mesh uv stays free for the game's own textures.
5
5
  import * as THREE from 'three';
6
6
  import { applyEffects } from '../../render/materials.js';
7
- import { copyPatches } from '../../render/patches.js';
7
+ import { cloneMaterial } from '../../render/patches.js';
8
8
  import { maxAnisotropy } from '../../render/backend.js';
9
9
 
10
10
  /** Material for one chunk: `base` plus the color map `t` ({ data, size }) of the chunk whose origin is (ox, oz) and edge length `chunk`; kept on `rec` */
@@ -16,9 +16,11 @@ export function mountColorMap(engine, base, rec, t, ox, oz, chunk) {
16
16
  tex.wrapS = tex.wrapT = THREE.ClampToEdgeWrapping;
17
17
  tex.anisotropy = Math.min(4, maxAnisotropy(engine.renderer)); // ground is seen at grazing angles
18
18
  tex.needsUpdate = true;
19
+ // upload and mipmaps now, in the chunk's task, not in the first frame that draws it (a WebGPURenderer before init has no device yet)
20
+ if (engine.renderer.initialized !== false) engine.renderer.initTexture(tex);
19
21
  // world xz -> texture uv: pixel k is centered (k - 0.5) * chunk / R from the origin (see terrainColorMap.js); .zw = scale, offset
20
22
  const rect = new THREE.Vector4(ox, oz, R / (chunk * size), 1 / size);
21
- const mat = copyPatches(base, base.clone()), texU = { value: tex }, rectU = { value: rect };
23
+ const mat = cloneMaterial(base), texU = { value: tex }, rectU = { value: rect };
22
24
  applyEffects(mat, { clouds: false, patches: [{
23
25
  name: 'terrainColorMap', cacheKey: 1, needs: { patches: ['world'] },
24
26
  uniforms: { uTColorMap: texU, uTColorRect: rectU },
@@ -79,7 +79,7 @@ export class Timeline {
79
79
  /** @internal how runs ended, and the last failure: describe */ this._endings = { finished: 0, skipped: 0, dropped: 0, failed: 0 }; this._failure = null;
80
80
  /** Skip every cutscene immediately (set by scenario param cutscene=skip) @type {boolean} @experimental */
81
81
  this.skipAll = false;
82
- ctx.track(engine.input.action('skip', { context: 'cutscene', label: 'timeline.skipAction', optional: true, owner: 'timeline' })); // cancel skips anyway
82
+ ctx.track(engine.input.define('skip', { context: 'cutscene', label: 'timeline.skipAction', optional: true, owner: 'timeline' })); // cancel skips anyway
83
83
  buildLetterbox(this);
84
84
  }
85
85
 
@@ -159,7 +159,8 @@ export class Timeline {
159
159
  _stop(r, ending) {
160
160
  if (r.ending && r.ending !== 'skipped') return;
161
161
  r.ending = ending;
162
- this._tweener.finishAll(r);
162
+ // only a skip completes the tweens (the playthrough's end state); a drop or a failure leaves the values where they are
163
+ if (ending === 'skipped') this._tweener.finishAll(r); else this._tweener.cancelAll(r);
163
164
  for (const c of [...r.cancels]) c();
164
165
  }
165
166
 
@@ -327,7 +328,7 @@ export function timeline(opts = {}) {
327
328
  frame(dt) { t.frame(dt); },
328
329
  afterLoad() { t._drop(r => r.duringLoad); },
329
330
  // unloaded mid-cutscene: every run ends through its finally (camera, focus, actors go back); nothing else would, the frame hook is gone
330
- dispose() { t._drop(); },
331
+ dispose() { t._drop(); t._tweener.cancelAll(); }, // also the tweens started with timeline.tween(): no run owns them
331
332
  // scenario param cutscene: 'skip' | 'keep'
332
333
  stateKeys: ['cutscene'],
333
334
  applyState(e, p) {
@@ -112,6 +112,9 @@ export class Tweener {
112
112
  /** Jump a group of tasks (or all) to their end */
113
113
  finishAll(group) { for (const t of [...this.list]) if (group === undefined || t.group === group) t.finish(); }
114
114
 
115
+ /** Stop a group of tasks (or all) where they are: nothing is written, what they hold goes back (a dropped cutscene must not paint its end values over a loaded state) */
116
+ cancelAll(group) { for (const t of [...this.list]) if (group === undefined || t.group === group) t.cancel(); }
117
+
115
118
  /** The one way a task ends: k 1 jumps to the end, null stops where it is. failed { error }: a throw on the way, and the first one is the promise's answer. So finish() never throws and finishAll reaches every task */
116
119
  _complete(task, k, failed = null) {
117
120
  if (task.done) return;
@@ -19,6 +19,7 @@ background:none;border:0;cursor:pointer;pointer-events:auto;opacity:0;transition
19
19
  t.skipBtn.type = 'button'; t.skipBtn.className = 'threedog-letterbox-skip';
20
20
  t.skipBtn.addEventListener('click', () => { for (const r of t.runs) if (r.skippable) t.skip(r); });
21
21
  t.bottom.appendChild(t.skipBtn);
22
+ t._track({ remove() { t.top.remove(); t.bottom.remove(); } }); // the bars own the button and its click listener
22
23
  t._track(t.engine.events.on('i18n:change', () => t._refreshUI()));
23
24
  t._track(t.engine.events.on('input:rebind', () => t._refreshUI()));
24
25
  }
@@ -39,11 +39,13 @@
39
39
  // The debug lines take their color from triggers({ debugColor, debugOpacity }); neutral gray if absent.
40
40
  // The action triggersDebug toggles that view; it has no key of its own (presets.bindings.debug binds F4 with the debug panel's F3).
41
41
  import { engineOwned } from '../../core/scene/things.js';
42
+ import { freeParts } from '../../core/base/freeParts.js';
42
43
  import * as THREE from 'three';
43
44
  import { readParams, keysSchema } from '../../core/base/params.js';
44
45
  import { Cells } from '../../core/stream/cells.js';
45
46
  import { codedError } from '../../core/base/errorHints.js';
46
47
  import { placeY } from '../../core/scene/ground.js';
48
+ import { reportError } from '../../core/base/errors.js';
47
49
 
48
50
  // Zones are indexed (core/stream/cells.js, the shared xz index) by the cells their bounding box covers, so a step looks at the zones near the actor instead of every
49
51
  // zone. A zone with its own `who` (any position, unknown until it runs) or one covering more than MAX_CELLS cells goes to the always-checked `_global` list.
@@ -75,7 +77,7 @@ export class Triggers {
75
77
  this._seq = 0; this._stamp = 0;
76
78
  /** @internal the wireframe group while the debug view 'triggers' is on (null otherwise) */ this._view = null;
77
79
  engine.i18n.add(STRINGS);
78
- track(engine.input.action(action, { label: 'triggers.debug', optional: true, owner: 'triggers' })); // a dev tool: silent while unbound
80
+ track(engine.input.define(action, { label: 'triggers.debug', optional: true, owner: 'triggers' })); // a dev tool: silent while unbound
79
81
  /** @internal */ this._viewDef = engine.debug.defineView('triggers', { what: 'every trigger zone drawn as a wireframe over the real picture (triggers({ debugColor }))', apply: scene => this._drawView(scene) });
80
82
  }
81
83
 
@@ -110,9 +112,11 @@ export class Triggers {
110
112
  t._gone = true;
111
113
  const i = this._list.indexOf(t); if (i >= 0) this._list.splice(i, 1);
112
114
  this._unregister(t); this._busy.delete(t);
113
- if (t.inside) this._exit(t, null);
114
- if (t._mesh) { t._mesh.parent?.remove(t._mesh); t._mesh.geometry.dispose(); t._mesh = null; }
115
+ try { if (t.inside) this._exit(t, null); }
116
+ finally { if (t._mesh) { t._mesh.parent?.remove(t._mesh); t._mesh.geometry.dispose(); t._mesh = null; } } // an onExit that throws still frees the debug mesh
115
117
  }
118
+ /** @internal remove each zone in its own try: one onExit that throws must not leave the rest (nor their debug meshes) standing; the error is reported and the loop goes on */
119
+ _removeEach(zones, what) { for (const t of zones) { try { t.remove(); } catch (err) { reportError(this.engine, err, what); } } }
116
120
  _register(t) {
117
121
  if (t.who || (t.volume && !t.volume.bounds)) { this._global.push(t); return; }
118
122
  const ex = (t.shape === 'box' || t.volume ? t.hx * Math.abs(t.c) + t.hz * Math.abs(t.s) : t.radius) + PAD;
@@ -125,7 +129,7 @@ export class Triggers {
125
129
  }
126
130
  /** All trigger zones (a new array) */
127
131
  list() { return [...this._list]; }
128
- clear() { for (const t of [...this._list]) this._remove(t); }
132
+ clear() { this._removeEach([...this._list], 'triggers.clear'); }
129
133
  byTag(tag) { return this._list.filter(t => t.tag === tag); }
130
134
 
131
135
  /**
@@ -219,9 +223,12 @@ export class Triggers {
219
223
  if (hit && !t.inside) {
220
224
  if (t._cool > 0) return;
221
225
  t.inside = true; t._id = id;
226
+ if (t.once) t.used = true; // spent before any callback runs: a save made inside onEnter or a trigger:enter listener already records it
222
227
  t.onEnter?.(t, hit, id);
228
+ if (t._gone) return; // onEnter removed the zone: remove() already ran its exit, so no enter event may follow it
223
229
  e.events.emit('trigger:enter', { tag: t.tag, trigger: t, who: hit, id });
224
- if (t.once) { t.used = true; this._exit(t, null); }
230
+ if (t._gone) return; // a trigger:enter listener removed it: its exit has run too
231
+ if (t.once) this._exit(t, null);
225
232
  } else if (!hit && t.inside) this._exit(t, null);
226
233
  else if (hit && t.inside) t.onStay?.(dt, t, hit, id);
227
234
  }
@@ -235,10 +242,12 @@ export class Triggers {
235
242
  if (inn.has(key)) { t.onStay?.(dt, t, o.p, o.id); if (t._gone) return; continue; }
236
243
  if (t._cool > 0 && !inn.size) return;
237
244
  inn.set(key, o); t.inside = true;
245
+ if (t.once) t.used = true; // spent before any callback (see _visit)
238
246
  t.onEnter?.(t, o.p, o.id);
247
+ if (t._gone) return; // as _visit: no enter event after the exit remove() ran
239
248
  e.events.emit('trigger:enter', { tag: t.tag, trigger: t, who: o.p, id: o.id });
240
249
  if (t._gone) return;
241
- if (t.once) { t.used = true; this._exit(t, null); return; }
250
+ if (t.once) { this._exit(t, null); return; }
242
251
  }
243
252
  }
244
253
  /** @internal one actor left: the callback and the event */
@@ -257,7 +266,7 @@ export class Triggers {
257
266
  this._list.forEach((t, i) => { if (t.used || t._cool > 0) out[keys[i]] = { used: t.used, cool: t._cool }; });
258
267
  return out;
259
268
  }
260
- /** @internal occupied zones exit (who is null), then used / cooldown come from the save; zones the save does not name start fresh */
269
+ /** @internal occupied zones exit (who is null; first: 1, after the level, so onExit and its effects run before the other parts restore and whatever they wrote is overwritten by the save), then used / cooldown come from the save; zones the save does not name start fresh */
261
270
  _load(d) {
262
271
  for (const t of [...this._list]) if (t.inside) this._exit(t, null);
263
272
  const keys = this._keys();
@@ -271,7 +280,13 @@ export class Triggers {
271
280
  // id: who was inside (remembered at enter), so an exit says who left even though the position that left is gone
272
281
  const id = t._id ?? null, all = t._in ? [...t._in.values()] : null;
273
282
  t.inside = false; t._cool = t.cooldown; t._id = null;
274
- if (all) { t._in.clear(); for (const o of all) this._left(t, who, o.id); return; } // occupancy 'each': everyone leaves
283
+ if (all) { // occupancy 'each': everyone leaves, each in its own try (the first throw is raised after the last exit has run)
284
+ t._in.clear();
285
+ let first, bad = false;
286
+ for (const o of all) { try { this._left(t, who, o.id); } catch (err) { if (!bad) { bad = true; first = err; } } }
287
+ if (bad) throw first;
288
+ return;
289
+ }
275
290
  this._left(t, who, id);
276
291
  }
277
292
 
@@ -288,7 +303,7 @@ export class Triggers {
288
303
  scene.add(engineOwned('triggers', g));
289
304
  return () => {
290
305
  for (const t of this._list) t._mesh = null;
291
- g.traverse(o => o.geometry?.dispose());
306
+ freeParts(g, x => x.isBufferGeometry); // each debug mesh's geometry is this overlay's; the one line material goes below
292
307
  g.removeFromParent(); this._mat.dispose();
293
308
  if (this._view === g) this._view = null;
294
309
  };
@@ -319,7 +334,7 @@ const TRIGGER_PARAMS = {
319
334
  */
320
335
  function triggerContent() {
321
336
  const table = {};
322
- let subs = null;
337
+ let subsTrack = null, fromLevel = [];
323
338
  return {
324
339
  desc: 'trigger zones (tag -> position / from level, enter/exit effects)',
325
340
  undo(d, { engine: e }) {
@@ -332,12 +347,15 @@ function triggerContent() {
332
347
  },
333
348
  commit(d, { engine: e, content, where, bind, track }) {
334
349
  Object.assign(table, d);
335
- if (Object.values(d).some(t => t.fromLevel)) e.triggers.fromMarkers();
350
+ // one set per content commit: a second commit (the same level loaded twice) replaces its own zones, never the ones a game's own fromMarkers() made
351
+ e.triggers._removeEach(fromLevel, 'triggers replace');
352
+ fromLevel = Object.values(d).some(t => t.fromLevel) ? e.triggers.fromMarkers() : [];
336
353
  for (const [tag, t] of Object.entries(d)) if (!t.fromLevel) bind(e.triggers.add({ ...t, tag, position: where(t.position), onEnter: null, onExit: null }), t.position);
337
- subs ??= [
338
- track(e.events.on('trigger:enter', ({ tag, id }) => content.run(table[tag]?.onEnter, { actor: id ?? e.actor }))),
339
- track(e.events.on('trigger:exit', ({ tag, id }) => content.run(table[tag]?.onExit, { actor: id ?? e.actor }))),
340
- ];
354
+ if (subsTrack !== track) { // a new content module has a new track: the old one's listeners were removed with it, so they are made again
355
+ subsTrack = track;
356
+ track(e.events.on('trigger:enter', ({ tag, id }) => content.run(table[tag]?.onEnter, { actor: id ?? e.actor })));
357
+ track(e.events.on('trigger:exit', ({ tag, id }) => content.run(table[tag]?.onExit, { actor: id ?? e.actor })));
358
+ }
341
359
  },
342
360
  };
343
361
  }
@@ -353,13 +371,14 @@ export function triggers(opts = {}) {
353
371
  tr = new Triggers(e, o, ctx.track);
354
372
  // audio rule condition { zone: 'cave' | ['cave', 'mine'] }: some trigger zone with that tag is occupied
355
373
  ctx.track(e.audio.condition('zone', v => [].concat(v).some(tag => tr.byTag(tag).some(t => t.inside))));
356
- ctx.saves.register('triggers', { notAtomic: 'bodies crossing a zone change it in the step, and its load fires exits', save: () => tr._save(), load: d => tr._load(d) });
374
+ ctx.saves.define('triggers', { notAtomic: 'bodies crossing a zone change it in the step, and its load fires exits', first: 1, save: () => tr._save(), load: d => tr._load(d) });
357
375
  return tr;
358
376
  },
359
377
  fixed(dt) { tr.update(dt); },
360
378
  // the key toggles the same debug view an AI calls: no second display path to keep in step
361
379
  frame(dt, e) { if (e.input.pressed(tr.action)) e.debug.view(e.debug.viewState().mode === 'triggers' ? 'off' : 'triggers'); },
362
- dispose() { tr._viewDef.remove(); }, // turns the view off when it is the triggers one, and drops the mode
380
+ // turns the view off when it is the triggers one, drops the mode, and removes every zone as remove() does (exits fire; a level's zones too, so its later removal of the handles is a no-op)
381
+ dispose() { tr._viewDef.remove(); tr._removeEach([...tr._list], 'triggers dispose'); },
363
382
  describe(e, ctx) {
364
383
  for (const t of tr._list) if (t.enabled && !t.used) ctx.near(t, { name: t.tag || t.shape, kind: 'trigger', inside: t.inside });
365
384
  return { inside: tr._list.filter(t => t.inside).map(t => t.tag || t.shape), used: tr._list.filter(t => t.used).map(t => t.tag || t.shape) };