Render: integrate optional CPU ray tracing, reflections and HDR lighting (#1693)

Publish the reviewed fa8c1206 source as a draft work-in-progress checkpoint.
Finish the actual merge of pinned upstream 04b4381b while preserving published
claim 28414b51 and all real ancestors. Exact staged tested tree: 8388e395.

Adopt the original RT2 (#1640), reflection (#1658), HDR (#1698), planar
anisotropy (#1699), planar-depth, deterministic-primary and stratified-source
contributions documented in the existing source-overlay receipts. Those
receipts are source provenance, not fictional implementation commit parents.

Actual cargo xtask ci: exit 1, 4344 passed, three golden groups failed,
52 existing ignored. Pristine 04b separately reproduces all seven seed lines.
Affected feature-on render/engine checks, Clippy/wasm and production native
MCP/PNG reopening passed on identical precommit source. No full-CI pass,
latest-main qualification, presentation readiness or merge approval claimed.
This commit is contained in:
lillith committed 2026-10-17 04:00:39 +02:00
commit bb2fff8e14
181 files changed
+19131 -605

No files matched your search

+5
View File
@@ -0,0 +1,5 @@
blank_issues_enabled: true
contact_links:
- name: Questions and chat
url: https://discord.gg/FtU4NQNVDH
about: Ask questions and talk with users and contributors on the SolidCraft Discord.
+2
View File
@@ -96,9 +96,11 @@ Editable drawing code, native projects and shipped exports are collected under `
| assets/locales/de.json | SolidCraft contributors | Original SolidCraft resource data or drawing code, collected without redesign | MIT OR Apache-2.0 |
| assets/locales/en.json | SolidCraft contributors | Original SolidCraft resource data or drawing code, collected without redesign | MIT OR Apache-2.0 |
| assets/locales/fr.json | rlartot | French translation of the English catalog, contributed upstream | MIT OR Apache-2.0 |
| assets/locales/gl.json | Pablo López (pablopeza) | Galician translation of the English catalog, contributed upstream | MIT OR Apache-2.0 |
| assets/locales/ja.json | SolidCraft contributors | Original SolidCraft resource data or drawing code, collected without redesign | MIT OR Apache-2.0 |
| assets/locales/ko.json | SolidCraft contributors | Original SolidCraft resource data or drawing code, collected without redesign | MIT OR Apache-2.0 |
| assets/locales/ru.json | Alex Pro (del000) | Russian translation of the English catalog, contributed upstream | MIT OR Apache-2.0 |
| assets/locales/pt-BR.json | DuBearte | Brazilian Portuguese translation of the English catalog, contributed upstream | MIT OR Apache-2.0 |
| assets/locales/tr.json | macrulz54 | Turkish translation of the English catalog, contributed upstream | MIT OR Apache-2.0 |
| assets/locales/uk.json | Igor Bronovskyi (BrunIF) | Ukrainian translation of the English catalog, contributed upstream | MIT OR Apache-2.0 |
| assets/locales/zh.json | SolidCraft contributors | Original SolidCraft resource data or drawing code, collected without redesign | MIT OR Apache-2.0 |
+2
View File
@@ -10,6 +10,8 @@ Help is welcome, whether that's a one-line fix or owning a whole area. This page
build it, how the code is laid out, the few rules that aren't negotiable, and where help is
needed most.
Questions, ideas or want to say what you're working on? Join the [Discord](https://discord.gg/FtU4NQNVDH).
## Get it running (about 10 minutes on a fast machine)
You need stable Rust 1.95 or newer (required by egui/eframe 0.36). For the web
Generated
+1
View File
@@ -4215,6 +4215,7 @@ dependencies = [
"serde_json",
"sha2 0.10.9",
"solidcraft-geom",
"weezl",
]
[[package]]
+2
View File
@@ -71,6 +71,8 @@ ttf-parser = { version = "0.25", default-features = false, features = ["std"] }
# images
image = { version = "0.25", default-features = false, features = ["png", "hdr"] }
png = "0.18.1"
# LZW for GIF animations (MIT OR Apache-2.0, pure Rust; already in the tree through image's tiff).
weezl = "0.1.12"
# ui
egui = "0.36"
+39 -10
View File
@@ -1,16 +1,17 @@
# SolidCraft
<p align="center">
<img src="assets/icons/app/linux/exports/hicolor/256x256/apps/ai.storyteller.solidcraft.png" width="96" height="96" alt="SolidCraft" />
</p>
**An open-source parametric 3D CAD application built in pure Rust.**
<h1 align="center">SolidCraft</h1>
Sketch, constrain, and build solids with a parametric feature timeline. Change a dimension
and watch your model rebuild. Run it on your desktop, in your browser, or let AI agents
model through the built-in MCP server.
<p align="center">
<strong>An open-source parametric 3D CAD application built in pure Rust.</strong><br />
Sketch, constrain, and build solids with a parametric feature timeline. Change a dimension
and watch your model rebuild. Run it on your desktop, in your browser, or let AI agents
model through the built-in MCP server.
</p>
![SolidCraft 0.8: model a Raspberry Pi 4 case from an empty design: a sketch dimensioned with parameters, extrude, fillets and shell, a rim rounded in one pick, standoffs patterned on the board's mounting holes, port cut-outs, vent slots, "Pi 4" engraved in a font, a PETG material with its mass in Properties, and a height change in Parameters](docs/screenshots/demo-0.8.gif)
*A Raspberry Pi 4 case from an empty design: a sketch dimensioned with the board's parameters, extrude, fillet, shell, the rim rounded in one pick, an M2.5 standoff patterned on the 58 × 49 mm hole rectangle, port cut-outs, vent slots, "Pi 4" engraved in DejaVu Sans Bold and a PETG material defined in the design, with its mass in Properties, then height 24 → 32 mm in Parameters and it all rebuilds. 9× playback. [Full video](https://github.com/bherbruck/solidcraft/raw/refs/heads/main/docs/screenshots/demo-0.8.mp4), recorded with the [demo script](examples/demo/record_ui.sh).*
## Download
<div align="center">
[![Download for Windows][badge-windows]][windows-msi]
[![Download for macOS][badge-macos]][macos-dmg]
@@ -18,6 +19,32 @@ model through the built-in MCP server.
[![Get it from the Snap Store][badge-snap]][snap-store]
[![Try it in your browser][badge-web]][web-app]
</div>
<p align="center">
<a href="https://solidcraft.io">Website</a> ·
<a href="https://github.com/bherbruck/solidcraft/releases/latest">Download</a> ·
<a href="https://bherbruck.github.io/solidcraft/app/">Try it in the browser</a> ·
<a href="https://bherbruck.github.io/solidcraft/">Documentation</a> ·
<a href="https://discord.gg/FtU4NQNVDH">Discord</a> ·
<a href="https://github.com/bherbruck/solidcore">SolidCore</a>
</p>
<p align="center">
<a href="https://github.com/bherbruck/solidcraft/actions/workflows/ci.yml?query=branch%3Amain"><img src="https://github.com/bherbruck/solidcraft/actions/workflows/ci.yml/badge.svg?branch=main" alt="CI" /></a>
<a href="https://github.com/bherbruck/solidcraft/releases/latest"><img src="https://img.shields.io/github/v/release/bherbruck/solidcraft?label=release" alt="Latest release" /></a>
<a href="https://github.com/bherbruck/solidcraft/releases"><img src="https://img.shields.io/github/downloads/bherbruck/solidcraft/total?label=downloads" alt="Downloads" /></a>
<a href="LICENSE"><img src="https://img.shields.io/github/license/bherbruck/solidcraft" alt="Licence" /></a>
<a href="https://discord.gg/FtU4NQNVDH"><img src="https://img.shields.io/badge/Discord-join-5865F2?logo=discord&logoColor=white" alt="Discord" /></a>
<a href="https://github.com/bherbruck/solidcraft/stargazers"><img src="https://img.shields.io/github/stars/bherbruck/solidcraft?style=flat" alt="Stars" /></a>
</p>
![SolidCraft 0.8: model a Raspberry Pi 4 case from an empty design: a sketch dimensioned with parameters, extrude, fillets and shell, a rim rounded in one pick, standoffs patterned on the board's mounting holes, port cut-outs, vent slots, "Pi 4" engraved in a font, a PETG material with its mass in Properties, and a height change in Parameters](docs/screenshots/demo-0.8.gif)
*A Raspberry Pi 4 case from an empty design: a sketch dimensioned with the board's parameters, extrude, fillet, shell, the rim rounded in one pick, an M2.5 standoff patterned on the 58 × 49 mm hole rectangle, port cut-outs, vent slots, "Pi 4" engraved in DejaVu Sans Bold and a PETG material defined in the design, with its mass in Properties, then height 24 → 32 mm in Parameters and it all rebuilds. 9× playback. [Full video](https://github.com/bherbruck/solidcraft/raw/refs/heads/main/docs/screenshots/demo-0.8.mp4), recorded with the [demo script](examples/demo/record_ui.sh).*
## Download
- **Windows:** download and run the [installer][windows-msi].
Also for [ARM64][windows-arm64-msi] and [32-bit][windows-x86-msi] PCs, or as a
[portable zip][windows-portable] that runs without installing.
@@ -62,6 +89,8 @@ Install details, upgrading from earlier builds and building from source are in
**Documentation:** the [SolidCraft book](https://bherbruck.github.io/solidcraft/) (user guide,
developer guide and command reference; sources in [docs/book](docs/book)).
**Community:** chat with users and contributors on [Discord](https://discord.gg/FtU4NQNVDH).
**Status: early but usable for simple parts.** 75 of 76 public reference parts
match their analytic or FreeCAD-computed volume, area, centre of mass and bounding box
([docs/oracle.md](docs/oracle.md)); the other is a tracked bug.
+14 -2
View File
@@ -54,7 +54,7 @@ PCB / Package, Render, Animation, Simulation, Manufacture/CAM, Drawings.
| M6 | UI depth: selection feedback and origin (done), timeline editing (done: hover and selection highlight modifier faces, including fillets and chamfers; edit feature, history marker drag, dependency-checked single and multi-item reorder, suppress, rename, delete with dependents, re-resolved references; redefining selections refreshes persistent edge/face references while retaining feature identity and dimension names; optional compact named left feature history with rollback bar, multi-selection and persistent folders above the parts browser), right-docked dialogs (done), live previews for every feature dialog (done), keyboard-first commands with on-canvas value boxes and sketch inline dimensions (done), drag manipulators with automatic join/cut (done: extrude incl. two sides, fillet, shell, hole depth, move, pattern spacing, revolve rotator; taper handle open), dark theme (done), right-click menu with Repeat (done), measure tool (done), section analysis (done), selection filter (done), drag-solve of sketch points (done); appearance controls now preserve body/face/component targeting, named transparent looks, reuse/search and override removal; preferences | in progress | 6 |
| M7 | Thin extrude (walls along open or closed curves: centre, inside, outside or two sides; mitred corners, crossing walls joined; #721), sweep, loft (incl. to a point), rib and web (to next / depth), emboss (planar faces and exact radial emboss/deboss of bounded orthogonal profiles on complete exterior cylinders/sleeves), thread (cosmetic, and modelled M3–M20 outside and inside: the ISO profile screwed in as a faceted cut), coil (smooth B-spline helical walls), pipe, pattern on path, patterns of bodies and components, replace face (parallel), align, remove, feature copy/paste: done. Unique eligible cylindrical targets are inferred for new Emboss features. Left: general curved-face emboss and exact (unfaceted) modelled threads | in progress | 12 |
| M8 | Surface workspace (#772). Done: Patch (sketch regions; edge loops filled G0, plus `crown`), Stitch, Thicken (planes and cylinders), Extend (straight edges of planar surfaces), Trim (by a plane or a face), Delete Face (healing), Boundary Fill, zebra/draft/curvature-map analysis, Surface Extrude/Revolve/Sweep/Loft from open and closed curves, Offset, Unstitch and Reverse Normal; the continuity-driven core (`kernel/src/bridge.rs`, G0–G3 Hermite rows) with **Blend** (`surface.blend`, #764), **Match** (`surface.match`), **Boundary** (`surface.boundary`, #763 — two boundaries exact, three/four refused pending a Gregory-type corner), **Fair** (`surface.fair`, CV fairing), **continuity analysis** (`inspect.continuity`, #770) and a multi-section **loft** with per-end continuity and crown. Also in the Class-A pass: G1…G4 blend curves in the sketch, chord and variable-radius fillets on curved edges (with honest refusals where the fit cannot hold), and a G2 corner patch where filleted edges meet (kernel; the command refuses until the patch's sections can be sewn to the blends' contacts). Left: bias/form-factor fillet sections (design recorded), a Gregory-type corner, surface Fillet between separate surface bodies (#769), Ruled (#762), Untrim (#761), curved-face Extend (#760), sweep guide rails and two-rail sweeps (#771; orientation, twist and end scale done; loft rails #201), and every remaining #757–#772 item | deferred | — |
| M9 | Components and assemblies: New Component / Create Components from Bodies, active component, per-component origin/bodies/sketches/timeline entries, occurrences with transforms, Copy/Paste vs Paste New, nested Browser tree with visibility and isolate; Ground, Move/Copy of occurrences, joints (rigid, revolute, slider, cylindrical, pin-slot, planar, ball) by joint origins with limits and Drive Joints, closed kinematic loops (four-bar, slider-crank: the loop's other joints follow the driven one on its branch, and driving stops where a loop can no longer close), As-built Joint, Rigid Group, Contact Sets (driving and motion studies stop where bodies in a set would pass through each other), Motion Study (joint values keyed along a timeline, playback, export of occurrence positions as JSON/CSV), Exploded views (automatic or by hand, shown without changing placements); interference, per-component physical properties; STEP with assembly structure; URDF export for robot simulators (links with meshes, mass and inertia; joint chains whose values match Drive Joints; docs/urdf.md). Physical properties now measure material-aware component/occurrence placements, descendants and repeated instances, including pending moves and body reassignment offsets; contact geometry and automatic exploded centres respect those offsets. Groundwork done: component tree, occurrences with transforms (instances, Paste New), world placement, active component as authoring frame, ground, Capture/Revert Position, moving bodies and sketches. UI: ASSEMBLE panel dialogs for New Component, Joint (snaps on faces, edges, circles and vertices; animated motion preview; offsets, flip, limits), As-built Joint, Joint Origin, Rigid Group, Drive Joints (live slider), Motion Link and Interference (overlaps shown red); joints in the timeline and the Browser | in progress | 32 |
| M9 | Components and assemblies: New Component / Create Components from Bodies, active component, per-component origin/bodies/sketches/timeline entries, occurrences with transforms, Copy/Paste vs Paste New, nested Browser tree with visibility and isolate; Ground, Move/Copy of occurrences, joints (rigid, revolute, slider, cylindrical, pin-slot, planar, ball) by joint origins with limits and Drive Joints, closed kinematic loops (four-bar, slider-crank: the loop's other joints follow the driven one on its branch, and driving stops where a loop can no longer close), cams (`joint.cam`: a revolute cam drives a slider or revolute follower along a closed sketch profile or the cam's edges, knife, roller or flat followers, worked out again when the profile changes; drives, studies, closed loops, contact sets), As-built Joint, Rigid Group, Contact Sets (driving and motion studies stop where bodies in a set would pass through each other), Motion Study (joint values keyed along a timeline, playback, export of occurrence positions as JSON/CSV), Exploded views (automatic or by hand, shown without changing placements); interference, per-component physical properties; STEP with assembly structure; URDF export for robot simulators (links with meshes, mass and inertia; joint chains whose values match Drive Joints; docs/urdf.md). Physical properties now measure material-aware component/occurrence placements, descendants and repeated instances, including pending moves and body reassignment offsets; contact geometry and automatic exploded centres respect those offsets. Groundwork done: component tree, occurrences with transforms (instances, Paste New), world placement, active component as authoring frame, ground, Capture/Revert Position, moving bodies and sketches. UI: ASSEMBLE panel dialogs for New Component, Joint (snaps on faces, edges, circles and vertices; animated motion preview; offsets, flip, limits), As-built Joint, Joint Origin, Rigid Group, Drive Joints (live slider), Motion Link, Cam and Interference (overlaps shown red); joints in the timeline and the Browser | in progress | 32 |
| M10 | Sheet metal: flange (base, edge, contour), hem, unfold/refold, convert, flat pattern + DXF, rules: done. PLASTIC enclosure subset: Boss, Rib, Web, Lip/Groove, Snap Fit, Rest, Plastic Rules (library, edit, assign; rule draft and clearance as feature defaults): done, tested against hand-computed geometry. UI: SHEET METAL and PLASTIC tabs in Fusion's layout with dialogs (live preview, Edit Feature, pre-selection) for Flange, Hem, Unfold/Refold, Convert, Sheet Metal Rules, Create Flat Pattern (flat view with bend lines, bend table CSV/JSON and DXF export with exact circle/arc/line cutouts), Boss, Lip/Groove, Snap Fit, Rest, Manage and Assign Plastic Rules; Fold (bend along a sketch line); flanges meeting at a corner closed at any angle with the rule's gap; edge flanges with their own angle and height per edge in one feature; corner reliefs (notch, round, rectangular, tear) chosen by the rule; Convert to Sheet Metal from a solid or shelled body by its bend edges (flat faces, sharp bends) | in progress | 36 |
| M11 | 2D drawings | deferred | — |
| M12 | Release: cross-platform packages, verification and deliberate publication implemented; original current-UI demo refreshed. Trusted distribution signing and broader performance work remain | in progress | 16 |
@@ -68,11 +68,23 @@ retain their saved two-finger scroll preference; camera motion is available thro
M11 precursor: File → Export Current View as DXF exports shown placed bodies from the current
camera as a 2D millimetre drawing, with hidden edges omitted or dashed. Vector occlusion splits
partly hidden edges and includes curved silhouettes. Curves are approximated; drawing sheets,
partly hidden edges and includes curved silhouettes. Repeated part meshes and triangle
hierarchies are shared; bounded desktop preparation and occlusion use up to eight workers.
Curves are approximated; drawing sheets,
annotations and exact projected curves remain deferred. See [view DXF](docs/view-dxf.md).
Desktop view DXF export runs in the file-operation worker with five-stage progress and
cooperative cancellation. Curve tolerance (0.0001–1 mm, default 0.01 mm) is remembered alongside
the hidden-edge setting. Cancelled exports preserve the model and the previous destination;
completed drawings publish atomically. The browser still exports synchronously.
## Interactive modelling
- Thread resolves a suggested metric size when a cylindrical face is picked. Diameter and
pitch selectors expose the existing metric designation parameter; custom designations stay
editable, and Automatic size returns to the face's suggestion. Cosmetic/modelled and
full/partial-length options remain available. This does not add tolerance classes or
left-hand threads.
- New Body extrusion and face-offset previews show completed intermediate geometry while a
drag continues, then catch up to the exact final value. Changes to the selected geometry,
operation or feature still discard obsolete results. Distance arrows and their value boxes
@@ -1559,7 +1559,6 @@ fn a_sketch_on_the_rim_a_shell_leaves() {
}
#[test]
#[ignore = "fails until #565 is fixed"]
fn sketches_after_split_body_and_intersect() {
reproduces(
None,
+14 -4
View File
@@ -94,10 +94,20 @@ impl eframe::App for App {
solidcraft_ui_egui::recovery_ui::close(&mut self.solve);
solidcraft_engine::crash::end_session();
// An update asked to restart into the new version or to run its installer.
if let Some((program, args)) = solidcraft_ui_egui::update::take_launch(&mut self.solve)
&& let Err(e) = std::process::Command::new(&program).args(&args).spawn()
{
log::error!("update: starting {}: {e}", program.display());
if let Some((program, args)) = solidcraft_ui_egui::update::take_launch(&mut self.solve) {
let mut command = std::process::Command::new(&program);
command.args(&args);
#[cfg(windows)]
{
use std::os::windows::process::CommandExt;
// Not tied to this process: its own process group, and no console (the PowerShell
// that waits for an installer is hidden; the app itself is detached).
let hidden_shell = program.file_stem().is_some_and(|n| n.eq_ignore_ascii_case("powershell"));
command.creation_flags(0x0000_0200 | if hidden_shell { 0x0800_0000 } else { 0x0000_0008 });
}
if let Err(e) = command.spawn() {
log::error!("update: starting {}: {e}", program.display());
}
}
}
}
+26 -18
View File
@@ -347,16 +347,23 @@ impl SpaceMouse {
/// Before the app's own hook (which adds the control channel's events): with navigation on,
/// the wheel events 3DxWare makes from the cap's motion are dropped.
pub fn raw_input_hook(&mut self, enabled: bool, raw: &mut egui::RawInput) {
self.raw_input_hook_at(enabled, raw, Instant::now());
}
fn raw_input_hook_at(&mut self, enabled: bool, raw: &mut egui::RawInput, now: Instant) {
if !enabled {
return;
}
let now = Instant::now();
let moving = self.shared.lock().map(|reading| reading.current(now).moving()).unwrap_or(false);
self.wheel.filter(moving, now.duration_since(self.started).as_secs_f64(), &mut raw.events);
}
pub fn tick(&mut self, app: &mut SolveApp, ctx: &Context) {
let now = Instant::now();
self.tick_at(app, ctx, Instant::now());
}
/// The frame at `now`. Tests pass their own clock, so a slow runner can't age a reading.
fn tick_at(&mut self, app: &mut SolveApp, ctx: &Context, now: Instant) {
let seconds = now.duration_since(self.last_frame).as_secs_f64();
self.last_frame = now;
if now.duration_since(self.mapping_checked_at) >= RETRY_AFTER {
@@ -486,6 +493,9 @@ mod tests {
#[test]
fn each_frame_hands_the_view_its_motion_through_the_drivers_mapping() {
// The reader's latest tilt, and a profile that makes tilt roll: the frame's motion rolls.
// The frame runs at the reading's own time, so a slow runner can't let the reading go stale.
let mut app = SolveApp::new(solidcraft_engine::Session::default(), solidcraft_ui_egui::Services::default());
app.home.open = false;
let now = Instant::now();
let mut reading = Reading::new(now);
reading.axes.rotation = [0, 350, 0];
@@ -497,9 +507,7 @@ mod tests {
wheel: WheelGuard::default(),
started: now,
};
let mut app = SolveApp::new(solidcraft_engine::Session::default(), solidcraft_ui_egui::Services::default());
app.home.open = false;
mouse.tick(&mut app, &Context::default());
mouse.tick_at(&mut app, &Context::default(), now);
let DeviceMotion { motion, seconds } = app.viewport.device_motion.expect("the frame hands the page its motion");
assert_eq!(motion, Motion { translation: [0.0; 3], rotation: [0.0, 0.0, -1.0] });
assert!(seconds > 0.0);
@@ -514,8 +522,7 @@ mod tests {
}
}
fn mouse(reading: Reading) -> SpaceMouse {
let now = Instant::now();
fn mouse(reading: Reading, now: Instant) -> SpaceMouse {
SpaceMouse {
shared: Arc::new(Mutex::new(reading)),
last_frame: now,
@@ -532,36 +539,37 @@ mod tests {
let now = Instant::now();
let mut tilted = Reading::new(now);
tilted.axes.rotation = [-200, 0, 0];
let mut moving = mouse(tilted);
let mut moving = mouse(tilted, now);
let mut raw = egui::RawInput { events: vec![wheel(), egui::Event::Zoom(1.1), egui::Event::Text("a".into())], ..Default::default() };
moving.raw_input_hook(true, &mut raw);
moving.raw_input_hook_at(true, &mut raw, now);
assert_eq!(raw.events, [egui::Event::Text("a".into())]);
// With navigation off, the wheel is the cap's only way to move the view: kept.
let mut raw = egui::RawInput { events: vec![wheel()], ..Default::default() };
moving.raw_input_hook(false, &mut raw);
moving.raw_input_hook_at(false, &mut raw, now);
assert_eq!(raw.events.len(), 1);
// The cap at rest: the wheel is the user's.
let mut resting = mouse(Reading::new(now));
let mut resting = mouse(Reading::new(now), now);
let mut raw = egui::RawInput { events: vec![wheel()], ..Default::default() };
resting.raw_input_hook(true, &mut raw);
resting.raw_input_hook_at(true, &mut raw, now);
assert_eq!(raw.events.len(), 1);
}
#[test]
fn the_wheel_is_the_users_again_once_the_cap_has_been_still_a_moment() {
let mut tilted = Reading::new(Instant::now());
let now = Instant::now();
let mut tilted = Reading::new(now);
tilted.axes.rotation = [-200, 0, 0];
let mut cap = mouse(tilted);
let mut cap = mouse(tilted, now);
let mut raw = egui::RawInput { events: vec![wheel()], ..Default::default() };
cap.raw_input_hook(true, &mut raw);
cap.raw_input_hook_at(true, &mut raw, now);
assert!(raw.events.is_empty(), "dropped while the cap moves");
// Let go, then wait out the quiet time.
let later = now + Duration::from_secs_f64(solidcraft_ui_egui::space_mouse::WHEEL_QUIET_S) + Duration::from_millis(60);
if let Ok(mut reading) = cap.shared.lock() {
*reading = Reading::new(Instant::now());
*reading = Reading::new(later);
}
std::thread::sleep(Duration::from_secs_f64(solidcraft_ui_egui::space_mouse::WHEEL_QUIET_S) + Duration::from_millis(60));
let mut raw = egui::RawInput { events: vec![wheel()], ..Default::default() };
cap.raw_input_hook(true, &mut raw);
cap.raw_input_hook_at(true, &mut raw, later);
assert_eq!(raw.events.len(), 1, "kept once the cap has been still");
}
}
+14
View File
@@ -1338,6 +1338,20 @@ pub(crate) fn paint_with(p: &Painter, r: Rect, name: &str, ink: Color32, fill: C
pen.poly(&[(6.0, 10.0), (18.0, 10.0), (18.0, 15.0), (6.0, 15.0)], pen.fill, a);
pen.arrow((21.0, 17.0), (21.0, 6.0), a);
}
"cam" => {
// A cam on its shaft, its lobe up under the follower it lifts.
let cam: Vec<(f32, f32)> = (0..36)
.map(|k| {
let t = std::f32::consts::TAU * k as f32 / 36.0;
let r = 5.0 + 3.0 * (0.5 + 0.5 * t.sin()).powi(3);
(11.0 + r * t.cos(), 16.0 - r * t.sin())
})
.collect();
pen.poly(&cam, pen.fill, ink);
pen.dot(11.0, 16.0, ink);
pen.poly(&[(9.0, 2.0), (13.0, 2.0), (13.0, 8.0), (9.0, 8.0)], pen.fill, a);
pen.arrow((18.5, 9.5), (18.5, 2.5), a);
}
"interference" => {
pen.closed(&[(3.0, 5.0), (14.0, 5.0), (14.0, 16.0), (3.0, 16.0)], ink);
pen.poly(&[(9.0, 10.0), (14.0, 10.0), (14.0, 16.0), (9.0, 16.0)], ic.interference, ic.interference);
+23
View File
@@ -24,6 +24,7 @@
"Drive Joint": "Gelenk antreiben",
"Edges": "Kanten",
"Edit Profile Sketch": "Profile-Skizze bearbeiten",
"Export Animation…": "Animation exportieren…",
"Export Current View as DXF": "Aktuelle Ansicht als DXF exportieren",
"Export Current View as DXF…": "Aktuelle Ansicht als DXF exportieren…",
"Export DXF…": "DXF exportieren…",
@@ -59,6 +60,7 @@
"Restore outer boundary": "Äußere Begrenzung wiederherstellen",
"Revert Position": "Position zurücksetzen",
"Round": "Rund",
"Save the study as an animated GIF, seen as the viewport shows it": "Die Studie als animiertes GIF speichern, so wie der Ansichtsbereich sie zeigt",
"Select bodies (a face picks its body)": "Körper auswählen (eine Fläche wählt ihren Körper)",
"Selection filter": "Auswahlfilter",
"Send your report on GitHub": "Bericht auf GitHub senden",
@@ -92,6 +94,13 @@
"browser.precision": "Genauigkeit: {precision}",
"browser.sketch_name": "Skizze {number}",
"browser.units": "Einheiten: {units}",
"cam.flat": "Flachstößel",
"cam.follower": "Stößel",
"cam.knife": "Schneide",
"cam.needs_joints": "braucht ein Gelenk, das sich dreht, und eines, das gleitet oder schwenkt",
"cam.roller": "Rolle",
"cam.roller_pick": "Rolle (optional)",
"cam.tip_pick": "Spitze (optional)",
"cmd.appearance_assign": "Erscheinungsbild",
"cmd.appearance_library": "Erscheinungsbild-Bibliothek",
"cmd.appearance_list": "Erscheinungsbilder auflisten",
@@ -195,6 +204,7 @@
"cmd.inspect_minimum_radius": "Mindestradiusanalyse",
"cmd.inspect_zebra": "Zebra-Analyse",
"cmd.joint_as_built": "Fertigungsgelenk",
"cmd.joint_cam": "Nocken",
"cmd.joint_create": "Gelenk",
"cmd.joint_delete": "Gelenk löschen",
"cmd.joint_drive": "Gelenke antreiben",
@@ -225,6 +235,7 @@
"cmd.model_threads": "Gewinde auflisten",
"cmd.motion_delete": "Bewegungsuntersuchung löschen",
"cmd.motion_export": "Bewegungsuntersuchung exportieren",
"cmd.motion_export_animation": "Bewegungsanimation exportieren",
"cmd.motion_list": "Bewegungsuntersuchungen auflisten",
"cmd.motion_play": "Bewegungsuntersuchung abspielen",
"cmd.motion_study": "Bewegungsuntersuchung",
@@ -428,6 +439,18 @@
"drive.stopped_by_contact": "Angehalten bei {value}: {a} würde {b} durchdringen",
"drive.stopped_by_loop": "Angehalten bei {value}: die Schleife über {joint} lässt sich nicht weiter schließen",
"drive.unconnected": "Bewegt nichts: {part} ist mit nichts Festgesetztem verbunden",
"dxf.cancel_wait": "Warten, bis der Export angehalten wurde…",
"dxf.cancelled": "DXF-Export abgebrochen",
"dxf.cancelling": "DXF-Export wird abgebrochen",
"dxf.exporting": "DXF wird exportiert",
"dxf.invalid_tolerance": "Die Kurventoleranz muss zwischen 0,0001 und 1 mm liegen.",
"dxf.progress.index": "Flächen vorbereiten (2/5)",
"dxf.progress.meshes": "Netze vorbereiten (1/5)",
"dxf.progress.occlusion": "Verdeckte Kanten ermitteln (4/5)",
"dxf.progress.projection": "Geometrie projizieren (3/5)",
"dxf.progress.write": "DXF schreiben (5/5)",
"dxf.tolerance": "Kurventoleranz",
"dxf.tolerance_help": "Nur sichtbare Körper. Kurven werden durch gerade Segmente angenähert. Eine kleinere Toleranz liefert feinere Kurven und benötigt mehr Zeit und Speicher.",
"home.documentation": "Dokumentation",
"home.in_this_browser": "in diesem Browser",
"home.missing": "fehlt",
+27
View File
@@ -92,6 +92,7 @@
"Enable rule": "Enable rule",
"Enabled": "Enabled",
"Explode": "Explode",
"Export Animation…": "Export Animation…",
"Export Current View as DXF": "Export Current View as DXF",
"Export Current View as DXF…": "Export Current View as DXF…",
"Export DXF…": "Export DXF…",
@@ -211,6 +212,7 @@
"Round": "Round",
"Rule": "Rule",
"Save Rule": "Save Rule",
"Save the study as an animated GIF, seen as the viewport shows it": "Save the study as an animated GIF, seen as the viewport shows it",
"Saved preview. Geometry is being checked before editing.": "Saved preview. Geometry is being checked before editing.",
"Scale factor": "Scale factor",
"Search": "Search",
@@ -293,6 +295,13 @@
"browser.precision": "Precision: {precision}",
"browser.sketch_name": "Sketch{number}",
"browser.units": "Units: {units}",
"cam.flat": "Flat face",
"cam.follower": "Follower",
"cam.knife": "Knife edge",
"cam.needs_joints": "needs a joint that turns and one that slides or swings",
"cam.roller": "Roller",
"cam.roller_pick": "Roller (optional)",
"cam.tip_pick": "Tip (optional)",
"cmd.appearance_assign": "Appearance",
"cmd.appearance_library": "Appearance Library",
"cmd.appearance_list": "List Appearances",
@@ -396,6 +405,7 @@
"cmd.inspect_minimum_radius": "Minimum Radius Analysis",
"cmd.inspect_zebra": "Zebra Analysis",
"cmd.joint_as_built": "As-Built Joint",
"cmd.joint_cam": "Cam",
"cmd.joint_create": "Joint",
"cmd.joint_delete": "Delete Joint",
"cmd.joint_drive": "Drive Joints",
@@ -426,6 +436,7 @@
"cmd.model_threads": "List Threads",
"cmd.motion_delete": "Delete Motion Study",
"cmd.motion_export": "Export Motion Study",
"cmd.motion_export_animation": "Export Motion Animation",
"cmd.motion_list": "List Motion Studies",
"cmd.motion_play": "Play Motion Study",
"cmd.motion_study": "Motion Study",
@@ -631,6 +642,18 @@
"drive.stopped_by_contact": "Stopped at {value}: {a} would pass through {b}",
"drive.stopped_by_loop": "Stopped at {value}: the loop through {joint} can't close any further",
"drive.unconnected": "Moves nothing: {part} is not connected to anything grounded",
"dxf.cancel_wait": "Waiting for the export to stop…",
"dxf.cancelled": "DXF export cancelled",
"dxf.cancelling": "Cancelling DXF export",
"dxf.exporting": "Exporting DXF",
"dxf.invalid_tolerance": "Curve tolerance must be between 0.0001 and 1 mm.",
"dxf.progress.index": "Preparing surfaces (2/5)",
"dxf.progress.meshes": "Preparing meshes (1/5)",
"dxf.progress.occlusion": "Resolving hidden lines (4/5)",
"dxf.progress.projection": "Projecting geometry (3/5)",
"dxf.progress.write": "Writing DXF (5/5)",
"dxf.tolerance": "Curve tolerance",
"dxf.tolerance_help": "Visible bodies only. Curves use straight segments. Smaller tolerance gives finer curves and uses more time and memory.",
"expression, e.g. 25 mm": "expression, e.g. 25 mm",
"fits the face, e.g. M8": "fits the face, e.g. M8",
"from the rule": "from the rule",
@@ -760,6 +783,10 @@
"sketch_text.path_hint": "A curve of the sketch the text follows: click here, then the curve",
"sketch_text.use_font_file": "Use the font file {path}",
"the parts library is not available": "the parts library is not available",
"thread.automatic_size": "Automatic size",
"thread.designation": "Designation",
"thread.iso_metric": "ISO metric",
"thread.select_size": "Select size",
"timeline.group": "New Feature Folder",
"timeline.move_many": "Move Timeline Items",
"timeline.move_to_group": "Move Features to Folder",
+11
View File
@@ -85,6 +85,7 @@
"Enable rule": "Activer la règle",
"Enabled": "Activé",
"Explode": "Éclater",
"Export Animation…": "Exporter l'animation…",
"Extents": "Étendues",
"Face": "Face",
"Face attachment lost": "Rattachement à la face perdu",
@@ -194,6 +195,7 @@
"Round": "Arrondi",
"Rule": "Règle",
"Save Rule": "Enregistrer la règle",
"Save the study as an animated GIF, seen as the viewport shows it": "Enregistrer l'étude en GIF animé, telle que la fenêtre d'affichage la montre",
"Saved preview. Geometry is being checked before editing.": "Aperçu enregistré. La géométrie est en cours de vérification avant modification.",
"Scale factor": "Facteur d'échelle",
"Search": "Rechercher",
@@ -273,6 +275,13 @@
"browser.precision": "Précision : {precision}",
"browser.sketch_name": "Esquisse{number}",
"browser.units": "Unités : {units}",
"cam.flat": "Plateau",
"cam.follower": "Suiveur",
"cam.knife": "Arête",
"cam.needs_joints": "nécessite une liaison qui tourne et une qui glisse ou pivote",
"cam.roller": "Galet",
"cam.roller_pick": "Galet (facultatif)",
"cam.tip_pick": "Pointe (facultatif)",
"cmd.appearance_assign": "Apparence",
"cmd.appearance_library": "Bibliothèque d'apparences",
"cmd.appearance_list": "Lister les apparences",
@@ -376,6 +385,7 @@
"cmd.inspect_minimum_radius": "Analyse du rayon minimal",
"cmd.inspect_zebra": "Analyse zébrée",
"cmd.joint_as_built": "Liaison telle que construite",
"cmd.joint_cam": "Came",
"cmd.joint_create": "Liaison",
"cmd.joint_delete": "Supprimer la liaison",
"cmd.joint_drive": "Piloter les liaisons",
@@ -406,6 +416,7 @@
"cmd.model_threads": "Lister les filetages",
"cmd.motion_delete": "Supprimer l'étude de mouvement",
"cmd.motion_export": "Exporter l'étude de mouvement",
"cmd.motion_export_animation": "Exporter l'animation du mouvement",
"cmd.motion_list": "Lister les études de mouvement",
"cmd.motion_play": "Lire l'étude de mouvement",
"cmd.motion_study": "Étude de mouvement",
File diff suppressed because it is too large. Load diff
+27
View File
@@ -92,6 +92,7 @@
"Enable rule": "ルールを有効化",
"Enabled": "有効",
"Explode": "分解",
"Export Animation…": "アニメーションをエクスポート…",
"Export Current View as DXF": "現在の表示をDXFでエクスポート",
"Export Current View as DXF…": "現在の表示をDXFでエクスポート…",
"Export DXF…": "DXFをエクスポート…",
@@ -211,6 +212,7 @@
"Round": "丸め",
"Rule": "ルール",
"Save Rule": "ルールを保存",
"Save the study as an animated GIF, seen as the viewport shows it": "ビューポートの表示どおりにスタディをアニメーション GIF として保存",
"Saved preview. Geometry is being checked before editing.": "保存済みのプレビューです。編集前にジオメトリを検証しています。",
"Scale factor": "尺度係数",
"Search": "検索",
@@ -293,6 +295,13 @@
"browser.precision": "精度: {precision}",
"browser.sketch_name": "スケッチ{number}",
"browser.units": "単位: {units}",
"cam.flat": "平面",
"cam.follower": "従動節",
"cam.knife": "ナイフエッジ",
"cam.needs_joints": "回転するジョイントと、スライドまたは揺動するジョイントが必要",
"cam.roller": "ローラー",
"cam.roller_pick": "ローラー (オプション)",
"cam.tip_pick": "先端 (オプション)",
"cmd.appearance_assign": "外観",
"cmd.appearance_library": "外観ライブラリ",
"cmd.appearance_list": "外観を一覧表示",
@@ -396,6 +405,7 @@
"cmd.inspect_minimum_radius": "最小半径解析",
"cmd.inspect_zebra": "ゼブラ解析",
"cmd.joint_as_built": "現位置ジョイント",
"cmd.joint_cam": "カム",
"cmd.joint_create": "ジョイント",
"cmd.joint_delete": "ジョイントを削除",
"cmd.joint_drive": "ジョイントを駆動",
@@ -426,6 +436,7 @@
"cmd.model_threads": "ねじを一覧表示",
"cmd.motion_delete": "モーション スタディを削除",
"cmd.motion_export": "モーション スタディをエクスポート",
"cmd.motion_export_animation": "モーション アニメーションをエクスポート",
"cmd.motion_list": "モーション スタディを一覧表示",
"cmd.motion_play": "モーション スタディを再生",
"cmd.motion_study": "モーション スタディ",
@@ -631,6 +642,18 @@
"drive.stopped_by_contact": "{value} で停止: {a} が {b} を通り抜けてしまいます",
"drive.stopped_by_loop": "{value} で停止: {joint} を通るループはこれ以上閉じられません",
"drive.unconnected": "何も動きません: {part} は空間固定されたものに接続されていません",
"dxf.cancel_wait": "出力処理の停止を待っています…",
"dxf.cancelled": "DXF出力をキャンセルしました",
"dxf.cancelling": "DXF出力をキャンセル中",
"dxf.exporting": "DXFを出力中",
"dxf.invalid_tolerance": "曲線の許容誤差は0.0001~1 mmで指定してください。",
"dxf.progress.index": "面データを準備中 (2/5)",
"dxf.progress.meshes": "メッシュを準備中 (1/5)",
"dxf.progress.occlusion": "隠線を判定中 (4/5)",
"dxf.progress.projection": "形状を投影中 (3/5)",
"dxf.progress.write": "DXFを書き込み中 (5/5)",
"dxf.tolerance": "曲線の許容誤差",
"dxf.tolerance_help": "表示中のボディを出力し、曲線は線分で近似します。許容誤差を小さくすると曲線が滑らかになりますが、処理時間とメモリ使用量が増えます。",
"expression, e.g. 25 mm": "計算式 (例: 25 mm)",
"fits the face, e.g. M8": "面に適合するサイズ (例: M8)",
"from the rule": "ルールから",
@@ -760,6 +783,10 @@
"sketch_text.path_hint": "文字が沿うスケッチの曲線: ここをクリックしてから曲線をクリック",
"sketch_text.use_font_file": "フォント ファイル {path} を使用",
"the parts library is not available": "パーツライブラリは利用できません",
"thread.automatic_size": "サイズを自動選択",
"thread.designation": "ねじの呼び",
"thread.iso_metric": "ISOメートルねじ",
"thread.select_size": "サイズを選択",
"timeline.group": "フィーチャーフォルダを新規作成",
"timeline.move_many": "タイムライン項目を移動",
"timeline.move_to_group": "フィーチャーをフォルダへ移動",
+23
View File
@@ -24,6 +24,7 @@
"Drive Joint": "조인트 구동",
"Edges": "모서리",
"Edit Profile Sketch": "윤곽 스케치 편집",
"Export Animation…": "애니메이션 내보내기…",
"Export Current View as DXF": "현재 뷰를 DXF로 내보내기",
"Export Current View as DXF…": "현재 뷰를 DXF로 내보내기…",
"Export DXF…": "DXF 내보내기…",
@@ -59,6 +60,7 @@
"Restore outer boundary": "외부 경계 복원",
"Revert Position": "위치 복원",
"Round": "둥글게",
"Save the study as an animated GIF, seen as the viewport shows it": "뷰포트에 보이는 대로 스터디를 애니메이션 GIF로 저장",
"Select bodies (a face picks its body)": "바디 선택(면을 클릭하면 해당 바디 선택)",
"Selection filter": "선택 필터",
"Send your report on GitHub": "GitHub에서 보고서 보내기",
@@ -92,6 +94,13 @@
"browser.precision": "정밀도: {precision}",
"browser.sketch_name": "스케치{number}",
"browser.units": "단위: {units}",
"cam.flat": "평면",
"cam.follower": "종동절",
"cam.knife": "나이프 에지",
"cam.needs_joints": "회전하는 관절과 미끄러지거나 흔들리는 관절이 필요함",
"cam.roller": "롤러",
"cam.roller_pick": "롤러 (선택 사항)",
"cam.tip_pick": "끝점 (선택 사항)",
"cmd.appearance_assign": "외관",
"cmd.appearance_library": "외관 라이브러리",
"cmd.appearance_list": "외관 목록",
@@ -195,6 +204,7 @@
"cmd.inspect_minimum_radius": "최소 반경 분석",
"cmd.inspect_zebra": "얼룩말줄무늬 분석",
"cmd.joint_as_built": "조립 상태 관절",
"cmd.joint_cam": "캠",
"cmd.joint_create": "관절",
"cmd.joint_delete": "관절 삭제",
"cmd.joint_drive": "관절 구동",
@@ -225,6 +235,7 @@
"cmd.model_threads": "나사산 목록",
"cmd.motion_delete": "운동 연구 삭제",
"cmd.motion_export": "운동 연구 내보내기",
"cmd.motion_export_animation": "모션 애니메이션 내보내기",
"cmd.motion_list": "운동 연구 목록",
"cmd.motion_play": "운동 연구 재생",
"cmd.motion_study": "운동 연구",
@@ -428,6 +439,18 @@
"drive.stopped_by_contact": "{value}에서 멈춤: {a}이(가) {b}을(를) 통과하게 됩니다",
"drive.stopped_by_loop": "{value}에서 멈춤: {joint}을(를) 지나는 루프를 더 이상 닫을 수 없습니다",
"drive.unconnected": "아무것도 움직이지 않습니다: {part}이(가) 고정된 것에 연결되어 있지 않습니다",
"dxf.cancel_wait": "내보내기가 중지될 때까지 기다리는 중…",
"dxf.cancelled": "DXF 내보내기를 취소했습니다",
"dxf.cancelling": "DXF 내보내기 취소 중",
"dxf.exporting": "DXF 내보내는 중",
"dxf.invalid_tolerance": "곡선 허용 오차는 0.0001~1 mm 범위여야 합니다.",
"dxf.progress.index": "면 데이터 준비 중 (2/5)",
"dxf.progress.meshes": "메시 준비 중 (1/5)",
"dxf.progress.occlusion": "숨은선 판정 중 (4/5)",
"dxf.progress.projection": "형상 투영 중 (3/5)",
"dxf.progress.write": "DXF 쓰는 중 (5/5)",
"dxf.tolerance": "곡선 허용 오차",
"dxf.tolerance_help": "표시된 바디만 내보내며 곡선은 직선 구간으로 근사합니다. 허용 오차가 작을수록 곡선이 매끄러워지지만 처리 시간과 메모리 사용량이 늘어납니다.",
"home.documentation": "문서",
"home.in_this_browser": "이 브라우저에 저장됨",
"home.missing": "찾을 수 없음",
File diff suppressed because it is too large. Load diff
+11
View File
@@ -81,6 +81,7 @@
"Enable rule": "Включить правило",
"Enabled": "Включено",
"Explode": "Разобрать",
"Export Animation…": "Экспортировать анимацию…",
"Extents": "Пределы",
"Face attachment lost": "Привязка к грани потеряна",
"Faces": "Грани",
@@ -177,6 +178,7 @@
"Round": "Круглая",
"Rule": "Правило",
"Save Rule": "Сохранить правило",
"Save the study as an animated GIF, seen as the viewport shows it": "Сохранить исследование как анимированный GIF, как его показывает видовой экран",
"Saved preview. Geometry is being checked before editing.": "Сохранённый предпросмотр. Геометрия проверяется перед редактированием.",
"Scale factor": "Коэффициент масштаба",
"Search": "Поиск",
@@ -249,6 +251,13 @@
"browser.precision": "Точность: {precision}",
"browser.sketch_name": "Эскиз{number}",
"browser.units": "Единицы: {units}",
"cam.flat": "Плоский",
"cam.follower": "Толкатель",
"cam.knife": "Острие",
"cam.needs_joints": "нужны вращающееся и скользящее или качающееся сопряжения",
"cam.roller": "Ролик",
"cam.roller_pick": "Ролик (необязательно)",
"cam.tip_pick": "Острие (необязательно)",
"cmd.appearance_assign": "Внешний вид",
"cmd.appearance_library": "Библиотека внешних видов",
"cmd.appearance_list": "Список внешних видов",
@@ -352,6 +361,7 @@
"cmd.inspect_minimum_radius": "Анализ минимального радиуса",
"cmd.inspect_zebra": "Зебра-анализ",
"cmd.joint_as_built": "Сопряжение на месте",
"cmd.joint_cam": "Кулачок",
"cmd.joint_create": "Сопряжение",
"cmd.joint_delete": "Удалить сопряжение",
"cmd.joint_drive": "Привод сопряжений",
@@ -378,6 +388,7 @@
"cmd.model_threads": "Список резьб",
"cmd.motion_delete": "Удалить исследование движения",
"cmd.motion_export": "Экспортировать исследование движения",
"cmd.motion_export_animation": "Экспортировать анимацию движения",
"cmd.motion_list": "Список исследований движения",
"cmd.motion_play": "Воспроизвести исследование движения",
"cmd.motion_study": "Исследование движения",
+3
View File
@@ -85,6 +85,7 @@
"Enable rule": "Kuralı etkinleştir",
"Enabled": "Etkin",
"Explode": "Patlat",
"Export Animation…": "Animasyonu dışa aktar…",
"Extents": "Kapsamlar",
"Face": "Yüz",
"Face attachment lost": "Yüze bağlama kayboldu",
@@ -193,6 +194,7 @@
"Round": "Yuvarlak",
"Rule": "Kural",
"Save Rule": "Kuralı kaydet",
"Save the study as an animated GIF, seen as the viewport shows it": "Etüdü görünüm alanında göründüğü gibi animasyonlu GIF olarak kaydet",
"Saved preview. Geometry is being checked before editing.": "Kaydedilmiş önizleme. Düzenlemeden önce geometri kontrol ediliyor.",
"Scale factor": "Ölçek faktörü",
"Search": "Ara",
@@ -400,6 +402,7 @@
"cmd.model_threads": "Dişleri listele",
"cmd.motion_delete": "Hareket etüdünü sil",
"cmd.motion_export": "Hareket etüdünü dışa aktar",
"cmd.motion_export_animation": "Hareket animasyonunu dışa aktar",
"cmd.motion_list": "Hareket etütlerini listele",
"cmd.motion_play": "Hareket etüdünü oynat",
"cmd.motion_study": "Hareket etüdü",
+11
View File
@@ -92,6 +92,7 @@
"Enable rule": "Увімкнути правило",
"Enabled": "Увімкнено",
"Explode": "Рознести",
"Export Animation…": "Експортувати анімацію…",
"Export Current View as DXF": "Експортувати поточний вид як DXF",
"Export Current View as DXF…": "Експортувати поточний вид як DXF…",
"Export DXF…": "Експорт DXF…",
@@ -211,6 +212,7 @@
"Round": "Круглий",
"Rule": "Правило",
"Save Rule": "Зберегти правило",
"Save the study as an animated GIF, seen as the viewport shows it": "Зберегти дослідження як анімований GIF, як його показує вікно перегляду",
"Saved preview. Geometry is being checked before editing.": "Збережений перегляд. Геометрію перевіряють перед редагуванням.",
"Scale factor": "Коефіцієнт масштабу",
"Search": "Пошук",
@@ -293,6 +295,13 @@
"browser.precision": "Точність: {precision}",
"browser.sketch_name": "Ескіз{number}",
"browser.units": "Одиниці: {units}",
"cam.flat": "Плоский",
"cam.follower": "Штовхач",
"cam.knife": "Вістря",
"cam.needs_joints": "потрібні обертове й ковзне або хитне з'єднання",
"cam.roller": "Ролик",
"cam.roller_pick": "Ролик (необов'язково)",
"cam.tip_pick": "Вістря (необов'язково)",
"cmd.appearance_assign": "Вигляд",
"cmd.appearance_library": "Бібліотека виглядів",
"cmd.appearance_list": "Список виглядів",
@@ -396,6 +405,7 @@
"cmd.inspect_minimum_radius": "Аналіз мінімального радіуса",
"cmd.inspect_zebra": "Зебра-аналіз",
"cmd.joint_as_built": "З'єднання за поточним положенням",
"cmd.joint_cam": "Кулачок",
"cmd.joint_create": "З'єднання",
"cmd.joint_delete": "Видалити з'єднання",
"cmd.joint_drive": "Керувати з'єднаннями",
@@ -426,6 +436,7 @@
"cmd.model_threads": "Список різьб",
"cmd.motion_delete": "Видалити дослідження руху",
"cmd.motion_export": "Експортувати дослідження руху",
"cmd.motion_export_animation": "Експортувати анімацію руху",
"cmd.motion_list": "Список досліджень руху",
"cmd.motion_play": "Відтворити дослідження руху",
"cmd.motion_study": "Дослідження руху",
+27
View File
@@ -92,6 +92,7 @@
"Enable rule": "启用规则",
"Enabled": "已启用",
"Explode": "爆炸",
"Export Animation…": "导出动画…",
"Export Current View as DXF": "将当前视图导出为DXF",
"Export Current View as DXF…": "将当前视图导出为DXF…",
"Export DXF…": "导出DXF…",
@@ -211,6 +212,7 @@
"Round": "圆角",
"Rule": "规则",
"Save Rule": "保存规则",
"Save the study as an animated GIF, seen as the viewport shows it": "按视口中的显示将研究保存为动画 GIF",
"Saved preview. Geometry is being checked before editing.": "已保存预览。编辑前正在检查几何。",
"Scale factor": "比例因子",
"Search": "搜索",
@@ -293,6 +295,13 @@
"browser.precision": "精度: {precision}",
"browser.sketch_name": "草图{number}",
"browser.units": "单位: {units}",
"cam.flat": "平底",
"cam.follower": "从动件",
"cam.knife": "尖顶",
"cam.needs_joints": "需要一个旋转接头和一个滑动或摆动接头",
"cam.roller": "滚子",
"cam.roller_pick": "滚子(可选)",
"cam.tip_pick": "尖端(可选)",
"cmd.appearance_assign": "外观",
"cmd.appearance_library": "外观库",
"cmd.appearance_list": "列出外观",
@@ -396,6 +405,7 @@
"cmd.inspect_minimum_radius": "最小半径分析",
"cmd.inspect_zebra": "斑马纹分析",
"cmd.joint_as_built": "现状接头",
"cmd.joint_cam": "凸轮",
"cmd.joint_create": "接头",
"cmd.joint_delete": "删除接头",
"cmd.joint_drive": "驱动接头",
@@ -426,6 +436,7 @@
"cmd.model_threads": "列出螺纹",
"cmd.motion_delete": "删除运动研究",
"cmd.motion_export": "导出运动研究",
"cmd.motion_export_animation": "导出运动动画",
"cmd.motion_list": "列出运动研究",
"cmd.motion_play": "播放运动研究",
"cmd.motion_study": "运动研究",
@@ -631,6 +642,18 @@
"drive.stopped_by_contact": "停在 {value}:{a} 会穿过 {b}",
"drive.stopped_by_loop": "停在 {value}:经过 {joint} 的环路无法再闭合",
"drive.unconnected": "没有任何移动:{part} 未连接到任何固定的零部件",
"dxf.cancel_wait": "正在等待导出停止…",
"dxf.cancelled": "DXF 导出已取消",
"dxf.cancelling": "正在取消 DXF 导出",
"dxf.exporting": "正在导出 DXF",
"dxf.invalid_tolerance": "曲线公差必须介于 0.0001 和 1 mm 之间。",
"dxf.progress.index": "正在准备曲面 (2/5)",
"dxf.progress.meshes": "正在准备网格 (1/5)",
"dxf.progress.occlusion": "正在判定隐藏线 (4/5)",
"dxf.progress.projection": "正在投影几何体 (3/5)",
"dxf.progress.write": "正在写入 DXF (5/5)",
"dxf.tolerance": "曲线公差",
"dxf.tolerance_help": "仅导出可见实体。曲线使用直线段近似。公差越小,曲线越精细,但需要更多时间和内存。",
"expression, e.g. 25 mm": "表达式,例如 25 mm",
"fits the face, e.g. M8": "适配该面,例如 M8",
"from the rule": "来自规则",
@@ -760,6 +783,10 @@
"sketch_text.path_hint": "文字所跟随的草图曲线:先单击此处,再选择曲线",
"sketch_text.use_font_file": "使用字体文件 {path}",
"the parts library is not available": "零件库不可用",
"thread.automatic_size": "自动尺寸",
"thread.designation": "螺纹标记",
"thread.iso_metric": "ISO 公制",
"thread.select_size": "选择尺寸",
"timeline.group": "新建特征文件夹",
"timeline.move_many": "移动时间线项目",
"timeline.move_to_group": "将特征移至文件夹",
+4 -2
View File
@@ -21,7 +21,8 @@
//! `|i: usize, n: usize| -> &'static str`; it may read the other fields;
//! - `pinned`: a face pick that stays where it is when the feature moves;
//! `pick_if = cond`: a face pick when `cond` holds, else a position;
//! - `placement`: a primitive's placement point (its X, Y and Z expressions are not inputs);
//! - `placement`: a primitive's placement point, or an optional one (its X, Y and Z expressions
//! are not inputs);
//! - `profiles_of = sketch_field`, optionally with `when = cond`: a profile selection;
//! - `after = field`: visit this field right after `field` instead of in declaration order (where
//! the parameter names already given need it);
@@ -162,7 +163,8 @@ fn walk_field(b: &Ident, r: &Roles, which: Which, mutable: bool) -> Tokens {
#w::Each::<#w::Vec3>::#each(#b, &mut |p| f(if #pick { #w::Geo::Pick(p) } else { #w::Geo::Pos(p) }));
}
}
Some(Geo::Placement) => quote! { f(#w::Geo::Placement(#b)); },
// A point or an optional one (a hole's `at`, #1678).
Some(Geo::Placement) => quote! { #w::Each::<crate::PointExpr>::#each(#b, &mut |p| f(#w::Geo::Placement(p))); },
Some(Geo::Profiles { .. }) => {
let (id, when) = (pre(b, "sketch"), pre(b, "when"));
quote! {
+22
View File
@@ -662,6 +662,12 @@ pub enum FeatureKind {
Hole {
#[walk(pick_if = points.is_none())]
position: FacePick,
/// The position as length expressions, when it was given that way (#1678): the hole is
/// drilled where they evaluate, and follows the parameters. `position` keeps the point
/// they gave when the hole was made.
#[serde(default, skip_serializing_if = "Option::is_none", with = "opt_point_expr")]
#[walk(placement)]
at: Option<PointExpr>,
/// Drilling direction (into the material).
direction: Dir,
#[walk(length = "Diameter")]
@@ -1935,6 +1941,22 @@ mod point_expr {
}
}
/// [`point_expr`] for an optional point.
mod opt_point_expr {
use serde::{Deserialize, Deserializer, Serialize, Serializer};
#[derive(Serialize, Deserialize)]
struct Wrap(#[serde(with = "super::point_expr")] super::PointExpr);
pub fn serialize<S: Serializer>(p: &Option<super::PointExpr>, s: S) -> Result<S::Ok, S::Error> {
p.as_ref().map(|p| Wrap(p.clone())).serialize(s)
}
pub fn deserialize<'de, D: Deserializer<'de>>(d: D) -> Result<Option<super::PointExpr>, D::Error> {
Ok(Option::<Wrap>::deserialize(d)?.map(|w| w.0))
}
}
impl FeatureKind {
/// A sheet metal feature (its result depends on the sheet metal rules).
pub fn is_plastic(&self) -> bool {
+124 -18
View File
@@ -209,6 +209,12 @@ const ISO_COARSE: [(f64, f64); 22] = [
(56.0, 5.5),
];
/// Nominal diameters and coarse pitches (mm) used for automatic ISO metric thread sizing.
/// Other diameter/pitch pairs can be supplied as explicit designations.
pub fn metric_thread_sizes() -> &'static [(f64, f64)] {
&ISO_COARSE
}
/// "M8" or "M8x1" → (nominal diameter, pitch).
pub fn parse_metric_thread(s: &str) -> Option<(f64, f64)> {
let t = s.trim().to_ascii_uppercase();
@@ -221,7 +227,7 @@ pub fn parse_metric_thread(s: &str) -> Option<(f64, f64)> {
Some(p) => p,
None => ISO_COARSE.iter().find(|(n, _)| (n - d).abs() < 1e-9)?.1,
};
(d > 0.0 && pitch > 0.0 && pitch < d).then_some((d, pitch))
(d.is_finite() && pitch.is_finite() && d > 0.0 && pitch > 0.0 && pitch < d).then_some((d, pitch))
}
/// The metric thread a cylinder of this diameter takes: a shaft is the major diameter, a hole
@@ -241,6 +247,12 @@ fn format_thread(d: f64, p: f64) -> String {
if coarse { format!("M{}", num(d)) } else { format!("M{}x{}", num(d), num(p)) }
}
/// The automatic ISO metric designation for a cylindrical face, using the same fit check as
/// a thread feature without an explicit size. This query does not change the model.
pub fn suggested_thread(st: &ModelState, p: Vec3) -> Result<String> {
thread_on(st, 0, p, None, None).map(|t| t.designation)
}
/// A cosmetic thread on the cylindrical face at `p`.
fn thread_on(st: &ModelState, feature: u64, p: Vec3, designation: Option<&str>, length: Option<f64>) -> Result<ThreadInfo> {
let (body, cyl) = st
@@ -1930,6 +1942,39 @@ fn extend_for_coplanar(st: &ModelState, plane: &Plane, r: &Region2, lo: f64, hi:
(lo2, hi2)
}
/// Whether a tapered tool, run on by `depth` behind the plane it starts in (`dir` the way it
/// extrudes), stays where running on changes nothing: in the targets for a join, out of them for
/// a cut. Its sides keep their slope, so the section there is the profile grown by up to `widen`
/// all round; that grown outline is probed at two depths.
#[allow(clippy::too_many_arguments)]
fn taper_run_on_fits(st: &ModelState, start: &Plane, dir: Vec3, r: &Region2, depth: f64, widen: f64, op: Operation, targets: &[String]) -> bool {
const MAX_SEGMENTS: usize = 2_000;
let meshes: Vec<Arc<Mesh>> = st.bodies.iter().filter(|b| targets.is_empty() || targets.contains(&b.name)).map(|b| b.mesh()).collect();
if meshes.is_empty() || !depth.is_finite() || !widen.is_finite() {
return false;
}
let want = op == Operation::Join;
// Each loop counterclockwise with the side away from the material: right of the outer loop,
// left of a hole.
let loops: Vec<(solidcraft_geom::Loop2, f64)> = std::iter::once((r.outer.ccw(), 1.0)).chain(r.holes.iter().map(|h| (h.ccw(), -1.0))).collect();
let count: usize = loops.iter().map(|(l, _)| l.segs.len()).sum();
if count > MAX_SEGMENTS {
return false;
}
loops.iter().all(|(lp, side)| {
lp.segs.iter().all(|seg| {
[0.0, 0.25, 0.5, 0.75].iter().all(|t| {
let Some(d) = seg.derivative(*t).normalized() else { return true };
let out = Vec2::new(d.y, -d.x) * *side;
[0.5, 1.0].iter().all(|k| {
let p = start.to_world(seg.point_at(*t) + out * (widen * k)) - dir * (depth * k);
meshes.iter().any(|m| m.contains(p)) == want
})
})
})
})
}
/// How high (mm) a tapered tool's sides stand straight where it starts on a face it can't run
/// on into.
const TAPER_FOOT: f64 = 0.01;
@@ -2300,8 +2345,8 @@ fn sketch_hole_dir(st: &ModelState, spots: &[Vec3], n: Vec3) -> Vec3 {
/// Where a hole feature drills (each on the surface) and in which direction: at its sketch
/// points perpendicular to the sketch (into the material), else at its position.
fn hole_spots(st: &ModelState, f: &Feature) -> Result<(Vec<Vec3>, Vec3)> {
let FeatureKind::Hole { position, direction, points, .. } = &f.kind else { return Err(DocError::Invalid("not a hole".into())) };
fn hole_spots(vals: &BTreeMap<String, Value>, st: &ModelState, f: &Feature) -> Result<(Vec<Vec3>, Vec3)> {
let FeatureKind::Hole { position, at, direction, points, .. } = &f.kind else { return Err(DocError::Invalid("not a hole".into())) };
let (spots, dir) = match points {
Some(sp) => {
let ss =
@@ -2317,7 +2362,7 @@ fn hole_spots(st: &ModelState, f: &Feature) -> Result<(Vec<Vec3>, Vec3)> {
}
None => {
let dir = direction.normalized().ok_or_else(|| DocError::Invalid("hole direction".into()))?;
let at = hole_on_surface(st, position.0, dir);
let at = hole_on_surface(st, hole_position(vals, position, at)?, dir);
let dir = hole_dir_into_face(st, at, dir);
return Ok((vec![hole_on_surface(st, at, dir)], dir));
}
@@ -2351,8 +2396,8 @@ fn hole_depth_to(st: &ModelState, at: &Vec3, dir: Vec3, to: &Option<Vec3>, depth
}
/// A hole's spots as given (not yet moved onto the surface) and its direction.
fn hole_spots_raw(st: &ModelState, f: &Feature) -> Result<(Vec<Vec3>, Vec3)> {
let FeatureKind::Hole { position, direction, points, .. } = &f.kind else { return Err(DocError::Invalid("not a hole".into())) };
fn hole_spots_raw(vals: &BTreeMap<String, Value>, st: &ModelState, f: &Feature) -> Result<(Vec<Vec3>, Vec3)> {
let FeatureKind::Hole { position, at, direction, points, .. } = &f.kind else { return Err(DocError::Invalid("not a hole".into())) };
match points {
Some(sp) => {
let ss = st.sketch(sp.sketch.0).ok_or_else(|| DocError::Unknown(format!("sketch {}", sp.sketch)))?;
@@ -2364,16 +2409,29 @@ fn hole_spots_raw(st: &ModelState, f: &Feature) -> Result<(Vec<Vec3>, Vec3)> {
}
None => {
let dir = direction.normalized().ok_or_else(|| DocError::Invalid("hole direction".into()))?;
Ok((vec![position.0], hole_dir_into_face(st, hole_on_surface(st, position.0, dir), dir)))
let p = hole_position(vals, position, at)?;
Ok((vec![p], hole_dir_into_face(st, hole_on_surface(st, p, dir), dir)))
}
}
}
/// Where a hole placed by position is drilled: its `at` expressions evaluated, so it follows the
/// parameters (#1678), else the point it was given.
fn hole_position(vals: &BTreeMap<String, Value>, position: &crate::FacePick, at: &Option<crate::PointExpr>) -> Result<Vec3> {
let Some([x, y, z]) = at else { return Ok(position.0) };
let p =
Vec3::new(Document::eval_in(vals, x, Kind::Length)?, Document::eval_in(vals, y, Kind::Length)?, Document::eval_in(vals, z, Kind::Length)?);
if ![p.x, p.y, p.z].iter().all(|c| c.is_finite() && c.abs() < 1e9) {
return Err(DocError::Invalid("the hole's position is out of range".into()));
}
Ok(p)
}
/// The cutting tools of a hole feature at every spot, each with its exact geometry when it is a
/// straight cylinder (see [`hole_tools_and_prisms`]).
fn hole_feature_tools(vals: &BTreeMap<String, Value>, st: &ModelState, f: &Feature) -> Result<Vec<(Traced, Option<more::PrimitivePrism>)>> {
let FeatureKind::Hole { diameter, depth, hole, to, .. } = &f.kind else { return Err(DocError::Invalid("not a hole".into())) };
let (spots, dir) = hole_spots(st, f)?;
let (spots, dir) = hole_spots(vals, st, f)?;
if spots.is_empty() || spots.len() > 10_000 {
return Err(DocError::Invalid("a hole needs 1…10000 points".into()));
}
@@ -2815,16 +2873,40 @@ fn feature_tools_with_constructor(
// sides standing on a face are curved where they meet it (along text, say),
// and the boolean finds no result there. The sides keep their slope, so
// the profile stays the section at the start.
let roles = crate::lineage::ProfileRoles { sketch: Some(&ss), region: Some(r), caps: caps.clone() };
// A start that is a whole face of the target (a foot under a part's base) is sewn on
// along it, as it lies: run on, the sides would leave the face through its edges.
if on_face
&& *operation == Operation::Join
&& let Ok(exact) = kernel::extrude_tapered_between(&start_plane, r, 0.0, len, 0.0, sign, taper)
&& st
.bodies
.iter()
.filter(|t| targets.is_empty() || targets.iter().any(|x| *x == t.name))
.any(|t| kernel::can_join_touching_faces(&t.body, &exact))
{
growth = growth.max(len * taper.tan().abs());
return Ok(roles.tool(exact, None));
}
let (lo, hi) = if sign < 0.0 { (from - len, from) } else { (from, from + len) };
let (l2, h2) = extend_for_coplanar(st, &ss.plane, r, lo, hi, *operation, &crate::plain(targets));
let (a, b) = if sign < 0.0 { (from - h2, from - l2) } else { (l2 - from, h2 - from) };
let (mut a, b) = if sign < 0.0 { (from - h2, from - l2) } else { (l2 - from, h2 - from) };
// A taper that narrows the tool away from the face widens it as it runs on into it, past
// the profile (where the profile is the whole face, out through the body's sides, #1534):
// then it starts on the face instead.
if a < 0.0 && a * taper.tan() > 0.0 {
let dir = n * sign;
if !taper_run_on_fits(st, &start_plane, dir, r, -a, a * taper.tan(), *operation, &crate::plain(targets)) {
a = 0.0;
}
}
// A start that can't run on (the profile hangs over the face's edge):
// the sides stand straight for a hair first, so the boolean can push the
// face the tool stands on into the body.
let foot = if a >= 0.0 && on_face { TAPER_FOOT.min((b - a) * 0.01) } else { 0.0 };
let body = kernel::extrude_tapered_between(&start_plane, r, a, b, foot, sign, taper)?;
growth = growth.max(a.abs().max(b.abs()) * taper.tan().abs());
Ok(crate::lineage::ProfileRoles { sketch: Some(&ss), region: Some(r), caps: caps.clone() }.tool(body, None))
Ok(roles.tool(body, None))
})
.collect::<Result<_>>()?;
// Profiles apart by more than the tools grow (the letters of a text): the tools
@@ -3085,6 +3167,9 @@ fn feature_tools_with_constructor(
{
return build_curved(&regions, -axis_w, tb);
}
// A new body is final: its planar faces come out whole. A boolean's tool is not
// healed (the boolean heals its result).
let revolve = if operation == Operation::NewBody { kernel::revolve_whole } else { kernel::revolve };
if *convention == crate::RevolveConvention::SketchNormal {
let mut out = Vec::new();
for (region, region_extent) in regions.iter().zip(&region_extents) {
@@ -3093,7 +3178,7 @@ fn feature_tools_with_constructor(
out.extend(build_curved(std::slice::from_ref(region), rotation_axis, tb)?);
continue;
}
let bodies = kernel::revolve(&ss.plane, std::slice::from_ref(region), o, d, region_extent.sweep)?;
let bodies = revolve(&ss.plane, std::slice::from_ref(region), o, d, region_extent.sweep)?;
let m = crate::rigid(Vec3::ZERO, origin_w, rotation_axis, region_extent.start);
for body in bodies {
out.push(if region_extent.start.abs() < 1e-12 {
@@ -3105,7 +3190,7 @@ fn feature_tools_with_constructor(
}
return Ok(out);
}
let bodies = kernel::revolve(&ss.plane, &regions, o, d, ang)?;
let bodies = revolve(&ss.plane, &regions, o, d, ang)?;
if start.abs() < 1e-12 {
return Ok(regions.iter().zip(bodies).map(|(r, body)| tool(r, body, None)).collect());
}
@@ -3755,7 +3840,7 @@ fn replay(
// A hole is drilled again at each copy of its spot (found on the surface there), so
// a blind hole's depth counts from the face at the copy, not from the bottom of the
// original hole under the original spot.
let (spots, dir) = hole_spots_raw(st, src)?;
let (spots, dir) = hole_spots_raw(vals, st, src)?;
for (k, m) in mats.iter().enumerate() {
let d = crate::apply_vector(m, dir).normalized().ok_or_else(|| DocError::Invalid("hole direction".into()))?;
for p in &spots {
@@ -4208,7 +4293,7 @@ fn eval_feature(doc: &Document, vals: &BTreeMap<String, Value>, f: &Feature, st:
apply_traced(st, f, tools, *operation, &crate::plain(targets))
}
FeatureKind::Hole { thread, diameter, .. } => {
let (spots, dir) = hole_spots(st, f)?;
let (spots, dir) = hole_spots(vals, st, f)?;
let tools = hole_feature_tools(vals, st, f)?;
let handled = sheet_hole_cut(st, f, &tools, warning)?;
let tools: Vec<Traced> = tools.into_iter().map(|(tool, _)| tool).collect();
@@ -4410,31 +4495,35 @@ fn eval_feature(doc: &Document, vals: &BTreeMap<String, Value>, f: &Feature, st:
FeatureKind::Split { body, plane, tool, sketch, line } => {
let i = st.bodies.iter().position(|b| &b.name == body).ok_or_else(|| DocError::Unknown(format!("body `{body}`")))?;
let Some(mb) = st.bodies.get(i).cloned() else { return Err(DocError::Unknown(format!("body `{body}`"))) };
let input = mb.traced();
let parts = match tool {
// A sketch line: the plane through it along the sketch's normal.
_ if sketch.is_some() || line.is_some() => {
let (Some(sketch), Some(line)) = (sketch, line) else {
return Err(DocError::Invalid("a sketch line tool needs both its sketch and its line".into()));
};
kernel::split_by_plane(&mb.body, &sketch_line_plane(st, sketch.0, line)?)?
split_by_plane_traced(&input, &sketch_line_plane(st, sketch.0, line)?)?
}
// A face of a body (its surface extended).
Some(t) => {
let tb = st.body(&t.body).ok_or_else(|| DocError::Unknown(format!("body `{}`", t.body)))?;
let face = crate::appearance::face_index_at(tb, t.point.0)
.ok_or_else(|| DocError::Invalid(format!("no face of `{}` at the tool point", t.body)))?;
// The pieces keep the planar roles of the faces they share with the body (#565).
kernel::split_body(&mb.body, &kernel::SplitTool::Face { body: &tb.body, face })?
.into_iter()
.map(|part| Ok(Traced::step(part.with_preserved_planar_sources(&mb.body)?, &[&input])))
.collect::<Result<Vec<_>>>()?
}
None => {
let pl = doc.resolve_plane_in(vals, plane, 0, Some(st))?;
kernel::split_by_plane(&mb.body, &pl)?
split_by_plane_traced(&input, &pl)?
}
};
if parts.len() < 2 {
return Err(DocError::Invalid("the tool does not split the body".into()));
}
let input = mb.traced();
let mut it = parts.into_iter().map(|part| Traced::step(part, &[&input]));
let mut it = parts.into_iter();
if let (Some(first), Some(slot)) = (it.next(), st.bodies.get_mut(i)) {
*slot = ModelBody::traced_new(mb.name.clone(), first, mb.feature);
}
@@ -5291,6 +5380,23 @@ mod body_name_tests {
}
}
/// The parts of a body split by a plane, on its positive side first (only the non-empty ones).
/// Each part's cut face is named `section` after the half-space box that cut it, so it takes an
/// attachment that follows the plane (#565); the box's other faces never reach the part.
fn split_by_plane_traced(input: &Traced, plane: &Plane) -> Result<Vec<Traced>> {
let mut parts = Vec::new();
for positive in [true, false] {
let (part, tool) = kernel::half_space(&input.body, plane, positive)?;
let Some(part) = part else { continue };
// The box's cap in the plane: its start cap on the positive side, its end cap on the other.
let section = Some("section".to_string());
let caps = if positive { [section, None] } else { [None, section] };
let tool = crate::lineage::ProfileRoles { sketch: None, region: None, caps }.tool(tool, None);
parts.push(Traced::step(part, &[input, &tool]));
}
Ok(parts)
}
/// The plane a straight sketch line sweeps along its sketch's normal: through the line, its x
/// along the line and its y along the normal (a Split Body tool, #1552).
pub fn sketch_line_plane(st: &ModelState, sketch: u64, line: &str) -> Result<Plane> {
@@ -0,0 +1,8 @@
//! A motion link can carry a `cam` coupling (`joint.cam`): the cam's `profile` (a sketch's closed
//! profile by its outer loop's curve ids, or picked edges of the cam's bodies with their names),
//! the `follower` (`knife`, `roller` with a `radius`, or `flat`), an optional `tip` (a joint origin
//! where the follower touches) and `reverse` (the side it rides from). The link then also saves
//! `lift`, the follower's values over one turn of the cam, worked out from the profile again
//! whenever the design changes. Older designs need no transformation: a link without them is a
//! plain motion link, as it always was; 0.13.x asks for an update instead of reading a cam's
//! follower as a plain link of ratio 1.
@@ -0,0 +1,5 @@
//! A Hole placed by position can keep that position as length expressions (`at`: `[x, y, z]`,
//! numbers as numbers, expressions as strings), and is drilled where they evaluate, so it follows
//! the design's parameters (#1678). `position` still holds the point it was made at. Older designs
//! need no transformation: a hole without `at` is drilled at `position` as before; 0.13.x asks for
//! an update instead of drilling a moved hole at its old point.
+61 -16
View File
@@ -1,8 +1,8 @@
//! Joints between occurrences: joint origins (snap frames on component geometry, re-found on
//! every solve so they follow edits), joints (rigid, revolute, slider, cylindrical, pin-slot,
//! planar, ball) with their motion values and limits, motion links (gears, racks and screws are
//! links whose ratio comes from radii or a pitch), and the solver that places occurrences from
//! the joint graph.
//! links whose ratio comes from radii or a pitch; a cam's follower follows a table worked out from
//! its profile, `joints_cam.rs`), and the solver that places occurrences from the joint graph.
//!
//! A joint makes B's joint frame coincide with A's frame moved by the joint's motion:
//! `T_B · F_b = T_A · F_a · M(q) · Flip`, so `T_B = T_A · F_a · M(q) · Flip · F_b⁻¹`, where `T`
@@ -140,7 +140,8 @@ pub struct Joint {
pub suppressed: bool,
}
/// Value of joint `b` (index `ib`) = ratio · value of joint `a` (index `ia`) + offset.
/// Value of joint `b` (index `ib`) = ratio · value of joint `a` (index `ia`) + offset, or for a
/// cam, its `lift` table at a's value + offset.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct MotionLink {
pub a: u64,
@@ -152,11 +153,29 @@ pub struct MotionLink {
pub ratio: f64,
#[serde(default)]
pub offset: f64,
/// Gears, a rack and pinion or a screw: what the ratio comes from. The ratio is worked out
/// from it again whenever the design changes (`coupling_ratio`), so it follows the radii and
/// the pitch; the last one worked out is kept in `ratio`.
/// Gears, a rack and pinion, a screw or a cam: what the ratio (or a cam's table) comes from.
/// It is worked out from it again whenever the design changes (`coupling_values`), so it
/// follows the radii, the pitch and the cam's profile; the last one worked out is kept in
/// `ratio` and `lift`.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub coupling: Option<Coupling>,
/// A cam's follower values over one turn of a (`cam::CAM_SAMPLES` of them, in b's units, the
/// offset left out); empty for every other link.
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub lift: Vec<f64>,
}
impl MotionLink {
/// b's value for a's value `x` (before b's limits). A cam's table that is not whole (a
/// hand-edited file) gives no value, so b keeps where it is; a table on any other link is
/// not read.
pub fn follow(&self, x: f64) -> f64 {
match &self.coupling {
Some(Coupling::Cam(_)) if self.lift.len() == cam::CAM_SAMPLES => cam::lift_at(&self.lift, x) + self.offset,
Some(Coupling::Cam(_)) => f64::NAN,
_ => self.ratio * x + self.offset,
}
}
}
/// A length a coupling's ratio comes from: millimetres, an expression over the design's
@@ -199,14 +218,22 @@ pub enum Coupling {
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
reverse: bool,
},
/// A cam on a revolute joint (a) and its follower (b, a slider or a revolute): b rides the
/// cam's profile (`joints_cam.rs`).
Cam(cam::Cam),
}
impl Coupling {
/// The lengths the ratio comes from: a's gear and b's, or the pinion's radius or the pitch.
/// The lengths the ratio comes from: a's gear and b's, the pinion's radius, the pitch, or a
/// cam's roller radius.
pub fn sizes(&self) -> Vec<&Size> {
match self {
Coupling::Gear { ra, rb, .. } => vec![ra, rb],
Coupling::RackPinion { radius: s, .. } | Coupling::Screw { pitch: s, .. } => vec![s],
Coupling::Cam(c) => match &c.follower {
cam::Follower::Roller { radius } => vec![radius],
_ => Vec::new(),
},
}
}
@@ -214,6 +241,10 @@ impl Coupling {
match self {
Coupling::Gear { ra, rb, .. } => vec![ra, rb],
Coupling::RackPinion { radius: s, .. } | Coupling::Screw { pitch: s, .. } => vec![s],
Coupling::Cam(c) => match &mut c.follower {
cam::Follower::Roller { radius } => vec![radius],
_ => Vec::new(),
},
}
}
}
@@ -231,14 +262,18 @@ fn size_of(doc: &Document, st: &ModelState, s: &Size) -> Result<f64> {
if v.is_finite() && v > 1e-9 && v <= MAX_SIZE {
Ok(v)
} else {
Err(DocError::Invalid(format!("a gear, rack or screw needs a positive length, not {v}")))
Err(DocError::Invalid(format!("a gear, rack, screw or roller needs a positive length, not {v}")))
}
}
/// The ratio a link's coupling gives it (b's value per a's, in radians and mm), worked out from
/// the geometry and parameters it is defined by; `None` for a plain link.
pub fn coupling_ratio(doc: &Document, st: &ModelState, l: &MotionLink) -> Option<Result<f64>> {
l.coupling.as_ref().map(|c| coupled(doc, st, l, c))
/// The ratio a link's coupling gives it (b's value per a's, in radians and mm) and a cam's table
/// (`MotionLink::lift`; empty for the others), worked out from the geometry and parameters it is
/// defined by; `None` for a plain link.
pub fn coupling_values(doc: &Document, st: &ModelState, l: &MotionLink) -> Option<Result<(f64, Vec<f64>)>> {
l.coupling.as_ref().map(|c| match c {
Coupling::Cam(c) => cam::table(doc, st, l, c).map(|t| (1.0, t)),
c => coupled(doc, st, l, c).map(|r| (r, Vec::new())),
})
}
fn coupled(doc: &Document, st: &ModelState, l: &MotionLink, c: &Coupling) -> Result<f64> {
@@ -260,6 +295,8 @@ fn coupled(doc: &Document, st: &ModelState, l: &MotionLink, c: &Coupling) -> Res
}
Coupling::RackPinion { radius, reverse } => Ok(travel(size_of(doc, st, radius)?)? * sign(*reverse)),
Coupling::Screw { pitch, reverse } => Ok(travel(size_of(doc, st, pitch)? / std::f64::consts::TAU)? * sign(*reverse)),
// A cam's follower follows its table (`coupling_values`), not a ratio.
Coupling::Cam(_) => Ok(1.0),
}
}
@@ -491,7 +528,11 @@ fn apply_links(asm: &Assembly, vals: &mut Values) {
let before = linked(vals);
for l in &asm.links {
let Some(src) = vals.get(&l.a).and_then(|q| q.get(l.ia)).copied() else { continue };
let mut next = l.ratio * src + l.offset;
let mut next = l.follow(src);
// A hand-edited table (or source) that gives no number leaves b where it is.
if !next.is_finite() {
continue;
}
if let Some((lo, hi)) = limits.get(&(l.b, l.ib)) {
next = next.max(*lo).min(*hi);
}
@@ -1388,6 +1429,9 @@ impl Document {
}
}
#[path = "joints_cam.rs"]
pub mod cam;
#[path = "joints_reach.rs"]
mod reach;
pub use reach::{REACH_TOL, Reach, Reached, reach};
@@ -1425,7 +1469,8 @@ mod tests {
suppressed: false,
})
.collect();
let links = (1..n).rev().map(|a| MotionLink { a, ia: 0, b: a + 1, ib: 0, ratio: 2.0, offset: 0.0, coupling: None }).collect();
let links =
(1..n).rev().map(|a| MotionLink { a, ia: 0, b: a + 1, ib: 0, ratio: 2.0, offset: 0.0, coupling: None, lift: Vec::new() }).collect();
Assembly { joints, links, ..Assembly::default() }
}
@@ -1477,8 +1522,8 @@ mod tests {
}
let st = ModelState::default();
let ratio = |a: u64, b: u64, c: Coupling| {
let l = MotionLink { a, ia: 0, b, ib: 0, ratio: 0.0, offset: 0.0, coupling: Some(c) };
coupling_ratio(&doc, &st, &l).map(|r| r.map_err(|e| e.to_string()))
let l = MotionLink { a, ia: 0, b, ib: 0, ratio: 0.0, offset: 0.0, coupling: Some(c), lift: Vec::new() };
coupling_values(&doc, &st, &l).map(|r| r.map(|(ratio, _)| ratio).map_err(|e| e.to_string()))
};
let len = Size::Length;
assert_eq!(ratio(1, 2, Coupling::Gear { ra: len(10.0), rb: len(40.0), internal: false, reverse: false }), Some(Ok(-0.25)));
File diff suppressed because it is too large. Load diff
+3 -3
View File
@@ -58,9 +58,9 @@ pub use assembly::{
pub use document::*;
pub use eval::{
EdgeRef, FeatureResult, Model, ModelBody, ModelState, PlacedBodies, RevolveExtent, SolvedSketch, ThreadInfo, curve_pick_error, edge_names_for,
edge_refs, face_point_names, face_point_state, hole_direction_at, import_body_names, object_height, parse_metric_thread, pattern_matrices,
revolve_extent, revolve_extent_with_convention, select_profiles, sketch_hole_direction, sketch_line_plane, state_in_frame, state_in_frame_at,
through_all_distance, world_state, world_state_reusing,
edge_refs, face_point_names, face_point_state, hole_direction_at, import_body_names, metric_thread_sizes, object_height, parse_metric_thread,
pattern_matrices, revolve_extent, revolve_extent_with_convention, select_profiles, sketch_hole_direction, sketch_line_plane, state_in_frame,
state_in_frame_at, suggested_thread, through_all_distance, world_state, world_state_reusing,
};
pub use expr::Expr;
pub use names::{BodyName, FeatureName, SketchId};
+4
View File
@@ -8,6 +8,10 @@ license.workspace = true
[lints]
workspace = true
[features]
default = []
raytrace-cpu = ["solidcraft-render/raytrace-cpu"]
[dependencies]
solidcraft-geom = { workspace = true }
solidcraft-sketch = { workspace = true }
+11 -3
View File
@@ -214,10 +214,18 @@ fn rename(s: &mut Session, p: &Value) -> Result<Value> {
let id = component(s, p, "component", cmd)?;
let name =
str_(p, "name").map(str::trim).filter(|n| !n.is_empty() && n.len() <= 128).ok_or_else(|| bad(cmd, "`name` must be 1…128 characters"))?;
let d = s.doc_mut();
if id == 0 {
s.doc_mut().name = name.to_string();
} else if let Some(c) = s.doc_mut().components.iter_mut().find(|c| c.id == id) {
c.name = name.to_string();
d.name = name.to_string();
} else if let Some(c) = d.components.iter_mut().find(|c| c.id == id) {
let old = std::mem::replace(&mut c.name, name.to_string());
// Placements still named after the component ("Old:2") follow it (#1665); others keep theirs.
for o in d.occurrences.iter_mut().filter(|o| o.component == id) {
let k = o.name.strip_prefix(old.as_str()).and_then(|r| r.strip_prefix(':'));
if let Some(k) = k.filter(|k| !k.is_empty() && k.bytes().all(|b| b.is_ascii_digit())) {
o.name = format!("{name}:{k}");
}
}
}
Ok(json!({"component": id, "name": name}))
}
@@ -3,6 +3,7 @@
use std::collections::{BTreeMap, BTreeSet};
use solidcraft_doc::Document;
use solidcraft_doc::joints::cam::CamProfile;
use solidcraft_doc::joints::{Assembly, Coupling, JointOrigin, Size, Snap};
use crate::{EngineError, Result};
@@ -102,9 +103,31 @@ fn budget(assembly: &Assembly) -> Result<()> {
return Err(invalid("exploded view contains non-finite moves"));
}
}
if !assembly.links.iter().all(|l| l.ratio.is_finite() && l.offset.is_finite()) {
if !assembly.links.iter().all(|l| l.ratio.is_finite() && l.offset.is_finite() && l.lift.iter().all(|v| v.is_finite())) {
return Err(invalid("motion link contains non-finite values"));
}
for cam in assembly.links.iter().filter_map(|l| match &l.coupling {
Some(Coupling::Cam(c)) => Some(c),
_ => None,
}) {
add_references(&mut references, cam.tip.iter().count())?;
if let Some(tip) = &cam.tip {
finite_origin(tip)?;
}
match &cam.profile {
CamProfile::Sketch { curves, .. } => {
add_references(&mut references, curves.len())?;
curves.iter().try_for_each(|c| text(c))?;
}
CamProfile::Edges { picks, names, .. } => {
add_references(&mut references, picks.len() + names.len())?;
if !picks.iter().all(|p| p.is_finite()) {
return Err(invalid("motion link contains non-finite values"));
}
names.iter().try_for_each(|n| text(n))?;
}
}
}
for size in assembly.links.iter().filter_map(|l| l.coupling.as_ref()).flat_map(Coupling::sizes) {
match size {
Size::Length(v) if !v.is_finite() => return Err(invalid("motion link contains non-finite values")),
@@ -300,12 +323,26 @@ pub(super) fn clone_assembly(
continue;
}
let mut item = old.clone();
// A gear's picked round faces are on occurrences of the copy too.
// A gear's picked round faces are on occurrences of the copy too, and so are a cam's
// profile and its follower's tip.
let faces = item.coupling.as_mut().is_none_or(|c| {
c.sizes_mut().into_iter().all(|size| match size {
let sizes = c.sizes_mut().into_iter().all(|size| match size {
Size::Circle(o) => origin(o, occurrences, features, bodies).map(|new| *o = new).is_some(),
_ => true,
})
});
let Coupling::Cam(cam) = c else { return sizes };
let tip = match &mut cam.tip {
Some(t) => origin(t, occurrences, features, bodies).map(|new| *t = new).is_some(),
None => true,
};
let profile = match &mut cam.profile {
CamProfile::Sketch { sketch, .. } => features.get(sketch).map(|new| *sketch = *new).is_some(),
CamProfile::Edges { occurrence, names, .. } => {
occurrences.get(occurrence).map(|new| *occurrence = *new).is_some()
&& names.iter_mut().all(|n| n.is_empty() || face_name(n, features, bodies).map(|new| *n = new).is_some())
}
};
sizes && tip && profile
});
match (joints.get(&old.a), joints.get(&old.b)) {
(Some(aa), Some(bb)) if faces => {
@@ -44,8 +44,8 @@ fn documents() -> (Document, Document) {
NamedOrigin { name: "Outside".into(), origin: at(9) },
];
source.assembly.links = vec![
MotionLink { a: 1, ia: 0, b: 2, ib: 0, ratio: -2.0, offset: 0.3, coupling: None },
MotionLink { a: 1, ia: 0, b: 3, ib: 0, ratio: 1.0, offset: 0.0, coupling: None },
MotionLink { a: 1, ia: 0, b: 2, ib: 0, ratio: -2.0, offset: 0.3, coupling: None, lift: Vec::new() },
MotionLink { a: 1, ia: 0, b: 3, ib: 0, ratio: 1.0, offset: 0.0, coupling: None, lift: Vec::new() },
];
source.assembly.contact_sets = vec![
ContactSet { id: 1, name: "Internal contact".into(), occurrences: vec![1, 2], suppressed: true },
@@ -106,8 +106,8 @@ fn copied_gears_take_their_picked_faces_along() {
let circle = |face: &str| Size::Circle(JointOrigin { occurrence: 1, snap: Snap::CircleCenter { pick: Vec3::X, face: Some(face.into()) } });
let gear = |ra| Coupling::Gear { ra, rb: Size::Length(5.0), internal: false, reverse: false };
source.assembly.links = vec![
MotionLink { a: 1, ia: 0, b: 2, ib: 0, ratio: -2.0, offset: 0.0, coupling: Some(gear(circle("F1:side"))) },
MotionLink { a: 2, ia: 0, b: 1, ib: 0, ratio: -0.5, offset: 0.0, coupling: Some(gear(circle("F99:side"))) },
MotionLink { a: 1, ia: 0, b: 2, ib: 0, ratio: -2.0, offset: 0.0, coupling: Some(gear(circle("F1:side"))), lift: Vec::new() },
MotionLink { a: 2, ia: 0, b: 1, ib: 0, ratio: -0.5, offset: 0.0, coupling: Some(gear(circle("F99:side"))), lift: Vec::new() },
];
let mut destination = source.clone();
destination.occurrences.extend([101, 102].map(occurrence));
+31 -4
View File
@@ -55,7 +55,7 @@ pub static COMMANDS: &[CommandSpec] = &[
.at("SOLID", "CREATE")
.icon("hole")
.key("H")
.params("position: [x,y,z] on a face | sketch + points: [sketch point ids] (one hole each, perpendicular to the sketch, into the material on whichever side of the sketch plane it is) | sketch alone (every sketch point: standalone points and circle centres); flip?: bool (sketch points: drill to the other side); direction?: [x,y,z] (default: into the face, against its outward normal; one that leaves the face is mirrored into it; ignored with sketch points); diameter | thread (a tapped hole: the tap drill, major − pitch) | clearance: \"M6\" with fit?: close|normal|loose (ISO 273); depth? (default through all) | to?: [x,y,z] (To Object: drill to that face or point); type?: simple|drilled|counterbore|countersink; tip_angle?; cb_diameter?, cb_depth?; cs_diameter?, cs_angle?; thread?: \"M6\" (cosmetic)"),
.params("position: [x,y,z] on a face (numbers, or length expressions the hole follows) | sketch + points: [sketch point ids] (one hole each, perpendicular to the sketch, into the material on whichever side of the sketch plane it is) | sketch alone (every sketch point: standalone points and circle centres); flip?: bool (sketch points: drill to the other side); direction?: [x,y,z] (default: into the face, against its outward normal; one that leaves the face is mirrored into it; ignored with sketch points); diameter | thread (a tapped hole: the tap drill, major − pitch) | clearance: \"M6\" with fit?: close|normal|loose (ISO 273); depth? (default through all) | to?: [x,y,z] (To Object: drill to that face or point); type?: simple|drilled|counterbore|countersink; tip_angle?; cb_diameter?, cb_depth?; cs_diameter?, cs_angle?; thread?: \"M6\" (cosmetic)"),
CommandSpec::new("solid.pipe", "Pipe", pipe)
.at("SOLID", "CREATE")
.icon("pipe")
@@ -79,7 +79,7 @@ pub static COMMANDS: &[CommandSpec] = &[
CommandSpec::new("solid.thread", "Thread", thread)
.at("SOLID", "CREATE")
.icon("thread")
.params("face: [x,y,z] on a cylindrical face; designation?: ISO metric (\"M8\", \"M8x1\"; default: the size that fits); length?: expr (default: the whole face). Cosmetic: the model is unchanged, model.threads lists it"),
.params("face: [x,y,z] on a cylindrical face; designation?: ISO metric (\"M8\", \"M8x1\"; default: the size that fits); length?: expr (default: the whole face); modeled?: bool (default false). Cosmetic: the model is unchanged, model.threads lists it. Modeled: cuts the thread profile into the body"),
CommandSpec::new("solid.shell", "Shell", shell)
.at("SOLID", "MODIFY")
.icon("shell")
@@ -1633,10 +1633,36 @@ fn hole(s: &mut Session, p: &Value) -> Result<Value> {
{
return Err(bad(cmd, format!("unknown thread `{t}` (ISO metric, like M6 or M6x0.75)")));
}
let position = match (&points, p.get("position").and_then(vec3)) {
// A position given as length expressions (#1678), say `["leg_h*0.4", "width/2", "t"]`: kept,
// so the hole follows the parameters; drilled where they evaluate now.
let at: Option<solidcraft_doc::PointExpr> = match p.get("position").and_then(Value::as_array) {
Some(a) if points.is_none() && a.len() == 3 && a.iter().any(Value::is_string) => {
let mut coords = Vec::with_capacity(3);
for v in a {
let e = match v {
Value::String(x) => x.trim().to_string(),
Value::Number(n) => n.to_string(),
_ => return Err(bad(cmd, "`position` must be [x, y, z]: numbers or length expressions")),
};
check_expr(s, &e, Kind::Length, cmd, "position")?;
coords.push(solidcraft_doc::Expr::new(e));
}
let [x, y, z]: [solidcraft_doc::Expr; 3] = coords.try_into().map_err(|_| bad(cmd, "`position` must be [x, y, z]"))?;
Some([x, y, z])
}
_ => None,
};
let at_value = match &at {
Some([x, y, z]) => {
let c = |e: &solidcraft_doc::Expr| s.doc.eval(e, Kind::Length).map_err(|e| bad(cmd, format!("`position`: {e}")));
Some(Vec3::new(c(x)?, c(y)?, c(z)?)).filter(|v| v.is_finite())
}
None => None,
};
let position = match (&points, at_value.or_else(|| p.get("position").and_then(vec3))) {
(Some((_, first, _)), None) => *first,
(_, Some(x)) => x,
(None, None) => return Err(bad(cmd, "`position` must be [x, y, z] (or give `sketch` and `points`)")),
(None, None) => return Err(bad(cmd, "`position` must be [x, y, z], numbers or length expressions (or give `sketch` and `points`)")),
};
let direction = match (p.get("direction").and_then(vec3), &points) {
(None, Some((_, _, d))) => *d,
@@ -1706,6 +1732,7 @@ fn hole(s: &mut Session, p: &Value) -> Result<Value> {
&p,
FeatureKind::Hole {
position: FacePick(position),
at,
direction: Dir(direction),
diameter,
depth,
+24 -6
View File
@@ -161,6 +161,8 @@ fn emboss(s: &mut Session, p: &Value) -> Result<Value> {
let at = solidcraft_doc::apply_point(&s.active_component_frame(), local);
let state = s.world_state();
let mut candidates = Vec::new();
// The nearest face off the point: (distance, body), for the error when none holds it.
let mut nearest: Option<(f64, &str)> = None;
for body in &state.bodies {
let definition = body.definition_name();
if !targets.is_empty() && !targets.iter().any(|n| n == definition || n == &body.name) {
@@ -179,14 +181,30 @@ fn emboss(s: &mut Session, p: &Value) -> Result<Value> {
inside.then_some(((at - a).dot(n).abs(), *face as usize))
})
.min_by(|a, b| a.0.total_cmp(&b.0));
if let Some((distance, index)) = closest
&& distance < (body.body.size() * 1e-3).max(1e-3)
{
candidates.push((body, index));
match closest {
Some((distance, index)) if distance < (body.body.size() * 1e-3).max(1e-3) => candidates.push((body, index)),
Some((distance, _)) if nearest.is_none_or(|(d, _)| distance < d) => nearest = Some((distance, body.name.as_str())),
_ => {}
}
}
if candidates.len() != 1 {
return Err(bad(cmd, "`face` must identify exactly one target body surface"));
// #392: say what is wrong with the point, not only that it picks no single face.
let point = format!("[{}, {}, {}]", local.x, local.y, local.z);
match (candidates.as_slice(), nearest) {
([], Some((d, body))) => {
return Err(bad(
cmd,
format!("`face` {point} lies on no face: the nearest, on `{body}`, is {d:.3} mm away; give a point on the face"),
));
}
([], None) => return Err(bad(cmd, format!("`face` {point} lies on no face of the target bodies"))),
([_], _) => {}
(more, _) => {
let names: Vec<&str> = more.iter().map(|(b, _)| b.name.as_str()).collect();
return Err(bad(
cmd,
format!("`face` {point} lies on faces of {} bodies ({}): name one in `targets`", names.len(), names.join(", ")),
));
}
}
let (selected, index) = candidates.first().copied().ok_or_else(|| bad(cmd, "no target face"))?;
let name = selected.definition_name();
@@ -92,6 +92,23 @@ fn emboss_and_deboss_on_a_face() {
assert!(s.execute("solid.emboss", &json!({"sketch": "Logo", "depth": 1, "mode": "sideways"})).is_err());
}
#[test]
fn emboss_face_off_the_part_says_how_far() {
// #392: a point beside the face was refused with "`face` must identify exactly one target
// body surface", which didn't say the point was off the face.
let mut s = Session::default();
run(&mut s, "solid.box", json!({"length": 40, "width": 30, "height": 10, "body_name": "A"}));
run(&mut s, "sketch.create", json!({"plane": {"face": [20, 15, 10]}, "name": "Logo"}));
run(&mut s, "sketch.rectangle.two_point", json!({"p0": [5, 5], "p1": [15, 15]}));
run(&mut s, "sketch.finish", json!({}));
let e = s.execute("solid.emboss", &json!({"sketch": "Logo", "depth": 1, "face": [20, 15, 11.25]})).unwrap_err().to_string();
assert!(e.contains("[20, 15, 11.25] lies on no face: the nearest, on `A`, is 1.250 mm away"), "{e}");
run(&mut s, "solid.box", json!({"length": 10, "width": 30, "height": 10, "corner": [40, 0, 0], "operation": "new_body", "body_name": "B"}));
let e = s.execute("solid.emboss", &json!({"sketch": "Logo", "depth": 1, "face": [40, 15, 5]})).unwrap_err().to_string();
assert!(e.contains("lies on faces of 2 bodies (A, B): name one in `targets`"), "{e}");
run(&mut s, "solid.emboss", json!({"sketch": "Logo", "depth": 1, "face": [20, 15, 10]}));
}
fn cylinder_badge() -> Session {
let mut s = Session::default();
run(&mut s, "parameters.add", json!({"name":"badge_depth","expression":"1 mm"}));
@@ -765,6 +782,60 @@ fn a_tapered_text_joins_a_block_on_its_face_or_hanging_over_its_edge() {
}
}
/// A tapered foot extruded 3 mm down from a part's bottom face and joined (#1534). Run on into
/// the part with their slope, sides that narrow the foot away from the face widened it past the
/// face: a box got a lip round its walls (0.16 mm wide, and nothing said), a cylinder's join found
/// no result, and sides that widen the foot met the face's edge there. A foot on the whole face is
/// sewn on along it; one drawn just inside the face's edge starts on it. Either way: the part plus
/// the frustum, and nothing beside the part's walls.
#[test]
fn a_tapered_foot_under_a_part_joins_as_drawn() {
// (round, the foot's half width: the whole face, or just inside its edge)
for (round, half) in [(false, 15.0), (true, 15.0), (false, 14.9)] {
for taper in [-20.0f64, 20.0] {
let t = taper.to_radians().tan();
let mut s = Session::default();
run(&mut s, "sketch.create", json!({"plane":"XY"}));
if round {
run(&mut s, "sketch.circle.center", json!({"center":[0,0],"radius":15}));
} else {
run(&mut s, "sketch.rectangle.two_point", json!({"p0":[-15,-15],"p1":[15,15]}));
}
run(&mut s, "sketch.finish", json!({}));
run(&mut s, "solid.extrude", json!({"distance":10,"body_name":"B"}));
let taper_deg = format!("{taper} deg");
if half < 15.0 {
run(&mut s, "sketch.create", json!({"plane":"XY"}));
run(&mut s, "sketch.rectangle.two_point", json!({"p0":[-half,-half],"p1":[half,half]}));
run(&mut s, "sketch.finish", json!({}));
run(&mut s, "solid.extrude", json!({"distance":3,"direction":"negative","operation":"join","taper":taper_deg}));
} else {
let foot = json!({"face":[5,1,0],"face_body":"B","distance":3,"direction":"positive","operation":"join","taper":taper_deg});
run(&mut s, "solid.extrude", foot);
}
let (part, frustum) = if round {
let r = 15.0 + 3.0 * t;
(std::f64::consts::PI * 225.0 * 10.0, std::f64::consts::PI * (225.0 + 15.0 * r + r * r))
} else {
let side = 2.0 * half + 6.0 * t;
(9000.0, 4.0 * half * half + 2.0 * half * side + side * side)
};
let v = volume(&mut s);
// The cylinder is measured on its mesh; a foot that starts on the face stands straight
// for a hair first.
let tol = if round || half < 15.0 { 2e-4 } else { 1e-9 } * (part + frustum);
assert!((v - (part + frustum)).abs() < tol, "round {round}, half {half}, taper {taper}: {v} for {}", part + frustum);
assert_eq!(s.world_state().bodies.len(), 1);
let state = s.model.state();
let mesh = state.body("B").unwrap().mesh();
// Beside the part, above the foot's start: nothing.
let out = |x: f64, y: f64| if round { x.hypot(y) } else { x.abs().max(y.abs()) } > 15.0 + 1e-6;
let beside = mesh.positions.iter().filter(|p| p.z > 1e-6 && out(p.x, p.y)).count();
assert_eq!(beside, 0, "round {round}, half {half}, taper {taper}: {:?}", mesh.bounds());
}
}
}
/// A rounded part as drawn in the app: a rectangle and a quarter circle tangent to its top
/// line, extruded together. The arc (about (62.17, -21), radius 21) ends square at the front
/// face and in a knife-edge tip where it runs into the back face.
+30 -5
View File
@@ -278,6 +278,19 @@ fn default_name_for(name: &str, path: &str) -> Option<String> {
(!stem.is_empty()).then_some(stem)
}
/// The name a design takes when saved to `path`, if it changes: its file's name while it has
/// none of its own ([`default_name_for`]), or while it still has the name it took from the file
/// it was saved as before, so Save As under another name renames it too (#1710). A name the
/// user chose is kept.
fn saved_name(name: &str, old_path: Option<&str>, path: &str) -> Option<String> {
if let Some(stem) = default_name_for(name, path) {
return Some(stem);
}
let stem = |p: &str| std::path::Path::new(p).file_stem().map(|x| x.to_string_lossy().trim().to_string()).filter(|x| !x.is_empty());
let (old, new) = (stem(old_path?)?, stem(path)?);
(name.trim() == old && new != old).then_some(new)
}
/// Rename the design, and the undo and redo states that still carry the old name, so undo
/// does not bring the default name back and leave the design looking changed.
fn rename_design(s: &mut Session, from: &str, to: &str) {
@@ -291,8 +304,9 @@ fn rename_design(s: &mut Session, from: &str, to: &str) {
fn write(s: &mut Session, path: &str, format: &str, compression: &str, preview: bool, cache: bool) -> Result<Value> {
solidcraft_io::vfs::check(path).map_err(|e| EngineError::Other(e.to_string()))?;
// Saving an unnamed design names it after its file (not an undoable edit).
let renamed = default_name_for(&s.doc.name, path).map(|stem| (s.doc.name.clone(), stem));
// Saving an unnamed design, or one named after the file it was saved as, names it after its
// file (not an undoable edit).
let renamed = saved_name(&s.doc.name, s.path.as_deref(), path).map(|stem| (s.doc.name.clone(), stem));
if let Some((from, to)) = &renamed {
rename_design(s, from, to);
}
@@ -883,9 +897,20 @@ mod tests {
// Undoing the box does not bring the old name back.
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(s.doc.name, "bracket");
// Saving under another file keeps the name it now has.
s.execute("file.save_as", &json!({"path":dir.join("copy.solidcraft")})).unwrap();
assert_eq!(s.doc.name, "bracket");
// Saved under another file, a name taken from the old file follows it (#1710), in the
// file too, so reopening shows it.
let copy = dir.join("copy.solidcraft");
s.execute("file.save_as", &json!({"path":copy})).unwrap();
assert_eq!(s.doc.name, "copy");
let mut reopened = Session::default();
reopened.execute("doc.open", &json!({"path":copy})).unwrap();
assert_eq!(reopened.doc.name, "copy");
// Saving again to the same file changes nothing.
s.execute("file.save", &json!({})).unwrap();
assert_eq!(s.doc.name, "copy");
// As in the issue: a design opened from its file, then saved as another.
reopened.execute("file.save_as", &json!({"path":dir.join("third.solidcraft")})).unwrap();
assert_eq!(reopened.doc.name, "third");
// A failed save leaves the name alone.
let mut failed = Session::default();
assert!(failed.execute("file.save_as", &json!({"path":dir.join("missing-dir").join("plate.solidcraft")})).is_err());
+169 -16
View File
@@ -7,6 +7,7 @@ use std::collections::{BTreeMap, BTreeSet};
use serde_json::{Value, json};
use solidcraft_doc::expr::Kind;
use solidcraft_doc::joints::cam::{self, Cam, CamProfile, Follower};
use solidcraft_doc::joints::{self, Coupling, Joint, JointKind, JointOrigin, MotionLink, NamedOrigin, Size, Snap};
use solidcraft_geom::{Aabb3, Vec3};
@@ -60,6 +61,9 @@ pub static COMMANDS: &[CommandSpec] = &[
travel per turn (mm or an expression); reverse?: bool (a left-hand thread); link?: index (replace that motion link) → link, \
ratio (mm per degree, or degrees per mm); b keeps where it is",
),
CommandSpec::new("joint.cam", "Cam", cam_cmd).at("SOLID", "ASSEMBLE").icon("cam").params(
"a: the cam's joint (revolute); b: the follower's joint, a slider (a translating follower) or a revolute (an oscillating one), b driven by a; profile: {sketch: id|name, index?: the profile (default: the largest)} | {edges: [[x,y,z]…] (points on edges of the cam's bodies forming one closed loop, world), occurrence?}: the cam's outline, in a plane square to its axis, read again whenever the design changes; follower?: knife|roller|flat (default knife; flat: a face square to a slider's line); radius?: the roller's radius (mm, an expression or {circle: [x,y,z], occurrence?}: the roller's round face, which is its tip too); tip?: a joint origin where the follower touches: its knife's point or its roller's centre, such as {circle: [x,y,z]} on the roller (needed for an oscillating follower; a translating one's line runs through it, by default along its slider's axis); flip?: bool (ride the cam from the other side than the one the follower is on now); link?: index (replace that motion link) → link, lift: {min, max, rise, unit} (b's travel over a turn of the cam), reverse (the side it rides from), follower_offset (mm: how far a translating follower's line passes from the cam's axis); b keeps where it is",
),
CommandSpec::new("joint.limits", "Joint Limits", limits).params("joint; index?: value index (default 0); min?, max? (omit both to clear)"),
CommandSpec::new("joint.edit", "Edit Joint", edit).params("joint; type?, flip?, offset?, angle?, suppressed?, name?"),
CommandSpec::new("joint.delete", "Delete Joint", delete).params("joint: id|name (or origin: name, link: index)"),
@@ -80,29 +84,30 @@ pub fn resolve(s: &mut Session) -> joints::Solution {
resolve_holding(s, &BTreeMap::new())
}
/// Work out the ratios of the coupled motion links again (a radius or a parameter may have
/// changed). A coupling that can't be worked out (its face gone) keeps its last ratio;
/// `joint.list` says why.
/// Work out the ratios (and cam tables) of the coupled motion links again (a radius, a parameter
/// or a cam's profile may have changed). A coupling that can't be worked out (its face gone)
/// keeps its last ratio and table; `joint.list` says why.
fn recouple(s: &mut Session) {
if s.doc.assembly.links.iter().all(|l| l.coupling.is_none()) {
return;
}
let st = s.model.state();
let changed: Vec<(usize, f64)> = s
let changed: Vec<(usize, (f64, Vec<f64>))> = s
.doc
.assembly
.links
.iter()
.enumerate()
.filter_map(|(i, l)| joints::coupling_ratio(&s.doc, &st, l)?.ok().filter(|r| *r != l.ratio).map(|r| (i, r)))
.filter_map(|(i, l)| joints::coupling_values(&s.doc, &st, l)?.ok().filter(|(r, t)| *r != l.ratio || *t != l.lift).map(|v| (i, v)))
.collect();
if changed.is_empty() {
return;
}
let doc = s.doc_mut();
for (i, r) in changed {
for (i, (r, t)) in changed {
if let Some(l) = doc.assembly.links.get_mut(i) {
l.ratio = r;
l.lift = t;
}
}
}
@@ -305,8 +310,29 @@ fn origin_param(s: &Session, v: Option<&Value>, cmd: &str) -> Result<JointOrigin
}
};
let o = JointOrigin { occurrence, snap };
joints::resolve_origin(&s.doc, &s.model.state(), &o).map_err(|e| bad(cmd, e.to_string()))?;
Ok(o)
match joints::resolve_origin(&s.doc, &s.model.state(), &o) {
Ok(_) => Ok(o),
// A circle given by its centre, where no face lies (#393).
Err(e) => match (what == "circle").then(|| circle_centre(s, occurrence, local(world))).flatten() {
Some(snap) => Ok(JointOrigin { occurrence, snap }),
None => Err(bad(cmd, e.to_string())),
},
}
}
/// The round end of a cylindrical face of the occurrence's bodies centred at `pick`: a point on
/// its axis there, pointing out of that end (as picking its circular edge gives).
fn circle_centre(s: &Session, occurrence: u64, pick: Vec3) -> Option<Snap> {
let component = if occurrence == 0 { 0 } else { s.doc.occurrences.iter().find(|o| o.id == occurrence)?.component };
let st = s.model.state();
let c = st
.bodies
.iter()
.filter(|b| s.doc.model_body_component(b) == component)
.find_map(|b| solidcraft_doc::kernel::cylinder_end_at(&b.body, pick))?;
let along = (pick - c.axis_point).dot(c.axis);
let (at, dir) = if (along - c.start).abs() <= (c.end - along).abs() { (c.start, -1.0) } else { (c.end, 1.0) };
Some(Snap::Point { point: c.axis_point + c.axis * at, z: Some(c.axis * dir) })
}
pub(crate) fn joint_id(s: &Session, v: Option<&Value>, cmd: &str) -> Result<u64> {
@@ -688,7 +714,7 @@ fn motion_link(s: &mut Session, p: &Value) -> Result<Value> {
None => 0.0,
};
let ratio = ratio * ratio_scale(s, a, ia, b, ib);
s.doc_mut().assembly.links.push(MotionLink { a, ia, b, ib, ratio, offset, coupling: None });
s.doc_mut().assembly.links.push(MotionLink { a, ia, b, ib, ratio, offset, coupling: None, lift: Vec::new() });
let sol = resolve(s);
Ok(sol_json(&sol, p))
}
@@ -699,7 +725,10 @@ fn size_param(s: &Session, p: &Value, key: &str, cmd: &str) -> Result<Size> {
match p.get(key) {
Some(Value::Number(n)) => n.as_f64().map(Size::Length).ok_or_else(|| bad(cmd, format!("`{key}` must be a finite length"))),
Some(Value::String(t)) if t.len() <= 1000 => Ok(Size::Expr(t.trim().to_string())),
Some(o @ Value::Object(m)) if m.contains_key("circle") => Ok(Size::Circle(origin_param(s, Some(o), cmd)?)),
Some(o @ Value::Object(m)) if m.contains_key("circle") => match origin_param(s, Some(o), cmd)? {
o @ JointOrigin { snap: Snap::CircleCenter { .. }, .. } => Ok(Size::Circle(o)),
_ => Err(bad(cmd, format!("`{key}`: give a point on the round face, not its centre"))),
},
_ => Err(bad(cmd, format!("`{key}` must be a length (mm or an expression) or a round face ({{circle: [x, y, z]}})"))),
}
}
@@ -742,7 +771,7 @@ fn gear(s: &mut Session, p: &Value) -> Result<Value> {
internal: bool_(p, "internal").unwrap_or(false),
reverse: reverse(p),
};
couple(s, p, cmd, MotionLink { a, ia, b, ib, ratio: 1.0, offset: 0.0, coupling: Some(c) })
couple(s, p, cmd, MotionLink { a, ia, b, ib, ratio: 1.0, offset: 0.0, coupling: Some(c), lift: Vec::new() })
}
fn rack_pinion(s: &mut Session, p: &Value) -> Result<Value> {
@@ -750,7 +779,7 @@ fn rack_pinion(s: &mut Session, p: &Value) -> Result<Value> {
let (a, b) = joint_pair(s, p, cmd)?;
let (ia, ib) = turn_and_travel(s, a, b, cmd)?;
let c = Coupling::RackPinion { radius: size_param(s, p, "radius", cmd)?, reverse: reverse(p) };
couple(s, p, cmd, MotionLink { a, ia, b, ib, ratio: 1.0, offset: 0.0, coupling: Some(c) })
couple(s, p, cmd, MotionLink { a, ia, b, ib, ratio: 1.0, offset: 0.0, coupling: Some(c), lift: Vec::new() })
}
fn screw(s: &mut Session, p: &Value) -> Result<Value> {
@@ -770,7 +799,120 @@ fn screw(s: &mut Session, p: &Value) -> Result<Value> {
}
};
let c = Coupling::Screw { pitch: size_param(s, p, "pitch", cmd)?, reverse: reverse(p) };
couple(s, p, cmd, MotionLink { a, ia, b, ib, ratio: 1.0, offset: 0.0, coupling: Some(c) })
couple(s, p, cmd, MotionLink { a, ia, b, ib, ratio: 1.0, offset: 0.0, coupling: Some(c), lift: Vec::new() })
}
fn cam_cmd(s: &mut Session, p: &Value) -> Result<Value> {
let cmd = "joint.cam";
let (a, b) = joint_pair(s, p, cmd)?;
let kind = |id: u64| s.doc.assembly.joints.iter().find(|j| j.id == id).map(|j| j.kind);
if kind(a) != Some(JointKind::Revolute) {
return Err(bad(cmd, "the cam (a) turns on a revolute joint"));
}
let oscillating = match kind(b) {
Some(JointKind::Slider) => false,
Some(JointKind::Revolute) => true,
_ => return Err(bad(cmd, "the follower (b) is a slider or a revolute joint")),
};
let follower = match str_(p, "follower").unwrap_or("knife") {
"knife" => Follower::Knife,
"roller" => Follower::Roller { radius: size_param(s, p, "radius", cmd)? },
"flat" => Follower::Flat,
_ => return Err(bad(cmd, "`follower` is knife, roller or flat")),
};
if oscillating && p.get("tip").is_none() && !matches!(follower, Follower::Roller { radius: Size::Circle(_) }) {
return Err(bad(cmd, "an oscillating follower needs `tip`: its knife's point or its roller's centre ({circle: [x, y, z]} on the roller)"));
}
let tip = match p.get("tip") {
Some(v) => Some(origin_param(s, Some(v), cmd)?),
None => None,
};
let mut c = Cam { profile: cam_profile(s, p, cmd)?, follower, tip, reverse: false };
let probe = MotionLink { a, ia: 0, b, ib: 0, ratio: 1.0, offset: 0.0, coupling: None, lift: Vec::new() };
let st = s.model.state();
c.reverse = cam::default_reverse(&s.doc, &st, &probe, &c).map_err(|e| bad(cmd, e.to_string()))? != bool_(p, "flip").unwrap_or(false);
let offset = cam::follower_offset(&s.doc, &st, &probe, &c).map_err(|e| bad(cmd, e.to_string()))?;
let reverse = c.reverse;
let mut out = couple(s, p, cmd, MotionLink { coupling: Some(Coupling::Cam(c)), ..probe })?;
let index = out["link"].as_u64().and_then(|i| usize::try_from(i).ok()).unwrap_or(usize::MAX);
if let (Some(o), Some(l)) = (out.as_object_mut(), s.doc.assembly.links.get(index)) {
o.remove("ratio");
o.insert("lift".into(), lift_json(l, oscillating));
o.insert("reverse".into(), json!(reverse));
if !oscillating {
o.insert("follower_offset".into(), json!(offset));
}
}
Ok(out)
}
/// A cam's follower travel over a turn of the cam: b's lowest and highest values and their
/// difference, in degrees (`angle`) or mm.
fn lift_json(l: &MotionLink, angle: bool) -> Value {
// A table that is not whole (a hand-edited file) moves nothing, and says so.
if l.lift.len() != cam::CAM_SAMPLES {
return Value::Null;
}
let unit = |v: f64| if angle { v.to_degrees() } else { v };
let (lo, hi) = l.lift.iter().fold((f64::INFINITY, f64::NEG_INFINITY), |(lo, hi), v| (lo.min(*v), hi.max(*v)));
let (lo, hi) = (unit(lo + l.offset), unit(hi + l.offset));
json!({"min": lo, "max": hi, "rise": hi - lo, "unit": if angle { "deg" } else { "mm" }})
}
/// A cam's profile: a sketch's closed profile (kept by its outer loop's curve ids, so the sketch's
/// other profiles may change), or picked edges of the cam's bodies (kept in the component's
/// coordinates with the edges' names).
fn cam_profile(s: &Session, p: &Value, cmd: &str) -> Result<CamProfile> {
let v = p.get("profile").ok_or_else(|| bad(cmd, "`profile` is required: {sketch: id|name} or {edges: [[x, y, z], …]}"))?;
if let Some(sk) = v.get("sketch") {
let sketch = super::features::sketch_id(s, Some(sk), cmd, "profile.sketch")?;
let st = s.model.state();
let solved =
st.sketches.iter().find(|x| x.feature == sketch).ok_or_else(|| bad(cmd, "that sketch is not evaluated (it is after the marker?)"))?;
let picked = match v.get("index") {
None => cam::sketch_profile(solved, &[]),
Some(i) => i.as_u64().and_then(|i| usize::try_from(i).ok()).and_then(|i| solved.profiles.get(i)),
};
let profile = picked.ok_or_else(|| bad(cmd, "the sketch has no such closed profile (an open curve makes none)"))?;
return Ok(CamProfile::Sketch { sketch, curves: profile.outer_curves.clone() });
}
let Some(Value::Array(pts)) = v.get("edges") else {
return Err(bad(cmd, "`profile` is {sketch: id|name} or {edges: [[x, y, z], …]}"));
};
if pts.is_empty() || pts.len() > cam::MAX_PROFILE_EDGES {
return Err(bad(cmd, format!("pick 1 to {} edges", cam::MAX_PROFILE_EDGES)));
}
let world: Vec<Vec3> = pts.iter().map(vec3).collect::<Option<_>>().ok_or_else(|| bad(cmd, "`edges` are finite [x, y, z] points"))?;
let occurrence = match v.get("occurrence") {
Some(o) => occurrence_id(s, Some(o), cmd)?,
None => world.first().and_then(|w| occurrence_at(s, *w)).ok_or_else(|| bad(cmd, "no body there"))?,
};
let t = if occurrence == 0 { solidcraft_doc::IDENTITY } else { joints::occurrence_world(&s.doc, occurrence) };
let inv = solidcraft_doc::mat_inverse(&t).ok_or_else(|| bad(cmd, "occurrence transform"))?;
let picks: Vec<Vec3> = world.iter().map(|w| solidcraft_doc::apply_point(&inv, *w)).collect();
let comp = s.doc.occurrences.iter().find(|o| o.id == occurrence).map(|o| o.component).unwrap_or(0);
let st = s.model.state();
let bodies: Vec<&solidcraft_doc::ModelBody> = st.bodies.iter().filter(|b| s.doc.model_body_component(b) == comp).collect();
// Each pick's edge name on the body whose edges pass nearest it.
let names = picks
.iter()
.map(|q| {
let near = |b: &&solidcraft_doc::ModelBody| {
b.mesh()
.edges
.iter()
.flat_map(|e| e.windows(2))
.filter_map(|w| Some(q.dist_to_segment(*w.first()?, *w.get(1)?)))
.fold(f64::MAX, f64::min)
};
bodies
.iter()
.min_by(|x, y| near(x).total_cmp(&near(y)))
.and_then(|b| solidcraft_doc::naming::edge_names_at(b, &[*q]).into_iter().next())
.unwrap_or_default()
})
.collect();
Ok(CamProfile::Edges { occurrence, picks, names })
}
/// Add a coupling's motion link, or put it in place of link `link`: its ratio worked out from its
@@ -802,14 +944,18 @@ fn couple(s: &mut Session, p: &Value, cmd: &str, mut l: MotionLink) -> Result<Va
None => break,
}
}
l.ratio = joints::coupling_ratio(&s.doc, &s.model.state(), &l).unwrap_or(Ok(l.ratio)).map_err(|e| bad(cmd, e.to_string()))?;
(l.ratio, l.lift) =
joints::coupling_values(&s.doc, &s.model.state(), &l).unwrap_or(Ok((l.ratio, Vec::new()))).map_err(|e| bad(cmd, e.to_string()))?;
let vals = joints::joint_values(&s.doc.assembly);
let value = |id: u64, i: usize| vals.get(&id).and_then(|q| q.get(i)).copied().unwrap_or(0.0);
// A link put in place of another keeps its offset, as a radius edited in the design does.
l.offset = match replace.and_then(|i| links.get(i)) {
Some(old) => old.offset,
None => value(l.b, l.ib) - l.ratio * value(l.a, l.ia),
None => value(l.b, l.ib) - MotionLink { offset: 0.0, ..l.clone() }.follow(value(l.a, l.ia)),
};
if !l.offset.is_finite() {
return Err(bad(cmd, "the coupling gives the driven joint no value where it is"));
}
let shown = l.ratio / ratio_scale(s, l.a, l.ia, l.b, l.ib);
let doc = s.doc_mut();
let index = match replace {
@@ -970,10 +1116,17 @@ fn list(s: &mut Session, p: &Value) -> Result<Value> {
json!({"a": l.a, "ia": l.ia, "b": l.b, "ib": l.ib, "ratio": ratio, "offset": offset, "unit": if angle { "deg" } else { "mm" }});
if let Some(c) = &l.coupling {
v["coupling"] = json!(c);
if let Some(Err(e)) = joints::coupling_ratio(&s.doc, &st, l) {
if let Some(Err(e)) = joints::coupling_values(&s.doc, &st, l) {
v["error"] = json!(e.to_string());
}
}
// A cam's follower follows its table, not a ratio: its travel instead.
if matches!(l.coupling, Some(Coupling::Cam(_)))
&& let Some(o) = v.as_object_mut()
{
o.remove("ratio");
o.insert("lift".into(), lift_json(l, angle));
}
v
})
.collect();
+435
View File
@@ -0,0 +1,435 @@
//! Cams: a revolute joint drives a follower that rides the cam's profile. Expected values are
//! analytic: an eccentric circle of radius R whose centre is e from its axis puts a knife-edge
//! follower on a line h from the axis at e·cos θ + √(R² − (h − e·sin θ)²), a roller of radius r
//! where a knife on the circle of radius R + r would be, a flat face at e·cos θ + R; an
//! oscillating follower's roller sits where its arm's circle meets the circle of radius R + r.
use super::*;
use solidcraft_doc::joints::Coupling;
use solidcraft_doc::joints::cam::CamProfile;
/// The cam's eccentricity and radius (mm).
const E: f64 = 10.0;
const R: f64 = 30.0;
fn joint_id(s: &Session, name: &str) -> u64 {
s.doc.assembly.joints.iter().find(|j| j.name == name).map(|j| j.id).unwrap_or(0)
}
/// A joint's value as `joint.list` gives it (degrees or mm).
fn shown(s: &mut Session, joint: &str) -> f64 {
let l = run(s, "joint.list", json!({"quiet": true}));
let j = l["joints"].as_array().into_iter().flatten().find(|j| j["name"] == joint).cloned().unwrap_or_default();
j["values"][0]["value"].as_f64().unwrap_or(f64::NAN)
}
/// Where a knife edge on a line `h` from the axis stands on the circle of radius `r` about the
/// cam's centre turned by `deg`.
fn knife(deg: f64, h: f64, r: f64) -> f64 {
let t = deg.to_radians();
E * t.cos() + (r * r - (h - E * t.sin()).powi(2)).sqrt()
}
/// A grounded base, and a cam: a disc of radius `rc` (a parameter, 30 mm) about (10, 0), 5 mm thick,
/// drawn in sketch `CamSketch` of its own component, on a revolute joint `Cam` about Z through the
/// origin (the cam is its b side).
fn cam_on_base() -> Session {
let mut s = Session::default();
run(&mut s, "parameters.add", json!({"name": "rc", "expression": "30 mm"}));
run(&mut s, "parameters.add", json!({"name": "th", "expression": "5 mm"}));
part(&mut s, "Base", [-90.0, -90.0, -20.0]);
let g = occ(&s, "Base");
run(&mut s, "occurrence.ground", json!({"occurrence": g, "grounded": true}));
run(&mut s, "component.activate", json!({"component": "root"}));
run(&mut s, "component.create", json!({"name": "Cam"}));
run(&mut s, "sketch.create", json!({"plane": "XY", "name": "CamSketch"}));
run(&mut s, "sketch.circle.center", json!({"center": [E, 0], "radius": R, "id": "c1"}));
run(&mut s, "sketch.dimension", json!({"entities": ["c1"], "type": "radius", "value": "rc"}));
run(&mut s, "sketch.finish", json!({}));
run(&mut s, "solid.extrude", json!({"distance": "th"}));
pin(&mut s, "revolute", "Cam", "Base", "Cam", Vec3::ZERO, Vec3::Z);
s
}
/// A tappet (a 20 mm bar, 4 wide) sliding along +X on the line y = `h`, its end at x = `tip`, on a
/// slider `Tappet`.
fn tappet(s: &mut Session, h: f64, tip: f64) {
run(s, "component.activate", json!({"component": "root"}));
run(s, "component.create", json!({"name": "Tappet"}));
run(s, "solid.box", json!({"length": 20, "width": 4, "height": 5, "corner": [tip, h - 2.0, 0]}));
pin(s, "slider", "Tappet", "Base", "Tappet", Vec3::new(0.0, h, 2.5), Vec3::X);
}
fn close(got: f64, want: f64, tol: f64) -> bool {
(got - want).abs() < tol
}
/// A knife-edge tappet on the eccentric circle, its line through the axis and 6 mm past it, rises
/// and falls as e·cos θ + √(R² − (h − e·sin θ)²); the tappet's body goes with it.
#[test]
fn a_knife_edge_tappet_rides_an_eccentric_circle() {
for h in [0.0, 6.0] {
let mut s = cam_on_base();
let tip = knife(0.0, h, R);
tappet(&mut s, h, tip);
let r = run(&mut s, "joint.cam", json!({"a": "Cam", "b": "Tappet", "profile": {"sketch": "CamSketch"}}));
assert_eq!((r["link"].clone(), r["reverse"].clone()), (json!(0), json!(false)), "{r}");
assert!(close(r["follower_offset"].as_f64().unwrap_or(f64::NAN), h, 1e-9), "{r}");
// It stays where it is, and its travel over a turn is the cam's.
assert!(close(shown(&mut s, "Tappet"), 0.0, 1e-9), "{r}");
let over_a_turn: Vec<f64> = (0..3600).map(|k| knife(f64::from(k) / 10.0, h, R)).collect();
let rise = over_a_turn.iter().fold(f64::MIN, |a, b| a.max(*b)) - over_a_turn.iter().fold(f64::MAX, |a, b| a.min(*b));
assert!(close(r["lift"]["rise"].as_f64().unwrap_or(f64::NAN), rise, 2e-3), "{r} vs {rise}");
for deg in [30.0f64, 90.0, 135.0, 200.0, 300.0, -45.0, 400.0] {
let d = run(&mut s, "joint.drive", json!({"joint": "Cam", "value": deg}));
assert_eq!(d["conflicts"].as_array().map(Vec::len), Some(0), "{d}");
let want = knife(deg, h, R) - tip;
assert!(close(shown(&mut s, "Tappet"), want, 1e-3), "h {h} θ {deg}: {} vs {want}", shown(&mut s, "Tappet"));
let end = place(&s, "Tappet", Vec3::new(tip, h, 2.5));
assert!(close(end.x, tip + want, 1e-3) && close(end.y, h, 1e-9), "{end:?}");
}
}
}
/// The follower's line is through its tip, wherever its slider's origin is across the line; a
/// guide of its own (grounded, the slider's b side) makes the tappet the slider's a side, and it
/// rides the same way.
#[test]
fn a_tappet_on_a_guide_of_its_own_rides_its_tip_s_line() {
let h = 6.0;
let tip = knife(0.0, h, R);
let mut s = cam_on_base();
part(&mut s, "Guide", [70.0, 20.0, 0.0]);
let g = occ(&s, "Guide");
run(&mut s, "occurrence.ground", json!({"occurrence": g, "grounded": true}));
run(&mut s, "component.activate", json!({"component": "root"}));
run(&mut s, "component.create", json!({"name": "Tappet"}));
run(&mut s, "solid.box", json!({"length": 20, "width": 4, "height": 5, "corner": [tip, h - 2.0, 0]}));
// The slider's origins 9 mm across from the tappet's line, a the tappet, b the guide.
pin(&mut s, "slider", "Tappet", "Tappet", "Guide", Vec3::new(0.0, h + 9.0, 2.5), Vec3::X);
let r = run(
&mut s,
"joint.cam",
json!({"a": "Cam", "b": "Tappet", "profile": {"sketch": "CamSketch"}, "tip": {"occurrence": "Tappet", "point": [tip, h, 2.5]}}),
);
assert!(close(r["follower_offset"].as_f64().unwrap_or(f64::NAN), h, 1e-9), "{r}");
for deg in [70.0f64, 160.0, 290.0] {
run(&mut s, "joint.drive", json!({"joint": "Cam", "value": deg}));
let end = place(&s, "Tappet", Vec3::new(tip, h, 2.5));
assert!(close(end.x, knife(deg, h, R), 1e-3), "θ {deg}: {end:?} vs {}", knife(deg, h, R));
}
}
/// A roller of radius 5 rides the circle of radius R + 5; a flat face e·cos θ + R, and when the
/// cam's radius parameter grows by 2 the flat face stands 2 further out at every angle.
#[test]
fn rollers_and_flat_faces_ride_their_offset_circles() {
let mut s = cam_on_base();
let tip = knife(0.0, 0.0, R + 5.0);
tappet(&mut s, 0.0, tip);
run(&mut s, "joint.cam", json!({"a": "Cam", "b": "Tappet", "profile": {"sketch": "CamSketch"}, "follower": "roller", "radius": "5 mm"}));
for deg in [60.0f64, 150.0, 250.0] {
run(&mut s, "joint.drive", json!({"joint": "Cam", "value": deg}));
let want = knife(deg, 0.0, R + 5.0) - tip;
assert!(close(shown(&mut s, "Tappet"), want, 1e-3), "roller θ {deg}: {} vs {want}", shown(&mut s, "Tappet"));
}
let mut s = cam_on_base();
tappet(&mut s, 3.0, E + R);
run(&mut s, "joint.cam", json!({"a": "Cam", "b": "Tappet", "profile": {"sketch": "CamSketch"}, "follower": "flat"}));
for deg in [60.0f64, 150.0, 250.0] {
run(&mut s, "joint.drive", json!({"joint": "Cam", "value": deg}));
let want = E * deg.to_radians().cos() - E;
assert!(close(shown(&mut s, "Tappet"), want, 1e-3), "flat θ {deg}: {} vs {want}", shown(&mut s, "Tappet"));
}
// Editing the profile: the table is worked out again.
run(&mut s, "parameters.change", json!({"name": "rc", "expression": "32 mm"}));
let want = E * 250f64.to_radians().cos() - E + 2.0;
assert!(close(shown(&mut s, "Tappet"), want, 1e-3), "after the edit: {} vs {want}", shown(&mut s, "Tappet"));
}
/// The cam's top edge picked on its body gives the table its sketch gives, and follows the
/// design the same way.
#[test]
fn picked_edges_give_the_sketch_s_table() {
let table = |profile: Value| {
let mut s = cam_on_base();
tappet(&mut s, 0.0, E + R);
run(&mut s, "joint.cam", json!({"a": "Cam", "b": "Tappet", "profile": profile}));
s.doc.assembly.links.first().map(|l| (l.lift.clone(), l.offset)).unwrap_or_default()
};
let (sketch, a) = table(json!({"sketch": "CamSketch"}));
let (edges, b) = table(json!({"edges": [[E + R, 0, 5]]}));
assert_eq!((sketch.len(), edges.len()), (360, 360));
assert!(sketch.iter().zip(&edges).all(|(x, y)| close(*x, *y, 1e-3)) && close(a, b, 1e-3));
// A second disc of the cam's component touching it in the same plane is not part of its loop.
let mut s = cam_on_base();
run(&mut s, "component.activate", json!({"component": "Cam"}));
run(&mut s, "solid.cylinder", json!({"base": [E + R + 20.0, 0, 0], "axis": [0, 0, 1], "radius": 20, "height": 5}));
tappet(&mut s, 0.0, E + R);
run(&mut s, "joint.cam", json!({"a": "Cam", "b": "Tappet", "profile": {"edges": [[E - R, 0, 5]]}}));
let touching = s.doc.assembly.links.first().map(|l| l.lift.clone()).unwrap_or_default();
assert!(touching.len() == 360 && touching.iter().zip(&sketch).all(|(x, y)| close(*x, *y, 1e-3)), "{touching:?}");
let mut s = cam_on_base();
tappet(&mut s, 0.0, E + R);
run(&mut s, "joint.cam", json!({"a": "Cam", "b": "Tappet", "profile": {"edges": [[E + R, 0, 5]]}}));
assert!(matches!(
s.doc.assembly.links.first().and_then(|l| l.coupling.clone()),
Some(Coupling::Cam(c)) if matches!(&c.profile, CamProfile::Edges { names, .. } if names.first().is_some_and(|n| !n.is_empty()))
));
run(&mut s, "parameters.change", json!({"name": "rc", "expression": "32 mm"}));
// A thicker cam: the picked edge is found at its new height, and its loop with it.
run(&mut s, "parameters.change", json!({"name": "th", "expression": "7 mm"}));
let l = run(&mut s, "joint.list", json!({"quiet": true}));
assert!(l["links"][0].get("error").is_none(), "{l}");
run(&mut s, "joint.drive", json!({"joint": "Cam", "value": 90}));
let want = knife(90.0, 0.0, 32.0) - (E + R);
assert!(close(shown(&mut s, "Tappet"), want, 1e-3), "{} vs {want}", shown(&mut s, "Tappet"));
}
/// An arm of 50 about (−50, 40) with a roller of 5: its roller's centre is where the arm's circle
/// meets the circle of radius R + 5 about the cam's centre, the meeting it turns into first from
/// pointing away from the cam's axis.
#[test]
fn an_oscillating_roller_follower_swings_to_the_offset_circle() {
let (pivot, arm, roller) = (Vec3::new(-50.0, 40.0, 2.5), 50.0, 5.0);
let away = pivot.y.atan2(pivot.x);
let wrap = |a: f64| (a + std::f64::consts::PI).rem_euclid(std::f64::consts::TAU) - std::f64::consts::PI;
let angle = |p: Vec3| (p.y - pivot.y).atan2(p.x - pivot.x);
// Where the roller's centre is at cam angle `deg`, turning the way `turn` says.
let centre = |deg: f64, turn: f64| {
let c = Vec3::new(E * deg.to_radians().cos(), E * deg.to_radians().sin(), 2.5);
let [p, q] = meet(pivot, arm, c, R + roller);
let swept = |x: Vec3| (turn * (angle(x) - away)).rem_euclid(std::f64::consts::TAU);
if swept(p) < swept(q) { p } else { q }
};
let [p, q] = meet(pivot, arm, Vec3::new(E, 0.0, 2.5), R + roller);
let start = if wrap(angle(p) - away).abs() < wrap(angle(q) - away).abs() { p } else { q };
let turn = wrap(angle(start) - away).signum();
let mut s = cam_on_base();
run(&mut s, "component.activate", json!({"component": "root"}));
run(&mut s, "component.create", json!({"name": "Arm"}));
run(&mut s, "solid.box", json!({"length": 4, "width": 4, "height": 5, "corner": [start.x - 2.0, start.y - 2.0, 0]}));
pin(&mut s, "revolute", "Arm", "Base", "Arm", pivot, Vec3::Z);
// An oscillating follower needs its tip.
assert!(s.execute("joint.cam", &json!({"a": "Cam", "b": "Arm", "profile": {"sketch": "CamSketch"}, "follower": "roller", "radius": 5})).is_err());
let r = run(
&mut s,
"joint.cam",
json!({"a": "Cam", "b": "Arm", "profile": {"sketch": "CamSketch"}, "follower": "roller", "radius": 5,
"tip": {"occurrence": "Arm", "point": [start.x, start.y, 2.5]}}),
);
assert_eq!((r["reverse"].clone(), r["lift"]["unit"].clone()), (json!(turn < 0.0), json!("deg")), "{r}");
for deg in [40.0f64, 120.0, 210.0, 330.0] {
run(&mut s, "joint.drive", json!({"joint": "Cam", "value": deg}));
let want = wrap(angle(centre(deg, turn)) - angle(start)).to_degrees();
assert!(close(shown(&mut s, "Arm"), want, 1e-3), "θ {deg}: {} vs {want}", shown(&mut s, "Arm"));
let at = place(&s, "Arm", start);
assert!(at.dist(centre(deg, turn)) < 1e-3, "θ {deg}: {at:?}");
}
// The roller's round face picked on its arm is where it touches, and its radius: the same table.
let table = s.doc.assembly.links.first().map(|l| l.lift.clone()).unwrap_or_default();
let mut t = cam_on_base();
run(&mut t, "component.activate", json!({"component": "root"}));
run(&mut t, "component.create", json!({"name": "Arm"}));
run(&mut t, "solid.cylinder", json!({"base": [start.x, start.y, 0], "axis": [0, 0, 1], "radius": roller, "height": 5}));
pin(&mut t, "revolute", "Arm", "Base", "Arm", pivot, Vec3::Z);
let face = [start.x + roller, start.y, 2.5];
run(
&mut t,
"joint.cam",
json!({"a": "Cam", "b": "Arm", "profile": {"sketch": "CamSketch"}, "follower": "roller", "radius": {"occurrence": "Arm", "circle": face}}),
);
let picked = t.doc.assembly.links.first().map(|l| l.lift.clone()).unwrap_or_default();
assert!(picked.len() == 360 && picked.iter().zip(&table).all(|(x, y)| close(*x, *y, 1e-6)));
}
/// A stationary cam: the profile on the grounded part, a rotor turning about it with the tappet's
/// guide on it. Turned by +θ against the cam, the tappet stands where it would on a cam turned by
/// −θ. A guide on the cam's own (grounded) side would turn with the profile: refused.
#[test]
fn a_stationary_cam_drives_a_follower_on_a_turning_rotor() {
let h = 6.0;
let tip = knife(0.0, h, R);
let mut s = cam_on_base();
// The cam is the fixed part: ground it, and take the base off its joint.
let (cam, base) = (occ(&s, "Cam"), occ(&s, "Base"));
run(&mut s, "joint.delete", json!({"joint": "Cam"}));
run(&mut s, "occurrence.ground", json!({"occurrence": cam, "grounded": true}));
run(&mut s, "occurrence.ground", json!({"occurrence": base, "grounded": false}));
pin(&mut s, "revolute", "Turret", "Cam", "Base", Vec3::ZERO, Vec3::Z);
tappet(&mut s, h, tip);
run(&mut s, "joint.cam", json!({"a": "Turret", "b": "Tappet", "profile": {"sketch": "CamSketch"}}));
for deg in [50.0f64, 140.0, 260.0] {
let d = run(&mut s, "joint.drive", json!({"joint": "Turret", "value": deg}));
assert_eq!(d["conflicts"].as_array().map(Vec::len), Some(0), "{d}");
let want = knife(-deg, h, R) - tip;
assert!(close(shown(&mut s, "Tappet"), want, 1e-3), "θ {deg}: {} vs {want}", shown(&mut s, "Tappet"));
}
let mut s = cam_on_base();
let (cam, base) = (occ(&s, "Cam"), occ(&s, "Base"));
run(&mut s, "joint.delete", json!({"joint": "Cam"}));
run(&mut s, "occurrence.ground", json!({"occurrence": cam, "grounded": true}));
run(&mut s, "occurrence.ground", json!({"occurrence": base, "grounded": false}));
part(&mut s, "Rotor", [-90.0, 60.0, -20.0]);
pin(&mut s, "revolute", "Turret", "Cam", "Rotor", Vec3::ZERO, Vec3::Z);
run(&mut s, "occurrence.ground", json!({"occurrence": base, "grounded": true}));
tappet(&mut s, h, tip);
let e = s.execute("joint.cam", &json!({"a": "Turret", "b": "Tappet", "profile": {"sketch": "CamSketch"}})).map_err(|e| e.to_string()).err();
assert!(e.as_deref().is_some_and(|e| e.contains("turns with the cam")), "{e:?}");
}
/// A motion study turning the cam plays the tappet through its analytic travel.
#[test]
fn a_cam_plays_in_a_motion_study() {
let mut s = cam_on_base();
let tip = knife(0.0, 0.0, R);
tappet(&mut s, 0.0, tip);
run(&mut s, "joint.cam", json!({"a": "Cam", "b": "Tappet", "profile": {"sketch": "CamSketch"}}));
run(&mut s, "motion.study", json!({"name": "Turn", "steps": 10, "keys": [{"joint": "Cam", "points": [[0, 0], [10, 360]]}]}));
for step in [0, 2, 5, 7, 10] {
run(&mut s, "motion.play", json!({"study": "Turn", "step": step}));
let want = knife(36.0 * f64::from(step), 0.0, R) - tip;
assert!(close(shown(&mut s, "Tappet"), want, 1e-3), "step {step}: {} vs {want}", shown(&mut s, "Tappet"));
}
}
/// The tappet is the piston of a slider-crank: a 40 mm rod from its end to a 20 mm crank about
/// (95, 0). Turning the cam moves the tappet, and the loop turns the crank to where the rod's
/// circle meets the crank's, on the branch it started on. A stop in a contact set with the cam and
/// the tappet halts the cam where the tappet reaches it; the cam and the flat tappet only touch.
#[test]
fn a_cam_drives_a_closed_loop_and_stops_at_a_contact() {
let mut s = cam_on_base();
let tip = knife(0.0, 0.0, R);
tappet(&mut s, 0.0, tip);
let (q, end) = (Vec3::new(95.0, 0.0, 2.5), Vec3::new(tip + 20.0, 0.0, 2.5));
let crank_pin = |x: f64| meet(q, 20.0, Vec3::new(x, 0.0, 2.5), 40.0).into_iter().find(|p| p.y > 0.0).unwrap_or(Vec3::ZERO);
let pin0 = crank_pin(end.x);
for (name, at) in [("Rod", end), ("Crank", pin0)] {
run(&mut s, "component.activate", json!({"component": "root"}));
run(&mut s, "component.create", json!({"name": name}));
run(&mut s, "solid.box", json!({"length": 2, "width": 2, "height": 2, "corner": [at.x - 1.0, at.y - 1.0, 10]}));
}
pin(&mut s, "revolute", "Crank", "Base", "Crank", q, Vec3::Z);
pin(&mut s, "revolute", "Wrist", "Tappet", "Rod", end, Vec3::Z);
pin(&mut s, "revolute", "Big end", "Rod", "Crank", pin0, Vec3::Z);
run(&mut s, "joint.cam", json!({"a": "Cam", "b": "Tappet", "profile": {"sketch": "CamSketch"}}));
for deg in [45.0f64, 120.0, 180.0] {
let d = run(&mut s, "joint.drive", json!({"joint": "Cam", "value": deg}));
assert_eq!(d["conflicts"].as_array().map(Vec::len), Some(0), "{d}");
let x = end.x + knife(deg, 0.0, R) - tip;
let at = place(&s, "Crank", pin0);
assert!(at.dist(crank_pin(x)) < 1e-3, "θ {deg}: {at:?} vs {:?}", crank_pin(x));
}
// A flat tappet, a stop 5 mm past where its end is at the top, and contact on.
let mut s = cam_on_base();
tappet(&mut s, 0.0, E + R);
run(&mut s, "joint.cam", json!({"a": "Cam", "b": "Tappet", "profile": {"sketch": "CamSketch"}, "follower": "flat"}));
run(&mut s, "joint.drive", json!({"joint": "Cam", "value": 180}));
run(&mut s, "component.activate", json!({"component": "root"}));
run(&mut s, "component.create", json!({"name": "Stop"}));
run(&mut s, "solid.box", json!({"length": 3, "width": 4, "height": 5, "corner": [E + R + 15.0, -2, 0]}));
let st = occ(&s, "Stop");
run(&mut s, "occurrence.ground", json!({"occurrence": st, "grounded": true}));
run(&mut s, "contact.create", json!({"occurrences": ["Cam", "Tappet", "Stop"]}));
// Touching the cam stops nothing: half a turn moves the tappet 20 mm back up, as far as the stop.
let d = run(&mut s, "joint.drive", json!({"joint": "Cam", "value": 90}));
assert!(d["stopped_by_contact"].is_null(), "{d}");
let d = run(&mut s, "joint.drive", json!({"joint": "Cam", "value": 0}));
assert!(d["stopped_by_contact"].is_object(), "{d}");
let reached = shown(&mut s, "Tappet");
assert!(reached > -5.5 && reached < -4.5, "{reached}");
}
/// What a cam can't be made from is refused, and a table edited by hand never puts a NaN into a
/// joint's value.
#[test]
fn hostile_cams_are_refused() {
let mut s = cam_on_base();
tappet(&mut s, 0.0, E + R);
let refused = |s: &mut Session, p: Value| s.execute("joint.cam", &p).map_err(|e| e.to_string()).err().unwrap_or_else(|| panic!("accepted {p}"));
// An open curve makes no closed profile.
run(&mut s, "component.activate", json!({"component": "Cam"}));
run(&mut s, "sketch.create", json!({"plane": "XY", "name": "Open"}));
run(&mut s, "sketch.line", json!({"points": [[0, 0], [20, 5], [10, 20]]}));
run(&mut s, "sketch.finish", json!({}));
let e = refused(&mut s, json!({"a": "Cam", "b": "Tappet", "profile": {"sketch": "Open"}}));
assert!(e.contains("closed profile"), "{e}");
// Two closed edges are not one loop; a line past the cam misses it.
let e = refused(&mut s, json!({"a": "Cam", "b": "Tappet", "profile": {"edges": [[E + R, 0, 5], [E + R, 0, 0]]}}));
assert!(e.contains("closed loop"), "{e}");
let mut far = cam_on_base();
tappet(&mut far, 50.0, 0.0);
let e = refused(&mut far, json!({"a": "Cam", "b": "Tappet", "profile": {"sketch": "CamSketch"}}));
assert!(e.contains("misses"), "{e}");
for p in [
json!({"a": "Tappet", "b": "Cam", "profile": {"sketch": "CamSketch"}}),
json!({"a": "Cam", "b": "Cam", "profile": {"sketch": "CamSketch"}}),
json!({"a": "Cam", "b": "Tappet"}),
json!({"a": "Cam", "b": "Tappet", "profile": {"sketch": "CamSketch", "index": 7}}),
json!({"a": "Cam", "b": "Tappet", "profile": {"edges": []}}),
json!({"a": "Cam", "b": "Tappet", "profile": {"edges": [[1, "x", 0]]}}),
json!({"a": "Cam", "b": "Tappet", "profile": {"edges": vec![[E + R, 0.0, 5.0]; 65]}}),
json!({"a": "Cam", "b": "Tappet", "profile": {"sketch": "CamSketch"}, "follower": "roller"}),
json!({"a": "Cam", "b": "Tappet", "profile": {"sketch": "CamSketch"}, "follower": "roller", "radius": -1}),
json!({"a": "Cam", "b": "Tappet", "profile": {"sketch": "CamSketch"}, "follower": "roller", "radius": "nope"}),
json!({"a": "Cam", "b": "Tappet", "profile": {"sketch": "CamSketch"}, "follower": "roller", "radius": 1e300}),
json!({"a": "Cam", "b": "Tappet", "profile": {"sketch": "CamSketch"}, "follower": "spring"}),
json!({"a": "Cam", "b": "Tappet", "profile": {"sketch": "CamSketch"}, "link": 3}),
] {
refused(&mut s, p);
}
assert!(s.doc.assembly.links.is_empty());
// A table edited by hand: NaN leaves the follower where it is, any length reads.
run(&mut s, "joint.cam", json!({"a": "Cam", "b": "Tappet", "profile": {"sketch": "CamSketch"}}));
let before = solidcraft_doc::joints::joint_values(&s.doc.assembly);
for lift in [vec![f64::NAN; 360], vec![1.0, 2.0, 3.0], vec![f64::INFINITY]] {
let mut d = (*s.doc).clone();
if let Some(l) = d.assembly.links.first_mut() {
l.lift = lift;
}
let vals = solidcraft_doc::joints::joint_values(&d.assembly);
assert!(vals.values().flatten().all(|v| v.is_finite()), "{vals:?}");
// The follower keeps where it is.
assert_eq!(vals.get(&joint_id(&s, "Tappet")), d.assembly.joints.iter().find(|j| j.name == "Tappet").map(|j| &j.values), "{before:?}");
}
// A table on a plain link is not read.
let mut d = (*s.doc).clone();
if let Some(l) = d.assembly.links.first_mut() {
(l.coupling, l.ratio, l.offset) = (None, 0.0, 3.0);
}
assert_eq!(solidcraft_doc::joints::joint_values(&d.assembly).get(&joint_id(&s, "Tappet")).and_then(|q| q.first()).copied(), Some(3.0));
// A roller's picked face must turn about an axis parallel to the cam's, a tip given or not.
run(&mut s, "component.activate", json!({"component": "root"}));
run(&mut s, "component.create", json!({"name": "Pin"}));
run(&mut s, "solid.cylinder", json!({"base": [60, 30, 0], "axis": [1, 0, 0], "radius": 3, "height": 10}));
run(&mut s, "joint.delete", json!({"link": 0}));
let tilted = json!({"a": "Cam", "b": "Tappet", "profile": {"sketch": "CamSketch"}, "follower": "roller",
"radius": {"occurrence": "Pin", "circle": [65, 33, 0]}, "tip": {"occurrence": "Tappet", "point": [E + R, 0, 2.5]}});
let e = refused(&mut s, tilted);
assert!(e.contains("roller's axis"), "{e}");
}
/// A cam saves and opens with its definition and table; a link saved before cams reads as a
/// plain link.
#[test]
fn cams_save_and_open_with_their_table() {
let mut s = cam_on_base();
tappet(&mut s, 0.0, E + R);
run(&mut s, "joint.cam", json!({"a": "Cam", "b": "Tappet", "profile": {"sketch": "CamSketch"}, "follower": "roller", "radius": 2}));
run(&mut s, "joint.drive", json!({"joint": "Cam", "value": 30}));
let text = s.doc.to_json();
let back = solidcraft_doc::format::read(&text).unwrap_or_else(|e| panic!("{e}"));
assert_eq!(back.assembly.links, s.doc.assembly.links);
assert_eq!(back.assembly.links.first().map(|l| l.lift.len()), Some(360));
let l = run(&mut s, "joint.list", json!({}));
let link = &l["links"][0];
assert!(link.get("ratio").is_none() && link["lift"]["unit"] == "mm" && link["coupling"]["type"] == "cam", "{link}");
assert!(link["coupling"].get("lift").is_none(), "{link}");
let mut v: Value = serde_json::from_str(&text).unwrap_or_default();
for l in v["assembly"]["links"].as_array_mut().into_iter().flatten() {
l.as_object_mut().map(|o| (o.remove("coupling"), o.remove("lift")));
}
let old = solidcraft_doc::format::read(&v.to_string()).unwrap_or_else(|e| panic!("{e}"));
assert!(old.assembly.links.iter().all(|l| l.coupling.is_none() && l.lift.is_empty()));
}
+37
View File
@@ -34,6 +34,40 @@ fn leaf(s: &mut Session, name: &str) {
run(s, "solid.cylinder", json!({"base": [0, 33, 4], "axis": [1, 0, 0], "radius": 4, "height": 40, "operation": "new"}));
}
#[test]
fn circle_given_by_its_centre_takes_that_round_end() {
// #393: `circle` at the centre of a round end, as the parameters document, was refused with
// "no cylindrical face there" (no face lies at a centre).
let mut s = Session::default();
run(&mut s, "component.create", json!({"name": "Plate"}));
run(&mut s, "solid.box", json!({"length": 30, "width": 20, "height": 6, "corner": [-15, -10, 0]}));
run(&mut s, "component.activate", json!({"component": "root"}));
run(&mut s, "component.create", json!({"name": "Knob"}));
run(&mut s, "solid.cylinder", json!({"base": [0, 0, 6], "axis": [0, 0, 1], "radius": 10, "height": 10, "operation": "new"}));
let r = run(
&mut s,
"joint.create",
json!({"type": "cylindrical", "a": {"occurrence": "Plate", "face": [0, 0, 6]}, "b": {"occurrence": "Knob", "circle": [0, 0, 6]}, "name": "J"}),
);
assert_eq!(r["conflicts"].as_array().map(Vec::len), Some(0), "{r}");
// The knob's bottom circle already sits on the plate's top: its axis stays put (it may turn
// about it, to line up the two frames' x).
for z in [6.0, 16.0] {
assert!(near(place(&s, "Knob", Vec3::new(0.0, 0.0, z)), Vec3::new(0.0, 0.0, z)), "{:?}", place(&s, "Knob", Vec3::new(0.0, 0.0, z)));
}
// The top end's centre: its axis points up, out of the knob.
run(&mut s, "joint.origin", json!({"occurrence": "Knob", "circle": [0, 0, 16], "name": "Top"}));
let top = s.doc.assembly.origins.iter().find(|o| o.name == "Top").map(|o| o.origin.snap.clone());
assert!(
matches!(top, Some(solidcraft_doc::joints::Snap::Point { point, z: Some(z) }) if near(point, Vec3::new(0.0, 0.0, 16.0)) && near(z, Vec3::Z)),
"{top:?}"
);
// Off the axis is still refused, and so is a coupling size (it follows a face).
assert!(s.execute("joint.origin", &json!({"occurrence": "Knob", "circle": [3, 0, 6]})).is_err());
let e = s.execute("joint.screw", &json!({"joint": "J", "pitch": {"occurrence": "Knob", "circle": [0, 0, 6]}})).unwrap_err();
assert!(e.to_string().contains("not its centre"), "{e}");
}
#[test]
fn revolute_hinge_turns_about_the_knuckle() {
let mut s = Session::default();
@@ -1411,3 +1445,6 @@ fn hostile_trace_params_are_refused() {
#[path = "joints_coupling_tests.rs"]
mod coupling;
#[path = "joints_cam_tests.rs"]
mod cam;
@@ -326,3 +326,76 @@ fn every_flat_face_of_an_elbow_up_and_an_elbow_down_takes_a_sketch() {
);
every_flat_face_takes_a_sketch(&mut s);
}
/// #565: Split Body by a plane a parameter moves (a raw plane, a construction plane or a sketch
/// line). The face the split cuts on each part is named after the half-space that cut it
/// (`F<split>:section`): a sketch and an offset plane attach to it and follow the plane.
#[test]
fn the_face_a_split_cuts_takes_a_sketch_and_an_offset_plane_that_follow_the_plane() {
for tool in ["plane", "construction", "line"] {
let mut s = Session::default();
run(&mut s, "parameters.add", json!({"name": "split_x", "expression": "15 mm"}));
run(&mut s, "solid.box", json!({"length": 40, "width": 20, "height": 10, "body_name": "Block"}));
let split = match tool {
"plane" => json!({"body": "Block", "plane": {"origin": ["split_x", 0, 0], "normal": [1, 0, 0]}}),
"construction" => {
run(&mut s, "construct.plane.offset", json!({"base": "YZ", "offset": "split_x", "name": "Cut"}));
json!({"body": "Block", "plane": "Cut"})
}
_ => {
let id = run(&mut s, "sketch.create", json!({"plane": "XY", "name": "Guide"}))["sketch"].as_u64().unwrap();
run(&mut s, "sketch.line", json!({"points": [[15, -10], [15, 30]], "ids": ["cut"], "connect": false}));
run(&mut s, "sketch.constraint.horizontal_vertical", json!({"line": "cut", "mode": "vertical"}));
run(&mut s, "sketch.dimension", json!({"entities": ["origin", "cut.start"], "type": "horizontal", "value": "split_x"}));
run(&mut s, "sketch.finish", json!({}));
json!({"body": "Block", "sketch": id, "line": "cut"})
}
};
run(&mut s, "solid.split_body", split);
no_errors(&s);
// Each part's cut face (the two lie on one another, so each is picked by body and index).
let cut_face = |s: &Session, body: &str, x: f64| {
let state = s.model.state();
let b = &state.body(body).unwrap().body;
let index = (0..b.face_count())
.find(|i| b.planar_face(*i).is_some_and(|p| p.normal().x.abs() > 0.999 && (p.origin.x - x).abs() < 1e-9))
.unwrap_or_else(|| panic!("{tool}: no cut face on `{body}`"));
json!({"face": [x, 10, 5], "body": body, "index": index})
};
let mut normals = Vec::new();
for (k, body) in ["Block", "Block (1)"].into_iter().enumerate() {
let pick = cut_face(&s, body, 15.);
run(&mut s, "sketch.create", json!({"plane": pick, "name": format!("OnCut{k}")}));
run(&mut s, "sketch.finish", json!({}));
let (plane, certificate) = healthy(&s, &format!("OnCut{k}"));
assert_eq!(certificate, Some(FaceCertificate::Lineage), "{tool} {body}");
assert!((plane.origin.x - 15.).abs() < 1e-9 && plane.normal().x.abs() > 0.999, "{tool} {body}: {plane:?}");
normals.push(plane.normal().x);
let pick = cut_face(&s, body, 15.);
run(&mut s, "construct.plane.offset", json!({"base": pick, "offset": 2, "name": format!("Off{k}")}));
}
assert!(normals[0] * normals[1] < 0., "{tool}: the two cut faces face each other's way: {normals:?}");
no_errors(&s);
run(&mut s, "parameters.change", json!({"name": "split_x", "expression": "20 mm"}));
no_errors(&s);
let offset = |s: &Session, name: &str| {
let feature = s.doc.find_feature(name).map(|f| f.id).unwrap();
let state = s.model.state();
match state.construct.iter().find(|c| c.feature == feature).map(|c| &c.geom) {
Some(solidcraft_doc::construct::ConstructGeom::Plane(p)) => *p,
other => panic!("{tool} {name}: {other:?}"),
}
};
for (k, n) in normals.iter().enumerate() {
let (plane, _) = healthy(&s, &format!("OnCut{k}"));
assert!((plane.origin.x - 20.).abs() < 1e-9 && (plane.normal().x - n).abs() < 1e-9, "{tool} OnCut{k}: {plane:?}");
let off = offset(&s, &format!("Off{k}"));
assert!((off.origin.x - (20. + 2. * n)).abs() < 1e-9, "{tool} Off{k}: {off:?}");
}
let t = reopened(&s);
for k in 0..2 {
assert!((healthy(&t, &format!("OnCut{k}")).0.origin.x - 20.).abs() < 1e-9, "{tool} reopened OnCut{k}");
}
}
}
+2
View File
@@ -74,6 +74,7 @@ mod sketch_modify;
mod sketch_project;
mod surface;
mod surface_analysis;
mod surface_boundary;
mod surface_match;
mod view_dxf;
mod view_navigation;
@@ -236,6 +237,7 @@ pub fn command_specs() -> Vec<&'static CommandSpec> {
v.extend(sketch_canvas::COMMANDS.iter());
v.extend(sketch_3d::COMMANDS.iter());
v.extend(surface_analysis::COMMANDS.iter());
v.extend(surface_boundary::COMMANDS.iter());
v.extend(surface::COMMANDS.iter());
v.extend(surface_match::COMMANDS.iter());
v.extend(sketch_modify::COMMANDS.iter());
+41 -24
View File
@@ -14,6 +14,8 @@ use super::joints::{cannot_move, effective_values, joint_id, occurrence_id, reso
use crate::params::{bad, bool_, str_, vec3};
use crate::{EngineError, Result, Session};
#[path = "motion_animation.rs"]
mod animation;
#[path = "contact_sweep.rs"]
mod contact_sweep;
@@ -54,6 +56,9 @@ pub static COMMANDS: &[CommandSpec] = &[
CommandSpec::new("motion.export", "Export Motion Study", export)
.noundo()
.params("study; samples? (default steps + 1); path? (.json or .csv) → occurrence positions per step (the design is not changed)"),
CommandSpec::new("motion.export_animation", "Export Motion Animation", animation::export).noundo().params(
"study: id|name, or joint: id|name with from and to (degrees for angles, mm for distances, or expressions) and index?; path: a .gif file, or a folder for PNG frames (frame-0001.png, frame-0002.png, …); samples? (frames, 2…1000; default the study's steps + 1, or 100); width?, height? (16…4096 pixels, default 800 × 500); camera?: {target, yaw, pitch, roll?, distance, fov?, up?} (ui.camera's reply; fields left out keep the default view: view.apply's camera, or the home view framing the model); fps? (1…50, default 20); grid?, axes? (default true: the ground grid and the origin's axes) - draws the study as it plays, or the joint as it is driven, with the headless renderer → path, format, frames, width, height, fps (GIF), bytes, renderer, stopped_at, stopped_by_loop, stopped_by_contact (the design is not changed)",
),
CommandSpec::new("motion.trace", "Motion Trace", trace).at("SOLID", "ASSEMBLE").icon("trace").noundo().params(concat!(
trace_doc!(),
" → points: [[x,y,z]…] world positions, samples (taken), stopped_at (the sample where the motion stopped short; the trace \
@@ -718,19 +723,45 @@ fn sample_trace(s: &Session, p: &Value, cmd: &str) -> Result<(Vec<Vec3>, Value)>
let local = solidcraft_doc::mat_inverse(&world(&t)?)
.map(|m| solidcraft_doc::apply_point(&m, at))
.ok_or_else(|| bad(cmd, "the occurrence's placement is not invertible"))?;
let samples = |default: usize| match p.get("samples") {
let (default, given, plan) = motion_plan(s, p, cmd)?;
let n = sample_count(p, default.min(MAX_TRACE), MAX_TRACE, cmd)?;
let mut points = Vec::new();
let mut stop = (Value::Null, Value::Null, Value::Null);
for k in 0..n {
let want = plan(&t, k, n);
let (r, _) = drive_with_contact(&mut t, &want, &given)?;
points.push(solidcraft_doc::apply_point(&world(&t)?, local));
if r["stopped_by_loop"].is_object() || r["stopped_by_contact"].is_object() {
stop = (json!(k), r["stopped_by_loop"].clone(), r["stopped_by_contact"].clone());
break;
}
}
let name = s.doc.occurrences.iter().find(|o| Some(&o.id) == path.last()).map_or_else(|| "root".to_string(), |o| o.name.clone());
let out = json!({"occurrence": name, "samples": points.len(), "stopped_at": stop.0, "stopped_by_loop": stop.1, "stopped_by_contact": stop.2});
Ok((points, out))
}
/// `samples`, 2…`max`, or `default` without it.
fn sample_count(p: &Value, default: usize, max: usize, cmd: &str) -> Result<usize> {
match p.get("samples") {
Some(v) => v
.as_f64()
.filter(|n| n.is_finite() && *n >= 2.0 && *n <= MAX_TRACE as f64)
.filter(|n| n.is_finite() && *n >= 2.0 && *n <= max as f64)
.map(|n| n.round() as usize)
.ok_or_else(|| bad(cmd, format!("`samples` must be 2…{MAX_TRACE}"))),
None => Ok(default),
};
let (n, given, plan): (usize, BTreeSet<(u64, usize)>, Plan) = match (p.get("study"), p.get("joint")) {
.ok_or_else(|| bad(cmd, format!("`samples` must be 2…{max}"))),
None => Ok(default.max(2)),
}
}
/// The motion a trace or an animation samples: a study played from start to end, or one joint
/// value driven from `from` to `to`. Returns the default sample count (the study's steps + 1, or
/// 100), the values driven and what they are at sample `k` of `n`.
fn motion_plan(s: &Session, p: &Value, cmd: &str) -> Result<(usize, BTreeSet<(u64, usize)>, Plan)> {
Ok(match (p.get("study"), p.get("joint")) {
(Some(_), Some(_)) => return Err(bad(cmd, "give `study` or `joint`, not both")),
(Some(_), None) => {
let m = s.doc.assembly.studies.get(study_index(s, p, cmd)?).cloned().ok_or_else(|| bad(cmd, "study"))?;
let n = samples((m.steps as usize).saturating_add(1).clamp(2, MAX_TRACE))?;
let n = (m.steps as usize).saturating_add(1);
(n, keyed(&m), Box::new(move |t, k, n| values_at(t, &m, f64::from(m.steps) * k as f64 / (n - 1) as f64)))
}
(None, Some(j)) => {
@@ -750,7 +781,7 @@ fn sample_trace(s: &Session, p: &Value, cmd: &str) -> Result<(Vec<Vec3>, Value)>
};
let end = |key: &str| match p.get(key) {
Some(v) => value(s, v, kind.is_angle(index), cmd),
None => Err(bad(cmd, format!("give `from` and `to`: the joint's values the trace runs between (no `{key}`)"))),
None => Err(bad(cmd, format!("give `from` and `to`: the joint's values the motion runs between (no `{key}`)"))),
};
let (from, to) = (end("from")?, end("to")?);
let plan: Plan = Box::new(move |t, k, n| {
@@ -761,24 +792,10 @@ fn sample_trace(s: &Session, p: &Value, cmd: &str) -> Result<(Vec<Vec3>, Value)>
}
vec![(id, q)]
});
(samples(100)?, BTreeSet::from([(id, index)]), plan)
(100, BTreeSet::from([(id, index)]), plan)
}
(None, None) => return Err(bad(cmd, "give a `study`, or a `joint` with `from` and `to`")),
};
let mut points = Vec::new();
let mut stop = (Value::Null, Value::Null, Value::Null);
for k in 0..n {
let want = plan(&t, k, n);
let (r, _) = drive_with_contact(&mut t, &want, &given)?;
points.push(solidcraft_doc::apply_point(&world(&t)?, local));
if r["stopped_by_loop"].is_object() || r["stopped_by_contact"].is_object() {
stop = (json!(k), r["stopped_by_loop"].clone(), r["stopped_by_contact"].clone());
break;
}
}
let name = s.doc.occurrences.iter().find(|o| Some(&o.id) == path.last()).map_or_else(|| "root".to_string(), |o| o.name.clone());
let out = json!({"occurrence": name, "samples": points.len(), "stopped_at": stop.0, "stopped_by_loop": stop.1, "stopped_by_contact": stop.2});
Ok((points, out))
})
}
fn trace(s: &mut Session, p: &Value) -> Result<Value> {
+154
View File
@@ -0,0 +1,154 @@
//! Motion animations (`motion.export_animation`): a study played, or one joint driven, drawn
//! frame by frame by the headless renderer the host installed ([`crate::capture`]) and written as
//! an animated GIF or a folder of PNG frames. Sampled on a copy, as a trace is: the design is not
//! changed.
use serde_json::{Value, json};
use super::{drive_with_contact, motion_plan, sample_count};
use crate::capture::{self, Renderer};
use crate::params::{bad, str_};
use crate::render::Camera;
use crate::{Result, Session};
/// Most frames of one animation.
const MAX_FRAMES: usize = 1000;
/// Largest frame side, in pixels.
const MAX_SIDE: u32 = 4096;
/// Most pixels of a GIF's frames together: they are held in memory (4 bytes each) until the
/// palette is chosen, so 256 MB at most.
const MAX_GIF_PIXELS: usize = 1 << 26;
/// Most pixels of a PNG folder's frames together (each frame is written as it is drawn): about
/// 500 frames of 1920 × 1080.
const MAX_PNG_PIXELS: usize = 1 << 30;
/// The camera fields `camera` may set: those of `ui.camera`'s reply.
const FIELDS: [&str; 7] = ["target", "yaw", "pitch", "roll", "distance", "fov", "up"];
pub(super) fn export(s: &mut Session, p: &Value) -> Result<Value> {
export_with(s, p, capture::installed().as_deref())
}
/// [`export`] drawn by `renderer`.
pub(super) fn export_with(s: &Session, p: &Value, renderer: Option<&Renderer>) -> Result<Value> {
let cmd = "motion.export_animation";
let path = str_(p, "path")
.filter(|x| !x.trim().is_empty() && x.len() <= 4096 && !x.chars().any(char::is_control))
.ok_or_else(|| bad(cmd, "`path` must name a .gif file, or a folder for PNG frames"))?;
let lower = path.to_ascii_lowercase();
if lower.ends_with(".png") {
return Err(bad(cmd, "`path` is a .gif file or a folder for the PNG frames (frame-0001.png, …), not one .png"));
}
let gif = lower.ends_with(".gif");
// In the browser written files stay in memory until the host takes them, and the host is not
// told of removed ones: a folder of frames would pile up there.
if !gif && cfg!(target_arch = "wasm32") {
return Err(bad(cmd, "a folder of PNG frames is not available in the browser: give a .gif path"));
}
let side = |key: &str, default: u32| match p.get(key) {
None => Ok(default),
Some(v) => v
.as_f64()
.filter(|n| n.is_finite() && (16.0..=f64::from(MAX_SIDE)).contains(n))
.map(|n| n.round() as u32)
.ok_or_else(|| bad(cmd, format!("`{key}` must be 16…{MAX_SIDE} pixels"))),
};
let (width, height) = (side("width", 800)?, side("height", 500)?);
let fps = match p.get("fps") {
None => 20.0,
Some(v) => v.as_f64().filter(|n| n.is_finite() && (1.0..=50.0).contains(n)).ok_or_else(|| bad(cmd, "`fps` must be 1…50"))?,
};
let cam = camera(s, p.get("camera"), cmd)?;
let shown = |key: &str| match p.get(key) {
None => Ok(true),
Some(Value::Bool(b)) => Ok(*b),
Some(_) => Err(bad(cmd, format!("`{key}` must be true or false"))),
};
let guides = crate::view::Guides { grid: shown("grid")?, axes: shown("axes")? };
let (default, given, plan) = motion_plan(s, p, cmd)?;
// At least 4 frames fit even at the largest size.
let max = MAX_FRAMES.min(if gif { MAX_GIF_PIXELS } else { MAX_PNG_PIXELS } / (width as usize * height as usize));
let n = sample_count(p, default.min(max), max, cmd).map_err(|_| bad(cmd, format!("`samples` must be 2…{max} for {width} × {height} frames")))?;
let renderer = renderer.ok_or_else(|| bad(cmd, "no renderer is installed to draw pictures in this process"))?;
// A destination outside an agent's folders is refused before anything is drawn.
let io = |e: std::io::Error| bad(cmd, format!("{path}: {e}"));
solidcraft_io::vfs::check(path).map_err(io)?;
let frame_path = |k: usize| std::path::Path::new(path).join(format!("frame-{k:04}.png")).to_string_lossy().to_string();
if !gif {
solidcraft_io::vfs::create_dir_all(path).map_err(io)?;
// The frames of an earlier export here go first, so the folder never mixes two
// animations: not after a shorter one, nor when this one fails part way.
for stale in (1..=MAX_FRAMES).map(frame_path).filter(|f| solidcraft_io::vfs::exists(f)) {
solidcraft_io::vfs::remove(&stale).map_err(|e| bad(cmd, format!("{stale}: {e}")))?;
}
}
let mut t = s.scratch();
// From where the parts are placed: moves only shown (an exploded view, the pose an open
// Motion Study dialog shows) are not where the joints are solved.
t.pending_moves.clear();
let (mut frames, mut bytes, mut drawn_by) = (Vec::new(), 0, "");
let mut stop = (Value::Null, Value::Null, Value::Null);
for k in 0..n {
let want = plan(&t, k, n);
let (r, _) = drive_with_contact(&mut t, &want, &given)?;
if stop.0.is_null() && (r["stopped_by_loop"].is_object() || r["stopped_by_contact"].is_object()) {
stop = (json!(k), r["stopped_by_loop"].clone(), r["stopped_by_contact"].clone());
}
let scene = crate::view::scene_with_guides(&t, &cam, s.section, guides);
let picture = capture::rgba_with(Some(renderer), &scene, &cam, width, height).map_err(|e| bad(cmd, e))?;
drawn_by = picture.renderer;
if gif {
frames.push(picture.rgba);
} else {
let png = crate::render::png(width as usize, height as usize, picture.rgba).ok_or_else(|| bad(cmd, "PNG encoding failed"))?;
let file = frame_path(k + 1);
solidcraft_io::vfs::write(&file, &png).map_err(|e| bad(cmd, format!("{file}: {e}")))?;
bytes += png.len();
}
}
let mut out = json!({"path": path, "format": if gif { "gif" } else { "png" }, "frames": n, "width": width, "height": height});
if gif {
// GIF counts in hundredths of a second, and viewers slow anything under 2 down.
let delay = (100.0 / fps).round().clamp(2.0, 100.0) as u16;
let gif = crate::render::gif(width as usize, height as usize, &frames, delay).ok_or_else(|| bad(cmd, "GIF encoding failed"))?;
solidcraft_io::write_atomic(std::path::Path::new(path), &gif, false).map_err(io)?;
bytes = gif.len();
out["fps"] = json!(100.0 / f64::from(delay));
}
out["bytes"] = json!(bytes);
out["renderer"] = json!(drawn_by);
if let Some(w) = capture::warning(drawn_by) {
out["warning"] = json!(w);
}
out["stopped_at"] = stop.0;
out["stopped_by_loop"] = stop.1;
out["stopped_by_contact"] = stop.2;
Ok(out)
}
/// The camera the frames are drawn from: the session's (`view.apply`), or the home view framing
/// the model, with the fields `given` sets (`ui.camera`'s reply sets them all).
fn camera(s: &Session, given: Option<&Value>, cmd: &str) -> Result<Camera> {
let base = s.camera.unwrap_or_else(|| crate::view::home_camera(s));
let Some(given) = given else { return Ok(base) };
let fields = given.as_object().ok_or_else(|| bad(cmd, "`camera` must be an object, such as ui.camera's reply"))?;
let mut v = serde_json::to_value(base).map_err(|e| bad(cmd, e.to_string()))?;
for (k, x) in fields {
if !FIELDS.contains(&k.as_str()) {
return Err(bad(cmd, format!("unknown camera field `{k}` (it takes {})", FIELDS.join(", "))));
}
if let Some(o) = v.as_object_mut() {
o.insert(k.clone(), x.clone());
}
}
let mut cam: Camera = serde_json::from_value(v).map_err(|e| bad(cmd, format!("bad camera: {e}")))?;
if !cam.is_valid() || cam.distance > 1e15 || cam.pitch.abs() > std::f64::consts::FRAC_PI_2 || !(0.0..3.0).contains(&cam.fov) {
return Err(bad(
cmd,
"the camera must be finite, with a distance up to 1e15 mm, a pitch within ±π/2 and a fov of 0 (orthographic) to 3 radians",
));
}
// Straight up or down keeps a heading, as ui.camera does.
let lim = std::f64::consts::FRAC_PI_2 - 1e-6;
cam.pitch = cam.pitch.clamp(-lim, lim);
Ok(cam)
}
+232
View File
@@ -173,3 +173,235 @@ fn exploded_views_show_without_changing_the_design() {
);
assert_eq!(run(&mut s, "explode.list", json!({}))["views"].as_array().map(Vec::len), Some(2));
}
/// Pictures drawn by the CPU rasterizer (the engine has no GPU): real views of the scene.
fn cpu(scene: &crate::render::Scene, cam: &crate::render::Camera, w: u32, h: u32) -> Result<crate::capture::Picture, String> {
Ok(crate::capture::Picture { rgba: crate::render::render(scene, cam, w as usize, h as usize).rgba, renderer: "cpu" })
}
/// A folder of its own for one test's files.
fn out_dir(test: &str) -> std::path::PathBuf {
let dir = solidcraft_io::vfs::temp_dir().join(format!("solidcraft-anim-{test}-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
dir
}
/// A GIF's logical screen size and the number of its frames (image descriptors).
fn gif_frames(gif: &[u8]) -> (usize, usize, usize) {
let u16_at = |i: usize| usize::from(u16::from_le_bytes([gif[i], gif[i + 1]]));
assert_eq!(&gif[..6], b"GIF89a");
let mut at = 13 + if gif[10] & 0x80 != 0 { 3 << ((gif[10] & 7) + 1) } else { 0 };
let mut frames = 0;
// Each block: a size byte and that many bytes, up to a 0.
let skip_blocks = |mut at: usize| {
while gif[at] != 0 {
at += usize::from(gif[at]) + 1;
}
at + 1
};
loop {
match gif[at] {
0x3B => return (u16_at(6), u16_at(8), frames),
0x21 => at = skip_blocks(at + 2),
0x2C => {
frames += 1;
at = skip_blocks(at + 11);
}
b => panic!("unexpected GIF block {b:#x}"),
}
}
}
/// A PNG's width and height (its IHDR).
fn png_size(png: &[u8]) -> (u32, u32) {
let be = |i: usize| u32::from_be_bytes([png[i], png[i + 1], png[i + 2], png[i + 3]]);
(be(16), be(20))
}
#[test]
fn an_animation_has_the_frames_and_the_size_asked_for() {
let mut s = rail();
run(&mut s, "motion.study", json!({"name": "Push", "steps": 10, "keys": [{"joint": "Rail", "points": [[0, 10], [10, 0]]}]}));
let dir = out_dir("size");
let before = s.doc.clone();
let gif = dir.join("push.gif");
let p = json!({"study": "Push", "path": gif.to_string_lossy(), "samples": 6, "width": 64, "height": 40, "fps": 25});
let r = super::animation::export_with(&s, &p, Some(&cpu)).unwrap();
assert_eq!(
(r["format"].as_str(), r["frames"].as_u64(), r["width"].as_u64(), r["height"].as_u64()),
(Some("gif"), Some(6), Some(64), Some(40)),
"{r}"
);
assert_eq!(r["fps"], 25.0, "{r}");
let bytes = std::fs::read(&gif).unwrap();
assert_eq!(r["bytes"].as_u64(), Some(bytes.len() as u64));
assert_eq!(gif_frames(&bytes), (64, 40, 6));
// Without samples: the study's steps + 1.
let r =
super::animation::export_with(&s, &json!({"study": "Push", "path": gif.to_string_lossy(), "width": 32, "height": 32}), Some(&cpu)).unwrap();
assert_eq!(gif_frames(&std::fs::read(&gif).unwrap()), (32, 32, 11), "{r}");
// A folder of PNG frames, made where missing; a joint driven instead of a study.
let frames = dir.join("frames").join("rail");
let p = json!({"joint": "Rail", "from": 10, "to": 0, "path": frames.to_string_lossy(), "samples": 3, "width": 48, "height": 30});
let r = super::animation::export_with(&s, &p, Some(&cpu)).unwrap();
assert_eq!((r["format"].as_str(), r["frames"].as_u64()), (Some("png"), Some(3)), "{r}");
let mut names: Vec<String> = std::fs::read_dir(&frames).unwrap().map(|e| e.unwrap().file_name().to_string_lossy().to_string()).collect();
names.sort();
assert_eq!(names, ["frame-0001.png", "frame-0002.png", "frame-0003.png"]);
assert!(names.iter().all(|n| png_size(&std::fs::read(frames.join(n)).unwrap()) == (48, 30)));
// A shorter export into the same folder leaves no frames of a longer one behind, past a gap
// too; other files stay.
std::fs::write(frames.join("notes.txt"), "mine").unwrap();
std::fs::write(frames.join("frame-0005.png"), "older").unwrap();
super::animation::export_with(&s, &json!({"joint": "Rail", "from": 10, "to": 0, "path": frames.to_string_lossy(), "samples": 2}), Some(&cpu))
.unwrap();
let mut names: Vec<String> = std::fs::read_dir(&frames).unwrap().map(|e| e.unwrap().file_name().to_string_lossy().to_string()).collect();
names.sort();
assert_eq!(names, ["frame-0001.png", "frame-0002.png", "notes.txt"]);
assert_eq!(*s.doc, *before, "the design is not changed");
// Through the registry, with the renderer the host installed.
crate::capture::install_test_renderer();
let r = run(&mut s, "motion.export_animation", json!({"study": "Push", "path": gif.to_string_lossy(), "samples": 2, "width": 16, "height": 16}));
assert_eq!(r["frames"], 2, "{r}");
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn a_two_frame_drive_gives_two_different_frames() {
let s = rail();
let dir = out_dir("two");
let frames = |name: &str, to: f64| {
let folder = dir.join(name);
let p = json!({"joint": "Rail", "from": 10, "to": to, "path": folder.to_string_lossy(), "samples": 2, "width": 120, "height": 80});
super::animation::export_with(&s, &p, Some(&cpu)).unwrap();
(std::fs::read(folder.join("frame-0001.png")).unwrap(), std::fs::read(folder.join("frame-0002.png")).unwrap())
};
let (a, b) = frames("moved", -5.0);
assert_ne!(a, b, "B moved 15 mm between the frames");
// Held still, the two frames are the same picture: the difference is the motion.
let (c, d) = frames("still", 10.0);
assert_eq!(c, d);
assert_eq!(a, c, "both start at 10 mm");
// Without the ground grid and the axes, the same pose is another picture.
let bare = dir.join("bare");
let p = json!({"joint": "Rail", "from": 10, "to": 10, "path": bare.to_string_lossy(), "samples": 2, "width": 120, "height": 80, "grid": false, "axes": false});
super::animation::export_with(&s, &p, Some(&cpu)).unwrap();
assert_ne!(std::fs::read(bare.join("frame-0001.png")).unwrap(), c);
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn an_animation_is_drawn_from_the_camera_given() {
let mut s = rail();
let dir = out_dir("camera");
// A renderer is 'static (hosts install it for the process): it shares what it saw.
let seen = std::sync::Arc::new(std::sync::Mutex::new(Vec::new()));
let record = {
let seen = seen.clone();
move |scene: &crate::render::Scene, cam: &crate::render::Camera, w: u32, h: u32| {
seen.lock().unwrap().push(*cam);
cpu(scene, cam, w, h)
}
};
let path = dir.join("cam.gif");
let base = json!({"joint": "Rail", "from": 10, "to": 0, "path": path.to_string_lossy(), "samples": 3, "width": 40, "height": 30});
let with = |camera: Value| {
let mut p = base.clone();
p["camera"] = camera;
p
};
// ui.camera's reply, every field.
let reply = json!({"target": [1.0, 2.0, 3.0], "yaw": 0.5, "pitch": -0.25, "roll": 0.1, "distance": 300.0, "fov": 0.6, "up": "y"});
super::animation::export_with(&s, &with(reply.clone()), Some(&record)).unwrap();
let cams = std::mem::take(&mut *seen.lock().unwrap());
assert_eq!(cams.len(), 3);
assert!(cams.iter().all(|c| json!(c) == reply), "{cams:?}");
// Fields left out keep the default view: view.apply's camera.
run(&mut s, "view.apply", json!({"camera": {"target": [0, 0, 0], "yaw": 1, "pitch": 0.2, "distance": 80}}));
super::animation::export_with(&s, &with(json!({"yaw": 2.0})), Some(&record)).unwrap();
let cams = std::mem::take(&mut *seen.lock().unwrap());
assert!(cams.iter().all(|c| c.yaw == 2.0 && c.pitch == 0.2 && c.distance == 80.0), "{cams:?}");
// Without one: view.apply's camera as it is; and another camera draws another picture.
super::animation::export_with(&s, &base, Some(&record)).unwrap();
assert!(seen.lock().unwrap().iter().all(|c| Some(*c) == s.camera));
let pictures = |camera: Value| {
let folder = dir.join(format!("p{}", camera["yaw"]));
let mut p = with(camera);
p["path"] = json!(folder.to_string_lossy());
super::animation::export_with(&s, &p, Some(&cpu)).unwrap();
std::fs::read(folder.join("frame-0001.png")).unwrap()
};
assert_ne!(pictures(json!({"yaw": 0.3})), pictures(json!({"yaw": 1.3})));
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn hostile_animation_params_are_refused() {
let mut s = rail();
run(&mut s, "motion.study", json!({"name": "Push", "steps": 10, "keys": [{"joint": "Rail", "points": [[0, 10], [10, 0]]}]}));
let dir = out_dir("hostile");
let gif = dir.join("x.gif").to_string_lossy().to_string();
let base = json!({"study": "Push", "path": gif, "samples": 2, "width": 16, "height": 16});
let refused = |change: Value| {
let mut p = base.clone();
if let (Some(p), Some(change)) = (p.as_object_mut(), change.as_object()) {
for (k, v) in change {
if v.is_null() {
p.remove(k);
} else {
p.insert(k.clone(), v.clone());
}
}
}
super::animation::export_with(&s, &p, Some(&cpu)).err().map(|e| e.to_string())
};
for change in [
json!({"samples": 0}),
json!({"samples": 1}),
json!({"samples": 1e9}),
json!({"samples": "many"}),
json!({"samples": 1001}),
json!({"width": 1e9}),
json!({"width": -16}),
json!({"height": 3}),
json!({"height": f64::MAX}),
json!({"fps": 0}),
json!({"fps": 1e9}),
json!({"path": ""}),
json!({"path": null}),
json!({"path": "one.png"}),
json!({"path": "a\u{0}b.gif"}),
json!({"path": "x".repeat(5000)}),
json!({"camera": "iso"}),
json!({"camera": {"distance": -1}}),
json!({"camera": {"distance": 1e300}}),
json!({"camera": {"pitch": 4}}),
json!({"camera": {"fov": 9}}),
json!({"camera": {"target": [1, 2]}}),
json!({"camera": {"fit": true}}),
json!({"grid": "no"}),
json!({"axes": 1}),
json!({"study": null}),
json!({"study": "Nope"}),
json!({"study": null, "joint": "Rail"}),
// 4096 × 4096 frames: a GIF holds four of them.
json!({"width": 4096, "height": 4096, "samples": 5}),
] {
assert!(refused(change.clone()).is_some(), "{change} was accepted");
}
let e = refused(json!({"width": 4096, "height": 4096, "samples": 5})).unwrap();
assert!(e.contains("2…4 for 4096 × 4096"), "{e}");
assert!(super::animation::export_with(&s, &base, None).unwrap_err().to_string().contains("no renderer"));
assert!(!std::path::Path::new(&gif).exists(), "nothing refused was written");
// An agent's export lands only inside its folders.
let root = dir.join("root");
std::fs::create_dir_all(&root).unwrap();
solidcraft_io::vfs::scoped(Some(solidcraft_io::vfs::PathScope::new([root.clone()])), || {
let e = refused(json!({"path": dir.join("out").to_string_lossy()})).unwrap();
assert!(e.contains("outside the folders this agent may use"), "{e}");
assert!(refused(json!({"path": root.join("in.gif").to_string_lossy()})).is_none());
});
assert!(root.join("in.gif").exists() && !dir.join("out").exists());
let _ = std::fs::remove_dir_all(&dir);
}
+16
View File
@@ -66,6 +66,22 @@ fn instance_selection_survives_rename_move_capture_and_serde() {
assert_eq!(roundtrip, s.selection);
}
#[test]
fn component_rename_carries_into_placement_names() {
// #1665: the browser row shows the placement's name, so a rename has to reach it.
let mut s = Session::default();
let (component, first) = created(&mut s, "Block");
let second = run(&mut s, "occurrence.copy", json!({"component": component, "translate": [20,0,0]}))["occurrence"].as_u64().unwrap();
let third = run(&mut s, "occurrence.copy", json!({"component": component, "translate": [40,0,0]}))["occurrence"].as_u64().unwrap();
let name = |s: &Session, id: u64| s.doc.occurrences.iter().find(|o| o.id == id).unwrap().name.clone();
assert_eq!(name(&s, second), "Block:2");
// A placement named otherwise (an import's own name) keeps it.
s.doc_mut().occurrences.iter_mut().find(|o| o.id == third).unwrap().name = "Blockade:3".into();
run(&mut s, "component.rename", json!({"component": component, "name": "box"}));
assert_eq!([name(&s, first), name(&s, second), name(&s, third)], ["box:1", "box:2", "Blockade:3"]);
assert_eq!(run(&mut s, "component.list", json!({}))["components"][0]["children"][0]["name"], "box:1");
}
#[test]
fn instance_selection_delete_removes_only_selected_instance() {
let mut s = Session::default();
+1 -1
View File
@@ -14,7 +14,7 @@ mod jobs;
pub static COMMANDS: &[CommandSpec] = &[
CommandSpec::new("render.preflight", "Check Render Request", jobs::preflight).noundo().doc_only()
.params("setup?: saved name OR settings?: full RenderSetup; transparent_background?: false; replace?: false. Validates the installed image host and bounded captured product scene without starting work. Stale geometry is rejected. See docs/render-jobs.md"),
.params("setup?: saved name OR settings?: full RenderSetup; integrator?: raster (default) or raytrace; raytrace?: bounded runtime lights/exposure_ev/shadows/reflections/anisotropic_faces options, only with raytrace; environment?: {path: scoped HDR, rotation_radians: 0, intensity: 1, samples: 16}; explicit sRGB/D65 HDR primaries required. Opaque CPU preview with selected mirror/rough-specular reflections and certified planar anisotropy. HDR with rough reflections or anisotropy requires fully metallic selected bodies and all effective faces; unsupported combinations refuse. No MIS, GI or glass/refraction. transparent_background?: false; replace?: false. Optional CPU raytracing requires a raytrace-cpu build and native host, checked before scene capture. Stale geometry is rejected. See docs/render-jobs.md"),
CommandSpec::new("render.start", "Render Image", jobs::start).noundo().doc_only().at("RENDER", "IMAGE").icon("box")
.params("Same request as render.preflight. Captures an immutable product scene and queues a bounded image job. Returns its session-scoped job identity, captured scene_generation and progress. Does not change the design. See docs/render-jobs.md"),
CommandSpec::new("render.status", "Render Progress", jobs::status).noundo().doc_only()
+149
View File
@@ -23,6 +23,31 @@ fn finish(host: &CpuHost) {
panic!("cooperative job did not finish");
}
#[test]
fn missing_image_host_is_rejected_before_stale_scene_capture() {
let mut s = Session::default();
for (command, params) in [
("sketch.create", json!({"plane":"XY"})),
("sketch.rectangle.two_point", json!({"p0":[5,5],"p1":[25,20]})),
("sketch.finish", json!({})),
("solid.extrude", json!({"distance":5})),
("sketch.edit", json!({"sketch":"Sketch1"})),
("sketch.drag", json!({"entity":"l1.start","from":[5,5],"to":[4,5],"live":true})),
] {
s.execute(command, &params).unwrap();
}
assert!(s.model.is_stale());
let doc = s.doc.clone();
let before = (s.revision, s.evaluations, s.is_dirty(), s.undo.len(), s.redo.len());
for command in ["render.preflight", "render.start"] {
let error = s.execute(command, &request()).unwrap_err().to_string();
assert!(error.contains("no image host is installed"), "{error}");
assert!(s.model.is_stale());
assert!(Arc::ptr_eq(&doc, &s.doc));
assert_eq!(before, (s.revision, s.evaluations, s.is_dirty(), s.undo.len(), s.redo.len()));
}
}
#[test]
fn runtime_commands_preserve_document_history_and_evaluation() {
let (mut s, host) = session();
@@ -41,6 +66,46 @@ fn runtime_commands_preserve_document_history_and_evaluation() {
assert_eq!(s.execute("render.cancel", &json!({"job":id})).unwrap()["progress"]["phase"], "completed");
}
#[test]
fn omitted_integrator_remains_raster_and_options_do_not_change_viewport_quality() {
let (mut s, host) = session();
let implicit = s.execute("render.preflight", &request()).unwrap();
let explicit = s.execute("render.preflight", &json!({"integrator":"raster","settings":{"width":16,"height":16}})).unwrap();
assert_eq!(implicit, explicit);
assert_eq!(implicit["request"]["integrator"], "raster");
assert_eq!(implicit["resolved"]["executor"], "cpu-product");
assert!(s.execute("render.preflight", &json!({"raytrace":{"shadows":true}})).is_err());
assert!(s.execute("render.preflight", &json!({"integrator":"quality"})).is_err());
assert_eq!(host.admitted_bytes(), 0);
}
#[cfg(not(feature = "raytrace-cpu"))]
#[test]
fn compiled_out_raytrace_is_rejected_before_scene_capture() {
let (mut s, host) = session();
for (command, params) in [
("sketch.create", json!({"plane":"XY"})),
("sketch.rectangle.two_point", json!({"p0":[5,5],"p1":[25,20]})),
("sketch.finish", json!({})),
("solid.extrude", json!({"distance":5})),
("sketch.edit", json!({"sketch":"Sketch1"})),
("sketch.drag", json!({"entity":"l1.start","from":[5,5],"to":[4,5],"live":true})),
] {
s.execute(command, &params).unwrap();
}
assert!(s.model.is_stale());
let doc = s.doc.clone();
let before = (s.revision, s.evaluations, s.is_dirty(), s.undo.len(), s.redo.len());
for command in ["render.preflight", "render.start"] {
let error = s.execute(command, &json!({"integrator":"raytrace","replace":true})).unwrap_err().to_string();
assert!(error.contains("not compiled in"), "{error}");
assert!(s.model.is_stale());
assert!(Arc::ptr_eq(&doc, &s.doc));
assert_eq!(before, (s.revision, s.evaluations, s.is_dirty(), s.undo.len(), s.redo.len()));
assert_eq!(host.admitted_bytes(), 0);
}
}
#[test]
fn identities_are_isolated_across_documents_scratch_and_new() {
let (mut a, host) = session();
@@ -217,3 +282,87 @@ fn native_start_and_cancel_measure_cached_capture_without_timing_assertions() {
);
assert!(status.progress.phase.terminal());
}
#[cfg(all(feature = "raytrace-cpu", not(target_arch = "wasm32")))]
#[test]
fn native_raytrace_preflight_start_and_frame_preserve_document_and_roundtrip_request() {
let mut s = Session::default();
s.set_render_job_host(Some(CpuHost::for_platform().unwrap())).unwrap();
s.execute("solid.box", &json!({"length":20,"width":15,"height":10})).unwrap();
s.execute("render.scene", &json!({})).unwrap();
let doc = s.doc.clone();
let before = (s.revision, s.evaluations, s.is_dirty(), s.undo.len(), s.redo.len());
let params = json!({"integrator":"raytrace","settings":{"width":32,"height":32},"raytrace":{"preset":"neutral","shadows":true}});
let preflight = s.execute("render.preflight", &params).unwrap();
let request: solidcraft_render::job::ImageRequest = serde_json::from_value(preflight["request"].clone()).unwrap();
assert_eq!(request.integrator, solidcraft_render::job::Integrator::Raytrace);
assert_eq!(preflight["resolved"]["executor"], "cpu-raytrace");
let started = s.execute("render.start", &params).unwrap();
let id: JobId = serde_json::from_value(started["job"].clone()).unwrap();
let handle = s.render_job_handle(id).unwrap();
let status = handle.wait_timeout(std::time::Duration::from_secs(60)).unwrap();
assert_eq!(status.progress.phase, solidcraft_render::job::Phase::Completed);
let frame = handle.frame().unwrap().unwrap();
assert_eq!(frame.info.job, id);
assert_eq!(frame.info.executor.as_str(), "cpu-raytrace");
assert_eq!((frame.info.width, frame.info.height), (32, 32));
assert!(frame.png().starts_with(b"\x89PNG\r\n\x1a\n"));
assert!(Arc::ptr_eq(&doc, &s.doc));
assert_eq!(before, (s.revision, s.evaluations, s.is_dirty(), s.undo.len(), s.redo.len()));
}
#[cfg(all(feature = "raytrace-cpu", not(target_arch = "wasm32")))]
#[test]
fn captured_hdr_input_lights_geometry_after_source_removal_and_preserves_history() {
let host = CpuHost::for_platform().unwrap();
let mut s = Session::default();
s.set_render_job_host(Some(host.clone())).unwrap();
let nonce = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_nanos();
let dir = std::env::temp_dir().join(format!("solidcraft-hdri-{}-{nonce}", std::process::id()));
std::fs::create_dir(&dir).unwrap();
let source = dir.join("original.hdr");
s.execute("solid.box", &json!({"length":20,"width":20,"height":20})).unwrap();
s.execute("render.scene", &json!({})).unwrap();
let bytes = |primaries: &str| {
let mut b = format!("#?RADIANCE\nFORMAT=32-bit_rle_rgbe\n{primaries}\n-Y 2 +X 4\n").into_bytes();
for _ in 0..8 {
b.extend_from_slice(&[128, 64, 32, 129]);
}
b
};
std::fs::write(&source, bytes("")).unwrap();
let params = json!({"integrator":"raytrace","raytrace":{"lights":[]},"settings":{"width":9,"height":9,"background":[13,27,41]},"environment":{"path":source.to_str().unwrap(),"samples":64}});
let doc = s.doc.clone();
let before = (s.revision, s.undo.len(), s.redo.len(), s.is_dirty());
assert!(s.execute("render.preflight", &params).unwrap_err().to_string().contains("primaries"));
assert_eq!(host.admitted_bytes(), 0);
std::fs::write(&source, bytes("PRIMARIES=0.64 0.33 0.30 0.60 0.15 0.06 0.3127 0.3290\n")).unwrap();
let preflight = s.execute("render.preflight", &params).unwrap();
assert_eq!(preflight["environment"]["color_policy"], "explicit_linear_srgb_d65");
assert_eq!(preflight["environment"]["header"]["width"], 4);
assert!(preflight["resolved"]["profile"]["features"].as_array().unwrap().contains(&json!("hdri")));
assert_eq!(preflight["environment"]["source_sha256"].as_array().unwrap().len(), 32);
assert!(!preflight["environment"].to_string().contains(dir.to_str().unwrap()));
assert_eq!(host.admitted_bytes(), 0);
let mut unlit = params.clone();
unlit.as_object_mut().unwrap().remove("environment");
let base = s.execute("render.start", &unlit).unwrap();
let base_id: JobId = serde_json::from_value(base["job"].clone()).unwrap();
let base_handle = s.render_jobs.handle(base_id).unwrap();
base_handle.wait_timeout(std::time::Duration::from_secs(60)).unwrap();
let baseline = base_handle.frame().unwrap().unwrap().png().to_vec();
let reply = s.execute("render.start", &params).unwrap();
assert_eq!(reply["environment"], preflight["environment"]);
let id: JobId = serde_json::from_value(reply["job"].clone()).unwrap();
// Captured bytes remain sufficient after the source disappears.
std::fs::remove_file(source).unwrap();
let handle = s.render_jobs.handle(id).unwrap();
assert_eq!(handle.wait_timeout(std::time::Duration::from_secs(60)).unwrap().progress.phase, solidcraft_render::job::Phase::Completed);
assert_ne!(handle.frame().unwrap().unwrap().png(), baseline.as_slice(), "captured HDR must illuminate actual geometry");
assert_eq!(serde_json::to_value(handle.status().unwrap()).unwrap()["environment"], preflight["environment"]);
let output = dir.join("background.png");
s.execute("render.export", &json!({"job":id,"path":output.to_str().unwrap()})).unwrap();
assert!(std::fs::metadata(output).unwrap().len() > 0);
assert!(Arc::ptr_eq(&doc, &s.doc));
assert_eq!(before, (s.revision, s.undo.len(), s.redo.len(), s.is_dirty()));
std::fs::remove_dir_all(dir).unwrap();
}
+103 -14
View File
@@ -4,24 +4,88 @@ use serde_json::{Value, json};
use solidcraft_doc::render_settings::RenderSetup;
use solidcraft_render::{
RenderOperation, RenderRequest,
job::{ImageRequest, JobId},
job::{ImageRequest, Integrator, JobId, RaytraceOptions},
};
#[derive(Default, Deserialize)]
#[serde(default, deny_unknown_fields)]
struct Start {
integrator: Integrator,
environment: Option<EnvironmentRequest>,
raytrace: Option<RaytraceOptions>,
setup: Option<String>,
settings: Option<RenderSetup>,
transparent_background: bool,
replace: bool,
}
fn prepare(s: &Session, params: &Value, command: &str) -> Result<(Start, solidcraft_render::ProductScene, ImageRequest, Value)> {
#[derive(Deserialize)]
#[serde(default, deny_unknown_fields)]
struct EnvironmentRequest {
path: String,
rotation_radians: f64,
intensity: f64,
samples: u32,
}
impl Default for EnvironmentRequest {
fn default() -> Self {
Self { path: String::new(), rotation_radians: 0.0, intensity: 1.0, samples: 16 }
}
}
type Prepared =
(Start, solidcraft_render::ProductScene, ImageRequest, Value, Option<solidcraft_render::lighting::environment_input::EnvironmentInput>);
fn prepare(s: &Session, params: &Value, command: &str) -> Result<Prepared> {
let input: Start = serde_json::from_value(params.clone()).map_err(|e| bad(command, e.to_string()))?;
if input.setup.is_some() && input.settings.is_some() {
return Err(bad(command, "choose either setup or settings"));
}
// Reject unavailable execution before capturing authoritative product meshes.
// Runtime services are independent of the document and can be checked cold.
let host = s.render_job_host().ok_or_else(|| bad(command, "no image host is installed"))?;
if !host.is_available() {
return Err(bad(command, "image host is unavailable"));
}
host.validate_integrator(input.integrator).map_err(job_error)?;
if input.integrator == Integrator::Raster && input.raytrace.is_some() {
return Err(bad(command, "raytrace options require integrator: raytrace"));
}
if input.integrator == Integrator::Raytrace && input.transparent_background {
return Err(bad(command, "raytrace supports opaque backgrounds only"));
}
if let Some(options) = &input.raytrace {
options.validate().map_err(job_error)?;
}
let environment = if let Some(environment) = &input.environment {
if input.integrator != Integrator::Raytrace
|| environment.path.is_empty()
|| environment.path.len() > 4096
|| environment.path.capacity() > 4096
|| environment.path.chars().any(char::is_control)
{
return Err(bad(command, "environment requires raytrace and a bounded HDR input path"));
}
// The established scoped, bounded file reader and HDR decoder remain the only input path.
let bytes =
solidcraft_io::vfs::read(&environment.path, solidcraft_render::lighting::MAX_HDR_BYTES).map_err(|e| bad(command, e.to_string()))?;
let source = solidcraft_render::lighting::HdrSource::new(bytes).map_err(|e| bad(command, e.to_string()))?;
Some(
solidcraft_render::lighting::environment_input::EnvironmentInput::new(
source,
environment.rotation_radians,
environment.intensity,
environment.samples,
)
.map_err(|e| bad(command, e.to_string()))?,
)
} else {
None
};
let scene = crate::product_scene::extract(s)?;
if environment.is_some() {
input.raytrace.as_ref().unwrap_or(&RaytraceOptions::default()).validate_environment_reflections(&scene).map_err(job_error)?;
}
let settings = if let Some(name) = &input.setup {
s.doc.render.setups.get(name).cloned().ok_or_else(|| bad(command, "no saved render setup with that name"))?
} else if let Some(settings) = &input.settings {
@@ -39,12 +103,17 @@ fn prepare(s: &Session, params: &Value, command: &str) -> Result<(Start, solidcr
if settings.exposure_ev != 0.0 || settings.environment_rotation != 0.0 || settings.environment_intensity != 1.0 {
return Err(bad(command, "exposure and environment controls are not supported by the R4a CPU image executor"));
}
let host = s.render_job_host().ok_or_else(|| bad(command, "no image host is installed"))?;
if !host.is_available() {
return Err(bad(command, "image host is unavailable"));
let descriptor = host.descriptor_for(input.integrator).map_err(job_error)?;
let expected_executor = descriptor.id.clone();
let mut backend = s.render_backend();
backend.executors = vec![descriptor];
let mut features = scene.required_features();
if environment.is_some() {
features.push(solidcraft_render::RenderFeature::Hdri);
}
let environment_info = environment.as_ref().map(|e| e.metadata());
let resolved = solidcraft_render::resolve_request(
&[s.render_backend()],
&[backend],
&RenderRequest {
backend: Some(settings.backend.clone()),
mode: settings.mode,
@@ -52,33 +121,53 @@ fn prepare(s: &Session, params: &Value, command: &str) -> Result<(Start, solidcr
width: u64::from(settings.width),
height: u64::from(settings.height),
format: Some(settings.format),
features: scene.required_features(),
features,
policy: Default::default(),
},
)
.map_err(|e| bad(command, e.to_string()))?;
if resolved.executor.as_str() != "cpu-product" {
if resolved.executor != expected_executor {
return Err(bad(command, "resolved executor is not installed as an image job host"));
}
let request = ImageRequest {
integrator: input.integrator,
raytrace: input.raytrace.clone(),
camera: settings.camera,
width: settings.width,
height: settings.height,
background: settings.background,
transparent_background: input.transparent_background,
};
let admission = solidcraft_render::job::admit(&scene, &request).map_err(job_error)?;
let reply = json!({"resolved":resolved,"admission":admission,"request":request,"scene_generation":s.revision,"host":host.kind(),"transparency":"sorted_alpha_approximation","refraction":false});
Ok((input, scene, request, reply))
let mut admission = solidcraft_render::job::admit(&scene, &request).map_err(job_error)?;
let environment_bytes = environment.as_ref().map_or(Ok(0), |e| e.required_bytes()).map_err(|e| bad(command, e.to_string()))?;
let retained_lights = request.raytrace.as_ref().map_or(Ok(0), |o| o.retained_bytes()).map_err(job_error)?;
let retained_environment =
if environment_info.is_some() { std::mem::size_of::<solidcraft_render::lighting::environment_input::EnvironmentInfo>() as u64 } else { 0 };
let retained_request_bytes = retained_lights.checked_add(retained_environment).ok_or_else(|| bad(command, "request metadata overflow"))?;
admission.estimated_total_bytes = admission
.estimated_total_bytes
.checked_add(environment_bytes)
.and_then(|v| v.checked_add(retained_request_bytes))
.filter(|v| *v <= 384 * 1024 * 1024)
.ok_or_else(|| bad(command, "environment job exceeds per-job memory limit"))?;
admission.preparation_bytes =
admission.preparation_bytes.checked_add(environment_bytes).ok_or_else(|| bad(command, "environment admission overflow"))?;
let transparency = match input.integrator {
Integrator::Raster => "sorted_alpha_approximation",
Integrator::Raytrace => "opaque_only",
};
let reply = json!({"environment":environment_info,"retained_request_bytes":retained_request_bytes,"resolved":resolved,"admission":admission,"request":request,"scene_generation":s.revision,"host":host.kind(),"transparency":transparency,"refraction":false});
Ok((input, scene, request, reply, environment))
}
pub(super) fn preflight(s: &mut Session, params: &Value) -> Result<Value> {
prepare(s, params, "render.preflight").map(|(_, _, _, reply)| reply)
prepare(s, params, "render.preflight").map(|(_, _, _, reply, _)| reply)
}
pub(super) fn start(s: &mut Session, params: &Value) -> Result<Value> {
let (input, scene, request, _) = prepare(s, params, "render.start")?;
let status = s.render_jobs.start(s.revision, scene, request, input.replace).map_err(job_error)?;
let (input, scene, request, _, environment) = prepare(s, params, "render.start")?;
let status = s.render_jobs.start_with_environment(s.revision, scene, request, input.replace, environment).map_err(job_error)?;
Ok(json!(status))
}
+18 -20
View File
@@ -1,6 +1,10 @@
//! A drawing of the visible bodies from a supplied viewport camera. No screen pixels, grid,
//! selection highlights or tessellation diagonals are exported.
#[path = "view_dxf_meshes.rs"]
mod meshes;
#[path = "view_dxf_progress.rs"]
mod progress;
#[path = "view_dxf_projection.rs"]
mod projection;
@@ -46,28 +50,17 @@ fn export(s: &mut Session, p: &Value) -> Result<Value> {
if let Some(path) = path {
solidcraft_io::vfs::check(path).map_err(|e| crate::EngineError::Other(e.to_string()))?;
}
let world = s.world_state();
let mut meshes = Vec::new();
let mut count = 0usize;
for body in world.bodies.iter().filter(|b| s.body_visible(&b.name)) {
let mesh = body.body.reference_display_mesh_angular(tolerance, solidcraft_kernel::DISPLAY_ANGLE)?;
count = count.saturating_add(mesh.triangles.len()).saturating_add(mesh.edges.iter().map(Vec::len).sum::<usize>());
if count > 1_000_000 {
return Err(bad(CMD, "view too complex to export; hide bodies or increase tolerance"));
}
if mesh.triangles.is_empty() {
return Err(bad(CMD, format!("{} has no exportable surface", body.name)));
}
meshes.push(mesh);
}
if meshes.is_empty() {
return Err(bad(CMD, "no visible bodies to export"));
}
let lines = projection::drawing(&meshes, &cam).map_err(|e| bad(CMD, e))?;
let started = std::time::Instant::now();
progress::Stage::new("dxf_meshes", 1).check().map_err(|e| bad(CMD, e))?;
let meshes = meshes::prepare(s, tolerance)?;
let prepare_ms = started.elapsed().as_secs_f64() * 1000.;
let drawing = projection::drawing(&meshes, &cam).map_err(|e| bad(CMD, e))?;
let writing = progress::Stage::new("dxf_write", 1);
writing.check().map_err(|e| bad(CMD, e))?;
let mut visible = 0;
let mut hidden = 0;
let mut entities = Vec::new();
for line in lines {
for line in drawing.lines {
if line.hidden && !dashed {
continue;
}
@@ -86,9 +79,14 @@ fn export(s: &mut Session, p: &Value) -> Result<Value> {
layers.push(DxfLayer { linetype: DxfLinetype::Hidden, ..DxfLayer::new("HIDDEN", 8) });
}
let text = solidcraft_io::write_dxf_drawing(&layers, &entities);
writing.check().map_err(|e| bad(CMD, e))?;
let mut result = json!({"visible":visible,"hidden":hidden,"units":"mm","tolerance":tolerance,"projection":if cam.fov > 0.0 {"perspective"} else {"orthographic"}});
result["stats"] = json!({"bodies":meshes.placements.len(),"shared_meshes":meshes.meshes.len(),"triangles":meshes.triangles,
"mesh_bytes":meshes.bytes,"worker_limit":meshes::WORKERS,"segments":drawing.segments,"occlusion_work":drawing.work,
"prepare_ms":prepare_ms,"projection_ms":drawing.projection_ms,"occlusion_ms":drawing.occlusion_ms});
if let Some(path) = path {
solidcraft_io::vfs::write(path, text.as_bytes()).map_err(|e| crate::EngineError::Other(e.to_string()))?;
solidcraft_io::vfs::check(path).map_err(|e| crate::EngineError::Other(e.to_string()))?;
solidcraft_io::write_atomic(std::path::Path::new(path), text.as_bytes(), false).map_err(|e| crate::EngineError::Other(e.to_string()))?;
result["path"] = json!(path);
} else {
result["dxf"] = json!(text);
+207
View File
@@ -0,0 +1,207 @@
//! Export-only mesh instances. Keep one geometry buffer per unambiguous definition, while
//! retaining the current placed body's edge choices (tangent classification can vary after
//! placement). Never modify the document, fuse parts, or share across separate exports.
use std::collections::BTreeMap;
use std::mem::size_of;
use std::sync::Arc;
use std::sync::atomic::{AtomicUsize, Ordering};
use solidcraft_doc::{IDENTITY, Mat, ModelBody, mat_inverse, mat_mul};
use solidcraft_geom::{Aabb3, Mesh, Vec3};
use solidcraft_kernel::{KernelError, map_with_local_pools};
use super::{CMD, progress::Stage};
use crate::params::bad;
use crate::{Result, Session};
#[cfg(not(target_arch = "wasm32"))]
pub(super) const WORKERS: usize = 8;
#[cfg(target_arch = "wasm32")]
pub(super) const WORKERS: usize = 1;
const MESH_BYTES: usize = 512 * 1024 * 1024;
const MAX_BODIES: usize = 100_000;
pub(super) struct Placement {
pub mesh: usize,
pub transform: Mat,
pub visibility: Vec<bool>,
}
pub(super) struct Scene {
pub meshes: Vec<Arc<Mesh>>,
pub placements: Vec<Placement>,
pub triangles: usize,
pub bytes: usize,
}
struct Group {
first: usize,
inverse: Mat,
}
struct Item<'a> {
body: &'a ModelBody,
group: usize,
keep: bool,
transform: Mat,
}
struct Prepared {
mesh: Option<Arc<Mesh>>,
visibility: Vec<bool>,
triangles: usize,
}
pub(super) fn claim(counter: &AtomicUsize, amount: usize, limit: usize) -> bool {
let mut old = counter.load(Ordering::Relaxed);
loop {
let Some(next) = old.checked_add(amount).filter(|n| *n <= limit) else { return false };
match counter.compare_exchange_weak(old, next, Ordering::Relaxed, Ordering::Relaxed) {
Ok(_) => return true,
Err(current) => old = current,
}
}
}
pub(super) fn buffer_bytes(m: &Mesh) -> usize {
m.positions.capacity() * size_of::<Vec3>()
+ m.normals.capacity() * size_of::<Vec3>()
+ m.triangles.capacity() * size_of::<[u32; 3]>()
+ m.tri_face.capacity() * size_of::<u32>()
+ m.edges.capacity() * size_of::<Vec<Vec3>>()
+ m.edges.iter().map(|e| e.capacity() * size_of::<Vec3>()).sum::<usize>()
+ m.seams.capacity()
+ m.smooth_edges.capacity()
+ m.sharp_edges.capacity()
+ m.edge_faces.capacity() * size_of::<Vec<u32>>()
+ m.edge_faces.iter().map(|e| e.capacity() * size_of::<u32>()).sum::<usize>()
}
fn rigid(m: &Mat) -> bool {
if m.iter().flatten().any(|v| !v.is_finite()) || m.iter().zip([0., 0., 0., 1.]).any(|(c, w)| (c[3] - w).abs() > 1e-10) {
return false;
}
let axes = [Vec3::new(m[0][0], m[0][1], m[0][2]), Vec3::new(m[1][0], m[1][1], m[1][2]), Vec3::new(m[2][0], m[2][1], m[2][2])];
let [x, y, z] = axes;
(x.len2() - 1.).abs() < 1e-9
&& (y.len2() - 1.).abs() < 1e-9
&& (z.len2() - 1.).abs() < 1e-9
&& x.dot(y).abs() < 1e-9
&& x.dot(z).abs() < 1e-9
&& y.dot(z).abs() < 1e-9
&& (x.cross(y).dot(z) - 1.).abs() < 1e-9
}
pub(super) fn prepare(s: &Session, tolerance: f64) -> Result<Scene> {
let world = s.world_state();
let state = s.model.state();
let mut definitions = BTreeMap::new();
for body in &state.bodies {
*definitions.entry((body.component, body.definition_name(), body.feature)).or_insert(0usize) += 1;
}
let mut by_definition = BTreeMap::new();
let mut groups: Vec<Group> = Vec::new();
let mut items = Vec::new();
for (index, body) in world.bodies.iter().enumerate().filter(|(_, b)| s.body_visible(&b.name)) {
if items.len() >= MAX_BODIES {
return Err(bad(CMD, "too many placed bodies to export"));
}
let key = (body.component, body.definition_name(), body.feature);
let unambiguous = definitions.get(&key) == Some(&1);
let reused = unambiguous
.then(|| by_definition.get(&key).copied())
.flatten()
.and_then(|g: usize| groups.get(g).map(|group| (g, mat_mul(&body.source_transform, &group.inverse))))
.filter(|(_, m)| rigid(m));
let (group, transform) = if let Some(reused) = reused {
reused
} else {
let g = groups.len();
groups.push(Group { first: index, inverse: mat_inverse(&body.source_transform).unwrap_or(IDENTITY) });
if unambiguous && mat_inverse(&body.source_transform).is_some() {
by_definition.entry(key).or_insert(g);
}
(g, IDENTITY)
};
let keep = groups.get(group).is_some_and(|g| g.first == index);
items.push(Item { body, group, keep, transform });
}
if items.is_empty() {
return Err(bad(CMD, "no visible bodies to export"));
}
let progress = Stage::new("dxf_meshes", items.len());
let bytes = AtomicUsize::new(0);
let results = map_with_local_pools(&items, WORKERS, |item| {
progress.check().map_err(|e| KernelError::Failed(e.into()))?;
let mut mesh = item.body.body.reference_display_mesh_angular(tolerance, solidcraft_kernel::DISPLAY_ANGLE)?;
if mesh.triangles.is_empty() {
return Err(KernelError::Invalid(format!("{} has no exportable surface", item.body.name)));
}
let visibility = (0..mesh.edges.len()).map(|i| mesh.shaded_edge_visible(i)).collect();
let triangles = mesh.triangles.len();
let mesh = if item.keep {
// These are owned export buffers, not the document's cached mesh. Picking and
// shading data are unused by vector occlusion; edge choices were captured above.
mesh.normals = Vec::new();
mesh.tri_face = Vec::new();
mesh.seams = Vec::new();
mesh.smooth_edges = Vec::new();
mesh.sharp_edges = Vec::new();
mesh.edge_faces = Vec::new();
if !claim(&bytes, buffer_bytes(&mesh), MESH_BYTES) {
return Err(KernelError::Invalid("view exceeds export memory budget; hide bodies or increase tolerance".into()));
}
Some(Arc::new(mesh))
} else {
None
};
progress.advance(1).map_err(|e| KernelError::Failed(e.into()))?;
Ok(Prepared { mesh, visibility, triangles })
});
let mut prepared = results.into_iter().collect::<solidcraft_kernel::Result<Vec<_>>>()?;
let mut meshes: Vec<Option<Arc<Mesh>>> = vec![None; groups.len()];
for (item, p) in items.iter().zip(&mut prepared) {
if let Some(mesh) = p.mesh.take()
&& let Some(slot) = meshes.get_mut(item.group)
{
*slot = Some(mesh);
}
}
let meshes = meshes.into_iter().map(|m| m.ok_or_else(|| bad(CMD, "missing export geometry"))).collect::<Result<Vec<_>>>()?;
let mut placements = Vec::with_capacity(items.len());
let mut triangles = 0usize;
for (item, p) in items.iter().zip(prepared) {
if meshes.get(item.group).is_none_or(|m| m.edges.len() != p.visibility.len()) {
return Err(bad(CMD, "placed edge identity changed"));
}
triangles = triangles.saturating_add(p.triangles);
placements.push(Placement { mesh: item.group, transform: item.transform, visibility: p.visibility });
}
Ok(Scene { meshes, placements, triangles, bytes: bytes.load(Ordering::Relaxed) })
}
pub(super) fn transformed_bounds(mesh: &Mesh, m: &Mat) -> Aabb3 {
let b = mesh.bounds();
let mut out = Aabb3::EMPTY;
for x in [b.min.x, b.max.x] {
for y in [b.min.y, b.max.y] {
for z in [b.min.z, b.max.z] {
out.add(solidcraft_doc::apply_point(m, Vec3::new(x, y, z)));
}
}
}
out
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn only_proper_rigid_placements_share_geometry() {
assert!(rigid(&solidcraft_doc::rigid(Vec3::new(1., 2., 3.), Vec3::ZERO, Vec3::Z, 0.7)));
let mut m = IDENTITY;
m[0][0] = -1.;
assert!(!rigid(&m));
m[0][0] = 2.;
assert!(!rigid(&m));
m[0][0] = f64::NAN;
assert!(!rigid(&m));
}
}
@@ -0,0 +1,35 @@
//! Stage counters shared by the export worker and its bounded computation workers.
use std::sync::{Arc, Mutex};
pub(super) const CANCELLED: &str = "DXF export cancelled";
pub(super) struct Stage {
watch: Option<Arc<dyn solidcraft_kernel::watch::Watch>>,
name: &'static str,
total: usize,
done: Mutex<usize>,
}
impl Stage {
pub fn new(name: &'static str, total: usize) -> Self {
let stage = Self { watch: solidcraft_kernel::watch::current(), name, total: total.max(1), done: Mutex::new(0) };
if let Some(watch) = &stage.watch {
watch.progress(name, 0, stage.total);
}
stage
}
pub fn check(&self) -> Result<(), &'static str> {
if self.watch.as_ref().is_some_and(|w| w.cancelled()) { Err(CANCELLED) } else { Ok(()) }
}
pub fn advance(&self, count: usize) -> Result<(), &'static str> {
self.check()?;
if let Some(watch) = &self.watch {
// Serialize reports as well as increments: eight workers must not report a
// smaller completed count after a larger one.
let mut done = self.done.lock().map_err(|_| "export progress unavailable")?;
*done = done.saturating_add(count).min(self.total);
watch.progress(self.name, *done, self.total);
}
self.check()
}
}
+25 -2
View File
@@ -1,10 +1,27 @@
//! Vector hidden-line removal: intersect each projected edge with triangle half planes and
//! its depth plane, then union occluded parameter intervals. A BVH bounds the candidate work.
use solidcraft_geom::{Aabb3, Mesh, Vec2, Vec3};
#[cfg(test)]
use solidcraft_geom::Mesh;
use solidcraft_geom::{Aabb3, Vec2, Vec3};
use solidcraft_io::{DxfEntity, DxfShape};
use solidcraft_render::Camera;
use std::collections::BTreeMap;
#[path = "view_dxf_scene.rs"]
mod scene;
pub(super) struct Drawing {
pub lines: Vec<Line>,
pub work: usize,
pub segments: usize,
pub projection_ms: f64,
pub occlusion_ms: f64,
}
pub(super) fn drawing(meshes: &super::meshes::Scene, cam: &Camera) -> Result<Drawing, &'static str> {
scene::drawing(meshes, cam)
}
/// Keep the hidden curves connected: restarting a dash on every short chord would make a
/// small circular hole look solid. Degree-two joins continue; junctions end the polyline.
pub(super) fn connect(entities: Vec<DxfEntity>) -> Vec<DxfEntity> {
@@ -50,6 +67,7 @@ pub(super) fn connect(entities: Vec<DxfEntity>) -> Vec<DxfEntity> {
result
}
#[derive(Clone, Debug)]
pub(super) struct Line {
pub a: Vec2,
pub b: Vec2,
@@ -73,15 +91,18 @@ fn overlap(a: &Aabb3, b: &Aabb3) -> bool {
a.min.x <= b.max.x && b.min.x <= a.max.x && a.min.y <= b.max.y && b.min.y <= a.max.y
}
#[cfg(test)]
struct Triangle {
p: [Vec3; 3],
bounds: Aabb3,
}
#[cfg(test)]
struct Tree {
bounds: Aabb3,
children: Option<(Box<Tree>, Box<Tree>)>,
triangles: Vec<Triangle>,
}
#[cfg(test)]
impl Tree {
fn new(mut triangles: Vec<Triangle>) -> Self {
let b = triangles.iter().fold(Aabb3::EMPTY, |b, t| b.union(&t.bounds));
@@ -213,6 +234,7 @@ fn merge_lines(lines: Vec<Line>, eps: f64) -> Vec<Line> {
/// B-rep edges plus curved silhouettes. Triangle adjacency is welded by position because
/// different faces can have different vertex indices along their shared boundary.
#[cfg(test)]
fn edges(mesh: &Mesh, cam: &Camera, eps: f64) -> Vec<(Vec3, Vec3)> {
let mut result = Vec::new();
for (_, e) in mesh.edges.iter().enumerate().filter(|(i, _)| mesh.shaded_edge_visible(*i)) {
@@ -241,7 +263,8 @@ fn edges(mesh: &Mesh, cam: &Camera, eps: f64) -> Vec<(Vec3, Vec3)> {
result
}
pub(super) fn drawing(meshes: &[Mesh], cam: &Camera) -> Result<Vec<Line>, &'static str> {
#[cfg(test)]
fn reference_drawing(meshes: &[Mesh], cam: &Camera) -> Result<Vec<Line>, &'static str> {
let (right, up, back) = cam.basis();
let scale = meshes.iter().fold(Aabb3::EMPTY, |b, m| b.union(&m.bounds())).diagonal().max(1.0);
let eps = scale * 1e-8;
+627
View File
@@ -0,0 +1,627 @@
//! Two levels of occlusion acceleration: an instance tree over projected bounds, and one
//! triangle hierarchy per shared mesh. Per-placement node bounds are small; projected
//! triangle coordinates are evaluated only in visited leaves. Covered line intervals prune
//! subsequent nodes and instances, including the entire query once coverage is complete.
use std::sync::Arc;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::time::Instant;
use solidcraft_doc::apply_point;
use solidcraft_geom::{Aabb3, Mesh, Vec3};
use solidcraft_render::Camera;
use super::super::meshes::{Placement, Scene, WORKERS, claim, transformed_bounds};
use super::super::progress::Stage;
use super::{Drawing, Line, bounds, clip, key, merge_lines, occluded, overlap, xy};
const TOO_COMPLEX: &str = "view exceeds export work budget; hide bodies or increase tolerance";
const MAX_LINES: usize = 1_000_000;
const MAX_SEGMENTS: usize = 4_000_000;
const MAX_SHARED_TRIANGLES: usize = 2_000_000;
const MAX_VIEW_NODES: usize = 256 * 1024 * 1024 / std::mem::size_of::<Aabb3>();
const WORK: usize = 200_000_000;
fn parallel<T: Sync, R: Send>(items: &[T], f: impl Fn(&T) -> Result<R, &'static str> + Sync) -> Result<Vec<R>, &'static str> {
solidcraft_kernel::map_on_threads(items, WORKERS, f).into_iter().map(|r| r.ok_or("export worker failed")?).collect()
}
struct Node {
bounds: Aabb3,
start: usize,
end: usize,
children: Option<(usize, usize)>,
}
struct Bvh {
nodes: Vec<Node>,
ids: Vec<usize>,
}
impl Bvh {
fn new(boxes: &[Aabb3], flat: bool) -> Self {
let mut tree = Self { nodes: Vec::new(), ids: (0..boxes.len()).collect() };
if !boxes.is_empty() {
tree.build(boxes, 0, boxes.len(), flat);
}
tree
}
fn build(&mut self, boxes: &[Aabb3], start: usize, end: usize, flat: bool) -> usize {
let b = self.ids.get(start..end).into_iter().flatten().filter_map(|i| boxes.get(*i)).fold(Aabb3::EMPTY, |b, t| b.union(t));
let index = self.nodes.len();
self.nodes.push(Node { bounds: b, start, end, children: None });
if end - start > 8 {
let size = b.size();
let axis = if !flat && size.z > size.x.max(size.y) {
2
} else if size.x > size.y {
0
} else {
1
};
let value = |i: &usize| {
boxes.get(*i).map(|b| b.center()).map_or(0., |p| match axis {
0 => p.x,
1 => p.y,
_ => p.z,
})
};
let mid = start + (end - start) / 2;
if let Some(ids) = self.ids.get_mut(start..end) {
ids.select_nth_unstable_by(mid - start, |a, b| value(a).total_cmp(&value(b)).then_with(|| a.cmp(b)));
}
let left = self.build(boxes, start, mid, flat);
let right = self.build(boxes, mid, end, flat);
if let Some(node) = self.nodes.get_mut(index) {
node.children = Some((left, right));
}
}
index
}
}
struct Edge {
vertices: [u32; 2],
start: usize,
end: usize,
}
struct Side {
key: [[i64; 3]; 2],
vertices: [u32; 2],
triangle: usize,
}
struct Shared {
mesh: Arc<Mesh>,
tree: Bvh,
edges: Vec<Edge>,
incident: Vec<usize>,
}
impl Shared {
fn new(mesh: &Arc<Mesh>, eps: f64, progress: &Stage) -> Result<Self, &'static str> {
let mut boxes = Vec::with_capacity(mesh.triangles.len());
let mut sides = Vec::new();
for (i, indices) in mesh.triangles.iter().enumerate() {
if i.is_multiple_of(1024) {
progress.check()?;
}
let points = mesh.tri(indices).ok_or("invalid export triangle")?;
if points.iter().any(|p| !p.is_finite()) {
return Err("model contains invalid coordinates");
}
boxes.push(bounds(points));
for (a, b) in [(0, 1), (1, 2), (2, 0)] {
let (Some(pa), Some(pb), Some(ia), Some(ib)) = (points.get(a), points.get(b), indices.get(a), indices.get(b)) else {
return Err("invalid export edge");
};
let (ka, kb) = (key(*pa, eps), key(*pb, eps));
if ka == kb {
continue;
}
let (key, vertices) = if ka < kb { ([ka, kb], [*ia, *ib]) } else { ([kb, ka], [*ib, *ia]) };
sides.push(Side { key, vertices, triangle: i });
}
}
let tree = Bvh::new(&boxes, false);
sides.sort_unstable_by(|a, b| a.key.cmp(&b.key).then_with(|| a.triangle.cmp(&b.triangle)));
let mut edges: Vec<Edge> = Vec::new();
let mut incident = Vec::with_capacity(sides.len());
let mut previous = None;
for side in sides {
if previous != Some(side.key) {
edges.push(Edge { vertices: side.vertices, start: incident.len(), end: incident.len() });
previous = Some(side.key);
}
incident.push(side.triangle);
if let Some(e) = edges.last_mut() {
e.end = incident.len();
}
}
Ok(Self { mesh: mesh.clone(), tree, edges, incident })
}
}
struct View<'a> {
cam: &'a Camera,
right: Vec3,
up: Vec3,
back: Vec3,
}
impl<'a> View<'a> {
fn new(cam: &'a Camera) -> Self {
let (right, up, back) = cam.basis();
Self { cam, right, up, back }
}
fn project(&self, p: Vec3) -> Result<Vec3, &'static str> {
if !p.is_finite() {
return Err("model contains invalid coordinates");
}
let d = p - self.cam.target;
let z = d.dot(self.back);
let projected = if self.cam.fov > 0. {
let w = self.cam.distance - z;
if w <= self.cam.distance * 1e-6 {
return Err("model crosses the camera eye plane; zoom out before exporting");
}
Vec3::new(d.dot(self.right) * self.cam.distance / w, d.dot(self.up) * self.cam.distance / w, 1. / w)
} else {
Vec3::new(d.dot(self.right), d.dot(self.up), z)
};
if !projected.is_finite() || projected.len() > 1e12 {
return Err("projected coordinates exceed the export range");
}
Ok(projected)
}
fn triangle(&self, shared: &Shared, placed: &Placement, id: usize) -> Result<[Vec3; 3], &'static str> {
let indices = shared.mesh.triangles.get(id).ok_or("invalid export triangle")?;
let [a, b, c] = shared.mesh.tri(indices).ok_or("invalid export triangle")?;
Ok([
self.project(apply_point(&placed.transform, a))?,
self.project(apply_point(&placed.transform, b))?,
self.project(apply_point(&placed.transform, c))?,
])
}
}
struct Projected {
nodes: Vec<Aabb3>,
segments: Vec<(Vec3, Vec3)>,
}
impl Projected {
fn new(shared: &Shared, placed: &Placement, view: &View<'_>, eps: f64, segments: &AtomicUsize, progress: &Stage) -> Result<Self, &'static str> {
let mut nodes = vec![Aabb3::EMPTY; shared.tree.nodes.len()];
// Exact projected leaf bounds avoid false near-eye errors from empty corners of a
// rotated model-space box. Interior bounds are just unions of the child bounds.
let mut front = vec![false; shared.mesh.triangles.len()];
for (i, node) in shared.tree.nodes.iter().enumerate().rev() {
if i.is_multiple_of(1024) {
progress.check()?;
}
let mut b = Aabb3::EMPTY;
if let Some((left, right)) = node.children {
b = nodes.get(left).ok_or("invalid export tree")?.union(nodes.get(right).ok_or("invalid export tree")?);
} else {
for id in shared.tree.ids.get(node.start..node.end).ok_or("invalid export tree")? {
let p = view.triangle(shared, placed, *id)?;
b = b.union(&bounds(p));
if let Some(f) = front.get_mut(*id) {
// A positive projective scale preserves the projected winding.
*f = super::cross(xy(p[1] - p[0]), xy(p[2] - p[0])) > 0.;
}
}
}
if let Some(slot) = nodes.get_mut(i) {
*slot = b;
}
}
let mut result = Vec::new();
let mut add = |a: Vec3, b: Vec3| -> Result<(), &'static str> {
let (a, b) = (view.project(apply_point(&placed.transform, a))?, view.project(apply_point(&placed.transform, b))?);
if xy(a).dist(xy(b)) > eps {
if !claim(segments, 1, MAX_SEGMENTS) {
return Err(TOO_COMPLEX);
}
result.push((a, b));
}
Ok(())
};
for (i, edge) in shared.mesh.edges.iter().enumerate() {
if !placed.visibility.get(i).copied().unwrap_or(false) {
continue;
}
for w in edge.windows(2) {
if let (Some(a), Some(b)) = (w.first(), w.get(1)) {
add(*a, *b)?;
}
}
}
for edge in &shared.edges {
let mut positive = false;
let mut negative = false;
for id in shared.incident.get(edge.start..edge.end).ok_or("invalid export adjacency")? {
if front.get(*id).copied().ok_or("invalid export adjacency")? {
positive = true;
} else {
negative = true;
}
}
if (positive && negative) || edge.end - edge.start == 1 {
let a = shared.mesh.positions.get(edge.vertices[0] as usize).ok_or("invalid silhouette")?;
let b = shared.mesh.positions.get(edge.vertices[1] as usize).ok_or("invalid silhouette")?;
add(*a, *b)?;
}
}
Ok(Self { nodes, segments: result })
}
}
/// A sorted union, updated as occluders are found. A node's line interval already covered by
/// nearer triangles cannot change the result and is skipped before visiting its children.
#[derive(Default)]
struct Coverage {
spans: Vec<(f64, f64)>,
}
impl Coverage {
fn contains(&self, lo: f64, hi: f64) -> bool {
self.spans.iter().any(|(a, b)| *a <= lo && *b >= hi)
}
fn add(&mut self, mut lo: f64, mut hi: f64) -> Result<(), &'static str> {
let first = self.spans.partition_point(|(_, b)| *b + 1e-9 < lo);
let mut end = first;
while let Some((a, b)) = self.spans.get(end) {
if *a > hi + 1e-9 {
break;
}
lo = lo.min(*a);
hi = hi.max(*b);
end += 1;
}
if first == end && self.spans.len() >= MAX_LINES / 2 {
return Err(TOO_COMPLEX);
}
self.spans.splice(first..end, [(lo, hi)]);
Ok(())
}
}
fn rectangle(a: Vec3, b: Vec3, box_: &Aabb3) -> Option<(f64, f64)> {
let (mut lo, mut hi) = (0., 1.);
for (v0, v1) in [
(a.x - box_.min.x, b.x - box_.min.x),
(box_.max.x - a.x, box_.max.x - b.x),
(a.y - box_.min.y, b.y - box_.min.y),
(box_.max.y - a.y, box_.max.y - b.y),
] {
if !clip(&mut lo, &mut hi, v0, v1) {
return None;
}
}
Some((lo, hi))
}
struct Budget<'a> {
global: &'a AtomicUsize,
progress: &'a Stage,
local: usize,
spent: usize,
}
impl<'a> Budget<'a> {
fn new(global: &'a AtomicUsize, progress: &'a Stage) -> Self {
Self { global, progress, local: 0, spent: 0 }
}
fn spend(&mut self) -> Result<(), &'static str> {
if self.local == 0 {
self.progress.check()?;
let mut old = self.global.load(Ordering::Relaxed);
loop {
let granted = old.min(4096);
if granted == 0 {
return Err(TOO_COMPLEX);
}
match self.global.compare_exchange_weak(old, old - granted, Ordering::Relaxed, Ordering::Relaxed) {
Ok(_) => {
self.local = granted;
break;
}
Err(current) => old = current,
}
}
}
self.local -= 1;
self.spent += 1;
Ok(())
}
}
struct Query<'a, 'b> {
shared: &'a [Shared],
scene: &'a Scene,
projected: &'a [Projected],
instances: &'a Bvh,
view: &'a View<'a>,
depth_eps: f64,
a: Vec3,
b: Vec3,
bounds: Aabb3,
covered: Coverage,
budget: &'b mut Budget<'a>,
}
impl Query<'_, '_> {
fn relevant(&self, b: &Aabb3) -> bool {
if b.max.z <= self.a.z.min(self.b.z) + self.depth_eps || !overlap(b, &self.bounds) {
return false;
}
rectangle(self.a, self.b, b).is_some_and(|(lo, hi)| !self.covered.contains(lo, hi))
}
fn instance_node(&mut self, index: usize) -> Result<(), &'static str> {
self.budget.spend()?;
let node = self.instances.nodes.get(index).ok_or("invalid instance tree")?;
if !self.relevant(&node.bounds) {
return Ok(());
}
if let Some((left, right)) = node.children {
let depth = |i: usize| self.instances.nodes.get(i).map_or(f64::NEG_INFINITY, |n| n.bounds.max.z);
let (near, far) = if depth(left) >= depth(right) { (left, right) } else { (right, left) };
self.instance_node(near)?;
if !self.covered.contains(0., 1.) {
self.instance_node(far)?;
}
} else {
for id in self.instances.ids.get(node.start..node.end).ok_or("invalid instance tree")? {
self.mesh_node(*id, 0)?;
if self.covered.contains(0., 1.) {
break;
}
}
}
Ok(())
}
fn mesh_node(&mut self, instance: usize, index: usize) -> Result<(), &'static str> {
self.budget.spend()?;
let placed = self.scene.placements.get(instance).ok_or("invalid instance")?;
let shared = self.shared.get(placed.mesh).ok_or("invalid shared geometry")?;
let projected = self.projected.get(instance).ok_or("invalid instance bounds")?;
let b = projected.nodes.get(index).ok_or("invalid mesh tree")?;
if !self.relevant(b) {
return Ok(());
}
let node = shared.tree.nodes.get(index).ok_or("invalid mesh tree")?;
if let Some((left, right)) = node.children {
let depth = |i: usize| projected.nodes.get(i).map_or(f64::NEG_INFINITY, |b| b.max.z);
let (near, far) = if depth(left) >= depth(right) { (left, right) } else { (right, left) };
self.mesh_node(instance, near)?;
if !self.covered.contains(0., 1.) {
self.mesh_node(instance, far)?;
}
} else {
for id in shared.tree.ids.get(node.start..node.end).ok_or("invalid mesh tree")? {
self.budget.spend()?;
let points = self.view.triangle(shared, placed, *id)?;
if let Some((lo, hi)) = occluded(self.a, self.b, points, self.depth_eps) {
self.covered.add(lo, hi)?;
if self.covered.contains(0., 1.) {
break;
}
}
}
}
Ok(())
}
}
pub(super) fn drawing(scene: &Scene, cam: &Camera) -> Result<Drawing, &'static str> {
let start = Instant::now();
let scale = scene
.placements
.iter()
.filter_map(|p| scene.meshes.get(p.mesh).map(|m| transformed_bounds(m, &p.transform)))
.fold(Aabb3::EMPTY, |b, p| b.union(&p))
.diagonal()
.max(1.);
if !scale.is_finite() {
return Err("model contains invalid coordinates");
}
let eps = scale * 1e-8;
// Indexed input can have many triangles but very few positions. Bound adjacency/sort
// scratch space as well as the retained mesh bytes before starting parallel builders.
let unique_triangles = scene.meshes.iter().try_fold(0usize, |n, m| n.checked_add(m.triangles.len()));
if unique_triangles.is_none_or(|n| n > MAX_SHARED_TRIANGLES) {
return Err("view exceeds export memory budget; hide bodies or increase tolerance");
}
let progress = Stage::new("dxf_index", scene.meshes.len());
let shared = parallel(&scene.meshes, |m| {
progress.check()?;
let shared = Shared::new(m, eps, &progress)?;
progress.advance(1)?;
Ok(shared)
})?;
let count = scene.placements.iter().try_fold(0usize, |n, p| n.checked_add(shared.get(p.mesh)?.tree.nodes.len()));
if count.is_none_or(|n| n > MAX_VIEW_NODES) {
return Err("view exceeds export memory budget; hide bodies or increase tolerance");
}
let view = View::new(cam);
let count = AtomicUsize::new(0);
let progress = Stage::new("dxf_projection", scene.placements.len());
let projected = parallel(&scene.placements, |p| {
progress.check()?;
let projected = Projected::new(shared.get(p.mesh).ok_or("missing shared geometry")?, p, &view, eps, &count, &progress)?;
progress.advance(1)?;
Ok(projected)
})?;
let boxes = projected.iter().map(|p| p.nodes.first().copied().unwrap_or(Aabb3::EMPTY)).collect::<Vec<_>>();
let mut instances = Bvh::new(&boxes, true);
// The view is fixed for the entire drawing. Sort the at-most-eight members of each
// instance leaf once, rather than allocating/sorting on every line query.
for node in instances.nodes.iter().filter(|n| n.children.is_none()) {
if let Some(ids) = instances.ids.get_mut(node.start..node.end) {
ids.sort_unstable_by(|a, b| {
boxes
.get(*b)
.map_or(f64::NEG_INFINITY, |b| b.max.z)
.total_cmp(&boxes.get(*a).map_or(f64::NEG_INFINITY, |b| b.max.z))
.then_with(|| a.cmp(b))
});
}
}
let segment_count = count.load(Ordering::Relaxed);
let projection_ms = start.elapsed().as_secs_f64() * 1000.;
let start = Instant::now();
let depth_eps = if cam.fov > 0. { 1e-8 / cam.distance } else { eps };
let global = AtomicUsize::new(WORK);
let output = AtomicUsize::new(0);
let chunks = projected.iter().flat_map(|p| p.segments.chunks(128)).collect::<Vec<_>>();
let progress = Stage::new("dxf_occlusion", segment_count);
let results = parallel(&chunks, |chunk| {
progress.check()?;
let mut budget = Budget::new(&global, &progress);
let mut lines = Vec::new();
for &(a, b) in *chunk {
let mut query = Query {
shared: &shared,
scene,
projected: &projected,
instances: &instances,
view: &view,
depth_eps,
a,
b,
bounds: bounds([a, b]),
covered: Coverage::default(),
budget: &mut budget,
};
query.instance_node(0)?;
let mut cursor = 0.;
let mut emit = |lo: f64, hi: f64, hidden: bool| -> Result<(), &'static str> {
let (p, q) = (xy(a + (b - a) * lo), xy(a + (b - a) * hi));
if p.dist(q) > eps {
if !claim(&output, 1, MAX_LINES) {
return Err(TOO_COMPLEX);
}
lines.push(Line { a: p, b: q, hidden });
}
Ok(())
};
for (lo, hi) in query.covered.spans {
emit(cursor, lo, false)?;
emit(lo, hi, true)?;
cursor = hi;
}
emit(cursor, 1., false)?;
}
progress.advance(chunk.len())?;
Ok((lines, budget.spent))
})?;
let work = results.iter().map(|(_, n)| *n).sum();
let lines = merge_lines(results.into_iter().flat_map(|(lines, _)| lines).collect(), eps);
progress.check()?;
Ok(Drawing { lines, work, segments: segment_count, projection_ms, occlusion_ms: start.elapsed().as_secs_f64() * 1000. })
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn coverage_handles_disjoint_spans_and_early_complete_coverage() {
let mut c = Coverage::default();
c.add(0.4, 0.6).unwrap();
c.add(0., 0.2).unwrap();
assert!(c.contains(0.05, 0.15));
assert!(!c.contains(0., 1.));
c.add(0.2, 0.9).unwrap();
c.add(0.8, 1.).unwrap();
assert_eq!(c.spans, vec![(0., 1.)]);
}
fn box_mesh() -> Mesh {
let mut mesh = Mesh::default();
mesh.positions = vec![
Vec3::new(0., 0., 0.),
Vec3::new(8., 0., 0.),
Vec3::new(8., 6., 0.),
Vec3::new(0., 6., 0.),
Vec3::new(0., 0., 3.),
Vec3::new(8., 0., 3.),
Vec3::new(8., 6., 3.),
Vec3::new(0., 6., 3.),
];
mesh.triangles =
vec![[0, 2, 1], [0, 3, 2], [4, 5, 6], [4, 6, 7], [0, 1, 5], [0, 5, 4], [1, 2, 6], [1, 6, 5], [2, 3, 7], [2, 7, 6], [3, 0, 4], [3, 4, 7]];
mesh.edges = [(0, 1), (1, 2), (2, 3), (3, 0), (4, 5), (5, 6), (6, 7), (7, 4), (0, 4), (1, 5), (2, 6), (3, 7)]
.into_iter()
.map(|(a, b)| vec![mesh.positions[a], mesh.positions[b]])
.collect();
mesh
}
fn canonical(lines: Vec<Line>) -> Vec<([i64; 2], [i64; 2], bool)> {
let k = |p: solidcraft_geom::Vec2| [(p.x * 1e6).round() as i64, (p.y * 1e6).round() as i64];
let mut result = lines
.into_iter()
.map(|l| {
let (a, b) = (k(l.a), k(l.b));
if a < b { (a, b, l.hidden) } else { (b, a, l.hidden) }
})
.collect::<Vec<_>>();
result.sort_unstable();
result
}
#[test]
fn shared_rotated_instances_match_flat_occlusion_in_orthographic_and_perspective_views() {
use std::sync::Arc;
let mesh = box_mesh();
let mut placements = Vec::new();
let mut flat = Vec::new();
for (offset, angle) in [(Vec3::ZERO, 0.), (Vec3::new(3., 2., 4.), 0.3), (Vec3::new(2., 1., -4.), -0.6)] {
let transform = solidcraft_doc::rigid(offset, Vec3::ZERO, Vec3::Z, angle);
placements.push(Placement { mesh: 0, transform, visibility: vec![true; mesh.edges.len()] });
let mut placed = mesh.clone();
placed.positions = placed.positions.iter().map(|p| apply_point(&transform, *p)).collect();
placed.edges = placed.edges.iter().map(|e| e.iter().map(|p| apply_point(&transform, *p)).collect()).collect();
flat.push(placed);
}
let scene = Scene { meshes: vec![Arc::new(mesh)], placements, triangles: 36, bytes: 0 };
for (yaw, pitch, roll) in [(0., std::f64::consts::FRAC_PI_2, 0.), (0.7, 0.4, 0.2), (0., 0., 0.)] {
for fov in [0., 0.6] {
let cam = Camera { target: Vec3::new(4., 3., 1.), yaw, pitch, roll, fov, distance: 100., ..Default::default() };
let expected = super::super::reference_drawing(&flat, &cam).unwrap();
let actual = drawing(&scene, &cam).unwrap();
assert_eq!(canonical(actual.lines), canonical(expected), "yaw={yaw}, pitch={pitch}, fov={fov}");
}
}
}
#[test]
fn repeated_surface_over_one_million_triangles_keeps_one_mesh_and_exports_all_placements() {
use solidcraft_render::StandardView;
use std::sync::Arc;
let mut mesh = Mesh::default();
for y in 0..=100 {
for x in 0..=100 {
mesh.positions.push(Vec3::new(x as f64 / 10., y as f64 / 10., 0.));
}
}
for y in 0..100u32 {
for x in 0..100u32 {
let a = y * 101 + x;
mesh.triangles.extend([[a, a + 1, a + 102], [a, a + 102, a + 101]]);
}
}
mesh.edges = vec![
vec![Vec3::ZERO, Vec3::new(10., 0., 0.)],
vec![Vec3::new(10., 0., 0.), Vec3::new(10., 10., 0.)],
vec![Vec3::new(10., 10., 0.), Vec3::new(0., 10., 0.)],
vec![Vec3::new(0., 10., 0.), Vec3::ZERO],
];
let placements = (0..60)
.map(|i| Placement {
mesh: 0,
transform: solidcraft_doc::rigid(Vec3::new((i % 10) as f64 * 20., (i / 10) as f64 * 20., 0.), Vec3::ZERO, Vec3::Z, 0.),
visibility: vec![true; 4],
})
.collect();
let scene = Scene { meshes: vec![Arc::new(mesh)], placements, triangles: 1_200_000, bytes: 0 };
let mut cam = Camera { target: Vec3::new(95., 55., 0.), fov: 0., distance: 300., ..Default::default() };
cam.set_view(StandardView::Top);
let result = drawing(&scene, &cam).unwrap();
assert_eq!(scene.meshes.len(), 1);
assert_eq!(result.lines.len(), 240);
assert!(result.lines.iter().all(|l| !l.hidden));
}
}
+72
View File
@@ -21,6 +21,49 @@ fn export(s: &mut Session, c: Camera, hidden: &str) -> Value {
run(s, CMD, json!({"camera":c,"hidden":hidden}))
}
#[test]
fn view_dxf_cancellation_at_each_stage_preserves_the_destination_and_document() {
use std::sync::{
Arc,
atomic::{AtomicBool, Ordering},
};
struct CancelAt {
stage: &'static str,
cancelled: AtomicBool,
reached: AtomicBool,
}
impl solidcraft_kernel::watch::Watch for CancelAt {
fn cancelled(&self) -> bool {
self.cancelled.load(Ordering::Relaxed)
}
fn progress(&self, stage: &'static str, done: usize, _total: usize) {
if stage == self.stage && (done > 0 || stage == "dxf_write") {
self.reached.store(true, Ordering::Relaxed);
self.cancelled.store(true, Ordering::Relaxed);
}
}
}
let dir = std::env::temp_dir().join(format!("solidcraft-dxf-cancel-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let path = dir.join("drawing.dxf");
let mut s = sample();
let doc = s.doc.clone();
let undo = s.undo.len();
for stage in ["dxf_meshes", "dxf_index", "dxf_projection", "dxf_occlusion", "dxf_write"] {
std::fs::write(&path, b"previous drawing").unwrap();
let watch = Arc::new(CancelAt { stage, cancelled: AtomicBool::new(false), reached: AtomicBool::new(false) });
let result = solidcraft_kernel::watch::watching(watch.clone(), || {
s.execute(CMD, &json!({"camera":camera(StandardView::Top),"path":path.to_string_lossy()}))
});
assert!(result.unwrap_err().to_string().contains("cancelled"), "{stage}");
assert!(watch.reached.load(Ordering::Relaxed), "{stage}");
assert_eq!(std::fs::read(&path).unwrap(), b"previous drawing", "{stage}");
assert!(Arc::ptr_eq(&doc, &s.doc));
assert_eq!(s.undo.len(), undo);
}
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn view_dxf_blind_back_hole_is_omitted_or_dashed_and_front_hole_is_visible() {
let mut s = sample();
@@ -100,3 +143,32 @@ fn view_dxf_rejects_invalid_options_and_near_eye_geometry_without_panicking() {
c.fov = 4.;
assert!(s.execute(CMD, &json!({"camera":c})).is_err());
}
#[test]
fn view_dxf_keeps_every_occurrence_while_sharing_geometry() {
let mut s = Session::default();
let component = run(&mut s, "component.create", json!({"name":"Repeated part"}))["component"].as_u64().unwrap();
run(&mut s, "solid.box", json!({"length":8,"width":6,"height":3}));
for x in [15., 30.] {
run(&mut s, "occurrence.copy", json!({"component":component,"translate":[x,0,0]}));
}
run(&mut s, "component.activate", json!({"component":0}));
let doc = s.doc.clone();
let result = export(&mut s, camera(StandardView::Top), "dashed");
assert_eq!(result["stats"]["bodies"], 3);
assert_eq!(result["stats"]["shared_meshes"], 1);
assert_eq!(result["stats"]["worker_limit"], meshes::WORKERS);
assert!(result["hidden"].as_u64().unwrap() > 0);
let lines = solidcraft_io::read_dxf(result["dxf"].as_str().unwrap()).unwrap();
let mut centers = std::collections::BTreeSet::new();
for line in lines {
if let solidcraft_io::Geom2::Line(a, b) = line {
// Each translated copy has a visible top perimeter, including the offscreen one.
if (a.y - b.y).abs() > 5.9 {
centers.insert(((a.x + 20.) / 15.).floor() as i64);
}
}
}
assert!(centers.len() >= 3, "{centers:?}");
assert!(std::sync::Arc::ptr_eq(&doc, &s.doc));
}
+3 -2
View File
@@ -77,12 +77,13 @@ impl Jobs {
Ok(())
}
pub(crate) fn start(
pub(crate) fn start_with_environment(
&mut self,
revision: u64,
scene: solidcraft_render::ProductScene,
request: solidcraft_render::job::ImageRequest,
replace: bool,
environment: Option<solidcraft_render::lighting::environment_input::EnvironmentInput>,
) -> Result<JobStatus, JobError> {
self.collect()?;
let host = self.host.as_ref().ok_or_else(|| JobError::new(ErrorCode::HostUnavailable, "no image host is installed"))?.clone();
@@ -109,7 +110,7 @@ impl Jobs {
}
let serial = self.serial.checked_add(1).ok_or_else(|| JobError::new(ErrorCode::LimitExceeded, "render job identity exhausted"))?;
let generation = self.generation.checked_add(1).ok_or_else(|| JobError::new(ErrorCode::LimitExceeded, "render generation exhausted"))?;
let handle = host.submit(JobId { session: self.owner, serial, generation }, revision, scene, request)?;
let handle = host.submit_with_environment(JobId { session: self.owner, serial, generation }, revision, scene, request, environment)?;
let status = handle.status()?;
self.serial = serial;
self.generation = generation;
+96
View File
@@ -512,6 +512,30 @@ fn revolve_and_primitives() {
assert!(rel(m["total"]["volume_mm3"].as_f64().unwrap(), PI * 125.0 * 5.0 / 2.0) < 5e-4);
}
/// #726: a revolve swept each profile edge into two or three patches and left the planar ones
/// apart, so a pick on such a face took part of it, and a sketch or an extrude there was refused
/// ("the selected planar face no longer exists") until a later feature merged them.
#[test]
fn revolved_planar_faces_come_out_whole() {
for angle in [360, 240] {
let mut s = Session::default();
run(&mut s, "sketch.create", json!({"plane": "XZ"}));
run(&mut s, "sketch.line", json!({"points": [[8, 0], [30, 0], [30, -6], [18, -6], [18, -22], [8, -22]], "closed": true}));
run(&mut s, "sketch.finish", json!({}));
run(&mut s, "solid.revolve", json!({"axis": "Z", "angle": angle}));
// Picks at 170°, in the last patch, which 240° covers whichever way it turns.
let at = |r: f64, z: f64| json!([r * 170f64.to_radians().cos(), r * 170f64.to_radians().sin(), z]);
// The flange's top annulus (z = 6, r 18…30), well inside it.
let sk = run(&mut s, "sketch.create", json!({"plane": {"face": at(24.0, 6.0)}}));
assert_eq!(sk["attachment"], "exact_face", "{angle}°: {sk}");
run(&mut s, "sketch.finish", json!({}));
// The bottom annulus (z = 0, r 8…30).
let v = volume(&mut s);
run(&mut s, "solid.extrude", json!({"face": at(20.0, 0.0), "distance": 2, "operation": "join"}));
assert!(volume(&mut s) > v + 1.0, "{angle}°: the extrude added nothing");
}
}
/// A spherical shell (a half ring between two arcs, both radial lines on the axis) revolved on a
/// sketch plane that does not pass through the origin: the body is the shell, as it is on XY.
/// Before, built in place, it measured a third too large (truck tessellates the degenerate faces
@@ -1196,6 +1220,43 @@ fn extrude_auto_operation() {
assert!(rel(volume(&mut s), 40.0 * 30.0 * 15.0 - 100.0 * 8.0) < 1e-6);
}
/// #1666: a loft between two 18-point polylines has twisted (bilinear) side faces. Each was
/// meshed as two flat triangles, which cross the surface; the mesh volume was 16 800.6 mm³
/// against the B-rep's 17 884. Divided to the chord tolerance, the mesh matches the B-rep.
#[test]
fn twisted_ruled_faces_are_meshed_to_the_chord_tolerance() {
let mut s = Session::default();
run(&mut s, "sketch.create", json!({"plane": "XY", "name": "Bottom"}));
run(
&mut s,
"sketch.line",
json!({"closed": true, "infer": false, "connect": false, "points": [[-26,3],[-24.76384,3],[-16.0568,14.97217],[-8,4.90117],[0,14.90117],[8,4.90117],[16.0568,14.97217],[24.76384,3],[26,3],[26,0],[23.23616,0],[15.9432,10.02783],[8,0.09883],[0,10.09883],[-8,0.09883],[-15.9432,10.02783],[-23.23616,0],[-26,0]]}),
);
run(&mut s, "sketch.finish", json!({}));
run(&mut s, "sketch.create", json!({"plane": "XY", "offset": 90.5, "name": "Top"}));
run(
&mut s,
"sketch.line",
json!({"closed": true, "infer": false, "connect": false, "points": [[-26,3],[-24,3],[-16,3],[-8,3],[0,3],[8,3],[16,3],[24,3],[26,3],[26,0],[24,0],[16,0],[8,0],[0,0],[-8,0],[-16,0],[-24,0],[-26,0]]}),
);
run(&mut s, "sketch.finish", json!({}));
run(&mut s, "solid.loft", json!({"sections": [{"sketch": "Bottom"}, {"sketch": "Top"}], "operation": "new"}));
let st = s.model.state();
let body = &st.bodies.first().unwrap().body;
let exact = solidcraft_kernel::measure(body).unwrap().volume;
let mesh = body.tessellate(0.05).unwrap();
let volume: f64 = mesh
.triangles
.iter()
.map(|t| {
let p = |i: u32| mesh.positions[i as usize];
p(t[0]).dot(p(t[1]).cross(p(t[2]))) / 6.0
})
.sum();
assert!(mesh.triangles.len() > 72, "the twisted faces are divided: {} triangles", mesh.triangles.len());
assert!(rel(volume.abs(), exact) < 2e-3, "mesh {volume} against B-rep {exact}");
}
/// #1633: to an object, the extrude goes to it on whichever side it is, whatever its
/// `direction`: through the body to its far face is a Cut, out to something above is a Join.
#[test]
@@ -1217,6 +1278,41 @@ fn extrude_auto_operation_follows_the_to_object() {
assert_eq!(extrude_reach(&s, &json!({"face": [20, 15, 20], "distance": 5, "direction": "negative"})), Some(-5.0));
}
/// #1678: a hole's `position` takes length expressions, keeps them and follows the parameters: a
/// hole on a plate's middle line stays there when the plate gets wider. A position of plain
/// numbers is stored as before, with no `at`.
#[test]
fn a_hole_position_of_expressions_follows_the_parameters() {
let mut s = Session::default();
run(&mut s, "parameters.add", json!({"name": "width", "expression": "30 mm"}));
run(&mut s, "parameters.add", json!({"name": "t", "expression": "4 mm"}));
run(&mut s, "solid.box", json!({"length": 100, "width": "width", "height": "t", "body_name": "Plate"}));
run(&mut s, "solid.hole", json!({"position": ["40", "width/2", "t"], "clearance": "M5", "name": "Middle"}));
run(&mut s, "solid.hole", json!({"position": [80, 10, 4], "clearance": "M5", "name": "Fixed"}));
let centre_y = |s: &Session| {
let st = s.model.state();
solidcraft_kernel::measure(&st.body("Plate").unwrap().body).unwrap().centroid.y
};
let hole = |s: &Session, name: &str| -> Value {
let saved: Value = serde_json::from_str(&s.doc.to_json()).unwrap();
saved["features"].as_array().and_then(|f| f.iter().find(|f| f["name"] == name)).cloned().unwrap()
};
assert_eq!(hole(&s, "Middle")["at"], json!([40.0, "width/2", "t"]), "the expressions are kept");
assert!(hole(&s, "Fixed").get("at").is_none(), "plain numbers are stored as before");
// The fixed hole sits off the middle line, so it alone moves the centre; widen the plate.
let before = centre_y(&s);
run(&mut s, "parameters.change", json!({"name": "width", "expression": "40 mm"}));
let after = centre_y(&s);
// The middle hole is at y = 20 now (the plate's middle); the fixed one stays at y = 10. With
// the middle hole left at y = 15 the centre would sit lower still.
let plate = 100.0 * 40.0 * 4.0;
let hole_v = std::f64::consts::PI * (5.5f64 / 2.0).powi(2) * 4.0;
let want = (plate * 20.0 - hole_v * 20.0 - hole_v * 10.0) / (plate - 2.0 * hole_v);
assert!((after - want).abs() < 1e-3, "centre y {after}, want {want} (was {before})");
// A bad expression is refused.
assert!(s.execute("solid.hole", &json!({"position": ["40", "nope/2", "t"], "diameter": 3})).is_err());
}
/// Additive extrusions default to joining even when only a profile side touches material.
#[test]
fn auto_extrude_joins_side_contact_elbow_and_keeps_new_body_explicit() {
+12
View File
@@ -22,6 +22,18 @@ fn volume(s: &mut Session, b: &str) -> f64 {
const SIZES: [(f64, f64); 9] = [(3.0, 0.5), (4.0, 0.7), (5.0, 0.8), (6.0, 1.0), (8.0, 1.25), (10.0, 1.5), (12.0, 1.75), (16.0, 2.0), (20.0, 2.5)];
#[test]
fn non_finite_thread_designations_are_refused_without_changing_the_design() {
let mut s = Session::default();
run(&mut s, "solid.cylinder", json!({"radius":4,"height":10}));
let saved = s.doc.to_json();
for designation in ["Minfx1", "M8xinf", "MNaNx1", "M8xNaN", "M1e999x1"] {
let result = s.execute("solid.thread", &json!({"face":[4,0,2],"designation":designation}));
assert!(result.is_err(), "{designation}: {result:?}");
assert_eq!(s.doc.to_json(), saved);
}
}
/// ∫ 2π r · width(r) dr over [a, b]: the volume one turn of the groove takes out (a screw
/// motion of a section in an axial plane sweeps 2π∫r dA per turn).
fn per_turn(a: f64, b: f64, width: impl Fn(f64) -> f64) -> f64 {
@@ -0,0 +1,77 @@
//! Mesh export regressions: a closed body exports as a closed mesh.
use std::collections::HashMap;
use serde_json::{Value, json};
use solidcraft_engine::Session;
use solidcraft_io::{Format, export, read_3mf, read_stl};
fn run(s: &mut Session, script: Value) {
for c in script.as_array().into_iter().flatten() {
let (id, p) = (c["command"].as_str().unwrap_or_default(), &c["params"]);
if let Err(e) = s.execute(id, p) {
panic!("{id} {p}: {e}");
}
}
}
/// The edges (by vertex index) that are not used by exactly two triangles.
fn open_edges(triangles: &[[u32; 3]]) -> Vec<((u32, u32), u32)> {
let mut uses: HashMap<(u32, u32), u32> = HashMap::new();
for t in triangles {
for (a, b) in [(t[0], t[1]), (t[1], t[2]), (t[2], t[0])] {
*uses.entry((a.min(b), a.max(b))).or_default() += 1;
}
}
uses.into_iter().filter(|(_, n)| *n != 2).collect()
}
/// A bowl section (lines and arcs) revolved about Z, its rim cut by a large cylinder across it.
/// The edge where the cylinder meets the inner cone is an intersection curve; one of its samples
/// lay a few ten-thousandths of a millimetre off both surfaces, each face put the point on its
/// own surface, and the exported mesh had a crack there (four edges used once).
#[test]
fn a_rim_cut_by_a_cylinder_exports_closed() {
let mut s = Session::default();
run(
&mut s,
json!([
{"command": "sketch.create", "params": {"plane": "XZ", "name": "Section"}},
{"command": "sketch.line", "params": {"points": [[0, 0], [48.8, 0], [50.0240096077, -1.2]]}},
{"command": "sketch.arc.three_point", "params": {"start": [50.0240096077, -1.2], "end": [58.7867965644, -21.2132034356], "through": [52.5188160894, -12.0326443841]}},
{"command": "sketch.line", "params": {"points": [[58.7867965644, -21.2132034356], [85.5735931288, -48], [82.1794805791, -48], [57.0897402896, -22.9102597104]]}},
{"command": "sketch.arc.three_point", "params": {"start": [57.0897402896, -22.9102597104], "end": [48.3846976331, -7.0875], "through": [51.6125175266, -15.6176451113]}},
{"command": "sketch.arc.three_point", "params": {"start": [48.3846976331, -7.0875], "end": [42.5300120096, -2.4], "through": [46.2800120096, -3.7162515012]}},
{"command": "sketch.line", "params": {"points": [[42.5300120096, -2.4], [0, -2.4], [0, 0]]}},
{"command": "sketch.finish", "params": {}},
{"command": "solid.revolve", "params": {"sketch": "Section", "axis": "Z"}},
{"command": "sketch.create", "params": {"plane": "YZ", "name": "RimCutter"}},
{"command": "sketch.arc.three_point", "params": {"start": [-100, 11.6204810674], "end": [100, 46.4045454912], "through": [-52, 8]}},
{"command": "sketch.line", "params": {"points": [[100, 46.4045454912], [100, 70], [-100, 70], [-100, 11.6204810674]]}},
{"command": "sketch.finish", "params": {}},
{"command": "solid.extrude", "params": {"sketch": "RimCutter", "distance": 200, "direction": "symmetric", "operation": "cut"}}
]),
);
let st = s.model.state();
assert_eq!(st.bodies.len(), 1);
let (objects, _) = read_3mf(&export(&st, &[], Format::ThreeMf, "cove").unwrap()).unwrap();
assert_eq!(objects.len(), 1);
let open = open_edges(&objects[0].triangles);
assert!(open.is_empty(), "3MF: {} edges not used twice, e.g. {:?}", open.len(), open.first());
// STL has no indices: vertices are the same where their coordinates are.
let mut index: HashMap<[u32; 3], u32> = HashMap::new();
let triangles: Vec<[u32; 3]> = read_stl(&export(&st, &[], Format::StlBinary, "cove").unwrap())
.unwrap()
.iter()
.map(|t| {
t.map(|p| {
let n = index.len() as u32;
*index.entry(p.map(f32::to_bits)).or_insert(n)
})
})
.collect();
let open = open_edges(&triangles);
assert!(open.is_empty(), "STL: {} edges not used twice, e.g. {:?}", open.len(), open.first());
}
+270
View File
@@ -0,0 +1,270 @@
//! A bounding volume hierarchy over boxes: the nearest hit along a ray, or every item whose box
//! passes a test, without looking at each item. Built once (median split on the widest axis of
//! the box centres, a few items per leaf) and only read afterwards. [`MeshIndex`] holds one over
//! a mesh's triangles and one over its edge segments, for picking.
use crate::{Aabb3, Mesh, Vec3};
/// Most items in a leaf.
const LEAF: usize = 4;
#[derive(Clone, Copy, Debug)]
struct Node {
bounds: Aabb3,
/// A leaf: the first of its `count` items in [`Bvh::order`]. Otherwise its children are
/// `first` and `first + 1`.
first: u32,
count: u32,
}
/// A hierarchy over boxes; items are the boxes' indices.
#[derive(Clone, Debug, Default)]
pub struct Bvh {
nodes: Vec<Node>,
order: Vec<u32>,
}
impl Bvh {
/// The hierarchy over `boxes` (empty boxes are left out).
pub fn new(boxes: &[Aabb3]) -> Bvh {
let mut order: Vec<u32> =
(0..boxes.len().min(u32::MAX as usize)).filter(|&i| boxes.get(i).is_some_and(|b| !b.is_empty() && finite(b))).map(|i| i as u32).collect();
if order.is_empty() {
return Bvh::default();
}
let item = |i: u32| boxes.get(i as usize).copied().unwrap_or(Aabb3::EMPTY);
let centre = |i: u32| item(i).center();
let mut nodes = vec![Node { bounds: Aabb3::EMPTY, first: 0, count: 0 }];
// (node, start, end) in `order` still to be filled in.
let mut todo = vec![(0usize, 0usize, order.len())];
while let Some((n, start, end)) = todo.pop() {
let Some(span) = order.get_mut(start..end) else { continue };
let mut bounds = Aabb3::EMPTY;
let mut centres = Aabb3::EMPTY;
for &i in span.iter() {
bounds = bounds.union(&item(i));
centres.add(centre(i));
}
let size = centres.size();
let axis = if size.x >= size.y && size.x >= size.z {
0
} else if size.y >= size.z {
1
} else {
2
};
let extent = [size.x, size.y, size.z][axis];
if span.len() <= LEAF || !(extent > 0.0) {
if let Some(node) = nodes.get_mut(n) {
*node = Node { bounds, first: start as u32, count: span.len() as u32 };
}
continue;
}
let key = |i: &u32| {
let c = centre(*i);
[c.x, c.y, c.z][axis]
};
let mid = span.len() / 2;
span.select_nth_unstable_by(mid, |a, b| key(a).total_cmp(&key(b)));
let left = nodes.len();
nodes.push(Node { bounds: Aabb3::EMPTY, first: 0, count: 0 });
nodes.push(Node { bounds: Aabb3::EMPTY, first: 0, count: 0 });
if let Some(node) = nodes.get_mut(n) {
*node = Node { bounds, first: left as u32, count: 0 };
}
todo.push((left, start, start + mid));
todo.push((left + 1, start + mid, end));
}
Bvh { nodes, order }
}
/// The box around everything (empty for no items).
pub fn bounds(&self) -> Aabb3 {
self.nodes.first().map_or(Aabb3::EMPTY, |n| n.bounds)
}
/// Calls `item` with every item in a leaf whose box, and every box above it, `enter` accepts.
pub fn visit(&self, mut enter: impl FnMut(&Aabb3) -> bool, mut item: impl FnMut(u32)) {
let mut stack = vec![0usize];
while let Some(n) = stack.pop() {
let Some(node) = self.nodes.get(n) else { continue };
if !enter(&node.bounds) {
continue;
}
if node.count > 0 {
let (a, b) = (node.first as usize, node.first as usize + node.count as usize);
for &i in self.order.get(a..b).unwrap_or(&[]) {
item(i);
}
} else {
stack.push(node.first as usize + 1);
stack.push(node.first as usize);
}
}
}
/// The nearest item along the ray from `o` along `d`: `hit` gives an item's distance along
/// `d` (`None`: missed). Equal distances go to the lowest item, as a scan in item order
/// keeping strictly nearer hits would answer. Boxes are entered nearest first, and one that
/// starts past the best hit so far is skipped.
pub fn nearest(&self, o: Vec3, d: Vec3, mut hit: impl FnMut(u32) -> Option<f64>) -> Option<(f64, u32)> {
if ![o.x, o.y, o.z, d.x, d.y, d.z].iter().all(|v| v.is_finite()) {
return None;
}
let inv = Vec3::new(1.0 / d.x, 1.0 / d.y, 1.0 / d.z);
let mut best: Option<(f64, u32)> = None;
let root = self.nodes.first().and_then(|n| ray_box(o, d, inv, &n.bounds, 0.0))?;
let mut stack = vec![(0usize, root)];
while let Some((n, t0)) = stack.pop() {
if best.is_some_and(|(bt, _)| t0 > bt) {
continue;
}
let Some(node) = self.nodes.get(n) else { continue };
if node.count > 0 {
let (a, b) = (node.first as usize, node.first as usize + node.count as usize);
for &i in self.order.get(a..b).unwrap_or(&[]) {
if let Some(t) = hit(i)
&& best.is_none_or(|(bt, bi)| t < bt || (t == bt && i < bi))
{
best = Some((t, i));
}
}
continue;
}
let (l, r) = (node.first as usize, node.first as usize + 1);
let tl = self.nodes.get(l).and_then(|c| ray_box(o, d, inv, &c.bounds, 0.0));
let tr = self.nodes.get(r).and_then(|c| ray_box(o, d, inv, &c.bounds, 0.0));
// The nearer child is popped first.
match (tl, tr) {
(Some(a), Some(b)) if a <= b => stack.extend([(r, b), (l, a)]),
(Some(a), Some(b)) => stack.extend([(l, a), (r, b)]),
(Some(a), None) => stack.push((l, a)),
(None, Some(b)) => stack.push((r, b)),
(None, None) => {}
}
}
best
}
}
fn finite(b: &Aabb3) -> bool {
[b.min.x, b.min.y, b.min.z, b.max.x, b.max.y, b.max.z].iter().all(|v| v.is_finite())
}
/// Where the ray from `o` along `d` (`inv` = 1 / `d` per axis) enters box `b` grown by `pad`,
/// from 0 on; `None` when it misses or the box lies behind.
fn ray_box(o: Vec3, d: Vec3, inv: Vec3, b: &Aabb3, pad: f64) -> Option<f64> {
let (mut t0, mut t1) = (0.0f64, f64::INFINITY);
for (o, d, inv, lo, hi) in [(o.x, d.x, inv.x, b.min.x, b.max.x), (o.y, d.y, inv.y, b.min.y, b.max.y), (o.z, d.z, inv.z, b.min.z, b.max.z)] {
let (lo, hi) = (lo - pad, hi + pad);
if d == 0.0 || !inv.is_finite() {
if o < lo || o > hi {
return None;
}
continue;
}
let (a, b) = ((lo - o) * inv, (hi - o) * inv);
let (a, b) = if a <= b { (a, b) } else { (b, a) };
t0 = t0.max(a);
t1 = t1.min(b);
if t0 > t1 {
return None;
}
}
(t0 <= t1).then_some(t0)
}
/// The farthest any corner of `b` lies along `d` from `o` (0 when the box is behind).
fn farthest_along(o: Vec3, d: Vec3, b: &Aabb3) -> f64 {
let along = |lo: f64, hi: f64, o: f64, d: f64| if d >= 0.0 { (hi - o) * d } else { (lo - o) * d };
(along(b.min.x, b.max.x, o.x, d.x) + along(b.min.y, b.max.y, o.y, d.y) + along(b.min.z, b.max.z, o.z, d.z)).max(0.0)
}
/// A mesh's triangles and edge segments in hierarchies, for picking: the nearest triangle along
/// a ray, and the edge segments near one. Built from one mesh and answers only for it.
#[derive(Clone, Debug, Default)]
pub struct MeshIndex {
triangles: Bvh,
triangle_count: usize,
segments: Bvh,
/// Per segment item: its edge, and its first point in that edge's polyline.
segment_of: Vec<(u32, u32)>,
}
impl MeshIndex {
/// The index of `mesh`.
pub fn new(mesh: &Mesh) -> MeshIndex {
let pad = |mut b: Aabb3| {
// Flat boxes (a triangle square to an axis) are grown a little, so a ray through
// them is never lost to rounding in the box test.
let scale = [b.min.x, b.min.y, b.min.z, b.max.x, b.max.y, b.max.z].iter().fold(1.0f64, |m, v| m.max(v.abs()));
let e = scale * 1e-9;
b.min -= Vec3::new(e, e, e);
b.max += Vec3::new(e, e, e);
b
};
let boxes: Vec<Aabb3> = mesh
.triangles
.iter()
.map(|t| {
let mut b = Aabb3::EMPTY;
for p in mesh.tri(t).into_iter().flatten() {
b.add(p);
}
if b.is_empty() { b } else { pad(b) }
})
.collect();
let mut segment_of = Vec::new();
let mut seg_boxes = Vec::new();
for (ei, e) in mesh.edges.iter().enumerate() {
// A one-point edge still has its vertex: it stands as a segment from it to itself.
let n = if e.len() == 1 { 1 } else { e.len().saturating_sub(1) };
for si in 0..n {
let (Some(a), Some(b)) = (e.get(si), e.get(si + 1).or(e.get(si))) else { continue };
let mut bx = Aabb3::EMPTY;
bx.add(*a);
bx.add(*b);
seg_boxes.push(pad(bx));
segment_of.push((ei as u32, si as u32));
}
}
MeshIndex { triangles: Bvh::new(&boxes), triangle_count: mesh.triangles.len(), segments: Bvh::new(&seg_boxes), segment_of }
}
/// [`Mesh::raycast`] through the index: the same answer, including which triangle wins a tie.
/// For a mesh other than the one indexed, the plain scan answers.
pub fn raycast(&self, mesh: &Mesh, o: Vec3, dir: Vec3) -> Option<(f64, usize)> {
if mesh.triangles.len() != self.triangle_count {
return mesh.raycast(o, dir);
}
let frame = crate::mesh::RayFrame::new(o, dir)?;
self.triangles
.nearest(o, dir, |i| mesh.triangles.get(i as usize).and_then(|t| mesh.tri(t)).and_then(|p| frame.hit(p)))
.map(|(t, i)| (t, i as usize))
}
/// Calls `f(edge, first point)` for every edge segment that may come within `a + b·t` of the
/// ray from `o` along unit `d`, `t` being the distance along it (each at most once). A
/// constant `a` suits an orthographic view; a perspective view widens with `b`.
pub fn segments_near(&self, o: Vec3, d: Vec3, a: f64, b: f64, mut f: impl FnMut(usize, usize)) {
if ![a, b, o.x, o.y, o.z, d.x, d.y, d.z].iter().all(|v| v.is_finite()) {
return;
}
let inv = Vec3::new(1.0 / d.x, 1.0 / d.y, 1.0 / d.z);
self.segments.visit(
|bx| {
let reach = a.max(0.0) + b.max(0.0) * farthest_along(o, d, bx);
ray_box(o, d, inv, bx, reach).is_some()
},
|i| {
if let Some((e, s)) = self.segment_of.get(i as usize) {
f(*e as usize, *s as usize);
}
},
);
}
}
#[cfg(test)]
#[path = "bvh_tests.rs"]
mod tests;
+130
View File
@@ -0,0 +1,130 @@
use super::*;
/// A small deterministic generator (the tests need no crate for randomness).
struct Lcg(u64);
impl Lcg {
fn next(&mut self) -> f64 {
self.0 = self.0.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407);
(self.0 >> 11) as f64 / (1u64 << 53) as f64
}
fn range(&mut self, lo: f64, hi: f64) -> f64 {
lo + (hi - lo) * self.next()
}
fn vec(&mut self, r: f64) -> Vec3 {
Vec3::new(self.range(-r, r), self.range(-r, r), self.range(-r, r))
}
}
/// A grid of `n` × `n` squares of two triangles on z = 0, and `extra` random triangles above.
fn mesh(n: u32, extra: usize, rng: &mut Lcg) -> Mesh {
let mut positions: Vec<Vec3> = (0..=n).flat_map(|j| (0..=n).map(move |i| Vec3::new(f64::from(i), f64::from(j), 0.0))).collect();
let id = |i: u32, j: u32| j * (n + 1) + i;
let mut triangles = Vec::new();
for j in 0..n {
for i in 0..n {
triangles.push([id(i, j), id(i + 1, j), id(i + 1, j + 1)]);
triangles.push([id(i, j), id(i + 1, j + 1), id(i, j + 1)]);
}
}
for _ in 0..extra {
let c = rng.vec(f64::from(n)) + Vec3::new(0.0, 0.0, f64::from(n));
let k = positions.len() as u32;
positions.extend([c + rng.vec(1.5), c + rng.vec(1.5), c + rng.vec(1.5)]);
triangles.push([k, k + 1, k + 2]);
}
let edges =
(0..n).map(|i| (0..=n).map(|j| Vec3::new(f64::from(i), f64::from(j), 0.0)).collect()).chain([vec![Vec3::new(0.5, 0.5, 2.0)]]).collect();
Mesh { tri_face: vec![0; triangles.len()], positions, triangles, edges, ..Default::default() }
}
#[test]
fn indexed_raycast_answers_as_the_scan_does() {
let mut rng = Lcg(7);
let m = mesh(12, 400, &mut rng);
let index = MeshIndex::new(&m);
let mut hits = 0;
for k in 0..4000 {
// Every few rays go straight down through grid vertices and edges, where two or more
// triangles tie.
let (o, d) = if k % 4 == 0 {
let p = Vec3::new(f64::from(k % 13), f64::from((k / 13) % 13) * 0.5, 50.0);
(p, Vec3::new(0.0, 0.0, -1.0))
} else {
let o = rng.vec(40.0) + Vec3::new(6.0, 6.0, 0.0);
let target = Vec3::new(rng.range(-1.0, 13.0), rng.range(-1.0, 13.0), rng.range(-2.0, 14.0));
let Some(d) = (target - o).normalized() else { continue };
(o, d)
};
let want = m.raycast(o, d);
assert_eq!(index.raycast(&m, o, d), want, "ray {k} from {o:?} along {d:?}");
hits += usize::from(want.is_some());
}
assert!(hits > 1000, "the rays should mostly hit ({hits})");
}
#[test]
fn indexed_raycast_of_another_mesh_falls_back_to_the_scan() {
let mut rng = Lcg(3);
let (a, b) = (mesh(2, 0, &mut rng), mesh(5, 0, &mut rng));
let index = MeshIndex::new(&a);
let (o, d) = (Vec3::new(4.5, 4.2, 9.0), Vec3::new(0.0, 0.0, -1.0));
assert!(b.raycast(o, d).is_some());
assert_eq!(index.raycast(&b, o, d), b.raycast(o, d));
}
/// Distance from point `p` to the ray from `o` along unit `d` (from its start on), and how far along.
fn ray_point(o: Vec3, d: Vec3, p: Vec3) -> (f64, f64) {
let t = (p - o).dot(d).max(0.0);
((o + d * t).dist(p), t)
}
#[test]
fn segments_near_the_ray_are_all_reported() {
let mut rng = Lcg(11);
let m = mesh(16, 0, &mut rng);
let index = MeshIndex::new(&m);
for k in 0..500 {
let o = rng.vec(30.0) + Vec3::new(8.0, 8.0, 30.0);
let target = Vec3::new(rng.range(0.0, 16.0), rng.range(0.0, 16.0), 0.0);
let Some(d) = (target - o).normalized() else { continue };
let (a, b) = if k % 2 == 0 { (0.3, 0.0) } else { (0.0, 0.01) };
let mut got = std::collections::HashSet::new();
index.segments_near(o, d, a, b, |e, s| {
assert!(got.insert((e, s)), "segment {e}/{s} reported twice");
});
for (ei, e) in m.edges.iter().enumerate() {
for (si, w) in e.windows(2).enumerate() {
// Sampled along the segment: any point within reach must have its segment reported.
for f in 0..=8 {
let p = w[0] + (w[1] - w[0]) * (f64::from(f) / 8.0);
let (dist, t) = ray_point(o, d, p);
if dist <= a + b * t {
assert!(got.contains(&(ei, si)), "ray {k}: segment {ei}/{si} is within reach but was not reported");
}
}
}
}
// The one-point edge stands as its own segment.
let last = m.edges.len() - 1;
let (dist, t) = ray_point(o, d, Vec3::new(0.5, 0.5, 2.0));
if dist <= a + b * t {
assert!(got.contains(&(last, 0)));
}
}
}
#[test]
fn hostile_boxes_never_panic() {
let nan = Vec3::new(f64::NAN, 0.0, 0.0);
let boxes = [Aabb3::EMPTY, Aabb3 { min: nan, max: nan }, Aabb3 { min: Vec3::ZERO, max: Vec3::new(1.0, 1.0, 1.0) }];
let bvh = Bvh::new(&boxes);
assert_eq!(bvh.nearest(Vec3::new(0.5, 0.5, 5.0), Vec3::new(0.0, 0.0, -1.0), |i| Some(f64::from(i))), Some((2.0, 2)));
assert_eq!(bvh.nearest(Vec3::ZERO, Vec3::new(f64::NAN, 0.0, 0.0), |_| Some(1.0)), None);
let empty = Bvh::new(&[]);
assert!(empty.nearest(Vec3::ZERO, Vec3::new(0.0, 0.0, 1.0), |_| Some(1.0)).is_none());
empty.visit(|_| true, |_| panic!("an empty hierarchy has no items"));
let m = Mesh { positions: vec![Vec3::ZERO], triangles: vec![[0, 5, 9]], ..Default::default() };
assert!(MeshIndex::new(&m).raycast(&m, Vec3::new(0.0, 0.0, 1.0), Vec3::new(0.0, 0.0, -1.0)).is_none());
MeshIndex::new(&m).segments_near(Vec3::ZERO, Vec3::new(0.0, 0.0, 1.0), f64::NAN, 0.0, |_, _| panic!("no segments"));
}
+2
View File
@@ -12,6 +12,7 @@ mod arcfit;
pub mod blend;
pub mod brep;
pub mod bspline;
mod bvh;
pub mod compare;
pub mod env;
pub mod fill;
@@ -25,6 +26,7 @@ mod vec;
pub use arcfit::MAX_FIT_PIECES;
pub use blend::hermite_bezier;
pub use bvh::{Bvh, MeshIndex};
pub use mesh::{Aabb3, BoxedTriangle, InsideIndex, MassProperties, Mesh, MeshMeasure, find_close_pair};
pub use plane::Plane;
pub use profile::{Loop2, MAX_BEZIER_CTRL, MAX_BEZIER_DEGREE, MAX_DERIVATIVE_ORDER, Region2, Seg2, bezier, regions_apart};
+57 -33
View File
@@ -559,13 +559,39 @@ impl Mesh {
/// two triangles that share an edge get exactly opposite values there. A ray through a
/// shared edge or vertex hits at least one of them; it never slips between them.
pub fn raycast(&self, o: Vec3, dir: Vec3) -> Option<(f64, usize)> {
let comp = |v: Vec3, k: usize| match k {
0 => v.x,
1 => v.y,
_ => v.z,
};
// The ray's dominant axis becomes z; x and y follow it cyclically, swapped to keep
// the frame right-handed when the ray runs towards −z.
let frame = RayFrame::new(o, dir)?;
let mut best: Option<(f64, usize)> = None;
for (i, t) in self.triangles.iter().enumerate() {
let Some(p) = self.tri(t) else { continue };
if let Some(t) = frame.hit(p)
&& best.is_none_or(|(bt, _)| t < bt)
{
best = Some((t, i));
}
}
best
}
}
/// A ray in the frame of [`Mesh::raycast`]'s watertight test: its dominant axis becomes z; x and
/// y follow it cyclically, swapped to keep the frame right-handed when the ray runs towards −z.
pub(crate) struct RayFrame {
o: Vec3,
k: [usize; 3],
s: [f64; 3],
}
fn comp(v: Vec3, k: usize) -> f64 {
match k {
0 => v.x,
1 => v.y,
_ => v.z,
}
}
impl RayFrame {
/// `None` for a direction that is zero or not finite.
pub(crate) fn new(o: Vec3, dir: Vec3) -> Option<RayFrame> {
let a = [dir.x.abs(), dir.y.abs(), dir.z.abs()];
let kz = if a[0] >= a[1] && a[0] >= a[2] {
0
@@ -582,33 +608,31 @@ impl Mesh {
if dz < 0.0 {
std::mem::swap(&mut kx, &mut ky);
}
let (sx, sy, sz) = (comp(dir, kx) / dz, comp(dir, ky) / dz, 1.0 / dz);
// A vertex in the ray's frame: (x, y) across the ray, z scaled along it.
let frame = |p: Vec3| {
let q = p - o;
let z = comp(q, kz);
(comp(q, kx) - sx * z, comp(q, ky) - sy * z, sz * z)
};
let mut best: Option<(f64, usize)> = None;
for (i, t) in self.triangles.iter().enumerate() {
let Some([pa, pb, pc]) = self.tri(t) else { continue };
let ((ax, ay, az), (bx, by, bz), (cx, cy, cz)) = (frame(pa), frame(pb), frame(pc));
let u = cx * by - cy * bx;
let v = ax * cy - ay * cx;
let w = bx * ay - by * ax;
if (u < 0.0 || v < 0.0 || w < 0.0) && (u > 0.0 || v > 0.0 || w > 0.0) {
continue;
}
let det = u + v + w;
if det == 0.0 {
continue;
}
let t = (u * az + v * bz + w * cz) / det;
if t.is_finite() && t > 1e-9 && best.is_none_or(|(bt, _)| t < bt) {
best = Some((t, i));
}
Some(RayFrame { o, k: [kx, ky, kz], s: [comp(dir, kx) / dz, comp(dir, ky) / dz, 1.0 / dz] })
}
/// A vertex in the ray's frame: (x, y) across the ray, z scaled along it.
fn frame(&self, p: Vec3) -> (f64, f64, f64) {
let q = p - self.o;
let z = comp(q, self.k[2]);
(comp(q, self.k[0]) - self.s[0] * z, comp(q, self.k[1]) - self.s[1] * z, self.s[2] * z)
}
/// The distance along the ray to triangle `[pa, pb, pc]` (`None`: missed, or not in front).
pub(crate) fn hit(&self, [pa, pb, pc]: [Vec3; 3]) -> Option<f64> {
let ((ax, ay, az), (bx, by, bz), (cx, cy, cz)) = (self.frame(pa), self.frame(pb), self.frame(pc));
let u = cx * by - cy * bx;
let v = ax * cy - ay * cx;
let w = bx * ay - by * ax;
if (u < 0.0 || v < 0.0 || w < 0.0) && (u > 0.0 || v > 0.0 || w > 0.0) {
return None;
}
best
let det = u + v + w;
if det == 0.0 {
return None;
}
let t = (u * az + v * bz + w * cz) / det;
(t.is_finite() && t > 1e-9).then_some(t)
}
}
+1
View File
@@ -21,6 +21,7 @@ use wgpu::util::DeviceExt;
pub mod capture;
mod pbr;
pub mod pick;
#[cfg(not(target_arch = "wasm32"))]
pub mod select;
pub mod view;
+503
View File
@@ -0,0 +1,503 @@
//! The pick buffer: which model edges are visible at each pixel of the viewport, for picking on a
//! large model without testing every edge. Surfaces are drawn into the depth buffer only; then
//! every edge segment is drawn as a line carrying its id, depth tested against them (lifted
//! toward the eye by the picker's slack, the depth by which an edge may lie behind a face and
//! still count as visible) and written into an `R32Uint` id texture (0: no edge).
//!
//! The pass is drawn once per view (camera, viewport size, model), and only small tiles around
//! the cursor are read back, so a pointer moving over a still view reads a few kilobytes and
//! draws nothing. Read-backs arrive a frame or two later ([`PickResults`]); until a tile is in,
//! the picker answers on the CPU. The ids are hints: the picker still runs its exact tests on
//! the edges a tile names.
use std::sync::atomic::{AtomicU8, Ordering};
use std::sync::{Arc, Mutex};
use wgpu::util::DeviceExt;
/// The side of a read-back tile, in pixels (a multiple of 64, so rows need no padding).
pub const TILE: u32 = 128;
/// Most tiles kept from one view.
const KEEP: usize = 6;
/// Most read-backs in flight.
const IN_FLIGHT: usize = 3;
/// Bytes per surface vertex (position) and per edge vertex (position, id).
const FACE_VERTEX: u64 = 12;
const EDGE_VERTEX: u64 = 16;
const UNIFORM_SIZE: u64 = 96;
const SHADER: &str = r#"
struct U {
vp: mat4x4<f32>,
eye: vec4<f32>, // eye position, w = 1 for perspective
back: vec4<f32>, // toward the eye (orthographic), w = how far edges are lifted toward it
};
@group(0) @binding(0) var<uniform> u: U;
@vertex
fn vs_face(@location(0) p: vec3<f32>) -> @builtin(position) vec4<f32> {
return u.vp * vec4<f32>(p, 1.0);
}
@fragment
fn fs_face() -> @location(0) u32 {
return 0u;
}
struct EOut {
@builtin(position) pos: vec4<f32>,
@location(0) @interpolate(flat) id: u32,
};
@vertex
fn vs_edge(@location(0) p: vec3<f32>, @location(1) id: u32) -> EOut {
var toward = u.back.xyz;
if (u.eye.w > 0.5) {
let v = u.eye.xyz - p;
let l = length(v);
if (l > 0.0) {
toward = v / l;
}
}
var o: EOut;
o.pos = u.vp * vec4<f32>(p + toward * u.back.w, 1.0);
o.id = id;
return o;
}
@fragment
fn fs_edge(i: EOut) -> @location(0) u32 {
return i.id;
}
"#;
/// What the pass draws: surfaces (for depth) and edge segments with their ids (from 1).
#[derive(Default, Clone)]
pub struct PickScene {
faces: Vec<u8>,
edges: Vec<u8>,
}
impl PickScene {
pub fn triangle(&mut self, t: [[f32; 3]; 3]) {
for p in t {
for c in p {
self.faces.extend_from_slice(&c.to_le_bytes());
}
}
}
/// Segment `a`–`b` of the edge `id` (0 is no edge: not drawn).
pub fn segment(&mut self, a: [f32; 3], b: [f32; 3], id: u32) {
if id == 0 {
return;
}
for p in [a, b] {
for c in p {
self.edges.extend_from_slice(&c.to_le_bytes());
}
self.edges.extend_from_slice(&id.to_le_bytes());
}
}
pub fn is_empty(&self) -> bool {
self.edges.is_empty()
}
}
/// The view the pass is drawn for.
#[derive(Clone, Copy, Debug)]
pub struct PickView {
/// Changes whenever anything below or the scene changes.
pub key: u64,
/// Column-major view-projection (as [`crate::view::Frame::view_proj`]).
pub view_proj: [[f32; 4]; 4],
/// Eye position, and 1 for a perspective camera (0: orthographic).
pub eye: [f32; 4],
/// Direction toward the eye (orthographic).
pub back: [f32; 3],
/// How far edges are lifted toward the eye (model units).
pub lift: f32,
/// The viewport in physical pixels.
pub size: [u32; 2],
}
/// Edge ids of a block of pixels of one view.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct PickTile {
pub key: u64,
pub origin: [u32; 2],
pub size: [u32; 2],
/// Row-major, `size[0] * size[1]`.
pub ids: Vec<u32>,
}
impl PickTile {
/// Whether the tile is of view `key` and holds every pixel of `[x0, y0, x1, y1]` (inclusive)
/// that lies inside a viewport of `view` pixels.
pub fn covers(&self, key: u64, view: [u32; 2], [x0, y0, x1, y1]: [i64; 4]) -> bool {
let clamp = |v: i64, n: u32| v.clamp(0, i64::from(n.max(1)) - 1);
let (x0, x1, y0, y1) = (clamp(x0, view[0]), clamp(x1, view[0]), clamp(y0, view[1]), clamp(y1, view[1]));
let [ox, oy] = self.origin.map(i64::from);
let [w, h] = self.size.map(i64::from);
self.key == key && x0 >= ox && y0 >= oy && x1 < ox + w && y1 < oy + h
}
/// The ids within `[x0, y0, x1, y1]` (inclusive; outside the tile: none), each once.
pub fn ids_in(&self, [x0, y0, x1, y1]: [i64; 4]) -> Vec<u32> {
let [ox, oy] = self.origin.map(i64::from);
let [w, h] = self.size.map(i64::from);
let mut out = Vec::new();
for y in y0.max(oy)..=y1.min(oy + h - 1) {
for x in x0.max(ox)..=x1.min(ox + w - 1) {
if let Some(&id) = self.ids.get(((y - oy) * w + (x - ox)) as usize)
&& id != 0
{
out.push(id);
}
}
}
out.sort_unstable();
out.dedup();
out
}
}
/// The tiles read back so far (of the latest view only), newest last.
#[derive(Default, Debug)]
pub struct PickResults {
pub tiles: Vec<PickTile>,
}
impl PickResults {
/// The newest tile of view `key` covering `window`.
pub fn tile(&self, key: u64, view: [u32; 2], window: [i64; 4]) -> Option<&PickTile> {
self.tiles.iter().rev().find(|t| t.covers(key, view, window))
}
}
pub type PickOut = Arc<Mutex<PickResults>>;
/// The tile (origin and size) around pixel `centre` of a viewport of `view` pixels.
pub fn tile_around(centre: [u32; 2], view: [u32; 2]) -> ([u32; 2], [u32; 2]) {
let size = [TILE.min(view[0]), TILE.min(view[1])];
let origin = [0, 1].map(|k| centre[k].saturating_sub(size[k] / 2).min(view[k].saturating_sub(size[k])));
(origin, size)
}
const NEW: u8 = 0;
const MAPPING: u8 = 1;
const READY: u8 = 2;
const FAILED: u8 = 3;
/// A tile being copied out of the id texture.
struct Pending {
key: u64,
origin: [u32; 2],
size: [u32; 2],
bytes_per_row: u32,
buffer: wgpu::Buffer,
/// The frame whose commands copy it (it is mapped once they are submitted).
frame: u64,
state: Arc<AtomicU8>,
}
struct Target {
size: [u32; 2],
ids: wgpu::Texture,
ids_view: wgpu::TextureView,
depth_view: wgpu::TextureView,
}
struct Uploaded {
key: u64,
faces: Option<(wgpu::Buffer, u32)>,
edges: Option<(wgpu::Buffer, u32)>,
}
/// The pass's pipelines, its textures and the read-backs in flight, on one device.
pub struct PickBuffer {
face: wgpu::RenderPipeline,
edge: wgpu::RenderPipeline,
uniform: wgpu::Buffer,
bind: wgpu::BindGroup,
scene: Option<Uploaded>,
target: Option<Target>,
/// The view drawn into the textures.
drawn: Option<u64>,
pending: Vec<Pending>,
frame: u64,
}
const DEPTH: wgpu::TextureFormat = wgpu::TextureFormat::Depth32Float;
const IDS: wgpu::TextureFormat = wgpu::TextureFormat::R32Uint;
impl PickBuffer {
pub fn new(device: &wgpu::Device) -> PickBuffer {
let module =
device.create_shader_module(wgpu::ShaderModuleDescriptor { label: Some("sc_pick"), source: wgpu::ShaderSource::Wgsl(SHADER.into()) });
let bgl = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
label: Some("sc_pick"),
entries: &[wgpu::BindGroupLayoutEntry {
binding: 0,
visibility: wgpu::ShaderStages::VERTEX,
ty: wgpu::BindingType::Buffer { ty: wgpu::BufferBindingType::Uniform, has_dynamic_offset: false, min_binding_size: None },
count: None,
}],
});
let layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
label: Some("sc_pick"),
bind_group_layouts: &[Some(&bgl)],
immediate_size: 0,
});
let uniform = device.create_buffer(&wgpu::BufferDescriptor {
label: Some("sc_pick_u"),
size: UNIFORM_SIZE,
usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
mapped_at_creation: false,
});
let bind = device.create_bind_group(&wgpu::BindGroupDescriptor {
label: Some("sc_pick"),
layout: &bgl,
entries: &[wgpu::BindGroupEntry { binding: 0, resource: uniform.as_entire_binding() }],
});
const FA: [wgpu::VertexAttribute; 1] = wgpu::vertex_attr_array![0 => Float32x3];
const EA: [wgpu::VertexAttribute; 2] = wgpu::vertex_attr_array![0 => Float32x3, 1 => Uint32];
let pipeline = |label: &str,
vs: &str,
fs: &str,
stride: u64,
attributes: &'static [wgpu::VertexAttribute],
topology: wgpu::PrimitiveTopology,
write: bool,
mask: wgpu::ColorWrites| {
device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
label: Some(label),
layout: Some(&layout),
vertex: wgpu::VertexState {
module: &module,
entry_point: Some(vs),
buffers: &[Some(wgpu::VertexBufferLayout { array_stride: stride, step_mode: wgpu::VertexStepMode::Vertex, attributes })],
compilation_options: Default::default(),
},
primitive: wgpu::PrimitiveState { topology, ..Default::default() },
depth_stencil: Some(wgpu::DepthStencilState {
format: DEPTH,
depth_write_enabled: Some(write),
depth_compare: Some(wgpu::CompareFunction::LessEqual),
stencil: Default::default(),
bias: Default::default(),
}),
multisample: wgpu::MultisampleState::default(),
fragment: Some(wgpu::FragmentState {
module: &module,
entry_point: Some(fs),
targets: &[Some(wgpu::ColorTargetState { format: IDS, blend: None, write_mask: mask })],
compilation_options: Default::default(),
}),
multiview_mask: None,
cache: None,
})
};
let face =
pipeline("sc_pick_face", "vs_face", "fs_face", FACE_VERTEX, &FA, wgpu::PrimitiveTopology::TriangleList, true, wgpu::ColorWrites::empty());
let edge = pipeline("sc_pick_edge", "vs_edge", "fs_edge", EDGE_VERTEX, &EA, wgpu::PrimitiveTopology::LineList, false, wgpu::ColorWrites::ALL);
PickBuffer { face, edge, uniform, bind, scene: None, target: None, drawn: None, pending: Vec::new(), frame: 0 }
}
/// Before the frame is submitted: collect the tiles read back, then draw `view` of `scene`
/// (`scene_key` names it; it is uploaded when that changes) unless it is drawn already, and
/// start reading back the tile around pixel `centre` unless it is in or on its way. The tiles
/// land in `out` a frame or two later; keep frames coming until then.
#[allow(clippy::too_many_arguments)]
pub fn prepare(
&mut self,
device: &wgpu::Device,
queue: &wgpu::Queue,
encoder: &mut wgpu::CommandEncoder,
scene_key: u64,
scene: &PickScene,
view: &PickView,
centre: Option<[u32; 2]>,
out: &PickOut,
) {
self.frame += 1;
self.collect(device, out);
let [w, h] = view.size;
let max = device.limits().max_texture_dimension_2d;
if w == 0 || h == 0 || w > max || h > max {
return;
}
if self.scene.as_ref().is_none_or(|s| s.key != scene_key) {
let limit = device.limits().max_buffer_size;
let upload = |label: &str, bytes: &[u8], stride: u64| {
let n = bytes.len() as u64 / stride;
(n > 0 && (bytes.len() as u64) <= limit && n <= u64::from(u32::MAX)).then(|| {
(
device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
label: Some(label),
contents: bytes,
usage: wgpu::BufferUsages::VERTEX,
}),
n as u32,
)
})
};
self.scene = Some(Uploaded {
key: scene_key,
faces: upload("sc_pick_faces", &scene.faces, FACE_VERTEX),
edges: upload("sc_pick_edges", &scene.edges, EDGE_VERTEX),
});
self.drawn = None;
}
if self.target.as_ref().is_none_or(|t| t.size != view.size) {
let texture = |label: &str, format, usage| {
device.create_texture(&wgpu::TextureDescriptor {
label: Some(label),
size: wgpu::Extent3d { width: w, height: h, depth_or_array_layers: 1 },
mip_level_count: 1,
sample_count: 1,
dimension: wgpu::TextureDimension::D2,
format,
usage,
view_formats: &[],
})
};
let ids = texture("sc_pick_ids", IDS, wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::COPY_SRC);
let depth = texture("sc_pick_depth", DEPTH, wgpu::TextureUsages::RENDER_ATTACHMENT);
let (ids_view, depth_view) = (ids.create_view(&Default::default()), depth.create_view(&Default::default()));
self.target = Some(Target { size: view.size, ids, ids_view, depth_view });
self.drawn = None;
}
let (Some(target), Some(scene)) = (&self.target, &self.scene) else { return };
if self.drawn != Some(view.key) {
queue.write_buffer(&self.uniform, 0, &uniform_bytes(view));
let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
label: Some("sc_pick"),
color_attachments: &[Some(wgpu::RenderPassColorAttachment {
view: &target.ids_view,
depth_slice: None,
resolve_target: None,
ops: wgpu::Operations { load: wgpu::LoadOp::Clear(wgpu::Color::TRANSPARENT), store: wgpu::StoreOp::Store },
})],
depth_stencil_attachment: Some(wgpu::RenderPassDepthStencilAttachment {
view: &target.depth_view,
depth_ops: Some(wgpu::Operations { load: wgpu::LoadOp::Clear(1.0), store: wgpu::StoreOp::Discard }),
stencil_ops: None,
}),
timestamp_writes: None,
occlusion_query_set: None,
multiview_mask: None,
});
pass.set_bind_group(0, &self.bind, &[]);
for (pipeline, part) in [(&self.face, &scene.faces), (&self.edge, &scene.edges)] {
if let Some((buffer, n)) = part {
pass.set_pipeline(pipeline);
pass.set_vertex_buffer(0, buffer.slice(..));
pass.draw(0..*n, 0..1);
}
}
drop(pass);
self.drawn = Some(view.key);
// Tiles of other views no longer answer.
self.pending.retain(|p| p.key == view.key);
if let Ok(mut o) = out.lock() {
o.tiles.retain(|t| t.key == view.key);
}
}
let Some(centre) = centre else { return };
let (origin, size) = tile_around(centre, view.size);
let known = out.lock().is_ok_and(|o| o.tiles.iter().any(|t| t.key == view.key && t.origin == origin && t.size == size))
|| self.pending.iter().any(|p| p.key == view.key && p.origin == origin && p.size == size);
if known || self.pending.len() >= IN_FLIGHT {
return;
}
let bytes_per_row = (size[0] * 4).div_ceil(wgpu::COPY_BYTES_PER_ROW_ALIGNMENT) * wgpu::COPY_BYTES_PER_ROW_ALIGNMENT;
let buffer = device.create_buffer(&wgpu::BufferDescriptor {
label: Some("sc_pick_tile"),
size: u64::from(bytes_per_row) * u64::from(size[1]),
usage: wgpu::BufferUsages::MAP_READ | wgpu::BufferUsages::COPY_DST,
mapped_at_creation: false,
});
encoder.copy_texture_to_buffer(
wgpu::TexelCopyTextureInfo {
texture: &target.ids,
mip_level: 0,
origin: wgpu::Origin3d { x: origin[0], y: origin[1], z: 0 },
aspect: wgpu::TextureAspect::All,
},
wgpu::TexelCopyBufferInfo {
buffer: &buffer,
layout: wgpu::TexelCopyBufferLayout { offset: 0, bytes_per_row: Some(bytes_per_row), rows_per_image: Some(size[1]) },
},
wgpu::Extent3d { width: size[0], height: size[1], depth_or_array_layers: 1 },
);
self.pending.push(Pending { key: view.key, origin, size, bytes_per_row, buffer, frame: self.frame, state: Arc::new(AtomicU8::new(NEW)) });
}
/// Whether read-backs are still on their way (keep frames coming).
pub fn waiting(&self) -> bool {
!self.pending.is_empty()
}
/// Maps the copies earlier frames submitted and moves the mapped ones into `out`.
fn collect(&mut self, device: &wgpu::Device, out: &PickOut) {
let frame = self.frame;
for p in &self.pending {
if p.frame < frame && p.state.load(Ordering::Acquire) == NEW {
p.state.store(MAPPING, Ordering::Release);
let state = p.state.clone();
p.buffer.slice(..).map_async(wgpu::MapMode::Read, move |r| state.store(if r.is_ok() { READY } else { FAILED }, Ordering::Release));
}
}
if self.pending.iter().any(|p| p.state.load(Ordering::Acquire) == MAPPING) {
let _ = device.poll(wgpu::PollType::Poll);
}
let mut done = Vec::new();
self.pending.retain(|p| match p.state.load(Ordering::Acquire) {
READY => {
if let Ok(bytes) = p.buffer.slice(..).get_mapped_range() {
let [w, h] = p.size;
let mut ids = Vec::with_capacity(w as usize * h as usize);
for row in bytes.chunks(p.bytes_per_row as usize).take(h as usize) {
ids.extend(row.as_chunks::<4>().0.iter().take(w as usize).map(|c| u32::from_le_bytes(*c)));
}
done.push(PickTile { key: p.key, origin: p.origin, size: p.size, ids });
}
p.buffer.unmap();
false
}
FAILED => false,
_ => true,
});
if !done.is_empty()
&& let Ok(mut o) = out.lock()
{
for t in done {
if self.drawn == Some(t.key) && t.ids.len() == t.size[0] as usize * t.size[1] as usize {
o.tiles.retain(|x| x.key == t.key);
o.tiles.push(t);
}
}
let excess = o.tiles.len().saturating_sub(KEEP);
o.tiles.drain(..excess);
}
}
}
fn uniform_bytes(v: &PickView) -> Vec<u8> {
let mut b = Vec::with_capacity(UNIFORM_SIZE as usize);
for col in v.view_proj {
for x in col {
b.extend_from_slice(&x.to_le_bytes());
}
}
for x in v.eye.into_iter().chain(v.back).chain([v.lift]) {
b.extend_from_slice(&x.to_le_bytes());
}
b
}
#[cfg(test)]
#[path = "pick_tests.rs"]
mod tests;
+79
View File
@@ -0,0 +1,79 @@
use super::*;
/// Looking down −z at x, y in −10..10 (orthographic): depth 0 at z = 50, 1 at z = −50.
const VIEW: [[f32; 4]; 4] = [[0.1, 0.0, 0.0, 0.0], [0.0, 0.1, 0.0, 0.0], [0.0, 0.0, -0.01, 0.0], [0.0, 0.0, 0.5, 1.0]];
const SIZE: u32 = 64;
/// The pixel of model point (x, y).
fn px(x: f32, y: f32) -> [i64; 2] {
[((x / 10.0 + 1.0) * 0.5 * SIZE as f32) as i64, ((1.0 - y / 10.0) * 0.5 * SIZE as f32) as i64]
}
/// A square face at z = 0 (x, y in −5..5), and three edges: 1 on it, 2 well behind it, 3 behind
/// it by less than the lift.
fn scene() -> PickScene {
let mut s = PickScene::default();
let (a, b, c, d) = ([-5.0, -5.0, 0.0], [5.0, -5.0, 0.0], [5.0, 5.0, 0.0], [-5.0, 5.0, 0.0]);
s.triangle([a, b, c]);
s.triangle([a, c, d]);
s.segment([-8.0, 0.0, 0.0], [8.0, 0.0, 0.0], 1);
s.segment([2.0, -8.0, -3.0], [2.0, 8.0, -3.0], 2);
s.segment([-2.0, -8.0, -0.2], [-2.0, 8.0, -0.2], 3);
s
}
#[test]
fn the_pick_buffer_names_the_edges_seen_at_each_pixel() {
let (_, device, queue) = match crate::open_headless() {
Ok(d) => d,
Err(e) => {
assert!(std::env::var_os("SOLIDCRAFT_REQUIRE_GPU").is_none(), "a GPU is required here: {e}");
eprintln!("skipping: {e}");
return;
}
};
let mut pb = PickBuffer::new(&device);
let out = PickOut::default();
let view = PickView { key: 7, view_proj: VIEW, eye: [0.0, 0.0, 100.0, 0.0], back: [0.0, 0.0, 1.0], lift: 0.5, size: [SIZE, SIZE] };
let scene = scene();
let all = [0, 0, SIZE as i64 - 1, SIZE as i64 - 1];
for _ in 0..8 {
let mut encoder = device.create_command_encoder(&Default::default());
pb.prepare(&device, &queue, &mut encoder, 1, &scene, &view, Some([SIZE / 2, SIZE / 2]), &out);
queue.submit([encoder.finish()]);
let _ = device.poll(wgpu::PollType::wait_indefinitely());
if out.lock().unwrap().tile(7, [SIZE, SIZE], all).is_some() {
break;
}
}
let results = out.lock().unwrap();
let tile = results.tile(7, [SIZE, SIZE], all).expect("the tile is read back within a few frames");
let at = |x: f32, y: f32| {
let [px, py] = px(x, y);
tile.ids_in([px - 1, py - 1, px + 1, py + 1])
};
assert_eq!(at(0.0, 0.0), vec![1], "the edge on the face");
assert_eq!(at(2.0, 3.0), Vec::<u32>::new(), "the edge behind the face is hidden");
assert_eq!(at(2.0, 7.5), vec![2], "and seen where the face does not cover it");
assert_eq!(at(-2.0, 3.0), vec![3], "an edge behind the face by less than the lift counts as seen");
assert_eq!(at(3.5, 3.5), Vec::<u32>::new(), "the face itself names no edge");
assert!(results.tile(8, [SIZE, SIZE], all).is_none(), "another view's tile does not answer");
drop(results);
assert!(!pb.waiting());
}
#[test]
fn tiles_cover_the_window_around_the_cursor_inside_the_view() {
assert_eq!(tile_around([10, 10], [1000, 800]), ([0, 0], [TILE, TILE]));
assert_eq!(tile_around([500, 400], [1000, 800]), ([500 - TILE / 2, 400 - TILE / 2], [TILE, TILE]));
assert_eq!(tile_around([999, 799], [1000, 800]), ([1000 - TILE, 800 - TILE], [TILE, TILE]));
assert_eq!(tile_around([30, 20], [50, 40]), ([0, 0], [50, 40]));
let t = PickTile { key: 1, origin: [100, 100], size: [TILE, TILE], ids: vec![0; (TILE * TILE) as usize] };
assert!(t.covers(1, [1000, 800], [110, 110, 120, 120]));
assert!(!t.covers(1, [1000, 800], [90, 110, 120, 120]));
assert!(!t.covers(2, [1000, 800], [110, 110, 120, 120]));
// A window past the view's border needs only the pixels inside it.
let corner = PickTile { key: 1, origin: [0, 0], size: [TILE, TILE], ids: vec![5; (TILE * TILE) as usize] };
assert!(corner.covers(1, [1000, 800], [-8, -8, 8, 8]));
assert_eq!(corner.ids_in([-8, -8, 8, 8]), vec![5]);
}
+1
View File
@@ -1335,6 +1335,7 @@ impl Renderer {
tris(pass, &res.trans, &h.trans);
tris(pass, &res.guide_trans, &h.guide_trans);
tris(pass, &res.xray, &pv.xray);
tris(pass, &res.xray, &h.xray);
lines(pass, &res.overlay, &m.overlays);
lines(pass, &res.overlay, &sk.overlays);
lines(pass, &res.overlay, &h.overlays);
+9
View File
@@ -50,6 +50,11 @@ mod imp {
check(path)?;
std::fs::remove_file(path)
}
/// A folder and the folders above it, where missing.
pub fn create_dir_all(path: &str) -> Result<()> {
check(path)?;
std::fs::create_dir_all(path)
}
}
#[cfg(target_arch = "wasm32")]
@@ -94,6 +99,10 @@ mod imp {
pub fn remove(path: &str) -> Result<()> {
FILES.with(|f| f.borrow_mut().remove(path)).map(|_| ()).ok_or_else(|| missing(path))
}
/// Files are keyed by their whole path here: a folder needs no making.
pub fn create_dir_all(_path: &str) -> Result<()> {
Ok(())
}
pub fn insert(path: &str, bytes: Vec<u8>) {
FILES.with(|f| f.borrow_mut().insert(path.to_string(), bytes));
}
+120 -10
View File
@@ -116,9 +116,52 @@ impl Frame {
if !(sa.is_finite() && sb.is_finite() && sa > 0.0 && sb > 0.0) {
return None;
}
self.prism(self.ta * sa, self.tb * sb)
}
/// For a round, the arc of its cross-section from the setback on face a to the one on face
/// b, in [`ARC_PIECES`] pieces, as offsets from the edge; `None` for a chamfer.
fn arc(&self, size: Size) -> Option<Vec<Vec3>> {
let Size::Round(r) = size else { return None };
let (sa, sb) = self.setbacks(size)?;
let half = 0.5 * self.ta.dot(self.tb).clamp(-1.0, 1.0).acos();
// The ball's centre, on the bisector, `r` from both faces.
let centre = (self.ta + self.tb).normalized()? * (r / half.sin());
let (a, b) = (self.ta * sa - centre, self.tb * sb - centre);
(0..=ARC_PIECES).map(|k| Some(centre + (a + (b - a) * (k as f64 / ARC_PIECES as f64)).normalized()? * r)).collect()
}
/// What a blend of the edge at `size` changes, within the wedge: for a round, the fan of
/// prisms from the edge to the pieces of its arc (between the edge and the arc lies all it
/// takes away or fills; the ball's side of the arc is left as it is), for a chamfer the
/// wedge itself.
fn pieces(&self, size: Size) -> Option<Vec<Wedge>> {
match self.arc(size) {
Some(arc) => arc.windows(2).map(|w| self.prism(*w.first()?, *w.get(1)?)).collect(),
None => Some(vec![self.wedge(size)?]),
}
}
/// The blend's own surface at `size`, as polygons: the strips between its arc's pieces, or
/// the chamfer's face.
fn surface(&self, size: Size) -> Option<Vec<Vec<Vec3>>> {
match self.arc(size) {
Some(arc) => arc
.windows(2)
.map(|w| {
let (u, v) = (*w.first()?, *w.get(1)?);
Some(vec![self.p0 + u, self.p0 + v, self.p1 + v, self.p1 + u])
})
.collect(),
None => Some(vec![self.wedge(size)?.faces.get(2)?.clone()]),
}
}
/// The triangle between the edge and the offsets `u` and `w` across it, swept along the edge.
fn prism(&self, u: Vec3, w: Vec3) -> Option<Wedge> {
let d = (self.p1 - self.p0).normalized()?;
let (a0, b0) = (self.p0 + self.ta * sa, self.p0 + self.tb * sb);
let (a1, b1) = (self.p1 + self.ta * sa, self.p1 + self.tb * sb);
let (a0, b0) = (self.p0 + u, self.p0 + w);
let (a1, b1) = (self.p1 + u, self.p1 + w);
// Each side's plane, facing away from the triangle's third corner.
let side = |p: Vec3, q: Vec3, opposite: Vec3| -> Option<(Vec3, f64)> {
let mut n = d.cross(q - p).normalized()?;
@@ -130,13 +173,18 @@ impl Frame {
let planes = [side(self.p0, a0, b0)?, side(self.p0, b0, a0)?, side(a0, b0, self.p0)?, (-d, -d.dot(self.p0)), (d, d.dot(self.p1))];
let faces =
vec![vec![self.p0, a0, a1, self.p1], vec![self.p0, b0, b1, self.p1], vec![a0, b0, b1, a1], vec![self.p0, a0, b0], vec![self.p1, a1, b1]];
let area = 0.5 * (self.ta * sa).cross(self.tb * sb).len();
let area = 0.5 * u.cross(w).len();
Some(Wedge { planes, faces, volume: area * self.p0.dist(self.p1) })
}
}
/// `poly` clipped to the half-spaces, each moved `eps` inwards: is anything left?
fn reaches_inside(poly: &[Vec3], planes: &[(Vec3, f64)], eps: f64) -> bool {
/// Pieces a round's arc is divided into for [`Frame::pieces`] and [`Frame::surface`]: each
/// chord sags under 0.5 % of the radius.
const ARC_PIECES: usize = 8;
/// `poly` clipped to the half-spaces `n·x <= c`, each moved `eps` inwards (empty when nothing
/// is left).
fn clip(poly: &[Vec3], planes: &[(Vec3, f64)], eps: f64) -> Vec<Vec3> {
let mut cur: Vec<Vec3> = poly.to_vec();
for (n, c) in planes {
let c = c - eps;
@@ -152,11 +200,53 @@ fn reaches_inside(poly: &[Vec3], planes: &[(Vec3, f64)], eps: f64) -> bool {
}
}
if next.is_empty() {
return false;
return next;
}
cur = next;
}
true
cur
}
/// `poly` clipped to the half-spaces, each moved `eps` inwards: is anything left?
fn reaches_inside(poly: &[Vec3], planes: &[(Vec3, f64)], eps: f64) -> bool {
!clip(poly, planes, eps).is_empty()
}
/// Most polygons [`reaches_inside_beyond`] clips before it gives up and answers yes.
const MAX_CLIPS: usize = 4096;
/// Whether the part of `poly` outside every one of the wedges `trimmed` (by more than `out`)
/// reaches inside `planes` (by `eps`). A face beside or at the end of another edge the same
/// feature blends is trimmed back to that blend, so its part inside that edge's wedge is gone
/// (#1668).
fn reaches_inside_beyond(poly: &[Vec3], planes: &[(Vec3, f64)], eps: f64, trimmed: &[&Wedge], out: f64) -> bool {
let mut parts = vec![poly.to_vec()];
for w in trimmed {
// Outside a convex wedge is outside one of its planes (pieces may overlap: only
// whether anything is left counts).
let mut next = Vec::new();
for part in &parts {
for (n, c) in &w.planes {
let piece = clip(part, &[(-*n, -*c)], out);
if !piece.is_empty() {
next.push(piece);
}
}
if next.len() > MAX_CLIPS {
return true;
}
}
parts = next;
}
parts.iter().any(|p| reaches_inside(p, planes, eps))
}
/// Whether two sets of convex prisms overlap (by more than `eps`): a face of one reaches
/// inside the other.
fn overlap(a: &[Wedge], b: &[Wedge], eps: f64) -> bool {
a.iter().any(|x| {
b.iter().any(|y| y.faces.iter().any(|p| reaches_inside(p, &x.planes, eps)) || x.faces.iter().any(|p| reaches_inside(p, &y.planes, eps)))
})
}
/// The body's straight edges between planar faces nearest the points (each once; `None` for a
@@ -275,11 +365,22 @@ fn first_clash(sel: &Selection, size: Size) -> Option<Clash> {
// Planar faces are exact in the mesh; curved ones are within the chord.
let flat = (sel.size * 1e-7).max(1e-9);
let curved = sel.chord * 2.0;
for (f, w) in sel.frames.iter().zip(&wedges) {
// Planar faces beside an edge lie in its wedge's side planes: outside it means further.
let out = (sel.size * 1e-6).max(1e-8);
for (i, (f, w)) in sel.frames.iter().zip(&wedges).enumerate() {
let (Some(f), Some(w)) = (f, w) else { continue };
let hit = sel.tris.iter().filter(|(_, face)| !f.allowed.contains(face)).any(|(t, face)| {
let eps = if sel.planar.get(*face).copied().unwrap_or(false) { flat } else { curved };
reaches_inside(t, &w.planes, eps)
// The other blended edges this face runs along or ends them trim it back.
let trimmed: Vec<&Wedge> = sel
.frames
.iter()
.zip(&wedges)
.enumerate()
.filter(|(j, (fj, _))| *j != i && fj.as_ref().is_some_and(|fj| fj.allowed.contains(face)))
.filter_map(|(_, (_, wj))| wj.as_ref())
.collect();
reaches_inside_beyond(t, &w.planes, eps, &trimmed, out)
});
if hit {
return Some(Clash::Face);
@@ -295,7 +396,7 @@ fn first_clash(sel: &Selection, size: Size) -> Option<Clash> {
continue;
}
let meet = wj.faces.iter().any(|p| reaches_inside(p, &wi.planes, eps)) || wi.faces.iter().any(|p| reaches_inside(p, &wj.planes, eps));
if meet {
if meet && blends_cross(fi, wi, fj, wj, size, eps) {
return Some(Clash::Blend);
}
}
@@ -303,6 +404,15 @@ fn first_clash(sel: &Selection, size: Size) -> Option<Clash> {
None
}
/// Two blends whose wedges overlap: do they cross? Rounds on both sides of a wall (the outside
/// round's wedge reaches past the inside corner, which the inside round fills) need not: they
/// cross only where what one changes (between its edge and its arc) overlaps what the other
/// does, or where either's surface runs into the other's wedge (#1668).
fn blends_cross(fi: &Frame, wi: &Wedge, fj: &Frame, wj: &Wedge, size: Size, eps: f64) -> bool {
let (Some(pi), Some(pj), Some(si), Some(sj)) = (fi.pieces(size), fj.pieces(size), fi.surface(size), fj.surface(size)) else { return true };
overlap(&pi, &pj, eps) || sj.iter().any(|p| reaches_inside(p, &wi.planes, eps)) || si.iter().any(|p| reaches_inside(p, &wj.planes, eps))
}
/// The step the largest fitting size is given to: three significant digits.
fn step(v: f64) -> f64 {
10f64.powf(v.log10().floor() - 3.0)
+47
View File
@@ -305,6 +305,18 @@ pub fn canonical_revolve_axis(plane: &Plane, region: &Region2, axis_origin: Vec2
/// Revolve each region about the sketch axis by `angle` radians.
/// This legacy API preserves its historical sweep sign behavior.
pub fn revolve(plane: &Plane, regions: &[Region2], axis_origin: Vec2, axis_dir: Vec2, angle: f64) -> Result<Vec<Body>> {
revolved(plane, regions, axis_origin, axis_dir, angle, false)
}
/// [`revolve`] for bodies that are final (new bodies, not a boolean's tools): a partial turn's
/// planar faces come out whole too, as a full turn's always do (#726). A tool is left as swept:
/// healed, its planar faces meet a target exactly where they are tangent to it, and the
/// boolean leaves pieces there that touch. The boolean heals its own result anyway.
pub fn revolve_whole(plane: &Plane, regions: &[Region2], axis_origin: Vec2, axis_dir: Vec2, angle: f64) -> Result<Vec<Body>> {
revolved(plane, regions, axis_origin, axis_dir, angle, true)
}
fn revolved(plane: &Plane, regions: &[Region2], axis_origin: Vec2, axis_dir: Vec2, angle: f64, whole: bool) -> Result<Vec<Body>> {
let angle = finite(angle, "angle")?;
if angle.abs() < 1e-6 {
return Err(KernelError::Invalid("revolve angle is zero".into()));
@@ -447,11 +459,46 @@ pub fn revolve(plane: &Plane, regions: &[Region2], axis_origin: Vec2, axis_dir:
let closed = angle.abs() >= std::f64::consts::TAU;
let history = guard("revolve history", || Ok(record::swept_face(&solid, &f, &seeds(&profile), closed)))?;
let solid = if shift.len() > 0.0 { builder::translated(&solid, v3(shift)) } else { solid };
let (solid, history) = if closed || whole { turned_whole(solid, history) } else { (solid, history) };
out.push(record::attach(Body::new(solid)?, &[], history, Default::default())?);
}
Ok(out)
}
/// A revolved solid with its planar faces whole (#726): the sweep turns each profile edge into
/// two or three patches, the planar ones on revolved surfaces, which stayed apart until a later
/// feature healed the body, so a pick on one took part of the face. Healed as booleans heal
/// their results, each face is still generated, from the profile edges of the patches merged
/// into it. The solid as it was when healing fails or can't be followed.
fn turned_whole(solid: Solid, faces: Option<Vec<FaceProv>>) -> (Solid, Option<Vec<FaceProv>>) {
let Some(given) = faces.as_ref() else { return (solid, faces) };
let Ok(size) = Body::new(solid.clone()).map(|b| b.size()) else { return (solid, faces) };
let healed = guard("heal revolve", || {
let (healed, map) = crate::heal::heal_traced(solid.clone(), size, &[]);
let failed = || KernelError::Failed("heal revolve".into());
if !crate::boolean_record::edges_evaluate(&healed) {
return Err(failed());
}
let carried = map
.ok_or_else(failed)?
.faces
.iter()
.map(|under| {
let mut origins: Vec<_> = under.iter().map(|i| given.get(*i).map(|f| f.origins.clone())).collect::<Option<Vec<_>>>()?.concat();
origins.sort();
origins.dedup();
Some(FaceProv { origins, change: crate::history::Change::Generated })
})
.collect::<Option<Vec<_>>>()
.ok_or_else(failed)?;
Ok((healed, carried))
});
match healed {
Ok((healed, carried)) => (healed, Some(carried)),
Err(_) => (solid, faces),
}
}
/// Axis-aligned box between two corners.
pub fn box_solid(a: Vec3, b: Vec3) -> Result<Body> {
let (lo, hi) = (a.min(b), a.max(b));
+17 -14
View File
@@ -1723,10 +1723,14 @@ fn curve_blend_sized(solid: &Solid, ids: &[mt::EdgeID], size: f64, size_law: Siz
continue;
}
let h = length(k) / (samples - 1) as f64;
let spaced = |nb: usize, from_end: bool| -> Result<Option<Vec<Section>>> {
// A neighbour shorter than two of the strip's steps lends none: its own sections are
// spaced far closer (a small round beside a long line), and borrowing them made the
// strip overshoot and fold back on itself past the joint, which its faces' meshes
// then folded with (#1667). The strip ends on the joint's section on its own.
let spaced = |nb: usize, from_end: bool| -> Result<Vec<Section>> {
let l = length(nb);
if !(l > 2.0 * h && h > 0.0) {
return Ok(None);
return Ok(Vec::new());
}
let mut out = Vec::with_capacity(2);
for j in [1.0, 2.0] {
@@ -1735,7 +1739,7 @@ fn curve_blend_sized(solid: &Solid, ids: &[mt::EdgeID], size: f64, size_law: Siz
if from_end {
out.reverse();
}
Ok(Some(out))
Ok(out)
};
let (prev, next) = ((k + n - 1) % n, (k + 1) % n);
let list = esec.get(k).ok_or_else(|| KernelError::Failed("section".into()))?;
@@ -1748,23 +1752,22 @@ fn curve_blend_sized(solid: &Solid, ids: &[mt::EdgeID], size: f64, size_law: Siz
_ => false,
};
let before = match (closed || k > 0) && rolls(prev) {
true => spaced(prev, true)?
.map(|b| if smooth([list.first(), list.get(1), list.get(2)], [list.first(), b.get(1), b.first()]) { b } else { Vec::new() }),
false => Some(Vec::new()),
true => {
let b = spaced(prev, true)?;
if smooth([list.first(), list.get(1), list.get(2)], [list.first(), b.get(1), b.first()]) { b } else { Vec::new() }
}
false => Vec::new(),
};
let after = match (closed || k + 1 < n) && rolls(next) {
true => spaced(next, false)?.map(|a| {
true => {
let a = spaced(next, false)?;
let m = list.len();
let tail = [list.last(), m.checked_sub(2).and_then(|i| list.get(i)), m.checked_sub(3).and_then(|i| list.get(i))];
if smooth(tail, [list.last(), a.first(), a.get(1)]) { a } else { Vec::new() }
}),
false => Some(Vec::new()),
}
false => Vec::new(),
};
let fit = match (before, after) {
(Some(b), Some(a)) => crate::guard("fit curve blend", || fit_strip(list, &b, &a, round))?,
_ => crate::guard("fit curve blend", || fit_sections(&esec, k, closed, round))?,
};
let mut fit = fit;
let mut fit = crate::guard("fit curve blend", || fit_strip(list, &before, &after, round))?;
fit.span = guides.get(k).and_then(Option::as_ref).map(|g| g.span).unwrap_or((0.0, 1.0));
fits.push(Some(fit));
}
+36
View File
@@ -693,3 +693,39 @@ fn chamfer_a_chain_of_a_line_and_an_arc_into_a_slanted_end() {
let got = volume(&body) - volume(&made);
assert!((got - want).abs() < want * 1e-3, "removed {got} vs {want}");
}
/// #1667: an R1 round around the end of a long bar whose four long edges are R5. The chain is
/// 290 mm lines and quarter turns of 7.85 mm, so the lines' sections are spaced far wider than
/// the turns'; borrowing the turns' sections for the lines' ends made their strips overshoot and
/// fold back past the joints, the strips' meshes folded with them, and the measured volume came
/// out thousands of mm³ off. The R1 pipe is exact: the corner's section, `1 - π/4`, along the
/// lines, and round each turn's axis at the section's centroid (Pappus).
#[test]
fn round_along_long_lines_and_small_turns_measures_its_volume() {
use std::f64::consts::{FRAC_PI_2, FRAC_PI_4};
let (w, d, h) = (300.0, 60.0, 40.0);
let bar = crate::build::box_solid(Vec3::new(-w / 2.0, 0.0, 0.0), Vec3::new(w / 2.0, d, h)).unwrap();
let long = [Vec3::new(-w / 2.0, d / 2.0, 0.0), Vec3::new(w / 2.0, d / 2.0, 0.0), Vec3::new(-w / 2.0, d / 2.0, h), Vec3::new(w / 2.0, d / 2.0, h)];
let rounded = fillet(&bar, &long, 5.0).unwrap();
// The rolling ball along the end face's loop (the exact blends would take this loop; a
// loop next to free-form faces, as in the issue, comes here).
let ids: Vec<mt::EdgeID> = crate::body::Body::unique_edges(&rounded.solid)
.into_iter()
.filter(|e| [e.front(), e.back()].iter().all(|v| crate::blend::vtx(v).y.abs() < 1e-9))
.map(|e| e.id())
.collect();
assert_eq!(ids.len(), 8);
let (solid, _) = crate::guard("test", || curve_blend(&rounded.solid, &ids, rounded.size(), 1.0, true)).unwrap();
let body = Body::new(solid).unwrap();
assert!(body.validity().is_empty(), "{:?}", body.validity());
let section = 1.0 - FRAC_PI_4;
// The section's centroid lies this far from its corner along each side.
let inset = (5.0 / 6.0 - FRAC_PI_4) / section;
let lines = 2.0 * (w - 10.0) + 2.0 * (h - 10.0);
let turns = 4.0 * FRAC_PI_2 * (5.0 - inset);
let want = w * d * h - 4.0 * 25.0 * section * d - section * (lines + turns);
let m = crate::measure(&body).unwrap();
assert!((m.volume - want).abs() < 1e-5 * want, "{} vs {want}", m.volume);
// Centred across the bar, as the part is.
assert!(m.centroid.x.abs() < 1e-3, "centre of mass x {}", m.centroid.x);
}
+25
View File
@@ -94,3 +94,28 @@ fn a_result_that_removes_more_than_the_blend_is_refused() {
let m = too_large(crate::blend_fit::check_volume(&b, worse, &e, size));
assert!(m.contains("more than the chamfer can"), "{m}");
}
/// #1668: a box shelled outward 2 mm, open at the bottom. R5 on its top outer edge alone would
/// reach past the sharp inside corner 2 mm away; with the inside edge rounded in the same
/// fillet, that corner is filled, and the two build as one feature as they do one after the
/// other: the outer round takes (1 - π/4) · 25 mm² along 104 mm, the inner one adds it along
/// 100 mm.
#[test]
fn rounds_on_both_sides_of_a_wall_build_as_one_fillet() {
let outer = box_solid(Vec3::new(-52.0, -32.0, 0.0), Vec3::new(52.0, 32.0, 42.0)).unwrap();
let shelled = cut(&outer, [-50.0, -30.0, -1.0], [50.0, 30.0, 40.0]);
let (out_edge, in_edge) = (Vec3::new(0.0, 32.0, 42.0), Vec3::new(0.0, 30.0, 40.0));
let m = too_large(crate::fillet(&shelled, &[out_edge], 5.0));
assert!(m.contains("runs past the faces beside the edge"), "{m}");
let both = crate::fillet(&shelled, &[out_edge, in_edge], 5.0).unwrap();
assert!(both.validity().is_empty(), "{:?}", both.validity());
let section = (1.0 - std::f64::consts::FRAC_PI_4) * 25.0;
let want = shelled.volume_at(0.01).unwrap() - section * 104.0 + section * 100.0;
let v = crate::measure(&both).unwrap().volume;
assert!((v - want).abs() < 1e-4 * want, "{v} vs {want}");
let stepped = crate::fillet(&crate::fillet(&shelled, &[in_edge], 5.0).unwrap(), &[out_edge], 5.0).unwrap();
assert!((crate::measure(&stepped).unwrap().volume - v).abs() < 1e-4 * want);
// Past the wall's own room they still cross: R7's outer round reaches the inner one's arc.
let m = too_large(crate::fillet(&shelled, &[out_edge, in_edge], 7.0));
assert!(m.contains("the largest radius that fits"), "{m}");
}
+5 -5
View File
@@ -85,7 +85,7 @@ mod outline;
#[cfg(test)]
mod outline_tests;
mod par;
pub use par::{for_each_on_threads, map_on_threads};
pub use par::{for_each_on_threads, map_on_threads, map_with_local_pools};
#[cfg(test)]
mod pinch_tests;
mod planar_faces;
@@ -134,8 +134,8 @@ pub use boolean_diagnostics::{BooleanDiagnostics, BooleanFallback, BooleanStrate
pub use boundary::{Boundary, boundary_patch};
pub use bridge::{Continuity, Frame, blend_between, bridge, chain, chain_closes, frames, frames_across, sample_grid};
pub use build::{
PathSeg, box_solid, canonical_revolve_axis, cylinder, extrude, extrude_tapered, extrude_tapered_between, loft, revolve, sphere, sweep,
sweep_with, torus,
PathSeg, box_solid, canonical_revolve_axis, cylinder, extrude, extrude_tapered, extrude_tapered_between, loft, revolve, revolve_whole, sphere,
sweep, sweep_with, torus,
};
pub use continuity::{
ContinuityReport, ContinuityTolerances, EdgePick, MAX_SAMPLES, MIN_SAMPLES, SeamReport, SeamVerdict, SeamWorst, pick_edges, seam_diagnostics,
@@ -159,7 +159,7 @@ pub use mesh_convert::convert_prismatic_mesh;
pub use meshbody::{MAX_TRIANGLES, mesh_body};
pub use native::{decode_native_body, encode_native_body, native_preview_mesh};
pub use offset::with_same_surface;
pub use ops::{BoolOp, boolean, can_join_touching_faces, join_apart, split_by_plane, transform, transform_matrix, union_apart};
pub use ops::{BoolOp, boolean, can_join_touching_faces, half_space, join_apart, split_by_plane, transform, transform_matrix, union_apart};
pub use polybool::{faceted_boolean, planar_boolean};
pub use polyhedron::{HalfSpace, convex_polyhedron, draft, offset_faces, shell};
pub use prism::{PLANAR_FIT_TOL, extrude_planar_regions, planar_regions_boolean};
@@ -181,7 +181,7 @@ pub use surfaces::{
sweep_sheet_points, sweep_sheet_points_with, sweep_sheet_with, thicken, trim, unstitch,
};
pub use sweep_path::{SweepControl, SweepOrientation, sweep_path, sweep_path_with};
pub use topo::{CylinderFace, cylinder_face_at};
pub use topo::{CylinderFace, cylinder_end_at, cylinder_face_at};
pub use topo::{TopoCounts, merged_topology, seam_flags};
pub use tspline::tspline_sheet;
+12 -6
View File
@@ -363,7 +363,9 @@ fn boolean_via(a: &Body, b: &Body, op: BoolOp, whole: &dyn Fn(&Body, &Body, Bool
match op {
BoolOp::Cut => r = r.and_then(|result| result.map(|body| body.with_preserved_boolean_planar_sources(a, b, true)).transpose()),
BoolOp::Union => r = r.and_then(|result| result.map(|body| body.with_preserved_union_planar_sources(a, b)).transpose()),
BoolOp::Intersect => {}
// Every face of an intersection lies on one operand's face, as a union's does: the same
// roles carry over (#565).
BoolOp::Intersect => r = r.and_then(|result| result.map(|body| body.with_preserved_union_planar_sources(a, b)).transpose()),
}
// A retry's result is held to what the operation can do at all; one that fails is refused
// rather than returned wrong (issue #616).
@@ -1426,15 +1428,19 @@ pub fn transform(body: &Body, translate: Vec3, origin: Vec3, axis: Vec3, angle:
pub fn split_by_plane(body: &Body, plane: &solidcraft_geom::Plane) -> Result<Vec<Body>> {
let mut out = Vec::new();
for positive in [true, false] {
out.extend(half_space(body, plane, positive)?);
out.extend(half_space(body, plane, positive)?.0);
}
Ok(out)
}
/// The part of a body on one side of a plane (`None` when nothing is there): its intersection
/// with [`half_box`] (whose history it carries, over the body and the box).
pub(crate) fn half_space(body: &Body, plane: &solidcraft_geom::Plane, positive: bool) -> Result<Option<Body>> {
boolean(body, &half_box(body, plane, positive)?, BoolOp::Intersect)
/// The part of a body on one side of a plane (`None` when nothing is there), and the tool it is
/// cut with: the part is the body's intersection with [`half_box`] (the tool), whose history it
/// carries, over the body and the box. The box's face in the plane, the part's cut face, is its
/// start cap on the positive side and its end cap on the negative side.
pub fn half_space(body: &Body, plane: &solidcraft_geom::Plane, positive: bool) -> Result<(Option<Body>, Body)> {
// The box's own construction roles describe no face of the design: the cut face has none.
let tool = half_box(body, plane, positive)?.with_face_sources(None);
Ok((boolean(body, &tool, BoolOp::Intersect)?, tool))
}
/// A box covering everything of `body` on one side of a plane, its start cap in the plane.
+44
View File
@@ -33,6 +33,37 @@ pub fn for_each_on_threads<T: Sync>(items: &[T], max_threads: usize, f: impl Fn(
let _ = map_on_threads(items, max_threads, f);
}
/// Independent kernel jobs, with one computation lane per native dispatcher. Each dispatcher
/// owns a single-thread Rayon pool: nested triangulation neither queues behind a common
/// one-thread pool nor multiplies the requested concurrency. No second body can be stolen by
/// a worker while it fills a shared lazy mesh cell. The browser runs serially.
pub fn map_with_local_pools<T: Sync, R: Send>(items: &[T], max_threads: usize, f: impl Fn(&T) -> Result<R> + Sync) -> Vec<Result<R>> {
#[cfg(not(target_arch = "wasm32"))]
let one = |item: &T| {
use std::cell::OnceCell;
thread_local! {
static POOL: OnceCell<rayon::ThreadPool> = const { OnceCell::new() };
}
POOL.with(|cell| {
if cell.get().is_none() {
let pool = rayon::ThreadPoolBuilder::new()
.num_threads(1)
.build()
.map_err(|e| crate::KernelError::Failed(format!("cannot start mesh worker: {e}")))?;
let _ = cell.set(pool);
}
let pool = cell.get().ok_or_else(|| crate::KernelError::Failed("missing mesh worker".into()))?;
pool.install(|| guard("mesh worker", || f(item)))
})
};
#[cfg(target_arch = "wasm32")]
let one = |item: &T| guard("mesh worker", || f(item));
map_on_threads(items, max_threads, one)
.into_iter()
.map(|r| r.unwrap_or_else(|| Err(crate::KernelError::Internal("mesh worker failed".into()))))
.collect()
}
/// `f` over `items` as [`for_each_on_threads`] runs it, results in item order (`None` where an
/// item panicked).
pub fn map_on_threads<T: Sync, R: Send>(items: &[T], max_threads: usize, f: impl Fn(&T) -> R + Sync) -> Vec<Option<R>> {
@@ -82,6 +113,19 @@ mod tests {
use super::*;
use crate::KernelError;
#[test]
fn local_pools_keep_order_and_errors_and_bound_nested_parallelism() {
let items: Vec<usize> = (0..32).collect();
let result = map_with_local_pools(&items, 8, |i| {
#[cfg(not(target_arch = "wasm32"))]
assert_eq!(rayon::current_num_threads(), 1);
if *i == 7 { Err(KernelError::Invalid("seven".into())) } else { Ok(*i * 2) }
});
for (i, r) in result.iter().enumerate() {
assert_eq!(r.as_ref().ok().copied(), (i != 7).then_some(i * 2));
}
}
#[test]
fn each_item_once_on_threads() {
let items: Vec<u32> = (0..1000).collect();
+16 -8
View File
@@ -208,15 +208,23 @@ fn expected_revolution(b: &Body, r: &Region2) -> Vec<Vec<FaceOrigin>> {
#[test]
fn revolve_partial_and_full() {
let r = Region2 { outer: rect(10.0, 0.0, 20.0, 5.0), holes: vec![rect(12.0, 1.0, 14.0, 2.0).reversed()] };
// Under half a turn truck sweeps in two parts, beyond it in three; a full turn has no caps.
for (angle, parts, caps) in [(FRAC_PI_2, 2, 2), (1.5 * PI, 3, 2), (TAU, 3, 0)] {
let b = crate::revolve(&SIDE, std::slice::from_ref(&r), Vec2::ZERO, Vec2::Y, angle).unwrap().pop().unwrap();
let got = origins(&b);
assert_eq!(got, expected_revolution(&b, &r), "angle {angle}");
for k in 0..8 {
assert_eq!(got.iter().filter(|o| **o == [P(k)]).count(), parts, "segment {k} at angle {angle}");
// Under half a turn truck sweeps in two parts, beyond it in three; a full turn has no caps,
// and its planar faces (from the segments square to the axis) are whole (#726), as a partial
// turn's are when it is final (`revolve_whole`).
let segs: Vec<Seg2> = r.outer.segs.iter().chain(r.holes.iter().flat_map(|h| &h.segs)).cloned().collect();
for whole in [false, true] {
for (angle, parts, caps) in [(FRAC_PI_2, 2, 2), (1.5 * PI, 3, 2), (TAU, 3, 0)] {
let revolve = if whole { crate::revolve_whole } else { crate::revolve };
let b = revolve(&SIDE, std::slice::from_ref(&r), Vec2::ZERO, Vec2::Y, angle).unwrap().pop().unwrap();
let got = origins(&b);
assert_eq!(got, expected_revolution(&b, &r), "angle {angle}, whole {whole}");
for (k, s) in segs.iter().enumerate() {
let square = matches!(s, Seg2::Line { a, b } if (a.y - b.y).abs() < 1e-12);
let want = if (angle == TAU || whole) && square { 1 } else { parts };
assert_eq!(got.iter().filter(|o| **o == [P(k)]).count(), want, "segment {k} at angle {angle}, whole {whole}");
}
assert_eq!(got.iter().filter(|o| **o == [START] || **o == [END]).count(), caps);
}
assert_eq!(got.iter().filter(|o| **o == [START] || **o == [END]).count(), caps);
}
}
+27 -1
View File
@@ -663,6 +663,32 @@ pub fn cylinder_face_at(b: &Body, p: Vec3) -> Option<CylinderFace> {
let tol = (size * 1e-4).max(1e-6);
let surfs = classify_faces(b, &mesh, nf, tol);
let Surf::Cylinder { axis, p: ap, r } = *surfs.get(face as usize)? else { return None };
Some(cylinder_extent(&mesh, face, axis, ap, r))
}
/// The cylindrical face one of whose end circles is centred at `p` (a circle given by its
/// centre, where no face lies), the nearest when several are.
pub fn cylinder_end_at(b: &Body, p: Vec3) -> Option<CylinderFace> {
let size = b.size();
let tol = (size * 1e-3).max(1e-3);
let mesh = b.tessellate(tol).ok()?;
let surfs = classify_faces(b, &mesh, b.face_count(), (size * 1e-4).max(1e-6));
let mut best: Option<(f64, CylinderFace)> = None;
for (face, s) in surfs.iter().enumerate() {
let Surf::Cylinder { axis, p: ap, r } = *s else { continue };
let c = cylinder_extent(&mesh, u32::try_from(face).ok()?, axis, ap, r);
let v = p - c.axis_point;
let along = v.dot(c.axis);
let off = (v - c.axis * along).len() + (along - c.start).abs().min((c.end - along).abs());
if off <= tol && best.is_none_or(|(bo, _)| off < bo) {
best = Some((off, c));
}
}
best.map(|(_, c)| c)
}
/// The extent along its axis, and the side, of a cylindrical face of a tessellated body.
fn cylinder_extent(mesh: &Mesh, face: u32, axis: Vec3, ap: Vec3, r: f64) -> CylinderFace {
let mut lo = f64::INFINITY;
let mut hi = f64::NEG_INFINITY;
let mut inward = 0.0;
@@ -679,5 +705,5 @@ pub fn cylinder_face_at(b: &Body, p: Vec3) -> Option<CylinderFace> {
inward += n.dot(radial);
}
}
Some(CylinderFace { axis_point: ap, axis, radius: r, start: lo, end: hi, internal: inward < 0.0 })
CylinderFace { axis_point: ap, axis, radius: r, start: lo, end: hi, internal: inward < 0.0 }
}
+1 -1
View File
@@ -34,7 +34,7 @@ pub fn watching<R>(watch: Arc<dyn Watch>, f: impl FnOnce() -> R) -> R {
}
/// The watch over this thread's work, to hand to the worker threads it starts.
pub(crate) fn current() -> Option<Arc<dyn Watch>> {
pub fn current() -> Option<Arc<dyn Watch>> {
CURRENT.with(|c| c.borrow().clone())
}
+53
View File
@@ -831,6 +831,59 @@ fn bridged_screenshots_with_grid_or_axes_are_model_renders() {
let _ = std::fs::remove_dir_all(&dir);
}
/// #1677: a hidden window gives no picture. With no `source`, a model render comes back and says
/// it is one (`fallback`); asked for the window, the tool says why there is none, at once.
#[test]
fn a_hidden_window_screenshot_says_so() {
struct Hidden {
calls: Vec<String>,
}
impl crate::backend::Backend for Hidden {
fn call(&mut self, method: &str, params: Value) -> Result<Value, String> {
self.calls.push(method.to_string());
match method {
"ui.screenshot" => Err("no frame was presented (window hidden?); use ui.render".into()),
"ui.render" => {
let path = params["path"].as_str().ok_or("missing `path`")?;
std::fs::write(path, b"\x89PNG").map_err(|e| e.to_string())?;
Ok(json!({"path": path, "width": 64, "height": 48}))
}
other => Err(format!("unknown method `{other}`")),
}
}
fn has_ui(&self) -> bool {
true
}
fn describe(&self) -> String {
"app".into()
}
}
let dir = std::env::temp_dir().join(format!("solidcraft-mcp-hidden-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let path = dir.join("shot.png").to_string_lossy().to_string();
let shoot = |extra: Value| {
let mut args = json!({"path": path, "width": 64, "height": 48});
args.as_object_mut().unwrap().extend(extra.as_object().unwrap().clone());
let mut app = Hidden { calls: Vec::new() };
let r = crate::tools::call_tool(&mut app, "screenshot", &args);
(app.calls, r)
};
// The default: the window first, then a model render that says why.
let (calls, r) = shoot(json!({}));
assert!(r["isError"] != json!(true), "{r}");
assert_eq!(calls, ["ui.screenshot", "ui.render"]);
let info: Value = serde_json::from_str(r["content"][1]["text"].as_str().unwrap()).unwrap();
assert_eq!(info["source"], "model", "{info}");
assert!(info["fallback"].as_str().is_some_and(|f| f.contains("window hidden")), "{info}");
// Asked for the window: an error naming the cause and the way out, and no render.
let (calls, r) = shoot(json!({"source": "window"}));
assert_eq!(r["isError"], json!(true), "{r}");
let text = r["content"][0]["text"].as_str().unwrap();
assert!(text.contains("window hidden") && text.contains("source \"model\""), "{text}");
assert_eq!(calls, ["ui.screenshot"]);
let _ = std::fs::remove_dir_all(&dir);
}
/// #530: in a design with many bodies every feature result lists all of them, so a batch reply
/// is mostly the same body list once per step. A compact batch reply names only what each step
/// added or changed.
+15 -2
View File
@@ -639,11 +639,21 @@ fn capture(b: &mut dyn Backend, a: &Map<String, Value>) -> Result<(Vec<u8>, Valu
}
b.call("ui.render", params)
};
let asked_window = str_arg(a, "source") == Some("window");
let mut fallback = None;
let (info, source) = if window {
match b.call("ui.screenshot", json!({"path": path})) {
Ok(v) => (v, "window"),
// No presented frame (minimised or hidden window): fall back to a model render.
Err(_) => (render(b)?, "model"),
// Asked for the window: say why there is none, so the caller can show it or ask for
// a model render (#1677).
Err(e) if asked_window => {
return Err(format!("screenshot: the window gave no picture ({e}); show the window, or use source \"model\""));
}
// No presented frame (minimised or hidden window): a model render, and the reply says so.
Err(e) => {
fallback = Some(e);
(render(b)?, "model")
}
}
} else {
(render(b)?, "model")
@@ -659,6 +669,9 @@ fn capture(b: &mut dyn Backend, a: &Map<String, Value>) -> Result<(Vec<u8>, Valu
};
let bytes = png.len();
let mut reply = json!({"source": source, "path": keep, "width": w, "height": h, "bytes": bytes});
if let Some(why) = fallback {
reply["fallback"] = json!(format!("the window gave no picture ({why}); this is a model render"));
}
// What drew a model render (gpu, gpu-software or cpu), and the warning a CPU render carries.
for k in ["renderer", "warning"] {
if let Some(v) = info.get(k).filter(|v| !v.is_null()) {
+5
View File
@@ -8,6 +8,10 @@ license.workspace = true
[lints]
workspace = true
[features]
default = []
raytrace-cpu = []
[dependencies]
solidcraft-geom = { workspace = true }
serde = { workspace = true }
@@ -15,6 +19,7 @@ image = { workspace = true, features = ["jpeg"] }
moxcms = { workspace = true }
png = { workspace = true }
sha2 = { workspace = true }
weezl = { workspace = true }
[dev-dependencies]
serde_json = { workspace = true }
+294
View File
@@ -0,0 +1,294 @@
//! Original anisotropic GGX reflection with separable Smith masking and Schlick Fresnel.
//!
//! Mathematics: Heitz, JCGT 7(4), 2018, equations 1 and 2,
//! <https://jcgt.org/published/0007/04/01/>. No external implementation adapted.
//! Sampling here uses the **NDF**, not Heitz's visible-normal (VNDF) sampler:
//! `p(h) = D(h) * n.h`, then `p(l) = p(h) / (4 * v.h)`.
//! Rejected reflections are null events, never resampled or renormalized.
//!
//! This numerical module does not install a renderer, persist a material or alter
//! engineering axes. The visual frame's normal may be a shading normal, but the
//! original geometric normal is required separately to reject below-surface rays.
//! Consumers retain geometric normals for ray spawning and optical boundaries.
//! No shading-normal energy correction, multiple scattering or transmission is modeled.
use std::f64::consts::{PI, TAU};
use solidcraft_geom::Vec3;
use crate::surface::{MIN_ROUGHNESS, OpaqueSurface, SurfaceError, unit_direction};
/// Admission or finite-arithmetic failure in the anisotropic numerical contract.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum AnisotropicError {
/// An existing opaque-surface parameter or direction was invalid.
Surface(SurfaceError),
/// A visual frame was not orthogonal, or opposed its geometric normal.
Frame,
/// A variate was not finite in the half-open interval [0, 1).
Variates,
/// A computed density, response or sample weight was not finite/nonnegative.
Arithmetic,
}
impl From<SurfaceError> for AnisotropicError {
fn from(value: SurfaceError) -> Self {
Self::Surface(value)
}
}
impl std::fmt::Display for AnisotropicError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::Surface(e) => std::fmt::Display::fmt(e, f),
Self::Frame => f.write_str("visual frame must be orthogonal and face the geometric normal"),
Self::Variates => f.write_str("anisotropic variates must be finite in [0, 1)"),
Self::Arithmetic => f.write_str("anisotropic result must be finite and nonnegative"),
}
}
}
impl std::error::Error for AnisotropicError {}
type Result<T> = std::result::Result<T, AnisotropicError>;
/// Right-handed orthonormal visual axes; independent of engineering material axes.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct VisualFrame {
normal: Vec3,
tangent: Vec3,
bitangent: Vec3,
}
impl VisualFrame {
/// Normalize finite nonzero orthogonal inputs. An arbitrary oblique tangent is
/// refused rather than silently choosing a different brushed direction.
/// Roundoff within 1e-10 of perpendicular is removed by orthogonalization.
pub fn new(normal: Vec3, tangent: Vec3) -> Result<Self> {
let normal = unit_direction(normal)?;
let tangent = unit_direction(tangent)?;
let dot = normal.dot(tangent);
if dot.abs() > 1e-10 {
return Err(AnisotropicError::Frame);
}
let tangent = unit_direction(tangent - normal * dot)?;
let bitangent = unit_direction(normal.cross(tangent))?;
Ok(Self { normal, tangent, bitangent })
}
/// Shading normal, never a replacement for an original geometric normal.
pub fn normal(self) -> Vec3 {
self.normal
}
/// Visual X axis, associated with the first roughness.
pub fn tangent(self) -> Vec3 {
self.tangent
}
/// Visual Y axis, associated with the second roughness.
pub fn bitangent(self) -> Vec3 {
self.bitangent
}
fn local(self, direction: Vec3) -> Vec3 {
Vec3::new(self.tangent.dot(direction), self.bitangent.dot(direction), self.normal.dot(direction))
}
fn world(self, local: Vec3) -> Vec3 {
self.tangent * local.x + self.bitangent * local.y + self.normal * local.z
}
fn geometric(self, normal: Vec3) -> Result<Vec3> {
let normal = unit_direction(normal)?;
if normal.dot(self.normal) <= 0.0 {
return Err(AnisotropicError::Frame);
}
Ok(normal)
}
}
/// A bounded opaque response with two perceptual roughness axes in [0.045, 1].
/// Alpha is roughness squared, matching [`OpaqueSurface`].
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct AnisotropicSurface {
base: OpaqueSurface,
roughness_y: f64,
}
/// One reflected **specular-only** NDF sample. Fields are in world coordinates.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct ReflectionSample {
/// Outgoing direction, pointing away from the surface.
pub direction: Vec3,
/// Unconditional density per steradian, without renormalizing null events.
pub pdf: f64,
/// `specular_brdf * shading_cosine / pdf`, in linear RGB.
/// Diffuse response is excluded; its sampling strategy belongs to the consumer.
pub weight: Vec3,
}
impl AnisotropicSurface {
/// Linear-sRGB reflectance, metal fraction and IOR use the opaque contract.
/// Perfect delta mirrors and out-of-range roughness are refused, not clamped.
pub fn new(base_color: Vec3, metallic: f64, roughness_x: f64, roughness_y: f64, dielectric_ior: f64) -> Result<Self> {
let base = OpaqueSurface::new(base_color, metallic, roughness_x, dielectric_ior)?;
if !roughness_y.is_finite() || !(MIN_ROUGHNESS..=1.0).contains(&roughness_y) {
return Err(SurfaceError::Roughness.into());
}
Ok(Self { base, roughness_y })
}
/// Admitted perceptual roughness along visual X and Y.
pub fn roughness(self) -> [f64; 2] {
[self.base.roughness(), self.roughness_y]
}
fn alpha(self) -> [f64; 2] {
[self.base.roughness().powi(2), self.roughness_y.powi(2)]
}
fn fresnel(self, cosine: f64) -> Vec3 {
let f0 = self.base.normal_reflectance();
f0 + (Vec3::new(1.0, 1.0, 1.0) - f0) * (1.0 - cosine.clamp(0.0, 1.0)).powi(5)
}
fn distribution_local(self, h: Vec3) -> f64 {
if h.z <= 0.0 {
return 0.0;
}
let [ax, ay] = self.alpha();
let q = (h.x / ax).powi(2) + (h.y / ay).powi(2) + h.z * h.z;
1.0 / (PI * ax * ay * q * q)
}
// Smith G1 / cosine, avoiding division by tiny cosines and tan(theta).
fn visibility(self, w: Vec3) -> f64 {
let [ax, ay] = self.alpha();
2.0 / (w.z + (w.z * w.z + (ax * w.x).powi(2) + (ay * w.y).powi(2)).sqrt())
}
/// GGX normal distribution D, per steradian of microfacet normal.
/// This is not a normalized probability density: [`Self::normal_pdf`] is.
pub fn distribution(self, frame: VisualFrame, half: Vec3) -> Result<f64> {
finite_scalar(self.distribution_local(frame.local(unit_direction(half)?)))
}
/// Projected NDF density `D(h) * n.h` on the upper shading hemisphere.
/// Its integral over that hemisphere is one.
pub fn normal_pdf(self, frame: VisualFrame, half: Vec3) -> Result<f64> {
let h = frame.local(unit_direction(half)?);
finite_scalar(self.distribution_local(h) * h.z.max(0.0))
}
/// Sample the projected NDF by stretching a radial GGX slope distribution.
/// The inverse radial CDF is `r = sqrt(u/(1-u))`; homogeneous coordinates
/// `(alpha_x*sqrt(u)*cos(phi), alpha_y*sqrt(u)*sin(phi), sqrt(1-u))`
/// avoid a large intermediate radius. No heap, rejection loop or RNG is used.
pub fn sample_normal(self, frame: VisualFrame, variates: [f64; 2]) -> Result<Vec3> {
let [u, azimuth] = variates;
if !variates.into_iter().all(|v| v.is_finite() && (0.0..1.0).contains(&v)) {
return Err(AnisotropicError::Variates);
}
let [ax, ay] = self.alpha();
let phi = TAU * azimuth;
let radial = u.sqrt();
let h = unit_direction(Vec3::new(ax * radial * phi.cos(), ay * radial * phi.sin(), (1.0 - u).sqrt()))?;
Ok(unit_direction(frame.world(h))?)
}
fn directions(self, frame: VisualFrame, geometric: Vec3, view: Vec3, light: Vec3) -> Result<Option<(Vec3, Vec3, Vec3)>> {
let geometric = frame.geometric(geometric)?;
let view = unit_direction(view)?;
let light = unit_direction(light)?;
let (v, l) = (frame.local(view), frame.local(light));
if v.z <= 0.0 || l.z <= 0.0 || geometric.dot(view) <= 0.0 || geometric.dot(light) <= 0.0 {
return Ok(None);
}
let h = unit_direction(view + light)?;
Ok(Some((v, l, frame.local(h))))
}
fn specular_local(self, v: Vec3, l: Vec3, h: Vec3) -> Result<Vec3> {
finite_rgb(self.fresnel(v.dot(h)) * (self.distribution_local(h) * 0.25 * self.visibility(v) * self.visibility(l)))
}
/// Specular component only, with independent geometric hemisphere rejection.
/// All input directions point away from the surface.
pub fn specular_brdf(self, frame: VisualFrame, geometric: Vec3, view: Vec3, light: Vec3) -> Result<Vec3> {
let Some((v, l, h)) = self.directions(frame, geometric, view, light)? else { return Ok(Vec3::ZERO) };
self.specular_local(v, l, h)
}
/// Full opaque BRDF, including the same symmetric attenuated Lambert term as
/// [`OpaqueSurface`]. No radiance, cosine, exposure or display transform included.
/// Equal roughness axes delegate to the existing isotropic numerical contract.
pub fn brdf(self, frame: VisualFrame, geometric: Vec3, view: Vec3, light: Vec3) -> Result<Vec3> {
let Some((v, l, h)) = self.directions(frame, geometric, view, light)? else { return Ok(Vec3::ZERO) };
if self.base.roughness() == self.roughness_y {
return Ok(self.base.brdf(frame.normal, view, light)?);
}
let specular = self.specular_local(v, l, h)?;
let fv = self.fresnel(v.z);
let fl = self.fresnel(l.z);
let diffuse = self.base.base_color() * ((1.0 - self.base.metallic()) / PI);
finite_rgb(
specular
+ Vec3::new(
(1.0 - fv.x) * (1.0 - fl.x) * diffuse.x,
(1.0 - fv.y) * (1.0 - fl.y) * diffuse.y,
(1.0 - fv.z) * (1.0 - fl.z) * diffuse.z,
),
)
}
/// Unconditional reflected-direction density for the specular NDF sampler.
/// Integrates to the acceptance probability, not necessarily one: invalid
/// microfacets and below-geometric/shading-hemisphere reflections are null events.
/// A mixture with a diffuse or environment sampler must use its own mixture PDF.
pub fn reflection_pdf(self, frame: VisualFrame, geometric: Vec3, view: Vec3, light: Vec3) -> Result<f64> {
let Some((v, _, h)) = self.directions(frame, geometric, view, light)? else { return Ok(0.0) };
finite_scalar(self.distribution_local(h) * h.z.max(0.0) / (4.0 * v.dot(h).max(0.0)))
}
/// One specular NDF attempt. `None` is a zero-contribution event and must
/// still count towards the consumer's sample denominator. Never retry until
/// success. Ray origins/visibility use the consumer's original geometric data.
pub fn sample_reflection(self, frame: VisualFrame, geometric: Vec3, view: Vec3, variates: [f64; 2]) -> Result<Option<ReflectionSample>> {
let geometric = frame.geometric(geometric)?;
let view = unit_direction(view)?;
let half = self.sample_normal(frame, variates)?;
let v = frame.local(view);
if v.z <= 0.0 || geometric.dot(view) <= 0.0 {
return Ok(None);
}
let vh = view.dot(half);
if vh <= 0.0 {
return Ok(None);
}
let light = unit_direction(half * (2.0 * vh) - view)?;
let l = frame.local(light);
if l.z <= 0.0 || geometric.dot(light) <= 0.0 {
return Ok(None);
}
let h = frame.local(half);
let pdf = self.reflection_pdf(frame, geometric, view, light)?;
if pdf <= 0.0 {
return Err(AnisotropicError::Arithmetic);
}
// Cancel D algebraically in f_spec * cos / pdf. No tiny-cosine division.
let weight = finite_rgb(self.fresnel(vh) * (self.visibility(v) * (self.visibility(l) * l.z) * vh / h.z))?;
Ok(Some(ReflectionSample { direction: light, pdf, weight }))
}
}
fn finite_scalar(value: f64) -> Result<f64> {
if value.is_finite() && value >= 0.0 { Ok(value) } else { Err(AnisotropicError::Arithmetic) }
}
fn finite_rgb(value: Vec3) -> Result<Vec3> {
if value.is_finite() && [value.x, value.y, value.z].into_iter().all(|c| c >= 0.0) { Ok(value) } else { Err(AnisotropicError::Arithmetic) }
}
#[cfg(test)]
#[path = "anisotropic_surface_tests.rs"]
mod tests;
@@ -0,0 +1,277 @@
use super::*;
fn frame() -> VisualFrame {
VisualFrame::new(Vec3::Z, Vec3::X).unwrap()
}
fn surface(rx: f64, ry: f64) -> AnisotropicSurface {
AnisotropicSurface::new(Vec3::new(0.8, 0.5, 0.2), 1.0, rx, ry, 1.5).unwrap()
}
fn close(a: f64, b: f64, tolerance: f64) {
assert!((a - b).abs() <= tolerance * (1.0 + a.abs().max(b.abs())), "{a} != {b}");
}
fn close_rgb(a: Vec3, b: Vec3, tolerance: f64) {
close(a.x, b.x, tolerance);
close(a.y, b.y, tolerance);
close(a.z, b.z, tolerance);
}
fn hemisphere(mu: f64, phi: f64) -> Vec3 {
let radius = (1.0 - mu * mu).sqrt();
Vec3::new(radius * phi.cos(), radius * phi.sin(), mu)
}
#[test]
fn constructor_rejects_hostile_parameters_on_both_axes() {
for bad in [f64::NAN, f64::INFINITY, f64::NEG_INFINITY, 0.0, MIN_ROUGHNESS.next_down(), 1.01] {
assert!(AnisotropicSurface::new(Vec3::X, 1.0, bad, 0.5, 1.5).is_err());
assert!(AnisotropicSurface::new(Vec3::X, 1.0, 0.5, bad, 1.5).is_err());
}
for bad in [f64::NAN, f64::INFINITY, -0.1, 1.1] {
assert!(AnisotropicSurface::new(Vec3::new(bad, 0.0, 0.0), 1.0, 0.5, 0.8, 1.5).is_err());
assert!(AnisotropicSurface::new(Vec3::X, bad, 0.5, 0.8, 1.5).is_err());
}
for bad in [f64::NAN, 0.99, 3.01] {
assert!(AnisotropicSurface::new(Vec3::X, 1.0, 0.5, 0.8, bad).is_err());
}
assert_eq!(surface(MIN_ROUGHNESS, 1.0).roughness(), [MIN_ROUGHNESS, 1.0]);
}
#[test]
fn frame_is_right_handed_and_requires_an_explicit_orthogonal_axis() {
let f = VisualFrame::new(Vec3::new(0.0, 0.0, 1e308), Vec3::new(1e-300, 0.0, 0.0)).unwrap();
assert_eq!(f.normal(), Vec3::Z);
assert_eq!(f.tangent(), Vec3::X);
assert_eq!(f.bitangent(), Vec3::Y);
for (n, t) in [(Vec3::ZERO, Vec3::X), (Vec3::Z, Vec3::Z), (Vec3::Z, Vec3::X + Vec3::Z), (Vec3::Z, Vec3::new(f64::NAN, 0.0, 0.0))] {
assert!(VisualFrame::new(n, t).is_err());
}
let tilted = VisualFrame::new(Vec3::new(0.3, 0.4, 1.0), Vec3::new(0.8, -0.6, 0.0)).unwrap();
close(tilted.tangent().dot(tilted.normal()), 0.0, 1e-14);
close_rgb(tilted.tangent().cross(tilted.bitangent()), tilted.normal(), 1e-14);
}
#[test]
fn normal_incidence_matches_independent_ggx_peak() {
let s = surface(0.3, 0.7);
let d = 1.0 / (PI * 0.3_f64.powi(2) * 0.7_f64.powi(2));
close(s.distribution(frame(), Vec3::Z).unwrap(), d, 1e-14);
close(s.normal_pdf(frame(), Vec3::Z).unwrap(), d, 1e-14);
close_rgb(s.brdf(frame(), Vec3::Z, Vec3::Z, Vec3::Z).unwrap(), Vec3::new(0.8, 0.5, 0.2) * (d / 4.0), 1e-14);
}
#[test]
fn isotropic_limit_matches_existing_opaque_contract() {
for r in [MIN_ROUGHNESS, 0.3, 0.7, 1.0] {
for metallic in [0.0, 0.5, 1.0] {
let color = Vec3::new(0.8, 0.5, 0.2);
let a = AnisotropicSurface::new(color, metallic, r, r, 1.5).unwrap();
let opaque = OpaqueSurface::new(color, metallic, r, 1.5).unwrap();
for (v, l) in [(Vec3::Z, Vec3::Z), (Vec3::new(0.4, 0.2, 0.8), Vec3::new(-0.2, 0.7, 0.6))] {
assert_eq!(a.brdf(frame(), Vec3::Z, v, l).unwrap(), opaque.brdf(Vec3::Z, v, l).unwrap());
if metallic == 1.0 {
close_rgb(a.specular_brdf(frame(), Vec3::Z, v, l).unwrap(), opaque.brdf(Vec3::Z, v, l).unwrap(), 1e-10);
}
}
}
}
}
#[test]
fn reciprocal_for_unequal_axes_and_mixed_metal_fraction() {
for metallic in [0.0, 0.4, 1.0] {
let s = AnisotropicSurface::new(Vec3::new(0.8, 0.5, 0.2), metallic, 0.2, 0.9, 2.0).unwrap();
for (v, l) in [(Vec3::new(0.4, 0.1, 1.0), Vec3::new(-0.3, 0.2, 0.8)), (Vec3::new(1.0, 0.0, 1e-300), Vec3::new(-1.0, 0.0, 1e-300))] {
close_rgb(s.brdf(frame(), Vec3::Z, v, l).unwrap(), s.brdf(frame(), Vec3::Z, l, v).unwrap(), 1e-12);
}
}
}
#[test]
fn ninety_degree_visual_rotation_swaps_the_brushed_response() {
let s = surface(0.25, 0.8);
let swapped = surface(0.8, 0.25);
let rotated = VisualFrame::new(Vec3::Z, Vec3::Y).unwrap();
let light = Vec3::new(0.6, 0.0, 0.8);
let initial = s.brdf(frame(), Vec3::Z, Vec3::Z, light).unwrap();
let turned = s.brdf(rotated, Vec3::Z, Vec3::Z, light).unwrap();
assert!((initial - turned).len() > 0.01);
close_rgb(turned, swapped.brdf(frame(), Vec3::Z, Vec3::Z, light).unwrap(), 1e-13);
let h = s.sample_normal(frame(), [0.3, 0.2]).unwrap();
let rotated_h = s.sample_normal(rotated, [0.3, 0.2]).unwrap();
close_rgb(rotated_h, Vec3::new(-h.y, h.x, h.z), 1e-14);
}
#[test]
fn geometric_and_shading_hemispheres_are_independent() {
let shading = VisualFrame::new(Vec3::new(0.8, 0.0, 0.6), Vec3::Y).unwrap();
let light = Vec3::new(0.99, 0.0, -0.1);
let s = surface(0.5, 0.8);
assert!(shading.normal().dot(light) > 0.0);
assert_eq!(s.brdf(shading, Vec3::Z, Vec3::Z, light).unwrap(), Vec3::ZERO);
assert_eq!(s.reflection_pdf(shading, Vec3::Z, Vec3::Z, light).unwrap(), 0.0);
assert!(s.brdf(frame(), -Vec3::Z, Vec3::Z, Vec3::Z).is_err());
assert_eq!(s.brdf(frame(), Vec3::Z, Vec3::Z, Vec3::X).unwrap(), Vec3::ZERO);
assert_eq!(s.brdf(frame(), Vec3::Z, -Vec3::Z, Vec3::Z).unwrap(), Vec3::ZERO);
}
#[test]
fn grazing_and_extreme_finite_direction_magnitudes_remain_finite() {
for (rx, ry) in [(MIN_ROUGHNESS, 1.0), (1.0, MIN_ROUGHNESS), (MIN_ROUGHNESS, MIN_ROUGHNESS)] {
let s = surface(rx, ry);
for (v, l) in [(Vec3::new(1.0, 0.0, 1e-300), Vec3::new(-1.0, 0.0, 1e-300)), (Vec3::new(1e308, 1e308, 1e308), Vec3::new(-1e-300, 0.0, 1e-300))]
{
let b = s.brdf(frame(), Vec3::Z, v, l).unwrap();
assert!(b.is_finite() && b.x >= 0.0 && b.y >= 0.0 && b.z >= 0.0);
}
for u in [0.0, f64::from_bits(1), 0.5, 1.0_f64.next_down()] {
let h = s.sample_normal(frame(), [u, 0.5]).unwrap();
assert!(h.is_finite() && h.z > 0.0);
assert!(s.normal_pdf(frame(), h).unwrap().is_finite());
}
let view = Vec3::new(1.0, 0.0, 1e-300);
let sample = s.sample_reflection(frame(), Vec3::Z, view, [0.0, 0.0]).unwrap().unwrap();
assert!(sample.pdf.is_finite() && sample.pdf > 0.0 && sample.weight.is_finite());
// A mathematical density beyond f64 is a typed refusal, never clamped.
assert_eq!(s.sample_reflection(frame(), Vec3::Z, Vec3::new(1.0, 0.0, f64::from_bits(1)), [0.0, 0.0]), Err(AnisotropicError::Arithmetic));
}
}
#[test]
fn malformed_directions_and_variates_fail_without_clamping() {
let s = surface(0.5, 0.8);
for bad in [Vec3::ZERO, Vec3::new(f64::NAN, 0.0, 1.0), Vec3::new(f64::INFINITY, 0.0, 1.0)] {
assert!(s.brdf(frame(), Vec3::Z, bad, Vec3::Z).is_err());
assert!(s.brdf(frame(), bad, Vec3::Z, Vec3::Z).is_err());
assert!(s.brdf(frame(), Vec3::Z, Vec3::Z, bad).is_err());
assert!(s.normal_pdf(frame(), bad).is_err());
}
for bad in [-0.1, 1.0, f64::NAN, f64::INFINITY] {
assert!(s.sample_reflection(frame(), Vec3::Z, Vec3::Z, [bad, 0.5]).is_err());
assert!(s.sample_reflection(frame(), Vec3::Z, Vec3::Z, [0.5, bad]).is_err());
}
}
#[test]
fn sampled_slopes_follow_the_independent_inverse_radial_cdf() {
let s = surface(0.3, 0.7);
for u in [0.0, 0.01, 0.3, 0.8, 0.9999] {
for azimuth in [0.0, 0.2, 0.5, 0.8] {
let h = s.sample_normal(frame(), [u, azimuth]).unwrap();
let sx = h.x / (0.3_f64.powi(2) * h.z);
let sy = h.y / (0.7_f64.powi(2) * h.z);
let radius2 = sx * sx + sy * sy;
close(radius2 / (1.0 + radius2), u, 1e-13);
close_rgb(h, s.sample_normal(frame(), [u, azimuth]).unwrap(), 0.0);
}
}
}
#[test]
fn reflection_samples_match_pdf_and_specular_throughput() {
let s = surface(0.4, 0.8);
let view = unit_direction(Vec3::new(0.2, 0.3, 1.0)).unwrap();
let mut accepted = 0;
let mut null = 0;
for i in 0..32 {
for j in 0..32 {
let uv = [(i as f64 + 0.5) / 32.0, (j as f64 + 0.5) / 32.0];
match s.sample_reflection(frame(), Vec3::Z, view, uv).unwrap() {
Some(sample) => {
accepted += 1;
close(sample.pdf, s.reflection_pdf(frame(), Vec3::Z, view, sample.direction).unwrap(), 1e-13);
let expected = s.specular_brdf(frame(), Vec3::Z, view, sample.direction).unwrap() * (sample.direction.z / sample.pdf);
close_rgb(sample.weight, expected, 1e-10);
}
None => null += 1,
}
}
}
assert!(accepted > 0 && null > 0);
assert_eq!(accepted + null, 1024);
}
#[test]
fn unit_roughness_normal_view_has_half_null_mass_and_uniform_reflection_pdf() {
let s = surface(1.0, 1.0);
assert!(s.sample_reflection(frame(), Vec3::Z, Vec3::Z, [0.75, 0.3]).unwrap().is_none());
let sample = s.sample_reflection(frame(), Vec3::Z, Vec3::Z, [0.25, 0.3]).unwrap().unwrap();
close(sample.pdf, 1.0 / (4.0 * PI), 1e-14);
let mut accepted = 0;
for i in 0..1024 {
accepted += usize::from(s.sample_reflection(frame(), Vec3::Z, Vec3::Z, [(i as f64 + 0.5) / 1024.0, 0.3]).unwrap().is_some());
}
assert_eq!(accepted, 512);
// p(l)=1/(4*pi) over the upper hemisphere: valid mass exactly1/2.
close(s.reflection_pdf(frame(), Vec3::Z, Vec3::Z, Vec3::Z).unwrap() * (2.0 * PI), 0.5, 1e-14);
assert_eq!(s.reflection_pdf(frame(), Vec3::Z, Vec3::Z, -Vec3::Z).unwrap(), 0.0);
}
#[test]
fn invisible_microfacets_are_null_and_weights_exclude_the_diffuse_substrate() {
let s = AnisotropicSurface::new(Vec3::new(0.8, 0.5, 0.2), 0.0, 1.0, 1.0, 1.5).unwrap();
let view = unit_direction(Vec3::new(0.99, 0.0, 0.1)).unwrap();
assert!(s.sample_reflection(frame(), Vec3::Z, view, [0.9, 0.5]).unwrap().is_none());
let sample = s.sample_reflection(frame(), Vec3::Z, Vec3::Z, [0.1, 0.2]).unwrap().unwrap();
let scale = sample.direction.z / sample.pdf;
let specular = s.specular_brdf(frame(), Vec3::Z, Vec3::Z, sample.direction).unwrap() * scale;
let total = s.brdf(frame(), Vec3::Z, Vec3::Z, sample.direction).unwrap() * scale;
close_rgb(sample.weight, specular, 1e-13);
assert!(total.x > sample.weight.x + 0.1);
assert_eq!(s.normal_pdf(frame(), -Vec3::Z).unwrap(), 0.0);
assert_eq!(s.normal_pdf(frame(), Vec3::X).unwrap(), 0.0);
}
#[test]
fn quadrature_distinguishes_normal_pdf_mass_from_valid_reflection_mass() {
// Finite midpoint grids resolve these broad lobes only. Narrowest admitted
// roughness is tested analytically and with inverse-CDF samples elsewhere.
const N: usize = 256;
for (rx, ry) in [(1.0, 1.0), (0.6, 0.9)] {
let s = surface(rx, ry);
let mut normal_mass = 0.0;
let mut valid_mass = 0.0;
let mut accepted = 0;
for i in 0..N {
for j in 0..N {
let u = (i as f64 + 0.5) / N as f64;
let azimuth = (j as f64 + 0.5) / N as f64;
let l = hemisphere(u, TAU * azimuth);
normal_mass += s.normal_pdf(frame(), l).unwrap();
valid_mass += s.reflection_pdf(frame(), Vec3::Z, Vec3::Z, l).unwrap();
accepted += usize::from(s.sample_reflection(frame(), Vec3::Z, Vec3::Z, [u, azimuth]).unwrap().is_some());
}
}
let domega = TAU / (N * N) as f64;
close(normal_mass * domega, 1.0, 0.001);
close(valid_mass * domega, accepted as f64 / (N * N) as f64, 0.003);
assert!(valid_mass * domega < 1.0);
}
}
#[test]
fn broad_lobe_importance_estimate_agrees_with_integrated_energy() {
// White metal, normal view, deterministic256² grids. A scoped consistency
// check, not universal energy certification or a variance/convergence claim.
const N: usize = 256;
let s = AnisotropicSurface::new(Vec3::new(1.0, 1.0, 1.0), 1.0, 0.6, 0.9, 1.5).unwrap();
let mut integrated = Vec3::ZERO;
let mut sampled = Vec3::ZERO;
for i in 0..N {
for j in 0..N {
let uv = [(i as f64 + 0.5) / N as f64, (j as f64 + 0.5) / N as f64];
let light = hemisphere(uv[0], TAU * uv[1]);
integrated += s.specular_brdf(frame(), Vec3::Z, Vec3::Z, light).unwrap() * light.z;
if let Some(sample) = s.sample_reflection(frame(), Vec3::Z, Vec3::Z, uv).unwrap() {
sampled += sample.weight;
}
}
}
integrated = integrated * (TAU / (N * N) as f64);
sampled = sampled / (N * N) as f64; // Includes ALL null attempts.
assert!(integrated.x > 0.0 && integrated.x <= 1.001);
assert!(sampled.x > 0.0 && sampled.x <= 1.001);
close_rgb(integrated, sampled, 0.003);
}
+321
View File
@@ -0,0 +1,321 @@
//! Animated GIF (GIF89a) from RGBA frames, for motion animations. Every frame shares one palette,
//! so a colour keeps its value from frame to frame, and each frame after the first stores only
//! the rectangle that changed. The palette splits the frames' colours where that removes the
//! most squared colour error, so a small, strongly coloured part (a red part, a thin trace line)
//! keeps its colour instead of being averaged into the shading around it. No dithering: what
//! stands still stays still.
use std::collections::HashMap;
/// Colours a GIF palette holds.
const PALETTE: usize = 256;
/// Frames (straight RGBA, `width × height`, rows top to bottom; alpha is ignored) as a GIF that
/// loops forever and shows each frame for `delay` hundredths of a second. `None` without frames,
/// for a frame of the wrong size, or a side GIF can't store (above 65535).
pub fn gif(width: usize, height: usize, frames: &[Vec<u8>], delay: u16) -> Option<Vec<u8>> {
let (w, h) = (u16::try_from(width).ok().filter(|w| *w > 0)?, u16::try_from(height).ok().filter(|h| *h > 0)?);
let bytes = width.checked_mul(height)?.checked_mul(4)?;
if frames.is_empty() || frames.iter().any(|f| f.len() != bytes) {
return None;
}
let (palette, index) = palette(frames);
let mut out = Vec::with_capacity(1024);
out.extend_from_slice(b"GIF89a");
out.extend_from_slice(&w.to_le_bytes());
out.extend_from_slice(&h.to_le_bytes());
// A global table of 256 colours (8 bits each), background colour 0, square pixels.
out.extend_from_slice(&[0xF7, 0, 0]);
for k in 0..PALETTE {
out.extend_from_slice(palette.get(k).unwrap_or(&[0, 0, 0]));
}
// Loop forever (the NETSCAPE2.0 extension every viewer reads).
out.extend_from_slice(&[0x21, 0xFF, 0x0B]);
out.extend_from_slice(b"NETSCAPE2.0");
out.extend_from_slice(&[0x03, 0x01, 0x00, 0x00, 0x00]);
let mut previous: Option<Vec<u8>> = None;
for frame in frames {
let now = indices(frame, &index);
let (x0, y0, x1, y1) = previous.as_deref().map_or(Some((0, 0, width - 1, height - 1)), |p| changed(p, &now, width)).unwrap_or((0, 0, 0, 0));
let mut rect = Vec::with_capacity((x1 - x0 + 1) * (y1 - y0 + 1));
for y in y0..=y1 {
rect.extend_from_slice(now.get(y * width + x0..=y * width + x1)?);
}
// Graphic control: kept on screen under the next frame (disposal 1), shown `delay`.
out.extend_from_slice(&[0x21, 0xF9, 0x04, 0x04]);
out.extend_from_slice(&delay.to_le_bytes());
out.extend_from_slice(&[0, 0]);
out.push(0x2C);
for v in [x0, y0, x1 - x0 + 1, y1 - y0 + 1] {
out.extend_from_slice(&u16::try_from(v).ok()?.to_le_bytes());
}
out.push(0);
out.push(8);
let data = weezl::encode::Encoder::new(weezl::BitOrder::Lsb, 8).encode(&rect).ok()?;
for block in data.chunks(255) {
out.push(block.len() as u8);
out.extend_from_slice(block);
}
out.push(0);
previous = Some(now);
}
out.push(0x3B);
Some(out)
}
/// The pixels' colours, `0xRRGGBB`.
fn colours(frame: &[u8]) -> impl Iterator<Item = u32> + '_ {
frame.as_chunks::<4>().0.iter().map(|&[r, g, b, _]| (u32::from(r) << 16) | (u32::from(g) << 8) | u32::from(b))
}
/// A frame's palette indices.
fn indices(frame: &[u8], index: &HashMap<u32, u8>) -> Vec<u8> {
let mut last = (u32::MAX, 0);
colours(frame)
.map(|k| {
if k != last.0 {
last = (k, index.get(&k).copied().unwrap_or(0));
}
last.1
})
.collect()
}
/// The smallest rectangle (x0, y0, x1, y1, inclusive) holding every pixel that differs, or `None`
/// when none does.
fn changed(before: &[u8], now: &[u8], width: usize) -> Option<(usize, usize, usize, usize)> {
let mut r: Option<(usize, usize, usize, usize)> = None;
for (i, _) in before.iter().zip(now).enumerate().filter(|(_, (a, b))| a != b) {
let (x, y) = (i % width, i / width);
r = Some(r.map_or((x, y, x, y), |(x0, y0, x1, y1)| (x0.min(x), y0.min(y), x1.max(x), y1.max(y))));
}
r
}
/// How many pixels have a colour, and the sums its mean and squared error follow from.
#[derive(Clone, Copy, Default)]
struct Sums {
n: f64,
s: [f64; 3],
q: f64,
}
impl Sums {
fn of(rgb: u32, n: u64) -> Sums {
let n = n as f64;
let c = [f64::from((rgb >> 16) as u8), f64::from((rgb >> 8) as u8), f64::from(rgb as u8)];
Sums { n, s: c.map(|v| n * v), q: n * c.iter().map(|v| v * v).sum::<f64>() }
}
fn add(&mut self, o: &Sums) {
self.n += o.n;
self.q += o.q;
self.s.iter_mut().zip(o.s).for_each(|(a, b)| *a += b);
}
fn minus(&self, o: &Sums) -> Sums {
let mut s = *self;
s.n -= o.n;
s.q -= o.q;
s.s.iter_mut().zip(o.s).for_each(|(a, b)| *a -= b);
s
}
/// The squared distance of the pixels from their mean colour.
fn error(&self) -> f64 {
if self.n <= 0.0 { 0.0 } else { self.q - self.s.iter().map(|s| s * s).sum::<f64>() / self.n }
}
fn mean(&self) -> [u8; 3] {
self.s.map(|s| if self.n > 0.0 { (s / self.n).round().clamp(0.0, 255.0) as u8 } else { 0 })
}
}
/// A set of the frames' colours that becomes one palette entry, and its best split: (error
/// removed, channel, the largest value of that channel on the low side).
struct Group {
colours: Vec<(u32, Sums)>,
sums: Sums,
split: Option<(f64, u32, u8)>,
}
impl Group {
fn new(colours: Vec<(u32, Sums)>) -> Group {
let mut sums = Sums::default();
colours.iter().for_each(|(_, s)| sums.add(s));
let mut best: Option<(f64, u32, u8)> = None;
for channel in [16u32, 8, 0] {
let mut bins = [Sums::default(); 256];
for (k, s) in &colours {
if let Some(b) = bins.get_mut(usize::from((k >> channel) as u8)) {
b.add(s);
}
}
let mut low = Sums::default();
for (v, b) in bins.iter().enumerate() {
low.add(b);
if low.n <= 0.0 || low.n >= sums.n {
continue;
}
let gain = sums.error() - low.error() - sums.minus(&low).error();
if best.is_none_or(|(g, _, _)| gain > g) {
best = Some((gain, channel, v as u8));
}
}
}
Group { colours, sums, split: best.filter(|(g, _, _)| *g > 0.0) }
}
}
/// One palette for all frames (up to 256 colours) and each colour's index in it. Every colour
/// gets its own entry while there are 256 or fewer.
fn palette(frames: &[Vec<u8>]) -> (Vec<[u8; 3]>, HashMap<u32, u8>) {
let mut counts: HashMap<u32, u64> = HashMap::new();
for frame in frames {
// Runs of one colour (the background) are counted once per run.
let mut run = (u32::MAX, 0u64);
for k in colours(frame) {
if k != run.0 {
if run.1 > 0 {
*counts.entry(run.0).or_default() += run.1;
}
run = (k, 0);
}
run.1 += 1;
}
if run.1 > 0 {
*counts.entry(run.0).or_default() += run.1;
}
}
let mut groups = vec![Group::new(counts.into_iter().map(|(k, n)| (k, Sums::of(k, n))).collect())];
while groups.len() < PALETTE {
let Some(i) = groups.iter().enumerate().filter_map(|(i, g)| g.split.map(|s| (i, s.0))).max_by(|a, b| a.1.total_cmp(&b.1)).map(|(i, _)| i)
else {
break;
};
let g = groups.swap_remove(i);
let Some((_, channel, at)) = g.split else { break };
let (low, high) = g.colours.into_iter().partition(|(k, _)| (k >> channel) as u8 <= at);
groups.push(Group::new(low));
groups.push(Group::new(high));
}
let mut index = HashMap::new();
for (i, g) in groups.iter().enumerate() {
for (k, _) in &g.colours {
index.insert(*k, i as u8);
}
}
(groups.iter().map(|g| g.sums.mean()).collect(), index)
}
#[cfg(test)]
mod tests {
use super::*;
/// The frames of a GIF this module wrote, as RGBA (each frame drawn over the one before).
fn decode(gif: &[u8]) -> (usize, usize, Vec<Vec<u8>>, Vec<u16>) {
let u16_at = |i: usize| usize::from(u16::from_le_bytes([gif[i], gif[i + 1]]));
assert_eq!(&gif[..6], b"GIF89a");
let (w, h) = (u16_at(6), u16_at(8));
let table = &gif[13..13 + 768];
let mut at = 13 + 768;
let (mut frames, mut delays) = (Vec::new(), Vec::new());
let mut canvas = vec![0u8; w * h * 4];
loop {
match gif[at] {
0x3B => break,
0x21 => {
if gif[at + 1] == 0xF9 {
delays.push(u16_at(at + 4) as u16);
}
at += 2;
while gif[at] != 0 {
at += usize::from(gif[at]) + 1;
}
at += 1;
}
0x2C => {
let (x0, y0, fw, fh) = (u16_at(at + 1), u16_at(at + 3), u16_at(at + 5), u16_at(at + 7));
at += 11;
let mut data = Vec::new();
while gif[at] != 0 {
data.extend_from_slice(&gif[at + 1..at + 1 + usize::from(gif[at])]);
at += usize::from(gif[at]) + 1;
}
at += 1;
let pixels = weezl::decode::Decoder::new(weezl::BitOrder::Lsb, 8).decode(&data).unwrap();
assert_eq!(pixels.len(), fw * fh);
for (i, p) in pixels.iter().enumerate() {
let o = ((y0 + i / fw) * w + x0 + i % fw) * 4;
let c = usize::from(*p) * 3;
canvas[o..o + 4].copy_from_slice(&[table[c], table[c + 1], table[c + 2], 255]);
}
frames.push(canvas.clone());
}
b => panic!("unexpected block {b:#x} at {at}"),
}
}
(w, h, frames, delays)
}
fn frame(w: usize, h: usize, f: impl Fn(usize, usize) -> [u8; 3]) -> Vec<u8> {
(0..w * h).flat_map(|i| f(i % w, i / w).into_iter().chain([255])).collect()
}
#[test]
fn few_colours_come_back_exactly_and_frames_keep_their_size() {
let (w, h) = (37, 23);
let a = frame(w, h, |x, y| {
if x < 10 {
[250, 30, 30]
} else if y > 15 {
[20, 200, 60]
} else {
[220, 224, 230]
}
});
// The second frame moves the red band: only that part changes.
let b = frame(w, h, |x, y| {
if (5..15).contains(&x) {
[250, 30, 30]
} else if y > 15 {
[20, 200, 60]
} else {
[220, 224, 230]
}
});
let bytes = gif(w, h, &[a.clone(), b.clone(), b.clone()], 5).unwrap();
let (dw, dh, frames, delays) = decode(&bytes);
assert_eq!((dw, dh, delays), (w, h, vec![5, 5, 5]));
assert_eq!(frames, vec![a, b.clone(), b]);
}
#[test]
fn a_thin_saturated_line_keeps_its_colour_among_many_shades() {
let (w, h) = (300, 200);
// A grey shading with far more than 256 shades, a red part and a 1-pixel green line.
let f = frame(w, h, |x, y| {
if y == 100 {
[30, 220, 40]
} else if (40..80).contains(&x) && (40..80).contains(&y) {
[200 + (y as u8 % 40), 30, 30]
} else {
let g = 60 + ((x * 180) / w) as u8;
[g, g.saturating_add((y / 4) as u8), g.saturating_add(10)]
}
});
let (_, _, frames, _) = decode(&gif(w, h, std::slice::from_ref(&f), 4).unwrap());
let px = |img: &[u8], x: usize, y: usize| img[(y * w + x) * 4..(y * w + x) * 4 + 3].to_vec();
assert_eq!(px(&frames[0], 150, 100), vec![30, 220, 40], "the line keeps its colour");
let red = px(&frames[0], 60, 60);
assert!(red[0] > 180 && red[1] < 60 && red[2] < 60, "the part stays red: {red:?}");
// Elsewhere each channel is close to the original.
let worst = f.chunks(4).zip(frames[0].chunks(4)).map(|(a, b)| (0..3).map(|c| a[c].abs_diff(b[c])).max().unwrap()).max().unwrap();
assert!(worst <= 12, "worst channel error {worst}");
}
#[test]
fn bad_input_is_none_not_a_crash() {
assert!(gif(4, 4, &[], 5).is_none());
assert!(gif(4, 4, &[vec![0; 63]], 5).is_none());
assert!(gif(0, 4, &[vec![]], 5).is_none());
assert!(gif(70_000, 1, &[vec![0; 280_000]], 5).is_none());
assert!(gif(usize::MAX, 2, &[vec![0; 8]], 5).is_none());
}
}
+133
View File
@@ -0,0 +1,133 @@
//! Shared bounded, cancellable sRGB PNG row encoder for CPU image integrators.
use super::{CancelToken, ErrorCode, JobError, Result};
use std::io::Write;
use std::sync::{Arc, Mutex};
struct BufferWriter {
bytes: Arc<Mutex<Vec<u8>>>,
limit: usize,
cancel: CancelToken,
}
impl Write for BufferWriter {
fn write(&mut self, bytes: &[u8]) -> std::io::Result<usize> {
if self.cancel.is_cancelled() {
return Err(std::io::Error::other("render cancelled"));
}
let mut out = self.bytes.lock().map_err(|_| std::io::Error::other("PNG output lock poisoned"))?;
if out.len().checked_add(bytes.len()).is_none_or(|n| n > self.limit) {
return Err(std::io::Error::other("PNG output exceeds its byte budget"));
}
out.try_reserve_exact(bytes.len()).map_err(|_| std::io::Error::other("PNG allocation failed"))?;
out.extend_from_slice(bytes);
Ok(bytes.len())
}
fn flush(&mut self) -> std::io::Result<()> {
if self.cancel.is_cancelled() { Err(std::io::Error::other("render cancelled")) } else { Ok(()) }
}
}
pub(crate) struct PngEncoding {
bytes: Arc<Mutex<Vec<u8>>>,
writer: Option<png::StreamWriter<'static, BufferWriter>>,
width: usize,
height: usize,
row: usize,
cancel: CancelToken,
}
impl PngEncoding {
pub(crate) fn new(width: u32, height: u32, limit: u64, cancel: CancelToken) -> Result<Self> {
cancel.check()?;
let limit = usize::try_from(limit).map_err(|_| JobError::new(ErrorCode::LimitExceeded, "PNG byte budget exceeds addressable memory"))?;
let bytes = Arc::new(Mutex::new(Vec::new()));
let writer = BufferWriter { bytes: bytes.clone(), limit, cancel: cancel.clone() };
let mut encoder = png::Encoder::new(writer, width, height);
encoder.set_color(png::ColorType::Rgba);
encoder.set_depth(png::BitDepth::Eight);
encoder.set_source_srgb(png::SrgbRenderingIntent::Perceptual);
let writer =
encoder.write_header().and_then(|w| w.into_stream_writer()).map_err(|e| JobError::new(ErrorCode::EncodingFailed, e.to_string()))?;
Ok(Self { bytes, writer: Some(writer), width: width as usize, height: height as usize, row: 0, cancel })
}
pub(crate) fn row(&self) -> usize {
self.row
}
/// Writes at most one row; callers retain the four-row-per-quantum limit.
pub(crate) fn step(&mut self, rgba: &[u8]) -> Result<Option<Vec<u8>>> {
self.cancel.check()?;
if self.row < self.height {
let length = self.width.checked_mul(4).ok_or_else(|| JobError::new(ErrorCode::LimitExceeded, "PNG row overflow"))?;
let start = self.row.checked_mul(length).ok_or_else(|| JobError::new(ErrorCode::LimitExceeded, "PNG row offset overflow"))?;
let end = start.checked_add(length).ok_or_else(|| JobError::new(ErrorCode::LimitExceeded, "PNG row end overflow"))?;
let row = rgba.get(start..end).ok_or_else(|| JobError::new(ErrorCode::InvalidScene, "missing PNG row"))?;
self.writer
.as_mut()
.ok_or_else(|| JobError::new(ErrorCode::Internal, "missing PNG writer"))?
.write_all(row)
.map_err(|e| JobError::new(ErrorCode::EncodingFailed, e.to_string()))?;
self.row += 1;
return Ok(None);
}
self.writer
.take()
.ok_or_else(|| JobError::new(ErrorCode::Internal, "missing PNG writer"))?
.finish()
.map_err(|e| JobError::new(ErrorCode::EncodingFailed, e.to_string()))?;
self.cancel.check()?;
let mut bytes = self.bytes.lock().map_err(|_| JobError::new(ErrorCode::Internal, "PNG output lock poisoned"))?;
let png = std::mem::take(&mut *bytes);
if !png.starts_with(b"\x89PNG\r\n\x1a\n") {
return Err(JobError::new(ErrorCode::EncodingFailed, "invalid PNG output"));
}
Ok(Some(png))
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn rows_roundtrip_and_cancel_before_finish_never_returns_png() {
let rgba = [20, 40, 60, 255, 80, 100, 120, 255];
let cancel = CancelToken::default();
let mut encoder = PngEncoding::new(1, 2, 65536, cancel.clone()).unwrap();
assert!(encoder.step(&rgba).unwrap().is_none());
assert_eq!(encoder.row(), 1);
assert!(encoder.step(&rgba).unwrap().is_none());
assert_eq!(encoder.row(), 2);
cancel.cancel();
assert_eq!(encoder.step(&rgba).unwrap_err().code, ErrorCode::Cancelled);
let mut encoder = PngEncoding::new(1, 2, 65536, CancelToken::default()).unwrap();
assert!(encoder.step(&rgba).unwrap().is_none());
assert!(encoder.step(&rgba).unwrap().is_none());
let png = encoder.step(&rgba).unwrap().unwrap();
let decoded = image::load_from_memory(&png).unwrap().to_rgba8();
assert_eq!(decoded.dimensions(), (1, 2));
assert_eq!(decoded.as_raw(), &rgba);
}
#[test]
fn encoded_byte_budget_and_missing_rows_are_errors() {
assert!(PngEncoding::new(1, 1, 1, CancelToken::default()).is_err());
let mut encoder = PngEncoding::new(1, 1, 65536, CancelToken::default()).unwrap();
assert_eq!(encoder.step(&[]).unwrap_err().code, ErrorCode::InvalidScene);
}
#[test]
fn png_output_budget_and_cancellation_fail_without_partial_publication() {
let bytes = Arc::new(Mutex::new(Vec::new()));
let cancel = CancelToken::default();
let mut writer = BufferWriter { bytes: bytes.clone(), limit: 4, cancel: cancel.clone() };
writer.write_all(b"PNG").unwrap();
assert!(writer.write_all(b"too large").is_err());
assert_eq!(*bytes.lock().unwrap(), b"PNG");
cancel.cancel();
assert!(writer.write_all(b"x").is_err());
assert!(writer.flush().is_err());
assert_eq!(*bytes.lock().unwrap(), b"PNG");
}
}
+272 -12
View File
@@ -12,8 +12,8 @@ use std::sync::{
use serde::Serialize;
use super::{
Admission, AlphaConvention, CancelToken, ColourEncoding, ErrorCode, FrameInfo, ImageRequest, ImageTask, JobError, JobId, Phase, Progress, Result,
TaskPoll, admit,
Admission, AlphaConvention, CancelToken, ColourEncoding, ErrorCode, FrameInfo, ImageRequest, ImageTask, Integrator, JobError, JobId, Phase,
Progress, Result, TaskPoll, admit,
};
use crate::{
Availability, ExecutorDescriptor, ExecutorId, ProductScene, RenderFormat, RenderLimits, RenderMode, RenderOperation, RenderProfile, ScratchLayout,
@@ -73,6 +73,18 @@ impl Drop for Reservation {
}
}
/// Retained runtime input capacities survive work/PNG eviction through status handles.
fn retained_request_bytes(request: &ImageRequest) -> Result<u64> {
request.raytrace.as_ref().map_or(Ok(0), |options| options.retained_bytes())
}
fn admit_request_sum(work_bytes: u64, request_bytes: u64) -> Result<()> {
if work_bytes.checked_add(request_bytes).is_none_or(|sum| sum > super::image::MAX_JOB_BYTES) {
return Err(JobError::new(ErrorCode::LimitExceeded, "render work and retained request exceed 384 MiB per-job admission"));
}
Ok(())
}
/// Borrow encoded bytes through the frame, so retaining the data also retains its admission lease.
pub struct RenderFrame {
pub info: FrameInfo,
@@ -87,6 +99,8 @@ impl RenderFrame {
#[derive(Clone, Debug, Serialize)]
pub struct JobStatus {
#[serde(skip_serializing_if = "Option::is_none")]
pub environment: Option<crate::lighting::environment_input::EnvironmentInfo>,
pub job: JobId,
pub scene_generation: u64,
pub request: ImageRequest,
@@ -102,6 +116,8 @@ struct Data {
frame: Option<Arc<RenderFrame>>,
}
struct Record {
environment: Option<crate::lighting::environment_input::EnvironmentInfo>,
_request_reservation: Option<Reservation>,
id: JobId,
scene_generation: u64,
request: ImageRequest,
@@ -129,6 +145,7 @@ impl JobHandle {
pub fn status(&self) -> Result<JobStatus> {
let data = self.0.data.lock().map_err(|_| JobError::new(ErrorCode::Internal, "render status lock poisoned"))?;
Ok(JobStatus {
environment: self.0.environment.clone(),
job: self.0.id,
scene_generation: self.0.scene_generation,
request: self.0.request.clone(),
@@ -176,16 +193,78 @@ impl JobHandle {
}
struct Work {
environment: Option<crate::lighting::environment_input::EnvironmentInput>,
scene: ProductScene,
handle: JobHandle,
reservation: Reservation,
}
struct Running {
task: ImageTask,
task: Option<WorkTask>,
handle: JobHandle,
reservation: Option<Reservation>,
}
/// One fallibly allocated task, keeping the dispatch enum small in either build.
/// Its bounded metadata allocation fits the existing per-job task allowance.
struct TaskSlot<T>(Vec<T>);
impl<T> TaskSlot<T> {
fn new(task: T) -> Result<Self> {
if std::mem::size_of::<T>() > 4096 {
return Err(JobError::new(ErrorCode::LimitExceeded, "render task metadata exceeds its admission allowance"));
}
let mut tasks = Vec::new();
tasks.try_reserve_exact(1).map_err(|_| JobError::new(ErrorCode::AllocationFailed, "could not reserve render task slot"))?;
if tasks.capacity() != 1 {
return Err(JobError::new(ErrorCode::LimitExceeded, "render task slot exceeds its bounded capacity"));
}
tasks.push(task);
Ok(Self(tasks))
}
fn get_mut(&mut self) -> Result<&mut T> {
self.0.first_mut().ok_or_else(|| JobError::new(ErrorCode::Internal, "missing render task slot"))
}
}
enum WorkTask {
Raster(TaskSlot<ImageTask>),
#[cfg(feature = "raytrace-cpu")]
Raytrace(TaskSlot<crate::raytrace::image::ImageTask>),
}
impl WorkTask {
fn new(
scene: ProductScene,
request: ImageRequest,
cancel: CancelToken,
environment: Option<crate::lighting::environment_input::EnvironmentInput>,
) -> Result<Self> {
let _ = &environment;
match request.integrator {
Integrator::Raster => ImageTask::new(scene, request, cancel).and_then(TaskSlot::new).map(Self::Raster),
Integrator::Raytrace => {
#[cfg(feature = "raytrace-cpu")]
{
let options = request.raytrace.clone().unwrap_or_default();
crate::raytrace::image::ImageTask::new_with_environment(scene, request, cancel, options, environment)
.and_then(TaskSlot::new)
.map(Self::Raytrace)
}
#[cfg(not(feature = "raytrace-cpu"))]
{
Err(JobError::new(ErrorCode::HostUnavailable, "CPU raytracing is not compiled in; enable raytrace-cpu"))
}
}
}
}
fn step(&mut self, units: usize) -> Result<TaskPoll> {
match self {
Self::Raster(task) => task.get_mut()?.step(units),
#[cfg(feature = "raytrace-cpu")]
Self::Raytrace(task) => task.get_mut()?.step(units),
}
}
}
fn terminal(handle: &JobHandle, error: JobError) {
if let Ok(mut data) = handle.0.data.lock() {
if data.progress.phase == Phase::Completed {
@@ -214,9 +293,9 @@ impl Running {
{
data.progress.phase = Phase::Preparing;
}
let task = ImageTask::new(work.scene, work.handle.0.request.clone(), work.handle.0.cancel.clone());
let task = WorkTask::new(work.scene, work.handle.0.request.clone(), work.handle.0.cancel.clone(), work.environment);
match task {
Ok(task) => Some(Self { task, handle: work.handle, reservation: Some(work.reservation) }),
Ok(task) => Some(Self { task: Some(task), handle: work.handle, reservation: Some(work.reservation) }),
Err(e) => {
terminal(&work.handle, e);
None
@@ -225,7 +304,7 @@ impl Running {
}
fn advance(&mut self, units: usize) -> Result<bool> {
let result = self.task.step(units)?;
let result = self.task.as_mut().ok_or_else(|| JobError::new(ErrorCode::Internal, "missing render task"))?.step(units)?;
let mut data = self.handle.0.data.lock().map_err(|_| JobError::new(ErrorCode::Internal, "render status lock poisoned"))?;
// The final publication check is under the same lock as cancellation.
if self.handle.0.cancel.is_cancelled() {
@@ -240,6 +319,9 @@ impl Running {
Ok(true)
}
TaskPoll::Complete(png) => {
// Release all integrator scratch before shrinking the shared lease
// to the completed PNG. Retained task metadata also owns memory.
self.task = None;
let mut reservation = self.reservation.take().ok_or_else(|| JobError::new(ErrorCode::Internal, "missing render reservation"))?;
reservation.shrink(png.capacity() as u64 + 1024)?;
let info = FrameInfo {
@@ -376,10 +458,39 @@ impl CpuHost {
}
pub fn descriptor(&self) -> Result<ExecutorDescriptor> {
self.descriptor_for(Integrator::Raster)
}
/// Check the execution choice without capturing geometry or reserving memory.
pub fn validate_integrator(&self, integrator: Integrator) -> Result<()> {
if !self.is_available() {
return Err(JobError::new(ErrorCode::HostUnavailable, "CPU image host has stopped"));
}
if integrator == Integrator::Raytrace && !cfg!(feature = "raytrace-cpu") {
return Err(JobError::new(ErrorCode::HostUnavailable, "CPU raytracing is not compiled in; enable raytrace-cpu"));
}
if integrator == Integrator::Raytrace && self.kind() != HostKind::NativeWorker {
return Err(JobError::new(ErrorCode::HostUnavailable, "CPU raytracing requires the native worker host"));
}
Ok(())
}
/// Select exactly one executor for this request. Never rely on registry order
/// to choose between raster and raytracing implementations.
pub fn descriptor_for(&self, integrator: Integrator) -> Result<ExecutorDescriptor> {
if integrator == Integrator::Raytrace && !cfg!(feature = "raytrace-cpu") {
return Err(JobError::new(ErrorCode::HostUnavailable, "CPU raytracing is not compiled in; enable raytrace-cpu"));
}
Ok(ExecutorDescriptor {
id: ExecutorId::new("cpu-product").map_err(|e| JobError::new(ErrorCode::Internal, e.to_string()))?,
id: ExecutorId::new(match integrator {
Integrator::Raster => "cpu-product",
Integrator::Raytrace => "cpu-raytrace",
})
.map_err(|e| JobError::new(ErrorCode::Internal, e.to_string()))?,
availability: if self.0.shared.stop.load(Ordering::Acquire) {
Availability::Unavailable { reason: "CPU image host has stopped".into() }
} else if integrator == Integrator::Raytrace && self.kind() != HostKind::NativeWorker {
Availability::Unavailable { reason: "CPU raytracing requires the native worker host".into() }
} else {
Availability::Available
},
@@ -387,7 +498,11 @@ impl CpuHost {
mode: RenderMode::Preview,
operation: RenderOperation::Image,
formats: vec![RenderFormat::Png],
features: vec![crate::RenderFeature::Pbr],
features: if integrator == Integrator::Raytrace && cfg!(feature = "raytrace-cpu") && self.kind() == HostKind::NativeWorker {
vec![crate::RenderFeature::Pbr, crate::RenderFeature::Hdri]
} else {
vec![crate::RenderFeature::Pbr]
},
}],
limits: RenderLimits::default(),
scratch: ScratchLayout { sample_scale: 2, sample_bytes_per_pixel: 8, output_bytes_per_pixel: 8, encoding_bytes_per_pixel: 8 },
@@ -395,12 +510,49 @@ impl CpuHost {
}
pub fn submit(&self, id: JobId, scene_generation: u64, scene: ProductScene, request: ImageRequest) -> Result<JobHandle> {
self.submit_with_environment(id, scene_generation, scene, request, None)
}
/// Captured HDR ownership stays in work, never serialized/cloned into status.
pub fn submit_with_environment(
&self,
id: JobId,
scene_generation: u64,
scene: ProductScene,
request: ImageRequest,
environment: Option<crate::lighting::environment_input::EnvironmentInput>,
) -> Result<JobHandle> {
if environment.is_some() && request.integrator != Integrator::Raytrace {
return Err(JobError::new(ErrorCode::InvalidRequest, "environment lighting requires CPU raytrace"));
}
self.validate_integrator(request.integrator)?;
if environment.is_some() {
request.raytrace.as_ref().unwrap_or(&super::RaytraceOptions::default()).validate_environment_reflections(&scene)?;
}
if id.session == 0 || id.serial == 0 || id.generation == 0 {
return Err(JobError::new(ErrorCode::InvalidRequest, "invalid render job identity"));
}
let environment_info = environment.as_ref().map(|e| e.metadata());
let metadata_bytes =
if environment_info.is_some() { std::mem::size_of::<crate::lighting::environment_input::EnvironmentInfo>() as u64 } else { 0 };
let request_bytes = retained_request_bytes(&request)?
.checked_add(metadata_bytes)
.ok_or_else(|| JobError::new(ErrorCode::LimitExceeded, "environment metadata overflow"))?;
let mut features = scene.required_features();
if environment.is_some() {
features.push(crate::RenderFeature::Hdri);
}
let Admission { estimated_total_bytes, .. } = admit(&scene, &request)?;
let environment_bytes =
environment.as_ref().map_or(Ok(0), |e| e.required_bytes()).map_err(|e| JobError::new(ErrorCode::InvalidRequest, e.to_string()))?;
let estimated_total_bytes = estimated_total_bytes
.checked_add(environment_bytes)
.ok_or_else(|| JobError::new(ErrorCode::LimitExceeded, "environment admission overflow"))?;
admit_request_sum(estimated_total_bytes, request_bytes)?;
let mut backend = crate::builtin_backend();
backend.executors.push(self.descriptor()?);
let descriptor = self.descriptor_for(request.integrator)?;
let expected_executor = descriptor.id.clone();
backend.executors = vec![descriptor];
let resolved = crate::resolve_request(
&[backend],
&crate::RenderRequest {
@@ -410,12 +562,12 @@ impl CpuHost {
width: u64::from(request.width),
height: u64::from(request.height),
format: Some(RenderFormat::Png),
features: scene.required_features(),
features,
policy: Default::default(),
},
)
.map_err(|e| JobError::new(ErrorCode::HostUnavailable, e.to_string()))?;
if resolved.executor.as_str() != "cpu-product" {
if resolved.executor != expected_executor {
return Err(JobError::new(ErrorCode::HostUnavailable, "CPU product executor is unavailable"));
}
let mut queue = self.0.shared.queue.lock().map_err(|_| JobError::new(ErrorCode::HostUnavailable, "render queue lock poisoned"))?;
@@ -426,8 +578,12 @@ impl CpuHost {
if queue.len() >= QUEUE_LIMIT {
return Err(JobError::new(ErrorCode::QueueFull, "CPU image queue is full"));
}
admit_request_sum(estimated_total_bytes, request_bytes)?;
let reservation = self.0.shared.budget.reserve(estimated_total_bytes)?;
let request_reservation = if request_bytes == 0 { None } else { Some(self.0.shared.budget.reserve(request_bytes)?) };
let handle = JobHandle(Arc::new(Record {
environment: environment_info,
_request_reservation: request_reservation,
id,
scene_generation,
request,
@@ -437,7 +593,7 @@ impl CpuHost {
#[cfg(not(target_arch = "wasm32"))]
done: Condvar::new(),
}));
queue.push_back(Work { scene, handle: handle.clone(), reservation });
queue.push_back(Work { scene, handle: handle.clone(), reservation, environment });
drop(queue);
#[cfg(not(target_arch = "wasm32"))]
self.0.shared.wake.notify_one();
@@ -514,3 +670,107 @@ fn native_worker(shared: Arc<Shared>) {
}
}
}
#[cfg(test)]
mod retained_request_tests {
use super::*;
fn request() -> ImageRequest {
let mut lights = Vec::with_capacity(8);
lights.push(super::super::DirectionalLightOptions { direction: [0.0, 0.0, 1.0], color: [1.0; 3], intensity: 1.0 });
ImageRequest {
integrator: Integrator::Raytrace,
raytrace: Some(super::super::RaytraceOptions { lights: Some(lights), ..Default::default() }),
camera: Default::default(),
width: 8,
height: 8,
background: [0; 3],
transparent_background: false,
}
}
#[test]
fn retained_lights_are_billed_by_original_capacity_and_sum_is_checked() {
let request = request();
let bytes = retained_request_bytes(&request).unwrap();
assert_eq!(bytes, 8 * std::mem::size_of::<super::super::DirectionalLightOptions>() as u64);
let cap = super::super::image::MAX_JOB_BYTES;
assert!(admit_request_sum(cap - bytes, bytes).is_ok());
assert_eq!(admit_request_sum(cap - bytes + 1, bytes).unwrap_err().code, ErrorCode::LimitExceeded);
assert_eq!(admit_request_sum(u64::MAX, 1).unwrap_err().code, ErrorCode::LimitExceeded);
}
#[cfg(all(feature = "raytrace-cpu", not(target_arch = "wasm32")))]
#[test]
fn retained_lights_keep_the_same_pool_lease_after_png_eviction() {
let host = CpuHost::for_platform().unwrap();
let request = request();
let expected = retained_request_bytes(&request).unwrap();
let job = host
.submit(
JobId { session: 99, serial: 1, generation: 1 },
1,
ProductScene { meshes: Vec::new(), bounds: solidcraft_geom::Aabb3::EMPTY },
request,
)
.unwrap();
assert_eq!(job.wait_timeout(std::time::Duration::from_secs(60)).unwrap().progress.phase, Phase::Completed);
let frame = job.frame().unwrap().unwrap();
let held_bytes = host.admitted_bytes();
assert!(held_bytes > expected);
job.0.data.lock().unwrap().frame = None;
assert_eq!(host.admitted_bytes(), held_bytes);
drop(frame);
assert_eq!(host.admitted_bytes(), expected);
let held = job.clone();
drop(job);
assert_eq!(host.admitted_bytes(), expected);
drop(held);
}
}
#[cfg(all(test, feature = "raytrace-cpu", not(target_arch = "wasm32")))]
mod environment_metadata_lease_tests {
use super::*;
#[test]
fn captured_environment_metadata_survives_png_eviction_without_source_bytes() {
use crate::lighting::{
HdrSource,
environment_input::{EnvironmentInfo, EnvironmentInput},
};
let mut bytes = b"#?RADIANCE\nFORMAT=32-bit_rle_rgbe\nPRIMARIES=0.64 0.33 0.30 0.60 0.15 0.06 0.3127 0.3290\n\n-Y 2 +X 4\n".to_vec();
for _ in 0..8 {
bytes.extend_from_slice(&[128, 64, 32, 129]);
}
let input = EnvironmentInput::new(HdrSource::new(bytes).unwrap(), 0.5, 2.0, 16).unwrap();
let metadata = input.metadata();
let expected = std::mem::size_of::<EnvironmentInfo>() as u64;
let host = CpuHost::for_platform().unwrap();
let budget = host.0.shared.budget.clone();
let request = ImageRequest {
integrator: Integrator::Raytrace,
raytrace: None,
camera: Default::default(),
width: 8,
height: 8,
background: [0; 3],
transparent_background: false,
};
let job = host
.submit_with_environment(
JobId { session: 1693, serial: 7, generation: 1 },
1,
ProductScene { meshes: Vec::new(), bounds: solidcraft_geom::Aabb3::EMPTY },
request,
Some(input),
)
.unwrap();
let status = job.wait_timeout(std::time::Duration::from_secs(60)).unwrap();
assert_eq!(status.progress.phase, Phase::Completed);
assert_eq!(status.environment.unwrap().source_sha256, metadata.source_sha256);
let frame = job.frame().unwrap().unwrap();
job.0.data.lock().unwrap().frame = None;
assert_eq!(host.admitted_bytes(), frame._reservation.bytes + expected);
drop(frame);
assert_eq!(host.admitted_bytes(), expected);
drop(host);
drop(job);
assert_eq!(budget.used.load(Ordering::Acquire), 0);
}
}
+42 -1
View File
@@ -2,7 +2,48 @@ use super::*;
use solidcraft_geom::{Aabb3, Mesh};
fn request() -> ImageRequest {
ImageRequest { camera: Default::default(), width: 16, height: 16, background: [40, 80, 120], transparent_background: false }
ImageRequest {
integrator: Default::default(),
raytrace: None,
camera: Default::default(),
width: 16,
height: 16,
background: [40, 80, 120],
transparent_background: false,
}
}
#[test]
fn legacy_image_requests_default_to_raster_and_reject_unknown_integrators() {
let mut value = serde_json::to_value(request()).unwrap();
value.as_object_mut().unwrap().remove("integrator");
let decoded: ImageRequest = serde_json::from_value(value.clone()).unwrap();
assert_eq!(decoded.integrator, Integrator::Raster);
value["integrator"] = serde_json::json!("gpu_pathtrace");
assert!(serde_json::from_value::<ImageRequest>(value).is_err());
}
#[cfg(feature = "raytrace-cpu")]
#[test]
fn cooperative_raytrace_descriptor_matches_native_only_validation() {
let host = CpuHost::cooperative();
assert!(host.validate_integrator(Integrator::Raytrace).is_err());
assert!(matches!(host.descriptor_for(Integrator::Raytrace).unwrap().availability, Availability::Unavailable { .. }));
assert!(host.validate_integrator(Integrator::Raster).is_ok());
}
#[cfg(not(feature = "raytrace-cpu"))]
#[test]
fn compiled_out_raytracing_never_enters_the_host_queue() {
let host = CpuHost::cooperative();
let mut request = request();
request.integrator = Integrator::Raytrace;
assert!(host.validate_integrator(Integrator::Raytrace).unwrap_err().message.contains("not compiled in"));
assert!(host.descriptor_for(Integrator::Raytrace).is_err());
let error = host.submit(JobId { session: 1, serial: 1, generation: 1 }, 0, empty(), request).err().unwrap();
assert_eq!(error.code, ErrorCode::HostUnavailable);
assert_eq!(host.admitted_bytes(), 0);
assert!(!host.pump(1).unwrap());
}
fn empty() -> ProductScene {
ProductScene { meshes: Vec::new(), bounds: Aabb3::EMPTY }
+41 -65
View File
@@ -1,8 +1,6 @@
//! Incremental product rasterization. Every phase yields between bounded work units.
use std::collections::BTreeMap;
use std::io::Write;
use std::sync::{Arc, Mutex};
use serde::Serialize;
use solidcraft_geom::Vec3;
@@ -50,6 +48,31 @@ fn add_bytes(sum: &mut u64, count: usize, size: usize) -> Result<()> {
/// Conservative admission before allocating pixels or projected-work lists. Source Arcs are
/// counted even when another owner already holds them. Allocator and codec internals are estimates.
pub fn admit(scene: &ProductScene, request: &ImageRequest) -> Result<Admission> {
match request.integrator {
super::Integrator::Raster => {
if request.raytrace.is_some() {
return Err(JobError::new(ErrorCode::InvalidRequest, "raytrace options require integrator: raytrace"));
}
admit_base(scene, request)
}
super::Integrator::Raytrace => {
#[cfg(feature = "raytrace-cpu")]
{
let defaults = super::RaytraceOptions::default();
let options = request.raytrace.as_ref().unwrap_or(&defaults);
options.validate()?;
crate::raytrace::image::admit(scene, request, options)
}
#[cfg(not(feature = "raytrace-cpu"))]
{
Err(JobError::new(ErrorCode::HostUnavailable, "CPU raytracing is not compiled in; enable raytrace-cpu"))
}
}
}
}
/// Shared dimension/source admission; integrators add their own complete work budgets.
pub(crate) fn admit_base(scene: &ProductScene, request: &ImageRequest) -> Result<Admission> {
if !request.camera.is_valid() {
return Err(JobError::new(ErrorCode::InvalidRequest, "invalid image camera"));
}
@@ -176,30 +199,6 @@ enum Stage {
Done,
}
struct BufferWriter {
bytes: Arc<Mutex<Vec<u8>>>,
limit: usize,
cancel: CancelToken,
}
impl Write for BufferWriter {
fn write(&mut self, bytes: &[u8]) -> std::io::Result<usize> {
if self.cancel.is_cancelled() {
return Err(std::io::Error::other("render cancelled"));
}
let mut out = self.bytes.lock().map_err(|_| std::io::Error::other("PNG output lock poisoned"))?;
if out.len().checked_add(bytes.len()).is_none_or(|n| n > self.limit) {
return Err(std::io::Error::other("PNG output exceeds its byte budget"));
}
out.try_reserve_exact(bytes.len()).map_err(|_| std::io::Error::other("PNG allocation failed"))?;
out.extend_from_slice(bytes);
Ok(bytes.len())
}
fn flush(&mut self) -> std::io::Result<()> {
if self.cancel.is_cancelled() { Err(std::io::Error::other("render cancelled")) } else { Ok(()) }
}
}
pub enum TaskPoll {
Pending(Progress),
Complete(Vec<u8>),
@@ -238,14 +237,15 @@ pub struct ImageTask {
draw: usize,
triangle: Option<Triangle>,
output: Vec<u8>,
encoded: Arc<Mutex<Vec<u8>>>,
encoder: Option<png::StreamWriter<'static, BufferWriter>>,
row: usize,
encoder: Option<super::encoding::PngEncoding>,
}
impl ImageTask {
pub fn new(scene: ProductScene, request: ImageRequest, cancel: CancelToken) -> Result<Self> {
cancel.check()?;
if request.integrator != super::Integrator::Raster {
return Err(JobError::new(ErrorCode::InvalidRequest, "raster task cannot execute a raytrace request"));
}
let admission = admit(&scene, &request)?;
let (sw, sh) = (request.width as usize * SS, request.height as usize * SS);
let radius = scene.bounds.diagonal().max(10.0) + scene.bounds.center().dist(request.camera.target);
@@ -289,9 +289,7 @@ impl ImageTask {
draw: 0,
triangle: None,
output,
encoded: Arc::new(Mutex::new(Vec::new())),
encoder: None,
row: 0,
})
}
@@ -307,7 +305,11 @@ impl ImageTask {
done: self.pixel_done,
total: self.pixel_tests + (self.sw * self.sh) as u64 + u64::from(self.request.width) * u64::from(self.request.height),
},
Stage::Encode => Progress { phase: Phase::Encoding, done: self.row as u64, total: u64::from(self.request.height) },
Stage::Encode => Progress {
phase: Phase::Encoding,
done: self.encoder.as_ref().map_or(0, |encoder| encoder.row() as u64),
total: u64::from(self.request.height),
},
Stage::Done => Progress { phase: Phase::Completed, done: 1, total: 1 },
}
}
@@ -562,14 +564,8 @@ impl ImageTask {
let width = self.request.width as usize;
let index = self.output.len() / 4;
if index >= width * self.request.height as usize {
let writer = BufferWriter { bytes: self.encoded.clone(), limit: self.admission.encoded_limit as usize, cancel: self.cancel.clone() };
let mut encoder = png::Encoder::new(writer, self.request.width, self.request.height);
encoder.set_color(png::ColorType::Rgba);
encoder.set_depth(png::BitDepth::Eight);
encoder.set_source_srgb(png::SrgbRenderingIntent::Perceptual);
self.encoder = Some(
encoder.write_header().and_then(|w| w.into_stream_writer()).map_err(|e| JobError::new(ErrorCode::EncodingFailed, e.to_string()))?,
);
self.encoder =
Some(super::encoding::PngEncoding::new(self.request.width, self.request.height, self.admission.encoded_limit, self.cancel.clone())?);
self.stage = Stage::Encode;
// Pixels and prepared geometry are no longer needed during PNG compression.
self.pixels = Vec::new();
@@ -600,32 +596,12 @@ impl ImageTask {
}
fn encode_step(&mut self) -> Result<Option<Vec<u8>>> {
if self.row < self.request.height as usize {
let length = self.request.width as usize * 4;
let start = self.row * length;
let row = self.output.get(start..start + length).ok_or_else(|| invalid("missing PNG row"))?;
self.encoder
.as_mut()
.ok_or_else(|| invalid("missing PNG writer"))?
.write_all(row)
.map_err(|e| JobError::new(ErrorCode::EncodingFailed, e.to_string()))?;
self.row += 1;
return Ok(None);
let result = self.encoder.as_mut().ok_or_else(|| invalid("missing PNG writer"))?.step(&self.output)?;
if result.is_some() {
self.output = Vec::new();
self.stage = Stage::Done;
}
self.encoder
.take()
.ok_or_else(|| invalid("missing PNG writer"))?
.finish()
.map_err(|e| JobError::new(ErrorCode::EncodingFailed, e.to_string()))?;
self.cancel.check()?;
let mut bytes = self.encoded.lock().map_err(|_| JobError::new(ErrorCode::Internal, "PNG output lock poisoned"))?;
let png = std::mem::take(&mut *bytes);
if !png.starts_with(b"\x89PNG\r\n\x1a\n") {
return Err(JobError::new(ErrorCode::EncodingFailed, "invalid PNG output"));
}
self.output = Vec::new();
self.stage = Stage::Done;
Ok(Some(png))
Ok(result)
}
}
+12 -17
View File
@@ -1,11 +1,20 @@
use super::*;
use crate::{Camera, ProductMesh, StandardView};
use solidcraft_geom::{Aabb3, Mesh};
use std::sync::Arc;
fn request() -> ImageRequest {
let mut camera = Camera { distance: 50.0, ..Default::default() };
camera.set_view(StandardView::Front);
ImageRequest { camera, width: 64, height: 64, background: [20, 40, 60], transparent_background: true }
ImageRequest {
integrator: Default::default(),
raytrace: None,
camera,
width: 64,
height: 64,
background: [20, 40, 60],
transparent_background: true,
}
}
fn square(name: &str, colour: [u8; 3], opacity: f64, offset: Vec3) -> ProductMesh {
@@ -93,9 +102,9 @@ fn encoding_yields_between_rows_and_completed_result_is_consumed_once() {
while task.stage != Stage::Encode {
assert!(matches!(task.step(64).unwrap(), TaskPoll::Pending(_)));
}
let before = task.row;
let before = task.encoder.as_ref().unwrap().row();
assert!(matches!(task.step(usize::MAX).unwrap(), TaskPoll::Pending(_)));
assert!(task.row - before <= 4);
assert!(task.encoder.as_ref().unwrap().row() - before <= 4);
loop {
if let TaskPoll::Complete(bytes) = task.step(4096).unwrap() {
assert_eq!(image::load_from_memory(&bytes).unwrap().width(), 64);
@@ -131,17 +140,3 @@ fn invalid_sizes_indices_opacity_and_large_work_lists_fail_without_a_frame() {
assert_eq!(ImageTask::new(scene(vec![body]), request(), CancelToken::default()).err().unwrap().code, ErrorCode::LimitExceeded);
assert_eq!(std::mem::size_of::<Draw>(), 16, "admission accounts for each of the three lists");
}
#[test]
fn png_output_budget_and_cancellation_fail_without_partial_publication() {
let bytes = Arc::new(Mutex::new(Vec::new()));
let cancel = CancelToken::default();
let mut writer = BufferWriter { bytes: bytes.clone(), limit: 4, cancel: cancel.clone() };
writer.write_all(b"PNG").unwrap();
assert!(writer.write_all(b"too large").is_err());
assert_eq!(*bytes.lock().unwrap(), b"PNG");
cancel.cancel();
assert!(writer.write_all(b"x").is_err());
assert!(writer.flush().is_err());
assert_eq!(*bytes.lock().unwrap(), b"PNG");
}
+307 -1
View File
@@ -11,8 +11,11 @@ use serde::{Deserialize, Serialize};
use crate::{BackendId, Camera, ExecutorId};
pub(crate) mod encoding;
mod host;
mod image;
pub(crate) mod image;
#[cfg(test)]
mod rt2_tests;
pub use host::{CpuHost, HostKind, JobHandle, JobStatus, RenderFrame};
pub use image::{Admission, ImageTask, TaskPoll, admit};
@@ -104,10 +107,290 @@ impl CancelToken {
}
}
/// Per-request execution choice, independent of viewport graphics presets.
/// Keep both variants parseable in builds without optional raytracing, so those
/// builds return an explicit capability error before capturing model geometry.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum Integrator {
#[default]
Raster,
Raytrace,
}
/// Explicit scene-reflection transport, separate from opaque roughness bounds.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ReflectionMode {
Mirror,
RoughSpecular,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct ReflectionBody {
pub body: String,
pub mode: ReflectionMode,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(default, deny_unknown_fields)]
pub struct ReflectionOptions {
#[serde(deserialize_with = "bounded_reflection_bodies")]
pub bodies: Vec<ReflectionBody>,
pub max_bounces: u8,
pub samples: u8,
}
impl Default for ReflectionOptions {
fn default() -> Self {
Self { bodies: Vec::new(), max_bounces: 2, samples: 4 }
}
}
fn bounded_reflection_bodies<'de, D: serde::Deserializer<'de>>(d: D) -> std::result::Result<Vec<ReflectionBody>, D::Error> {
struct Bodies;
impl<'de> serde::de::Visitor<'de> for Bodies {
type Value = Vec<ReflectionBody>;
fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("at most64 reflection body overrides")
}
fn visit_seq<A: serde::de::SeqAccess<'de>>(self, mut seq: A) -> std::result::Result<Self::Value, A::Error> {
let mut values = Vec::new();
while let Some(value) = seq.next_element()? {
if values.len() == 64 {
return Err(serde::de::Error::custom("at most64 reflection bodies"));
}
values.push(value);
}
Ok(values)
}
}
d.deserialize_seq(Bodies)
}
impl ReflectionOptions {
pub fn validate(&self) -> Result<()> {
if !(1..=8).contains(&self.max_bounces) || !(1..=64).contains(&self.samples) || self.bodies.len() > 64 || self.bodies.capacity() > 64 {
return Err(JobError::new(ErrorCode::InvalidRequest, "reflection bounds: 1..8 bounces, 1..64 samples, at most64 body slots"));
}
for (index, body) in self.bodies.iter().enumerate() {
if body.body.is_empty()
|| body.body.len() > 128
|| body.body.capacity() > 128
|| self.bodies.iter().take(index).any(|other| other.body == body.body)
{
return Err(JobError::new(ErrorCode::InvalidRequest, "reflection body names must be unique, nonempty and bounded to128 bytes"));
}
}
Ok(())
}
}
/// Linear-light runtime inputs. These are never design settings or GPU presets.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct DirectionalLightOptions {
pub direction: [f64; 3],
pub color: [f64; 3],
pub intensity: f64,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum LightingPreset {
Neutral,
WarmCool,
KeyRim,
}
/// Explicit visual rotation about a certified planar face's outward normal.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum AnisotropicOrientation {
#[default]
Zero,
QuarterTurn,
}
/// Runtime-only captured planar face selector; no persistent naming is invented.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct AnisotropicFaceOptions {
pub body_index: usize,
#[serde(deserialize_with = "bounded_anisotropic_body_name")]
pub body_name: String,
pub face: u32,
pub tangent: [f64; 3],
pub orientation: AnisotropicOrientation,
pub roughness_x: f64,
pub roughness_y: f64,
}
fn bounded_anisotropic_body_name<'de, D: serde::Deserializer<'de>>(d: D) -> std::result::Result<String, D::Error> {
struct Name;
impl serde::de::Visitor<'_> for Name {
type Value = String;
fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("captured body name of 1..1024 bytes")
}
fn visit_str<E: serde::de::Error>(self, value: &str) -> std::result::Result<String, E> {
if value.is_empty() || value.len() > 1024 {
return Err(E::custom("captured body name of 1..1024 bytes required"));
}
let mut name = String::new();
name.try_reserve_exact(value.len()).map_err(E::custom)?;
name.push_str(value);
Ok(name)
}
}
d.deserialize_str(Name)
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(default, deny_unknown_fields)]
pub struct RaytraceOptions {
pub reflections: Option<ReflectionOptions>,
pub anisotropic_faces: [Option<AnisotropicFaceOptions>; 2],
pub preset: Option<LightingPreset>,
#[serde(deserialize_with = "bounded_lights", skip_serializing_if = "Option::is_none")]
pub lights: Option<Vec<DirectionalLightOptions>>,
pub exposure_ev: f64,
pub shadows: bool,
}
impl Default for RaytraceOptions {
fn default() -> Self {
Self { anisotropic_faces: [None, None], reflections: None, preset: None, lights: None, exposure_ev: 0.0, shadows: true }
}
}
fn bounded_lights<'de, D: serde::Deserializer<'de>>(deserializer: D) -> std::result::Result<Option<Vec<DirectionalLightOptions>>, D::Error> {
struct Lights;
impl<'de> serde::de::Visitor<'de> for Lights {
type Value = Vec<DirectionalLightOptions>;
fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter.write_str("at most eight directional lights")
}
fn visit_seq<A: serde::de::SeqAccess<'de>>(self, mut sequence: A) -> std::result::Result<Self::Value, A::Error> {
let mut lights = Vec::new();
while let Some(light) = sequence.next_element()? {
if lights.len() == 8 {
return Err(serde::de::Error::custom("at most eight directional lights"));
}
lights.push(light);
}
Ok(lights)
}
}
deserializer.deserialize_seq(Lights).map(Some)
}
impl RaytraceOptions {
/// One capacity calculation shared by host and engine preflight.
pub fn retained_bytes(&self) -> Result<u64> {
self.validate()?;
let limit = || JobError::new(ErrorCode::LimitExceeded, "raytrace request capacity overflow");
let mut bytes = self
.lights
.as_ref()
.map_or(Some(0), |l| (l.capacity() as u64).checked_mul(std::mem::size_of::<DirectionalLightOptions>() as u64))
.ok_or_else(limit)?;
if let Some(reflections) = &self.reflections {
let slots = (reflections.bodies.capacity() as u64).checked_mul(std::mem::size_of::<ReflectionBody>() as u64).ok_or_else(limit)?;
bytes = bytes.checked_add(slots).ok_or_else(limit)?;
for body in &reflections.bodies {
bytes = bytes.checked_add(body.body.capacity() as u64).ok_or_else(limit)?;
}
}
for target in self.anisotropic_faces.iter().flatten() {
bytes = bytes.checked_add(target.body_name.capacity() as u64).ok_or_else(limit)?;
}
Ok(bytes)
}
/// No environment NEE on selected reflectors; rough transport must be purely metallic.
/// Rejecting every nonmetallic effective face prevents silently dropping its diffuse HDR.
pub fn validate_environment_reflections(&self, scene: &crate::ProductScene) -> Result<()> {
self.validate()?;
if let Some(reflections) = &self.reflections {
for selector in &reflections.bodies {
let mut bodies = scene.meshes.iter().filter(|b| b.name == selector.body);
let body = bodies.next().ok_or_else(|| JobError::new(ErrorCode::InvalidRequest, "environment reflection body missing"))?;
if bodies.next().is_some() {
return Err(JobError::new(ErrorCode::InvalidRequest, "ambiguous environment reflection body"));
}
if selector.mode == ReflectionMode::RoughSpecular
&& (body.surface.is_none_or(|s| s.metallic() != 1.0) || body.faces.iter().any(|f| f.surface.is_none_or(|s| s.metallic() != 1.0)))
{
return Err(JobError::new(
ErrorCode::InvalidRequest,
"HDR rough reflection requires fully metallic body and face surfaces; diffuse/specular partition is not supported",
));
}
}
}
for target in self.anisotropic_faces.iter().flatten() {
let mode = self.reflections.as_ref().and_then(|r| r.bodies.iter().find(|b| b.body == target.body_name).map(|b| b.mode));
if mode != Some(ReflectionMode::RoughSpecular) {
return Err(JobError::new(
ErrorCode::InvalidRequest,
"HDR anisotropy requires a selected fully metallic rough reflector; anisotropic HDR direct lighting is not supported",
));
}
}
Ok(())
}
pub fn validate(&self) -> Result<()> {
if let Some(reflections) = &self.reflections {
reflections.validate()?;
}
for (i, target) in self.anisotropic_faces.iter().enumerate().filter_map(|(i, target)| target.as_ref().map(|target| (i, target))) {
if target.body_name.is_empty()
|| target.body_name.len() > 1024
|| target.body_name.capacity() > 1024
|| !target.tangent.iter().all(|v| v.is_finite())
|| !target.tangent.iter().any(|v| *v != 0.0)
|| ![target.roughness_x, target.roughness_y].into_iter().all(|v| v.is_finite() && (crate::surface::MIN_ROUGHNESS..=1.0).contains(&v))
{
return Err(JobError::new(ErrorCode::InvalidRequest, "invalid bounded anisotropic planar face options"));
}
if self.anisotropic_faces.iter().skip(i + 1).flatten().any(|other| target.body_index == other.body_index && target.face == other.face) {
return Err(JobError::new(ErrorCode::InvalidRequest, "duplicate anisotropic captured face"));
}
}
if self.reflections.as_ref().is_some_and(|r| {
r.bodies.iter().any(|b| b.mode == ReflectionMode::Mirror && self.anisotropic_faces.iter().flatten().any(|t| t.body_name == b.body))
}) {
return Err(JobError::new(ErrorCode::InvalidRequest, "delta mirror cannot have anisotropic rough axes"));
}
if self.preset.is_some() && self.lights.is_some() {
return Err(JobError::new(ErrorCode::InvalidRequest, "choose either a lighting preset or custom lights"));
}
if !self.exposure_ev.is_finite() || !(-16.0..=16.0).contains(&self.exposure_ev) {
return Err(JobError::new(ErrorCode::InvalidRequest, "raytrace exposure_ev must be finite and within -16..16"));
}
if let Some(lights) = &self.lights {
if lights.len() > 8 || lights.capacity() > 8 {
return Err(JobError::new(ErrorCode::InvalidRequest, "at most eight directional lights"));
}
for light in lights {
let direction_valid = light.direction.iter().all(|n| n.is_finite()) && light.direction.iter().any(|n| *n != 0.0);
if !direction_valid
|| !light.color.iter().all(|n| n.is_finite() && (0.0..=1.0).contains(n))
|| !light.intensity.is_finite()
|| !(0.0..=64.0).contains(&light.intensity)
{
return Err(JobError::new(ErrorCode::InvalidRequest, "invalid bounded directional light"));
}
}
}
Ok(())
}
}
/// Fully resolved input; no mutable session, topology graph or GPU resources.
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct ImageRequest {
#[serde(default)]
pub integrator: Integrator,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub raytrace: Option<RaytraceOptions>,
pub camera: Camera,
pub width: u32,
pub height: u32,
@@ -138,3 +421,26 @@ pub struct FrameInfo {
pub encoding: ColourEncoding,
pub alpha: AlphaConvention,
}
#[cfg(test)]
mod runtime_request_roundtrip_tests {
use super::*;
#[test]
fn default_preset_and_empty_lights_requests_roundtrip_without_invalid_null_sequence() {
for options in [
RaytraceOptions::default(),
RaytraceOptions { preset: Some(LightingPreset::Neutral), ..Default::default() },
RaytraceOptions { lights: Some(Vec::new()), ..Default::default() },
] {
let value = serde_json::to_value(&options).unwrap();
if options.lights.is_none() {
assert!(value.get("lights").is_none());
} else {
assert_eq!(value.get("lights").unwrap(), &serde_json::json!([]));
}
let decoded: RaytraceOptions = serde_json::from_value(value).unwrap();
assert_eq!(decoded, options);
assert!(decoded.validate().is_ok());
}
assert_eq!(serde_json::from_value::<RaytraceOptions>(serde_json::json!({})).unwrap(), RaytraceOptions::default());
}
}
+137
View File
@@ -0,0 +1,137 @@
//! Runtime-option and admission regressions; no render timing assumptions.
use super::*;
use crate::ProductScene;
use solidcraft_geom::Aabb3;
fn request(integrator: Integrator) -> ImageRequest {
ImageRequest { integrator, raytrace: None, camera: Default::default(), width: 16, height: 16, background: [0; 3], transparent_background: false }
}
#[test]
fn options_reject_retained_capacity_even_when_no_lights_are_active() {
let options = RaytraceOptions { lights: Some(Vec::with_capacity(64)), ..Default::default() };
assert_eq!(options.validate().unwrap_err().code, ErrorCode::InvalidRequest);
let serialized = serde_json::to_value(&options).unwrap();
let decoded: RaytraceOptions = serde_json::from_value(serialized).unwrap();
assert!(decoded.validate().is_ok(), "wire input retains no oversized source allocation");
}
#[cfg(feature = "raytrace-cpu")]
#[test]
fn raytrace_admission_validates_retained_options_before_cloning() {
let scene = ProductScene { meshes: Vec::new(), bounds: Aabb3::EMPTY };
let mut request = request(Integrator::Raytrace);
request.raytrace = Some(RaytraceOptions { lights: Some(Vec::with_capacity(64)), ..Default::default() });
let original = request.raytrace.as_ref().unwrap();
assert_eq!(original.validate().unwrap_err().code, ErrorCode::InvalidRequest);
assert!(original.clone().validate().is_ok(), "cloning an empty Vec discards its retained capacity");
let error = admit(&scene, &request).err().unwrap();
assert_eq!(error.code, ErrorCode::InvalidRequest);
assert_eq!(request.raytrace.as_ref().unwrap().lights.as_ref().unwrap().capacity(), 64);
}
#[test]
fn options_preserve_the_eight_light_boundary_and_refuse_the_ninth() {
let light = serde_json::json!({"direction": [0.0, 0.0, -1.0], "color": [1.0, 1.0, 1.0], "intensity": 1.0});
let accepted: RaytraceOptions = serde_json::from_value(serde_json::json!({"lights": vec![light.clone(); 8]})).unwrap();
assert!(accepted.validate().is_ok());
assert!(serde_json::from_value::<RaytraceOptions>(serde_json::json!({"lights": vec![light; 9]})).is_err());
}
#[test]
fn exposure_refuses_nonfinite_and_out_of_range_values() {
for exposure_ev in [f64::NAN, f64::INFINITY, f64::NEG_INFINITY, -16.01, 16.01] {
let options = RaytraceOptions { exposure_ev, ..Default::default() };
assert_eq!(options.validate().unwrap_err().code, ErrorCode::InvalidRequest);
}
for exposure_ev in [-16.0, 16.0] {
assert!(RaytraceOptions { exposure_ev, ..Default::default() }.validate().is_ok());
}
}
#[test]
fn rejected_raytrace_submission_leaves_existing_raster_reservation_intact() {
let host = CpuHost::cooperative();
let scene = || ProductScene { meshes: Vec::new(), bounds: Aabb3::EMPTY };
let raster = host.submit(JobId { session: 1, serial: 1, generation: 1 }, 1, scene(), request(Integrator::Raster)).unwrap();
let before = host.admitted_bytes();
assert!(before > 0);
let error = host.submit(JobId { session: 1, serial: 2, generation: 2 }, 1, scene(), request(Integrator::Raytrace)).err().unwrap();
assert_eq!(error.code, ErrorCode::HostUnavailable);
assert_eq!(host.admitted_bytes(), before);
assert_eq!(raster.status().unwrap().progress.phase, Phase::Queued);
assert!(raster.frame().unwrap().is_none());
assert_eq!(raster.cancel().unwrap().progress.phase, Phase::Cancelled);
// Pump only to discard cancelled queued input; it must not produce a frame.
assert!(!host.pump(1).unwrap());
assert_eq!(host.admitted_bytes(), 0);
assert!(raster.frame().unwrap().is_none());
}
#[cfg(all(feature = "raytrace-cpu", not(target_arch = "wasm32")))]
#[test]
fn native_integrators_share_one_host_and_retained_frame_budget() {
let host = CpuHost::for_platform().unwrap();
let scene = || ProductScene { meshes: Vec::new(), bounds: Aabb3::EMPTY };
let raster_id = JobId { session: 10, serial: 1, generation: 1 };
let raytrace_id = JobId { session: 20, serial: 1, generation: 1 };
let raster = host.submit(raster_id, 100, scene(), request(Integrator::Raster)).unwrap();
let raytrace = host.submit(raytrace_id, 200, scene(), request(Integrator::Raytrace)).unwrap();
// Deadlock watchdog only; there is no rendering-speed assertion.
for job in [&raster, &raytrace] {
assert_eq!(job.wait_timeout(std::time::Duration::from_secs(60)).unwrap().progress.phase, Phase::Completed);
}
let raster_frame = raster.frame().unwrap().unwrap();
let raytrace_frame = raytrace.frame().unwrap().unwrap();
assert_eq!(raster_frame.info.job, raster_id);
assert_eq!(raytrace_frame.info.job, raytrace_id);
assert_eq!(raster_frame.info.scene_generation, 100);
assert_eq!(raytrace_frame.info.scene_generation, 200);
assert_eq!(raster_frame.info.executor.as_str(), "cpu-product");
assert_eq!(raytrace_frame.info.executor.as_str(), "cpu-raytrace");
let both = host.admitted_bytes();
assert!(both > 0);
drop(raster);
drop(raytrace);
assert_eq!(host.admitted_bytes(), both, "external frames retain both leases");
drop(raster_frame);
assert!(host.admitted_bytes() > 0 && host.admitted_bytes() < both);
drop(raytrace_frame);
assert_eq!(host.admitted_bytes(), 0);
}
#[cfg(feature = "raytrace-cpu")]
#[test]
fn cancelled_raytrace_task_never_returns_a_frame() {
let cancel = CancelToken::default();
let scene = ProductScene { meshes: Vec::new(), bounds: Aabb3::EMPTY };
let mut task = crate::raytrace::image::ImageTask::new(scene, request(Integrator::Raytrace), cancel.clone(), RaytraceOptions::default()).unwrap();
cancel.cancel();
assert_eq!(task.step(4).err().unwrap().code, ErrorCode::Cancelled);
}
#[cfg(feature = "raytrace-cpu")]
#[test]
fn completed_raytrace_task_releases_captured_mesh_before_returning_png() {
let mesh = Arc::new(solidcraft_geom::Mesh::default());
let captured = Arc::downgrade(&mesh);
let scene = ProductScene {
meshes: vec![crate::ProductMesh { name: "Lease probe".into(), mesh, color: [0; 3], opacity: 1.0, surface: None, faces: Vec::new() }],
bounds: Aabb3::EMPTY,
};
let mut task =
crate::raytrace::image::ImageTask::new(scene, request(Integrator::Raytrace), CancelToken::default(), RaytraceOptions::default()).unwrap();
assert!(captured.upgrade().is_some());
let mut completed = false;
for _ in 0..10_000 {
if let TaskPoll::Complete(png) = task.step(4).unwrap() {
assert!(png.starts_with(b"\x89PNG\r\n\x1a\n"));
completed = true;
break;
}
}
assert!(completed, "bounded empty-scene fixture must complete");
assert!(captured.upgrade().is_none(), "the host may shrink the lease as soon as Complete is returned, even while the task remains alive");
assert_eq!(task.progress().phase, Phase::Completed);
}
+5
View File
@@ -5,13 +5,17 @@
#![forbid(unsafe_code)]
mod analysis;
pub mod anisotropic_surface;
mod backend;
mod camera;
mod curve_display;
mod gif;
pub mod job;
pub mod lighting;
mod product;
mod raster;
#[cfg(feature = "raytrace-cpu")]
pub mod raytrace;
mod scene;
pub mod studio;
pub mod surface;
@@ -28,6 +32,7 @@ pub use backend::{
};
pub use camera::{Camera, CameraAnim, Mat4, Quat, StandardView, UpAxis, ease_in_out};
pub use curve_display::{PixelCurveView, SampledPath, SamplingBudget, SamplingQuality, sample_segment, sample_segment_unclipped};
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};
@@ -0,0 +1,115 @@
//! Captured existing HDR source, moved through a job under its ONE work lease.
#[cfg(feature = "raytrace-cpu")]
use super::environment_sampling::Environment;
use serde::Serialize;
use sha2::{Digest, Sha256};
#[derive(Clone, Debug, Serialize)]
pub struct EnvironmentInfo {
pub source_sha256: [u8; 32],
pub header: super::HdrInfo,
pub rotation_radians: f64,
pub intensity: f64,
pub samples: u32,
pub color_policy: EnvironmentColorPolicy,
}
#[derive(Clone, Copy, Debug, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum EnvironmentColorPolicy {
ExplicitLinearSrgbD65,
}
#[cfg(feature = "raytrace-cpu")]
use super::{DecodedHdr, HdrDecodeTask, HdrTaskPoll};
use super::{HdrError, HdrErrorCode, HdrSource, Result};
/// Transient captured input, never serialized into status or saved design data.
pub struct EnvironmentInput {
source: HdrSource,
info: EnvironmentInfo,
}
impl EnvironmentInput {
pub fn new(source: HdrSource, rotation: f64, intensity: f64, samples: u32) -> Result<Self> {
if !rotation.is_finite() || !intensity.is_finite() || !(0.0..=64.0).contains(&intensity) || !matches!(samples, 1 | 4 | 16 | 64) {
return Err(HdrError::new(HdrErrorCode::InvalidInput, "invalid environment controls"));
}
if source.info().primaries != Some([0.64, 0.33, 0.30, 0.60, 0.15, 0.06, 0.3127, 0.3290]) {
return Err(HdrError::new(HdrErrorCode::InvalidInput, "environment requires explicit sRGB/D65 primaries"));
}
let info = EnvironmentInfo {
source_sha256: Sha256::digest(source.encoded_bytes()).into(),
header: source.info().clone(),
rotation_radians: rotation,
intensity,
samples,
color_policy: EnvironmentColorPolicy::ExplicitLinearSrgbD65,
};
Ok(Self { source, info })
}
pub fn metadata(&self) -> EnvironmentInfo {
self.info.clone()
}
/// Source capacity + exact decoded allocation + scanline + conservative task state.
/// The host adds this BEFORE reserving; this is no separate memory pool.
pub fn required_bytes(&self) -> Result<u64> {
self.source
.retained_encoded_bytes()
.checked_add(self.source.info().decoded_rgb_bytes)
.and_then(|v| v.checked_add(u64::from(self.source.info().width) * 4))
.and_then(|v| v.checked_add(8192))
.ok_or_else(|| HdrError::new(HdrErrorCode::LimitExceeded, "environment admission overflow"))
}
#[cfg(feature = "raytrace-cpu")]
pub(crate) fn begin(self) -> Result<EnvironmentState> {
if std::mem::size_of::<HdrDecodeTask>() > 4096 {
return Err(HdrError::new(HdrErrorCode::LimitExceeded, "HDR decoder state exceeds admission"));
}
let mut decoder = Vec::new();
decoder.try_reserve_exact(1).map_err(|_| HdrError::new(HdrErrorCode::AllocationFailed, "HDR decoder state allocation failed"))?;
if decoder.capacity() != 1 {
return Err(HdrError::new(HdrErrorCode::LimitExceeded, "HDR decoder state capacity exceeds admission"));
}
decoder.push(HdrDecodeTask::new(self.source)?);
Ok(EnvironmentState {
decoder,
decoded: None,
rotation: self.info.rotation_radians,
intensity: self.info.intensity,
samples: self.info.samples,
})
}
}
#[cfg(feature = "raytrace-cpu")]
pub(crate) struct EnvironmentState {
decoder: Vec<HdrDecodeTask>,
decoded: Option<DecodedHdr>,
rotation: f64,
intensity: f64,
pub samples: u32,
}
#[cfg(feature = "raytrace-cpu")]
impl EnvironmentState {
pub fn ready(&self) -> bool {
self.decoded.is_some()
}
/// Caller debits one shared unit before each invocation; decoder also observes cancellation.
pub fn prepare_one(&mut self, cancelled: impl Fn() -> bool) -> Result<()> {
let decoder = self.decoder.first_mut().ok_or_else(|| HdrError::new(HdrErrorCode::Consumed, "environment decoder consumed"))?;
if let HdrTaskPoll::Complete(decoded) = decoder.step(1, cancelled)? {
let expected = decoded.info().decoded_rgb_bytes;
if decoded.retained_pixel_bytes()? != expected {
return Err(HdrError::new(HdrErrorCode::LimitExceeded, "environment decoded capacity exceeds admission"));
}
Environment::from_decoder_output(&decoded, self.rotation, self.intensity)?.require_linear_srgb()?;
self.decoded = Some(decoded);
self.decoder = Vec::new();
}
Ok(())
}
pub fn view(&self) -> Result<Environment<'_>> {
let decoded = self.decoded.as_ref().ok_or_else(|| HdrError::new(HdrErrorCode::Consumed, "environment not ready"))?;
Environment::from_decoder_output(decoded, self.rotation, self.intensity)
}
}
@@ -0,0 +1,39 @@
//! White-box hostile decoded input tests; production has no unchecked constructor.
use super::*;
use crate::lighting::environment_sampling::EnvironmentPreparation;
fn info() -> HdrInfo {
let mut bytes = b"#?RADIANCE\nFORMAT=32-bit_rle_rgbe\n\n-Y 2 +X 4\n".to_vec();
bytes.extend_from_slice(&[128, 64, 32, 129]);
HdrSource::new(bytes).unwrap().info().clone()
}
#[test]
fn malformed_decoded_dimensions_lengths_and_original_capacity_refuse() {
for dimensions in [(0, 2), (4, 0), (3, 2), (4096, 2048)] {
let mut metadata = info();
metadata.width = dimensions.0;
metadata.height = dimensions.1;
let decoded = DecodedHdr { info: metadata, pixels: vec![[1.0; 3]; 8] };
assert!(EnvironmentPreparation::new(&decoded, 0.0, 1.0).is_err());
}
let decoded = DecodedHdr { info: info(), pixels: vec![[1.0; 3]; 7] };
assert!(EnvironmentPreparation::new(&decoded, 0.0, 1.0).is_err());
let mut pixels = Vec::with_capacity(MAX_HDR_PIXELS as usize + 1);
pixels.resize(8, [1.0; 3]);
let decoded = DecodedHdr { info: info(), pixels };
assert!(decoded.retained_pixel_bytes().unwrap() > MAX_HDR_PIXELS * 12);
assert!(EnvironmentPreparation::new(&decoded, 0.0, 1.0).is_err());
}
#[test]
fn invalid_source_radiance_consumes_preparation_before_exposing_lookup() {
for channel in [f32::NAN, f32::INFINITY, -1.0, 1e9] {
let mut pixels = vec![[1.0; 3]; 8];
pixels[3][1] = channel;
let decoded = DecodedHdr { info: info(), pixels };
let mut preparation = EnvironmentPreparation::new(&decoded, 0.0, 1.0).unwrap();
assert_eq!(preparation.step(8, || Ok(())).unwrap_err().code, HdrErrorCode::InvalidInput);
assert!(preparation.finish().is_err());
}
}
@@ -0,0 +1,205 @@
//! Original Z-up equirectangular sampling; RGB remains in the decoded SOURCE space.
//! Uniform solid-angle sampling deliberately has no luminance CDF or extra pixel copy.
use super::{DecodedHdr, HdrError, HdrErrorCode, MAX_HDR_HEIGHT, MAX_HDR_PIXELS, MAX_HDR_WIDTH, Result};
use solidcraft_geom::Vec3;
use std::f64::consts::{PI, TAU};
fn invalid(message: &str) -> HdrError {
HdrError::new(HdrErrorCode::InvalidInput, message)
}
/// Borrowed decoded storage. Its owner and existing admission lease must outlive this view.
/// This is not a declaration that source RGB is linear sRGB.
pub struct Environment<'a> {
decoded: &'a DecodedHdr,
rotation: f64,
intensity: f64,
}
/// Incident SOURCE-space linear RGB and a density with respect to steradians.
#[derive(Clone, Copy, Debug)]
pub struct EnvironmentSample {
pub direction: Vec3,
pub radiance_source_rgb: Vec3,
pub pdf_solid_angle: f64,
}
/// One unoccluded linear-sRGB direct-light estimate. The consumer owns visibility
/// and averages these estimates once; no display transfer or sample-count division.
pub struct EnvironmentDirectSample {
pub direction: Vec3,
pub contribution_linear_srgb: Vec3,
pub pdf_solid_angle: f64,
}
/// Cooperative validation with no allocations. The caller charges each inspected texel
/// to its existing cumulative budget, and can return a typed cancellation/limit error.
pub struct EnvironmentPreparation<'a> {
environment: Option<Environment<'a>>,
inspected: usize,
}
impl<'a> EnvironmentPreparation<'a> {
pub fn new(decoded: &'a DecodedHdr, rotation_radians: f64, intensity: f64) -> Result<Self> {
let info = decoded.info();
let count = u64::from(info.width).checked_mul(u64::from(info.height));
if info.width == 0
|| info.height == 0
|| info.width > MAX_HDR_WIDTH
|| info.height > MAX_HDR_HEIGHT
|| info.width != info.height.saturating_mul(2)
|| count.is_none_or(|n| n > MAX_HDR_PIXELS || n != decoded.pixels().len() as u64)
|| decoded.retained_pixel_bytes()? > MAX_HDR_PIXELS * 12
{
return Err(invalid("invalid bounded decoded environment dimensions or retained capacity"));
}
if !rotation_radians.is_finite() || !intensity.is_finite() || !(0.0..=64.0).contains(&intensity) {
return Err(invalid("environment rotation must be finite and intensity within 0..64"));
}
Ok(Self { environment: Some(Environment { decoded, rotation: rotation_radians.rem_euclid(TAU), intensity }), inspected: 0 })
}
/// Returns true when validated. Any error consumes preparation; no partial view escapes.
pub fn step(&mut self, units: usize, mut charge_and_check_cancel: impl FnMut() -> Result<()>) -> Result<bool> {
let result = self.advance(units, &mut charge_and_check_cancel);
if result.is_err() {
self.environment = None;
}
result
}
fn advance(&mut self, units: usize, charge: &mut impl FnMut() -> Result<()>) -> Result<bool> {
let environment = self.environment.as_ref().ok_or_else(|| HdrError::new(HdrErrorCode::Consumed, "environment preparation consumed"))?;
// Even an already-complete poll observes cancellation without inspecting more texels.
for _ in 0..units.clamp(1, 16384) {
charge()?;
let Some(pixel) = environment.decoded.pixels().get(self.inspected) else {
return Ok(true);
};
if pixel.iter().any(|c| !c.is_finite() || !(0.0..=1e8).contains(c)) {
return Err(invalid("environment source radiance must be finite and within 0..1e8"));
}
self.inspected += 1;
if self.inspected == environment.decoded.pixels().len() {
return Ok(true);
}
}
Ok(false)
}
pub fn finish(mut self) -> Result<Environment<'a>> {
let environment = self.environment.take().ok_or_else(|| HdrError::new(HdrErrorCode::Consumed, "environment preparation consumed"))?;
if self.inspected != environment.decoded.pixels().len() {
return Err(invalid("environment preparation is incomplete"));
}
Ok(environment)
}
}
impl Environment<'_> {
/// Only decoder-owned output can reach this internal consumer fast path.
/// HdrDecodeTask already validates every corrected texel incrementally.
#[cfg(feature = "raytrace-cpu")]
pub(crate) fn from_decoder_output(decoded: &DecodedHdr, rotation: f64, intensity: f64) -> Result<Environment<'_>> {
let mut preparation = EnvironmentPreparation::new(decoded, rotation, intensity)?;
preparation.inspected = decoded.pixels().len();
preparation.finish()
}
/// First lighting adapter policy: only explicitly declared sRGB/D65 primaries.
/// Missing Radiance primaries are NOT assumed to be sRGB; other gamuts need
/// an independently validated conversion before this adapter can admit them.
pub fn require_linear_srgb(&self) -> Result<()> {
if self.decoded.info().primaries != Some([0.64, 0.33, 0.30, 0.60, 0.15, 0.06, 0.3127, 0.3290]) {
return Err(invalid("environment lighting requires explicit sRGB/D65 primaries; source gamut conversion is not supported yet"));
}
Ok(())
}
pub fn radiance_linear_srgb(&self, direction: Vec3) -> Result<Vec3> {
self.require_linear_srgb()?;
self.radiance_source_rgb(direction)
}
pub fn direct_sample_linear_srgb(
&self,
u: [f64; 2],
surface: crate::surface::OpaqueSurface,
shading_normal: Vec3,
geometric_normal: Vec3,
view: Vec3,
) -> Result<EnvironmentDirectSample> {
self.require_linear_srgb()?;
let sample = self.sample(u)?;
let normal = normalized(shading_normal)?;
let geometric = normalized(geometric_normal)?;
let view = normalized(view)?;
let brdf = surface.brdf(normal, view, sample.direction).map_err(|_| invalid("invalid environment BRDF directions"))?;
let cosine = if geometric.dot(sample.direction) > 0.0 && geometric.dot(view) > 0.0 { normal.dot(sample.direction).max(0.0) } else { 0.0 };
let li = sample.radiance_source_rgb;
let contribution = Vec3::new(brdf.x * li.x, brdf.y * li.y, brdf.z * li.z) * (cosine / sample.pdf_solid_angle);
if !contribution.is_finite() || [contribution.x, contribution.y, contribution.z].iter().any(|c| !(0.0..=1e12).contains(c)) {
return Err(invalid("environment direct contribution exceeds finite radiance bounds"));
}
Ok(EnvironmentDirectSample { direction: sample.direction, contribution_linear_srgb: contribution, pdf_solid_angle: sample.pdf_solid_angle })
}
/// Original allocation capacity, not logical slice length; charge the owner only once.
pub fn retained_pixel_bytes(&self) -> Result<u64> {
self.decoded.retained_pixel_bytes()
}
/// +Z north; phi=atan2(y,x), u=phi/2pi wrapped; v=acos(z)/pi.
/// Positive rotation turns the environment about +Z toward +Y (inverse for lookup).
/// Nearest texel uses half-open angular cells, centres ((x+.5)/W,(y+.5)/H).
/// The seam wraps, south clamps to the last row; exact poles choose longitude zero.
pub fn uv(&self, direction: Vec3) -> Result<[f64; 2]> {
let d = normalized(direction)?;
let phi = if d.x == 0.0 && d.y == 0.0 { 0.0 } else { d.y.atan2(d.x) };
Ok([((phi - self.rotation) / TAU).rem_euclid(1.0), d.z.clamp(-1.0, 1.0).acos() / PI])
}
/// Exposure/color-correction were applied by the decoder; do not repeat them.
/// No gamut conversion, tone mapping or background interpretation takes place here.
pub fn radiance_source_rgb(&self, direction: Vec3) -> Result<Vec3> {
let [u, v] = self.uv(direction)?;
let info = self.decoded.info();
let x = ((u * f64::from(info.width)) as usize).min(info.width as usize - 1);
let y = ((v * f64::from(info.height)) as usize).min(info.height as usize - 1);
let index = y.checked_mul(info.width as usize).and_then(|n| n.checked_add(x)).ok_or_else(|| invalid("environment index overflow"))?;
let [r, g, b] = *self.decoded.pixels().get(index).ok_or_else(|| invalid("missing environment texel"))?;
Ok(Vec3::new(f64::from(r), f64::from(g), f64::from(b)) * self.intensity)
}
pub fn pdf_solid_angle(&self, direction: Vec3) -> Result<f64> {
normalized(direction)?;
Ok(1.0 / (4.0 * PI))
}
/// Open variates avoid mathematical boundary samples (f64 may still round to a pole).
/// z is uniform on (-1,1), phi on (0,2pi): dOmega=dphi dz, PDF=1/(4pi).
/// Black and constant maps have the same normalized PDF; there is no zero-total CDF.
pub fn sample(&self, u: [f64; 2]) -> Result<EnvironmentSample> {
if u.iter().any(|v| !v.is_finite() || *v <= 0.0 || *v >= 1.0) {
return Err(invalid("environment variates must be finite and strictly between zero and one"));
}
let z = 1.0 - 2.0 * u[0];
let radius = ((1.0 - z) * (1.0 + z)).max(0.0).sqrt();
let phi = TAU * u[1];
let direction = Vec3::new(radius * phi.cos(), radius * phi.sin(), z);
Ok(EnvironmentSample { direction, radiance_source_rgb: self.radiance_source_rgb(direction)?, pdf_solid_angle: 1.0 / (4.0 * PI) })
}
}
fn normalized(direction: Vec3) -> Result<Vec3> {
let scale = direction.x.abs().max(direction.y.abs()).max(direction.z.abs());
if !direction.is_finite() || scale <= 0.0 {
return Err(invalid("environment direction must be finite and nonzero"));
}
let scaled = direction / scale;
Ok(scaled / scaled.len())
}
#[cfg(test)]
#[path = "environment_sampling_tests.rs"]
mod tests;
@@ -0,0 +1,157 @@
use super::*;
use crate::lighting::{HdrDecodeTask, HdrSource, HdrTaskPoll};
fn decoded(pixels: [[u8; 4]; 8], header: &str) -> DecodedHdr {
let mut bytes = format!("#?RADIANCE\nFORMAT=32-bit_rle_rgbe\n{header}\n-Y 2 +X 4\n").into_bytes();
for pixel in pixels {
bytes.extend_from_slice(&pixel);
}
let mut task = HdrDecodeTask::new(HdrSource::new(bytes).unwrap()).unwrap();
for _ in 0..100 {
if let HdrTaskPoll::Complete(decoded) = task.step(100, || false).unwrap() {
return decoded;
}
}
panic!("bounded fixture failed to decode");
}
fn prepared(decoded: &DecodedHdr, rotation: f64, intensity: f64) -> Environment<'_> {
let mut task = EnvironmentPreparation::new(decoded, rotation, intensity).unwrap();
while !task.step(1, || Ok(())).unwrap() {}
task.finish().unwrap()
}
#[test]
fn constant_source_has_uniform_solid_angle_pdf_and_exact_radiance_integral() {
let data = decoded([[128, 64, 32, 129]; 8], "");
let env = prepared(&data, 0.0, 2.0);
let expected = Vec3::new(2.0, 1.0, 0.5);
let mut integral = Vec3::ZERO;
for i in 0..64 {
let sample = env.sample([(f64::from(i) + 0.5) / 64.0, 0.37]).unwrap();
assert!((sample.direction.len() - 1.0).abs() < 1e-14);
assert_eq!(sample.radiance_source_rgb, expected);
assert_eq!(env.pdf_solid_angle(sample.direction).unwrap(), sample.pdf_solid_angle);
integral += sample.radiance_source_rgb / sample.pdf_solid_angle / 64.0;
}
assert!((integral - expected * (4.0 * PI)).len() < 1e-12);
assert!((env.pdf_solid_angle(Vec3::Z).unwrap() * 4.0 * PI - 1.0).abs() < 1e-15);
}
#[test]
fn z_up_uv_centres_seam_poles_and_positive_rotation_are_explicit() {
let data = decoded([[128, 0, 0, 129]; 8], "");
let env = prepared(&data, 0.0, 1.0);
assert_eq!(env.uv(Vec3::X).unwrap(), [0.0, 0.5]);
assert_eq!(env.uv(Vec3::Y).unwrap(), [0.25, 0.5]);
assert_eq!(env.uv(Vec3::Z).unwrap(), [0.0, 0.0]);
assert_eq!(env.uv(-Vec3::Z).unwrap(), [0.0, 1.0]);
let rotated = prepared(&data, PI / 2.0, 1.0);
assert_eq!(rotated.uv(Vec3::Y).unwrap(), [0.0, 0.5]);
assert!(env.uv(Vec3::new(1.0, -1e-8, 0.0)).unwrap()[0] > 0.99);
let theta = PI / 4.0;
let phi = PI / 4.0;
let centre = Vec3::new(theta.sin() * phi.cos(), theta.sin() * phi.sin(), theta.cos());
let uv = env.uv(centre).unwrap();
assert!((uv[0] - 0.125).abs() < 1e-14 && (uv[1] - 0.25).abs() < 1e-14);
}
#[test]
fn bright_texel_integral_matches_its_independent_spherical_cell_area() {
let mut pixels = [[0; 4]; 8];
pixels[0] = [128, 0, 0, 129];
let data = decoded(pixels, "");
let env = prepared(&data, 0.0, 1.0);
let mut integral = 0.0;
// 4x2: first cell has phi width pi/2 and z width 1, solid angle pi/2.
for y in 0..8 {
for x in 0..8 {
let sample = env.sample([(f64::from(y) + 0.5) / 8.0, (f64::from(x) + 0.5) / 8.0]).unwrap();
integral += sample.radiance_source_rgb.x / sample.pdf_solid_angle / 64.0;
}
}
assert!((integral - PI / 2.0).abs() < 1e-14);
let black = decoded([[0; 4]; 8], "");
let env = prepared(&black, 0.0, 1.0);
let sample = env.sample([0.3, 0.7]).unwrap();
assert_eq!(sample.radiance_source_rgb, Vec3::ZERO);
assert_eq!(sample.pdf_solid_angle, 1.0 / (4.0 * PI));
}
#[test]
fn caller_budget_cancellation_consumes_preparation_and_preserves_owner_capacity() {
let data = decoded([[128, 0, 0, 129]; 8], "");
let bytes = data.retained_pixel_bytes().unwrap();
let mut task = EnvironmentPreparation::new(&data, 0.0, 1.0).unwrap();
let mut charged = 0;
assert!(
!task
.step(3, || {
charged += 1;
Ok(())
})
.unwrap()
);
assert_eq!(charged, 3);
assert_eq!(task.step(1, || Err(HdrError::new(HdrErrorCode::Cancelled, "cancel"))).unwrap_err().code, HdrErrorCode::Cancelled);
assert!(task.finish().is_err());
assert_eq!(data.retained_pixel_bytes().unwrap(), bytes);
let mut task = EnvironmentPreparation::new(&data, 0.0, 1.0).unwrap();
assert_eq!(task.step(1, || Err(HdrError::new(HdrErrorCode::LimitExceeded, "shared work"))).unwrap_err().code, HdrErrorCode::LimitExceeded);
assert!(task.finish().is_err());
}
#[test]
fn source_colour_is_not_assumed_srgb_and_decoder_corrections_are_not_reapplied() {
let raw = decoded([[128, 64, 32, 129]; 8], "EXPOSURE=2\nCOLORCORR=2 1 1\n");
let env = prepared(&raw, 0.0, 1.0);
assert_eq!(env.radiance_source_rgb(Vec3::X).unwrap(), Vec3::new(0.25, 0.25, 0.125));
assert!(env.radiance_linear_srgb(Vec3::X).is_err());
for header in ["PRIMARIES=0.64 0.33 0.29 0.60 0.15 0.06 0.3333 0.3333\n", "PRIMARIES=0.64 0.33 0.30 0.60 0.15 0.06 0.3127 0.3290\n"] {
let data = decoded([[128, 0, 0, 129]; 8], header);
let env = prepared(&data, 0.0, 1.0);
assert_eq!(env.require_linear_srgb().is_ok(), data.info().primaries == Some([0.64, 0.33, 0.30, 0.60, 0.15, 0.06, 0.3127, 0.3290]));
}
}
#[test]
fn hostile_options_variates_and_directions_refuse_without_panics() {
let data = decoded([[128, 0, 0, 129]; 8], "");
for (rotation, intensity) in [(f64::NAN, 1.0), (0.0, f64::INFINITY), (0.0, -1.0), (0.0, 65.0)] {
assert!(EnvironmentPreparation::new(&data, rotation, intensity).is_err());
}
assert!(EnvironmentPreparation::new(&data, 0.0, 1.0).unwrap().finish().is_err());
let env = prepared(&data, 0.0, 0.0);
for u in [[0.0, 0.5], [1.0, 0.5], [f64::NAN, 0.5]] {
assert!(env.sample(u).is_err());
}
for d in [Vec3::ZERO, Vec3::new(f64::INFINITY, 0.0, 0.0)] {
assert!(env.uv(d).is_err());
assert!(env.pdf_solid_angle(d).is_err());
}
assert_eq!(env.radiance_source_rgb(Vec3::new(f64::MAX, f64::MAX, 0.0)).unwrap(), Vec3::ZERO);
}
#[test]
fn direct_conductor_estimates_average_once_and_do_not_cross_geometry() {
let data = decoded([[128, 64, 32, 129]; 8], "PRIMARIES=0.64 0.33 0.30 0.60 0.15 0.06 0.3127 0.3290\n");
let env = prepared(&data, 0.0, 1.0);
let surface = crate::surface::OpaqueSurface::new(Vec3::new(1.0, 1.0, 1.0), 1.0, 1.0, 1.5).unwrap();
let mut mean = Vec3::ZERO;
for i in 0..4096 {
let u = [(f64::from(i) + 0.5) / 4096.0, 0.375];
let sample = env.direct_sample_linear_srgb(u, surface, Vec3::Z, Vec3::Z, Vec3::Z).unwrap();
mean += sample.contribution_linear_srgb / 4096.0;
}
// Independent white-conductor roughness=1 normal-view integral:
// 2*pi*integral_0^1 z/(2*pi*(1+z)) dz = 1-ln(2).
assert!((mean - Vec3::new(1.0, 0.5, 0.25) * (1.0 - 2.0_f64.ln())).len() < 3e-8);
let blocked = env.direct_sample_linear_srgb([0.25, 0.375], surface, Vec3::Z, -Vec3::Z, Vec3::Z).unwrap();
assert_eq!(blocked.contribution_linear_srgb, Vec3::ZERO);
for view in [Vec3::new(0.99, 0.0, -0.1), Vec3::X] {
let crossed = env.direct_sample_linear_srgb([0.25, 0.01], surface, Vec3::new(0.8, 0.0, 0.6), Vec3::Z, view).unwrap();
assert_eq!(crossed.contribution_linear_srgb, Vec3::ZERO);
}
assert!(env.direct_sample_linear_srgb([0.25, 0.01], surface, Vec3::Z, Vec3::Z, Vec3::ZERO).is_err());
let unknown = decoded([[128, 0, 0, 129]; 8], "");
assert!(prepared(&unknown, 0.0, 1.0).direct_sample_linear_srgb([0.25, 0.375], surface, Vec3::Z, Vec3::Z, Vec3::Z).is_err());
}
+6
View File
@@ -122,6 +122,9 @@ impl HdrSource {
pub fn encoded_bytes(&self) -> &[u8] {
&self.bytes
}
pub fn retained_encoded_bytes(&self) -> u64 {
self.bytes.capacity() as u64
}
pub fn validate(&self, cancelled: impl Fn() -> bool) -> Result<()> {
check_cancelled(&cancelled)?;
let mut rows = Rows::new(self.clone())?;
@@ -173,6 +176,9 @@ impl Rows {
pixels
.try_reserve_exact(source.info.width as usize)
.map_err(|_| HdrError::new(ErrorCode::AllocationFailed, "could not reserve HDR scanline"))?;
if pixels.capacity() != source.info.width as usize {
return Err(limit("HDR scanline capacity exceeds admission"));
}
pixels.resize(source.info.width as usize, [0; 4]);
Ok(Self {
offset: source.info.offset,
+2
View File
@@ -1,5 +1,7 @@
//! Device-independent, bounded linear HDR input preparation.
pub mod environment_input;
pub mod environment_sampling;
mod hdr;
mod task;
pub use hdr::{HdrInfo, HdrSource, MAX_HDR_BYTES, MAX_HDR_HEIGHT, MAX_HDR_PIXELS, MAX_HDR_WIDTH};
Loaded 100 of 181 files, more files were not shown because too many files have changed in this diff. Show more