threedog 1.0.1 → 1.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (364) hide show
  1. package/CHANGELOG.md +90 -0
  2. package/README.md +1 -1
  3. package/core/assets/Animator.js +41 -3
  4. package/core/assets/Assets.js +100 -24
  5. package/core/assets/assetEntry.js +73 -20
  6. package/core/assets/assetHot.js +68 -16
  7. package/core/assets/assetLoad.js +6 -6
  8. package/core/assets/assetLod.js +9 -2
  9. package/core/assets/assetManifest.js +12 -2
  10. package/core/assets/assetPart.js +54 -0
  11. package/core/assets/ik.js +271 -0
  12. package/core/assets/modelNeeds.js +37 -0
  13. package/core/assets/namedModel.js +102 -29
  14. package/core/assets/nodeVisibility.js +15 -0
  15. package/core/audio/Audio.js +36 -4
  16. package/core/audio/audioReverb.js +99 -0
  17. package/core/audio/audioRules.js +1 -1
  18. package/core/audio/audioVoice.js +1 -1
  19. package/core/base/Events.js +14 -4
  20. package/core/base/Random.js +1 -1
  21. package/core/base/Vars.js +1 -1
  22. package/core/base/docRef.js +51 -0
  23. package/core/base/errorCodes.js +178 -126
  24. package/core/base/errorHints.js +9 -7
  25. package/core/base/errors.js +25 -10
  26. package/core/base/events.generated.js +2 -0
  27. package/core/base/freeParts.js +76 -0
  28. package/core/base/math.js +28 -0
  29. package/core/base/sections.js +5 -5
  30. package/core/base/validate.js +31 -3
  31. package/core/engine/Engine.js +16 -6
  32. package/core/engine/Loading.js +5 -3
  33. package/core/engine/copies.js +1 -1
  34. package/core/engine/headlessLoad.js +4 -1
  35. package/core/engine/lifecycle.js +32 -16
  36. package/core/engine/loop.js +71 -27
  37. package/core/engine/moduleSlots.js +2 -2
  38. package/core/engine/moduleTypes.js +3 -3
  39. package/core/engine/modules.js +65 -39
  40. package/core/engine/page.js +6 -3
  41. package/core/engine/services.js +6 -5
  42. package/core/engine/startup.js +5 -5
  43. package/core/input/Input.js +28 -14
  44. package/core/input/inputContext.js +28 -16
  45. package/core/input/inputKeyboard.js +31 -3
  46. package/core/input/inputPad.js +4 -0
  47. package/core/input/inputPointer.js +2 -1
  48. package/core/input/inputSeat.js +1 -1
  49. package/core/inspect/Budget.js +109 -19
  50. package/core/inspect/DebugOverrides.js +28 -4
  51. package/core/inspect/Describe.js +17 -9
  52. package/core/inspect/Inspect.js +4 -2
  53. package/core/inspect/InspectMaterials.js +3 -1
  54. package/core/inspect/InspectPerf.js +19 -9
  55. package/core/inspect/InspectScene.js +32 -7
  56. package/core/inspect/MaterialInfo.js +19 -2
  57. package/core/inspect/UrlState.js +46 -27
  58. package/core/inspect/catalog.js +28 -9
  59. package/core/inspect/debugView.js +2 -1
  60. package/core/inspect/describeRender.js +25 -13
  61. package/core/inspect/describeText.js +14 -6
  62. package/core/inspect/lightWatch.js +1 -1
  63. package/core/inspect/metadata.generated.js +35 -17
  64. package/core/inspect/pictureChecks.js +148 -0
  65. package/core/inspect/pictureMenu.js +84 -0
  66. package/core/inspect/pictureWriters.js +26 -6
  67. package/core/inspect/textureBytes.js +12 -2
  68. package/core/inspect/toolDoor.js +2 -4
  69. package/core/ops/Ops.js +11 -4
  70. package/core/ops/holds.js +27 -10
  71. package/core/ops/opsAtomic.js +15 -7
  72. package/core/ops/opsGuard.js +2 -2
  73. package/core/ops/opsRun.js +8 -7
  74. package/core/ops/sharedPoint.js +72 -21
  75. package/core/ops/stacks.js +56 -16
  76. package/core/saves/SaveStore.js +9 -3
  77. package/core/saves/Saves.js +32 -23
  78. package/core/saves/saveApply.js +96 -44
  79. package/core/saves/saveIds.js +1 -1
  80. package/core/saves/saveVersions.js +7 -5
  81. package/core/saves/session.js +17 -8
  82. package/core/saves/stateReplace.js +34 -15
  83. package/core/scene/Rays.js +52 -10
  84. package/core/scene/Views.js +13 -7
  85. package/core/scene/adaptive.js +144 -21
  86. package/core/scene/drawOnly.js +17 -0
  87. package/core/scene/gameLights.js +44 -3
  88. package/core/scene/sceneMethods.js +13 -11
  89. package/core/scene/stepPoses.js +11 -3
  90. package/core/scene/targeting.js +5 -3
  91. package/core/scene/thingOps.js +1 -1
  92. package/core/scene/tier.js +15 -0
  93. package/core/stream/Batching.js +30 -7
  94. package/core/stream/Stream.js +26 -7
  95. package/core/stream/batchGroups.js +2 -2
  96. package/core/stream/chunkStream.js +7 -5
  97. package/core/stream/prepare.js +77 -0
  98. package/core/time/skip.js +3 -1
  99. package/core/time/time.js +4 -2
  100. package/docs/AI.md +82 -83
  101. package/docs/API.md +16 -16
  102. package/docs/CODEMAP.md +16 -11
  103. package/docs/COMMANDS.md +31 -33
  104. package/docs/CONVENTIONS.md +37 -49
  105. package/docs/MIGRATING-0.8.md +2 -2
  106. package/docs/MIGRATING-1.0.md +2 -2
  107. package/docs/THREE.md +28 -35
  108. package/docs/api/assets.md +3 -1
  109. package/docs/api/audio.md +4 -2
  110. package/docs/api/budget.md +5 -0
  111. package/docs/api/cameraRig.md +2 -2
  112. package/docs/api/characters.md +10 -8
  113. package/docs/api/collision.md +6 -4
  114. package/docs/api/engine.md +16 -16
  115. package/docs/api/events.md +3 -2
  116. package/docs/api/ground.md +6 -5
  117. package/docs/api/hud.md +4 -2
  118. package/docs/api/input.md +5 -5
  119. package/docs/api/particles.md +2 -1
  120. package/docs/api/photo.md +3 -0
  121. package/docs/api/post.md +7 -4
  122. package/docs/api/quests.md +2 -2
  123. package/docs/api/rays.md +1 -2
  124. package/docs/api/saves.md +7 -7
  125. package/docs/api/settings.md +2 -2
  126. package/docs/api/tools.md +3 -1
  127. package/docs/api/vars.md +1 -1
  128. package/docs/api/vegetation.md +4 -2
  129. package/docs/api/world.md +1 -1
  130. package/docs/recipes/01-new-game.md +16 -17
  131. package/docs/recipes/02-npc.md +22 -18
  132. package/docs/recipes/03-items-pickups.md +37 -35
  133. package/docs/recipes/04-quests.md +15 -10
  134. package/docs/recipes/05-props-bake.md +101 -95
  135. package/docs/recipes/06-clock-events.md +28 -28
  136. package/docs/recipes/07-flow-scenes-pause.md +29 -26
  137. package/docs/recipes/08-weather-sky.md +52 -64
  138. package/docs/recipes/09-materials-lights-models.md +26 -17
  139. package/docs/recipes/10-blender-level.md +15 -10
  140. package/docs/recipes/11-vehicles.md +12 -7
  141. package/docs/recipes/12-navmesh.md +44 -26
  142. package/docs/recipes/13-animation.md +56 -45
  143. package/docs/recipes/14-custom-module.md +21 -18
  144. package/docs/recipes/15-perf.md +61 -55
  145. package/docs/recipes/16-dev-bridge.md +23 -33
  146. package/docs/recipes/18-world.md +36 -42
  147. package/docs/recipes/19-shooting-picking.md +20 -15
  148. package/docs/recipes/20-content-actions-save.md +48 -56
  149. package/docs/recipes/21-camera.md +45 -54
  150. package/docs/recipes/22-shop-gold.md +12 -7
  151. package/docs/recipes/23-ops.md +25 -23
  152. package/docs/recipes/26-ui-parts.md +67 -47
  153. package/docs/recipes/27-net.md +12 -7
  154. package/docs/recipes/28-terrain.md +24 -21
  155. package/docs/recipes/29-grid.md +32 -27
  156. package/docs/recipes/30-templates.md +21 -20
  157. package/docs/recipes/31-audio.md +39 -22
  158. package/docs/recipes/32-action-game.md +19 -14
  159. package/docs/recipes/33-stream-sources.md +15 -11
  160. package/docs/recipes/34-environment-lighting.md +126 -70
  161. package/docs/recipes/35-picture-from-reference.md +8 -8
  162. package/docs/recipes/36-ground-plants.md +27 -21
  163. package/docs/recipes/40-scene.md +19 -28
  164. package/docs/recipes/43-shader-patches-surfaces.md +15 -12
  165. package/docs/recipes/44-water-weather-hooks.md +34 -31
  166. package/docs/recipes/45-cascaded-shadows.md +35 -26
  167. package/docs/recipes/46-blender-art-route.md +6 -1
  168. package/docs/recipes/49-game-module-contract.md +13 -8
  169. package/docs/recipes/50-own-renderer.md +6 -2
  170. package/docs/recipes/51-capability-catalog.md +15 -8
  171. package/docs/recipes/52-around-the-picture.md +34 -32
  172. package/docs/recipes/53-ground-up-close.md +6 -1
  173. package/docs/recipes/55-mods-time-wrap.md +27 -19
  174. package/docs/recipes/56-webgpu-tsl.md +74 -43
  175. package/docs/recipes/57-control.md +18 -13
  176. package/docs/recipes/58-input.md +26 -16
  177. package/docs/recipes/59-depth-post-effects.md +8 -3
  178. package/docs/recipes/60-judge-the-picture.md +9 -8
  179. package/docs/recipes/61-deploy.md +5 -0
  180. package/docs/recipes/62-picture-code.md +70 -79
  181. package/docs/recipes/63-third-person-start.md +47 -45
  182. package/docs/recipes/64-particles.md +22 -10
  183. package/docs/recipes/65-swarm.md +18 -13
  184. package/docs/recipes/66-common-tasks.md +38 -35
  185. package/examples/action/GAMEMAP.md +2 -3
  186. package/examples/action/main.js +3 -3
  187. package/examples/action/picture/lights.js +3 -1
  188. package/examples/perf-island/GAMEMAP.md +3 -3
  189. package/examples/perf-island/picture/lights.js +2 -1
  190. package/examples/plain-picture/GAMEMAP.md +1 -1
  191. package/examples/rc2d/GAMEMAP.md +1 -1
  192. package/examples/styletest/GAMEMAP.md +2 -2
  193. package/examples/styletest/main.js +1 -1
  194. package/examples/techniques/interior-light/README.md +3 -3
  195. package/examples/techniques/interior-light/interiorLight.js +2 -4
  196. package/examples/techniques/interior-light/picture/lights.js +2 -1
  197. package/examples/techniques/modular-building/picture/lights.js +3 -1
  198. package/examples/techniques/outlines-and-rim/picture/lights.js +3 -1
  199. package/examples/techniques/procedural-animation/README.md +1 -1
  200. package/examples/techniques/procedural-animation/main.js +1 -1
  201. package/examples/webgpu-tsl/GAMEMAP.md +1 -1
  202. package/examples/world/GAMEMAP.md +2 -3
  203. package/examples/world/art/humanoid.js +1 -1
  204. package/examples/world/main.js +6 -3
  205. package/index.d.ts +2 -2
  206. package/llms.txt +101 -0
  207. package/modules/ambience/Ambience.js +21 -5
  208. package/modules/calendar/index.js +9 -5
  209. package/modules/calendar/schedule.js +23 -8
  210. package/modules/camera/FirstPersonCamera.js +3 -1
  211. package/modules/camera/FollowCamera.js +10 -5
  212. package/modules/camera/RtsCamera.js +4 -3
  213. package/modules/camera/common.js +70 -8
  214. package/modules/camera/contract.js +1 -1
  215. package/modules/characters/Character.js +16 -10
  216. package/modules/characters/NPC.js +31 -19
  217. package/modules/characters/assetModel.js +14 -9
  218. package/modules/characters/astar.js +6 -1
  219. package/modules/characters/contract.js +2 -2
  220. package/modules/characters/index.js +34 -22
  221. package/modules/characters/movers/manual.js +1 -1
  222. package/modules/characters/movers/rapier.js +17 -2
  223. package/modules/characters/movers/simple.js +1 -1
  224. package/modules/characters/movers/support.js +16 -7
  225. package/modules/characters/npcAvoid.js +2 -2
  226. package/modules/characters/npcSim.js +3 -2
  227. package/modules/characters/pathAsync.js +24 -8
  228. package/modules/characters/pathJob.js +1 -1
  229. package/modules/characters/player.js +10 -9
  230. package/modules/characters/playerStrings.js +5 -5
  231. package/modules/characters/proceduralRig.js +5 -5
  232. package/modules/characters/useModel.js +6 -0
  233. package/modules/characters/walkTo.js +1 -1
  234. package/modules/collision/Collision.js +29 -18
  235. package/modules/collision/grid.js +22 -4
  236. package/modules/content/index.js +3 -1
  237. package/modules/content/loader.js +1 -1
  238. package/modules/content/models.js +82 -33
  239. package/modules/content/props.js +2 -1
  240. package/modules/content/rules.js +11 -5
  241. package/modules/content/templates.js +3 -3
  242. package/modules/content/words.js +2 -2
  243. package/modules/debug/DebugPanel.js +9 -9
  244. package/modules/flow/index.js +9 -6
  245. package/modules/gameplay/Dialogue.js +34 -20
  246. package/modules/gameplay/Interactions.js +19 -15
  247. package/modules/gameplay/Inventory.js +9 -4
  248. package/modules/gameplay/Quests.js +12 -10
  249. package/modules/gameplay/pickups.js +23 -11
  250. package/modules/grid/index.js +1 -1
  251. package/modules/grid/preview.js +2 -2
  252. package/modules/grid/tiles.js +1 -1
  253. package/modules/hlod/index.js +4 -1
  254. package/modules/hud/index.js +47 -10
  255. package/modules/hud/parts.js +28 -9
  256. package/modules/level/geometry.js +8 -3
  257. package/modules/level/index.js +10 -5
  258. package/modules/level/load.js +4 -2
  259. package/modules/lights/sources.js +1 -1
  260. package/modules/music/Music.js +22 -4
  261. package/modules/nav/index.js +20 -10
  262. package/modules/particles/Particles.js +31 -14
  263. package/modules/particles/effect.js +20 -5
  264. package/modules/particles/lit.js +72 -0
  265. package/modules/photo/Photo.js +72 -28
  266. package/modules/photo/pathTrace.js +106 -0
  267. package/modules/rigid/RigidBodies.js +23 -14
  268. package/modules/rigid/Vehicles.js +3 -13
  269. package/modules/rigid/sync.js +2 -1
  270. package/modules/settings/Settings.js +52 -20
  271. package/modules/settings/apply.js +23 -9
  272. package/modules/settings/sections.js +39 -6
  273. package/modules/settings/strings.js +2 -0
  274. package/modules/settings/view.js +19 -3
  275. package/modules/sky/dome.js +15 -3
  276. package/modules/sky/environment.js +28 -12
  277. package/modules/sky/fog.js +1 -1
  278. package/modules/sky/frame.js +6 -1
  279. package/modules/sky/shader.js +4 -3
  280. package/modules/sky/skyModule.js +8 -4
  281. package/modules/swarm/Swarm.js +1 -1
  282. package/modules/terrain/ChunkManager.js +61 -15
  283. package/modules/terrain/chunkJob.js +2 -2
  284. package/modules/terrain/index.js +20 -5
  285. package/modules/terrain/terrainEdit.js +8 -4
  286. package/modules/terrain/terrainTexture.js +4 -2
  287. package/modules/timeline/Timeline.js +4 -3
  288. package/modules/timeline/Tween.js +3 -0
  289. package/modules/timeline/letterbox.js +1 -0
  290. package/modules/triggers/index.js +36 -17
  291. package/modules/vegetation/Vegetation.js +81 -19
  292. package/modules/vegetation/densityMap.js +13 -8
  293. package/modules/vegetation/draw.js +147 -24
  294. package/modules/vegetation/groundChunks.js +20 -5
  295. package/modules/vegetation/index.js +3 -3
  296. package/modules/vegetation/modelGeometry.js +9 -4
  297. package/modules/water/Water.js +11 -8
  298. package/modules/weather/Weather.js +7 -2
  299. package/modules/weather/shaders.js +25 -5
  300. package/modules/weather/weatherDraw.js +20 -6
  301. package/modules/world/World.js +2 -1
  302. package/modules/world/index.js +2 -2
  303. package/modules/world/persist.js +6 -2
  304. package/modules/world/views.js +15 -2
  305. package/package.json +4 -1
  306. package/presets.js +5 -5
  307. package/render/PostFX.js +84 -41
  308. package/render/backend.js +137 -16
  309. package/render/cascades.js +3 -1
  310. package/render/cascades.tsl.js +2 -0
  311. package/render/daylight.js +7 -1
  312. package/render/detail.js +7 -4
  313. package/render/effects.js +27 -8
  314. package/render/fogLook.js +24 -0
  315. package/render/fuse.js +5 -2
  316. package/render/fx/detail.tsl.js +9 -7
  317. package/render/fx/index.js +7 -2
  318. package/render/fx/library.tsl.js +1 -0
  319. package/render/fx/lightShaft.tsl.js +114 -0
  320. package/render/fx/noise.tsl.js +25 -8
  321. package/render/fx/objectOrigin.tsl.js +39 -10
  322. package/render/fx/particles.tsl.js +23 -6
  323. package/render/fx/patchNodes.tsl.js +17 -12
  324. package/render/fx/pcss.tsl.js +51 -0
  325. package/render/fx/postWebGPU.tsl.js +89 -29
  326. package/render/fx/sky.tsl.js +3 -9
  327. package/render/fxNumbers.js +10 -4
  328. package/render/impostor.tsl.js +107 -0
  329. package/render/lighting.js +33 -1
  330. package/render/lightmap.js +42 -28
  331. package/render/lights.js +19 -3
  332. package/render/materials.js +6 -4
  333. package/render/mergeCommon.js +4 -1
  334. package/render/occlusion.js +14 -4
  335. package/render/patches.js +79 -41
  336. package/render/postRuns.js +32 -0
  337. package/render/postWebGL.js +97 -10
  338. package/render/probes.js +10 -14
  339. package/render/shaderErrors.js +2 -1
  340. package/render/shadowCache.tsl.js +33 -5
  341. package/render/shadows.js +42 -16
  342. package/render/slots.js +8 -5
  343. package/render/vertexInputs.js +52 -0
  344. package/types/core.d.ts +114 -46
  345. package/types/gameplay.d.ts +56 -23
  346. package/types/generated/core/audio/Audio.d.ts +27 -1
  347. package/types/generated/core/base/Random.d.ts +1 -1
  348. package/types/generated/core/input/Input.d.ts +6 -8
  349. package/types/generated/core/input/inputSeat.d.ts +1 -1
  350. package/types/generated/core/inspect/Budget.d.ts +26 -0
  351. package/types/generated/core/inspect/DebugOverrides.d.ts +0 -2
  352. package/types/generated/core/saves/Saves.d.ts +10 -7
  353. package/types/generated/core/saves/session.d.ts +8 -2
  354. package/types/generated/core/scene/Rays.d.ts +1 -3
  355. package/types/generated/modules/particles/Particles.d.ts +1 -1
  356. package/types/generated/modules/world/World.d.ts +2 -1
  357. package/types/generated/render/PostFX.d.ts +35 -9
  358. package/types/physics.d.ts +43 -11
  359. package/types/pixel.d.ts +1 -1
  360. package/types/tsl.d.ts +62 -1
  361. package/types/world.d.ts +12 -3
  362. package/ui/Focus.js +7 -5
  363. package/ui/Parts.js +1 -1
  364. package/ui/touchPart.js +6 -3
