Initial Commit

This commit is contained in:
SoraKatadzuma committed 2026-11-14 15:40:07 -06:00
commit 05afb4a443
36 files changed
+8436

No files matched your search

+325
View File
@@ -0,0 +1,325 @@
#! Contains MTL's materials: their colors and numbers, the physically based
#! ones some tools add, and the textures each maps, with the options they're
#! given; and reading them from an MTL file's text.
import malunal::linear;
module malunal::obj;
#! What a texture of a material is a map of, as the statement naming it says.
pub enum map_slot: u8 {
ambient, #! `map_Ka`
diffuse, #! `map_Kd`
specular, #! `map_Ks`
emissive, #! `map_Ke`
shininess, #! `map_Ns`
dissolve, #! `map_d`
bump, #! `bump` or `map_bump`
displacement, #! `disp`
decal, #! `decal`
reflection, #! `refl`
normal, #! `norm`
roughness, #! `map_Pr`
metallic, #! `map_Pm`
sheen, #! `map_Ps`
}
#! The statements naming each slot's texture, in `map_slot`'s order, the first
#! of each written.
const slot_names: strview[14] = ["map_Ka", "map_Kd", "map_Ks", "map_Ke", "map_Ns", "map_d", "bump", "disp", "decal", "refl", "norm", "map_Pr", "map_Pm", "map_Ps"];
const slot_kinds: map_slot[14] = [
map_slot::ambient, map_slot::diffuse, map_slot::specular, map_slot::emissive, map_slot::shininess, map_slot::dissolve, map_slot::bump,
map_slot::displacement, map_slot::decal, map_slot::reflection, map_slot::normal, map_slot::roughness, map_slot::metallic, map_slot::sheen,
];
# The statement naming a slot's texture, as it's written.
def slot_name(slot: map_slot): strview {
for k in 0..14 {
return slot_names[k] if slot_kinds[k] == slot;
}
return "map_Kd";
}
#! A texture a material maps, and the options it's given.
pub struct texture_map {
pub var slot: map_slot;
#! The image's file, as the MTL file names it.
pub var file: string;
#! `-o`, `-s`, and `-t`: where on the texture it begins, how much of it, and
#! how much it's turbulent.
pub var offset := vec3::zero;
pub var scale := vec3::one;
pub var turbulence := vec3::zero;
#! `-bm`: how much a bump map bumps.
pub var bump_multiplier: f32 = 1;
#! `-boost`, and `-mm`'s base and gain.
pub var boost: f32;
pub var base: f32;
pub var gain: f32 = 1;
#! `-clamp`, `-blendu`, `-blendv`, and `-cc`.
pub var clamp: bool;
pub var blend_u: bool = true;
pub var blend_v: bool = true;
pub var color_correct: bool;
#! `-texres`, or 0 where it's none.
pub var resolution: u32;
#! `-imfchan`'s channel, `r`, `g`, `b`, `m`, `l`, or `z`, or 0 where it's none.
pub var channel: u8;
#! `-type`, a reflection map's: `sphere`, or a side of a cube, as `cube_top`.
pub var kind: string;
}
#! A material of an MTL file. Where the file leaves one out, a color is black,
#! but diffuse, white, and a number 0, but `dissolve` and `ior`, 1.
pub struct material {
pub var name: string;
#! `Ka`, `Kd`, `Ks`, `Ke`, and `Tf`: ambient, diffuse, specular, emitted, and
#! let through.
pub var ambient := vec3::zero;
pub var diffuse := vec3::one;
pub var specular := vec3::zero;
pub var emissive := vec3::zero;
pub var transmission := vec3::zero;
#! `Ns`, the specular exponent, from 0 to 1000.
pub var shininess: f32;
#! `Ni`, the index of refraction.
pub var ior: f32 = 1;
#! `d`, how opaque it is, or `Tr`, how transparent, 1 less it.
pub var dissolve: f32 = 1;
#! `illum`, the illumination model, from 0 to 10.
pub var illumination: u32;
#! `sharpness`, of reflections.
pub var sharpness: f32;
#! `Pr`, `Pm`, `Ps`, `Pc`, `Pcr`, `aniso`, and `anisor`: physically based,
#! as Blender and others write them.
pub var roughness: f32;
pub var metallic: f32;
pub var sheen: f32;
pub var clearcoat: f32;
pub var clearcoat_roughness: f32;
pub var anisotropy: f32;
pub var anisotropy_rotation: f32;
#! The textures it maps, in the order the file names them.
pub var maps: vector<texture_map>;
}
#! The texture it maps for a slot, where it maps one.
pub def material::map(&this, slot: map_slot): maybe<&texture_map> {
for i in 0..this.maps.length {
return &this.maps[i] if this.maps[i].slot == slot;
}
return nothing{};
}
#! A material of a name, of the defaults.
pub def material::named(name: strview): material {
return material{ name = string::from(name, nothing{}) };
}
#! Reads the materials of an MTL file's text.
#! @param text The text.
#! @returns Its materials, in its order, or why they couldn't be read.
pub def decode_materials(text: strview): result<vector<material>, obj_error> {
var made := vector::<material>::new();
var lines := statements_of(text);
while lines.next() {
var words := words_of(lines.current);
val keyword := words.next();
if keyword == "newmtl" {
made.append(material::named(words.rest()));
continue;
}
return at_line(lines.line, $"`{keyword}` comes before any `newmtl`.".span) if made.length == 0;
val held := &mut made[made.length - 1];
read_statement(held, keyword, &mut words, lines.line) else (e) { return e; };
}
return made;
}
# Reads a statement of a material.
def read_statement(held: &mut material, keyword: strview, words: &mut words, line: u64): result<void, obj_error> {
if keyword == "Ka" || keyword == "Kd" || keyword == "Ks" || keyword == "Ke" || keyword == "Tf" {
# `spectral` and `xyz` colors are read as their numbers, where they give
# three, and passed over otherwise.
var color := vec3::zero;
var count: u64 = 0;
while count < 3 {
val word := words.next();
break if word.length == 0;
continue if word == "xyz";
return if word == "spectral";
val value := number_of(word) else { return at_line(line, $"`{word}` isn't a number.".span); };
if count == 0 {
color = vec3{ value as f32, value as f32, value as f32 };
} else if count == 1 {
color.y = value as f32;
} else {
color.z = value as f32;
}
count++;
}
return at_line(line, $"`{keyword}` gives no color.".span) if count == 0;
if keyword == "Ka" {
held.ambient = color;
} else if keyword == "Kd" {
held.diffuse = color;
} else if keyword == "Ks" {
held.specular = color;
} else if keyword == "Ke" {
held.emissive = color;
} else {
held.transmission = color;
}
return;
}
if keyword == "illum" {
val word := words.next();
val value := integer_of(word) else { return at_line(line, $"`{word}` isn't an illumination model.".span); };
held.illumination = value as u32;
return;
}
if keyword == "d" || keyword == "Tr" {
var word := words.next();
if word == "-halo" {
word = words.next();
}
val value := number_of(word) else { return at_line(line, $"`{word}` isn't a number.".span); };
held.dissolve = keyword == "d" ? value as f32 : 1 - value as f32;
return;
}
val numbers: strview[10] = ["Ns", "Ni", "sharpness", "Pr", "Pm", "Ps", "Pc", "Pcr", "aniso", "anisor"];
for k in 0..10 {
continue if keyword != numbers[k];
val word := words.next();
val value := number_of(word) else { return at_line(line, $"`{word}` isn't a number.".span); };
val n := value as f32;
if k == 0 {
held.shininess = n;
} else if k == 1 {
held.ior = n;
} else if k == 2 {
held.sharpness = n;
} else if k == 3 {
held.roughness = n;
} else if k == 4 {
held.metallic = n;
} else if k == 5 {
held.sheen = n;
} else if k == 6 {
held.clearcoat = n;
} else if k == 7 {
held.clearcoat_roughness = n;
} else if k == 8 {
held.anisotropy = n;
} else {
held.anisotropy_rotation = n;
}
return;
}
val slot := slot_of(keyword) else { return; };
var texture := read_map(slot, words, line) else (e) { return e; };
held.maps.append(move(texture));
return;
}
# The slot a statement maps a texture for, where it's one that does.
def slot_of(keyword: strview): maybe<map_slot> {
for k in 0..14 {
return slot_kinds[k] if keyword == slot_names[k];
}
return map_slot::bump if keyword == "map_bump" || keyword == "map_Bump";
return map_slot::displacement if keyword == "map_disp";
return map_slot::reflection if keyword == "map_refl";
return map_slot::normal if keyword == "map_Kn" || keyword == "map_norm";
return nothing{};
}
# Reads a texture's options, then its file, the rest of the statement.
def read_map(slot: map_slot, words: &mut words, line: u64): result<texture_map, obj_error> {
var made := texture_map{ slot = slot };
while !words.ended() {
val before := words.at;
val option := words.next();
if option.length < 2 || option[0] != '-' || is_digit(option[1]) {
words.at = before;
break;
}
if option == "-o" || option == "-s" || option == "-t" {
var v := option == "-s" ? vec3::one : vec3::zero;
for k in 0..3 {
val at := words.at;
val word := words.next();
var value: f32 = 0;
if number_of(word) is some(n) {
value = n as f32;
} else {
words.at = at;
break;
}
if k == 0 {
v.x = value;
} else if k == 1 {
v.y = value;
} else {
v.z = value;
}
}
if option == "-o" {
made.offset = v;
} else if option == "-s" {
made.scale = v;
} else {
made.turbulence = v;
}
} else if option == "-bm" || option == "-boost" {
val word := words.next();
val value := number_of(word) else { return at_line(line, $"`{option}` needs a number, not `{word}`.".span); };
if option == "-bm" {
made.bump_multiplier = value as f32;
} else {
made.boost = value as f32;
}
} else if option == "-mm" {
val base_word := words.next();
val gain_word := words.next();
val base := number_of(base_word) else { return at_line(line, "`-mm` needs a base and a gain."); };
val gain := number_of(gain_word) else { return at_line(line, "`-mm` needs a base and a gain."); };
made.base = base as f32;
made.gain = gain as f32;
} else if option == "-clamp" || option == "-blendu" || option == "-blendv" || option == "-cc" {
val word := words.next();
return at_line(line, $"`{option}` is `on` or `off`, not `{word}`.".span) if word != "on" && word != "off";
val on := word == "on";
if option == "-clamp" {
made.clamp = on;
} else if option == "-blendu" {
made.blend_u = on;
} else if option == "-blendv" {
made.blend_v = on;
} else {
made.color_correct = on;
}
} else if option == "-texres" {
val word := words.next();
val value := integer_of(word) else { return at_line(line, $"`-texres` needs a whole number, not `{word}`.".span); };
made.resolution = value as u32;
} else if option == "-imfchan" {
val word := words.next();
return at_line(line, "`-imfchan` needs a channel.") if word.length == 0;
made.channel = word[0];
} else if option == "-type" {
made.kind = string::from(words.next(), nothing{});
} else {
# An option of another tool's, with a value, passed over.
_ = words.next();
}
}
val file := words.rest();
return at_line(line, "A texture map names no file.") if file.length == 0;
made.file = string::from(file, nothing{});
return made;
}
# Whether a byte is a digit.
def is_digit(c: u8): bool {
return c >= '0' && c <= '9';
}
+157
View File
@@ -0,0 +1,157 @@
#! Contains `model`, a model read from Wavefront's OBJ, why one couldn't be,
#! and reading one, from a file or from text, with the materials of the MTL
#! files it names.
#!
#! An OBJ file is lines of text, each a statement: `v`, `vt`, and `vn` give
#! positions, places on a texture, and normals, and `f`, `l`, and `p` faces,
#! lines, and points of them, by their numbers, counted from 1, or back from
#! the last where they're negative. `o`, `g`, `s`, and `usemtl` say which
#! object, group, smoothing group, and material what follows is of, and
#! `mtllib` names the MTL files the materials are in. A model keeps them as
#! they are: faces of any number of corners, each corner its position, and its
#! place on a texture and its normal where it has them, every index counted
#! from 0.
import std::io;
import malunal::linear;
module malunal::obj;
#! What kind of thing kept a model from being read or written.
pub enum failure: u8 {
unreadable, #! A file couldn't be read, or written.
malformed, #! The text breaks OBJ or MTL: a number that isn't one, an index past what it names, a face of fewer than three corners.
}
#! Why a model couldn't be read, or written: the kind of thing, and what, as
#! `line 12: its face has 2 corners, of the 3 it needs at least`. It holds its
#! text itself, its first 240 bytes, so it's plain data, as std's errors are.
pub struct obj_error {
pub var kind: failure;
var text: u8[240];
var length: u64;
}
#! What was wrong, and where.
pub def obj_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): obj_error {
var made := obj_error{ kind = kind };
made.length = why.length < 240 ? why.length : 240;
for i in 0..made.length {
made.text[i] = why[i];
}
return made;
}
#! What a corner names where it names nothing: no place on a texture, or no
#! normal; and what an element is of where it's of no material, object, or
#! group.
pub const absent: u32 = 0xFFFFFFFF;
#! A corner of a face, or a point of a line or of points: indices into the
#! model's positions, places on a texture, and normals.
pub struct corner {
pub var position: u32;
pub var uv: u32 = absent;
pub var normal: u32 = absent;
}
#! A face, a line, or points: a run of the model's corners, and what it's of.
pub struct element {
#! Its first corner, in the model's `corners`.
pub var first: u64;
#! How many corners it has: three or more of a face, two or more of a line.
pub var count: u32;
#! Its material, in the model's `materials`.
pub var material: u32 = absent;
#! Its smoothing group, or 0 where it's of none, and drawn flat.
pub var smoothing: u32;
#! The object it's of, in the model's `objects`.
pub var object: u32 = absent;
#! The group it's of, in the model's `groups`.
pub var group: u32 = absent;
}
#! A model read from OBJ: what it's made of, and its faces, lines, and points,
#! each a run of corners.
pub struct model {
pub var positions: vector<vec3>;
#! Each position's color, where the file gives them, as `v x y z r g b`,
#! white where it gives one none; empty where it gives none.
pub var colors: vector<vec3>;
pub var uvs: vector<vec2>;
pub var normals: vector<vec3>;
pub var corners: vector<corner>;
pub var faces: vector<element>;
pub var lines: vector<element>;
pub var points: vector<element>;
#! The names of its objects, by `o`, and of its groups, by `g`.
pub var objects: vector<string>;
pub var groups: vector<string>;
#! Its materials: those of the MTL files it names, in their order, then one
#! of each name `usemtl` gives that none of them has, of the defaults.
pub var materials: vector<material>;
#! The MTL files it names, as it names them, and those of them that weren't
#! found or couldn't be read.
pub var libraries: vector<string>;
pub var missing: vector<string>;
}
#! The corners of an element.
pub def model::corners_of(&this, of: &element): span<corner> {
return this.corners.span[of.first:of.count as u64];
}
#! The material named so, where it has one.
pub def model::material_named(&this, name: strview): maybe<u64> {
for i in 0..this.materials.length {
return i if this.materials[i].name.span == name;
}
return nothing{};
}
#! Reads a model from a file, and the materials of the MTL files it names, from
#! beside it.
#! @param at The file's path.
#! @returns The model, or why it couldn't be read: `unreadable` where the file
#! couldn't be. An MTL file that can't be is named in `missing`.
pub def load(at: &path): result<model, obj_error> {
val text := 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(text.span, folder.span);
}
#! Reads a model from a file named by text, as `load` does.
pub def load(at: strview): result<model, obj_error> {
val named := path::parse(at) else (_) { return failed(failure::unreadable, $"{at} isn't a path.".span); };
return load(&named);
}
#! Reads a model from text.
#! @param text The OBJ file's text.
#! @param folder The folder the MTL files it names are found in, or empty,
#! where none are read, but named in `missing`.
#! @returns The model, or why it couldn't be read.
pub def decode(text: strview, folder: strview = ""): result<model, obj_error> {
return read_model(text, folder);
}
#! Reads the materials of an MTL file.
#! @param at The file's path.
#! @returns Its materials, in its order, or why they couldn't be read.
pub def load_materials(at: &path): result<vector<material>, obj_error> {
val text := io::read_file(at) else (_) { return failed(failure::unreadable, $"{at.span} couldn't be read.".span); };
return decode_materials(text.span);
}
#! Reads the materials of an MTL file named by text, as `load_materials` does.
pub def load_materials(at: strview): result<vector<material>, obj_error> {
val named := path::parse(at) else (_) { return failed(failure::unreadable, $"{at} isn't a path.".span); };
return load_materials(&named);
}
+253
View File
@@ -0,0 +1,253 @@
#! Contains reading an OBJ file's statements into a model: what each gives,
#! its corners' indices checked once all are read, as one may name a position
#! given after it, and the materials of the MTL files it names.
import std::io;
import malunal::linear;
module malunal::obj;
# What the statements read so far say what follows is of.
struct state {
var material: u32 = absent;
var smoothing: u32;
var object: u32 = absent;
var group: u32 = absent;
}
# Reads a model from OBJ's text, the MTL files it names from a folder.
def read_model(text: strview, folder: strview): result<model, obj_error> {
var made := model{};
# The names `usemtl` gives, which elements' materials index until the end.
var named := vector::<string>::new();
var now := state{};
var lines := statements_of(text);
while lines.next() {
val line := lines.line;
var words := words_of(lines.current);
val keyword := words.next();
if keyword == "v" {
read_position(&mut made, &mut words, line) else (e) { return e; };
} else if keyword == "vt" {
val numbers := read_numbers(&mut words, line, 1, 3) else (e) { return e; };
made.uvs.append(vec2{ numbers[0] as f32, numbers[1] as f32 });
} else if keyword == "vn" {
val numbers := read_numbers(&mut words, line, 3, 3) else (e) { return e; };
made.normals.append(vec3{ numbers[0] as f32, numbers[1] as f32, numbers[2] as f32 });
} else if keyword == "f" || keyword == "fo" || keyword == "l" || keyword == "p" {
val first := made.corners.length;
while true {
val word := words.next();
break if word.length == 0;
val held := read_corner(&made, word, line) else (e) { return e; };
made.corners.append(held);
}
val count := made.corners.length - first;
var held := element{ first = first, count = count as u32, material = now.material, smoothing = now.smoothing, object = now.object, group = now.group };
if keyword == "l" {
return at_line(line, $"Its line has {count} points, of the 2 it needs at least.".span) if count < 2;
made.lines.append(held);
} else if keyword == "p" {
return at_line(line, "Its points are none.") if count < 1;
made.points.append(held);
} else {
return at_line(line, $"Its face has {count} corners, of the 3 it needs at least.".span) if count < 3;
made.faces.append(held);
}
} else if keyword == "o" {
now.object = name_index(&mut made.objects, words.rest());
} else if keyword == "g" {
val name := words.rest();
now.group = name.length == 0 ? absent : name_index(&mut made.groups, name);
} else if keyword == "s" {
val word := words.next();
if word == "off" || word.length == 0 {
now.smoothing = 0;
} else {
val value := integer_of(word) else { return at_line(line, $"`{word}` isn't a smoothing group.".span); };
now.smoothing = value as u32;
}
} else if keyword == "usemtl" {
val name := words.rest();
now.material = name.length == 0 ? absent : name_index(&mut named, name);
} else if keyword == "mtllib" {
read_libraries(&mut made, &mut words, folder);
}
# Other statements, of curves and surfaces, and of display, are passed over.
}
check_corners(&made) else (e) { return e; };
read_materials(&mut made, folder) else (e) { return e; };
name_materials(&mut made, &named);
return made;
}
# Reads a position, and its color, where it has one.
def read_position(made: &mut model, words: &mut words, line: u64): result<void, obj_error> {
val numbers := read_numbers(words, line, 3, 7) else (e) { return e; };
made.positions.append(vec3{ numbers[0] as f32, numbers[1] as f32, numbers[2] as f32 });
# Three more are a color; a fourth alone is a weight, which isn't kept.
if numbers[7] >= 6 {
while made.colors.length + 1 < made.positions.length {
made.colors.append(vec3::one);
}
made.colors.append(vec3{ numbers[3] as f32, numbers[4] as f32, numbers[5] as f32 });
} else if made.colors.length != 0 {
made.colors.append(vec3::one);
}
return;
}
# Reads from a least to a most numbers, those not given 0; how many were given
# is the last.
def read_numbers(words: &mut words, line: u64, least: u64, most: u64): result<f64[8], obj_error> {
var made: f64[8];
var count: u64 = 0;
while count < most {
val word := words.next();
break if word.length == 0;
val value := number_of(word) else { return at_line(line, $"`{word}` isn't a number.".span); };
made[count] = value;
count++;
}
return at_line(line, $"It gives {count} numbers, of the {least} it needs at least.".span) if count < least;
made[7] = count as f64;
return made;
}
# Reads a corner, `v`, `v/vt`, `v//vn`, or `v/vt/vn`, each index counted from 1,
# or back from the last given where it's negative.
def read_corner(made: &model, word: strview, line: u64): result<corner, obj_error> {
var parts: strview[3];
var count: u64 = 0;
var begun: u64 = 0;
for i in 0..=word.length {
if i == word.length || word[i] == '/' {
return at_line(line, $"`{word}` isn't a corner.".span) if count == 3;
parts[count] = word.substr(begun, i - begun);
count++;
begun = i + 1;
}
}
var held := corner{};
held.position = resolve(parts[0], made.positions.length, word, line) else (e) { return e; };
if count > 1 && parts[1].length != 0 {
held.uv = resolve(parts[1], made.uvs.length, word, line) else (e) { return e; };
}
if count > 2 && parts[2].length != 0 {
held.normal = resolve(parts[2], made.normals.length, word, line) else (e) { return e; };
}
return held;
}
# An index, counted from 0, of one counted from 1, or back from the last of
# those given so far where it's negative.
def resolve(text: strview, given: u64, word: strview, line: u64): result<u32, obj_error> {
val value := integer_of(text) else { return at_line(line, $"`{word}` isn't a corner.".span); };
if value > 0 {
return at_line(line, $"`{word}` names more than there may be.".span) if value > 0xFFFFFFFE;
return (value - 1) as u32;
}
val back := given as i64 + value;
return at_line(line, $"`{word}` names nothing: an index is counted from 1, or back from -1.".span) if value == 0 || back < 0;
return back as u32;
}
# The index of a name in a list, added where it isn't there.
def name_index(names: &mut vector<string>, name: strview): u32 {
for i in 0..names.length {
return i as u32 if names[i].span == name;
}
names.append(string::from(name, nothing{}));
return (names.length - 1) as u32;
}
# Notes the MTL files a statement names: its words, or the whole of it where
# that names a file beside the model, as a name with a space.
def read_libraries(made: &mut model, words: &mut words, folder: strview): void {
val whole := words.rest();
if folder.length != 0 && whole.find(" ") is some(_) {
val at := path::parse($"{folder}/{whole}".span) else (_) { return; };
if io::exists(&at) {
_ = name_index(&mut made.libraries, whole);
return;
}
}
var each := words_of(whole);
while true {
val word := each.next();
break if word.length == 0;
_ = name_index(&mut made.libraries, word);
}
}
# Checks each corner names a position, a place on a texture, and a normal there
# are.
def check_corners(made: &model): result<void, obj_error> {
for i in 0..made.corners.length {
val held := made.corners[i];
if held.position as u64 >= made.positions.length {
return failed(failure::malformed, $"Corner {i} names position {held.position + 1}, of the {made.positions.length} there are.".span);
}
if held.uv != absent && (held.uv as u64) >= made.uvs.length {
return failed(failure::malformed, $"Corner {i} names texture place {held.uv + 1}, of the {made.uvs.length} there are.".span);
}
if held.normal != absent && (held.normal as u64) >= made.normals.length {
return failed(failure::malformed, $"Corner {i} names normal {held.normal + 1}, of the {made.normals.length} there are.".span);
}
}
return;
}
# Reads the materials of the MTL files the model names, each name kept by the
# first that gives it; those that can't be read are noted as missing.
def read_materials(made: &mut model, folder: strview): result<void, obj_error> {
for k in 0..made.libraries.length {
val name := made.libraries[k].span;
if folder.length == 0 {
made.missing.append(string::from(name, nothing{}));
continue;
}
val at := path::parse($"{folder}/{name}".span) else (_) {
made.missing.append(string::from(name, nothing{}));
continue;
};
val text := io::read_file(&at) else (_) {
made.missing.append(string::from(name, nothing{}));
continue;
};
var read := decode_materials(text.span) else (e) {
val why := e.describe();
return failed(failure::malformed, $"{name}: {why.span}".span);
};
for i in 0..read.length {
continue if made.material_named(read[i].name.span) is some(_);
made.materials.append(move(read[i]));
}
}
return;
}
# Gives each element the index of its material in the model's, those named by
# `usemtl` that no MTL file gave made of the defaults.
def name_materials(made: &mut model, named: &vector<string>): void {
var index := vector::<u32>::new();
for i in 0..named.length {
if made.material_named(named[i].span) is some(found) {
index.append(found as u32);
} else {
made.materials.append(material::named(named[i].span));
index.append((made.materials.length - 1) as u32);
}
}
for i in 0..made.faces.length {
val m := made.faces[i].material;
made.faces[i].material = m == absent ? absent : index[m as u64];
}
for i in 0..made.lines.length {
val m := made.lines[i].material;
made.lines[i].material = m == absent ? absent : index[m as u64];
}
for i in 0..made.points.length {
val m := made.points[i].material;
made.points[i].material = m == absent ? absent : index[m as u64];
}
}
+146
View File
@@ -0,0 +1,146 @@
#! Contains reading OBJ's and MTL's text: its statements, a line each, blank
#! lines and comments passed over and a line ending with `\` joined to the
#! next; and the words and numbers of each.
module malunal::obj;
# The statements of a file's text, a line each.
struct statements {
var text: strview;
var at: u64;
#! The statement given last, its spaces about it trimmed.
var current: strview;
#! The number of the line it began on, from 1.
var line: u64;
var counted: u64;
var joined: string;
}
# The statements of text.
def statements_of(text: strview): statements {
return statements{ text = text, joined = string::new(nothing{}) };
}
# Moves to the next statement, passing over blank lines and those beginning
# with `#`.
# @returns Whether there was one; it's `current`.
def statements::next(&mut this): bool {
while this.at < this.text.length {
this.joined.clear();
var joining := false;
this.line = this.counted + 1;
while true {
val begun := this.at;
while this.at < this.text.length && this.text[this.at] != '\n' {
this.at++;
}
var end := this.at;
if this.at < this.text.length {
this.at++;
}
this.counted++;
while end > begun && is_space(this.text[end - 1]) {
end--;
}
# A line ending with `\` goes on in the next.
if end > begun && this.text[end - 1] == '\\' && this.at < this.text.length {
this.joined.append(this.text.substr(begun, end - 1 - begun));
this.joined.push(' ');
joining = true;
continue;
}
if joining {
this.joined.append(this.text.substr(begun, end - begun));
this.current = trimmed(this.joined.span);
} else {
this.current = trimmed(this.text.substr(begun, end - begun));
}
break;
}
continue if this.current.length == 0 || this.current[0] == '#';
return true;
}
return false;
}
# Whether a byte is a space between words.
def is_space(c: u8): bool {
return c == ' ' || c == '\t' || c == '\r' || c == 11 || c == 12;
}
# Text with the spaces about it taken away.
def trimmed(text: strview): strview {
var first: u64 = 0;
var end := text.length;
while first < end && is_space(text[first]) {
first++;
}
while end > first && is_space(text[end - 1]) {
end--;
}
return text.substr(first, end - first);
}
# The words of a statement, one after another.
struct words {
var text: strview;
var at: u64;
}
def words_of(text: strview): words {
return words{ text = text };
}
# The next word, or empty at the statement's end, or at a word beginning with
# `#`, a comment after it.
def words::next(&mut this): strview {
while this.at < this.text.length && is_space(this.text[this.at]) {
this.at++;
}
if this.at < this.text.length && this.text[this.at] == '#' {
this.at = this.text.length;
}
val begun := this.at;
while this.at < this.text.length && !is_space(this.text[this.at]) {
this.at++;
}
return this.text.substr(begun, this.at - begun);
}
# What's left of the statement, the spaces about it trimmed: a name, which may
# hold spaces.
def words::rest(&mut this): strview {
val left := trimmed(this.text.substr(this.at, this.text.length - this.at));
this.at = this.text.length;
return left;
}
# Whether nothing's left of the statement but spaces, or a comment.
def words::ended(&this): bool {
var at := this.at;
while at < this.text.length && is_space(this.text[at]) {
at++;
}
return at >= this.text.length || this.text[at] == '#';
}
# A word as a number.
def number_of(word: strview): maybe<f64> {
if real::parse::<f64>(word) is value(n) {
return n;
}
return nothing{};
}
# A word as a whole number.
def integer_of(word: strview): maybe<i64> {
if integer::parse::<i64>(word) is value(n) {
return n;
}
return nothing{};
}
# An error of malformed text, at a line.
def at_line(line: u64, why: strview): obj_error {
return failed(failure::malformed, $"line {line}: {why}".span);
}
+272
View File
@@ -0,0 +1,272 @@
#! Contains writing a model as OBJ, and its materials as MTL: `encode`,
#! `encode_materials`, and `save`, which writes both, the MTL file beside the
#! OBJ.
import std::io;
import malunal::linear;
module malunal::obj;
#! Writes a model as OBJ's text: its positions, and their colors where it has
#! them, places on a texture, and normals, then its faces, lines, and points,
#! each `o`, `g`, `usemtl`, and `s` written where what they're of changes.
#! @param made The model.
#! @param library The MTL file it names, or empty for the first it read from,
#! where it read from any.
#! @returns The text, numbers written as the shortest text that reads back as
#! them.
pub def encode(made: &model, library: strview = ""): string {
var out := string::new(nothing{});
out.append("# Written by malunal obj\n");
if library.length != 0 {
out.append($"mtllib {library}\n".span);
} else if made.libraries.length != 0 && made.materials.length != 0 {
out.append($"mtllib {made.libraries[0].span}\n".span);
}
val colored := made.colors.length == made.positions.length && made.colors.length != 0;
for i in 0..made.positions.length {
val p := made.positions[i];
out.append("v ");
put_numbers(&mut out, p.x, p.y, p.z);
if colored {
val c := made.colors[i];
out.push(' ');
put_numbers(&mut out, c.x, c.y, c.z);
}
out.push('\n');
}
for i in 0..made.uvs.length {
val t := made.uvs[i];
out.append("vt ");
put_number(&mut out, t.x);
out.push(' ');
put_number(&mut out, t.y);
out.push('\n');
}
for i in 0..made.normals.length {
val n := made.normals[i];
out.append("vn ");
put_numbers(&mut out, n.x, n.y, n.z);
out.push('\n');
}
var now := state{ object = absent - 1, group = absent - 1, material = absent - 1, smoothing = absent };
put_elements(&mut out, made, &made.faces, "f", &mut now);
put_elements(&mut out, made, &made.lines, "l", &mut now);
put_elements(&mut out, made, &made.points, "p", &mut now);
return out;
}
# Writes elements of a kind, and what they're of where it changes.
def put_elements(out: &mut string, made: &model, list: &vector<element>, keyword: strview, now: &mut state): void {
for i in 0..list.length {
val held := list[i];
if held.object != now.object {
now.object = held.object;
if held.object != absent {
out.append($"o {made.objects[held.object as u64].span}\n".span);
}
}
if held.group != now.group {
now.group = held.group;
if held.group != absent {
out.append($"g {made.groups[held.group as u64].span}\n".span);
} else {
out.append("g\n");
}
}
if held.material != now.material {
now.material = held.material;
if held.material != absent {
out.append($"usemtl {made.materials[held.material as u64].name.span}\n".span);
}
}
if held.smoothing != now.smoothing {
now.smoothing = held.smoothing;
if held.smoothing == 0 {
out.append("s off\n");
} else {
out.append($"s {held.smoothing}\n".span);
}
}
out.append(keyword);
for k in 0..held.count as u64 {
val c := made.corners[held.first + k];
out.append($" {c.position + 1}".span);
if c.uv != absent || c.normal != absent {
out.push('/');
if c.uv != absent {
out.append($"{c.uv + 1}".span);
}
if c.normal != absent {
out.append($"/{c.normal + 1}".span);
}
}
}
out.push('\n');
}
}
#! Writes materials as MTL's text: of each, its colors and numbers, and the
#! textures it maps, each with the options that aren't their defaults.
#! @param list The materials.
#! @returns The text.
pub def encode_materials(list: span<material>): string {
var out := string::new(nothing{});
out.append("# Written by malunal obj\n");
for i in 0..list.length {
val m := &list[i];
out.append($"\nnewmtl {m.name.span}\n".span);
put_color(&mut out, "Ka", m.ambient);
put_color(&mut out, "Kd", m.diffuse);
put_color(&mut out, "Ks", m.specular);
put_color(&mut out, "Ke", m.emissive);
if m.transmission.x != 0 || m.transmission.y != 0 || m.transmission.z != 0 {
put_color(&mut out, "Tf", m.transmission);
}
put_value(&mut out, "Ns", m.shininess);
put_value(&mut out, "Ni", m.ior);
put_value(&mut out, "d", m.dissolve);
out.append($"illum {m.illumination}\n".span);
val extra: strview[8] = ["sharpness", "Pr", "Pm", "Ps", "Pc", "Pcr", "aniso", "anisor"];
val values: f32[8] = [m.sharpness, m.roughness, m.metallic, m.sheen, m.clearcoat, m.clearcoat_roughness, m.anisotropy, m.anisotropy_rotation];
for k in 0..8 {
if values[k] != 0 {
put_value(&mut out, extra[k], values[k]);
}
}
for k in 0..m.maps.length {
put_map(&mut out, &m.maps[k]);
}
}
return out;
}
# A statement of a color.
def put_color(out: &mut string, keyword: strview, color: vec3): void {
out.append(keyword);
out.push(' ');
put_numbers(out, color.x, color.y, color.z);
out.push('\n');
}
# A statement of a number.
def put_value(out: &mut string, keyword: strview, value: f32): void {
out.append(keyword);
out.push(' ');
put_number(out, value);
out.push('\n');
}
# A texture map's statement: its options where they aren't their defaults,
# then its file.
def put_map(out: &mut string, held: &texture_map): void {
out.append(slot_name(held.slot));
if held.blend_u == false {
out.append(" -blendu off");
}
if held.blend_v == false {
out.append(" -blendv off");
}
if held.color_correct {
out.append(" -cc on");
}
if held.clamp {
out.append(" -clamp on");
}
if held.boost != 0 {
out.append(" -boost ");
put_number(out, held.boost);
}
if held.base != 0 || held.gain != 1 {
out.append(" -mm ");
put_numbers2(out, held.base, held.gain);
}
if held.offset.x != 0 || held.offset.y != 0 || held.offset.z != 0 {
out.append(" -o ");
put_numbers(out, held.offset.x, held.offset.y, held.offset.z);
}
if held.scale.x != 1 || held.scale.y != 1 || held.scale.z != 1 {
out.append(" -s ");
put_numbers(out, held.scale.x, held.scale.y, held.scale.z);
}
if held.turbulence.x != 0 || held.turbulence.y != 0 || held.turbulence.z != 0 {
out.append(" -t ");
put_numbers(out, held.turbulence.x, held.turbulence.y, held.turbulence.z);
}
if held.bump_multiplier != 1 {
out.append(" -bm ");
put_number(out, held.bump_multiplier);
}
if held.resolution != 0 {
out.append($" -texres {held.resolution}".span);
}
if held.channel != 0 {
out.append(" -imfchan ");
out.push(held.channel);
}
if held.kind.length != 0 {
out.append(" -type ");
out.append(held.kind.span);
}
out.push(' ');
out.append(held.file.span);
out.push('\n');
}
# A number, as the shortest text that reads back as it.
def put_number(out: &mut string, value: f32): void {
val text := $"{value}";
out.append(text.span);
}
def put_numbers2(out: &mut string, a: f32, b: f32): void {
put_number(out, a);
out.push(' ');
put_number(out, b);
}
def put_numbers(out: &mut string, a: f32, b: f32, c: f32): void {
put_numbers2(out, a, b);
out.push(' ');
put_number(out, c);
}
#! Writes a model to an OBJ file, and its materials, where it has any, to an MTL
#! file beside it: of the name of the first it read from, or of the OBJ file's
#! with `.mtl`. The folder is made where it isn't.
#! @param made The model.
#! @param at The OBJ file's path.
#! @returns Nothing, or why it couldn't be written: `unreadable` where a file
#! couldn't be written.
pub def save(made: &model, at: &path): result<void, obj_error> {
var folder := string::new(nothing{});
if at.parent() is some(&above) {
folder.append(above.span);
_ = io::create_directories(above);
}
var library := string::new(nothing{});
if made.materials.length != 0 {
if made.libraries.length != 0 {
library.append(made.libraries[0].span);
} else {
library.append($"{at.stem}.mtl".span);
}
var beside := string::new(nothing{});
if folder.length != 0 {
beside.append(folder.span);
beside.push('/');
}
beside.append(library.span);
val file := path::parse(beside.span) else (_) { return failed(failure::unreadable, $"{beside.span} isn't a path.".span); };
val text := encode_materials(made.materials.span);
io::write_file(&file, text.span) else (_) { return failed(failure::unreadable, $"{beside.span} couldn't be written.".span); };
}
val text := encode(made, library.span);
io::write_file(at, text.span) else (_) { return failed(failure::unreadable, $"{at.span} couldn't be written.".span); };
return;
}
#! Writes a model to a file named by text, as `save` does.
pub def save(made: &model, at: strview): result<void, obj_error> {
val named := path::parse(at) else (_) { return failed(failure::unreadable, $"{at} isn't a path.".span); };
return save(made, &named);
}