Snapshot: draw a see-through appearance see-through, and show a tool body inside its target (#2329) (#2330)

* Snapshot: draw a see-through appearance see-through, and give the CLI --body, --tool and --section

A headless picture dropped a body's opacity: the scene carried only a colour, so a design with
a translucent appearance was drawn opaque by `solidcraft-cli snapshot`, by MCP screenshots and
in a design's thumbnail, although the window has always drawn it as glass. There was then no
way to look at the body a cut would remove inside the material it meets: only a volume to
measure and reason about, which hides exactly the errors a picture makes obvious (a tool that
stops short, or lands in the wrong place).

- `SceneMesh` carries the body's opacity; `view::build_scene` takes it from the design
  (`model_body_opacity`), and a selected body stays solid so the selection colour reads.
- The GPU capture routes a see-through body into the scene's glass at its own alpha, as the
  viewport does; the CPU rasterizer draws the solid bodies first (they own the depth buffer),
  then the see-through ones blended over them, far sides before near sides and without writing
  depth, so what lies inside shows and a line between the two is not hidden.
- `snapshot --body NAME:opacity=0.3,color=#rrggbb`, `--tool NAME` (that body solid in the tool
  colour, the rest see-through) and `--section z=27` run the commands the app itself runs
  (`appearance.assign`, `inspect.section`): the options are shortcuts, not a second renderer.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

* Tests: measure the tool colour as it is drawn through a see-through target

The tool-colour filter was derived on paper and demanded a red more than twice either other
channel, which the target in front of it tints away (measured: (200, 108, 85) through opacity
0.3); and the colour check painted the tool, which a solid target hides.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

* fmt

* Snapshot options: strip the colour's # rather than slicing it; README

Slicing `value[1..]` on an input-derived string is what the house rules ask us not to write,
even where a length check has already made it safe. The error a failed assignment reports now
names the body rather than claiming it came from --body, since --tool reaches it too.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

* --tool: assign the bodies around the tool in groups, not one command at a time

Each appearance.assign is an undo step with a document snapshot behind it, so one per body
made --tool cost grow with the size of the design for no reason: the bodies around the tool
all get the same opacity, and the ones that share a colour can be named in one call. A design
whose bodies all wear the default grey now costs two commands whatever its size.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

* Rasterizer: say where its glass and the GPU's differ

Splitting each see-through body by facing orders its own two layers; it does not sort across
bodies, which the GPU does. Worth stating rather than leaving a reader to find it.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
Co-authored-by: bherbruck <brennen.herbruck@gmail.com>
This commit is contained in:
Brazz
2026-10-19 16:10:45 -04:00
committed by GitHub
parent f68a3dd5d5
commit 26f42ae09b
17 changed files with 904 additions and 106 deletions
+1
View File
@@ -45,6 +45,7 @@ Editable drawing code, native projects and shipped exports are collected under `
| docs/book/src/generated/enclosure.png | SolidCraft contributors | rendered by `cargo xtask book` (`solidcraft-cli snapshot docs/book/scripts/enclosure.json`; gitignored) | MIT OR Apache-2.0 |
| docs/book/src/generated/revolve.png | SolidCraft contributors | rendered by `cargo xtask book` (`solidcraft-cli snapshot docs/book/scripts/revolve.json`; gitignored) | MIT OR Apache-2.0 |
| docs/book/src/generated/sheet-metal.png | SolidCraft contributors | rendered by `cargo xtask book` (`solidcraft-cli snapshot docs/book/scripts/sheet-metal.json`; gitignored) | MIT OR Apache-2.0 |
| docs/book/src/generated/tool-preview.png | SolidCraft contributors | rendered by `cargo xtask book` (`solidcraft-cli snapshot docs/book/scripts/tool-preview.json`; gitignored) | MIT OR Apache-2.0 |
| assets/fonts/liberation-sans/LiberationSans-Regular.ttf | Red Hat, Inc. (Liberation Fonts 2.x; digitized data Google) | https://github.com/liberationfonts (Debian fonts-liberation), unmodified; licence text in assets/fonts/liberation-sans/OFL.txt; used for sketch Text outlines | SIL OFL 1.1 |
| assets/fonts/biz-udp-gothic/BIZUDPGothic-Regular.ttf | The BIZ UDGothic Project Authors | https://github.com/googlefonts/morisawa-biz-ud-gothic (Google Fonts), unmodified; licence text in assets/fonts/biz-udp-gothic/OFL.txt; used for web UI Japanese font | SIL OFL 1.1 |
| tests/oracle/17-loft/reference.stl | SolidCraft contributors | triangulation of our own recipe (tests/oracle/17-loft/recipe.json) built with FreeCAD as an external tool by tools/freecad-oracle | MIT OR Apache-2.0 |
+4
View File
@@ -197,6 +197,9 @@ rebuild with no errors, replayed here at 2× speed.
and an optional reviewed screenshot; opening GitHub does not submit the report.
- **Headless CLI** `solidcraft-cli`: run command scripts, measure (volume, area, centre of mass,
face/edge/vertex counts), export, render PNG snapshots and replay reference recipes.
A snapshot can draw a body see-through and another solid in a colour of its own, and cut
the model at a plane, so a picture shows the body a cut would remove inside the material
it meets.
- **MCP server** `solidcraft-cli mcp`: AI agents model, measure and look at parts headless or
in the running app (see below).
@@ -207,6 +210,7 @@ cargo run --release -p solidcraft -- --sample # desktop app with a samp
cargo run --release -p solidcraft-cli -- commands # the command registry
cargo run --release -p solidcraft-cli -- run examples/bracket.json --out bracket.step
cargo run --release -p solidcraft-cli -- snapshot examples/bracket.json --out bracket.png
cargo run --release -p solidcraft-cli -- snapshot part.solidcraft --out preview.png --tool Pin --section z=12
cargo run --release -p solidcraft-cli -- render examples/render-studio.json --out product.png
cargo run --release -p solidcraft -- part.step # open a STEP file as a new design
cargo run --release -p solidcraft-cli -- eval part.step # measure an imported STEP file
+19 -2
View File
@@ -7,6 +7,7 @@
//! solidcraft-cli bench-open <design.solidcraft | part.step> [--parse-only] [--display LEVEL [--edit NAME EXPR]] loading timings as JSON lines
//! solidcraft-cli bench-agent [--scale F] [--save F] [--script-out F] a ~1,300-body design built command by command, timed
//! solidcraft-cli snapshot <script|design> [--in design|part.step] --out shot.png [--width W] [--height H] [--view iso|front|top|…|NAME | --camera JSON] [--no-grid] [--no-axes]
//! [--body NAME:opacity=0.3,color=#rrggbb]... [--tool NAME]... [--section z=27]
//! solidcraft-cli exec <command> [json-params] run one command on an empty design
//! solidcraft-cli commands the command registry as JSON
//! solidcraft-cli recipe <recipe.json> translate an oracle recipe to a script
@@ -23,6 +24,7 @@ mod bench_agent;
mod crashes;
mod fuzz;
mod oracle;
mod preview;
mod recipe;
mod render;
mod spatial;
@@ -50,11 +52,18 @@ const USAGE: &str = "usage:
solidcraft-cli bench-open <design.solidcraft | part.step> [--parse-only] [--display LEVEL [--edit NAME EXPR]]
solidcraft-cli bench-agent [--scale F] [--save design.solidcraft] [--script-out script.json]
solidcraft-cli snapshot <script|design> [--in design.solidcraft|part.step] --out shot.png [--width W] [--height H] [--view NAME | --camera JSON] [--no-grid] [--no-axes]
[--body NAME:opacity=0.3,color=#rrggbb]... [--tool NAME]... [--section z=27]
solidcraft-cli snapshot --in <design.solidcraft|part.step> --out shot.png ...
(as with run, --in starts from a design and the script runs on top of it; an option snapshot doesn't take is an error;
--view: iso, front, back, top, bottom, left, right, or the name of a view saved in the design with view.save;
--camera: {target: [x,y,z], yaw, pitch, distance, fov?} in mm and radians, as the MCP screenshot takes it (docs/mcp.md);
--no-grid and --no-axes leave the ground grid (on Z 0) and the origin's axes out of the picture)
--no-grid and --no-axes leave the ground grid (on Z 0) and the origin's axes out of the picture;
--body: how one body is drawn, as appearance.assign takes it: opacity 0-1 (below 1 is see-through, so what is inside
it shows) and color #rrggbb, either or both, once per body;
--tool: draw this body solid in the tool colour and every other body see-through, so a cut's or a join's tool body
is visible inside the material it meets; a later --body overrides it;
--section: cut the model as inspect.section does, so the inside shows: z=27 (the plane through that world
coordinate, keeping the smaller side), add ,flip to keep the other side, or XY, XZ, YZ, or its own JSON)
solidcraft-cli render <script|design> --out image.png [--setup NAME] [--width W] [--height H] [--transparent] [--overwrite] [--timeout SECONDS]
solidcraft-cli exec <command> [json-params]
solidcraft-cli commands
@@ -405,7 +414,12 @@ fn install_renderer() {
fn cmd_snapshot(args: &[String]) -> Result<(), String> {
install_renderer();
known_flags("snapshot", args, &["--in", "--out", "--width", "--height", "--view", "--camera"], &["--no-grid", "--no-axes"])?;
known_flags(
"snapshot",
args,
&["--in", "--out", "--width", "--height", "--view", "--camera", "--body", "--tool", "--section"],
&["--no-grid", "--no-axes"],
)?;
if positional(args).is_none() && flag(args, "--in").is_none() {
return Err(USAGE.to_string());
}
@@ -416,6 +430,9 @@ fn cmd_snapshot(args: &[String]) -> Result<(), String> {
};
let (w, h) = (size("--width", 1280)?, size("--height", 800)?);
let mut s = open(flag(args, "--in"), positional(args))?;
// How the bodies are drawn and where the model is cut, through the commands the app's
// Appearance dialog and Section Analysis run (`preview`).
preview::apply(&mut s, &flags(args, "--body"), &flags(args, "--tool"), flag(args, "--section"))?;
// The camera choices of the MCP `screenshot`, through the same command (`view.apply`): a
// standard view, a view saved in the design, or an explicit camera. A script that applies a
// view itself sets the camera too; without any, the iso view framing the model.
+286
View File
@@ -0,0 +1,286 @@
//! What a `snapshot` draws see-through, what it draws in a colour of its own, and where it cuts
//! the model: the `--body`, `--tool` and `--section` options.
//!
//! None of this is a renderer of its own. Each option turns into the command the app itself runs
//! — `appearance.assign` for the Appearance dialog, `inspect.section` for Section Analysis — so
//! a picture of a tool body inside a translucent target is the picture the window would show
//! with the same appearances assigned, and a script can do the same thing without the options.
use serde_json::{Value, json};
use solidcraft_engine::Session;
/// How see-through the bodies around a `--tool` are drawn: enough to read the tool through them,
/// solid enough to keep the shape of the material it meets.
pub const TARGET_OPACITY: f64 = 0.3;
/// A `--tool` body's colour: the hue the viewport's feature preview uses for removed material,
/// so a cut's tool looks in a picture the way the preview looks in the window.
pub const TOOL_COLOR: &str = "#e8542c";
/// The colour of a body with no appearance of its own ([`solidcraft_engine::view::colors::BODY`]),
/// as `appearance.assign` takes it. Giving a body an opacity means giving it a look, and a look
/// carries a colour: this keeps the one it is already drawn in.
fn default_body_hex() -> String {
let c = solidcraft_engine::view::colors::BODY;
format!("#{:02x}{:02x}{:02x}", c.0, c.1, c.2)
}
/// How one body is drawn: `--body NAME:opacity=0.3,color=#cc3333`. Either key alone is enough;
/// the other keeps what the design already says.
#[derive(Debug, PartialEq)]
pub struct BodyLook {
pub name: String,
pub opacity: Option<f64>,
pub color: Option<String>,
}
/// `NAME:key=value[,key=value]`, or `NAME` on its own (which says nothing and is an error:
/// a body is named here to change how it is drawn).
pub fn parse_body(spec: &str) -> Result<BodyLook, String> {
let (name, rest) = spec
.split_once(':')
.ok_or_else(|| format!("--body `{spec}` must be NAME:key=value (`Target:opacity=0.3`, `Tool:color=#cc3333`, keys separated by commas)"))?;
let name = name.trim();
if name.is_empty() {
return Err(format!("--body `{spec}` names no body"));
}
let mut look = BodyLook { name: name.to_owned(), opacity: None, color: None };
for part in rest.split(',') {
let part = part.trim();
if part.is_empty() {
continue;
}
let (key, value) = part.split_once('=').ok_or_else(|| format!("--body {name}: `{part}` must be key=value (opacity, color)"))?;
let value = value.trim();
match key.trim().to_ascii_lowercase().as_str() {
"opacity" => {
let o: f64 = value.parse().map_err(|_| format!("--body {name}: opacity must be a number 0 to 1, not `{value}`"))?;
if !o.is_finite() || !(0.0..=1.0).contains(&o) {
return Err(format!("--body {name}: opacity must be 0 to 1, not `{value}`"));
}
look.opacity = Some(o);
}
"color" => {
let digits = value.strip_prefix('#').filter(|h| h.len() == 6 && h.chars().all(|c| c.is_ascii_hexdigit()));
let digits = digits.ok_or_else(|| format!("--body {name}: color must be #rrggbb, not `{value}`"))?;
look.color = Some(format!("#{}", digits.to_ascii_lowercase()));
}
other => return Err(format!("--body {name}: unknown key `{other}` (opacity, color)")),
}
}
if look.opacity.is_none() && look.color.is_none() {
return Err(format!("--body `{spec}` asks for nothing: give opacity, color, or both"));
}
Ok(look)
}
/// The `inspect.section` parameters a `--section` spec asks for: `z=27` (the plane through that
/// world coordinate, its normal along +Z), `XY` (a named plane through the origin), either with
/// `,flip` to keep the other side, or the command's own JSON object.
pub fn parse_section(spec: &str) -> Result<Value, String> {
let spec = spec.trim();
if spec.starts_with('{') {
return serde_json::from_str(spec).map_err(|e| format!("--section: not JSON: {e}"));
}
let mut parts = spec.split(',').map(str::trim);
let plane = parts.next().unwrap_or_default();
let mut flip = false;
for p in parts {
match p.to_ascii_lowercase().as_str() {
"" => {}
"flip" => flip = true,
other => return Err(format!("--section: unknown `{other}` (only `flip` follows the plane)")),
}
}
// A named plane through the world origin, as `inspect.section` takes it.
let mut params = match plane.to_ascii_uppercase().as_str() {
p @ ("XY" | "XZ" | "YZ") => json!({"plane": p}),
_ => {
// AXIS=VALUE: the plane whose normal is that axis, cutting at that world coordinate.
let (axis, at) = plane.split_once('=').ok_or_else(|| {
format!("--section `{spec}` must be z=27 (a world coordinate on an axis), XY, XZ, YZ, or the JSON inspect.section takes")
})?;
let at: f64 = at.trim().parse().map_err(|_| format!("--section {axis}: `{}` is not a number", at.trim()))?;
if !at.is_finite() {
return Err(format!("--section {axis}: `{at}` is not a finite coordinate"));
}
// The plane normal to each axis: Z is XY, Y is XZ, X is YZ.
let named = match axis.trim().to_ascii_lowercase().as_str() {
"x" => "YZ",
"y" => "XZ",
"z" => "XY",
other => return Err(format!("--section: unknown axis `{other}` (x, y or z)")),
};
json!({"plane": named, "at": at})
}
};
if flip {
params["flip"] = json!(true);
}
Ok(params)
}
/// The design's body names, for an error that says which ones there are.
fn body_names(s: &Session) -> Vec<String> {
s.model.state().bodies.iter().map(|b| b.name.clone()).collect()
}
/// The colour and opacity a body is drawn with now, as `appearance.assign` takes them: its own
/// appearance, else its component's or material's, else the default body colour.
fn current_look(s: &mut Session, name: &str) -> Result<(String, f64), String> {
let reply = s.execute("appearance.list", &json!({"body": name})).map_err(|e| e.to_string())?;
let body = reply.get("body");
let look = body.and_then(|b| b.get("appearance")).filter(|a| !a.is_null());
let hex = look
.and_then(|a| a.get("color"))
.and_then(Value::as_str)
.map(str::to_owned)
// No appearance, but an imported colour: `body.color` is that colour, 0..1 per channel.
.or_else(|| {
let c = body?.get("color")?.as_array()?;
let ch = |i: usize| -> Option<u8> { Some((c.get(i)?.as_f64()?.clamp(0.0, 1.0) * 255.0).round() as u8) };
Some(format!("#{:02x}{:02x}{:02x}", ch(0)?, ch(1)?, ch(2)?))
})
.unwrap_or_else(default_body_hex);
let opacity = look.and_then(|a| a.get("opacity")).and_then(Value::as_f64).filter(|o| o.is_finite()).unwrap_or(1.0);
Ok((hex, opacity))
}
/// Draw `name` with `look`, keeping whichever of colour and opacity it does not give.
fn assign(s: &mut Session, look: &BodyLook) -> Result<(), String> {
let name = &look.name;
if !body_names(s).iter().any(|b| b == name) {
return Err(format!("no body `{name}` in the design (it has {})", body_list(s)));
}
let (hex, opacity) = current_look(s, name)?;
let params = json!({
"bodies": [name],
"color": look.color.clone().unwrap_or(hex),
"opacity": look.opacity.unwrap_or(opacity),
});
s.execute("appearance.assign", &params).map(|_| ()).map_err(|e| format!("drawing `{name}`: {e}"))
}
/// The design's bodies, named, for an error message.
fn body_list(s: &Session) -> String {
let names = body_names(s);
if names.is_empty() { "no bodies".to_owned() } else { names.join(", ") }
}
/// Apply the options to the session, in the order a later one overrides an earlier: the `--tool`
/// preview first (it speaks for every body), then each `--body`, then the section.
pub fn apply(s: &mut Session, bodies: &[&str], tools: &[&str], section: Option<&str>) -> Result<(), String> {
// Everything is read before anything is drawn, so a misspelt option is an error rather than
// half a picture.
let looks: Vec<BodyLook> = bodies.iter().map(|spec| parse_body(spec)).collect::<Result<_, _>>()?;
let section = section.map(parse_section).transpose()?;
if !tools.is_empty() {
let names = body_names(s);
for t in tools {
if !names.iter().any(|b| b == t) {
return Err(format!("--tool: no body `{t}` in the design (it has {})", body_list(s)));
}
}
// Everything but the tool see-through, in the colour it already has, so the tool reads
// against the material it meets. Bodies that share a colour are assigned together: a
// design of many bodies then costs a command or two rather than one for each.
let mut around: std::collections::BTreeMap<String, Vec<String>> = std::collections::BTreeMap::new();
for name in names.iter().filter(|n| !tools.contains(&n.as_str())) {
around.entry(current_look(s, name)?.0).or_default().push(name.clone());
}
for (hex, sharing_it) in around {
let params = json!({"bodies": sharing_it, "color": hex, "opacity": TARGET_OPACITY});
s.execute("appearance.assign", &params).map_err(|e| format!("--tool: {e}"))?;
}
// Then the tool itself, solid in the tool colour.
let params = json!({"bodies": tools, "color": TOOL_COLOR, "opacity": 1.0});
s.execute("appearance.assign", &params).map_err(|e| format!("--tool: {e}"))?;
}
for look in &looks {
assign(s, look)?;
}
if let Some(params) = section {
s.execute("inspect.section", &params).map_err(|e| format!("--section: {e}"))?;
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
/// `--body` names a body and says how it is drawn. Either key alone is enough.
#[test]
fn a_body_spec_is_a_name_and_the_keys_appearance_assign_takes() {
let look = |s: &str| parse_body(s).unwrap();
assert_eq!(look("Target:opacity=0.3"), BodyLook { name: "Target".into(), opacity: Some(0.3), color: None });
assert_eq!(look("Tool:color=#CC3333"), BodyLook { name: "Tool".into(), opacity: None, color: Some("#cc3333".into()) });
assert_eq!(look("Tool: opacity = 1 , color = #00ff00 "), BodyLook { name: "Tool".into(), opacity: Some(1.0), color: Some("#00ff00".into()) });
// A body name with a space in it, as the browser shows them.
assert_eq!(look("Bracket arm:opacity=0").name, "Bracket arm");
assert_eq!(look("A:opacity=0").opacity, Some(0.0));
}
/// Every way of getting `--body` wrong is an error that says what it takes, never a panic
/// and never a silently ignored option.
#[test]
fn a_bad_body_spec_says_what_it_takes() {
for (spec, expect) in [
("Target", "NAME:key=value"),
(":opacity=0.3", "names no body"),
("Target:", "asks for nothing"),
("Target:opacity", "key=value"),
("Target:opacity=high", "0 to 1"),
("Target:opacity=1.5", "0 to 1"),
("Target:opacity=-0.2", "0 to 1"),
("Target:opacity=NaN", "0 to 1"),
("Target:opacity=inf", "0 to 1"),
("Target:color=red", "#rrggbb"),
("Target:color=#ccc", "#rrggbb"),
("Target:color=#gggggg", "#rrggbb"),
("Target:alpha=0.3", "unknown key `alpha`"),
] {
let e = parse_body(spec).err().unwrap_or_else(|| panic!("{spec} was accepted"));
assert!(e.contains(expect), "{spec}: {e}");
}
}
/// A `--section` spec is the plane `inspect.section` cuts with: an axis and a world
/// coordinate, a named plane, `flip` for the other side, or the command's own JSON.
#[test]
fn a_section_spec_is_the_plane_inspect_section_takes() {
let p = |s: &str| parse_section(s).unwrap();
// The plane normal to each axis, cutting at that coordinate.
assert_eq!(p("z=27"), json!({"plane": "XY", "at": 27.0}));
assert_eq!(p("y=-5.5"), json!({"plane": "XZ", "at": -5.5}));
assert_eq!(p("X=0"), json!({"plane": "YZ", "at": 0.0}));
assert_eq!(p("z=27,flip"), json!({"plane": "XY", "at": 27.0, "flip": true}));
// A named plane through the origin, and the command's own parameters.
assert_eq!(p("XY"), json!({"plane": "XY"}));
assert_eq!(p("yz,flip"), json!({"plane": "YZ", "flip": true}));
assert_eq!(p("{\"plane\": \"XY\", \"offset\": 4}"), json!({"plane": "XY", "offset": 4}));
}
#[test]
fn a_bad_section_spec_says_what_it_takes() {
for (spec, expect) in [
("27", "z=27"),
("w=4", "unknown axis `w`"),
("z=high", "is not a number"),
("z=inf", "not a finite coordinate"),
("z=27,upside-down", "unknown `upside-down`"),
("{\"plane\":", "not JSON"),
] {
let e = parse_section(spec).err().unwrap_or_else(|| panic!("{spec} was accepted"));
assert!(e.contains(expect), "{spec}: {e}");
}
}
/// The tool colour is the one the options document, in the form `appearance.assign` takes.
#[test]
fn the_tool_colour_is_a_hex_colour_the_command_takes() {
assert_eq!(parse_body(&format!("Tool:color={TOOL_COLOR}")).unwrap().color, Some(TOOL_COLOR.to_owned()));
assert!((0.0..1.0).contains(&TARGET_OPACITY), "a target must be see-through: {TARGET_OPACITY}");
assert_eq!(default_body_hex(), "#b0bac6");
}
}
@@ -0,0 +1,221 @@
//! `snapshot --body`, `--tool` and `--section`: a picture of a tool body inside the material it
//! meets, which is the one picture that says whether a cut reaches through.
//!
//! Each option is a shortcut for the command the app itself runs (`appearance.assign`,
//! `inspect.section`), so every test here asserts that the option's picture is the picture of a
//! script that runs those commands — not that the pixels match a stored image. Pictures are
//! compared with a tolerance, and the tests run on whatever renderer the machine has (a GPU, a
//! software adapter, or the CPU rasterizer), because they only ever compare two pictures this
//! same CLI drew.
use std::path::{Path, PathBuf};
use std::process::{Command, Output};
use std::sync::atomic::{AtomicUsize, Ordering};
use serde_json::{Value, json};
static NEXT: AtomicUsize = AtomicUsize::new(0);
const SIZE: (u32, u32) = (200, 140);
/// A PNG's size and RGBA pixels.
fn decode(png: &[u8]) -> (u32, u32, Vec<u8>) {
let img = image::load_from_memory_with_format(png, image::ImageFormat::Png).unwrap().to_rgba8();
(img.width(), img.height(), img.into_raw())
}
/// Pixels of two same-sized pictures that differ by more than a little in some channel.
fn differing(a: &[u8], b: &[u8]) -> usize {
let ((wa, ha, a), (wb, hb, b)) = (decode(a), decode(b));
assert_eq!((wa, ha), (wb, hb), "pictures of different sizes");
a.as_chunks::<4>().0.iter().zip(b.as_chunks::<4>().0).filter(|(p, q)| p.iter().zip(q.iter()).any(|(x, y)| x.abs_diff(*y) > 16)).count()
}
/// The same picture: a renderer's output may differ by a few levels or a stray edge pixel.
#[track_caller]
fn assert_same(a: &[u8], b: &[u8], what: &str) {
let (n, total) = (differing(a, b), (SIZE.0 * SIZE.1) as usize);
assert!(n * 500 <= total, "{what}: {n} of {total} pixels differ");
}
/// Different pictures: more than stray pixels differ.
#[track_caller]
fn assert_differs(a: &[u8], b: &[u8], what: &str) {
let n = differing(a, b);
assert!(n >= 100, "{what}: only {n} pixels differ");
}
/// How much of a picture is the tool colour (`preview::TOOL_COLOR`, #e8542c): a red neither
/// the default body grey nor the background has, still recognisable once a see-through body in
/// front of it has tinted it (measured on this machine: (200, 108, 85) through a target at
/// opacity 0.3, against (164, 173, 184) for the plain grey).
fn tool_pixels(png: &[u8]) -> usize {
let (_, _, px) = decode(png);
px.as_chunks::<4>().0.iter().filter(|p| p[0] > 140 && p[0] > p[1].saturating_add(50) && p[0] > p[2].saturating_add(50)).count()
}
struct Scratch(PathBuf);
impl Scratch {
fn new() -> Self {
let dir =
std::env::temp_dir().join(format!("solidcraft-snapshot-appearance-{}-{}", std::process::id(), NEXT.fetch_add(1, Ordering::Relaxed)));
std::fs::create_dir(&dir).unwrap();
Self(dir)
}
/// A plate with a pin standing in it: the tool body a cut would remove, reaching 6 mm short
/// of the far face, which is exactly what a picture is supposed to show and a volume is not.
/// `more` runs on top.
fn script(&self, name: &str, more: &[Value]) -> PathBuf {
let mut steps = vec![
json!({"command": "solid.box", "params": {"length": 50, "width": 34, "height": 20, "center": [0, 0, 10], "body_name": "Target"}}),
json!({"command": "solid.cylinder", "params": {"diameter": 12, "height": 14, "base": [0, 0, 0], "operation": "new_body", "body_name": "Tool"}}),
];
steps.extend(more.iter().cloned());
let path = self.0.join(name);
std::fs::write(&path, json!({"commands": steps}).to_string()).unwrap();
path
}
fn run(&self, script: &Path, out: &str, extra: &[&str]) -> Output {
let (w, h) = (SIZE.0.to_string(), SIZE.1.to_string());
Command::new(env!("CARGO_BIN_EXE_solidcraft-cli"))
.arg("snapshot")
.arg(script)
.arg("--out")
.arg(self.0.join(out))
.args(["--width", &w, "--height", &h, "--no-grid", "--no-axes"])
.args(extra)
.output()
.unwrap()
}
/// The PNG `snapshot` writes.
fn snapshot(&self, script: &Path, out: &str, extra: &[&str]) -> Vec<u8> {
let output = self.run(script, out, extra);
assert!(output.status.success(), "{extra:?}: {}", String::from_utf8_lossy(&output.stderr));
let png = std::fs::read(self.0.join(out)).unwrap();
assert!(png.starts_with(b"\x89PNG"), "{extra:?}");
png
}
}
impl Drop for Scratch {
fn drop(&mut self) {
let _ = std::fs::remove_dir_all(&self.0);
}
}
/// `--body NAME:opacity=…` draws that body see-through, and the picture is the one a script
/// gets by assigning the same appearance itself: the option is the command, not a second way
/// of drawing.
#[test]
fn a_body_drawn_see_through_is_the_picture_of_the_same_appearance_assigned() {
let dir = Scratch::new();
let plain = dir.script("plain.json", &[]);
let assigned =
dir.script("assigned.json", &[json!({"command": "appearance.assign", "params": {"bodies": ["Target"], "color": "#b0bac6", "opacity": 0.3}})]);
let solid = dir.snapshot(&plain, "solid.png", &[]);
let see_through = dir.snapshot(&plain, "see-through.png", &["--body", "Target:opacity=0.3"]);
assert_differs(&see_through, &solid, "--body opacity was ignored");
assert_same(&see_through, &dir.snapshot(&assigned, "by-script.png", &[]), "the same appearance assigned by a script");
// The option's colour is the design's too. It names the target, not the tool: the tool is
// inside the target, so a solid target hides whatever colour the tool is given.
let painted =
dir.script("painted.json", &[json!({"command": "appearance.assign", "params": {"bodies": ["Target"], "color": "#00aa33", "opacity": 1.0}})]);
let by_option = dir.snapshot(&plain, "painted.png", &["--body", "Target:color=#00aa33"]);
assert_differs(&by_option, &solid, "--body color was ignored");
assert_same(&by_option, &dir.snapshot(&painted, "painted-script.png", &[]), "the same colour assigned by a script");
}
/// `--tool NAME` is the whole point: the tool solid in the tool colour, every other body
/// see-through, so the tool shows inside the material it meets. The tool's colour covers more
/// of the picture than it does without the option, because the target no longer hides it.
#[test]
fn a_tool_shows_through_the_bodies_around_it() {
let dir = Scratch::new();
let script = dir.script("part.json", &[]);
let plain = dir.snapshot(&script, "plain.png", &["--view", "front"]);
let preview = dir.snapshot(&script, "preview.png", &["--view", "front", "--tool", "Tool"]);
assert_differs(&preview, &plain, "--tool was ignored");
// Seen from the front the plate hides the pin completely; the preview shows all of it.
assert_eq!(tool_pixels(&plain), 0, "nothing is the tool colour before the option");
assert!(tool_pixels(&preview) > 200, "the tool shows through the target: {} pixels", tool_pixels(&preview));
// It is the two commands it stands for, run in that order.
let by_script = dir.script(
"by-script.json",
&[
json!({"command": "appearance.assign", "params": {"bodies": ["Target"], "color": "#b0bac6", "opacity": 0.3}}),
json!({"command": "appearance.assign", "params": {"bodies": ["Tool"], "color": "#e8542c", "opacity": 1.0}}),
],
);
assert_same(&preview, &dir.snapshot(&by_script, "script.png", &["--view", "front"]), "the appearances --tool assigns");
// A later --body overrides what --tool said.
let overridden = dir.snapshot(&script, "override.png", &["--view", "front", "--tool", "Tool", "--body", "Tool:color=#2255cc"]);
assert!(tool_pixels(&overridden) < 50, "--body after --tool decides the tool's colour");
}
/// `--section` cuts the model where `inspect.section` would, and the same spec written as the
/// command's own JSON, or as the command in a script, gives the same picture.
#[test]
fn a_section_cuts_the_model_as_inspect_section_does() {
let dir = Scratch::new();
let script = dir.script("part.json", &[]);
let whole = dir.snapshot(&script, "whole.png", &[]);
let cut = dir.snapshot(&script, "cut.png", &["--section", "z=12"]);
assert_differs(&cut, &whole, "--section was ignored");
assert_same(&cut, &dir.snapshot(&script, "cut-json.png", &["--section", r#"{"plane": "XY", "at": 12}"#]), "the command's own JSON");
let by_script = dir.script("sectioned.json", &[json!({"command": "inspect.section", "params": {"plane": "XY", "at": 12}})]);
assert_same(&cut, &dir.snapshot(&by_script, "by-script.png", &[]), "inspect.section in a script");
// The other side of the same plane is a different picture.
let flipped = dir.snapshot(&script, "flipped.png", &["--section", "z=12,flip"]);
assert_differs(&flipped, &cut, "flip keeps the other side");
// A section through a see-through target still shows the tool inside it.
let both = dir.snapshot(&script, "both.png", &["--section", "z=12", "--tool", "Tool"]);
assert_differs(&both, &cut, "--tool and --section together");
assert!(tool_pixels(&both) > 100, "the tool is in the cut picture");
}
/// Every way of getting the options wrong is an error that says what it takes, and writes no
/// picture: a snapshot that quietly ignored an option would be a lie about the design.
#[test]
fn a_body_tool_or_section_that_cannot_be_used_is_an_error_and_writes_nothing() {
let dir = Scratch::new();
let script = dir.script("part.json", &[]);
let cases: [(&[&str], &str); 8] = [
(&["--body", "Nowhere:opacity=0.3"], "no body `Nowhere`"),
(&["--body", "Target"], "NAME:key=value"),
(&["--body", "Target:opacity=3"], "0 to 1"),
(&["--body", "Target:alpha=0.3"], "unknown key `alpha`"),
(&["--body", "Target:color=red"], "#rrggbb"),
(&["--tool", "Nowhere"], "no body `Nowhere`"),
(&["--section", "q=1"], "unknown axis `q`"),
(&["--section", "nonsense"], "z=27"),
];
for (extra, expect) in cases {
let output = dir.run(&script, "never.png", extra);
let stderr = String::from_utf8_lossy(&output.stderr);
assert_eq!(output.status.code(), Some(1), "{extra:?}: {stderr}");
assert!(stderr.contains(expect), "{extra:?}: {stderr}");
assert!(output.stdout.is_empty() && !dir.0.join("never.png").exists(), "{extra:?}");
}
// An error naming a body says which bodies the design has.
let stderr = String::from_utf8_lossy(&dir.run(&script, "never.png", &["--tool", "Nowhere"]).stderr).to_string();
assert!(stderr.contains("Target") && stderr.contains("Tool"), "{stderr}");
}
/// The usage text says what the options do.
#[test]
fn the_usage_names_the_body_tool_and_section_options() {
let output = Command::new(env!("CARGO_BIN_EXE_solidcraft-cli")).arg("snapshot").output().unwrap();
let stderr = String::from_utf8_lossy(&output.stderr);
for word in ["--body", "--tool", "--section", "appearance.assign", "inspect.section", "see-through"] {
assert!(stderr.contains(word), "usage lacks {word}: {stderr}");
}
}
+2 -1
View File
@@ -36,7 +36,8 @@ fn scene(s: &Session) -> Option<(Scene, Camera)> {
let color = s.doc.body_color(body).map_or(crate::view::colors::BODY, |[r, g, b]| Rgb(channel(r), channel(g), channel(b)));
let face_colors =
s.doc.face_colors(body).into_iter().map(|(face, look)| (face as u32, Rgb(look.color[0], look.color[1], look.color[2]))).collect();
scene.meshes.push(SceneMesh { mesh, color, face_colors });
let opacity = s.doc.model_body_opacity(body) as f32;
scene.meshes.push(SceneMesh { mesh, color, face_colors, opacity });
}
if bounds.is_empty() {
return None;
+4 -1
View File
@@ -501,7 +501,10 @@ fn build_scene(
} else {
s.doc.face_colors(body).into_iter().map(|(f, l)| (f as u32, Rgb(l.color[0], l.color[1], l.color[2]))).collect()
};
sc.meshes.push(SceneMesh { mesh: Arc::clone(&mesh), color, face_colors });
// A see-through appearance is drawn see-through, as the viewport draws it; a selected
// body is drawn solid, so the selection colour reads.
let opacity = if selected { 1.0 } else { s.doc.model_body_opacity(body) as f32 };
sc.meshes.push(SceneMesh { mesh: Arc::clone(&mesh), color, face_colors, opacity });
for (i, e) in mesh.edges.iter().enumerate() {
if !mesh.shaded_edge_visible(i) {
continue;
+28
View File
@@ -191,3 +191,31 @@ fn every_scene_colour_comes_from_its_palette_and_appearances_stay() {
assert_eq!(mesh(&default, "Plain").0, colors::BODY);
assert_eq!(mesh(&default, "Picked").0, colors::BODY_SELECTED);
}
/// A see-through appearance reaches the picture: the scene carries the body's opacity, so the
/// renderers draw it as glass and what is inside it shows. A selected body stays solid, as in
/// the viewport, so the selection colour reads.
#[test]
fn a_see_through_appearance_reaches_the_scene() {
let mut s = Session::default();
for (name, x) in [("Target", 0.), ("Tool", 20.), ("Picked", 40.)] {
s.execute("solid.box", &json!({"length": 10, "width": 10, "height": 10, "corner": [x, 0, 0], "operation": "new_body", "body_name": name}))
.unwrap();
}
s.execute("appearance.assign", &json!({"bodies": ["Target"], "color": "#b0bac6", "opacity": 0.3})).unwrap();
s.execute("appearance.assign", &json!({"bodies": ["Picked"], "color": "#b0bac6", "opacity": 0.3})).unwrap();
s.selection = vec![Sel::Body { name: "Picked".into() }];
let cam = home_camera(&s);
let sc = scene(&s, &cam);
let names: Vec<String> = s.world_state().bodies.iter().filter(|b| s.body_visible(&b.name)).map(|b| b.name.clone()).collect();
let opacity = |name: &str| names.iter().position(|n| n == name).and_then(|i| sc.meshes.get(i)).map(|m| (m.opacity, m.glass())).unwrap();
assert_eq!(opacity("Target"), (0.3, true), "the design's opacity is the one the renderers draw");
assert_eq!(opacity("Tool"), (1.0, false), "a body with no appearance of its own is solid");
assert_eq!(opacity("Picked"), (1.0, false), "a selected body is drawn solid, so the selection colour reads");
// Clearing the appearance makes it solid again.
s.execute("appearance.assign", &json!({"bodies": ["Target"], "color": null})).unwrap();
let sc = scene(&s, &cam);
assert_eq!(sc.meshes.first().map(|m| m.opacity), Some(1.0));
}
+70 -3
View File
@@ -350,11 +350,14 @@ fn frame(scene: &Scene, cam: &Camera, [width, height]: [u32; 2], key: u64, acces
/// A scene's meshes and lines as the viewport's model scene: faces in their colours (smooth
/// normals; a face normal where a vertex has none), lines as wide lines (over everything when
/// `on_top`), the grid under everything.
/// `on_top`), the grid under everything. A body whose appearance is see-through
/// ([`solidcraft_render::SceneMesh::glass`]) goes into the scene's glass, drawn as the viewport
/// draws glass: far sides first, then near sides, so what lies inside it shows through.
pub fn scene_geometry(scene: &Scene) -> GpuScene {
let mut sc = GpuScene::default();
let c4 = |c: Rgb| [c.0, c.1, c.2, 255];
for m in &scene.meshes {
let alpha = (m.alpha() * 255.0).round().clamp(0.0, 255.0) as u8;
let c4 = |c: Rgb| [c.0, c.1, c.2, alpha];
let faces: HashMap<u32, Rgb> = m.face_colors.iter().copied().collect();
let mesh = &m.mesh;
for (ti, t) in mesh.triangles.iter().enumerate() {
@@ -363,10 +366,15 @@ pub fn scene_geometry(scene: &Scene) -> GpuScene {
let flat = (b - a).cross(c - a).normalized().unwrap_or(Vec3::Z);
for (k, p) in t.iter().zip([a, b, c]) {
let n = mesh.normals.get(*k as usize).copied().filter(|n| n.is_finite() && n.len() > 0.5).unwrap_or(flat);
sc.tri(p.to_f32(), n.to_f32(), col);
if m.glass() {
sc.glass_tri(p.to_f32(), n.to_f32(), col);
} else {
sc.tri(p.to_f32(), n.to_f32(), col);
}
}
}
}
let c4 = |c: Rgb| [c.0, c.1, c.2, 255];
for l in &scene.grid {
for w in l.points.windows(2) {
sc.under_line(w[0].to_f32(), w[1].to_f32(), c4(l.color), l.width as f32);
@@ -470,3 +478,62 @@ fn background_pipeline(device: &wgpu::Device, samples: u32, depth: wgpu::Texture
cache: None,
})
}
#[cfg(test)]
mod tests {
use super::*;
use crate::view::TRI_SIZE;
use solidcraft_geom::Mesh;
use solidcraft_render::SceneMesh;
use std::sync::Arc;
/// One triangle facing the camera.
fn sheet() -> Arc<Mesh> {
Arc::new(Mesh {
positions: vec![Vec3::new(-1.0, 0.0, -1.0), Vec3::new(1.0, 0.0, -1.0), Vec3::new(0.0, 0.0, 1.0)],
normals: vec![Vec3::new(0.0, -1.0, 0.0); 3],
triangles: vec![[0, 1, 2]],
tri_face: vec![0],
..Default::default()
})
}
/// The alpha of a triangle `scene_geometry` wrote (the last byte of its first vertex).
fn alpha(bytes: &[u8]) -> Option<u8> {
bytes.get(TRI_SIZE - 1).copied()
}
/// A body the design draws see-through goes into the scene's glass, at its own alpha, and
/// not among the solid triangles: that is how the viewport draws glass, and it is why a
/// headless picture of a translucent target shows the tool inside it.
#[test]
fn a_see_through_body_is_glass_at_its_own_alpha_and_a_solid_one_is_not() {
let mesh = |opacity: f32| SceneMesh { mesh: sheet(), color: Rgb(200, 30, 30), face_colors: Vec::new(), opacity };
let geometry = |opacity: f32| scene_geometry(&Scene { meshes: vec![mesh(opacity)], ..Default::default() });
let solid = geometry(1.0);
assert_eq!((solid.tris.len(), solid.glass.len()), (3 * TRI_SIZE, 0));
assert_eq!(alpha(&solid.tris), Some(255), "a solid body is drawn opaque");
let glass = geometry(0.3);
assert_eq!((glass.tris.len(), glass.glass.len()), (0, 3 * TRI_SIZE), "a see-through body is glass, not a solid triangle");
assert_eq!(alpha(&glass.glass), Some(77), "0.3 of 255");
// The threshold and the floor are the viewport's: an appearance a hair under 1 stays
// solid, and opacity 0 still leaves a trace rather than vanishing.
let almost = geometry(0.9995);
assert_eq!((almost.tris.len(), almost.glass.len()), (3 * TRI_SIZE, 0), "an appearance a hair under 1 is still solid");
assert_eq!(alpha(&geometry(0.0).glass), Some(13), "0.05 of 255");
}
/// A face with a colour of its own is drawn in that colour, and takes its body's opacity:
/// painting one face does not make the body solid again.
#[test]
fn a_painted_face_keeps_its_bodys_opacity() {
let mesh = SceneMesh { mesh: sheet(), color: Rgb(200, 30, 30), face_colors: vec![(0, Rgb(0, 255, 0))], opacity: 0.5 };
let sc = scene_geometry(&Scene { meshes: vec![mesh], ..Default::default() });
assert_eq!(sc.tris.len(), 0);
let first = sc.glass.get(TRI_SIZE - 4..TRI_SIZE);
assert_eq!(first, Some(&[0, 255, 0, 128][..]), "the face's own colour at the body's alpha");
}
}
+1 -6
View File
@@ -146,12 +146,7 @@ fn sheet(tilt: f64) -> Mesh {
/// A front view of `mesh` with `lines`, as part of a design of `radius`, 40 mm high on 200 px.
fn front(mesh: Mesh, lines: Vec<SceneLine>, radius: f64, fov: f64) -> (Scene, Camera) {
let scene = Scene {
meshes: vec![SceneMesh { mesh: Arc::new(mesh), color: Rgb(160, 165, 175), face_colors: Vec::new() }],
lines,
radius,
..Default::default()
};
let scene = Scene { meshes: vec![SceneMesh::solid(Arc::new(mesh), Rgb(160, 165, 175))], lines, radius, ..Default::default() };
let mut cam = Camera { distance: if fov > 0.0 { 25.0 / (fov * 0.5).tan() } else { 62.5 }, fov, ..Default::default() };
cam.set_view(StandardView::Front);
(scene, cam)
+3 -1
View File
@@ -187,7 +187,9 @@ pub fn tool_definitions() -> Vec<Value> {
Connected to the app: a screenshot of the window (source \"window\", the default) or a render of the model \
with the app's camera (source \"model\"). Both show an active section (inspect.section) with its cut face \
capped. `view` first turns the camera to a standard view or a saved named view (view.save), `camera` to any camera (as view.apply). \
`grid: false` and `axes: false` leave the ground grid (on Z 0) and the origin's axes out of a model render.",
`grid: false` and `axes: false` leave the ground grid (on Z 0) and the origin's axes out of a model render. \
A body whose appearance is see-through (appearance.assign with an `opacity` below 1) is drawn see-through, \
so what is inside it shows: that is how to look at the body a cut would remove inside the material it meets.",
obj(
json!({
"view": string(
+1 -1
View File
@@ -32,4 +32,4 @@ pub use curve_display::{PixelCurveView, SampledPath, SamplingBudget, SamplingQua
pub use gif::gif;
pub use product::{FaceAppearance, ProductMesh, ProductScene};
pub use raster::{Canvas, render, render_png, render_transparent};
pub use scene::{Rgb, SECTION_CAP, Scene, SceneLine, SceneMesh, png};
pub use scene::{MIN_ALPHA, Rgb, SECTION_CAP, SEE_THROUGH, Scene, SceneLine, SceneMesh, png};
+196 -89
View File
@@ -35,6 +35,40 @@ impl Canvas {
}
}
/// The order a scene's bodies are drawn in. Solid bodies come first and own the depth buffer;
/// the see-through ones are then blended over them, far sides before near sides, so a
/// translucent body reads like glass and whatever lies inside it shows through. This is the
/// order the GPU viewport draws its own glass in.
///
/// Splitting each see-through body by facing orders its own two layers, which is what a single
/// translucent body needs. Two see-through bodies that overlap on screen blend in the order the
/// scene lists them, where the GPU sorts its glass triangles back to front: the difference shows
/// only where translucent bodies lie in front of each other, which the CPU rasterizer (a
/// fallback for machines without a GPU) does not try to match.
#[derive(Clone, Copy, PartialEq, Eq)]
enum Pass {
Solid,
GlassFar,
GlassNear,
}
impl Pass {
/// Does this pass draw the see-through bodies ([`SceneMesh::glass`])?
fn glass(self) -> bool {
self != Pass::Solid
}
/// Does it draw a triangle whose facing is `inside` (away from the eye)? A solid body draws
/// both: its back faces show only where a section opens it.
fn takes(self, inside: bool) -> bool {
match self {
Pass::Solid => true,
Pass::GlassFar => inside,
Pass::GlassNear => !inside,
}
}
}
pub(crate) fn shade(n: Vec3, view_dir: Vec3, base: [f64; 3]) -> [f64; 3] {
let n = if n.dot(view_dir) < 0.0 { -n } else { n };
let key = (view_dir * 0.8 + Vec3::new(-0.3, 0.2, 0.6)).normalized().unwrap_or(view_dir);
@@ -79,91 +113,104 @@ pub fn render(scene: &Scene, cam: &Camera, w: usize, h: usize) -> Canvas {
// depth test.
let mut slope = vec![0f32; sw * sh];
let cap_tint = scene.cap.unwrap_or(SECTION_CAP).f();
for sm in &scene.meshes {
let m = &sm.mesh;
let body = sm.color.f();
let pts: Vec<Option<[f64; 3]>> = m.positions.iter().map(|p| project(*p)).collect();
// 1 / clip w per vertex, for perspective-correct interpolation of world positions (so
// the section cuts along the plane, not a curve, in perspective views).
let inv_w: Vec<f64> = m.positions.iter().map(|p| 1.0 / vp.apply(*p)[3].max(1e-9)).collect();
for (ti, t) in m.triangles.iter().enumerate() {
let face = m.tri_face.get(ti).copied();
let base = sm.face_colors.iter().find(|(f, _)| Some(*f) == face).map_or(body, |(_, c)| c.f());
let wp = t.map(|k| m.positions.get(k as usize).copied().unwrap_or_default());
// Seen from inside (only where a section cuts the body open).
let to_eye = if cam.fov > 0.0 { cam.eye() - wp[0] } else { view_dir };
let inside = (wp[1] - wp[0]).cross(wp[2] - wp[0]).dot(to_eye) < 0.0;
let iw = t.map(|k| inv_w.get(k as usize).copied().unwrap_or(1.0));
let (Some(Some(a)), Some(Some(b)), Some(Some(cc))) = (pts.get(t[0] as usize), pts.get(t[1] as usize), pts.get(t[2] as usize)) else {
continue;
};
let ns: Vec<Vec3> = t.iter().map(|k| m.normals.get(*k as usize).copied().unwrap_or(Vec3::Z)).collect();
// A curved surface (its normals turn across the triangle) gets a silhouette line
// where it turns away from the eye.
let curved = ns.iter().any(|n| n.dist(ns[0]) > 1e-6);
let (x0, x1) = (a[0].min(b[0]).min(cc[0]).floor().max(0.0), a[0].max(b[0]).max(cc[0]).ceil().min(sw as f64 - 1.0));
let (y0, y1) = (a[1].min(b[1]).min(cc[1]).floor().max(0.0), a[1].max(b[1]).max(cc[1]).ceil().min(sh as f64 - 1.0));
if !(x0 <= x1 && y0 <= y1) {
continue;
}
let area = (b[0] - a[0]) * (cc[1] - a[1]) - (b[1] - a[1]) * (cc[0] - a[0]);
if area.abs() < 1e-12 {
continue;
}
let gx = ((b[2] - a[2]) * (cc[1] - a[1]) - (cc[2] - a[2]) * (b[1] - a[1])) / area;
let gy = ((cc[2] - a[2]) * (b[0] - a[0]) - (b[2] - a[2]) * (cc[0] - a[0])) / area;
let tri_slope = gx.hypot(gy) as f32;
for y in y0 as usize..=y1 as usize {
for x in x0 as usize..=x1 as usize {
let (px, py) = (x as f64 + 0.5, y as f64 + 0.5);
let w0 = ((b[0] - px) * (cc[1] - py) - (b[1] - py) * (cc[0] - px)) / area;
let w1 = ((cc[0] - px) * (a[1] - py) - (cc[1] - py) * (a[0] - px)) / area;
let w2 = 1.0 - w0 - w1;
if w0 < -1e-9 || w1 < -1e-9 || w2 < -1e-9 {
continue;
}
let (q0, q1, q2) = (w0 * iw[0], w1 * iw[1], w2 * iw[2]);
let qs = q0 + q1 + q2;
let (p0, p1, p2) = if qs > 1e-12 { (q0 / qs, q1 / qs, q2 / qs) } else { (w0, w1, w2) };
if let Some((cn, cd)) = scene.clip
&& cn.dot(wp[0] * p0 + wp[1] * p1 + wp[2] * p2) > cd
{
continue;
}
let z = (w0 * a[2] + w1 * b[2] + w2 * cc[2]) as f32;
let i = y * sw + x;
if c.depth.get(i).is_some_and(|d| z < *d) {
if let Some(d) = c.depth.get_mut(i) {
*d = z;
}
if let Some(s) = slope.get_mut(i) {
*s = tri_slope;
}
let n = (ns[0] * p0 + ns[1] * p1 + ns[2] * p2).normalized().unwrap_or(Vec3::Z);
let cut = scene.clip.is_some() && inside;
if let Some(d) = cap_depth.get_mut(i) {
*d = match cap_z {
Some([a, b, k]) if cut => ((a * px + b * py + k) as f32).min(z),
_ => f32::INFINITY,
};
}
if cut {
// The cut: the body's colour tinted toward the cap colour, hatched
// at 45 degrees (as the viewport draws it).
let tinted: [f64; 3] = std::array::from_fn(|k| base[k] + (cap_tint[k] - base[k]) * 0.35);
let k = if ((x + y) / SS) % 9 < 2 { 0.6 } else { 1.0 };
c.put(x, y, tinted.map(|v| v * k), 1.0);
for pass in [Pass::Solid, Pass::GlassFar, Pass::GlassNear] {
for sm in scene.meshes.iter().filter(|m| m.glass() == pass.glass()) {
let alpha = sm.alpha();
let m = &sm.mesh;
let body = sm.color.f();
let pts: Vec<Option<[f64; 3]>> = m.positions.iter().map(|p| project(*p)).collect();
// 1 / clip w per vertex, for perspective-correct interpolation of world positions (so
// the section cuts along the plane, not a curve, in perspective views).
let inv_w: Vec<f64> = m.positions.iter().map(|p| 1.0 / vp.apply(*p)[3].max(1e-9)).collect();
for (ti, t) in m.triangles.iter().enumerate() {
let face = m.tri_face.get(ti).copied();
let base = sm.face_colors.iter().find(|(f, _)| Some(*f) == face).map_or(body, |(_, c)| c.f());
let wp = t.map(|k| m.positions.get(k as usize).copied().unwrap_or_default());
// Seen from inside: where a section cuts a solid body open, and the far side of
// a see-through one (drawn in the pass before its near side).
let to_eye = if cam.fov > 0.0 { cam.eye() - wp[0] } else { view_dir };
let inside = (wp[1] - wp[0]).cross(wp[2] - wp[0]).dot(to_eye) < 0.0;
if !pass.takes(inside) {
continue;
}
let iw = t.map(|k| inv_w.get(k as usize).copied().unwrap_or(1.0));
let (Some(Some(a)), Some(Some(b)), Some(Some(cc))) = (pts.get(t[0] as usize), pts.get(t[1] as usize), pts.get(t[2] as usize)) else {
continue;
};
let ns: Vec<Vec3> = t.iter().map(|k| m.normals.get(*k as usize).copied().unwrap_or(Vec3::Z)).collect();
// A curved surface (its normals turn across the triangle) gets a silhouette line
// where it turns away from the eye.
let curved = ns.iter().any(|n| n.dist(ns[0]) > 1e-6);
let (x0, x1) = (a[0].min(b[0]).min(cc[0]).floor().max(0.0), a[0].max(b[0]).max(cc[0]).ceil().min(sw as f64 - 1.0));
let (y0, y1) = (a[1].min(b[1]).min(cc[1]).floor().max(0.0), a[1].max(b[1]).max(cc[1]).ceil().min(sh as f64 - 1.0));
if !(x0 <= x1 && y0 <= y1) {
continue;
}
let area = (b[0] - a[0]) * (cc[1] - a[1]) - (b[1] - a[1]) * (cc[0] - a[0]);
if area.abs() < 1e-12 {
continue;
}
let gx = ((b[2] - a[2]) * (cc[1] - a[1]) - (cc[2] - a[2]) * (b[1] - a[1])) / area;
let gy = ((cc[2] - a[2]) * (b[0] - a[0]) - (b[2] - a[2]) * (cc[0] - a[0])) / area;
let tri_slope = gx.hypot(gy) as f32;
for y in y0 as usize..=y1 as usize {
for x in x0 as usize..=x1 as usize {
let (px, py) = (x as f64 + 0.5, y as f64 + 0.5);
let w0 = ((b[0] - px) * (cc[1] - py) - (b[1] - py) * (cc[0] - px)) / area;
let w1 = ((cc[0] - px) * (a[1] - py) - (cc[1] - py) * (a[0] - px)) / area;
let w2 = 1.0 - w0 - w1;
if w0 < -1e-9 || w1 < -1e-9 || w2 < -1e-9 {
continue;
}
let mut col = shade(n, view_dir, base);
let ndv = n.dot(view_dir).abs();
if curved && ndv < 0.14 {
let a = 1.0 - ndv / 0.14;
for (k, e) in col.iter_mut().zip([0.07, 0.08, 0.10]) {
*k = *k * (1.0 - a) + e * a;
}
let (q0, q1, q2) = (w0 * iw[0], w1 * iw[1], w2 * iw[2]);
let qs = q0 + q1 + q2;
let (p0, p1, p2) = if qs > 1e-12 { (q0 / qs, q1 / qs, q2 / qs) } else { (w0, w1, w2) };
if let Some((cn, cd)) = scene.clip
&& cn.dot(wp[0] * p0 + wp[1] * p1 + wp[2] * p2) > cd
{
continue;
}
let z = (w0 * a[2] + w1 * b[2] + w2 * cc[2]) as f32;
let i = y * sw + x;
if c.depth.get(i).is_some_and(|d| z < *d) {
// A see-through body is blended over what is already drawn and
// leaves the depth buffer alone, so bodies inside it stay visible
// and the lines' depth test still answers for the solids.
if !pass.glass() {
if let Some(d) = c.depth.get_mut(i) {
*d = z;
}
if let Some(s) = slope.get_mut(i) {
*s = tri_slope;
}
}
let n = (ns[0] * p0 + ns[1] * p1 + ns[2] * p2).normalized().unwrap_or(Vec3::Z);
// A see-through body has no cut face: the interior already shows.
let cut = !pass.glass() && scene.clip.is_some() && inside;
if let Some(d) = cap_depth.get_mut(i).filter(|_| !pass.glass()) {
*d = match cap_z {
Some([a, b, k]) if cut => ((a * px + b * py + k) as f32).min(z),
_ => f32::INFINITY,
};
}
if cut {
// The cut: the body's colour tinted toward the cap colour, hatched
// at 45 degrees (as the viewport draws it).
let tinted: [f64; 3] = std::array::from_fn(|k| base[k] + (cap_tint[k] - base[k]) * 0.35);
let k = if ((x + y) / SS) % 9 < 2 { 0.6 } else { 1.0 };
c.put(x, y, tinted.map(|v| v * k), 1.0);
continue;
}
let mut col = shade(n, view_dir, base);
let ndv = n.dot(view_dir).abs();
if curved && ndv < 0.14 {
let a = 1.0 - ndv / 0.14;
for (k, e) in col.iter_mut().zip([0.07, 0.08, 0.10]) {
*k = *k * (1.0 - a) + e * a;
}
}
c.put(x, y, col, alpha);
}
c.put(x, y, col, 1.0);
}
}
}
@@ -336,7 +383,7 @@ mod tests {
edge_faces: vec![],
};
let scene = Scene {
meshes: vec![SceneMesh { mesh: Arc::new(mesh), color: Rgb(200, 30, 30), face_colors: Vec::new() }],
meshes: vec![SceneMesh::solid(Arc::new(mesh), Rgb(200, 30, 30))],
lines: vec![],
background: None,
radius: 20.0,
@@ -354,6 +401,71 @@ mod tests {
assert_eq!(render(&scene, &cam, 0, usize::MAX).w, 1);
}
/// A square panel facing the front camera (which looks along +Y), 20 × 20 about the origin
/// at `y`: nearer the eye the smaller `y` is.
fn panel(y: f64) -> Mesh {
let c = [(-10.0, -10.0), (10.0, -10.0), (10.0, 10.0), (-10.0, 10.0)].map(|(x, z)| Vec3::new(x, y, z));
Mesh {
positions: c.to_vec(),
normals: vec![Vec3::new(0.0, -1.0, 0.0); 4],
triangles: vec![[0, 1, 2], [0, 2, 3]],
tri_face: vec![0, 0],
..Default::default()
}
}
/// A front panel over a back one, with a line between them, seen from the front.
fn two_panels(front_opacity: f32) -> (Scene, Camera) {
let glass = SceneMesh { mesh: Arc::new(panel(-5.0)), color: Rgb(255, 0, 0), face_colors: Vec::new(), opacity: front_opacity };
let scene = Scene {
meshes: vec![SceneMesh::solid(Arc::new(panel(5.0)), Rgb(0, 255, 0)), glass],
lines: vec![SceneLine {
points: vec![Vec3::new(-8.0, 2.0, 0.0), Vec3::new(8.0, 2.0, 0.0)],
color: Rgb(0, 0, 255),
width: 1.4,
on_top: false,
}],
radius: 40.0,
..Default::default()
};
let mut cam = Camera { distance: 60.0, ..Default::default() };
cam.set_view(StandardView::Front);
(scene, cam)
}
/// A body the design draws see-through lets what is behind it show: the colour of the body
/// behind it comes through, and so does a line between the two, which a solid body in front
/// hides. This is what makes a picture of a cut's tool inside a translucent target readable.
#[test]
fn a_see_through_body_shows_what_is_inside_it() {
let middle = |opacity: f32| {
let (scene, cam) = two_panels(opacity);
let c = render(&scene, &cam, 64, 64);
// Inside both panels and clear of the line across the middle, so this pixel is
// the two panels alone.
let i = (24 * 64 + 24) * 4;
[c.rgba[i], c.rgba[i + 1], c.rgba[i + 2]]
};
let behind = |opacity: f32| {
let (scene, cam) = two_panels(opacity);
render(&scene, &cam, 64, 64).rgba.chunks(4).filter(|p| p[2] > 150 && p[0] < 120 && p[1] < 120).count()
};
let solid = middle(1.0);
assert!(solid[0] > 150 && solid[1] < 60, "a solid panel hides the one behind it: {solid:?}");
assert_eq!(behind(1.0), 0, "a solid panel hides the line behind it");
let glass = middle(0.35);
assert!(glass[1] > solid[1] + 60, "the panel behind shows through: {glass:?} vs {solid:?}");
assert!(glass[0] < solid[0], "the see-through panel itself is dimmer: {glass:?} vs {solid:?}");
assert!(behind(0.35) > 20, "the line between the panels shows through the see-through one");
// Opacity 0 still leaves a trace of the body rather than an invisible one, and the
// picture changes all the way down.
let faint = middle(0.0);
assert!(faint[0] > 0 && faint[0] < glass[0], "opacity 0 is a trace, not nothing and not glass: {faint:?} vs {glass:?}");
}
/// A sheet facing the front camera, turned back by `tilt` about X: the plane y = z·tan(tilt)
/// over x in ±15, z in ±`h`.
fn sheet(tilt: f64, h: f64) -> Mesh {
@@ -371,12 +483,7 @@ mod tests {
/// A close front view: 40 mm high on 64 px (128 canvas px, 0.3125 mm each), of a design of
/// radius `radius`.
fn close_view(mesh: Mesh, lines: Vec<SceneLine>, radius: f64, fov: f64) -> (Scene, Camera) {
let scene = Scene {
meshes: vec![SceneMesh { mesh: Arc::new(mesh), color: Rgb(160, 165, 175), face_colors: Vec::new() }],
lines,
radius,
..Default::default()
};
let scene = Scene { meshes: vec![SceneMesh::solid(Arc::new(mesh), Rgb(160, 165, 175))], lines, radius, ..Default::default() };
let mut cam = Camera { distance: if fov > 0.0 { 20.0 / (fov * 0.5).tan() } else { 50.0 }, fov, ..Default::default() };
cam.set_view(StandardView::Front);
(scene, cam)
+30
View File
@@ -23,8 +23,38 @@ pub struct SceneMesh {
pub color: Rgb,
/// Faces in colours of their own: (B-rep face index, colour).
pub face_colors: Vec<(u32, Rgb)>,
/// How opaque the body is (an appearance's opacity): 1 is solid, below [`SEE_THROUGH`] it is
/// drawn see-through, so what lies inside it shows, as the viewport draws glass. A body
/// without an appearance of its own is solid.
pub opacity: f32,
}
impl SceneMesh {
/// A solid body in `color`, with no face of its own look.
pub fn solid(mesh: Arc<Mesh>, color: Rgb) -> SceneMesh {
SceneMesh { mesh, color, face_colors: Vec::new(), opacity: 1.0 }
}
/// Is the body drawn see-through? (Its opacity is below [`SEE_THROUGH`].)
pub fn glass(&self) -> bool {
self.opacity < SEE_THROUGH
}
/// The alpha the body is blended with: its opacity, never so low that it vanishes
/// altogether, and 1 when it is solid.
pub fn alpha(&self) -> f64 {
if self.glass() { f64::from(self.opacity).clamp(MIN_ALPHA, 1.0) } else { 1.0 }
}
}
/// At or above this opacity a body is drawn solid: an appearance a hair under 1 is not worth a
/// see-through pass, and the viewport draws the same bodies as glass.
pub const SEE_THROUGH: f32 = 0.999;
/// The lowest alpha a see-through body is drawn with, so opacity 0 still leaves a trace of the
/// body rather than an invisible one (as the viewport clamps it).
pub const MIN_ALPHA: f64 = 0.05;
pub struct SceneLine {
pub points: Vec<Vec3>,
pub color: Rgb,
+2 -2
View File
@@ -587,7 +587,7 @@ fn partial_picture(world: &solidcraft_engine::doc::ModelState, stop: &dyn Fn() -
return None;
}
bounds = bounds.union(&mesh.bounds());
scene.meshes.push(SceneMesh { mesh, color: Rgb(176, 186, 199), face_colors: Vec::new() });
scene.meshes.push(SceneMesh::solid(mesh, Rgb(176, 186, 199)));
}
if bounds.is_empty() {
return None;
@@ -633,7 +633,7 @@ fn saved_picture(preview: solidcraft_engine::io::DesignPreview) -> Option<egui::
}
bounds = bounds.union(&mesh.bounds());
let [r, g, b] = cached.color.unwrap_or([0.69, 0.73, 0.78]).map(|c| (c * 255.0).round() as u8);
scene.meshes.push(SceneMesh { mesh: Arc::new(mesh), color: Rgb(r, g, b), face_colors: Vec::new() });
scene.meshes.push(SceneMesh::solid(Arc::new(mesh), Rgb(r, g, b)));
}
if bounds.is_empty() {
return None;
+7
View File
@@ -0,0 +1,7 @@
{"commands": [
{"command": "solid.box", "params": {"length": 60, "width": 40, "height": 20, "center": [0, 0, 10], "body_name": "Plate"}},
{"command": "solid.cylinder", "params": {"diameter": 14, "height": 14, "base": [0, 0, 0], "operation": "new_body", "body_name": "Pin"}},
{"command": "appearance.assign", "params": {"bodies": ["Plate"], "color": "#b0bac6", "opacity": 0.3}},
{"command": "appearance.assign", "params": {"bodies": ["Pin"], "color": "#e8542c"}},
{"command": "inspect.section", "params": {"plane": "XZ", "at": 0, "flip": true}}
]}
+29
View File
@@ -226,6 +226,35 @@ solidcraft-cli snapshot part.solidcraft --out photo.png --view Photo
solidcraft-cli snapshot part.solidcraft --out close-up.png --no-grid --no-axes --camera '{"target": [30, -20, 0], "yaw": 0.6, "pitch": 0.25, "distance": 60}'
```
### Seeing what a cut or a join is about to do
A picture answers in a glance what a volume cannot: does the tool body reach through the
material, and is it where you meant it to be? `--body NAME:opacity=0.3` draws that body
see-through, so whatever is inside it shows; `--body NAME:color=#cc3333` gives it a colour.
Either key on its own keeps what the design says about the other, and the option is a shortcut
for `appearance.assign`, the command the Appearance dialog runs — the picture is the one the
window would show with the same appearance assigned.
`--tool NAME` is the common case in one option: that body solid in the tool colour, every
other body see-through around it. `--section z=27` cuts the model at a plane so the inside
shows, as `inspect.section` does: an axis and the world coordinate to cut at, `,flip` to keep
the other side, `XY`, `XZ` or `YZ` for a plane through the origin, or the command's own JSON.
![A pin inside a translucent plate, cut by a section plane](../generated/tool-preview.png)
```sh
# The pin the cut would remove, inside the plate it stops 6 mm short of.
solidcraft-cli snapshot plate.solidcraft --out preview.png --tool Pin
solidcraft-cli snapshot plate.solidcraft --out cut.png --tool Pin --section z=12
solidcraft-cli snapshot plate.solidcraft --out glass.png --body "Plate:opacity=0.25" --body "Pin:color=#1a7f4b"
```
A body drawn see-through is drawn see-through everywhere a picture is drawn, not only here:
an appearance with an opacity below 1 (`Glass - Clear` in the library, or any `opacity` you
assign) now reads as glass in `snapshot`, in MCP screenshots and in a design's thumbnail, as it
always has in the window. A face painted with a see-through look of its own still draws at its
body's opacity.
Windows PowerShell 5.1 drops the double quotes inside an argument it passes to a program: write them as `\"` there.
A command that fails stops the script. A feature can also fail later, when a parameter change