@@ -1,14 +1,17 @@
1
1
  # Writing shader patches and surfaces
2
2
 
3
- **In this recipe**: Your own material · Patch a slot · Engine GLSL functions · Ready-made effects
3
+ > **Covers:** GLSL shader patches and surfaces on WebGL (WebGPU: recipe 56).
4
+ > **Use when:** a WebGL game needs its own shading on a material.
5
+ > **Shortest:** a `ShaderMaterial` that includes `threedog_lighting`.
6
+ > **Sections:** Your own material · Patch a slot your · Ready-made effects detail, light
4
7
 
5
8
  A new game draws on WebGPU, where shaders are TSL: start with [recipe 56](56-webgpu-tsl.md), whose node materials and `tsl:` patch fields do these same jobs. This page is the GLSL route, for a game made with `threedog new-game --webgl`: **write your own material or `ShaderMaterial`**, or **patch a slot** of any material with your own GLSL. The picture is the
6
9
  game's own; this page gives building blocks, not finished pictures. There is one entry for shader code: `applyEffects`.
7
10
 
8
11
  ```js fragment
9
- const fragmentShader = '#include <threedog_lighting>\n' + myFragmentBody; // 3. engine GLSL, called inside 1 or 2
10
- const mat = new THREE.ShaderMaterial({ uniforms: { ...engine.uniforms }, vertexShader, fragmentShader }); // 1. your own shader
11
- applyEffects(mat2, { patches: [{ name: 'tint', slot: 'color', glsl: 'diffuseColor.rgb *= 0.9;' }] }); // 2. patch a slot
12
+ const fragmentShader = '#include <threedog_lighting>\n' + myFragmentBody; // 3. engine GLSL, called inside 1 or 2
13
+ const mat = new THREE.ShaderMaterial({ uniforms: { ...engine.uniforms }, vertexShader, fragmentShader }); // 1. your own shader
14
+ applyEffects(mat2, { patches: [{ name: 'tint', slot: 'color', glsl: 'diffuseColor.rgb *= 0.9;' }] }); // 2. patch a slot
12
15
  ```
