threedog 1.1.0 → 1.3.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 (370) hide show
  1. package/CHANGELOG.md +893 -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 +187 -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 +17 -7
  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 +8 -7
  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 +50 -28
  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 +36 -15
  85. package/core/scene/adaptive.js +144 -21
  86. package/core/scene/drawOnly.js +17 -0
  87. package/core/scene/gameLights.js +47 -4
  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 +17 -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 +30 -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 +24 -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 +7 -2
  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 +75 -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 +10 -9
  178. package/docs/recipes/61-deploy.md +5 -0
  179. package/docs/recipes/62-picture-code.md +72 -79
  180. package/docs/recipes/63-third-person-start.md +48 -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/.threedog/content-index.json +1 -1
  185. package/examples/action/GAMEMAP.md +2 -3
  186. package/examples/action/main.js +3 -3
  187. package/examples/action/picture/lights.js +3 -1
  188. package/examples/perf-island/.threedog/content-index.json +1 -1
  189. package/examples/perf-island/GAMEMAP.md +3 -3
  190. package/examples/perf-island/picture/lights.js +2 -1
  191. package/examples/plain-picture/GAMEMAP.md +1 -1
  192. package/examples/rc2d/GAMEMAP.md +1 -1
  193. package/examples/styletest/.threedog/content-index.json +1 -1
  194. package/examples/styletest/GAMEMAP.md +2 -2
  195. package/examples/styletest/main.js +1 -1
  196. package/examples/techniques/interior-light/README.md +3 -3
  197. package/examples/techniques/interior-light/interiorLight.js +2 -4
  198. package/examples/techniques/interior-light/picture/lights.js +2 -1
  199. package/examples/techniques/modular-building/picture/lights.js +3 -1
  200. package/examples/techniques/outlines-and-rim/picture/lights.js +3 -1
  201. package/examples/techniques/procedural-animation/README.md +1 -1
  202. package/examples/techniques/procedural-animation/main.js +1 -1
  203. package/examples/webgpu-tsl/GAMEMAP.md +1 -1
  204. package/examples/world/.threedog/content-index.json +1 -1
  205. package/examples/world/GAMEMAP.md +2 -3
  206. package/examples/world/art/humanoid.js +1 -1
  207. package/examples/world/main.js +6 -3
  208. package/index.d.ts +2 -2
  209. package/llms.txt +101 -0
  210. package/modules/ambience/Ambience.js +21 -5
  211. package/modules/calendar/index.js +9 -5
  212. package/modules/calendar/schedule.js +23 -8
  213. package/modules/camera/FirstPersonCamera.js +3 -1
  214. package/modules/camera/FollowCamera.js +10 -5
  215. package/modules/camera/RtsCamera.js +4 -3
  216. package/modules/camera/common.js +70 -8
  217. package/modules/camera/contract.js +1 -1
  218. package/modules/characters/Character.js +16 -10
  219. package/modules/characters/NPC.js +31 -19
  220. package/modules/characters/assetModel.js +14 -9
  221. package/modules/characters/astar.js +6 -1
  222. package/modules/characters/contract.js +2 -2
  223. package/modules/characters/index.js +34 -22
  224. package/modules/characters/movers/manual.js +1 -1
  225. package/modules/characters/movers/rapier.js +17 -2
  226. package/modules/characters/movers/simple.js +1 -1
  227. package/modules/characters/movers/support.js +16 -7
  228. package/modules/characters/npcAvoid.js +2 -2
  229. package/modules/characters/npcSim.js +3 -2
  230. package/modules/characters/pathAsync.js +24 -8
  231. package/modules/characters/pathJob.js +1 -1
  232. package/modules/characters/player.js +10 -9
  233. package/modules/characters/playerStrings.js +5 -5
  234. package/modules/characters/proceduralRig.js +5 -5
  235. package/modules/characters/useModel.js +6 -0
  236. package/modules/characters/walkTo.js +1 -1
  237. package/modules/collision/Collision.js +29 -18
  238. package/modules/collision/grid.js +22 -4
  239. package/modules/content/index.js +3 -1
  240. package/modules/content/loader.js +1 -1
  241. package/modules/content/models.js +82 -33
  242. package/modules/content/props.js +2 -1
  243. package/modules/content/rules.js +11 -5
  244. package/modules/content/templates.js +3 -3
  245. package/modules/content/words.js +2 -2
  246. package/modules/debug/DebugPanel.js +9 -9
  247. package/modules/flow/index.js +9 -6
  248. package/modules/gameplay/Dialogue.js +34 -20
  249. package/modules/gameplay/Interactions.js +19 -15
  250. package/modules/gameplay/Inventory.js +9 -4
  251. package/modules/gameplay/Quests.js +12 -10
  252. package/modules/gameplay/pickups.js +23 -11
  253. package/modules/grid/index.js +1 -1
  254. package/modules/grid/preview.js +2 -2
  255. package/modules/grid/tiles.js +1 -1
  256. package/modules/hlod/index.js +4 -1
  257. package/modules/hud/index.js +47 -10
  258. package/modules/hud/parts.js +28 -9
  259. package/modules/level/geometry.js +8 -3
  260. package/modules/level/index.js +10 -5
  261. package/modules/level/load.js +4 -2
  262. package/modules/lights/sources.js +1 -1
  263. package/modules/music/Music.js +22 -4
  264. package/modules/nav/index.js +20 -10
  265. package/modules/particles/Particles.js +31 -14
  266. package/modules/particles/effect.js +20 -5
  267. package/modules/particles/lit.js +72 -0
  268. package/modules/photo/Photo.js +72 -28
  269. package/modules/photo/pathTrace.js +106 -0
  270. package/modules/rigid/RigidBodies.js +23 -14
  271. package/modules/rigid/Vehicles.js +3 -13
  272. package/modules/rigid/sync.js +2 -1
  273. package/modules/settings/Settings.js +52 -20
  274. package/modules/settings/apply.js +23 -9
  275. package/modules/settings/sections.js +39 -6
  276. package/modules/settings/strings.js +2 -0
  277. package/modules/settings/view.js +19 -3
  278. package/modules/sky/dome.js +15 -3
  279. package/modules/sky/environment.js +28 -12
  280. package/modules/sky/fog.js +1 -1
  281. package/modules/sky/frame.js +6 -1
  282. package/modules/sky/shader.js +4 -3
  283. package/modules/sky/skyModule.js +8 -4
  284. package/modules/swarm/Swarm.js +1 -1
  285. package/modules/terrain/ChunkManager.js +61 -15
  286. package/modules/terrain/chunkJob.js +2 -2
  287. package/modules/terrain/index.js +20 -5
  288. package/modules/terrain/terrainEdit.js +8 -4
  289. package/modules/terrain/terrainTexture.js +4 -2
  290. package/modules/timeline/Timeline.js +4 -3
  291. package/modules/timeline/Tween.js +3 -0
  292. package/modules/timeline/letterbox.js +1 -0
  293. package/modules/triggers/index.js +36 -17
  294. package/modules/vegetation/Vegetation.js +81 -19
  295. package/modules/vegetation/densityMap.js +13 -8
  296. package/modules/vegetation/draw.js +147 -24
  297. package/modules/vegetation/groundChunks.js +20 -5
  298. package/modules/vegetation/index.js +3 -3
  299. package/modules/vegetation/modelGeometry.js +9 -4
  300. package/modules/water/Water.js +11 -8
  301. package/modules/weather/Weather.js +7 -2
  302. package/modules/weather/shaders.js +25 -5
  303. package/modules/weather/weatherDraw.js +20 -6
  304. package/modules/world/World.js +2 -1
  305. package/modules/world/index.js +2 -2
  306. package/modules/world/persist.js +6 -2
  307. package/modules/world/views.js +15 -2
  308. package/package.json +5 -1
  309. package/presets.js +5 -5
  310. package/render/PostFX.js +102 -42
  311. package/render/backend.js +142 -16
  312. package/render/bindingLimits.js +59 -0
  313. package/render/cascades.js +3 -1
  314. package/render/cascades.tsl.js +2 -0
  315. package/render/daylight.js +7 -1
  316. package/render/detail.js +7 -4
  317. package/render/effects.js +27 -8
  318. package/render/fogLook.js +24 -0
  319. package/render/fuse.js +5 -2
  320. package/render/fx/compareLevel.tsl.js +23 -0
  321. package/render/fx/detail.tsl.js +9 -7
  322. package/render/fx/index.js +9 -2
  323. package/render/fx/library.tsl.js +1 -0
  324. package/render/fx/lightShaft.tsl.js +114 -0
  325. package/render/fx/noise.tsl.js +25 -8
  326. package/render/fx/objectOrigin.tsl.js +39 -10
  327. package/render/fx/particles.tsl.js +23 -6
  328. package/render/fx/patchNodes.tsl.js +17 -12
  329. package/render/fx/pcss.tsl.js +51 -0
  330. package/render/fx/postWebGPU.tsl.js +104 -29
  331. package/render/fx/sky.tsl.js +3 -9
  332. package/render/fxNumbers.js +10 -4
  333. package/render/impostor.tsl.js +107 -0
  334. package/render/lighting.js +33 -1
  335. package/render/lightmap.js +42 -28
  336. package/render/lights.js +19 -3
  337. package/render/materials.js +6 -4
  338. package/render/mergeCommon.js +4 -1
  339. package/render/occlusion.js +14 -4
  340. package/render/patches.js +79 -41
  341. package/render/postRuns.js +32 -0
  342. package/render/postWebGL.js +97 -10
  343. package/render/probes.js +10 -14
  344. package/render/shaderErrors.js +44 -7
  345. package/render/shadowCache.tsl.js +33 -5
  346. package/render/shadows.js +42 -16
  347. package/render/slots.js +8 -5
  348. package/render/vertexInputs.js +52 -0
  349. package/types/core.d.ts +115 -47
  350. package/types/gameplay.d.ts +56 -23
  351. package/types/generated/core/audio/Audio.d.ts +27 -1
  352. package/types/generated/core/base/Random.d.ts +1 -1
  353. package/types/generated/core/input/Input.d.ts +6 -8
  354. package/types/generated/core/input/inputSeat.d.ts +1 -1
  355. package/types/generated/core/inspect/Budget.d.ts +26 -0
  356. package/types/generated/core/inspect/DebugOverrides.d.ts +0 -2
  357. package/types/generated/core/saves/Saves.d.ts +10 -7
  358. package/types/generated/core/saves/session.d.ts +8 -2
  359. package/types/generated/core/scene/Rays.d.ts +1 -3
  360. package/types/generated/core/scene/Views.d.ts +17 -3
  361. package/types/generated/modules/particles/Particles.d.ts +1 -1
  362. package/types/generated/modules/world/World.d.ts +2 -1
  363. package/types/generated/render/PostFX.d.ts +35 -9
  364. package/types/physics.d.ts +796 -764
  365. package/types/pixel.d.ts +1 -1
  366. package/types/tsl.d.ts +62 -1
  367. package/types/world.d.ts +12 -3
  368. package/ui/Focus.js +7 -5
  369. package/ui/Parts.js +1 -1
  370. package/ui/touchPart.js +6 -3
