All files / systems/animation RecoveryPhaseEnhancer.ts

98.43% Statements 63/64
92.5% Branches 37/40
100% Functions 9/9
98.43% Lines 63/64

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                                                                                                                                              33x                                                                                                       3256x           3256x         1x         1x     3255x 3255x     3255x 3255x 3255x     3255x               3256x 17247x           17247x       3256x 3255x       156x 156x         156x         3255x               3256x 17247x             3256x 3255x 156x         3255x                                                                   2x                                                                                 3078x   3078x 1x 1x                   3077x 3077x   3077x     3077x 1x   3077x 1x         3077x 3077x 1x       3077x 3077x 43961x 1x       3077x 1x     3077x                                                       14x   14x 1x       13x 13x         14x 4x       9x 9x     9x     9x   2x 2x       7x 7x        
/**
 * Recovery Phase Enhancement for Black Trigram Animations
 * 
 * Implements realistic recovery animations following Korean martial arts principles:
 * - 균형회복 (Gyunhyeong Hoebog) - Balance restoration
 * - 자세복귀 (Jase Bokgwi) - Stance return
 * - 호흡조절 (Hoheup Jojoel) - Breath control during recovery
 * - 근육이완 (Geunryuk Ihwan) - Muscle relaxation after tension
 * 
 * @module systems/animation/RecoveryPhaseEnhancer
 * @category Animation System
 * @korean 복귀애니메이션강화
 */
 
import * as THREE from "three";
import type { SkeletalAnimation, AnimationKeyframe } from "../../types/skeletal";
 
/**
 * Recovery phase configuration options
 * 
 * **Korean**: 복귀 설정
 * 
 * @public
 * @category Animation
 * @korean 복귀설정
 */
export interface RecoveryPhaseConfig {
  /**
   * Duration of recovery phase in seconds (default: 0.2s = 200ms)
   * Recommended range: 0.15 - 0.25 seconds
   * **Korean**: 복귀 시간
   */
  readonly duration?: number;
 
  /**
   * Percentage of return in intermediate keyframe (default: 0.8 = 80%)
   * **Korean**: 중간 복귀 비율
   */
  readonly intermediateReturnPercent?: number;
 
  /**
   * Initial muscle tension level at peak technique (default: 1.0 = 100%)
   * **Korean**: 최대 근육 긴장도
   */
  readonly peakMuscleTension?: number;
 
  /**
   * Muscle tension at intermediate recovery (default: 0.4 = 40%)
   * **Korean**: 중간 근육 긴장도
   */
  readonly intermediateMuscleTension?: number;
 
  /**
   * Final muscle tension in relaxed state (default: 0.1 = 10%)
   * **Korean**: 최종 근육 긴장도
   */
  readonly finalMuscleTension?: number;
 
  /**
   * Whether to use ease-out interpolation (default: true)
   * **Korean**: 부드러운 감속 사용
   */
  readonly useEaseOut?: boolean;
}
 
/**
 * Default recovery phase configuration
 * Based on Korean martial arts recovery principles
 * 
 * **Korean**: 기본 복귀 설정
 */
const DEFAULT_RECOVERY_CONFIG: Required<RecoveryPhaseConfig> = {
  duration: 0.22, // 220ms - optimal for realistic recovery
  intermediateReturnPercent: 0.8, // 80% back to neutral
  peakMuscleTension: 1.0, // 100% tension at technique peak
  intermediateMuscleTension: 0.4, // 40% tension during recovery
  finalMuscleTension: 0.1, // 10% relaxed state
  useEaseOut: true,
};
 
/**
 * Add realistic recovery phase to technique animation
 * 
 * **Korean**: 기술 애니메이션에 복귀 단계 추가
 * 
 * Enhances technique animations with proper recovery phases following
 * Korean martial arts principles of 복귀 (Bokgwi - recovery/return).
 * 
 * The recovery phase consists of two keyframes:
 * 1. **Intermediate recovery** (60% of recovery duration):
 *    - Returns 80% toward neutral position
 *    - Reduces muscle tension to 40%
 *    - Uses ease-out for gradual deceleration
 * 
 * 2. **Final recovery** (100% of recovery duration):
 *    - Fully returns to neutral stance
 *    - Relaxes muscle tension to 10%
 *    - Completes breath cycle
 * 
 * @param animation - Base technique animation
 * @param config - Recovery phase configuration options
 * @returns Enhanced animation with recovery phase
 * 
 * @example
 * ```typescript
 * // Add default 220ms recovery to front kick
 * const kickWithRecovery = addRecoveryPhase(FRONT_KICK_ANIMATION);
 * 
 * // Add custom 180ms recovery with faster muscle release
 * const quickRecovery = addRecoveryPhase(JAB_ANIMATION, {
 *   duration: 0.18,
 *   intermediateMuscleTension: 0.3,
 *   finalMuscleTension: 0.05,
 * });
 * ```
 * 
 * @korean 복귀단계추가
 */
