All files / components/shared/three/anatomy Hand3D.tsx

94.87% Statements 37/39
61.53% Branches 32/52
100% Functions 9/9
94.87% Lines 37/39

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                                                                                                                                                                                                          12x 216x             216x 216x                                                             12x               5280x   2160x                                       5280x 2160x 2160x       5280x                                           12x                     2640x         1080x               1080x           1080x                     2640x 2640x 2640x   2640x 2640x 2640x     2640x   2640x                                                                                                                                                 12x                       528x 216x         528x           528x 528x 528x     528x 528x 528x 528x       528x   528x                                                                                                                                                                                                                                                                                                                                    
/**
 * Hand3D component with finger geometry for martial arts techniques
 *
 * Renders detailed hand with palm and 5 fingers, supporting multiple
 * Korean martial arts hand poses (Fist, Knife-hand, Spear-hand, etc.).
 *
 * Implements LOD (Level of Detail) for performance optimization:
 * - High detail (<5 units): Full finger bones (4 segments per finger)
 * - Medium detail (5-15 units): Simplified fingers (3 segments)
 * - Low detail (>15 units): No finger detail (hand as single unit)
 *
 * @module components/three/Hand3D
 * @category 3D Components
 * @korean 손3D컴포넌트
 */
 
import React, { useEffect, useMemo } from "react";
import * as THREE from "three";
import { KOREAN_COLORS } from "../../../../types/constants";
import type {
  FingerCurl,
  HandLODConfig,
  HandPoseType,
  HandSide,
} from "../../../../types/hand-animation";
 
/**
 * Props for Hand3D component
 *
 * @public
 * @korean 손3D속성
 */
export interface Hand3DProps {
  /**
   * Hand side (left or right)
   * @korean 손쪽
   */
  readonly side: HandSide;
 
  /**
   * Current hand pose
   * @korean 현재손자세
   */
  readonly pose: HandPoseType;
 
  /**
   * Finger curl amounts (0-1 per finger)
   * @korean 손가락구부림
   */
  readonly fingerCurl: FingerCurl;
 
  /**
   * Distance from camera for LOD
   * @korean 카메라거리
   */
  readonly distanceFromCamera: number;
 
  /**
   * Wrist rotation
   * @korean 손목회전
   */
  readonly wristRotation: THREE.Euler;
 
  /**
   * Whether hand is highlighted for vital point targeting
   * @korean 표시여부
   */
  readonly isHighlighted?: boolean;
 
  /**
   * Highlight mode for striking surfaces
   * @korean 표시모드
   */
  readonly highlightMode?:
    | "none"
    | "knuckles"
    | "palm"
    | "knife_edge"
    | "fingertips"
    | null;
 
  /**
   * Base skin color
   * @korean 피부색
   */
  readonly skinColor?: number;
 
  /**
   * Scale multiplier
   * @korean 크기배율
   */
  readonly scale?: number;
}
 
/**
 * Determine LOD config based on camera distance
 *
 * @param distance - Distance from camera
 * @returns LOD configuration
 * @korean LOD설정결정
 */
const getLODConfig = (distance: number): HandLODConfig => {
  Iif (distance < 5) {
    return {
      detailLevel: "high",
      distanceThresholds: { high: 5, medium: 15, low: 100 },
      renderFingers: true,
      fingerSegments: 4,
    };
  } else if (distance < 15) {
    return {
      detailLevel: "medium",
      distanceThresholds: { high: 5, medium: 15, low: 100 },
      renderFingers: true,
      fingerSegments: 3,
    };
  } else E{
    return {
      detailLevel: "low",
      distanceThresholds: { high: 5, medium: 15, low: 100 },
      renderFingers: false,
      fingerSegments: 0,
    };
  }
};
 
/**
 * Finger segment component
 *
 * Renders a single finger segment (proximal, intermediate, or distal phalanx).
 *
 * @korean 손가락세그먼트컴포넌트
 */
interface FingerSegmentProps {
  readonly position: [number, number, number];
  readonly rotation: [number, number, number];
  readonly length: number;
  readonly radius: number;
  readonly color: number;
}
 
