All files / systems/animation KeyframeInterpolation.ts

97.63% Statements 165/169
75% Branches 45/60
100% Functions 28/28
97.53% Lines 158/162

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 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 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922                                                                                                                                                                                                            1195x         1195x         1195x       1195x                                                 1175x                               146x                       33x                                                                                         821x                   301x                   229x                   33x 1x     1x                             33x                           33x                           33x                                                                                   33x     463x   51x   42x   1x   1x   117x   1x   1x   1x   248x                             33x       336x     336x           336x 336x 336x   336x 451x 451x   451x 336x 336x     336x 336x 336x   336x       336x                               33x           993x     993x 993x     993x             993x 993x                               33x           353x 353x                           33x         336x     336x     336x 336x         336x   870x   870x   870x           870x       336x 336x         336x   236x   236x   236x           236x     336x                                   33x         102x 624x 624x 624x         102x 2x 2x   2x                                   33x         117x     117x 117x         117x 123x 123x 123x 123x       117x 117x         117x 117x 117x 117x 117x     117x                                           33x             102x 102x     102x 5x     5x 5x         102x   102x                                                                         33x               117x 117x     117x 117x   117x                                                             370x                                         33x           7x   6x 6x     6x 7x 7x 7x     7x           6x 7x 7x   7x 7x     7x     7x 7x 7x 7x   7x   1x 1x     6x               7x         7x     7x           7x       6x                                                                 33x           107x     107x 107x 108x 108x   107x     107x   1x         107x 107x 107x 107x   107x           107x           107x              
/**
 * Keyframe interpolation for smooth skeletal animations
 * 
 * Provides interpolation between animation keyframes for smooth 60fps playback.
 * Supports linear, ease-in, ease-out, and ease-in-out easing functions.
 * 
 * @module systems/animation/KeyframeInterpolation
 * @category Animation System
 * @korean 키프레임보간
 */
 
import * as THREE from "three";
import type {
  AnimationKeyframe,
  SkeletalAnimation,
  SkeletalRig,
} from "../../types/skeletal";
 
/**
 * Easing function type
 * 
 * @param t - Time value between 0 and 1
 * @returns Eased value between 0 and 1
 * 
 * @korean 이징함수타입
 */
type EasingFunction = (t: number) => number;
 
/**
 * Cubic bezier control points for easing curves
 * 
 * **Korean**: 3차 베지어 제어점
 * 
 * @public
 * @category Animation
 * @korean 베지어제어점
 */
export interface BezierControlPoints {
  /** First control point x (0-1) */
  readonly p1x: number;
  /** First control point y (0-1) */
  readonly p1y: number;
  /** Second control point x (0-1) */
  readonly p2x: number;
  /** Second control point y (0-1) */
  readonly p2y: number;
  /** 
   * Enable precision mode for exact bezier curve calculation
   * 
   * **Reserved for future implementation.**
   * 
   * When false (default), uses simplified approximation assuming x progresses linearly with t.
   * This is standard for CSS cubic-bezier() and provides good results with minimal overhead.
   * 
   * When true (future), will perform iterative solving for accurate x-t mapping (higher CPU cost).
   * This would enable non-linear time progression for more complex easing curves.
   * 
   * Currently unused - kept in interface for forward compatibility without breaking API changes.
   * 
   * @korean 정밀모드
   */
  readonly precisionMode?: boolean;
}
 
