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

15.59% Statements 17/109
12.5% Branches 3/24
41.66% Functions 5/12
14.7% Lines 15/102

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                                                                                                                          2x                                                                                                                             2x             60x                           60x                 60x                                                                                                                                                                                                     60x 30x   30x 30x   30x                         30x 30x                     30x         60x                                                                                                                                     60x                
/**
 * BloodViscosity3D - Enhanced blood droplets with thicker physics for brutal combat realism
 *
 * Priority #5: Enhanced Blood Viscosity
 * - Thicker droplets with slower fall rate
 * - Variable splatter sizes (gouts vs mist)
 * - Cling/drip physics (stick to surfaces)
 * - Enhanced viscosity simulation
 *
 * PERFORMANCE OPTIMIZATION (Object Pooling):
 * - Reduced allocations from ~85+ per effect to ~4 pooled objects
 * - Pooling strategy:
 *   1. Temporary calculation objects (direction, color, velocity) use pool
 *   2. Owned objects (particle velocities) are cloned from pooled objects
 *   3. All pooled objects released after particle creation
 * - Estimated reduction: 
 *   - thin: 50 Color + 50 Vector3 = 100 allocations → 4 pooled objects
 *   - medium: 80 Color + 80 Vector3 = 160 allocations → 4 pooled objects
 *   - thick: 120 Color + 120 Vector3 = 240 allocations → 4 pooled objects
 *   - gout: 200 Color + 200 Vector3 = 400 allocations → 4 pooled objects
 *
 * Korean martial arts context:
 * - 절단격 (Cutting strikes) - Thin blood mist
 * - 타격 (Impact strikes) - Medium blood splatter
 * - 관통격 (Penetrating strikes) - Thick blood droplets
 * - 깊은 상처 (Deep wounds) - Large blood gouts
 */
 
import React, { useEffect, useMemo } from 'react';
import { useFrame } from '@react-three/fiber';
import * as THREE from 'three';
import { ThreeObjectPools } from '../../../../../utils/threeObjectPool';
 
/**
 * Viscosity types for blood splatter
 */
export type ViscosityType = 'thin' | 'medium' | 'thick' | 'gout';
 
/**
 * Individual blood viscosity effect
 */
export interface BloodViscosityEffect {
  readonly id: string;
  readonly position: [number, number, number];
  readonly direction: [number, number, number];
  readonly viscosityType: ViscosityType;
  readonly intensity: number; // 0.0-1.0
  readonly startTime: number;
}
 
/**
 * Props for BloodViscosity3D component
 */
export interface BloodViscosity3DProps {
  readonly effects: readonly BloodViscosityEffect[];
  readonly enabled?: boolean;
  readonly isMobile?: boolean;
  readonly onEffectComplete?: (id: string) => void;
}
 
// Physics constants for blood viscosity
const BLOOD_VISCOSITY_CONSTANTS = {
  // Gravity and air resistance
  GRAVITY: -9.8, // m/s²
  AIR_RESISTANCE: 0.94, // Thicker than arterial (0.97) or bone (0.96)
  
  // Particle counts by viscosity type (desktop)
  PARTICLE_COUNT: {
    thin: 50, // Mist
    medium: 80, // Normal splatter
    thick: 120, // Heavy droplets
    gout: 200, // Deep wound large gouts
  },
  
  // Velocity ranges (m/s) - slower than arterial
  VELOCITY: {
    thin: { min: 2.0, max: 4.0 },
    medium: { min: 1.5, max: 3.0 },
    thick: { min: 1.0, max: 2.5 },
    gout: { min: 0.5, max: 2.0 },
  },
  
  // Particle sizes
  SIZE: {
    thin: { min: 0.02, max: 0.04 },
    medium: { min: 0.04, max: 0.08 },
    thick: { min: 0.06, max: 0.12 },
    gout: { min: 0.10, max: 0.20 },
  },
  
  // Spread cone angles (radians)
  SPREAD_ANGLE: {
    thin: Math.PI / 3, // 60° wide spray
    medium: Math.PI / 4, // 45° normal
    thick: Math.PI / 6, // 30° narrow
    gout: Math.PI / 8, // 22.5° very narrow
  },
  
  // Lifetimes
  ACTIVE_LIFETIME: 2.5, // Active falling time
  CLING_LIFETIME: 3.0, // Time stuck to ground
  TOTAL_LIFETIME: 5.5, // Total before cleanup
  
  // Ground cling physics
  GROUND_LEVEL: 0.1, // y-position for ground contact
  CLING_DAMPING: 0.3, // Velocity reduction on contact
  
  // Color
  BLOOD_COLOR: 0x8b0000, // Dark red
  
  // Max delta time to prevent physics spiral
  MAX_DELTA: 1 / 30,
} as const;
 
