threedog 1.1.0 → 1.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (370) hide show
  1. package/CHANGELOG.md +893 -798
  2. package/README.md +1 -1
  3. package/core/assets/Animator.js +41 -3
  4. package/core/assets/Assets.js +100 -24
  5. package/core/assets/assetEntry.js +73 -20
  6. package/core/assets/assetHot.js +68 -16
  7. package/core/assets/assetLoad.js +6 -6
  8. package/core/assets/assetLod.js +9 -2
  9. package/core/assets/assetManifest.js +12 -2
  10. package/core/assets/assetPart.js +54 -0
  11. package/core/assets/ik.js +271 -0
  12. package/core/assets/modelNeeds.js +37 -0
  13. package/core/assets/namedModel.js +102 -29
  14. package/core/assets/nodeVisibility.js +15 -0
  15. package/core/audio/Audio.js +36 -4
  16. package/core/audio/audioReverb.js +99 -0
  17. package/core/audio/audioRules.js +1 -1
  18. package/core/audio/audioVoice.js +1 -1
  19. package/core/base/Events.js +14 -4
  20. package/core/base/Random.js +1 -1
  21. package/core/base/Vars.js +1 -1
  22. package/core/base/docRef.js +51 -0
  23. package/core/base/errorCodes.js +187 -126
  24. package/core/base/errorHints.js +9 -7
  25. package/core/base/errors.js +25 -10
  26. package/core/base/events.generated.js +2 -0
  27. package/core/base/freeParts.js +76 -0
  28. package/core/base/math.js +28 -0
  29. package/core/base/sections.js +5 -5
  30. package/core/base/validate.js +31 -3
  31. package/core/engine/Engine.js +17 -7
  32. package/core/engine/Loading.js +5 -3
  33. package/core/engine/copies.js +1 -1
  34. package/core/engine/headlessLoad.js +4 -1
  35. package/core/engine/lifecycle.js +32 -16
  36. package/core/engine/loop.js +71 -27
  37. package/core/engine/moduleSlots.js +2 -2
  38. package/core/engine/moduleTypes.js +3 -3
  39. package/core/engine/modules.js +65 -39
  40. package/core/engine/page.js +6 -3
  41. package/core/engine/services.js +6 -5
  42. package/core/engine/startup.js +8 -7
  43. package/core/input/Input.js +28 -14
  44. package/core/input/inputContext.js +28 -16
  45. package/core/input/inputKeyboard.js +31 -3
  46. package/core/input/inputPad.js +4 -0
  47. package/core/input/inputPointer.js +2 -1
  48. package/core/input/inputSeat.js +1 -1
  49. package/core/inspect/Budget.js +109 -19
  50. package/core/inspect/DebugOverrides.js +28 -4
  51. package/core/inspect/Describe.js +17 -9
  52. package/core/inspect/Inspect.js +4 -2
  53. package/core/inspect/InspectMaterials.js +3 -1
  54. package/core/inspect/InspectPerf.js +19 -9
  55. package/core/inspect/InspectScene.js +32 -7
  56. package/core/inspect/MaterialInfo.js +19 -2
  57. package/core/inspect/UrlState.js +50 -28
  58. package/core/inspect/catalog.js +28 -9
  59. package/core/inspect/debugView.js +2 -1
  60. package/core/inspect/describeRender.js +25 -13
  61. package/core/inspect/describeText.js +14 -6
  62. package/core/inspect/lightWatch.js +1 -1
  63. package/core/inspect/metadata.generated.js +35 -17
  64. package/core/inspect/pictureChecks.js +148 -0
  65. package/core/inspect/pictureMenu.js +84 -0
  66. package/core/inspect/pictureWriters.js +26 -6
  67. package/core/inspect/textureBytes.js +12 -2
  68. package/core/inspect/toolDoor.js +2 -4
  69. package/core/ops/Ops.js +11 -4
  70. package/core/ops/holds.js +27 -10
  71. package/core/ops/opsAtomic.js +15 -7
  72. package/core/ops/opsGuard.js +2 -2
  73. package/core/ops/opsRun.js +8 -7
  74. package/core/ops/sharedPoint.js +72 -21
  75. package/core/ops/stacks.js +56 -16
  76. package/core/saves/SaveStore.js +9 -3
  77. package/core/saves/Saves.js +32 -23
  78. package/core/saves/saveApply.js +96 -44
  79. package/core/saves/saveIds.js +1 -1
  80. package/core/saves/saveVersions.js +7 -5
  81. package/core/saves/session.js +17 -8
  82. package/core/saves/stateReplace.js +34 -15
  83. package/core/scene/Rays.js +52 -10
  84. package/core/scene/Views.js +36 -15
  85. package/core/scene/adaptive.js +144 -21
  86. package/core/scene/drawOnly.js +17 -0
  87. package/core/scene/gameLights.js +47 -4
  88. package/core/scene/sceneMethods.js +13 -11
  89. package/core/scene/stepPoses.js +11 -3
  90. package/core/scene/targeting.js +5 -3
  91. package/core/scene/thingOps.js +1 -1
  92. package/core/scene/tier.js +15 -0
  93. package/core/stream/Batching.js +30 -7
  94. package/core/stream/Stream.js +26 -7
  95. package/core/stream/batchGroups.js +2 -2
  96. package/core/stream/chunkStream.js +7 -5
  97. package/core/stream/prepare.js +77 -0
  98. package/core/time/skip.js +3 -1
  99. package/core/time/time.js +4 -2
  100. package/docs/AI.md +82 -83
  101. package/docs/API.md +16 -16
  102. package/docs/CODEMAP.md +17 -11
  103. package/docs/COMMANDS.md +139 -142
  104. package/docs/CONVENTIONS.md +37 -49
  105. package/docs/MIGRATING-0.8.md +2 -2
  106. package/docs/MIGRATING-1.0.md +2 -2
  107. package/docs/THREE.md +30 -35
  108. package/docs/api/assets.md +3 -1
  109. package/docs/api/audio.md +4 -2
  110. package/docs/api/budget.md +5 -0
  111. package/docs/api/characters.md +10 -8
  112. package/docs/api/collision.md +6 -4
  113. package/docs/api/engine.md +16 -16
  114. package/docs/api/events.md +3 -2
  115. package/docs/api/ground.md +6 -5
  116. package/docs/api/hud.md +4 -2
  117. package/docs/api/input.md +5 -5
  118. package/docs/api/particles.md +2 -1
  119. package/docs/api/photo.md +3 -0
  120. package/docs/api/post.md +7 -4
  121. package/docs/api/quests.md +2 -2
  122. package/docs/api/rays.md +1 -2
  123. package/docs/api/saves.md +7 -7
  124. package/docs/api/settings.md +2 -2
  125. package/docs/api/tools.md +3 -1
  126. package/docs/api/vars.md +1 -1
  127. package/docs/api/vegetation.md +4 -2
  128. package/docs/api/world.md +1 -1
  129. package/docs/recipes/01-new-game.md +16 -17
  130. package/docs/recipes/02-npc.md +22 -18
  131. package/docs/recipes/03-items-pickups.md +37 -35
  132. package/docs/recipes/04-quests.md +15 -10
  133. package/docs/recipes/05-props-bake.md +101 -95
  134. package/docs/recipes/06-clock-events.md +28 -28
  135. package/docs/recipes/07-flow-scenes-pause.md +29 -26
  136. package/docs/recipes/08-weather-sky.md +52 -64
  137. package/docs/recipes/09-materials-lights-models.md +26 -17
  138. package/docs/recipes/10-blender-level.md +15 -10
  139. package/docs/recipes/11-vehicles.md +12 -7
  140. package/docs/recipes/12-navmesh.md +44 -26
  141. package/docs/recipes/13-animation.md +56 -45
  142. package/docs/recipes/14-custom-module.md +21 -18
  143. package/docs/recipes/15-perf.md +61 -55
  144. package/docs/recipes/16-dev-bridge.md +24 -33
  145. package/docs/recipes/18-world.md +36 -42
  146. package/docs/recipes/19-shooting-picking.md +20 -15
  147. package/docs/recipes/20-content-actions-save.md +48 -56
  148. package/docs/recipes/21-camera.md +45 -54
  149. package/docs/recipes/22-shop-gold.md +12 -7
  150. package/docs/recipes/23-ops.md +25 -23
  151. package/docs/recipes/26-ui-parts.md +67 -47
  152. package/docs/recipes/27-net.md +12 -7
  153. package/docs/recipes/28-terrain.md +24 -21
  154. package/docs/recipes/29-grid.md +32 -27
  155. package/docs/recipes/30-templates.md +21 -20
  156. package/docs/recipes/31-audio.md +39 -22
  157. package/docs/recipes/32-action-game.md +19 -14
  158. package/docs/recipes/33-stream-sources.md +15 -11
  159. package/docs/recipes/34-environment-lighting.md +126 -70
  160. package/docs/recipes/35-picture-from-reference.md +8 -8
  161. package/docs/recipes/36-ground-plants.md +27 -21
  162. package/docs/recipes/40-scene.md +19 -28
  163. package/docs/recipes/43-shader-patches-surfaces.md +15 -12
  164. package/docs/recipes/44-water-weather-hooks.md +34 -31
  165. package/docs/recipes/45-cascaded-shadows.md +35 -26
  166. package/docs/recipes/46-blender-art-route.md +7 -2
  167. package/docs/recipes/49-game-module-contract.md +13 -8
  168. package/docs/recipes/50-own-renderer.md +6 -2
  169. package/docs/recipes/51-capability-catalog.md +15 -8
  170. package/docs/recipes/52-around-the-picture.md +34 -32
  171. package/docs/recipes/53-ground-up-close.md +6 -1
  172. package/docs/recipes/55-mods-time-wrap.md +27 -19
  173. package/docs/recipes/56-webgpu-tsl.md +75 -43
  174. package/docs/recipes/57-control.md +18 -13
  175. package/docs/recipes/58-input.md +26 -16
  176. package/docs/recipes/59-depth-post-effects.md +8 -3
  177. package/docs/recipes/60-judge-the-picture.md +10 -9
  178. package/docs/recipes/61-deploy.md +5 -0
  179. package/docs/recipes/62-picture-code.md +72 -79
  180. package/docs/recipes/63-third-person-start.md +48 -45
  181. package/docs/recipes/64-particles.md +22 -10
  182. package/docs/recipes/65-swarm.md +18 -13
  183. package/docs/recipes/66-common-tasks.md +38 -35
  184. package/examples/action/.threedog/content-index.json +1 -1
  185. package/examples/action/GAMEMAP.md +2 -3
  186. package/examples/action/main.js +3 -3
  187. package/examples/action/picture/lights.js +3 -1
  188. package/examples/perf-island/.threedog/content-index.json +1 -1
  189. package/examples/perf-island/GAMEMAP.md +3 -3
  190. package/examples/perf-island/picture/lights.js +2 -1
  191. package/examples/plain-picture/GAMEMAP.md +1 -1
  192. package/examples/rc2d/GAMEMAP.md +1 -1
  193. package/examples/styletest/.threedog/content-index.json +1 -1
  194. package/examples/styletest/GAMEMAP.md +2 -2
  195. package/examples/styletest/main.js +1 -1
  196. package/examples/techniques/interior-light/README.md +3 -3
  197. package/examples/techniques/interior-light/interiorLight.js +2 -4
  198. package/examples/techniques/interior-light/picture/lights.js +2 -1
  199. package/examples/techniques/modular-building/picture/lights.js +3 -1
  200. package/examples/techniques/outlines-and-rim/picture/lights.js +3 -1
  201. package/examples/techniques/procedural-animation/README.md +1 -1
  202. package/examples/techniques/procedural-animation/main.js +1 -1
  203. package/examples/webgpu-tsl/GAMEMAP.md +1 -1
  204. package/examples/world/.threedog/content-index.json +1 -1
  205. package/examples/world/GAMEMAP.md +2 -3
  206. package/examples/world/art/humanoid.js +1 -1
  207. package/examples/world/main.js +6 -3
  208. package/index.d.ts +2 -2
  209. package/llms.txt +101 -0
  210. package/modules/ambience/Ambience.js +21 -5
  211. package/modules/calendar/index.js +9 -5
  212. package/modules/calendar/schedule.js +23 -8
  213. package/modules/camera/FirstPersonCamera.js +3 -1
  214. package/modules/camera/FollowCamera.js +10 -5
  215. package/modules/camera/RtsCamera.js +4 -3
  216. package/modules/camera/common.js +70 -8
  217. package/modules/camera/contract.js +1 -1
  218. package/modules/characters/Character.js +16 -10
  219. package/modules/characters/NPC.js +31 -19
  220. package/modules/characters/assetModel.js +14 -9
  221. package/modules/characters/astar.js +6 -1
  222. package/modules/characters/contract.js +2 -2
  223. package/modules/characters/index.js +34 -22
  224. package/modules/characters/movers/manual.js +1 -1
  225. package/modules/characters/movers/rapier.js +17 -2
  226. package/modules/characters/movers/simple.js +1 -1
  227. package/modules/characters/movers/support.js +16 -7
  228. package/modules/characters/npcAvoid.js +2 -2
  229. package/modules/characters/npcSim.js +3 -2
  230. package/modules/characters/pathAsync.js +24 -8
  231. package/modules/characters/pathJob.js +1 -1
  232. package/modules/characters/player.js +10 -9
  233. package/modules/characters/playerStrings.js +5 -5
  234. package/modules/characters/proceduralRig.js +5 -5
  235. package/modules/characters/useModel.js +6 -0
  236. package/modules/characters/walkTo.js +1 -1
  237. package/modules/collision/Collision.js +29 -18
  238. package/modules/collision/grid.js +22 -4
  239. package/modules/content/index.js +3 -1
  240. package/modules/content/loader.js +1 -1
  241. package/modules/content/models.js +82 -33
  242. package/modules/content/props.js +2 -1
  243. package/modules/content/rules.js +11 -5
  244. package/modules/content/templates.js +3 -3
  245. package/modules/content/words.js +2 -2
  246. package/modules/debug/DebugPanel.js +9 -9
  247. package/modules/flow/index.js +9 -6
  248. package/modules/gameplay/Dialogue.js +34 -20
  249. package/modules/gameplay/Interactions.js +19 -15
  250. package/modules/gameplay/Inventory.js +9 -4
  251. package/modules/gameplay/Quests.js +12 -10
  252. package/modules/gameplay/pickups.js +23 -11
  253. package/modules/grid/index.js +1 -1
  254. package/modules/grid/preview.js +2 -2
  255. package/modules/grid/tiles.js +1 -1
  256. package/modules/hlod/index.js +4 -1
  257. package/modules/hud/index.js +47 -10
  258. package/modules/hud/parts.js +28 -9
  259. package/modules/level/geometry.js +8 -3
  260. package/modules/level/index.js +10 -5
  261. package/modules/level/load.js +4 -2
  262. package/modules/lights/sources.js +1 -1
  263. package/modules/music/Music.js +22 -4
  264. package/modules/nav/index.js +20 -10
  265. package/modules/particles/Particles.js +31 -14
  266. package/modules/particles/effect.js +20 -5
  267. package/modules/particles/lit.js +72 -0
  268. package/modules/photo/Photo.js +72 -28
  269. package/modules/photo/pathTrace.js +106 -0
  270. package/modules/rigid/RigidBodies.js +23 -14
  271. package/modules/rigid/Vehicles.js +3 -13
  272. package/modules/rigid/sync.js +2 -1
  273. package/modules/settings/Settings.js +52 -20
  274. package/modules/settings/apply.js +23 -9
  275. package/modules/settings/sections.js +39 -6
  276. package/modules/settings/strings.js +2 -0
  277. package/modules/settings/view.js +19 -3
  278. package/modules/sky/dome.js +15 -3
  279. package/modules/sky/environment.js +28 -12
  280. package/modules/sky/fog.js +1 -1
  281. package/modules/sky/frame.js +6 -1
  282. package/modules/sky/shader.js +4 -3
  283. package/modules/sky/skyModule.js +8 -4
  284. package/modules/swarm/Swarm.js +1 -1
  285. package/modules/terrain/ChunkManager.js +61 -15
  286. package/modules/terrain/chunkJob.js +2 -2
  287. package/modules/terrain/index.js +20 -5
  288. package/modules/terrain/terrainEdit.js +8 -4
  289. package/modules/terrain/terrainTexture.js +4 -2
  290. package/modules/timeline/Timeline.js +4 -3
  291. package/modules/timeline/Tween.js +3 -0
  292. package/modules/timeline/letterbox.js +1 -0
  293. package/modules/triggers/index.js +36 -17
  294. package/modules/vegetation/Vegetation.js +81 -19
  295. package/modules/vegetation/densityMap.js +13 -8
  296. package/modules/vegetation/draw.js +147 -24
  297. package/modules/vegetation/groundChunks.js +20 -5
  298. package/modules/vegetation/index.js +3 -3
  299. package/modules/vegetation/modelGeometry.js +9 -4
  300. package/modules/water/Water.js +11 -8
  301. package/modules/weather/Weather.js +7 -2
  302. package/modules/weather/shaders.js +25 -5
  303. package/modules/weather/weatherDraw.js +20 -6
  304. package/modules/world/World.js +2 -1
  305. package/modules/world/index.js +2 -2
  306. package/modules/world/persist.js +6 -2
  307. package/modules/world/views.js +15 -2
  308. package/package.json +5 -1
  309. package/presets.js +5 -5
  310. package/render/PostFX.js +102 -42
  311. package/render/backend.js +142 -16
  312. package/render/bindingLimits.js +59 -0
  313. package/render/cascades.js +3 -1
  314. package/render/cascades.tsl.js +2 -0
  315. package/render/daylight.js +7 -1
  316. package/render/detail.js +7 -4
  317. package/render/effects.js +27 -8
  318. package/render/fogLook.js +24 -0
  319. package/render/fuse.js +5 -2
  320. package/render/fx/compareLevel.tsl.js +23 -0
  321. package/render/fx/detail.tsl.js +9 -7
  322. package/render/fx/index.js +9 -2
  323. package/render/fx/library.tsl.js +1 -0
  324. package/render/fx/lightShaft.tsl.js +114 -0
  325. package/render/fx/noise.tsl.js +25 -8
  326. package/render/fx/objectOrigin.tsl.js +39 -10
  327. package/render/fx/particles.tsl.js +23 -6
  328. package/render/fx/patchNodes.tsl.js +17 -12
  329. package/render/fx/pcss.tsl.js +51 -0
  330. package/render/fx/postWebGPU.tsl.js +104 -29
  331. package/render/fx/sky.tsl.js +3 -9
  332. package/render/fxNumbers.js +10 -4
  333. package/render/impostor.tsl.js +107 -0
  334. package/render/lighting.js +33 -1
  335. package/render/lightmap.js +42 -28
  336. package/render/lights.js +19 -3
  337. package/render/materials.js +6 -4
  338. package/render/mergeCommon.js +4 -1
  339. package/render/occlusion.js +14 -4
  340. package/render/patches.js +79 -41
  341. package/render/postRuns.js +32 -0
  342. package/render/postWebGL.js +97 -10
  343. package/render/probes.js +10 -14
  344. package/render/shaderErrors.js +44 -7
  345. package/render/shadowCache.tsl.js +33 -5
  346. package/render/shadows.js +42 -16
  347. package/render/slots.js +8 -5
  348. package/render/vertexInputs.js +52 -0
  349. package/types/core.d.ts +115 -47
  350. package/types/gameplay.d.ts +56 -23
  351. package/types/generated/core/audio/Audio.d.ts +27 -1
  352. package/types/generated/core/base/Random.d.ts +1 -1
  353. package/types/generated/core/input/Input.d.ts +6 -8
  354. package/types/generated/core/input/inputSeat.d.ts +1 -1
  355. package/types/generated/core/inspect/Budget.d.ts +26 -0
  356. package/types/generated/core/inspect/DebugOverrides.d.ts +0 -2
  357. package/types/generated/core/saves/Saves.d.ts +10 -7
  358. package/types/generated/core/saves/session.d.ts +8 -2
  359. package/types/generated/core/scene/Rays.d.ts +1 -3
  360. package/types/generated/core/scene/Views.d.ts +17 -3
  361. package/types/generated/modules/particles/Particles.d.ts +1 -1
  362. package/types/generated/modules/world/World.d.ts +2 -1
  363. package/types/generated/render/PostFX.d.ts +35 -9
  364. package/types/physics.d.ts +796 -764
  365. package/types/pixel.d.ts +1 -1
  366. package/types/tsl.d.ts +62 -1
  367. package/types/world.d.ts +12 -3
  368. package/ui/Focus.js +7 -5
  369. package/ui/Parts.js +1 -1
  370. package/ui/touchPart.js +6 -3
