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

99.13% Statements 115/116
85.96% Branches 49/57
100% Functions 23/23
99.12% Lines 113/114

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 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628                                                                                                                                                                                                                                12x       7392x 7392x     7392x 7392x     7392x 7392x     7392x                 12x     6160x   2016x     1092x     2968x   84x                 12x 6160x           12x                       7392x 7392x   7392x           7392x 7392x   7392x 29736x               29736x     7392x           12x                       29736x           29736x 29736x   29736x     7392x 264x   264x   264x       264x         264x                                     7392x     528x 528x         528x 528x                                   7392x     528x 528x         528x 528x                                 7392x       7392x     528x 528x           528x 528x                                     7392x     528x 528x           528x 528x                                 7392x     5320x   190x 190x 190x         190x                                 5320x     1932x 69x   69x   69x       69x         69x                                 1932x     29736x                     12x           7392x   7392x                       7392x 7392x         7392x 3024x                       7392x   3024x   3024x 12152x 6160x 6160x 6160x             3024x       7392x 3024x 6160x                                   7392x 7392x   2635x 4212x   2635x 2635x       2635x 2635x   2635x     2635x                                                   2635x         7392x 7392x 7392x         7392x 7392x 7392x 2635x         7392x 4826x     2566x     2635x                                        
/**
 * Bone-attached clothing system for realistic clothing movement with skeleton
 *
 * **Enhanced Features (v0.6.23+)**:
 * - **Subsurface Scattering**: Realistic fabric translucency with light transmission
 * - **Physical Materials**: Advanced PBR materials with clearcoat and reflectivity
 * - **Body Thickness Scaling**: Accurate clothing sizing based on muscle/fat mass
 * - **Archetype Styling**: Unique clothing sets for all 5 player archetypes
 *
 * Clothing is rendered as children of their parent bones, inheriting bone
 * transformations automatically for proper movement during animation.
 * This mirrors the BoneMuscles approach for consistent rendering.
 *
 * **Visual Quality**:
 * - Transmission: 0.05 (minimal light passing through fabric)
 * - Thickness: 0.2 (thin fabric simulation)
 * - IOR: 1.4 (realistic fabric index of refraction)
 * - Clearcoat: 0.3 (surface depth and sheen)
 * - Double-sided rendering for cloth folding
 *
 * **Performance**:
 * - Geometry disposal on unmount (prevents memory leaks)
 * - Material cleanup system
 * - Optimized attachment calculations with useMemo
 *
 * @module components/three/BoneClothing
 * @category 3D Components
 * @korean 뼈부착의류시스템
 */
 
import React, { useEffect, useMemo } from "react";
import * as THREE from "three";
import {
  BICEP_RADIUS,
  CALF_RADIUS,
  CLOTHING_THICKNESS_FITTED,
  CORE_RADIUS,
  FOREARM_RADIUS,
  PECTORALS_RADIUS,
  QUAD_RADIUS,
  calculateClothingRadius,
} from "../../../../constants/bodyDimensions";
import { getArchetypeClothing } from "../../../../data/archetypeClothing";
import type {
  ClothingItem,
  ClothingMaterial,
} from "../../../../types/clothing";
import type { PlayerArchetype } from "../../../../types/common";
import {
  FABRIC_PRESETS,
  generateFabricTextureSet,
  type FabricTextureSet,
} from "../../../../utils/fabricTextures";
 
/**
 * Clothing attachment configuration for a bone
 *
 * Defines how clothing is positioned relative to its parent bone.
 * Position is in local bone space, so clothing moves with the bone.
 *
 * @korean 의류부착설정
 */
export interface ClothingAttachment {
  /** Geometry for this clothing piece */
  readonly geometry: THREE.BufferGeometry;
  /** Local position offset from bone origin */
  readonly localOffset: THREE.Vector3;
  /** Local rotation relative to bone */
  readonly localRotation: THREE.Euler;
  /** Color of the clothing */
  readonly color: number;
  /** Emissive color for glow effects */
  readonly emissiveColor?: number;
  /** Emissive intensity */
  readonly emissiveIntensity?: number;
  /** Metalness for material */
  readonly metalness?: number;
  /** Roughness for material */
  readonly roughness?: number;
  /** Clothing item ID */
  readonly itemId: string;
}
 
/**
 * Props for BoneClothing component
 */
