All files / systems/animation AnimationOptimizations.ts

98.08% Statements 154/157
88.46% Branches 69/78
100% Functions 27/27
98.05% Lines 151/154

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                                                                                                                                10x       10x                                 411x 411x 411x 71x       340x     340x 340x                                 345x   345x   70x 10x     70x         70x       345x     345x 345x 1286x     345x 345x 1x 1x       345x                       10x 10x   10x 500x 10x 10x       10x 10x               44x                     9x 9x 55x     9x                         10x                                     166x   166x 2561x 2561x 1901x       660x 660x 660x       660x 2561x   3x                                           3x 3x   3x   122x 122x 122x                                               411x 411x 187x       224x 224x 1x       223x 223x   223x 301x 217x 217x 217x         223x 3x 3x       220x 220x     411x   411x 1100x 1100x   1066x 1066x 1066x   1066x 1066x 1066x     1066x 1066x 1066x     1066x 1066x 1066x 1066x   34x         411x 411x           1x 1x 1x   1x 1x 1x 1x         220x               220x   220x                                   1x 2x 2x       2x 2x     2x 1x                                             63x   63x 125x 125x 1x 1x       124x 124x 124x   124x 120x         63x 1x 1x 1x           1x 1x 1x         63x                                                         10x 10x 10x 10x             316x 316x 30x               3x             1x             5x 5x   5x   5x 2x                     183x 3x 3x   3x                           23x 23x 23x                 10x  
/**
 * Optimized Animation System with Caching and Batch Processing
 *
 * High-performance animation pipeline optimizations:
 * - Keyframe caching to avoid redundant interpolations
 * - Batch bone transformation updates
 * - Dirty flag optimization
 * - Precomputed interpolation curves
 *
 * Target: Reduce animation overhead from ~8ms to <5ms per frame
 *
 * @module systems/animation/AnimationOptimizations
 * @category Animation System
 * @korean 애니메이션최적화
 */
 
import * as THREE from "three";
import type {
  AnimationKeyframe,
  SkeletalAnimation,
  SkeletalRig,
} from "../../types/skeletal";
import { ThreeObjectPools } from "../../utils/threeObjectPool";
 
/**
 * Cached keyframe with interpolated values
 * Reduces redundant interpolation calculations
 *
 * @korean 캐시된키프레임
 */
interface CachedKeyframe {
  /** Original keyframe */
  readonly keyframe: AnimationKeyframe;
  /** Cache timestamp (for invalidation) */
  readonly timestamp: number;
  /** Interpolated bone rotations (Map to avoid allocations) */
  readonly rotations: Map<string, THREE.Euler>;
  /** Interpolated bone positions (if animated) */
  readonly positions: Map<string, THREE.Vector3>;
}
 
/**
 * Animation cache entry
 *
 * @korean 애니메이션캐시항목
 */
interface AnimationCache {
  /** Animation being cached */
  readonly animation: SkeletalAnimation;
  /** Cached keyframes by time */
  readonly keyframes: Map<number, CachedKeyframe>;
  /** Last access time (for LRU eviction) */
  lastAccessTime: number;
}
 
/**
 * Animation Cache Manager
 *
 * Caches interpolated keyframes to avoid redundant calculations.
 * Uses LRU eviction when cache is full.
 *
 * @korean 애니메이션캐시관리자
 */
class AnimationCacheManager {
  private cache = new Map<string, AnimationCache>();
  private readonly maxCacheSize: number;
 
  constructor(maxCacheSize = 50) {
    this.maxCacheSize = maxCacheSize;
  }
 
  /**
   * Get cached keyframe or create new entry
   *
   * @param animationId - Animation identifier
   * @param animation - Animation data (reserved for future cache invalidation logic)
   * @param time - Current time
   * @returns Cached keyframe or null if not cached
   */
  get(
    animationId: string,
    animation: SkeletalAnimation,
    time: number
  ): CachedKeyframe | null {
    // Mark parameter as used for future extensibility (e.g., cache invalidation)
    void animation;
    const entry = this.cache.get(animationId);
    if (!entry) {
      return null;
    }
 
    // Update access time for LRU
    entry.lastAccessTime = performance.now();
 
    // Round time to nearest 0.01s for cache hits (100 possible values per second)
    const roundedTime = Math.round(time * 100) / 100;
    return entry.keyframes.get(roundedTime) ?? null;
  }
 
