All files / systems/animation BodyFacingSystem.ts

96.49% Statements 55/57
82.14% Branches 23/28
88.88% Functions 16/18
96.49% Lines 55/57

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                                                          27x               27x               27x               27x               27x                 27x                                   273x 273x 7x     273x                                               56x 56x   56x     56x 3x 53x 2x     56x                                                 19x 19x       19x   19x                             19x                         41x 41x                                                                                         30x 3x       27x 2x   2x   1x                       1x             25x     25x   6x                   19x     19x     19x       19x 19x         19x           19x                                                                                     3x 3x                               2x                                   3x                               2x                           4x                           2x 2x                                                                                                   3x                                             1x                                     1x                         1x                   27x      
/**
 * Body Facing Direction System for Black Trigram
 * 
 * Manages automatic character rotation to face opponent with:
 * - Smooth torso rotation at 45°/sec (±90° range)
 * - Independent head tracking (±45° range)
 * - 180° turn animations for repositioning
 * - Facing lock during attack/defend animations
 * 
 * Korean terminology:
 * - 정면향하기 (Jeongmyeon Hyanghagi) - Face forward
 * - 몸회전 (Mom Hoejeon) - Body rotation
 * - 머리추적 (Meori Chujok) - Head tracking
 * - 180도회전 (180-do Hoejeon) - 180-degree turn
 * 
 * @module systems/animation/BodyFacingSystem
 * @category Animation System
 * @korean 몸향하기시스템
 */
 
import { Position } from "@/types";
import type { BodyFacing } from "./types";
 
/**
 * Default rotation speed in degrees per second
 * 45°/sec provides smooth, realistic rotation
 * 
 * @korean 기본회전속도
 */
export const DEFAULT_ROTATION_SPEED = 45;
 
/**
 * Maximum torso rotation range in degrees
 * Torso can rotate ±90° from facing direction
 * 
 * @korean 최대몸통회전
 */
export const MAX_TORSO_ROTATION = 90;
 
/**
 * Maximum head rotation offset in degrees
 * Head can track independently ±45° from torso
 * 
 * @korean 최대머리회전
 */
export const MAX_HEAD_ROTATION = 45;
 
/**
 * Threshold angle for triggering 180° turn animation
 * If angle difference exceeds this, play full turn animation
 * 
 * @korean 180도회전기준각도
 */
export const TURN_THRESHOLD_ANGLE = 90;
 
/**
 * Duration of 180° turn animation in milliseconds
 * 12 frames at 60fps = 200ms
 * 
 * @korean 회전애니메이션시간
 */
export const TURN_ANIMATION_DURATION = 200;
 
/**
 * Head tracking smoothing factor (0-1)
 * Lower values = smoother but slower head tracking
 * 0.1 = smooth, natural head movement
 * 
 * @korean 머리추적부드러움
 */
export const HEAD_TRACKING_SMOOTHING = 0.1;
 
/**
 * Normalizes an angle to 0-360 degree range
 * 
 * @param angle - Angle in degrees
 * @returns Normalized angle in 0-360 range
 * 
 * @example
 * ```typescript
 * normalizeAngle(370); // Returns 10
 * normalizeAngle(-30); // Returns 330
 * ```
 * 
 * @public
 * @korean 각도정규화
 */
export function normalizeAngle(angle: number): number {
  let normalized = angle % 360;
  if (normalized < 0) {
    normalized += 360;
  }
  // Handle -0 edge case (JavaScript quirk)
  return normalized === 0 ? 0 : normalized;
}
 
/**
 * Calculates the shortest angular difference between two angles
 * Returns value in range [-180, 180]
 * - Positive = clockwise rotation
 * - Negative = counter-clockwise rotation
 * 
 * @param from - Starting angle in degrees
 * @param to - Target angle in degrees
 * @returns Shortest angular difference in degrees
 * 
 * @example
 * ```typescript
 * calculateAngleDifference(10, 350); // Returns -20 (turn left)
 * calculateAngleDifference(350, 10); // Returns 20 (turn right)
 * calculateAngleDifference(0, 180); // Returns 180
 * ```
 * 
 * @public
 * @korean 각도차이계산
 */
