threedog 1.0.1 → 1.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (364) hide show
  1. package/CHANGELOG.md +90 -0
  2. package/README.md +1 -1
  3. package/core/assets/Animator.js +41 -3
  4. package/core/assets/Assets.js +100 -24
  5. package/core/assets/assetEntry.js +73 -20
  6. package/core/assets/assetHot.js +68 -16
  7. package/core/assets/assetLoad.js +6 -6
  8. package/core/assets/assetLod.js +9 -2
  9. package/core/assets/assetManifest.js +12 -2
  10. package/core/assets/assetPart.js +54 -0
  11. package/core/assets/ik.js +271 -0
  12. package/core/assets/modelNeeds.js +37 -0
  13. package/core/assets/namedModel.js +102 -29
  14. package/core/assets/nodeVisibility.js +15 -0
  15. package/core/audio/Audio.js +36 -4
  16. package/core/audio/audioReverb.js +99 -0
  17. package/core/audio/audioRules.js +1 -1
  18. package/core/audio/audioVoice.js +1 -1
  19. package/core/base/Events.js +14 -4
  20. package/core/base/Random.js +1 -1
  21. package/core/base/Vars.js +1 -1
  22. package/core/base/docRef.js +51 -0
  23. package/core/base/errorCodes.js +178 -126
  24. package/core/base/errorHints.js +9 -7
  25. package/core/base/errors.js +25 -10
  26. package/core/base/events.generated.js +2 -0
  27. package/core/base/freeParts.js +76 -0
  28. package/core/base/math.js +28 -0
  29. package/core/base/sections.js +5 -5
  30. package/core/base/validate.js +31 -3
  31. package/core/engine/Engine.js +16 -6
  32. package/core/engine/Loading.js +5 -3
  33. package/core/engine/copies.js +1 -1
  34. package/core/engine/headlessLoad.js +4 -1
  35. package/core/engine/lifecycle.js +32 -16
  36. package/core/engine/loop.js +71 -27
  37. package/core/engine/moduleSlots.js +2 -2
  38. package/core/engine/moduleTypes.js +3 -3
  39. package/core/engine/modules.js +65 -39
  40. package/core/engine/page.js +6 -3
  41. package/core/engine/services.js +6 -5
  42. package/core/engine/startup.js +5 -5
  43. package/core/input/Input.js +28 -14
  44. package/core/input/inputContext.js +28 -16
  45. package/core/input/inputKeyboard.js +31 -3
  46. package/core/input/inputPad.js +4 -0
  47. package/core/input/inputPointer.js +2 -1
  48. package/core/input/inputSeat.js +1 -1
  49. package/core/inspect/Budget.js +109 -19
  50. package/core/inspect/DebugOverrides.js +28 -4
  51. package/core/inspect/Describe.js +17 -9
  52. package/core/inspect/Inspect.js +4 -2
  53. package/core/inspect/InspectMaterials.js +3 -1
  54. package/core/inspect/InspectPerf.js +19 -9
  55. package/core/inspect/InspectScene.js +32 -7
  56. package/core/inspect/MaterialInfo.js +19 -2
  57. package/core/inspect/UrlState.js +46 -27
  58. package/core/inspect/catalog.js +28 -9
  59. package/core/inspect/debugView.js +2 -1
  60. package/core/inspect/describeRender.js +25 -13
  61. package/core/inspect/describeText.js +14 -6
  62. package/core/inspect/lightWatch.js +1 -1
  63. package/core/inspect/metadata.generated.js +35 -17
  64. package/core/inspect/pictureChecks.js +148 -0
  65. package/core/inspect/pictureMenu.js +84 -0
  66. package/core/inspect/pictureWriters.js +26 -6
  67. package/core/inspect/textureBytes.js +12 -2
  68. package/core/inspect/toolDoor.js +2 -4
  69. package/core/ops/Ops.js +11 -4
  70. package/core/ops/holds.js +27 -10
  71. package/core/ops/opsAtomic.js +15 -7
  72. package/core/ops/opsGuard.js +2 -2
  73. package/core/ops/opsRun.js +8 -7
  74. package/core/ops/sharedPoint.js +72 -21
  75. package/core/ops/stacks.js +56 -16
  76. package/core/saves/SaveStore.js +9 -3
  77. package/core/saves/Saves.js +32 -23
  78. package/core/saves/saveApply.js +96 -44
  79. package/core/saves/saveIds.js +1 -1
  80. package/core/saves/saveVersions.js +7 -5
  81. package/core/saves/session.js +17 -8
  82. package/core/saves/stateReplace.js +34 -15
  83. package/core/scene/Rays.js +52 -10
  84. package/core/scene/Views.js +13 -7
  85. package/core/scene/adaptive.js +144 -21
  86. package/core/scene/drawOnly.js +17 -0
  87. package/core/scene/gameLights.js +44 -3
  88. package/core/scene/sceneMethods.js +13 -11
  89. package/core/scene/stepPoses.js +11 -3
  90. package/core/scene/targeting.js +5 -3
  91. package/core/scene/thingOps.js +1 -1
  92. package/core/scene/tier.js +15 -0
  93. package/core/stream/Batching.js +30 -7
  94. package/core/stream/Stream.js +26 -7
  95. package/core/stream/batchGroups.js +2 -2
  96. package/core/stream/chunkStream.js +7 -5
  97. package/core/stream/prepare.js +77 -0
  98. package/core/time/skip.js +3 -1
  99. package/core/time/time.js +4 -2
  100. package/docs/AI.md +82 -83
  101. package/docs/API.md +16 -16
  102. package/docs/CODEMAP.md +16 -11
  103. package/docs/COMMANDS.md +31 -33
  104. package/docs/CONVENTIONS.md +37 -49
  105. package/docs/MIGRATING-0.8.md +2 -2
  106. package/docs/MIGRATING-1.0.md +2 -2
  107. package/docs/THREE.md +28 -35
  108. package/docs/api/assets.md +3 -1
  109. package/docs/api/audio.md +4 -2
  110. package/docs/api/budget.md +5 -0
  111. package/docs/api/cameraRig.md +2 -2
  112. package/docs/api/characters.md +10 -8
  113. package/docs/api/collision.md +6 -4
  114. package/docs/api/engine.md +16 -16
  115. package/docs/api/events.md +3 -2
  116. package/docs/api/ground.md +6 -5
  117. package/docs/api/hud.md +4 -2
  118. package/docs/api/input.md +5 -5
  119. package/docs/api/particles.md +2 -1
  120. package/docs/api/photo.md +3 -0
  121. package/docs/api/post.md +7 -4
  122. package/docs/api/quests.md +2 -2
  123. package/docs/api/rays.md +1 -2
  124. package/docs/api/saves.md +7 -7
  125. package/docs/api/settings.md +2 -2
  126. package/docs/api/tools.md +3 -1
  127. package/docs/api/vars.md +1 -1
  128. package/docs/api/vegetation.md +4 -2
  129. package/docs/api/world.md +1 -1
  130. package/docs/recipes/01-new-game.md +16 -17
  131. package/docs/recipes/02-npc.md +22 -18
  132. package/docs/recipes/03-items-pickups.md +37 -35
  133. package/docs/recipes/04-quests.md +15 -10
  134. package/docs/recipes/05-props-bake.md +101 -95
  135. package/docs/recipes/06-clock-events.md +28 -28
  136. package/docs/recipes/07-flow-scenes-pause.md +29 -26
  137. package/docs/recipes/08-weather-sky.md +52 -64
  138. package/docs/recipes/09-materials-lights-models.md +26 -17
  139. package/docs/recipes/10-blender-level.md +15 -10
  140. package/docs/recipes/11-vehicles.md +12 -7
  141. package/docs/recipes/12-navmesh.md +44 -26
  142. package/docs/recipes/13-animation.md +56 -45
  143. package/docs/recipes/14-custom-module.md +21 -18
  144. package/docs/recipes/15-perf.md +61 -55
  145. package/docs/recipes/16-dev-bridge.md +23 -33
  146. package/docs/recipes/18-world.md +36 -42
  147. package/docs/recipes/19-shooting-picking.md +20 -15
  148. package/docs/recipes/20-content-actions-save.md +48 -56
  149. package/docs/recipes/21-camera.md +45 -54
  150. package/docs/recipes/22-shop-gold.md +12 -7
  151. package/docs/recipes/23-ops.md +25 -23
  152. package/docs/recipes/26-ui-parts.md +67 -47
  153. package/docs/recipes/27-net.md +12 -7
  154. package/docs/recipes/28-terrain.md +24 -21
  155. package/docs/recipes/29-grid.md +32 -27
  156. package/docs/recipes/30-templates.md +21 -20
  157. package/docs/recipes/31-audio.md +39 -22
  158. package/docs/recipes/32-action-game.md +19 -14
  159. package/docs/recipes/33-stream-sources.md +15 -11
  160. package/docs/recipes/34-environment-lighting.md +126 -70
  161. package/docs/recipes/35-picture-from-reference.md +8 -8
  162. package/docs/recipes/36-ground-plants.md +27 -21
  163. package/docs/recipes/40-scene.md +19 -28
  164. package/docs/recipes/43-shader-patches-surfaces.md +15 -12
  165. package/docs/recipes/44-water-weather-hooks.md +34 -31
  166. package/docs/recipes/45-cascaded-shadows.md +35 -26
  167. package/docs/recipes/46-blender-art-route.md +6 -1
  168. package/docs/recipes/49-game-module-contract.md +13 -8
  169. package/docs/recipes/50-own-renderer.md +6 -2
  170. package/docs/recipes/51-capability-catalog.md +15 -8
  171. package/docs/recipes/52-around-the-picture.md +34 -32
  172. package/docs/recipes/53-ground-up-close.md +6 -1
  173. package/docs/recipes/55-mods-time-wrap.md +27 -19
  174. package/docs/recipes/56-webgpu-tsl.md +74 -43
  175. package/docs/recipes/57-control.md +18 -13
  176. package/docs/recipes/58-input.md +26 -16
  177. package/docs/recipes/59-depth-post-effects.md +8 -3
  178. package/docs/recipes/60-judge-the-picture.md +9 -8
  179. package/docs/recipes/61-deploy.md +5 -0
  180. package/docs/recipes/62-picture-code.md +70 -79
  181. package/docs/recipes/63-third-person-start.md +47 -45
  182. package/docs/recipes/64-particles.md +22 -10
  183. package/docs/recipes/65-swarm.md +18 -13
  184. package/docs/recipes/66-common-tasks.md +38 -35
  185. package/examples/action/GAMEMAP.md +2 -3
  186. package/examples/action/main.js +3 -3
  187. package/examples/action/picture/lights.js +3 -1
  188. package/examples/perf-island/GAMEMAP.md +3 -3
  189. package/examples/perf-island/picture/lights.js +2 -1
  190. package/examples/plain-picture/GAMEMAP.md +1 -1
  191. package/examples/rc2d/GAMEMAP.md +1 -1
  192. package/examples/styletest/GAMEMAP.md +2 -2
  193. package/examples/styletest/main.js +1 -1
  194. package/examples/techniques/interior-light/README.md +3 -3
  195. package/examples/techniques/interior-light/interiorLight.js +2 -4
  196. package/examples/techniques/interior-light/picture/lights.js +2 -1
  197. package/examples/techniques/modular-building/picture/lights.js +3 -1
  198. package/examples/techniques/outlines-and-rim/picture/lights.js +3 -1
  199. package/examples/techniques/procedural-animation/README.md +1 -1
  200. package/examples/techniques/procedural-animation/main.js +1 -1
  201. package/examples/webgpu-tsl/GAMEMAP.md +1 -1
  202. package/examples/world/GAMEMAP.md +2 -3
  203. package/examples/world/art/humanoid.js +1 -1
  204. package/examples/world/main.js +6 -3
  205. package/index.d.ts +2 -2
  206. package/llms.txt +101 -0
  207. package/modules/ambience/Ambience.js +21 -5
  208. package/modules/calendar/index.js +9 -5
  209. package/modules/calendar/schedule.js +23 -8
  210. package/modules/camera/FirstPersonCamera.js +3 -1
  211. package/modules/camera/FollowCamera.js +10 -5
  212. package/modules/camera/RtsCamera.js +4 -3
  213. package/modules/camera/common.js +70 -8
  214. package/modules/camera/contract.js +1 -1
  215. package/modules/characters/Character.js +16 -10
  216. package/modules/characters/NPC.js +31 -19
  217. package/modules/characters/assetModel.js +14 -9
  218. package/modules/characters/astar.js +6 -1
  219. package/modules/characters/contract.js +2 -2
  220. package/modules/characters/index.js +34 -22
  221. package/modules/characters/movers/manual.js +1 -1
  222. package/modules/characters/movers/rapier.js +17 -2
  223. package/modules/characters/movers/simple.js +1 -1
  224. package/modules/characters/movers/support.js +16 -7
  225. package/modules/characters/npcAvoid.js +2 -2
  226. package/modules/characters/npcSim.js +3 -2
  227. package/modules/characters/pathAsync.js +24 -8
  228. package/modules/characters/pathJob.js +1 -1
  229. package/modules/characters/player.js +10 -9
  230. package/modules/characters/playerStrings.js +5 -5
  231. package/modules/characters/proceduralRig.js +5 -5
  232. package/modules/characters/useModel.js +6 -0
  233. package/modules/characters/walkTo.js +1 -1
  234. package/modules/collision/Collision.js +29 -18
  235. package/modules/collision/grid.js +22 -4
  236. package/modules/content/index.js +3 -1
  237. package/modules/content/loader.js +1 -1
  238. package/modules/content/models.js +82 -33
  239. package/modules/content/props.js +2 -1
  240. package/modules/content/rules.js +11 -5
  241. package/modules/content/templates.js +3 -3
  242. package/modules/content/words.js +2 -2
  243. package/modules/debug/DebugPanel.js +9 -9
  244. package/modules/flow/index.js +9 -6
  245. package/modules/gameplay/Dialogue.js +34 -20
  246. package/modules/gameplay/Interactions.js +19 -15
  247. package/modules/gameplay/Inventory.js +9 -4
  248. package/modules/gameplay/Quests.js +12 -10
  249. package/modules/gameplay/pickups.js +23 -11
  250. package/modules/grid/index.js +1 -1
  251. package/modules/grid/preview.js +2 -2
  252. package/modules/grid/tiles.js +1 -1
  253. package/modules/hlod/index.js +4 -1
  254. package/modules/hud/index.js +47 -10
  255. package/modules/hud/parts.js +28 -9
  256. package/modules/level/geometry.js +8 -3
  257. package/modules/level/index.js +10 -5
  258. package/modules/level/load.js +4 -2
  259. package/modules/lights/sources.js +1 -1
  260. package/modules/music/Music.js +22 -4
  261. package/modules/nav/index.js +20 -10
  262. package/modules/particles/Particles.js +31 -14
  263. package/modules/particles/effect.js +20 -5
  264. package/modules/particles/lit.js +72 -0
  265. package/modules/photo/Photo.js +72 -28
  266. package/modules/photo/pathTrace.js +106 -0
  267. package/modules/rigid/RigidBodies.js +23 -14
  268. package/modules/rigid/Vehicles.js +3 -13
  269. package/modules/rigid/sync.js +2 -1
  270. package/modules/settings/Settings.js +52 -20
  271. package/modules/settings/apply.js +23 -9
  272. package/modules/settings/sections.js +39 -6
  273. package/modules/settings/strings.js +2 -0
  274. package/modules/settings/view.js +19 -3
  275. package/modules/sky/dome.js +15 -3
  276. package/modules/sky/environment.js +28 -12
  277. package/modules/sky/fog.js +1 -1
  278. package/modules/sky/frame.js +6 -1
  279. package/modules/sky/shader.js +4 -3
  280. package/modules/sky/skyModule.js +8 -4
  281. package/modules/swarm/Swarm.js +1 -1
  282. package/modules/terrain/ChunkManager.js +61 -15
  283. package/modules/terrain/chunkJob.js +2 -2
  284. package/modules/terrain/index.js +20 -5
  285. package/modules/terrain/terrainEdit.js +8 -4
  286. package/modules/terrain/terrainTexture.js +4 -2
  287. package/modules/timeline/Timeline.js +4 -3
  288. package/modules/timeline/Tween.js +3 -0
  289. package/modules/timeline/letterbox.js +1 -0
  290. package/modules/triggers/index.js +36 -17
  291. package/modules/vegetation/Vegetation.js +81 -19
  292. package/modules/vegetation/densityMap.js +13 -8
  293. package/modules/vegetation/draw.js +147 -24
  294. package/modules/vegetation/groundChunks.js +20 -5
  295. package/modules/vegetation/index.js +3 -3
  296. package/modules/vegetation/modelGeometry.js +9 -4
  297. package/modules/water/Water.js +11 -8
  298. package/modules/weather/Weather.js +7 -2
  299. package/modules/weather/shaders.js +25 -5
  300. package/modules/weather/weatherDraw.js +20 -6
  301. package/modules/world/World.js +2 -1
  302. package/modules/world/index.js +2 -2
  303. package/modules/world/persist.js +6 -2
  304. package/modules/world/views.js +15 -2
  305. package/package.json +4 -1
  306. package/presets.js +5 -5
  307. package/render/PostFX.js +84 -41
  308. package/render/backend.js +137 -16
  309. package/render/cascades.js +3 -1
  310. package/render/cascades.tsl.js +2 -0
  311. package/render/daylight.js +7 -1
  312. package/render/detail.js +7 -4
  313. package/render/effects.js +27 -8
  314. package/render/fogLook.js +24 -0
  315. package/render/fuse.js +5 -2
  316. package/render/fx/detail.tsl.js +9 -7
  317. package/render/fx/index.js +7 -2
  318. package/render/fx/library.tsl.js +1 -0
  319. package/render/fx/lightShaft.tsl.js +114 -0
  320. package/render/fx/noise.tsl.js +25 -8
  321. package/render/fx/objectOrigin.tsl.js +39 -10
  322. package/render/fx/particles.tsl.js +23 -6
  323. package/render/fx/patchNodes.tsl.js +17 -12
  324. package/render/fx/pcss.tsl.js +51 -0
  325. package/render/fx/postWebGPU.tsl.js +89 -29
  326. package/render/fx/sky.tsl.js +3 -9
  327. package/render/fxNumbers.js +10 -4
  328. package/render/impostor.tsl.js +107 -0
  329. package/render/lighting.js +33 -1
  330. package/render/lightmap.js +42 -28
  331. package/render/lights.js +19 -3
  332. package/render/materials.js +6 -4
  333. package/render/mergeCommon.js +4 -1
  334. package/render/occlusion.js +14 -4
  335. package/render/patches.js +79 -41
  336. package/render/postRuns.js +32 -0
  337. package/render/postWebGL.js +97 -10
  338. package/render/probes.js +10 -14
  339. package/render/shaderErrors.js +2 -1
  340. package/render/shadowCache.tsl.js +33 -5
  341. package/render/shadows.js +42 -16
  342. package/render/slots.js +8 -5
  343. package/render/vertexInputs.js +52 -0
  344. package/types/core.d.ts +114 -46
  345. package/types/gameplay.d.ts +56 -23
  346. package/types/generated/core/audio/Audio.d.ts +27 -1
  347. package/types/generated/core/base/Random.d.ts +1 -1
  348. package/types/generated/core/input/Input.d.ts +6 -8
  349. package/types/generated/core/input/inputSeat.d.ts +1 -1
  350. package/types/generated/core/inspect/Budget.d.ts +26 -0
  351. package/types/generated/core/inspect/DebugOverrides.d.ts +0 -2
  352. package/types/generated/core/saves/Saves.d.ts +10 -7
  353. package/types/generated/core/saves/session.d.ts +8 -2
  354. package/types/generated/core/scene/Rays.d.ts +1 -3
  355. package/types/generated/modules/particles/Particles.d.ts +1 -1
  356. package/types/generated/modules/world/World.d.ts +2 -1
  357. package/types/generated/render/PostFX.d.ts +35 -9
  358. package/types/physics.d.ts +43 -11
  359. package/types/pixel.d.ts +1 -1
  360. package/types/tsl.d.ts +62 -1
  361. package/types/world.d.ts +12 -3
  362. package/ui/Focus.js +7 -5
  363. package/ui/Parts.js +1 -1
  364. package/ui/touchPart.js +6 -3
