threedog 0.2.1 → 0.5.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 (593) hide show
  1. package/CHANGELOG.md +290 -0
  2. package/README.md +9 -8
  3. package/core/Animator.js +15 -12
  4. package/core/Assets.js +71 -16
  5. package/core/Audio.js +45 -38
  6. package/core/Baked.js +32 -8
  7. package/core/Batching.js +102 -15
  8. package/core/Budget.js +39 -18
  9. package/core/Clock.js +40 -80
  10. package/core/DebugOverrides.js +45 -10
  11. package/core/Describe.js +104 -43
  12. package/core/Engine.js +183 -59
  13. package/core/Events.js +4 -1
  14. package/core/I18n.js +25 -13
  15. package/core/Input.js +168 -79
  16. package/core/Inspect.js +2 -2
  17. package/core/InspectMaterials.js +85 -0
  18. package/core/InspectPerf.js +61 -0
  19. package/core/InspectScene.js +13 -2
  20. package/core/Loading.js +2 -1
  21. package/core/Ops.js +50 -9
  22. package/core/Random.js +9 -2
  23. package/core/Rays.js +5 -5
  24. package/core/SaveStore.js +41 -9
  25. package/core/Saves.js +71 -15
  26. package/core/Stream.js +14 -10
  27. package/core/Threads.js +26 -7
  28. package/core/UrlState.js +25 -9
  29. package/core/Views.js +9 -6
  30. package/core/actor.js +1 -1
  31. package/core/adaptive.js +93 -0
  32. package/core/assetEntry.js +22 -5
  33. package/core/assetHot.js +176 -0
  34. package/core/assetLoad.js +38 -11
  35. package/core/assetManifest.js +48 -9
  36. package/core/assetReport.js +1 -1
  37. package/core/audioRules.js +13 -11
  38. package/core/audioVoice.js +69 -42
  39. package/core/canvasBox.js +1 -2
  40. package/core/catalog.js +5 -2
  41. package/core/cells.js +62 -0
  42. package/core/checks.js +10 -8
  43. package/core/chunkStream.js +87 -0
  44. package/core/control.js +149 -0
  45. package/core/copies.js +32 -0
  46. package/core/dayTime.js +12 -6
  47. package/core/debugView.js +82 -15
  48. package/core/describeRender.js +37 -17
  49. package/core/describeText.js +41 -21
  50. package/core/engineCamera.js +32 -0
  51. package/core/errorCodes.js +438 -19
  52. package/core/errorHints.js +37 -141
  53. package/core/errors.js +31 -8
  54. package/core/events.generated.js +12 -7
  55. package/core/gameLights.js +62 -0
  56. package/core/grayMap.js +20 -0
  57. package/core/grid.js +14 -13
  58. package/core/gridLoad.js +2 -1
  59. package/core/ground.js +6 -4
  60. package/core/headlessLoad.js +55 -0
  61. package/core/holds.js +78 -50
  62. package/core/inputContext.js +11 -7
  63. package/core/inputDefaults.js +24 -21
  64. package/core/inputPad.js +1 -1
  65. package/core/inputPointer.js +1 -1
  66. package/core/inputTouch.js +2 -2
  67. package/core/lifecycle.js +48 -12
  68. package/core/lightWatch.js +6 -4
  69. package/core/look/coreParts.js +137 -30
  70. package/core/look/part.js +175 -95
  71. package/core/look/points.js +255 -0
  72. package/core/look/report.js +34 -17
  73. package/core/look/shadowPart.js +63 -0
  74. package/core/look/state.js +45 -0
  75. package/core/look/write.js +12 -28
  76. package/core/loop.js +100 -41
  77. package/core/math.js +11 -3
  78. package/core/moduleSlots.js +75 -0
  79. package/core/moduleTypes.js +73 -0
  80. package/core/modules.js +145 -27
  81. package/core/movement.js +2 -2
  82. package/core/namedModel.js +70 -0
  83. package/core/opsCheck.js +3 -3
  84. package/core/opsFail.js +15 -6
  85. package/core/opsGuard.js +4 -4
  86. package/core/opsRun.js +4 -3
  87. package/core/owned.js +168 -0
  88. package/core/page.js +2 -1
  89. package/core/params.js +30 -8
  90. package/core/plugins.js +277 -0
  91. package/core/saveApply.js +99 -17
  92. package/core/saveFiles.js +8 -6
  93. package/core/saveValues.js +46 -0
  94. package/core/saveVersions.js +20 -3
  95. package/core/scatter.js +48 -19
  96. package/core/sceneDelta.js +203 -0
  97. package/core/sceneMethods.js +35 -30
  98. package/core/screenToGround.js +1 -1
  99. package/core/services.js +27 -11
  100. package/core/session.js +28 -25
  101. package/core/shaderCost.js +78 -0
  102. package/core/shadowTypes.js +2 -1
  103. package/core/sharedPoint.js +317 -0
  104. package/core/skip.js +36 -28
  105. package/core/stackFrames.js +34 -0
  106. package/core/stacks.js +166 -0
  107. package/core/startup.js +153 -11
  108. package/core/streamSources.js +0 -11
  109. package/core/styleParts.js +63 -47
  110. package/core/targeting.js +1 -1
  111. package/core/textureBytes.js +20 -0
  112. package/core/thingExplain.js +2 -2
  113. package/core/thingOps.js +29 -6
  114. package/core/things.js +21 -11
  115. package/core/threadPure.js +7 -3
  116. package/core/threePatches.js +47 -0
  117. package/core/tier.js +21 -10
  118. package/core/time.js +236 -0
  119. package/core/uiClock.js +25 -0
  120. package/core/util.js +7 -1
  121. package/core/validate.js +65 -86
  122. package/core/wrap.js +106 -0
  123. package/docs/AI.md +87 -100
  124. package/docs/API.md +32 -28
  125. package/docs/CODEMAP.md +220 -147
  126. package/docs/COMMANDS.md +56 -35
  127. package/docs/CONVENTIONS.md +90 -28
  128. package/docs/MIGRATING-0.3.md +248 -0
  129. package/docs/MIGRATING-0.4.md +228 -0
  130. package/docs/MIGRATING-0.5.md +68 -0
  131. package/docs/PERF.md +35 -7
  132. package/docs/THREE.md +79 -27
  133. package/docs/api/ambience.md +0 -1
  134. package/docs/api/assets.md +11 -9
  135. package/docs/api/audio.md +10 -14
  136. package/docs/api/calendar.md +41 -0
  137. package/docs/api/cameraRig.md +16 -5
  138. package/docs/api/characters.md +38 -23
  139. package/docs/api/clock.md +6 -5
  140. package/docs/api/collision.md +9 -6
  141. package/docs/api/content.md +6 -4
  142. package/docs/api/dialogue.md +9 -9
  143. package/docs/api/engine.md +63 -60
  144. package/docs/api/events.md +19 -14
  145. package/docs/api/grids.md +3 -3
  146. package/docs/api/ground.md +1 -1
  147. package/docs/api/hud.md +2 -2
  148. package/docs/api/i18n.md +1 -1
  149. package/docs/api/input.md +11 -6
  150. package/docs/api/interactions.md +7 -5
  151. package/docs/api/inventory.md +17 -16
  152. package/docs/api/level.md +0 -1
  153. package/docs/api/lightPool.md +3 -1
  154. package/docs/api/music.md +1 -1
  155. package/docs/api/nav.md +3 -0
  156. package/docs/api/openWorld.md +2 -1
  157. package/docs/api/particles.md +2 -2
  158. package/docs/api/photo.md +0 -2
  159. package/docs/api/pickups.md +15 -0
  160. package/docs/api/post.md +5 -4
  161. package/docs/api/quests.md +2 -3
  162. package/docs/api/rigid.md +16 -14
  163. package/docs/api/saves.md +6 -4
  164. package/docs/api/settings.md +2 -3
  165. package/docs/api/sky.md +11 -44
  166. package/docs/api/stream.md +1 -1
  167. package/docs/api/style.md +28 -26
  168. package/docs/api/terrain.md +9 -6
  169. package/docs/api/terrainLook.md +10 -0
  170. package/docs/api/timeline.md +3 -4
  171. package/docs/api/tools.md +29 -13
  172. package/docs/api/triggers.md +5 -10
  173. package/docs/api/vegetation.md +11 -8
  174. package/docs/api/vegetationLook.md +10 -0
  175. package/docs/api/water.md +4 -20
  176. package/docs/api/weather.md +5 -15
  177. package/docs/api/weatherLook.md +10 -0
  178. package/docs/api/world.md +2 -1
  179. package/docs/recipes/01-new-game.md +48 -34
  180. package/docs/recipes/02-npc.md +24 -7
  181. package/docs/recipes/03-items-pickups.md +35 -21
  182. package/docs/recipes/04-quests.md +12 -5
  183. package/docs/recipes/05-props-bake.md +151 -15
  184. package/docs/recipes/06-clock-events.md +100 -52
  185. package/docs/recipes/07-flow-scenes-pause.md +40 -9
  186. package/docs/recipes/08-weather-sky.md +145 -36
  187. package/docs/recipes/{09-style-pack.md → 09-style.md} +101 -52
  188. package/docs/recipes/10-blender-level.md +14 -2
  189. package/docs/recipes/11-vehicles.md +64 -7
  190. package/docs/recipes/13-animation.md +14 -6
  191. package/docs/recipes/14-custom-module.md +61 -29
  192. package/docs/recipes/15-perf.md +30 -9
  193. package/docs/recipes/16-dev-bridge.md +61 -37
  194. package/docs/recipes/18-world.md +16 -6
  195. package/docs/recipes/19-shooting-picking.md +6 -6
  196. package/docs/recipes/20-content-actions-save.md +55 -17
  197. package/docs/recipes/21-camera.md +49 -16
  198. package/docs/recipes/22-shop-gold.md +3 -3
  199. package/docs/recipes/23-ops.md +16 -10
  200. package/docs/recipes/26-ui-parts.md +61 -12
  201. package/docs/recipes/27-net.md +11 -5
  202. package/docs/recipes/28-terrain.md +34 -1
  203. package/docs/recipes/29-grid.md +34 -16
  204. package/docs/recipes/30-templates.md +64 -12
  205. package/docs/recipes/31-audio.md +20 -12
  206. package/docs/recipes/32-action-game.md +35 -2
  207. package/docs/recipes/34-environment-lighting.md +26 -3
  208. package/docs/recipes/35-style-from-reference.md +88 -19
  209. package/docs/recipes/36-sky-ground-plant-looks.md +18 -18
  210. package/docs/recipes/37-terrain-look-hooks.md +3 -2
  211. package/docs/recipes/38-environment-look-hooks.md +37 -26
  212. package/docs/recipes/40-scene.md +16 -13
  213. package/docs/recipes/41-thing-registry.md +11 -7
  214. package/docs/recipes/42-terrain-shape.md +2 -2
  215. package/docs/recipes/43-shader-patches-surface-looks.md +158 -76
  216. package/docs/recipes/44-water-weather-look-hooks.md +26 -17
  217. package/docs/recipes/45-cascaded-shadows.md +16 -7
  218. package/docs/recipes/47-island-snow-backdrop.md +7 -7
  219. package/docs/recipes/48-make-material.md +11 -6
  220. package/docs/recipes/49-game-module-contract.md +30 -17
  221. package/docs/recipes/50-own-renderer.md +2 -2
  222. package/docs/recipes/51-capability-catalog.md +3 -3
  223. package/docs/recipes/52-look.md +197 -61
  224. package/docs/recipes/53-ground-up-close.md +1 -1
  225. package/docs/recipes/54-three-idioms.md +88 -0
  226. package/docs/recipes/55-mods-time-wrap.md +112 -0
  227. package/docs/recipes/56-webgpu-tsl.md +260 -0
  228. package/docs/recipes/57-control.md +65 -0
  229. package/docs/recipes/58-input.md +57 -0
  230. package/docs/recipes/59-depth-post-effects.md +83 -0
  231. package/docs/recipes/60-judge-the-picture.md +55 -0
  232. package/examples/action/.threedog/content-index.json +1 -0
  233. package/examples/action/GAMEMAP.md +17 -13
  234. package/examples/action/assets.js +8 -0
  235. package/examples/action/content/actions.js +1 -1
  236. package/examples/action/content/audio.js +5 -5
  237. package/examples/action/look.js +1 -1
  238. package/examples/action/main.js +10 -14
  239. package/examples/action/models.js +24 -23
  240. package/examples/pullable.json +111 -0
  241. package/examples/rc2d/.threedog/content-index.json +1 -0
  242. package/examples/rc2d/GAMEMAP.md +83 -0
  243. package/examples/rc2d/README.md +52 -0
  244. package/examples/rc2d/main.js +63 -0
  245. package/examples/rc2d/rc2d.js +197 -0
  246. package/examples/rc2d/shaders.js +144 -0
  247. package/examples/sheepisland/.threedog/content-index.json +1 -0
  248. package/examples/sheepisland/GAMEMAP.md +13 -11
  249. package/examples/sheepisland/assets.js +5 -0
  250. package/examples/sheepisland/main.js +17 -12
  251. package/examples/sheepisland/style/index.js +6 -6
  252. package/examples/styletest/.threedog/content-index.json +1 -0
  253. package/examples/styletest/GAMEMAP.md +15 -16
  254. package/examples/styletest/assets.js +6 -0
  255. package/examples/styletest/content/templates.js +1 -1
  256. package/examples/styletest/content/vegetation.js +1 -1
  257. package/examples/styletest/look.js +1 -1
  258. package/examples/styletest/main.js +17 -16
  259. package/examples/styletest/models.js +1 -1
  260. package/examples/styletest/params.js +3 -3
  261. package/examples/techniques/contact-shadows/README.md +92 -0
  262. package/examples/techniques/contact-shadows/contactShadows.js +51 -0
  263. package/examples/techniques/contact-shadows/main.js +53 -0
  264. package/examples/techniques/day-night-grade/README.md +86 -0
  265. package/examples/techniques/day-night-grade/dayNightGrade.js +76 -0
  266. package/examples/techniques/day-night-grade/main.js +51 -0
  267. package/examples/techniques/interior-light/README.md +103 -0
  268. package/examples/techniques/interior-light/interiorLight.js +45 -0
  269. package/examples/techniques/interior-light/main.js +124 -0
  270. package/examples/techniques/modular-building/README.md +125 -0
  271. package/examples/techniques/modular-building/kit.js +426 -0
  272. package/examples/techniques/modular-building/main.js +47 -0
  273. package/examples/techniques/night-lights/README.md +94 -0
  274. package/examples/techniques/night-lights/main.js +70 -0
  275. package/examples/techniques/night-lights/nightLights.js +91 -0
  276. package/examples/techniques/outlines-and-rim/README.md +59 -0
  277. package/examples/techniques/outlines-and-rim/main.js +84 -0
  278. package/examples/techniques/outlines-and-rim/outlines.js +64 -0
  279. package/examples/techniques/procedural-animation/README.md +77 -0
  280. package/examples/techniques/procedural-animation/creature.js +44 -0
  281. package/examples/techniques/procedural-animation/main.js +45 -0
  282. package/examples/techniques/procedural-animation/proceduralAnim.js +118 -0
  283. package/examples/techniques/procedural-surface/README.md +67 -0
  284. package/examples/techniques/procedural-surface/main.js +103 -0
  285. package/examples/techniques/procedural-surface/surface.js +120 -0
  286. package/examples/techniques/stylized-shading/README.md +75 -0
  287. package/examples/techniques/stylized-shading/main.js +93 -0
  288. package/examples/techniques/stylized-shading/shading.js +131 -0
  289. package/examples/techniques/sun-and-key-light/README.md +135 -0
  290. package/examples/techniques/sun-and-key-light/keyLight.js +53 -0
  291. package/examples/techniques/sun-and-key-light/main.js +95 -0
  292. package/examples/techniques/wet-road/README.md +99 -0
  293. package/examples/techniques/wet-road/main.js +68 -0
  294. package/examples/techniques/wet-road/wetRoad.js +209 -0
  295. package/examples/webgpu-tsl/.threedog/content-index.json +1 -0
  296. package/examples/webgpu-tsl/GAMEMAP.md +84 -0
  297. package/examples/webgpu-tsl/README.md +42 -0
  298. package/examples/webgpu-tsl/main.js +21 -0
  299. package/examples/webgpu-tsl/tslScene.js +75 -0
  300. package/examples/world/.threedog/content-index.json +1 -0
  301. package/examples/world/GAMEMAP.md +22 -15
  302. package/examples/world/art/humanoid.js +42 -0
  303. package/examples/world/art/index.js +11 -0
  304. package/examples/world/art/models.js +58 -0
  305. package/examples/world/art/shapes.js +9 -0
  306. package/examples/world/assets.js +6 -0
  307. package/examples/world/content/audio.js +5 -5
  308. package/examples/world/content/npcs.js +1 -1
  309. package/examples/world/content/props.js +1 -1
  310. package/examples/world/content/rules.js +1 -1
  311. package/examples/world/content/templates.js +1 -1
  312. package/examples/world/content/vegetation.js +1 -1
  313. package/examples/world/main.js +17 -13
  314. package/examples/world/style/index.js +61 -0
  315. package/examples/world/style/plugins/10-bloom.js +5 -0
  316. package/index.d.ts +44 -45
  317. package/index.js +26 -22
  318. package/llms.txt +11 -4
  319. package/modules/ambience/Ambience.js +34 -23
  320. package/modules/calendar/Calendar.js +163 -0
  321. package/modules/calendar/contract.js +21 -0
  322. package/modules/calendar/index.js +81 -0
  323. package/modules/{sky → calendar}/schedule.js +17 -16
  324. package/modules/calendar/seasons.js +55 -0
  325. package/modules/camera/FirstPersonCamera.js +6 -15
  326. package/modules/camera/FixedCamera.js +33 -15
  327. package/modules/camera/FollowCamera.js +90 -16
  328. package/modules/camera/RtsCamera.js +18 -17
  329. package/modules/camera/common.js +70 -19
  330. package/modules/camera/contract.js +17 -0
  331. package/modules/camera/projection.js +11 -24
  332. package/modules/characters/Character.js +177 -42
  333. package/modules/characters/NPC.js +87 -36
  334. package/modules/characters/assetModel.js +4 -13
  335. package/modules/characters/behaviors.js +2 -1
  336. package/modules/characters/contract.js +13 -0
  337. package/modules/characters/footsteps.js +1 -1
  338. package/modules/characters/index.js +87 -49
  339. package/modules/characters/moveHelpers.js +4 -5
  340. package/modules/characters/movers/common.js +97 -19
  341. package/modules/characters/movers/manual.js +20 -0
  342. package/modules/characters/movers/rapier.js +19 -16
  343. package/modules/characters/movers/simple.js +14 -11
  344. package/modules/characters/movers/support.js +172 -0
  345. package/modules/characters/npcAvoid.js +47 -42
  346. package/modules/characters/npcSim.js +12 -8
  347. package/modules/characters/npcView.js +44 -16
  348. package/modules/characters/pathAsync.js +7 -3
  349. package/modules/characters/playerStrings.js +4 -3
  350. package/modules/characters/proceduralRig.js +2 -1
  351. package/modules/characters/useModel.js +1 -1
  352. package/modules/characters/vehicle.contract.js +21 -0
  353. package/modules/characters/walkTo.js +21 -7
  354. package/modules/collision/Collision.js +65 -25
  355. package/modules/collision/grid.js +8 -6
  356. package/modules/content/explain.js +2 -2
  357. package/modules/content/fields.js +102 -0
  358. package/modules/content/ids.js +8 -6
  359. package/modules/content/index.js +96 -27
  360. package/modules/content/loader.js +45 -33
  361. package/modules/content/models.js +11 -40
  362. package/modules/content/packs.js +6 -5
  363. package/modules/content/parts.js +41 -0
  364. package/modules/content/props.js +16 -9
  365. package/modules/content/rules.js +58 -0
  366. package/modules/content/stages.js +80 -0
  367. package/modules/content/templates.js +121 -30
  368. package/modules/debug/DebugPanel.js +24 -17
  369. package/modules/flow/contract.js +16 -0
  370. package/modules/flow/index.js +21 -15
  371. package/modules/gameplay/Container.js +41 -32
  372. package/modules/gameplay/Containers.js +30 -15
  373. package/modules/gameplay/Dialogue.js +113 -55
  374. package/modules/gameplay/Interactions.js +193 -67
  375. package/modules/gameplay/Inventory.js +69 -73
  376. package/modules/gameplay/Quests.js +75 -39
  377. package/modules/gameplay/boxOps.js +3 -3
  378. package/modules/gameplay/dialogue.contract.js +21 -0
  379. package/modules/gameplay/dialogueBox.js +4 -2
  380. package/modules/gameplay/dialogueBubbles.js +116 -0
  381. package/modules/gameplay/interactionPrompt.js +4 -1
  382. package/modules/gameplay/interactions.contract.js +16 -0
  383. package/modules/gameplay/inventory.contract.js +23 -0
  384. package/modules/gameplay/inventoryOps.js +18 -16
  385. package/modules/gameplay/pickups.js +268 -85
  386. package/modules/gameplay/questLog.js +4 -4
  387. package/modules/gameplay/quests.contract.js +17 -0
  388. package/modules/grid/Grid.js +92 -50
  389. package/modules/grid/Layer.js +14 -13
  390. package/modules/grid/index.js +60 -36
  391. package/modules/grid/ops.js +20 -18
  392. package/modules/grid/preview.js +15 -16
  393. package/modules/grid/strings.js +12 -0
  394. package/modules/grid/tiles.js +6 -5
  395. package/modules/hlod/index.js +51 -19
  396. package/modules/hud/index.js +35 -20
  397. package/modules/hud/parts.js +20 -7
  398. package/modules/level/heightfield.js +3 -1
  399. package/modules/level/index.js +45 -20
  400. package/modules/level/nodes.js +4 -3
  401. package/modules/lights/index.js +42 -18
  402. package/modules/music/Music.js +38 -21
  403. package/modules/music/rules.js +1 -1
  404. package/modules/nav/index.js +48 -42
  405. package/modules/net/Client.js +13 -6
  406. package/modules/net/Host.js +19 -5
  407. package/modules/net/Net.js +2 -1
  408. package/modules/net/index.js +13 -8
  409. package/modules/net/sync.js +9 -8
  410. package/modules/net/transports.js +77 -27
  411. package/modules/particles/Particles.js +23 -14
  412. package/modules/particles/contract.js +17 -0
  413. package/modules/particles/effect.js +39 -11
  414. package/modules/photo/Photo.js +53 -36
  415. package/modules/rigid/RigidBodies.js +194 -32
  416. package/modules/rigid/Vehicles.js +18 -15
  417. package/modules/rigid/sync.js +62 -17
  418. package/modules/settings/Settings.js +57 -52
  419. package/modules/settings/apply.js +38 -3
  420. package/modules/settings/sections.js +5 -3
  421. package/modules/settings/strings.js +3 -2
  422. package/modules/settings/view.js +5 -3
  423. package/modules/sky/Sky.js +88 -176
  424. package/modules/sky/cascades.js +86 -25
  425. package/modules/sky/cascades.tsl.js +82 -0
  426. package/modules/sky/clouds.js +34 -19
  427. package/modules/sky/domeLayers.js +30 -15
  428. package/modules/sky/environment.js +83 -13
  429. package/modules/sky/fog.js +140 -95
  430. package/modules/sky/frame.js +112 -44
  431. package/modules/sky/look.js +22 -19
  432. package/modules/sky/lookFog.js +48 -52
  433. package/modules/sky/lookShadow.js +53 -41
  434. package/modules/sky/lookSky.js +82 -21
  435. package/modules/sky/season.js +21 -0
  436. package/modules/sky/shader.js +41 -19
  437. package/modules/sky/shadow.js +44 -20
  438. package/modules/sky/skyModule.js +45 -33
  439. package/modules/sky/tint.js +61 -0
  440. package/modules/terrain/ChunkManager.js +175 -108
  441. package/modules/terrain/chunkJob.js +1 -1
  442. package/modules/terrain/chunkQueries.js +6 -4
  443. package/modules/terrain/index.js +105 -50
  444. package/modules/terrain/look.js +83 -0
  445. package/modules/terrain/lookGround.js +21 -16
  446. package/modules/terrain/terrainDefaults.js +1 -1
  447. package/modules/terrain/terrainEdit.js +18 -20
  448. package/modules/terrain/terrainGen.js +5 -3
  449. package/modules/terrain/terrainIsland.js +5 -4
  450. package/modules/terrain/terrainShape.js +12 -12
  451. package/modules/terrain/terrainShapeMain.js +8 -7
  452. package/modules/terrain/terrainTexture.js +21 -19
  453. package/modules/timeline/Timeline.js +95 -43
  454. package/modules/timeline/Tween.js +18 -10
  455. package/modules/timeline/letterbox.js +2 -2
  456. package/modules/timeline/shots.js +5 -1
  457. package/modules/triggers/index.js +107 -76
  458. package/modules/vegetation/Vegetation.js +186 -110
  459. package/modules/vegetation/densityMap.js +62 -0
  460. package/modules/vegetation/groundChunks.js +52 -58
  461. package/modules/vegetation/index.js +32 -11
  462. package/modules/vegetation/look.js +119 -0
  463. package/modules/vegetation/lookWind.js +71 -10
  464. package/modules/vegetation/modelGeometry.js +3 -2
  465. package/modules/vegetation/nearFade.js +8 -2
  466. package/modules/water/Water.js +65 -27
  467. package/modules/water/look.js +29 -18
  468. package/modules/water/surface.js +64 -25
  469. package/modules/water/surfaceDefaults.js +3 -0
  470. package/modules/weather/Weather.js +62 -104
  471. package/modules/weather/look.js +1 -2
  472. package/modules/weather/particles.js +24 -9
  473. package/modules/weather/strings.js +2 -2
  474. package/modules/weather/weatherLook.js +135 -0
  475. package/modules/world/World.js +24 -7
  476. package/modules/world/explain.js +1 -1
  477. package/modules/world/index.js +18 -4
  478. package/modules/world/persist.js +62 -2
  479. package/modules/world/pos.js +3 -2
  480. package/modules/world/records.js +8 -6
  481. package/modules/world/sim.js +60 -20
  482. package/modules/world/simFar.js +4 -3
  483. package/modules/world/state.js +3 -2
  484. package/modules/world/thingSource.js +1 -1
  485. package/modules/world/views.js +7 -5
  486. package/package.json +7 -3
  487. package/presets.js +41 -27
  488. package/render/PostFX.js +145 -120
  489. package/render/backend.js +440 -0
  490. package/render/detail.js +120 -39
  491. package/render/effects.js +130 -38
  492. package/render/engineUniforms.js +10 -1
  493. package/render/fuse.js +5 -4
  494. package/render/fx/cloudShadow.tsl.js +16 -0
  495. package/render/fx/detail.tsl.js +66 -0
  496. package/render/fx/index.js +26 -0
  497. package/render/fx/lighting.tsl.js +28 -0
  498. package/render/fx/nodeErrors.tsl.js +68 -0
  499. package/render/fx/noise.tsl.js +12 -0
  500. package/render/fx/objectOrigin.tsl.js +42 -0
  501. package/render/fx/particles.tsl.js +139 -0
  502. package/render/fx/patchNodes.tsl.js +403 -0
  503. package/render/fx/postWebGPU.tsl.js +158 -0
  504. package/render/fx/season.tsl.js +13 -0
  505. package/render/fx/sky.tsl.js +260 -0
  506. package/render/fx/uniforms.tsl.js +67 -0
  507. package/render/fx/water.tsl.js +53 -0
  508. package/render/fx/wind.tsl.js +22 -0
  509. package/render/fxNumbers.js +36 -0
  510. package/render/hotGlsl.js +24 -0
  511. package/render/lighting.js +66 -14
  512. package/render/lights.js +223 -4
  513. package/render/lookGlow.js +139 -0
  514. package/render/lookSurface.js +99 -36
  515. package/render/materials.js +71 -52
  516. package/render/modeling.js +73 -0
  517. package/render/ownFrame.js +76 -0
  518. package/render/patches.js +311 -34
  519. package/render/postLook.js +124 -46
  520. package/render/postWebGL.js +197 -0
  521. package/render/probes.js +231 -0
  522. package/render/shaderErrors.js +154 -0
  523. package/render/slots.js +165 -0
  524. package/render/surface.js +53 -17
  525. package/render/terms.js +211 -0
  526. package/render/uniformDecl.js +3 -2
  527. package/types/common.d.ts +2 -2
  528. package/types/core.d.ts +614 -240
  529. package/types/gameplay.d.ts +482 -312
  530. package/types/generated/core/Audio.d.ts +26 -42
  531. package/types/generated/core/Batching.d.ts +6 -2
  532. package/types/generated/core/Budget.d.ts +2 -8
  533. package/types/generated/core/DebugOverrides.d.ts +44 -3
  534. package/types/generated/core/I18n.d.ts +2 -2
  535. package/types/generated/core/Input.d.ts +102 -31
  536. package/types/generated/core/Ops.d.ts +31 -0
  537. package/types/generated/core/Random.d.ts +2 -2
  538. package/types/generated/core/Saves.d.ts +10 -2
  539. package/types/generated/core/Stream.d.ts +1 -1
  540. package/types/generated/core/Threads.d.ts +4 -1
  541. package/types/generated/core/Views.d.ts +0 -1
  542. package/types/generated/core/audioVoice.d.ts +17 -9
  543. package/types/generated/core/control.d.ts +55 -0
  544. package/types/generated/core/session.d.ts +2 -1
  545. package/types/generated/modules/ambience/Ambience.d.ts +0 -9
  546. package/types/generated/modules/calendar/Calendar.d.ts +84 -0
  547. package/types/generated/modules/calendar/index.d.ts +10 -0
  548. package/types/generated/modules/debug/DebugPanel.d.ts +2 -2
  549. package/types/generated/modules/grid/Grid.d.ts +61 -25
  550. package/types/generated/modules/grid/Layer.d.ts +5 -5
  551. package/types/generated/modules/grid/index.d.ts +29 -17
  552. package/types/generated/modules/music/Music.d.ts +5 -3
  553. package/types/generated/modules/net/index.d.ts +3 -3
  554. package/types/generated/modules/net/transports.d.ts +12 -3
  555. package/types/generated/modules/particles/Particles.d.ts +1 -1
  556. package/types/generated/modules/sky/Sky.d.ts +12 -104
  557. package/types/generated/modules/sky/skyModule.d.ts +1 -1
  558. package/types/generated/modules/timeline/Timeline.d.ts +8 -6
  559. package/types/generated/modules/weather/Weather.d.ts +17 -18
  560. package/types/generated/modules/weather/weatherLook.d.ts +12 -0
  561. package/types/generated/modules/world/World.d.ts +18 -3
  562. package/types/generated/render/PostFX.d.ts +67 -30
  563. package/types/generated/render/materials.d.ts +26 -20
  564. package/types/generated/render/modeling.d.ts +30 -0
  565. package/types/generated/render/patches.d.ts +16 -2
  566. package/types/generated/ui/UI.d.ts +6 -3
  567. package/types/nav.d.ts +6 -0
  568. package/types/physics.d.ts +137 -44
  569. package/types/style.d.ts +109 -81
  570. package/types/tsl.d.ts +86 -0
  571. package/types/world.d.ts +158 -110
  572. package/ui/Focus.js +25 -14
  573. package/ui/LoadingScreen.js +1 -1
  574. package/ui/Parts.js +27 -11
  575. package/ui/UI.js +20 -10
  576. package/ui/cursor.js +115 -0
  577. package/ui/defaults.js +15 -11
  578. package/ui/theme.js +9 -6
  579. package/ui/touchPart.js +1 -1
  580. package/core/claims.js +0 -51
  581. package/core/look/layers.js +0 -136
  582. package/core/renamed.js +0 -22
  583. package/docs/api/entities.md +0 -61
  584. package/examples/styletest/overrides.js +0 -33
  585. package/examples/styletest/panel.js +0 -135
  586. package/modules/entities/Entities.js +0 -243
  587. package/modules/entities/build.js +0 -25
  588. package/modules/entities/index.js +0 -4
  589. package/modules/sky/calendar.js +0 -80
  590. package/modules/sky/layers.js +0 -69
  591. package/modules/terrain/chunkLevels.js +0 -40
  592. package/modules/terrain/mountTerrain.js +0 -32
  593. package/modules/world/cells.js +0 -42