@@ -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
 
@@ -1,6 +1,6 @@
1
1
  // mover: 'manual': the game owns the position. The engine integrates no velocity and applies no gravity; it only keeps what other systems read
2
2
  // in step with where the game put the character: grounded, what it stands on (a support still carries it), safeGround and the fall check.
3
- // const p = createPlayer({ control: (p, input, dt) => { p.position.x += 3 * dt; return null; }, faceMode: 'manual', mover: 'manual' });
3
+ // const p = addPlayer({ control: (p, input, dt) => { p.position.x += 3 * dt; return null; }, faceMode: 'manual', mover: 'manual' });
4
4
  // Why a mover and not "a control that never moves": control decides where to go (core/ops/control.js), the mover is still the one that writes the
5
5
  // position. 'manual' is the takeover level for the position itself, so a hand-written controller (a platformer's own physics) keeps the
6
6
  // platform, safe-ground and fall behaviour without fighting the built-in integration.
@@ -4,6 +4,8 @@
4
4
  // The player uses rigid.playerBody / playerCollider (rigid syncs it to the player position each step); each NPC builds its own kinematic capsule.
5
5
  import { steer, water, float, tryJump, tickJump, leaveGround, land, finish, stat, inherited, climbLimit } from './common.js';
6
6
  import { beginMove, endMove } from './support.js';