/**
 * Cubic bezier easing for natural movement
 * 
 * **Korean**: 3차 베지어 이징
 * 
 * Implements cubic bezier curve interpolation for smooth, natural motion.
 * Based on CSS cubic-bezier() function specification.
 * 
 * This function uses a configuration object approach for better API clarity.
 * By default, uses simplified approximation (x progresses linearly with t) which
 * provides good results for animation with minimal overhead. Enable precisionMode
 * for exact calculations when needed.
 * 
 * @param t - Input time (0-1)
 * @param options - Bezier control points and configuration
 * @returns Eased value
 * 
 * @example
 * ```typescript
 * // Natural Korean martial arts movement (physics-based)
 * const eased = cubicBezierWithOptions(0.5, { 
 *   p1x: 0.25, p1y: 0.1, p2x: 0.25, p2y: 1.0 
 * });
 * 
 * // With precision mode for exact calculation
 * const precise = cubicBezierWithOptions(0.5, {
 *   p1x: 0.42, p1y: 0, p2x: 0.58, p2y: 1.0,
 *   precisionMode: true
 * });
 * ```
 * 
 * @korean 3차베지어이징옵션
 */
export function cubicBezierWithOptions(
  t: number,
  options: BezierControlPoints
): number {
  // Clamp t to [0, 1]
  const clampedT = Math.max(0, Math.min(1, t));
  
  // For performance, use direct calculation (standard for CSS cubic-bezier)
  // Note: options.precisionMode is currently unused and reserved for future implementation
  // where we could add iterative solving for exact x-t mapping
  const u = 1 - clampedT;
  
  // Cubic bezier formula: B(t) = (1-t)³P₀ + 3(1-t)²tP₁ + 3(1-t)t²P₂ + t³P₃
  // For easing, P₀ = (0,0) and P₃ = (1,1), so:
  // y(t) = 3(1-t)²t*p1y + 3(1-t)t²*p2y + t³
  const result = 3 * u * u * clampedT * options.p1y + 
                 3 * u * clampedT * clampedT * options.p2y + 
                 clampedT * clampedT * clampedT;
  
  return result;
}
 
/**
 * Cubic bezier easing (legacy function signature for backward compatibility)
 * 
 * **Korean**: 3차 베지어 이징 (레거시)
 * 
 * @param t - Input time (0-1)
 * @param p1x - First control point x (0-1) - currently unused, reserved for precision mode
 * @param p1y - First control point y (can exceed 0-1 for overshoot)
 * @param p2x - Second control point x (0-1) - currently unused, reserved for precision mode
 * @param p2y - Second control point y (can exceed 0-1 for overshoot)
 * @returns Eased value
 * 
 * @deprecated Use cubicBezierWithOptions for clearer API
 * @korean 3차베지어이징레거시
 */
export function cubicBezier(
  t: number,
  p1x: number,
  p1y: number,
  p2x: number,
  p2y: number
): number {
  return cubicBezierWithOptions(t, { p1x, p1y, p2x, p2y });
}
 
/**
 * Create a cubic bezier easing function with control points
 * 
 * **Korean**: 베지어 이징 함수 생성
 * 
 * Factory function to create reusable bezier easing functions.
 * 
 * @param points - Bezier control points
 * @returns Easing function
 * 
 * @korean 베지어이징함수생성
 */
export function createBezierEasing(points: BezierControlPoints): EasingFunction {
  return (t: number) => cubicBezier(t, points.p1x, points.p1y, points.p2x, points.p2y);
}
 
/**
 * Preset bezier easing curves for Korean martial arts movements
 * 
 * **Korean**: 무도 동작 이징 곡선
 * 
 * @public
 * @category Animation
 * @korean 무도동작이징곡선
 */
