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.
- package/CHANGELOG.md +219 -4
- package/README.md +6 -6
- package/core/assets/Animator.js +2 -0
- package/core/assets/Assets.js +44 -13
- package/core/assets/assetEntry.js +87 -22
- package/core/assets/assetHot.js +2 -1
- package/core/assets/assetReport.js +1 -2
- package/core/audio/Audio.js +24 -5
- package/core/base/I18n.js +6 -3
- package/core/base/Random.js +3 -1
- package/core/base/Vars.js +14 -4
- package/core/base/errorCodes.js +54 -16
- package/core/base/errorHints.js +12 -1
- package/core/base/errors.js +6 -4
- package/core/base/events.generated.js +10 -0
- package/core/base/follows.js +26 -0
- package/core/base/math.js +15 -8
- package/core/base/params.js +2 -2
- package/core/{saves → base}/saveValues.js +24 -6
- package/core/base/sections.js +97 -0
- package/core/base/spelling.js +32 -0
- package/core/base/validate.js +8 -29
- package/core/engine/Engine.js +61 -18
- package/core/engine/Loading.js +30 -3
- package/core/engine/copies.js +1 -1
- package/core/engine/headlessLoad.js +30 -13
- package/core/engine/lifecycle.js +30 -25
- package/core/engine/loop.js +22 -4
- package/core/engine/moduleSlots.js +91 -15
- package/core/engine/moduleTypes.js +13 -0
- package/core/engine/modules.js +248 -62
- package/core/engine/page.js +25 -8
- package/core/engine/plugins.js +15 -3
- package/core/engine/services.js +3 -0
- package/core/engine/startup.js +46 -36
- package/core/input/Input.js +39 -19
- package/core/input/inputKeyboard.js +39 -0
- package/core/input/inputPad.js +23 -2
- package/core/input/inputPointer.js +3 -1
- package/core/input/inputSeat.js +66 -0
- package/core/input/inputTouch.js +23 -6
- package/core/inspect/DebugOverrides.js +13 -2
- package/core/inspect/Describe.js +10 -6
- package/core/inspect/Inspect.js +31 -4
- package/core/inspect/UrlState.js +14 -10
- package/core/inspect/catalog.js +12 -5
- package/core/inspect/describeRender.js +3 -2
- package/core/inspect/describeText.js +6 -2
- package/core/inspect/metadata.generated.js +4140 -0
- package/core/inspect/pictureWriters.js +117 -33
- package/core/inspect/toolDoor.js +21 -0
- package/core/inspect/valueHistory.js +35 -0
- package/core/ops/Ops.js +32 -7
- package/core/ops/control.js +48 -23
- package/core/ops/holds.js +4 -3
- package/core/ops/opsAtomic.js +18 -6
- package/core/ops/opsCheck.js +7 -5
- package/core/ops/opsFail.js +5 -7
- package/core/ops/opsRun.js +2 -2
- package/core/ops/owned.js +20 -3
- package/core/ops/sharedPoint.js +7 -10
- package/core/ops/stacks.js +22 -1
- package/core/saves/SaveStore.js +52 -26
- package/core/saves/Saves.js +122 -27
- package/core/saves/saveApply.js +159 -61
- package/core/saves/saveFiles.js +30 -25
- package/core/saves/saveVersions.js +20 -6
- package/core/saves/session.js +76 -33
- package/core/saves/stateReplace.js +184 -0
- package/core/scene/Rays.js +21 -5
- package/core/scene/Views.js +6 -6
- package/core/scene/adaptive.js +13 -10
- package/core/scene/canvasBox.js +2 -0
- package/core/scene/compositeGround.js +72 -0
- package/core/scene/floor.js +17 -0
- package/core/scene/grid.js +2 -0
- package/core/scene/ground.contract.js +14 -0
- package/core/scene/ground.js +52 -17
- package/core/scene/pixel.js +154 -0
- package/core/scene/pixelRatio.js +167 -0
- package/core/scene/sceneDelta.js +3 -3
- package/core/scene/sceneMethods.js +11 -6
- package/core/scene/stepPoses.js +6 -1
- package/core/scene/thingExplain.js +1 -1
- package/core/scene/thingOps.js +22 -14
- package/core/scene/things.js +1 -1
- package/core/scene/tier.js +10 -0
- package/core/scene/view.js +126 -9
- package/core/stream/Batching.js +0 -1
- package/core/stream/Stream.js +24 -12
- package/core/stream/batchGroups.js +1 -0
- package/core/stream/scatter.js +5 -2
- package/core/stream/streamSources.js +2 -1
- package/core/threads/Commits.js +12 -7
- package/core/threads/Jobs.js +15 -5
- package/core/threads/Threads.js +5 -2
- package/core/time/Clock.js +3 -1
- package/core/time/skip.js +10 -4
- package/core/time/time.js +16 -10
- package/docs/AI.md +89 -72
- package/docs/API.md +18 -14
- package/docs/CODEMAP.md +68 -40
- package/docs/COMMANDS.md +22 -23
- package/docs/CONVENTIONS.md +120 -17
- package/docs/MIGRATING-0.8.md +2 -0
- package/docs/MIGRATING-1.0.md +101 -0
- package/docs/THREE.md +65 -12
- package/docs/api/cameraRig.md +3 -0
- package/docs/api/characters.md +13 -7
- package/docs/api/collider3d.md +9 -0
- package/docs/api/content.md +16 -15
- package/docs/api/dialogue.md +2 -1
- package/docs/api/engine.md +18 -16
- package/docs/api/events.md +14 -4
- package/docs/api/ground.md +2 -2
- package/docs/api/i18n.md +1 -1
- package/docs/api/input.md +2 -1
- package/docs/api/interactions.md +1 -1
- package/docs/api/inventory.md +1 -1
- package/docs/api/level.md +3 -2
- package/docs/api/nav.md +4 -2
- package/docs/api/particles.md +8 -5
- package/docs/api/pickups.md +1 -1
- package/docs/api/post.md +3 -4
- package/docs/api/quests.md +4 -2
- package/docs/api/rays.md +2 -0
- package/docs/api/rigid.md +3 -2
- package/docs/api/saves.md +8 -7
- package/docs/api/stream.md +4 -5
- package/docs/api/terrain.md +3 -4
- package/docs/api/terrainDraw.md +1 -1
- package/docs/api/timeline.md +2 -2
- package/docs/api/tools.md +3 -1
- package/docs/api/triggers.md +2 -0
- package/docs/api/vegetationDraw.md +1 -1
- package/docs/api/water.md +6 -2
- package/docs/api/weather.md +19 -4
- package/docs/api/weatherDraw.md +1 -1
- package/docs/api/world.md +1 -1
- package/docs/recipes/01-new-game.md +3 -3
- package/docs/recipes/02-npc.md +3 -4
- package/docs/recipes/03-items-pickups.md +11 -11
- package/docs/recipes/04-quests.md +2 -0
- package/docs/recipes/05-props-bake.md +9 -9
- package/docs/recipes/06-clock-events.md +6 -6
- package/docs/recipes/07-flow-scenes-pause.md +18 -15
- package/docs/recipes/08-weather-sky.md +5 -5
- package/docs/recipes/09-materials-lights-models.md +3 -3
- package/docs/recipes/10-blender-level.md +16 -4
- package/docs/recipes/11-vehicles.md +18 -6
- package/docs/recipes/12-navmesh.md +52 -8
- package/docs/recipes/13-animation.md +34 -8
- package/docs/recipes/14-custom-module.md +20 -8
- package/docs/recipes/15-perf.md +4 -4
- package/docs/recipes/16-dev-bridge.md +9 -8
- package/docs/recipes/18-world.md +13 -5
- package/docs/recipes/19-shooting-picking.md +3 -2
- package/docs/recipes/20-content-actions-save.md +26 -6
- package/docs/recipes/21-camera.md +17 -23
- package/docs/recipes/22-shop-gold.md +21 -12
- package/docs/recipes/23-ops.md +19 -15
- package/docs/recipes/26-ui-parts.md +3 -2
- package/docs/recipes/27-net.md +3 -3
- package/docs/recipes/28-terrain.md +3 -3
- package/docs/recipes/29-grid.md +1 -1
- package/docs/recipes/30-templates.md +10 -13
- package/docs/recipes/31-audio.md +2 -2
- package/docs/recipes/32-action-game.md +6 -5
- package/docs/recipes/33-stream-sources.md +4 -1
- package/docs/recipes/34-environment-lighting.md +7 -8
- package/docs/recipes/35-picture-from-reference.md +13 -9
- package/docs/recipes/36-ground-plants.md +3 -2
- package/docs/recipes/40-scene.md +11 -10
- package/docs/recipes/43-shader-patches-surfaces.md +7 -7
- package/docs/recipes/44-water-weather-hooks.md +9 -8
- package/docs/recipes/45-cascaded-shadows.md +3 -4
- package/docs/recipes/46-blender-art-route.md +3 -3
- package/docs/recipes/49-game-module-contract.md +2 -1
- package/docs/recipes/50-own-renderer.md +1 -0
- package/docs/recipes/51-capability-catalog.md +14 -8
- package/docs/recipes/52-around-the-picture.md +4 -4
- package/docs/recipes/55-mods-time-wrap.md +5 -4
- package/docs/recipes/56-webgpu-tsl.md +12 -1
- package/docs/recipes/57-control.md +30 -10
- package/docs/recipes/58-input.md +13 -0
- package/docs/recipes/60-judge-the-picture.md +1 -1
- package/docs/recipes/62-picture-code.md +106 -48
- package/docs/recipes/63-third-person-start.md +2 -1
- package/docs/recipes/64-particles.md +53 -4
- package/docs/recipes/65-swarm.md +2 -2
- package/docs/recipes/66-common-tasks.md +313 -0
- package/examples/action/.threedog/content-index.json +1 -1
- package/examples/action/GAMEMAP.md +3 -3
- package/examples/perf-island/.threedog/content-index.json +1 -1
- package/examples/perf-island/GAMEMAP.md +3 -3
- package/examples/perf-island/main.js +2 -2
- package/examples/plain-picture/GAMEMAP.md +3 -1
- package/examples/rc2d/GAMEMAP.md +1 -1
- package/examples/rc2d/rc2d.js +1 -1
- package/examples/styletest/.threedog/content-index.json +1 -1
- package/examples/styletest/GAMEMAP.md +3 -3
- package/examples/webgpu-tsl/GAMEMAP.md +1 -1
- package/examples/world/.threedog/content-index.json +1 -1
- package/examples/world/GAMEMAP.md +5 -4
- package/examples/world/main.js +3 -3
- package/index.d.ts +8 -5
- package/index.js +22 -1
- package/llms.txt +2 -1
- package/modules/ambience/Ambience.js +5 -3
- package/modules/calendar/index.js +7 -5
- package/modules/camera/FirstPersonCamera.js +3 -3
- package/modules/camera/FixedCamera.js +34 -20
- package/modules/camera/FollowCamera.js +20 -11
- package/modules/camera/RtsCamera.js +1 -0
- package/modules/camera/common.js +33 -22
- package/modules/camera/pixelSnap.js +62 -0
- package/modules/characters/Character.js +136 -43
- package/modules/characters/NPC.js +60 -28
- package/modules/characters/assetModel.js +2 -2
- package/modules/characters/astar.js +47 -28
- package/modules/characters/character.contract.js +21 -0
- package/modules/characters/contract.js +17 -3
- package/modules/characters/index.js +94 -34
- package/modules/characters/moveHelpers.js +80 -15
- package/modules/characters/mover.contract.js +14 -0
- package/modules/characters/movers/common.js +6 -4
- package/modules/characters/movers/rapier.js +12 -5
- package/modules/characters/movers/simple.js +25 -12
- package/modules/characters/movers/support.js +18 -7
- package/modules/characters/npcAvoid.js +15 -12
- package/modules/characters/npcSim.js +75 -25
- package/modules/characters/npcView.js +13 -6
- package/modules/characters/pathAsync.js +74 -24
- package/modules/characters/pathJob.js +38 -21
- package/modules/characters/player.js +59 -47
- package/modules/characters/seat.js +56 -0
- package/modules/characters/vehicle.contract.js +8 -5
- package/modules/characters/walkTo.js +31 -18
- package/modules/collision/Collision.js +44 -26
- package/modules/collision/contract.js +2 -2
- package/modules/collision/grid.js +6 -1
- package/modules/content/explain.js +1 -1
- package/modules/content/fields.js +3 -3
- package/modules/content/ids.js +3 -1
- package/modules/content/index.js +83 -27
- package/modules/content/loader.js +110 -130
- package/modules/content/markers.js +1 -1
- package/modules/content/models.js +48 -14
- package/modules/content/packs.js +2 -1
- package/modules/content/places.js +5 -4
- package/modules/content/props.js +8 -6
- package/modules/content/rules.js +29 -47
- package/modules/content/templates.js +66 -35
- package/modules/content/words.js +19 -6
- package/modules/debug/DebugPanel.js +4 -2
- package/modules/flow/contract.js +1 -0
- package/modules/flow/index.js +24 -14
- package/modules/gameplay/Container.js +5 -2
- package/modules/gameplay/Containers.js +9 -1
- package/modules/gameplay/Dialogue.js +82 -25
- package/modules/gameplay/Interactions.js +61 -32
- package/modules/gameplay/Inventory.js +56 -13
- package/modules/gameplay/Quests.js +133 -24
- package/modules/gameplay/boxOps.js +7 -0
- package/modules/gameplay/dialogueBubbles.js +14 -9
- package/modules/gameplay/inventoryOps.js +11 -7
- package/modules/gameplay/pickups.js +43 -16
- package/modules/gameplay/questLog.js +4 -2
- package/modules/gameplay/questSave.js +6 -1
- package/modules/gameplay/quests.contract.js +1 -1
- package/modules/grid/Grid.js +1 -1
- package/modules/grid/Layer.js +8 -4
- package/modules/grid/index.js +21 -15
- package/modules/grid/ops.js +43 -46
- package/modules/grid/tiles.js +1 -1
- package/modules/hlod/index.js +6 -3
- package/modules/hud/index.js +6 -4
- package/modules/hud/parts.js +4 -4
- package/modules/level/contract.js +2 -2
- package/modules/level/heightfield.js +17 -21
- package/modules/level/index.js +83 -26
- package/modules/level/load.js +165 -48
- package/modules/level/nodes.js +34 -16
- package/modules/lights/index.js +6 -3
- package/modules/lights/sources.js +3 -1
- package/modules/music/Music.js +4 -2
- package/modules/nav/contract.js +7 -5
- package/modules/nav/index.js +174 -44
- package/modules/nav/navPath.js +45 -10
- package/modules/net/index.js +1 -1
- package/modules/particles/Particles.js +85 -22
- package/modules/particles/effect.js +80 -28
- package/modules/particles/shaders.js +17 -0
- package/modules/photo/Photo.js +12 -10
- package/modules/rigid/RigidBodies.js +200 -57
- package/modules/rigid/Vehicles.js +15 -5
- package/modules/rigid/collider3d.contract.js +26 -0
- package/modules/rigid/ragdoll.js +55 -44
- package/modules/rigid/ragdollBones.js +83 -33
- package/modules/rigid/refresh.js +10 -0
- package/modules/rigid/sync.js +46 -15
- package/modules/settings/Settings.js +84 -37
- package/modules/settings/apply.js +15 -8
- package/modules/settings/sections.js +7 -4
- package/modules/settings/strings.js +2 -2
- package/modules/sky/skyModule.js +3 -1
- package/modules/swarm/Swarm.js +16 -6
- package/modules/terrain/ChunkManager.js +10 -16
- package/modules/terrain/index.js +17 -11
- package/modules/terrain/terrainEdit.js +13 -2
- package/modules/terrain/terrainGen.js +5 -3
- package/modules/terrain/terrainShape.js +1 -1
- package/modules/timeline/Timeline.js +58 -26
- package/modules/timeline/Tween.js +19 -13
- package/modules/timeline/shots.js +19 -10
- package/modules/triggers/index.js +87 -20
- package/modules/vegetation/Vegetation.js +4 -3
- package/modules/vegetation/draw.js +16 -0
- package/modules/vegetation/groundChunks.js +10 -7
- package/modules/vegetation/index.js +30 -7
- package/modules/water/Water.js +6 -2
- package/modules/weather/Weather.js +16 -15
- package/modules/weather/weatherDraw.js +7 -6
- package/modules/world/World.js +20 -7
- package/modules/world/explain.js +1 -1
- package/modules/world/index.js +13 -6
- package/modules/world/persist.js +23 -8
- package/modules/world/pos.js +4 -4
- package/modules/world/records.js +13 -7
- package/modules/world/sim.js +74 -23
- package/modules/world/simFar.js +2 -2
- package/modules/world/state.js +31 -6
- package/modules/world/thingSource.js +16 -3
- package/modules/world/views.js +19 -8
- package/package.json +7 -1
- package/render/PostFX.js +47 -29
- package/render/backend.js +5 -1
- package/render/fx/particles.tsl.js +8 -6
- package/render/fx/postWebGPU.tsl.js +3 -3
- package/render/layers.js +1 -1
- package/render/lightmap.js +23 -3
- package/render/occlusion.js +43 -12
- package/render/patches.js +2 -2
- package/render/postWebGL.js +4 -3
- package/render/probes.js +25 -0
- package/render/shadows.js +2 -2
- package/types/core.d.ts +142 -55
- package/types/gameplay.d.ts +92 -40
- package/types/generated/core/base/I18n.d.ts +2 -2
- package/types/generated/core/input/Input.d.ts +16 -2
- package/types/generated/core/input/inputSeat.d.ts +26 -0
- package/types/generated/core/inspect/DebugOverrides.d.ts +15 -1
- package/types/generated/core/ops/Ops.d.ts +2 -1
- package/types/generated/core/ops/control.d.ts +12 -2
- package/types/generated/core/saves/Saves.d.ts +26 -6
- package/types/generated/core/saves/session.d.ts +1 -1
- package/types/generated/core/scene/Views.d.ts +1 -1
- package/types/generated/core/stream/Stream.d.ts +6 -4
- package/types/generated/modules/grid/Grid.d.ts +1 -0
- package/types/generated/modules/particles/Particles.d.ts +4 -3
- package/types/generated/modules/timeline/Timeline.d.ts +5 -4
- package/types/generated/modules/weather/Weather.d.ts +1 -7
- package/types/generated/modules/world/World.d.ts +6 -4
- package/types/generated/render/PostFX.d.ts +6 -14
- package/types/nav.d.ts +36 -4
- package/types/physics.d.ts +55 -7
- package/types/pixel.d.ts +75 -0
- package/types/world.d.ts +14 -8
- package/ui/Parts.js +9 -2
- package/ui/theme.js +2 -2
- package/core/scene/engineCamera.js +0 -32
- package/modules/camera/projection.js +0 -21
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
// NPC-vs-NPC avoidance (near NPCs, every fixed step, called from goTo): nearby NPCs push each other apart to at least the sum of their radii;
|
|
2
|
-
// obstacle (NPCs yield,
|
|
1
|
+
// NPC-vs-NPC avoidance (near NPCs, every fixed step, called from goTo): nearby NPCs push each other apart to at least the sum of their radii; every player is an
|
|
2
|
+
// obstacle (NPCs yield, a player is never pushed).
|
|
3
3
|
// Why it is written this way: a continuous run and a save-then-load of the same scenario must give bit-identical positions:
|
|
4
4
|
// 1. Each NPC pushes only itself and reads neighbours' positions as of the start of this step (stamped), so a neighbour that already moved this step does not
|
|
5
5
|
// matter and order is irrelevant;
|
|
@@ -11,6 +11,7 @@
|
|
|
11
11
|
// avoidance (too costly).
|
|
12
12
|
import { readParams, keysSchema } from '../../core/base/params.js';
|
|
13
13
|
import { Cells } from '../../core/stream/cells.js';
|
|
14
|
+
import { sameFloor } from '../../core/scene/floor.js';
|
|
14
15
|
|
|
15
16
|
const KEYS = ['on', 'radius', 'strength'];
|
|
16
17
|
// push direction is rotated ~25° to the right: two NPCs meeting head-on each swerve to their own right instead of deadlocking in a line
|
|
@@ -29,15 +30,16 @@ function shove(acc, dx, dz, d, min, tie) {
|
|
|
29
30
|
|
|
30
31
|
/** Mounted on engine.npcs: engine.npcs.avoid.set(false | { radius, strength }) */
|
|
31
32
|
export class NpcAvoid {
|
|
32
|
-
/** @param {(h: any) => any} track the characters module's ctx.track: its listeners leave with the module */
|
|
33
|
-
constructor(engine, track) {
|
|
33
|
+
/** @param {any} engine @param {(h: any) => any} track the characters module's ctx.track: its listeners leave with the module @param {Map<string, { character: any }>} players */
|
|
34
|
+
constructor(engine, track, players) {
|
|
34
35
|
this.engine = engine;
|
|
36
|
+
/** @internal */ this._players = players;
|
|
35
37
|
this.on = true; // switch (default on)
|
|
36
38
|
this.radius = null; // avoid radius per NPC (m); null = engine.movement.radius
|
|
37
39
|
this.strength = 3; // max push speed (m/s)
|
|
38
40
|
this._acc = { x: 0, z: 0 };
|
|
39
41
|
/** @internal ids of NPCs that have a model now (NPCManager keeps it): only they take part, so far NPCs cost nothing per step */ this.built = new Set();
|
|
40
|
-
// id → { id, rec, k, x, z, position, n }: x, z = where its own step started (stamped on step k); position = where it was filed for step n (the stamp, or
|
|
42
|
+
// id → { id, rec, k, x, y, z, position, n }: x, y, z = where its own step started (stamped on step k); position = where it was filed for step n (the stamp, or
|
|
41
43
|
// where it stood before moving), what neighbours read
|
|
42
44
|
this._start = new Map();
|
|
43
45
|
// the shared xz index (core/stream/cells.js) with cells the size of the minimum distance of two NPCs, so a query looks at 3x3 cells. Not world's record index:
|
|
@@ -47,7 +49,7 @@ export class NpcAvoid {
|
|
|
47
49
|
this._q = null; this._qRec = null; // the NPC being pushed, for the query callback (built once, no closure per push)
|
|
48
50
|
this._onNear = (o, d2) => {
|
|
49
51
|
const own = this._q, rec = this._qRec;
|
|
50
|
-
if (o.rec === rec || d2 >= this._min2 || (o.rec.zone != null && rec.zone != null && o.rec.zone !== rec.zone)) return;
|
|
52
|
+
if (o.rec === rec || d2 >= this._min2 || (o.rec.zone != null && rec.zone != null && o.rec.zone !== rec.zone) || !sameFloor(own.y, o.position.y, this.engine.movement.height)) return;
|
|
51
53
|
shove(this._acc, own.x - o.position.x, own.z - o.position.z, Math.sqrt(d2), this._min, rec.id < o.id ? 1 : -1);
|
|
52
54
|
};
|
|
53
55
|
track(engine.events.on('world:remove', ({ id }) => { const s = this._start.get(id); if (s) { this._grid?.delete(s); this._filed.delete(s); this._start.delete(id); } }));
|
|
@@ -77,11 +79,11 @@ export class NpcAvoid {
|
|
|
77
79
|
stamp(rec) {
|
|
78
80
|
if (!this.on) return;
|
|
79
81
|
const s = this._entry(rec);
|
|
80
|
-
s.k = this.engine.world.steps; s.x = rec.position.x; s.z = rec.position.z;
|
|
82
|
+
s.k = this.engine.world.steps; s.x = rec.position.x; s.y = rec.position.y; s.z = rec.position.z;
|
|
81
83
|
}
|
|
82
84
|
_entry(rec) {
|
|
83
85
|
let s = this._start.get(rec.id);
|
|
84
|
-
if (!s) this._start.set(rec.id, s = { id: rec.id, rec, k: -1, x: 0, z: 0, position: { x: 0, z: 0 }, n: -1 });
|
|
86
|
+
if (!s) this._start.set(rec.id, s = { id: rec.id, rec, k: -1, x: 0, y: 0, z: 0, position: { x: 0, y: 0, z: 0 }, n: -1 });
|
|
85
87
|
s.rec = rec; // a load replaces record objects
|
|
86
88
|
return s;
|
|
87
89
|
}
|
|
@@ -99,13 +101,13 @@ export class NpcAvoid {
|
|
|
99
101
|
const o = W.get(id); if (!o || !W.view(id)) continue;
|
|
100
102
|
const s = this._entry(o);
|
|
101
103
|
const q = s.k === n ? s : o.position;
|
|
102
|
-
s.position.x = q.x; s.position.z = q.z;
|
|
104
|
+
s.position.x = q.x; s.position.y = q.y; s.position.z = q.z;
|
|
103
105
|
s.n = n; G.put(s); filed.add(s);
|
|
104
106
|
}
|
|
105
107
|
for (const s of filed) if (s.n !== n) { G.delete(s); filed.delete(s); } // model gone since last step
|
|
106
108
|
}
|
|
107
109
|
|
|
108
|
-
/** Push ch (the rec's model) apart
|
|
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 */
|
|
109
111
|
push(rec, ch, dt) {
|
|
110
112
|
const e = this.engine, W = e.world;
|
|
111
113
|
if (!this.on || e.nav?.crowd) return;
|
|
@@ -116,8 +118,9 @@ export class NpcAvoid {
|
|
|
116
118
|
const acc = this._acc; acc.x = acc.z = 0;
|
|
117
119
|
this._q = own; this._qRec = rec; this._min = min; this._min2 = min * min;
|
|
118
120
|
this._grid.forEach(own, min, this._onNear);
|
|
119
|
-
const
|
|
120
|
-
|
|
121
|
+
const ox = own.x, oz = own.z;
|
|
122
|
+
for (const { character: pl } of this._players.values()) { // a player is an obstacle: only the NPC yields, a player's position belongs to its mover
|
|
123
|
+
if (!sameFloor(own.y, pl.root.position.y, e.movement.height)) continue;
|
|
121
124
|
const q = pl.root.position, m = r + (pl.radius ?? r), dx = ox - q.x, dz = oz - q.z, d = Math.hypot(dx, dz);
|
|
122
125
|
if (d < m) shove(acc, dx, dz, d, m, 1);
|
|
123
126
|
}
|
|
@@ -7,10 +7,15 @@
|
|
|
7
7
|
// See the top of NPC.js for record fields.
|
|
8
8
|
|
|
9
9
|
import { standAt } from './movers/support.js';
|
|
10
|
-
import { nextPoint } from './moveHelpers.js';
|
|
10
|
+
import { nextPoint, sameLevel, climbTo, startLink, stepLink, landLink, leaveLink, linkAhead, LINK_REACH } from './moveHelpers.js';
|
|
11
11
|
|
|
12
12
|
/** Fixed steps an NPC waits for a findPathAsync answer before asking again (answers normally land 4 steps later; a long queue adds perStep batches) */
|
|
13
13
|
const PATH_WAIT = 300;
|
|
14
|
+
/** Recast's DT_CROWDAGENT_STATE_OFFMESH: the crowd has put the agent on a link */
|
|
15
|
+
const AGENT_ON_LINK = 2;
|
|
16
|
+
const STUCK_SECONDS = 0.5; // no ground gained for this long while walking a path: ask for a new one
|
|
17
|
+
const AGENT_LEASH = 1.5; // an agent farther than this from its NPC (m) is pulled back
|
|
18
|
+
const LINK_WALK = 3; // farther than this from the link the crowd took (m), the NPC was moved away: the crossing is off
|
|
14
19
|
|
|
15
20
|
/**
|
|
16
21
|
* Which stop to go to now (index): the latest stop at or before time t (0-1); before the first stop counts as the previous day's last stop; null if no schedule
|
|
@@ -60,7 +65,8 @@ export function advance(e, W, rec, seconds) {
|
|
|
60
65
|
}
|
|
61
66
|
const idx = stopIndex(s, timeOfDay(e)), g = s[idx];
|
|
62
67
|
rec.nav.stop = idx;
|
|
63
|
-
|
|
68
|
+
const moving = Math.hypot(g.x - x, g.z - z) > rec.arriveDistance;
|
|
69
|
+
settle(e, W, rec, x, z, moving, moving ? p.y : g.y ?? p.y); // at the stop, the stop's floor; on the way, the one it walks on
|
|
64
70
|
}
|
|
65
71
|
|
|
66
72
|
/** Set rec.state; with events.traceSize > 0 a change is noted as an `npc:state` trace entry (from, to), so "why did it stop" has a cause chain */
|
|
@@ -71,10 +77,12 @@ function noteState(e, rec, next) {
|
|
|
71
77
|
|
|
72
78
|
/**
|
|
73
79
|
* Settle without a model: write the computed x, z back to data (position, facing, animation state); shared by every behaviour's far. The path is for the model,
|
|
74
|
-
* so it is re-found at the new position after the model is built
|
|
80
|
+
* so it is re-found at the new position after the model is built. refY: the height the ground is looked up from, default where it stood
|
|
75
81
|
*/
|
|
76
|
-
export function settle(e, W, rec, x, z, moving) {
|
|
77
|
-
const
|
|
82
|
+
export function settle(e, W, rec, x, z, moving, refY = rec.position.y) {
|
|
83
|
+
const nav = rec.nav;
|
|
84
|
+
if (nav.link) { ({ x, z } = nav.link.to); W.move(rec.id, nav.link.to); leaveLink(e, rec.id, null, nav.link); nav.link = null; } // no model to cross with: it has crossed
|
|
85
|
+
const p = rec.position; nav.path = null; nav.repath = 0;
|
|
78
86
|
const m = rec.motion ??= {};
|
|
79
87
|
const facing = x !== p.x || z !== p.z ? Math.atan2(x - p.x, z - p.z) : m.facing ?? 0;
|
|
80
88
|
Object.assign(m, { vx: 0, vz: 0, vy: 0, amount: 0, facing, grounded: true, swimming: false, jump: { coyote: 0, used: 0 } });
|
|
@@ -82,10 +90,17 @@ export function settle(e, W, rec, x, z, moving) {
|
|
|
82
90
|
// NPC of another level: this level's ground height is meaningless for it, keep its y
|
|
83
91
|
const here = W.inZone(rec);
|
|
84
92
|
// the same rule the model uses (support.js standAt), from the height it is at: without it an NPC on a deck or an upper floor dropped to the ground in the data
|
|
85
|
-
const y = here ? standAt(e, x, z,
|
|
93
|
+
const y = here ? standAt(e, x, z, refY, rec.look?.stepHeight ?? e.movement.stepHeight).y : p.y;
|
|
86
94
|
W.move(rec.id, { x, y: y === -Infinity ? p.y : y, z });
|
|
87
95
|
}
|
|
88
96
|
|
|
97
|
+
/** One step of a link crossing with a model (rec.nav.link, saved): it runs before the behavior, so no goal, talk or behavior change leaves an NPC hanging over a gap. held: a control holder above has the body, so it lands now (landLink) */
|
|
98
|
+
export function crossLink(W, rec, ch, dt, held = false) {
|
|
99
|
+
if (held ? landLink(ch, rec.nav.link) : stepLink(ch, rec.nav.link, dt)) rec.nav.link = null;
|
|
100
|
+
rec.motion = ch.saveMotion(rec.motion ?? {});
|
|
101
|
+
W.move(rec.id, ch.root.position);
|
|
102
|
+
}
|
|
103
|
+
|
|
89
104
|
/**
|
|
90
105
|
* Near step of a schedule behaviour (every fixed step): pick the stop, goTo it, then copy position and motion state back to data.
|
|
91
106
|
*/
|
|
@@ -97,7 +112,7 @@ export function nearStep(e, W, rec, ch, dt) {
|
|
|
97
112
|
}
|
|
98
113
|
|
|
99
114
|
/**
|
|
100
|
-
* With a model, take one step toward goal ({ x, z }, null = stand): pathfind, move the model via the character's mover, then copy position and motion state
|
|
115
|
+
* With a model, take one step toward goal ({ x, y?, z }, null = stand): pathfind, move the model via the character's mover, then copy position and motion state
|
|
101
116
|
* back to data; shared by every behaviour's near.
|
|
102
117
|
* Standing when in conversation (rec.busy), arrived (distance < arriveDistance) or no goal.
|
|
103
118
|
* Pathfinding goes through engine.characters.findPathAsync; a goal too far (>120 m) first walks straight 100 m, then pathfinds exactly, to avoid
|
|
@@ -106,19 +121,20 @@ export function nearStep(e, W, rec, ch, dt) {
|
|
|
106
121
|
export function goTo(e, W, rec, ch, goal, dt) {
|
|
107
122
|
const nav = rec.nav, p = ch.root.position;
|
|
108
123
|
const dGoal = goal ? Math.hypot(goal.x - p.x, goal.z - p.z) : 0;
|
|
109
|
-
if (rec.busy || !goal || dGoal < rec.arriveDistance) ch.move(0, 0, false, dt);
|
|
110
|
-
else if (e.nav?.crowd) crowdMove(e, ch, goal, dt);
|
|
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);
|
|
111
126
|
else {
|
|
112
127
|
nav.repath -= dt;
|
|
113
128
|
// goal changed while waiting, or the answer never came (engine.commits.invalidate dropped it: a partial saves.apply, a level change): ask again
|
|
114
129
|
if (ch._pathReq && (ch._pathReq.goal !== goal || e.time.tick - ch._pathReq.at > PATH_WAIT)) { ch._pathReq.remove(); ch._pathReq = null; }
|
|
115
130
|
if (!nav.path && nav.repath <= 0 && !ch._pathReq) {
|
|
116
|
-
const far = dGoal > 120, tx = far ? p.x + (goal.x - p.x) / dGoal * 100 : goal.x, tz = far ? p.z + (goal.z - p.z) / dGoal * 100 : goal.z;
|
|
131
|
+
const far = dGoal > 120, tx = far ? p.x + (goal.x - p.x) / dGoal * 100 : goal.x, tz = far ? p.z + (goal.z - p.z) / dGoal * 100 : goal.z, ty = far ? undefined : goal.y; // the stop's height says nothing about a point on the way
|
|
117
132
|
// async: many NPCs repathing in one step cost the main thread almost nothing; the answer lands a few steps later (the NPC waits in place)
|
|
118
|
-
const req = ch._pathReq = e.characters.findPathAsync(p, { x: tx, z: tz }, path => {
|
|
133
|
+
const req = ch._pathReq = e.characters.findPathAsync(p, { x: tx, y: ty, z: tz }, path => {
|
|
119
134
|
if (ch._pathReq !== req) return;
|
|
120
|
-
|
|
121
|
-
|
|
135
|
+
// 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
|
+
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 });
|
|
122
138
|
req.goal = goal; req.at = e.time.tick;
|
|
123
139
|
nav.repath = rec.repath;
|
|
124
140
|
}
|
|
@@ -126,16 +142,19 @@ export function goTo(e, W, rec, ch, goal, dt) {
|
|
|
126
142
|
const reach = Math.min(0.8, rec.arriveDistance);
|
|
127
143
|
let wp = null;
|
|
128
144
|
if (nav.path?.length) {
|
|
129
|
-
const next = nextPoint(nav.path, 0, p.x, p.z, reach);
|
|
145
|
+
const next = nextPoint(nav.path, 0, p.x, p.y, p.z, reach, e.movement.height);
|
|
130
146
|
if (next) nav.path.splice(0, next); // the path stays one saved list: what is behind the NPC leaves it
|
|
131
147
|
wp = nav.path[0];
|
|
132
|
-
if (Math.hypot(wp.x - p.x, wp.z - p.z) < reach)
|
|
148
|
+
if (Math.hypot(wp.x - p.x, wp.z - p.z) < (wp.link ? LINK_REACH : reach) && sameLevel(e, p, wp)) {
|
|
149
|
+
if (wp.link) { nav.link = startLink(ch, wp.link); nav.path.shift(); }
|
|
150
|
+
else nav.path = null;
|
|
151
|
+
wp = null;
|
|
152
|
+
}
|
|
133
153
|
}
|
|
134
154
|
if (wp) {
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
} else ch.move(0, 0, false, dt); // waiting for a path: gravity, the idle pose and slowing down go on, it must not hang in the air walking on the spot
|
|
155
|
+
stepToward(nav, ch, wp, dt);
|
|
156
|
+
if (nav.stuck > STUCK_SECONDS) { nav.path = null; nav.stuck = 0; } // re-pathfind
|
|
157
|
+
} else if (!nav.link) ch.move(0, 0, false, dt); // waiting for a path: gravity, the idle pose and slowing down go on, it must not hang in the air walking on the spot
|
|
139
158
|
}
|
|
140
159
|
e.npcs.avoid.push(rec, ch, dt); // keep clear of other NPCs and the player (with crowd, the agents handle it: push adds nothing)
|
|
141
160
|
// position belongs to the mover: copy the model position back to data here (world also copies at the end of each fixed step; copying now means later
|
|
@@ -145,20 +164,51 @@ export function goTo(e, W, rec, ch, goal, dt) {
|
|
|
145
164
|
W.move(rec.id, p);
|
|
146
165
|
}
|
|
147
166
|
|
|
167
|
+
/** One step straight at wp. nav.stuck counts time, not speed: a body pressed against something that came after the path (an obstacle added in play) still reports a walk */
|
|
168
|
+
function stepToward(nav, ch, wp, dt) {
|
|
169
|
+
const p = ch.root.position, dx = wp.x - p.x, dz = wp.z - p.z, d = Math.hypot(dx, dz), ox = p.x, oz = p.z;
|
|
170
|
+
ch.move(dx / d, dz / d, false, dt, climbTo(p, wp));
|
|
171
|
+
nav.stuck = Math.hypot(p.x - ox, p.z - oz) < 0.002 ? (nav.stuck ?? 0) + dt : 0;
|
|
172
|
+
}
|
|
173
|
+
|
|
148
174
|
// Crowd avoidance (nav({ crowd: true })): Recast agents steer around other NPCs (smarter than the simple push in npcAvoid.js); the NPC reads the agent velocity
|
|
149
175
|
// and walks itself.
|
|
150
176
|
// The agent belongs to the model (stored on the character) and is deleted with it (dispose in npcView.js); the agent itself does not guarantee identical results
|
|
151
177
|
// after load.
|
|
152
|
-
|
|
178
|
+
// Links: the crowd takes an agent over one by itself, but it runs its own timed line that a game cannot shape, so the NPC crosses the same way as any other (crossLink) and
|
|
179
|
+
// the agent is pulled back to it after. Native Recast does not say which link an agent took, so it is the nearest one starting here. The crowd takes a link 2.25 agent radii
|
|
180
|
+
// short of its start and a crossing runs from where the walker stands, so the NPC first walks the rest (reachLink), or its climb starts a meter off the ladder and cuts through the deck.
|
|
181
|
+
function crowdMove(e, rec, ch, goal, dt) {
|
|
153
182
|
const crowd = e.nav.crowd, p = ch.root.position;
|
|
154
|
-
// nav mesh
|
|
155
|
-
if (ch._agent && ch.
|
|
156
|
-
ch.
|
|
183
|
+
// nav mesh rebuilt, or another nav module: the old agent went with its crowd. The crowd object says so; version numbers count per module and can match
|
|
184
|
+
if (ch._agent && ch._crowd !== crowd) { ch._agent = null; ch._agentGoal = null; ch._linkNext = null; }
|
|
185
|
+
ch._crowd = crowd;
|
|
157
186
|
if (!ch._agent) ch._agent = crowd.addAgent({ x: p.x, y: p.y, z: p.z }, { radius: ch.radius, height: e.movement.height, maxSpeed: ch.speed, maxAcceleration: ch.acceleration * ch.speed });
|
|
158
187
|
const a = ch._agent;
|
|
159
|
-
if (ch._agentGoal !== goal) { a.requestMoveTarget(
|
|
188
|
+
if (ch._agentGoal !== goal) { a.requestMoveTarget(e.nav.point(goal)); ch._agentGoal = goal; }
|
|
189
|
+
const onLink = a.state() === AGENT_ON_LINK;
|
|
190
|
+
if (onLink && !ch._agentOnLink) ch._linkNext = linkStartingAt(e.nav.links, p);
|
|
191
|
+
ch._agentOnLink = onLink; // once per crossing: the agent may still be on its line when a quick game crossing has landed
|
|
192
|
+
if (ch._linkNext) { reachLink(rec, ch, dt); return; }
|
|
160
193
|
const ap = a.position();
|
|
161
|
-
|
|
194
|
+
// blocked, drifted too far or left behind by a crossing (it walked on alone, and an agent already at the goal gives the NPC no way there): pull the agent back
|
|
195
|
+
if (ch._agentAhead || Math.hypot(ap.x - p.x, ap.z - p.z) > AGENT_LEASH) { a.teleport({ x: p.x, y: p.y, z: p.z }); ch._agentGoal = null; ch._agentAhead = false; }
|
|
162
196
|
const v = a.velocity(), sp = Math.hypot(v.x, v.z);
|
|
163
197
|
ch.move(sp > 0.05 ? v.x / ch.speed : 0, sp > 0.05 ? v.z / ch.speed : 0, false, dt);
|
|
164
198
|
}
|
|
199
|
+
|
|
200
|
+
/** Walk to the link the crowd took and start the crossing there, or from where the NPC is stuck */
|
|
201
|
+
function reachLink(rec, ch, dt) {
|
|
202
|
+
const nav = rec.nav, link = ch._linkNext, p = ch.root.position, d = Math.hypot(link.from.x - p.x, link.from.z - p.z);
|
|
203
|
+
if (d >= LINK_REACH && d < LINK_WALK && !(nav.stuck > STUCK_SECONDS)) { stepToward(nav, ch, link.from, dt); return; }
|
|
204
|
+
ch._linkNext = null; nav.stuck = 0; ch._agentAhead = true;
|
|
205
|
+
if (d < LINK_WALK) nav.link = startLink(ch, link);
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
/** The way across the link nearest to p: { id, from, to }, either end of a two-way link */
|
|
209
|
+
function linkStartingAt(links, p) {
|
|
210
|
+
let best = null, bestD = Infinity;
|
|
211
|
+
const take = (id, from, to) => { const d = Math.hypot(from.x - p.x, from.y - p.y, from.z - p.z); if (d < bestD) { bestD = d; best = { id, from, to }; } };
|
|
212
|
+
for (const l of links) { take(l.id, l.from, l.to); if (!l.oneWay) take(l.id, l.to, l.from); }
|
|
213
|
+
return best;
|
|
214
|
+
}
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
// The model side of an NPC (split out of NPC.js): build the Character when the NPC comes near, tear it down when it goes far, run its interact op.
|
|
2
2
|
// Plain functions that take the NPCManager; the manager keeps the maps (_views, _runtime) and avoid, these read and write them.
|
|
3
3
|
import { Character } from './Character.js';
|
|
4
|
+
import { seatFromRecord, vehicleById } from './seat.js';
|
|
4
5
|
|
|
5
6
|
/** Build the model: reads position, motion and animation state from data; attaches an interaction when it has interact */
|
|
6
7
|
export function buildNpcView(m, rec) {
|
|
@@ -8,8 +9,14 @@ export function buildNpcView(m, rec) {
|
|
|
8
9
|
// id: engine.mod('move.speed', { id }) and time.local use the NPC's record id, the same id the game knows it by
|
|
9
10
|
const ch = new Character(e, { ...rec.look, ...rt, speed: rec.speed, id: rec.id });
|
|
10
11
|
ch.npcModel = true; // the model of a world NPC: disposing it (the NPC went far) keeps the NPC's control slot (core/ops/control.js)
|
|
11
|
-
ch.
|
|
12
|
-
ch.
|
|
12
|
+
ch.placeRecord = p => m.get(rec.id).placeAt(p);
|
|
13
|
+
ch._turnRecord = yaw => { ch.face(yaw); const motion = e.world.get(rec.id).motion; if (motion) motion.facing = yaw; }; // a far step or a rebuild reads the facing back from there
|
|
14
|
+
ch._place(rec.position);
|
|
15
|
+
ch.loadMotion(rec.motion); ch._fromRecord(rec); ch.state = ch.stateMark = rec.state;
|
|
16
|
+
const car = vehicleById(e, rec.vehicle);
|
|
17
|
+
if (car) seatFromRecord(ch, car, rec.seat); // no vehicle with that id yet: the record waits, addVehicle answers it (seat.js)
|
|
18
|
+
// after the seat above, as a load writes nothing. Its record may be gone already: a model torn down with it gets out too
|
|
19
|
+
ch._writeSeat = (vehicle, seat) => { if (e.world.get(rec.id)) e.ops.allow(() => e.world.set(rec.id, { vehicle, seat })); };
|
|
13
20
|
let use = null;
|
|
14
21
|
const io = rec.interact;
|
|
15
22
|
if (io && e.interactions) use = e.interactions.add(ch.root, {
|
|
@@ -18,7 +25,7 @@ export function buildNpcView(m, rec) {
|
|
|
18
25
|
// the op's result is the use's result: { ok: false, code } from its can fails interaction.use with that code
|
|
19
26
|
onUse: () => { const r = e.ops.run(io.op, { npc: rec.id, ...io.args }, { source: 'player' }); return r.ok ? r.value : r; },
|
|
20
27
|
});
|
|
21
|
-
m._views.set(ch.root, { ch, use });
|
|
28
|
+
m._views.set(ch.root, { ch, use, useFrom: e.interactions });
|
|
22
29
|
m.avoid.built.add(rec.id);
|
|
23
30
|
return ch.root;
|
|
24
31
|
}
|
|
@@ -32,7 +39,7 @@ export function unbuildNpcView(m, rec, obj) {
|
|
|
32
39
|
const { ch, use } = v;
|
|
33
40
|
use?.remove();
|
|
34
41
|
ch._pathReq?.remove(); // an answer for this model would write a path from where it stood into the record, after far moved it on
|
|
35
|
-
if (ch._agent && ch.
|
|
42
|
+
if (ch._agent && ch._crowd === e.nav?.crowd) ch._crowd.removeAgent(ch._agent);
|
|
36
43
|
const model = rec && m._runtime.get(rec.id)?.model;
|
|
37
44
|
if (model && model.parent === ch.root) ch.root.remove(model);
|
|
38
45
|
ch.dispose();
|
|
@@ -43,9 +50,9 @@ export function unbuildNpcView(m, rec, obj) {
|
|
|
43
50
|
* when the dialogue ends. script defaults to the NPC id. channel 'bubble' plays the script as lines over the NPC's head while the player keeps
|
|
44
51
|
* playing (a shopkeeper's greeting, a guard's warning); default 'main' is the conversation that locks input
|
|
45
52
|
*/
|
|
46
|
-
export function defineTalk(e, m) {
|
|
53
|
+
export function defineTalk(e, ctx, m) {
|
|
47
54
|
if (e.ops.defs.has('npc.talk')) return;
|
|
48
|
-
|
|
55
|
+
ctx.ops.define('npc.talk', {
|
|
49
56
|
desc: 'Talk to an NPC: it stops and faces the actor while its dialogue (script, default the NPC id; channel main | bubble) runs',
|
|
50
57
|
args: { npc: 'string', script: 'string?', channel: { type: 'string', values: ['main', 'bubble'], default: 'main', desc: 'main locks input; bubble = lines over the NPC' } },
|
|
51
58
|
can(e, { npc, channel = 'main' }) {
|
|
@@ -7,35 +7,63 @@
|
|
|
7
7
|
// invalidates engine.commits is dropped (its done never runs), the same as a batch already sent.
|
|
8
8
|
// done stays a callback on purpose: it runs inside the fixed step. A Promise's then runs after the whole frame's steps, so a write there would depend on how many
|
|
9
9
|
// steps a frame ran, and a dropped request would leave the Promise pending forever.
|
|
10
|
-
import { xzOf } from '../../core/base/math.js';
|
|
10
|
+
import { xzOf, yOf } from '../../core/base/math.js';
|
|
11
|
+
import { surfaceOr } from '../../core/scene/ground.js';
|
|
11
12
|
import { solveBatch, pathHandler, astarDefaults, RES, TILE, tileOf } from './pathJob.js';
|
|
12
13
|
import { codedError } from '../../core/base/errorHints.js';
|
|
14
|
+
import { withHeights } from './moveHelpers.js';
|
|
13
15
|
|
|
14
16
|
/** 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 */
|
|
15
17
|
const PATH_LAG = 4;
|
|
16
18
|
/** A cached ground raster tile is reused for this many fixed steps (5 s), then sampled again: streamed terrain may have added trees meanwhile */
|
|
17
19
|
const TILE_TTL = 300;
|
|
20
|
+
/** Floors looked for under a cell's top one: only a ground that answers something new for every height ever reaches it */
|
|
21
|
+
const MAX_FLOORS = 16;
|
|
18
22
|
const NO_DONE = 'characters.findPathAsync(from, to, done): done must be a function (path, status) => { ... }; it runs on a fixed step when the path is ready';
|
|
19
23
|
|
|
24
|
+
/** A position in any form as the plain point a path source reads and writes */
|
|
25
|
+
const point = p => { const [x, z] = xzOf(p); return { x, y: yOf(p), z }; };
|
|
26
|
+
|
|
27
|
+
/**
|
|
28
|
+
* What the characters.path rule says for one request, as a search answer; null when the built-in search answers ('walk'). A game's source returns a list of points, null or an empty list for no way, 'walk' to fall back.
|
|
29
|
+
* The points are copied: walkers fill in heights and eat the path as they go, and the list may be one the game keeps and hands to everyone.
|
|
30
|
+
* Why it runs on the main thread at the due step, also for findPathAsync: a game's function cannot go to a worker, and done must still come on a fixed step
|
|
31
|
+
*/
|
|
32
|
+
export function sourcePath(e, rule, from, to, o) {
|
|
33
|
+
const d = rule.decide(o.id, { from: point(from), to: point(to), o });
|
|
34
|
+
if (d === 'walk') return null;
|
|
35
|
+
if (d && !Array.isArray(d)) throw codedError('character-option', `rule 'characters.path': a path source returns a list of { x, y?, z } points, null or 'walk', got ${JSON.stringify(d)}`);
|
|
36
|
+
return d?.length ? { status: 'ok', path: d.map(p => ({ ...p, ...point(p) })) } : { status: 'noPath', path: null };
|
|
37
|
+
}
|
|
38
|
+
|
|
20
39
|
/** @internal */
|
|
21
40
|
export class AsyncPaths {
|
|
22
|
-
constructor(e) {
|
|
41
|
+
constructor(e, rule) {
|
|
23
42
|
this.e = e;
|
|
43
|
+
this.rule = rule;
|
|
24
44
|
this.queue = [];
|
|
25
45
|
this.perStep = 32;
|
|
26
46
|
this.lane = null;
|
|
27
|
-
this.sent = {
|
|
47
|
+
this.sent = { from: null, meshes: new Map(), ver: -1 }; // what the workers mirror, and of which provider: mesh size -> its revision, collision version
|
|
48
|
+
this.turn = 0; // bumps with every provider
|
|
28
49
|
this.tiles = new Map(); // 'tx:tz' -> { data, trees, at, bv }
|
|
29
50
|
}
|
|
30
51
|
request(from, to, done, o = {}) {
|
|
31
52
|
if (typeof done !== 'function') throw codedError('character-option', NO_DONE);
|
|
32
53
|
const [sx, sz] = xzOf(from), [gx, gz] = xzOf(to);
|
|
33
|
-
const h = { sx, sz, gx, gz, o, done, epoch: this.e.commits.epoch, canceled: false, remove() { h.canceled = true; } };
|
|
54
|
+
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; } };
|
|
34
55
|
this.queue.push(h);
|
|
35
56
|
return h;
|
|
36
57
|
}
|
|
58
|
+
/** The module is unloading: nothing queued or on its way may answer, the world it was asked in has no characters now. A lane is the engine's: it ends with engine.threads */
|
|
59
|
+
stop() { this.queue.length = 0; this.stopped = true; }
|
|
37
60
|
/** Which walkable state answers now: navmesh revision, collision version, or nothing */
|
|
38
|
-
key() {
|
|
61
|
+
key() {
|
|
62
|
+
const e = this.e, from = e.nav?.ready ? e.nav : e.collision;
|
|
63
|
+
// 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
|
+
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}` : '-';
|
|
66
|
+
}
|
|
39
67
|
/** Each fixed step (characters fixed): send up to perStep queued requests as one batch */
|
|
40
68
|
flush() {
|
|
41
69
|
const list = [];
|
|
@@ -45,47 +73,58 @@ export class AsyncPaths {
|
|
|
45
73
|
const e = this.e, T = e.threads, batch = this.build(list);
|
|
46
74
|
const t = e.commits.request({ lag: PATH_LAG, fallback: () => null, apply: r => this.land(batch, list, r) });
|
|
47
75
|
if (!T.size || batch.key === '-') return;
|
|
48
|
-
this.mirror(batch
|
|
76
|
+
this.mirror(batch);
|
|
49
77
|
this.lane.run(batch).then(r => t.resolve(r), () => {}); // a failed run is ignored: land() computes the same answer here
|
|
50
78
|
}
|
|
51
79
|
/** Plain-data batch: everything the solver needs that the worker does not mirror */
|
|
52
80
|
build(list) {
|
|
53
|
-
const e = this.e, key = this.key(), mode = key[0] === 'n' ? 'nav' : key[0] === 'g' ? 'grid' : 'none', tiles = {}, trees = [], seen = new Set();
|
|
81
|
+
const e = this.e, key = this.key(), mode = key[0] === 'n' ? 'nav' : key[0] === 'g' ? 'grid' : 'none', tiles = {}, heights = {}, lower = {}, trees = [], seen = new Set();
|
|
54
82
|
const take = (tk, tx, tz) => {
|
|
55
83
|
if (tiles[tk]) return;
|
|
56
84
|
const c = this.tile(tk, tx, tz); tiles[tk] = c.data;
|
|
85
|
+
heights[tk] = c.top;
|
|
86
|
+
if (c.lower) lower[tk] = c.lower;
|
|
57
87
|
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]); } }
|
|
58
88
|
};
|
|
59
|
-
const reqs = list.map(({ sx, sz, gx, gz, o }) => {
|
|
60
|
-
if (mode === 'nav') return { mode,
|
|
89
|
+
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 }; }
|
|
61
91
|
if (mode === 'none') return { mode };
|
|
62
92
|
const radius = o.radius ?? e.movement.radius, dflt = astarDefaults(radius), step = o.step ?? dflt.step, maxNodes = o.maxNodes ?? dflt.maxNodes;
|
|
63
93
|
// A* may wander this far beyond the start-goal box; bounded by how far maxNodes cells can reach
|
|
64
94
|
const m = Math.min(step * Math.sqrt(maxNodes / Math.PI), 16 + Math.hypot(gx - sx, gz - sz) / 2);
|
|
65
95
|
for (let tx = tileOf(Math.min(sx, gx) - m); tx <= tileOf(Math.max(sx, gx) + m); tx++)
|
|
66
96
|
for (let tz = tileOf(Math.min(sz, gz) - m); tz <= tileOf(Math.max(sz, gz) + m); tz++) take(tx + ':' + tz, tx, tz);
|
|
67
|
-
|
|
97
|
+
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 };
|
|
68
99
|
});
|
|
69
|
-
return { type: 'batch', key, reqs, tiles, trees };
|
|
100
|
+
return { type: 'batch', key, reqs, tiles, heights, lower, trees };
|
|
70
101
|
}
|
|
71
102
|
/**
|
|
72
103
|
* One tile of the ground, sampled here (height / water / slope and terrain trees are main-thread functions) and cached for TILE_TTL steps:
|
|
73
|
-
* data =
|
|
104
|
+
* data = can the top floor be walked, top = its height, lower = the floors under it by cell index, { y, ok } each (null when no cell has one), trees = [x, z, r, ...] of the ground's colliders around the tile.
|
|
74
105
|
*/
|
|
75
106
|
tile(k, tx, tz) {
|
|
76
|
-
const e = this.e
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
107
|
+
const e = this.e;
|
|
108
|
+
// another collision module counts from zero, so an equal number says nothing; a new playthrough restarts the tick, so a negative age is an old tile, not a young one
|
|
109
|
+
const from = e.collision;
|
|
110
|
+
if (from !== this.tilesOf) { this.tiles.clear(); this.tilesOf = from; } // the issuer beside what it issued (architecture 8.2), compared, never called
|
|
111
|
+
const c = this.tiles.get(k), bv = e.collision.blockedVersion, age = c ? e.time.tick - c.at : -1;
|
|
112
|
+
if (c && c.bv === bv && age >= 0 && age < TILE_TTL) return c;
|
|
113
|
+
const data = new Uint8Array(TILE * TILE), top = new Float32Array(TILE * TILE), col = e.collision, trees = [], span = TILE * RES, body = e.movement.height;
|
|
114
|
+
let lower = null;
|
|
80
115
|
// addBlocked fields are functions and cannot go to a worker: they are sampled into this same raster (the worker sees blocked cells as unwalkable).
|
|
81
116
|
// A cell counts as blocked if fn is true at its centre or on a ring of half a cell (blockedAt), so a 1 m cell never hides a thin river; bounds skip the sampling outside.
|
|
82
117
|
for (let j = 0; j < TILE; j++) for (let i = 0; i < TILE; i++) {
|
|
83
118
|
const x = (tx * TILE + i) * RES, z = (tz * TILE + j) * RES;
|
|
84
|
-
|
|
119
|
+
const c = j * TILE + i, free = !col.blockedAt(x, z, RES / 2), t = e.surface(x, z);
|
|
120
|
+
data[c] = free && col.groundWalkable(x, z) ? 1 : 0;
|
|
121
|
+
top[c] = t;
|
|
122
|
+
// the ground gives floors by height only, so go down it: asked from a body under a floor (nearer is the same floor, and a ground's step is its own) it answers the next one, or the same one when that was the lowest
|
|
123
|
+
for (let n = 0, y = t, b; n < MAX_FLOORS && (b = e.surface(x, z, y - body)) < y; n++, y = b) ((lower ??= {})[c] ??= []).push({ y: b, ok: free && col.groundWalkable(x, z, b) ? 1 : 0 });
|
|
85
124
|
}
|
|
86
125
|
// every collider that can touch a point of the tile: half diagonal + the largest character radius we expect + 1 (the same reach walkableAt uses)
|
|
87
126
|
e.ground.forEachCollider?.((tx + 0.5) * span, (tz + 0.5) * span, span * 0.71 + 3, (x, z, r) => { trees.push(x, z, r); });
|
|
88
|
-
const v = { data, trees, at: e.time.tick, bv };
|
|
127
|
+
const v = { data, top, lower, trees, at: e.time.tick, bv };
|
|
89
128
|
this.tiles.set(k, v);
|
|
90
129
|
if (this.tiles.size > 4096) for (const [kk, o] of this.tiles) if (e.time.tick - o.at >= TILE_TTL) this.tiles.delete(kk);
|
|
91
130
|
return v;
|
|
@@ -99,21 +138,32 @@ export class AsyncPaths {
|
|
|
99
138
|
}
|
|
100
139
|
}
|
|
101
140
|
/** Bring the workers' mirror up to the state this batch is tagged with (broadcasts arrive before the batch: one message queue per worker) */
|
|
102
|
-
mirror(key) {
|
|
103
|
-
const e = this.e;
|
|
141
|
+
mirror({ key, reqs }) {
|
|
142
|
+
const e = this.e, sent = this.sent.meshes;
|
|
104
143
|
this.lane ??= e.threads.lane({ create: () => new Worker(new URL('./pathWorker.js', import.meta.url), { type: 'module' }), local: pathHandler });
|
|
105
|
-
if (key[0] === 'n'
|
|
144
|
+
if (key[0] === 'n') for (const size of new Set(reqs.map(q => q.size))) {
|
|
145
|
+
const m = e.nav.meshes.get(size);
|
|
146
|
+
if (sent.get(size) === e.nav.revision || !m.navMesh) continue;
|
|
147
|
+
sent.set(size, e.nav.revision);
|
|
148
|
+
this.lane.broadcast({ type: 'mesh', size, version: e.nav.version, data: e.nav.exportMesh(m), links: m.links }, 'mesh' + size);
|
|
149
|
+
}
|
|
106
150
|
if (key[0] === 'g' && this.sent.ver !== e.collision.version) {
|
|
107
151
|
this.sent.ver = e.collision.version;
|
|
108
152
|
const items = [];
|
|
109
|
-
e.collision.forEachStatic((type, o) => items.push(type === 'box' ? { x: o.x, z: o.z, 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 }));
|
|
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 }));
|
|
110
154
|
this.lane.broadcast({ type: 'colliders', items }, 'colliders');
|
|
111
155
|
}
|
|
112
156
|
}
|
|
113
157
|
/** Due step: worker answer if it arrived and the walkable state is unchanged, else the same solver here on the current state */
|
|
114
158
|
land(batch, list, r) {
|
|
159
|
+
if (this.stopped) return;
|
|
115
160
|
const e = this.e, key = this.key();
|
|
116
|
-
if (!r || key !== batch.key) r = solveBatch(key === batch.key ? batch : this.build(list), {
|
|
117
|
-
list.forEach((h, i) => {
|
|
161
|
+
if (!r || key !== batch.key) r = solveBatch(key === batch.key ? batch : this.build(list), { meshes: e.nav?.meshes, grid: e.collision?.grid });
|
|
162
|
+
list.forEach((h, i) => {
|
|
163
|
+
if (h.canceled) return;
|
|
164
|
+
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
|
+
if (a.path) withHeights(e, a.path, from, to);
|
|
166
|
+
h.done(a.path, a.status);
|
|
167
|
+
});
|
|
118
168
|
}
|
|
119
169
|
}
|
|
@@ -1,60 +1,77 @@
|
|
|
1
1
|
// Async pathfinding batch solver: the same code answers in the path worker (pathWorker.js), in the lane's main-thread fallback,
|
|
2
2
|
// and in engine.commits' fallback when a worker reply is late (pathAsync.js). Worker-safe: no three.js, no engine objects.
|
|
3
|
-
// A batch carries everything that is not mirrored in the worker: start / goal (with ground heights), and for A* a raster of the ground half of walkability.
|
|
4
|
-
// The worker mirrors the rest: the navmesh (imported from the bytes the nav module exports) and the collision module's colliders (rebuilt into the same grid).
|
|
3
|
+
// A batch carries everything that is not mirrored in the worker: start / goal (with ground heights), and for A* a raster of the ground half of walkability, every floor of it.
|
|
4
|
+
// The worker mirrors the rest: the navmesh of every body size a batch asked for (imported from the bytes the nav module exports) and the collision module's colliders (rebuilt into the same grid).
|
|
5
5
|
import { findPath as astar, astarDefaults } from './astar.js';
|
|
6
6
|
export { astarDefaults };
|
|
7
7
|
import { CollisionGrid, gridBlocks } from '../collision/grid.js';
|
|
8
8
|
import { navSearch } from '../nav/navPath.js';
|
|
9
|
+
import { layerUnder } from '../../core/scene/floor.js';
|
|
9
10
|
|
|
10
|
-
/** Ground
|
|
11
|
+
/** Ground raster (height, water, slope): RES-meter cells, TILE x TILE cells per tile, keyed `${tx}:${tz}`; a cell's top floor is in flat arrays, the floors under it, few cells have any, in a sparse list */
|
|
11
12
|
export const RES = 1, TILE = 32;
|
|
12
13
|
export const tileOf = v => Math.floor(Math.round(v / RES) / TILE);
|
|
13
14
|
|
|
15
|
+
const TOP = { y: 0, ok: 0 }; // the answer for a cell's top floor: the search asks for every node, so it must not allocate
|
|
16
|
+
|
|
14
17
|
/**
|
|
15
|
-
*
|
|
16
|
-
*
|
|
18
|
+
* The floor of a batch's ground a walker at height y comes to at (x, z), { y, ok } (nearest cell), the snapshot of what engine.surface(x, z, y) and the ground half of walkableAt
|
|
19
|
+
* say on the main thread: no y is the top floor. Null outside the sent tiles, which counts as blocked: both sides see the same tiles.
|
|
17
20
|
*/
|
|
18
|
-
function
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
21
|
+
function floorAt({ tiles, heights, lower }, x, z, y, climb) {
|
|
22
|
+
const ix = Math.round(x / RES), iz = Math.round(z / RES), tx = Math.floor(ix / TILE), tz = Math.floor(iz / TILE), k = tx + ':' + tz, ok = tiles[k];
|
|
23
|
+
if (!ok) return null;
|
|
24
|
+
const i = (iz - tz * TILE) * TILE + (ix - tx * TILE), top = heights[k][i], under = y === undefined || top <= y + climb ? undefined : lower[k]?.[i];
|
|
25
|
+
if (under) return layerUnder(under, y + climb);
|
|
26
|
+
TOP.y = top; TOP.ok = ok[i];
|
|
27
|
+
return TOP;
|
|
28
|
+
}
|
|
29
|
+
|
|
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
|
+
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));
|
|
33
|
+
}
|
|
34
|
+
|
|
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 */
|
|
36
|
+
function snapshotFloor(batch, q) {
|
|
37
|
+
return (x, z, y) => { const f = floorAt(batch, x, z, y, q.climb); return !f || f.y === -Infinity ? y : f.y; };
|
|
25
38
|
}
|
|
26
39
|
|
|
27
40
|
/**
|
|
28
41
|
* Answer every request of a batch: [{ status, path }...] in request order.
|
|
29
|
-
* @param {{ reqs: any[], tiles: Record<string, Uint8Array
|
|
30
|
-
* @param {{
|
|
42
|
+
* @param {{ reqs: any[], tiles: Record<string, Uint8Array>, heights: Record<string, Float32Array>, lower: Record<string, Record<number, { y: number, ok: number }[]>> }} batch
|
|
43
|
+
* @param {{ meshes: Map<any, any>, grid: any }} ctx navmeshes (query, navMesh, links) by size and collider grid (live ones on the main thread, mirrored ones in the worker)
|
|
31
44
|
*/
|
|
32
45
|
export function solveBatch(batch, ctx) {
|
|
33
46
|
let trees = null;
|
|
34
47
|
return batch.reqs.map(q => {
|
|
35
|
-
if (q.mode === 'nav') return navSearch(ctx.
|
|
48
|
+
if (q.mode === 'nav') return navSearch(ctx.meshes.get(q.size), q.s, q.g, q.reach, q.body);
|
|
36
49
|
if (q.mode !== 'grid') return { status: 'notReady', path: null };
|
|
37
50
|
if (!trees) { trees = new CollisionGrid(); for (let i = 0; i < batch.trees.length; i += 3) trees.add({ x: batch.trees[i], z: batch.trees[i + 1], r: batch.trees[i + 2] }, false); }
|
|
38
|
-
const
|
|
51
|
+
const floor = q.s.y === undefined ? undefined : snapshotFloor(batch, q); // undefined: no height to follow, A* keeps its default
|
|
52
|
+
const path = astar(snapshotWalkable(batch, q, ctx.grid, trees), q.s.x, q.s.z, q.g.x, q.g.z, { ...q, y: q.s.y, goalY: q.g.y, floor });
|
|
39
53
|
return { status: q.navPending ? 'notReady' : path ? 'ok' : 'noPath', path };
|
|
40
54
|
});
|
|
41
55
|
}
|
|
42
56
|
|
|
43
57
|
/**
|
|
44
|
-
* Lane handler: { type: 'mesh', data } (navmesh bytes
|
|
58
|
+
* Lane handler: { type: 'mesh', size, version, data, links } (the navmesh of a body size as bytes, the links its connections index; a new version drops the sizes of the old mesh), { type: 'colliders', items }, { type: 'batch', reqs, tiles } → results.
|
|
45
59
|
* @param {() => Promise<any> | any} load gives the Recast module: the worker passes its static import (a worker bundle cannot split chunks);
|
|
46
60
|
* the main-thread fallback imports it on demand so games without nav never download it
|
|
47
61
|
*/
|
|
48
62
|
export function pathHandler(load = () => import('@recast-navigation/core')) {
|
|
49
|
-
const ctx = {
|
|
50
|
-
let lib = null,
|
|
63
|
+
const ctx = { meshes: new Map(), grid: null };
|
|
64
|
+
let lib = null, chain = Promise.resolve(), version = -1;
|
|
51
65
|
// Recast loads asynchronously; every message waits for the ones before it, so a batch always sees the mesh / colliders sent before it
|
|
52
66
|
const then = fn => { const p = chain.then(fn); chain = p.catch(() => {}); return p; }; // one failed message must not block the rest
|
|
53
67
|
return msg => {
|
|
54
68
|
if (msg.type === 'mesh') return void then(async () => {
|
|
55
69
|
if (!lib) { const m = await load(); await m.init(); lib = m; }
|
|
56
|
-
ctx.query
|
|
57
|
-
if (msg.
|
|
70
|
+
const drop = size => { const m = ctx.meshes.get(size); m?.query.destroy(); m?.navMesh.destroy(); ctx.meshes.delete(size); };
|
|
71
|
+
if (msg.version !== version) { [...ctx.meshes.keys()].forEach(drop); version = msg.version; }
|
|
72
|
+
drop(msg.size);
|
|
73
|
+
const navMesh = lib.importNavMesh(msg.data).navMesh;
|
|
74
|
+
ctx.meshes.set(msg.size, { navMesh, query: new lib.NavMeshQuery(navMesh), links: msg.links });
|
|
58
75
|
});
|
|
59
76
|
if (msg.type === 'colliders') return void then(() => { const g = new CollisionGrid(); for (const it of msg.items) g.add(it, it.box); ctx.grid = g; });
|
|
60
77
|
return then(() => solveBatch(msg, ctx));
|