threedog 1.1.0 → 1.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (370) hide show
  1. package/CHANGELOG.md +893 -798
  2. package/README.md +1 -1
  3. package/core/assets/Animator.js +41 -3
  4. package/core/assets/Assets.js +100 -24
  5. package/core/assets/assetEntry.js +73 -20
  6. package/core/assets/assetHot.js +68 -16
  7. package/core/assets/assetLoad.js +6 -6
  8. package/core/assets/assetLod.js +9 -2
  9. package/core/assets/assetManifest.js +12 -2
  10. package/core/assets/assetPart.js +54 -0
  11. package/core/assets/ik.js +271 -0
  12. package/core/assets/modelNeeds.js +37 -0
  13. package/core/assets/namedModel.js +102 -29
  14. package/core/assets/nodeVisibility.js +15 -0
  15. package/core/audio/Audio.js +36 -4
  16. package/core/audio/audioReverb.js +99 -0
  17. package/core/audio/audioRules.js +1 -1
  18. package/core/audio/audioVoice.js +1 -1
  19. package/core/base/Events.js +14 -4
  20. package/core/base/Random.js +1 -1
  21. package/core/base/Vars.js +1 -1
  22. package/core/base/docRef.js +51 -0
  23. package/core/base/errorCodes.js +187 -126
  24. package/core/base/errorHints.js +9 -7
  25. package/core/base/errors.js +25 -10
  26. package/core/base/events.generated.js +2 -0
  27. package/core/base/freeParts.js +76 -0
  28. package/core/base/math.js +28 -0
  29. package/core/base/sections.js +5 -5
  30. package/core/base/validate.js +31 -3
  31. package/core/engine/Engine.js +17 -7
  32. package/core/engine/Loading.js +5 -3
  33. package/core/engine/copies.js +1 -1
  34. package/core/engine/headlessLoad.js +4 -1
  35. package/core/engine/lifecycle.js +32 -16
  36. package/core/engine/loop.js +71 -27
  37. package/core/engine/moduleSlots.js +2 -2
  38. package/core/engine/moduleTypes.js +3 -3
  39. package/core/engine/modules.js +65 -39
  40. package/core/engine/page.js +6 -3
  41. package/core/engine/services.js +6 -5
  42. package/core/engine/startup.js +8 -7
  43. package/core/input/Input.js +28 -14
  44. package/core/input/inputContext.js +28 -16
  45. package/core/input/inputKeyboard.js +31 -3
  46. package/core/input/inputPad.js +4 -0
  47. package/core/input/inputPointer.js +2 -1
  48. package/core/input/inputSeat.js +1 -1
  49. package/core/inspect/Budget.js +109 -19
  50. package/core/inspect/DebugOverrides.js +28 -4
  51. package/core/inspect/Describe.js +17 -9
  52. package/core/inspect/Inspect.js +4 -2
  53. package/core/inspect/InspectMaterials.js +3 -1
  54. package/core/inspect/InspectPerf.js +19 -9
  55. package/core/inspect/InspectScene.js +32 -7
  56. package/core/inspect/MaterialInfo.js +19 -2
  57. package/core/inspect/UrlState.js +50 -28
  58. package/core/inspect/catalog.js +28 -9
  59. package/core/inspect/debugView.js +2 -1
  60. package/core/inspect/describeRender.js +25 -13
  61. package/core/inspect/describeText.js +14 -6
  62. package/core/inspect/lightWatch.js +1 -1
  63. package/core/inspect/metadata.generated.js +35 -17
  64. package/core/inspect/pictureChecks.js +148 -0
  65. package/core/inspect/pictureMenu.js +84 -0
  66. package/core/inspect/pictureWriters.js +26 -6
  67. package/core/inspect/textureBytes.js +12 -2
  68. package/core/inspect/toolDoor.js +2 -4
  69. package/core/ops/Ops.js +11 -4
  70. package/core/ops/holds.js +27 -10
  71. package/core/ops/opsAtomic.js +15 -7
  72. package/core/ops/opsGuard.js +2 -2
  73. package/core/ops/opsRun.js +8 -7
  74. package/core/ops/sharedPoint.js +72 -21
  75. package/core/ops/stacks.js +56 -16
  76. package/core/saves/SaveStore.js +9 -3
  77. package/core/saves/Saves.js +32 -23
  78. package/core/saves/saveApply.js +96 -44
  79. package/core/saves/saveIds.js +1 -1
  80. package/core/saves/saveVersions.js +7 -5
  81. package/core/saves/session.js +17 -8
  82. package/core/saves/stateReplace.js +34 -15
  83. package/core/scene/Rays.js +52 -10
  84. package/core/scene/Views.js +36 -15
  85. package/core/scene/adaptive.js +144 -21
  86. package/core/scene/drawOnly.js +17 -0
  87. package/core/scene/gameLights.js +47 -4
  88. package/core/scene/sceneMethods.js +13 -11
  89. package/core/scene/stepPoses.js +11 -3
  90. package/core/scene/targeting.js +5 -3
  91. package/core/scene/thingOps.js +1 -1
  92. package/core/scene/tier.js +15 -0
  93. package/core/stream/Batching.js +30 -7
  94. package/core/stream/Stream.js +26 -7
  95. package/core/stream/batchGroups.js +2 -2
  96. package/core/stream/chunkStream.js +7 -5
  97. package/core/stream/prepare.js +77 -0
  98. package/core/time/skip.js +3 -1
  99. package/core/time/time.js +4 -2
  100. package/docs/AI.md +82 -83
  101. package/docs/API.md +16 -16
  102. package/docs/CODEMAP.md +17 -11
  103. package/docs/COMMANDS.md +139 -142
  104. package/docs/CONVENTIONS.md +37 -49
  105. package/docs/MIGRATING-0.8.md +2 -2
  106. package/docs/MIGRATING-1.0.md +2 -2
  107. package/docs/THREE.md +30 -35
  108. package/docs/api/assets.md +3 -1
  109. package/docs/api/audio.md +4 -2
  110. package/docs/api/budget.md +5 -0
  111. package/docs/api/characters.md +10 -8
  112. package/docs/api/collision.md +6 -4
  113. package/docs/api/engine.md +16 -16
  114. package/docs/api/events.md +3 -2
  115. package/docs/api/ground.md +6 -5
  116. package/docs/api/hud.md +4 -2
  117. package/docs/api/input.md +5 -5
  118. package/docs/api/particles.md +2 -1
  119. package/docs/api/photo.md +3 -0
  120. package/docs/api/post.md +7 -4
  121. package/docs/api/quests.md +2 -2
  122. package/docs/api/rays.md +1 -2
  123. package/docs/api/saves.md +7 -7
  124. package/docs/api/settings.md +2 -2
  125. package/docs/api/tools.md +3 -1
  126. package/docs/api/vars.md +1 -1
  127. package/docs/api/vegetation.md +4 -2
  128. package/docs/api/world.md +1 -1
  129. package/docs/recipes/01-new-game.md +16 -17
  130. package/docs/recipes/02-npc.md +22 -18
  131. package/docs/recipes/03-items-pickups.md +37 -35
  132. package/docs/recipes/04-quests.md +15 -10
  133. package/docs/recipes/05-props-bake.md +101 -95
  134. package/docs/recipes/06-clock-events.md +28 -28
  135. package/docs/recipes/07-flow-scenes-pause.md +29 -26
  136. package/docs/recipes/08-weather-sky.md +52 -64
  137. package/docs/recipes/09-materials-lights-models.md +26 -17
  138. package/docs/recipes/10-blender-level.md +15 -10
  139. package/docs/recipes/11-vehicles.md +12 -7
  140. package/docs/recipes/12-navmesh.md +44 -26
  141. package/docs/recipes/13-animation.md +56 -45
  142. package/docs/recipes/14-custom-module.md +21 -18
  143. package/docs/recipes/15-perf.md +61 -55
  144. package/docs/recipes/16-dev-bridge.md +24 -33
  145. package/docs/recipes/18-world.md +36 -42
  146. package/docs/recipes/19-shooting-picking.md +20 -15
  147. package/docs/recipes/20-content-actions-save.md +48 -56
  148. package/docs/recipes/21-camera.md +45 -54
  149. package/docs/recipes/22-shop-gold.md +12 -7
  150. package/docs/recipes/23-ops.md +25 -23
  151. package/docs/recipes/26-ui-parts.md +67 -47
  152. package/docs/recipes/27-net.md +12 -7
  153. package/docs/recipes/28-terrain.md +24 -21
  154. package/docs/recipes/29-grid.md +32 -27
  155. package/docs/recipes/30-templates.md +21 -20
  156. package/docs/recipes/31-audio.md +39 -22
  157. package/docs/recipes/32-action-game.md +19 -14
  158. package/docs/recipes/33-stream-sources.md +15 -11
  159. package/docs/recipes/34-environment-lighting.md +126 -70
  160. package/docs/recipes/35-picture-from-reference.md +8 -8
  161. package/docs/recipes/36-ground-plants.md +27 -21
  162. package/docs/recipes/40-scene.md +19 -28
  163. package/docs/recipes/43-shader-patches-surfaces.md +15 -12
  164. package/docs/recipes/44-water-weather-hooks.md +34 -31
  165. package/docs/recipes/45-cascaded-shadows.md +35 -26
  166. package/docs/recipes/46-blender-art-route.md +7 -2
  167. package/docs/recipes/49-game-module-contract.md +13 -8
  168. package/docs/recipes/50-own-renderer.md +6 -2
  169. package/docs/recipes/51-capability-catalog.md +15 -8
  170. package/docs/recipes/52-around-the-picture.md +34 -32
  171. package/docs/recipes/53-ground-up-close.md +6 -1
  172. package/docs/recipes/55-mods-time-wrap.md +27 -19
  173. package/docs/recipes/56-webgpu-tsl.md +75 -43
  174. package/docs/recipes/57-control.md +18 -13
  175. package/docs/recipes/58-input.md +26 -16
  176. package/docs/recipes/59-depth-post-effects.md +8 -3
  177. package/docs/recipes/60-judge-the-picture.md +10 -9
  178. package/docs/recipes/61-deploy.md +5 -0
  179. package/docs/recipes/62-picture-code.md +72 -79
  180. package/docs/recipes/63-third-person-start.md +48 -45
  181. package/docs/recipes/64-particles.md +22 -10
  182. package/docs/recipes/65-swarm.md +18 -13
  183. package/docs/recipes/66-common-tasks.md +38 -35
  184. package/examples/action/.threedog/content-index.json +1 -1
  185. package/examples/action/GAMEMAP.md +2 -3
  186. package/examples/action/main.js +3 -3
  187. package/examples/action/picture/lights.js +3 -1
  188. package/examples/perf-island/.threedog/content-index.json +1 -1
  189. package/examples/perf-island/GAMEMAP.md +3 -3
  190. package/examples/perf-island/picture/lights.js +2 -1
  191. package/examples/plain-picture/GAMEMAP.md +1 -1
  192. package/examples/rc2d/GAMEMAP.md +1 -1
  193. package/examples/styletest/.threedog/content-index.json +1 -1
  194. package/examples/styletest/GAMEMAP.md +2 -2
  195. package/examples/styletest/main.js +1 -1
  196. package/examples/techniques/interior-light/README.md +3 -3
  197. package/examples/techniques/interior-light/interiorLight.js +2 -4
  198. package/examples/techniques/interior-light/picture/lights.js +2 -1
  199. package/examples/techniques/modular-building/picture/lights.js +3 -1
  200. package/examples/techniques/outlines-and-rim/picture/lights.js +3 -1
  201. package/examples/techniques/procedural-animation/README.md +1 -1
  202. package/examples/techniques/procedural-animation/main.js +1 -1
  203. package/examples/webgpu-tsl/GAMEMAP.md +1 -1
  204. package/examples/world/.threedog/content-index.json +1 -1
  205. package/examples/world/GAMEMAP.md +2 -3
  206. package/examples/world/art/humanoid.js +1 -1
  207. package/examples/world/main.js +6 -3
  208. package/index.d.ts +2 -2
  209. package/llms.txt +101 -0
  210. package/modules/ambience/Ambience.js +21 -5
  211. package/modules/calendar/index.js +9 -5
  212. package/modules/calendar/schedule.js +23 -8
  213. package/modules/camera/FirstPersonCamera.js +3 -1
  214. package/modules/camera/FollowCamera.js +10 -5
  215. package/modules/camera/RtsCamera.js +4 -3
  216. package/modules/camera/common.js +70 -8
  217. package/modules/camera/contract.js +1 -1
  218. package/modules/characters/Character.js +16 -10
  219. package/modules/characters/NPC.js +31 -19
  220. package/modules/characters/assetModel.js +14 -9
  221. package/modules/characters/astar.js +6 -1
  222. package/modules/characters/contract.js +2 -2
  223. package/modules/characters/index.js +34 -22
  224. package/modules/characters/movers/manual.js +1 -1
  225. package/modules/characters/movers/rapier.js +17 -2
  226. package/modules/characters/movers/simple.js +1 -1
  227. package/modules/characters/movers/support.js +16 -7
  228. package/modules/characters/npcAvoid.js +2 -2
  229. package/modules/characters/npcSim.js +3 -2
  230. package/modules/characters/pathAsync.js +24 -8
  231. package/modules/characters/pathJob.js +1 -1
  232. package/modules/characters/player.js +10 -9
  233. package/modules/characters/playerStrings.js +5 -5
  234. package/modules/characters/proceduralRig.js +5 -5
  235. package/modules/characters/useModel.js +6 -0
  236. package/modules/characters/walkTo.js +1 -1
  237. package/modules/collision/Collision.js +29 -18
  238. package/modules/collision/grid.js +22 -4
  239. package/modules/content/index.js +3 -1
  240. package/modules/content/loader.js +1 -1
  241. package/modules/content/models.js +82 -33
  242. package/modules/content/props.js +2 -1
  243. package/modules/content/rules.js +11 -5
  244. package/modules/content/templates.js +3 -3
  245. package/modules/content/words.js +2 -2
  246. package/modules/debug/DebugPanel.js +9 -9
  247. package/modules/flow/index.js +9 -6
  248. package/modules/gameplay/Dialogue.js +34 -20
  249. package/modules/gameplay/Interactions.js +19 -15
  250. package/modules/gameplay/Inventory.js +9 -4
  251. package/modules/gameplay/Quests.js +12 -10
  252. package/modules/gameplay/pickups.js +23 -11
  253. package/modules/grid/index.js +1 -1
  254. package/modules/grid/preview.js +2 -2
  255. package/modules/grid/tiles.js +1 -1
  256. package/modules/hlod/index.js +4 -1
  257. package/modules/hud/index.js +47 -10
  258. package/modules/hud/parts.js +28 -9
  259. package/modules/level/geometry.js +8 -3
  260. package/modules/level/index.js +10 -5
  261. package/modules/level/load.js +4 -2
  262. package/modules/lights/sources.js +1 -1
  263. package/modules/music/Music.js +22 -4
  264. package/modules/nav/index.js +20 -10
  265. package/modules/particles/Particles.js +31 -14
  266. package/modules/particles/effect.js +20 -5
  267. package/modules/particles/lit.js +72 -0
  268. package/modules/photo/Photo.js +72 -28
  269. package/modules/photo/pathTrace.js +106 -0
  270. package/modules/rigid/RigidBodies.js +23 -14
  271. package/modules/rigid/Vehicles.js +3 -13
  272. package/modules/rigid/sync.js +2 -1
  273. package/modules/settings/Settings.js +52 -20
  274. package/modules/settings/apply.js +23 -9
  275. package/modules/settings/sections.js +39 -6
  276. package/modules/settings/strings.js +2 -0
  277. package/modules/settings/view.js +19 -3
  278. package/modules/sky/dome.js +15 -3
  279. package/modules/sky/environment.js +28 -12
  280. package/modules/sky/fog.js +1 -1
  281. package/modules/sky/frame.js +6 -1
  282. package/modules/sky/shader.js +4 -3
  283. package/modules/sky/skyModule.js +8 -4
  284. package/modules/swarm/Swarm.js +1 -1
  285. package/modules/terrain/ChunkManager.js +61 -15
  286. package/modules/terrain/chunkJob.js +2 -2
  287. package/modules/terrain/index.js +20 -5
  288. package/modules/terrain/terrainEdit.js +8 -4
  289. package/modules/terrain/terrainTexture.js +4 -2
  290. package/modules/timeline/Timeline.js +4 -3
  291. package/modules/timeline/Tween.js +3 -0
  292. package/modules/timeline/letterbox.js +1 -0
  293. package/modules/triggers/index.js +36 -17
  294. package/modules/vegetation/Vegetation.js +81 -19
  295. package/modules/vegetation/densityMap.js +13 -8
  296. package/modules/vegetation/draw.js +147 -24
  297. package/modules/vegetation/groundChunks.js +20 -5
  298. package/modules/vegetation/index.js +3 -3
  299. package/modules/vegetation/modelGeometry.js +9 -4
  300. package/modules/water/Water.js +11 -8
  301. package/modules/weather/Weather.js +7 -2
  302. package/modules/weather/shaders.js +25 -5
  303. package/modules/weather/weatherDraw.js +20 -6
  304. package/modules/world/World.js +2 -1
  305. package/modules/world/index.js +2 -2
  306. package/modules/world/persist.js +6 -2
  307. package/modules/world/views.js +15 -2
  308. package/package.json +5 -1
  309. package/presets.js +5 -5
  310. package/render/PostFX.js +102 -42
  311. package/render/backend.js +142 -16
  312. package/render/bindingLimits.js +59 -0
  313. package/render/cascades.js +3 -1
  314. package/render/cascades.tsl.js +2 -0
  315. package/render/daylight.js +7 -1
  316. package/render/detail.js +7 -4
  317. package/render/effects.js +27 -8
  318. package/render/fogLook.js +24 -0
  319. package/render/fuse.js +5 -2
  320. package/render/fx/compareLevel.tsl.js +23 -0
  321. package/render/fx/detail.tsl.js +9 -7
  322. package/render/fx/index.js +9 -2
  323. package/render/fx/library.tsl.js +1 -0
  324. package/render/fx/lightShaft.tsl.js +114 -0
  325. package/render/fx/noise.tsl.js +25 -8
  326. package/render/fx/objectOrigin.tsl.js +39 -10
  327. package/render/fx/particles.tsl.js +23 -6
  328. package/render/fx/patchNodes.tsl.js +17 -12
  329. package/render/fx/pcss.tsl.js +51 -0
  330. package/render/fx/postWebGPU.tsl.js +104 -29
  331. package/render/fx/sky.tsl.js +3 -9
  332. package/render/fxNumbers.js +10 -4
  333. package/render/impostor.tsl.js +107 -0
  334. package/render/lighting.js +33 -1
  335. package/render/lightmap.js +42 -28
  336. package/render/lights.js +19 -3
  337. package/render/materials.js +6 -4
  338. package/render/mergeCommon.js +4 -1
  339. package/render/occlusion.js +14 -4
  340. package/render/patches.js +79 -41
  341. package/render/postRuns.js +32 -0
  342. package/render/postWebGL.js +97 -10
  343. package/render/probes.js +10 -14
  344. package/render/shaderErrors.js +44 -7
  345. package/render/shadowCache.tsl.js +33 -5
  346. package/render/shadows.js +42 -16
  347. package/render/slots.js +8 -5
  348. package/render/vertexInputs.js +52 -0
  349. package/types/core.d.ts +115 -47
  350. package/types/gameplay.d.ts +56 -23
  351. package/types/generated/core/audio/Audio.d.ts +27 -1
  352. package/types/generated/core/base/Random.d.ts +1 -1
  353. package/types/generated/core/input/Input.d.ts +6 -8
  354. package/types/generated/core/input/inputSeat.d.ts +1 -1
  355. package/types/generated/core/inspect/Budget.d.ts +26 -0
  356. package/types/generated/core/inspect/DebugOverrides.d.ts +0 -2
  357. package/types/generated/core/saves/Saves.d.ts +10 -7
  358. package/types/generated/core/saves/session.d.ts +8 -2
  359. package/types/generated/core/scene/Rays.d.ts +1 -3
  360. package/types/generated/core/scene/Views.d.ts +17 -3
  361. package/types/generated/modules/particles/Particles.d.ts +1 -1
  362. package/types/generated/modules/world/World.d.ts +2 -1
  363. package/types/generated/render/PostFX.d.ts +35 -9
  364. package/types/physics.d.ts +796 -764
  365. package/types/pixel.d.ts +1 -1
  366. package/types/tsl.d.ts +62 -1
  367. package/types/world.d.ts +12 -3
  368. package/ui/Focus.js +7 -5
  369. package/ui/Parts.js +1 -1
  370. package/ui/touchPart.js +6 -3
