gltf#
glTF 2.0 import (.gltf, .glb): meshes, materials, textures, decoded images, nodes in f64, without a GPU -- crate root lib/gltf/lib.rs
gltf -- glTF 2.0 import (G5b; docs/GLTF.md): .gltf (JSON with external files or data URIs) and .glb, read
into a data model that needs no GPU: meshes of triangles with positions, normals and one uv set, materials
with the five textures of pbrMetallicRoughness, decoded images (PNG and JPEG through img_png / img_jpeg),
samplers, nodes with their world matrices in f64 and the instances a scene draws. lib/render3d puts a
Document on the GPU (render3d::gltf); a CAD or game tool can read the same without a device.
gltf::load(bytes, &mut |uri| Option<Vec<u8>>, &Limits) -> Result<Document> .glb or .gltf by its first
bytes; the closure reads the files a .gltf names (relative paths, decoded; never called for data URIs)
doc.instances(scene) -> Vec<InstanceRef> each node's mesh primitives with its world matrix
doc.lights_of(scene) -> Vec<LightRef> (G5c) each node's KHR_lights_punctual light with its world matrix
gltf::decompose(&matrix) -> Trs translation, rotation, scale (a mirror: x negative), shear
gltf::write_document(&doc) -> Result<Vec<u8>> (G7g) a Document as a .glb: meshes, materials by their factors,
nodes, scenes; load reads the same Document back (textures, images and lights: Unsupported)
Files are untrusted input: every index, offset, length and count is checked, sizes and counts are limited
(Limits), and a file that breaks a rule is an Err, never a panic. A file whose extensionsRequired names
anything but KHR_lights_punctual (Draco, meshopt, KTX2 / basisu, quantization, texture transforms, ...) is
Error::Unsupported; other extensions and what this model has no place for (animations, skins, cameras,
tangents, colours, further uv sets) are ignored. KHR_lights_punctual (G5c) is read as untrusted as the rest:
types, colours, intensities, ranges and cone angles checked, the lights limited. URIs that leave the file's
folder (absolute paths, "..", a scheme) are refused before the closure sees them.
gltf crate root#
enum Errorwhat went wrong; the text says whereJson(String)-- not JSON, or JSON that breaks the parser's limits (the byte offset in the text)Invalid(String)-- a rule of glTF or of a format inside it broken: an index or a range out of bounds, a wrong type, a cycleUnsupported(String)-- valid, but not supported here: a required extension, an image format, a URI schemeLimit(String)-- a Limits value exceededMissing(String)-- the closure had no file for this URI
type Result<T> = core::result::Result<T, Error>struct Limitsthe bounds a file must stay in (Limits::DEFAULT; raise them for large files you trust more)file_bytes: u64-- bytes of the .glb / .gltf and of each file it namesjson_bytes: usize-- bytes of the JSON part, and the values in it (objects, arrays, numbers, ...)json_values: usizebuffer_bytes: u64-- bytes of all buffers together, as given (a file two buffers name counts twice), and the zeros of accessors without a buffer view; the image files read count against it too (apart)vertices: u64-- vertices and indices of all primitives together, as the model holds them (flat normals split vertices)indices: u64nodes: usize-- nodes, and how deep they nestdepth: usizeinstances: u64-- instances of one scene (node x primitive)image_pixels: u64-- pixels of one image, bytes of all decoded images (4 per pixel)image_bytes: u64lights: usize-- (G5c) lights of KHR_lights_punctual
impl Limits
const DEFAULT: Limits = Limits { file_bytes: 1 << 30, json_bytes: 256 << 20, json ...struct Documentwhat a file holds, in the order of its arrays (indices of the file stay valid)version: String-- asset.version ("2.0") and asset.generatorgenerator: Stringmeshes: Vec<Mesh>materials: Vec<Material>textures: Vec<Texture>images: Vec<Image>nodes: Vec<Node>scenes: Vec<SceneDef>scene: Option<usize>-- the scene to show (the file'sscene; else the first; None: no scenes, instances() takes every root)lights: Vec<Light>-- (G5c) the lights of KHR_lights_punctual; nodes place themnotes: Vec<String>-- what was read but left out: points and lines, unused images, unknown attributes, ... (once each)
struct Mesha mesh: primitives with a material eachname: Stringprimitives: Vec<Primitive>
struct Primitivetriangles: one normal and one uv per position, three indices per triangle, counter-clockwise from outside. Strips and fans become lists; points and lines are left out (a note)positions: Vec<[f32; 3]>normals: Vec<[f32; 3]>uvs: Vec<[f32; 2]>indices: Vec<u32>material: Option<usize>flat_normals: bool-- the file had no normals: each triangle has its own three vertices with its face's normalhas_uvs: bool-- the file had TEXCOORD_0 (else every uv is 0)
enum AlphaModeOpaqueMask-- below alpha_cutoff: not drawnBlend
struct TextureRefa texture of a material: which one, which uv set (render3d takes 0)texture: usizetex_coord: u32
struct Materiala material: pbrMetallicRoughness and the three others, with glTF's defaults for what the file leaves outname: Stringbase_color_factor: [f32; 4]-- linear rgba; the texture is sRGBbase_color_texture: Option<TextureRef>metallic_factor: f32roughness_factor: f32metallic_roughness_texture: Option<TextureRef>-- linear: roughness in g, metallic in bnormal_texture: Option<TextureRef>normal_scale: f32occlusion_texture: Option<TextureRef>occlusion_strength: f32emissive_factor: [f32; 3]-- linear rgb; the texture is sRGBemissive_texture: Option<TextureRef>alpha_mode: AlphaModealpha_cutoff: f32double_sided: bool
enum FilterNearestLinear
enum WrapRepeatClampToEdgeMirroredRepeat
struct Samplera sampler; what the file leaves out is linear with linear mip levels, repeatingmag: Filtermin: Filtermip: Option<Filter>-- between mip levels; None: level 0 only (minFilter NEAREST or LINEAR)wrap_s: Wrapwrap_t: Wrap
impl Sampler
const DEFAULT: Sampler = Sampler { mag: Filter::Linear, min: Filter::Linear, mip: ...struct Texturean image with a sampler. image None: the file names its image only through an extension it does not require (the materials' references to it are dropped, a note)name: Stringimage: Option<usize>sampler: Sampler
struct Imagea decoded image: rows from the top, 4 bytes per pixel, r g b a with straight alpha; the file's colour profile and gamma are ignored (glTF says so), a JPEG's EXIF orientation too. Images no texture uses are not decoded (width 0)name: Stringwidth: u32height: u32rgba: Vec<u8>
struct Nodea node: its own transform (column-major 4 x 4, f64), the product of those of its ancestors and itselfname: Stringmesh: Option<usize>children: Vec<usize>parent: Option<usize>local: [f64; 16]world: [f64; 16]light: Option<usize>-- (G5c) the KHR_lights_punctual light this node places
struct Light(G5c) a light of KHR_lights_punctual; where it is and which way it shines come from the nodes naming itname: Stringkind: LightKindcolor: [f32; 3]-- linear rgb, 0 or more (white if the file says nothing)intensity: f32-- candela for point and spot lights, lux for directional ones (1 if the file says nothing)range: Option<f32>-- point and spot: the distance where it ends (above 0); None: it never does
enum LightKind(G5c) KHR_lights_punctual's kinds; spot cone angles in radians from the axis, 0 <= inner < outer <= pi / 2DirectionalPointSpot { inner: f32, outer: f32 }
struct LightRef(G5c) a light placed by a nodenode: usizelight: usizeworld: [f64; 16]
impl LightRef
fn position(&self) -> [f64; 3]where the light is: the node's originfn direction(&self) -> [f64; 3]which way it shines: the node's -z, a unit vector (spot and directional lights)struct SceneDefname: Stringnodes: Vec<usize>-- root nodes
struct InstanceRefa primitive drawn by a nodenode: usizemesh: usizeprimitive: usizeworld: [f64; 16]
/// the identity, column-major
IDENTITY: [f64; 16] = [1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0 ...
impl Document
fn instances(&self, scene: Option<usize>) -> Vec<InstanceRef>the instances of a scene (None: Document::scene), depth first in the order of the file; without scenes those of every node without a parent. Each node is visited oncefn lights_of(&self, scene: Option<usize>) -> Vec<LightRef>(G5c) the lights a scene places (KHR_lights_punctual), in the same order as instances()fn load(bytes: &[u8], files: &mut dyn FnMut(&str) -> Option<Vec<u8>>, limits: &Limits) -> Result<Document>read a .glb or a .gltf (by its first bytes);filesgives the bytes of a relative URI the file namesfn glb_chunks(b: &[u8]) -> Result<(&[u8], Option<&[u8]>)>the JSON and the BIN chunk of a .glbfn write_glb(json: &[u8], bin: Option<&[u8]>) -> Vec<u8>a .glb of a JSON text and a binary buffer (tools and tests; write_document builds both from a Document): chunks padded with spaces and zerosfn try_write_glb(json: &[u8], bin: Option<&[u8]>) -> Result<Vec<u8>>write_glb, Err(Limit) when the file would be 4 GiB or more (its lengths are 32-bit: write_glb wrote them cut off, a file no reader takes)fn base64_decode(s: &[u8]) -> Option<Vec<u8>>standard base64 (padding optional); None for anything elsefn base64_encode(b: &[u8]) -> Stringbase64 of bytes (tools and tests: data URIs)fn sqrt(x: f64) -> f64a square root in f64 (no libm in no_std)fn mat_mul(a: &[f64; 16], b: &[f64; 16]) -> [f64; 16]a * b, column-major 4 x 4fn trs_matrix(t: [f64; 3], q: [f64; 4], s: [f64; 3]) -> [f64; 16]the matrix of translation, rotation (unit quaternion x, y, z, w) and scale: T * R * Sstruct Trsa node matrix taken apart: translation, rotation (unit quaternion x, y, z, w), scale (a mirror makes x negative), and how far the columns are from right angles (|cos| of the worst pair: 0 without shear, which T * R * S cannot hold)translation: [f64; 3]rotation: [f64; 4]scale: [f64; 3]shear: f64
fn decompose(m: &[f64; 16]) -> Trs
gltf/write.rs#
Source: lib/gltf/write.rs
write -- a Document as a .glb (G7g): meshes with positions, normals and one uv set, materials by their
factors, nodes with their local transforms, scenes. What load reads back is the same Document (the
numbers are written as the shortest text that parses to the same value). Not written: textures,
images and samplers, lights; a Document with any of them is Error::Unsupported rather than written
without them.
fn write_document(doc: &Document) -> Result<Vec<u8>>The document as a .glb: meshes (positions with min and max, normals, TEXCOORD_0 when the primitive has UV, indices as u16 or u32), materials (factors, alpha mode and cutoff, double-sided), nodes (name, mesh, children, the local matrix unless it is the identity), scenes and the default scene;asset.generatoris the document's. Err(Invalid) for arrays that do not fit (an index out of range, normals or UV of another length, a number that is not finite, a reference to a mesh, material or node that is not there), Err(Unsupported) for textures, images or lights, which this writer leaves to later.