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
@@ -4,20 +4,35 @@
4
4
  // just nested calls, so three compiles them into one fullscreen pass and fuse.js's merging is not needed here (nor loaded).
5
5
  // Registered with render/backend.js when threedog/tsl loads (see PostFX.js for why not an import). Only three/webgpu, three/tsl and three's TSL display
6
6
  // nodes are imported: this file must never pull EffectComposer or other WebGL code.
7
- import { RenderPipeline } from 'three/webgpu';
7
+ import { RenderPipeline, UnsignedByteType } from 'three/webgpu';
8
8
  import * as TSL from 'three/tsl';
9
9
  import { bloom } from 'three/addons/tsl/display/BloomNode.js';
10
10
  import { ao } from 'three/addons/tsl/display/GTAONode.js';
11
11
  import { codedError } from '../../core/base/errorHints.js';
12
- import { registerWebGPUPart, MSAA_SAMPLES } from '../backend.js';
12
+ import { warnOnce } from '../../core/base/validate.js';
13
+ import { runsOnWebGPU, OUTPUT_TWICE } from '../postRuns.js';
14
+ import { registerWebGPUPart, MSAA_SAMPLES, borrowRenderer } from '../backend.js';
13
15
  import { RESERVED_LAYERS } from '../layers.js';
14
16
  import * as FX from './library.tsl.js';
15
17
  import { nameNodeBuild, lostStatements } from './nodeErrors.tsl.js';
16
18
 
17
- const { pass, renderOutput, uniform, screenUV, screenSize, time, convertToTexture, mrt, output, normalView, diffuseColor, velocity } = TSL;
19
+ const { pass, renderOutput, uniform, screenUV, screenSize, time, convertToTexture, mrt, output, normalView, diffuseColor, velocity, metalness, roughness, vec2, vec4 } = TSL;
18
20
 
19
- // What PostEffect.needsBuffers can ask of the scene render. Raw, not packed: display nodes read them as they are
20
- const BUFFERS = { normal: normalView, diffuse: diffuseColor, velocity };
21
+ // What PostEffect.needsBuffers can ask of the scene render. Raw, not packed into other encodings: display nodes read them as they are.
22
+ // metalRough is the one exception in storage, not in meaning: both are 0 to 1, so they share one 8-bit target (three's SSR example does the same), a quarter of a half-float one
23
+ const BUFFERS = { normal: normalView, diffuse: diffuseColor, velocity, metalRough: vec2(metalness, roughness) };
24
+ const BYTE_BUFFERS = ['metalRough'];
25
+ // velocity fills only xy of its target: with both asked, metalRough rides in its zw, one target fewer (output + normal + diffuse + velocity is WebGPU's default ceiling)
26
+ const VELOCITY_METAL_ROUGH = vec4(/** @type {any} */ (velocity), BUFFERS.metalRough); // three types the velocity node as no vec2
27
+
28
+ /** How many scene targets the device takes. Every target here is rgba16float or rgba8unorm, 8 bytes per sample each in WebGPU's table, so bytes reduce to a count; Infinity before the device exists */
29
+ function roomOf(r) {
30
+ const be = r.backend, l = be?.device?.limits, gl = be?.gl;; if (!l && !gl) return Infinity;
31
+ // read once per backend: render() asks every frame, and a GL query there would be a sync call each frame
32
+ if (!rooms.has(be)) rooms.set(be, l ? Math.min(l.maxColorAttachments, Math.floor(l.maxColorAttachmentBytesPerSample / 8)) : gl.getParameter(gl.MAX_DRAW_BUFFERS));
33
+ return rooms.get(be);
34
+ }
35
+ const rooms = new WeakMap();
21
36
 
22
37
  /** Which uniform a param value makes: 'number' (numbers, booleans as 0 / 1), a color or vector kind, or null: anything else rebuilds the chain when it changes */
23
38
  const kindOf = v => (typeof v === 'number' || typeof v === 'boolean' ? 'number' : v?.isColor ? 'color' : v?.isVector2 ? 'vec2' : v?.isVector3 ? 'vec3' : v?.isVector4 ? 'vec4' : null);
@@ -71,13 +86,15 @@ function extraPass(scene, camera, opts) {
71
86
  return n;
72
87
  }
73
88
 
89
+ const SCENE = 'scene render', OUTPUT = 'output (tone mapping)'; // the engine's own stages in P.stages and post.order
90
+
74
91
  const onlyCreate = e => codedError('post-effect', `[threedog] post effect '${e.name}' has only create() (a three.js Pass, WebGLRenderer only); on WebGPURenderer give it ` +
75
92
  `node: (input, ctx) => colorNode, e.g. node: (input, { tsl, p }) => tsl.vec4(input.rgb.mul(p.amount), input.a) (recipe 52)`);
76
93
  const glslOnly = e => codedError('post-effect', `[threedog] post effect '${e.name}': its fuse snippet is GLSL only; on WebGPURenderer add fuse.tsl: ` +
77
94
  `(color, uv, t) => color, e.g. tsl: (color, uv, { tsl, p }) => tsl.vec4(color.rgb.mul(p.amount), color.a) (recipe 52)`);
78
95
 