@@ -7,9 +7,7 @@ import { codedError } from '../base/errorHints.js';
7
7
  import { thing } from './thingOps.js';
8
8
  import { isUnder } from '../base/util.js';
9
9
  import { freshFrame, renderOnce as drawOnce } from '../../render/backend.js';
10
-
11
- /** The geometry and materials of one object */
12
- const parts = o => [o.geometry, ...[].concat(o.material)].filter(Boolean);
10
+ import { freeParts, partsOf as parts, copyOwns, kept } from '../base/freeParts.js';
13
11
  /**
14
12
  * How many objects in the scene use each geometry and material. Why remove asks: disposing a kit that other streamed blocks still draw makes the renderer
15
13
  * rebuild all of them (worst frame 270 ms against 79 in the city stress run). One walk per task, so removing ten thousand objects in a loop walks once; an object
@@ -71,9 +69,12 @@ export const sceneMethods = {
71
69
  thingConflict(text) { this._things.conflict(text); },
72
70
  /**
73
71
  * Delete an object for good: detach it, unregister its rays and dispose the geometries and materials nothing else in the scene uses (textures are kept).
74
- * One still used by another object stays, and goes with its last user. Geometry and materials shared by assets model clones are only decremented in use count (see Assets.js)
72
+ * One still used by another object stays, and goes with its last user. Geometry and materials shared by assets model clones are only decremented in use count (see Assets.js).
73
+ * The call is the game handing the object over (design.md 6.2), so a part the game made goes too; a model copy's own bones go with the copy
75
74
  */
