All files / components/shared/three/optimization AdaptiveQuality.ts

77.14% Statements 54/70
65.11% Branches 28/43
90% Functions 9/10
77.94% Lines 53/68

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                                                                                                            2x                   2x                                                       49x 49x 49x       49x               671x     671x 671x 4x       671x 657x       14x 4x         600x     10x   10x         3x 2x 1x 1x   7x         3x 1x 2x 2x       10x 6x 6x 6x   6x 6x         6x     4x             11x             2x             37x 37x 37x             2x 2x                                                                       60x   60x       60x   60x   30x                           30x 30x       60x 60x 60x   60x                                                             60x    
/**
 * AdaptiveQuality - Dynamic quality adjustment system for mobile performance
 *
 * Monitors real-time FPS and automatically adjusts rendering quality to maintain
 * 55fps target on mobile devices. Provides quality presets and smooth transitions.
 *
 * Features:
 * - Real-time FPS monitoring
 * - Automatic quality adjustment (high/medium/low)
 * - Debounced quality changes to prevent thrashing
 * - Mobile-optimized thresholds
 * - React hook integration
 *
 * @module components/shared/three/optimization/AdaptiveQuality
 * @category Performance Optimization
 * @korean 적응형품질시스템
 */
 
import { useFrame } from "@react-three/fiber";
import { useEffect, useRef, useState } from "react";
 
/**
 * Quality levels for adaptive rendering
 */
export type QualityLevel = "high" | "medium" | "low";
 
/**
 * Quality settings for each level
 */
export interface QualitySettings {
  readonly level: QualityLevel;
  readonly shadowMapSize: number;
  readonly maxParticles: number;
  readonly postProcessing: boolean;
  readonly effectsQuality: number; // 0.0-1.0 multiplier
}
 
/**
 * FPS thresholds for quality adjustment
 */
export interface AdaptiveQualityThresholds {
  /** FPS threshold to downgrade quality */
  readonly downgradeThreshold: number;
  /** FPS threshold to upgrade quality */
  readonly upgradeThreshold: number;
  /** Minimum time between quality changes (ms) */
  readonly debounceTime: number;
  /** Number of frames to average for stability */
  readonly sampleSize: number;
}
 
/**
 * Default thresholds for mobile optimization
 */
const DEFAULT_MOBILE_THRESHOLDS: AdaptiveQualityThresholds = {
  downgradeThreshold: 45, // Downgrade if fps drops below 45
  upgradeThreshold: 58, // Upgrade if fps consistently above 58
  debounceTime: 2000, // 2 seconds between changes
  sampleSize: 60, // Average over 60 frames (~1 second at 60fps)
};
 
/**
 * Quality presets optimized for mobile performance
 */
export const QUALITY_PRESETS: Record<QualityLevel, QualitySettings> = {
  high: {
    level: "high",
    shadowMapSize: 1536,
    maxParticles: 60,
    postProcessing: false, // Keep disabled on mobile
    effectsQuality: 1.0,
  },
  medium: {
    level: "medium",
    shadowMapSize: 1024,
    maxParticles: 40,
    postProcessing: false,
    effectsQuality: 0.75,
  },
  low: {
    level: "low",
    shadowMapSize: 512,
    maxParticles: 20,
    postProcessing: false,
    effectsQuality: 0.5,
  },
} as const;
 
/**
 * Adaptive quality system class
 */
export class AdaptiveQualitySystem {
  private currentQuality: QualityLevel = "high";
  private fpsHistory: number[] = [];
  private lastQualityChange = 0;
  private readonly thresholds: AdaptiveQualityThresholds;
 
  constructor(thresholds: Partial<AdaptiveQualityThresholds> = {}) {
    this.thresholds = { ...DEFAULT_MOBILE_THRESHOLDS, ...thresholds };
  }
 
