threedog 0.8.0 → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (372) hide show
  1. package/CHANGELOG.md +219 -4
  2. package/README.md +6 -6
  3. package/core/assets/Animator.js +2 -0
  4. package/core/assets/Assets.js +44 -13
  5. package/core/assets/assetEntry.js +87 -22
  6. package/core/assets/assetHot.js +2 -1
  7. package/core/assets/assetReport.js +1 -2
  8. package/core/audio/Audio.js +24 -5
  9. package/core/base/I18n.js +6 -3
  10. package/core/base/Random.js +3 -1
  11. package/core/base/Vars.js +14 -4
  12. package/core/base/errorCodes.js +54 -16
  13. package/core/base/errorHints.js +12 -1
  14. package/core/base/errors.js +6 -4
  15. package/core/base/events.generated.js +10 -0
  16. package/core/base/follows.js +26 -0
  17. package/core/base/math.js +15 -8
  18. package/core/base/params.js +2 -2
  19. package/core/{saves → base}/saveValues.js +24 -6
  20. package/core/base/sections.js +97 -0
  21. package/core/base/spelling.js +32 -0
  22. package/core/base/validate.js +8 -29
  23. package/core/engine/Engine.js +61 -18
  24. package/core/engine/Loading.js +30 -3
  25. package/core/engine/copies.js +1 -1
  26. package/core/engine/headlessLoad.js +30 -13
  27. package/core/engine/lifecycle.js +30 -25
  28. package/core/engine/loop.js +22 -4
  29. package/core/engine/moduleSlots.js +91 -15
  30. package/core/engine/moduleTypes.js +13 -0
  31. package/core/engine/modules.js +248 -62
  32. package/core/engine/page.js +25 -8
  33. package/core/engine/plugins.js +15 -3
  34. package/core/engine/services.js +3 -0
  35. package/core/engine/startup.js +46 -36
  36. package/core/input/Input.js +39 -19
  37. package/core/input/inputKeyboard.js +39 -0
  38. package/core/input/inputPad.js +23 -2
  39. package/core/input/inputPointer.js +3 -1
  40. package/core/input/inputSeat.js +66 -0
  41. package/core/input/inputTouch.js +23 -6
  42. package/core/inspect/DebugOverrides.js +13 -2
  43. package/core/inspect/Describe.js +10 -6
  44. package/core/inspect/Inspect.js +31 -4
  45. package/core/inspect/UrlState.js +14 -10
  46. package/core/inspect/catalog.js +12 -5
  47. package/core/inspect/describeRender.js +3 -2
  48. package/core/inspect/describeText.js +6 -2
  49. package/core/inspect/metadata.generated.js +4140 -0
  50. package/core/inspect/pictureWriters.js +117 -33
  51. package/core/inspect/toolDoor.js +21 -0
  52. package/core/inspect/valueHistory.js +35 -0
  53. package/core/ops/Ops.js +32 -7
  54. package/core/ops/control.js +48 -23
  55. package/core/ops/holds.js +4 -3
  56. package/core/ops/opsAtomic.js +18 -6
  57. package/core/ops/opsCheck.js +7 -5
  58. package/core/ops/opsFail.js +5 -7
  59. package/core/ops/opsRun.js +2 -2
  60. package/core/ops/owned.js +20 -3
  61. package/core/ops/sharedPoint.js +7 -10
  62. package/core/ops/stacks.js +22 -1
  63. package/core/saves/SaveStore.js +52 -26
  64. package/core/saves/Saves.js +122 -27
  65. package/core/saves/saveApply.js +159 -61
  66. package/core/saves/saveFiles.js +30 -25
  67. package/core/saves/saveVersions.js +20 -6
  68. package/core/saves/session.js +76 -33
  69. package/core/saves/stateReplace.js +184 -0
  70. package/core/scene/Rays.js +21 -5
  71. package/core/scene/Views.js +6 -6
  72. package/core/scene/adaptive.js +13 -10
  73. package/core/scene/canvasBox.js +2 -0
  74. package/core/scene/compositeGround.js +72 -0
  75. package/core/scene/floor.js +17 -0
  76. package/core/scene/grid.js +2 -0
  77. package/core/scene/ground.contract.js +14 -0
  78. package/core/scene/ground.js +52 -17
  79. package/core/scene/pixel.js +154 -0
  80. package/core/scene/pixelRatio.js +167 -0
  81. package/core/scene/sceneDelta.js +3 -3
  82. package/core/scene/sceneMethods.js +11 -6
  83. package/core/scene/stepPoses.js +6 -1
  84. package/core/scene/thingExplain.js +1 -1
  85. package/core/scene/thingOps.js +22 -14
  86. package/core/scene/things.js +1 -1
  87. package/core/scene/tier.js +10 -0
  88. package/core/scene/view.js +126 -9
  89. package/core/stream/Batching.js +0 -1
  90. package/core/stream/Stream.js +24 -12
  91. package/core/stream/batchGroups.js +1 -0
  92. package/core/stream/scatter.js +5 -2
  93. package/core/stream/streamSources.js +2 -1
  94. package/core/threads/Commits.js +12 -7
  95. package/core/threads/Jobs.js +15 -5
  96. package/core/threads/Threads.js +5 -2
  97. package/core/time/Clock.js +3 -1
  98. package/core/time/skip.js +10 -4
  99. package/core/time/time.js +16 -10
  100. package/docs/AI.md +89 -72
  101. package/docs/API.md +18 -14
  102. package/docs/CODEMAP.md +68 -40
  103. package/docs/COMMANDS.md +22 -23
  104. package/docs/CONVENTIONS.md +120 -17
  105. package/docs/MIGRATING-0.8.md +2 -0
  106. package/docs/MIGRATING-1.0.md +101 -0
  107. package/docs/THREE.md +65 -12
  108. package/docs/api/cameraRig.md +3 -0
  109. package/docs/api/characters.md +13 -7
  110. package/docs/api/collider3d.md +9 -0
  111. package/docs/api/content.md +16 -15
  112. package/docs/api/dialogue.md +2 -1
  113. package/docs/api/engine.md +18 -16
  114. package/docs/api/events.md +14 -4
  115. package/docs/api/ground.md +2 -2
  116. package/docs/api/i18n.md +1 -1
  117. package/docs/api/input.md +2 -1
  118. package/docs/api/interactions.md +1 -1
  119. package/docs/api/inventory.md +1 -1
  120. package/docs/api/level.md +3 -2
  121. package/docs/api/nav.md +4 -2
  122. package/docs/api/particles.md +8 -5
  123. package/docs/api/pickups.md +1 -1
  124. package/docs/api/post.md +3 -4
  125. package/docs/api/quests.md +4 -2
  126. package/docs/api/rays.md +2 -0
  127. package/docs/api/rigid.md +3 -2
  128. package/docs/api/saves.md +8 -7
  129. package/docs/api/stream.md +4 -5
  130. package/docs/api/terrain.md +3 -4
  131. package/docs/api/terrainDraw.md +1 -1
  132. package/docs/api/timeline.md +2 -2
  133. package/docs/api/tools.md +3 -1
  134. package/docs/api/triggers.md +2 -0
  135. package/docs/api/vegetationDraw.md +1 -1
  136. package/docs/api/water.md +6 -2
  137. package/docs/api/weather.md +19 -4
  138. package/docs/api/weatherDraw.md +1 -1
  139. package/docs/api/world.md +1 -1
  140. package/docs/recipes/01-new-game.md +3 -3
  141. package/docs/recipes/02-npc.md +3 -4
  142. package/docs/recipes/03-items-pickups.md +11 -11
  143. package/docs/recipes/04-quests.md +2 -0
  144. package/docs/recipes/05-props-bake.md +9 -9
  145. package/docs/recipes/06-clock-events.md +6 -6
  146. package/docs/recipes/07-flow-scenes-pause.md +18 -15
  147. package/docs/recipes/08-weather-sky.md +5 -5
  148. package/docs/recipes/09-materials-lights-models.md +3 -3
  149. package/docs/recipes/10-blender-level.md +16 -4
  150. package/docs/recipes/11-vehicles.md +18 -6
  151. package/docs/recipes/12-navmesh.md +52 -8
  152. package/docs/recipes/13-animation.md +34 -8
  153. package/docs/recipes/14-custom-module.md +20 -8
  154. package/docs/recipes/15-perf.md +4 -4
  155. package/docs/recipes/16-dev-bridge.md +9 -8
  156. package/docs/recipes/18-world.md +13 -5
  157. package/docs/recipes/19-shooting-picking.md +3 -2
  158. package/docs/recipes/20-content-actions-save.md +26 -6
  159. package/docs/recipes/21-camera.md +17 -23
  160. package/docs/recipes/22-shop-gold.md +21 -12
  161. package/docs/recipes/23-ops.md +19 -15
  162. package/docs/recipes/26-ui-parts.md +3 -2
  163. package/docs/recipes/27-net.md +3 -3
  164. package/docs/recipes/28-terrain.md +3 -3
  165. package/docs/recipes/29-grid.md +1 -1
  166. package/docs/recipes/30-templates.md +10 -13
  167. package/docs/recipes/31-audio.md +2 -2
  168. package/docs/recipes/32-action-game.md +6 -5
  169. package/docs/recipes/33-stream-sources.md +4 -1
  170. package/docs/recipes/34-environment-lighting.md +7 -8
  171. package/docs/recipes/35-picture-from-reference.md +13 -9
  172. package/docs/recipes/36-ground-plants.md +3 -2
  173. package/docs/recipes/40-scene.md +11 -10
  174. package/docs/recipes/43-shader-patches-surfaces.md +7 -7
  175. package/docs/recipes/44-water-weather-hooks.md +9 -8
  176. package/docs/recipes/45-cascaded-shadows.md +3 -4
  177. package/docs/recipes/46-blender-art-route.md +3 -3
  178. package/docs/recipes/49-game-module-contract.md +2 -1
  179. package/docs/recipes/50-own-renderer.md +1 -0
  180. package/docs/recipes/51-capability-catalog.md +14 -8
  181. package/docs/recipes/52-around-the-picture.md +4 -4
  182. package/docs/recipes/55-mods-time-wrap.md +5 -4
  183. package/docs/recipes/56-webgpu-tsl.md +12 -1
  184. package/docs/recipes/57-control.md +30 -10
  185. package/docs/recipes/58-input.md +13 -0
  186. package/docs/recipes/60-judge-the-picture.md +1 -1
  187. package/docs/recipes/62-picture-code.md +106 -48
  188. package/docs/recipes/63-third-person-start.md +2 -1
  189. package/docs/recipes/64-particles.md +53 -4
  190. package/docs/recipes/65-swarm.md +2 -2
  191. package/docs/recipes/66-common-tasks.md +313 -0
  192. package/examples/action/.threedog/content-index.json +1 -1
  193. package/examples/action/GAMEMAP.md +3 -3
  194. package/examples/perf-island/.threedog/content-index.json +1 -1
  195. package/examples/perf-island/GAMEMAP.md +3 -3
  196. package/examples/perf-island/main.js +2 -2
  197. package/examples/plain-picture/GAMEMAP.md +3 -1
  198. package/examples/rc2d/GAMEMAP.md +1 -1
  199. package/examples/rc2d/rc2d.js +1 -1
  200. package/examples/styletest/.threedog/content-index.json +1 -1
  201. package/examples/styletest/GAMEMAP.md +3 -3
  202. package/examples/webgpu-tsl/GAMEMAP.md +1 -1
  203. package/examples/world/.threedog/content-index.json +1 -1
  204. package/examples/world/GAMEMAP.md +5 -4
  205. package/examples/world/main.js +3 -3
  206. package/index.d.ts +8 -5
  207. package/index.js +22 -1
  208. package/llms.txt +2 -1
  209. package/modules/ambience/Ambience.js +5 -3
  210. package/modules/calendar/index.js +7 -5
  211. package/modules/camera/FirstPersonCamera.js +3 -3
  212. package/modules/camera/FixedCamera.js +34 -20
  213. package/modules/camera/FollowCamera.js +20 -11
  214. package/modules/camera/RtsCamera.js +1 -0
  215. package/modules/camera/common.js +33 -22
  216. package/modules/camera/pixelSnap.js +62 -0
  217. package/modules/characters/Character.js +136 -43
  218. package/modules/characters/NPC.js +60 -28
  219. package/modules/characters/assetModel.js +2 -2
  220. package/modules/characters/astar.js +47 -28
  221. package/modules/characters/character.contract.js +21 -0
  222. package/modules/characters/contract.js +17 -3
  223. package/modules/characters/index.js +94 -34
  224. package/modules/characters/moveHelpers.js +80 -15
  225. package/modules/characters/mover.contract.js +14 -0
  226. package/modules/characters/movers/common.js +6 -4
  227. package/modules/characters/movers/rapier.js +12 -5
  228. package/modules/characters/movers/simple.js +25 -12
  229. package/modules/characters/movers/support.js +18 -7
  230. package/modules/characters/npcAvoid.js +15 -12
  231. package/modules/characters/npcSim.js +75 -25
  232. package/modules/characters/npcView.js +13 -6
  233. package/modules/characters/pathAsync.js +74 -24
  234. package/modules/characters/pathJob.js +38 -21
  235. package/modules/characters/player.js +59 -47
  236. package/modules/characters/seat.js +56 -0
  237. package/modules/characters/vehicle.contract.js +8 -5
  238. package/modules/characters/walkTo.js +31 -18
  239. package/modules/collision/Collision.js +44 -26
  240. package/modules/collision/contract.js +2 -2
  241. package/modules/collision/grid.js +6 -1
  242. package/modules/content/explain.js +1 -1
  243. package/modules/content/fields.js +3 -3
  244. package/modules/content/ids.js +3 -1
  245. package/modules/content/index.js +83 -27
  246. package/modules/content/loader.js +110 -130
  247. package/modules/content/markers.js +1 -1
  248. package/modules/content/models.js +48 -14
  249. package/modules/content/packs.js +2 -1
  250. package/modules/content/places.js +5 -4
  251. package/modules/content/props.js +8 -6
  252. package/modules/content/rules.js +29 -47
  253. package/modules/content/templates.js +66 -35
  254. package/modules/content/words.js +19 -6
  255. package/modules/debug/DebugPanel.js +4 -2
  256. package/modules/flow/contract.js +1 -0
  257. package/modules/flow/index.js +24 -14
  258. package/modules/gameplay/Container.js +5 -2
  259. package/modules/gameplay/Containers.js +9 -1
  260. package/modules/gameplay/Dialogue.js +82 -25
  261. package/modules/gameplay/Interactions.js +61 -32
  262. package/modules/gameplay/Inventory.js +56 -13
  263. package/modules/gameplay/Quests.js +133 -24
  264. package/modules/gameplay/boxOps.js +7 -0
  265. package/modules/gameplay/dialogueBubbles.js +14 -9
  266. package/modules/gameplay/inventoryOps.js +11 -7
  267. package/modules/gameplay/pickups.js +43 -16
  268. package/modules/gameplay/questLog.js +4 -2
  269. package/modules/gameplay/questSave.js +6 -1
  270. package/modules/gameplay/quests.contract.js +1 -1
  271. package/modules/grid/Grid.js +1 -1
  272. package/modules/grid/Layer.js +8 -4
  273. package/modules/grid/index.js +21 -15
  274. package/modules/grid/ops.js +43 -46
  275. package/modules/grid/tiles.js +1 -1
  276. package/modules/hlod/index.js +6 -3
  277. package/modules/hud/index.js +6 -4
  278. package/modules/hud/parts.js +4 -4
  279. package/modules/level/contract.js +2 -2
  280. package/modules/level/heightfield.js +17 -21
  281. package/modules/level/index.js +83 -26
  282. package/modules/level/load.js +165 -48
  283. package/modules/level/nodes.js +34 -16
  284. package/modules/lights/index.js +6 -3
  285. package/modules/lights/sources.js +3 -1
  286. package/modules/music/Music.js +4 -2
  287. package/modules/nav/contract.js +7 -5
  288. package/modules/nav/index.js +174 -44
  289. package/modules/nav/navPath.js +45 -10
  290. package/modules/net/index.js +1 -1
  291. package/modules/particles/Particles.js +85 -22
  292. package/modules/particles/effect.js +80 -28
  293. package/modules/particles/shaders.js +17 -0
  294. package/modules/photo/Photo.js +12 -10
  295. package/modules/rigid/RigidBodies.js +200 -57
  296. package/modules/rigid/Vehicles.js +15 -5
  297. package/modules/rigid/collider3d.contract.js +26 -0
  298. package/modules/rigid/ragdoll.js +55 -44
  299. package/modules/rigid/ragdollBones.js +83 -33
  300. package/modules/rigid/refresh.js +10 -0
  301. package/modules/rigid/sync.js +46 -15
  302. package/modules/settings/Settings.js +84 -37
  303. package/modules/settings/apply.js +15 -8
  304. package/modules/settings/sections.js +7 -4
  305. package/modules/settings/strings.js +2 -2
  306. package/modules/sky/skyModule.js +3 -1
  307. package/modules/swarm/Swarm.js +16 -6
  308. package/modules/terrain/ChunkManager.js +10 -16
  309. package/modules/terrain/index.js +17 -11
  310. package/modules/terrain/terrainEdit.js +13 -2
  311. package/modules/terrain/terrainGen.js +5 -3
  312. package/modules/terrain/terrainShape.js +1 -1
  313. package/modules/timeline/Timeline.js +58 -26
  314. package/modules/timeline/Tween.js +19 -13
  315. package/modules/timeline/shots.js +19 -10
  316. package/modules/triggers/index.js +87 -20
  317. package/modules/vegetation/Vegetation.js +4 -3
  318. package/modules/vegetation/draw.js +16 -0
  319. package/modules/vegetation/groundChunks.js +10 -7
  320. package/modules/vegetation/index.js +30 -7
  321. package/modules/water/Water.js +6 -2
  322. package/modules/weather/Weather.js +16 -15
  323. package/modules/weather/weatherDraw.js +7 -6
  324. package/modules/world/World.js +20 -7
  325. package/modules/world/explain.js +1 -1
  326. package/modules/world/index.js +13 -6
  327. package/modules/world/persist.js +23 -8
  328. package/modules/world/pos.js +4 -4
  329. package/modules/world/records.js +13 -7
  330. package/modules/world/sim.js +74 -23
  331. package/modules/world/simFar.js +2 -2
  332. package/modules/world/state.js +31 -6
  333. package/modules/world/thingSource.js +16 -3
  334. package/modules/world/views.js +19 -8
  335. package/package.json +7 -1
  336. package/render/PostFX.js +47 -29
  337. package/render/backend.js +5 -1
  338. package/render/fx/particles.tsl.js +8 -6
  339. package/render/fx/postWebGPU.tsl.js +3 -3
  340. package/render/layers.js +1 -1
  341. package/render/lightmap.js +23 -3
  342. package/render/occlusion.js +43 -12
  343. package/render/patches.js +2 -2
  344. package/render/postWebGL.js +4 -3
  345. package/render/probes.js +25 -0
  346. package/render/shadows.js +2 -2
  347. package/types/core.d.ts +142 -55
  348. package/types/gameplay.d.ts +92 -40
  349. package/types/generated/core/base/I18n.d.ts +2 -2
  350. package/types/generated/core/input/Input.d.ts +16 -2
  351. package/types/generated/core/input/inputSeat.d.ts +26 -0
  352. package/types/generated/core/inspect/DebugOverrides.d.ts +15 -1
  353. package/types/generated/core/ops/Ops.d.ts +2 -1
  354. package/types/generated/core/ops/control.d.ts +12 -2
  355. package/types/generated/core/saves/Saves.d.ts +26 -6
  356. package/types/generated/core/saves/session.d.ts +1 -1
  357. package/types/generated/core/scene/Views.d.ts +1 -1
  358. package/types/generated/core/stream/Stream.d.ts +6 -4
  359. package/types/generated/modules/grid/Grid.d.ts +1 -0
  360. package/types/generated/modules/particles/Particles.d.ts +4 -3
  361. package/types/generated/modules/timeline/Timeline.d.ts +5 -4
  362. package/types/generated/modules/weather/Weather.d.ts +1 -7
  363. package/types/generated/modules/world/World.d.ts +6 -4
  364. package/types/generated/render/PostFX.d.ts +6 -14
  365. package/types/nav.d.ts +36 -4
  366. package/types/physics.d.ts +55 -7
  367. package/types/pixel.d.ts +75 -0
  368. package/types/world.d.ts +14 -8
  369. package/ui/Parts.js +9 -2
  370. package/ui/theme.js +2 -2
  371. package/core/scene/engineCamera.js +0 -32
  372. package/modules/camera/projection.js +0 -21