export const BEZIER_PRESETS = {
  /**
   * Natural motion with physics-based acceleration/deceleration
   * Ideal for: Stance transitions, body rotations, weight shifts
   * **Korean**: 자연스러운 물리 기반 동작
   */
  naturalMotion: { p1x: 0.25, p1y: 0.1, p2x: 0.25, p2y: 1.0 },
  
  /**
   * Smooth S-curve for fluid transitions
   * Ideal for: Attack wind-ups, defensive positioning, footwork
   * **Korean**: 부드러운 S곡선 전환
   */
  smoothTransition: { p1x: 0.42, p1y: 0.0, p2x: 0.58, p2y: 1.0 },
  
  /**
   * Quick start with gentle landing
   * Ideal for: Strike recoil, guard recovery, step completion
   * **Korean**: 빠른 시작과 부드러운 착지
   */
  quickStart: { p1x: 0.1, p1y: 0.8, p2x: 0.25, p2y: 1.0 },
  
  /**
   * Explosive power curve
   * Ideal for: Explosive strikes, power techniques, ki projection
   * **Korean**: 폭발적 힘 곡선
   */
  explosivePower: { p1x: 0.05, p1y: 0.9, p2x: 0.2, p2y: 1.0 },
  
  /**
   * Controlled deceleration
   * Ideal for: Defensive withdrawals, cautious movements, guard stance
   * **Korean**: 제어된 감속
   */
  controlledSlow: { p1x: 0.6, p1y: 0.0, p2x: 0.9, p2y: 0.4 },
} as const;
 
/**
 * Linear easing (no easing)
 * 
 * @param t - Input time (0-1)
 * @returns Same as input
 * 
 * @korean 선형이징
 */
export const easeLinear: EasingFunction = (t: number): number => t;
 
/**
 * Ease-in (slow start, fast end) - Simple quadratic
 * 
 * @param t - Input time (0-1)
 * @returns Eased value
 * 
 * @korean 이즈인
 */
export const easeIn: EasingFunction = (t: number): number => t * t;
 
/**
 * Ease-out (fast start, slow end) - Simple quadratic
 * 
 * @param t - Input time (0-1)
 * @returns Eased value
 * 
 * @korean 이즈아웃
 */
export const easeOut: EasingFunction = (t: number): number => t * (2 - t);
 
/**
 * Ease-in-out (slow start, slow end) - Simple quadratic
 * 
 * @param t - Input time (0-1)
 * @returns Eased value
 * 
 * @korean 이즈인아웃
 */
export const easeInOut: EasingFunction = (t: number): number => {
  Iif (t < 0.5) {
    return 2 * t * t;
  }
  return -1 + (4 - 2 * t) * t;
};
 
/**
 * Natural motion bezier easing (preset)
 * 
 * **Korean**: 자연스러운 동작 이징
 * 
 * Physics-based movement ideal for Korean martial arts.
 * 
 * @param t - Input time (0-1)
 * @returns Eased value
 * 
 * @korean 자연동작이징
 */
export const easeNaturalMotion: EasingFunction = createBezierEasing(BEZIER_PRESETS.naturalMotion);
 
/**
 * Smooth transition bezier easing (preset)
 * 
 * **Korean**: 부드러운 전환 이징
 * 
 * S-curve for fluid stance transitions.
 * 
 * @param t - Input time (0-1)
 * @returns Eased value
 * 
 * @korean 부드러운전환이징
 */
export const easeSmoothTransition: EasingFunction = createBezierEasing(BEZIER_PRESETS.smoothTransition);
 
/**
 * Explosive power bezier easing (preset)
 * 
 * **Korean**: 폭발적 힘 이징
 * 
 * Explosive acceleration for power strikes.
 * 
 * @param t - Input time (0-1)
 * @returns Eased value
 * 
 * @korean 폭발적힘이징
 */
export const easeExplosivePower: EasingFunction = createBezierEasing(BEZIER_PRESETS.explosivePower);
 
/**
 * Extended easing function names including bezier presets
 * 
 * **Korean**: 확장된 이징 함수 이름
 * 
 * @public
 * @category Animation
 * @korean 확장이징함수이름
 */
export type EasingName = 
  | "linear"
  | "ease-in" 
  | "ease-out" 
  | "ease-in-out"
  | "natural-motion"
  | "smooth-transition"
  | "quick-start"
  | "explosive-power"
  | "controlled-slow";
 
