threedog 0.8.0 → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (372) hide show
  1. package/CHANGELOG.md +219 -4
  2. package/README.md +6 -6
  3. package/core/assets/Animator.js +2 -0
  4. package/core/assets/Assets.js +44 -13
  5. package/core/assets/assetEntry.js +87 -22
  6. package/core/assets/assetHot.js +2 -1
  7. package/core/assets/assetReport.js +1 -2
  8. package/core/audio/Audio.js +24 -5
  9. package/core/base/I18n.js +6 -3
  10. package/core/base/Random.js +3 -1
  11. package/core/base/Vars.js +14 -4
  12. package/core/base/errorCodes.js +54 -16
  13. package/core/base/errorHints.js +12 -1
  14. package/core/base/errors.js +6 -4
  15. package/core/base/events.generated.js +10 -0
  16. package/core/base/follows.js +26 -0
  17. package/core/base/math.js +15 -8
  18. package/core/base/params.js +2 -2
  19. package/core/{saves → base}/saveValues.js +24 -6
  20. package/core/base/sections.js +97 -0
  21. package/core/base/spelling.js +32 -0
  22. package/core/base/validate.js +8 -29
  23. package/core/engine/Engine.js +61 -18
  24. package/core/engine/Loading.js +30 -3
  25. package/core/engine/copies.js +1 -1
  26. package/core/engine/headlessLoad.js +30 -13
  27. package/core/engine/lifecycle.js +30 -25
  28. package/core/engine/loop.js +22 -4
  29. package/core/engine/moduleSlots.js +91 -15
  30. package/core/engine/moduleTypes.js +13 -0
  31. package/core/engine/modules.js +248 -62
  32. package/core/engine/page.js +25 -8
  33. package/core/engine/plugins.js +15 -3
  34. package/core/engine/services.js +3 -0
  35. package/core/engine/startup.js +46 -36
  36. package/core/input/Input.js +39 -19
  37. package/core/input/inputKeyboard.js +39 -0
  38. package/core/input/inputPad.js +23 -2
  39. package/core/input/inputPointer.js +3 -1
  40. package/core/input/inputSeat.js +66 -0
  41. package/core/input/inputTouch.js +23 -6
  42. package/core/inspect/DebugOverrides.js +13 -2
  43. package/core/inspect/Describe.js +10 -6
  44. package/core/inspect/Inspect.js +31 -4
  45. package/core/inspect/UrlState.js +14 -10
  46. package/core/inspect/catalog.js +12 -5
  47. package/core/inspect/describeRender.js +3 -2
  48. package/core/inspect/describeText.js +6 -2
  49. package/core/inspect/metadata.generated.js +4140 -0
  50. package/core/inspect/pictureWriters.js +117 -33
  51. package/core/inspect/toolDoor.js +21 -0
  52. package/core/inspect/valueHistory.js +35 -0
  53. package/core/ops/Ops.js +32 -7
  54. package/core/ops/control.js +48 -23
  55. package/core/ops/holds.js +4 -3
  56. package/core/ops/opsAtomic.js +18 -6
  57. package/core/ops/opsCheck.js +7 -5
  58. package/core/ops/opsFail.js +5 -7
  59. package/core/ops/opsRun.js +2 -2
  60. package/core/ops/owned.js +20 -3
  61. package/core/ops/sharedPoint.js +7 -10
  62. package/core/ops/stacks.js +22 -1
  63. package/core/saves/SaveStore.js +52 -26
  64. package/core/saves/Saves.js +122 -27
  65. package/core/saves/saveApply.js +159 -61
  66. package/core/saves/saveFiles.js +30 -25
  67. package/core/saves/saveVersions.js +20 -6
  68. package/core/saves/session.js +76 -33
  69. package/core/saves/stateReplace.js +184 -0
  70. package/core/scene/Rays.js +21 -5
  71. package/core/scene/Views.js +6 -6
  72. package/core/scene/adaptive.js +13 -10
  73. package/core/scene/canvasBox.js +2 -0
  74. package/core/scene/compositeGround.js +72 -0
  75. package/core/scene/floor.js +17 -0
  76. package/core/scene/grid.js +2 -0
  77. package/core/scene/ground.contract.js +14 -0
  78. package/core/scene/ground.js +52 -17
  79. package/core/scene/pixel.js +154 -0
  80. package/core/scene/pixelRatio.js +167 -0
  81. package/core/scene/sceneDelta.js +3 -3
  82. package/core/scene/sceneMethods.js +11 -6
  83. package/core/scene/stepPoses.js +6 -1
  84. package/core/scene/thingExplain.js +1 -1
  85. package/core/scene/thingOps.js +22 -14
  86. package/core/scene/things.js +1 -1
  87. package/core/scene/tier.js +10 -0
  88. package/core/scene/view.js +126 -9
  89. package/core/stream/Batching.js +0 -1
  90. package/core/stream/Stream.js +24 -12
  91. package/core/stream/batchGroups.js +1 -0
  92. package/core/stream/scatter.js +5 -2
  93. package/core/stream/streamSources.js +2 -1
  94. package/core/threads/Commits.js +12 -7
  95. package/core/threads/Jobs.js +15 -5
  96. package/core/threads/Threads.js +5 -2
  97. package/core/time/Clock.js +3 -1
  98. package/core/time/skip.js +10 -4
  99. package/core/time/time.js +16 -10
  100. package/docs/AI.md +89 -72
  101. package/docs/API.md +18 -14
  102. package/docs/CODEMAP.md +68 -40
  103. package/docs/COMMANDS.md +22 -23
  104. package/docs/CONVENTIONS.md +120 -17
  105. package/docs/MIGRATING-0.8.md +2 -0
  106. package/docs/MIGRATING-1.0.md +101 -0
  107. package/docs/THREE.md +65 -12
  108. package/docs/api/cameraRig.md +3 -0
  109. package/docs/api/characters.md +13 -7
  110. package/docs/api/collider3d.md +9 -0
  111. package/docs/api/content.md +16 -15
  112. package/docs/api/dialogue.md +2 -1
  113. package/docs/api/engine.md +18 -16
  114. package/docs/api/events.md +14 -4
  115. package/docs/api/ground.md +2 -2
  116. package/docs/api/i18n.md +1 -1
  117. package/docs/api/input.md +2 -1
  118. package/docs/api/interactions.md +1 -1
  119. package/docs/api/inventory.md +1 -1
  120. package/docs/api/level.md +3 -2
  121. package/docs/api/nav.md +4 -2
  122. package/docs/api/particles.md +8 -5
  123. package/docs/api/pickups.md +1 -1
  124. package/docs/api/post.md +3 -4
  125. package/docs/api/quests.md +4 -2
  126. package/docs/api/rays.md +2 -0
  127. package/docs/api/rigid.md +3 -2
  128. package/docs/api/saves.md +8 -7
  129. package/docs/api/stream.md +4 -5
  130. package/docs/api/terrain.md +3 -4
  131. package/docs/api/terrainDraw.md +1 -1
  132. package/docs/api/timeline.md +2 -2
  133. package/docs/api/tools.md +3 -1
  134. package/docs/api/triggers.md +2 -0
  135. package/docs/api/vegetationDraw.md +1 -1
  136. package/docs/api/water.md +6 -2
  137. package/docs/api/weather.md +19 -4
  138. package/docs/api/weatherDraw.md +1 -1
  139. package/docs/api/world.md +1 -1
  140. package/docs/recipes/01-new-game.md +3 -3
  141. package/docs/recipes/02-npc.md +3 -4
  142. package/docs/recipes/03-items-pickups.md +11 -11
  143. package/docs/recipes/04-quests.md +2 -0
  144. package/docs/recipes/05-props-bake.md +9 -9
  145. package/docs/recipes/06-clock-events.md +6 -6
  146. package/docs/recipes/07-flow-scenes-pause.md +18 -15
  147. package/docs/recipes/08-weather-sky.md +5 -5
  148. package/docs/recipes/09-materials-lights-models.md +3 -3
  149. package/docs/recipes/10-blender-level.md +16 -4
  150. package/docs/recipes/11-vehicles.md +18 -6
  151. package/docs/recipes/12-navmesh.md +52 -8
  152. package/docs/recipes/13-animation.md +34 -8
  153. package/docs/recipes/14-custom-module.md +20 -8
  154. package/docs/recipes/15-perf.md +4 -4
  155. package/docs/recipes/16-dev-bridge.md +9 -8
  156. package/docs/recipes/18-world.md +13 -5
  157. package/docs/recipes/19-shooting-picking.md +3 -2
  158. package/docs/recipes/20-content-actions-save.md +26 -6
  159. package/docs/recipes/21-camera.md +17 -23
  160. package/docs/recipes/22-shop-gold.md +21 -12
  161. package/docs/recipes/23-ops.md +19 -15
  162. package/docs/recipes/26-ui-parts.md +3 -2
  163. package/docs/recipes/27-net.md +3 -3
  164. package/docs/recipes/28-terrain.md +3 -3
  165. package/docs/recipes/29-grid.md +1 -1
  166. package/docs/recipes/30-templates.md +10 -13
  167. package/docs/recipes/31-audio.md +2 -2
  168. package/docs/recipes/32-action-game.md +6 -5
  169. package/docs/recipes/33-stream-sources.md +4 -1
  170. package/docs/recipes/34-environment-lighting.md +7 -8
  171. package/docs/recipes/35-picture-from-reference.md +13 -9
  172. package/docs/recipes/36-ground-plants.md +3 -2
  173. package/docs/recipes/40-scene.md +11 -10
  174. package/docs/recipes/43-shader-patches-surfaces.md +7 -7
  175. package/docs/recipes/44-water-weather-hooks.md +9 -8
  176. package/docs/recipes/45-cascaded-shadows.md +3 -4
  177. package/docs/recipes/46-blender-art-route.md +3 -3
  178. package/docs/recipes/49-game-module-contract.md +2 -1
  179. package/docs/recipes/50-own-renderer.md +1 -0
  180. package/docs/recipes/51-capability-catalog.md +14 -8
  181. package/docs/recipes/52-around-the-picture.md +4 -4
  182. package/docs/recipes/55-mods-time-wrap.md +5 -4
  183. package/docs/recipes/56-webgpu-tsl.md +12 -1
  184. package/docs/recipes/57-control.md +30 -10
  185. package/docs/recipes/58-input.md +13 -0
  186. package/docs/recipes/60-judge-the-picture.md +1 -1
  187. package/docs/recipes/62-picture-code.md +106 -48
  188. package/docs/recipes/63-third-person-start.md +2 -1
  189. package/docs/recipes/64-particles.md +53 -4
  190. package/docs/recipes/65-swarm.md +2 -2
  191. package/docs/recipes/66-common-tasks.md +313 -0
  192. package/examples/action/.threedog/content-index.json +1 -1
  193. package/examples/action/GAMEMAP.md +3 -3
  194. package/examples/perf-island/.threedog/content-index.json +1 -1
  195. package/examples/perf-island/GAMEMAP.md +3 -3
  196. package/examples/perf-island/main.js +2 -2
  197. package/examples/plain-picture/GAMEMAP.md +3 -1
  198. package/examples/rc2d/GAMEMAP.md +1 -1
  199. package/examples/rc2d/rc2d.js +1 -1
  200. package/examples/styletest/.threedog/content-index.json +1 -1
  201. package/examples/styletest/GAMEMAP.md +3 -3
  202. package/examples/webgpu-tsl/GAMEMAP.md +1 -1
  203. package/examples/world/.threedog/content-index.json +1 -1
  204. package/examples/world/GAMEMAP.md +5 -4
  205. package/examples/world/main.js +3 -3
  206. package/index.d.ts +8 -5
  207. package/index.js +22 -1
  208. package/llms.txt +2 -1
  209. package/modules/ambience/Ambience.js +5 -3
  210. package/modules/calendar/index.js +7 -5
  211. package/modules/camera/FirstPersonCamera.js +3 -3
  212. package/modules/camera/FixedCamera.js +34 -20
  213. package/modules/camera/FollowCamera.js +20 -11
  214. package/modules/camera/RtsCamera.js +1 -0
  215. package/modules/camera/common.js +33 -22
  216. package/modules/camera/pixelSnap.js +62 -0
  217. package/modules/characters/Character.js +136 -43
  218. package/modules/characters/NPC.js +60 -28
  219. package/modules/characters/assetModel.js +2 -2
  220. package/modules/characters/astar.js +47 -28
  221. package/modules/characters/character.contract.js +21 -0
  222. package/modules/characters/contract.js +17 -3
  223. package/modules/characters/index.js +94 -34
  224. package/modules/characters/moveHelpers.js +80 -15
  225. package/modules/characters/mover.contract.js +14 -0
  226. package/modules/characters/movers/common.js +6 -4
  227. package/modules/characters/movers/rapier.js +12 -5
  228. package/modules/characters/movers/simple.js +25 -12
  229. package/modules/characters/movers/support.js +18 -7
  230. package/modules/characters/npcAvoid.js +15 -12
  231. package/modules/characters/npcSim.js +75 -25
  232. package/modules/characters/npcView.js +13 -6
  233. package/modules/characters/pathAsync.js +74 -24
  234. package/modules/characters/pathJob.js +38 -21
  235. package/modules/characters/player.js +59 -47
  236. package/modules/characters/seat.js +56 -0
  237. package/modules/characters/vehicle.contract.js +8 -5
  238. package/modules/characters/walkTo.js +31 -18
  239. package/modules/collision/Collision.js +44 -26
  240. package/modules/collision/contract.js +2 -2
  241. package/modules/collision/grid.js +6 -1
  242. package/modules/content/explain.js +1 -1
  243. package/modules/content/fields.js +3 -3
  244. package/modules/content/ids.js +3 -1
  245. package/modules/content/index.js +83 -27
  246. package/modules/content/loader.js +110 -130
  247. package/modules/content/markers.js +1 -1
  248. package/modules/content/models.js +48 -14
  249. package/modules/content/packs.js +2 -1
  250. package/modules/content/places.js +5 -4
  251. package/modules/content/props.js +8 -6
  252. package/modules/content/rules.js +29 -47
  253. package/modules/content/templates.js +66 -35
  254. package/modules/content/words.js +19 -6
  255. package/modules/debug/DebugPanel.js +4 -2
  256. package/modules/flow/contract.js +1 -0
  257. package/modules/flow/index.js +24 -14
  258. package/modules/gameplay/Container.js +5 -2
  259. package/modules/gameplay/Containers.js +9 -1
  260. package/modules/gameplay/Dialogue.js +82 -25
  261. package/modules/gameplay/Interactions.js +61 -32
  262. package/modules/gameplay/Inventory.js +56 -13
  263. package/modules/gameplay/Quests.js +133 -24
  264. package/modules/gameplay/boxOps.js +7 -0
  265. package/modules/gameplay/dialogueBubbles.js +14 -9
  266. package/modules/gameplay/inventoryOps.js +11 -7
  267. package/modules/gameplay/pickups.js +43 -16
  268. package/modules/gameplay/questLog.js +4 -2
  269. package/modules/gameplay/questSave.js +6 -1
  270. package/modules/gameplay/quests.contract.js +1 -1
  271. package/modules/grid/Grid.js +1 -1
  272. package/modules/grid/Layer.js +8 -4
  273. package/modules/grid/index.js +21 -15
  274. package/modules/grid/ops.js +43 -46
  275. package/modules/grid/tiles.js +1 -1
  276. package/modules/hlod/index.js +6 -3
  277. package/modules/hud/index.js +6 -4
  278. package/modules/hud/parts.js +4 -4
  279. package/modules/level/contract.js +2 -2
  280. package/modules/level/heightfield.js +17 -21
  281. package/modules/level/index.js +83 -26
  282. package/modules/level/load.js +165 -48
  283. package/modules/level/nodes.js +34 -16
  284. package/modules/lights/index.js +6 -3
  285. package/modules/lights/sources.js +3 -1
  286. package/modules/music/Music.js +4 -2
  287. package/modules/nav/contract.js +7 -5
  288. package/modules/nav/index.js +174 -44
  289. package/modules/nav/navPath.js +45 -10
  290. package/modules/net/index.js +1 -1
  291. package/modules/particles/Particles.js +85 -22
  292. package/modules/particles/effect.js +80 -28
  293. package/modules/particles/shaders.js +17 -0
  294. package/modules/photo/Photo.js +12 -10
  295. package/modules/rigid/RigidBodies.js +200 -57
  296. package/modules/rigid/Vehicles.js +15 -5
  297. package/modules/rigid/collider3d.contract.js +26 -0
  298. package/modules/rigid/ragdoll.js +55 -44
  299. package/modules/rigid/ragdollBones.js +83 -33
  300. package/modules/rigid/refresh.js +10 -0
  301. package/modules/rigid/sync.js +46 -15
  302. package/modules/settings/Settings.js +84 -37
  303. package/modules/settings/apply.js +15 -8
  304. package/modules/settings/sections.js +7 -4
  305. package/modules/settings/strings.js +2 -2
  306. package/modules/sky/skyModule.js +3 -1
  307. package/modules/swarm/Swarm.js +16 -6
  308. package/modules/terrain/ChunkManager.js +10 -16
  309. package/modules/terrain/index.js +17 -11
  310. package/modules/terrain/terrainEdit.js +13 -2
  311. package/modules/terrain/terrainGen.js +5 -3
  312. package/modules/terrain/terrainShape.js +1 -1
  313. package/modules/timeline/Timeline.js +58 -26
  314. package/modules/timeline/Tween.js +19 -13
  315. package/modules/timeline/shots.js +19 -10
  316. package/modules/triggers/index.js +87 -20
  317. package/modules/vegetation/Vegetation.js +4 -3
  318. package/modules/vegetation/draw.js +16 -0
  319. package/modules/vegetation/groundChunks.js +10 -7
  320. package/modules/vegetation/index.js +30 -7
  321. package/modules/water/Water.js +6 -2
  322. package/modules/weather/Weather.js +16 -15
  323. package/modules/weather/weatherDraw.js +7 -6
  324. package/modules/world/World.js +20 -7
  325. package/modules/world/explain.js +1 -1
  326. package/modules/world/index.js +13 -6
  327. package/modules/world/persist.js +23 -8
  328. package/modules/world/pos.js +4 -4
  329. package/modules/world/records.js +13 -7
  330. package/modules/world/sim.js +74 -23
  331. package/modules/world/simFar.js +2 -2
  332. package/modules/world/state.js +31 -6
  333. package/modules/world/thingSource.js +16 -3
  334. package/modules/world/views.js +19 -8
  335. package/package.json +7 -1
  336. package/render/PostFX.js +47 -29
  337. package/render/backend.js +5 -1
  338. package/render/fx/particles.tsl.js +8 -6
  339. package/render/fx/postWebGPU.tsl.js +3 -3
  340. package/render/layers.js +1 -1
  341. package/render/lightmap.js +23 -3
  342. package/render/occlusion.js +43 -12
  343. package/render/patches.js +2 -2
  344. package/render/postWebGL.js +4 -3
  345. package/render/probes.js +25 -0
  346. package/render/shadows.js +2 -2
  347. package/types/core.d.ts +142 -55
  348. package/types/gameplay.d.ts +92 -40
  349. package/types/generated/core/base/I18n.d.ts +2 -2
  350. package/types/generated/core/input/Input.d.ts +16 -2
  351. package/types/generated/core/input/inputSeat.d.ts +26 -0
  352. package/types/generated/core/inspect/DebugOverrides.d.ts +15 -1
  353. package/types/generated/core/ops/Ops.d.ts +2 -1
  354. package/types/generated/core/ops/control.d.ts +12 -2
  355. package/types/generated/core/saves/Saves.d.ts +26 -6
  356. package/types/generated/core/saves/session.d.ts +1 -1
  357. package/types/generated/core/scene/Views.d.ts +1 -1
  358. package/types/generated/core/stream/Stream.d.ts +6 -4
  359. package/types/generated/modules/grid/Grid.d.ts +1 -0
  360. package/types/generated/modules/particles/Particles.d.ts +4 -3
  361. package/types/generated/modules/timeline/Timeline.d.ts +5 -4
  362. package/types/generated/modules/weather/Weather.d.ts +1 -7
  363. package/types/generated/modules/world/World.d.ts +6 -4
  364. package/types/generated/render/PostFX.d.ts +6 -14
  365. package/types/nav.d.ts +36 -4
  366. package/types/physics.d.ts +55 -7
  367. package/types/pixel.d.ts +75 -0
  368. package/types/world.d.ts +14 -8
  369. package/ui/Parts.js +9 -2
  370. package/ui/theme.js +2 -2
  371. package/core/scene/engineCamera.js +0 -32
  372. package/modules/camera/projection.js +0 -21
