threedog 0.8.0 → 1.0.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 (372) hide show
  1. package/CHANGELOG.md +219 -4
  2. package/README.md +6 -6
  3. package/core/assets/Animator.js +2 -0
  4. package/core/assets/Assets.js +44 -13
  5. package/core/assets/assetEntry.js +87 -22
  6. package/core/assets/assetHot.js +2 -1
  7. package/core/assets/assetReport.js +1 -2
  8. package/core/audio/Audio.js +24 -5
  9. package/core/base/I18n.js +6 -3
  10. package/core/base/Random.js +3 -1
  11. package/core/base/Vars.js +14 -4
  12. package/core/base/errorCodes.js +54 -16
  13. package/core/base/errorHints.js +12 -1
  14. package/core/base/errors.js +6 -4
  15. package/core/base/events.generated.js +10 -0
  16. package/core/base/follows.js +26 -0
  17. package/core/base/math.js +15 -8
  18. package/core/base/params.js +2 -2
  19. package/core/{saves → base}/saveValues.js +24 -6
  20. package/core/base/sections.js +97 -0
  21. package/core/base/spelling.js +32 -0
  22. package/core/base/validate.js +8 -29
  23. package/core/engine/Engine.js +61 -18
  24. package/core/engine/Loading.js +30 -3
  25. package/core/engine/copies.js +1 -1
  26. package/core/engine/headlessLoad.js +30 -13
  27. package/core/engine/lifecycle.js +30 -25
  28. package/core/engine/loop.js +22 -4
  29. package/core/engine/moduleSlots.js +91 -15
  30. package/core/engine/moduleTypes.js +13 -0
  31. package/core/engine/modules.js +248 -62
  32. package/core/engine/page.js +25 -8
  33. package/core/engine/plugins.js +15 -3
  34. package/core/engine/services.js +3 -0
  35. package/core/engine/startup.js +46 -36
  36. package/core/input/Input.js +39 -19
  37. package/core/input/inputKeyboard.js +39 -0
  38. package/core/input/inputPad.js +23 -2
  39. package/core/input/inputPointer.js +3 -1
  40. package/core/input/inputSeat.js +66 -0
  41. package/core/input/inputTouch.js +23 -6
  42. package/core/inspect/DebugOverrides.js +13 -2
  43. package/core/inspect/Describe.js +10 -6
  44. package/core/inspect/Inspect.js +31 -4
  45. package/core/inspect/UrlState.js +14 -10
  46. package/core/inspect/catalog.js +12 -5
  47. package/core/inspect/describeRender.js +3 -2
  48. package/core/inspect/describeText.js +6 -2
  49. package/core/inspect/metadata.generated.js +4140 -0
  50. package/core/inspect/pictureWriters.js +117 -33
  51. package/core/inspect/toolDoor.js +21 -0
  52. package/core/inspect/valueHistory.js +35 -0
  53. package/core/ops/Ops.js +32 -7
  54. package/core/ops/control.js +48 -23
  55. package/core/ops/holds.js +4 -3
  56. package/core/ops/opsAtomic.js +18 -6
  57. package/core/ops/opsCheck.js +7 -5
  58. package/core/ops/opsFail.js +5 -7
  59. package/core/ops/opsRun.js +2 -2
  60. package/core/ops/owned.js +20 -3
  61. package/core/ops/sharedPoint.js +7 -10
  62. package/core/ops/stacks.js +22 -1
  63. package/core/saves/SaveStore.js +52 -26
  64. package/core/saves/Saves.js +122 -27
  65. package/core/saves/saveApply.js +159 -61
  66. package/core/saves/saveFiles.js +30 -25
  67. package/core/saves/saveVersions.js +20 -6
  68. package/core/saves/session.js +76 -33
  69. package/core/saves/stateReplace.js +184 -0
  70. package/core/scene/Rays.js +21 -5
  71. package/core/scene/Views.js +6 -6
  72. package/core/scene/adaptive.js +13 -10
  73. package/core/scene/canvasBox.js +2 -0
  74. package/core/scene/compositeGround.js +72 -0
  75. package/core/scene/floor.js +17 -0
  76. package/core/scene/grid.js +2 -0
  77. package/core/scene/ground.contract.js +14 -0
  78. package/core/scene/ground.js +52 -17
  79. package/core/scene/pixel.js +154 -0
  80. package/core/scene/pixelRatio.js +167 -0
  81. package/core/scene/sceneDelta.js +3 -3
  82. package/core/scene/sceneMethods.js +11 -6
  83. package/core/scene/stepPoses.js +6 -1
  84. package/core/scene/thingExplain.js +1 -1
  85. package/core/scene/thingOps.js +22 -14
  86. package/core/scene/things.js +1 -1
  87. package/core/scene/tier.js +10 -0
  88. package/core/scene/view.js +126 -9
  89. package/core/stream/Batching.js +0 -1
  90. package/core/stream/Stream.js +24 -12
  91. package/core/stream/batchGroups.js +1 -0
  92. package/core/stream/scatter.js +5 -2
  93. package/core/stream/streamSources.js +2 -1
  94. package/core/threads/Commits.js +12 -7
  95. package/core/threads/Jobs.js +15 -5
  96. package/core/threads/Threads.js +5 -2
  97. package/core/time/Clock.js +3 -1
  98. package/core/time/skip.js +10 -4
  99. package/core/time/time.js +16 -10
  100. package/docs/AI.md +89 -72
  101. package/docs/API.md +18 -14
  102. package/docs/CODEMAP.md +68 -40
  103. package/docs/COMMANDS.md +22 -23
  104. package/docs/CONVENTIONS.md +120 -17
  105. package/docs/MIGRATING-0.8.md +2 -0
  106. package/docs/MIGRATING-1.0.md +101 -0
  107. package/docs/THREE.md +65 -12
  108. package/docs/api/cameraRig.md +3 -0
  109. package/docs/api/characters.md +13 -7
  110. package/docs/api/collider3d.md +9 -0
  111. package/docs/api/content.md +16 -15
  112. package/docs/api/dialogue.md +2 -1
  113. package/docs/api/engine.md +18 -16
  114. package/docs/api/events.md +14 -4
  115. package/docs/api/ground.md +2 -2
  116. package/docs/api/i18n.md +1 -1
  117. package/docs/api/input.md +2 -1
  118. package/docs/api/interactions.md +1 -1
  119. package/docs/api/inventory.md +1 -1
  120. package/docs/api/level.md +3 -2
  121. package/docs/api/nav.md +4 -2
  122. package/docs/api/particles.md +8 -5
  123. package/docs/api/pickups.md +1 -1
  124. package/docs/api/post.md +3 -4
  125. package/docs/api/quests.md +4 -2
  126. package/docs/api/rays.md +2 -0
  127. package/docs/api/rigid.md +3 -2
  128. package/docs/api/saves.md +8 -7
  129. package/docs/api/stream.md +4 -5
  130. package/docs/api/terrain.md +3 -4
  131. package/docs/api/terrainDraw.md +1 -1
  132. package/docs/api/timeline.md +2 -2
  133. package/docs/api/tools.md +3 -1
  134. package/docs/api/triggers.md +2 -0
  135. package/docs/api/vegetationDraw.md +1 -1
  136. package/docs/api/water.md +6 -2
  137. package/docs/api/weather.md +19 -4
  138. package/docs/api/weatherDraw.md +1 -1
  139. package/docs/api/world.md +1 -1
  140. package/docs/recipes/01-new-game.md +3 -3
  141. package/docs/recipes/02-npc.md +3 -4
  142. package/docs/recipes/03-items-pickups.md +11 -11
  143. package/docs/recipes/04-quests.md +2 -0
  144. package/docs/recipes/05-props-bake.md +9 -9
  145. package/docs/recipes/06-clock-events.md +6 -6
  146. package/docs/recipes/07-flow-scenes-pause.md +18 -15
  147. package/docs/recipes/08-weather-sky.md +5 -5
  148. package/docs/recipes/09-materials-lights-models.md +3 -3
  149. package/docs/recipes/10-blender-level.md +16 -4
  150. package/docs/recipes/11-vehicles.md +18 -6
  151. package/docs/recipes/12-navmesh.md +52 -8
  152. package/docs/recipes/13-animation.md +34 -8
  153. package/docs/recipes/14-custom-module.md +20 -8
  154. package/docs/recipes/15-perf.md +4 -4
  155. package/docs/recipes/16-dev-bridge.md +9 -8
  156. package/docs/recipes/18-world.md +13 -5
  157. package/docs/recipes/19-shooting-picking.md +3 -2
  158. package/docs/recipes/20-content-actions-save.md +26 -6
  159. package/docs/recipes/21-camera.md +17 -23
  160. package/docs/recipes/22-shop-gold.md +21 -12
  161. package/docs/recipes/23-ops.md +19 -15
  162. package/docs/recipes/26-ui-parts.md +3 -2
  163. package/docs/recipes/27-net.md +3 -3
  164. package/docs/recipes/28-terrain.md +3 -3
  165. package/docs/recipes/29-grid.md +1 -1
  166. package/docs/recipes/30-templates.md +10 -13
  167. package/docs/recipes/31-audio.md +2 -2
  168. package/docs/recipes/32-action-game.md +6 -5
  169. package/docs/recipes/33-stream-sources.md +4 -1
  170. package/docs/recipes/34-environment-lighting.md +7 -8
  171. package/docs/recipes/35-picture-from-reference.md +13 -9
  172. package/docs/recipes/36-ground-plants.md +3 -2
  173. package/docs/recipes/40-scene.md +11 -10
  174. package/docs/recipes/43-shader-patches-surfaces.md +7 -7
  175. package/docs/recipes/44-water-weather-hooks.md +9 -8
  176. package/docs/recipes/45-cascaded-shadows.md +3 -4
  177. package/docs/recipes/46-blender-art-route.md +3 -3
  178. package/docs/recipes/49-game-module-contract.md +2 -1
  179. package/docs/recipes/50-own-renderer.md +1 -0
  180. package/docs/recipes/51-capability-catalog.md +14 -8
  181. package/docs/recipes/52-around-the-picture.md +4 -4
  182. package/docs/recipes/55-mods-time-wrap.md +5 -4
  183. package/docs/recipes/56-webgpu-tsl.md +12 -1
  184. package/docs/recipes/57-control.md +30 -10
  185. package/docs/recipes/58-input.md +13 -0
  186. package/docs/recipes/60-judge-the-picture.md +1 -1
  187. package/docs/recipes/62-picture-code.md +106 -48
  188. package/docs/recipes/63-third-person-start.md +2 -1
  189. package/docs/recipes/64-particles.md +53 -4
  190. package/docs/recipes/65-swarm.md +2 -2
  191. package/docs/recipes/66-common-tasks.md +313 -0
  192. package/examples/action/.threedog/content-index.json +1 -1
  193. package/examples/action/GAMEMAP.md +3 -3
  194. package/examples/perf-island/.threedog/content-index.json +1 -1
  195. package/examples/perf-island/GAMEMAP.md +3 -3
  196. package/examples/perf-island/main.js +2 -2
  197. package/examples/plain-picture/GAMEMAP.md +3 -1
  198. package/examples/rc2d/GAMEMAP.md +1 -1
  199. package/examples/rc2d/rc2d.js +1 -1
  200. package/examples/styletest/.threedog/content-index.json +1 -1
  201. package/examples/styletest/GAMEMAP.md +3 -3
  202. package/examples/webgpu-tsl/GAMEMAP.md +1 -1
  203. package/examples/world/.threedog/content-index.json +1 -1
  204. package/examples/world/GAMEMAP.md +5 -4
  205. package/examples/world/main.js +3 -3
  206. package/index.d.ts +8 -5
  207. package/index.js +22 -1
  208. package/llms.txt +2 -1
  209. package/modules/ambience/Ambience.js +5 -3
  210. package/modules/calendar/index.js +7 -5
  211. package/modules/camera/FirstPersonCamera.js +3 -3
  212. package/modules/camera/FixedCamera.js +34 -20
  213. package/modules/camera/FollowCamera.js +20 -11
  214. package/modules/camera/RtsCamera.js +1 -0
  215. package/modules/camera/common.js +33 -22
  216. package/modules/camera/pixelSnap.js +62 -0
  217. package/modules/characters/Character.js +136 -43
  218. package/modules/characters/NPC.js +60 -28
  219. package/modules/characters/assetModel.js +2 -2
  220. package/modules/characters/astar.js +47 -28
  221. package/modules/characters/character.contract.js +21 -0
  222. package/modules/characters/contract.js +17 -3
  223. package/modules/characters/index.js +94 -34
  224. package/modules/characters/moveHelpers.js +80 -15
  225. package/modules/characters/mover.contract.js +14 -0
  226. package/modules/characters/movers/common.js +6 -4
  227. package/modules/characters/movers/rapier.js +12 -5
  228. package/modules/characters/movers/simple.js +25 -12
  229. package/modules/characters/movers/support.js +18 -7
  230. package/modules/characters/npcAvoid.js +15 -12
  231. package/modules/characters/npcSim.js +75 -25
  232. package/modules/characters/npcView.js +13 -6
  233. package/modules/characters/pathAsync.js +74 -24
  234. package/modules/characters/pathJob.js +38 -21
  235. package/modules/characters/player.js +59 -47
  236. package/modules/characters/seat.js +56 -0
  237. package/modules/characters/vehicle.contract.js +8 -5
  238. package/modules/characters/walkTo.js +31 -18
  239. package/modules/collision/Collision.js +44 -26
  240. package/modules/collision/contract.js +2 -2
  241. package/modules/collision/grid.js +6 -1
  242. package/modules/content/explain.js +1 -1
  243. package/modules/content/fields.js +3 -3
  244. package/modules/content/ids.js +3 -1
  245. package/modules/content/index.js +83 -27
  246. package/modules/content/loader.js +110 -130
  247. package/modules/content/markers.js +1 -1
  248. package/modules/content/models.js +48 -14
  249. package/modules/content/packs.js +2 -1
  250. package/modules/content/places.js +5 -4
  251. package/modules/content/props.js +8 -6
  252. package/modules/content/rules.js +29 -47
  253. package/modules/content/templates.js +66 -35
  254. package/modules/content/words.js +19 -6
  255. package/modules/debug/DebugPanel.js +4 -2
  256. package/modules/flow/contract.js +1 -0
  257. package/modules/flow/index.js +24 -14
  258. package/modules/gameplay/Container.js +5 -2
  259. package/modules/gameplay/Containers.js +9 -1
  260. package/modules/gameplay/Dialogue.js +82 -25
  261. package/modules/gameplay/Interactions.js +61 -32
  262. package/modules/gameplay/Inventory.js +56 -13
  263. package/modules/gameplay/Quests.js +133 -24
  264. package/modules/gameplay/boxOps.js +7 -0
  265. package/modules/gameplay/dialogueBubbles.js +14 -9
  266. package/modules/gameplay/inventoryOps.js +11 -7
  267. package/modules/gameplay/pickups.js +43 -16
  268. package/modules/gameplay/questLog.js +4 -2
  269. package/modules/gameplay/questSave.js +6 -1
  270. package/modules/gameplay/quests.contract.js +1 -1
  271. package/modules/grid/Grid.js +1 -1
  272. package/modules/grid/Layer.js +8 -4
  273. package/modules/grid/index.js +21 -15
  274. package/modules/grid/ops.js +43 -46
  275. package/modules/grid/tiles.js +1 -1
  276. package/modules/hlod/index.js +6 -3
  277. package/modules/hud/index.js +6 -4
  278. package/modules/hud/parts.js +4 -4
  279. package/modules/level/contract.js +2 -2
  280. package/modules/level/heightfield.js +17 -21
  281. package/modules/level/index.js +83 -26
  282. package/modules/level/load.js +165 -48
  283. package/modules/level/nodes.js +34 -16
  284. package/modules/lights/index.js +6 -3
  285. package/modules/lights/sources.js +3 -1
  286. package/modules/music/Music.js +4 -2
  287. package/modules/nav/contract.js +7 -5
  288. package/modules/nav/index.js +174 -44
  289. package/modules/nav/navPath.js +45 -10
  290. package/modules/net/index.js +1 -1
  291. package/modules/particles/Particles.js +85 -22
  292. package/modules/particles/effect.js +80 -28
  293. package/modules/particles/shaders.js +17 -0
  294. package/modules/photo/Photo.js +12 -10
  295. package/modules/rigid/RigidBodies.js +200 -57
  296. package/modules/rigid/Vehicles.js +15 -5
  297. package/modules/rigid/collider3d.contract.js +26 -0
  298. package/modules/rigid/ragdoll.js +55 -44
  299. package/modules/rigid/ragdollBones.js +83 -33
  300. package/modules/rigid/refresh.js +10 -0
  301. package/modules/rigid/sync.js +46 -15
  302. package/modules/settings/Settings.js +84 -37
  303. package/modules/settings/apply.js +15 -8
  304. package/modules/settings/sections.js +7 -4
  305. package/modules/settings/strings.js +2 -2
  306. package/modules/sky/skyModule.js +3 -1
  307. package/modules/swarm/Swarm.js +16 -6
  308. package/modules/terrain/ChunkManager.js +10 -16
  309. package/modules/terrain/index.js +17 -11
  310. package/modules/terrain/terrainEdit.js +13 -2
  311. package/modules/terrain/terrainGen.js +5 -3
  312. package/modules/terrain/terrainShape.js +1 -1
  313. package/modules/timeline/Timeline.js +58 -26
  314. package/modules/timeline/Tween.js +19 -13
  315. package/modules/timeline/shots.js +19 -10
  316. package/modules/triggers/index.js +87 -20
  317. package/modules/vegetation/Vegetation.js +4 -3
  318. package/modules/vegetation/draw.js +16 -0
  319. package/modules/vegetation/groundChunks.js +10 -7
  320. package/modules/vegetation/index.js +30 -7
  321. package/modules/water/Water.js +6 -2
  322. package/modules/weather/Weather.js +16 -15
  323. package/modules/weather/weatherDraw.js +7 -6
  324. package/modules/world/World.js +20 -7
  325. package/modules/world/explain.js +1 -1
  326. package/modules/world/index.js +13 -6
  327. package/modules/world/persist.js +23 -8
  328. package/modules/world/pos.js +4 -4
  329. package/modules/world/records.js +13 -7
  330. package/modules/world/sim.js +74 -23
  331. package/modules/world/simFar.js +2 -2
  332. package/modules/world/state.js +31 -6
  333. package/modules/world/thingSource.js +16 -3
  334. package/modules/world/views.js +19 -8
  335. package/package.json +7 -1
  336. package/render/PostFX.js +47 -29
  337. package/render/backend.js +5 -1
  338. package/render/fx/particles.tsl.js +8 -6
  339. package/render/fx/postWebGPU.tsl.js +3 -3
  340. package/render/layers.js +1 -1
  341. package/render/lightmap.js +23 -3
  342. package/render/occlusion.js +43 -12
  343. package/render/patches.js +2 -2
  344. package/render/postWebGL.js +4 -3
  345. package/render/probes.js +25 -0
  346. package/render/shadows.js +2 -2
  347. package/types/core.d.ts +142 -55
  348. package/types/gameplay.d.ts +92 -40
  349. package/types/generated/core/base/I18n.d.ts +2 -2
  350. package/types/generated/core/input/Input.d.ts +16 -2
  351. package/types/generated/core/input/inputSeat.d.ts +26 -0
  352. package/types/generated/core/inspect/DebugOverrides.d.ts +15 -1
  353. package/types/generated/core/ops/Ops.d.ts +2 -1
  354. package/types/generated/core/ops/control.d.ts +12 -2
  355. package/types/generated/core/saves/Saves.d.ts +26 -6
  356. package/types/generated/core/saves/session.d.ts +1 -1
  357. package/types/generated/core/scene/Views.d.ts +1 -1
  358. package/types/generated/core/stream/Stream.d.ts +6 -4
  359. package/types/generated/modules/grid/Grid.d.ts +1 -0
  360. package/types/generated/modules/particles/Particles.d.ts +4 -3
  361. package/types/generated/modules/timeline/Timeline.d.ts +5 -4
  362. package/types/generated/modules/weather/Weather.d.ts +1 -7
  363. package/types/generated/modules/world/World.d.ts +6 -4
  364. package/types/generated/render/PostFX.d.ts +6 -14
  365. package/types/nav.d.ts +36 -4
  366. package/types/physics.d.ts +55 -7
  367. package/types/pixel.d.ts +75 -0
  368. package/types/world.d.ts +14 -8
  369. package/ui/Parts.js +9 -2
  370. package/ui/theme.js +2 -2
  371. package/core/scene/engineCamera.js +0 -32
  372. package/modules/camera/projection.js +0 -21
