threedog 0.1.0 → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/core/Animator.js +1 -0
- package/core/Assets.js +16 -0
- package/core/DebugOverrides.js +143 -0
- package/core/Describe.js +14 -3
- package/core/Engine.js +32 -69
- package/core/Events.js +59 -1
- package/core/I18n.js +2 -2
- package/core/Inspect.js +12 -32
- package/core/InspectScene.js +7 -3
- package/core/MaterialInfo.js +32 -0
- package/core/Ops.js +43 -59
- package/core/Saves.js +5 -4
- package/core/UrlState.js +3 -2
- package/core/Vars.js +1 -0
- package/core/Views.js +49 -0
- package/core/actor.js +2 -2
- package/core/assetReport.js +83 -0
- package/core/catalog.js +169 -0
- package/core/checks.js +67 -0
- package/core/claims.js +51 -0
- package/core/debugView.js +76 -0
- package/core/describeRender.js +45 -0
- package/core/describeText.js +11 -4
- package/core/errorCodes.js +33 -0
- package/core/errorHints.js +6 -1
- package/core/holds.js +106 -0
- package/core/lifecycle.js +1 -0
- package/core/lightWatch.js +23 -3
- package/core/look/coreParts.js +112 -0
- package/core/look/layers.js +136 -0
- package/core/look/part.js +173 -0
- package/core/look/report.js +79 -0
- package/core/look/write.js +86 -0
- package/core/loop.js +15 -14
- package/core/modules.js +19 -5
- package/core/opsAtomic.js +31 -0
- package/core/opsCheck.js +25 -14
- package/core/opsFail.js +20 -0
- package/core/opsHistory.js +6 -6
- package/core/opsRun.js +77 -0
- package/core/params.js +132 -0
- package/core/renamed.js +21 -0
- package/core/saveApply.js +2 -2
- package/core/sceneMethods.js +9 -34
- package/core/services.js +73 -0
- package/core/startup.js +3 -1
- package/core/styleParts.js +2 -2
- package/core/thingExplain.js +68 -0
- package/core/thingOps.js +35 -24
- package/core/things.js +15 -1
- package/core/util.js +11 -0
- package/core/validate.js +23 -7
- package/docs/AI.md +83 -109
- package/docs/API.md +7 -8
- package/docs/CODEMAP.md +63 -51
- package/docs/COMMANDS.md +17 -5
- package/docs/CONVENTIONS.md +17 -6
- package/docs/THREE.md +3 -3
- package/docs/api/assets.md +2 -0
- package/docs/api/characters.md +2 -0
- package/docs/api/collision.md +4 -0
- package/docs/api/content.md +1 -0
- package/docs/api/engine.md +20 -11
- package/docs/api/events.md +5 -1
- package/docs/api/post.md +5 -4
- package/docs/api/saves.md +2 -1
- package/docs/api/sky.md +3 -3
- package/docs/api/style.md +3 -3
- package/docs/api/tools.md +2 -0
- package/docs/api/weather.md +1 -1
- package/docs/recipes/02-npc.md +16 -0
- package/docs/recipes/03-items-pickups.md +1 -1
- package/docs/recipes/06-clock-events.md +13 -0
- package/docs/recipes/07-flow-scenes-pause.md +4 -0
- package/docs/recipes/08-weather-sky.md +1 -1
- package/docs/recipes/09-style-pack.md +5 -5
- package/docs/recipes/12-navmesh.md +22 -0
- package/docs/recipes/13-animation.md +3 -0
- package/docs/recipes/15-perf.md +1 -1
- package/docs/recipes/16-dev-bridge.md +51 -17
- package/docs/recipes/21-camera.md +51 -2
- package/docs/recipes/23-ops.md +45 -9
- package/docs/recipes/27-net.md +1 -1
- package/docs/recipes/29-grid.md +1 -1
- package/docs/recipes/34-environment-lighting.md +9 -8
- package/docs/recipes/38-environment-look-hooks.md +8 -6
- package/docs/recipes/40-scene.md +29 -0
- package/docs/recipes/41-thing-registry.md +29 -0
- package/docs/recipes/43-shader-patches-surface-looks.md +2 -0
- package/docs/recipes/44-water-weather-look-hooks.md +6 -4
- package/docs/recipes/45-cascaded-shadows.md +1 -1
- package/docs/recipes/46-blender-art-route.md +22 -0
- package/docs/recipes/48-make-material.md +70 -0
- package/docs/recipes/49-game-module-contract.md +71 -0
- package/docs/recipes/50-own-renderer.md +12 -0
- package/docs/recipes/51-capability-catalog.md +63 -0
- package/docs/recipes/52-look.md +108 -0
- package/examples/action/GAMEMAP.md +5 -5
- package/examples/action/content/index.js +2 -1
- package/examples/action/content/views.js +6 -0
- package/examples/sheepisland/GAMEMAP.md +2 -3
- package/examples/styletest/GAMEMAP.md +3 -3
- package/examples/styletest/main.js +1 -1
- package/examples/styletest/panel.js +3 -3
- package/examples/world/GAMEMAP.md +3 -3
- package/index.d.ts +27 -0
- package/index.js +3 -1
- package/llms.txt +5 -0
- package/modules/ambience/Ambience.js +5 -2
- package/modules/camera/FirstPersonCamera.js +3 -5
- package/modules/camera/FixedCamera.js +19 -12
- package/modules/camera/FollowCamera.js +14 -8
- package/modules/camera/RtsCamera.js +3 -5
- package/modules/camera/common.js +40 -10
- package/modules/camera/index.js +1 -1
- package/modules/camera/projection.js +34 -0
- package/modules/characters/Character.js +29 -17
- package/modules/characters/astar.js +14 -7
- package/modules/characters/index.js +6 -3
- package/modules/characters/movers/simple.js +6 -1
- package/modules/characters/npcSim.js +8 -2
- package/modules/characters/pathAsync.js +12 -6
- package/modules/characters/pathJob.js +2 -1
- package/modules/characters/proceduralRig.js +5 -1
- package/modules/characters/useModel.js +22 -0
- package/modules/characters/walkTo.js +58 -0
- package/modules/collision/Collision.js +102 -4
- package/modules/content/explain.js +13 -0
- package/modules/content/index.js +2 -0
- package/modules/content/loader.js +3 -0
- package/modules/content/rules.js +1 -0
- package/modules/debug/DebugPanel.js +11 -5
- package/modules/entities/Entities.js +6 -2
- package/modules/flow/index.js +5 -2
- package/modules/gameplay/Dialogue.js +5 -2
- package/modules/gameplay/Interactions.js +12 -2
- package/modules/gameplay/Inventory.js +21 -11
- package/modules/gameplay/Quests.js +13 -3
- package/modules/gameplay/pickups.js +5 -3
- package/modules/grid/Layer.js +1 -1
- package/modules/grid/index.js +1 -1
- package/modules/grid/tiles.js +9 -5
- package/modules/hlod/index.js +5 -2
- package/modules/hud/index.js +5 -2
- package/modules/level/index.js +5 -3
- package/modules/lights/index.js +5 -2
- package/modules/music/Music.js +6 -2
- package/modules/nav/index.js +5 -3
- package/modules/net/Client.js +4 -3
- package/modules/net/Host.js +2 -2
- package/modules/net/index.js +5 -3
- package/modules/particles/Particles.js +1 -1
- package/modules/photo/Photo.js +10 -7
- package/modules/rigid/RigidBodies.js +5 -2
- package/modules/settings/Settings.js +6 -3
- package/modules/settings/apply.js +2 -1
- package/modules/sky/Sky.js +21 -19
- package/modules/sky/cascades.js +6 -6
- package/modules/sky/domeLayers.js +1 -1
- package/modules/sky/environment.js +39 -13
- package/modules/sky/fog.js +9 -6
- package/modules/sky/frame.js +4 -3
- package/modules/sky/look.js +3 -2
- package/modules/sky/lookFog.js +80 -0
- package/modules/sky/lookShadow.js +50 -0
- package/modules/sky/lookSky.js +108 -0
- package/modules/sky/shader.js +2 -2
- package/modules/sky/shadow.js +4 -10
- package/modules/sky/skyModule.js +4 -3
- package/modules/terrain/ChunkManager.js +2 -33
- package/modules/terrain/chunkLevels.js +40 -0
- package/modules/terrain/index.js +10 -2
- package/modules/terrain/lookGround.js +61 -0
- package/modules/timeline/Timeline.js +7 -3
- package/modules/timeline/Tween.js +3 -7
- package/modules/timeline/shots.js +6 -4
- package/modules/triggers/index.js +9 -2
- package/modules/vegetation/Vegetation.js +2 -1
- package/modules/vegetation/index.js +6 -3
- package/modules/vegetation/lookWind.js +37 -0
- package/modules/water/Water.js +19 -3
- package/modules/water/look.js +80 -0
- package/modules/weather/Weather.js +22 -31
- package/modules/weather/look.js +75 -0
- package/modules/weather/particles.js +1 -1
- package/modules/weather/strings.js +15 -0
- package/modules/world/explain.js +11 -0
- package/modules/world/index.js +11 -4
- package/modules/world/thingSource.js +44 -0
- package/package.json +1 -1
- package/render/PostFX.js +48 -51
- package/render/effects.js +4 -2
- package/render/fuse.js +12 -0
- package/render/lights.js +4 -2
- package/render/lookSurface.js +161 -0
- package/render/materials.js +27 -10
- package/render/postLook.js +86 -0
- package/render/surface.js +3 -1
- package/types/core.d.ts +216 -24
- package/types/gameplay.d.ts +10 -0
- package/types/generated/core/DebugOverrides.d.ts +52 -0
- package/types/generated/core/Events.d.ts +43 -0
- package/types/generated/core/Ops.d.ts +62 -21
- package/types/generated/core/Saves.d.ts +1 -0
- package/types/generated/core/Views.d.ts +33 -0
- package/types/generated/modules/debug/DebugPanel.d.ts +2 -2
- package/types/generated/modules/grid/Layer.d.ts +1 -0
- package/types/generated/modules/sky/Sky.d.ts +10 -17
- package/types/generated/modules/weather/Weather.d.ts +5 -15
- package/types/generated/render/PostFX.d.ts +20 -23
- package/types/generated/render/materials.d.ts +10 -0
- package/types/physics.d.ts +8 -0
- package/types/style.d.ts +16 -6
- package/ui/Parts.js +6 -2
- package/ui/UI.js +1 -1
- package/ui/defaults.js +1 -1
- package/docs/api/debug.md +0 -10
package/modules/camera/common.js
CHANGED
|
@@ -7,14 +7,16 @@
|
|
|
7
7
|
// forward() / right() unit directions {x, z} on the XZ plane; player movement uses them
|
|
8
8
|
// update(dt, input) per-frame camera update
|
|
9
9
|
//
|
|
10
|
-
// Cutscene takeover contract: engine.cameraOverride
|
|
11
|
-
// A cutscene
|
|
12
|
-
// While
|
|
13
|
-
//
|
|
10
|
+
// Cutscene takeover contract: engine.takeCamera(owner, { focus? }) -> { remove() } (core/holds.js); engine.cameraOverride is the holder in charge.
|
|
11
|
+
// A cutscene, a named view or a photo mode that places the camera itself takes it; several can hold it, the latest is in charge.
|
|
12
|
+
// While anyone holds it the camera module leaves the camera alone; with a focus, engine.focus is set to it (the world loads around it).
|
|
13
|
+
// When the last holder removes its claim the camera module resumes from its previous state. cameraOverride itself is read-only.
|
|
14
14
|
import * as THREE from 'three';
|
|
15
15
|
import { ownedProps } from '../../core/validate.js';
|
|
16
|
+
import { readParams, keysSchema } from '../../core/params.js';
|
|
17
|
+
import { setProjection } from './projection.js';
|
|
16
18
|
|
|
17
|
-
const STRINGS = { ownedHint: 'To place the camera yourself,
|
|
19
|
+
const STRINGS = { ownedHint: 'To place the camera yourself, take it: const cam = engine.takeCamera(\'me\'); ... cam.remove() when done' };
|
|
18
20
|
|
|
19
21
|
/** True during a cutscene takeover, and updates engine.focus from the focus the owner supplied */
|
|
20
22
|
function applyOverride(e) {
|
|
@@ -51,16 +53,38 @@ export function clickToLock(rig, switched) {
|
|
|
51
53
|
const e = rig.engine, canvas = e.renderer.domElement;
|
|
52
54
|
const wouldLock = () => rig.pointerLock && !e.cameraOverride && e.input.enabled
|
|
53
55
|
&& !matchMedia('(pointer: coarse)').matches && document.pointerLockElement !== canvas;
|
|
56
|
+
// Last outcome, shown by describe(): the drag fallback stays, but a refused lock is no longer silent
|
|
57
|
+
const st = rig.lockState = { configured: !!rig.pointerLock, requested: false, locked: document.pointerLockElement === canvas, lastError: null,
|
|
58
|
+
supported: typeof canvas.requestPointerLock === 'function' };
|
|
59
|
+
const fail = err => { st.locked = false; st.lastError = String(err?.message ?? err ?? 'refused'); st.failedAt = e.elapsed; };
|
|
54
60
|
const lock = () => {
|
|
61
|
+
st.configured = !!rig.pointerLock;
|
|
55
62
|
if (!wouldLock()) return;
|
|
56
|
-
|
|
63
|
+
st.requested = true;
|
|
64
|
+
try { const r = canvas.requestPointerLock?.(); r?.catch?.(fail); } catch (err) { fail(err); } // browser refused the lock: fall back to dragging
|
|
57
65
|
};
|
|
58
66
|
rig._off = new AbortController();
|
|
67
|
+
const sig = { signal: AbortSignal.any([e.signal, rig._off.signal]) };
|
|
68
|
+
document.addEventListener('pointerlockchange', () => { st.locked = document.pointerLockElement === canvas; if (st.locked) st.lastError = null; else st.requested = false; }, sig);
|
|
69
|
+
document.addEventListener('pointerlockerror', () => fail('pointerlockerror (browser refused: needs a user gesture, or the page lost focus)'), sig);
|
|
59
70
|
const swallow = () => rig.swallowLockClick !== false && wouldLock();
|
|
60
71
|
e.input.swallowLockClick = swallow; rig._swallow = swallow;
|
|
61
|
-
canvas.addEventListener('click', lock,
|
|
72
|
+
canvas.addEventListener('click', lock, sig); // removed on switch-away or engine.dispose()
|
|
62
73
|
if (switched) lock(); // a runtime switch (a key press counts as a gesture) locks at once
|
|
63
74
|
}
|
|
75
|
+
/**
|
|
76
|
+
* The pointer-lock state machine for describe(): off (not configured) / unsupported / locked / refused (browser denied) / requesting / waiting-click;
|
|
77
|
+
* plus covered (an element other than the canvas sits at its centre, so a click never reaches it), cameraOverride (a takeover blocks locking) and the last failure
|
|
78
|
+
* @internal
|
|
79
|
+
*/
|
|
80
|
+
export function lockView(e, st) {
|
|
81
|
+
if (!st?.configured) return { state: 'off' };
|
|
82
|
+
const state = !st.configured ? 'off' : !st.supported ? 'unsupported' : st.locked ? 'locked' : st.lastError ? 'refused' : st.requested ? 'requesting' : 'waiting-click';
|
|
83
|
+
const c = e.renderer.domElement, r = c.getBoundingClientRect();
|
|
84
|
+
const top = typeof document.elementFromPoint === 'function' ? document.elementFromPoint(r.left + r.width / 2, r.top + r.height / 2) : null;
|
|
85
|
+
return { ...st, state, covered: top && top !== c ? (top.id ? '#' + top.id : top.className ? '.' + String(top.className).split(' ')[0] : top.tagName.toLowerCase()) : null,
|
|
86
|
+
cameraOverride: e.cameraOverride?.owner ?? null, lastFailure: st?.lastError ? { reason: st.lastError, agoSec: Math.round((e.elapsed - st.failedAt) / 100) / 10 } : null };
|
|
87
|
+
}
|
|
64
88
|
/** Release the mouse lock; stop listening for clicks too when switched away (call from onExit; from onOverride with keepListening) */
|
|
65
89
|
export function releaseLock(rig, keepListening = false) {
|
|
66
90
|
if (!keepListening) { rig._off?.abort(); if (rig.engine.input.swallowLockClick === rig._swallow) rig.engine.input.swallowLockClick = null; }
|
|
@@ -80,7 +104,9 @@ export { screenToGround } from '../../core/screenToGround.js'; // shared with
|
|
|
80
104
|
|
|
81
105
|
/** Camera kind table: kind name -> build(engine, opts). Each camera file registers once with defineRig; setCamera switches by name */
|
|
82
106
|
const RIGS = new Map();
|
|
83
|
-
|
|
107
|
+
const RIG_PARAMS = new Map(); // kind -> params schema (the option keys of that camera)
|
|
108
|
+
/** keys: the options that camera takes; they become its params schema (engine.catalog) and a misspelled one throws in dev */
|
|
109
|
+
export function defineRig(kind, build, keys = []) { RIGS.set(kind, build); RIG_PARAMS.set(kind, keysSchema(keys)); }
|
|
84
110
|
|
|
85
111
|
/**
|
|
86
112
|
* Wrap a camera as a module: handles cutscene takeover, updates engine.focus, and provides runtime switching engine.setCamera(kind, options?).
|
|
@@ -93,6 +119,7 @@ export function rigModule(kind, opts) {
|
|
|
93
119
|
const make = (k, o) => {
|
|
94
120
|
const build = RIGS.get(k);
|
|
95
121
|
if (!build) throw new Error(`setCamera() has no camera kind '${k}'; available: ${[...RIGS.keys()].join(', ')}`);
|
|
122
|
+
readParams(`${k}Camera`, RIG_PARAMS.get(k), o); // also covers setCamera(kind, options)
|
|
96
123
|
const r = build(engine, o ?? {});
|
|
97
124
|
r.kind = k; cache.set(k, r);
|
|
98
125
|
return r;
|
|
@@ -101,6 +128,7 @@ export function rigModule(kind, opts) {
|
|
|
101
128
|
if (k === c.kind && !o) return c;
|
|
102
129
|
const old = c, target = old.target;
|
|
103
130
|
old.onExit?.();
|
|
131
|
+
setProjection(engine.camera); // back to perspective; an orthographic rig sets its own in onEnter / constructor
|
|
104
132
|
engine.camera.fov = fov0; engine.camera.updateProjectionMatrix(); // fov returns to the value at install; each camera applies its own in onEnter / constructor
|
|
105
133
|
const next = o || !cache.has(k) ? make(k, o) : cache.get(k);
|
|
106
134
|
c = engine.cameraRig = next;
|
|
@@ -112,7 +140,7 @@ export function rigModule(kind, opts) {
|
|
|
112
140
|
return c;
|
|
113
141
|
}
|
|
114
142
|
return {
|
|
115
|
-
name: 'cameraRig', label: 'Camera', optional: ['collision'], stage: 'control',
|
|
143
|
+
name: 'cameraRig', label: 'Camera', params: RIG_PARAMS.get(kind), options: opts, optional: ['collision'], stage: 'control',
|
|
116
144
|
install(e) {
|
|
117
145
|
engine = e; fov0 = e.camera.fov;
|
|
118
146
|
e.setCamera = setCamera;
|
|
@@ -122,6 +150,7 @@ export function rigModule(kind, opts) {
|
|
|
122
150
|
e.events.on('session:start', () => {
|
|
123
151
|
const old = c;
|
|
124
152
|
old.onExit?.(); cache.clear();
|
|
153
|
+
setProjection(e.camera);
|
|
125
154
|
e.camera.fov = fov0; e.camera.updateProjectionMatrix();
|
|
126
155
|
c = e.cameraRig = make(kind, opts);
|
|
127
156
|
c.onEnter?.(false); c.follow(e.player?.cameraFollow ? e.player.root : null); fresh = true; // follows the player only if the game asked (createPlayer({ cameraFollow }))
|
|
@@ -141,7 +170,8 @@ export function rigModule(kind, opts) {
|
|
|
141
170
|
e.focus.copy(c.focusPoint()); // decides only where the view (terrain, models) loads; the gameplay simulation center is world.anchor (default the player), so moving the camera away changes nothing
|
|
142
171
|
owned.mark(); fresh = false;
|
|
143
172
|
},
|
|
144
|
-
describe(e, ctx) { ctx.out.camera.type = c.kind; if (c.current !== undefined) ctx.out.camera.shot = c.current;
|
|
173
|
+
describe(e, ctx) { ctx.out.camera.type = c.kind; if (c.current !== undefined) ctx.out.camera.shot = c.current;
|
|
174
|
+
ctx.out.camera.pointerLock = lockView(e, c.lockState); },
|
|
145
175
|
};
|
|
146
176
|
}
|
|
147
177
|
|
package/modules/camera/index.js
CHANGED
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
// firstPersonCamera() first person
|
|
4
4
|
// fixedCamera() fixed shots (camera cuts)
|
|
5
5
|
// rtsCamera() strategy top-down (pan, zoom, rotate, screen point -> ground)
|
|
6
|
-
// Cutscene takeover contract engine.cameraOverride: see common.js.
|
|
6
|
+
// Cutscene takeover contract engine.takeCamera / cameraOverride: see common.js.
|
|
7
7
|
export { followCamera, FollowCamera } from './FollowCamera.js';
|
|
8
8
|
export { firstPersonCamera, FirstPersonCamera } from './FirstPersonCamera.js';
|
|
9
9
|
export { fixedCamera, FixedCamera } from './FixedCamera.js';
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
// Orthographic projection for engine.camera, without replacing the camera object.
|
|
2
|
+
//
|
|
3
|
+
// engine.camera is one PerspectiveCamera that the render pass, post chain, cascaded shadows, sky and every module hold a reference to.
|
|
4
|
+
// Swapping in a THREE.OrthographicCamera would leave those pointing at the old camera, so the rig flips this same instance instead:
|
|
5
|
+
// updateProjectionMatrix() builds an orthographic matrix while camera.orthoSize is set (isPerspectiveCamera / isOrthographicCamera and
|
|
6
|
+
// left/right/top/bottom follow, so code that branches on the camera type keeps working), and the original perspective one otherwise.
|
|
7
|
+
// Resize needs nothing extra: canvasBox sets camera.aspect and calls updateProjectionMatrix().
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* Switch engine.camera between perspective and orthographic.
|
|
11
|
+
* @param {import('three').PerspectiveCamera} cam engine.camera
|
|
12
|
+
* @param {'perspective' | 'orthographic'} projection
|
|
13
|
+
* @param {number} [size] orthographic only: world units covered by the view height (before camera.zoom)
|
|
14
|
+
*/
|
|
15
|
+
export function setProjection(cam, projection = 'perspective', size = 20) {
|
|
16
|
+
if (projection !== 'perspective' && projection !== 'orthographic') throw new Error(`projection must be 'perspective' or 'orthographic', got '${projection}'`);
|
|
17
|
+
if (projection === 'orthographic' && !(size > 0)) throw new Error(`orthographic projection needs size > 0 (world units of view height), got ${size}`);
|
|
18
|
+
if (!cam._perspectiveUpdate) {
|
|
19
|
+
const original = cam.updateProjectionMatrix;
|
|
20
|
+
cam._perspectiveUpdate = original;
|
|
21
|
+
cam.updateProjectionMatrix = function () {
|
|
22
|
+
if (!this.orthoSize) return original.call(this);
|
|
23
|
+
const top = this.orthoSize / 2 / this.zoom, right = top * this.aspect;
|
|
24
|
+
this.left = -right; this.right = right; this.top = top; this.bottom = -top;
|
|
25
|
+
this.projectionMatrix.makeOrthographic(-right, right, top, -top, this.near, this.far, this.coordinateSystem);
|
|
26
|
+
this.projectionMatrixInverse.copy(this.projectionMatrix).invert();
|
|
27
|
+
};
|
|
28
|
+
}
|
|
29
|
+
const ortho = projection === 'orthographic';
|
|
30
|
+
if (ortho ? cam.orthoSize === size : !cam.orthoSize) return;
|
|
31
|
+
cam.orthoSize = ortho ? size : 0;
|
|
32
|
+
cam.isOrthographicCamera = ortho; cam.isPerspectiveCamera = !ortho;
|
|
33
|
+
cam.updateProjectionMatrix();
|
|
34
|
+
}
|
|
@@ -12,20 +12,21 @@ import * as THREE from 'three';
|
|
|
12
12
|
import { xzOf } from '../../core/math.js';
|
|
13
13
|
import { placeY } from '../../core/ground.js';
|
|
14
14
|
import { warnOnce, warnMissing } from '../../core/validate.js';
|
|
15
|
-
import {
|
|
15
|
+
import { reportError } from '../../core/errors.js';
|
|
16
16
|
import { simpleMover } from './movers/simple.js';
|
|
17
17
|
import { rapierMover } from './movers/rapier.js';
|
|
18
18
|
import { loadAssetModel } from './assetModel.js';
|
|
19
19
|
import { NO_CHARACTER, capsule, useRig, animateRig } from './proceduralRig.js';
|
|
20
|
+
import { walkTo } from './walkTo.js';
|
|
21
|
+
import { useModel } from './useModel.js';
|
|
20
22
|
|
|
21
23
|
const STRINGS = { noClip: 'character has no skeletal animation; playAction(\'{name}\') skipped (the model needs this action)' };
|
|
22
24
|
const MOVERS = { simple: simpleMover, rapier: rapierMover };
|
|
23
25
|
// Default action names for the clips shorthand (character state -> glTF action name)
|
|
24
|
-
const DEFAULT_CLIPS = { idle: 'Idle', walk: 'Walk', run: 'Run', swim: 'Swim', jump: 'Jump', fall: 'Fall', drive: 'Drive' };
|
|
25
26
|
|
|
26
27
|
// Options Character understands (shared by player and NPC)
|
|
27
28
|
export const CHARACTER_KEYS = ['colors', 'speed', 'runSpeed', 'radius', 'canSwim', 'swimDepth', 'swimSpeed', 'turnSpeed', 'acceleration', 'gravity',
|
|
28
|
-
'jumpSpeed', 'stepHeight', 'airControl', 'coyoteTime', 'canJump', 'model', 'clips', 'animation', 'mover', 'faceMode', 'faceTarget'];
|
|
29
|
+
'jumpSpeed', 'stepHeight', 'airControl', 'coyoteTime', 'canJump', 'model', 'clips', 'animation', 'mover', 'faceMode', 'faceTarget', 'rig'];
|
|
29
30
|
const FACE_MODES = ['move', 'camera', 'target', 'manual'];
|
|
30
31
|
|
|
31
32
|
export class Character {
|
|
@@ -40,6 +41,7 @@ export class Character {
|
|
|
40
41
|
* model + clips: optional glTF model and action-name map { idle, walk, run, swim, jump, fall, drive } (shorthand for animation)
|
|
41
42
|
* animation: animation state machine config (see core/Animator.js), state names are character state names;
|
|
42
43
|
* without walk/run, move (blend tree, param speed) is used
|
|
44
|
+
* rig: a ready body in the format style.character.create returns (proceduralRig.js), used instead of the style pack's (hand-built guard / pet)
|
|
43
45
|
* mover: 'simple' (default) | 'rapier' (Rapier character controller, needs the rigid module)
|
|
44
46
|
* faceMode which way it turns each move: 'move' (default, toward its velocity) | 'camera' (along cameraRig.forward(), over-the-shoulder aiming)
|
|
45
47
|
* | 'target' (toward faceTarget: Object3D / Vector3 / { x, z }, lock-on strafing) | 'manual' (only face() turns it);
|
|
@@ -50,7 +52,7 @@ export class Character {
|
|
|
50
52
|
constructor(engine, { colors = {}, speed = 4.5, runSpeed = 7, radius = engine.movement.radius, canSwim = true, swimDepth = 1.0, swimSpeed = 0.45,
|
|
51
53
|
turnSpeed = 10, acceleration = 12, gravity = -24, jumpSpeed = 8, stepHeight = engine.movement.stepHeight, airControl = 0.35, coyoteTime = 0.12,
|
|
52
54
|
canJump = true,
|
|
53
|
-
model = null, clips = null, animation = null, mover = 'simple', faceMode = 'move', faceTarget = null } = {}) {
|
|
55
|
+
model = null, clips = null, animation = null, mover = 'simple', faceMode = 'move', faceTarget = null, rig = null } = {}) {
|
|
54
56
|
this.engine = engine;
|
|
55
57
|
Object.assign(this, { speed, runSpeed, radius, canSwim, swimDepth, swimSpeedFactor: swimSpeed, turnSpeed, acceleration, gravity, jumpSpeed, stepHeight,
|
|
56
58
|
airControl, coyoteTime, canJump });
|
|
@@ -80,22 +82,19 @@ export class Character {
|
|
|
80
82
|
model ??= engine.style.character?.model ?? null;
|
|
81
83
|
if (model && typeof model !== 'string') { this._useModel(model, clips, animation); return; }
|
|
82
84
|
// style-pack procedural character: the rig format is in proceduralRig.js
|
|
83
|
-
|
|
85
|
+
rig ??= engine.style.character?.create?.(engine, c);
|
|
84
86
|
if (!rig && !model) warnOnce(NO_CHARACTER);
|
|
85
87
|
useRig(this, rig || capsule(c.body, engine));
|
|
86
88
|
if (model) this._whenReady = loadAssetModel(this, model, m => this._useModel(m, clips, animation));
|
|
87
89
|
}
|
|
88
|
-
_useModel(model, clips, animation) {
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
// the model's own mapping (fade, transitions) beats the style pack's default for every character; the game's per-character config beats both
|
|
97
|
-
this.anim = engine.assets.animate(model, { ...engine.style.character?.animation, ...map, states, ...(animation || {}) });
|
|
98
|
-
}
|
|
90
|
+
_useModel(model, clips, animation) { useModel(this, model, clips, animation); }
|
|
91
|
+
|
|
92
|
+
/**
|
|
93
|
+
* Walk to a point along characters.findPath on fixed steps (turn rate, skips passed points, re-plans when stuck). Returns a promise of
|
|
94
|
+
* { status: 'arrived' | 'noPath' | 'stuck' | 'cancelled' } (never rejects) with remove() to cancel; a new walkTo, dispose() or a save load cancels it (not saved). speed m/s, arrive metres, turnRate rad/s
|
|
95
|
+
* @example await guard.walkTo(player.position, { arrive: 1.5 })
|
|
96
|
+
*/
|
|
97
|
+
walkTo(target, opts) { return walkTo(this, target, opts); }
|
|
99
98
|
|
|
100
99
|
/** Request a jump (call when the jump key is pressed; has a jump buffer, so pressing slightly before landing counts) */
|
|
101
100
|
jump() { if (this.canJump) this._jumpBuffer = 0.12; }
|
|
@@ -155,6 +154,7 @@ export class Character {
|
|
|
155
154
|
/** Dispose this character completely: exit the vehicle first, release animation and mover, remove from the scene and dispose geometries and materials */
|
|
156
155
|
dispose() {
|
|
157
156
|
this._disposed = true; // a model still loading by asset name is dropped on arrival
|
|
157
|
+
this._walk?.remove(); // a walk in progress ends 'cancelled' (walkTo.js)
|
|
158
158
|
this.exit();
|
|
159
159
|
this.anim?.dispose();
|
|
160
160
|
this.mover.dispose?.();
|
|
@@ -202,8 +202,20 @@ export class Character {
|
|
|
202
202
|
this.root.rotation.y = this.facing;
|
|
203
203
|
}
|
|
204
204
|
|
|
205
|
+
/**
|
|
206
|
+
* Run fn(character, dt) every frame right after this character's animation pose is applied (model clips or procedural rig), so a game can attach things to bones
|
|
207
|
+
* or adjust bones on top of the pose. Returns a handle; h.remove() stops it. Presentation only: never read it for gameplay timing.
|
|
208
|
+
* @param {(character: Character, dt: number) => void} fn
|
|
209
|
+
* @returns {{ remove(): void }}
|
|
210
|
+
* @example const h = player.onPose(() => sword.position.copy(player.object.getObjectByName('Hand_R').getWorldPosition(v)));
|
|
211
|
+
*/
|
|
212
|
+
onPose(fn) { (this._poseFns ??= new Set()).add(fn); return { remove: () => this._poseFns.delete(fn) }; }
|
|
213
|
+
/** @internal */
|
|
214
|
+
_firePose(dt) { if (this._poseFns?.size) for (const f of [...this._poseFns]) { try { f(this, dt); } catch (err) { reportError(this.engine, err, 'character.onPose callback'); } } }
|
|
205
215
|
/** @internal Call every frame: play animation */
|
|
206
|
-
animate(dt) {
|
|
216
|
+
animate(dt) { this._animate(dt); if (!this.anim) this._firePose(dt); }
|
|
217
|
+
/** @internal */
|
|
218
|
+
_animate(dt) {
|
|
207
219
|
const sp = this.moveAmount, t = this.engine.elapsed, st = this.state;
|
|
208
220
|
this.phase += dt * (2.2 + sp * 1.25);
|
|
209
221
|
const s = Math.sin(this.phase);
|
|
@@ -2,6 +2,12 @@
|
|
|
2
2
|
// engine.characters.findPath calls it with the collision module's walkability, the pathfinding worker (pathJob.js) with a snapshot of it.
|
|
3
3
|
// In games use engine.characters.findPath / findPathAsync, do not import this directly. Worker-safe: no imports.
|
|
4
4
|
|
|
5
|
+
/** Default cell size from the character radius: a small character gets finer cells (never below the 1 m ground raster, never above the old 2 m); no radius = 2 */
|
|
6
|
+
const defaultStep = r => r == null ? 2 : Math.min(2, Math.max(1, r * 4));
|
|
7
|
+
const defaultNodes = step => Math.round(6000 * Math.max(1, 2 / step) ** 2); // finer cells need more of them to cover the same distance
|
|
8
|
+
/** The step / maxNodes findPath uses for a character radius when the caller gives none (pathAsync sizes its ground raster with the same numbers) */
|
|
9
|
+
export const astarDefaults = radius => { const step = defaultStep(radius); return { step, maxNodes: defaultNodes(step) }; };
|
|
10
|
+
|
|
5
11
|
class MinHeap {
|
|
6
12
|
constructor() { this.a = []; }
|
|
7
13
|
push(n, f) { const a = this.a; a.push([f, n]); let i = a.length - 1; while (i > 0) { const p = (i - 1) >> 1; if (a[p][0] <= a[i][0]) break; [a[p], a[i]] = [a[i], a[p]]; i = p; } }
|
|
@@ -13,7 +19,8 @@ class MinHeap {
|
|
|
13
19
|
* Grid A*: cells of step meters, searches at most maxNodes cells; returns [{ x, z }...] or null if no path.
|
|
14
20
|
* @param {(x: number, z: number) => boolean} walkable can a character stand here (radius already applied)
|
|
15
21
|
*/
|
|
16
|
-
export function findPath(walkable, sx, sz, gx, gz, { step =
|
|
22
|
+
export function findPath(walkable, sx, sz, gx, gz, { radius, step = defaultStep(radius), maxNodes = defaultNodes(step) } = {}) {
|
|
23
|
+
const sample = Math.min(0.75, Math.max(0.15, radius ?? 0.4)); // smoothing samples a segment at most one radius apart: walkable() already grows colliders by radius, so nothing 2r wide is stepped over
|
|
17
24
|
const key = (i, j) => i * 100003 + j;
|
|
18
25
|
const si = Math.round(sx / step), sj = Math.round(sz / step), gi = Math.round(gx / step), gj = Math.round(gz / step);
|
|
19
26
|
const open = new MinHeap(), g = new Map(), from = new Map(), walk = new Map();
|
|
@@ -27,8 +34,8 @@ export function findPath(walkable, sx, sz, gx, gz, { step = 2, maxNodes = 6000 }
|
|
|
27
34
|
if (i === gi && j === gj) {
|
|
28
35
|
const path = []; let k = key(i, j), cur = [i, j];
|
|
29
36
|
while (cur) { path.push({ x: cur[0] * step, z: cur[1] * step }); cur = from.get(k); if (cur) k = key(cur[0], cur[1]); }
|
|
30
|
-
path.reverse(); path[path.length - 1] = { x: gx, z: gz };
|
|
31
|
-
return simplify(walkable, path);
|
|
37
|
+
path.reverse(); path[0] = { x: sx, z: sz }; path[path.length - 1] = { x: gx, z: gz }; // real start, not the snapped cell centre (which may even lie behind a wall)
|
|
38
|
+
return simplify(walkable, path, sample);
|
|
32
39
|
}
|
|
33
40
|
const gc = g.get(key(i, j));
|
|
34
41
|
for (const [di, dj, c] of dirs) {
|
|
@@ -41,19 +48,19 @@ export function findPath(walkable, sx, sz, gx, gz, { step = 2, maxNodes = 6000 }
|
|
|
41
48
|
return null;
|
|
42
49
|
}
|
|
43
50
|
// drop redundant corners: go straight when two points are directly walkable
|
|
44
|
-
function simplify(walkable, path) {
|
|
51
|
+
function simplify(walkable, path, sample) {
|
|
45
52
|
if (path.length < 3) return path;
|
|
46
53
|
const out = [path[0]];
|
|
47
54
|
let a = 0;
|
|
48
55
|
while (a < path.length - 1) {
|
|
49
56
|
let b = path.length - 1;
|
|
50
|
-
while (b > a + 1 && !lineClear(walkable, path[a], path[b])) b--;
|
|
57
|
+
while (b > a + 1 && !lineClear(walkable, path[a], path[b], sample)) b--;
|
|
51
58
|
out.push(path[b]); a = b;
|
|
52
59
|
}
|
|
53
60
|
return out;
|
|
54
61
|
}
|
|
55
|
-
function lineClear(walkable, p, q) {
|
|
56
|
-
const d = Math.hypot(q.x - p.x, q.z - p.z), n = Math.ceil(d /
|
|
62
|
+
function lineClear(walkable, p, q, sample) {
|
|
63
|
+
const d = Math.hypot(q.x - p.x, q.z - p.z), n = Math.ceil(d / sample);
|
|
57
64
|
for (let i = 1; i < n; i++) { const t = i / n; if (!walkable(p.x + (q.x - p.x) * t, p.z + (q.z - p.z) * t)) return false; }
|
|
58
65
|
return true;
|
|
59
66
|
}
|
|
@@ -15,6 +15,7 @@ import { findPath } from './astar.js';
|
|
|
15
15
|
import { findSpawn, moveInput } from './moveHelpers.js';
|
|
16
16
|
import { AsyncPaths } from './pathAsync.js';
|
|
17
17
|
import { checkOptions, warnOnce, DEV } from '../../core/validate.js';
|
|
18
|
+
import { readParams, keysSchema } from '../../core/params.js';
|
|
18
19
|
import { codedError, coded } from '../../core/errorHints.js';
|
|
19
20
|
import { DEV_STRINGS, STRINGS, validControl } from './playerStrings.js';
|
|
20
21
|
import { footstepSynth, stepSound } from './footsteps.js';
|
|
@@ -41,20 +42,22 @@ function solvePath(e, from, to, o) {
|
|
|
41
42
|
else if (!e.collision) res = { status: 'notReady', path: null };
|
|
42
43
|
else {
|
|
43
44
|
const [sx, sz] = xzOf(from), [gx, gz] = xzOf(to), radius = rest.radius ?? e.movement.radius;
|
|
44
|
-
const path = findPath((x, z) => e.collision.walkableAt(x, z, radius), sx, sz, gx, gz, rest);
|
|
45
|
+
const path = findPath((x, z) => e.collision.walkableAt(x, z, radius), sx, sz, gx, gz, { ...rest, radius });
|
|
45
46
|
// nav installed but not ready: A* is only a stand-in, tell the caller honestly
|
|
46
47
|
res = { status: e.nav ? 'notReady' : path ? 'ok' : 'noPath', path };
|
|
47
48
|
}
|
|
48
49
|
return detailed ? res : res.path;
|
|
49
50
|
}
|
|
50
51
|
|
|
52
|
+
const CHARACTERS_PARAMS = keysSchema(['npcs', 'brakeKeys', 'brakePad']);
|
|
53
|
+
|
|
51
54
|
export function characters(opts = {}) {
|
|
55
|
+
readParams('characters', CHARACTERS_PARAMS, opts);
|
|
52
56
|
const { npcs = true, brakeKeys, brakePad } = opts; // no brake key by default: characters({ ...presets.keys.brake }) or the game's own
|
|
53
57
|
let mgr = null, paths = null, disposePlayer = null;
|
|
54
58
|
return {
|
|
55
|
-
name: 'characters', label: 'Characters', optional: ['cameraRig', 'sky', 'interactions', 'dialogue', 'nav', 'collision', 'rigid', 'world'],
|
|
59
|
+
name: 'characters', params: CHARACTERS_PARAMS, options: opts, label: 'Characters', noSkip: 'fixed only flushes path requests; schedules read the sky clock', optional: ['cameraRig', 'sky', 'interactions', 'dialogue', 'nav', 'collision', 'rigid', 'world'],
|
|
56
60
|
install(e) {
|
|
57
|
-
checkOptions('characters()', opts, ['npcs', 'brakeKeys', 'brakePad']);
|
|
58
61
|
e.i18n.add(STRINGS);
|
|
59
62
|
e.audio.register('footstep', footstepSynth, { builtIn: true });
|
|
60
63
|
if (npcs) { mgr = new NPCManager(e); e.npcs = mgr; }
|
|
@@ -16,7 +16,12 @@ export function simpleMover(c) {
|
|
|
16
16
|
const nh = e.surface(p.x, p.z, p.y), step = Math.hypot(p.x - ox, p.z - oz), maxClimb = e.collision?.maxClimb ?? e.movement.slopeRatio, rise = nh - Math.max(oh, c.grounded ? oh : p.y);
|
|
17
17
|
const blocked = c.grounded ? (rise > c.stepHeight && step > 1e-4 && (nh - oh) / step > maxClimb) : nh > p.y + c.stepHeight;
|
|
18
18
|
if (blocked) { p.x = ox; p.z = oz; c.velocity.set(0, 0); }
|
|
19
|
-
e.collision
|
|
19
|
+
const col = e.collision;
|
|
20
|
+
if (col?._blocked.length && col.blockedAt(p.x, p.z, c.radius)) { // addBlocked ground (river): slide along it, else stay put
|
|
21
|
+
const nx = p.x, nz = p.z;
|
|
22
|
+
if (!col.blockedAt(nx, oz, c.radius)) p.z = oz; else if (!col.blockedAt(ox, nz, c.radius)) p.x = ox; else { p.x = ox; p.z = oz; c.velocity.set(0, 0); }
|
|
23
|
+
}
|
|
24
|
+
col?.resolve(p, c.radius);
|
|
20
25
|
|
|
21
26
|
const { ground, swimY } = water(c, ox, oz);
|
|
22
27
|
|
|
@@ -56,6 +56,12 @@ export function advance(e, W, rec, seconds) {
|
|
|
56
56
|
settle(e, W, rec, x, z, Math.hypot(g.x - x, g.z - z) > rec.arriveDistance);
|
|
57
57
|
}
|
|
58
58
|
|
|
59
|
+
/** 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 */
|
|
60
|
+
function noteState(e, rec, next) {
|
|
61
|
+
if (rec.state !== next && e.events.traceSize > 0) e.events.note('npc:state', { obj: rec.id, data: { from: rec.state ?? null, to: next } });
|
|
62
|
+
rec.state = next;
|
|
63
|
+
}
|
|
64
|
+
|
|
59
65
|
/**
|
|
60
66
|
* 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,
|
|
61
67
|
* so it is re-found at the new position after the model is built
|
|
@@ -65,7 +71,7 @@ export function settle(e, W, rec, x, z, moving) {
|
|
|
65
71
|
const m = rec.motion ??= {};
|
|
66
72
|
const facing = x !== p.x || z !== p.z ? Math.atan2(x - p.x, z - p.z) : m.facing ?? 0;
|
|
67
73
|
Object.assign(m, { vx: 0, vz: 0, vy: 0, amount: 0, facing, grounded: true, swimming: false, coyote: 0 });
|
|
68
|
-
rec
|
|
74
|
+
noteState(e, rec, moving ? 'walk' : 'idle');
|
|
69
75
|
// NPC of another level: this level's ground height is meaningless for it, keep its y
|
|
70
76
|
const here = rec.zone == null || W.zone == null || rec.zone === W.zone;
|
|
71
77
|
W.move(rec.id, { x, y: here ? e.surface(x, z) : p.y, z });
|
|
@@ -121,7 +127,7 @@ export function goTo(e, W, rec, ch, goal, dt) {
|
|
|
121
127
|
// 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
|
|
122
128
|
// simulation and saves this step see the latest)
|
|
123
129
|
rec.motion = ch.saveMotion(rec.motion ?? {});
|
|
124
|
-
rec
|
|
130
|
+
noteState(e, rec, ch.state);
|
|
125
131
|
W.move(rec.id, p);
|
|
126
132
|
}
|
|
127
133
|
|
|
@@ -4,7 +4,7 @@
|
|
|
4
4
|
// solveBatch runs here at the due step. The batch is tagged with the walkable state it was computed on (navmesh revision or collision version);
|
|
5
5
|
// if that changed before it lands, it is recomputed here on the current state, so threads on / off / slow / crashed give identical paths.
|
|
6
6
|
import { xzOf } from '../../core/math.js';
|
|
7
|
-
import { solveBatch, pathHandler, RES, TILE, tileOf } from './pathJob.js';
|
|
7
|
+
import { solveBatch, pathHandler, astarDefaults, RES, TILE, tileOf } from './pathJob.js';
|
|
8
8
|
|
|
9
9
|
/** 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 */
|
|
10
10
|
const PATH_LAG = 4;
|
|
@@ -53,7 +53,7 @@ export class AsyncPaths {
|
|
|
53
53
|
const reqs = list.map(({ sx, sz, gx, gz, o }) => {
|
|
54
54
|
if (mode === 'nav') return { mode, s: { x: sx, y: e.surface(sx, sz), z: sz }, g: { x: gx, y: e.surface(gx, gz), z: gz }, reach: e.nav.reach(o.radius) };
|
|
55
55
|
if (mode === 'none') return { mode };
|
|
56
|
-
const radius = o.radius ?? e.movement.radius, step = o.step ??
|
|
56
|
+
const radius = o.radius ?? e.movement.radius, dflt = astarDefaults(radius), step = o.step ?? dflt.step, maxNodes = o.maxNodes ?? dflt.maxNodes;
|
|
57
57
|
// A* may wander this far beyond the start-goal box; bounded by how far maxNodes cells can reach
|
|
58
58
|
const m = Math.min(step * Math.sqrt(maxNodes / Math.PI), 16 + Math.hypot(gx - sx, gz - sz) / 2);
|
|
59
59
|
for (let tx = tileOf(Math.min(sx, gx) - m); tx <= tileOf(Math.max(sx, gx) + m); tx++)
|
|
@@ -68,12 +68,18 @@ export class AsyncPaths {
|
|
|
68
68
|
*/
|
|
69
69
|
tile(k, tx, tz) {
|
|
70
70
|
const e = this.e, c = this.tiles.get(k);
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
71
|
+
const bv = e.collision.blockedVersion;
|
|
72
|
+
if (c && c.bv === bv && e.tick - c.at < TILE_TTL) return c;
|
|
73
|
+
const data = new Uint8Array(TILE * TILE), col = e.collision, trees = [], span = TILE * RES, blocked = col._blocked.length > 0;
|
|
74
|
+
// addBlocked fields are functions and cannot go to a worker: they are sampled into this same raster (the worker sees blocked cells as unwalkable).
|
|
75
|
+
// 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.
|
|
76
|
+
for (let j = 0; j < TILE; j++) for (let i = 0; i < TILE; i++) {
|
|
77
|
+
const x = (tx * TILE + i) * RES, z = (tz * TILE + j) * RES;
|
|
78
|
+
data[j * TILE + i] = col.groundWalkable(x, z) && !(blocked && col.blockedAt(x, z, RES / 2)) ? 1 : 0;
|
|
79
|
+
}
|
|
74
80
|
// every collider that can touch a point of the tile: half diagonal + the largest character radius we expect + 1 (the same reach walkableAt uses)
|
|
75
81
|
e.ground.forEachCollider?.((tx + 0.5) * span, (tz + 0.5) * span, span * 0.71 + 3, (x, z, r) => { trees.push(x, z, r); });
|
|
76
|
-
const v = { data, trees, at: e.tick };
|
|
82
|
+
const v = { data, trees, at: e.tick, bv };
|
|
77
83
|
this.tiles.set(k, v);
|
|
78
84
|
if (this.tiles.size > 4096) for (const [kk, o] of this.tiles) if (e.tick - o.at >= TILE_TTL) this.tiles.delete(kk);
|
|
79
85
|
return v;
|
|
@@ -2,7 +2,8 @@
|
|
|
2
2
|
// and in engine.commits' fallback when a worker reply is late (pathAsync.js). Worker-safe: no three.js, no engine objects.
|
|
3
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
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).
|
|
5
|
-
import { findPath as astar } from './astar.js';
|
|
5
|
+
import { findPath as astar, astarDefaults } from './astar.js';
|
|
6
|
+
export { astarDefaults };
|
|
6
7
|
import { CollisionGrid, gridBlocks } from '../collision/grid.js';
|
|
7
8
|
import { navSearch } from '../nav/navPath.js';
|
|
8
9
|
|
|
@@ -3,6 +3,7 @@
|
|
|
3
3
|
// A rig is { root, body?, head?, joints?: { name: Group }, limbs: [{ joint, offset: 0 | Math.PI, amp, kind: 'arm' | 'leg', side? }] }; the style pack builds it.
|
|
4
4
|
import * as THREE from 'three';
|
|
5
5
|
import { makeMaterial } from '../../render/materials.js';
|
|
6
|
+
import { warnOnce } from '../../core/validate.js';
|
|
6
7
|
|
|
7
8
|
/** Warned once when no style pack and no model give the character a body */
|
|
8
9
|
export const NO_CHARACTER = 'characters: no style pack / model given, so characters are gray capsules (a placeholder). Pass one: a model '
|
|
@@ -25,7 +26,10 @@ export function useRig(ch, rig) {
|
|
|
25
26
|
ch.bodyBase = ch.hips.position.y;
|
|
26
27
|
ch.limbs = rig.limbs || [];
|
|
27
28
|
// named joints (lowpoly humanoid: armL armR legL legR) become properties so game poses can grab them; never shadow a Character field
|
|
28
|
-
for (const k in rig.joints || {})
|
|
29
|
+
for (const k in rig.joints || {}) {
|
|
30
|
+
if (!(k in ch)) ch[k] = rig.joints[k];
|
|
31
|
+
else if (ch[k] !== rig.joints[k]) warnOnce(`character rig: joint "${k}" has the same name as the Character field ch.${k}, so ch.${k} stays the field; use rig.joints.${k} (or rename the joint)`);
|
|
32
|
+
}
|
|
29
33
|
}
|
|
30
34
|
|
|
31
35
|
/** Swing the limbs and bob the body for the current state (sp = move amount, t = elapsed seconds, st = character state) */
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
// Swap a loaded glTF model into a Character: attach it and build its animation state machine from the default / mapped / game-given clips.
|
|
2
|
+
// Split out of Character.js; Character._useModel calls it.
|
|
3
|
+
import { warnOnce } from '../../core/validate.js';
|
|
4
|
+
import { findClip } from '../../core/Animator.js';
|
|
5
|
+
|
|
6
|
+
const DEFAULT_CLIPS = { idle: 'Idle', walk: 'Walk', run: 'Run', swim: 'Swim', jump: 'Jump', fall: 'Fall', drive: 'Drive' };
|
|
7
|
+
|
|
8
|
+
export function useModel(ch, model, clips, animation) {
|
|
9
|
+
const engine = ch.engine; ch.root.add(model);
|
|
10
|
+
// a bone named like a Character field (e.g. "head", "root", "state") makes `ch[name]` mean the field, not the bone: easy to miss when a game
|
|
11
|
+
// reads bones by name; say it once per name and point at the safe lookup
|
|
12
|
+
model.traverse(o => { if (o.isBone && o.name && o.name in ch) warnOnce(`character model "${model.name || 'model'}": bone "${o.name}" has the same name as the Character field ch.${o.name}; read the bone with ch.root.getObjectByName('${o.name}'), not ch.${o.name}, or rename the bone`); });
|
|
13
|
+
const states = {};
|
|
14
|
+
// default names only where the model has the clip (a model without Swim is fine) and the manifest mapped nothing (Assets.animate merges that under
|
|
15
|
+
// these states, so a default Idle must not shadow a mapped Idle_Sword); names the game wrote are always kept so a typo is reported
|
|
16
|
+
const have = model.userData.animations || [], map = engine.assets.mapping(model), mapped = map?.states || {};
|
|
17
|
+
for (const [st, clip] of Object.entries(DEFAULT_CLIPS)) if (!mapped[st] && findClip(have, clip)) states[st] = { clip };
|
|
18
|
+
for (const [st, clip] of Object.entries(clips || {})) states[st] = { clip };
|
|
19
|
+
// the model's own mapping (fade, transitions) beats the style pack's default for every character; the game's per-character config beats both
|
|
20
|
+
ch.anim = engine.assets.animate(model, { ...engine.style.character?.animation, ...map, states, ...(animation || {}) });
|
|
21
|
+
ch.anim.afterPose = dt => ch._firePose(dt); // a mixer pose is applied inside the Animator's update, so the Animator tells us when it is done
|
|
22
|
+
}
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
// character.walkTo(target, opts): follow characters.findPath on fixed steps. Exists so a hand-written guard / pet / follower does not re-implement
|
|
2
|
+
// path following (turn rate, skipping passed points, stuck detection) every time. Steering only: the mover still owns position (see Character.js).
|
|
3
|
+
// Transient on purpose (like a noSkip timer): a walk is not saved and engine.skip does not fast-forward it. So it never outlives what it steers:
|
|
4
|
+
// one walk per character (a new walkTo cancels the old, else two hooks would fight over move()), and character.dispose() or a save load
|
|
5
|
+
// ends it with 'cancelled' (the loaded state has its own positions; the old path no longer applies). A game that must resume a walk saves the target.
|
|
6
|
+
import { xzOf } from '../../core/math.js';
|
|
7
|
+
|
|
8
|
+
const STUCK_PROGRESS = 0.15; // metres the character must gain on the next point within the stuck window, else it counts as stuck
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* @param {any} ch Character
|
|
12
|
+
* @returns {Promise<{ status: 'arrived' | 'noPath' | 'stuck' | 'cancelled' }> & { remove(): void }}
|
|
13
|
+
*/
|
|
14
|
+
export function walkTo(ch, target, { speed, arrive = 0.5, turnRate = 8, stuckSeconds = 1.5, maxRepaths = 3, run = false } = {}) {
|
|
15
|
+
const e = ch.engine;
|
|
16
|
+
let done, hook, path = null, i = 0, heading = null, repaths = 0, bestD = Infinity, stuckT = 0;
|
|
17
|
+
const promise = new Promise(res => { done = res; });
|
|
18
|
+
ch._walk?.remove(); // one walk per character: the newer order wins
|
|
19
|
+
let onLoad = null, handle = null;
|
|
20
|
+
const finish = status => { if (!hook) return; hook.remove(); hook = null; onLoad?.remove(); if (ch._walk === handle) ch._walk = null; done({ status }); };
|
|
21
|
+
const dist = (p, x, z) => Math.hypot(p.x - x, p.z - z);
|
|
22
|
+
// points the character is already at or past (a later point is closer) would make it turn back, so drop them
|
|
23
|
+
const skipPassed = (x, z) => {
|
|
24
|
+
while (i < path.length - 1 && (dist(path[i], x, z) < arrive * 0.6 || dist(path[i + 1], x, z) < dist(path[i], x, z))) i++;
|
|
25
|
+
};
|
|
26
|
+
const solve = () => {
|
|
27
|
+
path = e.characters.findPath(ch.root.position, target, { radius: ch.radius });
|
|
28
|
+
i = 0; bestD = Infinity; stuckT = 0;
|
|
29
|
+
if (!path || !path.length) return false;
|
|
30
|
+
const [x, z] = xzOf(ch.root.position);
|
|
31
|
+
skipPassed(x, z);
|
|
32
|
+
return true;
|
|
33
|
+
};
|
|
34
|
+
if (!solve()) { queueMicrotask(() => done({ status: 'noPath' })); return Object.assign(promise, { remove() {} }); }
|
|
35
|
+
onLoad = e.events.on('save:loaded', () => finish('cancelled'));
|
|
36
|
+
hook = e.onFixed(dt => {
|
|
37
|
+
const [gx, gz] = xzOf(target), [x, z] = xzOf(ch.root.position);
|
|
38
|
+
if (Math.hypot(gx - x, gz - z) <= arrive) { ch.move(0, 0, false, dt); return finish('arrived'); }
|
|
39
|
+
skipPassed(x, z);
|
|
40
|
+
const p = path[i], d = dist(p, x, z);
|
|
41
|
+
// stuck: no gain on the next point for stuckSeconds, so replan; give up after maxRepaths
|
|
42
|
+
if (d < bestD - STUCK_PROGRESS) { bestD = d; stuckT = 0; }
|
|
43
|
+
else if ((stuckT += dt) > stuckSeconds) {
|
|
44
|
+
if (++repaths > maxRepaths || !solve()) { ch.move(0, 0, false, dt); return finish(repaths > maxRepaths ? 'stuck' : 'noPath'); }
|
|
45
|
+
return;
|
|
46
|
+
}
|
|
47
|
+
const want = Math.atan2(p.x - x, p.z - z);
|
|
48
|
+
heading ??= ch.facing;
|
|
49
|
+
let diff = want - heading; diff -= Math.PI * 2 * Math.round(diff / (Math.PI * 2));
|
|
50
|
+
const step = turnRate * dt;
|
|
51
|
+
heading += Math.abs(diff) <= step ? diff : Math.sign(diff) * step;
|
|
52
|
+
// slow down while the body is still turning toward the point, so it does not overshoot sideways
|
|
53
|
+
const align = Math.max(0.2, Math.cos(Math.min(Math.abs(diff), Math.PI / 2)));
|
|
54
|
+
ch.move(Math.sin(heading), Math.cos(heading), run, dt, (speed ?? (run ? ch.runSpeed : ch.speed)) * align);
|
|
55
|
+
});
|
|
56
|
+
handle = Object.assign(promise, { remove() { finish('cancelled'); } });
|
|
57
|
+
return ch._walk = handle;
|
|
58
|
+
}
|