  /**
   * Cache an interpolated keyframe
   *
   * @param animationId - Animation identifier
   * @param animation - Animation data
   * @param time - Current time
   * @param keyframe - Interpolated keyframe to cache
   */
  set(
    animationId: string,
    animation: SkeletalAnimation,
    time: number,
    keyframe: AnimationKeyframe
  ): void {
    let entry = this.cache.get(animationId);
 
    if (!entry) {
      // Evict oldest entry if cache is full
      if (this.cache.size >= this.maxCacheSize) {
        this.evictLRU();
      }
 
      entry = {
        animation,
        keyframes: new Map(),
        lastAccessTime: performance.now(),
      };
      this.cache.set(animationId, entry);
    }
 
    // Round time for consistent cache keys
    const roundedTime = Math.round(time * 100) / 100;
 
    // Clone keyframe data for caching (avoid reference issues)
    const cachedRotations = new Map<string, THREE.Euler>();
    keyframe.boneRotations.forEach((rotation, boneName) => {
      cachedRotations.set(boneName, rotation.clone());
    });
 
    const cachedPositions = new Map<string, THREE.Vector3>();
    if (keyframe.bonePositions && keyframe.bonePositions.size > 0) {
      keyframe.bonePositions.forEach((position, boneName) => {
        cachedPositions.set(boneName, position.clone());
      });
    }
 
    entry.keyframes.set(roundedTime, {
      keyframe,
      timestamp: performance.now(),
      rotations: cachedRotations,
      positions: cachedPositions,
    });
  }
 
  /**
   * Evict least recently used cache entry
   */
  private evictLRU(): void {
    let oldestKey: string | null = null;
    let oldestTime = Infinity;
 
    this.cache.forEach((entry, key) => {
      if (entry.lastAccessTime < oldestTime) {
        oldestTime = entry.lastAccessTime;
        oldestKey = key;
      }
    });
 
    Eif (oldestKey) {
      this.cache.delete(oldestKey);
    }
  }
 
  /**
   * Clear all cached keyframes
   */
  clear(): void {
    this.cache.clear();
  }
 
  /**
   * Get cache statistics
   */
  getStats(): {
    totalAnimations: number;
    totalKeyframes: number;
    cacheSize: number;
  } {
    let totalKeyframes = 0;
    this.cache.forEach((entry) => {
      totalKeyframes += entry.keyframes.size;
    });
 
    return {
      totalAnimations: this.cache.size,
      totalKeyframes,
      cacheSize: this.maxCacheSize,
    };
  }
}
 
/**
 * Global animation cache instance
 *
 * @korean 전역애니메이션캐시
 */
export const animationCache = new AnimationCacheManager(50);
 
/**
 * Batch update multiple bones with dirty flag optimization
 *
 * Only updates bones that have changed rotations/positions.
 * Uses object pooling to avoid allocations.
 *
 * @param rig - Skeletal rig to update
 * @param keyframe - Keyframe with bone transforms
 * @param dirtyBones - Set of bone names that changed (optional, updates all if not provided)
 *
 * @korean 배치뼈업데이트
 */
export function batchUpdateBones(
  rig: SkeletalRig,
  keyframe: AnimationKeyframe,
  dirtyBones?: Set<string>
): void {
  const bonesToUpdate = dirtyBones ?? new Set(keyframe.boneRotations.keys());
 
  bonesToUpdate.forEach((boneName) => {
    const bone = rig.bones.get(boneName);
    if (!bone) {
      return;
    }
 
    // Update rotation
    const rotation = keyframe.boneRotations.get(boneName);
    Eif (rotation) {
      bone.rotation.copy(rotation);
    }
 
    // Update position (if animated) - apply as offset from rest position
    const position = keyframe.bonePositions?.get(boneName);
    if (position) {
      // Position values in animations are offsets from rest position, not absolute values
      bone.position.copy(bone.restPosition).add(position);
    }
  });
}
 
/**
 * Precompute and cache animation interpolation
 *
 * Generates cached keyframes at regular intervals for smooth playback.
 * Call this during asset loading or idle time.
 *
 * @param animationId - Animation identifier
 * @param animation - Animation to precompute
 * @param sampleRate - Samples per second (default: 60fps = 60 samples/s)
 *
 * @korean 애니메이션사전계산
 */
export function precomputeAnimation(
  animationId: string,
  animation: SkeletalAnimation,
  sampleRate = 60
): void {
  const duration = animation.duration;
  const step = 1 / sampleRate;
 
  for (let t = 0; t <= duration; t += step) {
    // This will populate the cache
    const keyframe = interpolateKeyframeCached(animationId, animation, t);
    Eif (keyframe) {
      animationCache.set(animationId, animation, t, keyframe);
    }
  }
}
 
/**
 * Interpolate keyframe with caching
 *
 * Checks cache before performing interpolation.
 * Automatically caches result for future use.
 *
 * @param animationId - Animation identifier
 * @param animation - Animation data
 * @param time - Current time
 * @returns Interpolated keyframe
 *
 * @korean 캐시된키프레임보간
 */
