Import a 3D Model and automatically assign and export animations
TypeScript
Start adding more files like the human retargeting example
Scott Petrovic05238791c413
diff --git a/src/retarget/human-retargeting/AxisAdditive.ts b/src/retarget/human-retargeting/AxisAdditive.tsnew file mode 100644index 0000000..914fb41--- /dev/null+++ b/src/retarget/human-retargeting/AxisAdditive.ts@@ -0,0 +1,38 @@+// Apply rotation to the first join in the chain+// by using one of the inverse direction as the+// rotational axis+export class AxisAdditive {+ constructor (chName, axis = 'y', rad = 0) {+ this.chainName = chName+ this.onAxis = axis+ this.angle = rad+ }++ apply (rt) {+ if (this.angle === 0) return++ // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~+ const ch = rt.tarRig.chains[this.chainName]+ const itm = ch[0]+ const ptran = rt.pose.getWorld(itm.pidx)+ const ctran = new Transform().fromMul(ptran, rt.pose.joints[itm.idx].local) // Less computive+ // const ctran = rt.pose.getWorld( itm.idx );++ // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~+ const axis = new Vec3()+ switch (this.onAxis) {+ case 'y': axis.fromQuat(ctran.rot, itm.twist); break+ default:+ console.log('ERROR : AxisAdditive - Axis not implemented', this.onAxis)+ return+ }++ // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~+ const q = new Quat()+ .fromAxisAngle(axis, this.angle) // Compute WS Rotation+ .mul(ctran.rot) // Apply to joint+ .pmulInvert(ptran.rot) // To LocalSpace++ rt.pose.setRot(itm.idx, q)+ }+}diff --git a/src/retarget/human-retargeting/ChainTwistAdditive.ts b/src/retarget/human-retargeting/ChainTwistAdditive.tsnew file mode 100644index 0000000..1043c84--- /dev/null+++ b/src/retarget/human-retargeting/ChainTwistAdditive.ts@@ -0,0 +1,85 @@+// Compute a rotation axis between the first & last+// points of the chain, the apply the twist rotation+// to the first joint of the chain+export class ChainTwistAdditive {+ constructor (chName, rad = 0) {+ this.chainName = chName+ this.angle = rad+ }++ apply (rt) {+ if (this.angle === 0) return++ // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~+ const ch = 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++ // Debug.pnt.add( ctran.pos, 0xff0000, 2, 0 );+ // Debug.pnt.add( etran.pos, 0xffff00, 2, 0 );++ // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~+ const axis = new Vec3().fromSub(etran.pos, ctran.pos).norm()+ const q = new Quat()+ .fromAxisAngle(axis, this.angle) // Compute WS Rotation+ .mul(ctran.rot) // Apply to joint+ .pmulInvert(ptran.rot) // To LocalSpace++ 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/HumanRig.ts b/src/retarget/human-retargeting/HumanRig.tsdeleted file mode 100644index 2b59375..0000000--- a/src/retarget/human-retargeting/HumanRig.ts+++ /dev/null@@ -1,10 +0,0 @@-export class HumanRig {- private skeleton: any- private chains: any = {}- private t_pose: any = null- private scalar: number = 1.0-- constructor (skeleton: any) {- this.skeleton = skeleton- }-}diff --git a/src/retarget/human-retargeting/Joint.ts b/src/retarget/human-retargeting/Joint.tsnew file mode 100644index 0000000..cd4f1f4--- /dev/null+++ b/src/retarget/human-retargeting/Joint.ts@@ -0,0 +1,43 @@+export class Joint {+ name = ''+ index = -1+ pindex = -1+ isRoot = false+ children = []+ local = new Transform()+ world = new Transform()++ fromBone (b) {+ this.name = b.name++ let v = b.position.toArray()+ this.local.pos[0] = v[0]+ 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]++ v = b.scale.toArray()+ this.local.scl[0] = v[0]+ this.local.scl[1] = v[1]+ this.local.scl[2] = v[2]++ return this+ }++ clone () {+ const j = new Joint()+ j.name = this.name+ j.index = this.index+ j.pindex = this.pindex+ j.isRoot = this.isRoot+ j.children = [...this.children]+ j.local.copy(this.local)+ j.world.copy(this.world)+ return j+ }+}diff --git a/src/retarget/human-retargeting/Pose.ts b/src/retarget/human-retargeting/Pose.tsindex 58fd73f..aa9d095 100644--- a/src/retarget/human-retargeting/Pose.ts+++ b/src/retarget/human-retargeting/Pose.ts@@ -1,5 +1,206 @@+import { Transform } from './Transform'++// 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+// the bindpose plus have a working space for computing a new pose before+// commiting the results to the skeletonexport class Pose {- public src_pose: any = null- public name_index = new Map()- public joints: any[] = []+ // #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)+ }+ // #endregion++ // #region GETTERS / SETTERS++ getJoint (o) {+ switch (typeof o) {+ case 'number': return this.joints[o]+ case 'string': {+ const idx = this.nameIdx.get(o)+ return (idx !== undefined) ? this.joints[idx] : null+ }+ }+ return null+ }++ clone () {+ const p = new Pose()+ p.rootOffset.copy(this.rootOffset)+ p.poseOffset.copy(this.poseOffset)++ for (const j of this.joints) p.joints.push(j.clone())++ p.srcPose = this.srcPose ?? this+ p.nameIdx = this.nameIdx // Ref copy, should never change+ return p+ }++ fromSkeleton (skel) {+ this.nameIdx.clear()++ // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~+ let j+ for (const [i, b] of skel.bones.entries()) {+ // console.log( i, b );+ // Create Joint+ j = new Joint().fromBone(b)+ j.index = i++ // Map Name to Index+ this.nameIdx.set(j.name, j.index)++ // Link up parent-child relationshop+ if ((b.parent?.isBone)) {+ j.pindex = this.nameIdx.get(b.parent.name)+ this.joints[j.pindex].children.push(j.index)+ }++ this.joints[i] = j+ }++ // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~+ // Get pose offset transform++ const b = skel.bones[0]+ if (b.parent) {+ const v = new THREE.Vector3()+ b.parent.getWorldPosition(v)+ this.poseOffset.pos[0] = v.x+ this.poseOffset.pos[1] = v.y+ this.poseOffset.pos[2] = v.z++ b.parent.getWorldScale(v)+ this.poseOffset.scl[0] = v.x+ this.poseOffset.scl[1] = v.y+ this.poseOffset.scl[2] = v.z++ const q = new THREE.Quaternion()+ b.parent.getWorldQuaternion(q)+ this.poseOffset.rot[0] = q.x+ this.poseOffset.rot[1] = q.y+ this.poseOffset.rot[2] = q.z+ this.poseOffset.rot[3] = q.w+ }++ this.updateWorld()+ }++ reset () {+ if (!this.srcPose) { console.log('Pose.reset - No source available for resetting'); return }++ for (let i = 0; i < this.joints.length; i++) {+ this.joints[i].local.copy(this.srcPose.joints[i].local)+ }++ return this+ }++ toSkeleton (skel) {+ let j+ for (const [i, b] of skel.bones.entries()) {+ j = this.joints[i]+ b.position.fromArray(j.local.pos)+ b.quaternion.fromArray(j.local.rot)+ b.scale.fromArray(j.local.scl)+ }+ }++ setRot (i, rot) {+ const r = this.joints[i].local.rot+ r[0] = rot[0]+ r[1] = rot[1]+ r[2] = rot[2]+ r[3] = rot[3]+ return this+ }++ setPos (i, pos) {+ const p = this.joints[i].local.pos+ p[0] = pos[0]+ p[1] = pos[1]+ p[2] = pos[2]+ return this+ }++ setScl (i, scl) {+ const p = this.joints[i].local.scl+ p[0] = scl[0]+ p[1] = scl[1]+ p[2] = scl[2]+ return this+ }++ setScalar (i, s) {+ const p = this.joints[i].local.scl+ p[0] = s+ p[1] = s+ p[2] = s+ return this+ }++ // #endregion++ // #region COMPUTE+ updateWorld () {+ for (const j of this.joints) {+ if (j.pindex !== -1) {+ // Parent Exists+ j.world.fromMul(this.joints[j.pindex].world, j.local)+ } else {+ // No Parent, apply any possible offset+ j.world+ .fromMul(this.rootOffset, this.poseOffset)+ .mul(j.local)+ }+ }++ return this+ }++ getWorld (id, out = new Transform()) {+ let joint = this.getJoint(id)++ if (!joint) {+ if (id === -1) out.fromMul(this.rootOffset, this.poseOffset)+ else console.error('Pose.getWorld - joint not found', id)+ return out+ }++ // Work up the heirarchy till the root bone+ out.copy(joint.local)+ while (joint.pindex !== -1) {+ joint = this.joints[joint.pindex]+ out.pmul(joint.local)+ }++ // Add offset+ out.pmul(this.poseOffset)+ .pmul(this.rootOffset)++ return out+ }+ // #endregion++ // #region DEBUGGING+ debug () {+ const LN = 0x707070+ const PT = 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+ }+ // #endregion}diff --git a/src/retarget/human-retargeting/Quat.ts b/src/retarget/human-retargeting/Quat.tsnew file mode 100644index 0000000..aed6453--- /dev/null+++ b/src/retarget/human-retargeting/Quat.ts@@ -0,0 +1,548 @@+import Vec3 from './Vec3.js'++export default class Quat extends Array {+ constructor (v = null) {+ super(4)+ if (v?.length === 4) this.copy(v)+ else this.identity()+ }++ // #region SETTERS+ identity () {+ this[0] = 0+ this[1] = 0+ this[2] = 0+ this[3] = 1+ return this+ }++ copy (v) {+ this[0] = v[0]+ this[1] = v[1]+ this[2] = v[2]+ this[3] = v[3]+ return this+ }++ copyTo (v) {+ v[0] = this[0]+ v[1] = this[1]+ v[2] = this[2]+ v[3] = this[3]+ return this+ }++ copyObj (o) {+ this[0] = o.x+ this[1] = o.y+ this[2] = o.z+ this[3] = o.w+ return this+ }+ // #endregion++ // #region GETTERS+ clone () { return new Quat(this) }+ // #endregion++ // #region OPERATIONS+ /** Multiple Quaternion onto this Quaternion */+ mul (q) {+ const ax = this[0]; const ay = this[1]; const az = this[2]; const aw = this[3]+ const bx = q[0]; const by = q[1]; const bz = q[2]; const bw = q[3]+ this[0] = ax * bw + aw * bx + ay * bz - az * by+ this[1] = ay * bw + aw * by + az * bx - ax * bz+ this[2] = az * bw + aw * bz + ax * by - ay * bx+ this[3] = aw * bw - ax * bx - ay * by - az * bz+ return this+ }++ /** PreMultiple Quaternions onto this Quaternion */+ pmul (q) {+ const ax = q[0]; const ay = q[1]; const az = q[2]; const aw = q[3]+ const bx = this[0]; const by = this[1]; const bz = this[2]; const bw = this[3]+ this[0] = ax * bw + aw * bx + ay * bz - az * by+ this[1] = ay * bw + aw * by + az * bx - ax * bz+ this[2] = az * bw + aw * bz + ax * by - ay * bx+ this[3] = aw * bw - ax * bx - ay * by - az * bz+ return this+ }++ norm () {+ let len = this[0] ** 2 + this[1] ** 2 + this[2] ** 2 + this[3] ** 2+ if (len > 0) {+ len = 1 / Math.sqrt(len)+ this[0] *= len+ this[1] *= len+ this[2] *= len+ this[3] *= len+ }+ return this+ }++ invert () {+ const a0 = this[0]+ const a1 = this[1]+ const a2 = this[2]+ const a3 = this[3]+ const dot = a0 * a0 + a1 * a1 + a2 * a2 + a3 * a3++ if (dot == 0) { this[0] = this[1] = this[2] = this[3] = 0; return this }++ const invDot = 1.0 / dot // let invDot = dot ? 1.0/dot : 0;+ this[0] = -a0 * invDot+ this[1] = -a1 * invDot+ this[2] = -a2 * invDot+ this[3] = a3 * invDot+ return this+ }+ // #endregion++ // #region SPECIAL OPERATORS+ /** Inverts the quaternion passed in, then pre multiplies to this quaternion. */+ pmulInvert (q) {+ // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~+ // q.invert()+ let ax = q[0]+ let ay = q[1]+ let az = q[2]+ let aw = q[3]++ const dot = ax * ax + ay * ay + az * az + aw * aw++ if (dot === 0) {+ ax = ay = az = aw = 0+ } else {+ const dot_inv = 1.0 / dot+ ax = -ax * dot_inv+ ay = -ay * dot_inv+ az = -az * dot_inv+ aw = aw * dot_inv+ }++ // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~+ // Quat.mul( a, b );+ const bx = this[0]+ const by = this[1]+ const bz = this[2]+ const bw = this[3]+ this[0] = ax * bw + aw * bx + ay * bz - az * by+ this[1] = ay * bw + aw * by + az * bx - ax * bz+ this[2] = az * bw + aw * bz + ax * by - ay * bx+ this[3] = aw * bw - ax * bx - ay * by - az * bz+ return this+ }++ pmulAxisAngle (axis, rad) {+ // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~+ // Quat.AxisAngle()+ const half = rad * 0.5+ const s = Math.sin(half)+ const ax = axis[0] * s+ const ay = axis[1] * s+ const az = axis[2] * s+ const aw = Math.cos(half)++ // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~+ // Quat.mul( a, b );+ const bx = this[0]+ const by = this[1]+ const bz = this[2]+ const bw = this[3]+ this[0] = ax * bw + aw * bx + ay * bz - az * by+ this[1] = ay * bw + aw * by + az * bx - ax * bz+ this[2] = az * bw + aw * bz + ax * by - ay * bx+ this[3] = aw * bw - ax * bx - ay * by - az * bz+ return this+ }++ pmulSwing (a, b) {+ // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~+ // fromSwing+ const dot = Vec3.dot(a, b)+ if (dot < -0.999999) { // 180 opposites+ const tmp = new Vec3().fromCross([-1, 0, 0], a)++ if (tmp.len < 0.000001) tmp.fromCross([0, 1, 0], a)+ this.pmulAxisAngle(tmp.norm(), Math.PI)+ return this+ } else if (dot > 0.999999) { // Same Direction+ return this // Creates identity, so exist early+ }++ const v = Vec3.cross(a, b, [0, 0, 0])+ let ax = v[0]+ let ay = v[1]+ let az = v[2]+ let aw = 1 + dot++ // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~+ // Normalize+ let len = ax ** 2 + ay ** 2 + az ** 2 + aw ** 2+ if (len > 0) {+ len = 1 / Math.sqrt(len)+ ax *= len+ ay *= len+ az *= len+ aw *= len+ }++ // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~+ // Dot Negate+ const dot2 = this[0] * ax + this[1] * ay + this[2] * az + this[3] * aw+ if (dot2 < 0) {+ ax = -ax+ ay = -ay+ az = -az+ aw = -aw+ }++ // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~+ // Quat.mul( a, b );+ const bx = this[0]+ const by = this[1]+ const bz = this[2]+ const bw = this[3]+ this[0] = ax * bw + aw * bx + ay * bz - az * by+ this[1] = ay * bw + aw * by + az * bx - ax * bz+ this[2] = az * bw + aw * bz + ax * by - ay * bx+ this[3] = aw * bw - ax * bx - ay * by - az * bz++ return this+ }++ dotNegate (chk) {+ // quat.dot+ const dot = this[0] * chk[0] ++ this[1] * chk[1] ++ this[2] * chk[2] ++ this[3] * chk[3]++ if (dot < 0) {+ // quat.negate+ this[0] = -this[0]+ this[1] = -this[1]+ this[2] = -this[2]+ this[3] = -this[3]+ }++ return this+ }+ // #endregion++ // #region FROM OPS+ fromMul (a, b) {+ const ax = a[0]; const ay = a[1]; const az = a[2]; const aw = a[3]+ const bx = b[0]; const by = b[1]; const bz = b[2]; const bw = b[3]++ this[0] = ax * bw + aw * bx + ay * bz - az * by+ this[1] = ay * bw + aw * by + az * bx - ax * bz+ this[2] = az * bw + aw * bz + ax * by - ay * bx+ this[3] = aw * bw - ax * bx - ay * by - az * bz+ return this+ }++ fromInvert (q) {+ const a0 = q[0]+ const a1 = q[1]+ const a2 = q[2]+ const a3 = q[3]+ const dot = a0 * a0 + a1 * a1 + a2 * a2 + a3 * a3++ if (dot == 0) { this[0] = this[1] = this[2] = this[3] = 0; return this }++ const invDot = 1.0 / dot // let invDot = dot ? 1.0/dot : 0;+ this[0] = -a0 * invDot+ this[1] = -a1 * invDot+ this[2] = -a2 * invDot+ this[3] = a3 * invDot+ return this+ }++ fromPolar (lon, lat, up = null) {+ 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+ const theta = lon * 0.01745329251+ const phi_s = Math.sin(phi)+ const v = [+ -(phi_s * Math.sin(theta)),+ Math.cos(phi),+ phi_s * Math.cos(theta)+ ]++ this.fromLook(v, up || [0, 1, 0])+ return this+ }++ fromLookOLD (dir, up = [0, 1, 0]) {+ // Ported to JS from C# example at https://pastebin.com/ubATCxJY+ // TODO, if Dir and Up are equal, a roll happends. Need to find a way to fix this.+ const zAxis = new Vec3(dir).norm() // Forward+ const xAxis = new Vec3().fromCross(up, zAxis).norm() // Right+ const yAxis = new Vec3().fromCross(zAxis, xAxis).norm() // Up++ // fromAxis - Mat3 to Quat+ 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++ if (t > 0.0) {+ s = Math.sqrt(t + 1.0)+ w = s * 0.5 // |w| >= 0.5+ s = 0.5 / s+ x = (m12 - m21) * s+ y = (m20 - m02) * s+ z = (m01 - m10) * s+ } else if ((m00 >= m11) && (m00 >= m22)) {+ s = Math.sqrt(1.0 + m00 - m11 - m22)+ x = 0.5 * s// |x| >= 0.5+ s = 0.5 / s+ y = (m01 + m10) * s+ z = (m02 + m20) * s+ w = (m12 - m21) * s+ } else if (m11 > m22) {+ s = Math.sqrt(1.0 + m11 - m00 - m22)+ y = 0.5 * s // |y| >= 0.5+ s = 0.5 / s+ x = (m10 + m01) * s+ z = (m21 + m12) * s+ w = (m20 - m02) * s+ } else {+ s = Math.sqrt(1.0 + m22 - m00 - m11)+ z = 0.5 * s // |z| >= 0.5+ s = 0.5 / s+ x = (m20 + m02) * s+ y = (m21 + m12) * s+ w = (m01 - m10) * s+ }++ this[0] = x+ this[1] = y+ this[2] = z+ this[3] = w+ return this+ }++ fromLook (fwd, up = [0, 1, 0]) {+ // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~+ // Orthogonal axes to make a mat3x3+ const zAxis = new Vec3(fwd)+ const xAxis = new Vec3().fromCross(up, zAxis).norm() // Right++ // Z & UP are parallel+ if (xAxis.lenSqr === 0) {+ if (Math.abs(up[2]) === 1) zAxis[0] += 0.0001 // shift x when Fwd or Bak+ else zAxis[2] += 0.0001 // shift z++ zAxis.norm() // ReNormalize+ xAxis.fromCross(up, zAxis).norm() // Redo Right+ }++ const yAxis = new Vec3().fromCross(zAxis, xAxis).norm() // Up+ const m = [...xAxis, ...yAxis, ...zAxis]++ // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~+ // Mat3 to Quat+ // Algorithm in Ken Shoemake's article in 1987 SIGGRAPH course notes+ // article "Quat Calculus and Fast Animation".+ let fRoot+ const fTrace = m[0] + m[4] + m[8] // Diagonal axis++ if (fTrace > 0.0) {+ // |w| > 1/2, may as well choose w > 1/2+ fRoot = Math.sqrt(fTrace + 1.0) // 2w+ this[3] = 0.5 * fRoot++ fRoot = 0.5 / fRoot // 1/(4w)+ this[0] = (m[5] - m[7]) * fRoot+ this[1] = (m[6] - m[2]) * fRoot+ this[2] = (m[1] - m[3]) * fRoot+ } else {+ // |w| <= 1/2+ let i = 0+ if (m[4] > m[0]) i = 1+ if (m[8] > m[i * 3 + i]) i = 2++ const j = (i + 1) % 3+ const k = (i + 2) % 3++ fRoot = Math.sqrt(m[i * 3 + i] - m[j * 3 + j] - m[k * 3 + k] + 1.0)+ this[i] = 0.5 * fRoot+ fRoot = 0.5 / fRoot+ this[3] = (m[j * 3 + k] - m[k * 3 + j]) * fRoot+ this[j] = (m[j * 3 + i] + m[i * 3 + j]) * fRoot+ this[k] = (m[k * 3 + i] + m[i * 3 + k]) * fRoot+ }++ return this+ }++ /** Using unit vectors, Shortest swing rotation from Direction A to Direction B */+ fromSwing (a, b) {+ // http://physicsforgames.blogspot.com/2010/03/Quat-tricks.html+ const dot = Vec3.dot(a, b)++ if (dot < -0.999999) { // 180 opposites+ const tmp = new Vec3().fromCross([-1, 0, 0], a)++ if (tmp.len < 0.000001) tmp.fromCross([0, 1, 0], a)+ this.fromAxisAngle(tmp.norm(), Math.PI)+ } else if (dot > 0.999999) { // Same Direction+ this[0] = 0+ this[1] = 0+ this[2] = 0+ this[3] = 1+ } else {+ const v = Vec3.cross(a, b, [0, 0, 0])+ this[0] = v[0]+ this[1] = v[1]+ this[2] = v[2]+ this[3] = 1 + dot+ this.norm()+ }++ return this+ }++ /** Axis must be normlized, Angle in Radians */+ fromAxisAngle (axis, rad) {+ const half = rad * 0.5+ const s = Math.sin(half)+ this[0] = axis[0] * s+ this[1] = axis[1] * s+ this[2] = axis[2] * s+ this[3] = Math.cos(half)+ return this+ }++ fromAxes (xAxis, yAxis, zAxis) {+ 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++ if (t > 0.0) {+ s = Math.sqrt(t + 1.0)+ w = s * 0.5 // |w| >= 0.5+ s = 0.5 / s+ x = (m12 - m21) * s+ y = (m20 - m02) * s+ z = (m01 - m10) * s+ } else if ((m00 >= m11) && (m00 >= m22)) {+ s = Math.sqrt(1.0 + m00 - m11 - m22)+ x = 0.5 * s// |x| >= 0.5+ s = 0.5 / s+ y = (m01 + m10) * s+ z = (m02 + m20) * s+ w = (m12 - m21) * s+ } else if (m11 > m22) {+ s = Math.sqrt(1.0 + m11 - m00 - m22)+ y = 0.5 * s // |y| >= 0.5+ s = 0.5 / s+ x = (m10 + m01) * s+ z = (m21 + m12) * s+ w = (m20 - m02) * s+ } else {+ s = Math.sqrt(1.0 + m22 - m00 - m11)+ z = 0.5 * s // |z| >= 0.5+ s = 0.5 / s+ x = (m20 + m02) * s+ y = (m21 + m12) * s+ w = (m01 - m10) * s+ }++ this[0] = x+ this[1] = y+ this[2] = z+ this[3] = w+ return this+ }+ // #endregion++ // #region ROTATIONS+ rotX (rad) {+ // https://github.com/toji/gl-matrix/blob/master/src/gl-matrix/quat.js+ rad *= 0.5++ const ax = this[0]; const ay = this[1]; const az = this[2]; const aw = this[3]+ const bx = Math.sin(rad); const bw = Math.cos(rad)++ this[0] = ax * bw + aw * bx+ this[1] = ay * bw + az * bx+ this[2] = az * bw - ay * bx+ this[3] = aw * bw - ax * bx+ return this+ }++ rotY (rad) {+ rad *= 0.5++ const ax = this[0]; const ay = this[1]; const az = this[2]; const aw = this[3]+ const by = Math.sin(rad); const bw = Math.cos(rad)++ this[0] = ax * bw - az * by+ this[1] = ay * bw + aw * by+ this[2] = az * bw + ax * by+ this[3] = aw * bw - ay * by+ return this+ }++ rotZ (rad) {+ rad *= 0.5++ const ax = this[0]; const ay = this[1]; const az = this[2]; const aw = this[3]+ const bz = Math.sin(rad)+ const bw = Math.cos(rad)++ this[0] = ax * bw + ay * bz+ this[1] = ay * bw - ax * bz+ this[2] = az * bw + aw * bz+ this[3] = aw * bw - az * bz+ return this+ }+ // #endregion++ // #region CONVERT+ fromMat3 (m) {+ // https://github.com/toji/gl-matrix/blob/master/src/gl-matrix/quat.js#L305+ // Algorithm in Ken Shoemake's article in 1987 SIGGRAPH course notes+ // article "Quat Calculus and Fast Animation".+ let fRoot+ const fTrace = m[0] + m[4] + m[8]++ if (fTrace > 0.0) {+ // |w| > 1/2, may as well choose w > 1/2+ fRoot = Math.sqrt(fTrace + 1.0) // 2w+ this[3] = 0.5 * fRoot++ fRoot = 0.5 / fRoot // 1/(4w)+ this[0] = (m[5] - m[7]) * fRoot+ this[1] = (m[6] - m[2]) * fRoot+ this[2] = (m[1] - m[3]) * fRoot+ } else {+ // |w| <= 1/2+ let i = 0++ if (m[4] > m[0]) i = 1+ if (m[8] > m[i * 3 + i]) i = 2++ const j = (i + 1) % 3+ const k = (i + 2) % 3++ fRoot = Math.sqrt(m[i * 3 + i] - m[j * 3 + j] - m[k * 3 + k] + 1.0)+ this[i] = 0.5 * fRoot++ fRoot = 0.5 / fRoot+ this[3] = (m[j * 3 + k] - m[k * 3 + j]) * fRoot+ this[j] = (m[j * 3 + i] + m[i * 3 + j]) * fRoot+ this[k] = (m[k * 3 + i] + m[i * 3 + k]) * fRoot+ }+ return this+ }+ // #endregion+}diff --git a/src/retarget/human-retargeting/Retargeter.ts b/src/retarget/human-retargeting/Retargeter.tsnew file mode 100644index 0000000..c79f42d--- /dev/null+++ b/src/retarget/human-retargeting/Retargeter.ts@@ -0,0 +1,251 @@+import * as THREE from 'three'+import { type Rig } from './Rig'+import { type Pose } from './Pose'+import { type ChainTwistAdditive } from './ChainTwistAdditive'+import Vec3 from './Vec3'+import Quat from './Quat'+import Transform from './Transform'++export 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++ // #region SETTERS+ setSourceRig (rig: any) { this.srcRig = rig; return this }+ setTargetRig (rig: any) { this.tarRig = rig; return this }+ setClip (clip) {+ this.clip = clip++ if (this.action !== null) {+ this.action.stop() // TODO - Find how to clear out memory instead of just stopping it+ this.action = null+ }++ return this+ }+ // #endregion++ // #region METHODS+ update (delta_time: number): void {+ // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~+ // PREPARE+ if (this.action === null) {+ this.action = this.mixer.clipAction(this.clip, this.srcRig.skel.bones[0])+ this.action.play()+ }++ if (this.pose == null) this.pose = this.tarRig.tpose.clone()++ // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~+ // Run Animation+ this.mixer.update(delta_time)++ // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~+ // Compute vectors from animation source+ // then align target joints to it+ this.applyScaledTranslation('pelvis')+ this.applyChain('pelvis')+ this.applyEndInterp('spine')+ this.applyChain('head')++ this.applyChain('armL')+ this.applyChain('armR')+ this.applyChain('legL')+ this.applyChain('legR')++ // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~+ // Run Addtives+ for (const i of this.additives) {+ i.apply(this)+ }++ // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~+ // Apply working pose to 3JS skeleton for rendering+ this.pose.toSkeleton(this.tarRig.skel)+ }++ // Apply SwingTwist to each joint of a chain, 1 to 1 mappings+ applyChain (k) {+ // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~+ const src = this.srcRig.chains[k]+ const tar = this.tarRig.chains[k]+ if (!src || !tar) return++ // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~+ const cnt = src.length+ const v = new THREE.Vector3()+ const q = new THREE.Quaternion()++ const p = new Vec3()+ const sPos = new Vec3()+ const sRot = new Quat()+ const tRot = new Quat()+ const rot = new Quat()++ const sSwing = new Vec3() // Source Swing+ const sTwist = new Vec3() // Source Twist+ const nSwing = new Vec3()+ const nTwist = new Vec3()++ const ptran = new Transform()+ const ctran = new Transform()++ let b+ let j++ for (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+ b = this.srcRig.skel.bones[src[i].idx]+ b.getWorldPosition(v)+ b.getWorldQuaternion(q)+ sPos.copyObj(v)+ sRot.copyObj(q)++ sSwing.fromQuat(sRot, src[i].swing)+ sTwist.fromQuat(sRot, src[i].twist)++ // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~+ // Get Target Neutral Transform for the joint+ // ( neutralTwistDir x targetTwistDir ) * ( neutralSwingDir x targetSwingDir ) * neutralRot+ j = this.tarRig.tpose.joints[tar[i].idx]++ // neutral = currentPose.joint.world * tpose.joint.local+ this.pose.getWorld(j.pindex, ptran) // Current transform of parent joint+ ctran.fromMul(ptran, j.local) // Applied to TPose transform++ // ----------------------------+ // SWING+ nSwing.fromQuat(ctran.rot, tar[i].swing) // Get swing direction+ rot.fromSwing(nSwing, sSwing) // Rotation to match swing directions+ .mul(ctran.rot) // Apply to neutral rotation++ nSwing.fromQuat(rot, tar[i].swing) // For Debugging++ // ----------------------------+ // TWIST+ nTwist.fromQuat(rot, tar[i].twist) // Get twist from swing rotation+ tRot.fromSwing(nTwist, sTwist) // Rotation to match twist vectors+ rot.pmul(tRot) // Apply to swing rotation++ nTwist.fromQuat(rot, tar[i].twist) // For Debugging++ // ----------------------------+ rot.pmulInvert(ptran.rot) // To LocalSpace+ this.pose.setRot(tar[i].idx, rot) // Save to working pose++ // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~+ // 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)++ // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~+ // 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)+ }+ }++ // 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++ const dTran = new Transform() // Debug+ const vv = new Vec3() // Debug++ // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~+ const aTran = 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)++ // Visualize data over source skeleton+ 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)++ // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~+ 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+ itm = tar[i]++ // Lerp Target Vectors+ tDir.fromLerp(aSwing, bSwing, t).norm()+ dir.fromLerp(aTwist, bTwist, t).norm()++ // Make joint vectors match target vectors+ const rot = applySwingTwist(itm, tDir, dir, 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)+ }+ }++ // Compute offset translation & scale it to fit better on target+ applyScaledTranslation (k) {+ // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~+ // 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++ // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~+ // Compute offset position change from animation+ const 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++ // ( animated.joint.world.pos - tpose.joint.world.pos ) * ( tarHipHeight / srcHipHeight )+ const offset = new Vec3()+ .fromSub(srcTran.pos, tJoint.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)++ // Add scaled offset translation+ const pos = new Vec3().fromAdd(ctran.pos, offset)++ // Save to local space+ this.pose.setPos(tar.idx, ptran.toLocalPos(pos))+ }+ // #endregion+}diff --git a/src/retarget/human-retargeting/Rig.ts b/src/retarget/human-retargeting/Rig.tsnew file mode 100644index 0000000..1b3c42c--- /dev/null+++ b/src/retarget/human-retargeting/Rig.ts@@ -0,0 +1,90 @@+// Setup a standard definition of what a Humanoid is. The rig+// allows to work with different skeletons with various joint+// naming convention. This makes it easier to build a system+// that speaks a single language of whats what.+export class Rig {+ constructor (skel) {+ this.skel = skel+ this.chains = {}+ this.tpose = new Pose(skel)+ this.scalar = 1+ // this.tpose.debug();+ }++ fromConfig (cfg = {}) {+ 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 '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 '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+ }+ }+ return this+ }++ buildItem (k, names, swing, twist) {+ const ary = []+ let j++ for (const n of names) {+ j = this.tpose.getJoint(n)+ if (!j) { console.log('Error - Rig.buildLimb : Joint name not found in tpose, ', n); continue }++ ary.push(new RigItem().fromJoint(j, swing, twist))+ }++ this.chains[k] = ary+ return this+ }++ buildScalar (k) {+ const ch = this.chains[k]+ const j = this.tpose.joints[ch[0].idx]+ this.scalar = j.world.pos[1]+ return this+ }++ debugSkelVectors () {+ // 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 () {+ // 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) {+ 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.tsnew file mode 100644index 0000000..efa6590--- /dev/null+++ b/src/retarget/human-retargeting/RigItem.ts@@ -0,0 +1,23 @@+// Rig data about a single joint+export class RigItem {+ constructor () {+ this.idx = -1 // Joint Index+ this.pidx = -1 // Parent Joint Index+ this.swing = new Vec3(0, 0, 1) // Swing Direction - Z+ this.twist = new Vec3(0, 1, 0) // Twist Direction - Y+ }++ fromJoint (j, swing = null, twist = null) {+ this.idx = j.index+ this.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)+ }++ return this+ }+}diff --git a/src/retarget/human-retargeting/SwingTwistRetargeter.ts b/src/retarget/human-retargeting/SwingTwistRetargeter.tsdeleted file mode 100644index 6ded8ee..0000000--- a/src/retarget/human-retargeting/SwingTwistRetargeter.ts+++ /dev/null@@ -1,14 +0,0 @@-export class SwingTwistRetargeter {- private srcRig = null // Rig & Skeleton of the animation- private tarRig = null // Rig & Skeleton of target character-- public set_source_rig (rig: any): any {- this.srcRig = rig- return this- }-- public set_target_rig (rig: any): any {- this.tarRig = rig- return this- }-}diff --git a/src/retarget/human-retargeting/lib/maths/Transform.ts b/src/retarget/human-retargeting/Transform.tssimilarity index 100%rename from src/retarget/human-retargeting/lib/maths/Transform.tsrename to src/retarget/human-retargeting/Transform.tsdiff --git a/src/retarget/human-retargeting/Vec3.ts b/src/retarget/human-retargeting/Vec3.tsnew file mode 100644index 0000000..729cb54--- /dev/null+++ b/src/retarget/human-retargeting/Vec3.ts@@ -0,0 +1,304 @@+export default class Vec3 extends Array {+ constructor (v = null) {+ super(3)+ if (v?.length === 3) this.copy(v)+ else this.zero()+ }++ // #region SETTERS+ zero () {+ this[0] = 0+ this[1] = 0+ this[2] = 0+ return this+ }++ copy (v) {+ this[0] = v[0]+ this[1] = v[1]+ this[2] = v[2]+ return this+ }++ copyTo (v) {+ v[0] = this[0]+ v[1] = this[1]+ v[2] = this[2]+ return this+ }++ xyz (x, y, z) {+ this[0] = x+ this[1] = y+ this[2] = z+ return this+ }++ copyObj (o) {+ this[0] = o.x+ this[1] = o.y+ this[2] = o.z+ return this+ }+ // #endregion++ // #region GETTERS+ get len () { return Math.sqrt(this[0] ** 2 + this[1] ** 2 + this[2] ** 2) }+ get lenSqr () { return this[0] ** 2 + this[1] ** 2 + this[2] ** 2 }++ clone () { return new Vec3(this) }+ // #endregion++ // #region FROM OPS+ fromAdd (a, b) {+ this[0] = a[0] + b[0]+ this[1] = a[1] + b[1]+ this[2] = a[2] + b[2]+ return this+ }++ fromSub (a, b) {+ this[0] = a[0] - b[0]+ this[1] = a[1] - b[1]+ this[2] = a[2] - b[2]+ return this+ }++ fromScale (v, s) {+ this[0] = v[0] * s+ this[1] = v[1] * s+ this[2] = v[2] * s+ return this+ }++ fromScaleThenAdd (scale, a, b) {+ this[0] = a[0] * scale + b[0]+ this[1] = a[1] * scale + b[1]+ this[2] = a[2] * scale + b[2]+ return this+ }++ fromNorm (v) {+ let mag = Math.sqrt(v[0] ** 2 + v[1] ** 2 + v[2] ** 2)+ if (mag == 0) return this++ mag = 1 / mag+ this[0] = v[0] * mag+ this[1] = v[1] * mag+ this[2] = v[2] * mag+ return this+ }++ fromCross (a, b) {+ const ax = a[0]; const ay = a[1]; const az = a[2]+ const bx = b[0]; const by = b[1]; const bz = b[2]++ this[0] = ay * bz - az * by+ this[1] = az * bx - ax * bz+ this[2] = ax * by - ay * bx+ return this+ }++ fromQuat (q, v = [0, 0, 1]) {+ const qx = q[0]; const qy = q[1]; const qz = q[2]; const qw = q[3]+ const vx = v[0]; const vy = v[1]; const vz = v[2]+ const x1 = qy * vz - qz * vy+ const y1 = qz * vx - qx * vz+ const z1 = qx * vy - qy * vx+ const x2 = qw * x1 + qy * z1 - qz * y1+ const y2 = qw * y1 + qz * x1 - qx * z1+ const z2 = qw * z1 + qx * y1 - qy * x1+ this[0] = vx + 2 * x2+ this[1] = vy + 2 * y2+ this[2] = vz + 2 * z2+ return this+ }++ fromLerp (a, b, t) {+ const ti = 1 - t+ this[0] = a[0] * ti + b[0] * t+ this[1] = a[1] * ti + b[1] * t+ this[2] = a[2] * ti + b[2] * t+ return this+ }++ fromPlaneSnap (pnt, planeNorm, planePos = [0, 0, 0]) {+ if (!pnt) pnt = this++ // Dot Product between pnt vector & normal+ const dot =+ (pnt[0] - planePos[0]) * planeNorm[0] ++ (pnt[1] - planePos[1]) * planeNorm[1] ++ (pnt[2] - planePos[2]) * planeNorm[2]++ // Snap point to plane+ this[0] = pnt[0] - dot * planeNorm[0]+ this[1] = pnt[1] - dot * planeNorm[1]+ this[2] = pnt[2] - dot * planeNorm[2]++ return this+ }++ // #endregion++ // #region OPERATORS+ add (a) {+ this[0] += a[0]+ this[1] += a[1]+ this[2] += a[2]+ return this+ }++ sub (v) {+ this[0] -= v[0]+ this[1] -= v[1]+ this[2] -= v[2]+ return this+ }++ mul (v) {+ this[0] *= v[0]+ this[1] *= v[1]+ this[2] *= v[2]+ return this+ }++ scale (v) {+ this[0] *= v+ this[1] *= v+ this[2] *= v+ return this+ }++ invScale (v) {+ this[0] /= v+ this[1] /= v+ this[2] /= v+ return this+ }++ scaleThenAdd (s, v) {+ this[0] += v[0] * s+ this[1] += v[1] * s+ this[2] += v[2] * s+ return this+ }++ cross (b) {+ const ax = this[0]; const ay = this[1]; const az = this[2]+ const bx = b[0]; const by = b[1]; const bz = b[2]++ this[0] = ay * bz - az * by+ this[1] = az * bx - ax * bz+ this[2] = ax * by - ay * bx+ return this+ }++ norm () {+ let mag = Math.sqrt(this[0] ** 2 + this[1] ** 2 + this[2] ** 2)+ if (mag != 0) {+ mag = 1 / mag+ this[0] *= mag+ this[1] *= mag+ this[2] *= mag+ }+ return this+ }++ negate () {+ this[0] = -this[0]+ this[1] = -this[1]+ this[2] = -this[2]+ return this+ }++ transformQuat (q) {+ const qx = q[0]; const qy = q[1]; const qz = q[2]; const qw = q[3]+ const vx = this[0]; const vy = this[1]; const vz = this[2]+ const x1 = qy * vz - qz * vy+ const y1 = qz * vx - qx * vz+ const z1 = qx * vy - qy * vx+ const x2 = qw * x1 + qy * z1 - qz * y1+ const y2 = qw * y1 + qz * x1 - qx * z1+ const z2 = qw * z1 + qx * y1 - qy * x1+ this[0] = vx + 2 * x2+ this[1] = vy + 2 * y2+ this[2] = vz + 2 * z2+ return this+ }++ axisAngle (axis, rad) {+ // Rodrigues Rotation formula:+ // v_rot = v * cos(theta) + cross( axis, v ) * sin(theta) + axis * dot( axis, v) * (1-cos(theta))+ const cp = new Vec3().fromCross(axis, this)+ const dot = Vec3.dot(axis, this)+ const s = Math.sin(rad)+ const c = Math.cos(rad)+ const ci = 1 - c++ this[0] = this[0] * c + cp[0] * s + axis[0] * dot * ci+ this[1] = this[1] * c + cp[1] * s + axis[1] * dot * ci+ this[2] = this[2] * c + cp[2] * s + axis[2] * dot * ci+ return this+ }+ // #endregion++ // #region STATIC OPS+ static len (a) { return Math.sqrt(a[0] ** 2 + a[1] ** 2 + a[2] ** 2) }+ static lenSqr (a) { return a[0] ** 2 + a[1] ** 2 + a[2] ** 2 }++ static dist (a, b) { return Math.sqrt((a[0] - b[0]) ** 2 + (a[1] - b[1]) ** 2 + (a[2] - b[2]) ** 2) }+ static distSqr (a, b) { return (a[0] - b[0]) ** 2 + (a[1] - b[1]) ** 2 + (a[2] - b[2]) ** 2 }++ static dot (a, b) { return a[0] * b[0] + a[1] * b[1] + a[2] * b[2] }+ static cross (a, b, out = new Vec3()) {+ const ax = a[0]; const ay = a[1]; const az = a[2]+ const bx = b[0]; const by = b[1]; const bz = b[2]++ out[0] = ay * bz - az * by+ out[1] = az * bx - ax * bz+ out[2] = ax * by - ay * bx+ return out+ }++ static angle (a, b) {+ // acos(dot(a,b)/(len(a)*len(b)))+ // const theta = this.dot( a, b ) / ( Math.sqrt( Vec3.lenSqr(a) * Vec3.lenSqr(b) ) );+ // return Math.acos( Math.max( -1, Math.min( 1, theta ) ) ); // clamp ( t, -1, 1 )++ // atan2(len(cross(a,b)),dot(a,b))+ const d = this.dot(a, b)+ const c = this.cross(a, b)+ return Math.atan2(Vec3.len(c), d)++ // This also works, but requires more LEN / SQRT Calls+ // 2 * atan2( ( u * v.len - v * u.len ).len, ( u * v.len + v * u.len ).len );++ // https://math.stackexchange.com/questions/1143354/numerically-stable-method-for-angle-between-3d-vectors/1782769+ // θ=2 atan2(|| ||v||u−||u||v ||, || ||v||u+||u||v ||)++ // let cosine = this.dot( a, b );+ // if(cosine > 1.0) return 0;+ // else if(cosine < -1.0) return Math.PI;+ // else return Math.acos( cosine / ( Math.sqrt( a.lenSqr * b.lenSqr() ) ) );+ }++ static look (fwd, up = [0, 1, 0]) {+ const zAxis = new Vec3(fwd).norm()+ const xAxis = new Vec3().fromCross(up, zAxis).norm() // Right++ // Z & UP are parallel+ if (xAxis.lenSqr === 0) {+ if (Math.abs(up[2]) === 1) { zAxis[0] += 0.0001 } // shift x when Fwd or Bak+ else { zAxis[2] += 0.0001 } // shift z++ zAxis.norm() // ReNormalize+ xAxis.fromCross(up, zAxis).norm() // Redo Right+ }++ const yAxis = new Vec3().fromCross(zAxis, xAxis).norm() // Up+ return [xAxis, yAxis, zAxis]+ }++ // #endregion+}