All files / components/shared/three/models SkeletalPlayer3D.tsx

55.2% Statements 53/96
42.3% Branches 44/104
84.21% Functions 16/19
55.05% Lines 49/89

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                                                                                                      8x 71x                   71x                   8x 71x                   71x                                                                   8x                                                                         142x 71x         142x 71x                 142x                 142x               142x             142x           142x               142x 71x         142x 71x 71x 69x         142x 142x     142x 142x 142x     142x     71x         71x   71x 71x             142x     71x         71x 71x             142x 71x       71x       71x                                           142x 71x       142x 71x 71x                     142x     142x                                                                                                                                                                                           142x   142x                                                                                                                                                                                                                                                                          
/**
 * SkeletalPlayer3D component with articulated body model
 *
 * Implements full skeletal rigging system for realistic fighter animations
 * with independent limb movement, elbow/knee joints, and attack animations.
 *
 * @module components/three/SkeletalPlayer3D
 * @category 3D Components
 * @korean 골격플레이어3D컴포넌트
 */
 
import { Html } from "@react-three/drei";
import { useFrame } from "@react-three/fiber";
import React, { useEffect, useMemo, useRef, useState } from "react";
import * as THREE from "three";
import { getArchetypePhysicalAttributes } from "../../../../data/archetypePhysicalAttributes";
import {
  createDefaultFacialDamage,
  createScaledHumanoidRig,
  getExpressionFromCombatState,
  getFacingAngleRadians,
  getHeadAngleRadians,
  lockFacing,
  unlockFacing,
  updateFacingTowardOpponent,
} from "../../../../systems/animation";
import { useBalanceAnimations } from "../../../../hooks/useBalanceAnimations";
import { useGuardPoseOverlay } from "../../../../hooks/useGuardPoseOverlay";
import { useHandPoseTransitions } from "../../../../hooks/useHandPoseTransitions";
import { useMuscleActivation } from "../../../../hooks/useMuscleActivation";
import { useSkeletalAnimation } from "../../../../hooks/useSkeletalAnimation";
import { FONT_FAMILY, KOREAN_COLORS } from "../../../../types/constants";
import { FacialExpression } from "../../../../types/facial";
import type {
  Player3DUnifiedProps,
} from "../../../../types/player-visual";
import type {
  SkeletalRig,
} from "../../../../types/skeletal";
import { toHexColor } from "../../../../utils/colorHelpers";
import { getArchetypeColors } from "../../../../utils/colorUtils";
import BoneRenderer from "../anatomy/BoneRenderer";
import PlayerStateIndicators from "../effects/PlayerStateIndicators";
 
/**
 * Get stance-specific color from Korean theming
 *
 * @param stance - Current trigram stance
 * @returns Hex color number
 * @korean 자세색상가져오기
 */
const getStanceColor = (stance: string): number => {
  const stanceColors: Record<string, number> = {
    geon: KOREAN_COLORS.TRIGRAM_GEON_PRIMARY,
    tae: KOREAN_COLORS.TRIGRAM_TAE_PRIMARY,
    li: KOREAN_COLORS.TRIGRAM_LI_PRIMARY,
    jin: KOREAN_COLORS.TRIGRAM_JIN_PRIMARY,
    son: KOREAN_COLORS.TRIGRAM_SON_PRIMARY,
    gam: KOREAN_COLORS.TRIGRAM_GAM_PRIMARY,
    gan: KOREAN_COLORS.TRIGRAM_GAN_PRIMARY,
    gon: KOREAN_COLORS.TRIGRAM_GON_PRIMARY,
  };
  return stanceColors[stance] ?? KOREAN_COLORS.PRIMARY_CYAN;
};
 
/**
 * Get trigram symbol for stance
 *
 * @param stance - Current trigram stance
 * @returns Unicode trigram symbol
 * @korean 팔괘기호가져오기
 */
const getTrigramSymbol = (stance: string): string => {
  const symbols: Record<string, string> = {
    geon: "☰",
    tae: "☱",
    li: "☲",
    jin: "☳",
    son: "☴",
    gam: "☵",
    gan: "☶",
    gon: "☷",
  };
  return symbols[stance] ?? "☰";
};
 
