Skip to content

Shader

The Shader object is the main building block in FragmentColor.

It takes a WGSL or GLSL shader source as input, parses it, validates it, and exposes the uniforms as keys.

Shader::new refuses a source that no device FragmentColor opens can run, with a ShaderError that names the problem: a feature outside the set FragmentColor requests (such as ray queries or f64), two globals on one @group and @binding (a lights root included), writable storage in a @vertex entry point, an immediate root that breaks the uniform layout rules, a filtering sampler that samples a depth texture, and two vertex inputs with one name, which would read one mesh attribute. A shader that passes can still be one a given device can’t run, which Renderer::render refuses, as Device limits describes.

Shader::new accepts a source string, a registry slug like "sdf2d/circle", an https:// URL, a local file path, or an array mixing any of those. Array parts are deduplicated by hash and concatenated in order, so you can pull pure helper functions from the public registry at https://fragmentcolor.org/shaders/ into your own shader without copy-pasting. Override the registry base with Shader::set_registry.

To draw your shader, you must use your Shader instance as input to a Renderer.

You can compose Shader instances into a Pass object to create more complex rendering pipelines.

You can also create renderings with multiple Render Passes by passing an array of Pass instances to Renderer::render.

Classic uniforms are declared with var<uniform> and can be nested structs/arrays. FragmentColor exposes every root and nested field as addressable keys using dot and index notation:

  • Set a field: shader.set("u.color", [r, g, b, a])
  • Index arrays: shader.set("u.arr[1]", value)
struct MyUniform {
color: vec4<f32>,
arr: array<vec4<f32>, 2>
};
@group(0) @binding(0) var<uniform> u: MyUniform;

FragmentColor handles std140-style 16-byte alignment for you, and large uniform blobs are pooled internally. There is nothing to configure.

Sampled textures and samplers are supported via texture_* and sampler declarations. You can bind a Texture object created by the Renderer directly to a texture uniform (e.g., shader.set("tex", &texture)); samplers are provided automatically:

  • If a texture is bound in the same group, the sampler defaults to that texture’s sampler.
  • Otherwise, a reasonable default sampler is used.
@group(0) @binding(0) var tex: texture_2d<f32>;
@group(0) @binding(1) var samp: sampler;

1D, 2D and 3D textures bind with the view dimension the WGSL declaration gives. A FragmentColor texture’s view always covers all of it, so a cube, cube array or 2D array slot takes no texture yet, and Renderer::render refuses one with RendererError::BindingError. Integer textures map to Sint / Uint sample types; float textures use filterable float when the device allows it. A filtering sampler never samples a depth texture: use a sampler_comparison with textureSampleCompare, or textureLoad.

Writeable/readable image surfaces are supported via storage textures (texture_storage_*). Access flags are preserved from WGSL and mapped to the device:

  • read -> read-only storage access
  • write -> write-only storage access
  • read_write -> read+write (when supported)
  • atomic -> read, write and the texture atomics below, on r32uint and r32sint
@group(0) @binding(0) var img: texture_storage_2d<rgba8unorm, write>;

Every storage format binds as the format the shader declares. A format or access the device can’t bind fails in Renderer::render before it takes a frame, and so does a bound texture of another format, one without STORAGE_BINDING usage, or one with more than one mip level.

An r32uint or r32sint storage texture with atomic access takes texture atomics: textureAtomicAdd, textureAtomicMin, textureAtomicMax, textureAtomicAnd, textureAtomicOr and textureAtomicXor. Each call changes one texel in a single step, however many invocations reach it at once, and returns no value. Exchange and compare-exchange on textures aren’t in naga, and textureLoad and textureStore work on an atomic texture as on any other storage texture.

@group(0) @binding(0) var counts: texture_storage_2d<r32uint, atomic>;
@compute @workgroup_size(8, 8)
fn cs_main(@builtin(global_invocation_id) id: vec3<u32>) {
textureAtomicAdd(counts, id.xy / 16u, 1u);
}

Shader::new takes such a shader on every platform, and it runs where the device has TEXTURE_ATOMIC: Vulkan, DX12, and Metal from macOS 14 and iOS 17. The browser’s WebGPU, WebGL2 and native GL have no texture atomics, so Renderer::render refuses the shader there with RendererError::FeatureError, whose feature names TEXTURE_ATOMIC. Bind an R32Uint or R32Sint texture from Renderer::create_storage_texture, which takes no extra usage flag for atomics. An r64uint storage texture needs TEXTURE_INT64_ATOMIC, a feature FragmentColor doesn’t request, so Shader::new refuses it.