export function calculateAngleDifference(from: number, to: number): number {
  const fromNorm = normalizeAngle(from);
  const toNorm = normalizeAngle(to);
  
  let diff = toNorm - fromNorm;
  
  // Find shortest path
  if (diff > 180) {
    diff -= 360;
  } else if (diff < -180) {
    diff += 360;
  }
  
  return diff;
}
 
/**
 * Calculates angle from one position to another
 * Returns angle in degrees (0-360)
 * - 0° = pointing right (+X)
 * - 90° = pointing down (+Z)
 * - 180° = pointing left (-X)
 * - 270° = pointing up (-Z)
 * 
 * @param from - Starting position
 * @param to - Target position
 * @returns Angle in degrees
 * 
 * @example
 * ```typescript
 * calculateAngleToTarget({ x: 0, y: 0 }, { x: 1, y: 0 }); // Returns 0° (right)
 * calculateAngleToTarget({ x: 0, y: 0 }, { x: 0, y: 1 }); // Returns 90° (down)
 * ```
 * 
 * @public
 * @korean 목표각도계산
 */
export function calculateAngleToTarget(from: Position, to: Position): number {
  const dx = to.x - from.x;
  const dz = to.y - from.y; // Position.y is Z coordinate in 2D top-down
  
  // atan2 returns angle in radians, convert to degrees
  // atan2(y, x) where y is forward/back (Z), x is left/right (X)
  const angle = Math.atan2(dz, dx) * (180 / Math.PI);
  
  return normalizeAngle(angle);
}
 
/**
 * Linear interpolation between two values
 * 
 * @param start - Start value
 * @param end - End value
 * @param t - Interpolation factor (0-1)
 * @returns Interpolated value
 * 
 * @private
 * @korean 선형보간
 */
function lerp(start: number, end: number, t: number): number {
  return start + (end - start) * t;
}
 
/**
 * Creates default body facing state
 * 
 * @param initialAngle - Initial facing angle in degrees (default: 0)
 * @returns Default BodyFacing state
 * 
 * @public
 * @korean 기본몸향하기생성
 */
export function createDefaultBodyFacing(initialAngle = 0): BodyFacing {
  const initialRadians = (initialAngle * Math.PI) / 180;
  return {
    currentAngle: normalizeAngle(initialAngle),
    targetAngle: normalizeAngle(initialAngle),
    rotationSpeed: DEFAULT_ROTATION_SPEED,
    headAngleOffset: 0,
    isLocked: false,
    isTurning: false,
    torsoRotation: 0, // No initial torso twist
    hipRotation: initialRadians, // Hips aligned with current angle
  };
}
 
/**
 * Updates body facing direction with smooth rotation
 * 
 * Performs smooth rotation toward target angle at specified speed.
 * Handles:
 * - Rotation locking during attacks
 * - 180° turn animation triggering
 * - Head tracking with independent offset
 * - Smooth interpolation at 45°/sec
 * 
 * @param facing - Current body facing state
 * @param targetAngle - Desired facing angle in degrees
 * @param deltaTime - Time elapsed since last update in seconds
 * @param currentTime - Current timestamp in milliseconds
 * @returns Updated body facing state
 * 
 * @example
 * ```typescript
 * const facing = createDefaultBodyFacing(0);
 * const updated = updateBodyFacing(facing, 90, 0.016, Date.now());
 * // Rotates ~0.72° toward 90° (45°/sec * 0.016s)
 * ```
 * 
 * @public
 * @korean 몸향하기업데이트
 */