@@ -1,10 +1,12 @@
1
- // What any navmesh module must provide (fields: see gameplay/inventory.contract.js; shared check: @threedog/tools/contract).
2
- // Exactly what other code reads from engine.nav: findPath (characters, once ready is true), reach(radius) and exportMesh() (the path worker), crowd (NPC steering;
3
- // null: NPCs steer on their own), query (the path solver), version / revision (a new mesh / a changed one: caches drop on them).
1
+ // What a module in the nav slot must provide (fields: see gameplay/inventory.contract.js; shared check: @threedog/tools/contract).
2
+ // The slot does not swap the navigation library: navSearch (navPath.js) calls Recast's findPath and findStraightPath on query and getOffMeshConnectionByRef on navMesh, characters/pathJob.js gives exportMesh()'s bytes to Recast's importNavMesh,
3
+ // and NPC steering calls addAgent on crowd. A replacement is Recast underneath.
4
+ // Exactly what other code reads from engine.nav: findPath (characters, once ready is true), point(p) (the surface nearest the caller's height there, the ground when none is given), reach(radius), mesh(radius) (the mesh cut for that body), meshes and exportMesh(mesh) (the path worker), crowd (NPC steering;
5
+ // null: NPCs steer on their own), query (the path solver), version / revision (a new mesh / a changed one: caches of this module drop on them; they count per module, so another nav says nothing by its number).
4
6
  export default {
5
7
  name: 'nav',
6
- api: ['findPath', 'reach', 'exportMesh'],
7
- fields: ['ready', 'crowd', 'query', 'version', 'revision'],
8
+ api: ['findPath', 'point', 'reach', 'mesh', 'exportMesh'],
9
+ fields: ['ready', 'crowd', 'query', 'navMesh', 'links', 'meshes', 'version', 'revision'],
8
10
  ops: [],
9
11
  events: [],
10
12
  saves: {},
@@ -1,35 +1,55 @@
1
1
  // Navmesh (Recast): generated after a level loads; engine.characters.findPath switches to it automatically (falls back to A* when not installed).
2
2
  // engine.use(level({ url }), collision(), characters(), nav({ agentRadius: 0.4 }));
3
3
  // Once installed, engine.nav offers findPath(from, to) and the native objects navMesh / query / tileCache / crowd / helper.
4
- // version: +1 on every rebuild / unload. Native objects (crowd agents etc.) are destroyed on rebuild; code that cached them must compare version and re-fetch when it changed (NPCs do this).
4
+ // version: +1 on every rebuild / unload. Native objects (crowd agents etc.) are destroyed on rebuild; code that cached them keeps the object and compares it (NPCs compare crowd): version counts per module, so a replaced nav can show the same number.
5
5
  //
6
6
  // Where the mesh comes from: the ground API's staticTrimeshes() (the level's walkable mesh).
7
7
  // Walls and obstacles: boxes/circles in the collision module (level col_ boxes, ones added by game collision.addBox) are all synced into TileCache dynamic obstacles,
8
8
  // and affected tiles are rebuilt on add/remove, so level walls and later-added obstacles work the same way.
9
- // Levels only for now (ground with staticTrimeshes); procedural terrain keeps using A*. Recast (about 1MB) is downloaded only at init.
9
+ // Levels only for now (ground with staticTrimeshes); procedural terrain keeps using A*. Recast (728 KB, 218 KB gzipped) starts loading when nav() is installed.
10
10
  // The mesh is built once per level: ground edits (engine.terrain.edit, 'ground:change') do not update it, so paths keep following the ground as it was
11
11
  // at level load (rebuilding all tiles per edit is too slow to do automatically). A game that reshapes walkable ground at runtime leaves nav out:
12
12
  // characters.findPath then uses A*, which resamples the edited area (its rasters are dropped on 'ground:change').
13
+ // Body sizes: Recast bakes the body's radius into the mesh, so a mesh is good for one size (Recast's own advice, and what Unreal's supported agents do: one mesh per size).
14
+ // api itself is the mesh of agentRadius; a findPath for another radius gets its own, built the first time that size is asked for and kept in api.meshes until the next rebuild or unload.
15
+ // Radii that round to the same cells share one. Each has its own tile cache, obstacles and seated links; revision covers them all, and a game with one size pays for nothing else.
16
+ // shortcut: built on the main thread when first asked for, which stalls that step; move to a worker (or a list of sizes built at load) if a real level's build shows up in a frame.
17
+ // Links (Recast off-mesh connections): nav({ links: [{ id, from, to }] }) joins two places a walker cannot walk between, a gap to jump or a ladder to climb.
18
+ // generateTileCache has no offMeshConnections option (generateTiledNavMesh does), so they go in through the tile cache's mesh process, which Detour runs for
19
+ // every tile it builds: a tile rebuilt around an obstacle gets them back the same way. They live in the tile data, so exportMesh carries them to the path worker.
13
20
  import { readParams, keysSchema } from '../../core/base/params.js';
14
- import { xzOf } from '../../core/base/math.js';
15
- import { navSearch } from './navPath.js';
21
+ import { xzOf, yOf } from '../../core/base/math.js';
22
+ import { follows } from '../../core/base/follows.js';
23
+ import { navSearch, OPTS } from './navPath.js';
24
+ import { sameFloor } from '../../core/scene/floor.js';
16
25
  import { warnOnce } from '../../core/base/validate.js';
17
- import { coded } from '../../core/base/errorHints.js';
26
+ import { coded, codedError } from '../../core/base/errorHints.js';
18
27
 
19
- const NAV_PARAMS = keysSchema(['cellSize', 'agentRadius', 'agentHeight', 'maxClimb', 'maxSlope', 'tileSize', 'crowd', 'debug', 'maxObstacles', 'maxAgents', 'arrive']);
28
+ const NAV_PARAMS = keysSchema(['cellSize', 'agentRadius', 'agentHeight', 'maxClimb', 'maxSlope', 'tileSize', 'crowd', 'debug', 'maxObstacles', 'maxAgents', 'arrive', 'links']);
29
+ const LINK_PARAMS = keysSchema(['id', 'from', 'to', 'oneWay', 'radius']);
30
+ const ANY_FLOOR = { halfExtents: { ...OPTS.halfExtents, y: 1e4 } }; // the search's reach sideways, every floor up and down: what stands at this spot, however far the height given is
31
+ const BASE = 'agent'; // the size of the mesh cut for agentRadius, which is api itself: cells alone can't name it, a wider body in the same cells needs more room round an obstacle
32
+ const NO_LINK = -1; // Detour's DT_NULL_LINK, the end of a polygon's link list: 0xffffffff in C++, but the wrapper reads it back signed
20
33
 
21
34
  export function nav(opts = {}) {
22
35
  readParams('nav', NAV_PARAMS, opts);
23
36
  // maxObstacles / maxAgents: Recast's fixed capacities (a city of 3000 wall pieces needs more than a village; a crowd scene more than 128 agents).
24
37
  // arrive: meters past the character's radius a path may end short of its goal and still count as arrived (a ledge-strict platformer wants less)
25
- const { cellSize = 0.3, tileSize = 32, crowd = false, debug = false, maxObstacles = 1024, maxAgents = 128, arrive = 0.6 } = opts;
38
+ const { cellSize = 0.3, tileSize = 32, crowd = false, debug = false, maxObstacles = 1024, maxAgents = 128, arrive = 0.6, links = [] } = opts;
39
+ for (const l of links) readParams('nav links', LINK_PARAMS, l);
26
40
  // agent size defaults come from engine.movement (filled at install); opts values override them
27
41
  let agentRadius, agentHeight, maxClimb, maxSlope;
42
+ let revision = 0;
28
43
  let e = null, lib = null, gen = null, pending = false, wasm = null; // wasm: the recast import + init begun at install
29
- let obstacles = null; // engine.collision.mirror: collision-module collider -> its Recast obstacles (big boxes are cut into several pieces)
44
+ const processes = new Map(); // size -> what runs for every tile built, with links only: without them the generator's default is the same thing
45
+ const cellsOf = r => Math.ceil(+(r / cellSize).toFixed(6)); // rounded first: 0.9 / 0.3 is a hair over 3
30
46
 
31
47
  const api = {
32
- ready: false, agent: null, navMesh: null, query: null, tileCache: null, crowd: null, helper: null,
48
+ ready: false, agent: null, links: [], navMesh: null, query: null, tileCache: null, crowd: null, helper: null,
49
+ /** @internal this mesh's body: its size in api.meshes, walkableRadius in cells, the radius obstacles are grown by; obstacles: engine.collision.mirror, collider -> its Recast obstacles (big boxes are cut into several pieces), of the collision module obstaclesOf. A mesh of another size has these too */
50
+ size: BASE, cells: 0, radius: 0, obstacles: null, obstaclesOf: follows(() => e?.collision ?? null),
51
+ /** @internal size -> mesh ({ query, navMesh, links, ... }), this one included: async pathfinding looks a batch's mesh up here */
52
+ meshes: new Map(),
33
53
  /** +1 on rebuild / unload: code that cached native objects such as crowd agents must re-create them when it changes */
34
54
  version: 0,
35
55
  /**
@@ -37,29 +57,55 @@ export function nav(opts = {}) {
37
57
  * Pass { detailed: true } to get { status: 'ok' | 'noPath' | 'notReady', path } instead: tells "navmesh not generated yet" from "generated but unreachable"
38
58
  */
39
59
  findPath(from, to, o = {}) {
60
+ syncObstacles();
40
61
  const res = search(from, to, o);
41
62
  return o.detailed ? res : res.path;
42
63
  },
43
64
  /** @internal +1 whenever the walkable mesh changes (rebuild, unload, obstacle sync): async pathfinding re-sends the mesh to its workers and redoes answers computed on an older one */
44
- revision: 0,
45
- /** @internal the current mesh as bytes, imported by the pathfinding worker */
46
- exportMesh() { return lib.exportNavMesh(api.navMesh); },
47
- /** @internal how far (m) a path may end short of its goal and still count as arriving, for a character of this radius */
65
+ /** Any walkable change. A read of it is a read of the mesh, so it syncs first: a frozen engine runs no step, and a cached path asks here */
66
+ get revision() { syncObstacles(); return revision; },
67
+ /** @internal a mesh as bytes, imported by the pathfinding worker */
68
+ exportMesh(m = api) { return lib.exportNavMesh(m.navMesh); },
69
+ /** @internal the mesh for a body of this radius, built the first time it is asked for; no radius: agentRadius. A mesh the build refused has no query, and every path on it is noPath */
70
+ mesh(radius = agentRadius) {
71
+ if (!(radius >= 0)) throw codedError('character-option', `nav: a path's radius is a number of meters, 0 or more, got ${radius}`);
72
+ const c = cellsOf(radius), size = c === api.cells && radius <= agentRadius ? BASE : c;
73
+ return api.meshes.get(size) ?? extraMesh(size);
74
+ },
75
+ /**
76
+ * @internal The one rule for a position given to the navmesh (search, links, async paths, crowd goals). No height: the ground. A height picks the nearest surface of the mesh at that
77
+ * spot, which is what tells the floors of a building apart, and the point lands on it: a crowd target looks only a little way up and down. A height farther than a body from
78
+ * every surface was not meant as a floor ([x, 0, z] on ground at 8), so it also warns. Before the mesh exists it stays as given; seatLinks asks again once it does.
79
+ * m: the mesh the point is for: a passage only a small body fits is on no other
80
+ */
81
+ point(p, m = api) {
82
+ syncObstacles();
83
+ const [x, z] = xzOf(p), y = yOf(p);
84
+ if (y === undefined) return { x, y: e.surface(x, z), z };
85
+ const near = m.query?.findNearestPoly({ x, y, z }, ANY_FLOOR);
86
+ if (!near?.success || !near.nearestRef) return { x, y, z };
87
+ const floor = near.nearestPoint.y, r = v => +v.toFixed(2);
88
+ if (!sameFloor(y, floor, e.movement.height)) warnOnce(coded('nav-height', `nav: height ${r(y)} at x ${r(x)}, z ${r(z)} is on no floor, so ${r(floor)} is used, the nearest walkable surface there`), 'nav-height');
89
+ return { x, y: floor, z };
90
+ },
91
+ /** @internal how far (m) a search may end from its goal for a body of this radius; the path search and the worker read it */
48
92
  reach(radius) { return (radius ?? agentRadius) + arrive; },
49
93
  /** Unload the navmesh (frees native objects); afterwards characters.findPath falls back to A* */
50
94
  dispose() {
51
- api.ready = false; api.version++; api.revision++;
95
+ api.ready = false; api.version++; revision++;
52
96
  if (api.helper) e.remove(api.helper); // the debug mesh is built by us: remove it completely
53
- api.crowd?.destroy(); api.tileCache?.destroy(); api.navMesh?.destroy(); api.query?.destroy();
97
+ api.crowd?.destroy();
98
+ for (const m of api.meshes.values()) { m.tileCache?.destroy(); m.navMesh?.destroy(); m.query?.destroy(); }
54
99
  Object.assign(api, { navMesh: null, query: null, tileCache: null, crowd: null, helper: null });
55
- obstacles?.clear();
100
+ api.obstacles?.clear();
101
+ api.meshes.clear(); api.meshes.set(BASE, api);
56
102
  },
57
103
  };
58
104
 
59
105
  function search(from, to, o) {
60
106
  if (!api.ready) return { status: 'notReady', path: null };
61
- const [sx, sz] = xzOf(from), [gx, gz] = xzOf(to);
62
- return navSearch(api.query, { x: sx, y: e.surface(sx, sz), z: sz }, { x: gx, y: e.surface(gx, gz), z: gz }, api.reach(o.radius));
107
+ const m = api.mesh(o.radius);
108
+ return navSearch(m, api.point(from, m), api.point(to, m), api.reach(o.radius), e.movement.height);
63
109
  }
64
110
 
65
111
  /** Walkable triangle mesh of the ground (world coordinates), merged into one */
@@ -74,36 +120,106 @@ export function nav(opts = {}) {
74
120
  return { positions, indices };
75
121
  }
76
122
 
77
- async function build() {
78
- pending = false;
79
- if (api.ready) api.dispose();
80
- const { positions, indices } = geometry();
81
- if (!indices.length) return;
123
+ /** The links with their ends in 3D (a y left out is the ground there) and the catch radius: the mesh stops the agent radius, rounded up to cells, plus up to a cell short of an edge, and a ladder stands a little off that edge */
124
+ function placeLinks(m) {
125
+ return links.map((l, i) => ({ id: l.id ?? i, from: api.point(l.from, m), to: api.point(l.to, m), oneWay: !!l.oneWay, radius: l.radius ?? m.radius + cellSize * 3 }));
126
+ }
127
+ /**
128
+ * The mesh process with the links that start in the tile being built. Detour keeps a connection only in its start's tile, and the wrapper's copy of the list
129
+ * is never freed (nothing runs after this callback), so passing only those keeps that to a few bytes per link instead of the whole list for every tile.
130
+ */
131
+ function linkProcess(size) {
132
+ if (!processes.has(size)) processes.set(size, new lib.TileCacheMeshProcess((params, areas, flags) => {
133
+ for (let i = 0; i < params.polyCount(); i++) { areas.set(i, 0); flags.set(i, 1); }
134
+ const raw = params.raw, inside = (v, a) => v >= raw.get_bmin(a) && v < raw.get_bmax(a), mine = [];
135
+ api.meshes.get(size).links.forEach((l, i) => { if (inside(l.from.x, 0) && inside(l.from.z, 2)) mine.push({ startPosition: l.from, endPosition: l.to, radius: l.radius, bidirectional: !l.oneWay, userId: i }); });
136
+ params.setOffMeshConnections(mine);
137
+ }));
138
+ return processes.get(size);
139
+ }
140
+ /** The indexes of the links attached at both ends */
141
+ function joinedLinks(m) {
142
+ const mesh = m.navMesh, joined = new Set();
143
+ for (let t = 0; t < mesh.getMaxTiles(); t++) {
144
+ const tile = mesh.getTile(t), h = tile.header();
145
+ for (let i = 0; h && i < h.offMeshConCount(); i++) {
146
+ let ends = 0;
147
+ for (let k = tile.polys(h.offMeshBase() + i).firstLink(); (k | 0) !== NO_LINK; k = tile.links(k).next()) ends++;
148
+ if (ends >= 2) joined.add(tile.offMeshCons(i).userId());
149
+ }
150
+ }
151
+ return joined;
152
+ }
153
+ /** Where an end meets the ground it reaches: on that ground and inside its tile (a tile's far edge belongs to the next one), or the end as given when it reaches none */
154
+ function seat(m, p, radius) {
155
+ const near = m.query.findNearestPoly(p, { halfExtents: { x: radius, y: maxClimb, z: radius } });
156
+ if (!near.success || !near.nearestRef) return p;
157
+ const h = m.navMesh.getTileAndPolyByRef(near.nearestRef).tile.header(), { x, y, z } = near.nearestPoint, pad = cellSize / 4;
158
+ const within = (v, axis) => Math.min(Math.max(v, h.bmin(axis) + pad), h.bmax(axis) - pad);
159
+ return { x: within(x, 0), y, z: within(z, 2) };
160
+ }
161
+ /**
162
+ * Links on the finished mesh. Detour files an end under the tile its x, z fall in and looks for ground in that tile alone, so an end beside a tile's edge with its
163
+ * ground across the edge stays loose (a ladder under a deck that starts in the next tile), and a start in a tile with no ground is dropped. Each end moves onto its
164
+ * ground, and the tiles its start left and joined are rebuilt with it. m.links is then where walkers really step on and land, which a crowd NPC reads. On the ground
165
+ * an end needs no reach beyond a cell or two, so an obstacle standing on it cuts the link and does not leave it hooked to ground past the obstacle.
166
+ * A link Detour still could not attach at both ends does nothing, silently: say so once, at the build. Only for agentRadius: a ledge too narrow for a wide body is that body's limit, not the game's mistake.
167
+ */
168
+ function seatLinks(m) {
169
+ if (!m.links.length) return;
170
+ const tiles = new Map(), note = p => { const t = m.navMesh.calcTileLoc(p), x = t.tileX(), y = t.tileY(); tiles.set(`${x},${y}`, [x, y]); };
171
+ for (const l of m.links) { note(l.from); l.from = seat(m, api.point(l.from, m), l.radius); l.to = seat(m, api.point(l.to, m), l.radius); l.radius = cellSize * 2; note(l.from); }
172
+ for (const [x, y] of tiles.values()) m.tileCache.buildNavMeshTilesAt(x, y, m.navMesh);
173
+ if (m !== api) return;
174
+ const joined = joinedLinks(m);
175
+ m.links.forEach((l, i) => { if (!joined.has(i)) warnOnce(coded('nav-link', `nav: link "${l.id}" does not join the mesh at both ends, so no path uses it`)); });
176
+ }
177
+
178
+ /** Cut the mesh of m's body out of the ground; false when Recast refuses */
179
+ function cut(m, { positions, indices }) {
82
180
  const ch = cellSize / 2;
181
+ m.links = placeLinks(m);
83
182
  const r = gen.generateTileCache(positions, indices, {
84
- cs: cellSize, ch, tileSize, expectedLayersPerTile: 4, maxObstacles,
85
- walkableSlopeAngle: maxSlope, walkableHeight: Math.ceil(agentHeight / ch), walkableClimb: Math.ceil(maxClimb / ch), walkableRadius: Math.ceil(agentRadius / cellSize),
183
+ cs: cellSize, ch, tileSize, expectedLayersPerTile: 4, maxObstacles, tileCacheMeshProcess: links.length ? linkProcess(m.size) : undefined,
184
+ walkableSlopeAngle: maxSlope, walkableHeight: Math.ceil(agentHeight / ch), walkableClimb: Math.ceil(maxClimb / ch), walkableRadius: m.cells,
86
185
  });
87
- if (!r.success) { warnOnce(coded('nav-build', 'nav: ' + r.error)); return; }
88
- api.tileCache = r.tileCache; api.navMesh = r.navMesh;
89
- api.query = new lib.NavMeshQuery(r.navMesh);
90
- if (crowd) api.crowd = new lib.Crowd(r.navMesh, { maxAgents, maxAgentRadius: agentRadius * 2 });
91
- api.ready = true; api.version++; api.revision++;
186
+ if (!r.success) { warnOnce(coded('nav-build', 'nav: ' + r.error)); return false; }
187
+ m.tileCache = r.tileCache; m.navMesh = r.navMesh;
188
+ m.query = new lib.NavMeshQuery(r.navMesh);
189
+ seatLinks(m);
190
+ return true;
191
+ }
192
+
193
+ /** The mesh of a size no one asked for before. The whole cell counts as its radius: it stands for every body that rounds to it. It takes no part in revision: nothing walkable changed, and async pathfinding sends each size when a batch first needs it */
194
+ function extraMesh(size) {
195
+ const m = { size, cells: size, radius: size * cellSize, links: [], tileCache: null, navMesh: null, query: null, obstacles: null, obstaclesOf: follows(() => e.collision ?? null) };
196
+ api.meshes.set(size, m);
197
+ if (cut(m, geometry())) syncMesh(m);
198
+ return m;
199
+ }
200
+
201
+ async function build() {
202
+ pending = false;
203
+ if (api.ready) api.dispose();
204
+ const ground = geometry();
205
+ if (!ground.indices.length || !cut(api, ground)) return;
206
+ if (crowd) api.crowd = new lib.Crowd(api.navMesh, { maxAgents, maxAgentRadius: agentRadius * 2 });
207
+ api.ready = true; api.version++; revision++;
92
208
  syncObstacles();
93
209
  if (debug) {
94
210
  const three = await import('@recast-navigation/three');
95
- api.helper = new three.NavMeshHelper(r.navMesh);
211
+ api.helper = new three.NavMeshHelper(api.navMesh);
96
212
  api.helper.position.y = 0.05; e.add(api.helper, { owner: 'engine:nav' });
97
213
  }
98
214
  }
99
215
 
100
216
  // collision-module colliders -> TileCache obstacles (engine.collision.mirror diffs add / remove, shared with rigid), then rebuild affected tiles
101
- function obstacle(type, o) {
102
- const tc = api.tileCache, list = [];
217
+ function obstacle(m, type, o) {
218
+ const tc = m.tileCache, list = [];
103
219
  const y = (o.y ?? e.surface(o.x, o.z)) - maxClimb, h = (o.h ?? 6) + maxClimb; // extend a bit downward: Recast ignores a bottom face lying exactly on the ground
104
220
  if (type === 'box') {
105
221
  // one obstacle affects at most 8 tiles: cut big boxes into pieces no larger than half a tile (along the box's own orientation)
106
- const hw = o.hw + agentRadius, hd = o.hd + agentRadius, piece = tileSize * cellSize / 2; // add the agent radius so agents don't hug walls
222
+ const hw = o.hw + m.radius, hd = o.hd + m.radius, piece = tileSize * cellSize / 2; // add the agent radius so agents don't hug walls
107
223
  const nx = Math.ceil(hw * 2 / piece), nz = Math.ceil(hd * 2 / piece), c = Math.cos(o.rot), sn = Math.sin(o.rot);
108
224
  for (let i = 0; i < nx; i++) for (let j = 0; j < nz; j++) {
109
225
  const lx = -hw + (i + 0.5) * hw * 2 / nx, lz = -hd + (j + 0.5) * hd * 2 / nz;
@@ -111,35 +227,47 @@ export function nav(opts = {}) {
111
227
  if (res.success) list.push(res.obstacle);
112
228
  }
113
229
  } else {
114
- const res = tc.addCylinderObstacle({ x: o.x, y, z: o.z }, o.r + agentRadius, h);
230
+ const res = tc.addCylinderObstacle({ x: o.x, y, z: o.z }, o.r + m.radius, h);
115
231
  if (res.success) list.push(res.obstacle);
116
232
  }
117
233
  queued += list.length;
118
- if (queued >= BATCH) flush();
234
+ if (queued >= BATCH) flush(m);
119
235
  return list;
120
236
  }
237
+ /** One mesh's obstacles up to date; true when any changed */
238
+ function syncMesh(m) {
239
+ if (!m.tileCache) return false;
240
+ const col = e.collision ?? null, swapped = m.obstaclesOf.sync(() => { m.obstacles?.clear(true); m.obstacles = null; });
241
+ if (!col && !swapped) return false;
242
+ m.obstacles ??= col?.mirror({ add: (type, o) => obstacle(m, type, o), remove: list => { for (const ob of list) { m.tileCache.removeObstacle(ob); if (++queued >= BATCH) flush(m); } } }) ?? null;
243
+ if (!m.obstacles?.sync() && !swapped) return false;
244
+ flush(m);
245
+ return true;
246
+ }
121
247
  function syncObstacles() {
122
- if (!api.ready || !e.collision) return;
123
- obstacles ??= e.collision.mirror({ add: obstacle, remove: list => { for (const ob of list) { api.tileCache.removeObstacle(ob); if (++queued >= BATCH) flush(); } } });
124
- if (!obstacles.sync()) return;
125
- flush();
126
- api.revision++;
248
+ if (!api.ready) return;
249
+ let changed = false;
250
+ for (const m of api.meshes.values()) changed = syncMesh(m) || changed;
251
+ if (!changed) return;
252
+ revision++;
127
253
  api.helper?.update();
128
254
  }
129
255
  // obstacle requests are processed once a batch has built up, until all tiles are rebuilt
130
256
  const BATCH = 48;
131
257
  let queued = 0;
132
- function flush() { queued = 0; for (let i = 0; i < 256 && !api.tileCache.update(api.navMesh).upToDate; i++); }
258
+ function flush(m) { queued = 0; for (let i = 0; i < 256 && !m.tileCache.update(m.navMesh).upToDate; i++); }
133
259
 
134
260
  return {
135
- name: 'nav', type: 'world', provides: ['nav'], optional: { collision: 'walls and obstacles are not cut out of the navmesh', level: 'no walkable mesh to build from, so paths stay on A*' }, params: NAV_PARAMS, options: opts, label: 'Navmesh',
261
+ name: 'nav', skipKind: 'none', type: 'world', provides: ['nav'], optional: { collision: 'walls and obstacles are not cut out of the navmesh', level: 'no walkable mesh to build from, so paths stay on A*' }, params: NAV_PARAMS, options: opts, label: 'Navmesh',
136
262
  install(engine, ctx) {
137
263
  e = engine;
138
264
  e.i18n.add({ 'zh-CN': { 'module.nav': '导航网格' }, en: { 'module.nav': 'navmesh' } });
139
265
  const mv = e.movement;
140
266
  ({ agentRadius = mv.radius, agentHeight = mv.height, maxClimb = mv.stepHeight, maxSlope = mv.maxSlope } = opts);
141
267
  api.agent = { radius: agentRadius, height: agentHeight, maxClimb, maxSlope };
268
+ api.radius = agentRadius; api.cells = cellsOf(agentRadius); api.meshes.set(BASE, api);
142
269
  ctx.track(e.events.on('level:loaded', () => { if (lib) build(); else pending = true; }));
270
+ ctx.track(e.events.on('level:unloaded', () => { pending = false; if (api.ready) api.dispose(); })); // every size was cut from the level that left
143
271
  pending = !!e.level?.ready; // installed after the level loaded: that event is gone, init builds the mesh
144
272
  // fetch and compile the WASM from install on, so it loads while the page builds the world instead of inside start()'s module inits
145
273
  wasm = Promise.all([import('@recast-navigation/core'), import('@recast-navigation/generators')]).then(async ([l, g]) => { await l.init(); return [l, g]; });
@@ -155,9 +283,11 @@ export function nav(opts = {}) {
155
283
  syncObstacles();
156
284
  api.crowd?.update(dt);
157
285
  },
158
- describe() { return { ready: api.ready, version: api.version, obstacles: obstacles?.size ?? 0 }; },
286
+ describe() { return { ready: api.ready, version: api.version, obstacles: api.obstacles?.size ?? 0, links: api.links.length, meshes: api.ready ? api.meshes.size : 0 }; },
159
287
  // engine.dispose(): the Recast navMesh / query / tileCache / crowd live in the WASM heap, not in JS, so the garbage collector never frees
160
288
  // them; an editor or test that makes engines over and over would grow that heap every time
161
289
  dispose() { api.dispose(); },
162
290
  };
163
291
  }
292
+
293
+ export const handRolled = 'none: a pathfinder of its own is explicitly allowed';
@@ -1,17 +1,52 @@
1
- // Navmesh path query: the one Recast search in the engine. engine.nav.findPath calls it with the live query,
2
- // the pathfinding worker (characters/pathJob.js) with a query on an imported copy of the same mesh. Worker-safe: no imports.
1
+ // Navmesh path query: the one Recast search in the engine. engine.nav.findPath calls it with the live mesh,
2
+ // the pathfinding worker (characters/pathJob.js) with an imported copy of the same mesh. Worker-safe: imports only core/scene/floor.js.
3
+ // computePath would do, but it drops the flags that say a leg is a link; this is its search with the flags kept.
4
+
5
+ import { sameFloor } from '../../core/scene/floor.js';
6
+
7
+ export const OPTS = { halfExtents: { x: 2, y: 4, z: 2 } };
8
+ const OFF_MESH = 4; // DT_STRAIGHTPATH_OFFMESH_CONNECTION: this point starts a link, the next one ends it
9
+ const OFF_MESH_POLY = 1; // DT_POLYTYPE_OFFMESH_CONNECTION
10
+ const NO_PATH = { status: 'noPath', path: null };
3
11
 
4
12
  /**
5
- * @param {any} query a Recast NavMeshQuery
13
+ * @param {{ query: any, navMesh: any, links: { id: string | number }[] } | undefined} nav Recast NavMeshQuery and NavMesh, and the links by the index their connections carry; none or no query: a body no mesh could be cut for
6
14
  * @param {{ x: number, y: number, z: number }} s start (y = ground height, looked up by the caller: the worker has no ground)
7
15
  * @param {{ x: number, y: number, z: number }} g goal
8
16
  * @param {number} reach how far the path's end may stop short of the goal and still count as reaching it (m)
9
- * @returns {{ status: 'ok' | 'noPath', path: { x: number, z: number }[] | null }}
17
+ * @param {number} body character height: the end must be on the goal's floor
18
+ * @returns {{ status: 'ok' | 'noPath', path: { x: number, y: number, z: number, link?: { id: string | number, from: object, to: object } }[] | null }}
10
19
  */
11
- export function navSearch(query, s, g, reach) {
12
- const r = query.computePath(s, g, { halfExtents: { x: 2, y: 4, z: 2 } });
13
- if (!r.success || !r.path.length) return { status: 'noPath', path: null };
14
- const end = r.path[r.path.length - 1];
15
- if (Math.hypot(end.x - g.x, end.z - g.z) > reach) return { status: 'noPath', path: null }; // end point unreachable
16
- return { status: 'ok', path: r.path.map(p => ({ x: p.x, z: p.z })) };
20
+ export function navSearch(nav, s, g, reach, body) {
21
+ const q = nav?.query;
22
+ if (!q) return NO_PATH;
23
+ const a = q.findNearestPoly(s, OPTS), b = q.findNearestPoly(g, OPTS);
24
+ if (!a.success || !b.success) return NO_PATH;
25
+ const found = q.findPath(a.nearestRef, b.nearestRef, s, g), polys = found.polys;
26
+ let out = NO_PATH;
27
+ if (found.success && polys.size) {
28
+ const last = polys.get(polys.size - 1), close = last === b.nearestRef ? null : q.closestPointOnPoly(last, g);
29
+ if (!close || close.success) out = corners(nav, s, close ? close.closestPoint : g, polys, g, reach, body);
30
+ }
31
+ polys.destroy();
32
+ return out;
33
+ }
34
+
35
+ /** The corners of a polygon corridor as path points; the point that starts a link says so, with both ends in 3D */
36
+ function corners(nav, s, end, polys, g, reach, body) {
37
+ const r = nav.query.findStraightPath(s, end, polys), { straightPath: v, straightPathFlags: flags, straightPathRefs: refs, straightPathCount: n } = r;
38
+ const at = i => ({ x: v.get(i * 3), y: v.get(i * 3 + 1), z: v.get(i * 3 + 2) });
39
+ // A walker standing on a link's start (it has just landed there, say) gets no corner for it: the funnel's apex is already on it, so only the corridor still shows the link
40
+ const standing = r.success && n > 1 && polys.size > 1 && !((flags.get(0) | flags.get(1)) & OFF_MESH) && nav.navMesh.getTileAndPolyByRef(polys.get(1)).poly.getType() === OFF_MESH_POLY ? polys.get(1) : 0;
41
+ const path = [];
42
+ for (let i = 0; r.success && i < n; i++) {
43
+ const p = at(i), ref = flags.get(i) & OFF_MESH ? refs.get(i) : i ? 0 : standing;
44
+ if (ref && i + 1 < n) { const u = nav.navMesh.getOffMeshConnectionByRef(ref).userId(); p.link = { id: nav.links[u]?.id ?? u, from: at(i), to: at(i + 1) }; }
45
+ path.push(p);
46
+ }
47
+ v.destroy(); flags.destroy(); refs.destroy();
48
+ const tail = path[path.length - 1];
49
+ // end point unreachable: too far off, or right under it, where Detour's best try at a goal cut off upstairs ends
50
+ if (!tail || Math.hypot(tail.x - g.x, tail.z - g.z) > reach || !sameFloor(tail.y, g.y, body)) return NO_PATH;
51
+ return { status: 'ok', path };
17
52
  }
@@ -72,7 +72,7 @@ export function net(opts = {}) {
72
72
  };
73
73
  let n = null;
74
74
  return {
75
- name: 'net', type: 'net', params: NET_PARAMS, options: opts, label: 'Multiplayer', stage: 'late', optional: ['world', 'inventory'],
75
+ name: 'net', skipKind: 'none', type: 'net', params: NET_PARAMS, options: opts, label: 'Multiplayer', stage: 'late', optional: ['world', 'inventory'],
76
76
  // ctx.control: the holds on remote characters are the module's, so removing net hands them back
77
77
  install(e, ctx) { e.i18n.add({ 'zh-CN': { 'module.net': '联机' }, en: { 'module.net': 'multiplayer' } }); o.control = ctx.control; return (n = new Net(e, o)); },
78
78
  fixed(dt) { n._fixed(dt); },