threedog 0.8.0 → 1.0.1

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 +223 -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
@@ -23,7 +23,7 @@ export function reportError(engine, err, key, { module = null, soft = false } =
23
23
  const message = String(err?.message ?? err);
24
24
  // code + fix + docs: what to do and which page to read; at: the line that threw (the message alone often does not say which callback line)
25
25
  engine.error = { where: key, message, ...errorInfo(err), at: firstFrame(err) };
26
- engine.freeze('error');
26
+ engine.freeze('error'); // until reload, a new game included: dev must not walk past a bug, and a new playthrough on top of it would hide it. Release builds keep running
27
27
  console.error(fmt(STRINGS.halted, { key }) + hintText(err?.code ? `[${err.code}]` : message), err);
28
28
  engine.events.emit('engine:error', engine.error);
29
29
  return;
@@ -53,10 +53,12 @@ export function watchRejections(engine) {
53
53
  /** An event listener threw (called by the event bus): counted as gameplay */
54
54
  export function reportListenerError(engine, name, err) { reportError(engine, err, fmt(STRINGS.listener, { name })); }
55
55
 
56
- /** Disable a picture / ui module: remove its fixed / frame / afterRender hooks */
56
+ /** Disable a picture / ui module: give back what it borrowed, remove its fixed / frame / afterRender hooks */
57
57
  function disableModule(engine, m, err) {
58
- if (engine.disabledModules.has(m.name)) return;
59
- engine.disabledModules.add(m.name);
58
+ const was = engine._modState.get(m.name);
59
+ if (was === 'disabled') return;
60
+ if (was !== 'failed') engine._modState.set(m.name, 'disabled'); // a failed init stays 'failed': that word is what blocks the modules that require it
61
+ engine._returnBorrowed(m.name);
60
62
  for (const k in engine._hooks) engine._hooks[k] = engine._hooks[k].filter(h => h.name !== m.name);
61
63
  console.error(fmt(STRINGS.disabled, { type: m.type, name: m.name }), err);
62
64
  engine.events.emit('module:disabled', { name: m.name, message: String(err?.message ?? err) });
@@ -25,6 +25,8 @@ export const ENGINE_EVENTS = [
25
25
  'camera:change',
26
26
  'character:jump',
27
27
  'character:launch',
28
+ 'link:enter',
29
+ 'link:exit',
28
30
  'character:fall',
29
31
  'character:model',
30
32
  'character:step',
@@ -45,11 +47,17 @@ export const ENGINE_EVENTS = [
45
47
  'quest:done',
46
48
  'quest:part',
47
49
  'quest:fail',
50
+ 'quest:unpaid',
51
+ 'content:failed',
48
52
  'photo:taken',
49
53
  'photo:denied',
50
54
  'trigger:enter',
51
55
  'trigger:exit',
56
+ 'level:loading',
52
57
  'level:loaded',
58
+ 'level:unloaded',
59
+ 'level:playable',
60
+ 'level:failed',
53
61
  'timeline:start',
54
62
  'timeline:end',
55
63
  'template:stage',
@@ -76,6 +84,8 @@ export const ENGINE_EVENTS = [
76
84
  'net:result',
77
85
  'engine:error',
78
86
  'module:disabled',
87
+ 'module:restored',
88
+ 'state:replaced',
79
89
  'vehicle:enter',
80
90
  'vehicle:exit',
81
91
  'flow:change',
@@ -0,0 +1,26 @@
1
+ // A copy of another owner's data, checked when it is read: rigid's mirror of the walls, a level's walls in the collision module, nav's obstacles, chunks on the ground.
2
+ // Why identity first and then version: a version counts per owner, so a new owner can match the old number with other data in it. Why on read: a frozen engine runs no
3
+ // step and a skip runs no frame, so a copy kept by hooks answers from the past exactly when a menu or a timer asks.
4
+
5
+ /**
6
+ * @internal sync(update) answers false while the copy is current; else it runs update(change), change being 'source' (another owner, or the first read: what was built in the
7
+ * old one is gone) or 'version' (the same owner changed), and answers change. The copy counts as current only once update returned: one that throws is built again by the next
8
+ * read. A read from inside update answers false, so a rebuild that asks its own owner does not start over. reset() makes the next read stale: the copy was thrown away.
9
+ * @template S @param {() => S} source who holds the data now @param {(s: S) => any} [version] that owner's change count
10
+ */
11
+ export function follows(source, version) {
12
+ let held, at, read = false, busy = false;
13
+ return {
14
+ sync(update) {
15
+ if (busy) return false;
16
+ const s = source(), v = version?.(s);
17
+ if (read && s === held && v === at) return false;
18
+ const change = read && s === held ? 'version' : 'source';
19
+ busy = true;
20
+ try { update(change); } finally { busy = false; }
21
+ held = s; at = v; read = true;
22
+ return change;
23
+ },
24
+ reset() { read = false; },
25
+ };
26
+ }
package/core/base/math.js CHANGED
@@ -13,6 +13,7 @@ export const badPosition = (message, value, Type) => Object.assign(codedError('b
13
13
  // A horizontal position missing x or z (a 2-element [x, z] array reads z as undefined; { x, y } has no z) would become 0 silently
14
14
  // (player.placeAt([10, 20]) at z = 0): say which part is missing and how to write it
15
15
  const MAX_COORD = 1e9;
16
+ const VEC_ERR = 'A position or vector needs finite numbers in every part; got ';
16
17
  const XZ_ERR = 'A horizontal position needs finite x and z: pass [x, y, z] (a 2-element [x, z] array does not work) or { x, z }; got ';
17
18
 
18
19
  /** Round to one decimal (describe, budget reports) @param {number} v @returns {number} */
@@ -29,19 +30,25 @@ export const rv = v => (Number.isFinite(v) && v !== 0 ? Number(v.toPrecision(Mat
29
30
  /** An angle in radians as the same turn in -PI..PI; of a difference, the short way round @param {number} a @returns {number} */
30
31
  export const wrapAngle = a => Math.atan2(Math.sin(a), Math.cos(a));
31
32
 
32
- /** Normalize a Vector3 / Object3D / [x, y, z] / { x, y, z } into a Vector3 */
33
+ const _world = new THREE.Vector3();
34
+ /** Where an Object3D stands: a position argument is a place in the world, and a child's .position is one in its parent's space */
35
+ const placeOf = o => (o.parent && !o.parent.isScene ? o.getWorldPosition(_world) : o.position);
36
+
37
+ /** Normalize a Vector3 / Object3D / [x, y, z] / { x, y, z } into a Vector3. Every part must be a finite number: a NaN let in here reaches the solver, the picture and the save far from the call that made it */
33
38
  export function vec3(v, out = new THREE.Vector3()) {
34
- if (!v && v !== 0) return out;
39
+ if (v == null || v === false || v === '') return out;
35
40
  if (typeof v !== 'object') throw badPosition(POS_ERR + JSON.stringify(v), v, TypeError);
36
- if (v.isVector3) return out.copy(v);
37
- if (v.isObject3D) return out.copy(v.position);
38
- if (Array.isArray(v)) return out.set(v[0] ?? 0, v[1] ?? 0, v[2] ?? 0);
39
- return out.set(v.x ?? 0, v.y ?? 0, v.z ?? 0);
41
+ if (v.isVector3) out.copy(v);
42
+ else if (v.isObject3D) out.copy(placeOf(v));
43
+ else if (Array.isArray(v)) out.set(v[0] ?? 0, v[1] ?? 0, v[2] ?? 0);
44
+ else out.set(v.x ?? 0, v.y ?? 0, v.z ?? 0);
45
+ if (!Number.isFinite(out.x) || !Number.isFinite(out.y) || !Number.isFinite(out.z)) throw badPosition(VEC_ERR + `[${out.x}, ${out.y}, ${out.z}]`, v, TypeError);
46
+ return out;
40
47
  }
41
48
 
42
49
  /** The height a position names, or undefined when it names none ({ x, z }) */
43
50
  export function yOf(v) {
44
- if (v?.isObject3D) v = v.position;
51
+ if (v?.isObject3D) v = placeOf(v);
45
52
  const y = Array.isArray(v) ? v[1] : v?.y;
46
53
  return Number.isFinite(y) ? y : undefined;
47
54
  }
@@ -49,7 +56,7 @@ export function yOf(v) {
49
56
  /** Get the horizontal coordinates [x, z] from a Vector3 / Object3D / [x, y, z] / { x, z } */
50
57
  export function xzOf(v) {
51
58
  if (!v || typeof v !== 'object') throw badPosition(POS_ERR + JSON.stringify(v), v, TypeError);
52
- if (v.isObject3D) v = v.position;
59
+ if (v.isObject3D) v = placeOf(v);
53
60
  const x = Array.isArray(v) ? v[0] : v.x, z = Array.isArray(v) ? v[2] : v.z;
54
61
  if (!Number.isFinite(x) || !Number.isFinite(z)) throw badPosition(XZ_ERR + JSON.stringify(v), v, TypeError);
55
62
  // Far past float precision (render coordinates are 32-bit): not a place. Worse, the chunk loops (`for (cx = floor(x / size); ...; cx++)`) never advance once x / size passes 2^53, a silent freeze (found by fuzz: pos z = -3.6e178)
@@ -12,7 +12,7 @@ import { isOptions, isObject } from './util.js';
12
12
  export const OP_TYPES = ['string', 'number', 'int', 'bool', 'position', 'id', 'any'];
13
13
  // 'color': 0xRRGGBB or '#rrggbb' (a model generator's params, shown as a color picker in the dev panel); not an op arg type
14
14
  const TYPES = ['string', 'number', 'int', 'bool', 'position', 'id', 'any', 'object', 'array', 'function', 'color'];
15
- const SPEC_KEYS = ['type', 'default', 'min', 'max', 'values', 'desc', 'optional'];
15
+ const SPEC_KEYS = ['type', 'default', 'min', 'max', 'values', 'desc', 'optional', 'label', 'rare']; // label, rare: how a panel shows the field
16
16
  const isPos = v => Array.isArray(v) && (v.length === 2 || v.length === 3) && v.every(Number.isFinite);
17
17
  /** type name -> value check (op args use the first seven: plain data only) */
18
18
  const CHECK = {
@@ -90,7 +90,7 @@ export function schemaInfo(shape) {
90
90
  for (const key in shape) {
91
91
  const s = shape[key], o = /** @type {Record<string, any>} */ ({ type: s.type });
92
92
  if (s.optional) o.optional = true;
93
- for (const f of ['default', 'min', 'max', 'values', 'desc']) if (s[f] !== undefined && typeof s[f] !== 'function') o[f] = s[f];
93
+ for (const f of ['default', 'min', 'max', 'values', 'desc', 'label', 'rare']) if (s[f] !== undefined && typeof s[f] !== 'function') o[f] = s[f];
94
94
  out[key] = o;
95
95
  }
96
96
  return out;
@@ -7,17 +7,16 @@
7
7
  // const v = saveValues('clock');
8
8
  // this._now = v.num(d?.now, 'now', { min: 0, fallback: 0 });
9
9
  // v.done(); // one warning for the part, only when something was fixed
10
- import { warnOnce, fmt } from '../base/validate.js';
11
- import { coded, codedError } from '../base/errorHints.js';
10
+ import { warnOnce, fmt } from './validate.js';
11
+ import { coded, codedError } from './errorHints.js';
12
12
 
13
13
  const STRINGS = {
14
14
  warn: "[saves] save part '{part}' had {n} bad value(s), fixed while loading: {list}. The save was edited by hand or damaged; the next save writes the fixed values",
15
15
  };
16
16
 
17
- /** Positions and speeds beyond this are damage, not a big world: float32 models are already centimetres off at 1e5 and useless far before 1e7 */
18
- export const SAVE_MAX = 1e7;
19
- /** A saved number the running game can take. Past SAVE_MAX the ground loops around it never end, or a step later a position goes out of range */
20
- export const saveNumberOk = v => Number.isFinite(v) && Math.abs(v) <= SAVE_MAX;
17
+ export { SAVE_MAX, saveNumberOk } from './validate.js';
18
+ /** Clock seconds beyond this are damage: 30000 years of play, and much further a fixed step no longer moves the number, so time stops for good */
19
+ export const SAVE_MAX_SECONDS = 1e12;
21
20
  /**
22
21
  * Refuse a damaged save: throw save-bad-record, and saves.apply rolls the whole load back and reports this message. For shapes with no safe value.
23
22
  * @param {string} part 'world', 'scene'...
@@ -31,6 +30,25 @@ export function refuseSave(part, path, why, got) {
31
30
  throw codedError('save-bad-record', `${part} save: ${path} ${why} (got ${String(JSON.stringify(got)).slice(0, 120)}); the save was refused and the game was rolled back. The save was edited by hand or damaged: fix that field, or load another save`);
32
31
  }
33
32
 
33
+ /** Would a loader stay on this page's origin, inside the game's folders, with this text? new URL reads it as the browser's fetch does; a backslash or control character (read as a slash or dropped) has no place in a game's path */
34
+ const staysHome = name => {
35
+ if (/^[a-z][a-z\d+.-]*:|[\0-\x1f\\]|(^|\/)(\.|%2e){2}(\/|[?#]|$)/i.test(name)) return false;
36
+ try { const here = new URL(location.href), u = new URL(name, here); return u.protocol === here.protocol && u.host === here.host; } catch { return false; }
37
+ };
38
+ /**
39
+ * A file name in a save, before anything loads it. A save is outside data (a shared file, a hand edit), so it names what the game knows and never decides where the game
40
+ * connects to: an asset entry the game made passes, whatever its URL; anything else must be a relative path on this origin. A reload forgets the paths a
41
+ * playthrough used, so "the game used it" can only be read as "it is one of the game's own paths". Refuses like refuseSave.
42
+ * @param {any} assets engine.assets
43
+ * @param {string} part
44
+ * @param {string} path where in the part
45
+ * @param {string} name
46
+ * @internal
47
+ */
48
+ export function checkSaveFile(assets, part, path, name) {
49
+ if (!assets.entries.has(name) && !staysHome(name)) refuseSave(part, path, 'must be a registered asset name or a relative path on this site', name);
50
+ }
51
+
34
52
  /**
35
53
  * A checker for one part's load: num() clamps / replaces, done() warns once when anything was fixed.
36
54
  * @param {string} part
@@ -0,0 +1,97 @@
1
+ // Content sections: the one protocol for "this data becomes live state". A module owns a section through its `content` field:
2
+ // content: { quests: { desc, references, validate, prepare, commit, cancel } }
3
+ // validate(data, c) refuses bad data by throwing. prepare(data, c) does everything that can fail without touching the live game, and may be async.
4
+ // commit(prepared, c) swaps the prepared result in: it is the only step that changes state, so a failure before it leaves the old state whole. It returns
5
+ // DROPPED when this section gave way to a newer load of the same thing (the other sections go on), or a Promise for slow work nothing else stands on (a pack does not wait for it).
6
+ // waitFor(prepared, c): a Promise while the commits must wait for something newer that decides what they stand on; asked again when it ends. Every prepare is done by then.
7
+ // cancel(prepared, c): this prepare will not commit, let go of what it holds (prepared may be its Promise, still running: say so with a field on the Promise).
8
+ // undo(prepared, c): called just before commit; returns the function that puts back what this commit changes, whole or half done. A later step of the transaction
9
+ // failed, or this commit threw: every commit made so far is taken back, newest first, so state and registrations equal the state before it. That function may return a
10
+ // Promise (a level that has to load again): its first lines run in that order, what it waits for runs side by side, and the transaction fails only when all of it ended.
11
+ // What could not be put back rides on the error as err.notRestored, a list: the caller knows the old state is not whole.
12
+ // A commit that cannot leave a trace needs none; what a section without undo committed stays (a game kind's load is game code, so it runs after the modules' sections).
13
+ // Why one protocol: a level switch and a content pack are the same transaction at different sizes. Two forms would give them two failure rules.
14
+ // desc: one sentence for the docs and the "unknown content" error; the section's name and meaning are written here and nowhere else (metadata.mjs reads them).
15
+ // references(data): [{ section, id, at }], the ids this data names in other sections.
16
+ // effects: { word: { ref, desc, describe, run } }, effect words the section's owner runs, so replacing the module replaces its words too.
17
+ // live: true says one entry can be loaded again on its own in a running game, so the editor need not reload the page.
18
+ // once: true says commit gives state rather than a definition (starting goods): a module put back after a failed replaces has that state from its save part, so it is not committed again. A getter answers for this install: a level is state only once the save part brought it back.
19
+ // c from a content load: { engine, content, where, bind, zone, ids, origin, pickupId, track, after } (modules/content/loader.js).
20
+ import { codedError, coded } from './errorHints.js';
21
+ import { warnOnce } from './validate.js';
22
+
23
+ const KEYS = ['desc', 'references', 'validate', 'prepare', 'waitFor', 'commit', 'cancel', 'undo', 'effects', 'live', 'once'];
24
+
25
+ /** What a commit returns when it gave way to a newer load: this section is skipped, the newest stands, and the rest of the transaction goes on */
26
+ export const DROPPED = Symbol('section dropped');
27
+
28
+ /** An undo for a Map or Set a commit writes to: the function that puts its entries back. @param {Map<any, any> | Set<any>} t @returns {() => void} */
29
+ export function keepTable(t) {
30
+ const was = [...t];
31
+ return () => { t.clear(); for (const x of was) if (t instanceof Map) t.set(x[0], x[1]); else t.add(x); };
32
+ }
33
+
34
+ /** Every section of the installed modules: name -> { owner, ...section }. Two owners of one name are an error, not a last-writer-wins */
35
+ export function sectionsOf(e) {
36
+ const out = new Map();
37
+ for (const m of e.modules.values()) for (const [name, s] of Object.entries(m.content ?? {})) {
38
+ if (out.has(name)) throw codedError('content-misuse', `content section "${name}" has two owners, ${out.get(name).owner} and ${m.name}: keep one`);
39
+ const bad = Object.keys(s).find(k => !KEYS.includes(k));
40
+ if (bad) throw codedError('content-misuse', `content section "${name}" of module ${m.name}: unknown key "${bad}". Keys: ${KEYS.join(', ')}`);
41
+ if (typeof s.commit !== 'function') throw codedError('content-misuse', `content section "${name}" of module ${m.name} needs commit(prepared, c)`);
42
+ out.set(name, { owner: m.name, ...s });
43
+ }
44
+ return out;
45
+ }
46
+
47
+ /**
48
+ * Sections as one transaction, one or every pack of a load: all checked, then all prepared, then all committed in list order. Anything refused cancels what was prepared
49
+ * and nothing commits; a commit that throws takes back the commits before it (undo, above). With nothing to wait for the commits run on this tick, so a
50
+ * section is live on the next line; otherwise they run together once every prepare and `after` (an earlier transaction these stand on) are done, and a Promise of that
51
+ * comes back. Either way they run in one tick, so nothing reads a half-committed load. around runs the commits (content's window for writes). A failure whose undo has to wait
52
+ * rejects that Promise when the undo ended, even on the path that otherwise answers on this tick; around gets the Promise as fn's result.
53
+ * @param {{ s: any, data: any, done?: (committed: any) => void, gaveWay?: () => void }[]} list done: called after the section's commit with what it returned; gaveWay: when it returned DROPPED
54
+ * @param {any} c
55
+ * @param {{ after?: Promise<any> | null, around?: (fn: () => (void | Promise<void>)) => any }} [opts]
56
+ * @returns {Promise<void> | undefined}
57
+ */
58
+ export function runSections(list, c, { after = null, around = fn => fn() } = {}) {
59
+ for (const { s, data } of list) s.validate?.(data, c);
60
+ const prepared = [];
61
+ const cancel = from => {
62
+ for (let i = prepared.length - 1; i >= from; i--) {
63
+ prepared[i]?.then?.(null, () => {}); // nobody waits for it now, so its failure is nobody's error
64
+ list[i].s.cancel?.(prepared[i], c);
65
+ }
66
+ };
67
+ try { for (const { s, data } of list) prepared.push(s.prepare ? s.prepare(data, c) : data); }
68
+ catch (err) { cancel(0); throw err; }
69
+ const commit = values => {
70
+ const undos = [];
71
+ const takeBack = cause => {
72
+ const lost = [], waits = [];
73
+ const told = err => { lost.push(err); warnOnce(coded('content-misuse', `content: an undo failed, so part of a failed load may remain: ${err.message}`)); };
74
+ for (const fn of undos.reverse()) {
75
+ try { const r = fn(); if (typeof r?.then === 'function') waits.push(r.catch(told)); } catch (err) { told(err); } // the rest still goes back
76
+ }
77
+ const fail = () => { if (lost.length) cause.notRestored = lost; throw cause; };
78
+ if (waits.length) return Promise.all(waits).then(fail);
79
+ fail();
80
+ };
81
+ let i = 0;
82
+ try {
83
+ for (; i < list.length; i++) {
84
+ const undo = list[i].s.undo?.(values[i], c);
85
+ if (undo) undos.push(undo);
86
+ const r = list[i].s.commit(values[i], c);
87
+ if (r === DROPPED) { if (undo) undos.pop(); list[i].gaveWay?.(); } else list[i].done?.(r);
88
+ }
89
+ } catch (err) { cancel(i + 1); return takeBack(err); }
90
+ };
91
+ if (!after && !prepared.some(p => typeof p?.then === 'function')) return around(() => commit(prepared));
92
+ const settled = values => {
93
+ const waits = list.flatMap((l, i) => l.s.waitFor?.(values[i], c) ?? []);
94
+ return waits.length ? Promise.all(waits).then(() => settled(values)) : around(() => commit(values));
95
+ };
96
+ return Promise.all([after, ...prepared]).then(([, ...values]) => settled(values), err => { cancel(0); throw err; });
97
+ }
@@ -0,0 +1,32 @@
1
+ // Spelling helpers with no imports: "did you mean" in the engine's runtime checks (validate.js) and in the tools (packages/tools/lib/text.mjs),
2
+ // and the node-name rule that the asset report and `threedog assets check` both apply. One copy each; a change here changes both.
3
+
4
+ /** Edit distance (case-insensitive; swapping two adjacent letters counts as 1, e.g. jupm -> jump) */
5
+ export function distance(a, b) {
6
+ a = a.toLowerCase(); b = b.toLowerCase();
7
+ const d = Array.from({ length: a.length + 1 }, (_, i) => [i]);
8
+ for (let j = 1; j <= b.length; j++) d[0][j] = j;
9
+ for (let i = 1; i <= a.length; i++) for (let j = 1; j <= b.length; j++) {
10
+ d[i][j] = Math.min(d[i - 1][j] + 1, d[i][j - 1] + 1, d[i - 1][j - 1] + (a[i - 1] === b[j - 1] ? 0 : 1));
11
+ if (i > 1 && j > 1 && a[i - 1] === b[j - 2] && a[i - 2] === b[j - 1]) d[i][j] = Math.min(d[i][j], d[i - 2][j - 2] + 1);
12
+ }
13
+ return d[a.length][b.length];
14
+ }
15
+
16
+ /**
17
+ * The entry of list closest to name; null if too far. Without maxDist the limit scales with length (longer names tolerate more errors).
18
+ * Too far by spelling, a name of 4+ letters that is part of exactly one entry still matches ('forward' -> 'moveForward'): AIs often drop a prefix.
19
+ */
20
+ export function closest(name, list, maxDist) {
21
+ name = String(name);
22
+ const limit = maxDist ?? (name.length <= 4 ? 1 : name.length <= 8 ? 2 : 3);
23
+ let best = null, bd = Infinity;
24
+ for (const c of list) { if (c === name) continue; const d = distance(name, String(c)); if (d < bd) { bd = d; best = c; } }
25
+ if (bd <= limit) return best;
26
+ if (maxDist != null || name.length < 4) return null;
27
+ const low = name.toLowerCase(), part = [...list].filter(c => String(c).toLowerCase().includes(low));
28
+ return part.length === 1 ? part[0] : null;
29
+ }
30
+
31
+ /** three's PropertyBinding.sanitizeNodeName: the name the engine sees ("door.001" -> "door001", spaces -> "_") */
32
+ export const sanitize = n => String(n ?? '').replace(/\s/g, '_').replace(/[[\].:/]/g, '');
@@ -10,6 +10,8 @@
10
10
 
11
11
  import { hintText, coded, codedError } from './errorHints.js';
12
12
  import { isOptions } from './util.js';
13
+ import { closest } from './spelling.js';
14
+ export { closest };
13
15
 
14
16
  const STRINGS = {
15
17
  unknownKey: '{where}: unknown option "{key}", {hint}',
@@ -43,8 +45,12 @@ const enabled = () => live === 0 || quiet < live;
43
45
  // @ts-ignore Vite's import.meta.env (undefined outside Vite)
44
46
  const ENV = import.meta.env;
45
47
  export const DEV = !!(ENV?.DEV || ENV?.THREEDOG_TEST);
46
- /** Whether a position can be written: [x, y, z], or { x, z } with y left out or a number. The one answer; thing.set asks it in can, world's putPos before it writes @param {any} p @returns {boolean} @internal */
47
- export const goodPos = p => Array.isArray(p) ? p.length === 3 && p.every(Number.isFinite) : Number.isFinite(p?.x) && Number.isFinite(p?.z) && (p.y === undefined || Number.isFinite(p.y));
48
+ /** Positions and speeds beyond this are damage, not a big world: float32 models are already centimetres off at 1e5 and useless far before 1e7 @internal */
49
+ export const SAVE_MAX = 1e7;
50
+ /** A number the running game can take. Past SAVE_MAX the ground loops around it never end, or a step later a position goes out of range @internal */
51
+ export const saveNumberOk = v => Number.isFinite(v) && Math.abs(v) <= SAVE_MAX;
52
+ /** Whether a position can be written: [x, y, z], or { x, z } with y left out or a number, each one a save can hold (a save with a bigger one never loads). The one answer; thing.set asks it in can, world's putPos before it writes @param {any} p @returns {boolean} @internal */
53
+ export const goodPos = p => Array.isArray(p) ? p.length === 3 && p.every(saveNumberOk) : saveNumberOk(p?.x) && saveNumberOk(p?.z) && (p.y === undefined || saveNumberOk(p.y));
48
54
  /** The Vite dev server itself (npm run dev, not the test bundle): only it serves /__threedog endpoints and the dev bridge. The other spelling of "dev", named so nothing reads import.meta.env.DEV on its own. */
49
55
  export const DEV_SERVER = !!ENV?.DEV;
50
56
  /** Vite's base URL ('/' outside Vite) */
@@ -106,33 +112,6 @@ export function note(msg, key) {
106
112
  console.info('[threedog] ' + msg);
107
113
  }
108
114
 
109
- /** Edit distance (case-insensitive; swapping two adjacent letters counts as 1, e.g. jupm -> jump) */
110
- function distance(a, b) {
111
- a = a.toLowerCase(); b = b.toLowerCase();
112
- const d = Array.from({ length: a.length + 1 }, (_, i) => [i]);
113
- for (let j = 1; j <= b.length; j++) d[0][j] = j;
114
- for (let i = 1; i <= a.length; i++) for (let j = 1; j <= b.length; j++) {
115
- d[i][j] = Math.min(d[i - 1][j] + 1, d[i][j - 1] + 1, d[i - 1][j - 1] + (a[i - 1] === b[j - 1] ? 0 : 1));
116
- if (i > 1 && j > 1 && a[i - 1] === b[j - 2] && a[i - 2] === b[j - 1]) d[i][j] = Math.min(d[i][j], d[i - 2][j - 2] + 1);
117
- }
118
- return d[a.length][b.length];
119
- }
120
-
121
- /**
122
- * The entry of list closest to name; null if too far. Without maxDist the limit scales with length (longer names tolerate more errors).
123
- * Too far by spelling, a name of 4+ letters that is part of exactly one entry still matches ('forward' -> 'moveForward'): AIs often drop a prefix.
124
- */
125
- export function closest(name, list, maxDist) {
126
- name = String(name);
127
- const limit = maxDist ?? (name.length <= 4 ? 1 : name.length <= 8 ? 2 : 3);
128
- let best = null, bd = Infinity;
129
- for (const c of list) { if (c === name) continue; const d = distance(name, String(c)); if (d < bd) { bd = d; best = c; } }
130
- if (bd <= limit) return best;
131
- if (maxDist != null || name.length < 4) return null;
132
- const low = name.toLowerCase(), part = [...list].filter(c => String(c).toLowerCase().includes(low));
133
- return part.length === 1 ? part[0] : null;
134
- }
135
-
136
115
  const listText = list => { const a = [...list]; return a.length ? a.slice(0, 15).join(', ') + (a.length > 15 ? fmt(STRINGS.more, { n: a.length }) : '') : STRINGS.none; };
137
116
 
138
117
  /** Text like 'xxx "name" does not exist, did you mean `yyy`? (available: a, b, c)', shared by errors and warnings. */
@@ -22,26 +22,28 @@ import { holdMethods } from '../ops/holds.js';
22
22
  import { startupMethods } from './startup.js';
23
23
  import { groundMethods, flatGround } from '../scene/ground.js';
24
24
  import { actorMethods } from '../ops/actor.js';
25
- import { forcedTier, defaultPixelRatio } from '../scene/tier.js';
25
+ import { forcedTier, storedMsaa } from '../scene/tier.js';
26
26
  import { tier as detectTier, tierBeforeRenderer, ownMsaa, timerContext, isWebGPU, webgpuPart, watchNodePrograms } from '../../render/backend.js';
27
27
  import { recordSweep } from '../../render/recordSweep.js';
28
28
  import { dressNodeTwins } from '../../render/patches.js';
29
29
  import { lifecycleMethods, clearHooks, checkCanvasUsable } from './lifecycle.js';
30
30
  import { createAdaptive, GpuTimer } from '../scene/adaptive.js';
31
+ import { firstRatio, noteDeviceBox, pixelSizeOn } from '../scene/pixelRatio.js';
31
32
  import { watchRejections } from '../base/errors.js';
32
33
  import { createMovement } from '../scene/movement.js';
33
34
  import { moduleMethods } from './modules.js';
34
35
  import { skipMethods } from '../time/skip.js';
35
36
  import { checkMethods } from '../inspect/checks.js';
37
+ import { toolDoor } from '../inspect/toolDoor.js';
36
38
  import { canvasBox, placeUI, resizeMethods } from '../scene/canvasBox.js';
37
39
  import { sceneMethods } from '../scene/sceneMethods.js';
38
- import { EngineCamera } from '../scene/engineCamera.js';
40
+ import { movedOwned } from '../ops/owned.js';
39
41
  import { recordRender } from '../inspect/describeRender.js';
40
42
  import { installPictureWriters } from '../inspect/pictureWriters.js';
41
43
  import { ownHook } from './moduleTypes.js';
42
44
  import { defineShadows } from '../../render/shadows.js';
43
45
  import { defineTerms } from '../../render/terms.js';
44
- import { defineView } from '../scene/view.js';
46
+ import { defineView, checkCamera } from '../scene/view.js';
45
47
  import { nameShaderErrors } from '../../render/shaderErrors.js';
46
48
  import { probeMethods } from '../../render/probes.js';
47
49
  import { lightmapMethods } from '../../render/lightmap.js';
@@ -55,7 +57,7 @@ const FALLBACKS = ['webgl2', 'webgl', 'error'];
55
57
  export const ENGINE_PARAMS = {
56
58
  canvas: 'object?', renderer: { type: 'string|object', optional: true, desc: "'webgl' (default), 'webgpu', or a renderer the game built" },
57
59
  fallback: { type: 'string', optional: true, values: FALLBACKS }, antialias: 'bool?',
58
- pixelRatio: 'number?', adaptiveResolution: { type: 'bool', default: true }, targetFps: { type: 'number', default: 55, min: 1 },
60
+ pixelRatio: 'number?', pixelSize: { type: 'int', optional: true, min: 1, desc: 'real screen pixels per art pixel' }, adaptiveResolution: { type: 'bool', default: true }, targetFps: { type: 'number', default: 55, min: 1 },
59
61
  ui: 'object?', audio: 'object?', fov: { type: 'number', default: 55, min: 1, max: 179 }, near: { type: 'number', default: 0.3, min: 0 },
60
62
  locale: { type: 'string', default: 'auto' }, strings: 'object?', bindings: 'object?', saveKey: { type: 'string', default: 'game' },
61
63
  joystick: { type: 'string|bool', default: 'auto' }, headless: 'bool?', validate: { type: 'bool', default: true }, decoders: 'string?',
@@ -90,6 +92,12 @@ function rendererWant(r, rendererIn, fallback) {
90
92
  }
91
93
 
92
94
 
95
+ /** pixelSize decides the ratio, so an option asking for something else about it is an error that names which to keep */
96
+ function checkPixelSizeOptions(pixelSize, pixelRatio, adaptiveResolution) {
97
+ if (pixelRatio != null) throw codedError('pixel-conflict', `createEngine({ pixelRatio: ${pixelRatio}, pixelSize: ${pixelSize} }): both decide the render resolution. Keep pixelSize for art pixels of one exact size, or pixelRatio for a plain render scale`);
98
+ if (adaptiveResolution === true) throw codedError('pixel-conflict', `createEngine({ adaptiveResolution: true, pixelSize: ${pixelSize} }): adaptive resolution would change the art pixels' size. Keep pixelSize and drop adaptiveResolution`);
99
+ }
100
+
93
101
  // Dev note once when createEngine keeps the engine's placeholder lights; lights: false says the game writes its own picture
94
102
  const NO_PICTURE = 'createEngine(): the placeholder picture is on: a still white sun and hemisphere light with soft shadows, no tone curve, no environment map (see describe().render.defaults), ' +
95
103
  'gray background, ground, capsule characters and box props. Not an error, but the game has no picture yet: making the art is part of building the game. ' +
@@ -108,10 +116,11 @@ export class Engine {
108
116
  /** @internal */ this._untrackValidate = trackValidate(opts.validate);
109
117
  const o = readParams('createEngine()', ENGINE_PARAMS, opts);
110
118
  /** @internal createEngine options as read (engine.catalog('core').params shows them with the schema) */ this._createParams = o;
111
- const { canvas: canvasIn, renderer: rendererName, antialias, pixelRatio, adaptiveResolution, targetFps, ui = {}, audio = {},
119
+ const { canvas: canvasIn, renderer: rendererName, antialias, pixelRatio, pixelSize, adaptiveResolution, targetFps, ui = {}, audio = {},
112
120
  fov, near, locale, strings = {}, bindings = {}, saveKey, joystick,
113
121
  headless = new URLSearchParams(location.search).has('threedog-headless'), validate,
114
122
  decoders = null, budget = null, urlState = DEV, seed, movement, threads, pauseOnBlur, batching = {}, lights, fallback } = o;
123
+ if (pixelSize != null) checkPixelSizeOptions(pixelSize, pixelRatio, opts.adaptiveResolution);
115
124
  // 'webgl' names the default (a WebGLRenderer the engine builds), so it reads like leaving the option out
116
125
  const rendererIn = rendererName === 'webgl' ? undefined : rendererName;
117
126
  // 'webgpu' is the same road as a game's own WebGPURenderer: built here, then handed on like one (start() inits it, core/engine/startup.js)
@@ -128,7 +137,10 @@ export class Engine {
128
137
  // every headless browser low tier and drop the game's costly post from shots. An engine-built renderer needs it before it exists: MSAA defaults
129
138
  // from the tier and is the canvas's own (antialias, fixed when the context is made), so an effect-free frame skips the post chain
130
139
  const tierFirst = (headless && forcedTier()) || (owned ? tierBeforeRenderer() : null);
131
- const aa = antialias ?? (owned ? tierFirst !== 'low' : null);
140
+ // pixelSize: hard art pixels are the point, so the default is off
141
+ const authoredAA = antialias ?? (owned ? tierFirst !== 'low' && pixelSize == null : null);
142
+ // the player's choice from the last launch comes here because here is the last moment it can reach the canvas; art pixels stay as they are
143
+ const aa = (owned && pixelSize == null ? storedMsaa(saveKey) : null) ?? authoredAA;
132
144
  const r = this.renderer = gpuWanted ? newWebGPURenderer(canvas, aa) : rendererIn ?? new THREE.WebGLRenderer({ canvas, antialias: aa, powerPreference: 'high-performance' });
133
145
  /** @internal what the game asked for and what to do without WebGPU; start() fills describe().renderer from it */
134
146
  this._backendWant = rendererWant(r, rendererIn, fallback);
@@ -136,8 +148,9 @@ export class Engine {
136
148
  this._records = recordSweep(r); // WebGPU: meshes that left the scene free their records (render/recordSweep.js)
137
149
  if (isWebGPU(r)) dressNodeTwins(r); // WebGPU: classic materials get their patches as nodes (render/patches.js)
138
150
  nameShaderErrors(r); // compile errors name the patch and slot (render/shaderErrors.js); a game's own handler stays
139
- this.tier = tierFirst || detectTier(r);
140
- if (owned || pixelRatio != null) r.setPixelRatio(pixelRatio ?? defaultPixelRatio(devicePixelRatio || 1, this.tier));
151
+ this._deviceTier = tierFirst || detectTier(r);
152
+ /** @internal real screen pixels per art pixel, null when off (core/scene/pixelRatio.js) @type {number | null} */ this._pixelSize = null;
153
+ if (owned || pixelRatio != null) firstRatio(r, this._deviceTier, pixelRatio);
141
154
  this._autoSize = undefined; // decided once the canvas is in the page (sizeMode): true = no CSS size, the engine sizes it to the window
142
155
  const box = canvasBox(this);
143
156
  if (owned) r.setSize(box.w, box.h, !!this._autoSize);
@@ -147,18 +160,19 @@ export class Engine {
147
160
  /** @internal the neutral background a scene starts with: describe().render.defaults, and the reference a sky compares with @type {any} */ this.baseBackground = new THREE.Color(0x8c8c8c);
148
161
  /** @internal */ this.baseBackgroundHex = this.baseBackground.getHex();
149
162
  this.scene.background = this.baseBackground;
163
+ this.stacks = new Stacks(this); // shared points: before the lights, whose shadow size reads engine.tier, and the first engine.shadows / engine.post point
150
164
  /** Placeholder lights { sun: DirectionalLight, hemi: HemisphereLight }: neutral and still; createEngine({ lights: false }) leaves them out of the scene @type {{ sun: any, hemi: any }} */
151
165
  this.lights = createDefaultLights(this, { add: lights !== false });
152
166
  // the engine's own renderer gets soft shadows by default; tone curve and environment stay three.js's defaults
153
- this.stacks = new Stacks(this); // shared points: the registry exists before the first engine.shadows / engine.post point
154
167
  defineShadows(this, { owned }); // engine.shadows: master switch, cascades, box, budget on the lights a game hands in (render/shadows.js)
155
168
  recordRender(this, { owned }); // baseline for describe().render (after the shadow defaults are written): which values the engine set
156
169
  // Dev server only. A bundled build (npm test, threedog shot, release) is one minified file, so a stack there names assets/index-x.js:1 for every value: a
157
170
  // wrong answer. Written as the literal, not DEV_SERVER: only the literal folds at build time, so the tracker leaves a release bundle altogether
158
171
  // @ts-ignore Vite's import.meta.env (undefined outside Vite)
159
172
  if (import.meta.env?.DEV) installPictureWriters(this);
160
- this.camera = new EngineCamera(fov, box.w / box.h, near, 1500); // a PerspectiveCamera that camera rigs can switch to orthographic (core/scene/engineCamera.js)
161
- this.camera.position.set(0, 10, 20);
173
+ this._camera = new THREE.PerspectiveCamera(fov, box.w / box.h, near, 1500);
174
+ /** @internal { camera, home }: the orthographic camera a rig's projection swapped in, and the camera it stands in for (setProjection, core/scene/view.js) */ this._ortho = null;
175
+ this._camera.position.set(0, 10, 20);
162
176
  this.focus = new THREE.Vector3(); // camera focus (updated by the camera module): the view loads around it; simulation follows world.anchor
163
177
  this.ground = flatGround;
164
178
  this.player = null;
@@ -175,6 +189,7 @@ export class Engine {
175
189
  */
176
190
  this.phase = 'constructed';
177
191
  /** @internal module name -> handles its install / init passed to ctx.track (removed with the module: modules.js) */ this._modTracked = new Map();
192
+ /** @internal object -> property -> its one ctx.borrow holder (modules.js) */ this._borrowed = new WeakMap();
178
193
  /** @internal module name -> the token of its current install: ctx and async init check it (modules.js, a stale init must not act on a newcomer) */ this._modInst = new Map();
179
194
  this._abort = new AbortController();
180
195
  // attach DOM listeners to it: addEventListener(type, fn, { signal: engine.signal }); dispose cancels them together
@@ -190,16 +205,18 @@ export class Engine {
190
205
  /** How far the drawn frame is from the last fixed step to the next, 0-1 (real loop); 1 after step(). Holds still while frozen. For drawing fixed-step state smoothly: prev + (now - prev) * stepBlend */
191
206
  this.stepBlend = 1;
192
207
  /** @internal the picture check is rendering (tools/picture/check.mjs): what it changes and puts back is not the game's */ this._probing = false;
208
+ /** @internal the tools' one way in (rule R68) */ this._tools = toolDoor(this);
193
209
  /** @internal */ this._cpuMs = 0; // main-thread ms of the last real-time frame; _cpuPhases splits it (loop.js); read through engine.inspect.perf() and engine.budget
194
210
  /** @internal */ this._cpuPhases = { fixed: 0, frame: 0, render: 0, afterRender: 0 };
195
211
  this._openWindows = new Set(); // ids of open windows (for describe)
196
212
  this.modules = new Map();
197
213
  this._modState = new Map(); // module name -> registered | initializing | running | failed | disposed (modules.js)
214
+ /** @internal module name -> what it waits for: [{ requires, module, state }], derived from _modState (modules.js) */ this._modBlocked = new Map();
215
+ /** @internal installs (engine._modInst tokens) whose critical block was already reported */ this._modFatal = new WeakSet();
198
216
  this.waterBodies = [];
199
217
  clearHooks(this);
200
218
  this._hookErrors = new Set(); // places that already reported an error (once per place, see errors.js)
201
219
  this.error = null; // gameplay error in dev/test: { where, message, cause?, docs? }; gameplay is frozen (see errors.js)
202
- this.disabledModules = new Set(); // picture / ui modules disabled after they threw
203
220
  /**
204
221
  * This engine's shader uniforms (uTime, uWind, uWeatherCloud, season tints...); share these objects in your own ShaderMaterial or patch @type
205
222
  * {import('../../types/core').EngineUniforms}
@@ -217,29 +234,54 @@ export class Engine {
217
234
  this._prof = null; // module hook timing (profile(true) turns it on)
218
235
  this._afterTick = null; // at startup, checked once at the end of each frame for readiness
219
236
  // a game's own renderer keeps its own MSAA choice by default (used as is, like its pixel ratio)
220
- this.post = new PostFX(this, { antialias: aa ?? ownMsaa(r) });
237
+ this.post = new PostFX(this, { antialias: aa ?? ownMsaa(r), authored: authoredAA ?? ownMsaa(r) });
221
238
  this.occlusion = new Occlusion(this); // off until the game turns it on (render/occlusion.js)
222
239
  this._uiStyle = applyUITheme(this, ui); // theme variables and the game's CSS; removed on dispose
223
240
  this.ui = new UIParts(this, ui); // UI parts: every piece of screen UI is replaceable or off (ui/Parts.js)
224
241
  defineCoreParts(this);
225
242
  this.ui.get('loading')?.show({});
226
- this.adaptive = createAdaptive({ on: adaptiveResolution && !headless, target: targetFps, max: r.getPixelRatio() });
227
- this._gpu = this.adaptive.on ? new GpuTimer(timerContext(r)) : null; // GPU frame time for adaptive resolution where the browser offers the timer query
243
+ const adaptiveOn = adaptiveResolution && !headless;
244
+ this.adaptive = createAdaptive({ on: adaptiveOn, target: targetFps, max: r.getPixelRatio(), held: () => pixelSizeOn(this) });
245
+ this._gpu = adaptiveOn ? new GpuTimer(timerContext(r)) : null; // GPU frame time for adaptive resolution where the browser offers the timer query
228
246
  // follow the canvas's own CSS box, not the window: a canvas in a page section or editor panel renders at its own size.
229
247
  // The window event stays for a canvas outside the page (no box, falls back to the window) and for moves that do not resize the canvas
230
248
  addEventListener('resize', () => this._resize(), { signal: this.signal });
231
249
  this._unhandled = null; watchRejections(this);
232
250
  if (typeof ResizeObserver === 'function') {
233
- const ro = new ResizeObserver(() => this._resize());
234
- ro.observe(r.domElement);
251
+ const ro = new ResizeObserver(([entry]) => { noteDeviceBox(this, entry); this._resize(); });
252
+ try { ro.observe(r.domElement, { box: 'device-pixel-content-box' }); } catch { ro.observe(r.domElement); } // Safari rejects the box name
235
253
  this.signal.addEventListener('abort', () => ro.disconnect());
236
254
  }
237
255
  placeUI(this);
256
+ if (pixelSize != null) this.setPixelSize(pixelSize);
238
257
  this.page = new Page(this, { pauseOnBlur }); // window focus, tab visibility, mouse lock, WebGL context: handled only there
239
258
  this._born.built = performance.now(); // measure
240
259
  }
241
260
 
261
+ /**
262
+ * The camera the engine draws with. Assign a real THREE.PerspectiveCamera or THREE.OrthographicCamera to draw through it: rendering, post, picking, shadows, audio and an
263
+ * installed rig all go on with it. Its aspect follows the canvas unless the game took engine.autoView 'aspect'. Keep the first value to swap back. Any other class is refused.
264
+ * @example const own = engine.camera; engine.camera = new THREE.OrthographicCamera(-16, 16, 9, -9, 0.1, 500); engine.camera = own;
265
+ * @type {import('three').PerspectiveCamera | import('three').OrthographicCamera}
266
+ */
267
+ get camera() { return this._camera; }
268
+ set camera(cam) {
269
+ const old = this._camera;
270
+ if (cam === old) return;
271
+ checkCamera(cam);
272
+ cam.coordinateSystem = old.coordinateSystem; // the renderer's depth range: three sets it at the first draw, and a pick before that needs it too
273
+ cam.updateProjectionMatrix(); cam.updateMatrixWorld();
274
+ this._camera = cam;
275
+ movedOwned(this, new Map([[old, cam], [old.position, cam.position], [old.quaternion, cam.quaternion]]));
276
+ const c = this.renderer.domElement;
277
+ this._oAspect.drive(c.width / c.height); // the buffer, as a resize leaves it: with pixelSize it is not the canvas box
278
+ }
279
+
242
280
  get waterLevel() { return this.ground.waterLevel; }
281
+ /** The one quality value, 'low' | 'high', what everything that scales by quality reads: the device's tier, unless the player's preset says otherwise (shared point 'tier') @type {'low' | 'high'} */
282
+ get tier() { return this.stacks.has('tier') ? this.stacks.get('tier').value() : this._deviceTier; }
283
+ /** The device's tier, the base under a player's preset */
284
+ set tier(t) { this._deviceTier = t; if (this.stacks.has('tier')) this.stacks.get('tier').base = t; }
243
285
  /** True once the world is built (phase 'ready' or 'running'): fixed steps, ops and rendering run from here on @type {boolean} */
244
286
  get ready() { return this.phase === 'ready' || this.phase === 'running'; }
245
287
  /** @internal start() is on its way: no game time passes */
@@ -293,7 +335,8 @@ export class Engine {
293
335
  /**
294
336
  * Around the main render, after the camera update and batching: fn({ renderer, scene, camera, dt }). when 'before' (default) runs just before the
295
337
  * engine's frame render: render to your own target there (mirror, minimap, portal, picking); the render target is reset afterwards. 'after' runs
296
- * right after it (read pixels, overlays). The main frame render stays the engine's. Returns a handle { remove() }
338
+ * right after it (read pixels, overlays). The main frame render stays the engine's. A hook that throws has what it borrowed put back (target, viewport, scissor,
339
+ * autoClear, scene.overrideMaterial, camera.layers). Returns a handle { remove() }
297
340
  * @param {(ctx: { renderer: any, scene: any, camera: any, dt: number }) => void} fn @param {{ when?: 'before' | 'after' }} [opts]
298
341
  */
299
342
  onRender(fn, { when = 'before' } = {}) {