/**
 * SkeletalPlayer3D Component
 *
 * Complete skeletal player with 28-bone rig and realistic animations.
 * Supports all Korean martial arts attack animations (jab, cross, kicks, block).
 *
 * @example
 * ```tsx
 * <SkeletalPlayer3D
 *   playerId="player1"
 *   archetype={PlayerArchetype.MUSA}
 *   stance={TrigramStance.GEON}
 *   position={[0, 0, 0]}
 *   rotation={0}
 *   health={85}
 *   maxHealth={100}
 *   stamina={60}
 *   ki={40}
 *   currentAnimation="attack"
 *   attackAnimation="jab"
 *   showDetails={true}
 * />
 * ```
 *
 * @korean 골격플레이어3D컴포넌트
 */
export const SkeletalPlayer3D: React.FC<
  Player3DUnifiedProps & {
    readonly attackAnimation?: string;
    readonly showSkeleton?: boolean;
  }
> = ({
  playerId,
  archetype,
  stance,
  laterality = "right",
  position,
  rotation,
  health,
  maxHealth,
  stamina,
  ki,
  pain,
  balance,
  consciousness,
  bloodLoss,
  isBlocking,
  isStunned = false,
  isCountering = false,
  currentAnimation,
  isMobile,
  name,
  scale = 1,
  showDetails = true,
  facing = "right",
  showStanceIndicator = true,
  onAnimationComplete,
  attackAnimation,
  showSkeleton = false,
  facialExpression,
  facialDamage,
  enableFacialExpressions = false,
  enableEyeTracking = true,
  opponentPosition,
  bodyFacing,
  onBodyFacingUpdate,
}) => {
  // Get physical attributes for the archetype
  const physicalAttributes = useMemo(
    () => getArchetypePhysicalAttributes(archetype),
    [archetype]
  );
 
  // Create skeletal rig with scaled dimensions based on archetype
  const rig = useMemo<SkeletalRig>(
    () => createScaledHumanoidRig(physicalAttributes),
    [physicalAttributes]
  );
 
  // ========================================
  // ANIMATION HOOKS - Modular animation system
  // ========================================
 
  // Base skeletal animation (idle, walk, attack, etc.)
  const { updateRigAnimation, diagonalRotationY } =
    useSkeletalAnimation({
      currentAnimation,
      attackAnimation,
      isBlocking,
      onAnimationComplete,
    });
 
  // Hand pose transitions for both hands
  const { leftHandState, rightHandState, updateHandAnimations } =
    useHandPoseTransitions({
      currentAnimation,
      attackAnimation,
      isBlocking,
    });
 
  // Guard pose overlay (stance-specific positioning)
  const { applyGuardOverlay } = useGuardPoseOverlay({
    stance,
    laterality,
    currentAnimation,
  });
 
  // Balance animations (sway, stumble, lean based on balance state)
  const { swayPosition, helplessRotation, updateBalanceAnimations } =
    useBalanceAnimations({
      balance,
    });
 
  // Muscle activation system
  const { muscleStates, updateMuscleActivations } = useMuscleActivation({
    currentAnimation,
    attackAnimation,
    isBlocking,
    stamina,
  });
 
  // Get archetype colors
  const archetypeColors = useMemo(
    () => getArchetypeColors(archetype),
    [archetype]
  );
 
  // Body color based on state
  const bodyColor = useMemo(() => {
    Iif (isStunned) return KOREAN_COLORS.WARNING_YELLOW;
    if (health / maxHealth < 0.3) return KOREAN_COLORS.ACCENT_RED;
    Eif (ki / 100 > 0.8) return KOREAN_COLORS.PRIMARY_CYAN;
    return archetypeColors.primary;
  }, [isStunned, health, maxHealth, ki, archetypeColors.primary]);
 
  // Stance color
  const stanceColor = useMemo(() => getStanceColor(stance), [stance]);
  const trigramSymbol = useMemo(() => getTrigramSymbol(stance), [stance]);
 
  // Track recent combat events for expression calculation
  const [justHit, setJustHit] = useState(false);
  const [justLanded, setJustLanded] = useState(false);
  const lastHealthRef = useRef(health);
 
  // Detect hit events (health decreased)
  useEffect(() => {
    let timeoutId: ReturnType<typeof setTimeout> | undefined;
 
    Iif (health < lastHealthRef.current) {
      setJustHit(true);
      timeoutId = setTimeout(() => setJustHit(false), 1000); // Clear after 1 second
    }
 
    lastHealthRef.current = health;
 
    return () => {
      Iif (timeoutId !== undefined) {
        clearTimeout(timeoutId);
      }
    };
  }, [health]);
 
  // Detect successful attacks (currentAnimation changed to attack)
  useEffect(() => {
    let timeoutId: ReturnType<typeof setTimeout> | undefined;
 
    Iif (currentAnimation === "attack") {
      setJustLanded(true);
      timeoutId = setTimeout(() => setJustLanded(false), 500); // Clear after 0.5 seconds
    }
 
    return () => {
      Iif (timeoutId !== undefined) {
        clearTimeout(timeoutId);
      }
    };
  }, [currentAnimation]);
 
  // Calculate facial expression from combat state (or use provided one)
  const calculatedExpression = useMemo(() => {
    Iif (!enableFacialExpressions) {
      return FacialExpression.NEUTRAL;
    }
 
    Iif (facialExpression) {
      return facialExpression;
    }
 
    return getExpressionFromCombatState(
      health,
      maxHealth,
      stamina,
      pain,
      consciousness,
      justHit,
      justLanded
    );
  }, [
    enableFacialExpressions,
    facialExpression,
    health,
    maxHealth,
    stamina,
    pain,
    consciousness,
    justHit,
    justLanded,
  ]);
 
  // Facial damage state
  const calculatedFacialDamage = useMemo(() => {
    return facialDamage ?? createDefaultFacialDamage();
  }, [facialDamage]);
 
  // Opponent position for eye tracking
  const opponentPos = useMemo(() => {
    Eif (opponentPosition) {
      return new THREE.Vector3(...opponentPosition);
    }
    // Default: opponent in front
    return new THREE.Vector3(facing === "right" ? 5 : -5, 2, 0);
  }, [opponentPosition, facing]);
 
  // ========================================
  // ANIMATION FRAME LOOP - Modular hook-based system
  // ========================================
 
  // Frame counter for periodic updates
  const frameCounter = useRef(0);
 
  // Animation loop using useFrame (60fps)
  useFrame((_state, delta) => {
    // Update body facing to track opponent (if enabled)
    if (bodyFacing && opponentPosition && onBodyFacingUpdate) {
      const playerPos = { x: position[0], y: position[2] }; // X and Z for 2D top-down
      const opponentPos = { x: opponentPosition[0], y: opponentPosition[2] };
 
      // Check if facing should be locked during committed animations
      const isStepAnimation =
        typeof currentAnimation === "string" &&
        currentAnimation.startsWith("step_");
      const isTurnAnimation =
        typeof currentAnimation === "string" &&
        currentAnimation.startsWith("turn_");
 
      const shouldLock =
        currentAnimation === "attack" ||
        currentAnimation === "defend" ||
        isStepAnimation ||
        isTurnAnimation;
 
      let updatedFacing = bodyFacing;
 
      if (shouldLock && !bodyFacing.isLocked) {
        // Lock facing at start of committed action (attack/defend/step/turn)
        updatedFacing = lockFacing(bodyFacing);
      } else if (!shouldLock && bodyFacing.isLocked) {
        // Unlock facing after committed action completes
        updatedFacing = unlockFacing(bodyFacing);
      }
 
      // Update facing direction (handles rotation speed, head tracking, turns)
      if (!updatedFacing.isLocked) {
        updatedFacing = updateFacingTowardOpponent(
          updatedFacing,
          playerPos,
          opponentPos,
          delta,
          Date.now()
        );
      }
 
      // Notify parent if facing changed
      if (updatedFacing !== bodyFacing) {
        onBodyFacingUpdate(updatedFacing);
      }
    }
 
    // ========================================
    // HOOK-BASED ANIMATION UPDATES (60fps)
    // ========================================
 
    // Update frame counter for periodic state sync
    frameCounter.current = (frameCounter.current + 1) % 10;
 
    // 1. Base skeletal animation (idle, walk, attack, etc.)
    updateRigAnimation(rig, delta);
 
    // 2. Hand pose transitions
    updateHandAnimations(delta);
 
    // 3. Guard pose overlay (stance-specific positioning)
    applyGuardOverlay(rig, delta);
 
    // 4. Balance animations (sway, stumble, lean)
    updateBalanceAnimations(delta, frameCounter.current);
 
    // 5. Muscle activation states
    updateMuscleActivations(delta, frameCounter.current);
 
    // Apply body facing rotations (torso and head) if available
    // Note: This system already supports independent torso rotation via bodyFacing.torsoRotation
    // The torso rotation can be calculated using calculateTorsoRotation() from SkeletonRig
    // and integrated into bodyFacing state for dynamic upper/lower body separation
    if (bodyFacing) {
      // Apply torso rotation to spine bone from body facing
      // This rotation is relative to hips and allows strafing while facing opponent
      const spine = rig.bones.get("spine_upper");
      if (spine) {
        // Use torso rotation if available, otherwise fall back to full body facing
        const torsoRotation = bodyFacing.torsoRotation ?? getFacingAngleRadians(bodyFacing);
        spine.rotation.y = torsoRotation;
      }
 
      // Apply head rotation to head bone (includes independent offset)
      // Head can track ±45° independently from torso for natural looking
      const head = rig.bones.get("head");
      if (head) {
        const headRotation = getHeadAngleRadians(bodyFacing);
        head.rotation.y = headRotation;
      }
    }
  });
 
  // Use diagonal rotation override if set, otherwise use prop rotation
  const effectiveRotation = diagonalRotationY ?? rotation;
 
  return (
    <group
      position={position}
      rotation={[0, effectiveRotation, 0]}
      scale={[facing === "left" ? -scale : scale, scale, scale]}
      data-testid={`skeletal-player3d-${playerId}`}
    >
      {/* Inner group for sway animation and helpless lean */}
      <group position={swayPosition} rotation={[helplessRotation, 0, 0]}>
        {/* Skeletal rig rendering with bone-attached muscles */}
        <BoneRenderer
          rig={rig}
          color={bodyColor}
          showBones={true}
          renderMode={showSkeleton ? "debug" : "solid"}
          leftHandState={leftHandState}
          rightHandState={rightHandState}
          cameraDistance={10}
          facialExpression={calculatedExpression}
          facialDamage={calculatedFacialDamage}
          opponentPosition={opponentPos}
          enableFacialExpressions={enableFacialExpressions}
          enableEyeTracking={enableEyeTracking}
          physicalAttributes={{
            muscleMass: physicalAttributes.muscleMass,
            fatMass: physicalAttributes.fatMass,
          }}
          muscleStates={muscleStates}
          isExhausted={stamina < 20}
        />
 
        {/* Blocking shield effect */}
        {isBlocking && (
          <mesh position={[0, 1.2, 0.3]}>
            <circleGeometry args={[0.5, 32]} />
            <meshBasicMaterial
              color={KOREAN_COLORS.PRIMARY_BLUE}
              transparent
              opacity={0.5}
              side={2}
            />
          </mesh>
        )}
 
        {/* Counter indicator */}
        {isCountering && (
          <mesh position={[0, 1.5, 0]}>
            <torusGeometry args={[0.4, 0.05, 8, 32]} />
            <meshBasicMaterial color={KOREAN_COLORS.ACCENT_PURPLE} />
          </mesh>
        )}
 
        {/* Player name overlay */}
        {showDetails && name && (
          <Html
            position={[0, 2.8, 0]}
            center
            distanceFactor={isMobile ? 15 : 10}
            occlude={false}
            style={{ pointerEvents: "none", userSelect: "none" }}
          >
            <div
              style={{
                fontFamily: FONT_FAMILY.KOREAN,
                textAlign: "center",
                color: "white",
                textShadow: "0 0 4px rgba(0,0,0,0.8)",
              }}
            >
              {/* Player name */}
              <div
                style={{
                  fontSize: isMobile ? "12px" : "14px",
                  fontWeight: "bold",
                  marginBottom: "4px",
                }}
                data-testid="player-name"
              >
                {name.korean}
              </div>
 
              {/* Trigram symbol */}
              {showStanceIndicator && (
                <div
                  style={{
                    fontSize: isMobile ? "14px" : "16px",
                    color: toHexColor(stanceColor),
                  }}
                  data-testid="trigram-symbol"
                >
                  {trigramSymbol}
                </div>
              )}
 
              {/* Combat state text */}
              {(isBlocking || isStunned || isCountering) && (
                <div
                  style={{
                    fontSize: isMobile ? "10px" : "12px",
                    fontWeight: "bold",
                    color: "#ffff00",
                    marginTop: "4px",
                  }}
                  data-testid="combat-state"
                >
                  {isBlocking ? "방어" : isStunned ? "기절" : "반격"}
                </div>
              )}
            </div>
          </Html>
        )}
 
        {/* State indicators (health, stamina, Ki, balance) */}
        {showDetails && (
          <PlayerStateIndicators
            health={health}
            maxHealth={maxHealth}
            stamina={stamina}
            ki={ki}
            balance={balance}
            consciousness={consciousness}
            pain={pain}
            bloodLoss={bloodLoss}
            isMobile={isMobile}
          />
        )}
      </group>{" "}
      {/* Close inner sway group */}
    </group>
  );
};
 
export default SkeletalPlayer3D;