Files
models/gltf/files.sakura
T
2026-10-30 15:03:12 -05:00

158 lines
5.9 KiB
Plaintext

#! 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<u8>): bool {
return bytes.length >= 4 && word_at(bytes, 0) == glb_magic;
}
# A little-endian `u32` at a byte.
def word_at(bytes: span<u8>, 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<u8>;
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<u8>): result<chunks, gltf_error> {
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.".view()) 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}.".view()) 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::<u8>::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<vector<u8>, 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.".view()) if comma == uri.length;
val head := uri.substr(5, comma - 5);
return failed(failure::unsupported, $"{whose}: its data URI isn't base64.".view()) 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.".view());
};
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.".view());
}
break if uri[i] == '/';
}
val named := percent_decoded(uri) else { return failed(failure::malformed, $"{whose}: {uri} isn't percent-encoded right.".view()); };
val at := folder.length == 0 ? string::from(named.view(), nothing{}) : $"{folder}/{named.view()}";
val file := path::parse(at.view()) else (_) { return failed(failure::unreadable, $"{whose}: {at.view()} isn't a path.".view()); };
val text := io::read_file(&file) else (_) { return failed(failure::unreadable, $"{whose}: {at.view()} couldn't be read.".view()); };
var made := vector::<u8>::new();
made.extend(text.view());
return made;
}
# Text of `%XX` escapes decoded, or nothing where an escape isn't two hex
# digits.
def percent_decoded(text: strview): maybe<string> {
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<u8> {
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<vector<u8>> {
var made := vector::<u8>::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<u8> {
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{};
}