diff --git a/AGENTS.md b/AGENTS.md index 2d250fed..f89a6590 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -89,7 +89,7 @@ file first, then `docs/`. ```text crates/ - core image geom L0 document model (package, graphs, nodes, values, function graphs); float images; meshes, BVH, camera + core geom L0 document model (package, graphs, nodes, values, function graphs); meshes, BVH, camera nodes L1 the node library: native primitive definitions + CPU cooks, function evaluator and pattern graphs eval formats L2 graph cooking (topological order, sizes, content-addressed cache, sub-graphs); native .sbs packages, bitmaps, texture export engine render L3 Session + command registry (every action is a command), inspect, samples; the 3D preview renderer (CPU PBR + IBL) diff --git a/Cargo.lock b/Cargo.lock index 4fadfc61..cb4631bf 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -810,7 +810,7 @@ dependencies = [ [[package]] name = "craft-dialogs" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=6e03f65bf45181db77ba6229716e6624db9eb25b#6e03f65bf45181db77ba6229716e6624db9eb25b" +source = "git+https://github.com/storytold/craft-libs?rev=29fb8f8e860677e375263f9c8f4debe129d7add4#29fb8f8e860677e375263f9c8f4debe129d7add4" dependencies = [ "block2 0.6.2", "objc2 0.6.5", @@ -823,12 +823,12 @@ dependencies = [ [[package]] name = "craft-fonts-build" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=6e03f65bf45181db77ba6229716e6624db9eb25b#6e03f65bf45181db77ba6229716e6624db9eb25b" +source = "git+https://github.com/storytold/craft-libs?rev=29fb8f8e860677e375263f9c8f4debe129d7add4#29fb8f8e860677e375263f9c8f4debe129d7add4" [[package]] name = "craft-i18n" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=6e03f65bf45181db77ba6229716e6624db9eb25b#6e03f65bf45181db77ba6229716e6624db9eb25b" +source = "git+https://github.com/storytold/craft-libs?rev=29fb8f8e860677e375263f9c8f4debe129d7add4#29fb8f8e860677e375263f9c8f4debe129d7add4" dependencies = [ "fixed_decimal", "icu_decimal", @@ -851,7 +851,7 @@ dependencies = [ [[package]] name = "craft-keymap" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=6e03f65bf45181db77ba6229716e6624db9eb25b#6e03f65bf45181db77ba6229716e6624db9eb25b" +source = "git+https://github.com/storytold/craft-libs?rev=29fb8f8e860677e375263f9c8f4debe129d7add4#29fb8f8e860677e375263f9c8f4debe129d7add4" dependencies = [ "egui", "serde", @@ -861,7 +861,7 @@ dependencies = [ [[package]] name = "craft-menu" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=6e03f65bf45181db77ba6229716e6624db9eb25b#6e03f65bf45181db77ba6229716e6624db9eb25b" +source = "git+https://github.com/storytold/craft-libs?rev=29fb8f8e860677e375263f9c8f4debe129d7add4#29fb8f8e860677e375263f9c8f4debe129d7add4" dependencies = [ "craft-keymap", "craft-quit", @@ -874,7 +874,7 @@ dependencies = [ [[package]] name = "craft-quit" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=6e03f65bf45181db77ba6229716e6624db9eb25b#6e03f65bf45181db77ba6229716e6624db9eb25b" +source = "git+https://github.com/storytold/craft-libs?rev=29fb8f8e860677e375263f9c8f4debe129d7add4#29fb8f8e860677e375263f9c8f4debe129d7add4" dependencies = [ "dispatch2", "egui", @@ -882,10 +882,19 @@ dependencies = [ "objc2-app-kit 0.3.2", ] +[[package]] +name = "craft-texture" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=29fb8f8e860677e375263f9c8f4debe129d7add4#29fb8f8e860677e375263f9c8f4debe129d7add4" +dependencies = [ + "rayon", + "thiserror 2.0.21", +] + [[package]] name = "craft-ui" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=6e03f65bf45181db77ba6229716e6624db9eb25b#6e03f65bf45181db77ba6229716e6624db9eb25b" +source = "git+https://github.com/storytold/craft-libs?rev=29fb8f8e860677e375263f9c8f4debe129d7add4#29fb8f8e860677e375263f9c8f4debe129d7add4" dependencies = [ "craft-fonts-build", "craft-i18n", @@ -906,7 +915,7 @@ dependencies = [ [[package]] name = "craft-update" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=6e03f65bf45181db77ba6229716e6624db9eb25b#6e03f65bf45181db77ba6229716e6624db9eb25b" +source = "git+https://github.com/storytold/craft-libs?rev=29fb8f8e860677e375263f9c8f4debe129d7add4#29fb8f8e860677e375263f9c8f4debe129d7add4" dependencies = [ "chrono", "dunce", @@ -933,7 +942,7 @@ dependencies = [ [[package]] name = "craft-window" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=6e03f65bf45181db77ba6229716e6624db9eb25b#6e03f65bf45181db77ba6229716e6624db9eb25b" +source = "git+https://github.com/storytold/craft-libs?rev=29fb8f8e860677e375263f9c8f4debe129d7add4#29fb8f8e860677e375263f9c8f4debe129d7add4" dependencies = [ "egui", "objc2 0.6.5", @@ -2664,11 +2673,11 @@ dependencies = [ name = "materialcraft-engine" version = "0.4.1" dependencies = [ + "craft-texture", "materialcraft-core", "materialcraft-eval", "materialcraft-formats", "materialcraft-geom", - "materialcraft-image", "materialcraft-nodes", "serde", "serde_json", @@ -2679,8 +2688,8 @@ dependencies = [ name = "materialcraft-eval" version = "0.4.1" dependencies = [ + "craft-texture", "materialcraft-core", - "materialcraft-image", "materialcraft-nodes", "serde", "serde_json", @@ -2692,13 +2701,13 @@ version = "0.4.1" dependencies = [ "base64 0.22.1", "bytemuck", + "craft-texture", "dds", "flate2", "gltf", "image", "materialcraft-core", "materialcraft-geom", - "materialcraft-image", "materialcraft-nodes", "resvg", "roxmltree 0.20.0", @@ -2720,20 +2729,12 @@ dependencies = [ "thiserror 2.0.21", ] -[[package]] -name = "materialcraft-image" -version = "0.4.1" -dependencies = [ - "rayon", - "thiserror 2.0.21", -] - [[package]] name = "materialcraft-nodes" version = "0.4.1" dependencies = [ + "craft-texture", "materialcraft-core", - "materialcraft-image", "rayon", ] @@ -2741,9 +2742,9 @@ dependencies = [ name = "materialcraft-render" version = "0.4.1" dependencies = [ + "craft-texture", "materialcraft-core", "materialcraft-geom", - "materialcraft-image", "rayon", ] diff --git a/Cargo.toml b/Cargo.toml index a5be53c8..14ab52ca 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -2,7 +2,6 @@ resolver = "3" members = [ "crates/core", - "crates/image", "crates/geom", "crates/nodes", "crates/eval", @@ -20,7 +19,6 @@ exclude = ["vendor"] # The web app only builds for wasm32 (trunk); everything else is the default. default-members = [ "crates/core", - "crates/image", "crates/geom", "crates/nodes", "crates/eval", @@ -45,7 +43,6 @@ repository = "https://github.com/storytold/materialcraft" resvg = { version = "0.47", default-features = false } # internal materialcraft-core = { path = "crates/core" } -materialcraft-image = { path = "crates/image" } materialcraft-geom = { path = "crates/geom" } materialcraft-nodes = { path = "crates/nodes" } materialcraft-eval = { path = "crates/eval" } @@ -86,18 +83,20 @@ getrandom = "0.3" # Shared Craft egui components (widget palette, icon buttons, panel docking): storytold/craft-libs, # MIT OR Apache-2.0, every craft-libs crate pinned to one rev. egui_kittest = "0.37" -craft-ui = { git = "https://github.com/storytold/craft-libs", rev = "6e03f65bf45181db77ba6229716e6624db9eb25b", features = ["serde"] } +craft-ui = { git = "https://github.com/storytold/craft-libs", rev = "29fb8f8e860677e375263f9c8f4debe129d7add4", features = ["serde"] } # Keyboard bindings (chords, dispatch and display text): storytold/craft-libs, MIT OR Apache-2.0. -craft-keymap = { git = "https://github.com/storytold/craft-libs", rev = "6e03f65bf45181db77ba6229716e6624db9eb25b", features = ["egui"] } +craft-keymap = { git = "https://github.com/storytold/craft-libs", rev = "29fb8f8e860677e375263f9c8f4debe129d7add4", features = ["egui"] } # Native dialogs that do not block the event loop: storytold/craft-libs, MIT OR Apache-2.0. -craft-dialogs = { git = "https://github.com/storytold/craft-libs", rev = "6e03f65bf45181db77ba6229716e6624db9eb25b" } +craft-dialogs = { git = "https://github.com/storytold/craft-libs", rev = "29fb8f8e860677e375263f9c8f4debe129d7add4" } # The platform quit and the macOS Quit menu item: storytold/craft-libs, MIT OR Apache-2.0. -craft-quit = { git = "https://github.com/storytold/craft-libs", rev = "6e03f65bf45181db77ba6229716e6624db9eb25b", features = ["egui"] } -craft-menu = { git = "https://github.com/storytold/craft-libs", rev = "6e03f65bf45181db77ba6229716e6624db9eb25b" } +craft-quit = { git = "https://github.com/storytold/craft-libs", rev = "29fb8f8e860677e375263f9c8f4debe129d7add4", features = ["egui"] } +craft-menu = { git = "https://github.com/storytold/craft-libs", rev = "29fb8f8e860677e375263f9c8f4debe129d7add4" } # Who draws the window frame, and an app-drawn strip as the title bar: storytold/craft-libs, MIT OR Apache-2.0. -craft-window = { git = "https://github.com/storytold/craft-libs", rev = "6e03f65bf45181db77ba6229716e6624db9eb25b", features = ["egui"] } +craft-window = { git = "https://github.com/storytold/craft-libs", rev = "29fb8f8e860677e375263f9c8f4debe129d7add4", features = ["egui"] } # Release checks and self-updates for the desktop app: storytold/craft-libs, MIT OR Apache-2.0. -craft-update = { git = "https://github.com/storytold/craft-libs", rev = "6e03f65bf45181db77ba6229716e6624db9eb25b", features = ["egui"] } +craft-update = { git = "https://github.com/storytold/craft-libs", rev = "29fb8f8e860677e375263f9c8f4debe129d7add4", features = ["egui"] } +# Float image planes and texture sampling for node cooking: storytold/craft-libs, MIT OR Apache-2.0. +craft-texture = { git = "https://github.com/storytold/craft-libs", rev = "29fb8f8e860677e375263f9c8f4debe129d7add4", features = ["parallel"] } # egui 0.37 and winit: the suite's forks (storytold/egui, storytold/winit), as craft-libs pins them. [patch.crates-io] @@ -154,7 +153,7 @@ strip = "debuginfo" opt-level = "s" # Node cooking and the vector math under it run per pixel. -[profile.wasm-release.package.materialcraft-image] +[profile.wasm-release.package.craft-texture] opt-level = 3 [profile.wasm-release.package.materialcraft-nodes] opt-level = 3 diff --git a/README.md b/README.md index b577b346..0dc94287 100644 --- a/README.md +++ b/README.md @@ -185,7 +185,7 @@ operations and three pattern node kinds. Start with **File → New → Atomic sa 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. -**Workspace:** `crates/{core, image, geom, nodes, eval, formats, engine, render, automation, ui-egui}` +**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 crate, so the UI can be swapped without touching the engine; [`docs/architecture.md`](docs/architecture.md) explains how it fits together. diff --git a/crates/automation/src/headless.rs b/crates/automation/src/headless.rs index 836fcdfe..4c34f3c6 100644 --- a/crates/automation/src/headless.rs +++ b/crates/automation/src/headless.rs @@ -270,7 +270,7 @@ impl Headless { None => self.session.view2d_image().map(|(_, i)| i).ok_or_else(|| bad("nothing to show: the graph has no outputs; pass `node`"))?, }; - let (w, h) = (o.width.unwrap_or(img.w).clamp(16, max), o.height.unwrap_or(img.h).clamp(16, max)); + let (w, h) = (o.width.unwrap_or(img.width()).clamp(16, max), o.height.unwrap_or(img.height()).clamp(16, max)); let img = img.resize(w, h, true); Ok((w, h, img.to_rgba8_display())) } diff --git a/crates/engine/Cargo.toml b/crates/engine/Cargo.toml index 5eb7c489..309cbd38 100644 --- a/crates/engine/Cargo.toml +++ b/crates/engine/Cargo.toml @@ -10,7 +10,7 @@ workspace = true [dependencies] materialcraft-core = { workspace = true } -materialcraft-image = { workspace = true } +craft-texture = { workspace = true } materialcraft-nodes = { workspace = true } materialcraft-eval = { workspace = true } materialcraft-formats = { workspace = true } diff --git a/crates/engine/src/graph_cmds.rs b/crates/engine/src/graph_cmds.rs index 5f115af1..a05ee94d 100644 --- a/crates/engine/src/graph_cmds.rs +++ b/crates/engine/src/graph_cmds.rs @@ -168,7 +168,7 @@ fn cook(s: &mut Session, p: &J) -> Result { "nodes": cooked.nodes.iter().map(|(id, r)| { let n = g.node(*id).ok(); json!({"id": id.0, "def": n.map(|n| n.def.clone()), "ms": r.ms, "cached": r.cached, "error": r.error, - "size": r.outputs.first().and_then(materialcraft_eval::NodeOutput::as_image).map(|i| [i.w, i.h])}) + "size": r.outputs.first().and_then(materialcraft_eval::NodeOutput::as_image).map(|i| [i.width(), i.height()])}) }).collect::>(), })) } diff --git a/crates/engine/src/inspect.rs b/crates/engine/src/inspect.rs index d410c295..1f7f242e 100644 --- a/crates/engine/src/inspect.rs +++ b/crates/engine/src/inspect.rs @@ -32,7 +32,7 @@ pub fn session(session: &Session, requested_graph: Option) -> J { "error": entry.error, "ms": entry.ms, "cached": entry.cached, "base": entry.base, "baseValues": entry.base_values, "parameters": entry.parameters, "value": entry.outputs.first().and_then(materialcraft_eval::NodeOutput::as_value), - "size": entry.outputs.first().and_then(materialcraft_eval::NodeOutput::as_image).map(|image| [image.w, image.h]), + "size": entry.outputs.first().and_then(materialcraft_eval::NodeOutput::as_image).map(|image| [image.width(), image.height()]), "kind": entry.outputs.first().and_then(materialcraft_eval::NodeOutput::as_image).map(|image| if image.is_gray() { "gray" } else { "color" }), "mean": entry.outputs.first().and_then(materialcraft_eval::NodeOutput::as_image).map(|image| image.mean()), })); @@ -81,7 +81,7 @@ pub fn session(session: &Session, requested_graph: Option) -> J { "assignments": session.material_preview, "channels": session.material_preview.sources(&session.pkg).into_iter().map(|(channel, source)| { let image = session.material_image(&source); - json!({"channel": channel, "source": source, "size": image.map(|image| [image.w, image.h]), "mean": image.map(|image| image.mean())}) + json!({"channel": channel, "source": source, "size": image.map(|image| [image.width(), image.height()]), "mean": image.map(|image| image.mean())}) }).collect::>(), }, "previewSize": session.preview_size, diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 7557cc81..d882eaca 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -82,10 +82,10 @@ pub use color_space::ColorSpace; pub use export_request::ExportRequest; pub use export_size::ExportSize; +pub use craft_texture as image; pub use materialcraft_core as core; pub use materialcraft_eval as eval; pub use materialcraft_formats as formats; -pub use materialcraft_image as image; pub use materialcraft_nodes as nodes; mod engine_error; diff --git a/crates/engine/src/material_cmds.rs b/crates/engine/src/material_cmds.rs index d262c674..d42f8685 100644 --- a/crates/engine/src/material_cmds.rs +++ b/crates/engine/src/material_cmds.rs @@ -3,14 +3,14 @@ use std::collections::BTreeMap; use serde_json::{Value as J, json}; +#[cfg(test)] +use craft_texture::Image; use materialcraft_core::ComponentUsage; use materialcraft_core::Graph; #[cfg(any(test, not(target_arch = "wasm32")))] use materialcraft_core::Value; use materialcraft_formats::material::{FORMAT, ImageInput, Manifest, MapEntry, Parameter, PresetEntry, VERSION, portable, srgb_usage}; use materialcraft_formats::{Depth, encode}; -#[cfg(test)] -use materialcraft_image::Image; #[cfg(not(target_arch = "wasm32"))] use crate::commands::u64p; @@ -81,7 +81,7 @@ pub fn material_bytes(s: &Session, gi: usize, o: &MaterialOptions) -> Result = s.group("Temporary", |s| { execute(s, "graph.node.param", &json!({"id": id.0, "param": "color", "value": [0.1, 0.8, 0.2, 1.0]}))?; s.cook(); @@ -195,5 +195,5 @@ fn a_failed_group_recooks_if_it_cooked_a_temporary_document() { }); assert!(result.is_err()); s.cook_if_dirty(); - assert_eq!(s.cooked.image(id, 0).unwrap().data, before); + assert_eq!(s.cooked.image(id, 0).unwrap().data(), before.as_slice()); } diff --git a/crates/engine/tests/it/atomics.rs b/crates/engine/tests/it/atomics.rs index 968fab93..08069ad1 100644 --- a/crates/engine/tests/it/atomics.rs +++ b/crates/engine/tests/it/atomics.rs @@ -70,8 +70,8 @@ fn atomic_sample_round_trips_through_native_fields_and_cooks_identically() { assert!(result.error.is_none(), "{}: {:?}", after.def, result.error); match (original.cooked.image(before.id, 0), loaded.cooked.image(after.id, 0)) { (Some(before), Some(after)) => { - assert_eq!((before.w, before.h, before.kind), (after.w, after.h, after.kind)); - let error = before.data.iter().zip(after.data.iter()).map(|(a, b)| (a - b).abs()).fold(0.0_f32, f32::max); + assert_eq!((before.width(), before.height(), before.kind()), (after.width(), after.height(), after.kind())); + let error = before.data().iter().zip(after.data()).map(|(a, b)| (a - b).abs()).fold(0.0_f32, f32::max); assert!(error < 1e-5, "pixel error {error}"); } (None, None) => assert_eq!(original.cooked.value(before.id, 0), loaded.cooked.value(after.id, 0)), @@ -177,10 +177,10 @@ fn exposed_parameter_binding_remains_live_after_saving() { let mut loaded = Session::new(loaded.pkg); loaded.preview_size = Some(32); loaded.cook(); - let before = loaded.cooked.image(blur, 0).unwrap().data.clone(); + 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, loaded.cooked.image(blur, 0).unwrap().data); + assert_ne!(before.as_slice(), loaded.cooked.image(blur, 0).unwrap().data()); } #[test] diff --git a/crates/engine/tests/it/export_names.rs b/crates/engine/tests/it/export_names.rs index c9c8065c..e1c15ce1 100644 --- a/crates/engine/tests/it/export_names.rs +++ b/crates/engine/tests/it/export_names.rs @@ -104,7 +104,7 @@ fn unique_export_writes_both_maps_with_their_expected_pixels() { assert_eq!(result["files"].as_array().unwrap().len(), 2); for (name, value) in [("first.png", 0.2), ("second.png", 0.8)] { let image = formats::decode(&std::fs::read(dir.0.join(name)).unwrap(), false).unwrap(); - assert_eq!((image.w, image.h), (16, 16)); + assert_eq!((image.width(), image.height()), (16, 16)); assert!((image.get(0, 0, false)[0] - value).abs() < 0.001, "{name}"); } } diff --git a/crates/engine/tests/it/parameter_functions.rs b/crates/engine/tests/it/parameter_functions.rs index 2aed371b..849ec5c4 100644 --- a/crates/engine/tests/it/parameter_functions.rs +++ b/crates/engine/tests/it/parameter_functions.rs @@ -25,7 +25,7 @@ fn output_size_function_controls_resolution_and_survives_sbs() { let cooked = session.cook(); let image = cooked.image(owner, 0).unwrap(); - assert_eq!((image.w, image.h), (128, 32)); + assert_eq!((image.width(), image.height()), (128, 32)); assert!(cooked.nodes[&owner].error.is_none()); let bytes = formats::sbs::write_sbs(&session.pkg).unwrap(); @@ -36,7 +36,7 @@ fn output_size_function_controls_resolution_and_survives_sbs() { let owner = reopened.graph().unwrap().nodes.iter().find(|node| node.def == "uniform").unwrap().id; let cooked = reopened.cook(); let image = cooked.image(owner, 0).unwrap(); - assert_eq!((image.w, image.h), (128, 32)); + assert_eq!((image.width(), image.height()), (128, 32)); } #[test] @@ -90,7 +90,7 @@ fn native_dynamic_output_size_is_not_discarded_on_load() { let cooked = session.cook(); let image = cooked.image(owner, 0).unwrap(); - assert_eq!((image.w, image.h), (64, 32)); + assert_eq!((image.width(), image.height()), (64, 32)); } #[test] @@ -120,7 +120,7 @@ fn inherited_size_functions_use_nominal_input_size_before_preview_capping() { assert_eq!(cooked.nodes[&owner].error, None); assert_eq!(cooked.nodes[&owner].base.size, [256, 64]); assert_eq!(cooked.nodes[&owner].base_values[&BaseParameter::OutputSize], Value::Int2([1, 0])); - assert_eq!((cooked.image(owner, 0).unwrap().w, cooked.image(owner, 0).unwrap().h), (16, 4)); + assert_eq!((cooked.image(owner, 0).unwrap().width(), cooked.image(owner, 0).unwrap().height()), (16, 4)); command( &mut session, @@ -265,7 +265,7 @@ fn instance_parameter_functions_work_without_stored_literals_and_use_instance_si assert_eq!(result.nodes[&owner].error, None); assert!(result.nodes[&owner].outputs.iter().any(|output| output.as_value() == Some(&Value::Float2([64.0, 32.0])))); assert!((result.image(owner, 0).unwrap().get_gray(0, 0, false) - 0.75).abs() < 1e-6); - assert_eq!((result.image(owner, 0).unwrap().w, result.image(owner, 0).unwrap().h), (64, 32)); + assert_eq!((result.image(owner, 0).unwrap().width(), result.image(owner, 0).unwrap().height()), (64, 32)); assert!(!session.graph().unwrap().node(owner).unwrap().params.contains_key("amount")); let bytes = formats::sbs::write_sbs(&session.pkg).unwrap(); @@ -335,7 +335,7 @@ fn base_functions_inherit_from_the_primary_input_and_bypasses_keep_input_dimensi let cooked = session.cook(); let image = cooked.image(blend, 0).unwrap(); - assert_eq!((image.w, image.h), (16, 16)); + assert_eq!((image.width(), image.height()), (16, 16)); assert_eq!(cooked.nodes[&blend].base.size, [32, 32]); assert_eq!(cooked.nodes[&output].base.size, [32, 32]); } diff --git a/crates/engine/tests/it/subgraph_seed.rs b/crates/engine/tests/it/subgraph_seed.rs index 070f5fcc..569dec96 100644 --- a/crates/engine/tests/it/subgraph_seed.rs +++ b/crates/engine/tests/it/subgraph_seed.rs @@ -26,20 +26,20 @@ fn grouping_noise_preserves_pixels_seed_and_undo() { // Force an actual cook instead of relying on the pre-grouping cache entry. s.cache.lock().unwrap().clear(); let after = s.cook().image(output, 0).unwrap().clone(); - assert!(before.data == after.data, "grouping changed the material at graph seed {seed}"); - assert_eq!((after.w, after.h), (64, 32)); + assert!(before.data() == after.data(), "grouping changed the material at graph seed {seed}"); + assert_eq!((after.width(), after.height()), (64, 32)); assert_eq!(s.pkg.graphs[1].seed, seed); let grouped_graphs = s.pkg.graphs.clone(); run(&mut s, "edit.undo", json!({})); assert_eq!(s.pkg.graphs, before_graphs); - assert_eq!(s.cook().image(output, 0).unwrap().data, before.data); + assert_eq!(s.cook().image(output, 0).unwrap().data(), before.data()); run(&mut s, "edit.redo", json!({})); assert_eq!(s.pkg.graphs, grouped_graphs); - assert_eq!(s.cook().image(output, 0).unwrap().data, before.data); + assert_eq!(s.cook().image(output, 0).unwrap().data(), before.data()); let bytes = formats::sbs::write_sbs(&s.pkg).unwrap(); let mut reopened = Session::new(formats::sbs::read_sbs(&bytes, "seed.sbs", &|_| None).unwrap().pkg); reopened.preview_size = None; let reopened_output = reopened.graph().unwrap().nodes.iter().find(|node| node.def == "output").unwrap().id; - assert_eq!(reopened.cook().image(reopened_output, 0).unwrap().data, before.data); + assert_eq!(reopened.cook().image(reopened_output, 0).unwrap().data(), before.data()); } } diff --git a/crates/engine/tests/session.rs b/crates/engine/tests/session.rs index d46abadf..d967e072 100644 --- a/crates/engine/tests/session.rs +++ b/crates/engine/tests/session.rs @@ -87,7 +87,7 @@ fn package_save_and_open_round_trip() { run(&mut s, "file.export", json!({"dir": small.to_str().unwrap(), "format": "png", "depth": 8, "size": 64})); let file = std::fs::read_dir(&small).unwrap().next().unwrap().unwrap().path(); let img = materialcraft_formats::decode(&std::fs::read(file).unwrap(), false).unwrap(); - assert_eq!((img.w, img.h), (64, 64)); + assert_eq!((img.width(), img.height()), (64, 64)); let _ = std::fs::remove_dir_all(&dir); } @@ -101,7 +101,7 @@ fn export_size_keeps_proportions_and_clamps() { let dims = |s: &Session, size: Value| { let request = ExportRequest::from_params(s, &json!({"size": size})).unwrap(); let files = materialcraft_engine::file_cmds::export_outputs(s, &request).unwrap(); - files.iter().map(|f| materialcraft_formats::decode(&f.bytes, false).unwrap()).map(|i| (i.w, i.h)).collect::>() + files.iter().map(|f| materialcraft_formats::decode(&f.bytes, false).unwrap()).map(|i| (i.width(), i.height())).collect::>() }; let parsed = |s: &Session, size: Value| ExportRequest::from_params(s, &json!({"size": size})).map(|request| request.size); @@ -369,17 +369,17 @@ fn camera_prefs_bound_the_pan_and_survive_hostile_values() { #[test] fn reimported_bitmap_shows_new_pixels() { + use craft_texture::{Image, Kind}; use materialcraft_formats::{Depth, encode}; - use materialcraft_image::{Image, Kind}; let bmp = |v: f32| encode(&Image::filled(4, 4, Kind::Color, [v, v, v, 1.0]), "bmp", Depth::U8, true).unwrap(); let (dark, light) = (bmp(0.1), bmp(0.9)); assert_eq!(dark.len(), light.len(), "same-size files are the case under test"); let mut s = sample_session(); materialcraft_engine::file_cmds::add_resource(&mut s, "tex.bmp", dark, Some("tex")).unwrap(); - let before = s.resource_decoder()("tex").unwrap().data[0]; + let before = s.resource_decoder()("tex").unwrap().data()[0]; s.undo(); materialcraft_engine::file_cmds::add_resource(&mut s, "tex.bmp", light, Some("tex")).unwrap(); - let after = s.resource_decoder()("tex").unwrap().data[0]; + let after = s.resource_decoder()("tex").unwrap().data()[0]; assert!(after - before > 0.5, "{before} -> {after}"); } @@ -423,7 +423,7 @@ fn every_template_is_opaque_in_the_3d_view() { s.cook(); for (usage, img) in s.material_maps() { if usage == "baseColor" && !img.is_gray() { - let min = img.data.chunks(4).map(|p| p[3]).fold(f32::INFINITY, f32::min); + let min = img.data().chunks(4).map(|p| p[3]).fold(f32::INFINITY, f32::min); assert!(min >= 0.999, "{id}: base color alpha goes down to {min}"); } } diff --git a/crates/eval/Cargo.toml b/crates/eval/Cargo.toml index e30a1ef7..54e97be7 100644 --- a/crates/eval/Cargo.toml +++ b/crates/eval/Cargo.toml @@ -10,7 +10,7 @@ workspace = true [dependencies] materialcraft-core = { workspace = true } -materialcraft-image = { workspace = true } +craft-texture = { workspace = true } materialcraft-nodes = { workspace = true } serde_json = { workspace = true } serde = { workspace = true } diff --git a/crates/eval/src/cache_key.rs b/crates/eval/src/cache_key.rs index fb0d8a2c..a0d3aed7 100644 --- a/crates/eval/src/cache_key.rs +++ b/crates/eval/src/cache_key.rs @@ -1,25 +1,25 @@ use crate::{Cache, identifier}; +use craft_texture::Image; use materialcraft_core::{Node, Package, Value}; -use materialcraft_image::Image; use std::collections::{BTreeMap, HashSet}; use std::hash::{DefaultHasher, Hash, Hasher}; use std::sync::{Arc, Mutex}; pub(crate) fn image_key(i: &Image, cache: &Mutex) -> u64 { - let ptr = Arc::as_ptr(&i.data) as usize; - let shape = (i.w, i.h, i.kind.channels()); + let ptr = Arc::as_ptr(i.shared_data()) as usize; + let shape = (i.width(), i.height(), i.channels()); if let Some(key) = cache .lock() .unwrap_or_else(std::sync::PoisonError::into_inner) .input_hashes .get(&ptr) - .and_then(|saved| saved.buffer.upgrade().filter(|data| Arc::ptr_eq(data, &i.data) && saved.shape == shape).map(|_| saved.key)) + .and_then(|saved| saved.buffer.upgrade().filter(|data| Arc::ptr_eq(data, i.shared_data()) && saved.shape == shape).map(|_| saved.key)) { return key; } let mut h = DefaultHasher::new(); - (shape, i.data.len()).hash(&mut h); - for value in i.data.iter() { + (shape, i.data().len()).hash(&mut h); + for value in i.data() { value.to_bits().hash(&mut h); } let key = h.finish(); @@ -30,7 +30,7 @@ pub(crate) fn image_key(i: &Image, cache: &Mutex) -> u64 { cache.input_hashes.clear(); } } - cache.input_hashes.insert(ptr, crate::input_fingerprint::InputFingerprint { buffer: Arc::downgrade(&i.data), shape, key }); + cache.input_hashes.insert(ptr, crate::input_fingerprint::InputFingerprint { buffer: Arc::downgrade(i.shared_data()), shape, key }); key } diff --git a/crates/eval/src/cooked.rs b/crates/eval/src/cooked.rs index c64675b4..3c7e0759 100644 --- a/crates/eval/src/cooked.rs +++ b/crates/eval/src/cooked.rs @@ -1,6 +1,6 @@ use crate::NodeResult; +use craft_texture::Image; use materialcraft_core::NodeId; -use materialcraft_image::Image; use std::collections::BTreeMap; /// Results of a cook, by node diff --git a/crates/eval/src/graph_execution.rs b/crates/eval/src/graph_execution.rs index 9f1b364f..c3c18c8a 100644 --- a/crates/eval/src/graph_execution.rs +++ b/crates/eval/src/graph_execution.rs @@ -1,7 +1,7 @@ use crate::{Cache, Cooked, Options, now_ms}; use crate::{node_execution::cook_node, prepared_graph::PreparedGraph}; +use craft_texture::Image; use materialcraft_core::{Package, Value}; -use materialcraft_image::Image; use std::{ collections::BTreeMap, sync::{Mutex, atomic::Ordering}, @@ -19,7 +19,7 @@ pub fn cook(package: &Package, graph_index: usize, options: &Options, cache: &Mu .input_images .iter() .filter_map(|(id, resource)| { - Some((id.clone(), (options.resource)(&materialcraft_image::resource_key(resource, graph.input_images_linear.contains(id)))?)) + Some((id.clone(), (options.resource)(&craft_texture::resource_key(resource, graph.input_images_linear.contains(id)))?)) }) .collect(); inputs.extend(options.inputs.iter().map(|(name, value)| (name.clone(), value.clone()))); diff --git a/crates/eval/src/graph_instance.rs b/crates/eval/src/graph_instance.rs index db0fd837..d7f75baf 100644 --- a/crates/eval/src/graph_instance.rs +++ b/crates/eval/src/graph_instance.rs @@ -64,8 +64,8 @@ pub(crate) fn cook_instance( let root_resource = opts.resource_root.unwrap_or(opts.resource); let resource = |name: &str| match &node.instance { Some(instance) if !instance.package.is_empty() => { - let (name, linear) = materialcraft_image::split_resource_key(name); - root_resource(&materialcraft_image::resource_key(&format!("{}\0{name}", instance.package), linear)) + let (name, linear) = craft_texture::split_resource_key(name); + root_resource(&craft_texture::resource_key(&format!("{}\0{name}", instance.package), linear)) } _ => (opts.resource)(name), }; diff --git a/crates/eval/src/graph_output.rs b/crates/eval/src/graph_output.rs index e96e0ff4..46f08620 100644 --- a/crates/eval/src/graph_output.rs +++ b/crates/eval/src/graph_output.rs @@ -9,7 +9,7 @@ pub fn output_usage(node: &Node) -> &'static str { }; ComponentUsage::from_index(index).id } -use materialcraft_image::Image; +use craft_texture::Image; /// The graph's output nodes with their usage id and image, in node order pub fn outputs<'c>(graph: &Graph, cooked: &'c Cooked) -> Vec<(NodeId, &'static str, String, Option<&'c Image>)> { diff --git a/crates/eval/src/node_execution.rs b/crates/eval/src/node_execution.rs index f94f7909..59b542c4 100644 --- a/crates/eval/src/node_execution.rs +++ b/crates/eval/src/node_execution.rs @@ -6,8 +6,8 @@ use crate::{ prepared_graph::PreparedGraph, value_execution::evaluate_value, }; +use craft_texture::{Image, Kind}; use materialcraft_core::{Node, Package, Value}; -use materialcraft_image::{Image, Kind}; use materialcraft_nodes::{CookContext, find}; use std::{ collections::BTreeMap, diff --git a/crates/eval/src/node_output.rs b/crates/eval/src/node_output.rs index d9c6f0ed..15d6e66b 100644 --- a/crates/eval/src/node_output.rs +++ b/crates/eval/src/node_output.rs @@ -1,5 +1,5 @@ +use craft_texture::Image; use materialcraft_core::Value; -use materialcraft_image::Image; #[derive(Clone, Debug, PartialEq)] pub enum NodeOutput { @@ -24,7 +24,7 @@ impl NodeOutput { pub(crate) fn memory_bytes(&self) -> usize { match self { - Self::Image(image) => image.data.len().saturating_mul(size_of::()), + Self::Image(image) => image.data().len().saturating_mul(size_of::()), Self::Value(Value::Text(text)) => size_of::().saturating_add(text.len()), Self::Value(_) => size_of::(), } diff --git a/crates/eval/src/options.rs b/crates/eval/src/options.rs index 8505d4d8..9beb3f06 100644 --- a/crates/eval/src/options.rs +++ b/crates/eval/src/options.rs @@ -1,5 +1,5 @@ +use craft_texture::Image; use materialcraft_core::{NodeId, Value}; -use materialcraft_image::Image; use std::collections::BTreeMap; use std::sync::atomic::AtomicBool; diff --git a/crates/eval/src/resource_decoder.rs b/crates/eval/src/resource_decoder.rs index 7ddbefa4..0ec37812 100644 --- a/crates/eval/src/resource_decoder.rs +++ b/crates/eval/src/resource_decoder.rs @@ -1,4 +1,4 @@ -use materialcraft_image::Image; +use craft_texture::Image; /// Decodes an image resource by name within the current package pub type ResourceDecoder<'a> = dyn Fn(&str) -> Option + Sync + 'a; diff --git a/crates/eval/src/tests.rs b/crates/eval/src/tests.rs index aff79949..46c55a29 100644 --- a/crates/eval/src/tests.rs +++ b/crates/eval/src/tests.rs @@ -1,6 +1,6 @@ use crate::{cache_key::graph_tree_hash, graph_instance::instances_reach}; +use craft_texture::{Image, Kind, Limits}; use materialcraft_core::{NodeId, Package, Value}; -use materialcraft_image::{Image, Kind}; use std::sync::Mutex; use std::sync::atomic::Ordering; @@ -31,7 +31,7 @@ fn cooks_and_caches() { let opts = Options::new(&no_res); let a = cook(&p, 0, &opts, &cache); assert!(a.nodes.values().all(|r| r.error.is_none() && !r.cached)); - assert_eq!(a.image(out, 0).map(|i| (i.w, i.h)), Some((64, 64))); + assert_eq!(a.image(out, 0).map(|i| (i.width(), i.height())), Some((64, 64))); // Same graph: everything from the cache let b = cook(&p, 0, &opts, &cache); assert!(b.nodes.values().all(|r| r.cached)); @@ -76,7 +76,7 @@ fn hostile_param_is_clamped_before_cooking() { let cache = Mutex::new(Cache::default()); let c = cook(&p, 0, &Options::new(&no_res), &cache); assert!(c.nodes[&blur].error.is_none(), "{:?}", c.nodes[&blur].error); - assert_eq!(c.image(blur, 0).map(|i| (i.w, i.h)), Some((64, 64))); + assert_eq!(c.image(blur, 0).map(|i| (i.width(), i.height())), Some((64, 64))); } #[test] @@ -88,7 +88,7 @@ fn preview_cap_and_unknown_nodes() { let mut opts = Options::new(&no_res); opts.max_size = Some(128); let c = cook(&p, 0, &opts, &cache); - assert_eq!(c.image(out, 0).map(|i| i.w), Some(128)); + assert_eq!(c.image(out, 0).map(|i| i.width()), Some(128)); assert!(c.nodes[&bad].error.is_some()); } @@ -119,7 +119,7 @@ fn graph_instances_cook_their_subgraph() { let cache = Mutex::new(Cache::default()); let c = cook(&p, 0, &Options::new(&no_res), &cache); let img = c.image(inst, 0).unwrap(); - assert!((img.data[0] - (1.0 - 0.0722 * 0.25 - 0.2126 * 0.25 - 0.7152 * 0.25)).abs() < 1e-4, "{}", img.data[0]); + assert!((img.data()[0] - (1.0 - 0.0722 * 0.25 - 0.2126 * 0.25 - 0.7152 * 0.25)).abs() < 1e-4, "{}", img.data()[0]); assert!(c.nodes[&selfi].error.as_deref().is_some_and(|e| e.contains("uses itself")), "{:?}", c.nodes[&selfi].error); } @@ -240,12 +240,12 @@ fn input_nodes_read_bound_preview_images() { let cache = Mutex::new(Cache::default()); let c = cook(&p, 0, &Options::new(&res), &cache); let img = c.image(o, 0).unwrap(); - assert!(img.is_gray() && (img.data[0] - 0.8).abs() < 1e-4, "bound image, as gray"); + assert!(img.is_gray() && (img.data()[0] - 0.8).abs() < 1e-4, "bound image, as gray"); // The caller's image wins over the bound one let mut opts = Options::new(&res); opts.inputs.insert("curvature".into(), Image::filled(4, 4, Kind::Gray, [0.1; 4])); let c = cook(&p, 0, &opts, &cache); - assert!((c.image(o, 0).unwrap().data[0] - 0.1).abs() < 1e-4); + assert!((c.image(o, 0).unwrap().data()[0] - 0.1).abs() < 1e-4); } #[test] @@ -317,14 +317,16 @@ use std::sync::Arc; #[test] fn cached_input_fingerprint_tracks_copy_on_write_and_shape() { let cache = Mutex::new(Cache::default()); - let mut image = Image::filled(128, 128, Kind::Gray, [0.0; 4]); + let image = Image::filled(128, 128, Kind::Gray, [0.0; 4]); let first = image_key(&image, &cache); assert_eq!(image_key(&image, &cache), first); - Arc::make_mut(&mut image.data)[1] = 1.0; + let mut data = image.data().to_vec(); + data[1] = 1.0; + let image = Image::from_data(128, 128, Kind::Gray, data, &Limits::default()).unwrap(); let changed = image_key(&image, &cache); assert_ne!(changed, first); - image.w = 64; - image.h = 256; + // The same buffer read as another shape. + let image = Image::from_data(64, 256, Kind::Gray, Arc::clone(image.shared_data()), &Limits::default()).unwrap(); let reshaped = image_key(&image, &cache); assert_ne!(reshaped, changed); @@ -340,9 +342,9 @@ fn preview_cap_does_not_compound_downscaling() { let mut opts = Options::new(&no_res); opts.max_size = Some(512); let c = cook(&p, 0, &opts, &cache); - assert_eq!(c.image(noise, 0).map(|i| (i.w, i.h)), Some((512, 512))); - assert_eq!(c.image(blur, 0).map(|i| (i.w, i.h)), Some((128, 128))); - assert_eq!(c.image(out, 0).map(|i| (i.w, i.h)), Some((128, 128))); + assert_eq!(c.image(noise, 0).map(|i| (i.width(), i.height())), Some((512, 512))); + assert_eq!(c.image(blur, 0).map(|i| (i.width(), i.height())), Some((128, 128))); + assert_eq!(c.image(out, 0).map(|i| (i.width(), i.height())), Some((128, 128))); } #[test] fn preview_cap_uses_nominal_dimensions_through_bypassed_nodes() { @@ -354,9 +356,9 @@ fn preview_cap_uses_nominal_dimensions_through_bypassed_nodes() { let mut opts = Options::new(&no_res); opts.max_size = Some(128); let c = cook(&p, 0, &opts, &cache); - assert_eq!(c.image(noise, 0).map(|i| (i.w, i.h)), Some((128, 64))); - assert_eq!(c.image(blur, 0).map(|i| (i.w, i.h)), Some((128, 64))); - assert_eq!(c.image(out, 0).map(|i| (i.w, i.h)), Some((128, 64))); + assert_eq!(c.image(noise, 0).map(|i| (i.width(), i.height())), Some((128, 64))); + assert_eq!(c.image(blur, 0).map(|i| (i.width(), i.height())), Some((128, 64))); + assert_eq!(c.image(out, 0).map(|i| (i.width(), i.height())), Some((128, 64))); } #[test] fn changed_unsampled_input_recooks() { @@ -371,18 +373,19 @@ fn changed_unsampled_input_recooks() { let cache = Mutex::new(Cache::default()); let first = cook(&p, 0, &opts, &cache); assert!(!first.nodes[&input].cached); - let mut changed = image; - Arc::make_mut(&mut changed.data)[1] = 1.0; + let mut data = image.data().to_vec(); + data[1] = 1.0; + let changed = Image::from_data(128, 128, Kind::Gray, data, &Limits::default()).unwrap(); opts.inputs.insert("input".into(), changed); let second = cook(&p, 0, &opts, &cache); assert!(!second.nodes[&input].cached); - assert_eq!(second.image(input, 0).unwrap().data[1], 1.0); + assert_eq!(second.image(input, 0).unwrap().data()[1], 1.0); } #[test] fn linear_input_images_and_bitmap_nodes_request_data_reads() { // The decoder returns 0.5 for a linear request and 0.2 for an sRGB one. let res = |k: &str| { - let (name, linear) = materialcraft_image::split_resource_key(k); + let (name, linear) = craft_texture::split_resource_key(k); (name == "m").then(|| Image::filled(4, 4, Kind::Color, [if linear { 0.5 } else { 0.2 }; 4])) }; let mut p = Package::new("p"); @@ -397,7 +400,7 @@ fn linear_input_images_and_bitmap_nodes_request_data_reads() { let first = |p: &Package| { let cache = Mutex::new(Cache::default()); let c = cook(p, 0, &Options::new(&res), &cache); - (c.image(i, 0).unwrap().data[0], c.image(b, 0).unwrap().data[0]) + (c.image(i, 0).unwrap().data()[0], c.image(b, 0).unwrap().data()[0]) }; assert_eq!(first(&p), (0.2, 0.2), "default is sRGB, as before"); p.graphs[0].input_images_linear.insert("n".into()); @@ -451,7 +454,7 @@ fn bound_input_image_linear_flag_change_recooks_instance() { p.graphs = vec![top, sub]; p.resources.push(Resource::new("curv", "curv.bin", ResourceBytes::new(vec![1; 100]))); let res = |k: &str| { - let (name, linear) = materialcraft_image::split_resource_key(k); + let (name, linear) = craft_texture::split_resource_key(k); (name == "curv").then(|| Image::filled(4, 4, Kind::Gray, [if linear { 0.5 } else { 0.2 }; 4])) }; let cache = Mutex::new(Cache::default()); @@ -459,14 +462,14 @@ fn bound_input_image_linear_flag_change_recooks_instance() { let first = cook(&p, 0, &opts, &cache); assert!(first.nodes[&inst].error.is_none(), "{:?}", first.nodes[&inst].error); assert!(!first.nodes[&inst].cached); - let first_value = first.image(inst, 0).unwrap().data[0]; + let first_value = first.image(inst, 0).unwrap().data()[0]; assert!((first_value - 0.2).abs() < 1e-4, "sRGB bound image should reach the instance, got {first_value}"); let second = cook(&p, 0, &opts, &cache); assert!(second.nodes[&inst].cached, "an unchanged instance should be served from the cache"); p.graphs[1].input_images_linear.insert("in".into()); let third = cook(&p, 0, &opts, &cache); assert!(!third.nodes[&inst].cached, "toggling input_images_linear must recook the instance"); - let third_value = third.image(inst, 0).unwrap().data[0]; + let third_value = third.image(inst, 0).unwrap().data()[0]; assert!((third_value - 0.5).abs() < 1e-4, "linear bound image should reach the instance, got {third_value}"); } @@ -549,7 +552,7 @@ fn enabled_generators_use_parent_size_and_inherit_other_input_base_parameters() assert_eq!(result.error, None, "{definition}"); assert_eq!(result.base.size, [64, 32], "{definition}, dynamic: {dynamic}"); - assert_eq!(cooked.image(generator, 0).map(|image| (image.w, image.h)), Some((16, 8))); + assert_eq!(cooked.image(generator, 0).map(|image| (image.width(), image.height())), Some((16, 8))); assert_eq!(result.base.seed, 17); assert_eq!(result.base.format, OutputFormat::F32); assert_eq!(result.base.tiling, [false, true]); @@ -567,7 +570,7 @@ fn enabled_generators_use_parent_size_and_inherit_other_input_base_parameters() assert_eq!(cooked.nodes[&generator].error, None); assert_eq!(cooked.nodes[&generator].base.size, cooked.nodes[&background].base.size); - assert_eq!(cooked.image(generator, 0).map(|image| (image.w, image.h)), Some((8, 16))); + assert_eq!(cooked.image(generator, 0).map(|image| (image.width(), image.height())), Some((8, 16))); } } } diff --git a/crates/eval/src/value_execution.rs b/crates/eval/src/value_execution.rs index 6ed651cf..9813f855 100644 --- a/crates/eval/src/value_execution.rs +++ b/crates/eval/src/value_execution.rs @@ -1,5 +1,5 @@ +use craft_texture::Image; use materialcraft_core::Value; -use materialcraft_image::Image; use std::collections::BTreeMap; pub(crate) fn evaluate_value( diff --git a/crates/formats/Cargo.toml b/crates/formats/Cargo.toml index 37f33395..d9364cea 100644 --- a/crates/formats/Cargo.toml +++ b/crates/formats/Cargo.toml @@ -10,7 +10,7 @@ workspace = true [dependencies] materialcraft-core = { workspace = true } -materialcraft-image = { workspace = true } +craft-texture = { workspace = true } materialcraft-geom = { workspace = true } materialcraft-nodes = { workspace = true } gltf = { workspace = true } diff --git a/crates/formats/src/dds_image.rs b/crates/formats/src/dds_image.rs index cba769b7..c2bbd6db 100644 --- a/crates/formats/src/dds_image.rs +++ b/crates/formats/src/dds_image.rs @@ -1,5 +1,5 @@ use crate::{FormatError, Result}; -use materialcraft_image::{Image, Kind, MAX_SIDE, srgb_to_linear}; +use craft_texture::{Image, Kind, Limits, MAX_SIDE, srgb_to_linear}; pub(crate) fn decode(bytes: &[u8], linear: bool) -> Result { let error = |message: String| FormatError::Image(message); @@ -20,5 +20,5 @@ pub(crate) fn decode(bytes: &[u8], linear: bool) -> Result { } } } - Ok(Image { w: size.width, h: size.height, kind: Kind::Color, data: std::sync::Arc::new(data) }) + Image::from_data(size.width, size.height, Kind::Color, data, &Limits::default()).map_err(|e| error(e.to_string())) } diff --git a/crates/formats/src/image.rs b/crates/formats/src/image.rs index f3fabdd7..872316f3 100644 --- a/crates/formats/src/image.rs +++ b/crates/formats/src/image.rs @@ -1,7 +1,6 @@ use crate::{Depth, FormatError, Result, guard}; -use materialcraft_image::{Image, Kind, MAX_SIDE, linear_to_srgb, srgb_to_linear}; +use craft_texture::{Image, Kind, Limits, MAX_SIDE, linear_to_srgb, srgb_to_linear}; use std::io::Cursor; -use std::sync::Arc; /// Decode image file bytes into a linear float image (8-bit color is sRGB-decoded; grayscale files stay grayscale) pub fn decode(bytes: &[u8], linear: bool) -> Result { @@ -41,7 +40,7 @@ pub fn decode(bytes: &[u8], linear: bool) -> Result { if gray { let l = img.into_luma16(); let data: Vec = l.pixels().map(|p| p.0[0] as f32 / 65535.0).collect(); - return Ok(Image { w, h, kind: Kind::Gray, data: Arc::new(data) }); + return Image::from_data(w, h, Kind::Gray, data, &Limits::default()).map_err(|e| FormatError::Image(e.to_string())); } let mut data = img.into_rgba32f().into_raw(); @@ -52,21 +51,21 @@ pub fn decode(bytes: &[u8], linear: bool) -> Result { } } } - Ok(Image { w, h, kind: Kind::Color, data: Arc::new(data) }) + Image::from_data(w, h, Kind::Color, data, &Limits::default()).map_err(|e| FormatError::Image(e.to_string())) } /// Encode `img` as `ext` (see [`EXPORT_FORMATS`]). `srgb`: color values are written through the sRGB curve (base color); data maps (normal, roughness…) are written linear pub fn encode(img: &Image, ext: &str, depth: Depth, srgb: bool) -> Result> { let ext = ext.trim_start_matches('.').to_ascii_lowercase(); - let enc = |v: f32| if srgb && img.kind == Kind::Color { linear_to_srgb(v) } else { v }; - let (w, h) = (img.w, img.h); - let color = img.kind == Kind::Color; + let enc = |v: f32| if srgb && img.kind() == Kind::Color { linear_to_srgb(v) } else { v }; + let (w, h) = (img.width(), img.height()); + let color = img.kind() == Kind::Color; let px = |i: usize| -> [f32; 4] { if color { - let s = img.data.get(i * 4..i * 4 + 4).unwrap_or(&[0.0, 0.0, 0.0, 1.0]); + let s = img.data().get(i * 4..i * 4 + 4).unwrap_or(&[0.0, 0.0, 0.0, 1.0]); [enc(s[0]), enc(s[1]), enc(s[2]), s[3]] } else { - let v = img.data.get(i).copied().unwrap_or(0.0); + let v = img.data().get(i).copied().unwrap_or(0.0); [v, v, v, 1.0] } }; diff --git a/crates/formats/src/sbs/tests.rs b/crates/formats/src/sbs/tests.rs index ff9745b6..98ee19e3 100644 --- a/crates/formats/src/sbs/tests.rs +++ b/crates/formats/src/sbs/tests.rs @@ -59,7 +59,7 @@ fn sample_package() -> Package { }); pkg.graphs.push(graph); - let orange = materialcraft_image::Image::filled(4, 4, materialcraft_image::Kind::Color, [1.0, 0.5, 0.0, 1.0]); + let orange = craft_texture::Image::filled(4, 4, craft_texture::Kind::Color, [1.0, 0.5, 0.0, 1.0]); let png = crate::encode(&orange, "png", crate::Depth::U8, true).unwrap(); pkg.resources.push(Resource::new("tex", "tex.png", ResourceBytes::new(png))); pkg diff --git a/crates/formats/src/svg.rs b/crates/formats/src/svg.rs index 284272be..dc4d21a0 100644 --- a/crates/formats/src/svg.rs +++ b/crates/formats/src/svg.rs @@ -1,5 +1,5 @@ use crate::{FormatError, Result}; -use materialcraft_image::{Image, Kind, MAX_SIDE, srgb_to_linear}; +use craft_texture::{Image, Kind, MAX_SIDE, srgb_to_linear}; use resvg::{tiny_skia, usvg}; pub(crate) fn decode(bytes: &[u8]) -> Result { diff --git a/crates/formats/src/tests.rs b/crates/formats/src/tests.rs index e8fe792c..972ddc0b 100644 --- a/crates/formats/src/tests.rs +++ b/crates/formats/src/tests.rs @@ -1,5 +1,5 @@ use super::*; -use materialcraft_image::{Image, Kind, srgb_to_linear}; +use craft_texture::{Image, Kind, srgb_to_linear}; use std::io::Cursor; #[test] @@ -11,7 +11,7 @@ fn export_every_format() { for i in [&img, &gray] { let b = encode(i, ext, depth, true).unwrap_or_else(|e| panic!("{ext}: {e}")); let back = decode(&b, false).unwrap_or_else(|e| panic!("{ext} decode: {e}")); - assert_eq!((back.w, back.h), (8, 8)); + assert_eq!((back.width(), back.height()), (8, 8)); } } } @@ -39,7 +39,7 @@ fn tga_still_decodes() { let mut tga = Cursor::new(Vec::new()); ::image::RgbaImage::new(2, 2).write_to(&mut tga, ::image::ImageFormat::Tga).unwrap(); let img = decode(tga.get_ref(), false).unwrap(); - assert_eq!((img.w, img.h, img.kind), (2, 2, Kind::Color)); + assert_eq!((img.width(), img.height(), img.kind()), (2, 2, Kind::Color)); } #[test] diff --git a/crates/formats/tests/bitmap_imports.rs b/crates/formats/tests/bitmap_imports.rs index 5ec5438d..1d8e11f5 100644 --- a/crates/formats/tests/bitmap_imports.rs +++ b/crates/formats/tests/bitmap_imports.rs @@ -1,5 +1,5 @@ +use craft_texture::{Image, Kind}; use materialcraft_formats::{BITMAP_EXTENSIONS, BITMAP_FORMATS, Depth, decode, encode}; -use materialcraft_image::{Image, Kind}; use std::io::Cursor; #[test] @@ -23,7 +23,7 @@ fn common_bitmap_formats_decode() { let bytes = encode(&pixels, extension, Depth::U8, true).unwrap(); let image = decode(&bytes, false).unwrap(); - assert_eq!((image.w, image.h), (4, 4), "{extension}"); + assert_eq!((image.width(), image.height()), (4, 4), "{extension}"); } // GIF and TIFF import only, so another writer makes them @@ -31,15 +31,15 @@ fn common_bitmap_formats_decode() { let mut bytes = Cursor::new(Vec::new()); image::RgbaImage::from_pixel(2, 2, image::Rgba([255, 0, 0, 255])).write_to(&mut bytes, format).unwrap(); - assert_eq!(decode(bytes.get_ref(), false).unwrap().w, 2, "{format:?}"); + assert_eq!(decode(bytes.get_ref(), false).unwrap().width(), 2, "{format:?}"); } assert!(encode(&pixels, "tif", Depth::U8, true).is_err(), "TIFF is not an export format"); for pgm in [&b"P2\n2 1\n255\n0 255\n"[..], &b"P5\n2 1\n255\n\0\xff"[..]] { let image = decode(pgm, false).unwrap(); - assert_eq!(image.kind, Kind::Gray); - assert_eq!(image.data.as_slice(), &[0.0, 1.0]); + assert_eq!(image.kind(), Kind::Gray); + assert_eq!(image.data(), &[0.0, 1.0]); } } @@ -61,12 +61,12 @@ fn dds_supports_compressed_uncompressed_and_float_textures() { encoder.finish().unwrap(); let image = decode(&bytes, true).unwrap(); - assert_eq!((image.w, image.h), (4, 4)); - assert!(image.data.iter().all(|value| value.is_finite())); - assert!((image.data[0] - 64.0 / 255.0).abs() < 0.05, "{format:?}"); + assert_eq!((image.width(), image.height()), (4, 4)); + assert!(image.data().iter().all(|value| value.is_finite())); + assert!((image.data()[0] - 64.0 / 255.0).abs() < 0.05, "{format:?}"); if format == dds::Format::R32G32B32A32_FLOAT { - assert_eq!(decode(&bytes, false).unwrap().data, image.data, "float DDS stays linear"); + assert_eq!(decode(&bytes, false).unwrap().data(), image.data(), "float DDS stays linear"); } assert!(decode(&bytes[..bytes.len() / 2], true).is_err()); diff --git a/crates/formats/tests/project_packages.rs b/crates/formats/tests/project_packages.rs index feb3345a..4c8a33f7 100644 --- a/crates/formats/tests/project_packages.rs +++ b/crates/formats/tests/project_packages.rs @@ -9,7 +9,7 @@ const SVG: &[u8] = br#" Package { let mut package = Package::new("Surface"); - let pixels = materialcraft_image::Image::filled(2, 2, materialcraft_image::Kind::Color, [0.2, 0.4, 0.8, 1.0]); + let pixels = craft_texture::Image::filled(2, 2, craft_texture::Kind::Color, [0.2, 0.4, 0.8, 1.0]); let png = encode(&pixels, "png", Depth::U8, true).unwrap(); package.resources.push(Resource::new("Texture", "texture.png", ResourceBytes::new(png))); package.resources.push(Resource::new("Shape", "shape.svg", ResourceBytes::new(SVG.to_vec()))); diff --git a/crates/image/Cargo.toml b/crates/image/Cargo.toml deleted file mode 100644 index c8f371a3..00000000 --- a/crates/image/Cargo.toml +++ /dev/null @@ -1,13 +0,0 @@ -[package] -name = "materialcraft-image" -description = "MaterialCraft image buffers: grayscale and color float planes, sampling, resampling, conversions" -version.workspace = true -edition.workspace = true -license.workspace = true - -[lints] -workspace = true - -[dependencies] -rayon = { workspace = true } -thiserror = { workspace = true } diff --git a/crates/image/src/lib.rs b/crates/image/src/lib.rs deleted file mode 100644 index 396f1e5a..00000000 --- a/crates/image/src/lib.rs +++ /dev/null @@ -1,384 +0,0 @@ -//! # materialcraft-image -//! -//! Image buffers for node cooking, L0: an [`Image`] is a grayscale (1 channel) or color (RGBA) -//! plane of `f32`, shared copy-on-write through an `Arc` so cached node outputs cost nothing to -//! hand around. Values are linear and usually 0..1 (HDR formats may exceed it). Sampling wraps or -//! clamps per axis ("tiling"); everything per pixel runs in parallel rows (rayon). -#![forbid(unsafe_code)] -#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] - -use std::sync::Arc; - -use rayon::prelude::*; - -/// Largest side an image may have (an allocation cap for hostile sizes). -pub const MAX_SIDE: u32 = 8192; - -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] -pub enum Kind { - Gray, - Color, -} - -impl Kind { - pub fn channels(self) -> usize { - match self { - Kind::Gray => 1, - Kind::Color => 4, - } - } -} - -#[derive(Debug, thiserror::Error)] -pub enum ImageError { - #[error("image size {0}x{1} is outside 1..={MAX_SIDE}")] - BadSize(u32, u32), -} - -#[derive(Clone, Debug)] -pub struct Image { - pub w: u32, - pub h: u32, - pub kind: Kind, - /// Row-major, `kind.channels()` floats per pixel. - pub data: Arc>, -} - -impl PartialEq for Image { - fn eq(&self, o: &Image) -> bool { - self.w == o.w && self.h == o.h && self.kind == o.kind && (Arc::ptr_eq(&self.data, &o.data) || self.data == o.data) - } -} - -/// Clamp a requested size into the allowed range. -pub fn clamp_size(w: u32, h: u32) -> (u32, u32) { - (w.clamp(1, MAX_SIDE), h.clamp(1, MAX_SIDE)) -} - -#[inline] -fn wrap(i: i64, n: u32, tile: bool) -> usize { - let n = n as i64; - if tile { i.rem_euclid(n) as usize } else { i.clamp(0, n - 1) as usize } -} - -impl Image { - /// A constant image. - pub fn filled(w: u32, h: u32, kind: Kind, v: [f32; 4]) -> Image { - let (w, h) = clamp_size(w, h); - let n = (w * h) as usize; - let data = match kind { - Kind::Gray => vec![v[0]; n], - Kind::Color => v.iter().copied().cycle().take(n * 4).collect(), - }; - Image { w, h, kind, data: Arc::new(data) } - } - - /// Generate every pixel with `f(x, y)` (pixel indices) in parallel rows. - pub fn generate(w: u32, h: u32, kind: Kind, f: impl Fn(u32, u32) -> [f32; 4] + Sync) -> Image { - let (w, h) = clamp_size(w, h); - let c = kind.channels(); - let mut data = vec![0.0f32; (w * h) as usize * c]; - data.par_chunks_mut(w as usize * c).enumerate().for_each(|(y, row)| { - for x in 0..w as usize { - let p = f(x as u32, y as u32); - row[x * c..x * c + c].copy_from_slice(&p[..c]); - } - }); - Image { w, h, kind, data: Arc::new(data) } - } - - /// Generate from normalized coordinates (pixel centers, 0..1). - pub fn generate_uv(w: u32, h: u32, kind: Kind, f: impl Fn(f32, f32) -> [f32; 4] + Sync) -> Image { - let (iw, ih) = (1.0 / w.max(1) as f32, 1.0 / h.max(1) as f32); - Image::generate(w, h, kind, |x, y| f((x as f32 + 0.5) * iw, (y as f32 + 0.5) * ih)) - } - - pub fn gray(w: u32, h: u32, f: impl Fn(u32, u32) -> f32 + Sync) -> Image { - Image::generate(w, h, Kind::Gray, |x, y| [f(x, y), 0.0, 0.0, 0.0]) - } - - pub fn channels(&self) -> usize { - self.kind.channels() - } - - pub fn is_gray(&self) -> bool { - self.kind == Kind::Gray - } - - /// The pixel at integer coordinates (wrapped or clamped), as RGBA (gray → `[v, v, v, 1]`). - #[inline] - pub fn get(&self, x: i64, y: i64, tile: bool) -> [f32; 4] { - let (x, y) = (wrap(x, self.w, tile), wrap(y, self.h, tile)); - let i = y * self.w as usize + x; - match self.kind { - Kind::Gray => { - let v = self.data.get(i).copied().unwrap_or(0.0); - [v, v, v, 1.0] - } - Kind::Color => { - let s = self.data.get(i * 4..i * 4 + 4).unwrap_or(&[0.0, 0.0, 0.0, 1.0]); - [s[0], s[1], s[2], s[3]] - } - } - } - - /// The gray value, or the Rec. 709 luminance of a color image. - #[inline] - pub fn get_gray(&self, x: i64, y: i64, tile: bool) -> f32 { - let p = self.get(x, y, tile); - match self.kind { - Kind::Gray => p[0], - Kind::Color => luminance(p), - } - } - - /// Bilinear sample at normalized `(u, v)`; pixel centers sit at `(i + 0.5) / w`. - #[inline] - pub fn sample(&self, u: f32, v: f32, tile: bool) -> [f32; 4] { - let fx = u * self.w as f32 - 0.5; - let fy = v * self.h as f32 - 0.5; - if !fx.is_finite() || !fy.is_finite() { - return [0.0, 0.0, 0.0, 1.0]; - } - // Huge but finite coordinates would saturate the i64 cast and overflow at `+ 1`. - let (fx, fy) = (fx.clamp(-1.0e9, 1.0e9), fy.clamp(-1.0e9, 1.0e9)); - let (x0, y0) = (fx.floor(), fy.floor()); - let (tx, ty) = (fx - x0, fy - y0); - let (x0, y0) = (x0 as i64, y0 as i64); - let a = self.get(x0, y0, tile); - let b = self.get(x0 + 1, y0, tile); - let c = self.get(x0, y0 + 1, tile); - let d = self.get(x0 + 1, y0 + 1, tile); - let mut o = [0.0; 4]; - for k in 0..4 { - let top = a[k] + (b[k] - a[k]) * tx; - let bot = c[k] + (d[k] - c[k]) * tx; - o[k] = top + (bot - top) * ty; - } - o - } - - #[inline] - pub fn sample_gray(&self, u: f32, v: f32, tile: bool) -> f32 { - let p = self.sample(u, v, tile); - match self.kind { - Kind::Gray => p[0], - Kind::Color => luminance(p), - } - } - - /// Nearest sample at normalized `(u, v)`. - #[inline] - pub fn sample_nearest(&self, u: f32, v: f32, tile: bool) -> [f32; 4] { - let x = (u * self.w as f32).floor(); - let y = (v * self.h as f32).floor(); - if !x.is_finite() || !y.is_finite() { - return [0.0, 0.0, 0.0, 1.0]; - } - self.get(x as i64, y as i64, tile) - } - - /// Map every pixel (as RGBA) to a new image of `kind`, same size. - pub fn map(&self, kind: Kind, f: impl Fn([f32; 4]) -> [f32; 4] + Sync) -> Image { - Image::generate(self.w, self.h, kind, |x, y| f(self.get(x as i64, y as i64, false))) - } - - /// This image as grayscale (luminance of a color image). - pub fn to_gray(&self) -> Image { - match self.kind { - Kind::Gray => self.clone(), - Kind::Color => self.map(Kind::Gray, |p| [luminance(p), 0.0, 0.0, 0.0]), - } - } - - /// This image as RGBA (gray copied to RGB, alpha 1). - pub fn to_color(&self) -> Image { - match self.kind { - Kind::Color => self.clone(), - Kind::Gray => self.map(Kind::Color, |p| p), - } - } - - pub fn to_kind(&self, kind: Kind) -> Image { - match kind { - Kind::Gray => self.to_gray(), - Kind::Color => self.to_color(), - } - } - - /// Resample to `w × h` (bilinear when enlarging, box-filtered when shrinking). - pub fn resize(&self, w: u32, h: u32, tile: bool) -> Image { - let (w, h) = clamp_size(w, h); - if w == self.w && h == self.h { - return self.clone(); - } - if w <= self.w && h <= self.h && self.w.is_multiple_of(w) && self.h.is_multiple_of(h) { - let (fx, fy) = ((self.w / w) as i64, (self.h / h) as i64); - let inv = 1.0 / (fx * fy) as f32; - return Image::generate(w, h, self.kind, |x, y| { - let mut s = [0.0; 4]; - for j in 0..fy { - for i in 0..fx { - let p = self.get(x as i64 * fx + i, y as i64 * fy + j, tile); - for k in 0..4 { - s[k] += p[k]; - } - } - } - s.map(|v| v * inv) - }); - } - Image::generate_uv(w, h, self.kind, |u, v| self.sample(u, v, tile)) - } - - /// Raw float access for gray images (`None` for color). - pub fn gray_data(&self) -> Option<&[f32]> { - (self.kind == Kind::Gray).then_some(self.data.as_slice()) - } - - /// 8-bit sRGB-encoded RGBA for display (gray shown as is; color through the sRGB curve). - pub fn to_rgba8_display(&self) -> Vec { - let q = |v: f32| (v.clamp(0.0, 1.0) * 255.0 + 0.5) as u8; - let n = (self.w * self.h) as usize; - let mut out = vec![0u8; n * 4]; - out.par_chunks_mut(4).enumerate().for_each(|(i, px)| match self.kind { - Kind::Gray => { - let v = q(self.data.get(i).copied().unwrap_or(0.0)); - px.copy_from_slice(&[v, v, v, 255]); - } - Kind::Color => { - let s = self.data.get(i * 4..i * 4 + 4).unwrap_or(&[0.0, 0.0, 0.0, 1.0]); - px.copy_from_slice(&[q(linear_to_srgb(s[0])), q(linear_to_srgb(s[1])), q(linear_to_srgb(s[2])), q(s[3])]); - } - }); - out - } - - /// Mean of each channel (as RGBA), e.g. for tests and auto levels. - pub fn mean(&self) -> [f32; 4] { - let c = self.channels(); - let n = (self.w * self.h) as f64; - let mut s = [0f64; 4]; - for px in self.data.chunks(c) { - for (k, v) in px.iter().enumerate() { - s[k] += *v as f64; - } - } - if c == 1 { - let m = (s[0] / n) as f32; - return [m, m, m, 1.0]; - } - s.map(|v| (v / n) as f32) - } - - /// Minimum and maximum over all channels (alpha excluded). - pub fn range(&self) -> (f32, f32) { - let c = self.channels(); - let mut lo = f32::INFINITY; - let mut hi = f32::NEG_INFINITY; - for px in self.data.chunks(c) { - for v in px.iter().take(c.min(3)) { - lo = lo.min(*v); - hi = hi.max(*v); - } - } - if lo > hi { (0.0, 0.0) } else { (lo, hi) } - } -} - -/// Rec. 709 luminance of a linear RGB(A) pixel. -#[inline] -pub fn luminance(p: [f32; 4]) -> f32 { - 0.2126 * p[0] + 0.7152 * p[1] + 0.0722 * p[2] -} - -#[inline] -pub fn linear_to_srgb(v: f32) -> f32 { - if v <= 0.003_130_8 { v * 12.92 } else { 1.055 * v.max(0.0).powf(1.0 / 2.4) - 0.055 } -} - -#[inline] -pub fn srgb_to_linear(v: f32) -> f32 { - if v <= 0.04045 { v / 12.92 } else { ((v + 0.055) / 1.055).powf(2.4) } -} - -/// Encode the bitmap name and its requested color space without ambiguity. -/// Plain sRGB names remain readable by simple resource callbacks. -pub fn resource_key(name: &str, linear: bool) -> String { - if linear { - format!("\u{1}L{name}") - } else if name.starts_with('\u{1}') { - format!("\u{1}S{name}") - } else { - name.to_string() - } -} - -/// Split a key made by [`resource_key`] into its name and data-map flag. -pub fn split_resource_key(key: &str) -> (&str, bool) { - if let Some(name) = key.strip_prefix("\u{1}L") { - (name, true) - } else if let Some(name) = key.strip_prefix("\u{1}S") { - (name, false) - } else { - (key, false) - } -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn sample_survives_huge_coordinates() { - let img = Image::gray(8, 8, |x, _| x as f32); - for u in [1.0e30_f32, -1.0e30, f32::MAX, f32::MIN] { - for tile in [true, false] { - let p = img.sample(u, u, tile); - assert!(p.iter().all(|c| c.is_finite())); - } - } - } - - #[test] - fn resource_keys_round_trip() { - for name in ["n", "", "\u{1}Lnormal", "\u{1}Sn", "n\u{1}linear"] { - for linear in [false, true] { - assert_eq!(split_resource_key(&resource_key(name, linear)), (name, linear)); - } - } - } - - #[test] - fn sample_wraps_and_clamps() { - let img = Image::gray(4, 1, |x, _| x as f32); - assert_eq!(img.get(-1, 0, true)[0], 3.0); - assert_eq!(img.get(-1, 0, false)[0], 0.0); - // Halfway between the last and the (wrapped) first pixel. - assert!((img.sample(1.0, 0.5, true)[0] - 1.5).abs() < 1e-5); - } - - #[test] - fn resize_box_and_bilinear() { - let img = Image::gray(4, 4, |x, _| if x < 2 { 0.0 } else { 1.0 }); - let small = img.resize(2, 2, true); - assert_eq!(small.data.as_slice(), &[0.0, 1.0, 0.0, 1.0]); - let big = small.resize(8, 8, false); - assert_eq!(big.w, 8); - assert!(big.data[0] < big.data[7]); - } - - #[test] - fn hostile_sizes_are_clamped() { - let img = Image::filled(0, u32::MAX, Kind::Gray, [0.5; 4]); - assert_eq!((img.w, img.h), (1, MAX_SIDE)); - assert_eq!(img.sample(f32::NAN, 0.0, true), [0.0, 0.0, 0.0, 1.0]); - } - - #[test] - fn conversions() { - let c = Image::filled(2, 2, Kind::Color, [1.0, 1.0, 1.0, 1.0]); - assert!((c.to_gray().data[0] - 1.0).abs() < 1e-5); - assert_eq!(c.to_rgba8_display()[0], 255); - } -} diff --git a/crates/nodes/Cargo.toml b/crates/nodes/Cargo.toml index 437bb96d..daf743ef 100644 --- a/crates/nodes/Cargo.toml +++ b/crates/nodes/Cargo.toml @@ -10,5 +10,5 @@ workspace = true [dependencies] materialcraft-core = { workspace = true } -materialcraft-image = { workspace = true } +craft-texture = { workspace = true } rayon = { workspace = true } diff --git a/crates/nodes/src/atomic/bitmap.rs b/crates/nodes/src/atomic/bitmap.rs index 1a98ada3..ab07409f 100644 --- a/crates/nodes/src/atomic/bitmap.rs +++ b/crates/nodes/src/atomic/bitmap.rs @@ -15,7 +15,7 @@ pub(super) fn definition() -> NodeDefinition { fn bitmap(context: &CookContext) -> CookResult { let name = context.text("resource"); - let image = match (context.resource)(&materialcraft_image::resource_key(name, context.i("colour_space") == 1)) { + let image = match (context.resource)(&craft_texture::resource_key(name, context.i("colour_space") == 1)) { Some(image) => image.resize(context.w, context.h, context.tile), None if name.is_empty() => context.gen_color(|u, v| { let c = if ((u * 8.0) as i32 + (v * 8.0) as i32) % 2 == 0 { 0.8 } else { 0.2 }; diff --git a/crates/nodes/src/atomic/blend.rs b/crates/nodes/src/atomic/blend.rs index 3c890e4b..a6f46845 100644 --- a/crates/nodes/src/atomic/blend.rs +++ b/crates/nodes/src/atomic/blend.rs @@ -2,7 +2,7 @@ use super::ATOMIC; use crate::ops; use crate::ops::BLEND_MODES; use crate::{CookContext, CookResult, NodeDefinition, node}; -use materialcraft_image::{Image, Kind}; +use craft_texture::{Image, Kind}; pub(super) fn definition() -> NodeDefinition { node("blend", "Blend", ATOMIC) diff --git a/crates/nodes/src/atomic/blur.rs b/crates/nodes/src/atomic/blur.rs index 089e58f0..90604c98 100644 --- a/crates/nodes/src/atomic/blur.rs +++ b/crates/nodes/src/atomic/blur.rs @@ -1,7 +1,7 @@ use super::ATOMIC; use crate::ops; use crate::{CookContext, CookResult, NodeDefinition, node}; -use materialcraft_image::Kind; +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) diff --git a/crates/nodes/src/atomic/channels_shuffle.rs b/crates/nodes/src/atomic/channels_shuffle.rs index 1014f546..546fc9b0 100644 --- a/crates/nodes/src/atomic/channels_shuffle.rs +++ b/crates/nodes/src/atomic/channels_shuffle.rs @@ -1,6 +1,6 @@ use super::ATOMIC; use crate::{CookContext, CookResult, NodeDefinition, node}; -use materialcraft_image::{Image, Kind}; +use craft_texture::{Image, Kind}; pub(super) fn definition() -> NodeDefinition { node("channels_shuffle", "Channels shuffle", ATOMIC) diff --git a/crates/nodes/src/atomic/curve.rs b/crates/nodes/src/atomic/curve.rs index da61d433..6060202d 100644 --- a/crates/nodes/src/atomic/curve.rs +++ b/crates/nodes/src/atomic/curve.rs @@ -1,6 +1,6 @@ use super::ATOMIC; use crate::{CookContext, CookResult, NodeDefinition, node}; -use materialcraft_image::Kind; +use craft_texture::Kind; pub(super) fn definition() -> NodeDefinition { node("curve", "Curve", ATOMIC).desc("Remaps values through a tone curve.").atomic().any_in("input", "Input").curve("curve", "Curve").any_out().cook(curve) @@ -18,5 +18,5 @@ fn curve(context: &CookContext) -> CookResult { let b = lut.get(i + 1).copied().unwrap_or(a); a + (b - a) * (t - i as f32) }; - Ok(vec![img.map(img.kind, |p| [f(p[0]), f(p[1]), f(p[2]), p[3]])]) + Ok(vec![img.map(img.kind(), |p| [f(p[0]), f(p[1]), f(p[2]), p[3]])]) } diff --git a/crates/nodes/src/atomic/directional_blur.rs b/crates/nodes/src/atomic/directional_blur.rs index 905c0d07..32c576fa 100644 --- a/crates/nodes/src/atomic/directional_blur.rs +++ b/crates/nodes/src/atomic/directional_blur.rs @@ -1,6 +1,6 @@ use super::{ATOMIC, direction}; use crate::{CookContext, CookResult, NodeDefinition, node}; -use materialcraft_image::{Image, Kind}; +use craft_texture::{Image, Kind}; pub(super) fn definition() -> NodeDefinition { node("directional_blur", "Directional blur", ATOMIC) @@ -26,7 +26,7 @@ pub(super) fn blur(context: &CookContext, angle: f32) -> CookResult { 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| { + 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; diff --git a/crates/nodes/src/atomic/directional_warp.rs b/crates/nodes/src/atomic/directional_warp.rs index 9489b617..e7a4722a 100644 --- a/crates/nodes/src/atomic/directional_warp.rs +++ b/crates/nodes/src/atomic/directional_warp.rs @@ -1,6 +1,6 @@ use super::{ATOMIC, direction}; use crate::{CookContext, CookResult, NodeDefinition, node}; -use materialcraft_image::{Image, Kind}; +use craft_texture::{Image, Kind}; pub(super) fn definition() -> NodeDefinition { node("directional_warp", "Directional warp", ATOMIC) @@ -19,7 +19,7 @@ fn directional_warp(context: &CookContext) -> CookResult { let map = context.gray_or(1, 0.0); let (dx, dy) = direction(context.f("angle")); let k = context.f("intensity") / 256.0; - Ok(vec![Image::generate_uv(context.w, context.h, img.kind, |u, v| { + Ok(vec![Image::generate_uv(context.w, context.h, img.kind(), |u, v| { let m = map.sample_gray(u, v, context.tile) * k; img.sample(u + dx * m, v + dy * m, context.tile) })]) diff --git a/crates/nodes/src/atomic/distance.rs b/crates/nodes/src/atomic/distance.rs index fda95f52..8d5dae6b 100644 --- a/crates/nodes/src/atomic/distance.rs +++ b/crates/nodes/src/atomic/distance.rs @@ -1,7 +1,7 @@ use super::ATOMIC; use crate::ops; use crate::{CookContext, CookResult, NodeDefinition, node}; -use materialcraft_image::Image; +use craft_texture::Image; pub(super) fn definition() -> NodeDefinition { node("distance", "Distance", ATOMIC) @@ -18,16 +18,16 @@ pub(super) fn definition() -> NodeDefinition { fn distance(context: &CookContext) -> CookResult { let mask = context.gray_or(0, 0.0); let maxd = (context.f("distance").max(0.0) * context.w as f32 / 256.0).max(1e-3); - let data = mask.data.clone(); + let data = mask.shared_data().clone(); let inside = |i| data.get(i).copied().unwrap_or(0.0) > 0.5; let Some(src) = context.sized(1) else { let d2 = ops::distance_sq(context.w, context.h, inside, context.tile); - return Ok(vec![ops::gray_from(context.w, context.h, d2.iter().map(|d| (1.0 - d.sqrt() / maxd).clamp(0.0, 1.0)).collect())]); + return Ok(vec![ops::gray_from(context.w, context.h, d2.iter().map(|d| (1.0 - d.sqrt() / maxd).clamp(0.0, 1.0)).collect())?]); }; // Propagate the exact nearest site without gaps from gradient-walk stalls let (d2, sites) = ops::distance_sq_with_sites(context.w, context.h, inside, context.tile); let combine = context.b("combine"); - Ok(vec![Image::generate(context.w, context.h, src.kind, |x, y| { + Ok(vec![Image::generate(context.w, context.h, src.kind(), |x, y| { let i = y as usize * context.w as usize + x as usize; let site = sites.get(i).copied().unwrap_or(usize::MAX); let mut c = if site == usize::MAX { diff --git a/crates/nodes/src/atomic/dot.rs b/crates/nodes/src/atomic/dot.rs index 73f42930..8938d28c 100644 --- a/crates/nodes/src/atomic/dot.rs +++ b/crates/nodes/src/atomic/dot.rs @@ -1,6 +1,6 @@ use super::GRAPH_ITEMS; use crate::{CookContext, CookResult, NodeDefinition, node}; -use materialcraft_image::{Image, Kind}; +use craft_texture::{Image, Kind}; pub(super) fn definition() -> NodeDefinition { node("dot", "Dot", GRAPH_ITEMS).desc("A reroute point for wires.").atomic().any_in("input", "Input").any_out().cook(passthrough) diff --git a/crates/nodes/src/atomic/emboss.rs b/crates/nodes/src/atomic/emboss.rs index 66492a2e..1169151f 100644 --- a/crates/nodes/src/atomic/emboss.rs +++ b/crates/nodes/src/atomic/emboss.rs @@ -1,7 +1,7 @@ use super::{ATOMIC, direction}; use crate::ops; use crate::{CookContext, CookResult, NodeDefinition, node}; -use materialcraft_image::{Image, Kind}; +use craft_texture::{Image, Kind}; pub(super) fn definition() -> NodeDefinition { node("emboss", "Emboss", ATOMIC) @@ -23,7 +23,7 @@ fn emboss(context: &CookContext) -> CookResult { 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| { + 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); diff --git a/crates/nodes/src/atomic/gradient_dynamic.rs b/crates/nodes/src/atomic/gradient_dynamic.rs index cd38bdc7..d0ce93a0 100644 --- a/crates/nodes/src/atomic/gradient_dynamic.rs +++ b/crates/nodes/src/atomic/gradient_dynamic.rs @@ -1,6 +1,6 @@ use super::ATOMIC; use crate::{CookContext, CookResult, NodeDefinition, node}; -use materialcraft_image::{Image, Kind}; +use craft_texture::{Image, Kind}; pub(super) fn definition() -> NodeDefinition { node("gradient_dynamic", "Gradient (Dynamic)", ATOMIC) @@ -19,7 +19,7 @@ fn gradient_dynamic(context: &CookContext) -> CookResult { 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| { + 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) } })]) diff --git a/crates/nodes/src/atomic/gradient_map.rs b/crates/nodes/src/atomic/gradient_map.rs index 38677f5d..fce31a57 100644 --- a/crates/nodes/src/atomic/gradient_map.rs +++ b/crates/nodes/src/atomic/gradient_map.rs @@ -1,7 +1,7 @@ use super::ATOMIC; use crate::{CookContext, CookResult, NodeDefinition, node}; +use craft_texture::{Kind, luminance}; use materialcraft_core::Gradient; -use materialcraft_image::{Kind, luminance}; pub(super) fn definition() -> NodeDefinition { node("gradient_map", "Gradient map", ATOMIC) diff --git a/crates/nodes/src/atomic/grayscale_conversion.rs b/crates/nodes/src/atomic/grayscale_conversion.rs index f4b9fa1b..3e27cb00 100644 --- a/crates/nodes/src/atomic/grayscale_conversion.rs +++ b/crates/nodes/src/atomic/grayscale_conversion.rs @@ -1,6 +1,6 @@ use super::ATOMIC; use crate::{CookContext, CookResult, NodeDefinition, node}; -use materialcraft_image::Kind; +use craft_texture::Kind; pub(super) fn definition() -> NodeDefinition { node("grayscale_conversion", "Grayscale conversion", ATOMIC) diff --git a/crates/nodes/src/atomic/hsl.rs b/crates/nodes/src/atomic/hsl.rs index f174f2ba..a38ac73e 100644 --- a/crates/nodes/src/atomic/hsl.rs +++ b/crates/nodes/src/atomic/hsl.rs @@ -1,7 +1,7 @@ use super::ATOMIC; use crate::ops; use crate::{CookContext, CookResult, NodeDefinition, node}; -use materialcraft_image::Kind; +use craft_texture::Kind; pub(super) fn definition() -> NodeDefinition { node("hsl", "HSL", ATOMIC) diff --git a/crates/nodes/src/atomic/input_color.rs b/crates/nodes/src/atomic/input_color.rs index b3dc487b..547f49cb 100644 --- a/crates/nodes/src/atomic/input_color.rs +++ b/crates/nodes/src/atomic/input_color.rs @@ -1,7 +1,7 @@ use super::GRAPH_ITEMS; use crate::{CookContext, CookResult, NodeDefinition, node}; +use craft_texture::{Image, Kind}; use materialcraft_core::ComponentUsage; -use materialcraft_image::{Image, Kind}; pub(super) fn definition() -> NodeDefinition { node("input_color", "Input color", GRAPH_ITEMS) diff --git a/crates/nodes/src/atomic/input_grayscale.rs b/crates/nodes/src/atomic/input_grayscale.rs index 202263a6..cdb941f1 100644 --- a/crates/nodes/src/atomic/input_grayscale.rs +++ b/crates/nodes/src/atomic/input_grayscale.rs @@ -1,7 +1,7 @@ use super::GRAPH_ITEMS; use crate::{CookContext, CookResult, NodeDefinition, node}; +use craft_texture::{Image, Kind}; use materialcraft_core::ComponentUsage; -use materialcraft_image::{Image, Kind}; pub(super) fn definition() -> NodeDefinition { node("input_grayscale", "Input grayscale", GRAPH_ITEMS) diff --git a/crates/nodes/src/atomic/levels.rs b/crates/nodes/src/atomic/levels.rs index 079f7b46..743ad741 100644 --- a/crates/nodes/src/atomic/levels.rs +++ b/crates/nodes/src/atomic/levels.rs @@ -1,6 +1,6 @@ use super::ATOMIC; use crate::{CookContext, CookResult, NodeDefinition, node}; -use materialcraft_image::Kind; +use craft_texture::Kind; pub(super) fn definition() -> NodeDefinition { node("levels", "Levels", ATOMIC) @@ -24,7 +24,7 @@ fn levels(context: &CookContext) -> CookResult { let output_low = context.v4("out_low"); let output_high = context.v4("out_high"); - Ok(vec![image.map(image.kind, |pixel| { + Ok(vec![image.map(image.kind(), |pixel| { std::array::from_fn(|channel| levels_fn(pixel[channel], low[channel], mid[channel], high[channel], output_low[channel], output_high[channel])) })]) } diff --git a/crates/nodes/src/atomic/normal.rs b/crates/nodes/src/atomic/normal.rs index 6739c214..7505a180 100644 --- a/crates/nodes/src/atomic/normal.rs +++ b/crates/nodes/src/atomic/normal.rs @@ -1,7 +1,7 @@ use super::ATOMIC; use crate::ops; use crate::{CookContext, CookResult, NodeDefinition, node}; -use materialcraft_image::{Image, Kind}; +use craft_texture::{Image, Kind}; pub(super) fn definition() -> NodeDefinition { node("normal", "Normal", ATOMIC) @@ -22,7 +22,7 @@ fn normal(context: &CookContext) -> CookResult { } pub fn height_to_normal(h: &Image, k: f32, directx: bool, tile: bool, alpha_height: bool) -> Image { - Image::generate(h.w, h.h, Kind::Color, |x, y| { + Image::generate(h.width(), h.height(), Kind::Color, |x, y| { let (dx, dy) = ops::slope(h, x as i64, y as i64, tile); let (nx, ny, nz) = (-dx * k, dy * k, 1.0); let l = (nx * nx + ny * ny + nz * nz).sqrt(); diff --git a/crates/nodes/src/atomic/output.rs b/crates/nodes/src/atomic/output.rs index 62202a23..a0b3433d 100644 --- a/crates/nodes/src/atomic/output.rs +++ b/crates/nodes/src/atomic/output.rs @@ -1,7 +1,7 @@ use super::GRAPH_ITEMS; use super::dot::passthrough; use crate::{NodeDefinition, PortKind, node}; -use materialcraft_image::{Image, Kind}; +use craft_texture::{Image, Kind}; pub(super) fn definition() -> NodeDefinition { node("output", "Output", GRAPH_ITEMS) @@ -17,6 +17,6 @@ pub fn output_kind(def: &NodeDefinition, port: usize, inputs: &[Option]) match def.outputs.get(port).map(|p| p.kind) { Some(PortKind::Gray) => Kind::Gray, Some(PortKind::Color) => Kind::Color, - _ => inputs.iter().flatten().next().map_or(Kind::Gray, |i| i.kind), + _ => inputs.iter().flatten().next().map_or(Kind::Gray, |i| i.kind()), } } diff --git a/crates/nodes/src/atomic/sharpen.rs b/crates/nodes/src/atomic/sharpen.rs index ef2bd464..ec639b78 100644 --- a/crates/nodes/src/atomic/sharpen.rs +++ b/crates/nodes/src/atomic/sharpen.rs @@ -1,7 +1,7 @@ use super::ATOMIC; use crate::ops; use crate::{CookContext, CookResult, NodeDefinition, node}; -use materialcraft_image::{Image, Kind}; +use craft_texture::{Image, Kind}; pub(super) fn definition() -> NodeDefinition { node("sharpen", "Sharpen", ATOMIC) @@ -17,7 +17,7 @@ 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| { + 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]] })]) diff --git a/crates/nodes/src/atomic/text.rs b/crates/nodes/src/atomic/text.rs index 84088c42..2ebb1f15 100644 --- a/crates/nodes/src/atomic/text.rs +++ b/crates/nodes/src/atomic/text.rs @@ -208,7 +208,7 @@ mod tests { let vars = BTreeMap::new(); let context = CookContext { w: 256, h: 256, seed: 0, tile: true, inputs: &[], params: &p, resource: &no_res, vars: &vars }; let img = &text(&context).unwrap()[0]; - let lit = img.data.iter().filter(|value| **value > 0.5).count(); + let lit = img.data().iter().filter(|value| **value > 0.5).count(); assert!(lit > 300, "{lit} pixels"); // Centered: nothing in the top and bottom quarters assert!((0..256).all(|x| img.get(x, 20, false)[0] == 0.0 && img.get(x, 236, false)[0] == 0.0)); diff --git a/crates/nodes/src/atomic/transformation.rs b/crates/nodes/src/atomic/transformation.rs index 695ab306..2eb40994 100644 --- a/crates/nodes/src/atomic/transformation.rs +++ b/crates/nodes/src/atomic/transformation.rs @@ -1,6 +1,6 @@ use super::ATOMIC; use crate::{CookContext, CookResult, NodeDefinition, node}; -use materialcraft_image::{Image, Kind}; +use craft_texture::{Image, Kind}; pub(super) fn definition() -> NodeDefinition { node("transformation", "Transformation 2D", ATOMIC) @@ -26,7 +26,7 @@ fn transformation(context: &CookContext) -> CookResult { let nearest = context.i("filtering") == 1; let matte = context.v4("matte"); - Ok(vec![Image::generate_uv(context.w, context.h, input.kind, |u, v| { + Ok(vec![Image::generate_uv(context.w, context.h, input.kind(), |u, v| { let x = u - 0.5 - offset[0]; let y = v - 0.5 - offset[1]; let source_u = (matrix[3] * x - matrix[1] * y) / determinant + 0.5; diff --git a/crates/nodes/src/atomic/uniform.rs b/crates/nodes/src/atomic/uniform.rs index fedde70a..5a415422 100644 --- a/crates/nodes/src/atomic/uniform.rs +++ b/crates/nodes/src/atomic/uniform.rs @@ -1,6 +1,6 @@ use super::ATOMIC; use crate::{CookContext, CookResult, NodeDefinition, node}; -use materialcraft_image::{Image, Kind, luminance}; +use craft_texture::{Image, Kind, luminance}; pub(super) fn definition() -> NodeDefinition { node("uniform", "Uniform color", ATOMIC) diff --git a/crates/nodes/src/atomic/warp.rs b/crates/nodes/src/atomic/warp.rs index bbd1f36f..f0a5d7f9 100644 --- a/crates/nodes/src/atomic/warp.rs +++ b/crates/nodes/src/atomic/warp.rs @@ -1,7 +1,7 @@ use super::ATOMIC; use crate::ops; use crate::{CookContext, CookResult, NodeDefinition, node}; -use materialcraft_image::{Image, Kind}; +use craft_texture::{Image, Kind}; pub(super) fn definition() -> NodeDefinition { node("warp", "Warp", ATOMIC) @@ -18,7 +18,7 @@ fn warp(context: &CookContext) -> CookResult { let img = context.any_or(0, Kind::Gray, [0.0; 4]); let grad = context.gray_or(1, 0.0); let k = context.f("intensity"); - Ok(vec![Image::generate_uv(context.w, context.h, img.kind, |u, v| { + Ok(vec![Image::generate_uv(context.w, context.h, img.kind(), |u, v| { let (x, y) = ((u * context.w as f32) as i64, (v * context.h as f32) as i64); let (dx, dy) = ops::slope(&grad, x, y, context.tile); img.sample(u + dx * k, v + dy * k, context.tile) diff --git a/crates/nodes/src/cook_context.rs b/crates/nodes/src/cook_context.rs index bef04af8..e8177cae 100644 --- a/crates/nodes/src/cook_context.rs +++ b/crates/nodes/src/cook_context.rs @@ -1,5 +1,5 @@ +use craft_texture::{Image, Kind}; use materialcraft_core::{Curve, FunctionGraph, Gradient, Value}; -use materialcraft_image::{Image, Kind}; use std::collections::BTreeMap; /// Where a cook runs: output size, seed, tiling, inputs and resolved parameters @@ -93,7 +93,7 @@ impl CookContext<'_> { /// The kind an "Any" output takes: the main input's, else `fallback` pub fn main_kind(&self, fallback: Kind) -> Kind { - self.inputs.iter().flatten().next().map_or(fallback, |i| i.kind) + self.inputs.iter().flatten().next().map_or(fallback, |i| i.kind()) } /// A gray image from `f(u, v)` at the output size diff --git a/crates/nodes/src/function/evaluation_context.rs b/crates/nodes/src/function/evaluation_context.rs index 449b685e..1a5eba0f 100644 --- a/crates/nodes/src/function/evaluation_context.rs +++ b/crates/nodes/src/function/evaluation_context.rs @@ -1,5 +1,5 @@ +use craft_texture::Image; use materialcraft_core::Value; -use materialcraft_image::Image; use std::collections::BTreeMap; /// Inputs shared by one function evaluation diff --git a/crates/nodes/src/function/operation.rs b/crates/nodes/src/function/operation.rs index f83052de..5281d66c 100644 --- a/crates/nodes/src/function/operation.rs +++ b/crates/nodes/src/function/operation.rs @@ -98,7 +98,7 @@ pub(crate) fn evaluate( let index = usize::try_from(setting[0]).map_err(|_| "negative image index")?; let pixel = match context.images.get(index).and_then(Option::as_ref) { Some(image) if setting[1] == 0 => { - image.get((position[0] * image.w as f32).floor() as i64, (position[1] * image.h as f32).floor() as i64, context.tile) + image.get((position[0] * image.width() as f32).floor() as i64, (position[1] * image.height() as f32).floor() as i64, context.tile) } Some(image) => image.sample(position[0], position[1], context.tile), None => [0.0; 4], diff --git a/crates/nodes/src/function/processor.rs b/crates/nodes/src/function/processor.rs index 801bd2bd..9e337350 100644 --- a/crates/nodes/src/function/processor.rs +++ b/crates/nodes/src/function/processor.rs @@ -1,9 +1,8 @@ use super::{EvaluationContext, EvaluationState, compile}; use crate::{CookContext, CookResult}; +use craft_texture::{Image, Kind, Limits}; use materialcraft_core::Value; -use materialcraft_image::{Image, Kind}; use rayon::prelude::*; -use std::sync::Arc; fn pixel(value: Value, gray: bool) -> Result<[f32; 4], String> { let values = super::value_type::floats(&value)?; @@ -25,7 +24,7 @@ pub(crate) fn pixel_processor(context: &CookContext) -> CookResult { let gray = !context.b("color_mode"); let kind = if gray { Kind::Gray } else { Kind::Color }; - let (width, height) = materialcraft_image::clamp_size(context.w, context.h); + let (width, height) = craft_texture::clamp_size(context.w, context.h); let channels = kind.channels(); let mut data = vec![0.0; width as usize * height as usize * channels]; data.par_chunks_mut(width as usize * channels).enumerate().try_for_each_init(EvaluationState::default, |state, (y, row)| -> Result<(), String> { @@ -44,5 +43,5 @@ pub(crate) fn pixel_processor(context: &CookContext) -> CookResult { } Ok(()) })?; - Ok(vec![Image { w: width, h: height, kind, data: Arc::new(data) }]) + Ok(vec![Image::from_data(width, height, kind, data, &Limits::default()).map_err(|e| e.to_string())?]) } diff --git a/crates/nodes/src/function/tests.rs b/crates/nodes/src/function/tests.rs index 244a36ea..0ba26e80 100644 --- a/crates/nodes/src/function/tests.rs +++ b/crates/nodes/src/function/tests.rs @@ -1,5 +1,5 @@ +use craft_texture::{Image, Kind}; use materialcraft_core::{FunctionGraph, Value}; -use materialcraft_image::{Image, Kind}; use std::collections::{BTreeMap, BTreeSet}; use super::{EvaluationContext, EvaluationState, FUNCTIONS, compile, default_value}; diff --git a/crates/nodes/src/lib.rs b/crates/nodes/src/lib.rs index db54747e..d1a26b41 100644 --- a/crates/nodes/src/lib.rs +++ b/crates/nodes/src/lib.rs @@ -33,7 +33,7 @@ pub use parameter_descriptor::ParameterDescriptor; pub use port_definition::PortDefinition; pub use port_kind::PortKind; -pub type CookResult = Result, String>; +pub type CookResult = Result, String>; pub type Cook = fn(&CookContext<'_>) -> CookResult; #[cfg(test)] diff --git a/crates/nodes/src/ops.rs b/crates/nodes/src/ops.rs index c6a84ad7..7486db4b 100644 --- a/crates/nodes/src/ops.rs +++ b/crates/nodes/src/ops.rs @@ -1,9 +1,7 @@ //! Image operations shared by many nodes: Gaussian blur, Euclidean distance transform, slopes, //! color space helpers and blend modes. -use std::sync::Arc; - -use materialcraft_image::{Image, Kind}; +use craft_texture::{Image, Kind, Limits}; use rayon::prelude::*; /// Gaussian blur with standard deviation `sigma` (pixels). Small sigmas use a sampled kernel; @@ -12,7 +10,7 @@ pub fn gaussian(img: &Image, sigma: f32, tile: bool) -> Image { if sigma.is_nan() || sigma <= 0.05 || !sigma.is_finite() { return img.clone(); } - let sigma = sigma.min(img.w.max(img.h) as f32); + let sigma = sigma.min(img.width().max(img.height()) as f32); if sigma < 3.0 { let r = (sigma * 3.0).ceil() as i64; let k: Vec = (-r..=r).map(|i| (-(i * i) as f32 / (2.0 * sigma * sigma)).exp()).collect(); @@ -37,7 +35,7 @@ pub fn gaussian(img: &Image, sigma: f32, tile: bool) -> Image { fn convolve_1d(src: &Image, k: &[f32], r: i64, horizontal: bool, tile: bool) -> Image { let c = src.channels(); - Image::generate(src.w, src.h, src.kind, |x, y| { + Image::generate(src.width(), src.height(), src.kind(), |x, y| { let mut acc = [0.0f32; 4]; for (i, kv) in k.iter().enumerate() { let o = i as i64 - r; @@ -55,26 +53,27 @@ fn box_1d(src: &Image, r: i64, horizontal: bool, tile: bool) -> Image { if r <= 0 { return src.clone(); } - let (w, h) = (src.w as usize, src.h as usize); + let (w, h) = (src.width() as usize, src.height() as usize); let c = src.channels(); - let inv = 1.0 / (2 * r + 1) as f32; + let inv = 1.0 / (2 * r + 1) as f64; let mut data = vec![0.0f32; w * h * c]; let line_len = if horizontal { w } else { h }; let lines = if horizontal { h } else { w }; - let get = |line: usize, i: i64, ch: usize| -> f32 { + // The running sum is kept in f64, so a window of finite values near `f32::MAX` does not overflow. + let get = |line: usize, i: i64, ch: usize| -> f64 { let n = line_len as i64; let i = if tile { i.rem_euclid(n) } else { i.clamp(0, n - 1) } as usize; let (x, y) = if horizontal { (i, line) } else { (line, i) }; - src.data.get((y * w + x) * c + ch).copied().unwrap_or(0.0) + f64::from(src.data().get((y * w + x) * c + ch).copied().unwrap_or(0.0)) }; let results: Vec> = (0..lines) .into_par_iter() .map(|line| { let mut out = vec![0.0f32; line_len * c]; for ch in 0..c { - let mut sum: f32 = (-r..=r).map(|i| get(line, i, ch)).sum(); + let mut sum: f64 = (-r..=r).map(|i| get(line, i, ch)).sum(); for i in 0..line_len { - out[i * c + ch] = sum * inv; + out[i * c + ch] = (sum * inv) as f32; sum += get(line, i as i64 + r + 1, ch) - get(line, i as i64 - r, ch); } } @@ -88,7 +87,8 @@ fn box_1d(src: &Image, r: i64, horizontal: bool, tile: bool) -> Image { data[dst..dst + c].copy_from_slice(&vals[i * c..i * c + c]); } } - Image { w: src.w, h: src.h, kind: src.kind, data: Arc::new(data) } + // `data` has the size and kind of `src`, which is a valid image. + Image::from_data(src.width(), src.height(), src.kind(), data, &Limits::default()).unwrap_or_else(|_| src.clone()) } /// Squared Euclidean distance (pixels) from every pixel to the nearest pixel where `inside` is @@ -337,9 +337,10 @@ pub fn blend_px(mode: i32, bg: [f32; 4], fg: [f32; 4], opacity: f32, use_alpha: o } -/// A gray image of the output size from per-pixel values. -pub fn gray_from(w: u32, h: u32, v: Vec) -> Image { - Image { w, h, kind: Kind::Gray, data: Arc::new(v) } +/// A gray image of the output size from per-pixel values, or an error when the size is out of +/// range or `v` does not hold one value per pixel. +pub fn gray_from(w: u32, h: u32, v: Vec) -> Result { + Image::from_data(w, h, Kind::Gray, v, &Limits::default()).map_err(|e| e.to_string()) } #[cfg(test)] @@ -370,6 +371,23 @@ mod tests { assert!((flat.get(3, 3, false)[1] - 0.4).abs() < 1e-5); } + #[test] + fn box_blur_of_large_hdr_values_stays_finite() { + let value = 0.75 * f32::MAX; + let blurred = gaussian(&Image::filled(16, 4, Kind::Gray, [value; 4]), 5.0, true); + for x in 0..16 { + let v = blurred.get(x, 1, false)[0]; + assert!(v.is_finite() && (v / value - 1.0).abs() < 1e-5, "pixel {x} is {v}"); + } + } + + #[test] + fn gray_from_rejects_an_empty_size_and_a_wrong_value_count() { + assert!(gray_from(0, 4, Vec::new()).is_err()); + assert!(gray_from(2, 2, vec![0.0; 3]).is_err()); + assert_eq!(gray_from(2, 2, vec![0.5; 4]).map(|image| image.mean()[0]), Ok(0.5)); + } + #[test] fn edt_exact() { let d = distance_sq(9, 1, |i| i == 4, false); diff --git a/crates/nodes/src/pattern/raster.rs b/crates/nodes/src/pattern/raster.rs index 368693ff..f923fa43 100644 --- a/crates/nodes/src/pattern/raster.rs +++ b/crates/nodes/src/pattern/raster.rs @@ -1,4 +1,4 @@ -use materialcraft_image::{Image, Kind}; +use craft_texture::{Image, Kind, Limits}; use std::sync::Arc; use super::{pattern_stamp::PatternStamp, shape}; @@ -7,14 +7,16 @@ use crate::CookContext; const MAX_SAMPLES: u64 = 256_000_000; pub(super) fn render(context: &CookContext, stamps: &[PatternStamp]) -> Result { - let (width, height) = materialcraft_image::clamp_size(context.w, context.h); + let (width, height) = craft_texture::clamp_size(context.w, context.h); let kind = if context.b("color_mode") { Kind::Color } else { Kind::Gray }; - let mut image = + let background = context.input(0).map(|image| image.resize(width, height, context.tile)).unwrap_or_else(|| Image::filled(width, height, kind, context.v4("background"))); - image = if kind == Kind::Gray { image.to_gray() } else { image.to_color() }; + let background = if kind == Kind::Gray { background.to_gray() } else { background.to_color() }; let channels = kind.channels(); let opacity = context.f("opacity").max(0.0); - let pixels = Arc::make_mut(&mut image.data); + let data = Arc::clone(background.shared_data()); + drop(background); + let mut pixels = Arc::unwrap_or_clone(data); let mut budget = MAX_SAMPLES; for stamp in stamps { @@ -63,7 +65,7 @@ pub(super) fn render(context: &CookContext, stamps: &[PatternStamp]) -> Result { let uv = local.map(|coordinate| coordinate * 0.5 + 0.5); if stamp.filtering == 0 { - input.get((uv[0] * input.w as f32) as i64, (uv[1] * input.h as f32) as i64, false) + input.get((uv[0] * input.width() as f32) as i64, (uv[1] * input.height() as f32) as i64, false) } else { input.sample(uv[0], uv[1], false) } @@ -92,5 +94,5 @@ pub(super) fn render(context: &CookContext, stamps: &[PatternStamp]) -> Result], w: u32, h: u32, resource: &(dyn Fn(&str) -> Option + Sync)) -> CookResult { + let params = resolve_params(def, &BTreeMap::new()); + let vars = BTreeMap::new(); + let ctx = CookContext { w, h, seed: 7, tile: false, inputs, params: ¶ms, resource, vars: &vars }; + (def.cook)(&ctx) +} + +/// A request wider than the size limit spreads the normalized coordinates over the clamped width. +#[test] +fn an_oversized_transformation_covers_the_whole_input() { + let ramp = Image::gray(8192, 1, |x, _| x as f32 / 8191.0); + let out = cook_sized(find("transformation").unwrap(), &[Some(ramp)], 16384, 1, &|_| None).unwrap(); + let last = out[0].get(8191, 0, false)[0]; + assert!(last > 0.99, "the last pixel reads the ramp at {last}"); +} + +/// Bilinear resampling between finite values of opposite sign near the float limit stays finite. +#[test] +fn transformation_resamples_extreme_neighbors_to_finite_values() { + let extremes = Image::gray(2, 1, |x, _| if x == 0 { f32::MAX } else { -f32::MAX }); + let out = cook_sized(find("transformation").unwrap(), &[Some(extremes)], 4, 1, &|_| None).unwrap(); + for x in 0..4 { + let value = out[0].get(x, 0, false)[0]; + assert!(value.is_finite(), "pixel {x} is {value}"); + } +} + +/// A repeated input offset far past its edge keeps the offset's phase: an offset near 2^31 lands on +/// the same place as an offset of zero, halfway between the last and the first column. +#[test] +fn directional_warp_repeats_a_far_offset_with_its_phase() { + let stripes = Image::gray(3, 3, |x, _| [0.0, 1.0, 4.0][x as usize]); + // Intensity 10 scales the map by 10 / 256, so this map moves every pixel by about 2^31. + let far = Image::filled(3, 3, Kind::Gray, [2_147_483_648.0 * 25.6; 4]); + let out = cook(find("directional_warp").unwrap(), &[Some(stripes), Some(far)], 3).unwrap(); + for x in 0..3 { + assert_eq!(out[0].get_gray(x, 1, false), 2.0, "pixel {x}"); + } +} + +/// Shrinking a bitmap of large HDR values averages them without overflowing. +#[test] +fn bitmap_shrinks_large_hdr_values_without_overflow() { + let hdr = |_: &str| Some(Image::filled(2, 2, Kind::Color, [0.75 * f32::MAX, 0.75 * f32::MAX, 0.75 * f32::MAX, 1.0])); + let out = cook_sized(find("bitmap").unwrap(), &[], 1, 1, &hdr).unwrap(); + let pixel = out[0].get(0, 0, false); + assert!(pixel.iter().all(|value| value.is_finite()), "{pixel:?}"); + assert!((pixel[0] / (0.75 * f32::MAX) - 1.0).abs() < 1e-6, "{pixel:?}"); +} diff --git a/crates/nodes/tests/distance.rs b/crates/nodes/tests/distance.rs index 2da519af..8bdf5f09 100644 --- a/crates/nodes/tests/distance.rs +++ b/crates/nodes/tests/distance.rs @@ -1,13 +1,13 @@ use std::collections::BTreeMap; +use craft_texture::{Image, Kind}; use materialcraft_core::Value; -use materialcraft_image::{Image, Kind}; use materialcraft_nodes::{CookContext, find, resolve_params}; fn cook(mask: Image, source: Option, tile: bool, combine: bool, distance: f32) -> Image { let def = find("distance").unwrap(); let params = resolve_params(def, &BTreeMap::from([("distance".into(), Value::Float(distance)), ("combine".into(), Value::Bool(combine))])); - let (w, h) = (mask.w, mask.h); + let (w, h) = (mask.width(), mask.height()); let inputs = [Some(mask), source]; let vars = BTreeMap::new(); let resource = |_: &str| None; @@ -22,7 +22,7 @@ fn tiled_distance_spreads_source_across_stationary_gradient() { // This is within range of the only mask pixel, but the symmetric distance field has zero // slope here. A gradient walk stopped on the black source background instead of the seed. assert_eq!(output.get_gray(16, 16, false), 1.0); - assert!(output.data.iter().all(|&v| v == 1.0)); + assert!(output.data().iter().all(|&v| v == 1.0)); } #[test] @@ -54,9 +54,9 @@ fn distance_handles_empty_full_masks_and_no_source() { let empty = Image::filled(7, 5, Kind::Gray, [0.0; 4]); let full = Image::filled(7, 5, Kind::Gray, [1.0; 4]); let source = Image::generate(7, 5, Kind::Color, |x, y| [x as f32 / 7.0, y as f32 / 5.0, 0.4, 0.7]); - assert!(cook(empty.clone(), Some(source.clone()), tile, false, 256.0).data.iter().all(|&v| v == 0.0)); + assert!(cook(empty.clone(), Some(source.clone()), tile, false, 256.0).data().iter().all(|&v| v == 0.0)); assert_eq!(cook(full, Some(source), tile, true, 256.0).get(3, 2, false), [3.0 / 7.0, 2.0 / 5.0, 0.4, 0.7]); - assert!(cook(empty, None, tile, true, 256.0).data.iter().all(|&v| v == 0.0)); + assert!(cook(empty, None, tile, true, 256.0).data().iter().all(|&v| v == 0.0)); let mask = Image::gray(7, 5, |x, y| if x == 0 && y == 0 { 1.0 } else { 0.0 }); let ramp = cook(mask, None, tile, false, 512.0 / 7.0); assert_eq!(ramp.get_gray(0, 0, false), 1.0); diff --git a/crates/render/Cargo.toml b/crates/render/Cargo.toml index a2fe2a08..5e6791c2 100644 --- a/crates/render/Cargo.toml +++ b/crates/render/Cargo.toml @@ -11,5 +11,5 @@ workspace = true [dependencies] materialcraft-core = { workspace = true } materialcraft-geom = { workspace = true } -materialcraft-image = { workspace = true } +craft-texture = { workspace = true } rayon = { workspace = true } diff --git a/crates/render/src/preview.rs b/crates/render/src/preview.rs index 7ba30ba6..8b0ba907 100644 --- a/crates/render/src/preview.rs +++ b/crates/render/src/preview.rs @@ -8,9 +8,9 @@ use std::sync::Arc; use std::sync::atomic::{AtomicBool, Ordering}; use crate::{Displacement, Relief}; +use craft_texture::{Image, linear_to_srgb}; use materialcraft_geom::glam::{Vec2, Vec3}; use materialcraft_geom::{Bvh, Mesh, OrbitCamera}; -use materialcraft_image::{Image, linear_to_srgb}; use rayon::prelude::*; use crate::ibl::{self, EnvImage}; @@ -94,7 +94,7 @@ impl Scene { } // Pre-filtered so detail finer than the mesh (left to the normal map) does not spike the silhouette - let height = height.resize(height.w.min(512), height.h.min(512), true); + let height = height.resize(height.width().min(512), height.height().min(512), true); let level = if displacement.level.is_finite() { displacement.level.clamp(0.0, 1.0) } else { 0.0 }; let depth = if displacement.depth.is_finite() { displacement.depth } else { 0.0 }; let tiling = if displacement.tiling.is_finite() { displacement.tiling.max(0.01) } else { 1.0 }; @@ -538,7 +538,7 @@ pub fn render_cancellable(scene: &Scene, maps: &Maps, light: &Lighting, s: &Sett #[cfg(test)] mod tests { use super::*; - use materialcraft_image::Kind; + use craft_texture::Kind; #[test] fn renders_a_material_on_every_scene() { diff --git a/crates/ui-egui/src/export/export_tests.rs b/crates/ui-egui/src/export/export_tests.rs index 28d6efd7..e18d1f66 100644 --- a/crates/ui-egui/src/export/export_tests.rs +++ b/crates/ui-egui/src/export/export_tests.rs @@ -78,7 +78,7 @@ fn batch_writes_every_material_graph_at_the_output_size() { assert_eq!(files(&directory), ["New_graph_base_color.png", "New_graph_height.png", "Second_mask.png"]); let image = materialcraft_engine::formats::decode(&std::fs::read(directory.join("Second_mask.png")).unwrap(), true).unwrap(); - assert_eq!((image.w, image.h), (64, 32)); + assert_eq!((image.width(), image.height()), (64, 32)); let _ = std::fs::remove_dir_all(directory); } diff --git a/crates/ui-egui/src/graph/canvas.rs b/crates/ui-egui/src/graph/canvas.rs index 850b3826..3fc935dc 100644 --- a/crates/ui-egui/src/graph/canvas.rs +++ b/crates/ui-egui/src/graph/canvas.rs @@ -241,15 +241,15 @@ fn canvas(app: &mut MaterialCraftApp, ui: &mut Ui) { let [width, height] = graph.size_px(); resp.clone().on_hover_text(format!( "{} x {} ({bits}bpc)\n{}: {width} x {height}\n{}: {limit} px\n{}", - img.w, - img.h, + img.width(), + img.height(), tr("Parent size"), tr("Preview limit"), tr("Change Preview size while editing in Edit > Preferences. Exports use each node's configured output size.") )); - format!("{}x{} {}", img.w, img.h, tr("Preview")) + format!("{}x{} {}", img.width(), img.height(), tr("Preview")) } else { - format!("{}x{} - {format}", img.w, img.h) + format!("{}x{} - {format}", img.width(), img.height()) }; painter.text(footer.center(), Align2::CENTER_CENTER, txt, small.clone(), theme.text_dim); } diff --git a/crates/ui-egui/src/levels_editor.rs b/crates/ui-egui/src/levels_editor.rs index 986edb70..bdd4290d 100644 --- a/crates/ui-egui/src/levels_editor.rs +++ b/crates/ui-egui/src/levels_editor.rs @@ -16,10 +16,10 @@ const MIN_SPAN: f32 = 0.004; /// Histograms of an image's values in 0..1, clamped: one for a gray image, else R, G and B pub fn histogram(img: &Image) -> Vec<[u32; BINS]> { - let channels = if img.kind == Kind::Gray { 1 } else { 3 }; - let stride = img.kind.channels(); + let channels = if img.kind() == Kind::Gray { 1 } else { 3 }; + let stride = img.channels(); let mut h = vec![[0u32; BINS]; channels]; - for px in img.data.chunks(stride) { + for px in img.data().chunks(stride) { for (c, bins) in h.iter_mut().enumerate() { let v = px.get(c).copied().unwrap_or(0.0); let v = if v.is_finite() { v.clamp(0.0, 1.0) } else { 0.0 }; diff --git a/crates/ui-egui/src/view2d.rs b/crates/ui-egui/src/view2d.rs index e65308b9..0537797f 100644 --- a/crates/ui-egui/src/view2d.rs +++ b/crates/ui-egui/src/view2d.rs @@ -47,7 +47,7 @@ fn rgba8(img: &Image, channel: &str) -> Vec { _ => None, }; match pick { - Some(k) if img.kind == Kind::Color => base.chunks(4).flat_map(|p| [p[k], p[k], p[k], 255]).collect(), + Some(k) if img.kind() == Kind::Color => base.chunks(4).flat_map(|p| [p[k], p[k], p[k], 255]).collect(), _ => base, } } @@ -95,23 +95,24 @@ pub fn show(app: &mut MaterialCraftApp, ui: &mut Ui) { let texture_limit = ctx.input(|i| i.max_texture_side).max(1); let key = app.session.cooked.nodes.get(&id).map_or(0, |r| r.key) ^ (texture_limit as u64).rotate_left(32) - ^ (img.w as u64).rotate_left(16) - ^ img.h as u64 + ^ (img.width() as u64).rotate_left(16) + ^ img.height() as u64 ^ (app.session.view2d.port as u64).wrapping_mul(0x9e37) ^ (app.session.view2d.channel.len() as u64 * 31) ^ app.session.view2d.channel.bytes().next().unwrap_or(0) as u64; if app.view2d.tex.as_ref().is_none_or(|(k, _)| *k != key) { let px = rgba8(&img, &app.session.view2d.channel); // Keep source pixels for readout/screenshots, but respect the renderer's upload limit. - let ci = if img.w.max(img.h) as usize > texture_limit { - let scale = texture_limit as f64 / f64::from(img.w.max(img.h)); - let display = img.resize((f64::from(img.w) * scale).floor().max(1.0) as u32, (f64::from(img.h) * scale).floor().max(1.0) as u32, false); - ColorImage::from_rgba_unmultiplied([display.w as usize, display.h as usize], &rgba8(&display, &app.session.view2d.channel)) + let ci = if img.width().max(img.height()) as usize > texture_limit { + let scale = texture_limit as f64 / f64::from(img.width().max(img.height())); + let display = + img.resize((f64::from(img.width()) * scale).floor().max(1.0) as u32, (f64::from(img.height()) * scale).floor().max(1.0) as u32, false); + ColorImage::from_rgba_unmultiplied([display.width() as usize, display.height() as usize], &rgba8(&display, &app.session.view2d.channel)) } else { - ColorImage::from_rgba_unmultiplied([img.w as usize, img.h as usize], &px) + ColorImage::from_rgba_unmultiplied([img.width() as usize, img.height() as usize], &px) }; app.view2d.tex = Some((key, ctx.load_texture("view2d", ci, TextureOptions::NEAREST))); - app.view2d.shown = Some((img.w, img.h, px)); + app.view2d.shown = Some((img.width(), img.height(), px)); } let avail = ui.available_size(); let (rect, resp) = ui.allocate_exact_size(vec2(avail.x, (avail.y - 20.0).max(40.0)), Sense::click_and_drag()); @@ -122,7 +123,7 @@ pub fn show(app: &mut MaterialCraftApp, ui: &mut Ui) { app.ui.image_camera = app.ui.image_camera.sanitized(); let cam = &mut app.ui.image_camera; let tiles = if app.session.view2d.tiled { 3.0 } else { 1.0 }; - let fit_zoom = ((rect.width() - 16.0) / (img.w as f32 * tiles)).min((rect.height() - 16.0) / (img.h as f32 * tiles)).max(0.01); + let fit_zoom = ((rect.width() - 16.0) / (img.width() as f32 * tiles)).min((rect.height() - 16.0) / (img.height() as f32 * tiles)).max(0.01); if cam.fit { cam.zoom = fit_zoom; cam.offset = [0.0, 0.0]; @@ -146,11 +147,11 @@ pub fn show(app: &mut MaterialCraftApp, ui: &mut Ui) { let d = resp.drag_delta(); cam.offset = [cam.offset[0] + d.x, cam.offset[1] + d.y]; } - let size = vec2(img.w as f32, img.h as f32) * cam.zoom; + let size = vec2(img.width() as f32, img.height() as f32) * cam.zoom; let center = rect.center() + vec2(cam.offset[0], cam.offset[1]); let full = Rect::from_center_size(center, size * tiles); // A checker behind transparent images. - if img.kind == Kind::Color && app.session.view2d.channel == "rgba" { + if img.kind() == Kind::Color && app.session.view2d.channel == "rgba" { let cell = 8.0; let vis = full.intersect(rect); let mut y = vis.top(); @@ -181,15 +182,16 @@ pub fn show(app: &mut MaterialCraftApp, ui: &mut Ui) { // Info line: size, format, zoom and the pixel under the pointer. let info = Rect::from_min_size(pos2(rect.left(), rect.bottom()), vec2(rect.width(), 20.0)); let bits = app.session.cooked.nodes.get(&id).map_or("16", |result| result.base.format.bits()); - let mut text = format!("{} x {} ({}, {}bpc) {:.0}%", img.w, img.h, if img.is_gray() { "L" } else { "RGBA" }, bits, cam.zoom * 100.0); + let mut text = format!("{} x {} ({}, {}bpc) {:.0}%", img.width(), img.height(), if img.is_gray() { "L" } else { "RGBA" }, bits, cam.zoom * 100.0); if let Some(ptr) = resp.hover_pos() { let local = (ptr - (center - size * 0.5)) / cam.zoom; let (x, y) = (local.x.floor() as i64, local.y.floor() as i64); let v = img.get(x, y, true); if img.is_gray() { - text += &format!(" ({}, {}) {:.3}", x.rem_euclid(img.w as i64), y.rem_euclid(img.h as i64), v[0]); + text += &format!(" ({}, {}) {:.3}", x.rem_euclid(img.width() as i64), y.rem_euclid(img.height() as i64), v[0]); } else { - text += &format!(" ({}, {}) {:.3} {:.3} {:.3} {:.3}", x.rem_euclid(img.w as i64), y.rem_euclid(img.h as i64), v[0], v[1], v[2], v[3]); + text += + &format!(" ({}, {}) {:.3} {:.3} {:.3} {:.3}", x.rem_euclid(img.width() as i64), y.rem_euclid(img.height() as i64), v[0], v[1], v[2], v[3]); } } ui.painter().rect_filled(info, 0.0, tk.panel); diff --git a/crates/ui-egui/tests/it/preview_resolution.rs b/crates/ui-egui/tests/it/preview_resolution.rs index 59c3532d..c8e414fa 100644 --- a/crates/ui-egui/tests/it/preview_resolution.rs +++ b/crates/ui-egui/tests/it/preview_resolution.rs @@ -48,7 +48,7 @@ fn painted(h: &Harness<'static, MaterialCraftApp>) -> Vec { fn node_resolution_explains_the_preview_cap() { let (mut h, id) = harness(512, false); let img = h.state().session.cooked.image(id, 0).unwrap(); - assert_eq!((img.w, img.h), (512, 512)); + assert_eq!((img.width(), img.height()), (512, 512)); assert_eq!(h.state().session.graph().unwrap().size, [10, 10]); assert!(painted(&h).iter().any(|t| t == "512x512 Preview"), "missing preview label: {:?}", painted(&h)); let rect = h.state().graph.rects.iter().find(|(n, _)| *n == id).unwrap().1; @@ -61,14 +61,14 @@ fn node_resolution_explains_the_preview_cap() { assert!(text.contains("16bpc"), "format information lost: {text}"); let full = h.state().session.cook_full(0); let img = full.image(id, 0).unwrap(); - assert_eq!((img.w, img.h), (1024, 1024)); + assert_eq!((img.width(), img.height()), (1024, 1024)); } #[test] fn full_size_mode_retains_the_resolution_and_format() { let (h, id) = harness(0, false); let img = h.state().session.cooked.image(id, 0).unwrap(); - assert_eq!((img.w, img.h), (1024, 1024)); + assert_eq!((img.width(), img.height()), (1024, 1024)); assert!(painted(&h).iter().any(|t| t == "1024x1024 - C16"), "{:?}", painted(&h)); assert!(!painted(&h).iter().any(|t| t == "1024x1024 Preview")); } diff --git a/crates/ui-egui/tests/it/resolution.rs b/crates/ui-egui/tests/it/resolution.rs index 64231d57..40140ae4 100644 --- a/crates/ui-egui/tests/it/resolution.rs +++ b/crates/ui-egui/tests/it/resolution.rs @@ -25,8 +25,8 @@ fn choose_4k(h: &mut Harness<'static, MaterialCraftApp>) { h.step(); let app = h.state(); let (_, image) = app.session.view2d_image().unwrap(); - assert_eq!((image.w, image.h), (4096, 4096)); - assert!(app.session.material_maps().iter().all(|(_, image)| (image.w, image.h) == (4096, 4096))); + assert_eq!((image.width(), image.height()), (4096, 4096)); + assert!(app.session.material_maps().iter().all(|(_, image)| (image.width(), image.height()) == (4096, 4096))); assert!(!app.session.material_maps().is_empty()); assert_eq!(app.view2d.shown.as_ref().map(|(w, h, _)| (*w, *h)), Some((4096, 4096))); } @@ -66,7 +66,7 @@ fn four_k_preview_refreshes_texture_after_size_change() { h.state_mut().ui.prefs.preview_size = 4096; h.step(); let (_, image) = h.state().session.view2d_image().unwrap(); - assert_eq!((image.w, image.h), (4096, 4096)); + assert_eq!((image.width(), image.height()), (4096, 4096)); assert_eq!(h.state().view2d.shown.as_ref().map(|(w, h, _)| (*w, *h)), Some((4096, 4096))); h.state_mut().session.preview_size = Some(256); h.state_mut().session.cook(); @@ -74,7 +74,7 @@ fn four_k_preview_refreshes_texture_after_size_change() { h.state_mut().ui.prefs.preview_size = 256; h.step(); let (_, image) = h.state().session.view2d_image().unwrap(); - assert_eq!((image.w, image.h), (256, 256)); + assert_eq!((image.width(), image.height()), (256, 256)); assert_eq!(h.state().view2d.shown.as_ref().map(|(w, h, _)| (*w, *h)), Some((256, 256))); } diff --git a/crates/ui-egui/tests/snapshot.rs b/crates/ui-egui/tests/snapshot.rs index 9ef06c62..58de37cc 100644 --- a/crates/ui-egui/tests/snapshot.rs +++ b/crates/ui-egui/tests/snapshot.rs @@ -1223,7 +1223,7 @@ fn named_outputs_select_without_loading_and_open_on_double_click() { app.run("view.2d", json!({"node": source})).unwrap(); app.run("graph.select", json!({"ids": [source]})).unwrap(); app.session.cook(); - let material = app.session.material_maps().into_iter().map(|(name, image)| (name, image.data.clone())).collect::>(); + let material = app.session.material_maps().into_iter().map(|(name, image)| (name, image.shared_data().clone())).collect::>(); let view3d = serde_json::to_value(&app.session.view3d).unwrap(); let mut harness = harness(app, 1600.0, 960.0); settle(&mut harness, 5); @@ -1248,7 +1248,7 @@ fn named_outputs_select_without_loading_and_open_on_double_click() { assert_eq!(harness.state().session.selection, vec![materialcraft_engine::core::NodeId(output)]); assert!(harness.query_all(By::new().label("Identifier")).next().is_some()); assert_eq!(serde_json::to_value(&harness.state().session.view3d).unwrap(), view3d); - let current = harness.state().session.material_maps().into_iter().map(|(name, image)| (name, image.data.clone())).collect::>(); + let current = harness.state().session.material_maps().into_iter().map(|(name, image)| (name, image.shared_data().clone())).collect::>(); assert_eq!(current, material); save(&mut harness, &directory, "named-output-preview"); } diff --git a/docs/architecture.md b/docs/architecture.md index d357c061..690a3119 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -9,8 +9,8 @@ them). Everything below the UI is plain Rust with no UI toolkit and builds for ```text L0 core document model: Package → Graph → Node / Connection / Frame / Comment / Pin / ExposedParameter; Value (float, vectors, int, bool, color, enum, text, curve, gradient, function graph) -L0 image Image: grayscale or RGBA f32 planes behind an Arc (copy-on-write, free to share); - wrap/clamp sampling, bilinear, box/bilinear resampling, sRGB, 8-bit display +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; shared image operations and iterative function/pattern execution diff --git a/xtask/src/layers.rs b/xtask/src/layers.rs index 99f47644..c551092d 100644 --- a/xtask/src/layers.rs +++ b/xtask/src/layers.rs @@ -12,7 +12,7 @@ use serde_json::Value; /// Library crates by directory under `crates/` (package `materialcraft-`) and their layer. pub const TABLE: &[(&str, u8)] = - &[("core", 0), ("image", 0), ("geom", 0), ("nodes", 1), ("eval", 2), ("formats", 2), ("engine", 3), ("render", 3), ("automation", 4), ("ui-egui", 5)]; + &[("core", 0), ("geom", 0), ("nodes", 1), ("eval", 2), ("formats", 2), ("engine", 3), ("render", 3), ("automation", 4), ("ui-egui", 5)]; /// Binaries and build tooling on top of every layer: exempt from the rules. pub const EXEMPT: &[&str] = &["materialcraft", "materialcraft-cli", "materialcraft-web", "xtask"]; @@ -149,7 +149,7 @@ mod tests { fn downward_graph_passes() { let g = [ c("materialcraft-core", &[("serde", Normal, false)]), - c("materialcraft-nodes", &[("materialcraft-core", Normal, true), ("materialcraft-image", Normal, true)]), + c("materialcraft-nodes", &[("materialcraft-core", Normal, true), ("materialcraft-geom", Normal, true)]), c("materialcraft-engine", &[("materialcraft-eval", Normal, true), ("materialcraft-geom", Dev, true)]), c("materialcraft-render", &[("materialcraft-nodes", Normal, true), ("wgpu", Normal, false)]), c("materialcraft-ui-egui", &[("materialcraft-automation", Normal, true), ("egui", Normal, false), ("wgpu", Normal, false)]), diff --git a/xtask/src/main.rs b/xtask/src/main.rs index 240fd0e1..c3cfe00d 100644 --- a/xtask/src/main.rs +++ b/xtask/src/main.rs @@ -111,7 +111,6 @@ fn cmd_layers() -> Result<(), String> { /// Packages that must build for wasm32-unknown-unknown, in dependency order. const WASM_PACKAGES: &[&str] = &[ "materialcraft-core", - "materialcraft-image", "materialcraft-geom", "materialcraft-nodes", "materialcraft-eval",