76
75
  remove(...objs) {
76
+ // every root leaves and is uncounted first, then one free over all of them: two roots sharing a material free it once, and a part one root still
77
+ // drew while the other was freed is not kept by a root that is leaving in the same call
77
78
  for (const o of objs) {
78
79
  const counted = isUnder(o, this.scene) && !!this._users; // the count was made while this object was still in the scene
79
80
  o.removeFromParent();
@@ -81,19 +82,19 @@ export const sceneMethods = {
81
82
  this.rays.forget(o);
82
83
  this.assets.forget(o);
83
84
  this._poses.forget(o);
84
- const shared = this.assets.shared, held = this.batching.held; // a batch still drawing the same geometry / material keeps it alive
85
85
  if (counted) o.traverse(c => { for (const x of parts(c)) this._users.set(x, (this._users.get(x) ?? 0) - 1); });
86
- // The whole-scene count only for a part nothing else keeps: unloading a streamed block whose kit is all held by batches walked every object of the district for nothing (7 ms in one frame of the city run)
87
- const free = []; o.traverse(c => { for (const x of parts(c)) if (!shared.has(x) && !held.has(x)) free.push(x); });
88
- if (free.length) { const users = sceneUsers(this); for (const x of free) if (!(users.get(x) > 0)) x.dispose(); }
89
86
  }
87
+ const shared = this.assets.shared, held = this.batching.held; // a batch still drawing the same geometry / material keeps it alive
88
+ // The whole-scene count only for a part nothing else keeps (mine asks the cheap sets first): unloading a streamed block whose kit is all held by batches
89
+ // walked every object of the district for nothing (7 ms in one frame of the city run). A kept part (keepPart) is its maker's to free
90
+ freeParts(objs, x => !shared.has(x) && !held.has(x) && !kept(x) && !(sceneUsers(this).get(x) > 0), { own: c => copyOwns(shared, c) || c.isInstancedMesh || c.isBatchedMesh });
90
91
  },
91
92
  /**
92
93
  * Draw one picture now, outside the loop, on either renderer. renderOnce() (target null, the engine camera): the frame the player sees, onto
93
94
  * the canvas through engine.post; read the canvas in the same task (canvas.toDataURL / drawImage), as photo mode does.
94
- * renderOnce(target): that frame through engine.post into a render target instead (the canvas's pixels: tone mapped, output color space;
95
- * with no post work on, three's plain draw into a target). renderOnce(target, camera) with another camera: the scene without post (the chain
96
- * is built around the engine camera's screen), into target or, with target null, the canvas. On WebGPURenderer each call is a fresh node frame, so a RenderPipeline's scene
95
+ * renderOnce(target): that frame into a render target instead, always the canvas's pixels (tone mapped, output color space), whether or not an
96
+ * effect is on. renderOnce(target, camera) with another camera: the scene without post (the chain is built around the engine camera's screen) and
97
+ * as three draws into a target, linear and not tone mapped (for data or your own pass); into target or, with target null, the canvas. On WebGPURenderer each call is a fresh node frame, so a RenderPipeline's scene
97
98
  * pass, which three draws once per frame, draws again: two calls in one task give two pictures (docs/plans/2026-11-03-webgpu-phase2.md 3).
98
99
  * @example engine.renderOnce(); const url = engine.renderer.domElement.toDataURL('image/png');
99
100
  * engine.renderOnce(rt, mapCamera); // a minimap / thumbnail into your own render target
@@ -103,6 +104,7 @@ export const sceneMethods = {
103
104
  */
104
105
  renderOnce(target = null, camera = this.camera) {
105
106
  const own = this._ownFrame; // an engine draw, not the game taking the canvas over (render/ownFrame.js)
107
+ this._gameLights?.sync(); // the light watch catches up first: a RectAreaLight added since the last frame gets its tables before this draw (gameLights.js)
106
108
  if (own) own.inside++;
107
109
  try {
108
110
  if (camera === this.camera) { freshFrame(this.renderer); this.post.render(0, target); return; }
@@ -5,6 +5,7 @@
5
5
  // would rewrite the Euler the mover keeps facing in. The object's own matrix is composed here and matrixAutoUpdate is off just for that draw.
6
6
  // Anything that placed the object outside a step (a tween, a frame-driven mover, a platform carried in frame) leaves it different from the step's end: it is then drawn as it stands.
7
7
  import * as THREE from 'three';
8
+ import { codedError } from '../base/errorHints.js';
8
9
 
9
10
  /** Farther than this in one step (squared meters) is a teleport, not motion: drawn at once, never swept across the map */
10
11
  const JUMP2 = 16;
@@ -18,9 +19,16 @@ export class StepPoses {
18
19
  /** objects whose matrix is held for this draw */ this.held = [];
19
20
  engine.time.onMove(() => this.end());
20
21
  }
21
- /** place(at): how to move o if a solver owns its pose (a rigid body); gone(): what that solver does when o leaves for good. Core names no module, so the solver says both here */
22
- add(o, place = null, gone = null) { this.map.set(o, { o, place, gone, last: o.position.clone(), lastRot: o.quaternion.clone(), pos: o.position.clone(), rot: o.quaternion.clone(), moved: false }); }
23
- remove(o) { this.map.delete(o); }
22
+ /** place(at): how to move o if a solver owns its pose (a rigid body); gone(): what that solver does when o leaves for good. Core names no module, so the solver says both here.
23
+ * One object, one owner: a second add throws and names the first (two solvers writing one mesh, the last one winning silently, was the bug). owner() names it for that error (a function, so a character's id is read only if it is needed). Returns the owner's handle:
24
+ * remove() deletes only this entry, so an owner that is already gone cannot delete a newer one's */
25
+ add(o, place = null, gone = null, owner = () => 'another owner') {
26
+ const had = this.map.get(o);
27
+ if (had) throw codedError('rigid-misuse', `This object already has a physics owner: ${had.owner()}. One object has one owner of its pose (a rigid body, a character); ${owner()} cannot also take it. Remove the first (its remove() / dispose()) or give ${owner()} an object of its own`);
28
+ const p = { o, owner, place, gone, last: o.position.clone(), lastRot: o.quaternion.clone(), pos: o.position.clone(), rot: o.quaternion.clone(), moved: false };
29
+ this.map.set(o, p);
30
+ return { remove: () => { if (this.map.get(o) === p) this.map.delete(o); } };
31
+ }
24
32
  /** o and all under it left for good (engine.remove): a level's root takes the crates placed in it along, and a solver must not keep them solid and unseen */
25
33
  forget(o) { if (this.map.size) o.traverse(c => this.map.get(c)?.gone?.()); }
26
34
  /** A write moves o outside any step: the object goes there, and whatever solves it too, or the solver's next pose would undo the write */
@@ -8,9 +8,11 @@ const KEYS = ['radius', 'cone', 'close', 'angleWeight', 'blocked', 'at'];
8
8
  const yawOf = view => typeof view === 'number' ? view : Math.atan2(view.x, view.z);
9
9
  /** Candidate position: an Object3D / NPC / Character / world record has .position; a Vector3 / { x, z } / [x, y, z] is the position itself */
10
10
  const posOf = c => c.position ?? c;
11
+ // these two functions live in api/tools.md, not api/engine.md (the code's default page), so the error carries its own pointer
12
+ const misuse = (code, text) => Object.assign(codedError(code, text), { docs: ['api/tools.md'] });
11
13
  function check(fn, opts) {
12
- if ('range' in opts) throw codedError('unknown-option', `${fn}(): the distance option is radius (meters), as in world.query: write { radius: ${opts.range} }`);
13
- for (const k of Object.keys(opts)) if (!KEYS.includes(k)) throw codedError('unknown-option', `${fn}(): unknown option '${k}'; available: ${KEYS.join(', ')}`);
14
+ if ('range' in opts) throw misuse('unknown-option', `${fn}(): the distance option is radius (meters), as in world.query: write { radius: ${opts.range} }`);
15
+ for (const k of Object.keys(opts)) if (!KEYS.includes(k)) throw misuse('unknown-option', `${fn}(): unknown option '${k}'; available: ${KEYS.join(', ')}`);
14
16
  }
15
17
 
16
18
  /**
@@ -47,7 +49,7 @@ export function pickTarget(from, view, candidates, opts = {}) {
47
49
  */
48
50
  export function switchTarget(from, view, current, candidates, side, opts = {}) {
49
51
  check('switchTarget', opts);
50
- if (side !== 1 && side !== -1) throw codedError('engine-misuse', `switchTarget(): side must be 1 (right) or -1 (left), got ${side}`);
52
+ if (side !== 1 && side !== -1) throw misuse('engine-misuse', `switchTarget(): side must be 1 (right) or -1 (left), got ${side}`);
51
53
  const { radius = 15, blocked = null, at = posOf } = opts;
52
54
  const [fx, fz] = xzOf(posOf(from)), yaw = yawOf(view);
53
55
  // right of the view is the negative angle direction (facing grows toward +X, the screen's right is at -yaw), so negate to sort left → right
@@ -113,7 +113,7 @@ export function installThings(e) {
113
113
  * @example engine.explainWith((e, t, out) => { const r = e.myRecords.get(t.id); if (r) out.state = { ...r }; });
114
114
  */
115
115
  e.explainWith = fn => { T.explainers.push(fn); return { remove: () => { T.explainers = T.explainers.filter(x => x !== fn); } }; };
116
- e.saves.register('scene', { atomic: true, save: () => T.save(), load: d => T.load(d) });
116
+ e.saves.define('scene', { atomic: true, save: () => T.save(), load: d => T.load(d) });
117
117
  const kindOf = id => T.source(id) ? 'record' : T.live(id) ? T.tier(T.byObj.get(T.live(id))) : null;
118
118
  const reasons = {
119
119
  noThing: 'no world record or engine.add object has this id (engine.thing(id) suggests the closest one)',
@@ -11,6 +11,21 @@ export function forcedTier(search = typeof location === 'undefined' ? '' : locat
11
11
  return TIERS.includes(t) ? t : null;
12
12
  }
13
13
 
14
+ /** @type {WeakMap<any, Set<() => void>>} per engine: the parts that rebuild when engine.tier changes */
15
+ const FOLLOWERS = new WeakMap();
16
+ /**
17
+ * Follow engine.tier while running: fn runs once after every change (a preset, the device found at start). Why one notice: the post chain followed
18
+ * the tier and the cascades read it only when made, so a preset changed one and not the other (GPT review l2-render 2). Pixel ratio does not follow
19
+ * here: a settings preset writes its own ratio, and a second writer would undo the player's. @param {any} e @param {() => void} fn @returns {{ remove(): void }}
20
+ */
21
+ export function onTierChange(e, fn) {
22
+ if (!FOLLOWERS.has(e)) FOLLOWERS.set(e, new Set());
23
+ FOLLOWERS.get(e).add(fn);
24
+ return { remove: () => { FOLLOWERS.get(e)?.delete(fn); } };
25
+ }
26
+ /** The tier stack's onChange (core/engine/services.js) @param {any} e */
27
+ export function tierChanged(e) { for (const fn of [...(FOLLOWERS.get(e) ?? [])]) fn(); }
28
+
14
29
  /** The name under engine.saves.storageKey of a player's MSAA choice */
15
30
  export const MSAA_KEY = 'msaa';
16
31
  /**
@@ -24,7 +24,7 @@
24
24
  import * as THREE from 'three';
25
25
  import { warnOnce, DEV, note, fmt } from '../base/validate.js';
26
26
  import { BATCH_LAYER, build, join, leave, dissolve, color, localTint, bounds, snap, same, stored, inBundle } from './batchGroups.js';
27
- import { isUnder } from '../base/util.js';
27
+ import { isUnder, isShown } from '../base/util.js';
28
28
  import { codedError } from '../base/errorHints.js';
29
29
  import { notePatch, patchOn } from '../scene/threePatches.js';
30
30
  import { engineOwned } from '../scene/things.js';
@@ -176,7 +176,10 @@ export class Batching {
176
176
  }
177
177
  /** Re-check one object now (after you changed its parts by hand, or set userData.batch on a root already in the scene); normally automatic @param {THREE.Object3D} obj */
178
178
  refresh(obj) {
179
- const info = this._infoOf(obj), root = info?.root ?? obj; // a part of a placed object: the object is what goes round again
179
+ // a part of a placed object: the object is what goes round again. Untracked (none of its meshes qualified, all hlod's, say): the scene child holding the part
180
+ const info = this._infoOf(obj);
181
+ let root = info?.root ?? obj;
182
+ while (!info && root.parent && root.parent !== this.engine.scene) root = root.parent;
180
183
  if (info) this._untrack(root);
181
184
  this._uncount(root);
182
185
  if (root.parent === this.engine.scene) this.incoming.add(root);
@@ -352,28 +355,38 @@ export class Batching {
352
355
  snap(r, info.snap);
353
356
  if (!r.visible) { this._detach(info); return; }
354
357
  const cs = this.cell, cell = Math.floor(r.position.x / cs) + ',' + Math.floor(r.position.z / cs);
355
- if (cell !== info.cell) { this._detach(info); this._attach(info); return; }
358
+ if (cell !== info.cell) { this._detach(info); this._rejoin(info); return; } // the same judgment as any rejoin: a root that is mirrored as it crosses a cell must not upload
356
359
  r.updateMatrixWorld(true);
360
+ // mirrored now (a scale went negative): _eligible refuses that at tracking, so a live root that turns that way leaves its batch (only itself), not uploaded
361
+ if (info.entries.some(e => e.slot >= 0 && e.mesh.matrixWorld.determinant() < 0)) { this._release(info, 'mirrored'); return; }
357
362
  for (const e of info.entries) if (e.slot >= 0) { e.group.mesh.setMatrixAt(e.slot, e.mesh.matrixWorld); e.group.mesh.instanceMatrix.needsUpdate = true; e.group.dirty = true; }
358
363
  }
359
364
  /** @internal slow round robin: hidden roots coming back, pending roots that moved cell, batched parts changed behind our back */
360
365
  _verify(info) {
361
366
  const r = info.root;
367
+ // A part (or a group above it inside the root) hid itself: same as a hidden root, the model left its batch and rejoins once everything shows again
368
+ if (info.hidden) {
369
+ if (!info.entries.every(e => isShown(e.mesh))) return;
370
+ // what changed while it was out (a transparent material, a child) is judged as at first tracking: _eligible, else the usual eviction
371
+ if (!info.entries.every(e => this._eligible(e.mesh))) { this._release(info, 'changed while hidden'); return; }
372
+ info.hidden = false; snap(r, info.snap); if (r.visible) this._rejoin(info); return;
373
+ }
362
374
  if (!this.live.has(info)) { // not batched: only keep its cell right (so counting stays honest)
363
375
  // A root that moves on every visit (a floating pickup, a patrolling prop) is not static: regrouping it each visit cost a detach / attach
364
376
  // (and a batch build / dissolve at the minCount edge) forever. After MOVING visits in a row it leaves its group; it rejoins once a visit finds it still
365
- if (same(r, info.snap)) { info.moves = 0; if (info.moving) { info.moving = false; if (r.visible) this._attach(info); } return; }
377
+ if (same(r, info.snap)) { info.moves = 0; if (info.moving) { info.moving = false; if (r.visible) this._rejoin(info); } return; }
366
378
  snap(r, info.snap);
367
379
  if (info.moving) return;
368
380
  this._detach(info);
369
381
  if (++info.moves >= MOVING) { info.moving = true; return; }
370
- if (r.visible) this._attach(info);
382
+ if (r.visible) this._rejoin(info);
371
383
  return;
372
384
  }
373
385
  for (const e of info.entries) {
374
386
  if (e.slot < 0) continue;
375
387
  const m = e.mesh, g = e.group;
376
- let why = m.layers.mask !== HIDDEN ? 'layers' : !m.visible ? 'hidden' : m.material !== g.material ? 'material' : m.geometry !== g.geometry ? 'geometry' : m.children.length ? 'children'
388
+ if (m.layers.mask === HIDDEN && !isShown(m)) { this._detach(info); info.hidden = true; return; } // hidden is not a change of the model: no eviction, no ban
389
+ let why = m.layers.mask !== HIDDEN ? 'layers' : m.material !== g.material ? 'material' : m.geometry !== g.geometry ? 'geometry' : m.children.length ? 'children'
377
390
  : m.castShadow !== g.cast || m.receiveShadow !== g.receive ? 'shadow flags' : !isUnder(m, r) ? 're-parented' : '';
378
391
  if (!why) {
379
392
  m.updateWorldMatrix(true, false);
@@ -382,7 +395,17 @@ export class Batching {
382
395
  if (why) { this._evict(info, why); return; }
383
396
  }
384
397
  }
385
- /** @internal */
398
+ /** @internal a root coming back to a batch (shown again, stopped moving, back in a cell) is judged as at first tracking: _eligible, else the usual eviction */
399
+ _rejoin(info) {
400
+ info.root.updateMatrixWorld(true);
401
+ if (info.entries.every(e => this._eligible(e.mesh))) this._attach(info); else this._release(info, 'changed while out of its batch');
402
+ }
403
+ /** @internal only this root is ineligible (mirrored, a material swapped while it was out): it draws on its own and its geometry is not banned, other copies keep batching */
404
+ _release(info, why) {
405
+ warnOnce(fmt(STRINGS.evicted, { name: info.root.name || info.entries[0].mesh.name || 'model', why }));
406
+ this._untrack(info.root);
407
+ }
408
+ /** @internal a batched part changed behind our back: the geometry is banned too, nothing can tell which copies would do it again */
386
409
  _evict(info, why) {
387
410
  warnOnce(fmt(STRINGS.evicted, { name: info.root.name || info.entries[0].mesh.name || 'model', why }));
388
411
  for (const e of info.entries) this.banned.add(e.mesh.geometry);
@@ -7,10 +7,10 @@
7
7
  // h.remove(); // no longer needed (a built one is unloaded)
8
8
  // Stream sources (stream.player, stream.camera, stream.source(...), stream.teleport(...)) are the one list every distance-based loader reads: stream entries,
9
9
  // world models, terrain chunks, hlod and rigid colliders (the Source class is in streamSources.js).
10
- // build runs in engine.jobs spread over frames (nearest first); when build returns an object synchronously it is attached to the scene on the spot inside that
11
- // job (built / ready are already correct when engine.step returns),
12
- // and a returned Promise is awaited before attaching. Unloads only beyond radius x unloadFactor (walking back and forth does not rebuild); keep: true never
13
- // unloads.
10
+ // build runs in engine.jobs spread over frames (nearest first); a returned Promise is awaited first. An object whose materials the renderer has compiled
11
+ // is attached on the spot inside that job (built / ready are correct when engine.step returns). After start, one bringing a material the renderer has not drawn
12
+ // is readied first (prepare.js: textures uploaded, shaders compiled off the frame) and attached a task later, so the frame that first shows it does not hitch.
13
+ // Unloads only beyond radius x unloadFactor (walking back and forth does not rebuild); keep: true never unloads.
14
14
  // At startup start() waits for everything registered within radius to finish building before the loading screen goes away. The grid cell size cellSize is
15
15
  // shared with hlod.
16
16
  /** @import { StreamEntryOptions, StreamHandle, StreamSource, StreamSourceOptions } from '../../types/core' */
@@ -21,6 +21,7 @@ import { codedError } from '../base/errorHints.js';
21
21
  import { fmt } from '../base/validate.js';
22
22
  import { surfaceOr } from '../scene/ground.js';
23
23
  import { Source, SOURCE_KEYS, SOURCE_STRINGS } from './streamSources.js';
24
+ import { Prepare } from './prepare.js';
24
25
 
25
26
  const KEYS = ['position', 'radius', 'build', 'dispose', 'keep', 'priority'];
26
27
  const FULL = { detail: 'full' };
@@ -49,6 +50,7 @@ export class Stream {
49
50
  /** @internal */ this._sources = new Set();
50
51
  /** @internal Bumps when a source is added, removed or moved with at() */ this._version = 0;
51
52
  /** @internal name -> (source) => boolean */ this._checks = new Map();
53
+ /** @internal textures and shaders of streamed content readied before its first draw (prepare.js) */ this._prep = new Prepare(engine);
52
54
  /** Built-in source at the player (engine.focus without one): full detail and physics @type {StreamSource} */
53
55
  this.player = this.source(() => engine.player?.position ?? engine.focus, { name: 'player' });
54
56
  /** Built-in source at the camera focus engine.focus: full detail, no physics @type {StreamSource} */
@@ -294,16 +296,33 @@ export class Stream {
294
296
  // a failed build is tried again the next time a stream source moves (want goes back to false); reported once, the game goes on without it
295
297
  // counted down once: engine.add or a game dispose can throw after _built counted, and queued below 0 means ready is false for good
296
298
  let open = true;
297
- const settle = () => { if (open) { open = false; this.queued--; } };
299
+ const settle = () => { if (open) { open = false; if (!this.engine.disposed) this.queued--; } }; // dispose() zeroed queued: a build failing after it counts nothing
298
300
  const fail = err => { settle(); this.live.delete(h); h.want = false; reportError(this.engine, err, 'stream build', { soft: true }); };
299
301
  this.engine.jobs.add(() => {
300
302
  if (!h.want || !this.entries.has(h)) return this._built(h, null, settle);
301
303
  const t0 = performance.now(), r = h.def.build(); // measure: the 'stream' stage of engine.budget.cost
302
304
  this.engine.budget.cost.end('stream', t0);
303
- if (r && typeof r.then === 'function') return r.then(obj => this._built(h, obj, settle), fail);
304
- this._built(h, r, settle); // synchronous build: attach to the scene on the spot
305
+ // shortcut: an async build's result is readied outside the job budget (it lands in a promise callback); route it through a job if that shows in applyUploadMs
306
+ if (r && typeof r.then === 'function') return r.then(obj => this._show(h, obj, settle, fail), fail);
307
+ this._show(h, r, settle, fail); // synchronous build: attach on the spot when nothing needs readying
305
308
  }, { priority: (h.def.priority ?? 0) - near }).catch(fail);
306
309
  }
310
+ /** @internal Ready obj's textures and shaders first (prepare.js), then attach; queued stays counted until then, so ready and teleport wait for it */
311
+ _show(h, obj, settle, fail) {
312
+ if (this.engine.disposed) return this._late(h, obj);
313
+ let wait = null;
314
+ // the object exists but belongs to nobody until _built: a preprocess that throws (texture upload) must free it, or the retry builds a second one beside it
315
+ try { wait = obj && !obj.parent && h.want ? this._prep.run(obj) : null; } catch (err) { try { this._dispose(h, obj); } catch (e2) { reportError(this.engine, e2, 'stream build', { soft: true }); } throw err; }
316
+ if (wait) wait.then(() => { if (this.engine.disposed) this._late(h, obj); else this._built(h, obj, settle); }).catch(fail); else this._built(h, obj, settle);
317
+ }
318
+ /**
319
+ * @internal A build that finished after engine.dispose: dispose() zeroed queued and released the scene, so neither settle (queued below 0) nor engine.remove
320
+ * may run. The game's own dispose still does, as for any unwanted build: it may free what the scene walk never sees (a lease, a body). Its error is reported, not settled
321
+ */
322
+ _late(h, obj) {
323
+ if (!obj || !h.def.dispose) return;
324
+ try { h.def.dispose(obj); } catch (err) { reportError(this.engine, err, 'stream build', { soft: true }); }
325
+ }
307
326
  /** @internal Build finished (obj null means nothing was built): discard it if no longer wanted, otherwise attach to the scene */
308
327
  _built(h, obj, settle) {
309
328
  settle();
@@ -2,7 +2,7 @@
2
2
  // and the transform snapshots the per-frame check compares. B is the Batching instance; g a group (one cell + geometry + material + shadow flags);
3
3
  // e an entry (one mesh of one placed object). Hidden instances are swap-removed, not zero-scaled (vegetation's way), so batch bounds stay tight.
4
4
  import * as THREE from 'three';
5
- import { copyPatches } from '../../render/patches.js';
5
+ import { cloneMaterial } from '../../render/patches.js';
6
6
  import { RESERVED_LAYERS } from '../../render/layers.js';
7
7
  import { noRaycast } from '../../render/occlusion.js';
8
8
 
@@ -93,7 +93,7 @@ export function localTint(B, m) {
93
93
  const t = B.tints.get(m), base = B.orig.get(m) ?? m.material;
94
94
  if (!base || Array.isArray(base) || !base.color) return;
95
95
  if (t) {
96
- if (!B.orig.has(m)) { B.orig.set(m, base); m.material = copyPatches(base, base.clone()); }
96
+ if (!B.orig.has(m)) { B.orig.set(m, base); m.material = cloneMaterial(base); }
97
97
  m.material.color.copy(base.color).multiply(t);
98
98
  } else if (B.orig.has(m)) { m.material.dispose(); m.material = base; B.orig.delete(m); }
99
99
  }
@@ -9,10 +9,13 @@
9
9
  // (make + register a queued chunk), _dispose(c) (release a chunk's content). Hooks passed here: show(c, visible), level(c, ring) (near-only
10
10
  // detail per ring), count(c, ring) (instances drawn, for stats).
11
11
  import * as THREE from 'three';
12
- import { xzOf } from '../base/math.js';
12
+ import { xzOf, cameraFrustum } from '../base/math.js';
13
13
 
14
14
  const COLLIDER_LAG = 30; // fixed steps before a chunk's collision counts (30 = 0.5 s), times (1 + ring)
15
15
 
16
+ /** Fixed steps until collision of a chunk in this ring counts: 0 for the ring the loading screen waits for, else growing with the ring */
17
+ export const colliderLag = (table, ring) => !table.engine.ready && ring <= 1 ? 0 : COLLIDER_LAG * (1 + ring);
18
+
16
19
  /**
17
20
  * Book the tick a queued chunk's collision takes effect (engine.commits): set from gameplay alone, so machine speed never changes it. Ring 1, which the
18
21
  * loading screen waits for, counts the moment play starts. A table gives gen (bumped on a rebuild), so a ticket of a replaced chunk does nothing.
@@ -20,7 +23,7 @@ const COLLIDER_LAG = 30; // fixed steps before a chunk's collision counts (30
20
23
  */
21
24
  export function bookCollision(table, c, ring, { apply, fallback }) {
22
25
  c.ticket = table.engine.commits.request({
23
- lag: !table.engine.ready && ring <= 1 ? 0 : COLLIDER_LAG * (1 + ring),
26
+ lag: colliderLag(table, ring),
24
27
  apply, fallback,
25
28
  valid: () => table.chunks.get(c.key) === c && c.gen === table.gen,
26
29
  });
@@ -57,7 +60,7 @@ export class ChunkStream {
57
60
  /** stream sources in chunk units: { cx, cz, R, simple }, reused objects (set by follow) */ this.centers = [];
58
61
  this._for = [NaN, NaN]; // view distance and table version the wanted list was last built for
59
62
  this.ver = 0; // +1 whenever the table is cleared: the next follow() plans again
60
- this._frustum = new THREE.Frustum(); this._m = new THREE.Matrix4();
63
+ this._frustum = new THREE.Frustum();
61
64
  this._d2 = c => { let m = Infinity; for (const s of this.centers) m = Math.min(m, (c.cx - s.cx) ** 2 + (c.cz - s.cz) ** 2); return m; };
62
65
  this._byDist = (a, b) => this._d2(a) - this._d2(b);
63
66
  }
@@ -110,8 +113,7 @@ export class ChunkStream {
110
113
  /** LOD + frustum over ready chunks: level(c, ring) each, show(c, visible) when it changes. Returns { visible, instances } (reused object) */
111
114
  cull(camera) {
112
115
  camera.updateMatrixWorld();
113
- this._m.multiplyMatrices(camera.projectionMatrix, camera.matrixWorldInverse);
114
- this._frustum.setFromProjectionMatrix(this._m);
116
+ cameraFrustum(camera, this._frustum);
115
117
  const H = this.hooks, out = this._out ??= { visible: 0, instances: 0 };
116
118
  out.visible = 0; out.instances = 0;
117
119
  for (const c of this.table.chunks.values()) {
@@ -0,0 +1,77 @@
1
+ // Ready content that arrives after start before it is first drawn. start() compiles the startup scene behind the loading screen (core/engine/startup.js); a stream
2
+ // build that brings a material the renderer has not seen compiled it inside the frame that first drew it (the hitch the player sees), and uploaded its textures there.
3
+ // Streamed content goes through this one step instead: textures uploaded with renderer.initTexture, unseen materials compiled with
4
+ // renderer.compileAsync(object, camera, scene) against the scene's own lights and environment and the target the scene draws into, as start() does.
5
+ // Shown only once that settles; content whose materials are all known (the common case: kits, terrain, plants) is shown at once.
6
+ // Plain three.js equivalent: for (const t of textures) renderer.initTexture(t); await renderer.compileAsync(obj, camera, scene); scene.add(obj)
7
+ import { isWebGPU, programCount, borrowRenderer } from '../../render/backend.js';
8
+
9
+ /** Every texture the materials under root hold in a slot (map, normalMap...); a texture reached only through a TSL node is uploaded by the compile @param {any} root @param {Set<any>} [out] */
10
+ export function texturesOf(root, out = new Set()) {
11
+ root.traverse(o => { for (const m of [].concat(o.material || [])) for (const k in m) if (m[k]?.isTexture) out.add(m[k]); });
12
+ return out;
13
+ }
14
+
15
+ /** @internal engine.stream's prepare step (one per engine) */
16
+ export class Prepare {
17
+ constructor(engine) {
18
+ this.engine = engine;
19
+ // material -> true (compiled) or the Promise of its compile, so a second object with it waits for the same compile instead of drawing it half-done.
20
+ // By identity, not by program: a fresh material with a cached program costs one cheap compileAsync and a frame of delay, never a stall
21
+ this.known = new WeakMap();
22
+ // a disposed material lost its program: one a game reuses across builds must compile again when the player walks back
23
+ const known = this.known; // the listener holds the WeakMap only: a game material that outlives the engine must not keep the engine alive
24
+ this._forget = ev => known.delete(ev.target);
25
+ /** compileAsync calls made during play (inspect perf, the streaming test) */ this.compiles = 0;
26
+ // WebGPU: one compileAsync at a time (WebGL's parallel compile is safe: render/backend.js compileThrough). WebGPURenderer (three 0.187) keeps one precompile state: a second call whose items interleave with the first's ends the
27
+ // first's state (its _finishPreCompile then throws on null) and leaves _callDepth one too high, so every later frame draws in a fresh render context and
28
+ // each object gets new records that are never freed (found by tests/specs/stream-prepare.mjs: +4 records and 7 uniform buffers per walk out and back)
29
+ /** @internal the compile in flight, or null */ this._busy = null;
30
+ }
31
+ /** @internal compileAsync(obj) for the target the scene really draws into (the program is keyed by its output, as in startup.js) */
32
+ _compile(obj) {
33
+ const e = this.engine, r = e.renderer;
34
+ if (e.disposed) return Promise.resolve(); // a chained compile whose engine went away meanwhile
35
+ // WebGPU's compileAsync culls by the camera frustum: content streaming in behind the player would compile nothing and still count as known
36
+ const culled = [];
37
+ obj.traverse(o => { if (o.frustumCulled) { culled.push(o); o.frustumCulled = false; } });
38
+ try { return Promise.resolve(borrowRenderer(r, () => { r.setRenderTarget(e.post._sceneTarget()); return r.compileAsync(obj, e.camera, e.scene); })); } catch (err) { return Promise.reject(err); } finally {
39
+ for (const o of culled) o.frustumCulled = true;
40
+ // WebGL compiled the programs just now, before this frame's render: that render must not read the new count as a compile stall
41
+ const n = programCount(r), c = e.budget.cost; if (n != null && c._programs >= 0) c._programs = n;
42
+ }
43
+ }
44
+ /** @internal Track m (three's addEventListener skips a listener already added) */
45
+ _know(m, v) { m.addEventListener('dispose', this._forget); this.known.set(m, v); }
46
+ /** Materials under root count as compiled (start() calls it on the whole scene after its compile) @param {any} root */
47
+ mark(root) { root.traverse(o => { for (const m of [].concat(o.material || [])) this._know(m, true); }); }
48
+ /**
49
+ * Upload obj's textures and compile its unseen materials. null: nothing to wait for, show it now. Otherwise a Promise that resolves (never rejects:
50
+ * a shader error is the renderer's to report, and the object is shown as it would have been) when it may be shown.
51
+ * @param {any} obj @returns {Promise<void> | null}
52
+ */
53
+ run(obj) {
54
+ const e = this.engine, r = e.renderer;
55
+ if (!e.ready || e.disposed || r.initialized === false) return null; // loading: start() compiles everything in the scene; a WebGPURenderer before init has no device
56
+ const t0 = performance.now(); // measure: the 'upload' stage of engine.budget.cost
57
+ const tex = texturesOf(obj);
58
+ for (const t of tex) r.initTexture(t);
59
+ const waits = new Set(), fresh = [];
60
+ obj.traverse(o => { for (const m of [].concat(o.material || [])) { const k = this.known.get(m); if (k === undefined) fresh.push(m); else if (k !== true) waits.add(k); } });
61
+ if (fresh.length) {
62
+ this.compiles++;
63
+ // idle: compiled now, inside the caller's job (its node build is timed below). Busy: chained after the one in flight.
64
+ // shortcut: a chained compile's node build runs in a promise callback, outside the job budget; batch the waiting objects into one call if that shows in applyUploadMs
65
+ const gpu = isWebGPU(r), quiet = () => {}, p = gpu && this._busy ? this._busy.then(() => this._compile(obj)) : this._compile(obj);
66
+ const done = p.then(quiet, quiet).then(() => {
67
+ for (const m of fresh) if (this.known.get(m) === done) this._know(m, true); // disposed meanwhile: forgotten, stays out
68
+ if (this._busy === done) this._busy = null;
69
+ });
70
+ if (gpu) this._busy = done;
71
+ for (const m of fresh) this._know(m, done);
72
+ waits.add(done);
73
+ }
74
+ if (tex.size || fresh.length) e.budget.cost.add('upload', performance.now() - t0); // measure
75
+ return waits.size ? Promise.all(waits).then(() => {}) : null;
76
+ }
77
+ }
package/core/time/skip.js CHANGED
@@ -14,12 +14,13 @@ import { asModule } from '../engine/moduleTypes.js';
14
14
  import { readParams, keysSchema } from '../base/params.js';
15
15
  import { reportError } from '../base/errors.js';
16
16
  import { codedError } from '../base/errorHints.js';
17
- import { fmt } from '../base/validate.js';
17
+ import { fmt, warnOnce } from '../base/validate.js';
18
18
  import { fadeScreen } from '../../ui/UI.js';
19
19
 
20
20
  const NUDGE = 1e-6; // calendar seconds past each mark: land just after it, so float error never leaves a mark uncrossed
21
21
  const STRINGS = {
22
22
  amount: 'engine.skip(): pass { to: "06:00" } (until the calendar clock next reads 06:00) or { seconds: 600 } (calendar seconds, > 0); got {got}',
23
+ noSkip: "engine.skip(): module '{name}' has a fixed hook but no skip hook and no skipKind, so the skipped time does not advance it (its own timers and cooldowns stay behind). Add skip(dt, e, done), or skipKind: 'none' if it should not move",
23
24
  noCalendar: 'engine.skip({ to }) needs the calendar module (it reads the calendar clock: engine.use(calendar({ dayLength: 360 }))); without one pass { seconds } (calendar seconds)',
24
25
  fixedDay: 'engine.skip({ to }): the calendar time of day never moves (calendar({ dayLength: Infinity })), so the clock never reads that time; pass { seconds } (calendar seconds)',
25
26
  hook: 'skip hook of module {name}',
@@ -44,6 +45,7 @@ function amount(e, o) {
44
45
  function jump(e, seconds) {
45
46
  const clock = e.clock, cal = e.calendar, time = e.time; // clock: the calendar view of time (its timers are in time's one queue)
46
47
  let left = seconds, ended = false;
48
+ for (const h of e._hooks.fixed) if (!h.mod.skip && !h.mod.skipKind && !h.mod.noSkip) warnOnce(fmt(STRINGS.noSkip, { name: h.name })); // said at skip time, once per module: a skip that silently leaves a module behind
47
49
  const off = e.events.on('session:end', () => { ended = true; }); // a timer callback ended the playthrough mid-skip: the new one must not be skipped
48
50
  try {
49
51
  while (left > 0 && !ended) {
package/core/time/time.js CHANGED
@@ -1,7 +1,7 @@
1
1
  // engine.time: the one time source. Every other time in the engine is a read-only view of what this module counts.
2
2
  // engine.time.tick fixed steps run (the gameplay timeline: commits, op history, input records); stops while frozen
3
3
  // engine.time.now('real') tick / 60 (+ the part of a skip shorter than one step): no scale, stops while frozen. Cooldowns that ignore bullet time
4
- // engine.time.now('ambient') wind, water, clouds (= uniforms.uTime): moves while frozen too, unless a freezer asked freeze(owner, { ambient: true })
4
+ // engine.time.now('ambient') wind, water, clouds (= uniforms.uTime): moves while frozen too, unless a freezer asked freeze(owner, { still: true })
5
5
  // engine.time.now('world' | 'player' | 'enemies' ...) channel seconds: each step adds 1/60 x the channel's speed. Movement, AI, status effects
6
6
  // engine.time.now('calendar') calendar seconds = world seconds x the calendar rate (stack 'clock.rate'); engine.clock.now is the same number
7
7
  // Channel speeds change only through engine.mod (core/ops/stacks.js):
@@ -40,7 +40,7 @@ export class Time {
40
40
  this.channel('world', { parent: null });
41
41
  this.channel('player');
42
42
  this.channel('calendar', { stack: 'clock.rate' });
43
- engine.saves.register('time', { notAtomic: 'time goes on through a failed op: going back would run timers twice',
43
+ engine.saves.define('time', { notAtomic: 'time goes on through a failed op: going back would run timers twice',
44
44
  version: 2,
45
45
  // v1 kept the calendar in its own 'clock' part ({ now, timers }); v2 has it as the 'calendar' channel of this part
46
46
  migrate: { 1: (d, save) => {
@@ -199,6 +199,8 @@ export class Time {
199
199
  _restart() {
200
200
  const was = [this._tick, this._carry, this._amb], real = this.now('real'), S = this.engine.stacks;
201
201
  this._tick = 0; this._carry = 0; this._setAmbient(0);
202
+ // Only place tick resets to 0 (newGame, load, quit): the event layer's "already fired this tick" marks are keyed by tick, so they are all void after a reset (Events._firedNow)
203
+ this.engine.events._fired = null;
202
204
  S._rebase('real', -real); // an entry no save holds (a system-layer mod, a gate) keeps its time left
203
205
  return () => { [this._tick, this._carry] = was; this._setAmbient(was[2]); S._rebase('real', real); };
204
206
  }