@@ -30,6 +30,10 @@
30
30
  // after birth particles always move in world coordinates and are not dragged along by the object
31
31
  // fog true affected by fog
32
32
  // maxPixels 512 largest on-screen size of one particle (pixels), so smoke drifting past the camera does not fill the screen
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
+ // soft 0 meters over which a particle fades where it meets opaque geometry; 0 is off. Set at define, not per batch
35
+ // 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
+ // Each particle's life fraction (0 birth, 1 death) is the geometry attribute aLife, for a game's own material.
33
37
  //
34
38
  // Pictures: particles({ effects: { name: {...same params...} }, default: {...} }). effects[name] sits under the define() params (what define sets wins),
35
39
  // so a game can write only engine.particles.define('leaves', { max: 200 }) and keep color and texture with the rest of its picture. default is the fallback for all effects.
@@ -37,19 +41,28 @@
37
41
  // Material: each effect's material is a plain three.js material, swapped with fx.material = myMaterial and drawn as given; fx.uniforms are the engine's { value } objects.
38
42
  import * as THREE from 'three';
39
43
  import { vec3 } from '../../core/base/math.js';
40
- import { Effect, NEUTRAL, KEYS } from './effect.js';
44
+ import { Effect, NEUTRAL, KEYS, OVER_LIFE, curve } from './effect.js';
41
45
  import { warnMissing } from '../../core/base/validate.js';
