threedog 1.1.0 → 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 (363) hide show
  1. package/CHANGELOG.md +879 -798
  2. package/README.md +1 -1
  3. package/core/assets/Animator.js +41 -3
  4. package/core/assets/Assets.js +100 -24
  5. package/core/assets/assetEntry.js +73 -20
  6. package/core/assets/assetHot.js +68 -16
  7. package/core/assets/assetLoad.js +6 -6
  8. package/core/assets/assetLod.js +9 -2
  9. package/core/assets/assetManifest.js +12 -2
  10. package/core/assets/assetPart.js +54 -0
  11. package/core/assets/ik.js +271 -0
  12. package/core/assets/modelNeeds.js +37 -0
  13. package/core/assets/namedModel.js +102 -29
  14. package/core/assets/nodeVisibility.js +15 -0
  15. package/core/audio/Audio.js +36 -4
  16. package/core/audio/audioReverb.js +99 -0
  17. package/core/audio/audioRules.js +1 -1
  18. package/core/audio/audioVoice.js +1 -1
  19. package/core/base/Events.js +14 -4
  20. package/core/base/Random.js +1 -1
  21. package/core/base/Vars.js +1 -1
  22. package/core/base/docRef.js +51 -0
  23. package/core/base/errorCodes.js +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 +139 -142
  104. package/docs/CONVENTIONS.md +37 -49
  105. package/docs/MIGRATING-0.8.md +2 -2
  106. package/docs/MIGRATING-1.0.md +2 -2
  107. package/docs/THREE.md +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/characters.md +10 -8
  112. package/docs/api/collision.md +6 -4
  113. package/docs/api/engine.md +16 -16
  114. package/docs/api/events.md +3 -2
  115. package/docs/api/ground.md +6 -5
  116. package/docs/api/hud.md +4 -2
  117. package/docs/api/input.md +5 -5
  118. package/docs/api/particles.md +2 -1
  119. package/docs/api/photo.md +3 -0
  120. package/docs/api/post.md +7 -4
  121. package/docs/api/quests.md +2 -2
  122. package/docs/api/rays.md +1 -2
  123. package/docs/api/saves.md +7 -7
  124. package/docs/api/settings.md +2 -2
  125. package/docs/api/tools.md +3 -1
  126. package/docs/api/vars.md +1 -1
  127. package/docs/api/vegetation.md +4 -2
  128. package/docs/api/world.md +1 -1
  129. package/docs/recipes/01-new-game.md +16 -17
  130. package/docs/recipes/02-npc.md +22 -18
  131. package/docs/recipes/03-items-pickups.md +37 -35
  132. package/docs/recipes/04-quests.md +15 -10
  133. package/docs/recipes/05-props-bake.md +101 -95
  134. package/docs/recipes/06-clock-events.md +28 -28
  135. package/docs/recipes/07-flow-scenes-pause.md +29 -26
  136. package/docs/recipes/08-weather-sky.md +52 -64
  137. package/docs/recipes/09-materials-lights-models.md +26 -17
  138. package/docs/recipes/10-blender-level.md +15 -10
  139. package/docs/recipes/11-vehicles.md +12 -7
  140. package/docs/recipes/12-navmesh.md +44 -26
  141. package/docs/recipes/13-animation.md +56 -45
  142. package/docs/recipes/14-custom-module.md +21 -18
  143. package/docs/recipes/15-perf.md +61 -55
  144. package/docs/recipes/16-dev-bridge.md +23 -33
  145. package/docs/recipes/18-world.md +36 -42
  146. package/docs/recipes/19-shooting-picking.md +20 -15
  147. package/docs/recipes/20-content-actions-save.md +48 -56
  148. package/docs/recipes/21-camera.md +45 -54
  149. package/docs/recipes/22-shop-gold.md +12 -7
  150. package/docs/recipes/23-ops.md +25 -23
  151. package/docs/recipes/26-ui-parts.md +67 -47
  152. package/docs/recipes/27-net.md +12 -7
  153. package/docs/recipes/28-terrain.md +24 -21
  154. package/docs/recipes/29-grid.md +32 -27
  155. package/docs/recipes/30-templates.md +21 -20
  156. package/docs/recipes/31-audio.md +39 -22
  157. package/docs/recipes/32-action-game.md +19 -14
  158. package/docs/recipes/33-stream-sources.md +15 -11
  159. package/docs/recipes/34-environment-lighting.md +126 -70
  160. package/docs/recipes/35-picture-from-reference.md +8 -8
  161. package/docs/recipes/36-ground-plants.md +27 -21
  162. package/docs/recipes/40-scene.md +19 -28
  163. package/docs/recipes/43-shader-patches-surfaces.md +15 -12
  164. package/docs/recipes/44-water-weather-hooks.md +34 -31
  165. package/docs/recipes/45-cascaded-shadows.md +35 -26
  166. package/docs/recipes/46-blender-art-route.md +6 -1
  167. package/docs/recipes/49-game-module-contract.md +13 -8
  168. package/docs/recipes/50-own-renderer.md +6 -2
  169. package/docs/recipes/51-capability-catalog.md +15 -8
  170. package/docs/recipes/52-around-the-picture.md +34 -32
  171. package/docs/recipes/53-ground-up-close.md +6 -1
  172. package/docs/recipes/55-mods-time-wrap.md +27 -19
  173. package/docs/recipes/56-webgpu-tsl.md +74 -43
  174. package/docs/recipes/57-control.md +18 -13
  175. package/docs/recipes/58-input.md +26 -16
  176. package/docs/recipes/59-depth-post-effects.md +8 -3
  177. package/docs/recipes/60-judge-the-picture.md +9 -8
  178. package/docs/recipes/61-deploy.md +5 -0
  179. package/docs/recipes/62-picture-code.md +70 -79
  180. package/docs/recipes/63-third-person-start.md +47 -45
  181. package/docs/recipes/64-particles.md +22 -10
  182. package/docs/recipes/65-swarm.md +18 -13
  183. package/docs/recipes/66-common-tasks.md +38 -35
  184. package/examples/action/GAMEMAP.md +2 -3
  185. package/examples/action/main.js +3 -3
  186. package/examples/action/picture/lights.js +3 -1
  187. package/examples/perf-island/GAMEMAP.md +3 -3
  188. package/examples/perf-island/picture/lights.js +2 -1
  189. package/examples/plain-picture/GAMEMAP.md +1 -1
  190. package/examples/rc2d/GAMEMAP.md +1 -1
  191. package/examples/styletest/GAMEMAP.md +2 -2
  192. package/examples/styletest/main.js +1 -1
  193. package/examples/techniques/interior-light/README.md +3 -3
  194. package/examples/techniques/interior-light/interiorLight.js +2 -4
  195. package/examples/techniques/interior-light/picture/lights.js +2 -1
  196. package/examples/techniques/modular-building/picture/lights.js +3 -1
  197. package/examples/techniques/outlines-and-rim/picture/lights.js +3 -1
  198. package/examples/techniques/procedural-animation/README.md +1 -1
  199. package/examples/techniques/procedural-animation/main.js +1 -1
  200. package/examples/webgpu-tsl/GAMEMAP.md +1 -1
  201. package/examples/world/GAMEMAP.md +2 -3
  202. package/examples/world/art/humanoid.js +1 -1
  203. package/examples/world/main.js +6 -3
  204. package/index.d.ts +2 -2
  205. package/llms.txt +101 -0
  206. package/modules/ambience/Ambience.js +21 -5
  207. package/modules/calendar/index.js +9 -5
  208. package/modules/calendar/schedule.js +23 -8
  209. package/modules/camera/FirstPersonCamera.js +3 -1
  210. package/modules/camera/FollowCamera.js +10 -5
  211. package/modules/camera/RtsCamera.js +4 -3
  212. package/modules/camera/common.js +70 -8
  213. package/modules/camera/contract.js +1 -1
  214. package/modules/characters/Character.js +16 -10
  215. package/modules/characters/NPC.js +31 -19
  216. package/modules/characters/assetModel.js +14 -9
  217. package/modules/characters/astar.js +6 -1
  218. package/modules/characters/contract.js +2 -2
  219. package/modules/characters/index.js +34 -22
  220. package/modules/characters/movers/manual.js +1 -1
  221. package/modules/characters/movers/rapier.js +17 -2
  222. package/modules/characters/movers/simple.js +1 -1
  223. package/modules/characters/movers/support.js +16 -7
  224. package/modules/characters/npcAvoid.js +2 -2
  225. package/modules/characters/npcSim.js +3 -2
  226. package/modules/characters/pathAsync.js +24 -8
  227. package/modules/characters/pathJob.js +1 -1
  228. package/modules/characters/player.js +10 -9
  229. package/modules/characters/playerStrings.js +5 -5
  230. package/modules/characters/proceduralRig.js +5 -5
  231. package/modules/characters/useModel.js +6 -0
  232. package/modules/characters/walkTo.js +1 -1
  233. package/modules/collision/Collision.js +29 -18
  234. package/modules/collision/grid.js +22 -4
  235. package/modules/content/index.js +3 -1
  236. package/modules/content/loader.js +1 -1
  237. package/modules/content/models.js +82 -33
  238. package/modules/content/props.js +2 -1
  239. package/modules/content/rules.js +11 -5
  240. package/modules/content/templates.js +3 -3
  241. package/modules/content/words.js +2 -2
  242. package/modules/debug/DebugPanel.js +9 -9
  243. package/modules/flow/index.js +9 -6
  244. package/modules/gameplay/Dialogue.js +34 -20
  245. package/modules/gameplay/Interactions.js +19 -15
  246. package/modules/gameplay/Inventory.js +9 -4
  247. package/modules/gameplay/Quests.js +12 -10
  248. package/modules/gameplay/pickups.js +23 -11
  249. package/modules/grid/index.js +1 -1
  250. package/modules/grid/preview.js +2 -2
  251. package/modules/grid/tiles.js +1 -1
  252. package/modules/hlod/index.js +4 -1
  253. package/modules/hud/index.js +47 -10
  254. package/modules/hud/parts.js +28 -9
  255. package/modules/level/geometry.js +8 -3
  256. package/modules/level/index.js +10 -5
  257. package/modules/level/load.js +4 -2
  258. package/modules/lights/sources.js +1 -1
  259. package/modules/music/Music.js +22 -4
  260. package/modules/nav/index.js +20 -10
  261. package/modules/particles/Particles.js +31 -14
  262. package/modules/particles/effect.js +20 -5
  263. package/modules/particles/lit.js +72 -0
  264. package/modules/photo/Photo.js +72 -28
  265. package/modules/photo/pathTrace.js +106 -0
  266. package/modules/rigid/RigidBodies.js +23 -14
  267. package/modules/rigid/Vehicles.js +3 -13
  268. package/modules/rigid/sync.js +2 -1
  269. package/modules/settings/Settings.js +52 -20
  270. package/modules/settings/apply.js +23 -9
  271. package/modules/settings/sections.js +39 -6
  272. package/modules/settings/strings.js +2 -0
  273. package/modules/settings/view.js +19 -3
  274. package/modules/sky/dome.js +15 -3
  275. package/modules/sky/environment.js +28 -12
  276. package/modules/sky/fog.js +1 -1
  277. package/modules/sky/frame.js +6 -1
  278. package/modules/sky/shader.js +4 -3
  279. package/modules/sky/skyModule.js +8 -4
  280. package/modules/swarm/Swarm.js +1 -1
  281. package/modules/terrain/ChunkManager.js +61 -15
  282. package/modules/terrain/chunkJob.js +2 -2
  283. package/modules/terrain/index.js +20 -5
  284. package/modules/terrain/terrainEdit.js +8 -4
  285. package/modules/terrain/terrainTexture.js +4 -2
  286. package/modules/timeline/Timeline.js +4 -3
  287. package/modules/timeline/Tween.js +3 -0
  288. package/modules/timeline/letterbox.js +1 -0
  289. package/modules/triggers/index.js +36 -17
  290. package/modules/vegetation/Vegetation.js +81 -19
  291. package/modules/vegetation/densityMap.js +13 -8
  292. package/modules/vegetation/draw.js +147 -24
  293. package/modules/vegetation/groundChunks.js +20 -5
  294. package/modules/vegetation/index.js +3 -3
  295. package/modules/vegetation/modelGeometry.js +9 -4
  296. package/modules/water/Water.js +11 -8
  297. package/modules/weather/Weather.js +7 -2
  298. package/modules/weather/shaders.js +25 -5
  299. package/modules/weather/weatherDraw.js +20 -6
  300. package/modules/world/World.js +2 -1
  301. package/modules/world/index.js +2 -2
  302. package/modules/world/persist.js +6 -2
  303. package/modules/world/views.js +15 -2
  304. package/package.json +4 -1
  305. package/presets.js +5 -5
  306. package/render/PostFX.js +84 -41
  307. package/render/backend.js +137 -16
  308. package/render/cascades.js +3 -1
  309. package/render/cascades.tsl.js +2 -0
  310. package/render/daylight.js +7 -1
  311. package/render/detail.js +7 -4
  312. package/render/effects.js +27 -8
  313. package/render/fogLook.js +24 -0
  314. package/render/fuse.js +5 -2
  315. package/render/fx/detail.tsl.js +9 -7
  316. package/render/fx/index.js +7 -2
  317. package/render/fx/library.tsl.js +1 -0
  318. package/render/fx/lightShaft.tsl.js +114 -0
  319. package/render/fx/noise.tsl.js +25 -8
  320. package/render/fx/objectOrigin.tsl.js +39 -10
  321. package/render/fx/particles.tsl.js +23 -6
  322. package/render/fx/patchNodes.tsl.js +17 -12
  323. package/render/fx/pcss.tsl.js +51 -0
  324. package/render/fx/postWebGPU.tsl.js +89 -29
  325. package/render/fx/sky.tsl.js +3 -9
  326. package/render/fxNumbers.js +10 -4
  327. package/render/impostor.tsl.js +107 -0
  328. package/render/lighting.js +33 -1
  329. package/render/lightmap.js +42 -28
  330. package/render/lights.js +19 -3
  331. package/render/materials.js +6 -4
  332. package/render/mergeCommon.js +4 -1
  333. package/render/occlusion.js +14 -4
  334. package/render/patches.js +79 -41
  335. package/render/postRuns.js +32 -0
  336. package/render/postWebGL.js +97 -10
  337. package/render/probes.js +10 -14
  338. package/render/shaderErrors.js +2 -1
  339. package/render/shadowCache.tsl.js +33 -5
  340. package/render/shadows.js +42 -16
  341. package/render/slots.js +8 -5
  342. package/render/vertexInputs.js +52 -0
  343. package/types/core.d.ts +114 -46
  344. package/types/gameplay.d.ts +56 -23
  345. package/types/generated/core/audio/Audio.d.ts +27 -1
  346. package/types/generated/core/base/Random.d.ts +1 -1
  347. package/types/generated/core/input/Input.d.ts +6 -8
  348. package/types/generated/core/input/inputSeat.d.ts +1 -1
  349. package/types/generated/core/inspect/Budget.d.ts +26 -0
  350. package/types/generated/core/inspect/DebugOverrides.d.ts +0 -2
  351. package/types/generated/core/saves/Saves.d.ts +10 -7
  352. package/types/generated/core/saves/session.d.ts +8 -2
  353. package/types/generated/core/scene/Rays.d.ts +1 -3
  354. package/types/generated/modules/particles/Particles.d.ts +1 -1
  355. package/types/generated/modules/world/World.d.ts +2 -1
  356. package/types/generated/render/PostFX.d.ts +35 -9
  357. package/types/physics.d.ts +796 -764
  358. package/types/pixel.d.ts +1 -1
  359. package/types/tsl.d.ts +62 -1
  360. package/types/world.d.ts +12 -3
  361. package/ui/Focus.js +7 -5
  362. package/ui/Parts.js +1 -1
  363. package/ui/touchPart.js +6 -3
