threedog 1.1.0 → 1.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (363) hide show
  1. package/CHANGELOG.md +879 -798
  2. package/README.md +1 -1
  3. package/core/assets/Animator.js +41 -3
  4. package/core/assets/Assets.js +100 -24
  5. package/core/assets/assetEntry.js +73 -20
  6. package/core/assets/assetHot.js +68 -16
  7. package/core/assets/assetLoad.js +6 -6
  8. package/core/assets/assetLod.js +9 -2
  9. package/core/assets/assetManifest.js +12 -2
  10. package/core/assets/assetPart.js +54 -0
  11. package/core/assets/ik.js +271 -0
  12. package/core/assets/modelNeeds.js +37 -0
  13. package/core/assets/namedModel.js +102 -29
  14. package/core/assets/nodeVisibility.js +15 -0
  15. package/core/audio/Audio.js +36 -4
  16. package/core/audio/audioReverb.js +99 -0
  17. package/core/audio/audioRules.js +1 -1
  18. package/core/audio/audioVoice.js +1 -1
  19. package/core/base/Events.js +14 -4
  20. package/core/base/Random.js +1 -1
  21. package/core/base/Vars.js +1 -1
  22. package/core/base/docRef.js +51 -0
  23. package/core/base/errorCodes.js +178 -126
  24. package/core/base/errorHints.js +9 -7
  25. package/core/base/errors.js +25 -10
  26. package/core/base/events.generated.js +2 -0
  27. package/core/base/freeParts.js +76 -0
  28. package/core/base/math.js +28 -0
  29. package/core/base/sections.js +5 -5
  30. package/core/base/validate.js +31 -3
  31. package/core/engine/Engine.js +16 -6
  32. package/core/engine/Loading.js +5 -3
  33. package/core/engine/copies.js +1 -1
  34. package/core/engine/headlessLoad.js +4 -1
  35. package/core/engine/lifecycle.js +32 -16
  36. package/core/engine/loop.js +71 -27
  37. package/core/engine/moduleSlots.js +2 -2
  38. package/core/engine/moduleTypes.js +3 -3
  39. package/core/engine/modules.js +65 -39
  40. package/core/engine/page.js +6 -3
  41. package/core/engine/services.js +6 -5
  42. package/core/engine/startup.js +5 -5
  43. package/core/input/Input.js +28 -14
  44. package/core/input/inputContext.js +28 -16
  45. package/core/input/inputKeyboard.js +31 -3
  46. package/core/input/inputPad.js +4 -0
  47. package/core/input/inputPointer.js +2 -1
  48. package/core/input/inputSeat.js +1 -1
  49. package/core/inspect/Budget.js +109 -19
  50. package/core/inspect/DebugOverrides.js +28 -4
  51. package/core/inspect/Describe.js +17 -9
  52. package/core/inspect/Inspect.js +4 -2
  53. package/core/inspect/InspectMaterials.js +3 -1
  54. package/core/inspect/InspectPerf.js +19 -9
  55. package/core/inspect/InspectScene.js +32 -7
  56. package/core/inspect/MaterialInfo.js +19 -2
  57. package/core/inspect/UrlState.js +46 -27
  58. package/core/inspect/catalog.js +28 -9
  59. package/core/inspect/debugView.js +2 -1
  60. package/core/inspect/describeRender.js +25 -13
  61. package/core/inspect/describeText.js +14 -6
  62. package/core/inspect/lightWatch.js +1 -1
  63. package/core/inspect/metadata.generated.js +35 -17
  64. package/core/inspect/pictureChecks.js +148 -0
  65. package/core/inspect/pictureMenu.js +84 -0
  66. package/core/inspect/pictureWriters.js +26 -6
  67. package/core/inspect/textureBytes.js +12 -2
  68. package/core/inspect/toolDoor.js +2 -4
  69. package/core/ops/Ops.js +11 -4
  70. package/core/ops/holds.js +27 -10
  71. package/core/ops/opsAtomic.js +15 -7
  72. package/core/ops/opsGuard.js +2 -2
  73. package/core/ops/opsRun.js +8 -7
  74. package/core/ops/sharedPoint.js +72 -21
  75. package/core/ops/stacks.js +56 -16
  76. package/core/saves/SaveStore.js +9 -3
  77. package/core/saves/Saves.js +32 -23
  78. package/core/saves/saveApply.js +96 -44
  79. package/core/saves/saveIds.js +1 -1
  80. package/core/saves/saveVersions.js +7 -5
  81. package/core/saves/session.js +17 -8
  82. package/core/saves/stateReplace.js +34 -15
  83. package/core/scene/Rays.js +52 -10
  84. package/core/scene/Views.js +13 -7
  85. package/core/scene/adaptive.js +144 -21
  86. package/core/scene/drawOnly.js +17 -0
  87. package/core/scene/gameLights.js +44 -3
  88. package/core/scene/sceneMethods.js +13 -11
  89. package/core/scene/stepPoses.js +11 -3
  90. package/core/scene/targeting.js +5 -3
  91. package/core/scene/thingOps.js +1 -1
  92. package/core/scene/tier.js +15 -0
  93. package/core/stream/Batching.js +30 -7
  94. package/core/stream/Stream.js +26 -7
  95. package/core/stream/batchGroups.js +2 -2
  96. package/core/stream/chunkStream.js +7 -5
  97. package/core/stream/prepare.js +77 -0
  98. package/core/time/skip.js +3 -1
  99. package/core/time/time.js +4 -2
  100. package/docs/AI.md +82 -83
  101. package/docs/API.md +16 -16
  102. package/docs/CODEMAP.md +16 -11
  103. package/docs/COMMANDS.md +139 -142
  104. package/docs/CONVENTIONS.md +37 -49
  105. package/docs/MIGRATING-0.8.md +2 -2
  106. package/docs/MIGRATING-1.0.md +2 -2
  107. package/docs/THREE.md +28 -35
  108. package/docs/api/assets.md +3 -1
  109. package/docs/api/audio.md +4 -2
  110. package/docs/api/budget.md +5 -0
  111. package/docs/api/characters.md +10 -8
  112. package/docs/api/collision.md +6 -4
  113. package/docs/api/engine.md +16 -16
  114. package/docs/api/events.md +3 -2
  115. package/docs/api/ground.md +6 -5
  116. package/docs/api/hud.md +4 -2
  117. package/docs/api/input.md +5 -5
  118. package/docs/api/particles.md +2 -1
  119. package/docs/api/photo.md +3 -0
  120. package/docs/api/post.md +7 -4
  121. package/docs/api/quests.md +2 -2
  122. package/docs/api/rays.md +1 -2
  123. package/docs/api/saves.md +7 -7
  124. package/docs/api/settings.md +2 -2
  125. package/docs/api/tools.md +3 -1
  126. package/docs/api/vars.md +1 -1
  127. package/docs/api/vegetation.md +4 -2
  128. package/docs/api/world.md +1 -1
  129. package/docs/recipes/01-new-game.md +16 -17
  130. package/docs/recipes/02-npc.md +22 -18
  131. package/docs/recipes/03-items-pickups.md +37 -35
  132. package/docs/recipes/04-quests.md +15 -10
  133. package/docs/recipes/05-props-bake.md +101 -95
  134. package/docs/recipes/06-clock-events.md +28 -28
  135. package/docs/recipes/07-flow-scenes-pause.md +29 -26
  136. package/docs/recipes/08-weather-sky.md +52 -64
  137. package/docs/recipes/09-materials-lights-models.md +26 -17
  138. package/docs/recipes/10-blender-level.md +15 -10
  139. package/docs/recipes/11-vehicles.md +12 -7
  140. package/docs/recipes/12-navmesh.md +44 -26
  141. package/docs/recipes/13-animation.md +56 -45
  142. package/docs/recipes/14-custom-module.md +21 -18
  143. package/docs/recipes/15-perf.md +61 -55
  144. package/docs/recipes/16-dev-bridge.md +23 -33
  145. package/docs/recipes/18-world.md +36 -42
  146. package/docs/recipes/19-shooting-picking.md +20 -15
  147. package/docs/recipes/20-content-actions-save.md +48 -56
  148. package/docs/recipes/21-camera.md +45 -54
  149. package/docs/recipes/22-shop-gold.md +12 -7
  150. package/docs/recipes/23-ops.md +25 -23
  151. package/docs/recipes/26-ui-parts.md +67 -47
  152. package/docs/recipes/27-net.md +12 -7
  153. package/docs/recipes/28-terrain.md +24 -21
  154. package/docs/recipes/29-grid.md +32 -27
  155. package/docs/recipes/30-templates.md +21 -20
  156. package/docs/recipes/31-audio.md +39 -22
  157. package/docs/recipes/32-action-game.md +19 -14
  158. package/docs/recipes/33-stream-sources.md +15 -11
  159. package/docs/recipes/34-environment-lighting.md +126 -70
  160. package/docs/recipes/35-picture-from-reference.md +8 -8
  161. package/docs/recipes/36-ground-plants.md +27 -21
  162. package/docs/recipes/40-scene.md +19 -28
  163. package/docs/recipes/43-shader-patches-surfaces.md +15 -12
  164. package/docs/recipes/44-water-weather-hooks.md +34 -31
  165. package/docs/recipes/45-cascaded-shadows.md +35 -26
  166. package/docs/recipes/46-blender-art-route.md +6 -1
  167. package/docs/recipes/49-game-module-contract.md +13 -8
  168. package/docs/recipes/50-own-renderer.md +6 -2
  169. package/docs/recipes/51-capability-catalog.md +15 -8
  170. package/docs/recipes/52-around-the-picture.md +34 -32
  171. package/docs/recipes/53-ground-up-close.md +6 -1
  172. package/docs/recipes/55-mods-time-wrap.md +27 -19
  173. package/docs/recipes/56-webgpu-tsl.md +74 -43
  174. package/docs/recipes/57-control.md +18 -13
  175. package/docs/recipes/58-input.md +26 -16
  176. package/docs/recipes/59-depth-post-effects.md +8 -3
  177. package/docs/recipes/60-judge-the-picture.md +9 -8
  178. package/docs/recipes/61-deploy.md +5 -0
  179. package/docs/recipes/62-picture-code.md +70 -79
  180. package/docs/recipes/63-third-person-start.md +47 -45
  181. package/docs/recipes/64-particles.md +22 -10
  182. package/docs/recipes/65-swarm.md +18 -13
  183. package/docs/recipes/66-common-tasks.md +38 -35
  184. package/examples/action/GAMEMAP.md +2 -3
  185. package/examples/action/main.js +3 -3
  186. package/examples/action/picture/lights.js +3 -1
  187. package/examples/perf-island/GAMEMAP.md +3 -3
  188. package/examples/perf-island/picture/lights.js +2 -1
  189. package/examples/plain-picture/GAMEMAP.md +1 -1
  190. package/examples/rc2d/GAMEMAP.md +1 -1
  191. package/examples/styletest/GAMEMAP.md +2 -2
  192. package/examples/styletest/main.js +1 -1
  193. package/examples/techniques/interior-light/README.md +3 -3
  194. package/examples/techniques/interior-light/interiorLight.js +2 -4
  195. package/examples/techniques/interior-light/picture/lights.js +2 -1
  196. package/examples/techniques/modular-building/picture/lights.js +3 -1
  197. package/examples/techniques/outlines-and-rim/picture/lights.js +3 -1
  198. package/examples/techniques/procedural-animation/README.md +1 -1
  199. package/examples/techniques/procedural-animation/main.js +1 -1
  200. package/examples/webgpu-tsl/GAMEMAP.md +1 -1
  201. package/examples/world/GAMEMAP.md +2 -3
  202. package/examples/world/art/humanoid.js +1 -1
  203. package/examples/world/main.js +6 -3
  204. package/index.d.ts +2 -2
  205. package/llms.txt +101 -0
  206. package/modules/ambience/Ambience.js +21 -5
  207. package/modules/calendar/index.js +9 -5
  208. package/modules/calendar/schedule.js +23 -8
  209. package/modules/camera/FirstPersonCamera.js +3 -1
  210. package/modules/camera/FollowCamera.js +10 -5
  211. package/modules/camera/RtsCamera.js +4 -3
  212. package/modules/camera/common.js +70 -8
  213. package/modules/camera/contract.js +1 -1
  214. package/modules/characters/Character.js +16 -10
  215. package/modules/characters/NPC.js +31 -19
  216. package/modules/characters/assetModel.js +14 -9
  217. package/modules/characters/astar.js +6 -1
  218. package/modules/characters/contract.js +2 -2
  219. package/modules/characters/index.js +34 -22
  220. package/modules/characters/movers/manual.js +1 -1
  221. package/modules/characters/movers/rapier.js +17 -2
  222. package/modules/characters/movers/simple.js +1 -1
  223. package/modules/characters/movers/support.js +16 -7
  224. package/modules/characters/npcAvoid.js +2 -2
  225. package/modules/characters/npcSim.js +3 -2
  226. package/modules/characters/pathAsync.js +24 -8
  227. package/modules/characters/pathJob.js +1 -1
  228. package/modules/characters/player.js +10 -9
  229. package/modules/characters/playerStrings.js +5 -5
  230. package/modules/characters/proceduralRig.js +5 -5
  231. package/modules/characters/useModel.js +6 -0
  232. package/modules/characters/walkTo.js +1 -1
  233. package/modules/collision/Collision.js +29 -18
  234. package/modules/collision/grid.js +22 -4
  235. package/modules/content/index.js +3 -1
  236. package/modules/content/loader.js +1 -1
  237. package/modules/content/models.js +82 -33
  238. package/modules/content/props.js +2 -1
  239. package/modules/content/rules.js +11 -5
  240. package/modules/content/templates.js +3 -3
  241. package/modules/content/words.js +2 -2
  242. package/modules/debug/DebugPanel.js +9 -9
  243. package/modules/flow/index.js +9 -6
  244. package/modules/gameplay/Dialogue.js +34 -20
  245. package/modules/gameplay/Interactions.js +19 -15
  246. package/modules/gameplay/Inventory.js +9 -4
  247. package/modules/gameplay/Quests.js +12 -10
  248. package/modules/gameplay/pickups.js +23 -11
  249. package/modules/grid/index.js +1 -1
  250. package/modules/grid/preview.js +2 -2
  251. package/modules/grid/tiles.js +1 -1
  252. package/modules/hlod/index.js +4 -1
  253. package/modules/hud/index.js +47 -10
  254. package/modules/hud/parts.js +28 -9
  255. package/modules/level/geometry.js +8 -3
  256. package/modules/level/index.js +10 -5
  257. package/modules/level/load.js +4 -2
  258. package/modules/lights/sources.js +1 -1
  259. package/modules/music/Music.js +22 -4
  260. package/modules/nav/index.js +20 -10
  261. package/modules/particles/Particles.js +31 -14
  262. package/modules/particles/effect.js +20 -5
  263. package/modules/particles/lit.js +72 -0
  264. package/modules/photo/Photo.js +72 -28
  265. package/modules/photo/pathTrace.js +106 -0
  266. package/modules/rigid/RigidBodies.js +23 -14
  267. package/modules/rigid/Vehicles.js +3 -13
  268. package/modules/rigid/sync.js +2 -1
  269. package/modules/settings/Settings.js +52 -20
  270. package/modules/settings/apply.js +23 -9
  271. package/modules/settings/sections.js +39 -6
  272. package/modules/settings/strings.js +2 -0
  273. package/modules/settings/view.js +19 -3
  274. package/modules/sky/dome.js +15 -3
  275. package/modules/sky/environment.js +28 -12
  276. package/modules/sky/fog.js +1 -1
  277. package/modules/sky/frame.js +6 -1
  278. package/modules/sky/shader.js +4 -3
  279. package/modules/sky/skyModule.js +8 -4
  280. package/modules/swarm/Swarm.js +1 -1
  281. package/modules/terrain/ChunkManager.js +61 -15
  282. package/modules/terrain/chunkJob.js +2 -2
  283. package/modules/terrain/index.js +20 -5
  284. package/modules/terrain/terrainEdit.js +8 -4
  285. package/modules/terrain/terrainTexture.js +4 -2
  286. package/modules/timeline/Timeline.js +4 -3
  287. package/modules/timeline/Tween.js +3 -0
  288. package/modules/timeline/letterbox.js +1 -0
  289. package/modules/triggers/index.js +36 -17
  290. package/modules/vegetation/Vegetation.js +81 -19
  291. package/modules/vegetation/densityMap.js +13 -8
  292. package/modules/vegetation/draw.js +147 -24
  293. package/modules/vegetation/groundChunks.js +20 -5
  294. package/modules/vegetation/index.js +3 -3
  295. package/modules/vegetation/modelGeometry.js +9 -4
  296. package/modules/water/Water.js +11 -8
  297. package/modules/weather/Weather.js +7 -2
  298. package/modules/weather/shaders.js +25 -5
  299. package/modules/weather/weatherDraw.js +20 -6
  300. package/modules/world/World.js +2 -1
  301. package/modules/world/index.js +2 -2
  302. package/modules/world/persist.js +6 -2
  303. package/modules/world/views.js +15 -2
  304. package/package.json +4 -1
  305. package/presets.js +5 -5
  306. package/render/PostFX.js +84 -41
  307. package/render/backend.js +137 -16
  308. package/render/cascades.js +3 -1
  309. package/render/cascades.tsl.js +2 -0
  310. package/render/daylight.js +7 -1
  311. package/render/detail.js +7 -4
  312. package/render/effects.js +27 -8
  313. package/render/fogLook.js +24 -0
  314. package/render/fuse.js +5 -2
  315. package/render/fx/detail.tsl.js +9 -7
  316. package/render/fx/index.js +7 -2
  317. package/render/fx/library.tsl.js +1 -0
  318. package/render/fx/lightShaft.tsl.js +114 -0
  319. package/render/fx/noise.tsl.js +25 -8
  320. package/render/fx/objectOrigin.tsl.js +39 -10
  321. package/render/fx/particles.tsl.js +23 -6
  322. package/render/fx/patchNodes.tsl.js +17 -12
  323. package/render/fx/pcss.tsl.js +51 -0
  324. package/render/fx/postWebGPU.tsl.js +89 -29
  325. package/render/fx/sky.tsl.js +3 -9
  326. package/render/fxNumbers.js +10 -4
  327. package/render/impostor.tsl.js +107 -0
  328. package/render/lighting.js +33 -1
  329. package/render/lightmap.js +42 -28
  330. package/render/lights.js +19 -3
  331. package/render/materials.js +6 -4
  332. package/render/mergeCommon.js +4 -1
  333. package/render/occlusion.js +14 -4
  334. package/render/patches.js +79 -41
  335. package/render/postRuns.js +32 -0
  336. package/render/postWebGL.js +97 -10
  337. package/render/probes.js +10 -14
  338. package/render/shaderErrors.js +2 -1
  339. package/render/shadowCache.tsl.js +33 -5
  340. package/render/shadows.js +42 -16
  341. package/render/slots.js +8 -5
  342. package/render/vertexInputs.js +52 -0
  343. package/types/core.d.ts +114 -46
  344. package/types/gameplay.d.ts +56 -23
  345. package/types/generated/core/audio/Audio.d.ts +27 -1
  346. package/types/generated/core/base/Random.d.ts +1 -1
  347. package/types/generated/core/input/Input.d.ts +6 -8
  348. package/types/generated/core/input/inputSeat.d.ts +1 -1
  349. package/types/generated/core/inspect/Budget.d.ts +26 -0
  350. package/types/generated/core/inspect/DebugOverrides.d.ts +0 -2
  351. package/types/generated/core/saves/Saves.d.ts +10 -7
  352. package/types/generated/core/saves/session.d.ts +8 -2
  353. package/types/generated/core/scene/Rays.d.ts +1 -3
  354. package/types/generated/modules/particles/Particles.d.ts +1 -1
  355. package/types/generated/modules/world/World.d.ts +2 -1
  356. package/types/generated/render/PostFX.d.ts +35 -9
  357. package/types/physics.d.ts +796 -764
  358. package/types/pixel.d.ts +1 -1
  359. package/types/tsl.d.ts +62 -1
  360. package/types/world.d.ts +12 -3
  361. package/ui/Focus.js +7 -5
  362. package/ui/Parts.js +1 -1
  363. package/ui/touchPart.js +6 -3