/**
 * Get easing function by name
 * 
 * **Korean**: 이름으로 이징 함수 구하기
 * 
 * @param name - Easing function name (supports bezier presets)
 * @returns Easing function
 * 
 * @example
 * ```typescript
 * // Get natural motion easing for Korean martial arts
 * const easing = getEasingFunction("natural-motion");
 * const easedValue = easing(0.5); // Smooth physics-based interpolation
 * 
 * // Get explosive power for strike animations
 * const powerEasing = getEasingFunction("explosive-power");
 * ```
 * 
 * @korean 이징함수구하기
 */
export const getEasingFunction = (
  name: EasingName = "linear"
): EasingFunction => {
  switch (name) {
    case "ease-in":
      return easeIn;
    case "ease-out":
      return easeOut;
    case "ease-in-out":
      return easeInOut;
    case "natural-motion":
      return easeNaturalMotion;
    case "smooth-transition":
      return easeSmoothTransition;
    case "quick-start":
      return createBezierEasing(BEZIER_PRESETS.quickStart);
    case "explosive-power":
      return easeExplosivePower;
    case "controlled-slow":
      return createBezierEasing(BEZIER_PRESETS.controlledSlow);
    default:
      return easeLinear;
  }
};
 
/**
 * Find keyframes surrounding current time
 * 
 * Returns the two keyframes to interpolate between for current animation time.
 * 
 * @param animation - Skeletal animation
 * @param currentTime - Current time in animation (seconds)
 * @returns Tuple of [previousKeyframe, nextKeyframe, interpolationFactor]
 * 
 * @korean 주변키프레임찾기
 */
export const findSurroundingKeyframes = (
  animation: SkeletalAnimation,
  currentTime: number
): [AnimationKeyframe, AnimationKeyframe, number] => {
  const { keyframes } = animation;
 
  // Clamp time to animation duration
  const clampedTime = Math.max(
    0,
    Math.min(currentTime, animation.duration)
  );
 
  // Find keyframes
  let prevKeyframe = keyframes[0];
  let nextKeyframe = keyframes[keyframes.length - 1];
  let interpolationFactor = 0;
 
  for (let i = 0; i < keyframes.length - 1; i++) {
    const current = keyframes[i];
    const next = keyframes[i + 1];
 
    if (clampedTime >= current.time && clampedTime <= next.time) {
      prevKeyframe = current;
      nextKeyframe = next;
 
      // Calculate interpolation factor (0 to 1)
      const timeDelta = next.time - current.time;
      Eif (timeDelta > 0) {
        interpolationFactor = (clampedTime - current.time) / timeDelta;
      }
      break;
    }
  }
 
  return [prevKeyframe, nextKeyframe, interpolationFactor];
};
 
/**
 * Interpolate between two Euler rotations
 * 
 * Performs spherical linear interpolation (slerp) for smooth rotation.
 * 
 * @param from - Start rotation
 * @param to - End rotation
 * @param t - Interpolation factor (0-1)
 * @param easingFn - Easing function to apply
 * @returns Interpolated rotation
 * 
 * @korean 회전보간
 */
export const interpolateRotation = (
  from: THREE.Euler,
  to: THREE.Euler,
  t: number,
  easingFn: EasingFunction = easeLinear
): THREE.Euler => {
  const easedT = easingFn(t);
 
  // Convert Euler to Quaternion for proper slerp
  const fromQuat = new THREE.Quaternion().setFromEuler(from);
  const toQuat = new THREE.Quaternion().setFromEuler(to);
 
  // Slerp between quaternions
  const result = new THREE.Quaternion().slerpQuaternions(
    fromQuat,
    toQuat,
    easedT
  );
 
  // Convert back to Euler
  const resultEuler = new THREE.Euler().setFromQuaternion(result);
  return resultEuler;
};
 
/**
 * Interpolate between two Vector3 positions
 * 
 * Performs linear interpolation for smooth position changes.
 * 
 * @param from - Start position
 * @param to - End position
 * @param t - Interpolation factor (0-1)
 * @param easingFn - Easing function to apply
 * @returns Interpolated position
 * 
 * @korean 위치보간
 */