13
16
 
14
17
  A patch is a named piece of GLSL at a named place on any material, built-in or yours. The engine GLSL functions are tools you call inside your shader or a patch; none of them is a picture. A picture is what your
@@ -24,19 +27,19 @@ engine.water.material = applyEffects(new THREE.MeshPhongMaterial({ color: 0x3070
24
27
  ## Patch a slot: your own GLSL
25
28
  Write a **named patch** that names a **slot** (where the code goes) and add it with `applyEffects(material, { patches: [...] })`:
26
29
  ```js fragment
27
- { name: 'tint', slot: 'color', glsl: 'diffuseColor.rgb *= 0.9;' }, // one slot
30
+ { name: 'tint', slot: 'color', glsl: 'diffuseColor.rgb *= 0.9;' }, // one slot
28
31
  { name: 'sway', slot: 'position', shadow: true, glsl: 'transformed.x += sin(position.y) * 0.1;' }, // moves vertices: the shadow follows
29
32
  { name: 'glow', pars: 'uniform float uGlow;', uniforms: { uGlow: { value: 0.5 } },
30
- glsl: { color: 'diffuseColor.rgb *= 0.95;', output: 'outgoingLight += uGlow * 0.1;' } } // several slots; pars = declarations
33
+ glsl: { color: 'diffuseColor.rgb *= 0.95;', output: 'outgoingLight += uGlow * 0.1;' } } // several slots; pars = declarations
31
34
  ```
32
35
  The full form, with every field:
33
36
  ```js fragment
34
- { name: 'fuzz', // one name per effect; the same name again replaces it
37
+ { name: 'fuzz', // one name per effect; the same name again replaces it
35
38
  slot: 'color',
36
39
  glsl: 'diffuseColor.rgb *= 1.0 - uFuzz * 0.5;',
37
- pars: 'uniform float uFuzz;', // declarations at the top of every stage the patch touches (or { vertex, fragment })
40
+ pars: 'uniform float uFuzz;', // declarations at the top of every stage the patch touches (or { vertex, fragment })
38
41
  cacheKey: 'v1',
39
- uniforms: { uFuzz: { value: 0.3 } }, // numbers live here, so materials with different values share a program
42
+ uniforms: { uFuzz: { value: 0.3 } }, // numbers live here, so materials with different values share a program
40
43
  needs: { patches: ['world'], data: ['vertexColors'] },
41
44
  conflicts: ['wind'],
42
45
  shadow: false }
@@ -60,7 +63,7 @@ the same names map to node properties through a patch's `tsl` field, recipe 56).
60
63
  | `lighting` | after `lights_fragment_end` | inside `setupLightingModel` | reflectedLight.directDiffuse / directSpecular / indirectDiffuse (write), normal, diffuseColor, vViewPosition | after lights are summed: wrap, shadow tint, rim; WebGPU: hooks { start, light, direct, after }: light(light, ctx) returns a new color for one light before three lights the surface with it (what GLSL does by wrapping three's light info in lightsPars), direct(light, ctx) sees each light in three's loop and adds to its own sums, which join the summed light at the patch's place in the list, then its after() runs: the same order as WebGL |
61
64
  | `output` | before `opaque_fragment` | inside `setupOutput` | outgoingLight (vec3, write), diffuseColor.a | the final lit color, before fog and tone mapping |
62
65
  | `fogPars` | after `fog_pars_fragment` | WebGL only | declarations; fogColor and fogNear / fogFar or fogDensity are already declared (inside #ifdef USE_FOG) | fog functions that read three's fog uniforms (wrap them in #ifdef USE_FOG); WebGPU: fog on WebGPU is scene.fogNode, set by the game |
63
- | `fog` | replace `fog_fragment` | WebGL only | gl_FragColor (write, tone mapped already), fogColor, vFogDepth, fogNear / fogFar or fogDensity (inside #ifdef USE_FOG) | replace how fog mixes into the final color (one patch per material may take it); WebGPU: fog on WebGPU is scene.fogNode, set by the game |
66
+ | `fog` | before `tonemapping_fragment` | WebGL only | gl_FragColor (write; linear, before tone mapping), vFogDepth, threedogFogColor() (fog colour, linear), threedogFogFactor() (0..1, the same curve three uses), fogColor (as three has it) and fogNear / fogFar or fogDensity (all inside #ifdef USE_FOG) | replace how fog mixes into the final color: the only fog mix, in linear space before tone mapping and the output encoding (one patch per material may take it); WebGPU: fog on WebGPU is scene.fogNode, set by the game |
64
67
  <!-- slots:end -->
65
68
 
66
69
  Several patches in one slot run in the order added. A compile error names the patch and slot:
@@ -92,7 +95,7 @@ Patches on one material must agree. Each patch declares what it relies on, and a
92
95
  | `cacheKey` | Changes whenever the GLSL text changes (defines, branches), never for uniform values; the program key joins every patch's `name=cacheKey` in order | same name + cacheKey with different code throws. On WebGPU the program also follows the identity of each `tsl` function, so make it once and reuse it: one written fresh per material costs a program per material |
93
96
  ```js fragment
94
97
  applyEffects(mat, { wind: 0.03, season: 'foliage', patches: [{ name: 'ripple', needs: { patches: ['world'] }, conflicts: ['wind'],
95
- slot: 'color', glsl: 'diffuseColor.rgb *= 0.9 + 0.1 * sin(vThreedogWorld.x);' }] }); // throws: 'wind' and 'ripple' cannot be combined
98
+ slot: 'color', glsl: 'diffuseColor.rgb *= 0.9 + 0.1 * sin(vThreedogWorld.x);' }] }); // throws: 'wind' and 'ripple' cannot be combined
96
99
  ```
97
100
 
98
101
  **Exit: raw three.js anchors** (WebGL only). Where no slot fits, `glsl: { vertex|fragment: { <chunk>: code } }` puts code after `#include <chunk>` (a value may be `{ before, after, replace }`; the key `pars` is
