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
@@ -12,9 +12,8 @@
12
12
  //
13
13
  // Determinism: in engine.step() and headless loading frames, jobs ignore the real-time budget and drain the queue (see Jobs.js),
14
14
  // and stream's synchronous builds are attached to the scene before step returns: same input and same seed (engine.random) give the same result.
15
- import { Vector4 } from 'three';
16
15
  import { reportError } from '../base/errors.js';
17
- import { DEV, warnOnce, fmt } from '../base/validate.js';
16
+ import { DEV, warnOnce, fmt, syncOnly } from '../base/validate.js';
18
17
  import { coded, codedError } from '../base/errorHints.js';
19
18
  import { watchLights } from '../inspect/lightWatch.js';
20
19
  import { watchGeometries } from '../inspect/geometryWatch.js';
@@ -22,12 +21,44 @@ import { followFocus } from '../../render/lights.js';
22
21
  import { STEP } from '../time/time.js'; // fixed step length: 60 per second
23
22
  import { adapt } from '../scene/adaptive.js';
24
23
  import { advanceUiClock } from '../time/uiClock.js';
25
- import { resetStats, programCount, freshFrame } from '../../render/backend.js';
24
+ import { resetStats, programCount, freshFrame, holdRenderer, releaseRenderer } from '../../render/backend.js';
26
25
  import { engineDraws } from '../../render/ownFrame.js';
27
26
  import { writeDaylight } from '../../render/daylight.js';
27
+ import { quantile } from '../base/math.js';
28
+ import { unsettled } from './headlessLoad.js';
28
29
  // Most real time one frame may turn into fixed steps (6 steps). A longer hitch slows the game for that frame
29
30
  // instead of replaying it in a burst (no spiral of death, no jump after a stall).
30
31
  const MAX_CATCHUP = 0.1;
32
+ // Module hook timing keeps each module's ms of the last PROF_FRAMES frame-hook cycles: median (steady cost, what budgets judge), mean (what a
33
+ // benchmark run averages) and p95 (spikes). 300 cycles = 5 s live, 10 s of step(), enough for the benchmark pages; each ring is allocated once
34
+ // per module and read on demand, so the sort costs nothing per frame
35
+ const PROF_FRAMES = 300;
36
+ /** Timing judges play, not start-up: the first frame after ready at which loading is done and nothing is unsettled (modules' isReady, the stream's
37
+ * queued builds: the same answer start() and the tools' waits use) clears the module timing ring and the frame-time window, once. Start-up chunk
38
+ * builds would otherwise sit in the median window and read as spikes; a chunk built while walking later still counts */
39
+ function startPlayTiming(e) {
40
+ if (!e.ready || !e.loading.view().done || unsettled(e).length) return;
41
+ e._playTiming = true;
42
+ if (e._prof) e.profile(true);
43
+ e.budget._clearFrames();
44
+ }
45
+ /** Close one frame-hook cycle of module timing: each module's ms of the cycle goes into its ring (0 for a module whose hooks did not run).
46
+ * Each ring counts its own samples: a module first timed late (a level's module, a late use()) is judged on its cycles only, not on zeros for
47
+ * the cycles before it existed.
48
+ * Fixed hooks count one step: the cycle's dearest step (_runHooks keeps it). Why: a slow frame runs several catch-up steps and step() runs
49
+ * frameEvery per cycle, so the summed ms grew with the frame rate, not with the module: the open-world physics read median 0.7 / p95 3.9 ms
50
+ * ("spiky: rigid") on a slow software-rendered page while one step cost about 0.2 ms. The dearest, not the average: a step that itself spikes
51
+ * (a chunk's collider built) still shows in full */
52
+ function closeProfFrame(p) {
53
+ for (const k in p.fix) { p.cur[k] = (p.cur[k] || 0) + p.fix[k]; p.fix[k] = 0; }
54
+ for (const k in p.cur) if (!p.ring[k]) p.ring[k] = { buf: new Float32Array(PROF_FRAMES), i: 0, n: 0 };
55
+ for (const k in p.ring) {
56
+ const r = p.ring[k];
57
+ r.buf[r.i] = p.cur[k] || 0; p.cur[k] = 0;
58
+ r.i = (r.i + 1) % PROF_FRAMES;
59
+ if (r.n < PROF_FRAMES) r.n++;
60
+ }
61
+ }
31
62
  // Most milliseconds one frame spends on catch-up steps (two steps' worth of real time, one 30 fps frame). Why a time budget on top of the
32
63
  // step cap: after a hitch in a heavy scene, 6 steps of 13 ms made a 77 ms fixed phase, so the next frame was long too and caught up again
33
64
  // (a hitch cascade). Judged by the step just measured, so cheap steps still catch up all 6; the time left over is dropped (a brief slow-down)
@@ -41,32 +72,30 @@ const STRINGS = {
41
72
  };
42
73
 
43
74
  const SOFT = { soft: true }; // core steps (render, stream): report once only
44
- const _viewport = new Vector4(), _scissor = new Vector4();
45
75
  /** Call a hook fn.call(self, a, b); errors go to reportError for tiering.
46
76
  * opts: { module } the failing module / SOFT / null (game callback, counts as gameplay).
47
77
  * Takes no ...args and needs no caller closure: the main loop calls this many times a frame, so it must not allocate each time. */
48
78
  function safe(engine, key, fn, opts, self, a, b) {
49
- try { fn.call(self, a, b); } catch (err) { reportError(engine, err, key, opts ?? undefined); }
79
+ try { syncOnly(fn.call(self, a, b), opts?.module ? `${key} of module ${opts.module}` : key); } catch (err) { reportError(engine, err, key, opts ?? undefined); }
50
80
  }
51
81
  /**
52
82
  * One engine.onRender hook. What a hook borrows to draw (the target, viewport, scissor, autoClear, scene.overrideMaterial, camera.layers) it gives back on its last lines, which a
53
- * throw skips, and the engine's frame then draws into an 8-pixel corner or in one flat material from there on. So a hook that throws has them put back. One that returns
83
+ * throw skips, and the engine's frame then draws into an 8-pixel corner or in one flat material from there on. So a hook that throws has them put back (every field
84
+ * render/backend.js holdRenderer lists, scene and camera included). One that returns
54
85
  * is taken at its word: what it left is the game's choice.
55
86
  */