export const interpolatePosition = (
  from: THREE.Vector3,
  to: THREE.Vector3,
  t: number,
  easingFn: EasingFunction = easeLinear
): THREE.Vector3 => {
  const easedT = easingFn(t);
  return new THREE.Vector3().lerpVectors(from, to, easedT);
};
 
/**
 * Get interpolated keyframe at current time
 * 
 * Calculates bone transformations by interpolating between keyframes.
 * 
 * @param animation - Skeletal animation
 * @param currentTime - Current time in animation (seconds)
 * @returns Interpolated keyframe
 * 
 * @korean 보간된키프레임구하기
 */
export const getInterpolatedKeyframe = (
  animation: SkeletalAnimation,
  currentTime: number
): AnimationKeyframe => {
  const [prevKeyframe, nextKeyframe, t] =
    findSurroundingKeyframes(animation, currentTime);
 
  // Get easing function from next keyframe
  const easingFn = getEasingFunction(nextKeyframe.easing);
 
  // Interpolate bone rotations
  const boneRotations = new Map<string, THREE.Euler>();
  const allBoneNames = new Set([
    ...prevKeyframe.boneRotations.keys(),
    ...nextKeyframe.boneRotations.keys(),
  ]);
 
  for (const boneName of allBoneNames) {
    const prevRotation =
      prevKeyframe.boneRotations.get(boneName) ?? new THREE.Euler();
    const nextRotation =
      nextKeyframe.boneRotations.get(boneName) ?? new THREE.Euler();
 
    const interpolated = interpolateRotation(
      prevRotation,
      nextRotation,
      t,
      easingFn
    );
    boneRotations.set(boneName, interpolated);
  }
 
  // Interpolate bone positions
  const bonePositions = new Map<string, THREE.Vector3>();
  const allPositionBones = new Set([
    ...prevKeyframe.bonePositions.keys(),
    ...nextKeyframe.bonePositions.keys(),
  ]);
 
  for (const boneName of allPositionBones) {
    const prevPosition =
      prevKeyframe.bonePositions.get(boneName) ?? new THREE.Vector3();
    const nextPosition =
      nextKeyframe.bonePositions.get(boneName) ?? new THREE.Vector3();
 
    const interpolated = interpolatePosition(
      prevPosition,
      nextPosition,
      t,
      easingFn
    );
    bonePositions.set(boneName, interpolated);
  }
 
  return {
    time: currentTime,
    boneRotations,
    bonePositions,
    easing: nextKeyframe.easing,
  };
};
 
/**
 * Apply keyframe to skeletal rig
 * 
 * Updates all bone transformations based on keyframe data.
 * 
 * @param rig - Skeletal rig to update
 * @param keyframe - Keyframe to apply
 * 
 * @korean 키프레임적용
 */
export const applyKeyframeToRig = (
  rig: SkeletalRig,
  keyframe: AnimationKeyframe
): void => {
  // Apply bone rotations
  keyframe.boneRotations.forEach((rotation, boneName) => {
    const bone = rig.bones.get(boneName);
    Eif (bone) {
      bone.rotation.copy(rotation);
    }
  });
 
  // Apply bone positions (offset from rest pose)
  keyframe.bonePositions.forEach((position, boneName) => {
    const bone = rig.bones.get(boneName);
    Eif (bone) {
      // Add position offset to rest position
      bone.position.copy(bone.restPosition).add(position);
    }
  });
};
 
/**
 * Blend between two keyframes
 * 
 * Creates smooth transition between two animations for animation blending.
 * Useful for transitioning between stance change and attack, etc.
 * 
 * @param keyframe1 - First keyframe
 * @param keyframe2 - Second keyframe
 * @param blendFactor - Blend amount (0 = keyframe1, 1 = keyframe2)
 * @returns Blended keyframe
 * 
 * @korean 키프레임블렌드
 */
