Import a 3D Model and automatically assign and export animations
TypeScript
more typescript-ifying code for the human retargeting
Scott Petrovice09bdbc0a8e4
diff --git a/src/retarget/human-retargeting/ChainTwistAdditive.ts b/src/retarget/human-retargeting/ChainTwistAdditive.tsindex 1043c84..11cb535 100644--- a/src/retarget/human-retargeting/ChainTwistAdditive.ts+++ b/src/retarget/human-retargeting/ChainTwistAdditive.ts@@ -1,22 +1,38 @@// Compute a rotation axis between the first & last// points of the chain, the apply the twist rotation++import Quat from './Quat'+import { type Retargeter } from './Retargeter'+import { type RigItem } from './RigItem'+import Transform from './Transform'+import Vec3 from './Vec3'+// to the first joint of the chainexport class ChainTwistAdditive {- constructor (chName, rad = 0) {- this.chainName = chName+ public chainName: string+ public angle: number++ constructor (chain_name: string, rad: number = 0) {+ this.chainName = chain_namethis.angle = rad}- apply (rt) {- if (this.angle === 0) return+ apply (rt: Retargeter): void {+ if (this.angle === 0 || rt.tarRig === null) return// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~- const ch = rt.tarRig.chains[this.chainName]+ const ch: RigItem[] = rt.tarRig.chains[this.chainName]const itm0 = ch[0]- const itm1 = ch.at(-1)- const ptran = rt.pose.getWorld(itm0.pidx)- const ctran = new Transform().fromMul(ptran, rt.pose.joints[itm0.idx].local) // Chain Start Transform- const etran = rt.pose.getWorld(itm1.idx) // Chain End Transform+ const itm1 = ch[ch.length - 1]++ if (rt.pose === null) {+ console.warn('ChainTwistAdditive: Missing working pose.')+ return+ }++ const ptran: Transform = rt.pose.getWorld(itm0.pidx)+ const ctran: Transform = new Transform().fromMul(ptran, rt.pose.joints[itm0.idx].local) // Chain Start Transform+ const etran: Transform = rt.pose.getWorld(itm1.idx) // Chain End Transform// Debug.pnt.add( ctran.pos, 0xff0000, 2, 0 );// Debug.pnt.add( etran.pos, 0xffff00, 2, 0 );@@ -31,55 +47,3 @@ export class ChainTwistAdditive {rt.pose.setRot(itm0.idx, q)}}--// Run 3KJS's GetWorld functions & return as a Transform Object-function getWorld (skel, idx, t = new Transform()) {- const b = skel.bones[idx]- const p = b.getWorldPosition(new THREE.Vector3())- const q = b.getWorldQuaternion(new THREE.Quaternion())-- t.pos[0] = p.x- t.pos[1] = p.y- t.pos[2] = p.z-- t.rot[0] = q.x- t.rot[1] = q.y- t.rot[2] = q.z- t.rot[3] = q.w-- // SCALE - Not Needed for this proto- return t-}--// Make a rotation's invert directions match the target directions-// Create neutral transfroms for each joint as a starting point-// which is the current pose's parent joint worldspace transform applied-// to the local space tpose transform of the joint.-// This gives the transform of the joint as if itself has not change-// but its heirarchy has.-function applySwingTwist (itm, tSwing, tTwist, tpose, pose) {- // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~- // Compute Neutral Transform of the joint- // curentPose.parentJoint.world.rot * tPose.joint.local.rot- const j = tpose.joints[itm.idx]- const ptran = pose.getWorld(j.pindex) // Get WS of current pose of parent joint- const ctran = new Transform().fromMul(ptran, j.local) // Apply to Tpose's locaa for neutral rotation- const dir = new Vec3()- const sRot = new Quat()- const tRot = new Quat()-- // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~- // SWING- dir.fromQuat(ctran.rot, itm.swing) // Get Worldspace direction- sRot.fromSwing(dir, tSwing) // Compute rot current dir to target dir- .mul(ctran.rot) // PMul result to neutral rotation-- // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~- // Twist- dir.fromQuat(sRot, itm.twist) // Get WS twist direction after swring rotation- tRot.fromSwing(dir, tTwist) // Compute rot to make twist vectors match- .mul(sRot) // twist * ( swing * neutral )- .pmulInvert(ptran.rot) // To Localspace-- return tRot-}diff --git a/src/retarget/human-retargeting/Joint.ts b/src/retarget/human-retargeting/Joint.tsindex cd4f1f4..bdd6f37 100644--- a/src/retarget/human-retargeting/Joint.ts+++ b/src/retarget/human-retargeting/Joint.ts@@ -1,13 +1,17 @@+import Transform from './Transform'+import type * as THREE from 'three'+export class Joint {- name = ''- index = -1- pindex = -1- isRoot = false- children = []- local = new Transform()- world = new Transform()+ public name: string = ''+ public index: number = -1+ public pindex: number = -1+ public isRoot: boolean = false+ public children: number[] = [] // child joint indices+ public local: Transform = new Transform()+ public world: Transform = new Transform()+ public idx: number = 1 // set externally- fromBone (b) {+ fromBone (b: THREE.Bone): this {this.name = b.namelet v = b.position.toArray()@@ -15,11 +19,11 @@ export class Joint {this.local.pos[1] = v[1]this.local.pos[2] = v[2]- v = b.quaternion.toArray()- this.local.rot[0] = v[0]- this.local.rot[1] = v[1]- this.local.rot[2] = v[2]- this.local.rot[3] = v[3]+ const r: THREE.QuaternionTuple = b.quaternion.toArray()+ this.local.rot[0] = r[0]+ this.local.rot[1] = r[1]+ this.local.rot[2] = r[2]+ this.local.rot[3] = r[3]v = b.scale.toArray()this.local.scl[0] = v[0]@@ -29,7 +33,7 @@ export class Joint {return this}- clone () {+ clone (): Joint {const j = new Joint()j.name = this.namej.index = this.indexdiff --git a/src/retarget/human-retargeting/Pose.ts b/src/retarget/human-retargeting/Pose.tsindex aa9d095..5799adf 100644--- a/src/retarget/human-retargeting/Pose.ts+++ b/src/retarget/human-retargeting/Pose.ts@@ -1,4 +1,8 @@-import { Transform } from './Transform'+import { Joint } from './Joint'+import type Quat from './Quat'+import Transform from './Transform'+import * as THREE from 'three'+import type Vec3 from './Vec3'// Threejs does not have a method to clone a skeleton that works correctly.// Pose allows to make copies of a skeleton state. This is great to cache@@ -6,19 +10,27 @@ import { Transform } from './Transform'// commiting the results to the skeletonexport class Pose {// #region MAIN- srcPose = null- nameIdx = new Map()- joints = []- rootOffset = new Transform() // Absolute root transform- poseOffset = new Transform() // Offset applied to pose- constructor (skel) {- if (skel) this.fromSkeleton(skel)+ public srcPose: Pose | null = null+ public nameIdx = new Map<string, number>()+ public joints: Joint[] = []+ public rootOffset = new Transform() // Absolute root transform+ public poseOffset = new Transform() // Offset applied to pose++ constructor (skel?: THREE.Skeleton) {+ if (skel !== undefined) {+ this.fromSkeleton(skel)+ }}// #endregion// #region GETTERS / SETTERS- getJoint (o) {+ /**+ * Gets the joint by index or name+ * @param o either index of joint, or string name of joint+ * @returns joint object+ */+ getJoint (o: number | string): Joint | null {switch (typeof o) {case 'number': return this.joints[o]case 'string': {@@ -26,10 +38,11 @@ export class Pose {return (idx !== undefined) ? this.joints[idx] : null}}+return null}- clone () {+ public clone (): Pose {const p = new Pose()p.rootOffset.copy(this.rootOffset)p.poseOffset.copy(this.poseOffset)@@ -41,11 +54,11 @@ export class Pose {return p}- fromSkeleton (skel) {+ fromSkeleton (skel: THREE.Skeleton): void {this.nameIdx.clear()// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~- let j+ let j: Jointfor (const [i, b] of skel.bones.entries()) {// console.log( i, b );// Create Joint@@ -57,7 +70,12 @@ export class Pose {// Link up parent-child relationshopif ((b.parent?.isBone)) {- j.pindex = this.nameIdx.get(b.parent.name)+ const name_index: number | undefined = this.nameIdx.get(b.parent.name)++ if (name_index !== undefined) {+ j.pindex = name_index+ }+this.joints[j.pindex].children.push(j.index)}@@ -67,9 +85,11 @@ export class Pose {// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~// Get pose offset transform- const b = skel.bones[0]- if (b.parent) {+ const b: THREE.Bone = skel.bones[0]+ if (b !== null) {const v = new THREE.Vector3()++b.parent.getWorldPosition(v)this.poseOffset.pos[0] = v.xthis.poseOffset.pos[1] = v.y@@ -91,7 +111,7 @@ export class Pose {this.updateWorld()}- reset () {+ reset (): this {if (!this.srcPose) { console.log('Pose.reset - No source available for resetting'); return }for (let i = 0; i < this.joints.length; i++) {@@ -101,8 +121,8 @@ export class Pose {return this}- toSkeleton (skel) {- let j+ toSkeleton (skel: THREE.Skeleton): void {+ let j: Jointfor (const [i, b] of skel.bones.entries()) {j = this.joints[i]b.position.fromArray(j.local.pos)@@ -111,7 +131,7 @@ export class Pose {}}- setRot (i, rot) {+ setRot (i: number, rot: Quat): this {const r = this.joints[i].local.rotr[0] = rot[0]r[1] = rot[1]@@ -120,7 +140,7 @@ export class Pose {return this}- setPos (i, pos) {+ setPos (i: number, pos: Vec3): this {const p = this.joints[i].local.posp[0] = pos[0]p[1] = pos[1]@@ -128,7 +148,7 @@ export class Pose {return this}- setScl (i, scl) {+ setScl (i: number, scl: Vec3): this {const p = this.joints[i].local.sclp[0] = scl[0]p[1] = scl[1]@@ -136,7 +156,7 @@ export class Pose {return this}- setScalar (i, s) {+ setScalar (i: number, s: number): this {const p = this.joints[i].local.sclp[0] = sp[1] = s@@ -147,7 +167,7 @@ export class Pose {// #endregion// #region COMPUTE- updateWorld () {+ updateWorld (): this {for (const j of this.joints) {if (j.pindex !== -1) {// Parent Exists@@ -163,12 +183,16 @@ export class Pose {return this}- getWorld (id, out = new Transform()) {- let joint = this.getJoint(id)+ getWorld (id: number, out = new Transform()): Transform {+ let joint: Joint | null = this.getJoint(id)++ if (joint === null) {+ if (id === -1) {+ out.fromMul(this.rootOffset, this.poseOffset)+ } else {+ console.error('Pose.getWorld - joint not found', id)+ }- if (!joint) {- if (id === -1) out.fromMul(this.rootOffset, this.poseOffset)- else console.error('Pose.getWorld - joint not found', id)return out}@@ -188,19 +212,20 @@ export class Pose {// #endregion// #region DEBUGGING- debug () {- const LN = 0x707070- const PT = 0x505050+ // debug (): this {+ // const LN: number = 0x707070+ // const PT: number = 0x505050++ // let c+ // for (const j of this.joints) {+ // Debug.pnt.add(j.world.pos, PT, 0.7)+ // for (const i of j.children) {+ // c = this.joints[i]+ // Debug.ln.add(j.world.pos, c.world.pos, LN)+ // }+ // }+ // return this+ // }- let c- for (const j of this.joints) {- Debug.pnt.add(j.world.pos, PT, 0.7)- for (const i of j.children) {- c = this.joints[i]- Debug.ln.add(j.world.pos, c.world.pos, LN)- }- }- return this- }// #endregion}diff --git a/src/retarget/human-retargeting/Quat.ts b/src/retarget/human-retargeting/Quat.tsindex f171874..67f1eb3 100644--- a/src/retarget/human-retargeting/Quat.ts+++ b/src/retarget/human-retargeting/Quat.ts@@ -4,7 +4,7 @@ import Vec3 from './Vec3.js'// they are implicitly created by the Array base class.export default class Quat extends Array {// optional copy contructor- constructor (v: number[] | null = null) {+ constructor (v: Quat | null = null) {super(4)if (v?.length === 4) this.copy(v)else this.identity()@@ -183,16 +183,16 @@ export default class Quat extends Array {// fromSwingconst dot = Vec3.dot(a, b)if (dot < -0.999999) { // 180 opposites- const tmp = new Vec3().fromCross([-1, 0, 0], a)+ const tmp = new Vec3().fromCross(new Vec3(-1, 0, 0), a)- if (tmp.len < 0.000001) tmp.fromCross([0, 1, 0], a)+ if (tmp.len < 0.000001) tmp.fromCross(new Vec3(0, 1, 0), a)this.pmulAxisAngle(tmp.norm(), Math.PI)return this} else if (dot > 0.999999) { // Same Directionreturn this // Creates identity, so exist early}- const v = Vec3.cross(a, b, [0, 0, 0])+ const v = Vec3.cross(a, b, new Vec3(0, 0, 0))let ax = v[0]let ay = v[1]let az = v[2]@@ -291,7 +291,7 @@ export default class Quat extends Array {return this}- fromPolar (lon: number, lat: number, up = null): this {+ fromPolar (lon: number, lat: number, up: Vec3 | null = null): this {lat = Math.max(Math.min(lat, 89.999999), -89.999999) // Clamp lat, going to 90+ makes things spring around.const phi = (90 - lat) * 0.01745329251 // PI / 180@@ -304,11 +304,11 @@ export default class Quat extends Array {phi_s * Math.cos(theta)] as Vec3- this.fromLook(v, up || [0, 1, 0])+ this.fromLook(v, up || new Vec3(0, 1, 0))return this}- fromLook (fwd: Vec3, up = [0, 1, 0]): this {+ fromLook (fwd: Vec3, up: Vec3 = new Vec3(0, 1, 0)): this {// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~// Orthogonal axes to make a mat3x3const zAxis = new Vec3(fwd)@@ -368,9 +368,9 @@ export default class Quat extends Array {const dot = Vec3.dot(a, b)if (dot < -0.999999) { // 180 opposites- const tmp = new Vec3().fromCross([-1, 0, 0], a)+ const tmp = new Vec3().fromCross(new Vec3(-1, 0, 0), a)- if (tmp.len < 0.000001) tmp.fromCross([0, 1, 0], a)+ if (tmp.len < 0.000001) tmp.fromCross(new Vec3(0, 1, 0), a)this.fromAxisAngle(tmp.norm(), Math.PI)} else if (dot > 0.999999) { // Same Directionthis[0] = 0@@ -378,7 +378,7 @@ export default class Quat extends Array {this[2] = 0this[3] = 1} else {- const v = Vec3.cross(a, b, [0, 0, 0])+ const v = Vec3.cross(a, b, new Vec3(0, 0, 0))this[0] = v[0]this[1] = v[1]this[2] = v[2]@@ -401,11 +401,20 @@ export default class Quat extends Array {}fromAxes (xAxis: Vec3, yAxis: Vec3, zAxis: Vec3): this {- const m00 = xAxis[0]; const m01 = xAxis[1]; const m02 = xAxis[2]- const m10 = yAxis[0]; const m11 = yAxis[1]; const m12 = yAxis[2]- const m20 = zAxis[0]; const m21 = zAxis[1]; const m22 = zAxis[2]- const t = m00 + m11 + m22- let x, y, z, w, s+ const m00: number = xAxis[0]+ const m01: number = xAxis[1]+ const m02: number = xAxis[2]++ const m10: number = yAxis[0]+ const m11: number = yAxis[1]+ const m12: number = yAxis[2]++ const m20: number = zAxis[0]+ const m21: number = zAxis[1]+ const m22: number = zAxis[2]++ const t: number = m00 + m11 + m22+ let x: number, y: number, z: number, w: number, s: numberif (t > 0.0) {s = Math.sqrt(t + 1.0)diff --git a/src/retarget/human-retargeting/Retargeter.ts b/src/retarget/human-retargeting/Retargeter.tsindex cb99e0e..1970964 100644--- a/src/retarget/human-retargeting/Retargeter.ts+++ b/src/retarget/human-retargeting/Retargeter.ts@@ -5,29 +5,33 @@ import { type ChainTwistAdditive } from './ChainTwistAdditive'import Vec3 from './Vec3'import Quat from './Quat'import Transform from './Transform'+import { type RigItem } from './RigItem'+import { Joint } from './Joint'// example and library functions taken from sketchpunklabs// https://github.com/sketchpunklabs/threejs_proto/blob/main/code/webgl/anim/002_retarget_4m2m.htmlexport class Retargeter {- clip: THREE.AnimationClip | null = null- mixer: THREE.AnimationMixer- action: THREE.AnimationAction | null = null- srcRig: Rig | null = null- tarRig: Rig | null = null- pose: Pose | null = null- additives: ChainTwistAdditive[] = []-- // #region MAIN- constructor () {- this.mixer = new THREE.AnimationMixer(new THREE.Object3D())- }- // #endregion+ private clip: THREE.AnimationClip | null = null+ private readonly mixer: THREE.AnimationMixer = new THREE.AnimationMixer(new THREE.Object3D())+ private action: THREE.AnimationAction | null = null+ public srcRig: Rig | null = null+ public tarRig: Rig | null = null+ public pose: Pose | null = null+ public readonly additives: ChainTwistAdditive[] = []// #region SETTERS- setSourceRig (rig: any) { this.srcRig = rig; return this }- setTargetRig (rig: any) { this.tarRig = rig; return this }- setClip (clip) {+ public setSourceRig (rig: Rig): this {+ this.srcRig = rig+ return this+ }++ public setTargetRig (rig: Rig): this {+ this.tarRig = rig+ return this+ }++ public setClip (clip: THREE.AnimationClip): this {this.clip = clipif (this.action !== null) {@@ -40,7 +44,12 @@ export class Retargeter {// #endregion// #region METHODS- update (delta_time: number): void {+ public update (delta_time: number): void {+ if (this.srcRig === null || this.tarRig === null || this.clip === null) {+ console.warn('Retargeter: Missing srcRig, tarRig, or clip.')+ return+ }+// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~// PREPAREif (this.action === null) {@@ -79,44 +88,53 @@ export class Retargeter {}// Apply SwingTwist to each joint of a chain, 1 to 1 mappings- applyChain (k) {+ // k = chain key like 'pelvis', 'armL', etc+ applyChain (k: string): void {+ if (this.srcRig === null || this.tarRig === null || this.pose === null) {+ console.warn('Retargeter: Missing srcRig, tarRig, or pose.')+ return+ }+// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~- const src = this.srcRig.chains[k]- const tar = this.tarRig.chains[k]- if (!src || !tar) return+ const src: RigItem[] = this.srcRig.chains[k]+ const tar: RigItem[] = this.tarRig.chains[k]+ if (src === null || tar === null) {+ console.warn('Retargeter: Missing source or target chain for key ', k)+ return+ }// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~- const cnt = src.length- const v = new THREE.Vector3()- const q = new THREE.Quaternion()+ // const cnt = src.length+ const v: Vec3 = new Vec3()+ const q: Quat = new Quat()- const p = new Vec3()- const sPos = new Vec3()- const sRot = new Quat()- const tRot = new Quat()- const rot = new Quat()+ // const p = new Vec3()+ const sPos: Vec3 = new Vec3()+ const sRot: Quat = new Quat()+ const tRot: Quat = new Quat()+ const rot: Quat = new Quat()- const sSwing = new Vec3() // Source Swing- const sTwist = new Vec3() // Source Twist- const nSwing = new Vec3()- const nTwist = new Vec3()+ const sSwing: Vec3 = new Vec3() // Source Swing+ const sTwist: Vec3 = new Vec3() // Source Twist+ const nSwing: Vec3 = new Vec3()+ const nTwist: Vec3 = new Vec3()- const ptran = new Transform()- const ctran = new Transform()+ const ptran: Transform = new Transform()+ const ctran: Transform = new Transform()- let b+ let b: THREE.Bonelet jfor (let i = 0; i < src.length; i++) {// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~// Get source swing / twist vectors// Pose exists in 3JS skeleton, so need to get its- // Data threw 3JS methods+ // Data through 3JS methodsb = this.srcRig.skel.bones[src[i].idx]- b.getWorldPosition(v)- b.getWorldQuaternion(q)- sPos.copyObj(v)- sRot.copyObj(q)+ b.getWorldPosition(new THREE.Vector3(v[0], v[1], v[2]))+ b.getWorldQuaternion(new THREE.Quaternion(q[0], q[1], q[2], q[3]))+ sPos.copyTo(v)+ sRot.copyTo(q)sSwing.fromQuat(sRot, src[i].swing)sTwist.fromQuat(sRot, src[i].twist)@@ -152,103 +170,168 @@ export class Retargeter {// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~// Visualize computed target vectors from source animation- Debug.pnt.add(sPos, 0xffff00, 1)- Debug.ln.add(sPos, p.fromScaleThenAdd(0.1, sSwing, sPos), 0xffff00)- Debug.ln.add(sPos, p.fromScaleThenAdd(0.1, sTwist, sPos), 0xff00ff)+ // Debug.pnt.add(sPos, 0xffff00, 1)+ // Debug.ln.add(sPos, p.fromScaleThenAdd(0.1, sSwing, sPos), 0xffff00)+ // Debug.ln.add(sPos, p.fromScaleThenAdd(0.1, sTwist, sPos), 0xff00ff)// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~// Visualize target vectors over mesh- Debug.pnt.add(ctran.pos, 0x00ff00, 1)- Debug.ln.add(ctran.pos, p.fromScaleThenAdd(0.15, nSwing, ctran.pos), 0xffff00)- Debug.ln.add(ctran.pos, p.fromScaleThenAdd(0.1, nSwing, ctran.pos), 0xffffff)- Debug.ln.add(ctran.pos, p.fromScaleThenAdd(0.15, nTwist, ctran.pos), 0xff00ff)- Debug.ln.add(ctran.pos, p.fromScaleThenAdd(0.1, nTwist, ctran.pos), 0xff0000)+ // Debug.pnt.add(ctran.pos, 0x00ff00, 1)+ // Debug.ln.add(ctran.pos, p.fromScaleThenAdd(0.15, nSwing, ctran.pos), 0xffff00)+ // Debug.ln.add(ctran.pos, p.fromScaleThenAdd(0.1, nSwing, ctran.pos), 0xffffff)+ // Debug.ln.add(ctran.pos, p.fromScaleThenAdd(0.15, nTwist, ctran.pos), 0xff00ff)+ // Debug.ln.add(ctran.pos, p.fromScaleThenAdd(0.1, nTwist, ctran.pos), 0xff0000)}}// Interp start & end SwingTwist vectors over a chain- applyEndInterp (k) {- // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~- const src = this.srcRig.chains[k]- const tar = this.tarRig.chains[k]- if (!src || !tar) return+ // k = chain key like 'spine', etc+ applyEndInterp (k: string): void {+ if (this.srcRig === null || this.tarRig === null || this.pose === null) {+ console.warn('Retargeter: Missing srcRig, tarRig, or pose.')+ return+ }- const dTran = new Transform() // Debug- const vv = new Vec3() // Debug+ // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~+ const src: RigItem[] = this.srcRig.chains[k]+ const tar: RigItem[] = this.tarRig.chains[k]+ if (src === null || tar === null) return// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~- const aTran = getWorld(this.srcRig.skel, src[0].idx)+ const aTran = this.getWorld(this.srcRig.skel, src[0].idx)const aSwing = new Vec3().fromQuat(aTran.rot, src[0].swing)const aTwist = new Vec3().fromQuat(aTran.rot, src[0].twist)- const bTran = getWorld(this.srcRig.skel, src.at(-1).idx)- const bSwing = new Vec3().fromQuat(bTran.rot, src.at(-1).swing)- const bTwist = new Vec3().fromQuat(bTran.rot, src.at(-1).twist)+ const bTran = this.getWorld(this.srcRig.skel, src[src.length - 1].idx)+ const bSwing = new Vec3().fromQuat(bTran.rot, src[src.length - 1].swing)+ const bTwist = new Vec3().fromQuat(bTran.rot, src[src.length - 1].twist)// Visualize data over source skeleton- Debug.pnt.add(aTran.pos, 0xffff00, 1.2)- Debug.pnt.add(bTran.pos, 0xffff00, 1.2)+ // Debug.pnt.add(aTran.pos, 0xffff00, 1.2)+ // Debug.pnt.add(bTran.pos, 0xffff00, 1.2)- Debug.ln.add(aTran.pos, vv.fromScaleThenAdd(0.1, aSwing, aTran.pos), 0xffff00)- Debug.ln.add(aTran.pos, vv.fromScaleThenAdd(0.1, aTwist, aTran.pos), 0xff00ff)- Debug.ln.add(bTran.pos, vv.fromScaleThenAdd(0.1, bSwing, bTran.pos), 0xffff00)- Debug.ln.add(bTran.pos, vv.fromScaleThenAdd(0.1, bTwist, bTran.pos), 0xff00ff)+ // Debug.ln.add(aTran.pos, vv.fromScaleThenAdd(0.1, aSwing, aTran.pos), 0xffff00)+ // Debug.ln.add(aTran.pos, vv.fromScaleThenAdd(0.1, aTwist, aTran.pos), 0xff00ff)+ // Debug.ln.add(bTran.pos, vv.fromScaleThenAdd(0.1, bSwing, bTran.pos), 0xffff00)+ // Debug.ln.add(bTran.pos, vv.fromScaleThenAdd(0.1, bTwist, bTran.pos), 0xff00ff)// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~- const tDir = new Vec3()- const dir = new Vec3()- const iMax = tar.length - 1- let itm, t, j-- for (let i = 0; i <= iMax; i++) {- t = i / iMax+ const target_dir: Vec3 = new Vec3()+ const target_twist: Vec3 = new Vec3()+ const rig_items_count: number = tar.length - 1+ let itm: RigItem+ let t: number // 0-1 lerp factor for chain++ for (let i = 0; i <= rig_items_count; i++) {+ t = i / rig_items_countitm = tar[i]// Lerp Target Vectors- tDir.fromLerp(aSwing, bSwing, t).norm()- dir.fromLerp(aTwist, bTwist, t).norm()+ target_dir.fromLerp(aSwing, bSwing, t).norm()+ target_twist.fromLerp(aTwist, bTwist, t).norm()// Make joint vectors match target vectors- const rot = applySwingTwist(itm, tDir, dir, this.tarRig.tpose, this.pose)+ const rot = this.applySwingTwist(itm, target_dir, target_twist, this.tarRig.tpose, this.pose)this.pose.setRot(itm.idx, rot)// ------------------------ this.pose.getWorld(itm.idx, dTran)- Debug.pnt.add(dTran.pos, 0x00ff00, 1, 1)- Debug.ln.add(dTran.pos, vv.fromQuat(dTran.rot, itm.swing).scale(0.1).add(dTran.pos), 0xffff00)- Debug.ln.add(dTran.pos, vv.fromQuat(dTran.rot, itm.twist).scale(0.1).add(dTran.pos), 0xff00ff)+ const debug_transform: Transform = new Transform() // Debug+ this.pose.getWorld(itm.idx, debug_transform)+ // const vv: Vec3 = new Vec3() // Debug+ // Debug.pnt.add(debug_transform.pos, 0x00ff00, 1, 1)+ // Debug.ln.add(debug_transform.pos, vv.fromQuat(debug_transform.rot, itm.swing).scale(0.1).add(debug_transform.pos), 0xffff00)+ // Debug.ln.add(debug_transform.pos, vv.fromQuat(debug_transform.rot, itm.twist).scale(0.1).add(debug_transform.pos), 0xff00ff)}}// Compute offset translation & scale it to fit better on target- applyScaledTranslation (k) {+ applyScaledTranslation (k: string): void {+ if (this.srcRig === null || this.tarRig === null || this.pose === null) {+ console.warn('Retargeter: applyScaledTranslation(). Missing srcRig, tarRig, or pose.')+ return+ }+// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~// Make sure we have our src & target- const src = this.srcRig.chains[k][0]- const tar = this.tarRig.chains[k][0]- if (!src || !tar) return+ const src: RigItem = this.srcRig.chains[k][0]+ const tar: RigItem = this.tarRig.chains[k][0]+ if (src === null || tar === null) return// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~// Compute offset position change from animationconst scl = this.tarRig.scalar / this.srcRig.scalar // Scale from Src to Tar- const tJoint = this.srcRig.tpose.joints[src.idx] // TPose Src Joint- const srcTran = getWorld(this.srcRig.skel, src.idx) // WS Tranform of Src Bone+ const source_t_pose_joint: Joint = this.srcRig.tpose.joints[src.idx] // TPose Src Joint+ const source_ws_transform: Transform = this.getWorld(this.srcRig.skel, src.idx) // WS Tranform of Src Bone// ( animated.joint.world.pos - tpose.joint.world.pos ) * ( tarHipHeight / srcHipHeight )- const offset = new Vec3()- .fromSub(srcTran.pos, tJoint.world.pos)+ const offset: Vec3 = new Vec3()+ .fromSub(source_ws_transform.pos, source_t_pose_joint.world.pos).scale(scl)// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~// Neutral Transform- const ptran = this.pose.getWorld(tar.pidx)- const ctran = new Transform().fromMul(ptran, this.tarRig.tpose.joints[tar.idx].local)+ const ptran: Transform = this.pose.getWorld(tar.pidx)+ const ctran: Transform = new Transform().fromMul(ptran, this.tarRig.tpose.joints[tar.idx].local)// Add scaled offset translation- const pos = new Vec3().fromAdd(ctran.pos, offset)+ const pos: Vec3 = new Vec3().fromAdd(ctran.pos, offset)// Save to local spacethis.pose.setPos(tar.idx, ptran.toLocalPos(pos))}// #endregion++ // #region THREEJS HELPERS+ // Run 3KJS's GetWorld functions & return as a Transform Object+ public getWorld (skel: THREE.Skeleton, bone_idx: number, trans: Transform = new Transform()): Transform {+ const b: THREE.Bone = skel.bones[bone_idx]+ const p: THREE.Vector3 = b.getWorldPosition(new THREE.Vector3())+ const q: THREE.Quaternion = b.getWorldQuaternion(new THREE.Quaternion())++ trans.pos[0] = p.x+ trans.pos[1] = p.y+ trans.pos[2] = p.z++ trans.rot[0] = q.x+ trans.rot[1] = q.y+ trans.rot[2] = q.z+ trans.rot[3] = q.w++ // SCALE - Not Needed for this proto+ return trans+ }++ // Make a rotation's invert directions match the target directions+ // Create neutral transfroms for each joint as a starting point+ // which is the current pose's parent joint worldspace transform applied+ // to the local space tpose transform of the joint.+ // This gives the transform of the joint as if itself has not change+ // but its heirarchy has.+ public applySwingTwist (itm: RigItem, tSwing: Vec3, tTwist: Vec3, tpose: Pose, pose: Pose): Quat {+ // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~+ // Compute Neutral Transform of the joint+ // curentPose.parentJoint.world.rot * tPose.joint.local.rot+ const j: Joint = tpose.joints[itm.idx]+ const ptran: Transform = pose.getWorld(j.pindex) // Get WS of current pose of parent joint+ const ctran: Transform = new Transform().fromMul(ptran, j.local) // Apply to Tpose's locaa for neutral rotation+ const dir: Vec3 = new Vec3()+ const source_rot: Quat = new Quat()+ const target_rot: Quat = new Quat()++ // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~+ // SWING+ dir.fromQuat(ctran.rot, itm.swing) // Get Worldspace direction+ source_rot.fromSwing(dir, tSwing) // Compute rot current dir to target dir+ .mul(ctran.rot) // PMul result to neutral rotation++ // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~+ // Twist+ dir.fromQuat(source_rot, itm.twist) // Get WS twist direction after swring rotation+ target_rot.fromSwing(dir, tTwist) // Compute rot to make twist vectors match+ .mul(source_rot) // twist * ( swing * neutral )+ .pmulInvert(ptran.rot) // To Localspace++ return target_rot+ }+ // #endregion}diff --git a/src/retarget/human-retargeting/Rig.ts b/src/retarget/human-retargeting/Rig.tsindex 3d62cf0..c4af125 100644--- a/src/retarget/human-retargeting/Rig.ts+++ b/src/retarget/human-retargeting/Rig.ts@@ -4,17 +4,18 @@import { Pose } from './Pose'import { RigItem } from './RigItem'-import Transform from './Transform'import Vec3 from './Vec3'+import type * as THREE from 'three'+// that speaks a single language of whats what.export class Rig {- private readonly skel: any- private readonly tpose: Pose- private readonly chains: Record<string, RigItem[]>- private scalar: number+ public readonly skel: THREE.Skeleton+ public readonly tpose: Pose+ public readonly chains: Record<string, RigItem[]>+ public scalar: number- constructor (skel) {+ constructor (skel: THREE.Skeleton) {this.skel = skelthis.chains = {}this.tpose = new Pose(skel)@@ -25,27 +26,31 @@ export class Rig {fromConfig (cfg = {}): this {for (const [k, v] of Object.entries(cfg)) {switch (k) {- case 'pelvis' : this.buildItem(k, v.names, [0, 0, 1], [0, 1, 0]).buildScalar(k); break- case 'spine' : this.buildItem(k, v.names, [0, 1, 0], [0, 0, 1]); break- case 'head' : this.buildItem(k, v.names, [0, 0, 1], [0, 1, 0]); break+ case 'pelvis' : this.buildItem(k, v.names, new Vec3(0, 0, 1), new Vec3(0, 1, 0)).buildScalar(k); break+ case 'spine' : this.buildItem(k, v.names, new Vec3(0, 1, 0), new Vec3(0, 0, 1)); break+ case 'head' : this.buildItem(k, v.names, new Vec3(0, 0, 1), new Vec3(0, 1, 0)); break- case 'armL' : this.buildItem(k, v.names, [1, 0, 0], [0, 0, -1]); break- case 'armR' : this.buildItem(k, v.names, [-1, 0, 0], [0, 0, -1]); break+ case 'armL' : this.buildItem(k, v.names, new Vec3(1, 0, 0), new Vec3(0, 0, -1)); break+ case 'armR' : this.buildItem(k, v.names, new Vec3(-1, 0, 0), new Vec3(0, 0, -1)); break- case 'legL' : this.buildItem(k, v.names, [0, 0, 1], [0, -1, 0]); break- case 'legR' : this.buildItem(k, v.names, [0, 0, 1], [0, -1, 0]); break+ case 'legL' : this.buildItem(k, v.names, new Vec3(0, 0, 1), new Vec3(0, -1, 0)); break+ case 'legR' : this.buildItem(k, v.names, new Vec3(0, 0, 1), new Vec3(0, -1, 0)); break}}return this}- buildItem (k, names: string[], swing, twist): this {+ // k = chain key like 'pelvis', 'armL', etc+ buildItem (k: string, names: string[], swing: Vec3, twist: Vec3): this {const ary = []let jfor (const n of names) {j = this.tpose.getJoint(n)- if (!j) { console.log('Error - Rig.buildLimb : Joint name not found in tpose, ', n); continue }+ if (j === null) {+ console.log('Error - Rig.buildLimb : Joint name not found in tpose, ', n)+ continue+ }ary.push(new RigItem().fromJoint(j, swing, twist))}@@ -54,48 +59,49 @@ export class Rig {return this}- buildScalar (k): this {+ // k = chain key like 'pelvis', 'armL', etc+ buildScalar (k: string): this {const ch = this.chains[k]const j = this.tpose.joints[ch[0].idx]this.scalar = j.world.pos[1]return this}- debugSkelVectors (): void {- // const bAry = this.skel.bones;- const tran = new Transform()- const v = new Vec3()-- for (const [chName, ch] of Object.entries(this.chains)) {- for (const itm of ch) {- getWorld(this.skel, itm.idx, tran)- Debug.pnt.add(tran.pos, 0xffff00, 0.8)-- v.fromQuat(tran.rot, itm.swing).norm().scale(0.1).add(tran.pos)- Debug.ln.add(tran.pos, v, 0xffff00)-- v.fromQuat(tran.rot, itm.twist).norm().scale(0.1).add(tran.pos)- Debug.ln.add(tran.pos, v, 0xff00ff)- }- }- }-- debugTPoseVectors (): void {- // const bAry = this.skel.bones;- const tran: Transform = new Transform()- const v = new Vec3()-- for (const [chName, ch] of Object.entries(this.chains)) {- for (const itm of ch) {- this.tpose.getWorld(itm.idx, tran)- Debug.pnt.add(tran.pos, 0xffff00, 0.8)-- v.fromQuat(tran.rot, itm.swing).norm().scale(0.1).add(tran.pos)- Debug.ln.add(tran.pos, v, 0xffff00)-- v.fromQuat(tran.rot, itm.twist).norm().scale(0.1).add(tran.pos)- Debug.ln.add(tran.pos, v, 0xff00ff)- }- }- }+ // debugSkelVectors (): void {+ // // const bAry = this.skel.bones;+ // const tran = new Transform()+ // const v = new Vec3()++ // for (const [chName, ch] of Object.entries(this.chains)) {+ // for (const itm of ch) {+ // getWorld(this.skel, itm.idx, tran)+ // Debug.pnt.add(tran.pos, 0xffff00, 0.8)++ // v.fromQuat(tran.rot, itm.swing).norm().scale(0.1).add(tran.pos)+ // Debug.ln.add(tran.pos, v, 0xffff00)++ // v.fromQuat(tran.rot, itm.twist).norm().scale(0.1).add(tran.pos)+ // Debug.ln.add(tran.pos, v, 0xff00ff)+ // }+ // }+ // }++ // debugTPoseVectors (): void {+ // // const bAry = this.skel.bones;+ // const tran: Transform = new Transform()+ // const v = new Vec3()++ // for (const [chName, ch] of Object.entries(this.chains)) {+ // for (const itm of ch) {+ // this.tpose.getWorld(itm.idx, tran)+ // // Debug.pnt.add(tran.pos, 0xffff00, 0.8)++ // v.fromQuat(tran.rot, itm.swing).norm().scale(0.1).add(tran.pos)+ // // Debug.ln.add(tran.pos, v, 0xffff00)++ // v.fromQuat(tran.rot, itm.twist).norm().scale(0.1).add(tran.pos)+ // // Debug.ln.add(tran.pos, v, 0xff00ff)+ // }+ // }+ // }}diff --git a/src/retarget/human-retargeting/RigItem.ts b/src/retarget/human-retargeting/RigItem.tsindex cea6d45..12c6ed1 100644--- a/src/retarget/human-retargeting/RigItem.ts+++ b/src/retarget/human-retargeting/RigItem.ts@@ -4,20 +4,21 @@ import Vec3 from './Vec3'// Rig data about a single jointexport class RigItem {- private idx: number = -1 // Joint Index- private pidx: number = -1 // Parent Joint Index- private readonly swing: Vec3 = new Vec3(0, 0, 1) // Swing Direction - Z- private readonly twist: Vec3 = new Vec3(0, 1, 0) // Twist Direction - Y+ public idx: number = -1 // Joint Index+ public pidx: number = -1 // Parent Joint Index+ public readonly swing: Vec3 = new Vec3(0, 0, 1) // Swing Direction - Z+ public readonly twist: Vec3 = new Vec3(0, 1, 0) // Twist Direction - Y- public fromJoint (j: Joint, swing = null, twist = null): this {+ public fromJoint (j: Joint, swing: Vec3 | null = null, twist: Vec3 | null = null): this {this.idx = j.indexthis.pidx = j.pindex// Compute inverse direction on the current joint rotation- if (swing || twist) {- const q = new Quat().fromInvert(j.world.rot)- if (swing) this.swing.fromQuat(q, swing)- if (twist) this.twist.fromQuat(q, twist)+ if (swing !== null || twist !== null) {+ const joint_world_rotation: Quat = j.world.rot+ const q = new Quat().fromInvert(joint_world_rotation)+ if (swing !== null) this.swing.fromQuat(q, swing)+ if (twist !== null) this.twist.fromQuat(q, twist)}return thisdiff --git a/src/retarget/human-retargeting/Transform.ts b/src/retarget/human-retargeting/Transform.tsindex 9760657..bce0524 100644--- a/src/retarget/human-retargeting/Transform.ts+++ b/src/retarget/human-retargeting/Transform.ts@@ -6,7 +6,7 @@ import Vec3 from './Vec3'export default class Transform {// #region MAIN- private rot: Quat = new Quat([0, 0, 0, 1])+ public rot: Quat = new Quat([0, 0, 0, 1])public pos: Vec3 = new Vec3()public scl: Vec3 = new Vec3(1, 1, 1)@@ -71,11 +71,11 @@ export default class Transform {mul (tran: Transform): this {// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~// POSITION - parent.position + ( parent.rotation * ( parent.scale * child.position ) )- const p = [+ const p = new Vec3(this.scl[0] * tran.pos[0], // Scalethis.scl[1] * tran.pos[1],this.scl[2] * tran.pos[2]- ]+ )qTransform(this.rot, p, p) // Rotationthis.pos[0] += p[0] // Translation@@ -132,11 +132,11 @@ export default class Transform {fromMul (tp: Transform, tc: Transform): this {// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~// POSITION - parent.position + ( ( parent.scale * child.position ) * parent.rotation )- const v = [ // parent.scale * child.position+ const v = new Vec3( // parent.scale * child.positiontp.scl[0] * tc.pos[0],tp.scl[1] * tc.pos[1],tp.scl[2] * tc.pos[2]- ]+ )qTransform(tp.rot, v, v) // * parent.rotationthis.pos[0] = tp.pos[0] + v[0] // parent.position +@@ -250,29 +250,30 @@ export default class Transform {// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~// Invert Transform Rot & Sclconst qi = qInvert(this.rot)- const si = [+ const si = new Vec3(1 / this.scl[0],1 / this.scl[1],1 / this.scl[2]- ]+ )// Invert Transform Pos- const pi = [+ const pi = new Vec3(-this.pos[0] * si[0],-this.pos[1] * si[1],-this.pos[2] * si[2]- ]+ )+qTransform(qi, pi, pi)// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~// Invert Transform on WorldSpace Position// invertRot * ( invertScl * WPos ) + invertPos;- const p = [+ const p = new Vec3(si[0] * wp[0],si[1] * wp[1],si[2] * wp[2]- ]+ )qTransform(qi, p, p)@@ -282,7 +283,7 @@ export default class Transform {return out}- toLocalRot (wq: number[], out: number[] = [0, 0, 0, 1]): number[] {+ toLocalRot (wq: Quat, out: Quat = new Quat([0, 0, 0, 1])): number[] {return qMul(qInvert(this.rot), wq, out)}@@ -314,11 +315,11 @@ function qInvert (q: Quat, out: Quat = new Quat([0, 0, 0, 1])): Quat {if (dot === 0) { out[0] = out[1] = out[2] = out[3] = 0; return out }- const iDot = 1.0 / dot // let invDot = dot ? 1.0/dot : 0;- out[0] = -a0 * iDot- out[1] = -a1 * iDot- out[2] = -a2 * iDot- out[3] = a3 * iDot+ const inverse_dot_product = 1.0 / dot // let invDot = dot ? 1.0/dot : 0;+ out[0] = -a0 * inverse_dot_product+ out[1] = -a1 * inverse_dot_product+ out[2] = -a2 * inverse_dot_product+ out[3] = a3 * inverse_dot_productreturn out}diff --git a/src/retarget/human-retargeting/Vec3.ts b/src/retarget/human-retargeting/Vec3.tsindex c5f9cf2..4833990 100644--- a/src/retarget/human-retargeting/Vec3.ts+++ b/src/retarget/human-retargeting/Vec3.ts@@ -194,24 +194,24 @@ export default class Vec3 extends Array {return this}- scale (v: number): this {- this[0] *= v- this[1] *= v- this[2] *= v+ scale (scalar: number): this {+ this[0] *= scalar+ this[1] *= scalar+ this[2] *= scalarreturn this}- invScale (v: number): this {- this[0] /= v- this[1] /= v- this[2] /= v+ invScale (scalar: number): this {+ this[0] /= scalar+ this[1] /= scalar+ this[2] /= scalarreturn this}- scaleThenAdd (s: number, v: Vec3): this {- this[0] += v[0] * s- this[1] += v[1] * s- this[2] += v[2] * s+ scaleThenAdd (scalar: number, v: Vec3): this {+ this[0] += v[0] * scalar+ this[1] += v[1] * scalar+ this[2] += v[2] * scalarreturn this}