### Read getting started documentation Source: https://vgpu.sh/docs/guides/shader-workflow Access the primary API overview before initializing any shader projects. ```bash npx vgpu docs cat getting-started.md ``` -------------------------------- ### View Non-Bundler Setup Guides Source: https://vgpu.sh/docs/guides/getting-started Documentation for using vgpu in environments without a bundler. ```bash vgpu docs cat no-bundler.md # resolveShader(), headless Node rendering, ESM + CommonJS usage ``` -------------------------------- ### Show vgpu example metadata Source: https://vgpu.sh/docs/cli Lists files and metadata for a specific example ID. ```bash npx vgpu examples show npx vgpu examples show raymarched-fractal --pretty ``` -------------------------------- ### Search vgpu examples Source: https://vgpu.sh/docs/cli Finds examples in the gallery using a query string. ```bash npx vgpu examples search npx vgpu examples search "raymarching hdr" --any --limit 10 --pretty ``` -------------------------------- ### GET /.well-known/vgpu-examples.json Source: https://vgpu.sh/docs/examples-api Retrieves the entry point for the vgpu examples API, listing supported contracts and links to the latest mutable pointer. ```APIDOC ## GET /.well-known/vgpu-examples.json ### Description Lists supported contracts and provides links to the mutable latest pointer for vgpu examples. ### Method GET ### Endpoint /.well-known/vgpu-examples.json ### Response #### Success Response (200) - **contracts** (array) - List of supported contracts - **latestUrl** (string) - URL to the latest mutable pointer ``` -------------------------------- ### Pull vgpu example source Source: https://vgpu.sh/docs/cli Copies an example's complete source code into a local directory. ```bash npx vgpu examples pull --out npx vgpu examples pull raymarched-fractal --out ./fractal --pretty ``` -------------------------------- ### examples:read Source: https://vgpu.sh/docs/mcp Read one verified file from an example. ```APIDOC ## examples:read ### Description Read one verified file from an example. ### Parameters - **id** (string) - Required - The example ID. - **path** (string) - Required - The file path within the example. - **offline** (boolean) - Optional - Prohibit network access. - **offset** (integer) - Optional - UTF-16 offset for reading. - **limit** (integer) - Optional - Limit for code units (max 65,536). ``` -------------------------------- ### Run Three.js TSL example commands Source: https://vgpu.sh/docs/guides/threejs Commands to execute the test suite or start the development server for the Three.js TSL example package. ```bash pnpm --filter @vgpu/example-three-tsl test pnpm --filter @vgpu/example-three-tsl dev ``` -------------------------------- ### Manage vgpu examples cache Source: https://vgpu.sh/docs/cli Performs maintenance on the local example cache. ```bash npx vgpu examples cache path npx vgpu examples cache clear ``` -------------------------------- ### Initialize and Use OrbitControls Source: https://vgpu.sh/docs/reference/vgpu-scene/orbit-controls Example showing camera setup, control initialization, state updates, and disposal. ```ts import { orbitControls, perspectiveCamera } from "vgpu/scene"; const camera = perspectiveCamera({ fov: 45, position: [0, 0, 5], target: [0, 0, 0] }); const controls = orbitControls(camera, { damping: 0 }); controls.set({ yaw: Math.PI / 2, distance: 8 }); controls.update(); controls.dispose(); ``` -------------------------------- ### Interact with examples via CLI Source: https://vgpu.sh/docs/examples-api Use the vgpu CLI to list, search, inspect, and pull examples without manually implementing the API protocol. ```bash npx vgpu examples npx vgpu examples search gradient npx vgpu examples show gradient npx vgpu examples pull gradient --out ./gradient ``` -------------------------------- ### Print vgpu example file content Source: https://vgpu.sh/docs/cli Outputs the source code of a specific file within an example. ```bash npx vgpu examples cat npx vgpu examples cat raymarched-fractal renderer.ts npx vgpu examples cat raymarched-fractal renderer.ts --json ``` -------------------------------- ### Install Dawn binary Source: https://vgpu.sh/docs/get-started/node Manually trigger the download and installation of the Dawn binary. ```bash npx vgpu install-dawn ``` -------------------------------- ### View Framework Integration Guides Source: https://vgpu.sh/docs/guides/getting-started Documentation for integrating vgpu with Next.js or Vite. ```bash vgpu docs cat nextjs.md # Next.js (Turbopack or webpack), Vite, .wgsl types, canvas component ``` -------------------------------- ### Install Dawn Prebuild Source: https://vgpu.sh/docs/reference/vgpu-adapter-node/create-node-adapter Commands to manually install or verify the Dawn prebuild binary for the current environment. ```bash pnpm exec vgpu install-dawn # or npx vgpu install-dawn ``` -------------------------------- ### Install vgpu package Source: https://vgpu.sh/docs/get-started/web Install the vgpu package via npm. ```bash npm install vgpu ``` -------------------------------- ### Install vgpu and three.js dependencies Source: https://vgpu.sh/docs/guides/threejs Install the required vgpu packages and three.js version compatible with the reference implementation. ```bash npm install @vgpu/wgsl @vgpu/wgsl-std three@^0.180.0 npm install --save-dev @types/three@^0.180.0 vite typescript ``` -------------------------------- ### View Performance and Testing Guides Source: https://vgpu.sh/docs/guides/getting-started Documentation for performance optimization and browser testing. ```bash vgpu docs cat /guides/performance-model.docs.md vgpu docs cat /guides/performance-patterns.docs.md vgpu docs cat browser-testing ``` -------------------------------- ### View Concept Guides Source: https://vgpu.sh/docs/guides/getting-started List of available concept documentation files for sequential learning. ```bash vgpu docs cat concepts-context.md # the Gpu context, surfaces, targets vgpu docs cat concepts-wgsl-modules.md # split shaders with import and export vgpu docs cat concepts-draws.md # draw(), meshes, instancing vgpu docs cat concepts-compilation.md # compile() and pipeline warmup vgpu docs cat concepts-effects.md # fragment effects and set() vgpu docs cat concepts-passes.md # frame.pass and multi-pass work vgpu docs cat concepts-frames.md # frame batching and animation loops vgpu docs cat concepts-render-bundles.md # record draws once, replay cheap ``` -------------------------------- ### List vgpu documentation paths Source: https://vgpu.sh/docs/guides/shader-workflow Use these commands to explore the available documentation categories and specific guide files. ```bash npx vgpu docs ls # top-level paths: /guides plus one entry per package npx vgpu docs ls /guides # every guide, by file name ``` -------------------------------- ### Initialize FullscreenQuadOptions Source: https://vgpu.sh/docs/reference/vgpu-scene/geometry Example of initializing the empty options object. ```ts import type { FullscreenQuadOptions } from "vgpu/scene"; const passthrough: FullscreenQuadOptions = {}; ``` -------------------------------- ### View Rendering Recipe Guides Source: https://vgpu.sh/docs/guides/getting-started Documentation for implementing two-pass rendering for 3D scenes. ```bash vgpu docs cat two-pass-rendering.md # offscreen depth target -> composite to canvas ``` -------------------------------- ### Install and validate agent-browser environment Source: https://vgpu.sh/docs/guides/agent-browser-webgpu Install the package and verify the environment with the doctor command, ensuring Vulkan and virtual-display dependencies are present on Linux. ```bash npm i -g agent-browser@latest apt-get install -y libvulkan1 mesa-vulkan-drivers xvfb xauth agent-browser doctor --webgpu --headed ``` -------------------------------- ### Initialize a camera Source: https://vgpu.sh/docs/reference/vgpu-scene/camera Example of creating a camera using the perspectiveCamera helper and assigning it to the Camera type. ```ts import type { Camera } from "vgpu/scene"; import { perspectiveCamera } from "vgpu/scene"; const camera: Camera = perspectiveCamera({ fov: 60, aspect: 16 / 9, position: [0, 2, 4], target: [0, 0, 0], }); ``` -------------------------------- ### Install Software Renderer Source: https://vgpu.sh/docs/cli Downloads and verifies a portable CPU renderer for environments without a usable GPU. ```text Usage: vgpu install-software-renderer Download and sha256-verify the portable CPU software renderer for this platform. Honors VGPU_CACHE_DIR. ``` ```bash npx vgpu install-software-renderer ``` -------------------------------- ### WGSL function emission examples Source: https://vgpu.sh/docs/guides/threejs Examples of the underlying WGSL functions and the forwarding wrappers generated by the helper. ```wgsl fn _vgsl_1234abcd__surfaceRoughness(position: vec3f, timeSeconds: f32) -> f32 { // ... } ``` ```wgsl fn surfaceRoughness_vtsl(position: vec3f, timeSeconds: f32) -> f32 { return _vgsl_1234abcd__surfaceRoughness(position, timeSeconds); } ``` -------------------------------- ### Install software renderer Source: https://vgpu.sh/docs/reference/vgpu-adapter-node/create-node-device Download and cache the portable lavapipe build for CPU-based rendering. ```bash npx vgpu install-software-renderer ``` -------------------------------- ### Create CapsuleOptions Instance Source: https://vgpu.sh/docs/reference/vgpu-scene/geometry Example of initializing a CapsuleOptions object with specific height. ```ts import type { CapsuleOptions } from "vgpu/scene"; const short: CapsuleOptions = { height: 0.5 }; ``` -------------------------------- ### Initialize OrbitControls Source: https://vgpu.sh/docs/reference/vgpu-scene/orbit-controls Example of initializing orbit controls with specific camera and control parameters. ```ts import { orbitControls, perspectiveCamera } from "vgpu/scene"; orbitControls(perspectiveCamera({ fov: 45, position: [0, 0, 5] }), { target: [0, 0.5, 0], distance: { min: 1, max: 20 }, pitch: { min: -1.2, max: 1.2 }, }); ``` -------------------------------- ### Start VGPU MCP Stdio Server Source: https://vgpu.sh/docs/cli Launch the server locally without filesystem write access. ```bash npx vgpu mcp ``` -------------------------------- ### Run vgpu CLI commands Source: https://vgpu.sh/docs/cli Execute CLI commands using npx. The examples command does not execute fetched code. ```bash npx vgpu [args] [flags] npx vgpu --help npx vgpu --version ``` -------------------------------- ### docs:read Source: https://vgpu.sh/docs/mcp Read a resolved guide or API document. ```APIDOC ## docs:read ### Description Read a resolved guide or API document. ### Parameters - **target** (string) - Required - The document target to read. - **offset** (integer) - Optional - UTF-16 offset for reading. - **limit** (integer) - Optional - Limit for code units (max 65,536). ``` -------------------------------- ### Create and Configure MeshNode Source: https://vgpu.sh/docs/reference/vgpu-scene/scene-tree Example of creating a mesh node and assigning a material. ```ts import { box, mesh, unlitMaterial } from "vgpu/scene"; const node = mesh(box()); node.material = unlitMaterial({ color: [1, 0, 0] }); ``` -------------------------------- ### Initialize and Render to a Surface Source: https://vgpu.sh/docs/reference/vgpu/surface Basic setup for initializing a GPU surface and rendering a fragment effect to a canvas. ```typescript import { init, effect, frame, surface } from "vgpu"; declare const canvas: HTMLCanvasElement; const gpu = await init(); const canvasSurface = surface(gpu, canvas, { dpr: [1, 2] }); const wave = effect(gpu, `@fragment fn fs_main() -> @location(0) vec4f { return vec4f(0.2, 0.6, 1, 1); }`); frame(gpu, (currentFrame) => { currentFrame.pass({ target: canvasSurface }, (pass) => pass.draw(wave)); }); ``` -------------------------------- ### Install Dawn Runtime Source: https://vgpu.sh/docs/cli Downloads and verifies the portable Dawn prebuild for Node.js. Use when vgpu doctor reports a missing runtime. ```text Usage: vgpu install-dawn Download and verify the portable Dawn binary for this platform. Honors GH_TOKEN/GITHUB_TOKEN and VGPU_CACHE_DIR. ``` ```bash npx vgpu install-dawn ``` -------------------------------- ### Create an icosphere Source: https://vgpu.sh/docs/reference/vgpu-scene/geometry Example of initializing an icosphere with custom radius, subdivision, and shading parameters. ```ts import { icosphere } from "vgpu/scene"; const moon = icosphere({ radius: 1, subdivisions: 4, shading: "flat" }); ``` -------------------------------- ### Measure GPU frame time Source: https://vgpu.sh/docs/reference/render/perf Example usage of gpuFrameTime to measure a render pass, including setup of a mock device and pipeline. ```ts import { gpuFrameTime } from "@vgpu/render/perf"; import { createMockAdapter } from "@vgpu/adapter-mock"; async function bench(): Promise { const adapter = createMockAdapter(); const device = await adapter.requestDevice(); const renderPassDescriptor: GPURenderPassDescriptor = { colorAttachments: [{ view: {} as GPUTextureView, loadOp: "clear", storeOp: "store" }] }; const pipeline = device.gpu.createRenderPipeline({ layout: "auto", vertex: { module: device.gpu.createShaderModule({ code: "@vertex fn vs_main() -> @builtin(position) vec4f { return vec4f(); }" }), entryPoint: "vs_main" }, fragment: { module: device.gpu.createShaderModule({ code: "@fragment fn fs_main() -> @location(0) vec4f { return vec4f(1.0); }" }), entryPoint: "fs_main", targets: [{ format: "bgra8unorm" }] }, primitive: { topology: "triangle-list" }, }); const result = await gpuFrameTime(device, (encoder) => { const pass = encoder.beginRenderPass(renderPassDescriptor); pass.setPipeline(pipeline); pass.draw(3); pass.end(); }, { frames: 60, warmup: 10 }); console.log(result.method, result.medianMs); } bench().catch((error) => { console.error(error); }); ``` -------------------------------- ### Install vgpu skill Source: https://vgpu.sh/docs/get-started/agents Adds the vgpu skill to agents that support it, enabling targeted documentation loading. ```bash npx skills add vercel-labs/vgpu ``` -------------------------------- ### Configure Cone Geometry Source: https://vgpu.sh/docs/reference/vgpu-scene/geometry Example of initializing a ConeOptions object to create a partial cone. ```ts import type { ConeOptions } from "vgpu/scene"; const halfCone: ConeOptions = { thetaLength: Math.PI }; ``` -------------------------------- ### Native driver startup logs Source: https://vgpu.sh/docs/reference/vgpu-adapter-node/create-node-device Example of stderr output generated by the driver stack during initialization on headless machines. ```text error: XDG_RUNTIME_DIR is invalid or not set in the environment. error: XDG_RUNTIME_DIR is invalid or not set in the environment. Warning: Vulkan shaderUniform*ArrayDynamicIndexing required. ``` -------------------------------- ### Configure ambient light intensity Source: https://vgpu.sh/docs/reference/vgpu-scene/light Example of initializing an ambient light with a specific intensity value. ```ts import { ambientLight } from "vgpu/scene"; ambientLight({ intensity: 0.25 }); ``` -------------------------------- ### Constructor Source: https://vgpu.sh/docs/reference/vgpu-core/device Initializes a new Device wrapper instance using a raw WebGPU device. ```APIDOC ## Constructor ### Description Creates a new Device wrapper instance. ### Parameters - **gpu** (GPUDevice) - Required - Raw WebGPU device. - **adapterInfo** (GPUAdapterInfo | null) - Optional - Stored as device.adapterInfo. - **opts** (DeviceOptions) - Optional - Core-only options for wrapper behavior. - **opts.isCompatibilityMode** (boolean) - Optional - Indicates if the device is in compatibility mode. ``` -------------------------------- ### Create a ring geometry Source: https://vgpu.sh/docs/reference/vgpu-scene/geometry Example of initializing a ring geometry with custom radii and segment count. ```ts import { ring } from "vgpu/scene"; const halo = ring({ innerRadius: 0.9, outerRadius: 1, segments: 48 }); ``` -------------------------------- ### Track mouse movement on canvas Source: https://vgpu.sh/docs/reference/render/canvas-mouse-tracker Example showing how to initialize the tracker, read the position in a render loop, and dispose of the listener. ```ts import { canvasMouseTracker } from "@vgpu/render/utils"; const canvas = document.createElement("canvas"); const effect = { set(values: { readonly mouse: readonly [number, number] }): void { void values; } }; const mouse = canvasMouseTracker({ canvas, normalize: true, flipY: true }); function frame() { const [u, v] = mouse.position; // normalized UV with origin at bottom-left effect.set({ mouse: [u, v] }); requestAnimationFrame(frame); } frame(); // Later: mouse.dispose(); ``` -------------------------------- ### Running vgpu check commands Source: https://vgpu.sh/docs/cli Examples of running the check command with and without strict validation flags. ```bash npx vgpu check ./shaders/main.wgsl npx vgpu check ./shaders/main.wgsl --require-validation VGPU_VALIDATE=require npx vgpu check ./shaders/main.wgsl ``` -------------------------------- ### Create a disk geometry Source: https://vgpu.sh/docs/reference/vgpu-scene/geometry Example of creating a disk with custom radius, segment count, and angular sweep. ```ts import { disk } from "vgpu/scene"; const portal = disk({ radius: 1, segments: 64, thetaLength: Math.PI * 1.5 }); ``` -------------------------------- ### Show help information Source: https://vgpu.sh/docs/cli Display help documentation for the CLI. ```bash npx vgpu docs help npx vgpu docs --help ``` -------------------------------- ### Write Buffer and Flush Example Source: https://vgpu.sh/docs/reference/vgpu-core/queue Demonstrates writing data to a buffer using the queue and awaiting completion. ```ts import { createMockAdapter } from "vgpu/mock"; const device = await createMockAdapter().requestDevice(); const buffer = device.createBuffer({ size: 8, usage: ["copy_dst", "copy_src"] }); device.queue.writeBuffer(buffer.gpu, 0, new Uint32Array([10, 20])); await device.queue.flush(); const bytes = await buffer.read(8); console.log(new Uint32Array(bytes)[1]); // 20 device.destroy(); ``` -------------------------------- ### Configure UnlitMaterial with Options Source: https://vgpu.sh/docs/reference/vgpu-scene/material Example of applying color, opacity, and blend options to an unlit material. ```ts import { srgb, unlitMaterial } from "vgpu/scene"; unlitMaterial({ color: srgb("#ff8800"), opacity: 0.75, blend: "alpha" }); ``` -------------------------------- ### Track canvas resolution with observation Source: https://vgpu.sh/docs/reference/render/canvas-resolution Example demonstrating how to initialize canvas resolution tracking with observation enabled and clean up using dispose. ```ts import { canvasResolution } from "@vgpu/render/utils"; const canvas = document.createElement("canvas"); const effect = { set(values: { readonly resolution: readonly [number, number] }): void { void values; } }; const resolution = canvasResolution(canvas, { observe: true }); function frame() { effect.set({ resolution: [resolution.width, resolution.height] }); requestAnimationFrame(frame); } frame(); // Later: resolution.dispose(); ``` -------------------------------- ### Point agent at documentation Source: https://vgpu.sh/docs/get-started/agents Execute this command to provide the agent with a guide and tools to explore reference pages and error codes. ```bash npx vgpu ``` -------------------------------- ### Initialize vgpu with mock environment Source: https://vgpu.sh/docs/reference/vgpu/init Use the mock entrypoint for deterministic testing without requiring a physical GPU. ```typescript import { init, effect, frame, target } from "vgpu/mock"; const gpu = await init(); const colorTarget = target(gpu, { size: [64, 64], format: "rgba8unorm" }); const shader = effect(gpu, ` @fragment fn fs_main(@location(0) uv: vec2f) -> @location(0) vec4f { return vec4f(uv, 0.0, 1.0); } `); frame(gpu, (currentFrame) => { currentFrame.pass({ target: colorTarget }, (p) => p.draw(shader)); }); ``` -------------------------------- ### Install WGSL package dependency Source: https://vgpu.sh/docs/guides/publishing-wgsl-packages Use the standard npm install command to add a WGSL package as a project dependency. ```bash npm install @acme/shaders ``` -------------------------------- ### Enable WebGPU via environment or config Source: https://vgpu.sh/docs/guides/agent-browser-webgpu Enable the WebGPU preset using environment variables or a configuration file. ```bash AGENT_BROWSER_WEBGPU=1 agent-browser --headed open http://localhost:3001 # agent-browser.json: { "webgpu": true } ``` -------------------------------- ### Check GeometryKind Source: https://vgpu.sh/docs/reference/vgpu-scene/geometry Example function checking if a GeometryKind is a polyhedron. ```ts import type { GeometryKind } from "vgpu/scene"; function isPolyhedron(kind: GeometryKind): boolean { return ["dodecahedron", "icosahedron", "octahedron", "tetrahedron"].includes(kind); } ``` -------------------------------- ### Create a Tetrahedron Source: https://vgpu.sh/docs/reference/vgpu-scene/geometry Example of creating a tetrahedron with a specified radius. ```ts import { tetrahedron } from "vgpu/scene"; const marker = tetrahedron({ radius: 0.3 }); ``` -------------------------------- ### Create and use a vGPU buffer Source: https://vgpu.sh/docs/reference/vgpu-core/buffer Demonstrates initializing a mock device, creating a buffer with specific usages, and performing read/write operations. ```ts import { createMockAdapter } from "vgpu/mock"; const device = await createMockAdapter().requestDevice(); const buffer = device.createBuffer({ label: "cpu-visible-data", size: 16, usage: ["copy_dst", "copy_src"], }); buffer.write(new Uint32Array([1, 2, 3, 4])); const bytes = await buffer.read(16); console.log(new Uint32Array(bytes)[2]); // 3 buffer.destroy(); device.destroy(); ``` -------------------------------- ### Use PolyhedronOptions Source: https://vgpu.sh/docs/reference/vgpu-scene/geometry Example of configuring a polyhedron with a custom radius. ```ts import type { PolyhedronOptions } from "vgpu/scene"; const hudIcon: PolyhedronOptions = { radius: 0.25 }; ``` -------------------------------- ### vgpu(options?: InitOptions) Source: https://vgpu.sh/docs/reference/vgpu/init Initializes the vgpu environment and returns a Promise that resolves to a Gpu context. ```APIDOC ## vgpu(options?: InitOptions) ### Description Initializes the vgpu environment. This function returns a Promise that resolves to a Gpu context, which is required for all other factory functions like surface, target, draw, and compute. ### Parameters - **options** (InitOptions) - Optional - Device creation options. - **options.adapter** (VGPUAdapter) - Optional - Explicit adapter to use. If omitted, navigator.gpu.requestAdapter() is used. - **options.powerPreference** (GPUPowerPreference) - Optional - Forwarded to navigator.gpu.requestAdapter. - **options.requiredFeatures** (readonly GPUFeatureName[]) - Optional - Optional device features to enable. - **options.requiredLimits** (RequiredDeviceLimits) - Optional - Forwarded to adapter.requestDevice. - **options.label** (string) - Optional - Reserved public option. ### Returns - **Promise** - The context required for all factory functions. ### Throws - **VGPU-RING1-UNSUPPORTED** - Thrown when WebGPU is unavailable or adapter request fails. - **VGPU-FEATURE-UNSUPPORTED** - Thrown when a requested feature is not supported by the adapter. ``` -------------------------------- ### Create fullscreenQuad Descriptor Source: https://vgpu.sh/docs/reference/vgpu-scene/geometry Example usage of the fullscreenQuad function. ```ts import { fullscreenQuad } from "vgpu/scene"; const descriptor = fullscreenQuad(); ``` -------------------------------- ### Initialize and Update Camera Source: https://vgpu.sh/docs/reference/vgpu-scene/perspective-camera Demonstrates creating a camera and updating its state while maintaining stable matrix references. ```ts import { perspectiveCamera } from "vgpu/scene"; const cam = perspectiveCamera({ fov: 45, position: [2, 2, 3], target: [0, 0, 0] }); const matrix = cam.viewProjection; // stable identity — bind once cam.set({ fov: 60, position: [0, 2, 5] }); cam.lookAt([0, 0, 0]); void matrix; // same array, already updated in place ``` -------------------------------- ### Example Usage of QuatLike Source: https://vgpu.sh/docs/reference/vgpu-scene/scene-tree Assigning a tuple to a QuatLike variable. ```ts import type { QuatLike } from "vgpu/scene"; const identity: QuatLike = [0, 0, 0, 1]; ``` -------------------------------- ### Example Usage of Vec3Like Source: https://vgpu.sh/docs/reference/vgpu-scene/scene-tree Assigning a tuple to a Vec3Like variable. ```ts import type { Vec3Like } from "vgpu/scene"; const up: Vec3Like = [0, 1, 0]; ``` -------------------------------- ### Initialize and Render with VGPU Node Device Source: https://vgpu.sh/docs/reference/vgpu-adapter-node/create-node-device Demonstrates creating a device, setting up a render pipeline, and reading back pixel data from an offscreen texture. ```typescript import { createNodeDevice } from "@vgpu/adapter-node"; const width = 256; const height = 256; const format: GPUTextureFormat = "rgba8unorm"; const scene = { name: "hero-triangle", seed: 7, timeSeconds: 0, camera: "orthographic-front", }; const device = await createNodeDevice({ label: `snapshot.${scene.name}.device` }); try { const target = device.createTexture({ label: `snapshot.${scene.name}.target`, size: [width, height], format, usage: ["render_attachment", "copy_src"], }); const shader = device.gpu.createShaderModule({ label: `snapshot.${scene.name}.shader`, code: /* wgsl */ ` @vertex fn vs(@builtin(vertex_index) vertexIndex: u32) -> @builtin(position) vec4f { let positions = array( vec2f(-0.75, -0.75), vec2f( 0.75, -0.75), vec2f( 0.00, 0.75), ); return vec4f(positions[vertexIndex], 0.0, 1.0); } @fragment fn fs(@builtin(position) position: vec4f) -> @location(0) vec4f { let uv = position.xy / vec2f(${width}.0, ${height}.0); return vec4f(uv.x, uv.y, 0.25, 1.0); } `, }); const pipeline = device.gpu.createRenderPipeline({ label: `snapshot.${scene.name}.pipeline`, layout: "auto", vertex: { module: shader, entryPoint: "vs" }, fragment: { module: shader, entryPoint: "fs", targets: [{ format }] }, primitive: { topology: "triangle-list" }, }); const encoder = device.gpu.createCommandEncoder({ label: `snapshot.${scene.name}.frame` }); const pass = encoder.beginRenderPass({ label: `snapshot.${scene.name}.pass`, colorAttachments: [{ view: target.createView(), clearValue: { r: 0, g: 0, b: 0, a: 1 }, loadOp: "clear", storeOp: "store", }], }); pass.setPipeline(pipeline); pass.draw(3); pass.end(); device.queue.gpu.submit([encoder.finish()]); await device.queue.flush(); const rgba = await target.read(); // Pass `rgba` to project-owned PNG or pixel-diff tooling. target.destroy(); } finally { device.destroy(); } ``` -------------------------------- ### Usage of normalMaterial Source: https://vgpu.sh/docs/reference/vgpu-scene/material Example of applying a normal material to a mesh. ```ts import { mesh, normalMaterial, torus } from "vgpu/scene"; const donut = mesh(torus(), normalMaterial()); void donut; ``` -------------------------------- ### Initialize Vec3 Source: https://vgpu.sh/docs/reference/vgpu-scene/camera Example of initializing a Vec3 using a Float32Array. ```ts import type { Vec3 } from "vgpu/scene"; const up: Vec3 = new Float32Array([0, 1, 0]); ``` -------------------------------- ### Render geometry with custom shaders Source: https://vgpu.sh/docs/guides/concepts-draws Demonstrates initializing the GPU, defining a WGSL shader with vertex and fragment stages, and rendering a box geometry with uniform updates. ```javascript import { init, draw, geometry, target } from "vgpu"; const gpu = await init(); // ---cut--- import { box, orbit, perspectiveCamera } from "vgpu/scene"; const shader = ` struct Camera { viewProjection: mat4x4f } struct Model { model: mat4x4f } @group(0) @binding(0) var camera: Camera; @group(0) @binding(1) var model: Model; struct VertexOut { @builtin(position) position: vec4f, @location(0) normal: vec3f } @vertex fn vs_main(@location(0) position: vec3f, @location(1) normal: vec3f) -> VertexOut { var out: VertexOut; out.position = camera.viewProjection * model.model * vec4f(position, 1.0); out.normal = normal; return out; } @fragment fn fs_main(@location(0) normal: vec3f) -> @location(0) vec4f { let light = max(dot(normalize(normal), normalize(vec3f(1.0, 1.0, 1.0))), 0.15); return vec4f(vec3f(0.2, 0.5, 1.0) * light, 1.0); } `; const colorTarget = target(gpu, { size: [1280, 720], depth: true }); const camera = perspectiveCamera({ fov: 45, aspect: 16 / 9, position: [2, 2, 3], target: [0, 0, 0] }); const cube = draw(gpu, { shader, geometry: geometry(gpu, box({ size: 1 })) }); cube.set({ camera: { viewProjection: camera.viewProjection }, model: { model: orbit(0) }, }); cube.draw(colorTarget); ``` -------------------------------- ### Initialize CameraVec3 Source: https://vgpu.sh/docs/reference/vgpu-scene/camera Example of initializing a CameraVec3 using a Float32Array. ```ts import type { CameraVec3 } from "vgpu/scene"; const orbitPos: CameraVec3 = new Float32Array([0, 3, 5]); ``` -------------------------------- ### Use SceneGeometry Source: https://vgpu.sh/docs/reference/vgpu-scene/geometry Example of storing a primitive descriptor in a SceneGeometry array. ```ts import { box } from "vgpu/scene"; import type { SceneGeometry } from "vgpu/scene"; const primitives: SceneGeometry[] = [box({ size: 2 })]; ``` -------------------------------- ### Initialize and use wireframeMaterial Source: https://vgpu.sh/docs/reference/render/wireframe-material Demonstrates creating a wireframe material with a mock device and writing uniform data for rendering. ```ts import { createMockAdapter } from "@vgpu/adapter-mock"; import { InspectMaterial, wireframeMaterial } from "@vgpu/render/inspect"; const IDENTITY_MATRIX = new Float32Array([ 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, ]); async function main(): Promise { const device = await createMockAdapter().requestDevice(); const material: InspectMaterial = wireframeMaterial({ device, color: [1, 0.75, 0.5] }); const uniforms = device.createBuffer({ size: material.uniformByteSize, usage: ["uniform", "copy_dst"] }); material.writeUniforms(uniforms.gpu, 0, { viewProjectionMatrix: IDENTITY_MATRIX, modelMatrix: IDENTITY_MATRIX, }); } main().catch((error) => { console.error(error); }); ``` -------------------------------- ### Create Octahedron Geometry Source: https://vgpu.sh/docs/reference/vgpu-scene/geometry Example of creating an octahedron with a custom radius. ```ts import { octahedron } from "vgpu/scene"; const diamond = octahedron({ radius: 0.7 }); ``` -------------------------------- ### Initialize and Update orbitControls Source: https://vgpu.sh/docs/reference/vgpu-scene/orbit-controls Demonstrates setting up orbit controls on a perspective camera and updating them within a frame loop using the delta time from the GPU clock. ```ts import { clock, init, frameLoop } from "vgpu"; import { orbitControls, perspectiveCamera } from "vgpu/scene"; declare const canvas: HTMLCanvasElement; const gpu = await init(); const camera = perspectiveCamera({ fov: 45, position: [2, 2, 3], target: [0, 0, 0] }); const controls = orbitControls(camera, { element: canvas, damping: 0.1 }); frameLoop(gpu, () => { controls.update(clock(gpu).deltaTime); // explicit update, no hidden rAF }); ``` -------------------------------- ### Create Dodecahedron Geometry Source: https://vgpu.sh/docs/reference/vgpu-scene/geometry Example of creating a dodecahedron with a custom radius. ```ts import { dodecahedron } from "vgpu/scene"; const rock = dodecahedron({ radius: 0.8 }); ``` -------------------------------- ### Use SceneMaterial Source: https://vgpu.sh/docs/reference/vgpu-scene/material Example of assigning a material and checking its concrete type. ```ts import { UnlitMaterial, unlitMaterial, type SceneMaterial } from "vgpu/scene"; const material: SceneMaterial = unlitMaterial(); if (material instanceof UnlitMaterial) void material.color; ``` -------------------------------- ### init(options?: InitOptions): Promise Source: https://vgpu.sh/docs/reference/vgpu/init Initializes the GPU context. This function creates the device and returns a promise that resolves to the Gpu object. ```APIDOC ## init(options?: InitOptions): Promise ### Description Creates the public `Gpu` context. This function initializes the device; note that canvas-backed rendering requires a subsequent call to `surface(gpu, canvas, opts)`. ### Signature `async function init(options?: InitOptions): Promise` ### Parameters #### InitOptions (Optional) - **adapter** (VGPUAdapter) - Optional - A specific GPU adapter to use. - **powerPreference** (GPUPowerPreference) - Optional - Preference for power consumption (e.g., 'low-power' or 'high-performance'). - **requiredFeatures** (readonly GPUFeatureName[]) - Optional - List of required GPU features. - **requiredLimits** (RequiredDeviceLimits) - Optional - Set of required device limits. - **label** (string) - Optional - A label for the GPU device. ### Returns - **Promise** - A promise that resolves to the initialized Gpu context. ``` -------------------------------- ### Create Low-Poly Icosphere Source: https://vgpu.sh/docs/reference/vgpu-scene/geometry Example of configuring an icosphere with a specific subdivision level. ```ts import type { IcosphereOptions } from "vgpu/scene"; const lowPoly: IcosphereOptions = { subdivisions: 1 }; ``` -------------------------------- ### Create Icosahedron Source: https://vgpu.sh/docs/reference/vgpu-scene/geometry Example of creating an icosahedron geometry descriptor with a specific radius. ```ts import { icosahedron } from "vgpu/scene"; const crystal = icosahedron({ radius: 0.6 }); ``` -------------------------------- ### Access CLI help and version Source: https://vgpu.sh/docs/cli Use these commands to display the help menu or verify the current version of the CLI tool. ```bash npx vgpu --help npx vgpu --version ``` -------------------------------- ### Configure Disk Geometry Source: https://vgpu.sh/docs/reference/vgpu-scene/geometry Example of defining a disk slice using DiskOptions. ```ts import type { DiskOptions } from "vgpu/scene"; const slice: DiskOptions = { thetaLength: Math.PI }; ``` -------------------------------- ### Create Plane Geometry Source: https://vgpu.sh/docs/reference/vgpu-scene/geometry Example of defining plane options with custom dimensions. ```ts import type { PlaneOptions } from "vgpu/scene"; const quad: PlaneOptions = { width: 4, height: 2 }; ``` -------------------------------- ### Initialize and Configure PerspectiveCamera Source: https://vgpu.sh/docs/reference/vgpu-scene/perspective-camera Create a camera instance and update its aspect ratio. ```ts import { perspectiveCamera, type PerspectiveCamera } from "vgpu/scene"; const cam: PerspectiveCamera = perspectiveCamera({ fov: 45 }); cam.set({ aspect: 16 / 9 }); ``` -------------------------------- ### Configure Sphere Geometry Source: https://vgpu.sh/docs/reference/vgpu-scene/geometry Example of defining custom segment counts for a sphere. ```ts import type { SphereOptions } from "vgpu/scene"; const detail: SphereOptions = { widthSegments: 96, heightSegments: 64 }; ``` -------------------------------- ### Create a box geometry Source: https://vgpu.sh/docs/reference/vgpu-scene/geometry Example of creating a cube descriptor with a custom size. ```ts import { box } from "vgpu/scene"; const tallCube = box({ size: 3 }); console.log(tallCube.kind); // "box" ``` -------------------------------- ### Define the init signature and options Source: https://vgpu.sh/docs/reference/vgpu/init The init function returns a promise resolving to a Gpu context, accepting optional configuration for adapters, power preferences, and device limits. ```ts import type { Gpu } from "vgpu"; import type { RequiredDeviceLimits, VGPUAdapter } from "vgpu/core"; declare function init(options?: InitOptions): Promise; interface InitOptions { readonly adapter?: VGPUAdapter; readonly powerPreference?: GPUPowerPreference; readonly requiredFeatures?: readonly GPUFeatureName[]; readonly requiredLimits?: RequiredDeviceLimits; readonly label?: string; } ``` -------------------------------- ### Manage Scene Hierarchy Source: https://vgpu.sh/docs/reference/vgpu-scene/scene-tree Example of parent-child relationship and world matrix stability. ```ts import { group } from "vgpu/scene"; const parent = group({ position: [1, 0, 0] }); const child = group({ position: [0, 1, 0] }); parent.add(child); const world = child.worldMatrix; // stable identity parent.set({ position: [2, 0, 0] }); void world; // same array, refreshed on next read ``` -------------------------------- ### Pre-warming and recording a render bundle Source: https://vgpu.sh/docs/concepts/render-bundles Demonstrates initializing a GPU context, pre-compiling effects, and recording a bundle to avoid synchronous compilation during the frame loop. ```ts import { init, bundle, clock, effect, frameLoop, surface } from "vgpu"; const gpu = await init(); const canvas = document.querySelector("canvas")!; const canvasTarget = surface(gpu, canvas); const ocean = effect(gpu, ` @fragment fn fs_main(@location(0) uv: vec2f) -> @location(0) vec4f { return vec4f(0.1, 0.3, 0.6, 1.0); } `); const boat = effect(gpu, ` @fragment fn fs_main(@location(0) uv: vec2f) -> @location(0) vec4f { return vec4f(0.6, 0.4, 0.2, 1.0); } `); await Promise.all([ ocean.compile({ colors: ['bgra8unorm'] }), boat.compile({ colors: ['bgra8unorm'] }), ]); const scene = bundle(gpu, { target: { colors: ['bgra8unorm'] } }, (b) => { b.draw(ocean); b.draw(boat); }); // everything was pre-warmed — recording creates nothing frameLoop(gpu, (frame) => { frame.pass(canvasTarget, (pass) => pass.bundles(scene)); }); ``` -------------------------------- ### Access SceneCamera properties Source: https://vgpu.sh/docs/reference/vgpu-scene/camera Example of accessing the viewProjection property of a camera node. ```ts import { perspectiveCamera } from "vgpu/scene"; const camera = perspectiveCamera({ fov: 50, aspect: 4 / 3, position: [2, 2, 4], target: [0, 0, 0], }); void camera.viewProjection; ``` -------------------------------- ### Initialize InspectMaterialUniformParams Source: https://vgpu.sh/docs/reference/render/inspect-material Example of creating an instance of the uniform parameters with identity matrices. ```ts import type { InspectMaterialUniformParams } from "@vgpu/render/inspect"; const identity = new Float32Array([1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1]); const params: InspectMaterialUniformParams = { viewProjectionMatrix: identity, modelMatrix: identity, }; params.modelMatrix satisfies Float32Array; ``` -------------------------------- ### Initialize normalDebugMaterial Source: https://vgpu.sh/docs/reference/render/normal-debug-material Demonstrates how to initialize the material and write uniform data using a mock device. ```ts import { createMockAdapter } from "@vgpu/adapter-mock"; import { InspectMaterial, normalDebugMaterial } from "@vgpu/render/inspect"; const IDENTITY_MATRIX = new Float32Array([ 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, ]); async function main(): Promise { const device = await createMockAdapter().requestDevice(); const material: InspectMaterial = normalDebugMaterial({ device, targetFormat: "rgba8unorm-srgb" }); const uniforms = device.createBuffer({ size: material.uniformByteSize, usage: ["uniform", "copy_dst"] }); material.writeUniforms(uniforms.gpu, 0, { viewProjectionMatrix: IDENTITY_MATRIX, modelMatrix: IDENTITY_MATRIX, }); } main().catch((error) => { console.error(error); }); ``` -------------------------------- ### Import FullscreenQuadOptions Source: https://vgpu.sh/docs/reference/vgpu-scene/geometry Import the interface for configuring fullscreen quad rendering. ```ts import type { FullscreenQuadOptions } from "vgpu/scene"; ``` -------------------------------- ### Automate WebGPU Preview Capture Source: https://vgpu.sh/docs/guides/agent-browser-webgpu Iterates through a list of preview slugs, initializes the browser, verifies WebGPU support, and captures screenshots while filtering out uniform pixels. ```bash SESSION=vgpu-previews BASE_URL=http://localhost:3001 for slug in gradient triangle-led-front anti-aliasing black-hole fluid instanced-rendering batch-rendering fft-ocean raymarched-fractal; do agent-browser --session "$SESSION" --webgpu --headed open "$BASE_URL/preview/$slug" agent-browser --session "$SESSION" --webgpu --headed wait 6000 agent-browser --session "$SESSION" --webgpu --headed eval 'new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(resolve)))' agent-browser --session "$SESSION" --webgpu --headed eval 'JSON.stringify({hasCanvas:Boolean(document.querySelector("canvas")),webgpu:Boolean(navigator.gpu),text:document.body.innerText})' | sed 's/\"/"/g' | grep -q '"hasCanvas":true' agent-browser --session "$SESSION" --webgpu --headed screenshot "$slug.png" identify -format '%[fx:standard_deviation]\n' "$slug.png" | awk '$1 > 50' done agent-browser --session "$SESSION" close ``` -------------------------------- ### Usage of SceneGeometryOfKind Source: https://vgpu.sh/docs/reference/vgpu-scene/geometry Example demonstrating how to use the helper to type a specific geometry primitive. ```ts import { sphere } from "vgpu/scene"; import type { SceneGeometryOfKind } from "vgpu/scene"; const glossy: SceneGeometryOfKind<"sphere"> = sphere({ radius: 1 }); ``` -------------------------------- ### Create Ring Geometry Options Source: https://vgpu.sh/docs/reference/vgpu-scene/geometry Example of defining options for a partial ring arc. ```ts import type { RingOptions } from "vgpu/scene"; const arc: RingOptions = { thetaLength: Math.PI * 0.75 }; ``` -------------------------------- ### Capture and validate a WebGPU preview Source: https://vgpu.sh/docs/guides/agent-browser-webgpu Automates opening a URL, waiting for rendering, capturing a screenshot, and checking for uniform pixel output. ```bash SESSION=vgpu-webgpu URL=http://localhost:3001/preview/gradient agent-browser --session "$SESSION" --webgpu --headed open "$URL" agent-browser --session "$SESSION" --webgpu --headed wait 6000 agent-browser --session "$SESSION" --webgpu --headed eval 'new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(resolve)))' agent-browser --session "$SESSION" --webgpu --headed screenshot gradient.png identify -format '%[fx:standard_deviation]\n' gradient.png agent-browser --session "$SESSION" close ``` -------------------------------- ### Initialize GPU context and create resources Source: https://vgpu.sh/docs/concepts/context Initializes the WebGPU device and creates surfaces, targets, and effects. These resources should be created once and reused across frames. ```ts import { init, effect, surface, target } from "vgpu"; const gpu = await init(); const canvas = document.querySelector("canvas")!; const canvasSurface = surface(gpu, canvas); // the canvas you render into const colorTarget = target(gpu, { size: [256, 256] }); // an offscreen texture const gradient = effect(gpu, ` @fragment fn fs_main(@location(0) uv: vec2f) -> @location(0) vec4f { return vec4f(uv, 0.4, 1.0); } `); // Render the gradient onto the canvas once gradient.draw(canvasSurface); ``` -------------------------------- ### Initialize and draw to a target Source: https://vgpu.sh/docs/reference/vgpu/gpu Demonstrates initializing the GPU, creating a render target, and executing a draw call within a frame. ```ts import { init, draw, frame, target } from "vgpu/mock"; const gpu = await init(); const colorTarget = target(gpu, { size: [128, 128], depth: true }); const drawable = draw(gpu, { shader: ` @vertex fn vs_main(@builtin(vertex_index) vi: u32) -> @builtin(position) vec4f { var p = array(vec2f(-1, -1), vec2f(3, -1), vec2f(-1, 3)); return vec4f(p[vi], 0, 1); } @fragment fn fs_main() -> @location(0) vec4f { return vec4f(1, 0, 1, 1); } `, // optional sync pre-warm; `await draw.compile(target)` is preferred during browser load targets: [colorTarget], }); frame(gpu, (currentFrame) => { currentFrame.pass({ target: colorTarget, clear: [0, 0, 0, 1] }, (pass) => pass.draw(drawable)); }); ``` -------------------------------- ### Create a Capsule Geometry Source: https://vgpu.sh/docs/reference/vgpu-scene/geometry Example of creating a capsule with custom radius, height, and shading. ```ts import { capsule } from "vgpu/scene"; const pillar = capsule({ radius: 0.3, height: 2, shading: "flat" }); ``` -------------------------------- ### Initialize and Bind StorageBuffer for Compute Source: https://vgpu.sh/docs/reference/vgpu-core/storage-buffer Demonstrates creating a StorageBuffer, writing data, and binding it to a compute shader pipeline. ```ts import { init, compute } from "vgpu/mock"; import { StorageBuffer } from "vgpu/core"; const gpu = await init(); const values = new StorageBuffer(gpu.device, { size: 4 * 16, label: "values" }); values.write(new Float32Array(16)); const sim = compute(gpu, ` @group(0) @binding(0) var values: array; @compute @workgroup_size(1) fn cs_main(@builtin(global_invocation_id) id: vec3u) { _ = values[id.x]; } `, { set: { values } }); sim.dispatch(1); ``` -------------------------------- ### Configure Torus Geometry Source: https://vgpu.sh/docs/reference/vgpu-scene/geometry Example usage of TorusOptions to define a specific torus configuration. ```ts import type { TorusOptions } from "vgpu/scene"; const tight: TorusOptions = { radius: 0.75, tube: 0.3 }; ``` -------------------------------- ### List documentation paths Source: https://vgpu.sh/docs/cli List packages or documentation files under a virtual path. ```bash npx vgpu docs ls [path] npx vgpu docs ls /guides ``` -------------------------------- ### Create Tiled Plane Geometry Source: https://vgpu.sh/docs/reference/vgpu-scene/geometry Example of creating a plane with specific dimensions and tessellation. ```ts import { plane } from "vgpu/scene"; const tiled = plane({ width: 10, height: 10, widthSegments: 4, heightSegments: 4 }); ```