@@ -18,8 +18,10 @@
18
18
  import * as THREE from 'three';
19
19
  import { defineOwned, dropOwned } from '../../core/ops/owned.js';
20
20
  import { readParams, keysSchema } from '../../core/base/params.js';
21
+ import { pointSpotLights } from '../../core/scene/gameLights.js';
21
22
  import { setFov, setProjection } from '../../core/scene/view.js';
22
- import { codedError } from '../../core/base/errorHints.js';
23
+ import { codedError, coded } from '../../core/base/errorHints.js';
24
+ import { warnOnce } from '../../core/base/validate.js';
23
25
 
24
26
  // the takeover calls the owned-camera warning quotes (core/ops/owned.js): takeCamera is the one explicit entry (its remove() gives the camera back);
25
27
  // back is the hand-back for a camera the engine yielded to a direct write (that takeover has no handle)
@@ -38,6 +40,22 @@ function planar(dir, fallback = { x: 0, z: -1 }) {
38
40
  const l = Math.hypot(dir.x, dir.z);
39
41
  return l < 1e-4 ? { x: fallback.x, z: fallback.z } : { x: dir.x / l, z: dir.z / l };
40
42
  }
43
+ /**
44
+ * A rig value kept to its range [rig[loName], rig[hiName]] (the documented limit). Asked for outside it, it is said once in dev, naming the option that
45
+ * widens it: a silent clamp made a game's wheel zoom do nothing past the default maxDistance. kept: return the value as given (a start value the first
46
+ * wheel notch or drag pulls in), else the limit
47
+ * @param {any} rig @param {string} kind the module function ('followCamera') @param {string} call where the value came from ('followCamera()', 'cameraRig.setView()')
48
+ * @param {string} name @param {number} v @param {string[]} names [loName, hiName] @param {boolean} [kept]
49
+ * @internal
50
+ */
51
+ export function inRange(rig, kind, call, name, v, [loName, hiName], kept = false) {
52
+ const limit = v > rig[hiName] ? hiName : v < rig[loName] ? loName : null;
53
+ if (!limit) return v;
54
+ const at = rig[limit];
55
+ // a factory: the text is built only the one time it is said (a zoom past the limit asks every frame)
56
+ warnOnce(() => coded('camera-clamped', `${call}: ${name} ${v} is ${limit === hiName ? 'above' : 'below'} ${limit} (${at}), so the camera keeps to ${at}. To allow it: ${kind}({ ${limit}: ${v} }) or engine.cameraRig.${limit} = ${v}`), `camera-clamped:${call}:${limit}`);
57
+ return kept ? v : at;
58
+ }
41
59
  /** Right direction from the forward direction (Y up) */