WGSL reads video frames through texture_external, and FragmentColor fills that slot with an ordinary Texture: shader.set("video", &texture), as for any texture uniform. The shader reads it with textureSampleBaseClampToEdge, textureLoad and textureDimensions.

@group(0) @binding(0) var video: texture_external;
@group(0) @binding(1) var soft: sampler;
@fragment
fn fs_main(@builtin(position) pixel: vec4<f32>) -> @location(0) vec4<f32> {
let size = vec2<f32>(textureDimensions(video));
let filtered = textureSampleBaseClampToEdge(video, soft, pixel.xy / size);
let exact = textureLoad(video, vec2<u32>(pixel.xy));
return mix(filtered, exact, 0.5);
}

Every platform accepts such a shader at Shader::new. It draws on devices with EXTERNAL_TEXTURE, which wgpu offers on Metal and DX12. On Vulkan, OpenGL, WebGL2 and the browser’s WebGPU, Renderer::render refuses the shader with RendererError::FeatureError before it takes a frame, and the error’s feature names EXTERNAL_TEXTURE.

The slot takes a single-sampled 2D texture in Rgba8Unorm, Bgra8Unorm or Rgba16Float and reads its base mip level, which lets a texture with a mip chain bind too. Raw bytes with a size upload as Rgba8Unorm. An 8-bit color image, such as a PNG or a JPEG, decodes into Rgba8UnormSrgb, which the slot refuses with RendererError::BindingError. Name the format when you create the texture from one: renderer.create_texture((bytes, TextureFormat::Rgba8Unorm)).

wgpu counts one external slot as four sampled textures, a sampler and a uniform buffer in each stage that reads it, and Renderer::render counts it the same way against the device’s limits. A stage that reads four external slots counts 16 sampled textures against max_sampled_textures_per_shader_stage.

Structured buffers are supported via var<storage, read> or var<storage, read_write> and can contain nested structs/arrays. FragmentColor preserves and applies the WGSL access flags when creating binding layouts and setting visibility.

struct Buf { a: vec4<f32> };
@group(0) @binding(0) var<storage, read> ssbo: Buf;

Read-only buffers bind with read-only storage access; read_write allows writes where the device supports it. Each binding is visible to the stages whose entry points use it, so a fragment entry point can write a storage buffer or texture on a device with writable fragment storage. CPU-side updates use the same shader.set("path", value) API as uniforms, with array indexing (e.g. buf.items[2].v). Buffer byte spans are computed from the WGSL shape (arrays and structs honor stride and alignment automatically) and large buffers are pooled internally.

@size and @align on the members of a uniform, storage or immediate struct keep their layout on Vulkan, Metal, DX12 and the browser’s WebGPU. The WGSL that wgpu writes for the browser drops both attributes, so FragmentColor hands the browser WGSL with a @size on each member of such a struct, which pins every offset and the struct’s size. The GL backends, WebGL2 and native GL, write a struct into a std140 block member by member and can’t keep such a layout, so Renderer::render refuses it there with RendererError::FeatureError. Spelling the padding out as members works everywhere, as the built-in PBR shader does.

Immediate data, declared with var<immediate>, works on every platform, in render and compute shaders. One root that fits the device’s max_immediate_size takes native immediates. It becomes a classic uniform buffer instead on the web, on the GL backends, on a device without immediates, and when the shader declares more than one root, with one binding per root in the lowest bind group the shader leaves free. On WebGL2 and native GL the uniform is padded to a multiple of 16 bytes, as those backends take it. A root must therefore also follow the uniform layout rules, such as a 16-byte array stride, and Shader::new refuses one that doesn’t. An entry point reads at most one root.

A root that isn’t a struct takes its bytes whole through set, as a storage root does. A struct root also takes each field by name, as in pc.color.

Shader::new takes subgroup built-ins and functions, such as @builtin(subgroup_size) and subgroupAdd, and @builtin(primitive_index) after enable primitive_index;, on every platform. Each runs where the device has its wgpu feature. Elsewhere Renderer::render refuses the shader with RendererError::FeatureError, whose feature names the flag the device lacks.

  • Subgroup operations need SUBGROUP in compute and fragment shaders and SUBGROUP_VERTEX in vertex shaders, and subgroupBarrier also needs SUBGROUP_BARRIER. Vulkan devices with the full set of subgroup operations offer them, as do Metal GPUs of the Apple7, Mac2 and Metal 3 families and DX12 devices with Shader Model 6.0 wave operations. Only Vulkan offers SUBGROUP_VERTEX, and DX12 has no SUBGROUP_BARRIER.
  • primitive_index needs PRIMITIVE_INDEX, which DX12, Vulkan devices with geometry shaders, the same Metal GPU families, OpenGL 3.2 and OpenGL ES 3.2 offer.

