mirror of
https://github.com/storytold/materialcraft.git
synced 2026-11-20 06:21:05 +01:00
Merge main into feat/image-craft-texture
This commit is contained in:
commit
2ee4537c65
72 files changed
+1808
-602
No files matched your search
Generated
+10
-71
@@ -445,12 +445,6 @@ version = "1.5.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53"
|
||||
|
||||
[[package]]
|
||||
name = "base64"
|
||||
version = "0.13.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "9e1b586273c5702936fe7b7d6896644d8be71e6314cfe09d3167c95f712589e8"
|
||||
|
||||
[[package]]
|
||||
name = "base64"
|
||||
version = "0.22.1"
|
||||
@@ -575,12 +569,6 @@ dependencies = [
|
||||
"syn 3.0.9",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "byteorder"
|
||||
version = "1.5.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "1fd0f2584146f6f2ef48085050886acf353beff7305ebd1ae69500e27c67f64b"
|
||||
|
||||
[[package]]
|
||||
name = "byteorder-lite"
|
||||
version = "0.1.0"
|
||||
@@ -963,6 +951,14 @@ dependencies = [
|
||||
"objc2-app-kit 0.3.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-mesh"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=57288edafdc45552e30481cc649021de446abfa0#57288edafdc45552e30481cc649021de446abfa0"
|
||||
dependencies = [
|
||||
"serde_json",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-metadata"
|
||||
version = "0.1.0"
|
||||
@@ -2063,45 +2059,6 @@ dependencies = [
|
||||
"web-sys",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "gltf"
|
||||
version = "1.4.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e3ce1918195723ce6ac74e80542c5a96a40c2b26162c1957a5cd70799b8cacf7"
|
||||
dependencies = [
|
||||
"base64 0.13.1",
|
||||
"byteorder",
|
||||
"gltf-json",
|
||||
"image",
|
||||
"lazy_static",
|
||||
"serde_json",
|
||||
"urlencoding",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "gltf-derive"
|
||||
version = "1.4.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "14070e711538afba5d6c807edb74bcb84e5dbb9211a3bf5dea0dfab5b24f4c51"
|
||||
dependencies = [
|
||||
"inflections",
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 2.0.119",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "gltf-json"
|
||||
version = "1.4.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e6176f9d60a7eab0a877e8e96548605dedbde9190a7ae1e80bbcc1c9af03ab14"
|
||||
dependencies = [
|
||||
"gltf-derive",
|
||||
"serde",
|
||||
"serde_derive",
|
||||
"serde_json",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "glutin"
|
||||
version = "0.32.3"
|
||||
@@ -2537,12 +2494,6 @@ dependencies = [
|
||||
"serde_core",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "inflections"
|
||||
version = "1.1.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a257582fdcde896fd96463bf2d40eefea0580021c0712a0e2b028b60b47a837a"
|
||||
|
||||
[[package]]
|
||||
name = "io-extras"
|
||||
version = "0.19.0"
|
||||
@@ -2942,6 +2893,7 @@ dependencies = [
|
||||
"base64 0.22.1",
|
||||
"craft-fonts-build",
|
||||
"craft-mcmat",
|
||||
"craft-mesh",
|
||||
"craft-mime",
|
||||
"craft-svg",
|
||||
"craft-texture 0.1.0 (git+https://github.com/storytold/craft-libs?rev=726ad0f8290bedb6ced60fa06200a6b574f9990d)",
|
||||
@@ -2949,7 +2901,6 @@ dependencies = [
|
||||
"craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=b6d9feed23ceae249b40593ed84a668343091627)",
|
||||
"dds",
|
||||
"flate2",
|
||||
"gltf",
|
||||
"image",
|
||||
"materialcraft-core",
|
||||
"materialcraft-geom",
|
||||
@@ -2959,7 +2910,6 @@ dependencies = [
|
||||
"serde_json",
|
||||
"sha2",
|
||||
"thiserror 2.0.21",
|
||||
"tobj",
|
||||
"zip 2.6.1",
|
||||
]
|
||||
|
||||
@@ -3034,6 +2984,7 @@ dependencies = [
|
||||
"js-sys",
|
||||
"log",
|
||||
"materialcraft-engine",
|
||||
"materialcraft-formats",
|
||||
"materialcraft-ui-egui",
|
||||
"wasm-bindgen",
|
||||
"wasm-bindgen-futures",
|
||||
@@ -5019,12 +4970,6 @@ version = "1.13.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "fd3ca314f692efd6c868f8408f53fe444634a845f96c028b97d35f6a1f79f0ee"
|
||||
|
||||
[[package]]
|
||||
name = "tobj"
|
||||
version = "4.0.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "6eb8e04167c1c0c76b5de63226fd733485ad63ef71e40de31e16272f47b099e2"
|
||||
|
||||
[[package]]
|
||||
name = "tokio"
|
||||
version = "1.54.1"
|
||||
@@ -5290,12 +5235,6 @@ dependencies = [
|
||||
"log",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "urlencoding"
|
||||
version = "2.1.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "daf8dba3b7eb870caf1ddeed7bc9d2a049f3cfdfae7cb521b087cc33ae4c49da"
|
||||
|
||||
[[package]]
|
||||
name = "usvg"
|
||||
version = "0.48.1"
|
||||
|
||||
+4
-5
@@ -40,12 +40,14 @@ rust-version = "1.95"
|
||||
repository = "https://github.com/storytold/materialcraft"
|
||||
|
||||
[workspace.dependencies]
|
||||
# Standard Base64 output; strict SBS decoding remains app-local.
|
||||
# Standard Base64 output; strict SBS decoding remains app-local
|
||||
craft-mime = { git = "https://github.com/storytold/craft-libs", rev = "ea24422ae9859dc5da398d0462bc87f8e02e0d10", version = "0.1.0" }
|
||||
craft-texture-dds = { package = "craft-texture", version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "726ad0f8290bedb6ced60fa06200a6b574f9990d", features = ["dds"] }
|
||||
# Read 3D meshes through craft-mesh; keep mesh processing app-local
|
||||
craft-mesh = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "57288edafdc45552e30481cc649021de446abfa0", default-features = false, features = ["obj", "gltf"] }
|
||||
# Shared XML escaping; SBS model and serialization policy stay app-local.
|
||||
craft-xml = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "b6d9feed23ceae249b40593ed84a668343091627" }
|
||||
# SVG: bounded parsing (usvg re-exported) and drawing (resvg) behind the shared checks.
|
||||
# Bound SVG parsing and drawing through craft-svg
|
||||
craft-svg = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "57288edafdc45552e30481cc649021de446abfa0", features = ["tree-render"] }
|
||||
# internal
|
||||
materialcraft-core = { path = "crates/core" }
|
||||
@@ -64,7 +66,6 @@ serde = { version = "1", features = ["derive"] }
|
||||
serde_json = "1"
|
||||
sha2 = "0.10" # MIT OR Apache-2.0; stable content keys for persistent previews.
|
||||
glam = { version = "0.30", features = ["serde", "bytemuck"] }
|
||||
bytemuck = { version = "1", features = ["derive"] }
|
||||
rayon = "1"
|
||||
log = "0.4"
|
||||
image = { version = "0.25", default-features = false, features = ["png", "jpeg", "tga", "tiff", "exr", "hdr", "bmp", "webp", "gif", "pnm"] }
|
||||
@@ -76,8 +77,6 @@ wgpu = "30"
|
||||
rfd = "0.17"
|
||||
rustix = { version = "1", default-features = false, features = ["std", "fs", "process"] }
|
||||
zip = { version = "2", default-features = false, features = ["deflate"] }
|
||||
gltf = { version = "1.4", default-features = false, features = ["import", "utils"] }
|
||||
tobj = { version = "4", default-features = false }
|
||||
mikktspace = { version = "0.3", default-features = false, features = ["glam"] }
|
||||
rmcp = { version = "3.5", default-features = false, features = ["server", "macros", "transport-io"] }
|
||||
tokio = { version = "1", features = ["rt-multi-thread", "macros", "io-std", "sync", "net", "io-util", "time"] }
|
||||
|
||||
@@ -178,12 +178,13 @@ The details are in [`docs/control-protocol.md`](docs/control-protocol.md).
|
||||
MaterialCraft is under active development. [**ROADMAP.md**](ROADMAP.md) has the parity estimate by
|
||||
area, the remaining work and what's next.
|
||||
|
||||
**Current focus (2026-11-05):** primitive editing and native SBS save/load. The old Rust
|
||||
procedural library has been removed. The replacement includes 30 main-graph entries, 85 function
|
||||
operations and three pattern node kinds. Start with **File → New → Atomic sample**.
|
||||
**Current focus (2026-11-16):** node behavior, regression coverage and SBS save/load. The old Rust
|
||||
procedural library has been removed. The replacement includes 29 main-graph entries, 85 function
|
||||
operations and four pattern node kinds. Start with **File → New → Atomic sample**.
|
||||
|
||||
See [the primitive workflow](docs/atomic-workflow.md) for usage, validation scope and limitations.
|
||||
Reference-app rendering parity and full SBS library loading are still pending.
|
||||
The [catalog status](docs/node-catalog-parity.md) records implemented behavior and remaining work.
|
||||
Full numerical compatibility and arbitrary SBS interoperability remain unestablished.
|
||||
|
||||
**Workspace:** `crates/{core, geom, nodes, eval, formats, engine, render, automation, ui-egui}`
|
||||
and `apps/{materialcraft, materialcraft-cli, materialcraft-web}`. The egui frontend is its own
|
||||
|
||||
+11
-7
@@ -1,25 +1,29 @@
|
||||
# MaterialCraft roadmap
|
||||
|
||||
**Current focus (2026-11-08):** native primitive editing, reusable SBS functions and interoperable save/load.
|
||||
**Current focus (2026-11-16):** node behavior, regression coverage and interoperable save/load.
|
||||
|
||||
The old Rust procedural library has been removed. The main catalog has 30 entries: 26 native
|
||||
The old Rust procedural library has been removed. The main catalog has 29 entries: 25 native
|
||||
primitives and four graph input/output items. Functions have 85 operations; pattern graphs have
|
||||
Quadrant, Switch, Iterate and Dot. See [the primitive workflow](docs/atomic-workflow.md) for usage and limits.
|
||||
|
||||
Earlier percentage estimates and node counts are superseded by this change. Reference-app
|
||||
rendering parity and arbitrary SBS round trips have not been established.
|
||||
Earlier percentage estimates and node counts are superseded by this change. Full numerical
|
||||
compatibility and arbitrary SBS round trips have not been established. The
|
||||
[catalog status](docs/node-catalog-parity.md) records available nodes, implemented corrections
|
||||
and behavior that remains untested.
|
||||
|
||||
## Next steps
|
||||
|
||||
1. Verify the original atomic sample in the reference application
|
||||
2. Compare primitive outputs and parameter semantics against reference results
|
||||
3. Validate the converted standard library in the reference application and establish redistribution rights
|
||||
1. Extend atomic sample and SBS interoperability coverage
|
||||
2. Resolve the primitive, processor and map gaps in the catalog status
|
||||
3. Validate the converted standard library and establish redistribution rights
|
||||
4. Extend the SBS library beyond reusable functions to processing graphs
|
||||
|
||||
## Progress log
|
||||
|
||||
| Date | What landed |
|
||||
|---|---|
|
||||
| 2026-11-16 | Corrected six atomic nodes: filter kernels and Float32 arithmetic, rectangular scaling, independent tiling, channel selection and save/load, and empty Text/SVG backgrounds. [Behavior and validation](docs/atomic-parity-improvements.md) |
|
||||
| 2026-11-15 | Corrected node defaults, typed unconnected inputs, missing-texture output and SBS serialization; updated catalog counts and remaining validation scope |
|
||||
| 2026-11-08 | Explorer folder hierarchy and package/folder/graph context menus, native SBS empty folders and resource paths, undoable copy/move/rename/remove, and package reload/save-copy actions |
|
||||
| 2026-11-08 | Portable `sbs://` function instances in the Library, preserved package folders and missing references, and a converted library retaining all 171 supplied function bodies (2,334 nodes); external runtime equivalence and redistribution rights remain unverified |
|
||||
| 2026-11-02 | Cross-app materials: `.mcmat` portable materials, Send to TextureCraft, input-node preview images (mesh maps from TextureCraft), live re-cooks from TextureCraft through the CLI |
|
||||
|
||||
@@ -19,9 +19,11 @@ materialcraft-ui-egui = { workspace = true }
|
||||
log = { workspace = true }
|
||||
|
||||
[target.'cfg(target_arch = "wasm32")'.dependencies]
|
||||
# `wgpu` pulls egui-wgpu's defaults: WebGPU plus the WebGL2 fallback.
|
||||
# `wgpu` pulls egui-wgpu's defaults: WebGPU plus the WebGL2 fallback
|
||||
eframe = { workspace = true, features = ["default_fonts", "wgpu", "accesskit", "persistence"] }
|
||||
# The SBS library's `resources/`, which the browser build downloads at startup
|
||||
materialcraft-formats = { workspace = true }
|
||||
wasm-bindgen = "0.2"
|
||||
wasm-bindgen-futures = "0.4"
|
||||
js-sys = "0.3"
|
||||
web-sys = { version = "0.3", features = ["Window", "Document", "Element", "HtmlCanvasElement", "Location", "KeyboardEvent", "EventTarget", "AddEventListenerOptions"] }
|
||||
web-sys = { version = "0.3", features = ["Window", "Document", "Element", "HtmlCanvasElement", "Location", "KeyboardEvent", "EventTarget", "AddEventListenerOptions", "Response", "RequestInit", "AbortController", "AbortSignal"] }
|
||||
@@ -6,6 +6,8 @@
|
||||
<meta name="color-scheme" content="dark">
|
||||
<title>MaterialCraft</title>
|
||||
<link data-trunk rel="rust" data-bin="materialcraft-web" data-cargo-profile="wasm-release" data-wasm-opt="z" data-weak-refs />
|
||||
<!-- The SBS library's bitmaps ship beside the wasm: embedded, they push it past Cloudflare Pages' 25 MiB file cap -->
|
||||
<link data-trunk rel="copy-dir" href="../../assets/sbs/resources" data-target-path="sbs/resources" />
|
||||
<style>
|
||||
html, body { margin: 0; padding: 0; width: 100%; height: 100%; overflow: hidden; overscroll-behavior: none; background: #1c1c1c; }
|
||||
/* Touch and pen strokes paint and orbit; the browser must not scroll, zoom or select. */
|
||||
|
||||
@@ -33,9 +33,19 @@ mod tests {
|
||||
fn loading_page_offers_a_reload_when_startup_stalls() {
|
||||
let html = include_str!("../index.html");
|
||||
let (_, hint) = html.split_once("<p id=\"materialcraft_stalled\">").expect("stalled-startup hint in the loading element");
|
||||
|
||||
assert!(hint.contains("failed to") && hint.contains("<a href=\"\">Reload</a>"), "{hint}");
|
||||
assert!(html.contains("animation: materialcraft-stalled"), "the hint appears after a delay");
|
||||
assert!(html.contains("id=\"materialcraft_canvas\"") && html.contains("data-cargo-profile=\"wasm-release\""));
|
||||
assert!(!html.contains("<script"), "trunk injects the generated loader; the page has no script of its own");
|
||||
}
|
||||
|
||||
/// The SBS library's bitmaps would push the wasm past the 25 MiB file cap of Cloudflare Pages,
|
||||
/// so the page ships them beside it, where `web::LIBRARY_URL` downloads them from.
|
||||
#[test]
|
||||
fn loading_page_ships_the_library_resources_beside_the_wasm() {
|
||||
let html = include_str!("../index.html");
|
||||
|
||||
assert!(html.contains(r#"<link data-trunk rel="copy-dir" href="../../assets/sbs/resources" data-target-path="sbs/resources" />"#), "{html}");
|
||||
}
|
||||
}
|
||||
@@ -9,6 +9,11 @@ const CANVAS_ID: &str = "materialcraft_canvas";
|
||||
const LOADING_ID: &str = "materialcraft_loading";
|
||||
const STATUS_ID: &str = "materialcraft_status";
|
||||
const PROGRESS_ID: &str = "materialcraft_progress";
|
||||
/// Where `index.html` copies the SBS library's `resources/`, relative to the page
|
||||
const LIBRARY_URL: &str = "sbs";
|
||||
/// How long startup waits for the library files; a response that stalls would otherwise keep the
|
||||
/// loading screen up for good. Two minutes fits the 14 MB of bitmaps on a slow connection
|
||||
const LIBRARY_DOWNLOAD_TIMEOUT_MS: i32 = 120_000;
|
||||
|
||||
pub fn start() {
|
||||
eframe::WebLogger::init(log::LevelFilter::Info).ok();
|
||||
@@ -18,6 +23,7 @@ pub fn start() {
|
||||
log::error!("no document");
|
||||
return;
|
||||
};
|
||||
|
||||
let result = match document.get_element_by_id(CANVAS_ID).and_then(|e| e.dyn_into::<web_sys::HtmlCanvasElement>().ok()) {
|
||||
Some(canvas) => run(canvas).await,
|
||||
None => Err(format!("the page has no <canvas id=\"{CANVAS_ID}\">")),
|
||||
@@ -37,7 +43,9 @@ pub fn start() {
|
||||
}
|
||||
|
||||
async fn run(canvas: web_sys::HtmlCanvasElement) -> Result<(), String> {
|
||||
// The WebAssembly has downloaded and compiled when this runs.
|
||||
// The WebAssembly has downloaded and compiled when this runs
|
||||
step(0.3, "Downloading the material library…").await;
|
||||
download_library().await;
|
||||
step(0.5, "Preparing a new package…").await;
|
||||
let session = materialcraft_engine::new_session();
|
||||
step(0.8, "Starting the renderer…").await;
|
||||
@@ -53,7 +61,8 @@ async fn run(canvas: web_sys::HtmlCanvasElement) -> Result<(), String> {
|
||||
options,
|
||||
Box::new(|cc| {
|
||||
let mut app = MaterialCraftApp::new(cc, session);
|
||||
// One thread cooks in the browser: keep previews small.
|
||||
|
||||
// One thread cooks in the browser, so keep previews small
|
||||
app.ui.prefs.preview_size = app.ui.prefs.preview_size.clamp(128, 256);
|
||||
Ok(Box::new(app))
|
||||
}),
|
||||
@@ -62,6 +71,56 @@ async fn run(canvas: web_sys::HtmlCanvasElement) -> Result<(), String> {
|
||||
.map_err(|e| e.as_string().unwrap_or_else(|| format!("{e:?}")))
|
||||
}
|
||||
|
||||
/// Fetch the SBS library files that ship beside the wasm (`index.html` copies them to
|
||||
/// [`LIBRARY_URL`]) before the first cook needs one. A file that fails to download, or is still
|
||||
/// downloading after [`LIBRARY_DOWNLOAD_TIMEOUT_MS`], is logged and reported by the nodes that use
|
||||
/// it; it doesn't stop startup.
|
||||
async fn download_library() {
|
||||
use materialcraft_formats::sbs::library;
|
||||
let Some(window) = web_sys::window() else { return };
|
||||
|
||||
// One deadline covers every request and body; aborting rejects whatever is still pending
|
||||
let controller = web_sys::AbortController::new().ok();
|
||||
let init = web_sys::RequestInit::new();
|
||||
init.set_signal(controller.as_ref().map(|c| c.signal()).as_ref());
|
||||
let abort = controller.map(|c| Closure::<dyn FnMut()>::new(move || c.abort()));
|
||||
let timer = abort
|
||||
.as_ref()
|
||||
.and_then(|abort| window.set_timeout_with_callback_and_timeout_and_arguments_0(abort.as_ref().unchecked_ref(), LIBRARY_DOWNLOAD_TIMEOUT_MS).ok());
|
||||
|
||||
// Start every fetch before awaiting its response
|
||||
let requests: Vec<_> = library::external_assets()
|
||||
.iter()
|
||||
.map(|relative| {
|
||||
let url = String::from(js_sys::encode_uri(&format!("{LIBRARY_URL}/{relative}")));
|
||||
(*relative, wasm_bindgen_futures::JsFuture::from(window.fetch_with_str_and_init(&url, &init)))
|
||||
})
|
||||
.collect();
|
||||
for (relative, request) in requests {
|
||||
if let Err(e) = fetch_bytes(request).await.and_then(|bytes| library::install(relative, bytes)) {
|
||||
log::warn!("couldn't download sbs://{relative}: {e}");
|
||||
}
|
||||
}
|
||||
|
||||
// The closure must outlive the timer, so cancel the timer before dropping it
|
||||
if let Some(timer) = timer {
|
||||
window.clear_timeout_with_handle(timer);
|
||||
}
|
||||
drop(abort);
|
||||
}
|
||||
|
||||
async fn fetch_bytes(request: wasm_bindgen_futures::JsFuture) -> Result<Vec<u8>, String> {
|
||||
let response: web_sys::Response = request.await.and_then(|r| r.dyn_into()).map_err(|e| format!("{e:?}"))?;
|
||||
if !response.ok() {
|
||||
return Err(format!("HTTP {}", response.status()));
|
||||
}
|
||||
|
||||
let buffer = response.array_buffer().map_err(|e| format!("{e:?}"))?;
|
||||
let buffer = wasm_bindgen_futures::JsFuture::from(buffer).await.map_err(|e| format!("{e:?}"))?;
|
||||
|
||||
Ok(js_sys::Uint8Array::new(&buffer).to_vec())
|
||||
}
|
||||
|
||||
/// Show a startup step on the loading screen and let the browser paint it before the next
|
||||
/// (blocking) step runs.
|
||||
async fn step(progress: f32, status: &str) {
|
||||
@@ -72,8 +131,8 @@ async fn step(progress: f32, status: &str) {
|
||||
if let Some(el) = document.get_element_by_id(PROGRESS_ID) {
|
||||
let _ = el.set_attribute("value", &progress.to_string());
|
||||
}
|
||||
// A timer longer than a frame lets the browser paint the step before work resumes. Not
|
||||
// `requestAnimationFrame`: it never fires in a background tab, which would stall startup.
|
||||
|
||||
// A timer lets background tabs resume even without animation frames
|
||||
let promise = js_sys::Promise::new(&mut |resolve, _| {
|
||||
if let Some(w) = web_sys::window() {
|
||||
let _ = w.set_timeout_with_callback_and_timeout_and_arguments_0(&resolve, 20);
|
||||
@@ -101,7 +160,8 @@ fn capture_app_shortcuts() {
|
||||
if let Err(e) = window.add_event_listener_with_callback_and_add_event_listener_options("keydown", on_key.as_ref().unchecked_ref(), &options) {
|
||||
log::warn!("couldn't take over the browser's shortcuts: {e:?}");
|
||||
}
|
||||
// The listener lives as long as the page.
|
||||
|
||||
// The listener lives as long as the page
|
||||
on_key.forget();
|
||||
}
|
||||
|
||||
|
||||
@@ -11,36 +11,50 @@ use serde_json::json;
|
||||
#[test]
|
||||
fn generated_normal_conventions_produce_the_same_surface_when_matched() {
|
||||
let height = Image::gray(32, 32, |x, y| ((x as f32 * 0.15).sin() + (y as f32 * 0.25).sin()) * 0.25 + 0.5);
|
||||
let gl = height_to_normal(&height, 8.0, false, false, false);
|
||||
let dx = height_to_normal(&height, 8.0, true, false, false);
|
||||
let opengl_normal = height_to_normal(&height, 8.0, false, false, false);
|
||||
let directx_normal = height_to_normal(&height, 8.0, true, false, false);
|
||||
let normal_node = materialcraft_engine::nodes::find("normal").unwrap();
|
||||
assert_eq!(normal_node.param("opengl").unwrap().default.as_bool(), Some(true));
|
||||
|
||||
assert_eq!(normal_node.param("opengl").unwrap().default.as_bool(), Some(false));
|
||||
|
||||
let maps = |normal| Maps { normal: Some(normal), base_color: Some(Image::filled(4, 4, Kind::Color, [0.5, 0.5, 0.5, 1.0])), ..Maps::default() };
|
||||
let (scene, light) = (Scene::builtin("sphere"), Lighting::new("studio"));
|
||||
let settings = Settings::default();
|
||||
assert!(!settings.normal_y_flip);
|
||||
let expected = render(&scene, &maps(gl), &light, &settings, 64, 48);
|
||||
let flipped = maps(dx);
|
||||
let matched = render(&scene, &flipped, &light, &Settings { normal_y_flip: true, ..settings }, 64, 48);
|
||||
assert!(expected.iter().zip(&matched).all(|(a, b)| a.abs_diff(*b) <= 1));
|
||||
let wrong = render(&scene, &flipped, &light, &settings, 64, 48);
|
||||
assert!(expected.iter().zip(&wrong).filter(|(a, b)| a.abs_diff(**b) > 2).count() > 20);
|
||||
let expected = render(&scene, &maps(directx_normal.clone()), &light, &Settings { normal_y_flip: true, ..settings }, 64, 48);
|
||||
let matched = render(&scene, &maps(opengl_normal), &light, &Settings { normal_y_flip: false, ..settings }, 64, 48);
|
||||
|
||||
assert!(expected.iter().zip(&matched).all(|(actual, expected)| actual.abs_diff(*expected) <= 1));
|
||||
|
||||
let default_output = render(&scene, &maps(directx_normal.clone()), &light, &settings, 64, 48);
|
||||
|
||||
assert!(expected.iter().zip(&default_output).all(|(actual, expected)| actual.abs_diff(*expected) <= 1));
|
||||
|
||||
let mismatched = render(&scene, &maps(directx_normal), &light, &Settings { normal_y_flip: false, ..settings }, 64, 48);
|
||||
|
||||
assert!(expected.iter().zip(&mismatched).filter(|(actual, expected)| actual.abs_diff(**expected) > 2).count() > 20);
|
||||
assert!(settings.normal_y_flip);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn headless_render_honors_the_normal_y_command() {
|
||||
let mut s = new_session();
|
||||
s.preview_size = Some(64);
|
||||
let node = execute(&mut s, "graph.node.add", &json!({"def": "uniform", "params": {"color": [0.5, 0.75, 1.0, 1.0]}})).unwrap()["id"].as_u64().unwrap();
|
||||
execute(&mut s, "graph.node.add", &json!({"def": "output", "connectFrom": {"node": node}, "params": {"usage": 1}})).unwrap();
|
||||
let mut h = Headless::new(s, Filesystem::Denied);
|
||||
let mut session = new_session();
|
||||
session.preview_size = Some(64);
|
||||
let node = execute(&mut session, "graph.node.add", &json!({"def": "uniform", "params": {"color": [0.5, 0.75, 1.0, 1.0]}})).unwrap()["id"].as_u64().unwrap();
|
||||
execute(&mut session, "graph.node.add", &json!({"def": "output", "connectFrom": {"node": node}, "params": {"usage": 1}})).unwrap();
|
||||
let mut headless = Headless::new(session, Filesystem::Denied);
|
||||
let options = RenderOptions { width: Some(64), height: Some(48), ..RenderOptions::default() };
|
||||
let gl = h.render_png(&options).unwrap().png;
|
||||
execute(&mut h.session, "view.3d", &json!({"normalYFlip": true})).unwrap();
|
||||
let wrong = h.render_png(&options).unwrap().png;
|
||||
assert_ne!(gl, wrong);
|
||||
execute(&mut h.session, "graph.node.param", &json!({"id": node, "param": "color", "value": [0.5, 0.25, 1.0, 1.0]})).unwrap();
|
||||
assert_eq!(gl, h.render_png(&options).unwrap().png);
|
||||
execute(&mut h.session, "view.3d.reset", &json!({})).unwrap();
|
||||
assert_eq!(wrong, h.render_png(&options).unwrap().png);
|
||||
let directx_render = headless.render_png(&options).unwrap().png;
|
||||
|
||||
execute(&mut headless.session, "view.3d", &json!({"normalYFlip": false})).unwrap();
|
||||
let opengl_render = headless.render_png(&options).unwrap().png;
|
||||
|
||||
assert_ne!(directx_render, opengl_render);
|
||||
|
||||
execute(&mut headless.session, "graph.node.param", &json!({"id": node, "param": "color", "value": [0.5, 0.25, 1.0, 1.0]})).unwrap();
|
||||
|
||||
assert_eq!(directx_render, headless.render_png(&options).unwrap().png);
|
||||
|
||||
execute(&mut headless.session, "view.3d.reset", &json!({})).unwrap();
|
||||
|
||||
assert_eq!(opengl_render, headless.render_png(&options).unwrap().png);
|
||||
}
|
||||
@@ -56,7 +56,7 @@ impl Default for View3d {
|
||||
exposure: 0.0,
|
||||
height_scale: 0.04,
|
||||
height_level: 0.0,
|
||||
normal_y_flip: false,
|
||||
normal_y_flip: true,
|
||||
show_axis: false,
|
||||
show_grid: false,
|
||||
transparency: true,
|
||||
|
||||
@@ -29,7 +29,7 @@ pub(crate) fn specs() -> Vec<CommandSpec> {
|
||||
"3D view settings",
|
||||
[],
|
||||
None,
|
||||
"{scene? (cube|cylinder|plane|sphere|material_ball|rounded_cube|torus), tiling?, yaw?, pitch?, distance?, target? ([x, y, z] orbit point in mesh radii from its center, within the pan limit preference), environment? (studio|sunset|overcast|night), envRotation?, exposure?, heightScale? (displacement depth in mesh radii, 0..0.5), heightLevel? (height that stays on the surface, 0..1; 0 = rises out), normalYFlip? (DirectX normal maps; default false/OpenGL), axis?, grid?, transparency? (see through where alpha < 1), alphaView? (show the alpha channel)}",
|
||||
"{scene? (cube|cylinder|plane|sphere|material_ball|rounded_cube|torus), tiling?, yaw?, pitch?, distance?, target? ([x, y, z] orbit point in mesh radii from its center, within the pan limit preference), environment? (studio|sunset|overcast|night), envRotation?, exposure?, heightScale? (displacement depth in mesh radii, 0..0.5), heightLevel? (height that stays on the surface, 0..1; 0 = rises out), normalYFlip? (DirectX normal maps; default true/DirectX), axis?, grid?, transparency? (see through where alpha < 1), alphaView? (show the alpha channel)}",
|
||||
always,
|
||||
view3d
|
||||
),
|
||||
@@ -60,109 +60,117 @@ pub(crate) fn specs() -> Vec<CommandSpec> {
|
||||
]
|
||||
}
|
||||
|
||||
fn view2d(s: &mut Session, p: &J) -> Result<J> {
|
||||
// Validate the channel before applying any part of the request.
|
||||
let channel = strp(p, "channel");
|
||||
fn view2d(session: &mut Session, params: &J) -> Result<J> {
|
||||
// Validate the channel before applying any part of the request
|
||||
let channel = strp(params, "channel");
|
||||
if channel.is_some_and(|c| !["rgba", "r", "g", "b", "a"].contains(&c)) {
|
||||
return Err(bad("view.2d", "`channel` is rgba, r, g, b or a"));
|
||||
}
|
||||
if let Some(n) = u64p(p, "node") {
|
||||
s.graph()?.node(NodeId(n)).map_err(|_| bad("view.2d", format!("no node {n}")))?;
|
||||
s.view2d.node = Some(NodeId(n));
|
||||
s.view2d.port = 0;
|
||||
|
||||
if let Some(node) = u64p(params, "node") {
|
||||
session.graph()?.node(NodeId(node)).map_err(|_| bad("view.2d", format!("no node {node}")))?;
|
||||
session.view2d.node = Some(NodeId(node));
|
||||
session.view2d.port = 0;
|
||||
}
|
||||
if let Some(port) = u64p(p, "port") {
|
||||
s.view2d.port = port as usize;
|
||||
if let Some(port) = u64p(params, "port") {
|
||||
session.view2d.port = port as usize;
|
||||
}
|
||||
if let Some(t) = boolp(p, "tiled") {
|
||||
s.view2d.tiled = t;
|
||||
if let Some(tiled) = boolp(params, "tiled") {
|
||||
session.view2d.tiled = tiled;
|
||||
}
|
||||
if let Some(h) = boolp(p, "histogram") {
|
||||
s.view2d.histogram = h;
|
||||
if let Some(histogram) = boolp(params, "histogram") {
|
||||
session.view2d.histogram = histogram;
|
||||
}
|
||||
if let Some(c) = channel {
|
||||
s.view2d.channel = c.into();
|
||||
session.view2d.channel = c.into();
|
||||
}
|
||||
Ok(serde_json::to_value(&s.view2d).unwrap_or(J::Null))
|
||||
|
||||
Ok(serde_json::to_value(&session.view2d).unwrap_or(J::Null))
|
||||
}
|
||||
|
||||
fn view3d(s: &mut Session, p: &J) -> Result<J> {
|
||||
// Validated up front so a bad target changes nothing.
|
||||
let target = match p.get("target") {
|
||||
fn view3d(session: &mut Session, params: &J) -> Result<J> {
|
||||
// Validate up front so a bad target changes nothing
|
||||
let target = match params.get("target") {
|
||||
None => None,
|
||||
Some(t) => {
|
||||
let xyz: Option<Vec<f32>> =
|
||||
t.as_array().filter(|a| a.len() == 3).map(|a| a.iter().filter_map(J::as_f64).map(|f| f as f32).filter(|f| f.is_finite()).collect());
|
||||
match xyz.as_deref() {
|
||||
Some(&[x, y, z]) => Some(s.camera.clamp_target([x, y, z])),
|
||||
Some(&[x, y, z]) => Some(session.camera.clamp_target([x, y, z])),
|
||||
_ => return Err(bad("view.3d", "`target` is [x, y, z]")),
|
||||
}
|
||||
}
|
||||
};
|
||||
// A rejected environment must not leave a new scene applied.
|
||||
let environment = strp(p, "environment");
|
||||
if let Some(e) = environment
|
||||
&& !ENVIRONMENTS.iter().any(|(id, _)| *id == e)
|
||||
|
||||
// A rejected environment must not leave a new scene applied
|
||||
let environment = strp(params, "environment");
|
||||
if let Some(environment) = environment
|
||||
&& !ENVIRONMENTS.iter().any(|(id, _)| *id == environment)
|
||||
{
|
||||
return Err(bad("view.3d", format!("unknown environment `{e}`")));
|
||||
return Err(bad("view.3d", format!("unknown environment `{environment}`")));
|
||||
}
|
||||
if let Some(sc) = strp(p, "scene") {
|
||||
if sc == "custom" && s.custom_mesh.is_none() {
|
||||
|
||||
if let Some(scene) = strp(params, "scene") {
|
||||
if scene == "custom" && session.custom_mesh.is_none() {
|
||||
return Err(bad("view.3d", "no mesh is loaded: use view.3d.loadMesh"));
|
||||
}
|
||||
let v = &mut s.view3d;
|
||||
if sc != "custom" && !SCENES.iter().any(|(id, _)| *id == sc) {
|
||||
return Err(bad("view.3d", format!("unknown scene `{sc}`")));
|
||||
|
||||
let view = &mut session.view3d;
|
||||
if scene != "custom" && !SCENES.iter().any(|(id, _)| *id == scene) {
|
||||
return Err(bad("view.3d", format!("unknown scene `{scene}`")));
|
||||
}
|
||||
v.scene = sc.into();
|
||||
|
||||
view.scene = scene.into();
|
||||
}
|
||||
let v = &mut s.view3d;
|
||||
if let Some(e) = environment {
|
||||
v.environment = e.into();
|
||||
|
||||
let view = &mut session.view3d;
|
||||
if let Some(environment) = environment {
|
||||
view.environment = environment.into();
|
||||
}
|
||||
if let Some(t) = f32p(p, "tiling") {
|
||||
v.tiling = t.clamp(0.1, 64.0);
|
||||
if let Some(tiling) = f32p(params, "tiling") {
|
||||
view.tiling = tiling.clamp(0.1, 64.0);
|
||||
}
|
||||
if let Some(t) = f32p(p, "yaw") {
|
||||
v.yaw = t.rem_euclid(360.0);
|
||||
if let Some(yaw) = f32p(params, "yaw") {
|
||||
view.yaw = yaw.rem_euclid(360.0);
|
||||
}
|
||||
if let Some(t) = f32p(p, "pitch") {
|
||||
v.pitch = t.clamp(-89.0, 89.0);
|
||||
if let Some(pitch) = f32p(params, "pitch") {
|
||||
view.pitch = pitch.clamp(-89.0, 89.0);
|
||||
}
|
||||
if let Some(t) = f32p(p, "distance") {
|
||||
v.distance = t.clamp(1.2, 20.0);
|
||||
if let Some(distance) = f32p(params, "distance") {
|
||||
view.distance = distance.clamp(1.2, 20.0);
|
||||
}
|
||||
if let Some(t) = target {
|
||||
v.target = t;
|
||||
if let Some(target) = target {
|
||||
view.target = target;
|
||||
}
|
||||
if let Some(t) = f32p(p, "envRotation") {
|
||||
v.env_rotation = t.rem_euclid(360.0);
|
||||
if let Some(env_rotation) = f32p(params, "envRotation") {
|
||||
view.env_rotation = env_rotation.rem_euclid(360.0);
|
||||
}
|
||||
if let Some(t) = f32p(p, "exposure") {
|
||||
v.exposure = t.clamp(-10.0, 10.0);
|
||||
if let Some(exposure) = f32p(params, "exposure") {
|
||||
view.exposure = exposure.clamp(-10.0, 10.0);
|
||||
}
|
||||
if let Some(t) = f32p(p, "heightScale") {
|
||||
v.height_scale = t.clamp(0.0, 0.5);
|
||||
if let Some(height_scale) = f32p(params, "heightScale") {
|
||||
view.height_scale = height_scale.clamp(0.0, 0.5);
|
||||
}
|
||||
if let Some(t) = f32p(p, "heightLevel") {
|
||||
v.height_level = t.clamp(0.0, 1.0);
|
||||
if let Some(height_level) = f32p(params, "heightLevel") {
|
||||
view.height_level = height_level.clamp(0.0, 1.0);
|
||||
}
|
||||
if let Some(flip) = boolp(p, "normalYFlip") {
|
||||
v.normal_y_flip = flip;
|
||||
if let Some(flip) = boolp(params, "normalYFlip") {
|
||||
view.normal_y_flip = flip;
|
||||
}
|
||||
if let Some(b) = boolp(p, "axis") {
|
||||
v.show_axis = b;
|
||||
if let Some(show_axis) = boolp(params, "axis") {
|
||||
view.show_axis = show_axis;
|
||||
}
|
||||
if let Some(b) = boolp(p, "grid") {
|
||||
v.show_grid = b;
|
||||
if let Some(show_grid) = boolp(params, "grid") {
|
||||
view.show_grid = show_grid;
|
||||
}
|
||||
if let Some(b) = boolp(p, "transparency") {
|
||||
v.transparency = b;
|
||||
if let Some(transparency) = boolp(params, "transparency") {
|
||||
view.transparency = transparency;
|
||||
}
|
||||
if let Some(b) = boolp(p, "alphaView") {
|
||||
v.alpha_view = b;
|
||||
if let Some(alpha_view) = boolp(params, "alphaView") {
|
||||
view.alpha_view = alpha_view;
|
||||
}
|
||||
Ok(serde_json::to_value(&s.view3d).unwrap_or(J::Null))
|
||||
|
||||
Ok(serde_json::to_value(&session.view3d).unwrap_or(J::Null))
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
|
||||
@@ -170,16 +170,21 @@ fn exposed_parameter_binding_remains_live_after_saving() {
|
||||
let mut session = Session::new(atomic_sample().unwrap());
|
||||
let blur = session.graph().unwrap().nodes.iter().find(|node| node.def == "blur").unwrap().id;
|
||||
execute(&mut session, "graph.exposed.add", &json!({"id": "radius", "bind": {"node": blur.0, "param": "intensity"}})).unwrap();
|
||||
execute(&mut session, "graph.exposed.set", &json!({"id": "radius", "value": 4.0})).unwrap();
|
||||
|
||||
// At the 32-pixel preview, strength 4 covers only the center texel
|
||||
execute(&mut session, "graph.exposed.set", &json!({"id": "radius", "value": 8.0})).unwrap();
|
||||
let bytes = write_sbs(&session.pkg).unwrap();
|
||||
let loaded = read_sbs(&bytes, "exposed.sbs", &|_| None).unwrap();
|
||||
|
||||
assert!(loaded.warnings.is_empty(), "{:?}", loaded.warnings);
|
||||
|
||||
let mut loaded = Session::new(loaded.pkg);
|
||||
loaded.preview_size = Some(32);
|
||||
loaded.cook();
|
||||
let before = loaded.cooked.image(blur, 0).unwrap().data().to_vec();
|
||||
execute(&mut loaded, "graph.exposed.set", &json!({"id": "radius", "value": 0.0})).unwrap();
|
||||
loaded.cook();
|
||||
|
||||
assert_ne!(before.as_slice(), loaded.cooked.image(blur, 0).unwrap().data());
|
||||
}
|
||||
|
||||
|
||||
@@ -131,6 +131,7 @@ fn fx_map_starts_with_a_quadrant_and_grows_image_inputs_as_connected() {
|
||||
let mut session = new_session();
|
||||
session.preview_size = Some(16);
|
||||
let source = add(&mut session, "uniform");
|
||||
execute(&mut session, "graph.node.param", &json!({"id": source.0, "param": "color", "value": [0.5, 0.5, 0.5, 1.0]})).unwrap();
|
||||
execute(&mut session, "graph.node.param", &json!({"id": source.0, "param": "color_mode", "value": false})).unwrap();
|
||||
let owner = add(&mut session, "fx_map");
|
||||
let Value::PatternGraph(pattern) = &session.graph().unwrap().node(owner).unwrap().params["pattern"] else { panic!("missing default pattern") };
|
||||
@@ -204,24 +205,32 @@ fn terminal_outputs_cook_and_round_trip_without_source_pins() {
|
||||
let mut session = new_session();
|
||||
session.preview_size = Some(16);
|
||||
let source = add(&mut session, "uniform");
|
||||
execute(&mut session, "graph.node.param", &json!({"id": source.0, "param": "color", "value": [0.5, 0.5, 0.5, 1.0]})).unwrap();
|
||||
let output = add(&mut session, "output");
|
||||
execute(&mut session, "graph.connect", &json!({"from": source.0, "to": output.0})).unwrap();
|
||||
|
||||
assert_eq!(session.input_ports(output), vec!["input"]);
|
||||
assert!(session.output_ports(output).is_empty());
|
||||
|
||||
let before = session.pkg.clone();
|
||||
|
||||
assert!(execute(&mut session, "graph.connect", &json!({"from": output.0, "to": source.0})).is_err());
|
||||
assert_eq!(session.pkg, before);
|
||||
|
||||
let read = read_sbs(&write_sbs(&session.pkg).unwrap(), "terminal_output.sbs", &|_| None).unwrap();
|
||||
|
||||
assert!(read.warnings.is_empty(), "{:?}", read.warnings);
|
||||
|
||||
let mut loaded = Session::new(read.pkg);
|
||||
loaded.preview_size = Some(16);
|
||||
loaded.cook();
|
||||
let output = loaded.graph().unwrap().nodes.iter().find(|node| node.def == "output").unwrap().id;
|
||||
|
||||
assert!(loaded.output_ports(output).is_empty());
|
||||
assert!(loaded.cooked.nodes[&output].error.is_none());
|
||||
assert!((loaded.cooked.image(output, 0).unwrap().mean()[0] - 0.5).abs() < 1e-5);
|
||||
execute(&mut loaded, "view.2d", &json!({"node": output.0})).unwrap();
|
||||
|
||||
assert_eq!(loaded.view2d_image().unwrap().0, output);
|
||||
}
|
||||
|
||||
@@ -234,6 +243,7 @@ fn processors_sample_dynamic_image_inputs_after_sbs_round_trip() {
|
||||
session.graph_mut().unwrap().format = materialcraft_engine::core::OutputFormat::F32;
|
||||
session.preview_size = Some(16);
|
||||
let source = add(&mut session, "uniform");
|
||||
execute(&mut session, "graph.node.param", &json!({"id": source.0, "param": "color", "value": [0.5, 0.5, 0.5, 1.0]})).unwrap();
|
||||
let processor = add(&mut session, definition);
|
||||
for index in 0..6 {
|
||||
execute(&mut session, "graph.connect", &json!({"from": source.0, "to": processor.0, "toPort": format!("input{index}")})).unwrap();
|
||||
@@ -273,8 +283,10 @@ fn processors_sample_dynamic_image_inputs_after_sbs_round_trip() {
|
||||
fn background_pins_preserve_connected_images_through_sbs() {
|
||||
let mut session = new_session();
|
||||
session.preview_size = Some(16);
|
||||
let source = add(&mut session, "uniform");
|
||||
for definition in ["text", "svg"] {
|
||||
let source = add(&mut session, "uniform");
|
||||
execute(&mut session, "graph.node.param", &json!({"id": source.0, "param": "color", "value": [0.5, 0.5, 0.5, 1.0]})).unwrap();
|
||||
execute(&mut session, "graph.node.param", &json!({"id": source.0, "param": "color_mode", "value": definition == "svg"})).unwrap();
|
||||
let target = add(&mut session, definition);
|
||||
if definition == "text" {
|
||||
execute(&mut session, "graph.node.param", &json!({"id": target.0, "param": "text", "value": ""})).unwrap();
|
||||
@@ -283,13 +295,16 @@ fn background_pins_preserve_connected_images_through_sbs() {
|
||||
}
|
||||
|
||||
let read = read_sbs(&write_sbs(&session.pkg).unwrap(), "backgrounds.sbs", &|_| None).unwrap();
|
||||
|
||||
assert!(read.warnings.is_empty(), "{:?}", read.warnings);
|
||||
|
||||
let mut loaded = Session::new(read.pkg);
|
||||
loaded.preview_size = Some(16);
|
||||
loaded.cook();
|
||||
for node in loaded.graph().unwrap().nodes.iter().filter(|node| matches!(node.def.as_str(), "text" | "svg")) {
|
||||
assert_eq!(loaded.input_ports(node.id), vec!["background"]);
|
||||
let image = loaded.cooked.image(node.id, 0).unwrap();
|
||||
|
||||
assert_eq!(loaded.input_ports(node.id), vec!["background"]);
|
||||
assert_eq!(image.is_gray(), node.def == "text");
|
||||
assert!((image.mean()[0] - 0.5).abs() < 1e-5);
|
||||
assert!(loaded.cooked.nodes[&node.id].error.is_none());
|
||||
|
||||
@@ -2,16 +2,23 @@ use materialcraft_engine::{View3d, execute, new_session};
|
||||
use serde_json::json;
|
||||
|
||||
#[test]
|
||||
fn normal_map_convention_is_inspectable_and_resets_to_opengl() {
|
||||
let mut s = new_session();
|
||||
assert!(!s.view3d.normal_y_flip);
|
||||
assert_eq!(materialcraft_engine::nodes::find("normal").unwrap().param("opengl").unwrap().default.as_bool(), Some(true));
|
||||
execute(&mut s, "view.3d", &json!({"normalYFlip": true})).unwrap();
|
||||
let inspection = execute(&mut s, "session.inspect", &json!({})).unwrap();
|
||||
assert_eq!(inspection["view3d"]["normalYFlip"], true);
|
||||
let saved = serde_json::to_value(&s.view3d).unwrap();
|
||||
assert!(serde_json::from_value::<View3d>(saved).unwrap().normal_y_flip);
|
||||
assert!(!serde_json::from_value::<View3d>(json!({"scene": "sphere"})).unwrap().normal_y_flip);
|
||||
execute(&mut s, "view.3d.reset", &json!({})).unwrap();
|
||||
assert!(!s.view3d.normal_y_flip);
|
||||
fn normal_map_convention_is_inspectable_and_resets_to_directx() {
|
||||
let mut session = new_session();
|
||||
|
||||
assert!(session.view3d.normal_y_flip);
|
||||
assert_eq!(materialcraft_engine::nodes::find("normal").unwrap().param("opengl").unwrap().default.as_bool(), Some(false));
|
||||
|
||||
execute(&mut session, "view.3d", &json!({"normalYFlip": false})).unwrap();
|
||||
let inspection = execute(&mut session, "session.inspect", &json!({})).unwrap();
|
||||
|
||||
assert_eq!(inspection["view3d"]["normalYFlip"], false);
|
||||
|
||||
let saved = serde_json::to_value(&session.view3d).unwrap();
|
||||
|
||||
assert!(!serde_json::from_value::<View3d>(saved).unwrap().normal_y_flip);
|
||||
assert!(serde_json::from_value::<View3d>(json!({"scene": "sphere"})).unwrap().normal_y_flip);
|
||||
|
||||
execute(&mut session, "view.3d.reset", &json!({})).unwrap();
|
||||
|
||||
assert!(session.view3d.normal_y_flip);
|
||||
}
|
||||
@@ -13,6 +13,7 @@ fn setup() -> (Session, NodeId) {
|
||||
let mut s = new_session();
|
||||
s.preview_size = Some(32);
|
||||
let source = run(&mut s, "graph.node.add", json!({"def": "uniform"}))["id"].as_u64().unwrap();
|
||||
run(&mut s, "graph.node.param", json!({"id": source, "param": "color", "value": [0.5, 0.5, 0.5, 1.0]}));
|
||||
let levels = NodeId(run(&mut s, "graph.node.add", json!({"def": "levels", "connectFrom": {"node": source}}))["id"].as_u64().unwrap());
|
||||
(s, levels)
|
||||
}
|
||||
|
||||
@@ -30,7 +30,9 @@ fn imported_expression_cooks_follows_inputs_and_survives_undo_and_save() {
|
||||
s.pkg = imported.pkg;
|
||||
s.pkg.graphs[0].format = materialcraft_engine::core::OutputFormat::F32;
|
||||
let levels = s.graph().unwrap().nodes[0].id;
|
||||
let uniform = execute(&mut s, "graph.node.add", &json!({"def": "uniform", "params": {"color_mode": false}})).unwrap()["id"].as_u64().unwrap();
|
||||
let uniform = execute(&mut s, "graph.node.add", &json!({"def": "uniform", "params": {"color_mode": false, "color": [0.5, 0.5, 0.5, 1.0]}})).unwrap()["id"]
|
||||
.as_u64()
|
||||
.unwrap();
|
||||
execute(&mut s, "graph.connect", &json!({"from": uniform, "to": levels.0})).unwrap();
|
||||
let mean = |s: &mut materialcraft_engine::Session| {
|
||||
let levels = s.graph().unwrap().nodes.iter().find(|node| node.def == "levels").unwrap().id;
|
||||
|
||||
@@ -265,21 +265,28 @@ fn dynamic_parameters_follow_graph_inputs() {
|
||||
|
||||
let mut session = sample_session();
|
||||
run(&mut session, "file.new", json!({"template": "empty"}));
|
||||
let owner = NodeId(run(&mut session, "graph.node.add", json!({"def": "uniform", "params": {"color_mode": false}}))["id"].as_u64().unwrap());
|
||||
let owner = NodeId(
|
||||
run(&mut session, "graph.node.add", json!({"def": "uniform", "params": {"color_mode": false, "color": Value::Color([0.5, 0.5, 0.5, 1.0])}}))["id"]
|
||||
.as_u64()
|
||||
.unwrap(),
|
||||
);
|
||||
run(&mut session, "graph.exposed.add", json!({"id": "level", "default": Value::Float4([0.25; 4])}));
|
||||
let function = FunctionGraph::input("level", ValueType::Float4);
|
||||
run(&mut session, "graph.node.function", json!({"id": owner, "param": "color", "function": function}));
|
||||
|
||||
let mean = session.cook().image(owner, 0).unwrap().mean()[0];
|
||||
|
||||
assert!((mean - 0.25).abs() < 1e-4, "{mean}");
|
||||
run(&mut session, "graph.exposed.set", json!({"id": "level", "value": Value::Float4([0.75; 4])}));
|
||||
let mean = session.cook().image(owner, 0).unwrap().mean()[0];
|
||||
|
||||
assert!((mean - 0.75).abs() < 1e-4);
|
||||
|
||||
// Removing the function restores the plain value
|
||||
assert!(execute(&mut session, "graph.node.function", &json!({"id": owner, "param": "nope"})).is_err());
|
||||
run(&mut session, "graph.node.function", json!({"id": owner, "param": "color", "remove": true}));
|
||||
let mean = session.cook().image(owner, 0).unwrap().mean()[0];
|
||||
|
||||
assert!((mean - 0.5).abs() < 0.05);
|
||||
}
|
||||
|
||||
|
||||
@@ -114,7 +114,9 @@ pub(crate) fn cook_node(
|
||||
return fail(error, 0);
|
||||
}
|
||||
|
||||
if !node.functions.is_empty() || matches!(node.def.as_str(), "pixel_processor" | "value_processor" | "fx_map" | "transformation") {
|
||||
if !node.functions.is_empty()
|
||||
|| matches!(node.def.as_str(), "pixel_processor" | "value_processor" | "fx_map" | "transformation" | "blur" | "directional_blur" | "sharpen")
|
||||
{
|
||||
base.variables(variables.to_mut());
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,41 @@
|
||||
use craft_texture::Image;
|
||||
use materialcraft_core::{Graph, OutputFormat, Package, ParameterInheritance, Value};
|
||||
use materialcraft_eval::{Cache, Options, cook};
|
||||
use std::sync::Mutex;
|
||||
|
||||
#[test]
|
||||
fn atomic_filters_wrap_only_the_requested_axes_and_invalidate_cache() {
|
||||
for operation in ["blur", "directional_blur", "sharpen"] {
|
||||
let mut graph = Graph::new("Filter boundaries");
|
||||
graph.size = [4; 2];
|
||||
graph.format = OutputFormat::F32;
|
||||
graph.tiling_mode = ParameterInheritance::Absolute;
|
||||
let input = graph.add_node("input_grayscale", [0.0; 2]);
|
||||
graph.node_mut(input).unwrap().params.insert("identifier".into(), Value::Text("source".into()));
|
||||
let filter = graph.add_node(operation, [100.0, 0.0]);
|
||||
graph.node_mut(filter).unwrap().params.insert("intensity".into(), Value::Float(if operation == "sharpen" { 1.0 } else { 16.0 }));
|
||||
graph.connect(input, "output", filter, "input").unwrap();
|
||||
let mut package = Package::new("Filter boundaries");
|
||||
package.graphs.push(graph);
|
||||
let resource = |_: &str| None;
|
||||
let mut options = Options::new(&resource);
|
||||
options.inputs.insert("source".into(), Image::gray(16, 16, |x, y| if x == 0 && y == 0 { 0.5625 } else { 0.5 }));
|
||||
let cache = Mutex::new(Cache::default());
|
||||
|
||||
for tiling in [[false, false], [true, false], [false, true], [true, true]] {
|
||||
package.graphs[0].tiling = tiling;
|
||||
|
||||
let cooked = cook(&package, 0, &options, &cache);
|
||||
let image = cooked.image(filter, 0).unwrap();
|
||||
|
||||
assert_eq!(cooked.nodes[&filter].error, None);
|
||||
assert!(!cooked.nodes[&filter].cached);
|
||||
assert_eq!(image.get_gray(15, 0, false) != 0.5, tiling[0], "{operation}, x, {tiling:?}");
|
||||
assert_eq!(image.get_gray(0, 15, false) != 0.5, tiling[1] && operation != "directional_blur", "{operation}, y, {tiling:?}");
|
||||
|
||||
let cached = cook(&package, 0, &options, &cache);
|
||||
|
||||
assert!(cached.nodes[&filter].cached);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -16,8 +16,7 @@ materialcraft-core = { workspace = true }
|
||||
craft-texture = { workspace = true }
|
||||
materialcraft-geom = { workspace = true }
|
||||
materialcraft-nodes = { workspace = true }
|
||||
gltf = { workspace = true }
|
||||
tobj = { workspace = true }
|
||||
craft-mesh = { workspace = true }
|
||||
image = { workspace = true }
|
||||
craft-texture-dds = { workspace = true }
|
||||
serde = { workspace = true }
|
||||
|
||||
+19
-2
@@ -1,4 +1,5 @@
|
||||
//! Bundle the same SBS library and original resources used by native disk installations.
|
||||
//! Bundle the same SBS library and original resources used by native disk installations. The
|
||||
//! browser build leaves `resources/` out and lists it for download instead.
|
||||
#![forbid(unsafe_code)]
|
||||
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
|
||||
|
||||
@@ -55,6 +56,16 @@ fn main() -> Result<()> {
|
||||
std::fs::create_dir_all(&compressed)?;
|
||||
let mut files = Vec::new();
|
||||
scan(&root, Path::new(""), &mut files)?;
|
||||
|
||||
// Keep already-compressed bitmaps out of the size-capped wasm
|
||||
// The browser downloads them from beside the wasm
|
||||
let browser = std::env::var("CARGO_CFG_TARGET_ARCH").is_ok_and(|arch| arch == "wasm32");
|
||||
let (downloaded, files): (Vec<_>, Vec<_>) = files.into_iter().partition(|relative| browser && relative.starts_with("resources"));
|
||||
let mut external = Vec::new();
|
||||
for relative in &downloaded {
|
||||
external.push(relative.to_str().ok_or("non-UTF-8 asset path")?.replace('\\', "/"));
|
||||
}
|
||||
external.sort();
|
||||
let mut files: Vec<_> = files.into_iter().map(|relative| (relative.clone(), root.join(relative))).collect();
|
||||
files.extend(sbs_font::assets()?);
|
||||
files.sort_by_key(|(relative, _)| relative.to_string_lossy().replace('\\', "/"));
|
||||
@@ -78,6 +89,12 @@ fn main() -> Result<()> {
|
||||
}
|
||||
assets.push_str("];\n");
|
||||
packages.push_str("];\n");
|
||||
std::fs::write(out.join("sbs_assets.rs"), format!("{assets}{packages}"))?;
|
||||
let mut downloads = String::from("const EXTERNAL_ASSETS: &[&str] = &[\n");
|
||||
for name in &external {
|
||||
downloads.push_str(&format!("{name:?},\n"));
|
||||
}
|
||||
downloads.push_str("];\n");
|
||||
std::fs::write(out.join("sbs_assets.rs"), format!("{assets}{packages}{downloads}"))?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
+346
-232
@@ -1,7 +1,8 @@
|
||||
//! Meshes for the 3D view: OBJ and glTF/GLB (self-contained: embedded or data-URI buffers),
|
||||
//! normalized to fit a unit sphere at the origin, with normals, tangents and (when the file has
|
||||
//! none) generated UVs.
|
||||
//! read with craft-mesh, placed by their node hierarchy, then normalized to fit a unit sphere at
|
||||
//! the origin, with normals, tangents and (when the file has none) generated UVs.
|
||||
|
||||
use craft_mesh::{Limits, Scene};
|
||||
use materialcraft_geom::Mesh;
|
||||
use materialcraft_geom::glam::{Vec2, Vec3};
|
||||
|
||||
@@ -16,59 +17,17 @@ const MAX_TRIANGLES: usize = 4_000_000;
|
||||
/// Largest mesh accepted (vertices).
|
||||
const MAX_VERTICES: usize = 3 * MAX_TRIANGLES;
|
||||
|
||||
/// What the readers may take from one file. Every attribute pool is bounded by the vertex limit
|
||||
/// and the file's faces by the triangle limit, before anything is allocated for them.
|
||||
fn limits() -> Limits {
|
||||
Limits { max_vertices: MAX_VERTICES, max_triangles: MAX_TRIANGLES, ..Limits::default() }
|
||||
}
|
||||
|
||||
fn check_vertex_bound(current: usize, added: usize) -> Result<()> {
|
||||
if current.checked_add(added).is_none_or(|total| total > MAX_VERTICES) {
|
||||
return Err(bad("the mesh is too large"));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Reject an OBJ whose raw attribute or face definitions exceed the bounds
|
||||
/// before the parser allocates storage for them. Unreferenced definitions
|
||||
/// never reach the parsed mesh, so counting parsed vertices alone cannot
|
||||
/// bound this input. First tokens are matched with `split_whitespace`, the
|
||||
/// same Unicode whitespace rules the OBJ parser uses.
|
||||
fn check_obj_vertex_bound(bytes: &[u8]) -> Result<()> {
|
||||
let mut vertices = 0usize;
|
||||
let mut texcoords = 0usize;
|
||||
let mut normals = 0usize;
|
||||
let mut face_corners = 0usize;
|
||||
for line in bytes.split(|b| *b == b'\n') {
|
||||
let Ok(line) = std::str::from_utf8(line) else { continue };
|
||||
let mut tokens = line.split_whitespace();
|
||||
match tokens.next() {
|
||||
Some("v") => {
|
||||
vertices = vertices.saturating_add(1);
|
||||
if vertices > MAX_VERTICES {
|
||||
return Err(bad("the mesh is too large"));
|
||||
}
|
||||
}
|
||||
Some("vt") => {
|
||||
texcoords = texcoords.saturating_add(1);
|
||||
if texcoords > MAX_VERTICES {
|
||||
return Err(bad("the mesh is too large"));
|
||||
}
|
||||
}
|
||||
Some("vn") => {
|
||||
normals = normals.saturating_add(1);
|
||||
if normals > MAX_VERTICES {
|
||||
return Err(bad("the mesh is too large"));
|
||||
}
|
||||
}
|
||||
Some("f") | Some("l") => {
|
||||
// A triangulated face with k corners yields k - 2 triangles, so
|
||||
// a mesh within the triangle limit has at most 3 * MAX_TRIANGLES
|
||||
// corners. Lines are expanded by the parser like faces, so
|
||||
// bounding their corners too bounds the vertices the parser
|
||||
// expands from distinct index combinations.
|
||||
face_corners = face_corners.saturating_add(tokens.count());
|
||||
if face_corners > 3 * MAX_TRIANGLES {
|
||||
return Err(bad("the mesh is too large"));
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -76,25 +35,12 @@ fn bad(msg: impl Into<String>) -> FormatError {
|
||||
FormatError::BadPackage(msg.into())
|
||||
}
|
||||
|
||||
/// Append the triangles of `ix` to `out`, offset by `base`. Whole triangles are dropped when any
|
||||
/// of their indices is `>= n` (or when a trailing partial triangle is left over), so the
|
||||
/// triangles that follow keep their vertices.
|
||||
fn push_triangles(out: &mut Vec<u32>, ix: impl IntoIterator<Item = u32>, n: usize, base: u32) -> Result<()> {
|
||||
append_triangles(out, ix, n, base, MAX_TRIANGLES)
|
||||
}
|
||||
|
||||
fn append_triangles(out: &mut Vec<u32>, ix: impl IntoIterator<Item = u32>, n: usize, base: u32, limit: usize) -> Result<()> {
|
||||
let mut ix = ix.into_iter();
|
||||
while let (Some(a), Some(b), Some(c)) = (ix.next(), ix.next(), ix.next()) {
|
||||
let t = [a, b, c];
|
||||
if t.iter().all(|i| (*i as usize) < n) {
|
||||
if out.len() / 3 >= limit {
|
||||
return Err(bad("the mesh is too large"));
|
||||
}
|
||||
out.extend(t.iter().map(|i| i.saturating_add(base)));
|
||||
}
|
||||
/// A reader error as the message the 3D view shows; every exceeded limit reads the same.
|
||||
fn read_error(kind: &str, e: craft_mesh::Error) -> FormatError {
|
||||
match e {
|
||||
craft_mesh::Error::TooLarge(_) => bad("the mesh is too large"),
|
||||
e => bad(format!("{kind}: {e}")),
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Build the mesh, rejecting non-finite positions, normals and UVs before anything computes
|
||||
@@ -103,137 +49,159 @@ fn finish(positions: Vec<Vec3>, normals: Option<Vec<Vec3>>, uvs: Vec<Vec2>, indi
|
||||
if positions.iter().any(|p| !p.is_finite()) {
|
||||
return Err(bad("the mesh has non-finite (NaN or infinite) positions"));
|
||||
}
|
||||
|
||||
if normals.iter().flatten().any(|n| !n.is_finite()) {
|
||||
return Err(bad("the mesh has non-finite (NaN or infinite) normals"));
|
||||
}
|
||||
|
||||
if uvs.iter().any(|u| !u.is_finite()) {
|
||||
return Err(bad("the mesh has non-finite (NaN or infinite) UVs"));
|
||||
}
|
||||
|
||||
Mesh::from_parts(positions, normals, uvs, indices, "material").map_err(|e| bad(e.to_string()))
|
||||
}
|
||||
|
||||
/// Parse a mesh file by extension.
|
||||
pub fn load_mesh(name: &str, bytes: &[u8]) -> Result<Mesh> {
|
||||
let ext = name.rsplit_once('.').map(|(_, e)| e.to_ascii_lowercase()).unwrap_or_default();
|
||||
let mut mesh = match ext.as_str() {
|
||||
"obj" => obj(bytes)?,
|
||||
"glb" | "gltf" => gltf(bytes)?,
|
||||
let extension = name.rsplit_once('.').map(|(_, e)| e.to_ascii_lowercase()).unwrap_or_default();
|
||||
let limits = limits();
|
||||
|
||||
// The view has no source folder for external file references
|
||||
let scene = match extension.as_str() {
|
||||
"obj" => craft_mesh::obj::read(bytes, &limits, &mut craft_mesh::no_external).map_err(|e| read_error("OBJ", e))?,
|
||||
"glb" | "gltf" => craft_mesh::gltf::read(bytes, &limits, &mut craft_mesh::no_external).map_err(|e| read_error("glTF", e))?,
|
||||
other => return Err(bad(format!("unsupported mesh format `{other}` (OBJ, glTF or GLB)"))),
|
||||
};
|
||||
let mut mesh = scene_mesh(&scene, &limits)?;
|
||||
if mesh.indices.is_empty() || mesh.positions.is_empty() {
|
||||
return Err(bad("the mesh has no triangles"));
|
||||
}
|
||||
|
||||
if mesh.triangle_count() > MAX_TRIANGLES {
|
||||
return Err(bad(format!("the mesh has {} triangles (limit {MAX_TRIANGLES})", mesh.triangle_count())));
|
||||
}
|
||||
|
||||
if mesh.uvs.len() != mesh.positions.len() || mesh.uvs.iter().all(|u| *u == mesh.uvs[0]) {
|
||||
// No usable UVs: a box projection keeps materials tiling across the surface.
|
||||
// No usable UVs: a box projection keeps materials tiling across the surface
|
||||
mesh.uvs = box_uvs(&mesh);
|
||||
}
|
||||
|
||||
mesh.normalize_to(1.0);
|
||||
if mesh.normals.len() != mesh.positions.len() {
|
||||
mesh.compute_normals();
|
||||
}
|
||||
|
||||
mesh.compute_tangents();
|
||||
mesh.validate().map_err(|e| bad(e.to_string()))?;
|
||||
|
||||
Ok(mesh)
|
||||
}
|
||||
|
||||
fn obj(bytes: &[u8]) -> Result<Mesh> {
|
||||
check_obj_vertex_bound(bytes)?;
|
||||
let mut reader = std::io::BufReader::new(bytes);
|
||||
let opts = tobj::LoadOptions { triangulate: true, single_index: true, ..Default::default() };
|
||||
let (models, _) = crate::guard(
|
||||
|| tobj::load_obj_buf(&mut reader, &opts, |_| Ok((Vec::new(), Default::default()))).map_err(|e| bad(format!("OBJ: {e}"))),
|
||||
|| bad("the OBJ parser failed on this file"),
|
||||
)?;
|
||||
let mut positions = Vec::new();
|
||||
let mut normals = Vec::new();
|
||||
let mut uvs = Vec::new();
|
||||
let mut indices = Vec::new();
|
||||
for m in models {
|
||||
let base = positions.len() as u32;
|
||||
let mesh = &m.mesh;
|
||||
let n = mesh.positions.len() / 3;
|
||||
check_vertex_bound(positions.len(), n)?;
|
||||
for i in 0..n {
|
||||
positions.push(Vec3::new(mesh.positions[i * 3], mesh.positions[i * 3 + 1], mesh.positions[i * 3 + 2]));
|
||||
if mesh.normals.len() == mesh.positions.len() {
|
||||
normals.push(Vec3::new(mesh.normals[i * 3], mesh.normals[i * 3 + 1], mesh.normals[i * 3 + 2]));
|
||||
}
|
||||
// OBJ UVs have their origin at the bottom left.
|
||||
uvs.push(mesh.texcoords.get(i * 2..i * 2 + 2).map_or(Vec2::ZERO, |t| Vec2::new(t[0], 1.0 - t[1])));
|
||||
}
|
||||
push_triangles(&mut indices, mesh.indices.iter().copied(), n, base)?;
|
||||
if indices.len() / 3 > MAX_TRIANGLES {
|
||||
return Err(bad("the mesh is too large"));
|
||||
}
|
||||
/// Whether any value the file stored for a vertex is NaN or infinite. The reader drops the
|
||||
/// triangles that reach a non-finite position; the view rejects the whole file instead, so a
|
||||
/// damaged mesh is reported rather than shown with holes.
|
||||
fn non_finite(scene: &Scene) -> Option<&'static str> {
|
||||
let f64s = |v: &[[f64; 3]]| v.iter().flatten().any(|x| !x.is_finite());
|
||||
if scene.meshes.iter().any(|mesh| f64s(&mesh.positions)) {
|
||||
return Some("positions");
|
||||
}
|
||||
let normals = (normals.len() == positions.len()).then_some(normals);
|
||||
finish(positions, normals, uvs, indices)
|
||||
|
||||
if scene.meshes.iter().any(|mesh| f64s(&mesh.normals)) {
|
||||
return Some("normals");
|
||||
}
|
||||
|
||||
if scene.meshes.iter().flat_map(|mesh| mesh.uv_sets.first()).any(|s| s.iter().flatten().any(|x| !x.is_finite())) {
|
||||
return Some("UVs");
|
||||
}
|
||||
|
||||
None
|
||||
}
|
||||
|
||||
fn gltf(bytes: &[u8]) -> Result<Mesh> {
|
||||
let (doc, buffers, _) = crate::guard(|| gltf::import_slice(bytes).map_err(|e| bad(format!("glTF: {e}"))), || bad("the glTF parser failed on this file"))?;
|
||||
let mut positions = Vec::new();
|
||||
/// One triangle mesh of every placed mesh in the scene. Positions are transformed into world
|
||||
/// space in `f64`, then centered and scaled to a unit-size box before conversion to `f32`, so a
|
||||
/// placement far from the origin keeps its shape; [`load_mesh`] then normalizes to a unit sphere.
|
||||
/// Normals and UVs are kept only when every placed mesh has them (otherwise [`load_mesh`]
|
||||
/// computes normals and projects UVs for the whole mesh); the first UV set is used. Normals go
|
||||
/// through the inverse transpose, and a mirrored placement has its winding reversed so its
|
||||
/// triangles keep facing out.
|
||||
fn scene_mesh(scene: &Scene, limits: &Limits) -> Result<Mesh> {
|
||||
if let Some(what) = non_finite(scene) {
|
||||
return Err(bad(format!("the mesh has non-finite (NaN or infinite) {what}")));
|
||||
}
|
||||
|
||||
let instances = scene.instances(limits).map_err(|e| read_error("mesh", e))?;
|
||||
let mut world_positions = Vec::new();
|
||||
let mut normals = Vec::new();
|
||||
let mut uvs = Vec::new();
|
||||
let mut indices = Vec::new();
|
||||
let mut all_normals = true;
|
||||
for node in doc.nodes() {
|
||||
let Some(mesh) = node.mesh() else { continue };
|
||||
let m = materialcraft_geom::glam::Mat4::from_cols_array_2d(&node.transform().matrix());
|
||||
for prim in mesh.primitives() {
|
||||
if prim.mode() != gltf::mesh::Mode::Triangles {
|
||||
continue;
|
||||
}
|
||||
let reader = prim.reader(|b| buffers.get(b.index()).map(|d| d.0.as_slice()));
|
||||
let Some(pos) = reader.read_positions() else { continue };
|
||||
let base = positions.len() as u32;
|
||||
let pos_it = pos.map(|p| m.transform_point3(Vec3::from(p)));
|
||||
let n = pos_it.len();
|
||||
check_vertex_bound(positions.len(), n)?;
|
||||
let pos: Vec<Vec3> = pos_it.collect();
|
||||
match reader.read_normals() {
|
||||
Some(ns) => {
|
||||
for q in ns {
|
||||
if normals.len() >= MAX_VERTICES {
|
||||
return Err(bad("the mesh is too large"));
|
||||
}
|
||||
let v = m.transform_vector3(Vec3::from(q));
|
||||
if !v.is_finite() {
|
||||
return Err(bad("the mesh has non-finite (NaN or infinite) normals"));
|
||||
}
|
||||
normals.push(v.normalize_or_zero());
|
||||
}
|
||||
}
|
||||
None => all_normals = false,
|
||||
}
|
||||
match reader.read_tex_coords(0) {
|
||||
Some(t) => {
|
||||
for uv in t.into_f32() {
|
||||
if uvs.len() >= MAX_VERTICES {
|
||||
return Err(bad("the mesh is too large"));
|
||||
}
|
||||
uvs.push(Vec2::from(uv));
|
||||
}
|
||||
}
|
||||
None => uvs.extend(std::iter::repeat_n(Vec2::ZERO, n)),
|
||||
}
|
||||
match reader.read_indices() {
|
||||
Some(ix) => push_triangles(&mut indices, ix.into_u32(), n, base)?,
|
||||
None => push_triangles(&mut indices, 0..n as u32, n, base)?,
|
||||
}
|
||||
positions.extend(pos);
|
||||
if indices.len() / 3 > MAX_TRIANGLES {
|
||||
let mut all_uvs = true;
|
||||
for (index, world) in instances {
|
||||
let Some(mesh) = scene.meshes.get(index) else { continue };
|
||||
let unified = mesh.unified();
|
||||
let vertex_count = unified.positions.len();
|
||||
check_vertex_bound(world_positions.len(), vertex_count)?;
|
||||
let Ok(base) = u32::try_from(world_positions.len()) else { return Err(bad("the mesh is too large")) };
|
||||
world_positions.extend(unified.positions.iter().map(|p| craft_mesh::transform_point(&world, *p)));
|
||||
if unified.normals.len() == vertex_count {
|
||||
normals.extend(unified.normals.iter().map(|q| to_vec3(craft_mesh::transform_normal(&world, *q))));
|
||||
} else {
|
||||
all_normals = false;
|
||||
}
|
||||
if unified.uvs.len() == vertex_count {
|
||||
uvs.extend(unified.uvs.iter().map(|t| Vec2::from(*t)));
|
||||
} else {
|
||||
all_uvs = false;
|
||||
}
|
||||
let mirror = craft_mesh::is_mirror(&world);
|
||||
for tri in unified.parts.iter().flatten() {
|
||||
if indices.len() / 3 >= MAX_TRIANGLES {
|
||||
return Err(bad("the mesh is too large"));
|
||||
}
|
||||
|
||||
let [a, b, c] = tri.map(|i| i.saturating_add(base));
|
||||
indices.extend(if mirror { [a, c, b] } else { [a, b, c] });
|
||||
}
|
||||
}
|
||||
|
||||
let positions = to_f32_positions(&world_positions);
|
||||
let normals = (all_normals && normals.len() == positions.len()).then_some(normals);
|
||||
|
||||
// Partial UVs would hide the gap from the projection fallback: drop them all instead
|
||||
if !all_uvs || uvs.len() != positions.len() {
|
||||
uvs.clear();
|
||||
}
|
||||
|
||||
finish(positions, normals, uvs, indices)
|
||||
}
|
||||
|
||||
/// Center and scale world-space positions in `f64`, then convert to `f32`. A unit quad whose
|
||||
/// node sits at a large translation would otherwise collapse: at magnitude `2^25` the `f32`
|
||||
/// spacing is 4, so the four corners round to one point and [`Mesh::normalize_to`] cannot
|
||||
/// recover the shape.
|
||||
fn to_f32_positions(world: &[[f64; 3]]) -> Vec<Vec3> {
|
||||
if world.is_empty() {
|
||||
return Vec::new();
|
||||
}
|
||||
|
||||
let mut lo = [f64::INFINITY; 3];
|
||||
let mut hi = [f64::NEG_INFINITY; 3];
|
||||
for p in world {
|
||||
for (i, &x) in p.iter().enumerate() {
|
||||
lo[i] = lo[i].min(x);
|
||||
hi[i] = hi[i].max(x);
|
||||
}
|
||||
}
|
||||
let center = [0, 1, 2].map(|i| (lo[i] + hi[i]) * 0.5);
|
||||
let extent = hi.iter().zip(&lo).map(|(h, l)| h - l).fold(0.0, f64::max);
|
||||
let scale = if extent.is_finite() && extent > 0.0 { 1.0 / extent } else { 1.0 };
|
||||
world.iter().map(|p| to_vec3([(p[0] - center[0]) * scale, (p[1] - center[1]) * scale, (p[2] - center[2]) * scale])).collect()
|
||||
}
|
||||
|
||||
fn to_vec3(p: [f64; 3]) -> Vec3 {
|
||||
Vec3::new(p[0] as f32, p[1] as f32, p[2] as f32)
|
||||
}
|
||||
|
||||
/// Box-projected UVs: each vertex takes the plane of its normal's largest axis.
|
||||
fn box_uvs(mesh: &Mesh) -> Vec<Vec2> {
|
||||
let (lo, hi) = mesh.bounds();
|
||||
@@ -262,61 +230,51 @@ mod tests {
|
||||
#[test]
|
||||
fn obj_quad_loads_with_uvs_and_tangents() {
|
||||
let obj = b"v 0 0 0\nv 1 0 0\nv 1 1 0\nv 0 1 0\nvt 0 0\nvt 1 0\nvt 1 1\nvt 0 1\nf 1/1 2/2 3/3 4/4\n";
|
||||
let m = load_mesh("quad.obj", obj).unwrap();
|
||||
assert_eq!(m.triangle_count(), 2);
|
||||
assert_eq!(m.tangents.len(), m.positions.len());
|
||||
assert!(m.radius() <= 1.0 + 1e-4);
|
||||
// A mesh without UVs gets projected ones.
|
||||
let m = load_mesh("tri.obj", b"v 0 0 0\nv 1 0 0\nv 0 1 0\nf 1 2 3\n").unwrap();
|
||||
assert!(m.uvs.iter().any(|u| *u != m.uvs[0]));
|
||||
let mesh = load_mesh("quad.obj", obj).unwrap();
|
||||
|
||||
assert_eq!(mesh.triangle_count(), 2);
|
||||
assert_eq!(mesh.tangents.len(), mesh.positions.len());
|
||||
assert!(mesh.radius() <= 1.0 + 1e-4);
|
||||
|
||||
// A mesh without UVs gets projected ones
|
||||
let mesh = load_mesh("tri.obj", b"v 0 0 0\nv 1 0 0\nv 0 1 0\nf 1 2 3\n").unwrap();
|
||||
|
||||
assert!(mesh.uvs.iter().any(|u| *u != mesh.uvs[0]));
|
||||
}
|
||||
|
||||
/// A glTF with 4 vertices (positions given by `pos`, optional UVs) and the given indices.
|
||||
fn gltf_json(pos: [[f32; 3]; 4], uvs: Option<[[f32; 2]; 4]>, idx: &[u16]) -> Vec<u8> {
|
||||
/// A glTF with 4 vertices (positions given by `positions`, optional UVs) and the given indices.
|
||||
fn gltf_json(positions: [[f32; 3]; 4], uvs: Option<[[f32; 2]; 4]>, indices: &[u16]) -> Vec<u8> {
|
||||
use base64::Engine as _;
|
||||
let mut buf: Vec<u8> = pos.iter().flatten().flat_map(|f| f.to_le_bytes()).collect();
|
||||
let uv_off = buf.len();
|
||||
let mut buffer: Vec<u8> = positions.iter().flatten().flat_map(|f| f.to_le_bytes()).collect();
|
||||
let uv_offset_bytes = buffer.len();
|
||||
if let Some(uvs) = uvs {
|
||||
buf.extend(uvs.iter().flatten().flat_map(|f| f.to_le_bytes()));
|
||||
buffer.extend(uvs.iter().flatten().flat_map(|f| f.to_le_bytes()));
|
||||
}
|
||||
let idx_off = buf.len();
|
||||
buf.extend(idx.iter().flat_map(|i| i.to_le_bytes()));
|
||||
let b64 = base64::engine::general_purpose::STANDARD.encode(&buf);
|
||||
let index_offset_bytes = buffer.len();
|
||||
buffer.extend(indices.iter().flat_map(|i| i.to_le_bytes()));
|
||||
let encoded_buffer = base64::engine::general_purpose::STANDARD.encode(&buffer);
|
||||
let uv_attr = if uvs.is_some() { r#","TEXCOORD_0":1"# } else { "" };
|
||||
let uv_view = if uvs.is_some() { format!(r#"{{"buffer":0,"byteOffset":{uv_off},"byteLength":32}},"#) } else { String::new() };
|
||||
let uv_view = if uvs.is_some() { format!(r#"{{"buffer":0,"byteOffset":{uv_offset_bytes},"byteLength":32}},"#) } else { String::new() };
|
||||
let uv_acc = if uvs.is_some() { r#"{"bufferView":1,"componentType":5126,"count":4,"type":"VEC2"},"# } else { "" };
|
||||
// View/accessor layout: with UVs, views are [pos, uv, idx] and accessors [pos, uv, idx].
|
||||
|
||||
// View/accessor layout: with UVs, views are [positions, uv, indices] and accessors [positions, uv, indices]
|
||||
let idx_view = if uvs.is_some() { 2 } else { 1 };
|
||||
let idx_acc = if uvs.is_some() { 2 } else { 1 };
|
||||
format!(
|
||||
r#"{{"asset":{{"version":"2.0"}},"scene":0,"scenes":[{{"nodes":[0]}}],"nodes":[{{"mesh":0}}],
|
||||
"meshes":[{{"primitives":[{{"attributes":{{"POSITION":0{uv_attr}}},"indices":{idx_acc}}}]}}],
|
||||
"accessors":[{{"bufferView":0,"componentType":5126,"count":4,"type":"VEC3","min":[-1e9,-1e9,-1e9],"max":[1e9,1e9,1e9]}},{uv_acc}{{"bufferView":{idx_view},"componentType":5123,"count":{},"type":"SCALAR"}}],
|
||||
"bufferViews":[{{"buffer":0,"byteOffset":0,"byteLength":48}},{uv_view}{{"buffer":0,"byteOffset":{idx_off},"byteLength":{}}}],
|
||||
"buffers":[{{"byteLength":{},"uri":"data:application/octet-stream;base64,{b64}"}}]}}"#,
|
||||
idx.len(),
|
||||
idx.len() * 2,
|
||||
buf.len()
|
||||
"bufferViews":[{{"buffer":0,"byteOffset":0,"byteLength":48}},{uv_view}{{"buffer":0,"byteOffset":{index_offset_bytes},"byteLength":{}}}],
|
||||
"buffers":[{{"byteLength":{},"uri":"data:application/octet-stream;base64,{encoded_buffer}"}}]}}"#,
|
||||
indices.len(),
|
||||
indices.len() * 2,
|
||||
buffer.len()
|
||||
)
|
||||
.into_bytes()
|
||||
}
|
||||
|
||||
const QUAD: [[f32; 3]; 4] = [[0.0, 0.0, 0.0], [1.0, 0.0, 0.0], [1.0, 1.0, 0.0], [0.0, 1.0, 0.0]];
|
||||
|
||||
#[test]
|
||||
fn triangle_limit_stops_a_stream_before_collecting_the_rest() {
|
||||
let mut out = Vec::new();
|
||||
let mut read = 0;
|
||||
let indices = std::iter::from_fn(|| {
|
||||
read += 1;
|
||||
assert!(read <= 6, "read beyond the first triangle over the limit");
|
||||
Some(0)
|
||||
});
|
||||
assert!(append_triangles(&mut out, indices, 1, 0, 1).is_err());
|
||||
assert_eq!(out, [0, 0, 0]);
|
||||
assert_eq!(read, 6);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn obj_with_excess_vertices_is_rejected() {
|
||||
let mut obj = String::from("v 0 0 0\nv 1 0 0\nv 0 1 0\n");
|
||||
@@ -326,80 +284,168 @@ mod tests {
|
||||
obj.push_str("f 1 2 3\n");
|
||||
|
||||
let e = load_mesh("excess.obj", obj.as_bytes()).unwrap_err();
|
||||
|
||||
assert!(matches!(&e, FormatError::BadPackage(msg) if msg == "the mesh is too large"), "{e:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn gltf_with_excess_vertices_is_rejected() {
|
||||
fn gltf_primitives_sharing_a_large_accessor_stay_bounded() {
|
||||
use base64::Engine as _;
|
||||
// One position accessor of 100_000 vertices, referenced by 121
|
||||
// primitives: the cumulative count exceeds MAX_VERTICES on the
|
||||
// last primitive, while the single indexed triangle per primitive
|
||||
// stays far below the triangle limit.
|
||||
|
||||
// Shared accessors must count only vertices used by triangles
|
||||
const COUNT: usize = 100_000;
|
||||
let mut buf = vec![0u8; COUNT * 12];
|
||||
// Give the referenced triangle non-degenerate positions.
|
||||
let mut buffer = vec![0u8; COUNT * 12];
|
||||
|
||||
// Give the referenced triangle non-degenerate positions
|
||||
for (i, v) in [[0.0f32, 0.0, 0.0], [1.0, 0.0, 0.0], [0.0, 1.0, 0.0]].iter().enumerate() {
|
||||
buf[i * 12..i * 12 + 12].copy_from_slice(&v.iter().flat_map(|f| f.to_le_bytes()).collect::<Vec<_>>());
|
||||
buffer[i * 12..i * 12 + 12].copy_from_slice(&v.iter().flat_map(|f| f.to_le_bytes()).collect::<Vec<_>>());
|
||||
}
|
||||
buf.extend([0u16, 1, 2].iter().flat_map(|i| i.to_le_bytes()));
|
||||
let b64 = base64::engine::general_purpose::STANDARD.encode(&buf);
|
||||
let prim = r#"{"attributes":{"POSITION":0},"indices":1}"#;
|
||||
let prims = (0..121).map(|_| prim).collect::<Vec<_>>().join(",");
|
||||
buffer.extend([0u16, 1, 2].iter().flat_map(|i| i.to_le_bytes()));
|
||||
let encoded_buffer = base64::engine::general_purpose::STANDARD.encode(&buffer);
|
||||
let primitive = r#"{"attributes":{"POSITION":0},"indices":1}"#;
|
||||
let primitives = (0..121).map(|_| primitive).collect::<Vec<_>>().join(",");
|
||||
let gltf = format!(
|
||||
r#"{{"asset":{{"version":"2.0"}},"scene":0,"scenes":[{{"nodes":[0]}}],"nodes":[{{"mesh":0}}],
|
||||
"meshes":[{{"primitives":[{prims}]}}],
|
||||
"meshes":[{{"primitives":[{primitives}]}}],
|
||||
"accessors":[{{"bufferView":0,"componentType":5126,"count":{COUNT},"type":"VEC3","min":[0.0,0.0,0.0],"max":[1.0,1.0,0.0]}},{{"bufferView":1,"componentType":5123,"count":3,"type":"SCALAR"}}],
|
||||
"bufferViews":[{{"buffer":0,"byteOffset":0,"byteLength":{}}},{{"buffer":0,"byteOffset":{},"byteLength":6}}],
|
||||
"buffers":[{{"byteLength":{},"uri":"data:application/octet-stream;base64,{b64}"}}]}}"#,
|
||||
"buffers":[{{"byteLength":{},"uri":"data:application/octet-stream;base64,{encoded_buffer}"}}]}}"#,
|
||||
COUNT * 12,
|
||||
COUNT * 12,
|
||||
buf.len()
|
||||
buffer.len()
|
||||
);
|
||||
let e = load_mesh("excess.gltf", gltf.as_bytes()).unwrap_err();
|
||||
assert!(matches!(&e, FormatError::BadPackage(msg) if msg == "the mesh is too large"), "{e:?}");
|
||||
let mesh = load_mesh("shared.gltf", gltf.as_bytes()).unwrap();
|
||||
|
||||
assert_eq!(mesh.positions.len(), 3);
|
||||
assert_eq!(mesh.triangle_count(), 121);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn obj_non_finite_normals_are_rejected() {
|
||||
assert!(load_mesh("x.obj", b"v 0 0 0\nv 1 0 0\nv 0 1 0\nvn nan 0 1\nf 1//1 2//1 3//1\n").is_err());
|
||||
fn obj_non_finite_normals_and_uvs_never_reach_the_mesh() {
|
||||
// Dropped invalid OBJ attributes are replaced with finite fallbacks
|
||||
for obj in
|
||||
[&b"v 0 0 0\nv 1 0 0\nv 0 1 0\nvn nan 0 1\nf 1//1 2//1 3//1\n"[..], &b"v 0 0 0\nv 1 0 0\nv 0 1 0\nvt nan 0\nvt 1 0\nvt 0 1\nf 1/1 2/2 3/3\n"[..]]
|
||||
{
|
||||
let mesh = load_mesh("x.obj", obj).unwrap();
|
||||
|
||||
assert!(mesh.normals.iter().all(|n| n.is_finite()) && mesh.uvs.iter().all(|u| u.is_finite()), "{mesh:?}");
|
||||
}
|
||||
|
||||
// A triangle on a NaN position is dropped; with nothing left the file is refused
|
||||
assert!(load_mesh("x.obj", b"v 0 0 0\nv 1 0 0\nv nan 1 0\nf 1 2 3\n").is_err());
|
||||
}
|
||||
|
||||
/// [`QUAD`] with the given vertex normals, placed by one node.
|
||||
fn gltf_with_normals(normals: [[f32; 3]; 4]) -> Vec<u8> {
|
||||
use base64::Engine as _;
|
||||
let indices: [u16; 6] = [0, 1, 2, 0, 2, 3];
|
||||
let mut buffer: Vec<u8> = QUAD.iter().flatten().flat_map(|f| f.to_le_bytes()).collect();
|
||||
buffer.extend(normals.iter().flatten().flat_map(|f| f.to_le_bytes()));
|
||||
buffer.extend(indices.iter().flat_map(|i| i.to_le_bytes()));
|
||||
let encoded_buffer = base64::engine::general_purpose::STANDARD.encode(&buffer);
|
||||
format!(
|
||||
r#"{{"asset":{{"version":"2.0"}},"scene":0,"scenes":[{{"nodes":[0]}}],"nodes":[{{"mesh":0}}],
|
||||
"meshes":[{{"primitives":[{{"attributes":{{"POSITION":0,"NORMAL":1}},"indices":2}}]}}],
|
||||
"accessors":[{{"bufferView":0,"componentType":5126,"count":4,"type":"VEC3","min":[-1e9,-1e9,-1e9],"max":[1e9,1e9,1e9]}},{{"bufferView":1,"componentType":5126,"count":4,"type":"VEC3"}},{{"bufferView":2,"componentType":5123,"count":6,"type":"SCALAR"}}],
|
||||
"bufferViews":[{{"buffer":0,"byteOffset":0,"byteLength":48}},{{"buffer":0,"byteOffset":48,"byteLength":48}},{{"buffer":0,"byteOffset":96,"byteLength":12}}],
|
||||
"buffers":[{{"byteLength":{},"uri":"data:application/octet-stream;base64,{encoded_buffer}"}}]}}"#,
|
||||
buffer.len()
|
||||
)
|
||||
.into_bytes()
|
||||
}
|
||||
|
||||
/// `gltf` with its one placing node replaced by `node`.
|
||||
fn placed(gltf: Vec<u8>, node: &str) -> Vec<u8> {
|
||||
let base = String::from_utf8(gltf).unwrap();
|
||||
let out = base.replace(r#""nodes":[{"mesh":0}]"#, &format!(r#""nodes":[{node}]"#));
|
||||
|
||||
assert_ne!(base, out, "the node was not replaced");
|
||||
out.into_bytes()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn gltf_non_finite_normals_are_rejected() {
|
||||
use base64::Engine as _;
|
||||
let gltf_with_normals = |normals: [[f32; 3]; 4]| {
|
||||
let idx: [u16; 6] = [0, 1, 2, 0, 2, 3];
|
||||
let mut buf: Vec<u8> = QUAD.iter().flatten().flat_map(|f| f.to_le_bytes()).collect();
|
||||
buf.extend(normals.iter().flatten().flat_map(|f| f.to_le_bytes()));
|
||||
buf.extend(idx.iter().flat_map(|i| i.to_le_bytes()));
|
||||
let b64 = base64::engine::general_purpose::STANDARD.encode(&buf);
|
||||
format!(
|
||||
r#"{{"asset":{{"version":"2.0"}},"scene":0,"scenes":[{{"nodes":[0]}}],"nodes":[{{"mesh":0}}],
|
||||
"meshes":[{{"primitives":[{{"attributes":{{"POSITION":0,"NORMAL":1}},"indices":2}}]}}],
|
||||
"accessors":[{{"bufferView":0,"componentType":5126,"count":4,"type":"VEC3","min":[-1e9,-1e9,-1e9],"max":[1e9,1e9,1e9]}},{{"bufferView":1,"componentType":5126,"count":4,"type":"VEC3"}},{{"bufferView":2,"componentType":5123,"count":6,"type":"SCALAR"}}],
|
||||
"bufferViews":[{{"buffer":0,"byteOffset":0,"byteLength":48}},{{"buffer":0,"byteOffset":48,"byteLength":48}},{{"buffer":0,"byteOffset":96,"byteLength":12}}],
|
||||
"buffers":[{{"byteLength":{},"uri":"data:application/octet-stream;base64,{b64}"}}]}}"#,
|
||||
buf.len()
|
||||
)
|
||||
.into_bytes()
|
||||
};
|
||||
let mut nan_normals = [[0.0f32, 0.0, 1.0]; 4];
|
||||
nan_normals[2][0] = f32::NAN;
|
||||
|
||||
assert!(load_mesh("x.gltf", &gltf_with_normals(nan_normals)).is_err());
|
||||
|
||||
let mut inf_normals = [[0.0f32, 0.0, 1.0]; 4];
|
||||
inf_normals[1][2] = f32::INFINITY;
|
||||
|
||||
assert!(load_mesh("x.gltf", &gltf_with_normals(inf_normals)).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_far_translation_keeps_the_quads_shape() {
|
||||
// At 2^25, f32 conversion before centering would collapse the unit quad
|
||||
let local = load_mesh("quad.gltf", &gltf_json(QUAD, None, &[0, 1, 2, 0, 2, 3])).unwrap();
|
||||
let far = 33_554_432.0;
|
||||
let placed = placed(gltf_json(QUAD, None, &[0, 1, 2, 0, 2, 3]), &format!(r#"{{"mesh":0,"translation":[{far},{far},0]}}"#));
|
||||
let distant = load_mesh("far.gltf", &placed).unwrap();
|
||||
|
||||
let local_extent = extent(&local);
|
||||
let distant_extent = extent(&distant);
|
||||
|
||||
assert_eq!(distant.triangle_count(), local.triangle_count());
|
||||
assert!((distant_extent - local_extent).length() < 1e-4, "local={local_extent} far={distant_extent}");
|
||||
for (a, b) in local.positions.iter().zip(&distant.positions) {
|
||||
assert!(a.distance(*b) < 1e-4, "local={a} far={b}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn normals_follow_a_non_uniform_scale_by_the_inverse_transpose() {
|
||||
// Stretched twice along x, a (1,1,0) normal leans towards y: (0.5,1,0), normalised
|
||||
let gltf = placed(gltf_with_normals([[1.0, 1.0, 0.0]; 4]), r#"{"mesh":0,"scale":[2,1,1]}"#);
|
||||
let mesh = load_mesh("x.gltf", &gltf).unwrap();
|
||||
let want = Vec3::new(0.5, 1.0, 0.0).normalize();
|
||||
|
||||
assert!(mesh.normals.iter().all(|n| n.distance(want) < 1e-5), "{:?}", mesh.normals);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_mirrored_placement_keeps_its_triangles_facing_out() {
|
||||
let gltf = placed(gltf_with_normals([[0.0, 0.0, 1.0]; 4]), r#"{"mesh":0,"scale":[-1,1,1]}"#);
|
||||
let mesh = load_mesh("x.gltf", &gltf).unwrap();
|
||||
for tri in mesh.indices.chunks(3) {
|
||||
let [a, b, c] = [0, 1, 2].map(|k| mesh.positions[tri[k] as usize]);
|
||||
let face = (b - a).cross(c - a);
|
||||
|
||||
assert!(face.dot(mesh.normals[tri[0] as usize]) > 0.0, "triangle {tri:?} faces in");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_placed_mesh_without_uvs_still_gets_projected_ones() {
|
||||
// Two meshes: one with varied UVs, one with none, side by side
|
||||
let uvs = [[0.0f32, 0.0], [1.0, 0.0], [1.0, 1.0], [0.0, 1.0]];
|
||||
let base = String::from_utf8(gltf_json(QUAD, Some(uvs), &[0, 1, 2, 0, 2, 3])).unwrap();
|
||||
let with = r#""meshes":[{"primitives":[{"attributes":{"POSITION":0,"TEXCOORD_0":1},"indices":2}]}]"#;
|
||||
|
||||
assert!(base.contains(with));
|
||||
|
||||
let two = base
|
||||
.replace(with, r#""meshes":[{"primitives":[{"attributes":{"POSITION":0,"TEXCOORD_0":1},"indices":2}]},{"primitives":[{"attributes":{"POSITION":0},"indices":2}]}]"#)
|
||||
.replace(r#""scenes":[{"nodes":[0]}],"nodes":[{"mesh":0}]"#, r#""scenes":[{"nodes":[0,1]}],"nodes":[{"mesh":0},{"mesh":1,"translation":[2,0,0]}]"#);
|
||||
let mesh = load_mesh("two.gltf", two.as_bytes()).unwrap();
|
||||
|
||||
assert_eq!(mesh.positions.len(), 8);
|
||||
let second = &mesh.uvs[4..];
|
||||
assert!(second.iter().any(|u| *u != second[0]), "the mesh without UVs got one constant UV: {second:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_bad_index_drops_its_whole_triangle_and_later_ones_keep_their_vertices() {
|
||||
// Triangles: (0,1,2), (0,1,9) out of range, (0,2,3).
|
||||
let m = load_mesh("x.gltf", &gltf_json(QUAD, None, &[0, 1, 2, 0, 1, 9, 0, 2, 3])).unwrap();
|
||||
assert_eq!(m.indices, vec![0, 1, 2, 0, 2, 3]);
|
||||
// An index count that is not a multiple of 3 drops only the partial triangle.
|
||||
let m = load_mesh("x.gltf", &gltf_json(QUAD, None, &[0, 1, 2, 0, 2, 3, 1, 2])).unwrap();
|
||||
assert_eq!(m.indices, vec![0, 1, 2, 0, 2, 3]);
|
||||
// Triangles: (0,1,2), (0,1,9) out of range, (0,2,3)
|
||||
let mesh = load_mesh("x.gltf", &gltf_json(QUAD, None, &[0, 1, 2, 0, 1, 9, 0, 2, 3])).unwrap();
|
||||
|
||||
assert_eq!(mesh.indices, vec![0, 1, 2, 0, 2, 3]);
|
||||
|
||||
// An index count that is not a multiple of 3 drops only the partial triangle
|
||||
let mesh = load_mesh("x.gltf", &gltf_json(QUAD, None, &[0, 1, 2, 0, 2, 3, 1, 2])).unwrap();
|
||||
|
||||
assert_eq!(mesh.indices, vec![0, 1, 2, 0, 2, 3]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -407,12 +453,14 @@ mod tests {
|
||||
let mut nan_pos = QUAD;
|
||||
nan_pos[2][0] = f32::NAN;
|
||||
let e = load_mesh("x.gltf", &gltf_json(nan_pos, None, &[0, 1, 2, 0, 2, 3])).unwrap_err();
|
||||
|
||||
assert!(e.to_string().contains("non-finite"), "{e}");
|
||||
|
||||
let mut nan_uv = [[0.0f32, 0.0], [1.0, 0.0], [1.0, 1.0], [0.0, 1.0]];
|
||||
nan_uv[1][1] = f32::NAN;
|
||||
let e = load_mesh("x.gltf", &gltf_json(QUAD, Some(nan_uv), &[0, 1, 2, 0, 2, 3])).unwrap_err();
|
||||
|
||||
assert!(e.to_string().contains("non-finite"), "{e}");
|
||||
assert!(load_mesh("x.obj", b"v 0 0 0\nv 1 0 0\nv 0 1 0\nvt nan 0\nvt 1 0\nvt 0 1\nf 1/1 2/2 3/3\n").is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -423,6 +471,72 @@ mod tests {
|
||||
assert!(load_mesh("x.obj", b"v 0 0 0\nf 1 2 3\n").is_err());
|
||||
}
|
||||
|
||||
/// [`gltf_json`]'s quad with its scene's root nodes and node list replaced.
|
||||
fn gltf_with_nodes(roots: &str, nodes: &str) -> Vec<u8> {
|
||||
let base = String::from_utf8(gltf_json(QUAD, None, &[0, 1, 2, 0, 2, 3])).unwrap();
|
||||
let placed = base.replace(r#""scenes":[{"nodes":[0]}],"nodes":[{"mesh":0}]"#, &format!(r#""scenes":[{{"nodes":{roots}}}],"nodes":{nodes}"#));
|
||||
|
||||
assert_ne!(base, placed, "the node list was not replaced");
|
||||
placed.into_bytes()
|
||||
}
|
||||
|
||||
fn extent(mesh: &Mesh) -> Vec3 {
|
||||
let (lo, hi) = mesh.bounds();
|
||||
hi - lo
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn gltf_meshes_take_their_parent_nodes_transforms() {
|
||||
// The quad sits under a parent that stretches it three times taller
|
||||
let nested = gltf_with_nodes("[0]", r#"[{"scale":[1,3,1],"children":[1]},{"mesh":0}]"#);
|
||||
let mesh = load_mesh("nested.gltf", &nested).unwrap();
|
||||
let size = extent(&mesh);
|
||||
|
||||
assert!((size.y / size.x - 3.0).abs() < 1e-4, "{size}");
|
||||
|
||||
// A mesh placed twice is drawn twice
|
||||
let twice = gltf_with_nodes("[0,1]", r#"[{"mesh":0},{"mesh":0,"translation":[5,0,0]}]"#);
|
||||
|
||||
assert_eq!(load_mesh("twice.gltf", &twice).unwrap().triangle_count(), 4);
|
||||
|
||||
// Nodes outside the scene are not drawn
|
||||
let unplaced = gltf_with_nodes("[0]", r#"[{"mesh":0},{"mesh":0,"translation":[5,0,0]}]"#);
|
||||
|
||||
assert_eq!(load_mesh("one.gltf", &unplaced).unwrap().triangle_count(), 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn glb_container_loads() {
|
||||
let json = String::from_utf8(gltf_json(QUAD, None, &[0, 1, 2, 0, 2, 3])).unwrap();
|
||||
let glb = craft_mesh::gltf::glb_container(json.as_bytes(), &[]).unwrap();
|
||||
|
||||
assert_eq!(load_mesh("quad.GLB", &glb).unwrap().triangle_count(), 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn obj_polygons_split_corners_and_material_libraries() {
|
||||
// Missing material libraries must not discard usable UVs
|
||||
let obj = b"mtllib missing.mtl\nv 0 0 0\nv 1 0 0\nv 1.5 1 0\nv 0.5 2 0\nv -0.5 1 0\nvt 0 0\nvt 1 0\nvt 1 1\nvt 0.5 1\nvt 0 1\nusemtl paint\nf 1/1 2/2 3/3 4/4 5/5\n";
|
||||
let mesh = load_mesh("penta.obj", obj).unwrap();
|
||||
|
||||
assert_eq!(mesh.triangle_count(), 3);
|
||||
|
||||
// OBJ stores v up; the view uses v down
|
||||
assert!(mesh.uvs.iter().any(|u| (u.y - 1.0).abs() < 1e-6));
|
||||
assert!(mesh.uvs.iter().any(|u| u.y.abs() < 1e-6));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reader_errors_read_as_the_views_messages() {
|
||||
let e = read_error("OBJ", craft_mesh::Error::TooLarge("vertices".into()));
|
||||
|
||||
assert!(matches!(&e, FormatError::BadPackage(msg) if msg == "the mesh is too large"), "{e:?}");
|
||||
|
||||
let e = read_error("OBJ", craft_mesh::Error::Malformed("bad face".into()));
|
||||
|
||||
assert!(e.to_string().contains("OBJ: bad face"), "{e}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn vertex_bound_allows_three_vertices_per_triangle() {
|
||||
assert!(check_vertex_bound(0, 3 * MAX_TRIANGLES).is_ok());
|
||||
|
||||
@@ -31,6 +31,7 @@ pub(super) fn encode_embedded(bytes: &[u8]) -> Result<String> {
|
||||
let mut encoder = flate2::write::ZlibEncoder::new(length.to_be_bytes().to_vec(), flate2::Compression::default());
|
||||
encoder.write_all(bytes).map_err(|e| FormatError::Io(e.to_string()))?;
|
||||
let raw = encoder.finish().map_err(|e| FormatError::Io(e.to_string()))?;
|
||||
|
||||
Ok(craft_mime::transfer::base64(&raw))
|
||||
}
|
||||
|
||||
@@ -45,6 +46,7 @@ mod tests {
|
||||
let mut encoder = flate2::write::ZlibEncoder::new((len as u32).to_be_bytes().to_vec(), flate2::Compression::default());
|
||||
encoder.write_all(&bytes).unwrap();
|
||||
let raw = encoder.finish().unwrap();
|
||||
|
||||
assert_eq!(encode_embedded(&bytes).unwrap(), base64_engine().encode(&raw));
|
||||
assert_eq!(decode_embedded(&encode_embedded(&bytes).unwrap()).unwrap(), bytes);
|
||||
}
|
||||
@@ -54,8 +56,10 @@ mod tests {
|
||||
fn strict_decoder_policy_is_not_replaced_by_mime_tolerance() {
|
||||
assert!(decode_embedded("!!!!").unwrap_err().starts_with("bad base64:"));
|
||||
assert!(decode_embedded("AA").unwrap_err().starts_with("bad base64:"));
|
||||
|
||||
let encoded = encode_embedded(b"payload").unwrap();
|
||||
let spaced = encoded.chars().map(|c| format!("{c} \n")).collect::<String>();
|
||||
|
||||
assert_eq!(decode_embedded(&spaced).unwrap(), b"payload");
|
||||
}
|
||||
|
||||
|
||||
@@ -156,7 +156,12 @@ pub(super) fn write(graph: &FunctionGraph, writer: &mut SbsWriter) -> Result<Str
|
||||
} else if let Some(instance) = &node.instance {
|
||||
output.push_str(&super::function_instance::write(instance, writer));
|
||||
} else if let Some(value) = &node.value {
|
||||
let constant = constant_xml(value).ok_or("function data must be a scalar or vector constant")?;
|
||||
// Loop limits require scalar integer data rather than an enum-style integer tag
|
||||
let constant = if let ("while", Value::Int(limit)) = (node.op.as_str(), value) {
|
||||
format!("<constantValueInt1 v=\"{limit}\"/>")
|
||||
} else {
|
||||
constant_xml(value).ok_or("function data must be a scalar or vector constant")?
|
||||
};
|
||||
let _ =
|
||||
write!(output, "<funcDatas><funcData><name v=\"{}\"/><constantValue>{constant}</constantValue></funcData></funcDatas>", xml_escape(&node.op));
|
||||
}
|
||||
@@ -167,6 +172,7 @@ pub(super) fn write(graph: &FunctionGraph, writer: &mut SbsWriter) -> Result<Str
|
||||
super::canvas::write_items(&mut output, &graph.annotations.frames, &graph.annotations.comments, &graph.annotations.pins, writer);
|
||||
}
|
||||
output.push_str("</dynamicValue>");
|
||||
|
||||
Ok(output)
|
||||
}
|
||||
|
||||
|
||||
@@ -52,6 +52,7 @@ pub fn resolve(owner: &str, reference: &str) -> Result<String, String> {
|
||||
|
||||
let uri = format!("sbs://{}", parts.join("/"));
|
||||
relative_path(&uri)?;
|
||||
|
||||
Ok(uri)
|
||||
}
|
||||
|
||||
@@ -109,12 +110,54 @@ pub fn read(uri: &str) -> Result<Vec<u8>, String> {
|
||||
read_embedded(relative)
|
||||
}
|
||||
|
||||
/// Library files that the browser build downloads from beside the wasm instead of embedding
|
||||
/// them, as paths below the library root (`resources/…`). Empty on native builds.
|
||||
pub fn external_assets() -> &'static [&'static str] {
|
||||
EXTERNAL_ASSETS
|
||||
}
|
||||
|
||||
/// The largest library asset read into memory, embedded or downloaded
|
||||
const MAX_ASSET_BYTES: usize = 256 << 20;
|
||||
|
||||
/// The downloaded [`external_assets`], filled once by the web app's startup.
|
||||
static DOWNLOADED: std::sync::RwLock<std::collections::BTreeMap<String, Vec<u8>>> = std::sync::RwLock::new(std::collections::BTreeMap::new());
|
||||
|
||||
/// Supply the bytes of one downloaded [`external_assets`] file.
|
||||
pub fn install(relative: &str, bytes: Vec<u8>) -> Result<(), String> {
|
||||
if !EXTERNAL_ASSETS.contains(&relative) {
|
||||
return Err(format!("sbs://{relative} is not a downloadable library asset"));
|
||||
}
|
||||
|
||||
if bytes.len() > MAX_ASSET_BYTES {
|
||||
return Err("downloaded library asset exceeds 256 MiB".into());
|
||||
}
|
||||
|
||||
DOWNLOADED.write().unwrap_or_else(std::sync::PoisonError::into_inner).insert(relative.into(), bytes);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn read_downloaded(relative: &str) -> Result<Vec<u8>, String> {
|
||||
if let Some(bytes) = DOWNLOADED.read().unwrap_or_else(std::sync::PoisonError::into_inner).get(relative) {
|
||||
return Ok(bytes.clone());
|
||||
}
|
||||
|
||||
if EXTERNAL_ASSETS.contains(&relative) {
|
||||
return Err(format!("Library asset sbs://{relative} has not downloaded"));
|
||||
}
|
||||
|
||||
Err(format!("Missing library asset sbs://{relative}"))
|
||||
}
|
||||
|
||||
/// Compressed assets keep installed and browser builds independent of the source checkout.
|
||||
fn read_embedded(relative: &str) -> Result<Vec<u8>, String> {
|
||||
use std::io::Read;
|
||||
let index = EMBEDDED_ASSETS.binary_search_by_key(&relative, |(name, _, _)| *name).map_err(|_| format!("Missing library asset sbs://{relative}"))?;
|
||||
let Ok(index) = EMBEDDED_ASSETS.binary_search_by_key(&relative, |(name, _, _)| *name) else {
|
||||
return read_downloaded(relative);
|
||||
};
|
||||
|
||||
let (_, compressed, size) = EMBEDDED_ASSETS.get(index).ok_or("invalid bundled asset index")?;
|
||||
if *size > 256 << 20 {
|
||||
if *size > MAX_ASSET_BYTES {
|
||||
return Err("bundled asset exceeds 256 MiB".into());
|
||||
}
|
||||
|
||||
@@ -193,6 +236,15 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
/// Only the listed browser downloads are accepted, and native builds embed everything instead.
|
||||
#[test]
|
||||
fn only_listed_library_assets_can_be_installed() {
|
||||
assert!(install("functions.sbs", b"<package/>".to_vec()).is_err());
|
||||
assert!(install("../outside.png", Vec::new()).is_err());
|
||||
assert!(external_assets().is_empty(), "native builds embed every library asset");
|
||||
assert!(read_embedded("resources/not-in-the-library.png").unwrap_err().contains("Missing library asset"));
|
||||
}
|
||||
|
||||
/// Discovered packages have unique valid aliases and the embedded fallback is present.
|
||||
#[test]
|
||||
fn the_library_lists_every_package_once_and_bundles_a_fallback() {
|
||||
@@ -203,6 +255,7 @@ mod tests {
|
||||
}
|
||||
let mut unique = files.clone();
|
||||
unique.dedup();
|
||||
|
||||
assert_eq!(unique, files);
|
||||
assert!(files.iter().all(|file| relative_path(file).is_ok() && file.ends_with(".sbs")));
|
||||
}
|
||||
|
||||
@@ -610,6 +610,12 @@ impl<'text> SbsReader<'text, '_> {
|
||||
let Some(param_value) = child_element(param, "paramValue") else { return };
|
||||
|
||||
if let Some(value) = sbs_constant(param_value) {
|
||||
// Preserve selector bits until the cook can resolve them against connected image kinds
|
||||
if node.def == "channels_shuffle" && matches!(id, "red" | "green" | "blue" | "alpha") {
|
||||
node.params.insert(id.to_string(), Value::Enum(value.int(0) as u32));
|
||||
return;
|
||||
}
|
||||
|
||||
match to_param_value(like, &value, options) {
|
||||
Some(value) => {
|
||||
node.params.insert(id.to_string(), value);
|
||||
@@ -635,12 +641,11 @@ impl<'text> SbsReader<'text, '_> {
|
||||
pub(super) fn read_filter_params(&mut self, node: &mut Node, filter: &FilterMap, params: Option<XmlNode>, graph_name: &str) {
|
||||
let Some(def) = find(filter.def) else { return };
|
||||
|
||||
// Store omitted native values explicitly for imported node inspection and round trips
|
||||
if filter.sbs == "uniform" {
|
||||
// An omitted SBS output color is black; the editor's new-node preset is gray
|
||||
node.params.insert("color".into(), Value::Color([0.0, 0.0, 0.0, 1.0]));
|
||||
}
|
||||
if filter.sbs == "normal" {
|
||||
// Native files omit these defaults; the editor's new-node preset differs
|
||||
node.params.insert("opengl".into(), Value::Bool(false));
|
||||
node.params.insert("height_alpha".into(), Value::Bool(true));
|
||||
}
|
||||
|
||||
@@ -181,6 +181,16 @@ impl SbsWriter {
|
||||
let fallback = if node.def == "input_value" { Value::Float(0.0) } else { Value::Color([0.5, 0.5, 0.5, 1.0]) };
|
||||
|
||||
let value = node.params.get("default").unwrap_or(&fallback);
|
||||
|
||||
// A color constant on a grayscale image input is rejected by native readers
|
||||
// Retain legacy color authoring values by writing their first channel as a scalar
|
||||
let gray_default;
|
||||
let value = if node.def == "input_grayscale" {
|
||||
gray_default = Value::Float(value.as_vec4().map_or(0.0, |color| color[0]));
|
||||
&gray_default
|
||||
} else {
|
||||
value
|
||||
};
|
||||
let default = constant_xml(value).unwrap_or_default();
|
||||
let code = match node.def.as_str() {
|
||||
"input_value" => exposed_type_code(value),
|
||||
@@ -335,7 +345,12 @@ impl SbsWriter {
|
||||
continue;
|
||||
}
|
||||
|
||||
if filter.sbs == "text"
|
||||
if filter.sbs == "shuffle"
|
||||
&& let Value::Enum(selector) = value
|
||||
{
|
||||
// SBS integers are signed; keep every selector bit through a save/load
|
||||
out.push_str(¶m_xml(sbs_name, &Value::Int(*selector as i32)).unwrap_or_default());
|
||||
} else if filter.sbs == "text"
|
||||
&& *sbs_name == "fontdata"
|
||||
&& let Value::Text(name) = value
|
||||
&& let Some(resource) = package.resource(name)
|
||||
|
||||
@@ -8,6 +8,29 @@ fn no_linked_files(_: &str) -> Option<Vec<u8>> {
|
||||
None
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shuffle_roundtrip_preserves_signed_channel_selectors() {
|
||||
for selector in [-2_i32, -1, 8, 9, 16, 255] {
|
||||
let xml = format!(
|
||||
r#"<package><content><graph><identifier v="Original"/><compNodes>
|
||||
<compNode><uid v="1"/><compImplementation><compFilter><filter v="shuffle"/><parameters>
|
||||
<parameter><name v="channelred"/><paramValue><constantValueInt32 v="{selector}"/></paramValue></parameter>
|
||||
</parameters></compFilter></compImplementation></compNode>
|
||||
</compNodes></graph></content></package>"#
|
||||
);
|
||||
|
||||
let loaded = read_sbs(xml.as_bytes(), "original.sbs", &no_linked_files).unwrap();
|
||||
let node = &loaded.pkg.graphs[0].nodes[0];
|
||||
|
||||
assert_eq!(node.params.get("red"), Some(&Value::Enum(selector as u32)), "selector {selector}");
|
||||
|
||||
let saved = write_sbs(&loaded.pkg).unwrap();
|
||||
let reloaded = read_sbs(&saved, "original.sbs", &no_linked_files).unwrap();
|
||||
|
||||
assert_eq!(reloaded.pkg.graphs[0].nodes[0].params.get("red"), node.params.get("red"), "saved selector {selector}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn saved_dot_outputs_load_as_incomplete_functions() {
|
||||
let xml = r#"<package><identifier v="Dots"/><content><function><identifier v="Incomplete"/>
|
||||
|
||||
@@ -48,6 +48,7 @@ pub(crate) fn decode(bytes: &[u8]) -> Result<Image> {
|
||||
|
||||
let pixels = draw::render(&tree, usvg::Transform::identity(), width, height, 0, DRAW_BUDGET)
|
||||
.map_err(|refusal| FormatError::Image(format!("SVG not drawn: {}", refusal.message)))?;
|
||||
|
||||
Ok(Image::generate(width, height, Kind::Color, |x, y| {
|
||||
let pixel = pixels.pixel(x, y).map(|pixel| pixel.demultiply());
|
||||
pixel.map_or([0.0; 4], |pixel| {
|
||||
@@ -78,15 +79,16 @@ mod tests {
|
||||
#[test]
|
||||
fn draws_a_shape_in_linear_light() {
|
||||
let image = decode(&svg(r##"<rect width="2" height="2" fill="#ff0000"/>"##)).unwrap();
|
||||
assert_eq!((image.width(), image.height()), (4, 2));
|
||||
let left = image.get(0, 0, false);
|
||||
|
||||
assert_eq!((image.width(), image.height()), (4, 2));
|
||||
assert!((left[0] - 1.0).abs() < 1e-3 && left[1].abs() < 1e-3 && (left[3] - 1.0).abs() < 1e-3, "{left:?}");
|
||||
assert_eq!(image.get(3, 1, false)[3], 0.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hostile_documents_are_errors_not_crashes() {
|
||||
// Entities that expand past the shared bound (a "billion laughs").
|
||||
// Entities that expand past the shared bound (a "billion laughs")
|
||||
let mut laughs = String::from(r#"<?xml version="1.0"?><!DOCTYPE svg [<!ENTITY a "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa">"#);
|
||||
for level in 1..10 {
|
||||
let prev = char::from(b'a' + level - 1);
|
||||
@@ -94,12 +96,17 @@ mod tests {
|
||||
laughs.push_str(&format!("<!ENTITY {name} \"{}\">", format!("&{prev};").repeat(10)));
|
||||
}
|
||||
laughs.push_str(r#"]><svg xmlns="http://www.w3.org/2000/svg" width="1" height="1"><text>&j;</text></svg>"#);
|
||||
|
||||
assert!(decode(laughs.as_bytes()).is_err());
|
||||
// Nesting deeper than the tree depth.
|
||||
|
||||
// Nesting deeper than the tree depth
|
||||
let deep = format!("{}{}", "<g>".repeat(200), "</g>".repeat(200));
|
||||
|
||||
assert!(decode(&svg(&deep)).is_err());
|
||||
// Larger than the image side limit.
|
||||
|
||||
// Larger than the image side limit
|
||||
let huge = br#"<svg xmlns="http://www.w3.org/2000/svg" width="100000" height="1"/>"#;
|
||||
|
||||
assert!(decode(huge).is_err());
|
||||
assert!(decode(b"<svg").is_err());
|
||||
}
|
||||
@@ -120,10 +127,14 @@ mod tests {
|
||||
#[test]
|
||||
fn embedded_svgs_share_the_nesting_budget() {
|
||||
let shallow = decode(&embedded(2)).unwrap();
|
||||
|
||||
assert!(shallow.get(1, 1, false)[0] > 0.9, "{:?}", shallow.get(1, 1, false));
|
||||
|
||||
let deep = decode(&embedded(40)).unwrap();
|
||||
|
||||
assert_eq!(deep.get(1, 1, false)[3], 0.0);
|
||||
// The document alone past its own budget is refused.
|
||||
|
||||
// The document alone past its own budget is refused
|
||||
assert!(decode(&svg(&nested_groups(40, ""))).is_err());
|
||||
}
|
||||
|
||||
@@ -131,6 +142,7 @@ mod tests {
|
||||
fn linked_files_are_not_read() {
|
||||
let linked = svg(r#"<image href="file:///etc/hostname" width="4" height="2"/>"#);
|
||||
let image = decode(&linked).unwrap();
|
||||
|
||||
assert_eq!(image.get(0, 0, false)[3], 0.0);
|
||||
}
|
||||
|
||||
@@ -140,6 +152,7 @@ mod tests {
|
||||
let mut gz = flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::default());
|
||||
gz.write_all(&svg(r#"<rect width="4" height="2" fill="blue"/>"#)).unwrap();
|
||||
let image = decode(&gz.finish().unwrap()).unwrap();
|
||||
|
||||
assert!(image.get(1, 1, false)[2] > 0.9);
|
||||
}
|
||||
}
|
||||
@@ -84,6 +84,7 @@ fn shared_dds_keeps_rgb_transfer_alpha_and_float_range() {
|
||||
assert!((converted.data()[i] - craft_texture::srgb_to_linear(raw.data()[i])).abs() < 1e-6);
|
||||
}
|
||||
assert_eq!(converted.data()[3], raw.data()[3]);
|
||||
|
||||
let mut floats = Vec::new();
|
||||
dds::header::Header::new_image(1, 1, dds::Format::R32G32B32A32_FLOAT).write(&mut floats).unwrap();
|
||||
for v in [-0.5_f32, 2.0, 0.25, 0.75] {
|
||||
|
||||
@@ -0,0 +1,26 @@
|
||||
use materialcraft_core::{FunctionGraph, Graph, Package, Value};
|
||||
|
||||
#[test]
|
||||
fn function_loop_limit_uses_scalar_integer_data() {
|
||||
let mut function = FunctionGraph::default();
|
||||
let initial = function.add_constant(Value::Float(0.25));
|
||||
let condition = function.add_constant(Value::Bool(true));
|
||||
let body = function.add_constant(Value::Float(0.75));
|
||||
function.output = Some(function.add("while", &[initial, condition, body], Some(Value::Int(3))));
|
||||
let mut graph = Graph::new("Loop serialization");
|
||||
graph.function = Some(function);
|
||||
let mut package = Package::new("Original function data");
|
||||
package.graphs.push(graph);
|
||||
|
||||
let bytes = materialcraft_formats::sbs::write_sbs(&package).unwrap();
|
||||
let text = String::from_utf8(bytes).unwrap();
|
||||
let document = roxmltree::Document::parse(&text).unwrap();
|
||||
let loop_node = document
|
||||
.descendants()
|
||||
.find(|node| node.has_tag_name("paramNode") && node.children().any(|child| child.has_tag_name("function") && child.attribute("v") == Some("while")))
|
||||
.unwrap();
|
||||
let limit = loop_node.descendants().find(|node| node.has_tag_name("constantValue")).unwrap().children().find(roxmltree::Node::is_element).unwrap();
|
||||
|
||||
assert_eq!(limit.tag_name().name(), "constantValueInt1");
|
||||
assert_eq!(limit.attribute("v"), Some("3"));
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
use materialcraft_core::{Graph, Package, Value};
|
||||
|
||||
#[test]
|
||||
fn grayscale_image_defaults_are_scalar_in_sbs() {
|
||||
let mut package = Package::new("Grayscale defaults");
|
||||
let mut graph = Graph::new("defaults");
|
||||
graph.add_node("input_grayscale", [0.0, 0.0]);
|
||||
let colored = graph.add_node("input_grayscale", [0.0, 100.0]);
|
||||
graph.node_mut(colored).unwrap().params.insert("default".into(), Value::Color([0.25, 0.5, 0.75, 0.125]));
|
||||
package.graphs.push(graph);
|
||||
|
||||
let bytes = materialcraft_formats::sbs::write_sbs(&package).unwrap();
|
||||
let text = String::from_utf8(bytes).unwrap();
|
||||
let document = roxmltree::Document::parse(&text).unwrap();
|
||||
let defaults: Vec<_> = document
|
||||
.descendants()
|
||||
.filter(|node| node.has_tag_name("paraminput"))
|
||||
.map(|node| {
|
||||
let default = node.children().find(|node| node.has_tag_name("defaultValue")).unwrap();
|
||||
let constant = default.children().find(roxmltree::Node::is_element).unwrap();
|
||||
(constant.tag_name().name().to_string(), constant.attribute("v").unwrap().to_string())
|
||||
})
|
||||
.collect();
|
||||
|
||||
assert_eq!(defaults, vec![("constantValueFloat1".into(), "0.5".into()), ("constantValueFloat1".into(), "0.25".into())]);
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
#![forbid(unsafe_code)]
|
||||
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
|
||||
|
||||
use craft_texture::{Image, Kind};
|
||||
use materialcraft_core::{OutputFormat, Value};
|
||||
use materialcraft_nodes::{CookContext, find, resolve_params};
|
||||
use std::{collections::BTreeMap, time::Instant};
|
||||
|
||||
fn main() -> Result<(), String> {
|
||||
const REPETITIONS: u32 = 3;
|
||||
for side in [512, 1024] {
|
||||
let inputs = [Some(Image::generate(side, side, Kind::Color, |x, y| {
|
||||
[x as f32 / side as f32, y as f32 / side as f32, f32::from((x / 7 + y / 11) % 2 == 0), 0.75]
|
||||
}))];
|
||||
for (operation, intensity) in [("blur", 32.0), ("directional_blur", 10.0), ("sharpen", 10.0)] {
|
||||
let definition = find(operation).ok_or("missing filter definition")?;
|
||||
let parameters = BTreeMap::from([("intensity".into(), Value::Float(intensity)), ("angle".into(), Value::Float(0.125))]);
|
||||
let parameters = resolve_params(definition, ¶meters);
|
||||
let resource = |_: &str| None;
|
||||
let vars = BTreeMap::new();
|
||||
let context = CookContext {
|
||||
w: side,
|
||||
h: side,
|
||||
seed: 0,
|
||||
format: OutputFormat::F32,
|
||||
tile: true,
|
||||
inputs: &inputs,
|
||||
params: ¶meters,
|
||||
resource: &resource,
|
||||
vars: &vars,
|
||||
};
|
||||
|
||||
let start = Instant::now();
|
||||
for _ in 0..REPETITIONS {
|
||||
std::hint::black_box((definition.cook)(&context)?);
|
||||
}
|
||||
println!("{operation} {side}x{side}: {:.3} ms/cook ({REPETITIONS} repetitions)", start.elapsed().as_secs_f64() * 1000.0 / f64::from(REPETITIONS));
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
@@ -1,14 +1,22 @@
|
||||
use super::ATOMIC;
|
||||
use crate::ops;
|
||||
use super::{ATOMIC, box_filter};
|
||||
use crate::{CookContext, CookResult, NodeDefinition, node};
|
||||
use craft_texture::Kind;
|
||||
|
||||
pub(super) fn definition() -> NodeDefinition {
|
||||
node("blur", "Blur", ATOMIC).desc("Gaussian blur.").atomic().any_in("input", "Input").float("intensity", "Intensity", 2.0, 0.0, 32.0).any_out().cook(blur)
|
||||
node("blur", "Blur", ATOMIC)
|
||||
.desc("Box blur with fractional pixel coverage.")
|
||||
.atomic()
|
||||
.any_in("input", "Input")
|
||||
.float("intensity", "Intensity", 10.0, 0.0, 32.0)
|
||||
.any_out()
|
||||
.cook(blur)
|
||||
}
|
||||
|
||||
fn blur(context: &CookContext) -> CookResult {
|
||||
let img = context.any_or(0, Kind::Gray, [0.0; 4]);
|
||||
let sigma = context.f("intensity").max(0.0) * context.w as f32 / 256.0 * 0.5;
|
||||
Ok(vec![ops::gaussian(&img, sigma, context.tile)])
|
||||
let input = context.any_or(0, Kind::Gray, [0.0; 4]);
|
||||
const BASE_RESOLUTION: f32 = 256.0;
|
||||
let radius = context.f("intensity").max(0.0) * context.w.min(context.h) as f32 / BASE_RESOLUTION;
|
||||
let tile = context.tiling_axes();
|
||||
|
||||
Ok(vec![box_filter::axis(&box_filter::axis(&input, radius, true, tile[0]), radius, false, tile[1])])
|
||||
}
|
||||
@@ -0,0 +1,95 @@
|
||||
use craft_texture::{Image, Limits, MAX_SIDE};
|
||||
use rayon::prelude::*;
|
||||
|
||||
pub(super) fn axis(input: &Image, radius: f32, horizontal: bool, tile: bool) -> Image {
|
||||
if !radius.is_finite() || radius <= 0.5 {
|
||||
return input.clone();
|
||||
}
|
||||
|
||||
// Bound work for hostile strengths to the largest supported image dimension
|
||||
let radius = radius.min(MAX_SIDE as f32);
|
||||
let extent = (radius + 0.5).floor() as i64;
|
||||
let weight = 1.0 / (2.0 * f64::from(radius));
|
||||
let edge_weight = (0.5 - (extent as f64 - 0.5) * weight).max(0.0);
|
||||
let (length, lines) = if horizontal { (input.width(), input.height()) } else { (input.height(), input.width()) };
|
||||
let channels = input.channels();
|
||||
let results: Vec<Vec<f32>> = (0..lines)
|
||||
.into_par_iter()
|
||||
.map(|line| {
|
||||
let get = |position: i64| {
|
||||
if horizontal { input.get(position, i64::from(line), tile) } else { input.get(i64::from(line), position, tile) }
|
||||
};
|
||||
let mut output = vec![0.0; length as usize * channels];
|
||||
for channel in 0..channels {
|
||||
// Count NaN, positive infinity and negative infinity separately
|
||||
let mut sum = 0.0_f64;
|
||||
let mut non_finite = [0_i64; 3];
|
||||
for position in (1 - extent)..extent {
|
||||
accumulate(&mut sum, &mut non_finite, get(position)[channel], 1);
|
||||
}
|
||||
|
||||
for (position, pixel) in output.chunks_exact_mut(channels).enumerate() {
|
||||
let position = position as i64;
|
||||
let mut value = window_total(sum, non_finite) * weight;
|
||||
if edge_weight > 0.0 {
|
||||
value += (f64::from(get(position - extent)[channel]) + f64::from(get(position + extent)[channel])) * edge_weight;
|
||||
}
|
||||
pixel[channel] = value as f32;
|
||||
accumulate(&mut sum, &mut non_finite, get(position + extent)[channel], 1);
|
||||
accumulate(&mut sum, &mut non_finite, get(position - extent + 1)[channel], -1);
|
||||
}
|
||||
}
|
||||
|
||||
output
|
||||
})
|
||||
.collect();
|
||||
|
||||
let data = if horizontal {
|
||||
results.into_iter().flatten().collect()
|
||||
} else {
|
||||
let mut data = Vec::with_capacity(input.width() as usize * input.height() as usize * channels);
|
||||
for y in 0..input.height() as usize {
|
||||
for line in &results {
|
||||
data.extend_from_slice(line.get(y * channels..(y + 1) * channels).unwrap_or(&[]));
|
||||
}
|
||||
}
|
||||
|
||||
data
|
||||
};
|
||||
|
||||
let mut limits = Limits::default();
|
||||
limits.max_side = u32::MAX;
|
||||
limits.max_pixels = u64::MAX;
|
||||
limits.max_bytes = u64::MAX;
|
||||
|
||||
// `data` keeps the size and kind of a valid image, so `from_data` accepts it
|
||||
Image::from_data(input.width(), input.height(), input.kind(), data, &limits).unwrap_or_else(|_| input.clone())
|
||||
}
|
||||
|
||||
fn accumulate(sum: &mut f64, non_finite: &mut [i64; 3], value: f32, sign: i64) {
|
||||
if value.is_finite() {
|
||||
*sum += f64::from(value) * sign as f64;
|
||||
} else {
|
||||
let index = if value.is_nan() {
|
||||
0
|
||||
} else if value.is_sign_positive() {
|
||||
1
|
||||
} else {
|
||||
2
|
||||
};
|
||||
non_finite[index] += sign;
|
||||
}
|
||||
}
|
||||
|
||||
fn window_total(sum: f64, non_finite: [i64; 3]) -> f64 {
|
||||
// A non-finite sample must stop affecting the running sum once it leaves the window
|
||||
if non_finite[0] > 0 || (non_finite[1] > 0 && non_finite[2] > 0) {
|
||||
f64::NAN
|
||||
} else if non_finite[1] > 0 {
|
||||
f64::INFINITY
|
||||
} else if non_finite[2] > 0 {
|
||||
f64::NEG_INFINITY
|
||||
} else {
|
||||
sum
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
use super::ATOMIC;
|
||||
use crate::{CookContext, CookResult, NodeDefinition, node};
|
||||
use craft_texture::{Image, Kind};
|
||||
use materialcraft_core::Value;
|
||||
|
||||
pub(super) fn definition() -> NodeDefinition {
|
||||
node("channels_shuffle", "Channels shuffle", ATOMIC)
|
||||
@@ -17,19 +18,36 @@ pub(super) fn definition() -> NodeDefinition {
|
||||
}
|
||||
|
||||
fn channels_shuffle(context: &CookContext) -> CookResult {
|
||||
let a = context.any_or(0, Kind::Color, [0.0, 0.0, 0.0, 1.0]).to_color();
|
||||
let b = context.any_or(1, Kind::Color, [0.0, 0.0, 0.0, 1.0]).to_color();
|
||||
let src = [context.i("red"), context.i("green"), context.i("blue"), context.i("alpha")];
|
||||
// Sampling clamps the unconnected fallback to its single zero pixel
|
||||
let first_input = context.sized(0).unwrap_or_else(|| Image::filled(1, 1, Kind::Color, [0.0; 4]));
|
||||
let second_input = context.sized(1).unwrap_or_else(|| Image::filled(1, 1, Kind::Color, [0.0; 4]));
|
||||
let channel_sources = ["red", "green", "blue", "alpha"].map(|id| match context.value(id) {
|
||||
Some(Value::Enum(index)) => *index,
|
||||
_ => 0,
|
||||
});
|
||||
|
||||
Ok(vec![Image::generate(context.w, context.h, Kind::Color, |x, y| {
|
||||
let (pa, pb) = (a.get(x as i64, y as i64, false), b.get(x as i64, y as i64, false));
|
||||
src.map(|s| match s {
|
||||
0..=3 => pa[s as usize],
|
||||
4..=7 => pb[(s - 4) as usize],
|
||||
9 => 1.0,
|
||||
_ => 0.0,
|
||||
let first_pixel = first_input.get(x as i64, y as i64, false);
|
||||
let second_pixel = second_input.get(x as i64, y as i64, false);
|
||||
|
||||
channel_sources.map(|selector| {
|
||||
// Gray selection precedes the packed color swizzle, including for file values above seven
|
||||
if selector < 4 && first_input.is_gray() {
|
||||
return first_pixel[0];
|
||||
}
|
||||
|
||||
if selector >= 4 && second_input.is_gray() {
|
||||
return second_pixel[0];
|
||||
}
|
||||
|
||||
const CHANNEL_MASK: u32 = 0b111;
|
||||
match selector & CHANNEL_MASK {
|
||||
channel @ 0..=3 => first_pixel[channel as usize],
|
||||
channel => second_pixel[(channel - 4) as usize],
|
||||
}
|
||||
})
|
||||
})])
|
||||
}
|
||||
|
||||
const CHANNEL_SOURCES: &[&str] =
|
||||
&["Input 1 red", "Input 1 green", "Input 1 blue", "Input 1 alpha", "Input 2 red", "Input 2 green", "Input 2 blue", "Input 2 alpha", "Black", "White"];
|
||||
&["Input 1 red", "Input 1 green", "Input 1 blue", "Input 1 alpha", "Input 2 red", "Input 2 green", "Input 2 blue", "Input 2 alpha"];
|
||||
@@ -1,4 +1,4 @@
|
||||
use super::{ATOMIC, direction};
|
||||
use super::{ATOMIC, box_filter, direction};
|
||||
use crate::{CookContext, CookResult, NodeDefinition, node};
|
||||
use craft_texture::{Image, Kind};
|
||||
|
||||
@@ -18,23 +18,47 @@ fn directional_blur(context: &CookContext) -> CookResult {
|
||||
}
|
||||
|
||||
pub(super) fn blur(context: &CookContext, angle: f32) -> CookResult {
|
||||
let img = context.any_or(0, Kind::Gray, [0.0; 4]);
|
||||
let len = context.f("intensity").max(0.0) * context.w as f32 / 256.0;
|
||||
if len < 0.5 {
|
||||
return Ok(vec![img]);
|
||||
let input = context.any_or(0, Kind::Gray, [0.0; 4]);
|
||||
const BASE_RESOLUTION: f32 = 256.0;
|
||||
const MAX_HALF_SAMPLES: i32 = 512;
|
||||
let radius = context.f("intensity").max(0.0) * context.w.min(context.h) as f32 / BASE_RESOLUTION;
|
||||
if radius <= 0.5 {
|
||||
return Ok(vec![input]);
|
||||
}
|
||||
|
||||
let (dx, dy) = direction(angle);
|
||||
let n = (len.ceil() as i32).clamp(1, 512);
|
||||
let (iw, ih) = (1.0 / context.w as f32, 1.0 / context.h as f32);
|
||||
Ok(vec![Image::generate_uv(context.w, context.h, img.kind(), |u, v| {
|
||||
let mut acc = [0.0; 4];
|
||||
for i in -n..=n {
|
||||
let t = i as f32 / n as f32 * len * 0.5;
|
||||
let p = img.sample(u + dx * t * iw, v + dy * t * ih, context.tile);
|
||||
for k in 0..4 {
|
||||
acc[k] += p[k];
|
||||
|
||||
// Image-space rotation follows increasing rows
|
||||
let dy = -dy;
|
||||
let tile = context.tiling_axes();
|
||||
if dy == 0.0 {
|
||||
return Ok(vec![box_filter::axis(&input, radius, true, tile[0])]);
|
||||
}
|
||||
|
||||
let major = dx.abs().max(dy.abs());
|
||||
let projected_radius = 0.5 + (radius - 0.5) * major;
|
||||
let half_samples = (projected_radius + 0.5).floor().clamp(1.0, MAX_HALF_SAMPLES as f32) as i32;
|
||||
|
||||
// Bound oblique sampling cost while preserving the extent of large kernels
|
||||
let step = ((projected_radius - 0.5) / half_samples as f32).max(1.0);
|
||||
let weight = step / (2.0 * projected_radius);
|
||||
let edge_weight = (0.5 - (half_samples as f32 - 0.5) * weight).max(0.0);
|
||||
let (inverse_width, inverse_height) = (1.0 / context.w as f32, 1.0 / context.h as f32);
|
||||
|
||||
Ok(vec![Image::generate_uv(context.w, context.h, input.kind(), |u, v| {
|
||||
let mut pixel = [0.0; 4];
|
||||
for i in -half_samples..=half_samples {
|
||||
let sample_weight = if i.abs() == half_samples { edge_weight } else { weight };
|
||||
if sample_weight == 0.0 {
|
||||
continue;
|
||||
}
|
||||
|
||||
let offset = i as f32 * step / major;
|
||||
let sample = input.sample_axes(u + dx * offset * inverse_width, v + dy * offset * inverse_height, tile);
|
||||
for channel in 0..4 {
|
||||
pixel[channel] += sample[channel] * sample_weight;
|
||||
}
|
||||
}
|
||||
acc.map(|a| a / (2 * n + 1) as f32)
|
||||
pixel
|
||||
})])
|
||||
}
|
||||
@@ -10,7 +10,7 @@ pub(super) fn definition() -> NodeDefinition {
|
||||
.gray_in("mask", "Mask input")
|
||||
.any_in("source", "Source input")
|
||||
.float("distance", "Maximum distance", 10.0, 0.0, 256.0)
|
||||
.boolean("combine", "Combine distance with source", false)
|
||||
.boolean("combine", "Combine distance with source", true)
|
||||
.any_out()
|
||||
.cook(distance)
|
||||
}
|
||||
|
||||
@@ -10,25 +10,27 @@ pub(super) fn definition() -> NodeDefinition {
|
||||
.any_in("input", "Input")
|
||||
.gray_in("height", "Intensity input")
|
||||
.float("intensity", "Intensity", 5.0, 0.0, 32.0)
|
||||
.angle("light_angle", "Light angle", 0.375)
|
||||
.angle("light_angle", "Light angle", 0.0)
|
||||
.color("highlight", "Highlight color", [1.0, 1.0, 1.0, 1.0])
|
||||
.color("shadow", "Shadow color", [0.0, 0.0, 0.0, 1.0])
|
||||
.color("shadow", "Shadow color", [0.0; 4])
|
||||
.any_out()
|
||||
.cook(emboss)
|
||||
}
|
||||
|
||||
fn emboss(context: &CookContext) -> CookResult {
|
||||
let img = context.any_or(0, Kind::Color, [0.5, 0.5, 0.5, 1.0]);
|
||||
let hmap = context.gray_or(1, 0.0);
|
||||
let (lx, ly) = direction(context.f("light_angle"));
|
||||
let k = context.f("intensity") * context.w as f32 / 64.0;
|
||||
let (hi, sh) = (context.v4("highlight"), context.v4("shadow"));
|
||||
Ok(vec![Image::generate(context.w, context.h, img.kind(), |x, y| {
|
||||
let (gx, gy) = ops::slope(&hmap, x as i64, y as i64, context.tile);
|
||||
let l = (-(gx * lx + gy * ly) * k).clamp(-1.0, 1.0);
|
||||
let p = img.get(x as i64, y as i64, false);
|
||||
let tint = if l >= 0.0 { hi } else { sh };
|
||||
let t = l.abs();
|
||||
[p[0] + (tint[0] - p[0]) * t, p[1] + (tint[1] - p[1]) * t, p[2] + (tint[2] - p[2]) * t, p[3]]
|
||||
const INTENSITY_REFERENCE_WIDTH: f32 = 64.0;
|
||||
let input = context.any_or(0, Kind::Gray, [0.0; 4]);
|
||||
let height_map = context.gray_or(1, 0.0);
|
||||
let (light_x, light_y) = direction(context.f("light_angle"));
|
||||
let intensity = context.f("intensity") * context.w as f32 / INTENSITY_REFERENCE_WIDTH;
|
||||
let (highlight, shadow) = (context.v4("highlight"), context.v4("shadow"));
|
||||
|
||||
Ok(vec![Image::generate(context.w, context.h, input.kind(), |x, y| {
|
||||
let (gx, gy) = ops::slope(&height_map, x as i64, y as i64, context.tile);
|
||||
let lighting = (-(gx * light_x + gy * light_y) * intensity).clamp(-1.0, 1.0);
|
||||
let pixel = input.get(x as i64, y as i64, false);
|
||||
let tint = if lighting >= 0.0 { highlight } else { shadow };
|
||||
let blend = lighting.abs();
|
||||
[pixel[0] + (tint[0] - pixel[0]) * blend, pixel[1] + (tint[1] - pixel[1]) * blend, pixel[2] + (tint[2] - pixel[2]) * blend, pixel[3]]
|
||||
})])
|
||||
}
|
||||
@@ -8,17 +8,21 @@ pub(super) fn definition() -> NodeDefinition {
|
||||
.atomic()
|
||||
.gray_in("input", "Grayscale input")
|
||||
.any_in("gradient", "Gradient input")
|
||||
.float("position", "Position", 0.5, 0.0, 1.0)
|
||||
.float("position", "Position", 0.0, 0.0, 1.0)
|
||||
.choice("orientation", "Orientation", &["Horizontal", "Vertical"], 0)
|
||||
.any_out()
|
||||
.cook(gradient_dynamic)
|
||||
}
|
||||
|
||||
fn gradient_dynamic(context: &CookContext) -> CookResult {
|
||||
let Some(gradient) = context.input(1) else {
|
||||
return Ok(vec![Image::filled(context.w, context.h, Kind::Gray, [0.0; 4])]);
|
||||
};
|
||||
|
||||
let input = context.gray_or(0, 0.0);
|
||||
let gradient = context.input(1).cloned().unwrap_or_else(|| Image::generate_uv(256, 1, Kind::Gray, |position, _| [position; 4]));
|
||||
let position = context.f("position");
|
||||
let vertical = context.i("orientation") == 1;
|
||||
|
||||
Ok(vec![Image::generate(context.w, context.h, gradient.kind(), |x, y| {
|
||||
let intensity = input.get_gray(i64::from(x), i64::from(y), false).clamp(0.0, 1.0);
|
||||
if vertical { gradient.sample(position, intensity, false) } else { gradient.sample(intensity, position, false) }
|
||||
|
||||
@@ -12,7 +12,7 @@ pub(super) fn definition() -> NodeDefinition {
|
||||
.float("blue", "Blue weight", 1.0 / 3.0, 0.0, 1.0)
|
||||
.float("alpha", "Alpha weight", 0.0, 0.0, 1.0)
|
||||
.boolean("flatten_alpha", "Flatten alpha", false)
|
||||
.float("matte", "Matte level", 0.0, 0.0, 1.0)
|
||||
.float("matte", "Matte level", 1.0, 0.0, 1.0)
|
||||
.gray_out()
|
||||
.cook(grayscale_conversion)
|
||||
}
|
||||
|
||||
@@ -16,10 +16,11 @@ pub(super) fn definition() -> NodeDefinition {
|
||||
}
|
||||
|
||||
fn hsl(context: &CookContext) -> CookResult {
|
||||
let image = context.any_or(0, Kind::Color, [0.5, 0.5, 0.5, 1.0]).to_color();
|
||||
let image = context.any_or(0, Kind::Color, [0.0; 4]).to_color();
|
||||
|
||||
// The normalized slider spans one full turn in either direction from its midpoint
|
||||
let (hue_shift, saturation, lightness) = ((context.f("hue") - 0.5) * 2.0, context.f("saturation"), context.f("lightness"));
|
||||
|
||||
Ok(vec![image.map(Kind::Color, |pixel| {
|
||||
let [h, s, l] = ops::rgb_to_hsl(pixel);
|
||||
let s = if saturation <= 0.5 { s * saturation * 2.0 } else { s + (1.0 - s) * (saturation - 0.5) * 2.0 };
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
mod bitmap;
|
||||
mod blend;
|
||||
mod blur;
|
||||
mod box_filter;
|
||||
mod channels_shuffle;
|
||||
mod curve;
|
||||
mod directional_blur;
|
||||
|
||||
@@ -8,15 +8,17 @@ pub(super) fn definition() -> NodeDefinition {
|
||||
.atomic()
|
||||
.gray_in("input", "Input")
|
||||
.float("intensity", "Intensity", 1.0, 0.0, 10.0)
|
||||
.boolean("opengl", "OpenGL normals", true)
|
||||
.boolean("height_alpha", "Height in alpha", false)
|
||||
.boolean("opengl", "OpenGL normals", false)
|
||||
.boolean("height_alpha", "Height in alpha", true)
|
||||
.color_out()
|
||||
.cook(normal)
|
||||
}
|
||||
|
||||
fn normal(context: &CookContext) -> CookResult {
|
||||
const BASE_RESOLUTION: f32 = 256.0;
|
||||
let height_map = context.gray_or(0, 0.0);
|
||||
let intensity = context.f("intensity") * context.w as f32 / 256.0;
|
||||
let intensity = context.f("intensity") * context.w as f32 / BASE_RESOLUTION;
|
||||
|
||||
Ok(vec![height_to_normal(&height_map, intensity, !context.b("opengl"), context.tile, context.b("height_alpha"))])
|
||||
}
|
||||
|
||||
|
||||
@@ -10,9 +10,9 @@ pub(super) fn definition() -> NodeDefinition {
|
||||
.any_in("background", "Background")
|
||||
.any_in("pattern0", "Input image 0")
|
||||
.pattern_graph("pattern", "FX-Map graph", PatternGraph::with_root(PatternNodeKind::Quadrant))
|
||||
.float("roughness", "Roughness", 0.0, 0.0, 2.0)
|
||||
.float("roughness", "Roughness", 1.0, 0.0, 2.0)
|
||||
.float("opacity", "Opacity", 1.0, 0.0, 10.0)
|
||||
.boolean("color_mode", "Color output", false)
|
||||
.boolean("color_mode", "Color output", true)
|
||||
.color("background", "Background color", [0.0; 4])
|
||||
.float4("render_region", "Render region", [0.0, 1.0, 0.0, 1.0], -65536.0, 65536.0)
|
||||
.float4("tiling_region", "Tiling region", [0.0, 1.0, 0.0, 1.0], 0.0, 1.0)
|
||||
|
||||
@@ -1,11 +1,10 @@
|
||||
use super::ATOMIC;
|
||||
use crate::ops;
|
||||
use crate::{CookContext, CookResult, NodeDefinition, node};
|
||||
use craft_texture::{Image, Kind};
|
||||
|
||||
pub(super) fn definition() -> NodeDefinition {
|
||||
node("sharpen", "Sharpen", ATOMIC)
|
||||
.desc("Unsharp mask.")
|
||||
.desc("Sharpens local contrast with a four-neighbor Laplacian.")
|
||||
.atomic()
|
||||
.any_in("input", "Input")
|
||||
.float("intensity", "Intensity", 1.0, 0.0, 10.0)
|
||||
@@ -14,11 +13,38 @@ pub(super) fn definition() -> NodeDefinition {
|
||||
}
|
||||
|
||||
fn sharpen(context: &CookContext) -> CookResult {
|
||||
let img = context.any_or(0, Kind::Gray, [0.0; 4]);
|
||||
let soft = ops::gaussian(&img, 1.0, context.tile);
|
||||
let k = context.f("intensity");
|
||||
Ok(vec![Image::generate(context.w, context.h, img.kind(), |x, y| {
|
||||
let (a, b) = (img.get(x as i64, y as i64, false), soft.get(x as i64, y as i64, false));
|
||||
[a[0] + (a[0] - b[0]) * k, a[1] + (a[1] - b[1]) * k, a[2] + (a[2] - b[2]) * k, a[3]]
|
||||
let input = context.any_or(0, Kind::Gray, [0.0; 4]);
|
||||
let intensity = context.f("intensity");
|
||||
let tile = context.tiling_axes();
|
||||
let short_side = context.w.min(context.h) as f32;
|
||||
let horizontal = intensity * short_side / context.w.max(1) as f32;
|
||||
let vertical = intensity * short_side / context.h.max(1) as f32;
|
||||
|
||||
Ok(vec![Image::generate(context.w, context.h, input.kind(), |x, y| {
|
||||
let (x, y) = (i64::from(x), i64::from(y));
|
||||
let center = input.get(x, y, false);
|
||||
let left = input.get_axes(x - 1, y, tile);
|
||||
let right = input.get_axes(x + 1, y, tile);
|
||||
let top = input.get_axes(x, y - 1, tile);
|
||||
let bottom = input.get_axes(x, y + 1, tile);
|
||||
std::array::from_fn(|channel| {
|
||||
// Keep the axial differences separate to preserve Float32 cancellation order
|
||||
let twice_center = 2.0 * center[channel];
|
||||
let across = axial_difference(center[channel], twice_center, left[channel], right[channel]);
|
||||
let down = axial_difference(center[channel], twice_center, top[channel], bottom[channel]);
|
||||
|
||||
// Float outputs retain HDR values but discard negative sharpening lobes
|
||||
(center[channel] + (across * horizontal + down * vertical)).max(0.0)
|
||||
})
|
||||
})])
|
||||
}
|
||||
|
||||
fn axial_difference(center: f32, twice_center: f32, first: f32, second: f32) -> f32 {
|
||||
let difference = twice_center - (first + second);
|
||||
if difference.is_finite() || ![center, first, second].iter().all(|value| value.is_finite()) {
|
||||
return difference;
|
||||
}
|
||||
|
||||
// Finite HDR inputs can overflow both Float32 sums and turn their difference into NaN
|
||||
(2.0 * f64::from(center) - (f64::from(first) + f64::from(second))) as f32
|
||||
}
|
||||
@@ -118,9 +118,9 @@ pub(super) fn definition() -> NodeDefinition {
|
||||
.any_in("background", "Background")
|
||||
.boolean("color_mode", "Color output", false)
|
||||
.color("background", "Background color", [0.0, 0.0, 0.0, 1.0])
|
||||
.text("text", "Text", "MaterialCraft")
|
||||
.text("text", "Text", "")
|
||||
.text("fontdata", "Font reference", "")
|
||||
.float("fontsize", "Font size", 0.09, 0.0, 1.0)
|
||||
.float("fontsize", "Font size", 0.25, 0.0, 1.0)
|
||||
.float2("position", "Position", [0.0; 2], -1.0, 1.0)
|
||||
.float4("matrix", "Transform matrix", [1.0, 0.0, 0.0, 1.0], -10.0, 10.0)
|
||||
.choice("alignment", "Alignment", &["Left", "Center", "Right"], 1)
|
||||
@@ -205,7 +205,7 @@ mod tests {
|
||||
#[test]
|
||||
fn renders_material_craft() {
|
||||
let def = find("text").unwrap();
|
||||
let p = resolve_params(def, &BTreeMap::new());
|
||||
let p = resolve_params(def, &BTreeMap::from([("text".into(), materialcraft_core::Value::Text("MaterialCraft".into()))]));
|
||||
let no_res = |_: &str| None;
|
||||
let vars = BTreeMap::new();
|
||||
let context = CookContext {
|
||||
|
||||
@@ -7,17 +7,18 @@ pub(super) fn definition() -> NodeDefinition {
|
||||
.desc("A single color or gray value.")
|
||||
.atomic()
|
||||
.generator()
|
||||
.color("color", "Color", [0.5, 0.5, 0.5, 1.0])
|
||||
.color("color", "Color", [0.0, 0.0, 0.0, 1.0])
|
||||
.boolean("color_mode", "Color output", true)
|
||||
.any_out()
|
||||
.cook(uniform)
|
||||
}
|
||||
|
||||
fn uniform(context: &CookContext) -> CookResult {
|
||||
let c = context.v4("color");
|
||||
let color = context.v4("color");
|
||||
|
||||
Ok(vec![if !context.b("color_mode") {
|
||||
Image::filled(context.w, context.h, Kind::Gray, [luminance(c); 4])
|
||||
Image::filled(context.w, context.h, Kind::Gray, [luminance(color); 4])
|
||||
} else {
|
||||
Image::filled(context.w, context.h, Kind::Color, c)
|
||||
Image::filled(context.w, context.h, Kind::Color, color)
|
||||
}])
|
||||
}
|
||||
@@ -19,6 +19,10 @@ pub struct CookContext<'a> {
|
||||
}
|
||||
|
||||
impl CookContext<'_> {
|
||||
pub fn tiling_axes(&self) -> [bool; 2] {
|
||||
self.vars.get("$tiling").and_then(Value::as_i32).map_or([self.tile; 2], |mask| [mask & 1 != 0, mask & 2 != 0])
|
||||
}
|
||||
|
||||
pub fn value(&self, id: &str) -> Option<&Value> {
|
||||
self.params.get(id)
|
||||
}
|
||||
|
||||
@@ -100,10 +100,10 @@ pub fn default_value(id: &str) -> Option<Value> {
|
||||
|
||||
Some(match id {
|
||||
"const_bool" => Value::Bool(false),
|
||||
"const_float1" => Value::Float(0.5),
|
||||
"const_float1" => Value::Float(0.0),
|
||||
"const_float2" => Value::Float2([0.0; 2]),
|
||||
"const_float3" => Value::Float3([0.0; 3]),
|
||||
"const_float4" => Value::Float4([0.0, 0.0, 0.0, 1.0]),
|
||||
"const_float4" => Value::Float4([0.0; 4]),
|
||||
"const_int1" => Value::Int(0),
|
||||
"const_int2" => Value::Int2([0; 2]),
|
||||
"const_int3" => Value::Int3([0; 3]),
|
||||
@@ -114,7 +114,7 @@ pub fn default_value(id: &str) -> Option<Value> {
|
||||
"swizzle3" | "iswizzle3" => Value::Int3([0, 1, 2]),
|
||||
"swizzle4" | "iswizzle4" => Value::Int4([0, 1, 2, 3]),
|
||||
"samplecol" | "samplelum" => Value::Int2([0, 0]),
|
||||
"while" => Value::Int(100),
|
||||
"while" => Value::Int(super::DEFAULT_LOOP_LIMIT),
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
@@ -46,7 +46,7 @@ fn compile_nested(graph: &FunctionGraph, seed: u32, depth: usize, remaining: &mu
|
||||
};
|
||||
let names: Vec<_> = super::input_identifiers(node).collect();
|
||||
|
||||
// An operation computes with zero on an input nothing is connected to; a call needs a source default instead
|
||||
// Operations use zero for absent inputs; calls require source defaults
|
||||
let missing_input = node
|
||||
.instance
|
||||
.as_ref()
|
||||
@@ -55,7 +55,7 @@ fn compile_nested(graph: &FunctionGraph, seed: u32, depth: usize, remaining: &mu
|
||||
return Err(format!("{} ({id}) requires connected inputs: {}", super::node_label(node), names.join(", ")));
|
||||
}
|
||||
|
||||
// Preserved legacy connectors must not evaluate a duplicate random or stateful input twice
|
||||
// Legacy connectors must not evaluate stateful inputs twice
|
||||
let ports: Vec<_> = names
|
||||
.into_iter()
|
||||
.zip(&node.inputs)
|
||||
@@ -79,7 +79,7 @@ fn compile_nested(graph: &FunctionGraph, seed: u32, depth: usize, remaining: &mu
|
||||
connected
|
||||
} else {
|
||||
let sibling = if node.op == "ifelse" {
|
||||
// The condition is Boolean; absent value branches must use a value-port type.
|
||||
// Absent value branches must use a value-port type
|
||||
ports.iter().skip(1).find_map(|(_, input)| {
|
||||
input.and_then(|id| indices.get(&id)).and_then(|index| instructions.get(*index)).map(|instruction| instruction.type_code)
|
||||
})
|
||||
@@ -88,11 +88,18 @@ fn compile_nested(graph: &FunctionGraph, seed: u32, depth: usize, remaining: &mu
|
||||
};
|
||||
let mut connected = connected.into_iter();
|
||||
let mut inputs = Vec::with_capacity(ports.len());
|
||||
for (name, input) in &ports {
|
||||
for (slot, (name, input)) in ports.iter().enumerate() {
|
||||
let index = match input {
|
||||
Some(_) => connected.next().ok_or("unresolved function input")?,
|
||||
None => {
|
||||
let (definition, value) = unconnected(name, sibling.unwrap_or(node.type_code))?;
|
||||
let sibling_type_code = ports
|
||||
.get(if slot == 0 { 1 } else { 0 })
|
||||
.and_then(|(_, input)| **input)
|
||||
.and_then(|id| indices.get(&id))
|
||||
.and_then(|index| instructions.get(*index))
|
||||
.map(|instruction| instruction.type_code);
|
||||
let kind = super::unconnected_input::value_type(&node.op, name, sibling.unwrap_or(node.type_code), sibling_type_code);
|
||||
let (definition, value) = unconnected(kind)?;
|
||||
let type_code = super::value_type::type_code(&value);
|
||||
instructions.push(Instruction {
|
||||
id: 0,
|
||||
@@ -154,6 +161,7 @@ fn compile_nested(graph: &FunctionGraph, seed: u32, depth: usize, remaining: &mu
|
||||
}
|
||||
|
||||
let output = indices.get(&output).copied().ok_or("missing result instruction")?;
|
||||
|
||||
Ok(Program { instructions, output, seed })
|
||||
}
|
||||
|
||||
@@ -173,11 +181,10 @@ fn loop_members(instructions: &[Instruction], index: usize) -> Vec<usize> {
|
||||
member.iter().enumerate().filter(|(_, member)| **member).map(|(index, _)| index).collect()
|
||||
}
|
||||
|
||||
/// The constant an unconnected input `name` reads: false for a condition, otherwise zero of the type its node works with
|
||||
fn unconnected(name: &str, type_code: u32) -> Result<(&'static super::FunctionDefinition, materialcraft_core::Value), String> {
|
||||
/// The constant an unconnected input reads: false or zero of the operand type
|
||||
fn unconnected(value_type: materialcraft_core::ValueType) -> Result<(&'static super::FunctionDefinition, materialcraft_core::Value), String> {
|
||||
use materialcraft_core::ValueType;
|
||||
|
||||
let value_type = if matches!(name, "cond" | "condition") { ValueType::Boolean } else { ValueType::from_code(type_code).unwrap_or(ValueType::Float) };
|
||||
let operation = match value_type {
|
||||
ValueType::Boolean => "const_bool",
|
||||
ValueType::Integer => "const_int1",
|
||||
@@ -191,5 +198,6 @@ fn unconnected(name: &str, type_code: u32) -> Result<(&'static super::FunctionDe
|
||||
ValueType::String => "const_string",
|
||||
};
|
||||
let definition = catalog::definition(operation).ok_or("missing constant operation")?;
|
||||
|
||||
Ok((definition, value_type.default_value()))
|
||||
}
|
||||
@@ -5,6 +5,9 @@
|
||||
const MAX_EXPANDED_NODES: usize = 131_072;
|
||||
const MAX_CALL_DEPTH: usize = 16;
|
||||
|
||||
// Keep absent loop limits aligned with fresh-node defaults
|
||||
const DEFAULT_LOOP_LIMIT: i32 = 32;
|
||||
|
||||
mod arithmetic;
|
||||
mod catalog;
|
||||
mod compile;
|
||||
@@ -24,6 +27,10 @@ mod processor;
|
||||
mod program;
|
||||
mod resolve_instances;
|
||||
mod system_variable;
|
||||
mod unconnected_input;
|
||||
#[cfg(test)]
|
||||
#[path = "unconnected.test.rs"]
|
||||
mod unconnected_tests;
|
||||
pub mod value_type;
|
||||
mod vector;
|
||||
mod warnings;
|
||||
|
||||
@@ -169,7 +169,7 @@ impl Program {
|
||||
}
|
||||
LoopCondition { instruction: index, iteration, last } => {
|
||||
let exit = value_type::boolean(&state.values.pop().ok_or("missing loop condition")?)?;
|
||||
let maximum = self.instruction(index)?.value.as_ref().and_then(Value::as_i32).unwrap_or(100);
|
||||
let maximum = self.instruction(index)?.value.as_ref().and_then(Value::as_i32).unwrap_or(super::DEFAULT_LOOP_LIMIT);
|
||||
if exit || (maximum >= 0 && iteration >= maximum as u32) {
|
||||
state.values.push(last);
|
||||
} else {
|
||||
|
||||
@@ -0,0 +1,75 @@
|
||||
use super::{EvaluationContext, EvaluationState, compile, definition};
|
||||
use materialcraft_core::{FunctionGraph, Value};
|
||||
|
||||
#[test]
|
||||
fn unconnected_typed_operations_use_their_operand_types() {
|
||||
for (operation, expected) in [
|
||||
("vector3", Value::Float3([0.0; 3])),
|
||||
("vector4", Value::Float4([0.0; 4])),
|
||||
("ivector2", Value::Int2([0; 2])),
|
||||
("ivector3", Value::Int3([0; 3])),
|
||||
("ivector4", Value::Int4([0; 4])),
|
||||
("iswizzle1", Value::Int(0)),
|
||||
("iswizzle4", Value::Int4([0; 4])),
|
||||
("tofloat", Value::Float(0.0)),
|
||||
("tofloat2", Value::Float2([0.0; 2])),
|
||||
("tofloat3", Value::Float3([0.0; 3])),
|
||||
("tofloat4", Value::Float4([0.0; 4])),
|
||||
("toint2", Value::Int2([0; 2])),
|
||||
("toint3", Value::Int3([0; 3])),
|
||||
("toint4", Value::Int4([0; 4])),
|
||||
("and", Value::Bool(false)),
|
||||
("or", Value::Bool(false)),
|
||||
("not", Value::Bool(true)),
|
||||
("atan2", Value::Float(0.0)),
|
||||
("samplelum", Value::Float(0.0)),
|
||||
("samplecol", Value::Float4([0.0; 4])),
|
||||
] {
|
||||
let mut graph = FunctionGraph::default();
|
||||
let id = graph.add(operation, &[], None);
|
||||
graph.nodes.first_mut().unwrap().inputs.resize(definition(operation).unwrap().inputs.len(), None);
|
||||
graph.output = Some(id);
|
||||
let variables = Default::default();
|
||||
let context = EvaluationContext { scope: Default::default(), position: [0.5; 2], size: [16.0; 2], images: &[], tile: true, variables: &variables };
|
||||
|
||||
let value = compile(&graph, 0).unwrap().evaluate(&context, &mut EvaluationState::default());
|
||||
|
||||
assert_eq!(value, Ok(expected), "{operation}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn partially_connected_vectors_fill_only_the_missing_components() {
|
||||
for (operation, first, last, expected) in [
|
||||
("vector3", Some(Value::Float2([0.25, 0.75])), None, Value::Float3([0.25, 0.75, 0.0])),
|
||||
("vector4", None, Some(Value::Float2([0.25, 0.75])), Value::Float4([0.0, 0.0, 0.25, 0.75])),
|
||||
("ivector4", Some(Value::Int(7)), None, Value::Int4([7, 0, 0, 0])),
|
||||
] {
|
||||
let mut graph = FunctionGraph::default();
|
||||
let inputs = [first.map(|value| graph.add_constant(value)), last.map(|value| graph.add_constant(value))];
|
||||
let id = graph.add(operation, &[], None);
|
||||
graph.nodes.last_mut().unwrap().inputs = inputs.to_vec();
|
||||
graph.output = Some(id);
|
||||
let variables = Default::default();
|
||||
let context = EvaluationContext { scope: Default::default(), position: [0.5; 2], size: [16.0; 2], images: &[], tile: true, variables: &variables };
|
||||
|
||||
assert_eq!(compile(&graph, 0).unwrap().evaluate(&context, &mut EvaluationState::default()), Ok(expected), "{operation}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn partially_connected_dot_uses_the_connected_vector_width() {
|
||||
for vector in [Value::Float3([1.0, 2.0, 3.0]), Value::Float4([1.0, 2.0, 3.0, 4.0])] {
|
||||
for connected_slot in 0..2 {
|
||||
let mut graph = FunctionGraph::default();
|
||||
let source = graph.add_constant(vector.clone());
|
||||
let dot = graph.add("dot", &[], None);
|
||||
graph.nodes.last_mut().unwrap().inputs = if connected_slot == 0 { vec![Some(source), None] } else { vec![None, Some(source)] };
|
||||
graph.output = Some(dot);
|
||||
let variables = Default::default();
|
||||
let context = EvaluationContext { scope: Default::default(), position: [0.5; 2], size: [16.0; 2], images: &[], tile: true, variables: &variables };
|
||||
|
||||
assert_eq!(compile(&graph, 0).unwrap().evaluate(&context, &mut EvaluationState::default()), Ok(Value::Float(0.0)));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
use materialcraft_core::ValueType;
|
||||
|
||||
/// Missing operands have their port's type, which can differ from the result.
|
||||
pub(super) fn value_type(operation: &str, input_name: &str, inferred_type_code: u32, sibling_type_code: Option<u32>) -> ValueType {
|
||||
if matches!(input_name, "cond" | "condition") || matches!(operation, "and" | "or" | "not") {
|
||||
return ValueType::Boolean;
|
||||
}
|
||||
|
||||
if operation == "dot" {
|
||||
return sibling_type_code
|
||||
.and_then(ValueType::from_code)
|
||||
.filter(|kind| matches!(kind, ValueType::Float | ValueType::Float2 | ValueType::Float3 | ValueType::Float4))
|
||||
.unwrap_or(ValueType::Float2);
|
||||
}
|
||||
|
||||
if matches!(operation, "samplelum" | "samplecol" | "atan2") {
|
||||
return ValueType::Float2;
|
||||
}
|
||||
|
||||
if operation == "cartesian" || (operation == "mulscalar" && input_name == "scalar") {
|
||||
return ValueType::Float;
|
||||
}
|
||||
|
||||
let component_count = operation.chars().last().and_then(|character| character.to_digit(10)).unwrap_or(1);
|
||||
if operation.starts_with("tofloat") {
|
||||
return numeric_type(true, component_count);
|
||||
}
|
||||
|
||||
if operation.starts_with("toint") {
|
||||
return numeric_type(false, component_count);
|
||||
}
|
||||
|
||||
if operation.contains("swizzle") {
|
||||
return numeric_type(operation.starts_with('i'), 1);
|
||||
}
|
||||
|
||||
if operation.contains("vector") {
|
||||
let sibling_width = sibling_type_code.and_then(ValueType::from_code).map(|kind| match kind {
|
||||
ValueType::Integer2 | ValueType::Float2 => 2,
|
||||
ValueType::Integer3 | ValueType::Float3 => 3,
|
||||
ValueType::Integer4 | ValueType::Float4 => 4,
|
||||
_ => 1,
|
||||
});
|
||||
let width = sibling_width
|
||||
.map_or(if input_name == "componentslast" { 1 } else { component_count.saturating_sub(1) }, |width| component_count.saturating_sub(width));
|
||||
return numeric_type(operation.starts_with('i'), width);
|
||||
}
|
||||
|
||||
ValueType::from_code(inferred_type_code).unwrap_or(ValueType::Float)
|
||||
}
|
||||
|
||||
fn numeric_type(is_integer: bool, component_count: u32) -> ValueType {
|
||||
match (is_integer, component_count) {
|
||||
(true, 2) => ValueType::Integer2,
|
||||
(true, 3) => ValueType::Integer3,
|
||||
(true, 4) => ValueType::Integer4,
|
||||
(true, _) => ValueType::Integer,
|
||||
(false, 2) => ValueType::Float2,
|
||||
(false, 3) => ValueType::Float3,
|
||||
(false, 4) => ValueType::Float4,
|
||||
(false, _) => ValueType::Float,
|
||||
}
|
||||
}
|
||||
@@ -16,49 +16,54 @@ fn clamp_finite(v: f32, lo: f32, hi: f32, fallback: f32) -> f32 {
|
||||
if v.is_finite() { v.clamp(lo, hi) } else { fallback }
|
||||
}
|
||||
|
||||
pub fn clamp_params(def: &NodeDefinition, params: &mut BTreeMap<String, Value>) {
|
||||
for p in &def.params {
|
||||
let Some(v) = params.get_mut(p.id) else { continue };
|
||||
if let Value::Enum(i) = v {
|
||||
// (an enum without options has nothing to choose from: its default stands)
|
||||
*i = match (p.options.len().checked_sub(1), &p.default) {
|
||||
(Some(last), _) => (*i).min(u32::try_from(last).unwrap_or(u32::MAX)),
|
||||
(None, Value::Enum(d)) => *d,
|
||||
pub fn clamp_params(definition: &NodeDefinition, params: &mut BTreeMap<String, Value>) {
|
||||
for parameter in &definition.params {
|
||||
let Some(value) = params.get_mut(parameter.id) else { continue };
|
||||
if let Value::Enum(index) = value {
|
||||
// Shuffle resolves out-of-range selectors against the connected image kinds
|
||||
if definition.id == "channels_shuffle" && matches!(parameter.id, "red" | "green" | "blue" | "alpha") {
|
||||
continue;
|
||||
}
|
||||
|
||||
// An enum without options keeps its default
|
||||
*index = match (parameter.options.len().checked_sub(1), ¶meter.default) {
|
||||
(Some(last), _) => (*index).min(u32::try_from(last).unwrap_or(u32::MAX)),
|
||||
(None, Value::Enum(default)) => *default,
|
||||
(None, _) => 0,
|
||||
};
|
||||
continue;
|
||||
}
|
||||
|
||||
if let Value::Color(c) = v {
|
||||
for x in c {
|
||||
*x = clamp_finite(*x, -HARD_SPAN, 1.0 + HARD_SPAN, 0.0);
|
||||
if let Value::Color(components) = value {
|
||||
for component in components {
|
||||
*component = clamp_finite(*component, -HARD_SPAN, 1.0 + HARD_SPAN, 0.0);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
// An unconstrained Input Value accepts any number; reject only nonnumeric values
|
||||
let ranged = p.min < p.max;
|
||||
let span = p.max - p.min;
|
||||
let (lo, hi) = if ranged { (p.min - HARD_SPAN * span, p.max + HARD_SPAN * span) } else { (f32::MIN, f32::MAX) };
|
||||
let ranged = parameter.min < parameter.max;
|
||||
let span = parameter.max - parameter.min;
|
||||
let (lo, hi) = if ranged { (parameter.min - HARD_SPAN * span, parameter.max + HARD_SPAN * span) } else { (f32::MIN, f32::MAX) };
|
||||
|
||||
// The default's component `i`, or 0 when the default is a different variant
|
||||
let fallback = |i: usize| match &p.default {
|
||||
Value::Float(d) => [*d].get(i).copied(),
|
||||
Value::Float2(d) => d.get(i).copied(),
|
||||
Value::Float3(d) => d.get(i).copied(),
|
||||
Value::Float4(d) => d.get(i).copied(),
|
||||
// The default's component at `index`, or 0 for a different variant
|
||||
let fallback = |index: usize| match ¶meter.default {
|
||||
Value::Float(default) => [*default].get(index).copied(),
|
||||
Value::Float2(default) => default.get(index).copied(),
|
||||
Value::Float3(default) => default.get(index).copied(),
|
||||
Value::Float4(default) => default.get(index).copied(),
|
||||
_ => None,
|
||||
};
|
||||
|
||||
let clamp_at = |x: &mut f32, i: usize| *x = clamp_finite(*x, lo, hi, fallback(i).unwrap_or(0.0));
|
||||
let clamp_int = |x: &mut i32| *x = (*x as f32).clamp(lo, hi).round() as i32;
|
||||
match v {
|
||||
Value::Float(x) => clamp_at(x, 0),
|
||||
Value::Float2(a) => a.iter_mut().enumerate().for_each(|(i, x)| clamp_at(x, i)),
|
||||
Value::Float3(a) => a.iter_mut().enumerate().for_each(|(i, x)| clamp_at(x, i)),
|
||||
Value::Float4(a) => a.iter_mut().enumerate().for_each(|(i, x)| clamp_at(x, i)),
|
||||
Value::Int(x) if ranged => clamp_int(x),
|
||||
Value::Int2(a) if ranged => a.iter_mut().for_each(clamp_int),
|
||||
let clamp_at = |component: &mut f32, index: usize| *component = clamp_finite(*component, lo, hi, fallback(index).unwrap_or(0.0));
|
||||
let clamp_int = |component: &mut i32| *component = (*component as f32).clamp(lo, hi).round() as i32;
|
||||
match value {
|
||||
Value::Float(component) => clamp_at(component, 0),
|
||||
Value::Float2(components) => components.iter_mut().enumerate().for_each(|(index, component)| clamp_at(component, index)),
|
||||
Value::Float3(components) => components.iter_mut().enumerate().for_each(|(index, component)| clamp_at(component, index)),
|
||||
Value::Float4(components) => components.iter_mut().enumerate().for_each(|(index, component)| clamp_at(component, index)),
|
||||
Value::Int(component) if ranged => clamp_int(component),
|
||||
Value::Int2(components) if ranged => components.iter_mut().for_each(clamp_int),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -8,7 +8,16 @@ fn cook(graph: PatternGraph) -> crate::CookResult {
|
||||
|
||||
fn cook_with_variables(graph: PatternGraph, variables: &BTreeMap<String, Value>) -> crate::CookResult {
|
||||
let definition = find("fx_map").unwrap();
|
||||
let parameters = resolve_params(definition, &BTreeMap::from([("pattern".into(), Value::PatternGraph(Box::new(graph)))]));
|
||||
|
||||
// These traversal fixtures measure unattenuated grayscale stamps
|
||||
let parameters = resolve_params(
|
||||
definition,
|
||||
&BTreeMap::from([
|
||||
("pattern".into(), Value::PatternGraph(Box::new(graph))),
|
||||
("roughness".into(), Value::Float(0.0)),
|
||||
("color_mode".into(), Value::Bool(false)),
|
||||
]),
|
||||
);
|
||||
let context = CookContext {
|
||||
format: materialcraft_core::OutputFormat::F32,
|
||||
w: 16,
|
||||
@@ -214,7 +223,14 @@ fn a_full_nine_level_quadtree_renders_one_pattern_per_pixel() {
|
||||
}
|
||||
graph.nodes.last_mut().unwrap().parameters.insert("patterntype".into(), Value::Int(2));
|
||||
let definition = find("fx_map").unwrap();
|
||||
let parameters = resolve_params(definition, &BTreeMap::from([("pattern".into(), Value::PatternGraph(Box::new(graph)))]));
|
||||
let parameters = resolve_params(
|
||||
definition,
|
||||
&BTreeMap::from([
|
||||
("pattern".into(), Value::PatternGraph(Box::new(graph))),
|
||||
("roughness".into(), Value::Float(0.0)),
|
||||
("color_mode".into(), Value::Bool(false)),
|
||||
]),
|
||||
);
|
||||
let context = CookContext {
|
||||
format: materialcraft_core::OutputFormat::F32,
|
||||
w: 256,
|
||||
@@ -322,7 +338,14 @@ fn a_pixel_on_the_seam_of_two_patterns_is_drawn_once() {
|
||||
graph.nodes[1].parameters.insert("patterntype".into(), Value::Int(0));
|
||||
square(&mut graph, 2);
|
||||
let definition = find("fx_map").unwrap();
|
||||
let parameters = resolve_params(definition, &BTreeMap::from([("pattern".into(), Value::PatternGraph(Box::new(graph)))]));
|
||||
let parameters = resolve_params(
|
||||
definition,
|
||||
&BTreeMap::from([
|
||||
("pattern".into(), Value::PatternGraph(Box::new(graph))),
|
||||
("roughness".into(), Value::Float(0.0)),
|
||||
("color_mode".into(), Value::Bool(false)),
|
||||
]),
|
||||
);
|
||||
let variables = BTreeMap::new();
|
||||
|
||||
// Two pixels a side put every pixel center on the corner of four of the sixteen squares
|
||||
|
||||
@@ -1,13 +1,28 @@
|
||||
use craft_texture::{Image, Kind};
|
||||
use craft_texture::{Image, Kind, luminance};
|
||||
|
||||
use crate::CookContext;
|
||||
|
||||
pub(crate) fn composite(context: &CookContext, foreground: impl Fn(u32, u32) -> [f32; 4] + Sync) -> Image {
|
||||
let background = context.any_or(0, Kind::Color, context.v4("background"));
|
||||
let image = Image::generate(context.w, context.h, Kind::Color, |x, y| {
|
||||
let kind = if context.b("color_mode") { Kind::Color } else { Kind::Gray };
|
||||
let background = match context.input(0) {
|
||||
Some(image) if image.kind() == kind => image.resize(context.w, context.h, context.tile),
|
||||
|
||||
// An incompatible connection replaces the constant background with empty pixels
|
||||
Some(_) => Image::filled(1, 1, kind, [0.0; 4]),
|
||||
None => Image::filled(1, 1, Kind::Color, context.v4("background")),
|
||||
};
|
||||
let gray_background = background.is_gray();
|
||||
|
||||
// Clamped sampling broadcasts constant backgrounds from one pixel
|
||||
Image::generate(context.w, context.h, kind, |x, y| {
|
||||
let foreground = foreground(x, y);
|
||||
let background = background.get(i64::from(x), i64::from(y), false);
|
||||
let foreground_alpha = foreground[3].clamp(0.0, 1.0);
|
||||
if foreground_alpha == 0.0 {
|
||||
// Empty content must preserve hidden RGB in a transparent background
|
||||
return if kind == Kind::Gray && !gray_background { [luminance(background), 0.0, 0.0, 0.0] } else { background };
|
||||
}
|
||||
|
||||
let background_alpha = background[3].clamp(0.0, 1.0) * (1.0 - foreground_alpha);
|
||||
let alpha = foreground_alpha + background_alpha;
|
||||
if alpha <= 0.0 {
|
||||
@@ -15,8 +30,7 @@ pub(crate) fn composite(context: &CookContext, foreground: impl Fn(u32, u32) ->
|
||||
}
|
||||
|
||||
let channel = |index: usize| (foreground[index] * foreground_alpha + background[index] * background_alpha) / alpha;
|
||||
[channel(0), channel(1), channel(2), alpha]
|
||||
});
|
||||
|
||||
if context.b("color_mode") { image } else { image.to_gray() }
|
||||
let pixel = [channel(0), channel(1), channel(2), alpha];
|
||||
if kind == Kind::Gray { [luminance(pixel), 0.0, 0.0, 0.0] } else { pixel }
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,156 @@
|
||||
use craft_texture::{Image, Kind};
|
||||
use materialcraft_core::{OutputFormat, Value};
|
||||
use materialcraft_nodes::{CookContext, find, resolve_params};
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
fn cook(id: &str, inputs: &[Option<Image>], values: &[(&str, Value)], size: [u32; 2], tile: bool) -> Image {
|
||||
let definition = find(id).unwrap();
|
||||
let values = values.iter().map(|(key, value)| ((*key).into(), value.clone())).collect();
|
||||
let params = resolve_params(definition, &values);
|
||||
let resource = |_: &str| None;
|
||||
let vars = BTreeMap::new();
|
||||
let context = CookContext { w: size[0], h: size[1], seed: 0, format: OutputFormat::F32, tile, inputs, params: ¶ms, resource: &resource, vars: &vars };
|
||||
(definition.cook)(&context).unwrap().remove(0)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shuffle_reads_grayscale_from_every_selected_channel() {
|
||||
let inputs = [Some(Image::filled(3, 5, Kind::Gray, [0.25; 4])), Some(Image::filled(3, 5, Kind::Gray, [0.75; 4]))];
|
||||
for channel in 0..8 {
|
||||
let params = ["red", "green", "blue", "alpha"].map(|key| (key, Value::Enum(channel)));
|
||||
|
||||
let output = cook("channels_shuffle", &inputs, ¶ms, [3, 5], true);
|
||||
|
||||
assert_eq!(output.get(1, 2, false), [if channel < 4 { 0.25 } else { 0.75 }; 4], "channel {channel}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shuffle_wraps_selectors_over_the_eight_input_channels() {
|
||||
let inputs = [Some(Image::filled(3, 5, Kind::Color, [0.125, 0.25, 0.375, 0.5])), Some(Image::filled(3, 5, Kind::Color, [0.625, 0.75, 0.875, 1.0]))];
|
||||
for channel in [0, 3, 4, 7, 8, 9, 10, 16, 255] {
|
||||
let params = ["red", "green", "blue", "alpha"].map(|key| (key, Value::Enum(channel)));
|
||||
|
||||
let output = cook("channels_shuffle", &inputs, ¶ms, [3, 5], true);
|
||||
|
||||
assert_eq!(output.get(1, 2, false), [(channel % 8 + 1) as f32 / 8.0; 4], "channel {channel}");
|
||||
}
|
||||
assert_eq!(find("channels_shuffle").unwrap().param("red").unwrap().options.len(), 8);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shuffle_resolves_out_of_range_selectors_after_input_kind() {
|
||||
for kinds in [[Kind::Gray, Kind::Gray], [Kind::Color, Kind::Gray], [Kind::Gray, Kind::Color]] {
|
||||
let inputs = [Some(Image::filled(3, 5, kinds[0], [0.125, 0.25, 0.375, 0.5])), Some(Image::filled(3, 5, kinds[1], [0.625, 0.75, 0.875, 1.0]))];
|
||||
let params = [("red", Value::Enum(8)), ("green", Value::Enum(9)), ("blue", Value::Enum(11)), ("alpha", Value::Enum(u32::MAX - 1))];
|
||||
|
||||
let output = cook("channels_shuffle", &inputs, ¶ms, [3, 5], true);
|
||||
|
||||
let expected = if kinds[1] == Kind::Gray { [0.625; 4] } else { [0.125, 0.125, 1.0, 0.875] };
|
||||
|
||||
assert_eq!(output.get(1, 2, false), expected, "kinds {kinds:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sharpen_preserves_float_order_on_ramps() {
|
||||
let input = Image::gray(16, 16, |x, _| x as f32 / 15.0);
|
||||
|
||||
let output = cook("sharpen", &[Some(input)], &[("intensity", Value::Float(1.0))], [16, 16], true);
|
||||
|
||||
// Float32 ramps distinguish the Laplacian's arithmetic order
|
||||
for (x, bits) in [(1, 0x3d88_8889), (3, 0x3e4c_cccb), (7, 0x3eee_eeed), (13, 0x3f5d_ddde)] {
|
||||
assert_eq!(output.get_gray(x, 7, false).to_bits(), bits, "column {x}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sharpen_preserves_finite_hdr_constant() {
|
||||
let constant = 2.0e38;
|
||||
let input = Image::filled(16, 16, Kind::Gray, [constant; 4]);
|
||||
|
||||
let output = cook("sharpen", &[Some(input)], &[("intensity", Value::Float(1.0))], [16, 16], true);
|
||||
|
||||
assert!(output.data().iter().all(|value| value.to_bits() == constant.to_bits()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn blur_uses_fractional_box_coverage() {
|
||||
let input = Image::gray(16, 16, |x, y| f32::from(x == 8 && y == 8));
|
||||
|
||||
let output = cook("blur", &[Some(input)], &[("intensity", Value::Float(10.0))], [16, 16], true);
|
||||
|
||||
// A 0.625-pixel radius covers the center pixel and one eighth of each neighbor
|
||||
for (x, y, expected) in [(8, 8, 0.64), (7, 8, 0.08), (8, 7, 0.08), (7, 7, 0.01), (6, 8, 0.0)] {
|
||||
assert!((output.get_gray(x, y, false) - expected).abs() < 1e-7, "at {x},{y}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn blur_preserves_finite_hdr_constant() {
|
||||
let input = Image::filled(16, 16, Kind::Gray, [1.0e38; 4]);
|
||||
|
||||
let output = cook("blur", &[Some(input)], &[("intensity", Value::Float(64.0))], [16, 16], true);
|
||||
|
||||
assert!(output.data().iter().all(|value| value.is_finite() && (*value - 1.0e38).abs() < 1.0e32));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn directional_blur_uses_full_radius_and_fractional_endpoints() {
|
||||
let input = Image::gray(256, 256, |x, y| f32::from(x == 128 && y == 128));
|
||||
|
||||
let output = cook("directional_blur", &[Some(input)], &[("intensity", Value::Float(4.0))], [256, 256], true);
|
||||
|
||||
for offset in -4..=4 {
|
||||
let expected = if offset == -4 || offset == 4 { 0.0625 } else { 0.125 };
|
||||
|
||||
assert_eq!(output.get_gray(128 + offset, 128, false), expected, "offset {offset}");
|
||||
}
|
||||
assert_eq!(output.get_gray(128, 129, false), 0.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sharpen_has_center_gain_and_clamps_negative_lobes() {
|
||||
let input = Image::gray(16, 16, |x, y| f32::from(x == 8 && y == 8));
|
||||
|
||||
let output = cook("sharpen", &[Some(input)], &[("intensity", Value::Float(1.0))], [16, 16], true);
|
||||
|
||||
assert_eq!(output.get_gray(8, 8, false), 5.0);
|
||||
assert!(output.data().iter().all(|value| *value >= 0.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn empty_raster_preserves_transparent_rgb_and_rejects_mismatched_background_kind() {
|
||||
for id in ["text", "svg"] {
|
||||
let pixel = [0.25, 0.5, 0.75, 0.0];
|
||||
let color = Some(Image::filled(16, 16, Kind::Color, pixel));
|
||||
let gray = Some(Image::filled(16, 16, Kind::Gray, [0.25; 4]));
|
||||
|
||||
let output = cook(id, std::slice::from_ref(&color), &[("color_mode", Value::Bool(true))], [16, 16], true);
|
||||
|
||||
assert_eq!(output.get(0, 0, false), pixel, "{id} transparent color");
|
||||
|
||||
let output = cook(id, &[color], &[("color_mode", Value::Bool(false))], [16, 16], true);
|
||||
|
||||
assert_eq!(output.get_gray(0, 0, false), 0.0, "{id} color into gray");
|
||||
|
||||
let output = cook(id, &[gray], &[("color_mode", Value::Bool(true))], [16, 16], true);
|
||||
|
||||
assert_eq!(output.get(0, 0, false), [0.0; 4], "{id} gray into color");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rectangular_filters_scale_from_the_shorter_side() {
|
||||
for size in [[32, 16], [16, 32]] {
|
||||
let input = Image::gray(size[0], size[1], |x, y| f32::from(x == size[0] / 2 && y == size[1] / 2));
|
||||
for (operation, expected) in [("blur", 0.64), ("directional_blur", 0.8)] {
|
||||
let output = cook(operation, &[Some(input.clone())], &[("intensity", Value::Float(10.0))], size, true);
|
||||
|
||||
assert!((output.get_gray(i64::from(size[0] / 2), i64::from(size[1] / 2), false) - expected).abs() < 1e-7, "{operation}, {size:?}");
|
||||
}
|
||||
let output = cook("sharpen", &[Some(input)], &[("intensity", Value::Float(1.0))], size, true);
|
||||
|
||||
assert_eq!(output.get_gray(i64::from(size[0] / 2), i64::from(size[1] / 2), false), 4.0, "{size:?}");
|
||||
}
|
||||
}
|
||||
@@ -3,8 +3,15 @@ use materialcraft_core::{FunctionGraph, PatternGraph, PatternNodeKind, Value};
|
||||
use materialcraft_nodes::{CookContext, find, resolve_params};
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
fn cook(def: &str, values: BTreeMap<String, Value>, inputs: &[Option<Image>]) -> Image {
|
||||
fn cook(def: &str, mut values: BTreeMap<String, Value>, inputs: &[Option<Image>]) -> Image {
|
||||
let definition = find(def).unwrap();
|
||||
|
||||
// Geometry and maximum-blend fixtures use unattenuated grayscale patterns
|
||||
if def == "fx_map" {
|
||||
values.entry("roughness".into()).or_insert(Value::Float(0.0));
|
||||
values.entry("color_mode".into()).or_insert(Value::Bool(false));
|
||||
}
|
||||
|
||||
let params = resolve_params(definition, &values);
|
||||
let context = CookContext {
|
||||
format: materialcraft_core::OutputFormat::F32,
|
||||
|
||||
@@ -0,0 +1,56 @@
|
||||
use craft_texture::Kind;
|
||||
use materialcraft_core::{OutputFormat, Value};
|
||||
use materialcraft_nodes::{CookContext, find, resolve_params};
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
#[test]
|
||||
fn absent_textures_have_zero_pixels_and_expected_kinds() {
|
||||
for (id, kind, pixel) in [
|
||||
("channels_shuffle", Kind::Color, [0.0; 4]),
|
||||
("hsl", Kind::Color, [0.0; 4]),
|
||||
("emboss", Kind::Gray, [0.0, 0.0, 0.0, 1.0]),
|
||||
("gradient_dynamic", Kind::Gray, [0.0, 0.0, 0.0, 1.0]),
|
||||
] {
|
||||
let definition = find(id).unwrap();
|
||||
let params = resolve_params(definition, &BTreeMap::new());
|
||||
let resource = |_: &str| None;
|
||||
let vars = BTreeMap::new();
|
||||
for (w, h) in [(16, 16), (32, 16), (3, 5)] {
|
||||
let context = CookContext { w, h, seed: 0, format: OutputFormat::F32, tile: true, inputs: &[], params: ¶ms, resource: &resource, vars: &vars };
|
||||
|
||||
let outputs = (definition.cook)(&context).unwrap();
|
||||
let image = outputs.first().unwrap();
|
||||
|
||||
assert_eq!(image.kind(), kind, "{id}");
|
||||
for y in 0..h {
|
||||
for x in 0..w {
|
||||
assert_eq!(image.get(x.into(), y.into(), false), pixel, "{id} at {x},{y}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fresh_catalog_defaults_have_expected_values() {
|
||||
for (id, parameter, expected) in [
|
||||
("uniform", "color", Value::Color([0.0, 0.0, 0.0, 1.0])),
|
||||
("blur", "intensity", Value::Float(10.0)),
|
||||
("distance", "combine", Value::Bool(true)),
|
||||
("emboss", "light_angle", Value::Float(0.0)),
|
||||
("emboss", "shadow", Value::Color([0.0; 4])),
|
||||
("fx_map", "roughness", Value::Float(1.0)),
|
||||
("fx_map", "color_mode", Value::Bool(true)),
|
||||
("gradient_dynamic", "position", Value::Float(0.0)),
|
||||
("grayscale_conversion", "matte", Value::Float(1.0)),
|
||||
("normal", "opengl", Value::Bool(false)),
|
||||
("normal", "height_alpha", Value::Bool(true)),
|
||||
("text", "fontsize", Value::Float(0.25)),
|
||||
("text", "text", Value::Text(String::new())),
|
||||
] {
|
||||
assert_eq!(find(id).unwrap().param(parameter).unwrap().default, expected, "{id}.{parameter}");
|
||||
}
|
||||
for (op, expected) in [("const_float1", Value::Float(0.0)), ("const_float4", Value::Float4([0.0; 4])), ("while", Value::Int(32))] {
|
||||
assert_eq!(materialcraft_nodes::function::default_value(op), Some(expected), "{op}");
|
||||
}
|
||||
}
|
||||
@@ -247,7 +247,7 @@ impl Default for Settings {
|
||||
tiling: 1.0,
|
||||
exposure: 0.0,
|
||||
env_rotation: 0.0,
|
||||
normal_y_flip: false,
|
||||
normal_y_flip: true,
|
||||
show_env: false,
|
||||
supersample: 1,
|
||||
ao_rays: 0,
|
||||
|
||||
@@ -11,43 +11,48 @@ fn app() -> MaterialCraftApp {
|
||||
app
|
||||
}
|
||||
|
||||
fn settle(h: &mut Harness<'static, MaterialCraftApp>, after: u64) {
|
||||
for _ in 0..300 {
|
||||
h.step();
|
||||
let app = h.state();
|
||||
fn settle(harness: &mut Harness<'static, MaterialCraftApp>, after: u64) {
|
||||
const RENDER_ATTEMPTS: usize = 300;
|
||||
const POLL_INTERVAL: Duration = Duration::from_millis(10);
|
||||
for _ in 0..RENDER_ATTEMPTS {
|
||||
harness.step();
|
||||
let app = harness.state();
|
||||
if app.view3d.renders > after && !app.session.dirty && !app.cooker.busy() && !app.view3d.busy() {
|
||||
return;
|
||||
}
|
||||
std::thread::sleep(Duration::from_millis(10));
|
||||
|
||||
std::thread::sleep(POLL_INTERVAL);
|
||||
}
|
||||
panic!("the normal-map preview did not finish rendering");
|
||||
}
|
||||
|
||||
fn toggle(h: &mut Harness<'static, MaterialCraftApp>) {
|
||||
h.get_by_label("Display").click();
|
||||
h.run_steps(4);
|
||||
h.get_by_label("Flip normal map Y (DirectX)").click();
|
||||
h.run_steps(4);
|
||||
fn toggle(harness: &mut Harness<'static, MaterialCraftApp>) {
|
||||
harness.get_by_label("Display").click();
|
||||
harness.run_steps(4);
|
||||
harness.get_by_label("Flip normal map Y (DirectX)").click();
|
||||
harness.run_steps(4);
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore = "requires an offscreen GPU; run explicitly with --ignored"]
|
||||
fn normal_convention_snapshot() {
|
||||
let mut h = Harness::builder().with_size(vec2(1400.0, 860.0)).wgpu().build_ui_state(
|
||||
let mut harness = Harness::builder().with_size(vec2(1400.0, 860.0)).wgpu().build_ui_state(
|
||||
|ui, app: &mut MaterialCraftApp| {
|
||||
app.step(&ui.ctx().clone());
|
||||
app.draw(ui);
|
||||
},
|
||||
app(),
|
||||
);
|
||||
settle(&mut h, 0);
|
||||
let rendered = h.state().view3d.renders;
|
||||
toggle(&mut h);
|
||||
settle(&mut h, rendered);
|
||||
h.get_by_label("Display").click();
|
||||
h.run_steps(4);
|
||||
assert!(h.state().session.view3d.normal_y_flip);
|
||||
let dir = std::path::PathBuf::from(std::env::var_os("MC_SNAPSHOT_DIR").expect("MC_SNAPSHOT_DIR"));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
h.render().unwrap().save(dir.join("normal-convention.png")).unwrap();
|
||||
settle(&mut harness, 0);
|
||||
let rendered = harness.state().view3d.renders;
|
||||
toggle(&mut harness);
|
||||
settle(&mut harness, rendered);
|
||||
harness.get_by_label("Display").click();
|
||||
harness.run_steps(4);
|
||||
|
||||
assert!(!harness.state().session.view3d.normal_y_flip);
|
||||
|
||||
let snapshot_dir = std::path::PathBuf::from(std::env::var_os("MC_SNAPSHOT_DIR").expect("MC_SNAPSHOT_DIR"));
|
||||
std::fs::create_dir_all(&snapshot_dir).unwrap();
|
||||
harness.render().unwrap().save(snapshot_dir.join("normal-convention.png")).unwrap();
|
||||
}
|
||||
@@ -12,7 +12,7 @@ L0 core document model: Package → Graph → Node / Connection / Frame /
|
||||
L0 image the craft-texture crate from storytold/craft-libs: grayscale or RGBA f32 planes behind an
|
||||
Arc (free to share); repeat/clamp sampling, bilinear, box/bilinear resampling, sRGB, 8-bit display
|
||||
L0 geom meshes, primitives (rounded cube, sphere, cylinder, plane, torus, material ball), BVH, camera
|
||||
L1 nodes 30 main-graph entries (NodeDefinition), 85 function operations, four pattern node kinds;
|
||||
L1 nodes 29 main-graph entries (NodeDefinition), 85 function operations, four pattern node kinds;
|
||||
shared image operations and iterative function/pattern execution
|
||||
L2 eval cooking: topological order, output sizes (relative to input / parent, absolute, preview
|
||||
cap), parameter resolution (defaults, overrides, bindings to exposed inputs), the
|
||||
|
||||
@@ -0,0 +1,62 @@
|
||||
# Atomic node corrections
|
||||
|
||||
These changes correct filtering, channel selection and empty-content compositing in
|
||||
MaterialCraft. Catalog membership and bundled SBS assets are unchanged.
|
||||
|
||||
## Behavior changes
|
||||
|
||||
- Blur uses a separable box filter with fractional endpoint coverage and bounded running
|
||||
sums. Non-finite samples stop affecting a window after they leave it.
|
||||
- Directional Blur uses the full radius, weighted endpoints and image-space rotation.
|
||||
Its sampling budget is bounded for large strengths.
|
||||
- Sharpen uses a four-neighbor Laplacian, processes alpha, clamps negative lobes and retains
|
||||
HDR output. Explicit Float32 operation order preserves cancellation behavior on ramps.
|
||||
- All three filters scale from the shorter image dimension and honor horizontal and
|
||||
vertical tiling independently. Tiling changes invalidate the cook cache.
|
||||
- Channels Shuffle supplies a grayscale scalar through all ordinary channel selections,
|
||||
including alpha. Color inputs retain their alpha. Signed and oversized saved selectors
|
||||
remain intact until input kinds determine channel selection.
|
||||
- Empty Text/SVG content preserves background pixels, including hidden RGB under zero
|
||||
alpha. Incompatible background kinds produce empty pixels; matching gray backgrounds
|
||||
retain their scalar values.
|
||||
|
||||
Channels Shuffle now offers eight input-channel choices. Graphs using the former
|
||||
Black/White choices follow the corrected selector behavior. Use a Uniform Color input
|
||||
for constant channels.
|
||||
|
||||
## Regression coverage
|
||||
|
||||
Local tests cover fractional filter footprints, directional extent, sharpen gain and
|
||||
Float32 cancellation, rectangular images, independent tiling and cache invalidation,
|
||||
gray/color channel selection, signed-selector round trips and transparent backgrounds:
|
||||
|
||||
- [Filter and channel tests](../crates/nodes/tests/atomic_filter_parity.rs)
|
||||
- [Tiling and cache tests](../crates/eval/tests/filter_tiling.rs)
|
||||
- [SBS round-trip tests](../crates/formats/src/sbs/tests.rs)
|
||||
|
||||
Save/load fixtures use explicit blur strengths and compatible background kinds so their
|
||||
binding and connection-preservation assertions retain their purpose.
|
||||
|
||||
## Remaining limits
|
||||
|
||||
Full numerical compatibility remains unestablished. Open work includes oblique sampling,
|
||||
floating-point rounding and quantization, mixed input/output resolutions, non-default
|
||||
Sharpen alpha behavior and nonempty Text/SVG rasterization. Processor and map execution
|
||||
limits are summarized in the [catalog status](node-catalog-parity.md).
|
||||
|
||||
## Validation
|
||||
|
||||
Recorded release tests for nodes, formats, eval and engine pass, including
|
||||
`every_node_cooks` and `panic_hunt`. Formatting,
|
||||
workspace Clippy with `--all-targets -- -D warnings`, dependency layers and all ten wasm
|
||||
checks pass.
|
||||
|
||||
These checks cover the listed crates and targets; other build and runtime environments
|
||||
have not been validated by this local run.
|
||||
|
||||
The optional `filter_timing` example benchmarks MaterialCraft's Blur, Directional Blur
|
||||
and Sharpen on generated images at 512 and 1024 pixels. It uses no external application:
|
||||
|
||||
```sh
|
||||
cargo run -p materialcraft-nodes --release --example filter_timing
|
||||
```
|
||||
@@ -61,10 +61,15 @@ cargo +1.96.0 run -p materialcraft-engine --release --example atomic_sample -- e
|
||||
|
||||
| Context | Entries |
|
||||
|---|---:|
|
||||
| Main graph | 26 native primitives, including processors and reroute, plus 4 input/output items |
|
||||
| Main graph | 25 native primitives, including processors and reroute, plus 4 input/output items |
|
||||
| Functions | 85 native operations |
|
||||
| FX-Map graph | Quadrant (`paramset`), Switch (`markov2`), Iterate (`addnode`), Dot (`passthrough`) |
|
||||
|
||||
The former count of 26 primitives included `motion_blur`, removed in commit `a0032d6`.
|
||||
It was a MaterialCraft wrapper around Directional Blur. The count of 25 includes Dot/reroute.
|
||||
The [catalog status](node-catalog-parity.md) records the current 25 primitives plus four
|
||||
input/output entries.
|
||||
|
||||
Image primitives have individual files in `crates/nodes/src/atomic/`. Function evaluation and
|
||||
pattern traversal have separate modules. Document types each live in their own file under
|
||||
`crates/core/src/`. SBS parsing and writing live under `crates/formats/src/sbs/`.
|
||||
@@ -82,9 +87,9 @@ SBS library reference resolution is outside this change.
|
||||
|
||||
## Current limits
|
||||
|
||||
- Reopening the generated SBS in the reference application has not been verified
|
||||
- Native IDs, ports and types are mapped, but numerical parity with the reference renderer has
|
||||
not been established, including pattern shapes, blending, sampling and random sequences
|
||||
- SBS version-header compatibility remains unresolved
|
||||
- Node IDs, ports and types are mapped. The [catalog status](node-catalog-parity.md) records
|
||||
remaining numerical and interoperability gaps; broad rendering parity is unestablished
|
||||
- Text renders the original built-in stroke font; external font references produce an explicit
|
||||
error. SVG supports vector geometry, without external images or font loading
|
||||
- Some native parameter variants and package/editor metadata remain unsupported; import reports
|
||||
|
||||
@@ -116,7 +116,7 @@ Types: `move`, `down`, `up`, `click`, `doubleClick`, `drag`, `scroll`, `key` (eg
|
||||
| `graph.node.reset` | `{id?, param?, base?}` removes the driver and restores defaults; omit `param` to reset the selected parameter section |
|
||||
| `graph.preset.save` / `.apply` / `.delete` | `{name}`: store, restore or remove the current input values |
|
||||
| `graph.createFromSelection` | `{name?, ids?}`: move nodes into a sub-graph and replace them with an instance |
|
||||
| `view.2d` / `view.3d` | which node the 2D view shows, channel, tiling, histogram; scene, environment, camera, tiling, `heightScale` (how far the height output raises the mesh, in mesh radii) and `heightLevel` (the height that stays on the surface; 0 = the relief rises out of it), `normalYFlip` (interpret DirectX normal maps; default false/OpenGL), `transparency` (see through where the alpha is below one: the opacity output, else the base color's alpha), `alphaView` (show the alpha channel) |
|
||||
| `view.2d` / `view.3d` | which node the 2D view shows, channel, tiling, histogram; scene, environment, camera, tiling, `heightScale` (how far the height output raises the mesh, in mesh radii) and `heightLevel` (the height that stays on the surface; 0 = the relief rises out of it), `normalYFlip` (interpret DirectX normal maps; default true/DirectX), `transparency` (see through where the alpha is below one: the opacity output, else the base color's alpha), `alphaView` (show the alpha channel) |
|
||||
| `view.3d.loadMesh` | `{path}` shows an OBJ, glTF or GLB mesh (scene `custom`) |
|
||||
| `library.list` | `{filter?, category?}`: every node with ports and parameters |
|
||||
| `library.tree` | `{filter?, category? (Top or Top/Sub), canvas? (material\|function\|pattern)}`: the Library panel's category tree and its entries. Each entry has `id`, `label`, `category`, `type` (`node`, `comment`, `frame`, `pin`, `instance`, `operation`, `functionInstance`, `pattern`, `bitmap`), the `canvas` that takes it (`any` for shared graph items), `missing` when MaterialCraft lacks the library package it needs, and `warning` when it can be added but is incomplete |
|
||||
|
||||
@@ -1,5 +1,10 @@
|
||||
# Gaps
|
||||
|
||||
The [catalog status](node-catalog-parity.md) records implemented corrections and untested
|
||||
behavior, including all 954 loaded package function bodies. The
|
||||
[atomic corrections](atomic-parity-improvements.md) cover filters, channel selection and
|
||||
empty Text/SVG backgrounds. Sampling, precision, processor and map gaps remain open.
|
||||
|
||||
> The assessment below predates the 2026-11-05 primitive rewrite. Its old library counts and
|
||||
> compatibility claims are historical. See [atomic-workflow.md](atomic-workflow.md) and
|
||||
> [ROADMAP.md](../ROADMAP.md) for the current scope and remaining validation.
|
||||
|
||||
@@ -0,0 +1,57 @@
|
||||
# Node catalog status
|
||||
|
||||
MaterialCraft is a clean-room implementation. This page summarizes available catalogs,
|
||||
implemented corrections and remaining compatibility work.
|
||||
|
||||
## Inventory
|
||||
|
||||
| Catalog | Entries |
|
||||
|---|---:|
|
||||
| Main graph | 29: 25 primitives and four input/output items |
|
||||
| Function graph | 85 operations |
|
||||
| FX-Map graph | Quadrant, Switch, Iterate and Dot |
|
||||
| Loaded package functions | 954, including 689 hidden entries |
|
||||
|
||||
The earlier count of 26 primitives included the removed `motion_blur` wrapper around
|
||||
Directional Blur. The current count of 25 includes Dot/reroute. These corrections change
|
||||
no catalog membership.
|
||||
|
||||
Package counts describe availability. Function-body behavior and redistribution rights
|
||||
require separate verification; the 954 loaded package function bodies remain untested.
|
||||
|
||||
## Implemented corrections
|
||||
|
||||
- Missing function operands use their input types, including vectors, casts, Boolean
|
||||
operations and sampler coordinates. Partially connected vectors retain connected lanes.
|
||||
- Missing textures produce appropriate zero pixels and image kinds in Channels Shuffle,
|
||||
HSL, Emboss and Dynamic Gradient.
|
||||
- Fresh-node defaults are corrected for Uniform Color, function constants, loop limits
|
||||
and several image and pattern nodes.
|
||||
- Grayscale image-input defaults serialize as scalars. Function loop limits use the scalar
|
||||
integer tag. Channel selector values survive signed SBS save/load.
|
||||
- Filter kernels, rectangular scaling, independent tiling, channel selection and empty
|
||||
Text/SVG backgrounds are covered in [atomic node corrections](atomic-parity-improvements.md).
|
||||
|
||||
Regression coverage lives in the nodes, formats and eval test suites. These tests execute
|
||||
MaterialCraft code and use original procedural fixtures.
|
||||
|
||||
## Remaining work
|
||||
|
||||
Full behavioral parity is unestablished. Outstanding areas include:
|
||||
|
||||
- Filter sampling, image boundaries and output sizing.
|
||||
- Scalar/vector conversions, invalid-input handling, overflow and precision policy.
|
||||
- Function execution order, shared state, loop behavior and variable scope.
|
||||
- Random sequences, sampler coordinates and explicit addressing modes.
|
||||
- FX-Map shape rasterization, roughness/depth weighting and assignment scope.
|
||||
- Nonempty text/vector rendering, arbitrary SBS round trips and version-header compatibility.
|
||||
|
||||
Exhaustive parameter combinations, deeply nested processors/maps, arbitrary non-finite
|
||||
payloads, dynamic resource selection and every resolution/aspect ratio remain untested.
|
||||
Local safety tests cover cycles, allocation limits and execution budgets.
|
||||
|
||||
## Validation limits
|
||||
|
||||
Release suites for nodes, formats, eval and engine pass locally, including the
|
||||
SBS resource-substitution test. Formatting, workspace Clippy, dependency layers
|
||||
and wasm checks pass. Other targets and runtime environments remain unverified.
|
||||
@@ -1,5 +1,11 @@
|
||||
# Parity with the reference workflow
|
||||
|
||||
The [catalog status](node-catalog-parity.md) covers 29 main-graph entries, 85 function
|
||||
operations, four map kinds and 954 loaded package functions. The
|
||||
[atomic corrections](atomic-parity-improvements.md) describe filter, channel-selection
|
||||
and background fixes with local regression coverage. Full numerical parity remains
|
||||
unestablished.
|
||||
|
||||
> The assessment below predates the 2026-11-05 primitive rewrite. Its old library counts and
|
||||
> compatibility claims are historical. See [atomic-workflow.md](atomic-workflow.md) and
|
||||
> [ROADMAP.md](../ROADMAP.md) for the current scope and remaining validation.
|
||||
|
||||
@@ -86,11 +86,11 @@ session.
|
||||
|
||||
## Alpha in the 3D view
|
||||
|
||||
The 3D view reads OpenGL normal maps by default, matching the Normal node's default format.
|
||||
For a DirectX normal map, enable **Display ▸ Flip normal map Y (DirectX)**, or run
|
||||
`view.3d {"normalYFlip": true}`. Choose the corresponding format in the Normal node's properties.
|
||||
The 3D view reads DirectX normal maps by default, matching the Normal node's default format.
|
||||
For an OpenGL normal map, disable **Display ▸ Flip normal map Y (DirectX)**, or run
|
||||
`view.3d {"normalYFlip": false}`. Choose the corresponding format in the Normal node's properties.
|
||||
The setting affects both the interactive view and headless renders, appears as `view3d.normalYFlip`
|
||||
in `session.inspect`, and returns to OpenGL when the scene is reset.
|
||||
in `session.inspect`, and returns to DirectX when the scene is reset.
|
||||
|
||||
<p align="center">
|
||||
<img src="images/materialcraft-alpha-channel.png" alt="The same sphere in the alpha channel view: the opaque grid lines are white and the clear gaps black" width="100%">
|
||||
|
||||
@@ -8,20 +8,23 @@ static site in `materialcraft-web-<version>/`:
|
||||
| `index.html` | The page. It loads everything through relative URLs. |
|
||||
| `materialcraft-web-<hash>.js` | wasm-bindgen glue (generated by trunk, ES module) |
|
||||
| `materialcraft-web-<hash>_bg.wasm` | The app (built with the `wasm-release` Cargo profile) |
|
||||
| `sbs/resources/` | The SBS library's bitmaps and their licences, downloaded when the app starts |
|
||||
| `_headers`, `.htaccess` | Sample header rules for Netlify/Cloudflare Pages and Apache |
|
||||
|
||||
There is no server-side code and no hand-written JavaScript: trunk generates the glue from the
|
||||
Rust crate `apps/materialcraft-web`. Upload the folder's contents anywhere that serves static files.
|
||||
|
||||
`packaging/web/package.sh` fails the build when a `.wasm` grows past 24 MiB, because Cloudflare
|
||||
Pages and Workers reject any file over 25 MiB.
|
||||
Pages and Workers reject any file over 25 MiB. That is why the SBS library's bitmaps ship in
|
||||
`sbs/resources/` instead of inside the wasm.
|
||||
|
||||
## Any path works
|
||||
|
||||
All URLs in `index.html` are relative (`public_url = "./"` in `apps/materialcraft-web/Trunk.toml`),
|
||||
so the site works at a domain root (`https://example.com/`), under a prefix
|
||||
(`https://example.com/tools/materialcraft/`) and from a CDN bucket. The asset names carry a content
|
||||
hash, so they can be cached forever. Only `index.html` needs revalidation.
|
||||
hash, so they can be cached forever. `index.html` and the files in `sbs/` have no hash and need
|
||||
revalidation.
|
||||
|
||||
## Required server settings
|
||||
|
||||
|
||||
Reference in new issue
Block a user