export const blendKeyframes = (
  keyframe1: AnimationKeyframe,
  keyframe2: AnimationKeyframe,
  blendFactor: number
): AnimationKeyframe => {
  const clampedBlend = Math.max(0, Math.min(1, blendFactor));
 
  // Blend rotations
  const boneRotations = new Map<string, THREE.Euler>();
  const allBones = new Set([
    ...keyframe1.boneRotations.keys(),
    ...keyframe2.boneRotations.keys(),
  ]);
 
  allBones.forEach((boneName) => {
    const rot1 = keyframe1.boneRotations.get(boneName) ?? new THREE.Euler();
    const rot2 = keyframe2.boneRotations.get(boneName) ?? new THREE.Euler();
    const blended = interpolateRotation(rot1, rot2, clampedBlend);
    boneRotations.set(boneName, blended);
  });
 
  // Blend positions
  const bonePositions = new Map<string, THREE.Vector3>();
  const allPositionBones = new Set([
    ...keyframe1.bonePositions.keys(),
    ...keyframe2.bonePositions.keys(),
  ]);
 
  allPositionBones.forEach((boneName) => {
    const pos1 = keyframe1.bonePositions.get(boneName) ?? new THREE.Vector3();
    const pos2 = keyframe2.bonePositions.get(boneName) ?? new THREE.Vector3();
    const blended = interpolatePosition(pos1, pos2, clampedBlend);
    bonePositions.set(boneName, blended);
  });
 
  return {
    time: 0,
    boneRotations,
    bonePositions,
    easing: "linear",
  };
};
 
/**
 * Update animation state
 * 
 * Advances animation time and returns current interpolated keyframe.
 * Handles looping animations automatically.
 * 
 * @param animation - Skeletal animation
 * @param currentTime - Current time in animation
 * @param deltaTime - Time since last update (seconds)
 * @param playbackSpeed - Speed multiplier (1.0 = normal)
 * @returns Updated time and current keyframe
 * 
 * @korean 애니메이션상태업데이트
 */
export const updateAnimation = (
  animation: SkeletalAnimation,
  currentTime: number,
  deltaTime: number,
  playbackSpeed = 1.0
): { time: number; keyframe: AnimationKeyframe; completed: boolean } => {
  // Advance time
  let newTime = currentTime + deltaTime * playbackSpeed;
  let completed = false;
 
  // Handle looping or completion
  if (newTime >= animation.duration) {
    Iif (animation.loop) {
      newTime = newTime % animation.duration;
    } else {
      newTime = animation.duration;
      completed = true;
    }
  }
 
  // Get interpolated keyframe
  const keyframe = getInterpolatedKeyframe(animation, newTime);
 
  return {
    time: newTime,
    keyframe,
    completed,
  };
};
 
/**
 * Cross-fade blend between two animations
 * 
 * **Korean**: 크로스페이드 블렌드
 * 
 * Smoothly blends between two overlapping animations to prevent popping.
 * Uses cubic bezier easing for natural transitions.
 * 
 * @param animation1 - First animation
 * @param time1 - Current time in first animation
 * @param animation2 - Second animation
 * @param time2 - Current time in second animation
 * @param blendFactor - Blend weight (0 = animation1, 1 = animation2)
 * @param easingName - Easing curve for blend transition
 * @returns Blended keyframe
 * 
 * @example
 * ```typescript
 * // Cross-fade from idle to attack over 100ms
 * const blended = crossFadeAnimations(
 *   idleAnim, idleTime,
 *   attackAnim, attackTime,
 *   0.5, // 50% blend
 *   "smooth-transition"
 * );
 * applyKeyframeToRig(rig, blended);
 * ```
 * 
 * @korean 크로스페이드블렌드
 */
