### Self-Hosted Benchmark URLs Example Source: https://github.com/pmndrs/detect-gpu/blob/master/_autodocs/configuration.md An example of how to configure self-hosted benchmark data using a custom CDN. Ensure your self-hosted URLs follow a similar structure. ```text https://cdn.example.com/gpu-benchmarks/d-nvidia.json https://cdn.example.com/gpu-benchmarks/m-apple-ipad.json ``` -------------------------------- ### Get GPU Version Examples Source: https://github.com/pmndrs/detect-gpu/blob/master/_autodocs/internal-modules.md Demonstrates how to extract version identifiers from various GPU model strings using the getGPUVersion function. ```typescript getGPUVersion('GeForce RTX 2080 Ti') // → '2080' ``` ```typescript getGPUVersion('Intel Iris Graphics 6100') // → '6100' ``` ```typescript getGPUVersion('AMD Radeon RX 5700 XT') // → '5700' ``` ```typescript getGPUVersion('Apple A14 GPU') // → '14' ``` ```typescript getGPUVersion('Mali-T760') // → 't760' ``` ```typescript getGPUVersion('Samsung Xclipse 920') // → '' (no digits or letter codes) ``` -------------------------------- ### Example ModelEntry with Screen Measurements Source: https://github.com/pmndrs/detect-gpu/blob/master/_autodocs/types.md Provides a concrete example of a ModelEntry tuple, showcasing screen measurements for different resolutions and device types. This demonstrates how performance data is stored for various display configurations. ```typescript // Benchmark entry with screen measurements const entry: ModelEntry = [ 'nvidia geforce rtx 3080', '3080', '3080 geforce nvidia rtx', 0, [ [1920, 1080, 120, 'Desktop 1080p'], [2560, 1440, 90, 'Desktop 1440p'], [3840, 2160, 60, 'Desktop 4K'] ] ]; // When matching GPU, library finds closest screen size // If user is 2560×1440, will use the 2560×1440 entry (90 fps) ``` -------------------------------- ### Install @pmndrs/detect-gpu with npm Source: https://github.com/pmndrs/detect-gpu/blob/master/README.md Use this command to add the package to your project using npm. ```sh npm install @pmndrs/detect-gpu ``` -------------------------------- ### Usage Example for Device Info Source: https://github.com/pmndrs/detect-gpu/blob/master/_autodocs/internal-modules.md Demonstrates how to access the deviceInfo singleton to check for mobile devices and specific iOS versions. Ensure deviceInfo is available before accessing its properties. ```typescript if (deviceInfo?.isMobile) { console.log('Mobile device'); if (deviceInfo.iOSVersion && deviceInfo.iOSVersion >= 15) { console.log('iOS 15+'); } } ``` -------------------------------- ### Import and Usage Example for detect-gpu Source: https://github.com/pmndrs/detect-gpu/blob/master/_autodocs/exports.md Demonstrates how to import and use the getGPUTier function from the @pmndrs/detect-gpu library. Includes basic error handling for OutdatedBenchmarksError. ```typescript import { getGPUTier, TierResult, TierType, GetGPUTier, ModelEntry, ModelEntryScreen, OutdatedBenchmarksError } from '@pmndrs/detect-gpu'; // Usage try { const result: TierResult = await getGPUTier({ benchmarksURL: '/benchmarks', desktopTiers: [0, 15, 30, 60] }); console.log(`Tier: ${result.tier}, Type: ${result.type}`); } catch (error) { if (error instanceof OutdatedBenchmarksError) { console.error('Update benchmark data'); } } ``` -------------------------------- ### Install @pmndrs/detect-gpu with yarn Source: https://github.com/pmndrs/detect-gpu/blob/master/README.md Use this command to add the package to your project using yarn. ```sh yarn add @pmndrs/detect-gpu ``` -------------------------------- ### Deobfuscate Renderer Examples Source: https://github.com/pmndrs/detect-gpu/blob/master/_autodocs/internal-modules.md Demonstrates how deobfuscateRenderer identifies Apple GPUs. It shows cases with multiple potential candidates and when the renderer remains unchanged. ```typescript deobfuscateRenderer(gl, 'apple gpu', true) // Returns: ['apple a15 gpu', 'apple a16 gpu'] (multiple candidates) deobfuscateRenderer(gl, 'nvidia geforce rtx 2080 ti', false) // Returns: ['nvidia geforce rtx 2080 ti'] (unchanged) ``` -------------------------------- ### Benchmark Data Format Example Source: https://github.com/pmndrs/detect-gpu/blob/master/_autodocs/configuration.md Illustrates the expected format for benchmark data when implementing a custom loader. Includes model details, screen resolutions, and FPS. ```typescript type ModelEntry = [ modelName: string, // e.g., "nvidia geforce rtx 2080 ti" version: string, // e.g., "2080" tokenized: string, // e.g., "2080 nvidia rtx ti" blocklist: 0 | 1, // 0 = normal, 1 = blocklisted screens: [ [width: number, height: number, fps: number, device?: string], // ...more screen sizes ] ]; ``` ```typescript [ "4.1.0", // Version MUST be first [...ModelEntry], [...ModelEntry], // ... more entries ] ``` -------------------------------- ### Install @pmndrs/detect-gpu with pnpm Source: https://github.com/pmndrs/detect-gpu/blob/master/README.md Use this command to add the package to your project using pnpm. ```sh pnpm add @pmndrs/detect-gpu ``` -------------------------------- ### Clean Renderer Examples Source: https://github.com/pmndrs/detect-gpu/blob/master/_autodocs/internal-modules.md Shows examples of the cleanRenderer function transforming various raw WebGL renderer strings into a normalized format. Transformations include lowercasing, removing API names, memory suffixes, and trademark symbols. ```typescript cleanRenderer('ANGLE (NVIDIA GeForce RTX 2080 Ti Direct3D11 vs_5_0 ps_5_0)') // → 'nvidia geforce rtx 2080 ti' cleanRenderer('AMD Radeon (TM) RX 5700 XT 8GB Direct3D11') // → 'amd radeon rx 5700 xt' cleanRenderer('Intel Iris Graphics 6100') // → 'intel iris graphics 6100' cleanRenderer('Vulkan 1.2.175 (NVIDIA NVIDIA GeForce GTX 970)') // → 'nvidia nvidia geforce gtx 970' ``` -------------------------------- ### Parse iOS Version Examples Source: https://github.com/pmndrs/detect-gpu/blob/master/_autodocs/internal-modules.md Illustrates the usage of parseIOSVersion with different user agent strings and flags. Note the preference for the 'Version/' token for iOS 7+ and the handling of non-Apple mobile devices. ```typescript parseIOSVersion('Mozilla/5.0 (iPhone; CPU iPhone OS 15_0 like Mac OS X)', true) // Returns: 15 parseIOSVersion('Mozilla/5.0 (iPad; CPU OS 16_1 like Mac OS X) AppleWebKit/537.36 Version/16.1', true) // Returns: 16 (prefers Version/ over OS) parseIOSVersion('Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15) AppleWebKit/537.36 Version/15', false) // Returns: undefined (not Apple mobile) ``` -------------------------------- ### Get WebGL Context Source: https://github.com/pmndrs/detect-gpu/blob/master/_autodocs/internal-modules.md Provides examples for obtaining a WebGL context, including typical usage and strict mode to fail on software rendering. ```typescript const gl = getWebGLContext(deviceInfo?.isSafari12, false); if (!gl) { console.log('WebGL not available'); } ``` ```typescript const gl = getWebGLContext(false, true); if (!gl) { // No hardware acceleration available } ``` -------------------------------- ### Basic Usage and Conditional Rendering Source: https://github.com/pmndrs/detect-gpu/blob/master/_autodocs/types.md Demonstrates how to call getGPUTier and use the result for conditional rendering and error handling. Includes examples for checking GPU tier, handling benchmark fetch failures, and logging diagnostic information. ```typescript const result = await getGPUTier(); // Conditional rendering if (result.tier >= 2) { enableAdvancedFeatures(); } else { enableBasicRendering(); } // Error handling if (result.type === 'BENCHMARK_FETCH_FAILED') { console.error('Could not fetch benchmarks, will retry later'); } // Diagnostics if (result.type === 'BLOCKLISTED') { console.warn(`GPU ${result.gpu} is known to have issues`); } // Logging with full info console.log({ tier: result.tier, gpu: result.gpu, fps: result.fps, device: result.device }); ``` -------------------------------- ### Benchmark JSON Structure Example Source: https://github.com/pmndrs/detect-gpu/blob/master/_autodocs/types.md Illustrates the structure of benchmark JSON files, which contain arrays of ModelEntry tuples. Each tuple includes GPU model details, blocklist status, and screen performance measurements. ```json [ "4.1.0", ["nvidia geforce rtx 2080 ti", "2080", "2080 nvidia rtx ti", 0, [[1920, 1080, 60, "Desktop"], ...]], ["intel iris graphics 620", "620", "620 graphics intel iris", 0, [[1920, 1080, 20, "Desktop"], ...]] ] ``` -------------------------------- ### Handle Benchmark Fetch Failures Source: https://github.com/pmndrs/detect-gpu/blob/master/_autodocs/api-reference.md Example of how to handle `BENCHMARK_FETCH_FAILED` errors. This allows for implementing retry logic or informing the user about network issues. ```typescript const gpuTier = await getGPUTier(); if (gpuTier.type === 'BENCHMARK_FETCH_FAILED') { console.log('Network issue; can retry later'); // Retry with exponential backoff } ``` -------------------------------- ### Get GPU Tier Information Source: https://github.com/pmndrs/detect-gpu/blob/master/local.html Fetches the GPU tier and related information. Ensure the benchmarksURL points to the correct location of the benchmarks file. ```javascript import { getGPUTier } from './dist/index.mjs'; const result = await getGPUTier({ benchmarksURL: './dist/benchmarks' }); document.getElementById('root').textContent = JSON.stringify( result, null, 2 ); ``` -------------------------------- ### Levenshtein Distance Examples Source: https://github.com/pmndrs/detect-gpu/blob/master/_autodocs/internal-modules.md Illustrates the computation of minimum edit distance between strings using getLevenshteinDistance. ```typescript getLevenshteinDistance('NVIDIA RTX 2080', 'NVIDIA RTX 2080 Ti') // → 4 (insert ' Ti') ``` ```typescript getLevenshteinDistance('Intel UHD 620', 'Intel UHD 630') // → 1 (substitute '2' → '3') ``` ```typescript getLevenshteinDistance('apple a14 gpu', 'apple a14 gpu') // → 0 (identical) ``` ```typescript getLevenshteinDistance('Mali-T760', 'Mali-T880') // → 2 (substitute '7' and '6') ``` -------------------------------- ### Tokenize for Levenshtein Distance Examples Source: https://github.com/pmndrs/detect-gpu/blob/master/_autodocs/internal-modules.md Shows how tokenizeForLevenshteinDistance processes strings for optimized distance comparison, handling variations in token order. ```typescript tokenizeForLevenshteinDistance('RTX 2080 Ti (NVIDIA)') // → '2080 nvidia rtx ti' ``` ```typescript tokenizeForLevenshteinDistance('2080 Ti RTX (NVIDIA)') // → '2080 nvidia rtx ti' (same result despite different order) ``` ```typescript tokenizeForLevenshteinDistance('Intel-Iris/Graphics-6100') // → '6100 graphics intel iris' ``` ```typescript tokenizeForLevenshteinDistance('Mali T760') // → 'mali t760' ``` -------------------------------- ### Filter Chipsets by iOS Version Examples Source: https://github.com/pmndrs/detect-gpu/blob/master/_autodocs/internal-modules.md Illustrates the usage of filterByIOSVersion to filter a list of chipsets based on the iOS version and whether the device is an iPad. ```typescript const chips = [ ['a8', ...], ['a10', ...], ['a14', ...], ['m1', ...] ]; filterByIOSVersion(chips, 17, false) // Returns: a12, a14, m1 (a8, a10 filtered) filterByIOSVersion(chips, 13, true) // Returns: a8, a10, a14, m1 (all compatible) filterByIOSVersion(chips, undefined, false) // Returns: all chips unchanged (no version info) ``` -------------------------------- ### getGPUTier with Custom Tier Thresholds Source: https://github.com/pmndrs/detect-gpu/blob/master/_autodocs/types.md Provides an example of overriding the default FPS thresholds for mobile and desktop GPU tiers. This allows fine-tuning the tier classification. ```typescript // Custom tier thresholds const tier4 = await getGPUTier({ mobileTiers: [0, 20, 40, 60], desktopTiers: [0, 30, 60, 90] }); ``` -------------------------------- ### Get Optimized WebGL Context Source: https://github.com/pmndrs/detect-gpu/blob/master/_autodocs/api-reference.md Creates a WebGL rendering context with optimized attributes for performance. It can optionally fail if the system is in a low-power mode and handles a specific Safari 12 edge case. ```typescript const gl = getWebGLContext(false, false); if (!gl) { console.log('WebGL not supported'); } ``` -------------------------------- ### Get GPU tier information Source: https://github.com/pmndrs/detect-gpu/blob/master/README.md Import and call getGPUTier to retrieve an object containing the user's GPU tier, mobile status, type, FPS, and GPU name. This is the primary usage for detecting GPU performance. ```ts import { getGPUTier } from '@pmndrs/detect-gpu'; const gpuTier = await getGPUTier(); // Example output: // { // "tier": 1, // "isMobile": false, // "type": "BENCHMARK", // "fps": 21, // "gpu": "intel iris graphics 6100" // } ``` -------------------------------- ### Basic GPU Detection (All Defaults) Source: https://github.com/pmndrs/detect-gpu/blob/master/_autodocs/configuration.md Demonstrates basic GPU detection using all default configuration settings. It utilizes the default CDN for benchmarks and default tier thresholds. ```typescript const result = await getGPUTier(); // Uses https://unpkg.com CDN, default tier thresholds ``` -------------------------------- ### Get GPU Tier with Overrides Source: https://github.com/pmndrs/detect-gpu/blob/master/_autodocs/api-reference.md Use this snippet to get the GPU tier by overriding detection parameters like renderer, mobile status, and screen size. ```typescript const gpuTier = await getGPUTier({ override: { renderer: 'GeForce RTX 2080 Ti', isMobile: false, screenSize: { width: 1920, height: 1080 } } }); ``` -------------------------------- ### getGPUTier with Testing Overrides Source: https://github.com/pmndrs/detect-gpu/blob/master/_autodocs/types.md Demonstrates how to use the 'override' option for testing purposes. This allows you to simulate specific GPU characteristics, screen sizes, and mobile/desktop classifications. ```typescript // Testing with overrides const tier5 = await getGPUTier({ override: { renderer: 'GeForce RTX 3080', isMobile: false, screenSize: { width: 1920, height: 1080 } } }); ``` -------------------------------- ### Default Configuration Source: https://github.com/pmndrs/detect-gpu/blob/master/_autodocs/configuration.md Shows the default values for benchmarksURL, mobileTiers, and desktopTiers in the GetGPUTier configuration. ```typescript const defaultConfig: GetGPUTier = { benchmarksURL: 'https://unpkg.com/@pmndrs/detect-gpu@6.0.8/dist/benchmarks', mobileTiers: [0, 15, 30, 60], desktopTiers: [0, 15, 30, 60], }; ``` -------------------------------- ### Self-host benchmark data Source: https://github.com/pmndrs/detect-gpu/blob/master/README.md Configure getGPUTier to load benchmark data from a local URL instead of a CDN. Ensure the provided URL points to a directory containing the extracted benchmark files. ```ts const gpuTier = await getGPUTier({ benchmarksURL: '/benchmarks', }); ``` -------------------------------- ### Configuring Self-Hosted Benchmarks Source: https://github.com/pmndrs/detect-gpu/blob/master/_autodocs/README.md Provide a custom URL for benchmark data using the `benchmarksURL` option in the `getGPUTier` configuration. ```typescript const result = await getGPUTier({ benchmarksURL: '/benchmarks' }); ``` -------------------------------- ### getGPUTier with Custom Benchmark URL Source: https://github.com/pmndrs/detect-gpu/blob/master/_autodocs/types.md Shows how to specify a custom URL for fetching benchmark data. This is useful if you host your own benchmark files. ```typescript // Custom URL const tier2 = await getGPUTier({ benchmarksURL: '/api/benchmarks' }); ``` -------------------------------- ### GPU Detection with Self-Hosted Benchmarks Source: https://github.com/pmndrs/detect-gpu/blob/master/_autodocs/configuration.md Configures GPU detection to load benchmark data from a local '/benchmarks' directory instead of a CDN. This allows for custom hosting of benchmark files. ```typescript const result = await getGPUTier({ benchmarksURL: '/benchmarks' }); // Loads from /benchmarks/d-*.json and /benchmarks/m-*.json ``` -------------------------------- ### Get GPU Tier (TypeScript Async) Source: https://github.com/pmndrs/detect-gpu/blob/master/_autodocs/exports.md Asynchronously retrieves the GPU tier using TypeScript. Use this for modern async/await workflows. Handles fallback rendering based on the detected tier. ```typescript import { getGPUTier, TierResult } from '@pmndrs/detect-gpu'; async function setupRendering(): Promise { const result: TierResult = await getGPUTier(); if (result.tier === 0) { // Fallback rendering } else { // GPU-accelerated rendering } } ``` -------------------------------- ### Minimal getGPUTier Usage Source: https://github.com/pmndrs/detect-gpu/blob/master/_autodocs/types.md Demonstrates the simplest way to call getGPUTier without any configuration options. This will use default settings for detection. ```typescript // Minimal const tier1 = await getGPUTier(); ``` -------------------------------- ### Using a Pre-created WebGL Context Source: https://github.com/pmndrs/detect-gpu/blob/master/_autodocs/SUMMARY.txt Demonstrates how to reuse an existing WebGL context instead of letting the library create one. This is useful when integrating with other libraries that manage their own contexts. ```typescript import { getGPUTier } from "@pmndrs/detect-gpu"; // Assume 'myCanvas' is an existing HTMLCanvasElement const myCanvas = document.createElement("canvas"); const gl = myCanvas.getContext("webgl2", { antialias: false, depth: false, stencil: false, alpha: false, desynchronized: true, }); if (!gl) { throw new Error("WebGL context not supported"); } // Detect GPU tier using the provided context const tier = await getGPUTier({ gl }); console.log(tier); // Example output: // { // tier: 2, // type: "gpu", // isMobile: false, // fps: { // tier1: 60, // tier2: 30, // tier3: false // }, // gpu: { // vendor: "NVIDIA Corporation", // renderer: "NVIDIA GeForce RTX 3080", // vendorId: 4318, // deviceId: 10050 // } // } ``` -------------------------------- ### Testing with Overrides Source: https://github.com/pmndrs/detect-gpu/blob/master/_autodocs/SUMMARY.txt Shows how to use overrides to simulate specific GPU or browser environments for testing purposes. This is invaluable for debugging and ensuring consistent behavior across different platforms. ```typescript import { getGPUTier } from "@pmndrs/detect-gpu"; // Override GPU detection for testing const tier = await getGPUTier({ overrideGpu: "NVIDIA GeForce RTX 4090", overrideVendorId: 0x10de, overrideDeviceId: 0x2204, }); console.log(tier); // Example output with override: // { // tier: 1, // type: "gpu", // isMobile: false, // fps: { // tier1: 60, // tier2: 30, // tier3: false // }, // gpu: { // vendor: "NVIDIA Corporation", // renderer: "NVIDIA GeForce RTX 4090", // vendorId: 4318, // deviceId: 8708 // } // } ``` -------------------------------- ### Get GPU Tier (JavaScript Promise) Source: https://github.com/pmndrs/detect-gpu/blob/master/_autodocs/exports.md Retrieves the GPU tier using JavaScript Promises. This is suitable for environments or codebases that prefer Promise-based asynchronous operations. Logs the detected tier and device. ```javascript import { getGPUTier } from '@pmndrs/detect-gpu'; getGPUTier().then(result => { console.log(`GPU Tier: ${result.tier}`); console.log(`Device: ${result.device}`); }); ``` -------------------------------- ### Self-Hosted Benchmarks Source: https://github.com/pmndrs/detect-gpu/blob/master/_autodocs/index.md Configures the library to load benchmarks from a custom URL. This allows for self-hosting benchmark data instead of relying on a CDN. ```typescript const result = await getGPUTier({ benchmarksURL: '/gpu-benchmarks' }); ``` -------------------------------- ### Deobfuscate Apple GPU Identifiers Source: https://github.com/pmndrs/detect-gpu/blob/master/_autodocs/api-reference.md Use this function to get a list of possible Apple GPU identifiers based on the WebGL renderer string and whether the device is an iPad. It requires a WebGL context and the renderer string as input. ```typescript const candidates = deobfuscateAppleGPU(gl, 'apple gpu', true); // iOS 15 iPhone might return: ['apple a15 gpu'] // iOS 15 iPad might return: ['apple a14 gpu', 'apple a15 gpu'] ``` -------------------------------- ### Default UNPKG CDN Benchmark URLs Source: https://github.com/pmndrs/detect-gpu/blob/master/_autodocs/configuration.md These are the default URLs for accessing benchmark data via the UNPKG CDN. Versioning is indicated in the URL path. ```text https://unpkg.com/@pmndrs/detect-gpu@6.0.8/dist/benchmarks/d-nvidia.json https://unpkg.com/@pmndrs/detect-gpu@6.0.8/dist/benchmarks/m-apple-ipad.json ``` -------------------------------- ### getGPUTier with Custom Benchmark Loading Source: https://github.com/pmndrs/detect-gpu/blob/master/_autodocs/types.md Shows how to provide a custom function to load benchmark data. This is useful for integrating with custom data sources or fetching benchmarks from a specific API endpoint. ```typescript // Custom benchmark loading const tier6 = await getGPUTier({ override: { loadBenchmarks: async (file) => { const response = await fetch(`/local-benchmarks/${file}`); return response.json(); } } }); ``` -------------------------------- ### GetGPUTier Configuration Source: https://github.com/pmndrs/detect-gpu/blob/master/_autodocs/types.md Configuration options object for the `getGPUTier()` function. Allows customization of benchmark sources, WebGL context, performance caveats, tier thresholds, and overrides for testing. ```APIDOC ## GetGPUTier ### Description Configuration options object for `getGPUTier()` function. ### Fields #### `benchmarksURL` - **Type**: `string` - **Required**: No - **Default**: `https://unpkg.com/@pmndrs/detect-gpu@{version}/dist/benchmarks` - **Description**: URL path to benchmark data directory. Must be accessible via fetch and serve `.json` files. #### `glContext` - **Type**: `WebGLRenderingContext | WebGL2RenderingContext` - **Required**: No - **Default**: — - **Description**: Pre-created WebGL context to avoid creating temporary context. Must be valid and not lost. #### `failIfMajorPerformanceCaveat` - **Type**: `boolean` - **Required**: No - **Default**: `false` - **Description**: Fail context creation if system reports major performance caveat (software rendering). #### `mobileTiers` - **Type**: `number[]` - **Required**: No - **Default**: `[0, 15, 30, 60]` - **Description**: Fps thresholds for mobile tiers (0-3). #### `desktopTiers` - **Type**: `number[]` - **Required**: No - **Default**: `[0, 15, 30, 60]` - **Description**: Fps thresholds for desktop tiers (0-3). #### `override` - **Type**: `object` - **Required**: No - **Default**: `{}` - **Description**: Testing/debugging overrides to bypass automatic detection. All fields optional. ##### `override.renderer` - **Type**: `string` - **Required**: No - **Default**: — - **Description**: Override detected renderer string. Used with `override.isMobile` for complete control. ##### `override.isIpad` - **Type**: `boolean` - **Required**: No - **Default**: — - **Description**: Override iPad detection. Affects benchmark file selection (uses `-ipad` suffix). ##### `override.isMobile` - **Type**: `boolean` - **Required**: No - **Default**: — - **Description**: Override mobile vs desktop classification. Affects GPU type detection and tier thresholds. ##### `override.screenSize` - **Type**: `{ width: number; height: number }` - **Required**: No - **Default**: — - **Description**: Override screen dimensions for benchmark pixel-count matching. Must be positive integers. ##### `override.loadBenchmarks` - **Type**: `(file: string) => Promise` - **Required**: No - **Default**: — - **Description**: Custom benchmark loader. Receives filename like `d-nvidia.json`, must return array of benchmark entries. ### Usage Examples ```typescript // Minimal const tier1 = await getGPUTier(); // Custom URL const tier2 = await getGPUTier({ benchmarksURL: '/api/benchmarks' }); // Pre-created context const canvas = document.querySelector('canvas'); const gl = canvas.getContext('webgl2'); const tier3 = await getGPUTier({ glContext: gl }); // Custom tier thresholds const tier4 = await getGPUTier({ mobileTiers: [0, 20, 40, 60], desktopTiers: [0, 30, 60, 90] }); // Testing with overrides const tier5 = await getGPUTier({ override: { renderer: 'GeForce RTX 3080', isMobile: false, screenSize: { width: 1920, height: 1080 } } }); // Custom benchmark loading const tier6 = await getGPUTier({ override: { loadBenchmarks: async (file) => { const response = await fetch(`/local-benchmarks/${file}`); return response.json(); } } }); ``` ``` -------------------------------- ### getGPUTier Source: https://github.com/pmndrs/detect-gpu/blob/master/_autodocs/index.md Asynchronously detects the user's GPU and assigns a performance tier (0-3) based on WebGL benchmarks. It can be configured with various options to customize its behavior and data fetching. ```APIDOC ## getGPUTier ### Description Asynchronously detects the user's GPU and assigns a performance tier (0-3) based on WebGL benchmarks. It can be configured with various options to customize its behavior and data fetching. ### Method `getGPUTier(options?: GetGPUTier): Promise` ### Parameters #### Query Parameters - **options** (GetGPUTier) - Optional - An object containing configuration options for GPU detection. - **benchmarksURL** (string) - Optional - Custom URL to fetch benchmark data from. - **glContext** (WebGLRenderingContext | WebGL2RenderingContext) - Optional - A pre-created WebGL rendering context. - **failIfMajorPerformanceCaveat** (boolean) - Optional - If true, the function will reject if software rendering is detected. - **mobileTiers** (number[]) - Optional - Custom FPS thresholds for classifying mobile GPUs. - **desktopTiers** (number[]) - Optional - Custom FPS thresholds for classifying desktop GPUs. - **override** (object) - Optional - Allows overriding certain detection parameters for testing purposes. - **renderer** (string) - Overrides the detected renderer string. - **isMobile** (boolean) - Overrides the mobile device detection. - **isIpad** (boolean) - Overrides the iPad device detection. - **screenSize** (object) - Overrides screen size detection (e.g., `{ width: number, height: number }`). - **loadBenchmarks** (boolean) - Overrides the automatic loading of benchmarks. ### Response #### Success Response (Promise) - **tier** (number) - The performance tier of the GPU, ranging from 0 to 3. - **type** (TierType) - The classification type of the result (e.g., 'BENCHMARK', 'FALLBACK', 'WEBGL_UNSUPPORTED'). - **isMobile** (boolean) - Indicates if the detected device is a mobile device. - **fps** (number) - The measured frames per second, relevant for 'BENCHMARK' type. - **gpu** (string) - The detected GPU model name. - **device** (string) - The detected device name, relevant for 'BENCHMARK' type. ### Response Example ```json { "tier": 2, "type": "BENCHMARK", "isMobile": false, "fps": 45, "gpu": "NVIDIA GeForce RTX 3080", "device": "Desktop" } ``` ### Error Handling - **WEBGL_UNSUPPORTED**: Returned if the browser does not support WebGL. - **SSR**: Returned if the code is executed in a server-side rendering environment. - **BLOCKLISTED**: Returned if the detected GPU is on the blocklist. - **BENCHMARK_FETCH_FAILED**: Returned if there was an error fetching benchmark data. ``` -------------------------------- ### Catching OutdatedBenchmarksError Source: https://github.com/pmndrs/detect-gpu/blob/master/_autodocs/errors.md Demonstrates how to use a try-catch block to specifically catch and handle OutdatedBenchmarksError. This allows for targeted recovery actions when benchmark data is outdated. ```typescript import { getGPUTier } from '@pmndrs/detect-gpu'; import { OutdatedBenchmarksError } from '@pmndrs/detect-gpu'; try { const gpuTier = await getGPUTier(); } catch (error) { if (error instanceof OutdatedBenchmarksError) { console.error('Benchmark data is outdated'); // Action: Update package or benchmark files to 4.x+ } else { console.error('Unknown error:', error); } } ``` -------------------------------- ### Blocklisted GPU Matching Logic Source: https://github.com/pmndrs/detect-gpu/blob/master/_autodocs/internal-modules.md Demonstrates the substring search logic used to check if a GPU model is present in the BLOCKLISTED_GPUS array. ```typescript const isBlocklisted = BLOCKLISTED_GPUS.some( gpu => cleanedRenderer.includes(gpu) ); ``` -------------------------------- ### Main Export from Index Source: https://github.com/pmndrs/detect-gpu/blob/master/_autodocs/index.md Exports the primary `getGPUTier` function and public type definitions from the library's entry point. ```typescript export { getGPUTier, TierResult, TierType, GetGPUTier, ModelEntry, ModelEntryScreen } ``` -------------------------------- ### getGPUTier Source: https://github.com/pmndrs/detect-gpu/blob/master/_autodocs/exports.md Asynchronously detects the GPU's capabilities and classifies it into a performance tier. It can accept an optional configuration object to customize its behavior, such as providing a custom benchmark URL or overriding detection parameters. The function returns a Promise that resolves to a TierResult object, or throws an OutdatedBenchmarksError if the benchmark data is incompatible. ```APIDOC ## getGPUTier ### Description Main async function for GPU detection and tier classification. It returns a Promise resolving to a TierResult object. ### Method Async function ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body `options` (GetGPUTier) - Optional configuration object for GPU detection. ### Request Example ```typescript import { getGPUTier, TierResult, GetGPUTier } from '@pmndrs/detect-gpu'; const result: TierResult = await getGPUTier({ benchmarksURL: '/benchmarks', desktopTiers: [0, 15, 30, 60] }); ``` ### Response #### Success Response (200) - **TierResult** (object) - An object containing the detected GPU tier and related information. #### Response Example ```json { "tier": 2, "type": "BENCHMARK", "isMobile": false, "fps": 45.5, "gpu": "NVIDIA GeForce RTX 3070", "device": "Desktop" } ``` ### Error Handling - **OutdatedBenchmarksError** - Thrown if the benchmark version is less than 4. ``` -------------------------------- ### Simulating Blocklisted GPU Source: https://github.com/pmndrs/detect-gpu/blob/master/_autodocs/errors.md This snippet demonstrates how to simulate a blocklisted GPU by overriding the renderer to a known blocklisted model ('geforce 8600'). This tests the 'BLOCKLISTED' error type and its associated tier. ```typescript const result = await getGPUTier({ override: { renderer: 'geforce 8600', // In BLOCKLISTED_GPUS isMobile: false } }); // result.type === 'BLOCKLISTED' // result.tier === 0 ``` -------------------------------- ### Handling WebGL Context Creation Failure Source: https://github.com/pmndrs/detect-gpu/blob/master/_autodocs/errors.md Shows how the library handles WebGL context creation failures. If a WebGL context cannot be obtained, the function returns undefined with a specific type. ```typescript const gl = glContext || getWebGLContext(...); if (!gl) { return toResult(0, 'WEBGL_UNSUPPORTED'); } ``` -------------------------------- ### Offline Support with Custom Benchmarks Source: https://github.com/pmndrs/detect-gpu/blob/master/_autodocs/index.md Enables offline support by loading benchmarks from a local bundle. This is useful when network access is unreliable or restricted. ```typescript import benchmarks from './benchmarks.bundle.json'; const result = await getGPUTier({ override: { loadBenchmarks: (file) => Promise.resolve(benchmarks[file]) } }); ``` -------------------------------- ### getWebGLContext Source: https://github.com/pmndrs/detect-gpu/blob/master/_autodocs/internal-modules.md Creates a WebGLRenderingContext with optimized settings for performance and compatibility. It includes options to work around specific browser issues like Safari 12 crashes and to fail if major performance caveats are detected. ```APIDOC ## getWebGLContext ### Description Creates a WebGLRenderingContext with optimized settings for performance and compatibility. It includes options to work around specific browser issues like Safari 12 crashes and to fail if major performance caveats are detected. ### Signature ```typescript export function getWebGLContext(isSafari12?: boolean, failIfMajorPerformanceCaveat?: boolean): WebGLRenderingContext | undefined ``` ### Parameters #### Parameters - **isSafari12** (`boolean`) - Whether browser is Safari 12 (for crash workaround) - **failIfMajorPerformanceCaveat** (`boolean`) - Fail if system reports major performance issue (defaults to `false`) ### Return `WebGLRenderingContext` or `undefined` if creation fails. ### Context Attributes ```typescript { alpha: false, antialias: false, depth: false, stencil: false, powerPreference: 'high-performance', failIfMajorPerformanceCaveat: boolean } ``` ### Safari 12 Workaround If `isSafari12 === true`, removes `powerPreference` property to avoid crash. ``` -------------------------------- ### Usage with TierType Switch Statement Source: https://github.com/pmndrs/detect-gpu/blob/master/_autodocs/types.md Shows how to use a switch statement to handle different TierType results from getGPUTier. Provides specific actions for each tier, including retrying on fetch failures and logging warnings for blocklisted GPUs. ```typescript const result = await getGPUTier(); switch (result.type) { case 'BENCHMARK': console.log(`GPU matched: ${result.gpu} (${result.fps} fps)`); break; case 'FALLBACK': console.log('GPU recognized but no exact benchmark match'); break; case 'BENCHMARK_FETCH_FAILED': console.log('Network issue, can retry later'); // Schedule retry setTimeout(() => getGPUTier(), 5000); break; case 'BLOCKLISTED': console.log(`GPU ${result.gpu} is known to have issues`); break; case 'WEBGL_UNSUPPORTED': console.log('WebGL not supported, fallback to canvas'); break; case 'SSR': console.log('Running server-side'); break; } ``` -------------------------------- ### Custom Benchmark Data Loading Source: https://github.com/pmndrs/detect-gpu/blob/master/_autodocs/SUMMARY.txt Shows how to load custom benchmark data, enabling the use of a private or updated benchmark database. This is useful for specialized applications or offline scenarios. ```typescript import { getGPUTier } from "@pmndrs/detect-gpu"; // Custom benchmark data (example) const customBenchmarks = { "10de:1f08": { // NVIDIA GeForce RTX 3080 tier1: 90, tier2: 60, tier3: 40, }, // Add more entries as needed }; // Detect GPU tier with custom benchmarks const tier = await getGPUTier({ benchmarks: customBenchmarks }); console.log(tier); // Example output (if GPU matches custom benchmark): // { // tier: 1, // type: "gpu", // isMobile: false, // fps: { // tier1: 90, // tier2: 60, // tier3: 40 // }, // gpu: { // vendor: "NVIDIA Corporation", // renderer: "NVIDIA GeForce RTX 3080", // vendorId: 4318, // deviceId: 10050 // } // } ``` -------------------------------- ### Override GPU and Screen Properties for Testing Source: https://github.com/pmndrs/detect-gpu/blob/master/_autodocs/configuration.md Simulate specific GPU models, mobile status, and screen resolutions for testing purposes. This is useful for debugging and verifying behavior. ```typescript const result = await getGPUTier({ override: { renderer: 'GeForce RTX 3080', isMobile: false, screenSize: { width: 3840, height: 2160 } // 4K } }); ``` -------------------------------- ### Basic GPU Detection with Conditional Rendering Source: https://github.com/pmndrs/detect-gpu/blob/master/_autodocs/START_HERE.md Perform basic GPU detection and enable advanced rendering if the detected GPU tier is 2 or higher. ```typescript const result = await getGPUTier(); if (result.tier >= 2) enableAdvancedRendering(); ``` -------------------------------- ### Basic GPU Tier Detection Source: https://github.com/pmndrs/detect-gpu/blob/master/_autodocs/SUMMARY.txt Demonstrates the most common usage pattern for detecting the GPU tier. This is useful for adaptive rendering or feature flagging based on GPU performance. ```typescript import { getGPUTier } from "@pmndrs/detect-gpu"; // Detect GPU tier const tier = await getGPUTier(); console.log(tier); // Example output: // { // tier: 2, // type: "gpu", // isMobile: false, // fps: { // tier1: 60, // tier2: 30, // tier3: false // }, // gpu: { // vendor: "NVIDIA Corporation", // renderer: "NVIDIA GeForce RTX 3080", // vendorId: 4318, // deviceId: 10050 // } // } ``` -------------------------------- ### Fail on Software Rendering Source: https://github.com/pmndrs/detect-gpu/blob/master/_autodocs/configuration.md Configure the library to return an unsupported status if the GPU is software-based, such as SwiftShader. This ensures native GPU usage. ```typescript const result = await getGPUTier({ failIfMajorPerformanceCaveat: true }); ``` -------------------------------- ### Basic GPU Tier Detection Source: https://github.com/pmndrs/detect-gpu/blob/master/_autodocs/README.md Import and use the `getGPUTier` function to detect the GPU tier. The result object contains information about the detected GPU. ```typescript import { getGPUTier } from '@pmndrs/detect-gpu'; const result = await getGPUTier(); console.log(result); // { tier: 2, type: 'BENCHMARK', isMobile: false, fps: 45, gpu: 'nvidia geforce rtx 2080 ti' } ``` -------------------------------- ### Configure GPU Tier Detection Source: https://github.com/pmndrs/detect-gpu/blob/master/_autodocs/exports.md Customizes the GPU tier detection process by providing specific URLs for benchmarks and defining custom tier thresholds for mobile and desktop devices. Also includes an option to fail if major performance caveats are detected. ```typescript const result = await getGPUTier({ benchmarksURL: 'https://cdn.example.com/benchmarks', mobileTiers: [0, 20, 40, 60], desktopTiers: [0, 30, 60, 90], failIfMajorPerformanceCaveat: true }); ``` -------------------------------- ### Error Handling for Outdated Benchmarks Source: https://github.com/pmndrs/detect-gpu/blob/master/_autodocs/index.md Demonstrates how to catch and handle the `OutdatedBenchmarksError` which is thrown when the benchmark data version is incompatible. This ensures graceful degradation or prompts for updates. ```typescript try { const result = await getGPUTier(); } catch (error) { if (error instanceof OutdatedBenchmarksError) { // Handle version incompatibility } } ``` -------------------------------- ### Testing with Overrides Source: https://github.com/pmndrs/detect-gpu/blob/master/_autodocs/START_HERE.md Use the override option to simulate specific GPU hardware for testing and debugging purposes. ```typescript const result = await getGPUTier({ override: { renderer: 'GeForce RTX 3080', isMobile: false } }); ``` -------------------------------- ### Custom Desktop Tier Thresholds Source: https://github.com/pmndrs/detect-gpu/blob/master/_autodocs/configuration.md Set custom frames per second requirements for desktop GPU tiers. This allows for a more conservative tier assignment. ```typescript const result = await getGPUTier({ desktopTiers: [0, 30, 60, 90] // Require 30fps for tier 1 }); ``` -------------------------------- ### Server-Side Rendering (SSR) Detection Source: https://github.com/pmndrs/detect-gpu/blob/master/_autodocs/SUMMARY.txt Demonstrates how the library detects if it's running in a server-side rendering environment. This is important for avoiding WebGL context creation on the server. ```typescript import { getGPUTier } from "@pmndrs/detect-gpu"; // Detect GPU tier, will return a specific tier for SSR environments const tier = await getGPUTier(); console.log(tier); // Example output for SSR: // { // tier: 0, // type: "unknown", // isMobile: false, // fps: { // tier1: 60, // tier2: 30, // tier3: false // }, // gpu: null // } ``` -------------------------------- ### getGPUTier Function Signature Source: https://github.com/pmndrs/detect-gpu/blob/master/README.md The `getGPUTier` function accepts an options object to configure GPU detection. This includes specifying benchmark data URLs, providing an existing WebGL context, setting performance caveat behavior, defining framerates for mobile and desktop tiers, and overriding device properties. ```typescript getGPUTier({ /** * URL of directory where benchmark data is hosted. * * @default https://unpkg.com/@pmndrs/detect-gpu@{version}/dist/benchmarks */ benchmarksURL?: string; /** * Optionally pass in a WebGL context to avoid creating a temporary one * internally. */ glContext?: WebGLRenderingContext | WebGL2RenderingContext; /** * Whether to fail if the system performance is low or if no hardware GPU is * available. * * @default false */ failIfMajorPerformanceCaveat?: boolean; /** * Framerate per tier for mobile devices. * * @defaultValue [0, 15, 30, 60] */ mobileTiers?: number[]; /** * Framerate per tier for desktop devices. * * @defaultValue [0, 15, 30, 60] */ desktopTiers?: number[]; /** * Optionally override specific parameters. Used mainly for testing. */ override?: { renderer?: string; /** * Override whether device is an iPad. */ isIpad?: boolean; /** * Override whether device is a mobile device. */ isMobile?: boolean; /** * Override device screen size. */ screenSize?: { width: number; height: number }; /** * Override how benchmark data is loaded */ loadBenchmarks?: (file: string) => Promise; }; }) ``` -------------------------------- ### ModelEntry Type Definition Source: https://github.com/pmndrs/detect-gpu/blob/master/_autodocs/exports.md Defines the tuple format for benchmark data entries. Includes GPU model name, version, tokenized model, blocklist flag, and screen measurements. ```typescript export type ModelEntry = [string, string, string, 0 | 1, ModelEntryScreen[]]; ``` -------------------------------- ### Simulating Network Failure Source: https://github.com/pmndrs/detect-gpu/blob/master/_autodocs/errors.md This snippet shows how to simulate a network failure during benchmark loading by throwing an error within the overridden 'loadBenchmarks' function. This tests the 'BENCHMARK_FETCH_FAILED' error condition. ```typescript const result = await getGPUTier({ override: { loadBenchmarks: async () => { throw new Error('Network error'); } } }); // result.type === 'BENCHMARK_FETCH_FAILED' ``` -------------------------------- ### Detecting WebGL Unsupported Source: https://github.com/pmndrs/detect-gpu/blob/master/_autodocs/errors.md Demonstrates how to detect if WebGL is unsupported on the device by checking the 'type' property of the result. This is useful for implementing fallback rendering strategies. ```typescript const result = await getGPUTier(); if (result.type === 'WEBGL_UNSUPPORTED') { console.log('WebGL not supported on this device'); console.log('Tier:', result.tier); // Will be 0 // Fallback to canvas 2D or basic rendering } ``` -------------------------------- ### Automatic Device Detection (Default) Source: https://github.com/pmndrs/detect-gpu/blob/master/_autodocs/configuration.md The library automatically detects device type (mobile, desktop, iPad) using navigator properties and screen dimensions. No configuration is needed for default behavior. ```typescript // Detected from navigator properties: // - navigator.userAgent // - navigator.platform // - navigator.maxTouchPoints // - window.screen dimensions const result = await getGPUTier(); ``` -------------------------------- ### getGPUTier() Source: https://github.com/pmndrs/detect-gpu/blob/master/_autodocs/README.md The main function for detecting the GPU tier. It returns an object with information about the detected GPU, including its tier, type, mobile status, FPS, and model name. It can also be configured with various options. ```APIDOC ## getGPUTier() ### Description Detects the GPU tier and provides detailed information about the detected GPU. This is the primary function for users of the library. ### Method `getGPUTier(options?: GetGPUTier)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body `options` (GetGPUTier) - Optional configuration object for the detection process. This can include: - `benchmarksURL`: URL to fetch benchmark data from. - `tier1Threshold`, `tier2Threshold`, `tier3Threshold`: Custom FPS thresholds for each tier. - `failIfMajorPerformanceCaveat`: Whether to fail if a major performance caveat is detected. - `mobileApproximate`: Approximate mobile GPU detection. - `disableBufferClear`: Disable buffer clearing for WebGL context. - `forceLowEndDevice`: Force detection as a low-end device. - `useBypassCache`: Bypass cache for benchmark data. - `overrideBenchmark`: Override benchmark data with a custom object. ### Request Example ```javascript import { getGPUTier } from '@pmndrs/detect-gpu'; const result = await getGPUTier({ benchmarksURL: '/custom-benchmarks', tier1Threshold: 30, }); console.log(result); ``` ### Response #### Success Response (200) - **tier** (TierType) - The detected GPU tier (0-3). - **type** (string) - The type of detection result (e.g., 'BENCHMARK', 'WEBGL_UNSUPPORTED', 'BENCHMARK_FETCH_FAILED'). - **isMobile** (boolean) - Whether the device is considered mobile. - **fps** (number) - Estimated frames per second. - **gpu** (string) - The detected GPU model name. #### Response Example ```json { "tier": 2, "type": "BENCHMARK", "isMobile": false, "fps": 45, "gpu": "nvidia geforce rtx 2080 ti" } ``` ### Errors - `OutdatedBenchmarksError`: Thrown when the benchmark data is outdated. - Network failures: Indicated by `BENCHMARK_FETCH_FAILED` in the result type. - WebGL creation failures: Indicated by `WEBGL_UNSUPPORTED` in the result type. ```