export interface BoneClothingProps {
  /** Name of the bone this clothing attaches to */
  readonly boneName: string;
  /** Player archetype for clothing style */
  readonly archetype: PlayerArchetype;
  /** Physical attributes for sizing */
  readonly physicalAttributes?: {
    readonly muscleMass: number;
    readonly fatMass: number;
    readonly shoulderWidth: number;
    readonly torsoLength: number;
    readonly armLength: number;
    readonly legLength: number;
  };
}
 
/**
 * Calculate body thickness multiplier based on muscle mass and fat mass
 *
 * Uses linear scaling with reasonable limits to prevent "michelin man" effect.
 * This matches the BodySurface calculation for consistency.
 *
 * @param muscleMass - Muscle mass in kg
 * @param fatMass - Fat mass in kg
 * @returns Body thickness multiplier (0.75 - 1.20)
 */
const calculateBodyThickness = (
  muscleMass: number,
  fatMass: number,
): number => {
  const referenceMuscle = 35; // Reference: athletic build
  const referenceFat = 12; // Reference: low body fat
 
  // Linear scaling with limits (not square root which causes excessive inflation)
  const muscleRatio = muscleMass / referenceMuscle;
  const fatRatio = fatMass / referenceFat;
 
  // Base 0.85, muscle adds up to +0.15, fat adds up to +0.20
  const muscleContribution = (muscleRatio - 1.0) * 0.15;
  const fatContribution = (fatRatio - 1.0) * 0.2;
 
  // Cap at 1.20x maximum to prevent "michelin man" effect
  return Math.max(
    0.75,
    Math.min(1.2, 0.85 + muscleContribution + fatContribution),
  );
};
 
/**
 * Get fabric preset based on clothing material type
 */
const getFabricPreset = (
  material: ClothingMaterial,
): keyof typeof FABRIC_PRESETS => {
  switch (material) {
    case "fabric":
      return "dobok";
    case "tactical":
    case "synthetic":
      return "tactical";
    case "leather":
    case "armored":
      return "leather";
    case "cybernetic":
      return "silk"; // Shiny synthetic look
    default:
      return "dobok";
  }
};
 
/**
 * Convert number color to hex string
 */
const numberToHex = (color: number): string => {
  return `#${color.toString(16).padStart(6, "0")}`;
};
 
/**
 * Get clothing attachments for a specific bone
 */
const getClothingForBone = (
  boneName: string,
  archetype: PlayerArchetype,
  physicalAttributes: {
    muscleMass: number;
    fatMass: number;
    shoulderWidth: number;
    torsoLength: number;
    armLength: number;
    legLength: number;
  },
): ClothingAttachment[] => {
  const clothingSet = getArchetypeClothing(archetype);
  const attachments: ClothingAttachment[] = [];
 
  const bodyThickness = calculateBodyThickness(
    physicalAttributes.muscleMass,
    physicalAttributes.fatMass,
  );
 
  // Scaling factors
  const torsoScale = physicalAttributes.torsoLength / 59;
  const legScale = physicalAttributes.legLength / 96;
 
  for (const item of clothingSet.items) {
    const attachmentsForItem = getAttachmentsForItem(
      item,
      boneName,
      bodyThickness,
      torsoScale,
      legScale,
      physicalAttributes,
    );
    attachments.push(...attachmentsForItem);
  }
 
  return attachments;
};
 
/**
 * Generate clothing attachments for a specific item on a bone
 */