export function updateBodyFacing(
  facing: BodyFacing,
  targetAngle: number,
  deltaTime: number,
  currentTime: number
): BodyFacing {
  // If locked, no rotation allowed
  if (facing.isLocked) {
    return facing;
  }
 
  // Check if 180° turn animation is in progress
  if (facing.isTurning && facing.turnStartTime) {
    const elapsed = currentTime - facing.turnStartTime;
    
    if (elapsed >= TURN_ANIMATION_DURATION) {
      // Turn animation complete - snap to target angle
      return {
        ...facing,
        currentAngle: normalizeAngle(targetAngle),
        targetAngle: normalizeAngle(targetAngle),
        headAngleOffset: 0,
        isTurning: false,
        turnDirection: undefined,
        turnStartTime: undefined,
      };
    }
    
    // Still turning - don't update angle yet
    return {
      ...facing,
      targetAngle: normalizeAngle(targetAngle),
    };
  }
 
  // Calculate angle difference
  const angleDiff = calculateAngleDifference(facing.currentAngle, targetAngle);
 
  // Check if 180° turn is needed
  if (Math.abs(angleDiff) > TURN_THRESHOLD_ANGLE && !facing.isTurning) {
    // Trigger 180° turn animation
    return {
      ...facing,
      targetAngle: normalizeAngle(targetAngle),
      isTurning: true,
      turnDirection: angleDiff > 0 ? 'right' : 'left',
      turnStartTime: currentTime,
    };
  }
 
  // Calculate maximum rotation for this frame
  const maxRotation = facing.rotationSpeed * deltaTime;
  
  // Calculate actual rotation (limited by max rotation)
  const rotation = Math.sign(angleDiff) * Math.min(Math.abs(angleDiff), maxRotation);
 
  // Update current angle
  const newCurrentAngle = normalizeAngle(facing.currentAngle + rotation);
 
  // Update head tracking (±45° range independent of torso)
  // Head smoothly tracks toward target within allowed range
  const remainingDiff = calculateAngleDifference(newCurrentAngle, targetAngle);
  const targetHeadOffset = Math.max(
    -MAX_HEAD_ROTATION,
    Math.min(MAX_HEAD_ROTATION, remainingDiff)
  );
  
  const newHeadOffset = lerp(
    facing.headAngleOffset,
    targetHeadOffset,
    HEAD_TRACKING_SMOOTHING
  );
 
  return {
    ...facing,
    currentAngle: newCurrentAngle,
    targetAngle: normalizeAngle(targetAngle),
    headAngleOffset: newHeadOffset,
  };
}
 
/**
 * Updates facing direction to point toward opponent
 * 
 * Calculates target angle based on opponent position and updates
 * body facing state with smooth rotation.
 * 
 * @param facing - Current body facing state
 * @param playerPosition - Player's current position
 * @param opponentPosition - Opponent's current position
 * @param deltaTime - Time elapsed since last update in seconds
 * @param currentTime - Current timestamp in milliseconds
 * @returns Updated body facing state
 * 
 * @example
 * ```typescript
 * const updated = updateFacingTowardOpponent(
 *   facing,
 *   { x: 100, y: 200 },
 *   { x: 300, y: 200 },
 *   0.016,
 *   Date.now()
 * );
 * // Faces toward opponent (pointing right in this case)
 * ```
 * 
 * @public
 * @korean 상대방향하기업데이트
 */
export function updateFacingTowardOpponent(
  facing: BodyFacing,
  playerPosition: Position,
  opponentPosition: Position,
  deltaTime: number,
  currentTime: number
): BodyFacing {
  const targetAngle = calculateAngleToTarget(playerPosition, opponentPosition);
  return updateBodyFacing(facing, targetAngle, deltaTime, currentTime);
}
 
/**
 * Locks facing direction (during attacks/defends)
 * 
 * Prevents rotation while attack or defend animation is playing.
 * Maintains current facing angle.
 * 
 * @param facing - Current body facing state
 * @returns Updated body facing state with lock enabled
 * 
 * @public
 * @korean 회전잠금
 */
export function lockFacing(facing: BodyFacing): BodyFacing {
  return {
    ...facing,
    isLocked: true,
  };
}
 
/**
 * Unlocks facing direction (after attacks/defends complete)
 * 
 * Allows rotation to resume after attack or defend animation completes.
 * 
 * @param facing - Current body facing state
 * @returns Updated body facing state with lock disabled
 * 
 * @public
 * @korean 회전잠금해제
 */
