### Example demo directory structure Source: https://github.com/kaltwrk/spektral/blob/master/apps/web/src/routes/playground/demos/README.md Shows the required folder layout for a demo named 'flow-field', including framework variants and shared shader files. ```text demos/ flow-field/ svelte/ App.svelte runtime.svelte react/ App.tsx runtime.tsx vue/ App.vue runtime.vue shaders/ fragment.wgsl shader.ts ``` -------------------------------- ### Local setup: corepack enable, pnpm install, playwright install Source: https://github.com/kaltwrk/spektral/blob/master/CONTRIBUTING.md Sets up the local development environment for Spektral. Enables Corepack, installs dependencies with pnpm, and installs the Playwright Chromium browser for the packages/spektral package. ```sh corepack enable pnpm install pnpm --dir packages/spektral exec playwright install chromium ``` -------------------------------- ### Install Spektral with npm Source: https://github.com/kaltwrk/spektral/blob/master/README.md Install the Spektral package from npm. Use this command in a project that requires WebGPU and a secure context such as HTTPS or localhost. ```bash npm install spektral ``` -------------------------------- ### ShaderPass public methods Source: https://github.com/kaltwrk/spektral/blob/master/apps/web/src/lib/content/docs/api-passes-reference/index.svx Public methods for ShaderPass. setFragment validates the source contract and starts asynchronous preparation; getFragment returns the current fragment. ```ts setFragment(fragment: string): void getFragment(): string ``` -------------------------------- ### Run svelte-autofixer on a Svelte file Source: https://github.com/kaltwrk/spektral/blob/master/SKILL.md Run the svelte-autofixer tool on a Svelte file when available. Use this only when touching `.svelte` files and the `svelte-autofixer` package is installed. ```bash npx @sveltejs/mcp svelte-autofixer ``` -------------------------------- ### Vite plugin setup for TypeGPU Source: https://github.com/kaltwrk/spektral/blob/master/apps/web/src/lib/content/docs/integrations-typegpu/index.svx Configure Vite to transform TypeGPU shader functions containing 'use gpu'. If shader transformation runs inside a worker bundler, configure the matching TypeGPU integration in that bundler as well. ```ts import { defineConfig } from 'vite'; import typegpu from 'unplugin-typegpu/vite'; export default defineConfig({ plugins: [typegpu()] }); ``` -------------------------------- ### Get render graph snapshot with graph.getSnapshot() Source: https://github.com/kaltwrk/spektral/blob/master/apps/web/src/lib/content/docs/hooks-and-context/index.svx Returns the cached render graph snapshot. The API is experimental until 1.0; repeated reads return the same frozen object until Spektral builds a new graph plan. ```ts const { graph } = useSpektral(); const snapshot = graph.getSnapshot(); ``` -------------------------------- ### Create and check hardware GPU baseline with SPEKTRAL_PERF_POWER_MODE Source: https://github.com/kaltwrk/spektral/blob/master/packages/spektral/benchmarks/README.md Creates a hardware GPU baseline on the reference machine, then runs the strict check. Baseline creation requires a clean worktree, controlled power mode, and at least five fresh browser processes; it refuses to overwrite an existing fingerprint. The check also requires at least five processes and fails on a missing metric, old schema, or incompatible environment. ```sh SPEKTRAL_PERF_POWER_MODE=ac-high-power pnpm run perf:spektral:gpu:baseline pnpm run perf:spektral:gpu:check ``` -------------------------------- ### Import FragCanvas from framework entrypoints Source: https://github.com/kaltwrk/spektral/blob/master/apps/web/src/lib/content/docs/fragcanvas-reference/index.svx Import FragCanvas from the framework-specific entrypoint. Use 'spektral/svelte' for Svelte, 'spektral/react' for React, and 'spektral/vue' for Vue. ```ts import { FragCanvas } from 'spektral/svelte'; ``` ```ts import { FragCanvas } from 'spektral/react'; ``` ```ts import { FragCanvas } from 'spektral/vue'; ``` -------------------------------- ### Create and check a real renderer baseline with SPEKTRAL_PERF_POWER_MODE Source: https://github.com/kaltwrk/spektral/blob/master/packages/spektral/benchmarks/README.md Creates a baseline for the real renderer suite with an explicitly controlled power mode, then runs the strict check. Baseline creation requires a clean worktree, at least five fresh browser processes, and the power mode set to ac-high-power. The check rejects baselines with fewer than five processes, a different scenario or correctness contract, an old schema, or an incompatible hardware fingerprint. ```sh SPEKTRAL_PERF_POWER_MODE=ac-high-power pnpm run perf:spektral:renderer:baseline pnpm run perf:spektral:renderer:check ``` -------------------------------- ### Run paired compute topology benchmark from package directory Source: https://github.com/kaltwrk/spektral/blob/master/packages/spektral/benchmarks/README.md Package-level equivalent of the paired compute topology benchmark command. Expands to --runs=12 --seed=1394060030. ```sh pnpm --dir packages/spektral run perf:compute-topology:paired ``` -------------------------------- ### Run performance benchmarks: perf:spektral:core:check, perf:spektral:check, perf:spektral:gpu:check, perf:spektral:renderer:check, bundle:spektral:check Source: https://github.com/kaltwrk/spektral/blob/master/CONTRIBUTING.md Runs the performance benchmark checks for Spektral. These are kept separate from the required PR gate and should be compared on the same class of machine due to CPU, browser, and power-mode dependencies. ```sh pnpm run perf:spektral:core:check pnpm run perf:spektral:check pnpm run perf:spektral:gpu:check pnpm run perf:spektral:renderer:check pnpm run bundle:spektral:check ``` -------------------------------- ### Run WebGPU E2E tests: pnpm run ci:e2e Source: https://github.com/kaltwrk/spektral/blob/master/CONTRIBUTING.md Runs the WebGPU end-to-end tests explicitly. Use this if the pre-commit hook was skipped, since E2E is not a required GitHub check. ```sh pnpm run ci:e2e ``` -------------------------------- ### Run paired core A/B benchmark with tsx Source: https://github.com/kaltwrk/spektral/blob/master/packages/spektral/benchmarks/core-paired-ab-evidence.md Run the paired core A/B benchmark from the package root. The command uses 20 runs per source and a fixed seed to reproduce the comparison. Output is written to benchmarks/results/core-paired-ab-latest.json. ```sh tsx scripts/perf/paired-core-benchmark.ts --runs=20 --seed=1296523349 ``` -------------------------------- ### Run paired compute topology benchmark Source: https://github.com/kaltwrk/spektral/blob/master/packages/spektral/benchmarks/README.md Runs the paired A/B compute topology benchmark with 12 fresh processes per arm, four external buffer resources per pass, scenarios 0/4/16/32, balanced alternating arm order, shuffled scenario order, raw samples, and validated checksums. Expands to --runs=12 --seed=1394060030. ```sh pnpm run perf:spektral:compute-topology:paired ``` -------------------------------- ### Run full local gate: pnpm run ci Source: https://github.com/kaltwrk/spektral/blob/master/CONTRIBUTING.md Runs the full local gate: changelog check, formatting, lint, builds, type checks, unit tests, and all Playwright/WebGPU scenarios for Svelte, React, and Vue. This is the command configured as the pre-commit hook. ```sh pnpm run ci ``` -------------------------------- ### Run web app validation commands Source: https://github.com/kaltwrk/spektral/blob/master/apps/web/src/lib/content/docs/testing-and-internals/index.svx Validation commands for the web app. Run from `apps/web`. These are the standard build, check, and lint commands for the web application. ```bash pnpm run build pnpm run check pnpm run lint ``` -------------------------------- ### Define a material with defineMaterial Source: https://github.com/kaltwrk/spektral/blob/master/apps/web/src/lib/content/docs/defining-materials/index.svx Creates a material with a fragment shader, uniforms, textures, and defines. The fragment must be WGSL containing fn frag(uv: vec2f) -> vec4f. Uniforms, textures, defines, includes, and storageBuffers are optional. The resulting FragMaterial is frozen and immutable. ```ts const material = defineMaterial({ fragment, uniforms: { uTime: 0, uColor: [0.2, 0.8, 1] }, textures: { uImage: { colorSpace: 'srgb' } }, defines: { ENABLE_GLOW: true } }); ``` -------------------------------- ### Configure scheduler diagnostics and profiling Source: https://github.com/kaltwrk/spektral/blob/master/apps/web/src/lib/content/docs/render-modes/index.svx Configures scheduler diagnostics and profiling, then retrieves last-run timings and a profiling snapshot. The profiling window must be a safe integer from 1 through 10,000 frames. Schedule, last-run timing, and profiling results are deeply frozen snapshots; copy them before adding application metadata. Diagnostics and profiling share one internal toggle, so advanced preset overrides must give them the same value. ```ts const scheduler = gpu.scheduler; scheduler.setProfilingWindow(120); scheduler.setDiagnosticsEnabled(true); scheduler.setProfilingEnabled(true); const lastRun = scheduler.getLastRunTimings(); const profile = scheduler.getProfilingSnapshot(); ``` -------------------------------- ### Create performance baselines: perf:spektral:gpu:baseline and perf:spektral:renderer:baseline Source: https://github.com/kaltwrk/spektral/blob/master/CONTRIBUTING.md Creates baselines for the strict GPU and real-renderer performance checks. Run these on the reference Apple M4 Pro/Metal machine against baselines with the same GPU, backend, driver, macOS, Chromium major, and benchmark-suite fingerprint. The hardware commands reject SwiftShader and other software adapters. ```sh pnpm run perf:spektral:gpu:baseline ``` ```sh pnpm run perf:spektral:renderer:baseline ``` -------------------------------- ### ComputePass with resource descriptors Source: https://github.com/kaltwrk/spektral/blob/master/apps/web/src/lib/content/docs/compute-shaders/index.svx Declares a ComputePass with a resource map that binds a camera texture, a motion texture, a particles buffer, and a camera sampler. The map keys are exact WGSL variable names. A ComputePass without resources has only frame and material uniforms; material textures and storage buffers are never injected automatically. ```ts new ComputePass({ compute, resources: { uCamera: { texture: 'camera', access: 'sampled' }, uMotion: { texture: 'motion', access: 'storage-write' }, uParticles: { buffer: 'particles', access: 'storage-read-write' }, uCameraSampler: { sampler: 'camera' } } }); ``` -------------------------------- ### PingPongComputePass constructor with ping-pong resources Source: https://github.com/kaltwrk/spektral/blob/master/apps/web/src/lib/content/docs/api-passes-reference/index.svx Creates a PingPongComputePass that alternates between two storage textures over a set number of iterations. Requires exactly one sampled 'read' and one storage-write 'write' descriptor pointing to the same texture. The renderer keeps A/B names private and publishes the latest result under the logical material key after the batch. ```ts new PingPongComputePass({ label: 'Velocity iterations', compute, resources: { previous: { texture: 'velocity', access: 'sampled', pingPong: 'read' }, next: { texture: 'velocity', access: 'storage-write', pingPong: 'write' }, obstacles: { texture: 'obstacles', access: 'sampled' } }, iterations: 8, dispatch: 'auto' }); ``` -------------------------------- ### useFrame Source: https://github.com/kaltwrk/spektral/blob/master/apps/web/src/lib/content/docs/api-hooks-reference/index.svx Registers a callback to run on each frame. Accepts an optional key to identify the task. Returns a UseFrameResult with task metadata and control functions. ```APIDOC ## useFrame ### Description Registers a callback to run on each frame. Accepts an optional key to identify the task. Returns a UseFrameResult with task metadata and control functions. ### Signature ```ts useFrame(callback, options?): UseFrameResult useFrame(key, callback, options?): UseFrameResult ``` ### Parameters #### callback - **type**: Function - Required - The callback to execute each frame. #### key - **type**: string - Optional - A unique key for the task. #### options - **type**: UseFrameOptions - Optional - Configuration options. ### UseFrameOptions | Option | Type | Default | | --- | --- | --- | | `autoStart` | `boolean` | `true` | | `autoInvalidate` | `boolean` | `true` | | `invalidation` | `FrameTaskInvalidation` | Implicit | | `stage` | `FrameKey \| FrameStage` | Main stage | | `before`, `after` | Task reference or array | — | | `running` | `() => boolean` | — | ### Return Value `UseFrameResult` contains `task: { key, stage }`, `start()`, `stop()`, and `started: Subscribable`. ### FrameState | Member | Type | | --- | --- | | `time`, `delta` | `number` | | `canvas` | `HTMLCanvasElement` | | `renderMode` | `RenderMode` | | `autoRender` | `boolean` | | `setUniform` | `(name, value) => void` | | `setTexture` | `(name, value) => void` | | `writeStorageBuffer` | `(name, data, { offset? }?) => void` | | `readStorageBuffer` | `(name) => Promise` | | `invalidate` | `(token?) => void` | | `advance` | `() => void` | ### Notes Storage writes require a four-byte-aligned offset and byte length and must fit in the declared buffer. The runtime copies the bytes immediately. Reading a buffer flushes its queued writes in call order before readback. ``` -------------------------------- ### Create a ComputePass with compute shader and resources Source: https://github.com/kaltwrk/spektral/blob/master/apps/web/src/lib/content/docs/api-passes-reference/index.svx Constructor for a compute pass. Requires a WGSL compute shader with @compute, @workgroup_size(...), and @builtin(global_invocation_id). Set workgroupSize when the WGSL uses an override or non-literal constant expression; it must match literal WGSL when both are present. resources is keyed by WGSL alias; an omitted map is equivalent to {}. ```ts new ComputePass({ label?: string, compute: string, workgroupSize?: [number, number?, number?], resources?: ComputeResourceMap, dispatch?: tuple | 'auto' | (context) => [number, number, number], enabled?: boolean }) ``` -------------------------------- ### usePointer Source: https://github.com/kaltwrk/spektral/blob/master/apps/web/src/lib/content/docs/api-hooks-reference/index.svx Hook for pointer tracking with options for enabling, frame requests, capture, click detection, and callbacks. Returns state, lastClick, and resetClick. ```APIDOC ## `usePointer(options?)` ### Options | Option | Default | | --- | --- | | `enabled` | `true` | | `requestFrame` | `'auto'` | | `capturePointer` | `true` | | `trackWhilePressedOutsideCanvas` | `true` | | `clickEnabled` | `true` | | `clickMaxDurationMs` | `350` | | `clickMaxMovePx` | `8` | | `clickButtons` | `[0]` | | `onMove`, `onDown`, `onUp`, `onClick` | — | `requestFrame` accepts `'auto'`, `'invalidate'`, `'advance'`, or `'none'`. Auto resolves to advance in manual mode, invalidate in on-demand mode, and none in always mode. ### Returns The result contains `state: CurrentReadable`, `lastClick: CurrentReadable`, and `resetClick()`. State includes `px`, `uv`, `ndc`, inside/pressed/dragging state, pointer identity and buttons, down position, deltas, and velocities. ``` -------------------------------- ### Fragment entrypoint signature Source: https://github.com/kaltwrk/spektral/blob/master/apps/web/src/lib/content/docs/defining-materials/index.svx The fragment must contain exactly this entrypoint signature. The parameter is uv of type vec2f and the return type is vec4f. ```wgsl fn frag(uv: vec2f) -> vec4f ``` -------------------------------- ### Ordering tasks with after dependency Source: https://github.com/kaltwrk/spektral/blob/master/apps/web/src/lib/content/docs/frame-scheduler/index.svx Orders two tasks in the same stage using the after dependency. The first task is stored in a variable so its task metadata can be referenced; the second task runs after the simulation task. Dependencies accept task keys, metadata, or arrays of either. ```ts const simulation = useFrame('simulation', updateSimulation); useFrame('upload', uploadState, { after: simulation.task }); ``` -------------------------------- ### useTexture: Load URL textures with reactive state Source: https://github.com/kaltwrk/spektral/blob/master/apps/web/src/lib/content/docs/texture-loading/index.svx Loads a batch of textures from URLs with reactive state. The URL input is a string[] or lazy () => string[]; Svelte and Vue also accept a lazy options provider, while React accepts an options object. The returned object exposes textures, loading, error, errorReport, and reload(). ```ts const loaded = useTexture( () => ['/textures/albedo.png', '/textures/normal.png'], { colorSpace: 'srgb', generateMipmaps: true } ); ``` -------------------------------- ### Run Spektral package validation commands Source: https://github.com/kaltwrk/spektral/blob/master/apps/web/src/lib/content/docs/testing-and-internals/index.svx Validation commands for the Spektral package. Run from `packages/spektral`. Core, runtime, and bundle checks are deterministic enough for the normal quality flow; the strict GPU and real-renderer commands are local release gates on the reference Apple M4 Pro/Metal machine and require matching GPU, backend, driver, macOS, Chromium major, and suite fingerprints. ```bash pnpm run build pnpm run test pnpm run check pnpm run lint pnpm run perf:core pnpm run perf:core:check pnpm run perf:runtime pnpm run perf:runtime:check pnpm run perf:gpu:check pnpm run perf:renderer:check pnpm run bundle:check ``` -------------------------------- ### Define external texture reference and use in ComputePass Source: https://github.com/kaltwrk/spektral/blob/master/apps/web/src/lib/content/docs/compute-shaders/index.svx Shows how to define an external texture reference with required metadata and pass it to a ComputePass. The provider runs once per pass per frame and must return a resource for the current device. The resourceId must remain stable for the same logical allocation. ```ts const externalInput = { externalTexture: ({ device }) => getTextureForDevice(device), resourceId: 'camera-decoder-output', format: 'rgba8unorm', usage: GPUTextureUsage.TEXTURE_BINDING, viewDimension: '2d' } satisfies ComputeExternalTextureReference; const pass = new ComputePass({ compute, resources: { uInput: { texture: externalInput, access: 'sampled' } } }); ``` -------------------------------- ### Apply scheduler preset with applySchedulerPreset Source: https://github.com/kaltwrk/spektral/blob/master/apps/web/src/lib/content/docs/render-modes/index.svx Applies a scheduler preset. Available presets are 'performance', 'balanced', and 'debug'. Diagnostics and profiling share one internal toggle, so advanced preset overrides must give them the same value. ```ts import { applySchedulerPreset } from 'spektral/advanced'; applySchedulerPreset(gpu.scheduler, 'balanced'); ``` -------------------------------- ### Declare render targets with FragCanvas Source: https://github.com/kaltwrk/spektral/blob/master/apps/web/src/lib/content/docs/render-targets/index.svx Declares named render targets using the `renderTargets` prop on `FragCanvas`. Each key is used as a pass input or output. Named targets must be written before read, and named routing requires `needsSwap: false`. ```svelte ``` -------------------------------- ### Mount FragCanvas in Svelte Source: https://github.com/kaltwrk/spektral/blob/master/apps/web/src/lib/content/docs/getting-started/index.svx Svelte adapter usage. FragCanvas fills its container; CSS controls visible size, and Spektral sets backing-store resolution from measured size and dpr. ```svelte
``` -------------------------------- ### Run validation checks with pnpm Source: https://github.com/kaltwrk/spektral/blob/master/SKILL.md Run the standard validation commands available in the target package or app. Prefer scoped commands from the monorepo root, such as `pnpm --dir packages/spektral run test` or `pnpm --dir apps/web run check`, and use equivalent package manager commands if the repository uses npm, yarn, or bun. ```bash pnpm run check pnpm run test pnpm run lint ``` -------------------------------- ### ComputePass Source: https://github.com/kaltwrk/spektral/blob/master/apps/web/src/lib/content/docs/api-passes-reference/index.svx Documentation for the ComputePass class, including constructor, resource descriptors, and methods. ```APIDOC ## `new ComputePass(options)` ### Description Creates a compute pass with a WGSL compute shader, optional workgroup size, resources, dispatch configuration, and enabled flag. ### Constructor `new ComputePass(options)` ### Parameters - **label** (string) - Optional - Immutable label for diagnostics and graph snapshots. - **compute** (string) - Required - WGSL compute shader source. - **workgroupSize** ([number, number?, number?]) - Optional - Workgroup size; required when WGSL uses an override or non-literal constant expression. - **resources** (ComputeResourceMap) - Optional - Map of WGSL aliases to resource descriptors. - **dispatch** (tuple | 'auto' | (context) => [number, number, number]) - Optional - Dispatch configuration. - **enabled** (boolean) - Optional - Whether the pass is enabled. ### Resource Descriptor Types - **texture** (string | ComputeExternalTextureReference | ComputeExternalTextureViewReference) - Required - Texture resource. - **access** ('sampled' | 'storage-write') - Required - Access mode. - **view** (ComputeTextureViewDescriptor) - Optional - Texture view descriptor. - **version** ('current' | 'initial') - Optional - Version of the resource. - **pingPong** ('read' | 'write') - Optional - Ping-pong access. - **buffer** (string | ComputeExternalBufferReference) - Required - Buffer resource. - **access** ('storage-read' | 'storage-read-write') - Required - Access mode. - **sampler** (string | ComputeExternalSamplerReference) - Required - Sampler resource. ### Texture View Descriptor - **baseMipLevel** (number) - Optional - Base mip level. - **mipLevelCount** (number) - Optional - Number of mip levels. - **baseArrayLayer** (number) - Optional - Base array layer. - **arrayLayerCount** (number) - Optional - Must be 1. ### Notes - The compute shader must include `@compute`, `@workgroup_size(...)`, a `compute` function, and `@builtin(global_invocation_id)`. - Literal dimensions are inferred; set `workgroupSize` when WGSL uses an override or non-literal constant expression. - Omitted resources map is equivalent to `{}`; no material storage resource is injected implicitly. - External references are borrowed typed objects with a stable `resourceId`. ## `setCompute(source, { workgroupSize? })` ### Description Sets the compute shader source and optionally the workgroup size. ### Parameters - **source** (string) - Required - WGSL compute shader source. - **workgroupSize** ([number, number, number]) - Optional - Workgroup size. ## `setDispatch(dispatch)` ### Description Sets the dispatch configuration. ### Parameters - **dispatch** (tuple | 'auto' | (context) => [number, number, number]) - Required - Dispatch configuration. ## `getCompute()` ### Description Returns the current compute shader source. ### Returns - **string** - The compute shader source. ## `getResources()` ### Description Returns the resource map. ### Returns - **ComputeResourceMap** - The resource map. ## `getWorkgroupSize()` ### Description Returns the workgroup size. ### Returns - **[number, number, number]** - The workgroup size. ## `resolveDispatch(context)` ### Description Resolves the dispatch configuration for a given context. ### Parameters - **context** - Required - The context object. ### Returns - **[number, number, number]** - The resolved dispatch dimensions. ## `dispose()` ### Description Releases resources associated with the compute pass. ### Notes - `isCompute` is a readonly `true` discriminant for inspection; custom compute objects are rejected by the render graph. - `label` is optional and immutable; diagnostics and graph snapshots use it when present, otherwise they derive a deterministic label from the pass kind and declaration index. ``` -------------------------------- ### textureSampleLevel with explicit LOD Source: https://github.com/kaltwrk/spektral/blob/master/apps/web/src/lib/content/docs/compute-shaders/index.svx Shows how to sample a texture in WGSL using a sampler descriptor and an explicit LOD of 0.0. Filtering samplers are valid only with filterable float textures; integer and unfilterable-float textures require non-filtering samplers. ```wgsl let color = textureSampleLevel(uCamera, uCameraSampler, uv, 0.0); ``` -------------------------------- ### Svelte minimal animated component with FragCanvas and useFrame Source: https://github.com/kaltwrk/spektral/blob/master/SKILL.md Svelte minimal animated component using FragCanvas and defineMaterial. The first block defines a material with a fragment shader that animates based on uTime, and the second block uses useFrame to update uTime each frame. Requires a separate Runtime.svelte component. ```svelte ``` ```svelte ``` -------------------------------- ### useFrame with gpu.size.current Source: https://github.com/kaltwrk/spektral/blob/master/apps/web/src/lib/content/docs/hooks-and-context/index.svx Use .current in frame callbacks to read the current canvas size synchronously without creating a subscription. ```ts const gpu = useSpektral(); useFrame(() => { const { width, height } = gpu.size.current; }); ``` -------------------------------- ### defineMaterial(input) Source: https://github.com/kaltwrk/spektral/blob/master/apps/web/src/lib/content/docs/api-material-reference/index.svx Creates an immutable FragMaterial from the provided input, validating the fragment entrypoint, uniforms, textures, defines, includes, and storage buffers. Returns a material whose fields are always present and whose nested descriptors are isolated from the input. ```APIDOC ## defineMaterial(input) ### Description Creates an immutable FragMaterial from the provided input, validating the fragment entrypoint, uniforms, textures, defines, includes, and storage buffers. Returns a material whose fields are always present and whose nested descriptors are isolated from the input. ### Parameters #### Input Object - **fragment** (string) - Required - The WGSL fragment shader source. Must contain `fn frag(uv: vec2f) -> vec4f` in the main source. - **uniforms** (UniformMap) - Optional - Map of uniform values. - **textures** (TextureDefinitionMap) - Optional - Map of texture definitions. - **defines** (MaterialDefines) - Optional - Map of preprocessor defines. - **includes** (MaterialIncludes) - Optional - Map of include sources. - **storageBuffers** (StorageBufferDefinitionMap) - Optional - Map of storage buffer definitions. ### Returns - **FragMaterial** - An immutable material object with six fields always present. Omitted maps resolve to frozen empty objects. Storage-buffer `initialData` reads return defensive typed-array copies; caller-owned DOM and WebGPU objects remain unfrozen. ### Usage Notes - To change a declaration, call `defineMaterial(...)` with a new value and pass the replacement to `FragCanvas`. Do not mutate a returned material or its nested descriptors. - Material helper functions can read the current fragment coordinates from `spektralFragment.uv`. ### Example ```ts const material = defineMaterial({ fragment: `fn frag(uv: vec2f) -> vec4f { return vec4f(uv, 0.0, 1.0); }` }); ``` ``` -------------------------------- ### useFrame signatures Source: https://github.com/kaltwrk/spektral/blob/master/apps/web/src/lib/content/docs/frame-scheduler/index.svx Registers a per-frame callback in the FragCanvas scheduler. The first form takes a callback and optional options; the second adds an explicit string or symbol key for stable ordering and diagnostics. Must run inside the canvas subtree; the adapter lifecycle automatically unregisters the task. ```ts useFrame(callback, options?) useFrame(key, callback, options?) ``` -------------------------------- ### Mount FragCanvas in React Source: https://github.com/kaltwrk/spektral/blob/master/apps/web/src/lib/content/docs/getting-started/index.svx React adapter usage. FragCanvas fills its container; CSS controls visible size, and Spektral sets backing-store resolution from measured size and dpr. ```tsx import { FragCanvas } from 'spektral/react'; export function App() { return
; } ``` -------------------------------- ### Define material with WGSL include Source: https://github.com/kaltwrk/spektral/blob/master/apps/web/src/lib/content/docs/shader-includes-and-defines/index.svx Declares a material with a fragment shader that includes a named chunk via the `#include ` directive. The `includes` object maps the include name to its WGSL source. Include names must be WGSL-safe identifiers; unknown names, empty source, invalid directives, and circular chains throw before shader compilation. ```ts const material = defineMaterial({ fragment: ` #include fn frag(uv: vec2f) -> vec4f { return vec4f(remap(uv.x, 0.0, 1.0), uv.y, 0.0, 1.0); } `, includes: { math: `fn remap(x: f32, a: f32, b: f32) -> f32 { return (x - a) / (b - a); }` } }); ``` -------------------------------- ### Aspect ratio using spektralFrame.resolution Source: https://github.com/kaltwrk/spektral/blob/master/apps/web/src/lib/content/docs/writing-shaders/index.svx Computes the aspect ratio from the physical render resolution. Use this for aspect-correct calculations. ```wgsl let aspect = spektralFrame.resolution.x / spektralFrame.resolution.y; ``` -------------------------------- ### Feedback bindings for PingPongShaderPass Source: https://github.com/kaltwrk/spektral/blob/master/apps/web/src/lib/content/docs/writing-shaders/index.svx Shows the bindings that PingPongShaderPass exposes for its previous state. The target material texture is excluded from that pass's regular texture bindings while it is being written. Sample prior state through spektralPrevious. ```wgsl @group(1) @binding(0) var spektralPreviousSampler: sampler; @group(1) @binding(1) var spektralPrevious: texture_2d; ``` -------------------------------- ### Bind storage buffers in ComputePass Source: https://github.com/kaltwrk/spektral/blob/master/apps/web/src/lib/content/docs/storage-buffers/index.svx Declares compute pass resources that reference material buffers. The map key is the WGSL alias and can differ from the material key. 'storage-read' generates var and a graph read; 'storage-read-write' generates var, reads the imported value, and publishes a current-frame version. A material buffer declared with access: 'read' cannot be bound as storage-read-write. ```ts const integrate = new ComputePass({ compute, resources: { particlesIn: { buffer: 'particles', access: 'storage-read' }, forces: { buffer: 'forces', access: 'storage-read-write' } } }); ``` -------------------------------- ### PingPongComputePass methods Source: https://github.com/kaltwrk/spektral/blob/master/apps/web/src/lib/content/docs/api-passes-reference/index.svx Public API of PingPongComputePass. workgroupSize has the same override/non-literal behavior as ComputePass. Methods manage iteration count, compute source, dispatch, and resource queries. ```ts setIterations(count): void setCompute(source, { workgroupSize? }): void setDispatch(dispatch): void getIterations(): number getCompute(): string getResources(): ComputeResourceMap getWorkgroupSize(): [number, number, number] resolveDispatch(context): [number, number, number] dispose(): void ``` -------------------------------- ### ShaderPass with custom fragment shader Source: https://github.com/kaltwrk/spektral/blob/master/apps/web/src/lib/content/docs/render-passes/index.svx Creates a ShaderPass that multiplies the input color by the UV coordinates. The fragment shader is defined inline and uses the shade function signature. ```ts const pass = new ShaderPass({ fragment: ` fn shade(inputColor: vec4f, uv: vec2f) -> vec4f { return vec4f(inputColor.rgb * vec3f(uv, 1.0), inputColor.a); } ` }); ``` -------------------------------- ### Update uniforms with useFrame Source: https://github.com/kaltwrk/spektral/blob/master/apps/web/src/lib/content/docs/getting-started/index.svx Call useFrame from a descendant of FragCanvas. Declare resource names in defineMaterial before updating them at runtime. The Frame Scheduler documents registration and invalidation. ```ts useFrame((state) => { state.setUniform('uTime', state.time); }); ``` -------------------------------- ### Write user context with setSpektralUserContext and existing: 'skip' Source: https://github.com/kaltwrk/spektral/blob/master/apps/web/src/lib/content/docs/user-context/index.svx Write to a namespace using a factory function. The setter returns the effective value stored under the namespace. The existing option 'skip' keeps an existing value and does not evaluate the factory; the default is 'skip'. ```ts setSpektralUserContext( 'controls', () => ({ enabled: true, speed: 1 }), { existing: 'skip' } ); ``` -------------------------------- ### PingPongShaderPass methods Source: https://github.com/kaltwrk/spektral/blob/master/apps/web/src/lib/content/docs/api-passes-reference/index.svx Public API of PingPongShaderPass. Dimensions and scale must be finite and positive, iterations a positive integer, and format float-sampled. setDimensions, setScale, and reset request A/B reinitialization; consumeResetColor is renderer-facing and clears that pending request. ```ts setFragment(fragment, { defines?, includes? }?): void setIterations(count): void setDimensions(width?, height?): void setScale(scale): void reset(clearColor?): void consumeResetColor(): RGBA | null getCurrentOutput(): string advanceFrame(): void resolveSize(canvasSize): { width, height } getTarget(): string getFragment(): string getFragmentLineMap(): MaterialLineMap getIterations(): number getFormat(): GPUTextureFormat getFilter(): GPUFilterMode getAddressModeU(): GPUAddressMode getAddressModeV(): GPUAddressMode getClearColor(): RGBA dispose(): void ``` -------------------------------- ### Import setSpektralUserContext and useSpektralUserContext from spektral/svelte/advanced Source: https://github.com/kaltwrk/spektral/blob/master/apps/web/src/lib/content/docs/user-context/index.svx Import the advanced user-context functions from the Svelte package. React also exports useSetSpektralUserContext() for writes from effects and event handlers; Vue and Svelte use setSpektralUserContext(...) directly. ```ts import { setSpektralUserContext, useSpektralUserContext } from 'spektral/svelte/advanced'; ``` -------------------------------- ### resolveMaterial(material) Source: https://github.com/kaltwrk/spektral/blob/master/apps/web/src/lib/content/docs/api-material-reference/index.svx Returns cached renderer input for a validated material, including preprocessed WGSL, original sources, uniform values, texture definitions, storage-buffer keys, and a deterministic signature. Intended for adapters, validation, or tooling; applications normally pass the FragMaterial directly to FragCanvas. ```APIDOC ## resolveMaterial(material) ### Description Returns cached renderer input for a validated material, including preprocessed WGSL, original sources, uniform values, texture definitions, storage-buffer keys, and a deterministic signature. Intended for adapters, validation, or tooling; applications normally pass the FragMaterial directly to FragCanvas. ### Parameters #### Material - **material** (FragMaterial) - Required - The material to resolve. ### Returns - **Cached renderer input** - An object containing: - `fragmentWgsl` (string) - Preprocessed WGSL source. - `lineMap` (object) - Line map for the preprocessed source. - `fragment` (string) - Original fragment source. - `includeSources` (object) - Original include sources. - `defineBlock` (string) - Original define block. - `sourceMetadata` (object) - Captured source metadata. - `uniformValues` (object) - Uniform values. - `uniformLayout` (object) - Sorted uniform layout. - `textureDefinitions` (object) - Texture definitions. - `textureKeys` (array) - Sorted texture keys. - `storageTextureKeys` (array) - Storage texture keys. - `storageBufferKeys` (array) - Sorted storage-buffer keys. - `signature` (string) - Deterministic material signature. ### Usage Notes - Spektral-owned cache structures are deeply frozen and cannot be mutated. Repeated calls for the same material return the same protected snapshot. - Caller-owned `TextureSource` values retained as direct sources, including `data.source`, remain direct references and are not frozen. Copy an array before making local tooling edits. ``` -------------------------------- ### Set render mode to on-demand with useSpektral Source: https://github.com/kaltwrk/spektral/blob/master/apps/web/src/lib/content/docs/render-modes/index.svx Sets the render mode to 'on-demand' and invalidates to open the next render gate. Switching to on-demand creates one initial invalidation; in this mode both invalidate() and advance() open the next render gate, while in 'manual' only advance() does. ```ts const gpu = useSpektral(); gpu.renderMode.set('on-demand'); gpu.invalidate(); ``` -------------------------------- ### React minimal animated component with FragCanvas and useFrame Source: https://github.com/kaltwrk/spektral/blob/master/SKILL.md React minimal animated component using FragCanvas, defineMaterial, and useFrame. The material defines a fragment shader that animates based on uTime, and the Runtime component updates uTime each frame. The App component renders the canvas with the material. ```tsx import { FragCanvas, defineMaterial, useFrame } from 'spektral/react'; const material = defineMaterial({ fragment: ` fn frag(uv: vec2f) -> vec4f { let t = 0.5 + 0.5 * sin(spektralUniforms.uTime + uv.x * 8.0); return vec4f(vec3f(t), 1.0); } `, uniforms: { uTime: 0 } }); function Runtime() { useFrame((state) => { state.setUniform('uTime', state.time); }); return null; } export function App() { return ( ); } ``` -------------------------------- ### Advanced user context API signatures (useSpektralUserContext, setSpektralUserContext) Source: https://github.com/kaltwrk/spektral/blob/master/apps/web/src/lib/content/docs/api-hooks-reference/index.svx Provides the type signatures for the advanced user context API. Use the overloaded useSpektralUserContext to read the entire context or a namespaced value, and setSpektralUserContext to write values. The options 'existing' and 'functionValue' control merge behavior and factory evaluation, with defaults 'skip' and 'factory' respectively. ```ts useSpektralUserContext(): CurrentReadable> useSpektralUserContext(namespace): CurrentReadable setSpektralUserContext(namespace, valueOrFactory, options?): T | undefined ``` -------------------------------- ### Generated fragment context declaration Source: https://github.com/kaltwrk/spektral/blob/master/apps/web/src/lib/content/docs/writing-shaders/index.svx Shows the generated SpektralFragment struct and private variable that fragment shaders receive. The generated fragment entrypoint assigns its interpolated UV to spektralFragment.uv immediately before calling frag(...) or shade(...). var is invocation-local WGSL state, not a uniform or storage resource. ```wgsl struct SpektralFragment { uv: vec2f, }; var spektralFragment: SpektralFragment; ``` -------------------------------- ### useFrame hook signatures Source: https://github.com/kaltwrk/spektral/blob/master/apps/web/src/lib/content/docs/api-hooks-reference/index.svx Two overloads for the useFrame hook: one with a callback and optional options, and one with a key, callback, and optional options. The hook returns a UseFrameResult. ```ts useFrame(callback, options?): UseFrameResult useFrame(key, callback, options?): UseFrameResult ``` -------------------------------- ### Define a material with defineMaterial Source: https://github.com/kaltwrk/spektral/blob/master/apps/web/src/lib/content/docs/getting-started/index.svx Create a material outside the component render path. The fragment shader returns a color based on UV coordinates. Declare resource names here before updating them at runtime. ```ts import { defineMaterial } from 'spektral'; const material = defineMaterial({ fragment: ` fn frag(uv: vec2f) -> vec4f { return vec4f(uv, 0.5, 1.0); } ` }); ``` -------------------------------- ### Read storage buffer from CPU Source: https://github.com/kaltwrk/spektral/blob/master/apps/web/src/lib/content/docs/storage-buffers/index.svx Reads back a storage buffer as a copied ArrayBuffer. Requires an initialized renderer. Flushes queued writes for that buffer in call order before the GPU copy, so a write followed by a read observes the new data. The attempted writes are removed from the queue even if flushing or readback fails. Internally uses a MAP_READ | COPY_DST staging buffer and synchronizes GPU work with the CPU; should not be used as a per-frame feedback path. ```ts const bytes = await state.readStorageBuffer('particles'); ``` -------------------------------- ### Read user context with useSpektralUserContext Source: https://github.com/kaltwrk/spektral/blob/master/apps/web/src/lib/content/docs/user-context/index.svx Read the user context. The first overload returns a CurrentReadable view of the complete namespace map; the second returns CurrentReadable for one string or symbol namespace. ```ts const all = useSpektralUserContext(); const controls = useSpektralUserContext('controls'); ``` -------------------------------- ### Mount FragCanvas in Vue Source: https://github.com/kaltwrk/spektral/blob/master/apps/web/src/lib/content/docs/getting-started/index.svx Vue adapter usage. FragCanvas fills its container; CSS controls visible size, and Spektral sets backing-store resolution from measured size and dpr. ```vue
``` -------------------------------- ### Compute sampled texture and sampler resources Source: https://github.com/kaltwrk/spektral/blob/master/apps/web/src/lib/content/docs/textures/index.svx Declares compute resources for sampling a material texture. The pass-local alias uFrame does not rename the material key 'camera' for other passes or the fragment shader. textureSampleLevel requires a sampler descriptor because compute shaders have no implicit derivatives. ```ts resources: { uFrame: { texture: 'camera', access: 'sampled' }, uFrameSampler: { sampler: 'camera' } } ``` -------------------------------- ### useSpektral Source: https://github.com/kaltwrk/spektral/blob/master/apps/web/src/lib/content/docs/api-hooks-reference/index.svx Hook that returns a SpektralContext object with canvas, size, dpr, maxDelta, renderMode, autoRender, user, graph, invalidate, advance, and scheduler members. ```APIDOC ## `useSpektral` Returns `SpektralContext`: | Member | Type | | --- | --- | | `canvas` | `HTMLCanvasElement \| undefined` | | `size` | `CurrentReadable<{ width; height }>` in CSS pixels | | `dpr`, `maxDelta` | `CurrentWritable` | | `renderMode` | `CurrentWritable` | | `autoRender` | `CurrentWritable` | | `user` | `CurrentWritable>` | | `graph` | `SpektralGraph` | | `invalidate`, `advance` | `() => void` | | `scheduler` | `SpektralScheduler` | The scheduler exposes `createStage`, `getStage`, schedule inspection, diagnostics/profiling setters and getters, reset, last-run timings, and rolling snapshots. ``` -------------------------------- ### Declare storage buffer in material Source: https://github.com/kaltwrk/spektral/blob/master/apps/web/src/lib/content/docs/storage-buffers/index.svx Defines a storage buffer in the material with size, type, and access. The size must be a positive byte length multiple of 4. Supported types include array, array, array, array, array, array, array, and array. Access defaults to 'read-write'. ```ts storageBuffers: { particles: { size: 1024 * 16, type: 'array', access: 'read-write' } } ``` -------------------------------- ### Write storage buffer from CPU Source: https://github.com/kaltwrk/spektral/blob/master/apps/web/src/lib/content/docs/storage-buffers/index.svx Queues a write to a storage buffer. Offset and data.byteLength must be finite integer multiples of four, and the write must fit inside the buffer. Writes are flushed before rendering or compute dispatch. An attempted batch is cleared even if the flush or render fails; it is not replayed automatically. Spektral copies the selected bytes when called, so changing the source typed array afterward does not change the queued write. Runtime writes do not rebuild the renderer. ```ts state.writeStorageBuffer('particles', data, { offset: 0 }); ``` -------------------------------- ### Access Spektral bindings with rawCodeSnippet Source: https://github.com/kaltwrk/spektral/blob/master/apps/web/src/lib/content/docs/integrations-typegpu/index.svx Expose a generated Spektral identifier to TypeGPU as a raw code snippet. Available frame fields are 'spektralFrame.time', '.delta', and '.resolution'. User fields use 'spektralUniforms.' and must also be declared in 'defineMaterial({ uniforms })'. ```ts const time = tgpu['~unstable'].rawCodeSnippet( 'spektralFrame.time', d.f32, 'uniform' ); ``` -------------------------------- ### applySchedulerPreset TypeScript signature Source: https://github.com/kaltwrk/spektral/blob/master/apps/web/src/lib/content/docs/api-advanced-reference/index.svx Defines the applySchedulerPreset function that applies a scheduler preset with optional overrides. The preset can be 'performance', 'balanced', or 'debug', and overrides may set diagnosticsEnabled, profilingEnabled, and profilingWindow. The window must be a safe integer from 1 through 10,000, and diagnostics and profiling boolean overrides must match. ```typescript applySchedulerPreset( scheduler, preset: 'performance' | 'balanced' | 'debug', overrides? ): SchedulerPresetConfig ``` -------------------------------- ### ComputePass storage-write texture alias Source: https://github.com/kaltwrk/spektral/blob/master/apps/web/src/lib/content/docs/textures/index.svx Creates a compute pass that writes to a storage texture. Requires an explicit storage-compatible format, width, and height, and rejects a source. The texture is exposed under the pass-local alias uOutput while the material key remains 'motion'. ```ts new ComputePass({ compute, resources: { uOutput: { texture: 'motion', access: 'storage-write' } } }); ``` -------------------------------- ### Toggle autoRender gate Source: https://github.com/kaltwrk/spektral/blob/master/apps/web/src/lib/content/docs/render-modes/index.svx Toggles the global autoRender gate. When false, shouldRender() rejects every mode, including pending manual advances, while the runtime loop and scheduler continue to run. ```ts gpu.autoRender.set(false); gpu.autoRender.set(true); ``` -------------------------------- ### Vignette using spektralFragment.uv Source: https://github.com/kaltwrk/spektral/blob/master/apps/web/src/lib/content/docs/writing-shaders/index.svx Shows how to access the current fragment UV via spektralFragment.uv in a material fragment. The field is available in material fragments, ShaderPass, and PingPongShaderPass, but not in compute shaders. The required uv entrypoint parameter remains part of each fragment contract. ```wgsl fn vignette() -> f32 { let centered = spektralFragment.uv - vec2f(0.5); return 1.0 - smoothstep(0.2, 0.7, length(centered)); } fn frag(uv: vec2f) -> vec4f { return vec4f(vec3f(vignette()), 1.0); } ``` -------------------------------- ### React advanced user-context write with useSetSpektralUserContext Source: https://github.com/kaltwrk/spektral/blob/master/SKILL.md React advanced user-context write using useSetSpektralUserContext. The QualityButton component sets a user context value 'config' with quality 'medium' and merges with existing context. Requires the advanced API from 'spektral/react/advanced'. ```tsx import { useSetSpektralUserContext } from 'spektral/react/advanced'; export function QualityButton() { const setUserContext = useSetSpektralUserContext(); return ( ); } ``` -------------------------------- ### SpektralGraph.getSnapshot Source: https://github.com/kaltwrk/spektral/blob/master/apps/web/src/lib/content/docs/api-hooks-reference/index.svx Method on SpektralGraph that returns a RenderGraphSnapshot with schemaVersion 1. It contains ordered nodes, deduplicated resources, directed edges with dependency reasons, and finalOutput. The snapshot is deeply frozen, serializable, and cached by graph plan. ```APIDOC ## `graph.getSnapshot(): RenderGraphSnapshot` Returns a `RenderGraphSnapshot` which is an experimental, deeply frozen schema with `schemaVersion: 1`. It contains ordered nodes, deduplicated resources, directed edges with dependency reasons, and `finalOutput`. Reads are cached by graph plan: unchanged plans return the same object, while a rebuild returns a new one and leaves earlier snapshots intact. Logical resource IDs come from declarations. Physical IDs are opaque and remain stable only within one renderer lifecycle. The snapshot is serializable and excludes GPU objects, WGSL, uniform or storage data, callbacks, and timings. Before initialization and after teardown, `getSnapshot()` returns the shared empty snapshot. ```