All files / systems/physics AttackMovementPhysics.ts

100% Statements 50/50
100% Branches 98/98
100% Functions 8/8
100% Lines 50/50

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                                                                                                                                                                                                                                                                                                          345x     345x 345x     345x     345x 345x   345x                                                     345x         11x     334x       14x     320x         3x       317x         6x       311x       6x       305x         8x     297x       68x     229x         4x       225x                             25x       200x                     18x       182x       4x       178x           8x       170x                                         31x           139x                                                 345x                   345x                                                                                                           13x   8x       8x     8x       8x     5x 5x       5x     5x       5x                                 5x                                     5x                                 1x                                 1x                
/**
 * Attack Movement Physics System for realistic forward momentum during attacks.
 *
 * **Korean**: 공격 이동 물리 시스템 (Attack Movement Physics System)
 *
 * Implements realistic forward movement physics when fighters execute attacks.
 * Kicks naturally extend the body forward, punches lunge with body weight,
 * and spinning techniques carry rotational momentum.
 *
 * ## Attack Movement Mechanics
 *
 * Forward movement distance is determined by:
 * - Animation type (kicks > punches > elbows/knees)
 * - Stance modifiers (8 trigram stances affect aggression)
 * - Animation phase timing (extension → peak → recovery)
 *
 * ## Movement Integration
 *
 * - Extension phase (frames 3-6): Forward lunge with ease-out
 * - Peak phase (frame 6): Maximum extension reached
 * - Recovery phase (frames 7-10): Return to original stance
 * - Arena bounds: Automatically clamp movement to valid zone
 *
 * ## Performance
 *
 * Optimized for 60fps with efficient vector calculations and
 * smooth easing curves for realistic attack momentum feel.
 *
 * @module systems/physics/AttackMovementPhysics
 * @category Physics System
 * @korean 공격이동물리
 */
 
import * as THREE from "three";
import { TrigramStance } from "@/types/common";
import { AnimationType } from "@/systems/animation";
 
/**
 * Configuration for attack movement calculation.
 *
 * **Korean**: 공격 이동 설정 (Attack Movement Configuration)
 *
 * @public
 * @korean 공격이동설정
 */
export interface AttackMovementConfig {
  /** Animation type being executed */
  readonly animationType: AnimationType;
  /** Current trigram stance */
  readonly currentStance: TrigramStance;
  /** Normalized attack direction vector (attacker → target) */
  readonly direction: THREE.Vector3;
  /** Total attack animation duration in seconds */
  readonly animationDuration: number;
}
 
/**
 * Result of attack movement calculation.
 *
 * **Korean**: 공격 이동 결과 (Attack Movement Result)
 *
 * Contains displacement vector and timing for attack lunge.
 *
 * @public
 * @korean 공격이동결과
 */
export interface AttackMovementResult {
  /** Total forward displacement vector in world space */
  readonly displacement: THREE.Vector3;
  /** Duration of forward lunge phase in seconds */
  readonly lungeDuration: number;
  /** Duration of recovery return phase in seconds */
  readonly recoveryDuration: number;
  /** Total movement cycle duration in seconds */
  readonly totalDuration: number;
}
 
/**
 * Attack Movement Physics Engine.
 *
 * **Korean**: 공격 이동 물리 엔진
 *
 * Calculates realistic forward movement during attack animations
 * based on technique type, stance modifiers, and animation timing.
 * Provides smooth lunge and recovery phases for authentic martial arts feel.
 *
 * @example
 * ```typescript
 * const physics = new AttackMovementPhysics();
 *
 * // Calculate movement for roundhouse kick
 * const config: AttackMovementConfig = {
 *   animationType: AnimationType.ROUNDHOUSE_KICK,
 *   currentStance: TrigramStance.LI, // Fire stance (aggressive)
 *   direction: new THREE.Vector3(1, 0, 0).normalize(),
 *   animationDuration: 0.48, // 480ms kick animation
 * };
 *
 * const result = physics.calculateAttackMovement(config);
 * // Result: 1.0m base * 1.3 (Fire bonus) = ~1.3m forward lunge
 * // lungeDuration: 0.24s (50% of animation)
 * // recoveryDuration: 0.24s (50% of animation)
 * ```
 *
 * @public
 * @korean 공격이동물리
 */
