From 9e2ed2daaa62b9fc6cc26ec8f2e0654af746153c Mon Sep 17 00:00:00 2001 From: SoraKatadzuma Date: Fri, 30 Oct 2026 12:04:54 -0500 Subject: [PATCH] Initial Commit --- .editorconfig | 9 + .gitignore | 1 + README.md | 59 ++++ blossomfile | 42 +++ gltf/accessors.sakura | 240 ++++++++++++++++ gltf/files.sakura | 157 ++++++++++ gltf/gltf.sakura | 123 ++++++++ gltf/members.sakura | 161 +++++++++++ gltf/nodes.sakura | 133 +++++++++ gltf/parse.sakura | 630 +++++++++++++++++++++++++++++++++++++++++ gltf/parts.sakura | 243 ++++++++++++++++ tests/accessors.sakura | 113 ++++++++ tests/main.sakura | 10 + tests/nodes.sakura | 119 ++++++++ tests/reading.sakura | 186 ++++++++++++ tests/support.sakura | 181 ++++++++++++ 16 files changed, 2407 insertions(+) create mode 100644 .editorconfig create mode 100644 .gitignore create mode 100644 README.md create mode 100644 blossomfile create mode 100644 gltf/accessors.sakura create mode 100644 gltf/files.sakura create mode 100644 gltf/gltf.sakura create mode 100644 gltf/members.sakura create mode 100644 gltf/nodes.sakura create mode 100644 gltf/parse.sakura create mode 100644 gltf/parts.sakura create mode 100644 tests/accessors.sakura create mode 100644 tests/main.sakura create mode 100644 tests/nodes.sakura create mode 100644 tests/reading.sakura create mode 100644 tests/support.sakura diff --git a/.editorconfig b/.editorconfig new file mode 100644 index 0000000..c6c8b36 --- /dev/null +++ b/.editorconfig @@ -0,0 +1,9 @@ +root = true + +[*] +indent_style = space +indent_size = 2 +end_of_line = lf +charset = utf-8 +trim_trailing_whitespace = true +insert_final_newline = true diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..cfecb95 --- /dev/null +++ b/.gitignore @@ -0,0 +1 @@ +.blossom diff --git a/README.md b/README.md new file mode 100644 index 0000000..8f92019 --- /dev/null +++ b/README.md @@ -0,0 +1,59 @@ +# gltf +Models read from glTF 2.0, as a `.gltf` file and the files it names or as a `.glb` file, whole and checked: every part of the file, each index between parts, and each accessor's reach within its buffer, so what's read is read without failing after. What an accessor holds is read as numbers, as floats or as integers. It's Sakura's, built with [blossom](https://git.malunal.studio/sakura/blossom), reads std's `containers`, `io`, `json`, and `math`, and places nodes by the vectors, rotations, and matrices of `linear`, of the [physics](https://git.malunal.studio/malunal/physics) package. + +```sakura +import malunal::gltf; + +val tree := gltf::load("models/tree.glb") else (e) { io::println(e.describe().span); ... }; +for &part in tree.meshes[0].primitives { + val places := tree.floats(part.find("POSITION").expect("...")); # x, y, z of each vertex + val indices := tree.integers(part.indices.expect("...")); # three a triangle + val look := &tree.materials[part.material.expect("...")]; # base color, textures, alpha +} +val placed := tree.world_matrix(2); # a node, through its parents +``` +`gltf::decode(bytes, folder)` reads bytes already in memory, the files they name found in the folder. An image is given as the bytes of its file, PNG or JPEG, as [image](https://git.malunal.studio/malunal/image) reads them, which `gltf` doesn't decode itself. + +A project reads it by requiring this folder, or its remote, and naming `malunal.gltf`, whose module is `malunal::gltf`, among a target's `deps`: + +```yaml +requires: +- ../gltf +targets: +- name: game + type: program + deps: [malunal.gltf] +``` + +## Layout +`gltf/` is the module `malunal::gltf`. + +| Path | Holds | +|---|---| +| `gltf.sakura` | `asset`, `gltf_error` and its `failure`, the extensions read, and `load` and `decode` | +| `parts.sakura` | The parts of an asset: scenes, nodes, meshes and their primitives, materials and the textures they name, textures, samplers, images, cameras, skins, animations, and lights | +| `accessors.sakura` | Buffers, their views, and accessors; reading an accessor's numbers, sparse ones among them | +| `nodes.sakura` | The tree of nodes: each placed by a matrix or a translation, rotation, and scale, each child's parent, and a node's world matrix | +| `parse.sakura` | Reading the JSON into the parts, in the order they need one another, each checked as it's read | +| `members.sakura` | Reading the JSON's members: each of its kind, with its default, an index checked against its list | +| `files.sakura` | A `.glb` file's chunks, and the bytes a URI names: a `data:` URI's base64, or a file beside the asset | + +## What's read +- **Files**: `.gltf`, its buffers and images named as files beside it, their URIs percent-decoded, or as `data:` URIs of base64; and `.glb`, its JSON and binary chunks, other chunks passed over. A URI naming another place, as `https:`, isn't fetched, and is `unsupported`. +- **Every part of glTF 2.0**: scenes, and the scene shown at first; nodes, each with its children and parent, its mesh, camera, skin, and light, its morph weights, and where it is, as a matrix, taken apart into a translation, rotation, and scale, x's negative where it mirrors, or those, put together into a matrix; meshes, their primitives' attributes, indices, material, mode, and morph targets; materials of the metallic-rough model, each texture they name with its `TEXCOORD` set, a normal map's scale and occlusion's strength, emission, and alpha opaque, cut out, or blended, and double sided; textures, samplers, and images; cameras, perspective or orthographic; skins; and animations, their channels and samplers, linear, step, or cubic spline. +- **Accessors** of every component type and element, normalized or not, interleaved by a view's stride, a matrix's columns each begun at a multiple of 4 bytes, and sparse, over a view's elements or over zeros. `floats` makes integers floats, and normalized ones fractions, as glTF says, -1 at the least for a signed one; `integers` reads indices and joints as they are. +- **Extensions**: `KHR_lights_punctual`'s directional, point, and spot lights; `KHR_materials_unlit`; `KHR_materials_emissive_strength`, multiplying emission; and `KHR_mesh_quantization`, whose accessors of integers `floats` reads anyway. An asset requiring another is `unsupported`, naming it. One using another without requiring it is read without what it adds, and names it in `extensions`. +- **What's checked**: the version is 2; every index names a part there is; each buffer view lies within its buffer, of a stride from 4 to 252, a multiple of 4; each accessor lies within its view, its stride no less than an element; each sparse index names an element; a primitive's attributes are of one count, and its indices name vertices it has; a skin's inverse binds are a matrix of floats for each joint; an animation's times are floats; each node has one parent at most, following parents up ends, and a scene's nodes are roots. What breaks it is `malformed`, saying what and where, as `meshes[2].primitives[0]: its index 9 is past its 8 vertices.` + +A `gltf_error` holds the first 240 bytes of why, so it's plain data, as std's errors are. + +## Speed +33 of Khronos's sample models, 65 MB of them, from a box of 24 vertices to BrainStem's skin and MetalRoughSpheres' 3.5 million numbers, each read whole and every accessor's numbers read after, take 136 ms on a Ryzen 9 9950X3D, the files' own reading among it. + +## Testing +`blossom test` runs `tests/`, which writes models of its own and reads them back: a quad from JSON with its buffer in a `data:` URI, from a `.glb` file, and from files beside it, one named with a space; an image in a buffer view; numbers of every size, interleaved, normalized, in a matrix's padded columns, and sparse; a matrix taken apart and a translation put together, through a parent; cameras, a spot light, a skin, and an animation; and what's refused, each with why. + +What's read was checked further against Khronos's [glTF sample assets](https://github.com/KhronosGroup/glTF-Sample-Assets), which aren't part of the repository: 33 models, as `.glb`, embedded `.gltf`, and `.gltf` with files beside it, each read, every accessor its primitives, skins, and animations name read, and every position within the least and the most its accessor says. + +## Not yet +Writing glTF; URIs fetched from the network; `KHR_texture_transform`, `KHR_draco_mesh_compression`, `EXT_meshopt_compression`, and `KHR_texture_basisu`; and extensions' `extras`. diff --git a/blossomfile b/blossomfile new file mode 100644 index 0000000..bb279e9 --- /dev/null +++ b/blossomfile @@ -0,0 +1,42 @@ +name: gltf +gpid: malunal +semv: 1.0.0 + +options: + level: 2 + +requires: +- https://git.malunal.studio/sakura/std@v1.0.0 +# Vectors, rotations, and matrices, which nodes are placed by: +# `malunal::linear`, of the `physics` package. +- https://git.malunal.studio/malunal/physics@v1.0.0 + +targets: +- name: malunal.gltf + type: library + root: ./gltf + deps: + - malunal.linear + - std.containers + - std.io + - std.json + - std.math + +tests: +# They write and read models of their own, under `.blossom/gltf tests/`. +- name: malunal.gltf.tests + type: program + deps: [malunal.gltf, malunal.linear, std.io, std.math, std.testing] + srcs: + - tests/main.sakura + - tests/support.sakura + - tests/reading.sakura + - tests/accessors.sakura + - tests/nodes.sakura + +exports: +- malunal.gltf + +package: + desc: Models read from glTF 2.0, as .gltf and its files or .glb, whole and checked, with what their accessors hold read as numbers. + auth: John Christman diff --git a/gltf/accessors.sakura b/gltf/accessors.sakura new file mode 100644 index 0000000..5a5b93c --- /dev/null +++ b/gltf/accessors.sakura @@ -0,0 +1,240 @@ +#! Contains buffers, the views of them, and accessors, which say how a view's +#! bytes are read as numbers; and reading an accessor's numbers, as floats or +#! as integers, its sparse values put in place. + +import std::math; +module malunal::gltf; + +#! A buffer: bytes, read from its file, a `data:` URI, or a `.glb` file's +#! binary chunk. +pub struct buffer { + pub var name: string; + #! Its URI, as the JSON writes it, or empty for a `.glb` file's binary chunk. + pub var uri: string; + #! How many bytes it is, as the JSON says, which its bytes are at least. + pub var length: u64; + pub var bytes: vector; +} + +#! A part of a buffer, which accessors read. +pub struct buffer_view { + pub var name: string; + pub var buffer: u64; + pub var offset: u64; + pub var length: u64; + #! The bytes from one element to the next, or zero where they're packed. + pub var stride: u64; +} + +#! The type of each number of an accessor. +pub enum component: u8 { byte, unsigned_byte, short, unsigned_short, unsigned_int, float } + +#! How many bytes a number of the type takes. +pub val component::bytes: u64 { + get => match this { + byte, unsigned_byte => 1, + short, unsigned_short => 2, + unsigned_int, float => 4, + }; +} + +#! What each element of an accessor is. +pub enum element: u8 { scalar, vec2, vec3, vec4, mat2, mat3, mat4 } + +#! How many numbers an element holds. +pub val element::components: u64 { + get => match this { + scalar => 1, + vec2 => 2, + vec3 => 3, + vec4, mat2 => 4, + mat3 => 9, + mat4 => 16, + }; +} + +# How many rows a matrix has, or 1 for a vector, as a column of a matrix is +# kept on its own, at a multiple of 4 bytes. +def element::rows(&this): u64 { + return match this { + mat2 => 2, + mat3 => 3, + mat4 => 4, + else => 0, + }; +} + +#! Values an accessor puts in place of some of its elements, of `count` +#! indices, in a view of integers, and as many values, in a view of the +#! accessor's own type. +pub struct sparse { + pub var count: u64; + pub var indices_view: u64; + pub var indices_offset: u64; + pub var indices_type := component::unsigned_int; + pub var values_view: u64; + pub var values_offset: u64; +} + +#! How the bytes of a view are read as `count` elements, each of `kind`'s +#! numbers of `type`, from `offset`. +pub struct accessor { + pub var name: string; + #! Its view, or none where every element is zero but its sparse ones. + pub var view: maybe; + pub var offset: u64; + pub var component_type := component::float; + #! Whether its integers are read as fractions, 0 to 1, or -1 to 1 where signed. + pub var normalized: bool; + pub var count: u64; + pub var kind := element::scalar; + #! The least and the most of each of its numbers, where the JSON says. + pub var min: vector; + pub var max: vector; + pub var sparse: maybe; +} + +# How many bytes an element of an accessor takes, each column of a matrix +# begun at a multiple of 4. +def accessor::element_bytes(&this): u64 { + val rows := this.kind.rows(); + return this.kind.components * this.component_type.bytes if rows == 0; + return rows * column_stride(rows, this.component_type); +} + +# The bytes from one column of a matrix to the next. +def column_stride(rows: u64, numbers: component): u64 { + val bytes := rows * numbers.bytes; + return (bytes + 3) / 4 * 4; +} + +# Where the number `k` of an element is, from the element's first byte. +def accessor::component_at(&this, k: u64): u64 { + val rows := this.kind.rows(); + return k * this.component_type.bytes if rows == 0; + return (k / rows) * column_stride(rows, this.component_type) + (k % rows) * this.component_type.bytes; +} + +#! The numbers of an accessor, as floats: each element's in turn, `count` of +#! them, integers made floats, normalized ones made fractions as glTF says, and +#! its sparse values put in place. +#! @param this The asset. +#! @param which The accessor. +#! @returns `count * kind.components` floats. +pub def asset::floats(&this, which: u64): vector { + val read := &this.accessors[which]; + val width := read.kind.components; + var made := vector::::new(); + made.resize(read.count * width); + if read.view is some(v) { + val at := this.place_of(read, v); + val stride := this.stride_of(read, v); + for e in 0..read.count { + for k in 0..width { + made[e * width + k] = float_at(at.bytes, at.start + e * stride + read.component_at(k), read.component_type, read.normalized); + } + } + } + if read.sparse is some(&s) { + val indices := this.place_of_view(s.indices_view, s.indices_offset); + val values := this.place_of_view(s.values_view, s.values_offset); + val size := read.element_bytes(); + for i in 0..s.count { + val e := integer_at(indices.bytes, indices.start + i * s.indices_type.bytes, s.indices_type); + for k in 0..width { + made[e * width + k] = float_at(values.bytes, values.start + i * size + read.component_at(k), read.component_type, read.normalized); + } + } + } + return made; +} + +#! The numbers of an accessor of integers, as indices and joints are: each +#! element's in turn, its sparse values put in place. +#! @param this The asset. +#! @param which The accessor, of a type of integers, not normalized. +#! @returns `count * kind.components` integers. +pub def asset::integers(&this, which: u64): vector { + val read := &this.accessors[which]; + val width := read.kind.components; + var made := vector::::new(); + made.resize(read.count * width); + if read.view is some(v) { + val at := this.place_of(read, v); + val stride := this.stride_of(read, v); + for e in 0..read.count { + for k in 0..width { + made[e * width + k] = integer_at(at.bytes, at.start + e * stride + read.component_at(k), read.component_type) as u32; + } + } + } + if read.sparse is some(&s) { + val indices := this.place_of_view(s.indices_view, s.indices_offset); + val values := this.place_of_view(s.values_view, s.values_offset); + val size := read.element_bytes(); + for i in 0..s.count { + val e := integer_at(indices.bytes, indices.start + i * s.indices_type.bytes, s.indices_type); + for k in 0..width { + made[e * width + k] = integer_at(values.bytes, values.start + i * size + read.component_at(k), read.component_type) as u32; + } + } + } + return made; +} + +# Where an accessor's, or a view's, bytes begin, in its buffer's. +struct place { + var bytes: span; + var start: u64; +} + +def asset::place_of(&this, read: &accessor, view: u64): place { + return this.place_of_view(view, read.offset); +} + +def asset::place_of_view(&this, view: u64, offset: u64): place { + val v := &this.views[view]; + return place{ bytes = this.buffers[v.buffer].bytes.span, start = v.offset + offset }; +} + +# The bytes from one element of an accessor to the next. +def asset::stride_of(&this, read: &accessor, view: u64): u64 { + val given := this.views[view].stride; + return given != 0 ? given : read.element_bytes(); +} + +# A number of a type, at a byte, as a float, made a fraction where it's +# normalized. +def float_at(bytes: span, at: u64, numbers: component, normalized: bool): f32 { + if numbers == component::float { + return math::real_of_bits(integer_at(bytes, at, component::unsigned_int) as u32); + } + val raw := integer_at(bytes, at, numbers); + val signed := signed_value(raw, numbers); + return signed as f32 if !normalized; + return match numbers { + byte => math::max(signed as f32 / 127, -1f), + unsigned_byte => raw as f32 / 255, + short => math::max(signed as f32 / 32767, -1f), + unsigned_short => raw as f32 / 65535, + else => raw as f32 / 4294967295, + }; +} + +# The bytes of an integer of a type, at a byte, little-endian, unsigned. +def integer_at(bytes: span, at: u64, numbers: component): u64 { + var value: u64 = 0; + for i in 0..numbers.bytes { + value = value | (bytes[at + i] as u64 << (8 * i) as u32); + } + return value; +} + +# An integer's bytes as the signed value they are, of a signed type. +def signed_value(raw: u64, numbers: component): i64 { + return match numbers { + byte => raw >= 0x80 ? raw as i64 - 0x100 : raw as i64, + short => raw >= 0x8000 ? raw as i64 - 0x10000 : raw as i64, + else => raw as i64, + }; +} diff --git a/gltf/files.sakura b/gltf/files.sakura new file mode 100644 index 0000000..eab8f37 --- /dev/null +++ b/gltf/files.sakura @@ -0,0 +1,157 @@ +#! Contains the files an asset is read from: a `.glb` file's chunks, and the +#! bytes a URI names, the data of a `data:` URI, in base64, or a file's, beside +#! the asset's, its path percent-decoded. + +import std::io; +module malunal::gltf; + +const glb_magic: u32 = 0x46546C67; # `glTF`, little-endian. +const json_chunk: u32 = 0x4E4F534A; # `JSON`. +const bin_chunk: u32 = 0x004E4942; # `BIN`, and a zero. + +# Whether bytes are a `.glb` file's, by their first four. +def is_binary(bytes: span): bool { + return bytes.length >= 4 && word_at(bytes, 0) == glb_magic; +} + +# A little-endian `u32` at a byte. +def word_at(bytes: span, at: u64): u32 { + return bytes[at] as u32 | (bytes[at + 1] as u32 << 8) | (bytes[at + 2] as u32 << 16) | (bytes[at + 3] as u32 << 24); +} + +# The chunks of a `.glb` file: its JSON, and its binary chunk, where it has one. +struct chunks { + var json: strview; + var bin: span; + var has_bin: bool; +} + +# Finds a `.glb` file's chunks: the JSON first, as it must be, then the first +# binary chunk, passing over others, as glTF says to. +def binary_chunks(bytes: span): result { + return failed(failure::malformed, "Its .glb header is cut short.") if bytes.length < 20; + val version := word_at(bytes, 4); + return failed(failure::unsupported, $"Its .glb container is of version {version}, not 2.".span) if version != 2; + val length := word_at(bytes, 8) as u64; + return failed(failure::malformed, $"Its .glb header says it's {length} bytes, but it's {bytes.length}.".span) if length > bytes.length || length < 20; + var made := chunks{}; + var found_json := false; + var at: u64 = 12; + while at + 8 <= length { + val size := word_at(bytes, at) as u64; + val kind := word_at(bytes, at + 4); + at += 8; + return failed(failure::malformed, "A chunk of its .glb container reaches past its end.") if size > length - at; + if !found_json { + return failed(failure::malformed, "Its .glb container's first chunk isn't its JSON.") if kind != json_chunk; + made.json = strview::over(bytes.data + at, size); + found_json = true; + } else if kind == bin_chunk && !made.has_bin { + made.bin = span::::over(bytes.data + at, size); + made.has_bin = true; + } + at += size; + } + return failed(failure::malformed, "Its .glb container holds no JSON.") if !found_json; + return made; +} + +# The bytes a URI names: a `data:` URI's, decoded from base64, its type kept; +# or a file's, its path, percent-decoded, taken from the folder. +# @param uri The URI. +# @param folder The folder the asset's files are in, or empty for none. +# @param whose Whose URI, as `buffers[1]`, for what's wrong with it. +# @param type The type a `data:` URI says, as `image/png`, kept. +# @returns The bytes, or why they couldn't be had. +def bytes_of_uri(uri: strview, folder: strview, whose: strview, mime: &mut string): result, gltf_error> { + if uri.starts_with("data:") { + var comma := uri.length; + for i in 5..uri.length { + if uri[i] == ',' { + comma = i; + break; + } + } + return failed(failure::malformed, $"{whose}: its data URI has no comma.".span) if comma == uri.length; + val head := uri.substr(5, comma - 5); + return failed(failure::unsupported, $"{whose}: its data URI isn't base64.".span) if !head.ends_with(";base64"); + mime = string::from(head.substr(0, head.length - 7), nothing{}); + val decoded := base64(uri.substr(comma + 1, uri.length - comma - 1)) else { + return failed(failure::malformed, $"{whose}: its data URI's base64 isn't.".span); + }; + return decoded; + } + for i in 0..uri.length { + if uri[i] == ':' { + return failed(failure::unsupported, $"{whose}: {uri} names another place than a file beside it, which isn't read.".span); + } + break if uri[i] == '/'; + } + val named := percent_decoded(uri) else { return failed(failure::malformed, $"{whose}: {uri} isn't percent-encoded right.".span); }; + val at := folder.length == 0 ? string::from(named.span, nothing{}) : $"{folder}/{named.span}"; + val file := path::parse(at.span) else (_) { return failed(failure::unreadable, $"{whose}: {at.span} isn't a path.".span); }; + val text := io::read_file(&file) else (_) { return failed(failure::unreadable, $"{whose}: {at.span} couldn't be read.".span); }; + var made := vector::::new(); + made.extend(text.span); + return made; +} + +# Text of `%XX` escapes decoded, or nothing where an escape isn't two hex +# digits. +def percent_decoded(text: strview): maybe { + var made := string::new(nothing{}); + var i: u64 = 0; + while i < text.length { + if text[i] != '%' { + made.push(text[i]); + i++; + continue; + } + return nothing{} if i + 2 >= text.length; + val high := hex_value(text[i + 1]) else { return nothing{}; }; + val low := hex_value(text[i + 2]) else { return nothing{}; }; + made.push(high << 4 | low); + i += 3; + } + return made; +} + +def hex_value(c: u8): maybe { + return c - '0' if c >= '0' && c <= '9'; + return c - 'a' + 10 if c >= 'a' && c <= 'f'; + return c - 'A' + 10 if c >= 'A' && c <= 'F'; + return nothing{}; +} + +# Base64's bytes, its padding optional, or nothing where it isn't base64. +def base64(text: strview): maybe> { + var made := vector::::new(); + var held: u32 = 0; + var bits: u32 = 0; + var ended := false; + for i in 0..text.length { + val c := text[i]; + if c == '=' { + ended = true; + continue; + } + return nothing{} if ended; + val value := base64_value(c) else { return nothing{}; }; + held = ((held << 6) | value as u32) & 0xFFFFFF; + bits += 6; + if bits >= 8 { + bits -= 8; + made.append(((held >> bits) & 0xFF) as u8); + } + } + return made; +} + +def base64_value(c: u8): maybe { + return c - 'A' if c >= 'A' && c <= 'Z'; + return c - 'a' + 26 if c >= 'a' && c <= 'z'; + return c - '0' + 52 if c >= '0' && c <= '9'; + return 62 if c == '+'; + return 63 if c == '/'; + return nothing{}; +} diff --git a/gltf/gltf.sakura b/gltf/gltf.sakura new file mode 100644 index 0000000..d50a3bd --- /dev/null +++ b/gltf/gltf.sakura @@ -0,0 +1,123 @@ +#! Contains `asset`, a model read from glTF 2.0, why one couldn't be, and +#! reading one, from a file or from bytes. +#! +#! A `.gltf` file is JSON, naming its buffers and images as files beside it or +#! as data in `data:` URIs; a `.glb` file is the same JSON and its first buffer +#! in one file, as chunks. Either is read whole: its JSON into the parts of an +#! `asset`, each index between them checked, its buffers' and images' bytes read, +#! and every accessor checked to lie within its buffer, so what an asset holds +#! is read without failing after. What an accessor holds is read as numbers by +#! `asset::floats` and `asset::integers`. +#! +#! Indices into an asset's lists are `u64`s, as glTF's are, and one that's +#! optional a `maybe`. Each part keeps glTF's defaults where its JSON leaves +#! them out, and a node its translation, rotation, and scale and its matrix both, +#! whichever the JSON gave. + +import std::io; +import malunal::linear; +module malunal::gltf; + +#! What kind of thing kept an asset from being read. +pub enum failure: u8 { + unreadable, #! A file couldn't be read: the asset's, or a buffer's or an image's it names. + malformed, #! The data breaks glTF: JSON that isn't, a member of the wrong kind or missing, an index past what it names, an accessor past its buffer. + unsupported, #! It's well formed, but asks for what isn't read: a version but 2, or an extension it requires that isn't read. +} + +#! Why an asset couldn't be read: the kind of thing, and what, as +#! `meshes[2].primitives[0]: its material is 9, of the 4 there are`. It holds +#! its text itself, its first 240 bytes, so it's plain data, as std's errors +#! are. +pub struct gltf_error { + pub var kind: failure; + var text: u8[240]; + var length: u64; +} + +#! What was wrong, and where. +pub def gltf_error::describe(&this): string { + return string::from(strview::over(&this.text[0] as *u8, this.length), nothing{}); +} + +# An error of a kind, saying why. +def failed(kind: failure, why: strview): gltf_error { + var made := gltf_error{ kind = kind }; + made.length = why.length < 240 ? why.length : 240; + for i in 0..made.length { + made.text[i] = why[i]; + } + return made; +} + +#! The extensions read. An asset requiring another is `unsupported`; one using +#! another, without requiring it, is read without what it adds. +pub const extensions_read: strview[4] = [ + "KHR_lights_punctual", + "KHR_materials_unlit", + "KHR_materials_emissive_strength", + "KHR_mesh_quantization", +]; + +#! A model read from glTF 2.0: its scenes, the tree of nodes they hold, and +#! what those draw with, each part in the list glTF keeps it in, by index. +pub struct asset { + #! The glTF version it says it's of, as `2.0`. + pub var version: string; + #! What wrote it, where it says. + pub var generator: string; + #! The scene shown at first, where it says. + pub var scene: maybe; + pub var scenes: vector; + pub var nodes: vector; + pub var meshes: vector; + pub var materials: vector; + pub var textures: vector; + pub var samplers: vector; + pub var images: vector; + pub var accessors: vector; + pub var views: vector; + pub var buffers: vector; + pub var cameras: vector; + pub var skins: vector; + pub var animations: vector; + #! Its lights, of `KHR_lights_punctual`. + pub var lights: vector; + #! The extensions it uses, those not read among them. + pub var extensions: vector; +} + +#! Reads an asset from a file: `.gltf` or `.glb`, whichever its first bytes +#! say, the files it names read from beside it. +#! @param at The file's path. +#! @returns The asset, or why it couldn't be read: `unreadable` where the file, +#! or one it names, couldn't be. +pub def load(at: &path): result { + val bytes := io::read_file(at) else (_) { return failed(failure::unreadable, $"{at.span} couldn't be read.".span); }; + var folder := path::new(); + if at.parent() is some(&above) { + folder = path::copy_of(&above); + } + return decode(bytes.span, folder.span); +} + +#! Reads an asset from a file named by text, as `load` does. +pub def load(at: strview): result { + val named := path::parse(at) else (_) { return failed(failure::unreadable, $"{at} isn't a path.".span); }; + return load(&named); +} + +#! Reads an asset from bytes: a `.glb` file's, whose first four are `glTF`, or +#! else a `.gltf` file's JSON. +#! @param bytes The bytes. +#! @param folder The folder the files it names are found in, or empty where +#! it names none but data, as a `.glb` file of one buffer. +#! @returns The asset, or why it couldn't be read. +pub def decode(bytes: span, folder: strview = ""): result { + if is_binary(bytes) { + val chunks := binary_chunks(bytes) else (e) { return e; }; + return read_json(chunks.json, chunks.bin, chunks.has_bin, folder); + } + val text := strview::over(bytes.data, bytes.length); + return read_json(text, span::::over(bytes.data, 0), false, folder); +} diff --git a/gltf/members.sakura b/gltf/members.sakura new file mode 100644 index 0000000..6a76b93 --- /dev/null +++ b/gltf/members.sakura @@ -0,0 +1,161 @@ +#! Contains reading the members of the JSON's objects, each of the kind glTF +#! says, with its default where it's left out or null, and an index checked to +#! name one of the parts there are; what's wrong said with where it is, as +#! `meshes[2].primitives[0]`. + +import std::json; +module malunal::gltf; + +# What's wrong with a value of the JSON, and where it is. +def wrong(site: strview, why: strview): gltf_error { + return failed(failure::malformed, $"{site}: {why}.".span); +} + +# A member of an object, where it has it, and it isn't null. +def member_of(v: &json::value, key: strview): maybe { + if v.get(key) is some(found) { + return found if !found.is_null; + } + return nothing{}; +} + +# A member that must be an object, where there is one. +def object_member(v: &json::value, key: strview, site: strview): result, gltf_error> { + var none: maybe = nothing{}; + val found := member_of(v, key) else { return none; }; + return wrong(site, $"its {key} isn't an object".span) if found.kind != json::kind::object; + val held: maybe = found; + return held; +} + +# A member that must be an array, where there is one. +def array_member(v: &json::value, key: strview, site: strview): result, gltf_error> { + var none: maybe = nothing{}; + val found := member_of(v, key) else { return none; }; + return wrong(site, $"its {key} isn't an array".span) if found.kind != json::kind::array; + val held: maybe = found; + return held; +} + +# How many elements an array member holds, or none where it's missing. +def length_of(v: &json::value, key: strview): u64 { + if member_of(v, key) is some(found) { + return found.length if found.kind == json::kind::array; + } + return 0; +} + +# A number, or its default. +def number_member(v: &json::value, key: strview, site: strview, given: f64): result { + val found := member_of(v, key) else { return given; }; + val n := found.as_f64() else (_) { return wrong(site, $"its {key} isn't a number".span); }; + return n; +} + +# A number as an `f32`, or its default. +def float_member(v: &json::value, key: strview, site: strview, given: f32): result { + val n := number_member(v, key, site, given as f64) else (e) { return e; }; + return n as f32; +} + +# A number that may be left out. +def maybe_number(v: &json::value, key: strview, site: strview): result, gltf_error> { + var none: maybe = nothing{}; + val found := member_of(v, key) else { return none; }; + val n := found.as_f64() else (_) { return wrong(site, $"its {key} isn't a number".span); }; + val held: maybe = n as f32; + return held; +} + +# A whole number of 0 or more, or its default. +def count_member(v: &json::value, key: strview, site: strview, given: u64): result { + val found := member_of(v, key) else { return given; }; + val n := found.as_u64() else (_) { return wrong(site, $"its {key} isn't a whole number of 0 or more".span); }; + return n; +} + +# A whole number that must be there. +def needed_count(v: &json::value, key: strview, site: strview): result { + return wrong(site, $"it has no {key}".span) if member_of(v, key) is none; + return count_member(v, key, site, 0); +} + +# An index of one of `count` parts of a list, as `meshes`, where it's there. +def index_member(v: &json::value, key: strview, site: strview, count: u64, list: strview): result, gltf_error> { + var none: maybe = nothing{}; + return none if member_of(v, key) is none; + val n := count_member(v, key, site, 0) else (e) { return e; }; + return wrong(site, $"its {key} is {n}, of the {count} {list} there are".span) if n >= count; + val held: maybe = n; + return held; +} + +# An index that must be there. +def needed_index(v: &json::value, key: strview, site: strview, count: u64, list: strview): result { + val found := index_member(v, key, site, count, list) else (e) { return e; }; + val n := found else { return wrong(site, $"it has no {key}".span); }; + return n; +} + +# Text, or empty. +def text_member(v: &json::value, key: strview, site: strview): result { + val found := member_of(v, key) else { return string::new(nothing{}); }; + val text := found.as_text() else (_) { return wrong(site, $"its {key} isn't text".span); }; + return string::from(text, nothing{}); +} + +# `true` or `false`, or its default. +def bool_member(v: &json::value, key: strview, site: strview, given: bool): result { + val found := member_of(v, key) else { return given; }; + val truth := found.as_bool() else (_) { return wrong(site, $"its {key} isn't true or false".span); }; + return truth; +} + +# An array of numbers: exactly `wanted` of them where that isn't 0, or none +# where it's left out. +def floats_member(v: &json::value, key: strview, site: strview, wanted: u64): result, gltf_error> { + var made := vector::::new(); + val found := array_member(v, key, site) else (e) { return e; }; + val list := found else { return made; }; + return wrong(site, $"its {key} holds {list.length} numbers, not {wanted}".span) if wanted != 0 && list.length != wanted; + for i in 0..list.length { + val each := list.at(i) else { break; }; + val n := each.as_f64() else (_) { return wrong(site, $"its {key} holds what isn't a number".span); }; + made.append(n as f32); + } + return made; +} + +# An array of numbers kept as `f64`, as an accessor's least and most. +def reals_member(v: &json::value, key: strview, site: strview): result, gltf_error> { + var made := vector::::new(); + val found := array_member(v, key, site) else (e) { return e; }; + val list := found else { return made; }; + for i in 0..list.length { + val each := list.at(i) else { break; }; + val n := each.as_f64() else (_) { return wrong(site, $"its {key} holds what isn't a number".span); }; + made.append(n); + } + return made; +} + +# An array of indices of one of `count` parts of a list. +def indices_member(v: &json::value, key: strview, site: strview, count: u64, list: strview): result, gltf_error> { + var made := vector::::new(); + val found := array_member(v, key, site) else (e) { return e; }; + val items := found else { return made; }; + for i in 0..items.length { + val each := items.at(i) else { break; }; + val n := each.as_u64() else (_) { return wrong(site, $"its {key} holds what isn't an index".span); }; + return wrong(site, $"its {key} names {n}, of the {count} {list} there are".span) if n >= count; + made.append(n); + } + return made; +} + +# An array's elements, each an object, as the parts of a list are. +def object_at(list: &json::value, i: u64, site: strview): result { + val each := list.at(i) else { return wrong(site, "it's missing"); }; + return wrong(site, "it isn't an object") if each.kind != json::kind::object; + return each; +} diff --git a/gltf/nodes.sakura b/gltf/nodes.sakura new file mode 100644 index 0000000..400c4ee --- /dev/null +++ b/gltf/nodes.sakura @@ -0,0 +1,133 @@ +#! Contains the tree of nodes: each read with where it is within its parent, as +#! a translation, rotation, and scale, or as a matrix, the other worked out of +#! it; each child's parent found, and the tree checked to have no node of two +#! parents and no loop; and where a node is in the world, through its parents. + +import std::json; +import std::math; +import malunal::linear; +module malunal::gltf; + +def read_nodes(made: &mut asset, root: &json::value, n: &counts): result { + val found := array_member(root, "nodes", "nodes") else (e) { return e; }; + val list := found else { return; }; + for i in 0..list.length { + val site := $"nodes[{i}]"; + val each := object_at(&list, i, site.span) else (e) { return e; }; + var read := node{}; + read.name = text_member(&each, "name", site.span) else (e) { return e; }; + read.children = indices_member(&each, "children", site.span, n.nodes, "nodes") else (e) { return e; }; + read.mesh = index_member(&each, "mesh", site.span, n.meshes, "meshes") else (e) { return e; }; + read.camera = index_member(&each, "camera", site.span, n.cameras, "cameras") else (e) { return e; }; + read.skin = index_member(&each, "skin", site.span, n.skins, "skins") else (e) { return e; }; + read.weights = floats_member(&each, "weights", site.span, 0) else (e) { return e; }; + val extensions := object_member(&each, "extensions", site.span) else (e) { return e; }; + if extensions is some(x) { + if member_of(&x, "KHR_lights_punctual") is some(lit) { + read.light = index_member(&lit, "light", site.span, n.lights, "lights") else (e) { return e; }; + } + } + place_node(&mut read, &each, site.span) else (e) { return e; }; + made.nodes.append(move(read)); + } + + # Each child has one parent, and following parents up ends. + for i in 0..made.nodes.length { + for k in 0..made.nodes[i].children.length { + val child := made.nodes[i].children[k]; + return failed(failure::malformed, $"nodes[{i}]: it's a child of itself.".span) if child == i; + if made.nodes[child].parent is some(other) { + return failed(failure::malformed, $"nodes[{child}]: it's a child of both {other} and {i}.".span); + } + made.nodes[child].parent = i; + } + } + for i in 0..made.nodes.length { + var at := i; + var steps: u64 = 0; + while made.nodes[at].parent is some(up) { + at = up; + steps++; + return failed(failure::malformed, $"nodes[{i}]: following its parents up comes back to it.".span) if steps > made.nodes.length; + } + } + return; +} + +# Where a node is within its parent: its matrix, taken apart into its +# translation, rotation, and scale; or those, put together into its matrix. +def place_node(read: &mut node, v: &json::value, site: strview): result { + val matrix := floats_member(v, "matrix", site, 16) else (e) { return e; }; + if matrix.length == 16 { + for i in 0..16u { + read.matrix.m[i] = matrix[i]; + } + take_apart(read); + return; + } + val t := floats_member(v, "translation", site, 3) else (e) { return e; }; + val r := floats_member(v, "rotation", site, 4) else (e) { return e; }; + val s := floats_member(v, "scale", site, 3) else (e) { return e; }; + if t.length == 3 { + read.translation = vec3{ t[0], t[1], t[2] }; + } + if r.length == 4 { + val q := quat{ r[0], r[1], r[2], r[3] }; + read.rotation = q.length > 0 ? q.normalized() : quat::identity; + } + if s.length == 3 { + read.scale = vec3{ s[0], s[1], s[2] }; + } + read.matrix = mat4::compose(read.translation, read.rotation, read.scale); + return; +} + +# Takes a node's matrix apart: its translation, the lengths of its axes as its +# scale, x's negative where the matrix mirrors, and the rotation of its axes +# made unit length. glTF holds that a node's matrix is no more than that. +def take_apart(read: &mut node): void { + val m := &read.matrix.m; + read.translation = vec3{ m[12], m[13], m[14] }; + val x := vec3{ m[0], m[1], m[2] }; + val y := vec3{ m[4], m[5], m[6] }; + val z := vec3{ m[8], m[9], m[10] }; + var sx := x.length; + val sy := y.length; + val sz := z.length; + if x.cross(y).dot(z) < 0 { + sx = -sx; + } + read.scale = vec3{ sx, sy, sz }; + if sx == 0 || sy == 0 || sz == 0 { + read.rotation = quat::identity; + return; + } + read.rotation = quat::of_basis(x / sx, y / sy, z / sz).normalized(); +} + +#! Where a node is in the world: its matrix, by its parent's, by its parent's, +#! up to its root. +#! @param this The asset. +#! @param which The node. +#! @returns The matrix taking its space to its scene's. +pub def asset::world_matrix(&this, which: u64): mat4 { + var made := this.nodes[which].matrix; + var at := which; + while this.nodes[at].parent is some(up) { + made = this.nodes[up].matrix * made; + at = up; + } + return made; +} + +#! The nodes at the roots of the tree: those of no parent, in the order the +#! asset holds them, as a scene of every one would hold them. +pub def asset::roots(&this): vector { + var made := vector::::new(); + for i in 0..this.nodes.length { + if this.nodes[i].parent is none { + made.append(i); + } + } + return made; +} diff --git a/gltf/parse.sakura b/gltf/parse.sakura new file mode 100644 index 0000000..8fbdfcd --- /dev/null +++ b/gltf/parse.sakura @@ -0,0 +1,630 @@ +#! Contains reading an asset's JSON into its parts, in the order they need one +#! another: its buffers and their bytes, the views of them, the accessors of +#! those, each checked to lie within its view, then images, samplers, textures, +#! materials, meshes, cameras, lights, skins, the nodes and their tree, scenes, +#! and animations. + +import std::json; +import std::math; +import malunal::linear; +module malunal::gltf; + +# How many of each part the JSON holds, so an index is checked as it's read, +# whichever comes first. +struct counts { + var nodes: u64; + var meshes: u64; + var materials: u64; + var textures: u64; + var samplers: u64; + var images: u64; + var accessors: u64; + var views: u64; + var buffers: u64; + var cameras: u64; + var skins: u64; + var lights: u64; +} + +# Reads an asset of its JSON, the binary chunk of its `.glb` file where it has +# one, and the folder its files are found in. +def read_json(text: strview, bin: span, has_bin: bool, folder: strview): result { + val doc := json::parse(text) else (e) { + val why := e.describe(); + return failed(failure::malformed, $"Its JSON isn't JSON: {why.span}".span); + }; + val root := doc.root; + return failed(failure::malformed, "Its JSON isn't an object.") if root.kind != json::kind::object; + var made := asset{}; + + val info := object_member(&root, "asset", "asset") else (e) { return e; }; + val about := info else { return failed(failure::malformed, "It says no asset, of which version of glTF it is."); }; + made.version = text_member(&about, "version", "asset") else (e) { return e; }; + made.generator = text_member(&about, "generator", "asset") else (e) { return e; }; + return failed(failure::unsupported, $"It's of glTF {made.version.span}, not 2.".span) if !made.version.span.starts_with("2."); + + val used := array_member(&root, "extensionsUsed", "extensionsUsed") else (e) { return e; }; + if used is some(list) { + for i in 0..list.length { + if list.at(i) is some(each) && each.as_text() is value(name) { + made.extensions.append(string::from(name, nothing{})); + } + } + } + val required := array_member(&root, "extensionsRequired", "extensionsRequired") else (e) { return e; }; + if required is some(list) { + for i in 0..list.length { + val each := list.at(i) else { break; }; + val name := each.as_text() else (_) { return failed(failure::malformed, "extensionsRequired: it holds what isn't text."); }; + return failed(failure::unsupported, $"It requires {name}, which isn't read.".span) if !is_read(name); + } + } + + val n := counts{ + nodes = length_of(&root, "nodes"), meshes = length_of(&root, "meshes"), materials = length_of(&root, "materials"), + textures = length_of(&root, "textures"), samplers = length_of(&root, "samplers"), images = length_of(&root, "images"), + accessors = length_of(&root, "accessors"), views = length_of(&root, "bufferViews"), buffers = length_of(&root, "buffers"), + cameras = length_of(&root, "cameras"), skins = length_of(&root, "skins"), lights = light_count(&root), + }; + read_buffers(&mut made, &root, bin, has_bin, folder) else (e) { return e; }; + read_views(&mut made, &root, &n) else (e) { return e; }; + read_accessors(&mut made, &root, &n) else (e) { return e; }; + read_images(&mut made, &root, &n, folder) else (e) { return e; }; + read_samplers(&mut made, &root) else (e) { return e; }; + read_textures(&mut made, &root, &n) else (e) { return e; }; + read_materials(&mut made, &root, &n) else (e) { return e; }; + read_meshes(&mut made, &root, &n) else (e) { return e; }; + read_cameras(&mut made, &root) else (e) { return e; }; + read_lights(&mut made, &root) else (e) { return e; }; + read_skins(&mut made, &root, &n) else (e) { return e; }; + read_nodes(&mut made, &root, &n) else (e) { return e; }; + read_scenes(&mut made, &root, &n) else (e) { return e; }; + read_animations(&mut made, &root, &n) else (e) { return e; }; + made.scene = index_member(&root, "scene", "scene", made.scenes.length, "scenes") else (e) { return e; }; + return made; +} + +# Whether an extension is among those read. +def is_read(name: strview): bool { + for each in extensions_read { + return true if each == name; + } + return false; +} + +# The lights `KHR_lights_punctual` gives, where it gives them. +def lights_of(root: &json::value): maybe { + val extensions := member_of(root, "extensions") else { return nothing{}; }; + val lights := member_of(&extensions, "KHR_lights_punctual") else { return nothing{}; }; + return member_of(&lights, "lights"); +} + +def light_count(root: &json::value): u64 { + if lights_of(root) is some(list) { + return list.length if list.kind == json::kind::array; + } + return 0; +} + +def read_buffers(made: &mut asset, root: &json::value, bin: span, has_bin: bool, folder: strview): result { + val found := array_member(root, "buffers", "buffers") else (e) { return e; }; + val list := found else { return; }; + for i in 0..list.length { + val site := $"buffers[{i}]"; + val each := object_at(&list, i, site.span) else (e) { return e; }; + var read := buffer{}; + read.name = text_member(&each, "name", site.span) else (e) { return e; }; + read.uri = text_member(&each, "uri", site.span) else (e) { return e; }; + read.length = needed_count(&each, "byteLength", site.span) else (e) { return e; }; + if read.uri.length != 0 { + var mime := string::new(nothing{}); + read.bytes = bytes_of_uri(read.uri.span, folder, site.span, &mut mime) else (e) { return e; }; + } else if i == 0 && has_bin { + read.bytes.extend(bin); + } else { + return wrong(site.span, "it has no URI, and isn't a .glb file's binary chunk"); + } + return wrong(site.span, $"it says it's {read.length} bytes, but it's {read.bytes.length}".span) if read.bytes.length < read.length; + made.buffers.append(move(read)); + } + return; +} + +def read_views(made: &mut asset, root: &json::value, n: &counts): result { + val found := array_member(root, "bufferViews", "bufferViews") else (e) { return e; }; + val list := found else { return; }; + for i in 0..list.length { + val site := $"bufferViews[{i}]"; + val each := object_at(&list, i, site.span) else (e) { return e; }; + var read := buffer_view{}; + read.name = text_member(&each, "name", site.span) else (e) { return e; }; + read.buffer = needed_index(&each, "buffer", site.span, n.buffers, "buffers") else (e) { return e; }; + read.offset = count_member(&each, "byteOffset", site.span, 0) else (e) { return e; }; + read.length = needed_count(&each, "byteLength", site.span) else (e) { return e; }; + read.stride = count_member(&each, "byteStride", site.span, 0) else (e) { return e; }; + val held := made.buffers[read.buffer].length; + return wrong(site.span, $"it reaches byte {read.offset + read.length} of its buffer's {held}".span) if read.offset > held || read.length > held - read.offset; + return wrong(site.span, $"its byteStride is {read.stride}, not a multiple of 4 from 4 to 252".span) + if read.stride != 0 && (read.stride < 4 || read.stride > 252 || read.stride % 4 != 0); + made.views.append(move(read)); + } + return; +} + +# The type of an accessor's numbers, by glTF's code for it. +def component_of(code: u64): maybe { + return match code { + 5120 => component::byte, + 5121 => component::unsigned_byte, + 5122 => component::short, + 5123 => component::unsigned_short, + 5125 => component::unsigned_int, + 5126 => component::float, + else => nothing{}, + }; +} + +# What an accessor's elements are, by glTF's name for it. +def element_of(name: strview): maybe { + return element::scalar if name == "SCALAR"; + return element::vec2 if name == "VEC2"; + return element::vec3 if name == "VEC3"; + return element::vec4 if name == "VEC4"; + return element::mat2 if name == "MAT2"; + return element::mat3 if name == "MAT3"; + return element::mat4 if name == "MAT4"; + return nothing{}; +} + +def read_accessors(made: &mut asset, root: &json::value, n: &counts): result { + val found := array_member(root, "accessors", "accessors") else (e) { return e; }; + val list := found else { return; }; + for i in 0..list.length { + val site := $"accessors[{i}]"; + val each := object_at(&list, i, site.span) else (e) { return e; }; + var read := accessor{}; + read.name = text_member(&each, "name", site.span) else (e) { return e; }; + read.view = index_member(&each, "bufferView", site.span, n.views, "bufferViews") else (e) { return e; }; + read.offset = count_member(&each, "byteOffset", site.span, 0) else (e) { return e; }; + val code := needed_count(&each, "componentType", site.span) else (e) { return e; }; + read.component_type = component_of(code) else { return wrong(site.span, $"its componentType {code} is none of glTF's".span); }; + read.normalized = bool_member(&each, "normalized", site.span, false) else (e) { return e; }; + read.count = needed_count(&each, "count", site.span) else (e) { return e; }; + return wrong(site.span, "its count is 0") if read.count == 0; + val kind := text_member(&each, "type", site.span) else (e) { return e; }; + read.kind = element_of(kind.span) else { return wrong(site.span, $"its type {kind.span} is none of glTF's".span); }; + read.min = reals_member(&each, "min", site.span) else (e) { return e; }; + read.max = reals_member(&each, "max", site.span) else (e) { return e; }; + if read.view is some(v) { + val view := &made.views[v]; + val size := read.element_bytes(); + return wrong(site.span, $"its bufferView's byteStride, {view.stride}, is less than an element's {size} bytes".span) + if view.stride != 0 && view.stride < size; + val stride := view.stride != 0 ? view.stride : size; + return wrong(site.span, $"its {read.count} elements reach past its bufferView's {view.length} bytes".span) + if read.offset > view.length || (read.count - 1) * stride + size > view.length - read.offset; + } + val holds_sparse := object_member(&each, "sparse", site.span) else (e) { return e; }; + if holds_sparse is some(s) { + read.sparse = read_sparse(made, &s, &read, $"{site.span}.sparse".span, n) else (e) { return e; }; + } + made.accessors.append(move(read)); + } + return; +} + +# An accessor's sparse values: where their indices and values are, each +# checked to lie within its view, and each index to name an element. +def read_sparse(made: &asset, s: &json::value, read: &accessor, site: strview, n: &counts): result { + var held := sparse{}; + held.count = needed_count(s, "count", site) else (e) { return e; }; + return wrong(site, $"its count is {held.count}, of the accessor's {read.count}".span) if held.count == 0 || held.count > read.count; + val indices_found := object_member(s, "indices", site) else (e) { return e; }; + val indices := indices_found else { return wrong(site, "it has no indices"); }; + val values_found := object_member(s, "values", site) else (e) { return e; }; + val values := values_found else { return wrong(site, "it has no values"); }; + held.indices_view = needed_index(&indices, "bufferView", site, n.views, "bufferViews") else (e) { return e; }; + held.indices_offset = count_member(&indices, "byteOffset", site, 0) else (e) { return e; }; + val code := needed_count(&indices, "componentType", site) else (e) { return e; }; + held.indices_type = component_of(code) else { return wrong(site, $"its indices' componentType {code} is none of glTF's".span); }; + return wrong(site, "its indices aren't of unsigned integers") + if held.indices_type != component::unsigned_byte && held.indices_type != component::unsigned_short && held.indices_type != component::unsigned_int; + held.values_view = needed_index(&values, "bufferView", site, n.views, "bufferViews") else (e) { return e; }; + held.values_offset = count_member(&values, "byteOffset", site, 0) else (e) { return e; }; + + val index_view := &made.views[held.indices_view]; + val value_view := &made.views[held.values_view]; + val index_bytes := held.count * held.indices_type.bytes; + val value_bytes := held.count * read.element_bytes(); + return wrong(site, "its indices reach past their bufferView") if held.indices_offset > index_view.length || index_bytes > index_view.length - held.indices_offset; + return wrong(site, "its values reach past their bufferView") if held.values_offset > value_view.length || value_bytes > value_view.length - held.values_offset; + val bytes := made.buffers[index_view.buffer].bytes.span; + for i in 0..held.count { + val e := integer_at(bytes, index_view.offset + held.indices_offset + i * held.indices_type.bytes, held.indices_type); + return wrong(site, $"its index {e} is past the accessor's {read.count} elements".span) if e >= read.count; + } + return held; +} + +def read_images(made: &mut asset, root: &json::value, n: &counts, folder: strview): result { + val found := array_member(root, "images", "images") else (e) { return e; }; + val list := found else { return; }; + for i in 0..list.length { + val site := $"images[{i}]"; + val each := object_at(&list, i, site.span) else (e) { return e; }; + var read := image{}; + read.name = text_member(&each, "name", site.span) else (e) { return e; }; + read.uri = text_member(&each, "uri", site.span) else (e) { return e; }; + read.mime_type = text_member(&each, "mimeType", site.span) else (e) { return e; }; + read.view = index_member(&each, "bufferView", site.span, n.views, "bufferViews") else (e) { return e; }; + if read.uri.length != 0 { + var mime := string::new(nothing{}); + read.bytes = bytes_of_uri(read.uri.span, folder, site.span, &mut mime) else (e) { return e; }; + if read.mime_type.length == 0 { + read.mime_type = move(mime); + } + } else if read.view is some(v) { + val view := &made.views[v]; + read.bytes.extend(made.buffers[view.buffer].bytes.span[view.offset:view.length]); + } else { + return wrong(site.span, "it has neither a URI nor a bufferView"); + } + made.images.append(move(read)); + } + return; +} + +def read_samplers(made: &mut asset, root: &json::value): result { + val found := array_member(root, "samplers", "samplers") else (e) { return e; }; + val list := found else { return; }; + for i in 0..list.length { + val site := $"samplers[{i}]"; + val each := object_at(&list, i, site.span) else (e) { return e; }; + var read := sampler{}; + read.name = text_member(&each, "name", site.span) else (e) { return e; }; + val mag := count_member(&each, "magFilter", site.span, 0) else (e) { return e; }; + val min := count_member(&each, "minFilter", site.span, 0) else (e) { return e; }; + val s := count_member(&each, "wrapS", site.span, 10497) else (e) { return e; }; + val t := count_member(&each, "wrapT", site.span, 10497) else (e) { return e; }; + read.mag_filter = mag == 9728 ? filter::nearest : mag == 9729 ? filter::linear : filter::unset; + # 9984 to 9987: nearest or linear, between the nearest mip level or two. + read.min_filter = min == 9728 || min == 9984 || min == 9986 ? filter::nearest : min == 9729 || min == 9985 || min == 9987 ? filter::linear : filter::unset; + read.mip_filter = min == 9984 || min == 9985 ? filter::nearest : min == 9986 || min == 9987 ? filter::linear : filter::unset; + read.wrap_s = wrap_of(s) else { return wrong(site.span, $"its wrapS {s} is none of glTF's".span); }; + read.wrap_t = wrap_of(t) else { return wrong(site.span, $"its wrapT {t} is none of glTF's".span); }; + made.samplers.append(move(read)); + } + return; +} + +def wrap_of(code: u64): maybe { + return match code { + 10497 => wrap::repeat, + 33071 => wrap::clamp, + 33648 => wrap::mirror, + else => nothing{}, + }; +} + +def read_textures(made: &mut asset, root: &json::value, n: &counts): result { + val found := array_member(root, "textures", "textures") else (e) { return e; }; + val list := found else { return; }; + for i in 0..list.length { + val site := $"textures[{i}]"; + val each := object_at(&list, i, site.span) else (e) { return e; }; + var read := texture{}; + read.name = text_member(&each, "name", site.span) else (e) { return e; }; + read.sampler = index_member(&each, "sampler", site.span, n.samplers, "samplers") else (e) { return e; }; + read.source = index_member(&each, "source", site.span, n.images, "images") else (e) { return e; }; + made.textures.append(move(read)); + } + return; +} + +# A texture a material names, where it names one, and its scale or strength. +def texture_member(v: &json::value, key: strview, site: strview, n: &counts, scale_key: strview): result, gltf_error> { + var none: maybe = nothing{}; + val found := object_member(v, key, site) else (e) { return e; }; + val info := found else { return none; }; + val inner := $"{site}.{key}"; + var made := texture_ref{}; + made.texture = needed_index(&info, "index", inner.span, n.textures, "textures") else (e) { return e; }; + made.set = count_member(&info, "texCoord", inner.span, 0) else (e) { return e; }; + if scale_key.length != 0 { + made.scale = float_member(&info, scale_key, inner.span, 1) else (e) { return e; }; + } + val held: maybe = made; + return held; +} + +def read_materials(made: &mut asset, root: &json::value, n: &counts): result { + val found := array_member(root, "materials", "materials") else (e) { return e; }; + val list := found else { return; }; + for i in 0..list.length { + val site := $"materials[{i}]"; + val each := object_at(&list, i, site.span) else (e) { return e; }; + var read := material{}; + read.name = text_member(&each, "name", site.span) else (e) { return e; }; + val pbr_found := object_member(&each, "pbrMetallicRoughness", site.span) else (e) { return e; }; + if pbr_found is some(pbr) { + val inner := $"{site.span}.pbrMetallicRoughness"; + val color := floats_member(&pbr, "baseColorFactor", inner.span, 4) else (e) { return e; }; + if color.length == 4 { + read.base_color = [color[0], color[1], color[2], color[3]]; + } + read.base_color_texture = texture_member(&pbr, "baseColorTexture", inner.span, n, "") else (e) { return e; }; + read.metallic = float_member(&pbr, "metallicFactor", inner.span, 1) else (e) { return e; }; + read.roughness = float_member(&pbr, "roughnessFactor", inner.span, 1) else (e) { return e; }; + read.metallic_roughness_texture = texture_member(&pbr, "metallicRoughnessTexture", inner.span, n, "") else (e) { return e; }; + } + read.normal_texture = texture_member(&each, "normalTexture", site.span, n, "scale") else (e) { return e; }; + read.occlusion_texture = texture_member(&each, "occlusionTexture", site.span, n, "strength") else (e) { return e; }; + read.emissive_texture = texture_member(&each, "emissiveTexture", site.span, n, "") else (e) { return e; }; + val emissive := floats_member(&each, "emissiveFactor", site.span, 3) else (e) { return e; }; + if emissive.length == 3 { + read.emissive = [emissive[0], emissive[1], emissive[2]]; + } + val mode := text_member(&each, "alphaMode", site.span) else (e) { return e; }; + if mode.span == "MASK" { + read.alpha_mode = alpha_mode::mask; + } else if mode.span == "BLEND" { + read.alpha_mode = alpha_mode::blend; + } else if mode.length != 0 && mode.span != "OPAQUE" { + return wrong(site.span, $"its alphaMode {mode.span} is none of glTF's".span); + } + read.alpha_cutoff = float_member(&each, "alphaCutoff", site.span, 0.5) else (e) { return e; }; + read.double_sided = bool_member(&each, "doubleSided", site.span, false) else (e) { return e; }; + val extensions := object_member(&each, "extensions", site.span) else (e) { return e; }; + if extensions is some(x) { + read.unlit = member_of(&x, "KHR_materials_unlit") is some(_); + if member_of(&x, "KHR_materials_emissive_strength") is some(strength) { + val by := float_member(&strength, "emissiveStrength", site.span, 1) else (e) { return e; }; + read.emissive = [read.emissive[0] * by, read.emissive[1] * by, read.emissive[2] * by]; + } + } + made.materials.append(move(read)); + } + return; +} + +# A primitive's attributes, or a morph target's, each naming an accessor. +def attributes_of(v: &json::value, site: strview, n: &counts): result, gltf_error> { + var made := vector::::new(); + for each in v.members() { + val index := each.value.as_u64() else (_) { return wrong(site, $"its {each.key} isn't an accessor's index".span); }; + return wrong(site, $"its {each.key} is {index}, of the {n.accessors} accessors there are".span) if index >= n.accessors; + made.append(attribute{ name = string::from(each.key, nothing{}), accessor = index }); + } + return made; +} + +def read_meshes(made: &mut asset, root: &json::value, n: &counts): result { + val found := array_member(root, "meshes", "meshes") else (e) { return e; }; + val list := found else { return; }; + for i in 0..list.length { + val site := $"meshes[{i}]"; + val each := object_at(&list, i, site.span) else (e) { return e; }; + var read := mesh{}; + read.name = text_member(&each, "name", site.span) else (e) { return e; }; + read.weights = floats_member(&each, "weights", site.span, 0) else (e) { return e; }; + val parts_found := array_member(&each, "primitives", site.span) else (e) { return e; }; + val parts := parts_found else { return wrong(site.span, "it has no primitives"); }; + return wrong(site.span, "it has no primitives") if parts.length == 0; + for k in 0..parts.length { + val inner := $"{site.span}.primitives[{k}]"; + val part := object_at(&parts, k, inner.span) else (e) { return e; }; + var drawn := read_primitive(made, &part, inner.span, n) else (e) { return e; }; + read.primitives.append(move(drawn)); + } + made.meshes.append(move(read)); + } + return; +} + +# A primitive, its accessors checked: its attributes of one count, and its +# indices whole numbers naming vertices it has. +def read_primitive(made: &asset, v: &json::value, site: strview, n: &counts): result { + var read := primitive{}; + val held := object_member(v, "attributes", site) else (e) { return e; }; + val attributes := held else { return wrong(site, "it has no attributes"); }; + read.attributes = attributes_of(&attributes, site, n) else (e) { return e; }; + read.indices = index_member(v, "indices", site, n.accessors, "accessors") else (e) { return e; }; + read.material = index_member(v, "material", site, n.materials, "materials") else (e) { return e; }; + val mode := count_member(v, "mode", site, 4) else (e) { return e; }; + val modes: topology[7] = [ + topology::points, topology::lines, topology::line_loop, topology::line_strip, + topology::triangles, topology::triangle_strip, topology::triangle_fan, + ]; + return wrong(site, $"its mode {mode} is none of glTF's".span) if mode > 6; + read.mode = modes[mode]; + val targets_found := array_member(v, "targets", site) else (e) { return e; }; + if targets_found is some(targets) { + for t in 0..targets.length { + val inner := $"{site}.targets[{t}]"; + val target := object_at(&targets, t, inner.span) else (e) { return e; }; + var moved := attributes_of(&target, inner.span, n) else (e) { return e; }; + read.targets.append(move(moved)); + } + } + + var vertices: u64 = 0; + for i in 0..read.attributes.length { + val count := made.accessors[read.attributes[i].accessor].count; + return wrong(site, $"its {read.attributes[i].name.span} has {count} elements, of the other attributes' {vertices}".span) + if vertices != 0 && count != vertices; + vertices = count; + } + if read.indices is some(at) { + val list := &made.accessors[at]; + return wrong(site, "its indices are of other than unsigned integers, one each") + if list.kind != element::scalar || list.normalized + || (list.component_type != component::unsigned_byte && list.component_type != component::unsigned_short && list.component_type != component::unsigned_int); + if vertices != 0 { + val indices := made.integers(at); + for i in 0..indices.length { + return wrong(site, $"its index {indices[i]} is past its {vertices} vertices".span) if indices[i] as u64 >= vertices; + } + } + } + return read; +} + +def read_cameras(made: &mut asset, root: &json::value): result { + val found := array_member(root, "cameras", "cameras") else (e) { return e; }; + val list := found else { return; }; + for i in 0..list.length { + val site := $"cameras[{i}]"; + val each := object_at(&list, i, site.span) else (e) { return e; }; + var read := camera{}; + read.name = text_member(&each, "name", site.span) else (e) { return e; }; + val kind := text_member(&each, "type", site.span) else (e) { return e; }; + if kind.span == "perspective" { + val held := object_member(&each, "perspective", site.span) else (e) { return e; }; + val p := held else { return wrong(site.span, "it's a perspective but says none"); }; + read.fov_y = float_member(&p, "yfov", site.span, 0) else (e) { return e; }; + read.aspect = maybe_number(&p, "aspectRatio", site.span) else (e) { return e; }; + read.near = float_member(&p, "znear", site.span, 0) else (e) { return e; }; + read.far = maybe_number(&p, "zfar", site.span) else (e) { return e; }; + } else if kind.span == "orthographic" { + read.kind = camera_kind::orthographic; + val held := object_member(&each, "orthographic", site.span) else (e) { return e; }; + val o := held else { return wrong(site.span, "it's orthographic but says nothing of it"); }; + read.x_mag = float_member(&o, "xmag", site.span, 1) else (e) { return e; }; + read.y_mag = float_member(&o, "ymag", site.span, 1) else (e) { return e; }; + read.near = float_member(&o, "znear", site.span, 0) else (e) { return e; }; + read.far = maybe_number(&o, "zfar", site.span) else (e) { return e; }; + } else { + return wrong(site.span, $"its type {kind.span} is none of glTF's".span); + } + made.cameras.append(move(read)); + } + return; +} + +def read_lights(made: &mut asset, root: &json::value): result { + val list := lights_of(root) else { return; }; + return failed(failure::malformed, "KHR_lights_punctual: its lights aren't an array.") if list.kind != json::kind::array; + for i in 0..list.length { + val site := $"KHR_lights_punctual.lights[{i}]"; + val each := object_at(&list, i, site.span) else (e) { return e; }; + var read := light{}; + read.name = text_member(&each, "name", site.span) else (e) { return e; }; + val kind := text_member(&each, "type", site.span) else (e) { return e; }; + if kind.span == "directional" { + read.kind = light_kind::directional; + } else if kind.span == "spot" { + read.kind = light_kind::spot; + } else if kind.span != "point" { + return wrong(site.span, $"its type {kind.span} is none of the extension's".span); + } + val color := floats_member(&each, "color", site.span, 3) else (e) { return e; }; + if color.length == 3 { + read.color = [color[0], color[1], color[2]]; + } + read.intensity = float_member(&each, "intensity", site.span, 1) else (e) { return e; }; + read.range = maybe_number(&each, "range", site.span) else (e) { return e; }; + val cone := object_member(&each, "spot", site.span) else (e) { return e; }; + if cone is some(s) { + read.inner_cone = float_member(&s, "innerConeAngle", site.span, 0) else (e) { return e; }; + read.outer_cone = float_member(&s, "outerConeAngle", site.span, 0.7853981633974483) else (e) { return e; }; + } + made.lights.append(move(read)); + } + return; +} + +def read_skins(made: &mut asset, root: &json::value, n: &counts): result { + val found := array_member(root, "skins", "skins") else (e) { return e; }; + val list := found else { return; }; + for i in 0..list.length { + val site := $"skins[{i}]"; + val each := object_at(&list, i, site.span) else (e) { return e; }; + var read := skin{}; + read.name = text_member(&each, "name", site.span) else (e) { return e; }; + read.joints = indices_member(&each, "joints", site.span, n.nodes, "nodes") else (e) { return e; }; + return wrong(site.span, "it has no joints") if read.joints.length == 0; + read.inverse_binds = index_member(&each, "inverseBindMatrices", site.span, n.accessors, "accessors") else (e) { return e; }; + read.skeleton = index_member(&each, "skeleton", site.span, n.nodes, "nodes") else (e) { return e; }; + if read.inverse_binds is some(at) { + val binds := &made.accessors[at]; + return wrong(site.span, "its inverseBindMatrices aren't a matrix of floats for each joint") + if binds.kind != element::mat4 || binds.component_type != component::float || binds.count < read.joints.length; + } + made.skins.append(move(read)); + } + return; +} + +def read_scenes(made: &mut asset, root: &json::value, n: &counts): result { + val found := array_member(root, "scenes", "scenes") else (e) { return e; }; + val list := found else { return; }; + for i in 0..list.length { + val site := $"scenes[{i}]"; + val each := object_at(&list, i, site.span) else (e) { return e; }; + var read := scene{}; + read.name = text_member(&each, "name", site.span) else (e) { return e; }; + read.nodes = indices_member(&each, "nodes", site.span, n.nodes, "nodes") else (e) { return e; }; + for k in 0..read.nodes.length { + return wrong(site.span, $"its node {read.nodes[k]} is another's child, not a root".span) if made.nodes[read.nodes[k]].parent is some(_); + } + made.scenes.append(move(read)); + } + return; +} + +def read_animations(made: &mut asset, root: &json::value, n: &counts): result { + val found := array_member(root, "animations", "animations") else (e) { return e; }; + val list := found else { return; }; + for i in 0..list.length { + val site := $"animations[{i}]"; + val each := object_at(&list, i, site.span) else (e) { return e; }; + var read := animation{}; + read.name = text_member(&each, "name", site.span) else (e) { return e; }; + val samplers_found := array_member(&each, "samplers", site.span) else (e) { return e; }; + val samplers := samplers_found else { return wrong(site.span, "it has no samplers"); }; + for k in 0..samplers.length { + val inner := $"{site.span}.samplers[{k}]"; + val s := object_at(&samplers, k, inner.span) else (e) { return e; }; + var keys := animation_sampler{}; + keys.input = needed_index(&s, "input", inner.span, n.accessors, "accessors") else (e) { return e; }; + keys.output = needed_index(&s, "output", inner.span, n.accessors, "accessors") else (e) { return e; }; + val how := text_member(&s, "interpolation", inner.span) else (e) { return e; }; + if how.span == "STEP" { + keys.interpolation = interpolation::step; + } else if how.span == "CUBICSPLINE" { + keys.interpolation = interpolation::cubic_spline; + } else if how.length != 0 && how.span != "LINEAR" { + return wrong(inner.span, $"its interpolation {how.span} is none of glTF's".span); + } + val times := &made.accessors[keys.input]; + return wrong(inner.span, "its input isn't of floats, one each") if times.kind != element::scalar || times.component_type != component::float; + read.samplers.append(keys); + } + val channels_found := array_member(&each, "channels", site.span) else (e) { return e; }; + val channels := channels_found else { return wrong(site.span, "it has no channels"); }; + for k in 0..channels.length { + val inner := $"{site.span}.channels[{k}]"; + val c := object_at(&channels, k, inner.span) else (e) { return e; }; + var moved := channel{}; + moved.sampler = needed_index(&c, "sampler", inner.span, read.samplers.length, "samplers") else (e) { return e; }; + val target_found := object_member(&c, "target", inner.span) else (e) { return e; }; + val target := target_found else { return wrong(inner.span, "it has no target"); }; + moved.node = index_member(&target, "node", inner.span, n.nodes, "nodes") else (e) { return e; }; + val path := text_member(&target, "path", inner.span) else (e) { return e; }; + if path.span == "translation" { + moved.path = target_path::translation; + } else if path.span == "rotation" { + moved.path = target_path::rotation; + } else if path.span == "scale" { + moved.path = target_path::scale; + } else if path.span == "weights" { + moved.path = target_path::weights; + } else { + return wrong(inner.span, $"its path {path.span} is none of glTF's".span); + } + read.channels.append(moved); + } + made.animations.append(move(read)); + } + return; +} diff --git a/gltf/parts.sakura b/gltf/parts.sakura new file mode 100644 index 0000000..0c526a5 --- /dev/null +++ b/gltf/parts.sakura @@ -0,0 +1,243 @@ +#! Contains the parts of an asset, as glTF lays them out: scenes and their nodes, +#! meshes and their primitives, materials, textures, samplers, images, cameras, +#! skins, animations, and lights, each with glTF's defaults where its JSON +#! leaves a member out. + +import malunal::linear; +module malunal::gltf; + +#! A scene: the nodes at its roots. +pub struct scene { + pub var name: string; + pub var nodes: vector; +} + +#! A node of the tree a scene holds: where it is within its parent, and what's +#! there, a mesh, a camera, a light, or nothing but its children. +pub struct node { + pub var name: string; + pub var children: vector; + #! The node it's a child of, or none at a root. + pub var parent: maybe; + pub var mesh: maybe; + pub var camera: maybe; + #! The skin its mesh is bound to. + pub var skin: maybe; + #! Its light, of `KHR_lights_punctual`. + pub var light: maybe; + #! Where it is within its parent: its translation, rotation, and scale, and + #! the matrix of them, whichever the JSON gave, the other worked out of it. + pub var translation := vec3::zero; + pub var rotation := quat::identity; + pub var scale := vec3::one; + pub var matrix := mat4::identity; + #! The weights of its mesh's morph targets, where it gives its own. + pub var weights: vector; +} + +#! What a primitive's vertices make. +pub enum topology: u8 { points, lines, line_loop, line_strip, triangles, triangle_strip, triangle_fan } + +#! An attribute of a primitive's vertices: its name, as `POSITION`, `NORMAL`, +#! `TEXCOORD_0`, or `COLOR_0`, and the accessor holding it. +pub struct attribute { + pub var name: string; + pub var accessor: u64; +} + +#! A part of a mesh drawn at once: its vertices' attributes, the indices of +#! them it draws, or none to draw them in order, and its material. +pub struct primitive { + pub var attributes: vector; + pub var indices: maybe; + #! Its material, or none for glTF's default: white, not metallic, rough. + pub var material: maybe; + pub var mode := topology::triangles; + #! Its morph targets, each the attributes it moves. + pub var targets: vector>; +} + +#! The accessor of an attribute of a primitive, by its name, where it has it. +pub def primitive::find(&this, name: strview): maybe { + for i in 0..this.attributes.length { + return this.attributes[i].accessor if this.attributes[i].name.span == name; + } + return nothing{}; +} + +#! A mesh: its primitives, each drawn with its own material. +pub struct mesh { + pub var name: string; + pub var primitives: vector; + #! The weights of its morph targets, where it gives them. + pub var weights: vector; +} + +#! A texture as a material samples it: which, by which of its primitives' +#! `TEXCOORD_n`, and, of a normal map, its scale, or of occlusion, its strength. +pub struct texture_ref { + pub var texture: u64; + pub var set: u64; + pub var scale: f32 = 1; +} + +#! How a material's alpha is taken. +pub enum alpha_mode: u8 { + #! Not at all: it's opaque. + opaque, + #! As a cutout: opaque where alpha is at least its cutoff, and not drawn where + #! it's below. + mask, + #! Blended over what's behind it. + blend, +} + +#! A material, of glTF's metallic and rough model. Its colors are linear, as +#! glTF's factors are, and its textures of color are sRGB, as glTF's images are. +pub struct material { + pub var name: string; + #! The color its base color texture is multiplied by, and alpha. + pub var base_color: f32[4] = [1, 1, 1, 1]; + pub var base_color_texture: maybe; + pub var metallic: f32 = 1; + pub var roughness: f32 = 1; + #! Its roughness in green and metalness in blue. + pub var metallic_roughness_texture: maybe; + #! Its normal map: which way each texel faces, across the surface's tangent + #! and the way up its texture, as OpenGL's normal maps hold it. + pub var normal_texture: maybe; + #! How much light reaches it, in red. + pub var occlusion_texture: maybe; + #! The light it gives, by `KHR_materials_emissive_strength` where it says. + pub var emissive: f32[3]; + pub var emissive_texture: maybe; + pub var alpha_mode := alpha_mode::opaque; + pub var alpha_cutoff: f32 = 0.5; + #! Whether its faces are seen from behind too. + pub var double_sided: bool; + #! Whether it's drawn as its colors are, unlit, by `KHR_materials_unlit`. + pub var unlit: bool; +} + +#! A texture: an image, sampled by a sampler, or by repeating and blending +#! where it names none. +pub struct texture { + pub var name: string; + pub var sampler: maybe; + pub var source: maybe; +} + +#! How a sampler picks between texels, where it says. +pub enum filter: u8 { unset, nearest, linear } + +#! What a sampler reads past a texture's edge. +pub enum wrap: u8 { repeat, clamp, mirror } + +#! How a texture is sampled. +pub struct sampler { + pub var name: string; + pub var mag_filter: filter; + pub var min_filter: filter; + #! Between mip levels, where the minifying filter uses them; unset where it + #! doesn't. + pub var mip_filter: filter; + pub var wrap_s := wrap::repeat; + pub var wrap_t := wrap::repeat; +} + +#! An image, encoded as its file is, PNG or JPEG: its bytes, read from its file, +#! a `data:` URI, or a buffer view. +pub struct image { + pub var name: string; + #! Its URI, as the JSON writes it, or empty where it's in a buffer view. + pub var uri: string; + #! Its buffer view, where it's in one. + pub var view: maybe; + #! Its type, as `image/png`, where the JSON or its `data:` URI says. + pub var mime_type: string; + pub var bytes: vector; +} + +#! How a camera projects. +pub enum camera_kind: u8 { perspective, orthographic } + +#! A camera, looking down its node's -z. +pub struct camera { + pub var name: string; + pub var kind := camera_kind::perspective; + #! Of a perspective: how far it sees up and down, in radians, and its width + #! by its height, where it says. + pub var fov_y: f32; + pub var aspect: maybe; + #! Of an orthographic one: half its width and half its height. + pub var x_mag: f32; + pub var y_mag: f32; + pub var near: f32; + #! The furthest it draws, or none, of a perspective, for no end. + pub var far: maybe; +} + +#! A skin: the nodes of its skeleton, its joints, and the inverses of where +#! each was as the mesh was bound to them. +pub struct skin { + pub var name: string; + pub var joints: vector; + #! An accessor of a matrix for each joint, or none for none but the identity. + pub var inverse_binds: maybe; + #! The skeleton's root, where it says. + pub var skeleton: maybe; +} + +#! What an animation's channel moves. +pub enum target_path: u8 { translation, rotation, scale, weights } + +#! How an animation's values change between its keys. +pub enum interpolation: u8 { linear, step, cubic_spline } + +#! A channel of an animation: what it moves of a node, by which of its samplers. +pub struct channel { + pub var sampler: u64; + #! The node, or none where an extension names what it moves. + pub var node: maybe; + pub var path: target_path; +} + +#! The keys of an animation: the accessor of their times, in seconds, and of +#! their values. +pub struct animation_sampler { + pub var input: u64; + pub var output: u64; + pub var interpolation := interpolation::linear; +} + +#! An animation: channels, each moving a node by a sampler's keys. +pub struct animation { + pub var name: string; + pub var channels: vector; + pub var samplers: vector; +} + +#! What a light is, of `KHR_lights_punctual`. +pub enum light_kind: u8 { + #! Shining down its node's -z, everywhere. + directional, + #! Shining every way from its node. + point, + #! Shining down its node's -z in a cone. + spot, +} + +#! A light, of `KHR_lights_punctual`: its color, linear, and its intensity, in +#! lux for a directional light and in candela for the others. +pub struct light { + pub var name: string; + pub var kind := light_kind::point; + pub var color: f32[3] = [1, 1, 1]; + pub var intensity: f32 = 1; + #! How far it reaches, or none where it reaches as far as its intensity does. + pub var range: maybe; + #! Of a spot light: the angles from its middle where it begins to dim, and + #! where it's dark, in radians. + pub var inner_cone: f32; + pub var outer_cone: f32 = 0.7853982; +} diff --git a/tests/accessors.sakura b/tests/accessors.sakura new file mode 100644 index 0000000..ddd1596 --- /dev/null +++ b/tests/accessors.sakura @@ -0,0 +1,113 @@ +#! Contains the tests of reading accessors: integers of each size, normalized +#! or not, interleaved in a view by its stride; a matrix of bytes, each column +#! begun at a multiple of 4; and sparse values, over a view's or over zeros. + +import std::io; +import std::testing; +import malunal::gltf; + +# A buffer of 68 bytes, its views as `accessors_json` names them. +def accessors_buffer(): vector { + var made := packed::new(); + # View 0, interleaved by 8: a color of normalized bytes, and two normalized + # shorts, for each of two elements. + for each in [255u, 0, 128, 255] { made.byte(each as u8); } + made.short(32767); + made.short(0x8000); + for each in [0u, 51, 255, 0] { made.byte(each as u8); } + made.short(0); + made.short(0xC000); + # View 1: signed bytes, -3 and 7. + made.byte(253); + made.byte(7); + made.align(); + # View 2: a matrix of two columns of two bytes, each column padded to 4. + for each in [1u, 2, 0, 0, 3, 4, 0, 0] { made.byte(each as u8); } + # View 3: four floats; views 4 and 5: sparse indices 3 and 1, and their values. + val four: f32[4] = [10, 20, 30, 40]; + made.floats(four[:]); + made.byte(3); + made.byte(1); + made.align(); + val two: f32[2] = [-1, -2]; + made.floats(two[:]); + # View 6: a sparse value of two floats; view 7: its index, 2, a short. + val pair: f32[2] = [5, 6]; + made.floats(pair[:]); + made.short(2); + made.align(); + return move(made.bytes); +} + +def accessors_json(uri: strview): string { + var made := string::from(""" + { + "asset": { "version": "2.0" }, + "accessors": [ + { "bufferView": 0, "componentType": 5121, "normalized": true, "count": 2, "type": "VEC4" }, + { "bufferView": 0, "byteOffset": 4, "componentType": 5122, "normalized": true, "count": 2, "type": "VEC2" }, + { "bufferView": 1, "componentType": 5120, "count": 2, "type": "SCALAR" }, + { "bufferView": 2, "componentType": 5121, "count": 1, "type": "MAT2" }, + { "bufferView": 3, "componentType": 5126, "count": 4, "type": "SCALAR", + "sparse": { "count": 2, "indices": { "bufferView": 4, "componentType": 5121 }, "values": { "bufferView": 5 } } }, + { "componentType": 5126, "count": 3, "type": "VEC2", + "sparse": { "count": 1, "indices": { "bufferView": 7, "componentType": 5123 }, "values": { "bufferView": 6 } } }, + { "bufferView": 7, "componentType": 5123, "count": 1, "type": "SCALAR" } + ], + "bufferViews": [ + { "buffer": 0, "byteOffset": 0, "byteLength": 16, "byteStride": 8 }, + { "buffer": 0, "byteOffset": 16, "byteLength": 2 }, + { "buffer": 0, "byteOffset": 20, "byteLength": 8 }, + { "buffer": 0, "byteOffset": 28, "byteLength": 16 }, + { "buffer": 0, "byteOffset": 44, "byteLength": 2 }, + { "buffer": 0, "byteOffset": 48, "byteLength": 8 }, + { "buffer": 0, "byteOffset": 56, "byteLength": 8 }, + { "buffer": 0, "byteOffset": 64, "byteLength": 2 } + ], + "buffers": [{ "byteLength": 68 + """, nothing{}); + made.append(", \"uri\": \""); + made.append(uri); + made.append("\" }] }"); + return made; +} + +# The accessors' asset, read. +def read_accessors(t: &mut tester): maybe { + val bytes := accessors_buffer(); + t.expects(bytes.length == 68); + val uri := data_uri(bytes.span); + val json := accessors_json(uri.span); + match gltf::decode(json.span) { + value(read) => return read; + error(e) => { + io::println(e.describe().span); + t.expects(false); + return nothing{}; + } + } +} + +@test def reads_numbers_of_every_size_interleaved_by_stride(t: &mut tester): void { + val read := read_accessors(t) else { return; }; + val colors := read.floats(0); + t.expects(colors.length == 8 && near(colors[0], 1) && near(colors[1], 0) && near(colors[2], 128.0 / 255) && near(colors[3], 1)); + t.expects(near(colors[4], 0) && near(colors[5], 0.2) && near(colors[6], 1) && near(colors[7], 0)); + # A normalized short's least is -1, as -32767 is. + val shorts := read.floats(1); + t.expects(shorts.length == 4 && near(shorts[0], 1) && near(shorts[1], -1) && near(shorts[2], 0) && near(shorts[3], -16384.0 / 32767)); + val signed := read.floats(2); + t.expects(signed.length == 2 && near(signed[0], -3) && near(signed[1], 7)); + val matrix := read.floats(3); + t.expects(matrix.length == 4 && near(matrix[0], 1) && near(matrix[1], 2) && near(matrix[2], 3) && near(matrix[3], 4)); + val index := read.integers(6); + t.expects(index.length == 1 && index[0] == 2); +} + +@test def puts_sparse_values_in_place(t: &mut tester): void { + val read := read_accessors(t) else { return; }; + val over_view := read.floats(4); + t.expects(over_view.length == 4 && near(over_view[0], 10) && near(over_view[1], -2) && near(over_view[2], 30) && near(over_view[3], -1)); + val over_zeros := read.floats(5); + t.expects(over_zeros.length == 6 && near(over_zeros[0], 0) && near(over_zeros[3], 0) && near(over_zeros[4], 5) && near(over_zeros[5], 6)); +} diff --git a/tests/main.sakura b/tests/main.sakura new file mode 100644 index 0000000..315f63c --- /dev/null +++ b/tests/main.sakura @@ -0,0 +1,10 @@ +#! Contains the `main` that runs gltf's tests, each in a copy of the program of +#! its own. `blossom test` runs them, and `-- --only TEXT` those whose name +#! holds the text. + +import system; +import std::testing; + +def main(args: span): void { + exit(tester::run(args)); +} diff --git a/tests/nodes.sakura b/tests/nodes.sakura new file mode 100644 index 0000000..ffe7aa1 --- /dev/null +++ b/tests/nodes.sakura @@ -0,0 +1,119 @@ +#! Contains the tests of the tree of nodes: a matrix taken apart into a +#! translation, rotation, and scale, one mirroring, those put together, and +#! where a child is in the world; and the cameras, lights, skins, and +#! animations nodes name. + +import std::io; +import std::testing; +import malunal::linear; +import malunal::gltf; + +# A buffer of two identity matrices, two times, and two translations. +def nodes_buffer(): vector { + var made := packed::new(); + val identity: f32[16] = [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1]; + made.floats(identity[:]); + made.floats(identity[:]); + val times: f32[2] = [0, 1]; + made.floats(times[:]); + val places: f32[6] = [0, 0, 3, 0, 1, 3]; + made.floats(places[:]); + return move(made.bytes); +} + +# A root turned a quarter about y, scaled by 2, and moved 1 along x, as a +# matrix; a child of it 3 along z, as a translation, with a camera and a spot +# light; a node mirrored in x; and one with a skin. +def nodes_json(uri: strview): string { + var made := string::from(""" + { + "asset": { "version": "2.0" }, + "extensionsUsed": ["KHR_lights_punctual"], + "extensions": { "KHR_lights_punctual": { "lights": [ + { "name": "lamp", "type": "spot", "color": [1, 0.5, 0], "intensity": 20, "range": 8, "spot": { "outerConeAngle": 0.5 } } + ] } }, + "scenes": [{ "nodes": [0, 2, 3] }], + "nodes": [ + { "name": "Root", "children": [1], "matrix": [0, 0, -2, 0, 0, 2, 0, 0, 2, 0, 0, 0, 1, 0, 0, 1] }, + { "name": "Child", "translation": [0, 0, 3], "camera": 0, "extensions": { "KHR_lights_punctual": { "light": 0 } } }, + { "name": "Mirror", "matrix": [-1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1] }, + { "name": "Skinned", "skin": 0 } + ], + "cameras": [ + { "type": "perspective", "perspective": { "yfov": 0.8, "znear": 0.1 } }, + { "type": "orthographic", "orthographic": { "xmag": 2, "ymag": 1, "znear": 0, "zfar": 10 } } + ], + "skins": [{ "joints": [0, 1], "inverseBindMatrices": 0 }], + "animations": [{ "name": "rise", + "channels": [{ "sampler": 0, "target": { "node": 1, "path": "translation" } }], + "samplers": [{ "input": 1, "output": 2, "interpolation": "STEP" }] + }], + "accessors": [ + { "bufferView": 0, "componentType": 5126, "count": 2, "type": "MAT4" }, + { "bufferView": 1, "componentType": 5126, "count": 2, "type": "SCALAR" }, + { "bufferView": 2, "componentType": 5126, "count": 2, "type": "VEC3" } + ], + "bufferViews": [ + { "buffer": 0, "byteOffset": 0, "byteLength": 128 }, + { "buffer": 0, "byteOffset": 128, "byteLength": 8 }, + { "buffer": 0, "byteOffset": 136, "byteLength": 24 } + ], + "buffers": [{ "byteLength": 160 + """, nothing{}); + made.append(", \"uri\": \""); + made.append(uri); + made.append("\" }] }"); + return made; +} + +def read_nodes(t: &mut tester): maybe { + val bytes := nodes_buffer(); + val uri := data_uri(bytes.span); + val json := nodes_json(uri.span); + match gltf::decode(json.span) { + value(read) => return read; + error(e) => { + io::println(e.describe().span); + t.expects(false); + return nothing{}; + } + } +} + +@test def takes_matrices_apart_and_puts_transforms_together(t: &mut tester): void { + val read := read_nodes(t) else { return; }; + val root := &read.nodes[0]; + t.expects(near(root.translation.x, 1) && near(root.translation.z, 0)); + t.expects(near(root.scale.x, 2) && near(root.scale.y, 2) && near(root.scale.z, 2)); + # A quarter turn about y. + t.expects(near(root.rotation.x, 0) && near(root.rotation.y, 0.70710677) && near(root.rotation.z, 0) && near(root.rotation.w, 0.70710677)); + val child := &read.nodes[1]; + t.expects(child.parent is some(p) && p == 0 && near(child.matrix.m[14], 3) && root.parent is none); + # Its place, 3 along z, turned to x, doubled, and moved 1 along x. + val world := read.world_matrix(1); + t.expects(near(world.m[12], 7) && near(world.m[13], 0) && near(world.m[14], 0)); + val mirror := &read.nodes[2]; + t.expects(near(mirror.scale.x, -1) && near(mirror.scale.y, 1) && near(mirror.rotation.w, 1)); + val roots := read.roots(); + t.expects(roots.length == 3 && roots[0] == 0 && roots[1] == 2 && roots[2] == 3); +} + +@test def reads_cameras_lights_skins_and_animations(t: &mut tester): void { + val read := read_nodes(t) else { return; }; + t.expects(read.cameras.length == 2 && read.nodes[1].camera is some(c) && c == 0); + val eye := &read.cameras[0]; + t.expects(eye.kind == gltf::camera_kind::perspective && near(eye.fov_y, 0.8) && eye.aspect is none && eye.far is none); + val plan := &read.cameras[1]; + t.expects(plan.kind == gltf::camera_kind::orthographic && near(plan.x_mag, 2) && plan.far is some(f) && near(f, 10)); + t.expects(read.lights.length == 1 && read.nodes[1].light is some(l) && l == 0); + val lamp := &read.lights[0]; + t.expects(lamp.kind == gltf::light_kind::spot && lamp.name.span == "lamp" && near(lamp.color[1], 0.5) && near(lamp.intensity, 20)); + t.expects(lamp.range is some(r) && near(r, 8) && near(lamp.inner_cone, 0) && near(lamp.outer_cone, 0.5)); + t.expects(read.skins.length == 1 && read.skins[0].joints.length == 2 && read.nodes[3].skin is some(s) && s == 0); + t.expects(read.floats(0).length == 32); + val rise := &read.animations[0]; + t.expects(rise.name.span == "rise" && rise.channels.length == 1 && rise.channels[0].path == gltf::target_path::translation); + t.expects(rise.channels[0].node is some(n) && n == 1 && rise.samplers[0].interpolation == gltf::interpolation::step); + val keys := read.floats(rise.samplers[0].output); + t.expects(keys.length == 6 && near(keys[4], 1)); +} diff --git a/tests/reading.sakura b/tests/reading.sakura new file mode 100644 index 0000000..84a7c5e --- /dev/null +++ b/tests/reading.sakura @@ -0,0 +1,186 @@ +#! Contains the tests of reading assets: from `.gltf` JSON with its buffer in a +#! `data:` URI, from a `.glb` file, and from files beside it; and what's refused, +#! each with why. + +import std::io; +import std::testing; +import malunal::linear; +import malunal::gltf; + +# Checks what the quad holds, read any way. +def expect_quad(t: &mut tester, read: &gltf::asset): void { + t.expects(read.version.span == "2.0" && read.generator.span == "gltf tests"); + t.expects(read.scene is some(s) && s == 0 && read.scenes.length == 1 && read.scenes[0].name.span == "Quad"); + t.expects(read.nodes.length == 1 && read.nodes[0].name.span == "Square" && read.nodes[0].mesh is some(m) && m == 0); + t.expects(near(read.nodes[0].translation.y, 2) && near(read.nodes[0].matrix.m[14], 3)); + val part := &read.meshes[0].primitives[0]; + t.expects(part.mode == gltf::topology::triangles && part.find("POSITION") is some(p) && p == 0 && part.find("TEXCOORD_0") is none); + val places := read.floats(0); + t.expects(places.length == 12 && near(places[3], 0.5) && near(places[7], 0.5)); + val normals := read.floats(1); + t.expects(normals.length == 12 && near(normals[2], 1)); + val indices := read.integers(2); + t.expects(indices.length == 6 && indices[4] == 2 && indices[5] == 3); + val red := &read.materials[0]; + t.expects(red.name.span == "red" && red.double_sided && near(red.base_color[0], 1) && near(red.base_color[1], 0)); + t.expects(near(red.metallic, 0) && near(red.roughness, 1) && red.alpha_mode == gltf::alpha_mode::opaque && red.base_color_texture is none); + t.expects(read.accessors[0].max.length == 3 && read.accessors[0].max[0] == 0.5); +} + +@test def reads_json_with_its_buffer_in_a_data_uri(t: &mut tester): void { + val bytes := quad_buffer(); + val uri := data_uri(bytes.span); + val json := quad_json(uri.span); + val read := gltf::decode(json.span) else (e) { + t.expects(false); + io::println(e.describe().span); + return; + }; + expect_quad(t, &read); +} + +@test def reads_glb_files(t: &mut tester): void { + val json := quad_json(""); + val bytes := quad_buffer(); + val glb := glb_of(json.span, bytes.span); + put("quad.glb", glb.span); + val read := gltf::load(".blossom/gltf tests/quad.glb") else (e) { + t.expects(false); + io::println(e.describe().span); + return; + }; + expect_quad(t, &read); + t.expects(read.buffers[0].uri.length == 0 && read.buffers[0].bytes.length >= 108); +} + +# A buffer and an image as files beside the asset, the buffer's named with a +# space, percent-encoded, and an image in a buffer view of a `.glb` file. +@test def reads_buffers_and_images_from_files_beside_it(t: &mut tester): void { + val bytes := quad_buffer(); + put("beside/quad data.bin", bytes.span); + val picture: u8[8] = [0x89, 'P', 'N', 'G', 13, 10, 26, 10]; + put("beside/red.png", picture[:]); + val json := quad_json("quad%20data.bin", ", \"images\": [{ \"uri\": \"red.png\" }], \"textures\": [{ \"source\": 0 }]"); + put("beside/quad.gltf", json.span); + val read := gltf::load(".blossom/gltf tests/beside/quad.gltf") else (e) { + t.expects(false); + io::println(e.describe().span); + return; + }; + expect_quad(t, &read); + t.expects(read.images.length == 1 && read.images[0].bytes.length == 8 && read.images[0].bytes[1] == 'P'); + t.expects(read.textures[0].source is some(s) && s == 0 && read.textures[0].sampler is none); + + # The same image, in a view of a `.glb` file's buffer, after the quad's. + var packed_bytes := quad_buffer(); + packed_bytes.extend(picture[:]); + val inner := quad_json("", ", \"images\": [{ \"bufferView\": 2, \"mimeType\": \"image/png\" }]"); + # Its buffer is the quad's and the image's: 116 bytes, the image a third view. + val with_image := replaced(replaced(inner.span, "\"byteLength\": 108", "\"byteLength\": 116").span, + "{ \"buffer\": 0, \"byteOffset\": 96, \"byteLength\": 12 }", + "{ \"buffer\": 0, \"byteOffset\": 96, \"byteLength\": 12 }, { \"buffer\": 0, \"byteOffset\": 108, \"byteLength\": 8 }"); + val glb := glb_of(with_image.span, packed_bytes.span); + val bound := gltf::decode(glb.span) else (e) { + t.expects(false); + io::println(e.describe().span); + return; + }; + t.expects(bound.images[0].mime_type.span == "image/png" && bound.images[0].bytes.length == 8 && bound.images[0].bytes[3] == 'G'); +} + +# Two texts, one after the other. +def joined(a: strview, b: strview): string { + var made := string::from(a, nothing{}); + made.append(b); + return made; +} + +# Text with the first of some text replaced. +def replaced(text: strview, what: strview, with: strview): string { + var made := string::new(nothing{}); + var i: u64 = 0; + var done := false; + while i < text.length { + if !done && i + what.length <= text.length && text.substr(i, what.length) == what { + made.append(with); + i += what.length; + done = true; + continue; + } + made.push(text[i]); + i++; + } + return made; +} + +# Whether what's refused is refused as `kind`, saying `says` somewhere in why. +def refuses(t: &mut tester, json: strview, kind: gltf::failure, says: strview): void { + match gltf::decode(json) { + value(_) => { + io::println($"read, but shouldn't be: {json}".span); + t.expects(false); + } + error(e) => { + val why := e.describe(); + val found := holds(why.span, says); + if e.kind != kind || !found { + io::println($"refused as `{why.span}`, not as `{says}`".span); + } + t.expects(e.kind == kind && found); + } + } +} + +def holds(text: strview, part: strview): bool { + return true if part.length == 0; + var i: u64 = 0; + while i + part.length <= text.length { + return true if text.substr(i, part.length) == part; + i++; + } + return false; +} + +@test def refuses_what_breaks_gltf(t: &mut tester): void { + refuses(t, "{ not json", gltf::failure::malformed, "JSON"); + refuses(t, "{ \"asset\": { \"version\": \"1.0\" } }", gltf::failure::unsupported, "1.0"); + refuses(t, "{ \"scenes\": [] }", gltf::failure::malformed, "version"); + refuses(t, asset_with("\"extensionsRequired\": [\"KHR_draco_mesh_compression\"]").span, gltf::failure::unsupported, "KHR_draco_mesh_compression"); + refuses(t, asset_with("\"nodes\": [{ \"mesh\": 0 }]").span, gltf::failure::malformed, "nodes[0]: its mesh is 0, of the 0 meshes"); + refuses(t, asset_with("\"nodes\": [{ \"children\": [1] }, { \"children\": [0] }]").span, gltf::failure::malformed, "comes back to it"); + refuses(t, asset_with("\"nodes\": [{ \"children\": [1] }, {}, { \"children\": [1] }]").span, gltf::failure::malformed, "child of both"); + refuses(t, asset_with("\"nodes\": [{ \"children\": [1] }, {}], \"scenes\": [{ \"nodes\": [1] }]").span, gltf::failure::malformed, "not a root"); + refuses(t, asset_with("\"buffers\": [{ \"byteLength\": 8 }]").span, gltf::failure::malformed, "buffers[0]"); + refuses(t, asset_with("\"buffers\": [{ \"byteLength\": 8, \"uri\": \"missing.bin\" }]").span, gltf::failure::unreadable, "missing.bin"); + refuses(t, asset_with("\"buffers\": [{ \"byteLength\": 4, \"uri\": \"https://example.com/a.bin\" }]").span, gltf::failure::unsupported, "another place"); + refuses(t, asset_with("\"buffers\": [{ \"byteLength\": 4, \"uri\": \"data:application/octet-stream;base64,AAAA\" }]").span, gltf::failure::malformed, "3"); + + # An accessor reaching past its view, and one of a type glTF hasn't. + val one_view := "\"buffers\": [{ \"byteLength\": 12, \"uri\": \"data:application/octet-stream;base64,AAAAAAAAAAAAAAAA\" }], \"bufferViews\": [{ \"buffer\": 0, \"byteLength\": 12 }]"; + refuses(t, asset_with(joined(one_view, ", \"accessors\": [{ \"bufferView\": 0, \"componentType\": 5126, \"count\": 2, \"type\": \"VEC2\" }]").span).span, + gltf::failure::malformed, "reach past"); + refuses(t, asset_with(joined(one_view, ", \"accessors\": [{ \"bufferView\": 0, \"componentType\": 5124, \"count\": 1, \"type\": \"SCALAR\" }]").span).span, + gltf::failure::malformed, "componentType 5124"); + val twelve := "\"buffers\": [{ \"byteLength\": 12, \"uri\": \"data:application/octet-stream;base64,AAAAAAAAAAAAAAAA\" }]"; + refuses(t, asset_with(joined(twelve, ", \"bufferViews\": [{ \"buffer\": 0, \"byteOffset\": 8, \"byteLength\": 8 }]").span).span, + gltf::failure::malformed, "reaches byte 16"); + + # A `.glb` file of another version, and one cut short. + val none := vector::::new(); + var glb := glb_of(asset_with("").span, none.span); + glb[4] = 1; + refuses(t, strview::over(glb.data, glb.length), gltf::failure::unsupported, "version 1"); + glb[4] = 2; + refuses(t, strview::over(glb.data, 16), gltf::failure::malformed, "cut short"); +} + +# What an asset uses but doesn't require, of extensions it doesn't read, is +# read without them, and named among its extensions. +@test def reads_past_extensions_it_only_uses(t: &mut tester): void { + val json := asset_with("\"extensionsUsed\": [\"KHR_texture_transform\"], \"nodes\": [{ \"extensions\": { \"KHR_texture_transform\": {} } }]"); + val read := gltf::decode(json.span) else (_) { + t.expects(false); + return; + }; + t.expects(read.extensions.length == 1 && read.extensions[0].span == "KHR_texture_transform" && read.nodes.length == 1); +} diff --git a/tests/support.sakura b/tests/support.sakura new file mode 100644 index 0000000..b71f3b4 --- /dev/null +++ b/tests/support.sakura @@ -0,0 +1,181 @@ +#! Contains what the tests of `gltf` share: buffers packed of numbers, their +#! base64 for `data:` URIs, `.glb` files put together of JSON and a buffer, and +#! files written where the tests read them back. + +import std::io; +import std::math; +import malunal::gltf; + +# The folder the tests write their files into. +const written: strview = ".blossom/gltf tests"; + +# Bytes being packed, little-endian, as a buffer holds them. +struct packed { + var bytes: vector; +} + +def packed::new(): packed { + return packed{ bytes = vector::::new() }; +} + +def packed::byte(&mut this, value: u8): void { + this.bytes.append(value); +} + +def packed::short(&mut this, value: u16): void { + this.bytes.append((value & 0xFF) as u8); + this.bytes.append((value >> 8) as u8); +} + +def packed::word(&mut this, value: u32): void { + for i in 0..4u { + this.bytes.append(((value >> (8 * i)) & 0xFF) as u8); + } +} + +def packed::float(&mut this, value: f32): void { + this.word(math::bits_of(value)); +} + +def packed::floats(&mut this, values: span): void { + for i in 0..values.length { + this.float(values[i]); + } +} + +# Pads with zeros to a multiple of 4 bytes. +def packed::align(&mut this): void { + while this.bytes.length % 4 != 0 { + this.bytes.append(0); + } +} + +# Bytes as base64, padded. +def base64_of(bytes: span): string { + val digits: strview = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; + var made := string::new(nothing{}); + var i: u64 = 0; + while i < bytes.length { + val left := bytes.length - i; + val a := bytes[i] as u32; + val b: u32 = left > 1 ? bytes[i + 1] as u32 : 0; + val c: u32 = left > 2 ? bytes[i + 2] as u32 : 0; + val all := (a << 16) | (b << 8) | c; + made.push(digits[((all >> 18) & 63) as u64]); + made.push(digits[((all >> 12) & 63) as u64]); + made.push(left > 1 ? digits[((all >> 6) & 63) as u64] : '='); + made.push(left > 2 ? digits[(all & 63) as u64] : '='); + i += 3; + } + return made; +} + +# A `data:` URI of a buffer's bytes. +def data_uri(bytes: span): string { + val digits := base64_of(bytes); + return $"data:application/octet-stream;base64,{digits.span}"; +} + +# A `.glb` file of JSON and a buffer: its header, then the JSON chunk, padded +# with spaces, and the binary chunk, padded with zeros. +def glb_of(json: strview, bin: span): vector { + var text := packed::new(); + text.bytes.extend(json); + while text.bytes.length % 4 != 0 { + text.bytes.append(' '); + } + var data := packed::new(); + data.bytes.extend(bin); + data.align(); + var made := packed::new(); + made.word(0x46546C67); + made.word(2); + made.word((12 + 8 + text.bytes.length + (bin.length != 0 ? 8 + data.bytes.length : 0)) as u32); + made.word(text.bytes.length as u32); + made.word(0x4E4F534A); + made.bytes.extend(text.bytes.span); + if bin.length != 0 { + made.word(data.bytes.length as u32); + made.word(0x004E4942); + made.bytes.extend(data.bytes.span); + } + return move(made.bytes); +} + +# Writes a file the tests read, beneath `written`, making its folder. +def put(at: strview, bytes: span): void { + var file := path::parse($"{written}/{at}".span).expect("A path."); + if file.parent() is some(&above) { + _ = io::create_directories(above); + } + io::write_file(&file, bytes).expect("The file is written."); +} + +# The positions, normals, and indices of a quad of two triangles, facing +z, a +# unit across, packed one after another: 48 bytes of positions, 48 of normals, +# and 12 of indices, as `quad_json` names them. +def quad_buffer(): vector { + var made := packed::new(); + val places: f32[12] = [-0.5, -0.5, 0, 0.5, -0.5, 0, 0.5, 0.5, 0, -0.5, 0.5, 0]; + val normals: f32[12] = [0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1]; + made.floats(places[:]); + made.floats(normals[:]); + for each in [0u, 1, 2, 0, 2, 3] { + made.short(each as u16); + } + made.align(); + return move(made.bytes); +} + +# The JSON of the quad, of one node of one mesh, its material red and double +# sided, its buffer named by a URI, or the `.glb` file's where that's empty, +# and other members after, where given. +def quad_json(uri: strview, more: strview = ""): string { + var made := string::from(""" + { + "asset": { "version": "2.0", "generator": "gltf tests" }, + "scene": 0, + "scenes": [{ "name": "Quad", "nodes": [0] }], + "nodes": [{ "name": "Square", "mesh": 0, "translation": [1, 2, 3] }], + "meshes": [{ "name": "quad", "primitives": [{ + "attributes": { "POSITION": 0, "NORMAL": 1 }, "indices": 2, "material": 0 + }] }], + "materials": [{ "name": "red", "doubleSided": true, "pbrMetallicRoughness": { "baseColorFactor": [1, 0, 0, 1], "metallicFactor": 0 } }], + "accessors": [ + { "bufferView": 0, "componentType": 5126, "count": 4, "type": "VEC3", "min": [-0.5, -0.5, 0], "max": [0.5, 0.5, 0] }, + { "bufferView": 0, "byteOffset": 48, "componentType": 5126, "count": 4, "type": "VEC3" }, + { "bufferView": 1, "componentType": 5123, "count": 6, "type": "SCALAR" } + ], + "bufferViews": [ + { "buffer": 0, "byteOffset": 0, "byteLength": 96 }, + { "buffer": 0, "byteOffset": 96, "byteLength": 12 } + ], + "buffers": [{ "byteLength": 108 + """, nothing{}); + if uri.length != 0 { + made.append(", \"uri\": \""); + made.append(uri); + made.append("\""); + } + made.append(" }]"); + made.append(more); + made.append(" }"); + return made; +} + +# JSON of an asset, a version and the members given, as the tests of what's +# refused write each. +def asset_with(members: strview): string { + var made := string::from("{ \"asset\": { \"version\": \"2.0\" }", nothing{}); + if members.length != 0 { + made.append(", "); + made.append(members); + } + made.append(" }"); + return made; +} + +# Whether two floats are within a millionth. +def near(a: f32, b: f32): bool { + return math::abs(a - b) < 1e-5; +}