79
96
  const webgpuPost = {
80
- init(post) { post._pipe = null; },
97
+ init(post) { post._pipe = null; post._pipeOut = null; },
81
98
  object: post => (post._pipe ? { pipeline: post._pipe.pipeline, scenePass: post._pipe.scenePass } : null),
82
99
  // The pass node owns its render targets and resizes them with the renderer; nothing is handed out as ping-pong targets on this backend
83
100
  targets: () => null,
@@ -96,30 +113,41 @@ const webgpuPost = {
96
113
  return true;
97
114
  },
98
115
  samples: post => (post.active ? post._pipe?.samples ?? (post._aa ? MSAA_SAMPLES : 0) : post.engine.renderer.samples),
99
- setAntialias(post) { if (post._pipe) post._pipe.key = null; },
116
+ // nothing here: sync's key holds the effective samples, so a switch under a temporal resolve (samples stay 0) rebuilds nothing
117
+ setAntialias() {},
100
118
  sync(post) {
101
119
  const { renderer, scene, camera } = post.engine;
102
120
  const on = post._sorted().filter(e => e.enabled);
121
+ // nothing on: the frame goes straight to the canvas, so the scene pass's color, depth and MSAA targets are freed now, not at engine.dispose
122
+ // (postWebGL.js frees its composer targets the same way); the next effect builds a new pipeline (GPT review l2-render 6)
123
+ if (!on.length) { for (const e of post._list) { e._impl?.dispose?.(); e._impl = null; } webgpuPost.dispose(post); return; }
103
124
  // the union over the effects that are on, in one fixed order: one setMRT for all of them, and none at all (no extra targets) when nobody asks
104
125
  const buffers = Object.keys(BUFFERS).filter(b => on.some(e => e._def.needsBuffers?.includes(b)));
126
+ const packed = buffers.includes('velocity') && buffers.includes('metalRough'), room = roomOf(renderer);
127
+ const targets = Object.fromEntries(buffers.filter(b => !(packed && b === 'metalRough')).map(b => [b, packed && b === 'velocity' ? VELOCITY_METAL_ROUGH : BUFFERS[b]]));
128
+ // over the device's limit three's pipeline validation fails naming no effect; checked before anything is torn down, so add() rolls back cleanly
129
+ const n = 1 + Object.keys(targets).length;
130
+ if (n > room) throw codedError('post-effect', `[threedog] post effects ${on.filter(e => e._def.needsBuffers?.length).map(e => `${e.name} (${e._def.needsBuffers.join(', ')})`).join(', ')} ` +
131
+ `need ${n} scene targets (${n * 8} bytes per pixel), this device takes ${room} (${room * 8} bytes): turn off the one that matters least`);
105
132
  // velocity means a temporal resolve follows: it is the antialiasing, and MSAA under it would only cost
106
133
  const samples = post._aa && !buffers.includes('velocity') ? MSAA_SAMPLES : 0;
107
- for (const e of on) if (e._def.fuse ? typeof e._def.fuse.tsl !== 'function' : typeof e._def.node !== 'function') throw e._def.fuse ? glslOnly(e) : onlyCreate(e);
134
+ for (const e of on) if (!runsOnWebGPU(e._def)) throw e._def.fuse ? glslOnly(e) : onlyCreate(e); // the rule the picture menu's "runs here" reads too
108
135
  // Same effects, same build, same samples: the graph is current (a set() of a number param never gets here)
109
- const key = `${samples}|${buffers}|${on.map(e => e.name).join(',')}`;
136
+ const key = `${samples}|${buffers}|${room}|${on.map(e => e.name).join(',')}`;
110
137
  if (post._pipe?.key === key && post._pipe.camera === camera) return;
111
138
  let P = post._pipe;
112
139
  if (!P) P = post._pipe = { pipeline: new RenderPipeline(renderer), scenePass: null, samples: -1, buffers: '', key: null, order: [] };
113
140
  P.key = null; // the graph is coming down: when a node() throws below, PostFX syncs the old list again, and that sync must rebuild, not find its key current
141
+ P.room = room; P.packed = packed;
114
142
  if (P.samples !== samples || P.buffers !== `${buffers}` || P.camera !== camera) {
115
143
  P.scenePass?.dispose(); P.scenePass = pass(scene, camera, { samples }); P.samples = samples; P.buffers = `${buffers}`; P.camera = camera;
116
- if (buffers.length) P.scenePass.setMRT(mrt({ output, ...Object.fromEntries(buffers.map(b => [b, BUFFERS[b]])) }));
144
+ if (buffers.length) P.scenePass.setMRT(mrt({ output, ...targets }));
145
+ for (const b of Object.keys(targets)) if (BYTE_BUFFERS.includes(b)) P.scenePass.getTexture(b).type = UnsignedByteType;
146
+ P.stages = []; // a new scene pass (samples, MRT, camera): every stage reads it, none is kept
117
147
  }
118
- // Every structural change rebuilds every effect's nodes: an effect's input is the node before it, which changed too
119
- for (const e of post._list) { e._impl?.dispose?.(); e._impl = null; }
120
- const size = post._size(), order = [];
148
+ const size = post._size();
121
149
  const ctxOf = (e, made) => ({ engine: post.engine, scene, camera, width: size.x, height: size.y, params: paramsOf(e), scenePass: P.scenePass,
122
- tsl: TSL, fx: FX, display: displayFor(made), p: uniformsOf(e) });
150
+ buffer: b => (b === 'metalRough' && P.packed ? P.scenePass.getTextureNode('velocity').zw : P.scenePass.getTextureNode(b)), tsl: TSL, fx: FX, display: displayFor(made), p: uniformsOf(e), borrowRenderer });
123
151
  // the effect's node is built only when the pipeline first draws: errors then, and statements lost outside an Fn, name the effect
