Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
37 changes: 37 additions & 0 deletions crates/forma-core/src/uv.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1383,6 +1383,43 @@ fn partition_chart_by_cut(ch: &Chart, axis: usize, cut_val: f64) -> (Vec<usize>,
(a_faces, b_faces)
}

/// World-scale box (triplanar) projection for tiling materials.
///
/// Each face is projected onto the plane of its dominant normal axis, so one UV
/// unit spans `tile` metres on every face (`meters_per_unit` converts model
/// units) and repeating textures keep the same scale everywhere. Opposite faces
/// are not mirrored. Writes per-corner UVs to `mesh.faces[fi].uvs`.
pub fn unwrap_box(mesh: &mut PolyMesh, meters_per_unit: f64, tile: f64) -> Result<(), String> {
if !(tile.is_finite() && tile > 0.0) {
return Err(format!("box_uv: tile must be a positive number, got {tile}"));
}
if mesh.faces.is_empty() || mesh.verts.is_empty() {
return Err("box_uv: empty mesh".into());
}
let k = meters_per_unit / tile;
for fi in 0..mesh.faces.len() {
let n = mesh.face_normal(fi);
let (ax, ay, az) = (n.x.abs(), n.y.abs(), n.z.abs());
let uvs: Vec<[f32; 2]> = mesh.faces[fi]
.verts
.iter()
.map(|&vi| {
let p = mesh.verts[vi] * k;
let (u, v) = if az >= ax && az >= ay {
(p.x, if n.z >= 0.0 { p.y } else { -p.y })
} else if ax >= ay {
(if n.x >= 0.0 { p.y } else { -p.y }, p.z)
} else {
(if n.y >= 0.0 { -p.x } else { p.x }, p.z)
};
[u as f32, v as f32]
})
.collect();
mesh.faces[fi].uvs = uvs;
}
Ok(())
}

/// Unwrap `mesh` using dihedral angle seam segmentation + LSCM + ARAP + rotating-calipers +
/// multi-strategy MaxRects atlas packing guided by Forma's 2-stage `int4` decision models.
/// Writes non-overlapping `[0, 1]^2` UV coordinates directly onto `mesh.faces[fi].uvs`.
Expand Down
40 changes: 40 additions & 0 deletions crates/forma-core/tests/box_uv_export.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
//! GLB export of `box_uv` UVs (#67).
use forma_core::export::export_mesh_bytes_with_unit;
use forma_core::Unit;

#[test]
fn glb_export_carries_box_uvs() {
let mut m = forma_core::primitives::make_box(2.0, 2.0, 2.0, 1);
forma_core::uv::unwrap_box(&mut m, Unit::Meter.meters_per_unit(), 1.0).unwrap();
let glb = export_mesh_bytes_with_unit(&m, "glb", Unit::Meter).unwrap();
let jlen = u32::from_le_bytes([glb[12], glb[13], glb[14], glb[15]]) as usize;
let gltf: serde_json::Value = serde_json::from_slice(&glb[20..20 + jlen]).unwrap();
let idx = gltf["meshes"][0]["primitives"][0]["attributes"]["TEXCOORD_0"]
.as_u64()
.expect("TEXCOORD_0") as usize;
let acc = &gltf["accessors"][idx];
let view = &gltf["bufferViews"][acc["bufferView"].as_u64().unwrap() as usize];
let bin = 20 + jlen + 8; // skip the BIN chunk header
let start = bin
+ view["byteOffset"].as_u64().unwrap_or(0) as usize
+ acc["byteOffset"].as_u64().unwrap_or(0) as usize;
let stride = view["byteStride"].as_u64().unwrap_or(8) as usize;
let (mut lo, mut hi) = ([f32::INFINITY; 2], [f32::NEG_INFINITY; 2]);
for i in 0..acc["count"].as_u64().unwrap() as usize {
for k in 0..2 {
let o = start + i * stride + k * 4;
let x = f32::from_le_bytes(glb[o..o + 4].try_into().unwrap());
lo[k] = lo[k].min(x);
hi[k] = hi[k].max(x);
}
}
assert_eq!((lo, hi), ([-1.0, -1.0], [1.0, 1.0]));
}