export class AttackMovementPhysics {
  /**
   * Calculates attack movement displacement and timing.
   *
   * **Korean**: 공격 이동 계산 (Calculate Attack Movement)
   *
   * Determines forward lunge distance and recovery timing based on:
   * 1. Base movement from animation type
   * 2. Stance movement modifier (8 trigram effects)
   * 3. Animation phase durations (lunge vs recovery)
   *
   * @param config - Attack movement configuration
   * @returns Attack movement result with displacement and timing
   *
   * @example
   * ```typescript
   * // Front kick with Heaven stance
   * const kick = physics.calculateAttackMovement({
   *   animationType: AnimationType.FRONT_KICK,
   *   currentStance: TrigramStance.GEON,
   *   direction: attackVector,
   *   animationDuration: 0.4,
   * });
   * // Result: ~0.88m forward (0.8m * 1.1 Geon modifier)
   *
   * // Jab with Mountain stance
   * const jab = physics.calculateAttackMovement({
   *   animationType: AnimationType.JAB,
   *   currentStance: TrigramStance.GAN,
   *   direction: attackVector,
   *   animationDuration: 0.25,
   * });
   * // Result: ~0.24m forward (0.3m * 0.8 Gan modifier)
   * ```
   *
   * @public
   * @korean 공격이동계산
   */
  calculateAttackMovement(
    config: AttackMovementConfig
  ): AttackMovementResult {
    // 1. Get base movement distance for animation type
    const baseDistance = this.getBaseMovementDistance(config.animationType);
 
    // 2. Apply stance movement modifier
    const stanceModifier = this.getStanceMovementModifier(config.currentStance);
    const finalDistance = baseDistance * stanceModifier;
 
    // 3. Calculate displacement vector
    const displacement = config.direction.clone().multiplyScalar(finalDistance);
 
    // 4. Calculate phase durations (lunge + recovery)
    const lungeDuration = config.animationDuration * 0.5; // First 50% = forward
    const recoveryDuration = config.animationDuration * 0.5; // Last 50% = return
 
    return {
      displacement,
      lungeDuration,
      recoveryDuration,
      totalDuration: config.animationDuration,
    };
  }
 