export function addRecoveryPhase(
  animation: SkeletalAnimation,
  config: RecoveryPhaseConfig = {}
): SkeletalAnimation {
  // Merge with defaults
  const finalConfig: Required<RecoveryPhaseConfig> = {
    ...DEFAULT_RECOVERY_CONFIG,
    ...config,
  };
 
  // Validate animation has at least 2 keyframes
  if (animation.keyframes.length < 2) {
    // In production, this would use proper logging system
    // For now, using console.warn is acceptable for development
    // Suppress console output during tests to avoid cluttering test output
    // Note: In test environments, proper assertions should validate this condition
    Iif (process.env.NODE_ENV !== 'test') {
      console.warn(
        `Animation "${animation.name}" has fewer than 2 keyframes. Recovery phase not added.`
      );
    }
    return animation;
  }
 
  const lastKeyframe = animation.keyframes[animation.keyframes.length - 1];
  const peakKeyframe = animation.keyframes[animation.keyframes.length - 2];
 
  // Calculate recovery timing
  const recoveryStartTime = lastKeyframe.time;
  const intermediateTime = recoveryStartTime + finalConfig.duration * 0.6;
  const finalTime = recoveryStartTime + finalConfig.duration;
 
  // Create intermediate recovery keyframe (80% back to neutral)
  const intermediateFrame: AnimationKeyframe = {
    time: intermediateTime,
    easing: finalConfig.useEaseOut ? "ease-out" : "linear",
    boneRotations: new Map(),
    bonePositions: new Map(),
  };
 
  // Interpolate bone rotations 80% toward neutral
  peakKeyframe.boneRotations.forEach((rotation, bone) => {
    const intermediate = new THREE.Euler(
      rotation.x * (1 - finalConfig.intermediateReturnPercent),
      rotation.y * (1 - finalConfig.intermediateReturnPercent),
      rotation.z * (1 - finalConfig.intermediateReturnPercent),
      rotation.order
    );
    intermediateFrame.boneRotations.set(bone, intermediate);
  });
 
  // Interpolate bone positions 80% toward rest
  if (peakKeyframe.bonePositions) {
    peakKeyframe.bonePositions.forEach((position, bone) => {
      // Manual interpolation instead of Vector3.lerp() because bonePositions map
      // may contain objects that aren't true THREE.Vector3 instances with prototype methods.
      // This approach ensures compatibility with any object having x, y, z properties.
      const returnPercent = finalConfig.intermediateReturnPercent;
      const intermediate = new THREE.Vector3(
        position.x * (1 - returnPercent),
        position.y * (1 - returnPercent),
        position.z * (1 - returnPercent)
      );
      intermediateFrame.bonePositions.set(bone, intermediate);
    });
  }
 
  // Create final recovery frame (100% neutral)
  const finalFrame: AnimationKeyframe = {
    time: finalTime,
    easing: finalConfig.useEaseOut ? "ease-out" : "linear",
    boneRotations: new Map(),
    bonePositions: new Map(),
  };
 
  // All bones return to neutral (0 rotation)
  peakKeyframe.boneRotations.forEach((rotation, bone) => {
    finalFrame.boneRotations.set(
      bone,
      new THREE.Euler(0, 0, 0, rotation.order)
    );
  });
 
  // All positions return to rest
  if (peakKeyframe.bonePositions) {
    peakKeyframe.bonePositions.forEach((_, bone) => {
      finalFrame.bonePositions.set(bone, new THREE.Vector3(0, 0, 0));
    });
  }
 
  // Build enhanced animation
  return {
    ...animation,
    duration: finalTime,
    keyframes: [...animation.keyframes, intermediateFrame, finalFrame],
  };
}
 
/**
 * Create technique animation with recovery phase
 * 
 * **Korean**: 복귀 단계를 포함한 기술 애니메이션 생성
 * 
 * Convenience function that wraps animation creation with automatic recovery phase.
 * Use this when creating new technique animations from scratch.
 * 
 * @param baseAnimation - Base animation without recovery
 * @param config - Recovery configuration
 * @returns Complete animation with recovery phase
 * 
 * @example
 * ```typescript
 * // Create front kick with recovery
 * const frontKick = createTechniqueWithRecovery(
 *   baseFrontKickAnimation,
 *   { duration: 0.22 }
 * );
 * ```
 * 
 * @korean 복귀단계기술생성
 */
export function createTechniqueWithRecovery(
  baseAnimation: SkeletalAnimation,
  config: RecoveryPhaseConfig = {}
): SkeletalAnimation {
  return addRecoveryPhase(baseAnimation, config);
}
 
/**
 * Validate recovery phase quality
 * 
 * **Korean**: 복귀 단계 품질 검증
 * 
 * Checks if an animation has proper recovery phase characteristics:
 * - Has at least 2 recovery keyframes
 * - Recovery duration between 150-250ms
 * - Uses ease-out interpolation
 * - Returns to neutral position
 * 
 * @param animation - Animation to validate
 * @returns Validation result with details
 * 
 * @korean 복귀품질검증
 */
