Skip to content
Merged
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
20 changes: 15 additions & 5 deletions bin/forma.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -18,9 +18,9 @@ function printHelp() {
process.stdout.write(
`forma ${VERSION} (WASM) — pure-Rust headless 3D polyhedral modeling engine for AI agents\n\n` +
`USAGE:\n` +
` forma-3d eval [--dialect pipe|compact] [--unit m|cm|mm|um|in|ft] [--strict|--no-strict] [--json] [--scene] [--out path.(glb|obj|stl|3mf|step|blend)] [--render preview.png] [--size 512] [--draw blueprint.svg] [file|-]\n` +
` forma-3d render [--size 512] --out preview.png [file|-]\n` +
` forma-3d draw --out blueprint.svg [file|-]\n` +
` forma-3d eval [--dialect pipe|compact] [--unit m|cm|mm|um|in|ft] [--strict|--no-strict] [--json] [--scene] [--out path.(glb|obj|stl|3mf|step|blend)] [--render preview.png] [--size 512] [--view quad|front|back|right|left|top|iso] [--draw blueprint.svg] [file|-]\n` +
` forma-3d render [--scene] [--size 512] [--view quad|front|back|right|left|top|iso] --out preview.png [file|-]\n` +
` forma-3d draw [--scene] --out blueprint.svg [file|-]\n` +
` forma-3d spec [--dialect pipe|compact] [--topic TOPIC] [--gbnf]\n` +
` forma-3d mcp\n` +
` forma-3d version | --version | -V\n\n` +
Expand Down Expand Up @@ -114,6 +114,7 @@ async function main() {
let renderPath = null;
let drawPath = null;
let renderSize = 512;
let renderView = "quad";
let inFile = null;

for (let i = 1; i < args.length; i++) {
Expand All @@ -138,6 +139,8 @@ async function main() {
usageErr(`invalid --size '${raw}': expected positive integer`);
}
renderSize = parsed;
} else if (a === "--view") {
renderView = requireVal(args, i++, a, "value (quad|front|back|right|left|top|iso)");
} else if (a === "--strict") {
strict = true;
} else if (a === "--no-strict") {
Expand Down Expand Up @@ -191,10 +194,14 @@ async function main() {
}
}
if (renderPath) {
await writeFile(renderPath, session.exportBytes("png", { size: renderSize }));
const pngBytes = exportScene
? session.exportScenePngBytes(renderSize, renderView)
: session.exportBytes("png", { size: renderSize, view: renderView });
await writeFile(renderPath, pngBytes);
}
if (drawPath) {
await writeFile(drawPath, session.exportBytes("svg"));
const svgData = exportScene ? session.exportSceneSvg() : session.exportBytes("svg");
await writeFile(drawPath, svgData);
}

if (asJson) {
Expand All @@ -212,6 +219,9 @@ async function main() {
} else {
process.stderr.write(`ERR: ${msg}\n`);
}
if (strict && msg.includes("invariant violation on '")) {
process.exit(3);
}
process.exit(1);
} finally {
session.free();
Expand Down
8 changes: 7 additions & 1 deletion crates/forma-cli/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,10 @@
//! forma version | --version | -V

use forma_core::{LintOptions, Scene, Unit};
use forma_lang::{eval_script, spec_topic, Dialect, SPEC_COMPACT, SPEC_PIPE, SPEC_PIPE_GBNF};
use forma_lang::{
eval_script, is_invariant_violation_err, spec_topic, Dialect, SPEC_COMPACT, SPEC_PIPE,
SPEC_PIPE_GBNF,
};
use std::io::{self, Read};
use std::path::PathBuf;
use std::process;
Expand Down Expand Up @@ -379,6 +382,9 @@ fn main() {
} else {
eprintln!("ERR: {e}");
}
if strict && is_invariant_violation_err(&e) {
process::exit(3);
}
process::exit(1);
}
}
Expand Down
59 changes: 59 additions & 0 deletions crates/forma-cli/tests/cli_exit_codes.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
use std::io::Write;
use std::process::{Command, Stdio};

fn run_forma(args: &[&str], stdin_data: &str) -> (i32, String, String) {
let bin = env!("CARGO_BIN_EXE_forma");
let mut child = Command::new(bin)
.args(args)
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.spawn()
.expect("spawn forma binary");
child
.stdin
.as_mut()
.unwrap()
.write_all(stdin_data.as_bytes())
.unwrap();
let out = child.wait_with_output().unwrap();
let code = out.status.code().unwrap_or(-1);
(
code,
String::from_utf8_lossy(&out.stdout).into_owned(),
String::from_utf8_lossy(&out.stderr).into_owned(),
)
}

#[test]
fn issue_84_strict_invariant_failure_exits_with_code_3() {
// 1. Self-intersecting torus in --strict mode exits 3
let (code, _, stderr) = run_forma(&["eval", "--strict", "-"], "a = torus(0.5, 1)\n");
assert_eq!(code, 3, "expected exit code 3 for strict self-intersection, stderr={stderr}");
assert!(stderr.contains("invariant violation"), "stderr={stderr}");

// 2. Overlapping multi-shell array in --strict mode exits 3
let (code2, _, stderr2) = run_forma(
&["eval", "--strict", "-"],
"a = box(1, 1, 1) | array(2, step=(0.5, 0, 0), union=false)\n",
);
assert_eq!(code2, 3, "expected exit code 3 for overlapping shells, stderr={stderr2}");

// 3. JSON mode still exits 3 on strict invariant failure
let (code3, stdout3, _) = run_forma(&["eval", "--strict", "--json", "-"], "a = torus(0.5, 1)\n");
assert_eq!(code3, 3, "expected exit code 3 in --json mode, stdout={stdout3}");
assert!(stdout3.contains("\"ok\":false"), "stdout={stdout3}");

// 4. Syntax/script error still exits 1
let (code_syn, _, _) = run_forma(&["eval", "--strict", "-"], "a = box(1,\n");
assert_eq!(code_syn, 1, "syntax error must still exit 1");

// 5. Unknown flag still exits 2
let (code_flag, _, _) = run_forma(&["eval", "--bogus-flag"], "a = box(1,1,1)\n");
assert_eq!(code_flag, 2, "unknown flag must still exit 2");

// 6. Valid solid exits 0
let (code_ok, stdout_ok, _) = run_forma(&["eval", "--strict", "-"], "a = box(1,1,1)\n");
assert_eq!(code_ok, 0);
assert!(stdout_ok.contains("WT=ok"));
}
50 changes: 48 additions & 2 deletions crates/forma-core/src/export.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,50 @@ use std::fs::File;
use std::io::{BufWriter, Write};
use std::path::Path;

/// Convert a single sRGB channel `[0, 1]` to linear light (IEC 61966-2-1) for glTF 2.0 `baseColorFactor`.
#[inline]
pub(crate) fn srgb_to_linear(c: f32) -> f32 {
let c = c.clamp(0.0, 1.0);
if c <= 0.04045 {
c / 12.92
} else {
((c + 0.055) / 1.055).powf(2.4)
}
}

/// Convert a single linear channel `[0, 1]` back to sRGB (IEC 61966-2-1) when importing glTF 2.0 colors.
#[inline]
pub(crate) fn linear_to_srgb(c: f32) -> f32 {
let c = c.clamp(0.0, 1.0);
if c <= 0.0031308 {
c * 12.92
} else {
1.055 * c.powf(1.0 / 2.4) - 0.055
}
}

/// Convert sRGB `[r, g, b, a]` (alpha stays linear per glTF 2.0) to linear `[r, g, b, a]`.
#[inline]
pub(crate) fn srgb_rgba_to_linear(rgba: [f32; 4]) -> [f32; 4] {
[
srgb_to_linear(rgba[0]),
srgb_to_linear(rgba[1]),
srgb_to_linear(rgba[2]),
rgba[3].clamp(0.0, 1.0),
]
}

/// Convert linear `[r, g, b, a]` (alpha stays linear per glTF 2.0) to sRGB `[r, g, b, a]`.
#[inline]
pub(crate) fn linear_rgba_to_srgb(rgba: [f32; 4]) -> [f32; 4] {
[
linear_to_srgb(rgba[0]),
linear_to_srgb(rgba[1]),
linear_to_srgb(rgba[2]),
rgba[3].clamp(0.0, 1.0),
]
}

/// 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] {
Expand Down Expand Up @@ -359,10 +403,11 @@ pub fn write_glb_bytes_with_unit(mesh: &PolyMesh, yup: bool, unit: Unit) -> Resu
s.push(',');
}
let name_json = serde_json::to_string(&mat.name).unwrap_or_else(|_| "\"mat\"".to_string());
let lin = srgb_rgba_to_linear(mat.color);
s.push_str(&format!(
r#"{{"name":{},"pbrMetallicRoughness":{{"baseColorFactor":[{},{},{},{}],"metallicFactor":{},"roughnessFactor":{}}}}}"#,
name_json,
mat.color[0], mat.color[1], mat.color[2], mat.color[3],
lin[0], lin[1], lin[2], lin[3],
mat.metallic, mat.roughness
));
}
Expand Down Expand Up @@ -502,10 +547,11 @@ pub fn write_scene_glb_bytes_with_unit(
let key = format!("{}:{:?}:{}:{}", mat.name, mat.color, mat.metallic, mat.roughness);
let mslot = *mat_dedup.entry(key).or_insert_with(|| {
let idx = gltf_materials.len();
let lin = srgb_rgba_to_linear(mat.color);
gltf_materials.push(serde_json::json!({
"name": mat.name,
"pbrMetallicRoughness": {
"baseColorFactor": mat.color,
"baseColorFactor": lin,
"metallicFactor": mat.metallic,
"roughnessFactor": mat.roughness
}
Expand Down
14 changes: 8 additions & 6 deletions crates/forma-core/src/import.rs
Original file line number Diff line number Diff line change
Expand Up @@ -483,12 +483,14 @@ pub fn read_glb_bytes_with_opts(bytes: &[u8], yup_override: Option<bool>) -> Res
.and_then(|p| p.get("baseColorFactor"))
.and_then(|v| v.as_array())
.filter(|a| a.len() >= 3)
.map(|a| [
a[0].as_f64().unwrap_or(0.7) as f32,
a[1].as_f64().unwrap_or(0.7) as f32,
a[2].as_f64().unwrap_or(0.7) as f32,
a.get(3).and_then(|x| x.as_f64()).unwrap_or(1.0) as f32,
])
.map(|a| {
crate::export::linear_rgba_to_srgb([
a[0].as_f64().unwrap_or(0.7) as f32,
a[1].as_f64().unwrap_or(0.7) as f32,
a[2].as_f64().unwrap_or(0.7) as f32,
a.get(3).and_then(|x| x.as_f64()).unwrap_or(1.0) as f32,
])
})
.unwrap_or([0.72, 0.75, 0.80, 1.0]);
let metallic = pbr.and_then(|p| p.get("metallicFactor")).and_then(|v| v.as_f64()).unwrap_or(0.1) as f32;
let roughness = pbr.and_then(|p| p.get("roughnessFactor")).and_then(|v| v.as_f64()).unwrap_or(0.5) as f32;
Expand Down
Loading