### Manual MCP Installation Source: https://github.com/babylonjs/spector.js/blob/master/mcp/README.md Alternatively, navigate to the MCP directory and install dependencies, then install Playwright browsers and build the project. ```bash cd mcp npm install npx playwright install chromium npm run build ``` -------------------------------- ### Webpack Setup for Spector.js Source: https://github.com/babylonjs/spector.js/blob/master/readme.md Steps to set up a new project with Webpack and install Spector.js as a development dependency. ```bash mkdir sample cd sample npm init npm install --save-dev webpack webpack-cli npm install spectorjs --save-dev ``` -------------------------------- ### Install MCP Dependencies Source: https://github.com/babylonjs/spector.js/blob/master/mcp/README.md Run these commands from the Spector.js repository root to install and build the MCP client. ```bash npm run mcp:install npm run mcp:build ``` -------------------------------- ### Install Spector.js via npm Source: https://github.com/babylonjs/spector.js/blob/master/readme.md Use this command to install the Spector.js library into your application's directory. ```bash npm install spectorjs ``` -------------------------------- ### Clone and Install Spector.js Source: https://github.com/babylonjs/spector.js/blob/master/documentation/build.md Clone the Spector.js repository from GitHub and install its dependencies using npm. ```bash git clone https://github.com/BabylonJS/Spector.js.git cd spector npm install ``` -------------------------------- ### Run Local Development Server Source: https://github.com/babylonjs/spector.js/blob/master/documentation/build.md Compiles and runs a local server with watch commands for live development. Navigate to the embedded sample to start. ```bash npm start ``` -------------------------------- ### Build and Watch Commands Source: https://github.com/babylonjs/spector.js/blob/master/spec/AI_WORKING_SPEC.md Use these npm scripts for building the Spector.js bundle for production or development with watch mode. The 'start' command launches a dev server with watch capabilities. ```bash npm run build:bundle npm run watch npm run start ``` -------------------------------- ### Start Capture Source: https://github.com/babylonjs/spector.js/blob/master/documentation/extension.md Starts capturing WebGL commands for a specific canvas or context until a command limit is reached or a timeout occurs. ```APIDOC ## startCapture ### Description Start a capture on a specific canvas or context. The capture will stop once it reaches the number of commands specified as a parameter, or after 10 seconds. ### Method ```javascript spector.startCapture(obj: HTMLCanvasElement | RenderingContext, commandCount: number) ``` ### Parameters #### Path Parameters - **obj** (HTMLCanvasElement | RenderingContext) - Required - The canvas element or rendering context to capture. - **commandCount** (number) - Required - The maximum number of GL commands to capture. ``` -------------------------------- ### Setup Colored Triangle Geometry Source: https://github.com/babylonjs/spector.js/blob/master/test/integration/fixtures/test-scene.html Defines and buffers vertex data for a colored triangle. Sets up attribute pointers for position and color. ```javascript var vertices = new Float32Array([ // top vertex - red 0.0, 0.7, 1.0, 0.0, 0.0, // bottom-left - green -0.7, -0.5, 0.0, 1.0, 0.0, // bottom-right - blue 0.7, -0.5, 0.0, 0.0, 1.0 ]); var buffer = gl.createBuffer(); gl.bindBuffer(gl.ARRAY_BUFFER, buffer); gl.bufferData(gl.ARRAY_BUFFER, vertices, gl.STATIC_DRAW); var STRIDE = 5 * Float32Array.BYTES_PER_ELEMENT; var aPosition = gl.getAttribLocation(program, "aPosition"); gl.enableVertexAttribArray(aPosition); gl.vertexAttribPointer(aPosition, 2, gl.FLOAT, false, STRIDE, 0); var aColor = gl.getAttribLocation(program, "aColor"); gl.enableVertexAttribArray(aColor); gl.vertexAttribPointer(aColor, 3, gl.FLOAT, false, STRIDE, 2 * Float32Array.BYTES_PER_ELEMENT); ``` -------------------------------- ### Start Capture with Spector.js Source: https://github.com/babylonjs/spector.js/blob/master/documentation/apis.md Begin capturing commands on a specific canvas or context. The capture stops after a set number of commands or 10 seconds. `quickCapture` omits thumbnails for faster capture. ```javascript spector.startCapture(obj, commandCount, quickCapture); ``` -------------------------------- ### Get Textures Tool Source: https://github.com/babylonjs/spector.js/blob/master/mcp/README.md List all texture uploads from the last capture with their dimensions, format, and type using the `get_textures` tool. ```json { "tool": "get_textures" } ``` -------------------------------- ### Get Shaders Tool Source: https://github.com/babylonjs/spector.js/blob/master/mcp/README.md Retrieve the source code for vertex and fragment shaders, along with their compile and link status, using the `get_shaders` tool. ```json { "tool": "get_shaders" } ``` -------------------------------- ### Initialize WebGL 2 Context Source: https://github.com/babylonjs/spector.js/blob/master/test/integration/fixtures/test-scene.html Gets the WebGL 2 rendering context for the canvas. Falls back to WebGL 1 if WebGL 2 is not available. Displays an error if neither is supported. ```javascript var canvas = document.getElementById("renderCanvas"); var gl = canvas.getContext("webgl2", { preserveDrawingBuffer: true }); if (!gl) { // Fall back to WebGL 1 if WebGL 2 is unavailable (e.g. SwiftShader). gl = canvas.getContext("webgl", { preserveDrawingBuffer: true }); } if (!gl) { document.body.textContent = "WebGL not supported"; return; } ``` -------------------------------- ### Get Context Info Tool Source: https://github.com/babylonjs/spector.js/blob/master/mcp/README.md Retrieve detailed information about the WebGL context, including version, supported extensions, capabilities, and the renderer, using `get_context_info`. ```json { "tool": "get_context_info" } ``` -------------------------------- ### Run TSLint Source: https://github.com/babylonjs/spector.js/blob/master/documentation/build.md Executes TSLint locally to check code style and quality before submitting a Pull Request. Recommended to install the TSLint plugin in VSCode for easier integration. ```bash npm run build:tslint ``` -------------------------------- ### Capture Main-thread OffscreenCanvas with Spector.js Source: https://github.com/babylonjs/spector.js/blob/master/readme.md Use `captureCanvas` with an OffscreenCanvas on the main thread. No special setup is required beyond initializing Spector and adding a capture listener. ```javascript var spector = new SPECTOR.Spector(); var offscreen = new OffscreenCanvas(800, 600); var gl = offscreen.getContext('webgl2'); // ... render ... spector.onCapture.add(function(capture) { console.log('Captured', capture.commands.length, 'commands'); }); spector.captureCanvas(offscreen); ``` -------------------------------- ### Get WebGL State Tool Source: https://github.com/babylonjs/spector.js/blob/master/mcp/README.md Compare the initial and final WebGL states for a captured frame using `get_webgl_state`. This highlights all changes made during the frame. ```json { "tool": "get_webgl_state" } ``` -------------------------------- ### Get Command Details Tool Source: https://github.com/babylonjs/spector.js/blob/master/mcp/README.md Obtain detailed WebGL state information for a specific command using `get_command_details`. This includes states like blending, depth, stencil, and bound textures. ```json { "tool": "get_command_details", "args": { "command_id": 123 } } ``` -------------------------------- ### Get Current FPS in Spector.js Source: https://github.com/babylonjs/spector.js/blob/master/documentation/apis.md Retrieve the current frames per second (FPS) for the selected canvas. ```javascript spector.getFps(); ``` -------------------------------- ### Get Draw Calls Tool Source: https://github.com/babylonjs/spector.js/blob/master/mcp/README.md Retrieve a list of all draw calls from the most recent capture using the `get_draw_calls` tool. This includes command IDs, names, and arguments. ```json { "tool": "get_draw_calls" } ``` -------------------------------- ### Get Console Logs Tool Source: https://github.com/babylonjs/spector.js/blob/master/mcp/README.md Fetch browser console logs, including errors and warnings, with the `get_console_logs` tool. This is useful for catching JavaScript errors and WebGL warnings. ```json { "tool": "get_console_logs" } ``` -------------------------------- ### Stop Capture and Get Result in Spector.js Source: https://github.com/babylonjs/spector.js/blob/master/documentation/apis.md Stop the current capture and return the result as a JSON object. If the UI is displayed, the result will also be shown. Returns undefined if the capture is incomplete or has no commands. ```javascript spector.stopCapture(); ``` -------------------------------- ### Instantiate and Display UI Source: https://github.com/babylonjs/spector.js/blob/master/readme.md Demonstrates how to create a Spector instance and display its embedded UI directly in the web page. ```APIDOC ## Basic Usage ### Instantiate Spector ```javascript var spector = new SPECTOR.Spector(); ``` ### Display UI ```javascript spector.displayUI(); ``` ``` -------------------------------- ### Instantiate Spector Source: https://github.com/babylonjs/spector.js/blob/master/readme.md Initialize Spector.js in your application. This is the first step to enable debugging capabilities. ```javascript var spector = new SPECTOR.Spector(); ``` -------------------------------- ### Initialize Spector.js Spector Instance Source: https://github.com/babylonjs/spector.js/blob/master/documentation/apis.md Create a new instance of the Spector class. This is the main entry point for Spector.js functionality. ```javascript new SPECTOR.Spector(); ``` -------------------------------- ### Webpack Entry Point with Spector.js Source: https://github.com/babylonjs/spector.js/blob/master/readme.md A JavaScript file demonstrating how to require and initialize Spector.js within a Webpack project. ```javascript var SPECTOR = require("spectorjs"); var spector = new SPECTOR.Spector(); spector.displayUI(); ``` -------------------------------- ### JavaScript for Dynamic Sample Loading in Spector.js Source: https://github.com/babylonjs/spector.js/blob/master/sample/index.html Configures JavaScript to dynamically load sample scenes based on URL query parameters. It includes logic to select a specific JS file or default to 'lights.js'. ```javascript // Allow querystring to navigate easily in debug in local samples. var indexjs = 'js/'; var sampleSearch = /sample=([0-9-zA-z]+)/i; var matches = null; if ((matches = sampleSearch.exec(window.location)) !== null) { indexjs += matches[1]; } else { indexjs += 'lights'; } indexjs += '.js'; spector = null; // Load the scripts + map file to allow vscode debug. SPECTORTOOLS.Loader .onReady(function () { console.log('All loaded.'); }) .load([indexjs]); ``` -------------------------------- ### Bundle JavaScript with Webpack Source: https://github.com/babylonjs/spector.js/blob/master/readme.md Command to bundle your entry JavaScript file using Webpack. ```bash npx webpack entry.js ``` -------------------------------- ### Build Spector.js Distribution Files Source: https://github.com/babylonjs/spector.js/blob/master/documentation/build.md Creates and builds new version of the distribution folder files. ```bash npm run build ``` -------------------------------- ### Configure MCP Client for VS Code (Copilot) Source: https://github.com/babylonjs/spector.js/blob/master/mcp/README.md Add this JSON configuration to your `.vscode/mcp.json` file, replacing `` with the absolute path to your Spector.js clone. ```json { "servers": { "spector": { "type": "stdio", "command": "node", "args": ["/mcp/dist/index.js"] } } } ``` -------------------------------- ### MCP Server Architecture Overview Source: https://github.com/babylonjs/spector.js/blob/master/mcp/README.md Illustrates the communication flow between an AI Assistant, the MCP Server, Playwright, and the target WebGL website with Spector.js. ```text AI Assistant ←→ MCP Server (stdio) ←→ Playwright (headless Chromium) ←→ Any WebGL Website + Spector.js ``` -------------------------------- ### Spector.js Integration Source: https://github.com/babylonjs/spector.js/blob/master/test/integration/fixtures/test-scene.html Initializes Spector.js and displays its UI. The Spector instance and canvas are exposed globally for debugging. ```javascript var spector = new SPECTOR.Spector(); spector.displayUI(); window.__spector = spector; window.__canvas = canvas; ``` -------------------------------- ### Configure MCP Client for Claude Code / Copilot CLI Source: https://github.com/babylonjs/spector.js/blob/master/mcp/README.md Add this JSON configuration to your MCP settings, replacing `` with the absolute path to your Spector.js clone. ```json { "mcpServers": { "spector": { "command": "node", "args": ["/mcp/dist/index.js"] } } } ``` -------------------------------- ### Development Commands Source: https://github.com/babylonjs/spector.js/blob/master/mcp/README.md Run Spector.js in development mode using tsx, build the project, or run the built version. ```bash npm run dev # Run with tsx (no build needed) npm run build # Build to dist/ npm start # Run the built version ``` -------------------------------- ### Configure MCP Client for Spector.js Server Source: https://github.com/babylonjs/spector.js/blob/master/readme.md Add this configuration to your MCP client's config file to connect to the Spector.js MCP server. Replace `` with the actual path to your Spector.js repository. ```json { "mcpServers": { "spector": { "command": "node", "args": ["/mcp/dist/index.js"] } } } ``` -------------------------------- ### Compile and Link Shaders Source: https://github.com/babylonjs/spector.js/blob/master/test/integration/fixtures/test-scene.html Compiles vertex and fragment shaders, then links them into a program. Throws an error if compilation or linking fails. ```javascript var VERT_SRC = "attribute vec2 aPosition;\n" + "attribute vec3 aColor;\n" + "varying vec3 vColor;\n" + "void main() {\n" + " gl_Position = vec4(aPosition, 0.0, 1.0);\n" + " vColor = aColor;\n" + "}\n"; var FRAG_SRC = "precision mediump float;\n" + "varying vec3 vColor;\n" + "void main() {\n" + " gl_FragColor = vec4(vColor, 1.0);\n" + "}\n"; function compileShader(type, src) { var shader = gl.createShader(type); gl.shaderSource(shader, src); gl.compileShader(shader); if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) { throw new Error("Shader compile error: " + gl.getShaderInfoLog(shader)); } return shader; } var vertShader = compileShader(gl.VERTEX_SHADER, VERT_SRC); var fragShader = compileShader(gl.FRAGMENT_SHADER, FRAG_SRC); var program = gl.createProgram(); gl.attachShader(program, vertShader); gl.attachShader(program, fragShader); gl.linkProgram(program); if (!gl.getProgramParameter(program, gl.LINK_STATUS)) { throw new Error("Program link error: " + gl.getProgramInfoLog(program)); } gl.useProgram(program); ``` -------------------------------- ### Load URL Tool Source: https://github.com/babylonjs/spector.js/blob/master/mcp/README.md Use the `load_url` tool to navigate to any web address and prepare it for WebGL debugging with Spector.js. This tool is compatible with all WebGL websites. ```json { "tool": "load_url", "args": { "url": "https://example.com" } } ``` -------------------------------- ### Load Babylon.js Playground Tool Source: https://github.com/babylonjs/spector.js/blob/master/mcp/README.md The `load_playground` tool is a shortcut to load a Babylon.js Playground using its snippet ID. It returns the source code and a screenshot of the playground. ```json { "tool": "load_playground", "args": { "id": "some-playground-id" } } ``` -------------------------------- ### Capture Canvas and Handle Capture Event Source: https://github.com/babylonjs/spector.js/blob/master/readme.md Shows how to capture a specific canvas and attach a listener to process the capture data, including dispatching a custom event. ```APIDOC ## Basic Usage ### Capture Canvas ```javascript spector.onCapture.add((capture) => { // Do something with capture. var myEvent = new CustomEvent("SpectorOnCaptureEvent", { detail: { captureString: JSON.stringify(capture) } }); document.dispatchEvent(myEvent); }); var canvas = document.getElementById("renderCanvas"); spector.captureCanvas(canvas); ``` ``` -------------------------------- ### Capture Next Frame with Spector.js Source: https://github.com/babylonjs/spector.js/blob/master/documentation/apis.md Initiate a capture of the next frame for a specified canvas or context. Setting `quickCapture` to true speeds up the process by omitting thumbnails. ```javascript spector.captureNextFrame(obj, quickCapture); ``` -------------------------------- ### Basic HTML and CSS for Spector.js Canvas Source: https://github.com/babylonjs/spector.js/blob/master/sample/index.html Sets up the basic HTML and CSS to ensure the render canvas takes up the full viewport. This is essential for Spector.js applications. ```css html, body { width: 100%; height: 100%; padding: 0; margin: 0; overflow: hidden; } #renderCanvas { width: 100%; height: 100%; } ``` -------------------------------- ### SPECTOR.Spector Methods Source: https://github.com/babylonjs/spector.js/blob/master/documentation/apis.md The main entry point for Spector.js, providing methods to control capturing, UI display, and data logging. ```APIDOC ## SPECTOR.Spector This is the main entry point of the library and contains the following methods: ### constructor() Creates a new instance of Spector. ### displayUI() Displays the embedded UI and begins to track the pages available canvas elements. ### spyCanvases() Enables recording some extra information merged in the capture like texture memory sizes and formats. This should be launched before you update the texture objects. ### getFps() Returns the current FPS of the selected canvas. ### captureNextFrame(obj: HTMLCanvasElement | RenderingContext, quickCapture: boolean) Calls to begin a capture of the next frame of a specific canvas or context. If quick capture is true, the thumbnails are not captured in order to speed up the capture. ### startCapture(obj: HTMLCanvasElement | RenderingContext, commandCount: number, quickCapture: boolean) Starts a capture on a specific canvas or context. The capture will stop once it reaches the number of commands specified as a parameter, or after 10 seconds. If quick capture is true, the thumbnails are not captured in order to speed up the capture. ### stopCapture(): ICapture Stops the current capture and returns the result in JSON. It displays the result if the UI has been displayed. This returns undefined if the capture has not been completed or did not find any commands. ### setMarker(marker: string) Adds a marker that is displayed in the capture, helping you analyze the results. ### clearMarker() Clears the current marker from the capture for any subsequent calls. ### log(value: string) Adds a command with the name value in the list. This can be filtered in the search. All logs can be filtered searching for "LOG". ``` -------------------------------- ### HTML File for Webpack Output Source: https://github.com/babylonjs/spector.js/blob/master/readme.md A basic HTML file to load the bundled JavaScript output from a Webpack build. ```html ``` -------------------------------- ### Run End-to-End Tests Source: https://github.com/babylonjs/spector.js/blob/master/documentation/build.md Runs Playwright E2E tests against Chromium with SwiftShader, covering sample page loading and OffscreenCanvas capture scenarios. ```bash npm run test:e2e ``` -------------------------------- ### Take Screenshot Tool Source: https://github.com/babylonjs/spector.js/blob/master/mcp/README.md Capture a screenshot of the current canvas using the `take_screenshot` tool. ```json { "tool": "take_screenshot" } ``` -------------------------------- ### Select Canvas Tool Source: https://github.com/babylonjs/spector.js/blob/master/mcp/README.md If multiple canvases are present, use the `select_canvas` tool to specify which canvas should be targeted for debugging. ```json { "tool": "select_canvas", "args": { "index": 0 } } ``` -------------------------------- ### Set and Clear Markers in Spector.js Source: https://github.com/babylonjs/spector.js/blob/master/documentation/extension.md Use setMarker and clearMarker to add annotations to your captures. This is useful for pinpointing specific events like shadow map creation during analysis. ```javascript if (spector) { spector.setMarker("Shadow map creation"); } [your shadow creation code] if (spector) { spector.clearMarker(); } ``` -------------------------------- ### Capture Frame Tool Source: https://github.com/babylonjs/spector.js/blob/master/mcp/README.md Capture a single WebGL frame using the `capture_frame` tool. The response includes summary statistics such as the number of commands and draw calls. ```json { "tool": "capture_frame" } ``` -------------------------------- ### Testing Commands Source: https://github.com/babylonjs/spector.js/blob/master/mcp/README.md Execute unit tests for the capture analyzer using Jest. These tests focus on analysis functions like draw call extraction and shader parsing. ```bash npm test ``` -------------------------------- ### Reference Spector.js via Script Tag (CDN) Source: https://github.com/babylonjs/spector.js/blob/master/readme.md Include this script tag in your HTML header to use Spector.js directly from the jsDeliver CDN. ```html ``` -------------------------------- ### Visual Regression Testing Commands Source: https://github.com/babylonjs/spector.js/blob/master/spec/AI_WORKING_SPEC.md Execute Playwright visual regression tests to ensure UI consistency. Use 'update' to regenerate baselines when intentional changes are made. ```bash npm run test:visual npm run test:visual:update ``` -------------------------------- ### ResultViewState Interface Source: https://github.com/babylonjs/spector.js/blob/master/spec/AI_WORKING_SPEC.md Defines the state for the result view, managing visibility, search, capture data, command indexing, and information display. ```typescript interface ResultViewState { visible: boolean; menuStatus: MenuStatus; // enum: Captures | Information | InitState | EndState | Commands | SourceCode searchText: string; captures: Array<{ capture: ICapture; active: boolean }>; currentCapture: ICapture | null; commands: ICommandListItemState[]; currentCommandIndex: number; visualStates: IVisualStateItem[]; currentVisualStateIndex: number; sourceCodeState: ISourceCodeState | null; sourceCodeError: string; commandCount: number; informationLeft: JSONRenderItem[]; // JSON tree for Information tab (left column) informationRight: JSONRenderItem[]; // JSON tree for Information tab (right column) initStateData: JSONRenderItem[]; // JSON tree for Init State tab endStateData: JSONRenderItem[]; // JSON tree for End State tab commandDetailData: JSONRenderItem[]; // JSON tree for selected command detail } ``` -------------------------------- ### Run Unit Tests Source: https://github.com/babylonjs/spector.js/blob/master/documentation/build.md Executes Jest unit tests covering various components like CanvasFactory, TimeSpy, and the message protocol. ```bash npm run test:unit ``` -------------------------------- ### Render Loop Source: https://github.com/babylonjs/spector.js/blob/master/test/integration/fixtures/test-scene.html Clears the canvas and draws the triangle. Uses requestAnimationFrame for continuous rendering, though the scene is static. ```javascript function render() { gl.clearColor(0.1, 0.1, 0.18, 1.0); gl.clear(gl.COLOR_BUFFER_BIT); gl.drawArrays(gl.TRIANGLES, 0, 3); requestAnimationFrame(render); } render(); ``` -------------------------------- ### CaptureMenuState Interface Source: https://github.com/babylonjs/spector.js/blob/master/spec/AI_WORKING_SPEC.md Represents the state of the capture menu, controlling visibility, logging, canvas information, and playback status. ```typescript interface CaptureMenuState { visible: boolean; logText: string; logLevel: LogLevel; // from src/shared/utils/logger logVisible: boolean; canvases: ICanvasInformation[]; selectedCanvas: ICanvasInformation | null; showCanvasList: boolean; isPlaying: boolean; fps: number; } ``` -------------------------------- ### List Canvases Tool Source: https://github.com/babylonjs/spector.js/blob/master/mcp/README.md Use the `list_canvases` tool to retrieve a list of all canvas elements present on the page, including their WebGL context information. ```json { "tool": "list_canvases" } ``` -------------------------------- ### Capture Next Frame Source: https://github.com/babylonjs/spector.js/blob/master/documentation/extension.md Initiates a capture of the very next frame rendered by a specified canvas or rendering context. ```APIDOC ## captureNextFrame ### Description Call to begin a capture of the next frame of a specific canvas or context. ### Method ```javascript spector.captureNextFrame(obj: HTMLCanvasElement | RenderingContext) ``` ### Parameters #### Path Parameters - **obj** (HTMLCanvasElement | RenderingContext) - Required - The canvas element or rendering context to capture. ``` -------------------------------- ### Attach Rebuild Function to WebGLProgram Source: https://github.com/babylonjs/spector.js/blob/master/documentation/extension.md Append the custom rebuild function to your linked WebGLProgram. Ensure the context is bound correctly to run within your engine's scope. ```typescript // program is the linked WebglProgram that Babylon is expanding // with a custom rebuild function. // Noticed we bind the context to ensure it runs as part of your engine and not the program itself. program.__SPECTOR_rebuildProgram = this._rebuildProgram.bind(this); ``` -------------------------------- ### SPECTOR.Spector Worker APIs Source: https://github.com/babylonjs/spector.js/blob/master/documentation/apis.md APIs for integrating Spector.js with Web Workers for capturing. ```APIDOC ## Worker / OffscreenCanvas APIs ### spyWorkers(workerBundleUrl?: string) Intercepts all `new Worker()` calls to auto-inject Spector. Best-effort — may fail with CORS, CSP, or module Workers. Defaults to `"spector.worker.bundle.js"`. ### stopSpyingWorkers() Stops intercepting Worker construction. ### spyWorker(worker: Worker): WorkerBridge Manually bridges a specific Worker for capture. This is the primary, reliable API. The Worker must have `spector.worker.bundle.js` loaded via `importScripts`. ### captureWorker(worker: Worker, commandCount?: number, quickCapture?: boolean, fullCapture?: boolean) Captures a frame from a Worker's WebGL context. If the Worker hasn't been bridged yet, `spyWorker` is called automatically. ``` -------------------------------- ### ExternalStore State Management in React Source: https://github.com/babylonjs/spector.js/blob/master/spec/AI_WORKING_SPEC.md Minimal external store for bridging imperative code and React via `useSyncExternalStore`. Always return a new object reference from `setState` to trigger re-renders. Components subscribe via the `useStore(store)` hook. ```typescript import { useSyncExternalStore } from "react"; export class ExternalStore { private state: State; private listeners: Set<() => void> = new Set(); constructor(state: State) { this.state = state; } public getSnapshot(): State { return this.state; } public subscribe(listener: () => void): () => void { this.listeners.add(listener); return () => this.listeners.delete(listener); } public setState(updater: (prev: State) => State): void { this.state = updater(this.state); this.listeners.forEach(listener => listener()); } } export const useStore = (store: ExternalStore) => { return useSyncExternalStore(store.subscribe, store.getSnapshot); }; ``` -------------------------------- ### Manually Bridge a Worker for Capture in Spector.js Source: https://github.com/babylonjs/spector.js/blob/master/documentation/apis.md Reliably bridge a specific Worker for capture. The Worker must have `spector.worker.bundle.js` loaded via `importScripts`. ```javascript spector.spyWorker(worker); ``` -------------------------------- ### Add Event Listener in Spector.js Source: https://github.com/babylonjs/spector.js/blob/master/documentation/apis.md Attach event listeners to Spector.js events. Use the second argument to specify a context for the event handler. ```javascript foo.onEvent.add(function(s) { console.log(s); }; ``` ```javascript foo.onEvent.add(function(s) { console.log(s); }, context); ``` -------------------------------- ### Display Spector.js UI Source: https://github.com/babylonjs/spector.js/blob/master/documentation/apis.md Display the embedded Spector.js UI. This will also begin tracking available canvas elements on the page. ```javascript spector.displayUI(); ``` -------------------------------- ### Clean Generated Files Source: https://github.com/babylonjs/spector.js/blob/master/documentation/build.md Removes all generated files from the repository. ```bash npm run clean ``` -------------------------------- ### Enable Extra Capture Information in Spector.js Source: https://github.com/babylonjs/spector.js/blob/master/documentation/apis.md Enable the recording of extra information, such as texture memory sizes and formats, within captures. This should be called before updating texture objects. ```javascript spector.spyCanvases(); ``` -------------------------------- ### Add Custom Metadata to WebGL Objects Source: https://github.com/babylonjs/spector.js/blob/master/readme.md Explains how to add custom data, such as a 'name', to WebGL objects using the `__SPECTOR_Metadata` property, which will be visible in captures for easier troubleshooting and referencing. ```APIDOC ## Custom Data ### Add Custom Metadata ```javascript var cubeVerticesColorBuffer = gl.createBuffer(); cubeVerticesColorBuffer.__SPECTOR_Metadata = { name: "cubeVerticesColorBuffer" }; ``` ``` -------------------------------- ### Set Marker for Capture Analysis in Spector.js Source: https://github.com/babylonjs/spector.js/blob/master/documentation/apis.md Add a marker to the capture, which will be displayed during analysis to help identify specific points in the captured sequence. ```javascript spector.setMarker(marker); ``` -------------------------------- ### Bridge and Capture Worker OffscreenCanvas (Manual API) Source: https://github.com/babylonjs/spector.js/blob/master/readme.md Manually bridge a specific Worker using `spyWorker` and then trigger a capture with `captureWorker`. The Worker must load `spector.worker.bundle.js`. ```javascript var spector = new SPECTOR.Spector(); var worker = new Worker('myWorker.js'); // Bridge the Worker for capture spector.spyWorker(worker); // Capture from the Worker spector.onCapture.add(function(capture) { console.log('Captured from Worker:', capture.commands.length, 'commands'); spector.getResultUI().display(); spector.getResultUI().addCapture(capture); }); spector.captureWorker(worker); ``` ```javascript importScripts('spector.worker.bundle.js'); // OffscreenCanvas received via message or created directly var canvas = new OffscreenCanvas(800, 600); var gl = canvas.getContext('webgl2'); function render() { // ... draw calls ... setTimeout(render, 16); // rAF may not be available in Workers } render(); ``` -------------------------------- ### Capture Canvas and Handle Capture Data Source: https://github.com/babylonjs/spector.js/blob/master/readme.md Capture the contents and WebGL calls of a specific canvas element. It also demonstrates how to listen for capture events and process the capture data. ```javascript spector.onCapture.add((capture) => { // Do something with capture. var myEvent = new CustomEvent("SpectorOnCaptureEvent", { detail: { captureString: JSON.stringify(capture) } }); document.dispatchEvent(myEvent); }); var canvas = document.getElementById("renderCanvas"); spector.captureCanvas(canvas); ``` -------------------------------- ### Auto-inject Spector into Workers Source: https://github.com/babylonjs/spector.js/blob/master/readme.md Use `spyWorkers` to automatically inject the Spector bundle into all new Workers created via `new Worker()`. This is a best-effort approach and may fail under certain conditions. ```javascript var spector = new SPECTOR.Spector(); spector.spyWorkers('spector.worker.bundle.js'); // All subsequent new Worker() calls get Spector injected automatically // Stop intercepting: // spector.stopSpyingWorkers(); ``` -------------------------------- ### Intercept Worker Calls with Spector.js Source: https://github.com/babylonjs/spector.js/blob/master/documentation/apis.md Automatically inject Spector.js into all new Worker calls. This is a best-effort approach and may encounter issues with CORS, CSP, or module Workers. Defaults to 'spector.worker.bundle.js'. ```javascript spector.spyWorkers(workerBundleUrl?); ``` -------------------------------- ### Define Shader Rebuild Function Signature Source: https://github.com/babylonjs/spector.js/blob/master/documentation/extension.md This is the signature for the rebuild function that Spector.js expects. Implement this in your engine to allow recompilation and state management of shaders. ```typescript rebuildProgram(vertexSourceCode: string, // The new vertex shader source fragmentSourceCode: string, // The new fragment shader source onCompiled: (program: WebGLProgram) => void, // Callback triggered by your engine when the compilation is successful. It needs to send back the new linked program. onError: (message: string) => void): void; // Callback triggered by your engine in case of error. It needs to send the WebGL error to allow the editor to display the error in the gutter. ``` -------------------------------- ### ICommandListItemState Interface Source: https://github.com/babylonjs/spector.js/blob/master/spec/AI_WORKING_SPEC.md Defines the state for a command list item, including active status and indices for navigating linked lists of commands and visual states. ```typescript interface ICommandListItemState { capture: ICommandCapture; active: boolean; visualStateIndex: number; previousCommandIndex: number; nextCommandIndex: number; } ``` -------------------------------- ### Set Marker Source: https://github.com/babylonjs/spector.js/blob/master/documentation/extension.md Adds a marker to the capture data, which can be used for easier analysis of specific events or code sections. ```APIDOC ## setMarker ### Description Adds a marker that is displayed in the capture, helping you analyze the results. ### Method ```javascript spector.setMarker(marker: string) ``` ### Parameters #### Path Parameters - **marker** (string) - Required - The marker text to add to the capture. ``` -------------------------------- ### Spy on Canvases Source: https://github.com/babylonjs/spector.js/blob/master/readme.md Enables comprehensive tracking of WebGL calls on all canvases, allowing access to information like texture inputs and memory consumption even before a capture. ```APIDOC ## Basic Usage ### Spy Canvases ```javascript spector.spyCanvases(); ``` ``` -------------------------------- ### Add Custom Metadata to WebGL Objects Source: https://github.com/babylonjs/spector.js/blob/master/readme.md Assign custom names or metadata to WebGL objects, such as buffers, by adding a `__SPECTOR_Metadata` property. This aids in identifying and referencing these objects within Spector.js captures. ```javascript var cubeVerticesColorBuffer = gl.createBuffer(); cubeVerticesColorBuffer.__SPECTOR_Metadata = { name: "cubeVerticesColorBuffer" }; ``` -------------------------------- ### Stop Capture Source: https://github.com/babylonjs/spector.js/blob/master/documentation/extension.md Stops the current capture and returns the captured data. If the UI has been displayed, it will also show the results. ```APIDOC ## stopCapture ### Description Stop the current capture and returns the result in JSON. It displays the result if the UI has been displayed. This returns undefined if the capture has not been completed or did not find any commands. ### Method ```javascript spector.stopCapture(): ICapture ``` ### Response #### Success Response (200) - **ICapture** - The captured data or undefined if capture failed. ``` -------------------------------- ### Capture Frame from Worker's WebGL Context in Spector.js Source: https://github.com/babylonjs/spector.js/blob/master/documentation/apis.md Capture a frame from a Worker's WebGL context. If the Worker is not yet bridged, `spyWorker` is called automatically. ```javascript spector.captureWorker(worker, commandCount?, quickCapture?, fullCapture?); ``` -------------------------------- ### SPECTOR.Spector Events Source: https://github.com/babylonjs/spector.js/blob/master/documentation/apis.md Events that can be listened to for various capture-related occurrences. ```APIDOC ## SPECTOR.Spector Events And the following list of events: ### onCaptureStarted: IEvent Triggered when a capture starts. ### onCapture: IEvent Triggered when a new capture is available (this is a JSON only object containing all the information). ### onError: IEvent Triggered when an error occurred and returns the error message. ``` -------------------------------- ### Stop Intercepting Worker Calls in Spector.js Source: https://github.com/babylonjs/spector.js/blob/master/documentation/apis.md Halt the interception of Worker construction calls made by Spector.js. ```javascript spector.stopSpyingWorkers(); ``` -------------------------------- ### Log Custom Message in Spector.js Capture Source: https://github.com/babylonjs/spector.js/blob/master/documentation/apis.md Add a custom log message to the capture, which can be filtered by searching for 'LOG'. This helps in annotating and debugging captured sequences. ```javascript spector.log(value); ``` -------------------------------- ### Clear Marker Source: https://github.com/babylonjs/spector.js/blob/master/documentation/extension.md Removes the currently set marker from the capture data. ```APIDOC ## clearMarker ### Description Clears the current marker from the capture for any subsequent calls. ### Method ```javascript spector.clearMarker() ``` ``` -------------------------------- ### JSONRenderItem Discriminated Union Type Source: https://github.com/babylonjs/spector.js/blob/master/spec/AI_WORKING_SPEC.md A discriminated union type for rendering JSON data, supporting groups, items, images, help text, and visual states. ```typescript type JSONRenderItem = | { type: "group"; title: string; children: JSONRenderItem[] } | { type: "item"; key: string; value: string } | { type: "image"; key: string; value: string; pixelated: boolean } | { type: "help"; key: string; value: string; help: string } | { type: "visualState"; visualState: any }; ``` -------------------------------- ### Clear Marker in Spector.js Capture Source: https://github.com/babylonjs/spector.js/blob/master/documentation/apis.md Remove the current marker from the capture. Any subsequent calls will not be associated with this marker. ```javascript spector.clearMarker(); ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.