threedog 0.8.0 → 1.0.1
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 +223 -4
- package/README.md +6 -6
- package/core/assets/Animator.js +2 -0
- package/core/assets/Assets.js +44 -13
- package/core/assets/assetEntry.js +87 -22
- package/core/assets/assetHot.js +2 -1
- package/core/assets/assetReport.js +1 -2
- package/core/audio/Audio.js +24 -5
- package/core/base/I18n.js +6 -3
- package/core/base/Random.js +3 -1
- package/core/base/Vars.js +14 -4
- package/core/base/errorCodes.js +54 -16
- package/core/base/errorHints.js +12 -1
- package/core/base/errors.js +6 -4
- package/core/base/events.generated.js +10 -0
- package/core/base/follows.js +26 -0
- package/core/base/math.js +15 -8
- package/core/base/params.js +2 -2
- package/core/{saves → base}/saveValues.js +24 -6
- package/core/base/sections.js +97 -0
- package/core/base/spelling.js +32 -0
- package/core/base/validate.js +8 -29
- package/core/engine/Engine.js +61 -18
- package/core/engine/Loading.js +30 -3
- package/core/engine/copies.js +1 -1
- package/core/engine/headlessLoad.js +30 -13
- package/core/engine/lifecycle.js +30 -25
- package/core/engine/loop.js +22 -4
- package/core/engine/moduleSlots.js +91 -15
- package/core/engine/moduleTypes.js +13 -0
- package/core/engine/modules.js +248 -62
- package/core/engine/page.js +25 -8
- package/core/engine/plugins.js +15 -3
- package/core/engine/services.js +3 -0
- package/core/engine/startup.js +46 -36
- package/core/input/Input.js +39 -19
- package/core/input/inputKeyboard.js +39 -0
- package/core/input/inputPad.js +23 -2
- package/core/input/inputPointer.js +3 -1
- package/core/input/inputSeat.js +66 -0
- package/core/input/inputTouch.js +23 -6
- package/core/inspect/DebugOverrides.js +13 -2
- package/core/inspect/Describe.js +10 -6
- package/core/inspect/Inspect.js +31 -4
- package/core/inspect/UrlState.js +14 -10
- package/core/inspect/catalog.js +12 -5
- package/core/inspect/describeRender.js +3 -2
- package/core/inspect/describeText.js +6 -2
- package/core/inspect/metadata.generated.js +4140 -0
- package/core/inspect/pictureWriters.js +117 -33
- package/core/inspect/toolDoor.js +21 -0
- package/core/inspect/valueHistory.js +35 -0
- package/core/ops/Ops.js +32 -7
- package/core/ops/control.js +48 -23
- package/core/ops/holds.js +4 -3
- package/core/ops/opsAtomic.js +18 -6
- package/core/ops/opsCheck.js +7 -5
- package/core/ops/opsFail.js +5 -7
- package/core/ops/opsRun.js +2 -2
- package/core/ops/owned.js +20 -3
- package/core/ops/sharedPoint.js +7 -10
- package/core/ops/stacks.js +22 -1
- package/core/saves/SaveStore.js +52 -26
- package/core/saves/Saves.js +122 -27
- package/core/saves/saveApply.js +159 -61
- package/core/saves/saveFiles.js +30 -25
- package/core/saves/saveVersions.js +20 -6
- package/core/saves/session.js +76 -33
- package/core/saves/stateReplace.js +184 -0
- package/core/scene/Rays.js +21 -5
- package/core/scene/Views.js +6 -6
- package/core/scene/adaptive.js +13 -10
- package/core/scene/canvasBox.js +2 -0
- package/core/scene/compositeGround.js +72 -0
- package/core/scene/floor.js +17 -0
- package/core/scene/grid.js +2 -0
- package/core/scene/ground.contract.js +14 -0
- package/core/scene/ground.js +52 -17
- package/core/scene/pixel.js +154 -0
- package/core/scene/pixelRatio.js +167 -0
- package/core/scene/sceneDelta.js +3 -3
- package/core/scene/sceneMethods.js +11 -6
- package/core/scene/stepPoses.js +6 -1
- package/core/scene/thingExplain.js +1 -1
- package/core/scene/thingOps.js +22 -14
- package/core/scene/things.js +1 -1
- package/core/scene/tier.js +10 -0
- package/core/scene/view.js +126 -9
- package/core/stream/Batching.js +0 -1
- package/core/stream/Stream.js +24 -12
- package/core/stream/batchGroups.js +1 -0
- package/core/stream/scatter.js +5 -2
- package/core/stream/streamSources.js +2 -1
- package/core/threads/Commits.js +12 -7
- package/core/threads/Jobs.js +15 -5
- package/core/threads/Threads.js +5 -2
- package/core/time/Clock.js +3 -1
- package/core/time/skip.js +10 -4
- package/core/time/time.js +16 -10
- package/docs/AI.md +89 -72
- package/docs/API.md +18 -14
- package/docs/CODEMAP.md +68 -40
- package/docs/COMMANDS.md +22 -23
- package/docs/CONVENTIONS.md +120 -17
- package/docs/MIGRATING-0.8.md +2 -0
- package/docs/MIGRATING-1.0.md +101 -0
- package/docs/THREE.md +65 -12
- package/docs/api/cameraRig.md +3 -0
- package/docs/api/characters.md +13 -7
- package/docs/api/collider3d.md +9 -0
- package/docs/api/content.md +16 -15
- package/docs/api/dialogue.md +2 -1
- package/docs/api/engine.md +18 -16
- package/docs/api/events.md +14 -4
- package/docs/api/ground.md +2 -2
- package/docs/api/i18n.md +1 -1
- package/docs/api/input.md +2 -1
- package/docs/api/interactions.md +1 -1
- package/docs/api/inventory.md +1 -1
- package/docs/api/level.md +3 -2
- package/docs/api/nav.md +4 -2
- package/docs/api/particles.md +8 -5
- package/docs/api/pickups.md +1 -1
- package/docs/api/post.md +3 -4
- package/docs/api/quests.md +4 -2
- package/docs/api/rays.md +2 -0
- package/docs/api/rigid.md +3 -2
- package/docs/api/saves.md +8 -7
- package/docs/api/stream.md +4 -5
- package/docs/api/terrain.md +3 -4
- package/docs/api/terrainDraw.md +1 -1
- package/docs/api/timeline.md +2 -2
- package/docs/api/tools.md +3 -1
- package/docs/api/triggers.md +2 -0
- package/docs/api/vegetationDraw.md +1 -1
- package/docs/api/water.md +6 -2
- package/docs/api/weather.md +19 -4
- package/docs/api/weatherDraw.md +1 -1
- package/docs/api/world.md +1 -1
- package/docs/recipes/01-new-game.md +3 -3
- package/docs/recipes/02-npc.md +3 -4
- package/docs/recipes/03-items-pickups.md +11 -11
- package/docs/recipes/04-quests.md +2 -0
- package/docs/recipes/05-props-bake.md +9 -9
- package/docs/recipes/06-clock-events.md +6 -6
- package/docs/recipes/07-flow-scenes-pause.md +18 -15
- package/docs/recipes/08-weather-sky.md +5 -5
- package/docs/recipes/09-materials-lights-models.md +3 -3
- package/docs/recipes/10-blender-level.md +16 -4
- package/docs/recipes/11-vehicles.md +18 -6
- package/docs/recipes/12-navmesh.md +52 -8
- package/docs/recipes/13-animation.md +34 -8
- package/docs/recipes/14-custom-module.md +20 -8
- package/docs/recipes/15-perf.md +4 -4
- package/docs/recipes/16-dev-bridge.md +9 -8
- package/docs/recipes/18-world.md +13 -5
- package/docs/recipes/19-shooting-picking.md +3 -2
- package/docs/recipes/20-content-actions-save.md +26 -6
- package/docs/recipes/21-camera.md +17 -23
- package/docs/recipes/22-shop-gold.md +21 -12
- package/docs/recipes/23-ops.md +19 -15
- package/docs/recipes/26-ui-parts.md +3 -2
- package/docs/recipes/27-net.md +3 -3
- package/docs/recipes/28-terrain.md +3 -3
- package/docs/recipes/29-grid.md +1 -1
- package/docs/recipes/30-templates.md +10 -13
- package/docs/recipes/31-audio.md +2 -2
- package/docs/recipes/32-action-game.md +6 -5
- package/docs/recipes/33-stream-sources.md +4 -1
- package/docs/recipes/34-environment-lighting.md +7 -8
- package/docs/recipes/35-picture-from-reference.md +13 -9
- package/docs/recipes/36-ground-plants.md +3 -2
- package/docs/recipes/40-scene.md +11 -10
- package/docs/recipes/43-shader-patches-surfaces.md +7 -7
- package/docs/recipes/44-water-weather-hooks.md +9 -8
- package/docs/recipes/45-cascaded-shadows.md +3 -4
- package/docs/recipes/46-blender-art-route.md +3 -3
- package/docs/recipes/49-game-module-contract.md +2 -1
- package/docs/recipes/50-own-renderer.md +1 -0
- package/docs/recipes/51-capability-catalog.md +14 -8
- package/docs/recipes/52-around-the-picture.md +4 -4
- package/docs/recipes/55-mods-time-wrap.md +5 -4
- package/docs/recipes/56-webgpu-tsl.md +12 -1
- package/docs/recipes/57-control.md +30 -10
- package/docs/recipes/58-input.md +13 -0
- package/docs/recipes/60-judge-the-picture.md +1 -1
- package/docs/recipes/62-picture-code.md +106 -48
- package/docs/recipes/63-third-person-start.md +2 -1
- package/docs/recipes/64-particles.md +53 -4
- package/docs/recipes/65-swarm.md +2 -2
- package/docs/recipes/66-common-tasks.md +313 -0
- package/examples/action/.threedog/content-index.json +1 -1
- package/examples/action/GAMEMAP.md +3 -3
- package/examples/perf-island/.threedog/content-index.json +1 -1
- package/examples/perf-island/GAMEMAP.md +3 -3
- package/examples/perf-island/main.js +2 -2
- package/examples/plain-picture/GAMEMAP.md +3 -1
- package/examples/rc2d/GAMEMAP.md +1 -1
- package/examples/rc2d/rc2d.js +1 -1
- package/examples/styletest/.threedog/content-index.json +1 -1
- package/examples/styletest/GAMEMAP.md +3 -3
- package/examples/webgpu-tsl/GAMEMAP.md +1 -1
- package/examples/world/.threedog/content-index.json +1 -1
- package/examples/world/GAMEMAP.md +5 -4
- package/examples/world/main.js +3 -3
- package/index.d.ts +8 -5
- package/index.js +22 -1
- package/llms.txt +2 -1
- package/modules/ambience/Ambience.js +5 -3
- package/modules/calendar/index.js +7 -5
- package/modules/camera/FirstPersonCamera.js +3 -3
- package/modules/camera/FixedCamera.js +34 -20
- package/modules/camera/FollowCamera.js +20 -11
- package/modules/camera/RtsCamera.js +1 -0
- package/modules/camera/common.js +33 -22
- package/modules/camera/pixelSnap.js +62 -0
- package/modules/characters/Character.js +136 -43
- package/modules/characters/NPC.js +60 -28
- package/modules/characters/assetModel.js +2 -2
- package/modules/characters/astar.js +47 -28
- package/modules/characters/character.contract.js +21 -0
- package/modules/characters/contract.js +17 -3
- package/modules/characters/index.js +94 -34
- package/modules/characters/moveHelpers.js +80 -15
- package/modules/characters/mover.contract.js +14 -0
- package/modules/characters/movers/common.js +6 -4
- package/modules/characters/movers/rapier.js +12 -5
- package/modules/characters/movers/simple.js +25 -12
- package/modules/characters/movers/support.js +18 -7
- package/modules/characters/npcAvoid.js +15 -12
- package/modules/characters/npcSim.js +75 -25
- package/modules/characters/npcView.js +13 -6
- package/modules/characters/pathAsync.js +74 -24
- package/modules/characters/pathJob.js +38 -21
- package/modules/characters/player.js +59 -47
- package/modules/characters/seat.js +56 -0
- package/modules/characters/vehicle.contract.js +8 -5
- package/modules/characters/walkTo.js +31 -18
- package/modules/collision/Collision.js +44 -26
- package/modules/collision/contract.js +2 -2
- package/modules/collision/grid.js +6 -1
- package/modules/content/explain.js +1 -1
- package/modules/content/fields.js +3 -3
- package/modules/content/ids.js +3 -1
- package/modules/content/index.js +83 -27
- package/modules/content/loader.js +110 -130
- package/modules/content/markers.js +1 -1
- package/modules/content/models.js +48 -14
- package/modules/content/packs.js +2 -1
- package/modules/content/places.js +5 -4
- package/modules/content/props.js +8 -6
- package/modules/content/rules.js +29 -47
- package/modules/content/templates.js +66 -35
- package/modules/content/words.js +19 -6
- package/modules/debug/DebugPanel.js +4 -2
- package/modules/flow/contract.js +1 -0
- package/modules/flow/index.js +24 -14
- package/modules/gameplay/Container.js +5 -2
- package/modules/gameplay/Containers.js +9 -1
- package/modules/gameplay/Dialogue.js +82 -25
- package/modules/gameplay/Interactions.js +61 -32
- package/modules/gameplay/Inventory.js +56 -13
- package/modules/gameplay/Quests.js +133 -24
- package/modules/gameplay/boxOps.js +7 -0
- package/modules/gameplay/dialogueBubbles.js +14 -9
- package/modules/gameplay/inventoryOps.js +11 -7
- package/modules/gameplay/pickups.js +43 -16
- package/modules/gameplay/questLog.js +4 -2
- package/modules/gameplay/questSave.js +6 -1
- package/modules/gameplay/quests.contract.js +1 -1
- package/modules/grid/Grid.js +1 -1
- package/modules/grid/Layer.js +8 -4
- package/modules/grid/index.js +21 -15
- package/modules/grid/ops.js +43 -46
- package/modules/grid/tiles.js +1 -1
- package/modules/hlod/index.js +6 -3
- package/modules/hud/index.js +6 -4
- package/modules/hud/parts.js +4 -4
- package/modules/level/contract.js +2 -2
- package/modules/level/heightfield.js +17 -21
- package/modules/level/index.js +83 -26
- package/modules/level/load.js +165 -48
- package/modules/level/nodes.js +34 -16
- package/modules/lights/index.js +6 -3
- package/modules/lights/sources.js +3 -1
- package/modules/music/Music.js +4 -2
- package/modules/nav/contract.js +7 -5
- package/modules/nav/index.js +174 -44
- package/modules/nav/navPath.js +45 -10
- package/modules/net/index.js +1 -1
- package/modules/particles/Particles.js +85 -22
- package/modules/particles/effect.js +80 -28
- package/modules/particles/shaders.js +17 -0
- package/modules/photo/Photo.js +12 -10
- package/modules/rigid/RigidBodies.js +200 -57
- package/modules/rigid/Vehicles.js +15 -5
- package/modules/rigid/collider3d.contract.js +26 -0
- package/modules/rigid/ragdoll.js +55 -44
- package/modules/rigid/ragdollBones.js +83 -33
- package/modules/rigid/refresh.js +10 -0
- package/modules/rigid/sync.js +46 -15
- package/modules/settings/Settings.js +84 -37
- package/modules/settings/apply.js +15 -8
- package/modules/settings/sections.js +7 -4
- package/modules/settings/strings.js +2 -2
- package/modules/sky/skyModule.js +3 -1
- package/modules/swarm/Swarm.js +16 -6
- package/modules/terrain/ChunkManager.js +10 -16
- package/modules/terrain/index.js +17 -11
- package/modules/terrain/terrainEdit.js +13 -2
- package/modules/terrain/terrainGen.js +5 -3
- package/modules/terrain/terrainShape.js +1 -1
- package/modules/timeline/Timeline.js +58 -26
- package/modules/timeline/Tween.js +19 -13
- package/modules/timeline/shots.js +19 -10
- package/modules/triggers/index.js +87 -20
- package/modules/vegetation/Vegetation.js +4 -3
- package/modules/vegetation/draw.js +16 -0
- package/modules/vegetation/groundChunks.js +10 -7
- package/modules/vegetation/index.js +30 -7
- package/modules/water/Water.js +6 -2
- package/modules/weather/Weather.js +16 -15
- package/modules/weather/weatherDraw.js +7 -6
- package/modules/world/World.js +20 -7
- package/modules/world/explain.js +1 -1
- package/modules/world/index.js +13 -6
- package/modules/world/persist.js +23 -8
- package/modules/world/pos.js +4 -4
- package/modules/world/records.js +13 -7
- package/modules/world/sim.js +74 -23
- package/modules/world/simFar.js +2 -2
- package/modules/world/state.js +31 -6
- package/modules/world/thingSource.js +16 -3
- package/modules/world/views.js +19 -8
- package/package.json +7 -1
- package/render/PostFX.js +47 -29
- package/render/backend.js +5 -1
- package/render/fx/particles.tsl.js +8 -6
- package/render/fx/postWebGPU.tsl.js +3 -3
- package/render/layers.js +1 -1
- package/render/lightmap.js +23 -3
- package/render/occlusion.js +43 -12
- package/render/patches.js +2 -2
- package/render/postWebGL.js +4 -3
- package/render/probes.js +25 -0
- package/render/shadows.js +2 -2
- package/types/core.d.ts +142 -55
- package/types/gameplay.d.ts +92 -40
- package/types/generated/core/base/I18n.d.ts +2 -2
- package/types/generated/core/input/Input.d.ts +16 -2
- package/types/generated/core/input/inputSeat.d.ts +26 -0
- package/types/generated/core/inspect/DebugOverrides.d.ts +15 -1
- package/types/generated/core/ops/Ops.d.ts +2 -1
- package/types/generated/core/ops/control.d.ts +12 -2
- package/types/generated/core/saves/Saves.d.ts +26 -6
- package/types/generated/core/saves/session.d.ts +1 -1
- package/types/generated/core/scene/Views.d.ts +1 -1
- package/types/generated/core/stream/Stream.d.ts +6 -4
- package/types/generated/modules/grid/Grid.d.ts +1 -0
- package/types/generated/modules/particles/Particles.d.ts +4 -3
- package/types/generated/modules/timeline/Timeline.d.ts +5 -4
- package/types/generated/modules/weather/Weather.d.ts +1 -7
- package/types/generated/modules/world/World.d.ts +6 -4
- package/types/generated/render/PostFX.d.ts +6 -14
- package/types/nav.d.ts +36 -4
- package/types/physics.d.ts +55 -7
- package/types/pixel.d.ts +75 -0
- package/types/world.d.ts +14 -8
- package/ui/Parts.js +9 -2
- package/ui/theme.js +2 -2
- package/core/scene/engineCamera.js +0 -32
- package/modules/camera/projection.js +0 -21
package/modules/rigid/ragdoll.js
CHANGED
|
@@ -1,11 +1,12 @@
|
|
|
1
1
|
// Ragdoll: one dynamic rigid body per part of a skinned character, joined by joints; every fixed step the result is written back to the plain three.js bones.
|
|
2
2
|
// const rd = engine.rigid.ragdoll(player, { impulse: [0, 2, -8], position: hitPoint });
|
|
3
3
|
// rd.remove(); // back to animation
|
|
4
|
+
// engine.mod('ragdoll.graph', { owner: 'game', id: 'wolf', set: { body: { bone: 'Spine' }, tail: { bone: 'Tail1', parent: 'body' } } }); // not a human: any graph of parts
|
|
4
5
|
//
|
|
5
6
|
// Why it is done this way:
|
|
6
7
|
// - Bodies do not use the bone's orientation but "one shared frame for the whole body in bind pose": bodyQ = boneWorldQ * inv(restQ). That way the frames on both sides of every joint coincide in bind pose,
|
|
7
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.
|
|
8
|
-
// - Only
|
|
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).
|
|
9
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.
|
|
10
11
|
// - Not saved: as soon as rigid's save part is read in (new game, load and saves.load all go through it) every ragdoll ends and a normal character comes back; a refused load never gets here, so the ragdoll keeps lying there.
|
|
11
12
|
// On a world rebuild without a load, rigid carries the bodies over and this rebuilds the joints on rigid:rebuilt.
|
|
@@ -15,26 +16,15 @@ import * as THREE from 'three';
|
|
|
15
16
|
import { vec3 } from '../../core/base/math.js';
|
|
16
17
|
import { readParams, keysSchema } from '../../core/base/params.js';
|
|
17
18
|
import { codedError } from '../../core/base/errorHints.js';
|
|
18
|
-
import {
|
|
19
|
+
import { humanoidGraph, shapeParts } from './ragdollBones.js';
|
|
19
20
|
|
|
20
21
|
const KEYS = keysSchema(['impulse', 'position', 'bones', 'limits', 'mass']);
|
|
21
22
|
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
|
|
22
|
-
const D = Math.PI / 180;
|
|
23
|
-
// Default range of motion (radians, relative to bind pose). bend is positive forward (backward for knees), side is sideways, twist is around the bone. This is physical plausibility, not looks
|
|
24
|
-
const LIMITS = {
|
|
25
|
-
chest: { bend: [-30 * D, 40 * D], side: [-25 * D, 25 * D], twist: [-30 * D, 30 * D] },
|
|
26
|
-
head: { bend: [-40 * D, 50 * D], side: [-35 * D, 35 * D], twist: [-60 * D, 60 * D] },
|
|
27
|
-
upperArm: { bend: [-60 * D, 120 * D], side: [-100 * D, 100 * D], twist: [-70 * D, 70 * D] },
|
|
28
|
-
lowerArm: { bend: [0, 145 * D], side: [-3 * D, 3 * D], twist: [-60 * D, 60 * D] },
|
|
29
|
-
upperLeg: { bend: [-25 * D, 110 * D], side: [-45 * D, 45 * D], twist: [-35 * D, 35 * D] },
|
|
30
|
-
lowerLeg: { bend: [0, 140 * D], side: [-3 * D, 3 * D], twist: [-5 * D, 5 * D] },
|
|
31
|
-
};
|
|
32
|
-
const SHARE = { hips: 0.16, chest: 0.3, head: 0.08, upperArm: 0.03, lowerArm: 0.025, upperLeg: 0.11, lowerLeg: 0.07 }; // how the total mass is split
|
|
33
23
|
const FRICTION = 2; // damping in the joints (1/s): limbs with no muscle still do not whip around like ropes forever
|
|
34
24
|
const CALM_SPEED = 0.09, CALM_SPIN = 4, CALM_STEPS = 45; // speed squared (m²/s²), angular speed squared (rad²/s²), how many steps in a row
|
|
35
25
|
const HIT_SPEED = 6; // the speed (m/s) the hit part alone can take, see _push
|
|
36
26
|
|
|
37
|
-
const q1 = new THREE.Quaternion(), q2 = new THREE.Quaternion(), p1 = new THREE.Vector3(),
|
|
27
|
+
const q1 = new THREE.Quaternion(), q2 = new THREE.Quaternion(), p1 = new THREE.Vector3(), s1 = new THREE.Vector3(), m1 = new THREE.Matrix4();
|
|
38
28
|
const toQ = (r, out = q1) => out.set(r.x, r.y, r.z, r.w);
|
|
39
29
|
const worldOf = (o, p, q) => { o.matrixWorld.decompose(p, q, s1); };
|
|
40
30
|
const shapes = new WeakMap(); // skeleton -> { key, parts }: the same character falling again and again is not re-measured
|
|
@@ -57,7 +47,8 @@ export class Ragdolls {
|
|
|
57
47
|
if (ch?.vehicle) throw codedError('rigid-misuse', `rigid.ragdoll(): character '${ch.id}' sits in a vehicle. Fix: character.exit() first`);
|
|
58
48
|
const mesh = skinOf(root);
|
|
59
49
|
if (!mesh) throw codedError('rigid-misuse', `rigid.ragdoll(): no SkinnedMesh under ${ch ? `character '${ch.id}'` : `'${root.name || root.type}'`}, so there are no bones to drive. A capsule or a procedural rig cannot go limp; a model given by name loads later: await character.whenReady first`);
|
|
60
|
-
const shape = this._shape(mesh, o.bones);
|
|
50
|
+
const shape = this._shape(ch, root, mesh, o.bones);
|
|
51
|
+
if (!shape) return null; // the game's rule says this one does not go limp
|
|
61
52
|
// Take control first: a remote character throws here, when nothing has been built yet
|
|
62
53
|
const hold = ch ? this.e.control.take(ch, { owner: 'ragdoll', layer: 'physics', step: () => false }) : null;
|
|
63
54
|
const rd = this._build(ch, root, mesh, shape, hold, o);
|
|
@@ -75,23 +66,29 @@ export class Ragdolls {
|
|
|
75
66
|
return { ch, root: ch.root };
|
|
76
67
|
}
|
|
77
68
|
|
|
78
|
-
|
|
79
|
-
|
|
69
|
+
/** The rule 'ragdoll.graph' for this body: 'humanoid', a graph, or false for no ragdoll. Measured once per skeleton and graph */
|
|
70
|
+
_shape(ch, root, mesh, bones = {}) {
|
|
71
|
+
const g = this.r._graph.decide(ch?.id, { character: ch, root, mesh });
|
|
72
|
+
if (g === false) return null;
|
|
73
|
+
const human = g === 'humanoid';
|
|
74
|
+
if (!human && Object.keys(bones).length) throw codedError('rigid-misuse', `rigid.ragdoll({ bones }): bones names the parts of the humanoid graph, and this body's rule 'ragdoll.graph' gives its own. Fix: name the bones in the graph`);
|
|
75
|
+
const key = JSON.stringify(human ? bones : g, (k, v) => (v?.isObject3D ? v.uuid : v));
|
|
80
76
|
const c = shapes.get(mesh.skeleton);
|
|
81
77
|
if (c?.key === key) return c.parts;
|
|
82
|
-
const parts = shapeParts(mesh,
|
|
78
|
+
const parts = shapeParts(mesh, human ? humanoidGraph(mesh, bones) : g);
|
|
83
79
|
shapes.set(mesh.skeleton, { key, parts });
|
|
84
80
|
return parts;
|
|
85
81
|
}
|
|
86
82
|
|
|
87
83
|
_build(ch, root, mesh, shape, hold, o) {
|
|
88
|
-
const { r } = this, R = r.rapier,
|
|
84
|
+
const { r } = this, R = r.rapier, skeleton = mesh.skeleton, top = shape[0];
|
|
85
|
+
const massK = o.mass != null ? o.mass / shape.reduce((n, s) => n + s.mass, 0) : 1; // the call's whole-body mass keeps the graph's proportions
|
|
89
86
|
root.updateWorldMatrix(true, true);
|
|
90
87
|
const holder = new THREE.Group(); // parent of the placeholder objects: _add does not add to the scene when there is a parent
|
|
91
88
|
const parts = {}, list = [];
|
|
92
89
|
// bind space to world scale: when the model is scaled (0.01 is common for Mixamo) colliders must use the real length as it is now
|
|
93
|
-
|
|
94
|
-
const k =
|
|
90
|
+
// read from the skinning matrix of the root part: bind to now is pose and scale, and pose does not change its size, whatever the body looks like
|
|
91
|
+
const k = s1.setFromMatrixScale(m1.multiplyMatrices(top.bone.matrixWorld, skeleton.boneInverses[skeleton.bones.indexOf(top.bone)])).x;
|
|
95
92
|
for (const s of shape) {
|
|
96
93
|
const proxy = new THREE.Object3D(), bq = new THREE.Quaternion();
|
|
97
94
|
holder.add(proxy);
|
|
@@ -101,18 +98,19 @@ export class Ragdolls {
|
|
|
101
98
|
const mid = seg.clone().multiplyScalar(0.5), up = q1.setFromUnitVectors(new THREE.Vector3(0, 1, 0), seg.clone().normalize());
|
|
102
99
|
const desc = R.ColliderDesc.capsule(Math.max(len / 2 - rad, len * 0.02), rad).setTranslation(mid.x, mid.y, mid.z)
|
|
103
100
|
.setRotation({ x: up.x, y: up.y, z: up.z, w: up.w }).setCollisionGroups(GROUP);
|
|
104
|
-
const entry = r._add(proxy, desc, { mass: mass *
|
|
101
|
+
const entry = r._add(proxy, desc, { mass: s.mass * massK, friction: 0.8, restitution: 0, damping: 0.1, angularDamping: 0.8 });
|
|
105
102
|
entry.ragdoll = true; entry.object = s.bone; // a ray hit returns the bone: the game needs to know what was hit
|
|
106
103
|
entry.body.enableCcd(true); // limbs are thin and fast when knocked away; without it they pass through thin ground
|
|
107
|
-
const part = { name: s.name, shape: s, entry, mass: mass *
|
|
104
|
+
const part = { name: s.name, shape: s, entry, mass: s.mass * massK, seg: seg.clone(), rad, bone: s.bone, pos0: s.bone.position.clone(), q0: s.bone.quaternion.clone() };
|
|
108
105
|
list.push(parts[s.name] = part);
|
|
109
106
|
}
|
|
110
107
|
const self = this;
|
|
111
108
|
const rd = {
|
|
112
|
-
ch, root, mesh, list, parts: Object.fromEntries(list.map(p => [p.name, p.entry])), hold, joints: [], limits: o.limits ?? {}, anchor: null,
|
|
109
|
+
ch, root, mesh, list, parts: Object.fromEntries(list.map(p => [p.name, p.entry])), hold, joints: [], limits: o.limits ?? {}, anchor: null, anim: null, drawn: false, void: false, calm: 0,
|
|
113
110
|
get active() { return self.live.has(rd); },
|
|
114
111
|
get settled() { return rd.active && list.every(p => !p.entry.enabled || p.entry.body.isSleeping()); },
|
|
115
112
|
remove() { self._end(rd); },
|
|
113
|
+
/** @internal character.placeAt: root follows the body, so a placement moves the body */ shift(x, y, z) { self._shift(rd, x, y, z); },
|
|
116
114
|
};
|
|
117
115
|
// Joint anchors are computed from the current pose (not the bind pose): in-between bones that are not in the part table (Spine1, clavicle) may not be at their bind position at the start, and this way the error on the first step is zero
|
|
118
116
|
for (const p of list) {
|
|
@@ -130,7 +128,7 @@ export class Ragdolls {
|
|
|
130
128
|
|
|
131
129
|
/** The three-axis range of this joint. If the starting pose is already past the limit, widen the range to the starting angle: otherwise the solver yanks it back on the first step and it looks like a twitch */
|
|
132
130
|
_range(p, limits) {
|
|
133
|
-
const given = limits[p.name] ?? limits[p.shape.kind], base =
|
|
131
|
+
const given = limits[p.name] ?? limits[p.shape.kind], base = p.shape.limits;
|
|
134
132
|
const lim = { twist: given?.twist ?? base.twist, side: given?.side ?? base.side, bend: given?.bend ?? base.bend };
|
|
135
133
|
const F = p.shape.frame;
|
|
136
134
|
// The child's rotation relative to the parent, read in the joint frame: the imaginary x / y / z are the three values Rapier's limits use
|
|
@@ -158,7 +156,7 @@ export class Ragdolls {
|
|
|
158
156
|
}
|
|
159
157
|
|
|
160
158
|
/**
|
|
161
|
-
* The impulse hits the part nearest to position (
|
|
159
|
+
* The impulse hits the part nearest to position (the root part when no position is given). That part only takes HIT_SPEED worth, the rest is shared over the whole body by mass:
|
|
162
160
|
* in a real body force travels along the skeleton, but the solver cannot pass that much in one step, and the whole hit on a 5 kg head would send it flying and tear the joints apart. Total momentum is unchanged.
|
|
163
161
|
*/
|
|
164
162
|
_push(rd, { impulse, position }) {
|
|
@@ -184,27 +182,27 @@ export class Ragdolls {
|
|
|
184
182
|
rd.anim = ch ? ch.anim : e.assets.animatorOf(root);
|
|
185
183
|
if (rd.anim) rd.anim._held = true;
|
|
186
184
|
if (ch) {
|
|
187
|
-
ch.
|
|
188
|
-
ch.velocity.set(0, 0); ch.vy = 0; ch.moveAmount = 0; ch.state = ch.
|
|
189
|
-
// the player capsule is turned off by rigid.step according to
|
|
190
|
-
if (ch !== e.player && ch.mover.collider && ch.mover.
|
|
185
|
+
ch.limp = rd;
|
|
186
|
+
ch.velocity.set(0, 0); ch.vy = 0; ch.moveAmount = 0; ch.state = ch.stateMark = 'ragdoll';
|
|
187
|
+
// the player capsule is turned off by rigid.step according to limp; an NPC's capsule belongs to its mover
|
|
188
|
+
if (ch !== e.player && ch.mover.collider && ch.mover.world === this.r.world) ch.mover.collider.setEnabled(false);
|
|
191
189
|
}
|
|
192
190
|
const rig = e.cameraRig;
|
|
193
191
|
if (rig?.target === root) {
|
|
194
|
-
// follow the
|
|
195
|
-
rd.
|
|
192
|
+
// follow the root part, not the feet: the camera looks at the body, not at the air a person's height above it
|
|
193
|
+
rd.anchor = new THREE.Object3D();
|
|
196
194
|
this._anchor(rd);
|
|
197
195
|
rig.follow(rd.anchor, { height: 0 });
|
|
198
196
|
}
|
|
199
197
|
}
|
|
200
198
|
|
|
201
|
-
_anchor(rd) { const t = rd.
|
|
199
|
+
_anchor(rd) { const t = rd.list[0].entry.body.translation(); rd.anchor.position.set(t.x, t.y, t.z); }
|
|
202
200
|
|
|
203
201
|
/** Every fixed step, after the world has stepped (called by RigidBodies.step) */
|
|
204
202
|
sync() {
|
|
205
203
|
for (const rd of this.live) {
|
|
206
204
|
const { ch, root } = rd;
|
|
207
|
-
if (ch?.
|
|
205
|
+
if (ch?.disposed || !root.parent) { this._end(rd, true); continue; } // the character or model was deleted: only clean up the physics
|
|
208
206
|
if (rd.settled) { if (rd.drawn) continue; rd.drawn = true; } else { rd.drawn = false; this._calm(rd); } // once asleep, stop writing: saves cost and a bone the game wrote stays
|
|
209
207
|
this._pose(rd);
|
|
210
208
|
ch?.syncRecord();
|
|
@@ -222,13 +220,13 @@ export class Ragdolls {
|
|
|
222
220
|
|
|
223
221
|
/** Write the physics result back to the bones. root follows the body (triggers, streaming and saves read it), so the bones are computed after root has moved */
|
|
224
222
|
_pose(rd) {
|
|
225
|
-
const { root, list } = rd,
|
|
223
|
+
const { root, list } = rd, core = list[0].entry.body.translation();
|
|
226
224
|
let low = Infinity;
|
|
227
225
|
for (const p of list) { // lowest point of the body: the soles when standing, the ground when lying, no need to ask the terrain
|
|
228
226
|
const t = p.entry.body.translation(), q = toQ(p.entry.body.rotation());
|
|
229
227
|
low = Math.min(low, t.y - p.rad, t.y + p1.copy(p.seg).applyQuaternion(q).y - p.rad);
|
|
230
228
|
}
|
|
231
|
-
p1.set(
|
|
229
|
+
p1.set(core.x, low, core.z);
|
|
232
230
|
if (root.parent) root.parent.worldToLocal(p1);
|
|
233
231
|
root.position.copy(p1);
|
|
234
232
|
root.updateWorldMatrix(true, false);
|
|
@@ -244,21 +242,32 @@ export class Ragdolls {
|
|
|
244
242
|
p.bone.updateMatrixWorld();
|
|
245
243
|
}
|
|
246
244
|
if (rd.anchor) this._anchor(rd);
|
|
247
|
-
const under =
|
|
248
|
-
if (under && !rd.void) this.e.events.emit('terrain:void', { who:
|
|
245
|
+
const under = core.y < this.e.ground.voidY();
|
|
246
|
+
if (under && !rd.void) this.e.events.emit('terrain:void', { who: list[0].entry, position: { x: core.x, y: core.y, z: core.z } });
|
|
249
247
|
rd.void = under;
|
|
250
248
|
}
|
|
251
249
|
|
|
252
250
|
/** Is this character lying down (rigid.step turns the player capsule off by this) */
|
|
253
|
-
holds(ch) { return !!ch.
|
|
251
|
+
holds(ch) { return !!ch.limp; }
|
|
254
252
|
|
|
255
253
|
/** Load: position belongs to the save, so the character is not put back where the body lies */
|
|
256
254
|
load() { for (const rd of [...this.live]) this._end(rd, false, false); }
|
|
257
255
|
|
|
256
|
+
/** A placement: every part moves by the same offset, so the joints see the pose they had, and at rest, so nothing the fall carried arrives with it. Woken parts settle again */
|
|
257
|
+
_shift(rd, x, y, z) {
|
|
258
|
+
for (const p of rd.list) {
|
|
259
|
+
const b = p.entry.body, t = b.translation();
|
|
260
|
+
this.r.setPosition(p.entry, { x: t.x + x, y: t.y + y, z: t.z + z });
|
|
261
|
+
b.setAngvel({ x: 0, y: 0, z: 0 }, true);
|
|
262
|
+
}
|
|
263
|
+
rd.calm = 0;
|
|
264
|
+
if (rd.anchor) this._anchor(rd);
|
|
265
|
+
}
|
|
266
|
+
|
|
258
267
|
/** End: tear down the physics and give every slot back to its owner. gone: the character no longer exists, nothing to give back; place: put the character where the body lies */
|
|
259
268
|
_end(rd, gone = false, place = true) {
|
|
260
269
|
if (!this.live.delete(rd)) return;
|
|
261
|
-
const { ch, list, anim,
|
|
270
|
+
const { ch, list, anim, anchor, hold } = rd;
|
|
262
271
|
for (const j of rd.joints) if (j.isValid()) this.r.world.removeImpulseJoint(j, true);
|
|
263
272
|
rd.joints = [];
|
|
264
273
|
for (const p of list) p.entry.remove();
|
|
@@ -267,16 +276,18 @@ export class Ragdolls {
|
|
|
267
276
|
for (const p of list) { p.bone.position.copy(p.pos0); p.bone.quaternion.copy(p.q0); } // bones no animation clip writes also go back to how they were before falling
|
|
268
277
|
if (anim) anim._held = false;
|
|
269
278
|
if (ch) {
|
|
270
|
-
ch.
|
|
271
|
-
if (ch !== this.e.player && ch.mover.collider && ch.mover.
|
|
272
|
-
if (ch.state === 'ragdoll') ch.state = ch.
|
|
279
|
+
ch.limp = null;
|
|
280
|
+
if (ch !== this.e.player && ch.mover.collider && ch.mover.world === this.r.world) ch.mover.collider.setEnabled(true);
|
|
281
|
+
if (ch.state === 'ragdoll') ch.state = ch.stateMark = 'idle';
|
|
273
282
|
if (place) ch.placeAt(ch.root.position);
|
|
274
283
|
}
|
|
275
284
|
// if the game switched the camera away meanwhile, do not take it back
|
|
285
|
+
const rig = this.e.cameraRig; // read now: the rig that started following may have been swapped out (architecture 8.2)
|
|
276
286
|
if (rig?.target === anchor) rig.follow(rd.root);
|
|
277
287
|
}
|
|
278
288
|
|
|
279
|
-
|
|
289
|
+
/** The solver is going (rigid left or was replaced): every limp body gets up while its parts can still be read, or the character stays held by a physics that is gone. A dispose of the whole engine, or of the character, has nobody left to give it to */
|
|
290
|
+
dispose() { this._sub.remove(); for (const rd of [...this.live]) this._end(rd, this.e.disposed || !!rd.ch?.disposed); }
|
|
280
291
|
}
|
|
281
292
|
|
|
282
293
|
/** The SkinnedMesh with the most bones: clothes and accessories are often small meshes on the same skeleton */
|
|
@@ -1,6 +1,8 @@
|
|
|
1
|
-
// Ragdoll skeleton reading:
|
|
1
|
+
// Ragdoll skeleton reading: a graph of parts over a skeleton, each measured for its real length and thickness. The default graph comes from recognising each tool's bone names
|
|
2
|
+
// (Mixamo, Blender, Unreal, Bip01, VRM, Quaternius...) as the 11 parts of a human body; a game's own graph (four legs, a tail) goes through the same measuring.
|
|
2
3
|
// Why this is apart from ragdoll.js: it only reads, never writes, and never touches Rapier, so it can be tested without physics.
|
|
3
4
|
import * as THREE from 'three';
|
|
5
|
+
import { vec3 } from '../../core/base/math.js';
|
|
4
6
|
import { codedError } from '../../core/base/errorHints.js';
|
|
5
7
|
|
|
6
8
|
const PARTS = ['hips', 'chest', 'head', 'upperArmL', 'lowerArmL', 'upperArmR', 'lowerArmR', 'upperLegL', 'lowerLegL', 'upperLegR', 'lowerLegR'];
|
|
@@ -12,6 +14,20 @@ const NAMES = {
|
|
|
12
14
|
upperLeg: ['thigh', 'upperleg', 'upleg', 'femur', 'leg'], lowerLeg: ['shin', 'calf', 'lowerleg', 'loleg', 'knee', 'tibia', 'leg'],
|
|
13
15
|
};
|
|
14
16
|
|
|
17
|
+
const D = Math.PI / 180;
|
|
18
|
+
// Default range of motion (radians, relative to bind pose). bend is positive forward (backward for knees), side is sideways, twist is around the bone. This is physical plausibility, not looks
|
|
19
|
+
const LIMITS = {
|
|
20
|
+
chest: { bend: [-30 * D, 40 * D], side: [-25 * D, 25 * D], twist: [-30 * D, 30 * D] },
|
|
21
|
+
head: { bend: [-40 * D, 50 * D], side: [-35 * D, 35 * D], twist: [-60 * D, 60 * D] },
|
|
22
|
+
upperArm: { bend: [-60 * D, 120 * D], side: [-100 * D, 100 * D], twist: [-70 * D, 70 * D] },
|
|
23
|
+
lowerArm: { bend: [0, 145 * D], side: [-3 * D, 3 * D], twist: [-60 * D, 60 * D] },
|
|
24
|
+
upperLeg: { bend: [-25 * D, 110 * D], side: [-45 * D, 45 * D], twist: [-35 * D, 35 * D] },
|
|
25
|
+
lowerLeg: { bend: [0, 140 * D], side: [-3 * D, 3 * D], twist: [-5 * D, 5 * D] },
|
|
26
|
+
};
|
|
27
|
+
const SHARE = { hips: 0.16, chest: 0.3, head: 0.08, upperArm: 0.03, lowerArm: 0.025, upperLeg: 0.11, lowerLeg: 0.07 }; // how the total mass is split
|
|
28
|
+
const WHOLE = 70; // kg of a body whose graph or call names none
|
|
29
|
+
const OPEN = { bend: [-45 * D, 45 * D], side: [-45 * D, 45 * D], twist: [-30 * D, 30 * D] }; // a part of a game's graph that gives no limits: loose, but no joint folds through itself
|
|
30
|
+
|
|
15
31
|
/** Bone name -> { side: 'L' | 'R' | '', word }: LeftForeArm, upperarm_l, Bip01 L Thigh, DEF-forearm.L, UpperArmR (GLTFLoader eats the dot) all split into the same shape */
|
|
16
32
|
function parse(name) {
|
|
17
33
|
const words = name.replace(/([a-z0-9])([A-Z])/g, '$1 $2').split(/[^a-zA-Z0-9]+/).map(w => w.toLowerCase().replace(/\d+$/, '')).filter(w => w && !NOISE.has(w));
|
|
@@ -68,7 +84,7 @@ export function readBones(skeleton, given = {}) {
|
|
|
68
84
|
if (bad.length || missing.length) {
|
|
69
85
|
const names = skeleton.bones.slice(0, 40).map(b => b.name).join(', ');
|
|
70
86
|
throw codedError('rigid-misuse', `rigid.ragdoll(): cannot read this skeleton. Missing: ${[...bad, ...missing.filter(p => !bad.some(s => s.startsWith(p + ':')))].join(', ')}. `
|
|
71
|
-
+ `Bones in it: ${names}${skeleton.bones.length > 40 ? ', ...' : ''}. Fix: name them, e.g. engine.rigid.ragdoll(character, { bones: { ${missing[0] ?? 'hips'}: '<bone name>' } })`);
|
|
87
|
+
+ `Bones in it: ${names}${skeleton.bones.length > 40 ? ', ...' : ''}. Fix: name them, e.g. engine.rigid.ragdoll(character, { bones: { ${missing[0] ?? 'hips'}: '<bone name>' } }); a body that is not a human: the rule 'ragdoll.graph', recipe 11`);
|
|
72
88
|
}
|
|
73
89
|
if (map.hips === map.chest) throw codedError('rigid-misuse', `rigid.ragdoll(): hips and chest are the same bone ('${map.hips.name}'), so the torso has one part. Fix: pass bones: { hips: '<pelvis bone>', chest: '<upper spine bone>' }`);
|
|
74
90
|
return map;
|
|
@@ -89,40 +105,59 @@ function toSegment(p, a, b) {
|
|
|
89
105
|
}
|
|
90
106
|
|
|
91
107
|
/**
|
|
92
|
-
*
|
|
93
|
-
*
|
|
94
|
-
*
|
|
108
|
+
* The default graph: the 11 parts of a human body, read from the skeleton. Everything that knows a body has legs lives here, so a wolf or a snake is just another graph.
|
|
109
|
+
* Beyond the data any graph has: kind names the limits a game can widen for both sides at once, end is the part a bone points at, forward the way this joint bends.
|
|
110
|
+
* @returns {Record<string, any>}
|
|
95
111
|
*/
|
|
96
|
-
export function
|
|
97
|
-
const sk = mesh.skeleton, rest = {};
|
|
112
|
+
export function humanoidGraph(mesh, given) {
|
|
113
|
+
const map = readBones(mesh.skeleton, given), sk = mesh.skeleton, rest = {};
|
|
98
114
|
for (const n of PARTS) rest[n] = restOf(sk, map[n]);
|
|
99
115
|
const right = v1.subVectors(rest.upperLegR.p, rest.upperLegL.p).clone().normalize();
|
|
100
116
|
const up = new THREE.Vector3().subVectors(rest.chest.p, rest.hips.p).normalize();
|
|
101
117
|
const forward = new THREE.Vector3().crossVectors(up, right).normalize();
|
|
102
|
-
|
|
103
|
-
const
|
|
104
|
-
return c ? restOf(sk, c).p : null;
|
|
105
|
-
};
|
|
106
|
-
const parts = PARTS.map(name => {
|
|
107
|
-
const kind = name.replace(/[LR]$/, ''), side = name.slice(-1), r = rest[name];
|
|
108
|
-
let end;
|
|
109
|
-
if (name === 'hips') end = rest.chest.p;
|
|
110
|
-
else if (name === 'chest') end = rest.head.p;
|
|
111
|
-
else if (kind === 'upperArm') end = rest['lowerArm' + side].p;
|
|
112
|
-
else if (kind === 'upperLeg') end = rest['lowerLeg' + side].p;
|
|
113
|
-
else if (name === 'head') end = null;
|
|
114
|
-
else end = childEnd(map[name]) ?? new THREE.Vector3().subVectors(r.p, rest[(kind === 'lowerArm' ? 'upperArm' : 'upperLeg') + side].p).add(r.p);
|
|
118
|
+
return Object.fromEntries(PARTS.map(name => {
|
|
119
|
+
const kind = name.replace(/[LR]$/, ''), side = name.slice(-1);
|
|
115
120
|
let parent = null;
|
|
116
121
|
for (let o = map[name].parent; o && !parent; o = o.parent) parent = PARTS.find(n => map[n] === o) ?? null;
|
|
117
122
|
if (name !== 'hips' && !parent) throw codedError('rigid-misuse', `rigid.ragdoll(): bone '${map[name].name}' (${name}) is not under hips ('${map.hips.name}'), so nothing holds it. Fix: pass bones: { hips: '<the bone every body part hangs from>' }`);
|
|
118
|
-
|
|
123
|
+
const end = { hips: 'chest', chest: 'head', head: 'top', upperArm: 'lowerArm' + side, upperLeg: 'lowerLeg' + side }[kind];
|
|
124
|
+
// Knees bend backward, other joints forward
|
|
125
|
+
return [name, { bone: map[name], parent, kind, limits: LIMITS[kind], mass: WHOLE * SHARE[kind], end, forward: kind === 'lowerLeg' ? forward.clone().negate() : forward, up }];
|
|
126
|
+
}));
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
/** A graph's bone: a name or the bone itself; one outside the skeleton is refused by name */
|
|
130
|
+
function boneOf(sk, name, b) {
|
|
131
|
+
const bone = b?.isObject3D ? b : sk.bones.find(x => x.name === b);
|
|
132
|
+
if (bone && sk.bones.includes(bone)) return bone;
|
|
133
|
+
throw codedError('rigid-misuse', `ragdoll.graph: part '${name}' names bone '${b?.name ?? b}', which is not in the skeleton. Bones in it: ${sk.bones.slice(0, 40).map(x => x.name).join(', ')}`);
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
/**
|
|
137
|
+
* Static shape of each part of a graph { part: { bone, parent, limits, mass, end, forward, kind, up } } (all in bind space, in bind-time length units):
|
|
138
|
+
* { name, kind, bone, parent, p, q, end, radius, frame, limits, mass }, parents before children, so the one part without a parent comes first.
|
|
139
|
+
* end: the tip of this bone, from the real bone length, not guessed by proportion (a misaligned collider is where mesh deformation comes from). radius: distance from skinned vertices to this bone, so thin and heavy characters both fit.
|
|
140
|
+
* frame: joint frame, x along the bone (twist), y toward positive bend, z the hinge axis.
|
|
141
|
+
*/
|
|
142
|
+
export function shapeParts(mesh, graph) {
|
|
143
|
+
const bad = why => codedError('rigid-misuse', `ragdoll.graph: ${why}. A graph is { part: { bone, parent, limits?, mass?, end?, forward? } }, one part without a parent`);
|
|
144
|
+
if (!graph || typeof graph !== 'object') throw bad(`got ${String(graph)}`);
|
|
145
|
+
const sk = mesh.skeleton, names = Object.keys(graph), roots = names.filter(n => !graph[n].parent);
|
|
146
|
+
if (names.length < 2 || roots.length !== 1) throw bad(`${names.length} part(s) with ${roots.length} root(s) (${roots.join(', ')})`);
|
|
147
|
+
const parts = names.map(name => {
|
|
148
|
+
const g = graph[name], bone = boneOf(sk, name, g.bone), r = restOf(sk, bone);
|
|
149
|
+
if (g.parent && !graph[g.parent]) throw bad(`part '${name}' has parent '${g.parent}', which is not a part`);
|
|
150
|
+
if (g.parent && !under(bone, boneOf(sk, g.parent, graph[g.parent].bone))) throw bad(`part '${name}': bone '${bone.name}' is not under the bone of its parent '${g.parent}'`);
|
|
151
|
+
return { name, kind: g.kind, bone, parent: g.parent ?? null, p: r.p, q: r.q, end: null, radius: 0, frame: null, limits: { ...OPEN, ...g.limits }, mass: g.mass ?? WHOLE / names.length, d: depth(bone) };
|
|
119
152
|
}).sort((a, b) => a.d - b.d);
|
|
120
|
-
|
|
153
|
+
const byName = Object.fromEntries(parts.map(s => [s.name, s]));
|
|
154
|
+
for (const s of parts) if (graph[s.name].end !== 'top') s.end = tipOf(sk, s, parts, byName, graph[s.name].end);
|
|
155
|
+
measure(mesh, parts, graph, byName);
|
|
121
156
|
for (const s of parts) {
|
|
157
|
+
const g = graph[s.name], F = g.forward ? vec3(g.forward) : new THREE.Vector3(0, 0, 1), up = g.up ? vec3(g.up) : new THREE.Vector3(0, 1, 0);
|
|
122
158
|
const x = new THREE.Vector3().subVectors(s.end, s.p).normalize();
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
if (y.lengthSq() < 1e-4) y.copy(up).addScaledVector(x, -x.dot(up)); // The bone points straight forward (a rare bind pose)
|
|
159
|
+
const y = F.clone().addScaledVector(x, -x.dot(F)); // the y axis is the direction the bone tip moves when bend is positive
|
|
160
|
+
if (y.lengthSq() < 1e-4) y.copy(up).addScaledVector(x, -x.dot(up)); // The bone points straight along forward (a rare bind pose)
|
|
126
161
|
y.normalize();
|
|
127
162
|
const z = new THREE.Vector3().crossVectors(x, y);
|
|
128
163
|
s.frame = new THREE.Quaternion().setFromRotationMatrix(new THREE.Matrix4().makeBasis(x, y, z));
|
|
@@ -130,11 +165,23 @@ export function shapeParts(mesh, map) {
|
|
|
130
165
|
return parts;
|
|
131
166
|
}
|
|
132
167
|
|
|
133
|
-
/**
|
|
134
|
-
function
|
|
168
|
+
/** Where a part ends: the part it names; else the middle of its child parts (the one child when they meet at its own joint); else its first child bone, a hand or a foot; else on along the segment before it */
|
|
169
|
+
function tipOf(sk, s, parts, byName, end) {
|
|
170
|
+
if (end) { if (!byName[end]) throw codedError('rigid-misuse', `ragdoll.graph: part '${s.name}' has end '${end}', which is not a part`); return byName[end].p; }
|
|
171
|
+
const kids = parts.filter(c => c.parent === s.name);
|
|
172
|
+
if (kids.length) {
|
|
173
|
+
const mid = kids.reduce((m, c) => m.add(c.p), new THREE.Vector3()).divideScalar(kids.length);
|
|
174
|
+
return mid.distanceTo(s.p) > 1e-5 ? mid : kids[0].p;
|
|
175
|
+
}
|
|
176
|
+
const c = s.bone.children.find(o => o.isBone && sk.bones.includes(o));
|
|
177
|
+
return c ? restOf(sk, c).p : new THREE.Vector3().subVectors(s.p, byName[s.parent].p).add(s.p);
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
/** Measure thickness: assign each vertex to the part of its heaviest-weighted bone and take the 60th percentile of the distance to the segment (outliers such as fingers and capes do not count). A part with end: 'top' (a head) has no next bone, so its top is measured from vertices too */
|
|
181
|
+
function measure(mesh, parts, graph, byName) {
|
|
135
182
|
const g = mesh.geometry, pos = g.attributes.position, si = g.attributes.skinIndex, sw = g.attributes.skinWeight, sk = mesh.skeleton;
|
|
136
183
|
const owner = sk.bones.map(b => { for (let o = b; o; o = o.parent) { const s = parts.find(x => x.bone === o); if (s) return s; } return null; });
|
|
137
|
-
const lists = new Map(parts.map(s => [s, []]))
|
|
184
|
+
const lists = new Map(parts.map(s => [s, []]));
|
|
138
185
|
const pts = new Map(parts.map(s => [s, []]));
|
|
139
186
|
if (pos && si && sw) {
|
|
140
187
|
for (let i = 0; i < pos.count; i++) {
|
|
@@ -144,11 +191,14 @@ function measure(mesh, parts, up) {
|
|
|
144
191
|
if (s) pts.get(s).push(new THREE.Vector3().fromBufferAttribute(pos, i).applyMatrix4(mesh.bindMatrix));
|
|
145
192
|
}
|
|
146
193
|
}
|
|
147
|
-
//
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
194
|
+
// The top: the vertex farthest up; with no vertices, estimate half the distance to the parent
|
|
195
|
+
for (const s of parts) {
|
|
196
|
+
if (graph[s.name].end !== 'top') continue;
|
|
197
|
+
const up = graph[s.name].up ? vec3(graph[s.name].up) : new THREE.Vector3(0, 1, 0);
|
|
198
|
+
let top = 0;
|
|
199
|
+
for (const v of pts.get(s)) top = Math.max(top, v1.subVectors(v, s.p).dot(up));
|
|
200
|
+
s.end = s.p.clone().addScaledVector(up, top > 0 ? top : byName[s.parent].p.distanceTo(s.p) * 0.5);
|
|
201
|
+
}
|
|
152
202
|
for (const s of parts) {
|
|
153
203
|
const list = lists.get(s), len = s.p.distanceTo(s.end);
|
|
154
204
|
for (const v of pts.get(s)) list.push(toSegment(v, s.p, s.end));
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
// Rapier 0.21 keeps its query structures in the broad phase, and only a step rebuilds them: World has no updateSceneQueries and no query pipeline, and
|
|
2
|
+
// propagateModifiedBodyPositionsToColliders moves colliders without touching the broad phase. So a frozen engine refreshes with a step of no time, here and nowhere else.
|
|
3
|
+
// Twice: the first leaves a moved body's collider in the old place, the second catches it up. Tools test `rapier refresh` holds each of these, per Rapier version.
|
|
4
|
+
|
|
5
|
+
/** @internal Rebuild what queries read and nothing else (velocities, positions, sleep and contacts stay); the step length comes back even if Rapier throws */
|
|
6
|
+
export function refreshQueries(world) {
|
|
7
|
+
const dt = world.timestep;
|
|
8
|
+
world.timestep = 0;
|
|
9
|
+
try { world.step(); world.step(); } finally { world.timestep = dt; }
|
|
10
|
+
}
|
package/modules/rigid/sync.js
CHANGED
|
@@ -129,30 +129,61 @@ function dropTerrain(r, key) {
|
|
|
129
129
|
if (t) for (const c of t.colliders) r.world.removeCollider(c, false);
|
|
130
130
|
r.terrain.delete(key);
|
|
131
131
|
}
|
|
132
|
+
// Chunk copies of a ground source that left: terrain and trunks are copies of the ground too, and nothing else asks for them once chunkCollision is gone. Answers whether any went.
|
|
133
|
+
export function dropChunks(r) {
|
|
134
|
+
if (r.engine.ground.chunkCollision || !(r.terrain.size || r.trees.size)) return false;
|
|
135
|
+
for (const key of [...r.terrain.keys()]) dropTerrain(r, key);
|
|
136
|
+
for (const key of [...r.trees.keys()]) dropTrees(r, key);
|
|
137
|
+
return true;
|
|
138
|
+
}
|
|
132
139
|
// Houses and pillars from the collision module, as physics colliders: engine.collision.mirror does the add / remove diff (shared with nav), this
|
|
133
|
-
// only says how one collider is built and dropped. Built lazily: the mirror lives on the collision module, which rigid requires.
|
|
140
|
+
// only says how one collider is built and dropped. Built lazily: the mirror lives on the collision module, which rigid requires. A mirror knows one module, so another
|
|
141
|
+
// collision module (replaces) drops the old colliders and starts a new mirror. Answers whether a collider changed.
|
|
134
142
|
const UP = new THREE.Vector3(0, 1, 0), Q = new THREE.Quaternion();
|
|
135
143
|
export function syncStatics(r) {
|
|
136
|
-
r.
|
|
144
|
+
r._collision.sync(() => { r._statics?.clear(true); r._statics = null; });
|
|
145
|
+
r._statics ??= r.engine.collision?.mirror({
|
|
137
146
|
add(type, o) {
|
|
138
147
|
const R = r.rapier, g = o.y ?? r.engine.surface(o.x, o.z);
|
|
139
|
-
|
|
140
|
-
Q.
|
|
141
|
-
|
|
148
|
+
Q.setFromAxisAngle(UP, o.rot ?? 0);
|
|
149
|
+
const shape = type === 'box' ? R.ColliderDesc.cuboid(o.hw, o.h / 2, o.hd).setRotation({ x: Q.x, y: Q.y, z: Q.z, w: Q.w }) : R.ColliderDesc.cylinder(o.h / 2, o.r);
|
|
150
|
+
const c = r.world.createCollider(shape.setTranslation(o.x, g + o.h / 2, o.z));
|
|
151
|
+
if (o.y == null) r._onGround.set(o, c);
|
|
152
|
+
return c;
|
|
142
153
|
},
|
|
143
|
-
remove(
|
|
144
|
-
});
|
|
145
|
-
r._statics
|
|
154
|
+
remove(c, o) { r._onGround.delete(o); r.world.removeCollider(c, false); },
|
|
155
|
+
}) ?? null;
|
|
156
|
+
return !!r._statics?.sync();
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
/** The ground moved under a world box: a collider that stands on the ground, one with no y of its own, stands on what is there now. Mirror data keeps no height, so nothing else would tell it. No area: all of them */
|
|
160
|
+
export function restandStatics(r, { x0 = -Infinity, z0 = -Infinity, x1 = Infinity, z1 = Infinity } = {}) {
|
|
161
|
+
for (const [o, c] of r._onGround) if (o.x + o.r >= x0 && o.x - o.r <= x1 && o.z + o.r >= z0 && o.z - o.r <= z1) { c.setTranslation({ x: o.x, y: r.engine.surface(o.x, o.z) + o.h / 2, z: o.z }); r._behind = true; }
|
|
146
162
|
}
|
|
147
163
|
|
|
148
|
-
// Ground of a level (hand-built scene): one static triangle mesh, rebuilt when the level changes
|
|
164
|
+
// Ground of a level (hand-built scene): one static triangle mesh, rebuilt when the level changes. The provider's staticTrimeshes names the source
|
|
165
|
+
// (engine.ground itself is a fresh object whenever a collider source joins, and that alone must not rebuild it). A new ground of any kind stands the world boxes on it again:
|
|
166
|
+
// a level at another height sends no ground:change. Answers whether the triangles changed.
|
|
149
167
|
export function syncLevel(r) {
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
168
|
+
r._standOn.sync(() => restandStatics(r));
|
|
169
|
+
return !!r._level.sync(() => {
|
|
170
|
+
const G = r.engine.ground, old = r._levelColliders || [];
|
|
171
|
+
r._levelColliders = []; // before anything can throw: the retry must not remove these twice
|
|
172
|
+
for (const c of old) r.world.removeCollider(c, false);
|
|
173
|
+
const desc = t => r.rapier.ColliderDesc.trimesh(t.positions, t.indices).setFriction(0.9);
|
|
174
|
+
for (const t of G.staticTrimeshes?.() ?? []) r._levelColliders.push(r.world.createCollider(desc(t)));
|
|
175
|
+
});
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
// A ground with no collision of its own stands on an infinite flat plane at y = 0, unless the game turned it off. One more copy of the ground, so it comes and goes with the ground
|
|
179
|
+
// source: left standing it is an invisible floor over a level installed later. Answers whether it changed.
|
|
180
|
+
export const wantsFloor = r => { const G = r.engine.ground; return r.fallbackFloor && !G.chunkCollision && !G.staticTrimeshes; };
|
|
181
|
+
export function syncFloor(r) {
|
|
182
|
+
return !!r._floor.sync(() => {
|
|
183
|
+
const want = wantsFloor(r);
|
|
184
|
+
if (want && !r._floorCollider) r._floorCollider = r.world.createCollider(r.rapier.ColliderDesc.cuboid(5000, 0.5, 5000).setTranslation(0, -0.5, 0));
|
|
185
|
+
else if (!want && r._floorCollider) { r.world.removeCollider(r._floorCollider, false); r._floorCollider = null; }
|
|
186
|
+
});
|
|
156
187
|
}
|
|
157
188
|
|
|
158
189
|
// ---------- Game-set body / collider state across RigidBodies._fresh ----------
|