export function interpolateKeyframeCached(
  animationId: string,
  animation: SkeletalAnimation,
  time: number
): AnimationKeyframe | null {
  // Check cache first
  const cached = animationCache.get(animationId, animation, time);
  if (cached) {
    return cached.keyframe;
  }
 
  // Find surrounding keyframes
  const keyframes = animation.keyframes;
  if (keyframes.length === 0) {
    return null;
  }
 
  // Find previous and next keyframes
  let prevKeyframe = keyframes[0];
  let nextKeyframe = keyframes[keyframes.length - 1];
 
  for (let i = 0; i < keyframes.length - 1; i++) {
    if (time >= keyframes[i].time && time <= keyframes[i + 1].time) {
      prevKeyframe = keyframes[i];
      nextKeyframe = keyframes[i + 1];
      break;
    }
  }
 
  // If at exact keyframe, return it directly
  if (Math.abs(time - prevKeyframe.time) < 0.001) {
    animationCache.set(animationId, animation, time, prevKeyframe);
    return prevKeyframe;
  }
 
  // Calculate interpolation factor
  const timeDiff = nextKeyframe.time - prevKeyframe.time;
  const t = timeDiff > 0 ? (time - prevKeyframe.time) / timeDiff : 0;
 
  // Interpolate rotations using object pool
  const interpolatedRotations = new Map<string, THREE.Euler>();
 
  prevKeyframe.boneRotations.forEach((prevRot, boneName) => {
    const nextRot = nextKeyframe.boneRotations.get(boneName);
    if (nextRot) {
      // Use pooled quaternions for slerp interpolation
      const prevQuat = ThreeObjectPools.quaternion.acquire();
      const nextQuat = ThreeObjectPools.quaternion.acquire();
      const resultQuat = ThreeObjectPools.quaternion.acquire();
 
      prevQuat.setFromEuler(prevRot);
      nextQuat.setFromEuler(nextRot);
      resultQuat.slerpQuaternions(prevQuat, nextQuat, t);
 
      // Use pooled Euler, then clone for storage to avoid pooled object reuse issues
      const tempEuler = ThreeObjectPools.euler.acquire();
      tempEuler.setFromQuaternion(resultQuat);
      interpolatedRotations.set(boneName, tempEuler.clone());
 
      // Release pooled objects
      ThreeObjectPools.quaternion.release(prevQuat);
      ThreeObjectPools.quaternion.release(nextQuat);
      ThreeObjectPools.quaternion.release(resultQuat);
      ThreeObjectPools.euler.release(tempEuler);
    } else {
      interpolatedRotations.set(boneName, prevRot.clone());
    }
  });
 
  // Interpolate positions if present
  const interpolatedPositions = new Map<string, THREE.Vector3>();
  if (
    prevKeyframe.bonePositions &&
    prevKeyframe.bonePositions.size > 0 &&
    nextKeyframe.bonePositions &&
    nextKeyframe.bonePositions.size > 0
  ) {
    prevKeyframe.bonePositions.forEach((prevPos, boneName) => {
      const nextPos = nextKeyframe.bonePositions?.get(boneName);
      Eif (nextPos) {
        // Use pooled Vector3, then clone for storage to avoid pooled object reuse issues
        const tempVec = ThreeObjectPools.vector3.acquire();
        tempVec.lerpVectors(prevPos, nextPos, t);
        interpolatedPositions.set(boneName, tempVec.clone());
        ThreeObjectPools.vector3.release(tempVec);
      }
    });
  }
 
  const interpolatedKeyframe: AnimationKeyframe = {
    time,
    boneRotations: interpolatedRotations,
    bonePositions: interpolatedPositions,
    easing: prevKeyframe.easing,
  };
 
  // Cache for future use
  animationCache.set(animationId, animation, time, interpolatedKeyframe);
 
  return interpolatedKeyframe;
}
 
/**
 * Batch transform multiple bones in a single operation
 *
 * Applies transformations to all bones efficiently using temporary objects.
 * Reduces per-bone overhead by batching operations.
 *
 * @param rig - Skeletal rig
 * @param transforms - Map of bone names to transforms
 *
 * @korean 배치변환
 */
export function batchTransformBones(
  rig: SkeletalRig,
  transforms: Map<string, { rotation?: THREE.Euler; position?: THREE.Vector3 }>
): void {
  transforms.forEach((transform, boneName) => {
    const bone = rig.bones.get(boneName);
    Iif (!bone) {
      return;
    }
 
    Eif (transform.rotation) {
      bone.rotation.copy(transform.rotation);
    }
 
    if (transform.position) {
      bone.position.copy(transform.position);
    }
  });
}
 
