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
@@ -5,71 +5,74 @@ import { engineOwned } from '../../core/scene/things.js';
5
5
  import { readParams, keysSchema } from '../../core/base/params.js';
6
6
  import { codedError, coded } from '../../core/base/errorHints.js';
7
7
  import { DEV_STRINGS, validControl } from './playerStrings.js';
8
+ import { vehicleById, seatFromRecord } from './seat.js';
8
9
 
9
10
  /** The player's world record: its id and its kind */
10
11
  export const PLAYER = 'player';
11
12
 
12
- /** vehicle id saved in the player record; a number is a save from before vehicles had ids (the index in rigid.vehicles) */
13
- const vehicleOf = (e, v) => v == null ? null : typeof v === 'number' ? (v >= 0 ? e.rigid?.vehicles[v] ?? null : null) : e.rigid?.vehicles.find(c => c.id === v) ?? null;
14
-
15
13
  /** Everything createPlayer refuses, before it touches the old player */
16
- function checkOptions(e, opts) {
17
- readParams('characters.createPlayer()', keysSchema([...CHARACTER_KEYS, 'spawn', 'control', 'cameraFollow']), opts);
14
+ function checkOptions(e, st, opts) {
15
+ readParams('characters.createPlayer()', keysSchema([...CHARACTER_KEYS, 'spawn', 'control', 'cameraFollow', 'id', 'input']), opts);
18
16
  const control = opts.control;
19
17
  if (control === undefined) throw codedError('player-control', DEV_STRINGS.noControl);
20
18
  if (!validControl(control)) throw codedError('player-control', fmt(DEV_STRINGS.badControl, { got: JSON.stringify(control) ?? String(control) }));
21
19
  if (!e.world) throw codedError('module-needs', DEV_STRINGS.noWorld);
20
+ if (opts.input !== undefined && !e.input.seats.includes(opts.input)) throw codedError('input-seat', 'characters.createPlayer(): input is a seat from engine.input.seat({ pad, keys })');
21
+ const id = opts.id ?? PLAYER;
22
+ if (opts.input) for (const [other, q] of st.players) if (other !== id && q.input === opts.input) throw codedError('input-seat', `characters.createPlayer(): this seat already drives player '${other}'`);
22
23
  }
23
24
 
24
25
  /** Place the player by the record (loading, reusing an existing record): do not write back to the record while placing, write once afterwards so record and
25
26
  * character agree */
26
- function placeByRecord(e, p, rec) {
27
- const car = vehicleOf(e, rec.vehicle), { x, y, z } = rec.position;
27
+ function placeByRecord(e, p, rec, id) {
28
+ const car = vehicleById(e, rec.vehicle), { x, y, z } = rec.position;
28
29
  p.recordId = null;
29
- if (p.vehicle && p.vehicle !== car) p.exit(); // when loading a walking save, exit the vehicle first, else every step pulls it back to the seat
30
- p.root.position.set(x, y, z); p.loadMotion(rec);
31
- if (car && p.vehicle !== car) p.enter(car);
32
- p.recordId = PLAYER; p._store();
30
+ if (p.vehicle && (p.vehicle !== car || p.seat !== (rec.seat ?? p.seat))) p.exit({ force: true }); // the save has it elsewhere: off this seat first, else every step pulls it back
31
+ p.root.position.set(x, y, z); p.loadMotion(rec); p._fromRecord(rec);
32
+ if (car && !p.vehicle) seatFromRecord(p, car, rec.seat); // no vehicle with that id yet: the record waits, addVehicle answers it (seat.js)
33
+ p.recordId = id; p._store();
34
+ if (p.vehicle && rec.vehicle !== p._ride.id) p._writeSeat(p._ride.id, p.seat); // an old save named it by index: from here on by id
33
35
  }
34
36
 
35
37
  /**
36
38
  * The step of the player's control slot. Gameplay keys are read in the fixed step (input snapshot, frame-rate independent); frame only plays animation.
37
39
  * The input is the base holder of the slot: engine.control runs this step (characters fixed, index.js) only while it is in charge, so a walkTo, a game script
38
40
  * or a cutscene pauses keys, jump and driving alike, and nothing else moves the player in that step.
39
- * dt is the player's channel (bullet time on 'player', time.local on 'player').
41
+ * dt is the player's channel (bullet time on 'player', time.local on 'player'). input: engine.input, or the seat of a local player.
40
42
  */
41
- function inputStep(e, api, p, control) {
43
+ function inputStep(e, api, p, control, input) {
42
44
  let autoSpeed = null; // the autopilot speed the move.speed entry holds now (null: no entry)
45
+ let rig = e.cameraRig; // the rig this player was handed to: a replaced one starts with nothing to follow (setCamera hands the target over itself)
43
46
  return dt => {
44
- const has = a => e.input.actions.has(a); // 'interact' exists only with a module or binding that declares it
47
+ if (rig !== e.cameraRig) {
48
+ rig = e.cameraRig;
49
+ if (rig && !rig.target && p.cameraFollow && e.player === p) rig.follow(p.vehicle?.object ?? p.root, p.vehicle?.camera);
50
+ }
51
+ const has = a => input.actions.has(a); // 'interact' exists only with a module or binding that declares it
45
52
  // when the interactions module is installed, the vehicle's "exit" interaction handles it
46
- if (p.vehicle) { if (!e.interactions && has('interact') && e.input.pressed('interact')) p.exit(); }
47
- else if (p.canJump && e.input.pressed('jump')) p.jump();
48
- if (p.vehicle && p.seat === 0) { const a = e.input.autopilot || e.input.axis; p.vehicle.drive(a.y, a.x, e.input.down('brake') ? 1 : 0); }
53
+ if (p.vehicle) { if (!e.interactions && has('interact') && input.pressed('interact')) p.exit(); }
54
+ else if (p.canJump && input.pressed('jump')) p.jump();
49
55
  // autopilot { speed } (benchmarks, recordings) is a move.speed entry like any other modifier, not a second way to set the speed
50
- const ap = e.input.autopilot?.speed;
56
+ const ap = input.autopilot?.speed;
51
57
  // taken again only when the speed changed (or the entry was cleared): a take every step changed the stack each step, so every
52
58
  // speed read recomputed instead of using the stack's memo (core/ops/stacks.js)
53
- if (ap != null) { if (ap !== autoSpeed || !e.stacks.get('move.speed').has('autopilot', PLAYER)) e.mod('move.speed', { owner: 'autopilot', id: PLAYER, set: ap, layer: 'debug' }); }
54
- else if (autoSpeed != null) e.stacks.get('move.speed').release('autopilot', { id: PLAYER });
59
+ if (ap != null) { if (ap !== autoSpeed || !e.stacks.get('move.speed').has('autopilot', p.id)) e.mod('move.speed', { owner: 'autopilot', id: p.id, set: ap, layer: 'debug' }); }
60
+ else if (autoSpeed != null) e.stacks.get('move.speed').release('autopilot', { id: p.id });
55
61
  autoSpeed = ap ?? null;
56
- return control === 'camera' ? api.moveInput() : control(p, e.input, dt);
62
+ return control === 'camera' ? api.moveInput(input) : control(p, input, dt);
57
63
  };
58
64
  }
59
65
 
60
66
  /** The listeners that keep the record and the player together; returns their handles */
61
- function watchRecord(e, W, p) {
62
- // record the stable id of the vehicle the player is in (world.set: world:change fires; it follows an enter / exit that already happened)
63
- const setCar = id => e.ops.allow(() => W.set(PLAYER, { vehicle: id }));
67
+ function watchRecord(e, W, p, id) {
68
+ const begin = p.position.clone(), rest = p.saveMotion(); // a player made after start() is in no new-game state: this is how a new playthrough has it
64
69
  return [
65
- e.events.on('vehicle:enter', ({ character }) => { if (character === p) setCar(p.vehicle?.id ?? null); }),
66
- e.events.on('vehicle:exit', ({ character }) => { if (character === p) setCar(null); }),
67
70
  // loading: after world is replaced wholesale, place the player back by the record; if the save has no player record (saved before the player was
68
71
  // created), add one from the current state
69
72
  e.events.on('world:load', () => {
70
- const rec = W.get(PLAYER);
71
- if (rec) placeByRecord(e, p, rec);
72
- else { W.add({ id: PLAYER, kind: PLAYER, position: p.position, vehicle: null }); p._store(); }
73
+ const rec = W.get(id);
74
+ if (rec) placeByRecord(e, p, rec, id);
75
+ else { if (e.session.replacing) { if (p.vehicle) p.exit({ force: true }); p.root.position.copy(begin); p.loadMotion(rest); } W.add({ id, kind: PLAYER, position: p.position, vehicle: null }); p._store(); }
73
76
  }),
74
77
  ];
75
78
  }
@@ -78,31 +81,40 @@ function watchRecord(e, W, p) {
78
81
  * engine.characters.createPlayer, documented there
79
82
  * @param {any} e engine
80
83
  * @param {any} api engine.characters
81
- * @param {any} st the module's state: gets the new player's animatePlayer and disposePlayer
84
+ * @param {any} st the module's state: the new player joins st.players
82
85
  * @param {any} opts
83
86
  */
84
87
  export function createPlayer(e, api, st, opts) {
85
- checkOptions(e, opts);
86
- const W = e.world;
87
- api.removePlayer(); // existing player: dispose the old one first (else two characters respond to keys)
88
- const p = new Character(e, { channel: 'player', ...opts }), had = W.get(PLAYER);
88
+ checkOptions(e, st, opts);
89
+ const W = e.world, { id = PLAYER, input = e.input } = opts;
90
+ api.removePlayer(id); // a player of this id: dispose the old one first (else two characters respond to the same keys)
91
+ const p = new Character(e, { channel: 'player', ...opts }), had = W.get(id);
92
+ // engine.player is the first player. The one without an id is always it, as a replaced one was; a second player must not take the driving keys or camera in enter()
93
+ const first = id === PLAYER || !e.player;
89
94
  p.cameraFollow = !!opts.cameraFollow; // read again on vehicle exit and a new session (Character.js, camera/common.js)
90
- if (DEV && opts.cameraFollow === undefined && e.cameraRig) warnOnce(coded('player-control', DEV_STRINGS.noFollow));
91
- if (!had) W.add({ id: PLAYER, kind: PLAYER, position: [0, 0, 0], vehicle: null });
92
- if (had && !opts.spawn) { e.player = p; placeByRecord(e, p, had); } // a record in a vehicle enters it here, and enter() gives the driving keys and camera only to engine.player
93
- else { p.recordId = PLAYER; p.placeAt(opts.spawn || api.findSpawn()); }
95
+ if (DEV && first && opts.cameraFollow === undefined && e.cameraRig) warnOnce(coded('player-control', DEV_STRINGS.noFollow));
96
+ if (!had) W.add({ id, kind: PLAYER, position: [0, 0, 0], vehicle: null });
97
+ if (had && !opts.spawn) { if (first) e.player = p; placeByRecord(e, p, had, id); } // a record in a vehicle enters it here, and enter() gives the driving keys and camera only to engine.player
98
+ else { p.recordId = id; p.placeAt(opts.spawn || api.findSpawn()); }
94
99
  e.scene.add(engineOwned('characters', p.root));
95
100
  // a touch jump button only when the game bound jump (a game without jumping gets no button)
96
- if (p.canJump && e.input.keysOf('jump').length) e.input.touchButton('jump', 'input.jump');
97
- e.player = p;
101
+ const jump = first && p.canJump && e.input.keysOf('jump').length ? e.input.touchButton('jump', 'input.jump') : null; // released: entry.dispose below, which the module's dispose runs
102
+ if (first) e.player = p;
98
103
  if (p.cameraFollow && !p.vehicle) e.cameraRig?.follow(p.root);
99
- const held = e.control.take(p, { owner: 'player-input', layer: 'base', step: inputStep(e, api, p, opts.control) });
100
- st.animatePlayer = dt => p.animate(dt);
101
- const watching = watchRecord(e, W, p);
102
- st.disposePlayer = () => {
103
- st.animatePlayer = null; held.remove(); for (const h of watching) h.remove();
104
- p.recordId = null; p.dispose(); W.remove(PLAYER);
105
- if (e.player === p) e.player = null;
104
+ // in the map before control.take: the control lookup finds a held character by id through it
105
+ const entry = { character: p, input, dispose: null };
106
+ st.players.set(id, entry);
107
+ if (input !== e.input) input.actor = id;
108
+ const held = e.control.take(p, { owner: 'player-input', layer: 'base', step: inputStep(e, api, p, opts.control, input) });
109
+ // what the keys ask of the pedal, while the keys are in charge: the seat reads it each step, so a holder above lets go of it (seat.js)
110
+ p._pedal = () => { if (!held.active) return null; const a = input.autopilot || input.axis; return [a.y, a.x, input.down('brake') ? 1 : 0]; };
111
+ const watching = watchRecord(e, W, p, id);
112
+ // keepRecord: the module is going, not the player; its place stays in world for the next createPlayer
113
+ entry.dispose = (keepRecord = false) => {
114
+ st.players.delete(id); held.remove(); jump?.remove(); for (const h of watching) h.remove();
115
+ if (input.actor === id) input.actor = null;
116
+ p.recordId = null; p.dispose(); if (!keepRecord) W.remove(id);
117
+ if (e.player === p) e.player = st.players.values().next().value?.character ?? null; // the next player is the first now
106
118
  };
107
119
  return p;
108
120
  }
@@ -0,0 +1,56 @@
1
+ // The seat: one relation { rider, vehicle, id, seat } between a character and anything with the vehicle contract. Owned here, so it holds whoever the control slot's holder is:
2
+ // a holder only says what the driver wants. The rider's world record keeps the vehicle id and the seat, written when the relation changes and read back on a load.
3
+ // Vehicles are found through one registry, not through the module that built them: rigid joins its cars, a game joins its own (characters.addVehicle), and enter joins whatever has an id.
4
+ // Why a vehicle that joins answers the records: a car built after the load is the same case as a car built before it, so the rider sits and the record never lies.
5
+ // Per engine, like the supports (movers/support.js): a hand-built Character has a seat with no module around it.
6
+ const books = new WeakMap();
7
+
8
+ /** @param {any} e @returns {{ rides: Set<any>, vehicles: Set<any> }} */
9
+ export function seatsOf(e) {
10
+ let s = books.get(e);
11
+ if (!s) books.set(e, s = { rides: new Set(), vehicles: new Set() });
12
+ return s;
13
+ }
14
+
15
+ /** The vehicle a record names. A number is a save from before vehicles had ids: the place in the registry, as it was in rigid.vehicles */
16
+ export function vehicleById(e, ref) {
17
+ const list = [...seatsOf(e).vehicles].filter(v => !v.gone);
18
+ return ref == null ? null : typeof ref === 'number' ? list[ref] ?? null : list.find(v => v.id === ref) ?? null;
19
+ }
20
+
21
+ /** Back on the seat a record names. Whoever sits there now is from the state being replaced: it goes without touching its record, which its own turn reads */
22
+ export function seatFromRecord(c, v, seat) {
23
+ if (seat == null) return c.enter(v); // a save from before the seat was saved
24
+ const other = seat === 0 ? v.driver : v.passengers?.find(r => r.seat === seat);
25
+ if (other && other !== c) { const id = other.recordId; other.recordId = null; other.exit({ force: true }); other.recordId = id; }
26
+ v.passengers ??= [];
27
+ c._sit(v, seat);
28
+ }
29
+
30
+ /** The records that name this vehicle. A far NPC has no model, so only its record knows */
31
+ const ridersOf = (e, v) => (v.id == null ? [] : e.world?.query({}).filter(r => r.vehicle === v.id) ?? []);
32
+
33
+ /** characters.addVehicle: join the registry, and seat the riders whose record is waiting for this id. A far NPC is seated by its next build (npcView.js). A vehicle gone for good answers those records too: nothing will come for them */
34
+ export function addVehicle(e, v) {
35
+ const book = seatsOf(e).vehicles;
36
+ book.add(v);
37
+ for (const rec of ridersOf(e, v)) { const c = e.control.characterOf(rec.id); if (c && !c.vehicle) seatFromRecord(c, v, rec.seat); }
38
+ return { remove() { book.delete(v); if (v.gone) for (const { id } of ridersOf(e, v)) e.ops.allow(() => e.world.set(id, { vehicle: null, seat: null })); } };
39
+ }
40
+
41
+ /** Every fixed step, after the holders: a rider stays on its seat, and the pedal goes up when no one in charge is pressing it */
42
+ export function stepSeats(e) {
43
+ for (const ride of [...seatsOf(e).rides]) {
44
+ const { rider: c, vehicle: v, seat } = ride;
45
+ c.root.position.copy(v.seatPosition(seat));
46
+ // a visible rider turns with the vehicle (a hidden one only needs the position: saves, interactions, trigger zones measure from it)
47
+ if (c.root.visible) { v.object.getWorldQuaternion(c.root.quaternion); c.facing = c.root.rotation.y; }
48
+ c.moveAmount = Math.abs(v.speed); c.state = c.stateMark = 'drive';
49
+ if (seat === 0) {
50
+ const want = c._pedal?.();
51
+ if (want) { v.drive(...want); ride.pedal = true; }
52
+ else if (ride.pedal) { v.drive(0, 0, 0); ride.pedal = false; } // only on the change: a game driving the car itself is not overwritten
53
+ }
54
+ c._store();
55
+ }
56
+ }
@@ -1,20 +1,23 @@
1
1
  // What character.enter(vehicle) needs from anything a character rides (an object contract, not a module: shared check @threedog/tools/contract,
2
2
  // runContract sees kind: 'object'). rigid.addWheeled's car passes it; so must a game's own boat, horse, mech or lift, so riding needs no rigid module.
3
- // seatPosition(seat) / exitPosition(seat) world { x, y, z } for that seat (0 = driver): a rider is kept on its seat; exit places it at the exit
3
+ // seatPosition(seat) / exitPosition(seat, n = 0) world { x, y, z } for that seat (0 = driver): a rider is kept on its seat. n numbers the exits, best first, null past the last; a vehicle with one exit ignores n.
4
+ // exit() takes the first walkable one, and with none it refuses and the rider stays. A placement or a vehicle going uses exit({ force: true })
4
5
  // speed m/s, a number: the driver's moveAmount (animation, describe)
5
- // drive(throttle, steer, brake) called every fixed step while the player drives (-1..1, -1..1, 0..1); the driver's exit calls drive(0, 0, 1)
6
+ // drive(throttle, steer, brake) called every fixed step while the keys drive (-1..1, -1..1, 0..1); drive(0, 0, 0) when a holder above takes over; the driver's exit calls drive(0, 0, 1)
6
7
  // driver set by enter / exit (null when empty); object: what the camera follows; camera?: { distance, height } while driving
7
8
  // seats? how many riders, driver included (default 1): enter takes the driver seat, else the first free passenger seat
8
9
  // hideDriver? false keeps riders visible on their seats (bikes, open carts); default hidden
9
10
  // passengers optional: enter creates the list of seated passengers when missing (rigid vehicles start with [])
10
- // id optional: saves put the player back into the vehicle with that id (rigid vehicles have one)
11
+ // gone? true once removed for good: an undo cannot seat anyone there (rigid vehicles set it; leaving the scene counts too), and with it set, the remove() addVehicle returned lets go of the records still waiting for this id. Whoever owns the vehicle exits its riders first, also when its module leaves: only the owner knows it is going
12
+ // id optional: the rider's record keeps it and the seat, and a load puts it back on that seat. characters.addVehicle(vehicle) joins before or after the load; rigid vehicles join themselves
11
13
  export default {
12
14
  name: 'vehicle',
13
15
  kind: 'object',
14
- methods: ['seatPosition', 'exitPosition', 'drive'],
16
+ api: ['seatPosition', 'exitPosition', 'drive'],
15
17
  fields: ['speed', 'driver', 'object'],
18
+ position: { authority: 'solver', writers: { seat: 'seatPosition(seat) places a rider every step; exitPosition(seat) places it once on the way out' } },
16
19
  // optional fields: when present they must pass (enter reads them with defaults)
17
- optional: { seats: v => Number.isInteger(v) && v >= 1, hideDriver: v => typeof v === 'boolean', passengers: Array.isArray },
20
+ optional: { seats: v => Number.isInteger(v) && v >= 1, hideDriver: v => typeof v === 'boolean', passengers: Array.isArray, gone: v => typeof v === 'boolean' },
18
21
  points: ['seatPosition', 'exitPosition'], // called for every seat (0 .. seats - 1), must return finite world { x, y, z }
19
22
  numbers: ['speed'],
20
23
  calls: [['drive', 1, 0, 0], ['drive', 0, 0, 1]], // full throttle, then the brake exit() uses
@@ -1,14 +1,17 @@
1
1
  // character.walkTo(target, opts): follow characters.findPath on fixed steps. Exists so a hand-written guard / pet / follower does not re-implement
2
2
  // path following (turn rate, skipping passed points, stuck detection) every time. Steering only: the mover still owns position (see Character.js).
3
3
  // Transient on purpose (like a noSkip timer): a walk is not saved and engine.skip does not fast-forward it. So it never outlives what it steers:
4
- // one walk per character (a new walkTo cancels the old, else two hooks would fight over move()), and character.dispose() or a save load
5
- // ends it with 'cancelled' (the loaded state has its own positions; the old path no longer applies). A game that must resume a walk saves the target.
4
+ // one walk per character (a new walkTo cancels the old, else two hooks would fight over move()), and whatever TASK_ENDS (core/ops/control.js) lists
5
+ // ends it with 'cancelled'. A walk listens to nothing itself. A game that must resume a walk saves the target.
6
6
  // Control: a walk holds the character on layer 'script' (core/ops/control.js). So the player's keys pause while it walks and come back when it ends; a
7
7
  // cutscene above pauses the walk (no progress, no stuck clock) and the walk carries on after; another script owner on the same character is a
8
8
  // control-conflict error instead of two hooks pushing one body.
9
+ // Links on the path are crossed as NPCs cross them (moveHelpers.js). A walk cancelled by its handle, a newer order or the character going, or paused by a holder above, lands the character at the far end; every other ending has its own idea of where the body is, so it only drops the crossing.
9
10
  import { xzOf, wrapAngle } from '../../core/base/math.js';
10
- import { nextPoint } from './moveHelpers.js';
11
+ import { nextPoint, sameLevel, climbTo, startLink, stepLink, landLink, linkAhead, LINK_REACH } from './moveHelpers.js';
11
12
 
13
+ const STRAIGHT_UP = 0.05; // metres on the ground plane under which the next point counts as straight above or below
14
+ const LANDS = new Set(['order', 'gone']); // the endings that leave a crossing to finish on its far side (see the header)
12
15
  const STUCK_PROGRESS = 0.15; // metres the character must gain on the next point within the stuck window, else it counts as stuck
13
16
 
14
17
  /**
@@ -17,41 +20,52 @@ const STUCK_PROGRESS = 0.15; // metres the character must gain on the next poi
17
20
  */
18
21
  export function walkTo(ch, target, { speed, arrive = 0.5, turnRate = 8, stuckSeconds = 1.5, maxRepaths = 3, run = false } = {}) {
19
22
  const e = ch.engine;
20
- let done, hook, path = null, i = 0, heading = null, repaths = 0, bestD = Infinity, stuckT = 0;
23
+ let done, hook, path = null, i = 0, heading = null, repaths = 0, bestD = Infinity, stuckT = 0, crossing = null;
21
24
  const promise = new Promise(res => { done = res; });
22
- ch._walk?.remove(); // one walk per character: the newer order wins
23
- let onLoad = null, handle = null, ctl = null;
25
+ e.control.endTasks(ch, 'order'); // one walk per character: the newer order wins
26
+ let ctl = null;
24
27
  // speed is a move.speed entry for the walk (not a speed argument to move): haste / mud modifiers still apply on top, and it ends with the walk
25
28
  const sped = speed != null ? e.mod('move.speed', { owner: 'walkTo', id: ch.id, set: speed }) : null;
26
29
  const runMod = sped && run ? e.mod('move.runSpeed', { owner: 'walkTo', id: ch.id, set: speed }) : null;
27
30
  const finish = status => {
28
- if (!hook) return; hook.remove(); hook = null; onLoad?.remove(); ctl.remove(); if (ch._walk === handle) ch._walk = null;
31
+ if (!hook) return; hook.remove(); hook = null; ctl.remove();
32
+ if (crossing) landLink(ch, crossing);
29
33
  finishMods();
30
34
  done({ status });
31
35
  };
32
36
  function finishMods() { sped?.remove(); runMod?.remove(); }
33
37
  const solve = () => {
34
- path = e.characters.findPath(ch.root.position, target, { radius: ch.radius });
38
+ path = e.characters.findPath(ch.root.position, target, { radius: ch.radius, id: ch.id });
35
39
  i = 0; bestD = Infinity; stuckT = 0;
36
40
  return !!path?.length;
37
41
  };
38
- if (!solve()) { finishMods(); queueMicrotask(() => done({ status: 'noPath' })); return Object.assign(promise, { remove() {} }); }
39
- try { ctl = e.control.take(ch, { owner: 'walkTo', layer: 'script' }); } catch (err) { finishMods(); throw err; }
40
- onLoad = e.events.on('save:loaded', () => finish('cancelled'));
42
+ const refuse = status => { finishMods(); queueMicrotask(() => done({ status })); return Object.assign(promise, { remove() {} }); };
43
+ if (ch.vehicle || e.control.of(ch)?.layer === 'physics') return refuse('cancelled'); // what would end the walk already holds: it could only wait
44
+ if (!solve()) return refuse('noPath');
45
+ try { ctl = e.control.take(ch, { owner: 'walkTo', layer: 'script', task: why => { if (hook && !LANDS.has(why)) crossing = null; finish('cancelled'); } }); } catch (err) { finishMods(); throw err; }
41
46
  hook = e.onFixed(() => {
42
- if (!ctl.active) return; // paused under a cutscene (or another higher holder): keep the path and the stuck clock as they are
47
+ if (!ctl.active && !crossing) return; // paused under a cutscene (or another higher holder): keep the path and the stuck clock as they are
43
48
  const dt = e.time.dt(ch.channel, ch.id); // the character's time channel: bullet time slows a walk too
49
+ if (crossing) { if (ctl.active ? stepLink(ch, crossing, dt) : landLink(ch, crossing)) { crossing = null; i++; bestD = Infinity; stuckT = 0; } return; }
44
50
  const [gx, gz] = xzOf(target), [x, z] = xzOf(ch.root.position);
45
- if (Math.hypot(gx - x, gz - z) <= arrive) { ctl.move(0, 0, false, dt); return finish('arrived'); }
46
- const next = nextPoint(path, i, x, z, arrive * 0.6);
51
+ if (Math.hypot(gx - x, gz - z) <= arrive && !linkAhead(path, i) && sameLevel(e, ch.root.position, target)) { ctl.move(0, 0, false, dt); return finish('arrived'); }
52
+ const next = nextPoint(path, i, x, ch.root.position.y, z, arrive * 0.6, e.movement.height);
47
53
  if (next !== i) { i = next; bestD = Infinity; stuckT = 0; } // a point passed is progress, and the next one starts farther away than the best distance to the last
48
54
  const p = path[i], d = Math.hypot(p.x - x, p.z - z);
55
+ // the end of the path, and the target has left it: a follower plans on from here, it is not stuck. A new plan that ends here too is a target out of reach
56
+ if (i === path.length - 1 && d < arrive && Math.hypot(gx - p.x, gz - p.z) > arrive) {
57
+ if (!solve() || Math.hypot(path.at(-1).x - x, path.at(-1).z - z) < arrive) { ctl.move(0, 0, false, dt); finish('noPath'); }
58
+ return;
59
+ }
60
+ if (p.link && d < LINK_REACH) { crossing = startLink(ch, p.link); return; }
49
61
  // stuck: no gain on the next point for stuckSeconds, so replan; give up after maxRepaths
50
- if (d < bestD - STUCK_PROGRESS) { bestD = d; stuckT = 0; }
62
+ const left = Math.hypot(d, (p.y ?? ch.root.position.y) - ch.root.position.y); // height counts: a flyer on a vertical leg gains nothing on the ground plane
63
+ if (left < bestD - STUCK_PROGRESS) { bestD = left; stuckT = 0; }
51
64
  else if ((stuckT += dt) > stuckSeconds) {
52
65
  if (++repaths > maxRepaths || !solve()) { ctl.move(0, 0, false, dt); return finish(repaths > maxRepaths ? 'stuck' : 'noPath'); }
53
66
  return;
54
67
  }
68
+ if (d < STRAIGHT_UP) { ctl.move(0, 0, run, dt, climbTo(ch.root.position, p)); return; } // the point is right above or below: atan2(0, 0) would send it sideways
55
69
  const want = Math.atan2(p.x - x, p.z - z);
56
70
  heading ??= ch.facing;
57
71
  const diff = wrapAngle(want - heading);
@@ -59,8 +73,7 @@ export function walkTo(ch, target, { speed, arrive = 0.5, turnRate = 8, stuckSec
59
73
  heading += Math.abs(diff) <= step ? diff : Math.sign(diff) * step;
60
74
  // slow down while the body is still turning toward the point, so it does not overshoot sideways
61
75
  const align = Math.max(0.2, Math.cos(Math.min(Math.abs(diff), Math.PI / 2)));
62
- ctl.move(Math.sin(heading) * align, Math.cos(heading) * align, run, dt); // the direction's length scales the speed
76
+ ctl.move(Math.sin(heading) * align, Math.cos(heading) * align, run, dt, climbTo(ch.root.position, p)); // the direction's length scales the speed
63
77
  });
64
- handle = Object.assign(promise, { remove() { finish('cancelled'); } });
65
- return ch._walk = handle;
78
+ return Object.assign(promise, { remove() { finish('cancelled'); } });
66
79
  }
@@ -5,10 +5,11 @@
5
5
  // Positions are always a single argument (Vector3 / Object3D / [x, y, z] / { x, z }); sizes go in the options object:
6
6
  // const h = engine.collision.addBox(house, { halfWidth: 3, halfDepth: 2, rotation: 0.3 }); h.remove();
7
7
  import { Box3, Vector3 } from 'three';
8
- import { xzOf } from '../../core/base/math.js';
8
+ import { xzOf, yOf } from '../../core/base/math.js';
9
+ import { surfaceOr } from '../../core/scene/ground.js';
9
10
 
10
11
  import { readParams, keysSchema } from '../../core/base/params.js';
11
- import { CollisionGrid, gridBlocks } from './grid.js';
12
+ import { CollisionGrid, gridBlocks, bodyHits } from './grid.js';
12
13
  import { codedError } from '../../core/base/errorHints.js';
13
14
 
14
15
  /** One axis of the slab test: narrows S.t0 / S.t1 to where the ray is inside |o + d t| <= h; false when it misses */
@@ -53,7 +54,8 @@ export class Collision {
53
54
  * Keep an outside copy of the static colliders (boxes and circles) in step, e.g. physics colliders or navmesh obstacles. add(type, data) builds the
54
55
  * copy of one collider and returns it; remove(piece, data) drops one. sync() does the work only when `version` moved since the last sync, then adds
55
56
  * what is new (in forEachStatic order) and removes what is gone; returns whether anything was compared. clear() forgets every piece without calling
56
- * remove (the outside world they lived in was thrown away) so the next sync builds all again.
57
+ * remove (the outside world they lived in was thrown away) so the next sync builds all again; clear(true) calls remove on each (this collision module is leaving, the
58
+ * outside world stays).
57
59
  * Why one shared mirror: nav and rigid each had their own copy of this diff, and the two copies drifted (one checked readiness, the other a version
58
60
  * field of its own); a third consumer would copy it a third time.
59
61
  * @param {{ add: (type: 'box' | 'circle', data: any) => any, remove: (piece: any, data: any) => void }} fns
@@ -71,13 +73,13 @@ export class Collision {
71
73
  seen.clear();
72
74
  return true;
73
75
  },
74
- clear() { pieces.clear(); version = -1; },
76
+ clear(drop = false) { if (drop) for (const [o, p] of pieces) remove(p, o); pieces.clear(); version = -1; },
75
77
  get size() { return pieces.size; },
76
78
  };
77
79
  }
78
80
 
79
81
  /**
80
- * Add a circle collider (pillar, statue, campfire): position is the centre, radius (default 0.5), height (default 6).
82
+ * Add a circle collider (pillar, statue, campfire): position is the centre, radius (default 0.5), height (default 6). It stands on the ground and stops walkers on every floor; a pillar upstairs is an addBox with a y.
81
83
  * occluder: false keeps it from pulling the follow camera in (walkers are still stopped), e.g. forest trunks the camera may pass through. Returns a handle { remove() }
82
84
  */
83
85
  addCircle(position, opts = {}) {
@@ -133,14 +135,17 @@ export class Collision {
133
135
  obj.updateMatrixWorld(true);
134
136
  // a THREE.LOD is measured by its full model: a low level may stick out a little, and collision must not change with which levels exist
135
137
  const box = new Box3().setFromObject(obj.isLOD ? obj.levels[0].object : obj), c = box.getCenter(new Vector3()), s = box.getSize(new Vector3());
136
- return this.addBox(c, { halfWidth: s.x / 2 + pad, halfDepth: s.z / 2 + pad, height: s.y, occluder });
138
+ return this.addBox(c, { halfWidth: s.x / 2 + pad, halfDepth: s.z / 2 + pad, height: s.y, y: box.min.y, occluder });
137
139
  }
138
140
 
139
141
  // The per-frame walkers below pass state through fields instead of building callbacks: resolve() and cameraDistance() run every step / frame.
140
142
  // resolve saves and restores its fields, so a nested call (from a ground collider callback) stays safe.
141
143
  _pushCircle(pos, a, b, c, radius) {
142
- const dx = pos.x - a, dz = pos.z - b, d = Math.hypot(dx, dz), min = radius + c;
143
- if (d < min && d > 1e-5) { pos.x = a + dx / d * min; pos.z = b + dz / d * min; this._rHit = true; }
144
+ let dx = pos.x - a, dz = pos.z - b, d = Math.hypot(dx, dz);
145
+ const min = radius + c;
146
+ if (d >= min) return;
147
+ if (d <= 1e-5) { dx = 1; dz = 0; d = 1; } // dead centre has no direction: always leave towards +x, so the same input gives the same exit
148
+ pos.x = a + dx / d * min; pos.z = b + dz / d * min; this._rHit = true;
144
149
  }
145
150
  _pushBox(pos, bx, radius) {
146
151
  const lx0 = pos.x - bx.x, lz0 = pos.z - bx.z;
@@ -152,22 +157,27 @@ export class Collision {
152
157
  if (d > 1e-5) { nx = dx / d; nz = dz / d; nx = lx + nx * (radius - d); nz = lz + nz * (radius - d); }
153
158
  else { // centre is inside the box: push out along the nearest edge
154
159
  const px = bx.hw - Math.abs(lx), pz = bx.hd - Math.abs(lz);
155
- if (px < pz) { nx = Math.sign(lx) * (bx.hw + radius); nz = lz; } else { nx = lx; nz = Math.sign(lz) * (bx.hd + radius); }
160
+ if (px < pz) { nx = (lx < 0 ? -1 : 1) * (bx.hw + radius); nz = lz; } else { nx = lx; nz = (lz < 0 ? -1 : 1) * (bx.hd + radius); }
156
161
  }
157
162
  pos.x = bx.x + nx * bx.c + nz * bx.s; pos.z = bx.z - nx * bx.s + nz * bx.c; this._rHit = true;
158
163
  }
159
164
 
160
- /** @internal Push a character of radius `radius` out of obstacles; edits pos.x / pos.z directly. Returns whether a collision happened */
165
+ /**
166
+ * @internal Push a character of radius `radius` out of obstacles; edits pos.x / pos.z directly. Returns whether a collision happened.
167
+ * A box with an explicit `y` occupies y .. y + height, and stops only a body (pos.y .. + movement.height) that overlaps that span: a wall upstairs leaves the floor below free.
168
+ * A box without `y` is a footprint, as is every box when pos has no y: those stop at any height. walkableAt and A* read boxes the same way (bodyHits)
169
+ */
161
170
  resolve(pos, radius = this.engine.movement.radius) {
162
171
  const sPos = this._rPos, sRad = this._rRad;
163
172
  this._rPos = pos; this._rRad = radius; this._rHit = false;
164
- const g = this.engine.ground;
173
+ const g = this.engine.ground, y = pos.y, body = this.engine.movement.height;
165
174
  for (let iter = 0; iter < 2; iter++) {
166
175
  g.forEachCollider?.(pos.x, pos.z, radius + 2, this._onGroundCircle);
167
176
  const list = this._grid.query(pos.x, pos.z, radius + 2);
168
177
  for (let i = 0; i < list.length; i++) {
169
178
  const it = list[i];
170
- if (it._b) this._pushBox(pos, it, radius); else this._pushCircle(pos, it.x, it.z, it.r, radius);
179
+ if (!it._b) this._pushCircle(pos, it.x, it.z, it.r, radius);
180
+ else if (bodyHits(it, y, body)) this._pushBox(pos, it, radius);
171
181
  }
172
182
  if (!this._rHit) break; // nothing pushed: a second pass would ask the same questions at the same spot (most steps of most walkers)
173
183
  }
@@ -176,8 +186,8 @@ export class Collision {
176
186
  return hit;
177
187
  }
178
188
 
179
- /** Can anyone stand here (for pathfinding): not in water, not too steep, not inside an obstacle. radius is the character radius (m, default engine.movement.radius) */
180
- walkable(position, { radius = this.engine.movement.radius } = {}) { const [x, z] = xzOf(position); return this.walkableAt(x, z, radius); }
189
+ /** Can anyone stand here (for pathfinding): not in water, not too steep, not inside an obstacle. radius is the character radius (m, default engine.movement.radius). A position with y asks about the floor that height picks */
190
+ walkable(position, { radius = this.engine.movement.radius } = {}) { const [x, z] = xzOf(position); return this.walkableAt(x, z, radius, yOf(position)); }
181
191
  /**
182
192
  * Line of sight with height: is the 3D segment a -> b free of colliders (boxes, circles, terrain trees)? Positions like addBox ([x, y, z] / Vector3 / Object3D).
183
193
  * Heights count: a 1 m wall does not block a sight line passing 3 m above it; a collider's `y` and `height` are honoured (no `y` = sits on the ground).
@@ -214,19 +224,21 @@ export class Collision {
214
224
  return blocks((-qb - sq) / (2 * qa), (-qb + sq) / (2 * qa), bottom, top);
215
225
  };
216
226
  const len = Math.hypot(dx, dz), mx = A.x + dx / 2, mz = A.z + dz / 2;
227
+ // what stands on the ground stands on the floor the line passes over, not on a deck far above it
228
+ const floorAt = (x, z) => this.engine.surface(x, z, A.y + dy * (len > 1e-6 ? Math.min(1, Math.max(0, ((x - A.x) * dx + (z - A.z) * dz) / (len * len))) : 0));
217
229
  const list = this._grid.query(mx, mz, len / 2 + rad + 1);
218
230
  for (let i = 0; i < list.length; i++) {
219
231
  const it = list[i];
220
- if (!it._b) { const g = this.engine.surface(it.x, it.z); if (circle(it.x, it.z, it.r, g, g + it.h)) return false; continue; }
232
+ if (!it._b) { const g = floorAt(it.x, it.z); if (circle(it.x, it.z, it.r, g, g + it.h)) return false; continue; }
221
233
  const ox = A.x - it.x, oz = A.z - it.z;
222
234
  const lx = ox * it.c - oz * it.s, lz = ox * it.s + oz * it.c, ldx = dx * it.c - dz * it.s, ldz = dx * it.s + dz * it.c;
223
235
  S.t0 = 0; S.t1 = 1;
224
236
  if (!slab(S, lx, ldx, it.hw + rad) || !slab(S, lz, ldz, it.hd + rad)) continue;
225
- const bottom = it.y ?? this.engine.surface(it.x, it.z);
237
+ const bottom = it.y ?? floorAt(it.x, it.z);
226
238
  if (blocks(S.t0, S.t1, bottom, bottom + it.h)) return false;
227
239
  }
228
240
  let treeHit = false;
229
- this.engine.ground.forEachCollider?.(mx, mz, len / 2 + rad + 1, (cx, cz, r) => {
241
+ this.engine.ground.forEachCollider?.(mx, mz, len / 2 + rad + 1, (cx, cz, r) => { // plants grow on the top ground: that is where their trunks stand
230
242
  if (!treeHit) { const g = this.engine.surface(cx, cz); treeHit = circle(cx, cz, r, g, g + this.canopyHeight); }
231
243
  });
232
244
  return !treeHit;
@@ -234,19 +246,23 @@ export class Collision {
234
246
  /** @internal position argument -> { x, y, z } (y 0 when only x, z are given) */
235
247
  _vec(p) {
236
248
  const [x, z] = xzOf(p);
237
- const q = p.isObject3D ? p.position : p;
238
- const y = (Array.isArray(q) ? q[1] : q.y) ?? 0;
239
- return { x, y, z };
249
+ return { x, y: yOf(p) ?? 0, z };
240
250
  }
241
251
  /** @internal The collider grid (boxes and circles added through this module), read by async pathfinding on the main thread */
242
252
  get grid() { return this._grid; }
243
- /** Same as walkable but takes plain numbers (inner loop of A* pathfinding and spawn search, allocates nothing; like engine.surface(x, z)). radius defaults to engine.movement.radius */
244
- walkableAt(x, z, radius = this.engine.movement.radius) { return this.groundWalkable(x, z) && !this.blockedAt(x, z, radius) && !this._groundBlocks(x, z, radius) && !gridBlocks(this._grid, x, z, radius); }
253
+ /**
254
+ * Same as walkable but takes plain numbers (inner loop of A* pathfinding and spawn search, allocates nothing; like engine.surface(x, z)). radius defaults to engine.movement.radius.
255
+ * y picks the floor as in surface(), and only the floor it picks counts, so [x, 0, z] on raised ground asks about that ground. Left out: the top ground, and every box blocks at any height
256
+ */
257
+ walkableAt(x, z, radius = this.engine.movement.radius, y) {
258
+ const f = y === undefined ? y : surfaceOr(this.engine, x, z, y, y);
259
+ return this.groundWalkable(x, z, f) && !this.blockedAt(x, z, radius) && !this._groundBlocks(x, z, radius) && !gridBlocks(this._grid, x, z, radius, f, this.engine.movement.height);
260
+ }
245
261
  /** @internal Ground shape half of walkableAt (water, slope): a smooth field, so async pathfinding samples it on a raster; colliders are tested exactly there */
246
- groundWalkable(x, z) {
262
+ groundWalkable(x, z, y) {
247
263
  const e = this.engine;
248
264
  // the void of terrain({ shape }): -Infinity is not below a water level of -Infinity, so it must be asked directly
249
- return e.ground.has(x, z) && !(e.surface(x, z) < e.waterAt(x, z) + this.walkableWaterMargin || e.slope(x, z) > this.maxClimb * 0.8);
265
+ return e.ground.has(x, z) && !(e.surface(x, z, y) < e.waterAt(x, z, y) + this.walkableWaterMargin || e.slope(x, z, y) > this.maxClimb * 0.8);
250
266
  }
251
267
  /** Does one of the ground's own colliders (terrain trees) block this spot */
252
268
  _groundBlocks(x, z, radius) {
@@ -275,7 +291,7 @@ export class Collision {
275
291
  if (!slab(S, lx, dx, bx.hw + S.pad) || !slab(S, lz, dz, bx.hd + S.pad)) return;
276
292
  if (S.t0 <= 0.3) return;
277
293
  const yAt = from.y + (S.to.y - from.y) * (S.t0 / len);
278
- if (yAt > (bx.y ?? this.engine.surface(bx.x, bx.z)) + bx.h) return; // camera above the wall top
294
+ if (yAt > (bx.y ?? this.engine.surface(bx.x, bx.z, yAt)) + bx.h) return; // camera above the wall top
279
295
  S.best = Math.min(S.best, S.want * S.t0 / len);
280
296
  }
281
297
 
@@ -312,7 +328,7 @@ const COLLISION_PARAMS = keysSchema(['maxClimb', 'canopyHeight', 'cameraPad', 'c
312
328
  export function collision(opts = {}) {
313
329
  readParams('collision', COLLISION_PARAMS, opts);
314
330
  let c = null;
315
- return { name: 'collision', type: 'world', provides: ['collision'], params: COLLISION_PARAMS, options: opts, label: 'Collision', install(e) { e.i18n.add({ 'zh-CN': { 'module.collision': '碰撞' }, en: { 'module.collision': 'collision' } }); return (c = new Collision(e, opts)); },
331
+ return { name: 'collision', skipKind: 'none', type: 'world', provides: ['collision'], params: COLLISION_PARAMS, options: opts, label: 'Collision', install(e) { e.i18n.add({ 'zh-CN': { 'module.collision': '碰撞' }, en: { 'module.collision': 'collision' } }); return (c = new Collision(e, opts)); },
316
332
  // counts of what blocks walking, and whether the player's own spot is walkable: answers "why can the player not go there" without stepping
317
333
  describe(e) {
318
334
  const p = e.player?.position;
@@ -320,3 +336,5 @@ export function collision(opts = {}) {
320
336
  ...(p ? { atPlayer: { walkable: c.groundWalkable(p.x, p.z), blocked: c.blockedAt(p.x, p.z) } } : {}) };
321
337
  } };
322
338
  }
339
+
340
+ export const handRolled = [{ kind: 'collision', seen: 'a hand-written box overlap', use: 'engine.collision.addBox / addCircle for walls and props (movement, rays and physics read them); engine.collision.walkable to ask', quiet: /\b(engine|e|eng|ctx)\.collision\b/, code: /Math\.abs\([^)]*\)\s*<=?[^&|;]*&&\s*Math\.abs\([^)]*\)\s*<=?|[<>]=?\s*[\w.]*\bmin[XYZ]?\b[^;]*&&[^;]*[<>]=?\s*[\w.]*\bmax[XYZ]?\b/i }];
@@ -1,10 +1,10 @@
1
1
  // What any collision module must provide (fields: see gameplay/inventory.contract.js; shared check: @threedog/tools/contract).
2
- // Exactly what other code reads from engine.collision: addBox / addCircle (content models, level colliders), walkableAt / blockedAt / resolve (characters, NPC avoidance),
2
+ // Exactly what other code reads from engine.collision: addBox / addCircle (content models, level colliders), walkableAt / blockedAt / resolve (characters, NPC avoidance), groundWalkable (the path worker's tiles),
3
3
  // cameraDistance (the follow camera's arm), forEachStatic / mirror (rigid and nav copy the static colliders). Fields: version and blockedVersion go up when
4
4
  // colliders change (cached paths resample), maxClimb is the steepest walkable slope, grid is what the path worker queries.
5
5
  export default {
6
6
  name: 'collision',
7
- api: ['addBox', 'addCircle', 'walkableAt', 'blockedAt', 'resolve', 'cameraDistance', 'forEachStatic', 'mirror'],
7
+ api: ['addBox', 'addCircle', 'walkableAt', 'blockedAt', 'groundWalkable', 'resolve', 'cameraDistance', 'forEachStatic', 'mirror'],
8
8
  fields: ['version', 'blockedVersion', 'maxClimb', 'grid'],
9
9
  ops: [],
10
10
  events: [],
@@ -2,6 +2,9 @@
2
2
  // Results are ordered circles first, then boxes, each in insertion order, exactly the callback order of a linear scan (resolve edits the position in turn, so a different order changes the result).
3
3
  // Worker-safe (no imports): the path worker (characters/pathJob.js) rebuilds the same grid from the colliders it mirrors.
4
4
  const CELL = 8, MAX_CELLS = 64, KEY = 1048576; // colliders too large (covering > 64 cells) skip the grid and are scanned linearly, so registration cost does not blow up
5
+ /** Does a body with its feet at y reach this box? A box without a y of its own is a footprint, and a body without y is anywhere: both hit. Written so an undefined on either side falls through to true */
6
+ export const bodyHits = (it, y, body) => !(y >= it.y + it.h || y + body <= it.y);
7
+
5
8
  const byOrder = (a, b) => a._b - b._b || a._o - b._o;
6
9
 
7
10
  /** Cell span [x0, x1, z0, z1] that an item (x, z, r) covers */
@@ -54,10 +57,12 @@ export class CollisionGrid {
54
57
  /**
55
58
  * Does a collider in the grid block a character of `radius` standing at (x, z)? The obstacle half of Collision.walkableAt,
56
59
  * shared with the pathfinding worker (it rebuilds a grid from the same colliders), so both answer identically. Worker-safe: no imports.
60
+ * y, body: the feet and height of the character; a box on another floor does not block it. Left out, every box blocks.
57
61
  */
58
- export function gridBlocks(grid, x, z, radius) {
62
+ export function gridBlocks(grid, x, z, radius, y, body) {
59
63
  for (const it of grid.query(x, z, radius + 1)) {
60
64
  if (!it._b) { if (Math.hypot(x - it.x, z - it.z) < radius + it.r) return true; continue; }
65
+ if (!bodyHits(it, y, body)) continue;
61
66
  const dx = x - it.x, dz = z - it.z, lx = dx * it.c - dz * it.s, lz = dx * it.s + dz * it.c;
62
67
  if (Math.abs(lx) < it.hw + radius && Math.abs(lz) < it.hd + radius) return true;
63
68
  }
@@ -1,4 +1,4 @@
1
- // Content's contribution to thing.explain(): rules read from the thing's template (collide, static, interact), which win over the world record's own.
1
+ // Content's contribution to engine.explain({ thing }): rules read from the thing's template (collide, static, interact), which win over the world record's own.
2
2
  import { orNull } from '../../core/base/util.js';
3
3
 
4
4
  /** @internal */
@@ -110,9 +110,9 @@ export function fieldsOf(e, api, st, name) {
110
110
  return { ...schemaInfo(placementShape('props.template')), ...own };
111
111
  }
112
112
  if (PLACEMENT_FIELDS[name]) return schemaInfo(placementShape(name));
113
- const kind = st.kinds[name];
114
- if (kind?.fields) {
115
- const { shape, problems } = fieldsShape(`kind '${name}'`, kind.fields);
113
+ const table = st.kinds[name]?.fields;
114
+ if (table) {
115
+ const { shape, problems } = fieldsShape(`kind '${name}'`, table);
116
116
  if (problems.length) throw codedError('content-misuse', problems.join('; '));
117
117
  return schemaInfo(shape);
118
118
  }