/**
 * BloodViscosity3D - Enhanced blood droplets with realistic thicker physics
 *
 * Features:
 * - Variable viscosity types (thin mist to thick gouts)
 * - Cling/drip physics when hitting ground
 * - Slower fall rates than arterial spray
 * - Larger droplet sizes
 * - Mobile optimization (50% particles)
 */
export const BloodViscosity3D: React.FC<BloodViscosity3DProps> = ({
  effects,
  enabled = true,
  isMobile = false,
  onEffectComplete,
}) => {
  // Track active effect instances
  const [effectInstances, setEffectInstances] = React.useState<
    Map<
      string,
      {
        particles: THREE.Points;
        velocities: THREE.Vector3[];
        startTime: number;
        effect: BloodViscosityEffect;
        clinging: boolean[];
      }
    >
  >(new Map());
 
  // Calculate particle count based on viscosity and mobile
  const getParticleCount = useMemo(
    () => (viscosityType: ViscosityType) => {
      const baseCount = BLOOD_VISCOSITY_CONSTANTS.PARTICLE_COUNT[viscosityType];
      return isMobile ? Math.floor(baseCount * 0.5) : baseCount;
    },
    [isMobile]
  );
 
  // Create particle system for blood droplets
  const createBloodParticles = useMemo(
    () => (effect: BloodViscosityEffect) => {
      const count = getParticleCount(effect.viscosityType);
      const geometry = new THREE.BufferGeometry();
      const positions = new Float32Array(count * 3);
      const colors = new Float32Array(count * 3);
      const sizes = new Float32Array(count);
      const velocities: THREE.Vector3[] = [];
      const clinging: boolean[] = [];
 
      // Pooled objects for calculations - PERFORMANCE: Eliminates 2 + (count * 3) allocations
      const tempDirection = ThreeObjectPools.vector3.acquire();
      const tempColor = ThreeObjectPools.color.acquire();
      const tempVelocity = ThreeObjectPools.vector3.acquire();
      const tempDeviation = ThreeObjectPools.vector3.acquire();
 
      try {
        tempDirection.set(...effect.direction).normalize();
        const spreadAngle = BLOOD_VISCOSITY_CONSTANTS.SPREAD_ANGLE[effect.viscosityType];
        const velocityRange = BLOOD_VISCOSITY_CONSTANTS.VELOCITY[effect.viscosityType];
        const sizeRange = BLOOD_VISCOSITY_CONSTANTS.SIZE[effect.viscosityType];
 
        // Set color once from pool
        tempColor.set(BLOOD_VISCOSITY_CONSTANTS.BLOOD_COLOR);
 
        for (let i = 0; i < count; i++) {
          // Start at impact position
          positions[i * 3] = 0;
          positions[i * 3 + 1] = 0;
          positions[i * 3 + 2] = 0;
 
          // Dark red color (reuse pooled color)
          colors[i * 3] = tempColor.r;
          colors[i * 3 + 1] = tempColor.g;
          colors[i * 3 + 2] = tempColor.b;
 
          // Variable size based on viscosity
          const size =
            sizeRange.min +
            Math.random() * (sizeRange.max - sizeRange.min) *
              effect.intensity;
          sizes[i] = size;
 
          // Calculate velocity with spread
          const speed =
            velocityRange.min +
            Math.random() * (velocityRange.max - velocityRange.min);
 
          // Random deviation within spread angle
          const theta = (Math.random() - 0.5) * spreadAngle;
          const phi = Math.random() * Math.PI * 2;
 
          // Use pooled vectors for calculation
          tempDeviation.set(
            Math.sin(theta) * Math.cos(phi),
            Math.sin(theta) * Math.sin(phi),
            Math.cos(theta)
          );
 
          tempVelocity.copy(tempDirection)
            .add(tempDeviation)
            .normalize()
            .multiplyScalar(speed);
 
          // Clone for ownership - particles own their velocity vectors
          velocities.push(tempVelocity.clone());
          clinging.push(false);
        }
      } finally {
        // Release all pooled objects back to pool
        ThreeObjectPools.vector3.release(tempDirection);
        ThreeObjectPools.color.release(tempColor);
        ThreeObjectPools.vector3.release(tempVelocity);
        ThreeObjectPools.vector3.release(tempDeviation);
      }
 
      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.08,
        vertexColors: true,
        transparent: true,
        opacity: 0.9,
        blending: THREE.NormalBlending,
        depthWrite: false,
        sizeAttenuation: true,
      });
 
      const points = new THREE.Points(geometry, material);
      points.position.set(...effect.position);
 
      return { points, velocities, clinging };
    },
    [getParticleCount]
  );
 
  // Update effect instances
  useEffect(() => {
    Iif (!enabled) return;
 
    setEffectInstances((prev) => {
      const updated = new Map(prev);
 
      effects.forEach((effect) => {
        if (!updated.has(effect.id)) {
          const { points, velocities, clinging } = createBloodParticles(effect);
          updated.set(effect.id, {
            particles: points,
            velocities,
            startTime: effect.startTime,
            effect,
            clinging,
          });
        }
      });
 
      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.particles.geometry.dispose();
            (instance.particles.material as THREE.Material).dispose();
          }
          updated.delete(id);
        }
      });
 
      return updated;
    });
  }, [effects, enabled, createBloodParticles]);
 
  // Animation loop
  useFrame((_state, delta) => {
    if (!enabled || effectInstances.size === 0) return;
 
    const clampedDelta = Math.min(delta, BLOOD_VISCOSITY_CONSTANTS.MAX_DELTA);
    const now = Date.now();
    const completedIds: string[] = [];
 
    effectInstances.forEach((instance, id) => {
      const elapsed = (now - instance.startTime) / 1000;
 
      // Check for completion
      if (elapsed >= BLOOD_VISCOSITY_CONSTANTS.TOTAL_LIFETIME) {
        completedIds.push(id);
        return;
      }
 
      const geometry = instance.particles.geometry;
      const positions = geometry.attributes.position.array as Float32Array;
      const count = positions.length / 3;
 
      // Update each particle
      for (let i = 0; i < count; i++) {
        const idx = i * 3;
 
        if (!instance.clinging[i]) {
          // Apply gravity
          instance.velocities[i].y +=
            BLOOD_VISCOSITY_CONSTANTS.GRAVITY * clampedDelta;
 
          // Apply air resistance
          instance.velocities[i].multiplyScalar(
            BLOOD_VISCOSITY_CONSTANTS.AIR_RESISTANCE
          );
 
          // Update position
          positions[idx] += instance.velocities[i].x * clampedDelta;
          positions[idx + 1] += instance.velocities[i].y * clampedDelta;
          positions[idx + 2] += instance.velocities[i].z * clampedDelta;
 
          // Check ground contact
          if (positions[idx + 1] <= BLOOD_VISCOSITY_CONSTANTS.GROUND_LEVEL) {
            positions[idx + 1] = BLOOD_VISCOSITY_CONSTANTS.GROUND_LEVEL;
            instance.velocities[i].multiplyScalar(
              BLOOD_VISCOSITY_CONSTANTS.CLING_DAMPING
            );
            instance.clinging[i] = true;
          }
        }
      }
 
      geometry.attributes.position.needsUpdate = true;
 
      // Fade out during cling phase
      if (elapsed >= BLOOD_VISCOSITY_CONSTANTS.ACTIVE_LIFETIME) {
        const fadeProgress =
          (elapsed - BLOOD_VISCOSITY_CONSTANTS.ACTIVE_LIFETIME) /
          BLOOD_VISCOSITY_CONSTANTS.CLING_LIFETIME;
        const material = instance.particles.material as THREE.PointsMaterial;
        material.opacity = 0.9 * (1.0 - fadeProgress);
      }
    });
 
    completedIds.forEach((id) => {
      onEffectComplete?.(id);
    });
  });
 
  return (
    <>
      {Array.from(effectInstances.values()).map((instance) => (
        <primitive key={instance.effect.id} object={instance.particles} />
      ))}
    </>
  );
};