All files / components/screens/combat/components/effects InternalDamage3D.tsx

17.88% Statements 27/151
26.92% Branches 7/26
52.94% Functions 9/17
17.73% Lines 25/141

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                                                                                                                                2x                                                                             2x           60x                       60x 30x     30x     30x     60x                                                                                                                           60x                                                                                                         60x 30x   30x 30x   30x                         30x 30x                         30x       60x                 60x 60x     60x 30x 30x                           60x                                                                                                                                                         60x                      
/**
 * InternalDamage3D - Deep red organ pulses for Korean martial arts organ strikes
 *
 * Priority #4: Internal Damage Visualization
 * - Deep red organ pulses (liver, kidney, spleen, stomach, heart)
 * - Tissue deformation ripples
 * - Penetration depth visualization
 * - Critical organ damage feedback
 *
 * PERFORMANCE OPTIMIZATION (Object Pooling):
 * - Reduced allocations from ~120+ per effect to 2 pooled objects
 * - Pooling strategy:
 *   1. Temporary Color objects for particle initialization use pool
 *   2. Colors are copied to Float32Array (no ownership needed)
 *   3. All pooled objects released after particle system creation
 * - Estimated reduction:
 *   - Pulse particles: 60 Color allocations → 1 pooled object
 *   - Ripple particles: 30 Color allocations → 1 pooled object
 *   - Total: ~90 Color allocations per effect → 2 pooled objects
 *
 * Korean martial arts context (내장 공격 - Internal organ strikes):
 * - 간격 (Liver strike) - Right side body blow
 * - 신장격 (Kidney strike) - Lower back strike
 * - 비장격 (Spleen strike) - Left side body blow
 * - 명치격 (Solar plexus) - Stomach strike
 * - 심장격 (Heart strike) - Chest strike (critical)
 */
 
import React, { useEffect, useMemo, useRef } from 'react';
import { useFrame } from '@react-three/fiber';
import * as THREE from 'three';
import { ThreeObjectPools } from '../../../../../utils/threeObjectPool';
 
/**
 * Organ types for Korean martial arts internal strikes
 */
export type OrganType = 'liver' | 'kidney' | 'spleen' | 'stomach' | 'heart';
 
/**
 * Penetration depth levels for organ damage
 */
export type PenetrationDepth = 'surface' | 'shallow' | 'deep' | 'critical';
 
/**
 * Individual internal damage effect
 */
export interface InternalDamageEffect {
  readonly id: string;
  readonly position: [number, number, number];
  readonly organType: OrganType;
  readonly penetrationDepth: PenetrationDepth;
  readonly startTime: number;
}
 
/**
 * Props for InternalDamage3D component
 */
export interface InternalDamage3DProps {
  readonly effects: readonly InternalDamageEffect[];
  readonly enabled?: boolean;
  readonly isMobile?: boolean;
  readonly onEffectComplete?: (id: string) => void;
}
 
const INTERNAL_DAMAGE_CONSTANTS = {
  PULSE_SPEED: 2.5, // m/s expansion rate
  
  PULSE_LIFETIME: 1.5, // seconds for pulse to complete
  RIPPLE_LIFETIME: 0.8, // seconds for tissue ripple
  
  MAX_RADIUS: {
    surface: 0.4,
    shallow: 0.7,
    deep: 1.0,
    critical: 1.2,
  },
  
  INTENSITY: {
    surface: 0.5,
    shallow: 0.8,
    deep: 1.2,
    critical: 1.5,
  },
  
  PULSE_PARTICLES: 60,
  RIPPLE_PARTICLES: 30,
  
  ORGAN_COLOR: 0x8b0000, // Dark red for organs
  RIPPLE_COLOR: 0xdc143c, // Crimson for tissue ripples
  
  EMISSIVE_INTENSITY: 0.8,
} as const;
 
/**
 * InternalDamage3D - Visualizes internal organ damage with deep red pulses
 *
 * Features:
 * - Expanding sphere pulses from organ impacts
 * - Tissue deformation ripples
 * - Penetration depth-based sizing
 * - Korean martial arts organ strike feedback
 * - Mobile optimization (50% particles)
 */