42
46
  import { readParams, keysSchema } from '../../core/base/params.js';
43
47
  import { isOptions } from '../../core/base/util.js';
44
48
  import { codedError } from '../../core/base/errorHints.js';
45
- // 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 only key names are checked
46
- const FX_PARAMS = keysSchema(KEYS);
49
+ // 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
+ const FX_PARAMS = keysSchema(KEYS, {}, {
51
+ ratePerMeter: { type: 'number', optional: true, min: 0, desc: 'particles per meter the emitter moves' },
52
+ soft: { type: 'number', optional: true, min: 0, desc: 'meters over which a particle fades into opaque geometry' },
53
+ });
54
+ /** Check one table of effect params: the schema, then the values over life (at the call, not on a later emit) */
55
+ function readFx(where, o) {
56
+ readParams(where, FX_PARAMS, o);
57
+ for (const k of Object.keys(OVER_LIFE)) if (k in o) curve(k, o[k], where);
58
+ }
47
59
  const PARTICLES_PARAMS = {
48
60
  effects: { type: 'object', optional: true, desc: 'effect params by name: under what define() gives, and defined on the first emit / attach when define() never ran' },
49
61
  default: { type: 'object', optional: true, desc: 'params every effect starts from' },
50
62
  };
51
63
  const EMIT_PARAMS = { count: { type: 'number', default: 10, min: 0, desc: 'particles in this burst' }, overrides: 'any?' }; // overrides: null is allowed (no override)
52
- const ATTACH_PARAMS = { rate: { type: 'number', optional: true, min: 0, desc: 'particles per second (default: the effect rate)' }, offset: 'any?', overrides: 'any?' };
64
+ const ATTACH_PARAMS = { rate: { type: 'number', optional: true, min: 0, desc: 'particles per second (default: the effect rate)' },
65
+ ratePerMeter: { type: 'number', optional: true, min: 0, desc: 'particles per meter moved (default: the effect ratePerMeter)' }, offset: 'any?', overrides: 'any?' };
53
66
  const _vs = new THREE.Vector2(); // canvas CSS size (particle point scale follows the canvas height, not the window)
