Renderer
Description
Section titled “Description”The Renderer is the main entry point for FragmentColor and normally the first object you create.
It is used to render Shaders and Passes (single passes or any iterable of them) to a Target (canvas, window, or texture).
The Renderer internals are lazily initialized when the user creates a Target.
See the constructor Renderer::new() description below for details.
Example
Section titled “Example”use fragmentcolor::{Shader, Renderer, Target};
let renderer = Renderer::new();
// The canvas comes from your platform's windowing systemlet target = renderer.create_target(canvas).await?;let texture_target = renderer.create_texture_target([16, 16]).await?;
// RENDERINGrenderer.render(&Shader::default(), &texture_target)?;
// That's it. Welcome to FragmentColor!import { Shader, Renderer } from "fragmentcolor";1 collapsed line
const canvas = document.createElement("canvas");
const renderer = new Renderer();
// The canvas comes from your platform's windowing systemconst target = await renderer.createTarget(canvas);const texture_target = await renderer.createTextureTarget([16, 16]);
// RENDERINGrenderer.render(Shader.default(), texture_target);
// That's it. Welcome to FragmentColor!from fragmentcolor import Shader, Renderer2 collapsed lines
from rendercanvas.auto import RenderCanvascanvas = RenderCanvas(size=(800, 600))
renderer = Renderer()
# The canvas comes from your platform's windowing systemtarget = renderer.create_target(canvas)texture_target = renderer.create_texture_target([16, 16])
# RENDERINGrenderer.render(Shader.default(), texture_target)
# That's it. Welcome to FragmentColor!import FragmentColor2 collapsed lines
import QuartzCorelet canvas = CAMetalLayer()
let renderer = Renderer()
// The canvas comes from your platform's windowing systemlet target = try renderer.createTarget(canvas)let texture_target = try await renderer.createTextureTarget([16, 16])
// RENDERINGtry renderer.render(Shader.default(), texture_target)
// That's it. Welcome to FragmentColor!import org.fragmentcolor.*2 collapsed lines
val surfaceTexture = android.graphics.SurfaceTexture(0)val canvas = android.view.Surface(surfaceTexture)
val renderer = Renderer()
// The canvas comes from your platform's windowing systemval target = renderer.createTarget(canvas)val texture_target = renderer.createTextureTarget(listOf(16u, 16u))
// RENDERINGrenderer.render(Shader.default(), texture_target)
// That's it. Welcome to FragmentColor!1 collapsed line
surfaceTexture.release()Methods
Section titled “Methods”Renderer::create_depth_texture
Section titled “Renderer::create_depth_texture”Create a depth texture using Depth32Float.
A pass that draws models gets a depth buffer without one. Create a depth texture to read depth in a later pass, or to give depth to a pass of plain meshes.
A width or height of zero, a side past the device limit, or a depth other than 1 is an error, the one resize returns: TextureError::InvalidInput inside InitializationError::TextureError in Rust.
The created depth texture inherits the renderer’s current sample count:
- If you called
create_target(window)(surface-backed), it matches the negotiated MSAA (e.g., 2×/4×) for that surface. - If you are rendering offscreen via
create_texture_target, it defaults to 1.
This ensures the depth attachment sample_count matches the pass sample count.
A depth texture with a different sample_count than the pass makes render return
RendererError::DepthSampleCountMismatch, and one whose width or height differs from
the pass’s color attachment returns RendererError::DepthSizeMismatch, before it takes
a frame. A window that resizes needs a depth texture of the new size, or a resize of this one.
Example
Section titled “Example”use fragmentcolor::Renderer;let r = Renderer::new();let depth = r.create_depth_texture([800, 600]).await?;import { Renderer } from "fragmentcolor";const r = new Renderer();const depth = await r.createDepthTexture([800, 600]);from fragmentcolor import Rendererr = Renderer()depth = r.create_depth_texture([800, 600])import FragmentColorlet r = Renderer()let depth = try await r.createDepthTexture([800, 600])import org.fragmentcolor.*val r = Renderer()val depth = r.createDepthTexture(listOf(800u, 600u))Renderer::create_storage_texture
Section titled “Renderer::create_storage_texture”Create a storage-class texture for compute shaders, image store/load, or as a render target.
Common forms:
(size, format): empty storage texture, no initial data.(size, format, bytes): storage texture pre-seeded withbytes, exactly the size’s pixel count times the format’s bytes per pixel.- A full
TextureInput { data, options }literal: passoptions.usage(viaTextureOptions::with_usage(...)) for non-default usage flags.
size is required; storage textures have no source to infer dimensions from. Missing it returns RendererError::CreateTextureError.
A depth of 1, or none, makes a 2D texture, and a larger depth makes a 3D texture. A side of zero, or a size past the device’s limits for that kind of texture, is an error that reaches no GPU call: TextureError::InvalidInput inside RendererError::TextureError in Rust, a thrown Error named InvalidInputError in JavaScript, InvalidInputError (a FragmentColorError) in Python, FragmentColorError in Swift and FragmentColorException in Kotlin.
options.usage overrides the default mask of STORAGE_BINDING | TEXTURE_BINDING | COPY_SRC | COPY_DST. Every binding has the same named TextureUsage flags, combined with | (or in Kotlin). The other bindings take the size, format, optional bytes and optional usage as separate arguments. An empty mask, or a bit outside the five TextureUsage flags, is the same InvalidInput error. So is a usage the format can’t take on this device, such as STORAGE_BINDING on Depth32Float or Rgba8UnormSrgb, and a depth texture with a depth past 1.
R32Uint, R32Sint and R32Float hold one 32-bit value per texel, which reads back as 4 little-endian bytes. A compute shader reads and writes them in place through a read_write storage slot, which WebGPU guarantees for these three formats, so it works in the browser too. An R32Uint or R32Sint texture also binds to an atomic slot, such as texture_storage_2d<r32uint, atomic>, where texture atomics change a texel safely from many invocations at once. They need no usage flag of their own. Texture atomics run on Vulkan, DX12, and Metal from macOS 14 and iOS 17. The browser’s WebGPU and GL have none, so there Renderer::render returns RendererError::FeatureError for such a shader before it takes a frame.
Example
Section titled “Example”use fragmentcolor::{Renderer, Shader, TextureFormat};
let r = Renderer::new();
// Empty storage texture.let tex = r.create_storage_texture(([64, 64], TextureFormat::Rgba)).await?;
// Pre-seeded with bytes.let pixels = vec![0; 64 * 64 * 4];let tex2 = r .create_storage_texture(([64, 64], TextureFormat::Rgba, pixels)) .await?;
// One 32-bit counter per texel, for texture atomics.let counts = r.create_storage_texture(([4, 4], TextureFormat::R32Uint)).await?;let shader = Shader::new(r#"@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.set("counts", &counts)?;import { Renderer, Shader, TextureFormat } from "fragmentcolor";
const r = new Renderer();
// Empty storage texture.const tex = await r.createStorageTexture([64, 64], TextureFormat.Rgba);
// Pre-seeded with bytes.const pixels = Array(64 * 64 * 4).fill(0);const tex2 = await r.createStorageTexture([64, 64], TextureFormat.Rgba, pixels);
// One 32-bit counter per texel, for texture atomics.const counts = await r.createStorageTexture([4, 4], TextureFormat.R32Uint);const shader = new Shader(`
@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.set("counts", counts);from fragmentcolor import Renderer, Shader, TextureFormat
r = Renderer()# Empty storage texture -- positional args: (size, format).tex = r.create_storage_texture([64, 64], TextureFormat.Rgba)
# Pre-seeded with bytes -- same method, optional data kwarg.pixels = [0] * (64 * 64 * 4)tex2 = r.create_storage_texture([64, 64], TextureFormat.Rgba, data=pixels)
# One 32-bit counter per texel, for texture atomics.counts = r.create_storage_texture([4, 4], TextureFormat.R32Uint)shader = Shader("""@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.set("counts", counts)import FragmentColor
let r = Renderer()
// Empty storage texture.let tex = try await r.createStorageTexture([64, 64], TextureFormat.rgba)
// Pre-seeded with bytes.let pixels = Array(repeating: 0, count: 64 * 64 * 4)let tex2 = try await r.createStorageTexture([64, 64], TextureFormat.rgba, pixels)
// One 32-bit counter per texel, for texture atomics.let counts = try await r.createStorageTexture([4, 4], TextureFormat.r32Uint)let shader = try Shader("""@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);}
""")try shader.set("counts", counts)import org.fragmentcolor.*
val r = Renderer()
// Empty storage texture.val tex = r.createStorageTexture(listOf(64u, 64u), TextureFormat.RGBA)
// Pre-seeded with bytes.val pixels = ByteArray(64 * 64 * 4)val tex2 = r.createStorageTexture(listOf(64u, 64u), TextureFormat.RGBA, pixels)
// One 32-bit counter per texel, for texture atomics.val counts = r.createStorageTexture(listOf(4u, 4u), TextureFormat.R32_UINT)val shader = Shader("""@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.set("counts", counts)Renderer::create_target(target: Canvas | Window)
Section titled “Renderer::create_target(target: Canvas | Window)”Creates a Target attached to a platform-specific canvas or window.
In Rust, we officially support Winit. Check the examples folder for details.
A window with no area yet gets one pixel on that side, and resize gives it the real size later. A side past the device limit is an error, the one resize returns: TextureError::InvalidInput inside InitializationError::TextureError in Rust, a thrown Error named InvalidInputError in JavaScript, InvalidInputError (a FragmentColorError) in Python, FragmentColorError in Swift and FragmentColorException in Kotlin.
Example
Section titled “Example”use fragmentcolor::{Renderer, Target};
let renderer = Renderer::new();
// The canvas comes from your platform's windowing system.let target = renderer.create_target(canvas).await?;import { Renderer } from "fragmentcolor";1 collapsed line
const canvas = document.createElement("canvas");
const renderer = new Renderer();
// The canvas comes from your platform's windowing system.const target = await renderer.createTarget(canvas);from fragmentcolor import Renderer2 collapsed lines
from rendercanvas.auto import RenderCanvascanvas = RenderCanvas(size=(800, 600))
renderer = Renderer()
# The canvas comes from your platform's windowing system.target = renderer.create_target(canvas)import FragmentColor2 collapsed lines
import QuartzCorelet canvas = CAMetalLayer()
let renderer = Renderer()
// The canvas comes from your platform's windowing system.let target = try renderer.createTarget(canvas)import org.fragmentcolor.*2 collapsed lines
val surfaceTexture = android.graphics.SurfaceTexture(0)val canvas = android.view.Surface(surfaceTexture)
val renderer = Renderer()
// The canvas comes from your platform's windowing system.val target = renderer.createTarget(canvas)1 collapsed line
surfaceTexture.release()Renderer::create_texture
Section titled “Renderer::create_texture”Create a Texture from bytes, a file path, a URL, a KTX2 container, or a pre-built Mipmap.
When you pass a size, the bytes are treated as raw pixels in the chosen format. Without a size, the bytes (or the file/URL contents) are decoded as PNG, JPEG, BMP, HDR, etc. A size applies to bytes only: a path, a URL, a KTX2 file and a Mipmap carry their own, so a size with one is an InvalidInput error, raised before any file read or fetch. An empty byte list, path or URL holds nothing to read, and is an InvalidInput error too.
A size with a side of zero, or one past the device’s limits, is an error that reaches no GPU call, and so is an image larger than the device takes, which is checked from its header before the pixels decode: TextureError::InvalidInput inside RendererError::TextureError in Rust, a thrown Error named InvalidInputError in JavaScript, InvalidInputError (a FragmentColorError) in Python, FragmentColorError in Swift and FragmentColorException in Kotlin.
Decode and mipmap generation run on a background worker on native platforms. On the web they run inline on the caller’s thread; move heavy decode into a Web Worker if you need parallelism.
Per-language shapes
Section titled “Per-language shapes”- Rust:
create_texture(input).inputaccepts bare bytes,(bytes, [w, h]),(bytes, format),(bytes, options), a path or a URL string, alone or as(path, format)or(path, options), aTexture, aMipmap, alone or as(chain, options), or a KTX2 input. A string that starts withhttp://orhttps://is a URL; any other string is a path. - JS:
await renderer.createTexture(input, options?).inputisUint8Array/ArrayBuffer/ URL string / CSS selector /HTMLImageElement/HTMLCanvasElement/OffscreenCanvas/ImageData/ aTexture/ aMipmap.optionsis{ size?, format?, mipmaps?, sampler?, usage? }; whensizeis set,inputis read as raw pixel bytes.ImageDataand canvases bring their own size and RGBA pixels, so their options may repeat that size and pick an 8-bit RGBA or BGRA format, and anything else throws. The options object takes the size undersize, and awidthorheightbeside another option throws. ATexturekeeps the options it was created with, so options beside one throw anInvalidInputError. - Python:
renderer.create_texture(input, size=None, format=None, mipmaps=None, sampler=None, usage=None).inputisbytes/bytearray/memoryview/ a list or tuple of ints / a path or URLstr/os.PathLike/ uint8 numpyndarray[H, W, C]/Texture/Mipmap. Numpy arrays fill insizefor you, and asizethat differs from the array’s raisesInvalidInputError, as does any keyword beside aTexture, which keeps the options it was created with. An array is raw bytes in the named format: one whose channels match the format’s bytes per pixel uploads as it is, such as an(H, W)array asR8Unormor a 4-channel array asBgra8Unormwith no swap, and one with 1 or 3 channels gains an opaque alpha for an 8-bit RGBA or BGRA format. Any other shape raisesInvalidInputError. - Swift / Kotlin:
try await renderer.createTexture(bytes),createTexture(bytes, format),createTexture(bytes, [w, h]),createTexture(bytes, size),createTexture(bytes, options),createTexture(path),createTexture(path, format),createTexture(path, options),createTexture(chain)orcreateTexture(chain, options). Bytes areData,[UInt8]or[Int]in Swift andByteArrayorList<Int>in Kotlin, in every bytes form, and anIntoutside 0 to 255 throws. The bytes forms withoutoptionsalso take an optionalusage.
How the discriminator works
Section titled “How the discriminator works”| Form | Treatment |
|---|---|
bytes (no size) |
Encoded image; decoded internally (PNG, JPEG, BMP, HDR, etc.). |
(bytes, size) / options with size set |
Raw pixel bytes; exactly bpp(format) * width * height * depth long, no decode, and any other length is an InvalidInput error. The default Rgba format uploads them as linear Rgba8Unorm. |
(bytes, format) / options with format set |
Encoded image reinterpreted as format (e.g. Rgba8Unorm for normal-map data, R16Unorm for 16-bit grayscale, Rgba32Float for full float precision). |
path / URL |
File or HTTP fetch, then decoded. A size with it is an error. |
Mipmap |
Pre-built CPU mip chain; GPU-only upload, in the format it was built in. Build via Mipmap::build on a worker thread. A format option may pick that format’s sRGB twin, which reads the same bytes, and any other format is an InvalidInput error that names create_texture. |
Texture |
Returned as it is. It keeps the options it was created with, so any option beside it is an InvalidInput error that names the call. |
Ktx2Bytes / Ktx2Path / Ktx2Url |
KTX2 container (BC / ETC2 / ASTC / uncompressed), found by its identifier in plain bytes or a plain path too; the file’s declared format and pre-baked mip chain win. A format option may pick that format’s sRGB twin, which reads the same bytes, and any other format is an InvalidInput error that names create_texture. |
A full mipmap chain is generated by default (options.mipmaps = true), for source images and for raw bytes in a color format, Rgba16Float or Rgba32Float. Set to false to skip the CPU work for textures that won’t be sampled at distance, and for any texture you update in parts with write_region, which refuses a partial write into a chain. Raw bytes upload as given at level 0, and the levels below it are resampled from them. An integer format or R32Float takes its raw bytes as one level, with no chain.
An HDR image decodes into Rgba16Float. A value past the half float range saturates at 65504, or -65504, and never becomes infinity, the way Three.js converts it. An explicit Rgba32Float keeps the full range, and a linear sampler filters it where the device has FLOAT32_FILTERABLE. Every mip level of a float texture averages the f32 values of the level above it with a box filter, so values below 0 and above 1 keep their size at every level. For Rgba16Float those are the values before the level is stored as half floats, and only storing a level saturates it.
A decoded image, an ImageData or a canvas holds RGBA by definition, so it uploads into Bgra8Unorm blue first and its colors sample right. Every path that takes an ImageData or a canvas does this: createTexture, the Material texture setters, Texture.write and writeRegion, Mipmap.build and the createStorageTexture seed. Raw bytes, a NumPy array among them, are texels in the named format and upload as given, never swapped. A decoded image fills the 8-bit and 16-bit color formats and Rgba16Float or Rgba32Float. Any other format, such as Rgba32Uint, R32Uint, R32Float or Depth32Float, is an InvalidInput error: pass raw bytes with a size for an integer or R32Float texture, and draw into a depth texture.
options.usage adds TextureUsage flags to the TEXTURE_BINDING | COPY_DST every texture made from data has, such as COPY_SRC to read it back. A bit outside the five TextureUsage flags is an InvalidInput error.
Example
Section titled “Example”use fragmentcolor::Renderer;let renderer = Renderer::new();let tex = renderer.create_texture(&image).await?;import { Renderer } from "fragmentcolor";1 collapsed line
const image = new Uint8Array(await (await fetch("/healthcheck/public/favicon.png")).arrayBuffer());const renderer = new Renderer();const tex = await renderer.createTexture(image);from fragmentcolor import Renderer1 collapsed line
image = open("examples/assets/logo.png", "rb").read()renderer = Renderer()tex = renderer.create_texture(image)import FragmentColor2 collapsed lines
import Foundationlet image = try Data(contentsOf: URL(fileURLWithPath: "examples/assets/logo.png"))let renderer = Renderer()let tex = try await renderer.createTexture(image)import org.fragmentcolor.*1 collapsed line
val image = java.io.File("examples/assets/logo.png").readBytes()val renderer = Renderer()val tex = renderer.createTexture(image)Renderer::create_texture_target(size: [u32; 2])
Section titled “Renderer::create_texture_target(size: [u32; 2])”Render to an offscreen texture without a Window or Canvas.
This is useful for tests, server-side rendering, or running examples in CI.
A width or height of zero, a side past the device limit, or a depth other than 1 is an error, the one resize returns: TextureError::InvalidInput inside InitializationError::TextureError in Rust, a thrown Error named InvalidInputError in JavaScript, InvalidInputError (a FragmentColorError) in Python, FragmentColorError in Swift and FragmentColorException in Kotlin.
Example
Section titled “Example”use fragmentcolor::{Renderer, Shader, Target};let renderer = Renderer::new();
// Create an offscreen texture target with a size of 64x64 pixels.let target = renderer.create_texture_target([64, 64]).await?;
renderer.render(&Shader::default(), &target)?;
// get the rendered imagelet image = target.get_image().await?;import { Renderer, Shader } from "fragmentcolor";const renderer = new Renderer();
// Create an offscreen texture target with a size of 64x64 pixels.const target = await renderer.createTextureTarget([64, 64]);
renderer.render(Shader.default(), target);
// get the rendered imageconst image = await target.getImage();from fragmentcolor import Renderer, Shaderrenderer = Renderer()
# Create an offscreen texture target with a size of 64x64 pixels.target = renderer.create_texture_target([64, 64])
renderer.render(Shader.default(), target)
# get the rendered imageimage = target.get_image()import FragmentColorlet renderer = Renderer()
// Create an offscreen texture target with a size of 64x64 pixels.let target = try await renderer.createTextureTarget([64, 64])
try renderer.render(Shader.default(), target)
// get the rendered imagelet image = try await target.getImage()import org.fragmentcolor.*val renderer = Renderer()
// Create an offscreen texture target with a size of 64x64 pixels.val target = renderer.createTextureTarget(listOf(64u, 64u))
renderer.render(Shader.default(), target)
// get the rendered imageval image = target.getImage()Renderer::load
Section titled “Renderer::load”Uploads into this Renderer every Material map of a renderable that it
lacks, or holds from an older set. Material’s texture setters
(base_color_texture, metallic_roughness_texture, …) take an
already-uploaded Texture
or a source: bytes, a path, a URL or a Mipmap. The Material keeps a source
as a map with one texture id. load walks every Shader the renderable visits
and decodes each map this Renderer needs into a copy of its own, under that id.
An upload that fails keeps no copy, and the others still upload: a good
normal map draws even when the base color path is missing. load returns
the first failure, as does every later load and every native render,
until the source is fixed or replaced. The latest setter call for a map
wins, even one made while load is uploading the older source. That older
upload stands in, so this Renderer always holds a copy, until the next
load uploads the latest. A slot the shader doesn’t declare never becomes a map, since
the setter logs a warning and leaves the Material as it was.
Each Renderer holds copies of its own. One Material draws with every
Renderer that loads it, and a copy goes when its Renderer or the
Material drops. A map set again draws its old copy until this Renderer
loads the new one.
On native targets, Renderer::render
runs load first, which makes an explicit load optional there. Reach for
it when you want to pay the decode and upload cost outside the render loop,
for example in a loading screen that prepares the scene before the first
frame goes out.
On the web, render can’t wait for an upload and uploads nothing. Await
load in each Renderer before its first render. Until then, each map
draws its 1×1 PBR default wherever that default fits the slot, in the
built-in shader or a custom one. A slot it doesn’t fit, such as an integer
texture, and a map in a compute shader fail the render with a
BindingError that asks for load.
On native, a map that another thread sets while render runs, on a slot
this Renderer holds no copy for, draws the same way for that one frame,
and the next render uploads it.
In JavaScript, load first waits for the frames rendered before it to
report their GPU errors, and throws the first one, as
Renderer::render describes.
Example
Section titled “Example”use fragmentcolor::{Material, Mesh, Model, Renderer, Scene, Vertex};
let renderer = Renderer::new();let target = renderer.create_texture_target([64, 64]).await?;
let mesh = Mesh::new();mesh.add_vertices([ Vertex::pbr([0.0, 0.5, 0.0]).set(Vertex::UV0, [0.5, 1.0]), Vertex::pbr([-0.5, -0.5, 0.0]).set(Vertex::UV0, [0.0, 0.0]), Vertex::pbr([0.5, -0.5, 0.0]).set(Vertex::UV0, [1.0, 0.0]),]);
// The material keeps the encoded image as a map.let material = Material::pbr().base_color_texture(&image)?;let model = Model::new(mesh, material);let scene = Scene::new();scene.add(&model)?;
// Decode and upload it now, so the first render only draws.renderer.load(&scene).await?;renderer.render(&scene, &target)?;
// A second Renderer draws the same map from a copy of its own.let other = Renderer::new();let frame = other.create_texture_target([64, 64]).await?;other.load(&scene).await?;other.render(&scene, &frame)?;import { Material, Mesh, Model, Renderer, Scene, Vertex } from "fragmentcolor";1 collapsed line
const image = new Uint8Array(await (await fetch("/healthcheck/public/favicon.png")).arrayBuffer());
const renderer = new Renderer();const target = await renderer.createTextureTarget([64, 64]);
const mesh = new Mesh();mesh.addVertices([ Vertex.pbr([0.0, 0.5, 0.0]).set(Vertex.UV0, [0.5, 1.0]), Vertex.pbr([-0.5, -0.5, 0.0]).set(Vertex.UV0, [0.0, 0.0]), Vertex.pbr([0.5, -0.5, 0.0]).set(Vertex.UV0, [1.0, 0.0]), ]);
// The material keeps the encoded image as a map.const material = Material.pbr().baseColorTexture(image);const model = new Model(mesh, material);const scene = new Scene();scene.add(model);
// Decode and upload it now, so the first render only draws.await renderer.load(scene);renderer.render(scene, target);
// A second Renderer draws the same map from a copy of its own.const other = new Renderer();const frame = await other.createTextureTarget([64, 64]);await other.load(scene);other.render(scene, frame);from fragmentcolor import Material, Mesh, Model, Renderer, Scene, Vertex1 collapsed line
image = open("examples/assets/logo.png", "rb").read()
renderer = Renderer()target = renderer.create_texture_target([64, 64])
mesh = Mesh()mesh.add_vertices([ Vertex.pbr([0.0, 0.5, 0.0]).set(Vertex.UV0, [0.5, 1.0]), Vertex.pbr([-0.5, -0.5, 0.0]).set(Vertex.UV0, [0.0, 0.0]), Vertex.pbr([0.5, -0.5, 0.0]).set(Vertex.UV0, [1.0, 0.0]),])
# The material keeps the encoded image as a map.material = Material.pbr().base_color_texture(image)model = Model(mesh, material)scene = Scene()scene.add(model)
# Decode and upload it now, so the first render only draws.renderer.load(scene)renderer.render(scene, target)
# A second Renderer draws the same map from a copy of its own.other = Renderer()frame = other.create_texture_target([64, 64])other.load(scene)other.render(scene, frame)import FragmentColor2 collapsed lines
import Foundationlet image = try Data(contentsOf: URL(fileURLWithPath: "examples/assets/logo.png"))
let renderer = Renderer()let target = try await renderer.createTextureTarget([64, 64])
let mesh = Mesh()mesh.addVertices([ try Vertex.pbr([0.0, 0.5, 0.0]).set(Vertex.UV0, [0.5, 1.0]), try Vertex.pbr([-0.5, -0.5, 0.0]).set(Vertex.UV0, [0.0, 0.0]), try Vertex.pbr([0.5, -0.5, 0.0]).set(Vertex.UV0, [1.0, 0.0]),])
// The material keeps the encoded image as a map.let material = try Material.pbr().baseColorTexture(image)let model = Model(mesh, material)let scene = Scene()try scene.add(model)
// Decode and upload it now, so the first render only draws.try await renderer.load(scene)try renderer.render(scene, target)
// A second Renderer draws the same map from a copy of its own.let other = Renderer()let frame = try await other.createTextureTarget([64, 64])try await other.load(scene)try other.render(scene, frame)import org.fragmentcolor.*1 collapsed line
val image = java.io.File("examples/assets/logo.png").readBytes()
val renderer = Renderer()val target = renderer.createTextureTarget(listOf(64u, 64u))
val mesh = Mesh()mesh.addVertices(listOf(Vertex.pbr(listOf(0.0f, 0.5f, 0.0f)).set(Vertex.UV0, listOf(0.5f, 1.0f)), Vertex.pbr(listOf(-0.5f, -0.5f, 0.0f)).set(Vertex.UV0, listOf(0.0f, 0.0f)), Vertex.pbr(listOf(0.5f, -0.5f, 0.0f)).set(Vertex.UV0, listOf(1.0f, 0.0f))))
// The material keeps the encoded image as a map.val material = Material.pbr().baseColorTexture(image)val model = Model(mesh, material)val scene = Scene()scene.add(model)
// Decode and upload it now, so the first render only draws.renderer.load(scene)renderer.render(scene, target)
// A second Renderer draws the same map from a copy of its own.val other = Renderer()val frame = other.createTextureTarget(listOf(64u, 64u))other.load(scene)other.render(scene, frame)Renderer::new()
Section titled “Renderer::new()”Create a new Renderer.
The renderer’s GPU adapter and device are initialized lazily on the first
target you create, so the same Renderer works whether you end up
rendering offscreen or attaching it to a window. By the time render()
is called the GPU resources are already in place. render requires a
Target, and the only way to
build one is through this renderer:
renderer.create_target(Window)for an on-screen target, orrenderer.create_texture_target([w, h])for offscreen rendering.
Example
Section titled “Example”use fragmentcolor::{Renderer, Target};
let renderer = Renderer::new();let texture_target = renderer.create_texture_target([16, 16]).await?;import { Renderer } from "fragmentcolor";
const renderer = new Renderer();const texture_target = await renderer.createTextureTarget([16, 16]);from fragmentcolor import Renderer
renderer = Renderer()texture_target = renderer.create_texture_target([16, 16])import FragmentColor
let renderer = Renderer()let texture_target = try await renderer.createTextureTarget([16, 16])import org.fragmentcolor.*
val renderer = Renderer()val texture_target = renderer.createTextureTarget(listOf(16u, 16u))Renderer::read_storage
Section titled “Renderer::read_storage”Round-trip the GPU-side bytes of a Shader’s
storage binding back to the CPU. Submits any pending uploads, copies the
storage buffer into a pooled readback staging buffer, maps it, and returns
the bytes.
This is the only way to observe what a compute pass wrote into a storage
binding. Shader::get returns
what was last set on the CPU side, so GPU writes don’t show up through it.
A Shader::set on any field
of the root uploads the whole root from that CPU copy at the next render that
binds it, which replaces what a compute pass wrote there.
read_storage is async because the underlying map_async requires an
awaited callback. It returns a Promise in JS, is async in Swift and
suspend in Kotlin, and blocks until the bytes arrive in Python. On native
the implementation drives the device forward (device.poll(Wait)) before
awaiting, so callers don’t have to spin their own poll loop. On Web the
browser schedules the callback; the helper just awaits.
The result holds exactly as many bytes as the binding spans, also for a
root of f16 values, which can span 2 or 6 bytes and reads back as 2-byte
IEEE halves.
Returns RendererError::StorageBindingNotFound when the shader does not
declare a storage binding called binding, or when no render pass has yet
materialized the GPU-side buffer (storage buffers are allocated lazily on
first bind).
In JavaScript, readStorage waits for the frames rendered before it to
report their GPU errors and throws the first one, as
Renderer::render
describes. An error throws only once, so when another call, such as the next
render, has already thrown it, readStorage returns the bytes the failed
frame left behind.
Example
Section titled “Example”use fragmentcolor::{Pass, Renderer, Shader};
let renderer = Renderer::new();let target = renderer.create_texture_target([16, 16]).await?;
let compute = Shader::new( r#" struct Out { values: array<f32, 4> }; @group(0) @binding(0) var<storage, read_write> out: Out; @compute @workgroup_size(1) fn main() { out.values[0] = 1.0; out.values[1] = 2.0; out.values[2] = 3.0; out.values[3] = 4.0; } "#,)?;
let pass = Pass::compute("seed");pass.set_compute_dispatch(1, 1, 1);pass.add_shader(&compute)?;renderer.render(&pass, &target)?;
let bytes = renderer.read_storage(&compute, "out").await?;import { Pass, Renderer, Shader } from "fragmentcolor";
const renderer = new Renderer();const target = await renderer.createTextureTarget([16, 16]);
const compute = new Shader(`
struct Out { values: array<f32, 4> }; @group(0) @binding(0) var<storage, read_write> out: Out; @compute @workgroup_size(1) fn main() { out.values[0] = 1.0; out.values[1] = 2.0; out.values[2] = 3.0; out.values[3] = 4.0; }
`);
const pass = Pass.compute("seed");pass.setComputeDispatch(1, 1, 1);pass.addShader(compute);renderer.render(pass, target);
const bytes = await renderer.readStorage(compute, "out");from fragmentcolor import Pass, Renderer, Shader
renderer = Renderer()target = renderer.create_texture_target([16, 16])
compute = Shader(""" struct Out { values: array<f32, 4> }; @group(0) @binding(0) var<storage, read_write> out: Out; @compute @workgroup_size(1) fn main() { out.values[0] = 1.0; out.values[1] = 2.0; out.values[2] = 3.0; out.values[3] = 4.0; }
""")
rpass = Pass.compute("seed")rpass.set_compute_dispatch(1, 1, 1)rpass.add_shader(compute)renderer.render(rpass, target)
bytes = renderer.read_storage(compute, "out")import FragmentColor
let renderer = Renderer()let target = try await renderer.createTextureTarget([16, 16])
let compute = try Shader(""" struct Out { values: array<f32, 4> }; @group(0) @binding(0) var<storage, read_write> out: Out; @compute @workgroup_size(1) fn main() { out.values[0] = 1.0; out.values[1] = 2.0; out.values[2] = 3.0; out.values[3] = 4.0; }
""")
let pass = Pass.compute("seed")pass.setComputeDispatch(1, 1, 1)try pass.addShader(compute)try renderer.render(pass, target)
let bytes = try await renderer.readStorage(compute, "out")import org.fragmentcolor.*
val renderer = Renderer()val target = renderer.createTextureTarget(listOf(16u, 16u))
val compute = Shader(""" struct Out { values: array<f32, 4> }; @group(0) @binding(0) var<storage, read_write> out: Out; @compute @workgroup_size(1) fn main() { out.values[0] = 1.0; out.values[1] = 2.0; out.values[2] = 3.0; out.values[3] = 4.0; }
""")
val pass = Pass.compute("seed")pass.setComputeDispatch(1u, 1u, 1u)pass.addShader(compute)renderer.render(pass, target)
val bytes = renderer.readStorage(compute, "out")Renderer::read_texture(texture_id)
Section titled “Renderer::read_texture(texture_id)”Read back the mip-0 contents of a registered texture as tightly-packed bytes in the texture’s native format.
- Works on native and on the web; the call awaits the GPU readback mapping.
- Equivalent to calling [
Texture::get_image] on the texture handle. Use this entry point when you only kept theTextureIdaround. - The texture must have
COPY_SRCusage. Creation helpers likecreate_storage_textureenable it by default. - GLES and WebGL2 can’t copy a depth texture to a buffer, so reading one back there returns
TextureError::Readback. So does a texture whose readback needs a buffer past the device’s largest,max_buffer_size. - A block-compressed texture, such as one loaded from a BC7 or ASTC KTX2 file, has no size per pixel, so reading it back is an
InvalidInputerror. - In JavaScript,
readTexturefirst waits for the frames rendered before it to report their GPU errors and throws the first one, asRenderer::renderdescribes.
Example
Section titled “Example”use fragmentcolor::{Renderer, TextureFormat};let renderer = Renderer::new();let texture = renderer.create_storage_texture(([64, 64], TextureFormat::Rgba)).await?;texture.write(&vec![0; 64 * 64 * 4])?;
let bytes = renderer.read_texture(texture.id()).await?;import { Renderer, TextureFormat } from "fragmentcolor";const renderer = new Renderer();const texture = await renderer.createStorageTexture([64, 64], TextureFormat.Rgba);texture.write(new Uint8Array(64 * 64 * 4));
const bytes = await renderer.readTexture(texture.id());from fragmentcolor import Renderer, TextureFormatrenderer = Renderer()texture = renderer.create_storage_texture([64, 64], TextureFormat.Rgba)texture.write([0] * (64 * 64 * 4))
bytes = renderer.read_texture(texture.id())import FragmentColorlet renderer = Renderer()let texture = try await renderer.createStorageTexture([64, 64], TextureFormat.rgba)try texture.write(Array(repeating: 0, count: 64 * 64 * 4))
let bytes = try await renderer.readTexture(texture.id())import org.fragmentcolor.*val renderer = Renderer()val texture = renderer.createStorageTexture(listOf(64u, 64u), TextureFormat.RGBA)texture.write(ByteArray(64 * 64 * 4))
val bytes = renderer.readTexture(texture.id())Renderer::render(renderable, target)
Section titled “Renderer::render(renderable, target)”Renders the given object to the given Target.
renderable can be a Shader, a Pass, a Mesh, a Scene, or any iterable of Pass (Vec<Pass>, &[Pass], &[&Pass]). Passes in an iterable render in order, each after the passes it requires. A render runs each pass once, at the first place a list, a Scene or a require puts it, so with b.require(&a), render(&vec![a, b]), render(&vec![b]) and render(&b) all run a, then b.
A window that is hidden or minimized has no frame to draw on. render then returns RendererError::SurfaceError(SurfaceError::Occluded), which Python raises as OccludedSurfaceError, a FragmentColorError, Swift throws as FragmentColorError.Occluded and Kotlin as FragmentColorException.Occluded. Skip that frame and draw the next one.
A shader that reads @location vertex inputs needs a mesh. Without one, render returns ShaderError::InvalidKey naming the input. The inputs are the @location arguments of the vertex entry point and the @location members of its struct arguments, and each one reads the mesh attribute of its own name. The checks on the shader and its textures come first, so an input past max_vertex_attributes returns RendererError::LimitError instead.
Each mesh a shader draws is checked against the device, and a mesh past one of its limits returns RendererError::LimitError, as a shader does: a vertex or instance stride past max_vertex_buffer_array_stride, and mesh data that needs a buffer past max_buffer_size. Its item names the stride or the buffer. WebGL2 takes strides up to 255 bytes. A mesh draws with every Renderer that renders it, each from buffers of its own. These checks, and the mesh’s own, apply only to the meshes the frame draws: the mesh of a hidden Model, or of a Model in another pass, isn’t checked.
render(mesh) draws the mesh with a shader of its own, built from its first vertex. That shader reads position, and color when the first vertex sets it as four numbers. It checks the mesh again on every render that draws it after the mesh changed, a render of a pass that requires the mesh included, and adds nothing that vertices must hold for the mesh’s other shaders. The types it gives plain numbers stay for as long as the mesh lives, as any shader’s do: once it reads color as four floats, a shader that reads color as vec4<u32> fails to attach with ShaderError::AttributeConflict. A mesh it refuses returns the error an attach would, such as ShaderError::AttributeMismatch for a vertex without color, where a shader the mesh is attached to returns MeshError::InvalidVertex. It draws only what its check saw, and a mesh that another thread keeps changing through each of its tries returns MeshError::Busy.
Before it takes a frame, render checks each shader against the device and each texture uniform against its slot, so every language returns these errors from the call that caused them, the web included. A group, binding, binding count, buffer size or workgroup past the device’s limits, or a vertex input at a location past max_vertex_attributes, returns RendererError::LimitError, a feature the device lacks RendererError::FeatureError, a texture uniform that was never set or whose texture its slot can’t take RendererError::BindingError, and a render shader without its vertex or fragment entry point RendererError::EntryError, each with its fields. An unset PBR map slot binds its 1x1 default instead, when the slot takes a 2D float texture. A texture unregister_texture removed, or one from another Renderer, returns RendererError::TextureNotFoundError, in a PBR map slot too. The Shader page lists the checks and each language’s form of these errors.
A Renderer draws only into the targets it created. A target from another Renderer returns RendererError::ForeignTarget, unless every pass is a compute pass, which draws into no target, and a pass target or texture uniform from another Renderer returns RendererError::TextureNotFoundError. A Material map set from bytes, a path, a URL or a Mipmap belongs to no Renderer: each one draws it from a copy of its own. These checks come before render uploads a map or opens a device, so a refused render changes nothing. A Renderer that has opened no device yet returns RendererError::NoContext for a target without an owner. Each pass is checked against what it draws into before it records: a depth target of the color attachment’s size and sample count, shader outputs and blending the target’s format takes, a viewport and a compute dispatch the device takes, and textures that one pass doesn’t both write and read. A render pass can’t bind a texture it draws into, and no pass can read a texture one of its bindings writes, so a compute dispatch that samples a texture and stores into it returns PassError::TextureConflict too.
render also returns what the GPU rejects. When a pipeline fails to build or a frame’s commands fail, it returns a DeviceError, RendererError::DeviceError in Rust. Its kind tells validation errors, internal errors such as a shader the backend compiler refuses, and running out of memory apart, and its label names the step that failed: the render pipeline, the compute pipeline, the light binning pipeline, the frame, or a bind group or texture view inside the frame. When one error causes another, render returns the first. In Rust, Python, Swift and Kotlin, a pipeline that failed is never kept, and the next frame builds it again and returns the same error.
A frame that fails is still presented. wgpu clears an image that no valid command drew into, so after a GPU error the window usually shows a cleared frame. On Apple GPUs the renderer submits the commands recorded so far before each compute pass that follows another compute pass. When a pass after that point fails, what the earlier passes drew stays on the image. On Apple GPUs, after a compute pass whose shader binds a storage texture with atomic access, render also submits the commands recorded so far and waits for the GPU to finish them before it records the next pass, so a readback, a later pass and the next render all see the pass’s counts. A shader without its mesh, an instance count past the mesh’s instances, a mesh the device’s limits or its own checks refuse, a shader or texture the device checks refuse, a target from another Renderer, a pass target that is missing, a viewport past the device’s 2D limit, and a pass whose own target or compute dispatch fails its checks fail before render takes a frame, and the window keeps its last image.
JavaScript gets the GPU’s errors late, because WebGPU reports them after render has returned. Each error logs a console.error when it lands, and the next render still throws the first one, as an Error named DeviceError, with kind, label and detail properties, before doing any work. load, readTexture, readStorage, and getImage on a Texture or TextureTarget wait for the frames before them to report, so they throw a frame’s error even when called right after it. A call that waits throws only the error of a frame rendered before it began: the error of a frame rendered while it waits, even one rendered in the same task right after the call, stays for the next call. Only the first error to land throws, and only once; the ones that land after it, before a call takes it, only log. The label names the render pipeline, the compute pipeline, the light binning pipeline or the frame. A pipeline that failed stays in the cache until its error lands, and a frame that draws with it before then reports a frame error. Once the error lands, the pipeline leaves the cache. In a loop that renders each frame, the next render throws the error before doing any work, and the one after it builds the pipeline again and reports the same error.
Example
Section titled “Example”use fragmentcolor::{Renderer, Shader};
let renderer = Renderer::new();let target = renderer.create_texture_target([10, 10]).await?;let shader = Shader::default();
renderer.render(&shader, &target)?;import { Renderer, Shader } from "fragmentcolor";
const renderer = new Renderer();const target = await renderer.createTextureTarget([10, 10]);const shader = Shader.default();
renderer.render(shader, target);from fragmentcolor import Renderer, Shader
renderer = Renderer()target = renderer.create_texture_target([10, 10])shader = Shader.default()
renderer.render(shader, target)import FragmentColor
let renderer = Renderer()let target = try await renderer.createTextureTarget([10, 10])let shader = Shader.default()
try renderer.render(shader, target)import org.fragmentcolor.*
val renderer = Renderer()val target = renderer.createTextureTarget(listOf(10u, 10u))val shader = Shader.default()
renderer.render(shader, target)Renderer::set_log_level(level: LogLevel)
Section titled “Renderer::set_log_level(level: LogLevel)”Sets how much FragmentColor logs, for the whole process. The LogLevel values run from quiet to verbose: Off, Error, Warn, Info, Debug and Trace.
The web build prints to the browser console and starts at Info. Raise it to Debug to see naga’s notes on each shader. On other platforms FragmentColor logs through Rust’s log crate, and the level limits what an installed logger prints.
Example
Section titled “Example”use fragmentcolor::{LogLevel, Renderer, Shader};
// Log naga's notes while this shader builds, then go back to the usual level.Renderer::set_log_level(LogLevel::Debug);let shader = Shader::default();Renderer::set_log_level(LogLevel::Info);import { LogLevel, Renderer, Shader } from "fragmentcolor";
// Log naga's notes while this shader builds, then go back to the usual level.Renderer.setLogLevel(LogLevel.Debug);const shader = Shader.default();Renderer.setLogLevel(LogLevel.Info);from fragmentcolor import LogLevel, Renderer, Shader
# Log naga's notes while this shader builds, then go back to the usual level.Renderer.set_log_level(LogLevel.Debug)shader = Shader.default()Renderer.set_log_level(LogLevel.Info)import FragmentColor
// Log naga's notes while this shader builds, then go back to the usual level.Renderer.setLogLevel(LogLevel.debug)let shader = Shader.default()Renderer.setLogLevel(LogLevel.info)import org.fragmentcolor.*
// Log naga's notes while this shader builds, then go back to the usual level.Renderer.setLogLevel(LogLevel.DEBUG)val shader = Shader.default()Renderer.setLogLevel(LogLevel.INFO)Renderer::unregister_texture(id)
Section titled “Renderer::unregister_texture(id)”Remove a texture from the renderer’s registry now.
The renderer releases a texture on its own when the last thing holding it
drops: every Texture handle, the TextureTarget that owns it, and each
shader uniform or pass target that binds it. Call this to release one sooner,
for example when a video stream stops.
- After the call, the id names no texture, and shaders and passes that bind it can’t draw it. A pass that keeps it as its color or depth target makes
renderreturnTextureNotFoundError. - A
Texturehandle you still hold keeps its GPU memory until it drops. - The id of a
Materialmap removes thisRenderer’s copy of it. The Material keeps the map, and the nextload, or nativerender, uploads it again.
Example
Section titled “Example”use fragmentcolor::{Renderer, TextureFormat};let renderer = Renderer::new();let texture = renderer.create_storage_texture(([16, 16], TextureFormat::Rgba)).await?;let id = texture.id();
renderer.unregister_texture(id)?;import { Renderer, TextureFormat } from "fragmentcolor";
const renderer = new Renderer();const texture = await renderer.createStorageTexture([16, 16], TextureFormat.Rgba);const id = texture.id();
renderer.unregisterTexture(id);from fragmentcolor import Renderer, TextureFormat
renderer = Renderer()texture = renderer.create_storage_texture([16, 16], TextureFormat.Rgba)id = texture.id()
renderer.unregister_texture(id)import FragmentColorlet renderer = Renderer()let texture = try await renderer.createStorageTexture([16, 16], TextureFormat.rgba)let id = texture.id()
try renderer.unregisterTexture(id)import org.fragmentcolor.*val renderer = Renderer()val texture = renderer.createStorageTexture(listOf(16u, 16u), TextureFormat.RGBA)val id = texture.id()
renderer.unregisterTexture(id)