#[test]
fn box_uv_rejects_bad_tile_and_empty_mesh() {
let mut m = forma_core::primitives::make_box(1.0, 1.0, 1.0, 1);
assert!(forma_core::uv::unwrap_box(&mut m, 1.0, 0.0).is_err());
assert!(forma_core::uv::unwrap_box(&mut m, 1.0, f64::NAN).is_err());
assert!(forma_core::uv::unwrap_box(&mut forma_core::PolyMesh::new(), 1.0, 1.0).is_err());
}
1 change: 1 addition & 0 deletions crates/forma-lang/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -102,6 +102,7 @@ pub fn spec_topic(topic: &str) -> Result<&'static str, String> {
"Forma-Pipe // Smooth Normals & LSCM UVs:\n\
- `smooth(angle=35, weighted=true)` / `flat()` — auto-smooth & area/angle-weighted normals in GLB\n\
- `unwrap(angle=45, margin=0.01)` — pure-Rust LSCM conformal UV unwrap + MaxRects atlas pack into [0,1]^2\n\
- `box_uv(tile=1)` — world-scale box projection for tiling materials: 1 UV repeat per `tile` metres on every face\n\
- `decimate(ratio=0.5, faces=)` — Link-Condition QEM LOD reduction keeping WT=ok NM=0"
),
"remesh" => Ok(
Expand Down
11 changes: 9 additions & 2 deletions crates/forma-lang/src/pipeline.rs
Original file line number Diff line number Diff line change
Expand Up @@ -385,7 +385,7 @@ fn max_pipe_positional(op_name: &str) -> Option<usize> {
"mat" | "material" => 4,
"mirror" => 2,
"pattern_linear" | "array" | "pattern_radial" | "radial" => 3,
"decimate" | "lod" | "remesh" => 1,
"decimate" | "lod" | "remesh" | "box_uv" => 1,
"flat" => 0,
"smooth" | "unwrap" | "uv" => 2,
"solidify" | "deform" | "bisect" => 3,
Expand Down Expand Up @@ -416,7 +416,7 @@ const PIPE_OP_NAMES: &[&str] = &[
"add", "union", "cut", "sub", "diff", "intersect", "bevel", "shell", "extrude", "inset", "subsurf",
"subdiv", "move", "translate", "rot", "rotate", "scale", "align_z0", "align", "on", "place_on", "mat", "material",
"color", "mirror", "pattern_linear", "array", "pattern_radial", "radial", "decimate", "lod", "smooth", "flat",
"solidify", "deform", "unwrap", "uv", "remesh", "bisect",
"solidify", "deform", "unwrap", "uv", "box_uv", "remesh", "bisect",
];

/// " — did you mean 'x'?" for the closest known name, plus the full list of accepted names.
Expand Down Expand Up @@ -522,6 +522,7 @@ fn allowed_pipe_kwargs(op_name: &str) -> Option<&'static [&'static str]> {
"solidify" => &["t", "thickness", "offset", "open_top"],
"deform" => &["mode", "axis", "path", "corners", "angle", "factor", "subdivs"],
"unwrap" | "uv" => &["angle", "margin"],
"box_uv" => &["tile"],
"remesh" => &["voxel_size", "size"],
"bisect" => &["normal", "offset", "clear_inner"],
_ => return None,
Expand Down Expand Up @@ -2058,6 +2059,12 @@ impl<'a> Parser<'a> {
));
Ok(mesh)
}
"box_uv" => {
let tile = kw.get("tile").or_else(|| pos.first()).map(|v| v.as_num(&ctx)).transpose()?.unwrap_or(1.0);
forma_core::uv::unwrap_box(&mut mesh, self.scene.unit.meters_per_unit(), tile)
.map_err(|e| format!("{ctx}: {e}"))?;
Ok(mesh)
}
"remesh" => {
let vs = kw.get("voxel_size").or_else(|| kw.get("size")).or_else(|| pos.first())
.map(|v| v.as_num(&ctx)).transpose()?.unwrap_or(0.0);
Expand Down
77 changes: 77 additions & 0 deletions crates/forma-lang/tests/box_uv.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
//! `box_uv(tile=)`: world-scale box projection UVs for tiling materials (#67).
use forma_core::{PolyMesh, Scene};
use forma_lang::{eval_script, Dialect};

fn part(src: &str, name: &str) -> (Scene, PolyMesh) {
let mut s = Scene::new();
eval_script(&mut s, Dialect::Pipe, src).unwrap();
let m = (**s.get_part(name).unwrap()).clone();
(s, m)
}

/// UV bounds over all face corners.
fn uv_bounds(m: &PolyMesh) -> ([f32; 2], [f32; 2]) {
let mut lo = [f32::INFINITY; 2];
let mut hi = [f32::NEG_INFINITY; 2];
for f in &m.faces {
assert_eq!(f.uvs.len(), f.verts.len(), "every face corner gets a UV");
for uv in &f.uvs {
for k in 0..2 {
lo[k] = lo[k].min(uv[k]);
hi[k] = hi[k].max(uv[k]);
}
}
}
(lo, hi)
}

#[test]
fn one_uv_unit_per_tile_metres_on_every_face() {
let (_, m) = part("a = box(2, 4, 6) | box_uv(1)", "a");
for (fi, f) in m.faces.iter().enumerate() {
// Each face's UV extent equals its two in-plane side lengths in metres.
let mut lo = [f32::INFINITY; 2];
let mut hi = [f32::NEG_INFINITY; 2];
for uv in &f.uvs {
for k in 0..2 {
lo[k] = lo[k].min(uv[k]);
hi[k] = hi[k].max(uv[k]);
}
}
let n = m.face_normal(fi);
let want = if n.z.abs() > 0.5 { [2.0, 4.0] } else if n.x.abs() > 0.5 { [4.0, 6.0] } else { [2.0, 6.0] };
let got = [hi[0] - lo[0], hi[1] - lo[1]];
assert!((got[0] - want[0]).abs() < 1e-5 && (got[1] - want[1]).abs() < 1e-5, "face {fi}: {got:?} != {want:?}");
}
}

#[test]
fn tile_and_scene_unit_set_the_repeat_size() {
let (_, m) = part("a = box(2, 2, 2) | box_uv(tile=2)", "a");
assert_eq!(uv_bounds(&m), ([-0.5, -0.5], [0.5, 0.5]));

// 2000 mm == 2 m, so a mm scene gets the same UVs as the metre scene.
let (_, mm) = part("units(\"mm\")\na = box(2000, 2000, 2000) | box_uv(tile=2)", "a");
assert_eq!(uv_bounds(&mm), ([-0.5, -0.5], [0.5, 0.5]));
}

#[test]
fn opposite_faces_are_not_mirrored() {
let (_, m) = part("a = box(1, 1, 1) | box_uv(1)", "a");
for (fi, f) in m.faces.iter().enumerate() {
// Signed UV area must be positive for an outward-facing CCW face.
let mut area = 0.0f32;
for i in 0..f.uvs.len() {
let (a, b) = (f.uvs[i], f.uvs[(i + 1) % f.uvs.len()]);
area += a[0] * b[1] - b[0] * a[1];
}
assert!(area > 0.0, "face {fi} has mirrored UVs (signed area {area})");
}
}

#[test]
fn invalid_tile_is_rejected() {
for src in ["a = box(1, 1, 1) | box_uv(0)", "a = box(1, 1, 1) | box_uv(-1)", "a = box(1, 1, 1) | box_uv(size=1)"] {
assert!(eval_script(&mut Scene::new(), Dialect::Pipe, src).is_err(), "{src}");
}
}
2 changes: 1 addition & 1 deletion grammar/forma_pipe.gbnf
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ pipe-op ::= "add" | "union" | "cut" | "sub" | "diff" | "intersect"
| "pattern_linear" | "pattern_radial" | "array" | "radial"
| "mat" | "material" | "color"
| "decimate" | "lod" | "smooth" | "flat" | "solidify" | "deform"
| "unwrap" | "uv" | "remesh" | "bisect"
| "unwrap" | "uv" | "box_uv" | "remesh" | "bisect"

ident ::= [a-zA-Z_] [a-zA-Z0-9_]*
number ::= ([0-9]+ ("." [0-9]*)? | "." [0-9]+) ([eE] [+-]? [0-9]+)?
Expand Down
Loading