42
60
  export const rightOf = f => ({ x: -f.z, z: f.x });
43
61
 
@@ -62,10 +80,54 @@ export const HIDE_RIG = {
62
80
  if ((o.isMesh || o.isSkinnedMesh || o.isPoints || o.isLine) && !o.layers.isEnabled(this.hideLayer)) { this._hidden.push([o, o.layers.mask]); o.layers.set(this.hideLayer); }
63
81
  });
64
82
  },
65
- _unhide() { for (const [o, mask] of this._hidden) o.layers.mask = mask; this._hidden.length = 0; }, // follow calls it every frame
66
- // Lights present now (the sky module has built them by onEnter); a light added later calls shadow.camera.layers.enable(hideLayer) itself
67
- _shadowLayers() { this.engine.scene.traverse(o => { if (o.isLight && o.shadow?.camera) o.shadow.camera.layers.enable(this.hideLayer); }); },
83
+ _unhide() { // follow calls it every frame
84
+ for (const [o, mask] of this._hidden) o.layers.mask = mask; this._hidden.length = 0;
85
+ // the body shows again: carried lights get hideLayer back (a body that is seen casts its shadow from every light, as in plain three.js)
86
+ if (this._lightTook?.size) { for (const l of this._lightTook) hideBit(l, this.hideLayer, true); this._lightTook.clear(); }
87
+ },
88
+ // Every light present now gets the hidden layer; point / spot lights added later get it from _carriedLights on the frame they show up
89
+ _shadowLayers() { this.engine.scene.traverse(o => { if (o.isLight && o.shadow?.camera) hideBit(o, this.hideLayer, true); }); },
90
+ /**
91
+ * A light the player carries (head lamp, torch, flashlight) is not shadowed by the player's own hidden body; the sun and other lights still are.
92
+ * Why: the hidden body still casts shadows on purpose (you see your shadow from the sun), but a lamp that sits in or right next to the body
93
+ * sees that body fill half its view, so every frame shows a hard black wedge the player cannot explain (the body they would explain it with is hidden).
94
+ * Rule, automatic, no new option: while the body is hidden, a casting point / spot light whose world position is inside the body's box,
95
+ * grown by one body width on every side, is "carried", and its shadow camera drops hideLayer. Both renderers then draw that light's shadow
96
+ * with the view camera's layers (three.js: a shadow camera with only layer 0 falls back to the camera's layers, WebGLShadowMap and ShadowNode alike),
97
+ * and the view camera does not see hideLayer, so the body is left out. A sun / directional light is never carried.
98
+ * The engine writes only the hideLayer bit, and only puts it back on a light it took it from; a game that clears the bit itself keeps it cleared.
99
+ * Cost: per frame one loop over the scene's point / spot lights (gameLights keeps the set) and, while hidden with a casting one, one box of the body.
100
+ */
101
+ _carriedLights() {
102
+ const lights = pointSpotLights(this.engine), seen = this._lightSeen ??= new WeakSet(), took = this._lightTook ??= new Set(), bit = this.hideLayer;
103
+ // a carried light that left the scene gets its bit back now: it may come back later, or be added to another scene, as the game left it
104
+ for (const l of took) if (!lights.has(l)) { hideBit(l, bit, true); took.delete(l); }
105
+ if (!lights.size) return;
106
+ let box = null;
107
+ for (const l of lights) {
108
+ const c = l.shadow?.camera; if (!c) continue;
109
+ if (!seen.has(l)) { seen.add(l); hideBit(l, bit, true); } // a light added after onEnter also gets the body's shadow
110
+ let carried = false;
111
+ if (l.castShadow && this._hidden.length) {
112
+ if (!box) {
113
+ box = (this._carrierBox ??= new THREE.Box3()).setFromObject(this.target);
114
+ if (!box.isEmpty()) { const s = box.getSize(_sz); box.expandByScalar(Math.max(s.x, s.z)); }
115
+ }
116
+ carried = !box.isEmpty() && box.containsPoint(l.getWorldPosition(_lp));
117
+ }
118
+ if (carried && c.layers.isEnabled(bit)) { hideBit(l, bit, false); took.add(l); }
119
+ else if (!carried && took.delete(l)) hideBit(l, bit, true);
120
+ }
121
+ },
68
122
  };