package/core/stacks.js ADDED
@@ -0,0 +1,166 @@
1
+ // engine.stacks: the registry of every shared point (the point itself and its rules are core/sharedPoint.js). Here: define / get / mod, the timers
2
+ // behind `for`, saving entries, and describe().shared. Kept apart from sharedPoint.js only for size: the rules read without the bookkeeping between.
3
+ import { codedError } from './errorHints.js';
4
+ import { DEV, warnOnce } from './validate.js';
5
+ import { Stack } from './sharedPoint.js';
6
+
7
+ const KEYS = ['owner', 'set', 'add', 'mul', 'clamp', 'value', 'for', 'clock', 'id', 'layer'];
8
+ // Saved: engine / style / game / effect entries (what the playthrough did). Not saved: system / debug (menus, cutscenes, debug: "what the
9
+ // screen is doing now", retaken after a load), settings (the settings module re-applies the player's choices from its own prefs)
10
+ const SAVED = new Set(['engine', 'style', 'game', 'effect']);
11
+ const saved = e => SAVED.has(e.layer);
12
+
13
+ /** engine.stacks: every shared point by name; engine.mod(name, o) is the one way to change one */
14
+ export class Stacks {
15
+ constructor(engine) {
16
+ this.engine = engine;
17
+ /** @type {Map<string, Stack>} */ this._all = new Map();
18
+ /** @internal saved entries of a point the game has not defined yet: applied when it does */ this._pending = {};
19
+ this._version = 0; this._timedDirty = false;
20
+ /** @internal now on a clock ('real' or a channel); core/time.js replaces it */ this._nowOf = () => 0;
21
+ // since = game clock time of the take (engine.clock.now), not engine.time.now('real'): session.newGame resets the clock, so an entry a fresh
22
+ // playthrough makes reads the same in every new game
23
+ this._at = () => engine.clock?.now ?? 0;
24
+ this._hooked = false; this._hook();
25
+ }
26
+ /** @internal saves and world:remove. The registry is made before them (Engine.js: the look parts' points exist from the first look part on);
27
+ * createServices calls this again once saves and events exist */
28
+ _hook() {
29
+ const e = this.engine;
30
+ if (this._hooked || !e.saves || !e.events) return;
31
+ this._hooked = true;
32
+ e.saves.register('stacks', { save: () => this._save(), load: d => this._load(d) });
33
+ e.events.on('world:remove', ({ id }) => { for (const s of this._all.values()) if (s.per) s.dropId(id); });
34
+ }
35
+ /**
36
+ * Define a shared point (engine modules and games use the same call). kind: 'number' (default; base 1), 'value' (any data, set only), 'any'
37
+ * (true while held), 'top' (latest holder wins), 'one' (an exclusive slot; modules take theirs with `provides`).
38
+ * per: true = one value per record id (mod with { id }); per: 'optional' = an entry with { id } is that record's, one without is every record's
39
+ * (move.speed: haste on the player, mud on everyone). save: false keeps it out of saves (screen state like the camera holder).
40
+ * manual: the copyable takeover call the conflict error offers (a look part's manual()).
41
+ * @param {string} name @param {{ kind?: 'number' | 'value' | 'any' | 'top' | 'one', base?: any, min?: number, max?: number, per?: boolean | 'optional', save?: boolean, manual?: string, settingsSet?: boolean, onChange?: (id: string | null) => void }} [o]
42
+ * @returns {Stack}
43
+ * @example engine.stacks.define('damageTaken', { per: true, min: 0 }); engine.mod('damageTaken', { owner: 'shield', id: 'player', mul: 0.5, for: 3 });
44
+ */
45
+ define(name, o = {}) {
46
+ if (this._all.has(name)) throw codedError('mod-owner', `engine.stacks.define('${name}'): already defined; read it with engine.stacks.get('${name}')`);
47
+ const s = new Stack(this, name, o);
48
+ this._all.set(name, s);
49
+ if (this._pending[name]) { this._loadOne(s, this._pending[name]); delete this._pending[name]; }
50
+ return s;
51
+ }
52
+ /** @param {string} name @returns {Stack} */
53
+ get(name) {
54
+ const s = this._all.get(name);
55
+ if (!s) throw codedError('unknown-name', `engine.stacks: no shared point '${name}'. Known: ${[...this._all.keys()].join(', ')}. Define your own with engine.stacks.define('${name}', { base })`);
56
+ return s;
57
+ }
58
+ /** @param {string} name */
59
+ has(name) { return this._all.has(name); }
60
+ /** Names of every point */
61
+ list() { return [...this._all.keys()]; }
62
+ /**
63
+ * The one entry: change a shared point; returns a handle whose remove() ends only this owner's entry.
64
+ * @param {string} name @param {{ owner: string, set?: any, add?: number, mul?: number, clamp?: { min?: number, max?: number }, value?: any, for?: number, clock?: string, id?: string, layer?: 'engine' | 'style' | 'game' | 'effect' | 'system' | 'settings' | 'debug' }} o
65
+ * @returns {{ owner: string, remove(): void, change(value: any): boolean }} remove() ends it; change(v) rewrites its value in place (same op, layer)
66
+ */
67
+ mod(name, o) {
68
+ if (DEV) { const bad = Object.keys(o ?? {}).filter(k => !KEYS.includes(k)); if (bad.length) warnOnce(`engine.mod('${name}'): unknown option ${bad.join(', ')}; known: ${KEYS.join(', ')}`); }
69
+ return this.get(name).take(o ?? {});
70
+ }
71
+ /**
72
+ * describe().shared: one row per point that has entries (or that the engine yielded to a three.js write):
73
+ * { 'time.enemies': { value, writer, layer?, at?, how?, also: [{ owner, layer, op, value, left?, at?, hidden? }] } }.
74
+ * Per-record points show as 'move.speed[player]'; a per: 'optional' point's every-record entries as 'move.speed[*]'.
75
+ */
76
+ describe() {
77
+ const out = {};
78
+ for (const s of this._all.values()) {
79
+ if (s.per) {
80
+ for (const id of s.ids()) out[`${s.name}[${id}]`] = s.row(id);
81
+ if (s.size()) out[`${s.name}[*]`] = s.row();
82
+ } else if (s.size() || s.yielded) out[s.name] = s.row();
83
+ }
84
+ return out;
85
+ }
86
+ /**
87
+ * Everything one owner changes now, grouped the other way round from describe().shared: "what did rainyNight change?"
88
+ * @param {string} owner a module name, a game owner ('bullet-time'), 'settings', ...
89
+ * @returns {string[]} e.g. ['time.world (mul 0.8, effect)', 'inventory (holds)']
90
+ * @example engine.stacks.of('weather')
91
+ */
92
+ of(owner) {
93
+ const out = [];
94
+ for (const s of this._all.values()) for (const [id, m] of s._by) {
95
+ const e = m.get(owner);
96
+ if (e) out.push(`${id ? `${s.name}[${id}]` : s.name} (${e.op ? `${e.op} ${JSON.stringify(e.value)}, ${e.layer}` : 'holds'})`);
97
+ }
98
+ return out;
99
+ }
100
+ /** @internal entries with a `for`, as [point, entry] */
101
+ _timed() {
102
+ const out = [];
103
+ for (const s of this._all.values()) for (const m of s._by.values()) for (const e of m.values()) if (e.until != null) out.push([s, e]);
104
+ return out;
105
+ }
106
+ /**
107
+ * @internal End every entry whose time is up (core/time.js calls it after advancing the clocks), earliest first; emits mod:end for each.
108
+ * @returns {number} how many ended
109
+ */
110
+ _expire() {
111
+ if (!this._timedDirty) return 0;
112
+ const timed = this._timed();
113
+ if (!timed.length) { this._timedDirty = false; return 0; } // nothing timed: later steps return at once until the next timed mod
114
+ const due = timed.map(([s, e]) => ({ s, e, over: this._nowOf(e.clock) - e.until })).filter(d => d.over >= -1e-9);
115
+ due.sort((a, b) => b.over - a.over); // the most overdue ended first in time
116
+ for (const { s, e } of due) {
117
+ if (!s._drop(e.owner, e.id, e)) continue;
118
+ this.engine.events?.emit('mod:end', { target: s.name, owner: e.owner, id: e.id });
119
+ }
120
+ return due.length;
121
+ }
122
+ /** @internal smallest time left on any timed entry, converted to game seconds by toGame(clock, left) (engine.skip ends a segment there) */
123
+ _untilNext(toGame) {
124
+ let best = Infinity;
125
+ for (const [, e] of this._timed()) best = Math.min(best, toGame(e.clock, Math.max(0, e.until - this._nowOf(e.clock))));
126
+ return best;
127
+ }
128
+ /** @internal a channel's clock jumped by delta (a load set its now): entries timed on it keep their time left, whichever save part loaded first */
129
+ _rebase(clock, delta) { for (const [, e] of this._timed()) if (e.clock === clock) e.until += delta; }
130
+ /** @internal number and value points; entries below the settings layer */
131
+ _save() {
132
+ const out = {};
133
+ for (const s of this._all.values()) {
134
+ if (s.save === false || (s.kind !== 'number' && s.kind !== 'value')) continue;
135
+ const list = [];
136
+ for (const m of s._by.values()) for (const e of m.values()) {
137
+ if (!saved(e)) continue;
138
+ list.push({ owner: e.owner, id: e.id, op: e.op, value: e.value, layer: e.layer, clock: e.clock, left: e.until == null ? null : e.until - this._nowOf(e.clock) });
139
+ }
140
+ if (list.length) out[s.name] = list;
141
+ }
142
+ return out;
143
+ }
144
+ /** @internal a load replaces every saved (engine..effect) entry; system / settings / debug entries stay (the menu that holds them is still up) */
145
+ _load(d) {
146
+ this._pending = {};
147
+ for (const s of this._all.values()) if (s.save !== false && (s.kind === 'number' || s.kind === 'value')) this._loadOne(s, d?.[s.name] ?? []);
148
+ for (const [k, v] of Object.entries(d ?? {})) if (!this._all.has(k)) this._pending[k] = v;
149
+ }
150
+ /**
151
+ * @internal Replace s's saved entries with list. An owner that holds an entry now and also in the save keeps the SAME entry object, rewritten
152
+ * with the saved values: handles taken before the load (engine.mod, ctx.mod) still remove() / change() it. A new object here made every such
153
+ * handle stale in silence (a slow zone's time.world mul 0.5 stayed after leaving the zone).
154
+ */
155
+ _loadOne(s, list) {
156
+ const had = new Map();
157
+ for (const m of [...s._by.values()]) for (const e of [...m.values()]) if (saved(e)) { had.set(`${e.id ?? ''}\0${e.owner}`, e); s._drop(e.owner, e.id, e); }
158
+ for (const e of list) {
159
+ const m = s._map(e.id, true), clock = e.clock ?? 'real', old = had.get(`${e.id ?? ''}\0${e.owner}`);
160
+ const fields = { since: this._at(), op: e.op, value: e.value, layer: SAVED.has(e.layer) ? e.layer : 'game', clock, until: e.left == null ? null : this._nowOf(clock) + e.left };
161
+ m.set(e.owner, old ? Object.assign(old, fields) : { owner: e.owner, id: e.id ?? null, where: null, ...fields });
162
+ this._timedDirty = true;
163
+ s._changed(e.id);
164
+ }
165
+ }
166
+ }
package/core/startup.js CHANGED
@@ -3,10 +3,22 @@
3
3
  // A critical asset (manifest critical: true) that fails stops start() with the reason instead of starting a broken game.
