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
16 changes: 1 addition & 15 deletions crates/forma-core/src/export.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
use crate::math::Vec3;
use crate::mesh::PolyMesh;
use crate::units::Unit;
use crate::uv::triplanar_uv;
use std::fs::File;
use std::io::{BufWriter, Write};
use std::path::Path;
Expand Down Expand Up @@ -52,21 +53,6 @@ pub(crate) fn linear_rgba_to_srgb(rgba: [f32; 4]) -> [f32; 4] {
]
}

/// Compute deterministic triplanar box UV coordinates for vertex `p` on a face with normal `n`.
#[inline]
fn triplanar_uv(p: Vec3, n: Vec3) -> [f32; 2] {
let ax = n.x.abs();
let ay = n.y.abs();
let az = n.z.abs();
if az >= ax && az >= ay {
[p.x as f32, p.y as f32]
} else if ax >= ay {
[p.y as f32, p.z as f32]
} else {
[p.x as f32, p.z as f32]
}
}

#[inline]
fn normalize_f32_unit(n: [f32; 3], fallback: [f32; 3], yup: bool) -> [f32; 3] {
if n[0].is_finite() && n[1].is_finite() && n[2].is_finite() {
Expand Down
47 changes: 42 additions & 5 deletions crates/forma-core/src/uv.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,5 @@
//! Pure-Rust LSCM (Least Squares Conformal Maps) UV Unwrapping + Rotating-Calipers
//! Orientation + MaxRects Best-Short-Side-Fit (BSSF) UV Atlas Packer.
//!
//! Zero external crates; populates `Face::uvs` directly for non-overlapping `[0, 1]^2`
//! game-engine / baking-ready `TEXCOORD_0` export in glTF 2.0.
//! Box projection and LSCM (Least Squares Conformal Maps) atlas unwrapping.
//! Both write per-corner `Face::uvs` for glTF `TEXCOORD_0` export.

use crate::math::Vec3;
use crate::mesh::{edge_key, EdgeAdjacency, PolyMesh};
Expand Down Expand Up @@ -1383,6 +1380,46 @@ fn partition_chart_by_cut(ch: &Chart, axis: usize, cut_val: f64) -> (Vec<usize>,
(a_faces, b_faces)
}

/// Compute deterministic triplanar box UV coordinates for vertex `p` on a face with normal `n`.
#[inline]
pub(crate) fn triplanar_uv(p: Vec3, n: Vec3) -> [f32; 2] {
let ax = n.x.abs();
let ay = n.y.abs();
let az = n.z.abs();
if az >= ax && az >= ay {
[p.x as f32, p.y as f32]
} else if ax >= ay {
[p.y as f32, p.z as f32]
} else {
[p.x as f32, p.z as f32]
}
}

/// Project each face onto its dominant axis plane at `scale` UV units per mesh unit.
pub fn box_uv(mesh: &mut PolyMesh, scale: f64) -> Result<(), String> {
if !scale.is_finite() || scale <= 0.0 {
return Err("scale must be positive and finite".into());
}

let mut projected = Vec::with_capacity(mesh.faces.len());
for (fi, face) in mesh.faces.iter().enumerate() {
let normal = mesh.face_normal(fi);
let uvs: Vec<_> = face
.verts
.iter()
.map(|&vi| triplanar_uv(mesh.verts[vi] * scale, normal))
.collect();
if uvs.iter().flatten().any(|coord| !coord.is_finite()) {
return Err("projected UV coordinates must be finite".into());
}
projected.push(uvs);
}
for (face, uvs) in mesh.faces.iter_mut().zip(projected) {
face.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
39 changes: 38 additions & 1 deletion crates/forma-lang/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -99,9 +99,10 @@ pub fn spec_topic(topic: &str) -> Result<&'static str, String> {
- `sweep(profile2d, path3d, scale_end=1.0, twist=0.0, closed=false)` -> tapered/twisted 3D rail sweep"
),
"uv" | "normals" => Ok(
"Forma-Pipe // Smooth Normals & LSCM UVs:\n\
"Forma-Pipe // Smooth Normals & 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(scale=1.0)` — dominant-axis UV projection with scale repeats per model unit\n\
- `decimate(ratio=0.5, faces=)` — Link-Condition QEM LOD reduction keeping WT=ok NM=0"
),
"remesh" => Ok(
Expand Down Expand Up @@ -207,6 +208,42 @@ mod tests {
assert_eq!(s.unit, forma_core::Unit::Meter);
}

#[test]
fn box_uv_projects_at_model_scale() {
let mut scene = Scene::new();
scene.strict_manifold = true;
eval_script(
&mut scene,
Dialect::Pipe,
"units(\"mm\")\nbase = box(12, 8, 4) | move(8, 8, 8)\n\
tiled = base | box_uv(scale=0.25)\nfull = box_uv(base)",
)
.unwrap();

let tiled = scene.get_part("tiled").unwrap();
let full = scene.get_part("full").unwrap();
for (tag, expected_min, expected_max) in [
("top", [0.5, 1.0], [3.5, 3.0]),
("front", [0.5, 1.5], [3.5, 2.5]),
("right", [1.0, 1.5], [3.0, 2.5]),
] {
for (mesh, factor) in [(tiled, 1.0), (full, 4.0)] {
let face = mesh.faces.iter().find(|face| face.has_tag(tag)).unwrap();
assert_eq!(face.uvs.len(), face.verts.len());
for axis in 0..2 {
let coords = || face.uvs.iter().map(|uv| uv[axis]);
let min = coords().fold(f32::INFINITY, f32::min);
let max = coords().fold(f32::NEG_INFINITY, f32::max);
assert_eq!([min, max], [expected_min[axis] * factor, expected_max[axis] * factor]);
}
}
}
for scale in ["0", "-1", "1e100"] {
let script = format!("tiled = base | box_uv(scale={scale})");
assert!(eval_script(&mut scene, Dialect::Pipe, &script).is_err());
}
}

#[test]
fn test_fallback_bevel_segs_warning() {
let mut s = Scene::new();
Expand Down
12 changes: 9 additions & 3 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" => &["scale"],
"remesh" => &["voxel_size", "size"],
"bisect" => &["normal", "offset", "clear_inner"],
_ => return None,
Expand Down Expand Up @@ -1401,7 +1402,7 @@ impl<'a> Parser<'a> {
| "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" => {
if pos.is_empty() {
return Err(format!("{ctx}: requires target mesh as first argument (or use `mesh | {name}(...)`)"));
}
Expand Down Expand Up @@ -2048,6 +2049,11 @@ impl<'a> Parser<'a> {
}
}
}
"box_uv" => {
let scale = kw.get("scale").or_else(|| pos.first()).map(|v| v.as_num(&ctx)).transpose()?.unwrap_or(1.0);
forma_core::uv::box_uv(&mut mesh, scale).map_err(|e| format!("{ctx}: {e}"))?;
Ok(mesh)
}
"unwrap" | "uv" => {
let angle = kw.get("angle").or_else(|| pos.first()).map(|v| v.as_num(&ctx)).transpose()?.unwrap_or(45.0);
let margin = kw.get("margin").or_else(|| pos.get(1)).map(|v| v.as_num(&ctx)).transpose()?.unwrap_or(0.01) as f32;
Expand Down
6 changes: 4 additions & 2 deletions docs/reference/language-and-formats.md
Original file line number Diff line number Diff line change
Expand Up @@ -63,10 +63,12 @@ Query via `forma spec --topic <name>`, `npx forma-3d spec --topic <name>`, `GET
| --- | --- | --- |
| `deform` | `deform` | `solidify(t, offset=-1.0, open_top=false)`, `deform("bend"\|"twist"\|"taper", axis=, angle=, factor=, subdivs=)`, `deform("curve", path=, axis=)`, `deform("lattice", corners=[8 Vec3 points in (x,y,z) bit order])` |
| `curves` | `curves` | `bezier([(x,y,z), ...], segs=24)`, `nurbs([(x,y,z), ...], degree=3, segs=32, weights=)`, `extrude2d(outer, z0, z1, holes=...)`, `sweep(profile2d, path3d, scale_end=1.0, twist=0.0, closed=false)` |
| `uv` | `uv`, `normals` | `smooth(angle=35, weighted=true)`, `flat()`, `unwrap(angle=45, margin=0.01)`, `decimate(ratio=0.5, faces=)` |
| `uv` | `uv`, `normals` | `smooth(angle=35, weighted=true)`, `flat()`, `unwrap(angle=45, margin=0.01)`, `box_uv(scale=1.0)`, `decimate(ratio=0.5, faces=)` |
| `remesh` | `remesh` | `remesh(voxel_size=0.0)` (`0` = auto `diag/28`), `bisect(normal=(0,0,1), offset=0.0, clear_inner=false)`, `load("path.glb\|obj\|stl", yup=)` |
| `scene` | `scene` | Multi-object scene graph export & rendering (`--scene` in CLI, `scene: true` in MCP `export` for `.glb`, `.blend`, `.png`, and `.svg`, `exportSceneBytes()` in JS/TS); `_`-prefixed locals and `del("name")`. |

`box_uv(scale=1.0)` projects each face onto the plane that best matches its normal. Wall faces use Z for the vertical texture coordinate. Apply it after placement and scaling to project from the final model coordinates. The scale gives texture repeats per model unit, so `box_uv(scale=0.25)` repeats every four metres in a metre scene.

## Invariant metrics (`MeshInvariants`)

| Field | Observation key | Strict requirement |
Expand Down Expand Up @@ -95,7 +97,7 @@ Query via `forma spec --topic <name>`, `npx forma-3d spec --topic <name>`, `GET

| Format | Extension | Direction | Unit handling | Axis / notes |
| --- | --- | --- | --- | --- |
| Binary glTF 2.0 | `.glb` | Import + Export | Scaled to meters (`meters_per_unit()`) | Y-up conversion, PBR materials, optional `TEXCOORD_0` UVs (via `unwrap()`); supports multi-node `--scene` / `scene: true`. |
| Binary glTF 2.0 | `.glb` | Import + Export | Scaled to meters (`meters_per_unit()`) | Y-up conversion, PBR materials, optional `TEXCOORD_0` UVs (via `unwrap()` or `box_uv()`), and multi-node scene export (`--scene` or `scene: true`). |
| STEP AP214 | `.step`, `.stp` | Export | Declares model unit in header | Faceted B-Rep solid for CAD interoperability. |
| 3D Manufacturing Format | `.3mf` | Export | Declares `model/@unit` | Ready for modern 3D-printing slicers. |
| Binary STL | `.stl` | Import + Export | Raw model units (format has no unit field) | Triangulated mesh. |
Expand Down
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