@@ -6,7 +6,7 @@
6
6
  // engine.use(collision(), rigid(), followCamera(), characters(), level({ url: '/models/town.glb' }), triggers());
7
7
  // engine.events.on('level:loaded', ({ markers }) => {
8
8
  // const s = engine.level.spawn; // spawn point { x, y, z }
9
- // engine.characters.createPlayer({ spawn: { x: s.x, z: s.z } });
9
+ // engine.characters.addPlayer({ spawn: { x: s.x, z: s.z } });
10
10
  // engine.triggers.fromMarkers({ onEnter: t => console.log('entered', t.tag) });
11
11
  // });
12
12
  // engine.start();
@@ -60,6 +60,7 @@
60
60
  // Events: level:loading { source }, then level:failed { source, error } or level:loaded { root, markers, spawn } (state committed), then level:playable { root }.
61
61
  // level:unloaded { source } says a level left: on unload(), and on a switch just before the new one commits. What was built from the level goes on it
62
62
  // Picture: the level module draws nothing itself, the scene looks entirely like your model, so it does not read the style.
63
+ import { reportError } from '../../core/base/errors.js';
63
64
  import * as THREE from 'three';
64
65
  import { readParams, keysSchema } from '../../core/base/params.js';
65
66
  import { levelNodes } from './nodes.js';