Neither runs on the web. Chrome’s WebGPU offers subgroups, but wgpu 30 doesn’t request them for the device it opens there, and WebGL2 has neither. Native GL offers no subgroups. Write subgroup code in WGSL and leave out enable subgroups;, which naga doesn’t take yet:

@group(0) @binding(0) var<storage, read_write> sums: array<u32, 64>;
@compute @workgroup_size(64)
fn cs_main(@builtin(local_invocation_index) index: u32) {
sums[index] = subgroupAdd(1u);
}

After enable f16;, a shader holds 16-bit floats: f16, its vectors and its square matrices, in uniforms, storage buffers and vertex inputs. The directive opens the source, or the part that needs it when Shader::new joins several parts.

enable f16;
struct Light { color: vec3<f16>, power: f16 };
@group(0) @binding(0) var<uniform> light: Light;
@group(0) @binding(1) var<uniform> gain: f16;
@fragment
fn fs_main() -> @location(0) vec4<f32> {
let color = light.color * light.power * gain;
return vec4<f32>(vec3<f32>(color), 1.0);
}

set takes plain numbers for an f16 key, as it does for an f32 one, and rounds each to the nearest f16. NaN, infinities and numbers past ±65504 that don’t round back to it throw, and the key keeps its value. get returns the rounded value as f32 numbers in every language, so 0.1 reads back as 0.0999755859375. Past 2048, an f16 skips some whole numbers, as an f32 does past 2^24, and rounding one raises no error.

A Camera or Scene::ambient value that an f16 field can’t hold leaves the field as it was, and Renderer::render returns the same error until a later value fits.

A vertex input declared as f16 or vec4<f16> reads the mesh’s 32-bit floats, which the GPU converts, so one mesh feeds f32 and f16 shaders alike. An attach error names the type the shader declares, such as vec2<f16>.

Values take WGSL’s f16 layout: 2 bytes for each component, a vec3<f16> aligned to 8 bytes, and the columns of a mat3x3<f16> 8 bytes apart. A root such as var<uniform> gain: f16 spans 2 bytes, and Renderer::read_storage returns exactly as many bytes as a storage root spans. Immediate data can’t hold f16, which Shader::new refuses.

A color output must be vec4<f32>, never vec4<f16>, since wgpu refuses a narrower float at @location(0). Convert the result before the fragment shader returns it, as vec4<f32>(vec3<f32>(color), 1.0) does above.

Every platform accepts such a shader at Shader::new. It draws where the device has SHADER_F16: every Metal device, DX12 with Shader Model 6.2, Vulkan devices with f16 arithmetic and 16-bit storage, and the browser’s WebGPU where the browser offers shader-f16. On WebGL2, OpenGL and every other device, Renderer::render refuses the shader with RendererError::FeatureError before it takes a frame, and the error’s feature names SHADER_F16.

Renderer::render checks each shader against the device before it takes a frame, so every platform returns the same error from the call that caused it, the web included. Each refusal has a typed error with fields:

  • RendererError::LimitError { item, limit, value, max } for a group past max_bind_groups, a binding past max_bindings_per_bind_group, more bindings of a kind in one stage than the device takes, a uniform or storage buffer past its binding size limit, a workgroup past the device’s sizes, invocations or workgroup memory, and a vertex input at a location past max_vertex_attributes. A mesh whose stride or buffers pass the device’s limits gets it too.
  • RendererError::FeatureError { item, feature } for a compute shader on a device without compute, storage a stage of the device can’t bind, a storage format or access the device lacks, such as an atomic storage texture on a device without TEXTURE_ATOMIC, an external texture on a device without EXTERNAL_TEXTURE, an explicit layout on a GL backend, a shader that measures its light roots with arrayLength on a device that takes lights through a uniform block, a shader feature the device lacks, such as subgroups or f16, whose feature names the wgpu flag, and anything else the device’s shader validator refuses.
  • RendererError::BindingError { uniform, expected, found } for a texture uniform that was never set, or whose texture its slot can’t take by format, usage, dimension, sample count or mip levels.
  • RendererError::EntryError { stage } for a render shader without its @vertex or @fragment entry point.