  /**
   * Gets base forward movement distance for animation type.
   *
   * **Korean**: 기본 이동 거리 (Base Movement Distance)
   *
   * Movement distances by technique category:
   * - Kicks: 0.8-1.2m (leg extension, longest reach)
   * - Punches: 0.3-0.5m (arm extension, body lunge)
   * - Elbows/Knees: 0.2-0.3m (close range techniques)
   * - Spinning: 0.5-0.8m (rotation carries momentum)
   *
   * @param animationType - Type of attack animation
   * @returns Base movement distance in meters
   *
   * @private
   * @korean 기본이동거리
   */
  private getBaseMovementDistance(animationType: AnimationType): number {
    // Kicks - highest forward movement (leg extension)
    if (
      animationType === AnimationType.ROUNDHOUSE_KICK ||
      animationType === AnimationType.SIDE_KICK ||
      animationType === AnimationType.BACK_KICK
    ) {
      return 1.0; // 1.0m forward lunge
    }
 
    if (
      animationType === AnimationType.FRONT_KICK ||
      animationType === AnimationType.PUSH_KICK
    ) {
      return 0.8; // 0.8m forward lunge
    }
 
    if (
      animationType === AnimationType.AXE_KICK ||
      animationType === AnimationType.CRESCENT_KICK ||
      animationType === AnimationType.LOW_KICK
    ) {
      return 0.9; // 0.9m forward lunge
    }
 
    // Spinning kicks - momentum carries body forward
    if (
      animationType === AnimationType.SPINNING_HOOK ||
      animationType === AnimationType.SPINNING_HEEL_KICK ||
      animationType === AnimationType.TORNADO_KICK
    ) {
      return 0.8; // 0.8m with rotation
    }
 
    // Jumping/flying kicks - aerial momentum
    if (
      animationType === AnimationType.FLYING_KICK ||
      animationType === AnimationType.JUMPING_KICK
    ) {
      return 1.2; // 1.2m maximum extension
    }
 
    // Punches - moderate forward movement (arm + body lunge)
    if (
      animationType === AnimationType.CROSS ||
      animationType === AnimationType.OVERHAND ||
      animationType === AnimationType.HOOK
    ) {
      return 0.5; // 0.5m forward lunge
    }
 
    if (
      animationType === AnimationType.JAB ||
      animationType === AnimationType.BACKFIST
    ) {
      return 0.3; // 0.3m forward lunge
    }
 
    if (
      animationType === AnimationType.UPPERCUT ||
      animationType === AnimationType.HAMMER_FIST ||
      animationType === AnimationType.PALM_STRIKE
    ) {
      return 0.4; // 0.4m forward lunge
    }
 
    // Elbow/Knee - minimal movement (close range)
    if (
      animationType === AnimationType.ELBOW_STRIKE ||
      animationType === AnimationType.KNEE_STRIKE ||
      animationType === AnimationType.KNEE_KICK ||
      animationType === AnimationType.ELBOW_UPPERCUT ||
      animationType === AnimationType.FLYING_KNEE ||
      animationType === AnimationType.CLINCH_KNEE ||
      animationType === AnimationType.SPINNING_ELBOW ||
      animationType === AnimationType.TEMPLE_ELBOW ||
      animationType === AnimationType.SPINNING_BACK_ELBOW ||
      animationType === AnimationType.SPINAL_ELBOW ||
      animationType === AnimationType.BRACHIAL_ELBOW ||
      animationType === AnimationType.KIDNEY_KNEE ||
      animationType === AnimationType.FEMORAL_KNEE
    ) {
      return 0.2; // 0.2m forward lunge
    }
 
    // Specialized jab variants - similar to jab (quick extension)
    if (
      animationType === AnimationType.SPEAR_HAND_STRIKE ||
      animationType === AnimationType.NERVE_STRIKE ||
      animationType === AnimationType.PRESSURE_POINT_STRIKE ||
      animationType === AnimationType.LIGHTNING_STRIKE ||
      animationType === AnimationType.RAPID_BARRAGE ||
      animationType === AnimationType.RHYTHMIC_STRIKES ||
      animationType === AnimationType.NERVE_PARALYSIS ||
      animationType === AnimationType.THROAT_STRIKE ||
      animationType === AnimationType.EYE_GOUGE
    ) {
      return 0.3; // 0.3m forward lunge (jab-like)
    }
 
    // Specialized cross variants - similar to cross (body weight transfer)
    if (
      animationType === AnimationType.HEAVEN_STRIKE ||
      animationType === AnimationType.FLOWING_CROSS
    ) {
      return 0.5; // 0.5m forward lunge (cross-like)
    }
 
    // Specialized palm strikes - similar to palm strike
    if (
      animationType === AnimationType.SOLAR_PLEXUS_STRIKE ||
      animationType === AnimationType.FLOWING_PUSH ||
      animationType === AnimationType.LIVER_DISRUPTION ||
      animationType === AnimationType.EAR_STRIKE
    ) {
      return 0.4; // 0.4m forward lunge (palm-like)
    }
 
    // Grappling - minimal forward movement (rotation/off-balancing in place)
    if (
      animationType === AnimationType.THROW ||
      animationType === AnimationType.JOINT_LOCK ||
      animationType === AnimationType.TAKEDOWN ||
      animationType === AnimationType.SWEEP ||
      animationType === AnimationType.CLINCH ||
      animationType === AnimationType.GRAPPLE ||
      animationType === AnimationType.SLAM ||
      animationType === AnimationType.WRIST_LOCK ||
      animationType === AnimationType.ARM_BAR ||
      animationType === AnimationType.SHOULDER_LOCK ||
      animationType === AnimationType.HIP_THROW ||
      animationType === AnimationType.LEG_REAP ||
      animationType === AnimationType.SMALL_CIRCLE_LOCK ||
      animationType === AnimationType.FINGER_LOCK ||
      animationType === AnimationType.ELBOW_LOCK ||
      animationType === AnimationType.SHOULDER_MANIPULATION ||
      animationType === AnimationType.MOUNTAIN_LOCK ||
      animationType === AnimationType.EARTH_EMBRACE ||
      animationType === AnimationType.CAROTID_CHOKE
    ) {
      return 0.05; // 0.05m forward movement for grappling entries
    }
 
    // Default - conservative minimal movement for any unmapped types
    // Additional AnimationType values can be grouped with the closest category above
    // to fine-tune their forward displacement without changing overall behavior
    return 0.2;
  }
 