@@ -1,5 +1,11 @@
1
- // "Who wrote this picture value": the last file:line that changed a light, the fog, tone, environment, background or a material color, and one warning
2
- // when two places fight over a value inside one frame. Dev server only (npm run dev, threedog snap): see ON below. It observes; every write goes through.
1
+ // "Who wrote this value": the file:line and frame that changed it, a short history, and a one-line hint when two places fight over it. Dev server only (npm run dev,
2
+ // threedog snap): the install line in Engine.js is the one test a bundler drops, so a release build has none of this. It observes; every write goes through.
3
+ //
4
+ // What is watched, and why these: picture values (a light, the fog, tone, environment, background, a material color), because nothing else stands between two picture
5
+ // files; values the engine writes on its own (core/ops/owned.js), because the engine yields quietly and "who took it" was the missing fact; shared points, which
6
+ // keep their owner and line anyway, so they need no hook at all; and whatever the game names with engine.debug.watch.
7
+ // What is not, on purpose: every other three.js property. An accessor on each would be the wrapper this engine promises not to be (docs/design.md 5.5), so
8
+ // an unwatched value says "not tracked", and no answer here ever says two writers do not exist (valueHistory.js LIMIT).
3
9
  //
4
10
  // Why accessors and a stack, not per-hook attribution: picture/index.js calls all its parts from one engine.onRender, so "which hook was running" names the
