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
@@ -27,6 +27,7 @@ import { sectionsOf } from '../../core/base/sections.js';
27
27
  import { addProps, needWorld } from './props.js';
28
28
  import { templateOf, spawnTemplate, placeTemplate, defineTemplates } from './templates.js';
29
29
  import { refit } from './models.js';
30
+ import { holdProtos } from '../../core/assets/namedModel.js';
30
31
  import { packsOf } from './packs.js';
31
32
  import { IdCheck } from './ids.js';
32
33
  import { fieldsOf } from './fields.js';
@@ -221,8 +222,9 @@ export function content() {
221
222
  install(engine, ctx) { engine.i18n.add({ 'zh-CN': { 'module.content': '内容' }, en: { 'module.content': 'content' } });
222
223
  const e = st.e = engine;
223
224
  st.track = ctx.track; // templates.js subscribes on content.load: those listeners belong to the module too
225
+ ctx.track(holdProtos(e, api)); // the model prototypes its props and templates clone (namedModel.js): unloading content gives them back
224
226
  ctx.things.explainWith(contentExplain);
225
- ctx.saves.register('content', { ...marksPart(api, st), atomic: true });
227
+ ctx.saves.define('content', { ...marksPart(api, st), atomic: true });
226
228
  for (const holder of ['collision', 'collider3d']) ctx.feeds(holder, () => refit(e));
227
229
  ctx.track(e.events.on('engine:ready', () => { checkOps(e, st); checkRefs(st); }));
228
230
  ctx.track(e.events.on('module:restored', ({ modules }) => api._replay(modules)));
@@ -116,7 +116,7 @@ function loadSteps(e, api, c, st) {
116
116
  // game kinds stay registered across loads, so a later content.load({ recipes }) without rules still finds them
117
117
  if (c.rules) steps.push({ commit() { each(c.rules.conditions, (name, d) => api.condition(name, d)); Object.assign(st.kinds, c.rules.kinds); } });
118
118
  // a pack's actions are the game's own (owner 'game'): loading the pack again replaces them, it is not a second binder
119
- if (c.actions) steps.push({ undo: () => e.input.keepActions(Object.keys(c.actions)), commit: () => each(c.actions, (name, a) => e.input.action(name, { label: a.label, keys: a.keys, ...(a.context ? { context: a.context } : {}) })) });
119
+ if (c.actions) steps.push({ undo: () => e.input.keepActions(Object.keys(c.actions)), commit: () => each(c.actions, (name, a) => e.input.define(name, { label: a.label, keys: a.keys, ...(a.context ? { context: a.context } : {}) })) });
120
120
  // audio: sounds / footsteps by name into engine.audio.config, rules to ambience() / music() (core/audio/audioRules.js). A pack loaded again
121
121
  // replaces its own rules (hot reload): a named pack by its name, an unnamed one by the data object itself, so loading the same object
122
122
  // twice never stacks its rules (a fresh key per load did); two different unnamed objects both keep theirs
@@ -1,35 +1,60 @@
1
1
  // Models of placed content records: clone the shared prototype of a model name (core/assets/namedModel.js protoOf, the one path every system uses),
2
2
  // align it and its collision to the record (props and template instances).
3
3
  import * as THREE from 'three';
4
- import { codedError } from '../../core/base/errorHints.js';
5
- import { protoOf } from '../../core/assets/namedModel.js';
4
+ import { codedError, coded } from '../../core/base/errorHints.js';
5
+ import { warnOnce } from '../../core/base/validate.js';
6
+ import { protoOf, copyLeft, protoLease } from '../../core/assets/namedModel.js';
6
7
  import { wrapLod } from '../../core/assets/assetLod.js';
7
8
  import { Vector3 } from 'three';
8
- import { clone as skeletonClone } from 'three/addons/utils/SkeletonUtils.js';
9
+ import { cloneModel } from '../../core/base/freeParts.js';
9
10
  import { list } from '../../core/base/util.js';
11
+ import { rotOf, scaleOf } from '../../core/base/math.js';
12
+ import { isTilted, layerIgnored } from './rules.js';
10
13
 
11
14
  const BASE_BAND = 0.2; // the share of the model's height above the ground that counts as its base
12
15
 
13
16
  /**
14
- * Where a model stands, in model space, measured once per prototype: { x, z } centre and width of the base (its larger side, so a plain box keeps the same radius).
17
+ * Every part with geometry under a model root, with its matrix in model space: frame (the root's own matrix as built) times the local matrices down to the part.
18
+ * Why local matrices and not matrixWorld: a copy already placed (a hot swap measures it again) is measured as built, and two copies of the same parts give the
19
+ * very same numbers, which is what baseOf's cache keys on. A LOD's low levels are left out: they only stand in on screen, collision is the full model's. @internal
20
+ */
21
+ function partsOf(root, frame) {
22
+ const out = [];
23
+ const walk = (o, m) => {
24
+ if (o.userData.lodLevel) return;
25
+ if (o.geometry?.attributes?.position) out.push({ o, m });
26
+ for (const c of o.children) { if (c.matrixAutoUpdate) c.updateMatrix(); walk(c, m.clone().multiply(c.matrix)); }
27
+ };
28
+ walk(root, frame);
29
+ return out;
30
+ }
31
+
32
+ /**
33
+ * Where a model stands, in model space: { x, z } centre and width of the base (its larger side, so a plain box keeps the same radius). Takes a prototype or a
34
+ * prepared copy's measure (measureOf), and only a circle collider asks, so box colliders and props without one never walk triangles.
15
35
  * Why this measure: the base is the geometry in the lowest fifth of the height above y = 0 (above its lowest point when it floats), clipped from the triangles, because a crown or an arm starts higher, a tall box has no vertex halfway up and a boulder's belly is what walkers hit.
16
- * @internal
36
+ * Cached per prototype by the parts themselves (geometry and matrix): copies whose setup only swapped materials share the prototype's base, while a setup that
37
+ * thickened the trunk under the same crown gets its own. Overall bounds would not tell those two apart. @internal
17
38
  */
18
- export function baseOf(proto) {
19
- if (proto.base) return proto.base;
39
+ export function baseOf(m) {
40
+ if (m.base) return m.base;
41
+ if (!m.parts) { m.obj.updateMatrix(); m.parts = partsOf(m.obj, m.obj.matrix.clone()); } // a prototype: never placed, its root matrix is its frame
42
+ const cache = ((m.owner ?? m).bases ??= new Map());
43
+ // an instanced part falls back to its own instances' bounds, which its geometry does not name: such a part is not shared
44
+ const key = m.parts.map(({ o, m: at }) => (o.isInstancedMesh || o.isBatchedMesh ? `own${o.id}` : o.geometry.id) + ':' + at.elements.join(',')).join('|');
45
+ if (cache.has(key)) return m.base = cache.get(key);
20
46
  const meshes = [], p = new Vector3();
21
47
  let bottom = Infinity, top = -Infinity, instanced = false;
22
- proto.obj.updateMatrixWorld(true);
23
- proto.obj.traverse(m => {
24
- if (!m.isMesh || !m.geometry?.attributes.position) return;
25
- instanced ||= !!(m.isInstancedMesh || m.isBatchedMesh);
26
- const pos = m.geometry.attributes.position, at = new Float32Array(pos.count * 3);
48
+ for (const { o, m: at } of m.parts) {
49
+ if (!o.isMesh) continue;
50
+ instanced ||= !!(o.isInstancedMesh || o.isBatchedMesh);
51
+ const pos = o.geometry.attributes.position, xyz = new Float32Array(pos.count * 3);
27
52
  for (let i = 0; i < pos.count; i++) {
28
- p.fromBufferAttribute(pos, i).applyMatrix4(m.matrixWorld).toArray(at, i * 3);
53
+ p.fromBufferAttribute(pos, i).applyMatrix4(at).toArray(xyz, i * 3);
29
54
  bottom = Math.min(bottom, p.y); top = Math.max(top, p.y);
30
55
  }
31
- meshes.push({ at, index: m.geometry.index });
32
- });
56
+ meshes.push({ at: xyz, index: o.geometry.index });
57
+ }
33
58
  const low = top > 0 ? Math.max(bottom, 0) : bottom, high = low + (top - low) * BASE_BAND;
34
59
  let x0 = Infinity, x1 = -Infinity, z0 = Infinity, z1 = -Infinity;
35
60
  const take = (x, z) => { x0 = Math.min(x0, x); x1 = Math.max(x1, x); z0 = Math.min(z0, z); z1 = Math.max(z1, z); };
@@ -43,9 +68,11 @@ export function baseOf(proto) {
43
68
  for (let i = 0; i + 2 < n; i += 3) { const a = v(i), b = v(i + 1), c = v(i + 2); edge(at, a, b); edge(at, b, c); edge(at, c, a); }
44
69
  }
45
70
  // shortcut: instanced parts and models without triangles (points, lines, sprites) use the bounding box; measure their instances if a prop ever needs it
46
- const { size, center } = proto;
47
- return proto.base = instanced || x0 > x1 ? { x: center.x, z: center.z, width: Math.max(size.x, size.z) }
71
+ const { size, center } = m;
72
+ m.base = instanced || x0 > x1 ? { x: center.x, z: center.z, width: Math.max(size.x, size.z) }
48
73
  : { x: (x0 + x1) / 2, z: (z0 + z1) / 2, width: Math.max(x1 - x0, z1 - z0) };
74
+ cache.set(key, m.base);
75
+ return m.base;
49
76
  }
50
77
 
51
78
  /**
@@ -68,28 +95,28 @@ export function settle(e, rec, o, solid, mul = 1) {
68
95
  for (const h of ud.colliders.splice(0)) h.remove();
69
96
  // a solid prop blocks the camera with its whole mesh, not only its footprint collider: crowns and eaves stand outside the footprint, and no game code should have to say so
70
97
  const blocks = !!solid.collide && solid.collide.occluder !== false && solid.occluder !== false;
71
- if (solid.static !== false && e.rays) { o.updateMatrixWorld(true); ud.unstatic = e.rays.addStatic(o, { occluder: blocks }); }
98
+ if (solid.static !== false && e.rays) { o.updateMatrixWorld(true); ud.unstatic = e.assets.addStatic(o, { occluder: blocks }); }
72
99
  if (!solid.collide) return;
73
- const { collide } = solid, set = typeof collide === 'object' ? collide : null, base = set || collide === 'circle' ? baseOf(ud.proto) : null;
74
- const size = ud.proto.size.clone().multiply(new THREE.Vector3(...sv));
100
+ const { collide } = solid, set = typeof collide === 'object' ? collide : null, base = set?.circle !== undefined || collide === 'circle' ? baseOf(ud.measure) : null, layer = set?.layer;
101
+ const size = ud.measure.size.clone().multiply(new THREE.Vector3(...sv));
102
+ // a turned-over solid is held by collider3d, which has no layers: said once, and the prop stops every mover (a world.set that tilts it must not throw mid-game)
103
+ const lost = layerIgnored(rec, collide);
104
+ if (lost) warnOnce(coded('content-layer-ignored', `prop ${JSON.stringify(rec.id ?? rec.model)}: ${lost}`), 'content-layer:' + (rec.id ?? rec.model));
75
105
  if (tilted) { // a turned-over solid is not a footprint on the ground: the three-axis provider holds it (o.quaternion carries the same turn the model has)
76
- const mid = ud.proto.center.clone().multiply(new THREE.Vector3(...sv)).applyQuaternion(o.quaternion).add(o.position);
106
+ const mid = ud.measure.center.clone().multiply(new THREE.Vector3(...sv)).applyQuaternion(o.quaternion).add(o.position);
77
107
  ud.colliders.push(e.collider3d.addSolid(base
78
108
  ? { position: [mid.x, mid.y, mid.z], radius: (set?.circle ?? base.width / 2) * Math.max(sv[0], sv[2]) }
79
109
  : { position: [mid.x, mid.y, mid.z], size: [size.x, size.y, size.z], rotation: rot }));
80
110
  return;
81
111
  }
82
112
  if (!e.collision) return;
83
- const c = base ?? ud.proto.center, ox = c.x * sv[0], oz = c.z * sv[2];
113
+ const c = base ?? ud.measure.center, ox = c.x * sv[0], oz = c.z * sv[2];
84
114
  const cx = x + ox * Math.cos(rot[1]) + oz * Math.sin(rot[1]), cz = z - ox * Math.sin(rot[1]) + oz * Math.cos(rot[1]);
85
115
  ud.colliders.push(base
86
- ? e.collision.addCircle({ x: cx, z: cz }, { radius: (set?.circle ?? base.width / 2) * Math.max(sv[0], sv[2]), height: size.y, occluder: blocks })
87
- : e.collision.addBox({ x: cx, z: cz }, { halfWidth: size.x / 2, halfDepth: size.z / 2, rotation: rot[1], height: size.y, occluder: blocks }));
116
+ ? e.collision.addCircle({ x: cx, z: cz }, { radius: (set?.circle ?? base.width / 2) * Math.max(sv[0], sv[2]), height: size.y, occluder: blocks, layer })
117
+ : e.collision.addBox({ x: cx, z: cz }, { halfWidth: size.x / 2, halfDepth: size.z / 2, rotation: rot[1], height: size.y, occluder: blocks, layer }));
88
118
  }
89
119
  /** Is the model still as settle aligned it, with its collider in the holder installed now (a new one starts empty; with none there is nothing to do yet)? update asks every frame for every built prop, because world.move sends no event @internal */
90
- /** rot / scale of a record as [x, y, z]: a number is the facing about Y and a uniform scale, as it always was; an array sets each axis (the model's Euler order XYZ) */
91
- export const rotOf = rec => Array.isArray(rec.rot) ? rec.rot : [0, rec.rot ?? 0, 0];
92
- export const scaleOf = (rec, mul = 1) => (Array.isArray(rec.scale) ? rec.scale : [rec.scale ?? 1, rec.scale ?? 1, rec.scale ?? 1]).map(v => v * mul);
93
120
  const fitOf = (rec, mul) => JSON.stringify([rec.position.x, rec.position.z, rec.ground === false ? rec.position.y : null, rotOf(rec), scaleOf(rec, mul)]);
94
121
  export const fits = (e, o, rec, mul = 1) => { const h = holderOf(e, rec); return (!h || o.userData.holder === h) && o.userData.fit === fitOf(rec, mul); };
95
122
  const shapeOf = (rec, mul) => JSON.stringify([rotOf(rec), scaleOf(rec, mul)]);
@@ -97,26 +124,48 @@ const shapeOf = (rec, mul) => JSON.stringify([rotOf(rec), scaleOf(rec, mul)]);
97
124
  export const fitsShape = (o, rec, mul = 1) => o.userData.shape === shapeOf(rec, mul);
98
125
  /** A tilted solid needs the three-axis provider (collider3d); the same error at load (props.js) and at build, so a mistake shows once, early @internal */
99
126
  export const tiltError = rec => codedError('content-misuse', `prop ${JSON.stringify(rec.id ?? rec.model)}: collide on a model turned about x or z (rot ${JSON.stringify(rec.rot)}) needs a collider3d provider: install rigid() (or your own collider3d), or set collide: false`);
100
- export const isTilted = rec => { const r = rotOf(rec); return !!(r[0] || r[2]); };
101
127
  const holderOf = (e, rec) => isTilted(rec) ? e.collider3d : e.collision;
102
128
 
103
129
  /** Clone the shared prototype of a model for one record and align it (props and template instances). skeletonClone: a skinned part of a plain clone keeps the prototype's bones and draws where they stand @internal */
104
130
  export async function buildModel(e, api, rec, model, solid, mul = 1) {
105
131
  const proto = await protoOf(e, api, model), name = list(model)[0], lod = rec.lod ?? solid.lod;
106
- // settle below measures proto, never o, so collision stays the full model's; the record keeps only the word `lod`, so a save holds no level
107
- const o = lod ? await wrapLod(e.assets, name, skeletonClone(proto.obj), { distances: Array.isArray(lod) ? lod : undefined, scale: Math.max(...scaleOf(rec, mul)) }) : skeletonClone(proto.obj);
132
+ // the record keeps only the word `lod`, so a save holds no level
133
+ const lease = protoLease(e, proto, `content:${rec.id ?? name}`); // at clone time, before any wait: a hot swap during the LOD wait retires the prototype's own lease
134
+ try {
135
+ const o = lod ? await wrapLod(e.assets, name, cloneModel(proto.obj), { distances: Array.isArray(lod) ? lod : undefined, scale: Math.max(...scaleOf(rec, mul)) }) : cloneModel(proto.obj);
108
136
  o.name ||= name; o.userData.name ??= name;
137
+ // one order: copy, the game's setup, measure, then settle registers rays and colliders. A setup that throws gives back what the copy took (Assets.handOut)
138
+ e.assets.handOut(o, name);
139
+ o.updateMatrix();
140
+ const frame = o.matrix.clone(); // before settle places it: what the parts are measured in, now and after a hot swap
109
141
  o.userData.proto = proto; o.userData.colliders = [];
142
+ // a hot swap gives the copy new parts and a new prototype (core/assets/assetHot.js): measured again by this same rule, and the next align reads it
143
+ (o.userData.remeasure = () => { o.userData.measure = measureOf(e, o.userData.proto, o, frame); })();
110
144
  o.userData.refit = r => { if (!solid.body && !fits(e, o, r, mul)) settle(e, r, o, solid, mul); }; // a body places itself; a stale solid or mul is put right by the presenter's next update
111
145
  // a file model only: a generator's prototype is pinned for good (Assets.cached), so nothing could free it. The built prop counts in describe().assets until it is torn down
112
- if (!e.assets.builder(name)) o.userData.lease = await e.assets.lease(name);
146
+ o.userData.lease = lease;
113
147
  if (rec.batch === false) o.userData.batch = false; // opt out of engine.batching for this record
114
148
  o.position.set(rec.position.x, 0, rec.position.z); // world puts the model on the record after build; height and collision are aligned here
115
149
  settle(e, rec, o, solid, mul);
116
150
  return o;
151
+ } catch (err) { lease?.remove(); throw err; } // a build that fails gives the lease back (handOut gave back the copy's own)
117
152
  }
118
153
  /** ctx.feeds: every built solid goes into the holder installed now, so the line after use() reads it. The presenters' update asks the same every frame, for what moved @internal */
119
154
  export const refit = e => { for (const rec of e.world?.query({}) ?? []) e.world.view(rec.id)?.userData.refit?.(rec); };
120
155
 
121
- /** Tear down only: geometry and material belong to the shared prototype, the next build clones it again @internal */
122
- export function unbuildModel(e, o) { o.userData.lease?.remove(); o.userData.unstatic?.remove(); for (const h of o.userData.colliders) h.remove(); o.removeFromParent(); }
156
+ /**
157
+ * What collision and bodies measure for one built copy: { obj, size, center } like a prototype, so baseOf takes either. The prototype when no setup ran on the
158
+ * copy; else the copy as prepared, from its parts (partsOf: as built whatever its place now, never a LOD's low levels, so collision is the same with lod on or
159
+ * off). Only the bounds here, cheap (each geometry's own box); the base waits for a circle collider (baseOf). frame: the root's matrix as built (a LOD's is identity) @internal
160
+ */
161
+ function measureOf(e, proto, o, frame) {
162
+ if (!e.assets.prepared(o)) return proto;
163
+ const parts = partsOf(o, frame), box = new THREE.Box3(), b = new THREE.Box3();
164
+ // the box three's Box3.setFromObject takes (protoOf measures the prototype with it): an instanced or skinned part's own, else its geometry's
165
+ const own = x => x.boundingBox ?? (x.computeBoundingBox(), x.boundingBox);
166
+ for (const { o: p, m } of parts) box.union(b.copy(p.boundingBox !== undefined ? own(p) : own(p.geometry)).applyMatrix4(m));
167
+ return { obj: o, parts, owner: proto, size: box.getSize(new THREE.Vector3()), center: box.getCenter(new THREE.Vector3()) };
168
+ }
169
+
170
+ /** Tear down only: geometry and material belong to the shared prototype, the next build clones it again; dropCopy gives back what the copy itself took (LOD levels' leases, Animators, bones) @internal */
171
+ export function unbuildModel(e, o) { o.userData.lease?.remove(); o.userData.unstatic?.remove(); for (const h of o.userData.colliders) h.remove(); o.removeFromParent(); e.assets.dropCopy(o); copyLeft(e); } // copyLeft: a retired prototype's material this copy drew may go now
@@ -17,7 +17,8 @@ import { buildModel, settle, fits, unbuildModel } from './models.js';
17
17
  import { placeTemplate } from './templates.js';
18
18
  import { srcOf } from './ids.js';
19
19
  import { placeY } from '../../core/scene/ground.js';
20
- import { isTilted, tiltError } from './models.js';
20
+ import { tiltError } from './models.js';
21
+ import { isTilted } from './rules.js';
21
22
  import { PLACEMENT_FIELDS, collideProblem } from './rules.js';
22
23
  import { list } from '../../core/base/util.js';
23
24
  import { DEV, fmt, closest } from '../../core/base/validate.js';
@@ -79,7 +79,7 @@ const RULE_STRINGS = {
79
79
  id: { type: 'string', optional: true, desc: 'stable id (needed when entries are later inserted in the middle)' },
80
80
  model: { type: 'any', desc: "model name, or [name, ...args] for a generated model" }, ...at, ...pose, ...copied,
81
81
  ground: { type: 'bool', optional: true, desc: 'false = do not snap to the ground: y is the height in the world' },
82
- collide: { label: 'Collision', rare: true, type: 'any', optional: true, desc: "collision: 'box', 'circle', { circle: radius, occluder?: false }, or false = none" },
82
+ collide: { label: 'Collision', rare: true, type: 'any', optional: true, desc: "collision: 'box', 'circle', { circle?: radius, occluder?: false, layer?: 'gate' } (layer: characters with passes: ['gate'] walk through), or false = none" },
83
83
  occluder: { label: 'Blocks camera', rare: true, type: 'bool', optional: true, desc: 'false = a solid prop the follow camera may pass through (walkers are still stopped)' },
84
84
  static: { label: 'Never moves', rare: true, type: 'bool', optional: true, desc: 'never moves (may be merged into one draw call)' },
85
85
  batch: { label: 'Merge copies', rare: true, type: 'bool', optional: true, desc: 'false = never batch this copy' },
@@ -137,10 +137,16 @@ export const PLACEMENT_FIELDS = RULE_STRINGS.fields;
137
137
  /** Why a prop's or template's `collide` is wrong, or null. One rule for the load and content-check: a mistyped object must not quietly become a box */
138
138
  export function collideProblem(v) {
139
139
  if (v === undefined || v === false || v === 'box' || v === 'circle') return null;
140
- const form = isObject(v) && Object.keys(v).every(k => k === 'circle' || k === 'occluder');
141
- if (form && Number.isFinite(v.circle) && v.circle > 0 && (v.occluder === undefined || typeof v.occluder === 'boolean')) return null;
142
- return `must be one of false, "box", "circle" or { circle: radius in meters above 0, occluder?: false }, got ${JSON.stringify(v)}`;
140
+ const keys = isObject(v) ? Object.keys(v) : [];
141
+ const form = keys.length > 0 && keys.every(k => k === 'circle' || k === 'occluder' || k === 'layer');
142
+ if (form && (v.circle === undefined || Number.isFinite(v.circle) && v.circle > 0) && (v.occluder === undefined || typeof v.occluder === 'boolean')
143
+ && (v.layer === undefined || typeof v.layer === 'string' && v.layer)) return null;
144
+ return `must be one of false, "box", "circle" or { circle?: radius in meters above 0 (a box without it), occluder?: false, layer?: 'gate' }, got ${JSON.stringify(v)}`;
143
145
  }
146
+ /** A prop turned about X or Z (not only faced about Y): the three-axis provider holds it. One reading for the load and content-check */
147
+ export const isTilted = rec => Array.isArray(rec?.rot) && !!(rec.rot[0] || rec.rot[2]);
148
+ /** Why a layer is ignored, or null: collide.layer on a tilted prop (collider3d has no layers, so it stops every mover). The load warns with it, content-check reports it */
149
+ export const layerIgnored = (rec, collide) => isTilted(rec) && isObject(collide) && collide.layer ? 'collide.layer needs an upright model; this tilted one stops every mover' : null;
144
150
  /** Why a place cannot load, or null: a turned place moves everything standing on it, so a bad rot stops at the load and in content-check alike */
145
151
  export const placeProblem = p => p?.rot !== undefined && !Number.isFinite(p.rot) ? `rot must be a number of radians about Y, got ${JSON.stringify(p.rot)}` : null;
146
152
  /** Clock time notation 'HH:MM' (24-hour) */
@@ -168,7 +174,7 @@ export const unknownContent = (name, game) => `unknown content "${name}". Known:
168
174
  + `For the game's own data, register it in content/rules.js: export default { kinds: { ${name}: { desc: '…', load: (e, data) => { … } } } }, and list \`rules\` in content/index.js too: the loader only knows what it is handed`;
169
175
  /** Error text for an effects key in a game's content/rules.js */
170
176
  export const NO_GAME_EFFECTS = "content/rules.js: effects is not a key here. Register the action as an op (engine.ops.define('noun.verb', { can, run }) in main.js) "
171
- + "and call it from content with { op: ['noun.verb', { args }] }; see recipes/23-ops.md";
177
+ + "and call it from content with { op: ['noun.verb', { args }] }; see recipes/23-ops.md §2";
172
178
 
173
179
  const say = (vocab, x) => Object.entries(x).map(([k, v]) => vocab[k]?.describe?.(v) ?? `${k} ${JSON.stringify(v)}`);
174
180
 
@@ -25,9 +25,9 @@
25
25
  // and its whole state (turn, speed, asleep) with it in the save part 'rigid'. A copy nothing moved stays out of the save.
26
26
  // Ids: an instance with state (state / container / interact / body) should have a written id (ids.js); without one dev warns.
27
27
  import { checkOptions, freezeDef, missingText, fmt, DEV } from '../../core/base/validate.js';
28
- import { xzOf } from '../../core/base/math.js';
28
+ import { xzOf, scaleOf } from '../../core/base/math.js';
29
29
  import { placeY } from '../../core/scene/ground.js';
30
- import { buildModel, settle, fits, fitsShape, unbuildModel, scaleOf } from './models.js';
30
+ import { buildModel, settle, fits, fitsShape, unbuildModel } from './models.js';
31
31
  import { srcOf, stateful, templateId } from './ids.js';
32
32
  import { PLACEMENT_FIELDS, collideProblem } from './rules.js';
33
33
  import { fieldsShape } from './fields.js';
@@ -219,7 +219,7 @@ const SETTLE = 0.05; // meters: a body that only settled (contact with uneven
219
219
  * - A copy moved with no state (rebuilt by a new holder, a save without it, or a record moved after that state: rigid drops it): it starts awake at the record, so one left in the air comes down.
220
220
  */
221
221
  function addBody(e, rec, o, d) {
222
- const { shape, ...opts } = d.body, s = o.userData.proto.size, ud = o.userData, p = rec.position;
222
+ const { shape, ...opts } = d.body, s = o.userData.measure.size, ud = o.userData, p = rec.position;
223
223
  ud.batch = false; ud.bodyFrom = d.body; ud.holder = bodyHolder(e);
224
224
  const half = s.y * scaleOf(rec)[1] / 2, floor = e.surface(p.x, p.z, rec.floor) + half;
225
225
  // a state from the save decides this copy's place, even when the record reads as unmoved (put back by an undo): resting it would rewrite the baseline to a place it is not at
@@ -1,5 +1,5 @@
1
1
  // Running condition and effect words: content.test and content.run. The vocabulary is rules.js, the built-in meanings are in loader.js.
2
- import { warnMissing, warnOnce } from '../../core/base/validate.js';
2
+ import { warnMissing, warnOnce, syncOnly } from '../../core/base/validate.js';
3
3
  import { coded } from '../../core/base/errorHints.js';
4
4
  import { parseClock } from '../../core/time/dayTime.js';
5
5
  import { list } from '../../core/base/util.js';
@@ -34,7 +34,7 @@ export function runWords(e, api, effects, a, actor) {
34
34
  for (const x of list(a)) for (const [k, v] of Object.entries(x)) {
35
35
  const d = effects.get(k);
36
36
  if (!d) { warnMissing('effect', k, [...effects.keys()]); continue; }
37
- try { const r = d.run(e, d.raw ? v : norm(e, api, d.ref, v), v, ctx); if (isRunFailure(r)) failed.push({ word: k, code: r.code, facts: r.facts }); } catch (err) { first ??= err; threw++; }
37
+ try { const r = d.run(e, d.raw ? v : norm(e, api, d.ref, v), v, ctx); syncOnly(r, `content word { ${k} }`, true); if (isRunFailure(r)) failed.push({ word: k, code: r.code, facts: r.facts }); } catch (err) { first ??= err; threw++; }
38
38
  }
39
39
  const answer = failed.length ? failure({ code: failed[0].code, facts: { failed } }) : { ok: true };
40
40
  if (failed.length) {
@@ -10,7 +10,7 @@ import { stats } from '../../render/backend.js';
10
10
  /** engine.debug.panel (the debug panel) */
11
11
  export class DebugPanel {
12
12
  /** @internal */
13
- constructor(engine, { open = false } = {}) {
13
+ constructor(engine, { open = false } = {}, mod = null) {
14
14
  /** @internal */ this.engine = engine;
15
15
  /** Panel root element @type {HTMLElement} */
16
16
  this.el = document.createElement('div');
@@ -70,7 +70,7 @@ export class DebugPanel {
70
70
  return i;
71
71
  };
72
72
  if (e.calendar) {
73
- bind('ts', () => e.clock.rate, v => e.mod('clock.rate', { owner: 'debug', set: v, layer: 'debug' }), v => v + '×'); // the panel's own entry: the game's rate comes back when it is ended
73
+ bind('ts', () => e.clock.rate, v => mod('clock.rate', { set: v, layer: 'debug' }), v => v + '×'); // ctx.mod: the module's own tracked entry, so the game's rate comes back when the panel leaves
74
74
  /** @internal */ this.tod = bind('tod', () => e.calendar.timeOfDay, v => e.calendar.timeOfDay = v, () => e.calendar.clock);
75
75
  }
76
76
  const ws = q('[data-s="weather"]');
@@ -124,13 +124,13 @@ const DEBUG_PANEL_PARAMS = keysSchema(['open']);
124
124
  */
125
125
  export function debug(opts = {}) {
126
126
  readParams('debugPanel', DEBUG_PANEL_PARAMS, opts);
127
- let d = null; const prof = { n: 0, t: 0, cpu: 0 };
127
+ let d = null; const prof = { n: 0, t: 0 };
128
128
  return {
129
129
  name: 'debugPanel', skipKind: 'none', type: 'ui', params: DEBUG_PANEL_PARAMS, options: opts, label: 'Debug panel', optional: ['calendar', 'weather', 'terrain'],
130
130
  install(e, ctx) { e.i18n.add({ 'zh-CN': { 'module.debugPanel': '调试面板' }, en: { 'module.debugPanel': 'debug panel' } });
131
- d = new DebugPanel(e, opts); e.debug.panel = d;
131
+ d = new DebugPanel(e, opts, ctx.mod); e.debug.panel = d;
132
132
  // the toggle action has no key of its own (presets.bindings.debug binds F3); optional: the panel works by code (panel.el.hidden) too
133
- ctx.input.action('debugPanel', { label: 'debug.toggle', optional: true });
133
+ ctx.input.define('debugPanel', { label: 'debug.toggle', optional: true });
134
134
  return d;
135
135
  },
136
136
  dispose(e) { if (e.debug.panel === d) e.debug.panel = null; d?.el.remove(); },
@@ -138,11 +138,11 @@ export function debug(opts = {}) {
138
138
  // open matters to a screenshot (the panel covers a corner)
139
139
  describe() { return { open: !d.el.hidden }; },
140
140
  afterRender(dt, e) {
141
- prof.n++; prof.t += dt; prof.cpu += e._cpuMs || 0;
142
- if (prof.t < 0.5) return;
141
+ prof.n++; prof.t += dt;
142
+ if (prof.t < 0.5) return; // the text refreshes twice a second; the ms it shows and judges is the budget's median, the one reading describe and inspect.perf give
143
143
  const s = e.terrain?.stats || {}, info = stats(e.renderer);
144
- d.stats({ fps: prof.n / prof.t, cpu: prof.cpu / prof.n, calls: info.drawCalls, tris: info.triangles, visible: s.visible ?? 0, loaded: s.loaded ?? 0, instances: s.instances ?? 0, apply: s.applyMs ?? 0, queued: s.queued ?? 0 });
145
- prof.n = prof.t = prof.cpu = 0;
144
+ d.stats({ fps: prof.n / prof.t, cpu: e.budget._frameMs()?.ms ?? 0, calls: info.drawCalls, tris: info.triangles, visible: s.visible ?? 0, loaded: s.loaded ?? 0, instances: s.instances ?? 0, apply: s.applyMs ?? 0, queued: s.queued ?? 0 });
145
+ prof.n = prof.t = 0;
146
146
  },
147
147
  };
148
148
  }
@@ -27,7 +27,7 @@ const FLOW_PARAMS = keysSchema(['start']);
27
27
  */
28
28
  export function flow(opts = {}) {
29
29
  readParams('flow', FLOW_PARAMS, opts);
30
- let e = null, sig = null, chain = Promise.resolve(), held = null, frozen = null;
30
+ let e = null, sig = null, chain = Promise.resolve(), held = null, frozen = null, leaving = false, queued = null;
31
31
  const states = new Map([['playing', {}], ['paused', { freeze: true, lockInput: true }]]);
32
32
  // turn freeze / input lock on or off for one state
33
33
  const hold = (def, on) => {
@@ -46,15 +46,18 @@ export function flow(opts = {}) {
46
46
  go(name) {
47
47
  const to = states.get(name);
48
48
  if (!to) { warnMissing('flowState', name, [...states.keys()]); return; }
49
+ // a go() asked from inside an exit waits for it: the state is still the old one there, and leaving it twice would recurse or overwrite the state just entered
50
+ if (leaving) { queued = name; return; }
49
51
  const from = api.state, def = states.get(from);
50
52
  if (from === name) return;
51
- def.exit?.(e, name);
53
+ leaving = true;
54
+ try { def.exit?.(e, name); } catch (err) { queued = null; throw err; } finally { leaving = false; }
52
55
  hold(def, false);
53
56
  api.state = name;
54
57
  hold(to, true);
55
58
  if (to.music !== undefined) to.music === null ? e.music?.stop() : e.music?.play(to.music);
56
- to.enter?.(e, from);
57
- e.events.emit('flow:change', { from, to: name });
59
+ try { to.enter?.(e, from); e.events.emit('flow:change', { from, to: name }); } catch (err) { queued = null; throw err; }
60
+ if (queued !== null) { const next = queued; queued = null; api.go(next); } // the exit's own go(), now that this change is complete
58
61
  },
59
62
  /** Scene transition: lock input → fade out → fade music → (autosave: 'auto' saves slot 'auto') → fn() → wait for modules ready → fade in → unlock. Repeated calls are queued.
60
63
  * A new game or load that goes through before the fade out ends drops the transition, one still in line included, as if it was never asked: fn was written for the state that is gone.
@@ -78,7 +81,7 @@ export function flow(opts = {}) {
78
81
  if (autosave === 'auto') e.saves.save('auto');
79
82
  turn = stateTurn(e); // from here until the far door stands, the world is between two states
80
83
  await e.ops.allow(async () => { await fn?.(); }); // the scene swap is loading: the ops guard lets its writes through
81
- await whenSettled(e);
84
+ await whenSettled(e, undefined, true);
82
85
  if (sig?.aborted) return;
83
86
  if (m && prev && !m.current && !m.ruled && !replaced()) m.play(prev); // no track rule: resume the previous track after the switch. A new game or load has its own music, however fn started it; a level load nobody awaited is still this playthrough
84
87
  await fadeScreen(e, 0, { seconds: fade });
@@ -113,7 +116,7 @@ export function flow(opts = {}) {
113
116
  dispose() { frozen?.remove(); held?.remove(); frozen = held = null; },
114
117
  // ?play / applyState({ play }): leave the start state (a title) the way its Start button does; session:start then goes to 'playing'
115
118
  stateKeys: ['play'],
116
- applyState(e, { play }) { if (play != null && opts.start && opts.start !== 'playing' && api.state === opts.start) return e.session.newGame(); },
119
+ applyState(e, { play }, turn) { if (play != null && opts.start && opts.start !== 'playing' && api.state === opts.start) return e.session.newGame({ turn }); }, // inside the scene request's turn: in line it would wait for itself
117
120
  describe() { return { state: api.state, transitioning: api.transitioning }; },
118
121
  };
119
122
  }
@@ -32,6 +32,8 @@ const NODE_KEYS = ['text', 'next', 'choices', 'do', 'speaker', 'data'], CHOICE_K
32
32
  const NONE = Object.freeze([]);
33
33
  const OWN_FIELDS = ' (put your own fields in data: { ... })';
34
34
  const CHANNELS = ['main', 'bubble'];
35
+ /** What _try answers when the game callback threw */
36
+ const FAIL = Symbol('dialogue callback threw');
35
37
  const STR = {
36
38
  channel: "dialogue: channel '{got}' is not one of 'main' (the conversation the player reads, locks input) | 'bubble' (a line over its speaker while play goes on)",
37
39
  bubbleChoices: "[dialogue] '{name}' node '{id}' has choices: choices need the main channel (the player picks them), so on the bubble channel the script ends there",
@@ -101,14 +103,17 @@ export class Dialogue {
101
103
  const step = id => {
102
104
  const node = id && id !== 'end' && nodes[id];
103
105
  if (!node || stopped) { finish(); return; }
104
- const opts = node.choices?.length && this.bubbleChoice === 'ask' ? node.choices.filter(c => !c.if || c.if(this.state, this.engine)) : null;
106
+ const opts = node.choices?.length && this.bubbleChoice === 'ask' ? this._choicesOf(node) : null;
107
+ if (opts === FAIL) { finish(); return; }
105
108
  if (node.choices?.length && !opts) { warnOnce(fmt(STR.bubbleChoices, { name, id })); finish(); return; }
106
- const text = typeof node.text === 'function' ? node.text(this.state, this.engine) : node.text;
107
- if (!this._do(node)) { finish(); return; }
109
+ const text = this._try('dialogue text', () => this._line(node));
110
+ if (text === FAIL || !this._do(node)) { finish(); return; } // a throwing line ends this script on its own channel (its onEnter / promise settle), the main dialogue is left alone
108
111
  const speaker = node.speaker || (name.startsWith('__say_') ? '' : name);
109
112
  if (opts?.length) { // 'ask': the line stays up with its choices until one is picked (dialogue.choose { index, run })
110
- const run = asking = ++this._askSeq, label = c => typeof c.text === 'function' ? c.text(this.state, this.engine) : c.text;
111
- cur = this._bubbles.say(at, text, { speaker, seconds: Infinity, queue, run, choices: opts.map(label) });
113
+ const labels = this._try('dialogue choice', () => opts.map(c => this._line(c)));
114
+ if (labels === FAIL) { finish(); return; }
115
+ const run = asking = ++this._askSeq;
116
+ cur = this._bubbles.say(at, text, { speaker, seconds: Infinity, queue, run, choices: labels });
112
117
  this._asks.set(run, { opts, actor, pick: i => { const c = opts[i]; this._asks.delete(run); asking = 0; cur.remove(); step(this._do(c) ? c.next || 'end' : 'end'); } });
113
118
  return;
114
119
  }
@@ -159,9 +164,11 @@ export class Dialogue {
159
164
  }
160
165
 
161
166
  /** @internal A node's or choice's do. One that throws ends the conversation, as a throwing step ends a cutscene: a line nobody can finish would keep the keys and a say() waiting */
162
- _do(x) {
163
- try { x.do?.(this.state, this.engine); return true; } catch (err) { reportError(this.engine, err, 'dialogue do', { soft: true }); return false; }
164
- }
167
+ _do(x) { return this._try('dialogue do', () => { x.do?.(this.state, this.engine); }) !== FAIL; }
168
+ /** @internal A node's or choice's text: a string, or a function of (state, engine) */
169
+ _line(x) { return typeof x.text === 'function' ? x.text(this.state, this.engine) : x.text; }
170
+ /** @internal Run a game callback; one that throws is reported (soft, no freeze) and answers FAIL, so the caller ends what it was showing instead of leaving it half open */
171
+ _try(what, fn) { try { return fn(); } catch (err) { reportError(this.engine, err, what, { soft: true }); return FAIL; } }
165
172
 
166
173
  _show(id) {
167
174
  const a = this.active;
@@ -171,8 +178,8 @@ export class Dialogue {
171
178
  if (!node || id === 'end') { this.end(); return; }
172
179
  a.node = node; a.id = id;
173
180
  a.focus.setNav(null); // no choices while the new line types
174
- const text = typeof node.text === 'function' ? node.text(this.state, this.engine) : node.text;
175
- if (!this._do(node)) { this.end(); return; } // read the line before running effects, so it doesn't see flags just changed
181
+ const text = this._try('dialogue text', () => this._line(node));
182
+ if (text === FAIL || !this._do(node)) { this.end(); return; } // a throwing line ends like a throwing do: a half-open line would keep the focus and the old line // read the line before running effects, so it doesn't see flags just changed
176
183
  if (this.active !== a) return; // do ended the dialogue or started another
177
184
  a.who = node.speaker || a.speaker;
178
185
  this.full = String(text ?? ''); this.shown = 0; this.typing = true; this._opts = null;
@@ -186,11 +193,11 @@ export class Dialogue {
186
193
  this.typing = false;
187
194
  this.shown = this.full.length;
188
195
  const a = this.active, e = this.engine;
189
- const opts = (a.node.choices || []).filter(c => !c.if || c.if(this.state, e));
190
- this._opts = opts.length ? opts : null;
191
- const label = c => typeof c.text === 'function' ? c.text(this.state, e) : c.text;
196
+ const opts = this._choicesOf(a.node);
192
197
  // key: the first bound key only ('1', not '1/Numpad1'), so a rebound choice key shows its new name
193
- this._choices = opts.map((c, i) => ({ text: label(c), key: i < 9 ? e.input.label('choice' + (i + 1)).split('/')[0] || null : null, data: c.data ?? {} }));
198
+ const choices = opts === FAIL ? FAIL : this._try('dialogue choice', () => opts.map((c, i) => ({ text: this._line(c), key: i < 9 ? e.input.label('choice' + (i + 1)).split('/')[0] || null : null, data: c.data ?? {} })));
199
+ if (choices === FAIL) { this.end(); return; } // a choice that throws ends the dialogue like a line that throws
200
+ this._opts = opts.length ? opts : null; this._choices = choices;
194
201
  // the choice cursor: the menu keys / d-pad / stick move it, confirm picks (the same op as a click or a number key); the part draws view.selected
195
202
  if (this._opts) a.focus.setNav({ count: () => this._choices.length, moved: () => this._draw(), confirm: i => e.ops.run('dialogue.choose', { index: i }, this._by) });
196
203
  this._draw();
@@ -218,7 +225,14 @@ export class Dialogue {
218
225
  }
219
226
 
220
227
  /** Choices shown for the current line (typing or not). @internal */
221
- _visible() { return this._opts ?? (this.active?.node.choices || []).filter(c => !c.if || c.if(this.state, this.engine)); }
228
+ _visible() {
229
+ if (this._opts) return this._opts;
230
+ const opts = this._choicesOf(this.active?.node);
231
+ if (opts === FAIL) { this.end(); return []; } // a condition that throws while a line is typing (a number key, an availability check) ends the dialogue like it does when the line is done
232
+ return opts;
233
+ }
234
+ /** @internal The choices of a node whose condition holds; FAIL when a condition threw (the one place choice conditions run) */
235
+ _choicesOf(node) { return this._try('dialogue choice', () => (node?.choices || []).filter(c => !c.if || c.if(this.state, this.engine))); }
222
236
  /** @internal run through the op dialogue.choose */
223
237
  _choose(i) {
224
238
  if (!this.active) return;
@@ -241,8 +255,8 @@ export class Dialogue {
241
255
  if (this.shown >= this.full.length) this._finishTyping();
242
256
  else if (Math.floor(this.shown) !== was) this._draw(); // redraw only when another character shows
243
257
  }
244
- // just opened this frame (the press that opened it does not advance), or the choice cursor already used confirm this frame
245
- if (a.focus.fresh || a.focus.consumed) return;
258
+ // just opened this frame (the press that opened it does not advance), the cursor already used confirm this frame (on the dialogue's choices, or on a window over it), or a window over it owns the keys
259
+ if (a.focus.fresh || a.focus.consumed || !a.focus.onTop) return;
246
260
  const input = this.engine.input, P = this._by;
247
261
  if (this.advanceActions.some(x => input.pressedRaw(x))) ops.run('dialogue.advance', {}, P);
248
262
  for (let i = 1; i <= 9; i++) if (input.pressedRaw('choice' + i) && this.active && this._visible()[i - 1]) ops.run('dialogue.choose', { index: i - 1 }, P);
@@ -297,7 +311,7 @@ export function dialogue(opts = {}) {
297
311
  d = new Dialogue(e, opts);
298
312
  // choice1..9 pick a choice by number: declared, never bound here (presets.bindings.dialogNumbers binds 1-9). Optional: the choice cursor
299
313
  // (basic menu keys + confirm) and clicks pick choices without them. Context 'dialog', so 1-9 stay free for hotbars outside a conversation
300
- for (let i = 1; i <= 9; i++) ctx.input.action('choice' + i, { context: 'dialog', label: 'dialogue.choice', optional: true });
314
+ for (let i = 1; i <= 9; i++) ctx.input.define('choice' + i, { context: 'dialog', label: 'dialogue.choice', optional: true });
301
315
  ctx.track(e.events.on('session:end', () => d._cancel())); // an open dialogue belongs to the playthrough that opened it
302
316
  ctx.ui.define('dialogue', dialogueBox);
303
317
  ctx.ui.define('dialogue.bubble', bubblePart, { multi: true });
@@ -324,9 +338,9 @@ export function dialogue(opts = {}) {
324
338
  describe(e, ctx) {
325
339
  const a = d.active, bubbles = d.bubbles();
326
340
  if (!a && !bubbles.length) return;
327
- const label = c => (typeof c.text === 'function' ? c.text(d.state, e) : c.text);
328
341
  if (ctx.out.ui) {
329
- if (a) ctx.out.ui.dialogue = { speaker: a.who, text: d.full, typing: d.typing, choices: (d._opts || []).map(label), selected: d._opts ? a.focus.index ?? 0 : -1, advance: d.advanceActions.map(x => e.input.label(x)).join(' / ') };
342
+ // choices: the labels already read when the line finished, so inspecting never runs game code
343
+ if (a) ctx.out.ui.dialogue = { speaker: a.who, text: d.full, typing: d.typing, choices: d._opts ? d._choices.map(c => c.text) : [], selected: d._opts ? a.focus.index ?? 0 : -1, advance: d.advanceActions.map(x => e.input.label(x)).join(' / ') };
330
344
  if (bubbles.length) ctx.out.ui.bubbles = bubbles;
331
345
  }
332
346
  },