r3f-perf

repository·main·Indexed 21 days ago

https://github.com/utsuboco/r3f-perf

A performance monitoring tool for @react-three/fiber applications. It provides real-time visual overlays for FPS, GPU usage, memory, and custom metrics via the <Perf /> component. It also offers <PerfHeadless /> and the usePerf hook for programmatic access to performance data, as well as deep analysis of GL programs and Three.js matrix updates.

Tokens
4K
Snippets
14
Records
20
Agent score
71%

What's inside r3f-perf

  1. Configure Perf component options

    main

    The <Perf /> component accepts several options to customize the monitoring interface:

    OptionTypeDefaultDescription
    logsPerSecondnumber10Refresh rate of the logs
    antialiasbooleantrueRender text with antialiasing (uses more performance)
    overClockbooleanfalseDisable the limitation of the monitor refresh rate for the fps
    deepAnalyzebooleanfalseProvides more detailed information about GL programs
    showGraphbooleantrueShow the graphs
    minimalbooleanfalseCondensed version showing only essential info (gpu/memory/fps/custom data)
    matrixUpdatebooleanfalseCount the number of times matrixWorldUpdate is called per frame
    colorBlindbooleanfalseUse color blind friendly colors for accessibility
    classNamestring''Override CSS class
    styleobject{}Override style
    position'top-right'|'top-left'|'bottom-right'|'bottom-left''top-right'Quickly set the position of the monitor
    customDataobjectConfiguration for custom data: { value: number, name: string, round: number, info: string }
    chartobjectGraph configuration: { hz: number, length: number }
  2. How PerfHeadless collects and stores performance data

    main

    PerfHeadless operates by intercepting the Three.js onBeforeRender and onAfterRender lifecycle methods and integrating with @react-three/fiber's addEffect and addAfterEffect hooks.

    Data Flow

    1. Initialization: PerfHeadless creates a GLPerf instance and sets up the WebGL context info (renderer, vendor, version).
    2. Lifecycle Hooking: It patches THREE.Scene.prototype to mark the start and end of the profiler session during the render loop.
    3. Metric Collection:
      • GPU/GL Metrics: It reads gl.info for calls, triangles, points, and lines.
      • System Metrics: It uses window.performance to track CPU and timing.
      • Deep Analysis: If deepAnalyze is enabled, it traverses the scene to map WebGL programs back to specific materials and meshes.
    4. Storage: All collected data (logs, charts, accumulated totals, and max values) is pushed to the central store via setPerf().

    Accessing Data

    You can retrieve the current state of the profiler using getPerf() from the ../store module.

  3. Enable deep analysis mode

    main
    Setting deepAnalyze={true} on the Perf component unlocks additional tabs such as 'Programs' and 'Infos'. This is useful for inspecting shaders and other low-level Three.js information. When deepAnalyze is active, the UI provides a toggle to expand or minimize these detailed views.
  4. Use the Perf component for visual monitoring

    main

    To monitor the performance of your @react-three/fiber application with a visual interface, add the <Perf /> component anywhere inside your <Canvas /> component.

    import { Canvas } from '@react-three/fiber'
    import { Perf } from 'r3f-perf'
    
    function App() {
      return (
        <Canvas>
          <Perf />
        </Canvas>
      )
    }
  5. Use PerfHeadless and usePerf for programmatic access

    main

    If you want to access performance data without rendering the visual UI, use <PerfHeadless /> and the usePerf hook.

    usePerf allows you to select specific parts of the performance state. You can also use getReport() for a non-reactive way to retrieve the current report.

    import { Canvas } from '@react-three/fiber'
    import { PerfHeadless, usePerf } from 'r3f-perf'
    
    const PerfHook = () => {
      // getPerf() is also available for non-reactive way
      const [gl, log, getReport] = usePerf((s) => s[(s.gl, s.log, s.getReport)])
      console.log(gl, log, getReport())
      return <PerfHeadless />
    }
    
    function App() {
      return (
        <Canvas>
          <PerfHook />
        </Canvas>
      )
    }
  6. Add custom data to the performance monitor

    main

    You can inject custom metrics into the performance panel using setCustomData. It is recommended to throttle these updates (e.g., to once per second) to maintain readability.

    Import setCustomData and call it within your frame loop or logic.

    import { setCustomData, getCustomData } from 'r3f-perf'
    
    const UpdateCustomData = () => {
      // recommended to throttle to 1sec for readability
      useFrame(() => {
        setCustomData(55 + Math.random() * 5) // will update the panel with the current information
      })
      return null
    }
  7. Configure the Perf component via PerfProps

    main

    The PerfProps interface defines the core performance monitoring configuration. Use these properties to control the frequency of logs, data analysis depth, and custom data visualization.

    Key properties:

    • logsPerSecond: Frequency of performance logging.
    • overClock: Boolean to enable overclocking mode.
    • matrixUpdate: Boolean to enable matrix updates.
    • customData: An object of type customData containing specific numeric values for display.
    • chart: An object of type chart defining the length and frequency (hz) of the performance chart.
    • deepAnalyze: Boolean to enable deeper performance analysis.
    // Example configuration object based on PerfProps
    const perfConfig: PerfProps = {
      logsPerSecond: 60,
      overClock: true,
      customData: {
        name: 1,
        info: 2,
        value: 3,
        round: 4
      },
      chart: {
        length: 100,
        hz: 60
      }
    };
  8. Use the Perf component to monitor performance

    main

    The Perf component is the primary entry point for the r3f-perf library. It provides a visual overlay that monitors GPU/CPU usage, FPS, and other Three.js/R3F metrics. It can be configured to show a graph, run in a minimal mode, or perform deep analysis of programs and info.

    import { Perf } from 'r3f-perf'
    
    function App() {
      return (
        <Canvas>
          <Perf 
            showGraph={true} 
            deepAnalyze={true} 
            position="top-right"
          />
          {/* Your R3F components */}
        </Canvas>
      )
    }
  9. Manage custom data with setCustomData and getCustomData

    main

    You can attach arbitrary metadata to the performance monitor using the custom data API. This is useful for labeling specific scenes, levels, or states in your application.

    • setCustomData: Sets the custom data object.
    • getCustomData: Retrieves the current custom data object.
    import { setCustomData, getCustomData } from 'r3f-perf';
    
    // Set custom metadata
    setCustomData({ level: 'forest', difficulty: 'hard' });
    
    // Retrieve it later
    const data = getCustomData();
  10. Access and manage performance state with usePerf, getPerf, and setPerf

    main

    The r3f-perf store provides hooks and functions to interact with the performance monitoring state.

    • usePerf: A React hook to access the performance state within a component.
    • getPerf: A function to retrieve the current performance state outside of the React lifecycle.
    • setPerf: A function to update the performance state manually.
    import { usePerf, getPerf, setPerf } from 'r3f-perf';
    
    // Inside a component
    const perf = usePerf();
    
    // Outside a component
    const currentPerf = getPerf();
    
    // Updating state
    setPerf({ ... });