const getAttachmentsForItem = (
  item: ClothingItem,
  boneName: string,
  bodyThickness: number,
  torsoScale: number,
  legScale: number,
  physicalAttributes: {
    shoulderWidth: number;
    armLength: number;
    legLength: number;
  },
): ClothingAttachment[] => {
  const fitScaleMap: Record<string, number> = {
    tight: 1.08,
    fitted: 1.15,
    loose: 1.25,
    oversized: 1.4,
  };
  const fitScale = fitScaleMap[item.fit] ?? 1.15;
  const attachments: ClothingAttachment[] = [];
 
  switch (item.type) {
    case "torso":
      // Main torso on spine_middle - wraps fully around body
      if (boneName === "spine_middle") {
        const height = (59 / 100) * torsoScale * 1.2; // Using base torsoLength
        // Clothing wraps around the torso using CylinderGeometry (full 360°)
        const clothingThickness = CLOTHING_THICKNESS_FITTED * fitScale;
        // Torso radius: average of shoulder width and pectorals depth
        const torsoRadius =
          ((physicalAttributes.shoulderWidth / 100) * 0.5 * bodyThickness +
            PECTORALS_RADIUS * bodyThickness) *
          0.5;
        const clothingRadius = calculateClothingRadius(
          torsoRadius,
          1.0, // bodyThickness already applied above
          clothingThickness,
        );
        attachments.push({
          geometry: new THREE.CylinderGeometry(
            clothingRadius * 0.95, // Slightly narrower at top (chest taper)
            clothingRadius * 1.05, // Slightly wider at bottom (waist)
            height,
            16, // Smooth cylinder
          ),
          localOffset: new THREE.Vector3(0, 0, 0), // Centered on bone
          localRotation: new THREE.Euler(0, 0, 0),
          color: item.colorPrimary,
          emissiveColor: item.colorEmissive,
          emissiveIntensity: item.emissiveIntensity,
          metalness: item.metalness,
          roughness: item.roughness,
          itemId: item.id,
        });
      }
 
      // Sleeves
      if (boneName === "upper_arm_L" || boneName === "upper_arm_R") {
        // Uses centralized BICEP_RADIUS from bodyDimensions
        // Clothing wraps around muscle, so offset outward
        const clothingThickness = CLOTHING_THICKNESS_FITTED * fitScale;
        const clothingRadius = calculateClothingRadius(
          BICEP_RADIUS,
          bodyThickness,
          clothingThickness,
        );
        const upperArmLength = (physicalAttributes.armLength / 100) * 0.45;
        attachments.push({
          geometry: new THREE.CylinderGeometry(
            clothingRadius * 1.05, // Slightly larger at top
            clothingRadius * 0.95, // Tapers slightly
            upperArmLength,
            12,
          ),
          localOffset: new THREE.Vector3(0, -upperArmLength * 0.4, 0),
          localRotation: new THREE.Euler(0, 0, 0),
          color: item.colorPrimary,
          emissiveColor: item.colorEmissive,
          emissiveIntensity: item.emissiveIntensity,
          metalness: item.metalness,
          roughness: item.roughness,
          itemId: `${item.id}-sleeve-upper-${boneName}`,
        });
      }
 
      if (boneName === "forearm_L" || boneName === "forearm_R") {
        // Uses centralized FOREARM_RADIUS from bodyDimensions
        // Clothing must be OUTSIDE, so use larger radius
        const clothingThickness = CLOTHING_THICKNESS_FITTED * fitScale * 0.8;
        const clothingRadius = calculateClothingRadius(
          FOREARM_RADIUS,
          bodyThickness,
          clothingThickness,
        );
        const forearmLength = (physicalAttributes.armLength / 100) * 0.4;
        attachments.push({
          geometry: new THREE.CylinderGeometry(
            clothingRadius * 0.98, // Slightly smaller at top
            clothingRadius * 0.85, // Tapers toward wrist
            forearmLength,
            12,
          ),
          localOffset: new THREE.Vector3(0, -forearmLength * 0.4, 0),
          localRotation: new THREE.Euler(0, 0, 0),
          color: item.colorPrimary,
          emissiveColor: item.colorEmissive,
          emissiveIntensity: item.emissiveIntensity,
          metalness: item.metalness,
          roughness: item.roughness,
          itemId: `${item.id}-sleeve-forearm-${boneName}`,
        });
      }
      break;
 
    case "pants":
      // Thigh segments
      if (boneName === "thigh_L" || boneName === "thigh_R") {
        // Uses centralized QUAD_RADIUS from bodyDimensions
        // Clothing wraps around muscle, so offset outward
        const clothingThickness = CLOTHING_THICKNESS_FITTED * fitScale * 1.3;
        const clothingRadius = calculateClothingRadius(
          QUAD_RADIUS,
          bodyThickness,
          clothingThickness,
        );
        const thighLength =
          (physicalAttributes.legLength / 100) * legScale * 0.45;
        attachments.push({
          geometry: new THREE.CylinderGeometry(
            clothingRadius * 1.08, // Larger at hip
            clothingRadius * 0.92, // Tapers toward knee
            thighLength,
            16,
          ),
          localOffset: new THREE.Vector3(0, -thighLength * 0.4, 0),
          localRotation: new THREE.Euler(0, 0, 0),
          color: item.colorPrimary,
          emissiveColor: item.colorEmissive,
          emissiveIntensity: item.emissiveIntensity,
          metalness: item.metalness,
          roughness: item.roughness,
          itemId: `${item.id}-thigh-${boneName}`,
        });
      }
 
      // Shin segments
      if (boneName === "shin_L" || boneName === "shin_R") {
        // Uses centralized CALF_RADIUS from bodyDimensions
        // Clothing must be OUTSIDE, so use larger radius
        const clothingThickness = CLOTHING_THICKNESS_FITTED * fitScale;
        const clothingRadius = calculateClothingRadius(
          CALF_RADIUS,
          bodyThickness,
          clothingThickness,
        );
        const shinLength =
          (physicalAttributes.legLength / 100) * legScale * 0.42;
        attachments.push({
          geometry: new THREE.CylinderGeometry(
            clothingRadius * 0.95, // Larger at knee
            clothingRadius * 0.75, // Tapers toward ankle
            shinLength,
            16,
          ),
          localOffset: new THREE.Vector3(0, -shinLength * 0.4, 0),
          localRotation: new THREE.Euler(0, 0, 0),
          color: item.colorPrimary,
          emissiveColor: item.colorEmissive,
          emissiveIntensity: item.emissiveIntensity,
          metalness: item.metalness,
          roughness: item.roughness,
          itemId: `${item.id}-shin-${boneName}`,
        });
      }
      break;
 
    case "belt":
      if (boneName === "pelvis") {
        // Belt wraps fully around waist using CylinderGeometry
        const clothingThickness = CLOTHING_THICKNESS_FITTED * fitScale;
        const waistRadius = CORE_RADIUS * bodyThickness;
        const beltRadius = calculateClothingRadius(
          waistRadius,
          1.0, // bodyThickness already applied
          clothingThickness + 0.005, // Extra so belt sits outside clothing
        );
        attachments.push({
          geometry: new THREE.CylinderGeometry(
            beltRadius,
            beltRadius,
            0.06, // Belt height
            16, // Smooth cylinder
          ),
          localOffset: new THREE.Vector3(0, 0, 0), // Centered on bone
          localRotation: new THREE.Euler(0, 0, 0),
          color: item.colorPrimary,
          emissiveColor: item.colorEmissive,
          emissiveIntensity: item.emissiveIntensity,
          metalness: item.metalness,
          roughness: item.roughness,
          itemId: item.id,
        });
      }
      break;
 
    case "vest":
      if (boneName === "spine_middle") {
        const height = (59 / 100) * 0.75 * torsoScale;
        // Vest wraps fully around torso using CylinderGeometry
        const clothingThickness = CLOTHING_THICKNESS_FITTED * fitScale;
        // Vest sits slightly outside the torso clothing layer
        const torsoRadius =
          ((physicalAttributes.shoulderWidth / 100) * 0.5 * bodyThickness +
            (PECTORALS_RADIUS + 0.01) * bodyThickness) *
          0.5;
        const vestRadius = calculateClothingRadius(
          torsoRadius,
          1.0, // bodyThickness already applied
          clothingThickness + 0.008, // Extra gap for layering over shirt
        );
        attachments.push({
          geometry: new THREE.CylinderGeometry(
            vestRadius * 0.97, // Slightly narrower at top
            vestRadius * 1.03, // Slightly wider at bottom
            height,
            16, // Smooth cylinder
          ),
          localOffset: new THREE.Vector3(0, 0, 0), // Centered on bone
          localRotation: new THREE.Euler(0, 0, 0),
          color: item.colorPrimary,
          emissiveColor: item.colorEmissive,
          emissiveIntensity: item.emissiveIntensity,
          metalness: item.metalness,
          roughness: item.roughness,
          itemId: item.id,
        });
      }
      break;
  }
 
  return attachments;
};
 