JavaScript throws an Error named after the class Python raises, such as LimitError, with the same fields as properties. Python raises LimitError, FeatureError, BindingError and EntryError, each a FragmentColorError with the fields as attributes. Swift throws FragmentColorError.Limit, .Feature, .Binding and .Entry, and Kotlin the FragmentColorException subclasses of the same names.

An unset PBR map slot, such as base_color_map, binds a 1x1 default in a render shader, when the slot takes a 2D float texture. One set to a texture unregister_texture removed, or one another Renderer created, returns RendererError::TextureNotFoundError. A Material map that this Renderer holds no copy of yet binds the PBR default when its slot has one of the five PBR names, sits in a render shader and takes a 2D float texture, as an unset slot does, and returns RendererError::BindingError otherwise. That happens on the web before load, where the error asks for load, and on native for a map that another thread sets while render runs, which the next render uploads.

use fragmentcolor::{Shader, Renderer};
let shader = Shader::new(r#"
@vertex
fn vs_main(@builtin(vertex_index) index: u32) -> @builtin(position) vec4<f32> {
var pos = array<vec2<f32>, 3>(
vec2<f32>(-1.0, -1.0),
vec2<f32>( 3.0, -1.0),
vec2<f32>(-1.0, 3.0)
);
return vec4<f32>(pos[index], 0.0, 1.0);
}
@group(0) @binding(0)
var<uniform> resolution: vec2<f32>;
@fragment
fn fs_main() -> @location(0) vec4<f32> {
return vec4<f32>(1.0, 0.0, 0.0, 1.0); // Red
}
"#)?;
// Set the "resolution" uniform
shader.set("resolution", [800.0, 600.0])?;
let res: [f32; 2] = shader.get("resolution")?;
let renderer = Renderer::new();
let target = renderer.create_texture_target([16, 16]).await?;
renderer.render(&shader, &target)?;

Creates a new Shader. The input is a single string, or an array of strings, of any of these shapes:

  • a raw WGSL source string
  • a registry slug like "sdf2d/circle", which pulls a helper function from the public registry at https://fragmentcolor.org/shaders/
  • an https:// URL pointing at a .wgsl file
  • a local file path ending in .wgsl, .glsl, .frag, or .vert

When you pass an array, parts are deduplicated by source hash and concatenated in order before validation, so you can compose pure helper functions from the registry with your own source. The enable, requires and diagnostic directives a later part opens with move to the top, the only place WGSL takes them, so a helper can carry the enable it needs.

If validation fails, the error message points at the line and column in the parts as written, joined in order by two line breaks. A shader that passes is one some device can run: Renderer::render still checks it against its own device, and refuses one past that device’s limits or features with a typed error. All uniforms are initialized to zero.

GLSL is supported only as a single part (a .vert, .frag, or .glsl file). Mixing GLSL with other parts is rejected.

An empty string, or an empty array, gives the default shader.

Platform Registry slugs and registry URLs Other https:// URLs File paths
Rust (desktop) Bundled shader library, offline Fetched with the network feature, an error without it Read from disk
Python Bundled shader library, offline Fetched by a wheel built with the network feature, an error otherwise Read from disk
Swift / Kotlin Bundled shader library, offline Not fetched; a network error Read from disk
Web, Shader.fetch The browser’s fetch() The browser’s fetch() Fetched relative to the page’s origin
Web, new Shader Not fetched; an error that points at Shader.fetch Not fetched; an error Not fetched; an error

After Shader::set_registry, slugs and registry URLs are fetched first on every platform, and the bundled copy stands in when the fetch fails. A slug resolves against the new registry. A registry URL is fetched as written, so https://fragmentcolor.org/shaders/sdf2d/circle.wgsl still asks the default registry.

use fragmentcolor::Shader;
let shader = Shader::new(r#"
@vertex
fn vs_main(@builtin(vertex_index) index: u32) -> @builtin(position) vec4<f32> {
var pos = array<vec2<f32>, 3>(
vec2<f32>(-1.0, -1.0),
vec2<f32>( 3.0, -1.0),
vec2<f32>(-1.0, 3.0)
);
return vec4<f32>(pos[index], 0.0, 1.0);
}
@group(0) @binding(0)
var<uniform> resolution: vec2<f32>;
@fragment
fn fs_main() -> @location(0) vec4<f32> {
return vec4<f32>(1.0, 0.0, 0.0, 1.0); // Red
}
"#)?;
use fragmentcolor::Shader;
let main = r#"
@vertex fn vs(@builtin(vertex_index) i: u32) -> @builtin(position) vec4<f32> {
let p = array<vec2<f32>,3>(vec2f(-1.,-1.), vec2f(3.,-1.), vec2f(-1.,3.));
return vec4<f32>(p[i], 0.0, 1.0);
}
@fragment fn fs(@builtin(position) pos: vec4<f32>) -> @location(0) vec4<f32> {
let d = circle(pos.xy - vec2<f32>(400.0, 300.0), 100.0);
let n = simplex2(pos.xy * 0.01);
return vec4<f32>(vec3<f32>(step(0.0, d) + n * 0.1), 1.0);
}
"#;
let shader = Shader::new([
"sdf2d/circle", // pure function: fn circle(p: vec2<f32>, r: f32) -> f32
"noise/simplex2", // pure function: fn simplex2(v: vec2<f32>) -> f32
main,
])?;

Async constructor that returns a compiled Shader from one or more parts. Each part can be:

  • a raw WGSL source string
  • a registry slug like "sdf2d/circle"
  • an https:// URL pointing at a .wgsl file
  • a local file path ending in .wgsl, .glsl, .frag, or .vert

Parts are deduplicated by source hash and concatenated in order before compilation. fetch is the async path used when any part needs network or file I/O. Shader::new covers the same shapes for callers that prefer a synchronous constructor.

Platform Spelling Async mechanism
Web (JS) await Shader.fetch(input) Promise via wasm_bindgen async
Python Shader.fetch(input) Blocks the calling thread via pollster::block_on
Swift try await Shader.fetch(input) async throws via uniffi async method
Kotlin Shader.fetch(input) suspend fun via uniffi async method

Note (Swift / Kotlin): the underlying uniffi binding is an async instance method. The Swift and Kotlin Shader.fetch(...) extensions call it on a throwaway default shader, so callers see a static factory.

Platform Registry slugs and registry URLs Other https:// URLs File paths
Rust (desktop) Bundled shader library, offline Fetched with the network feature, an error without it Read from disk
Python Bundled shader library, offline Fetched by a wheel built with the network feature, an error otherwise Read from disk
Swift / Kotlin Bundled shader library, offline Not fetched; a network error Read from disk
Web, Shader.fetch The browser’s fetch() The browser’s fetch() Fetched relative to the page’s origin
Web, new Shader Not fetched; an error that points at Shader.fetch Not fetched; an error Not fetched; an error

After Shader::set_registry, slugs and registry URLs are fetched first on every platform, and the bundled copy stands in when the fetch fails. A slug resolves against the new registry. A registry URL is fetched as written, so https://fragmentcolor.org/shaders/sdf2d/circle.wgsl still asks the default registry.

use fragmentcolor::Shader;
// Full registry URL.
let shader = Shader::fetch("https://fragmentcolor.org/shaders/sdf2d/circle.wgsl").await?;
// Equivalent shorthand using the registry slug.
let shader2 = Shader::fetch("sdf2d/circle").await?;

Sets the value of the uniform identified by the given key.

If the key does not exist or the value format is incorrect, the set method throws an exception. The shader remains valid, and if the exception is caught, the shader can still be used with the renderer.

set never waits for a draw. When another thread holds the shader’s storage, the value is queued and applied before the next draw. A texture can wait a moment while another thread binds a texture to the same shader, or while the renderer applies the shader’s queued values, so the latest one wins. A bad value that can’t be checked right away is dropped later with a logged warning instead of throwing.

The uniform’s declared WGSL type decides how the value is read, so a call behaves the same in every language:

  • A number fits an f32, f16, i32, or u32 uniform. Integer uniforms take whole numbers in range. A float uniform rounds the number to its type, so an f16 one keeps the nearest f16, and NaN, infinities and numbers past the type’s range throw.
  • A vector takes exactly as many numbers as it has components. A mat2x2, mat3x3, or mat4x4 takes 4, 9, or 16.
  • A Texture created by a Renderer binds to a texture uniform, a texture_external one included.
  • Raw bytes replace a whole storage-buffer or push-constant root: a byte slice in Rust, a Uint8Array in JavaScript, bytes (or a bytearray or memoryview) in Python, Data in Swift, or a ByteArray in Kotlin. The byte count must equal the root’s size, and any other length throws.

Setting one field of a storage root uploads the whole root from the shader’s CPU copy at the next render that binds it, which overwrites everything a compute pass wrote to that root.

use fragmentcolor::{Renderer, Shader};
let r = Renderer::new();
let shader = Shader::new(r#"
enable f16;
@group(0) @binding(0) var<uniform> resolution: vec2<f32>;
@group(0) @binding(1) var<uniform> gain: f16;
struct VOut { @builtin(position) pos: vec4<f32> };
@vertex fn vs_main(@builtin(vertex_index) i: u32) -> VOut {
var p = array<vec2<f32>, 3>(vec2<f32>(-1.,-1.), vec2<f32>(3.,-1.), vec2<f32>(-1.,3.));
var out: VOut;
out.pos = vec4<f32>(p[i], 0., 1.);
return out;
}
@fragment fn main() -> @location(0) vec4<f32> { return vec4<f32>(f32(gain), 0., 0., 1.); }
"#)?;
// Set scalars/vectors on declared uniforms
shader.set("resolution", [800.0, 600.0])?;
shader.set("gain", 0.5)?;

Returns the current value of the uniform identified by the given key.

A struct or array root reads back as its bytes, and set doesn’t take those bytes back for that root. Set a struct one field at a time ("light.color") and an array one element at a time ("weights[0]"). Only a storage-buffer or push-constant root takes its whole bytes.

An f16 uniform reads back as f32 numbers that hold the value rounded to f16, so 0.1 reads back as 0.0999755859375.

A texture slot reads back the id of what it binds. A Material map’s slot holds the map’s id from the setter call on, before any Renderer loads it.

use fragmentcolor::Shader;
let shader = Shader::default();
shader.set("resolution", [800.0, 600.0])?;
let res: [f32; 2] = shader.get("resolution")?;

Returns a list of all uniform names in the Shader (excluding struct fields).

use fragmentcolor::Shader;
let shader = Shader::default();
let list = shader.list_uniforms();

Returns a list of all keys in the Shader, including uniform names and struct fields using the dot notation. Array elements aren’t listed, and set and get still take them by index, as in u.items[2].v.

list_keys never blocks. When another thread holds the shader’s storage, it returns an empty list and logs a warning.

use fragmentcolor::Shader;
let shader = Shader::default();
let keys = shader.list_keys();

Build a basic WGSL shader source from a single Vertex layout.

This inspects the vertex position dimensionality (2D or 3D) and optional properties. It generates a minimal vertex shader that consumes @location(0) position and a fragment shader that returns a flat color by default. If a color: vec4<f32> property exists, the shader reads it at @location(1), whatever its place among the vertex’s properties, and uses it as the output.

This is intended as a fallback and for quick debugging. Canonical usage is the opposite: write your own shader and then build Meshes that match it.

It returns Result<Shader, ShaderError>, like Shader::new.

use fragmentcolor::{Shader, Vertex};
let vertex = Vertex::new([0.0, 0.0, 0.0]);
let shader = Shader::from_vertex(&vertex)?;

Build a basic WGSL shader source from the first vertex in a Mesh.

The resulting shader automatically adds the provided Mesh to its internal list of Meshes to render, so the user doesn’t need to call Shader::add_mesh manually.

This function uses the first Vertex to infer position dimensionality and optional properties.

It generates a minimal vertex shader that consumes @location(0) position and a fragment shader that returns a flat color by default. If a color: vec4<f32> property exists, it is passed through to the fragment stage and used as output.

from_mesh returns Result<Shader, ShaderError>. A mesh with no vertices returns ShaderError::InvalidKey, since there is no first vertex to build from. A mesh the new shader refuses returns the error Shader::add_mesh gives, such as a vertex whose position has another dimension than the first one’s.

use fragmentcolor::{Mesh, Shader};
let mut mesh = Mesh::new();
mesh.add_vertices([
[-0.5, -0.5, 0.0],
[0.5, -0.5, 0.0],
[0.0, 0.5, 0.0],
]);
let shader = Shader::from_mesh(&mesh)?;

Attach a Mesh to this Shader. The Renderer draws every mesh attached to it, one draw call per mesh. Meshes that lay out their data alike share one pipeline, and a mesh whose stride, attribute offsets or instance stream differ draws with a pipeline of its own.

add_mesh checks every vertex and instance of the mesh against the shader’s @location inputs and returns Result<(), ShaderError>.

  • An attribute set from numbers takes the type the shader declares at its location: floats for f32, f16 and their vectors, integers for u32, i32 and their vectors when every value is whole and fits. The mesh holds 32-bit floats for an f16 input, and the GPU converts them. A float takes a number only when it stays finite after rounding to the declared type, so NaN, infinities, numbers past the f32 range, and numbers past ±65504 for an f16 input, its position included, fail.
  • On success, the mesh is attached, its attributes keep those types for as long as the mesh lives, and it is drawn when this shader renders.
  • On a missing attribute or a value that doesn’t fit, the error names the attribute, the declared type and the value, or the vertex or instance that lacks it. The mesh isn’t attached and records no type.
  • A shader that declares another type for an attribute an earlier shader already typed on this mesh fails to attach.
  • A vertex that sets a property named position fails with ShaderError::InvalidKey, since its position comes from Vertex::new.
  • A vertex or instance added after the attach must hold every attribute the shader reads, each value in the range of the type the shader declares, f16 included. Renderer.render returns MeshError::InvalidVertex or MeshError::InvalidInstance naming the attribute and that type otherwise.
  • The @location members of a struct argument are inputs too, each read from the attribute of its own name, so struct VIn { @location(1) color: vec4<f32> } reads color. Built-in members such as @builtin(vertex_index) read nothing from the mesh.
  • A shader with no @location inputs, in its arguments or their members, draws fullscreen and rejects every mesh with ShaderError::InvalidKey.

Use Shader::validate_mesh for performing a compatibility check without attaching.

use fragmentcolor::{Shader, Mesh};
let shader = Shader::new(r#"
@vertex fn vs_main(@location(0) pos: vec3<f32>) -> @builtin(position) vec4<f32> {
return vec4<f32>(pos, 1.0);
}
@fragment fn fs_main() -> @location(0) vec4<f32> { return vec4<f32>(1.,0.,0.,1.); }
"#)?;
let mesh = Mesh::new();
mesh.add_vertices([
[-0.5, -0.5, 0.0],
[0.5, -0.5, 0.0],
[0.0, 0.5, 0.0],
]);
// Attach mesh to this shader (errors if incompatible)
shader.add_mesh(&mesh)?;
// Renderer will draw the mesh when rendering this pass.
// Meshes that lay out their vertices alike draw with one
// RenderPipeline, and each other layout gets one of its own.

Remove a single Mesh previously attached to this Shader. If the Mesh is attached multiple times, removes the first match. Once the shader holds the mesh no more, a vertex or instance added to the mesh may leave out what this shader reads.

use fragmentcolor::{Shader, Mesh};
let shader = Shader::new(r#"
struct VOut { @builtin(position) pos: vec4<f32> };
@vertex
fn vs_main(@location(0) pos: vec2<f32>) -> VOut {
var out: VOut;
out.pos = vec4<f32>(pos, 0.0, 1.0);
return out;
}
@fragment
fn fs_main(_v: VOut) -> @location(0) vec4<f32> { return vec4<f32>(1.0,0.0,0.0,1.0); }
"#)?;
let mesh = Mesh::new();
mesh.add_vertices([
[-0.5, -0.5],
[0.5, -0.5],
[0.0, 0.5],
]);
shader.add_mesh(&mesh)?;
// Detach the mesh
shader.remove_mesh(&mesh);

Remove multiple meshes from this Shader.

use fragmentcolor::{Shader, Mesh};
let shader = Shader::new(r#"
struct VOut { @builtin(position) pos: vec4<f32> };
@vertex
fn vs_main(@location(0) pos: vec2<f32>) -> VOut {
var out: VOut;
out.pos = vec4<f32>(pos, 0.0, 1.0);
return out;
}
@fragment
fn fs_main(_v: VOut) -> @location(0) vec4<f32> { return vec4<f32>(1.0,0.0,0.0,1.0); }
"#)?;
let m1 = Mesh::new();
m1.add_vertices([
[-0.5, -0.5],
[0.0, -0.5],
[-0.5, 0.0],
]);
let m2 = Mesh::new();
m2.add_vertices([
[0.0, 0.0],
[0.5, 0.0],
[0.0, 0.5],
]);
shader.add_mesh(&m1)?;
shader.add_mesh(&m2)?;
shader.remove_meshes([&m1, &m2]);

Remove all meshes attached to this Shader. A vertex or instance added to one of them afterwards may leave out what this shader reads.

use fragmentcolor::{Shader, Mesh};
let shader = Shader::new(r#"
struct VOut { @builtin(position) pos: vec4<f32> };
@vertex
fn vs_main(@location(0) pos: vec2<f32>) -> VOut {
var out: VOut;
out.pos = vec4<f32>(pos, 0.0, 1.0);
return out;
}
@fragment
fn fs_main(_v: VOut) -> @location(0) vec4<f32> { return vec4<f32>(1.0,0.0,0.0,1.0); }
"#)?;
let mesh = Mesh::new();
mesh.add_vertices([
[-0.5, -0.5],
[0.5, -0.5],
[0.0, 0.5],
]);
shader.add_mesh(&mesh)?;
// Clear all
shader.clear_meshes();

Validate that a Mesh is compatible with this Shader’s vertex inputs.

  • Checks that every @location input of the vertex entry point finds an attribute, that every vertex and instance holds each attribute the shader reads, and that every value fits the type the input declares. The @location members of a struct argument count as inputs, each under its member name.
  • Matches each input in this order:
    1. by name, instance attributes first, then vertex attributes (position included)
    2. the position, at @location(0)
    3. by the attribute’s own location, instance attributes first, then vertex attributes
  • A number fills a float input unless the shader declares an integer type there. An integer input takes whole numbers that fit its type.
  • Returns Ok(()) when every input matches; returns the same error Shader::add_mesh would otherwise.
  • Shader::add_mesh and Pass::add_mesh run the same check. Call validate_mesh to test a mesh without attaching it.
  • It changes nothing: the mesh isn’t attached and its attributes take no type.
  • If the Shader has no @location inputs, as arguments or struct members, it draws fullscreen and attaching a Mesh is rejected. A struct of built-ins only, such as @builtin(vertex_index), still counts as no input.
  • This method does not allocate GPU buffers; it inspects CPU-side vertex/instance data only.
use fragmentcolor::{Shader, Pass, Mesh};
let shader = Shader::new(r#"
struct VOut { @builtin(position) pos: vec4<f32> };
@vertex fn vs_main(@location(0) pos: vec3<f32>) -> VOut {
var out: VOut;
out.pos = vec4<f32>(pos, 1.0);
return out;
}
@fragment fn fs_main(_v: VOut) -> @location(0) vec4<f32> { return vec4<f32>(1.,0.,0.,1.); }
"#)?;
let pass = Pass::from_shader("p", &shader);
let mesh = Mesh::new();
mesh.add_vertices([
[-0.5, -0.5, 0.0],
[ 0.5, -0.5, 0.0],
[ 0.0, 0.5, 0.0],
]);
shader.validate_mesh(&mesh)?; // Ok
pass.add_mesh(&mesh)?;

Returns true if this Shader is a compute shader (has a compute entry point).

use fragmentcolor::Shader;
let shader = Shader::new(r#"
@compute @workgroup_size(1)
fn cs_main() { }
"#)?;
// Call the method
let is_compute = shader.is_compute();

Override the base URL used to resolve shader slugs (e.g. "sdf2d/circle").

When a slug is passed to Shader::new, it is expanded to:

<base_url>/<slug>.wgsl

The default base URL is https://fragmentcolor.org/shaders/, which serves the public shader registry. Override it to point at your own collection (a CDN, a local dev server, or a mirror) without changing the rest of your code.

The base may end with or without a trailing slash; both are normalized at lookup time.

This setting is process-wide. It applies to every subsequent call to Shader::new(...) until overridden again.

A full URL into the default registry keeps pointing there. After set_registry, https://fragmentcolor.org/shaders/sdf2d/circle.wgsl is fetched as written, and the bundled shader library stands in when the fetch fails. Builds without the network feature, such as the Swift and Kotlin packages, always take the bundled copy.

use fragmentcolor::Shader;
// Point at your own mirror of the registry
Shader::set_registry("https://cdn.example.com/shaders/");
// Now the slug "sdf2d/circle" resolves to https://cdn.example.com/shaders/sdf2d/circle.wgsl
// (Skipping the actual fetch in this doctest)

Creates a new Shader from the default shader source.

Useful for examples and quick demos. Includes a “resolution” uniform.

struct VertexOutput {
@builtin(position) coords: vec4<f32>,
}
@group(0) @binding(0)
var<uniform> resolution: vec2<f32>;
@vertex
fn vs_main(@builtin(vertex_index) in_vertex_index: u32) -> VertexOutput {
let x = f32(i32(in_vertex_index) - 1);
let y = f32(i32(in_vertex_index & 1u) * 2 - 1);
return VertexOutput(vec4<f32>(x, y, 0.0, 1.0));
}
@fragment
fn fs_main(pixel: VertexOutput) -> @location(0) vec4<f32> {
let _dummy = resolution.x + resolution.y * 0.0;
return vec4<f32>(1.0, 0.0, 0.0, 1.0);
}
use fragmentcolor::{Shader};
let shader = Shader::default();
// The default shader includes a "resolution" uniform
shader.set("resolution", [800.0, 600.0])?;
let res: [f32; 2] = shader.get("resolution")?;