@@ -150,7 +153,7 @@ The ground takes the same object as `terrain({ detail })`, its live numbers are
150
153
  **Light shaping** is a patch in the `lighting` slot, after the lights are summed. three has no "shadow color": a shadow only removes the sun's light. The ready-made form:
151
154
  ```js fragment
152
155
  applyEffects(mat, { lighting: { wrap: 0.4, shadowTint: { color: 0x4060a0, strength: 0.6, soft: 0.3 }, rim: { color: 0xffe0b0, strength: 0.4, power: 3, shadowSide: 0 } } });
153
- applyEffects(mat, { lighting: { glsl: 'void threedogLighting(inout ReflectedLight light, vec3 normal, vec3 viewDir, vec3 sunDir, float sunShadow, vec3 albedo){ ... }' } }); // your own function
156
+ applyEffects(mat, { lighting: { glsl: 'void threedogLighting(inout ReflectedLight light, vec3 normal, vec3 viewDir, vec3 sunDir, float sunShadow, vec3 albedo){ ... }' } }); // your own function
154
157
  ```
155
158
  All numbers are uniforms, and materials with the same options share one program. Written by hand, the first directional
156
159
  light is the sun (three sorts shadow casters first), so a patch reads it there and calls `threedogRim`, `threedogWrapDiffuse` or `threedogShadowTint`:
@@ -1,12 +1,15 @@
1
1
  # Water and rain/snow: depth color, foam, reflections, particles, snow cover, lightning
2
2
 
3
- **In this recipe**: water look and material, foam and depth, a reflecting mirror (WebGL addon and WebGPU node), weather particles, snow that settles, lightning.
3
+ > **Covers:** water (depth color, foam, reflections, your own surface) and rain or snow hooks.
4
+ > **Use when:** a game has water or weather on surfaces.
5
+ > **Shortest:** `engine.use(water({ level: 2 }))`.
6
+ > **Sections:** Water material and uniforms · Water depth color and · Water replace the wave · Water normal map · Water your own material · Water your own meshes · Weather particles rain and · Weather particles replace the · Snow that settles weather · Lightning picture · Particles of the game's
4
7
 
5
8
  ```js
6
9
  engine.use(water({ level: 2 }));
7
- engine.water.material.color.set(0x3070a0); // the water's picture is a plain three.js material
10
+ engine.water.material.color.set(0x3070a0); // the water's picture is a plain three.js material
8
11
  engine.water.material.opacity = 0.7;
9
- engine.water.uniforms.uWave.value = 1.5; // live: uWave uWaveScale uWaveSpeed uFresnel
12
+ engine.water.uniforms.uWave.value = 1.5; // live: uWave uWaveScale uWaveSpeed uFresnel
10
13
  engine.water.shader({ foam: true, depthColor: { shallow: 0x55ddcc, deep: 0x082040 } });
11
14
  engine.water.normalMap('water-n', { scale: 0.4, repeat: 0.05, speed: [0.01, 0.006] });
12
15
  ```
@@ -23,8 +26,8 @@ plain writes. Lambert has no highlight; for `shininess` / `specular` set your ow
23
26
 
24
27
  ## Water: depth color and crest foam
25
28
  ```js fragment
26
- engine.water.shader({ depthColor: { shallow: 0x55ddcc, deep: 0x082040 } }); // by 'view' (default): shallow looking down, deep at grazing angles
27
- engine.water.shader({ depthColor: { shallow: 0x7fe0d0, deep: 0x0a3050, by: 'wave', curve: 1.5 } }); // shallow on the crests, deep in the troughs
29
+ engine.water.shader({ depthColor: { shallow: 0x55ddcc, deep: 0x082040 } }); // by 'view' (default): shallow looking down, deep at grazing angles
30
+ engine.water.shader({ depthColor: { shallow: 0x7fe0d0, deep: 0x0a3050, by: 'wave', curve: 1.5 } }); // shallow on the crests, deep in the troughs
28
31
  engine.water.shader({ foam: { color: 0xffffff, start: 0.55, end: 0.85, opacity: 1 } }); // white on the wave tops; foam: true = these defaults
29
32
  ```
30
33
  - `shader()` decides which GLSL exists, so each call is one recompile: a scene change, not a frame. What it keeps and refreshes: `../api/water.md`.