@@ -97,11 +98,13 @@ function levelApi(st) {
97
98
  /** Unload the level: remove from scene, delete colliders, ground reverts to the outside height */
98
99
  unload() {
99
100
  const source = api.root ? st.current : undefined; // undefined: no level stood here, nobody needs telling
100
- for (const h of [...st.removers.splice(0), ...st.walls.splice(0)]) h.remove();
101
+ // each handle in its own try: one that throws (a trigger's onExit) must not leave the rest, nor the level root, standing; the unload finishes, the error is reported (engine.error in dev, console in release), and the unload goes on
102
+ for (const h of [...st.removers.splice(0), ...st.walls.splice(0)]) { try { h.remove(); } catch (err) { reportError(st.e, err, 'level unload'); } }
101
103
  if (api.root && st.o.addToScene) st.e.remove(api.root); // full removal (geometries and materials shared by assets are not disposed)
102
- st.walkMeshes.length = 0; st.hf = api.heightfield = null; st.colliders = null; st.wallsIn.reset(); st.trimeshCache = null; api.markers = {}; api.root = null; st.current = null; st.version++; dropAsks(st); st.playable = false;
104
+ st.walkMeshes.length = 0; st.hf = api.heightfield = null; st.colliders = null; st.wallsIn.reset(); st.trimeshCache = null; api.markers = {}; api.root = null; st.current = null; st.version++; dropAsks(st);
103
105
  st.done = true; st.playable = false; // nothing is loading now: a file still on its way is dropped, and no finishLoad would ever come for it (load sets it back)
104
106
  if (source !== undefined) {
107
+ st.unloaded = true; // a level stood and left: only then is "no level" a fact worth saving (a session that never had one saves nothing, so its new-game state keeps a level loaded later)
105
108
  // a level that left takes its zone and spawn with it: the next scene's nodes must not be placed in a zone that is gone
106
109
  api.spawn = new THREE.Vector3();
107
110
  if (st.e.world) st.e.world.zone = null;
@@ -114,6 +117,7 @@ function levelApi(st) {
114
117
  return api;
115
118
  }
116
119
 
120
+ const NONE = { none: true }; // saved when no level stands: null means "nothing to save" to the save system, and a load without the part keeps the level that stands
117
121
  const OPENING = '(opening scene)'; // no file or asset can be named this
118
122
 
119
123
  /** What the save holds for a level built in code. Weak: a token in a stored save must not keep every level this page ever built in memory */
@@ -169,14 +173,15 @@ export function level(opts = {}) {
169
173
  // load returns a Promise: the save system waits for the new level (old level's trigger zones are already removed by unload) before reading player
170
174
  // position etc.
171
175
  // a save that names this level, or none, stays here: a load on its way would land on top of what the save put back
172
- // The level a holder stood on comes back through the same part when a module takes over the key (Saves.register): a swap keeps the game where it was, and a pack's older
176
+ // The level a holder stood on comes back through the same part when a module takes over the key (Saves.define): a swap keeps the game where it was, and a pack's older
173
177
  // level must not take it back (the section's once). A newcomer that says where to open keeps that promise; the same definition put back after a failed swap has none to make
174
178
  // the opening scene has no name either, so it saves as OPENING: a new game goes back to it, and a save from before this mark takes it from the new-game state
175
179
  const opens = !st.installed && (scene || url);
176
180
  let installing = st.installed = true;
177
181
  st.kept = false;
178
- ctx.saves.register('level', { notAtomic: 'its load fetches and builds a level: not plain data, and not something a failed op can wait for', first: true, save: () => st.current ?? (!api.root ? null : api.root === scene ? OPENING : sceneToken(st, api.root)), load: (d, turn) => {
182
+ ctx.saves.define('level', { notAtomic: 'its load fetches and builds a level: not plain data, and not something a failed op can wait for', first: true, save: () => st.current ?? (!api.root ? (st.unloaded ? NONE : null) : api.root === scene ? OPENING : sceneToken(st, api.root)), load: (d, turn) => {
179
183
  if (installing) { if (opens || typeof d !== 'string' || d === OPENING) return; st.kept = true; }
184
+ else if (d?.none) return api.root ? api.unload() : dropLoad(st); // saved with no level standing: that is what the save says, so the level now standing goes
180
185
  else if (d === OPENING) return api.root === scene ? dropLoad(st) : api.load(scene, { turn });
181
186
  else if (d?.scene != null) { const root = st.scenes[d.scene]?.deref(); return !root || root === api.root ? dropLoad(st) : api.load(root, { turn }); }
182
187
  else if (typeof d !== 'string' || d === st.current) return dropLoad(st);
@@ -134,7 +134,7 @@ export function finishLoad(st) {
134
134
  // playable comes later than committed: nav, nearby models and physics start building on level:loaded. This level leaving ends the wait, a load that may not come to anything does not
135
135
  const version = st.version;
136
136
  st.playable = false;
137
- whenSettled(e, () => version === st.version).then(ok => {
137
+ whenSettled(e, () => version === st.version, true).then(ok => {
138
138
  if (!ok) return;
139
139
  st.playable = true;
140
140
  e.events.emit('level:playable', { root: api.root });
@@ -189,7 +189,9 @@ export function addColliders(st) {
189
189
  st.wallsIn.sync(() => {
190
190
  const ph = st.e.collision, fresh = [];
191
191
  if (ph) try {
192
- for (const b of colliderBoxes(st.colliders, { colliderHeight: st.o.colliderHeight, colliderPad: st.o.colliderPad })) fresh.push(ph.addBox(b.at, b.opts));
192
+ for (const b of colliderBoxes(st.colliders, { colliderHeight: st.o.colliderHeight, colliderPad: st.o.colliderPad,
193
+ // `layer` read up the parent chain like occluder: it is often on the col_ / collider object, and a mesh with two materials is a Group of meshes in three
194
+ layerOf: m => chainValue(m, st.api.root, 'layer') })) fresh.push(ph.addBox(b.at, b.opts));
193
195
  } catch (err) { for (const h of fresh) h.remove?.(); throw err; }
194
196
  st.walls.length = 0; st.walls.push(...fresh);
195
197
  });
@@ -45,7 +45,7 @@ function apply(pool, src, o) {
45
45
  if (d !== null && !(typeof d === 'number' && d >= 0 && d <= 1)) throw codedError('lightpool-dusk', fmt(STRINGS.dusk, { d: String(DUSK) }) + JSON.stringify(o.dusk), TypeError);
46
46
  src.dusk = d;
47
47
  }
48
- if ('glow' in o) { if (src.glow) setGlow(pool, src, 1); src.glow = glowOf(o.glow); setGlow(pool, src, src.slot ? 1 - src.slot.w : 1); }
48
+ if ('glow' in o) { restoreGlow(src); src.glow = glowOf(o.glow); setGlow(pool, src, src.slot ? 1 - src.slot.w : 1); }
49
49
  pool.timer = Infinity; // a changed source is reconsidered on the next frame, not after `every`
50
50
  }
51
51
 
@@ -48,6 +48,8 @@ export class Music {
48
48
  this.tracks = new Map();
49
49
  this._defineAll(st.tracks || {});
50
50
  this._defineAll(opts.tracks || {});
51
+ /** @internal stingers sounding now (their handles), and whether the module is gone: a stinger whose file loads after that must not start */
52
+ this._stingers = new Set(); this._gone = false;
51
53
  /** Name of the track playing (or wanted) @type {string | null} */
52
54
  this.current = null;
53
55
  /** 0-1: how loud each stem of the playing track is (see the stems `at` range); fades in about half a second @type {number} */
@@ -151,7 +153,7 @@ export class Music {
151
153
  const t = ctx.currentTime + 0.02, loop = tr.loop !== false;
152
154
  bufs.forEach((buf, i) => { const src = ctx.createBufferSource(); src.buffer = buf; src.loop = loop; src.connect(parts[i].out); src.start(t); slot.srcs.push(src); });
153
155
  if (fade > 0) { g.gain.setValueAtTime(0, t); g.gain.linearRampToValueAtTime(vol, t + fade); }
154
- if (!loop && slot.srcs[0]) slot.srcs[0].onended = () => { if (this.playing === slot) { this.playing = null; this.current = null; this.engine.events.emit('music:change', { from: name, to: null }); } };
156
+ if (slot.srcs[0]) slot.srcs[0].onended = () => this._ended(slot); // a looping source ends only when a fade stops it
155
157
  }).catch(err => { warnOnce(err.message); if (this.playing === slot) this.playing = null; }); // a missing file is said once; the game goes on silent
156
158
  }
157
159
  /**
@@ -175,7 +177,21 @@ export class Music {
175
177
  p.gain.gain.setValueAtTime(p.gain.gain.value, t);
176
178
  p.gain.gain.linearRampToValueAtTime(0, t + f);
177
179
  for (const s of p.srcs) { try { s.stop(t + f + 0.05); } catch { /* already stopped */ } }
178
- if (p.srcs[0]) p.srcs[0].onended = () => p.gain.disconnect(); // free the nodes once the fade has really ended
180
+ if (p.srcs[0]) p.srcs[0].onended = () => this._ended(p); // free the nodes once the fade has really ended
181
+ }
182
+ /** @internal The one end of a track's nodes, natural or faded (a fade-out already took it off `playing`): free them, and if it is still the playing one, say the music ended */
183
+ _ended(slot) {
184
+ slot.gain.disconnect();
185
+ if (this.playing !== slot) return;
186
+ this.playing = null; const from = this.current; this.current = null;
187
+ this.engine.events.emit('music:change', { from, to: null });
188
+ }
189
+ /** @internal the module goes: stop the background, every stinger, and refuse the ones still loading */
190
+ _close() {
191
+ this._gone = true;
192
+ this.stop({ fade: 0 }); this._duck?.remove(0); this.output?.disconnect();
193
+ for (const h of [...this._stingers]) h.remove();
194
+ this._stingers.clear();
179
195
  }
180
196
  /** @internal the background bed: tracks connect here, then to the music bus; a stinger dips this node, never the bus (it plays on the bus itself) */
181
197
  _ensureOutput() {
@@ -203,6 +219,8 @@ export class Music {
203
219
  this.engine.events.emit('music:stinger', { name, played: !!live });
204
220
  if (!live) return; // a one-shot piece is not worth queueing
205
221
  a.play(tr.url, { bus: 'music', volume: volume ?? tr.volume ?? 1 }).then(h => {
222
+ if (this._gone) { h.remove(); return; } // the file loaded after the module went
223
+ this._stingers.add(h); h.source.addEventListener?.('ended', () => this._stingers.delete(h));
206
224
  const d = h.source.buffer?.duration || 1, g = this.output.gain, t = a.ctx.currentTime;
207
225
  if (duck >= 1) return;
208
226
  // scheduled on the audio clock (no timers): dip, hold for the stinger's length, come back
@@ -304,11 +322,11 @@ export function music(opts = {}) {
304
322
  install(e, ctx) { e.i18n.add({ 'zh-CN': { 'module.music': '音乐' }, en: { 'module.music': 'music' } });
305
323
  m = new Music(e, opts, ctx.track);
306
324
  ctx.track(e.events.on('session:end', () => m.stop({ fade: 0 }))); // a playthrough ends: its music stops at once
307
- ctx.saves.register('music', { notAtomic: 'sound, which an atomic op leaves alone: side effects go in after', save: () => ({ override: m._override ?? null, intensity: m.intensity }), load: d => m._load(d) });
325
+ ctx.saves.define('music', { notAtomic: 'sound, which an atomic op leaves alone: side effects go in after', save: () => ({ override: m._override ?? null, intensity: m.intensity }), load: d => m._load(d) });
308
326
  return m;
309
327
  },
310
328
  frame(dt) { m.frame(dt); },
311
- dispose() { m.stop({ fade: 0 }); m._duck?.remove(0); m.output?.disconnect(); }, // nothing would stop a looping track once the module is gone
329
+ dispose() { m._close(); }, // nothing would stop a looping track once the module is gone
312
330
  // the same state the tests read (music.state) plus why nothing may sound: audio still locked (ready false, the track waits in pending), rules on, ducked by dialogue
313
331
  describe() { return { ...m.state, ready: m.ready, ruled: m.ruled, ducked: !!m._duck, tracks: m.tracks.size }; },
314
332
  };
@@ -13,6 +13,9 @@
13
13
  // Body sizes: Recast bakes the body's radius into the mesh, so a mesh is good for one size (Recast's own advice, and what Unreal's supported agents do: one mesh per size).
14
14
  // api itself is the mesh of agentRadius; a findPath for another radius gets its own, built the first time that size is asked for and kept in api.meshes until the next rebuild or unload.
15
15
  // Radii that round to the same cells share one. Each has its own tile cache, obstacles and seated links; revision covers them all, and a game with one size pays for nothing else.
16
+ // Collider layers (collision.addBox { layer }) work the same way: a path for a body that passes some layers gets a mesh where colliders of those layers cut nothing,
17
+ // keyed by size and layer list. Why a mesh and not a Detour query filter: the tile cache cuts an obstacle out of the mesh for every query, and an obstacle that only
18
+ // marks polygons is not in this Recast build; Godot's advice for agents that need different geometry is the same, a map of their own. A game without layers builds none.
16
19
  // shortcut: built on the main thread when first asked for, which stalls that step; move to a worker (or a list of sizes built at load) if a real level's build shows up in a frame.
17
20
  // Links (Recast off-mesh connections): nav({ links: [{ id, from, to }] }) joins two places a walker cannot walk between, a gap to jump or a ladder to climb.
18
21
  // generateTileCache has no offMeshConnections option (generateTiledNavMesh does), so they go in through the tile cache's mesh process, which Detour runs for
@@ -24,6 +27,7 @@ import { navSearch, OPTS } from './navPath.js';
24
27
  import { sameFloor } from '../../core/scene/floor.js';
25
28
  import { warnOnce } from '../../core/base/validate.js';
26
29
  import { coded, codedError } from '../../core/base/errorHints.js';
30
+ import { passesOf, passesThrough } from '../collision/grid.js';
27
31
 
28
32
  const NAV_PARAMS = keysSchema(['cellSize', 'agentRadius', 'agentHeight', 'maxClimb', 'maxSlope', 'tileSize', 'crowd', 'debug', 'maxObstacles', 'maxAgents', 'arrive', 'links']);
29
33
  const LINK_PARAMS = keysSchema(['id', 'from', 'to', 'oneWay', 'radius']);
@@ -66,11 +70,12 @@ export function nav(opts = {}) {
66
70
  get revision() { syncObstacles(); return revision; },
67
71
  /** @internal a mesh as bytes, imported by the pathfinding worker */
68
72
  exportMesh(m = api) { return lib.exportNavMesh(m.navMesh); },
69
- /** @internal the mesh for a body of this radius, built the first time it is asked for; no radius: agentRadius. A mesh the build refused has no query, and every path on it is noPath */
70
- mesh(radius = agentRadius) {
73
+ /** @internal the mesh for a body of this radius that goes through colliders of these layers, built the first time it is asked for; no radius: agentRadius. A mesh the build refused has no query, and every path on it is noPath */
74
+ mesh(radius = agentRadius, passes) {
71
75
  if (!(radius >= 0)) throw codedError('character-option', `nav: a path's radius is a number of meters, 0 or more, got ${radius}`);
72
- const c = cellsOf(radius), size = c === api.cells && radius <= agentRadius ? BASE : c;
73
- return api.meshes.get(size) ?? extraMesh(size);
76
+ // a structured key: a layer name may hold a comma, and joined text would make the one layer "a,b" the same body as the two layers a and b
77
+ const c = cellsOf(radius), size = c === api.cells && radius <= agentRadius ? BASE : c, through = passesOf('nav: passes', passes), key = through ? JSON.stringify([size, ...through]) : size;
78
+ return api.meshes.get(key) ?? extraMesh(key, size, through);
74
79
  },
75
80
  /**
76
81
  * @internal The one rule for a position given to the navmesh (search, links, async paths, crowd goals). No height: the ground. A height picks the nearest surface of the mesh at that
@@ -104,7 +109,7 @@ export function nav(opts = {}) {
104
109
 
105
110
  function search(from, to, o) {
106
111
  if (!api.ready) return { status: 'notReady', path: null };
107
- const m = api.mesh(o.radius);
112
+ const m = api.mesh(o.radius, o.passes);
108
113
  return navSearch(m, api.point(from, m), api.point(to, m), api.reach(o.radius), e.movement.height);
109
114
  }
110
115
 
@@ -190,10 +195,13 @@ export function nav(opts = {}) {
190
195
  return true;
191
196
  }
192
197
 
193
- /** The mesh of a size no one asked for before. The whole cell counts as its radius: it stands for every body that rounds to it. It takes no part in revision: nothing walkable changed, and async pathfinding sends each size when a batch first needs it */
194
- function extraMesh(size) {
195
- const m = { size, cells: size, radius: size * cellSize, links: [], tileCache: null, navMesh: null, query: null, obstacles: null, obstaclesOf: follows(() => e.collision ?? null) };
196
- api.meshes.set(size, m);
198
+ /**
199
+ * The mesh of a size (and layer list) no one asked for before; key names it in api.meshes. The whole cell counts as its radius: it stands for every body that rounds to it, the agent's own size keeps the agent's.
200
+ * passes: colliders of these layers cut nothing in it. It takes no part in revision: nothing walkable changed, and async pathfinding sends each mesh when a batch first needs it
201
+ */
202
+ function extraMesh(key, size, passes) {
203
+ const cells = size === BASE ? api.cells : size, m = { size: key, cells, radius: size === BASE ? api.radius : cells * cellSize, passes, links: [], tileCache: null, navMesh: null, query: null, obstacles: null, obstaclesOf: follows(() => e.collision ?? null) };
204
+ api.meshes.set(key, m);
197
205
  if (cut(m, geometry())) syncMesh(m);
198
206
  return m;
199
207
  }
@@ -207,7 +215,8 @@ export function nav(opts = {}) {
207
215
  api.ready = true; api.version++; revision++;
208
216
  syncObstacles();
209
217
  if (debug) {
210
- const three = await import('@recast-navigation/three');
218
+ const built = api.navMesh, three = await import('@recast-navigation/three');
219
+ if (api.navMesh !== built) return; // unloaded or rebuilt while the import ran: that mesh is gone (dispose clears it), a helper of it would draw freed data
211
220
  api.helper = new three.NavMeshHelper(api.navMesh);
212
221
  api.helper.position.y = 0.05; e.add(api.helper, { owner: 'engine:nav' });
213
222
  }
@@ -216,6 +225,7 @@ export function nav(opts = {}) {
216
225
  // collision-module colliders -> TileCache obstacles (engine.collision.mirror diffs add / remove, shared with rigid), then rebuild affected tiles
217
226
  function obstacle(m, type, o) {
218
227
  const tc = m.tileCache, list = [];
228
+ if (passesThrough(o, m.passes)) return list; // a gate this mesh's bodies walk through: no piece, and remove() has nothing to drop
219
229
  const y = (o.y ?? e.surface(o.x, o.z)) - maxClimb, h = (o.h ?? 6) + maxClimb; // extend a bit downward: Recast ignores a bottom face lying exactly on the ground
220
230
  if (type === 'box') {
221
231
  // one obstacle affects at most 8 tiles: cut big boxes into pieces no larger than half a tile (along the box's own orientation)
@@ -32,6 +32,8 @@
32
32
  // maxPixels 512 largest on-screen size of one particle (pixels), so smoke drifting past the camera does not fill the screen
33
33
  // ratePerMeter 0 with attach, particles per meter the emitter moves, on top of rate, spread along the path it moved (no beads behind a fast emitter)
34
34
  // soft 0 meters over which a particle fades where it meets opaque geometry; 0 is off. Set at define, not per batch
35
+ // lit false the scene's lights tint the color: dust a lamp lights, smoke dark away from the fire (point, spot, directional, ambient,
36
+ // hemisphere; no shadows, environment map or probes; cost live particles x lights on the CPU, lit.js). Set at define, not per batch
35
37
  // size, color and opacity also take more stops: evenly spaced [0, 0.8, 0], or timed [[0, 0], [0.1, 0.8], [1, 0]] (time 0 birth, 1 death).
36
38
  // Each particle's life fraction (0 birth, 1 death) is the geometry attribute aLife, for a game's own material.
37
39
  //
@@ -44,12 +46,15 @@ import { vec3 } from '../../core/base/math.js';
44
46
  import { Effect, NEUTRAL, KEYS, OVER_LIFE, curve } from './effect.js';
45
47
  import { warnMissing } from '../../core/base/validate.js';
46
48
  import { readParams, keysSchema } from '../../core/base/params.js';
47
- import { isOptions } from '../../core/base/util.js';
49
+ import { isOptions, isUnder } from '../../core/base/util.js';
48
50
  import { codedError } from '../../core/base/errorHints.js';
51
+ import { borrowRenderer } from '../../render/backend.js';
52
+ import { ParticleLights } from './lit.js';
49
53
  // one schema per public entry (unknown keys throw in dev with did-you-mean). Effect param values come in many shapes (number or [min, max], color), so most are only checked by key name
50
54
  const FX_PARAMS = keysSchema(KEYS, {}, {
51
55
  ratePerMeter: { type: 'number', optional: true, min: 0, desc: 'particles per meter the emitter moves' },
52
56
  soft: { type: 'number', optional: true, min: 0, desc: 'meters over which a particle fades into opaque geometry' },
57
+ lit: { type: 'bool', optional: true, desc: "the scene's lights tint the color (lamp-lit dust); off: the color is drawn as given" },
53
58
  });
54
59
  /** Check one table of effect params: the schema, then the values over life (at the call, not on a later emit) */
55
60
  function readFx(where, o) {
@@ -125,7 +130,7 @@ export class Particles {
125
130
  }
126
131
 
127
132
  /**
128
- * Burst: emit count particles at once (default 10) at position (Vector3 / Object3D / [x, y, z] / {x, y, z}). overrides affect this batch only (color, speed, direction...; max/texture/blending/soft cannot be changed temporarily)
133
+ * Burst: emit count particles at once (default 10) at position (Vector3 / Object3D / [x, y, z] / {x, y, z}). overrides affect this batch only (color, speed, direction...; max/texture/blending/soft/lit cannot be changed temporarily)
129
134
  * @param {string} name
130
135
  * @param {PositionLike} position
131
136
  * @param {{ count?: number, overrides?: ParticleOptions | null }} [opts]
@@ -201,22 +206,29 @@ export class Particles {
201
206
  const d = this._depth ??= { target: new THREE.WebGLRenderTarget(1, 1, { depthTexture: new THREE.DepthTexture(1, 1) }), frame: -1, camera: null,
202
207
  material: new THREE.MeshDepthMaterial({ colorWrite: false, side: THREE.DoubleSide }) };
203
208
  if (d.frame === r.info.render.frame && d.camera === camera) return d.target.depthTexture;
204
- const size = r.getDrawingBufferSize(_vs), target = r.getRenderTarget(), { autoClear } = r, { autoUpdate } = r.shadowMap, { overrideMaterial, background } = scene, off = [];
209
+ const size = r.getDrawingBufferSize(_vs), off = [];
205
210
  d.target.setSize(size.x, size.y);
206
211
  // by layer, not visible: an opaque child of a transparent parent still counts
207
212
  scene.traverseVisible(o => { if (o.material && (o.isPoints || [o.material].flat().some(m => !m.depthWrite || m.transmission > 0))) { off.push(o, o.layers.mask); o.layers.disableAll(); } });
208
- scene.overrideMaterial = d.material; scene.background = null; r.autoClear = true; r.shadowMap.autoUpdate = false;
209
- r.state.buffers.depth.setMask(true); // the transparent pass left it off, and the clear needs it
210
- try { r.setRenderTarget(d.target); r.render(scene, camera); }
211
- finally { // a throwing render must not leave the scene on the depth material with layers off (M11)
212
- r.setRenderTarget(target);
213
- scene.overrideMaterial = overrideMaterial; scene.background = background; r.autoClear = autoClear; r.shadowMap.autoUpdate = autoUpdate;
214
- for (let i = 0; i < off.length; i += 2) off[i].layers.mask = off[i + 1];
215
- }
213
+ // a throwing render must not leave the scene on the depth material with layers off (M11): the renderer and scene come back through the
214
+ // engine's one borrow (render/backend.js), the layers of the objects switched off here are this pass's own to give back
215
+ try {
216
+ borrowRenderer(r, () => {
217
+ scene.overrideMaterial = d.material; scene.background = null; r.autoClear = true; r.shadowMap.autoUpdate = false;
218
+ r.state.buffers.depth.setMask(true); // the transparent pass left it off, and the clear needs it
219
+ r.setRenderTarget(d.target); r.render(scene, camera);
220
+ }, { scene });
221
+ } finally { for (let i = 0; i < off.length; i += 2) off[i].layers.mask = off[i + 1]; }
216
222
  d.frame = r.info.render.frame; d.camera = camera;
217
223
  return d.target.depthTexture;
218
224
  }
219
225
 
226
+ /** Recolor live lit particles from the lights as they are now, touching nothing else (the picture check, after it changes a light) */
227
+ _relight() {
228
+ const lights = (this._lights ??= new ParticleLights(this.engine)); let walked = false;
229
+ for (const fx of this.effects.values()) if (fx.o.lit && fx.alive) { if (!walked) { lights.refresh(true); walked = true; } fx.relight(lights); }
230
+ }
231
+
220
232
  /**
221
233
  * Update all effects every frame (called by the module each frame)
222
234
  * @param {number} dt
@@ -224,11 +236,11 @@ export class Particles {
224
236
  * @internal
225
237
  */
226
238
  update(dt) {
227
- if (this.engine.still) dt = 0; // freeze(owner, { ambient: true }): sparks hold in the air
239
+ if (this.engine.still) dt = 0; // freeze(owner, { still: true }): sparks hold in the air
228
240
  const cam = this.engine.camera, pr = this.engine.renderer.getPixelRatio(), scale = this.engine.renderer.getSize(_vs).y * pr / (cam.isOrthographicCamera ? 2 / cam.projectionMatrix.elements[5] : 2 * Math.tan(THREE.MathUtils.degToRad(cam.fov) / 2)); // orthographic: pixels per world unit
229
241
  for (const h of this.emitters) {
230
242
  if (!h.active) { h.last = null; continue; } // a pause leaves no line from where it stopped to where it starts again
231
- if (!h.object.parent) { h.remove(); continue; } // object removed from the scene: stop automatically
243
+ if (!isUnder(h.object, this.engine.scene) && !isUnder(h.object, cam)) { h.remove(); continue; } // object left the scene (it or any group above it was removed; one carried by the camera counts): stop automatically
232
244
  const path = h.ratePerMeter > 0 ? this._walked(h, dt) : null;
233
245
  h.acc += dt * h.rate;
234
246
  const n = Math.floor(h.acc);
@@ -241,7 +253,12 @@ export class Particles {
241
253
  h.object.getWorldQuaternion(this._q);
242
254
  h.fx.spawn(p, n, o, o.worldSpace === false ? this._q : null, path);
243
255
  }
244
- for (const fx of this.effects.values()) { fx.uniforms.uScale.value = scale; fx.update(dt); }
256
+ // lit effects share one read of the scene's lights per frame, made only while one of them has live particles
257
+ let lights = null;
258
+ for (const fx of this.effects.values()) {
259
+ if (fx.o.lit && fx.alive && !lights) (lights = this._lights ??= new ParticleLights(this.engine)).refresh();
260
+ fx.uniforms.uScale.value = scale; fx.update(dt, fx.o.lit ? lights : null);
261
+ }
245
262
  }
246
263
  }
247
264
 
@@ -8,13 +8,13 @@ import { isWebGPU, webgpuPart, onRendererSwap } from '../../render/backend.js';
8
8
  export const NEUTRAL = {
9
9
  max: 120, lifetime: [1, 2], rate: 10, speed: [0.5, 1.5], direction: [0, 1, 0], spread: 0.5, area: 0,
10
10
  gravity: -2, drag: 0.5, wind: 0, windDir: [1, 0, 0.3], size: [0.3, 0.3], color: [0xcccccc, 0xcccccc], opacity: [0.8, 0],
11
- texture: null, blending: 'normal', spin: 0, worldSpace: true, fog: true, maxPixels: 512, ratePerMeter: 0, soft: 0,
11
+ texture: null, blending: 'normal', spin: 0, worldSpace: true, fog: true, maxPixels: 512, ratePerMeter: 0, soft: 0, lit: false,
12
12
  };
13
13
  export const KEYS = Object.keys(NEUTRAL);
14
14
  const pair = v => Array.isArray(v) ? v : [v, v];
15
15
  /** Numbers per stop of the values that change over life */
16
16
  export const OVER_LIFE = { size: 1, opacity: 1, color: 3 };
17
- const _col = new THREE.Color();
17
+ const _col = new THREE.Color(), _lit = [1, 1, 1];
18
18
  /**
19
19
  * A value over life as { t, v, w }: stop times (0 birth, 1 death) and w numbers per stop. Given as one value, [birth, death], evenly spaced
20
20
  * [a, b, c...] or timed [[0, a], [0.2, b], [1, c]] (before the first time and after the last the end stop holds). Throws on anything else.
@@ -175,9 +175,24 @@ export class Effect {
175
175
  this.points.visible = true;
176
176
  }
177
177
 
178
- update(dt) {
178
+ /** Color of particle i at life fraction k into aColor, times the scene's light for a lit effect (lit: true, lit.js) */
179
+ _paint(i, k, lights) {
180
+ const i3 = i * 3, ac = this.aColor.array, c = this.overLife.color[i], P = this.pos;
181
+ ac[i3] = sample(c, k); ac[i3 + 1] = sample(c, k, 1); ac[i3 + 2] = sample(c, k, 2);
182
+ if (lights) { lights.at(P[i3], P[i3 + 1], P[i3 + 2], _lit); ac[i3] *= _lit[0]; ac[i3 + 1] *= _lit[1]; ac[i3 + 2] *= _lit[2]; }
183
+ }
184
+
185
+ /** Rewrite only the colors of the live particles from the lights as they are now: no motion, age, visibility or spawning change (the picture check, which changes lights between captures) */
186
+ relight(lights) {
187
+ if (!this.alive) return;
188
+ for (let i = 0; i < this.max; i++) if (this.life[i] !== 0 && this.age[i] < this.life[i]) this._paint(i, this.age[i] / this.life[i], lights);
189
+ const a = this.aColor; a.clearUpdateRanges(); a.addUpdateRange(0, this.max * 3); a.needsUpdate = true;
190
+ }
191
+
192
+ /** @param {number} dt @param {import('./lit.js').ParticleLights | null} [lights] the scene's lights this frame, for a lit effect */
193
+ update(dt, lights = null) {
179
194
  if (!this.alive) { this.points.visible = false; return; }
180
- const N = this.max, P = this.pos, V = this.vel, ap = this.aPos.array, as = this.aSize.array, aa = this.aAlpha.array, ac = this.aColor.array, ag = this.aAngle.array, al = this.aLife.array, { size, opacity, color } = this.overLife;
195
+ const N = this.max, P = this.pos, V = this.vel, ap = this.aPos.array, as = this.aSize.array, aa = this.aAlpha.array, ag = this.aAngle.array, al = this.aLife.array, { size, opacity } = this.overLife;
181
196
  const w = this.o.windDir, wl = Math.hypot(w[0], w[2]) || 1, wind = this.sys.engine.uniforms.uWind.value, wx = w[0] / wl * wind, wz = w[2] / wl * wind;
182
197
  let alive = 0, hi = -1;
183
198
  for (let i = 0; i < N; i++) {
@@ -191,7 +206,7 @@ export class Effect {
191
206
  V[i3] = V[i3] * dr + wx * wd * dt; V[i3 + 1] = V[i3 + 1] * dr + g * dt; V[i3 + 2] = V[i3 + 2] * dr + wz * wd * dt;
192
207
  ap[i3] = P[i3] += V[i3] * dt; ap[i3 + 1] = P[i3 + 1] += V[i3 + 1] * dt; ap[i3 + 2] = P[i3 + 2] += V[i3 + 2] * dt;
193
208
  al[i] = k; as[i] = sample(size[i], k); aa[i] = sample(opacity[i], k);
194
- ac[i3] = sample(color[i], k); ac[i3 + 1] = sample(color[i], k, 1); ac[i3 + 2] = sample(color[i], k, 2);
209
+ this._paint(i, k, lights);
195
210
  if (this.spinV[i]) ag[i] += this.spinV[i] * dt;
196
211
  }
197
212
  this.alive = alive;
@@ -0,0 +1,72 @@
1
+ // Lit particles (helper of Particles.js, the `lit: true` effect param): the scene's lights tint each particle's color on the CPU, in the same loop
2
+ // that already samples its color over life.
3
+ // Why on the CPU and not in the shader: the particle color is already written per particle per frame into aColor, so one multiply there lights
4
+ // every route the same (WebGLRenderer points, WebGPURenderer sprite quads, and a game's own material that reads aColor), with no second shader
5
+ // path per renderer to keep in step. Cost: live lit particles x lights, a few multiplies each (300 dust x 4 lights ~ 1200 per frame).
6
+ // What it is, so a game knows what it gets: what a matte card facing every light would show (three's Lambert formula, color * light / pi, no
7
+ // facing term: soft dust and smoke scatter from all sides). No shadows (dust behind a wall still sees the lamp), no environment map or light
8
+ // probes, no area lights. A game wanting more swaps the material (recipes/64 "The material").
9
+ import * as THREE from 'three';
10
+
11
+ const _p = new THREE.Vector3(), _t = new THREE.Vector3(), _c = new THREE.Color();
12
+ const INV_PI = 1 / Math.PI;
13
+ /** Frames between scene walks for lights: lights come and go rarely, their positions are read every frame from the list. Frames, not game
14
+ * seconds: under engine.still the particles' dt is 0, and a light removed or added during the freeze must still be seen */
15
+ const GATHER = 15;
16
+
17
+ export class ParticleLights {
18
+ /** @param {any} engine anything with a scene */
19
+ constructor(engine) {
20
+ this.engine = engine;
21
+ /** @type {THREE.Light[]} visible lights found by the last walk */ this.found = [];
22
+ this.since = GATHER;
23
+ /** packed per light this frame: [kind, x, y, z, r, g, b, distance, decay, dx, dy, dz, coneCos, penumbraCos]; kind 0 = everywhere (ambient, hemisphere, directional) */
24
+ this.packed = new Float32Array(0); this.n = 0;
25
+ /** the constant part (ambient, hemisphere, directional), summed once */ this.base = [0, 0, 0];
26
+ }
27
+
28
+ /** Once per frame, before lit effects update. force: walk the scene now (the picture check, which changes lights between captures) */
29
+ refresh(force = false) {
30
+ if (force || ++this.since > GATHER) {
31
+ if (!force) this.since = 0; // a forced walk (picture check) keeps the normal schedule
32
+ const f = this.found = [];
33
+ this.engine.scene.traverseVisible(o => { if (o.isLight && !o.isLightProbe && !o.isLightProbeGrid && !o.isRectAreaLight) f.push(o); });
34
+ }
35
+ const b = this.base; b[0] = b[1] = b[2] = 0;
36
+ if (this.packed.length < this.found.length * 14) this.packed = new Float32Array(this.found.length * 14);
37
+ const P = this.packed; let n = 0;
38
+ for (const l of this.found) {
39
+ if (!(l.intensity > 0) || !l.visible) continue;
40
+ if (l.isHemisphereLight) { _c.copy(l.color).add(l.groundColor).multiplyScalar(0.5 * l.intensity * INV_PI); b[0] += _c.r; b[1] += _c.g; b[2] += _c.b; continue; } // no normal: the mean of sky and ground
41
+ _c.copy(l.color).multiplyScalar(l.intensity * INV_PI);
42
+ if (!l.isPointLight && !l.isSpotLight) { b[0] += _c.r; b[1] += _c.g; b[2] += _c.b; continue; } // ambient and directional reach every particle alike
43
+ l.updateWorldMatrix(true, false); _p.setFromMatrixPosition(l.matrixWorld);
44
+ const k = n * 14; P[k] = l.isSpotLight ? 2 : 1; P[k + 1] = _p.x; P[k + 2] = _p.y; P[k + 3] = _p.z; P[k + 4] = _c.r; P[k + 5] = _c.g; P[k + 6] = _c.b;
45
+ P[k + 7] = l.distance; P[k + 8] = l.decay;
46
+ if (l.isSpotLight) {
47
+ l.target.updateWorldMatrix(true, false); _t.setFromMatrixPosition(l.target.matrixWorld).sub(_p).normalize(); // light -> target
48
+ P[k + 9] = _t.x; P[k + 10] = _t.y; P[k + 11] = _t.z; P[k + 12] = Math.cos(l.angle); P[k + 13] = Math.cos(l.angle * (1 - l.penumbra));
49
+ }
50
+ n++;
51
+ }
52
+ this.n = n;
53
+ }
54
+
55
+ /** The light at (x, y, z) into out[0..2], per channel (multiply the particle color by it) */
56
+ at(x, y, z, out) {
57
+ const P = this.packed, b = this.base; let r = b[0], g = b[1], bl = b[2];
58
+ for (let i = 0; i < this.n; i++) {
59
+ const k = i * 14, dx = x - P[k + 1], dy = y - P[k + 2], dz = z - P[k + 3], d = Math.sqrt(dx * dx + dy * dy + dz * dz) || 1e-4;
60
+ // three's getDistanceAttenuation: 1 / max(d^decay, 0.01), with the smooth cutoff when distance > 0
61
+ let f = 1 / Math.max(Math.pow(d, P[k + 8]), 0.01);
62
+ const cut = P[k + 7]; if (cut > 0) { const q = d / cut, s = Math.min(1, Math.max(0, 1 - q * q * q * q)); f *= s * s; }
63
+ if (P[k] === 2) { // spot: smoothstep(coneCos, penumbraCos, cos of the angle off its axis), as three does
64
+ const cos = (dx * P[k + 9] + dy * P[k + 10] + dz * P[k + 11]) / d, lo = P[k + 12], hi = P[k + 13];
65
+ const t = Math.min(1, Math.max(0, (cos - lo) / ((hi - lo) || 1e-4))); f *= t * t * (3 - 2 * t);
66
+ }
67
+ if (f <= 0) continue;
68
+ r += P[k + 4] * f; g += P[k + 5] * f; bl += P[k + 6] * f;
69
+ }
70
+ out[0] = r; out[1] = g; out[2] = bl;
71
+ }
72
+ }