Texture
Description
Section titled “Description”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).
inputaccepts 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.
How to use
Section titled “How to use”Create a Texture and set it on a Shader
Example
Section titled “Example”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)?;import { Renderer, Shader } from "fragmentcolor";const renderer = new Renderer();const shader = new Shader(`@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 RGBA (white) raw pixel bytes. With size set, createTexture skips// the image decoder and uploads the bytes directly as raw pixel data.const pixels = new Uint8Array([255, 255, 255, 255]);const texture = await renderer.createTexture(pixels, { size: [1, 1] });
// Insert the texture in the shader matching the name in the shader.shader.set("my_texture", texture);from fragmentcolor import Renderer, Shaderrenderer = Renderer()shader = Shader("""@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 RGBA (white) raw pixel bytes -- positional: (data, size=...).pixels = [255, 255, 255, 255]texture = renderer.create_texture(pixels, size=[1, 1])
# insert the texture in the shader matching the name in the shadershader.set("my_texture", texture)import FragmentColorlet renderer = Renderer()let shader = try Shader("""@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 = [255, 255, 255, 255]let texture = try await renderer.createTexture(pixels, [1, 1])
// Bind the texture to the uniform name declared in WGSL.try shader.set("my_texture", texture)import org.fragmentcolor.*val renderer = Renderer()val shader = Shader("""@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.val pixels = listOf(255, 255, 255, 255)val texture = renderer.createTexture(pixels, listOf(1u, 1u))
// Bind the texture to the uniform name declared in WGSL.shader.set("my_texture", texture)Methods
Section titled “Methods”Texture::id()
Section titled “Texture::id()”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.
Example
Section titled “Example”use fragmentcolor::{Renderer, TextureFormat};let renderer = Renderer::new();let texture = renderer.create_storage_texture(([64, 64], TextureFormat::Rgba)).await?;let id = *texture.id();import { Renderer, TextureFormat } from "fragmentcolor";
const renderer = new Renderer();const texture = await renderer.createStorageTexture([64, 64], TextureFormat.Rgba);const id = texture.id();from fragmentcolor import Renderer, TextureFormat
renderer = Renderer()texture = renderer.create_storage_texture([64, 64], TextureFormat.Rgba)id = texture.id()import FragmentColorlet renderer = Renderer()let texture = try await renderer.createStorageTexture([64, 64], TextureFormat.rgba)let id = texture.id()import org.fragmentcolor.*val renderer = Renderer()val texture = renderer.createStorageTexture(listOf(64u, 64u), TextureFormat.RGBA)val id = texture.id()Texture::size
Section titled “Texture::size”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.
Example
Section titled “Example”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;import { Renderer } from "fragmentcolor";const renderer = new Renderer();const pixels = new Uint8Array([255, 255, 255, 255]);const tex = await renderer.createTexture(pixels, { size: [1, 1] });const sz = tex.size();const width = sz.width;const height = sz.height;from fragmentcolor import Rendererrenderer = Renderer()pixels = [255, 255, 255, 255]tex = renderer.create_texture(pixels, size=[1, 1])sz = tex.size()width = sz.widthheight = sz.heightimport FragmentColorlet renderer = Renderer()let pixels = [255,255,255,255]let tex = try await renderer.createTexture(pixels, [1, 1])let sz = tex.size()let width = sz.widthlet height = sz.heightimport org.fragmentcolor.*val renderer = Renderer()val pixels = listOf(255, 255, 255, 255)val tex = renderer.createTexture(pixels, listOf(1u, 1u))val sz = tex.size()val width = sz.widthval height = sz.heightTexture::aspect
Section titled “Texture::aspect”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.
Example
Section titled “Example”use fragmentcolor::{Renderer, Size};
let renderer = Renderer::new();// 1x1 RGBA (white) raw pixel byteslet pixels: &[u8] = &[255,255,255,255];let tex = renderer.create_texture((pixels, [1, 1])).await?;let a = tex.aspect();import { Renderer } from "fragmentcolor";
const renderer = new Renderer();// 1x1 RGBA (white) raw pixel bytesconst pixels = new Uint8Array([255, 255, 255, 255]);const tex = await renderer.createTexture(pixels, { size: [1, 1] });const a = tex.aspect();from fragmentcolor import Renderer
renderer = Renderer()# 1x1 RGBA (white) raw pixel bytespixels = [255, 255, 255, 255]tex = renderer.create_texture(pixels, size=[1, 1])a = tex.aspect()import FragmentColor
let renderer = Renderer()// 1x1 RGBA (white) raw pixel byteslet pixels = [255,255,255,255]let tex = try await renderer.createTexture(pixels, [1, 1])let a = tex.aspect()import org.fragmentcolor.*
val renderer = Renderer()// 1x1 RGBA (white) raw pixel bytesval pixels = listOf(255, 255, 255, 255)val tex = renderer.createTexture(pixels, listOf(1u, 1u))val a = tex.aspect()Texture::set_sampler_options
Section titled “Texture::set_sampler_options”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.
Example
Section titled “Example”use fragmentcolor::{Renderer, Size, SamplerOptions};let renderer = Renderer::new();// 1x1 RGBA (white) raw pixel byteslet 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);import { Renderer } from "fragmentcolor";const renderer = new Renderer();// 1x1 RGBA (white) raw pixel bytesconst pixels = new Uint8Array([255, 255, 255, 255]);const texture = await renderer.createTexture(pixels, { size: [1, 1] });const opts = { repeatX: true, repeatY: true, smooth: true, compare: null };texture.setSamplerOptions(opts);from fragmentcolor import Renderer, SamplerOptionsrenderer = Renderer()# 1x1 RGBA (white) raw pixel bytespixels = [255, 255, 255, 255]
texture = renderer.create_texture(pixels, size=[1, 1])opts = SamplerOptions(repeat_x=True, repeat_y=True, smooth=True, compare=None)texture.set_sampler_options(opts)import FragmentColor
let renderer = Renderer()// 1x1 RGBA (white) raw pixel byteslet pixels: [UInt8] = [255, 255, 255, 255]
let texture = try await renderer.createTexture(pixels, [1, 1])let opts = SamplerOptions(repeatX: true, repeatY: true, smooth: true, compare: nil)texture.setSamplerOptions(opts)import org.fragmentcolor.*
val renderer = Renderer()// 1x1 RGBA (white) raw pixel bytesval pixels = listOf(255, 255, 255, 255)
val texture = renderer.createTexture(pixels, listOf(1u, 1u))val opts = SamplerOptions(repeatX = true, repeatY = true, smooth = true, compare = null)texture.setSamplerOptions(opts)Texture::write(bytes)
Section titled “Texture::write(bytes)”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). bytesholds 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 toTexture.write_region. Data of any other length is anInvalidInputerror, so a frame of the wrong size never uploads cropped.
- Any format with a fixed size per pixel works, from 1-byte
R8Unormto 16-byteRgba32Float. A block-compressed texture, such as one loaded from a BC7 or ASTC KTX2 file, is anInvalidInputerror. - The texture must have COPY_DST usage.
create_texturebuilds 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
Depth32Floattakes no uploaded pixels, so writing into one is anInvalidInputerror. Draw into it instead.
Example
Section titled “Example”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)?;import { Renderer, TextureFormat } from "fragmentcolor";
const renderer = new Renderer();const texture = await renderer.createStorageTexture([64, 64], TextureFormat.Rgba);const frame = new Uint8Array(64 * 64 * 4);
texture.write(frame);from fragmentcolor import Renderer, TextureFormat
renderer = Renderer()texture = renderer.create_storage_texture([64, 64], TextureFormat.Rgba)frame = bytes(64 * 64 * 4)
texture.write(frame)import FragmentColorlet renderer = Renderer()let texture = try await renderer.createStorageTexture([64, 64], TextureFormat.rgba)let frame_bytes = Array(repeating: 0, count: 64 * 64 * 4)
try texture.write(frame_bytes)import org.fragmentcolor.*val renderer = Renderer()val texture = renderer.createStorageTexture(listOf(64u, 64u), TextureFormat.RGBA)val frame_bytes = ByteArray(64 * 64 * 4)
texture.write(frame_bytes)Texture::write_region(bytes, region)
Section titled “Texture::write_region(bytes, region)”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): awbyhrectangle 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 atz = 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, returnsTextureError::RegionwithScreenRegionError::ReversedorScreenRegionError::Empty - A
TextureRegionconstructed explicitly with.with_stride(...)/.with_rows(...)for advanced data-layout control
- See
Texture::writefor 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 anInvalidInputerror. 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_texturebuilds by default, takes whole writes only, since a partial one would leave the smaller levels stale. Any other region is anInvalidInputerror, so create a texture you update in parts withmipmaps: false, or from a KTX2 file with one level.
Example
Section titled “Example”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)?;import { Renderer, TextureFormat } from "fragmentcolor";
const renderer = new Renderer();const texture = await renderer.createStorageTexture([64, 32], TextureFormat.Rgba);const bytes = new Uint8Array(64 * 32 * 4);
// Simple sub-rectangle update.texture.writeRegion(bytes, [0, 0, 64, 32]);
// Explicit data layout (advanced).texture.writeRegion(bytes, { x: 0, y: 0, width: 64, height: 32, bytesPerRow: 256, rowsPerImage: 32 });from fragmentcolor import Renderer, TextureFormat
renderer = Renderer()texture = renderer.create_storage_texture([64, 32], TextureFormat.Rgba)bytes_data = bytes(64 * 32 * 4)
# Simple sub-rectangle update.texture.write_region(bytes_data, [0, 0, 64, 32])
# Explicit data layout (advanced).texture.write_region(bytes_data, {"x": 0, "y": 0, "width": 64, "height": 32, "bytes_per_row": 256, "rows_per_image": 32})import FragmentColorlet renderer = Renderer()let texture = try await renderer.createStorageTexture([64, 32], TextureFormat.rgba)let bytes = Array(repeating: 0, count: 64 * 32 * 4)
// Simple sub-rectangle update.try texture.writeRegion(bytes, [0, 0, 64, 32])
// Explicit data layout, for when the source rows are padded.let region = try TextureRegion.from([0, 0, 64, 32]).withStride(256).withRows(32)try texture.writeRegion(bytes, region)import org.fragmentcolor.*val renderer = Renderer()val texture = renderer.createStorageTexture(listOf(64u, 32u), TextureFormat.RGBA)val bytes = ByteArray(64 * 32 * 4)
// Simple sub-rectangle update.texture.writeRegion(bytes, listOf(0u, 0u, 64u, 32u))
// Explicit data layout, for when the source rows are padded.val region = TextureRegion.from(listOf(0u, 0u, 64u, 32u)).withStride(256u).withRows(32u)texture.writeRegion(bytes, region)Texture::get_image()
Section titled “Texture::get_image()”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_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. - 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)forRgba16Float, the format an HDR file decodes into, andimage.view(numpy.float32)forRgba32FloatandR32Float. A 32-bit integer format reads throughimage.view(numpy.uint32)forR32UintandRgba32Uint, andimage.view(numpy.int32)forR32SintandRgba32Sint. - In JavaScript,
getImagefirst 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 = texture.get_image().await?;import { Renderer, TextureFormat } from "fragmentcolor";const renderer = new Renderer();const texture = await renderer.createStorageTexture([64, 64], TextureFormat.Rgba);texture.write(Array(64 * 64 * 4).fill(0));
const bytes = await texture.getImage();from fragmentcolor import Renderer, TextureFormatrenderer = Renderer()texture = renderer.create_storage_texture([64, 64], TextureFormat.Rgba)texture.write([0] * (64 * 64 * 4))
bytes = texture.get_image()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 texture.getImage()import org.fragmentcolor.*val renderer = Renderer()val texture = renderer.createStorageTexture(listOf(64u, 64u), TextureFormat.RGBA)texture.write(ByteArray(64 * 64 * 4))
val bytes = texture.getImage()Texture::resize(size)
Section titled “Texture::resize(size)”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.
Example
Section titled “Example”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])?;import { Pass, Renderer } from "fragmentcolor";
const renderer = new Renderer();const depth = await renderer.createDepthTexture([800, 600]);const pass = new Pass("scene");pass.setDepthTarget(depth);
// The window grew. The pass keeps the same depth texture at the new size.depth.resize([1024, 768]);from fragmentcolor import Pass, Renderer
renderer = Renderer()depth = renderer.create_depth_texture([800, 600])rpass = Pass("scene")rpass.set_depth_target(depth)
# The window grew. The pass keeps the same depth texture at the new size.depth.resize([1024, 768])import FragmentColor
let renderer = Renderer()let depth = try await renderer.createDepthTexture([800, 600])let pass = Pass("scene")try pass.setDepthTarget(depth)
// The window grew. The pass keeps the same depth texture at the new size.try depth.resize([1024, 768])import org.fragmentcolor.*
val renderer = Renderer()val depth = renderer.createDepthTexture(listOf(800u, 600u))val pass = Pass("scene")pass.setDepthTarget(depth)
// The window grew. The pass keeps the same depth texture at the new size.depth.resize(listOf(1024u, 768u))