package/render/PostFX.js CHANGED
@@ -10,13 +10,15 @@
10
10
  // and stays synchronous (a dynamic import would leave the first frames without post and make _sync async).
11
11
  import * as THREE from 'three';
12
12
  import { webglPost } from './postWebGL.js';
13
- import { codedError } from '../core/base/errorHints.js';
13
+ import { codedError, coded } from '../core/base/errorHints.js';
14
14
  import { warnOnce } from '../core/base/validate.js';
15
+ import { reportError } from '../core/base/errors.js';
15
16
  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';
17
+ import { isWebGPU, webgpuPart, ownMsaa } from './backend.js';
18
+ import { MSAA_KEY, onTierChange } from '../core/scene/tier.js';
18
19
  import { defineOwned } from '../core/ops/owned.js';
19
20
  import { watchOwnFrame } from './ownFrame.js';
21
+ import { runsHere, OUTPUT_TWICE } from './postRuns.js';
20
22
  /** @import { Engine } from '../types/core' */
21
23
 
22
24
  /**
@@ -25,8 +27,12 @@ import { watchOwnFrame } from './ownFrame.js';
25
27
  * 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
28
  * color and must output display color, tone mapped AND converted to the output color space, as three's OutputPass / renderOutput do);
27
29
  * 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.
30
+ * @typedef {(renderer: any, draw: () => any, opts?: { scene?: import('three').Scene, camera?: import('three').Camera, clean?: boolean }) => any} BorrowRenderer
31
+ * @typedef {{ engine: Engine, scene: import('three').Scene, camera: import('three').Camera, width: number, height: number, params: Record<string, any>, borrowRenderer: BorrowRenderer }} PostContext
32
+ * width / height are in device pixels. borrowRenderer(renderer, draw, { scene, camera, clean }): run draw() with the renderer borrowed, the engine's one
33
+ * borrow (render/backend.js): target with cube face and mip, viewport, scissor, clear color, autoClear, tone mapping, shadowMap.autoUpdate (and with scene
34
+ * / camera their overrideMaterial, background, fog, layers) are put back afterwards, also when draw throws. For an effect that draws an extra pass of
35
+ * 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
36
  * @typedef {{ uniforms?: Record<string, string>, values?: (params: Record<string, any>) => Record<string, any>, glsl: string, reads?: boolean }} PostFuse
31
37
  * A GLSL snippet that colors the pixel; neighboring effects with a fuse run as ONE fullscreen pass. glsl is statements that edit
32
38
  * `vec4 color` (the input pixel so far) and may use vUv, tDiffuse, uTime (s), uResolution (device px) and fxHash(vec2). uniforms
@@ -37,16 +43,16 @@ import { watchOwnFrame } from './ownFrame.js';
37
43
  * 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
44
  * t.input.sample(uv)), time (s), resolution (device px). Neighbors are chained into one node, so three draws them in one pass.
39
45
  * @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
46
+ * scenePass: any, buffer: (name: string) => any, tsl: any, fx: Record<string, Function>, display: Record<string, Function>, p: Record<string, any>, borrowRenderer: BorrowRenderer }} PostNodeContext
47
+ * WebGPU only. scenePass: the scene's pass() node (.getTextureNode('depth'), getViewZNode() ...); buffer(name): a needsBuffers output as a texture node
48
+ * ('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
49
  * 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
50
  * 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
51
  * fx: the threedog/tsl functions (noise, hash ...), handed in for the same reason;
46
52
  * 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
53
  * 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
54
  * @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,
55
+ * 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
56
  * params?: Record<string, any>, update?: (impl: any, params: Record<string, any>) => void }} PostEffect
51
57
  * 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
58
  * 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 +68,16 @@ import { watchOwnFrame } from './ownFrame.js';
62
68
  * 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
69
  * without it set() rebuilds the implementation.
64
70
  * 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).
71
+ * 'normal' (view space, raw), 'diffuse' (surface color), 'velocity' (a temporal resolve follows, so the scene pass runs without MSAA), 'metalRough' (metalness, roughness).
72
+ * More targets than the device takes (WebGPU's default: 32 bytes per pixel, four with the color) throws naming the effects.
66
73
  * backend: 'webgpu' = needs three's WebGPU backend itself (storage textures; WebGPURenderer on its WebGL2 backend cannot run it, so it is held there).
67
74
  * 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
75
  * 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.
76
+ * 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
77
+ * 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
78
+ * 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
79
  * facts: read by describe().render.post (a voxel size, what the effect still misses).
80
+ * 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
81
  * @typedef {{ readonly name: string, readonly slot: PostSlot, readonly order: number, enabled: boolean, readonly params: Record<string, any>,
71
82
  * set(params: Record<string, any>): void, remove(): void }} PostHandle
72
83
  * 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 +120,10 @@ export class PostFX {
109
120
  // own(): the game takes the built chain (composer passes / pipeline.outputNode) and the engine stops rebuilding it; handing it
110
121
  // 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
122
  /** @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(); } });
123
+ // 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
124
+ levels: { manual: 'engine.post.own()' }, onChange: o => { if (!o.on) return; if (this._pipe) { this._pipe.key = null; this._pipe.stages = []; } this._sync(); } });
113
125
  this._sync();
126
+ onTierChange(engine, () => this._sync()); // effects held by tier (skipOnLowTier) follow it; after the first sync, so a throw there leaves no listener
114
127
  }
115
128
 
116
129
  /**
@@ -122,6 +135,7 @@ export class PostFX {
122
135
  */