const FingerSegment: React.FC<FingerSegmentProps> = ({
  position,
  rotation,
  length,
  radius,
  color,
}) => {
  // Memoize material to avoid recreating on every render
  const material = useMemo(
    () =>
      new THREE.MeshPhysicalMaterial({
        color: color,
        metalness: 0,
        roughness: 0.6,
        clearcoat: 0.3,
        clearcoatRoughness: 0.5,
        // PBR skin properties
        transmission: 0,
        thickness: 0.1,
        ior: 1.4, // Index of refraction for skin
        sheen: 0.1, // Subtle skin sheen
        sheenRoughness: 0.8,
        // Subtle emissive for alive appearance
        emissive: new THREE.Color(color),
        emissiveIntensity: 0.02,
      }),
    [color],
  );
 
  // Dispose material on unmount to prevent memory leaks
  useEffect(() => {
    return () => {
      material.dispose();
    };
  }, [material]);
 
  return (
    <mesh position={position} rotation={rotation} castShadow receiveShadow>
      <capsuleGeometry args={[radius, length, 4, 8]} />
      <primitive object={material} attach="material" />
    </mesh>
  );
};
 
/**
 * Single finger component with curl animation
 *
 * @korean 손가락컴포넌트
 */
interface FingerProps {
  readonly fingerName: string;
  readonly basePosition: [number, number, number];
  readonly curl: number;
  readonly segments: number;
  readonly isHighlighted: boolean;
  readonly skinColor: number;
}
 
const Finger: React.FC<FingerProps> = ({
  fingerName,
  basePosition,
  curl,
  segments,
  isHighlighted,
  skinColor,
}) => {
  // Finger dimensions based on anatomical proportions
  // For ~180cm person: index ~7cm, middle ~8cm, ring ~7.5cm, pinky ~6cm, thumb ~5cm
  // These dimensions are in METERS for Three.js
  const dimensions = useMemo(() => {
    // Finger segment lengths based on anatomical proportions (in meters)
    // Total finger length: proximal + intermediate + distal
    // Index: ~7cm total = 0.03 + 0.022 + 0.018
    const baseLength =
      fingerName === "thumb"
        ? 0.025 // Thumb proximal is shorter
        : fingerName === "pinky"
          ? 0.022 // Pinky is shorter
          : 0.03; // Other fingers
 
    // Finger thickness: ~1.5-1.8cm diameter (0.75-0.9cm radius)
    const baseRadius =
      fingerName === "pinky"
        ? 0.006 // Pinky is thinner
        : fingerName === "thumb"
          ? 0.009 // Thumb is thicker
          : 0.007;
 
    return {
      proximalLength: baseLength,
      intermediateLength: baseLength * 0.75,
      distalLength: baseLength * 0.55,
      radius: baseRadius,
    };
  }, [fingerName]);
 
  // Calculate curl rotations for each segment
  // Curl value 0-1 maps to rotation angles
  // These factors represent biomechanical constraints of human finger joints
  const PROXIMAL_CURL_FACTOR = 0.5; // Proximal joint bends less (0-90 degrees)
  const INTERMEDIATE_CURL_FACTOR = 0.7; // Middle joint bends moderately (0-126 degrees)
  const DISTAL_CURL_FACTOR = 1.0; // Distal joint bends most (0-180 degrees)
 
  const proximalCurl = curl * PROXIMAL_CURL_FACTOR * Math.PI;
  const intermediateCurl = curl * INTERMEDIATE_CURL_FACTOR * Math.PI;
  const distalCurl = curl * DISTAL_CURL_FACTOR * Math.PI;
 
  // Highlight with color change only (NO glow/emissive)
  const highlightColor = isHighlighted ? KOREAN_COLORS.ACCENT_RED : skinColor;
 
  return (
    <group position={basePosition}>
      {/* Proximal phalanx (knuckle joint) */}
      <FingerSegment
        position={[0, dimensions.proximalLength / 2, 0]}
        rotation={[0, 0, proximalCurl]}
        length={dimensions.proximalLength}
        radius={dimensions.radius}
        color={highlightColor}
      />
 
      {/* Intermediate phalanx (middle joint) - skip for thumb or low detail */}
      {segments >= 4 && fingerName !== "thumb" && (
        <FingerSegment
          position={[
            0,
            dimensions.proximalLength + dimensions.intermediateLength / 2,
            0,
          ]}
          rotation={[0, 0, intermediateCurl]}
          length={dimensions.intermediateLength}
          radius={dimensions.radius * 0.9}
          color={highlightColor}
        />
      )}
 
      {/* Distal phalanx (fingertip) */}
      <FingerSegment
        position={[
          0,
          dimensions.proximalLength +
            (fingerName !== "thumb" && segments >= 4
              ? dimensions.intermediateLength
              : 0) +
            dimensions.distalLength / 2,
          0,
        ]}
        rotation={[0, 0, distalCurl]}
        length={dimensions.distalLength}
        radius={dimensions.radius * 0.7}
        color={highlightColor}
      />
    </group>
  );
};
 