5
11
  // wiring file for every value. Only the call stack of the write tells parts apart. Why own accessors on r / g / b and x / y / z: Color and Vector3 are
@@ -9,7 +15,11 @@
9
15
  // changes nothing is ignored, and a value written every frame is looked at every EVERY frames (staggered). What still gets a stack at once: the first
10
16
  // frames, a value that was not written last frame (a one-shot write), and a frame with more writes to a value than its last looked-at frame had (a
11
17
  // new writer). So `framesAgo` says how old the answer is, and `writtenSince` says the value moved after that, unseen. An answer is never presented as
12
- // fresher than it is.
18
+ // fresher than it is. A close record (owned and game-named values) also looks at the first write of every frame: an owned value moves every frame by the engine's own
19
+ // hand, so a single outside write would otherwise pass as usual, and the yield would have no line to give. That costs one stack per frame per moving value, not one per write.
20
+ //
21
+ // Why also "taking turns": two writers that never share a frame (one on even frames, one in a timer) overwrite each other just the same. But one state handing a value to
22
+ // another is normal, so it takes TURNS changes of writer within WINDOW frames. Each change seen also asks for a look next frame, or sampling would rarely see the next one.
13
23
  //
14
24
  // Why two places in one function are not a fight: fog.color.copy(a) then fog.color.lerp(b, t) is a value computed in steps. A place is a file plus a
15
25
  // function name, plus the part running it. shortcut: outside parts, two anonymous functions or two same-named methods in one file count as one place, so a fight between them goes unwarned;
@@ -29,15 +39,18 @@ import { notePatch } from '../scene/threePatches.js';
29
39
  import { sceneVisitor, onSceneRoot } from '../scene/sceneDelta.js';
30
40
  import { stackFrames, frameText, callerAt, engineFile } from '../ops/stackFrames.js';
31
41
  import { slotOfValue, slotHolder } from '../scene/pictureSlots.js';
42
+ import { LIMIT, remember, historyText, partsOf, sharedAnswer } from './valueHistory.js';
32
43
 
33
44
  const EVERY = 30; // frames between two looks at a value written every frame: a stale answer is at most half a second old
34
45
  const DEPTH = 10; // three's own frames above the writer: setter, Color.copy, lerpColors ... always fewer
46
+ const TURNS = 6, WINDOW = 240; // changes of writer within 4 seconds at 60 frames: a state change makes one or two, a fight makes one per frame
35
47
  const NOT = {
36
48
  before: 'not tracked: set before it entered the scene',
37
49
  start: 'not tracked: three.js default or set before the engine was made',
38
50
  own: 'not tracked: this object defines the property with its own accessor',
39
51
  none: 'not tracked: never written since tracking began',
40
52
  noFile: 'not tracked: the last write had no source file (console, eval or the picture check)',
53
+ hidden: 'not tracked: it is no plain property a hook can sit on, so its writers cannot be seen',
41
54
  };
42
55
  // three.js and pre-bundled libraries are never "the writer": the line that called them is
43
56
  const SKIP = /\/deps\/|\/node_modules\/|\/three(?:\.[a-z]+)*\.js$/;
@@ -46,13 +59,16 @@ const CORE = /\/(?:core|render)\/(?:[^/]+\/)?[^/]+$/; // with engineFile: core
46
59
  const MATERIALS_MAX = 40; // describe() stays small on a big scene; explain still answers any one of them
47
60
  const SHARED_FIX = "make it a shared value: the owner defines it with engine.stacks.define(name, { base: 1 }) and reads it where it writes three.js, the others change it with ctx.mod(name, { mul: 0.5 }); for an amount that moves, take it once, const h = ctx.mod(name, { mul: 1 }), and call h.change(x) each frame (recipes/62-picture-code.md)";
48
61
  const STRINGS = {
49
- conflict: '{value} was written twice in one frame with different results: {first}, then {second}. The later write is what is drawn. Fix, one of: (1) one place keeps the write, delete the other{claim}; (2) if both need a say, ' + SHARED_FIX,
62
+ conflict: "{value}: two writers {how}, {first} and {second}; the last write stands. engine.explain({ value: '{value}' }) has the history and the fix",
63
+ fix: 'Fix, one of: (1) one place keeps the write, delete the other{claim}; (2) if both need a say, ' + SHARED_FIX,
50
64
  claim: ", and that part declares it with provides: ['{slot}']",
51
65
  held: "{value} is held by part '{holder}' (provides: ['{slot}'], {place}), but {at} ({who}) wrote it too. The later write is what is drawn, so one of them never shows. Fix, one of: (1) delete the write at {at}; " +
52
66
  "(2) if that code should own it, give it provides: ['{slot}'] and install it with engine.use(thatPart(), { replaces: '{slot}' }), which unloads '{holder}'; (3) if both need a say, " + SHARED_FIX,
53
67
  leftover: "part '{name}' is gone, but what it added is still there: {list}. Fix: in its install, hand each one to ctx.track, e.g. ctx.track({ remove() { e.scene.remove(obj); obj.geometry.dispose(); } }), or undo it in the part's dispose()",
54
68
  };
55
69
 