export function unlockFacing(facing: BodyFacing): BodyFacing {
  return {
    ...facing,
    isLocked: false,
  };
}
 
/**
 * Checks if character is currently turning (180° animation)
 * 
 * @param facing - Current body facing state
 * @returns True if 180° turn animation is in progress
 * 
 * @public
 * @korean 회전중확인
 */
export function isTurning(facing: BodyFacing): boolean {
  return facing.isTurning;
}
 
/**
 * Gets current facing angle in radians
 * Useful for Three.js rotation (expects radians)
 * 
 * @param facing - Current body facing state
 * @returns Current facing angle in radians
 * 
 * @public
 * @korean 라디안각도
 */
export function getFacingAngleRadians(facing: BodyFacing): number {
  return (facing.currentAngle * Math.PI) / 180;
}
 
/**
 * Gets head angle in radians including offset
 * Combines torso rotation with head tracking offset
 * 
 * @param facing - Current body facing state
 * @returns Head rotation angle in radians
 * 
 * @public
 * @korean 머리각도라디안
 */
export function getHeadAngleRadians(facing: BodyFacing): number {
  const totalAngle = facing.currentAngle + facing.headAngleOffset;
  return (totalAngle * Math.PI) / 180;
}
 
/**
 * Gets torso rotation in radians
 * Returns the torso rotation relative to hips
 * 
 * @param facing - Current body facing state
 * @returns Torso rotation in radians (defaults to 0 if not set)
 * 
 * @public
 * @korean 허리회전라디안
 */
export function getTorsoRotationRadians(facing: BodyFacing): number {
  return facing.torsoRotation ?? 0;
}
 
/**
 * Gets hip rotation in radians
 * Returns the hip/pelvis base rotation
 * 
 * @param facing - Current body facing state
 * @returns Hip rotation in radians
 * 
 * @public
 * @korean 골반회전라디안
 */
export function getHipRotationRadians(facing: BodyFacing): number {
  return facing.hipRotation ?? getFacingAngleRadians(facing);
}
 
/**
 * Body Facing System singleton for managing character rotation
 * 
 * Provides centralized system for body facing calculations and updates.
 * 
 * @public
 * @korean 몸향하기시스템
 */
export class BodyFacingSystem {
  /**
   * Creates default body facing state for a new player
   * 
   * @param initialAngle - Initial facing angle in degrees
   * @returns Default body facing state
   * 
   * @public
   * @korean 기본상태생성
   */
  createDefaultState(initialAngle = 0): BodyFacing {
    return createDefaultBodyFacing(initialAngle);
  }
 
  /**
   * Updates body facing with opponent tracking
   * 
   * @param facing - Current body facing state
   * @param playerPosition - Player position
   * @param opponentPosition - Opponent position
   * @param deltaTime - Delta time in seconds
   * @param currentTime - Current timestamp
   * @returns Updated body facing state
   * 
   * @public
   * @korean 업데이트
   */
  update(
    facing: BodyFacing,
    playerPosition: Position,
    opponentPosition: Position,
    deltaTime: number,
    currentTime: number
  ): BodyFacing {
    return updateFacingTowardOpponent(
      facing,
      playerPosition,
      opponentPosition,
      deltaTime,
      currentTime
    );
  }
 
  /**
   * Locks facing during attacks
   * 
   * @param facing - Current body facing state
   * @returns Updated state with lock
   * 
   * @public
   * @korean 잠금
   */
  lock(facing: BodyFacing): BodyFacing {
    return lockFacing(facing);
  }
 
  /**
   * Unlocks facing after attacks
   * 
   * @param facing - Current body facing state
   * @returns Updated state without lock
   * 
   * @public
   * @korean 잠금해제
   */
  unlock(facing: BodyFacing): BodyFacing {
    return unlockFacing(facing);
  }
}
 
/**
 * Default body facing system instance
 * 
 * @public
 * @korean 기본몸향하기시스템
 */
export const bodyFacingSystem = new BodyFacingSystem();
 
export default bodyFacingSystem;