/**
 * Hand3D Component
 *
 * Complete hand with palm and 5 fingers, supporting Korean martial arts
 * hand poses with LOD optimization for performance.
 *
 * @example
 * ```tsx
 * <Hand3D
 *   side="right"
 *   pose={HandPoseType.FIST}
 *   fingerCurl={{
 *     thumb: 0.8,
 *     index: 1.0,
 *     middle: 1.0,
 *     ring: 1.0,
 *     pinky: 1.0,
 *   }}
 *   distanceFromCamera={3}
 *   wristRotation={new THREE.Euler(0, 0, 0)}
 *   isHighlighted={false}
 *   highlightMode="knuckles"
 * />
 * ```
 *
 * @korean 손3D컴포넌트
 */
export const Hand3D: React.FC<Hand3DProps> = ({
  side,
  // pose, // TODO: Reserved for future pose-specific hand adjustments (e.g., different palm sizes per pose)
  fingerCurl,
  distanceFromCamera,
  wristRotation,
  isHighlighted = false,
  highlightMode = null,
  skinColor = 0xffdbac,
  scale = 1.0,
}) => {
  // Determine LOD based on distance
  const lodConfig = useMemo(
    () => getLODConfig(distanceFromCamera),
    [distanceFromCamera],
  );
 
  // Hand orientation
  const sideMultiplier = side === "left" ? -1 : 1;
 
  // Palm dimensions (realistic for ~180cm person)
  // Palm width: ~8-9cm, Palm length (metacarpal area): ~9-10cm
  // Total hand length including palm and fingers: ~18-19cm
  // These dimensions are in METERS for Three.js
  const palmWidth = 0.085 * scale; // 8.5cm palm width
  const palmLength = 0.095 * scale; // 9.5cm palm/metacarpal length
  const palmThickness = 0.025 * scale; // 2.5cm palm thickness
 
  // Determine which parts to highlight
  const highlightKnuckles = highlightMode === "knuckles";
  const highlightPalm = highlightMode === "palm";
  const highlightKnifeEdge = highlightMode === "knife_edge";
  const highlightFingertips = highlightMode === "fingertips";
 
  // Palm color (highlight with brighter color, NO emissive/glow)
  const palmColor =
    isHighlighted && highlightPalm ? KOREAN_COLORS.ACCENT_GOLD : skinColor;
 
  return (
    <group
      rotation={[wristRotation.x, wristRotation.y, wristRotation.z]}
      name={`hand-3d-${side}`}
    >
      {/* Wrist connector - smooth sphere bridging forearm to palm */}
      <mesh
        position={[0, -palmLength * 0.45, 0]}
        castShadow
        receiveShadow
        name={`hand-wrist-bridge-${side}`}
      >
        <sphereGeometry args={[palmWidth * 0.35, 8, 8]} />
        <meshPhysicalMaterial
          color={skinColor}
          metalness={0}
          roughness={0.6}
          clearcoat={0.3}
          clearcoatRoughness={0.5}
          transmission={0}
          thickness={0.1}
          ior={1.4}
          sheen={0.1}
          sheenRoughness={0.8}
          emissive={new THREE.Color(0xff6040)}
          emissiveIntensity={0.02}
        />
      </mesh>
 
      {/* Palm */}
      <mesh castShadow receiveShadow name={`hand-palm-${side}`}>
        <boxGeometry args={[palmWidth, palmLength, palmThickness]} />
        <meshPhysicalMaterial
          color={palmColor}
          metalness={0}
          roughness={0.6}
          clearcoat={0.3}
          clearcoatRoughness={0.5}
          // PBR skin properties
          transmission={0}
          thickness={0.1}
          ior={1.4} // Index of refraction for skin
          sheen={0.1} // Subtle skin sheen
          sheenRoughness={0.8}
          // Subtle emissive for alive appearance
          emissive={new THREE.Color(0xff6040)}
          emissiveIntensity={0.02}
        />
      </mesh>
 
      {/* Knife edge highlight (pinky side of hand) - emissive highlight for visibility */}
      {isHighlighted && highlightKnifeEdge && (
        <mesh
          position={[(-palmWidth / 2) * sideMultiplier, 0, 0]}
          castShadow
          receiveShadow
          name={`hand-knife-edge-${side}`}
        >
          <boxGeometry args={[0.005, palmLength, palmThickness]} />
          <meshPhysicalMaterial
            color={KOREAN_COLORS.ACCENT_GOLD}
            metalness={0.8}
            roughness={0.2}
            clearcoat={0.8}
            clearcoatRoughness={0.1}
            // High emissive for striking surface visibility
            emissive={KOREAN_COLORS.ACCENT_GOLD}
            emissiveIntensity={2.0}
            transmission={0}
            thickness={0.05}
          />
        </mesh>
      )}
 
      {/* Render fingers based on LOD */}
      {lodConfig.renderFingers && (
        <>
          {/* Thumb - offset toward palm center and forward */}
          <Finger
            fingerName="thumb"
            basePosition={[
              0.015 * sideMultiplier * scale,
              palmLength / 2,
              palmThickness / 2,
            ]}
            curl={fingerCurl.thumb}
            segments={3} // Thumb has no intermediate phalanx
            isHighlighted={isHighlighted && highlightFingertips}
            skinColor={skinColor}
          />
 
          {/* Index finger */}
          <Finger
            fingerName="index"
            basePosition={[0.015 * sideMultiplier * scale, palmLength / 2, 0]}
            curl={fingerCurl.index}
            segments={lodConfig.fingerSegments}
            isHighlighted={
              isHighlighted && (highlightFingertips || highlightKnuckles)
            }
            skinColor={skinColor}
          />
 
          {/* Middle finger */}
          <Finger
            fingerName="middle"
            basePosition={[0.005 * sideMultiplier * scale, palmLength / 2, 0]}
            curl={fingerCurl.middle}
            segments={lodConfig.fingerSegments}
            isHighlighted={
              isHighlighted && (highlightFingertips || highlightKnuckles)
            }
            skinColor={skinColor}
          />
 
          {/* Ring finger */}
          <Finger
            fingerName="ring"
            basePosition={[-0.005 * sideMultiplier * scale, palmLength / 2, 0]}
            curl={fingerCurl.ring}
            segments={lodConfig.fingerSegments}
            isHighlighted={
              isHighlighted && (highlightFingertips || highlightKnuckles)
            }
            skinColor={skinColor}
          />
 
          {/* Pinky finger */}
          <Finger
            fingerName="pinky"
            basePosition={[-0.015 * sideMultiplier * scale, palmLength / 2, 0]}
            curl={fingerCurl.pinky}
            segments={lodConfig.fingerSegments}
            isHighlighted={
              isHighlighted && (highlightFingertips || highlightKnuckles)
            }
            skinColor={skinColor}
          />
        </>
      )}
 
      {/* Low detail: just palm, no fingers */}
      {!lodConfig.renderFingers && (
        <mesh
          position={[0, palmLength / 2, 0]}
          castShadow
          receiveShadow
          name={`hand-simple-${side}`}
        >
          <capsuleGeometry args={[palmWidth / 2, palmLength * 0.3, 4, 8]} />
          <meshStandardMaterial
            color={skinColor}
            metalness={0.1}
            roughness={0.8}
          />
        </mesh>
      )}
    </group>
  );
};
 
export default Hand3D;