124
152
  const run = (e, color) => {
125
153
  const label = `[threedog] post effect '${e.name}'`;
@@ -128,29 +156,49 @@ const webgpuPost = {
128
156
  const build = (e, color) => {
129
157
  const made = [];
130
158
  e._impl = { nodes: made, dispose() { for (const n of made) n.dispose?.(); made.length = 0; } };
131
- order.push(e.name);
132
159
  e._read = new Set(); e._building = true;
133
160
  try {
134
161
  if (e._def.fuse) {
135
162
  const f = e._def.fuse, c = ctxOf(e, made);
136
163
  return f.tsl(color, screenUV, { ...c, time, resolution: screenSize, input: f.reads ? c.display.texture(color) : null });
137
164
  }
138
- return e._def.node(color, ctxOf(e, made));
165
+ const out = e._def.node(color, ctxOf(e, made));
166
+ // a node that calls renderOutput() itself is tone mapped a second time by the engine's own output stage: said once, never guessed away
167
+ // (an output stage the INPUT already had is the engine's own, for ldr / final effects)
168
+ if (e.slot !== 'tone' && out?.traverse) {
169
+ const had = new Set(); color.traverse(x => x.isRenderOutputNode && had.add(x));
170
+ let again = false; out.traverse(x => { if (x.isRenderOutputNode && !had.has(x)) again = true; });
171
+ if (again) warnOnce(OUTPUT_TWICE(e.name));
172
+ }
173
+ return out;
139
174
  } finally { e._building = false; }
140
175
  };
141
176
  const slot = s => on.filter(e => e.slot === s);
142
- let color = P.scenePass.getTextureNode();
143
- const sceneFx = slot('scene')[0];
144
- if (sceneFx) color = run(sceneFx, color); else order.push('scene render');
145
- for (const e of slot('hdr')) color = run(e, color);
146
- const toneFx = slot('tone')[0]; // a game's tone stage replaces renderOutput (it outputs display color itself)
147
- if (toneFx) color = run(toneFx, color); else { color = renderOutput(color); order.push('output (tone mapping)'); }
148
- for (const e of [...slot('ldr'), ...slot('final')]) color = run(e, color);
177
+ // the chain as stages: an effect handle, or the engine's own 'scene render' / 'output (tone mapping)' (a game's tone stage replaces renderOutput)
178
+ const want = [slot('scene')[0] ?? SCENE, ...slot('hdr'), slot('tone')[0] ?? OUTPUT, ...slot('ldr'), ...slot('final')];
179
+ // Why stages are kept: an effect's input is the node before it, so only what follows the first changed stage has to be rebuilt. Toggling a
180
+ // cheap final effect left voxel GI re-voxelising and TRAA / reflections losing their history (GPT review l2-render 5). A stage is the same when
181
+ // it is the same effect at the same place and still holds the nodes it was built with (set() of a baked-in param or freeImpl dropped them)
182
+ const was = P.stages ?? [];
183
+ let k = 0;
184
+ while (k < want.length && k < was.length && was[k].e === want[k] && (typeof want[k] === 'string' || want[k]._impl === was[k].impl)) k++;
185
+ const kept = new Set(was.slice(0, k).map(s => s.e));
186
+ for (const e of post._list) if (!kept.has(e)) { e._impl?.dispose?.(); e._impl = null; }
187
+ const stages = was.slice(0, k);
188
+ P.stages = stages; // set before the build: a node() that throws below leaves only stages that are still whole
189
+ let color = k ? stages[k - 1].out : P.scenePass.getTextureNode();
190
+ for (const w of want.slice(k)) {
191
+ if (w === OUTPUT) color = renderOutput(color);
192
+ else if (w !== SCENE) color = run(w, color);
193
+ stages.push({ e: w, impl: typeof w === 'string' ? null : w._impl, out: color });
194
+ }
195
+ const order = stages.map(s => (typeof s.e === 'string' ? s.e : s.e.name));
149
196
  P.pipeline.outputColorTransform = false;
150
197
  P.pipeline.outputNode = color; P.pipeline.needsUpdate = true;
151
198
  P.output = color; P.order = order; P.key = key;
152
199
  },
153
200
  dispose(post) {
201
+ if (post._pipeOut) { post._pipeOut.scenePass.dispose(); post._pipeOut.pipeline.dispose(); post._pipeOut = null; }
154
202
  const P = post._pipe;
155
203
  if (!P) return;
156
204
  P.scenePass?.dispose(); P.pipeline.dispose(); post._pipe = null;
@@ -159,7 +207,8 @@ const webgpuPost = {
159
207
  sceneTarget: () => null,
160
208
  // target: the pipeline's last quad draws into the renderer's current target (pass() nodes put it back after their own renders)
161
209
  render(post, dt, target = null) {
162
- if (!post._pipe) post._sync();
210
+ // a chain built before start() had no device to check against: the first frame after it rebuilds once and checks (sync's key holds the room)
211
+ if (!post._pipe || post._pipe.room !== roomOf(post.engine.renderer)) post._sync();
163
212
  onTarget(post.engine.renderer, target, () => post._pipe.pipeline.render());
164
213
  },
165
214
  /**
@@ -171,15 +220,26 @@ const webgpuPost = {
171
220
  * MSAA: the renderer's own samples (made with the default antialias), so an effect-free frame needs no pipeline; a runtime switch away from
172
221
  * them runs the pipeline with pass() samples (PostFX active).
173
222
  */
174
- direct(post, target = null) { const { renderer, scene, camera } = post.engine; onTarget(renderer, target, () => renderer.render(scene, camera)); },
223
+ direct(post, target = null) {
224
+ const { renderer, scene, camera } = post.engine;
225
+ if (!target) { renderer.render(scene, camera); return; }
226
+ // a target gets the canvas's pixels too (tone mapped, output color space): three's plain draw into a target is linear. A small pipeline, scene pass -> renderOutput,
227
+ // kept for the next call (a minimap asks every frame) and freed with the chain
228
+ let O = post._pipeOut;
229
+ if (!O || O.camera !== camera || O.scene !== scene) { // engine.scene / engine.camera can be replaced: the pass node holds the ones it was made with
230
+ O?.scenePass.dispose(); O?.pipeline.dispose();
231
+ const scenePass = pass(scene, camera, { samples: 0 }), pipeline = new RenderPipeline(renderer);
232
+ pipeline.outputColorTransform = false; pipeline.outputNode = renderOutput(scenePass.getTextureNode());
233
+ O = post._pipeOut = { pipeline, scenePass, camera, scene };
234
+ }
235
+ onTarget(renderer, target, () => O.pipeline.render());
236
+ },
175
237
  };
176
238
 
177
- /** Run draw with target set (null: as it is, the canvas), then put the previous target back */
239
+ /** Run draw with target set (null: as it is, the canvas), the renderer borrowed and given back */
178
240
  function onTarget(r, target, draw) {
179
241
  if (!target) { draw(); return; }
180
- const prev = r.getRenderTarget();
181
- r.setRenderTarget(target);
182
- try { draw(); } finally { r.setRenderTarget(prev); }
242
+ borrowRenderer(r, () => { r.setRenderTarget(target); draw(); });
183
243
  }
184
244
 
185
245
  registerWebGPUPart('post', Object.freeze(webgpuPost));
@@ -11,7 +11,7 @@
11
11
  // only GLSL throws [webgpu-needs-tsl] by name on this renderer; the GLSL form keeps drawing on WebGLRenderer unchanged.
12
12
  import * as TSL from 'three/tsl';
13
13
  import { MeshBasicNodeMaterial, BackSide } from 'three/webgpu';
14
- import { noise } from './noise.tsl.js';
14
+ import { noise, hash } from './noise.tsl.js';
15
15
  import * as FX from './library.tsl.js';
16
16
  import { uniforms as engineUniforms, valueNode } from './uniforms.tsl.js';
17
17
  import { codedError } from '../../core/base/errorHints.js';
@@ -19,7 +19,7 @@ import { registerWebGPUPart } from '../backend.js';
19
19
  import { SKY as K } from '../fxNumbers.js';
20
20
 
21
21
  const { Fn, positionGeometry, varying, float, vec2, vec3, vec4, select, mix, pow, max, dot,
22
- floor, fract, step, smoothstep, clamp, normalize, If } = TSL;
22
+ floor, step, smoothstep, clamp, normalize, If } = TSL;
23
23
 
24
24
  /** @template {string} T @typedef {import('three/webgpu').Node<T>} N */
25
25
  /**
@@ -47,12 +47,6 @@ function nodesOf(u, engine) {
47
47
  return n;
48
48
  }
49
49
 
50
- /** GLSL h3 (the star hash) */
51
- const h3 = Fn(/** @param {[N<'vec3'>]} a */ ([p0]) => {
52
- const p = fract(p0.mul(K.starMul).add(K.starAdd)).mul(K.starScale);
53
- return fract(p.x.mul(p.y).mul(p.z).mul(p.x.add(p.y).add(p.z)));
54
- });
55
-
56
50
  /** clouds dim toward SKY.nightDim at night (GLSL nightDim + (1 - nightDim) * (1 - night)) */
57
51
  const nightDim = (/** @type {SkyNodes} */ U) => U.uNight.oneMinus().mul(1 - K.nightDim).add(K.nightDim);
58
52
 
@@ -141,7 +135,7 @@ function domeColor(U, kind, clouds, layers) {
141
135
  col.assign(mix(col, cl.rgb, cl.a)); clA.assign(cl.a);
142
136
  });
143
137
  // stars behind the clouds, dimmed by the weather's cover (see the GLSL comment in shader.js)
