Skip to content

Texture

A GPU texture resource. Public API wrapper that holds a shareable reference to the internal TextureObject and a numeric handle used by uniforms.

  • Construct via Renderer::create_texture(input). input accepts bytes, (bytes, [w, h]), (bytes, format), a path, a URL, a KTX2 container, or a prepared chain.
  • Bind to a shader with shader.set("key", &texture).
  • The texture owns its sampler; tweak filtering and wrapping via set_sampler_options.
  • A texture a pass draws into, such as a depth texture, takes a new size with resize, and every clone of the handle follows.

Create a Texture and set it on a Shader

use fragmentcolor::{Renderer, Shader, Size};
let renderer = Renderer::new();
let shader = Shader::new(r#"
@group(0) @binding(0) var my_texture: texture_2d<f32>;
@group(0) @binding(1) var my_sampler: sampler;
@vertex fn vs_main(@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 vec4f(p[i], 0., 1.);
}
@fragment fn main() -> @location(0) vec4<f32> { return vec4f(1.,1.,1.,1.); }
"#)?;
// 1x1 white pixel. Passing a size tells create_texture to read the bytes
// as raw pixels; the default format, Rgba, uploads them as linear Rgba8Unorm.
let pixels: &[u8] = &[255, 255, 255, 255];
let texture = renderer.create_texture((pixels, [1, 1])).await?;
// Bind the texture to the uniform name declared in WGSL.
shader.set("my_texture", &texture)?;

Return the stable TextureId for this texture. The id is valid within the Renderer that created it and is the handle uniforms use to refer to the texture. It names the texture while something holds it: a Texture handle, the TextureTarget that owns it, or a shader uniform or pass target that binds it. An id on its own doesn’t keep the texture in the registry.

A Material map set from bytes, a path, a URL or a Mipmap keeps one id in every Renderer, where it names the copy that Renderer loaded. The copies go when the map does, so only the map’s own slot binds that id, and any other slot refuses it with ShaderError::ForeignMap. To share a map, pass the same source to each Material.

use fragmentcolor::{Renderer, TextureFormat};
let renderer = Renderer::new();
let texture = renderer.create_storage_texture(([64, 64], TextureFormat::Rgba)).await?;
let id = *texture.id();

Return the texture’s dimensions as a Size (width, height, and depth, which is absent for a 2D texture and holds the depth of a 3D texture or the layer count of an array). The size reflects the allocated GPU resource. It changes when resize gives the texture a new size, and every clone of the handle reads the new size.

use fragmentcolor::{Renderer, Size};
let renderer = Renderer::new();
let pixels: &[u8] = &[255,255,255,255];
let tex = renderer.create_texture((pixels, [1, 1])).await?;
let sz = tex.size();
let width = sz.width;
let height = sz.height;

Return the texture’s width / height as f32. Useful for setting up projection matrices or laying out a sprite without recomputing the ratio on every frame.

use fragmentcolor::{Renderer, Size};
let renderer = Renderer::new();
// 1x1 RGBA (white) raw pixel bytes
let pixels: &[u8] = &[255,255,255,255];
let tex = renderer.create_texture((pixels, [1, 1])).await?;
let a = tex.aspect();

Update the texture sampler options (filtering, wrapping, etc.).

smooth: true (the default) uses linear filtering for both magnification and minification, including trilinear interpolation between mip levels when the texture has a mipmap chain (created automatically for source images). smooth: false uses nearest-neighbor for everything.

The options apply from the next render to the sampler declared in the same bind group as the texture. When a group holds several textures, each sampler takes the options of the texture with the lowest @binding between the previous sampler and itself, or of the nearest texture if none sits in between. A single sampler after five textures uses the first texture’s options.

A plain sampler ignores compare. A sampler_comparison uses compare, or LessEqual when it is None.

use fragmentcolor::{Renderer, Size, SamplerOptions};
let renderer = Renderer::new();
// 1x1 RGBA (white) raw pixel bytes
let pixels: &[u8] = &[255,255,255,255];
let texture = renderer.create_texture((pixels, [1, 1])).await?;
let opts = SamplerOptions { repeat_x: true, repeat_y: true, smooth: true, compare: None };
texture.set_sampler_options(opts);

Efficiently upload raw pixel data into an existing texture, such as each frame of a video or any image that changes from frame to frame.

A texture from create_texture has a mip chain by default, and every whole write rebuilds that chain on the CPU, on the calling thread. For video and other per-frame updates, create the texture with mipmaps: false, so a write is a single GPU upload.

  • Whole texture updates: use Texture.write(&bytes).
  • Sub-rectangle updates or explicit data layout: use Texture.write_region(&bytes, region).
  • bytes holds tightly packed rows: each row is the texture width times the bytes per pixel, with no padding. Data sized exactly for rows padded to 256 bytes reads at that padded stride. For any other padding, pass the stride to Texture.write_region. Data of any other length is an InvalidInput error, so a frame of the wrong size never uploads cropped.
  • Any format with a fixed size per pixel works, from 1-byte R8Unorm to 16-byte Rgba32Float. A block-compressed texture, such as one loaded from a BC7 or ASTC KTX2 file, is an InvalidInput error.
  • The texture must have COPY_DST usage.
  • create_texture builds a mip chain by default, and a whole write rebuilds it, so the texture looks the same up close and far away.
  • A depth texture such as Depth32Float takes no uploaded pixels, so writing into one is an InvalidInput error. Draw into it instead.
use fragmentcolor::{Renderer, TextureFormat};
let renderer = Renderer::new();
let texture = renderer.create_storage_texture(([64, 64], TextureFormat::Rgba)).await?;
let frame_bytes = vec![0; 64 * 64 * 4];
texture.write(&frame_bytes)?;

Same as Texture::write, but writes into a sub-region of the texture and/or with explicit source data layout.

The region argument is required; use Texture::write to replace the whole texture. An array, tuple or TextureRegion with a width, height or depth of 0 is an InvalidInput error. It accepts anything convertible into a TextureRegion:

  • [w, h] / (w, h): a w by h rectangle at origin (0, 0, 0)
  • [x, y, w, h] / (x, y, w, h): 2D rectangle
  • [x, y, z, w, h, d]: 3D box (for layered or 3D textures)
  • A ScreenRegion: its pixel rectangle at z = 0, one layer deep. A region built field by field can be invalid: one whose max lies before its min, or with a width or height of 0, returns TextureError::Region with ScreenRegionError::Reversed or ScreenRegionError::Empty
  • A TextureRegion constructed explicitly with .with_stride(...) / .with_rows(...) for advanced data-layout control
  • See Texture::write for format and row layout details.
  • bytes_per_row (set via .with_stride(...)) defaults to the region width times the bytes per pixel, or to that row padded to 256 bytes when the data is exactly that size. Without it, data of any other length is an InvalidInput error. A larger value skips the padding at the end of each source row, and the data may then run past the region.
  • rows_per_image (set via .with_rows(...)) defaults to the region height.
  • A texture with a mip chain, which create_texture builds by default, takes whole writes only, since a partial one would leave the smaller levels stale. Any other region is an InvalidInput error, so create a texture you update in parts with mipmaps: false, or from a KTX2 file with one level.
use fragmentcolor::{Renderer, TextureFormat, TextureRegion};
let renderer = Renderer::new();
let texture = renderer.create_storage_texture(([64, 32], TextureFormat::Rgba)).await?;
let bytes = vec![0; 64 * 32 * 4];
// Simple sub-rectangle update.
texture.write_region(&bytes, [0, 0, 64, 32])?;
// Explicit data layout, for when the source rows are padded.
let region = TextureRegion::from([0, 0, 64, 32])
.with_stride(256)
.with_rows(32);
texture.write_region(&bytes, region)?;

Read back the mip-0 contents of this 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.
  • For multi-layer textures, layers come first in the byte layout (layer-major).
  • The texture must have COPY_SRC usage. Creation helpers like create_storage_texture enable 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 InvalidInput error.
  • Python returns the same bytes as a uint8 NumPy array shaped (height, width, bytes per pixel), with a leading layer axis for array textures. A float format reads as floats through a view: image.view(numpy.float16) for Rgba16Float, the format an HDR file decodes into, and image.view(numpy.float32) for Rgba32Float and R32Float. A 32-bit integer format reads through image.view(numpy.uint32) for R32Uint and Rgba32Uint, and image.view(numpy.int32) for R32Sint and Rgba32Sint.
  • In JavaScript, getImage first waits for the frames rendered before it to report their GPU errors and throws the first one, as Renderer::render describes.
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 = texture.get_image().await?;

Gives the texture a new size, with the same format, usage and sample count. Every clone of the handle follows, and so do the passes and shaders that hold it, so a depth texture or an offscreen image can follow a window without being created again. The pixels start blank at the new size. Asking for the current size keeps the texture as it is.

Only a texture made to be drawn into resizes: one from create_depth_texture, the texture() of a TextureTarget, or a texture made with RENDER_ATTACHMENT in its usage by create_storage_texture or create_texture. A resize keeps the mip chain create_texture builds by default, and a pass draws only into a texture of one level, so create one for set_target with mipmaps false. A texture made from an image loses that image when it resizes. Resizing a target’s texture() resizes the target. Any other texture returns TextureError::FixedSize, and a side of zero, or one past the device limit, returns TextureError::InvalidInput. Both keep the old size.

use fragmentcolor::{Pass, Renderer};
let renderer = Renderer::new();
let depth = renderer.create_depth_texture([800, 600]).await?;
let pass = Pass::new("scene");
pass.set_depth_target(&depth)?;
// The window grew. The pass keeps the same depth texture at the new size.
depth.resize([1024, 768])?;