All files / components/shared/three/optimization InstancedGeometry.tsx

46.42% Statements 13/28
15.78% Branches 3/19
30.76% Functions 4/13
44% Lines 11/25

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                                                                                                                                                                    2x                                                                                                                         2x                                                                                                                                         2x                                                                                                                   7x   6x   1x                           7x 7x 26x   7x                                   61x              
/* eslint-disable react-refresh/only-export-components */
/**
 * InstancedGeometry - Reusable instancing utilities for optimized rendering
 *
 * Provides helpers and components for GPU instancing to reduce draw calls.
 * Especially useful for particles, repeated geometry, and effects.
 *
 * Features:
 * - Instanced particle systems
 * - Batch rendering utilities
 * - Position/rotation/scale management
 * - Color variations per instance
 * - Korean-themed effects optimization
 *
 * Performance Impact:
 * - Reduces draw calls from N to 1 per geometry type
 * - 50%+ performance improvement for particle-heavy scenes
 * - Target: <100 draw calls per frame
 *
 * @module components/shared/three/optimization/InstancedGeometry
 * @category Performance Optimization
 * @korean 인스턴스기하학
 */
 
import { Instances, Instance } from "@react-three/drei";
import React, { useMemo } from "react";
import * as THREE from "three";
 
/**
 * Instance data for a single object
 */
export interface InstanceData {
  readonly position: THREE.Vector3 | [number, number, number];
  readonly rotation?: THREE.Euler | [number, number, number];
  readonly scale?: number | [number, number, number];
  readonly color?: THREE.ColorRepresentation;
}
 
/**
 * Props for InstancableSpheres component
 */
export interface InstancableSpheresProps {
  /** Array of instance data */
  readonly instances: readonly InstanceData[];
  /** Sphere radius */
  readonly radius?: number;
  /** Sphere segments (lower = better performance) */
  readonly segments?: number;
  /** Base material color */
  readonly color?: THREE.ColorRepresentation;
  /** Material properties */
  readonly materialProps?: Partial<THREE.MeshBasicMaterialParameters>;
}
 
/**
 * Instanced spheres component
 *
 * Renders multiple spheres with a single draw call.
 * Ideal for particles, projectiles, effects.
 *
 * **Important**: The instances array should be stable (use useMemo).
 * Array indices are used as React keys, so adding/removing/reordering
 * instances during component lifecycle may cause incorrect rendering.
 * If instances need to be dynamic, consider using unique identifiers as keys.
 *
 * @example
 * ```tsx
 * const particles = useMemo(() =>
 *   Array.from({ length: 50 }, (_, i) => ({
 *     position: [Math.random() * 10 - 5, Math.random() * 10, Math.random() * 10 - 5],
 *     color: i % 2 === 0 ? 0x00ffff : 0xffd700,
 *   })),
 *   []
 * );
 *
 * <InstancableSpheres
 *   instances={particles}
 *   radius={0.1}
 *   segments={8}
 * />
 * ```
 */
export const InstancableSpheres: React.FC<InstancableSpheresProps> = ({
  instances,
  radius = 0.1,
  segments = 8,
  color = 0x00ffff,
  materialProps = {},
}) => {
  return (
    <Instances limit={instances.length}>
      <sphereGeometry args={[radius, segments, segments]} />
      <meshBasicMaterial color={color} {...materialProps} />
      {instances.map((instance, index) => (
        <Instance
          key={index}
          position={instance.position}
          rotation={instance.rotation}
          scale={instance.scale}
          color={instance.color}
        />
      ))}
    </Instances>
  );
};
 
/**
 * Props for InstancableBoxes component
 */
export interface InstancableBoxesProps {
  /** Array of instance data */
  readonly instances: readonly InstanceData[];
  /** Box dimensions [width, height, depth] */
  readonly size?: [number, number, number];
  /** Base material color */
  readonly color?: THREE.ColorRepresentation;
  /** Material properties */
  readonly materialProps?: Partial<THREE.MeshStandardMaterialParameters>;
}
 
/**
 * Instanced boxes component
 *
 * Renders multiple boxes with a single draw call.
 * Useful for environment objects, obstacles, UI elements.
 *
 * **Important**: The instances array should be stable (use useMemo).
 * Array indices are used as React keys, so adding/removing/reordering
 * instances during component lifecycle may cause incorrect rendering.
 * If instances need to be dynamic, consider using unique identifiers as keys.
 *
 * @example
 * ```tsx
 * <InstancableBoxes
 *   instances={[
 *     { position: [0, 0, 0], scale: 1 },
 *     { position: [2, 0, 0], scale: 1.5 },
 *   ]}
 *   size={[1, 1, 1]}
 *   color={0x404040}
 * />
 * ```
 */