144
- const star = step(U.uStars.oneMinus(), h3(g)).mul(U.uNight).mul(smoothstep(0, K.starFade, d.y)).mul(clA.oneMinus())
138
+ const star = step(U.uStars.oneMinus(), hash(vec2(g.x.add(g.z.mul(K.starZ)), g.y))).mul(U.uNight).mul(smoothstep(0, K.starFade, d.y)).mul(clA.oneMinus())
145
139
  .mul(clamp(U.uWeatherCloud, 0, 1).mul(U.uStarCloudDim).oneMinus());
146
140
  col.addAssign(vec3(star));
147
141
  // fog band (fog.js DOME_FOG): always built, switched by uFogBand
@@ -6,18 +6,24 @@
6
6
 
7
7
  /** threedogWind: sway = sin(t * (speed + gust * uWind) + origin . phase) * weight + sin(t * speed2 + origin . phase2) * weight2; lean along x, side share on z */
8
8
  export const WIND = Object.freeze({ speed: 1.2, gust: 0.6, phase: [0.31, 0.23], weight: 0.6, speed2: 2.9, phase2: [0.77, -0.4], weight2: 0.4, lean: 0.4, side: 0.6 });
9
- /** threedogHash: fract(sin(dot(p, dir)) * scale) */
10
- export const HASH = Object.freeze({ dir: [127.1, 311.7], scale: 43758.5453 });
9
+ /** threedogHash: the x of pcg2d (Jarzynski & Olano 2020, "Hash Functions for GPU Rendering") on p's float bits (public) or the cell floor(p) (engine noise), as uints:
10
+ * v = v * mul + add; v.x += v.y * mul; v.y += v.x * mul; v ^= v >> 16; v.x += v.y * mul; x ^= x >> 16; value = (x >> 8) / 2^24, so 0 <= value < 1.
11
+ * Why integers and not the usual sin hash: sin of large arguments differs between GPUs and between GLSL and WGSL, so WebGL and WebGPU drew different
12
+ * patterns; uint multiply / xor / shift wrap the same way everywhere, and a 24-bit uint turns into a float exactly. */
13
+ export const HASH = Object.freeze({ mul: 1664525, add: 1013904223 });
14
+ /** A whole-cell offset as the uint it adds to a cell's first pcg2d step (n * mul, wrapped to 32 bits): what the dabs add per salt @param {number} n */
15
+ export const hashOffset = n => Math.imul(n, HASH.mul) >>> 0;
11
16
  /** threedogCloudShadow: two noise octaves (weight, then weight2 at octave x the scale), cover edge width */
12
17
  export const CLOUD = Object.freeze({ weight: 0.65, octave: 2.3, weight2: 0.35, edge: 0.25 });
13
18
 
14
19
  /** threedogDetailNoise (render/detail.js): fbm octave step (p = p * lacunarity + offset), paper = fbm * paper[0] + stretched noise * paper[1]
15
20
  * at (x * paperStretch[0], y * paperStretch[1]); stroke = smoothstep(stroke[0], stroke[1], fbm(x, y * strokeStretch)); dabs: first weight, then * dabFall per octave */
16
21
  export const DETAIL = Object.freeze({ lacunarity: 2.03, offset: 17, paper: [0.65, 0.35], paperStretch: [7, 0.9], stroke: [0.15, 0.85], strokeStretch: 1.7, dabWeight: 0.85, dabFall: 0.6 });
17
- /** The sky dome (modules/sky/shader.js, clouds.js): star hash h3 = fract(p * mul + add) * scale; sun glow power; sun-below-horizon cut-off;
22
+ /** The sky dome (modules/sky/shader.js, clouds.js): stars = threedogHash of the star cell g as (g.x + g.z * starZ, g.y) (no two cells of a
23
+ * star grid up to starZ / 2 per side share a value); sun glow power; sun-below-horizon cut-off;
18
24
  * stars fade in over dir.y 0..starFade; clouds dim to nightDim at night; plane tone smoothstep(tone); cumulus fbm step / normalizer,
19
25
  * sun-ward probe step, cover share, core width, shading (rim boost, core darkening) */