  /**
   * Gets stance movement modifier for attack lunge.
   *
   * **Korean**: 자세 이동 배율 (Stance Movement Modifier)
   *
   * Trigram stance movement modifiers based on combat philosophy:
   * - ☰ 건 (Geon/Heaven): +30% movement (aggressive, drives forward with pure yang)
   * - ☳ 진 (Jin/Thunder): +20% movement (explosive power, shocking force)
   * - ☴ 손 (Son/Wind): +15% movement (continuous flow, mobile)
   * - ☲ 리 (Li/Fire): +10% movement (precision strikes, controlled aggression)
   * - ☱ 태 (Tae/Lake): 0% (neutral, fluid and adaptive)
   * - ☵ 감 (Gam/Water): 0% (neutral, flowing and flexible)
   * - ☷ 곤 (Gon/Earth): -10% movement (grounded, stable techniques)
   * - ☶ 간 (Gan/Mountain): -20% movement (defensive mastery, minimal advance)
   *
   * @param stance - Current trigram stance
   * @returns Movement multiplier (0.8 to 1.3)
   *
   * @private
   * @korean 자세이동배율
   */
  private getStanceMovementModifier(stance: TrigramStance): number {
    const modifiers: Record<TrigramStance, number> = {
      [TrigramStance.GEON]: 1.3, // Heaven: +30% aggressive forward pressure (pure yang drives forward)
      [TrigramStance.JIN]: 1.2, // Thunder: +20% explosive movement
      [TrigramStance.SON]: 1.15, // Wind: +15% flowing movement
      [TrigramStance.LI]: 1.1, // Fire: +10% precision strikes with controlled forward movement
      [TrigramStance.TAE]: 1.0, // Lake: neutral movement
      [TrigramStance.GAM]: 1.0, // Water: neutral movement
      [TrigramStance.GON]: 0.9, // Earth: -10% grounded movement
      [TrigramStance.GAN]: 0.8, // Mountain: -20% defensive movement
    };
    return modifiers[stance];
  }
 