export const InstancableBoxes: React.FC<InstancableBoxesProps> = ({
  instances,
  size = [1, 1, 1],
  color = 0x00ffff,
  materialProps = {},
}) => {
  return (
    <Instances limit={instances.length}>
      <boxGeometry args={size} />
      <meshStandardMaterial color={color} {...materialProps} />
      {instances.map((instance, index) => (
        <Instance
          key={index}
          position={instance.position}
          rotation={instance.rotation}
          scale={instance.scale}
          color={instance.color}
        />
      ))}
    </Instances>
  );
};
 
/**
 * Props for InstancableParticles component
 */
export interface InstancableParticlesProps {
  /** Particle positions */
  readonly positions: readonly (THREE.Vector3 | [number, number, number])[];
  /** Particle colors (optional) */
  readonly colors?: readonly THREE.ColorRepresentation[];
  /** Particle size */
  readonly size?: number;
  /** Quality level affects particle complexity */
  readonly quality?: "high" | "medium" | "low";
  /** Base particle color */
  readonly baseColor?: THREE.ColorRepresentation;
}
 
/**
 * Optimized instanced particles
 *
 * High-performance particle system using instancing.
 * Quality parameter adjusts geometry complexity.
 *
 * **Important**: The positions array should be stable (use useMemo).
 * Array indices are used as React keys, so adding/removing/reordering
 * particles during component lifecycle may cause incorrect rendering.
 * If particles need to be dynamic, consider using unique identifiers as keys.
 *
 * @example
 * ```tsx
 * const positions = useMemo(() =>
 *   Array.from({ length: 100 }, () => [
 *     Math.random() * 10 - 5,
 *     Math.random() * 5,
 *     Math.random() * 10 - 5,
 *   ]),
 *   []
 * );
 *
 * <InstancableParticles
 *   positions={positions}
 *   size={0.1}
 *   quality="medium"
 *   baseColor={0x00ffff}
 * />
 * ```
 */
export const InstancableParticles: React.FC<InstancableParticlesProps> = ({
  positions,
  colors,
  size = 0.1,
  quality = "medium",
  baseColor = 0x00ffff,
}) => {
  // Adjust geometry complexity based on quality
  const segments = useMemo(() => {
    switch (quality) {
      case "high":
        return 16;
      case "medium":
        return 8;
      case "low":
        return 4;
      default:
        return 8;
    }
  }, [quality]);
 
  const instances = useMemo(
    () =>
      positions.map((position, index) => ({
        position,
        color: colors?.[index] ?? baseColor,
        scale: size,
      })),
    [positions, colors, baseColor, size],
  );
 
  return (
    <Instances limit={positions.length}>
      <sphereGeometry args={[1, segments, segments]} />
      <meshBasicMaterial transparent opacity={0.8} />
      {instances.map((instance, index) => (
        <Instance
          key={index}
          position={instance.position}
          scale={instance.scale}
          color={instance.color}
        />
      ))}
    </Instances>
  );
};
 
/**
 * Calculate optimal instance limit based on performance tier
 *
 * @param baseLimit - Ideal instance count
 * @param isMobile - Whether device is mobile
 * @returns Adjusted instance limit
 */
export function getOptimalInstanceLimit(
  baseLimit: number,
  isMobile: boolean,
): number {
  if (isMobile) {
    // 50% reduction on mobile
    return Math.floor(baseLimit * 0.5);
  }
  return baseLimit;
}
 
/**
 * Batch instance data into chunks for efficient rendering
 *
 * @param instances - Array of instance data
 * @param batchSize - Maximum instances per batch
 * @returns Array of batched instances
 */
export function batchInstances<T>(
  instances: readonly T[],
  batchSize: number,
): T[][] {
  const batches: T[][] = [];
  for (let i = 0; i < instances.length; i += batchSize) {
    batches.push(instances.slice(i, i + batchSize) as T[]);
  }
  return batches;
}
 
/**
 * Create instance data from positions array
 *
 * @param positions - Array of positions
 * @param options - Optional instance properties
 * @returns Array of instance data
 */
export function createInstancesFromPositions(
  positions: readonly (THREE.Vector3 | [number, number, number])[],
  options: {
    color?: THREE.ColorRepresentation;
    scale?: number | [number, number, number];
    rotation?: THREE.Euler | [number, number, number];
  } = {},
): InstanceData[] {
  return positions.map((position) => ({
    position,
    color: options.color,
    scale: options.scale,
    rotation: options.rotation,
  }));
}