@needle-tools/three-mesh-effects 0.1.0-alpha → 0.1.0-alpha.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/LICENSE +21 -21
- package/README.md +94 -88
- package/build/deformation-runtime.js.map +1 -1
- package/build/impostor-runtime-needle-engine.js.map +1 -1
- package/build/impostor-runtime.js.map +1 -1
- package/build/internal/deformation/cloth-surface.js.map +1 -1
- package/build/internal/deformation/fur-surface.js.map +1 -1
- package/build/internal/deformation/ik-constraints.js.map +1 -1
- package/build/internal/deformation/joints-json.js.map +1 -1
- package/build/internal/deformation/limits.js.map +1 -1
- package/build/internal/deformation/motion-settings.js.map +1 -1
- package/build/internal/deformation/pin-cloth.js.map +1 -1
- package/build/internal/deformation/pin-ik.js.map +1 -1
- package/build/internal/deformation/pin-types.js.map +1 -1
- package/build/internal/deformation/pin-wiggle.js.map +1 -1
- package/build/internal/deformation/pose-slots.js.map +1 -1
- package/build/internal/deformation/pose-timeline.js.map +1 -1
- package/build/internal/deformation/rig-drivers.js.map +1 -1
- package/build/internal/deformation/rig-extension.js.map +1 -1
- package/build/internal/deformation/rig-runtime.js.map +1 -1
- package/build/internal/deformation/wind.js.map +1 -1
- package/build/internal/impostor/impostor-metadata.js.map +1 -1
- package/build/internal/impostor/impostor-node-material.js.map +1 -1
- package/build/internal/impostor/impostor-runtime-support.js.map +1 -1
- package/build/internal/impostor/octahedral.js.map +1 -1
- package/build/internal/pixel-impostor/pixel-impostor-display.js.map +1 -1
- package/build/internal/pixel-impostor/pixel-impostor-metadata.js.map +1 -1
- package/build/internal/pixel-impostor/pixel-impostor-runtime.js.map +1 -1
- package/build/internal/rendering/skin-projection.js +52 -52
- package/build/internal/rendering/skin-projection.js.map +2 -2
- package/build/internal/rendering/surface-query.js +52 -52
- package/build/internal/rendering/surface-query.js.map +2 -2
- package/build/internal/rendering/wireframe.js.map +1 -1
- package/build/internal/rendering/wrap-preview-settings.js.map +1 -1
- package/build/internal/rendering/wrap-preview.js +52 -52
- package/build/internal/rendering/wrap-preview.js.map +2 -2
- package/build/internal/rendering/wrap-skin.js +52 -52
- package/build/internal/rendering/wrap-skin.js.map +2 -2
- package/build/pixel-impostor-runtime.js.map +1 -1
- package/build/wrap-effects.js +52 -52
- package/build/wrap-effects.js.map +2 -2
- package/package.json +107 -94
- package/src/deformation/cloth-surface.ts +223 -223
- package/src/deformation/fur-surface.ts +129 -129
- package/src/deformation/ik-constraints.ts +37 -37
- package/src/deformation/joints-json.ts +94 -94
- package/src/deformation/limits.ts +25 -25
- package/src/deformation/motion-settings.ts +9 -9
- package/src/deformation/pin-cloth.ts +149 -149
- package/src/deformation/pin-ik.ts +582 -582
- package/src/deformation/pin-types.ts +22 -22
- package/src/deformation/pin-wiggle.ts +119 -119
- package/src/deformation/pose-slots.ts +106 -106
- package/src/deformation/pose-timeline.ts +242 -242
- package/src/deformation/rig-drivers.ts +32 -32
- package/src/deformation/rig-extension.ts +87 -87
- package/src/deformation/rig-runtime.ts +416 -416
- package/src/deformation/wind.ts +36 -36
- package/src/impostor/impostor-metadata.js +137 -137
- package/src/impostor/impostor-node-material.js +1581 -1581
- package/src/impostor/impostor-runtime-support.js +139 -139
- package/src/impostor/octahedral.js +280 -280
- package/src/pixel-impostor/pixel-impostor-display.js +794 -794
- package/src/pixel-impostor/pixel-impostor-metadata.js +74 -74
- package/src/pixel-impostor/pixel-impostor-runtime.js +78 -78
- package/src/public/deformation-runtime.ts +3 -3
- package/src/public/impostor-runtime-needle-engine.js +56 -56
- package/src/public/impostor-runtime.js +21 -21
- package/src/public/pixel-impostor-runtime.js +5 -5
- package/src/public/wrap-effects.js +21 -21
- package/src/rendering/skin-projection.js +113 -113
- package/src/rendering/surface-query.js +88 -88
- package/src/rendering/wireframe.js +115 -115
- package/src/rendering/wrap-preview-settings.js +123 -123
- package/src/rendering/wrap-preview.js +645 -645
- package/src/rendering/wrap-skin.js +109 -109
- package/build/internal/public/deformation-runtime.js +0 -2143
- package/build/internal/public/deformation-runtime.js.map +0 -7
- package/build/internal/public/impostor-runtime-needle-engine.js +0 -42
- package/build/internal/public/impostor-runtime-needle-engine.js.map +0 -7
- package/build/internal/public/impostor-runtime.js +0 -1333
- package/build/internal/public/impostor-runtime.js.map +0 -7
- package/build/internal/public/pixel-impostor-runtime.js +0 -876
- package/build/internal/public/pixel-impostor-runtime.js.map +0 -7
- package/build/internal/public/wrap-effects.js +0 -5640
- package/build/internal/public/wrap-effects.js.map +0 -7
|
@@ -1,2143 +0,0 @@
|
|
|
1
|
-
// @ts-nocheck
|
|
2
|
-
|
|
3
|
-
// src/deformation/rig-runtime.ts
|
|
4
|
-
import { AnimationMixer, PropertyBinding, Matrix4 as Matrix43, Object3D, Quaternion as Quaternion6, SkinnedMesh as SkinnedMesh2, Vector3 as Vector38 } from "three";
|
|
5
|
-
|
|
6
|
-
// src/deformation/pin-types.ts
|
|
7
|
-
var DEFAULT_FUR_DEPTH = 0.1;
|
|
8
|
-
var MAX_FUR_DEPTH = 0.5;
|
|
9
|
-
var IK_CHAIN_KINDS = ["leg", "arm", "head", "tail", "wing", "fin", "tentacle", "spine"];
|
|
10
|
-
|
|
11
|
-
// src/deformation/limits.ts
|
|
12
|
-
var MAX_DEFORMATION_PINS = 128;
|
|
13
|
-
|
|
14
|
-
// src/deformation/motion-settings.ts
|
|
15
|
-
var DEFAULT_MOTION = { reach: 0.5, frequency: 14 / (2 * Math.PI), damping: 0.28, massInfluence: 1, strength: 1 };
|
|
16
|
-
function validateMotionSettings(value) {
|
|
17
|
-
if (!value || !Number.isFinite(value.reach) || value.reach < 0 || value.reach > 1 || !Number.isFinite(value.frequency) || value.frequency < 0.25 || value.frequency > 8 || !Number.isFinite(value.damping) || value.damping < 0.05 || value.damping > 1 || !Number.isFinite(value.massInfluence) || value.massInfluence < 0 || value.massInfluence > 2 || !Number.isFinite(value.strength) || value.strength < 0 || value.strength > 3) throw new Error("Invalid motion settings.");
|
|
18
|
-
}
|
|
19
|
-
|
|
20
|
-
// src/deformation/ik-constraints.ts
|
|
21
|
-
import { Quaternion, Vector3 } from "three";
|
|
22
|
-
var DEFAULT_IK_CONSTRAINT = { mode: "free", axis: "auto", min: -120, max: 120 };
|
|
23
|
-
function validateIKConstraint(value) {
|
|
24
|
-
if (value?.maxY !== void 0 && (!Number.isFinite(value.maxY) || value.maxY < 0 || value.maxY > 180)) throw new Error("Invalid IK cone aperture.");
|
|
25
|
-
if (value?.orientation !== void 0 && (!Array.isArray(value.orientation) || value.orientation.length !== 4 || !value.orientation.every(Number.isFinite) || Math.abs(Math.hypot(...value.orientation) - 1) > 1e-4)) throw new Error("Invalid IK cone orientation.");
|
|
26
|
-
if (!value || !["free", "cone", "hinge", "locked"].includes(value.mode) || !["auto", "x", "y", "z"].includes(value.axis) || !Number.isFinite(value.min) || !Number.isFinite(value.max) || value.min < -180 || value.max > 180 || value.min > value.max || value.mode === "cone" && value.max < 0) throw new Error("Invalid IK joint constraint.");
|
|
27
|
-
}
|
|
28
|
-
function coneFrame(axis, constraint) {
|
|
29
|
-
return new Quaternion().fromArray(constraint.orientation ?? [0, 0, 0, 1]).multiply(new Quaternion().setFromUnitVectors(new Vector3(0, 0, 1), axis.clone().normalize()));
|
|
30
|
-
}
|
|
31
|
-
function coneAngle(constraint, azimuth) {
|
|
32
|
-
const x = (constraint.mode === "cone" ? constraint.max : 90) * Math.PI / 180, y = (constraint.mode === "cone" ? constraint.maxY ?? constraint.max : 90) * Math.PI / 180;
|
|
33
|
-
const c = Math.cos(azimuth), s = Math.sin(azimuth);
|
|
34
|
-
if (x === 0 && Math.abs(c) > 1e-8 || y === 0 && Math.abs(s) > 1e-8) return 0;
|
|
35
|
-
return 1 / Math.sqrt((Math.abs(c) < 1e-8 ? 0 : c / Math.max(x, 1e-12)) ** 2 + (Math.abs(s) < 1e-8 ? 0 : s / Math.max(y, 1e-12)) ** 2);
|
|
36
|
-
}
|
|
37
|
-
function constrainCone(rotation, axis, constraint, movingAxis = axis) {
|
|
38
|
-
const frame = coneFrame(axis, constraint), direction = movingAxis.clone().normalize().applyQuaternion(rotation);
|
|
39
|
-
const local = direction.clone().applyQuaternion(frame.clone().invert()), azimuth = Math.atan2(local.y, local.x);
|
|
40
|
-
const angle = Math.atan2(Math.hypot(local.x, local.y), local.z), limit = coneAngle(constraint, azimuth);
|
|
41
|
-
if (angle <= limit + 1e-8) return rotation.clone();
|
|
42
|
-
const target = new Vector3(Math.sin(limit) * Math.cos(azimuth), Math.sin(limit) * Math.sin(azimuth), Math.cos(limit)).applyQuaternion(frame);
|
|
43
|
-
return new Quaternion().setFromUnitVectors(direction, target).multiply(rotation).normalize();
|
|
44
|
-
}
|
|
45
|
-
|
|
46
|
-
// src/deformation/pose-slots.ts
|
|
47
|
-
var POSE_SLOTS = 9;
|
|
48
|
-
function capturePose(pins) {
|
|
49
|
-
return pins.map((pin) => ({ id: pin.id, pose: pin.pose, ...pin.authored ? { authored: true } : {}, ...pin.ikTarget ? { ikTarget: pin.ikTarget } : {} }));
|
|
50
|
-
}
|
|
51
|
-
var restPoseOf = (rest) => ({ position: [rest[0], rest[1], rest[2]], rotation: [0, 0, 0, 1], scale: [1, 1, 1] });
|
|
52
|
-
function carriedPose(rest, parentRest, parent) {
|
|
53
|
-
const [qx, qy, qz, qw] = parent.rotation;
|
|
54
|
-
const x = (rest[0] - parentRest[0]) * parent.scale[0], y = (rest[1] - parentRest[1]) * parent.scale[1], z = (rest[2] - parentRest[2]) * parent.scale[2];
|
|
55
|
-
const tx = 2 * (qy * z - qz * y), ty = 2 * (qz * x - qx * z), tz = 2 * (qx * y - qy * x);
|
|
56
|
-
const position = [parent.position[0] + x + qw * tx + (qy * tz - qz * ty), parent.position[1] + y + qw * ty + (qz * tx - qx * tz), parent.position[2] + z + qw * tz + (qx * ty - qy * tx)];
|
|
57
|
-
const rotation = [qx, qy, qz, qw], scale = [parent.scale[0], parent.scale[1], parent.scale[2]];
|
|
58
|
-
return { position, rotation, scale };
|
|
59
|
-
}
|
|
60
|
-
function resolvePose(pins, slot, parents = /* @__PURE__ */ new Map()) {
|
|
61
|
-
const saved = new Map(slot.poses.map((p) => [p.id, p]));
|
|
62
|
-
const byId = new Map(pins.map((pin) => [pin.id, pin]));
|
|
63
|
-
const memo = /* @__PURE__ */ new Map(), visiting = /* @__PURE__ */ new Set();
|
|
64
|
-
const poseOf = (pin) => {
|
|
65
|
-
const cached = memo.get(pin.id);
|
|
66
|
-
if (cached) return cached;
|
|
67
|
-
const stored = saved.get(pin.id);
|
|
68
|
-
let pose2;
|
|
69
|
-
if (stored) pose2 = stored.pose;
|
|
70
|
-
else {
|
|
71
|
-
const parentId = parents.get(pin.id);
|
|
72
|
-
const parent = parentId && !visiting.has(parentId) ? byId.get(parentId) : void 0;
|
|
73
|
-
if (!parent) pose2 = restPoseOf(pin.rest);
|
|
74
|
-
else {
|
|
75
|
-
visiting.add(pin.id);
|
|
76
|
-
pose2 = carriedPose(pin.rest, parent.rest, poseOf(parent));
|
|
77
|
-
visiting.delete(pin.id);
|
|
78
|
-
}
|
|
79
|
-
}
|
|
80
|
-
memo.set(pin.id, pose2);
|
|
81
|
-
return pose2;
|
|
82
|
-
};
|
|
83
|
-
const resolved = pins.map((pin) => {
|
|
84
|
-
const stored = saved.get(pin.id), { ikTarget: _target, authored: _authored, ...base } = pin;
|
|
85
|
-
return { ...base, pose: poseOf(pin), ...stored?.authored ? { authored: true } : {}, ...stored?.ikTarget ? { ikTarget: stored.ikTarget } : {} };
|
|
86
|
-
});
|
|
87
|
-
return resolved.map((pin) => {
|
|
88
|
-
if (!pin.rigidGroup) return pin;
|
|
89
|
-
const anchor = resolved.find((p) => p.rigidGroup === pin.rigidGroup);
|
|
90
|
-
return { ...pin, pose: { ...pin.pose, rotation: anchor.pose.rotation, scale: [anchor.pose.scale[0], anchor.pose.scale[0], anchor.pose.scale[0]] } };
|
|
91
|
-
});
|
|
92
|
-
}
|
|
93
|
-
function definedPoses(model) {
|
|
94
|
-
const slots = model.poseSlots.filter((p) => p.slot !== model.activePose);
|
|
95
|
-
return [...slots, ...model.activePose === 0 ? [] : [{ slot: model.activePose, poses: capturePose(model.pins) }]].sort((a, b) => a.slot - b.slot);
|
|
96
|
-
}
|
|
97
|
-
function restPoseSlot(pins) {
|
|
98
|
-
return { slot: 0, poses: pins.map((pin) => ({ id: pin.id, pose: restPoseOf(pin.rest) })) };
|
|
99
|
-
}
|
|
100
|
-
|
|
101
|
-
// src/deformation/pose-timeline.ts
|
|
102
|
-
var MIN_POSE_SECONDS = 0.05;
|
|
103
|
-
var MAX_POSE_SECONDS = 60;
|
|
104
|
-
|
|
105
|
-
// src/deformation/wind.ts
|
|
106
|
-
import { Vector3 as Vector32 } from "three";
|
|
107
|
-
var MAX_WIND_STRENGTH = 4;
|
|
108
|
-
function windProfile(strength) {
|
|
109
|
-
const level = Math.max(0, Math.min(MAX_WIND_STRENGTH, strength));
|
|
110
|
-
const label = level === 0 ? "Off" : level < 0.75 ? "Breeze" : level < 1.5 ? "Windy" : level < 2.5 ? "Strong wind" : level < 3.3 ? "Gale" : "Storm";
|
|
111
|
-
return {
|
|
112
|
-
label,
|
|
113
|
-
load: 30 * level * level / (0.8 + level * level),
|
|
114
|
-
surfaceLoad: 4 * level * level,
|
|
115
|
-
gust: 0.14 + 0.12 * level,
|
|
116
|
-
crosswind: 0.05 + 0.07 * level,
|
|
117
|
-
gustRate: 0.42 + 0.12 * level
|
|
118
|
-
};
|
|
119
|
-
}
|
|
120
|
-
function windAcceleration(seconds, strength, scale, position) {
|
|
121
|
-
if (strength <= 0) return new Vector32();
|
|
122
|
-
const size = Math.max(1e-4, scale);
|
|
123
|
-
const profile = windProfile(strength);
|
|
124
|
-
const along = position[0] / size, lateral = (position[1] * 0.67 + position[2] * 0.33) / size;
|
|
125
|
-
const slow = seconds * profile.gustRate - along * 0.55;
|
|
126
|
-
const fast = seconds * (profile.gustRate * 2.7) - along * 1.4 + lateral * 0.4;
|
|
127
|
-
const gust = Math.max(0.2, 1 + profile.gust * (0.7 * Math.sin(slow) + 0.3 * Math.sin(fast + 1.3)));
|
|
128
|
-
const cross = profile.crosswind * (0.65 * Math.sin(fast + lateral) + 0.35 * Math.sin(slow * 0.73 - lateral * 0.6));
|
|
129
|
-
return new Vector32(1, cross * 0.35, cross).normalize().multiplyScalar(profile.load * size * gust);
|
|
130
|
-
}
|
|
131
|
-
|
|
132
|
-
// src/deformation/joints-json.ts
|
|
133
|
-
function record(value) {
|
|
134
|
-
if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error("Invalid joints JSON object.");
|
|
135
|
-
return value;
|
|
136
|
-
}
|
|
137
|
-
function numbers(value, length) {
|
|
138
|
-
if (!Array.isArray(value) || value.length !== length || !value.every((v) => typeof v === "number" && Number.isFinite(v))) throw new Error("Invalid joint coordinates.");
|
|
139
|
-
return [...value];
|
|
140
|
-
}
|
|
141
|
-
function point(value) {
|
|
142
|
-
const v = numbers(value, 3);
|
|
143
|
-
return [v[0], v[1], v[2]];
|
|
144
|
-
}
|
|
145
|
-
function quaternion(value) {
|
|
146
|
-
const v = numbers(value, 4);
|
|
147
|
-
return [v[0], v[1], v[2], v[3]];
|
|
148
|
-
}
|
|
149
|
-
function validateJoints(value, maximum = MAX_DEFORMATION_PINS) {
|
|
150
|
-
if (!Array.isArray(value) || value.length > maximum) throw new Error(`Joints JSON must contain at most ${maximum} joints.`);
|
|
151
|
-
const ids = /* @__PURE__ */ new Set();
|
|
152
|
-
const pins = value.map((item) => {
|
|
153
|
-
const pin = record(item), pose2 = record(pin.pose);
|
|
154
|
-
if (typeof pin.id !== "string" || !pin.id || ids.has(pin.id)) throw new Error("Joint IDs must be unique non-empty strings.");
|
|
155
|
-
ids.add(pin.id);
|
|
156
|
-
if (typeof pin.independent !== "boolean" || pin.rigidGroup !== null && (typeof pin.rigidGroup !== "string" || !pin.rigidGroup)) throw new Error("Invalid joint membership.");
|
|
157
|
-
if (pin.guide !== void 0 && typeof pin.guide !== "boolean") throw new Error("Invalid guide flag.");
|
|
158
|
-
if (pin.authored !== void 0 && typeof pin.authored !== "boolean") throw new Error("Invalid authored flag.");
|
|
159
|
-
if (pin.ik !== void 0 && typeof pin.ik !== "boolean") throw new Error("Invalid IK flag.");
|
|
160
|
-
if (pin.wiggle !== void 0 && typeof pin.wiggle !== "boolean") throw new Error("Invalid Wiggle flag.");
|
|
161
|
-
if (pin.cloth !== void 0 && typeof pin.cloth !== "boolean") throw new Error("Invalid Cloth flag.");
|
|
162
|
-
if (pin.fur !== void 0 && typeof pin.fur !== "boolean") throw new Error("Invalid Fur flag.");
|
|
163
|
-
if (pin.furDepth !== void 0 && (typeof pin.furDepth !== "number" || !Number.isFinite(pin.furDepth) || pin.furDepth < 0 || pin.furDepth > MAX_FUR_DEPTH)) throw new Error("Invalid Fur depth.");
|
|
164
|
-
const chainRole = pin.chainRole === void 0 ? void 0 : (() => {
|
|
165
|
-
const value2 = record(pin.chainRole);
|
|
166
|
-
if (!IK_CHAIN_KINDS.includes(value2.kind) || !["center", "left", "right"].includes(value2.side) || value2.position !== void 0 && !["front", "hind"].includes(value2.position)) throw new Error("Invalid IK chain role.");
|
|
167
|
-
return { kind: value2.kind, side: value2.side, ...value2.position ? { position: value2.position } : {} };
|
|
168
|
-
})();
|
|
169
|
-
if (Number(Boolean(pin.ik)) + Number(Boolean(pin.wiggle)) + Number(Boolean(pin.cloth)) + Number(Boolean(pin.fur)) > 1) throw new Error("Choose IK, Wiggle, Cloth or Fur.");
|
|
170
|
-
const motion = pin.motion === void 0 ? void 0 : (() => {
|
|
171
|
-
const raw = record(pin.motion), result = { reach: Number(raw.reach), frequency: Number(raw.frequency), damping: Number(raw.damping), massInfluence: raw.massInfluence === void 0 ? DEFAULT_MOTION.massInfluence : Number(raw.massInfluence), strength: raw.strength === void 0 ? DEFAULT_MOTION.strength : Number(raw.strength) };
|
|
172
|
-
for (const key of ["massInfluence", "strength"]) if (raw[key] !== void 0 && typeof raw[key] !== "number") throw new Error("Invalid motion settings.");
|
|
173
|
-
if (typeof raw.reach !== "number" || typeof raw.frequency !== "number" || typeof raw.damping !== "number") throw new Error("Invalid motion settings.");
|
|
174
|
-
validateMotionSettings(result);
|
|
175
|
-
return result;
|
|
176
|
-
})();
|
|
177
|
-
const ikConstraint = pin.ikConstraint === void 0 ? void 0 : (() => {
|
|
178
|
-
const raw = record(pin.ikConstraint);
|
|
179
|
-
const value2 = { mode: raw.mode, axis: raw.axis, min: raw.min, max: raw.max, ...raw.orientation !== void 0 ? { orientation: quaternion(raw.orientation) } : {}, ...raw.maxY !== void 0 ? { maxY: raw.maxY } : {} };
|
|
180
|
-
validateIKConstraint(value2);
|
|
181
|
-
return value2;
|
|
182
|
-
})();
|
|
183
|
-
const ikTarget = pin.ikTarget === void 0 ? void 0 : (() => {
|
|
184
|
-
const raw = record(pin.ikTarget), rotation2 = quaternion(raw.rotation);
|
|
185
|
-
if (Math.abs(Math.hypot(...rotation2) - 1) > 1e-4) throw new Error("Invalid IK target rotation.");
|
|
186
|
-
return { position: point(raw.position), rotation: rotation2 };
|
|
187
|
-
})();
|
|
188
|
-
if (pin.guide && (pin.rigidGroup || pin.independent)) throw new Error("Guides cannot be rigid members or roots.");
|
|
189
|
-
const scale = point(pose2.scale), rotation = quaternion(pose2.rotation);
|
|
190
|
-
if (scale.some((v) => v < 0.01 || v > 100) || Math.abs(Math.hypot(...rotation) - 1) > 1e-4) throw new Error("Invalid joint rotation or scale.");
|
|
191
|
-
return {
|
|
192
|
-
id: pin.id,
|
|
193
|
-
independent: pin.independent,
|
|
194
|
-
rigidGroup: pin.rigidGroup,
|
|
195
|
-
...pin.authored === true ? { authored: true } : {},
|
|
196
|
-
...typeof pin.guide === "boolean" ? { guide: pin.guide } : {},
|
|
197
|
-
...typeof pin.ik === "boolean" ? { ik: pin.ik } : {},
|
|
198
|
-
...ikConstraint ? { ikConstraint } : {},
|
|
199
|
-
...chainRole ? { chainRole } : {},
|
|
200
|
-
...motion ? { motion } : {},
|
|
201
|
-
...ikTarget ? { ikTarget } : {},
|
|
202
|
-
...typeof pin.wiggle === "boolean" ? { wiggle: pin.wiggle } : {},
|
|
203
|
-
...typeof pin.cloth === "boolean" ? { cloth: pin.cloth } : {},
|
|
204
|
-
...typeof pin.fur === "boolean" ? { fur: pin.fur } : {},
|
|
205
|
-
...pin.furDepth !== void 0 ? { furDepth: pin.furDepth } : {},
|
|
206
|
-
rest: point(pin.rest),
|
|
207
|
-
pose: { position: point(pose2.position), rotation, scale }
|
|
208
|
-
};
|
|
209
|
-
});
|
|
210
|
-
for (const pin of pins) if (pin.rigidGroup) {
|
|
211
|
-
const anchor = pins.find((other) => other.rigidGroup === pin.rigidGroup);
|
|
212
|
-
const dot = pin.pose.rotation.reduce((sum, v, i) => sum + v * anchor.pose.rotation[i], 0);
|
|
213
|
-
if (pin.pose.scale.some((v) => Math.abs(v - anchor.pose.scale[0]) > 1e-5) || 1 - Math.abs(dot) > 1e-5) throw new Error("Rigid joints must share rotation and uniform scale.");
|
|
214
|
-
}
|
|
215
|
-
return pins;
|
|
216
|
-
}
|
|
217
|
-
function validatePoseTimes(value) {
|
|
218
|
-
if (!Array.isArray(value) || value.length > POSE_SLOTS) throw new Error("Invalid pose times.");
|
|
219
|
-
const slots = /* @__PURE__ */ new Set();
|
|
220
|
-
return value.map((item) => {
|
|
221
|
-
const entry = record(item);
|
|
222
|
-
if (!Number.isInteger(entry.slot) || entry.slot < 0 || entry.slot > POSE_SLOTS || slots.has(entry.slot)) throw new Error("Invalid pose time slot.");
|
|
223
|
-
slots.add(entry.slot);
|
|
224
|
-
if (typeof entry.seconds !== "number" || !Number.isFinite(entry.seconds) || entry.seconds < MIN_POSE_SECONDS || entry.seconds > MAX_POSE_SECONDS) throw new Error("Invalid pose time.");
|
|
225
|
-
return { slot: entry.slot, seconds: entry.seconds };
|
|
226
|
-
}).sort((a, b) => a.slot - b.slot);
|
|
227
|
-
}
|
|
228
|
-
function validateRig(value, maximum = MAX_DEFORMATION_PINS, parents = /* @__PURE__ */ new Map()) {
|
|
229
|
-
const pins = validateJoints(value.pins, maximum);
|
|
230
|
-
if (value.windStrength !== void 0 && (!Number.isFinite(value.windStrength) || value.windStrength < 0 || value.windStrength > MAX_WIND_STRENGTH)) throw new Error("Invalid wind strength.");
|
|
231
|
-
if (!Number.isInteger(value.activePose) || value.activePose < 0 || value.activePose > POSE_SLOTS || !Array.isArray(value.poseSlots) || value.poseSlots.length > POSE_SLOTS) throw new Error("Invalid pose slots.");
|
|
232
|
-
const slots = /* @__PURE__ */ new Set(), ids = new Set(pins.map((p) => p.id));
|
|
233
|
-
const poseSlots = value.poseSlots.map((slot) => {
|
|
234
|
-
if (!slot || !Number.isInteger(slot.slot) || slot.slot < 1 || slot.slot > POSE_SLOTS || slots.has(slot.slot) || !Array.isArray(slot.poses)) throw new Error("Invalid pose slot.");
|
|
235
|
-
slots.add(slot.slot);
|
|
236
|
-
const pinIds = /* @__PURE__ */ new Set();
|
|
237
|
-
for (const p of slot.poses) {
|
|
238
|
-
if (!p || !ids.has(p.id) || pinIds.has(p.id)) throw new Error("Invalid pose pin.");
|
|
239
|
-
pinIds.add(p.id);
|
|
240
|
-
}
|
|
241
|
-
return { slot: slot.slot, poses: capturePose(validateJoints(resolvePose(pins, slot, parents), maximum)) };
|
|
242
|
-
}).filter((slot) => slot.slot !== value.activePose);
|
|
243
|
-
return { pins, activePose: value.activePose, poseSlots, poseTimes: validatePoseTimes(value.poseTimes ?? []), ...value.windStrength !== void 0 ? { windStrength: value.windStrength } : {} };
|
|
244
|
-
}
|
|
245
|
-
|
|
246
|
-
// src/deformation/pin-ik.ts
|
|
247
|
-
import { Goal, Joint, Link, Solver } from "closed-chain-ik/core";
|
|
248
|
-
import { Euler, Matrix4, Quaternion as Quaternion2, Vector3 as Vector33 } from "three";
|
|
249
|
-
var POSE_CONTINUITY_WEIGHT = 1e-4;
|
|
250
|
-
function articulatedNodes(pins, parents) {
|
|
251
|
-
const nodes = /* @__PURE__ */ new Set();
|
|
252
|
-
for (const pin of pins) if (!pin.guide) {
|
|
253
|
-
let id = pin.id;
|
|
254
|
-
while (id && !nodes.has(id)) {
|
|
255
|
-
nodes.add(id);
|
|
256
|
-
id = parents.get(id);
|
|
257
|
-
}
|
|
258
|
-
}
|
|
259
|
-
return nodes;
|
|
260
|
-
}
|
|
261
|
-
function ikChain(pins, parents, id, mass = /* @__PURE__ */ new Map()) {
|
|
262
|
-
const byId = new Map(pins.map((pin2) => [pin2.id, pin2]));
|
|
263
|
-
const element = (pin2) => pin2.rigidGroup ?? pin2.id;
|
|
264
|
-
const articulated = articulatedNodes(pins, parents);
|
|
265
|
-
const children = /* @__PURE__ */ new Map();
|
|
266
|
-
const supportLength = /* @__PURE__ */ new Map();
|
|
267
|
-
for (const pin2 of pins) {
|
|
268
|
-
if (!articulated.has(pin2.id)) continue;
|
|
269
|
-
const parent = byId.get(parents.get(pin2.id) ?? "");
|
|
270
|
-
if (!parent) continue;
|
|
271
|
-
const length = Math.hypot(...pin2.rest.map((x, i) => x - parent.rest[i])) * 0.5;
|
|
272
|
-
supportLength.set(pin2.id, (supportLength.get(pin2.id) ?? 0) + length);
|
|
273
|
-
supportLength.set(parent.id, (supportLength.get(parent.id) ?? 0) + length);
|
|
274
|
-
const set = children.get(element(parent)) ?? /* @__PURE__ */ new Set();
|
|
275
|
-
set.add(element(pin2));
|
|
276
|
-
children.set(element(parent), set);
|
|
277
|
-
}
|
|
278
|
-
const chain = [], seen = /* @__PURE__ */ new Set();
|
|
279
|
-
let pin = byId.get(id);
|
|
280
|
-
const reach = pin?.motion?.reach ?? DEFAULT_MOTION.reach;
|
|
281
|
-
let automatic;
|
|
282
|
-
const density = (p) => mass.has(p.id) ? mass.get(p.id) / Math.max(supportLength.get(p.id) ?? 0, 1e-12) : void 0;
|
|
283
|
-
while (pin && !seen.has(element(pin))) {
|
|
284
|
-
chain.unshift(pin);
|
|
285
|
-
seen.add(element(pin));
|
|
286
|
-
if (pin.independent) break;
|
|
287
|
-
const parent = byId.get(parents.get(pin.id) ?? "");
|
|
288
|
-
if (!parent) break;
|
|
289
|
-
if (!automatic && ((children.get(element(parent))?.size ?? 0) > 1 || !pin.guide && !parent.guide && (density(parent) ?? 0) > 8 * Math.max(density(pin) ?? Infinity, 1e-12))) automatic = parent.id;
|
|
290
|
-
pin = parent;
|
|
291
|
-
}
|
|
292
|
-
if (chain.length < 2) return chain;
|
|
293
|
-
const distance = new Float64Array(chain.length);
|
|
294
|
-
for (let i = chain.length - 2; i >= 0; i--) distance[i] = distance[i + 1] + Math.hypot(...chain[i].rest.map((x, k) => x - chain[i + 1].rest[k]));
|
|
295
|
-
const boundary = automatic ? chain.findIndex((p) => p.id === automatic) : -1;
|
|
296
|
-
const automaticDistance = distance[Math.max(0, boundary)];
|
|
297
|
-
const budget = reach <= 0.5 ? automaticDistance * reach * 2 : automaticDistance + (distance[0] - automaticDistance) * (reach - 0.5) * 2;
|
|
298
|
-
const first = reach <= 0.5 && boundary >= 0 ? Math.min(boundary + 1, chain.length - 2) : 0;
|
|
299
|
-
let start = chain.length - 2;
|
|
300
|
-
for (let i = start - 1; i >= first; i--) if (Math.abs(distance[i] - budget) < Math.abs(distance[start] - budget)) start = i;
|
|
301
|
-
if (reach === 1) start = 0;
|
|
302
|
-
return chain.slice(start);
|
|
303
|
-
}
|
|
304
|
-
function solveLocalPinIK(pins, parents, goal, mass, floor = -Infinity) {
|
|
305
|
-
const chain = ikChain(pins, parents, goal.id, mass), key = (p) => p.rigidGroup ?? p.id;
|
|
306
|
-
const keys = new Set(chain.map(key)), byId = new Map(pins.map((p) => [p.id, p]));
|
|
307
|
-
const articulated = articulatedNodes(pins, parents);
|
|
308
|
-
let boundary = -1;
|
|
309
|
-
for (let i = 0; i < chain.length - 1; i++) if (chain[i].independent || pins.some((p) => {
|
|
310
|
-
if (!articulated.has(p.id)) return false;
|
|
311
|
-
const parent = byId.get(parents.get(p.id) ?? "");
|
|
312
|
-
return parent && key(parent) === key(chain[i]) && !keys.has(key(p));
|
|
313
|
-
})) boundary = i;
|
|
314
|
-
const shared = boundary >= 0 && pins.some((p) => {
|
|
315
|
-
if (!articulated.has(p.id)) return false;
|
|
316
|
-
const parent = byId.get(parents.get(p.id) ?? "");
|
|
317
|
-
return parent && key(parent) === key(chain[boundary]) && !keys.has(key(p));
|
|
318
|
-
});
|
|
319
|
-
const fixed = new Set(chain.slice(0, shared ? boundary + 1 : Math.max(0, boundary)).flatMap((p) => pins.filter((q) => key(q) === key(p)).map((q) => q.id)));
|
|
320
|
-
const moving = new Set(chain.slice(boundary + 1).map(key));
|
|
321
|
-
for (let added = true; added; ) {
|
|
322
|
-
added = false;
|
|
323
|
-
for (const p of pins) {
|
|
324
|
-
const parent = byId.get(parents.get(p.id) ?? "");
|
|
325
|
-
if (parent && moving.has(key(parent)) && !moving.has(key(p))) {
|
|
326
|
-
moving.add(key(p));
|
|
327
|
-
added = true;
|
|
328
|
-
}
|
|
329
|
-
}
|
|
330
|
-
}
|
|
331
|
-
const retained = new Set(boundary >= 0 ? [key(chain[boundary])] : []);
|
|
332
|
-
return solvePinIKGoals(pins, parents, [goal], mass, fixed, retained, floor).filter((p) => moving.has(key(byId.get(p.id))));
|
|
333
|
-
}
|
|
334
|
-
function solvePlantedPinIKGoals(pins, parents, goals, mass, fixed = /* @__PURE__ */ new Set(), floor = -Infinity) {
|
|
335
|
-
if (!goals.length) return [];
|
|
336
|
-
const edits = /* @__PURE__ */ new Map();
|
|
337
|
-
let independent = true;
|
|
338
|
-
for (const goal of goals) {
|
|
339
|
-
const limb = solveLocalPinIK(pins, parents, goal, mass, floor);
|
|
340
|
-
for (const edit of limb) {
|
|
341
|
-
if (fixed.has(edit.id) || edits.has(edit.id)) {
|
|
342
|
-
independent = false;
|
|
343
|
-
break;
|
|
344
|
-
}
|
|
345
|
-
edits.set(edit.id, edit);
|
|
346
|
-
}
|
|
347
|
-
if (!independent) break;
|
|
348
|
-
}
|
|
349
|
-
return independent ? [...edits.values()] : solvePinIKGoals(pins, parents, goals, mass, fixed, /* @__PURE__ */ new Set(), floor);
|
|
350
|
-
}
|
|
351
|
-
function solvePinIKGoals(pins, parents, goals, mass, fixed = /* @__PURE__ */ new Set(), retained = /* @__PURE__ */ new Set(), floor = -Infinity, poleChains = /* @__PURE__ */ new Map()) {
|
|
352
|
-
if (!goals.length) return [];
|
|
353
|
-
const byId = new Map(pins.map((p) => [p.id, p])), key = (p) => p.rigidGroup ?? p.id;
|
|
354
|
-
const groups = /* @__PURE__ */ new Map();
|
|
355
|
-
for (const pin of pins) {
|
|
356
|
-
const group = groups.get(key(pin)) ?? [];
|
|
357
|
-
group.push(pin);
|
|
358
|
-
groups.set(key(pin), group);
|
|
359
|
-
}
|
|
360
|
-
const active = /* @__PURE__ */ new Set(), roots = /* @__PURE__ */ new Set();
|
|
361
|
-
const bendSeeds = /* @__PURE__ */ new Map();
|
|
362
|
-
let size = 0;
|
|
363
|
-
for (const goal of goals) {
|
|
364
|
-
const chain = ikChain(pins, parents, goal.id, mass);
|
|
365
|
-
if (chain.length < 2) throw new Error("IK needs a parent chain. Add a parent pin or remove Independent from this endpoint.");
|
|
366
|
-
for (const p of chain) active.add(key(p));
|
|
367
|
-
roots.add(key(chain[0]));
|
|
368
|
-
const start = new Vector33().fromArray(chain[0].pose.position), direction = new Vector33().fromArray(chain.at(-1).pose.position).sub(start);
|
|
369
|
-
const span = direction.length();
|
|
370
|
-
if (span > 1e-8 && new Vector33().fromArray(goal.position).distanceTo(start) < span * (1 - 1e-6)) {
|
|
371
|
-
direction.divideScalar(span);
|
|
372
|
-
const straight = chain.every((p) => new Vector33().fromArray(p.pose.position).sub(start).cross(direction).lengthSq() < span * span * 1e-12);
|
|
373
|
-
const candidate = straight ? chain.slice(1, -1).find((p) => !groups.get(key(p)).some((q) => fixed.has(q.id)) && ["free", "cone"].includes((p.ikConstraint ?? DEFAULT_IK_CONSTRAINT).mode)) : void 0;
|
|
374
|
-
if (candidate) {
|
|
375
|
-
const axis = new Vector33().crossVectors(direction, new Vector33().fromArray(goal.position).sub(start));
|
|
376
|
-
if (axis.lengthSq() < 1e-12) {
|
|
377
|
-
const components = direction.toArray().map(Math.abs);
|
|
378
|
-
axis.setComponent(components.indexOf(Math.min(...components)), 1).addScaledVector(direction, -axis.dot(direction));
|
|
379
|
-
}
|
|
380
|
-
bendSeeds.set(key(candidate), axis.normalize());
|
|
381
|
-
}
|
|
382
|
-
}
|
|
383
|
-
size = Math.max(size, chain.slice(1).reduce((sum, p, i) => sum + new Vector33().fromArray(p.pose.position).distanceTo(new Vector33().fromArray(chain[i].pose.position)), 0));
|
|
384
|
-
}
|
|
385
|
-
if (size < 1e-8) throw new Error("IK chain has no length. Separate its rest pins first.");
|
|
386
|
-
const parentGroup = /* @__PURE__ */ new Map();
|
|
387
|
-
for (const [id, members] of groups) {
|
|
388
|
-
const parent = members.map((p) => byId.get(parents.get(p.id) ?? "")).find((p) => p && key(p) !== id);
|
|
389
|
-
if (parent) parentGroup.set(id, key(parent));
|
|
390
|
-
}
|
|
391
|
-
const affected = new Set(active);
|
|
392
|
-
for (let changed = true; changed; ) {
|
|
393
|
-
changed = false;
|
|
394
|
-
for (const [id, parent] of parentGroup) if (affected.has(parent) && !affected.has(id)) {
|
|
395
|
-
affected.add(id);
|
|
396
|
-
changed = true;
|
|
397
|
-
}
|
|
398
|
-
}
|
|
399
|
-
const unchanged = goals.every((g) => {
|
|
400
|
-
const p = byId.get(g.id);
|
|
401
|
-
return new Vector33().fromArray(g.position).distanceToSquared(new Vector33().fromArray(p.pose.position)) < 1e-20 && new Quaternion2().fromArray(g.rotation).angleTo(new Quaternion2().fromArray(p.pose.rotation)) < 1e-10;
|
|
402
|
-
});
|
|
403
|
-
if (unchanged && !pins.some((p) => p.ikConstraint && p.ikConstraint.mode !== "free")) return pins.filter((p) => affected.has(key(p))).map((p) => ({ id: p.id, pose: p.pose }));
|
|
404
|
-
const origin = new Vector33().fromArray(byId.get(goals[0].id).pose.position);
|
|
405
|
-
const frames = /* @__PURE__ */ new Map(), forest = [], building = /* @__PURE__ */ new Set();
|
|
406
|
-
const coneJoints = /* @__PURE__ */ new Map();
|
|
407
|
-
const freeJoints = /* @__PURE__ */ new Map();
|
|
408
|
-
const branchJoints = /* @__PURE__ */ new Map();
|
|
409
|
-
const build = (id) => {
|
|
410
|
-
const cached = frames.get(id);
|
|
411
|
-
if (cached) return cached;
|
|
412
|
-
if (building.has(id)) throw new Error("Cyclic IK hierarchy.");
|
|
413
|
-
building.add(id);
|
|
414
|
-
const pin = groups.get(id)[0], parentId = parentGroup.get(id), parent = parentId ? groups.get(parentId)[0] : void 0;
|
|
415
|
-
const parentFrame = parentId ? build(parentId) : new Link();
|
|
416
|
-
let attachment = parentFrame;
|
|
417
|
-
if (parentId && active.has(id) && !groups.get(id).some((p) => fixed.has(p.id)) && groups.get(parentId).some((p) => fixed.has(p.id))) {
|
|
418
|
-
const pivot = new Joint();
|
|
419
|
-
pivot.setDoF(3, 4, 5);
|
|
420
|
-
pivot.setDoFValues(0, 0, 0);
|
|
421
|
-
pivot.setRestPoseValues(0, 0, 0);
|
|
422
|
-
parentFrame.addChild(pivot);
|
|
423
|
-
attachment = new Link();
|
|
424
|
-
pivot.addChild(attachment);
|
|
425
|
-
branchJoints.set(id, { joint: pivot, frame: attachment });
|
|
426
|
-
}
|
|
427
|
-
const parentRotation = parent ? new Quaternion2().fromArray(parent.pose.rotation) : new Quaternion2();
|
|
428
|
-
const position = new Vector33().fromArray(pin.pose.position).sub(parent ? new Vector33().fromArray(parent.pose.position) : origin).applyQuaternion(parentRotation.clone().invert()).divideScalar(size);
|
|
429
|
-
const relative = parentRotation.clone().invert().multiply(new Quaternion2().fromArray(pin.pose.rotation)).normalize();
|
|
430
|
-
const joint = new Joint();
|
|
431
|
-
joint.setPosition(position.x, position.y, position.z);
|
|
432
|
-
attachment.addChild(joint);
|
|
433
|
-
const link = new Link(), constraint = pin.ikConstraint ?? DEFAULT_IK_CONSTRAINT;
|
|
434
|
-
const movable = active.has(id) && !groups.get(id).some((p) => fixed.has(p.id));
|
|
435
|
-
if (!movable || constraint.mode === "locked") joint.setQuaternion(...relative.toArray());
|
|
436
|
-
else if (constraint.mode === "hinge") {
|
|
437
|
-
let axis = new Vector33();
|
|
438
|
-
if (constraint.axis !== "auto") axis.setComponent(["x", "y", "z"].indexOf(constraint.axis), 1);
|
|
439
|
-
else {
|
|
440
|
-
const child = pins.find((p) => parents.get(p.id) === pin.id && active.has(key(p)));
|
|
441
|
-
if (parent && child) axis.crossVectors(new Vector33().fromArray(pin.rest).sub(new Vector33().fromArray(parent.rest)), new Vector33().fromArray(child.rest).sub(new Vector33().fromArray(pin.rest)));
|
|
442
|
-
if (axis.lengthSq() < 1e-10) {
|
|
443
|
-
const direction = child ? new Vector33().fromArray(child.rest).sub(new Vector33().fromArray(pin.rest)).normalize() : new Vector33(0, 1, 0);
|
|
444
|
-
axis.crossVectors(direction, Math.abs(direction.z) < 0.9 ? new Vector33(0, 0, 1) : new Vector33(1, 0, 0));
|
|
445
|
-
}
|
|
446
|
-
axis.normalize();
|
|
447
|
-
}
|
|
448
|
-
const basis = new Quaternion2().setFromUnitVectors(new Vector33(0, 0, 1), axis);
|
|
449
|
-
joint.setQuaternion(...basis.toArray());
|
|
450
|
-
link.setQuaternion(...basis.clone().invert().toArray());
|
|
451
|
-
joint.setDoF(5);
|
|
452
|
-
joint.setMinLimits(constraint.min * Math.PI / 180);
|
|
453
|
-
joint.setMaxLimits(constraint.max * Math.PI / 180);
|
|
454
|
-
const twist = 2 * Math.atan2(new Vector33(relative.x, relative.y, relative.z).dot(axis), relative.w);
|
|
455
|
-
joint.setDoFValues(Math.atan2(Math.sin(twist), Math.cos(twist)));
|
|
456
|
-
joint.setRestPoseValues(0);
|
|
457
|
-
} else {
|
|
458
|
-
if (constraint.mode === "cone") coneJoints.set(id, joint);
|
|
459
|
-
else freeJoints.set(id, joint);
|
|
460
|
-
joint.setDoF(3, 4, 5);
|
|
461
|
-
const euler = new Euler().setFromQuaternion(relative, "ZYX");
|
|
462
|
-
joint.setDoFValues(euler.x, euler.y, euler.z);
|
|
463
|
-
joint.setRestPoseValues(euler.x, euler.y, euler.z);
|
|
464
|
-
const seed = bendSeeds.get(id);
|
|
465
|
-
if (seed && !roots.has(id) && !goals.some((g) => key(byId.get(g.id)) === id)) {
|
|
466
|
-
const axis = seed.clone().applyQuaternion(parentRotation.clone().invert());
|
|
467
|
-
const seeded = new Euler().setFromQuaternion(new Quaternion2().setFromAxisAngle(axis, 0.03).multiply(relative), "ZYX");
|
|
468
|
-
joint.setDoFValues(seeded.x, seeded.y, seeded.z);
|
|
469
|
-
}
|
|
470
|
-
}
|
|
471
|
-
joint.addChild(link);
|
|
472
|
-
frames.set(id, link);
|
|
473
|
-
building.delete(id);
|
|
474
|
-
if (!parentId) forest.push(parentFrame);
|
|
475
|
-
return link;
|
|
476
|
-
};
|
|
477
|
-
for (const id of groups.keys()) build(id);
|
|
478
|
-
const limitRotation = (id, rotation, parentRotation) => {
|
|
479
|
-
const pin = groups.get(id)[0];
|
|
480
|
-
if (pin.ikConstraint?.mode !== "cone") return rotation;
|
|
481
|
-
const parentId = parentGroup.get(id), parent = parentId ? groups.get(parentId)[0] : void 0;
|
|
482
|
-
const child = pins.find((p) => parents.get(p.id) === pin.id);
|
|
483
|
-
if (retained.has(id) && child && !active.has(key(child))) return rotation;
|
|
484
|
-
const axis = child ? new Vector33().fromArray(child.rest).sub(new Vector33().fromArray(pin.rest)) : parent ? new Vector33().fromArray(pin.rest).sub(new Vector33().fromArray(parent.rest)) : new Vector33(0, 1, 0);
|
|
485
|
-
if (axis.lengthSq() < 1e-12) axis.set(0, 1, 0);
|
|
486
|
-
const movingAxis = child ? new Vector33().fromArray(child.pose.position).sub(new Vector33().fromArray(pin.pose.position)).applyQuaternion(new Quaternion2().fromArray(pin.pose.rotation).invert()) : axis;
|
|
487
|
-
if (movingAxis.lengthSq() < 1e-12) movingAxis.copy(axis);
|
|
488
|
-
const reference = parentId && retained.has(parentId) ? new Quaternion2().fromArray(parent.pose.rotation) : parentRotation;
|
|
489
|
-
const relative = reference.clone().invert().multiply(parentRotation).multiply(rotation);
|
|
490
|
-
return parentRotation.clone().invert().multiply(reference).multiply(constrainCone(relative, axis, pin.ikConstraint, movingAxis));
|
|
491
|
-
};
|
|
492
|
-
const priorRotations = new Map([...frames.values(), ...[...branchJoints.values()].map((branch) => branch.frame)].map((frame) => {
|
|
493
|
-
frame.updateMatrixWorld();
|
|
494
|
-
return [frame, new Quaternion2().setFromRotationMatrix(new Matrix4().fromArray(frame.matrixWorld))];
|
|
495
|
-
}));
|
|
496
|
-
const closures = [];
|
|
497
|
-
for (const target of goals) {
|
|
498
|
-
const pin = byId.get(target.id), anchor = groups.get(key(pin))[0];
|
|
499
|
-
const offset = new Vector33().fromArray(pin.pose.position).sub(new Vector33().fromArray(anchor.pose.position)).applyQuaternion(new Quaternion2().fromArray(anchor.pose.rotation).invert()).divideScalar(size);
|
|
500
|
-
const attachment = new Joint();
|
|
501
|
-
attachment.setPosition(...offset.toArray());
|
|
502
|
-
frames.get(key(pin)).addChild(attachment);
|
|
503
|
-
const tip = new Link();
|
|
504
|
-
attachment.addChild(tip);
|
|
505
|
-
const goal = new Goal();
|
|
506
|
-
const freeEndpoint = groups.get(key(pin)).length === 1 && (!pin.ikConstraint || pin.ikConstraint.mode === "free");
|
|
507
|
-
if (freeEndpoint) goal.setGoalDoF(0, 1, 2);
|
|
508
|
-
else goal.setGoalDoF(0, 1, 2, 3, 4, 5);
|
|
509
|
-
goal.makeClosure(tip);
|
|
510
|
-
const requested = new Vector33().fromArray(target.position);
|
|
511
|
-
if (goals.length === 1 && freeEndpoint) {
|
|
512
|
-
const chain = ikChain(pins, parents, target.id, mass);
|
|
513
|
-
const first = chain.findIndex((p) => !groups.get(key(p)).some((q) => fixed.has(q.id)) && (p.ikConstraint ?? DEFAULT_IK_CONSTRAINT).mode !== "locked");
|
|
514
|
-
const moving = first < 0 ? [] : chain.slice(branchJoints.has(key(chain[first])) ? Math.max(0, first - 1) : first);
|
|
515
|
-
if (moving.length > 1 && moving.every((p, i) => i === 0 && branchJoints.has(key(moving[1])) || !fixed.has(p.id) && groups.get(key(p)).length === 1 && (p.ikConstraint ?? DEFAULT_IK_CONSTRAINT).mode === "free")) {
|
|
516
|
-
const pivot = new Vector33().fromArray(moving[0].pose.position);
|
|
517
|
-
const lengths = moving.slice(1).map((p, i) => new Vector33().fromArray(p.pose.position).distanceTo(new Vector33().fromArray(moving[i].pose.position)));
|
|
518
|
-
const outer = lengths.reduce((a, b) => a + b, 0), inner = Math.max(0, 2 * Math.max(...lengths) - outer), delta = requested.clone().sub(pivot), distance = delta.length();
|
|
519
|
-
if (distance < inner || distance > outer) {
|
|
520
|
-
if (distance < 1e-12) delta.fromArray(moving.at(-1).pose.position).sub(pivot);
|
|
521
|
-
if (delta.lengthSq() > 1e-24) requested.copy(pivot).add(delta.setLength(Math.max(inner, Math.min(outer, distance))));
|
|
522
|
-
}
|
|
523
|
-
if (moving.length === 2) {
|
|
524
|
-
const before = new Vector33().fromArray(moving[1].pose.position).sub(pivot), after = requested.clone().sub(pivot);
|
|
525
|
-
if (before.lengthSq() > 1e-24 && after.lengthSq() > 1e-24) {
|
|
526
|
-
const branch = branchJoints.get(key(moving[1])), parent = branch ? moving[0] : byId.get(parents.get(moving[0].id) ?? "");
|
|
527
|
-
const local = parent ? new Quaternion2().fromArray(parent.pose.rotation).invert() : new Quaternion2();
|
|
528
|
-
local.multiply(new Quaternion2().setFromUnitVectors(before.normalize(), after.normalize())).multiply(new Quaternion2().fromArray(moving[0].pose.rotation));
|
|
529
|
-
const euler = new Euler().setFromQuaternion(local, "ZYX");
|
|
530
|
-
(branch?.joint ?? freeJoints.get(key(moving[0]))).setDoFValues(euler.x, euler.y, euler.z);
|
|
531
|
-
}
|
|
532
|
-
}
|
|
533
|
-
}
|
|
534
|
-
}
|
|
535
|
-
goal.setPosition(...requested.sub(origin).divideScalar(size).toArray());
|
|
536
|
-
goal.setQuaternion(...target.rotation);
|
|
537
|
-
closures.push(goal);
|
|
538
|
-
}
|
|
539
|
-
let analytic = false;
|
|
540
|
-
if (goals.length === 1) {
|
|
541
|
-
const goal = goals[0], chain = ikChain(pins, parents, goal.id, mass);
|
|
542
|
-
const first = chain.findIndex((p, i) => coneJoints.has(key(p)) || freeJoints.has(key(p)) || i + 1 < chain.length && branchJoints.has(key(chain[i + 1])));
|
|
543
|
-
const limb = first < 0 ? [] : chain.slice(first), tipPin = byId.get(goal.id);
|
|
544
|
-
if (limb.length === 3 && limb.every((p) => groups.get(key(p)).length === 1) && limb.slice(0, 2).every((p, i) => coneJoints.has(key(p)) || freeJoints.has(key(p)) || branchJoints.has(key(limb[i + 1]))) && (!tipPin.ikConstraint || tipPin.ikConstraint.mode === "free")) {
|
|
545
|
-
const world = (p) => {
|
|
546
|
-
const frame = frames.get(key(p));
|
|
547
|
-
frame.updateMatrixWorld();
|
|
548
|
-
return new Matrix4().fromArray(frame.matrixWorld);
|
|
549
|
-
};
|
|
550
|
-
const matrices = limb.map(world), points = matrices.map((m) => new Vector33().setFromMatrixPosition(m));
|
|
551
|
-
const [base, knee, tip] = points, a = base.distanceTo(knee), b = knee.distanceTo(tip);
|
|
552
|
-
const direction = new Vector33().fromArray(closures[0].position).sub(base);
|
|
553
|
-
if (a > 1e-10 && b > 1e-10 && direction.lengthSq() > 1e-20) {
|
|
554
|
-
const distance = Math.max(Math.abs(a - b) + 1e-9, Math.min(a + b - 1e-9, direction.length()));
|
|
555
|
-
direction.normalize();
|
|
556
|
-
const oldAxis = tip.clone().sub(base).normalize();
|
|
557
|
-
const bend = knee.clone().sub(base).addScaledVector(oldAxis, -knee.clone().sub(base).dot(oldAxis));
|
|
558
|
-
bend.applyQuaternion(new Quaternion2().setFromUnitVectors(oldAxis, direction));
|
|
559
|
-
if (bend.lengthSq() < 1e-16) {
|
|
560
|
-
bend.fromArray(limb[1].rest).sub(new Vector33().fromArray(limb[0].rest));
|
|
561
|
-
const restAxis = new Vector33().fromArray(limb[2].rest).sub(new Vector33().fromArray(limb[0].rest)).normalize();
|
|
562
|
-
bend.addScaledVector(restAxis, -bend.dot(restAxis)).applyQuaternion(new Quaternion2().setFromRotationMatrix(matrices[0]));
|
|
563
|
-
bend.addScaledVector(direction, -bend.dot(direction));
|
|
564
|
-
}
|
|
565
|
-
if (bend.lengthSq() < 1e-16) {
|
|
566
|
-
bend.set(Math.abs(direction.x) < 0.8 ? 1 : 0, Math.abs(direction.x) < 0.8 ? 0 : 1, 0);
|
|
567
|
-
bend.addScaledVector(direction, -bend.dot(direction));
|
|
568
|
-
}
|
|
569
|
-
const along = (a * a - b * b + distance * distance) / (2 * distance);
|
|
570
|
-
const desiredKnee = base.clone().addScaledVector(direction, along).addScaledVector(bend.normalize(), Math.sqrt(Math.max(0, a * a - along * along)));
|
|
571
|
-
const desiredTip = base.clone().addScaledVector(direction, distance);
|
|
572
|
-
for (const [i, end] of [desiredKnee, desiredTip].entries()) {
|
|
573
|
-
const pin = limb[i], branch = branchJoints.get(key(limb[i + 1])), frame = branch?.frame ?? frames.get(key(pin));
|
|
574
|
-
frame.updateMatrixWorld();
|
|
575
|
-
const matrix3 = new Matrix4().fromArray(frame.matrixWorld), pivot = new Vector33().setFromMatrixPosition(matrix3);
|
|
576
|
-
const before = new Vector33().setFromMatrixPosition(world(limb[i + 1])).sub(pivot), after = end.clone().sub(pivot);
|
|
577
|
-
const parentId = parentGroup.get(key(pin)), parentFrame = branch ? frames.get(key(pin)) : branchJoints.get(key(pin))?.frame ?? (parentId ? frames.get(parentId) : void 0);
|
|
578
|
-
parentFrame?.updateMatrixWorld();
|
|
579
|
-
const parentRotation = parentFrame ? new Quaternion2().setFromRotationMatrix(new Matrix4().fromArray(parentFrame.matrixWorld)) : new Quaternion2();
|
|
580
|
-
const rotation = parentRotation.invert().multiply(new Quaternion2().setFromUnitVectors(before.normalize(), after.normalize())).multiply(new Quaternion2().setFromRotationMatrix(matrix3));
|
|
581
|
-
const euler = new Euler().setFromQuaternion(rotation, "ZYX");
|
|
582
|
-
(branch?.joint ?? coneJoints.get(key(pin)) ?? freeJoints.get(key(pin))).setDoFValues(euler.x, euler.y, euler.z);
|
|
583
|
-
}
|
|
584
|
-
analytic = true;
|
|
585
|
-
}
|
|
586
|
-
}
|
|
587
|
-
}
|
|
588
|
-
const positionOnlyGoal = goals.length === 1 && groups.get(key(byId.get(goals[0].id))).length === 1 && (!byId.get(goals[0].id).ikConstraint || byId.get(goals[0].id).ikConstraint.mode === "free");
|
|
589
|
-
const positionOnlyGoals = goals.every((goal) => groups.get(key(byId.get(goal.id))).length === 1 && (!byId.get(goal.id).ikConstraint || byId.get(goal.id).ikConstraint.mode === "free"));
|
|
590
|
-
if (!analytic && !positionOnlyGoal && !positionOnlyGoals) {
|
|
591
|
-
const solver = new Solver([...forest, ...closures]);
|
|
592
|
-
solver.useSVD = true;
|
|
593
|
-
solver.maxIterations = 48;
|
|
594
|
-
solver.restPoseFactor = 1e-3;
|
|
595
|
-
solver.translationConvergeThreshold = 1e-6;
|
|
596
|
-
solver.rotationConvergeThreshold = 1e-6;
|
|
597
|
-
solver.translationErrorClamp = 0.2;
|
|
598
|
-
solver.solve();
|
|
599
|
-
}
|
|
600
|
-
const projectCones = () => {
|
|
601
|
-
for (const [id, joint] of coneJoints) {
|
|
602
|
-
const parentId = parentGroup.get(id), frame = frames.get(id);
|
|
603
|
-
frame.updateMatrixWorld();
|
|
604
|
-
const parentFrame = branchJoints.get(id)?.frame ?? (parentId ? frames.get(parentId) : void 0);
|
|
605
|
-
const parentRotation = parentFrame ? new Quaternion2().setFromRotationMatrix(new Matrix4().fromArray(parentFrame.matrixWorld)) : new Quaternion2();
|
|
606
|
-
const relative = parentRotation.clone().invert().multiply(new Quaternion2().setFromRotationMatrix(new Matrix4().fromArray(frame.matrixWorld)));
|
|
607
|
-
const limited = limitRotation(id, relative, parentRotation), euler = new Euler().setFromQuaternion(limited, "ZYX");
|
|
608
|
-
joint.setDoFValues(euler.x, euler.y, euler.z);
|
|
609
|
-
frame.updateMatrixWorld();
|
|
610
|
-
}
|
|
611
|
-
};
|
|
612
|
-
if (goals.length === 1 || !positionOnlyGoals) projectCones();
|
|
613
|
-
if (goals.length > 1 && positionOnlyGoals) {
|
|
614
|
-
const world = (frame) => {
|
|
615
|
-
frame.updateMatrixWorld();
|
|
616
|
-
return new Matrix4().fromArray(frame.matrixWorld);
|
|
617
|
-
};
|
|
618
|
-
const tips = goals.map((goal) => ({ goal, frame: frames.get(key(byId.get(goal.id))), desired: new Vector33().fromArray(closures[goals.indexOf(goal)].position), chain: ikChain(pins, parents, goal.id, mass).slice(0, -1).reverse() }));
|
|
619
|
-
const poles = tips.flatMap((tip) => {
|
|
620
|
-
const chain = poleChains.get(tip.goal.id);
|
|
621
|
-
if (!chain || chain.length < 3) return [];
|
|
622
|
-
const base = chain[0], knee = chain[Math.floor((chain.length - 1) / 2)], end = chain.at(-1);
|
|
623
|
-
const restAxis = new Vector33().fromArray(end.rest).sub(new Vector33().fromArray(base.rest));
|
|
624
|
-
const restBend = new Vector33().fromArray(knee.rest).sub(new Vector33().fromArray(base.rest));
|
|
625
|
-
if (restAxis.lengthSq() < 1e-16) return [];
|
|
626
|
-
restBend.addScaledVector(restAxis, -restBend.dot(restAxis) / restAxis.lengthSq());
|
|
627
|
-
if (restBend.length() < restAxis.length() * 0.02) return [];
|
|
628
|
-
const minBend = Math.min(0.03, restBend.length() / size * 0.5);
|
|
629
|
-
return [{ base, knee, chain, tip, minBend, restAxis: restAxis.normalize(), restPole: restBend.normalize() }];
|
|
630
|
-
});
|
|
631
|
-
const poleState = (pole) => {
|
|
632
|
-
const base = new Vector33().setFromMatrixPosition(world(frames.get(key(pole.base))));
|
|
633
|
-
const knee = new Vector33().setFromMatrixPosition(world(frames.get(key(pole.knee))));
|
|
634
|
-
const axis = pole.tip.desired.clone().sub(base).normalize();
|
|
635
|
-
const preferred = pole.restPole.clone().applyQuaternion(new Quaternion2().setFromUnitVectors(pole.restAxis, axis));
|
|
636
|
-
preferred.addScaledVector(axis, -preferred.dot(axis)).normalize();
|
|
637
|
-
const bend = knee.sub(base);
|
|
638
|
-
bend.addScaledVector(axis, -bend.dot(axis));
|
|
639
|
-
return { base, axis, preferred, bend };
|
|
640
|
-
};
|
|
641
|
-
const initial = [...new Set(tips.flatMap((tip) => tip.chain.flatMap((pin) => [frames.get(key(pin)), branchJoints.get(key(pin))?.frame]).filter((frame) => Boolean(frame))))].map((frame) => ({ frame, rotation: new Quaternion2().setFromRotationMatrix(world(frame)) }));
|
|
642
|
-
const cost = () => tips.reduce((sum, tip) => sum + new Vector33().setFromMatrixPosition(world(tip.frame)).distanceToSquared(tip.desired), 0) + POSE_CONTINUITY_WEIGHT * initial.reduce((sum, { frame, rotation }) => sum + new Quaternion2().setFromRotationMatrix(world(frame)).angleTo(rotation) ** 2, 0) + 10 * poles.reduce((sum, pole) => {
|
|
643
|
-
const { preferred, bend } = poleState(pole);
|
|
644
|
-
return sum + Math.max(0, pole.minBend - bend.dot(preferred)) ** 2;
|
|
645
|
-
}, 0);
|
|
646
|
-
for (let sweep = 0; sweep < 96; sweep++) {
|
|
647
|
-
if (cost() < 1e-12) break;
|
|
648
|
-
let largestChange = 0;
|
|
649
|
-
for (const tip of tips) for (const pin of tip.chain) {
|
|
650
|
-
const id = key(pin), joints = [coneJoints.get(id) ?? freeJoints.get(id), branchJoints.get(id)?.joint];
|
|
651
|
-
for (const [index, joint] of joints.entries()) {
|
|
652
|
-
if (!joint) continue;
|
|
653
|
-
const branch = index === 1, frame = branch ? branchJoints.get(id).frame : frames.get(id);
|
|
654
|
-
const matrix3 = world(frame), pivot = new Vector33().setFromMatrixPosition(matrix3), end = new Vector33().setFromMatrixPosition(world(tip.frame));
|
|
655
|
-
const a = end.sub(pivot), b = tip.desired.clone().sub(pivot);
|
|
656
|
-
if (a.lengthSq() < 1e-20 || b.lengthSq() < 1e-20) continue;
|
|
657
|
-
const parentId = parentGroup.get(id), localParent = branch ? parentId ? frames.get(parentId) : void 0 : branchJoints.get(id)?.frame ?? (parentId ? frames.get(parentId) : void 0);
|
|
658
|
-
const parentRotation = localParent ? new Quaternion2().setFromRotationMatrix(world(localParent)) : new Quaternion2();
|
|
659
|
-
const old = parentRotation.clone().invert().multiply(new Quaternion2().setFromRotationMatrix(matrix3));
|
|
660
|
-
let rotation = parentRotation.clone().invert().multiply(new Quaternion2().setFromUnitVectors(a.normalize(), b.normalize())).multiply(new Quaternion2().setFromRotationMatrix(matrix3));
|
|
661
|
-
if (!branch) rotation = limitRotation(id, rotation, parentRotation);
|
|
662
|
-
const before = cost(), set = (q) => {
|
|
663
|
-
const e = new Euler().setFromQuaternion(q, "ZYX");
|
|
664
|
-
joint.setDoFValues(e.x, e.y, e.z);
|
|
665
|
-
frame.updateMatrixWorld();
|
|
666
|
-
};
|
|
667
|
-
for (let fraction = 1; fraction >= 1 / 32; fraction /= 2) {
|
|
668
|
-
const attempt = old.clone().slerp(rotation, fraction);
|
|
669
|
-
set(attempt);
|
|
670
|
-
if (cost() < before - 1e-14) {
|
|
671
|
-
largestChange = Math.max(largestChange, old.angleTo(attempt));
|
|
672
|
-
break;
|
|
673
|
-
}
|
|
674
|
-
set(old);
|
|
675
|
-
}
|
|
676
|
-
}
|
|
677
|
-
}
|
|
678
|
-
for (const pole of poles) {
|
|
679
|
-
const { base, preferred, bend } = poleState(pole), along = bend.dot(preferred);
|
|
680
|
-
if (along >= pole.minBend) continue;
|
|
681
|
-
const baseId = key(pole.base), nextId = key(pole.chain[1]);
|
|
682
|
-
const branch = branchJoints.get(nextId), joint = branch?.joint ?? coneJoints.get(baseId) ?? freeJoints.get(baseId);
|
|
683
|
-
const frame = branch?.frame ?? frames.get(baseId);
|
|
684
|
-
if (!joint || !frame) continue;
|
|
685
|
-
const knee = new Vector33().setFromMatrixPosition(world(frames.get(key(pole.knee))));
|
|
686
|
-
const arm = knee.sub(base), aim = arm.clone().addScaledVector(preferred, Math.min(0.01, pole.minBend - along));
|
|
687
|
-
if (arm.lengthSq() < 1e-20 || aim.lengthSq() < 1e-20) continue;
|
|
688
|
-
const parentId = branch ? baseId : parentGroup.get(baseId), parentFrame = parentId ? frames.get(parentId) : void 0;
|
|
689
|
-
const parentRotation = parentFrame ? new Quaternion2().setFromRotationMatrix(world(parentFrame)) : new Quaternion2();
|
|
690
|
-
const matrix3 = world(frame), old = parentRotation.clone().invert().multiply(new Quaternion2().setFromRotationMatrix(matrix3));
|
|
691
|
-
let proposal = parentRotation.clone().invert().multiply(new Quaternion2().setFromUnitVectors(arm.normalize(), aim.normalize())).multiply(new Quaternion2().setFromRotationMatrix(matrix3));
|
|
692
|
-
if (!branch) proposal = limitRotation(baseId, proposal, parentRotation);
|
|
693
|
-
const before = cost(), set = (q) => {
|
|
694
|
-
const e = new Euler().setFromQuaternion(q, "ZYX");
|
|
695
|
-
joint.setDoFValues(e.x, e.y, e.z);
|
|
696
|
-
frame.updateMatrixWorld();
|
|
697
|
-
};
|
|
698
|
-
for (let fraction = 1; fraction >= 1 / 32; fraction /= 2) {
|
|
699
|
-
const attempt = old.clone().slerp(proposal, fraction);
|
|
700
|
-
set(attempt);
|
|
701
|
-
if (cost() < before - 1e-14) {
|
|
702
|
-
largestChange = Math.max(largestChange, old.angleTo(attempt));
|
|
703
|
-
break;
|
|
704
|
-
}
|
|
705
|
-
set(old);
|
|
706
|
-
}
|
|
707
|
-
}
|
|
708
|
-
if (largestChange < 1e-5) break;
|
|
709
|
-
}
|
|
710
|
-
}
|
|
711
|
-
if (goals.length === 1) {
|
|
712
|
-
const target = goals[0], tipPin = byId.get(target.id);
|
|
713
|
-
if (groups.get(key(tipPin)).length === 1 && (!tipPin.ikConstraint || tipPin.ikConstraint.mode === "free")) {
|
|
714
|
-
const tip = frames.get(key(tipPin)), desired = new Vector33().fromArray(closures[0].position);
|
|
715
|
-
const ordered = ikChain(pins, parents, target.id, mass), chain = ordered.slice(0, -1).reverse();
|
|
716
|
-
const world = (frame) => {
|
|
717
|
-
frame.updateMatrixWorld();
|
|
718
|
-
return new Matrix4().fromArray(frame.matrixWorld);
|
|
719
|
-
};
|
|
720
|
-
const ground = tipPin.chainRole?.kind === "leg" && Number.isFinite(floor) ? (floor - origin.y) / size : -Infinity;
|
|
721
|
-
const point2 = (pin) => new Vector33().setFromMatrixPosition(world(frames.get(key(pin))));
|
|
722
|
-
const initial = [...new Set(chain.flatMap((pin) => [frames.get(key(pin)), branchJoints.get(key(pin))?.frame].filter((frame) => Boolean(frame))))].map((frame) => ({ frame, rotation: priorRotations.get(frame) }));
|
|
723
|
-
const poles = ordered.slice(1, -1).flatMap((knee, i) => {
|
|
724
|
-
const base = ordered[i], end = ordered[i + 2];
|
|
725
|
-
const chord = new Vector33().fromArray(end.pose.position).sub(new Vector33().fromArray(base.pose.position)), span = chord.length(), axis = chord.normalize();
|
|
726
|
-
const bend = new Vector33().fromArray(knee.pose.position).sub(new Vector33().fromArray(base.pose.position));
|
|
727
|
-
bend.addScaledVector(axis, -bend.dot(axis));
|
|
728
|
-
if (bend.length() < span * 0.02) {
|
|
729
|
-
const restAxis = new Vector33().fromArray(end.rest).sub(new Vector33().fromArray(base.rest)).normalize();
|
|
730
|
-
bend.fromArray(knee.rest).sub(new Vector33().fromArray(base.rest));
|
|
731
|
-
bend.addScaledVector(restAxis, -bend.dot(restAxis));
|
|
732
|
-
const rotation = new Quaternion2().fromArray(base.pose.rotation);
|
|
733
|
-
bend.applyQuaternion(rotation);
|
|
734
|
-
restAxis.applyQuaternion(rotation);
|
|
735
|
-
bend.applyQuaternion(new Quaternion2().setFromUnitVectors(restAxis, axis));
|
|
736
|
-
}
|
|
737
|
-
return bend.length() < span * 0.02 ? [] : [{ base, knee, end, axis, pole: bend.normalize() }];
|
|
738
|
-
});
|
|
739
|
-
const poleCost = () => poles.reduce((sum, pole) => {
|
|
740
|
-
const base = point2(pole.base), axis = point2(pole.end).sub(base).normalize();
|
|
741
|
-
const preferred = pole.pole.clone().applyQuaternion(new Quaternion2().setFromUnitVectors(pole.axis, axis));
|
|
742
|
-
const bend = point2(pole.knee).sub(base);
|
|
743
|
-
bend.addScaledVector(axis, -bend.dot(axis));
|
|
744
|
-
return sum + Math.max(0, -bend.dot(preferred)) ** 2;
|
|
745
|
-
}, 0);
|
|
746
|
-
const cost = () => {
|
|
747
|
-
const error = new Vector33().setFromMatrixPosition(world(tip)).distanceToSquared(desired);
|
|
748
|
-
let penetration = 0;
|
|
749
|
-
if (Number.isFinite(ground)) for (const pin of ordered.slice(1, -1)) penetration += Math.max(0, ground - point2(pin).y) ** 2;
|
|
750
|
-
const drift = initial.reduce((sum, { frame, rotation }) => sum + new Quaternion2().setFromRotationMatrix(world(frame)).angleTo(rotation) ** 2, 0);
|
|
751
|
-
return error + 16 * penetration + 100 * poleCost() + POSE_CONTINUITY_WEIGHT * drift;
|
|
752
|
-
};
|
|
753
|
-
for (let sweep = 0; sweep < 128; sweep++) {
|
|
754
|
-
if (cost() < 1e-12) break;
|
|
755
|
-
let largestChange = 0;
|
|
756
|
-
for (const pin of chain) {
|
|
757
|
-
const id = key(pin);
|
|
758
|
-
const joints = [coneJoints.get(id) ?? freeJoints.get(id), branchJoints.get(id)?.joint];
|
|
759
|
-
for (const [jointIndex, joint] of joints.entries()) {
|
|
760
|
-
if (!joint) continue;
|
|
761
|
-
const branch = jointIndex === 1, frame = branch ? branchJoints.get(id).frame : frames.get(id);
|
|
762
|
-
const matrix3 = world(frame), pivot = new Vector33().setFromMatrixPosition(matrix3);
|
|
763
|
-
const end = new Vector33().setFromMatrixPosition(world(tip)), before = cost();
|
|
764
|
-
const a = end.clone().sub(pivot), b = desired.clone().sub(pivot);
|
|
765
|
-
if (a.lengthSq() < 1e-20 || b.lengthSq() < 1e-20) continue;
|
|
766
|
-
const parentId = parentGroup.get(id), localParent = branch ? parentId ? frames.get(parentId) : void 0 : branchJoints.get(id)?.frame ?? (parentId ? frames.get(parentId) : void 0);
|
|
767
|
-
const parentRotation = localParent ? new Quaternion2().setFromRotationMatrix(world(localParent)) : new Quaternion2();
|
|
768
|
-
const old = parentRotation.clone().invert().multiply(new Quaternion2().setFromRotationMatrix(matrix3));
|
|
769
|
-
let rotation = parentRotation.clone().invert().multiply(new Quaternion2().setFromUnitVectors(a.normalize(), b.normalize())).multiply(new Quaternion2().setFromRotationMatrix(matrix3));
|
|
770
|
-
if (!branch) rotation = limitRotation(id, rotation, parentRotation);
|
|
771
|
-
const set = (q) => {
|
|
772
|
-
const e = new Euler().setFromQuaternion(q, "ZYX");
|
|
773
|
-
joint.setDoFValues(e.x, e.y, e.z);
|
|
774
|
-
frame.updateMatrixWorld();
|
|
775
|
-
};
|
|
776
|
-
let accepted = false;
|
|
777
|
-
for (let fraction = 1; fraction >= 1 / 32; fraction /= 2) {
|
|
778
|
-
let attempt = old.clone().slerp(rotation, fraction);
|
|
779
|
-
if (!branch) attempt = limitRotation(id, attempt, parentRotation);
|
|
780
|
-
set(attempt);
|
|
781
|
-
if (cost() <= before + 1e-14) {
|
|
782
|
-
largestChange = Math.max(largestChange, old.angleTo(attempt));
|
|
783
|
-
accepted = true;
|
|
784
|
-
break;
|
|
785
|
-
}
|
|
786
|
-
}
|
|
787
|
-
if (!accepted) set(old);
|
|
788
|
-
if (Number.isFinite(ground)) for (const descendant of ordered.slice(ordered.indexOf(pin) + 1, -1)) {
|
|
789
|
-
const lower = point2(descendant);
|
|
790
|
-
if (lower.y >= ground) continue;
|
|
791
|
-
const current = point2(pin), arm = lower.clone().sub(current), raised = lower.clone();
|
|
792
|
-
raised.y = ground;
|
|
793
|
-
const aim = raised.sub(current);
|
|
794
|
-
if (arm.lengthSq() < 1e-20 || aim.lengthSq() < 1e-20) continue;
|
|
795
|
-
const parentNow = localParent ? new Quaternion2().setFromRotationMatrix(world(localParent)) : new Quaternion2();
|
|
796
|
-
const previous = parentNow.clone().invert().multiply(new Quaternion2().setFromRotationMatrix(world(frame)));
|
|
797
|
-
let proposal = parentNow.clone().invert().multiply(new Quaternion2().setFromUnitVectors(arm.normalize(), aim.normalize())).multiply(new Quaternion2().setFromRotationMatrix(world(frame)));
|
|
798
|
-
if (!branch) proposal = limitRotation(id, proposal, parentNow);
|
|
799
|
-
const start = cost();
|
|
800
|
-
for (let fraction = 1; fraction >= 1 / 16; fraction /= 2) {
|
|
801
|
-
const attempt = previous.clone().slerp(proposal, fraction);
|
|
802
|
-
set(attempt);
|
|
803
|
-
if (cost() < start - 1e-14) {
|
|
804
|
-
largestChange = Math.max(largestChange, previous.angleTo(attempt));
|
|
805
|
-
break;
|
|
806
|
-
}
|
|
807
|
-
set(previous);
|
|
808
|
-
}
|
|
809
|
-
}
|
|
810
|
-
}
|
|
811
|
-
}
|
|
812
|
-
if (largestChange < 1e-5) break;
|
|
813
|
-
}
|
|
814
|
-
}
|
|
815
|
-
}
|
|
816
|
-
if (goals.length === 1 || !positionOnlyGoals) projectCones();
|
|
817
|
-
for (const goal of goals) {
|
|
818
|
-
const id = key(byId.get(goal.id)), joint = freeJoints.get(id);
|
|
819
|
-
if (!joint || groups.get(id).length !== 1) continue;
|
|
820
|
-
const parentId = parentGroup.get(id), parent = parentId ? frames.get(parentId) : void 0;
|
|
821
|
-
parent?.updateMatrixWorld();
|
|
822
|
-
const rotation = parent ? new Quaternion2().setFromRotationMatrix(new Matrix4().fromArray(parent.matrixWorld)).invert() : new Quaternion2();
|
|
823
|
-
rotation.multiply(new Quaternion2().fromArray(goal.rotation));
|
|
824
|
-
const e = new Euler().setFromQuaternion(rotation, "ZYX");
|
|
825
|
-
joint.setDoFValues(e.x, e.y, e.z);
|
|
826
|
-
frames.get(id).updateMatrixWorld();
|
|
827
|
-
}
|
|
828
|
-
const result = pins.filter((p) => affected.has(key(p))).map((pin) => {
|
|
829
|
-
if (fixed.has(pin.id)) return { id: pin.id, pose: pin.pose };
|
|
830
|
-
const anchor = groups.get(key(pin))[0], frame = frames.get(key(pin));
|
|
831
|
-
frame.updateMatrixWorld();
|
|
832
|
-
const matrix3 = new Matrix4().fromArray(frame.matrixWorld), rotation = new Quaternion2().setFromRotationMatrix(matrix3).normalize();
|
|
833
|
-
const position = new Vector33().setFromMatrixPosition(matrix3).multiplyScalar(size).add(origin);
|
|
834
|
-
const delta = rotation.clone().multiply(new Quaternion2().fromArray(anchor.pose.rotation).invert());
|
|
835
|
-
const goal = goals.find((g) => key(byId.get(g.id)) === key(pin));
|
|
836
|
-
const terminal = ![...parentGroup.values()].includes(key(pin));
|
|
837
|
-
if (goal && terminal && (!pin.ikConstraint || pin.ikConstraint.mode === "free")) rotation.fromArray(goal.rotation);
|
|
838
|
-
const offset = new Vector33().fromArray(pin.pose.position).sub(new Vector33().fromArray(anchor.pose.position));
|
|
839
|
-
if (goal && terminal && (!pin.ikConstraint || pin.ikConstraint.mode === "free")) delta.copy(rotation).multiply(new Quaternion2().fromArray(anchor.pose.rotation).invert());
|
|
840
|
-
position.add(offset.applyQuaternion(delta));
|
|
841
|
-
if (!parentGroup.has(key(pin)) && pin.id === anchor.id) position.fromArray(pin.pose.position);
|
|
842
|
-
if (![...position.toArray(), ...rotation.toArray()].every(Number.isFinite)) throw new Error("IK produced an invalid pose.");
|
|
843
|
-
return { id: pin.id, pose: { position: position.toArray(), rotation: rotation.toArray(), scale: pin.pose.scale } };
|
|
844
|
-
});
|
|
845
|
-
return result;
|
|
846
|
-
}
|
|
847
|
-
|
|
848
|
-
// src/deformation/rig-extension.ts
|
|
849
|
-
var NEEDLE_DEFORMATION_RIG = "NEEDLE_deformation_rig";
|
|
850
|
-
function parseRigDescriptor(value, nodeCount, textureCount = Infinity) {
|
|
851
|
-
if (!value || typeof value !== "object") throw new Error("Invalid deformation rig.");
|
|
852
|
-
const raw = value;
|
|
853
|
-
if (raw.version !== 1 && raw.version !== 2 && raw.version !== 3 && raw.version !== 4 && raw.version !== 5 && raw.version !== 6 && raw.version !== 7 && raw.version !== 8 && raw.version !== 9) throw new Error("Unsupported NEEDLE_deformation_rig version.");
|
|
854
|
-
if (raw.furSurface?.texCoord !== void 0 && (raw.version < 8 || !Number.isInteger(raw.furSurface.texCoord) || raw.furSurface.texCoord < 0 || raw.furSurface.texCoord > 1)) throw new Error("Invalid Fur height texture coordinates.");
|
|
855
|
-
if (raw.furSurface && (raw.version < 6 || !Number.isInteger(raw.furSurface.heightTexture) || raw.furSurface.heightTexture < 0 || raw.furSurface.heightTexture >= textureCount)) throw new Error("Invalid Fur height texture.");
|
|
856
|
-
if (raw.version < 5 && raw.windStrength !== void 0) throw new Error("Wind requires NEEDLE_deformation_rig version 5.");
|
|
857
|
-
if (raw.activePose === 0 && raw.version < 9) throw new Error("An unselected authored pose requires NEEDLE_deformation_rig version 9.");
|
|
858
|
-
const restSlot = raw.poseSlots?.find((slot) => slot.slot === 0);
|
|
859
|
-
if (restSlot && raw.version < 7) throw new Error("Pose 0 requires NEEDLE_deformation_rig version 7.");
|
|
860
|
-
const rig = validateRig({ ...raw, poseSlots: raw.poseSlots?.filter((slot) => slot.slot !== 0) }, raw.version >= 3 ? 256 : 128);
|
|
861
|
-
if (restSlot) {
|
|
862
|
-
if (raw.poseSlots.filter((slot) => slot.slot === 0).length !== 1 || !Array.isArray(restSlot.poses) || restSlot.poses.length !== rig.pins.length || new Set(restSlot.poses.map((p) => p.id)).size !== rig.pins.length || restSlot.poses.some((p) => !rig.pins.some((pin) => pin.id === p.id))) throw new Error("Invalid rest pose clip.");
|
|
863
|
-
validateRig({ pins: rig.pins, activePose: 1, poseSlots: [{ slot: 1, poses: restSlot.poses }], poseTimes: [] }, raw.version >= 3 ? 256 : 128);
|
|
864
|
-
}
|
|
865
|
-
if (raw.version < 5 && rig.pins.some((pin) => pin.fur)) throw new Error("Fur requires NEEDLE_deformation_rig version 5.");
|
|
866
|
-
if (raw.furSurface && !rig.pins.some((pin) => pin.fur)) throw new Error("Fur height requires a Fur rig.");
|
|
867
|
-
const node = (n) => Number.isInteger(n) && n >= 0 && n < nodeCount;
|
|
868
|
-
if (!Array.isArray(raw.joints) || raw.joints.length !== rig.pins.length) throw new Error("Invalid rig joint bindings.");
|
|
869
|
-
const indices = /* @__PURE__ */ new Set();
|
|
870
|
-
for (const joint of raw.joints) {
|
|
871
|
-
if (!joint || !node(joint.node) || indices.has(joint.node) || joint.parent !== null && !node(joint.parent) || !Number.isFinite(joint.mass) || joint.mass < 0) throw new Error("Invalid rig node or mass.");
|
|
872
|
-
indices.add(joint.node);
|
|
873
|
-
}
|
|
874
|
-
const parents = new Map(raw.joints.map((j) => [j.node, j.parent]));
|
|
875
|
-
for (const joint of raw.joints) {
|
|
876
|
-
const seen = /* @__PURE__ */ new Set();
|
|
877
|
-
let cursor = joint.node;
|
|
878
|
-
while (cursor !== null) {
|
|
879
|
-
if (!indices.has(cursor) || seen.has(cursor)) throw new Error("Invalid or cyclic rig hierarchy.");
|
|
880
|
-
seen.add(cursor);
|
|
881
|
-
cursor = parents.get(cursor);
|
|
882
|
-
}
|
|
883
|
-
}
|
|
884
|
-
if (!Array.isArray(raw.chains) || raw.chains.length > rig.pins.length) throw new Error("Invalid motion chains.");
|
|
885
|
-
const endpoints = /* @__PURE__ */ new Set();
|
|
886
|
-
for (const chain of raw.chains) {
|
|
887
|
-
if (!chain || !indices.has(chain.endpoint) || endpoints.has(chain.endpoint) || !["ik", "secondary", "cloth", "fur"].includes(chain.mode) || !Array.isArray(chain.joints) || !chain.joints.length || chain.joints.length > rig.pins.length || chain.joints.at(-1) !== chain.endpoint || new Set(chain.joints).size !== chain.joints.length || chain.joints.some((n) => !indices.has(n))) throw new Error("Invalid motion chain.");
|
|
888
|
-
endpoints.add(chain.endpoint);
|
|
889
|
-
}
|
|
890
|
-
const pinParents = /* @__PURE__ */ new Map(), masses = /* @__PURE__ */ new Map();
|
|
891
|
-
raw.joints.forEach((j, i) => {
|
|
892
|
-
masses.set(rig.pins[i].id, j.mass);
|
|
893
|
-
if (j.parent !== null) pinParents.set(rig.pins[i].id, rig.pins[raw.joints.findIndex((p) => p.node === j.parent)].id);
|
|
894
|
-
});
|
|
895
|
-
for (const [i, pin] of rig.pins.entries()) {
|
|
896
|
-
const chain = raw.chains.find((c) => c.endpoint === raw.joints[i].node);
|
|
897
|
-
const mode = !pin.guide && (pin.ik ? "ik" : pin.wiggle ? "secondary" : pin.cloth ? "cloth" : pin.fur ? "fur" : null);
|
|
898
|
-
if (!mode && chain) throw new Error("Unexpected motion chain.");
|
|
899
|
-
if (!mode) continue;
|
|
900
|
-
const articulated = raw.version >= 3 ? rig.pins.filter((_, i2) => !raw.helpers?.some((h) => h.node === raw.joints[i2].node)) : rig.pins;
|
|
901
|
-
const expected = ikChain(articulated.map((p) => p.id === pin.id ? { ...p, motion: { ...p.motion ?? DEFAULT_MOTION, reach: 1 } } : p), pinParents, pin.id, masses).map((p) => raw.joints[rig.pins.findIndex((pin2) => pin2.id === p.id)].node);
|
|
902
|
-
if (!chain || chain.mode !== mode || chain.joints.length > expected.length || chain.joints.some((n, i2) => n !== expected[expected.length - chain.joints.length + i2])) throw new Error("Motion chain does not match its hierarchy and reach.");
|
|
903
|
-
}
|
|
904
|
-
if (raw.helpers !== void 0 && (!Array.isArray(raw.helpers) || raw.helpers.length > 256)) throw new Error("Invalid helper bindings.");
|
|
905
|
-
const helpers = raw.helpers?.map((helper) => {
|
|
906
|
-
if (!node(helper.node) || raw.version < 3 && indices.has(helper.node) || raw.version >= 3 && !parents.has(helper.node) || !Array.isArray(helper.influences) || helper.influences.length > rig.pins.length) throw new Error("Invalid helper node.");
|
|
907
|
-
const seen = /* @__PURE__ */ new Set();
|
|
908
|
-
let sum = 0;
|
|
909
|
-
for (const influence of helper.influences) {
|
|
910
|
-
if (!parents.has(influence.node) || raw.version >= 3 && raw.helpers?.some((h) => h.node === influence.node) || seen.has(influence.node) || !Number.isFinite(influence.weight) || influence.weight <= 0) throw new Error("Invalid helper influence.");
|
|
911
|
-
seen.add(influence.node);
|
|
912
|
-
sum += influence.weight;
|
|
913
|
-
}
|
|
914
|
-
if (helper.influences.length && Math.abs(sum - 1) > 1e-4) throw new Error("Helper weights must sum to one.");
|
|
915
|
-
indices.add(helper.node);
|
|
916
|
-
return { node: helper.node, influences: helper.influences.map((i) => ({ ...i })) };
|
|
917
|
-
});
|
|
918
|
-
if (raw.version >= 2 && !helpers) throw new Error("Rig requires helper bindings.");
|
|
919
|
-
if (helpers && new Set(helpers.map((h) => h.node)).size !== helpers.length) throw new Error("Duplicate helper bone.");
|
|
920
|
-
if (raw.version < 4 && (raw.cloth !== void 0 || rig.pins.some((p) => p.cloth)) || raw.version === 4 && !raw.cloth || rig.pins.some((p) => p.cloth) && !raw.cloth || raw.cloth && (!Array.isArray(raw.cloth.links) || !Array.isArray(raw.cloth.colliders) || raw.cloth.links.length > 512 || raw.cloth.colliders.length > 4096)) throw new Error("Invalid cloth simulation data.");
|
|
921
|
-
const pinById = new Map(rig.pins.map((p) => [p.id, p]));
|
|
922
|
-
for (const link of raw.cloth?.links ?? []) if (!link || !pinById.has(link.a) || !pinById.has(link.b) || link.a === link.b || !(pinById.get(link.a)?.cloth || pinById.get(link.b)?.cloth) || !Number.isFinite(link.length) || link.length < 0) throw new Error("Invalid cloth link.");
|
|
923
|
-
for (const collider of raw.cloth?.colliders ?? []) if (!collider || !Array.isArray(collider.position) || collider.position.length !== 3 || !collider.position.every(Number.isFinite) || !Number.isFinite(collider.radius) || collider.radius <= 0 || !collider.driver || !pinById.has(collider.driver) || pinById.get(collider.driver)?.cloth) throw new Error("Invalid cloth collider.");
|
|
924
|
-
return { ...rig, poseSlots: restSlot ? [restSlot, ...rig.poseSlots] : rig.poseSlots, version: raw.version, joints: raw.joints.map((j) => ({ ...j })), chains: raw.chains.map((c) => ({ ...c, joints: [...c.joints] })), ...helpers ? { helpers } : {}, ...raw.cloth ? { cloth: { links: raw.cloth.links.map((l) => ({ ...l })), colliders: raw.cloth.colliders.map((c) => ({ ...c, position: [...c.position] })) } } : {}, ...raw.furSurface ? { furSurface: { ...raw.furSurface } } : {} };
|
|
925
|
-
}
|
|
926
|
-
|
|
927
|
-
// src/deformation/pin-wiggle.ts
|
|
928
|
-
import { Quaternion as Quaternion3, Vector3 as Vector34 } from "three";
|
|
929
|
-
var PinWiggle = class {
|
|
930
|
-
springs = /* @__PURE__ */ new Map();
|
|
931
|
-
topology = "";
|
|
932
|
-
lastPins = null;
|
|
933
|
-
lastParents = null;
|
|
934
|
-
awake = false;
|
|
935
|
-
windTime = 0;
|
|
936
|
-
reset() {
|
|
937
|
-
this.springs.clear();
|
|
938
|
-
this.topology = "";
|
|
939
|
-
this.lastPins = null;
|
|
940
|
-
this.lastParents = null;
|
|
941
|
-
this.awake = false;
|
|
942
|
-
this.windTime = 0;
|
|
943
|
-
}
|
|
944
|
-
step(pins, parents, seconds, masses, windStrength = 0) {
|
|
945
|
-
if (windStrength <= 0 && !this.awake && pins === this.lastPins && parents === this.lastParents) return { pins, active: false };
|
|
946
|
-
const topology = JSON.stringify(pins.map((p) => [p.id, p.rest, p.rigidGroup, p.independent, p.guide, p.wiggle, p.fur, p.furDepth, p.motion, parents.get(p.id)]));
|
|
947
|
-
if (topology !== this.topology) {
|
|
948
|
-
this.reset();
|
|
949
|
-
this.topology = topology;
|
|
950
|
-
}
|
|
951
|
-
const groups = /* @__PURE__ */ new Map(), byId = new Map(pins.map((p) => [p.id, p]));
|
|
952
|
-
const key = (p) => p.rigidGroup ?? p.id;
|
|
953
|
-
for (const pin of pins) {
|
|
954
|
-
const group = groups.get(key(pin)) ?? [];
|
|
955
|
-
group.push(pin);
|
|
956
|
-
groups.set(key(pin), group);
|
|
957
|
-
}
|
|
958
|
-
const settings = /* @__PURE__ */ new Map();
|
|
959
|
-
const volumes = [...groups.values()].filter((group) => !group.every((p) => p.guide)).map((group) => Math.max(1e-9, masses?.get(group[0].id) ?? 1)).sort((a, b) => a - b);
|
|
960
|
-
const typicalVolume = volumes[Math.floor(volumes.length / 2)] ?? 1;
|
|
961
|
-
for (const pin of pins.filter((p) => p.wiggle && !p.guide)) {
|
|
962
|
-
const chain = ikChain(pins, parents, pin.id, masses);
|
|
963
|
-
for (const node of chain.length > 1 ? chain.slice(1) : chain) if (!settings.has(key(node))) settings.set(key(node), pin.motion ?? DEFAULT_MOTION);
|
|
964
|
-
}
|
|
965
|
-
for (const pin of pins.filter((p) => p.wiggle && !p.guide)) settings.set(key(pin), pin.motion ?? DEFAULT_MOTION);
|
|
966
|
-
for (const pin of pins.filter((p) => p.fur && !p.guide)) settings.set(key(pin), pin.motion ?? DEFAULT_MOTION);
|
|
967
|
-
const output = /* @__PURE__ */ new Map(), visiting = /* @__PURE__ */ new Set();
|
|
968
|
-
let active = false;
|
|
969
|
-
const dt = Math.min(Math.max(seconds, 0), 0.05);
|
|
970
|
-
this.windTime += dt;
|
|
971
|
-
const visit = (id) => {
|
|
972
|
-
const group = groups.get(id);
|
|
973
|
-
if (output.has(group[0].id)) return;
|
|
974
|
-
if (visiting.has(id)) {
|
|
975
|
-
for (const pin of group) output.set(pin.id, pin.pose);
|
|
976
|
-
return;
|
|
977
|
-
}
|
|
978
|
-
visiting.add(id);
|
|
979
|
-
const parent = group.map((p) => byId.get(parents.get(p.id) ?? "")).find((p) => p && key(p) !== id);
|
|
980
|
-
if (parent) visit(key(parent));
|
|
981
|
-
const parentPose = parent ? output.get(parent.id) : void 0;
|
|
982
|
-
const inherited = parent && parentPose ? new Quaternion3().fromArray(parentPose.rotation).multiply(new Quaternion3().fromArray(parent.pose.rotation).invert()) : new Quaternion3();
|
|
983
|
-
const targets = group.map((pin) => {
|
|
984
|
-
const position2 = new Vector34().fromArray(pin.pose.position);
|
|
985
|
-
if (!pin.ik && parent && parentPose) position2.sub(new Vector34().fromArray(parent.pose.position)).applyQuaternion(inherited).add(new Vector34().fromArray(parentPose.position));
|
|
986
|
-
return { pin, position: position2, rotation: (pin.ik ? new Quaternion3() : inherited.clone()).multiply(new Quaternion3().fromArray(pin.pose.rotation)) };
|
|
987
|
-
});
|
|
988
|
-
const center = targets.reduce((sum, p) => sum.add(p.position), new Vector34()).divideScalar(group.length);
|
|
989
|
-
let position = center, rotation = new Quaternion3();
|
|
990
|
-
const motion = settings.get(id);
|
|
991
|
-
if (motion && !group.every((p) => p.guide) && !group.some((p) => p.ik)) {
|
|
992
|
-
const ratio = Math.max(0.125, Math.min(8, (masses?.get(group[0].id) ?? typicalVolume) / typicalVolume));
|
|
993
|
-
const gain = motion.strength * Math.max(0.25, Math.min(4, Math.pow(1 / ratio, 0.5 * motion.massInfluence)));
|
|
994
|
-
const frequency = motion.frequency * 2 * Math.PI, damping = Math.max(0.05, Math.min(1, motion.damping * Math.pow(ratio, 0.25 * motion.massInfluence)));
|
|
995
|
-
const decay = damping * frequency, oscillation = frequency * Math.sqrt(1 - damping * damping);
|
|
996
|
-
const e = Math.exp(-decay * dt), c = Math.cos(oscillation * dt), s = oscillation > 1e-8 ? Math.sin(oscillation * dt) / oscillation : dt;
|
|
997
|
-
let spring = this.springs.get(id);
|
|
998
|
-
if (!spring) {
|
|
999
|
-
spring = { position: center.clone(), velocity: new Vector34(), target: center.clone() };
|
|
1000
|
-
this.springs.set(id, spring);
|
|
1001
|
-
}
|
|
1002
|
-
spring.position.addScaledVector(center.clone().sub(spring.target), 1 - gain);
|
|
1003
|
-
spring.target.copy(center);
|
|
1004
|
-
if (motion.strength === 0) {
|
|
1005
|
-
spring.position.copy(center);
|
|
1006
|
-
spring.velocity.set(0, 0, 0);
|
|
1007
|
-
} else if (windStrength > 0) spring.velocity.addScaledVector(windAcceleration(
|
|
1008
|
-
this.windTime,
|
|
1009
|
-
windStrength,
|
|
1010
|
-
parentPose ? Math.max(center.distanceTo(new Vector34().fromArray(parentPose.position)), 1e-3) : 1,
|
|
1011
|
-
center.toArray()
|
|
1012
|
-
), motion.strength * dt);
|
|
1013
|
-
const offset = spring.position.clone().sub(center), velocity = spring.velocity.clone();
|
|
1014
|
-
spring.position.copy(offset).multiplyScalar(c).addScaledVector(velocity.clone().addScaledVector(offset, decay), s).multiplyScalar(e).add(center);
|
|
1015
|
-
spring.velocity.copy(velocity).multiplyScalar(c).sub(velocity.clone().multiplyScalar(decay).addScaledVector(offset, frequency * frequency).multiplyScalar(s)).multiplyScalar(e);
|
|
1016
|
-
const fur = group.find((p) => p.fur), furDepth = fur?.furDepth ?? DEFAULT_FUR_DEPTH;
|
|
1017
|
-
let radius = 1;
|
|
1018
|
-
if (parentPose) {
|
|
1019
|
-
const pivot = new Vector34().fromArray(parentPose.position), desired = center.clone().sub(pivot);
|
|
1020
|
-
radius = desired.length();
|
|
1021
|
-
const direction = spring.position.clone().sub(pivot);
|
|
1022
|
-
if (radius > 1e-8) {
|
|
1023
|
-
if (direction.lengthSq() < 1e-16) direction.copy(desired);
|
|
1024
|
-
const length = direction.length();
|
|
1025
|
-
direction.divideScalar(length);
|
|
1026
|
-
const coreRadius = radius * (1 - furDepth), outerRadius = radius * (1 + furDepth);
|
|
1027
|
-
const projected = fur ? Math.max(coreRadius, Math.min(outerRadius, length)) : radius;
|
|
1028
|
-
spring.position.copy(pivot).addScaledVector(direction, projected);
|
|
1029
|
-
if (!fur || length < coreRadius || length > outerRadius) spring.velocity.addScaledVector(direction, -spring.velocity.dot(direction));
|
|
1030
|
-
rotation.setFromUnitVectors(desired.normalize(), direction);
|
|
1031
|
-
} else {
|
|
1032
|
-
spring.position.copy(center);
|
|
1033
|
-
spring.velocity.set(0, 0, 0);
|
|
1034
|
-
}
|
|
1035
|
-
}
|
|
1036
|
-
if (fur) {
|
|
1037
|
-
const shell = Math.max(1e-4, radius) * furDepth;
|
|
1038
|
-
if (shell === 0) {
|
|
1039
|
-
spring.position.copy(center);
|
|
1040
|
-
spring.velocity.set(0, 0, 0);
|
|
1041
|
-
rotation.identity();
|
|
1042
|
-
}
|
|
1043
|
-
const displacement = spring.position.clone().sub(center);
|
|
1044
|
-
if (displacement.length() > shell) {
|
|
1045
|
-
displacement.setLength(shell);
|
|
1046
|
-
spring.position.copy(center).add(displacement);
|
|
1047
|
-
const outward = displacement.normalize();
|
|
1048
|
-
spring.velocity.addScaledVector(outward, -Math.max(0, spring.velocity.dot(outward)));
|
|
1049
|
-
}
|
|
1050
|
-
if (parentPose && radius > 1e-8) {
|
|
1051
|
-
const pivot = new Vector34().fromArray(parentPose.position), desired = center.clone().sub(pivot).normalize(), direction = spring.position.clone().sub(pivot).normalize();
|
|
1052
|
-
rotation.setFromUnitVectors(desired, direction);
|
|
1053
|
-
}
|
|
1054
|
-
}
|
|
1055
|
-
const epsilon = Math.max(radius, 1e-3) * 1e-5;
|
|
1056
|
-
if (spring.position.distanceToSquared(center) < epsilon * epsilon && spring.velocity.lengthSq() < epsilon * epsilon * frequency * frequency) {
|
|
1057
|
-
spring.position.copy(center);
|
|
1058
|
-
spring.velocity.set(0, 0, 0);
|
|
1059
|
-
rotation.identity();
|
|
1060
|
-
} else active = true;
|
|
1061
|
-
position = spring.position;
|
|
1062
|
-
}
|
|
1063
|
-
for (const target of targets) output.set(target.pin.id, {
|
|
1064
|
-
position: target.position.sub(center).applyQuaternion(rotation).add(position).toArray(),
|
|
1065
|
-
rotation: rotation.clone().multiply(target.rotation).normalize().toArray(),
|
|
1066
|
-
scale: target.pin.pose.scale
|
|
1067
|
-
});
|
|
1068
|
-
visiting.delete(id);
|
|
1069
|
-
};
|
|
1070
|
-
for (const id of groups.keys()) visit(id);
|
|
1071
|
-
this.lastPins = pins;
|
|
1072
|
-
this.lastParents = parents;
|
|
1073
|
-
this.awake = active;
|
|
1074
|
-
return { pins: active ? pins.map((pin) => ({ ...pin, pose: output.get(pin.id) })) : pins, active };
|
|
1075
|
-
}
|
|
1076
|
-
};
|
|
1077
|
-
|
|
1078
|
-
// src/deformation/pin-cloth.ts
|
|
1079
|
-
import { Quaternion as Quaternion4, Vector3 as Vector35 } from "three";
|
|
1080
|
-
var PinCloth = class {
|
|
1081
|
-
particles = /* @__PURE__ */ new Map();
|
|
1082
|
-
layout = "";
|
|
1083
|
-
windTime = 0;
|
|
1084
|
-
reset() {
|
|
1085
|
-
this.particles.clear();
|
|
1086
|
-
this.layout = "";
|
|
1087
|
-
this.windTime = 0;
|
|
1088
|
-
}
|
|
1089
|
-
step(pins, parents, seconds, links, colliders = [], windStrength = 0) {
|
|
1090
|
-
const cloth = pins.filter((p) => p.cloth && !p.guide);
|
|
1091
|
-
if (!cloth.length) {
|
|
1092
|
-
this.reset();
|
|
1093
|
-
return { pins, active: false };
|
|
1094
|
-
}
|
|
1095
|
-
const layout = JSON.stringify([cloth.map((p) => [p.id, p.rest]), links]);
|
|
1096
|
-
if (layout !== this.layout) {
|
|
1097
|
-
this.reset();
|
|
1098
|
-
this.layout = layout;
|
|
1099
|
-
}
|
|
1100
|
-
const byId = new Map(pins.map((p) => [p.id, p]));
|
|
1101
|
-
for (const pin of cloth) if (!this.particles.has(pin.id)) {
|
|
1102
|
-
const position = new Vector35().fromArray(pin.pose.position);
|
|
1103
|
-
this.particles.set(pin.id, { position, previous: position.clone() });
|
|
1104
|
-
}
|
|
1105
|
-
const dt = Math.min(Math.max(seconds, 0), 0.05), steps = Math.max(1, Math.ceil(dt / (1 / 60))), h = dt / steps;
|
|
1106
|
-
const scale = Math.max(1e-4, ...links.map((link) => link.length));
|
|
1107
|
-
let maxRadius = 0;
|
|
1108
|
-
for (const collider of colliders) maxRadius = Math.max(maxRadius, collider.radius);
|
|
1109
|
-
const cell = Math.max(1e-4, scale * 2 + maxRadius);
|
|
1110
|
-
const spatial = cloth.length > 4 && colliders.length > 128;
|
|
1111
|
-
const bins = /* @__PURE__ */ new Map();
|
|
1112
|
-
const key = (x, y, z) => `${x},${y},${z}`;
|
|
1113
|
-
if (spatial) for (const collider of colliders) {
|
|
1114
|
-
const p = collider.position, id = key(Math.floor(p[0] / cell), Math.floor(p[1] / cell), Math.floor(p[2] / cell));
|
|
1115
|
-
const bin = bins.get(id) ?? [];
|
|
1116
|
-
bin.push(collider);
|
|
1117
|
-
bins.set(id, bin);
|
|
1118
|
-
}
|
|
1119
|
-
const candidates = (position) => {
|
|
1120
|
-
const found = [];
|
|
1121
|
-
const search = (collider) => {
|
|
1122
|
-
const p = collider.position, dx = position.x - p[0], dy = position.y - p[1], dz = position.z - p[2], reach = collider.radius + scale * 2;
|
|
1123
|
-
if (dx * dx + dy * dy + dz * dz < reach * reach) found.push(collider);
|
|
1124
|
-
};
|
|
1125
|
-
if (spatial) {
|
|
1126
|
-
const x = Math.floor(position.x / cell), y = Math.floor(position.y / cell), z = Math.floor(position.z / cell);
|
|
1127
|
-
for (let dz = -1; dz <= 1; dz++) for (let dy = -1; dy <= 1; dy++) for (let dx = -1; dx <= 1; dx++)
|
|
1128
|
-
for (const collider of bins.get(key(x + dx, y + dy, z + dz)) ?? []) search(collider);
|
|
1129
|
-
} else for (const collider of colliders) search(collider);
|
|
1130
|
-
return found;
|
|
1131
|
-
};
|
|
1132
|
-
for (let substep = 0; substep < steps && dt > 0; substep++) {
|
|
1133
|
-
this.windTime += h;
|
|
1134
|
-
for (const pin of cloth) {
|
|
1135
|
-
const particle = this.particles.get(pin.id);
|
|
1136
|
-
const motion = pin.motion ?? DEFAULT_MOTION;
|
|
1137
|
-
const velocity = particle.position.clone().sub(particle.previous).multiplyScalar(Math.exp(-motion.damping * 3 * h));
|
|
1138
|
-
particle.previous.copy(particle.position);
|
|
1139
|
-
particle.position.add(velocity).y -= 2.5 * scale * h * h;
|
|
1140
|
-
if (windStrength > 0 && motion.strength > 0) particle.position.addScaledVector(windAcceleration(this.windTime, windStrength, scale, particle.position.toArray()), motion.strength * h * h);
|
|
1141
|
-
particle.position.lerp(new Vector35().fromArray(pin.pose.position), 1 - Math.exp(-2 * Math.PI * motion.frequency * h));
|
|
1142
|
-
}
|
|
1143
|
-
const nearby = new Map(cloth.map((pin) => [pin.id, candidates(this.particles.get(pin.id).position)]));
|
|
1144
|
-
for (let iteration = 0; iteration < 6; iteration++) {
|
|
1145
|
-
for (const link of links) {
|
|
1146
|
-
const a = this.particles.get(link.a), b = this.particles.get(link.b);
|
|
1147
|
-
const pa = a?.position ?? new Vector35().fromArray(byId.get(link.a)?.pose.position ?? [0, 0, 0]);
|
|
1148
|
-
const pb = b?.position ?? new Vector35().fromArray(byId.get(link.b)?.pose.position ?? [0, 0, 0]);
|
|
1149
|
-
const delta = pa.clone().sub(pb), distance = delta.length();
|
|
1150
|
-
if (distance < 1e-8) continue;
|
|
1151
|
-
const correction = delta.multiplyScalar((distance - link.length) / distance);
|
|
1152
|
-
if (a && b) {
|
|
1153
|
-
a.position.addScaledVector(correction, -0.5);
|
|
1154
|
-
b.position.addScaledVector(correction, 0.5);
|
|
1155
|
-
} else if (a) a.position.sub(correction);
|
|
1156
|
-
else if (b) b.position.add(correction);
|
|
1157
|
-
}
|
|
1158
|
-
for (const [id, particle] of this.particles) for (const collider of nearby.get(id) ?? []) {
|
|
1159
|
-
const center = collider.position, dx = particle.position.x - center[0], dy = particle.position.y - center[1], dz = particle.position.z - center[2];
|
|
1160
|
-
const squared = dx * dx + dy * dy + dz * dz;
|
|
1161
|
-
if (squared >= collider.radius * collider.radius) continue;
|
|
1162
|
-
if (squared < 1e-16) particle.position.set(center[0], center[1] + collider.radius, center[2]);
|
|
1163
|
-
else {
|
|
1164
|
-
const factor = collider.radius / Math.sqrt(squared);
|
|
1165
|
-
particle.position.set(center[0] + dx * factor, center[1] + dy * factor, center[2] + dz * factor);
|
|
1166
|
-
}
|
|
1167
|
-
}
|
|
1168
|
-
}
|
|
1169
|
-
}
|
|
1170
|
-
let active = false;
|
|
1171
|
-
const result = pins.map((pin) => {
|
|
1172
|
-
const particle = this.particles.get(pin.id);
|
|
1173
|
-
if (!particle) return pin;
|
|
1174
|
-
const target = new Vector35().fromArray(pin.pose.position), offset = particle.position.clone().sub(target);
|
|
1175
|
-
const velocity = particle.position.clone().sub(particle.previous);
|
|
1176
|
-
if (offset.lengthSq() > scale * scale * 1e-10 || velocity.lengthSq() > scale * scale * 1e-10) active = true;
|
|
1177
|
-
const parent = byId.get(parents.get(pin.id) ?? "");
|
|
1178
|
-
const rotation = parent ? new Quaternion4().setFromUnitVectors(
|
|
1179
|
-
target.clone().sub(new Vector35().fromArray(parent.pose.position)).normalize(),
|
|
1180
|
-
particle.position.clone().sub(new Vector35().fromArray(parent.pose.position)).normalize()
|
|
1181
|
-
) : new Quaternion4();
|
|
1182
|
-
return { ...pin, pose: {
|
|
1183
|
-
...pin.pose,
|
|
1184
|
-
position: particle.position.toArray(),
|
|
1185
|
-
rotation: rotation.multiply(new Quaternion4().fromArray(pin.pose.rotation)).normalize().toArray()
|
|
1186
|
-
} };
|
|
1187
|
-
});
|
|
1188
|
-
return { pins: active ? result : pins, active };
|
|
1189
|
-
}
|
|
1190
|
-
};
|
|
1191
|
-
|
|
1192
|
-
// src/deformation/cloth-surface.ts
|
|
1193
|
-
import { Vector3 as Vector36 } from "three";
|
|
1194
|
-
function clothSurfaceMotion(pins) {
|
|
1195
|
-
if (!pins.length) return { ...DEFAULT_MOTION };
|
|
1196
|
-
const values = pins.map((pin) => pin.motion ?? DEFAULT_MOTION);
|
|
1197
|
-
return {
|
|
1198
|
-
...DEFAULT_MOTION,
|
|
1199
|
-
damping: values.reduce((sum, motion) => sum + motion.damping, 0) / values.length,
|
|
1200
|
-
strength: values.reduce((sum, motion) => sum + motion.strength, 0) / values.length
|
|
1201
|
-
};
|
|
1202
|
-
}
|
|
1203
|
-
function distances(graph, seeds) {
|
|
1204
|
-
const distance = new Float64Array(graph.length).fill(Infinity);
|
|
1205
|
-
const heap = [];
|
|
1206
|
-
const push = (node, value) => {
|
|
1207
|
-
let i = heap.length;
|
|
1208
|
-
heap.push({ node, distance: value });
|
|
1209
|
-
while (i) {
|
|
1210
|
-
const parent = i - 1 >> 1;
|
|
1211
|
-
if (heap[parent].distance <= value) break;
|
|
1212
|
-
heap[i] = heap[parent];
|
|
1213
|
-
i = parent;
|
|
1214
|
-
}
|
|
1215
|
-
heap[i] = { node, distance: value };
|
|
1216
|
-
};
|
|
1217
|
-
const pop = () => {
|
|
1218
|
-
const top = heap[0], last = heap.pop();
|
|
1219
|
-
if (heap.length) {
|
|
1220
|
-
let i = 0;
|
|
1221
|
-
for (; ; ) {
|
|
1222
|
-
let child = i * 2 + 1;
|
|
1223
|
-
if (child >= heap.length) break;
|
|
1224
|
-
if (child + 1 < heap.length && heap[child + 1].distance < heap[child].distance) child++;
|
|
1225
|
-
if (last.distance <= heap[child].distance) break;
|
|
1226
|
-
heap[i] = heap[child];
|
|
1227
|
-
i = child;
|
|
1228
|
-
}
|
|
1229
|
-
heap[i] = last;
|
|
1230
|
-
}
|
|
1231
|
-
return top;
|
|
1232
|
-
};
|
|
1233
|
-
for (const seed of seeds) if (distance[seed] > 0) {
|
|
1234
|
-
distance[seed] = 0;
|
|
1235
|
-
push(seed, 0);
|
|
1236
|
-
}
|
|
1237
|
-
while (heap.length) {
|
|
1238
|
-
const next = pop();
|
|
1239
|
-
if (next.distance !== distance[next.node]) continue;
|
|
1240
|
-
for (const edge of graph[next.node]) {
|
|
1241
|
-
const value = next.distance + edge.length;
|
|
1242
|
-
if (value < distance[edge.to]) {
|
|
1243
|
-
distance[edge.to] = value;
|
|
1244
|
-
push(edge.to, value);
|
|
1245
|
-
}
|
|
1246
|
-
}
|
|
1247
|
-
}
|
|
1248
|
-
return distance;
|
|
1249
|
-
}
|
|
1250
|
-
var ClothSurface = class {
|
|
1251
|
-
particles;
|
|
1252
|
-
vertexParticle;
|
|
1253
|
-
triangles;
|
|
1254
|
-
edges;
|
|
1255
|
-
scale;
|
|
1256
|
-
time = 0;
|
|
1257
|
-
constructor(restVertices, indices, pins) {
|
|
1258
|
-
const vertexCount = restVertices.length / 3;
|
|
1259
|
-
const min = new Vector36(Infinity, Infinity, Infinity), max = new Vector36(-Infinity, -Infinity, -Infinity);
|
|
1260
|
-
for (let i = 0; i < vertexCount; i++) {
|
|
1261
|
-
const p = new Vector36().fromArray(restVertices, i * 3);
|
|
1262
|
-
min.min(p);
|
|
1263
|
-
max.max(p);
|
|
1264
|
-
}
|
|
1265
|
-
this.scale = Math.max(1e-4, max.clone().sub(min).length());
|
|
1266
|
-
const tolerance = this.scale * 1e-6;
|
|
1267
|
-
const welded = /* @__PURE__ */ new Map(), particles = [];
|
|
1268
|
-
this.vertexParticle = new Uint32Array(vertexCount);
|
|
1269
|
-
for (let i = 0; i < vertexCount; i++) {
|
|
1270
|
-
const p = new Vector36().fromArray(restVertices, i * 3);
|
|
1271
|
-
const key = p.toArray().map((value) => Math.round(value / tolerance)).join(",");
|
|
1272
|
-
let node = welded.get(key);
|
|
1273
|
-
if (node === void 0) {
|
|
1274
|
-
node = particles.length;
|
|
1275
|
-
welded.set(key, node);
|
|
1276
|
-
particles.push({ position: p.clone(), previous: p.clone(), base: p, share: 0, anchor: 0 });
|
|
1277
|
-
}
|
|
1278
|
-
this.vertexParticle[i] = node;
|
|
1279
|
-
}
|
|
1280
|
-
const edgeMap = /* @__PURE__ */ new Map();
|
|
1281
|
-
const graph = particles.map(() => []);
|
|
1282
|
-
const triangles = [];
|
|
1283
|
-
const edge = (a, b, opposite) => {
|
|
1284
|
-
if (a === b) return;
|
|
1285
|
-
const key = a < b ? `${a}:${b}` : `${b}:${a}`;
|
|
1286
|
-
const existing = edgeMap.get(key);
|
|
1287
|
-
if (existing) existing.opposites.push(opposite);
|
|
1288
|
-
else edgeMap.set(key, { a, b, opposites: [opposite] });
|
|
1289
|
-
};
|
|
1290
|
-
for (let i = 0; i + 2 < indices.length; i += 3) {
|
|
1291
|
-
const a = this.vertexParticle[indices[i]], b = this.vertexParticle[indices[i + 1]], c = this.vertexParticle[indices[i + 2]];
|
|
1292
|
-
if (a === b || b === c || c === a) continue;
|
|
1293
|
-
triangles.push({ a, b, c });
|
|
1294
|
-
edge(a, b, c);
|
|
1295
|
-
edge(b, c, a);
|
|
1296
|
-
edge(c, a, b);
|
|
1297
|
-
}
|
|
1298
|
-
this.triangles = triangles;
|
|
1299
|
-
const edges = [];
|
|
1300
|
-
for (const value of edgeMap.values()) {
|
|
1301
|
-
const length = particles[value.a].base.distanceTo(particles[value.b].base);
|
|
1302
|
-
edges.push({ a: value.a, b: value.b, length, bend: false });
|
|
1303
|
-
graph[value.a].push({ to: value.b, length });
|
|
1304
|
-
graph[value.b].push({ to: value.a, length });
|
|
1305
|
-
if (value.opposites.length === 2 && value.opposites[0] !== value.opposites[1]) {
|
|
1306
|
-
const a = value.opposites[0], b = value.opposites[1];
|
|
1307
|
-
edges.push({ a, b, length: particles[a].base.distanceTo(particles[b].base), bend: true });
|
|
1308
|
-
}
|
|
1309
|
-
}
|
|
1310
|
-
this.edges = edges;
|
|
1311
|
-
const nearest = (point2) => {
|
|
1312
|
-
const p = new Vector36().fromArray(point2);
|
|
1313
|
-
let found = 0, best = Infinity;
|
|
1314
|
-
for (let i = 0; i < particles.length; i++) {
|
|
1315
|
-
const d = particles[i].base.distanceToSquared(p);
|
|
1316
|
-
if (d < best) {
|
|
1317
|
-
best = d;
|
|
1318
|
-
found = i;
|
|
1319
|
-
}
|
|
1320
|
-
}
|
|
1321
|
-
return found;
|
|
1322
|
-
};
|
|
1323
|
-
const cloth = pins.filter((pin) => pin.cloth && !pin.guide).map((pin) => nearest(pin.rest));
|
|
1324
|
-
const body = pins.filter((pin) => !pin.cloth && !pin.guide).map((pin) => nearest(pin.rest));
|
|
1325
|
-
const clothDistance = distances(graph, cloth), bodyDistance = distances(graph, body);
|
|
1326
|
-
for (let i = 0; i < particles.length; i++) {
|
|
1327
|
-
const a = clothDistance[i], b = bodyDistance[i];
|
|
1328
|
-
particles[i].share = Number.isFinite(a) && Number.isFinite(b) ? b / Math.max(1e-6, a + b) : Number.isFinite(a) ? 1 : 0;
|
|
1329
|
-
particles[i].anchor = Number.isFinite(b) ? Math.exp(-b / (0.12 * this.scale)) : 0;
|
|
1330
|
-
}
|
|
1331
|
-
this.particles = particles;
|
|
1332
|
-
}
|
|
1333
|
-
get movableCount() {
|
|
1334
|
-
return this.particles.filter((p) => p.share > 0.25).length;
|
|
1335
|
-
}
|
|
1336
|
-
reset() {
|
|
1337
|
-
this.time = 0;
|
|
1338
|
-
for (const particle of this.particles) particle.position.copy(particle.base), particle.previous.copy(particle.base);
|
|
1339
|
-
}
|
|
1340
|
-
step(baseVertices, seconds, windStrength, colliders = [], motion = DEFAULT_MOTION) {
|
|
1341
|
-
const count = this.particles.length, base = Array.from({ length: count }, () => new Vector36()), samples = new Uint32Array(count);
|
|
1342
|
-
for (let i = 0; i < this.vertexParticle.length; i++) {
|
|
1343
|
-
const node = this.vertexParticle[i];
|
|
1344
|
-
base[node].add(new Vector36().fromArray(baseVertices, i * 3));
|
|
1345
|
-
samples[node]++;
|
|
1346
|
-
}
|
|
1347
|
-
for (let i = 0; i < count; i++) {
|
|
1348
|
-
base[i].divideScalar(samples[i] || 1);
|
|
1349
|
-
const particle = this.particles[i], delta = base[i].clone().sub(particle.base);
|
|
1350
|
-
particle.position.add(delta);
|
|
1351
|
-
particle.previous.add(delta);
|
|
1352
|
-
particle.base.copy(base[i]);
|
|
1353
|
-
}
|
|
1354
|
-
const dt = Math.min(Math.max(seconds, 0), 0.05), steps = Math.max(1, Math.ceil(dt * 60)), h = dt / steps;
|
|
1355
|
-
const profile = windProfile(windStrength), pressureScale = profile.load ? 0.025 * profile.surfaceLoad / profile.load : 0;
|
|
1356
|
-
const radius = Math.max(1e-4, ...colliders.map((collider) => collider.radius));
|
|
1357
|
-
const cell = radius * 2;
|
|
1358
|
-
const bins = /* @__PURE__ */ new Map();
|
|
1359
|
-
const key = (x, y, z) => Math.imul(x, 73856093) ^ Math.imul(y, 19349663) ^ Math.imul(z, 83492791) | 0;
|
|
1360
|
-
for (const collider of colliders) {
|
|
1361
|
-
const p = collider.position, id = key(Math.floor(p[0] / cell), Math.floor(p[1] / cell), Math.floor(p[2] / cell));
|
|
1362
|
-
const bin = bins.get(id) ?? [];
|
|
1363
|
-
bin.push(collider);
|
|
1364
|
-
bins.set(id, bin);
|
|
1365
|
-
}
|
|
1366
|
-
for (let step = 0; step < steps && h > 0; step++) {
|
|
1367
|
-
this.time += h;
|
|
1368
|
-
const force = Array.from({ length: count }, () => new Vector36());
|
|
1369
|
-
const area = new Float32Array(count);
|
|
1370
|
-
if (pressureScale && motion.strength) for (const triangle of this.triangles) {
|
|
1371
|
-
const a = this.particles[triangle.a].position, b = this.particles[triangle.b].position, c = this.particles[triangle.c].position;
|
|
1372
|
-
const normal = b.clone().sub(a).cross(c.clone().sub(a));
|
|
1373
|
-
const surface = normal.length();
|
|
1374
|
-
if (surface < 1e-10) continue;
|
|
1375
|
-
normal.divideScalar(surface);
|
|
1376
|
-
const center = a.clone().add(b).add(c).divideScalar(3);
|
|
1377
|
-
const wind = windAcceleration(this.time, windStrength, this.scale, center.toArray());
|
|
1378
|
-
const pressure = normal.multiplyScalar(wind.dot(normal)).addScaledVector(wind, 0.12).multiplyScalar(pressureScale);
|
|
1379
|
-
for (const node of [triangle.a, triangle.b, triangle.c]) {
|
|
1380
|
-
force[node].addScaledVector(pressure, surface);
|
|
1381
|
-
area[node] += surface;
|
|
1382
|
-
}
|
|
1383
|
-
}
|
|
1384
|
-
for (let i = 0; i < count; i++) {
|
|
1385
|
-
const particle = this.particles[i], share = particle.share;
|
|
1386
|
-
if (share < 1e-4) {
|
|
1387
|
-
particle.position.copy(particle.base);
|
|
1388
|
-
particle.previous.copy(particle.base);
|
|
1389
|
-
continue;
|
|
1390
|
-
}
|
|
1391
|
-
const velocity = particle.position.clone().sub(particle.previous).multiplyScalar(Math.exp(-motion.damping * 3 * h));
|
|
1392
|
-
particle.previous.copy(particle.position);
|
|
1393
|
-
particle.position.add(velocity).y -= 2.5 * this.scale * share * h * h;
|
|
1394
|
-
if (area[i]) particle.position.addScaledVector(force[i], motion.strength * share * h * h / area[i]);
|
|
1395
|
-
const anchor = 1 - Math.exp(-(1.5 + 60 * particle.anchor ** 2) * h);
|
|
1396
|
-
particle.position.lerp(particle.base, anchor);
|
|
1397
|
-
}
|
|
1398
|
-
for (let iteration = 0; iteration < 5; iteration++) {
|
|
1399
|
-
for (const edge of this.edges) {
|
|
1400
|
-
const a = this.particles[edge.a], b = this.particles[edge.b];
|
|
1401
|
-
const difference = b.position.clone().sub(a.position), length = difference.length();
|
|
1402
|
-
if (length < 1e-8) continue;
|
|
1403
|
-
const wa = a.share * a.share, wb = b.share * b.share, total = wa + wb;
|
|
1404
|
-
if (total < 1e-8) continue;
|
|
1405
|
-
const strength = edge.bend ? 0.14 : 0.72;
|
|
1406
|
-
difference.multiplyScalar((length - edge.length) * strength / (length * total));
|
|
1407
|
-
a.position.addScaledVector(difference, wa);
|
|
1408
|
-
b.position.addScaledVector(difference, -wb);
|
|
1409
|
-
}
|
|
1410
|
-
}
|
|
1411
|
-
if (colliders.length) for (const particle of this.particles) {
|
|
1412
|
-
if (particle.share < 0.35) continue;
|
|
1413
|
-
const p = particle.position, px = p.x / cell, py = p.y / cell, pz = p.z / cell;
|
|
1414
|
-
const x = Math.floor(px), y = Math.floor(py), z = Math.floor(pz);
|
|
1415
|
-
const sx = px - x < 0.5 ? -1 : 1, sy = py - y < 0.5 ? -1 : 1, sz = pz - z < 0.5 ? -1 : 1;
|
|
1416
|
-
let chosen, penetration = 0;
|
|
1417
|
-
for (let iz = 0; iz < 2; iz++) for (let iy = 0; iy < 2; iy++) for (let ix = 0; ix < 2; ix++) {
|
|
1418
|
-
for (const collider of bins.get(key(x + ix * sx, y + iy * sy, z + iz * sz)) ?? []) {
|
|
1419
|
-
const center = collider.position, bx = particle.base.x - center[0], by = particle.base.y - center[1], bz = particle.base.z - center[2];
|
|
1420
|
-
if (bx * bx + by * by + bz * bz < collider.radius * collider.radius * 1.04) continue;
|
|
1421
|
-
const vx = p.x - center[0], vy = p.y - center[1], vz = p.z - center[2];
|
|
1422
|
-
const depth = collider.radius - Math.hypot(vx, vy, vz);
|
|
1423
|
-
if (depth > penetration) {
|
|
1424
|
-
penetration = depth;
|
|
1425
|
-
chosen = collider;
|
|
1426
|
-
}
|
|
1427
|
-
}
|
|
1428
|
-
}
|
|
1429
|
-
if (chosen) {
|
|
1430
|
-
const center = chosen.position, delta = p.clone().sub(new Vector36().fromArray(center));
|
|
1431
|
-
if (delta.lengthSq() < 1e-12) delta.copy(particle.base).sub(new Vector36().fromArray(center));
|
|
1432
|
-
p.copy(new Vector36().fromArray(center).add(delta.setLength(chosen.radius)));
|
|
1433
|
-
}
|
|
1434
|
-
}
|
|
1435
|
-
}
|
|
1436
|
-
const result = new Float32Array(baseVertices.length);
|
|
1437
|
-
for (let i = 0; i < this.vertexParticle.length; i++) result.set(this.particles[this.vertexParticle[i]].position.toArray(), i * 3);
|
|
1438
|
-
return result;
|
|
1439
|
-
}
|
|
1440
|
-
};
|
|
1441
|
-
|
|
1442
|
-
// src/deformation/rig-drivers.ts
|
|
1443
|
-
import { Matrix4 as Matrix42, Quaternion as Quaternion5, Vector3 as Vector37 } from "three";
|
|
1444
|
-
var matrix = (pose2) => new Matrix42().compose(new Vector37().fromArray(pose2.position), new Quaternion5().fromArray(pose2.rotation), new Vector37().fromArray(pose2.scale));
|
|
1445
|
-
function driverDelta(driver, pins, reference) {
|
|
1446
|
-
const affine = new Matrix42();
|
|
1447
|
-
affine.elements.fill(0);
|
|
1448
|
-
const rotation = new Quaternion5(0, 0, 0, 0), scale = new Vector37();
|
|
1449
|
-
let hemisphere;
|
|
1450
|
-
for (const influence of driver.influences) {
|
|
1451
|
-
const current = pins.find((p) => p.id === influence.id).pose, rest = reference.find((p) => p.id === influence.id).pose, w = influence.weight;
|
|
1452
|
-
const delta = matrix(current).multiply(matrix(rest).invert()), q = new Quaternion5().fromArray(current.rotation).multiply(new Quaternion5().fromArray(rest.rotation).invert());
|
|
1453
|
-
hemisphere ??= q;
|
|
1454
|
-
const sign = hemisphere.dot(q) < 0 ? -w : w;
|
|
1455
|
-
delta.elements.forEach((value, i) => affine.elements[i] += value * w);
|
|
1456
|
-
rotation.set(rotation.x + q.x * sign, rotation.y + q.y * sign, rotation.z + q.z * sign, rotation.w + q.w * sign);
|
|
1457
|
-
scale.addScaledVector(new Vector37().fromArray(current.scale).divide(new Vector37().fromArray(rest.scale)), w);
|
|
1458
|
-
}
|
|
1459
|
-
if (!driver.influences.length) {
|
|
1460
|
-
affine.identity();
|
|
1461
|
-
rotation.identity();
|
|
1462
|
-
scale.setScalar(1);
|
|
1463
|
-
}
|
|
1464
|
-
return { affine, rotation: rotation.normalize(), scale };
|
|
1465
|
-
}
|
|
1466
|
-
function drivenPose(pose2, driver, pins, reference) {
|
|
1467
|
-
const delta = driverDelta(driver, pins, reference);
|
|
1468
|
-
return { position: new Vector37().fromArray(pose2.position).applyMatrix4(delta.affine).toArray(), rotation: delta.rotation.multiply(new Quaternion5().fromArray(pose2.rotation)).normalize().toArray(), scale: delta.scale.multiply(new Vector37().fromArray(pose2.scale)).toArray() };
|
|
1469
|
-
}
|
|
1470
|
-
function referencePose(pose2, driver, pins, reference) {
|
|
1471
|
-
const delta = driverDelta(driver, pins, reference);
|
|
1472
|
-
if (Math.abs(delta.affine.determinant()) < 1e-10) throw new Error("This blended bone frame is singular. Adjust its driving bones before editing its position.");
|
|
1473
|
-
return { position: new Vector37().fromArray(pose2.position).applyMatrix4(delta.affine.invert()).toArray(), rotation: delta.rotation.invert().multiply(new Quaternion5().fromArray(pose2.rotation)).normalize().toArray(), scale: new Vector37().fromArray(pose2.scale).divide(delta.scale).toArray() };
|
|
1474
|
-
}
|
|
1475
|
-
function driveRig(pins, reference, drivers) {
|
|
1476
|
-
return pins.map((pin) => {
|
|
1477
|
-
const driver = drivers.find((d) => d.id === pin.id);
|
|
1478
|
-
return driver ? { ...pin, pose: drivenPose(pin.pose, driver, pins, reference) } : pin;
|
|
1479
|
-
});
|
|
1480
|
-
}
|
|
1481
|
-
|
|
1482
|
-
// src/deformation/fur-surface.ts
|
|
1483
|
-
import { BufferAttribute, MeshPhysicalMaterial, MeshStandardMaterial, SkinnedMesh } from "three";
|
|
1484
|
-
import { MeshPhysicalNodeMaterial, MeshStandardNodeMaterial } from "three/webgpu";
|
|
1485
|
-
import { attribute, float, mix, normalMap, positionLocal, texture, uniform, uv, varying, vec2, vec3, vec4 } from "three/tsl";
|
|
1486
|
-
var FurSurface = class {
|
|
1487
|
-
surfaces = [];
|
|
1488
|
-
height = null;
|
|
1489
|
-
clock = uniform(0);
|
|
1490
|
-
wind = uniform(0);
|
|
1491
|
-
constructor(scene, descriptor, nodes, helpers) {
|
|
1492
|
-
const depth = /* @__PURE__ */ new Map();
|
|
1493
|
-
descriptor.pins.forEach((pin, i) => depth.set(nodes[i], pin.fur ? pin.furDepth ?? 0.1 : 0));
|
|
1494
|
-
descriptor.helpers?.forEach((helper, i) => depth.set(helpers[i], helper.influences.reduce((sum, influence) => {
|
|
1495
|
-
const index = descriptor.joints.findIndex((joint) => joint.node === influence.node);
|
|
1496
|
-
const pin = descriptor.pins[index];
|
|
1497
|
-
return sum + (pin?.fur ? (pin.furDepth ?? 0.1) * influence.weight : 0);
|
|
1498
|
-
}, 0)));
|
|
1499
|
-
scene.traverse((object) => {
|
|
1500
|
-
if (!(object instanceof SkinnedMesh)) return;
|
|
1501
|
-
const geometry = object.geometry, indices = geometry.getAttribute("skinIndex"), weights = geometry.getAttribute("skinWeight");
|
|
1502
|
-
if (!indices || !weights || !geometry.getAttribute("uv") || !geometry.getAttribute("normal")) return;
|
|
1503
|
-
if ((Array.isArray(object.material) ? object.material : [object.material]).some((material) => !(material instanceof MeshStandardMaterial))) return;
|
|
1504
|
-
const values = new Float32Array(indices.count);
|
|
1505
|
-
for (let v = 0; v < values.length; v++) for (let lane = 0; lane < 4; lane++) {
|
|
1506
|
-
values[v] += (depth.get(object.skeleton.bones[indices.getComponent(v, lane)]) ?? 0) * weights.getComponent(v, lane);
|
|
1507
|
-
}
|
|
1508
|
-
if (!values.some((value) => value > 1e-5)) return;
|
|
1509
|
-
const modified = geometry.clone();
|
|
1510
|
-
modified.setAttribute("furDepth", new BufferAttribute(values, 1));
|
|
1511
|
-
const surface = { mesh: object, geometry, modified, material: object.material, variants: [] };
|
|
1512
|
-
object.geometry = modified;
|
|
1513
|
-
this.surfaces.push(surface);
|
|
1514
|
-
});
|
|
1515
|
-
this.rebuild();
|
|
1516
|
-
}
|
|
1517
|
-
setHeightMap(height) {
|
|
1518
|
-
if (this.height !== height) {
|
|
1519
|
-
this.height = height;
|
|
1520
|
-
this.rebuild();
|
|
1521
|
-
}
|
|
1522
|
-
}
|
|
1523
|
-
update(seconds, windStrength) {
|
|
1524
|
-
this.clock.value += Math.max(0, Math.min(seconds, 0.1));
|
|
1525
|
-
this.wind.value = windStrength;
|
|
1526
|
-
}
|
|
1527
|
-
/** GLTFExporter must only see standard portable materials and attributes. */
|
|
1528
|
-
setPortable(portable) {
|
|
1529
|
-
for (const surface of this.surfaces) {
|
|
1530
|
-
surface.mesh.geometry = portable ? surface.geometry : surface.modified;
|
|
1531
|
-
surface.mesh.material = portable ? surface.material : Array.isArray(surface.material) ? surface.variants : surface.variants[0];
|
|
1532
|
-
}
|
|
1533
|
-
}
|
|
1534
|
-
dispose() {
|
|
1535
|
-
this.setPortable(true);
|
|
1536
|
-
for (const surface of this.surfaces) {
|
|
1537
|
-
surface.modified.dispose();
|
|
1538
|
-
surface.mesh.geometry = surface.geometry;
|
|
1539
|
-
for (const variant of surface.variants) variant.dispose();
|
|
1540
|
-
}
|
|
1541
|
-
this.surfaces.length = 0;
|
|
1542
|
-
}
|
|
1543
|
-
rebuild() {
|
|
1544
|
-
for (const surface of this.surfaces) {
|
|
1545
|
-
const sources = Array.isArray(surface.material) ? surface.material : [surface.material];
|
|
1546
|
-
const variants = sources.map((source) => this.material(source));
|
|
1547
|
-
this.setPortable(true);
|
|
1548
|
-
for (const old of surface.variants) old.dispose();
|
|
1549
|
-
surface.variants = variants;
|
|
1550
|
-
}
|
|
1551
|
-
this.setPortable(false);
|
|
1552
|
-
}
|
|
1553
|
-
material(source) {
|
|
1554
|
-
const material = source instanceof MeshPhysicalMaterial ? new MeshPhysicalNodeMaterial() : new MeshStandardNodeMaterial();
|
|
1555
|
-
material.copy(source);
|
|
1556
|
-
material.name = `${source.name || "Material"} \xB7 Fur texture motion`;
|
|
1557
|
-
const coordinates = uv();
|
|
1558
|
-
const signal = source.map ?? source.normalMap ?? source.roughnessMap ?? source.metalnessMap ?? source.emissiveMap ?? source.aoMap ?? source.alphaMap ?? this.height;
|
|
1559
|
-
if (!signal) return material;
|
|
1560
|
-
const depth = attribute("furDepth", "float").mul(5).clamp(0, 1);
|
|
1561
|
-
const skinnedDelta = varying(positionLocal.sub(attribute("position", "vec3")), "furSkinDelta");
|
|
1562
|
-
const dimensions = signal.image;
|
|
1563
|
-
const pixel = vec2(1 / Math.max(1, dimensions?.width ?? 1024), 1 / Math.max(1, dimensions?.height ?? 1024));
|
|
1564
|
-
const movement = projectMotionToUv(skinnedDelta, coordinates).clamp(pixel.mul(-1.5), pixel.mul(1.5));
|
|
1565
|
-
const height = this.height ? texture(this.height, uv(this.height.channel)).r : float(0.5);
|
|
1566
|
-
const raised = mix(0.65, 1.35, height);
|
|
1567
|
-
const phase = coordinates.dot(vec2(31, 43)).add(height.sub(0.5).mul(2.4)).add(this.clock.mul(this.wind).mul(1.7));
|
|
1568
|
-
const gust = vec2(phase.sin(), phase.mul(1.31).cos()).mul(pixel).mul(this.wind.mul(0.65));
|
|
1569
|
-
const shift = movement.add(gust).mul(depth).mul(raised).clamp(pixel.mul(-2), pixel.mul(2)).toVar("furTextureShift");
|
|
1570
|
-
const sample = (map) => {
|
|
1571
|
-
const node = texture(map, uv(map.channel).add(shift));
|
|
1572
|
-
node.updateMatrix = true;
|
|
1573
|
-
return node;
|
|
1574
|
-
};
|
|
1575
|
-
const base = source.map ? sample(source.map) : vec4(1);
|
|
1576
|
-
material.colorNode = base.mul(vec4(source.color.r, source.color.g, source.color.b, 1));
|
|
1577
|
-
if (source.alphaMap) material.opacityNode = sample(source.alphaMap).g;
|
|
1578
|
-
if (source.normalMap) material.normalNode = normalMap(
|
|
1579
|
-
sample(source.normalMap).xyz,
|
|
1580
|
-
vec2(source.normalScale.x, source.normalScale.y)
|
|
1581
|
-
);
|
|
1582
|
-
material.roughnessNode = source.roughnessMap ? sample(source.roughnessMap).g.mul(source.roughness) : float(source.roughness);
|
|
1583
|
-
material.metalnessNode = source.metalnessMap ? sample(source.metalnessMap).b.mul(source.metalness) : float(source.metalness);
|
|
1584
|
-
if (source.aoMap) material.aoNode = float(1).sub(float(1).sub(sample(source.aoMap).r).mul(source.aoMapIntensity));
|
|
1585
|
-
if (source.emissiveMap) material.emissiveNode = sample(source.emissiveMap).rgb.mul(vec3(
|
|
1586
|
-
source.emissive.r * source.emissiveIntensity,
|
|
1587
|
-
source.emissive.g * source.emissiveIntensity,
|
|
1588
|
-
source.emissive.b * source.emissiveIntensity
|
|
1589
|
-
));
|
|
1590
|
-
material.userData.furSurface = { heightMapped: Boolean(this.height), motionMapped: true };
|
|
1591
|
-
return material;
|
|
1592
|
-
}
|
|
1593
|
-
};
|
|
1594
|
-
function projectMotionToUv(movement, coordinates) {
|
|
1595
|
-
const dUvDx = coordinates.dFdx(), dUvDy = coordinates.dFdy();
|
|
1596
|
-
const dPosDx = positionLocal.dFdx(), dPosDy = positionLocal.dFdy();
|
|
1597
|
-
const determinant = dUvDx.x.mul(dUvDy.y).sub(dUvDx.y.mul(dUvDy.x));
|
|
1598
|
-
const safe = determinant.abs().max(1e-10).mul(determinant.lessThan(0).select(-1, 1));
|
|
1599
|
-
const dPosDu = dPosDx.mul(dUvDy.y).sub(dPosDy.mul(dUvDx.y)).div(safe);
|
|
1600
|
-
const dPosDv = dPosDy.mul(dUvDx.x).sub(dPosDx.mul(dUvDx.y)).div(safe);
|
|
1601
|
-
const uu = dPosDu.dot(dPosDu), vv = dPosDv.dot(dPosDv), uvMetric = dPosDu.dot(dPosDv);
|
|
1602
|
-
const metric = uu.mul(vv).sub(uvMetric.mul(uvMetric)).max(1e-12);
|
|
1603
|
-
const u = movement.dot(dPosDu), v = movement.dot(dPosDv);
|
|
1604
|
-
return vec2(vv.mul(u).sub(uvMetric.mul(v)).div(metric), uu.mul(v).sub(uvMetric.mul(u)).div(metric));
|
|
1605
|
-
}
|
|
1606
|
-
|
|
1607
|
-
// src/deformation/rig-runtime.ts
|
|
1608
|
-
var runtimes = /* @__PURE__ */ new WeakMap();
|
|
1609
|
-
var matrix2 = (pose2) => new Matrix43().compose(new Vector38().fromArray(pose2.position), new Quaternion6().fromArray(pose2.rotation), new Vector38().fromArray(pose2.scale));
|
|
1610
|
-
function pose(matrix3) {
|
|
1611
|
-
const p = new Vector38(), q = new Quaternion6(), s = new Vector38();
|
|
1612
|
-
matrix3.decompose(p, q, s);
|
|
1613
|
-
return { position: p.toArray(), rotation: q.normalize().toArray(), scale: s.toArray() };
|
|
1614
|
-
}
|
|
1615
|
-
var DeformationRigRuntime = class {
|
|
1616
|
-
constructor(scene, descriptor, nodes, clips, helperNodes = []) {
|
|
1617
|
-
this.scene = scene;
|
|
1618
|
-
this.descriptor = descriptor;
|
|
1619
|
-
this.clips = clips;
|
|
1620
|
-
this.base = descriptor.pins;
|
|
1621
|
-
this.displayed = this.base;
|
|
1622
|
-
this.activePose = descriptor.activePose;
|
|
1623
|
-
this.windStrength = descriptor.windStrength ?? 0;
|
|
1624
|
-
descriptor.joints.forEach((joint, i) => {
|
|
1625
|
-
const pin = descriptor.pins[i];
|
|
1626
|
-
this.bones.set(pin.id, nodes[i]);
|
|
1627
|
-
this.masses.set(pin.id, joint.mass);
|
|
1628
|
-
if (joint.parent !== null) this.parents.set(pin.id, descriptor.pins[descriptor.joints.findIndex((j) => j.node === joint.parent)].id);
|
|
1629
|
-
if (pin.ik || pin.wiggle || pin.cloth || pin.fur) {
|
|
1630
|
-
const target = new Object3D();
|
|
1631
|
-
target.name = `${pin.id} target`;
|
|
1632
|
-
target.visible = false;
|
|
1633
|
-
scene.add(target);
|
|
1634
|
-
this.targets.set(pin.id, target);
|
|
1635
|
-
}
|
|
1636
|
-
});
|
|
1637
|
-
descriptor.helpers?.forEach((h, i) => this.helpers.push({ bone: helperNodes[i], influences: h.influences.map((w) => ({ id: descriptor.pins[descriptor.joints.findIndex((j) => j.node === w.node)].id, weight: w.weight })) }));
|
|
1638
|
-
if (descriptor.version >= 3) this.fittedDrivers = this.helpers.map((h) => ({ id: [...this.bones].find(([, bone]) => bone === h.bone)[0], influences: h.influences }));
|
|
1639
|
-
this.furSurface = descriptor.pins.some((pin) => pin.fur) ? new FurSurface(scene, descriptor, nodes, helperNodes) : null;
|
|
1640
|
-
this.mixer = new AnimationMixer(scene);
|
|
1641
|
-
const bones = [...this.bones.values()];
|
|
1642
|
-
const animated = clips.some((clip) => clip.tracks.some((track) => {
|
|
1643
|
-
const node = PropertyBinding.findNode(scene, PropertyBinding.parseTrackName(track.name).nodeName);
|
|
1644
|
-
return bones.some((bone) => bone === node);
|
|
1645
|
-
}));
|
|
1646
|
-
if (animated) for (const bone of bones) this.animationFrames.set(bone, this.localFrame(bone));
|
|
1647
|
-
this.selectPose(this.activePose);
|
|
1648
|
-
if (descriptor.pins.some((pin) => pin.cloth)) this.prepareClothMeshes();
|
|
1649
|
-
}
|
|
1650
|
-
/** Stable pin IDs mapped to the glTF bone nodes. Edit a bone for FK. */
|
|
1651
|
-
bones = /* @__PURE__ */ new Map();
|
|
1652
|
-
/** Scene-local goal objects for IK and secondary controls. Move one before `update()`. */
|
|
1653
|
-
targets = /* @__PURE__ */ new Map();
|
|
1654
|
-
parents = /* @__PURE__ */ new Map();
|
|
1655
|
-
masses = /* @__PURE__ */ new Map();
|
|
1656
|
-
helpers = [];
|
|
1657
|
-
helperReferences = /* @__PURE__ */ new Map();
|
|
1658
|
-
referencePins = [];
|
|
1659
|
-
localFrames = /* @__PURE__ */ new Map();
|
|
1660
|
-
fittedDrivers = [];
|
|
1661
|
-
get drivers() {
|
|
1662
|
-
return this.fittedDrivers;
|
|
1663
|
-
}
|
|
1664
|
-
articulated(pins) {
|
|
1665
|
-
const helpers = new Set(this.drivers.map((d) => d.id));
|
|
1666
|
-
return pins.filter((p) => !helpers.has(p.id));
|
|
1667
|
-
}
|
|
1668
|
-
springs = new PinWiggle();
|
|
1669
|
-
cloth = new PinCloth();
|
|
1670
|
-
clothMeshes = [];
|
|
1671
|
-
furSurface;
|
|
1672
|
-
mixer;
|
|
1673
|
-
base;
|
|
1674
|
-
displayed;
|
|
1675
|
-
disposed = false;
|
|
1676
|
-
dirty = true;
|
|
1677
|
-
targetFrames = /* @__PURE__ */ new Map();
|
|
1678
|
-
editedTargets = /* @__PURE__ */ new Set();
|
|
1679
|
-
mixedPoseWeights = /* @__PURE__ */ new Map();
|
|
1680
|
-
mixingStaticPoses = false;
|
|
1681
|
-
animationFrames = /* @__PURE__ */ new Map();
|
|
1682
|
-
windStrength;
|
|
1683
|
-
activePose;
|
|
1684
|
-
/** Supply a Fur height atlas. The loader calls this for embedded atlases. */
|
|
1685
|
-
setFurHeightMap(texture2) {
|
|
1686
|
-
this.furSurface?.setHeightMap(texture2);
|
|
1687
|
-
}
|
|
1688
|
-
/** Keep ordinary glTF materials on renderers without the Fur node shader. */
|
|
1689
|
-
setPortableMaterials(portable) {
|
|
1690
|
-
this.furSurface?.setPortable(portable);
|
|
1691
|
-
}
|
|
1692
|
-
/** Joint records in the last displayed frame, including secondary motion. */
|
|
1693
|
-
get pins() {
|
|
1694
|
-
return this.displayed;
|
|
1695
|
-
}
|
|
1696
|
-
/** Return stable pin IDs from the root of the selected chain to its endpoint. */
|
|
1697
|
-
chain(id) {
|
|
1698
|
-
return ikChain(this.articulated(this.base), this.parents, id, this.masses).map((p) => p.id);
|
|
1699
|
-
}
|
|
1700
|
-
/** Clear accumulated spring and Cloth motion after a pose or editor reset. */
|
|
1701
|
-
resetSecondary() {
|
|
1702
|
-
this.springs.reset();
|
|
1703
|
-
this.cloth.reset();
|
|
1704
|
-
for (const entry of this.clothMeshes) {
|
|
1705
|
-
entry.surface.reset();
|
|
1706
|
-
entry.elapsed = 0;
|
|
1707
|
-
}
|
|
1708
|
-
}
|
|
1709
|
-
prepareClothMeshes() {
|
|
1710
|
-
this.scene.updateWorldMatrix(true, true);
|
|
1711
|
-
const inverse = this.scene.matrixWorld.clone().invert();
|
|
1712
|
-
const candidates = [];
|
|
1713
|
-
this.scene.traverse((object) => {
|
|
1714
|
-
if (!(object instanceof SkinnedMesh2)) return;
|
|
1715
|
-
const mesh = object, position = mesh.geometry.getAttribute("position");
|
|
1716
|
-
if (!position) return;
|
|
1717
|
-
const original = mesh.geometry, positions = new Float32Array(position.count * 3), rest = new Float32Array(position.count * 3);
|
|
1718
|
-
for (let i = 0; i < position.count; i++) {
|
|
1719
|
-
const point2 = new Vector38().fromBufferAttribute(position, i);
|
|
1720
|
-
positions.set(point2.toArray(), i * 3);
|
|
1721
|
-
rest.set(mesh.applyBoneTransform(i, point2).applyMatrix4(mesh.matrixWorld).applyMatrix4(inverse).toArray(), i * 3);
|
|
1722
|
-
}
|
|
1723
|
-
candidates.push({
|
|
1724
|
-
mesh,
|
|
1725
|
-
original,
|
|
1726
|
-
positions,
|
|
1727
|
-
rest,
|
|
1728
|
-
indices: original.index?.array ?? Uint32Array.from({ length: position.count }, (_, i) => i)
|
|
1729
|
-
});
|
|
1730
|
-
});
|
|
1731
|
-
const assigned = /* @__PURE__ */ new Map();
|
|
1732
|
-
for (const pin of this.descriptor.pins.filter((record2) => record2.cloth && !record2.guide)) {
|
|
1733
|
-
const point2 = new Vector38().fromArray(pin.pose.position);
|
|
1734
|
-
let best = Infinity, owner = null;
|
|
1735
|
-
for (const candidate of candidates) for (let i = 0; i < candidate.rest.length; i += 3) {
|
|
1736
|
-
const dx = candidate.rest[i] - point2.x, dy = candidate.rest[i + 1] - point2.y, dz = candidate.rest[i + 2] - point2.z;
|
|
1737
|
-
const distance = dx * dx + dy * dy + dz * dz;
|
|
1738
|
-
if (distance < best) {
|
|
1739
|
-
best = distance;
|
|
1740
|
-
owner = candidate.mesh;
|
|
1741
|
-
}
|
|
1742
|
-
}
|
|
1743
|
-
if (owner) assigned.set(owner, [...assigned.get(owner) ?? [], pin]);
|
|
1744
|
-
}
|
|
1745
|
-
for (const candidate of candidates) {
|
|
1746
|
-
const cloth = assigned.get(candidate.mesh);
|
|
1747
|
-
if (!cloth?.length) continue;
|
|
1748
|
-
const fitted = new Set(this.drivers.map((driver) => driver.id));
|
|
1749
|
-
const pins = [...this.descriptor.pins.filter((pin) => !pin.cloth && !pin.guide && !fitted.has(pin.id)), ...cloth].map((pin) => ({ ...pin, rest: pin.pose.position }));
|
|
1750
|
-
candidate.mesh.geometry = candidate.original.clone();
|
|
1751
|
-
this.clothMeshes.push({
|
|
1752
|
-
mesh: candidate.mesh,
|
|
1753
|
-
original: candidate.original,
|
|
1754
|
-
positions: candidate.positions,
|
|
1755
|
-
surface: new ClothSurface(candidate.rest, candidate.indices, pins),
|
|
1756
|
-
clothIds: cloth.map((pin) => pin.id),
|
|
1757
|
-
elapsed: 0
|
|
1758
|
-
});
|
|
1759
|
-
}
|
|
1760
|
-
}
|
|
1761
|
-
updateClothMeshes(seconds, colliders) {
|
|
1762
|
-
if (!this.clothMeshes.length) return;
|
|
1763
|
-
this.scene.updateWorldMatrix(true, true);
|
|
1764
|
-
const sceneInverse = this.scene.matrixWorld.clone().invert();
|
|
1765
|
-
for (const entry of this.clothMeshes) {
|
|
1766
|
-
entry.elapsed += Math.max(0, seconds);
|
|
1767
|
-
if (entry.elapsed < 1 / 30) continue;
|
|
1768
|
-
const step = Math.min(entry.elapsed, 0.05);
|
|
1769
|
-
entry.elapsed = 0;
|
|
1770
|
-
const { mesh, positions, surface } = entry, target = mesh.geometry.getAttribute("position");
|
|
1771
|
-
mesh.skeleton.update();
|
|
1772
|
-
const base = new Float32Array(positions.length);
|
|
1773
|
-
for (let i = 0; i < positions.length / 3; i++) {
|
|
1774
|
-
const point2 = new Vector38().fromArray(positions, i * 3);
|
|
1775
|
-
base.set(mesh.applyBoneTransform(i, point2).applyMatrix4(mesh.matrixWorld).applyMatrix4(sceneInverse).toArray(), i * 3);
|
|
1776
|
-
}
|
|
1777
|
-
const moved = surface.step(
|
|
1778
|
-
base,
|
|
1779
|
-
step,
|
|
1780
|
-
this.windStrength,
|
|
1781
|
-
colliders,
|
|
1782
|
-
clothSurfaceMotion(this.base.filter((pin) => entry.clothIds.includes(pin.id)))
|
|
1783
|
-
);
|
|
1784
|
-
const skinIndex = mesh.geometry.getAttribute("skinIndex"), skinWeight = mesh.geometry.getAttribute("skinWeight");
|
|
1785
|
-
const meshInverse = mesh.matrixWorld.clone().invert().multiply(this.scene.matrixWorld);
|
|
1786
|
-
const bone = new Matrix43(), blended = new Matrix43(), skin = new Matrix43();
|
|
1787
|
-
for (let i = 0; i < positions.length / 3; i++) {
|
|
1788
|
-
const elements = blended.elements;
|
|
1789
|
-
elements.fill(0);
|
|
1790
|
-
for (let j = 0; j < 4; j++) {
|
|
1791
|
-
const weight = skinWeight.getComponent(i, j);
|
|
1792
|
-
if (!weight) continue;
|
|
1793
|
-
bone.fromArray(mesh.skeleton.boneMatrices, skinIndex.getComponent(i, j) * 16);
|
|
1794
|
-
for (let k = 0; k < 16; k++) elements[k] += bone.elements[k] * weight;
|
|
1795
|
-
}
|
|
1796
|
-
skin.copy(mesh.bindMatrixInverse).multiply(blended).multiply(mesh.bindMatrix).invert();
|
|
1797
|
-
const local = new Vector38().fromArray(moved, i * 3).applyMatrix4(meshInverse).applyMatrix4(skin);
|
|
1798
|
-
target.setXYZ(i, local.x, local.y, local.z);
|
|
1799
|
-
}
|
|
1800
|
-
target.needsUpdate = true;
|
|
1801
|
-
mesh.geometry.computeVertexNormals();
|
|
1802
|
-
mesh.geometry.computeBoundingSphere();
|
|
1803
|
-
mesh.frustumCulled = false;
|
|
1804
|
-
}
|
|
1805
|
-
}
|
|
1806
|
-
/** Select an exported `Pose N` clip and reset its IK goals and secondary motion. */
|
|
1807
|
-
selectPose(slot) {
|
|
1808
|
-
const stored = slot === 0 ? this.descriptor.poseSlots.find((p) => p.slot === 0) ?? (this.descriptor.activePose === 0 ? restPoseSlot(this.descriptor.pins) : void 0) : definedPoses(this.descriptor).find((p) => p.slot === slot);
|
|
1809
|
-
if (!stored) throw new Error(`Pose ${slot} is not included in this GLB.`);
|
|
1810
|
-
this.mixer.stopAllAction();
|
|
1811
|
-
this.mixingStaticPoses = false;
|
|
1812
|
-
const clip = this.clips.find((c) => c.name === `Pose ${slot}`);
|
|
1813
|
-
if (clip) {
|
|
1814
|
-
this.mixer.clipAction(clip).play();
|
|
1815
|
-
this.mixer.update(0);
|
|
1816
|
-
}
|
|
1817
|
-
this.mixedPoseWeights = /* @__PURE__ */ new Map([[slot, 1]]);
|
|
1818
|
-
this.scene.updateWorldMatrix(true, true);
|
|
1819
|
-
const inverse = this.scene.matrixWorld.clone().invert();
|
|
1820
|
-
this.referencePins = resolvePose(this.descriptor.pins, stored, this.parents);
|
|
1821
|
-
this.helperReferences = new Map(this.helpers.map((h) => [h.bone, pose(inverse.clone().multiply(h.bone.matrixWorld))]));
|
|
1822
|
-
this.activePose = slot;
|
|
1823
|
-
this.resetSecondary();
|
|
1824
|
-
this.setPins(resolvePose(this.descriptor.pins, stored, this.parents));
|
|
1825
|
-
}
|
|
1826
|
-
get poseWeights() {
|
|
1827
|
-
return this.mixedPoseWeights;
|
|
1828
|
-
}
|
|
1829
|
-
/** Change the editable reference pose without interrupting secondary motion. */
|
|
1830
|
-
preparePose(slot) {
|
|
1831
|
-
const stored = slot === 0 ? this.descriptor.poseSlots.find((p) => p.slot === 0) ?? (this.descriptor.activePose === 0 ? restPoseSlot(this.descriptor.pins) : void 0) : definedPoses(this.descriptor).find((p) => p.slot === slot);
|
|
1832
|
-
if (!stored) throw new Error(`Pose ${slot} is not included in this GLB.`);
|
|
1833
|
-
this.referencePins = resolvePose(this.descriptor.pins, stored, this.parents);
|
|
1834
|
-
this.activePose = slot;
|
|
1835
|
-
}
|
|
1836
|
-
/** Mix the GLB's standard static pose clips, then simulate on that fitted frame. */
|
|
1837
|
-
previewPoseWeights(weights, seconds) {
|
|
1838
|
-
if (this.disposed) return;
|
|
1839
|
-
this.mixedPoseWeights = new Map(weights);
|
|
1840
|
-
const starting = !this.mixingStaticPoses;
|
|
1841
|
-
if (starting) {
|
|
1842
|
-
this.mixer.stopAllAction();
|
|
1843
|
-
for (const clip of this.clips) if (/^Pose \d+$/.test(clip.name)) this.mixer.clipAction(clip).play();
|
|
1844
|
-
this.mixingStaticPoses = true;
|
|
1845
|
-
}
|
|
1846
|
-
if (!starting) this.apply(this.base, true);
|
|
1847
|
-
for (const clip of this.clips) {
|
|
1848
|
-
const match = /^Pose (\d+)$/.exec(clip.name);
|
|
1849
|
-
if (match) this.mixer.clipAction(clip).setEffectiveWeight(weights.get(Number(match[1])) ?? 0);
|
|
1850
|
-
}
|
|
1851
|
-
this.mixer.update(0);
|
|
1852
|
-
this.scene.updateWorldMatrix(true, true);
|
|
1853
|
-
const inverse = this.scene.matrixWorld.clone().invert();
|
|
1854
|
-
const fitted = this.base.map((pin) => ({ ...pin, pose: pose(inverse.clone().multiply(this.bones.get(pin.id).matrixWorld)) }));
|
|
1855
|
-
this.base = fitted;
|
|
1856
|
-
this.dirty = false;
|
|
1857
|
-
this.rememberAnimationFrame();
|
|
1858
|
-
this.advanceSecondary(seconds, fitted);
|
|
1859
|
-
this.rememberDisplayedAnimationFrame();
|
|
1860
|
-
}
|
|
1861
|
-
/** Adapter for editors: authored state stays in the caller's action history. */
|
|
1862
|
-
setPins(pins) {
|
|
1863
|
-
if (pins.length !== this.bones.size || pins.some((p) => !this.bones.has(p.id))) throw new Error("Rig layout changed; rebuild the GLB.");
|
|
1864
|
-
if (this.mixingStaticPoses) {
|
|
1865
|
-
this.mixer.stopAllAction();
|
|
1866
|
-
this.mixingStaticPoses = false;
|
|
1867
|
-
}
|
|
1868
|
-
this.base = pins;
|
|
1869
|
-
this.dirty = false;
|
|
1870
|
-
this.editedTargets.clear();
|
|
1871
|
-
this.mixedPoseWeights = /* @__PURE__ */ new Map([[this.activePose, 1]]);
|
|
1872
|
-
for (const [id, target] of this.targets) if (!pins.some((p) => p.id === id && (p.ik || p.wiggle || p.cloth || p.fur) && !p.guide)) {
|
|
1873
|
-
target.removeFromParent();
|
|
1874
|
-
this.targets.delete(id);
|
|
1875
|
-
this.targetFrames.delete(id);
|
|
1876
|
-
}
|
|
1877
|
-
for (const pin of pins) {
|
|
1878
|
-
if (pin.guide || !pin.ik && !pin.wiggle && !pin.cloth && !pin.fur) continue;
|
|
1879
|
-
let target = this.targets.get(pin.id);
|
|
1880
|
-
if (!target) {
|
|
1881
|
-
target = new Object3D();
|
|
1882
|
-
target.name = `${pin.id} target`;
|
|
1883
|
-
target.visible = false;
|
|
1884
|
-
this.scene.add(target);
|
|
1885
|
-
this.targets.set(pin.id, target);
|
|
1886
|
-
}
|
|
1887
|
-
target.position.fromArray(pin.ikTarget?.position ?? pin.pose.position);
|
|
1888
|
-
target.quaternion.fromArray(pin.ikTarget?.rotation ?? pin.pose.rotation);
|
|
1889
|
-
this.targetFrames.set(pin.id, JSON.stringify([target.position.toArray(), target.quaternion.toArray()]));
|
|
1890
|
-
}
|
|
1891
|
-
this.apply(pins);
|
|
1892
|
-
this.rememberAnimationFrame();
|
|
1893
|
-
}
|
|
1894
|
-
/** Display a caller-supplied fitted frame. Workbench playback uses the clips. */
|
|
1895
|
-
previewPins(pins) {
|
|
1896
|
-
if (pins.length !== this.bones.size || pins.some((p) => !this.bones.has(p.id))) throw new Error("Rig layout changed; rebuild the GLB.");
|
|
1897
|
-
if (this.mixingStaticPoses) {
|
|
1898
|
-
this.mixer.stopAllAction();
|
|
1899
|
-
this.mixingStaticPoses = false;
|
|
1900
|
-
}
|
|
1901
|
-
this.base = pins;
|
|
1902
|
-
this.dirty = false;
|
|
1903
|
-
this.apply(pins, true);
|
|
1904
|
-
this.rememberAnimationFrame();
|
|
1905
|
-
}
|
|
1906
|
-
localFrame(bone) {
|
|
1907
|
-
return {
|
|
1908
|
-
position: bone.position.clone(),
|
|
1909
|
-
rotation: bone.quaternion.clone(),
|
|
1910
|
-
scale: bone.scale.clone(),
|
|
1911
|
-
displayedPosition: bone.position.clone(),
|
|
1912
|
-
displayedRotation: bone.quaternion.clone(),
|
|
1913
|
-
displayedScale: bone.scale.clone()
|
|
1914
|
-
};
|
|
1915
|
-
}
|
|
1916
|
-
rememberAnimationFrame() {
|
|
1917
|
-
for (const bone of this.animationFrames.keys()) this.animationFrames.set(bone, this.localFrame(bone));
|
|
1918
|
-
}
|
|
1919
|
-
/** PropertyMixer skips unchanged values. Recover their clip-only components
|
|
1920
|
-
* rather than feeding last frame's secondary motion back into animation. */
|
|
1921
|
-
animationFrame() {
|
|
1922
|
-
if (!this.animationFrames.size) return null;
|
|
1923
|
-
for (const [bone, frame] of this.animationFrames) {
|
|
1924
|
-
if (!bone.position.equals(frame.displayedPosition)) frame.position.copy(bone.position);
|
|
1925
|
-
if (!bone.quaternion.equals(frame.displayedRotation)) frame.rotation.copy(bone.quaternion);
|
|
1926
|
-
if (!bone.scale.equals(frame.displayedScale)) frame.scale.copy(bone.scale);
|
|
1927
|
-
bone.position.copy(frame.position);
|
|
1928
|
-
bone.quaternion.copy(frame.rotation);
|
|
1929
|
-
bone.scale.copy(frame.scale);
|
|
1930
|
-
}
|
|
1931
|
-
this.scene.updateWorldMatrix(true, true);
|
|
1932
|
-
const inverse = this.scene.matrixWorld.clone().invert();
|
|
1933
|
-
return this.base.map((pin) => ({ ...pin, pose: pose(inverse.clone().multiply(this.bones.get(pin.id).matrixWorld)) }));
|
|
1934
|
-
}
|
|
1935
|
-
rememberDisplayedAnimationFrame() {
|
|
1936
|
-
for (const [bone, frame] of this.animationFrames) {
|
|
1937
|
-
frame.displayedPosition.copy(bone.position);
|
|
1938
|
-
frame.displayedRotation.copy(bone.quaternion);
|
|
1939
|
-
frame.displayedScale.copy(bone.scale);
|
|
1940
|
-
}
|
|
1941
|
-
}
|
|
1942
|
-
apply(pins, fitted = false) {
|
|
1943
|
-
if (this.descriptor.version >= 3 && !fitted) pins = driveRig(pins, this.referencePins, this.drivers);
|
|
1944
|
-
this.scene.updateWorldMatrix(true, true);
|
|
1945
|
-
const desired = new Map(pins.map((p) => [this.bones.get(p.id), this.scene.matrixWorld.clone().multiply(matrix2(p.pose))]));
|
|
1946
|
-
const pending = new Set(desired.keys());
|
|
1947
|
-
const apply = (bone) => {
|
|
1948
|
-
if (!pending.has(bone)) return;
|
|
1949
|
-
if (bone.parent && pending.has(bone.parent)) apply(bone.parent);
|
|
1950
|
-
bone.parent?.updateWorldMatrix(true, false);
|
|
1951
|
-
const local = (bone.parent?.matrixWorld.clone() ?? new Matrix43()).invert().multiply(desired.get(bone));
|
|
1952
|
-
local.decompose(bone.position, bone.quaternion, bone.scale);
|
|
1953
|
-
bone.updateMatrix();
|
|
1954
|
-
bone.updateWorldMatrix(false, true);
|
|
1955
|
-
pending.delete(bone);
|
|
1956
|
-
};
|
|
1957
|
-
for (const bone of desired.keys()) apply(bone);
|
|
1958
|
-
const deltas = new Map(this.referencePins.map((reference) => {
|
|
1959
|
-
const current = pins.find((p) => p.id === reference.id).pose;
|
|
1960
|
-
return [reference.id, { matrix: matrix2(current).multiply(matrix2(reference.pose).invert()), rotation: new Quaternion6().fromArray(current.rotation).multiply(new Quaternion6().fromArray(reference.pose.rotation).invert()), scale: new Vector38().fromArray(current.scale).divide(new Vector38().fromArray(reference.pose.scale)) }];
|
|
1961
|
-
}));
|
|
1962
|
-
for (const helper of this.descriptor.version >= 3 ? [] : this.helpers) {
|
|
1963
|
-
const reference = this.helperReferences.get(helper.bone);
|
|
1964
|
-
const p = new Vector38(), q = new Quaternion6(0, 0, 0, 0), s = new Vector38(), ref = new Vector38().fromArray(reference.position);
|
|
1965
|
-
const hemisphere = helper.influences.length ? deltas.get(helper.influences[0].id).rotation : new Quaternion6();
|
|
1966
|
-
for (const influence of helper.influences) {
|
|
1967
|
-
const delta = deltas.get(influence.id), w = influence.weight;
|
|
1968
|
-
p.addScaledVector(ref.clone().applyMatrix4(delta.matrix), w);
|
|
1969
|
-
s.addScaledVector(delta.scale, w);
|
|
1970
|
-
const sign = hemisphere.dot(delta.rotation) < 0 ? -w : w;
|
|
1971
|
-
q.set(q.x + delta.rotation.x * sign, q.y + delta.rotation.y * sign, q.z + delta.rotation.z * sign, q.w + delta.rotation.w * sign);
|
|
1972
|
-
}
|
|
1973
|
-
if (!helper.influences.length) {
|
|
1974
|
-
p.copy(ref);
|
|
1975
|
-
q.identity();
|
|
1976
|
-
s.setScalar(1);
|
|
1977
|
-
}
|
|
1978
|
-
q.normalize().multiply(new Quaternion6().fromArray(reference.rotation));
|
|
1979
|
-
s.multiply(new Vector38().fromArray(reference.scale));
|
|
1980
|
-
const world = this.scene.matrixWorld.clone().multiply(new Matrix43().compose(p, q, s));
|
|
1981
|
-
helper.bone.parent?.updateWorldMatrix(true, false);
|
|
1982
|
-
const local = (helper.bone.parent?.matrixWorld.clone() ?? new Matrix43()).invert().multiply(world);
|
|
1983
|
-
local.decompose(helper.bone.position, helper.bone.quaternion, helper.bone.scale);
|
|
1984
|
-
helper.bone.updateWorldMatrix(false, true);
|
|
1985
|
-
}
|
|
1986
|
-
this.displayed = pins;
|
|
1987
|
-
for (const bone of this.bones.values()) {
|
|
1988
|
-
bone.updateMatrix();
|
|
1989
|
-
this.localFrames.set(bone, [...bone.matrix.elements]);
|
|
1990
|
-
}
|
|
1991
|
-
}
|
|
1992
|
-
/** Call after an external AnimationMixer/TransformControls, before rendering.
|
|
1993
|
-
* Targets are scene-local Object3Ds; moving an independent bone never moves them. */
|
|
1994
|
-
update(seconds) {
|
|
1995
|
-
if (this.disposed) return;
|
|
1996
|
-
const fitted = this.animationFrame();
|
|
1997
|
-
if (fitted) {
|
|
1998
|
-
this.base = fitted;
|
|
1999
|
-
this.displayed = fitted;
|
|
2000
|
-
this.dirty = false;
|
|
2001
|
-
} else this.furSurface?.update(seconds, this.windStrength);
|
|
2002
|
-
this.scene.updateWorldMatrix(true, true);
|
|
2003
|
-
const inverse = this.scene.matrixWorld.clone().invert();
|
|
2004
|
-
const edited = fitted ? this.base : this.base.map((pin, i) => {
|
|
2005
|
-
const driver = this.drivers.find((d) => d.id === pin.id);
|
|
2006
|
-
if (driver) {
|
|
2007
|
-
const bone = this.bones.get(pin.id);
|
|
2008
|
-
bone.updateMatrix();
|
|
2009
|
-
if (!bone.matrix.elements.some((v, k) => Math.abs(v - (this.localFrames.get(bone)?.[k] ?? v)) > 1e-6)) return pin;
|
|
2010
|
-
return { ...pin, pose: referencePose(pose(inverse.clone().multiply(bone.matrixWorld)), driver, this.base, this.referencePins) };
|
|
2011
|
-
}
|
|
2012
|
-
const current = pose(inverse.clone().multiply(this.bones.get(pin.id).matrixWorld));
|
|
2013
|
-
const previous = this.displayed[i].pose;
|
|
2014
|
-
const previousMatrix = matrix2(previous);
|
|
2015
|
-
const changed = matrix2(current).elements.some((v, k) => Math.abs(v - previousMatrix.elements[k]) > 1e-6);
|
|
2016
|
-
if (changed) this.dirty = true;
|
|
2017
|
-
return changed ? { ...pin, pose: current } : pin;
|
|
2018
|
-
});
|
|
2019
|
-
const bonesEdited = edited.some((p, i) => p !== this.base[i]);
|
|
2020
|
-
if (bonesEdited) this.base = edited;
|
|
2021
|
-
const movedTargets = /* @__PURE__ */ new Set();
|
|
2022
|
-
for (const [id, target] of this.targets) {
|
|
2023
|
-
const signature = JSON.stringify([target.position.toArray(), target.quaternion.toArray()]);
|
|
2024
|
-
if (this.targetFrames.get(id) !== signature) {
|
|
2025
|
-
movedTargets.add(id);
|
|
2026
|
-
this.dirty = true;
|
|
2027
|
-
this.targetFrames.set(id, signature);
|
|
2028
|
-
}
|
|
2029
|
-
}
|
|
2030
|
-
for (const id of movedTargets) this.editedTargets.add(id);
|
|
2031
|
-
const goalTargets = fitted ? this.editedTargets : movedTargets;
|
|
2032
|
-
if (fitted && goalTargets.size) this.dirty = true;
|
|
2033
|
-
for (const root of this.base.filter((p) => (p.wiggle || p.cloth || p.fur) && goalTargets.has(p.id) && !this.parents.has(p.id))) {
|
|
2034
|
-
const target = this.targets.get(root.id);
|
|
2035
|
-
const delta = matrix2({ ...root.pose, position: target.position.toArray(), rotation: target.quaternion.toArray() }).multiply(matrix2(root.pose).invert());
|
|
2036
|
-
const affected = /* @__PURE__ */ new Set([root.id]);
|
|
2037
|
-
for (let added = true; added; ) {
|
|
2038
|
-
added = false;
|
|
2039
|
-
for (const [child, parent] of this.parents) if (affected.has(parent) && !affected.has(child)) {
|
|
2040
|
-
affected.add(child);
|
|
2041
|
-
added = true;
|
|
2042
|
-
}
|
|
2043
|
-
}
|
|
2044
|
-
this.base = this.base.map((p) => affected.has(p.id) && !this.drivers.some((d) => d.id === p.id) ? { ...p, pose: pose(delta.clone().multiply(matrix2(p.pose))) } : p);
|
|
2045
|
-
}
|
|
2046
|
-
const goals = this.base.filter((p) => (p.ik || (p.wiggle || p.cloth || p.fur) && goalTargets.has(p.id)) && !p.guide && this.chain(p.id).length > 1).map((p) => {
|
|
2047
|
-
const target = this.targets.get(p.id);
|
|
2048
|
-
const goal = { id: p.id, position: target.position.toArray(), rotation: target.quaternion.toArray() };
|
|
2049
|
-
if (!fitted && (!p.ikTarget || goal.position.some((v, i) => Math.abs(v - p.ikTarget.position[i]) > 1e-8) || goal.rotation.some((v, i) => Math.abs(v - p.ikTarget.rotation[i]) > 1e-8))) this.dirty = true;
|
|
2050
|
-
return fitted && !goalTargets.has(p.id) ? { id: p.id, position: [...p.pose.position], rotation: [...p.pose.rotation] } : goal;
|
|
2051
|
-
});
|
|
2052
|
-
if (this.dirty) {
|
|
2053
|
-
const localGoal = !bonesEdited && goalTargets.size === 1 ? goals.find((g) => goalTargets.has(g.id)) : void 0;
|
|
2054
|
-
const articulated = this.articulated(this.base);
|
|
2055
|
-
const solved = new Map((localGoal ? solveLocalPinIK(articulated, this.parents, localGoal, this.masses) : solvePlantedPinIKGoals(articulated, this.parents, goals, this.masses, new Set(articulated.filter((p) => p.independent).map((p) => p.id)))).map((p) => [p.id, p.pose]));
|
|
2056
|
-
this.base = this.base.map((p) => ({ ...p, pose: solved.get(p.id) ?? p.pose, ikTarget: p.ik ? goals.find((g) => g.id === p.id) ?? p.ikTarget : p.ikTarget }));
|
|
2057
|
-
this.dirty = false;
|
|
2058
|
-
}
|
|
2059
|
-
if (fitted && !goalTargets.size && !fitted.some((pin) => pin.wiggle || pin.cloth || pin.fur)) {
|
|
2060
|
-
this.displayed = this.base;
|
|
2061
|
-
for (const bone of this.bones.values()) {
|
|
2062
|
-
bone.updateMatrix();
|
|
2063
|
-
this.localFrames.set(bone, [...bone.matrix.elements]);
|
|
2064
|
-
}
|
|
2065
|
-
} else this.advanceSecondary(seconds, fitted ?? void 0);
|
|
2066
|
-
this.rememberDisplayedAnimationFrame();
|
|
2067
|
-
}
|
|
2068
|
-
advanceSecondary(seconds, fitted) {
|
|
2069
|
-
if (fitted) this.furSurface?.update(seconds, this.windStrength);
|
|
2070
|
-
const secondary = this.springs.step(this.articulated(this.base), this.parents, seconds, this.masses, this.windStrength).pins;
|
|
2071
|
-
const byId = new Map(secondary.map((p) => [p.id, p]));
|
|
2072
|
-
const colliders = (this.descriptor.cloth?.colliders ?? []).map((collider) => {
|
|
2073
|
-
const driver = byId.get(collider.driver);
|
|
2074
|
-
if (!driver) return collider;
|
|
2075
|
-
const rest = { position: driver.rest, rotation: [0, 0, 0, 1], scale: [1, 1, 1] };
|
|
2076
|
-
const position = new Vector38().fromArray(collider.position).applyMatrix4(matrix2(driver.pose).multiply(matrix2(rest).invert()));
|
|
2077
|
-
return { ...collider, position: position.toArray() };
|
|
2078
|
-
});
|
|
2079
|
-
const cloth = this.cloth.step(secondary, this.parents, seconds, this.descriptor.cloth?.links ?? [], colliders, this.windStrength).pins;
|
|
2080
|
-
const displayed = this.base.map((p) => cloth.find((q) => q.id === p.id) ?? p);
|
|
2081
|
-
this.apply(fitted && this.descriptor.version >= 3 ? driveRig(displayed, fitted, this.drivers) : displayed, Boolean(fitted));
|
|
2082
|
-
this.updateClothMeshes(seconds, colliders);
|
|
2083
|
-
}
|
|
2084
|
-
dispose() {
|
|
2085
|
-
this.disposed = true;
|
|
2086
|
-
this.mixer.stopAllAction();
|
|
2087
|
-
this.mixer.uncacheRoot(this.scene);
|
|
2088
|
-
this.resetSecondary();
|
|
2089
|
-
this.furSurface?.dispose();
|
|
2090
|
-
for (const entry of this.clothMeshes) {
|
|
2091
|
-
entry.mesh.geometry.dispose();
|
|
2092
|
-
entry.mesh.geometry = entry.original;
|
|
2093
|
-
}
|
|
2094
|
-
this.clothMeshes = [];
|
|
2095
|
-
for (const target of this.targets.values()) target.removeFromParent();
|
|
2096
|
-
this.targets.clear();
|
|
2097
|
-
runtimes.delete(this.scene);
|
|
2098
|
-
}
|
|
2099
|
-
};
|
|
2100
|
-
var NeedleDeformationRigLoaderPlugin = class {
|
|
2101
|
-
constructor(parser) {
|
|
2102
|
-
this.parser = parser;
|
|
2103
|
-
}
|
|
2104
|
-
name = NEEDLE_DEFORMATION_RIG;
|
|
2105
|
-
async afterRoot(gltf) {
|
|
2106
|
-
const json = this.parser.json;
|
|
2107
|
-
for (const [i, scene] of gltf.scenes.entries()) {
|
|
2108
|
-
const raw = json.scenes?.[i]?.extensions?.[this.name];
|
|
2109
|
-
if (!raw) continue;
|
|
2110
|
-
const descriptor = parseRigDescriptor(raw, json.nodes?.length ?? 0, json.textures?.length ?? 0);
|
|
2111
|
-
const nodes = await Promise.all(descriptor.joints.map((j) => this.parser.getDependency("node", j.node)));
|
|
2112
|
-
const helpers = await Promise.all((descriptor.helpers ?? []).map((h) => this.parser.getDependency("node", h.node)));
|
|
2113
|
-
for (const node of [...nodes, ...helpers]) {
|
|
2114
|
-
let parent = node;
|
|
2115
|
-
while (parent && parent !== scene) parent = parent.parent;
|
|
2116
|
-
if (!parent) throw new Error("Rig bone is outside its scene.");
|
|
2117
|
-
}
|
|
2118
|
-
const runtime = new DeformationRigRuntime(scene, descriptor, nodes, gltf.animations, helpers);
|
|
2119
|
-
if (descriptor.furSurface) {
|
|
2120
|
-
const height = await this.parser.getDependency("texture", descriptor.furSurface.heightTexture);
|
|
2121
|
-
height.channel = descriptor.furSurface.texCoord ?? 0;
|
|
2122
|
-
runtime.setFurHeightMap(height);
|
|
2123
|
-
}
|
|
2124
|
-
runtimes.set(scene, runtime);
|
|
2125
|
-
}
|
|
2126
|
-
}
|
|
2127
|
-
};
|
|
2128
|
-
function registerNeedleDeformationRigLoader(loader) {
|
|
2129
|
-
loader.register((parser) => new NeedleDeformationRigLoaderPlugin(parser));
|
|
2130
|
-
return loader;
|
|
2131
|
-
}
|
|
2132
|
-
function getDeformationRig(scene) {
|
|
2133
|
-
return runtimes.get(scene);
|
|
2134
|
-
}
|
|
2135
|
-
export {
|
|
2136
|
-
DeformationRigRuntime,
|
|
2137
|
-
NEEDLE_DEFORMATION_RIG,
|
|
2138
|
-
NeedleDeformationRigLoaderPlugin,
|
|
2139
|
-
getDeformationRig,
|
|
2140
|
-
parseRigDescriptor,
|
|
2141
|
-
registerNeedleDeformationRigLoader
|
|
2142
|
-
};
|
|
2143
|
-
//# sourceMappingURL=deformation-runtime.js.map
|