70
+ const HOW = { frame: 'in one frame', turns: 'taking turns across frames' };
71
+
56
72
  const page = { off: false, nextId: 0 }; // off: threePatches.off('picture-writers'), page-wide like the list
57
73
 
58
74
  /** The writer of the running write: { at: 'picture/sky.js:12', key } or null when no frame names a source file */
@@ -67,8 +83,12 @@ function writerNow() {
67
83
  return { at: frameText(f), key: `${f.file}|${f.fn}`, file: f.file, frames: all.slice(i), engine: all.slice(0, i + 1).some(x => CORE.test(x.file) && engineFile(x.file)) };
68
84
  }
69
85
 
70
- // name: the value's writers name while it can be in a slot (null: a material); ownBy / ownAt: the holder's last write; last: the slot and whether its holder wrote last
71
- const newRec = (why, name = null) => ({ id: page.nextId++, at: null, why, seen: 0, wrote: -1, f: -1, n: 0, usual: 0, next: 0, sample: true, placeKey: null, placeAt: null, placeBy: null, fought: false, name, ownBy: null, ownAt: null, last: null });
86
+ // name: the value's writers name while it can be in a slot (null: a material); ownBy / ownAt: the holder's last write; last: the slot and whether its holder wrote last;
87
+ // same: another record already hooks this property and answers for this one; close: see the header; owned: the engine's modules write it, so they are no party to a fight;
88
+ // game: named by engine.debug.watch; turn*: the writer last seen, across frames
89
+ const newRec = (why, name = null) => ({ id: page.nextId++, at: null, why, seen: 0, wrote: -1, f: -1, n: 0, usual: 0, next: 0, sample: true, placeKey: null, placeAt: null, placeBy: null, fought: false, fight: null, name, ownBy: null, ownAt: null, last: null,
90
+ history: [], same: null, close: false, owned: false, game: false, turnKey: null, turnAt: null, turnBy: null, turns: 0, turnFrom: -Infinity });
91
+ const real = r => r.same ?? r;
72
92
  const who = name => name ? `part '${name}'` : 'code outside any part';
73
93
 
74
94
  class Writers {
@@ -87,7 +107,8 @@ class Writers {
87
107
  this.addedBy = new WeakMap(); // thing -> part
88
108
  this.top = new Map(); // 'fog.far' -> record (scene, fog and renderer values)
89
109
  this.parts = new WeakMap(); // light or material -> { intensity: record, ... }
90
- this.done = new WeakSet(); // a Color or Vector3 already watched (a color shared by two objects answers for the first)
110
+ this.hooked = new WeakMap(); // object -> Map(key -> record): one accessor per property, so a second record of it (a color two objects share, an owned value that is also a picture value) answers through the first
111
+ this.shared = new Map(); // shared point -> its history (no record: nothing is hooked)
91
112
  const s = e.scene, r = e.renderer;
92
113
  this.number(r, 'toneMapping', this.named('renderer.toneMapping', NOT.start));
93
114
  this.number(r, 'toneMappingExposure', this.named('renderer.toneMappingExposure', NOT.start));
@@ -105,14 +126,20 @@ class Writers {
105
126
  const m = /** @type {any} */ (o).material;
106
127
  if (m) for (const x of [].concat(m)) this.material(x);
107
128
  } });
129
+ for (const o of e._owned?.values() ?? []) this.owned(o); // the view's values exist before this tool does
108
130
  }
109
131
 
110
132
  named(label, why) { const r = newRec(why, () => label); this.top.set(label, r); return r; }
111
133
 
112
134
  /** Own accessor for one plain value; false when the object has none to replace. Reads and writes pass straight through */