package/render/PostFX.js CHANGED
@@ -13,10 +13,11 @@ import { webglPost } from './postWebGL.js';
13
13
  import { codedError } from '../core/base/errorHints.js';
14
14
  import { warnOnce } from '../core/base/validate.js';
15
15
  import { readParams, keysSchema } from '../core/base/params.js';
16
- import { isWebGPU, backendName, webgpuPart, ownMsaa } from './backend.js';
17
- import { MSAA_KEY } from '../core/scene/tier.js';
16
+ import { isWebGPU, webgpuPart, ownMsaa } from './backend.js';
17
+ import { MSAA_KEY, onTierChange } from '../core/scene/tier.js';
18
18
  import { defineOwned } from '../core/ops/owned.js';
19
19
  import { watchOwnFrame } from './ownFrame.js';
20
+ import { runsHere, OUTPUT_TWICE } from './postRuns.js';
20
21
  /** @import { Engine } from '../types/core' */
21
22
 
22
23
  /**
@@ -25,8 +26,12 @@ import { watchOwnFrame } from './ownFrame.js';
25
26
  * outline); tone: replaces the engine's tone-mapping output stage (one at a time: an own curve, a filmic grade; it receives linear HDR
26
27
  * color and must output display color, tone mapped AND converted to the output color space, as three's OutputPass / renderOutput do);
27
28
  * ldr: sRGB color after tone mapping (LUT, palette, grain, vignette); final: last of all (FXAA / SMAA).
28
- * @typedef {{ engine: Engine, scene: import('three').Scene, camera: import('three').Camera, width: number, height: number, params: Record<string, any> }} PostContext
29
- * width / height are in device pixels.
29
+ * @typedef {(renderer: any, draw: () => any, opts?: { scene?: import('three').Scene, camera?: import('three').Camera, clean?: boolean }) => any} BorrowRenderer
30
+ * @typedef {{ engine: Engine, scene: import('three').Scene, camera: import('three').Camera, width: number, height: number, params: Record<string, any>, borrowRenderer: BorrowRenderer }} PostContext
31
+ * width / height are in device pixels. borrowRenderer(renderer, draw, { scene, camera, clean }): run draw() with the renderer borrowed, the engine's one
32
+ * borrow (render/backend.js): target with cube face and mip, viewport, scissor, clear color, autoClear, tone mapping, shadowMap.autoUpdate (and with scene
33
+ * / camera their overrideMaterial, background, fog, layers) are put back afterwards, also when draw throws. For an effect that draws an extra pass of
34
+ * its own; its targets and materials stay the effect's. clean (WebGPU): start from three's reset state (no MRT), for a quad drawn inside a node frame.
30
35
  * @typedef {{ uniforms?: Record<string, string>, values?: (params: Record<string, any>) => Record<string, any>, glsl: string, reads?: boolean }} PostFuse
31
36
  * A GLSL snippet that colors the pixel; neighboring effects with a fuse run as ONE fullscreen pass. glsl is statements that edit
32
37
  * `vec4 color` (the input pixel so far) and may use vUv, tDiffuse, uTime (s), uResolution (device px) and fxHash(vec2). uniforms
@@ -37,16 +42,16 @@ import { watchOwnFrame } from './ownFrame.js';
37
42
  * p (a uniform node per number, boolean (0 / 1), color and vector param, live: set() changes .value, no rebuild), input (the image so far, sample it at other uvs with
38
43
  * t.input.sample(uv)), time (s), resolution (device px). Neighbors are chained into one node, so three draws them in one pass.
39
44
  * @typedef {{ engine: Engine, scene: import('three').Scene, camera: import('three').Camera, width: number, height: number, params: Record<string, any>,
40
- * scenePass: any, tsl: any, fx: Record<string, Function>, display: Record<string, Function>, p: Record<string, any> }} PostNodeContext
41
- * WebGPU only. scenePass: the scene's pass() node (.getTextureNode('depth'), getViewZNode() ...; .getTextureNode('normal' | 'diffuse' | 'velocity')
42
- * when an effect that is on says so in needsBuffers); tsl: three/tsl; display: three's display nodes (bloom, ao from three/addons/tsl/display) plus
45
+ * scenePass: any, buffer: (name: string) => any, tsl: any, fx: Record<string, Function>, display: Record<string, Function>, p: Record<string, any>, borrowRenderer: BorrowRenderer }} PostNodeContext
46
+ * WebGPU only. scenePass: the scene's pass() node (.getTextureNode('depth'), getViewZNode() ...); buffer(name): a needsBuffers output as a texture node
47
+ * ('normal' | 'diffuse' | 'velocity' | 'metalRough', the last as .x metalness, .y roughness: it may share velocity's target, so read it here, not from scenePass); tsl: three/tsl; display: three's display nodes (bloom, ao from three/addons/tsl/display) plus
43
48
  * pass (an extra scene render), texture (the color so far as a texture to sample at other uvs) and own (a node the effect made itself, disposed with the chain),
44
49
  * handed in so the main entry of an effect package never imports three/webgpu (its /tsl subpath may, a WebGL game never loads that) and so the nodes they make are disposed with the chain;
45
50
  * fx: the threedog/tsl functions (noise, hash ...), handed in for the same reason;
46
51
  * p: live uniform nodes of the number, boolean (0 / 1), color and vector params (as in PostFuse tsl), so set() of those never rebuilds the pipeline; a param read from
47
52
  * ctx.params while node() runs is a constant in the graph, so set() of it rebuilds the chain (as WebGL rebuilds an effect without update()).
48
53
  * @typedef {{ name: string, create?: (ctx: PostContext) => object, node?: (input: any, ctx: PostNodeContext) => any, fuse?: PostFuse, slot?: PostSlot | (string & {}), order?: number, enabled?: boolean,
49
- * needsDepth?: boolean, needsBuffers?: ('normal' | 'diffuse' | 'velocity')[], backend?: 'webgpu', skipOnLowTier?: boolean, facts?: () => Record<string, any> | null,
54
+ * needsDepth?: boolean, needsBuffers?: ('normal' | 'diffuse' | 'velocity' | 'metalRough')[], backend?: 'webgpu', skipOnLowTier?: boolean, cheaper?: Record<string, any>, facts?: () => Record<string, any> | null, about?: Record<string, any>,
50
55
  * params?: Record<string, any>, update?: (impl: any, params: Record<string, any>) => void }} PostEffect
51
56
  * An effect as data, the form post.add() takes. node (WebGPURenderer): returns the effect's output color node built on input (the color node so far); called again only when a param
52
57
  * that is not a number, boolean, color or vector changes (those are live in ctx.p). An effect with only create cannot run on WebGPURenderer (it throws by name).
@@ -62,11 +67,16 @@ import { watchOwnFrame } from './ownFrame.js';
62
67
  * RenderPixelatedPass, or the tone-mapping output); the chain throws when it would not. A pass that writes the scene depth into its own output (gl_FragDepth, then set pass.keepsDepth = true; dof does) does not count as a swap. update: apply new params in place;
63
68
  * without it set() rebuilds the implementation.
64
69
  * needsBuffers (WebGPU): extra outputs of the one scene render, merged across every effect that is on, so two effects never overwrite each other's setMRT:
65
- * 'normal' (view space, raw), 'diffuse' (surface color), 'velocity' (a temporal resolve follows, so the scene pass runs without MSAA).
70
+ * 'normal' (view space, raw), 'diffuse' (surface color), 'velocity' (a temporal resolve follows, so the scene pass runs without MSAA), 'metalRough' (metalness, roughness).
71
+ * More targets than the device takes (WebGPU's default: 32 bytes per pixel, four with the color) throws naming the effects.
66
72
  * backend: 'webgpu' = needs three's WebGPU backend itself (storage textures; WebGPURenderer on its WebGL2 backend cannot run it, so it is held there).
67
73
  * skipOnLowTier: the effect's own statement that engine.tier 'low' is too weak for it. The rule: an effect declares this itself and the engine only follows the declaration; no list of
68
74
  * expensive effects lives in the engine, and an effect that does not declare it runs on every tier. A held effect costs nothing, describe().render.post says why in `held`, the console says it once; the game's enabled stays as written.
75
+ * cheaper: the effect's own cheaper params ({ quality: 0.25 }), the first step adaptive quality takes under load before the resolution (core/scene/adaptive.js); only
76
+ * params that change in place belong here (live uniforms, or WebGL update()): a param that rebuilds the chain would cause the hitch the step is meant to cure. A declared
77
+ * skipOnLowTier is the ladder's last step: the effect held off. Neither is a list in the engine; the game reorders or drops them with engine.adaptive.steps.
69
78
  * facts: read by describe().render.post (a voxel size, what the effect still misses).
79
+ * about: what the picture menu (engine.catalog('picture')) prints for it: { cost, on, recipe, limits, webgpuOnly?, acts? } (acts: 'glow' | 'exposure' | 'ao', what the combination checks, the settings rows and photo read in place of a name); @threedog/post-effects puts the same object on each factory as fn.about.
70
80
  * @typedef {{ readonly name: string, readonly slot: PostSlot, readonly order: number, enabled: boolean, readonly params: Record<string, any>,
71
81
  * set(params: Record<string, any>): void, remove(): void }} PostHandle
72
82
  * What add() and get() return. enabled reads what runs now; writing it is the game's choice on the shared point post.<name>.enabled, so a settings
@@ -109,8 +119,10 @@ export class PostFX {
109
119
  // own(): the game takes the built chain (composer passes / pipeline.outputNode) and the engine stops rebuilding it; handing it
110
120
  // back rebuilds from the list. read is a constant: a direct write to object() is not a takeover (the next chain change replaces it)
111
121
  /** @internal */ this._own = defineOwned(engine, { id: 'post.chain', part: 'post', key: 'chain', read: () => 0,
112
- levels: { manual: 'engine.post.own()' }, onChange: o => { if (!o.on) return; if (this._pipe) this._pipe.key = null; this._sync(); } });
122
+ // handed back: the kept WebGPU stages go too, the game may have edited those nodes while it owned them, so the declared chain is rebuilt whole
123
+ levels: { manual: 'engine.post.own()' }, onChange: o => { if (!o.on) return; if (this._pipe) { this._pipe.key = null; this._pipe.stages = []; } this._sync(); } });
113
124
  this._sync();
