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,4 +1,4 @@
1
- // Quest progress in saves (part 'quests', version 2): saved by stable step and part ids, never by position, so content may insert or reorder steps.
1
+ // Quest progress in saves (part 'quests', version 3: visited added; owed is optional, so older saves read as they are): saved by stable step and part ids, never by position, so content may insert or reorder steps.
2
2
  // { state: { questId: { step: stepId | null (when done), done, failed?, parts?: [ids of parts met in the current parallel step],
3
3
  // got?: { stepId: [ids of parts met in a finished parallel step] } } } }
4
4
  // A step's (or parallel part's) id is its `id` field (quests.define / content: steps: [{ id: 'talk-mayor', text, done }]), else its position as text
@@ -30,6 +30,8 @@ const indexOf = (def, id) => def.steps.findIndex((_, i) => stepId(def, i) === id
30
30
  export function toSaved(def, s) {
31
31
  const out = { step: s.done ? null : stepId(def, s.step), done: !!s.done };
32
32
  if (s.failed) out.failed = true;
33
+ if (s.owed) out.owed = { ...s.owed };
34
+ if (s.visited?.length) out.visited = [...s.visited];
33
35
  if (s.parts) out.parts = metIds(def.steps[s.step], s.parts);
34
36
  if (s.got) out.got = Object.fromEntries(Object.entries(s.got).map(([i, flags]) => [stepId(def, +i), metIds(def.steps[+i], flags)]));
35
37
  return out;
@@ -47,6 +49,9 @@ export function fromSaved(id, def, q) {
47
49
  if (step < 0) { warnOnce(coded('quest-step', fmt(STRINGS.missing, { q: id, step: String(q.step) }))); step = 0; }
48
50
  const s = { step, done: !!q.done };
49
51
  if (q.failed) s.failed = true;
52
+ if (q.owed) s.owed = { ...q.owed };
53
+ // a save from before visited went through the list in order, so the steps behind this one are what it left
54
+ s.visited = Array.isArray(q.visited) ? q.visited.filter(v => typeof v === 'string' && indexOf(def, v) >= 0) : def.steps.slice(0, step).map((_, i) => stepId(def, i));
50
55
  const st = def.steps[step];
51
56
  if (q.parts && st?.all) s.parts = metFlags(st, q.parts);
52
57
  for (const [sid, ids] of Object.entries(q.got || {})) {
@@ -6,7 +6,7 @@ export default {
6
6
  api: ['define', 'start', 'advance', 'state', 'list'],
7
7
  ops: [],
8
8
  events: ['quest:start', 'quest:step', 'quest:done'],
9
- saves: { quests: 2 },
9
+ saves: { quests: 3 },
10
10
  describe: true,
11
11
  options: {},
12
12
  probe: {
@@ -16,7 +16,7 @@ export const occKey = (occupy, level, i, j) => `${occupy}|${level}|${i},${j}`;
16
16
  const cap = s => s[0].toUpperCase() + s.slice(1);
17
17
  const FLAT_SAMPLES = [[0, 0], [-1, -1], [1, -1], [-1, 1], [1, 1]];
18
18
  // [x, z] here (a grid is flat), [x, y, z] / Vector3 / Object3D / { x, z } as everywhere else
19
- const planar = v => (Array.isArray(v) && v.length === 2 ? v : xzOf(v));
19
+ export const planar = v => (Array.isArray(v) && v.length === 2 ? v : xzOf(v));
20
20
 
21
21
  /**
22
22
  * A placement grid. Several can exist at once (a yard outdoors, a room indoors); each has its own cell size, origin and bounds.
@@ -8,6 +8,8 @@
8
8
  // _ver counts changes so views (tiles) rebuild only when something changed, without events.
9
9
  import { DEV, needMaterial } from '../../core/base/validate.js';
10
10
  import { codedError } from '../../core/base/errorHints.js';
11
+ import { isPlainObject } from '../../core/base/util.js';
12
+ import { refuseSave, saveNumberOk } from '../../core/base/saveValues.js';
11
13
 
12
14
  const key = (i, j) => i + ',' + j;
13
15
  const plainErr = (where, v) => `${where}: layer data must be plain values (numbers, strings, booleans, arrays, plain objects); got ${v?.constructor?.name ?? typeof v}. Keep models in tiles / world.present`;
@@ -51,7 +53,7 @@ export class Layer {
51
53
  get material() { return this.grid._owner._tiles.get(this)?.mesh?.material ?? null; }
52
54
  set material(m) {
53
55
  const mesh = this.grid._owner._tiles.get(this)?.mesh;
54
- if (!mesh) throw codedError('grids-misuse', `layer '${this.name}'.material: this layer draws no default tiles; give it a picture first: grid.layer('${this.name}', { tiles: true })`);
56
+ if (!mesh) throw codedError('grids-misuse', `layer '${this.name}'.material: this layer draws no default tiles, and a layer takes that when it is created: first call grid.layer('${this.name}', { tiles: true })`);
55
57
  needMaterial('grids-misuse', `layer '${this.name}'.material`, m);
56
58
  mesh.material = m;
57
59
  }
@@ -74,7 +76,7 @@ export class Layer {
74
76
  */
75
77
  set([i, j], patch) {
76
78
  this._guard('set');
77
- if (DEV) checkPlain(`layer ${this.name}.set`, patch);
79
+ checkPlain(`layer ${this.name}.set`, patch);
78
80
  const k = key(i, j), d = { ...this._cells.get(k) };
79
81
  for (const [f, v] of Object.entries(patch)) { if (v == null) delete d[f]; else d[f] = v; }
80
82
  if (Object.keys(d).length) this._cells.set(k, seal(d)); else this._cells.delete(k);
@@ -115,7 +117,7 @@ export class Layer {
115
117
  const copy = { ...d }, r = fn(copy, /** @type {[number, number]} */ (k.split(',').map(Number)));
116
118
  const v = r === undefined ? copy : r;
117
119
  if (v == null || !Object.keys(v).length) this._cells.delete(k);
118
- else { if (DEV) checkPlain(`layer ${this.name}.updateAll`, v); this._cells.set(k, seal(v === d ? { ...v } : v)); }
120
+ else { checkPlain(`layer ${this.name}.updateAll`, v); this._cells.set(k, seal(v === d ? { ...v } : v)); }
119
121
  }
120
122
  this._ver++;
121
123
  return this._cells.size;
@@ -136,6 +138,8 @@ export class Layer {
136
138
  get _same() { const d = this.toJSON(); return !d.set.length && !d.clear; }
137
139
  /** @internal a save diff (or null = none): baseline first, then the diff */
138
140
  fromJSON(d) {
141
+ const rows = l => l == null || (Array.isArray(l) && l.every(c => Array.isArray(c) && saveNumberOk(c[0]) && saveNumberOk(c[1])));
142
+ if (d != null && !(isPlainObject(d) && rows(d.set) && rows(d.clear) && (d.set ?? []).every(c => isPlainObject(c[2])))) refuseSave('grids', `layer '${this.name}'`, 'must be { set: [[i, j, data], ...], clear: [[i, j], ...] }', d);
139
143
  this._diff = d ?? null;
140
144
  this._cells = new Map(d?.whole ? [] : this._base);
141
145
  for (const [i, j, v] of d?.set ?? []) this._cells.set(key(i, j), seal(v));
@@ -144,7 +148,7 @@ export class Layer {
144
148
  }
145
149
  /** @internal authored cells ([[i, j, data], ...] from content/grids.js): the baseline; the last loaded diff is applied on top again */
146
150
  _setBase(rows) {
147
- for (const [i, j, v] of rows ?? []) { if (DEV) checkPlain(`content grids layer ${this.name}`, v); this._base.set(key(i, j), seal(structuredClone(v))); }
151
+ for (const [i, j, v] of rows ?? []) { checkPlain(`content grids layer ${this.name}`, v); this._base.set(key(i, j), seal(structuredClone(v))); }
148
152
  this.fromJSON(this._diff);
149
153
  }
150
154
  }
@@ -9,7 +9,8 @@
9
9
  // Picture: grids({ ok, bad, previewOpacity, previewHeight, tiles, tileLift }) for the plain values, pv.material and layer.material for the three.js materials.
10
10
  // The index is the "don't go around it" check: in dev a record's grid field is frozen (editing it in place throws), writes outside ops
11
11
  // trigger the ops guard, and a record whose footprint overlaps another one is reported with the fix.
12
- import { Grid, MAIN, occKey } from './Grid.js';
12
+ import { keepTable } from '../../core/base/sections.js';
13
+ import { Grid, MAIN, occKey, planar } from './Grid.js';
13
14
  import { layerTiles } from './tiles.js';
14
15
  import { makePreview } from './preview.js';
15
16
  import { defineGridOps, placed } from './ops.js';
@@ -61,6 +62,8 @@ export class Grids {
61
62
  /** @internal */ this._previews = new Set();
62
63
  /** @internal layer data from a save, for layers created after the load */ this._loaded = null;
63
64
  }
65
+ /** @internal A failed content load takes its grids back (core/base/sections.js undo): the function that does it @returns {() => void} */
66
+ undoPoint() { const back = keepTable(this._grids); return () => { back(); this._rebuild(); }; }
64
67
  /**
65
68
  * Create a grid. cell: edge length (m, default 1); origin: world [x, z] of the min corner of cell [0, 0]; size: [cells wide, cells deep] (omit = unbounded);
66
69
  * zone: level name (tiles only show there); flat: max height difference under a footprint (m, default 0.5);
@@ -80,6 +83,10 @@ export class Grids {
80
83
  const m = opts.mapping;
81
84
  if (m && !(typeof m.toCell === 'function' && typeof m.center === 'function')) throw codedError('grids-misuse', `grids.add('${name}'): mapping needs both toCell(x, z) => [i, j] and center([i, j]) => [x, z]`, TypeError);
82
85
  if (this._grids.has(name)) throw codedError('grids-misuse', fmt(STRINGS.dup, { name }));
86
+ // a cell of 0 or NaN turns every position into cell NaN: placed things collide with nothing and every later lookup misses
87
+ const { cell = 1, origin = [0, 0], size = null } = opts, whole = n => Number.isSafeInteger(n) && n > 0;
88
+ if (!(cell > 0 && Number.isFinite(cell)) || !planar(origin).every(Number.isFinite) || !(size === null || (Array.isArray(size) && size.length === 2 && size.every(whole))))
89
+ throw codedError('grids-misuse', `grids.add('${name}'): cell must be a number > 0, origin finite and size [width, depth] whole numbers > 0 or left out; got ${JSON.stringify({ cell, origin, size })}`);
83
90
  const g = new Grid(this.engine, this, name, opts);
84
91
  this._grids.set(name, g);
85
92
  for (const [ln, rows] of Object.entries(opts.layers ?? {})) { const l = g.layer(ln); l._byContent = true; l._setBase(rows); }
@@ -258,31 +265,30 @@ const GRID_PARAMS = {
258
265
  */
259
266
  export function grids(opts = {}) {
260
267
  const o = readParams('grids', GRID_PARAMS, opts);
261
- let G = null, offOps = null;
262
- const subs = [];
268
+ let G = null;
263
269
  return {
264
- name: 'grids', type: 'world', label: 'Grid placement', stage: 'gameplay', requires: ['world'], params: GRID_PARAMS, options: o,
265
- install(e) {
270
+ // layout rules, not saved, before props: a props entry with grid places an item on one; a repeated load keeps the grid that exists
271
+ content: { grids: { desc: 'placement grids (name -> { cell, origin, size, zone?, flat? }); layout rules, not saved', undo: (d, { engine: e }) => e.grids.undoPoint(), commit(d, { engine: e }) { for (const [name, g] of Object.entries(d)) if (!e.grids.get(name)) e.grids.add(name, g); } } },
272
+ name: 'grids', skipKind: 'none', type: 'world', label: 'Grid placement', stage: 'gameplay', requires: ['world'], params: GRID_PARAMS, options: o,
273
+ install(e, ctx) {
266
274
  G = new Grids(e, o);
267
275
  e.i18n.add(TEXT); // grid.<code> player text for every built-in failure code, and the rotate action's label
268
- e.saves.register('grids', { atomic: true, version: 2, migrate: GRIDS_MIGRATE, save: () => G.toJSON(), load: d => G.fromJSON(d) });
269
- offOps = defineGridOps(e, G);
270
- subs.push(
271
- e.events.on('world:add', ({ id }) => G._reindex(id)),
272
- e.events.on('world:remove', ({ id }) => G._unindex(id)),
273
- e.events.on('world:change', ({ id, keys }) => { if (keys.includes('grid')) G._reindex(id); }),
274
- e.events.on('world:load', () => G._rebuild()),
275
- );
276
+ ctx.saves.register('grids', { atomic: true, version: 2, migrate: GRIDS_MIGRATE, save: () => G.toJSON(), load: d => G.fromJSON(d) });
277
+ defineGridOps(ctx, G);
278
+ ctx.track(e.events.on('world:add', ({ id }) => G._reindex(id)));
279
+ ctx.track(e.events.on('world:remove', ({ id }) => G._unindex(id)));
280
+ ctx.track(e.events.on('world:change', ({ id, keys }) => { if (keys.includes('grid')) G._reindex(id); }));
281
+ ctx.track(e.events.on('world:load', () => G._rebuild()));
276
282
  return G;
277
283
  },
278
284
  frame() { for (const t of G._tiles.values()) t.frame(); for (const p of G._previews) p.frame(); },
279
285
  explain: { grid: (e, q) => G._explain(q) },
280
286
  describe() { return G._describe(); },
281
287
  dispose() {
282
- for (const s of subs) s.remove();
283
- offOps?.();
284
288
  for (const t of G._tiles.values()) t.dispose();
285
289
  for (const p of [...G._previews]) p.remove();
286
290
  },
287
291
  };
288
292
  }
293
+
294
+ export const handRolled = 'none: cell maths is one Math.floor that any other code writes too';
@@ -26,50 +26,47 @@ export function placed(g, rule, item, cell, rotation, level = 0) {
26
26
  }
27
27
 
28
28
  /** Define the grid ops (once per install) @internal */
29
- export function defineGridOps(e, grids) {
30
- const handles = [
31
- e.ops.define('grid.place', {
32
- desc: 'Place an item on a grid: creates a world record whose footprint occupies cells in the item\'s occupancy layer. item = name from engine.grids.define; rotation = quarter turns; level = storey (default 0)',
33
- args: { grid: 'string', item: 'string', cell: 'any', rotation: 'int?', level: 'int?', fields: 'any?', id: 'string?' },
34
- can(e, { grid, item, cell, rotation = 0, level = 0, id, fields }) {
35
- const g = grids.get(grid);
36
- if (fields && RESERVED.some(k => k in fields)) return 'badFields';
37
- if (!g) return 'noGrid';
38
- if (id && e.world.get(id)) return 'idTaken';
39
- return g.can(item, cell, { rotation, level });
40
- },
41
- run(e, { grid, item, cell, rotation = 0, level = 0, fields, id }) {
42
- const g = grids._must(grid), rule = grids._rule(item);
43
- const rec = e.world.add({ ...(id ? { id } : {}), kind: rule.kind ?? item, ...structuredClone(rule.fields ?? {}), ...fields, ...placed(g, rule, item, cell, rotation, level) });
44
- return rec.id;
45
- },
46
- reasons: { ...REASONS, idTaken: 'A world record with that id exists', badFields: 'fields may not set id / kind / grid / position / rot: the placement owns them (pass id as its own argument)' },
47
- }),
48
- e.ops.define('grid.remove', {
49
- desc: 'Pick up a placed thing: removes its world record and frees its cells',
50
- args: { id: 'string' },
51
- can(e, { id }) { const r = e.world.get(id); return !r ? 'unknown' : !r.grid ? 'notPlaced' : true; },
52
- run(e, { id }) { const r = e.world.get(id), out = { item: r.grid.item ?? r.kind, kind: r.kind }; e.world.remove(id); return out; },
53
- reasons: REASONS,
54
- }),
55
- e.ops.define('grid.move', {
56
- desc: 'Move / turn a placed thing to another cell (or another grid / level); its own cells do not block it',
57
- args: { id: 'string', cell: 'any', rotation: 'int?', grid: 'string?', level: 'int?' },
58
- can(e, { id, cell, rotation, grid, level }) {
59
- const r = e.world.get(id);
60
- if (!r) return 'unknown';
61
- if (!r.grid) return 'notPlaced';
62
- const g = grids.get(grid ?? r.grid.id);
63
- if (!g) return 'noGrid';
64
- return g.can(grids._ruleOf(r.grid), cell, { rotation: rotation ?? r.grid.rotation, ignore: id, level: level ?? r.grid.level ?? 0 });
65
- },
66
- run(e, { id, cell, rotation, grid, level }) {
67
- const r = e.world.get(id), g = grids._must(grid ?? r.grid.id), rule = grids._ruleOf(r.grid);
68
- e.world.set(id, placed(g, rule, r.grid.item, cell, rotation ?? r.grid.rotation, level ?? r.grid.level ?? 0));
69
- return id;
70
- },
71
- reasons: REASONS,
72
- }),
73
- ];
74
- return () => { for (const h of handles) h.remove(); };
29
+ export function defineGridOps(ctx, grids) {
30
+ ctx.ops.define('grid.place', {
31
+ desc: 'Place an item on a grid: creates a world record whose footprint occupies cells in the item\'s occupancy layer. item = name from engine.grids.define; rotation = quarter turns; level = storey (default 0)',
32
+ args: { grid: 'string', item: 'string', cell: 'any', rotation: 'int?', level: 'int?', fields: 'any?', id: 'string?' },
33
+ can(e, { grid, item, cell, rotation = 0, level = 0, id, fields }) {
34
+ const g = grids.get(grid);
35
+ if (fields && RESERVED.some(k => k in fields)) return 'badFields';
36
+ if (!g) return 'noGrid';
37
+ if (id && e.world.get(id)) return 'idTaken';
38
+ return g.can(item, cell, { rotation, level });
39
+ },
40
+ run(e, { grid, item, cell, rotation = 0, level = 0, fields, id }) {
41
+ const g = grids._must(grid), rule = grids._rule(item);
42
+ const rec = e.world.add({ ...(id ? { id } : {}), kind: rule.kind ?? item, ...structuredClone(rule.fields ?? {}), ...fields, ...placed(g, rule, item, cell, rotation, level) });
43
+ return rec.id;
44
+ },
45
+ reasons: { ...REASONS, idTaken: 'A world record with that id exists', badFields: 'fields may not set id / kind / grid / position / rot: the placement owns them (pass id as its own argument)' },
46
+ });
47
+ ctx.ops.define('grid.remove', {
48
+ desc: 'Pick up a placed thing: removes its world record and frees its cells',
49
+ args: { id: 'string' },
50
+ can(e, { id }) { const r = e.world.get(id); return !r ? 'unknown' : !r.grid ? 'notPlaced' : true; },
51
+ run(e, { id }) { const r = e.world.get(id), out = { item: r.grid.item ?? r.kind, kind: r.kind }; e.world.remove(id); return out; },
52
+ reasons: REASONS,
53
+ });
54
+ ctx.ops.define('grid.move', {
55
+ desc: 'Move / turn a placed thing to another cell (or another grid / level); its own cells do not block it',
56
+ args: { id: 'string', cell: 'any', rotation: 'int?', grid: 'string?', level: 'int?' },
57
+ can(e, { id, cell, rotation, grid, level }) {
58
+ const r = e.world.get(id);
59
+ if (!r) return 'unknown';
60
+ if (!r.grid) return 'notPlaced';
61
+ const g = grids.get(grid ?? r.grid.id);
62
+ if (!g) return 'noGrid';
63
+ return g.can(grids._ruleOf(r.grid), cell, { rotation: rotation ?? r.grid.rotation, ignore: id, level: level ?? r.grid.level ?? 0 });
64
+ },
65
+ run(e, { id, cell, rotation, grid, level }) {
66
+ const r = e.world.get(id), g = grids._must(grid ?? r.grid.id), rule = grids._ruleOf(r.grid);
67
+ e.world.set(id, placed(g, rule, r.grid.item, cell, rotation ?? r.grid.rotation, level ?? r.grid.level ?? 0));
68
+ return id;
69
+ },
70
+ reasons: REASONS,
71
+ });
75
72
  }
@@ -34,7 +34,7 @@ export function layerTiles(e, layer, st) {
34
34
  mesh.name = `grid:${layer.grid.name}.${name}`; mesh.receiveShadow = true; mesh.frustumCulled = false;
35
35
  e.add(mesh, { owner: 'engine:grid' });
36
36
  let ver = -1, ground = 0, built = -1;
37
- const offs = ['level:loaded', 'ground:change'].map(n => e.events.on(n, () => { ground++; })); // new ground heights: a new level, or dug / raised terrain
37
+ const offs = ['level:loaded', 'level:unloaded', 'ground:change'].map(n => e.events.on(n, () => { ground++; })); // new ground heights: a level came or left, or dug / raised terrain
38
38
  const col = new THREE.Color(), g = layer.grid;
39
39
  function rebuild() {
40
40
  const cells = layer.query(), pos = [], clr = [], idx = [];
@@ -59,7 +59,7 @@ export function hlod(opts = {}) {
59
59
  function setFar(c, far) {
60
60
  if (c.far === far) return;
61
61
  c.far = far;
62
- // occlusion watches what is on screen. Taking the old watch away first shows anything it hid, so its mask never mixes with the one kept here
62
+ // occlusion watches what is on screen. Taking the old watch away first shows anything it hid
63
63
  c.watch?.remove();
64
64
  for (const p of c.proxy) p.visible = far;
65
65
  for (const m of c.originals) {
@@ -142,7 +142,7 @@ export function hlod(opts = {}) {
142
142
  for (const c of list) { setFar(c, false); c.watch?.remove(); for (const p of c.proxy) p.geometry.dispose(); for (const m of c.originals) delete m.userData.hlod; }
143
143
  api.cells = api.cells.filter(c => !list.includes(c));
144
144
  for (const l of lods.values()) l.node.visible = l.visible;
145
- e.detach(group); // proxies share the originals' materials and are never ray-registered: geometries were disposed above
145
+ group.removeFromParent(); // proxies share the originals' materials and are never ray-registered: geometries were disposed above
146
146
  },
147
147
  };
148
148
  handles.add(h);
@@ -164,12 +164,13 @@ export function hlod(opts = {}) {
164
164
 
165
165
  const addLevel = root => { levelHandle?.remove(); levelHandle = root ? api.add(root) : null; };
166
166
  return {
167
- name: 'hlod', type: 'picture', params: HLOD_PARAMS, options: opts, label: 'HLOD', optional: ['terrain', 'level'],
167
+ name: 'hlod', skipKind: 'none', type: 'picture', params: HLOD_PARAMS, options: opts, label: 'HLOD', optional: ['terrain', 'level'],
168
168
  install(engine, ctx) {
169
169
  e = engine;
170
170
  e.i18n.add({ 'zh-CN': { 'module.hlod': '远景合并' }, en: { 'module.hlod': 'distant merge' } });
171
171
  if (autoLevel) {
172
172
  ctx.track(e.events.on('level:loaded', ({ root }) => addLevel(root)));
173
+ ctx.track(e.events.on('level:unloaded', () => addLevel(null)));
173
174
  if (e.level?.ready && e.level.root) addLevel(e.level.root); // install hlod only after the level is ready
174
175
  }
175
176
  return api;
@@ -180,3 +181,5 @@ export function hlod(opts = {}) {
180
181
  describe() { return { cells: api.cells.length, far: api.cells.filter(c => c.far).length }; },
181
182
  };
182
183
  }
184
+
185
+ export const handRolled = 'none: merging far meshes is plain three.js, used on purpose';
@@ -173,13 +173,13 @@ export function hud(opts = {}) {
173
173
  };
174
174
 
175
175
  return {
176
- name: 'hud', type: 'ui', params: HUD_PARAMS, options: opts, label: 'Objective markers', optional: ['pickups', 'content', 'level', 'quests'], stage: 'effects', after: ['particles', 'settings'],
176
+ name: 'hud', skipKind: 'none', type: 'ui', params: HUD_PARAMS, options: opts, label: 'Objective markers', optional: ['pickups', 'content', 'level', 'quests'], stage: 'effects', after: ['particles', 'settings'],
177
177
  install(engine, ctx) {
178
178
  e = engine;
179
179
  e.i18n.add(STRINGS);
180
- defineHudParts(e, containers);
181
- for (const ev of ['quest:start', 'quest:step', 'quest:part', 'quest:done', 'quest:fail', 'save:loaded', 'session:start']) ctx.track(e.events.on(ev, syncQuests));
182
- // quest markers are derived from the quests save part: they belong to the old quests, and session:start / save:loaded rebuild them
180
+ defineHudParts(e, ctx, containers);
181
+ for (const ev of ['quest:start', 'quest:step', 'quest:part', 'quest:done', 'quest:fail', 'state:replaced']) ctx.track(e.events.on(ev, syncQuests));
182
+ // quest markers are derived from the quests save part: they belong to the old quests, and session:start / save:loaded rebuild them; session:failed too, the quests stayed
183
183
  ctx.track(e.events.on('session:end', () => { for (const m of quest.values()) m.remove(); quest.clear(); }));
184
184
  ctx.track(e.events.on('i18n:change', () => { for (const [id, it] of items) it.part?.update({ id, ...it.o }); }));
185
185
  return api;
@@ -199,3 +199,5 @@ export function hud(opts = {}) {
199
199
  },
200
200
  };
201
201
  }
202
+
203
+ export const handRolled = 'none: a score line is ordinary DOM that the game owns';
@@ -31,12 +31,12 @@ export const CSS = `
31
31
  * @param {() => { layer: HTMLElement, column(anchor?: string): HTMLElement }} root
32
32
  * @returns {void}
33
33
  */
34
- export function defineHudParts(e, root) {
34
+ export function defineHudParts(e, ctx, root) {
35
35
  const tools = { esc, t: (k, p) => e.t(k, p) };
36
36
  const tpl = name => e.ui.templates[name];
37
37
 
38
38
  // One marker: update({ x, y, arrow, angle, label, icon, distance }) moves and redraws it; hide() hides it
39
- e.ui.define('hud.marker', () => {
39
+ ctx.ui.define('hud.marker', () => {
40
40
  const el = document.createElement('div');
41
41
  el.className = 'threedog-hud-marker'; el.hidden = true; root().layer.appendChild(el);
42
42
  let html = null;
@@ -61,7 +61,7 @@ export function defineHudParts(e, root) {
61
61
  // a counter / bar lives in the column of its anchor; a changed anchor moves the element there
62
62
  const place = (el, d) => { const col = root().column(d.anchor ?? 'top-left'); if (el.parentNode !== col) col.appendChild(el); };
63
63
 
64
- e.ui.define('hud.counter', () => {
64
+ ctx.ui.define('hud.counter', () => {
65
65
  const el = document.createElement('div'); el.className = 'threedog-hud-counter';
66
66
  return {
67
67
  el,
@@ -77,7 +77,7 @@ export function defineHudParts(e, root) {
77
77
  };
78
78
  }, { multi: true });
79
79
 
80
- e.ui.define('hud.bar', () => {
80
+ ctx.ui.define('hud.bar', () => {
81
81
  const el = document.createElement('div'); el.className = 'threedog-hud-bar';
82
82
  let label;
83
83
  return {
@@ -1,14 +1,14 @@
1
1
  // What any level module must provide (fields: see gameplay/inventory.contract.js; shared check: @threedog/tools/contract).
2
2
  // Exactly what other code reads from engine.level: marker(name) (content places, the HUD), track(handle) (a handle that goes when the level unloads),
3
3
  // load (a level change); root / ready (hlod), markers (triggers), heightfield (vegetation's area; null when there is none).
4
- // A replacement also gives the ground with engine.setGround({ height, slope, type }) and emits 'level:loaded' after each load: nav and the path caches rebuild on
4
+ // A replacement also claims provides: ['level', 'ground'] and gives the ground with ctx.ground.provide({ height, slope, type }) and emits 'level:loaded' after each load and 'level:unloaded' when a level leaves: nav and the path caches rebuild on
5
5
  // it (not exercised by the shared check: it needs a scene). A game with several levels registers a 'level' save with first: true, so the level is up before the player lands.
6
6
  export default {
7
7
  name: 'level',
8
8
  api: ['marker', 'track', 'load'],
9
9
  fields: ['root', 'markers', 'ready', 'heightfield'],
10
10
  ops: [],
11
- events: ['level:loaded'],
11
+ events: ['level:loaded', 'level:unloaded', 'level:failed'],
12
12
  saves: {},
13
13
  describe: true,
14
14
  options: {},
@@ -4,13 +4,14 @@
4
4
  //
5
5
  // Internal to the level module only:
6
6
  // const hf = buildHeightfield(meshes, { cellSize: 0.5, outside: 0, typeOf });
7
- // hf.height(x, z, refY?) / hf.slope(x, z) / hf.type(x, z)
7
+ // hf.height(x, z, refY?) / hf.slope(x, z, refY?) / hf.type(x, z, refY?)
8
8
  //
9
9
  // Multi-layer (bridges, caves, interiors): up-facing surfaces more than layerGap apart at one grid point each get a layer (layerGap defaults to character height: a gap too low to stand in, like a crate on the ground, is not a layer). The top layer stays in H/T;
10
10
  // other layers are stored only for points that have several (extra: point index -> [{ y, t }]); single-layer levels pay no extra memory or time.
11
- // height(x, z, refY) with a reference height picks the highest layer not above refY + stepUp.
11
+ // A query with a reference height picks the highest layer not above refY + stepUp.
12
12
  import * as THREE from 'three';
13
13
  import { MOVEMENT_DEFAULTS } from '../../core/scene/movement.js';
14
+ import { layerUnder } from '../../core/scene/floor.js';
14
15
  import { warnOnce } from '../../core/base/validate.js';
15
16
  import { coded } from '../../core/base/errorHints.js';
16
17
 
@@ -112,14 +113,13 @@ export function buildHeightfield(meshes, { cellSize = 0.5, outside = 0, maxCells
112
113
  return id;
113
114
  }
114
115
 
115
- // highest layer below limit lim at a point; if none, take the lowest layer (so a cave with only a ceiling overhead still has a floor)
116
- function layerAt(k, lim) {
117
- const a = extra.get(k);
118
- if (!a || H[k] <= lim) return H[k];
119
- let best = -Infinity, low = H[k];
120
- for (const l of a) { if (l.y <= lim && l.y > best) best = l.y; if (l.y < low) low = l.y; }
121
- return best > -Infinity ? best : low;
116
+ // the layer under limit lim at a point, null for the top one (H / T); if none is under it, the lowest layer (so a cave with only a ceiling overhead still has a floor)
117
+ function lowerLayer(k, lim) {
118
+ const a = H[k] > lim && extra.size ? extra.get(k) : null;
119
+ return a ? layerUnder(a, lim) : null;
122
120
  }
121
+ const layerAt = (k, lim) => lowerLayer(k, lim)?.y ?? H[k];
122
+ const limit = refY => refY === undefined ? Infinity : refY + stepUp;
123
123
 
124
124
  const maxI = nx - 1, maxJ = nz - 1;
125
125
  return {
@@ -129,31 +129,27 @@ export function buildHeightfield(meshes, { cellSize = 0.5, outside = 0, maxCells
129
129
  const fx = (x - minX) / cell, fz = (z - minZ) / cell;
130
130
  if (!(fx >= 0 && fz >= 0 && fx <= maxI && fz <= maxJ)) return outside;
131
131
  const i = Math.min(maxI - 1, fx | 0), j = Math.min(maxJ - 1, fz | 0), tx = fx - i, tz = fz - j, k = j * nx + i;
132
- let h00 = H[k], h10 = H[k + 1], h01 = H[k + nx], h11 = H[k + nx + 1];
133
- if (refY !== undefined && extra.size && (extra.has(k) || extra.has(k + 1) || extra.has(k + nx) || extra.has(k + nx + 1))) {
134
- const lim = refY + stepUp;
135
- h00 = layerAt(k, lim); h10 = layerAt(k + 1, lim); h01 = layerAt(k + nx, lim); h11 = layerAt(k + nx + 1, lim);
136
- }
132
+ const lim = limit(refY), h00 = layerAt(k, lim), h10 = layerAt(k + 1, lim), h01 = layerAt(k + nx, lim), h11 = layerAt(k + nx + 1, lim);
137
133
  if (Math.max(h00, h10, h01, h11) - Math.min(h00, h10, h01, h11) > sharpEdge) return tz < 0.5 ? (tx < 0.5 ? h00 : h10) : (tx < 0.5 ? h01 : h11);
138
134
  return (h00 * (1 - tx) + h10 * tx) * (1 - tz) + (h01 * (1 - tx) + h11 * tx) * tz;
139
135
  },
140
- /** Slope = height change / horizontal distance (same as the terrain module) */
141
- slope(x, z) {
136
+ /** Slope = height change / horizontal distance (same as the terrain module); refY picks the layer as in height */
137
+ slope(x, z, refY) {
142
138
  const fx = (x - minX) / cell, fz = (z - minZ) / cell;
143
139
  if (!(fx >= 0 && fz >= 0 && fx <= maxI && fz <= maxJ)) return 0;
144
140
  const i = Math.min(maxI - 1, fx | 0), j = Math.min(maxJ - 1, fz | 0), tx = fx - i, tz = fz - j, k = j * nx + i;
145
- const h00 = H[k], h10 = H[k + 1], h01 = H[k + nx], h11 = H[k + nx + 1];
141
+ const lim = limit(refY), h00 = layerAt(k, lim), h10 = layerAt(k + 1, lim), h01 = layerAt(k + nx, lim), h11 = layerAt(k + nx + 1, lim);
146
142
  const gx = ((h10 - h00) * (1 - tz) + (h11 - h01) * tz) / cell, gz = ((h01 - h00) * (1 - tx) + (h11 - h10) * tx) / cell;
147
143
  return Math.sqrt(gx * gx + gz * gz);
148
144
  },
149
- /** Ground type at the nearest grid point */
150
- type(x, z) {
145
+ /** Ground type at the nearest grid point; refY picks the layer as in height */
146
+ type(x, z, refY) {
151
147
  const fx = (x - minX) / cell, fz = (z - minZ) / cell;
152
148
  // same bounds as height / slope: rounding alone would give a point up to half a cell outside the grid the edge's type while
153
149
  // height already says "outside", and a rule picking that type would plant on the outside plane next to the floor
154
150
  if (!(fx >= 0 && fz >= 0 && fx <= maxI && fz <= maxJ)) return 'default';
155
- const i = Math.round(fx), j = Math.round(fz);
156
- return types[T[j * nx + i]];
151
+ const k = Math.round(fz) * nx + Math.round(fx);
152
+ return types[lowerLayer(k, limit(refY))?.t ?? T[k]];
157
153
  },
158
154
  };
159
155
  }