threedog 2.2.2 → 2.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +20 -0
- package/README.md +4 -4
- package/core/assets/Animator.js +66 -12
- package/core/assets/ik.js +144 -18
- package/core/assets/maskLayer.js +377 -0
- package/core/assets/rootMotion.js +148 -0
- package/core/audio/Audio.js +100 -4
- package/core/base/errorCodes.js +6 -369
- package/core/base/errorCodesModules.js +378 -0
- package/core/engine/Engine.js +8 -5
- package/core/engine/Loading.js +8 -4
- package/core/engine/copies.js +1 -1
- package/core/engine/headlessLoad.js +15 -4
- package/core/engine/lifecycle.js +1 -0
- package/core/engine/loop.js +22 -3
- package/core/engine/moduleSlots.js +3 -7
- package/core/engine/modules.js +30 -58
- package/core/engine/startup.js +3 -3
- package/core/input/Input.js +7 -3
- package/core/input/inputContext.js +3 -2
- package/core/input/inputSeat.js +1 -1
- package/core/inspect/DebugOverrides.js +1 -1
- package/core/inspect/Describe.js +7 -2
- package/core/inspect/describeRender.js +4 -1
- package/core/inspect/describeText.js +2 -2
- package/core/inspect/metadata.generated.js +371 -74
- package/core/inspect/pictureMenu.js +2 -0
- package/core/inspect/pictureWriters.js +4 -3
- package/core/ops/Ops.js +9 -3
- package/core/ops/actor.js +10 -0
- package/core/ops/control.js +17 -6
- package/core/ops/holds.js +1 -1
- package/core/ops/opsAtomic.js +6 -1
- package/core/ops/opsGuard.js +2 -2
- package/core/ops/owned.js +37 -11
- package/core/ops/sharedPoint.js +5 -1
- package/core/ops/stacks.js +30 -7
- package/core/saves/Saves.js +0 -2
- package/core/saves/saveApply.js +7 -7
- package/core/saves/session.js +6 -3
- package/core/saves/stateReplace.js +71 -41
- package/core/scene/Rays.js +74 -26
- package/core/scene/gameLights.js +19 -11
- package/core/scene/sceneDelta.js +8 -4
- package/core/stream/chunkStream.js +21 -0
- package/core/stream/dirtyWatch.js +37 -0
- package/core/time/skip.js +9 -6
- package/core/time/time.js +72 -18
- package/docs/AI.md +22 -21
- package/docs/API.md +5 -4
- package/docs/CODEMAP.md +16 -10
- package/docs/COMMANDS.md +5 -5
- package/docs/CONVENTIONS.md +9 -25
- package/docs/api/ambience.md +1 -0
- package/docs/api/assets.md +10 -3
- package/docs/api/audio.md +5 -3
- package/docs/api/decals.md +16 -0
- package/docs/api/engine.md +1 -0
- package/docs/api/tools.md +3 -1
- package/docs/api/water.md +3 -0
- package/docs/recipes/09-materials-lights-models.md +15 -1
- package/docs/recipes/13-animation.md +51 -10
- package/docs/recipes/16-dev-bridge.md +1 -1
- package/docs/recipes/31-audio.md +15 -9
- package/docs/recipes/34-environment-lighting.md +11 -1
- package/docs/recipes/44-water-weather-hooks.md +1 -0
- package/examples/action/.threedog/content-index.json +1 -0
- package/examples/perf-island/.threedog/content-index.json +1 -0
- package/examples/plain-picture/.threedog/content-index.json +1 -0
- package/examples/rc2d/.threedog/content-index.json +1 -0
- package/examples/styletest/.threedog/content-index.json +1 -0
- package/examples/techniques/outlines-and-rim/main.js +1 -1
- package/examples/techniques/procedural-surface/main.js +1 -1
- package/examples/techniques/stylized-shading/main.js +1 -1
- package/examples/webgpu-tsl/.threedog/content-index.json +1 -0
- package/examples/world/.threedog/content-index.json +1 -0
- package/index.d.ts +6 -2
- package/index.js +3 -2
- package/llms.txt +11 -10
- package/modules/ambience/Ambience.js +97 -15
- package/modules/camera/common.js +18 -12
- package/modules/characters/Character.js +30 -3
- package/modules/characters/NPC.js +2 -5
- package/modules/characters/astar.js +45 -14
- package/modules/characters/movers/rapier.js +53 -41
- package/modules/characters/movers/simple.js +37 -24
- package/modules/characters/npcView.js +2 -2
- package/modules/characters/pathAsync.js +3 -3
- package/modules/collision/contract.js +2 -2
- package/modules/content/index.js +3 -0
- package/modules/content/models.js +11 -4
- package/modules/content/templates.js +11 -11
- package/modules/debug/DebugPanel.js +1 -0
- package/modules/decals/Decals.js +393 -0
- package/modules/decals/index.js +1 -0
- package/modules/gameplay/Container.js +2 -0
- package/modules/gameplay/Containers.js +17 -3
- package/modules/gameplay/Dialogue.js +1 -1
- package/modules/gameplay/Interactions.js +7 -6
- package/modules/gameplay/Inventory.js +5 -1
- package/modules/gameplay/Quests.js +4 -3
- package/modules/gameplay/inventoryOps.js +2 -2
- package/modules/gameplay/pickups.js +32 -12
- package/modules/gameplay/questSave.js +2 -2
- package/modules/grid/index.js +8 -2
- package/modules/hud/index.js +1 -1
- package/modules/level/heightfield.js +1 -0
- package/modules/level/index.js +3 -2
- package/modules/level/nodes.js +2 -1
- package/modules/lights/index.js +27 -4
- package/modules/lights/slots.js +33 -16
- package/modules/nav/contract.js +4 -4
- package/modules/nav/index.js +6 -2
- package/modules/net/Client.js +24 -11
- package/modules/net/Host.js +73 -20
- package/modules/net/index.js +33 -21
- package/modules/net/sync.js +38 -8
- package/modules/net/transports.js +7 -3
- package/modules/particles/Particles.js +11 -4
- package/modules/particles/contract.js +6 -6
- package/modules/particles/effect.js +0 -1
- package/modules/rigid/RigidBodies.js +69 -57
- package/modules/rigid/Vehicles.js +8 -7
- package/modules/rigid/ragdoll.js +4 -6
- package/modules/rigid/rapierCompat.js +90 -0
- package/modules/rigid/sync.js +2 -5
- package/modules/settings/Settings.js +10 -4
- package/modules/sky/Sky.js +10 -2
- package/modules/sky/environment.js +29 -13
- package/modules/sky/frame.js +2 -2
- package/modules/sky/shader.js +5 -2
- package/modules/sky/skyModule.js +2 -2
- package/modules/swarm/Swarm.js +3 -2
- package/modules/swarm/grid.js +12 -7
- package/modules/terrain/ChunkManager.js +16 -26
- package/modules/triggers/index.js +5 -6
- package/modules/vegetation/draw.js +62 -26
- package/modules/vegetation/groundChunks.js +8 -22
- package/modules/water/Water.js +152 -24
- package/modules/water/surface.js +43 -20
- package/modules/weather/weatherDraw.js +4 -1
- package/modules/world/World.js +21 -2
- package/modules/world/index.js +5 -0
- package/modules/world/persist.js +1 -0
- package/modules/world/records.js +3 -1
- package/modules/world/sim.js +3 -2
- package/modules/world/simFar.js +4 -2
- package/modules/world/state.js +7 -1
- package/package.json +2 -2
- package/presets.js +30 -0
- package/render/PostFX.js +24 -17
- package/render/backend.js +72 -31
- package/render/cascades.js +25 -14
- package/render/cascades.tsl.js +32 -21
- package/render/fogLook.js +2 -1
- package/render/fx/library.tsl.js +1 -1
- package/render/fx/particles.tsl.js +4 -18
- package/render/fx/pcss.tsl.js +2 -2
- package/render/fx/postWebGPU.tsl.js +47 -25
- package/render/fx/sky.tsl.js +6 -18
- package/render/fx/uniforms.tsl.js +16 -0
- package/render/fx/water.tsl.js +24 -5
- package/render/fxNumbers.js +2 -0
- package/render/impostor.tsl.js +10 -6
- package/render/lights.js +6 -6
- package/render/occlusion.js +17 -6
- package/render/patches.js +40 -28
- package/render/postWebGL.js +6 -4
- package/render/reflectionProbes.js +302 -0
- package/render/shaderErrors.js +18 -8
- package/render/shadowCache.tsl.js +10 -5
- package/render/shadows.js +70 -49
- package/render/threeCompat.js +166 -0
- package/types/core.d.ts +33 -3
- package/types/gameplay.d.ts +80 -0
- package/types/generated/core/audio/Audio.d.ts +18 -1
- package/types/generated/core/ops/Ops.d.ts +2 -1
- package/types/generated/core/ops/control.d.ts +7 -3
- package/types/generated/core/saves/session.d.ts +4 -1
- package/types/generated/modules/ambience/Ambience.d.ts +6 -0
- package/types/generated/modules/debug/DebugPanel.d.ts +1 -0
- package/types/generated/modules/grid/index.d.ts +27 -3
- package/types/generated/modules/net/index.d.ts +8 -3
- package/types/generated/modules/sky/Sky.d.ts +1 -0
- package/types/generated/modules/water/Water.d.ts +15 -0
- package/types/generated/modules/world/index.d.ts +5 -0
- package/types/generated/render/patches.d.ts +5 -0
- package/types/physics.d.ts +66 -9
- package/types/tsl.d.ts +2 -0
- package/types/world.d.ts +2 -0
- package/ui/Parts.js +3 -2
- package/docs/MIGRATING-0.7.md +0 -39
- package/docs/MIGRATING-0.8.md +0 -171
- package/modules/rigid/refresh.js +0 -10
|
@@ -22,7 +22,7 @@ import { readParams, keysSchema } from '../../core/base/params.js';
|
|
|
22
22
|
import { cellsChanged } from '../../core/stream/streamCells.js';
|
|
23
23
|
import { createVehicle, VEHICLE_KEYS, STRINGS } from './Vehicles.js';
|
|
24
24
|
import { syncTerrain, syncTrees, treesChanged, syncGroundTrees, syncStatics, restandStatics, syncLevel, syncFloor, dropChunks, wantsFloor, recordLocks, carryBody, carryCollider, carryWorld } from './sync.js';
|
|
25
|
-
import { refreshQueries } from './
|
|
25
|
+
import { loadRapier, warmRapier, refreshQueries, readShapeCastHit } from './rapierCompat.js';
|
|
26
26
|
import { Ragdolls } from './ragdoll.js';
|
|
27
27
|
import { codedError, coded } from '../../core/base/errorHints.js';
|
|
28
28
|
import { refuseSave, saveNumberOk, SAVE_MAX } from '../../core/base/saveValues.js';
|
|
@@ -42,14 +42,33 @@ function worldPose(mesh, who) {
|
|
|
42
42
|
mesh.updateWorldMatrix(true, false); mesh.matrixWorld.decompose(_p, _q, _s);
|
|
43
43
|
return { p: _p, q: _q };
|
|
44
44
|
}
|
|
45
|
-
function setLocalPose(mesh, t, r) {
|
|
45
|
+
function setLocalPose(mesh, t, r, scene = null, sceneIdentity = false) {
|
|
46
46
|
const P = mesh.parent;
|
|
47
|
-
if (!P || P.matrixWorld.equals(_I)) { mesh.position.set(t.x, t.y, t.z); mesh.quaternion.set(r.x, r.y, r.z, r.w); return; }
|
|
47
|
+
if (!P || (sceneIdentity && P === scene) || P.matrixWorld.equals(_I)) { mesh.position.set(t.x, t.y, t.z); mesh.quaternion.set(r.x, r.y, r.z, r.w); return; }
|
|
48
48
|
P.matrixWorld.decompose(_p, _pq, _s);
|
|
49
49
|
mesh.position.copy(P.worldToLocal(_p.set(t.x, t.y, t.z)));
|
|
50
50
|
mesh.quaternion.copy(_pq.invert().multiply(_q.set(r.x, r.y, r.z, r.w)));
|
|
51
51
|
}
|
|
52
52
|
const _I = new THREE.Matrix4(), _eu = new THREE.Euler(), _box = new THREE.Box3(), _part = new THREE.Box3(), _inv = new THREE.Matrix4(), _rel = new THREE.Matrix4();
|
|
53
|
+
const _v3 = { x: 0, y: 0, z: 0 }, _imp = { x: 0, y: 0, z: 0 }, _zero = { x: 0, y: 0, z: 0 };
|
|
54
|
+
const CHUNK_OFF = 524288, CHUNK_MUL = 1048576;
|
|
55
|
+
const inPackRange = (cx, cz) => cx >= -CHUNK_OFF && cx < CHUNK_OFF && cz >= -CHUNK_OFF && cz < CHUNK_OFF;
|
|
56
|
+
const packChunk = (cx, cz) => (cx + CHUNK_OFF) * CHUNK_MUL + (cz + CHUNK_OFF);
|
|
57
|
+
const parseChunkKey = k => {
|
|
58
|
+
if (typeof k !== 'string') return null;
|
|
59
|
+
const i = k.indexOf(',');
|
|
60
|
+
if (i <= 0) return null;
|
|
61
|
+
const cx = Number(k.slice(0, i)), cz = Number(k.slice(i + 1));
|
|
62
|
+
return inPackRange(cx, cz) ? packChunk(cx, cz) : null;
|
|
63
|
+
};
|
|
64
|
+
class TerrainMap extends Map {
|
|
65
|
+
constructor() { super(); this._byInt = new Map(); }
|
|
66
|
+
set(k, v) { const p = parseChunkKey(k); if (p !== null) this._byInt.set(p, v); return super.set(k, v); }
|
|
67
|
+
delete(k) { const p = parseChunkKey(k); if (p !== null) this._byInt.delete(p); return super.delete(k); }
|
|
68
|
+
clear() { this._byInt.clear(); return super.clear(); }
|
|
69
|
+
getAt(cx, cz) { return inPackRange(cx, cz) ? this._byInt.get(packChunk(cx, cz)) : this.get(cx + ',' + cz); }
|
|
70
|
+
hasAt(cx, cz) { return inPackRange(cx, cz) ? this._byInt.has(packChunk(cx, cz)) : this.has(cx + ',' + cz); }
|
|
71
|
+
}
|
|
53
72
|
/**
|
|
54
73
|
* The size a body gets from its model, as [x, y, z]: measured in the mesh's own axes, since the body takes its rotation, and at its world scale, parents included.
|
|
55
74
|
* The box around it in the world grew with the turn, so a turned crate got a larger body turned on top of that.
|
|
@@ -76,36 +95,6 @@ const PHYSICS = { physics: true }; // stream source filter (shared, not rebuil
|
|
|
76
95
|
const SOLID_PARAMS = keysSchema(['position', 'size', 'radius', 'rotation', 'friction']);
|
|
77
96
|
const BODY_KEYS = ['id', 'mass', 'friction', 'restitution', 'damping', 'angularDamping', 'fixed'];
|
|
78
97
|
|
|
79
|
-
/**
|
|
80
|
-
* Run Rapier's step and character-controller code once in a throwaway world, while start() still loads. Why: the browser compiles a WASM
|
|
81
|
-
* function on its first call, and the game world's first step paid that for the whole step path: ~120 ms with 77 colliders on a real GPU
|
|
82
|
-
* machine (built page), the whole "draw" part of the first frame (docs/testing/field/2026-11-03-perf.md). Here it runs while start() waits
|
|
83
|
-
* for the GPU to compile shaders, when the page's thread is idle anyway (a setTimeout instead landed in WebGPU's nearby-build wait and made
|
|
84
|
-
* it 150 ms longer). The game's world is untouched (no game time passes, same results).
|
|
85
|
-
* Once per page: the compiled code belongs to the one WASM instance.
|
|
86
|
-
*/
|
|
87
|
-
const WARMED = new WeakSet();
|
|
88
|
-
function warmRapier(R) {
|
|
89
|
-
if (WARMED.has(R)) return;
|
|
90
|
-
WARMED.add(R);
|
|
91
|
-
const w = new R.World({ x: 0, y: -9.81, z: 0 });
|
|
92
|
-
try {
|
|
93
|
-
w.createCollider(R.ColliderDesc.cuboid(5, 0.5, 5));
|
|
94
|
-
w.createCollider(R.ColliderDesc.trimesh(new Float32Array([-5, 1, -5, 5, 1, -5, 0, 1, 5]), new Uint32Array([0, 1, 2])));
|
|
95
|
-
for (const [i, c] of [R.ColliderDesc.ball(0.5), R.ColliderDesc.cuboid(0.4, 0.4, 0.4), R.ColliderDesc.cylinder(0.4, 0.3), R.ColliderDesc.capsule(0.3, 0.2)].entries())
|
|
96
|
-
w.createCollider(c, w.createRigidBody(R.RigidBodyDesc.dynamic().setTranslation(i - 1.5, 1.2, 0)));
|
|
97
|
-
const kin = w.createRigidBody(R.RigidBodyDesc.kinematicPositionBased().setTranslation(2, 1.5, 2));
|
|
98
|
-
const me = w.createCollider(R.ColliderDesc.capsule(0.5, 0.3), kin);
|
|
99
|
-
const cc = w.createCharacterController(0.01);
|
|
100
|
-
for (let i = 0; i < 3; i++) {
|
|
101
|
-
cc.computeColliderMovement(me, { x: 0.1, y: -0.1, z: 0 });
|
|
102
|
-
kin.setNextKinematicTranslation({ x: 2 + i * 0.1, y: 1.5, z: 2 });
|
|
103
|
-
w.step();
|
|
104
|
-
}
|
|
105
|
-
w.removeCharacterController(cc);
|
|
106
|
-
} finally { w.free(); }
|
|
107
|
-
}
|
|
108
|
-
|
|
109
98
|
export class RigidBodies {
|
|
110
99
|
/** terrainRing = chunk rings around each physics stream source that get terrain collision; buoyancyForce = buoyancy strength (1 = exactly floats); waterDrag = drag in water;
|
|
111
100
|
* floatLine / floatDepth: buoyancy starts when the body center is below floatLine meters above the surface and peaks floatDepth meters deeper;
|
|
@@ -127,7 +116,8 @@ export class RigidBodies {
|
|
|
127
116
|
this.bodies = []; // { body, mesh, enabled }
|
|
128
117
|
/** @internal body handle -> entry for rays, rebuilt only after bodies changed (null): a ray cast every frame (aim, a camera probe) built a new Map each time */ this._byHandle = null;
|
|
129
118
|
/** @internal a session:end asked for a rebuild that world:load / afterLoad has not run yet (one rebuild per new game or load) */ this._freshDue = false;
|
|
130
|
-
this.terrain = new
|
|
119
|
+
this.terrain = new TerrainMap(); // chunk key -> { colliders: [] }, indexed by packed 20-bit int for O(1) zero-alloc step lookup
|
|
120
|
+
/** @internal reused Rapier Ray for _raycast */ this._ray = null;
|
|
131
121
|
this.trees = new Map(); // chunk key -> { token, colliders }: trunk cylinders of the chunks near the player / bodies (see sync.js)
|
|
132
122
|
this._anchors = []; this._treeMemo = [];
|
|
133
123
|
this.groundTrees = new Map(); // 'x,z,r' -> cylinder collider: circles from ground.forEachCollider when the ground has no chunked collision
|
|
@@ -145,7 +135,7 @@ export class RigidBodies {
|
|
|
145
135
|
* @internal Import and instantiate Rapier once. Started at install: the import plus WASM compile took 0.8-1.1 s on a cold start and used to
|
|
146
136
|
* begin only when start() reached this module's init, with every later init waiting behind it; begun at install it overlaps the world build
|
|
147
137
|
*/
|
|
148
|
-
_wasm() { return (this._rapier ??=
|
|
138
|
+
_wasm() { return (this._rapier ??= loadRapier()); }
|
|
149
139
|
|
|
150
140
|
/** @internal module hook */
|
|
151
141
|
async init(signal) {
|
|
@@ -183,7 +173,7 @@ export class RigidBodies {
|
|
|
183
173
|
/** @internal Copies of what others own are current, as any read needs them. Every step runs it; a frozen engine runs no step, and queries still ask */
|
|
184
174
|
_upkeep() { if (syncStatics(this) | syncLevel(this) | syncFloor(this) | dropChunks(this)) this._behind = true; }
|
|
185
175
|
/**
|
|
186
|
-
* @internal Every query starts here, and answers whether physics can be asked. Rapier has no call that refreshes its query structures alone (
|
|
176
|
+
* @internal Every query starts here, and answers whether physics can be asked. Rapier has no call that refreshes its query structures alone (rapierCompat.js), so a step of no time does, twice (one leaves a moved body or a reused collider slot out, measured in `refresh while frozen`): nothing
|
|
187
177
|
* moves, and it runs only when something changed, so a ray pays three compares.
|
|
188
178
|
*/
|
|
189
179
|
_current() {
|
|
@@ -209,7 +199,13 @@ export class RigidBodies {
|
|
|
209
199
|
this._freshDue = false;
|
|
210
200
|
if (!this.ready) return;
|
|
211
201
|
if (this.vehicles.length) {
|
|
212
|
-
for (const b of this.bodies) {
|
|
202
|
+
for (const b of this.bodies) {
|
|
203
|
+
const y = b.body;
|
|
204
|
+
y.setLinvel({ x: 0, y: 0, z: 0 }, false); y.setAngvel({ x: 0, y: 0, z: 0 }, false); y.resetForces(false); y.resetTorques(false);
|
|
205
|
+
if (b.wet) { y.setLinearDamping(b.damping); y.setAngularDamping(b.angularDamping); }
|
|
206
|
+
b.wet = false; b._void = false; b._fell = false;
|
|
207
|
+
if (y.isDynamic()) y.sleep();
|
|
208
|
+
}
|
|
213
209
|
return;
|
|
214
210
|
}
|
|
215
211
|
const old = this.world, R = this.rapier, hadJoints = old.impulseJoints.len();
|
|
@@ -344,10 +340,10 @@ export class RigidBodies {
|
|
|
344
340
|
return this._chunkReady(x, z);
|
|
345
341
|
}
|
|
346
342
|
/** @internal */
|
|
347
|
-
_chunkReady(x, z) { const CH = this.engine.ground.chunkSize ?? 64; return !!this.terrain.
|
|
343
|
+
_chunkReady(x, z) { const CH = this.engine.ground.chunkSize ?? 64; return !!this.terrain.getAt(Math.floor(x / CH), Math.floor(z / CH))?.ready; }
|
|
348
344
|
/** @internal A moving body left the terrain colliders. Told once in dev; not told: a body at rest left behind (normal), a chunk still waiting for its collider (it has a terrain entry, or chunks are pending) */
|
|
349
345
|
_tellFrozen(b, t, CH) {
|
|
350
|
-
if (this._srcPending || !b.body.isDynamic() || b.body.isSleeping() || this.terrain.
|
|
346
|
+
if (this._srcPending || !b.body.isDynamic() || b.body.isSleeping() || this.terrain.hasAt(Math.floor(t.x / CH), Math.floor(t.z / CH))) return;
|
|
351
347
|
warnOnce(coded('rigid-misuse', `rigid: body '${b.id ?? (b.mesh.name || 'unnamed')}' froze at x ${t.x.toFixed(0)}, z ${t.z.toFixed(0)} (entry.enabled is false): it left rigid({ terrainRing: ${this.terrainRing} }), the ${CH} m chunks around the player that have terrain colliders, and would fall through the ground. It stays frozen until the player comes near. A body that must keep moving out there needs a larger terrainRing (recipe 11 section 3)`), 'rigid-frozen');
|
|
352
348
|
}
|
|
353
349
|
/** Delete the body (called by entry.remove()); the model stays */
|
|
@@ -358,12 +354,13 @@ export class RigidBodies {
|
|
|
358
354
|
entry._pose.remove();
|
|
359
355
|
}
|
|
360
356
|
/** Push: impulse vector v (Vector3 / [x, y, z] / { x, y, z }) */
|
|
361
|
-
impulse(entry, v) { const { x, y, z } = vec3(v); entry.body.wakeUp(); entry.body.applyImpulse(
|
|
357
|
+
impulse(entry, v) { const { x, y, z } = vec3(v); _v3.x = x; _v3.y = y; _v3.z = z; entry.body.wakeUp(); entry.body.applyImpulse(_v3, true); }
|
|
362
358
|
/** Teleport to position (velocity zeroed) */
|
|
363
359
|
setPosition(entry, position) {
|
|
364
360
|
const { x, y, z } = vec3(position);
|
|
365
361
|
entry._x = x; entry._z = z;
|
|
366
|
-
|
|
362
|
+
_v3.x = x; _v3.y = y; _v3.z = z;
|
|
363
|
+
entry.body.setTranslation(_v3, true); entry.body.setLinvel(_zero, true); this._behind = true;
|
|
367
364
|
}
|
|
368
365
|
|
|
369
366
|
// ---------- The collider3d contract (collider3d.contract.js): engine.collider3d is this object ----------
|
|
@@ -406,8 +403,8 @@ export class RigidBodies {
|
|
|
406
403
|
d.divideScalar(len);
|
|
407
404
|
const hit = this.world.castShape({ x: a.x, y: a.y, z: a.z }, NO_TURN, { x: d.x, y: d.y, z: d.z }, new R.Ball(radius), 0, len, false, R.QueryFilterFlags.EXCLUDE_SENSORS, undefined, undefined, this.playerBody);
|
|
408
405
|
if (!hit) return null;
|
|
409
|
-
const
|
|
410
|
-
return { point: a.addScaledVector(d,
|
|
406
|
+
const { timeOfImpact, normal: n } = readShapeCastHit(hit);
|
|
407
|
+
return { point: a.addScaledVector(d, timeOfImpact), normal: new THREE.Vector3(n.x, n.y, n.z), distance: timeOfImpact };
|
|
411
408
|
}
|
|
412
409
|
|
|
413
410
|
/** Ray (provider for engine.rays, called by engine.raycast when targets: 'all'): hits dynamic bodies only, returns RayHit (with entry, kind: 'rigid') */
|
|
@@ -417,7 +414,10 @@ export class RigidBodies {
|
|
|
417
414
|
if (!byHandle) { byHandle = this._byHandle = new Map(); for (const b of this.bodies) byHandle.set(b.body.handle, b); }
|
|
418
415
|
const max = Number.isFinite(far) ? far : 1e6;
|
|
419
416
|
const only = c => byHandle.has(c.parent()?.handle);
|
|
420
|
-
|
|
417
|
+
let ray = this._ray;
|
|
418
|
+
if (!ray) ray = this._ray = new this.rapier.Ray({ x: origin.x, y: origin.y, z: origin.z }, { x: dir.x, y: dir.y, z: dir.z });
|
|
419
|
+
else { ray.origin.x = origin.x; ray.origin.y = origin.y; ray.origin.z = origin.z; ray.dir.x = dir.x; ray.dir.y = dir.y; ray.dir.z = dir.z; }
|
|
420
|
+
const hit = this.world.castRayAndGetNormal(ray, max, true, undefined, undefined, undefined, this.playerBody, only);
|
|
421
421
|
if (!hit) return null;
|
|
422
422
|
const entry = byHandle.get(hit.collider.parent()?.handle);
|
|
423
423
|
if (!entry) return null;
|
|
@@ -444,7 +444,7 @@ export class RigidBodies {
|
|
|
444
444
|
// a body past float precision (x = -1e308) sends the ground loops around it spinning and the page never comes back: damage, refused like a damaged world record (world/persist.js)
|
|
445
445
|
for (const [id, s] of Object.entries(d ?? {}))
|
|
446
446
|
if (!Array.isArray(s) || s.length !== 14 || !s.every(v => typeof v === 'boolean' || saveNumberOk(v))) refuseSave('rigid', `body '${id}'`, `must be a list of 14 numbers within ±${SAVE_MAX}`, s);
|
|
447
|
-
this._saved = new Map(Object.entries(d ?? {}));
|
|
447
|
+
this._saved = new Map(Object.entries(d ?? {}));
|
|
448
448
|
}
|
|
449
449
|
/** @internal afterLoad: hand the loaded state to the bodies that exist (vehicles, bodies the game keeps across a load) */
|
|
450
450
|
_claimSaved() {
|
|
@@ -496,37 +496,48 @@ export class RigidBodies {
|
|
|
496
496
|
}
|
|
497
497
|
// player capsule follows the player (the rapier mover computes collision and writes the position itself); turned off while driving to avoid colliding with
|
|
498
498
|
// the car
|
|
499
|
-
if (e.player)
|
|
499
|
+
if (e.player) { _v3.x = focus.x; _v3.y = focus.y; _v3.z = focus.z; this.playerBody.setNextKinematicTranslation(_v3); }
|
|
500
500
|
// no player, no capsule: with no player nothing moves it, and it would sit as an invisible solid body at the origin
|
|
501
501
|
const onFoot = !!e.player && !e.player.vehicle && !this._ragdolls?.holds(e.player);
|
|
502
502
|
if (this.playerCollider.isEnabled() !== onFoot) this.playerCollider.setEnabled(onFoot);
|
|
503
503
|
if (worldDt > 0) for (const v of this.vehicles) if (v.enabled) v._update(worldDt);
|
|
504
504
|
|
|
505
505
|
// freeze bodies without terrain collision under them (unfrozen they would fall through)
|
|
506
|
+
const waterCheck = worldDt > 0 && this.buoyancy;
|
|
506
507
|
for (const b of this.bodies) {
|
|
508
|
+
if (b.enabled && b.body.isSleeping() && !b.wet) {
|
|
509
|
+
if (chunked && !this._chunkReady(b._x, b._z)) {
|
|
510
|
+
if (DEV) this._tellFrozen(b, b.body.translation(), CH);
|
|
511
|
+
b.body.setEnabled(false); b.enabled = false;
|
|
512
|
+
}
|
|
513
|
+
continue;
|
|
514
|
+
}
|
|
507
515
|
const t = b.body.translation();
|
|
508
516
|
b._x = t.x; b._z = t.z;
|
|
509
517
|
const ok = !chunked || this._chunkReady(t.x, t.z);
|
|
510
518
|
if (ok !== b.enabled) { if (DEV && !ok) this._tellFrozen(b, t, CH); b.body.setEnabled(ok); b.enabled = ok; }
|
|
511
519
|
// buoyancy: the submerged part gets an upward force, and water adds drag
|
|
512
|
-
|
|
513
|
-
|
|
514
|
-
|
|
515
|
-
|
|
516
|
-
|
|
517
|
-
|
|
518
|
-
|
|
519
|
-
|
|
520
|
-
|
|
520
|
+
if (waterCheck) {
|
|
521
|
+
const water = e.waterAt(t.x, t.z, t.y); // at its own height: a game's water body may be a pool upstairs or a falling column
|
|
522
|
+
if (ok && t.y < water + this.floatLine && b.body.isDynamic()) {
|
|
523
|
+
const depth = Math.min(1, (water + this.floatLine - t.y) / this.floatDepth);
|
|
524
|
+
const m = b.body.mass();
|
|
525
|
+
_imp.x = 0; _imp.y = -this.gravity * m * (this.buoyancyForce * depth) * worldDt; _imp.z = 0;
|
|
526
|
+
b.body.applyImpulse(_imp, true); // an impulse, not addForce: Rapier keeps forces until reset, and a reset would wipe the game's own thrust / wind on the same body
|
|
527
|
+
if (!b.wet) { b.body.setLinearDamping(this.waterDrag); b.body.setAngularDamping(this.waterDrag); b.wet = true; }
|
|
528
|
+
} else if (b.wet) {
|
|
529
|
+
b.body.setLinearDamping(b.damping); b.body.setAngularDamping(b.angularDamping); b.wet = false;
|
|
530
|
+
}
|
|
521
531
|
}
|
|
522
532
|
}
|
|
523
533
|
|
|
524
534
|
if (worldDt > 0) { this.world.timestep = worldDt; this.world.step(); this._behind = false; }
|
|
525
535
|
|
|
536
|
+
const scene = e.scene, sceneIdentity = scene.matrixWorld.equals(_I);
|
|
526
537
|
for (const b of this.bodies) {
|
|
527
538
|
if (!b.enabled || b.body.isSleeping() || b.ragdoll) continue; // ragdoll parts are drawn by ragdoll.js, through the bones
|
|
528
539
|
const t = b.body.translation(), r = b.body.rotation();
|
|
529
|
-
setLocalPose(b.mesh, t, r);
|
|
540
|
+
setLocalPose(b.mesh, t, r, scene, sceneIdentity);
|
|
530
541
|
this._fallen(b, t);
|
|
531
542
|
// fell off terrain({ shape }): one terrain:void per fall, the game decides what next
|
|
532
543
|
const under = t.y < e.ground.voidY();
|
|
@@ -586,6 +597,7 @@ export function rigid(opts = {}) {
|
|
|
586
597
|
r._wasm().catch(() => {}); // start loading now (see _wasm); a failure surfaces in init, which awaits the same promise
|
|
587
598
|
ctx.budget.metric('rigidBodies', () => r.bodies.length);
|
|
588
599
|
ctx.stream.addReadyCheck('rigid', s => !s.physics || r.ready && r.readyAt(s)); // a physics stream source waits for the collider under it
|
|
600
|
+
ctx.feeds('interactions', () => { for (const v of r.vehicles) v._offerSeat?.(); });
|
|
589
601
|
ctx.track(e.rays.addProvider((o, d, far) => r._raycast(o, d, far))); // engine.raycast(..., { targets: 'all' }) includes rigid bodies
|
|
590
602
|
// A refused load (session:failed) leaves the game as it was, physics included: no afterLoad runs after a rollback, so the state its rigid part read back is claimed here.
|
|
591
603
|
ctx.track(e.events.on('ground:change', b => { r._srcPending = true; restandStatics(r, b); })); // dug or raised ground: colliders follow on the next step, not at the half-second check a body could fall through
|
|
@@ -598,7 +610,7 @@ export function rigid(opts = {}) {
|
|
|
598
610
|
// it, afterLoad (newGame / load / quit all apply a save) runs it. Rebuilding in both steps built the world twice per new game.
|
|
599
611
|
sessionEnd() { r._freshDue = true; },
|
|
600
612
|
worldLoad() { r._fresh(); },
|
|
601
|
-
afterLoad() { if (r._freshDue) r._fresh(); r._claimSaved(); }, // after every part loaded and _fresh rebuilt the world (world:load is emitted inside the world part's load)
|
|
613
|
+
afterLoad() { if (r._freshDue) r._fresh(); r._ragdolls?.load(); r._claimSaved(); }, // after every part loaded and _fresh rebuilt the world (world:load is emitted inside the world part's load)
|
|
602
614
|
async init(e, ctx) { await r.init(ctx.signal); ctx.whileCompiling(() => warmRapier(r.rapier)); },
|
|
603
615
|
counts() { return r.bodies.length; }, // engine.counts().rigid
|
|
604
616
|
// bodies by type and what they are doing: sleeping = at rest (normal), frozen = disabled because no terrain collider is under them yet (they wait, not fall)
|
|
@@ -10,6 +10,7 @@
|
|
|
10
10
|
import * as THREE from 'three';
|
|
11
11
|
import { vec3 } from '../../core/base/math.js';
|
|
12
12
|
import { ownBox } from './RigidBodies.js';
|
|
13
|
+
import { setVehicleAxes } from './rapierCompat.js';
|
|
13
14
|
|
|
14
15
|
export const VEHICLE_KEYS = ['id', 'wheels', 'mass', 'engineForce', 'brakeForce', 'maxSteer', 'suspension', 'seats', 'hideDriver', 'camera', 'size', 'friction', 'exitOffset'];
|
|
15
16
|
export const STRINGS = { 'zh-CN': { 'vehicle.enter': '上车', 'vehicle.exit': '下车' }, en: { 'vehicle.enter': 'Get in', 'vehicle.exit': 'Get out' } };
|
|
@@ -24,7 +25,7 @@ export function createVehicle(rigid, mesh, { wheels, mass = 800, engineForce = 8
|
|
|
24
25
|
const s = size ? new THREE.Vector3().fromArray(size) : box.getSize(new THREE.Vector3()), c = size ? new THREE.Vector3() : box.getCenter(new THREE.Vector3());
|
|
25
26
|
const entry = rigid._add(mesh, R.ColliderDesc.cuboid(s.x / 2, s.y / 2, s.z / 2).setTranslation(c.x, c.y, c.z), { id, mass, friction: 0.5, damping: 0.1, angularDamping: 0.5 });
|
|
26
27
|
const ctl = w.createVehicleController(entry.body);
|
|
27
|
-
ctl
|
|
28
|
+
setVehicleAxes(ctl, 1, 2); // up = Y, forward = Z
|
|
28
29
|
const { rest = 0.3, stiffness = 30, damping = 4 } = suspension;
|
|
29
30
|
wheels.forEach((wh, i) => {
|
|
30
31
|
const at = vec3(wh.position);
|
|
@@ -39,7 +40,7 @@ export function createVehicle(rigid, mesh, { wheels, mass = 800, engineForce = 8
|
|
|
39
40
|
const drives = wheels.filter(x => x.drive).length || wheels.length;
|
|
40
41
|
// seat 0 drives, the rest ride; without seats one driver seat at the chassis center
|
|
41
42
|
const seatAt = seats?.length ? seats.map(p => vec3(p)) : [new THREE.Vector3(c.x, c.y, c.z)];
|
|
42
|
-
let throttle = 0, steerIn = 0, brake = 0
|
|
43
|
+
let throttle = 0, steerIn = 0, brake = 0;
|
|
43
44
|
|
|
44
45
|
const v = Object.assign(entry, {
|
|
45
46
|
controller: ctl, wheels, driver: null, camera, hideDriver, seats: seatAt.length, passengers: [],
|
|
@@ -55,7 +56,6 @@ export function createVehicle(rigid, mesh, { wheels, mass = 800, engineForce = 8
|
|
|
55
56
|
},
|
|
56
57
|
/** Every fixed step: write controls to the wheels and advance the vehicle controller (called before the physics step) */
|
|
57
58
|
_update(dt) {
|
|
58
|
-
if (useFrom !== e.interactions) offerSeat();
|
|
59
59
|
wheels.forEach((wh, i) => {
|
|
60
60
|
ctl.setWheelEngineForce(i, wh.drive || drives === wheels.length ? throttle * engineForce / drives : 0);
|
|
61
61
|
ctl.setWheelSteering(i, wh.steer ? -steerIn * maxSteer : 0);
|
|
@@ -81,18 +81,19 @@ export function createVehicle(rigid, mesh, { wheels, mass = 800, engineForce = 8
|
|
|
81
81
|
return l.x * fwd.x + l.y * fwd.y + l.z * fwd.z;
|
|
82
82
|
} });
|
|
83
83
|
// With the interactions module installed: press the interact key near the car to get in, and again while driving to get out
|
|
84
|
+
const riderOf = actor => (actor ? e.control.characterOf(actor) : null) ?? e.player;
|
|
84
85
|
const offerSeat = () => {
|
|
85
86
|
v._use?.remove(); v._use = null;
|
|
86
|
-
useFrom = e.interactions; // the use lives in that module: another one starts empty, so _update offers the seat again
|
|
87
87
|
if (!e.interactions) return;
|
|
88
88
|
v._use = e.interactions.add(mesh, {
|
|
89
89
|
id: v.id,
|
|
90
|
-
label: () => e.t(
|
|
90
|
+
label: (_, ctx) => e.t(riderOf(ctx?.actor)?.vehicle === v ? 'vehicle.exit' : 'vehicle.enter'), radius: Math.max(3, s.z / 2 + 1.5),
|
|
91
91
|
// in it: get out; else get in while a seat is free (driver first, then passenger seats)
|
|
92
|
-
enabled: () => !!
|
|
93
|
-
onUse: () =>
|
|
92
|
+
enabled: (_, ctx) => { const r = riderOf(ctx?.actor); return !!r && (r.vehicle === v || !v.driver || v.passengers.length < v.seats - 1); },
|
|
93
|
+
onUse: (_, ctx) => { const r = riderOf(ctx?.actor); if (r) return r.vehicle === v ? r.exit() : r.enter(v); },
|
|
94
94
|
});
|
|
95
95
|
};
|
|
96
|
+
v._offerSeat = offerSeat;
|
|
96
97
|
offerSeat();
|
|
97
98
|
v._seatBook = e.characters?.addVehicle(v); // after the use: a rider seated here finds a finished vehicle
|
|
98
99
|
return v;
|
package/modules/rigid/ragdoll.js
CHANGED
|
@@ -8,7 +8,7 @@
|
|
|
8
8
|
// so the limit zero is the bind pose, whatever pose the animation was in at the start. Using bone orientation directly gives every joint an error the moment it is created and it blows apart on the first step.
|
|
9
9
|
// - Only the root part writes a position, other bones write rotation only: child bones keep their local offsets, so bone length cannot change and the mesh cannot stretch (the forum post this was modelled on fails right here).
|
|
10
10
|
// - Parts go through rigid's _add: buoyancy, freezing while terrain is not ready, engine.raycast and world rebuild all come for free; no second copy.
|
|
11
|
-
// - Not saved:
|
|
11
|
+
// - Not saved: once a load commits (afterLoad: new game, load and saves.load all run it) every ragdoll ends and a normal character comes back; a refused load rolls back without afterLoad, so the ragdoll keeps lying there.
|
|
12
12
|
// On a world rebuild without a load, rigid carries the bodies over and this rebuilds the joints on rigid:rebuilt.
|
|
13
13
|
// - Self-collision is off: capsules of neighbouring parts overlap at the start and would push each other away; the limits keep the pose.
|
|
14
14
|
// shortcut: one collision group, so ragdolls do not collide with each other either; to pile bodies up, give each ragdoll its own group bit.
|
|
@@ -17,6 +17,7 @@ import { vec3 } from '../../core/base/math.js';
|
|
|
17
17
|
import { readParams, keysSchema } from '../../core/base/params.js';
|
|
18
18
|
import { codedError } from '../../core/base/errorHints.js';
|
|
19
19
|
import { humanoidGraph, shapeParts } from './ragdollBones.js';
|
|
20
|
+
import { configureSphericalJoint } from './rapierCompat.js';
|
|
20
21
|
|
|
21
22
|
const KEYS = keysSchema(['impulse', 'position', 'bones', 'limits', 'mass']);
|
|
22
23
|
const GROUP = (0x8000 << 16 | 0x7fff) >>> 0; // the high 16 bits are its own group, the low 16 bits say what it can touch: everything except its own group
|
|
@@ -138,7 +139,7 @@ export class Ragdolls {
|
|
|
138
139
|
return [[lim.twist, f.x], [lim.side, f.y], [lim.bend, f.z]].map(([[lo, hi], c]) => { const x = ang(c); return [Math.min(lo, x - 0.02), Math.max(hi, x + 0.02)]; });
|
|
139
140
|
}
|
|
140
141
|
|
|
141
|
-
/** Build the joints; runs again after a world rebuild.
|
|
142
|
+
/** Build the joints; runs again after a world rebuild. Three-axis limits and damping go through rapierCompat.configureSphericalJoint */
|
|
142
143
|
_joints(rd) {
|
|
143
144
|
const { r } = this, R = r.rapier, w = r.world, zero = { x: 0, y: 0, z: 0 };
|
|
144
145
|
rd.joints = [];
|
|
@@ -147,10 +148,7 @@ export class Ragdolls {
|
|
|
147
148
|
const j = w.createImpulseJoint(R.JointData.spherical(p.anchor, zero), p.parent.entry.body, p.entry.body, true);
|
|
148
149
|
const F = p.shape.frame, f = { x: F.x, y: F.y, z: F.z, w: F.w };
|
|
149
150
|
j.setLocalFrame1(p.anchor, f); j.setLocalFrame2(zero, f);
|
|
150
|
-
|
|
151
|
-
j.rawSet.jointSetLimits(j.handle, axis, p.range[i][0], p.range[i][1]);
|
|
152
|
-
j.rawSet.jointConfigureMotorVelocity(j.handle, axis, 0, FRICTION);
|
|
153
|
-
});
|
|
151
|
+
configureSphericalJoint(R, j, p.range, FRICTION);
|
|
154
152
|
rd.joints.push(j);
|
|
155
153
|
}
|
|
156
154
|
}
|
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
// Rapier 0.21 compatibility layer: isolates WASM loading, first-step JIT warm-up, and query-pipeline refresh quirks in one place.
|
|
2
|
+
// Upgrading @dimforge/rapier3d-compat should only require adjusting this file.
|
|
3
|
+
|
|
4
|
+
const WARMED = new WeakSet();
|
|
5
|
+
|
|
6
|
+
/** @internal Load and initialize @dimforge/rapier3d-compat */
|
|
7
|
+
export function loadRapier() {
|
|
8
|
+
return import('@dimforge/rapier3d-compat').then(async mod => {
|
|
9
|
+
const R = mod.default ?? mod;
|
|
10
|
+
await R.init();
|
|
11
|
+
return R;
|
|
12
|
+
});
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* @internal Run Rapier's step and character-controller code once in a throwaway world while start() still loads,
|
|
17
|
+
* paying WASM JIT compilation off the first-frame critical path. Once per WASM instance.
|
|
18
|
+
*/
|
|
19
|
+
export function warmRapier(R) {
|
|
20
|
+
if (WARMED.has(R)) return;
|
|
21
|
+
WARMED.add(R);
|
|
22
|
+
const w = new R.World({ x: 0, y: -9.81, z: 0 });
|
|
23
|
+
try {
|
|
24
|
+
w.createCollider(R.ColliderDesc.cuboid(5, 0.5, 5));
|
|
25
|
+
w.createCollider(R.ColliderDesc.trimesh(new Float32Array([-5, 1, -5, 5, 1, -5, 0, 1, 5]), new Uint32Array([0, 1, 2])));
|
|
26
|
+
for (const [i, c] of [R.ColliderDesc.ball(0.5), R.ColliderDesc.cuboid(0.4, 0.4, 0.4), R.ColliderDesc.cylinder(0.4, 0.3), R.ColliderDesc.capsule(0.3, 0.2)].entries())
|
|
27
|
+
w.createCollider(c, w.createRigidBody(R.RigidBodyDesc.dynamic().setTranslation(i - 1.5, 1.2, 0)));
|
|
28
|
+
const kin = w.createRigidBody(R.RigidBodyDesc.kinematicPositionBased().setTranslation(2, 1.5, 2));
|
|
29
|
+
const me = w.createCollider(R.ColliderDesc.capsule(0.5, 0.3), kin);
|
|
30
|
+
const cc = w.createCharacterController(0.01);
|
|
31
|
+
for (let i = 0; i < 3; i++) {
|
|
32
|
+
cc.computeColliderMovement(me, { x: 0.1, y: -0.1, z: 0 });
|
|
33
|
+
kin.setNextKinematicTranslation({ x: 2 + i * 0.1, y: 1.5, z: 2 });
|
|
34
|
+
w.step();
|
|
35
|
+
}
|
|
36
|
+
w.removeCharacterController(cc);
|
|
37
|
+
} finally { w.free(); }
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/**
|
|
41
|
+
* @internal Rapier 0.21 keeps its query structures in the broad phase, and only a step rebuilds them:
|
|
42
|
+
* World has no updateSceneQueries / query pipeline, and propagateModifiedBodyPositionsToColliders does not update the broad phase.
|
|
43
|
+
* Two zero-timestep steps catch up moved colliders without advancing simulation.
|
|
44
|
+
*/
|
|
45
|
+
export function refreshQueries(world) {
|
|
46
|
+
const dt = world.timestep;
|
|
47
|
+
world.timestep = 0;
|
|
48
|
+
try { world.step(); world.step(); } finally { world.timestep = dt; }
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/**
|
|
52
|
+
* @internal Rapier 0.21 exposes `indexUpAxis` as a getter+setter, `indexForwardAxis` as a getter-only property,
|
|
53
|
+
* and `setIndexForwardAxis` as a setter-only property (not a method). Isolating this here prevents future typos or upgrade breakage.
|
|
54
|
+
*/
|
|
55
|
+
export function setVehicleAxes(ctl, up = 1, forward = 2) {
|
|
56
|
+
ctl.indexUpAxis = up;
|
|
57
|
+
if ('setIndexForwardAxis' in ctl) ctl.setIndexForwardAxis = forward;
|
|
58
|
+
else ctl.indexForwardAxis = forward;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/**
|
|
62
|
+
* @internal Rapier 0.21's JS layer only exposes setLimits for single-axis joints; three-axis angular limits and damping on a spherical (Generic) joint go through rawSet.
|
|
63
|
+
*/
|
|
64
|
+
export function configureSphericalJoint(R, joint, ranges, friction) {
|
|
65
|
+
const axes = [R.JointAxis.AngX, R.JointAxis.AngY, R.JointAxis.AngZ];
|
|
66
|
+
for (let i = 0; i < 3; i++) {
|
|
67
|
+
joint.rawSet.jointSetLimits(joint.handle, axes[i], ranges[i][0], ranges[i][1]);
|
|
68
|
+
joint.rawSet.jointConfigureMotorVelocity(joint.handle, axes[i], 0, friction);
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/**
|
|
73
|
+
* @internal Rapier 0.21 exposes `contact_natural_frequency` as a setter without a getter: recover it from `contact_erp`
|
|
74
|
+
* (erp = a*f / (a*f + c), a = 2*pi*dt) by probing a known frequency on the new world so no Rapier constant is copied.
|
|
75
|
+
*/
|
|
76
|
+
export function copyContactFrequency(oldParams, newParams) {
|
|
77
|
+
const proto = Object.getPrototypeOf(oldParams), d = k => Object.getOwnPropertyDescriptor(proto, k);
|
|
78
|
+
if (!d('contact_natural_frequency')?.set || !d('contact_erp')?.get) return;
|
|
79
|
+
const a0 = 2 * Math.PI * oldParams.dt, a1 = 2 * Math.PI * newParams.dt, f1 = 30;
|
|
80
|
+
newParams.contact_natural_frequency = f1;
|
|
81
|
+
const e0 = oldParams.contact_erp, e1 = newParams.contact_erp, c = a1 * f1 * (1 - e1) / e1;
|
|
82
|
+
if (e0 > 0 && e0 < 1) newParams.contact_natural_frequency = c * e0 / ((1 - e0) * a0);
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/**
|
|
86
|
+
* @internal Rapier 0.21's World.castShape returns snake_case `time_of_impact` and world-space `normal1` (unlike castRayAndGetNormal's `timeOfImpact` / `normal`).
|
|
87
|
+
*/
|
|
88
|
+
export function readShapeCastHit(hit) {
|
|
89
|
+
return { timeOfImpact: hit.time_of_impact ?? hit.timeOfImpact, normal: hit.normal1 ?? hit.normal };
|
|
90
|
+
}
|
package/modules/rigid/sync.js
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
// Colliders the rigid module keeps in sync with what the game draws: terrain chunks (trimesh + trunk cylinders), trunks on a level or code-built ground, the
|
|
2
2
|
// collision module's houses / pillars, and a level's static ground. Each function takes the RigidBodies instance as `r` and is called from its step().
|
|
3
3
|
import * as THREE from 'three';
|
|
4
|
+
import { copyContactFrequency } from './rapierCompat.js';
|
|
4
5
|
|
|
5
6
|
// Chunks around physics stream sources ([cx, cz, rings] each): terrain uses triangle-mesh colliders (identical to what is drawn), vegetation uses cylinders.
|
|
6
7
|
// Data comes from the ground API ground.chunkCollision
|
|
@@ -231,11 +232,7 @@ export function carryBody(entry, o, n) {
|
|
|
231
232
|
export function carryWorld(o, n) {
|
|
232
233
|
const proto = Object.getPrototypeOf(o), d = k => Object.getOwnPropertyDescriptor(proto, k);
|
|
233
234
|
for (const k of Object.getOwnPropertyNames(proto)) if (k !== 'dt' && d(k).set && d(k).get && o[k] !== n[k]) n[k] = o[k];
|
|
234
|
-
|
|
235
|
-
const a0 = 2 * Math.PI * o.dt, a1 = 2 * Math.PI * n.dt, f1 = 30;
|
|
236
|
-
n.contact_natural_frequency = f1;
|
|
237
|
-
const e0 = o.contact_erp, e1 = n.contact_erp, c = a1 * f1 * (1 - e1) / e1;
|
|
238
|
-
if (e0 > 0 && e0 < 1) n.contact_natural_frequency = c * e0 / ((1 - e0) * a0);
|
|
235
|
+
copyContactFrequency(o, n);
|
|
239
236
|
}
|
|
240
237
|
|
|
241
238
|
/** @internal Copy game-set collider state from the old collider onto the one rebuilt from the entry's desc */
|
|
@@ -65,7 +65,7 @@ const DEFINE_KEYS = keysSchema(['apply', 'limits', 'menu', 'label', 'options', '
|
|
|
65
65
|
* @param {any} sections @returns {Set<string>}
|
|
66
66
|
*/
|
|
67
67
|
function omittedRows(sections) {
|
|
68
|
-
const entry = Array.isArray(sections) ? sections.find(s => typeof s === 'object') : null;
|
|
68
|
+
const entry = Array.isArray(sections) ? sections.find(s => s && typeof s === 'object') : null;
|
|
69
69
|
if (!entry) return new Set();
|
|
70
70
|
readParams('settings sections', keysSchema(['id', 'omit']), entry);
|
|
71
71
|
const rows = ['quality', 'adaptive', ...Object.keys(PRESETS.low)], bad = (entry.omit ?? []).filter(k => !rows.includes(k));
|
|
@@ -163,7 +163,7 @@ export class Settings extends SettingsView {
|
|
|
163
163
|
*/
|
|
164
164
|
get _omit() { return pixelSizeOn(this.engine) ? new Set([...this._leftOut, 'pixelRatio', 'adaptive']) : this._leftOut; }
|
|
165
165
|
get values() { return { ...this._values, pixelRatio: +this.engine.renderer.getPixelRatio().toFixed(2) }; }
|
|
166
|
-
get(key) { return this.
|
|
166
|
+
get(key) { return key === 'pixelRatio' ? +this.engine.renderer.getPixelRatio().toFixed(2) : this._values[key]; }
|
|
167
167
|
/** @internal Someone answers for this key: a built-in row, a defined one, or a bus's slider @param {string} key */
|
|
168
168
|
_hasRow(key) { return key in this._defaults || this.custom.has(key) || (key.startsWith('vol.') && key.slice(4) in this.engine.audio.levels); }
|
|
169
169
|
/**
|
|
@@ -178,7 +178,7 @@ export class Settings extends SettingsView {
|
|
|
178
178
|
}
|
|
179
179
|
this._values[key] = value; this._changed[key] = value;
|
|
180
180
|
if (apply) this._apply(key, value);
|
|
181
|
-
if (
|
|
181
|
+
if (this._presetKeys().has(key)) this._values.quality = this._matchPreset();
|
|
182
182
|
if (save) this.save();
|
|
183
183
|
this.win.refresh();
|
|
184
184
|
}
|
|
@@ -271,7 +271,7 @@ export class Settings extends SettingsView {
|
|
|
271
271
|
reset(key) {
|
|
272
272
|
const def = k => this.custom.has(k) ? this.custom.get(k).def : this._defaults[k];
|
|
273
273
|
// 'quality' is no value of its own (it is the name of the preset the graphics values match): resetting it resets the graphics values the presets set
|
|
274
|
-
const keys = key === undefined ? Object.keys(this._values).filter(k => k !== 'quality' && !this._omit.has(k)) : key === 'quality' ?
|
|
274
|
+
const keys = key === undefined ? Object.keys(this._values).filter(k => k !== 'quality' && !this._omit.has(k)) : key === 'quality' ? [...this._presetKeys()].filter(k => !this._omit.has(k) && k in this._values) : [key];
|
|
275
275
|
if (key === undefined || key === 'quality') delete this._changed.quality;
|
|
276
276
|
const preset = this._presetValues(this._changed.quality); // a row a kept preset sets must stay stored, or the preset takes it back on the next launch
|
|
277
277
|
for (const k of keys) {
|
|
@@ -343,6 +343,12 @@ export class Settings extends SettingsView {
|
|
|
343
343
|
for (const [bus, level] of Object.entries(e.audio.levels)) v['vol.' + bus] = level; // one slider per bus, the game's own buses too
|
|
344
344
|
return v;
|
|
345
345
|
}
|
|
346
|
+
/** @internal Union of keys touched by any graphics preset */
|
|
347
|
+
_presetKeys() {
|
|
348
|
+
const keys = new Set();
|
|
349
|
+
for (const p of Object.values(this.presets)) if (p && typeof p === 'object') for (const k in p) keys.add(k);
|
|
350
|
+
return keys;
|
|
351
|
+
}
|
|
346
352
|
/** A preset's values in this game on this device: each share made a value. A share of a row nobody offered is left out. Nothing for 'custom' or no preset @param {string} [name] */
|
|
347
353
|
_presetValues(name) {
|
|
348
354
|
const out = {};
|
package/modules/sky/Sky.js
CHANGED
|
@@ -27,6 +27,14 @@ const DIM_PARAMS = {
|
|
|
27
27
|
tint: { type: 'bool', default: true, desc: 'a sky.tint color (weather grey, a cave tint) dims with the sky\'s own light, so a grey rain tint stays dark at night' },
|
|
28
28
|
stars: { type: 'bool', default: true, desc: 'stars fade with the weather\'s cloud cover (uWeatherCloud), not only behind drawn clouds' },
|
|
29
29
|
};
|
|
30
|
+
/** @internal Detach and dispose a sky dome mesh (handles single or array materials) */
|
|
31
|
+
export function disposeDome(dome) {
|
|
32
|
+
if (!dome) return;
|
|
33
|
+
dome.removeFromParent();
|
|
34
|
+
dome.geometry?.dispose();
|
|
35
|
+
[dome.material].flat().forEach(m => m?.dispose());
|
|
36
|
+
}
|
|
37
|
+
|
|
30
38
|
/** @import { Object3D, Vector3 } from '../../types/common' */
|
|
31
39
|
/** engine.sky */
|
|
32
40
|
export class Sky {
|
|
@@ -73,8 +81,8 @@ export class Sky {
|
|
|
73
81
|
const old = this.dome, at = old.parent, vis = old.visible;
|
|
74
82
|
this.dome = makeDome(this.uniforms, st, domeParts, engine);
|
|
75
83
|
this.dome.visible = vis;
|
|
76
|
-
|
|
77
|
-
|
|
84
|
+
disposeDome(old);
|
|
85
|
+
at?.add(engineOwned('sky', this.dome));
|
|
78
86
|
this._entries?.reapply();
|
|
79
87
|
this._envSwap();
|
|
80
88
|
});
|
|
@@ -16,20 +16,35 @@ import { isWebGPU, webgpuPart } from '../../render/backend.js';
|
|
|
16
16
|
const DEFAULT_INTERVAL = 1; // seconds between rebuilds (only when the sky actually changed)
|
|
17
17
|
const LOW_TIER_SLOWER = 4; // by default a low-tier device rebuilds this many times less often (an interval the game gives stands): the cube cannot be made smaller (256 px is PMREMGenerator's floor)
|
|
18
18
|
|
|
19
|
+
const _H = new Int32Array(2);
|
|
20
|
+
function hashInt(v) {
|
|
21
|
+
const n = v | 0;
|
|
22
|
+
_H[0] = Math.imul(_H[0] ^ n, 0x01000193);
|
|
23
|
+
_H[1] = Math.imul(_H[1] ^ (n + 0x9e3779b9), 0x85ebca6b);
|
|
24
|
+
}
|
|
25
|
+
function hashStr(s) {
|
|
26
|
+
hashInt(s.length);
|
|
27
|
+
for (let i = 0; i < s.length; i++) hashInt(s.charCodeAt(i));
|
|
28
|
+
}
|
|
29
|
+
|
|
19
30
|
// Everything that decides how the procedural sky looks right now: when it stays put the environment is not rebuilt. It walks the dome's own uniforms
|
|
20
31
|
// (sun, moon, cloud colour / cover / speed and a game's layer uniforms are all in there, so a new one needs no edit here) and the dome material's
|
|
21
32
|
// shader revision (a changed clouds() / layer() hook). uTime is left out: it moves every frame, and cloud drift alone is not worth a rebuild
|
|
22
33
|
function skyKey(sky) {
|
|
23
|
-
const
|
|
24
|
-
|
|
34
|
+
const m = sky.dome.material, U = sky.uniforms;
|
|
35
|
+
_H[0] = 0x811c9dc5 | 0; _H[1] = 0x9e3779b9 | 0;
|
|
36
|
+
hashStr(m.uuid); hashInt(m.version);
|
|
37
|
+
for (const k in U) {
|
|
25
38
|
if (k === 'uTime') continue;
|
|
26
|
-
const v =
|
|
27
|
-
if (typeof v === 'number')
|
|
28
|
-
else if (v?.isColor)
|
|
29
|
-
else if (v?.isVector2
|
|
30
|
-
else if (v?.
|
|
39
|
+
const v = U[k].value;
|
|
40
|
+
if (typeof v === 'number') hashInt(Math.round(v * 400));
|
|
41
|
+
else if (v?.isColor) { hashInt(Math.round(v.r * 400)); hashInt(Math.round(v.g * 400)); hashInt(Math.round(v.b * 400)); }
|
|
42
|
+
else if (v?.isVector2) { hashInt(Math.round(v.x * 400)); hashInt(Math.round(v.y * 400)); }
|
|
43
|
+
else if (v?.isVector3) { hashInt(Math.round(v.x * 400)); hashInt(Math.round(v.y * 400)); hashInt(Math.round(v.z * 400)); }
|
|
44
|
+
else if (v?.isVector4) { hashInt(Math.round(v.x * 400)); hashInt(Math.round(v.y * 400)); hashInt(Math.round(v.z * 400)); hashInt(Math.round(v.w * 400)); }
|
|
45
|
+
else if (v?.isTexture) { hashStr(v.uuid); hashInt(v.version); }
|
|
31
46
|
}
|
|
32
|
-
return
|
|
47
|
+
return (_H[0] >>> 0) * 0x200000 + (_H[1] >>> 11);
|
|
33
48
|
}
|
|
34
49
|
|
|
35
50
|
export const environmentMethods = {
|
|
@@ -62,11 +77,12 @@ export const environmentMethods = {
|
|
|
62
77
|
if (!this._oEnv.on) return; // the game wrote scene.environment: nothing is rebuilt while the sky has yielded (frame.js watchOwned)
|
|
63
78
|
if (!e.deferred && e.since < e.interval) return;
|
|
64
79
|
e.since = 0; e.deferred = false;
|
|
65
|
-
|
|
80
|
+
const key = skyKey(this);
|
|
81
|
+
if (key !== e.key) this._envBuild(key);
|
|
66
82
|
},
|
|
67
83
|
|
|
68
84
|
// Render the dome alone into a cube and prefilter it (PMREM). The dome mesh follows the camera, so a copy sharing its material is rendered
|
|
69
|
-
_envBuild() {
|
|
85
|
+
_envBuild(key = skyKey(this)) {
|
|
70
86
|
const e = this._env, r = this.engine.renderer;
|
|
71
87
|
// WebGPURenderer needs three/webgpu's PMREMGenerator (registered by threedog/tsl)
|
|
72
88
|
this._pmrem ??= new (isWebGPU(r) ? webgpuPart('classes', 'engine.sky.environment').PMREMGenerator : THREE.PMREMGenerator)(r);
|
|
@@ -84,13 +100,13 @@ export const environmentMethods = {
|
|
|
84
100
|
// a map the game wrote there is the game's: the owned check (frame.js) has yielded, and the sky writes it no more
|
|
85
101
|
if (e.into && this._oEnv.on) { e.into.environment = next.texture; this._oEnv.mark(); }
|
|
86
102
|
if (old !== next) old?.dispose(); e.target = next;
|
|
87
|
-
e.builds++; e.key =
|
|
103
|
+
e.builds++; e.key = key;
|
|
88
104
|
},
|
|
89
105
|
|
|
90
106
|
// Renderer swap (fallback 'webgl'): the generator and the map belong to the old renderer, so the next frame builds them again on the new one
|
|
91
107
|
_envSwap() {
|
|
92
|
-
this._pmrem = null; this._envScene = null;
|
|
93
|
-
if (this._env) { this._env.key = null; this._env.deferred = true; }
|
|
108
|
+
this._pmrem?.dispose(); this._pmrem = null; this._envScene = null;
|
|
109
|
+
if (this._env) { this._env.target?.dispose(); this._env.target = null; this._env.key = null; this._env.deferred = true; }
|
|
94
110
|
},
|
|
95
111
|
|
|
96
112
|
// handle.remove() and module dispose: what the engine wrote comes off, the GPU memory is released
|