56
87
  function drawHook(f, ctx) {
57
- const { renderer: r, scene, camera } = ctx, target = r.getRenderTarget(), viewport = r.getViewport(_viewport), scissor = r.getScissor(_scissor), scissorTest = r.getScissorTest();
58
- const { autoClear } = r, { overrideMaterial } = scene, { mask } = camera.layers;
59
- try { f(ctx); } catch (err) {
60
- r.setRenderTarget(target); r.setViewport(viewport); r.setScissor(scissor); r.setScissorTest(scissorTest);
61
- r.autoClear = autoClear; scene.overrideMaterial = overrideMaterial; camera.layers.mask = mask;
62
- throw err;
63
- }
88
+ const held = holdRenderer(ctx.renderer, { scene: ctx.scene, camera: ctx.camera });
89
+ let threw = true;
90
+ try { syncOnly(f(ctx), STRINGS.onRender); threw = false; } finally { releaseRenderer(held, threw); }
64
91
  }
65
92
  /** Run one game callback list. remove() replaces the list, so a hook an earlier one removed in this pass (or a dispose) is skipped: it may sit on what its remover just tore down */
66
93
  function runList(e, name, key, a) {
67
94
  const list = e[name];
68
- for (const f of list) if (e[name] === list || e[name].includes(f)) safe(e, key, f, null, undefined, a);
95
+ for (const f of list) if (live(e, name, list, f)) safe(e, key, f, null, undefined, a);
69
96
  }
97
+ /** Whether f still belongs to holder[name]: the list was replaced (remove, dispose) and f is not in the new one = skip it. Shared by runList and the engine.onRender passes */
98
+ const live = (holder, name, list, f) => holder[name] === list || holder[name].includes(f);
70
99
 
71
100
  // The first frame drawn after ready ends the first-frame measure (engine.startup.firstFrameMs, startup.js); one compare per frame after that
