Files
models/obj/writing.sakura
T

272 lines
8.9 KiB
Plaintext
Raw Normal View History

2026-10-30 12:04:54 -05:00
#! 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);
}