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
@@ -13,7 +13,7 @@ import { touchStart } from '../input/inputTouch.js';
13
13
  import { Loading, failureText } from './Loading.js';
14
14
  import { startHeadlessLoad } from './headlessLoad.js';
15
15
  import * as THREE from 'three';
16
- import { isWebGPU, backendName, whyNoWebGPU, firstNodeMaterial, webglOnlyOn, tier as detectTier, timerContext, rendererSwapped, compileThrough } from '../../render/backend.js';
16
+ import { isWebGPU, backendName, whyNoWebGPU, firstNodeMaterial, webglOnlyOn, tier as detectTier, timerContext, rendererSwapped, compileThrough, borrowRenderer } from '../../render/backend.js';
17
17
  import { bindUniforms } from '../../render/engineUniforms.js';
18
18
  import { nameShaderErrors } from '../../render/shaderErrors.js';
19
19
  import { forcedTier } from '../scene/tier.js';
@@ -107,14 +107,13 @@ export const startupMethods = {
107
107
  // Compile every visible material for the current lights now, behind the loading screen, instead of stalling the first frame that shows it
108
108
  // (async where the browser has KHR_parallel_shader_compile). A later change in the number of lights compiles again: see recipes/09 "Lights and stalls"
109
109
  this._checkBackendScene(); // the scene is built now: materials the chosen backend cannot draw fail by name, not as a blank picture
110
+ this._gameLights?.sync(); // the light watch sees it before the compile: a RectAreaLight's tables must be set first (gameLights.js)
110
111
  const tc = performance.now(); // measure
111
112
  // Everything below is handed to the parallel compile together, then awaited once: the scene, and on WebGL the post chain's fullscreen passes
112
113
  // compile for the target the scene really draws into (the composer's when post is on): see PostFX._sceneTarget.
113
114
  // compile() runs synchronously inside compileAsync, so the target only needs to be set around the call, not across the await
114
115
  const r = this.renderer, target = this.post._sceneTarget();
115
- r.setRenderTarget(target);
116
- let compiling;
117
- try { compiling = r.compileAsync(this.scene, this.camera); } finally { r.setRenderTarget(null); }
116
+ const compiling = borrowRenderer(r, () => { r.setRenderTarget(target); return r.compileAsync(this.scene, this.camera); });
118
117
  // the chain's passes draw through three themselves, so compileAsync of the scene never sees their materials: a dry run of the chain
119
118
  // (render/backend.js compileThrough) starts them now instead of one by one in the warm-up frame (~130 ms measured, nine passes).
120
119
  // Not on WebGPU: its passes are nodes of one pipeline whose inner renders run only inside a real frame
@@ -123,6 +122,7 @@ export const startupMethods = {
123
122
  for (const f of this._whileCompiling.splice(0)) { try { f(); } catch (err) { reportError(this, err, 'warm-up while compiling', { soft: true }); } }
124
123
  await Promise.all([compiling, post]);
125
124
  this._alive();
125
+ this.stream._prep.mark(this.scene); // compiled now: streamed content sharing these materials is shown at once (core/stream/prepare.js)
126
126
  // One hidden frame behind the loading screen: shadow depth materials, the post passes and the background quad are programs compileAsync
127
127
  // never sees, and without this frame they compiled in the first frame the player saw (a 300 ms hitch measured)
128
128
  if (!this.headless) { try { this._render(0); } catch (err) { reportError(this, err, 'render (warm-up frame)', { soft: true }); } }
@@ -161,7 +161,7 @@ export const startupMethods = {
161
161
  const r = this.renderer, want = this._backendWant;
162
162
  if (!isWebGPU(r)) { this._backend = { requested: 'webgl', backend: 'webgl', reason: null }; return; }
163
163
  const forced = !!r.backend?.parameters?.forceWebGL; // the game asked for the WebGL2 backend itself: not a fallback
164
- let reason = forced || (r.initialized && r.backend.isWebGPUBackend) ? null : await whyNoWebGPU();
164
+ let reason = forced || (r.initialized && r.backend.isWebGPUBackend) ? null : await whyNoWebGPU(want.limits, r.backend?.parameters?.powerPreference);
165
165
  this._alive();
166
166
  if (reason && want.fallback === 'error') {
167
167
  throw codedError('renderer-backend', `[threedog] WebGPU unavailable (${reason}) and createEngine({ fallback: 'error' }) asked not to fall back; `
@@ -2,7 +2,7 @@
2
2
  // Why: keys can be rebound in settings, and on-screen key hints follow automatically.
3
3
  //
4
4
  // Who does what (one rule each, so an AI can predict it):
5
- // - a module DECLARES actions and the context they belong to, never keys: ctx.input.action('choice1', { context: 'dialog', optional: true })
5
+ // - a module DECLARES actions and the context they belong to, never keys: ctx.input.define('choice1', { context: 'dialog', optional: true })
6
6
  // - the GAME BINDS keys: createEngine({ bindings: { jump: ['Space'] } }), engine.input.bind('jump', ['Space']) or a whole preset map
7
7
  // engine.input.bind(presets.bindings.dialogNumbers). The basics (WASD / arrows move, confirm, cancel, UI cursor) are the one default preset.
8
8
  // - the PLAYER REBINDS: engine.input.rebind('jump', ['KeyJ']) (the settings menu calls it and saves it).
@@ -34,7 +34,7 @@ import { bindKeyboard } from './inputKeyboard.js';
34
34
  import { pollPad, keyLabel } from './inputPad.js';
35
35
  import { Seat, moveAxis } from './inputSeat.js';
36
36
  import { BASIC_KEYS, BASIC_LABELS, BOUND_LABELS } from './inputDefaults.js';
37
- import { initContexts, pushContext, readableMap, applyContexts, settledStack, BASE_CONTEXT } from './inputContext.js';
37
+ import { initContexts, pushContext, readableMap, blockers, applyContexts, settledStack, BASE_CONTEXT } from './inputContext.js';
38
38
 
39
39
  const NONE = Object.freeze([]);
40
40
  const ACTION_OPTS = ['context', 'label', 'optional', 'keys', 'owner'];
@@ -43,7 +43,7 @@ const ACTION_OPTS = ['context', 'label', 'optional', 'keys', 'owner'];
43
43
  /** Input: read by "action", not by "key". Key names are the browser's KeyboardEvent.code, e.g. 'KeyE', 'Space', 'ShiftLeft'; gamepad keys are 'PadA' etc. */
44
44
  export class Input {
45
45
  /** @internal */
46
- constructor(engine, canvas, { joystick = 'auto', bindings = {}, padDeadzone = 0.18, padLookSpeed = 9 } = {}) {
46
+ constructor(engine, canvas, { joystick = 'auto', bindings = {}, padDeadzone = 0.18, padLookSpeed = 9, blockBrowserKeys = true } = {}) {
47
47
  /** @internal */ this.engine = engine;
48
48
  /** @internal */ this.canvas = canvas;
49
49
  /** @internal */ this.keys = new Set();
@@ -73,6 +73,7 @@ export class Input {
73
73
  /** @internal the shared point holding every action's keys (record id = action); its base is the default preset */
74
74
  this._keys = engine.stacks.define('input.keys', { kind: 'value', per: true, save: false, settingsSet: true, onChange: () => { this._readable = null; } });
75
75
  /** @internal 'Touch:<action>' keys of on-screen buttons (inputTouch.js), added to keysOf */ this._touchKeys = new Map();
76
+ /** @internal createEngine({ blockBrowserKeys }): while playing, bound keys do not reach the browser (inputKeyboard.js) */ this.blockBrowserKeys = blockBrowserKeys;
76
77
  /** @internal */ this.padDeadzone = padDeadzone;
77
78
  /** @internal */ this.padLookSpeed = padLookSpeed;
78
79
  /** @internal */ this.padStick = { x: 0, y: 0 };
@@ -96,7 +97,7 @@ export class Input {
96
97
 
97
98
  // ---------- actions ----------
98
99
  /**
99
- * Declare an action: its context and display name, never its keys (the game binds those). Modules call ctx.input.action (owned by the module,
100
+ * Declare an action: its context and display name, never its keys (the game binds those). Modules call ctx.input.define (owned by the module,
100
101
  * removed with it); a game's own action can pass keys to declare and bind in one line.
101
102
  * context: the input context it is read in (default 'walk'); readable only while that context is on the stack and not shadowed, see push().
102
103
  * optional: true = the module works without it (number keys for dialogue choices), so reading it unbound is silent.
@@ -104,16 +105,16 @@ export class Input {
104
105
  * @param {string} name
105
106
  * @param {{ context?: string, label?: string, optional?: boolean, keys?: string | string[], owner?: string }} [o]
106
107
  * @returns {{ name: string, remove(): void }} remove() takes the declaration (and keys given here) away
107
- * @example ctx.input.action('choice1', { context: 'dialog', label: 'dialogue.choice', optional: true }); // in a module: no keys
108
- * @example engine.input.action('brake', { context: 'vehicle', keys: ['KeyB', 'PadLT'] }); // a game's own action, bound at once
108
+ * @example ctx.input.define('choice1', { context: 'dialog', label: 'dialogue.choice', optional: true }); // in a module: no keys
109
+ * @example engine.input.define('brake', { context: 'vehicle', keys: ['KeyB', 'PadLT'] }); // a game's own action, bound at once
109
110
  */
110
- action(name, o = {}) {
111
+ define(name, o = {}) {
111
112
  const bad = Object.keys(o).filter(k => !ACTION_OPTS.includes(k));
112
- if (bad.length) throw codedError('unknown-option', `input.action('${name}', { ${bad.join(', ')} }): known options are ${ACTION_OPTS.join(', ')}. Keys are bound by the game: engine.input.bind('${name}', ['KeyX'])`, TypeError);
113
+ if (bad.length) throw codedError('unknown-option', `input.define('${name}', { ${bad.join(', ')} }): known options are ${ACTION_OPTS.join(', ')}. Keys are bound by the game: engine.input.bind('${name}', ['KeyX'])`, TypeError);
113
114
  const { context = BASE_CONTEXT, label, optional = false, keys, owner = 'game' } = o;
114
115
  const cur = this.actions.get(name);
115
116
  if (cur?.by && cur.by !== owner && cur.context !== context) {
116
- throw codedError('input-action-context', `input.action('${name}'): '${cur.by}' already declared it in context '${cur.context}', now '${owner}' declares it in '${context}'. `
117
+ throw codedError('input-action-context', `input.define('${name}'): '${cur.by}' already declared it in context '${cur.context}', now '${owner}' declares it in '${context}'. `
117
118
  + `Rule: an action belongs to one context. Fix: give one of them another name (e.g. '${owner}.${name}'), or declare it in the same context`);
118
119
  }
119
120
  // a second owner declaring the same action in the same context shares the first declaration (two modules may read one 'interact')
@@ -201,7 +202,7 @@ export class Input {
201
202
  /** @internal */
202
203
  _keyUp(code) { this._muted.delete(code); if (this.keys.delete(code)) { this.justReleased.add(code); this._accR.add(code); } }
203
204
  /**
204
- * A local player's share of the input on a shared screen: its own keys and gamepad, read like engine.input (axis, down, pressed, released). Pass it to createPlayer({ id, input }).
205
+ * A local player's share of the input on a shared screen: its own keys and gamepad, read like engine.input (axis, down, pressed, released). Pass it to addPlayer({ id, input }).
205
206
  * pad: gamepad index; that pad leaves engine.input and answers the game's pad bindings here. keys: { action: keys } for this seat alone. Two seats on one pad or key throw `input-seat`.
206
207
  * @example const two = engine.input.seat({ pad: 1, keys: { moveForward: 'KeyI', moveBack: 'KeyK', moveLeft: 'KeyJ', moveRight: 'KeyL', jump: 'KeyU' } });
207
208
  * @param {{ pad?: number, keys?: Record<string, string | string[]> }} [opts] @returns {Seat}
@@ -230,12 +231,13 @@ export class Input {
230
231
  /**
231
232
  * All keys bound to an action: the player's rebinding, else the game's bind, else the default preset (basics only); plus its touch button
232
233
  * @param {string} action @returns {readonly string[]}
233
- * @experimental
234
234
  */
235
235
  keysOf(action) {
236
236
  const k = this._keys.value(action, BASIC_KEYS[action] ?? null) ?? NONE, t = this._touchKeys.get(action);
237
237
  return t ? [...k, t] : k;
238
238
  }
239
+ /** @internal Every key that can drive an action: its bound keys, plus each seat's own keys and its '@pad' gamepad keys. The context switch lets go of all of them @param {string} action @returns {string[]} */
240
+ _sourcesOf(action) { return [...new Set([...this.keysOf(action), ...this.seats.flatMap(s => s._keysOf(action))])]; }
239
241
  /** @internal reading an undeclared action is most likely a misspelled name; a declared one nobody bound says how to bind it (dev, once) */
240
242
  _known(action) {
241
243
  const a = this.actions.get(action);
@@ -269,7 +271,6 @@ export class Input {
269
271
  /**
270
272
  * Just released (which copy is read is the same as pressed; for things like release-to-fire after charging) @param {string} action @returns {boolean}
271
273
  * @example if (engine.input.released('fire')) shoot(charge);
272
- * @experimental
273
274
  */
274
275
  released(action) { return this._has(action, 'released'); }
275
276
  /**
@@ -282,7 +283,7 @@ export class Input {
282
283
  * Push an input context (an action group, like a Unity Action Map). The top context shadows lower actions bound to the same key.
283
284
  * Opaque by default (nothing below is readable: menus, dialogue, cutscenes); { pass: true } lets unrelated lower actions keep working (vehicle, build mode).
284
285
  * Applies at the start of the next fixed step; actions it blocks lose their held state (no stuck keys after a menu closes). Join a context with
285
- * input.action(name, { context }); menu keys: pressedRaw.
286
+ * input.define(name, { context }); menu keys: pressedRaw.
286
287
  * @param {string} name e.g. 'vehicle', 'dialog', 'menu', 'cutscene', 'build' (the base context is 'walk')
287
288
  * owner (default the name) is who pushed it, listed in describe().holds.input
288
289
  * @param {{ pass?: boolean, owner?: string }} [opts]
@@ -321,6 +322,19 @@ export class Input {
321
322
  const o = typeof owner === 'string' ? { owner } : owner;
322
323
  return this.engine.mod('input.gate', { ...o, id: action });
323
324
  }
325
+ /**
326
+ * Why a game action cannot be read right now, for a driver about to press it or that pressed it and saw nothing happen; [] when it is readable. Every cause,
327
+ * top down: an opaque input context above the action's own ('win-settings', 'dialogue'...), 'shadowed-by:<context>' (a pass-through context above binds
328
+ * the same key), or 'context-off:<context>' alone (its own context is not on the stack); then the owners of the action's gate. Pushes and removes
329
+ * count at once, as in holders. A real key is blocked the same way, so this is the game's rule, not the driver's.
330
+ * Without an action: every opaque context, which is runState.blockedBy's input part (one list, so the two never disagree)
331
+ * @param {string} [action] @returns {string[]}
332
+ * @internal
333
+ */
334
+ blockedBy(action) {
335
+ if (action == null) return this.holders.filter(h => !h.pass).map(h => h.context);
336
+ return [...blockers(this, action, settledStack(this)), ...(this._gated(action) ? this._gateStack.names(action) : [])];
337
+ }
324
338
  /** @internal true while someone holds this action's gate */
325
339
  _gated(action) { return (this._gateStack ??= this.engine.stacks.get('input.gate')).size(action) > 0; }
326
340
  /**
@@ -363,6 +377,6 @@ export class Input {
363
377
  }
364
378
 
365
379
  export const handRolled = [
366
- { kind: 'keys', seen: 'a raw keydown / keyup listener', use: "engine.input.action('jump', { label, keys }) in a module, the game binds keys with engine.input.bind (rebinding, contexts, gamepad); read engine.input.pressed(name) (recipe 58)", raw: /(?:^|[^\w.])(?:(?:window|document|self|globalThis|canvas|document\.body|[\w.]*domElement)\.)?(?:addEventListener\s*\(\s*['"]|on)key(?:down|up)\b/, yields: { kind: 'pause', raw: /['"]Escape['"]/ } },
380
+ { kind: 'keys', seen: 'a raw keydown / keyup listener', use: "engine.input.define('jump', { label, keys }) in a module, the game binds keys with engine.input.bind (rebinding, contexts, gamepad); read engine.input.pressed(name) (recipe 58)", raw: /(?:^|[^\w.])(?:(?:window|document|self|globalThis|canvas|document\.body|[\w.]*domElement)\.)?(?:addEventListener\s*\(\s*['"]|on)key(?:down|up)\b/, yields: { kind: 'pause', raw: /['"]Escape['"]/ } },
367
381
  { kind: 'lock', seen: 'an input lock of its own', use: "engine.input.push('ride', { owner }) takes the keys and h.remove() gives them back: no key sticks, and describe().holds.input shows who holds them (recipe 07 §2b)", quiet: /\b(engine|e|eng|ctx)\.input\.(push|gate)\b|\blockInput\b/, code: /\b(?:let|var)\s+(?:input|controls?|keys)(?:Locked|Disabled|Enabled|Frozen)\s*=/i, tags: false },
368
382
  ];
@@ -29,24 +29,36 @@ export function pushContext(input, name, { pass = false, owner = name } = {}) {
29
29
  };
30
30
  }
31
31
 
32
- /** Which actions can currently be read: walk the stack from the top down to the action's own context @internal */
33
- export function readableMap(input) {
34
- if (input._readable) return input._readable;
32
+ /** context name -> the keys its actions bind */
33
+ function keyIndex(input) {
35
34
  const keysOf = new Map();
36
35
  for (const [n, a] of input.actions) { const c = a.context || BASE_CONTEXT; let s = keysOf.get(c); if (!s) keysOf.set(c, s = new Set()); for (const k of input.keysOf(n)) s.add(k); }
37
- const m = new Map(), stack = input._stack;
38
- for (const [name, a] of input.actions) {
39
- const ctx = a.context || BASE_CONTEXT;
40
- let ok = false;
41
- for (let i = stack.length - 1; i >= 0; i--) {
42
- const c = stack[i];
43
- if (c.name === ctx) { ok = true; break; }
44
- if (!c.pass) break;
45
- const shadow = keysOf.get(c.name);
46
- if (shadow && input.keysOf(name).some(k => shadow.has(k))) break;
47
- }
48
- m.set(name, ok);
36
+ return keysOf;
37
+ }
38
+ /**
39
+ * Every reason an action cannot be read on this stack, walked from the top down to the action's own context: an opaque context above it (its name),
40
+ * a pass-through context above it that binds one of its keys ('shadowed-by:<context>'); or, alone, its own context not on the stack ('context-off:<context>').
41
+ * [] = readable. The one walk behind readableMap, input.blockedBy and describe().holds, so "can it be read" and "why not" never disagree @internal
42
+ */
43
+ export function blockers(input, name, stack = input._stack, keysOf = keyIndex(input)) {
44
+ const ctx = input.actions.get(name)?.context || BASE_CONTEXT, keys = input.keysOf(name), out = [];
45
+ let at = stack.length - 1;
46
+ while (at >= 0 && stack[at].name !== ctx) at--;
47
+ // its context is off: nothing is "above" it, and pushing it would put it on top, so that is the one cause (a closed menu's action under a walk key)
48
+ if (at < 0) return [`context-off:${ctx}`];
49
+ for (let i = stack.length - 1; i > at; i--) {
50
+ const c = stack[i], shadow = keysOf.get(c.name);
51
+ if (!c.pass) out.push(c.name);
52
+ else if (shadow && keys.some(k => shadow.has(k))) out.push(`shadowed-by:${c.name}`);
49
53
  }
54
+ return out;
55
+ }
56
+
57
+ /** Which actions can currently be read (no blocker on the applied stack); cached until a switch / define / rebind @internal */
58
+ export function readableMap(input) {
59
+ if (input._readable) return input._readable;
60
+ const m = new Map(), keysOf = keyIndex(input);
61
+ for (const name of input.actions.keys()) m.set(name, !blockers(input, name, input._stack, keysOf).length);
50
62
  return input._readable = m;
51
63
  }
52
64
 
@@ -73,7 +85,7 @@ export function applyContexts(input) {
73
85
  const after = readableMap(input);
74
86
  for (const [name, was] of before) {
75
87
  if (!was || after.get(name)) continue;
76
- for (const k of input.keysOf(name)) {
88
+ for (const k of input._sourcesOf(name)) {
77
89
  if (!input.keys.has(k)) continue; // even if another action on this key becomes readable: it needs a fresh press (F that boards must not also exit)
78
90
  input.keys.delete(k); input._accP.delete(k); input._accR.delete(k); input._muted.add(k);
79
91
  }
@@ -4,6 +4,8 @@
4
4
  // Only a keydown is gated. A keyup always counts, and what the old owner held it lets go of at the handover: its keyup may come much later.
5
5
  // Mouse buttons and on-screen buttons are the engine's own: those keys stay as they are. Gamepads are polled: a former owner's next poll reads no pad and lets go (inputPad.js).
6
6
 
7
+ import { warnOnce, DEV } from '../base/validate.js';
8
+
7
9
  const NOT_KEYBOARD = /^(Mouse|Pad|Touch:)/;
8
10
  /** The Inputs alive on this page; the first is the owner, the one after it had the keyboard before and gets it back if the owner goes */
9
11
  const inputs = [];
@@ -14,6 +16,15 @@ export const owns = input => inputs[0] === input;
14
16
  /** Is this pad bound to a seat of any engine on the page? A seat was told its pad: it hears it whoever owns the input, and the owner does not read it too @internal @param {number} i */
15
17
  export const padSeated = i => inputs.some(input => input.seats.some(s => s.pad === i));
16
18
 
19
+ /** The keyboard codes any action is bound to (mouse, pad and touch keys are not the browser's) @param {any} input */
20
+ const boundCodes = input => [...new Set([...input.actions.keys()].flatMap(a => input.keysOf(a)).filter(k => !NOT_KEYBOARD.test(k)))];
21
+ /** Is the game being played: no opaque context (menu, dialogue), not frozen (pause, tab away). The same two facts every other system reads, not a notion of its own @param {any} input */
22
+ const playing = input => !input.blockedBy().length && !input.engine.frozen;
23
+ /** Is this where the player types text: a field, a select, or anything inside a contenteditable (isContentEditable is true for its children too). Game keys never route from here @param {any} t */
24
+ const isEditable = t => !!t && (t.isContentEditable === true || /INPUT|TEXTAREA|SELECT/.test(t.tagName));
25
+ /** Keys a developer needs: reload and devtools stay with the browser in dev builds, even when a game binds them @param {KeyboardEvent} e */
26
+ const devKey = e => e.code === 'F5' || e.code === 'F12' || ((e.ctrlKey || e.metaKey) && (e.code === 'KeyR' || (e.shiftKey && e.code === 'KeyI')));
27
+
17
28
  /** @param {any} input the engine.input that takes the keyboard */
18
29
  function take(input) {
19
30
  const [owner] = inputs;
@@ -21,6 +32,7 @@ function take(input) {
21
32
  for (const k of [...owner.keys]) if (!NOT_KEYBOARD.test(k)) owner._keyUp(k);
22
33
  inputs.splice(inputs.indexOf(input), 1);
23
34
  inputs.unshift(input);
35
+ owner._kbSync?.(); input._kbSync?.(); // the old owner gives the page's key lock back, then the new one asks for its own
24
36
  }
25
37
 
26
38
  /** Wire the keyboard to input (called once when Input is constructed). signal: engine.dispose() cancels all listeners at once @param {any} input @param {HTMLCanvasElement} canvas @param {AbortSignal} signal */
@@ -30,10 +42,26 @@ export function bindKeyboard(input, canvas, signal) {
30
42
  addEventListener('pointerdown', claim, { signal, capture: true }); // on the window, capturing: a game's stopPropagation must not hide the press
31
43
  addEventListener('focusin', claim, { signal, capture: true });
32
44
  addEventListener('keydown', e => {
33
- if (!owns(input) || /INPUT|TEXTAREA|SELECT/.test(e.target.tagName)) return;
45
+ if (!owns(input) || isEditable(e.target)) return;
34
46
  input._keyDown(e.code, 'keyboard');
35
- if (e.code === 'Space' || e.code === 'Tab' || e.code.startsWith('Arrow')) e.preventDefault();
47
+ if (input.blockBrowserKeys && (e.code === 'Space' || e.code === 'Tab' || e.code.startsWith('Arrow') || (playing(input) && boundCodes(input).includes(e.code)))) {
48
+ if (DEV && devKey(e)) { warnOnce(`input: '${e.code}' is bound but reload / devtools keys stay with the browser in dev builds (blockBrowserKeys never blocks F5, Ctrl+R, F12, Ctrl+Shift+I here); pick another key`, 'browser-key:' + e.code); return; }
49
+ e.preventDefault();
50
+ }
36
51
  }, { signal });
52
+ // Keyboard Lock (Chromium, fullscreen only): while playing, the bound keys go to the page even for Ctrl+W and friends; menus, pause and leaving fullscreen give them back.
53
+ // input._kbSync is the one place that decides the page's lock state: context, rebind, blur, fullscreen, freeze (holds.js), a change of owner (take) and dispose all call it
54
+ const kb = /** @type {any} */ (navigator).keyboard;
55
+ if (kb?.lock) {
56
+ const sync = () => { try { if (input.blockBrowserKeys && document.fullscreenElement && owns(input) && playing(input)) kb.lock(boundCodes(input))?.catch?.(() => {}); else kb.unlock(); } catch { /* not allowed here: the keys simply stay the browser's */ } };
57
+ input._kbSync = sync;
58
+ document.addEventListener('fullscreenchange', sync, { signal });
59
+ for (const ev of ['input:context', 'input:rebind', 'page:blur']) input.engine.events.on(ev, sync);
60
+ }
37
61
  addEventListener('keyup', e => input._keyUp(e.code), { signal });
38
- signal.addEventListener('abort', () => inputs.splice(inputs.indexOf(input), 1));
62
+ signal.addEventListener('abort', () => {
63
+ const was = owns(input);
64
+ inputs.splice(inputs.indexOf(input), 1);
65
+ if (was) { input._kbSync?.(); inputs[0]?._kbSync?.(); } // a disposed owner leaves no lock on the page; the next owner asks for its own
66
+ });
39
67
  }
@@ -54,3 +54,7 @@ export function keyLabel(input, action) {
54
54
  const name = k => input.engine.i18n.has('key.' + k) ? input.engine.t('key.' + k) : keyName(k);
55
55
  return use.map(name).filter((v, i, arr) => arr.indexOf(v) === i).join('/');
56
56
  }
57
+ /** The key an on-screen hint shows: its label; the 'input.noKey' text when it needs a key and has none (never an empty name); '' for none on purpose (touch, click only) or an action removed since @internal */
58
+ export function hintKey(input, action) { return keyLabel(input, action) || (input.actions.has(action) && input.isUnbound(action) ? input.engine.t('input.noKey') : ''); }
59
+ /** "E · Talk": the one way an on-screen key and its text read (the interaction prompt, HUD hints and markers) @internal */
60
+ export const keyed = (key, text) => key ? (text ? `${key} · ${text}` : key) : text;
@@ -42,8 +42,9 @@ export function bindPointer(input, canvas, signal) {
42
42
  // When the mouse is locked (first person), use relative movement
43
43
  addEventListener('mousemove', e => { if (document.pointerLockElement === canvas) { input.look.dx += e.movementX; input.look.dy += e.movementY; } }, { signal });
44
44
  const end = e => {
45
+ if (drag && drag.id !== e.pointerId) return; // another finger lifting is not this gesture's end
45
46
  const swallowed = drag?.swallowed;
46
- if (drag && !swallowed && drag.moved < 6) input.pointer.clicked = true;
47
+ if (drag && !swallowed && drag.moved < 6 && e.type === 'pointerup') input.pointer.clicked = true; // a cancelled pointer (the browser took the gesture) is no click
47
48
  drag = null;
48
49
  if (swallowed) return;
49
50
  input.pointer.down = false;
@@ -25,7 +25,7 @@ export class Seat {
25
25
  if (pad !== undefined && !(Number.isInteger(pad) && pad >= 0)) throw codedError('input-seat', `engine.input.seat(): pad is a gamepad index (0, 1, ...), got ${JSON.stringify(pad)}`);
26
26
  /** @internal */ this.input = input;
27
27
  /** The gamepad index this seat owns, if any @type {number | undefined} */ this.pad = pad;
28
- /** Who this seat acts for, as engine.actor for engine.input: createPlayer sets the player's id; interactions read it. Set it to hand the seat to a vehicle or a squad member @type {string | null} */ this.actor = null;
28
+ /** Who this seat acts for, as engine.actor for engine.input: addPlayer sets the player's id; interactions read it. Set it to hand the seat to a vehicle or a squad member @type {string | null} */ this.actor = null;
29
29
  /** @internal action -> this seat's keyboard keys */ this.own = new Map(Object.entries(keys).map(([a, k]) => [a, [k].flat()]));
30
30
  for (const s of input.seats) {
31
31
  if (pad !== undefined && s.pad === pad) throw codedError('input-seat', `engine.input.seat(): pad ${pad} already has a seat; give each seat its own pad`);
@@ -1,32 +1,46 @@
1
1
  // Performance budget, engine.budget: the game sets limits (only categories given are checked); on overrun it reports which category and who uses the most.
2
2
  // createEngine({ budget: { drawCalls: 250, fps: 55 } }) or engine.budget.enable({ drawCalls: 250 })
3
3
  // engine.budget.report() // { ok, over: [{ category, value, limit, top }] }; null when off
4
- // Off by default; when off, sample() returns immediately and costs nothing. The engine presets no limit numbers.
5
- // Categories: drawCalls, triangles, textures, cpuMs, fps, low1 (fps and low1 are lower bounds) + registered metrics (lights, shadowLights, shadowMaps, shadowMapSize, chunkApplyMs, rigidBodies...)
4
+ // Off by default: when off, sample() only keeps the frame times (two array writes; the median frame time every reader reports) and checks nothing.
5
+ // The engine presets no limit numbers for the game; its own reference limits (registered while it builds) never show as the game's overrun in notice().
6
+ // Categories: drawCalls, triangles, textures, gpuMemoryMB (WebGPU: three's own byte count, not driver VRAM), cpuMs, fps, low1 (fps and low1 are lower bounds) + registered metrics (lights, shadowLights, shadowMaps, shadowMapSize, chunkApplyMs, rigidBodies...)
6
7
  // + the apply-cost stages (applyTransitMs, applyBuildMs, applyColliderMs, applyUploadMs, applyStreamMs: ms per frame, see ApplyCost).
7
8
  // "Who uses the most": draw calls are estimated by the userData.budgetTag of an object (or its parent); untagged counts as 'other'.
9
+ // modules: { name: ms } limits a module's hook time per frame (median of engine.profile(), on in dev builds), checked as category 'modules.<name>'. A fixed-step hook counts its dearest step of the frame, not the sum of catch-up steps (cpuPhases.fixed keeps the sum).
10
+ // notice(): the one line shot, verify and describeText print when the game is over its own limits, slower than its recorded baseline
11
+ // (engine.budget.baseline, the tools load .threedog/perf-baseline.json into it), or running at a resolution adaptive resolution lowered; null when all is fine.
8
12
  /** @import { Handle } from '../../types/common' */
9
13
  /** @import { BudgetLimits, BudgetReport, BudgetTagStat } from '../../types/world' */
10
14
  import { coded } from '../base/errorHints.js';
11
15
  import { fmt, warnOnce } from '../base/validate.js';
12
- import { r1 } from '../base/math.js';
16
+ import { r1, median, cameraFrustum } from '../base/math.js';
17
+ import { loweredText } from '../scene/adaptive.js';
13
18
  import { SHADOW_TYPES } from '../../render/shadowTypes.js';
14
19
  import * as THREE from 'three';
15
- import { stats, shadowMaps } from '../../render/backend.js';
20
+ import { stats, shadowMaps, backendFacts, gpuMemoryMB } from '../../render/backend.js';
16
21
 
17
22
  const STRINGS = {
18
23
  startup: 'Startup took {value} ms, over budget startupMs {limit} ms; slowest module: {top}',
19
24
  module: 'Module {name} took {value} ms to start, over budget moduleMs {limit} ms (init + waiting for ready)',
20
25
  over: 'Performance budget exceeded: {category} = {value} ({dir} {limit}). Most draw calls: {top}',
21
26
  min: 'minimum', max: 'maximum',
27
+ noMemory: 'budget gpuMemoryMB is not checked on WebGLRenderer: three counts GPU bytes only on WebGPURenderer (createEngine({ renderer: "webgpu" })); geometries and textures counts are in engine.counts()',
22
28
  };
23
29
  const LOWER = new Set(['fps', 'low1']); // these two are lower bounds ("not below")
24
30
  const WINDOW = 300; // how many recent frames the frame-rate stats use
31
+ /** The recent frames as a ring allocated once: sample() runs every frame with the budget off too, so it writes in place (no push / shift) */
32
+ const ring = () => ({ buf: new Float64Array(WINDOW), n: 0, i: 0 });
33
+ const put = (r, v) => { r.buf[r.i] = v; r.i = (r.i + 1) % WINDOW; if (r.n < WINDOW) r.n++; };
34
+ const view = r => r.buf.subarray(0, r.n); // the filled part, in any order: every reader is a sum, sort or median
25
35
 
26
36
  /** Cost stages of bringing a background result into the frame, in the order a chunk goes through them */
27
37
  const STAGES = ['transit', 'build', 'collider', 'upload', 'stream'];
28
38
  const EMA = 0.1; // per-frame smoothing, the same factor chunkApplyMs always used
29
39
  const COMPILES_KEPT = 20; // compile-stall frames remembered by ApplyCost.compiles
40
+ // Noise margins of the baseline comparison. Times: browsers round performance.now() to 0.1 ms and the same run moves 10-30% between runs
41
+ // (recipe 15), so a time is slower only past both +20% and +0.2 ms. Counts (draw calls, triangles) repeat exactly in the same view: +5%.
42
+ const SLOW_MS = { share: 0.2, abs: 0.2 }, SLOW_COUNT = 0.05;
43
+ const pct = (v, base) => `${v >= base ? '+' : ''}${Math.round((v / base - 1) * 100)}%`;
30
44
 
31
45
  /** Bytes of the typed arrays in a plain result object, `depth` levels down @param {any} v @param {number} depth @returns {number} */
32
46
  function arrayBytes(v, depth) {
@@ -114,15 +128,18 @@ export class Budget {
114
128
  this.limits = {};
115
129
  /** @internal Module-defined categories: name -> { read, limit } @type {Map<string, { read: () => number, limit?: number }>} */
116
130
  this.metrics = new Map();
117
- /** @internal */ this._dts = [];
118
- /** @internal */ this._cpu = [];
131
+ /** @internal */ this._dts = ring();
132
+ /** @internal */ this._cpu = ring();
119
133
  /** @internal */ this._t = 0;
120
134
  /** @internal @type {any} */ this._last = null;
121
135
  /** Cost of applying background results, split in stages (see ApplyCost) */
122
136
  this.cost = new ApplyCost();
123
137
  for (const k of STAGES) this.metric('apply' + k[0].toUpperCase() + k.slice(1) + 'Ms', () => this.cost.t[k].frameMs);
138
+ /** The recorded run to compare against: { [where]: { drawCalls, triangles, cpuMs?, modules: { name: ms } } } as record() makes it. threedog shot / verify
139
+ * load the game's .threedog/perf-baseline.json (this machine's) here when the game set none (and write it with --save-baseline). null = no comparison
140
+ * @type {Record<string, any> | null} */
141
+ this.baseline = null;
124
142
  /** @internal */ this._frustum = new THREE.Frustum();
125
- /** @internal */ this._m = new THREE.Matrix4();
126
143
  }
127
144
  /**
128
145
  * Turn on and set limits (only categories given are checked)
@@ -130,7 +147,7 @@ export class Budget {
130
147
  * @returns {this}
131
148
  * @example engine.budget.enable({ drawCalls: 250, fps: 55 });
132
149
  */
133
- enable(limits = {}) { this.enabled = true; this.limits = { ...limits }; this._dts = []; this._cpu = []; this._last = null; return this; }
150
+ enable(limits = {}) { this.enabled = true; this.limits = { ...limits }; this._last = null; return this; }
134
151
  /** Turn off @experimental */
135
152
  disable() { this.enabled = false; this._last = null; }
136
153
  /**
@@ -141,19 +158,22 @@ export class Budget {
141
158
  * @returns {Handle}
142
159
  */
143
160
  metric(name, read, opts = {}) {
144
- const m = { read, limit: opts.limit };
161
+ // registered while the engine builds = the engine's reference limit (gameLights' lights), not the game's budget (_ownLimit)
162
+ const m = { read, limit: opts.limit, engine: !this.engine._born?.built };
145
163
  this.metrics.set(name, m);
146
164
  return { remove: () => { if (this.metrics.get(name) === m) this.metrics.delete(name); } };
147
165
  }
148
166
  /** Limit of a category; undefined if none was given (not checked) @param {string} name @returns {number | undefined} @experimental */
149
- limitOf(name) { return this.limits[name] ?? this.metrics.get(name)?.limit; }
167
+ limitOf(name) {
168
+ if (name.startsWith('modules.')) return this.limits.modules?.[name.slice(8)];
169
+ const v = this.limits[name];
170
+ return typeof v === 'number' ? v : this.metrics.get(name)?.limit;
171
+ }
150
172
 
151
173
  /** @internal Called by the engine after each rendered frame: records frame time, checks once a second, and warns once per category over its limit */
152
174
  sample(dt) {
153
- if (!this.enabled) return;
154
- this._dts.push(dt); this._cpu.push(this.engine._cpuMs ?? 0);
155
- if (this._dts.length > WINDOW) { this._dts.shift(); this._cpu.shift(); }
156
- if ((this._t += dt) < 1) return;
175
+ put(this._dts, dt); put(this._cpu, this.engine._cpuMs ?? 0); // always: the median frame time describe and inspect.perf report
176
+ if (!this.enabled || (this._t += dt) < 1) return;
157
177
  this._t = 0;
158
178
  const r = this._last = this._evaluate();
159
179
  for (const o of r.over) {
@@ -164,7 +184,7 @@ export class Budget {
164
184
  /** Budget report; null when off. In the real-time loop it returns the last second's result; in step() mode it is computed on demand @returns {BudgetReport | null} */
165
185
  report() {
166
186
  if (!this.enabled) return null;
167
- return this._last && this._dts.length ? this._last : this._evaluate();
187
+ return this._last && this._dts.n ? this._last : this._evaluate();
168
188
  }
169
189
  /**
170
190
  * Called by the engine when startup finishes: warns if startupMs / moduleMs is exceeded and returns the offenders (empty array if none)
@@ -187,19 +207,36 @@ export class Budget {
187
207
  }
188
208
  return over;
189
209
  }
210
+ /** @internal Forget the frame times so far (the loop calls it once, when start-up has settled: start-up frames are not play) */
211
+ _clearFrames() { this._dts.n = this._dts.i = 0; this._cpu.n = this._cpu.i = 0; }
212
+ /** @internal Frame time as every reader reports it: the median main-thread ms of the last n real-time frames (null before the first one) */
213
+ _frameMs() { return this._cpu.n ? { ms: r1(median(view(this._cpu))), n: this._cpu.n } : null; }
190
214
  /** Current value per category (fps/low1/cpuMs exist only once there are frame times) @returns {Record<string, number>} */
191
215
  values() {
192
- const s = stats(this.engine.renderer), v = /** @type {Record<string, number>} */ ({ drawCalls: s.drawCalls, triangles: s.triangles, textures: s.textures });
193
- const d = this._dts;
216
+ const r = this.engine.renderer, s = stats(r), v = /** @type {Record<string, number>} */ ({ drawCalls: s.drawCalls, triangles: s.triangles, textures: s.textures });
217
+ const mb = gpuMemoryMB(r);
218
+ if (mb != null) v.gpuMemoryMB = mb;
219
+ else if (this.limits.gpuMemoryMB != null) warnOnce(coded('budget-option', STRINGS.noMemory)); // a declared limit never checked must say so
220
+ const d = view(this._dts);
194
221
  if (d.length) {
195
222
  const sum = d.reduce((a, b) => a + b, 0), worst = d.slice().sort((a, b) => b - a), n = Math.max(1, Math.floor(d.length * 0.01));
196
223
  v.fps = r1(d.length / sum);
197
224
  v.low1 = r1(n / worst.slice(0, n).reduce((a, b) => a + b, 0));
198
- v.cpuMs = r1(this._cpu.reduce((a, b) => a + b, 0) / this._cpu.length);
225
+ v.cpuMs = this._frameMs().ms; // median: one GC pause or chunk build does not read as a slow game
199
226
  }
200
227
  for (const [name, m] of this.metrics) v[name] = r1(m.read());
228
+ const own = this.limits.modules, prof = own && this.engine.profile?.();
229
+ if (prof) for (const k in own) if (prof[k] != null) v['modules.' + k] = prof[k].ms;
201
230
  return v;
202
231
  }
232
+ /** @internal The limit the GAME declared for a category (enable / createEngine, or a metric registered after the engine was built), else undefined.
233
+ * The one filter between "the game's budget" and the engine's own reference limits (gameLights' lights limit, registered while the engine builds):
234
+ * the notice reports only these */
235
+ _ownLimit(name) {
236
+ if (name.startsWith('modules.')) return this.limits.modules?.[name.slice(8)];
237
+ const v = this.limits[name], m = this.metrics.get(name);
238
+ return typeof v === 'number' ? v : m && !m.engine ? m.limit : undefined;
239
+ }
203
240
  /** @internal */
204
241
  _evaluate() {
205
242
  const v = this.values(), over = [];
@@ -212,6 +249,59 @@ export class Budget {
212
249
  }
213
250
  return { ok: !over.length, over };
214
251
  }
252
+ /** @internal Where a measurement was taken: this machine's GPU, timing mode, backend, canvas size and pixel ratio, camera position (1 m) and
253
+ * direction. A baseline compares only like with like: counts follow what the camera sees, times follow the machine and the pixels drawn */
254
+ _where() {
255
+ const e = this.engine, r = e.renderer, c = e.camera, d = c.getWorldDirection(this._v ??= new THREE.Vector3()), cv = r.domElement;
256
+ const n = (/** @type {number} */ x, k = 1) => Math.round(x * k) / k;
257
+ this._gpu ||= backendFacts(r).gpu ?? ''; // WebGPU knows its adapter only after init: asked again until it answers
258
+ return `${e.headless ? 'step' : 'live'} ${r.isWebGPURenderer ? 'webgpu' : 'webgl'} ${this._gpu || 'gpu?'} ${cv.width}x${cv.height}@${n(r.getPixelRatio(), 100)} @${n(c.position.x)},${n(c.position.y)},${n(c.position.z)} >${n(d.x, 10)},${n(d.y, 10)},${n(d.z, 10)}`;
259
+ }
260
+ /**
261
+ * This run's numbers in the shape baseline keeps: { where, values: { drawCalls, triangles, cpuMs (live runs), modules: { name: median ms, 0 too } } }.
262
+ * threedog shot / verify --save-baseline write it into the game's .threedog/perf-baseline.json (this machine's, not committed)
263
+ * @returns {{ where: string, values: { drawCalls: number, triangles: number, cpuMs?: number, modules: Record<string, number> } }}
264
+ */
265
+ record() {
266
+ const v = this.values(), prof = this.engine.profile?.() ?? {};
267
+ const modules = Object.fromEntries(Object.entries(prof).map(([k, p]) => [k, p.ms])); // zeros kept: a module that was free and now costs shows
268
+ return { where: this._where(), values: { drawCalls: v.drawCalls, triangles: v.triangles, ...(v.cpuMs != null && { cpuMs: v.cpuMs }), modules } };
269
+ }
270
+ /** @internal What is slower than the baseline recorded at this same spot: [{ category, value, base }] (base null: a module the baseline lacks), worst first */
271
+ _slower() {
272
+ const b = this.baseline?.[this._where()];
273
+ if (!b) return [];
274
+ const v = this.values(), prof = this.engine.profile?.() ?? {}, out = [], mods = b.modules ?? {};
275
+ const push = (category, value, base) => out.push({ category, value, base });
276
+ for (const k of ['drawCalls', 'triangles']) if (b[k] > 0 && v[k] > b[k] * (1 + SLOW_COUNT)) push(k, v[k], b[k]); // a 0 recorded before any draw compares nothing
277
+ // times: past both margins; from 0 or absent (a module new since the baseline) the absolute floor alone, so a regression from nothing shows
278
+ const slowMs = (now, was) => now - (was ?? 0) >= SLOW_MS.abs && (!(was > 0) || now > was * (1 + SLOW_MS.share));
279
+ if (typeof b.cpuMs === 'number' && v.cpuMs != null && slowMs(v.cpuMs, b.cpuMs)) push('cpuMs', v.cpuMs, b.cpuMs);
280
+ for (const [k, p] of Object.entries(prof)) if (slowMs(p.ms, mods[k])) push('modules.' + k, p.ms, typeof mods[k] === 'number' ? mods[k] : null);
281
+ const ratio = s => s.value / Math.max(s.base ?? 0, 1e-3);
282
+ return out.sort((a, b) => ratio(b) - ratio(a));
283
+ }
284
+ /**
285
+ * One line when something is off, null when all is fine: over a limit the game declared (only when the budget is on; the engine's own reference
286
+ * limits never), slower than the baseline recorded at this spot on this machine (medians, past a noise margin), a module with spikes (p95 over 3x
287
+ * its median and over 2 ms), or what adaptive quality lowered (resolution, effects). threedog shot, verify and describeText print it
288
+ * @returns {string | null}
289
+ * @example engine.budget.notice() // 'Perf: over budget drawCalls 312 (limit 250, +25%); slower than baseline: modules.terrain 1.4 ms (was 0.6, +133%) -> threedog inspect perf'
290
+ */
291
+ notice() { return this._notice(this.report()); }
292
+ /** @internal notice() on a report already made (describe() makes one for its own budget field: an overrun walks the scene once, not twice) */
293
+ _notice(rep) {
294
+ const parts = [], e = this.engine, prof = e.profile?.() ?? {};
295
+ const unit = k => k === 'cpuMs' || k.startsWith('modules.') ? ' ms' : '';
296
+ const over = rep?.over.filter(o => this._ownLimit(o.category) != null) ?? [], slow = this._slower();
297
+ const spiky = Object.entries(prof).filter(([, p]) => p.p95 > 2 && p.p95 > 3 * p.ms);
298
+ if (over.length) parts.push('over budget ' + over.slice(0, 3).map(o => `${o.category} ${o.value}${unit(o.category)} (limit ${o.limit}, ${pct(o.value, o.limit)})`).join(', '));
299
+ if (slow.length) parts.push('slower than baseline: ' + slow.slice(0, 3).map(s => `${s.category} ${s.value}${unit(s.category)} (${s.base == null ? 'new' : s.base > 0 ? `was ${s.base}, ${pct(s.value, s.base)}` : 'was 0'})`).join(', '));
300
+ if (spiky.length) parts.push('spiky: ' + spiky.slice(0, 3).map(([k, p]) => `${k} (p95 ${p.p95} ms, median ${p.ms})`).join(', '));
301
+ const lowered = loweredText(e); // adaptive quality: what its ladder holds lowered now (core/scene/adaptive.js)
302
+ if (lowered) parts.push(lowered);
303
+ return parts.length ? `Perf: ${parts.join('; ')} -> threedog inspect perf` : null;
304
+ }
215
305
  /**
216
306
  * Estimate draw calls and triangles by userData.budgetTag (visible meshes inside the frustum; shadow casters count a second shadow draw).
217
307
  * Returns [{ tag, drawCalls, triangles }], largest first. Called only on overrun (at most once a second) or when debugging
@@ -222,7 +312,7 @@ export class Budget {
222
312
  // shadow passes a caster is drawn in: one per shadow map the renderer draws (each cascade on both renderers), six for a point light
223
313
  const passes = Math.max(1, shadowMaps(e.renderer, e.scene).reduce((n, m) => n + m.faces, 0));
224
314
  cam.updateMatrixWorld();
225
- this._frustum.setFromProjectionMatrix(this._m.multiplyMatrices(cam.projectionMatrix, cam.matrixWorldInverse));
315
+ cameraFrustum(cam, this._frustum);
226
316
  const walk = (o, tag) => {
227
317
  if (!o.visible) return;
228
318
  tag = o.userData.budgetTag ?? tag;