72
101
  function firstFrame(e, at) {
@@ -85,7 +114,7 @@ export const loopMethods = {
85
114
  this.input.beginFixed();
86
115
  try {
87
116
  // gameplay frozen: no clock moves, no channel, no mod({ for }) timer (frame hooks and render continue). uTime is the ambient clock (wind, water,
88
- // clouds): it keeps moving behind a pause menu, the common expectation, unless a freezer asked freeze(owner, { ambient: true })
117
+ // clouds): it keeps moving behind a pause menu, the common expectation, unless a freezer asked freeze(owner, { still: true })
89
118
  if (this.frozen) { this.time._frozenStep(!this.still); return; }
90
119
  this.time._beginStep(); // the one counter (core/time/time.js): this step's commits, ops and input records carry the new tick
91
120
  this._inFixed = true; // ops log phase 'fixed' and the dev guard lets gameplay writes through
@@ -102,8 +131,9 @@ export const loopMethods = {
102
131
  if (this.disposed) return; // a fixed step of this frame disposed the engine (step() checks the same)
103
132
  // one profile frame = one frame-hook cycle (the real loop: one per rendered frame; step(): one per frameEvery fixed steps). Counting rendered frames
104
133
  // instead made step(render: false) divide by zero frames and report the whole run's milliseconds as one frame's
105
- if (this._prof) this._prof.frames++;
134
+ if (this._prof) closeProfFrame(this._prof);
106
135
  this._picture?.frameStart();
136
+ this.rays.fresh = -1; // frames advance while time is frozen (tick stays): the next ray re-reads the statics' matrices
107
137
  advanceUiClock(this, dt); // headless pages: UI display timers run on the stepped time (core/time/uiClock.js)
108
138
  writeDaylight(this); // before the hooks: an onFrame reads this frame's signal
109
139
  runList(this, '_frame', STRINGS.onFrame, dt);
@@ -115,6 +145,8 @@ export const loopMethods = {
115
145
  safe(this, 'stream.settle', this.stream._settle, SOFT, this.stream); // after every loader ran: readiness of stream sources
116
146
  safe(this, 'batching.update', this.batching.update, SOFT, this.batching); // last before rendering: picks up everything built this frame
117
147
  safe(this, 'audio.tick', this.audio._tick, SOFT, this.audio); // positional sounds follow their objects (returns at once when there are none)
148
+ // every 30th cycle: loading.view() and unsettled() build arrays, and a game that never settles would pay that every frame
149
+ if (!this._playTiming && (this._settleTick = ((this._settleTick ?? 0) + 1) % 30) === 1) startPlayTiming(this);
118
150
  },
119
151
  /** @internal The loop and the dev tools: one whole engine frame (onRender hooks, own-frame yielding, per-frame bookkeeping). engine.renderOnce stays the public draw: photo mode needs its picture even from a game that owns the frame, and a game may call it inside a hook.
120
152
  * @param {number} dt @param {boolean} [hooks] false: draw without the game's onRender hooks (the picture check's probe renders: picture code
@@ -136,14 +168,14 @@ export const loopMethods = {
136
168
  if (own) own.inside++;
137
169
  this._poses.draw(); // moving things draw between the last two fixed steps (stepPoses.js); undone below, gameplay never sees it
138
170
  try {
139
- for (const f of before) { safe(this, STRINGS.onRender, drawHook, null, undefined, f, ctx); r.setRenderTarget(null); }
171
+ for (const f of before) { if (!live(this._onRender, 'before', before, f)) continue; safe(this, STRINGS.onRender, drawHook, null, undefined, f, ctx); r.setRenderTarget(null); }
140
172
  this.shadows._frame(); // a game light's cascades, after 'before': picture code aims its light there, and the placement must be what is drawn (render/shadows.js)
141
173
  this._checkBackendAdds(); // WebGPU route: a WebGL-only material added since the last frame is named, not drawn blank (startup.js)
142
174
  freshFrame(r); // WebGPU: step() several times in one task, or a renderOnce() earlier in this tick, must not reuse that scene pass
143
175
  if (this._picture) this._picture.drawing = true;
144
176
  if (draws) { this.batching.skip(); try { this.post.render(dt); } finally { this.batching.unskip(); } }
145
177
  if (this._picture) this._picture.drawing = false;
146
- for (const f of after) safe(this, STRINGS.onRender, drawHook, null, undefined, f, ctx);
178
+ for (const f of after) if (live(this._onRender, 'after', after, f)) safe(this, STRINGS.onRender, drawHook, null, undefined, f, ctx);
147
179
  } finally { this._poses.undraw(); if (own) own.inside--; this._picture?.frameEnd(); }
148
180
  gpu?.end();
149
181
  // frames that first draw new objects pay their GPU upload here (Budget.js ApplyCost); a frame that compiled shaders is not judged by adaptive resolution
@@ -165,18 +197,26 @@ export const loopMethods = {
165
197
  if (!p) { safe(this, key, h.fn, opts, undefined, dt, this); continue; }
166
198
  const t0 = performance.now(); // measure
167
199
  safe(this, key, h.fn, opts, undefined, dt, this);
168
- p.t[h.name] = (p.t[h.name] || 0) + performance.now() - t0; // measure
200
+ const into = kind === 'fixed' ? p.step : p.cur; // fixed hooks: this step's ms, kept below as the cycle's dearest step (closeProfFrame)
201
+ into[h.name] = (into[h.name] || 0) + performance.now() - t0; // measure
169
202
  }
203
+ if (p && kind === 'fixed') for (const k in p.step) { if (p.step[k] > (p.fix[k] || 0)) p.fix[k] = p.step[k]; p.step[k] = 0; }
170
204
  this._curModule = was;
171
205
  },
172
- /** Time module hooks: profile(true) starts, profile(false) stops; profile() returns { moduleName: average ms per frame } and resets (null when off). */
206
+ /** Time module hooks (fixed + frame + afterRender): on by default in dev builds, off in production. profile(true) starts afresh, profile(false) stops;
207
+ * profile() returns { moduleName: { ms, mean, p95 } } per frame over the last 300 frame-hook cycles: ms is the median (null when off); fixed hooks
208
+ * count one fixed step per frame (the frame's dearest), so a slow frame's catch-up steps do not read as the module's cost. Only the
209
+ * module's own hooks count, not engine.jobs / stream work it hands off. Without cross-origin isolation the browser rounds performance.now() to 0.1 ms */
173
210
  profile(on) {
174
- if (on !== undefined) { this._prof = on ? { frames: 0, t: {} } : null; return this; }
211
+ if (on !== undefined) { this._prof = on ? { cur: {}, step: {}, fix: {}, ring: {} } : null; return this; }
175
212
  const p = this._prof;
176
213
  if (!p) return null;
177
214
  const r = {};
178
- for (const k in p.t) r[k] = Math.round(p.t[k] / Math.max(1, p.frames) * 100) / 100;
179
- p.frames = 0; p.t = {};
215
+ const r2 = v => Math.round(v * 100) / 100;
216
+ for (const k in p.ring) {
217
+ const a = p.ring[k].buf.subarray(0, p.ring[k].n);
218
+ r[k] = { ms: r2(quantile(a, 0.5)), mean: r2(a.reduce((s, v) => s + v, 0) / a.length), p95: r2(quantile(a, 0.95)) };
219
+ }
180
220
  return r;
181
221
  },
182
222
 
@@ -202,16 +242,18 @@ export const loopMethods = {
202
242
  * Returns how many ran (tests read it).
203
243
  */
204
244
  _catchUp(dt) {
205
- let acc = Math.min((this._acc || 0) + dt, MAX_CATCHUP), n = 0;
245
+ const want = (this._acc || 0) + dt;
246
+ let acc = Math.min(want, MAX_CATCHUP), n = 0, lost = want - acc; // lost: real time the fixed steps will not run (over MAX_CATCHUP, or dropped for the budget below)
206
247
  const f0 = performance.now(); // measure
207
248
  let s0 = f0;
208
249
  while (acc >= STEP && !this.disposed) { // a hook may dispose the engine
209
250
  this._fixedStep(); acc -= STEP; n++;
210
251
  const t = performance.now(); // measure
211
- if (acc >= STEP && t - f0 + (t - s0) > CATCHUP_MS) { acc %= STEP; break; } // the next one would go over: drop the rest
252
+ if (acc >= STEP && t - f0 + (t - s0) > CATCHUP_MS) { lost += acc - acc % STEP; acc %= STEP; break; } // the next one would go over: drop the rest
212
253
  s0 = t;
213
254
  }
214
255
  this._acc = acc;
256
+ this._gameDt = Math.max(0, dt - lost); // the one time frame hooks get this frame: what the fixed steps took of dt, minus every drop (hooks never run ahead of game logic)
215
257
  // held while frozen: with no fixed steps positions stand still, and a moving ratio would make interpolated things shake in place
216
258
  if (!this.frozen) this.stepBlend = acc / STEP;
217
259
  return n;
@@ -241,10 +283,12 @@ export const loopMethods = {
241
283
  try {
242
284
  this.input.poll(dt);
243
285
  // coming back from a hidden tab drops the time spent away, so play resumes without a burst of steps (page.js)
286
+ // gameDt: the time the fixed steps took this frame (_catchUp: minus MAX_CATCHUP and budget drops; none after a resync), so frame hooks (tweens, cutscenes) never move more than game logic does
287
+ let gameDt = 0;
244
288
  if (this.page.consumeResync()) this._acc = 0;
245
- else this._catchUp(dt);
289
+ else { this._catchUp(dt); gameDt = this._gameDt; }
246
290
  c1 = performance.now(); // measure
247
- this._frameHooks(dt);
291
+ this._frameHooks(gameDt);
248
292
  c2 = performance.now(); // measure
249
293
  // Before ready only the loading screen (DOM) is on screen: a scene frame there is never seen, but it compiled shaders and uploaded
250
294
  // geometry in the middle of loading (cold start measured 2.9 s -> 1.6 s without it). start() draws one hidden warm-up frame itself
@@ -5,7 +5,7 @@
5
5
  // engine.use(mine(), { replaces: 'inventory' }) unload the holder first (its tracked handles, slot, ctx.mod entries, drawing parts, dispose)
6
6
  // Why the slot is a shared point and not a module-name table: one owner registry for everything (describe().shared shows the holder beside
7
7
  // every shared value, ctx.track releases it with the rest), so there is no second mechanism to learn. Kept apart from modules.js only for size.
8
- import { DEV, fmt, closest, warnOnce } from '../base/validate.js';
8
+ import { DEV, fmt, closest, warnOnce, syncOnly } from '../base/validate.js';
9
9
  import { codedError, coded } from '../base/errorHints.js';
10
10
  import { reportError } from '../base/errors.js';
11
11
  import { PICTURE_SLOTS } from '../scene/pictureSlots.js';
@@ -132,7 +132,7 @@ export const slotMethods = {
132
132
  _unuse(name, swapping = false) {
133
133
  const m = this.modules.get(name);
134
134
  this._dropTracked(name);
135
- try { m.dispose?.(this); } catch (err) { reportError(this, err, fmt(STRINGS.unuse, { name }), { soft: true }); }
135
+ try { syncOnly(m.dispose?.(this), `dispose() of module ${name}`, true); } catch (err) { reportError(this, err, fmt(STRINGS.unuse, { name }), { soft: true }); }
136
136
  this._picture?.partGone(m, swapping);
137
137
  this.modules.delete(name); this._modState.delete(name); this._modInst.delete(name); delete this[name];
138
138
  this._sortHooks();
@@ -42,8 +42,8 @@ const RULES = {
42
42
  'world.write': [['picture', 'ui'], 'world records are game state; a {type} module only reads them',
43
43
  "run an op that writes it (engine.ops.run('<noun.verb>', args)) or move the write into a rules / world module"],
44
44
  'input.bind': [['ui'], 'a ui module declares actions; which key does what is the game\'s choice',
45
- "declare the action (ctx.input.action(name, { context })) and bind keys in the game: engine.input.bind(name, ['KeyE']) or createEngine({ bindings })"],
46
- 'saves.register': [['ui'], 'a ui module keeps menus and preferences out of the game save (a load must not change the volume)',
45
+ "declare the action (ctx.input.define(name, { context })) and bind keys in the game: engine.input.bind(name, ['KeyE']) or createEngine({ bindings })"],
46
+ 'saves.define': [['ui'], 'a ui module keeps menus and preferences out of the game save (a load must not change the volume)',
47
47
  'keep preferences in browser storage (engine.settings does), and game state in a rules / world module'],
48
48
  };
49
49
 
@@ -56,7 +56,7 @@ export function checkType(m) {
56
56
 
57
57
  /**
58
58
  * @internal dev check at a write point: warns once when the module installing or running a hook now does `what` and its type does not usually own it.
59
- * what: 'ops.define' | 'world.write' | 'input.bind' | 'saves.register'; did: what it did, for the message ("defined op shop.buy").
59
+ * what: 'ops.define' | 'world.write' | 'input.bind' | 'saves.define'; did: what it did, for the message ("defined op shop.buy").
60
60
  */
61
61
  export function checkTypeRule(e, what, did) {
62
62
  const m = DEV ? e?._curModule : null;
@@ -27,10 +27,10 @@
27
27
  // that fails halfway leaves no ghost listener behind (review 0.4 A; the rollback spec checks every built-in module).
28
28
  // ctx.mod(point, o) = ctx.track(engine.mod(point, { ...o, owner: ctx.name })): a module's changes to shared values go with it too.
29
29
  // ctx.rule(name, default, names?) = a replaceable rule on a plain shared point: .decide(id, facts) gives a built-in name, false for manual, or what the game's function answered.
30
- // ctx.input.action(name, { context }) / ctx.input.bind(name, keys): the module's input declarations and bindings, gone with it too.
31
- // ctx.ops.define, ctx.saves.register, ctx.ui.define, ctx.stream.addReadyCheck, ctx.budget.metric, ctx.things.addSource / explainWith, ctx.ground.provide / addColliders:
30
+ // ctx.input.define(name, { context }) / ctx.input.bind(name, keys): the module's input declarations and bindings, gone with it too.
31
+ // ctx.ops.define, ctx.saves.define, ctx.ui.define, ctx.stream.addReadyCheck, ctx.budget.metric, ctx.things.addSource / explainWith, ctx.ground.provide / addColliders:
32
32
  // the same registrars, recorded in the one scope with kind, id, owner and instance (engine.catalog(name).resources reads it). Built-in modules register only through
33
- // these (tools/tests/module-boundaries). A save part leaving keeps its data as unattached data of the save (Saves.register), so a module unloaded for a while loses nothing.
33
+ // these (tools/tests/module-boundaries). A save part leaving keeps its data as unattached data of the save (Saves.define), so a module unloaded for a while loses nothing.
34
34
  // Every install is its own instance (engine._modInst: name -> token): a ctx belongs to one install, not to a name. An async init that resumes after
35
35
  // its module was unloaded (replaces, a plugin removed) and a same-named one installed must not act on the newcomer: a stale ctx verb does nothing and gives a spent handle, because
36
36
  // the owner name is shared and doing it first would replace the newcomer's entry (dev warning naming the module); what it tracks is removed at once; its completion or failure
@@ -44,9 +44,9 @@
44
44
  // Dependencies: requires must be installed first (throws if missing). optional is a soft dependency: an array is only recorded (for GAMEMAP and rule R16);
45
45
  // written as { module: 'what is lost without it' }, start() warns once in dev when it is missing: use this form for optional dependencies
46
46
  // that change gameplay results, which must not be skipped silently.
47
- import { warnOnce, DEV, fmt, closest } from '../base/validate.js';
47
+ import { warnOnce, DEV, fmt, closest, syncOnly } from '../base/validate.js';
48
48
  import { codedError, coded } from '../base/errorHints.js';
49
- import { reportError } from '../base/errors.js';
49
+ import { reportError, removeEach } from '../base/errors.js';
50
50
  import { catalog, catalogSnap, catalogClaim } from '../inspect/catalog.js';
51
51
  import { readParams } from '../base/params.js';
52
52
  import { slotMethods, isUseOpts, checkProvides, slotTaken, giversOf, CORE_SLOTS } from './moduleSlots.js';
@@ -68,9 +68,12 @@ const STRINGS = {
68
68
  + "or your own module with provides: ['{dep}'] (then engine.{dep} is your module's API){typo}",
69
69
  typo: " (did you mean '{hint}'? installed: {list})",
70
70
  clash: 'module name {name} clashes with an existing engine property; pick another name',
71
+ twoGivers: "module {named} is named '{cap}' and module {giver} provides '{cap}', so requires, engine.has and engine.{cap} could each reach a different one. "
72
+ + 'Rule: one name answers to one module. Fix: give one of them another name, or unload {named} first when {giver} takes its place',
71
73
  slotClash: "module {name} provides '{slot}', but engine.{slot} is already an engine property, so dependents could not reach it there. Fix: pick another slot name",
72
74
  lateInit: 'init of module {name} (installed after start)',
73
75
  groundClaim: "module {name} called ctx.ground.provide, but ground is an exclusive capability it did not claim. Fix: add 'ground' to its provides",
76
+ blocked: "module {name} cannot run: it requires '{dep}', and {by} is {state}. It stays off until {by} runs again (engine.explain({ module: '{name}' }) says more)",
74
77
  critical: "critical module {name} cannot run: it requires '{dep}', and {by} is {state}. Fix what stopped {by}, or drop critical from {name}",
75
78
  conflict: 'module {a} (stage "{sa}") sets {kind}: ["{said}"], but module {b} is in stage "{sb}", which always runs {kind} stage "{sa}" (stage order: {list}); '
76
79
  + 'before / after only order modules inside one stage. Fix: give both modules the same stage, or remove {kind}: ["{said}"] from {a}',
@@ -166,7 +169,7 @@ export const moduleMethods = {
166
169
  const ctx = this._modCtx(m);
167
170
  this._picture?.installing(m);
168
171
  for (const slot of m.provides ?? []) ctx.track(this._slot(slot, m.name).take({ owner: m.name })); // shared-taken when another module holds it
169
- const api = asModule(this, m, () => m.install?.(this, ctx)) ?? m; // asModule: the type checks know who is installing (moduleTypes.js)
172
+ const api = asModule(this, m, () => { const r = m.install?.(this, ctx); syncOnly(r, `install() of module ${m.name}`, true); return r; }) ?? m; // asModule: the type checks know who is installing (moduleTypes.js)
170
173
  catalogClaim(this, m.name, snap); // ops / save parts / describe names it registered show under it in engine.catalog()
171
174
  this.modules.set(m.name, m);
172
175
  if (m.name) this[m.name] = api;
@@ -183,7 +186,7 @@ export const moduleMethods = {
183
186
  this.modules.delete(m.name); this._modState.delete(m.name); this._modInst.delete(m.name);
184
187
  if (had) this[m.name] = prev; else delete this[m.name]; // put back what was there (an undefined slot stays undefined), never blank it
185
188
  this._dropTracked(m.name);
186
- if (installed) try { m.dispose?.(this); } catch { /* the install error below is the one to report */ }
189
+ if (installed) try { syncOnly(m.dispose?.(this), `dispose() of module ${m.name}`, true); } catch (e2) { reportError(this, e2, `dispose() of module ${m.name} after its install failed`, { soft: true }); } // reported, but the install error below stays the primary one
187
190
  }
188
191
  this._sortHooks();
189
192
  if (removed.length) this._putBack(removed, order, base);
@@ -205,7 +208,7 @@ export const moduleMethods = {
205
208
  },
206
209
  /**
207
210
  * @internal a failed swap leaves the game as it was: the replaced modules install fresh (their old handles already went), their save parts take back their data as a part registered
208
- * late does (Saves.register), and 'module:restored' tells whoever fed them, because a fresh install has no definitions, as after a swap that worked: content sections load again (modules/content).
211
+ * late does (Saves.define), and 'module:restored' tells whoever fed them, because a fresh install has no definitions, as after a swap that worked: content sections load again (modules/content).
209
212
  * What game code defined by hand it defines again on that event. Colliders of the level and of props need no event: they check the holder themselves.
210
213
  * @param {any[]} removed in install order @param {string[]} order the module names to go back to @param {string | null} base the new-game state to go back to
211
214
  */
@@ -230,6 +233,9 @@ export const moduleMethods = {
230
233
  if (!m) continue;
231
234
  if (typeof m === 'function') throw codedError('module-called', fmt(STRINGS.called, { name: m.name }));
232
235
  if (names.has(m.name)) { warnOnce(coded('module-name', fmt(STRINGS.twice, { name: m.name }))); continue; }
236
+ // one name, one module: requires, has and engine.<name> read a module name and a provides alike (giversOf), so two modules answering to one name
237
+ // would bind each of them to a different one (and unloading the provider would clear engine.<name> under the other). Both orders, also inside one call
238
+ if (holders.has(m.name)) throw codedError('module-name', fmt(STRINGS.twoGivers, { named: m.name, giver: holders.get(m.name), cap: m.name }));
233
239
  if (typeof m.ready === 'function') warnOnce(coded('engine-misuse', fmt(STRINGS.readyHook, { name: m.name })));
234
240
  if (m.order != null) throw codedError('module-stage', fmt(STRINGS.order, { name: m.name, list: Object.keys(STAGES).join(', ') }));
235
241
  if (m.stage != null && !(m.stage in STAGES))
@@ -243,7 +249,8 @@ export const moduleMethods = {
243
249
  for (const slot of m.provides ?? []) {
244
250
  if (holders.has(slot)) throw slotTaken(slot, holders.get(slot), m.name);
245
251
  holders.set(slot, m.name);
246
- if (slot !== m.name && !gone.has(slot) && !names.has(slot) && !CORE_SLOTS.has(slot) && slot in this && this[slot] !== undefined && !this._slotAlias?.has(slot))
252
+ if (slot !== m.name && names.has(slot)) throw codedError('module-name', fmt(STRINGS.twoGivers, { named: slot, giver: m.name, cap: slot }));
253
+ if (slot !== m.name && !gone.has(slot) && !CORE_SLOTS.has(slot) && slot in this && this[slot] !== undefined && !this._slotAlias?.has(slot))
247
254
  throw codedError('module-provides', fmt(STRINGS.slotClash, { name: m.name, slot }));
248
255
  }
249
256
  if (DEV && m.params && m.options) readParams(m.name, m.params, m.options); // a definition built by hand still gets its options checked
@@ -270,7 +277,8 @@ export const moduleMethods = {
270
277
  const snap = catalogSnap(this);
271
278
  // the instance and its ctx are taken now, not when the microtask runs: by then a same-named module may be installed in its place
272
279
  const inst = this._modInst.get(m.name), ctx = this._modCtx(m, inst), live = () => this._isLive(m.name, inst);
273
- L._track(Promise.resolve().then(() => asModule(this, m, () => m.init(this, ctx))).then(
280
+ // live() again when the microtask runs: an unuse in the same turn already disposed it, and an init after dispose would leak what it makes
281
+ L._track(Promise.resolve().then(() => (live() ? asModule(this, m, () => m.init(this, ctx)) : undefined)).then(
274
282
  () => { L._done(task); if (live()) { catalogClaim(this, m.name, snap); this._setModState(m, 'running'); this.session._lateInit([...(this._modTracked.get(m.name) ?? [])].filter(h => h.kind === 'save').map(h => h.id)); } },
275
283
  e => {
276
284
  L._fail(task, e);
@@ -279,8 +287,17 @@ export const moduleMethods = {
279
287
  this._setModState(m, 'failed'); this._dropTracked(m.name); reportError(this, e, fmt(STRINGS.lateInit, { name: m.name }), { module: m });
280
288
  }));
281
289
  },
282
- /** @internal is this install (token from engine._modInst) still the module installed under its name? */
283
- _isLive(name, inst) { return !this.disposed && inst !== undefined && this._modInst.get(name) === inst; },
290
+ /** @internal the one gate for module hooks, the loop's and afterLoad (saveApply.js): registered (init not run yet), initializing, failed, disabled, blocked run none */
291
+ _runsHooks(name) { return this._modState.get(name) === 'running' && !this._modBlocked.has(name); },
292
+ /**
293
+ * @internal may this install (token from engine._modInst) still register? It is the one under its name and not closed. Closed = its signal aborted (_dropTracked:
294
+ * unload, rollback, failed init), set before the cleanup runs, so a late callback and a remove() that calls ctx.track during that cleanup are both refused (design 6.1)
295
+ */
296
+ _isLive(name, inst) { return this._wasRunning(name, inst, false) && !inst.ac.signal.aborted; },
297
+ /** @internal is this the install under its name (and, with running, did it run)? The question a save part asks while its install closes: a module that ran keeps its data on unload */
298
+ _wasRunning(name, inst, running = true) {
299
+ return !this.disposed && inst !== undefined && this._modInst.get(name) === inst && (!running || this._modState.get(name) === 'running');
300
+ },
284
301
  /** @internal the ctx install / init receive: track(handle) ties a handle to the module's life (see the top of this file) */
285
302
  _modCtx(m, inst = this._modInst.get(m.name)) {
286
303
  const name = m.name;
@@ -310,6 +327,8 @@ export const moduleMethods = {
310
327
  // Why read back after writing: a setter may keep something else than it was handed, and that is what "still mine" has to compare with.
311
328
  // Why one holder: a borrow is one party's temporary use. Two overlapping ones ended oldest first brought an ended value back, and a value with two parties is what
312
329
  // shared points own (engine.mod). A holder whose value the game replaced has lost it, so that property is free again.
330
+ // Why the holder is asked on the way back too, not only the value: a later borrow may write the same value the lost one wrote, and then the value alone cannot tell them apart.
331
+ // Why a batch is undone when a setter throws: no handle exists yet to give the first properties back, so they would stay written with nobody holding them.
313
332
  const borrow = ifLive((obj, values) => {
314
333
  if (!obj || typeof obj !== 'object' || !values || typeof values !== 'object') throw codedError('module-handle', fmt(BAD_BORROW, { name, got: `${String(obj)}, ${String(values)}` }));
315
334
  let lent = this._borrowed.get(obj);
@@ -318,19 +337,34 @@ export const moduleMethods = {
318
337
  const t = lent.get(key);
319
338
  if (t && Object.is(obj[key], t.wrote)) throw codedError('module-handle', fmt(BORROW_HELD, { name, key, holder: t.name }));
320
339
  }
321
- const taken = Object.keys(values).map(key => { const was = obj[key]; obj[key] = values[key]; const t = { key, was, wrote: obj[key], name }; lent.set(key, t); return t; });
322
- const h = { borrow: true, remove: () => {
340
+ const taken = [];
341
+ // each property on its own: a setter that throws while giving back must not keep the others written, and its holder record goes either way (the list is
342
+ // already emptied, so nothing could clean it later). Returns the first such error, which the caller throws after the rest went back
343
+ const giveBack = () => {
344
+ let failed = null;
323
345
  for (const t of taken.splice(0)) {
324
- if (Object.is(obj[t.key], t.wrote)) obj[t.key] = t.was;
325
- if (lent.get(t.key) === t) lent.delete(t.key);
346
+ try { if (lent.get(t.key) === t && Object.is(obj[t.key], t.wrote)) obj[t.key] = t.was; }
347
+ catch (err) { failed ??= { err }; }
348
+ finally { if (lent.get(t.key) === t) lent.delete(t.key); }
326
349
  }
350
+ return failed;
351
+ };
352
+ try { for (const key of Object.keys(values)) { const was = obj[key]; obj[key] = values[key]; const t = { key, was, wrote: obj[key], name }; lent.set(key, t); taken.push(t); } }
353
+ catch (err) { // the write error stays the primary one; a failure undoing it is reported on its own (soft), not lost
354
+ const undo = giveBack();
355
+ if (undo) reportError(this, undo.err, `giving back a failed borrow of module ${name}`, { soft: true });
356
+ throw err;
357
+ }
358
+ const h = { borrow: true, remove: () => {
359
+ const failed = giveBack();
327
360
  this._modTracked.get(name)?.delete(h); // a module that borrows often (a cutscene a minute) does not pile up dead handles, as with control below
361
+ if (failed) throw failed.err;
328
362
  } };
329
363
  return track(h);
330
364
  });
331
365
  // input: declare actions / bind the keys the game handed the module, owned by the module (removed with it); never a key of its own
332
366
  const input = {
333
- action: ifLive((n, o) => track(this.input.action(n, { ...o, owner: name }))),
367
+ define: ifLive((n, o) => track(this.input.define(n, { ...o, owner: name }))),
334
368
  bind: ifLive((n, keys) => track(this.input.bind(n, keys, { owner: name }))),
335
369
  };
336
370
  // control: engine.control.take with the module as default owner, tracked, so a module that goes (unload, rollback, replaces) hands back every
@@ -362,10 +396,10 @@ export const moduleMethods = {
362
396
  // Why ctx verbs and not "the module installing now": the callback that registers may run long after install; inst says which install it belongs to
363
397
  const own = (kind, id, h) => track(Object.assign(h, { kind, id, owner: name, inst }));
364
398
  const owned = (kind, add) => ifLive((id, ...rest) => own(kind, id, add(id, ...rest)));
365
- // a part keeps its data only when the module ran: a rolled-back or failed install has only half-built state to offer (Saves.register)
366
- const register = ifLive((key, part) => {
367
- const h = this.saves.register(key, part);
368
- return own('save', key, { remove: () => h.remove({ keep: this._isLive(name, inst) && this._modState.get(name) === 'running' }) });
399
+ // a part keeps its data only when the module ran: a rolled-back or failed install has only half-built state to offer (Saves.define)
400
+ const defineSave = ifLive((key, part) => {
401
+ const h = this.saves.define(key, part);
402
+ return own('save', key, { remove: () => h.remove({ keep: this._wasRunning(name, inst) }) }); // runs after the install closed: not _isLive
369
403
  });
370
404
  // declared, not just called: _planUse finds a ground conflict from provides before anything installs, which a call inside install() could not give
371
405
  const provideGround = ifLive(g => {
@@ -376,14 +410,16 @@ export const moduleMethods = {
376
410
  const feeds = (capability, fn) => {
377
411
  const f = { name: capability, fn };
378
412
  (this._feeders ??= []).push(f);
379
- return track({ remove: () => this._feeders.splice(this._feeders.indexOf(f), 1) });
413
+ return track({ remove: () => { const i = this._feeders.indexOf(f); if (i >= 0) this._feeders.splice(i, 1); } }); // a handle removed twice must not take the next feeder
380
414
  };
381
415
  // signal: aborts when this install ends (_dropTracked), the one lifecycle; an async init checks it after each await instead of keeping its own flag
382
- return { name, signal: inst?.ac.signal, track, mod, borrow, feeds, input, control, whileCompiling,
416
+ // commits: a module reaches the commit queue through its ctx; a game outside a module uses engine.nextFixed (engine.commits is internal)
417
+ return { name, signal: inst?.ac.signal, track, mod, borrow, feeds, input, control, whileCompiling, commits: this.commits,
383
418
  // rule: a replaceable rule of this module, set by anyone with engine.mod(name, { owner, id?, set }). Not tracked: the point outlives a module that shares it, its entries go with their owners
384
- rule: (n, def, names) => this.stacks.rule(n, def, names),
419
+ // a closed install defines no rule: Stacks.rule would define a point for good under a name a later module may need. It still answers like a rule, with its default
420
+ rule: (n, def, names) => (stale() ? { name: n, value: () => def, decide: (_id, facts) => (typeof def === 'function' ? def(facts, this) : def) } : this.stacks.rule(n, def, names)),
385
421
  ops: { define: owned('op', (n, def) => this.ops.define(n, def)) },
386
- saves: { register },
422
+ saves: { define: defineSave },
387
423
  ui: { define: owned('ui', (n, factory, def) => this.ui.define(n, factory, def)) },
388
424
  stream: { addReadyCheck: owned('ready', (n, fn) => this.stream.addReadyCheck(n, fn)) },
389
425
  budget: { metric: owned('metric', (n, read, o) => this.budget.metric(n, read, o)) },
@@ -397,16 +433,7 @@ export const moduleMethods = {
397
433
  const set = this._modTracked.get(name);
398
434
  if (!set) return;
399
435
  this._modTracked.delete(name);
400
- for (const h of [...set].reverse()) { if (h._timer) this.session._dropTimer(h._timer); try { h.remove(); } catch (err) { reportError(this, err, `remove() of a handle module ${name} tracked`, { soft: true }); } }
401
- },
402
- /**
403
- * @internal a module disabled after an error stays installed, so its other handles wait for unload, but what it borrowed goes back now: nothing keeps that value up any more.
404
- * Newest first, like unload: oldest first would leave a first borrow's value in place of the original.
405
- */
406
- _returnBorrowed(name) {
407
- for (const h of [...this._modTracked.get(name) ?? []].reverse()) if (h.borrow) {
408
- try { h.remove(); } catch (err) { reportError(this, err, `remove() of a borrow module ${name} made`, { soft: true }); }
409
- }
436
+ removeEach(this, [...set].reverse(), `remove() of a handle module ${name} tracked`, h => { if (h._timer) this.session._dropTimer(h._timer); });
410
437
  },
411
438
  /** @internal move a module to a new state and refresh the hooks (initializing / failed modules run none) */
412
439
  _setModState(m, state) {
@@ -430,7 +457,7 @@ export const moduleMethods = {
430
457
  * @returns {any}
431
458
  * @example engine.catalog(); engine.catalog('sky'); engine.catalog('shop.buy'); engine.catalog({ find: 'buy' })
432
459
  */
433
- catalog(id) { return catalog(this, id); },
460
+ catalog(id, o) { return catalog(this, id, o); },
434
461
  /**
435
462
  * Is a module of this name, or a provider of this capability, installed? Installed only: engine.explain({ module: name }) says whether it is running.
436
463
  * @param {string} name
@@ -451,8 +478,7 @@ export const moduleMethods = {
451
478
  this._refreshBlocks();
452
479
  for (const k of HOOKS) this._hooks[k] = [];
453
480
  for (const m of order) {
454
- const st = this._modState.get(m.name);
455
- if (st !== 'running' || this._modBlocked.has(m.name)) continue; // registered (init not run yet), initializing, failed, disabled, blocked: no hooks
481
+ if (!this._runsHooks(m.name)) continue;
456
482
  let c = hookCache.get(m);
457
483
  if (!c) hookCache.set(m, c = {});
458
484
  for (const k of HOOKS) if (m[k]) this._hooks[k].push(c[k] ??= { fn: m[k].bind(m), name: m.name, mod: m });
@@ -472,7 +498,7 @@ export const moduleMethods = {
472
498
  if (givers.some(up)) continue;
473
499
  const p = givers[0], state = !p ? 'missing' : blocks.has(p.name) ? 'blocked' : this._modState.get(p.name);
474
500
  by.push({ requires: dep, module: p?.name ?? null, state });
475
- if (state === 'failed' || dead.has(p?.name)) dead.add(m.name); // waiting ends by itself; a failure does not
501
+ if (state === 'failed' || state === 'disabled' || dead.has(p?.name)) { dead.add(m.name); warnOnce(fmt(STRINGS.blocked, { name: m.name, dep, by: p.name, state })); } // waiting ends by itself; a failure does not, so it is said once
476
502
  }
477
503
  if (by.length) blocks.set(m.name, by);
478
504
  const ok = !by.length && this._modState.get(m.name) === 'running';
@@ -4,7 +4,7 @@
4
4
  // engine.page.pauseOnBlur = false; // same, at runtime (e.g. a settings toggle)
5
5
  // engine.events.on('page:blur', () => engine.flow?.go('paused')); // show the pause menu as well, if the game wants one
6
6
  // While the page is away (window lost focus or tab hidden) with pauseOnBlur, gameplay is frozen by owner 'page': an ordinary freeze, so everything that obeys a freeze
7
- // (fixed steps, timers, cutscenes, engine.frozen, runState, describe) agrees with no code of its own here, and the sound waits too (Audio._hold). It is a full still ({ ambient: true }): limbs walking on
7
+ // (fixed steps, timers, cutscenes, engine.frozen, runState, describe) agrees with no code of its own here, and the sound waits too (Audio._hold). It is a full still ({ still: true }): limbs walking on
8
8
  // the spot over a stopped world look broken. Rendering and UI go on. Coming back resumes from where it stopped, with no catch-up burst (the loop drops the time spent
9
9
  // away). A halted engine (tests, the dev bridge) has no real-time loop to hold, so there is no page freeze, and step() drives a page in a background window.
10
10
  // Held keys are released by Input when it hears page:blur.
@@ -26,6 +26,9 @@ const DEV = { lost: '[page] WebGL context lost: gameplay waits until the browser
26
26
  notePatch('device-lost-hook', "renderer.onDeviceLost of a WebGPURenderer (three's own hook, kept and called first): reports the loss through engine.page (core/engine/page.js)", () => {},
27
27
  { scope: 'engine renderer', lost: 'engines made from now on: after a device loss the picture freezes while the game keeps running, with no message' });
28
28
 
29
+ notePatch('page-exit-pointer-lock', "document.exitPointerLock (one wrapper for every live engine, taken off with the last one): tells engine.page the unlock was the game's own call (core/engine/page.js)", () => {}, // off: the wrapper stays (gone with the last engine) and stops telling
30
+ { scope: 'page', lost: 'a game-requested unlock reads as the player pressing Esc (page:pointerlock byEngine stays false)' });
31
+
29
32
  // document.exitPointerLock is one property for the page: one wrapper for every live engine, gone with the last. A wrapper per engine could only be taken off all at once
30
33
  const lockers = new Set();
31
34
  /** @param {Page} page @param {AbortSignal} signal */
@@ -34,7 +37,7 @@ function watchExitLock(page, signal) {
34
37
  if (!exitLock) return;
35
38
  if (!lockers.size) {
36
39
  const own = Object.hasOwn(document, 'exitPointerLock');
37
- const wrapper = () => { for (const p of lockers) p._releasing = document.pointerLockElement === p.engine.renderer.domElement; return exitLock.call(document); };
40
+ const wrapper = () => { if (patchOn('page-exit-pointer-lock')) for (const p of lockers) p._releasing = document.pointerLockElement === p.engine.renderer.domElement; return exitLock.call(document); };
38
41
  document.exitPointerLock = wrapper;
39
42
  lockers.unwrap = () => { if (document.exitPointerLock !== wrapper) return; if (own) document.exitPointerLock = exitLock; else delete document.exitPointerLock; };
40
43
  }
@@ -99,7 +102,7 @@ export class Page {
99
102
  _sync() {
100
103
  const want = !this.engine.halted && ((this._pauseOnBlur && this.away) || this.contextLost);
101
104
  if (want === !!this._hold) return;
102
- if (want) this._hold = this.engine.freeze('page', { ambient: true });
105
+ if (want) this._hold = this.engine.freeze('page', { still: true });
103
106
  else { this._hold.remove(); this._hold = null; }
104
107
  this.engine.audio?._hold(want); // a frozen game keeps no loop sounding on its own in a background tab
105
108
  }
@@ -3,7 +3,7 @@
3
3
  // The true order. At run time services call each other in a cycle (commits, ui, session, input, i18n, saves, clock, stacks, time), always through engine.x when a call
4
4
  // happens, and nothing runs until createEngine returns. So the only order that counts is what a constructor reads itself:
5
5
  // i18n -> saves (its strings); events + saves -> stacks._hook; stacks + events -> input; stacks + saves -> time -> _poses; saves -> vars; ops -> defineSkipOp; events -> control.
6
- // saves.register calls set the order parts save and load: stacks, time, vars, random, scene, then the modules.
6
+ // saves.define calls set the order parts save and load: stacks, time, vars, random, scene, then the modules.
7
7
  // Made in Engine.js: stacks before this function (drawing parts define points); post, ui and page after it, so a constructor here must not touch those three.
8
8
  // Input binds keys before time exists, so an entry taken then is stamped 0 (Stacks._nowOf), which is what the calendar reads at that moment anyway.
9
9
  // A new service goes below everything its constructor reads, and its line is added here; tests/specs/services-order.mjs fails when a constructor reads a service made after it.
@@ -41,13 +41,14 @@ import { defineSkipOp } from '../time/skip.js';
41
41
  import { installThings } from '../scene/thingOps.js';
42
42
  import { Plugins } from './plugins.js';
43
43
  import { watchGameLights } from '../scene/gameLights.js';
44
+ import { tierChanged } from '../scene/tier.js';
44
45
 
45
46
  /**
46
47
  * Create the engine services on `engine` (called once from the Engine constructor, after the renderer, scene and uniforms exist).
47
48
  * @param engine the engine under construction
48
49
  * @param o the createEngine options these services read, already defaulted by the constructor
49
50
  */
50
- export function createServices(engine, { canvas, validate, locale, strings, saveKey, joystick, bindings, audio, decoders, budget, seed, headless, urlState, threads, batching }) {
51
+ export function createServices(engine, { canvas, validate, locale, strings, saveKey, joystick, blockBrowserKeys, bindings, audio, decoders, budget, seed, headless, urlState, threads, batching }) {
51
52
  // DEV, not import.meta.env.DEV: the npm test bundle is a production build that sets THREEDOG_TEST, and the spelling check must run there too
52
53
  engine.events = new Events({ check: DEV && validate !== false,
53
54
  onError: (name, err) => reportListenerError(engine, name, err), now: () => engine.time.tick }); // listener errors are handled by severity (errors.js)
@@ -58,7 +59,7 @@ export function createServices(engine, { canvas, validate, locale, strings, save
58
59
  engine.stacks._hook(); // one registry, made early by Engine.js (drawing parts register points); saves and events hook in now
59
60
  engine.mod = (name, o) => engine.stacks.mod(name, o);
60
61
  engine.stacks.define('input.gate', { kind: 'any', per: true }); // input.gate(action, owner): one entry per owner and action (Input.js)
61
- engine.input = new Input(engine, canvas, { joystick, bindings });
62
+ engine.input = new Input(engine, canvas, { joystick, bindings, blockBrowserKeys });
62
63
  engine.events.on('ui:open', id => engine._openWindows.add(id));
63
64
  engine.events.on('ui:close', id => engine._openWindows.delete(id));
64
65
  engine.audio = new Audio(engine, audio);
@@ -77,12 +78,12 @@ export function createServices(engine, { canvas, validate, locale, strings, save
77
78
  engine.rays = new Rays(engine); // ray registry: engine.raycast / pick
78
79
  Object.assign(engine, describeApi(engine)); // describe / describeText / inspect / explain, see Describe.js
79
80
  engine.random = new Random(seed ?? (headless ? 1 : Date.now())); // wall-clock: differs per run when no seed is given
80
- engine.saves.register('random', { atomic: true, save: () => engine.random.toJSON(), load: d => engine.random.fromJSON(d) });
81
+ engine.saves.define('random', { atomic: true, save: () => engine.random.toJSON(), load: d => engine.random.fromJSON(d) });
81
82
  engine._urlState = new UrlState(engine, { fromUrl: urlState });
82
83
  // who holds the engine still: three named stacks (stacks.js: same owner rules as every shared quantity, holders in describe); haltLoop / freeze / takeCamera in holds.js
83
84
  defineHoldStacks(engine);
84
85
  // the one quality value (engine.tier): the device gives the base, the player's preset sets over it. settingsSet: on this point the player's choice is a choice, not a restriction
85
- engine.stacks.define('tier', { kind: 'value', base: engine._deviceTier, save: false, settingsSet: true, onChange: () => engine.post?._sync() }); // effects held by tier follow it
86
+ engine.stacks.define('tier', { kind: 'value', base: engine._deviceTier, save: false, settingsSet: true, onChange: () => tierChanged(engine) }); // the post chain and cascades follow it (core/scene/tier.js onTierChange)
86
87
  engine.commits = new Commits(engine); // background results that affect gameplay take effect on a fixed tick (see Commits.js)
87
88
  engine.ops = new Ops(engine); // one entry point for actions (define / run / can / list / recent), see Ops.js
88
89
  engine.views = new Views(engine); // named fixed camera views for repeatable screenshots (Views.js)