4
4
 
5
5
  import { reportError } from './errors.js';
6
+ import { asModule } from './moduleTypes.js';
6
7
  import { catalogSnap, catalogClaim } from './catalog.js';
7
- import { codedError } from './errorHints.js';
8
+ import { codedError, coded } from './errorHints.js';
9
+ import { warnOnce, DEV_SERVER } from './validate.js';
8
10
  import { touchStart } from './inputTouch.js';
9
11
  import { Loading, failureText } from './Loading.js';
12
+ import { prepareRoomEnvironment } from '../render/lights.js';
13
+ import { startHeadlessLoad } from './headlessLoad.js';
14
+ import * as THREE from 'three';
15
+ import { isWebGPU, backendName, whyNoWebGPU, firstNodeMaterial, webglOnlyOn, tier as detectTier, timerContext, rendererSwapped, compileThrough } from '../render/backend.js';
16
+ import { bindUniforms } from '../render/engineUniforms.js';
17
+ import { nameShaderErrors } from '../render/shaderErrors.js';
18
+ import { forcedTier, defaultPixelRatio } from './tier.js';
19
+ import { GpuTimer } from './adaptive.js';
20
+ import { sceneVisitor } from './sceneDelta.js';
21
+ import { plugAtStart } from './plugins.js';
10
22
 
