All files / systems/animation/core SkeletalPosePlayback.ts

100% Statements 61/61
86.2% Branches 25/29
100% Functions 9/9
100% Lines 59/59

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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                                              13x 13x       163x 163x   47x 47x 3412x 3412x 956x 956x   3412x   47x 227x 227x 227x 3176x           227x 236x     47x         163x 163x                   37128x 37128x 37128x 35115x 35115x       2013x 15101x 1830x 1830x         1830x   13271x   183x 10x   173x             14x 14x 14x 18564x 18564x   18564x 18564x       392x                     6x 168x 168x         663x 663x 663x 663x 18564x 18564x 18564x 18564x 18564x 16884x 16884x   18564x 18564x        
import { Quaternion, Vector3 } from "three";
import type { SkeletalAnimation, SkeletalRig } from "../../../types/skeletal";
import { getEasingFunction } from "../builders/KeyframeInterpolation";
 
type Easing = ReturnType<typeof getEasingFunction>;
 
interface TrackKey<T> {
  readonly time: number;
  readonly value: T;
  readonly easing: Easing;
}
 
interface BoneTracks {
  readonly rotations: TrackKey<Quaternion>[];
  readonly offsets: TrackKey<Vector3>[];
}
 
export interface PreparedSkeletalPose {
  readonly tracks: ReadonlyMap<string, BoneTracks>;
  readonly start: number;
  readonly end: number;
}
 
const preparedClips = new WeakMap<SkeletalAnimation, PreparedSkeletalPose>();
const zeroOffset = new Vector3();
 
/** Cache authored tracks, not quantized samples or rig-dependent transforms. */
export function prepareSkeletalPose(clip: SkeletalAnimation): PreparedSkeletalPose {
  const cached = preparedClips.get(clip);
  if (cached) return cached;
 
  const tracks = new Map<string, BoneTracks>();
  const getBoneTracks = (name: string): BoneTracks => {
    let channels = tracks.get(name);
    if (!channels) {
      channels = { rotations: [], offsets: [] };
      tracks.set(name, channels);
    }
    return channels;
  };
  for (const key of clip.keyframes) {
    const { time } = key;
    const easing = getEasingFunction(key.easing);
    for (const [name, rotation] of key.boneRotations) {
      getBoneTracks(name).rotations.push({
        time,
        easing,
        value: new Quaternion().setFromEuler(rotation),
      });
    }
    for (const [name, offset] of key.bonePositions) {
      getBoneTracks(name).offsets.push({ time, easing, value: offset });
    }
  }
  const prepared = {
    tracks,
    start: clip.keyframes[0]?.time ?? 0,
    end: clip.keyframes.at(-1)?.time ?? 0,
  };
  preparedClips.set(clip, prepared);
  return prepared;
}
 
/** Internal holes are unkeyed; missing track endpoints use the rig's rest pose. */
function sampleTrack<T extends Quaternion | Vector3>(
  keys: readonly TrackKey<T>[] | undefined,
  rest: T,
  clock: { readonly time: number; readonly start: number; readonly end: number },
  write: (from: T, to: T, alpha: number) => void,
): void {
  const { time, start, end } = clock;
  const first = keys?.[0];
  if (!keys || !first) {
    write(rest, rest, 0);
    return;
  }
 
  let prev: TrackKey<T> | undefined;
  for (const next of keys) {
    if (time < next.time) {
      const fromTime = prev?.time ?? start;
      write(
        prev?.value ?? rest,
        next.value,
        next.easing((time - fromTime) / (next.time - fromTime)),
      );
      return;
    }
    prev = next;
  }
  if (prev && prev.time < end) {
    write(prev.value, rest, (time - prev.time) / (end - prev.time));
  } else {
    write(prev?.value ?? rest, prev?.value ?? rest, 0);
  }
}
 
/** Per-rig scratch space for exact pose sampling and interrupted crossfades. */
export class SkeletalPosePlayback {
  private readonly bones;
  private readonly rotation = new Quaternion();
  private readonly position = new Vector3();
  private readonly clock = { time: 0, start: 0, end: 0 };
  private readonly writeRotation = (from: Quaternion, to: Quaternion, t: number) => {
    this.rotation.slerpQuaternions(from, to, t);
  };
  private readonly writeOffset = (from: Vector3, to: Vector3, t: number) => {
    this.position.lerpVectors(from, to, t);
  };
 
  constructor(rig: SkeletalRig) {
    this.bones = Array.from(rig.bones, ([name, bone]) => ({
      name,
      bone,
      rest: new Quaternion().setFromEuler(bone.restRotation),
      fromRotation: new Quaternion(),
      fromPosition: new Vector3(),
    }));
  }
 
  /** Capture the displayed pose at a handoff, even during another blend. */
  capture(): void {
    for (const { bone, fromRotation, fromPosition } of this.bones) {
      fromRotation.setFromEuler(bone.rotation);
      fromPosition.copy(bone.position);
    }
  }
 
  apply(pose: PreparedSkeletalPose, time: number, blendWeight = 1): void {
    this.clock.time = Math.min(Math.max(time, pose.start), pose.end);
    this.clock.start = pose.start;
    this.clock.end = pose.end;
    for (const { name, bone, rest, fromRotation, fromPosition } of this.bones) {
      const tracks = pose.tracks.get(name);
      sampleTrack(tracks?.rotations, rest, this.clock, this.writeRotation);
      sampleTrack(tracks?.offsets, zeroOffset, this.clock, this.writeOffset);
      this.position.add(bone.restPosition);
      if (blendWeight < 1) {
        this.rotation.slerp(fromRotation, 1 - blendWeight);
        this.position.lerp(fromPosition, 1 - blendWeight);
      }
      bone.rotation.setFromQuaternion(this.rotation, bone.restRotation.order);
      bone.position.copy(this.position);
    }
  }
}