Spaces:
Sleeping
Sleeping
File size: 8,005 Bytes
af60542 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 | import * as THREE from "three";
import {
GLTF,
GLTFLoaderPlugin,
GLTFParser,
} from "three/examples/jsm/loaders/GLTFLoader";
import { VRMAnimationLoaderPluginOptions } from "./VRMAnimationLoaderPluginOptions";
import { GLTF as GLTFSchema } from "@gltf-transform/core";
import { VRMCVRMAnimation } from "./VRMCVRMAnimation";
import { VRMHumanBoneName, VRMHumanBoneParentMap } from "@pixiv/three-vrm";
import { VRMAnimation } from "./VRMAnimation";
import { arrayChunk } from "./utils/arrayChunk";
const MAT4_IDENTITY = new THREE.Matrix4();
const _v3A = new THREE.Vector3();
const _quatA = new THREE.Quaternion();
const _quatB = new THREE.Quaternion();
const _quatC = new THREE.Quaternion();
interface VRMAnimationLoaderPluginNodeMap {
humanoidIndexToName: Map<number, VRMHumanBoneName>;
expressionsIndexToName: Map<number, string>;
lookAtIndex: number | null;
}
type VRMAnimationLoaderPluginWorldMatrixMap = Map<
VRMHumanBoneName | "hipsParent",
THREE.Matrix4
>;
export class VRMAnimationLoaderPlugin implements GLTFLoaderPlugin {
public readonly parser: GLTFParser;
public constructor(
parser: GLTFParser,
options?: VRMAnimationLoaderPluginOptions
) {
this.parser = parser;
}
public get name(): string {
return "VRMC_vrm_animation";
}
public async afterRoot(gltf: GLTF): Promise<void> {
const defGltf = gltf.parser.json as GLTFSchema.IGLTF;
const defExtensionsUsed = defGltf.extensionsUsed;
if (
defExtensionsUsed == null ||
defExtensionsUsed.indexOf(this.name) == -1
) {
return;
}
const defExtension = defGltf.extensions?.[this.name] as
| VRMCVRMAnimation
| undefined;
if (defExtension == null) {
return;
}
const nodeMap = this._createNodeMap(defExtension);
const worldMatrixMap = await this._createBoneWorldMatrixMap(
gltf,
defExtension
);
const hipsNode = defExtension.humanoid.humanBones["hips"]!.node;
const hips = (await gltf.parser.getDependency(
"node",
hipsNode
)) as THREE.Object3D;
const restHipsPosition = hips.getWorldPosition(new THREE.Vector3());
const clips = gltf.animations;
const animations: VRMAnimation[] = clips.map((clip, iAnimation) => {
const defAnimation = defGltf.animations![iAnimation];
const animation = this._parseAnimation(
clip,
defAnimation,
nodeMap,
worldMatrixMap
);
animation.restHipsPosition = restHipsPosition;
return animation;
});
gltf.userData.vrmAnimations = animations;
}
private _createNodeMap(
defExtension: VRMCVRMAnimation
): VRMAnimationLoaderPluginNodeMap {
const humanoidIndexToName: Map<number, VRMHumanBoneName> = new Map();
const expressionsIndexToName: Map<number, string> = new Map();
let lookAtIndex: number | null;
// humanoid
const humanBones = defExtension.humanoid?.humanBones;
if (humanBones) {
Object.entries(humanBones).forEach(([name, bone]) => {
const { node } = bone;
humanoidIndexToName.set(node, name as VRMHumanBoneName);
});
}
// expressions
const preset = defExtension.expressions?.preset;
if (preset) {
Object.entries(preset).forEach(([name, expression]) => {
const { node } = expression;
expressionsIndexToName.set(node, name as string);
});
}
const custom = defExtension.expressions?.custom;
if (custom) {
Object.entries(custom).forEach(([name, expression]) => {
const { node } = expression;
expressionsIndexToName.set(node, name as string);
});
}
// lookAt
lookAtIndex = defExtension.lookAt?.node ?? null;
return { humanoidIndexToName, expressionsIndexToName, lookAtIndex };
}
private async _createBoneWorldMatrixMap(
gltf: GLTF,
defExtension: VRMCVRMAnimation
): Promise<VRMAnimationLoaderPluginWorldMatrixMap> {
// update the entire hierarchy first
gltf.scene.updateWorldMatrix(false, true);
const threeNodes = (await gltf.parser.getDependencies(
"node"
)) as THREE.Object3D[];
const worldMatrixMap: VRMAnimationLoaderPluginWorldMatrixMap = new Map();
for (const [boneName, { node }] of Object.entries(
defExtension.humanoid.humanBones
)) {
const threeNode = threeNodes[node];
worldMatrixMap.set(boneName as VRMHumanBoneName, threeNode.matrixWorld);
if (boneName === "hips") {
worldMatrixMap.set(
"hipsParent",
threeNode.parent?.matrixWorld ?? MAT4_IDENTITY
);
}
}
return worldMatrixMap;
}
private _parseAnimation(
animationClip: THREE.AnimationClip,
defAnimation: GLTFSchema.IAnimation,
nodeMap: VRMAnimationLoaderPluginNodeMap,
worldMatrixMap: VRMAnimationLoaderPluginWorldMatrixMap
): VRMAnimation {
const tracks = animationClip.tracks;
const defChannels = defAnimation.channels;
const result = new VRMAnimation();
result.duration = animationClip.duration;
defChannels.forEach((channel, iChannel) => {
const { node, path } = channel.target;
const origTrack = tracks[iChannel];
if (node == null) {
return;
}
// humanoid
const boneName = nodeMap.humanoidIndexToName.get(node);
if (boneName != null) {
let parentBoneName: VRMHumanBoneName | "hipsParent" | null =
VRMHumanBoneParentMap[boneName];
while (
parentBoneName != null &&
worldMatrixMap.get(parentBoneName) == null
) {
parentBoneName = VRMHumanBoneParentMap[parentBoneName];
}
parentBoneName ??= "hipsParent";
if (path === "translation") {
const hipsParentWorldMatrix = worldMatrixMap.get("hipsParent")!;
const trackValues = arrayChunk(origTrack.values, 3).flatMap((v) =>
_v3A.fromArray(v).applyMatrix4(hipsParentWorldMatrix).toArray()
);
const track = origTrack.clone();
track.values = new Float32Array(trackValues);
result.humanoidTracks.translation.set(boneName, track);
} else if (path === "rotation") {
// a = p^-1 * a' * p * c
// a' = p * p^-1 * a' * p * c * c^-1 * p^-1
// = p * a * c^-1 * p^-1
const worldMatrix = worldMatrixMap.get(boneName)!;
const parentWorldMatrix = worldMatrixMap.get(parentBoneName)!;
_quatA.setFromRotationMatrix(worldMatrix).normalize().invert();
_quatB.setFromRotationMatrix(parentWorldMatrix).normalize();
const trackValues = arrayChunk(origTrack.values, 4).flatMap((q) =>
_quatC.fromArray(q).premultiply(_quatB).multiply(_quatA).toArray()
);
const track = origTrack.clone();
track.values = new Float32Array(trackValues);
result.humanoidTracks.rotation.set(boneName, track);
} else {
throw new Error(`Invalid path "${path}"`);
}
return;
}
// expressions
const expressionName = nodeMap.expressionsIndexToName.get(node);
if (expressionName != null) {
if (path === "translation") {
const times = origTrack.times;
const values = new Float32Array(origTrack.values.length / 3);
for (let i = 0; i < values.length; i++) {
values[i] = origTrack.values[3 * i];
}
const newTrack = new THREE.NumberKeyframeTrack(
`${expressionName}.weight`,
times as any,
values as any
);
result.expressionTracks.set(expressionName, newTrack);
} else {
throw new Error(`Invalid path "${path}"`);
}
return;
}
// lookAt
if (node === nodeMap.lookAtIndex) {
if (path === "rotation") {
result.lookAtTrack = origTrack;
} else {
throw new Error(`Invalid path "${path}"`);
}
}
});
return result;
}
}
|