@@ -37,19 +40,19 @@ engine.water.shader({ foam: { color: 0xffffff, start: 0.55, end: 0.85, opacity:
37
40
  Do it with your own material: render the scene's depth to a target before the water draws (`material.onBeforeRender`), pass it as a uniform, and compare it with this fragment's depth, both in meters through three's
38
41
  `perspectiveDepthToViewZ` (`#include <packing>`). A cheap fake: `engine.addWaterBody` lakes have known radii, so a surface function can foam the
39
42
  ring `length(worldPos.xz - center) > radius - 1.0` (pass the center and radius as `uniforms`).
40
- - A look that changes with real depth (tint, opacity) reads depth as the water level minus `engine.ground.height(x, z)`: once per vertex of a subdivided plane, or baked into an attribute a material reads.
43
+ - A look that changes with real depth (tint, opacity) reads depth as the water level minus `engine.surface(x, z)`: once per vertex of a subdivided plane, or baked into an attribute a material reads.
41
44
 
42
45
  ## Water: replace the wave or the surface function (GLSL)
43
46
  ```js
44
47
  engine.water.shader({
45
- uniforms: { uBands: 4, uDeep: [0.05, 0.2, 0.4] }, // numbers, colors, [x, y(, z, w)] arrays, textures; in both stages, live in engine.water.uniforms
48
+ uniforms: { uBands: 4, uDeep: [0.05, 0.2, 0.4] }, // numbers, colors, [x, y(, z, w)] arrays, textures; in both stages, live in engine.water.uniforms
46
49
  wave: {
47
- glsl: `float threedogWaterWave(vec3 p, float t) { // p = world position * uWaveScale, t = time * uWaveSpeed
48
- return sin(p.x * 0.5 + t) * 0.2 + sin(p.z * 0.8 - t * 1.3) * 0.1; }`, // height before uWave
49
- waveMax: 0.3, // its peak: foam and depthColor 'wave' divide by it
50
+ glsl: `float threedogWaterWave(vec3 p, float t) { // p = world position * uWaveScale, t = time * uWaveSpeed
51
+ return sin(p.x * 0.5 + t) * 0.2 + sin(p.z * 0.8 - t * 1.3) * 0.1; }`, // height before uWave
52
+ waveMax: 0.3, // its peak: foam and depthColor 'wave' divide by it
50
53
  },
51
54
  surface: `vec4 threedogWaterSurface(vec4 base, float wave, float facing, vec3 worldPos, float time) {
52
- float b = floor(facing * uBands) / uBands; // toon bands by view angle
55
+ float b = floor(facing * uBands) / uBands; // toon bands by view angle
53
56
  return vec4(mix(uDeep, vec3(0.4, 0.8, 0.9), b), base.a); }`,
54
57
  });
55
58
  ```
@@ -68,8 +71,8 @@ engine.water.shader({
68
71
  ## Water: your own material (reflections, refraction)
69
72
  ```js fragment
70
73
  engine.water.material = applyEffects(new THREE.MeshPhongMaterial({ color: 0x3070a0, shininess: 90, specular: 0xaaaaaa, transparent: true, opacity: 0.85 }),
71
- { patches: engine.water.patches }); // keep the waves, the surface and the fresnel
72
- engine.water.material = new THREE.ShaderMaterial({ uniforms: engine.water.uniforms, vertexShader, fragmentShader }); // or all your own
74
+ { patches: engine.water.patches }); // keep the waves, the surface and the fresnel
75
+ engine.water.material = new THREE.ShaderMaterial({ uniforms: engine.water.uniforms, vertexShader, fragmentShader }); // or all your own (WebGL; a node material on WebGPU)
73
76
  ```
74
77
  Setting `engine.water.material` swaps it on every water mesh, now and later, and draws it as given: the engine adds no patch, so `patches` is how waves
75
78
  stay (pick from the list by `name` for only some: `waves`, `waterSurface`, `fresnel`; `waterSurface` needs `waves` before it). After a later `shader()` call
@@ -87,10 +90,10 @@ const mirror = new Reflector(new THREE.PlaneGeometry(1, 1), { textureWidth: 512,
87
90
  const toPlane = new THREE.Matrix4().makeRotationX(-Math.PI / 2), back = new THREE.Matrix4().makeRotationX(Math.PI / 2);
88
91
  let busy = false;
89
92
  m.onBeforeRender = (renderer, scene, camera, geometry, mesh) => {
90
- if (busy) return; busy = true; // the mirror's own render must not reflect again
93
+ if (busy) return; busy = true; // the mirror's own render must not reflect again
91
94
  mirror.matrixWorld.copy(mesh.matrixWorld).multiply(toPlane);
92
95
  mesh.visible = false; mirror.onBeforeRender(renderer, scene, camera); mesh.visible = true;
93
- m.uniforms.textureMatrix.value.multiply(back); // undo the turn for the pre-rotated vertices
96
+ m.uniforms.textureMatrix.value.multiply(back); // undo the turn for the pre-rotated vertices
94
97
  busy = false;
95
98
  };
96
99
  engine.water.material = m;
@@ -102,12 +105,12 @@ geometry does not matter. The mirror is the XY plane of `target` (normal +Z): tu
102
105
  import * as THREE from 'three/webgpu';
103
106
  import { reflector, mix, color } from 'three/tsl';
104
107
 
105
- const mirror = reflector({ resolutionScale: 0.5 }); // half-size render target
106
- mirror.target.rotateX(-Math.PI / 2); // XY plane -> flat, normal up
107
- mirror.target.position.y = 0; // the water level
108
- engine.scene.add(mirror.target); // must be in the scene
108
+ const mirror = reflector({ resolutionScale: 0.5 }); // half-size render target
109
+ mirror.target.rotateX(-Math.PI / 2); // XY plane -> flat, normal up
110
+ mirror.target.position.y = 0; // the water level
111
+ engine.scene.add(mirror.target); // must be in the scene
109
112
  const m = new THREE.MeshBasicNodeMaterial();
110
- m.colorNode = mix(color(0x2a5a7a), mirror, 0.6); // 0 = water color, 1 = pure reflection
113
+ m.colorNode = mix(color(0x2a5a7a), mirror, 0.6); // 0 = water color, 1 = pure reflection
111
114
  engine.water.material = m;
112
115
  ```
113
116
  - Cost: the whole scene drawn once more per frame per water mesh at `textureWidth` x `textureHeight` (shadows are not re-rendered). Use 256-512
@@ -127,10 +130,10 @@ you when one comes or goes, so swimming, buoyancy and anything else reading the
127
130
 
128
131
  ```js fragment
129
132
  weather({ types,
130
- rain: { color: 0xa8b8d0, opacity: 0.6, length: 1.2, speed: 26, slant: 1.5, density: a => a * a }, // streaks; sparse in a drizzle
131
- // rain: { shape: 'soft', size: 10, maxSize: 6, sway: 0.3 }, // drops as soft sprites instead of streaks
133
+ rain: { color: 0xa8b8d0, opacity: 0.6, length: 1.2, speed: 26, slant: 1.5, density: a => a * a }, // streaks; sparse in a drizzle
134
+ // rain: { shape: 'soft', size: 10, maxSize: 6, sway: 0.3 }, // drops as soft sprites instead of streaks
132
135
  snow: { shape: 'soft', size: 28, maxSize: 7, speed: 1, sway: 3, count: 4000 },
133
- // snow: { texture: 'flake' }, // a sprite image replaces the shape
136
+ // snow: { texture: 'flake' }, // a sprite image replaces the shape
134
137
  });
135
138
  ```
136
139
  The keys and defaults are `WeatherParticles` in `types/world.d.ts`. `density` decides how many particles show at a weather amount; opacity follows the amount as well. Coverage is `weather({ area })`.
@@ -138,10 +141,10 @@ The keys and defaults are `WeatherParticles` in `types/world.d.ts`. `density` de
138
141
  At run time each system is in `engine.weather.particles`, and every number is a plain write, live on both renderers. `particles.rain` exists only when the weather table has a `rain` field (`particles.snow` likewise for `snow`); with a table of your own, read it as `particles.rain?.`:
139
142
  ```js
140
143
  const rain = engine.weather.particles.rain, myFragment = 'void main() { gl_FragColor = vec4(0.7, 0.8, 1.0, 0.4); }';
141
- rain.spec.speed = 30; rain.spec.opacity = 0.3; rain.spec.slant = 2; // read each frame; density too
142
- rain.uniforms.uColor.value.set(0xa8b8d0); rain.uniforms.uLen.value = 1.2; // sprites: uPx (size), uMaxPx (maxSize), uSwayAmp (sway)
144
+ rain.spec.speed = 30; rain.spec.opacity = 0.3; rain.spec.slant = 2; // read each frame; density too
145
+ rain.uniforms.uColor.value.set(0xa8b8d0); rain.uniforms.uLen.value = 1.2; // sprites: uPx (size), uMaxPx (maxSize), uSwayAmp (sway)
143
146
  rain.material = new THREE.ShaderMaterial({ uniforms: rain.uniforms, vertexShader: rain.material.vertexShader,
144
- fragmentShader: myFragment, transparent: true, depthWrite: false }); // your material, drawn as given; null gives the engine's back
147
+ fragmentShader: myFragment, transparent: true, depthWrite: false }); // your material (WebGL form), drawn as given; null gives the engine's back
145
148
  engine.weather.overcastColor.set(0x667788); engine.weather.lightningBrightness = 0.5;
146
149
  ```
147
150
  The fall and the follow-the-camera wrap live in the vertex shader, so a material of your own shares `uniforms` and keeps a vertex shader like it.
@@ -151,7 +154,7 @@ The fall and the follow-the-camera wrap live in the vertex shader, so a material
151
154
  weather({ types, snow: { uniforms: { uTint: [1, 0.85, 0.9] }, glsl: { fragment: `uniform float uOpacity;
152
155
  void main(){
153
156
  vec2 d = gl_PointCoord - 0.5;
154
- float a = 1.0 - smoothstep(0.1, 0.25, dot(d, d)); // a soft petal
157
+ float a = 1.0 - smoothstep(0.1, 0.25, dot(d, d)); // a soft petal
155
158
  gl_FragColor = vec4(uTint, uOpacity * a);
156
159
  #include <tonemapping_fragment>
157
160
  #include <colorspace_fragment>
@@ -174,9 +177,9 @@ weather({ types, snow: { size: 18, cover: { foliage: 0xf2f4f6, ground: 0xeef0f2,
174
177
 
175
178
  ## Lightning picture
176
179
  ```js fragment
177
- weather({ types, lightning: f => f * f * 0.8 }); // flash 1 at the strike -> sky flash amount (default flickers)
178
- weather({ types, lightning: () => 0 }); // no sky flash: draw your own bolt instead
179
- engine.events.on('weather:lightning', () => spawnBolt()); // when it strikes stays the weather table's (lightning > 0.5)
180
+ weather({ types, lightning: f => f * f * 0.8 }); // flash 1 at the strike -> sky flash amount (default flickers)
181
+ weather({ types, lightning: () => 0 }); // no sky flash: draw your own bolt instead
182
+ engine.events.on('weather:lightning', () => spawnBolt()); // when it strikes stays the weather table's (lightning > 0.5)
180
183
  ```
181
184
 
182
185
  ## Particles of the game's own weather
@@ -188,7 +191,7 @@ round sprites), or `create` for a system of your own:
188
191
  const engine = createEngine({ canvas });
189
192
  engine.use(sky(), weather({ types: { clear: {}, shower: { rain: 1 }, ashfall: { ash: 1, grey: 0.5, sun: 0.6 } } }));
190
193
  engine.weather.defineField('ash', { shape: 'soft', color: 0x555555, size: 14, speed: 0.8, sway: 3 });
191
- engine.weather.defineField('rain', { create: (engine, { area, count }) => { // the same call replaces rain or snow
194
+ engine.weather.defineField('rain', { create: (engine, { area, count }) => { // the same call replaces rain or snow
192
195
  const drops = new THREE.InstancedMesh(new THREE.SphereGeometry(0.03), new THREE.MeshBasicMaterial({ color: 0x99bbff }), count);
193
196
  return { object: drops, update(amount, { camera, time, wind }) { /* move the instances; shown while amount > 0.02 */ } };
194
197
  } });
@@ -1,7 +1,9 @@
1
1
  # Shadows: cascades, box, budget, cache, the switch
2
2
 
3
- **In this recipe**: `engine.shadows` works on a light you hand it and leaves every other light alone: cascades, a box that follows, an update budget, the master
4
- switch. Filter, bias, softness and map size are plain three.js (last section).
3
+ > **Covers:** shadows: cascades, the box, budget, cache, the master switch, filtering.
4
+ > **Use when:** shadows look wrong, cost too much or must follow the view.
5
+ > **Shortest:** `sun.castShadow = true` on your own light.
6
+ > **Sections:** How it works what · Costs and stalls · Rules of the entry · A box that follows · Keep what does not · An update budget · Resolution after the first · The master switch · Filter, bias, softness, map
5
7
 
6
8
  ```js
7
9
  const sun = new THREE.DirectionalLight('#fff4e0', 3);
@@ -9,11 +11,12 @@ sun.position.set(40, 80, 30);
9
11
  sun.castShadow = true;
10
12
  sun.shadow.mapSize.setScalar(engine.tier === 'low' ? 1024 : 2048);
11
13
  engine.scene.add(sun);
14
+ if (engine.lights.sun) engine.lights.sun.castShadow = false; // WebGL: cascades must be the only shadowing DirectionalLight (or createEngine({ lights: false }))
12
15
 
13
16
  const shadows = engine.shadows.cascades(sun, { count: 3, maxFar: 150 });
14
- engine.onRender(() => sun.position.copy(engine.uniforms.uSunDir.value).multiplyScalar(100)); // aim it as usual
15
- shadows.set({ count: 2 }); // on a settings screen: it recompiles
16
- shadows.remove(); // one plain shadow map again
17
+ engine.onRender(() => sun.position.copy(engine.uniforms.uSunDir.value).multiplyScalar(100)); // aim it as usual
18
+ shadows.set({ count: 2 }); // on a settings screen: it recompiles
19
+ shadows.remove(); // one plain shadow map again
17
20
  ```
18
21
 
19
22
  Cascades split one light's shadow along the view into 2-4 maps (three's CSM addon): sharp near the camera, coarse far away. Use them when near
@@ -65,11 +68,14 @@ lights). The cascade shadow cameras reach `lightMargin + 2 * maxFar` meters, as
65
68
  ## Rules of the entry
66
69
  It works with and without a sky, on both renderers (WebGPU needs `import 'threedog/tsl'`, or the call says so).
67
70
  - The light must be a DirectionalLight, a direct child of `engine.scene`, with `castShadow = true`; anything else throws at the call.
71
+ - On WebGL the cascades must be the only shadow-casting DirectionalLight: cascades on your own light while `engine.lights.sun` (or any other DirectionalLight) casts throws at the call (`shadow-cascades`), because three's CSM shader reads one cascade per shadow-casting directional light. Set `engine.lights.sun.castShadow = false` first, or put the cascades on the sun. Turning such a light's `castShadow` on later is not caught: the patched materials then fail to compile.
68
72
  - Color, intensity, `visible`, `castShadow` and `light.shadow` values stay yours and are read every frame. The cascades only place the light. On WebGL, while they are on,
69
73
  `light.position` and `light.target` hold that placement: writes to `light.position` or a new `light.target` still set the direction, and
70
74
  `remove()` puts both back as you left them, with the shadow camera box. A `light.target` you assigned (your player, say) is never moved.
71
- - `engine.tier === 'low'` gets one map unless you pass `low: { count: 2 }`. On a game's light that map follows the camera and covers `maxFar` each way, so it is blurrier than cascades but never stops at the
72
- origin; like cascades it places the light, so `engine.shadows.box` on that light is refused. On `engine.lights.sun` the one map stays the engine's own box around the focus, with its size. `handle.csm` is null while there is one map.
75
+ - `engine.tier === 'low'` gets one map unless you pass `low: { count: 2 }`. That map covers `maxFar / count` each way, so its texels are as small as an average cascade's: the low tier
76
+ saves shadow passes and draws shadows less far, not blurrier (one map over all of `maxFar` has `count` times the texels, and the PCF blur is `radius` x texel). On a game's light it follows the
77
+ camera, shifted half its size ahead of the view, and never stops at the origin; like cascades it places the light, so `engine.shadows.box` on that light is refused. On `engine.lights.sun` the
78
+ one map stays the engine's own box around the focus, sized the same way. `count: 1` (one map on every tier) covers all of `maxFar`. `handle.csm` is null while there is one map.
73
79
  - An engine draws one set of cascades: a second handle throws. A box on the same light throws too, except the engine's own box on `engine.lights.sun`, which waits
74
80
  until `remove()`.
75
81
  - Another shadow-casting DirectionalLight next to cascades breaks the cascade order on WebGL (three sorts shadow casters first): one warning
@@ -85,8 +91,8 @@ sun.position.set(40, 80, 30); sun.castShadow = true;
85
91
  engine.scene.add(sun);
86
92
 
87
93
  const box = engine.shadows.box(sun, { follow: engine.player.root, extent: 40, snap: 'texel' });
88
- box.set({ extent: 60 }); // a wider view
89
- box.remove(); // position, target and the shadow camera come back
94
+ box.set({ extent: 60 }); // a wider view
95
+ box.remove(); // position, target and the shadow camera come back
90
96
  ```
91
97
 
92
98
  | field | default | meaning |
@@ -94,7 +100,7 @@ box.remove(); // position, target and the shadow camera come back
94
100
  | `follow` | `'focus'` | `'focus'` (`engine.focus`), `'camera'`, an Object3D, `() => Vector3`, or `false` (it stays on the light's target) |
95
101
  | `extent` | left out | half size in meters, written on `light.shadow.camera`; left out, the camera stays as you set it |
96
102
  | `snap` | 0.5 | center snap grid in meters, or `'texel'`: one shadow pixel, no shimmer on a moving camera |
97
- | `ahead` | 0 | meters the center is shifted in front of the view |
103
+ | `ahead` | 0 | meters the center is shifted in front of a level view; less as the view tilts down, 0 straight down |
98
104
 
99
105
  - A game light gets no box unless you call this. The light keeps its direction, which is its position minus its target, so aim it as usual. `position`, `target` and a `light.target` you assigned work as under cascades above.
100
106
  - The engine's placeholder sun under `sky()` has a box already, following `engine.focus`, 30 m each way. `engine.shadows.box(engine.lights.sun, { follow: false, extent: 9 })` changes that one
@@ -103,10 +109,10 @@ box.remove(); // position, target and the shadow camera come back
103
109
  ## Keep what does not move
104
110
 
105
111
  ```js fragment
106
- const kept = engine.shadows.cache(sun, { static: mesh => mesh !== cars.mesh }); // a test on each mesh; or an Object3D, or a list of them
107
- kept.redraw(); // a static object moved, hid or left
108
- kept.set({ static: town }); // say again what is static
109
- kept.remove(); // three's own shadow node again
112
+ const kept = engine.shadows.cache(sun, { static: mesh => mesh !== cars.mesh }); // a test on each mesh; or an Object3D, or a list of them
113
+ kept.redraw(); // a static object moved, hid or left
114
+ kept.set({ static: town }); // say again what is static
115
+ kept.remove(); // three's own shadow node again
110
116
  ```
111
117
 
112
118
  Off until you call it, and only on the light you hand in. Static casters are drawn once into a second depth map. Each shadow frame copies that map into the light's own
@@ -132,11 +138,11 @@ Listed in `describe().threePatches` as `shadow-cache`.
132
138
  A shadow map of a still scene need not redraw every frame:
133
139
 
134
140
  ```js
135
- const sun = new THREE.DirectionalLight(0xffffff, 2); // your main light
136
- const budget = engine.shadows.budget(sun, { every: 3 }); // a third of the shadow fill cost
137
- budget.redraw(); // something big moved: draw on the next frame
138
- budget.set({ every: 1 }); // every frame again
139
- budget.remove(); // light.shadow.autoUpdate as it was
141
+ const sun = new THREE.DirectionalLight(0xffffff, 2); // your main light
142
+ const budget = engine.shadows.budget(sun, { every: 3 }); // a third of the shadow fill cost
143
+ budget.redraw(); // something big moved: draw on the next frame
144
+ budget.set({ every: 1 }); // every frame again
145
+ budget.remove(); // light.shadow.autoUpdate as it was
140
146
  ```
141
147
 
142
148
  It works on any light with a shadow, through that light's own `shadow.autoUpdate` and `shadow.needsUpdate`, so other lights are not touched. Skipped frames make swaying shadows stutter.
@@ -147,16 +153,16 @@ Before the first frame `light.shadow.mapSize.set(2048, 2048)` is all it takes. O
147
153
 
148
154
  ```js
149
155
  const sun = new THREE.DirectionalLight(0xffffff, 2);
150
- engine.shadows.mapSize(sun, 1024); // the map is rebuilt and redrawn; with cascades, every cascade's map
156
+ engine.shadows.mapSize(sun, 1024); // the map is rebuilt and redrawn; with cascades, every cascade's map
151
157
  ```
152
158
 
153
- Photo mode does this itself for every casting DirectionalLight in the scene (`photo({ shadowMapSize })`) and puts the sizes back after the shot.
159
+ Photo mode does this for every casting DirectionalLight (`photo({ shadowMapSize })`) and restores the sizes.
154
160
 
155
161
  ## The master switch
156
162
  ```js
157
- engine.shadows.enabled = false; // a game's own setting
163
+ engine.shadows.enabled = false; // a game's own setting
158
164
  const hold = engine.mod('shadows.enabled', { owner: 'cutscene', layer: 'system', set: false });
159
- hold.remove(); // back to what was before
165
+ hold.remove(); // back to what was before
160
166
  ```
161
167
 
162
168
  It writes `renderer.shadowMap.enabled` only, so no light's `castShadow` changes, and recompiles materials once: use it on a menu, not per frame. The settings menu holds the same
@@ -164,13 +170,16 @@ point (`'shadows.enabled'`, layer `settings`, restrict only), so a player who tu
164
170
 
165
171
  ## Filter, bias, softness, map size: three.js
166
172
  ```js
167
- engine.renderer.shadowMap.type = THREE.VSMShadowMap; // BasicShadowMap | PCFShadowMap (default) | VSMShadowMap
173
+ engine.renderer.shadowMap.type = THREE.VSMShadowMap; // BasicShadowMap | PCFShadowMap (default) | VSMShadowMap
168
174
  const sun = new THREE.DirectionalLight(0xffffff, 2);
169
- sun.shadow.radius = 3; sun.shadow.blurSamples = 8; // softness (pcf, vsm); blur quality (vsm)
175
+ sun.shadow.radius = 3; sun.shadow.blurSamples = 8; // softness (pcf, vsm); blur quality (vsm)
170
176
  sun.shadow.bias = -0.0001; sun.shadow.normalBias = 0.03;
171
- sun.shadow.mapSize.setScalar(2048); // before the first frame; later also sun.shadow.map?.dispose(); sun.shadow.map = null;
177
+ sun.shadow.mapSize.setScalar(2048); // before the first frame; later also sun.shadow.map?.dispose(); sun.shadow.map = null;
172
178
  ```
173
179
 
180
+ PCF's `radius` is in shadow texels, so the blur in meters is `radius x 2 x extent / mapSize`: halve the map (a low-tier size) and keep the radius, and the blur doubles. Scale them
181
+ together, `sun.shadow.radius = Math.max(Math.min(R, 2), R * size / 2048)` for a radius `R` tuned on the 2048 map, as the engine's own sun does (`R` = 3): under about 2 texels PCF shows the map's stair steps.
182
+
174
183
  Changing the type later:
175
184
  - WebGLRenderer does the work itself on the next frame that draws a shadow, only for lights that draw on that frame. A light under `engine.shadows.budget` is redrawn
176
185
  by the budget at once. A light of your own with `shadow.autoUpdate = false` needs `light.shadow.needsUpdate = true` in the same frame, or it keeps its old map.
@@ -1,5 +1,10 @@
1
1
  # Blender to game (GLB) route
2
2
 
3
+ > **Covers:** from Blender to a GLB in the game: export, check, compress, use, troubleshoot.
4
+ > **Use when:** art made in Blender.
5
+ > **Shortest:** `threedog assets check art/models/town.glb`.
6
+ > **Sections:** 1 In Blender · 2 Export glTF / · 3 Check, then compress · 4 Use it · 5 The GLB's own · 6 Smallest copyable flow · 7 Troubleshooting
7
+
3
8
  Code-built geometry (`models.js`, recipe 05) is good for blockout, props and variations, but it cannot reach the finish of hand-made art: painted
4
9
  textures, baked shadows, sculpted edges. That finish comes from Blender. This page is the whole path, in order. The level naming rules live in
5
10
  `10-blender-level.md`; they are not repeated here.
@@ -60,7 +65,7 @@ Views can also be content: `content/views.js` = `{ gate: { position: [10, 4, 12]
60
65
  `engine.debug.view('albedo')` shows only the base color and texture (unlit), `'lighting'` plain white clay under the scene lights, `'shadow'` the same with
61
66
  ambient and hemisphere light hidden so shadows read black, `'normals'` the normals as color (a normal map shows here); `'off'` restores everything.
62
67
  A view is temporary and owner-scoped (`{ owner }`; another owner needs `force: true` to clear it), never saved, and `describe().render` / `describe render`
63
- start with a DEBUG VIEW line while one is on, so a screenshot of clay is not taken for the real picture. Meshes added after the call are not covered: call it again.
68
+ start with a DEBUG VIEW line while one is on, so a screenshot of clay is not taken for the real picture. Meshes added after the call are not covered: call it again. One model or material alone, per channel: recipe 05 "Look-dev".
64
69
 
65
70
  ## 4. Use it
66
71
  Register the compressed file in the asset pack and refer to it by name everywhere else:
@@ -1,11 +1,16 @@
1
1
  # Writing a game system module (a smelter, a recharging turret, growing crops) that plugs into the engine's contracts
2
2
 
3
+ > **Covers:** the five contracts of a game system module (saves, skip, describe, ops, time).
4
+ > **Use when:** a system of your own that must save and skip time like the built-in ones.
5
+ > **Shortest:** a module `{ name, install }` that keeps the five contracts.
6
+ > **Sections:** The five contracts · Declaring stage and dependencies · One copyable module something · Check "advance 10h normally · Checking it a contract · What the engine does
7
+
3
8
  A game system is a module (`{ name, install, ... }`) given to `engine.use(...)`. If it follows the five contracts below it saves, loads, skips time,
4
9
  shows in `describe()` and the dev bridge, and can be driven by ops, without special cases. Read recipe 14 (template, hook cheat sheet), 06 (clock, skip), 18 (world records), 23 (ops).
5
10
 
6
11
  ## The five contracts
7
12
  1. **State.** Prefer world records (`engine.world.add({ kind, ... })`, recipe 18): saved, streamed and far-simulated for you. State that is not a
8
- record (a counter, a machine's queue) goes in `engine.saves.register(key, { save, load, version?, migrate? })`. Raise `version` by 1 whenever the
13
+ record (a counter, a machine's queue) goes in `engine.saves.define(key, { save, load, version?, migrate? })`. Raise `version` by 1 whenever the
9
14
  saved shape changes and add `migrate: { oldVersion: d => newData }`. Never keep game state only in a closure or module variable.
10
15
  2. **Time, normal play.** Store *when* something happened in calendar seconds (`engine.clock.now`), and derive the state from `now - startedAt`. Never use
11
16
  `Date.now`, `performance.now` or `setTimeout` for game time: they ignore pause, time channels, `step` and saves. If you must accumulate, do it in
@@ -31,15 +36,15 @@ modules. The module `name` must not clash with an existing engine property.
31
36
  ## One copyable module: something that finishes after a delay (a smelter, a turret recharge, a crop)
32
37
  ```js
33
38
  export const machines = () => {
34
- const started = new Map(); // id -> startedAt (calendar seconds)
39
+ const started = new Map(); // id -> startedAt (calendar seconds)
35
40
  return {
36
41
  name: 'machines', type: 'rules', stage: 'gameplay', requires: ['inventory'],
37
42
  install(e) {
38
- e.saves.register('machines', { version: 1, // contract 1: saved and restored
43
+ e.saves.define('machines', { version: 1, // contract 1: saved and restored
39
44
  save: () => [...started],
40
45
  load: d => { started.clear(); for (const [id, t] of d) started.set(id, t); } });
41
- const progress = id => Math.min(1, (e.clock.now - started.get(id)) / 120); // contracts 2+3: derived from clock.now, so normal == skipped
42
- e.ops.define('job.start', { args: { id: 'string' }, desc: 'Start a job on a machine', // contract 5
46
+ const progress = id => Math.min(1, (e.clock.now - started.get(id)) / 120); // contracts 2+3: derived from clock.now, so normal == skipped
47
+ e.ops.define('job.start', { args: { id: 'string' }, desc: 'Start a job on a machine', // contract 5
43
48
  can: (_, { id }) => (started.has(id) ? 'busy' : true),
44
49
  run: (_, { id }) => { started.set(id, e.clock.now); return id; }, reasons: { busy: 'Already running' } });
45
50
  e.ops.define('job.collect', { args: { id: 'string' }, desc: 'Collect a finished job',
@@ -47,9 +52,9 @@ export const machines = () => {
47
52
  offers: () => [...started.keys()].filter(id => progress(id) >= 1).map(id => ({ id })),
48
53
  run: (_, { id }) => { started.delete(id); e.inventory.add('item', 2); return id; },
49
54
  reasons: { idle: 'Nothing running', notDone: 'Not done yet' } });
50
- return { progress }; // becomes engine.machines (engine.jobs is the engine's own job queue)
55
+ return { progress }; // becomes engine.machines (engine.jobs is the engine's own job queue)
51
56
  },
52
- describe: e => ({ running: started.size, done: [...started.keys()].filter(id => e.machines.progress(id) >= 1) }), // contract 4
57
+ describe: e => ({ running: started.size, done: [...started.keys()].filter(id => e.machines.progress(id) >= 1) }), // contract 4
53
58
  };
54
59
  };
55
60
  ```
@@ -69,7 +74,7 @@ Write the five points down as data in `contract.js` (`{ name, api, ops, events,
69
74
  `modules/gameplay/inventory.contract.js`) and run it from your tests (works in a game installed from npm):
70
75
  ```js fragment
71
76
  import { runContract } from '@threedog/tools/contract';
72
- runContract(contract, () => myModule(contract.options), { check }); // check(label, ok, detail?)
77
+ await runContract(contract, () => myModule(contract.options), { check }); // check(label, ok, detail?)
73
78
  ```
74
79
  It installs the module, checks the api / ops / save versions / probe events / describe, and that the probed
75
80
  value survives save -> fresh install -> load. `props` lists fields that must exist (`dialogue.active`), `probe.state.map` turns a non-number read
@@ -1,13 +1,17 @@
1
1
  # Bring your own renderer: `createEngine({ renderer })`
2
2
 
3
+ > **Covers:** passing in your own three.js renderer (a `WebGLRenderer` or `WebGPURenderer` you made) instead of the one the engine makes.
4
+ > **Use when:** the game must own the renderer (shared canvas, editor).
5
+ > **Shortest:** `createEngine({ renderer })`.
6
+
3
7
  Pass a ready three.js renderer when the game must own it (shared canvas, an editor, a custom context):
4
8
 
5
9
  ```js
6
10
  const renderer = new THREE.WebGLRenderer({ canvas, antialias: true });
7
- const engine = createEngine({ renderer }); // canvas defaults to renderer.domElement
11
+ const engine = createEngine({ renderer }); // canvas defaults to renderer.domElement
8
12
  ```
9
13
 
10
14
  - The engine configures only a renderer it created itself. With yours it sets nothing: pixel ratio (unless `pixelRatio` is given), size, tone mapping, exposure and shadow map stay as you left them, so set them yourself on the renderer. MSAA follows your renderer's `antialias` too (unless `createEngine({ antialias })` says otherwise; a value that differs from the renderer's runs the post chain's MSAA targets every frame).
11
15
  - **WebGLRenderer or three's WebGPURenderer.** On WebGPURenderer, materials, patches and post effects take their node / TSL forms (recipe 56). Everything else (scene, modules, input, saves, ops) does not depend on the renderer.
12
16
  - Changing the renderer, lights or post effects is yours to do at any time; the engine never warns. `engine.describe().render` (CLI: `describe render`) lists the current values; `describe().picture.writers` says which line wrote each on the dev server.
13
- - **A transparent canvas** (the page shows through where nothing is drawn) is this same route; createEngine has no option for it. WebGL: `new THREE.WebGLRenderer({ canvas, alpha: true })` (three's default is opaque). WebGPURenderer: alpha is on by default; pass `alpha: true` to be explicit. Then `renderer.setClearColor(0x000000, 0)` and keep `engine.scene.background` null (a colour or texture background is opaque by definition). Post effects keep the alpha (tested on both backends with vignette). With `fallback: 'webgl'` a WebGPURenderer you built with alpha is replaced by a WebGLRenderer that keeps the alpha (a renderer the engine built itself stays opaque).
17
+ - **A transparent canvas** (the page shows through where nothing is drawn) is this same route; createEngine has no option for it. WebGL: `new THREE.WebGLRenderer({ canvas, alpha: true })` (three's default is opaque). WebGPURenderer: alpha is on by default (`alpha: true` to be explicit). Then `renderer.setClearColor(0x000000, 0)` and keep `engine.scene.background` null (any colour or texture background is opaque). Post effects keep the alpha (tested on both backends with vignette). With `fallback: 'webgl'` a WebGPURenderer you built with alpha is replaced by a WebGLRenderer that keeps the alpha (a renderer the engine built itself stays opaque).
@@ -1,17 +1,24 @@
1
1
  # Capability catalog: ask what the game can do before reading docs
2
2
 
3
+ > **Covers:** the capability catalog and the picture menu: what this game can do, asked at run time.
4
+ > **Use when:** before reading docs, to see what is installed.
5
+ > **Shortest:** `engine.catalog()` / `threedog catalog`.
6
+ > **Sections:** 1 Ask · 2 Declare args once · 3 Declare module options · 4 Debugging with it · 5 "How do I
7
+
3
8
  `engine.catalog()` answers "which modules are here, what can they do, what do they save, how do they keep time" from the registrations
4
- that already exist: module definitions (`requires`, `optional`, `stage`, hooks), `engine.ops.define`, `engine.saves.register`,
9
+ that already exist: module definitions (`requires`, `optional`, `stage`, hooks), `engine.ops.define`, `engine.saves.define`,
5
10
  `engine.describe.add` and params schemas. There is no second list to keep in sync: a removed op is gone from the catalog at once.
6
11
 
7
12
  ## 1. Ask
8
13
  ```js
9
- engine.catalog(); // short list: [{ id: 'sky', kind: 'module', state: 'running', stage: 'environment', ops: [], saves: ['sky'], time: 'fixed+skip' }, ...]
10
- engine.catalog('shop'); // one module expanded (below)
11
- engine.catalog('shop.buy'); // one op: args schema, reasons, can / offers / undo / net, its last attempt
14
+ engine.catalog(); // short list: [{ id: 'sky', kind: 'module', state: 'running', stage: 'environment', ops: [], saves: ['sky'], time: 'fixed+skip' }, ...]
15
+ engine.catalog('shop'); // one module expanded (below)
16
+ engine.catalog('shop.buy'); // one op: args schema, reasons, can / offers / undo / net, its last attempt
12
17
  engine.catalog({ find: 'throw' }); // the short list filtered by id, label, op or save name
13
- engine.catalog('core'); // what the engine registered itself (time.skip, clock, random...); 'game': what game code registered outside modules
18
+ engine.catalog('core'); // what the engine registered itself (time.skip, clock, random...); 'game': what game code registered outside modules
19
+ engine.catalog('picture'); // the picture menu: what the picture could turn on (below)
14
20
  ```
21
+ **The picture menu** (`engine.catalog('picture')`, `threedog catalog picture`): one row per picture capability, three's own (fog, environment map, tone curve, shadows…) and each `@threedog/post-effects` effect: on now, can it run here, a rough cost class, one way to turn it on, the recipe section, its main limit; then the combination checks (effects that clash or do the same job twice). Capabilities only: no row says how strong or which color. A game module with a capability's name (the template's `picture` module) is a prefix away: `catalog('module:picture')`.
15
22
  From the dev bridge: `threedog catalog`, `threedog catalog shop`, `threedog catalog --find buy` (`--json` for the data). The bridge prints the
16
23
  same data and adds the files: `source` (where `name: 'shop'` or `define('shop.buy'` is written), `api` (the generated api page), `recipes` and
17
24
  `examples` that use `engine.shop`. The MCP server has one `catalog` tool with the same arguments.
@@ -39,9 +46,9 @@ engine.ops.define('shop.buy', {
39
46
  e.inventory.remove('gold', n * PRICE[item]);
40
47
  return e.inventory.add(item, n).added === n ? n : { ok: false, code: 'bagFull' };
41
48
  },
42
- reasons: { noMoney: 'Not enough gold', bagFull: 'No room in the bag' }, // the failure codes the catalog lists
49
+ reasons: { noMoney: 'Not enough gold', bagFull: 'No room in the bag' }, // the failure codes the catalog lists
43
50
  });
44
- engine.ops.run('shop.buy', { item: 'bread' }); // n: 1; with n: 0, dev throws "n must be >= 1" and release returns { ok: false, code: 'badArgs' } (run never starts)
51
+ engine.ops.run('shop.buy', { item: 'bread' }); // n: 1; with n: 0, dev throws "n must be >= 1" and release returns { ok: false, code: 'badArgs' } (run never starts)
45
52
  ```
46
53
 
47
54
  ## 3. Declare module options once (`readParams`)
@@ -49,7 +56,7 @@ engine.ops.run('shop.buy', { item: 'bread' }); // n: 1; with n: 0, dev throws
49
56
  import { readParams } from 'threedog';
50
57
  const PARAMS = { radius: { type: 'number', default: 2, min: 0, desc: 'pickup reach in m' }, sound: 'string?' };
51
58
  export const magnet = (opts) => {
52
- const o = readParams('magnet', PARAMS, opts); // wrong type / out of range throws [module-params] with the fix; an unknown key throws in dev and warns once in a release build
59
+ const o = readParams('magnet', PARAMS, opts); // wrong type / out of range throws [module-params] with the fix; an unknown key throws in dev and warns once in a release build
53
60
  return { name: 'magnet', type: 'rules', params: PARAMS, options: o, stage: 'gameplay', install(e) { return { radius: o.radius }; } };
54
61
  };
55
62
  ```