125
+ onTierChange(engine, () => this._sync()); // effects held by tier (skipOnLowTier) follow it; after the first sync, so a throw there leaves no listener
114
126
  }
115
127
 
116
128
  /**
@@ -122,6 +134,7 @@ export class PostFX {
122
134
  */
123
135
  get antialias() { return this._aa; }
124
136
  set antialias(on) {
137
+ if (!!on === this._aa) return; // a game writing its settings each frame writes the same value: nothing to rebuild (GPT review l2-render 4)
125
138
  this._aa = !!on;
126
139
  this._be.setAntialias(this, this._aa);
127
140
  this._sync();
@@ -165,8 +178,8 @@ export class PostFX {
165
178
 
166
179
  /**
167
180
  * The one way to add a post effect. x is a three.js Pass (WebGL), a TSL node function (input, ctx) => node (WebGPU), or an effect
168
- * { name, create | node | fuse, slot, order, params, needsDepth, needsBuffers, backend, skipOnLowTier, facts } (both renderers when it gives create and node, or a fuse). A wrong shape throws with nothing added.
169
- * needsDepth, needsBuffers ('normal' | 'diffuse' | 'velocity', WebGPU), backend ('webgpu': not on the WebGL2 backend), skipOnLowTier (held when engine.tier is 'low') and facts (shown by describe().render.post) are explained on PostEffect.
181
+ * { name, create | node | fuse, slot, order, params, needsDepth, needsBuffers, backend, skipOnLowTier, cheaper, facts } (both renderers when it gives create and node, or a fuse). A wrong shape throws with nothing added.
182
+ * needsDepth, needsBuffers ('normal' | 'diffuse' | 'velocity' | 'metalRough', WebGPU), backend ('webgpu': not on the WebGL2 backend), skipOnLowTier (held when engine.tier is 'low') and facts (shown by describe().render.post) are explained on PostEffect.
170
183
  * A Pass that draws engine.scene takes the 'scene' slot, FXAA / SMAA / TAA 'final', any other 'hdr' after the effects already there, or 'ldr' once an
171
184
  * OutputPass was added. A RenderPass of engine.scene and an OutputPass are the engine's own stages: skipped and said once (an OutputPass still marks where display color starts).
172
185
  * @example const glow = engine.post.add(new UnrealBloomPass(size, 0.6, 0.4, 0.85), { name: 'glow' }); glow.enabled = false;
@@ -196,6 +209,9 @@ export class PostFX {
196
209
  if (effect.fuse && s === 'scene') throw codedError('post-effect', `post effect '${effect.name}': a fuse snippet colors an existing image, it cannot replace the scene render; use slot 'hdr' | 'ldr' | 'final'`);
197
210
  const other = s in EXCLUSIVE && this._list.find(e => e.slot === s);
198
211
  if (other) throw codedError('post-effect', `post slot '${s}' already holds '${other.name}'; remove it first (only one effect can ${EXCLUSIVE[s]})`);
212
+ const odd = Object.keys(effect.cheaper ?? {}).filter(k => !(k in (effect.params ?? {})));
213
+ if (odd.length) throw codedError('post-effect', `post effect '${effect.name}': cheaper names ${odd.join(', ')}, not in its params (${Object.keys(effect.params ?? {}).join(', ') || 'none'}); cheaper holds lower values of its own params`);
214
+ finiteParams(effect.name, effect.params, 'params');
199
215
  const post = this, point = this.switchPoint(`post.${effect.name}.enabled`);
200
216
  point.release('game'); point.base = effect.enabled ?? true; // only the game's own word starts over: the player's off and any other owner's hold stay on the effect that comes back
201
217
  let on = !!point.value();
@@ -214,27 +230,34 @@ export class PostFX {
214
230
  if (h._removed) return;
215
231
  const unknown = Object.keys(p ?? {}).filter(k => !(k in h.params));
216
232
  if (!p || typeof p !== 'object' || unknown.length) throw codedError('post-effect', `post effect '${h.name}': set(params) takes ${Object.keys(h.params).join(', ') || 'nothing, it has no params'}; unknown: ${unknown.join(', ') || JSON.stringify(p)}${unknown.includes('enabled') ? ' (on / off: handle.enabled = false)' : ''}`);
233
+ finiteParams(h.name, p, 'set(params)');
217
234
  const changed = Object.fromEntries(Object.entries(p).filter(([k, v]) => h.params[k] !== v));
218
235
  if (!Object.keys(changed).length) return;
219
236
  const was = Object.fromEntries(Object.keys(changed).map(k => [k, h.params[k]]));
220
- try { h._apply(changed); } catch (err) { h._apply(was); throw err; }
237
+ // through the one gate: an update() in place may change the pass's needsSwap, a rebuilt pass is probed; a refusal puts the old params back
238
+ let rebuild = false;
239
+ post._change(() => { rebuild = h._apply(changed); }, () => { h._apply(was); }, () => rebuild);
221
240
  },
241
+ /** New params on the built part; true when the pass was dropped to be built again (the caller's sync builds it, after the order check) */
222
242
  _apply(p) {
223
243
  Object.assign(h.params, p);
224
- if (post._be.set?.(post, h, p)) return; // WebGPU: live uniforms, or a rebuild of the node graph
225
- if (effect.fuse) { post._be.refresh(post, h); return; }
226
- if (!h._impl) return;
227
- if (effect.update) effect.update(h._impl, h.params); else { freeImpl(h); post._sync(); }
244
+ h._swaps = undefined; // the order rule's probe of a pass never built yet was made from the old params
245
+ if (post._be.set?.(post, h, p)) return false; // WebGPU: live uniforms, or a rebuild of the node graph
246
+ if (effect.fuse) { post._be.refresh(post, h); return false; }
247
+ if (!h._impl) return false;
248
+ if (effect.update) { effect.update(h._impl, h.params); return false; }
249
+ freeImpl(h); return true;
228
250
  },
229
251
  remove() {
230
252
  if (h._removed) return;
231
253
  h._removed = true;
232
254
  point.onChange = null; point.release('game');
233
- freeImpl(h);
234
- post._list = post._list.filter(e => e !== h);
235
- if (!post._kept.has(h.name)) post._seq.delete(h.name); // removed for good: a later effect of that name starts at the end (plugins keep theirs)
236
- const i = post._plain.indexOf(h._entry); if (i >= 0) post._plain.splice(i, 1);
237
- post._sync();
255
+ post._change(() => {
256
+ freeImpl(h);
257
+ post._list = post._list.filter(e => e !== h);
258
+ if (!post._kept.has(h.name)) post._seq.delete(h.name); // removed for good: a later effect of that name starts at the end (plugins keep theirs)
259
+ const i = post._plain.indexOf(h._entry); if (i >= 0) post._plain.splice(i, 1);
260
+ }, () => {}); // a removal cannot break depth order: nothing to put back
238
261
  },
239
262
  };
240
263
  // a settings restriction or a hold ending turns it on or off here; a rebuild that throws leaves it as it was
@@ -243,6 +266,7 @@ export class PostFX {
243
266
  try { this._change(() => this._list.push(h), () => { freeImpl(h); this._list = this._list.filter(e => e !== h); }); }
244
267
  catch (err) { point.onChange = null; if (!this._kept.has(h.name)) this._seq.delete(h.name); throw err; }
245
268
  this.engine._picture?.added('post effect', h, h.name); // dev: a picture part removed with this still on is reported (core/inspect/pictureWriters.js)
269
+ this.engine.events.emit('post:add', h.name); // the settings rows follow an effect by its role, so one added after them still gets the player's choice
246
270
  return h;
247
271
  }
248
272
  /**
@@ -252,17 +276,10 @@ export class PostFX {
252
276
  */
253
277
  _held(h) {
254
278
  if (!h._on()) return null;
255
- const d = h._def, r = this.engine.renderer;
256
- let why = null;
257
- if (!isWebGPU(r) && !d.create && !d.fuse?.glsl) {
258
- if (!this._fellBack) return null; // before the tier: the mistake must show on every machine, not only on good ones
259
- why = 'this device has no WebGPU (start() fell back to WebGLRenderer)';
260
- } else if (d.backend === 'webgpu' && isWebGPU(r) && backendName(r) !== 'webgpu') why = r.backend?.parameters?.forceWebGL
261
- ? "needs three's WebGPU backend; the game chose WebGL2 (forceWebGL: true)"
262
- : "needs three's WebGPU backend; this device has none, so WebGPURenderer runs on its WebGL2 fallback";
263
- else if (d.skipOnLowTier && this.engine.tier === 'low') why = "engine.tier is 'low' and the effect declares skipOnLowTier";
264
- if (why) warnOnce(`post effect '${h.name}' held off: ${why}`);
265
- return why;
279
+ const w = runsHere(h._def, this.engine);
280
+ if (!w?.held) return null; // a mistake (node-only effect on the game's WebGLRenderer) is not held: postWebGL's sync throws it by name
281
+ warnOnce(`post effect '${h.name}' held off: ${w.why}`);
282
+ return w.why;
266
283
  }
267
284
  /**
268
285
  * What antialiases the picture now: the samples really in effect, and the effect standing in for MSAA (asking for 'velocity' means a temporal resolve, so the scene pass runs without samples).
@@ -285,9 +302,18 @@ export class PostFX {
285
302
  * @example engine.post.get('bloom').set({ strength: 0.6 });
286
303
  * @param {string} name
287
304
  * @returns {PostHandle | undefined}
288
- * @experimental
289
305
  */
290
306
  get(name) { return this._list.find(e => e.name === name); }
307
+ /**
308
+ * The added effects that declare this role in about.acts ('glow', 'ao', 'exposure'): found by what they do, never by name; the settings rows and
309
+ * photo follow every one of them. Only when NO effect declares the role does the effect named `name` stand in (a game's own 'bloom' written before
310
+ * roles existed); with no `name` that case gives [].
311
+ * @param {string} role
312
+ * @param {string} [name] fallback effect name
313
+ * @returns {PostHandle[]}
314
+ * @experimental
315
+ */
316
+ byRole(role, name) { const by = this._list.filter(h => h._def?.about?.acts === role); return by.length || !name ? by : this._list.filter(h => h.name === name); }
291
317
  /**
292
318
  * Hand the built chain to the game: the engine stops rebuilding it, so the composer's passes (post.object().passes) or the WebGPU pipeline's
293
319
  * outputNode are the game's to edit. own(false) gives it back and rebuilds from the list. describe().owned shows who has it.
@@ -300,7 +326,6 @@ export class PostFX {
300
326
  /**
301
327
  * Effects in render order: [{ name, slot, order, enabled }]
302
328
  * @returns {{ name: string, slot: PostSlot, order: number, enabled: boolean }[]}
303
- * @experimental
304
329
  */
305
330
  list() { return this._sorted().map(({ name, slot, order, enabled }) => ({ name, slot, order, enabled })); }
306
331
 
@@ -311,9 +336,15 @@ export class PostFX {
311
336
  /** @internal */
312
337
  _size() { return this.engine.renderer.getSize(new THREE.Vector2()).multiplyScalar(this.engine.renderer.getPixelRatio()); }
313
338
  /** Apply a list change, rebuild the chain, and undo the change when the rebuild throws (then rethrow) @internal */
314
- _change(apply, undo) {
315
- apply();
316
- try { this._sync(); } catch (err) { undo(); this._sync(); throw err; }
339
+ /**
340
+ * The one gate for every change to the effect list or to a pass's swap / depth behaviour (add, remove, on / off, a slot move, set): apply, then the
341
+ * depth-order rule over the candidate chain (always, also while the game owns the chain or nothing is built), then the rebuild. A refusal undoes
342
+ * before anything is built; apply is inside the same try, so a throw from apply itself (an effect's update() half-done) is undone too. rebuild() says
343
+ * whether this change needs the chain built again (a set() through update() in place does not).
344
+ * @param {() => void} apply @param {() => void} undo @param {() => boolean} [rebuild]
345
+ */
346
+ _change(apply, undo, rebuild = () => true) {
347
+ try { apply(); this._be.checkOrder?.(this); if (rebuild()) this._sync(); } catch (err) { undo(); this._sync(); throw err; }
317
348
  }
318
349
  // Rebuild the chain from the list (the backend does it)
319
350
  /** @internal */
@@ -389,6 +420,16 @@ export class PostFX {
389
420
  * _impl is the engine's record of the nodes it built (bloom's mip targets), and skipping it leaked them on every off / on
390
421
  * @param {any} h
391
422
  */
423
+ /**
424
+ * Both ways a param value comes in (the effect's params at add, handle.set later) go through here: NaN or Infinity in a uniform turns the whole frame
425
+ * black or white with no word, so it is refused by name. A finite value stays the game's, negative and huge included: no clamp (a negative vignette brightens).
426
+ * @param {string} name @param {Record<string, any> | undefined} p @param {string} where
427
+ */
428
+ function finiteParams(name, p, where) {
429
+ const bad = Object.entries(p ?? {}).filter(([, v]) => typeof v === 'number' && !Number.isFinite(v));
430
+ if (bad.length) throw codedError('post-effect', `post effect '${name}': ${where} takes finite numbers; got ${bad.map(([k, v]) => `${k}: ${v}`).join(', ')}`);
431
+ }
432
+
392
433
  function freeImpl(h) {
393
434
  if (h._impl !== h._def._pass) h._impl?.dispose?.();
394
435
  h._impl = null;
@@ -404,13 +445,13 @@ const skipped = remove => /** @type {any} */ ({ name: null, enabled: false, set(
404
445
 
405
446
  /** hdr or ldr for each plain pass by its place among the game's OutputPass markers, as in the game's hand-built composer */
406
447
  function reslot(post) {
407
- let after = false, changed = false;
448
+ let after = false; const moved = [];
408
449
  for (const e of post._plain) {
409
450
  if (e.output) { after = true; continue; }
410
451
  const h = post._list.find(x => x._def === e.def), s = after ? 'ldr' : 'hdr';
411
- if (h && h.slot !== s) { h.slot = s; changed = true; }
452
+ if (h && h.slot !== s) moved.push([h, h.slot, s]);
412
453
  }
413
- if (changed) post._sync();
454
+ if (moved.length) post._change(() => { for (const [h, , s] of moved) h.slot = s; }, () => { for (const [h, was] of moved) h.slot = was; });
414
455
  }
415
456
 
416
457
  /** A three.js Pass that draws the scene itself (RenderPixelatedPass, SSAARenderPass, TAARenderPass, a RenderPass): it replaces the scene render */
@@ -441,6 +482,8 @@ function effectOf(post, x, { name, slot, order }) {
441
482
  }
442
483
  // a readable name that survives minified class names: the pass's own name, else a ShaderPass's shader name (CopyShader, FXAAShader)
443
484
  const mn = x.material?.name, cls = (typeof x.name === 'string' && x.name) || (mn && mn !== 'unspecified' ? mn : 'pass'), n = next();
485
+ // a known display-conversion shader (three's GammaCorrectionShader / OutputShader as a ShaderPass) is encoded a second time by the engine's output stage
486
+ if (/^(GammaCorrection|Output)Shader$/.test(mn ?? '') && slot !== 'tone') warnOnce(OUTPUT_TWICE(cls));
444
487
  const s = drawsScene(eng, x) ? 'scene' : /FXAA|SMAA|TAA/i.test(cls) || x._edgesRT ? 'final' : post._plain.some(e => e.output) ? 'ldr' : 'hdr';
445
488
  // _pass: the game's own object, not disposed when the effect is removed (three's removePass habit; remove() in _add).
446
489
  // _auto: hdr / ldr follows where the game's OutputPass sits (reslot above), unless the game named the slot
package/render/backend.js CHANGED
@@ -3,11 +3,15 @@
3
3
  // read directly in every caller, each one would need its own WebGPU branch and the next renderer change would miss some of them.
4
4
  // Plain three.js equivalent: renderer.info.render / .memory / .programs, renderer.shadowMap.autoUpdate / needsUpdate (WebGL) or
5
5
  // light.shadow.autoUpdate / needsUpdate (WebGPU), WEBGL_debug_renderer_info (WebGL) or GPUDevice.adapterInfo (WebGPU).
6
- // Imports nothing from three (only engine files that do not either): threedog/tsl (render/fx) registers the WebGPU classes here, so WebGL games never load three/webgpu.
6
+ // Imports nothing from three at all, and only engine files that do not either: threedog/tsl (render/fx) registers the WebGPU classes here, so
7
+ // WebGL games never load three/webgpu; and threedog/tsl reaches this file, so importing 'three' here would load WebGLRenderer into it.
8
+ // The two math classes the renderer borrow needs are handed in by the engine core (mathClasses).
7
9
 
8
10
  import { codedError } from '../core/base/errorHints.js';
11
+ import { warnOnce } from '../core/base/validate.js';
9
12
  import { notePatch, patchOn } from '../core/scene/threePatches.js';
10
13
  import { isShown } from '../core/base/util.js';
14
+ import { checkVertexInputs } from './vertexInputs.js';
11
15
 
12
16
  /** Samples of the MSAA the post chain's targets use, on both renderers */
13
17
  export const MSAA_SAMPLES = 4;
@@ -32,6 +36,13 @@ export function stats(r) {
32
36
  geometries: i.memory.geometries, textures: i.memory.textures };
33
37
  }
34
38
 
39
+ /**
40
+ * Whether r has drawn at least once. Why here: WebGLRenderer counts frames in info.render.frame; WebGPURenderer has no such field (its
41
+ * info.frame is the node frame, which three's own tick moves before anything is drawn) and counts render() calls since start in info.render.calls
42
+ * @param {any} r @returns {boolean}
43
+ */
44
+ export const drawnAFrame = r => (isWebGPU(r) ? r.info.render.calls : r.info.render.frame) > 0;
45
+
35
46
  /** Compiled shader programs (WebGLRenderer keeps the list), or null where the renderer keeps none (WebGPU) @param {any} r @returns {number | null} */
36
47
  export const programCount = r => isWebGPU(r) ? null : r.info.programs?.length ?? null;
37
48
 
@@ -43,19 +54,26 @@ export const programList = r => isWebGPU(r) ? [] : r.info.programs ?? [];
43
54
  // last render object built per material is kept (weakly: the material's lifetime) and its NodeBuilderState read on demand.
44
55
  // RECENT: the last builds in order, also weak, so a compile error (which three reports without its render object) can be matched back to one.
45
56
  const NODE_PROGRAMS = new WeakMap(), RECENT = [], RECENT_MAX = 256;
46
- notePatch('node-builder-hook', "renderer.debug.onNodeBuilderCreated of a WebGPURenderer: remembers the render object built per material, a game's own hook still runs (render/backend.js)", () => {},
47
- { scope: 'engine renderer', lost: 'on WebGPU: shader errors no longer name the material, and shaderCost and the program costs in inspect.perf stay empty' });
57
+ notePatch('node-builder-hook', "renderer.debug.onNodeBuilderCreated of a WebGPURenderer: remembers the render object built per material and counts each program's vertex inputs " +
58
+ "before its code is written (that builder's buildCode), a game's own hook still runs (render/backend.js)", () => {},
59
+ { scope: 'engine renderer', lost: "on WebGPU: shader errors no longer name the material, shaderCost and the program costs in inspect.perf stay empty, and a program over the device's vertex inputs fails with three's raw pipeline error" });
48
60
  /** @internal core/engine/Engine.js: on WebGPURenderer, remember the render object three builds per material (a game's own hook still runs) @param {any} r */
49
61
  export function watchNodePrograms(r) {
50
62
  const d = r?.debug;
51
63
  if (!isWebGPU(r) || !d || d._threedogPrograms) return;
52
64
  const prev = d.onNodeBuilderCreated;
53
65
  d.onNodeBuilderCreated = (builder, ro) => {
54
- if (ro?.material && patchOn('node-builder-hook')) { NODE_PROGRAMS.set(ro.material, ro); RECENT.push(new WeakRef(ro)); if (RECENT.length > RECENT_MAX) RECENT.shift(); }
66
+ if (ro?.material && patchOn('node-builder-hook')) {
67
+ NODE_PROGRAMS.set(ro.material, ro); RECENT.push(new WeakRef(ro)); if (RECENT.length > RECENT_MAX) RECENT.shift();
68
+ const code = builder.buildCode;
69
+ // the material's own build only: three's plain stand-in after a failed build gets the same render object, and must not fail again
70
+ builder.buildCode = function () { if (this.material === ro.material) checkVertexInputs(this, r); return code.call(this); };
71
+ }
55
72
  prev?.(builder, ro);
56
73
  };
57
74
  d._threedogPrograms = true;
58
75
  }
76
+
59
77
  /**
60
78
  * @internal render/shaderErrors.js: the newest render object three built that passes test(renderObject), or null
61
79
  * @param {(ro: any) => boolean} test @returns {any}
@@ -89,6 +107,14 @@ export function memory(r) {
89
107
  return isWebGPU(r) ? { geometries: m.geometries, textures: m.textures } : { ...m };
90
108
  }
91
109
 
110
+ /** GPU memory in MB as three.js counts it (WebGPURenderer's info.memory.total: textures, buffers, programs it made; an estimate, not driver VRAM). null on
111
+ * WebGLRenderer, which keeps counts but no byte sizes @param {any} r @returns {number | null} */
112
+ export const GPU_MEMORY = "estimate: three's own count, not driver VRAM";
113
+ export const gpuMemoryMB = r => isWebGPU(r) ? Math.round(r.info.memory.total / 104857.6) / 10 : null;
114
+ /** Texture bytes as three.js counts them: WebGPURenderer's info.memory.texturesSize, every texture it uploaded (render targets and shadow maps too, which no material
115
+ * slot holds; TSL textures sit in nodes, not slots). null on WebGLRenderer, which counts textures but not their bytes @param {any} r @returns {number | null} */
116
+ export const countedTextureBytes = r => isWebGPU(r) ? r.info.memory.texturesSize ?? null : null;
117
+
92
118
  /** Start this frame's counters from zero (the engine renders with info.autoReset off: onRender targets count too) @param {any} r */
93
119
  export function resetStats(r) { r.info.reset(); }
94
120
 
@@ -237,7 +263,7 @@ function tierOf(name) {
237
263
  try {
238
264
  if (matchMedia('(pointer: coarse)').matches) return 'low';
239
265
  if (/intel|uhd|iris|mali|adreno|powervr|swiftshader|llvmpipe|software/i.test(name())) return 'low';
240
- } catch { /* cannot tell: assume high-end */ }
266
+ } catch (e) { warnOnce(`[backend] the device tier could not be detected (${e?.message ?? e}); assuming a high-end device`); } // said once: a wrong guess changes every tier-following default
241
267
  return 'high';
242
268
  }
243
269
  let probedName = /** @type {string | null} */ (null);
@@ -300,9 +326,102 @@ export function freshFrame(r) {
300
326
  */
301
327
  export function renderOnce(r, scene, camera, target = null) {
302
328
  freshFrame(r);
303
- const prev = r.getRenderTarget();
304
- r.setRenderTarget(target);
305
- try { r.render(scene, camera); } finally { r.setRenderTarget(prev); }
329
+ borrowRenderer(r, () => { r.setRenderTarget(target); r.render(scene, camera); });
330
+ }
331
+
332
+ // Borrowing the renderer (design.md 4.5): every engine task that changes renderer state to draw something of its own goes through these, so
333
+ // each one puts back the same fields, and puts them back when the draw throws. Before, five places each restored their own subset: one lost
334
+ // the cube face and mip level of the target it gave back, two skipped the restore on a throw, and the engine's next frame drew into the wrong target.
335
+ // The fields are written out below, not looped over a list: each one has its own getter / setter pair on three's renderers.
336
+ // What a task draws into (its own targets, materials, the layers of its own objects) stays the task's to make and free.
337
+ /** One saved state per nesting depth, reused: borrows run every frame (auto exposure, soft particles, onRender hooks), so the saved vectors are not made anew each time */
338
+ const held = [];
339
+ let depth = 0;
340
+ /** three's Vector4 and Color, handed in by core/engine/Engine.js (it imports 'three'; three/webgpu shares the same three.core.js classes) */
341
+ let M = /** @type {{ Vector4: any, Color: any } | null} */ (null), _cv = /** @type {any} */ (null);
342
+ /** @param {{ Vector4: any, Color: any }} classes */
343
+ export function mathClasses({ Vector4, Color }) { M = { Vector4, Color }; _cv = new Vector4(); }
344
+ /**
345
+ * Save the renderer state a borrow may change. Pair it with releaseRenderer(s, putBack) in a finally (borrowRenderer does both).
346
+ * Saved: the target with its cube face and mip level, viewport, scissor and scissor test, clear color and alpha, autoClear (and its color / depth /
347
+ * stencil parts), toneMapping and toneMappingExposure, shadowMap.autoUpdate; on WebGPURenderer also the MRT, the render-object function and the
348
+ * opaque / transparent switches and the viewport's minDepth / maxDepth. With scene: its overrideMaterial, background and fog (and WebGPU's backgroundNode and fogNode);
349
+ * with camera: its layers.mask.
350
+ * WebGLRenderer keeps two of each: what was set (getViewport, getScissor, getScissorTest) and what draws (getCurrentViewport and the GL scissor box / test,
351
+ * which a setViewport after binding a target changes and a later setRenderTarget overwrites with the target's own). Both are saved and both come back.
352
+ * clean: true (WebGPU) then sets what three's RendererUtils.resetRendererState sets (no MRT, no render-object function, clear 0x000000 / 1, every autoClear
353
+ * part on, opaque and transparent on), for a quad drawn inside a node frame that must not inherit the scene pass's MRT.
354
+ * @param {any} r @param {{ scene?: any, camera?: any, clean?: boolean }} [o] @returns {any}
355
+ */
356
+ export function holdRenderer(r, { scene = null, camera = null, clean = false } = {}) {
357
+ const V = /** @type {any} */ (M).Vector4; // null only when the engine core was never loaded: nothing can hand this file a renderer then
358
+ const s = held[depth] ??= { viewport: new V(), scissor: new V(), color: new (/** @type {any} */ (M).Color)(), current: new V(), box: new V() };
359
+ s.depth = depth++; s.r = r; s.scene = scene; s.camera = camera;
360
+ s.target = r.getRenderTarget(); s.face = r.getActiveCubeFace(); s.mip = r.getActiveMipmapLevel();
361
+ r.getViewport(s.viewport); r.getScissor(s.scissor); s.scissorTest = r.getScissorTest();
362
+ r.getClearColor(s.color); s.alpha = r.getClearAlpha();
363
+ s.autoClear = r.autoClear; s.autoColor = r.autoClearColor; s.autoDepth = r.autoClearDepth; s.autoStencil = r.autoClearStencil;
364
+ s.toneMapping = r.toneMapping; s.exposure = r.toneMappingExposure; s.shadowAuto = r.shadowMap.autoUpdate;
365
+ s.gpu = isWebGPU(r);
366
+ if (s.gpu) {
367
+ s.mrt = r.getMRT(); s.objectFn = r.getRenderObjectFunction(); s.opaque = r.opaque; s.transparent = r.transparent;
368
+ // Vector4.copy (getViewport) drops the depth range, and setViewport(vector) puts 0..1 back: read from the canvas target (no public getter)
369
+ const v = r.getCanvasTarget?.()._viewport; s.minDepth = v?.minDepth ?? 0; s.maxDepth = v?.maxDepth ?? 1;
370
+ } else {
371
+ r.getCurrentViewport(s.current);
372
+ const gl = r.getContext(), b = gl.getParameter(gl.SCISSOR_BOX); // three keeps the drawing scissor nowhere readable
373
+ if (b) s.box.set(b[0], b[1], b[2], b[3]); s.boxTest = gl.isEnabled(gl.SCISSOR_TEST); // b is null on a lost context
374
+ }
375
+ if (scene) { s.override = scene.overrideMaterial; s.background = scene.background; s.bgNode = scene.backgroundNode; s.fog = scene.fog; s.fogNode = scene.fogNode; }
376
+ if (camera) s.layers = camera.layers.mask;
377
+ if (clean) {
378
+ if (s.gpu) { r.setMRT(null); r.setRenderObjectFunction(null); r.opaque = r.transparent = true; }
379
+ r.setClearColor(0x000000, 1); r.autoClear = r.autoClearColor = r.autoClearDepth = r.autoClearStencil = true;
380
+ }
381
+ return s;
382
+ }
383
+ /**
384
+ * End a hold: putBack writes every saved field back; false only lets the slot go (an onRender hook that returned keeps what it left).
385
+ * Order on WebGLRenderer: the set values, then the target (which draws with its own viewport / scissor), then the drawing area as it was.
386
+ * @param {any} s @param {boolean} [putBack]
387
+ */
388
+ export function releaseRenderer(s, putBack = true) {
389
+ depth = s.depth;
390
+ const { r, scene, camera } = s;
391
+ if (putBack) putBackState(s, r, scene, camera);
392
+ s.r = s.scene = s.camera = s.target = s.mrt = s.objectFn = s.override = s.background = s.bgNode = s.fog = s.fogNode = null; // a slot keeps no scene alive between borrows
393
+ }
394
+ /**
395
+ * Run draw() with the renderer borrowed: whatever draw changes of the fields holdRenderer lists is put back afterwards, also when it throws.
396
+ * Returns what draw returns. Plain three.js equivalent: save each field, try { draw } finally { set each one back }.
397
+ * @template T @param {any} r @param {() => T} draw @param {{ scene?: any, camera?: any, clean?: boolean }} [o] @returns {T}
398
+ */
399
+ export function borrowRenderer(r, draw, o) {
400
+ const s = holdRenderer(r, o);
401
+ try { return draw(); } finally { releaseRenderer(s); }
402
+ }
403
+ /** @param {any} s @param {any} r @param {any} scene @param {any} camera */
404
+ function putBackState(s, r, scene, camera) {
405
+ if (scene) {
406
+ scene.overrideMaterial = s.override; scene.background = s.background; scene.fog = s.fog;
407
+ // only where it was changed: a WebGL scene gets no such property. fogNode is the fog WebGPURenderer draws (render/fogLook.js), so a pass that
408
+ // turned it off and threw would otherwise leave scene.fog back but the fog gone for good
409
+ if (scene.backgroundNode !== s.bgNode) scene.backgroundNode = s.bgNode;
410
+ if (scene.fogNode !== s.fogNode) scene.fogNode = s.fogNode;
411
+ }
412
+ if (camera) camera.layers.mask = s.layers;
413
+ r.toneMapping = s.toneMapping; r.toneMappingExposure = s.exposure; r.shadowMap.autoUpdate = s.shadowAuto;
414
+ r.setClearColor(s.color, s.alpha);
415
+ r.autoClear = s.autoClear; r.autoClearColor = s.autoColor; r.autoClearDepth = s.autoDepth; r.autoClearStencil = s.autoStencil;
416
+ if (s.gpu) { r.setMRT(s.mrt); r.setRenderObjectFunction(s.objectFn); r.opaque = s.opaque; r.transparent = s.transparent; }
417
+ const v = s.viewport;
418
+ r.setViewport(v.x, v.y, v.z, v.w, s.gpu ? s.minDepth : 0, s.gpu ? s.maxDepth : 1); r.setScissor(s.scissor); r.setScissorTest(s.scissorTest);
419
+ r.setRenderTarget(s.target, s.face, s.mip);
420
+ if (s.gpu) return; // WebGPURenderer draws a target with the target's own viewport: the set values above are all it keeps
421
+ // the drawing viewport differs from the target's own only when setViewport ran after the bind: running it again gives the same rounding;
422
+ // otherwise (an ArrayCamera's sub-viewport left mid-render) only the GL viewport can be put back
423
+ if (!r.getCurrentViewport(_cv).equals(s.current)) { r.setViewport(v); if (!r.getCurrentViewport(_cv).equals(s.current)) r.state.viewport(s.current); }
424
+ r.state.scissor(s.box); r.state.setScissorTest(s.boxTest); // three's GL state cache: no GL call when already equal
306
425
  }
307
426
 
308
427
  /**
@@ -318,7 +437,7 @@ export function renderOnce(r, scene, camera, target = null) {
318
437
  */
319
438
  export function compileThrough(r, draw) {
320
439
  const own = Object.hasOwn(r, 'render'), real = r.render, jobs = [];
321
- r.render = (scene, camera) => { jobs.push(r.compileAsync(scene, camera)); };
440
+ r.render = (scene, camera) => { const j = r.compileAsync(scene, camera); j.catch(() => {}); jobs.push(j); }; // handled at once: if a later pass throws, Promise.all below is never reached and a rejection would be unhandled
322
441
  let out;
323
442
  try { out = draw(); } finally { if (own) r.render = real; else delete r.render; }
324
443
  return Promise.all(jobs).then(() => out);
@@ -339,10 +458,9 @@ export async function readLayer(r, rt, w, h, layer) {
339
458
  for (let y = 0; y < h; y++) out.set(px.subarray(y * row, (y + 1) * row), (h - 1 - y) * row);
340
459
  return out;
341
460
  }
342
- const keep = r.getRenderTarget(), face = r.getActiveCubeFace(), mip = r.getActiveMipmapLevel(), px = new Float32Array(w * h * 4);
343
- r.setRenderTarget(rt, layer); // on WebGL the layer is chosen by what is attached, readRenderTargetPixels has no layer argument
344
- r.readRenderTargetPixels(rt, 0, 0, w, h, px);
345
- r.setRenderTarget(keep, face, mip);
461
+ const px = new Float32Array(w * h * 4);
462
+ // on WebGL the layer is chosen by what is attached, readRenderTargetPixels has no layer argument
463
+ borrowRenderer(r, () => { r.setRenderTarget(rt, layer); r.readRenderTargetPixels(rt, 0, 0, w, h, px); });
346
464
  return px;
347
465
  }
348
466
 
@@ -359,7 +477,7 @@ export const projectionKey = cam => (cam.isPerspectiveCamera ? `${cam.fov},${cam
359
477
  // a sixth part had nothing to copy. Now a .tsl.js file calls registerWebGPUPart(name, impl) once at load, and every user asks
360
478
  // webgpuPart(name, who): the same error code and the same fix line wherever threedog/tsl is missing.
361
479
  // Module scope, not a page global: the .tsl.js files import this file, so they always fill the table the engine copy using them reads.
362
- /** @typedef {'classes' | 'nodePatches' | 'particles' | 'post' | 'sky' | 'cascades' | 'shadowCache'} WebGPUPartName */
480
+ /** @typedef {'classes' | 'nodePatches' | 'particles' | 'post' | 'sky' | 'cascades' | 'shadowCache' | 'impostor'} WebGPUPartName */
363
481
  /** @type {Map<string, any>} */
364
482
  const PARTS = new Map();
365
483
  /**
@@ -406,12 +524,15 @@ export function rendererSwapped(engine) { for (const fn of [...(SWAP.get(engine)
406
524
  * the adapter is still asked each time, it costs no device. If the GPU goes bad later, three's own fallback still lands and _startRenderer says so.
407
525
  * @returns {Promise<string | null>}
408
526
  */
409
- export async function whyNoWebGPU() {
527
+ /** @param {Record<string, number>} [limits] three's requiredLimits of a renderer the engine made: filled before its init() requests the device @param {string} [powerPreference] */
528
+ export async function whyNoWebGPU(limits, powerPreference) {
410
529
  const gpu = typeof navigator === 'undefined' ? undefined : /** @type {any} */ (navigator).gpu;
411
530
  if (!gpu) return 'navigator.gpu is missing';
412
531
  let adapter;
413
- try { adapter = await gpu.requestAdapter({ featureLevel: 'compatibility' }); } catch (err) { return `requestAdapter() failed: ${err?.message ?? err}`; }
532
+ try { adapter = await gpu.requestAdapter({ featureLevel: 'compatibility', powerPreference }); } catch (err) { return `requestAdapter() failed: ${err?.message ?? err}`; }
414
533
  if (!adapter) return 'requestAdapter() returned no adapter';
534
+ // the post chain's merged scene targets (render/fx/postWebGPU.tsl.js) can pass WebGPU's default 32 bytes per pixel; asking what this adapter supports costs nothing and lifts it where the hardware can
535
+ if (limits) for (const k of ['maxColorAttachmentBytesPerSample', 'maxColorAttachments']) limits[k] ??= adapter.limits[k];
415
536
  if (deviceFrom === gpu) return null;
416
537
  try { (await adapter.requestDevice()).destroy?.(); } catch (err) { return `requestDevice() failed: ${err?.message ?? err}`; }
417
538
  deviceFrom = gpu;
@@ -27,6 +27,7 @@ import { patchMaterial, unpatchMaterial, isEngineMade } from './patches.js';
27
27
  import { warnOnce } from '../core/base/validate.js';
28
28
  import { sceneVisitor } from '../core/scene/sceneDelta.js';
29
29
  import { engineOwned } from '../core/scene/things.js';
30
+ import { drawOnly } from '../core/scene/drawOnly.js';
30
31
  import { codedError } from '../core/base/errorHints.js';
31
32
  import { setShadowUpdate, shadowUpdatePending, shadowsOn, isWebGPU, webgpuPart, projectionKey } from './backend.js';
32
33
 
@@ -74,7 +75,7 @@ class LightCSM extends CSM {
74
75
  this.parent = e.scene;
75
76
  this.lights[0].dispose();
76
77
  this.lights[0] = light;
77
- for (const l of this.lights) if (l !== light) { engineOwned('shadows', l, l.target); e.scene.add(l, l.target); }
78
+ for (const l of this.lights) if (l !== light) { engineOwned('shadows', l, l.target); drawOnly('', l); e.scene.add(l, l.target); } // copies of the sun: a scene copy keeps the sun alone
78
79
  // uniforms shared by every patched material: one write here reaches all of them
79
80
  this.uniforms = { CSM_cascades: { value: [] }, cameraNear: { value: 0 }, shadowFar: { value: 0 } };
80
81
  this.fade = S.fade;
@@ -185,6 +186,7 @@ export function createCascades(e, light, S, who) {
185
186
  const c = isWebGPU(e.renderer) ? webgpuPart('cascades', `[shadows] cascaded shadows (${who})`).create(e, light, S) : new LightCSM(e, light, S);
186
187
  c._box = box;
187
188
  c.shadowParams();
189
+ e.occlusion?.shadowLightsAdded(); // fresh shadow cameras: culling adds its layers to them now, or what it hides casts no shadow for a second
188
190
  return (e._cascades = c);
189
191
  }
190
192
 
@@ -36,6 +36,8 @@ class CascadeNode extends CSMShadowNode {
36
36
  // _init is the node's own first-build step (cascade stand-in lights, frustums); run it with the engine camera instead of builder.camera
37
37
  // (private to three, so not in @types/three)
38
38
  if (this.camera === null) /** @type {any} */ (this)._init({ camera: this._engine.camera, renderer: builder.renderer });
39
+ // the game's filter (pcss from threedog/tsl, or its own) reaches every cascade: three's LightShadow.copy, which made them, leaves filterNode out
40
+ for (const l of this.lights) l.shadow.filterNode = /** @type {any} */ (this.light).shadow.filterNode;
39
41
  return super.setup(builder);
40
42
  }
41
43
  /** @param {any} frame @returns {boolean} false would make three call it again this frame (NodeFrame) */
@@ -5,6 +5,7 @@
5
5
  // each lightPool source may pass its own `dusk`, and a game's own fade reads uDaylight with its own edge
6
6
  import { DEV, warnOnce } from '../core/base/validate.js';
7
7
  import { coded } from '../core/base/errorHints.js';
8
+ import { resetSignals } from './effects.js';
8
9
  export const DUSK = 0.3;
9
10
 
10
11
  /** Daylight 0..1 from the 'daylight' measure (engine.audio.measure): the calendar registers it (gameplay day / night), the sky only when no
@@ -36,9 +37,14 @@ const timeOfDayOf = e => { const t = e.audio?.measures.get('timeOfDay')?.(e); re
36
37
  export function writeDaylight(e) {
37
38
  const d = daylightOf(e), t = timeOfDayOf(e), w = e._daySignals ??= signalWatch(e, { uDaylight: "engine.audio.measure('daylight', () => value)", uTimeOfDay: "engine.audio.measure('timeOfDay', () => value)" });
38
39
  w.check();
39
- e.uniforms.uNight.value = nightOf(d, DUSK);
40
+ if (d !== null || !e._daySeen) e.uniforms.uNight.value = nightOf(d, DUSK); // a source seen and gone for one write: held with the others until the reset below moves all three
40
41
  if (d !== null) e.uniforms.uDaylight.value = d;
41
42
  if (t !== null) e.uniforms.uTimeOfDay.value = t;
43
+ // the last day / night source went (calendar and sky removed): all three go back to the neutral day together, or uNight 0 would sit beside a
44
+ // midnight uDaylight and two readers would see two times of day. Gone means no source at two writes in a row: the first write of a frame runs before
45
+ // the sky's frame hook has taken a removed calendar's measure over, so one null alone is a swap in progress, and a reset there would show noon for a frame.
46
+ // A game with no source from the start may write the signals itself: nothing is reset until a source has been seen
47
+ if (d !== null) { e._daySeen = true; e._dayGone = 0; } else if (e._daySeen && ++e._dayGone >= 2) { resetSignals(e, ['uNight', 'uDaylight', 'uTimeOfDay']); e._daySeen = false; }
42
48
  w.mark();
43
49
  }
44
50
 
package/render/detail.js CHANGED
@@ -7,7 +7,9 @@ import { isOptions } from '../core/base/util.js';
7
7
  import { placeholderTexture, hashText } from './effects.js';
8
8
  import { declareUniforms } from './uniformDecl.js';
9
9
  import { codedError } from '../core/base/errorHints.js';
10
- import { DETAIL as D, LUMA_601, glslFloat as f } from './fxNumbers.js';
10
+ import { DETAIL as D, LUMA_601, glslFloat as f, hashOffset } from './fxNumbers.js';
11
+ /** A dab salt (whole cells x, y) as the uvec2 added to a cell's first hash step @param {number} x @param {number} y */
12
+ const salt = (x, y) => `uvec2(${hashOffset(x)}u, ${hashOffset(y)}u)`;
11
13
 
12
14
  /**
13
15
  * @typedef {{ texture?: string | import('three').Texture, noise?: 'grain' | 'paper' | 'stroke' | 'dabs', glsl?: string, uniforms?: Record<string, any>,
@@ -35,9 +37,10 @@ float threedogDDabs(vec2 p, float octaves){ float s = 0.5, w = ${f(D.dabWeight)}
35
37
  for (int o = 0; o < 3; o++) { if (float(o) >= octaves) break;
36
38
  vec2 ip = floor(p); float fo = float(o);
37
39
  for (int j = -1; j <= 1; j++) for (int i = -1; i <= 1; i++) {
38
- vec2 c = ip + vec2(float(i), float(j));
39
- vec2 h = vec2(threedogHash(c + fo * 13.1), threedogHash(c.yx + 7.7 + fo * 5.3));
40
- float ang = 6.2832 * threedogHash(c * 1.7 + 3.1 + fo), r = 0.35 + 0.3 * threedogHash(c * 2.3 + 11.9 + fo), tone = threedogHash(c + vec2(5.5, 1.3) + fo);
40
+ // five hashes of whole cells k + salt (the hash takes cells, a fraction would be cut off); the salt is added to k's first step (effects.js)
41
+ vec2 c = ip + vec2(float(i), float(j)); highp uvec2 k = threedogHashCell(c + fo * 131.0);
42
+ vec2 h = vec2(threedogHashStep(k), threedogHashStep(k + ${salt(57, 113)}));
43
+ float ang = 6.2832 * threedogHashStep(k + ${salt(211, 37)}), r = 0.35 + 0.3 * threedogHashStep(k + ${salt(89, 271)}), tone = threedogHashStep(k + ${salt(163, 199)});
41
44
  vec2 d = p - (c + 0.15 + 0.7 * h); float ca = cos(ang), sa = sin(ang);
42
45
  d = vec2(ca * d.x + sa * d.y, -sa * d.x + ca * d.y) / vec2(r * 1.3, r * 0.75);
43
46
  s = mix(s, tone, (1.0 - smoothstep(0.3, 1.0, length(d))) * w); }