7
+ import { passesThrough } from '../../collision/grid.js';
8
+ import { warnOnce, DEV } from '../../../core/base/validate.js';
7
9
 
8
10
  /** Create the 'rapier' mover (c is the character, fallback is the simple mover used when not ready) */
9
11
  export function rapierMover(c, fallback) {
@@ -32,7 +34,9 @@ export function rapierMover(c, fallback) {
32
34
  else { c.vy += stat(c, 'gravity') * dt; dy = c.vy * dt; }
33
35
  }
34
36
  const wasGrounded = c.grounded;
35
- m.controller.computeColliderMovement(col, { x: (c.velocity.x + (inh?.x ?? 0)) * dt, y: dy, z: (c.velocity.y + (inh?.y ?? 0)) * dt }, r.rapier.QueryFilterFlags.EXCLUDE_DYNAMIC | r.rapier.QueryFilterFlags.EXCLUDE_SENSORS);
37
+ // a collision-module collider with a layer this body passes is skipped (the same passesThrough the simple mover and paths use); no layers anywhere: no predicate, as before
38
+ const through = c.passes && r._layered.size ? m.through : undefined;
39
+ m.controller.computeColliderMovement(col, { x: (c.velocity.x + (inh?.x ?? 0)) * dt, y: dy, z: (c.velocity.y + (inh?.y ?? 0)) * dt }, r.rapier.QueryFilterFlags.EXCLUDE_DYNAMIC | r.rapier.QueryFilterFlags.EXCLUDE_SENSORS, undefined, through);
36
40
  const mv = m.controller.computedMovement();
37
41
  p.x += mv.x; p.y += mv.y; p.z += mv.z;
38
42
  // hit a wall (not stepping up): velocity becomes the wall-sliding velocity, so standing at a wall does not keep walking
@@ -70,7 +74,18 @@ export function rapierMover(c, fallback) {
70
74
  function setup(e, r) {
71
75
  const R = r.rapier, w = r.world, p = c.root.position;
72
76
  m.world = w; // what the handles below belong to: the world object itself, since a count would match across two rigid modules
73
- if (c === e.player) { m.body = r.playerBody; m.collider = r.playerCollider; }
77
+ // built with the controller: a replaced rigid keeps its layered colliders in its own map, and a test kept from the first one would read every collider as "no layer"
78
+ m.through = hit => { const o = r._layered.get(hit); return !(o && passesThrough(o, c.passes)); };
79
+ if (c === e.player) {
80
+ m.body = r.playerBody; m.collider = r.playerCollider;
81
+ // the capsule is the character's radius (as for every other character, and for simple movers and paths), unless the game set rigid({ playerCapsule: { radius } }): that wins.
82
+ // Written back, so a rebuilt world (rigid _newWorld) makes the same capsule
83
+ if (r._capsuleRadiusGiven) { if (DEV && c.radius !== r.playerCapsule.radius) warnOnce(`rigid({ playerCapsule: { radius: ${r.playerCapsule.radius} } }) differs from the player's radius ${c.radius}: the rapier collider uses ${r.playerCapsule.radius}, paths and the simple mover ${c.radius}. Set one of them, or make them equal`); }
84
+ else if (c.radius !== r.playerCapsule.radius) {
85
+ r.playerCapsule = { ...r.playerCapsule, radius: c.radius };
86
+ m.collider.setRadius(c.radius); m.collider.setTranslationWrtParent({ x: 0, y: r.playerCapsule.halfHeight + c.radius, z: 0 });
87
+ }
88
+ }
74
89
  else {
75
90
  const hh = r.playerCapsule.halfHeight;
76
91
  m.body = w.createRigidBody(R.RigidBodyDesc.kinematicPositionBased().setTranslation(p.x, p.y, p.z));
@@ -19,7 +19,7 @@ function walkPiece(c, dx, dz) {
19
19
  const nx = p.x, nz = p.z;
20
20
  if (!col.blockedAt(nx, oz, c.radius)) p.z = oz; else if (!col.blockedAt(ox, nz, c.radius)) p.x = ox; else { p.x = ox; p.z = oz; c.velocity.set(0, 0); moving = false; }
21
21
  }
22
- col?.resolve(p, c.radius);
22
+ col?.resolve(p, c.radius, c.passes);
23
23
  return moving;
24
24
  }
25
25
 
@@ -49,7 +49,9 @@ export function addSupport(e, object, { id, safe = true, carry = 'position', inh
49
49
  box.union(_b.copy(g.boundingBox).applyMatrix4(_m.multiplyMatrices(inv, o.matrixWorld)));
50
50
  });
51
51
  if (box.isEmpty()) throw codedError('character-option', `characters.support(object '${id}'): it has no mesh to measure; pass a mesh or a group with meshes`);
52
- const entry = { id, object, safe, carry, inherit, box };
52
+ // r: the box's reach across x / z from the object's origin, for a quick "nowhere near" test (standAt's quick form)
53
+ const r = Math.max(...[box.min, box.max].flatMap(a => [box.min, box.max].map(b => Math.hypot(a.x, b.z))));
54
+ const entry = { id, object, safe, carry, inherit, box, r };
53
55
  R.list.set(id, entry);
54
56
  return { id, remove: () => {
55
57
  if (R.list.get(id) !== entry) return;
@@ -58,9 +60,13 @@ export function addSupport(e, object, { id, safe = true, carry = 'position', inh
58
60
  } };
59
61
  }
60
62
 
61
- /** Height of entry's top under world (x, z), or null when (x, z) is off it */
62
- function topAt(entry, x, z) {
63
+ /** Height of entry's top under world (x, z), or null when (x, z) is off it. quick: judge "nowhere near" by the matrix as last refreshed first */
64
+ function topAt(entry, x, z, quick) {
63
65
  const o = entry.object, b = entry.box;
66
+ if (quick) {
67
+ const el = o.matrixWorld.elements, sc = Math.max(Math.hypot(el[0], el[1], el[2]), Math.hypot(el[8], el[9], el[10]));
68
+ if (Math.hypot(x - el[12], z - el[14]) > entry.r * sc + 1) return null; // +1 m: it may have moved since the last refresh
69
+ }
64
70
  o.updateWorldMatrix(true, false); // the game moved it this step; matrixWorld is otherwise only refreshed at render
65
71
  _v.set(x, 0, z).applyMatrix4(_inv.copy(o.matrixWorld).invert());
66
72
  if (_v.x < b.min.x || _v.x > b.max.x || _v.z < b.min.z || _v.z > b.max.z) return null;
@@ -71,15 +77,18 @@ function topAt(entry, x, z) {
71
77
  * @internal What stands at (x, z): { y, on } with on the support that won, or null. With a height y: engine.surface plus every registered support whose
72
78
  * top is within `step` above y, higher ones are passed under. Without y (undefined): the highest support top, so a placement on a boat at sea stands on
73
79
  * the deck and not on the sea floor. y may be -Infinity beyond terrain({ shape }). The one rule for walking, placing and data-only NPCs: one place, one answer.
80
+ * out: the object to fill (a per-frame caller allocates nothing); quick: skip supports far from (x, z) by their last refreshed matrix (feet IK, a picture
81
+ * reader every frame; the movers keep the exact form).
74
82
  */
75
- export function standAt(e, x, z, y, step) {
83
+ export function standAt(e, x, z, y, step, out = { y: 0, on: null }, quick = false) {
76
84
  let h = e.surface(x, z, y), on = null;
77
85
  const R = REG.get(e);
78
86
  if (R?.list.size) for (const en of R.list.values()) {
79
- const t = topAt(en, x, z);
87
+ const t = topAt(en, x, z, quick);
80
88
  if (t != null && t > h && (y === undefined || t <= y + step + 1e-3)) { h = t; on = en; }
81
89
  }
82
- return { y: h, on };
90
+ out.y = h; out.on = on;
91
+ return out;
83
92
  }
84
93
 
85
94
  /** @internal Ground height under (x, z) for a character at height y (standAt). Sets the state's `hit` to the support that won (or null) */
@@ -161,7 +170,7 @@ function tellNoFallRule(c) {
161
170
  if (c !== e.player || c.root.position.y >= Math.max(e.ground.voidY?.() ?? -Infinity, FALL_Y)) return;
162
171
  const point = e.stacks.get('fall');
163
172
  if (point.holders().length + point.holders(c.id).length) return;
164
- warnOnce(coded('character-option', `the player fell past the void and no rule 'fall' is set, so nothing brings it back. Decide what a fall is: engine.mod('fall', { owner: 'game', set: 'rescue' }) with createPlayer({ fall: { belowY } }) returns it to safeGround, a function is your own rule, and set: false says the game handles it`), 'fall-no-rule');
173
+ warnOnce(coded('character-option', `the player fell past the void and no rule 'fall' is set, so nothing brings it back. Decide what a fall is: engine.mod('fall', { owner: 'game', set: 'rescue' }) with addPlayer({ fall: { belowY } }) returns it to safeGround, a function is your own rule, and set: false says the game handles it`), 'fall-no-rule');
165
174
  }
166
175
 
167
176
  /** belowY: a height or (character) => boolean. character:fall once per fall, then the rule 'fall' decides: 'rescue' goes back to safeGround, nothing or false leaves it to the game */
@@ -110,7 +110,7 @@ export class NpcAvoid {
110
110
  /** Push ch (the rec's model) apart in x, z, from walkers on its own floor only (nav({ crowd: true }) separates by the mesh). Call after ch.move, edits ch.root.position x, z directly */
111
111
  push(rec, ch, dt) {
112
112
  const e = this.engine, W = e.world;
113
- if (!this.on || e.nav?.crowd) return;
113
+ if (!this.on || (e.nav?.crowd && ch._agent)) return; // a walker with a crowd agent is steered by it; one the crowd cannot serve (passes, own path source) is pushed as without a crowd
114
114
  const n = W.steps, own = this._start.get(rec.id), r = this.radius ?? e.movement.radius, min = 2 * r;
115
115
  if (!own || own.k !== n) return; // did not enter via NPC.js (goTo called directly): no avoidance
116
116
  if (this._gridN !== n) this._file(W, n, min);
@@ -132,6 +132,6 @@ export class NpcAvoid {
132
132
  p.x += mx; p.z += mz;
133
133
  // skip collision for pushes under half a centimetre (the mover keeps it out of walls next step); in a crowd every NPC is nudged every step, so this saves
134
134
  // most collision queries
135
- if (mx * mx + mz * mz > 2.5e-5) e.collision?.resolve(p, ch.radius);
135
+ if (mx * mx + mz * mz > 2.5e-5) e.collision?.resolve(p, ch.radius, ch.passes);
136
136
  }
137
137
  }
@@ -122,7 +122,8 @@ export function goTo(e, W, rec, ch, goal, dt) {
122
122
  const nav = rec.nav, p = ch.root.position;
123
123
  const dGoal = goal ? Math.hypot(goal.x - p.x, goal.z - p.z) : 0;
124
124
  if (rec.busy || !goal || (dGoal < rec.arriveDistance && sameLevel(e, p, goal) && !linkAhead(nav.path) && !ch._linkNext)) ch.move(0, 0, false, dt);
125
- else if (e.nav?.crowd) crowdMove(e, rec, ch, goal, dt);
125
+ // a Detour crowd lives on the agent's one mesh and knows no 'characters.path' source: an NPC with passes or its own source takes the path entry below, like every other walker
126
+ else if (e.nav?.crowd && e.characters._crowdFits(rec.id, ch.passes)) crowdMove(e, rec, ch, goal, dt);
126
127
  else {
127
128
  nav.repath -= dt;
128
129
  // goal changed while waiting, or the answer never came (engine.commits.invalidate dropped it: a partial saves.apply, a level change): ask again
@@ -134,7 +135,7 @@ export function goTo(e, W, rec, ch, goal, dt) {
134
135
  if (ch._pathReq !== req) return;
135
136
  // no way there: it stands and asks again at the next repath, a failed search is no licence to press on along the line. A far leg is only a heading, not a place it must reach
136
137
  ch._pathReq = null; nav.path = path ?? (far ? [{ x: tx, y: p.y, z: tz }] : null);
137
- }, { radius: ch.radius, step: rec.pathStep, id: rec.id });
138
+ }, { radius: ch.radius, passes: ch.passes, step: rec.pathStep, id: rec.id });
138
139
  req.goal = goal; req.at = e.time.tick;
139
140
  nav.repath = rec.repath;
140
141
  }
@@ -10,8 +10,11 @@
10
10
  import { xzOf, yOf } from '../../core/base/math.js';
11
11
  import { surfaceOr } from '../../core/scene/ground.js';
12
12
  import { solveBatch, pathHandler, astarDefaults, RES, TILE, tileOf } from './pathJob.js';
13
- import { codedError } from '../../core/base/errorHints.js';
13
+ import { codedError, coded } from '../../core/base/errorHints.js';
14
14
  import { withHeights } from './moveHelpers.js';
15
+ import { reportError } from '../../core/base/errors.js';
16
+ import { warnOnce } from '../../core/base/validate.js';
17
+ import { passesOf } from '../collision/grid.js';
15
18
 
16
19
  /** Steps between sending a batch and its answers taking effect (4 = 67 ms): enough for a worker round trip, short enough that an NPC barely waits */
17
20
  const PATH_LAG = 4;
@@ -36,6 +39,15 @@ export function sourcePath(e, rule, from, to, o) {
36
39
  return d?.length ? { status: 'ok', path: d.map(p => ({ ...p, ...point(p) })) } : { status: 'noPath', path: null };
37
40
  }
38
41
 
42
+ /**
43
+ * nav() is installed but cannot answer, and has no walkable mesh (procedural terrain has none): paths silently stand on collision A*. Say so once,
44
+ * in dev. Which method answers is unchanged. Also said while a level is still loading, so the text names both causes (characters may not import the level module).
45
+ */
46
+ export function noteAStarStandIn(e) {
47
+ if (!e.nav || e.nav.ready) return;
48
+ warnOnce(coded('nav-fallback', 'nav() is installed but has no navmesh (it is built from the level ground: that level is still loading, or the terrain is procedural, which has none), so characters.findPath and findPathAsync use collision A* instead. Paths work, but are coarser than a navmesh and nav links / crowds do not apply.'), 'nav-fallback');
49
+ }
50
+
39
51
  /** @internal */
40
52
  export class AsyncPaths {
41
53
  constructor(e, rule) {
@@ -46,11 +58,13 @@ export class AsyncPaths {
46
58
  this.lane = null;
47
59
  this.sent = { from: null, meshes: new Map(), ver: -1 }; // what the workers mirror, and of which provider: mesh size -> its revision, collision version
48
60
  this.turn = 0; // bumps with every provider
61
+ this.ground = 0; // bumps with every ground:change: a batch computed on the ground before a terrain edit must not land (the navmesh / collision numbers do not move for it)
49
62
  this.tiles = new Map(); // 'tx:tz' -> { data, trees, at, bv }
50
63
  }
51
64
  request(from, to, done, o = {}) {
52
65
  if (typeof done !== 'function') throw codedError('character-option', NO_DONE);
53
- const [sx, sz] = xzOf(from), [gx, gz] = xzOf(to);
66
+ const [sx, sz] = xzOf(from), [gx, gz] = xzOf(to), passes = passesOf('characters.findPathAsync()', o.passes);
67
+ if (passes !== o.passes) o = { ...o, passes }; // the read form: one set of layers is one navmesh
54
68
  const h = { sx, sz, gx, gz, sy: yOf(from), gy: yOf(to), o, done, epoch: this.e.commits.epoch, canceled: false, remove() { h.canceled = true; } };
55
69
  this.queue.push(h);
56
70
  return h;
@@ -60,9 +74,10 @@ export class AsyncPaths {
60
74
  /** Which walkable state answers now: navmesh revision, collision version, or nothing */
61
75
  key() {
62
76
  const e = this.e, from = e.nav?.ready ? e.nav : e.collision;
77
+ if (from === e.collision) noteAStarStandIn(e);
63
78
  // another provider starts its numbers over, so equal ones say nothing: what the workers mirror goes, and a batch of the old one cannot match the new key
64
79
  if (from !== this.sent.from) { this.sent = { from, meshes: new Map(), ver: -1 }; this.turn++; }
65
- return from === e.nav ? `n${this.turn}.${e.nav.revision}` : from ? `g${this.turn}.${e.collision.version}` : '-';
80
+ return from === e.nav ? `n${this.turn}.${e.nav.revision}.${this.ground}` : from ? `g${this.turn}.${e.collision.version}.${this.ground}` : '-';
66
81
  }
67
82
  /** Each fixed step (characters fixed): send up to perStep queued requests as one batch */
68
83
  flush() {
@@ -87,7 +102,7 @@ export class AsyncPaths {
87
102
  for (let i = 0; i < c.trees.length; i += 3) { const id = c.trees[i] + ',' + c.trees[i + 1]; if (!seen.has(id)) { seen.add(id); trees.push(c.trees[i], c.trees[i + 1], c.trees[i + 2]); } }
88
103
  };
89
104
  const reqs = list.map(({ sx, sy, sz, gx, gy, gz, o }) => {
90
- if (mode === 'nav') { const m = e.nav.mesh(o.radius); return { mode, size: m.size, s: e.nav.point([sx, sy, sz], m), g: e.nav.point([gx, gy, gz], m), reach: e.nav.reach(o.radius), body: e.movement.height }; }
105
+ if (mode === 'nav') { const m = e.nav.mesh(o.radius, o.passes); return { mode, size: m.size, s: e.nav.point([sx, sy, sz], m), g: e.nav.point([gx, gy, gz], m), reach: e.nav.reach(o.radius), body: e.movement.height }; }
91
106
  if (mode === 'none') return { mode };
92
107
  const radius = o.radius ?? e.movement.radius, dflt = astarDefaults(radius), step = o.step ?? dflt.step, maxNodes = o.maxNodes ?? dflt.maxNodes;
93
108
  // A* may wander this far beyond the start-goal box; bounded by how far maxNodes cells can reach
@@ -95,7 +110,7 @@ export class AsyncPaths {
95
110
  for (let tx = tileOf(Math.min(sx, gx) - m); tx <= tileOf(Math.max(sx, gx) + m); tx++)
96
111
  for (let tz = tileOf(Math.min(sz, gz) - m); tz <= tileOf(Math.max(sz, gz) + m); tz++) take(tx + ':' + tz, tx, tz);
97
112
  const at = (x, z, y) => surfaceOr(e, x, z, y, y);
98
- return { mode, s: { x: sx, y: at(sx, sz, sy), z: sz }, g: { x: gx, y: gy === undefined ? undefined : at(gx, gz, gy), z: gz }, body: e.movement.height, climb: e.movement.stepHeight, radius, step, maxNodes, navPending: !!e.nav };
113
+ return { mode, s: { x: sx, y: at(sx, sz, sy), z: sz }, g: { x: gx, y: gy === undefined ? undefined : at(gx, gz, gy), z: gz }, body: e.movement.height, climb: e.movement.stepHeight, radius, passes: o.passes, step, maxNodes, navPending: !!e.nav };
99
114
  });
100
115
  return { type: 'batch', key, reqs, tiles, heights, lower, trees };
101
116
  }
@@ -129,8 +144,9 @@ export class AsyncPaths {
129
144
  if (this.tiles.size > 4096) for (const [kk, o] of this.tiles) if (e.time.tick - o.at >= TILE_TTL) this.tiles.delete(kk);
130
145
  return v;
131
146
  }
132
- /** Forget cached tiles overlapping a world box (ground:change) */
147
+ /** Forget cached tiles overlapping a world box and retire batches in flight (ground:change) */
133
148
  dropTiles({ x0, z0, x1, z1 }) {
149
+ this.ground++; // also ends the batches in flight: key() reads it, land() recomputes them on the edited ground
134
150
  const span = TILE * RES;
135
151
  for (const k of this.tiles.keys()) {
136
152
  const [tx, tz] = k.split(':').map(Number);
@@ -150,7 +166,7 @@ export class AsyncPaths {
150
166
  if (key[0] === 'g' && this.sent.ver !== e.collision.version) {
151
167
  this.sent.ver = e.collision.version;
152
168
  const items = [];
153
- e.collision.forEachStatic((type, o) => items.push(type === 'box' ? { x: o.x, y: o.y, z: o.z, h: o.h, r: o.r, c: o.c, s: o.s, hw: o.hw, hd: o.hd, box: true } : { x: o.x, z: o.z, r: o.r, box: false }));
169
+ e.collision.forEachStatic((type, o) => items.push(type === 'box' ? { x: o.x, y: o.y, z: o.z, h: o.h, r: o.r, c: o.c, s: o.s, hw: o.hw, hd: o.hd, ly: o.ly, box: true } : { x: o.x, z: o.z, r: o.r, ly: o.ly, box: false }));
154
170
  this.lane.broadcast({ type: 'colliders', items }, 'colliders');
155
171
  }
156
172
  }
@@ -163,7 +179,7 @@ export class AsyncPaths {
163
179
  if (h.canceled) return;
164
180
  const from = { x: h.sx, y: h.sy, z: h.sz }, to = { x: h.gx, y: h.gy, z: h.gz }, a = sourcePath(e, this.rule, from, to, h.o) ?? r[i];
165
181
  if (a.path) withHeights(e, a.path, from, to);
166
- h.done(a.path, a.status);
182
+ try { h.done(a.path, a.status); } catch (err) { reportError(e, err, 'findPathAsync done', { soft: true }); } // one request's throw must not leave the rest of the batch without an answer
167
183
  });
168
184
  }
169
185
  }
@@ -29,7 +29,7 @@ function floorAt({ tiles, heights, lower }, x, z, y, climb) {
29
29
 
30
30
  /** Walkability from a batch: ground shape from the floor the walker is on, colliders tested exactly: the ground's own (terrain trees, sent with the batch) and the collision module's (mirrored grid) */
31
31
  function snapshotWalkable(batch, q, grid, trees) {
32
- return (x, z, y) => !!floorAt(batch, x, z, y, q.climb)?.ok && !gridBlocks(trees, x, z, q.radius) && !(grid && gridBlocks(grid, x, z, q.radius, y, q.body));
32
+ return (x, z, y) => !!floorAt(batch, x, z, y, q.climb)?.ok && !gridBlocks(trees, x, z, q.radius) && !(grid && gridBlocks(grid, x, z, q.radius, y, q.body, q.passes));
33
33
  }
34
34
 
35
35
  /** The worker's engine.surface(x, z, y); no ground there (the void of terrain({ shape }), or outside the sent tiles) leaves the walker at its height, as surfaceOr does */
@@ -1,4 +1,4 @@
1
- // The player: createPlayer and the parts it is made of. What the player is and how it is saved: the top of index.js.
1
+ // The player: addPlayer and the parts it is made of. What the player is and how it is saved: the top of index.js.
2
2
  import { Character, CHARACTER_KEYS } from './Character.js';
3
3
  import { warnOnce, DEV, fmt } from '../../core/base/validate.js';
4
4
  import { engineOwned } from '../../core/scene/things.js';
@@ -10,16 +10,16 @@ import { vehicleById, seatFromRecord } from './seat.js';
10
10
  /** The player's world record: its id and its kind */
11
11
  export const PLAYER = 'player';
12
12
 
13
- /** Everything createPlayer refuses, before it touches the old player */
13
+ /** Everything addPlayer refuses, before it touches the old player */
14
14
  function checkOptions(e, st, opts) {
15
- readParams('characters.createPlayer()', keysSchema([...CHARACTER_KEYS, 'spawn', 'control', 'cameraFollow', 'id', 'input']), opts);
15
+ readParams('characters.addPlayer()', keysSchema([...CHARACTER_KEYS, 'spawn', 'control', 'cameraFollow', 'id', 'input']), opts);
16
16
  const control = opts.control;
17
17
  if (control === undefined) throw codedError('player-control', DEV_STRINGS.noControl);
18
18
  if (!validControl(control)) throw codedError('player-control', fmt(DEV_STRINGS.badControl, { got: JSON.stringify(control) ?? String(control) }));
19
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 })');
20
+ if (opts.input !== undefined && !e.input.seats.includes(opts.input)) throw codedError('input-seat', 'characters.addPlayer(): input is a seat from engine.input.seat({ pad, keys })');
21
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
+ if (opts.input) for (const [other, q] of st.players) if (other !== id && q.input === opts.input) throw codedError('input-seat', `characters.addPlayer(): this seat already drives player '${other}'`);
23
23
  }
24
24
 
25
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
@@ -78,13 +78,13 @@ function watchRecord(e, W, p, id) {
78
78
  }
79
79
 
80
80
  /**
81
- * engine.characters.createPlayer, documented there
81
+ * engine.characters.addPlayer, documented there
82
82
  * @param {any} e engine
83
83
  * @param {any} api engine.characters
84
84
  * @param {any} st the module's state: the new player joins st.players
85
85
  * @param {any} opts
86
86
  */
87
- export function createPlayer(e, api, st, opts) {
87
+ export function addPlayer(e, api, st, opts) {
88
88
  checkOptions(e, st, opts);
89
89
  const W = e.world, { id = PLAYER, input = e.input } = opts;
90
90
  api.removePlayer(id); // a player of this id: dispose the old one first (else two characters respond to the same keys)
@@ -104,16 +104,17 @@ export function createPlayer(e, api, st, opts) {
104
104
  // in the map before control.take: the control lookup finds a held character by id through it
105
105
  const entry = { character: p, input, dispose: null };
106
106
  st.players.set(id, entry);
107
+ p._release = () => entry.dispose(); // player.dispose() from the game is the same teardown as removePlayer
107
108
  if (input !== e.input) input.actor = id;
108
109
  const held = e.control.take(p, { owner: 'player-input', layer: 'base', step: inputStep(e, api, p, opts.control, input) });
109
110
  // 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
111
  p._pedal = () => { if (!held.active) return null; const a = input.autopilot || input.axis; return [a.y, a.x, input.down('brake') ? 1 : 0]; };
111
112
  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
+ // keepRecord: the module is going, not the player; its place stays in world for the next addPlayer
113
114
  entry.dispose = (keepRecord = false) => {
114
115
  st.players.delete(id); held.remove(); jump?.remove(); for (const h of watching) h.remove();
115
116
  if (input.actor === id) input.actor = null;
116
- p.recordId = null; p.dispose(); if (!keepRecord) W.remove(id);
117
+ p.recordId = null; p._release = null; p.dispose(); if (!keepRecord) W.remove(id);
117
118
  if (e.player === p) e.player = st.players.values().next().value?.character ?? null; // the next player is the first now
118
119
  };
119
120
  return p;
@@ -1,13 +1,13 @@
1
1
  // Player-control error texts, i18n strings and the control check (split out of index.js)
2
2
  // The engine picks no player feel: control has no default (genericity rule: core carries no preset). A preset is one spread away, so the error names it first.
3
- const CONTROL_FIX = "pick how the player moves: createPlayer({ ...presets.player.thirdPerson, spawn }) (import { presets } from 'threedog'), " +
3
+ const CONTROL_FIX = "pick how the player moves: addPlayer({ ...presets.player.thirdPerson, spawn }) (import { presets } from 'threedog'), " +
4
4
  "control: 'camera' (keys relative to the camera) or a function (player, input, dt) => ({ x, z, run? }). The game moving the player itself (a roll, a lunge) " +
5
5
  "takes control for that time: engine.control.take(player, { owner: 'roll', layer: 'script', step })";
6
- export const DEV_STRINGS = { noControl: 'characters.createPlayer(): no control given; ' + CONTROL_FIX,
7
- badControl: "characters.createPlayer(): control {got} is not a control; " + CONTROL_FIX + ". (A function returning null stands still; a game-driven move takes control, see recipe 57)",
8
- noFollow: "characters.createPlayer(): a camera module is installed but cameraFollow was not given, so the camera does not follow the player. " +
6
+ export const DEV_STRINGS = { noControl: 'characters.addPlayer(): no control given; ' + CONTROL_FIX,
7
+ badControl: "characters.addPlayer(): control {got} is not a control; " + CONTROL_FIX + ". (A function returning null stands still; a game-driven move takes control, see recipe 57)",
8
+ noFollow: "characters.addPlayer(): a camera module is installed but cameraFollow was not given, so the camera does not follow the player. " +
9
9
  'Pass cameraFollow: true (presets.player.* do), or cameraFollow: false if the game aims the camera itself',
10
- noWorld: 'characters.createPlayer() needs world() installed first: the player is a record in world (position is saved, world splits near/far by it). Use engine.use(world(), …); openWorld() already installs it' };
10
+ noWorld: 'characters.addPlayer() needs world() installed first: the player is a record in world (position is saved, world splits near/far by it). Use engine.use(world(), …); openWorld() already installs it' };
11
11
  export const STRINGS = { 'zh-CN': { 'npc.talk': '和{name}说话', 'input.brake': '刹车' }, en: { 'npc.talk': 'Talk to {name}', 'input.brake': 'Brake' } };
12
12
 
13
13
  export const validControl = c => c === 'camera' || typeof c === 'function';
@@ -5,12 +5,12 @@
5
5
  // clone and GLB export and object references do not; so a procedural builder and a baked / hand-made GLB with those names animate the same way.
6
6
  import * as THREE from 'three';
7
7
  import { neutralMaterial } from '../../render/neutral.js';
8
- import { copyPatches, isEngineMade, markEngineMade } from '../../render/patches.js';
8
+ import { cloneMaterial, isEngineMade, markEngineMade } from '../../render/patches.js';
9
9
  import { warnOnce } from '../../core/base/validate.js';
10
10
 
11
11
  /** Warned once when no model gives the character a body */
12
12
  export const NO_CHARACTER = 'characters: no model given, so characters are gray capsules (a placeholder). Character bodies are assets: '
13
- + "register a pack's models (engine.assets.manifest(yourAssets)) and pass createPlayer({ model: 'yourBody' }), "
13
+ + "register a pack's models (engine.assets.manifest(yourAssets)) and pass addPlayer({ model: 'yourBody' }), "
14
14
  + "a GLB asset name ({ model: 'hero' }), or a ready body ({ rig })";
15
15
 
16
16
  /**
@@ -23,7 +23,7 @@ export function rigFromObject(root) {
23
23
  if (!d) return null;
24
24
  const get = n => {
25
25
  const o = n ? root.getObjectByName(n) : null;
26
- if (n && !o) warnOnce(`character model "${root.name || 'model'}": userData.rig names "${n}", but the model has no object with that name`);
26
+ if (n && !o) warnOnce(`character model "${root.name || 'model'}": userData.rig names "${n}", but the model has no object with that name. Change the name in root.userData.rig to an existing descendant's name, or rename that object in the model; check with root.getObjectByName(name)`);
27
27
  return o || null;
28
28
  };
29
29
  const joints = {};
@@ -41,7 +41,7 @@ export function tintParts(root, colors) {
41
41
  root.traverse(o => {
42
42
  const c = o.isMesh ? colors[o.userData.part] : null;
43
43
  if (c == null || !o.material?.color) return;
44
- o.material = copyPatches(o.material, o.material.clone()); o.material.color.set(c); // the tinted copy keeps wind / cloud / pack shader patches
44
+ o.material = cloneMaterial(o.material); o.material.color.set(c); // the tinted copy keeps wind / cloud / pack shader patches
45
45
  });
46
46
  }
47
47
 
@@ -51,7 +51,7 @@ export const capsuleDefault = () => neutralMaterial('character', { color: 0x8a8a
51
51
  /** A capsule's material: the shared one, or a copy of it in the character's own color (a material without .color has nothing to tint) @internal */
52
52
  export function capsuleMaterial(base, color) {
53
53
  if (color == null) return base;
54
- const m = copyPatches(base, base.clone());
54
+ const m = cloneMaterial(base);
55
55
  m.color?.set(color);
56
56
  if (isEngineMade(base)) markEngineMade(m);
57
57
  return m;
@@ -2,6 +2,7 @@
2
2
  // Split out of Character.js; Character._useModel calls it.
3
3
  import { warnOnce } from '../../core/base/validate.js';
4
4
  import { findClip } from '../../core/assets/Animator.js';
5
+ import { standAt } from './movers/support.js';
5
6
 
6
7
  const DEFAULT_CLIPS = { idle: 'Idle', walk: 'Walk', run: 'Run', swim: 'Swim', jump: 'Jump', fall: 'Fall', drive: 'Drive' };
7
8
 
@@ -18,5 +19,10 @@ export function useModel(ch, model, clips, animation) {
18
19
  for (const [st, clip] of Object.entries(clips || {})) states[st] = { clip };
19
20
  // the model's own mapping (fade, transitions) beats characters({ animation }), the default for every character; the game's per-character config beats both
20
21
  ch.anim = engine.assets.animate(model, { ...engine.characters?._animation, ...map, states, ...(animation || {}) });
22
+ ch.anim._rate = () => engine.time.scale(ch.channel, ch.id); // the character's time channel (bullet time, time.local) slows clips, fades and IK too, as it does the walk cycle
21
23
  ch.anim.afterPose = dt => ch._firePose(dt); // a mixer pose is applied inside the Animator's update, so the Animator tells us when it is done
24
+ // feet (anim.addFeet) stand where the character walks: the ground with its platforms; off while it jumps or swims (asked before any ground query)
25
+ const at = { y: 0, on: null };
26
+ ch.anim._ground = (x, z, y) => standAt(engine, x, z, y, ch.stepHeight, at, true).y;
27
+ ch.anim._standing = () => ch.grounded && !ch.swimming;
22
28
  }
@@ -35,7 +35,7 @@ export function walkTo(ch, target, { speed, arrive = 0.5, turnRate = 8, stuckSec
35
35
  };
36
36
  function finishMods() { sped?.remove(); runMod?.remove(); }
37
37
  const solve = () => {
38
- path = e.characters.findPath(ch.root.position, target, { radius: ch.radius, id: ch.id });
38
+ path = e.characters.findPath(ch.root.position, target, { radius: ch.radius, passes: ch.passes, id: ch.id });
39
39
  i = 0; bestD = Infinity; stuckT = 0;
40
40
  return !!path?.length;
41
41
  };