export const crossFadeAnimations = (
  animation1: SkeletalAnimation,
  time1: number,
  animation2: SkeletalAnimation,
  time2: number,
  blendFactor: number,
  easingName: EasingName = "smooth-transition"
): AnimationKeyframe => {
  const keyframe1 = getInterpolatedKeyframe(animation1, time1);
  const keyframe2 = getInterpolatedKeyframe(animation2, time2);
  
  // Apply easing to blend factor
  const easingFn = getEasingFunction(easingName);
  const easedBlend = easingFn(Math.max(0, Math.min(1, blendFactor)));
  
  return blendKeyframes(keyframe1, keyframe2, easedBlend);
};
 
/**
 * Motion prediction state for latency reduction
 * 
 * **Korean**: 동작 예측 상태
 * 
 * Stores recent animation velocities for motion prediction.
 * 
 * @public
 * @category Animation
 * @korean 동작예측상태
 */
export interface MotionPredictionState {
  /** Recent position velocities per bone */
  readonly velocities: Map<string, THREE.Vector3>;
  /** Recent rotation velocities per bone */
  readonly angularVelocities: Map<string, THREE.Euler>;
  /** Last update timestamp */
  readonly lastUpdateTime: number;
}
 
/**
 * Create motion prediction state
 * 
 * **Korean**: 동작 예측 상태 생성
 * 
 * @returns Initial motion prediction state
 * @korean 동작예측상태생성
 */
export const createMotionPredictionState = (): MotionPredictionState => ({
  velocities: new Map(),
  angularVelocities: new Map(),
  lastUpdateTime: 0,
});
 
/**
 * Update motion prediction state with new keyframe
 * 
 * **Korean**: 동작 예측 상태 업데이트
 * 
 * Calculates velocities from keyframe differences for motion prediction.
 * 
 * @param state - Current prediction state
 * @param previousKeyframe - Previous animation keyframe
 * @param currentKeyframe - Current animation keyframe
 * @param deltaTime - Time elapsed between keyframes
 * @returns Updated prediction state
 * 
 * @korean 동작예측상태업데이트
 */
export const updateMotionPrediction = (
  state: MotionPredictionState,
  previousKeyframe: AnimationKeyframe,
  currentKeyframe: AnimationKeyframe,
  deltaTime: number
): MotionPredictionState => {
  if (deltaTime <= 0) return state;
  
  const newVelocities = new Map<string, THREE.Vector3>();
  const newAngularVelocities = new Map<string, THREE.Euler>();
  
  // Calculate position velocities
  currentKeyframe.bonePositions.forEach((currentPos, boneName) => {
    const prevPos = previousKeyframe.bonePositions.get(boneName);
    Eif (prevPos) {
      const velocity = new THREE.Vector3()
        .subVectors(currentPos, prevPos)
        .divideScalar(deltaTime);
      newVelocities.set(boneName, velocity);
    }
  });
  
  // Calculate angular velocities using quaternion-based rotation differences
  // This avoids gimbal lock and angle wrapping issues with Euler angle differences
  currentKeyframe.boneRotations.forEach((currentRot, boneName) => {
    const prevRot = previousKeyframe.boneRotations.get(boneName);
    Eif (prevRot) {
      // Convert Euler rotations to quaternions
      const qCurrent = new THREE.Quaternion().setFromEuler(currentRot);
      const qPrev = new THREE.Quaternion().setFromEuler(prevRot);
      
      // Calculate relative rotation: qDiff = qCurrent * qPrev^(-1)
      const qDiff = qCurrent.clone().multiply(qPrev.clone().invert());
      
      // Extract axis-angle representation for angular velocity
      const axis = new THREE.Vector3();
      const wClamped = THREE.MathUtils.clamp(qDiff.w, -1, 1);
      let angle = 2 * Math.acos(wClamped);
      const sinHalfAngle = Math.sqrt(1 - wClamped * wClamped);
      
      if (sinHalfAngle < 0.0001) {
        // If sinHalfAngle is too small, rotation is negligible - use zero velocity
        axis.set(0, 0, 0);
        angle = 0;
      } else {
        // Extract normalized axis from quaternion
        axis.set(
          qDiff.x / sinHalfAngle,
          qDiff.y / sinHalfAngle,
          qDiff.z / sinHalfAngle
        );
      }
      
      // Use shortest rotation path
      Iif (angle > Math.PI) {
        angle -= 2 * Math.PI;
      }
      
      // Angular velocity vector = axis * (angle / deltaTime)
      const angularVelocityVec = axis.multiplyScalar(angle / deltaTime);
      
      // Store as Euler for consistency with existing API
      const angularVel = new THREE.Euler(
        angularVelocityVec.x,
        angularVelocityVec.y,
        angularVelocityVec.z,
        currentRot.order
      );
      newAngularVelocities.set(boneName, angularVel);
    }
  });
  
  return {
    velocities: newVelocities,
    angularVelocities: newAngularVelocities,
    lastUpdateTime: performance.now(),
  };
};
 