20
- export const SKY = Object.freeze({ starMul: 0.3183099, starAdd: 0.1, starScale: 17, glowPower: 12, sunCut: 0.05, starFade: 0.25, nightDim: 0.35,
26
+ export const SKY = Object.freeze({ starZ: 4096, glowPower: 12, sunCut: 0.05, starFade: 0.25, nightDim: 0.35,
21
27
  planeTone: [0.3, 0.8], lacunarity: 2.03, offset: 3.7, norm: 0.9375, toSun: 0.12, cover: 0.9, core: 0.35, rim: 0.5, coreDark: 0.45 });
22
28
 
23
29
  /** Luminance weights: Rec. 709 for light (render/lighting.js, the sky's own light), Rec. 601 for a detail texture's alpha. Two sets on purpose: moving either shifts pictures */
@@ -0,0 +1,107 @@
1
+ // Impostor cards for far plants (vegetation.define({ impostor })): bake N views around a model into array textures (albedo + normal, alpha = coverage),
2
+ // then draw each far plant as a card that turns to the camera and samples the nearest view, lit live through the baked normals.
3
+ // Why bake from the species' own model and materials: the card keeps the game's colours, alpha cut and lighting model; the engine adds no look.
4
+ // Why one array layer per view (not a flat atlas): low mips of neighbouring views never bleed into each other.
5
+ // Why a ring of views (not octahedral): far trees are seen from near eye level in a follow camera, and a ring spends every texel on the side views.
6
+ // WebGPU route only (also WebGPURenderer's WebGL2 backend); registered as a WebGPU part like the other .tsl.js files, so WebGL bundles stay as they are.
7
+ import * as THREE from 'three/webgpu'; // three/webgpu, not three: threedog/tsl stays WebGL-free (both share three.core.js)
8
+ import { MeshBasicNodeMaterial, MeshLambertNodeMaterial, MeshStandardNodeMaterial, MeshToonNodeMaterial } from 'three/webgpu';
9
+ import { attribute, cameraPosition, cameraViewMatrix, positionGeometry, vec2, vec3, vec4, float, int, atan, cos, sin, floor, fract, texture, varying, uv, normalLocal, faceDirection, uniform } from 'three/tsl';
10
+ import { registerWebGPUPart, holdRenderer, releaseRenderer } from './backend.js';
11
+ import { season } from './fx/season.tsl.js';
12
+
13
+ const TAU = Math.PI * 2;
14
+
15
+ /** Bounds of a plant around its own vertical axis: the card spans [-r, r] across and [minY, maxY] up (plants stand on their origin) */
16
+ function bounds(geometry) {
17
+ const p = geometry.attributes.position;
18
+ let r = 0, lo = Infinity, hi = -Infinity;
19
+ for (let i = 0; i < p.count; i++) { r = Math.max(r, Math.hypot(p.getX(i), p.getZ(i))); lo = Math.min(lo, p.getY(i)); hi = Math.max(hi, p.getY(i)); }
20
+ // a small margin so mip filtering of the outermost leaves never reaches the card edge
21
+ const m = 1.04, h = (hi - lo) || 1;
22
+ return { radius: (r || 0.5) * m, minY: lo - h * (m - 1) / 2, height: h * m };
23
+ }
24
+
25
+ /** What a material renders into the normal layers: its object-space normal packed 0..1, and its own alpha cut so leaf cards keep their outline */
26
+ function normalMaterial(m) {
27
+ const alpha = m?.map ? texture(m.map, uv()).a : float(1);
28
+ const n = new MeshBasicNodeMaterial({ side: m?.side ?? THREE.FrontSide });
29
+ n.colorNode = vec4(normalLocal.mul(faceDirection).normalize().mul(0.5).add(0.5), alpha);
30
+ n.alphaTest = m?.alphaTest || (m?.transparent || m?.map ? 0.5 : 0);
31
+ return n;
32
+ }
33
+
34
+ /**
35
+ * Render the views. src: { geometry, material (one or an array matching the geometry's groups) }, the species' own, unpatched.
36
+ * Albedo comes from the game's materials under a white ambient light of intensity PI: three's diffuse BRDF divides irradiance by PI, so the
37
+ * layer holds the surface colour (vertex colours and maps included) with no sun baked in; the live scene lights the card.
38
+ * @returns {{ albedo: THREE.Texture, normal: THREE.Texture, views: number, radius: number, minY: number, height: number, dispose(): void }}
39
+ */
40
+ function bake(renderer, src, { views = 8, size = 128 } = {}) {
41
+ const b = bounds(src.geometry);
42
+ // depth > 1: an array texture, one layer per view (three sets isArrayTexture from the depth)
43
+ const mk = () => new THREE.RenderTarget(size, size, { depth: views, type: THREE.HalfFloatType, generateMipmaps: true, minFilter: THREE.LinearMipmapLinearFilter, magFilter: THREE.LinearFilter });
44
+ const scene = new THREE.Scene(), holder = new THREE.Group(), mesh = new THREE.Mesh(src.geometry, src.material);
45
+ holder.add(mesh); scene.add(holder, new THREE.AmbientLight(0xffffff, Math.PI));
46
+ const cam = new THREE.OrthographicCamera(-b.radius, b.radius, b.minY + b.height, b.minY, 0.01, b.radius * 6);
47
+ cam.position.set(0, 0, b.radius * 3); cam.lookAt(0, 0, 0); cam.updateMatrixWorld();
48
+ const albedo = mk(), normal = mk(), normals = [src.material].flat().map(normalMaterial);
49
+ let done = false;
50
+ // the renderer is borrowed mid-frame: everything the bake changes is put back, whether it finishes or throws (render/backend.js holdRenderer)
51
+ const held = holdRenderer(renderer);
52
+ try {
53
+ renderer.setClearColor(0x000000, 0); renderer.autoClear = true;
54
+ for (const [rt, mat] of [[albedo, src.material], [normal, Array.isArray(src.material) ? normals : normals[0]]]) {
55
+ mesh.material = mat;
56
+ for (let i = 0; i < views; i++) {
57
+ // view i is the plant seen from yaw i/N around it: turning the plant by -yaw shows that side to a camera on +Z (the card's maths in cardMaterial)
58
+ holder.rotation.y = -i * TAU / views; holder.updateMatrixWorld(true);
59
+ renderer.setRenderTarget(rt, i);
60
+ renderer.render(scene, cam);
61
+ }
62
+ }
63
+ done = true;
64
+ } finally {
65
+ releaseRenderer(held);
66
+ for (const n of normals) n.dispose();
67
+ if (!done) { albedo.dispose(); normal.dispose(); } // a failed bake leaves no render targets behind
68
+ }
69
+ return { albedo: albedo.texture, normal: normal.texture, views, ...b, dispose() { albedo.dispose(); normal.dispose(); } };
70
+ }
71
+
72
+ /**
73
+ * The card material. Per instance (InstancedBufferGeometry): aCenter (world position of the plant), aShape (yaw, across scale, up scale; 0 scale =
74
+ * felled, the card collapses to a point), aTint (instance colour, as InstancedMesh's instanceColor tints the mesh). The material class follows the
75
+ * species' first material (toon stays toon, unlit stays unlit), so the card answers the scene's lights the way the mesh does.
76
+ */
77
+ function cardMaterial(src, b) {
78
+ const m0 = [src.material].flat()[0], type = m0?.type ?? '';
79
+ const C = /Toon/.test(type) ? MeshToonNodeMaterial : /Basic/.test(type) ? MeshBasicNodeMaterial : /Lambert|Phong/.test(type) ? MeshLambertNodeMaterial : MeshStandardNodeMaterial;
80
+ const m = /** @type {any} */ (new C());
81
+ if (m0?.gradientMap && 'gradientMap' in m) m.gradientMap = m0.gradientMap;
82
+ if (m.isMeshStandardNodeMaterial) { m.roughness = m0?.roughness ?? 1; m.metalness = 0; }
83
+ m.alphaTest = 0.5;
84
+ const N = b.views, center = attribute('aCenter', 'vec3'), shape = attribute('aShape', 'vec3');
85
+ const toCam = cameraPosition.sub(center), ang = /** @type {any} */ (atan)(toCam.x, toCam.z); // the camera's yaw seen from the plant
86
+ // nearest baked view in the plant's own frame; fract keeps it positive whatever the yaw (a % of a negative stays negative in WGSL)
87
+ const cell = floor(fract(ang.sub(shape.x).div(TAU).add(0.5 / N).add(4)).mul(N));
88
+ const right = vec3(cos(ang), 0, sin(ang).negate());
89
+ const across = uniform(b.radius * 2), up = uniform(b.height), minY = uniform(b.minY);
90
+ const pg = /** @type {any} */ (positionGeometry);
91
+ m.positionNode = center.add(right.mul(pg.x.mul(across).mul(shape.y))).add(vec3(0, pg.y.mul(up).add(minY).mul(shape.z), 0));
92
+ // the layers come out upside down against the card's uv on both WebGPU backends (render-target rows), so read them flipped
93
+ const layer = int(/** @type {any} */ (varying(cell)).add(0.5)), st = vec2(uv().x, uv().y.oneMinus());
94
+ const alb = texture(b.albedo, st).depth(layer);
95
+ // the season tint the mesh gets from its patches (effects on), so autumn reaches the far cards too; the bake itself is untinted
96
+ const rgb = alb.rgb.mul(attribute('aTint', 'vec3'));
97
+ m.colorNode = vec4(src.season ? season(rgb, 0) : rgb, alb.a);
98
+ if (!m.isMeshBasicNodeMaterial) {
99
+ // baked normal is in the plant's own frame: turn it by the plant's yaw into the world, then into view space (what normalNode takes)
100
+ const n = texture(b.normal, st).depth(layer).rgb.mul(2).sub(1), y = shape.x, c = cos(y), s = sin(y);
101
+ const world = vec3(n.x.mul(c).add(n.z.mul(s)), n.y, n.z.mul(c).sub(n.x.mul(s)));
102
+ m.normalNode = cameraViewMatrix.mul(vec4(world, 0)).xyz.normalize();
103
+ }
104
+ return m;
105
+ }
106
+
107
+ registerWebGPUPart('impostor', Object.freeze({ bake, cardMaterial }));
@@ -38,8 +38,40 @@ vec3 threedogRim(vec3 normal, vec3 viewDir, vec3 color, float strength, float po
38
38
  Object.assign(THREE.ShaderChunk, { threedog_lighting: LIGHTING_CHUNK }); // the same registry effects.js fills
39
39
 
40
40
  // Functions need getShadow and the light uniforms, which exist only after these includes: they go after shadowmap_pars_fragment
41
+ // With cascades (render/cascades.js, the 'csm' patch: USE_CSM) the sun is N directional lights with one color and direction, one shadow map each: the shadow is
42
+ // the map of the cascade this fragment's depth falls in, picked the way three's CSMShader picks it (linear depth against CSM_cascades; the last one takes the rest).
43
+ // Cascade 0 alone read as "lit" past its far edge, so wrap added sun light inside shadows and shadowTint went missing there.
44
+ // With CSM_FADE (the engine default) CSMShader adds each cascade's light weighted by its margin ratio and fades the last one out; the sun's light is linear
45
+ // in the shadow factor, so the same sum on the factor gives the same result, from the same CSM_cascades values.
41
46
  const SUN = `float threedogSunShadow(){
42
- #if NUM_DIR_LIGHTS > 0 && defined( USE_SHADOWMAP ) && NUM_DIR_LIGHT_SHADOWS > 0
47
+ #if NUM_DIR_LIGHTS > 0 && defined( USE_SHADOWMAP ) && NUM_DIR_LIGHT_SHADOWS > 0 && defined( USE_CSM ) && defined( CSM_CASCADES )
48
+ float s = 1.0, sh, linearDepth = vViewPosition.z / ( shadowFar - cameraNear );
49
+ #ifdef CSM_FADE
50
+ vec2 cascade; float cascadeCenter, margin, csmx, csmy, ratio; bool lastOne;
51
+ s = 0.0; // each cascade adds its share (CSMShader: reflectedLight = mix( before, before + this cascade's light, ratio ))
52
+ #endif
53
+ #pragma unroll_loop_start
54
+ for ( int i = 0; i < NUM_DIR_LIGHT_SHADOWS; i ++ ) {
55
+ #ifdef CSM_FADE
56
+ cascade = CSM_cascades[ i ]; cascadeCenter = ( cascade.x + cascade.y ) / 2.0;
57
+ margin = 0.25 * pow( linearDepth < cascadeCenter ? cascade.x : cascade.y, 2.0 );
58
+ csmx = cascade.x - margin / 2.0; csmy = cascade.y + margin / 2.0; lastOne = UNROLLED_LOOP_INDEX == CSM_CASCADES - 1;
59
+ if ( linearDepth >= csmx && ( linearDepth < csmy || lastOne ) ) {
60
+ ratio = clamp( min( linearDepth - csmx, csmy - linearDepth ) / margin, 0.0, 1.0 );
61
+ sh = receiveShadow ? getShadow( directionalShadowMap[ i ], directionalLightShadows[ i ].shadowMapSize, directionalLightShadows[ i ].shadowIntensity,
62
+ directionalLightShadows[ i ].shadowBias, directionalLightShadows[ i ].shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;
63
+ sh = mix( 1.0, sh, lastOne && linearDepth > cascadeCenter ? ratio : 1.0 ); // the last cascade fades out to unshadowed
64
+ s += sh * ( !lastOne || linearDepth < cascadeCenter ? ratio : 1.0 ); // neighbours cross over across the margin
65
+ }
66
+ #else
67
+ if ( linearDepth >= CSM_cascades[ i ].x && linearDepth < CSM_cascades[ i ].y ) // past the last far edge three lights unshadowed: s stays 1
68
+ s = receiveShadow ? getShadow( directionalShadowMap[ i ], directionalLightShadows[ i ].shadowMapSize, directionalLightShadows[ i ].shadowIntensity,
69
+ directionalLightShadows[ i ].shadowBias, directionalLightShadows[ i ].shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;
70
+ #endif
71
+ }
72
+ #pragma unroll_loop_end
73
+ return s;
74
+ #elif NUM_DIR_LIGHTS > 0 && defined( USE_SHADOWMAP ) && NUM_DIR_LIGHT_SHADOWS > 0
43
75
  return receiveShadow ? getShadow( directionalShadowMap[ 0 ], directionalLightShadows[ 0 ].shadowMapSize, directionalLightShadows[ 0 ].shadowIntensity,
44
76
  directionalLightShadows[ 0 ].shadowBias, directionalLightShadows[ 0 ].shadowRadius, vDirectionalShadowCoord[ 0 ] ) : 1.0;
45
77
  #else
@@ -8,7 +8,8 @@ import * as THREE from 'three';
8
8
  import { readParams } from '../core/base/params.js';
9
9
  import { codedError, coded } from '../core/base/errorHints.js';
10
10
  import { warnOnce, fmt } from '../core/base/validate.js';
11
- import { mats, noteFillLight, noteEnvironment } from './lit.js';
11
+ import { mats } from './lit.js';
12
+ import { litTwice } from '../core/inspect/pictureChecks.js';
12
13
 
13
14
  const FORMAT = 'threedog-lightmap', VERSION = 1, MAGIC = 0x4d4c4454; // 'TDLM'
14
15
  const LOAD = { owner: { type: 'string', default: 'game', desc: 'who loaded it (describe().render.lightmap)' } };
@@ -18,7 +19,6 @@ const STRINGS = {
18
19
  fetch: 'engine.loadLightmap({file}): the file could not be read ({why}). Bake it with `threedog bake light`',
19
20
  missing: 'lightmap: {n} baked mesh(es) not in the scene or changed since the bake ({names}): they keep their old look. Load after the level is built, or bake again',
20
21
  moved: 'lightmap: {n} baked mesh(es) moved since the bake ({names}): baked light stays where it was. Moving things use a probe grid, not a lightmap',
21
- doubled: 'lightmap is added on top of {what}, which the bake already saw, so that light counts twice. Turn it down on the baked level, or bake without it',
22
22
  shared: 'lightmap: a baked mesh shares its material with an unbaked one ({names}): that mesh has no second UV set and samples the map wrongly. Give it its own material',
23
23
  };
24
24
 
@@ -35,8 +35,20 @@ function parse(buf) {
35
35
  if (!Number.isInteger(meta.size) || meta.size < 4 || !Array.isArray(meta.meshes)) throw bad('its table has no size or mesh list');
36
36
  const base = (8 + n + 7) & ~7, end = base + meta.size * meta.size * 8; // 8: the half floats and the 32-bit lists after them need aligned views
37
37
  if (end > buf.byteLength) throw bad('the file is cut short');
38
- for (const m of meta.meshes) if (end + m.at + (m.count * 3 + m.indices) * 4 > buf.byteLength) throw bad(`the data of mesh ${m.name} is cut short`);
39
- return { meta, base };
38
+ // every entry checked here, before load touches the scene: a typed-array view on a bad offset throws, and a value past the list scrambles the mesh,
39
+ // both half-way through the swaps if found there (GPT review l2-render 1)
40
+ const seen = new Set(), views = meta.meshes.map(m => {
41
+ const name = JSON.stringify(m?.name), whole = v => Number.isInteger(v) && v >= 0;
42
+ if (typeof m?.name !== 'string' || seen.has(m.name)) throw bad(`mesh ${name} has no name of its own in the table`);
43
+ seen.add(m.name);
44
+ if (![m.at, m.count, m.indices, m.vertices].every(whole) || m.at % 4 || !Array.isArray(m.matrix) || m.matrix.length !== 16 || !m.matrix.every(Number.isFinite))
45
+ throw bad(`the table entry of mesh ${name} is malformed (at, count, indices, vertices: whole numbers, at a multiple of 4; matrix: 16 numbers)`);
46
+ if (end + m.at + (m.count * 3 + m.indices) * 4 > buf.byteLength) throw bad(`the data of mesh ${name} is cut short`);
47
+ const at = end + m.at, from = new Uint32Array(buf, at, m.count), index = new Uint32Array(buf, at + m.count * 4, m.indices);
48
+ if (from.some(v => v >= m.vertices) || index.some(v => v >= m.count)) throw bad(`the data of mesh ${name} names a vertex past its own list`);
49
+ return { from, index, uv1: new Float32Array(buf, at + (m.count + m.indices) * 4, m.count * 2) };
50
+ });
51
+ return { meta, base, views };
40
52
  }
41
53
 
42
54
  /** Unwrapped geometry -> { vertices: the source's count, place: source vertex -> a vertex holding it now, or -1 }. A second file's list speaks of the source, not of the layout the first file left */
@@ -80,24 +92,21 @@ class Lightmap {
80
92
  }
81
93
  /** Meshes that moved, mapped materials shared with unmapped meshes, and what adds the light again. Runs on describe() and at load, never per frame */
82
94
  _checks() {
83
- const moved = [], doubled = [], shared = [], onMapped = new Set();
95
+ const moved = [], shared = [], onMapped = new Set();
84
96
  for (const [o] of this._entries) for (const m of mats(o)) onMapped.add(m);
85
97
  this._e.scene.traverseVisible(o => {
86
- if (noteFillLight(o, doubled)) return;
87
- if (o.isLightProbeGrid) doubled.push(`probe grid ${o.name}`);
88
- else if (o.isMesh && !this._entries.has(o) && mats(o).some(m => onMapped.has(m))) shared.push(o.name || `${o.type} ${o.id}`);
98
+ if (o.isMesh && !this._entries.has(o) && mats(o).some(m => onMapped.has(m))) shared.push(o.name || `${o.type} ${o.id}`);
89
99
  });
90
- noteEnvironment(this._e.scene, doubled);
91
100
  for (const [o, matrix] of this._entries) {
92
101
  o.updateWorldMatrix(true, false);
93
102
  if (o.matrixWorld.elements.some((v, i) => Math.abs(v - matrix[i]) > 1e-3)) moved.push(o.name);
94
103
  }
95
- return { moved, doubled, shared };
104
+ return { moved, shared };
96
105
  }
97
106
  /** describe().render.lightmap row */
98
107
  info() {
99
- const { moved, doubled, shared } = this._checks();
100
- return { file: this.file, size: this.size, meshes: this._entries.size, owner: this.owner, bakedOn: this.backend, skipped: this.skipped, missing: this.missing, moved, doubled, shared };
108
+ const { moved, shared } = this._checks();
109
+ return { file: this.file, size: this.size, meshes: this._entries.size, owner: this.owner, bakedOn: this.backend, skipped: this.skipped, missing: this.missing, moved, shared };
101
110
  }
102
111
  /** Take the map off the meshes and free it (the unwrapped geometry stays: it draws the same). Safe to call twice */
103
112
  remove() {
@@ -114,7 +123,7 @@ export const lightmapMethods = {
114
123
  * its second UV set and sets plain `material.lightMap`, on WebGL and WebGPU alike. Call it once the level is built, with its lights as they will be
115
124
  * played. Nothing runs per frame. Keep the sun real-time; the ambient light the bake saw (hemisphere, environment) has to go, or it counts twice.
116
125
  * A wrong file is refused with code `lightmap-data` and nothing is changed. `material.lightMapIntensity` is yours. describe().render.lightmap says what
117
- * was skipped, moved or doubled.
126
+ * was skipped or moved; describe().render.checks names light counted twice.
118
127
  * @example userData: floor.userData.static = true; // then: threedog bake light
119
128
  * const light = await engine.loadLightmap('light/level.lightmap');
120
129
  * hemi.intensity = 0;
@@ -131,31 +140,36 @@ export const lightmapMethods = {
131
140
  if (!res.ok) throw codedError('lightmap-data', fmt(STRINGS.fetch, { file, why: res.statusText }));
132
141
  buf = await res.arrayBuffer();
133
142
  }
134
- const { meta, base } = parse(/** @type {ArrayBuffer} */ (buf));
143
+ const { meta, base, views } = parse(/** @type {ArrayBuffer} */ (buf));
135
144
  const tex = new THREE.DataTexture(new Uint16Array(/** @type {ArrayBuffer} */ (buf), base, meta.size * meta.size * 4), meta.size, meta.size, THREE.RGBAFormat, THREE.HalfFloatType);
136
145
  tex.channel = 1; tex.minFilter = tex.magFilter = THREE.LinearFilter; tex.needsUpdate = true;
137
- this._lightmap?.remove();
138
- const set = new Lightmap(this, meta, tex, o.owner, typeof file === 'string' ? file : 'bytes');
139
- const binary = base + meta.size * meta.size * 8, names = new Map();
146
+ const set = new Lightmap(this, meta, tex, o.owner, typeof file === 'string' ? file : 'bytes'), names = new Map(), swaps = [];
140
147
  this.scene.traverse(x => { if (x.isMesh && x.name) names.set(x.name, x); });
141
- for (const m of meta.meshes) {
142
- const mesh = names.get(m.name);
143
- // the vertex count is what the bake's list was made from: another count means another mesh, and its UVs would be noise
144
- if (!mesh || mesh.isInstancedMesh || (layouts.get(mesh.geometry)?.vertices ?? mesh.geometry.attributes.position.count) !== m.vertices) { set.missing.push(m.name); continue; }
145
- const at = binary + m.at, old = mesh.geometry, from = new Uint32Array(/** @type {ArrayBuffer} */ (buf), at, m.count), list = gatherList(old, from);
146
- if (!list) { set.missing.push(m.name); continue; }
147
- mesh.geometry = relayout(old, list, new Uint32Array(/** @type {ArrayBuffer} */ (buf), at + m.count * 4, m.indices),
148
- new Float32Array(/** @type {ArrayBuffer} */ (buf), at + (m.count + m.indices) * 4, m.count * 2));
149
- noteLayout(mesh.geometry, m.vertices, from);
148
+ // two steps, so a failure leaves the scene as it was: every new geometry is made first, nothing in the scene touched; only then the old map goes and all swap at once
149
+ try {
150
+ meta.meshes.forEach((m, i) => {
151
+ const mesh = names.get(m.name);
152
+ // the vertex count is what the bake's list was made from: another count means another mesh, and its UVs would be noise
153
+ if (!mesh || mesh.isInstancedMesh || (layouts.get(mesh.geometry)?.vertices ?? mesh.geometry.attributes.position.count) !== m.vertices) { set.missing.push(m.name); return; }
154
+ const { from, index, uv1 } = views[i], list = gatherList(mesh.geometry, from);
155
+ if (!list) { set.missing.push(m.name); return; }
156
+ swaps.push({ mesh, m, from, geometry: relayout(mesh.geometry, list, index, uv1) });
157
+ });
158
+ } catch (err) { for (const x of swaps) x.geometry.dispose(); tex.dispose(); throw err; }
159
+ this._lightmap?.remove();
160
+ for (const { mesh, m, from, geometry } of swaps) {
161
+ const old = mesh.geometry;
162
+ mesh.geometry = geometry;
163
+ noteLayout(geometry, m.vertices, from);
150
164
  old.dispose(); // nothing else frees its GPU buffers; a mesh that shares it just uploads it again
151
165
  for (const x of mats(mesh)) { x.lightMap = tex; x.needsUpdate = true; }
152
166
  set._entries.set(mesh, m.matrix);
153
167
  }
154
168
  this._lightmap = set;
155
- const { moved, doubled, shared } = set._checks(), first = l => l.slice(0, 3).join(', ');
169
+ const { moved, shared } = set._checks(), twice = litTwice(this), first = l => l.slice(0, 3).join(', ');
156
170
  if (set.missing.length) warnOnce(coded('lightmap-check', fmt(STRINGS.missing, { n: set.missing.length, names: first(set.missing) })));
157
171
  if (moved.length) warnOnce(coded('lightmap-check', fmt(STRINGS.moved, { n: moved.length, names: first(moved) })));
158
- if (doubled.length) warnOnce(coded('lightmap-check', fmt(STRINGS.doubled, { what: doubled.join(', ') })));
172
+ if (twice) warnOnce(coded('lightmap-check', twice));
159
173
  if (shared.length) warnOnce(coded('lightmap-check', fmt(STRINGS.shared, { names: first(shared) })));
160
174
  return set;
161
175
  },
package/render/lights.js CHANGED
@@ -5,6 +5,7 @@
5
5
  import { engineOwned } from '../core/scene/things.js';
6
6
  import * as THREE from 'three';
7
7
  import { defineOwned } from '../core/ops/owned.js';
8
+ import { onTierChange } from '../core/scene/tier.js';
8
9
 
9
10
  const BOX = 30, SNAP = 0.5;
10
11
 
@@ -17,13 +18,28 @@ export function createDefaultLights(engine, { add = true } = {}) {
17
18
  // the one place these defaults live: nothing writes them later, a sky included, so what a game writes on engine.lights.sun stays.
18
19
  // baseline shadow box: 2048 map over 60 m around engine.focus (~3 cm texels; 1024 on a low-tier device, a quarter of the fill cost), PCF with a small blur
19
20
  // radius = soft edges; bias / normalBias keep acne off flat ground and slopes without visible peter-panning at this texel size. bias is in the shadow
20
- // camera's 0-1 depth (near 1 - far 250 m): -0.0001 = 2.5 cm; the old -0.0005 was 12 cm and cut the shadow at the base of things standing on the ground
21
- const sc = sun.shadow.camera, map = engine.tier === 'low' ? 1024 : 2048;
21
+ // camera's 0-1 depth (near 1 - far 250 m): -0.0001 = 2.5 cm; the old -0.0005 was 12 cm and cut the shadow at the base of things standing on the ground.
22
+ // radius is in texels (three's PCF offsets are radius x texel), so it scales with the map: ~9 cm of blur in meters on both tiers. A fixed 3 doubled the
23
+ // blur with the low tier's twice-as-large texels, the soft smear of low-tier shadows. Never under 2 texels: below that PCF's few taps no longer cover the
24
+ // map's own grid and the edges show stair steps (the picture check's shadow-jag fires at 1.5 on the 1024 map), so the low tier blurs ~12 cm, not 18
25
+ const sc = sun.shadow.camera, sizeFor = () => engine.tier === 'low' ? 1024 : 2048, radiusFor = size => Math.max(2, 3 * size / 2048);
26
+ let map = sizeFor();
22
27
  sun.shadow.mapSize.set(map, map);
23
28
  sc.left = sc.bottom = -BOX; sc.right = sc.top = BOX; sc.near = 1; sc.far = 250; sc.updateProjectionMatrix();
24
- sun.shadow.bias = -0.0001; sun.shadow.normalBias = 0.04; sun.shadow.radius = 3;
29
+ sun.shadow.bias = -0.0001; sun.shadow.normalBias = 0.04; sun.shadow.radius = radiusFor(map);
25
30
  // add: false (createEngine({ lights: false })): the objects still exist so engine.lights.sun / hemi and the sky module never hit undefined, but they
26
31
  // are not in the scene, so nothing is lit by them and they cost no shader light slots; the game brings all its own lights
32
+ // the size is a tier default: it follows the tier (a stored preset arrives after this runs, settings installs last) unless the game wrote another size
33
+ // on the sun, which stays. engine.shadows.mapSize is the one resize path (reallocates the map on WebGL, the cascades' maps too); the engine lives as long as this listener
34
+ // One rule for both tier defaults, size and radius: a value still at the engine's default for the old tier follows the tier, any other value is the
35
+ // game's and stays. Known edge: a game that writes exactly the engine's default reads as untouched and still follows (no accessor: it would hide the
36
+ // value from engine.debug.watch / explain, which only hook plain properties)
37
+ onTierChange(engine, () => {
38
+ const was = map, next = map = sizeFor(), s = sun.shadow;
39
+ if (next === was) return;
40
+ if (s.mapSize.x === was && s.mapSize.y === was) { if (engine.shadows) engine.shadows.mapSize(sun, next); else s.mapSize.set(next, next); }
41
+ if (s.radius === radiusFor(was)) s.radius = radiusFor(next);
42
+ });
27
43
  engineOwned('lights', hemi, sun, sun.target); // the module's, not the game's, when the scene adopts what is added (core/scene/things.js)
28
44
  if (add) engine.scene.add(hemi, sun, sun.target);
29
45
  return { sun, hemi };