/**
 * BoneClothing Component
 *
 * Renders clothing attached to a specific bone.
 * Clothing inherits bone transformations automatically through the scene graph.
 *
 * @korean 뼈부착의류
 */
export const BoneClothing: React.FC<BoneClothingProps> = ({
  boneName,
  archetype,
  physicalAttributes,
}) => {
  // Default physical attributes if not provided - memoized to prevent new object on every render
  const attrs = useMemo(
    () =>
      physicalAttributes ?? {
        muscleMass: 35,
        fatMass: 12,
        shoulderWidth: 45,
        torsoLength: 59,
        armLength: 62,
        legLength: 96,
      },
    [physicalAttributes],
  );
 
  // Get clothing attachments for this bone
  const attachments = useMemo(
    () => getClothingForBone(boneName, archetype, attrs),
    [boneName, archetype, attrs],
  );
 
  // Get clothing set for fabric texture generation
  const clothingSet = useMemo(
    () => getArchetypeClothing(archetype),
    [archetype],
  );
 
  /**
   * Generate fabric textures for realistic dobok (도복) rendering
   *
   * Creates procedural weave patterns, normal maps, and roughness maps
   * for enhanced cloth realism without external image assets.
   *
   * @korean 직물텍스처생성
   */
  const fabricTextures = useMemo(() => {
    // Generate textures for each unique clothing item
    const textureMap = new Map<string, FabricTextureSet>();
 
    for (const item of clothingSet.items) {
      if (!textureMap.has(item.material)) {
        const preset = getFabricPreset(item.material);
        const colorHex = numberToHex(item.colorPrimary);
        textureMap.set(
          item.material,
          generateFabricTextureSet(colorHex, preset),
        );
      }
    }
 
    return textureMap;
  }, [clothingSet]);
 
  // Cleanup fabric textures on unmount
  useEffect(() => {
    return () => {
      fabricTextures.forEach((textureSet) => textureSet.dispose());
    };
  }, [fabricTextures]);
 
  /**
   * Create materials with advanced physical properties for realistic cloth rendering
   *
   * Enhanced with:
   * - **Fabric textures**: Procedural weave patterns for dobok authenticity
   * - **Normal maps**: Surface detail for thread texture visibility
   * - **Roughness maps**: Realistic light scattering on fabric surface
   * - Subsurface scattering: Light transmission through fabric for realism
   * - Clearcoat: Surface depth and sheen for material quality
   * - Double-sided rendering: Proper display when cloth folds
   * - Physical properties: IOR, reflectivity for authentic appearance
   *
   * @korean 향상된물리재료생성
   */
  const materials = useMemo(() => {
    return attachments.map((attachment) => {
      // Find the clothing item for this attachment to get its material type
      const clothingItem = clothingSet.items.find((item) =>
        attachment.itemId.startsWith(item.id),
      );
      const materialType = clothingItem?.material ?? "fabric";
      const textureSet = fabricTextures.get(materialType);
 
      // Create normal scale safely (Vector2 may not be available in test environments)
      let normalScale: THREE.Vector2 | undefined;
      try {
        normalScale = new THREE.Vector2(0.3, 0.3);
      } catch {
        normalScale = undefined;
      }
 
      const mat = new THREE.MeshPhysicalMaterial({
        color: attachment.color,
        // Apply fabric texture maps for realistic dobok appearance
        map: textureSet?.colorMap ?? null,
        normalMap: textureSet?.normalMap ?? null,
        normalScale, // Subtle normal effect
        roughnessMap: textureSet?.roughnessMap ?? null,
        emissive: attachment.emissiveColor ?? 0x000000,
        emissiveIntensity: attachment.emissiveIntensity ?? 0,
        metalness: attachment.metalness ?? 0.1, // Lower metalness for fabric
        roughness: attachment.roughness ?? 0.8, // Higher roughness for cloth
        // Enhanced cloth realism with clearcoat for depth
        clearcoat: 0.2,
        clearcoatRoughness: 0.6,
        // Subsurface scattering for realistic fabric translucency
        // Subtle effect for cloth materials (not skin)
        transmission: 0.03, // Minimal light transmission through fabric
        thickness: 0.15, // Thin fabric thickness
        ior: 1.4, // Index of refraction for fabric (lower than glass)
        // Enable proper reflections
        reflectivity: 0.2,
        // Double-sided rendering for cloth that may fold
        side: THREE.DoubleSide,
        // Improved shading for folds
        flatShading: false,
      });
      return mat;
    });
  }, [attachments, clothingSet, fabricTextures]);
 
  // Cleanup materials on unmount
  useEffect(() => {
    return () => {
      materials.forEach((mat) => mat.dispose());
    };
  }, [materials]);
 
  // Cleanup geometries on unmount
  useEffect(() => {
    return () => {
      attachments.forEach((attachment) => {
        attachment.geometry.dispose();
      });
    };
  }, [attachments]);
 
  if (attachments.length === 0) {
    return null;
  }
 
  return (
    <>
      {attachments.map((attachment, index) => (
        <mesh
          key={attachment.itemId}
          geometry={attachment.geometry}
          material={materials[index]}
          position={attachment.localOffset.toArray()}
          rotation={[
            attachment.localRotation.x,
            attachment.localRotation.y,
            attachment.localRotation.z,
          ]}
          castShadow
          receiveShadow
          name={`clothing-${attachment.itemId}`}
        />
      ))}
    </>
  );
};
 
export default BoneClothing;