54
67
  /** @import { ModuleDef } from '../../types/core' */
55
68
  /** @import { Object3D, PositionLike } from '../../types/common' */
@@ -73,6 +86,8 @@ export class Particles {
73
86
  /** @internal */ this._q = new THREE.Quaternion();
74
87
  /** @internal */ this._o = new THREE.Vector3();
75
88
  /** @internal */ this._e = new THREE.Vector3();
89
+ /** @internal */ this._path = { from: new THREE.Vector3(), first: 0, step: 0 };
90
+ /** @internal the scene depth soft effects read on WebGLRenderer, once one draws */ this._depth = null;
76
91
  }
77
92
 
78
93
  /**
@@ -86,7 +101,7 @@ export class Particles {
86
101
  * @returns {ParticleEffect}
87
102
  */
88
103
  define(name, opts = {}) {
89
- readParams(`particles.define('${name}')`, FX_PARAMS, opts);
104
+ readFx(`particles.define('${name}')`, opts);
90
105
  const old = this.effects.get(name);
91
106
  const o = { ...NEUTRAL, max: this.engine.tier === 'low' ? NEUTRAL.max / 2 : NEUTRAL.max, ...this._fallback, ...this._given[name], ...opts };
92
107
  const fx = new Effect(this, name, o);
@@ -110,7 +125,7 @@ export class Particles {
110
125
  }
111
126
 
112
127
  /**
113
- * 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 cannot be changed temporarily)
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)
114
129
  * @param {string} name
115
130
  * @param {PositionLike} position
116
131
  * @param {{ count?: number, overrides?: ParticleOptions | null }} [opts]
@@ -119,22 +134,22 @@ export class Particles {
119
134
  emit(name, position, opts = {}) {
120
135
  const { count, overrides = null } = readParams(`particles.emit('${name}')`, EMIT_PARAMS, opts);
121
136
  const fx = this._get(name); if (!fx) return;
122
- if (overrides) readParams(`particles.emit('${name}') overrides`, FX_PARAMS, overrides);
137
+ if (overrides) readFx(`particles.emit('${name}') overrides`, overrides);
123
138
  fx.spawn(vec3(position, this._e), count, overrides ? { ...fx.o, ...overrides } : fx.o, null);
124
139
  }
125
140
 
126
141
  /**
127
- * Keep emitting while following an object: rate per second, offset in the object's local coordinates [x, y, z] (meters). Returns a handle { remove(), rate, active } (active = false pauses)
142
+ * Keep emitting while following an object: rate per second, ratePerMeter per meter it moves (spread along the path, on top of rate), offset in the object's local coordinates [x, y, z] (meters). Returns a handle { remove(), rate, ratePerMeter, active } (active = false pauses)
128
143
  * @param {string} name
129
144
  * @param {Object3D} object3d
130
- * @param {{ rate?: number, offset?: number[], overrides?: ParticleOptions | null }} [opts]
145
+ * @param {{ rate?: number, ratePerMeter?: number, offset?: number[], overrides?: ParticleOptions | null }} [opts]
131
146
  * @returns {ParticleEmitter}
132
147
  */
133
148
  attach(name, object3d, opts = {}) {
134
- const { rate, offset = [0, 0, 0], overrides = null } = readParams(`particles.attach('${name}')`, ATTACH_PARAMS, opts);
135
- if (overrides) readParams(`particles.attach('${name}') overrides`, FX_PARAMS, overrides);
136
- const fx = this._get(name); if (!fx) return { remove() {}, rate: 0, active: false };
137
- const h = { fx, object: object3d, rate: rate ?? fx.o.rate, offset, overrides, active: true, acc: 0, remove: () => { h.active = false; this.emitters.delete(h); } };
149
+ const { rate, ratePerMeter, offset = [0, 0, 0], overrides = null } = readParams(`particles.attach('${name}')`, ATTACH_PARAMS, opts);
150
+ if (overrides) readFx(`particles.attach('${name}') overrides`, overrides);
151
+ const fx = this._get(name); if (!fx) return { remove() {}, rate: 0, ratePerMeter: 0, active: false };
152
+ const h = { fx, object: object3d, rate: rate ?? fx.o.rate, ratePerMeter: ratePerMeter ?? fx.o.ratePerMeter, last: null, offset, overrides, active: true, acc: 0, remove: () => { h.active = false; this.emitters.delete(h); } };
138
153
  this.emitters.add(h);
139
154
  return h;
140
155
  }
@@ -156,6 +171,52 @@ export class Particles {
156
171
  */
157
172
  clear(name) { for (const fx of name ? [this.effects.get(name)].filter(Boolean) : this.effects.values()) { fx.life.fill(0); fx.aAlpha.array.fill(0); fx.alive = 0; fx._stale = fx.max; fx.points.visible = false; } }
158
173
 
174
+ /** @internal Where the emitter is in the world (written into this._o) */
175
+ _at(h) {
176
+ h.object.updateWorldMatrix(true, false);
177
+ return this._o.set(h.offset[0], h.offset[1], h.offset[2]).applyMatrix4(h.object.matrixWorld);
178
+ }
179
+
180
+ /**
181
+ * @internal Add what emitter h earned by moving this step to h.acc. Returns the path for spawn, or null when it did not move: every particle
182
+ * this step gets the same spacing, whichever of rate and ratePerMeter earned it, and the fraction left in h.acc carries it across steps
183
+ */
184
+ _walked(h, dt) {
185
+ const to = this._at(h), moved = h.last && dt > 0 ? to.distanceTo(h.last) : 0, path = this._path;
186
+ if (moved > 0) {
187
+ const earned = moved * h.ratePerMeter;
188
+ path.from.copy(h.last); path.step = 1 / (earned + dt * h.rate); path.first = (1 - h.acc) * path.step;
189
+ h.acc += earned;
190
+ }
191
+ (h.last ??= new THREE.Vector3()).copy(to);
192
+ return moved > 0 ? path : null;
193
+ }
194
+
195
+ /**
196
+ * @internal The depth of what is opaque, for soft effects on WebGLRenderer. A shader cannot read the depth buffer it is drawing into there, so the scene's
197
+ * opaque objects are drawn once more, depth only, from inside the draw of the first soft effect of this render: nothing runs unless a soft effect is on screen.
198
+ * The stand-in material knows no wind, displacement or alphaTest, so such surfaces fade as their plain shape
199
+ */
200
+ _sceneDepth(r, scene, camera) {
201
+ const d = this._depth ??= { target: new THREE.WebGLRenderTarget(1, 1, { depthTexture: new THREE.DepthTexture(1, 1) }), frame: -1, camera: null,
202
+ material: new THREE.MeshDepthMaterial({ colorWrite: false, side: THREE.DoubleSide }) };
203
+ 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 = [];
205
+ d.target.setSize(size.x, size.y);
206
+ // by layer, not visible: an opaque child of a transparent parent still counts
207
+ 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
+ }
216
+ d.frame = r.info.render.frame; d.camera = camera;
217
+ return d.target.depthTexture;
218
+ }
219
+
159
220
  /**
160
221
  * Update all effects every frame (called by the module each frame)
161
222
  * @param {number} dt
@@ -164,10 +225,11 @@ export class Particles {
164
225
  */
165
226
  update(dt) {
166
227
  if (this.engine.still) dt = 0; // freeze(owner, { ambient: true }): sparks hold in the air
167
- const cam = this.engine.camera, pr = this.engine.renderer.getPixelRatio(), scale = this.engine.renderer.getSize(_vs).y * pr / (cam.orthoSize ? cam.orthoSize / cam.zoom : 2 * Math.tan(THREE.MathUtils.degToRad(cam.fov) / 2)); // orthographic: pixels per world unit
228
+ 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
168
229
  for (const h of this.emitters) {
169
- if (!h.active) continue;
230
+ if (!h.active) { h.last = null; continue; } // a pause leaves no line from where it stopped to where it starts again
170
231
  if (!h.object.parent) { h.remove(); continue; } // object removed from the scene: stop automatically
232
+ const path = h.ratePerMeter > 0 ? this._walked(h, dt) : null;
171
233
  h.acc += dt * h.rate;
172
234
  const n = Math.floor(h.acc);
173
235
  if (n <= 0) continue;
@@ -175,10 +237,9 @@ export class Particles {
175
237
  // merged params are cached on the handle (re-merged only when overrides is a new object), not spread every frame
176
238
  if (h._ov !== h.overrides || h._base !== h.fx.o) { h._ov = h.overrides; h._base = h.fx.o; h._merged = h.overrides ? { ...h.fx.o, ...h.overrides } : h.fx.o; }
177
239
  const o = h._merged;
178
- h.object.updateWorldMatrix(true, false);
179
- const p = this._o.set(h.offset[0], h.offset[1], h.offset[2]).applyMatrix4(h.object.matrixWorld);
240
+ const p = this._at(h);
180
241
  h.object.getWorldQuaternion(this._q);
181
- h.fx.spawn(p, n, o, o.worldSpace === false ? this._q : null);
242
+ h.fx.spawn(p, n, o, o.worldSpace === false ? this._q : null, path);
182
243
  }
183
244
  for (const fx of this.effects.values()) { fx.uniforms.uScale.value = scale; fx.update(dt); }
184
245
  }
@@ -196,12 +257,12 @@ export function particles(opts = {}) {
196
257
  // checked here, not on the first emit: a typo in a style table should fail at startup, not in the middle of play
197
258
  for (const [name, spec] of Object.entries(opts.effects ?? {})) {
198
259
  if (!isOptions(spec)) throw codedError('module-params', `particles({ effects: { ${name} } }): an effect is an object of params, e.g. { max: 200, color: 0xcccccc }; got ${JSON.stringify(spec)}`);
199
- readParams(`particles({ effects: { ${name} } })`, FX_PARAMS, spec);
260
+ readFx(`particles({ effects: { ${name} } })`, spec);
200
261
  }
201
- if (opts.default) readParams('particles({ default })', FX_PARAMS, opts.default);
262
+ if (opts.default) readFx('particles({ default })', opts.default);
202
263
  let p = null;
203
- return { name: 'particles', type: 'picture', provides: ['particles'], label: 'Particles', params: PARTICLES_PARAMS, options: opts, stage: 'effects', install(e) { e.i18n.add({ 'zh-CN': { 'module.particles': '粒子' }, en: { 'module.particles': 'particles' } }); p = new Particles(e, opts); return p; }, frame(dt) { p.update(dt); },
204
- dispose() { for (const fx of p.effects.values()) fx.dispose(); p.effects.clear(); p.emitters.clear(); },
264
+ return { name: 'particles', skipKind: 'none', type: 'picture', provides: ['particles'], label: 'Particles', params: PARTICLES_PARAMS, options: opts, stage: 'effects', install(e) { e.i18n.add({ 'zh-CN': { 'module.particles': '粒子' }, en: { 'module.particles': 'particles' } }); p = new Particles(e, opts); return p; }, frame(dt) { p.update(dt); },
265
+ dispose() { for (const fx of p.effects.values()) fx.dispose(); p.effects.clear(); p.emitters.clear(); p._depth?.target.depthTexture.dispose(); p._depth?.target.dispose(); p._depth?.material.dispose(); },
205
266
  counts() { return { alive: p.count(), emitters: p.emitters.size }; }, // engine.counts().particles
206
267
  // "did the dust burst fire": live particles in total and per effect that has any (idle effects left out to stay short). Kept under `alive`
207
268
  // because the numbers change every frame (an emitter's smoke): state comparisons (the session spec) skip that key as presentation, not game state
@@ -210,3 +271,5 @@ export function particles(opts = {}) {
210
271
  return { effects: p.effects.size, emitters: p.emitters.size, alive: { total: p.count(), effects: each } };
211
272
  } };
212
273
  }
274
+
275
+ export const handRolled = [{ kind: 'particles', seen: 'a particle loop of its own', use: 'engine.particles: emitters on game time, one draw call, budgets (recipe 64)', quiet: /\b(engine|e|eng|ctx)\.particles\b|\bparticles\(\s*[{)]/, code: /\bfor\s*\([^)]*\bof\s+[\w.]*(?:particles|sparks|embers)\b|\b(?:particles|sparks|embers)\.(?:forEach|filter)\s*\(/i, near: [{ re: /\.(?:life|age|ttl|vel\w*|v[xyz])\b/, lines: 5 }] }];
@@ -1,16 +1,47 @@
1
1
  // One particle effect (helper of Particles.js): a ring buffer of particles drawn as one THREE.Points, updated on the CPU every frame.
2
2
  import * as THREE from 'three';
3
- import { needMaterial } from '../../core/base/validate.js';
3
+ import { needMaterial, warnOnce } from '../../core/base/validate.js';
4
+ import { codedError, coded } from '../../core/base/errorHints.js';
4
5
  import { vert, frag } from './shaders.js';
5
6
  import { isWebGPU, webgpuPart, onRendererSwap } from '../../render/backend.js';
6
7
 
7
8
  export const NEUTRAL = {
8
9
  max: 120, lifetime: [1, 2], rate: 10, speed: [0.5, 1.5], direction: [0, 1, 0], spread: 0.5, area: 0,
9
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],
10
- texture: null, blending: 'normal', spin: 0, worldSpace: true, fog: true, maxPixels: 512,
11
+ texture: null, blending: 'normal', spin: 0, worldSpace: true, fog: true, maxPixels: 512, ratePerMeter: 0, soft: 0,
11
12
  };
12
13
  export const KEYS = Object.keys(NEUTRAL);
13
14
  const pair = v => Array.isArray(v) ? v : [v, v];
15
+ /** Numbers per stop of the values that change over life */
16
+ export const OVER_LIFE = { size: 1, opacity: 1, color: 3 };
17
+ const _col = new THREE.Color();
18
+ /**
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
+ * [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.
21
+ * @param {keyof typeof OVER_LIFE} key @param {any} given @param {string} where
22
+ */
23
+ export function curve(key, given, where) {
24
+ const list = Array.isArray(given) ? given : [given, given], timed = Array.isArray(list[0]), n = list.length, w = OVER_LIFE[key], t = [], v = [];
25
+ const bad = why => codedError('module-params', `${where}: ${key} ${why}. It is one value, [birth, death], evenly spaced stops [a, b, c], or timed stops [[0, a], [0.2, b], [1, c]]; got ${JSON.stringify(given)}`);
26
+ if (n < 2) throw bad('needs two stops or more');
27
+ list.forEach((s, i) => {
28
+ if (Array.isArray(s) !== timed || timed && s.length !== 2) throw bad('mixes the forms');
29
+ const at = timed ? s[0] : i / (n - 1), val = timed ? s[1] : s;
30
+ if (!(at >= (i ? t[i - 1] : 0) && at <= 1)) throw bad('needs stop times from 0 to 1, in order');
31
+ t.push(at);
32
+ if (w === 3) { _col.set(val); v.push(_col.r, _col.g, _col.b); } // three converts to linear color space automatically
33
+ else if (Number.isFinite(val)) v.push(val);
34
+ else throw bad('needs numbers');
35
+ });
36
+ return { t, v, w };
37
+ }
38
+ /** One channel of c at life fraction k */
39
+ function sample(c, k, ch = 0) {
40
+ const t = c.t, last = t.length - 2;
41
+ let s = 0; while (s < last && k >= t[s + 1]) s++;
42
+ const a = c.v[s * c.w + ch];
43
+ return a + (c.v[(s + 1) * c.w + ch] - a) * Math.min(1, Math.max(0, (k - t[s]) / (t[s + 1] - t[s] || 1)));
44
+ }
14
45
  /** The node-material side (render/fx/particles.tsl.js, loaded with threedog/tsl) when the renderer is a WebGPURenderer, else null */
15
46
  function nodeSide(engine, name) {
16
47
  return isWebGPU(engine.renderer) ? webgpuPart('particles', `[particles ${name}] the particle material`) : null;
@@ -23,21 +54,20 @@ export class Effect {
23
54
  this.pos = new Float32Array(N * 3); this.vel = new Float32Array(N * 3);
24
55
  this.age = new Float32Array(N); this.life = new Float32Array(N).fill(0); // life 0 = empty slot
25
56
  this.spinV = new Float32Array(N);
26
- this.col0 = new Float32Array(N * 3); this.col1 = new Float32Array(N * 3); // start/end color of each particle (emit may override)
27
- this.sz = new Float32Array(N * 2); this.op = new Float32Array(N * 2);
57
+ this.overLife = { size: new Array(N), opacity: new Array(N), color: new Array(N) }; // each particle's curves, shared by its batch (emit may override)
28
58
  this.extra = new Float32Array(N * 3); // gravity, drag, wind (emit may override)
59
+ this._curves = {}; // the last curve of each kind: most batches reuse the effect's own, like the merged params of a handle
29
60
  this.head = 0; this.alive = 0;
30
61
  /** @internal clear() zeroed slots the GPU copy still shows: the next upload reaches this far */ this._stale = 0;
31
62
  /** @internal the game's material while one is set */ this._given = null;
32
- this._c0 = new THREE.Color(); this._c1 = new THREE.Color();
33
63
  this._build();
34
64
  // fallback 'webgl': an effect defined before start() was built for the WebGPURenderer start() then replaced; build its draw object again
35
65
  // for the renderer in use (the particle state lives in the arrays above, so live particles carry over)
36
66
  /** @internal */ this._swap = onRendererSwap(sys.engine, () => {
37
- const vis = this.points.visible, was = [this.aPos, this.aSize, this.aAlpha, this.aAngle, this.aColor].map(a => a.array);
67
+ const vis = this.points.visible, was = this._attrs.map(a => a.array);
38
68
  this._drop();
39
69
  this._build();
40
- [this.aPos, this.aSize, this.aAlpha, this.aAngle, this.aColor].forEach((a, i) => a.array.set(was[i]));
70
+ this._attrs.forEach((a, i) => a.array.set(was[i]));
41
71
  this.points.visible = vis;
42
72
  if (this._given) this.points.material = this._given;
43
73
  if (this._tex) this._useTexture(this._tex);
@@ -49,10 +79,13 @@ export class Effect {
49
79
  get material() { return this._given ?? this._own; }
50
80
  set material(m) {
51
81
  if (m != null) needMaterial('module-params', `particles '${this.name}': material`, m, " (null gives the engine's back)");
82
+ if (m && this._own.isNodeMaterial && !m.isNodeMaterial) throw codedError('module-params', `particles '${this.name}': on WebGPURenderer the material is a node material (PointsNodeMaterial from 'three/webgpu'), got ${m.type}`);
52
83
  this._given = m || null;
84
+ // WebGPU: the effect is one quad drawn N times, and where each one goes and how big is the engine material's nodes. Without them every particle sits on the origin
85
+ if (m && this._own.isNodeMaterial) { m.positionNode ??= this._own.positionNode; m.sizeNode ??= this._own.sizeNode; }
53
86
  this.points.material = m ?? this._own;
54
87
  }
55
- /** The engine material's { value } objects (uMap, uHasMap, uScale, uMaxPx): the engine writes them whichever material is drawn, a ShaderMaterial of yours can share them */
88
+ /** The engine material's { value } objects (uMap, uHasMap, uScale, uMaxPx, and uSoft with soft on): the engine writes them whichever material is drawn, a ShaderMaterial of yours can share them */
56
89
  get uniforms() { return this._own.uniforms; }
57
90
 
58
91
  /** @internal engine.remove disposes what the object draws, so the game's material comes off first: it stays the game's */
@@ -64,16 +97,30 @@ export class Effect {
64
97
  const g = this.geometry = new THREE.BufferGeometry();
65
98
  const gpu = nodeSide(sys.engine, name); // WebGPU: the same attributes, read per instance by sprite quads
66
99
  const attr = (n, size) => { const a = new (gpu ? THREE.InstancedBufferAttribute : THREE.BufferAttribute)(new Float32Array(N * size), size); a.setUsage(THREE.DynamicDrawUsage); g.setAttribute(n, a); return a; };
67
- this.aPos = attr('position', 3); this.aSize = attr('aSize', 1); this.aAlpha = attr('aAlpha', 1); this.aAngle = attr('aAngle', 1); this.aColor = attr('aColor', 3);
68
- this._attrs = null;
100
+ this.aPos = attr('position', 3); this.aSize = attr('aSize', 1); this.aAlpha = attr('aAlpha', 1); this.aAngle = attr('aAngle', 1); this.aColor = attr('aColor', 3); this.aLife = attr('aLife', 1);
101
+ this._attrs = [this.aPos, this.aSize, this.aAlpha, this.aColor, this.aAngle, this.aLife];
102
+ const soft = o.soft > 0 ? o.soft : 0;
69
103
  if (gpu) ({ material: this._own, object: this.points } = gpu.particles({ count: N, fog: o.fog !== false, additive: o.blending === 'additive',
70
- maxPixels: o.maxPixels, attrs: { aPos: this.aPos, aSize: this.aSize, aAlpha: this.aAlpha, aAngle: this.aAngle, aColor: this.aColor } }));
104
+ maxPixels: o.maxPixels, soft, attrs: { aPos: this.aPos, aSize: this.aSize, aAlpha: this.aAlpha, aAngle: this.aAngle, aColor: this.aColor, aLife: this.aLife } }));
71
105
  else this._own = new THREE.ShaderMaterial({
72
106
  vertexShader: vert, fragmentShader: frag, transparent: true, depthWrite: false, fog: o.fog !== false,
73
107
  blending: o.blending === 'additive' ? THREE.AdditiveBlending : THREE.NormalBlending,
74
- uniforms: THREE.UniformsUtils.merge([THREE.UniformsLib.fog, { uMap: { value: null }, uHasMap: { value: 0 }, uScale: { value: 400 }, uMaxPx: { value: o.maxPixels } }]),
108
+ uniforms: THREE.UniformsUtils.merge([THREE.UniformsLib.fog, { uMap: { value: null }, uHasMap: { value: 0 }, uScale: { value: 400 }, uMaxPx: { value: o.maxPixels } },
109
+ soft ? { uSoft: { value: soft }, uDepth: { value: null }, uDepthView: { value: new THREE.Vector4() }, uClip: { value: new THREE.Vector2() } } : {}]),
110
+ defines: soft ? { SOFT: 1 } : {},
75
111
  });
76
112
  if (!gpu) this.points = new THREE.Points(g, this._own);
113
+ // On the WebGL2 backend three's depth copy works from a multisampled target only, so the canvas and a plain target give no fade. The backend is known at the first draw
114
+ if (gpu && soft) this.points.onBeforeRender = r => {
115
+ if (r.backend.isWebGLBackend) warnOnce(coded('module-params', `particles '${name}': soft has no fade on WebGPURenderer's WebGL2 backend unless post draws with antialias; the particles draw hard`), 'particles-soft-webgl2');
116
+ };
117
+ if (!gpu && soft) this.points.onBeforeRender = (r, scene, camera) => {
118
+ if (this.points.material !== this._own) return; // the game's material reads what it wants; nobody needs the depth drawn
119
+ const u = this._own.uniforms;
120
+ u.uDepth.value = sys._sceneDepth(r, scene, camera);
121
+ r.getCurrentViewport(u.uDepthView.value); u.uClip.value.set(camera.near, camera.far);
122
+ this._own.uniformsNeedUpdate = true;
123
+ };
77
124
  this.points.frustumCulled = false; this.points.visible = false; this.points.renderOrder = 10;
78
125
  this.points.matrixAutoUpdate = false;
79
126
  sys.engine.add(this.points, { owner: 'engine:particles' });
@@ -87,22 +134,32 @@ export class Effect {
87
134
  else this.sys.engine.assets.useTexture(t, tex => this._useTexture(tex), { where: `particles '${this.name}'`, instead: 'a round dot shows instead' });
88
135
  }
89
136
 
90
- /** Emit count particles. origin {x,y,z}; o is the merged params; frame optional: particle direction rotates with the object */
91
- spawn(origin, count, o, quat) {
137
+ /** curve(), read again only when the value given is another one @internal */
138
+ _curve(key, given, where) {
139
+ const last = this._curves[key];
140
+ return last?.given === given ? last : (this._curves[key] = { ...curve(key, given, where), given });
141
+ }
142
+
143
+ /**
144
+ * Emit count particles. origin {x,y,z}; o is the merged params; frame optional: particle direction rotates with the object.
145
+ * path optional { from, first, step }: particle n is born that fraction of the way from `from` to origin (first + n * step); over max, the newest stay
146
+ */
147
+ spawn(origin, count, o, quat, path = null) {
92
148
  // presentation: particle scatter
93
- const N = this.max, rnd = Math.random, life = pair(o.lifetime), spd = pair(o.speed), sz = pair(o.size), op = pair(o.opacity), col = pair(o.color);
94
- this._c0.set(col[0]); this._c1.set(col[1]); // three converts to linear color space automatically
149
+ const N = this.max, rnd = Math.random, life = pair(o.lifetime), spd = pair(o.speed), where = `particles '${this.name}'`;
150
+ const size = this._curve('size', o.size, where), opacity = this._curve('opacity', o.opacity, where), color = this._curve('color', o.color, where);
95
151
  const dir = this.sys._dir.set(o.direction[0], o.direction[1], o.direction[2]).normalize();
96
152
  if (quat) dir.applyQuaternion(quat);
97
153
  // two perpendicular directions around axis dir, for random picks inside the cone
98
154
  const up = Math.abs(dir.y) < 0.99 ? this.sys._up.set(0, 1, 0) : this.sys._up.set(1, 0, 0);
99
155
  const t1 = this.sys._t1.crossVectors(dir, up).normalize(), t2 = this.sys._t2.crossVectors(dir, t1);
100
156
  const area = o.area, ax = Array.isArray(area) ? area[0] : area, ay = Array.isArray(area) ? area[1] : area, az = Array.isArray(area) ? area[2] : area;
101
- for (let n = 0; n < count; n++) {
157
+ for (let n = path ? Math.max(0, count - N) : 0; n < count; n++) {
102
158
  const i = this.head; this.head = (this.head + 1) % N;
103
159
  if (this.life[i] === 0) this.alive++;
104
160
  const i3 = i * 3;
105
- this.pos[i3] = origin.x + (rnd() * 2 - 1) * ax; this.pos[i3 + 1] = origin.y + (rnd() * 2 - 1) * ay; this.pos[i3 + 2] = origin.z + (rnd() * 2 - 1) * az;
161
+ const at = path ? this.sys._e.lerpVectors(path.from, origin, path.first + n * path.step) : origin;
162
+ this.pos[i3] = at.x + (rnd() * 2 - 1) * ax; this.pos[i3 + 1] = at.y + (rnd() * 2 - 1) * ay; this.pos[i3 + 2] = at.z + (rnd() * 2 - 1) * az;
106
163
  // random direction in a cone: off-axis angle theta in [0, spread] (cos theta uniform = uniform on the sphere)
107
164
  const cosT = 1 - rnd() * (1 - Math.cos(Math.min(Math.PI, o.spread))), sinT = Math.sqrt(1 - cosT * cosT), ph = rnd() * Math.PI * 2;
108
165
  const a = Math.cos(ph) * sinT, b = Math.sin(ph) * sinT, v = spd[0] + rnd() * (spd[1] - spd[0]);
@@ -112,9 +169,7 @@ export class Effect {
112
169
  this.age[i] = 0; this.life[i] = life[0] + rnd() * (life[1] - life[0]) || 0.01;
113
170
  this.spinV[i] = o.spin ? (rnd() * 2 - 1) * o.spin : 0;
114
171
  this.aAngle.array[i] = rnd() * Math.PI * 2;
115
- this.col0[i3] = this._c0.r; this.col0[i3 + 1] = this._c0.g; this.col0[i3 + 2] = this._c0.b;
116
- this.col1[i3] = this._c1.r; this.col1[i3 + 1] = this._c1.g; this.col1[i3 + 2] = this._c1.b;
117
- this.sz[i * 2] = sz[0]; this.sz[i * 2 + 1] = sz[1]; this.op[i * 2] = op[0]; this.op[i * 2 + 1] = op[1];
172
+ this.overLife.size[i] = size; this.overLife.opacity[i] = opacity; this.overLife.color[i] = color;
118
173
  this.extra[i3] = o.gravity; this.extra[i3 + 1] = o.drag; this.extra[i3 + 2] = o.wind;
119
174
  }
120
175
  this.points.visible = true;
@@ -122,7 +177,7 @@ export class Effect {
122
177
 
123
178
  update(dt) {
124
179
  if (!this.alive) { this.points.visible = false; return; }
125
- 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;
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;
126
181
  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;
127
182
  let alive = 0, hi = -1;
128
183
  for (let i = 0; i < N; i++) {
@@ -135,11 +190,8 @@ export class Effect {
135
190
  const i3 = i * 3, k = age / L, g = this.extra[i3], dr = Math.max(0, 1 - this.extra[i3 + 1] * dt), wd = this.extra[i3 + 2];
136
191
  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;
137
192
  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;
138
- as[i] = this.sz[i * 2] + (this.sz[i * 2 + 1] - this.sz[i * 2]) * k;
139
- aa[i] = this.op[i * 2] + (this.op[i * 2 + 1] - this.op[i * 2]) * k;
140
- ac[i3] = this.col0[i3] + (this.col1[i3] - this.col0[i3]) * k;
141
- ac[i3 + 1] = this.col0[i3 + 1] + (this.col1[i3 + 1] - this.col0[i3 + 1]) * k;
142
- ac[i3 + 2] = this.col0[i3 + 2] + (this.col1[i3 + 2] - this.col0[i3 + 2]) * k;
193
+ 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);
143
195
  if (this.spinV[i]) ag[i] += this.spinV[i] * dt;
144
196
  }
145
197
  this.alive = alive;
@@ -148,7 +200,7 @@ export class Effect {
148
200
  const n = hi + 1, up = Math.max(n, this._stale);
149
201
  this._stale = 0;
150
202
  if (this.points.isSprite) this.points.count = n; // WebGPU sprites: instances up to the last live one (dead ones in between have size 0)
151
- for (const a of this._attrs ||= [this.aPos, this.aSize, this.aAlpha, this.aColor, this.aAngle]) {
203
+ for (const a of this._attrs) {
152
204
  a.clearUpdateRanges(); a.addUpdateRange(0, up * a.itemSize); a.needsUpdate = true;
153
205
  }
154
206
  }
@@ -1,13 +1,20 @@
1
1
  // Particle point-sprite shaders: size by distance (capped at uMaxPx), soft round dot or a texture, rotation, fog, tone mapping and output color space.
2
+ // SOFT (the soft option): fades where the particle meets opaque geometry; uDepth is the scene depth Particles._sceneDepth drew. Without it the shaders are as ever.
2
3
  export const vert = `
3
4
  attribute float aSize; attribute float aAlpha; attribute float aAngle; attribute vec3 aColor;
4
5
  varying float vAlpha; varying float vAngle; varying vec3 vColor;
5
6
  uniform float uScale; uniform float uMaxPx;
7
+ #ifdef SOFT
8
+ varying float vViewZ;
9
+ #endif
6
10
  #include <fog_pars_vertex>
7
11
  void main() {
8
12
  vAlpha = aAlpha; vAngle = aAngle; vColor = aColor;
9
13
  vec4 mvPosition = modelViewMatrix * vec4(position, 1.0);
10
14
  gl_Position = projectionMatrix * mvPosition;
15
+ #ifdef SOFT
16
+ vViewZ = mvPosition.z;
17
+ #endif
11
18
  // uScale is pixels per meter at distance 1, or just pixels per meter on an orthographic camera (no shrink with distance); capped: no screen-filling sprites near the camera
12
19
  gl_PointSize = aAlpha <= 0.0 ? 0.0 : min(aSize * uScale / (isOrthographic ? 1.0 : max(0.1, -mvPosition.z)), uMaxPx);
13
20
  #include <fog_vertex>
@@ -15,6 +22,11 @@ export const vert = `
15
22
  export const frag = `
16
23
  uniform sampler2D uMap; uniform float uHasMap;
17
24
  varying float vAlpha; varying float vAngle; varying vec3 vColor;
25
+ #ifdef SOFT
26
+ #include <packing>
27
+ uniform sampler2D uDepth; uniform vec4 uDepthView; uniform vec2 uClip; uniform float uSoft;
28
+ varying float vViewZ;
29
+ #endif
18
30
  #include <fog_pars_fragment>
19
31
  void main() {
20
32
  vec2 p = gl_PointCoord - 0.5;
@@ -22,6 +34,11 @@ export const frag = `
22
34
  p = vec2(c * p.x - s * p.y, s * p.x + c * p.y);
23
35
  vec4 tex = uHasMap > 0.5 ? texture2D(uMap, p + 0.5) : vec4(1.0, 1.0, 1.0, smoothstep(0.5, 0.2, length(p)));
24
36
  gl_FragColor = vec4(vColor * tex.rgb, tex.a * vAlpha);
37
+ #ifdef SOFT
38
+ float d = texture2D(uDepth, (gl_FragCoord.xy - uDepthView.xy) / uDepthView.zw).x;
39
+ float sceneZ = isOrthographic ? orthographicDepthToViewZ(d, uClip.x, uClip.y) : perspectiveDepthToViewZ(d, uClip.x, uClip.y);
40
+ gl_FragColor.a *= clamp((vViewZ - sceneZ) / uSoft, 0.0, 1.0);
41
+ #endif
25
42
  if (gl_FragColor.a < 0.01) discard;
26
43
  #include <tonemapping_fragment>
27
44
  #include <colorspace_fragment>
@@ -16,6 +16,7 @@ import { readParams, keysSchema } from '../../core/base/params.js';
16
16
  import { toast } from '../../ui/UI.js';
17
17
  import { coded } from '../../core/base/errorHints.js';
18
18
  import { setShadowUpdate, shadowsOn } from '../../render/backend.js';
19
+ import { borrowRatio } from '../../core/scene/pixelRatio.js';
19
20
  const GROUP = 'photo'; // attachment group in engine.saves
20
21
  const TAKE_KEYS = ['scale', 'shadowMapSize', 'bloom', 'quality', 'format'];
21
22
 
@@ -32,15 +33,14 @@ export class Photo {
32
33
  readParams('photo.take()', keysSchema(TAKE_KEYS), opts);
33
34
  const o = { scale: this.scale, shadowMapSize: this.shadowMapSize, bloom: this.bloom, quality: this.quality, format: this.format, ...opts };
34
35
  const e = this.engine, r = e.renderer;
35
- const prevPR = r.getPixelRatio(), prevBloom = e.post.get('bloom')?.enabled, suns = [];
36
+ const prevBloom = e.post.get('bloom')?.enabled, suns = [];
36
37
  if (shadowsOn(e)) e.scene.traverse(l => { if (l.isDirectionalLight && l.castShadow && l.visible) suns.push([l, l.shadow.mapSize.x, l.shadow.mapSize.y]); });
37
- const pr = Math.min(3, prevPR * o.scale);
38
38
  const forceBloom = typeof o.bloom === 'boolean' && prevBloom !== undefined;
39
- let url, bloomHold = null;
39
+ let url, bloomHold = null, ratioBack = null;
40
40
  // restored in finally: a throw mid-shot (a failed WebGPU frame, a tainted canvas in toDataURL) must not leave the game running at the photo's
41
41
  // pixel ratio and shadow map size with photo's bloom hold still on
42
42
  try {
43
- r.setPixelRatio(pr); // the post chain follows the renderer on its next draw (postWebGL.js follow)
43
+ ratioBack = borrowRatio(e, Math.min(3, r.getPixelRatio() * o.scale)); // the post chain follows the renderer on its next draw (postWebGL.js follow)
44
44
  for (const [l] of suns) e.shadows.mapSize(l, o.shadowMapSize);
45
45
  // a hold on the system layer, removed after the shot: the game's own choice stays what it was (tests/specs/render-once.mjs); a settings restriction still wins
46
46
  bloomHold = forceBloom ? e.mod('post.bloom.enabled', { owner: 'photo', set: o.bloom, layer: 'system' }) : null;
@@ -48,7 +48,7 @@ export class Photo {
48
48
  e.renderOnce(); // the frame the player sees, post included, read below in the same task; a fresh frame on WebGPU (engine.renderOnce)
49
49
  url = r.domElement.toDataURL(o.format, o.quality);
50
50
  } finally {
51
- r.setPixelRatio(prevPR);
51
+ ratioBack?.();
52
52
  for (const [l, w, h] of suns) e.shadows.mapSize(l, w, h);
53
53
  bloomHold?.remove();
54
54
  }
@@ -84,7 +84,7 @@ export class Photo {
84
84
  async restore() {
85
85
  let rows; try { rows = await this.engine.saves.attachments(GROUP); } catch (err) { this._fail(err); return; }
86
86
  const have = new Set(this.album.map(s => s.id));
87
- for (const r of rows) if (!have.has(r.id)) this.album.push({ id: r.id, url: URL.createObjectURL(r.blob), ...r.meta, at: r.at });
87
+ for (const r of rows) if (!have.has(r.id)) this.album.push({ ...r.meta, id: r.id, url: URL.createObjectURL(r.blob), at: r.at }); // meta first: an imported file's meta.url must not replace the photo
88
88
  this.album.sort((a, b) => (b.at ?? Infinity) - (a.at ?? Infinity) || 0); // a just-taken shot has no `at`: goes first
89
89
  while (this.album.length > this.maxAlbum) this._drop(this.album.pop());
90
90
  }
@@ -124,25 +124,25 @@ export function photo(all = {}) {
124
124
  const opts = all;
125
125
  let ph = null;
126
126
  return {
127
- name: 'photo', type: 'tool', params: PHOTO_PARAMS, options: all, label: 'Photo mode', optional: ['cameraRig', 'sky', 'calendar', 'vegetation', 'characters'],
127
+ name: 'photo', skipKind: 'none', type: 'tool', params: PHOTO_PARAMS, options: all, label: 'Photo mode', optional: ['cameraRig', 'sky', 'calendar', 'vegetation', 'characters'],
128
128
  install(e, ctx) {
129
129
  e.i18n.add(STRINGS);
130
130
  // declared only: the game binds the key (presets.bindings.photo or its own; [] = no key), so every key in a game comes from one bindings table
131
131
  ctx.input.action('photo', { label: 'photo.action' });
132
- if (e.input.keysOf('photo').length) e.input.touchButton('photo', 'photo.action');
132
+ if (e.input.keysOf('photo').length) ctx.track(e.input.touchButton('photo', 'photo.action'));
133
133
  builtInSounds(e.assets, { shutter: (audio, p, out) => { // sound asset 'shutter', silent until audio.sounds names it
134
134
  audio.noiseBurst({ dur: 0.03, type: 'highpass', freq: p.freq ?? 3000, vol: p.volume ?? 0.4, out });
135
135
  audio.noiseBurst({ dur: 0.05, type: 'bandpass', freq: 1800, vol: (p.volume ?? 0.4) * 0.75, delay: 0.07, out }); return 0.15;
136
136
  } });
137
137
  ph = new Photo(e, opts);
138
138
  ph.restore(); // read photos taken last time back from storage
139
- ctx.track(e.ops.define('photo.take', {
139
+ ctx.ops.define('photo.take', {
140
140
  desc: 'Take a photo (refused when photo.canTake() returns false or a reason)',
141
141
  can: () => { const r = ph.canTake(); return r === true ? true : typeof r === 'string' && r ? r : 'denied'; },
142
142
  run: () => ph.take(),
143
143
  offers: () => [{}],
144
144
  reasons: { denied: 'photo.canTake() returned false' },
145
- }));
145
+ });
146
146
  ctx.track(e.events.on('save:imported', () => ph.restore())); // after restoring from a save file, the attachments in the file (photos) also go into the album
147
147
  return ph;
148
148
  },
@@ -160,3 +160,5 @@ export function photo(all = {}) {
160
160
  },
161
161
  };
162
162
  }
163
+
164
+ export const handRolled = 'none: a screenshot is one browser call, and a hint would add nothing to it';