/**
 * Predict future keyframe using motion prediction
 * 
 * **Korean**: 동작 예측으로 미래 키프레임 예측
 * 
 * Reduces perceived latency by predicting future bone positions/rotations
 * based on current velocities. Typical prediction: 16-33ms (1-2 frames at 60fps).
 * 
 * @param currentKeyframe - Current animation keyframe
 * @param predictionState - Motion prediction state
 * @param predictionTime - Time ahead to predict (seconds, typically 0.016-0.033)
 * @returns Predicted keyframe
 * 
 * @example
 * ```typescript
 * // Predict 1 frame ahead (16.67ms at 60fps) for <50ms total latency
 * const predicted = predictFutureKeyframe(
 *   currentKeyframe,
 *   motionState,
 *   0.01667
 * );
 * applyKeyframeToRig(rig, predicted);
 * ```
 * 
 * @korean 미래키프레임예측
 */
export const predictFutureKeyframe = (
  currentKeyframe: AnimationKeyframe,
  predictionState: MotionPredictionState,
  predictionTime: number
): AnimationKeyframe => {
  // Clamp prediction time to reasonable bounds (max 50ms)
  const clampedPrediction = Math.min(predictionTime, 0.05);
  
  // Predict bone positions
  const predictedPositions = new Map<string, THREE.Vector3>();
  currentKeyframe.bonePositions.forEach((currentPos, boneName) => {
    const velocity = predictionState.velocities.get(boneName);
    if (velocity) {
      // Apply damping to prevent overshoot (0.8 factor for natural motion)
      const predicted = currentPos.clone().add(
        velocity.clone().multiplyScalar(clampedPrediction * 0.8)
      );
      predictedPositions.set(boneName, predicted);
    } else {
      predictedPositions.set(boneName, currentPos.clone());
    }
  });
  
  // Predict bone rotations
  const predictedRotations = new Map<string, THREE.Euler>();
  currentKeyframe.boneRotations.forEach((currentRot, boneName) => {
    const angularVel = predictionState.angularVelocities.get(boneName);
    if (angularVel) {
      // Apply damping to prevent overshoot
      const predicted = new THREE.Euler(
        currentRot.x + angularVel.x * clampedPrediction * 0.8,
        currentRot.y + angularVel.y * clampedPrediction * 0.8,
        currentRot.z + angularVel.z * clampedPrediction * 0.8,
        currentRot.order
      );
      predictedRotations.set(boneName, predicted);
    } else E{
      predictedRotations.set(boneName, currentRot.clone());
    }
  });
  
  return {
    time: currentKeyframe.time + clampedPrediction,
    boneRotations: predictedRotations,
    bonePositions: predictedPositions,
    easing: currentKeyframe.easing,
  };
};