123
136
  get antialias() { return this._aa; }
124
137
  set antialias(on) {
138
+ 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
139
  this._aa = !!on;
126
140
  this._be.setAntialias(this, this._aa);
127
141
  this._sync();
@@ -165,8 +179,8 @@ export class PostFX {
165
179
 
166
180
  /**
167
181
  * 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.
182
+ * { 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.
183
+ * 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
184
  * 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
185
  * 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
186
  * @example const glow = engine.post.add(new UnrealBloomPass(size, 0.6, 0.4, 0.85), { name: 'glow' }); glow.enabled = false;
@@ -196,6 +210,9 @@ export class PostFX {
196
210
  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
211
  const other = s in EXCLUSIVE && this._list.find(e => e.slot === s);
198
212
  if (other) throw codedError('post-effect', `post slot '${s}' already holds '${other.name}'; remove it first (only one effect can ${EXCLUSIVE[s]})`);
213
+ const odd = Object.keys(effect.cheaper ?? {}).filter(k => !(k in (effect.params ?? {})));
214
+ 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`);
215
+ finiteParams(effect.name, effect.params, 'params');
199
216
  const post = this, point = this.switchPoint(`post.${effect.name}.enabled`);
200
217
  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
218
  let on = !!point.value();
@@ -214,27 +231,34 @@ export class PostFX {
214
231
  if (h._removed) return;
215
232
  const unknown = Object.keys(p ?? {}).filter(k => !(k in h.params));
216
233
  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)' : ''}`);
234
+ finiteParams(h.name, p, 'set(params)');
217
235
  const changed = Object.fromEntries(Object.entries(p).filter(([k, v]) => h.params[k] !== v));
218
236
  if (!Object.keys(changed).length) return;
219
237
  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; }
238
+ // 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
239
+ let rebuild = false;
240
+ post._change(() => { rebuild = h._apply(changed); }, () => { h._apply(was); }, () => rebuild);
221
241
  },
242
+ /** 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
243
  _apply(p) {
223
244
  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(); }
245
+ h._swaps = undefined; // the order rule's probe of a pass never built yet was made from the old params
246
+ if (post._be.set?.(post, h, p)) return false; // WebGPU: live uniforms, or a rebuild of the node graph
247
+ if (effect.fuse) { post._be.refresh(post, h); return false; }
248
+ if (!h._impl) return false;
249
+ if (effect.update) { effect.update(h._impl, h.params); return false; }
250
+ freeImpl(h); return true;
228
251
  },
229
252
  remove() {
230
253
  if (h._removed) return;
231
254
  h._removed = true;
232
255
  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();
256
+ post._change(() => {
257
+ freeImpl(h);
258
+ post._list = post._list.filter(e => e !== h);
259
+ 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)
260
+ const i = post._plain.indexOf(h._entry); if (i >= 0) post._plain.splice(i, 1);
261
+ }, () => {}); // a removal cannot break depth order: nothing to put back
238
262
  },
239
263
  };
240
264
  // a settings restriction or a hold ending turns it on or off here; a rebuild that throws leaves it as it was
@@ -243,6 +267,7 @@ export class PostFX {
243
267
  try { this._change(() => this._list.push(h), () => { freeImpl(h); this._list = this._list.filter(e => e !== h); }); }
244
268
  catch (err) { point.onChange = null; if (!this._kept.has(h.name)) this._seq.delete(h.name); throw err; }
245
269
  this.engine._picture?.added('post effect', h, h.name); // dev: a picture part removed with this still on is reported (core/inspect/pictureWriters.js)
270
+ 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
271
  return h;
247
272
  }
248
273
  /**
@@ -252,17 +277,26 @@ export class PostFX {
252
277
  */
253
278
  _held(h) {
254
279
  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;
280
+ if (h._failed) return h._failed;
281
+ const w = runsHere(h._def, this.engine);
282
+ 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
283
+ warnOnce(`post effect '${h.name}' held off: ${w.why}`);
284
+ return w.why;
285
+ }
286
+ /**
287
+ * The device refused a pipeline of this material (render/shaderErrors.js). When one effect's own pass draws with it, that effect is held and the chain
288
+ * rebuilt without it: an invalid pipeline fails every frame it is drawn in, the whole frame with it. It stays held until it is removed and added again
289
+ * (a new handle), since the same shader on the same device fails the same way.
290
+ * @param {number} id material id @returns {string} what was done, '' when no effect owns the material @internal
291
+ */
292
+ _pipelineFailed(id) {
293
+ const h = this._be.ownerOf?.(this, id);
294
+ if (!h) return '';
295
+ if (!h._failed) {
296
+ h._failed = 'the device refused its shader (the page error names it); held until it is removed and added again';
297
+ try { this._sync(); } catch (err) { reportError(this.engine, err, 'post chain', { soft: true }); } // from a device callback: nothing above to catch it
298
+ }
299
+ return coded('post-effect-failed', `it draws post effect '${h.name}', which is now held off so the rest of the frame draws (describe().render.post says so)`);
266
300
  }
267
301
  /**
268
302
  * 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 +319,18 @@ export class PostFX {
285
319
  * @example engine.post.get('bloom').set({ strength: 0.6 });
286
320
  * @param {string} name
287
321
  * @returns {PostHandle | undefined}
288
- * @experimental
289
322
  */
290
323
  get(name) { return this._list.find(e => e.name === name); }
324
+ /**
325
+ * 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
326
+ * 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
327
+ * roles existed); with no `name` that case gives [].
328
+ * @param {string} role
329
+ * @param {string} [name] fallback effect name
330
+ * @returns {PostHandle[]}
331
+ * @experimental
332
+ */
333
+ 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
334
  /**
292
335
  * 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
336
  * 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 +343,6 @@ export class PostFX {
300
343
  /**
301
344
  * Effects in render order: [{ name, slot, order, enabled }]
302
345
  * @returns {{ name: string, slot: PostSlot, order: number, enabled: boolean }[]}
303
- * @experimental
304
346
  */
305
347
  list() { return this._sorted().map(({ name, slot, order, enabled }) => ({ name, slot, order, enabled })); }
306
348
 
@@ -311,9 +353,15 @@ export class PostFX {
311
353
  /** @internal */
312
354
  _size() { return this.engine.renderer.getSize(new THREE.Vector2()).multiplyScalar(this.engine.renderer.getPixelRatio()); }
313
355
  /** 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; }
356
+ /**
357
+ * 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
358
+ * 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
359
+ * 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
360
+ * whether this change needs the chain built again (a set() through update() in place does not).
361
+ * @param {() => void} apply @param {() => void} undo @param {() => boolean} [rebuild]
362
+ */
363
+ _change(apply, undo, rebuild = () => true) {
364
+ try { apply(); this._be.checkOrder?.(this); if (rebuild()) this._sync(); } catch (err) { undo(); this._sync(); throw err; }
317
365
  }
318
366
  // Rebuild the chain from the list (the backend does it)
319
367
  /** @internal */
@@ -389,6 +437,16 @@ export class PostFX {
389
437
  * _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
438
  * @param {any} h
391
439
  */
440
+ /**
441
+ * 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
442
+ * 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).
443
+ * @param {string} name @param {Record<string, any> | undefined} p @param {string} where
444
+ */
445
+ function finiteParams(name, p, where) {
446
+ const bad = Object.entries(p ?? {}).filter(([, v]) => typeof v === 'number' && !Number.isFinite(v));
447
+ if (bad.length) throw codedError('post-effect', `post effect '${name}': ${where} takes finite numbers; got ${bad.map(([k, v]) => `${k}: ${v}`).join(', ')}`);
448
+ }
449
+
392
450
  function freeImpl(h) {
393
451
  if (h._impl !== h._def._pass) h._impl?.dispose?.();
394
452
  h._impl = null;
@@ -404,13 +462,13 @@ const skipped = remove => /** @type {any} */ ({ name: null, enabled: false, set(
404
462
 
405
463
  /** 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
464
  function reslot(post) {
407
- let after = false, changed = false;
465
+ let after = false; const moved = [];
408
466
  for (const e of post._plain) {
409
467
  if (e.output) { after = true; continue; }
410
468
  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; }
469
+ if (h && h.slot !== s) moved.push([h, h.slot, s]);
412
470
  }
413
- if (changed) post._sync();
471
+ if (moved.length) post._change(() => { for (const [h, , s] of moved) h.slot = s; }, () => { for (const [h, was] of moved) h.slot = was; });
414
472
  }
415
473
 
416
474
  /** A three.js Pass that draws the scene itself (RenderPixelatedPass, SSAARenderPass, TAARenderPass, a RenderPass): it replaces the scene render */
@@ -441,6 +499,8 @@ function effectOf(post, x, { name, slot, order }) {
441
499
  }
442
500
  // a readable name that survives minified class names: the pass's own name, else a ShaderPass's shader name (CopyShader, FXAAShader)
443
501
  const mn = x.material?.name, cls = (typeof x.name === 'string' && x.name) || (mn && mn !== 'unspecified' ? mn : 'pass'), n = next();
502
+ // a known display-conversion shader (three's GammaCorrectionShader / OutputShader as a ShaderPass) is encoded a second time by the engine's output stage
503
+ if (/^(GammaCorrection|Output)Shader$/.test(mn ?? '') && slot !== 'tone') warnOnce(OUTPUT_TWICE(cls));
444
504
  const s = drawsScene(eng, x) ? 'scene' : /FXAA|SMAA|TAA/i.test(cls) || x._edgesRT ? 'final' : post._plain.some(e => e.output) ? 'ldr' : 'hdr';
445
505
  // _pass: the game's own object, not disposed when the effect is removed (three's removePass habit; remove() in _add).
446
506
  // _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,16 @@
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';
15
+ import { checkBindingLimits } from './bindingLimits.js';
11
16
 
12
17
  /** Samples of the MSAA the post chain's targets use, on both renderers */
13
18
  export const MSAA_SAMPLES = 4;
@@ -32,6 +37,13 @@ export function stats(r) {
32
37
  geometries: i.memory.geometries, textures: i.memory.textures };
33
38
  }
34
39
 
40
+ /**
41
+ * Whether r has drawn at least once. Why here: WebGLRenderer counts frames in info.render.frame; WebGPURenderer has no such field (its
42
+ * 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
43
+ * @param {any} r @returns {boolean}
44
+ */
45
+ export const drawnAFrame = r => (isWebGPU(r) ? r.info.render.calls : r.info.render.frame) > 0;
46
+
35
47
  /** Compiled shader programs (WebGLRenderer keeps the list), or null where the renderer keeps none (WebGPU) @param {any} r @returns {number | null} */
36
48
  export const programCount = r => isWebGPU(r) ? null : r.info.programs?.length ?? null;
37
49
 
@@ -43,19 +55,26 @@ export const programList = r => isWebGPU(r) ? [] : r.info.programs ?? [];
43
55
  // last render object built per material is kept (weakly: the material's lifetime) and its NodeBuilderState read on demand.
44
56
  // 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
57
  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' });
58
+ notePatch('node-builder-hook', "renderer.debug.onNodeBuilderCreated of a WebGPURenderer: remembers the render object built per material and counts each program's vertex inputs, sampled textures and samplers " +
59
+ "before its code is written (that builder's buildCode), a game's own hook still runs (render/backend.js)", () => {},
60
+ { 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 or texture bindings fails with three's raw pipeline error" });
48
61
  /** @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
62
  export function watchNodePrograms(r) {
50
63
  const d = r?.debug;
51
64
  if (!isWebGPU(r) || !d || d._threedogPrograms) return;
52
65
  const prev = d.onNodeBuilderCreated;
53
66
  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(); }
67
+ if (ro?.material && patchOn('node-builder-hook')) {
68
+ NODE_PROGRAMS.set(ro.material, ro); RECENT.push(new WeakRef(ro)); if (RECENT.length > RECENT_MAX) RECENT.shift();
69
+ const code = builder.buildCode;
70
+ // 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
71
+ builder.buildCode = function () { if (this.material === ro.material) { checkVertexInputs(this, r); checkBindingLimits(this, r); } return code.call(this); };
72
+ }
55
73
  prev?.(builder, ro);
56
74
  };
57
75
  d._threedogPrograms = true;
58
76
  }
77
+
59
78
  /**
60
79
  * @internal render/shaderErrors.js: the newest render object three built that passes test(renderObject), or null
61
80
  * @param {(ro: any) => boolean} test @returns {any}
@@ -89,6 +108,14 @@ export function memory(r) {
89
108
  return isWebGPU(r) ? { geometries: m.geometries, textures: m.textures } : { ...m };
90
109
  }
91
110
 
111
+ /** 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
112
+ * WebGLRenderer, which keeps counts but no byte sizes @param {any} r @returns {number | null} */
113
+ export const GPU_MEMORY = "estimate: three's own count, not driver VRAM";
114
+ export const gpuMemoryMB = r => isWebGPU(r) ? Math.round(r.info.memory.total / 104857.6) / 10 : null;
115
+ /** 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
116
+ * 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} */
117
+ export const countedTextureBytes = r => isWebGPU(r) ? r.info.memory.texturesSize ?? null : null;
118
+
92
119
  /** Start this frame's counters from zero (the engine renders with info.autoReset off: onRender targets count too) @param {any} r */
93
120
  export function resetStats(r) { r.info.reset(); }
94
121
 
@@ -237,7 +264,7 @@ function tierOf(name) {
237
264
  try {
238
265
  if (matchMedia('(pointer: coarse)').matches) return 'low';
239
266
  if (/intel|uhd|iris|mali|adreno|powervr|swiftshader|llvmpipe|software/i.test(name())) return 'low';
240
- } catch { /* cannot tell: assume high-end */ }
267
+ } 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
268
  return 'high';
242
269
  }
243
270
  let probedName = /** @type {string | null} */ (null);
@@ -300,9 +327,102 @@ export function freshFrame(r) {
300
327
  */
301
328
  export function renderOnce(r, scene, camera, target = null) {
302
329
  freshFrame(r);
303
- const prev = r.getRenderTarget();
304
- r.setRenderTarget(target);
305
- try { r.render(scene, camera); } finally { r.setRenderTarget(prev); }
330
+ borrowRenderer(r, () => { r.setRenderTarget(target); r.render(scene, camera); });
331
+ }
332
+
333
+ // Borrowing the renderer (design.md 4.5): every engine task that changes renderer state to draw something of its own goes through these, so
334
+ // 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
335
+ // 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.
336
+ // The fields are written out below, not looped over a list: each one has its own getter / setter pair on three's renderers.
337
+ // What a task draws into (its own targets, materials, the layers of its own objects) stays the task's to make and free.
338
+ /** 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 */
339
+ const held = [];
340
+ let depth = 0;
341
+ /** three's Vector4 and Color, handed in by core/engine/Engine.js (it imports 'three'; three/webgpu shares the same three.core.js classes) */
342
+ let M = /** @type {{ Vector4: any, Color: any } | null} */ (null), _cv = /** @type {any} */ (null);
343
+ /** @param {{ Vector4: any, Color: any }} classes */
344
+ export function mathClasses({ Vector4, Color }) { M = { Vector4, Color }; _cv = new Vector4(); }
345
+ /**
346
+ * Save the renderer state a borrow may change. Pair it with releaseRenderer(s, putBack) in a finally (borrowRenderer does both).
347
+ * Saved: the target with its cube face and mip level, viewport, scissor and scissor test, clear color and alpha, autoClear (and its color / depth /
348
+ * stencil parts), toneMapping and toneMappingExposure, shadowMap.autoUpdate; on WebGPURenderer also the MRT, the render-object function and the
349
+ * opaque / transparent switches and the viewport's minDepth / maxDepth. With scene: its overrideMaterial, background and fog (and WebGPU's backgroundNode and fogNode);
350
+ * with camera: its layers.mask.
351
+ * WebGLRenderer keeps two of each: what was set (getViewport, getScissor, getScissorTest) and what draws (getCurrentViewport and the GL scissor box / test,
352
+ * 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.
353
+ * clean: true (WebGPU) then sets what three's RendererUtils.resetRendererState sets (no MRT, no render-object function, clear 0x000000 / 1, every autoClear
354
+ * part on, opaque and transparent on), for a quad drawn inside a node frame that must not inherit the scene pass's MRT.
355
+ * @param {any} r @param {{ scene?: any, camera?: any, clean?: boolean }} [o] @returns {any}
356
+ */
357
+ export function holdRenderer(r, { scene = null, camera = null, clean = false } = {}) {
358
+ const V = /** @type {any} */ (M).Vector4; // null only when the engine core was never loaded: nothing can hand this file a renderer then
359
+ const s = held[depth] ??= { viewport: new V(), scissor: new V(), color: new (/** @type {any} */ (M).Color)(), current: new V(), box: new V() };
360
+ s.depth = depth++; s.r = r; s.scene = scene; s.camera = camera;
361
+ s.target = r.getRenderTarget(); s.face = r.getActiveCubeFace(); s.mip = r.getActiveMipmapLevel();
362
+ r.getViewport(s.viewport); r.getScissor(s.scissor); s.scissorTest = r.getScissorTest();
363
+ r.getClearColor(s.color); s.alpha = r.getClearAlpha();
364
+ s.autoClear = r.autoClear; s.autoColor = r.autoClearColor; s.autoDepth = r.autoClearDepth; s.autoStencil = r.autoClearStencil;
365
+ s.toneMapping = r.toneMapping; s.exposure = r.toneMappingExposure; s.shadowAuto = r.shadowMap.autoUpdate;
366
+ s.gpu = isWebGPU(r);
367
+ if (s.gpu) {
368
+ s.mrt = r.getMRT(); s.objectFn = r.getRenderObjectFunction(); s.opaque = r.opaque; s.transparent = r.transparent;
369
+ // Vector4.copy (getViewport) drops the depth range, and setViewport(vector) puts 0..1 back: read from the canvas target (no public getter)
370
+ const v = r.getCanvasTarget?.()._viewport; s.minDepth = v?.minDepth ?? 0; s.maxDepth = v?.maxDepth ?? 1;
371
+ } else {
372
+ r.getCurrentViewport(s.current);
373
+ const gl = r.getContext(), b = gl.getParameter(gl.SCISSOR_BOX); // three keeps the drawing scissor nowhere readable
374
+ 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
375
+ }
376
+ if (scene) { s.override = scene.overrideMaterial; s.background = scene.background; s.bgNode = scene.backgroundNode; s.fog = scene.fog; s.fogNode = scene.fogNode; }
377
+ if (camera) s.layers = camera.layers.mask;
378
+ if (clean) {
379
+ if (s.gpu) { r.setMRT(null); r.setRenderObjectFunction(null); r.opaque = r.transparent = true; }
380
+ r.setClearColor(0x000000, 1); r.autoClear = r.autoClearColor = r.autoClearDepth = r.autoClearStencil = true;
381
+ }
382
+ return s;
383
+ }
384
+ /**
385
+ * End a hold: putBack writes every saved field back; false only lets the slot go (an onRender hook that returned keeps what it left).
386
+ * Order on WebGLRenderer: the set values, then the target (which draws with its own viewport / scissor), then the drawing area as it was.
387
+ * @param {any} s @param {boolean} [putBack]
388
+ */
389
+ export function releaseRenderer(s, putBack = true) {
390
+ depth = s.depth;
391
+ const { r, scene, camera } = s;
392
+ if (putBack) putBackState(s, r, scene, camera);
393
+ 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
394
+ }
395
+ /**
396
+ * Run draw() with the renderer borrowed: whatever draw changes of the fields holdRenderer lists is put back afterwards, also when it throws.
397
+ * Returns what draw returns. Plain three.js equivalent: save each field, try { draw } finally { set each one back }.
398
+ * @template T @param {any} r @param {() => T} draw @param {{ scene?: any, camera?: any, clean?: boolean }} [o] @returns {T}
399
+ */
400
+ export function borrowRenderer(r, draw, o) {
401
+ const s = holdRenderer(r, o);
402
+ try { return draw(); } finally { releaseRenderer(s); }
403
+ }
404
+ /** @param {any} s @param {any} r @param {any} scene @param {any} camera */
405
+ function putBackState(s, r, scene, camera) {
406
+ if (scene) {
407
+ scene.overrideMaterial = s.override; scene.background = s.background; scene.fog = s.fog;
408
+ // 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
409
+ // turned it off and threw would otherwise leave scene.fog back but the fog gone for good
410
+ if (scene.backgroundNode !== s.bgNode) scene.backgroundNode = s.bgNode;
411
+ if (scene.fogNode !== s.fogNode) scene.fogNode = s.fogNode;
412
+ }
413
+ if (camera) camera.layers.mask = s.layers;
414
+ r.toneMapping = s.toneMapping; r.toneMappingExposure = s.exposure; r.shadowMap.autoUpdate = s.shadowAuto;
415
+ r.setClearColor(s.color, s.alpha);
416
+ r.autoClear = s.autoClear; r.autoClearColor = s.autoColor; r.autoClearDepth = s.autoDepth; r.autoClearStencil = s.autoStencil;
417
+ if (s.gpu) { r.setMRT(s.mrt); r.setRenderObjectFunction(s.objectFn); r.opaque = s.opaque; r.transparent = s.transparent; }
418
+ const v = s.viewport;
419
+ 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);
420
+ r.setRenderTarget(s.target, s.face, s.mip);
421
+ if (s.gpu) return; // WebGPURenderer draws a target with the target's own viewport: the set values above are all it keeps
422
+ // the drawing viewport differs from the target's own only when setViewport ran after the bind: running it again gives the same rounding;
423
+ // otherwise (an ArrayCamera's sub-viewport left mid-render) only the GL viewport can be put back
424
+ if (!r.getCurrentViewport(_cv).equals(s.current)) { r.setViewport(v); if (!r.getCurrentViewport(_cv).equals(s.current)) r.state.viewport(s.current); }
425
+ r.state.scissor(s.box); r.state.setScissorTest(s.boxTest); // three's GL state cache: no GL call when already equal
306
426
  }
307
427
 
308
428
  /**
@@ -318,7 +438,7 @@ export function renderOnce(r, scene, camera, target = null) {
318
438
  */
319
439
  export function compileThrough(r, draw) {
320
440
  const own = Object.hasOwn(r, 'render'), real = r.render, jobs = [];
321
- r.render = (scene, camera) => { jobs.push(r.compileAsync(scene, camera)); };
441
+ 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
442
  let out;
323
443
  try { out = draw(); } finally { if (own) r.render = real; else delete r.render; }
324
444
  return Promise.all(jobs).then(() => out);
@@ -339,10 +459,9 @@ export async function readLayer(r, rt, w, h, layer) {
339
459
  for (let y = 0; y < h; y++) out.set(px.subarray(y * row, (y + 1) * row), (h - 1 - y) * row);
340
460
  return out;
341
461
  }
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);
462
+ const px = new Float32Array(w * h * 4);
463
+ // on WebGL the layer is chosen by what is attached, readRenderTargetPixels has no layer argument
464
+ borrowRenderer(r, () => { r.setRenderTarget(rt, layer); r.readRenderTargetPixels(rt, 0, 0, w, h, px); });
346
465
  return px;
347
466
  }
348
467
 
@@ -359,7 +478,7 @@ export const projectionKey = cam => (cam.isPerspectiveCamera ? `${cam.fov},${cam
359
478
  // a sixth part had nothing to copy. Now a .tsl.js file calls registerWebGPUPart(name, impl) once at load, and every user asks
360
479
  // webgpuPart(name, who): the same error code and the same fix line wherever threedog/tsl is missing.
361
480
  // 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 */
481
+ /** @typedef {'classes' | 'nodePatches' | 'particles' | 'post' | 'sky' | 'cascades' | 'shadowCache' | 'impostor'} WebGPUPartName */
363
482
  /** @type {Map<string, any>} */
364
483
  const PARTS = new Map();
365
484
  /**
@@ -406,17 +525,24 @@ export function rendererSwapped(engine) { for (const fn of [...(SWAP.get(engine)
406
525
  * 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
526
  * @returns {Promise<string | null>}
408
527
  */
409
- export async function whyNoWebGPU() {
528
+ /** @param {Record<string, number>} [limits] three's requiredLimits of a renderer the engine made: filled before its init() requests the device @param {string} [powerPreference] */
529
+ export async function whyNoWebGPU(limits, powerPreference) {
410
530
  const gpu = typeof navigator === 'undefined' ? undefined : /** @type {any} */ (navigator).gpu;
411
531
  if (!gpu) return 'navigator.gpu is missing';
412
532
  let adapter;
413
- try { adapter = await gpu.requestAdapter({ featureLevel: 'compatibility' }); } catch (err) { return `requestAdapter() failed: ${err?.message ?? err}`; }
533
+ try { adapter = await gpu.requestAdapter({ featureLevel: 'compatibility', powerPreference }); } catch (err) { return `requestAdapter() failed: ${err?.message ?? err}`; }
414
534
  if (!adapter) return 'requestAdapter() returned no adapter';
535
+ // WebGPU hands out its default limits unless a higher one is asked for, whatever the hardware can do; asking what this adapter supports costs nothing and lifts each where it can
536
+ if (limits) for (const k of ADAPTER_LIMITS) limits[k] ??= adapter.limits[k];
415
537
  if (deviceFrom === gpu) return null;
416
538
  try { (await adapter.requestDevice()).destroy?.(); } catch (err) { return `requestDevice() failed: ${err?.message ?? err}`; }
417
539
  deviceFrom = gpu;
418
540
  return null;
419
541
  }
542
+ // The defaults a game's picture can pass, asked for at the adapter's own value in the one place the engine requests a device (a game's own renderer keeps the game's limits):
543
+ // the post chain's merged scene targets pass 32 bytes per pixel (render/fx/postWebGPU.tsl.js); a material with several texture layers, plus the lights' shadow maps, passes
544
+ // 16 textures and samplers per stage; voxelGI's triangle buffer (three's VXGIVolume, about 200 bytes a triangle) passes a 256 MB buffer and a 128 MB storage binding
545
+ const ADAPTER_LIMITS = ['maxColorAttachmentBytesPerSample', 'maxColorAttachments', 'maxSampledTexturesPerShaderStage', 'maxSamplersPerShaderStage', 'maxBufferSize', 'maxStorageBufferBindingSize'];
420
546
  let deviceFrom = null; // the navigator.gpu that gave a device (a page's stand-in for it is another object, so it is asked again)
421
547
 
422
548
  /** Each material on a scene object, once @param {any} scene @param {(m: any, o: any) => void} fn */
@@ -0,0 +1,59 @@
1
+ // Sampled textures and samplers of a WebGPURenderer program, counted before three writes its code.
2
+ // A shader stage binds at most maxSampledTexturesPerShaderStage textures and maxSamplersPerShaderStage samplers (16 each on most devices). They stack up from
3
+ // parts that know nothing of each other: the material's own maps (a ground with 4 layers of color, normal and ARM plus a mask is 13), every shadow-casting
4
+ // light's shadow map, the environment map. Over the limit the device's only word is `Invalid PipelineLayout` / a bind group layout error that names no
5
+ // material. Counted where every node has asked for its bindings and no code exists yet (the builder's buildCode, as render/vertexInputs.js does): the throw
6
+ // lands in three's build-error path, which logs it and draws its plain stand-in instead. Real WebGPU only (the WebGL2 backend has no such limits here).
7
+ import { codedError } from '../core/base/errorHints.js';
8
+
9
+ const STAGES = ['vertex', 'fragment'];
10
+ /** @param {any} t a texture @returns {'shadow maps' | 'environment / cube maps' | 'other maps'} three has no flag for "this is the environment": a depth texture is a shadow
11
+ * map, a texture not mapped as plain UVs (cube, equirect, the PMREM of scene.environment) is an environment */
12
+ const kindOf = t => t?.isDepthTexture ? 'shadow maps' : t?.isCubeTexture || (t?.mapping ?? 300) !== 300 ? 'environment / cube maps' : 'other maps';
13
+
14
+ /**
15
+ * Per shader stage: the sampled textures and the samplers three bound for the program being built, and which textures are shadow maps / environment.
16
+ * three keeps them in builder.bindings[stage][group] (WGSLNodeBuilder.getUniformFromNode): a NodeSampledTexture (isSampledTexture; it extends Sampler, so
17
+ * isSampler is true for it too) and, beside each filterable one, a NodeSampler. Storage textures are no sampled textures (their own limit).
18
+ * @internal render/backend.js watchNodePrograms and tests/vertex-inputs @param {any} builder
19
+ * @returns {Record<string, { textures: number, samplers: number, kinds: Record<string, number> }>}
20
+ */
21
+ export function bindingCounts(builder) {
22
+ /** @type {Record<string, { textures: number, samplers: number, kinds: Record<string, number> }>} */
23
+ const out = {};
24
+ for (const stage of STAGES) {
25
+ const c = out[stage] = { textures: 0, samplers: 0, kinds: {} };
26
+ for (const group of Object.values(builder.bindings?.[stage] ?? {})) for (const b of /** @type {any[]} */ (group)) {
27
+ if (b.isSampledTexture) {
28
+ if (b.store) continue;
29
+ c.textures++;
30
+ const k = kindOf(b.texture ?? b.textureNode?.value);
31
+ c.kinds[k] = (c.kinds[k] ?? 0) + 1;
32
+ } else if (b.isSampler) c.samplers++;
33
+ }
34
+ }
35
+ return out;
36
+ }
37
+
38
+ /**
39
+ * @internal render/backend.js watchNodePrograms, for every node program before its code is written.
40
+ * Throws, naming the material and what stacked up, when a stage binds more textures or samplers than the device allows (real WebGPU only) @param {any} builder @param {any} r
41
+ */
42
+ export function checkBindingLimits(builder, r) {
43
+ const l = r.backend?.device?.limits;
44
+ if (!l) return;
45
+ const counts = bindingCounts(builder), over = [];
46
+ for (const stage of STAGES) {
47
+ const c = counts[stage];
48
+ for (const [what, n, max] of [['sampled textures', c.textures, l.maxSampledTexturesPerShaderStage], ['samplers', c.samplers, l.maxSamplersPerShaderStage]]) {
49
+ if (n <= max) continue;
50
+ const kinds = Object.entries(c.kinds).map(([k, v]) => `${v} ${k}`).join(', ');
51
+ over.push(`the ${stage} stage binds ${n} ${what}, this device takes ${max}${kinds ? ` (${kinds})` : ''}`);
52
+ }
53
+ }
54
+ if (!over.length) return;
55
+ const m = builder.material, o = builder.object;
56
+ throw codedError('texture-bindings', `[threedog] ${m?.type}${m?.name ? ` '${m.name}'` : ''} (#${m?.id}) on ${o?.type ?? 'object'} '${o?.name || '(unnamed)'}': ${over.join('; ')}. `
57
+ + 'To fit: fewer texture layers, pack maps into one texture\'s channels (roughness / ao / metalness in one ARM texture), fewer shadow-casting lights (castShadow = false), '
58
+ + 'or drop the environment map on this material.');
59
+ }