123
+ const _sz = new THREE.Vector3(), _lp = new THREE.Vector3();
124
+ /** Set or clear the hidden layer on a light's shadow camera; only a real change asks for a redraw (needsUpdate), so a light whose game redraws it
125
+ * rarely (autoUpdate off, a shadow budget) does not keep the old shadow (a wedge, or no body) until its next turn, and one that did not change costs nothing */
126
+ function hideBit(l, bit, on) {
127
+ const ly = l.shadow.camera.layers; if (ly.isEnabled(bit) === on) return;
128
+ if (on) ly.enable(bit); else ly.disable(bit);
129
+ l.shadow.needsUpdate = true;
130
+ }
69
131
 
70
132
  /**
71
133
  * Click-to-lock the mouse for a camera with a pointerLock flag (first person, over-the-shoulder follow); call from onEnter.
@@ -138,7 +200,7 @@ export function rigPlaced(engine) { RIG_OWNED.get(engine)?.mark(); }
138
200
  const RIG_OWNED = new WeakMap(); // engine -> the camera's owned entry (one camera module per engine)
139
201
 
140
202
  /** Camera kind table: kind name -> build(engine, opts, input). Each camera file registers once with defineRig; setCamera switches by name.
141
- * input.action(name, o) declares an action owned by the camera module (once per name, removed with the module), so a rig built later by
203
+ * input.define(name, o) declares an action owned by the camera module (once per name, removed with the module), so a rig built later by
142
204
  * setCamera or a new session leaves no declaration behind */
143
205
  const RIGS = new Map();
144
206
  const RIG_PARAMS = new Map(); // kind -> params schema (the option keys of that camera)