export const InternalDamage3D: React.FC<InternalDamage3DProps> = ({
  effects,
  enabled = true,
  isMobile = false,
  onEffectComplete,
}) => {
  const [effectInstances, setEffectInstances] = React.useState<
    Map<
      string,
      {
        pulseParticles: THREE.Points;
        rippleParticles: THREE.Points;
        startTime: number;
        effect: InternalDamageEffect;
      }
    >
  >(new Map());
 
  const particleCounts = useMemo(() => {
    const pulseCount = isMobile
      ? Math.floor(INTERNAL_DAMAGE_CONSTANTS.PULSE_PARTICLES * 0.5)
      : INTERNAL_DAMAGE_CONSTANTS.PULSE_PARTICLES;
    const rippleCount = isMobile
      ? Math.floor(INTERNAL_DAMAGE_CONSTANTS.RIPPLE_PARTICLES * 0.5)
      : INTERNAL_DAMAGE_CONSTANTS.RIPPLE_PARTICLES;
    return { pulseCount, rippleCount };
  }, [isMobile]);
 
  const createPulseParticles = useMemo(
    () => (effect: InternalDamageEffect) => {
      const { pulseCount } = particleCounts;
      const geometry = new THREE.BufferGeometry();
      const positions = new Float32Array(pulseCount * 3);
      const colors = new Float32Array(pulseCount * 3);
      const sizes = new Float32Array(pulseCount);
 
      const tempColor = ThreeObjectPools.color.acquire();
 
      try {
        tempColor.set(INTERNAL_DAMAGE_CONSTANTS.ORGAN_COLOR);
 
        for (let i = 0; i < pulseCount; i++) {
 
          positions[i * 3] = 0;
          positions[i * 3 + 1] = 0;
          positions[i * 3 + 2] = 0;
 
          colors[i * 3] = tempColor.r;
          colors[i * 3 + 1] = tempColor.g;
          colors[i * 3 + 2] = tempColor.b;
 
          const baseSize = 0.03;
          const depthMultiplier =
            INTERNAL_DAMAGE_CONSTANTS.INTENSITY[effect.penetrationDepth];
          sizes[i] = baseSize * depthMultiplier;
        }
      } finally {
        ThreeObjectPools.color.release(tempColor);
      }
 
      geometry.setAttribute('position', new THREE.BufferAttribute(positions, 3));
      geometry.setAttribute('color', new THREE.BufferAttribute(colors, 3));
      geometry.setAttribute('size', new THREE.BufferAttribute(sizes, 1));
 
      const material = new THREE.PointsMaterial({
        size: 0.05,
        vertexColors: true,
        transparent: true,
        opacity: 1.0,
        blending: THREE.AdditiveBlending,
        depthWrite: false,
        sizeAttenuation: true,
      });
 
      const points = new THREE.Points(geometry, material);
      points.position.set(...effect.position);
 
      (geometry as THREE.BufferGeometry & { sphereData: Record<string, number | Float32Array> }).sphereData = { positions: positions.slice() };
      for (let i = 0; i < pulseCount; i++) {
        const phi = Math.acos(1 - 2 * (i + 0.5) / pulseCount);
        const theta = Math.PI * (1 + Math.sqrt(5)) * i;
        (geometry as THREE.BufferGeometry & { sphereData: Record<string, number | Float32Array> }).sphereData[`phi_${i}`] = phi;
        (geometry as THREE.BufferGeometry & { sphereData: Record<string, number | Float32Array> }).sphereData[`theta_${i}`] = theta;
      }
 
      return points;
    },
    [particleCounts]
  );
 
  const createRippleParticles = useMemo(
    () => (effect: InternalDamageEffect) => {
      const { rippleCount } = particleCounts;
      const geometry = new THREE.BufferGeometry();
      const positions = new Float32Array(rippleCount * 3);
      const colors = new Float32Array(rippleCount * 3);
      const sizes = new Float32Array(rippleCount);
 
      const tempColor = ThreeObjectPools.color.acquire();
 
      try {
        tempColor.set(INTERNAL_DAMAGE_CONSTANTS.RIPPLE_COLOR);
 
        for (let i = 0; i < rippleCount; i++) {
          const angle = (i / rippleCount) * Math.PI * 2;
          positions[i * 3] = 0;
          positions[i * 3 + 1] = 0;
          positions[i * 3 + 2] = 0;
 
          colors[i * 3] = tempColor.r;
          colors[i * 3 + 1] = tempColor.g;
          colors[i * 3 + 2] = tempColor.b;
 
          sizes[i] = 0.02;
 
          (geometry as THREE.BufferGeometry & { [key: string]: number })[`angle_${i}`] = angle;
        }
      } finally {
        ThreeObjectPools.color.release(tempColor);
      }
 
      geometry.setAttribute('position', new THREE.BufferAttribute(positions, 3));
      geometry.setAttribute('color', new THREE.BufferAttribute(colors, 3));
      geometry.setAttribute('size', new THREE.BufferAttribute(sizes, 1));
 
      const material = new THREE.PointsMaterial({
        size: 0.03,
        vertexColors: true,
        transparent: true,
        opacity: 1.0,
        blending: THREE.NormalBlending,
        depthWrite: false,
        sizeAttenuation: true,
      });
 
      const points = new THREE.Points(geometry, material);
      points.position.set(...effect.position);
 
      return points;
    },
    [particleCounts]
  );
 
  useEffect(() => {
    Iif (!enabled) return;
 
    setEffectInstances((prev) => {
      const updated = new Map(prev);
 
      effects.forEach((effect) => {
        if (!updated.has(effect.id)) {
          const pulseParticles = createPulseParticles(effect);
          const rippleParticles = createRippleParticles(effect);
          updated.set(effect.id, {
            pulseParticles,
            rippleParticles,
            startTime: effect.startTime,
            effect,
          });
        }
      });
 
      const currentIds = new Set(effects.map((e) => e.id));
      Array.from(updated.keys()).forEach((id) => {
        if (!currentIds.has(id)) {
          const instance = updated.get(id);
          if (instance) {
            instance.pulseParticles.geometry.dispose();
            (instance.pulseParticles.material as THREE.Material).dispose();
            instance.rippleParticles.geometry.dispose();
            (instance.rippleParticles.material as THREE.Material).dispose();
          }
          updated.delete(id);
        }
      });
 
      return updated;
    });
  }, [effects, enabled, createPulseParticles, createRippleParticles]);
 
  const effectInstancesRef = useRef<Map<
    string,
    {
      pulseParticles: THREE.Points;
      rippleParticles: THREE.Points;
      startTime: number;
      effect: InternalDamageEffect;
    }
  >>(effectInstances);
  useEffect(() => {
    effectInstancesRef.current = effectInstances;
  }, [effectInstances]);
 
  useEffect(() => {
    return () => {
      effectInstancesRef.current.forEach((instance: {
        pulseParticles: THREE.Points;
        rippleParticles: THREE.Points;
        startTime: number;
        effect: InternalDamageEffect;
      }) => {
        instance.pulseParticles.geometry.dispose();
        (instance.pulseParticles.material as THREE.Material).dispose();
        instance.rippleParticles.geometry.dispose();
        (instance.rippleParticles.material as THREE.Material).dispose();
      });
    };
  }, []); // Empty deps - cleanup on unmount only
 
  useFrame(() => {
    if (!enabled || effectInstances.size === 0) return;
 
    const now = Date.now();
    const completedIds: string[] = [];
 
    effectInstances.forEach((instance, id) => {
      const elapsed = (now - instance.startTime) / 1000;
      const { effect } = instance;
 
      const pulseProgress = Math.min(
        elapsed / INTERNAL_DAMAGE_CONSTANTS.PULSE_LIFETIME,
        1.0
      );
      if (pulseProgress < 1.0) {
      const pulseGeometry = instance.pulseParticles.geometry;
        const pulsePositions = pulseGeometry.attributes.position
          .array as Float32Array;
        const maxRadius =
          INTERNAL_DAMAGE_CONSTANTS.MAX_RADIUS[effect.penetrationDepth];
 
        const { pulseCount } = particleCounts;
        const sphereData = (pulseGeometry as THREE.BufferGeometry & { sphereData: Record<string, number | Float32Array> }).sphereData;
        for (let i = 0; i < pulseCount; i++) {
          const phi = sphereData[`phi_${i}`] as number;
          const theta = sphereData[`theta_${i}`] as number;
          const radius = maxRadius * pulseProgress;
 
          pulsePositions[i * 3] = radius * Math.sin(phi) * Math.cos(theta);
          pulsePositions[i * 3 + 1] = radius * Math.sin(phi) * Math.sin(theta);
          pulsePositions[i * 3 + 2] = radius * Math.cos(phi);
        }
 
        pulseGeometry.attributes.position.needsUpdate = true;
 
        const material = instance.pulseParticles.material as THREE.PointsMaterial;
        material.opacity = 1.0 - pulseProgress * 0.7;
      }
 
      const rippleProgress = Math.min(
        elapsed / INTERNAL_DAMAGE_CONSTANTS.RIPPLE_LIFETIME,
        1.0
      );
      if (rippleProgress < 1.0) {
        const rippleGeometry = instance.rippleParticles.geometry;
        const ripplePositions = rippleGeometry.attributes.position
          .array as Float32Array;
 
        const { rippleCount } = particleCounts;
        const rippleRadius = 0.6 * rippleProgress;
        for (let i = 0; i < rippleCount; i++) {
          const angle = (rippleGeometry as THREE.BufferGeometry & { [key: string]: number })[`angle_${i}`];
          ripplePositions[i * 3] = rippleRadius * Math.cos(angle);
          ripplePositions[i * 3 + 1] = 0;
          ripplePositions[i * 3 + 2] = rippleRadius * Math.sin(angle);
        }
 
        rippleGeometry.attributes.position.needsUpdate = true;
 
        const material = instance.rippleParticles
          .material as THREE.PointsMaterial;
        material.opacity = 1.0 - rippleProgress;
      }
 
      if (
        elapsed >= INTERNAL_DAMAGE_CONSTANTS.PULSE_LIFETIME &&
        elapsed >= INTERNAL_DAMAGE_CONSTANTS.RIPPLE_LIFETIME
      ) {
        completedIds.push(id);
      }
    });
 
    completedIds.forEach((id) => {
      onEffectComplete?.(id);
    });
  });
 
  return (
    <>
      {Array.from(effectInstances.values()).map((instance) => (
        <React.Fragment key={instance.effect.id}>
          <primitive object={instance.pulseParticles} />
          <primitive object={instance.rippleParticles} />
        </React.Fragment>
      ))}
    </>
  );
};