  /**
   * Update system with current FPS
   * Returns new quality level if changed, null otherwise
   */
  update(currentFps: number): QualityLevel | null {
    const now = performance.now();
 
    // Add to history
    this.fpsHistory.push(currentFps);
    if (this.fpsHistory.length > this.thresholds.sampleSize) {
      this.fpsHistory.shift();
    }
 
    // Need enough samples before adjusting
    if (this.fpsHistory.length < this.thresholds.sampleSize) {
      return null;
    }
 
    // Check debounce time
    if (now - this.lastQualityChange < this.thresholds.debounceTime) {
      return null;
    }
 
    // Calculate average FPS
    const avgFps =
      this.fpsHistory.reduce((a, b) => a + b, 0) / this.fpsHistory.length;
 
    // Determine if quality should change
    let newQuality: QualityLevel | null = null;
 
    if (
      avgFps < this.thresholds.downgradeThreshold &&
      this.currentQuality !== "low"
    ) {
      // Downgrade quality
      if (this.currentQuality === "high") {
        newQuality = "medium";
      E} else if (this.currentQuality === "medium") {
        newQuality = "low";
      }
    } else if (
      avgFps > this.thresholds.upgradeThreshold &&
      this.currentQuality !== "high"
    ) {
      // Upgrade quality
      if (this.currentQuality === "low") {
        newQuality = "medium";
      E} else if (this.currentQuality === "medium") {
        newQuality = "high";
      }
    }
 
    if (newQuality !== null) {
      this.currentQuality = newQuality;
      this.lastQualityChange = now;
      this.fpsHistory = []; // Reset history after change
 
      Eif (import.meta.env.DEV) {
        console.log(
          `[AdaptiveQuality] Quality changed to ${newQuality} (avg fps: ${avgFps.toFixed(1)})`,
        );
      }
 
      return newQuality;
    }
 
    return null;
  }
 
  /**
   * Get current quality level
   */
  getCurrentQuality(): QualityLevel {
    return this.currentQuality;
  }
 
  /**
   * Get settings for current quality level
   */
  getCurrentSettings(): QualitySettings {
    return QUALITY_PRESETS[this.currentQuality];
  }
 
  /**
   * Manually set quality level
   */
  setQuality(quality: QualityLevel): void {
    this.currentQuality = quality;
    this.lastQualityChange = performance.now();
    this.fpsHistory = [];
  }
 
  /**
   * Reset the system
   */
  reset(): void {
    this.fpsHistory = [];
    this.lastQualityChange = 0;
  }
}
 
/**
 * React hook for adaptive quality management
 *
 * Automatically monitors FPS and adjusts quality settings.
 * Returns current quality level and settings.
 *
 * @param enabled - Whether adaptive quality is enabled
 * @param isMobile - Whether device is mobile (stricter thresholds)
 * @param onQualityChange - Callback when quality level changes
 * @returns Current quality settings
 *
 * @example
 * ```tsx
 * function CombatScene({ isMobile }) {
 *   const quality = useAdaptiveQuality(true, isMobile, (level) => {
 *     console.log(`Quality changed to ${level}`);
 *   });
 *
 *   return (
 *     <Canvas shadowMap={{ size: quality.shadowMapSize }}>
 *       <ParticleSystem maxParticles={quality.maxParticles} />
 *     </Canvas>
 *   );
 * }
 * ```
 */
export function useAdaptiveQuality(
  enabled: boolean = true,
  isMobile: boolean = false,
  onQualityChange?: (quality: QualityLevel) => void,
): QualitySettings {
  // Initialize with appropriate starting quality
  const initialQuality: QualityLevel = isMobile ? "medium" : "high";
 
  const [currentQuality, setCurrentQuality] =
    useState<QualityLevel>(initialQuality);
 
  // Create system instance
  const systemRef = useRef<AdaptiveQualitySystem | null>(null);
 
  useEffect(() => {
    // Create system with mobile-optimized thresholds
    const thresholds = isMobile
      ? {
          downgradeThreshold: 45, // More aggressive on mobile
          upgradeThreshold: 58,
          debounceTime: 2000,
          sampleSize: 60,
        }
      : {
          downgradeThreshold: 50,
          upgradeThreshold: 59,
          debounceTime: 3000,
          sampleSize: 90,
        };
 
    systemRef.current = new AdaptiveQualitySystem(thresholds);
    systemRef.current.setQuality(initialQuality);
  }, [isMobile, initialQuality]);
 
  // FPS tracking - Initialize with 0, will be set on first frame
  const lastTimeRef = useRef(0);
  const frameCountRef = useRef(0);
  const initializedRef = useRef(false);
 
  useFrame(() => {
    if (!enabled || !systemRef.current) return;
 
    // Calculate FPS
    const now = performance.now();
 
    // Initialize on first frame
    if (!initializedRef.current) {
      lastTimeRef.current = now;
      initializedRef.current = true;
      return;
    }
 
    const delta = now - lastTimeRef.current;
 
    if (delta > 0) {
      const fps = 1000 / delta;
      frameCountRef.current++;
 
      // Update every frame for smooth monitoring
      const newQuality = systemRef.current.update(fps);
 
      if (newQuality !== null) {
        setCurrentQuality(newQuality);
        onQualityChange?.(newQuality);
      }
    }
 
    lastTimeRef.current = now;
  });
 
  return QUALITY_PRESETS[currentQuality];
}