113
135
  slot(o, key, rec, after) {
136
+ let mine = this.hooked.get(o);
137
+ const had = mine?.get(key);
138
+ if (had) { if (had !== rec) rec.same = real(had); return true; }
114
139
  const d = Object.getOwnPropertyDescriptor(o, key);
115
140
  if (!d || !('value' in d) || !d.configurable) { if (rec.why !== NOT.none || !d) rec.why = NOT.own; return false; }
141
+ if (!mine) this.hooked.set(o, mine = new Map());
142
+ mine.set(key, rec);
116
143
  let v = d.value;
117
144
  const t = this;
118
145
  Object.defineProperty(o, key, { configurable: true, enumerable: d.enumerable, get: () => v,
@@ -121,10 +148,46 @@ class Writers {
121
148
  }
122
149
  number(o, key, rec) { this.slot(o, key, rec); }
123
150
  /** The components of a Color or Vector3, all reporting to one record: to the game it is one value */
124
- watch(c, keys, rec) {
125
- if (this.done.has(c)) return;
126
- this.done.add(c);
127
- for (const k of keys) this.slot(c, k, rec);
151
+ watch(c, keys, rec) { for (const k of keys) this.slot(c, k, rec); }
152
+ /** A value changed in place, or a plain property; false when there is nothing to hook */
153
+ hook(rec, o, key) {
154
+ const c = partsOf(o) ? o : key != null && partsOf(o?.[key]) ? o[key] : null;
155
+ if (c) { this.watch(c, partsOf(c), rec); return true; }
156
+ return key != null && !!o && this.slot(o, key, rec);
157
+ }
158
+
159
+ /** An engine-written value (core/ops/owned.js): spec.objects names what it lives on, and its key is the property where there is one (view.pixelRatio has none: the renderer keeps it private) */
160
+ owned(o) {
161
+ if (page.off) return;
162
+ const rec = this.top.get(o.id) ?? this.named(o.id, NOT.start); // a module reinstalled: same name, maybe new objects, and the history goes on
163
+ let any = false;
164
+ for (const x of o.objects) any = this.hook(rec, x, o.key) || any;
165
+ if (!rec.at) rec.why = any ? NOT.start : NOT.hidden;
166
+ real(rec).close = real(rec).owned = true;
167
+ }
168
+ /** The last line outside the engine that wrote this owned value, for the yield warning and describe().owned. Null when no look saw it @param {string} id */
169
+ outside(id) {
170
+ const r = this.top.get(id);
171
+ return r ? real(r).history.findLast(x => !x.engine)?.at ?? null : null;
172
+ }
173
+ /** A take on a shared point (sharedPoint.js). No stack: the entry already holds its line @param {string} name @param {{ owner: string, where: string | null }} ent */
174
+ sharedTook(name, ent) {
175
+ if (page.off) return;
176
+ let h = this.shared.get(name);
177
+ if (!h) this.shared.set(name, h = []);
178
+ remember(h, { at: ent.where, frame: this.frame, owner: ent.owner });
179
+ }
180
+ /** engine.debug.watch: a game's own value, the same record as any other. A name in use is refused: it would hide what that name answers @param {string} label @param {any} o @param {string} [key] */
181
+ watchNamed(label, o, key) {
182
+ const old = this.top.get(label);
183
+ if (page.off || (old && !old.game)) return { watching: false, remove() {} };
184
+ const rec = this.named(label, NOT.none);
185
+ rec.game = true;
186
+ const watching = this.hook(rec, o, key);
187
+ if (!watching) rec.why = NOT.hidden;
188
+ real(rec).close = true;
189
+ // the accessors stay, like threePatches.off: they pass values through, and another record may be answering through them
190
+ return { watching, remove: () => { if (this.top.get(label) === rec) this.top.delete(label); real(rec).close = false; } };
128
191
  }
129
192
  /** A color held in a property: the components, and the property itself (light.color = other replaces the object the components were on) */
130
193
  color(o, key, rec) {
@@ -164,9 +227,9 @@ class Writers {
164
227
  }
165
228
 
166
229
  /** The hot path: runs on every write that changed a value. No stack unless the header's rules ask for one */
167
- wrote(rec) {
230
+ wrote(hit) {
168
231
  if (page.off || this.drawing || this.e._probing) return;
169
- const fr = this.frame;
232
+ const rec = real(hit), fr = this.frame;
170
233
  rec.wrote = fr;
171
234
  if (rec.f !== fr) {
172
235
  const cold = fr - rec.f > 1;
@@ -176,19 +239,35 @@ class Writers {
176
239
  }
177
240
  rec.n++;
178
241
  if (!rec.sample) {
179
- if (rec.n <= rec.usual) return;
180
- rec.sample = true; rec.next = fr + 1; // more writes than usual: this one may be a new writer; next frame sees all of them from the first
242
+ const more = rec.n > rec.usual;
243
+ if (!more && !(rec.close && rec.n === 1)) return;
244
+ if (more) { rec.sample = true; rec.next = fr + 1; } // more writes than usual: this one may be a new writer; next frame sees all of them from the first
181
245
  }
182
- rec.usual = rec.n;
246
+ rec.usual = Math.max(rec.usual, rec.n);
183
247
  this.stacks++;
184
248
  const w = writerNow();
185
249
  rec.seen = fr;
186
250
  if (!w) { rec.at = null; rec.why = NOT.noFile; rec.placeKey = null; return; }
251
+ if (rec.owned && engineFile(w.file)) w.engine = true; // a module's write to an engine-owned value is the engine's: yielding is the rule there, not a fight
187
252
  const by = this.partsOf(w);
188
253
  this.claim(rec, w, by);
254
+ remember(rec.history, { at: w.at, frame: fr, part: by[0], engine: w.engine });
255
+ rec.at = w.at; rec.why = null;
256
+ if (w.engine) return; // the engine is no party to a fight: it yields, or it is a debug view
189
257
  const place = `${w.key}|${by[0] ?? ''}`; // the part too: two parts' anonymous hooks in one file are two places
190
- if (!w.engine && fr > 0 && rec.placeKey && rec.placeKey !== place && !rec.fought) this.fight(rec, rec.placeAt, rec.placeBy, w.at, by[0]);
191
- rec.at = w.at; rec.why = null; rec.placeKey = place; rec.placeAt = w.at; rec.placeBy = by[0] ?? null;
258
+ if (fr > 0 && rec.placeKey && rec.placeKey !== place && !rec.fought) this.fight(rec, rec.placeAt, rec.placeBy, w.at, by[0], 'frame');
259
+ this.turn(rec, place, w.at, by[0] ?? null, fr);
260
+ rec.placeKey = place; rec.placeAt = w.at; rec.placeBy = by[0] ?? null;
261
+ }
262
+
263
+ /** The writer seen changed since the last look: often enough, in a short enough time, and it is a fight that never shares a frame */
264
+ turn(rec, place, at, by, fr) {
265
+ const was = rec.turnKey, wasAt = rec.turnAt, wasBy = rec.turnBy;
266
+ rec.turnKey = place; rec.turnAt = at; rec.turnBy = by;
267
+ if (rec.fought || fr === 0 || !was || was === place) return;
268
+ rec.next = fr + 1;
269
+ if (fr - rec.turnFrom > WINDOW) { rec.turnFrom = fr; rec.turns = 0; }
270
+ if (++rec.turns >= TURNS) this.fight(rec, wasAt, wasBy, at, by, 'turns');
192
271
  }
193
272
 
194
273
  /** The parts this write can be from: the running module alone, else every part that ran from a file on the stack, nearest first */
@@ -271,12 +350,12 @@ class Writers {
271
350
  warnOnce(coded('picture-leftover', fmt(STRINGS.leftover, { name: m.name, list })), `picture-leftover\0${m.name}\0${list}`);
272
351
  }
273
352
 
274
- fight(rec, first, firstBy, second, secondBy) {
353
+ fight(rec, first, firstBy, second, secondBy, how) {
275
354
  rec.fought = true;
276
- const label = this.labelOf(rec) ?? 'a picture value', slot = slotOfValue(label);
355
+ const label = this.labelOf(rec) ?? 'a watched value';
277
356
  const said = (at, by) => by ? `${at} (part '${by}')` : at;
278
- this.fights.push({ value: label, first, second, ...(firstBy ? { firstBy } : {}), ...(secondBy ? { secondBy } : {}) });
279
- warnOnce(coded('picture-conflict', fmt(STRINGS.conflict, { value: label, first: said(first, firstBy), second: said(second, secondBy), claim: slot ? fmt(STRINGS.claim, { slot }) : '' })), `picture-conflict\0${rec.id}`);
357
+ this.fights.push(rec.fight = { value: label, how, first, second, ...(firstBy ? { firstBy } : {}), ...(secondBy ? { secondBy } : {}) });
358
+ warnOnce(coded('picture-conflict', fmt(STRINGS.conflict, { value: label, how: HOW[how], first: said(first, firstBy), second: said(second, secondBy) })), `picture-conflict\0${rec.id}`);
280
359
  }
281
360
 
282
361
  /** Every value with a name, in one pass: lights and materials are found through the scene, so their names are the current ones */
@@ -300,9 +379,10 @@ class Writers {
300
379
  for (const m of mats) add('material', m, m.name || `${m.type}-${m.uuid.slice(0, 6)}`);
301
380
  return out;
302
381
  }
303
- labelOf(rec) { for (const [k, r] of this.everyValue()) if (r === rec) return k; return null; }
382
+ labelOf(rec) { for (const [k, r] of this.everyValue()) if (real(r) === rec) return k; return null; }
304
383
 
305
- answer(r) {
384
+ answer(hit) {
385
+ const r = real(hit);
306
386
  if (!r.at) return { at: null, note: r.why };
307
387
  return { at: r.at, framesAgo: this.frame - r.seen, ...(r.wrote > r.seen ? { writtenSince: true } : {}), ...(r.last ?? {}) };
308
388
  }
@@ -311,19 +391,23 @@ class Writers {
311
391
  const values = {};
312
392
  let mats = 0, more = 0;
313
393
  for (const [k, r] of this.everyValue()) {
314
- if (k.startsWith('material:')) { if (!r.at) continue; if (++mats > MATERIALS_MAX) { more++; continue; } }
394
+ if (k.startsWith('material:')) { if (!real(r).at) continue; if (++mats > MATERIALS_MAX) { more++; continue; } }
315
395
  values[k] = this.answer(r);
316
396
  }
317
- return { tracked: true, frame: this.frame, stacks: this.stacks, values, conflicts: this.fights, held: this.held.map(({ key, ...h }) => h), leftovers: this.leftovers, ...(more ? { moreMaterials: more } : {}) };
397
+ return { tracked: true, limit: LIMIT, frame: this.frame, stacks: this.stacks, values, conflicts: this.fights, held: this.held.map(({ key, ...h }) => h), leftovers: this.leftovers, ...(more ? { moreMaterials: more } : {}) };
318
398
  }
319
- /** One value by its describe name @param {string} label */
399
+ /** One value by its describe name, a shared point's name or a name given to engine.debug.watch @param {string} label */
320
400
  why(label) {
321
- const all = this.everyValue(), r = all.get(label);
322
- if (!r) return { ok: false, text: `${label}: not tracked. Tracked names (describe('picture').writers): ${[...all.keys()].filter(k => !k.startsWith('material:')).join(', ')}, material:<name>.color / emissive / opacity / emissiveIntensity`, detail: null };
323
- const a = this.answer(r), fight = this.fights.find(f => f.value === label);
401
+ if (page.off) return { ok: false, text: `${label}: not tracked: threePatches.off('picture-writers') turned this off`, detail: null };
402
+ const hit = this.everyValue().get(label);
403
+ if (!hit && this.e.stacks.has(label)) return sharedAnswer(this.e, label, this.shared.get(label) ?? []);
404
+ if (!hit) return { ok: false, text: `${label}: not tracked, so nothing is known about its writers. Names: describe('picture').picture.writers; any value: engine.debug.watch('${label}', object, 'key')`, detail: null };
405
+ const r = real(hit), a = this.answer(hit), fight = r.fight, slot = slotOfValue(label);
324
406
  const owner = !a.slot ? '' : a.writer === 'holder' ? `, by part '${a.holder}', which holds ${a.slot}` : `, by ${who(a.by)}, a stray write: part '${a.holder}' holds ${a.slot}`;
325
407
  const age = a.framesAgo ? `, looked at ${a.framesAgo} frames ago${a.writtenSince ? ' (written since, not looked at)' : ''}` : '';
326
- return { ok: !!a.at, text: `${label}: ${a.at ? `last changed at ${a.at}${owner}${age}` : a.note}${fight ? `. Two writers in one frame: ${fight.first}, then ${fight.second}` : ''}`, detail: { ...a, ...(fight ? { conflict: fight } : {}) } };
408
+ const end = fight ? `Two writers ${HOW[fight.how]}: ${fight.first} and ${fight.second}. ${fmt(STRINGS.fix, { claim: slot ? fmt(STRINGS.claim, { slot }) : '' })}` : `No fight seen; ${LIMIT}`;
409
+ const text = [`${label}: ${a.at ? `last changed at ${a.at}${owner}${age}` : a.note}`, historyText(r.history), end].filter(Boolean).join('. ');
410
+ return { ok: !!a.at, text, detail: { ...a, history: r.history, ...(fight ? { conflict: fight } : {}) } };
327
411
  }
328
412
 
329
413
  /** Top of a frame's hooks. Two frame hooks with no draw between (engine.step many frames, one draw) are two frames: a state change between them is no fight */
@@ -335,8 +419,8 @@ class Writers {
335
419
 
336
420
  /** @param {any} e */
337
421
  export function installPictureWriters(e) {
338
- notePatch('picture-writers', 'dev server only: intensity, color, position of lights, scene.fog and its values, renderer.toneMapping / toneMappingExposure, scene.environment / background and their intensities, material color / emissive / opacity: an own get / set on each, and on the r g b / x y z of the Color or Vector3 (core/inspect/pictureWriters.js)',
422
+ notePatch('picture-writers', 'dev server only: intensity, color, position of lights, scene.fog and its values, renderer.toneMapping / toneMappingExposure, scene.environment / background and their intensities, material color / emissive / opacity, the camera and other values the engine writes on its own (describe().owned), and values named with engine.debug.watch: an own get / set on each, and on the components of a Color, Vector or rotation (core/inspect/pictureWriters.js)',
339
423
  () => { page.off = true; }, // accessors already placed stay and only pass values through; new objects get none
340
- { scope: 'objects in the scene', lost: "describe('picture').writers stops answering, and two writers in one frame are no longer warned about" });
424
+ { scope: 'objects in the scene', lost: "describe('picture').writers and explain({ value }) stop answering, engine.debug.watch watches nothing, and two writers are no longer warned about" });
341
425
  e._picture = new Writers(e);
342
426
  }
@@ -0,0 +1,21 @@
1
+ // engine._tools: the one door packages/tools has into the engine's internals, for what no game needs: draw a frame while halted, run the frame hooks, hand a halt back, read the
2
+ // frame cost. Why a door and not the private names: about twenty sites in tools called them directly, so renaming one in core broke a tool with no error until it ran. Now core can
3
+ // rename freely behind these words, and rule R68 fails any other reach from packages/tools. Internal: on no public page, not in the types.
4
+ /** @param {any} e @returns {any} */
5
+ export const toolDoor = e => ({
6
+ /** Draw one frame; hooks false leaves the frame hooks out @param {number} dt @param {boolean} [hooks] */
7
+ render: (dt, hooks) => e._render(dt, hooks),
8
+ /** Run the frame hooks with no draw, the way a halted frame does @param {number} dt @param {boolean} [halted] */
9
+ frameHooks: (dt, halted) => e._frameHooks(dt, halted),
10
+ /** Hand back the halt this owner took @param {string} owner */
11
+ resume: owner => e._unhalt(owner),
12
+ /** Main-thread ms of the last real-time frame */
13
+ get cpuMs() { return e._cpuMs ?? 0; },
14
+ /** What the light watch saw (lightWatch.js) */
15
+ get lightWatch() { return e._lightWatch; },
16
+ /** The picture check is rendering: what it changes and puts back is not the game's */
17
+ get probing() { return e._probing; },
18
+ set probing(on) { e._probing = on; },
19
+ /** Whether a material is a debug view's stand-in, not one of the game's @param {any} m */
20
+ standIn: m => !!m?.userData?._dbgOf,
21
+ });
@@ -0,0 +1,35 @@
1
+ // The small, plain half of the writers tool (core/inspect/pictureWriters.js): one value's history and the words that report it.
2
+ //
3
+ // Why a short history and not only "last writer": two writers that take turns look like one writer to whoever asks at the wrong moment. Why runs of one line
4
+ // and not one row per write: a value written every frame would push everything else out in a few frames, and the older line is the one being looked for.
5
+ //
6
+ // Why every answer without a fight carries LIMIT: an open engine cannot prove two pieces of plain code never meet (docs/design.md 4.6), and an AI reads
7
+ // "no conflicts" as "safe". Only watched values are seen, a write that changes nothing is invisible, and most values are only looked at now and then.
8
+ const KEEP = 8; // runs kept per value: enough to show two writers alternating, small enough to read in one line
9
+ export const LIMIT = 'none seen is not proof of none: only watched values are seen, and writes are sampled';
10
+
11
+ /**
12
+ * What can be hooked inside a value: three.js changes these in place, so a hook on the property that holds them would see nothing. Quaternion and Euler keep theirs in
13
+ * underscore fields behind prototype accessors, and those fields are what an own get / set can sit on.
14
+ * @param {any} v @returns {string | string[] | null}
15
+ */
16
+ export const partsOf = v => v?.isColor ? 'rgb' : v?.isVector3 ? 'xyz' : v?.isVector2 ? 'xy' : v?.isQuaternion ? ['_x', '_y', '_z', '_w'] : v?.isEuler ? ['_x', '_y', '_z'] : null;
17
+
18
+ /** Add one seen write to a history: the same line again extends its run @param {any[]} h @param {{ at: string | null, frame: number, part?: string | null, owner?: string, engine?: boolean }} w */
19
+ export function remember(h, { at, frame, part, owner, engine }) {
20
+ const top = h[h.length - 1];
21
+ if (top?.at === at && top?.owner === owner) { top.lastFrame = frame; top.times++; return; }
22
+ h.push({ at, frame, lastFrame: frame, times: 1, ...(part ? { part } : {}), ...(owner ? { owner } : {}), ...(engine ? { engine } : {}) });
23
+ if (h.length > KEEP) h.shift();
24
+ }
25
+
26
+ const run = r => `${r.at ?? 'an unknown line'}${r.owner ? ` (${r.owner})` : r.engine ? ' (engine)' : r.part ? ` (part '${r.part}')` : ''} frame ${r.frame}${r.times > 1 ? `, ${r.times} looks to frame ${r.lastFrame}` : ''}`;
27
+ /** The last runs, newest first, as one clause @param {any[]} h */
28
+ export const historyText = h => h.length ? `Seen: ${h.slice(-3).reverse().map(run).join('; ')}` : '';
29
+
30
+ /** explain's answer for a shared point: it composes, so its entries and their lines are the whole story of the point, not of what it drives @param {any} e @param {string} label @param {any[]} h */
31
+ export function sharedAnswer(e, label, h) {
32
+ const row = e.stacks.get(label).row();
33
+ const text = [`${label}: shared point, now ${JSON.stringify(row.value)}, led by ${row.writer}${row.at ? ` (${row.at})` : ''}${row.how ? `, ${row.how}` : ''}`, historyText(h), 'Direct writes to what it drives are not seen here'];
34
+ return { ok: true, text: text.filter(Boolean).join('. '), detail: { ...row, history: h } };
35
+ }
package/core/ops/Ops.js CHANGED
@@ -19,6 +19,7 @@ import { failure, isStructured, opsBlocked } from './opsFail.js';
19
19
  import { runOp } from './opsRun.js';
20
20
  import { newRing, logEntry, recentEntries } from './opsHistory.js';
21
21
  import { defaultsOf, withDefaults } from '../base/params.js';
22
+ import { reportError } from '../base/errors.js';
22
23
 
23
24
  const STRINGS = {
24
25
  dup: "ops.define('{name}'): already defined. To replace it call remove() on the handle define returned first",
@@ -44,7 +45,7 @@ export class Ops {
44
45
  /** @internal */ this._inCan = null;
45
46
  /** @internal > 0 while state may be written without an op (save load, applyState, net sync) */ this._allowDepth = 0;
46
47
  /** @internal request counter (net replies carry it) */ this._seq = 0;
47
- /** @internal ctx of the innermost running op (nested ops inherit source and actor) */ this._last = null;
48
+ /** @internal ctx of the innermost running op (nested ops inherit source, actor and session) */ this._last = null;
48
49
  /** @internal set through route() (net clients): (def, args, opts) => result to return instead of running locally, or null to run here */ this._route = null;
49
50
  /** @internal true while route() is held: every write outside allow() is reported, even in fixed steps and ops (own movement, world.move, excepted) */ this._client = false;
50
51
  /** Counter that only goes up: each committed op, undo, load and rollback bumps it (a failed op that changed nothing does not); every run result carries it, so "did anything change since I looked" is one compare */
@@ -78,7 +79,7 @@ export class Ops {
78
79
  * run (and can) may fail with { ok: false, code, facts, nextActions } (facts: object or list [{ id, field, actual, expected? }]); nextActions are the game's own suggestions.
79
80
  * owner (optional, checked by net() for peer requests): args => world record id whose `owner` field must equal the requesting actor.
80
81
  * @param {string} name
81
- * targets (optional): the thing ids, kinds or template names this op is for; engine.thing(id).explain().ops lists it ('*' = any thing).
82
+ * targets (optional): the thing ids, kinds or template names this op is for; engine.explain({ thing: id }).ops lists it ('*' = any thing).
82
83
  * @param {{ run: (e: any, args: any, ctx: OpContext) => any, can?: (e: any, args: any, ctx: OpContext) => true | string | { code: string, facts?: object, nextActions?: { op: string, args?: object }[] }, targets?: string | string[], args?: Record<string, string | { type: string, default?: any, min?: number, max?: number, values?: any[], desc?: string, optional?: boolean }>, offers?: (e: any, ctx: OpContext) => object[], reasons?: Record<string, string>, desc?: string, undo?: (e: any, args: any, value: any) => void, net?: 'peer' | 'local', owner?: (args: any) => string, atomic?: boolean, after?: (e: any, args: any, value: any, ctx: OpContext) => void }} def
83
84
  * @returns {{ remove(): void }}
84
85
  * @example
@@ -128,6 +129,7 @@ export class Ops {
128
129
 
129
130
  /**
130
131
  * Reverse a finished op with the undo(e, args, value) its definition declared: pass the same args and the value run returned.
132
+ * canUndo(e, args, value) in the definition answers like can (true, a reason, a structured failure) when the world may have moved on so far that it cannot be reversed.
131
133
  * Returns { ok: true }, or { ok: false, code: 'noUndo', facts: { op }, nextActions } when the op did not declare undo. The undo runs as an op write (the dev guard stays quiet).
132
134
  * @example const r = engine.ops.run('inventory.trade', { take: 'rusty_key', give: 'gold_key' }); engine.ops.undo('inventory.trade', { take: 'rusty_key', give: 'gold_key' }, r.value);
133
135
  * @param {string} name
@@ -142,12 +144,30 @@ export class Ops {
142
144
  if (typeof d.undo !== 'function') return this._res(failure({ code: 'noUndo', facts: { op: name }, nextActions: [] }));
143
145
  const blocked = opsBlocked(this.engine); // as run: a load in progress or a gameplay error
144
146
  if (blocked) return this._res(failure(blocked));
147
+ // as run: a broken op is reported and answered, a thrown error is not the caller's to catch
148
+ const broke = err => { if (err?.opsDevError) throw err; reportError(this.engine, err, `ops.undo('${name}')`); return this._res(failure('error')); };
149
+ let no;
150
+ try { no = d.canUndo?.(this.engine, args, value) ?? true; } catch (err) { return broke(err); }
151
+ if (no !== true) return this._res(failure(no)); // as can: answered, and nothing changed, so the revision stays
152
+ const ctx = this._ctx(name, args, opts, this._stack.length ? this._last : null);
145
153
  this._allowDepth++;
146
- // the op's code is the defining module's, not the caller's (run)
147
- try { asModule(this.engine, null, () => d.undo(this.engine, args, value, this._ctx(name, args, opts, null))); } finally { this._allowDepth--; }
148
- this.revision++; // the state changed: "did anything change since I looked" must see it
154
+ try {
155
+ // the op's code is the defining module's, not the caller's (run)
156
+ asModule(this.engine, null, () => this._as(name, ctx, () => d.undo(this.engine, args, value, ctx)));
157
+ } catch (err) {
158
+ return broke(err);
159
+ } finally {
160
+ this._allowDepth--;
161
+ this.revision++; // the state changed, a half-done undo too: "did anything change since I looked" must see it
162
+ }
149
163
  return { ok: true };
150
164
  }
165
+ /** @internal Run fn as part of op `name` with its ctx, when the op is not on the stack (undo, an after hook held for the commit, a use after a walk): nested ops, ops.actor and content words read it */
166
+ _as(name, ctx, fn) {
167
+ const prev = this._last;
168
+ this._stack.push(name); this._last = ctx;
169
+ try { return fn(); } finally { this._stack.pop(); this._last = prev; }
170
+ }
151
171
 
152
172
  /**
153
173
  * Ask without doing: runs only can (no state change, no history). For greying out buttons and input buffers.
@@ -166,7 +186,12 @@ export class Ops {
166
186
  const blocked = opsBlocked(this.engine);
167
187
  if (blocked) return this._res(failure(blocked));
168
188
  let res;
169
- try { res = this._can(d, args, ctx); } catch (err) { if (err?.opsDevError) throw err; res = 'error'; }
189
+ try { res = this._can(d, args, ctx); } catch (err) {
190
+ if (err?.opsDevError) throw err;
191
+ // soft: buttons and describe() ask every frame, and asking must not freeze a game; the run path stops it. The reason stays in the answer
192
+ reportError(this.engine, err, `ops.can('${name}')`, { soft: true });
193
+ res = { code: 'error', facts: { message: String(err?.message ?? err) } };
194
+ }
170
195
  return this._res(res === true ? { ok: true } : failure(res));
171
196
  }
172
197
 
@@ -279,7 +304,7 @@ export class Ops {
279
304
  if (!SOURCES.includes(source)) throw devError(fmt(STRINGS.badSource, { name, source }));
280
305
  if (args) checkArgs(e, this.defs.get(name), args);
281
306
  }
282
- return { source, actor: opts?.actor ?? parent?.actor ?? e.actor, tick: e.time.tick, frozen: e.frozen };
307
+ return { source, actor: opts?.actor ?? parent?.actor ?? e.actor, tick: e.time.tick, frozen: e.frozen, session: parent?.session ?? e.session.id };
283
308
  }
284
309
  /** @internal returns true or a reason string */
285
310
  _can(d, args, ctx) {
@@ -10,23 +10,36 @@
10
10
  // order) < cutscene (timeline) < physics (a ragdoll: nothing can steer a limp body, a cutscene included) < net (a character another machine
11
11
  // drives: held for good, nobody else may take it)
12
12
  // - the highest layer is in charge; the ones below are paused, not cancelled: when it ends they carry on (a walk resumes after a cutscene)
13
- // - one owner per layer: a second, different owner on the same layer throws control-conflict in dev naming both (release: the later wins, the
14
- // earlier is dropped, warned once). The same owner taking again replaces its own hold.
13
+ // - one owner per layer: a second, different owner on the same layer throws control-conflict naming both, in every build, and the first keeps
14
+ // the character. The same owner taking again replaces its own hold.
15
15
  // - a character with any holder moves only through its holder: the step function, or the handle's move(). A direct character.move() from
16
16
  // anyone else throws control-bypass in dev. A character nobody holds (a hand-built Character in a test) moves freely.
17
17
  // - "who decides where to go" (this) is not "how the body moves" (character.mover: simple / rapier / manual); the two never mix.
18
+ // - a hold given task(why) is a task: it runs until something in TASK_ENDS happens to the ground under it. Pausing below a higher holder does not end it.
18
19
  // Kept by id, not by model: an NPC's model is torn down and rebuilt as it goes far and near; the hold stays with the NPC. The slot is dropped when
19
20
  // the world record goes (world:remove) or a record-less character is disposed. Not saved: holders are code (a running walk, a cutscene), retaken
20
21
  // by that code after a load.
21
- import { codedError, coded } from '../base/errorHints.js';
22
- import { DEV, warnOnce } from '../base/validate.js';
22
+ import { codedError } from '../base/errorHints.js';
23
+ import { DEV } from '../base/validate.js';
23
24
  import { callerAt } from './stackFrames.js';
24
25
  import { STEP } from '../time/time.js'; // the fixed step: handle.move()'s dt when none is given
26
+ import { reportError } from '../base/errors.js';
25
27
 
26
28
  /** Control layers, lowest first (see the header) */
27
29
  const CONTROL_LAYERS = { base: 0, script: 1, cutscene: 2, physics: 3, net: 4 };
28
30
  const LAYER_NAMES = Object.keys(CONTROL_LAYERS);
29
31
 
32
+ /** @internal What ends a task on a slot, and who says so. The one list: a task subscribes to nothing itself, so a new ending is a row here and a call to endTasks. Pause, freeze and a cutscene only suspend */
33
+ export const TASK_ENDS = {
34
+ replaced: 'the state it ran in is gone: a load, a new game, quit (control hears them itself)',
35
+ level: 'the level changed (characters: level:loaded, level:unloaded)',
36
+ placed: 'a placement: character.placeAt, npc.placeAt, a write to its record',
37
+ seated: 'it sat down in a vehicle',
38
+ physics: 'a hold on layer physics took the body: nothing can steer it (take does this)',
39
+ gone: 'its character left: disposed, or its record removed',
40
+ order: 'a newer order replaces it (walkTo: one walk per character)',
41
+ };
42
+
30
43
  const idOf = who => (typeof who === 'string' ? who : who?.id);
31
44
 
32
45
  /** engine.control (made for every engine in services.js; the characters module tells it how to find a character by id) */
@@ -37,18 +50,21 @@ export class Control {
37
50
  /** @internal the entry whose move is running now (handle.move / a behaviour run): the one caller character.move() lets through */ this._cur = null;
38
51
  /** @internal id -> Character; set by the characters module through resolveWith (core names no module) */ this.characterOf = () => null;
39
52
  engine.events.on('world:remove', ({ id }) => this.forget(id));
53
+ // Two moments, and state:replaced is neither. session:end: the old playthrough stops, before anything is replaced, so no walk runs on into the swap. save:loaded: a save landed on a
54
+ // running playthrough, the only word a direct apply gives. state:replaced comes last, after the save:loaded and session:start listeners that start the new state's walks: it would end them
55
+ for (const n of ['save:loaded', 'session:end']) engine.events.on(n, () => this.endTasks(null, 'replaced'));
40
56
  }
41
57
  /**
42
- * Take a character's control. step (optional): (dt, character) => ({ x, z, run? }) | null | false, called each fixed step while this owner is in
58
+ * Take a character's control. step (optional): (dt, character) => ({ x, y?, z, run? }) | null | false, called each fixed step while this owner is in
43
59
  * charge (dt on the character's time channel): a direction moves it, null stands still (gravity and the idle pose go on), false skips the
44
60
  * move this step (you placed it yourself). Without step, move it with handle.move(x, z, run, dt), which does nothing while paused.
45
61
  * @param {any} who a Character, an NPC handle or a character id ('player', an NPC id)
46
- * @param {{ owner: string, layer?: 'base' | 'script' | 'cutscene' | 'physics' | 'net', step?: (dt: number, ch: any) => ({ x: number, z: number, run?: boolean } | null | false | void) }} o
62
+ * @param {{ owner: string, layer?: 'base' | 'script' | 'cutscene' | 'physics' | 'net', step?: (dt: number, ch: any) => ({ x: number, y?: number, z: number, run?: boolean } | null | false | void) }} o
47
63
  * @returns {{ owner: string, layer: string, id: string, readonly active: boolean, move(x: number, z: number, run?: boolean, dt?: number): boolean, remove(): void }}
48
64
  * @example const h = engine.control.take(player, { owner: 'tutorial', layer: 'script', step: () => ({ x: 0, z: 1 }) }); ... h.remove();
49
65
  */
50
66
  take(who, o = {}) {
51
- const id = idOf(who), { owner, layer = 'script', step = null } = o;
67
+ const id = idOf(who), { owner, layer = 'script', step = null, task = null } = o;
52
68
  if (!id || typeof id !== 'string') throw codedError('control-layer', `engine.control.take(character, { owner }): pass a character, an NPC handle or an id like 'player', got ${String(who)}`);
53
69
  if (!owner || typeof owner !== 'string') throw codedError('control-layer', `engine.control.take('${id}', { owner }): owner is a non-empty string naming who drives it, e.g. 'escort-quest', got ${JSON.stringify(owner)}`);
54
70
  if (!(layer in CONTROL_LAYERS)) throw codedError('control-layer', `engine.control.take('${id}', { layer }): layer is one of ${LAYER_NAMES.join(' < ')}, got ${JSON.stringify(layer)}`);
@@ -62,32 +78,35 @@ export class Control {
62
78
  if (e.layer === 'net') throw codedError('control-net', `character '${id}' is driven by another machine (held by '${e.owner}'), so '${owner}' cannot take it. `
63
79
  + `Fix: change it where it is driven: run an op the host runs (engine.ops.run(...)), or take the character that is yours (engine.player)`);
64
80
  if (e.layer !== layer) continue;
65
- const msg = `character '${id}': two owners want layer '${layer}': '${e.owner}'${e.at ? ` (${e.at})` : ''} and '${owner}'${at ? ` (${at})` : ''}. `
81
+ throw codedError('control-conflict', `character '${id}': two owners want layer '${layer}': '${e.owner}'${e.at ? ` (${e.at})` : ''} and '${owner}'${at ? ` (${at})` : ''}. `
66
82
  + `Rule: one owner per layer, so nothing silently decides which one steers. Fix, one of: (1) end the old one first (its handle.remove()); `
67
- + `(2) take another layer: engine.control.take(ch, { owner: '${owner}', layer: '${layer === 'cutscene' ? 'script' : 'cutscene'}' }) (higher pauses lower)`;
68
- if (DEV) throw codedError('control-conflict', msg);
69
- warnOnce(coded('control-conflict', `${msg}. In this build the later one takes it`), `control-conflict:${id}:${e.owner}:${owner}`);
70
- m.delete(e.owner);
83
+ + `(2) take another layer: engine.control.take(ch, { owner: '${owner}', layer: '${layer === 'cutscene' ? 'script' : 'cutscene'}' }) (higher pauses lower)`);
71
84
  }
85
+ if (layer === 'physics') this.endTasks(id, 'physics');
72
86
  const old = m.get(owner);
73
87
  m.delete(owner); // a new object: the old handle goes stale, so its remove() cannot end the new hold
74
- const ent = { id, owner, layer, step, at: old ? old.at : at, ch: typeof who === 'object' && who?.move ? who : null };
88
+ const ent = { id, owner, layer, step, task, at: old ? old.at : at, ch: typeof who === 'object' && who?.move ? who : null };
75
89
  m.set(owner, ent);
76
90
  const self = this;
77
- return {
91
+ const hold = {
78
92
  owner, layer, id,
79
93
  /** true while this owner is in charge (highest layer); false while paused below a higher one, or after remove() */
80
94
  get active() { return self._top(id) === ent; },
81
- /** Move the character for this step (x, z: world direction, length 0-1 scales the speed). Does nothing and returns false while paused */
82
- move(x, z, run = false, dt = STEP) {
95
+ /** @internal true while this owner may place the body itself (a cutscene path): in charge, and no ragdoll or seat has the body, which is what makes character.move() refuse too */
96
+ get placing() { return self._top(id) === ent && !self._char(ent)?.bodyHeld; },
97
+ /** Move the character for this step (x, z: world direction, length 0-1 scales the speed; y: up or down, default 0, used by a mover that flies or swims). Does nothing and returns false while paused */
98
+ move(x, z, run = false, dt = STEP, y = 0) {
83
99
  if (self._top(id) !== ent) return false;
84
100
  const ch = self._char(ent);
85
101
  if (!ch) return false;
86
- self._drive(ent, () => ch.move(x, z, run, dt));
102
+ self._drive(ent, () => ch.move(x, z, run, dt, y));
87
103
  return true;
88
104
  },
89
- remove() { const mm = self._by.get(id); if (mm?.get(owner) === ent) { mm.delete(owner); if (!mm.size) self._by.delete(id); } },
105
+ remove() { self.engine.session._untrack(hold); const mm = self._by.get(id); if (mm?.get(owner) === ent) { mm.delete(owner); if (!mm.size) self._by.delete(id); ent.task?.('replaced'); } }, // a task's own ending removes its hold too and ignores this; here the playthrough ended the hold first
90
106
  };
107
+ // a hold taken during play is not saved and what ends it (a timer, a callback) dies with the playthrough, so it ends there too. Base and net holds stand for a character's whole life, not a move in it
108
+ if (this.engine.session.captured && layer !== 'base' && layer !== 'net') this.engine.session.track(hold);
109
+ return hold;
91
110
  }
92
111
  /**
93
112
  * Who controls a character now: { owner, layer, at?, waiting: [{ owner, layer }] } (waiting = paused below, highest first), or null.
@@ -99,14 +118,19 @@ export class Control {
99
118
  const waiting = [...this._by.get(id).values()].filter(e => e !== top).sort((a, b) => CONTROL_LAYERS[b.layer] - CONTROL_LAYERS[a.layer]).map(e => ({ owner: e.owner, layer: e.layer }));
100
119
  return { owner: top.owner, layer: top.layer, ...(top.at && { at: top.at }), waiting };
101
120
  }
102
- /** @internal the characters module tells control how to find a live Character by id (the player, an NPC's model) @param {(id: string) => any} fn */
121
+ /** @internal Tell every task on a slot (who null: on every slot) that the ground under it changed. Each decides what that means for it @param {any} who @param {keyof typeof TASK_ENDS} why */
122
+ endTasks(who, why) {
123
+ if (!(why in TASK_ENDS)) throw codedError('control-layer', `control.endTasks: '${why}' is not in TASK_ENDS (core/ops/control.js)`);
124
+ for (const m of who == null ? [...this._by.values()] : [this._by.get(idOf(who))]) for (const ent of m ? [...m.values()] : []) ent.task?.(why);
125
+ }
126
+ /** @internal a provider of characters tells control how to find a live character by id (the player, an NPC's model); what it answers with is characters/character.contract.js @param {(id: string) => any} fn */
103
127
  resolveWith(fn) { this.characterOf = fn; }
104
128
  /** True while owner holds the character (in charge or paused) @param {any} who @param {string} owner */
105
129
  has(who, owner) { return !!this._by.get(idOf(who))?.has(owner); }
106
130
  /** describe().control: every held character by id, as of() */
107
131
  describe() { const out = {}; for (const id of this._by.keys()) out[id] = this.of(id); return out; }
108
132
  /** Drop every hold on a character (its record left the world, or a record-less character was disposed) @param {string} id @experimental */
109
- forget(id) { this._by.delete(id); }
133
+ forget(id) { this.endTasks(id, 'gone'); this._by.delete(id); }
110
134
  /** @internal the entry in charge: highest layer, latest taker inside it (only one per layer in dev) */
111
135
  _top(id) {
112
136
  const m = this._by.get(id); if (!m) return null;
@@ -115,7 +139,7 @@ export class Control {
115
139
  return t;
116
140
  }
117
141
  /** @internal the Character an entry moves: the one passed in, if it is still the live one, else found by id (an NPC model rebuilt) */
118
- _char(ent) { const ch = ent.ch && !ent.ch._disposed ? ent.ch : this.characterOf(ent.id); return ch ?? null; }
142
+ _char(ent) { const ch = ent.ch && !ent.ch.disposed ? ent.ch : this.characterOf(ent.id); return ch ?? null; }
119
143
  /** @internal run fn as the entry's own move (checkMove reads _cur) */
120
144
  _drive(ent, fn) { const prev = this._cur; this._cur = ent; try { return fn(); } finally { this._cur = prev; } }
121
145
  /** @internal for drivers that call character.move inside their own code (an NPC behaviour): run fn as owner's move when it is in charge; false when paused */
@@ -134,9 +158,10 @@ export class Control {
134
158
  const ch = this._char(top);
135
159
  if (!ch) continue;
136
160
  const dt = T ? T.dt(ch.channel, ch.id) : STEP;
137
- const m = top.step(dt, ch);
161
+ let m;
162
+ try { m = top.step(dt, ch); } catch (err) { reportError(this.engine, err, `control step of '${top.owner}' on character '${id}'`); continue; } // the next character's holder is not to blame
138
163
  if (m === false || this._top(id) !== top) continue; // placed by hand this step, or the step handed control on (ended itself, something took it)
139
- this._drive(top, () => ch.move(m?.x ?? 0, m?.z ?? 0, !!m?.run, dt));
164
+ this._drive(top, () => ch.move(m?.x ?? 0, m?.z ?? 0, !!m?.run, dt, m?.y ?? 0));
140
165
  }
141
166
  }
142
167
  /** @internal dev check from character.move(): a held character moves only through its holder (the header's bypass rule) */