11
23
  const DEV_STRINGS = {
12
24
  initFailed: 'init of module {name}',
@@ -24,7 +36,7 @@ export const startupMethods = {
24
36
  get loading() { return this._loading ||= new Loading(this); },
25
37
 
26
38
  /** Start the game: init modules, preload, apply scenario parameters, wait until the world is ready. A second call returns the first call's Promise. */
27
- start() { return (this._starting ??= this._start()); },
39
+ start() { this._born.start ||= performance.now(); return (this._starting ??= this._start()); }, // measure
28
40
 
29
41
  /** @internal stop when dispose() ran during an await of start() */
30
42
  _alive(at) { if (this.disposed) throw codedError('engine-disposed', DEV_STRINGS.disposed.replace('{at}', at)); },
@@ -32,10 +44,15 @@ export const startupMethods = {
32
44
  /** @internal */
33
45
  async _start() {
34
46
  // Dev server only (npm run dev): if main.js forgot window.engine = engine, set it so the dev bridge and console can find the engine; leave an existing one alone (including tests with several engines)
35
- if (import.meta.env?.DEV && typeof window !== 'undefined' && !window.engine) window.engine = this;
47
+ if (DEV_SERVER && typeof window !== 'undefined' && !window.engine) window.engine = this;
48
+ this._alive('starting');
49
+ this.phase = 'loading'; // from here until the world is built: frame hooks only, no fixed step (loop.js)
36
50
  await this.saves.whenReady; // read the save index into memory (IndexedDB is async) so saves.list / check are synchronous afterwards
37
51
  this._alive('reading saves');
38
- this._checkOptional(); // optional dependencies that affect gameplay are missing: warn once in dev (modules.js)
52
+ await this._startRenderer(); // WebGPURenderer: init (or fall back) before anything draws or compiles; WebGL: nothing to do
53
+ plugAtStart(this); // the plugins folder: before module init, so a module from a plugin inits with the others (plugins.js)
54
+ this._alive('plugging plugins');
55
+ this._checkOptional(); // optional dependencies that affect gameplay are missing: warn once in dev (modules.js)
39
56
  if (!this.headless) this._loop();
40
57
  this.ui._check(); // a UI part name the game set but no module declared is a typo: fail now, not silently
41
58
  touchStart(this.input); // on-screen stick / buttons are a UI part too, so they are drawn only once the parts are settled
@@ -49,9 +66,11 @@ export const startupMethods = {
49
66
  const t = performance.now(); // measure
50
67
  this._setModState(m, 'initializing'); // no hooks until init succeeded (modules.js)
51
68
  const snap = catalogSnap(this); // what init registers belongs to this module in engine.catalog()
52
- try { await m.init(this); catalogClaim(this, m.name, snap); L._done(task); this._setModState(m, 'running'); }
69
+ const inst = this._modInst.get(m.name); // a plugin removed while init awaits: its completion must not touch a same-named newcomer (modules.js)
70
+ try { await asModule(this, m, () => m.init(this, this._modCtx(m, inst))); if (this._isLive(m.name, inst)) { catalogClaim(this, m.name, snap); this._setModState(m, 'running'); } L._done(task); }
53
71
  catch (e) {
54
- L._fail(task, e); this._setModState(m, 'failed');
72
+ L._fail(task, e);
73
+ if (this._isLive(m.name, inst)) { this._setModState(m, 'failed'); this._dropTracked(m.name); } // a failed module keeps no listener on half-built state
55
74
  // a critical module stops start() with the reason (below); any other failure is reported by severity and start() goes on
56
75
  if (!m.critical) reportError(this, e, DEV_STRINGS.initFailed.replace('{name}', m.name), { module: m });
57
76
  }
@@ -75,23 +94,146 @@ export const startupMethods = {
75
94
  await this._waitReady(timing, tr, ms, v => { streamMs = v; }, () => streamMs).catch(why => Array.isArray(why) ? this._blocked(why) : Promise.reject(why));
76
95
  // Compile every visible material for the current lights now, behind the loading screen, instead of stalling the first frame that shows it
77
96
  // (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"
97
+ this._checkBackendScene(); // the scene is built now: materials the chosen backend cannot draw fail by name, not as a blank picture
78
98
  const tc = performance.now(); // measure
79
- await this.renderer.compileAsync(this.scene, this.camera);
80
- const compileMs = ms(tc);
99
+ // Everything below is handed to the parallel compile together, then awaited once: the baseline room map's prefilter (if a material reads
100
+ // scene.environment; first, since the map is part of the scene's program key), the scene, and on WebGL the post chain's fullscreen passes
101
+ const room = prepareRoomEnvironment(this);
102
+ // compile for the target the scene really draws into (the composer's when post is on): see PostFX._sceneTarget.
103
+ // compile() runs synchronously inside compileAsync, so the target only needs to be set around the call, not across the await
104
+ const r = this.renderer, target = this.post._sceneTarget();
105
+ r.setRenderTarget(target);
106
+ let compiling;
107
+ try { compiling = r.compileAsync(this.scene, this.camera); } finally { r.setRenderTarget(null); }
108
+ // the chain's passes draw through three themselves, so compileAsync of the scene never sees their materials: a dry run of the chain
109
+ // (render/backend.js compileThrough) starts them now instead of one by one in the warm-up frame (~130 ms measured, nine passes).
110
+ // Not on WebGPU: its passes are nodes of one pipeline whose inner renders run only inside a real frame
111
+ const post = !this.headless && this.post.active && !isWebGPU(r) ? compileThrough(r, () => this.post.render(0)) : null;
112
+ // the page's thread is idle until the GPU is done: the one-time warm-ups modules queued run now instead of in the first frame (rigid)
113
+ for (const f of this._whileCompiling.splice(0)) { try { f(); } catch (err) { reportError(this, err, 'warm-up while compiling', { soft: true }); } }
114
+ await Promise.all([compiling, room, post]);
81
115
  this._alive('compiling shaders');
82
- this.ready = true;
116
+ // One hidden frame behind the loading screen: shadow depth materials, the post passes and the background quad are programs compileAsync
117
+ // never sees, and without this frame they compiled in the first frame the player saw (a 300 ms hitch measured)
118
+ if (!this.headless) { try { this._render(0); } catch (err) { reportError(this, err, 'render (warm-up frame)', { soft: true }); } }
119
+ const compileMs = ms(tc), tReady = performance.now(); // measure
120
+ this.phase = 'ready'; // fixed steps run from the next one on: game time starts here on every machine (loop.js)
83
121
  this.commits.rebase(); // background results registered during loading restart timing from now (see Commits.js)
84
122
  // Startup timing: totalMs from page open to playable, startMs from start() to playable
85
- this.startup = { totalMs: Math.round(performance.now()), startMs: ms(t0), preloadMs, streamMs, compileMs, modules: timing }; // measure
123
+ // firstFrameMs (page open to the end of the first frame drawn after the loading screen) and its phases, which add up to it: script (page
124
+ // open until createEngine), construct (createEngine), setup (game code until start(), installs included), init (saves, renderer, module
125
+ // init), preload, world (scenario parameters, nearby builds), compile (shaders + hidden warm-up frame), draw (ready until that frame's
126
+ // draw calls were submitted; loop.js). draw and firstFrameMs stay null until the frame, and with no real-time loop (headless)
127
+ const b = this._born, d = (a, z) => Math.round(z - a); // measure
128
+ const phases = { script: Math.round(b.at), construct: d(b.at, b.built), setup: d(b.built, b.start), init: d(b.start, tp), preload: d(tp, tr), world: d(tr, tc), compile: d(tc, tReady), draw: null };
129
+ this.startup = { totalMs: Math.round(performance.now()), startMs: ms(t0), preloadMs, streamMs, compileMs, firstFrameMs: null, phases, modules: timing }; // measure
130
+ this._readyAt = tReady;
86
131
  this.budget.checkStartup(this.startup);
87
132
  ls?.update({ progress: 1, text: '' }); ls?.hide();
88
133
  this.ops.allow(() => this.events.emit('engine:ready')); // engine:ready listeners finish setting up the game; still loading for the ops guard
89
134
  this.session._capture(); // the state engine.session.newGame() returns to: set up, nothing played yet
90
135
  this.ui.open('title'); // the title screen, only when the game turned it on (createEngine({ ui: { title: {...} } }))
91
136
  await this._urlState.late(); // scenario parameters: skip the cutscene, wait, align the time, then emit state:applied
137
+ startHeadlessLoad(this); // headless: what the game sets up after start (a species, a teleport) still loads with no step() (headlessLoad.js)
138
+ this._alive('applying scenario parameters');
139
+ this.phase = 'running';
92
140
  return this;
93
141
  },
94
142
 
143
+ /**
144
+ * @internal The WebGPU route (docs/plans/2026-11-03-webgpu-phase2.md section 1.2; Engine already checked threedog/tsl is loaded): find out
145
+ * whether WebGPU is there, then init or fall back by createEngine({ fallback }). Whatever it falls back to is said loudly and kept in
146
+ * describe().renderer. Why probe before init(): three falls back to WebGL2 silently and loses the reason, and once its WebGL2 backend took
147
+ * the canvas, fallback 'webgl' could not hand a clean canvas to WebGLRenderer.
148
+ */
149
+ async _startRenderer() {
150
+ const r = this.renderer, want = this._backendWant;
151
+ if (!isWebGPU(r)) { this._backend = { requested: 'webgl', backend: 'webgl', reason: null }; return; }
152
+ const forced = !!r.backend?.parameters?.forceWebGL; // the game asked for the WebGL2 backend itself: not a fallback
153
+ let reason = forced || (r.initialized && r.backend.isWebGPUBackend) ? null : await whyNoWebGPU();
154
+ this._alive('looking for WebGPU');
155
+ if (reason && want.fallback === 'error') {
156
+ throw codedError('renderer-backend', `[threedog] WebGPU unavailable (${reason}) and createEngine({ fallback: 'error' }) asked not to fall back; `
157
+ + "fallback: 'webgl2' runs the same renderer on WebGL2 (your TSL keeps working), 'webgl' runs WebGLRenderer (GLSL only)");
158
+ }
159
+ if (reason && want.fallback === 'webgl') this._swapToWebGL(r);
160
+ else if (!r.initialized) { await r.init(); this._alive('initializing WebGPU'); }
161
+ const backend = backendName(this.renderer);
162
+ // the probe said yes but three still fell back (a device lost in between): say so all the same
163
+ if (!forced && backend === 'webgl2') reason ??= 'three fell back to its WebGL2 backend during init()';
164
+ if (reason && want.fallback === 'error') throw codedError('renderer-backend', `[threedog] WebGPU unavailable (${reason}) and createEngine({ fallback: 'error' }) asked not to fall back`);
165
+ this._backend = { requested: 'webgpu', backend, reason: forced ? 'forceWebGL: true (asked for by the game)' : reason };
166
+ // loud on purpose: a game that chose WebGPU runs 1.5-1.9x slower on the WebGL2 backend, or without its TSL on WebGLRenderer
167
+ if (reason && !forced) warnOnce(coded('renderer-backend', `[threedog] WebGPU unavailable (${reason}), running ${backend}; createEngine({ renderer: 'webgpu', fallback: 'webgl2' | 'webgl' | 'error' })`));
168
+ // the GPU is known only now (adapterInfo after init): the default quality follows the real device
169
+ if (!(this.headless && forcedTier())) {
170
+ const t = detectTier(this.renderer);
171
+ if (t !== this.tier && this._ownsRenderer && this._createParams.pixelRatio == null) this.renderer.setPixelRatio(defaultPixelRatio(devicePixelRatio || 1, t));
172
+ // MSAA defaults from the tier too (Engine.js: antialias ?? style.antialias ?? tier !== 'low'); decided from a WebGL probe before the WebGPU
173
+ // adapter was known, so a low-tier device could keep MSAA on the WebGPU route (found by the WebGPU parity test). Untouched when the game or
174
+ // style chose, or changed it since. The renderer's own samples stay as made: the new value then runs through the post chain (PostFX active)
175
+ const aaDefault = this._createParams.antialias == null && this.style?.antialias == null && this.post.antialias === (this.tier !== 'low');
176
+ if (t !== this.tier && aaDefault) this.post.setAntialias(t !== 'low');
177
+ this.tier = t;
178
+ }
179
+ },
180
+
181
+ /**
182
+ * @internal fallback 'webgl': drop the WebGPURenderer (never initialized, so the canvas has no context yet) for a WebGLRenderer on the
183
+ * same canvas, carrying over what was already set on it (size, scale, tone, shadows, clear color) and what the engine hooked onto it.
184
+ * @param {any} old
185
+ */
186
+ _swapToWebGL(old) {
187
+ // the canvas's own MSAA as the post chain wants it, so an effect-free frame still draws straight to the canvas (PostFX active)
188
+ const r = new THREE.WebGLRenderer({ canvas: old.domElement, antialias: this.post.antialias, powerPreference: 'high-performance' });
189
+ const size = old.getSize(new THREE.Vector2());
190
+ r.setPixelRatio(old.getPixelRatio()); r.setSize(size.x, size.y, false);
191
+ r.shadowMap.enabled = old.shadowMap.enabled; r.shadowMap.type = old.shadowMap.type;
192
+ r.toneMapping = old.toneMapping; r.toneMappingExposure = old.toneMappingExposure; r.outputColorSpace = old.outputColorSpace;
193
+ r.setClearColor(old.getClearColor(new THREE.Color()), old.getClearAlpha());
194
+ r.info.autoReset = false;
195
+ nameShaderErrors(r); bindUniforms(r, this.uniforms);
196
+ try { old.dispose(); } catch { /* never initialized: nothing of it reached the GPU */ }
197
+ // owned rows name the renderer object they live on (tween exemptions, core/owned.js)
198
+ for (const row of [this._oTone, this._oPixelRatio]) if (row) row.objects = row.objects.map(o => (o === old ? r : o));
199
+ this.renderer = r;
200
+ // parts built for the old renderer before start(): the post chain (its backend and every effect's part), then whatever registered a rebuild
201
+ this.post._setBackend();
202
+ rendererSwapped(this);
203
+ if (this._gpu) this._gpu = new GpuTimer(timerContext(r));
204
+ },
205
+
206
+ /** @internal After the world is built, before compiling: what the backend in use cannot draw is an error naming it (plan section 1.3) */
207
+ _checkBackendScene() {
208
+ const b = this._backend;
209
+ if (b?.requested !== 'webgpu') return;
210
+ if (b.backend === 'webgl') {
211
+ const hit = firstNodeMaterial(this.scene);
212
+ if (hit) throw codedError('renderer-backend', `[threedog] ${hit.material.type} on ${hit.object.type} '${hit.object.name || '(unnamed)'}' is a NodeMaterial (TSL), and `
213
+ + `createEngine({ fallback: 'webgl' }) is running WebGLRenderer, which cannot draw it (WebGPU unavailable: ${b.reason}). Use fallback: 'webgl2' `
214
+ + '(the same WebGPURenderer on WebGL2: TSL keeps working), or give these objects a GLSL material too');
215
+ return;
216
+ }
217
+ // one visitor on the engine's "entered the scene" mechanism (core/sceneDelta.js): the whole scene now, then only what is added later,
218
+ // checked each frame by _checkBackendAdds; a material swapped in (mesh.material = m) counts as an add.
219
+ // shortcut: an onBeforeCompile assigned to a material already in the scene is not seen; an add after it is. Upgrade if games do that.
220
+ const found = [];
221
+ this._webglOnlyView = sceneVisitor(this.scene, { enter: o => { if (o.material) { const msg = webglOnlyOn(o); if (msg) found.push(msg); } } });
222
+ this._webglOnlyFound = found;
223
+ this._webglOnlyView.sync();
224
+ if (found.length) { const msg = found[0]; found.length = 0; throw codedError('renderer-backend', `[threedog] ${msg}`); }
225
+ },
226
+ /** @internal Per frame on the WebGPU route: what entered the scene since the last frame and will not draw there is an error naming it (reportError) */
227
+ _checkBackendAdds() {
228
+ const v = this._webglOnlyView;
229
+ if (!v) return;
230
+ v.sync();
231
+ const found = this._webglOnlyFound;
232
+ if (!found.length) return;
233
+ const msgs = found.splice(0);
234
+ for (const msg of msgs) reportError(this, codedError('renderer-backend', `[threedog] ${msg} (added after start())`), msg);
235
+ },
236
+
95
237
  /** Critical items that failed: assets, track() steps and modules declared critical: true (a non-critical module's init error goes through reportError instead) */
96
238
  _fatal() { return this.loading.list({ phase: 'failed' }).filter(t => t.critical); },
97
239
 
@@ -99,7 +241,7 @@ export const startupMethods = {
99
241
  _blocked(fatal) {
100
242
  const err = codedError(fatal.some(t => t.kind === 'module') ? 'module-critical' : 'asset-critical', DEV_STRINGS.blocked.replace('{n}', String(fatal.length)).replace('{list}', fatal.map(failureText).join('\n ')));
101
243
  this.ui.get('loading')?.update({ progress: 1, text: this.t('loading.failed', { name: fatal.map(t => t.name).join(', ') }), failed: fatal });
102
- console.error(err.message);
244
+ reportError(this, err, 'engine.start()', { soft: true }); // logged once (errors.log in dev), then start() rejects with it
103
245
  throw err;
104
246
  },
105
247
 
@@ -60,14 +60,3 @@ export class Source {
60
60
  this._settle(codedError('stream-removed', SOURCE_STRINGS.removed.replace('{name}', this.name))); // an await on whenReady never hangs
61
61
  }
62
62
  }
63
-
64
- /**
65
- * Ring of a chunk (cx, cz) from the nearest stream source, in chunk units. `centers` are the sources in chunk units ({ cx, cz, simple }); a simple
66
- * source counts as the outer ring (far look, no near detail). Shared by the terrain and vegetation chunk tables so both rings mean the same.
67
- * @internal
68
- */
69
- export function chunkRing(cx, cz, centers, viewChunks) {
70
- let r = Infinity;
71
- for (const s of centers) r = Math.min(r, Math.max(Math.abs(cx - s.cx), Math.abs(cz - s.cz), s.simple ? viewChunks : 0));
72
- return r;
73
- }
@@ -1,56 +1,64 @@
1
1
  // A style built from parts: createEngine({ style: [basePack, { sky: mySky }, toonMaterials] }) merges the parts left to right into engine.style.
2
2
  // Why parts and not one object: a look is often borrowed piecemeal (one pack's materials, another's sky, the game's own UI colors), and a
3
- // spread `{ ...basePack, sky }` loses basePack's other sky fields; a deep merge keeps them. Rules (one place; recipes/09-style-pack.md "Composing"):
3
+ // spread `{ ...basePack, sky }` loses basePack's other sky fields; a deep merge keeps them. Rules (one place; recipes/09-style.md "Composing"):
4
4
  // - parts merge left to right, later wins; nested arrays are flattened (a pack may itself be a list of parts); null / undefined / false parts are skipped
5
5
  // - plain objects ({ } literals) merge key by key, recursively: { sky: { sunSize: 600 } } changes only sunSize
6
- // - anything else replaces whole: arrays (sky.keyframes, post, terrain.steep), functions, numbers, strings, three.js objects and class instances
7
- // - a key set to undefined is ignored; a key set to null removes it (e.g. { post: null } = no post effects from earlier parts)
6
+ // - anything else replaces whole: arrays (sky.keyframes, terrain.steep), functions, numbers, strings, three.js objects and class instances
7
+ // - a key set to undefined is ignored; a key set to null removes it (e.g. { ui: null } = no UI look from earlier parts)
8
8
  // - parts are never mutated; plain objects are copied, functions and three.js objects are shared by reference
9
- // - post is the one list you often edit rather than replace: postAdd(effect) / postRemove(name) are parts that change the list built so far
9
+ // - plugins (the part's look plugins, stylePlugins below) are not merged file by file: each part's stay grouped under its name; plugins: null drops the earlier parts'
10
+ // (post effects are plugins too: one way in, look.post.add; switch one of a pack off with engine.plugins.off('<pack>/<file>') or look.post.set({ name: false }))
10
11
  // Zero cost when unused: a single object (not a list) is used as it is, engine.style === that object.
11
12
  // Looks only: a style never holds world state (water level, sea, terrain shape); checkStyleLooks throws in dev.
12
13
  import { DEV } from './validate.js';
13
14
  import { isPlainObject as plain, getPath } from './util.js';
15
+ import { codedError } from './errorHints.js';
14
16
 
15
17
 
16
- // A post edit is a function carrying this mark: mergeInto calls it with the list built so far instead of replacing the list
17
- const EDIT = Symbol('threedog.postEdit');
18
- const edit = fn => ({ post: Object.assign(fn, { [EDIT]: true }) });
18
+ /** Merge part into out. src (path -> pack label) records which part set each leaf, so describe can name the pack behind a style value */
19
+ function mergeInto(out, part, src = null, label = '', at = '') {
20
+ for (const [k, v] of Object.entries(part)) {
21
+ if (v === undefined) continue;
22
+ const path = at + k;
23
+ if (v === null) { delete out[k]; if (src) for (const p of [...src.keys()]) if (p === path || p.startsWith(path + '.')) src.delete(p); }
24
+ else if (plain(v)) out[k] = mergeInto(plain(out[k]) ? out[k] : {}, v, src, label, path + '.');
25
+ else { out[k] = v; src?.set(path, label); }
26
+ }
27
+ return out;
28
+ }
19
29
 
30
+ // style object -> Map(path -> label of the part that set it), only for a style merged from several parts (one object has one source: itself)
31
+ const SOURCES = new WeakMap();
32
+ /** A part's name in describe: its own name field (packs set one), else its place in the list */
33
+ const partLabel = (part, i) => typeof part.name === 'string' && part.name ? part.name : `style[${i}]`;
20
34
  /**
21
- * A style part that adds post effects to the ones before it (a plain { post: [...] } would replace the whole list). An effect with the same name as
22
- * an earlier one replaces it in place; names are the effects' own ('bloom', 'ao', 'outline', or your own).
23
- * @example createEngine({ style: [basePack, postAdd(myGrain, bloom({ strength: 0.6 }))] }) // grain added, the pack's bloom swapped for yours
24
- * @param {...import('../render/PostFX.js').PostEffect} effects
25
- * @returns {{ post: any }}
35
+ * Which style part set the value a look key shows, when engine.style was merged from several: the merged path whose last segment is the key's
36
+ * last segment and whose value is that value. null when the style is one object, or when no path (or more than one pack) matches.
37
+ * @param {any} style engine.style @param {string} key a look part's flat key ('far', 'sun.intensity') @param {any} value the style layer's value
38
+ * @internal
26
39
  */
27
- export function postAdd(...effects) {
28
- return edit(list => {
29
- const out = [...(list ?? [])];
30
- for (const e of effects) { const i = out.findIndex(o => o.name === e.name); if (i >= 0) out[i] = e; else out.push(e); }
31
- return out;
32
- });
40
+ export function stylePackOf(style, key, value) {
41
+ const src = style && SOURCES.get(style);
42
+ if (!src) return null;
43
+ const last = key.split('.').at(-1), found = new Set();
44
+ for (const [path, label] of src) if (path.split('.').at(-1) === last && getPath(style, path) === value) found.add(label);
45
+ return found.size === 1 ? [...found][0] : null;
33
46
  }
34
47
 
48
+ // merged style object -> [{ group, files }]: the plugins of each part, in part order (a single style object reads its own `plugins` field)
49
+ const PLUGINS = new WeakMap();
50
+ const checkPlugins = files => {
51
+ if (!plain(files)) throw codedError('style-value', `style.plugins is what engine.plugins.add takes: import.meta.glob('./plugins/*.js', { eager: true }) or { name: { default: value } }; got ${Array.isArray(files) ? 'an array' : typeof files}`);
52
+ return files;
53
+ };
35
54
  /**
36
- * A style part that removes post effects by name from the ones before it.
37
- * @example createEngine({ style: [basePack, postRemove('ao', 'outline')] })
38
- * @param {...string} names
39
- * @returns {{ post: any }}
55
+ * The look plugins a style brings, grouped by the pack that brought them: engine.plugins plugs them (core/plugins.js), the same path as the
56
+ * game's plugins/ folder. Why grouped: a style is one folder, so it is plugged and taken out as one (engine.plugins.off('<pack name>')).
57
+ * @param {any} style engine.style @returns {{ group: string, files: Record<string, any> }[]} @internal
40
58
  */
41
- export function postRemove(...names) {
42
- return edit(list => (list ?? []).filter(e => !names.includes(e.name)));
43
- }
44
-
45
- function mergeInto(out, part) {
46
- for (const [k, v] of Object.entries(part)) {
47
- if (v === undefined) continue;
48
- if (v?.[EDIT]) out[k] = v(out[k]);
49
- else if (v === null) delete out[k];
50
- else if (plain(v)) out[k] = mergeInto(plain(out[k]) ? out[k] : {}, v);
51
- else out[k] = v;
52
- }
53
- return out;
59
+ export function stylePlugins(style) {
60
+ if (PLUGINS.has(style)) return PLUGINS.get(style);
61
+ return style?.plugins ? [{ group: typeof style.name === 'string' && style.name ? style.name : 'style', files: checkPlugins(style.plugins) }] : [];
54
62
  }
55
63
 
56
64
  /**
@@ -63,13 +71,21 @@ export function styleFrom(style) {
63
71
  let out = style ?? {};
64
72
  if (Array.isArray(style)) {
65
73
  out = {};
66
- for (const part of style.flat(Infinity)) {
67
- if (!part) continue;
68
- if (!plain(part)) throw new Error(`createEngine({ style: [...] }): each part must be a plain object (a style pack or { key: value }), got ${typeof part}`);
74
+ const src = new Map();
75
+ const plugins = [];
76
+ style.flat(Infinity).forEach((part, i) => {
77
+ if (!part) return;
78
+ if (!plain(part)) throw codedError('style-value', `createEngine({ style: [...] }): each part must be a plain object (a style or { key: value }), got ${typeof part}`);
79
+ // each part's plugins stay grouped under that part's name (not merged file by file), so off('<pack>') takes out exactly that pack's
80
+ const { plugins: own, ...rest } = part;
81
+ if (own === null) plugins.length = 0;
82
+ else if (own !== undefined) plugins.push({ group: partLabel(part, i), files: checkPlugins(own) });
69
83
  // copy the part's plain objects too, so a later part never writes into an earlier pack
70
- mergeInto(out, part);
71
- }
72
- }
84
+ mergeInto(out, rest, src, partLabel(part, i));
85
+ });
86
+ SOURCES.set(out, src);
87
+ PLUGINS.set(out, plugins);
88
+ } else if (out.plugins != null) checkPlugins(out.plugins); // a wrong shape fails at createEngine, not at start
73
89
  if (DEV) checkStyleLooks(out);
74
90
  return out;
75
91
  }
@@ -86,13 +102,13 @@ function checkStyleLooks(style) {
86
102
  const obj = getPath(style, path);
87
103
  if (!obj || typeof obj !== 'object') continue;
88
104
  for (const k of Object.keys(obj))
89
- if (isWorld(k)) throw new Error(`style.${path}.${k} is world state, not a look: swapping the style would change the map or the rules. Set it where the world is made: ${where}`);
105
+ if (isWorld(k)) throw codedError('style-value', `style.${path}.${k} is world state, not a look: swapping the style would change the map or the rules. Set it where the world is made: ${where}`);
90
106
  }
91
107
  }
92
108
 
93
- // Dev warning when createEngine gets no style pack (shown once from Engine.js)
94
- export const NO_STYLE = 'createEngine(): the style pack is missing or empty, so everything is a neutral gray placeholder: plain lights (one white hemisphere + one neutral '
95
- + 'directional light, no shadows, no tone mapping), gray background, ground, capsule characters and box props. This is not a look and not an error. '
96
- + 'Fill your own pack (style/index.js in a new game; recipes/09-style-pack.md, recipes/52-look.md) or pass a published one';
109
+ // Dev warning when createEngine gets no style (shown once from Engine.js)
110
+ export const NO_STYLE = 'createEngine(): the style is missing or empty, so everything is a neutral gray placeholder on a technical render baseline (AgX tone mapping, '
111
+ + 'soft sun shadows, a generated neutral room environment, white hemisphere + sun; see describe().look.tone / .lights), gray background, ground, capsule characters and box props. Not an error, but the game has no look yet: '
112
+ + 'making the art is part of building the game. Fill your own style (style/index.js in a new game; recipes/09-style.md, recipes/52-look.md)';
97
113
  /** true when createEngine got no style, or only empty parts ({} / [{}, {}]): the game has no look yet */
98
- export const styleIsEmpty = st => !st || (Array.isArray(st) ? st.every(styleIsEmpty) : typeof st === 'object' && Object.keys(st).every(k => k === 'name')); // a name alone (the new-game empty pack) is still empty
114
+ export const styleIsEmpty = st => !st || (Array.isArray(st) ? st.every(styleIsEmpty) : typeof st === 'object' && Object.keys(st).every(k => k === 'name')); // a name alone (the new-game empty style) is still empty
package/core/targeting.js CHANGED
@@ -10,7 +10,7 @@ const yawOf = view => typeof view === 'number' ? view : Math.atan2(view.x, view.
10
10
  /** Candidate position: an Object3D / NPC / Character / world record has .position; a Vector3 / { x, z } / [x, y, z] is the position itself */
11
11
  const posOf = c => c.position ?? c;
12
12
  function check(fn, opts) {
13
- if ('range' in opts) throw codedError('unknown-option', `${fn}(): the distance option is radius (meters), as in entities.nearest / world.query: write { radius: ${opts.range} }`);
13
+ if ('range' in opts) throw codedError('unknown-option', `${fn}(): the distance option is radius (meters), as in world.query: write { radius: ${opts.range} }`);
14
14
  for (const k of Object.keys(opts)) if (!KEYS.includes(k)) throw codedError('unknown-option', `${fn}(): unknown option '${k}'; available: ${KEYS.join(', ')}`);
15
15
  }
16
16
 
@@ -0,0 +1,20 @@
1
+ // Estimated GPU bytes of a three.js texture (engine.inspect.materials / engine.inspect.perf). An estimate: three.js does not report VRAM.
2
+ // Compressed / data textures: their data size; images: width x height x bytes per texel, x 4/3 with mipmaps, x 6 for a cube.
3
+ const PER_CHANNEL = { 1009: 1, 1010: 1, 1011: 2, 1012: 2, 1013: 4, 1014: 4, 1015: 4, 1016: 2 }; // three's type constants UnsignedByte ... HalfFloat
4
+ const CHANNELS = { 1021: 1, 1022: 3, 1023: 4, 1024: 1, 1025: 2, 1028: 1, 1030: 2, 1033: 4 }; // Alpha, RGB, RGBA, Luminance, LuminanceAlpha, Red, RG, RGBAInteger
5
+
6
+ /** @param {any} t a THREE.Texture @returns {number} estimated bytes on the GPU (0 when unknown) */
7
+ export function textureBytes(t) {
8
+ if (!t) return 0;
9
+ if (t.isCompressedTexture) return (t.mipmaps || []).reduce((s, m) => s + (m?.data?.byteLength ?? 0), 0) * (t.isCubeTexture ? 6 : 1);
10
+ const faces = Array.isArray(t.image) ? t.image : [t.image];
11
+ const i = faces[0];
12
+ if (!i) return 0;
13
+ const w = i.width ?? i.videoWidth ?? 0, h = i.height ?? i.videoHeight ?? 0, d = i.depth ?? 1;
14
+ const texel = (PER_CHANNEL[t.type] ?? 1) * (CHANNELS[t.format] ?? 4);
15
+ const mips = t.generateMipmaps !== false && t.minFilter !== 1006 && t.minFilter !== 1003 ? 4 / 3 : 1; // Linear / Nearest min filter: no mip chain
16
+ return Math.round(w * h * d * texel * mips * faces.length);
17
+ }
18
+
19
+ /** Bytes as a short MB / KB string @param {number} b */
20
+ export const mb = b => b >= 1048576 ? `${(b / 1048576).toFixed(1)} MB` : `${Math.round(b / 1024)} KB`;
@@ -2,9 +2,9 @@
2
2
  // Why one object: an AI asked "why is this crate here, blocking me, and how do I change it?" otherwise joins thing(), world.origin, material info, the
3
3
  // template, collision settings and the op list by hand. Each part reads an existing source; nothing here is stored or changes any state.
4
4
  import { materialInfo } from './MaterialInfo.js';
5
+ import { orNull } from './util.js';
5
6
 
6
7
  const MAT_MAX = 8;
7
- const safe = f => { try { return f(); } catch { return null; } };
8
8
 
9
9
  /** Unique materials under obj with role / name / where the spec came from */
10
10
  function materialsOf(obj) {
@@ -63,6 +63,6 @@ export function explainThing(e, t) {
63
63
  };
64
64
  // Explain contributions (arch #6): a module that owns records or templates adds to the object with e._things.explainers.push((e, t, out) => { ... }),
65
65
  // so core never reads their shapes. A throwing explainer is skipped: explain is a diagnostic and must not fail because of one part.
66
- for (const f of T.explainers) safe(() => f(e, t, out));
66
+ for (const f of T.explainers) orNull(() => f(e, t, out));
67
67
  return out;
68
68
  }