/**
 * Calculate dirty bones between two keyframes
 *
 * Identifies which bones have changed between keyframes for dirty flag optimization.
 * Only changed bones need to be updated.
 *
 * @param prevKeyframe - Previous keyframe
 * @param nextKeyframe - Next keyframe
 * @param threshold - Minimum rotation difference in radians (default: 0.01)
 * @returns Set of bone names that changed
 *
 * @korean 변경된뼈계산
 */
export function calculateDirtyBones(
  prevKeyframe: AnimationKeyframe,
  nextKeyframe: AnimationKeyframe,
  threshold = 0.01
): Set<string> {
  const dirtyBones = new Set<string>();
 
  nextKeyframe.boneRotations.forEach((nextRot, boneName) => {
    const prevRot = prevKeyframe.boneRotations.get(boneName);
    if (!prevRot) {
      dirtyBones.add(boneName);
      return;
    }
 
    // Check if rotation changed significantly
    const dx = Math.abs(nextRot.x - prevRot.x);
    const dy = Math.abs(nextRot.y - prevRot.y);
    const dz = Math.abs(nextRot.z - prevRot.z);
 
    if (dx > threshold || dy > threshold || dz > threshold) {
      dirtyBones.add(boneName);
    }
  });
 
  // Check positions if animated
  if (nextKeyframe.bonePositions && nextKeyframe.bonePositions.size > 0) {
    nextKeyframe.bonePositions.forEach((nextPos, boneName) => {
      const prevPos = prevKeyframe.bonePositions?.get(boneName);
      Iif (!prevPos) {
        dirtyBones.add(boneName);
        return;
      }
 
      // Check if position changed
      const distance = nextPos.distanceTo(prevPos);
      Eif (distance > threshold) {
        dirtyBones.add(boneName);
      }
    });
  }
 
  return dirtyBones;
}
 
/**
 * Animation performance metrics
 *
 * @korean 애니메이션성능지표
 */
export interface AnimationPerformanceMetrics {
  /** Average frame time (ms) */
  avgFrameTime: number;
  /** Maximum frame time (ms) */
  maxFrameTime: number;
  /** Minimum frame time (ms) */
  minFrameTime: number;
  /** Number of frames measured */
  frameCount: number;
  /** Cache hit rate (0-1) */
  cacheHitRate: number;
  /** Total cache entries */
  cacheEntries: number;
}
 
/**
 * Performance monitor for animation system
 *
 * @korean 성능모니터
 */
class AnimationPerformanceMonitor {
  private frameTimes: number[] = [];
  private cacheHits = 0;
  private cacheMisses = 0;
  private readonly maxSamples = 120; // 2 seconds at 60fps
 
  /**
   * Record frame time
   * @param time - Frame time in milliseconds
   */
  recordFrame(time: number): void {
    this.frameTimes.push(time);
    if (this.frameTimes.length > this.maxSamples) {
      this.frameTimes.shift();
    }
  }
 
  /**
   * Record cache hit
   */
  recordCacheHit(): void {
    this.cacheHits++;
  }
 
  /**
   * Record cache miss
   */
  recordCacheMiss(): void {
    this.cacheMisses++;
  }
 
  /**
   * Get current metrics
   */
  getMetrics(): AnimationPerformanceMetrics {
    const totalHits = this.cacheHits + this.cacheMisses;
    const cacheHitRate = totalHits > 0 ? this.cacheHits / totalHits : 0;
 
    const stats = animationCache.getStats();
 
    if (this.frameTimes.length === 0) {
      return {
        avgFrameTime: 0,
        maxFrameTime: 0,
        minFrameTime: 0,
        frameCount: 0,
        cacheHitRate,
        cacheEntries: stats.totalKeyframes,
      };
    }
 
    const avgFrameTime =
      this.frameTimes.reduce((a, b) => a + b, 0) / this.frameTimes.length;
    const maxFrameTime = Math.max(...this.frameTimes);
    const minFrameTime = Math.min(...this.frameTimes);
 
    return {
      avgFrameTime,
      maxFrameTime,
      minFrameTime,
      frameCount: this.frameTimes.length,
      cacheHitRate,
      cacheEntries: stats.totalKeyframes,
    };
  }
 
  /**
   * Reset metrics
   */
  reset(): void {
    this.frameTimes = [];
    this.cacheHits = 0;
    this.cacheMisses = 0;
  }
}
 
/**
 * Global performance monitor instance
 *
 * @korean 전역성능모니터
 */
export const performanceMonitor = new AnimationPerformanceMonitor();