  /**
   * Applies attack movement force to attacker position over time.
   *
   * **Korean**: 공격 이동 적용 (Apply Attack Movement)
   *
   * Uses smooth ease-out cubic curve for realistic lunge feel:
   * - Fast initial forward movement (attack commitment)
   * - Gradual deceleration at peak extension
   * - Smooth return during recovery phase
   *
   * @param basePosition - Original stance position (does not change during attack)
   * @param result - Attack movement result with displacement
   * @param elapsedTime - Time elapsed since attack started
   * @param isRecoveryPhase - Whether in recovery (return) phase
   * @returns New position with attack displacement applied
   *
   * @example
   * ```typescript
   * // In animation update loop (60fps)
   * const basePos = new THREE.Vector3(0, 0, 0); // Original stance position
   * 
   * if (elapsedTime < result.lungeDuration) {
   *   // Lunge forward phase
   *   const newPosition = physics.applyAttackMovement(
   *     basePos,
   *     result,
   *     elapsedTime,
   *     false
   *   );
   * } else if (elapsedTime < result.totalDuration) {
   *   // Recovery return phase
   *   const newPosition = physics.applyAttackMovement(
   *     basePos,
   *     result,
   *     elapsedTime,
   *     true
   *   );
   * }
   * ```
   *
   * @public
   * @korean 공격이동적용
   */
  applyAttackMovement(
    basePosition: THREE.Vector3,
    result: AttackMovementResult,
    elapsedTime: number,
    isRecoveryPhase: boolean
  ): THREE.Vector3 {
    let progress: number;
 
    if (!isRecoveryPhase) {
      // Lunge forward phase
      progress = Math.min(1.0, elapsedTime / result.lungeDuration);
 
      // Smooth forward lunge curve (ease-out cubic)
      // Fast initial commitment, gradual deceleration at peak
      const easedProgress = 1 - Math.pow(1 - progress, 3);
 
      // Calculate position along forward path
      const currentDisplacement = result.displacement
        .clone()
        .multiplyScalar(easedProgress);
 
      return basePosition.clone().add(currentDisplacement);
    } else {
      // Recovery return phase
      const recoveryTime = elapsedTime - result.lungeDuration;
      progress = Math.min(1.0, recoveryTime / result.recoveryDuration);
 
      // Smooth return curve (ease-in cubic)
      // Gradual start, faster finish back to stance
      const easedProgress = Math.pow(progress, 3);
 
      // Calculate return position (from peak back to origin)
      const returnDisplacement = result.displacement
        .clone()
        .multiplyScalar(1.0 - easedProgress);
 
      return basePosition.clone().add(returnDisplacement);
    }
  }
 
  /**
   * Checks if attacker is currently in lunge phase.
   *
   * **Korean**: 돌진 상태 확인 (Check Lunge State)
   *
   * @param elapsedTime - Time elapsed since attack started
   * @param lungeDuration - Total lunge phase duration
   * @returns True if in forward lunge phase
   *
   * @public
   * @korean 돌진상태확인
   */
  isInLungePhase(elapsedTime: number, lungeDuration: number): boolean {
    return elapsedTime < lungeDuration;
  }
 
  /**
   * Checks if attacker is in recovery return phase.
   *
   * **Korean**: 회복 상태 확인 (Check Recovery State)
   *
   * @param elapsedTime - Time elapsed since attack started
   * @param result - Attack movement result with timing
   * @returns True if in recovery return phase
   *
   * @public
   * @korean 회복상태확인
   */
  isInRecoveryPhase(
    elapsedTime: number,
    result: AttackMovementResult
  ): boolean {
    return (
      elapsedTime >= result.lungeDuration &&
      elapsedTime < result.totalDuration
    );
  }
 
  /**
   * Gets bilingual Korean-English name for lunge phase.
   *
   * **Korean**: 돌진 단계 이름 (Lunge Phase Name)
   *
   * @returns Korean and English phase names
   *
   * @public
   * @korean 돌진단계이름
   */
  getLungePhaseName(): { korean: string; english: string } {
    return {
      korean: "돌진",
      english: "Lunge",
    };
  }
 
  /**
   * Gets bilingual Korean-English name for recovery phase.
   *
   * **Korean**: 복귀 단계 이름 (Recovery Phase Name)
   *
   * @returns Korean and English phase names
   *
   * @public
   * @korean 복귀단계이름
   */
  getRecoveryPhaseName(): { korean: string; english: string } {
    return {
      korean: "복귀",
      english: "Recovery",
    };
  }
}
 
export default AttackMovementPhysics;