@@ -157,7 +219,7 @@ export function rigModule(kind, opts) {
157
219
  const cache = new Map(); // kind -> camera instance: params like distance and pitch survive switching away and back
158
220
  const builtWith = new WeakMap(); // rig -> the options it was built with
159
221
  let modInput = null; const declared = new Set();
160
- const input = { action: (n, o) => { if (!declared.has(n)) { declared.add(n); modInput.action(n, o); } } };
222
+ const input = { define: (n, o) => { if (!declared.has(n)) { declared.add(n); modInput.define(n, o); } } };
161
223
  const make = (k, o) => {
162
224
  const build = RIGS.get(k);
163
225
  if (!build) throw codedError('camera-kind', `setCamera() has no camera kind '${k}'; available: ${[...RIGS.keys()].join(', ')}`);
@@ -197,7 +259,7 @@ export function rigModule(kind, opts) {
197
259
  c.onEnter?.(false);
198
260
  // The view the player had is save data. Written to a rig of the saved kind only: a follow rig's pitch means the opposite of a first-person one's, so across kinds
199
261
  // only the heading carries (as in setCamera). A kind switched to at runtime is not restored: its options are the game's and are not save data
200
- ctx.saves.register('cameraRig', { notAtomic: 'the view is output: no game rule reads it, and a rollback must not move the camera',
262
+ ctx.saves.define('cameraRig', { notAtomic: 'the view is output: no game rule reads it, and a rollback must not move the camera',
201
263
  save: () => ({ kind: c.kind, yaw: c.yaw, pitch: c.pitch }),
202
264
  load: d => {
203
265
  const r = d.kind === c.kind ? c : home;
@@ -219,7 +281,7 @@ export function rigModule(kind, opts) {
219
281
  for (const k of Object.keys(home)) delete home[k];
220
282
  c = e.cameraRig = Object.assign(home, built, yaw !== undefined && { yaw, pitch });
221
283
  cache.set(kind, home);
222
- // follows the player only if the game asked (createPlayer({ cameraFollow })), through the seat the load put it in: the rig was rebuilt after that seat was taken
284
+ // follows the player only if the game asked (addPlayer({ cameraFollow })), through the seat the load put it in: the rig was rebuilt after that seat was taken
223
285
  const P = e.player, car = P?.cameraFollow ? P.vehicle : null;
224
286
  c.onEnter?.(false); c.follow(car ? car.object : P?.cameraFollow ? P.root : null, car?.camera); fresh = true;
225
287
  e.events.emit('camera:change', { kind, previous: old.kind }); // settings re-apply the player's sensitivity / fov to the rebuilt rig
@@ -1,6 +1,6 @@
1
1
  // What any camera module must provide (fields: see gameplay/inventory.contract.js; shared check: @threedog/tools/contract). It installs as engine.cameraRig.
2
2
  // Exactly what other code reads from engine.cameraRig: forward() / right() (control: 'camera', faceMode 'camera', targeting), follow(object, opts?)
3
- // (createPlayer, entering / leaving a vehicle), focusPoint() (photo, where the world loads), screenToGround(ndcX, ndcY) (click-to-move, placing
3
+ // (addPlayer, entering / leaving a vehicle), focusPoint() (photo, where the world loads), screenToGround(ndcX, ndcY) (click-to-move, placing
4
4
  // things); sensitivity / invertY are optional fields the settings menu writes when present. A camera that places engine.camera itself during a
5
5
  // cutscene takeover leaves it alone while engine.cameraOverride is set (common.js).
6
6
  export default {
@@ -24,6 +24,7 @@ import { seatsOf } from './seat.js';
24
24
  import { useModel } from './useModel.js';
25
25
  import { codedError, coded } from '../../core/base/errorHints.js';
26
26
  import { isModelName } from '../../core/base/util.js';
27
+ import { passesOf } from '../collision/grid.js';
27
28
 
28
29
  // A record whose jump / safe is the wrong kind of thing (a damaged or hand-edited save) is repaired so the game keeps running, but said out loud once: bad data is reported, not quietly fixed
29
30
  function badField(v, name, want) { if (v != null) warnOnce(`[threedog] character motion: the world record's '${name}' is ${JSON.stringify(v)} but should be ${want}; it was replaced with a fresh one. Check the save or the code that writes the record`); return undefined; }
@@ -32,7 +33,7 @@ const BUILT_IN = { simple: simpleMover, rapier: rapierMover, manual: manualMover
32
33
 
33
34
  // Options Character understands (shared by player and NPC)
34
35
  export const CHARACTER_KEYS = ['colors', 'speed', 'runSpeed', 'radius', 'water', 'states', 'swimDepth', 'swimSpeed', 'turnSpeed', 'acceleration', 'gravity',
35
- 'jumpSpeed', 'stepHeight', 'airControl', 'coyoteTime', 'canJump', 'maxJumps', 'airJumpSpeed', 'jumpBuffer', 'fall', 'channel', 'model', 'clips', 'animation', 'mover', 'faceMode', 'faceTarget', 'rig', 'id'];
36
+ 'jumpSpeed', 'stepHeight', 'airControl', 'coyoteTime', 'canJump', 'maxJumps', 'airJumpSpeed', 'jumpBuffer', 'fall', 'channel', 'model', 'clips', 'animation', 'mover', 'faceMode', 'faceTarget', 'rig', 'id', 'passes'];
36
37
  const FACE_MODES = ['move', 'camera', 'target', 'manual'];
37
38
 
38
39
  export class Character {
@@ -42,6 +43,7 @@ export class Character {
42
43
  * engine.assets.model() returned; without model and rig a gray capsule (warned once). rig: a ready body (proceduralRig.js format)
43
44
  * colors: { body, skin, legs, hair } per-character part colors (meshes marked userData.part; a capsule takes colors.body)
44
45
  * speed walk speed, runSpeed run speed (m/s), radius collision radius
46
+ * passes the collider layers it walks through, e.g. ['gate'] (collision.addBox { layer }): its walking, paths and navmesh all follow it; plain, may be rewritten later
45
47
  * water what water deeper than swimDepth does: 'swim' (default, floats, state 'swim') | 'block' (never enters it) | 'wade' (walks the
46
48
  * bottom) | (character, { depth, x, z }) => one of those (per spot: a swim skill, a boat, depth); character:water fires on each change.
47
49
  * swimDepth water depth at which it counts as deep, swimSpeed swim speed multiplier
@@ -70,7 +72,7 @@ export class Character {
70
72
  constructor(engine, { colors = {}, speed = 4.5, runSpeed = 7, radius = engine.movement.radius, water = 'swim', states = null, swimDepth = 1.0, swimSpeed = 0.45,
71
73
  turnSpeed = 10, acceleration = 12, gravity = -24, jumpSpeed = 8, stepHeight = engine.movement.stepHeight, airControl = 0.35, coyoteTime = 0.12,
72
74
  canJump = true, maxJumps = 1, airJumpSpeed = null, jumpBuffer = 0.12, fall = false, channel = 'world',
73
- model = null, clips = null, animation = null, mover = 'simple', faceMode = 'move', faceTarget = null, rig = null, id = null } = {}) {
75
+ model = null, clips = null, animation = null, mover = 'simple', faceMode = 'move', faceTarget = null, rig = null, id = null, passes } = {}) {
74
76
  /** @internal the id option, else the generated one (a character without a world record); the getter id below is the one public form */ this._ownId = id;
75
77
  /** @internal true for a world NPC's model (npcView.js): disposing it keeps the NPC's control slot */ this.npcModel = false;
76
78
  this.engine = engine;
@@ -78,6 +80,7 @@ export class Character {
78
80
  if (states != null && typeof states !== 'function') throw codedError('character-option', 'character option states: (character, facts) => state name | null', TypeError);
79
81
  /** What deep water does ('swim' | 'block' | 'wade' | function); states: the game's state hook. Both plain, change them at any time */
80
82
  this.water = water; this.states = states;
83
+ /** Collider layers this body goes through (character option passes); undefined: stopped by every collider */ this.passes = passesOf('character option passes', passes);
81
84
  Object.assign(this, { speed, runSpeed, radius, swimDepth, swimSpeedFactor: swimSpeed, turnSpeed, acceleration, gravity, jumpSpeed, stepHeight,
82
85
  airControl, coyoteTime, canJump, maxJumps, airJumpSpeed, jumpBuffer, channel });
83
86
  if (fall && !(typeof fall.belowY === 'number' || typeof fall.belowY === 'function')) throw codedError('character-option', `character option fall: { belowY: -20 } (a height, or (character) => boolean), or false; got ${JSON.stringify(fall)}`, TypeError);
@@ -93,7 +96,7 @@ export class Character {
93
96
  this.vy = 0; this.grounded = true; this._push = 0;
94
97
  this.limp = null; this.disposed = false; // limp: the ragdoll that has the body (rigid/ragdoll.js)
95
98
  this.root = new THREE.Group();
96
- engine._poses.add(this.root);
99
+ this._pose = engine._poses.add(this.root, null, null, () => `character '${this.id}'`);
97
100
  this.velocity = new THREE.Vector2();
98
101
  this.facing = 0; this.phase = 0; this.moveAmount = 0;
99
102
  this.swimming = false;
@@ -103,6 +106,7 @@ export class Character {
103
106
  this.state = this.stateMark = 'idle';
104
107
  /** The vehicle it sits in (null on foot) and its seat there (0 = driver, null on foot) */
105
108
  /** @internal the seat relation (seat.js), null on foot */ this._ride = null; this.anim = null;
109
+ /** @internal set by addPlayer: tears the player's registry entry down and then this character (player.js), so dispose() reaches it from either side */ this._release = null;
106
110
  /** false while a model named by asset loads (placeholder shows); await whenReady */
107
111
  this.ready = true;
108
112
  /**
@@ -119,10 +123,10 @@ export class Character {
119
123
  this._colors = colors;
120
124
  // one path for every body: an object, a procedural builder built now (joints exist at once), or a file asset loaded behind a capsule
121
125
  const now = isModelName(model) ? buildNow(engine, model) : model;
122
- if (now) { this._useModel(now, clips, animation); return; }
126
+ if (now && !now.then) { this._useModel(now, clips, animation); return; } // a promise: an async builder, waited on below
123
127
  if (!rig && !model) warnOnce(NO_CHARACTER);
124
128
  useRig(this, rig || capsule(colors.body, engine));
125
- if (model) this._whenReady = loadAssetModel(this, model, m => this._useModel(m, clips, animation));
129
+ if (model) this._whenReady = loadAssetModel(this, model, m => this._useModel(m, clips, animation), now);
126
130
  }
127
131
  /** A model object with userData.rig is a procedural body (limb swing); anything else animates by its clips */
128
132
  _useModel(model, clips, animation) {
@@ -156,7 +160,7 @@ export class Character {
156
160
  /**
157
161
  * Request a jump (call when the jump key is pressed). It waits jumpBuffer seconds for the ground, so pressing slightly before landing counts;
158
162
  * on the ground or in coyote time it is the ground jump, otherwise an air jump while maxJumps allows. air: false = only a ground jump.
159
- * @example createPlayer({ ..., maxJumps: 2 }); // double jump: the same jump key twice
163
+ * @example addPlayer({ ..., maxJumps: 2 }); // double jump: the same jump key twice
160
164
  */
161
165
  jump({ air = true } = {}) { const j = jumpOf(this); j.buffer = this.jumpBuffer || 1e-6; j.fresh = true; j.air = air; return this; }
162
166
  /** Give back n jumps for this airtime (a pickup, a wall touch) @param {number} [n] */
@@ -332,7 +336,7 @@ export class Character {
332
336
  if (e.player === this) this._driveCtx = e.input.push('vehicle', { pass: true }); // driving: brake lives in this context, walking-only keys are shadowed
333
337
  if (e.player === this && !e.input.keysOf('brake').length) warnOnce(coded('input-keys', "the player drives without a brake key: no module binds one by itself. engine.input.bind(presets.bindings.brake) (B / gamepad LT) or engine.input.bind('brake', ['KeyX'])"));
334
338
  this.root.visible = vehicle.hideDriver === false; this.velocity.set(0, 0); this.vy = 0; this.swimming = false; this.state = this.stateMark = 'drive'; this._store();
335
- // only when the game asked the camera to follow the player (createPlayer({ cameraFollow }))
339
+ // only when the game asked the camera to follow the player (addPlayer({ cameraFollow }))
336
340
  if (e.player === this && this.cameraFollow) e.cameraRig?.follow(vehicle.object, vehicle.camera);
337
341
  e.events.emit('vehicle:enter', { character: this, vehicle });
338
342
  }
@@ -343,7 +347,7 @@ export class Character {
343
347
  for (let n = 0; n < 8; n++) { // bounded: a vehicle with one exit answers the same point for every n
344
348
  const p = v.exitPosition(seat, n);
345
349
  if (!p) return null;
346
- if (this.engine.collision?.walkableAt(p.x, p.z, this.radius, p.y) ?? true) return p;
350
+ if (this.engine.collision?.walkableAt(p.x, p.z, this.radius, p.y, this.passes) ?? true) return p;
347
351
  }
348
352
  return null;
349
353
  }
@@ -370,6 +374,8 @@ export class Character {
370
374
  }
371
375
  /** Dispose this character completely: exit the vehicle first, release animation and mover, remove from the scene and dispose geometries and materials */
372
376
  dispose() {
377
+ // a player made by addPlayer: its registry entry (st.players, keys, touch button, world:load listener) goes first, and calls this again with _release cleared
378
+ if (this._release) { const r = this._release; this._release = null; r(); return; }
373
379
  this.disposed = true; // a model still loading by asset name is dropped on arrival
374
380
  this.engine.control?.endTasks(this, 'gone');
375
381
  // a character without a world record or NPC id has nothing to come back as: its control slot goes with it (records drop theirs on world:remove,
@@ -377,7 +383,7 @@ export class Character {
377
383
  if (!this.recordId && !this.npcModel) this.engine.control?.forget(this.id);
378
384
  this.exit({ force: true });
379
385
  detach(this); // a disposed rider must leave the platform's rider list, or it is carried and kept alive for as long as the platform lives
380
- this.engine._poses.remove(this.root);
386
+ this._pose.remove();
381
387
  this.anim?.dispose();
382
388
  for (const m of new Set(this._movers.values())) m.dispose?.();
383
389
  this.engine.characters?._capsules.delete(this._rig?.capsule);
@@ -449,7 +455,7 @@ export class Character {
449
455
  animate(dt) {
450
456
  dt *= this.engine.still ? 0 : this.engine.time.scale(this.channel, this.id);
451
457
  if (!this.limp) this._animate(dt);
452
- if (!this.anim) this._firePose(dt);
458
+ if (!this.anim?._hook) this._firePose(dt); // an Animator with a frame hook fires it itself, once the pose is applied; a model without clips (and no IK) has no hook
453
459
  }
454
460
  /** @internal */
455
461
  _animate(dt) {
@@ -46,6 +46,7 @@ import { leaveLink } from './moveHelpers.js';
46
46
  import { Behaviors } from './behaviors.js';
47
47
  import { codedError } from '../../core/base/errorHints.js';
48
48
  import { isModelName } from '../../core/base/util.js';
49
+ import { passesOf } from '../collision/grid.js';
49
50
 
50
51
  const STRINGS = {
51
52
  noInteract: 'NPC "{name}" has interact set, but the interactions() module is not installed: nothing can use it',
@@ -268,8 +269,9 @@ export class NPCManager {
268
269
  position, zone = null, speed = 2.6, initial = false, behavior = 'schedule', mind = {}, ...rest } = opts;
269
270
  if (io !== null && !(io && typeof io === 'object' && typeof io.op === 'string')) throw codedError('character-option', fmt(STRINGS.badInteract, { got: JSON.stringify(io) }), TypeError);
270
271
  if (io) readParams('npcs.add() interact', keysSchema(['label', 'op', 'args', 'radius']), io);
272
+ passesOf('npcs.add() passes', rest.passes); // here, not when its body is first built near the player
271
273
  const id = given ?? name, look = {}, runtime = { ...this._runtime.get(id) }; // a re-add keeps what it does not pass, as the record does
272
- if (given == null) { if (this._byName.has(id)) throw codedError('world-id', fmt(STRINGS.sameName, { name })); this._byName.add(id); }
274
+ if (given == null && this._byName.has(id)) throw codedError('world-id', fmt(STRINGS.sameName, { name }));
273
275
  // an asset name is data (saved); a model object, animation, clips and whatever is not plain stay in memory
274
276
  for (const [k, v] of Object.entries(rest)) {
275
277
  if ((RUNTIME_KEYS.includes(k) && !(k === 'model' && isModelName(v))) || !W.isPlain(v)) runtime[k] = v;
@@ -277,7 +279,8 @@ export class NPCManager {
277
279
  }
278
280
  if (io) { if (typeof io.label === 'function') runtime.interactLabel = io.label; else delete runtime.interactLabel; }
279
281
  this._b.check(behavior);
280
- this._runtime.set(id, runtime);
282
+ const old = W.get(id);
283
+ if (old && old.kind !== KIND) throw codedError('world-id', fmt(STRINGS.notNpc, { id, kind: old.kind }));
281
284
  const hpd = e.calendar?.hoursPerDay ?? 24;
282
285
  // at may be 'HH:MM' or 0-1
283
286
  const sched = schedule.map(s => { const [x, z] = xzOf(s.position), y = yOf(s.position); return { at: parseClock(s.at, hpd), x, ...(y !== undefined && { y }), z }; }).sort((a, b) => a.at - b.at);
@@ -285,23 +288,32 @@ export class NPCManager {
285
288
  // the record keeps plain values only: a function label stays in runtime (above), the record gets null and the view reads runtime first
286
289
  const interact = io && { label: typeof io.label === 'string' ? io.label : null, op: io.op, args: io.args ?? {}, radius: io.radius ?? 3.2 };
287
290
  const def = { name, behavior, mind, schedule: sched, interact, pathStep, repath, arriveDistance, speed, look, zone };
288
- const old = W.get(id);
289
- if (old) {
290
- if (old.kind !== KIND) throw codedError('world-id', fmt(STRINGS.notNpc, { id, kind: old.kind }));
291
- // re-add overrides only fields passed explicitly (unpassed zone, schedule etc. keep their values)
292
- const patch = {};
293
- const keys = ['name', 'interact', 'pathStep', 'repath', 'arriveDistance', 'speed', 'zone', 'schedule'];
294
- for (const k of keys) if (opts[k] !== undefined) patch[k] = k === 'schedule' ? sched : def[k];
295
- // a new behavior starts a new memory, as setBehavior does; naming the one it has is setup code running again, and the memory is state
296
- const changes = opts.behavior !== undefined && behavior !== old.behavior;
297
- if (changes) { patch.behavior = behavior; patch.nav = { ...old.nav, path: null, repath: 0 }; }
298
- if (changes || opts.mind !== undefined) patch.mind = mind;
299
- if (Object.keys(look).length) patch.look = { ...old.look, ...look };
300
- W.set(id, patch);
301
- } else {
302
- const i = stopIndex(sched, timeOfDay(e)), at = position ?? (i != null ? sched[i] : { x: 0, z: 0 }), [x, z] = xzOf(at);
303
- const nav = { stop: null, path: null, repath: 0 };
304
- W.add({ id, kind: KIND, position: [x, placeAtHeight(e, `npcs.${id}`, x, z, yOf(at), 0, 0).y, z], ...def, state: 'idle', busy: false, nav, motion: null }, { initial });
291
+ // the name and the runtime entry (the presenters read it as the record arrives) are taken only now, and given back if the world write throws (checkPlain on a mind with a function, a
292
+ // dev id clash): a failed add leaves nothing behind, so a retry is not 'sameName' and a non-NPC id has no entry
293
+ const prev = this._runtime.get(id);
294
+ if (given == null) this._byName.add(id);
295
+ this._runtime.set(id, runtime);
296
+ try {
297
+ if (old) {
298
+ // re-add overrides only fields passed explicitly (unpassed zone, schedule etc. keep their values)
299
+ const patch = {};
300
+ const keys = ['name', 'interact', 'pathStep', 'repath', 'arriveDistance', 'speed', 'zone', 'schedule'];
301
+ for (const k of keys) if (opts[k] !== undefined) patch[k] = k === 'schedule' ? sched : def[k];
302
+ // a new behavior starts a new memory, as setBehavior does; naming the one it has is setup code running again, and the memory is state
303
+ const changes = opts.behavior !== undefined && behavior !== old.behavior;
304
+ if (changes) { patch.behavior = behavior; patch.nav = { ...old.nav, path: null, repath: 0 }; }
305
+ if (changes || opts.mind !== undefined) patch.mind = mind;
306
+ if (Object.keys(look).length) patch.look = { ...old.look, ...look };
307
+ W.set(id, patch);
308
+ } else {
309
+ const i = stopIndex(sched, timeOfDay(e)), at = position ?? (i != null ? sched[i] : { x: 0, z: 0 }), [x, z] = xzOf(at);
310
+ const nav = { stop: null, path: null, repath: 0 };
311
+ W.add({ id, kind: KIND, position: [x, placeAtHeight(e, `npcs.${id}`, x, z, yOf(at), 0, 0).y, z], ...def, state: 'idle', busy: false, nav, motion: null }, { initial });
312
+ }
313
+ } catch (err) {
314
+ if (prev) this._runtime.set(id, prev); else this._runtime.delete(id);
315
+ if (given == null) this._byName.delete(id);
316
+ throw err;
305
317
  }
306
318
  return this._handle(id);
307
319
  }
@@ -13,17 +13,21 @@ import { builderArgs } from '../../core/assets/namedModel.js';
13
13
  import { list as nameAndArgs } from '../../core/base/util.js';
14
14
 
15
15
  /**
16
- * Build a procedural model asset now (synchronously) when `name` is a registered builder; null when it is a file model, unknown, or the
17
- * builder is async (those load through loadAssetModel). The builder gets this = { palette: engine.assets.palette, engine } like any generator in the manifest.
16
+ * Build a procedural model asset now (synchronously) when `name` is a registered builder; null when it is a file model or unknown. A builder that answers with a
17
+ * promise (async) is not run again by loadAssetModel: its promise is handed back (of the made model), and loadAssetModel waits on that one job.
18
+ * The builder gets this = { palette: engine.assets.palette, engine } like any generator in the manifest.
18
19
  */
19
20
  export function buildNow(engine, model) {
20
21
  const [name] = nameAndArgs(model), build = engine.assets.builder(name);
21
22
  if (!build) return null;
22
23
  const v = build.call({ palette: engine.assets.palette, engine }, ...builderArgs(engine, model));
23
- if (!v || typeof v.then === 'function') return null;
24
- if (v.isBufferGeometry) return new THREE.Mesh(v, neutralMaterial('character', { vertexColors: !!v.attributes.color }));
25
- if (!v.name) v.name = name;
26
- return v;
24
+ const made = r => {
25
+ if (r.isBufferGeometry) return engine.assets.handOut(new THREE.Mesh(r, neutralMaterial('character', { vertexColors: !!r.attributes.color })), name);
26
+ if (!r.name) r.name = name;
27
+ return engine.assets.handOut(r, name);
28
+ };
29
+ if (typeof v?.then === 'function') return v.then(made);
30
+ return v ? made(v) : null;
27
31
  }
28
32
 
29
33
  const STRINGS = {
@@ -37,8 +41,9 @@ const STRINGS = {
37
41
  * @param {import('./Character.js').Character} ch
38
42
  * @param {string | any[]} model a name, or [name, ...args]
39
43
  * @param {(model: any) => void} use builds the model and Animator on ch
44
+ * @param {Promise<any>} [job] the promise buildNow got from an async builder: the one run of it, so the generator is not called a second time
40
45
  */
41
- export function loadAssetModel(ch, model, use) {
46
+ export function loadAssetModel(ch, model, use, job) {
42
47
  const e = ch.engine, A = e.assets, [name, ...args] = nameAndArgs(model);
43
48
  const names = [...A.entries].filter(([, x]) => x.type === 'model' && x.named).map(([n]) => n);
44
49
  const list = names.join(', ') || 'none; register them with engine.assets.manifest({ models })';
@@ -59,8 +64,8 @@ export function loadAssetModel(ch, model, use) {
59
64
  e.events.emit('character:model', { character: ch, model: m });
60
65
  };
61
66
  // already loaded (another NPC uses it, or this one was built before): swap now, so a character rebuilt far -> near never shows the placeholder
62
- const now = A.entries.get(name)?.value ? A.modelNow(name) : null; // only when loaded: modelNow hints in dev when nothing loads it
67
+ const now = !job && A.entries.get(name)?.value ? A.modelNow(name) : null; // only when loaded: modelNow hints in dev when nothing loads it
63
68
  if (now) { swap(now); return Promise.resolve(); }
64
69
  ch.ready = false;
65
- return A.model(name).then(swap).catch(err => { if (!ch.disposed) fail(err.message); }).finally(() => { ch.ready = true; });
70
+ return (job ?? A.model(name)).then(swap).catch(err => { if (!ch.disposed) fail(err.message); }).finally(() => { ch.ready = true; });
66
71
  }
@@ -61,7 +61,12 @@ export function findPath(walkable, sx, sz, gx, gz, { radius, step = defaultStep(
61
61
  const ni = s.i + di, nj = s.j + dj, t = reach(ni, nj, s.y);
62
62
  if (!t.ok && !(ni === gi && nj === gj)) continue;
63
63
  const ng = s.g + c;
64
- if (ng < t.g) { t.g = ng; t.from = s; open.push(t, ng + h(ni, nj), ng); }
64
+ // the cells being free says nothing about the way between them: a thin wall or fence lies between two free cell centres. Checked only for a step that would improve the cell, sampled
65
+ // every third of a cell (smoothing below samples finer). The first and last leg run from the real start / to the real goal, as the path does: a cell centre may lie behind a wall
66
+ if (ng < t.g) {
67
+ const from = s === first ? { x: sx, y, z: sz } : { x: s.i * step, y: s.y, z: s.j * step }, to = ni === gi && nj === gj ? { x: gx, y: t.y, z: gz } : { x: ni * step, y: t.y, z: nj * step };
68
+ if (lineClear(walkable, floor, level, from, to, step / 3)) { t.g = ng; t.from = s; open.push(t, ng + h(ni, nj), ng); }
69
+ }
65
70
  }
66
71
  }
67
72
  return null;
@@ -1,11 +1,11 @@
1
1
  // What any characters module must provide (fields: see gameplay/inventory.contract.js; shared check: @threedog/tools/contract).
2
2
  // The player is the world record 'player' (saved with world, not under a key of its own); jumps, landings, launches and falls are events other
3
3
  // modules listen to, fired by the character itself (not exercised by the shared check: they need a player on ground). kit is what a game's mover calls (mover.contract.js).
4
- // What createPlayer and control.characterOf hand out is character.contract.js: every member other modules use, the world protocol among them.
4
+ // What addPlayer and control.characterOf hand out is character.contract.js: every member other modules use, the world protocol among them.
5
5
  // position: who may write a character's position (design.md section 9). The record follows the character, so a write to the record of a live character is a placeAt (world.move).
6
6
  export default {
7
7
  name: 'characters',
8
- api: ['createPlayer', 'removePlayer', 'findSpawn', 'findPath', 'findPathAsync', 'support', 'moveInput', 'carryRiders', 'addVehicle'],
8
+ api: ['addPlayer', 'removePlayer', 'findSpawn', 'findPath', 'findPathAsync', 'support', 'moveInput', 'carryRiders', 'addVehicle'],
9
9
  fields: ['kit'],
10
10
  resolves: true, // calls engine.control.resolveWith; what it answers with is character.contract.js
11
11
  position: {
@@ -10,11 +10,11 @@
10
10
  // Vehicles are used through an interface (the { object, speed, drive(), seatPosition(), exitPosition() } returned by rigid.addWheeled); rigid is not imported
11
11
  // here.
12
12
  import { Character } from './Character.js';
13
- import { createPlayer } from './player.js';
13
+ import { addPlayer } from './player.js';
14
14
  import { NPCManager, NPC } from './NPC.js';
15
15
  import { findPath } from './astar.js';
16
16
  import { findSpawn, moveInput, withHeights } from './moveHelpers.js';
17
- import { AsyncPaths, sourcePath } from './pathAsync.js';
17
+ import { AsyncPaths, sourcePath, noteAStarStandIn } from './pathAsync.js';
18
18
  import { needMaterial } from '../../core/base/validate.js';
19
19
  import { builtInSounds } from '../../core/assets/assetManifest.js';
20
20
  import { readParams, keysSchema } from '../../core/base/params.js';
@@ -27,12 +27,14 @@ import { footstepSynth, stepSound } from './footsteps.js';
27
27
  import { xzOf, yOf } from '../../core/base/math.js';
28
28
  import { surfaceOr } from '../../core/scene/ground.js';
29
29
  import { isEngineMade } from '../../render/patches.js';
30
+ import { keepPart } from '../../core/base/freeParts.js';
30
31
  import { capsuleDefault, capsuleMaterial } from './proceduralRig.js';
32
+ import { passesOf } from '../collision/grid.js';
31
33
  export { Character, NPC };
32
34
 
33
35
  /**
34
36
  * Characters module. Once installed:
35
- * engine.characters.createPlayer({ spawn: {x, z}, colors, model, clips }) → player
37
+ * engine.characters.addPlayer({ spawn: {x, z}, colors, model, clips }) → player
36
38
  * engine.npcs.add({ id, name, schedule, interact, ... }) → NPC handle (needs npcs: true, on by default; data lives in engine.world)
37
39
  * engine.npcs.remove(npc or name); engine.characters.removePlayer()
38
40
  * three.js object of player and NPC: .root (Group), position .position (Vector3); spawn / position accept a Vector3 directly
@@ -42,14 +44,16 @@ export { Character, NPC };
42
44
  /** The characters.path rule, else navmesh when ready, else A* (characters.findPath; the one synchronous A* entry, see R20) */
43
45
  function solvePath(e, st, from, to, o) {
44
46
  const { detailed, id, ...rest } = o;
47
+ rest.passes = passesOf('characters.findPath()', o.passes);
45
48
  let res = sourcePath(e, st.path, from, to, o);
46
49
  if (res) { /* the game's source answered */ }
47
50
  else if (e.nav?.ready) res = e.nav.findPath(from, to, { ...rest, detailed: true });
48
51
  else if (!e.collision) res = { status: 'notReady', path: null };
49
52
  else {
53
+ noteAStarStandIn(e);
50
54
  const [sx, sz] = xzOf(from), [gx, gz] = xzOf(to), radius = rest.radius ?? e.movement.radius;
51
55
  const floor = (x, z, y) => surfaceOr(e, x, z, y, y);
52
- const path = findPath((x, z, y) => e.collision.walkableAt(x, z, radius, y), sx, sz, gx, gz, { ...rest, radius, y: floor(sx, sz, yOf(from)), goalY: yOf(to), floor, body: e.movement.height });
56
+ const path = findPath((x, z, y) => e.collision.walkableAt(x, z, radius, y, rest.passes), sx, sz, gx, gz, { ...rest, radius, y: floor(sx, sz, yOf(from)), goalY: yOf(to), floor, body: e.movement.height });
53
57
  // nav installed but not ready: A* is only a stand-in, tell the caller honestly
54
58
  res = { status: e.nav ? 'notReady' : path ? 'ok' : 'noPath', path };
55
59
  }
@@ -66,7 +70,9 @@ const CHARACTERS_PARAMS = keysSchema(['npcs', 'npcTiers', 'animation', 'fall']);
66
70
  * @param {any} animation characters({ animation })
67
71
  */
68
72
  function charactersApi(e, st, animation) {
69
- const share = m => { e.assets.shared.add(m); return m; }; // every capsule draws with it: removing one character must not dispose it
73
+ // keepPart: every capsule draws with this material, so removing one character must not dispose it. The hold goes when the material is replaced or the
74
+ // module unloads (dispose below), and a default one is then freed here, as no asset load owns it; a game's is ordinary again for engine.remove
75
+ const hold = m => { st.keep?.remove(); st.keep = keepPart(m); return (st.material = m); };
70
76
  const api = {
71
77
  /** @internal characters({ animation }): what every model's Animator starts from (useModel.js) */
72
78
  _animation: animation,
@@ -78,12 +84,12 @@ function charactersApi(e, st, animation) {
78
84
  * @example engine.characters.material = new THREE.MeshToonMaterial({ color: 0xd9a066 });
79
85
  * @type {THREE.Material}
80
86
  */
81
- get material() { return (st.material ??= share(capsuleDefault())); },
87
+ get material() { return st.material ?? hold(capsuleDefault()); },
82
88
  set material(m) {
83
89
  needMaterial('character-option', 'engine.characters.material', m, '. Example: engine.characters.material = new THREE.MeshStandardMaterial({ color: 0xd9a066 })');
84
90
  const old = api.material;
85
91
  if (m === old) return;
86
- st.material = share(m);
92
+ hold(m);
87
93
  for (const [mesh, color] of api._capsules) {
88
94
  if (mesh.material !== old) mesh.material.dispose(); // the copy in a character's own color
89
95
  mesh.material = capsuleMaterial(m, color);
@@ -109,12 +115,15 @@ function charactersApi(e, st, animation) {
109
115
  /**
110
116
  * Pathfinding (the only entry): navmesh if nav is ready, else A* (needs the collision module). Returns [{ x, y, z }…], null if unreachable: every point has its height, and a y on from / to picks the floor.
111
117
  * Pass { detailed: true } to get { status, path }: 'ok' found | 'noPath' unreachable | 'notReady' nav installed but mesh not generated yet (path is the
112
- * A* fallback, may be inaccurate; null without collision)
118
+ * A* fallback, may be inaccurate; null without collision). { passes: ['gate'] }: the path goes through colliders of those layers (collision.addBox { layer }), as the body does
119
+ * (walkTo and NPCs pass their character's passes themselves)
113
120
  * Where paths come from is the rule 'characters.path' (findPathAsync, walkTo and NPCs follow it too; o.id picks an entry for one character): default 'walk' is the above, false is no path,
114
121
  * a function ({ from, to, o }, engine) => [{ x, y?, z }…] | null | 'walk' is your own source, for flight, swimming or anything off the ground. It must be deterministic; it is not saved
115
122
  * @example engine.mod('characters.path', { owner: 'birds', id: 'hawk', set: ({ from, to }) => [from, { x: to.x, y: 40, z: to.z }, to] });
116
123
  */
117
124
  findPath(from, to, o = {}) { return solvePath(e, st, from, to, o); },
125
+ /** @internal may a nav crowd agent walk for this NPC: not with passes (the crowd's one mesh stops at every collider) or a 'characters.path' entry of its own (a game's source or false) */
126
+ _crowdFits(id, passes) { return !passes?.length && st.path.value(id) === 'walk'; },
118
127
  /**
119
128
  * findPath for many callers (NPC crowds, AI squads): solved in engine.threads workers, done(path, status) runs on a fixed step ~4 steps later
120
129
  * via engine.commits, so threads on / off give the same paths. Keep findPath for the few that need a path now (click-to-move). Details: recipe 12
@@ -122,13 +131,12 @@ function charactersApi(e, st, animation) {
122
131
  * @param {any} from
123
132
  * @param {any} to
124
133
  * @param {(path: { x: number, y: number, z: number }[] | null, status: 'ok' | 'noPath' | 'notReady') => void} done
125
- * @param {{ radius?: number, step?: number, maxNodes?: number }} [opts]
134
+ * @param {{ radius?: number, passes?: string[], step?: number, maxNodes?: number }} [opts]
126
135
  * @returns {{ remove: () => void }}
127
136
  * @example const req = engine.characters.findPathAsync(guard.position, target, (path, status) => { guard.path = path; });
128
137
  * req.remove(); // target changed before the answer came
129
138
  */
130
139
  findPathAsync(from, to, done, opts) { return st.paths.request(from, to, done, opts); },
131
- /** How many findPathAsync requests leave per fixed step (default 32); the rest wait for the next steps */
132
140
  /**
133
141
  * Bends a link crossing away from its straight line: (t, position, crossing, character) with t 0-1, called each step after position is set on the line, write to position.
134
142
  * Depends only on its arguments, so a crossing saved halfway resumes on the same curve. null = the straight line
@@ -136,13 +144,14 @@ function charactersApi(e, st, animation) {
136
144
  * @experimental
137
145
  */
138
146
  linkPose: null,
147
+ /** How many findPathAsync requests leave per fixed step (default 32); the rest wait for the next steps */
139
148
  get pathsPerStep() { return st.paths.perStep; },
140
149
  set pathsPerStep(n) { st.paths.perStep = Math.max(1, n | 0); },
141
150
  /**
142
151
  * The 'camera' player control as a value: movement keys / stick relative to the camera (world axes, up = -Z, without a camera module), the 'run' action
143
152
  * when the game bound one, input.autopilot.
144
153
  * Returns a reused { x, z, run } (do not keep it). Call it from your own control function to wrap the default instead of rewriting it. seat: read an engine.input.seat() instead of engine.input
145
- * @example createPlayer({ ...presets.player.thirdPerson, control: (p, input) => busy ? null : engine.characters.moveInput() }) // no movement while
154
+ * @example addPlayer({ ...presets.player.thirdPerson, control: (p, input) => busy ? null : engine.characters.moveInput() }) // no movement while
146
155
  * attacking
147
156
  */
148
157
  moveInput(seat) { return moveInput(e, seat); },
@@ -162,7 +171,6 @@ function charactersApi(e, st, animation) {
162
171
  */
163
172
  addVehicle(vehicle) { return e.ops.allow(() => addVehicle(e, vehicle)); },
164
173
  /** @internal outside a fixed step: the rig calls it before it reads a rider's position (camera/common.js) */
165
- /** @internal the camera calls this after its own step, so a rider and the view move together */
166
174
  carryRiders() { carryRiders(e, true); },
167
175
  /**
168
176
  * Remove a player, by default engine.player (exit the vehicle first, stop responding to keys, dispose the model: animation, geometry, materials; the 'player' record in
@@ -186,13 +194,13 @@ function charactersApi(e, st, animation) {
186
194
  * module at the player (and back after a vehicle)
187
195
  * The world record, saving and describe().player work the same for every control. The engine drives the player on its channel (default
188
196
  * 'player': dt passed to move and to the control function is engine.time.dt('player', 'player'), so engine.mod('time.player', ...) slows it)
189
- * @example const player = engine.characters.createPlayer({ ...presets.player.thirdPerson, spawn: engine.characters.findSpawn() })
197
+ * @example const player = engine.characters.addPlayer({ ...presets.player.thirdPerson, spawn: engine.characters.findSpawn() })
190
198
  * @example const roll = engine.control.take(player, { owner: 'roll', layer: 'script', step: () => ({ x: 0, z: 1, run: true }) }); engine.clock.after(0.4, () => roll.remove(), { channel: 'real' })
191
199
  */
192
200
  // creating the player is setup (a game does it after loading its model, or on level:loaded), not a gameplay action: the ops guard lets its writes through
193
- createPlayer(opts = {}) { return e.ops.allow(() => api._createPlayer(opts)); },
201
+ addPlayer(opts = {}) { return e.ops.allow(() => api._createPlayer(opts)); },
194
202
  /** @internal */
195
- _createPlayer(opts) { return createPlayer(e, api, st, opts); },
203
+ _createPlayer(opts) { return addPlayer(e, api, st, opts); },
196
204
  };
197
205
  return api;
198
206
  }
@@ -200,9 +208,9 @@ function charactersApi(e, st, animation) {
200
208
  /** The player's actions, declared once by the module (gone with it); the game binds their keys (presets.bindings.walk / .brake), so no option takes keys.
201
209
  * optional: a player without jump or brake still works, reading them unbound stays silent */
202
210
  function declareActions(ctx) {
203
- ctx.input.action('jump', { label: 'input.jump', optional: true });
204
- ctx.input.action('run', { label: 'input.run', optional: true });
205
- ctx.input.action('brake', { label: 'input.brake', context: 'vehicle', optional: true });
211
+ ctx.input.define('jump', { label: 'input.jump', optional: true });
212
+ ctx.input.define('run', { label: 'input.run', optional: true });
213
+ ctx.input.define('brake', { label: 'input.brake', context: 'vehicle', optional: true });
206
214
  }
207
215
 
208
216
  /** What the module listens to, all through ctx.track */
@@ -250,10 +258,10 @@ function describeCharacters(e, ctx, mgr) {
250
258
  export function characters(opts = {}) {
251
259
  readParams('characters', CHARACTERS_PARAMS, opts);
252
260
  const { npcs = true, npcTiers, animation, fall } = opts;
253
- // players: what createPlayer made, by id. Their per-frame animation and per-step drive run in this module's own fixed / frame hooks (not
254
- // engine.onFixed), so a game onFixed sees the same player position whether it was registered before or after createPlayer (phase 'early' = before the move,
261
+ // players: what addPlayer made, by id. Their per-frame animation and per-step drive run in this module's own fixed / frame hooks (not
262
+ // engine.onFixed), so a game onFixed sees the same player position whether it was registered before or after addPlayer (phase 'early' = before the move,
255
263
  // 'late' = after)
256
- const st = { mgr: null, paths: null, path: null, players: new Map(), material: null };
264
+ const st = { mgr: null, paths: null, path: null, players: new Map(), material: null, keep: null };
257
265
  return {
258
266
  // before rigid: the player's move this step is in the physics step that follows (as when control was an onFixed)
259
267
  content: { npcs: NPC_CONTENT },
@@ -285,7 +293,11 @@ export function characters(opts = {}) {
285
293
  frame(dt, e) { for (const p of st.players.values()) p.character.animate(dt); carryRiders(e, true); },
286
294
  describe(e, ctx) { describeCharacters(e, ctx, st.mgr); },
287
295
  // a player, a queued path and the control lookup all outlive install unless they are ended here; the player's record stays in world, as NPC records do
288
- dispose(e) { for (const p of [...st.players.values()]) p.dispose(true); st.paths?.stop(); e.control.resolveWith(() => null); if (st.mgr) e.npcs = null; },
296
+ dispose(e) {
297
+ for (const p of [...st.players.values()]) p.dispose(true); st.paths?.stop(); e.control.resolveWith(() => null); if (st.mgr) e.npcs = null;
298
+ if (isEngineMade(st.material)) st.material.dispose(); // the default capsule material is this module's (kept, so nothing else frees it); a game's stays the game's
299
+ st.keep?.remove(); st.material = st.keep = null;
300
+ },
289
301
  };
290
302
  }
291
303