Material
Description
Section titled “Description”A Material bundles a Shader with the glTF 2.0 PBR-MR field set (base
color, metallic, roughness, emissive, normal scale, occlusion strength,
alpha cutoff, plus the matching set of optional textures) and exposes
each as a builder-style setter.
The default Material::pbr constructs the bundle from FragmentColor’s
built-in physically-based shader (Cook-Torrance specular with GGX + Smith +
Schlick, Lambertian diffuse with energy conservation, glTF-spec texture
sampling on top of the factor uniforms), pre-populated with sensible
defaults. The five glTF texture slots start unbound; the renderer resolves
each one to a 1×1 default from its lazy texture cache the first time a Pass
renders the Material, so the Material’s shader has every binding it needs
without any further setup. Material::pbr can’t fail: the shader parts it
composes are compiled into the library. You can also call
Material::custom(shader) to wrap your own shader; the same setters apply
best-effort, no-op-ing for uniform paths the shader doesn’t declare.
Materials are typically combined with a Mesh
into a Model, which is the
object you actually add to a Pass. The Material itself doesn’t render
anything on its own.
Cloning is an Arc-share, not a deep copy
Section titled “Cloning is an Arc-share, not a deep copy”Material clones (and every setter’s return value) point at the same
inner shader. Mutating one handle changes the state every other handle
reads:
let red = Material::pbr().base_color([1.0, 0.0, 0.0, 1.0])?;let same = red.clone();same.base_color([0.0, 1.0, 0.0, 1.0])?; // both `red` and `same` now read greenSame goes for the chained-setter return: Material::pbr().metallic(...)
gives you back a handle to the same shader, not a fresh copy. This is the
mechanic that makes setters chain cheaply and lets one Material drive
hundreds of Models without per-instance shader duplication.
When you genuinely need an independent material, build a fresh
Material::pbr() (and re-set the factor / texture slots you care about).
The “many handles to one shader” share semantics is the right default;
the explicit-fresh-Material path is the escape hatch.
What lives where
Section titled “What lives where”- Factor uniforms (base color, metallic, …) are stored on the shader as
material.<name>fields and read every frame. They’re per-Material, so many Models that share a Material share these values. - Texture bindings (base color texture, …) are stored under the
canonical glTF binding names (
base_color_map,metallic_roughness_map,normal_map,occlusion_map,emissive_map) and sampled by the default shader. Unset slots resolve to the renderer’s 1×1 defaults so the shader’s bind group is always complete. - UV sources: each texture slot samples its own UV set (
UV0orUV1) through its ownKHR_texture_transform. The PBR shader keeps them inmaterial.uv, five entries inTextureSlotorder, each withuv_set,offset,scaleandrotation.Material::texture_uv,Material::texture_transformandMaterial::uv_transformset them. - Per-Model transform rides the per-instance vertex attribute stream
as
model_0tomodel_3(fourvec4<f32>columns of amat4x4<f32>, at locations 3 to 6 in the PBR shader). The renderer fills it from each Model’s transform at draw time. It’s not a Material uniform, so Models that share one Material each draw with their own transform.
Pipeline state
Section titled “Pipeline state”alpha_mode (Opaque / Mask / Blend) and double_sided are wired
through to the pipeline. See Material::alpha_mode and
Material::double_sided. Mask mode uses material.alpha_cutoff to discard
transparent fragments; Blend uses standard SrcAlpha/OneMinusSrcAlpha
over-blend with depth-write turned off.
Tangent-space TBN normal mapping is supported via the default PBR shader:
the sampled normal is decoded from the stored [0, 1] bytes, the XY
components are scaled by material.normal_scale, and the result is rotated
from tangent space into world space using the per-vertex tangent (with the
glTF tangent.w handedness flag preserved). For custom TBN beyond the
bundled implementation, use Material::custom.
Example
Section titled “Example”use fragmentcolor::{Material, Mesh, Model, Vertex};
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]),]);
let material = Material::pbr() .base_color([0.85, 0.2, 0.2, 1.0])? .metallic(0.0)? .roughness(0.4)? .emissive([0.0, 0.0, 0.05])?;
let model = Model::new(mesh, material);import { Material, Mesh, Model, Vertex } from "fragmentcolor";
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]), ]);
const material = Material.pbr().baseColor([0.85, 0.2, 0.2, 1.0]).metallic(0.0).roughness(0.4).emissive([0.0, 0.0, 0.05]);
const model = new Model(mesh, material);from fragmentcolor import Material, Mesh, Model, Vertex
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]),])
material = Material.pbr().base_color([0.85, 0.2, 0.2, 1.0]).metallic(0.0).roughness(0.4).emissive([0.0, 0.0, 0.05])
model = Model(mesh, material)import FragmentColor
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]),])
let material = try Material.pbr().baseColor([0.85, 0.2, 0.2, 1.0]).metallic(0.0).roughness(0.4).emissive([0.0, 0.0, 0.05])
let model = Model(mesh, material)import org.fragmentcolor.*
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))))
val material = Material.pbr().baseColor(listOf(0.85f, 0.2f, 0.2f, 1.0f)).metallic(0.0f).roughness(0.4f).emissive(listOf(0.0f, 0.0f, 0.05f))
val model = Model(mesh, material)Methods
Section titled “Methods”Material::alpha_cutoff
Section titled “Material::alpha_cutoff”Sets the alpha threshold used by AlphaMode::Mask. Fragments whose
base_color.a falls below this value are discarded in the fragment
shader. Stored on material.alpha_cutoff; default 0.5, matching glTF 2.0.
Only AlphaMode::Mask reads this value; in Opaque and Blend modes the
fragment shader ignores it. Use it together with Material::alpha_mode
when you want hard-edged cut-out transparency (foliage, chain-link, decals).
NaN or an infinity returns MaterialError::NotFinite, which names the
call, and the material keeps the value it had. The other languages also
refuse a number past the 32-bit float range, such as 1e39, with a
message like Material.alphaCutoff: value must be a finite number that fits a 32-bit float, got 1e39. JavaScript throws an Error named
InvalidInputError, Python raises InvalidInputError, Swift throws
FragmentColorError and Kotlin throws FragmentColorException.
Example
Section titled “Example”use fragmentcolor::Material;
let foliage = Material::pbr().alpha_cutoff(0.3)?;import { Material } from "fragmentcolor";
const foliage = Material.pbr().alphaCutoff(0.3);from fragmentcolor import Material
foliage = Material.pbr().alpha_cutoff(0.3)import FragmentColor
let foliage = try Material.pbr().alphaCutoff(0.3)import org.fragmentcolor.*
val foliage = Material.pbr().alphaCutoff(0.3f)Material::alpha_mode
Section titled “Material::alpha_mode”Set how the renderer interprets the alpha channel of the material’s output. Mirrors the
glTF 2.0 alphaMode semantics. Pipeline state is baked into the WebGPU pipeline, so
different AlphaMode values for the same shader cache to distinct pipelines.
The three variants:
AlphaMode::Opaque(default): depth-test is on, blending is off. Alpha is written out but ignored by the framebuffer. Pick this for solid surfaces; it’s the cheapest option and the only one that lets the depth buffer fully describe the geometry.AlphaMode::Mask: depth-test is on, blending is off, but the fragment shaderdiscards any pixel whosematerial.base_color.afalls belowmaterial.alpha_cutoff. The classic foliage / chain-link / decal trick: keeps the perf profile of opaque geometry (no order dependence, full depth writes) while letting silhouettes punch out hard-edged transparency. Tune the cut-off withMaterial::alpha_cutoff.AlphaMode::Blend: depth-test stays on but depth-write turns off, and the color target uses standardSrcAlpha / OneMinusSrcAlphaover-blend. Use for glass, smoke, fades, decals that need soft edges. The renderer sorts blend Models on the Pass back-to-front by eye-space Z before drawing, using the Camera attached viaPass::add(&camera). Translucent surfaces over-blend in the right order without the caller managing it. Limitation: sorts by per-Model AABB centroid (not per-fragment), so self-intersecting or interpenetrating translucent meshes can still show artifacts. Cross-Material interleaving works correctly: translucent draws across every shader in the Pass merge into one globally-sorted back-to-front pass. Blending needs a color target that blends and a shader that writes avec4. A format that never blends, such as an integer one, and an output without alpha returnPassError::InvalidColorTargeton every device. WhetherRgba32Floatblends depends on the device: the renderer asks for float32 blending wherever the GPU offers it, and a device without it returnsRendererError::FeatureError.Rgba16Floatand the 8-bit unorm formats blend everywhere.
This is a pipeline-state flag. Changing it forces the renderer to rebuild the pipeline
for the affected (shader, alpha_mode, double_sided) key. Switching it every frame is
fine in practice (the second build hits the cache from then on) but avoid toggling per
draw call inside a frame.
Example
Section titled “Example”use fragmentcolor::{AlphaMode, Material};
let foliage = Material::pbr() .alpha_mode(AlphaMode::Mask) .alpha_cutoff(0.3)?;
let glass = Material::pbr() .base_color([0.9, 0.95, 1.0, 0.25])? .alpha_mode(AlphaMode::Blend);
let solid = Material::pbr().alpha_mode(AlphaMode::Opaque);import { AlphaMode, Material } from "fragmentcolor";
const foliage = Material.pbr().alphaMode(AlphaMode.Mask).alphaCutoff(0.3);
const glass = Material.pbr().baseColor([0.9, 0.95, 1.0, 0.25]).alphaMode(AlphaMode.Blend);
const solid = Material.pbr().alphaMode(AlphaMode.Opaque);from fragmentcolor import AlphaMode, Material
foliage = Material.pbr().alpha_mode(AlphaMode.Mask).alpha_cutoff(0.3)
glass = Material.pbr().base_color([0.9, 0.95, 1.0, 0.25]).alpha_mode(AlphaMode.Blend)
solid = Material.pbr().alpha_mode(AlphaMode.Opaque)import FragmentColor
let foliage = try Material.pbr().alphaMode(AlphaMode.mask).alphaCutoff(0.3)
let glass = try Material.pbr().baseColor([0.9, 0.95, 1.0, 0.25]).alphaMode(AlphaMode.blend)
let solid = Material.pbr().alphaMode(AlphaMode.opaque)import org.fragmentcolor.*
val foliage = Material.pbr().alphaMode(AlphaMode.MASK).alphaCutoff(0.3f)
val glass = Material.pbr().baseColor(listOf(0.9f, 0.95f, 1.0f, 0.25f)).alphaMode(AlphaMode.BLEND)
val solid = Material.pbr().alphaMode(AlphaMode.OPAQUE)Material::base_color
Section titled “Material::base_color”Set the base color factor (linear RGBA). For dielectrics this is the diffuse albedo; for metals it’s the F0 reflectance. Alpha goes through the fragment output unchanged.
Maps to the material.base_color uniform on the underlying shader. Default
is [1, 1, 1, 1].
Returns a handle to the same Material (Arc-shared) so calls chain. See Material: Cloning is an Arc-share for what that means for mutation visibility.
An item that is NaN or an infinity returns MaterialError::NotFinite,
which names the call and the item, and the material keeps the value it
had. The other languages also refuse an item past the 32-bit float range,
such as 1e39, with a message like Material.baseColor: item 3 must be a finite number that fits a 32-bit float, got 1e39. JavaScript throws an
Error named InvalidInputError, Python raises InvalidInputError,
Swift throws FragmentColorError and Kotlin throws
FragmentColorException.
Example
Section titled “Example”use fragmentcolor::{Material, Renderer};
let renderer = Renderer::new();let red = Material::pbr().base_color([1.0, 0.2, 0.2, 1.0])?;import { Material, Renderer } from "fragmentcolor";
const renderer = new Renderer();const red = Material.pbr().baseColor([1.0, 0.2, 0.2, 1.0]);from fragmentcolor import Material, Renderer
renderer = Renderer()red = Material.pbr().base_color([1.0, 0.2, 0.2, 1.0])import FragmentColor
let renderer = Renderer()let red = try Material.pbr().baseColor([1.0, 0.2, 0.2, 1.0])import org.fragmentcolor.*
val renderer = Renderer()val red = Material.pbr().baseColor(listOf(1.0f, 0.2f, 0.2f, 1.0f))Material::base_color_texture
Section titled “Material::base_color_texture”Bind a texture to the base_color_map slot. The default PBR shader samples it in fs_main and multiplies by the factor. The albedo for each fragment is material.base_color * textureSample(base_color_map, pbr_sampler, uv) * vertex_color, where uv is slot_uv(material.uv[0], in.uv0, in.uv1): the UV set texture_uv picks for the slot, through the slot’s texture_transform.
Accepts any Into<TextureInput>, the inputs Renderer::create_texture takes:
- A pre-built
&Texture. The setter stores the texture’s ID immediately and the GPU texture stays Arc-shared across every Material that points at it. Passing the same&shared_textureto N Materials produces one GPU upload and N shader-uniform references: the cheap way to reuse one texture map across a scene full of objects without paying for N texture allocations. The texture belongs to theRendererthat created it, and anotherRendererrefuses to draw it. It keeps the options it was created with, and the setter refuses options beside it. - Encoded bytes, raw pixels with their size as
(bytes, [w, h]), bytes with a format as(bytes, format), bytes with every option as(bytes, options), a path or a URL, alone or as(path, format)or(path, options), or aMipmap, alone or as(chain, options). The Material keeps this source as a map. EachRendererthat draws the Material uploads a copy of its own atRenderer::load, or on native targets at its firstRenderer::render, and frees it when theRendereror the Material drops. A map set again draws its old copy until theRendererloads the new one.
To share a map across Renderers, pass bytes, a path, a URL or a Mipmap.
Each language spells these inputs the way its create_texture does, and the other four texture setters take the same ones:
- JavaScript:
baseColorTexture(input, options?), whereoptionsis a size such as[w, h], aTextureFormat, or{ size?, format?, mipmaps?, sampler?, usage? }. - Python:
base_color_texture(input, size=None, format=None, mipmaps=None, sampler=None, usage=None). A NumPy array brings its own size, and asizethat differs from it raisesInvalidInputError. - Swift and Kotlin:
baseColorTexture(texture),baseColorTexture(bytes),baseColorTexture(bytes, format),baseColorTexture(bytes, [w, h]),baseColorTexture(bytes, size),baseColorTexture(bytes, options),baseColorTexture(path),baseColorTexture(path, format),baseColorTexture(path, options),baseColorTexture(chain)andbaseColorTexture(chain, options). Bytes areData,[UInt8]or[Int]in Swift andByteArrayorList<Int>in Kotlin, in every bytes form. The bytes forms withoutoptionstake an optionalusage. AnIntoutside 0 to 255 throws, and so does a[w, h]that isn’t 2 or 3 numbers.
A source with no format of its own reads as sRGB in this slot, as glTF’s
base color does. A Mipmap or a KTX2 container keeps the format it stores,
and takes that sRGB reading only where its bytes read the same in it, so a
float chain or container stays linear. A format you pass yourself is the
one it uploads in, and a Mipmap or KTX2 container whose bytes can’t be
read in it fails the load with an InvalidInput error that names load.
Unset, this slot resolves to a 1×1 white default the renderer hands out
lazily, so calling Material::pbr() without binding a
texture renders correctly under the factor alone.
Memory
Section titled “Memory”A map holds its source for as long as the slot keeps it. That is the file’s
bytes for an encoded PNG or JPEG, a glTF image inside its file included, the
pixels for raw bytes or a NumPy array, the container for KTX2, and the chain
for a Mipmap. A path or
a URL holds only its string, and each Renderer reads or fetches it again.
renderer.create_texture keeps nothing on the CPU, and the texture it returns
draws in that one Renderer.
Errors
Section titled “Errors”The setter checks its input and the slot at once, and a call it refuses
leaves the slot as it was. Options beside a Texture return
MaterialError::Texture with an InvalidInput texture error that names the
call, and so does an input that holds no data: Rust’s TextureData::Empty,
or an empty byte list, path or URL in any language. A slot that a Material::custom shader declares as
something other than a texture returns MaterialError::Shader with the
shader’s TypeMismatch. A slot the shader doesn’t declare is skipped with a
log warning, as the number setters skip a field, and the setter returns the
Material.
The bindings read their arguments before the setter runs and throw for one
they can’t use: a size that isn’t 2 or 3 whole numbers, options of the wrong
type or shape, options beside a Texture, and in Python a size that
differs from a NumPy array’s own. Python raises TypeError for an argument
of the wrong type, MaterialError for a slot the shader declares as a
number, and InvalidInputError for the rest. JavaScript throws an Error
of the same name. Swift throws FragmentColorError, and each call needs
try, while Kotlin throws FragmentColorException.
A source that fails to upload (file not found, decode error, unsupported
format) fails Renderer::load(&material).await,
or the native render that runs it. That Renderer keeps no copy and tries
again at each later call, until the source is fixed or replaced, while the
other maps upload.
On the web, render uploads nothing, so await load in each Renderer
before its first frame. Until then the slot draws its 1×1 default, in a custom
shader too, where the default fits the slot. Otherwise, as for an integer
texture or a compute shader, the render fails with a BindingError that asks
for load. On native, only a map set on another thread during a render
meets this, for that frame.
For deterministic error handling, pre-build the texture eagerly:
renderer.create_texture(path).await? returns a Texture that has already
uploaded, so no load can fail on it later, and
Material::base_color_texture(&texture) takes an Arc-shared reference. The
lazy path stays useful when the URL / path resolves at render time but the
caller doesn’t want to await yet.
Example
Section titled “Example”use fragmentcolor::{Material, Renderer};
let renderer = Renderer::new();let albedo_bytes: Vec<u8> = vec![ 255, 200, 120, 255, 255, 240, 180, 255, 230, 180, 100, 255, 255, 220, 150, 255,];let albedo = renderer.create_texture((albedo_bytes, [2, 2])).await?;
// Every Material that points at `albedo` reuses the same uploaded GPU// texture; passing the same handle into N Material instances costs one// upload and N shader-uniform references.let material = Material::pbr().base_color_texture(&albedo)?;
// Raw pixels with their size upload when the scene loads.let tint: Vec<u8> = vec![255, 128, 0, 255];let tinted = Material::pbr().base_color_texture((tint, [1, 1]))?;import { Material, Renderer } from "fragmentcolor";
const renderer = new Renderer();const albedo_bytes = [ 255, 200, 120, 255, 255, 240, 180, 255, 230, 180, 100, 255, 255, 220, 150, 255, ];const albedo = await renderer.createTexture(albedo_bytes, [2, 2]);
// Every Material that points at `albedo` reuses the same uploaded GPU// texture; passing the same handle into N Material instances costs one// upload and N shader-uniform references.const material = Material.pbr().baseColorTexture(albedo);
// Raw pixels with their size upload when the scene loads.const tint = [255, 128, 0, 255];const tinted = Material.pbr().baseColorTexture(tint, [1, 1]);from fragmentcolor import Material, Renderer
renderer = Renderer()albedo_bytes = [ 255, 200, 120, 255, 255, 240, 180, 255, 230, 180, 100, 255, 255, 220, 150, 255,]albedo = renderer.create_texture(albedo_bytes, size=[2, 2])
# Every Material that points at `albedo` reuses the same uploaded GPU# texture; passing the same handle into N Material instances costs one# upload and N shader-uniform references.material = Material.pbr().base_color_texture(albedo)
# Raw pixels with their size upload when the scene loads.tint = [255, 128, 0, 255]tinted = Material.pbr().base_color_texture(tint, size=[1, 1])import FragmentColor
let renderer = Renderer()let albedo_bytes = [ 255, 200, 120, 255, 255, 240, 180, 255, 230, 180, 100, 255, 255, 220, 150, 255,]let albedo = try await renderer.createTexture(albedo_bytes, [2, 2])
// Every Material that points at `albedo` reuses the same uploaded GPU// texture; passing the same handle into N Material instances costs one// upload and N shader-uniform references.let material = try Material.pbr().baseColorTexture(albedo)
// Raw pixels with their size upload when the scene loads.let tint = [255, 128, 0, 255]let tinted = try Material.pbr().baseColorTexture(tint, [1, 1])import org.fragmentcolor.*
val renderer = Renderer()val albedo_bytes = listOf(255, 200, 120, 255, 255, 240, 180, 255, 230, 180, 100, 255, 255, 220, 150, 255)val albedo = renderer.createTexture(albedo_bytes, listOf(2u, 2u))
// Every Material that points at `albedo` reuses the same uploaded GPU// texture; passing the same handle into N Material instances costs one// upload and N shader-uniform references.val material = Material.pbr().baseColorTexture(albedo)
// Raw pixels with their size upload when the scene loads.val tint = listOf(255, 128, 0, 255)val tinted = Material.pbr().baseColorTexture(tint, listOf(1u, 1u))Material::custom
Section titled “Material::custom”Wrap an arbitrary Shader as a Material so it can be paired with a
Mesh to form a Model. The PBR-named setters (base_color, metallic,
…) still work; they call shader.set(...) under matching uniform paths
(material.base_color, etc.). A setter skips a uniform your shader doesn’t
declare with a log warning and returns the Material, so set custom uniforms
directly via material.shader().set(...).
A value your shader declares but can’t hold, such as a number past ±65504
for an f16 field or a texture for a slot it declares as a number, returns
MaterialError::Shader with the shader’s error, and the call changes
nothing, a whole uv_transform included. JavaScript
throws an Error named MaterialError, Python raises MaterialError, Swift
throws FragmentColorError and Kotlin throws FragmentColorException.
Material::custom is the escape hatch for any shading model that isn’t
glTF-spec PBR: toon shading, flat unlit colors, wireframe debug views,
volumetric or post-process effects that you want to attach to a Mesh.
What custom shaders should declare for full Material-style ergonomics
Section titled “What custom shaders should declare for full Material-style ergonomics”Optional but recommended:
struct PbrMaterial { base_color: vec4<f32>, … }at@group(1) @binding(0)bound asmaterial. This lets the PBR factor setters work as-is.- A
uvfield in that struct, with one entry per texture slot inTextureSlotorder, foruv_transform,texture_transformandtexture_uvto write. The built-in PBR shader declares it this way:
struct TextureUv { offset: vec2<f32>, scale: vec2<f32>, rotation: f32, uv_set: u32, pad: vec2<u32>,}
struct PbrMaterial { base_color: vec4<f32>, // … the other factors, then plain padding members up to // an offset that is a multiple of 16 … uv: array<TextureUv, 5>,}Spell the padding out as members, as the built-in PBR shader does. @size and @align keep their layout on Vulkan, Metal, DX12 and the browser’s WebGPU, where FragmentColor hands the browser WGSL that keeps them, and the GL backends, WebGL2 among them, refuse them, since a std140 block can’t hold such a layout.
- Four
vec4<f32>vertex inputs namedmodel_0tomodel_3, the columns of the Model’s transform. The renderer fills them at draw time from each Model’sset_transform,translate,rotateandscale. The PBR shader reads them at locations 3 to 6. Any free locations work, since the renderer matches these inputs by name. It fills them for each visible Model that a pass draws through this shader. A Model’s Mesh that no visible Model in the pass draws through it, such as a hidden Model’s, or one in another pass that shares the Material, draws nothing. A shader that draws none of the pass’s Models and reads these columns for a Model’s Mesh, such as this Material’s shader rendered on its own, makesRenderer::renderreturnMeshError::InvalidInstance, which names the columns the shader reads.
Without these the Material still draws. The factor setters do nothing, and every Model draws at its Mesh’s own coordinates, whatever its transform.
Lights
Section titled “Lights”A render shader takes the Lights
that reach it by declaring a root named lights, and optionally one named
light_grid, at any group and binding. The member names, types and offsets
must match the ones below, and so must the struct’s size, so no @align may
raise its alignment. The struct names are free. The renderer fills
both roots in render passes, so they don’t appear in list_uniforms or
list_keys, and set and get reach only lights.ambient.
struct Light { // 64 bytes kind: u32, // 0 directional, 1 point, 2 spot intensity: f32, range: f32, // 0 reaches everywhere inner_cone_cos: f32, position: vec3<f32>, outer_cone_cos: f32, direction: vec3<f32>, color: vec3<f32>,}struct LightGrid { // 112 bytes view_proj: mat4x4<f32>, depth_plane: vec4<f32>, size: vec3<u32>, slicing: u32, // 0 no grid, 1 logarithmic, 2 linear slice_scale: f32, slice_bias: f32, reach: f32,}struct Lights { count: u32, global_count: u32, promoted_count: u32, ambient: vec3<f32>, grid: LightGrid, // at byte 32 lights: array<Light>, // at byte 144}@group(0) @binding(1) var<storage, read> lights: Lights;@group(0) @binding(2) var<storage, read> light_grid: array<u32>;A storage lights with another layout, or a light_grid of another type,
fails Shader::new with ShaderError::TypeMismatch, which spells out the
layout above.
lights.lights holds lights.count lights: first the global_count lights
without a range, then the lights with one. A shader without light_grid
loops over all of them. With it, a fragment reads only the lights that
reach its cluster. light_grid starts with promoted_count light indices
that every cluster reads, and cluster c follows at word
promoted_count + 2 * c, as the word where its index list starts and the
length of that list. Copy light_cell and accumulate_lights below and
write a shade_light for your shading model:
const GRID_MARGIN: f32 = 0.015625;const CELL_EVERY: u32 = 0xffffffffu;const CELL_GLOBAL: u32 = 0xfffffffeu;
// The cluster that holds `world`, or CELL_GLOBAL past every light's reach,// or CELL_EVERY with no grid, behind the grid's eye, or outside the grid.fn light_cell(world: vec3<f32>) -> u32 { let grid = lights.grid; if (grid.slicing == 0u) { return CELL_EVERY; } let point = vec4<f32>(world, 1.0); let depth = dot(grid.depth_plane, point); if (depth > grid.reach) { return CELL_GLOBAL; } let clip = grid.view_proj * point; if (clip.w <= 0.0) { return CELL_EVERY; } let size = vec3<f32>(grid.size); var slice = depth * grid.slice_scale + grid.slice_bias; if (grid.slicing == 1u) { slice = log2(max(depth, 1.0e-30)) * grid.slice_scale + grid.slice_bias; } let cell = vec3<f32>((clip.xy / clip.w * 0.5 + 0.5) * size.xy, slice); if (any(cell < vec3<f32>(-GRID_MARGIN)) || any(cell > size + GRID_MARGIN)) { return CELL_EVERY; } let index = min(vec3<u32>(max(cell, vec3<f32>(0.0))), grid.size - vec3<u32>(1u)); return index.x + grid.size.x * (index.y + grid.size.y * index.z);}
// Every light that reaches `world`, shaded by your `shade_light`.fn accumulate_lights(world: vec3<f32>, normal: vec3<f32>) -> vec3<f32> { var total = vec3<f32>(0.0); let cell = light_cell(world); if (cell == CELL_EVERY) { for (var i = 0u; i < lights.count; i++) { total += shade_light(lights.lights[i], world, normal); } return total; } for (var i = 0u; i < lights.global_count; i++) { total += shade_light(lights.lights[i], world, normal); } if (cell == CELL_GLOBAL) { return total; } for (var k = 0u; k < lights.promoted_count; k++) { total += shade_light(lights.lights[light_grid[k]], world, normal); } let entry = lights.promoted_count + 2u * cell; let first = light_grid[entry]; for (var k = 0u; k < light_grid[entry + 1u]; k++) { total += shade_light(lights.lights[light_grid[first + k]], world, normal); } return total;}A light with a range adds nothing past it, and a spot light adds nothing
outside its outer cone, so shade_light must honor both for the grid to
stay exact. The Material::pbr shader’s shade_light uses the
KHR_lights_punctual falloff, (1 - (d / range)^4) scaled by the inverse
square distance.
On every OpenGL backend, WebGL2 included, and on a device without compute
shaders or storage buffers in fragment shaders, the same source runs with
lights turned into a uniform block that holds as many lights as the device
allows, and with no grid, so light_cell returns CELL_EVERY. A shader that
calls arrayLength on either root can’t run there, and Renderer::render
refuses it with RendererError::FeatureError before it takes a frame. Loop to
lights.count instead.
A fixed-size light array
Section titled “A fixed-size light array”A uniform LightArray of a fixed length N fills on every device too,
with up to N lights:
struct LightArray { count: u32, ambient: vec3<f32>, lights: array<Light, N> }@group(0) @binding(1) var<uniform> lights: LightArray;A shader of this shape takes at most N lights, and the add past them
fails with PassError::LightCapReached { cap: N }. lights.lights[i] holds
the lights in the order they reached the shader. A uniform lights that
matches neither shape stays an ordinary uniform, which set reaches, and
logs a warning.
Example
Section titled “Example”use fragmentcolor::{Material, Shader};
let flat = Shader::new(r#" struct Camera { view_proj: mat4x4<f32>, position: vec3<f32> } struct Light { kind: u32, intensity: f32, range: f32, inner_cone_cos: f32, position: vec3<f32>, outer_cone_cos: f32, direction: vec3<f32>, color: vec3<f32> } struct LightGrid { view_proj: mat4x4<f32>, depth_plane: vec4<f32>, size: vec3<u32>, slicing: u32, slice_scale: f32, slice_bias: f32, reach: f32 } struct Lights { count: u32, global_count: u32, promoted_count: u32, ambient: vec3<f32>, grid: LightGrid, lights: array<Light> } @group(0) @binding(0) var<uniform> camera: Camera; @group(0) @binding(1) var<storage, read> lights: Lights;
@vertex fn vs_main( @location(0) p: vec3<f32>, @location(3) model_0: vec4<f32>, @location(4) model_1: vec4<f32>, @location(5) model_2: vec4<f32>, @location(6) model_3: vec4<f32>, ) -> @builtin(position) vec4<f32> { let model = mat4x4<f32>(model_0, model_1, model_2, model_3); return camera.view_proj * model * vec4<f32>(p, 1.0); } @fragment fn fs_main() -> @location(0) vec4<f32> { var glow = lights.ambient; for (var i = 0u; i < lights.count; i++) { glow += lights.lights[i].color * lights.lights[i].intensity * 0.1; } return vec4<f32>(glow, 1.0); }"#)?;
let flat_mat = Material::custom(flat);import { Material, Shader } from "fragmentcolor";
const flat = new Shader(`
struct Camera { view_proj: mat4x4<f32>, position: vec3<f32> } struct Light { kind: u32, intensity: f32, range: f32, inner_cone_cos: f32, position: vec3<f32>, outer_cone_cos: f32, direction: vec3<f32>, color: vec3<f32> } struct LightGrid { view_proj: mat4x4<f32>, depth_plane: vec4<f32>, size: vec3<u32>, slicing: u32, slice_scale: f32, slice_bias: f32, reach: f32 } struct Lights { count: u32, global_count: u32, promoted_count: u32, ambient: vec3<f32>, grid: LightGrid, lights: array<Light> } @group(0) @binding(0) var<uniform> camera: Camera; @group(0) @binding(1) var<storage, read> lights: Lights;
@vertex fn vs_main( @location(0) p: vec3<f32>, @location(3) model_0: vec4<f32>, @location(4) model_1: vec4<f32>, @location(5) model_2: vec4<f32>, @location(6) model_3: vec4<f32>, ) -> @builtin(position) vec4<f32> { let model = mat4x4<f32>(model_0, model_1, model_2, model_3); return camera.view_proj * model * vec4<f32>(p, 1.0); } @fragment fn fs_main() -> @location(0) vec4<f32> { var glow = lights.ambient; for (var i = 0u; i < lights.count; i++) { glow += lights.lights[i].color * lights.lights[i].intensity * 0.1; } return vec4<f32>(glow, 1.0); }
`);
const flat_mat = Material.custom(flat);from fragmentcolor import Material, Shader
flat = Shader(""" struct Camera { view_proj: mat4x4<f32>, position: vec3<f32> } struct Light { kind: u32, intensity: f32, range: f32, inner_cone_cos: f32, position: vec3<f32>, outer_cone_cos: f32, direction: vec3<f32>, color: vec3<f32> } struct LightGrid { view_proj: mat4x4<f32>, depth_plane: vec4<f32>, size: vec3<u32>, slicing: u32, slice_scale: f32, slice_bias: f32, reach: f32 } struct Lights { count: u32, global_count: u32, promoted_count: u32, ambient: vec3<f32>, grid: LightGrid, lights: array<Light> } @group(0) @binding(0) var<uniform> camera: Camera; @group(0) @binding(1) var<storage, read> lights: Lights;
@vertex fn vs_main( @location(0) p: vec3<f32>, @location(3) model_0: vec4<f32>, @location(4) model_1: vec4<f32>, @location(5) model_2: vec4<f32>, @location(6) model_3: vec4<f32>, ) -> @builtin(position) vec4<f32> { let model = mat4x4<f32>(model_0, model_1, model_2, model_3); return camera.view_proj * model * vec4<f32>(p, 1.0); } @fragment fn fs_main() -> @location(0) vec4<f32> { var glow = lights.ambient; for (var i = 0u; i < lights.count; i++) { glow += lights.lights[i].color * lights.lights[i].intensity * 0.1; } return vec4<f32>(glow, 1.0); }
""")
flat_mat = Material.custom(flat)import FragmentColor
let flat = try Shader(""" struct Camera { view_proj: mat4x4<f32>, position: vec3<f32> } struct Light { kind: u32, intensity: f32, range: f32, inner_cone_cos: f32, position: vec3<f32>, outer_cone_cos: f32, direction: vec3<f32>, color: vec3<f32> } struct LightGrid { view_proj: mat4x4<f32>, depth_plane: vec4<f32>, size: vec3<u32>, slicing: u32, slice_scale: f32, slice_bias: f32, reach: f32 } struct Lights { count: u32, global_count: u32, promoted_count: u32, ambient: vec3<f32>, grid: LightGrid, lights: array<Light> } @group(0) @binding(0) var<uniform> camera: Camera; @group(0) @binding(1) var<storage, read> lights: Lights;
@vertex fn vs_main( @location(0) p: vec3<f32>, @location(3) model_0: vec4<f32>, @location(4) model_1: vec4<f32>, @location(5) model_2: vec4<f32>, @location(6) model_3: vec4<f32>, ) -> @builtin(position) vec4<f32> { let model = mat4x4<f32>(model_0, model_1, model_2, model_3); return camera.view_proj * model * vec4<f32>(p, 1.0); } @fragment fn fs_main() -> @location(0) vec4<f32> { var glow = lights.ambient; for (var i = 0u; i < lights.count; i++) { glow += lights.lights[i].color * lights.lights[i].intensity * 0.1; } return vec4<f32>(glow, 1.0); }
""")
let flat_mat = Material.custom(flat)import org.fragmentcolor.*
val flat = Shader(""" struct Camera { view_proj: mat4x4<f32>, position: vec3<f32> } struct Light { kind: u32, intensity: f32, range: f32, inner_cone_cos: f32, position: vec3<f32>, outer_cone_cos: f32, direction: vec3<f32>, color: vec3<f32> } struct LightGrid { view_proj: mat4x4<f32>, depth_plane: vec4<f32>, size: vec3<u32>, slicing: u32, slice_scale: f32, slice_bias: f32, reach: f32 } struct Lights { count: u32, global_count: u32, promoted_count: u32, ambient: vec3<f32>, grid: LightGrid, lights: array<Light> } @group(0) @binding(0) var<uniform> camera: Camera; @group(0) @binding(1) var<storage, read> lights: Lights;
@vertex fn vs_main( @location(0) p: vec3<f32>, @location(3) model_0: vec4<f32>, @location(4) model_1: vec4<f32>, @location(5) model_2: vec4<f32>, @location(6) model_3: vec4<f32>, ) -> @builtin(position) vec4<f32> { let model = mat4x4<f32>(model_0, model_1, model_2, model_3); return camera.view_proj * model * vec4<f32>(p, 1.0); } @fragment fn fs_main() -> @location(0) vec4<f32> { var glow = lights.ambient; for (var i = 0u; i < lights.count; i++) { glow += lights.lights[i].color * lights.lights[i].intensity * 0.1; } return vec4<f32>(glow, 1.0); }
""")
val flat_mat = Material.custom(flat)Material::double_sided
Section titled “Material::double_sided”Toggle backface culling for this material’s pipeline. When true, the renderer skips
its default back-face cull and draws both faces of every triangle. When false
(the default), back faces are culled, the standard CCW-winding-is-front convention.
Mirrors glTF 2.0’s doubleSided. Reach for it on thin geometry that legitimately reads
from both sides: a single-quad leaf card, a cloth banner, decals applied to non-closed
meshes, or any authored asset that comes out of a tool that didn’t bother to mirror its
back faces. For closed solid geometry, leave it off; the culled back faces are a free
~50% fragment-shader saving on every draw.
Like alpha_mode, this is a pipeline-state flag and bakes into the WebGPU pipeline.
The renderer caches a separate pipeline per (shader, alpha_mode, double_sided) key,
so toggling it doesn’t fight the shader cache as long as you stay on a small set of
values.
Example
Section titled “Example”use fragmentcolor::{AlphaMode, Material, Renderer};
let renderer = Renderer::new();// Leaf cards: thin, single-quad geometry; needs both sides + alpha cut-out.let leaf = Material::pbr() .double_sided(true) .alpha_mode(AlphaMode::Mask) .alpha_cutoff(0.5)?;
// The default is single-sided, with back-face culling on.let solid_mesh = Material::pbr().double_sided(false);import { AlphaMode, Material, Renderer } from "fragmentcolor";
const renderer = new Renderer();// Leaf cards: thin, single-quad geometry; needs both sides + alpha cut-out.const leaf = Material.pbr().doubleSided(true).alphaMode(AlphaMode.Mask).alphaCutoff(0.5);
// The default is single-sided, with back-face culling on.const solid_mesh = Material.pbr().doubleSided(false);from fragmentcolor import AlphaMode, Material, Renderer
renderer = Renderer()# Leaf cards: thin, single-quad geometry; needs both sides + alpha cut-out.leaf = Material.pbr().double_sided(True).alpha_mode(AlphaMode.Mask).alpha_cutoff(0.5)
# The default is single-sided, with back-face culling on.solid_mesh = Material.pbr().double_sided(False)import FragmentColor
let renderer = Renderer()// Leaf cards: thin, single-quad geometry; needs both sides + alpha cut-out.let leaf = try Material.pbr().doubleSided(true).alphaMode(AlphaMode.mask).alphaCutoff(0.5)
// The default is single-sided, with back-face culling on.let solid_mesh = Material.pbr().doubleSided(false)import org.fragmentcolor.*
val renderer = Renderer()// Leaf cards: thin, single-quad geometry; needs both sides + alpha cut-out.val leaf = Material.pbr().doubleSided(true).alphaMode(AlphaMode.MASK).alphaCutoff(0.5f)
// The default is single-sided, with back-face culling on.val solid_mesh = Material.pbr().doubleSided(false)Material::emissive
Section titled “Material::emissive”Set the emissive factor (linear RGB): light the surface emits regardless of
incident illumination. Added on top of the PBR shading and clamped only by
the output format; for tonemapped pipelines use values in [0, 1], for HDR
you can go beyond.
Maps to the material.emissive uniform. Default is [0, 0, 0].
An item that is NaN or an infinity returns MaterialError::NotFinite,
which names the call and the item, and the material keeps the value it
had. The other languages also refuse an item past the 32-bit float range,
such as 1e39, with a message like Material.emissive: item 1 must be a finite number that fits a 32-bit float, got 1e39. JavaScript throws an
Error named InvalidInputError, Python raises InvalidInputError,
Swift throws FragmentColorError and Kotlin throws
FragmentColorException.
Example
Section titled “Example”use fragmentcolor::{Material, Renderer};
let renderer = Renderer::new();let lava = Material::pbr() .base_color([0.1, 0.05, 0.0, 1.0])? .emissive([1.5, 0.4, 0.1])?;import { Material, Renderer } from "fragmentcolor";
const renderer = new Renderer();const lava = Material.pbr().baseColor([0.1, 0.05, 0.0, 1.0]).emissive([1.5, 0.4, 0.1]);from fragmentcolor import Material, Renderer
renderer = Renderer()lava = Material.pbr().base_color([0.1, 0.05, 0.0, 1.0]).emissive([1.5, 0.4, 0.1])import FragmentColor
let renderer = Renderer()let lava = try Material.pbr().baseColor([0.1, 0.05, 0.0, 1.0]).emissive([1.5, 0.4, 0.1])import org.fragmentcolor.*
val renderer = Renderer()val lava = Material.pbr().baseColor(listOf(0.1f, 0.05f, 0.0f, 1.0f)).emissive(listOf(1.5f, 0.4f, 0.1f))Material::emissive_texture
Section titled “Material::emissive_texture”Bind an emissive map to the canonical emissive_map slot. The default PBR
shader samples it in fs_main and multiplies by the factor: per-fragment
emission is material.emissive * textureSample(emissive_map, pbr_sampler, uv).rgb,
where uv is slot_uv(material.uv[4], in.uv0, in.uv1), the slot’s own UV
set through its own transform.
Unset, this slot resolves to a 1×1 white default so the multiplied
emission falls back to the material.emissive factor as-is.
Takes the inputs Material::base_color_texture takes, spelled as each language’s create_texture spells them: a Texture, or encoded bytes, raw pixels with their size, bytes with a format or with every option, a path or a URL, alone or with a format or every option, or a Mipmap, alone or with options. The Material keeps a source as a map, and each Renderer uploads a copy of its own when it loads the scene. base_color_texture tells how a map loads, what it holds in memory and how it fails.
The setter refuses options beside a Texture, and an input that holds no
data, such as an empty byte list, with MaterialError::Texture. JavaScript throws it as an Error
named InvalidInputError, and Python raises InvalidInputError. A
Material::custom shader that declares emissive_map as something other
than a texture refuses the call with MaterialError::Shader, which
JavaScript and Python raise as MaterialError. Swift throws
FragmentColorError and Kotlin throws FragmentColorException. A refused
call leaves the slot as it was, and a shader that doesn’t declare
emissive_map skips the call with a log warning.
Example
Section titled “Example”use fragmentcolor::Material;
// Raw pixels with their size upload when the scene loads.let glow_bytes: Vec<u8> = vec![ 255, 0, 0, 255, 255, 0, 0, 255, 255, 0, 0, 255, 255, 0, 0, 255,];let mat = Material::pbr() .emissive([0.8, 0.0, 0.0])? .emissive_texture((glow_bytes, [2, 2]))?;import { Material } from "fragmentcolor";
// Raw pixels with their size upload when the scene loads.const glow_bytes = [ 255, 0, 0, 255, 255, 0, 0, 255, 255, 0, 0, 255, 255, 0, 0, 255, ];const mat = Material.pbr().emissive([0.8, 0.0, 0.0]).emissiveTexture(glow_bytes, [2, 2]);from fragmentcolor import Material
# Raw pixels with their size upload when the scene loads.glow_bytes = [ 255, 0, 0, 255, 255, 0, 0, 255, 255, 0, 0, 255, 255, 0, 0, 255,]mat = Material.pbr().emissive([0.8, 0.0, 0.0]).emissive_texture(glow_bytes, size=[2, 2])import FragmentColor
// Raw pixels with their size upload when the scene loads.let glow_bytes = [ 255, 0, 0, 255, 255, 0, 0, 255, 255, 0, 0, 255, 255, 0, 0, 255,]let mat = try Material.pbr().emissive([0.8, 0.0, 0.0]).emissiveTexture(glow_bytes, [2, 2])import org.fragmentcolor.*
// Raw pixels with their size upload when the scene loads.val glow_bytes = listOf(255, 0, 0, 255, 255, 0, 0, 255, 255, 0, 0, 255, 255, 0, 0, 255)val mat = Material.pbr().emissive(listOf(0.8f, 0.0f, 0.0f)).emissiveTexture(glow_bytes, listOf(2u, 2u))Material::metallic
Section titled “Material::metallic”Set the metallic factor in [0, 1]. 0 is a pure dielectric (uses the
default F0 of 0.04), 1 is a pure metal (F0 = base_color). Values in
between linearly interpolate.
Maps to the material.metallic uniform. Default is 0.0 (dielectric);
Material::pbr deviates from the glTF spec’s 1.0 default here so the
out-of-the-box surface reads as a clean dielectric rather than dark gunmetal
under the factor-driven defaults.
NaN or an infinity returns MaterialError::NotFinite, which names the
call, and the material keeps the value it had. The other languages also
refuse a number past the 32-bit float range, such as 1e39, with a
message like Material.metallic: value must be a finite number that fits a 32-bit float, got 1e39. JavaScript throws an Error named
InvalidInputError, Python raises InvalidInputError, Swift throws
FragmentColorError and Kotlin throws FragmentColorException.
Example
Section titled “Example”use fragmentcolor::Material;
let chrome = Material::pbr().metallic(1.0)?.roughness(0.05)?;import { Material } from "fragmentcolor";
const chrome = Material.pbr().metallic(1.0).roughness(0.05);from fragmentcolor import Material
chrome = Material.pbr().metallic(1.0).roughness(0.05)import FragmentColor
let chrome = try Material.pbr().metallic(1.0).roughness(0.05)import org.fragmentcolor.*
val chrome = Material.pbr().metallic(1.0f).roughness(0.05f)Material::metallic_roughness_texture
Section titled “Material::metallic_roughness_texture”Bind a texture to the canonical metallic_roughness_map slot. Following
glTF 2.0, the green channel encodes per-fragment roughness, the blue channel
encodes metallic. Both are multiplied by their respective factors at sample
time inside the default PBR shader.
Unset, this slot resolves to a 1×1 default with (R=0, G=1, B=1, A=1) so
the factor multiplication passes both material.metallic and
material.roughness through unchanged.
Takes the inputs Material::base_color_texture takes, spelled as each language’s create_texture spells them: a Texture, or encoded bytes, raw pixels with their size, bytes with a format or with every option, a path or a URL, alone or with a format or every option, or a Mipmap, alone or with options. The Material keeps a source as a map, and each Renderer uploads a copy of its own when it loads the scene. base_color_texture tells how a map loads, what it holds in memory and how it fails.
The setter refuses options beside a Texture, and an input that holds no
data, such as an empty byte list, with MaterialError::Texture. JavaScript throws it as an Error
named InvalidInputError, and Python raises InvalidInputError. A
Material::custom shader that declares metallic_roughness_map as
something other than a texture refuses the call with
MaterialError::Shader, which JavaScript and Python raise as
MaterialError. Swift throws FragmentColorError and Kotlin throws
FragmentColorException. A refused call leaves the slot as it was, and a
shader that doesn’t declare metallic_roughness_map skips the call with a
log warning.
Example
Section titled “Example”use fragmentcolor::Material;
// Raw pixels with their size upload when the scene loads.let mr_map_bytes: Vec<u8> = vec![ 0, 200, 50, 255, 0, 240, 80, 255, 0, 180, 30, 255, 0, 220, 60, 255,];let mat = Material::pbr().metallic_roughness_texture((mr_map_bytes, [2, 2]))?;import { Material } from "fragmentcolor";
// Raw pixels with their size upload when the scene loads.const mr_map_bytes = [ 0, 200, 50, 255, 0, 240, 80, 255, 0, 180, 30, 255, 0, 220, 60, 255, ];const mat = Material.pbr().metallicRoughnessTexture(mr_map_bytes, [2, 2]);from fragmentcolor import Material
# Raw pixels with their size upload when the scene loads.mr_map_bytes = [ 0, 200, 50, 255, 0, 240, 80, 255, 0, 180, 30, 255, 0, 220, 60, 255,]mat = Material.pbr().metallic_roughness_texture(mr_map_bytes, size=[2, 2])import FragmentColor
// Raw pixels with their size upload when the scene loads.let mr_map_bytes = [ 0, 200, 50, 255, 0, 240, 80, 255, 0, 180, 30, 255, 0, 220, 60, 255,]let mat = try Material.pbr().metallicRoughnessTexture(mr_map_bytes, [2, 2])import org.fragmentcolor.*
// Raw pixels with their size upload when the scene loads.val mr_map_bytes = listOf(0, 200, 50, 255, 0, 240, 80, 255, 0, 180, 30, 255, 0, 220, 60, 255)val mat = Material.pbr().metallicRoughnessTexture(mr_map_bytes, listOf(2u, 2u))Material::normal_scale
Section titled “Material::normal_scale”Scales the per-fragment normal perturbation read from a tangent-space normal
map, mirroring glTF 2.0’s normalTextureInfo.scale. Higher values exaggerate
the bumps; values below 1 soften them.
Maps to the material.normal_scale uniform. Default is 1.0. The default
PBR shader samples normal_map, decodes the bytes, and scales the XY
perturbation by this value before combining with the world-space normal.
NaN or an infinity returns MaterialError::NotFinite, which names the
call, and the material keeps the value it had. The other languages also
refuse a number past the 32-bit float range, such as 1e39, with a
message like Material.normalScale: value must be a finite number that fits a 32-bit float, got 1e39. JavaScript throws an Error named
InvalidInputError, Python raises InvalidInputError, Swift throws
FragmentColorError and Kotlin throws FragmentColorException.
Example
Section titled “Example”use fragmentcolor::Material;
let detailed = Material::pbr().normal_scale(1.5)?;import { Material } from "fragmentcolor";
const detailed = Material.pbr().normalScale(1.5);from fragmentcolor import Material
detailed = Material.pbr().normal_scale(1.5)import FragmentColor
let detailed = try Material.pbr().normalScale(1.5)import org.fragmentcolor.*
val detailed = Material.pbr().normalScale(1.5f)Material::normal_texture
Section titled “Material::normal_texture”Bind a tangent-space normal map to the canonical normal_map slot. The
default PBR shader samples the map in fs_main, decodes the stored
[0, 1] bytes into [-1, 1] floats, scales the XY components by
material.normal_scale, and rotates the perturbed normal from tangent
space into world space using the per-vertex tangent (the glTF tangent.w
handedness flag is preserved).
Unset, this slot resolves to a 1×1 flat tangent-space default
(128, 128, 255, 255) so the decoded normal is (0, 0, 1) and the world
normal passes through unchanged.
Takes the inputs Material::base_color_texture takes, spelled as each language’s create_texture spells them: a Texture, or encoded bytes, raw pixels with their size, bytes with a format or with every option, a path or a URL, alone or with a format or every option, or a Mipmap, alone or with options. The Material keeps a source as a map, and each Renderer uploads a copy of its own when it loads the scene. base_color_texture tells how a map loads, what it holds in memory and how it fails.
The setter refuses options beside a Texture, and an input that holds no
data, such as an empty byte list, with MaterialError::Texture. JavaScript throws it as an Error
named InvalidInputError, and Python raises InvalidInputError. A
Material::custom shader that declares normal_map as something other than
a texture refuses the call with MaterialError::Shader, which JavaScript
and Python raise as MaterialError. Swift throws FragmentColorError and
Kotlin throws FragmentColorException. A refused call leaves the slot as it
was, and a shader that doesn’t declare normal_map skips the call with a
log warning.
Example
Section titled “Example”use fragmentcolor::Material;
// Raw pixels with their size upload when the scene loads.let normal_map_bytes: Vec<u8> = vec![ 128, 128, 255, 255, 128, 128, 255, 255, 128, 128, 255, 255, 128, 128, 255, 255,];let mat = Material::pbr() .normal_texture((normal_map_bytes, [2, 2]))? .normal_scale(1.2)?;import { Material } from "fragmentcolor";
// Raw pixels with their size upload when the scene loads.const normal_map_bytes = [ 128, 128, 255, 255, 128, 128, 255, 255, 128, 128, 255, 255, 128, 128, 255, 255, ];const mat = Material.pbr().normalTexture(normal_map_bytes, [2, 2]).normalScale(1.2);from fragmentcolor import Material
# Raw pixels with their size upload when the scene loads.normal_map_bytes = [ 128, 128, 255, 255, 128, 128, 255, 255, 128, 128, 255, 255, 128, 128, 255, 255,]mat = Material.pbr().normal_texture(normal_map_bytes, size=[2, 2]).normal_scale(1.2)import FragmentColor
// Raw pixels with their size upload when the scene loads.let normal_map_bytes = [ 128, 128, 255, 255, 128, 128, 255, 255, 128, 128, 255, 255, 128, 128, 255, 255,]let mat = try Material.pbr().normalTexture(normal_map_bytes, [2, 2]).normalScale(1.2)import org.fragmentcolor.*
// Raw pixels with their size upload when the scene loads.val normal_map_bytes = listOf(128, 128, 255, 255, 128, 128, 255, 255, 128, 128, 255, 255, 128, 128, 255, 255)val mat = Material.pbr().normalTexture(normal_map_bytes, listOf(2u, 2u)).normalScale(1.2f)Material::occlusion_strength
Section titled “Material::occlusion_strength”Blends the per-fragment ambient-occlusion factor (read from an occlusion
map) toward 1.0, matching glTF 2.0’s occlusionTextureInfo.strength.
1.0 uses the map’s value as-is; 0.0 ignores the map entirely.
Maps to the material.occlusion_strength uniform. Default is 1.0. The
default PBR shader samples occlusion_map.r and mix(1.0, sampled, strength)s
the result into the diffuse term.
NaN or an infinity returns MaterialError::NotFinite, which names the
call, and the material keeps the value it had. The other languages also
refuse a number past the 32-bit float range, such as 1e39, with a
message like Material.occlusionStrength: value must be a finite number that fits a 32-bit float, got 1e39. JavaScript throws an Error named
InvalidInputError, Python raises InvalidInputError, Swift throws
FragmentColorError and Kotlin throws FragmentColorException.
Example
Section titled “Example”use fragmentcolor::Material;
let crevices = Material::pbr().occlusion_strength(0.8)?;import { Material } from "fragmentcolor";
const crevices = Material.pbr().occlusionStrength(0.8);from fragmentcolor import Material
crevices = Material.pbr().occlusion_strength(0.8)import FragmentColor
let crevices = try Material.pbr().occlusionStrength(0.8)import org.fragmentcolor.*
val crevices = Material.pbr().occlusionStrength(0.8f)Material::occlusion_texture
Section titled “Material::occlusion_texture”Bind an ambient-occlusion map to the canonical occlusion_map slot.
Following glTF 2.0, only the red channel is read; the sampled value is
blended toward 1.0 by 1 - material.occlusion_strength inside the
default PBR shader, then multiplied into the diffuse term.
Unset, this slot resolves to a 1×1 white default so the multiplied
occlusion factor is 1.0 and no darkening is applied.
Takes the inputs Material::base_color_texture takes, spelled as each language’s create_texture spells them: a Texture, or encoded bytes, raw pixels with their size, bytes with a format or with every option, a path or a URL, alone or with a format or every option, or a Mipmap, alone or with options. The Material keeps a source as a map, and each Renderer uploads a copy of its own when it loads the scene. base_color_texture tells how a map loads, what it holds in memory and how it fails.
The setter refuses options beside a Texture, and an input that holds no
data, such as an empty byte list, with MaterialError::Texture. JavaScript throws it as an Error
named InvalidInputError, and Python raises InvalidInputError. A
Material::custom shader that declares occlusion_map as something other
than a texture refuses the call with MaterialError::Shader, which
JavaScript and Python raise as MaterialError. Swift throws
FragmentColorError and Kotlin throws FragmentColorException. A refused
call leaves the slot as it was, and a shader that doesn’t declare
occlusion_map skips the call with a log warning.
Example
Section titled “Example”use fragmentcolor::Material;
// Raw pixels with their size upload when the scene loads.let ao_bytes: Vec<u8> = vec![ 220, 0, 0, 255, 180, 0, 0, 255, 200, 0, 0, 255, 160, 0, 0, 255,];let mat = Material::pbr().occlusion_texture((ao_bytes, [2, 2]))?;import { Material } from "fragmentcolor";
// Raw pixels with their size upload when the scene loads.const ao_bytes = [ 220, 0, 0, 255, 180, 0, 0, 255, 200, 0, 0, 255, 160, 0, 0, 255, ];const mat = Material.pbr().occlusionTexture(ao_bytes, [2, 2]);from fragmentcolor import Material
# Raw pixels with their size upload when the scene loads.ao_bytes = [ 220, 0, 0, 255, 180, 0, 0, 255, 200, 0, 0, 255, 160, 0, 0, 255,]mat = Material.pbr().occlusion_texture(ao_bytes, size=[2, 2])import FragmentColor
// Raw pixels with their size upload when the scene loads.let ao_bytes = [ 220, 0, 0, 255, 180, 0, 0, 255, 200, 0, 0, 255, 160, 0, 0, 255,]let mat = try Material.pbr().occlusionTexture(ao_bytes, [2, 2])import org.fragmentcolor.*
// Raw pixels with their size upload when the scene loads.val ao_bytes = listOf(220, 0, 0, 255, 180, 0, 0, 255, 200, 0, 0, 255, 160, 0, 0, 255)val mat = Material.pbr().occlusionTexture(ao_bytes, listOf(2u, 2u))Material::pbr
Section titled “Material::pbr”Construct a Material whose shader is FragmentColor’s built-in
physically-based-rendering default. The bundle ships pre-configured with
glTF 2.0 PBR-MR defaults, lightly tweaked so a freshly-constructed Material
renders as a clean white surface under the default light rather than dark
gunmetal.
The five glTF texture slots (base_color_map, metallic_roughness_map,
normal_map, occlusion_map, emissive_map) start unbound; the renderer
resolves each one to a sensible 1×1 default from its lazy texture cache the
first time a Pass renders the Material. That way the underlying shader has
every binding it needs and the per-factor render is correct even when no map
is attached. Call the texture setters to override any of them.
The shader uses:
- Cook-Torrance specular with GGX normal distribution, Smith geometry, and Schlick Fresnel.
- Lambertian diffuse with energy conservation against the specular Fresnel and metalness.
- Clustered lights: as many lights as the device allows, in the
read-only storage roots
lightsandlight_gridthat the renderer fills. Each fragment reads only the lights whose range reaches its cluster, plus every light without a range. See Light for the cost of each kind and the cap on each device, andMaterial::customfor the layout of the roots. - One camera (uniform
camera), and the per-Model transform via the instance-attribute stream. - glTF 2.0 PBR-MR texture sampling: five sampled maps (
base_color_map,metallic_roughness_map,normal_map,occlusion_map,emissive_map) combined with their matching factors per the spec. - Output for the target: lighting is computed in linear light. On the
Rgba8UnormandBgra8Unormtargets FragmentColor creates, which hold colors encoded for display, the shader encodes it as sRGB. An sRGB target encodes on write and a float target keeps linear light for the passes after it, so both get linear light. The renderer picks per pipeline from the target’s format, through the shader’soverride ENCODE_SRGB: bool. A custom shader that declares the same override gets the same value.
The shader reads these vertex inputs from the mesh:
@location(0) position : vec3<f32>, a 3D position fromVertex::new([...])orVertex::pbr([...]).@location(1) normal : vec3<f32>, set as.set(Vertex::NORMAL, ...).@location(2) uv0 : vec2<f32>, set as.set(Vertex::UV0, ...).@location(7) color0 : vec4<f32>, set as.set(Vertex::COLOR0, ...), which tints the base color.@location(8) uv1 : vec2<f32>, set as.set(Vertex::UV1, ...), which the texture slots on UV set 1 sample.@location(9) tangent : vec4<f32>, set as.set(Vertex::TANGENT, ...), with the bitangent sign inw.
Each input finds its attribute by name, then by the location
Vertex::set gave the
attribute. A vertex that sets them under these names can set them in any
order. Locations 3 to 6 hold model_0 to model_3, the columns of the
Model’s transform, which come from the Model rather than the mesh.
The shader has no default for any mesh input. An attribute under another name
stands in for one when it sits at the input’s location and fits its type, and
a Model fails to attach when an input finds no attribute by either rule. The
error names the input, or the attribute at the input’s location when that
attribute has the wrong type. Vertex::pbr sets every input after the
position to a neutral value. Use Material::custom(...) to bring your own
vertex layout.
Defaults (post-construction)
Section titled “Defaults (post-construction)”| key | value |
|---|---|
material.base_color |
[1, 1, 1, 1] |
material.metallic |
0.0 |
material.roughness |
1.0 |
material.normal_scale |
1.0 |
material.occlusion_strength |
1.0 |
material.emissive |
[0, 0, 0] |
material.alpha_cutoff |
0.5 |
base_color_map |
1×1 white |
metallic_roughness_map |
1×1 (R=0, G=1, B=1) |
normal_map |
1×1 flat (128,128,255) |
occlusion_map |
1×1 white |
emissive_map |
1×1 white |
camera.view_proj |
identity 4×4 |
camera.position |
[0, 0, 0] |
lights.ambient |
[0.03, 0.03, 0.03] |
| placeholder light | white, directional, pointing down [0, -1, 0] |
The placeholder light lights a fresh Material until the first Light reaches its shader, and returns once no Light does.
The camera and lights are the user’s domain, not the Material’s. Pass them
to Pass::add. The typed
Camera handle seeds the
camera.* uniforms and propagates later updates into the Material’s shader,
and the renderer packs every Light that reaches the shader at each render.
material.shader().set(...) still sets camera.* and lights.ambient
directly. The lights themselves have no keys: set and get on
lights.count or lights.lights[i] return ShaderError::UniformNotFound.
Example
Section titled “Example”use fragmentcolor::Material;
let bronze = Material::pbr() .base_color([0.8, 0.5, 0.2, 1.0])? .metallic(1.0)? .roughness(0.3)?;import { Material } from "fragmentcolor";
const bronze = Material.pbr().baseColor([0.8, 0.5, 0.2, 1.0]).metallic(1.0).roughness(0.3);from fragmentcolor import Material
bronze = Material.pbr().base_color([0.8, 0.5, 0.2, 1.0]).metallic(1.0).roughness(0.3)import FragmentColor
let bronze = try Material.pbr().baseColor([0.8, 0.5, 0.2, 1.0]).metallic(1.0).roughness(0.3)import org.fragmentcolor.*
val bronze = Material.pbr().baseColor(listOf(0.8f, 0.5f, 0.2f, 1.0f)).metallic(1.0f).roughness(0.3f)Material::roughness
Section titled “Material::roughness”Set the surface roughness in [0, 1]. 0 is a perfect mirror; 1 is a
fully matte surface. The PBR shader uses the squared form (alpha = r²) for
the GGX normal distribution, which is the GGX/Trowbridge-Reitz convention
shared with glTF 2.0.
Maps to the material.roughness uniform. Default is 1.0.
NaN or an infinity returns MaterialError::NotFinite, which names the
call, and the material keeps the value it had. The other languages also
refuse a number past the 32-bit float range, such as 1e39, with a
message like Material.roughness: value must be a finite number that fits a 32-bit float, got 1e39. JavaScript throws an Error named
InvalidInputError, Python raises InvalidInputError, Swift throws
FragmentColorError and Kotlin throws FragmentColorException.
Example
Section titled “Example”use fragmentcolor::{Material, Renderer};
let renderer = Renderer::new();let satin = Material::pbr().roughness(0.35)?;import { Material, Renderer } from "fragmentcolor";
const renderer = new Renderer();const satin = Material.pbr().roughness(0.35);from fragmentcolor import Material, Renderer
renderer = Renderer()satin = Material.pbr().roughness(0.35)import FragmentColor
let renderer = Renderer()let satin = try Material.pbr().roughness(0.35)import org.fragmentcolor.*
val renderer = Renderer()val satin = Material.pbr().roughness(0.35f)Material::shader
Section titled “Material::shader”Borrow the underlying Shader to drop down to direct uniform manipulation.
This is the escape hatch when the Material’s typed setters don’t cover what you need
(custom uniforms beyond the glTF PBR field set, raw texture binds, anything
the Camera and
Light helpers don’t speak to).
The returned reference is the same Shader the Material is built around, so
changes propagate immediately to every Model that uses this Material. If you
want a Material variant with different state, build a fresh
Material::pbr().<setters> rather than cloning. Material
clones share their Shader handle (Arc-clone) so mutations are visible across
all clones.
For camera + light state, prefer absorbing the typed
Camera and
Light handles into the
Pass that’s about to render this
Material rather than calling shader().set(...) by hand. The typed
handles propagate updates live across every absorbed shader.
Example
Section titled “Example”use fragmentcolor::Material;
// Direct uniform access for a custom field that isn't covered by the// Material setters or by Camera / Light.let material = Material::pbr();material.shader().set("material.alpha_cutoff", 0.25)?;import { Material } from "fragmentcolor";
// Direct uniform access for a custom field that isn't covered by the// Material setters or by Camera / Light.const material = Material.pbr();material.shader().set("material.alpha_cutoff", 0.25);from fragmentcolor import Material
# Direct uniform access for a custom field that isn't covered by the# Material setters or by Camera / Light.material = Material.pbr()material.shader().set("material.alpha_cutoff", 0.25)import FragmentColor
// Direct uniform access for a custom field that isn't covered by the// Material setters or by Camera / Light.let material = Material.pbr()try material.shader().set("material.alpha_cutoff", 0.25)import org.fragmentcolor.*
// Direct uniform access for a custom field that isn't covered by the// Material setters or by Camera / Light.val material = Material.pbr()material.shader().set("material.alpha_cutoff", 0.25f)Material::texture_transform
Section titled “Material::texture_transform”Give one texture slot its own UV transform, the one glTF’s
KHR_texture_transform
describes. The slot’s UV is scaled first, then rotated, then offset:
scalemultiplies the UV ([1, 1]keeps it)rotationturns the scaled UV around the origin, in radians. A positive angle turns the UVs counter-clockwise in texture space, wherevpoints down, so the image itself turns clockwiseoffsetmoves the result, in fractions of the texture ([0, 0]keeps it)
Every slot starts with the identity transform. The transform applies to
the UV set that
texture_uv
picks for the slot.
uv_transform
sets one transform on all five slots, and a texture_transform after it
replaces the transform of its slot alone.
Whether a UV past 0 to 1 repeats the texture depends on the sampler. The
PBR shader samples all five slots with one sampler, which takes the
options of the first texture the material sets, in TextureSlot order:
base color, metallic-roughness, normal, occlusion, then emissive. A slot
left at its 1×1 default doesn’t count. So a material with only an
occlusion map tiles it with the occlusion map’s own options, and one with
a clamped base color texture clamps a tiled normal map too.
A number that is NaN or an infinity returns MaterialError::NotFinite,
which names the part, such as Material::texture_transform: rotation must be finite, got NaN, and leaves the slot as it was: the setter checks the
offset, the scale and the rotation before it writes any of them. The other
languages also refuse a number past the 32-bit float range, such as
1e39, with a message like Material.textureTransform: rotation must be a finite number that fits a 32-bit float, got 1e39. JavaScript throws an
Error named InvalidInputError, Python raises InvalidInputError,
Swift throws FragmentColorError and Kotlin throws
FragmentColorException.
Example
Section titled “Example”use fragmentcolor::{Material, TextureSlot};
// Every map spans the surface twice, and the normal map eight times.let tiles = Material::pbr() .uv_transform([0.0, 0.0], [2.0, 2.0], 0.0)? .texture_transform(TextureSlot::Normal, [0.0, 0.0], [8.0, 8.0], 0.0)?;import { Material, TextureSlot } from "fragmentcolor";
// Every map spans the surface twice, and the normal map eight times.const tiles = Material.pbr().uvTransform([0.0, 0.0], [2.0, 2.0], 0.0).textureTransform(TextureSlot.Normal, [0.0, 0.0], [8.0, 8.0], 0.0);from fragmentcolor import Material, TextureSlot
# Every map spans the surface twice, and the normal map eight times.tiles = Material.pbr().uv_transform([0.0, 0.0], [2.0, 2.0], 0.0).texture_transform(TextureSlot.Normal, [0.0, 0.0], [8.0, 8.0], 0.0)import FragmentColor
// Every map spans the surface twice, and the normal map eight times.let tiles = try Material.pbr().uvTransform([0.0, 0.0], [2.0, 2.0], 0.0).textureTransform(TextureSlot.normal, [0.0, 0.0], [8.0, 8.0], 0.0)import org.fragmentcolor.*
// Every map spans the surface twice, and the normal map eight times.val tiles = Material.pbr().uvTransform(listOf(0.0f, 0.0f), listOf(2.0f, 2.0f), 0.0f).textureTransform(TextureSlot.NORMAL, listOf(0.0f, 0.0f), listOf(8.0f, 8.0f), 0.0f)Material::texture_uv
Section titled “Material::texture_uv”Pick the vertex UV set one texture slot samples: 0 reads Vertex::UV0
and 1 reads Vertex::UV1. glTF calls this choice texCoord. Baked
lighting and occlusion often live on a second UV layout, apart from the
tiled UVs of the color maps. Every slot starts on set 0.
A set other than 0 or 1 returns MaterialError::UvSet and keeps the
slot’s set. JavaScript throws an Error named MaterialError, Python raises MaterialError, a
FragmentColorError that is also a ValueError, Swift throws
FragmentColorError, and Kotlin throws FragmentColorException. The set
is a count like any other: JavaScript throws for a fraction or a negative
number, and Python takes an int, raising TypeError for a float and
InvalidInputError for an int below 0 or past 2**32 - 1.
The PBR shader reads UV1 from every vertex, and a mesh whose vertices
lack it fails to attach with an error that names uv1. Vertex::pbr
seeds UV1 at [0, 0], so a slot on set 1 reads that one point until
the mesh sets its own. Scene::load gives a primitive without
TEXCOORD_1 its TEXCOORD_0 values as UV1, so set 1 reads the same UVs
as set 0 there.
The slot’s
texture_transform
applies to whichever set it reads.
Example
Section titled “Example”use fragmentcolor::{Material, Mesh, TextureSlot, Vertex};
let mesh = Mesh::new();mesh.add_vertices([ Vertex::pbr([0.0, 0.5, 0.0]) .set(Vertex::UV0, [0.5, 1.0]) .set(Vertex::UV1, [0.25, 0.75]), Vertex::pbr([-0.5, -0.5, 0.0]) .set(Vertex::UV0, [0.0, 0.0]) .set(Vertex::UV1, [0.0, 0.5]), Vertex::pbr([0.5, -0.5, 0.0]) .set(Vertex::UV0, [1.0, 0.0]) .set(Vertex::UV1, [0.5, 0.5]),]);
// The occlusion map follows the second UV layout.let material = Material::pbr().texture_uv(TextureSlot::Occlusion, 1)?;import { Material, Mesh, TextureSlot, Vertex } from "fragmentcolor";
const mesh = new Mesh();mesh.addVertices([ Vertex.pbr([0.0, 0.5, 0.0]) .set(Vertex.UV0, [0.5, 1.0]) .set(Vertex.UV1, [0.25, 0.75]), Vertex.pbr([-0.5, -0.5, 0.0]) .set(Vertex.UV0, [0.0, 0.0]) .set(Vertex.UV1, [0.0, 0.5]), Vertex.pbr([0.5, -0.5, 0.0]) .set(Vertex.UV0, [1.0, 0.0]) .set(Vertex.UV1, [0.5, 0.5]), ]);
// The occlusion map follows the second UV layout.const material = Material.pbr().textureUv(TextureSlot.Occlusion, 1);from fragmentcolor import Material, Mesh, TextureSlot, Vertex
mesh = Mesh()mesh.add_vertices([ Vertex.pbr([0.0, 0.5, 0.0]).set(Vertex.UV0, [0.5, 1.0]).set(Vertex.UV1, [0.25, 0.75]), Vertex.pbr([-0.5, -0.5, 0.0]).set(Vertex.UV0, [0.0, 0.0]).set(Vertex.UV1, [0.0, 0.5]), Vertex.pbr([0.5, -0.5, 0.0]).set(Vertex.UV0, [1.0, 0.0]).set(Vertex.UV1, [0.5, 0.5]),])
# The occlusion map follows the second UV layout.material = Material.pbr().texture_uv(TextureSlot.Occlusion, 1)import FragmentColor
let mesh = Mesh()mesh.addVertices([ try Vertex.pbr([0.0, 0.5, 0.0]).set(Vertex.UV0, [0.5, 1.0]).set(Vertex.UV1, [0.25, 0.75]), try Vertex.pbr([-0.5, -0.5, 0.0]).set(Vertex.UV0, [0.0, 0.0]).set(Vertex.UV1, [0.0, 0.5]), try Vertex.pbr([0.5, -0.5, 0.0]).set(Vertex.UV0, [1.0, 0.0]).set(Vertex.UV1, [0.5, 0.5]),])
// The occlusion map follows the second UV layout.let material = try Material.pbr().textureUv(TextureSlot.occlusion, 1)import org.fragmentcolor.*
val mesh = Mesh()mesh.addVertices(listOf(Vertex.pbr(listOf(0.0f, 0.5f, 0.0f)).set(Vertex.UV0, listOf(0.5f, 1.0f)).set(Vertex.UV1, listOf(0.25f, 0.75f)), Vertex.pbr(listOf(-0.5f, -0.5f, 0.0f)).set(Vertex.UV0, listOf(0.0f, 0.0f)).set(Vertex.UV1, listOf(0.0f, 0.5f)), Vertex.pbr(listOf(0.5f, -0.5f, 0.0f)).set(Vertex.UV0, listOf(1.0f, 0.0f)).set(Vertex.UV1, listOf(0.5f, 0.5f))))
// The occlusion map follows the second UV layout.val material = Material.pbr().textureUv(TextureSlot.OCCLUSION, 1u)Material::uv_transform
Section titled “Material::uv_transform”Set one UV transform on all five texture slots, the transform glTF’s
KHR_texture_transform
describes. Each slot’s UV is scaled first, then rotated, then offset:
scalemultiplies the UV ([1, 1]keeps it)rotationturns the scaled UV around the origin, in radians. A positive angle turns the UVs counter-clockwise in texture space, wherevpoints down, so the image itself turns clockwiseoffsetmoves the result, in fractions of the texture ([0, 0]keeps it)
Every slot starts with the identity transform: scale [1, 1], rotation
0 and offset [0, 0].
texture_transform
sets the transform of one slot, so a call after uv_transform replaces
that slot’s transform and keeps the other four. Each slot applies its
transform to the UV set that
texture_uv
picks for it.
A number that is NaN or an infinity returns MaterialError::NotFinite,
which names the part, such as Material::uv_transform: rotation must be finite, got NaN, and leaves every slot as it was: the setter checks the
offset, the scale and the rotation before it writes any of them. The other
languages also refuse a number past the 32-bit float range, such as
1e39, with a message like Material.uvTransform: rotation must be a finite number that fits a 32-bit float, got 1e39. JavaScript throws an
Error named InvalidInputError, Python raises InvalidInputError,
Swift throws FragmentColorError and Kotlin throws
FragmentColorException.
Example
Section titled “Example”use fragmentcolor::Material;
// Tile the texture 4× in both directions, rotate 45°, shift by half a tile.let brick = Material::pbr() .uv_transform([0.5, 0.0], [4.0, 4.0], 0.785)?; // 45° in radiansimport { Material } from "fragmentcolor";
// Tile the texture 4× in both directions, rotate 45°, shift by half a tile.const brick = Material.pbr().uvTransform([0.5, 0.0], [4.0, 4.0], 0.785); // 45° in radiansfrom fragmentcolor import Material
# Tile the texture 4× in both directions, rotate 45°, shift by half a tile.brick = Material.pbr().uv_transform([0.5, 0.0], [4.0, 4.0], 0.785) # 45° in radiansimport FragmentColor
// Tile the texture 4× in both directions, rotate 45°, shift by half a tile.let brick = try Material.pbr().uvTransform([0.5, 0.0], [4.0, 4.0], 0.785) // 45° in radiansimport org.fragmentcolor.*
// Tile the texture 4× in both directions, rotate 45°, shift by half a tile.val brick = Material.pbr().uvTransform(listOf(0.5f, 0.0f), listOf(4.0f, 4.0f), 0.785f) // 45° in radians