export interface RecoveryValidationResult {
  /** Whether animation has valid recovery phase */
  readonly isValid: boolean;
  /** Validation issues found */
  readonly issues: string[];
  /** Recovery duration in milliseconds */
  readonly recoveryDuration: number;
  /** Number of recovery keyframes */
  readonly recoveryKeyframes: number;
}
 
/**
 * Validate recovery phase in animation
 * 
 * @param animation - Animation to validate
 * @returns Validation result
 * 
 * @korean 복귀검증
 */
export function validateRecoveryPhase(
  animation: SkeletalAnimation
): RecoveryValidationResult {
  const issues: string[] = [];
  
  if (animation.keyframes.length < 3) {
    issues.push("Animation has fewer than 3 keyframes (needs at least 3 for recovery)");
    return {
      isValid: false,
      issues,
      recoveryDuration: 0,
      recoveryKeyframes: 0,
    };
  }
 
  // Recovery phase is from the third-to-last keyframe (peak) to last keyframe (final recovery)
  // This is because addRecoveryPhase adds TWO keyframes: intermediate and final
  const lastKeyframe = animation.keyframes[animation.keyframes.length - 1];
  const thirdLastKeyframe = animation.keyframes[animation.keyframes.length - 3];
  
  const recoveryDuration = (lastKeyframe.time - thirdLastKeyframe.time) * 1000; // ms
  
  // Validate duration
  if (recoveryDuration < 150) {
    issues.push(`Recovery duration too short: ${recoveryDuration.toFixed(0)}ms (minimum: 150ms)`);
  }
  if (recoveryDuration > 250) {
    issues.push(`Recovery duration too long: ${recoveryDuration.toFixed(0)}ms (maximum: 250ms)`);
  }
 
  // Validate easing - both ease-out and ease-in are acceptable for recovery
  // ease-out is preferred but ease-in can also work for final deceleration
  const acceptableEasings = ['ease-out', 'ease-in'];
  if (!acceptableEasings.includes(lastKeyframe.easing || '')) {
    issues.push(`Last keyframe should use ease-out or ease-in interpolation, found: ${lastKeyframe.easing}`);
  }
 
  // Validate return to neutral
  let hasNonZeroRotation = false;
  lastKeyframe.boneRotations.forEach((rotation) => {
    if (Math.abs(rotation.x) > 0.01 || Math.abs(rotation.y) > 0.01 || Math.abs(rotation.z) > 0.01) {
      hasNonZeroRotation = true;
    }
  });
  
  if (hasNonZeroRotation) {
    issues.push("Final keyframe should return to neutral position (0, 0, 0)");
  }
 
  return {
    isValid: issues.length === 0,
    issues,
    recoveryDuration,
    recoveryKeyframes: 2,
  };
}
 
/**
 * Calculate muscle tension at specific time in animation
 * 
 * **Korean**: 애니메이션 시간별 근육 긴장도 계산
 * 
 * Interpolates muscle tension based on animation progress and recovery phase.
 * Tension peaks during technique execution and gradually releases during recovery.
 * 
 * @param animation - Animation with recovery phase
 * @param currentTime - Current time in animation (seconds)
 * @param config - Recovery configuration used
 * @returns Muscle tension value (0.0 to 1.0)
 * 
 * @korean 근육긴장도계산
 */
export function calculateMuscleTension(
  animation: SkeletalAnimation,
  currentTime: number,
  config: RecoveryPhaseConfig = {}
): number {
  const finalConfig = { ...DEFAULT_RECOVERY_CONFIG, ...config };
  
  if (animation.keyframes.length < 2) {
    return finalConfig.finalMuscleTension;
  }
 
  // Recovery phase starts at the third-to-last keyframe (after peak)
  const lastKeyframe = animation.keyframes[animation.keyframes.length - 1];
  const recoveryStartTime = animation.keyframes.length >= 3
    ? animation.keyframes[animation.keyframes.length - 3].time
    : animation.keyframes[animation.keyframes.length - 2].time;
  
  // Before recovery: peak tension
  if (currentTime < recoveryStartTime) {
    return finalConfig.peakMuscleTension;
  }
  
  // During recovery: interpolate from peak to relaxed
  const recoveryProgress = (currentTime - recoveryStartTime) / (lastKeyframe.time - recoveryStartTime);
  const clampedProgress = Math.max(0, Math.min(1, recoveryProgress));
  
  // Use ease-out curve for natural muscle release
  const easedProgress = 1 - Math.pow(1 - clampedProgress, 2);
  
  // Interpolate tension
  if (easedProgress < 0.6) {
    // First 60%: peak -> intermediate
    const t = easedProgress / 0.6;
    return finalConfig.peakMuscleTension + 
      (finalConfig.intermediateMuscleTension - finalConfig.peakMuscleTension) * t;
  } else {
    // Last 40%: intermediate -> final
    const t = (easedProgress - 0.6) / 0.4;
    return finalConfig.intermediateMuscleTension + 
      (finalConfig.finalMuscleTension - finalConfig.intermediateMuscleTension) * t;
  }
}