mirror of
https://github.com/storytold/materialcraft.git
synced 2026-11-20 22:40:59 +01:00
Merge pull request #243 from dotCooCoo/feat/image-craft-texture
Image: use craft-texture's image planes and sampling
This commit is contained in:
110 files changed
+1101
-1183
No files matched your search
@@ -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)
|
||||
|
||||
Generated
+27
-28
@@ -832,7 +832,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-atomic"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=6e03f65bf45181db77ba6229716e6624db9eb25b#6e03f65bf45181db77ba6229716e6624db9eb25b"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=92fb3fa8ac2981c4c31961cfce7f7fdfbb03540d#92fb3fa8ac2981c4c31961cfce7f7fdfbb03540d"
|
||||
dependencies = [
|
||||
"rustix 1.1.6",
|
||||
]
|
||||
@@ -845,7 +845,7 @@ source = "git+https://github.com/storytold/craft-libs?rev=ea24422ae9859dc5da398d
|
||||
[[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=92fb3fa8ac2981c4c31961cfce7f7fdfbb03540d#92fb3fa8ac2981c4c31961cfce7f7fdfbb03540d"
|
||||
dependencies = [
|
||||
"block2 0.6.2",
|
||||
"objc2 0.6.5",
|
||||
@@ -858,12 +858,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=92fb3fa8ac2981c4c31961cfce7f7fdfbb03540d#92fb3fa8ac2981c4c31961cfce7f7fdfbb03540d"
|
||||
|
||||
[[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=92fb3fa8ac2981c4c31961cfce7f7fdfbb03540d#92fb3fa8ac2981c4c31961cfce7f7fdfbb03540d"
|
||||
dependencies = [
|
||||
"fixed_decimal",
|
||||
"icu_decimal",
|
||||
@@ -920,7 +920,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=92fb3fa8ac2981c4c31961cfce7f7fdfbb03540d#92fb3fa8ac2981c4c31961cfce7f7fdfbb03540d"
|
||||
dependencies = [
|
||||
"egui",
|
||||
"serde",
|
||||
@@ -930,7 +930,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-mcmat"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=828b07f3c9f3f6a2e935087b859016a5e46b1c31#828b07f3c9f3f6a2e935087b859016a5e46b1c31"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=92fb3fa8ac2981c4c31961cfce7f7fdfbb03540d#92fb3fa8ac2981c4c31961cfce7f7fdfbb03540d"
|
||||
dependencies = [
|
||||
"craft-zip",
|
||||
"serde",
|
||||
@@ -941,7 +941,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=92fb3fa8ac2981c4c31961cfce7f7fdfbb03540d#92fb3fa8ac2981c4c31961cfce7f7fdfbb03540d"
|
||||
dependencies = [
|
||||
"craft-keymap",
|
||||
"craft-quit",
|
||||
@@ -984,7 +984,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=92fb3fa8ac2981c4c31961cfce7f7fdfbb03540d#92fb3fa8ac2981c4c31961cfce7f7fdfbb03540d"
|
||||
dependencies = [
|
||||
"dispatch2",
|
||||
"egui",
|
||||
@@ -1021,6 +1021,15 @@ dependencies = [
|
||||
"thiserror 2.0.21",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-texture"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=92fb3fa8ac2981c4c31961cfce7f7fdfbb03540d#92fb3fa8ac2981c4c31961cfce7f7fdfbb03540d"
|
||||
dependencies = [
|
||||
"rayon",
|
||||
"thiserror 2.0.21",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-tiff"
|
||||
version = "0.1.0"
|
||||
@@ -1033,7 +1042,7 @@ dependencies = [
|
||||
[[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=92fb3fa8ac2981c4c31961cfce7f7fdfbb03540d#92fb3fa8ac2981c4c31961cfce7f7fdfbb03540d"
|
||||
dependencies = [
|
||||
"craft-fonts-build",
|
||||
"craft-i18n",
|
||||
@@ -1054,7 +1063,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=92fb3fa8ac2981c4c31961cfce7f7fdfbb03540d#92fb3fa8ac2981c4c31961cfce7f7fdfbb03540d"
|
||||
dependencies = [
|
||||
"chrono",
|
||||
"dunce",
|
||||
@@ -1081,7 +1090,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=92fb3fa8ac2981c4c31961cfce7f7fdfbb03540d#92fb3fa8ac2981c4c31961cfce7f7fdfbb03540d"
|
||||
dependencies = [
|
||||
"egui",
|
||||
"objc2 0.6.5",
|
||||
@@ -1112,7 +1121,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-zip"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=828b07f3c9f3f6a2e935087b859016a5e46b1c31#828b07f3c9f3f6a2e935087b859016a5e46b1c31"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=92fb3fa8ac2981c4c31961cfce7f7fdfbb03540d#92fb3fa8ac2981c4c31961cfce7f7fdfbb03540d"
|
||||
dependencies = [
|
||||
"flate2",
|
||||
"thiserror 2.0.21",
|
||||
@@ -2817,9 +2826,7 @@ dependencies = [
|
||||
"getrandom 0.3.4",
|
||||
"image",
|
||||
"materialcraft-engine",
|
||||
"materialcraft-formats",
|
||||
"materialcraft-render",
|
||||
"rayon",
|
||||
"rmcp",
|
||||
"rustix 1.1.6",
|
||||
"schemars",
|
||||
@@ -2853,11 +2860,11 @@ dependencies = [
|
||||
name = "materialcraft-engine"
|
||||
version = "0.4.1"
|
||||
dependencies = [
|
||||
"craft-texture 0.1.0 (git+https://github.com/storytold/craft-libs?rev=92fb3fa8ac2981c4c31961cfce7f7fdfbb03540d)",
|
||||
"materialcraft-core",
|
||||
"materialcraft-eval",
|
||||
"materialcraft-formats",
|
||||
"materialcraft-geom",
|
||||
"materialcraft-image",
|
||||
"materialcraft-nodes",
|
||||
"serde",
|
||||
"serde_json",
|
||||
@@ -2869,9 +2876,9 @@ dependencies = [
|
||||
name = "materialcraft-eval"
|
||||
version = "0.4.1"
|
||||
dependencies = [
|
||||
"craft-texture 0.1.0 (git+https://github.com/storytold/craft-libs?rev=92fb3fa8ac2981c4c31961cfce7f7fdfbb03540d)",
|
||||
"half",
|
||||
"materialcraft-core",
|
||||
"materialcraft-image",
|
||||
"materialcraft-nodes",
|
||||
"serde",
|
||||
"serde_json",
|
||||
@@ -2887,14 +2894,14 @@ dependencies = [
|
||||
"craft-mesh",
|
||||
"craft-mime",
|
||||
"craft-svg",
|
||||
"craft-texture",
|
||||
"craft-texture 0.1.0 (git+https://github.com/storytold/craft-libs?rev=726ad0f8290bedb6ced60fa06200a6b574f9990d)",
|
||||
"craft-texture 0.1.0 (git+https://github.com/storytold/craft-libs?rev=92fb3fa8ac2981c4c31961cfce7f7fdfbb03540d)",
|
||||
"craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=b6d9feed23ceae249b40593ed84a668343091627)",
|
||||
"dds",
|
||||
"flate2",
|
||||
"image",
|
||||
"materialcraft-core",
|
||||
"materialcraft-geom",
|
||||
"materialcraft-image",
|
||||
"materialcraft-nodes",
|
||||
"roxmltree 0.20.0",
|
||||
"serde",
|
||||
@@ -2915,20 +2922,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 0.1.0 (git+https://github.com/storytold/craft-libs?rev=92fb3fa8ac2981c4c31961cfce7f7fdfbb03540d)",
|
||||
"materialcraft-core",
|
||||
"materialcraft-image",
|
||||
"rayon",
|
||||
]
|
||||
|
||||
@@ -2936,9 +2935,9 @@ dependencies = [
|
||||
name = "materialcraft-render"
|
||||
version = "0.4.1"
|
||||
dependencies = [
|
||||
"craft-texture 0.1.0 (git+https://github.com/storytold/craft-libs?rev=92fb3fa8ac2981c4c31961cfce7f7fdfbb03540d)",
|
||||
"materialcraft-core",
|
||||
"materialcraft-geom",
|
||||
"materialcraft-image",
|
||||
"rayon",
|
||||
]
|
||||
|
||||
|
||||
+14
-16
@@ -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",
|
||||
@@ -53,7 +51,6 @@ craft-xml = { version = "0.1.0", git = "https://github.com/storytold/craft-libs"
|
||||
craft-svg = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "57288edafdc45552e30481cc649021de446abfa0", features = ["tree-render"] }
|
||||
# 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" }
|
||||
@@ -76,7 +73,6 @@ dds = { version = "0.2", default-features = false }
|
||||
half = "2"
|
||||
eframe = { version = "0.37", default-features = false }
|
||||
egui = "0.37"
|
||||
wgpu = "30"
|
||||
rfd = "0.17"
|
||||
rustix = { version = "1", default-features = false, features = ["std", "fs", "process"] }
|
||||
zip = { version = "2", default-features = false, features = ["deflate"] }
|
||||
@@ -90,25 +86,27 @@ flate2 = { version = "1", default-features = false, features = ["rust_backend"]
|
||||
cap-std = "4"
|
||||
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.
|
||||
# MIT OR Apache-2.0, with each dependency pinned to its reviewed revision
|
||||
egui_kittest = "0.37"
|
||||
craft-mcmat = { git = "https://github.com/storytold/craft-libs", rev = "828b07f3c9f3f6a2e935087b859016a5e46b1c31" }
|
||||
craft-ui = { git = "https://github.com/storytold/craft-libs", rev = "6e03f65bf45181db77ba6229716e6624db9eb25b", features = ["serde"] }
|
||||
craft-mcmat = { git = "https://github.com/storytold/craft-libs", rev = "92fb3fa8ac2981c4c31961cfce7f7fdfbb03540d" }
|
||||
craft-ui = { git = "https://github.com/storytold/craft-libs", rev = "92fb3fa8ac2981c4c31961cfce7f7fdfbb03540d", 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 = "92fb3fa8ac2981c4c31961cfce7f7fdfbb03540d", 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 = "92fb3fa8ac2981c4c31961cfce7f7fdfbb03540d" }
|
||||
# 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 = "92fb3fa8ac2981c4c31961cfce7f7fdfbb03540d", features = ["egui"] }
|
||||
craft-menu = { git = "https://github.com/storytold/craft-libs", rev = "92fb3fa8ac2981c4c31961cfce7f7fdfbb03540d" }
|
||||
# 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 = "92fb3fa8ac2981c4c31961cfce7f7fdfbb03540d", 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 = "92fb3fa8ac2981c4c31961cfce7f7fdfbb03540d", features = ["egui"] }
|
||||
# Atomic persistence, at the suite's current revision.
|
||||
craft-atomic = { git = "https://github.com/storytold/craft-libs", rev = "6e03f65bf45181db77ba6229716e6624db9eb25b" }
|
||||
craft-atomic = { git = "https://github.com/storytold/craft-libs", rev = "92fb3fa8ac2981c4c31961cfce7f7fdfbb03540d" }
|
||||
# Parse the optional shared font catalog at build time; the font repository is not a dependency.
|
||||
craft-fonts-build = { git = "https://github.com/storytold/craft-libs", rev = "6e03f65bf45181db77ba6229716e6624db9eb25b" }
|
||||
craft-fonts-build = { git = "https://github.com/storytold/craft-libs", rev = "92fb3fa8ac2981c4c31961cfce7f7fdfbb03540d" }
|
||||
# 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 = "92fb3fa8ac2981c4c31961cfce7f7fdfbb03540d", features = ["parallel"] }
|
||||
|
||||
# egui 0.37 and winit: the suite's forks (storytold/egui, storytold/winit), as craft-libs pins them.
|
||||
[patch.crates-io]
|
||||
@@ -165,7 +163,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
|
||||
|
||||
@@ -186,7 +186,7 @@ See [the primitive workflow](docs/atomic-workflow.md) for usage, validation scop
|
||||
The [catalog status](docs/node-catalog-parity.md) records implemented behavior and remaining work.
|
||||
Full numerical compatibility and arbitrary SBS interoperability remain unestablished.
|
||||
|
||||
**Workspace:** `crates/{core, 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.
|
||||
|
||||
@@ -11,12 +11,10 @@ workspace = true
|
||||
[dependencies]
|
||||
materialcraft-engine = { workspace = true }
|
||||
materialcraft-render = { workspace = true }
|
||||
materialcraft-formats = { workspace = true }
|
||||
serde = { workspace = true }
|
||||
serde_json = { workspace = true }
|
||||
thiserror = { workspace = true }
|
||||
image = { workspace = true }
|
||||
rayon = { workspace = true }
|
||||
rmcp = { workspace = true }
|
||||
tokio = { workspace = true }
|
||||
schemars = { workspace = true }
|
||||
|
||||
@@ -264,15 +264,15 @@ impl Headless {
|
||||
Ok(Rendered { width: w, height: h, png })
|
||||
}
|
||||
|
||||
fn render_2d(&mut self, o: &RenderOptions, max: u32) -> Result<(u32, u32, Vec<u8>), AutomationError> {
|
||||
let img = match o.node {
|
||||
Some(n) => self.session.cooked.image(NodeId(n), o.port.unwrap_or(0)).ok_or_else(|| bad(format!("node {n} has no cooked output")))?,
|
||||
fn render_2d(&mut self, options: &RenderOptions, maximum_side: u32) -> Result<(u32, u32, Vec<u8>), AutomationError> {
|
||||
let image = match options.node {
|
||||
Some(n) => self.session.cooked.image(NodeId(n), options.port.unwrap_or(0)).ok_or_else(|| bad(format!("node {n} has no cooked output")))?,
|
||||
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 img = img.resize(w, h, true);
|
||||
Ok((w, h, img.to_rgba8_display()))
|
||||
let (w, h) = (options.width.unwrap_or(image.width()).clamp(16, maximum_side), options.height.unwrap_or(image.height()).clamp(16, maximum_side));
|
||||
let image = image.resize(w, h, true);
|
||||
Ok((w, h, image.to_rgba8_display()))
|
||||
}
|
||||
|
||||
fn render_3d(&mut self, o: &RenderOptions, max: u32) -> (u32, u32, Vec<u8>) {
|
||||
|
||||
@@ -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 }
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
use std::collections::{HashMap, HashSet};
|
||||
|
||||
use materialcraft_image::Image;
|
||||
use craft_texture::Image;
|
||||
|
||||
const DEFAULT_LIMIT_BYTES: usize = 128 << 20;
|
||||
const MAX_ENTRIES: usize = 128;
|
||||
@@ -68,20 +68,20 @@ impl DecodedImages {
|
||||
}
|
||||
|
||||
fn bytes(image: &Image) -> usize {
|
||||
image.data.len().saturating_mul(size_of::<f32>())
|
||||
image.data().len().saturating_mul(size_of::<f32>())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use materialcraft_image::Kind;
|
||||
use craft_texture::Kind;
|
||||
use std::sync::Arc;
|
||||
|
||||
#[test]
|
||||
fn repeated_decodes_are_bounded_and_evicted_images_are_released() {
|
||||
let mut cache = DecodedImages::new(128);
|
||||
let image = Image::filled(4, 4, Kind::Gray, [0.5; 4]);
|
||||
let weak = Arc::downgrade(&image.data);
|
||||
let weak = Arc::downgrade(image.shared_data());
|
||||
cache.insert((0, false), image);
|
||||
for key in 1..1_000 {
|
||||
cache.insert((key, key % 2 == 0), Image::filled(4, 4, Kind::Gray, [0.5; 4]));
|
||||
@@ -113,7 +113,7 @@ mod tests {
|
||||
assert!(cache.get(&(1, false)).is_none());
|
||||
|
||||
let large = Image::filled(16, 16, Kind::Gray, [0.5; 4]);
|
||||
let weak = Arc::downgrade(&large.data);
|
||||
let weak = Arc::downgrade(large.shared_data());
|
||||
cache.insert((3, false), large);
|
||||
|
||||
assert!(weak.upgrade().is_none());
|
||||
|
||||
@@ -149,26 +149,27 @@ fn format(s: &mut Session, p: &J) -> Result<J> {
|
||||
})
|
||||
}
|
||||
|
||||
fn cook(s: &mut Session, p: &J) -> Result<J> {
|
||||
let index = match p.get("graph").filter(|graph| !graph.is_null()) {
|
||||
None => s.graph,
|
||||
fn cook(session: &mut Session, parameters: &J) -> Result<J> {
|
||||
let index = match parameters.get("graph").filter(|graph| !graph.is_null()) {
|
||||
None => session.graph,
|
||||
Some(graph) => {
|
||||
let index = graph.as_u64().and_then(|index| usize::try_from(index).ok()).ok_or_else(|| bad("graph.cook", "`graph` is a graph index"))?;
|
||||
let graph = s.pkg.graph(index)?;
|
||||
let graph = session.pkg.graph(index)?;
|
||||
if graph.function.is_some() {
|
||||
return Err(bad("graph.cook", "a Function Graph has no outputs to compute"));
|
||||
}
|
||||
|
||||
index
|
||||
}
|
||||
};
|
||||
let cooked = if index != s.graph || boolp(p, "full") == Some(true) { s.cook_full(index) } else { s.cook().clone() };
|
||||
let g = s.pkg.graph(index)?;
|
||||
let cooked = if index != session.graph || boolp(parameters, "full") == Some(true) { session.cook_full(index) } else { session.cook().clone() };
|
||||
let graph = session.pkg.graph(index)?;
|
||||
Ok(json!({
|
||||
"ms": cooked.ms,
|
||||
"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])})
|
||||
"nodes": cooked.nodes.iter().map(|(id, result)| {
|
||||
let node = graph.node(*id).ok();
|
||||
json!({"id": id.0, "def": node.map(|node| node.def.clone()), "ms": result.ms, "cached": result.cached, "error": result.error,
|
||||
"size": result.outputs.first().and_then(materialcraft_eval::NodeOutput::as_image).map(|image| [image.width(), image.height()])})
|
||||
}).collect::<Vec<_>>(),
|
||||
}))
|
||||
}
|
||||
|
||||
@@ -32,7 +32,7 @@ pub fn session(session: &Session, requested_graph: Option<usize>) -> 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<usize>) -> 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::<Vec<_>>(),
|
||||
},
|
||||
"previewSize": session.preview_size,
|
||||
|
||||
@@ -88,10 +88,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;
|
||||
|
||||
@@ -4,8 +4,8 @@ use std::collections::BTreeMap;
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
|
||||
use craft_texture::{Image, Kind};
|
||||
use materialcraft_core::Package;
|
||||
use materialcraft_image::{Image, Kind};
|
||||
|
||||
use crate::{NodeLibrary, Session};
|
||||
|
||||
@@ -32,7 +32,7 @@ impl NodeLibrary {
|
||||
let index = source.graphs.iter().position(|candidate| candidate.function.is_none() && candidate.sbs_path() == graph)?;
|
||||
let size = size.clamp(1, COOKED_SIZE);
|
||||
|
||||
// A session links the graph's instances and functions to the library, as an opened package gets
|
||||
// A session resolves library references just as it does for an opened package
|
||||
let mut session = Session::with_library(Package::clone(source), library.clone());
|
||||
session.limit_preview_caches();
|
||||
if cancel.load(Ordering::Relaxed) {
|
||||
@@ -43,7 +43,7 @@ impl NodeLibrary {
|
||||
let decode = session.resource_decoder();
|
||||
let mut options = materialcraft_eval::Options::new(&decode);
|
||||
|
||||
// Thin lines and fine grain vanish when cooked at thumbnail size, so the graph cooks larger and is scaled down
|
||||
// Cook larger before downsampling so fine detail survives in thumbnails
|
||||
let cooked_size = size.max(COOKED_SIZE);
|
||||
options.max_size = Some(cooked_size);
|
||||
options.cancel = Some(cancel);
|
||||
@@ -60,7 +60,7 @@ impl NodeLibrary {
|
||||
let outputs = materialcraft_eval::outputs(graph, &cooked);
|
||||
let base_color = outputs.iter().find(|(_, usage, _, image)| *usage == "baseColor" && image.is_some());
|
||||
let image = base_color.or_else(|| outputs.iter().find(|output| output.3.is_some()))?.3?;
|
||||
(!is_flat(image)).then(|| image.resize(size.min(image.w), size.min(image.h), false))
|
||||
(!is_flat(image)).then(|| image.resize(size.min(image.width()), size.min(image.height()), false))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -101,8 +101,8 @@ fn sample_inputs(graph: &materialcraft_core::Graph, size: u32) -> BTreeMap<Strin
|
||||
fn is_flat(image: &Image) -> bool {
|
||||
let mut low = [f32::INFINITY; 3];
|
||||
let mut high = [f32::NEG_INFINITY; 3];
|
||||
for y in 0..i64::from(image.h) {
|
||||
for x in 0..i64::from(image.w) {
|
||||
for y in 0..i64::from(image.height()) {
|
||||
for x in 0..i64::from(image.width()) {
|
||||
let pixel = image.get(x, y, false);
|
||||
for channel in 0..3 {
|
||||
low[channel] = low[channel].min(pixel[channel]);
|
||||
|
||||
@@ -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;
|
||||
@@ -54,64 +54,66 @@ pub(crate) fn specs() -> Vec<CommandSpec> {
|
||||
|
||||
pub use crate::MaterialOptions;
|
||||
|
||||
/// Cook graph `gi` with `o` and pack it as a portable material (`.mcmat` bytes)
|
||||
pub fn material_bytes(s: &Session, gi: usize, o: &MaterialOptions) -> Result<Vec<u8>> {
|
||||
let mut pkg = s.pkg.clone();
|
||||
let g = pkg.graph_mut(gi)?;
|
||||
if let Some(px) = o.size {
|
||||
let log2 = 31 - px.clamp(16, 8192).leading_zeros();
|
||||
g.size = [log2, log2];
|
||||
/// Cook `graph_index` with `options` and pack it as a portable material (`.mcmat` bytes)
|
||||
pub fn material_bytes(session: &Session, graph_index: usize, options: &MaterialOptions) -> Result<Vec<u8>> {
|
||||
let mut package = session.pkg.clone();
|
||||
let graph = package.graph_mut(graph_index)?;
|
||||
if let Some(side_pixels) = options.size {
|
||||
let log2 = 31 - side_pixels.clamp(16, 8192).leading_zeros();
|
||||
graph.size = [log2, log2];
|
||||
}
|
||||
g.inputs.extend(o.values.clone());
|
||||
let g = pkg.graph(gi)?;
|
||||
let dec = s.resource_decoder();
|
||||
let mut opts = materialcraft_eval::Options::new(&dec);
|
||||
opts.environment = s.environment;
|
||||
opts.inputs = o.inputs.clone();
|
||||
let cooked = materialcraft_eval::cook(&pkg, gi, &opts, &s.cache);
|
||||
graph.inputs.extend(options.values.clone());
|
||||
let graph = package.graph(graph_index)?;
|
||||
let decode = session.resource_decoder();
|
||||
let mut cook_options = materialcraft_eval::Options::new(&decode);
|
||||
cook_options.environment = session.environment;
|
||||
cook_options.inputs = options.inputs.clone();
|
||||
let cooked = materialcraft_eval::cook(&package, graph_index, &cook_options, &session.cache);
|
||||
let mut maps: Vec<(String, Vec<u8>)> = Vec::new();
|
||||
let mut entries = Vec::new();
|
||||
let mut size = [0, 0];
|
||||
for (_, usage, _, img) in materialcraft_eval::outputs(g, &cooked) {
|
||||
let Some(img) = img else { continue };
|
||||
for (_, usage, _, image) in materialcraft_eval::outputs(graph, &cooked) {
|
||||
let Some(image) = image else { continue };
|
||||
if usage == "any" || entries.iter().any(|e: &MapEntry| e.usage == usage) {
|
||||
continue;
|
||||
}
|
||||
|
||||
let srgb = srgb_usage(usage);
|
||||
let file = format!("maps/{usage}.png");
|
||||
maps.push((file.clone(), encode(img, "png", if srgb { Depth::U8 } else { Depth::U16 }, srgb)?));
|
||||
maps.push((file.clone(), encode(image, "png", if srgb { Depth::U8 } else { Depth::U16 }, srgb)?));
|
||||
entries.push(MapEntry { usage: usage.into(), file, color_space: if srgb { "srgb" } else { "linear" }.into() });
|
||||
size = [img.w, img.h];
|
||||
size = [image.width(), image.height()];
|
||||
}
|
||||
if entries.is_empty() {
|
||||
return Err(bad(
|
||||
"file.exportMaterial",
|
||||
format!(
|
||||
"graph `{}` has no outputs with a material usage ({})",
|
||||
g.name,
|
||||
graph.name,
|
||||
ComponentUsage::ALL.iter().filter(|usage| **usage != ComponentUsage::ANY).map(|usage| usage.id).collect::<Vec<_>>().join(", ")
|
||||
),
|
||||
));
|
||||
}
|
||||
|
||||
let manifest = Manifest {
|
||||
format: FORMAT.into(),
|
||||
version: VERSION,
|
||||
name: g.name.replace('_', " "),
|
||||
graph: g.name.clone(),
|
||||
name: graph.name.replace('_', " "),
|
||||
graph: graph.name.clone(),
|
||||
size,
|
||||
maps: entries,
|
||||
parameters: g
|
||||
parameters: graph
|
||||
.exposed
|
||||
.iter()
|
||||
.filter(|e| portable(&e.default))
|
||||
.map(|e| Parameter { param: e.clone(), value: g.input_value(&e.id).cloned().unwrap_or_else(|| e.default.clone()) })
|
||||
.map(|e| Parameter { param: e.clone(), value: graph.input_value(&e.id).cloned().unwrap_or_else(|| e.default.clone()) })
|
||||
.collect(),
|
||||
inputs: image_inputs(g),
|
||||
presets: g.presets.iter().map(|p| PresetEntry { name: p.name.clone(), values: p.values.clone() }).collect(),
|
||||
inputs: image_inputs(graph),
|
||||
presets: graph.presets.iter().map(|p| PresetEntry { name: p.name.clone(), values: p.values.clone() }).collect(),
|
||||
source: String::new(),
|
||||
};
|
||||
|
||||
let source = materialcraft_formats::sbs::write_sbs(&pkg)?;
|
||||
let source = materialcraft_formats::sbs::write_sbs(&package)?;
|
||||
Ok(materialcraft_formats::material::write_material(&manifest, &maps, &source)?)
|
||||
}
|
||||
|
||||
@@ -289,17 +291,24 @@ mod tests {
|
||||
fn binds_preview_images_to_input_nodes() {
|
||||
let mut s = crate::sample_session();
|
||||
crate::execute(&mut s, "graph.node.add", &json!({"def": "input_grayscale", "params": {"identifier": "curvature"}})).unwrap();
|
||||
let png = encode(&Image::filled(4, 4, materialcraft_image::Kind::Gray, [0.7; 4]), "png", Depth::U16, false).unwrap();
|
||||
let png = encode(&Image::filled(4, 4, craft_texture::Kind::Gray, [0.7; 4]), "png", Depth::U16, false).unwrap();
|
||||
let res = crate::file_cmds::add_resource(&mut s, "curv.png", png, None).unwrap();
|
||||
|
||||
assert!(crate::execute(&mut s, "graph.input.bind", &json!({"identifier": "nope", "resource": res})).is_err());
|
||||
|
||||
crate::execute(&mut s, "graph.input.bind", &json!({"identifier": "curvature", "resource": res, "linear": true})).unwrap();
|
||||
|
||||
assert_eq!(s.graph().unwrap().input_images.get("curvature"), Some(&res));
|
||||
|
||||
let bytes = materialcraft_formats::sbs::write_sbs(&s.pkg).unwrap();
|
||||
let reopened = materialcraft_formats::sbs::read_sbs(&bytes, "input.sbs", &|_| None).unwrap().pkg;
|
||||
|
||||
assert_eq!(reopened.graphs[s.graph].input_images.get("curvature"), Some(&res));
|
||||
assert!(reopened.graphs[s.graph].input_images_linear.contains("curvature"));
|
||||
|
||||
let bytes = material_bytes(&s, s.graph, &MaterialOptions { size: Some(16), ..Default::default() }).unwrap();
|
||||
let (m, _) = read_material(&bytes).unwrap();
|
||||
|
||||
assert!(m.inputs.iter().any(|i| i.identifier == "curvature" && i.kind == "gray"));
|
||||
assert_eq!(crate::execute(&mut s, "graph.input.unbind", &json!({"identifier": "curvature"})).unwrap(), J::Bool(true));
|
||||
assert!(s.graph().unwrap().input_images.is_empty());
|
||||
@@ -329,7 +338,7 @@ mod tests {
|
||||
.unwrap();
|
||||
crate::execute(&mut s, "graph.connect", &json!({"from": input, "to": output})).unwrap();
|
||||
|
||||
let png = encode(&Image::filled(16, 16, materialcraft_image::Kind::Color, [128.0 / 255.0; 4]), "png", Depth::U16, false).unwrap();
|
||||
let png = encode(&Image::filled(16, 16, craft_texture::Kind::Color, [128.0 / 255.0; 4]), "png", Depth::U16, false).unwrap();
|
||||
let dir = std::env::temp_dir().join(format!("materialcraft-linear-input-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let file = dir.join("normal.png");
|
||||
@@ -338,23 +347,26 @@ mod tests {
|
||||
let output_path = dir.join("out.mcmat").to_str().unwrap().to_string();
|
||||
|
||||
let result = crate::execute(&mut s, "file.exportMaterial", &json!({"path": output_path, "size": 16, "inputs": {"normal": input_path}}));
|
||||
|
||||
assert!(result.is_ok());
|
||||
|
||||
let bytes = std::fs::read(&output_path).unwrap();
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
|
||||
// The material archive stores maps uncompressed; pull the normal map
|
||||
// out of its local file header and decode it as linear data.
|
||||
// The uncompressed archive exposes the normal map after its local file header
|
||||
let name = b"maps/normal.png";
|
||||
let pos = bytes.windows(name.len()).position(|w| w == name).unwrap();
|
||||
let header = pos - 30;
|
||||
|
||||
assert_eq!(&bytes[header..header + 4], b"PK\x03\x04");
|
||||
|
||||
let name_len = u16::from_le_bytes([bytes[header + 26], bytes[header + 27]]) as usize;
|
||||
let extra_len = u16::from_le_bytes([bytes[header + 28], bytes[header + 29]]) as usize;
|
||||
let compressed = u32::from_le_bytes([bytes[header + 18], bytes[header + 19], bytes[header + 20], bytes[header + 21]]) as usize;
|
||||
let start = header + 30 + name_len + extra_len;
|
||||
let map = &bytes[start..start + compressed];
|
||||
let decoded = decode(map, true).unwrap();
|
||||
|
||||
assert!((decoded.get(0, 0, false)[0] - 128.0 / 255.0).abs() < 1e-3, "data inputs must be decoded as linear");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
use craft_texture::Image;
|
||||
use materialcraft_core::Value;
|
||||
use materialcraft_image::Image;
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
/// What to cook a portable material with, over the graph's own values
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
use std::collections::{BTreeMap, BTreeSet};
|
||||
use std::hash::{Hash, Hasher};
|
||||
|
||||
use craft_texture::Image;
|
||||
use materialcraft_core::{MaterialChannel, Package};
|
||||
use materialcraft_image::Image;
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use crate::{MaterialSource, Session};
|
||||
|
||||
@@ -345,7 +345,7 @@ fn library_graphs_cook_previews_from_sample_inputs() {
|
||||
|
||||
let filter = preview("sbs://blur_hq.sbs", "blur_hq").unwrap();
|
||||
|
||||
assert_eq!((filter.w, filter.h), (32, 32));
|
||||
assert_eq!((filter.width(), filter.height()), (32, 32));
|
||||
assert!(preview("sbs://materials/pbr/bricks_001.sbs", "bricks_001").is_some());
|
||||
assert!(preview("sbs://noise_bnw_spots_1.sbs", "bnw_spots_1").is_some(), "an FX-Map noise reads the variables its size function sets");
|
||||
assert!(preview("sbs://blur_hq.sbs", "no_such_graph").is_none());
|
||||
@@ -362,7 +362,7 @@ fn repeated_library_previews_release_images_and_source_references() {
|
||||
[("sbs://blur_hq.sbs", "blur_hq"), ("sbs://noise_clouds_3_v2.sbs", "clouds_3"), ("sbs://materials/pbr/bricks_001.sbs", "bricks_001")]
|
||||
{
|
||||
let image = NodeLibrary::preview(&library, package, graph, 72).unwrap_or_else(|| panic!("missing preview {package}#{graph}"));
|
||||
let buffer = Arc::downgrade(&image.data);
|
||||
let buffer = Arc::downgrade(image.shared_data());
|
||||
drop(image);
|
||||
|
||||
assert!(buffer.upgrade().is_none(), "a completed thumbnail must release its image after upload");
|
||||
|
||||
@@ -3,9 +3,9 @@
|
||||
|
||||
use std::sync::{Arc, Mutex, PoisonError};
|
||||
|
||||
use craft_texture::Image;
|
||||
use materialcraft_core::{Graph, NodeId, Package, ResourceBytes};
|
||||
use materialcraft_eval::{Cache, Cooked, Options};
|
||||
use materialcraft_image::Image;
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use crate::snapshot::Snapshot;
|
||||
@@ -426,29 +426,29 @@ impl Session {
|
||||
|
||||
/// A decoder for the package's bitmap resources (memoized, shareable with worker threads).
|
||||
pub fn resource_decoder(&self) -> impl Fn(&str) -> Option<Image> + Sync + Send + 'static {
|
||||
let mut res: Vec<(String, ResourceBytes)> = self.pkg.resources.iter().map(|r| (r.name.clone(), r.bytes.clone())).collect();
|
||||
res.extend(
|
||||
let mut resources: Vec<(String, ResourceBytes)> = self.pkg.resources.iter().map(|r| (r.name.clone(), r.bytes.clone())).collect();
|
||||
resources.extend(
|
||||
self.pkg
|
||||
.dependencies
|
||||
.iter()
|
||||
.flat_map(|(file, package)| package.resources.iter().map(move |resource| (format!("{file}\0{}", resource.name), resource.bytes.clone()))),
|
||||
);
|
||||
let memo = self.decoded.clone();
|
||||
let decoded = self.decoded.clone();
|
||||
|
||||
// Release decoded images of deleted or replaced resources
|
||||
let hashes = res.iter().map(|(_, bytes)| bytes.content_hash()).collect();
|
||||
memo.lock().unwrap_or_else(PoisonError::into_inner).retain_resources(&hashes);
|
||||
let hashes = resources.iter().map(|(_, bytes)| bytes.content_hash()).collect();
|
||||
decoded.lock().unwrap_or_else(PoisonError::into_inner).retain_resources(&hashes);
|
||||
move |requested: &str| {
|
||||
let (name, linear) = materialcraft_image::split_resource_key(requested);
|
||||
let (_, bytes) = res.iter().find(|(n, _)| n == name)?;
|
||||
let (name, linear) = craft_texture::split_resource_key(requested);
|
||||
let (_, bytes) = resources.iter().find(|(name_candidate, _)| name_candidate == name)?;
|
||||
let key = (bytes.content_hash(), linear);
|
||||
if let Some(i) = memo.lock().unwrap_or_else(PoisonError::into_inner).get(&key) {
|
||||
return Some(i);
|
||||
if let Some(image) = decoded.lock().unwrap_or_else(PoisonError::into_inner).get(&key) {
|
||||
return Some(image);
|
||||
}
|
||||
|
||||
let img = materialcraft_formats::decode(bytes.as_slice(), linear).ok()?;
|
||||
memo.lock().unwrap_or_else(PoisonError::into_inner).insert(key, img.clone());
|
||||
Some(img)
|
||||
let image = materialcraft_formats::decode(bytes.as_slice(), linear).ok()?;
|
||||
decoded.lock().unwrap_or_else(PoisonError::into_inner).insert(key, image.clone());
|
||||
Some(image)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
use craft_texture::{Image, Kind, resource_key};
|
||||
use materialcraft_core::{Package, Resource};
|
||||
use materialcraft_formats::{Depth, encode};
|
||||
use materialcraft_image::{Image, Kind, resource_key};
|
||||
|
||||
use crate::session::Session;
|
||||
|
||||
@@ -187,13 +187,16 @@ fn a_failed_group_recooks_if_it_cooked_a_temporary_document() {
|
||||
s.preview_size = Some(16);
|
||||
let id = NodeId(execute(&mut s, "graph.node.add", &json!({"def": "uniform"})).unwrap()["id"].as_u64().unwrap());
|
||||
execute(&mut s, "graph.node.param", &json!({"id": id.0, "param": "color_mode", "value": true})).unwrap();
|
||||
let before = s.cook().image(id, 0).unwrap().data.clone();
|
||||
let before = s.cook().image(id, 0).unwrap().data().to_vec();
|
||||
let result: crate::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();
|
||||
Err(crate::EngineError::Other("failed".into()))
|
||||
});
|
||||
|
||||
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());
|
||||
}
|
||||
@@ -59,19 +59,28 @@ fn atomic_sample_round_trips_through_native_fields_and_cooks_identically() {
|
||||
assert!(!text.contains(forbidden));
|
||||
}
|
||||
let read = read_sbs(&bytes, "atomic_sample.sbs", &|_| None).unwrap();
|
||||
|
||||
assert!(read.warnings.is_empty(), "{:?}", read.warnings);
|
||||
|
||||
let mut loaded = Session::new(read.pkg);
|
||||
loaded.preview_size = Some(64);
|
||||
loaded.cook();
|
||||
|
||||
assert_eq!(original.graph().unwrap().connections.len(), loaded.graph().unwrap().connections.len());
|
||||
|
||||
for (before, after) in original.graph().unwrap().nodes.iter().zip(&loaded.graph().unwrap().nodes) {
|
||||
assert_eq!(before.def, after.def);
|
||||
|
||||
let result = &loaded.cooked.nodes[&after.id];
|
||||
|
||||
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)),
|
||||
@@ -181,11 +190,11 @@ 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]
|
||||
|
||||
@@ -101,10 +101,13 @@ fn unique_export_writes_both_maps_with_their_expected_pixels() {
|
||||
let (mut s, _) = session();
|
||||
let dir = TempDir::new("unique");
|
||||
let result = execute(&mut s, "file.export", &json!({"dir": dir.0, "pattern": "$(identifier)"})).unwrap();
|
||||
|
||||
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}");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -45,8 +45,8 @@ fn bundled_voronoi_bitmaps_load_the_shared_resource_and_survive_portable_saving(
|
||||
assert!(cooked.nodes[&node.id].error.is_none());
|
||||
|
||||
let image = cooked.image(node.id, 0).unwrap();
|
||||
let low = image.data.iter().copied().fold(f32::INFINITY, f32::min);
|
||||
let high = image.data.iter().copied().fold(f32::NEG_INFINITY, f32::max);
|
||||
let low = image.data().iter().copied().fold(f32::INFINITY, f32::min);
|
||||
let high = image.data().iter().copied().fold(f32::NEG_INFINITY, f32::max);
|
||||
|
||||
assert!(low.is_finite() && high.is_finite() && high > low);
|
||||
}
|
||||
|
||||
@@ -23,8 +23,8 @@ fn bundled_cloud_and_white_noise_parameter_scopes_cook() {
|
||||
|
||||
for node in nodes.iter().filter(|node| matches!(node.def.as_str(), "output" | "fx_map")) {
|
||||
let image = cooked.image(node.id, 0).unwrap();
|
||||
let low = image.data.iter().copied().fold(f32::INFINITY, f32::min);
|
||||
let high = image.data.iter().copied().fold(f32::NEG_INFINITY, f32::max);
|
||||
let low = image.data().iter().copied().fold(f32::INFINITY, f32::min);
|
||||
let high = image.data().iter().copied().fold(f32::NEG_INFINITY, f32::max);
|
||||
|
||||
assert!(high - low > 0.05, "{file} lost variation: {low}..{high}");
|
||||
}
|
||||
@@ -51,14 +51,14 @@ fn bundled_brick_material_cooks_without_missing_functions_or_budget_errors() {
|
||||
for output in outputs {
|
||||
let image = cooked.image(output, 0).unwrap();
|
||||
|
||||
assert!(image.data.iter().all(|value| value.is_finite()));
|
||||
assert!(image.data().iter().all(|value| value.is_finite()));
|
||||
}
|
||||
|
||||
// Finite output alone missed flat noise, identical tile values and a half-turn hue error
|
||||
for id in [24, 34, 48, 91] {
|
||||
let image = cooked.image(materialcraft_engine::core::NodeId(id), 0).unwrap();
|
||||
let low = image.data.iter().copied().fold(f32::INFINITY, f32::min);
|
||||
let high = image.data.iter().copied().fold(f32::NEG_INFINITY, f32::max);
|
||||
let low = image.data().iter().copied().fold(f32::INFINITY, f32::min);
|
||||
let high = image.data().iter().copied().fold(f32::NEG_INFINITY, f32::max);
|
||||
|
||||
assert!(high - low > 0.05, "node {id} lost its variation: {low}..{high}");
|
||||
|
||||
|
||||
@@ -25,18 +25,22 @@ 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();
|
||||
let loaded = formats::sbs::read_sbs(&bytes, "parameter-functions.sbs", &|_| None).unwrap();
|
||||
|
||||
assert!(loaded.warnings.is_empty(), "{:?}", loaded.warnings);
|
||||
|
||||
let mut reopened = Session::new(loaded.pkg);
|
||||
reopened.preview_size = None;
|
||||
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 +94,8 @@ 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 +125,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,
|
||||
@@ -267,7 +272,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();
|
||||
@@ -394,7 +399,8 @@ 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]);
|
||||
}
|
||||
|
||||
@@ -85,7 +85,7 @@ fn dynamic_roughness_survives_native_saving_and_invalidates_the_cook_cache() {
|
||||
let cached = materialcraft_engine::eval::cook(&package, 0, &options, &cache);
|
||||
|
||||
assert!(cached.nodes[&owner].cached);
|
||||
assert_eq!(cached.image(owner, 0).unwrap().data, result.image(owner, 0).unwrap().data);
|
||||
assert_eq!(cached.image(owner, 0).unwrap().data(), result.image(owner, 0).unwrap().data());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -23,23 +23,31 @@ fn grouping_noise_preserves_pixels_seed_and_undo() {
|
||||
let before_graphs = s.pkg.graphs.clone();
|
||||
let before = s.cook().image(output, 0).unwrap().clone();
|
||||
run(&mut s, "graph.createFromSelection", json!({"name": "Grouped_noise"}));
|
||||
// Force an actual cook instead of relying on the pre-grouping cache entry.
|
||||
|
||||
// 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());
|
||||
}
|
||||
}
|
||||
@@ -79,15 +79,21 @@ fn package_save_and_open_round_trip() {
|
||||
let before = s.pkg.clone();
|
||||
run(&mut s, "file.newPackage", json!({}));
|
||||
run(&mut s, "file.open", json!({"path": path.to_str().unwrap()}));
|
||||
|
||||
assert_eq!(s.pkg.graphs[0].nodes.len(), before.graphs[0].nodes.len());
|
||||
|
||||
let out = dir.join("tex");
|
||||
let r = run(&mut s, "file.export", json!({"dir": out.to_str().unwrap(), "format": "png", "depth": 8}));
|
||||
|
||||
assert_eq!(r["files"].as_array().unwrap().len(), 1);
|
||||
|
||||
let small = dir.join("small");
|
||||
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 +107,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::<Vec<_>>()
|
||||
files.iter().map(|f| materialcraft_formats::decode(&f.bytes, false).unwrap()).map(|i| (i.width(), i.height())).collect::<Vec<_>>()
|
||||
};
|
||||
let parsed = |s: &Session, size: Value| ExportRequest::from_params(s, &json!({"size": size})).map(|request| request.size);
|
||||
|
||||
@@ -113,11 +119,13 @@ fn export_size_keeps_proportions_and_clamps() {
|
||||
assert_eq!(parsed(&s, json!(0)).unwrap(), None);
|
||||
assert_eq!(parsed(&s, json!(u64::MAX)).unwrap(), Some(ExportSize::LargerSide(u32::MAX)));
|
||||
assert_eq!(parsed(&s, json!([1, u64::MAX])).unwrap(), Some(ExportSize::Exact([1, u32::MAX])));
|
||||
|
||||
for invalid in [json!("large"), json!([64]), json!([64, "wide"]), json!([64, 64, 64])] {
|
||||
assert!(parsed(&s, invalid.clone()).is_err(), "{invalid}");
|
||||
}
|
||||
|
||||
s.pkg.graphs[0].size = [u32::MAX, u32::MAX];
|
||||
|
||||
assert!(dims(&s, json!(32)).iter().all(|d| *d == (32, 32)));
|
||||
assert!(dims(&s, json!([1, u64::MAX])).iter().all(|d| *d == (16, 8192)), "sides clamp to 16..8192");
|
||||
}
|
||||
@@ -376,17 +384,20 @@ 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}");
|
||||
}
|
||||
|
||||
@@ -422,7 +433,7 @@ fn a_wire_splits_with_a_reroute_dot_and_deletes() {
|
||||
|
||||
#[test]
|
||||
fn every_template_is_opaque_in_the_3d_view() {
|
||||
// The 3D view sees through a base color whose alpha is below one: the templates must not
|
||||
// Template base colors must stay opaque in the 3D view
|
||||
let mut s = sample_session();
|
||||
s.preview_size = Some(64);
|
||||
for (id, _) in materialcraft_engine::samples::TEMPLATES {
|
||||
@@ -430,7 +441,8 @@ 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}");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -10,7 +10,7 @@ workspace = true
|
||||
|
||||
[dependencies]
|
||||
materialcraft-core = { workspace = true }
|
||||
materialcraft-image = { workspace = true }
|
||||
craft-texture = { workspace = true }
|
||||
materialcraft-nodes = { workspace = true }
|
||||
half = { workspace = true }
|
||||
serde_json = { workspace = true }
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
use super::*;
|
||||
use materialcraft_image::{Image, Kind};
|
||||
use craft_texture::{Image, Kind};
|
||||
|
||||
fn output(side: u32) -> Arc<Vec<NodeOutput>> {
|
||||
Arc::new(vec![NodeOutput::Image(Image::filled(side, side, Kind::Gray, [0.5; 4]))])
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
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};
|
||||
@@ -8,21 +8,21 @@ use std::sync::{Arc, Mutex};
|
||||
const MAX_INPUT_FINGERPRINTS: usize = 128;
|
||||
|
||||
pub(crate) fn image_key(image: &Image, cache: &Mutex<Cache>) -> u64 {
|
||||
let buffer_id = Arc::as_ptr(&image.data) as usize;
|
||||
let shape = (image.w, image.h, image.kind.channels());
|
||||
let buffer_id = Arc::as_ptr(image.shared_data()) as usize;
|
||||
let shape = (image.width(), image.height(), image.channels());
|
||||
if let Some(key) = cache
|
||||
.lock()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner)
|
||||
.input_hashes
|
||||
.get(&buffer_id)
|
||||
.and_then(|saved| saved.buffer.upgrade().filter(|data| Arc::ptr_eq(data, &image.data) && saved.shape == shape).map(|_| saved.key))
|
||||
.and_then(|saved| saved.buffer.upgrade().filter(|data| Arc::ptr_eq(data, image.shared_data()) && saved.shape == shape).map(|_| saved.key))
|
||||
{
|
||||
return key ^ hash_of(&image.integer_sampling);
|
||||
return key ^ hash_of(&image.integer_sampling());
|
||||
}
|
||||
|
||||
let mut hasher = DefaultHasher::new();
|
||||
(shape, image.data.len()).hash(&mut hasher);
|
||||
for value in image.data.iter() {
|
||||
(shape, image.data().len()).hash(&mut hasher);
|
||||
for value in image.data() {
|
||||
value.to_bits().hash(&mut hasher);
|
||||
}
|
||||
|
||||
@@ -35,8 +35,8 @@ pub(crate) fn image_key(image: &Image, cache: &Mutex<Cache>) -> u64 {
|
||||
}
|
||||
}
|
||||
|
||||
cache.input_hashes.insert(buffer_id, crate::input_fingerprint::InputFingerprint { buffer: Arc::downgrade(&image.data), shape, key });
|
||||
key ^ hash_of(&image.integer_sampling)
|
||||
cache.input_hashes.insert(buffer_id, crate::input_fingerprint::InputFingerprint { buffer: Arc::downgrade(image.shared_data()), shape, key });
|
||||
key ^ hash_of(&image.integer_sampling())
|
||||
}
|
||||
|
||||
pub(crate) fn hash_of(value: &impl Hash) -> u64 {
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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())));
|
||||
@@ -47,6 +47,7 @@ pub fn cook(package: &Package, graph_index: usize, options: &Options, cache: &Mu
|
||||
cooked.cancelled = true;
|
||||
break;
|
||||
}
|
||||
|
||||
let Some(node) = prepared.index.node(id) else { continue };
|
||||
|
||||
let result = cook_node(package, graph_index, &prepared, node, &cooked, &variables, options, cache);
|
||||
|
||||
@@ -37,71 +37,76 @@ pub(crate) fn instances_reach(pkg: &Package, from: usize, target: usize) -> bool
|
||||
}
|
||||
|
||||
pub(crate) fn cook_instance(
|
||||
pkg: &Package,
|
||||
gi: usize,
|
||||
package: &Package,
|
||||
graph_index: usize,
|
||||
node: &Node,
|
||||
in_ports: &[Port],
|
||||
out_ports: &[Port],
|
||||
input_ports: &[Port],
|
||||
output_ports: &[Port],
|
||||
inputs: &[Option<&NodeOutput>],
|
||||
params: &BTreeMap<String, Value>,
|
||||
size: (u32, u32),
|
||||
base: crate::resolved_base_parameters::ResolvedBaseParameters,
|
||||
opts: &Options,
|
||||
options: &Options,
|
||||
cache: &Mutex<Cache>,
|
||||
) -> Result<Vec<NodeOutput>, String> {
|
||||
if opts.depth >= MAX_DEPTH {
|
||||
if options.depth >= MAX_DEPTH {
|
||||
return Err("graph instances nest too deep (does a graph use itself?)".into());
|
||||
}
|
||||
let registry = opts.registry.unwrap_or(pkg);
|
||||
let (source, sub_gi, sub) = resolve(registry, pkg, node).ok_or("the instanced graph does not exist")?;
|
||||
let identity = std::ptr::from_ref(sub) as usize;
|
||||
if pkg.graphs.get(gi).is_some_and(|graph| std::ptr::eq(graph, sub)) || opts.graph_stack.contains(&identity) {
|
||||
return Err(format!("graph `{}` uses itself through a graph instance", sub.name));
|
||||
|
||||
let registry = options.registry.unwrap_or(package);
|
||||
let (source, source_graph_index, source_graph) = resolve(registry, package, node).ok_or("the instanced graph does not exist")?;
|
||||
let identity = std::ptr::from_ref(source_graph) as usize;
|
||||
if package.graphs.get(graph_index).is_some_and(|graph| std::ptr::eq(graph, source_graph)) || options.graph_stack.contains(&identity) {
|
||||
return Err(format!("graph `{}` uses itself through a graph instance", source_graph.name));
|
||||
}
|
||||
if sub.function.is_some() || !sub.nodes.iter().any(|node| node.def == "output") {
|
||||
|
||||
if source_graph.function.is_some() || !source_graph.nodes.iter().any(|node| node.def == "output") {
|
||||
return Err("the referenced graph must be a main graph with an output".into());
|
||||
}
|
||||
let root_resource = opts.resource_root.unwrap_or(opts.resource);
|
||||
|
||||
let root_resource = options.resource_root.unwrap_or(options.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),
|
||||
_ => (options.resource)(name),
|
||||
};
|
||||
let mut o = Options::new(&resource);
|
||||
o.environment = opts.environment;
|
||||
o.parent_tiling = Some(base.tiling);
|
||||
o.parent_pixel_ratio = Some(base.pixel_ratio);
|
||||
o.parent_base = Some(base);
|
||||
o.registry = Some(registry);
|
||||
o.resource_root = Some(root_resource);
|
||||
o.max_size = opts.max_size;
|
||||
o.cancel = opts.cancel;
|
||||
o.depth = opts.depth + 1;
|
||||
o.graph_stack = opts.graph_stack.clone();
|
||||
o.graph_stack.push(identity);
|
||||
o.only = Some(sub.nodes.iter().filter(|node| node.def == "output").map(|node| node.id).collect());
|
||||
o.inputs = in_ports.iter().zip(inputs).filter_map(|(port, input)| Some((port.id.clone(), input.as_ref()?.as_image()?.clone()))).collect();
|
||||
o.overrides = params.iter().filter(|(k, _)| sub.exposed.iter().any(|e| &e.id == *k)).map(|(k, v)| (k.clone(), v.clone())).collect();
|
||||
o.overrides.extend(in_ports.iter().zip(inputs).filter_map(|(port, input)| Some((port.id.clone(), input.as_ref()?.as_value()?.clone()))));
|
||||
let cooked = cook(source, sub_gi, &o, cache);
|
||||
let mut source_options = Options::new(&resource);
|
||||
source_options.environment = options.environment;
|
||||
source_options.parent_tiling = Some(base.tiling);
|
||||
source_options.parent_pixel_ratio = Some(base.pixel_ratio);
|
||||
source_options.parent_base = Some(base);
|
||||
source_options.registry = Some(registry);
|
||||
source_options.resource_root = Some(root_resource);
|
||||
source_options.max_size = options.max_size;
|
||||
source_options.cancel = options.cancel;
|
||||
source_options.depth = options.depth + 1;
|
||||
source_options.graph_stack = options.graph_stack.clone();
|
||||
source_options.graph_stack.push(identity);
|
||||
source_options.only = Some(source_graph.nodes.iter().filter(|node| node.def == "output").map(|node| node.id).collect());
|
||||
source_options.inputs = input_ports.iter().zip(inputs).filter_map(|(port, input)| Some((port.id.clone(), input.as_ref()?.as_image()?.clone()))).collect();
|
||||
source_options.overrides = params.iter().filter(|(k, _)| source_graph.exposed.iter().any(|e| &e.id == *k)).map(|(k, v)| (k.clone(), v.clone())).collect();
|
||||
source_options.overrides.extend(input_ports.iter().zip(inputs).filter_map(|(port, input)| Some((port.id.clone(), input.as_ref()?.as_value()?.clone()))));
|
||||
let cooked = cook(source, source_graph_index, &source_options, cache);
|
||||
if cooked.cancelled {
|
||||
return Err("cancelled".into());
|
||||
}
|
||||
|
||||
if let Some(error) = cooked.nodes.values().find_map(|result| result.error.as_deref()) {
|
||||
return Err(format!("{}: {error}", sub.name));
|
||||
return Err(format!("{}: {error}", source_graph.name));
|
||||
}
|
||||
out_ports
|
||||
|
||||
output_ports
|
||||
.iter()
|
||||
.map(|p| {
|
||||
let output = sub
|
||||
.map(|port| {
|
||||
let output = source_graph
|
||||
.nodes
|
||||
.iter()
|
||||
.find(|n| n.def == "output" && identifier(n) == p.id)
|
||||
.find(|candidate| candidate.def == "output" && identifier(candidate) == port.id)
|
||||
.and_then(|node| cooked.nodes.get(&node.id))
|
||||
.and_then(|result| result.outputs.first())
|
||||
.ok_or_else(|| format!("the source output `{}` is missing", p.id))?;
|
||||
.ok_or_else(|| format!("the source output `{}` is missing", port.id))?;
|
||||
Ok(match output {
|
||||
NodeOutput::Image(image) => NodeOutput::Image(image.resize(size.0, size.1, true)),
|
||||
NodeOutput::Value(value) => NodeOutput::Value(value.clone()),
|
||||
|
||||
@@ -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>)> {
|
||||
|
||||
@@ -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,
|
||||
@@ -177,7 +177,7 @@ pub(crate) fn cook_node(
|
||||
} else if matches!(node.def.as_str(), "output" | "dot") && incoming.first().and_then(Option::as_ref).is_some_and(|output| output.as_value().is_some()) {
|
||||
incoming.first().copied().flatten().cloned().map(|output| vec![output]).ok_or("missing value input".into())
|
||||
} else if let Some(image) = input_image {
|
||||
let mut image = if node.def == "input_grayscale" && image.kind == Kind::Color {
|
||||
let mut image = if node.def == "input_grayscale" && image.kind() == Kind::Color {
|
||||
// Grayscale bridges use equal RGB weights and preserve fused float order
|
||||
let weight = 1.0 / 3.0;
|
||||
image.map(Kind::Gray, |pixel| [pixel[2].mul_add(weight, pixel[1].mul_add(weight, pixel[0] * weight)), 0.0, 0.0, 0.0])
|
||||
@@ -189,12 +189,12 @@ pub(crate) fn cook_node(
|
||||
|
||||
// Bound resources clamp edges through stored factor-two levels
|
||||
// Preserve resampling and storage conversion for HDR bridges
|
||||
let resized = image.w != w || image.h != h;
|
||||
while image.w != w || image.h != h {
|
||||
let resized = image.width() != w || image.height() != h;
|
||||
while image.width() != w || image.height() != h {
|
||||
let next = |current: u32, target: u32| {
|
||||
if current < target { current.saturating_mul(2).min(target) } else { current.div_ceil(2).max(target) }
|
||||
};
|
||||
image = crate::output_precision::apply(image.resize(next(image.w, w), next(image.h, h), false), base.format);
|
||||
image = crate::output_precision::apply(image.resize(next(image.width(), w), next(image.height(), h), false), base.format);
|
||||
}
|
||||
|
||||
// Resized inputs already store the final level at the declared precision
|
||||
|
||||
@@ -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::<f32>()),
|
||||
Self::Image(image) => image.data().len().saturating_mul(size_of::<f32>()),
|
||||
Self::Value(Value::Text(text)) => size_of::<Value>().saturating_add(text.len()),
|
||||
Self::Value(_) => size_of::<Value>(),
|
||||
}
|
||||
|
||||
@@ -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;
|
||||
|
||||
|
||||
@@ -1,43 +1,61 @@
|
||||
use craft_texture::{Image, Limits};
|
||||
use materialcraft_core::OutputFormat;
|
||||
use materialcraft_image::Image;
|
||||
use std::sync::Arc;
|
||||
|
||||
pub(crate) fn apply(mut image: Image, format: OutputFormat) -> Image {
|
||||
pub(crate) fn apply(image: Image, format: OutputFormat) -> Image {
|
||||
const HALF_FLOAT_MAX: f32 = 65504.0;
|
||||
const U8_FIXED_SCALE: f64 = 4096.0;
|
||||
const U16_FIXED_SCALE: f64 = 1_048_576.0;
|
||||
|
||||
image.integer_sampling = integer_sampling(format);
|
||||
let integer = integer_sampling(format);
|
||||
if format == OutputFormat::F16 {
|
||||
for pixel in Arc::make_mut(&mut image.data) {
|
||||
return with_pixels(image, integer, |pixel| {
|
||||
// Half-float storage saturates finite overflow and truncates toward zero
|
||||
// Leaving the f32 unconverted changes every downstream read and export
|
||||
let value = pixel.clamp(-HALF_FLOAT_MAX, HALF_FLOAT_MAX);
|
||||
let rounded = half::f16::from_f32(value);
|
||||
*pixel = if rounded.to_f32().abs() > value.abs() { half::f16::from_bits(rounded.to_bits().saturating_sub(1)).to_f32() } else { rounded.to_f32() };
|
||||
}
|
||||
|
||||
return image;
|
||||
});
|
||||
}
|
||||
|
||||
let (fraction, maximum) = match format {
|
||||
OutputFormat::U8 => (U8_FIXED_SCALE, f64::from(u8::MAX)),
|
||||
OutputFormat::Inherit | OutputFormat::U16 => (U16_FIXED_SCALE, f64::from(u16::MAX)),
|
||||
OutputFormat::F16 | OutputFormat::F32 => return image,
|
||||
OutputFormat::F16 | OutputFormat::F32 => return image.with_integer_sampling(integer),
|
||||
};
|
||||
|
||||
for pixel in Arc::make_mut(&mut image.data) {
|
||||
with_pixels(image, integer, |pixel| {
|
||||
// Integer outputs retain four fractional guard bits before conversion
|
||||
// Halfway-down rounding affects constants and downstream blends
|
||||
let value = if pixel.is_nan() { 0.0 } else { f64::from(*pixel).clamp(0.0, 1.0) };
|
||||
let fixed = (value * fraction).floor() / fraction;
|
||||
let integer = (fixed * maximum - 0.5).ceil() as u32;
|
||||
*pixel = integer as f32 / maximum as f32;
|
||||
}
|
||||
|
||||
image
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) fn integer_sampling(format: OutputFormat) -> bool {
|
||||
matches!(format, OutputFormat::Inherit | OutputFormat::U8 | OutputFormat::U16)
|
||||
}
|
||||
|
||||
/// `image` with `convert` applied to every float and the integer-sampling flag set. The buffer is
|
||||
/// changed in place when no other image shares it, and copied once otherwise.
|
||||
fn with_pixels(image: Image, integer_sampling: bool, convert: impl Fn(&mut f32)) -> Image {
|
||||
let (width, height, kind) = (image.width(), image.height(), image.kind());
|
||||
|
||||
// Limits that admit any valid image, so one made with raised limits keeps its size
|
||||
let mut limits = Limits::default();
|
||||
limits.max_side = u32::MAX;
|
||||
limits.max_pixels = u64::MAX;
|
||||
limits.max_bytes = u64::MAX;
|
||||
|
||||
let mut data = Arc::clone(image.shared_data());
|
||||
drop(image);
|
||||
|
||||
Arc::make_mut(&mut data).iter_mut().for_each(convert);
|
||||
|
||||
// `data` keeps the size and kind of a valid image, so `from_data` accepts it
|
||||
Image::from_data(width, height, kind, data, &limits)
|
||||
.unwrap_or_else(|_| Image::filled(width, height, kind, [0.0; 4]))
|
||||
.with_integer_sampling(integer_sampling)
|
||||
}
|
||||
@@ -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<Image> + Sync + 'a;
|
||||
+56
-27
@@ -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;
|
||||
|
||||
@@ -32,7 +32,7 @@ fn cooks_and_caches() {
|
||||
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);
|
||||
@@ -121,8 +121,9 @@ fn hostile_param_is_clamped_before_cooking() {
|
||||
p.graphs[0].node_mut(blur).unwrap().params.insert("intensity".into(), Value::Float(1e30));
|
||||
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]
|
||||
@@ -134,7 +135,8 @@ 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());
|
||||
}
|
||||
|
||||
@@ -168,7 +170,7 @@ fn graph_instances_cook_their_subgraph() {
|
||||
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);
|
||||
}
|
||||
|
||||
@@ -298,14 +300,14 @@ fn input_nodes_read_bound_preview_images() {
|
||||
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]
|
||||
@@ -377,20 +379,29 @@ 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);
|
||||
|
||||
cache.lock().unwrap().clear();
|
||||
|
||||
assert_eq!(image_key(&image, &cache), reshaped);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn preview_cap_does_not_compound_downscaling() {
|
||||
let (mut p, noise, blur, out) = sample();
|
||||
@@ -400,10 +411,12 @@ 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() {
|
||||
let (mut p, noise, blur, out) = sample();
|
||||
@@ -414,10 +427,12 @@ 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() {
|
||||
let mut g = Graph::new("g");
|
||||
@@ -430,19 +445,24 @@ fn changed_unsampled_input_recooks() {
|
||||
opts.inputs.insert("input".into(), image.clone());
|
||||
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]))
|
||||
};
|
||||
|
||||
@@ -459,7 +479,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");
|
||||
@@ -522,22 +542,31 @@ 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());
|
||||
let opts = Options::new(&res);
|
||||
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}");
|
||||
}
|
||||
|
||||
@@ -620,7 +649,7 @@ fn enabled_generators_use_parent_size_and_seed_with_input_image_properties() {
|
||||
|
||||
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, 0);
|
||||
assert_eq!(result.base.format, OutputFormat::F32);
|
||||
assert_eq!(result.base.tiling, [false, true]);
|
||||
@@ -639,7 +668,7 @@ fn enabled_generators_use_parent_size_and_seed_with_input_image_properties() {
|
||||
|
||||
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)));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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(
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
use craft_texture::Image;
|
||||
use materialcraft_core::{Graph, OutputFormat, Package, ParameterInheritance, Value};
|
||||
use materialcraft_eval::{Cache, Options, cook};
|
||||
use materialcraft_image::Image;
|
||||
use std::sync::Mutex;
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -13,7 +13,7 @@ craft-mime = { workspace = true }
|
||||
craft-xml = { workspace = true }
|
||||
craft-mcmat = { workspace = true }
|
||||
materialcraft-core = { workspace = true }
|
||||
materialcraft-image = { workspace = true }
|
||||
craft-texture = { workspace = true }
|
||||
materialcraft-geom = { workspace = true }
|
||||
materialcraft-nodes = { workspace = true }
|
||||
craft-mesh = { workspace = true }
|
||||
|
||||
@@ -152,11 +152,11 @@ fn library_art_is_decodable_without_reading_source_assets() {
|
||||
let bytes = resources::load(key).unwrap();
|
||||
let image = materialcraft_formats::decode(&bytes, true).unwrap();
|
||||
|
||||
assert!(image.w > 0 && image.h > 0);
|
||||
assert!(image.data.iter().all(|value| value.is_finite()));
|
||||
assert!(image.width() > 0 && image.height() > 0);
|
||||
assert!(image.data().iter().all(|value| value.is_finite()));
|
||||
|
||||
let min = image.data.iter().copied().fold(f32::INFINITY, f32::min);
|
||||
let max = image.data.iter().copied().fold(f32::NEG_INFINITY, f32::max);
|
||||
let min = image.data().iter().copied().fold(f32::INFINITY, f32::min);
|
||||
let max = image.data().iter().copied().fold(f32::NEG_INFINITY, f32::max);
|
||||
|
||||
assert!(max > min, "constant replacement {key}");
|
||||
}
|
||||
|
||||
@@ -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<Image> {
|
||||
let error = |message: String| FormatError::Image(message);
|
||||
@@ -18,5 +18,5 @@ pub(crate) fn decode(bytes: &[u8], linear: bool) -> Result<Image> {
|
||||
}
|
||||
}
|
||||
|
||||
Ok(Image { w: decoded.width, h: decoded.height, kind: Kind::Color, integer_sampling: false, data: std::sync::Arc::new(data) })
|
||||
Image::from_data(decoded.width, decoded.height, Kind::Color, data, &Limits::default()).map_err(|e| error(e.to_string()))
|
||||
}
|
||||
+45
-43
@@ -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<Image> {
|
||||
@@ -9,7 +8,10 @@ pub fn decode(bytes: &[u8], linear: bool) -> Result<Image> {
|
||||
return guard(|| crate::dds_image::decode(bytes, linear), || FormatError::Image("DDS decoder failed".into()));
|
||||
}
|
||||
|
||||
if std::str::from_utf8(bytes.get(..bytes.len().min(4096)).unwrap_or_default()).is_ok_and(|text| text.contains("<svg")) {
|
||||
const SVG_SNIFF_BYTES: usize = 4096;
|
||||
const MAX_DECODE_BYTES: u64 = 1 << 30;
|
||||
|
||||
if std::str::from_utf8(bytes.get(..bytes.len().min(SVG_SNIFF_BYTES)).unwrap_or_default()).is_ok_and(|text| text.contains("<svg")) {
|
||||
return guard(|| crate::svg::decode(bytes), || FormatError::Image("SVG decoder failed".into()));
|
||||
}
|
||||
|
||||
@@ -21,7 +23,7 @@ pub fn decode(bytes: &[u8], linear: bool) -> Result<Image> {
|
||||
let mut limits = image::Limits::default();
|
||||
limits.max_image_width = Some(MAX_SIDE);
|
||||
limits.max_image_height = Some(MAX_SIDE);
|
||||
limits.max_alloc = Some(1 << 30);
|
||||
limits.max_alloc = Some(MAX_DECODE_BYTES);
|
||||
reader.limits(limits);
|
||||
Ok(reader)
|
||||
};
|
||||
@@ -36,16 +38,16 @@ pub fn decode(bytes: &[u8], linear: bool) -> Result<Image> {
|
||||
return Err(FormatError::Image(format!("{w}x{h} is outside 1..={MAX_SIDE} pixels")));
|
||||
}
|
||||
|
||||
let img = guard(|| open()?.decode().map_err(image_error), failed)?;
|
||||
let gray = matches!(img.color(), image::ColorType::L8 | image::ColorType::L16 | image::ColorType::La8 | image::ColorType::La16);
|
||||
let float = matches!(img.color(), image::ColorType::Rgb32F | image::ColorType::Rgba32F);
|
||||
let decoded = guard(|| open()?.decode().map_err(image_error), failed)?;
|
||||
let gray = matches!(decoded.color(), image::ColorType::L8 | image::ColorType::L16 | image::ColorType::La8 | image::ColorType::La16);
|
||||
let float = matches!(decoded.color(), image::ColorType::Rgb32F | image::ColorType::Rgba32F);
|
||||
if gray {
|
||||
let l = img.into_luma16();
|
||||
let data: Vec<f32> = l.pixels().map(|p| p.0[0] as f32 / 65535.0).collect();
|
||||
return Ok(Image { w, h, kind: Kind::Gray, integer_sampling: false, data: Arc::new(data) });
|
||||
let luminance = decoded.into_luma16();
|
||||
let data: Vec<f32> = luminance.pixels().map(|p| p.0[0] as f32 / 65535.0).collect();
|
||||
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();
|
||||
let mut data = decoded.into_rgba32f().into_raw();
|
||||
if !(float || linear) {
|
||||
for px in data.as_chunks_mut::<4>().0 {
|
||||
for c in px.iter_mut().take(3) {
|
||||
@@ -54,27 +56,27 @@ pub fn decode(bytes: &[u8], linear: bool) -> Result<Image> {
|
||||
}
|
||||
}
|
||||
|
||||
Ok(Image { w, h, kind: Kind::Color, integer_sampling: false, 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<Vec<u8>> {
|
||||
/// Encode `image` 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(image: &Image, ext: &str, depth: Depth, srgb: bool) -> Result<Vec<u8>> {
|
||||
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 px = |i: usize| -> [f32; 4] {
|
||||
let encode_channel = |v: f32| if srgb && image.kind() == Kind::Color { linear_to_srgb(v) } else { v };
|
||||
let (w, h) = (image.width(), image.height());
|
||||
let color = image.kind() == Kind::Color;
|
||||
let pixel = |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]);
|
||||
[enc(s[0]), enc(s[1]), enc(s[2]), s[3]]
|
||||
let s = image.data().get(i * 4..i * 4 + 4).unwrap_or(&[0.0, 0.0, 0.0, 1.0]);
|
||||
[encode_channel(s[0]), encode_channel(s[1]), encode_channel(s[2]), s[3]]
|
||||
} else {
|
||||
let v = img.data.get(i).copied().unwrap_or(0.0);
|
||||
let v = image.data().get(i).copied().unwrap_or(0.0);
|
||||
[v, v, v, 1.0]
|
||||
}
|
||||
};
|
||||
|
||||
let n = (w * h) as usize;
|
||||
let fmt = match ext.as_str() {
|
||||
let pixel_count = (w * h) as usize;
|
||||
let format = match ext.as_str() {
|
||||
"png" => image::ImageFormat::Png,
|
||||
"jpg" | "jpeg" => image::ImageFormat::Jpeg,
|
||||
"tga" => image::ImageFormat::Tga,
|
||||
@@ -85,44 +87,44 @@ pub fn encode(img: &Image, ext: &str, depth: Depth, srgb: bool) -> Result<Vec<u8
|
||||
other => return Err(FormatError::Image(format!("unsupported export format `{other}`"))),
|
||||
};
|
||||
|
||||
let float_only = matches!(fmt, image::ImageFormat::OpenExr | image::ImageFormat::Hdr);
|
||||
let sixteen_ok = fmt == image::ImageFormat::Png;
|
||||
let q8 = |v: f32| (v.clamp(0.0, 1.0) * 255.0 + 0.5) as u8;
|
||||
let q16 = |v: f32| (v.clamp(0.0, 1.0) * 65535.0 + 0.5) as u16;
|
||||
let dynimg: image::DynamicImage = if float_only {
|
||||
let data: Vec<f32> = (0..n)
|
||||
let float_only = matches!(format, image::ImageFormat::OpenExr | image::ImageFormat::Hdr);
|
||||
let sixteen_ok = format == image::ImageFormat::Png;
|
||||
let quantize_u8 = |v: f32| (v.clamp(0.0, 1.0) * 255.0 + 0.5) as u8;
|
||||
let quantize_u16 = |v: f32| (v.clamp(0.0, 1.0) * 65535.0 + 0.5) as u16;
|
||||
let dynamic_image: image::DynamicImage = if float_only {
|
||||
let data: Vec<f32> = (0..pixel_count)
|
||||
.flat_map(|i| {
|
||||
let p = px(i);
|
||||
let p = pixel(i);
|
||||
[p[0], p[1], p[2]]
|
||||
})
|
||||
.collect();
|
||||
let buf = image::Rgb32FImage::from_raw(w, h, data).ok_or_else(|| FormatError::Image("bad buffer".into()))?;
|
||||
buf.into()
|
||||
let buffer = image::Rgb32FImage::from_raw(w, h, data).ok_or_else(|| FormatError::Image("bad buffer".into()))?;
|
||||
buffer.into()
|
||||
} else if depth != Depth::U8 && sixteen_ok {
|
||||
if color {
|
||||
let data: Vec<u16> = (0..n).flat_map(|i| px(i).map(q16)).collect();
|
||||
let data: Vec<u16> = (0..pixel_count).flat_map(|i| pixel(i).map(quantize_u16)).collect();
|
||||
image::ImageBuffer::<image::Rgba<u16>, _>::from_raw(w, h, data).ok_or_else(|| FormatError::Image("bad buffer".into()))?.into()
|
||||
} else {
|
||||
let data: Vec<u16> = (0..n).map(|i| q16(px(i)[0])).collect();
|
||||
let data: Vec<u16> = (0..pixel_count).map(|i| quantize_u16(pixel(i)[0])).collect();
|
||||
image::ImageBuffer::<image::Luma<u16>, _>::from_raw(w, h, data).ok_or_else(|| FormatError::Image("bad buffer".into()))?.into()
|
||||
}
|
||||
} else if color && !matches!(fmt, image::ImageFormat::Jpeg) {
|
||||
let data: Vec<u8> = (0..n).flat_map(|i| px(i).map(q8)).collect();
|
||||
} else if color && !matches!(format, image::ImageFormat::Jpeg) {
|
||||
let data: Vec<u8> = (0..pixel_count).flat_map(|i| pixel(i).map(quantize_u8)).collect();
|
||||
image::RgbaImage::from_raw(w, h, data).ok_or_else(|| FormatError::Image("bad buffer".into()))?.into()
|
||||
} else if color {
|
||||
let data: Vec<u8> = (0..n)
|
||||
let data: Vec<u8> = (0..pixel_count)
|
||||
.flat_map(|i| {
|
||||
let p = px(i);
|
||||
[q8(p[0]), q8(p[1]), q8(p[2])]
|
||||
let p = pixel(i);
|
||||
[quantize_u8(p[0]), quantize_u8(p[1]), quantize_u8(p[2])]
|
||||
})
|
||||
.collect();
|
||||
image::RgbImage::from_raw(w, h, data).ok_or_else(|| FormatError::Image("bad buffer".into()))?.into()
|
||||
} else {
|
||||
let data: Vec<u8> = (0..n).map(|i| q8(px(i)[0])).collect();
|
||||
let data: Vec<u8> = (0..pixel_count).map(|i| quantize_u8(pixel(i)[0])).collect();
|
||||
image::GrayImage::from_raw(w, h, data).ok_or_else(|| FormatError::Image("bad buffer".into()))?.into()
|
||||
};
|
||||
|
||||
let mut out = Cursor::new(Vec::new());
|
||||
dynimg.write_to(&mut out, fmt).map_err(|e| FormatError::Image(e.to_string()))?;
|
||||
Ok(out.into_inner())
|
||||
let mut output = Cursor::new(Vec::new());
|
||||
dynamic_image.write_to(&mut output, format).map_err(|e| FormatError::Image(e.to_string()))?;
|
||||
Ok(output.into_inner())
|
||||
}
|
||||
@@ -93,7 +93,7 @@ pub(super) fn write(value: &Value, color_mode: bool, writer: &mut SbsWriter) ->
|
||||
}
|
||||
Value::Gradient(gradient) => {
|
||||
for key in &gradient.keys {
|
||||
let color = if color_mode { Value::Color(key.color) } else { Value::Float(materialcraft_image::luminance(key.color)) };
|
||||
let color = if color_mode { Value::Color(key.color) } else { Value::Float(craft_texture::luminance(key.color)) };
|
||||
cell(vec![("position", Value::Float(key.pos)), ("midpoint", Value::Float(key.midpoint)), ("value", color)]);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -82,7 +82,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
|
||||
|
||||
@@ -6,7 +6,7 @@
|
||||
|
||||
use crate::{FormatError, Result};
|
||||
use craft_svg::tree::{self, ImageResolver, Limits, draw, usvg};
|
||||
use materialcraft_image::{Image, Kind, MAX_SIDE, srgb_to_linear};
|
||||
use craft_texture::{Image, Kind, MAX_SIDE, srgb_to_linear};
|
||||
|
||||
/// Largest SVG file (unpacked when SVGZ).
|
||||
const MAX_BYTES: usize = 16 << 20;
|
||||
@@ -82,7 +82,7 @@ mod tests {
|
||||
|
||||
let left = image.get(0, 0, false);
|
||||
|
||||
assert_eq!((image.w, image.h), (4, 2));
|
||||
assert_eq!((image.width(), image.height()), (4, 2));
|
||||
assert!((left[0] - 1.0).abs() < 1e-3 && left[1].abs() < 1e-3 && (left[3] - 1.0).abs() < 1e-3, "{left:?}");
|
||||
assert_eq!(image.get(3, 1, false)[3], 0.0);
|
||||
}
|
||||
|
||||
@@ -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,11 +11,13 @@ 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));
|
||||
}
|
||||
}
|
||||
}
|
||||
let png16 = encode(&gray, "png", Depth::U16, false).unwrap();
|
||||
|
||||
assert!((decode(&png16, false).unwrap().get(7, 0, false)[0] - gray.get(7, 0, false)[0]).abs() < 1e-3);
|
||||
}
|
||||
|
||||
@@ -39,7 +41,8 @@ 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]
|
||||
|
||||
@@ -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());
|
||||
@@ -81,9 +81,9 @@ fn shared_dds_keeps_rgb_transfer_alpha_and_float_range() {
|
||||
let raw = decode(&bytes, true).unwrap();
|
||||
let converted = decode(&bytes, false).unwrap();
|
||||
for i in 0..3 {
|
||||
assert!((converted.data[i] - materialcraft_image::srgb_to_linear(raw.data[i])).abs() < 1e-6);
|
||||
assert!((converted.data()[i] - craft_texture::srgb_to_linear(raw.data()[i])).abs() < 1e-6);
|
||||
}
|
||||
assert_eq!(converted.data[3], raw.data[3]);
|
||||
assert_eq!(converted.data()[3], raw.data()[3]);
|
||||
|
||||
let mut floats = Vec::new();
|
||||
dds::header::Header::new_image(1, 1, dds::Format::R32G32B32A32_FLOAT).write(&mut floats).unwrap();
|
||||
@@ -91,6 +91,6 @@ fn shared_dds_keeps_rgb_transfer_alpha_and_float_range() {
|
||||
floats.extend_from_slice(&v.to_le_bytes());
|
||||
}
|
||||
for linear in [false, true] {
|
||||
assert_eq!(decode(&floats, linear).unwrap().data.as_slice(), &[-0.5, 2.0, 0.25, 0.75]);
|
||||
assert_eq!(decode(&floats, linear).unwrap().data(), &[-0.5, 2.0, 0.25, 0.75]);
|
||||
}
|
||||
}
|
||||
@@ -25,7 +25,7 @@ fn archived_sbs_replaces_surface_references_from_the_shared_library() {
|
||||
|
||||
fn package() -> 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())));
|
||||
|
||||
@@ -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 }
|
||||
@@ -1,442 +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,
|
||||
/// Normalized integer textures use 16-bit filtered results in function samplers.
|
||||
pub integer_sampling: bool,
|
||||
/// Row-major, `kind.channels()` floats per pixel.
|
||||
pub data: Arc<Vec<f32>>,
|
||||
}
|
||||
|
||||
impl PartialEq for Image {
|
||||
fn eq(&self, o: &Image) -> bool {
|
||||
self.w == o.w
|
||||
&& self.h == o.h
|
||||
&& self.kind == o.kind
|
||||
&& self.integer_sampling == o.integer_sampling
|
||||
&& (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, integer_sampling: false, 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, integer_sampling: false, 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] {
|
||||
self.get_axes(x, y, [tile; 2])
|
||||
}
|
||||
|
||||
/// Read a texel with independent horizontal and vertical wrapping.
|
||||
#[inline]
|
||||
pub fn get_axes(&self, x: i64, y: i64, tiling: [bool; 2]) -> [f32; 4] {
|
||||
let (x, y) = (wrap(x, self.w, tiling[0]), wrap(y, self.h, tiling[1]));
|
||||
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] {
|
||||
self.sample_axes(u, v, [tile; 2])
|
||||
}
|
||||
|
||||
/// Bilinear sample with independent horizontal and vertical wrapping.
|
||||
#[inline]
|
||||
pub fn sample_axes(&self, u: f32, v: f32, tiling: [bool; 2]) -> [f32; 4] {
|
||||
self.sample_filtered(u, v, tiling, false)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn sample_filtered(&self, u: f32, v: f32, tiling: [bool; 2], fixed_weights: 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 (mut tx, mut ty) = (fx - x0, fy - y0);
|
||||
if fixed_weights {
|
||||
// Function texture reads use eight fractional bits for filter weights
|
||||
tx = (tx * 256.0).round() / 256.0;
|
||||
ty = (ty * 256.0).round() / 256.0;
|
||||
}
|
||||
|
||||
let (x0, y0) = (x0 as i64, y0 as i64);
|
||||
let a = self.get_axes(x0, y0, tiling);
|
||||
let b = self.get_axes(x0 + 1, y0, tiling);
|
||||
let c = self.get_axes(x0, y0 + 1, tiling);
|
||||
let d = self.get_axes(x0 + 1, y0 + 1, tiling);
|
||||
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),
|
||||
}
|
||||
}
|
||||
|
||||
/// Function texture reads use fixed filter weights and 16-bit integer results.
|
||||
#[inline]
|
||||
pub fn sample_stored(&self, u: f32, v: f32, tile: bool) -> [f32; 4] {
|
||||
let pixel = self.sample_filtered(u, v, [tile; 2], true);
|
||||
if self.integer_sampling {
|
||||
// Eight-bit sources also retain sixteen bits after interpolation
|
||||
pixel.map(|value| (value.clamp(0.0, 1.0) * 65535.0).round() / 65535.0)
|
||||
} else {
|
||||
pixel
|
||||
}
|
||||
}
|
||||
|
||||
/// Nearest sample at normalized `(u, v)`.
|
||||
#[inline]
|
||||
pub fn sample_nearest(&self, u: f32, v: f32, tile: bool) -> [f32; 4] {
|
||||
self.sample_nearest_axes(u, v, [tile; 2])
|
||||
}
|
||||
|
||||
/// Nearest sample with independent horizontal and vertical wrapping.
|
||||
#[inline]
|
||||
pub fn sample_nearest_axes(&self, u: f32, v: f32, tiling: [bool; 2]) -> [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_axes(x as i64, y as i64, tiling)
|
||||
}
|
||||
|
||||
/// 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<u8> {
|
||||
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);
|
||||
}
|
||||
}
|
||||
@@ -10,5 +10,5 @@ workspace = true
|
||||
|
||||
[dependencies]
|
||||
materialcraft-core = { workspace = true }
|
||||
materialcraft-image = { workspace = true }
|
||||
craft-texture = { workspace = true }
|
||||
rayon = { workspace = true }
|
||||
@@ -1,8 +1,8 @@
|
||||
#![forbid(unsafe_code)]
|
||||
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
|
||||
|
||||
use craft_texture::{Image, Kind};
|
||||
use materialcraft_core::{OutputFormat, Value};
|
||||
use materialcraft_image::{Image, Kind};
|
||||
use materialcraft_nodes::{CookContext, find, resolve_params};
|
||||
use std::{collections::BTreeMap, time::Instant};
|
||||
|
||||
|
||||
@@ -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 };
|
||||
|
||||
@@ -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)
|
||||
@@ -21,19 +21,19 @@ pub(super) fn definition() -> NodeDefinition {
|
||||
}
|
||||
|
||||
fn blend(context: &CookContext) -> CookResult {
|
||||
let (fg, bg) = (context.sized(0), context.sized(1));
|
||||
let kind = if [&fg, &bg].iter().any(|i| i.as_ref().is_some_and(|i| !i.is_gray())) { Kind::Color } else { Kind::Gray };
|
||||
let fg = fg.unwrap_or_else(|| Image::filled(context.w, context.h, kind, [0.0, 0.0, 0.0, 0.0]));
|
||||
let bg = bg.unwrap_or_else(|| Image::filled(context.w, context.h, kind, [0.0, 0.0, 0.0, 1.0]));
|
||||
let (foreground, background) = (context.sized(0), context.sized(1));
|
||||
let kind = if [&foreground, &background].iter().any(|i| i.as_ref().is_some_and(|i| !i.is_gray())) { Kind::Color } else { Kind::Gray };
|
||||
let foreground = foreground.unwrap_or_else(|| Image::filled(context.w, context.h, kind, [0.0, 0.0, 0.0, 0.0]));
|
||||
let background = background.unwrap_or_else(|| Image::filled(context.w, context.h, kind, [0.0, 0.0, 0.0, 1.0]));
|
||||
let mask = context.sized(2).map(|m| m.to_gray());
|
||||
let (mode, op) = (context.i("mode"), context.f("opacity"));
|
||||
let (mode, opacity) = (context.i("mode"), context.f("opacity"));
|
||||
let color_blending = context.i("color_blending");
|
||||
let blend_alpha = context.b("alpha") && !fg.is_gray();
|
||||
let blend_alpha = context.b("alpha") && !foreground.is_gray();
|
||||
let clamp =
|
||||
matches!(context.format, materialcraft_core::OutputFormat::U8 | materialcraft_core::OutputFormat::U16 | materialcraft_core::OutputFormat::Inherit);
|
||||
Ok(vec![Image::generate(context.w, context.h, kind, |x, y| {
|
||||
let (x, y) = (x as i64, y as i64);
|
||||
let m = mask.as_ref().map_or(1.0, |m| m.get_gray(x, y, false));
|
||||
ops::blend_px(mode, bg.get(x, y, false), fg.get(x, y, false), op * m, color_blending, blend_alpha, clamp)
|
||||
ops::blend_px(mode, background.get(x, y, false), foreground.get(x, y, false), opacity * m, color_blending, blend_alpha, clamp)
|
||||
})])
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
use super::{ATOMIC, box_filter};
|
||||
use crate::{CookContext, CookResult, NodeDefinition, node};
|
||||
use materialcraft_image::Kind;
|
||||
use craft_texture::Kind;
|
||||
|
||||
pub(super) fn definition() -> NodeDefinition {
|
||||
node("blur", "Blur", ATOMIC)
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
use materialcraft_image::{Image, MAX_SIDE};
|
||||
use craft_texture::{Image, Limits, MAX_SIDE};
|
||||
use rayon::prelude::*;
|
||||
use std::sync::Arc;
|
||||
|
||||
pub(super) fn axis(input: &Image, radius: f32, horizontal: bool, tile: bool) -> Image {
|
||||
if !radius.is_finite() || radius <= 0.5 {
|
||||
@@ -12,44 +11,49 @@ pub(super) fn axis(input: &Image, radius: f32, horizontal: bool, tile: bool) ->
|
||||
let extent = (radius + 0.5).floor() as i64;
|
||||
let weight = 1.0 / (2.0 * f64::from(radius));
|
||||
let edge_weight = (0.5 - (extent as f64 - 0.5) * weight).max(0.0);
|
||||
let (length, lines) = if horizontal { (input.w, input.h) } else { (input.h, input.w) };
|
||||
let (length, lines) = if horizontal { (input.width(), input.height()) } else { (input.height(), input.width()) };
|
||||
let channels = input.channels();
|
||||
let results: Vec<Vec<f32>> = (0..lines)
|
||||
.into_par_iter()
|
||||
.map(|line| {
|
||||
let get = |position: i64| {
|
||||
if horizontal { input.get(position, i64::from(line), tile) } else { input.get(i64::from(line), position, tile) }
|
||||
};
|
||||
let mut output = vec![0.0; length as usize * channels];
|
||||
for channel in 0..channels {
|
||||
// Count NaN, positive infinity and negative infinity separately
|
||||
let mut sum = 0.0_f64;
|
||||
let mut non_finite = [0_i64; 3];
|
||||
for position in (1 - extent)..extent {
|
||||
accumulate(&mut sum, &mut non_finite, get(position)[channel], 1);
|
||||
}
|
||||
|
||||
for (position, pixel) in output.chunks_exact_mut(channels).enumerate() {
|
||||
let position = position as i64;
|
||||
let mut value = window_total(sum, non_finite) * weight;
|
||||
if edge_weight > 0.0 {
|
||||
value += (f64::from(get(position - extent)[channel]) + f64::from(get(position + extent)[channel])) * edge_weight;
|
||||
}
|
||||
pixel[channel] = value as f32;
|
||||
accumulate(&mut sum, &mut non_finite, get(position + extent)[channel], 1);
|
||||
accumulate(&mut sum, &mut non_finite, get(position - extent + 1)[channel], -1);
|
||||
}
|
||||
let fill_line = |line: u32, output: &mut [f32]| {
|
||||
let get = |position: i64| {
|
||||
if horizontal { input.get(position, i64::from(line), tile) } else { input.get(i64::from(line), position, tile) }
|
||||
};
|
||||
for channel in 0..channels {
|
||||
// Count NaN, positive infinity and negative infinity separately
|
||||
let mut sum = 0.0_f64;
|
||||
let mut non_finite = [0_i64; 3];
|
||||
for position in (1 - extent)..extent {
|
||||
accumulate(&mut sum, &mut non_finite, get(position)[channel], 1);
|
||||
}
|
||||
|
||||
output
|
||||
})
|
||||
.collect();
|
||||
for (position, pixel) in output.chunks_exact_mut(channels).enumerate() {
|
||||
let position = position as i64;
|
||||
let mut value = window_total(sum, non_finite) * weight;
|
||||
if edge_weight > 0.0 {
|
||||
value += (f64::from(get(position - extent)[channel]) + f64::from(get(position + extent)[channel])) * edge_weight;
|
||||
}
|
||||
|
||||
pixel[channel] = value as f32;
|
||||
accumulate(&mut sum, &mut non_finite, get(position + extent)[channel], 1);
|
||||
accumulate(&mut sum, &mut non_finite, get(position - extent + 1)[channel], -1);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
let data = if horizontal {
|
||||
results.into_iter().flatten().collect()
|
||||
let mut data = vec![0.0; input.width() as usize * input.height() as usize * channels];
|
||||
data.par_chunks_mut(length as usize * channels).enumerate().for_each(|(line, output)| fill_line(line as u32, output));
|
||||
data
|
||||
} else {
|
||||
let mut data = Vec::with_capacity(input.w as usize * input.h as usize * channels);
|
||||
for y in 0..input.h as usize {
|
||||
let results: Vec<Vec<f32>> = (0..lines)
|
||||
.into_par_iter()
|
||||
.map(|line| {
|
||||
let mut output = vec![0.0; length as usize * channels];
|
||||
fill_line(line, &mut output);
|
||||
output
|
||||
})
|
||||
.collect();
|
||||
let mut data = Vec::with_capacity(input.width() as usize * input.height() as usize * channels);
|
||||
for y in 0..input.height() as usize {
|
||||
for line in &results {
|
||||
data.extend_from_slice(line.get(y * channels..(y + 1) * channels).unwrap_or(&[]));
|
||||
}
|
||||
@@ -58,7 +62,13 @@ pub(super) fn axis(input: &Image, radius: f32, horizontal: bool, tile: bool) ->
|
||||
data
|
||||
};
|
||||
|
||||
Image { w: input.w, h: input.h, kind: input.kind, integer_sampling: false, data: Arc::new(data) }
|
||||
let mut limits = Limits::default();
|
||||
limits.max_side = u32::MAX;
|
||||
limits.max_pixels = u64::MAX;
|
||||
limits.max_bytes = u64::MAX;
|
||||
|
||||
// `data` keeps the size and kind of a valid image, so `from_data` accepts it
|
||||
Image::from_data(input.width(), input.height(), input.kind(), data, &limits).unwrap_or_else(|_| input.clone())
|
||||
}
|
||||
|
||||
fn accumulate(sum: &mut f64, non_finite: &mut [i64; 3], value: f32, sign: i64) {
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
use super::ATOMIC;
|
||||
use crate::{CookContext, CookResult, NodeDefinition, node};
|
||||
use craft_texture::{Image, Kind};
|
||||
use materialcraft_core::Value;
|
||||
use materialcraft_image::{Image, Kind};
|
||||
|
||||
pub(super) fn definition() -> NodeDefinition {
|
||||
node("channels_shuffle", "Channels shuffle", ATOMIC)
|
||||
|
||||
@@ -1,22 +1,24 @@
|
||||
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)
|
||||
}
|
||||
|
||||
fn curve(context: &CookContext) -> CookResult {
|
||||
let img = context.any_or(0, Kind::Gray, [0.0; 4]);
|
||||
let c = context.curve("curve");
|
||||
// A 1024-entry table: the curve is smooth, so linear lookups are exact enough
|
||||
let lut: Vec<f32> = (0..=1024).map(|i| c.eval(i as f32 / 1024.0)).collect();
|
||||
let f = |v: f32| {
|
||||
let t = v.clamp(0.0, 1.0) * 1024.0;
|
||||
let i = t as usize;
|
||||
let a = lut.get(i).copied().unwrap_or(0.0);
|
||||
let b = lut.get(i + 1).copied().unwrap_or(a);
|
||||
a + (b - a) * (t - i as f32)
|
||||
let image = context.any_or(0, Kind::Gray, [0.0; 4]);
|
||||
let curve = context.curve("curve");
|
||||
|
||||
// Linear interpolation over 1024 intervals approximates the smooth curve
|
||||
const TABLE_INTERVALS: usize = 1024;
|
||||
let table: Vec<f32> = (0..=TABLE_INTERVALS).map(|i| curve.eval(i as f32 / TABLE_INTERVALS as f32)).collect();
|
||||
let lookup = |value: f32| {
|
||||
let position = value.clamp(0.0, 1.0) * TABLE_INTERVALS as f32;
|
||||
let i = position as usize;
|
||||
let a = table.get(i).copied().unwrap_or(0.0);
|
||||
let b = table.get(i + 1).copied().unwrap_or(a);
|
||||
a + (b - a) * (position - i as f32)
|
||||
};
|
||||
Ok(vec![img.map(img.kind, |p| [f(p[0]), f(p[1]), f(p[2]), p[3]])])
|
||||
Ok(vec![image.map(image.kind(), |p| [lookup(p[0]), lookup(p[1]), lookup(p[2]), p[3]])])
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
use super::{ATOMIC, box_filter, 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)
|
||||
@@ -45,7 +45,7 @@ pub(super) fn blur(context: &CookContext, angle: f32) -> CookResult {
|
||||
let edge_weight = (0.5 - (half_samples as f32 - 0.5) * weight).max(0.0);
|
||||
let (inverse_width, inverse_height) = (1.0 / context.w as f32, 1.0 / context.h as f32);
|
||||
|
||||
Ok(vec![Image::generate_uv(context.w, context.h, input.kind, |u, v| {
|
||||
Ok(vec![Image::generate_uv(context.w, context.h, input.kind(), |u, v| {
|
||||
let mut pixel = [0.0; 4];
|
||||
for i in -half_samples..=half_samples {
|
||||
let sample_weight = if i.abs() == half_samples { edge_weight } else { weight };
|
||||
|
||||
@@ -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)
|
||||
@@ -15,12 +15,13 @@ pub(super) fn definition() -> NodeDefinition {
|
||||
}
|
||||
|
||||
fn directional_warp(context: &CookContext) -> CookResult {
|
||||
let img = context.any_or(0, Kind::Gray, [0.0; 4]);
|
||||
let image = context.any_or(0, Kind::Gray, [0.0; 4]);
|
||||
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| {
|
||||
let m = map.sample_gray(u, v, context.tile) * k;
|
||||
img.sample(u + dx * m, v + dy * m, context.tile)
|
||||
const BASE_RESOLUTION: f32 = 256.0;
|
||||
let intensity_scale = context.f("intensity") / BASE_RESOLUTION;
|
||||
Ok(vec![Image::generate_uv(context.w, context.h, image.kind(), |u, v| {
|
||||
let offset = map.sample_gray(u, v, context.tile) * intensity_scale;
|
||||
image.sample(u + dx * offset, v + dy * offset, context.tile)
|
||||
})])
|
||||
}
|
||||
@@ -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)
|
||||
@@ -17,31 +17,38 @@ 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();
|
||||
const BASE_RESOLUTION: f32 = 256.0;
|
||||
const MIN_DISTANCE_PIXELS: f32 = 1e-3;
|
||||
let maximum_distance = (context.f("distance").max(0.0) * context.w as f32 / BASE_RESOLUTION).max(MIN_DISTANCE_PIXELS);
|
||||
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())]);
|
||||
let Some(source) = context.sized(1) else {
|
||||
let squared_distances = ops::distance_sq(context.w, context.h, inside, context.tile);
|
||||
return Ok(vec![ops::gray_from(
|
||||
context.w,
|
||||
context.h,
|
||||
squared_distances.iter().map(|d| (1.0 - d.sqrt() / maximum_distance).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 (squared_distances, 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, source.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 {
|
||||
[0.0, 0.0, 0.0, if src.is_gray() { 1.0 } else { 0.0 }]
|
||||
let mut pixel = if site == usize::MAX {
|
||||
[0.0, 0.0, 0.0, if source.is_gray() { 1.0 } else { 0.0 }]
|
||||
} else {
|
||||
src.get((site % context.w as usize) as i64, (site / context.w as usize) as i64, false)
|
||||
source.get((site % context.w as usize) as i64, (site / context.w as usize) as i64, false)
|
||||
};
|
||||
let d = d2.get(i).copied().unwrap_or(f32::INFINITY).sqrt();
|
||||
if d > maxd {
|
||||
c = [0.0, 0.0, 0.0, if src.is_gray() { 1.0 } else { 0.0 }];
|
||||
let d = squared_distances.get(i).copied().unwrap_or(f32::INFINITY).sqrt();
|
||||
if d > maximum_distance {
|
||||
pixel = [0.0, 0.0, 0.0, if source.is_gray() { 1.0 } else { 0.0 }];
|
||||
} else if combine {
|
||||
let f = (1.0 - d / maxd).clamp(0.0, 1.0);
|
||||
c = [c[0] * f, c[1] * f, c[2] * f, c[3]];
|
||||
let falloff = (1.0 - d / maximum_distance).clamp(0.0, 1.0);
|
||||
pixel = [pixel[0] * falloff, pixel[1] * falloff, pixel[2] * falloff, pixel[3]];
|
||||
}
|
||||
c
|
||||
pixel
|
||||
})])
|
||||
}
|
||||
@@ -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)
|
||||
|
||||
@@ -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)
|
||||
@@ -25,7 +25,7 @@ fn emboss(context: &CookContext) -> CookResult {
|
||||
let intensity = context.f("intensity") * context.w as f32 / INTENSITY_REFERENCE_WIDTH;
|
||||
let (highlight, shadow) = (context.v4("highlight"), context.v4("shadow"));
|
||||
|
||||
Ok(vec![Image::generate(context.w, context.h, input.kind, |x, y| {
|
||||
Ok(vec![Image::generate(context.w, context.h, input.kind(), |x, y| {
|
||||
let (gx, gy) = ops::slope(&height_map, x as i64, y as i64, context.tile);
|
||||
let lighting = (-(gx * light_x + gy * light_y) * intensity).clamp(-1.0, 1.0);
|
||||
let pixel = input.get(x as i64, y as i64, false);
|
||||
|
||||
@@ -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)
|
||||
@@ -23,7 +23,7 @@ fn gradient_dynamic(context: &CookContext) -> CookResult {
|
||||
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) }
|
||||
})])
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
use super::ATOMIC;
|
||||
use crate::{CookContext, CookResult, NodeDefinition, node};
|
||||
use craft_texture::{Kind, luminance};
|
||||
use materialcraft_core::{Gradient, OutputFormat};
|
||||
use materialcraft_image::{Kind, luminance};
|
||||
|
||||
pub(super) fn definition() -> NodeDefinition {
|
||||
node("gradient_map", "Gradient map", ATOMIC)
|
||||
@@ -28,7 +28,7 @@ fn gradient_map(context: &CookContext) -> CookResult {
|
||||
Ok(vec![if gray { input.map(Kind::Gray, |p| [luminance(look(p[0])), 0.0, 0.0, 0.0]) } else { input.map(Kind::Color, |p| look(p[0])) }])
|
||||
}
|
||||
|
||||
fn integer_map(input: &materialcraft_image::Image, mut gradient: Gradient, gray: bool) -> materialcraft_image::Image {
|
||||
fn integer_map(input: &craft_texture::Image, mut gradient: Gradient, gray: bool) -> craft_texture::Image {
|
||||
// The 16-bit path evaluates a 256-entry table in integer position space
|
||||
// Coarse nearest sampling shifts transitions and downstream noise octaves
|
||||
for key in &mut gradient.keys {
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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]))
|
||||
})])
|
||||
}
|
||||
|
||||
@@ -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("normal", "Normal", ATOMIC)
|
||||
@@ -23,8 +23,8 @@ fn normal(context: &CookContext) -> CookResult {
|
||||
}
|
||||
|
||||
pub fn height_to_normal(height_map: &Image, intensity: f32, directx: bool, tile: bool, alpha_height: bool) -> Image {
|
||||
Image::generate(height_map.w, height_map.h, Kind::Color, |x, y| {
|
||||
// Backward differences place alpha wrapped discontinuity on its owning pixel
|
||||
Image::generate(height_map.width(), height_map.height(), Kind::Color, |x, y| {
|
||||
// Backward differences place a wrapped discontinuity on its owning pixel
|
||||
let height = height_map.get_gray(x as i64, y as i64, tile);
|
||||
let dx = height - height_map.get_gray(x as i64 - 1, y as i64, tile);
|
||||
let dy = height - height_map.get_gray(x as i64, y as i64 - 1, tile);
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
use super::GRAPH_ITEMS;
|
||||
use crate::{CookContext, CookResult, NodeDefinition, PortKind, node};
|
||||
use materialcraft_image::{Image, Kind};
|
||||
use craft_texture::{Image, Kind};
|
||||
|
||||
pub(super) fn definition() -> NodeDefinition {
|
||||
node("output", "Output", GRAPH_ITEMS)
|
||||
@@ -21,6 +21,6 @@ pub fn output_kind(def: &NodeDefinition, port: usize, inputs: &[Option<Image>])
|
||||
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()),
|
||||
}
|
||||
}
|
||||
@@ -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("sharpen", "Sharpen", ATOMIC)
|
||||
@@ -20,7 +20,7 @@ fn sharpen(context: &CookContext) -> CookResult {
|
||||
let horizontal = intensity * short_side / context.w.max(1) as f32;
|
||||
let vertical = intensity * short_side / context.h.max(1) as f32;
|
||||
|
||||
Ok(vec![Image::generate(context.w, context.h, input.kind, |x, y| {
|
||||
Ok(vec![Image::generate(context.w, context.h, input.kind(), |x, y| {
|
||||
let (x, y) = (i64::from(x), i64::from(y));
|
||||
let center = input.get(x, y, false);
|
||||
let left = input.get_axes(x - 1, y, tile);
|
||||
|
||||
@@ -221,7 +221,7 @@ mod tests {
|
||||
};
|
||||
|
||||
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");
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
use super::ATOMIC;
|
||||
use crate::{CookContext, CookResult, NodeDefinition, node};
|
||||
use craft_texture::{Image, Kind};
|
||||
use materialcraft_core::OutputFormat;
|
||||
use materialcraft_image::{Image, Kind};
|
||||
|
||||
pub(super) fn definition() -> NodeDefinition {
|
||||
node("transformation", "Transformation 2D", ATOMIC)
|
||||
@@ -21,8 +21,9 @@ fn transformation(context: &CookContext) -> CookResult {
|
||||
let input = context.input(0).cloned().unwrap_or_else(|| Image::filled(context.w, context.h, Kind::Gray, [0.0; 4]));
|
||||
let offset = context.v2("offset");
|
||||
let matrix = context.v4("matrix");
|
||||
const MIN_DETERMINANT: f32 = 1e-8;
|
||||
let determinant = matrix[0] * matrix[3] - matrix[1] * matrix[2];
|
||||
if !determinant.is_finite() || determinant.abs() < 1e-8 {
|
||||
if !determinant.is_finite() || determinant.abs() < MIN_DETERMINANT {
|
||||
return Err("transform matrix is singular".into());
|
||||
}
|
||||
|
||||
@@ -33,7 +34,7 @@ fn transformation(context: &CookContext) -> CookResult {
|
||||
// Keep independent wrap axes for panoramic images
|
||||
let tiling = context.vars.get("$tiling").and_then(materialcraft_core::Value::as_i32).map_or([context.tile; 2], |mask| [mask & 1 != 0, mask & 2 != 0]);
|
||||
|
||||
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;
|
||||
let y = v - 0.5;
|
||||
|
||||
@@ -53,8 +54,8 @@ fn transformation(context: &CookContext) -> CookResult {
|
||||
fn nearest_mip(mut input: Image, matrix: [f32; 4], context: &CookContext) -> Image {
|
||||
let width = context.w.max(1) as f32;
|
||||
let height = context.h.max(1) as f32;
|
||||
let dx = (matrix[0] * input.w as f32 / width).hypot(matrix[1] * input.h as f32 / width);
|
||||
let dy = (matrix[2] * input.w as f32 / height).hypot(matrix[3] * input.h as f32 / height);
|
||||
let dx = (matrix[0] * input.width() as f32 / width).hypot(matrix[1] * input.height() as f32 / width);
|
||||
let dy = (matrix[2] * input.width() as f32 / height).hypot(matrix[3] * input.height() as f32 / height);
|
||||
|
||||
// Thirteen reductions cover the maximum supported side of 8192 texels
|
||||
let levels = dx.max(dy).max(1.0).log2().round().clamp(0.0, 13.0) as u32;
|
||||
@@ -65,12 +66,12 @@ fn nearest_mip(mut input: Image, matrix: [f32; 4], context: &CookContext) -> Ima
|
||||
};
|
||||
|
||||
for _ in 0..levels {
|
||||
if input.w <= 1 && input.h <= 1 {
|
||||
if input.width() <= 1 && input.height() <= 1 {
|
||||
break;
|
||||
}
|
||||
|
||||
// Integer mip levels round four-texel averages halfway up
|
||||
input = Image::generate(input.w.div_ceil(2), input.h.div_ceil(2), input.kind, |x, y| {
|
||||
input = Image::generate(input.width().div_ceil(2), input.height().div_ceil(2), input.kind(), |x, y| {
|
||||
let (x, y) = (i64::from(x) * 2, i64::from(y) * 2);
|
||||
let pixels = [input.get(x, y, false), input.get(x + 1, y, false), input.get(x, y + 1, false), input.get(x + 1, y + 1, false)];
|
||||
std::array::from_fn(|channel| {
|
||||
@@ -78,7 +79,8 @@ fn nearest_mip(mut input: Image, matrix: [f32; 4], context: &CookContext) -> Ima
|
||||
let sum: u32 = pixels.iter().map(|pixel| (pixel[channel].clamp(0.0, 1.0) * maximum).round() as u32).sum();
|
||||
((sum + 2) / 4) as f32 / maximum
|
||||
} else {
|
||||
pixels.iter().map(|pixel| pixel[channel]).sum::<f32>() * 0.25
|
||||
// Average in f64 so finite HDR texels cannot overflow the sum
|
||||
(pixels.iter().map(|pixel| f64::from(pixel[channel])).sum::<f64>() * 0.25) as f32
|
||||
}
|
||||
})
|
||||
});
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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)
|
||||
@@ -15,12 +15,12 @@ pub(super) fn definition() -> NodeDefinition {
|
||||
}
|
||||
|
||||
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| {
|
||||
let image = context.any_or(0, Kind::Gray, [0.0; 4]);
|
||||
let gradient = context.gray_or(1, 0.0);
|
||||
let intensity = context.f("intensity");
|
||||
Ok(vec![Image::generate_uv(context.w, context.h, image.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)
|
||||
let (dx, dy) = ops::slope(&gradient, x, y, context.tile);
|
||||
image.sample(u + dx * intensity, v + dy * intensity, context.tile)
|
||||
})])
|
||||
}
|
||||
@@ -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
|
||||
@@ -98,7 +98,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
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -123,7 +123,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_stored(position[0], position[1], context.tile),
|
||||
None => [0.0; 4],
|
||||
|
||||
@@ -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, format: materialcraft_core::OutputFormat) -> Result<[f32; 4], String> {
|
||||
let values = super::value_type::floats(&value)?;
|
||||
@@ -41,7 +40,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> {
|
||||
@@ -61,5 +60,5 @@ pub(crate) fn pixel_processor(context: &CookContext) -> CookResult {
|
||||
|
||||
Ok(())
|
||||
})?;
|
||||
Ok(vec![Image { w: width, h: height, kind, integer_sampling: false, data: Arc::new(data) }])
|
||||
Ok(vec![Image::from_data(width, height, kind, data, &Limits::default()).map_err(|e| e.to_string())?])
|
||||
}
|
||||
@@ -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};
|
||||
@@ -37,7 +37,9 @@ fn every_native_function_executes_with_its_declared_ports() {
|
||||
let mut covered = BTreeSet::new();
|
||||
for definition in FUNCTIONS {
|
||||
let name = definition.id;
|
||||
|
||||
assert!(covered.insert(name), "duplicate {name}");
|
||||
|
||||
let mut graph = FunctionGraph::default();
|
||||
let mut variables = BTreeMap::new();
|
||||
let mut setting = default_value(name);
|
||||
@@ -131,11 +133,13 @@ fn branches_are_lazy_and_sequence_orders_side_effects() {
|
||||
let expected = graph.add_constant(Value::Int(17));
|
||||
let undefined = graph.add("get_integer1", &[], Some(Value::Text("missing".into())));
|
||||
graph.output = Some(graph.add("ifelse", &[condition, expected, undefined], None));
|
||||
|
||||
assert_eq!(evaluate(&graph, &BTreeMap::new()).unwrap(), Value::Int(17));
|
||||
|
||||
let set = graph.add("set", &[expected], Some(Value::Text("stored".into())));
|
||||
let get = graph.add("get_integer1", &[], Some(Value::Text("stored".into())));
|
||||
graph.output = Some(graph.add("sequence", &[set, get], None));
|
||||
|
||||
assert_eq!(evaluate(&graph, &BTreeMap::new()).unwrap(), Value::Int(17));
|
||||
}
|
||||
|
||||
@@ -153,18 +157,22 @@ fn time_and_tiling_variables_have_typed_defaults_and_host_overrides() {
|
||||
let expected = variables.get(name).unwrap_or(&default);
|
||||
let context = EvaluationContext { scope: Default::default(), position: [0.5; 2], size: [1.0; 2], images: &[], tile: true, variables: &variables };
|
||||
let program = compile(&graph, 0).unwrap();
|
||||
|
||||
assert_eq!(program.evaluate(&context, &mut EvaluationState::default()).unwrap(), *expected);
|
||||
assert_eq!(program.evaluate_pixel(&context, &mut EvaluationState::default()).unwrap(), *expected);
|
||||
}
|
||||
|
||||
assert!(evaluate(&graph, &BTreeMap::from([(name.into(), Value::Bool(false))])).unwrap_err().contains("wrong type"));
|
||||
|
||||
graph.output = Some(defined);
|
||||
|
||||
assert_eq!(evaluate(&graph, &BTreeMap::new()).unwrap(), Value::Bool(true));
|
||||
}
|
||||
|
||||
let mut graph = FunctionGraph::default();
|
||||
graph.output = Some(graph.add("get_integer1", &[], Some(Value::Text("$tiling".into()))));
|
||||
let context = EvaluationContext { scope: Default::default(), position: [0.5; 2], size: [1.0; 2], images: &[], tile: false, variables: &BTreeMap::new() };
|
||||
|
||||
assert_eq!(compile(&graph, 0).unwrap().evaluate(&context, &mut EvaluationState::default()).unwrap(), Value::Int(0));
|
||||
}
|
||||
|
||||
@@ -180,10 +188,12 @@ fn loops_recompute_state_and_have_a_budget() {
|
||||
let add = graph.add("add", &[get, one], None);
|
||||
let body = graph.add("set", &[add], Some(Value::Text("counter".into())));
|
||||
graph.output = Some(graph.add("while", &[init, condition, body], Some(Value::Int(-1))));
|
||||
|
||||
assert_eq!(evaluate(&graph, &BTreeMap::new()).unwrap(), Value::Int(3));
|
||||
|
||||
let condition = graph.add_constant(Value::Bool(false));
|
||||
graph.output = Some(graph.add("while", &[zero, condition, one], Some(Value::Int(-1))));
|
||||
|
||||
assert!(evaluate(&graph, &BTreeMap::new()).unwrap_err().contains("budget"));
|
||||
}
|
||||
|
||||
@@ -195,9 +205,12 @@ fn deep_graphs_shared_inputs_and_cycles_do_not_recurse() {
|
||||
previous = graph.add("passthrough", &[previous], None);
|
||||
}
|
||||
graph.output = Some(graph.add("abs", &[previous], None));
|
||||
|
||||
assert_eq!(evaluate(&graph, &BTreeMap::new()).unwrap(), Value::Float(1.0));
|
||||
|
||||
graph.nodes[0].op = "passthrough".into();
|
||||
graph.nodes[0].inputs = vec![Some(previous)];
|
||||
|
||||
assert!(compile(&graph, 0).err().unwrap().contains("cycle"));
|
||||
|
||||
let mut graph = FunctionGraph::constant(Value::Float(1.0));
|
||||
@@ -206,6 +219,7 @@ fn deep_graphs_shared_inputs_and_cycles_do_not_recurse() {
|
||||
previous = graph.add("add", &[previous, previous], None);
|
||||
}
|
||||
graph.output = Some(previous);
|
||||
|
||||
assert_eq!(evaluate(&graph, &BTreeMap::new()).unwrap(), Value::Float(1_073_741_824.0));
|
||||
}
|
||||
|
||||
@@ -236,6 +250,7 @@ fn pixel_assignments_are_local_and_match_exported_evaluation() {
|
||||
|
||||
let read_only = compile(&FunctionGraph::constant(Value::Float(0.5)), 7).unwrap();
|
||||
let context = EvaluationContext { scope: Default::default(), position: [0.5; 2], size: [1.0; 2], images: &[], tile: true, variables: &BTreeMap::new() };
|
||||
|
||||
assert_eq!(read_only.evaluate_pixel(&context, &mut pixel_state).unwrap(), Value::Float(0.5));
|
||||
assert!(pixel_state.variables().is_empty());
|
||||
}
|
||||
@@ -253,6 +268,7 @@ fn pixel_random_seed_and_defined_variables_match_general_evaluation() {
|
||||
for variables in [BTreeMap::from([("$randomseed".into(), Value::Int(42)), ("known".into(), Value::Bool(true))]), BTreeMap::new()] {
|
||||
let context = EvaluationContext { scope: Default::default(), position: [0.5; 2], size: [1.0; 2], images: &[], tile: true, variables: &variables };
|
||||
let expected = program.evaluate(&context, &mut EvaluationState::default()).unwrap();
|
||||
|
||||
assert_eq!(program.evaluate_pixel(&context, &mut state).unwrap(), expected);
|
||||
}
|
||||
}
|
||||
@@ -587,6 +603,7 @@ fn unconnected_ifelse_branches_use_the_value_type_not_the_condition() {
|
||||
node.type_code = declared_type;
|
||||
let selected = if condition_value { 1 } else { 2 };
|
||||
let expected = if selected == missing { zero.clone() } else { value.clone() };
|
||||
|
||||
assert_eq!(evaluate(&graph, &BTreeMap::new()).unwrap(), expected);
|
||||
}
|
||||
}
|
||||
@@ -603,6 +620,7 @@ fn unconnected_ifelse_condition_stays_boolean_and_empty_branches_keep_declared_t
|
||||
let node = graph.nodes.last_mut().unwrap();
|
||||
node.inputs = vec![None, Some(branch), None];
|
||||
node.type_code = 0;
|
||||
|
||||
assert_eq!(evaluate(&graph, &BTreeMap::new()).unwrap(), Value::Float(0.0));
|
||||
|
||||
for condition_value in [false, true] {
|
||||
@@ -612,6 +630,7 @@ fn unconnected_ifelse_condition_stays_boolean_and_empty_branches_keep_declared_t
|
||||
let node = graph.nodes.last_mut().unwrap();
|
||||
node.inputs = vec![Some(condition), None, None];
|
||||
node.type_code = 512;
|
||||
|
||||
assert_eq!(evaluate(&graph, &BTreeMap::new()).unwrap(), Value::Float2([0.0; 2]));
|
||||
}
|
||||
}
|
||||
@@ -33,7 +33,7 @@ pub use parameter_descriptor::ParameterDescriptor;
|
||||
pub use port_definition::PortDefinition;
|
||||
pub use port_kind::PortKind;
|
||||
|
||||
pub type CookResult = Result<Vec<materialcraft_image::Image>, String>;
|
||||
pub type CookResult = Result<Vec<craft_texture::Image>, String>;
|
||||
pub type Cook = fn(&CookContext<'_>) -> CookResult;
|
||||
|
||||
#[cfg(test)]
|
||||
|
||||
+128
-64
@@ -1,101 +1,125 @@
|
||||
//! 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;
|
||||
/// larger ones three box passes (a close Gaussian approximation in O(1) per pixel).
|
||||
pub fn gaussian(img: &Image, sigma: f32, tile: bool) -> Image {
|
||||
if sigma.is_nan() || sigma <= 0.05 || !sigma.is_finite() {
|
||||
return img.clone();
|
||||
pub fn gaussian(image: &Image, sigma: f32, tile: bool) -> Image {
|
||||
const MIN_SIGMA_PIXELS: f32 = 0.05;
|
||||
const BOX_BLUR_MIN_SIGMA_PIXELS: f32 = 3.0;
|
||||
const KERNEL_RADIUS_SIGMAS: f32 = 3.0;
|
||||
|
||||
if sigma.is_nan() || sigma <= MIN_SIGMA_PIXELS || !sigma.is_finite() {
|
||||
return image.clone();
|
||||
}
|
||||
|
||||
let sigma = sigma.min(img.w.max(img.h) as f32);
|
||||
if sigma < 3.0 {
|
||||
let r = (sigma * 3.0).ceil() as i64;
|
||||
let k: Vec<f32> = (-r..=r).map(|i| (-(i * i) as f32 / (2.0 * sigma * sigma)).exp()).collect();
|
||||
let s: f32 = k.iter().sum();
|
||||
let k: Vec<f32> = k.iter().map(|v| v / s).collect();
|
||||
let pass = |src: &Image, horizontal: bool| convolve_1d(src, &k, r, horizontal, tile);
|
||||
return pass(&pass(img, true), false);
|
||||
let sigma = sigma.min(image.width().max(image.height()) as f32);
|
||||
if sigma < BOX_BLUR_MIN_SIGMA_PIXELS {
|
||||
let radius = (sigma * KERNEL_RADIUS_SIGMAS).ceil() as i64;
|
||||
let kernel: Vec<f32> = (-radius..=radius).map(|i| (-(i * i) as f32 / (2.0 * sigma * sigma)).exp()).collect();
|
||||
let kernel_sum: f32 = kernel.iter().sum();
|
||||
let kernel: Vec<f32> = kernel.iter().map(|v| v / kernel_sum).collect();
|
||||
let pass = |src: &Image, horizontal: bool| convolve_1d(src, &kernel, radius, horizontal, tile);
|
||||
return pass(&pass(image, true), false);
|
||||
}
|
||||
|
||||
// Box widths for three passes (Kovesi, "Fast almost-Gaussian filtering")
|
||||
let n = 3.0f32;
|
||||
let wl = ((12.0 * sigma * sigma / n + 1.0).sqrt()).floor() as i64;
|
||||
let wl = if wl % 2 == 0 { wl - 1 } else { wl };
|
||||
let wu = wl + 2;
|
||||
let m = ((12.0 * sigma * sigma - n * (wl * wl) as f32 - 4.0 * n * wl as f32 - 3.0 * n) / (-4.0 * wl as f32 - 4.0)).round() as i64;
|
||||
let mut out = img.clone();
|
||||
let pass_count = 3.0f32;
|
||||
let lower_width = ((12.0 * sigma * sigma / pass_count + 1.0).sqrt()).floor() as i64;
|
||||
let lower_width = if lower_width % 2 == 0 { lower_width - 1 } else { lower_width };
|
||||
let upper_width = lower_width + 2;
|
||||
let lower_passes = ((12.0 * sigma * sigma - pass_count * (lower_width * lower_width) as f32 - 4.0 * pass_count * lower_width as f32 - 3.0 * pass_count)
|
||||
/ (-4.0 * lower_width as f32 - 4.0))
|
||||
.round() as i64;
|
||||
let mut output = image.clone();
|
||||
for i in 0..3 {
|
||||
let r = (if i < m { wl } else { wu } - 1) / 2;
|
||||
out = box_1d(&box_1d(&out, r.max(0), true, tile), r.max(0), false, tile);
|
||||
let radius = (if i < lower_passes { lower_width } else { upper_width } - 1) / 2;
|
||||
output = box_1d(&box_1d(&output, radius.max(0), true, tile), radius.max(0), false, tile);
|
||||
}
|
||||
|
||||
out
|
||||
output
|
||||
}
|
||||
|
||||
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| {
|
||||
let mut acc = [0.0f32; 4];
|
||||
for (i, kv) in k.iter().enumerate() {
|
||||
let o = i as i64 - r;
|
||||
let p = if horizontal { src.get(x as i64 + o, y as i64, tile) } else { src.get(x as i64, y as i64 + o, tile) };
|
||||
for ch in 0..c.clamp(1, 4) {
|
||||
acc[ch] += p[ch] * kv;
|
||||
/// The default limits, raised to admit `src`, so a pass over an image made with raised limits
|
||||
/// returns an image of the same size.
|
||||
fn limits_for(src: &Image) -> Limits {
|
||||
let mut limits = Limits::default();
|
||||
limits.max_side = limits.max_side.max(src.width()).max(src.height());
|
||||
limits.max_pixels = limits.max_pixels.max(u64::from(src.width()) * u64::from(src.height()));
|
||||
limits.max_bytes = limits.max_bytes.max(size_of_val(src.data()) as u64);
|
||||
limits
|
||||
}
|
||||
|
||||
fn convolve_1d(src: &Image, kernel: &[f32], radius: i64, horizontal: bool, tile: bool) -> Image {
|
||||
let channels = src.channels();
|
||||
Image::try_generate(src.width(), src.height(), src.kind(), &limits_for(src), |x, y| {
|
||||
let mut accumulator = [0.0f32; 4];
|
||||
for (i, weight) in kernel.iter().enumerate() {
|
||||
let offset = i as i64 - radius;
|
||||
let pixel = if horizontal { src.get(x as i64 + offset, y as i64, tile) } else { src.get(x as i64, y as i64 + offset, tile) };
|
||||
for channel in 0..channels.clamp(1, 4) {
|
||||
accumulator[channel] += pixel[channel] * weight;
|
||||
}
|
||||
}
|
||||
if c == 1 { [acc[0], 0.0, 0.0, 0.0] } else { acc }
|
||||
if channels == 1 { [accumulator[0], 0.0, 0.0, 0.0] } else { accumulator }
|
||||
})
|
||||
.unwrap_or_else(|_| src.clone())
|
||||
}
|
||||
|
||||
/// One running-sum box pass of radius `r`.
|
||||
fn box_1d(src: &Image, r: i64, horizontal: bool, tile: bool) -> Image {
|
||||
if r <= 0 {
|
||||
/// One running-sum box pass of radius `radius`.
|
||||
fn box_1d(src: &Image, radius: i64, horizontal: bool, tile: bool) -> Image {
|
||||
if radius <= 0 {
|
||||
return src.clone();
|
||||
}
|
||||
|
||||
let (w, h) = (src.w as usize, src.h as usize);
|
||||
let c = src.channels();
|
||||
let inv = 1.0 / (2 * r + 1) as f32;
|
||||
let mut data = vec![0.0f32; w * h * c];
|
||||
let (w, h) = (src.width() as usize, src.height() as usize);
|
||||
let channels = src.channels();
|
||||
let inverse_width = 1.0 / (2 * radius + 1) as f64;
|
||||
let mut data = vec![0.0f32; w * h * channels];
|
||||
let line_len = if horizontal { w } else { h };
|
||||
let lines = if horizontal { h } else { w };
|
||||
let get = |line: usize, i: i64, ch: usize| -> f32 {
|
||||
|
||||
// f64 keeps finite HDR windows from overflowing the running sum
|
||||
let get = |line: usize, i: i64, channel: 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) * channels + channel).copied().unwrap_or(0.0))
|
||||
};
|
||||
|
||||
let results: Vec<Vec<f32>> = (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();
|
||||
for i in 0..line_len {
|
||||
out[i * c + ch] = sum * inv;
|
||||
sum += get(line, i as i64 + r + 1, ch) - get(line, i as i64 - r, ch);
|
||||
}
|
||||
let fill_line = |line: usize, output: &mut [f32]| {
|
||||
for channel in 0..channels {
|
||||
let mut sum: f64 = (-radius..=radius).map(|i| get(line, i, channel)).sum();
|
||||
for i in 0..line_len {
|
||||
output[i * channels + channel] = (sum * inverse_width) as f32;
|
||||
sum += get(line, i as i64 + radius + 1, channel) - get(line, i as i64 - radius, channel);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
out
|
||||
})
|
||||
.collect();
|
||||
for (line, vals) in results.iter().enumerate() {
|
||||
for i in 0..line_len {
|
||||
let (x, y) = if horizontal { (i, line) } else { (line, i) };
|
||||
let dst = (y * w + x) * c;
|
||||
data[dst..dst + c].copy_from_slice(&vals[i * c..i * c + c]);
|
||||
if horizontal {
|
||||
data.par_chunks_mut(w * channels).enumerate().for_each(|(line, output)| fill_line(line, output));
|
||||
} else {
|
||||
let results: Vec<Vec<f32>> = (0..lines)
|
||||
.into_par_iter()
|
||||
.map(|line| {
|
||||
let mut output = vec![0.0f32; line_len * channels];
|
||||
fill_line(line, &mut output);
|
||||
output
|
||||
})
|
||||
.collect();
|
||||
for (line, values) in results.into_iter().enumerate() {
|
||||
for i in 0..line_len {
|
||||
let destination = (i * w + line) * channels;
|
||||
data[destination..destination + channels].copy_from_slice(&values[i * channels..i * channels + channels]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Image { w: src.w, h: src.h, kind: src.kind, integer_sampling: false, data: Arc::new(data) }
|
||||
// A valid source has matching dimensions and data length
|
||||
Image::from_data(src.width(), src.height(), src.kind(), data, &limits_for(src)).unwrap_or_else(|_| src.clone())
|
||||
}
|
||||
|
||||
/// Squared Euclidean distance (pixels) from every pixel to the nearest pixel where `inside` is
|
||||
@@ -376,9 +400,10 @@ pub fn blend_px(mode: i32, bg: [f32; 4], fg: [f32; 4], opacity: f32, color_blend
|
||||
o
|
||||
}
|
||||
|
||||
/// A gray image of the output size from per-pixel values.
|
||||
pub fn gray_from(w: u32, h: u32, v: Vec<f32>) -> Image {
|
||||
Image { w, h, kind: Kind::Gray, integer_sampling: false, 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<f32>) -> Result<Image, String> {
|
||||
Image::from_data(w, h, Kind::Gray, v, &Limits::default()).map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -405,12 +430,51 @@ mod tests {
|
||||
let img = Image::gray(32, 32, |x, y| if (x / 4 + y / 4) % 2 == 0 { 1.0 } else { 0.0 });
|
||||
for s in [1.0, 6.0] {
|
||||
let b = gaussian(&img, s, true);
|
||||
|
||||
assert!((b.mean()[0] - img.mean()[0]).abs() < 1e-3, "sigma {s}");
|
||||
}
|
||||
let flat = gaussian(&Image::filled(8, 8, Kind::Color, [0.2, 0.4, 0.6, 1.0]), 4.0, false);
|
||||
|
||||
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 blur_keeps_the_size_and_result_of_an_image_over_the_default_limits() {
|
||||
let w = craft_texture::MAX_SIDE + 1;
|
||||
let mut limits = Limits::default();
|
||||
limits.max_side = w;
|
||||
let values: Vec<f32> = (0..w).map(|x| if (x / 8) % 2 == 0 { 1.0 } else { 0.0 }).collect();
|
||||
let Ok(img) = Image::from_data(w, 1, Kind::Gray, values, &limits) else {
|
||||
panic!("a {w}x1 image fits the raised limits");
|
||||
};
|
||||
|
||||
for sigma in [1.0, 5.0] {
|
||||
let blurred = gaussian(&img, sigma, false);
|
||||
|
||||
assert_eq!((blurred.width(), blurred.height()), (w, 1), "sigma {sigma}");
|
||||
assert_ne!(blurred.data(), img.data(), "sigma {sigma} left the pixels unchanged");
|
||||
}
|
||||
}
|
||||
|
||||
#[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);
|
||||
|
||||
@@ -1,27 +1,33 @@
|
||||
use materialcraft_image::{Image, Kind};
|
||||
use craft_texture::{Image, Kind, Limits};
|
||||
use std::sync::Arc;
|
||||
|
||||
use super::{pattern_stamp::PatternStamp, region::Region, shape};
|
||||
use crate::CookContext;
|
||||
|
||||
const MAX_SAMPLES: u64 = 256_000_000;
|
||||
const MAX_STAMP_COPIES: u64 = 1_048_576;
|
||||
const MIN_STAMP_SIZE: f32 = 1e-8;
|
||||
|
||||
pub(super) fn render(context: &CookContext, stamps: &[PatternStamp], max_depth: u32) -> Result<Image, String> {
|
||||
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 mut 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() };
|
||||
background = if kind == Kind::Gray { background.to_gray() } else { background.to_color() };
|
||||
if stamps.is_empty() {
|
||||
return Ok(image);
|
||||
return Ok(background);
|
||||
}
|
||||
|
||||
let channels = kind.channels();
|
||||
let opacity = context.f("opacity").max(0.0);
|
||||
let weights = depth_weights(context.f("roughness"), max_depth)?;
|
||||
let pixels = Arc::make_mut(&mut image.data);
|
||||
let integer_sampling = background.integer_sampling();
|
||||
let mut data = Arc::clone(background.shared_data());
|
||||
drop(background);
|
||||
|
||||
let pixels = Arc::make_mut(&mut data);
|
||||
let mut budget = MAX_SAMPLES;
|
||||
let mut copies_left = 1_048_576_u64;
|
||||
let mut copies_left = MAX_STAMP_COPIES;
|
||||
let render_region = Region::new(context.v4("render_region"))?;
|
||||
let period = if context.tile { Region::new(context.v4("tiling_region"))?.period() } else { [1.0; 2] };
|
||||
|
||||
@@ -30,7 +36,7 @@ pub(super) fn render(context: &CookContext, stamps: &[PatternStamp], max_depth:
|
||||
return Err("pattern parameters must be finite".into());
|
||||
}
|
||||
|
||||
if stamp.size.iter().any(|size| size.abs() < 1e-8) {
|
||||
if stamp.size.iter().any(|size| size.abs() < MIN_STAMP_SIZE) {
|
||||
continue;
|
||||
}
|
||||
|
||||
@@ -84,7 +90,7 @@ pub(super) fn render(context: &CookContext, stamps: &[PatternStamp], max_depth:
|
||||
Some(input) => {
|
||||
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)
|
||||
}
|
||||
@@ -120,11 +126,11 @@ pub(super) fn render(context: &CookContext, stamps: &[PatternStamp], max_depth:
|
||||
}
|
||||
}
|
||||
|
||||
Ok(image)
|
||||
Image::from_data(width, height, kind, data, &Limits::default()).map(|image| image.with_integer_sampling(integer_sampling)).map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
fn depth_weights(roughness: f32, max_depth: u32) -> Result<Vec<f32>, String> {
|
||||
// Traversal is bounded by the 4096-node acyclic pattern graph. Keep this allocation bounded too
|
||||
// Match the depth allocation cap to the 4096-node acyclic traversal limit
|
||||
if max_depth >= 4096 || !roughness.is_finite() || roughness < 0.0 {
|
||||
return Err("pattern roughness must be finite and nonnegative, with depth below 4096".into());
|
||||
}
|
||||
|
||||
@@ -67,12 +67,17 @@ fn iterate_sets_number_and_switch_selects_one_child() {
|
||||
function.output = Some(function.add("get_float1", &[], Some(Value::Text("$number".into()))));
|
||||
graph.nodes[2].parameters.insert("opacity".into(), Value::Function(Box::new(function)));
|
||||
let image = cook(graph.clone()).unwrap().remove(0);
|
||||
|
||||
assert!((image.mean()[0] - 3.0).abs() < 1e-6);
|
||||
|
||||
let dot = graph.add(PatternNodeKind::Dot).unwrap();
|
||||
graph.nodes[1].children[0] = Some(dot);
|
||||
graph.nodes[3].children[0] = Some(quadrant);
|
||||
assert_eq!(cook(graph.clone()).unwrap()[0].data, image.data);
|
||||
|
||||
assert_eq!(cook(graph.clone()).unwrap()[0].data(), image.data());
|
||||
|
||||
graph.nodes[1].parameters.insert("switch".into(), Value::Bool(true));
|
||||
|
||||
assert_eq!(cook(graph).unwrap()[0].mean()[0], 0.0);
|
||||
}
|
||||
|
||||
@@ -96,7 +101,7 @@ fn iterate_preserves_assignments_from_previous_iterations() {
|
||||
graph.nodes[1].parameters.insert("opacity".into(), Value::Function(Box::new(increment)));
|
||||
let image = cook(graph).unwrap().remove(0);
|
||||
|
||||
assert!(image.data.iter().all(|value| *value == 6.0), "expected 1 + 2 + 3, got {:?}", image.mean());
|
||||
assert!(image.data().iter().all(|value| *value == 6.0), "expected 1 + 2 + 3, got {:?}", image.mean());
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -182,7 +187,7 @@ fn roughness_attenuates_quadrants_by_depth_and_keeps_background() {
|
||||
for blend in 0..=2 {
|
||||
let image = roughness_sample(roughness, depth, blend, color, false).unwrap().remove(0);
|
||||
let pixel = image.get(0, 0, false);
|
||||
for (channel, foreground) in [0.8_f32, 0.4, 0.2, 1.0].into_iter().take(image.kind.channels()).enumerate() {
|
||||
for (channel, foreground) in [0.8_f32, 0.4, 0.2, 1.0].into_iter().take(image.channels()).enumerate() {
|
||||
let value = foreground * 0.5 * weight;
|
||||
let expected = match blend {
|
||||
1 if !color => value.max(0.1),
|
||||
@@ -245,7 +250,7 @@ fn a_full_nine_level_quadtree_renders_one_pattern_per_pixel() {
|
||||
|
||||
let images = (definition.cook)(&context).unwrap();
|
||||
|
||||
assert!(images[0].data.iter().all(|value| (*value - 1.0).abs() < 1e-6));
|
||||
assert!(images[0].data().iter().all(|value| (*value - 1.0).abs() < 1e-6));
|
||||
}
|
||||
|
||||
fn square(graph: &mut PatternGraph, node: usize) {
|
||||
|
||||
@@ -1,11 +1,11 @@
|
||||
use materialcraft_image::{Image, Kind, luminance};
|
||||
use craft_texture::{Image, Kind, luminance};
|
||||
|
||||
use crate::CookContext;
|
||||
|
||||
pub(crate) fn composite(context: &CookContext, foreground: impl Fn(u32, u32) -> [f32; 4] + Sync) -> Image {
|
||||
let kind = if context.b("color_mode") { Kind::Color } else { Kind::Gray };
|
||||
let background = match context.input(0) {
|
||||
Some(image) if image.kind == kind => image.resize(context.w, context.h, context.tile),
|
||||
Some(image) if image.kind() == kind => image.resize(context.w, context.h, context.tile),
|
||||
|
||||
// An incompatible connection replaces the constant background with empty pixels
|
||||
Some(_) => Image::filled(1, 1, kind, [0.0; 4]),
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
use craft_texture::{Image, Kind};
|
||||
use materialcraft_core::Value;
|
||||
use materialcraft_image::{Image, Kind};
|
||||
|
||||
use super::*;
|
||||
|
||||
@@ -69,14 +69,17 @@ fn every_node_cooks() {
|
||||
let result = cook(definition, &inputs, 32);
|
||||
if definition.id == "pixel_processor" {
|
||||
assert_eq!(result.unwrap_err(), "function has no result node");
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
let outputs = result.unwrap_or_else(|error| panic!("{}: {error}", definition.id));
|
||||
|
||||
assert_eq!(outputs.len(), definition.outputs.len().max(1), "{}", definition.id);
|
||||
|
||||
for image in &outputs {
|
||||
assert_eq!((image.w, image.h), (32, 32), "{}", definition.id);
|
||||
assert!(image.data.iter().all(|value| value.is_finite()), "{} produced a non-finite value", definition.id);
|
||||
assert_eq!((image.width(), image.height()), (32, 32), "{}", definition.id);
|
||||
assert!(image.data().iter().all(|value| value.is_finite()), "{} produced a non-finite value", definition.id);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -134,8 +137,8 @@ fn every_node_survives_hostile_params() {
|
||||
}
|
||||
|
||||
for img in &out {
|
||||
assert_eq!((img.w, img.h), (16, 16), "{}.{}={h}", def.id, p.id);
|
||||
assert!(img.data.iter().all(|x| x.is_finite()), "{}.{}={h} produced a non-finite value", def.id, p.id);
|
||||
assert_eq!((img.width(), img.height()), (16, 16), "{}.{}={h}", def.id, p.id);
|
||||
assert!(img.data().iter().all(|x| x.is_finite()), "{}.{}={h} produced a non-finite value", def.id, p.id);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -168,7 +171,7 @@ fn blend_and_levels_math() {
|
||||
|
||||
let out = (def.cook)(&ctx).unwrap();
|
||||
|
||||
assert!((out[0].data[0] - 0.125).abs() < 1e-6);
|
||||
assert!((out[0].data()[0] - 0.125).abs() < 1e-6);
|
||||
assert!((atomic::levels_fn(0.5, 0.0, 0.5, 1.0, 0.0, 1.0) - 0.5).abs() < 1e-5);
|
||||
assert_eq!(atomic::levels_fn(0.2, 0.4, 0.5, 0.8, 0.0, 1.0), 0.0);
|
||||
}
|
||||
@@ -180,7 +183,93 @@ fn dynamic_gradient_preserves_the_gradient_image_type() {
|
||||
let source = Image::filled(4, 4, Kind::Gray, [0.5; 4]);
|
||||
let gradient = Image::filled(4, 4, kind, [0.25, 0.5, 0.75, 1.0]);
|
||||
let result = cook(definition, &[Some(source), Some(gradient.clone())], 16).unwrap();
|
||||
assert_eq!(result[0].kind, kind);
|
||||
|
||||
assert_eq!(result[0].kind(), kind);
|
||||
assert_eq!(result[0].get(0, 0, false), gradient.get(0, 0, false));
|
||||
}
|
||||
}
|
||||
|
||||
/// Cooks `def` at `w × h` without tiling, with `resource` as the package's bitmaps.
|
||||
fn cook_sized(def: &NodeDefinition, inputs: &[Option<Image>], w: u32, h: u32, resource: &(dyn Fn(&str) -> Option<Image> + Sync)) -> CookResult {
|
||||
let params = resolve_params(def, &BTreeMap::new());
|
||||
let vars = BTreeMap::new();
|
||||
let ctx = CookContext { format: materialcraft_core::OutputFormat::F32, 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}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nearest_transformation_mips_preserve_finite_hdr_constants() {
|
||||
let definition = find("transformation").unwrap();
|
||||
let parameters = resolve_params(definition, &BTreeMap::from([("filtering".into(), Value::Enum(1))]));
|
||||
let variables = BTreeMap::new();
|
||||
let value = 0.75 * f32::MAX;
|
||||
|
||||
for kind in [Kind::Gray, Kind::Color] {
|
||||
let inputs = [Some(Image::filled(16, 16, kind, [value; 4]))];
|
||||
let context = CookContext {
|
||||
format: materialcraft_core::OutputFormat::F32,
|
||||
w: 4,
|
||||
h: 4,
|
||||
seed: 7,
|
||||
tile: false,
|
||||
inputs: &inputs,
|
||||
params: ¶meters,
|
||||
resource: &|_| None,
|
||||
vars: &variables,
|
||||
};
|
||||
|
||||
let output = (definition.cook)(&context).unwrap().remove(0);
|
||||
|
||||
assert_eq!((output.width(), output.height(), output.kind()), (4, 4, kind));
|
||||
assert!(output.data().iter().all(|pixel| *pixel == value), "{:?}", output.data());
|
||||
}
|
||||
}
|
||||
|
||||
/// 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, moving each 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:?}");
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
use craft_texture::{Image, Kind};
|
||||
use materialcraft_core::{OutputFormat, Value};
|
||||
use materialcraft_image::{Image, Kind};
|
||||
use materialcraft_nodes::{CookContext, find, resolve_params};
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
@@ -71,7 +71,7 @@ fn sharpen_preserves_finite_hdr_constant() {
|
||||
|
||||
let output = cook("sharpen", &[Some(input)], &[("intensity", Value::Float(1.0))], [16, 16], true);
|
||||
|
||||
assert!(output.data.iter().all(|value| value.to_bits() == constant.to_bits()));
|
||||
assert!(output.data().iter().all(|value| value.to_bits() == constant.to_bits()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -92,7 +92,7 @@ fn blur_preserves_finite_hdr_constant() {
|
||||
|
||||
let output = cook("blur", &[Some(input)], &[("intensity", Value::Float(64.0))], [16, 16], true);
|
||||
|
||||
assert!(output.data.iter().all(|value| value.is_finite() && (*value - 1.0e38).abs() < 1.0e32));
|
||||
assert!(output.data().iter().all(|value| value.is_finite() && (*value - 1.0e38).abs() < 1.0e32));
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -116,7 +116,7 @@ fn sharpen_has_center_gain_and_clamps_negative_lobes() {
|
||||
let output = cook("sharpen", &[Some(input)], &[("intensity", Value::Float(1.0))], [16, 16], true);
|
||||
|
||||
assert_eq!(output.get_gray(8, 8, false), 5.0);
|
||||
assert!(output.data.iter().all(|value| *value >= 0.0));
|
||||
assert!(output.data().iter().all(|value| *value >= 0.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
use craft_texture::{Image, Kind};
|
||||
use materialcraft_core::{FunctionGraph, PatternGraph, PatternNodeKind, Value};
|
||||
use materialcraft_image::{Image, Kind};
|
||||
use materialcraft_nodes::{CookContext, find, resolve_params};
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
@@ -59,7 +59,7 @@ fn repeated_quadrants_have_distinct_reproducible_random_values() {
|
||||
let samples: Vec<_> = [(16, 16), (48, 16), (16, 48), (48, 48)].map(|(x, y)| image.get_gray(x, y, false)).into_iter().collect();
|
||||
|
||||
assert!(samples.windows(2).all(|pair| pair[0] != pair[1]), "{samples:?}");
|
||||
assert_eq!(image.data, cook("fx_map", values, &[]).data);
|
||||
assert_eq!(image.data(), cook("fx_map", values, &[]).data());
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -89,7 +89,7 @@ fn subpixel_quadrants_do_not_accumulate_at_shared_edges() {
|
||||
leaf.parameters.insert("opacity".into(), Value::Float(0.25));
|
||||
let image = cook("fx_map", BTreeMap::from([("pattern".into(), Value::PatternGraph(Box::new(graph)))]), &[]);
|
||||
|
||||
assert!(image.data.iter().all(|value| (*value - 0.25).abs() < 1e-6), "mean {}", image.mean()[0]);
|
||||
assert!(image.data().iter().all(|value| (*value - 0.25).abs() < 1e-6), "mean {}", image.mean()[0]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -105,5 +105,5 @@ fn grayscale_max_patterns_do_not_accumulate_opacity() {
|
||||
graph.nodes[0].parameters.insert("numberadded".into(), Value::Int(2));
|
||||
let repeated = cook("fx_map", values(graph), &[]);
|
||||
|
||||
assert!(single.data == repeated.data, "repeating a maximum blend must not brighten the image");
|
||||
assert!(single.data() == repeated.data(), "repeating a maximum blend must not brighten the image");
|
||||
}
|
||||
@@ -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<Image>, 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;
|
||||
@@ -23,7 +23,7 @@ fn tiled_distance_spreads_source_across_stationary_gradient() {
|
||||
|
||||
// A zero slope at the only mask pixel must not stop the walk on background
|
||||
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]
|
||||
@@ -55,11 +55,14 @@ 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);
|
||||
assert_eq!(ramp.get_gray(1, 0, false), 0.5);
|
||||
assert_eq!(ramp.get_gray(3, 0, false), 0.0);
|
||||
|
||||
@@ -2,7 +2,7 @@ use materialcraft_core::{PatternGraph, PatternNodeKind, Value};
|
||||
use materialcraft_nodes::{CookContext, find, resolve_params};
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
fn render(depth: usize, roughness: f32, stack: bool, color: Option<[f32; 4]>) -> materialcraft_image::Image {
|
||||
fn render(depth: usize, roughness: f32, stack: bool, color: Option<[f32; 4]>) -> craft_texture::Image {
|
||||
let mut graph = PatternGraph::with_root(PatternNodeKind::Quadrant);
|
||||
for index in 0..depth {
|
||||
let child = graph.add(PatternNodeKind::Quadrant).unwrap();
|
||||
@@ -59,7 +59,7 @@ fn quadrant_opacity_matches_measured_depth_and_stack_values() {
|
||||
let image = render(depth, roughness, false, None);
|
||||
|
||||
assert!(
|
||||
image.data.iter().all(|value| (*value - expected).abs() < 2e-7),
|
||||
image.data().iter().all(|value| (*value - expected).abs() < 2e-7),
|
||||
"roughness {roughness}, depth {depth}: {:?}, expected {expected}",
|
||||
image.mean()
|
||||
);
|
||||
@@ -68,7 +68,7 @@ fn quadrant_opacity_matches_measured_depth_and_stack_values() {
|
||||
for roughness in [0.42, 1.0] {
|
||||
let image = render(4, roughness, true, None);
|
||||
|
||||
assert!(image.data.iter().all(|value| (*value - 0.125).abs() < 2e-7), "stack roughness {roughness}: {:?}", image.mean());
|
||||
assert!(image.data().iter().all(|value| (*value - 0.125).abs() < 2e-7), "stack roughness {roughness}: {:?}", image.mean());
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -35,7 +35,7 @@ fn render_region_samples_a_cropped_area() {
|
||||
let crop = render([0.25, 0.75, 0.25, 0.75], identity, false).unwrap().remove(0);
|
||||
|
||||
assert_eq!(full.mean()[0], 0.25);
|
||||
assert!(crop.data.iter().all(|value| *value == 1.0));
|
||||
assert!(crop.data().iter().all(|value| *value == 1.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -47,7 +47,7 @@ fn tiling_region_sets_repeat_distance_independently_of_render_region() {
|
||||
|
||||
assert_eq!(repeated.get(48, 32, false)[0], 1.0);
|
||||
assert_eq!(wider.get(48, 32, false)[0], 0.0);
|
||||
assert_eq!(wider.data, untiled.data);
|
||||
assert_eq!(wider.data(), untiled.data());
|
||||
assert_eq!(repeated.mean()[0], 0.25);
|
||||
assert_eq!(wider.mean()[0], 0.125);
|
||||
}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
use craft_texture::Kind;
|
||||
use materialcraft_core::{OutputFormat, Value};
|
||||
use materialcraft_image::Kind;
|
||||
use materialcraft_nodes::{CookContext, find, resolve_params};
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
@@ -21,7 +21,8 @@ fn absent_textures_have_zero_pixels_and_expected_kinds() {
|
||||
let outputs = (definition.cook)(&context).unwrap();
|
||||
let image = outputs.first().unwrap();
|
||||
|
||||
assert_eq!(image.kind, kind, "{id}");
|
||||
assert_eq!(image.kind(), kind, "{id}");
|
||||
|
||||
for y in 0..h {
|
||||
for x in 0..w {
|
||||
assert_eq!(image.get(x.into(), y.into(), false), pixel, "{id} at {x},{y}");
|
||||
|
||||
@@ -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 }
|
||||
@@ -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,8 +94,9 @@ impl Scene {
|
||||
mesh = mesh.subdivided();
|
||||
}
|
||||
|
||||
// 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);
|
||||
// Filter detail finer than the mesh to prevent silhouette spikes
|
||||
const MAX_HEIGHT_MAP_SIDE: u32 = 512;
|
||||
let height = height.resize(height.width().min(MAX_HEIGHT_MAP_SIDE), height.height().min(MAX_HEIGHT_MAP_SIDE), 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 };
|
||||
@@ -495,52 +496,52 @@ pub fn render(scene: &Scene, maps: &Maps, light: &Lighting, s: &Settings, w: u32
|
||||
/// [`render`] that gives up once `cancel` is set (rows not yet started are skipped) and then
|
||||
/// returns `None`: a frame the viewer no longer needs (the camera moved, the view was resized)
|
||||
/// stops holding the CPU.
|
||||
pub fn render_cancellable(scene: &Scene, maps: &Maps, light: &Lighting, s: &Settings, w: u32, h: u32, cancel: &AtomicBool) -> Option<Vec<u8>> {
|
||||
pub fn render_cancellable(scene: &Scene, maps: &Maps, light: &Lighting, settings: &Settings, w: u32, h: u32, cancel: &AtomicBool) -> Option<Vec<u8>> {
|
||||
let (w, h) = (w.clamp(1, 4096), h.clamp(1, 4096));
|
||||
let cam = camera(scene, s);
|
||||
let camera = camera(scene, settings);
|
||||
let aspect = w as f32 / h as f32;
|
||||
let ss = s.supersample.clamp(1, 4);
|
||||
let k = 2f32.powf(s.exposure);
|
||||
let bg_env = light.specular.get(3).or(light.specular.last());
|
||||
let samples_per_axis = settings.supersample.clamp(1, 4);
|
||||
let exposure_scale = 2f32.powf(settings.exposure);
|
||||
let background_environment = light.specular.get(3).or(light.specular.last());
|
||||
|
||||
// Key light from the camera's upper left, a little in front of the subject
|
||||
let fwd = cam.ray(Vec2::ZERO, aspect).dir;
|
||||
let right = fwd.cross(Vec3::Y).normalize_or(Vec3::X);
|
||||
let key = (right * -0.6 + right.cross(fwd) * 0.75 - fwd * 0.5).normalize_or_zero();
|
||||
let mut out = vec![0u8; (w * h * 4) as usize];
|
||||
out.par_chunks_mut(w as usize * 4).enumerate().for_each(|(y, row)| {
|
||||
let forward = camera.ray(Vec2::ZERO, aspect).dir;
|
||||
let right = forward.cross(Vec3::Y).normalize_or(Vec3::X);
|
||||
let key = (right * -0.6 + right.cross(forward) * 0.75 - forward * 0.5).normalize_or_zero();
|
||||
let mut output = vec![0u8; (w * h * 4) as usize];
|
||||
output.par_chunks_mut(w as usize * 4).enumerate().for_each(|(y, row)| {
|
||||
if cancel.load(Ordering::Relaxed) {
|
||||
return;
|
||||
}
|
||||
|
||||
for x in 0..w as usize {
|
||||
let mut acc = Vec3::ZERO;
|
||||
for sy in 0..ss {
|
||||
for sx in 0..ss {
|
||||
let px = (x as f32 + (sx as f32 + 0.5) / ss as f32) / w as f32 * 2.0 - 1.0;
|
||||
let py = 1.0 - (y as f32 + (sy as f32 + 0.5) / ss as f32) / h as f32 * 2.0;
|
||||
let ray = cam.ray(Vec2::new(px, py), aspect);
|
||||
let bg = backdrop(Vec2::new(px, py));
|
||||
let p = Px { key, jitter: jitter(x as u32 * ss + sx, y as u32 * ss + sy) };
|
||||
let miss = match (s.show_env, bg_env) {
|
||||
(true, Some(e)) => e.sample(rotate_y(ray.dir, -s.env_rotation)) * k,
|
||||
_ => bg,
|
||||
let mut accumulated = Vec3::ZERO;
|
||||
for sy in 0..samples_per_axis {
|
||||
for sx in 0..samples_per_axis {
|
||||
let px = (x as f32 + (sx as f32 + 0.5) / samples_per_axis as f32) / w as f32 * 2.0 - 1.0;
|
||||
let py = 1.0 - (y as f32 + (sy as f32 + 0.5) / samples_per_axis as f32) / h as f32 * 2.0;
|
||||
let ray = camera.ray(Vec2::new(px, py), aspect);
|
||||
let background = backdrop(Vec2::new(px, py));
|
||||
let p = Px { key, jitter: jitter(x as u32 * samples_per_axis + sx, y as u32 * samples_per_axis + sy) };
|
||||
let miss = match (settings.show_env, background_environment) {
|
||||
(true, Some(e)) => e.sample(rotate_y(ray.dir, -settings.env_rotation)) * exposure_scale,
|
||||
_ => background,
|
||||
};
|
||||
acc += if s.alpha_view {
|
||||
accumulated += if settings.alpha_view {
|
||||
// Display values: the alpha as is, the background tone mapped
|
||||
match shade(scene, maps, light, s, ray.origin, ray.dir, &p) {
|
||||
match shade(scene, maps, light, settings, ray.origin, ray.dir, &p) {
|
||||
Some(h) => h.color,
|
||||
None => miss.map(|v| linear_to_srgb(aces(v))),
|
||||
}
|
||||
} else {
|
||||
trace(scene, maps, light, s, ray.origin, ray.dir, &p, k, miss)
|
||||
trace(scene, maps, light, settings, ray.origin, ray.dir, &p, exposure_scale, miss)
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
let c = acc / (ss * ss) as f32;
|
||||
let c = accumulated / (samples_per_axis * samples_per_axis) as f32;
|
||||
let q = |v: f32| {
|
||||
let d = if s.alpha_view { v } else { linear_to_srgb(aces(v)) };
|
||||
let d = if settings.alpha_view { v } else { linear_to_srgb(aces(v)) };
|
||||
(d.clamp(0.0, 1.0) * 255.0 + 0.5) as u8
|
||||
};
|
||||
if let Some(px) = row.get_mut(x * 4..x * 4 + 4) {
|
||||
@@ -548,13 +549,13 @@ pub fn render_cancellable(scene: &Scene, maps: &Maps, light: &Lighting, s: &Sett
|
||||
}
|
||||
}
|
||||
});
|
||||
if cancel.load(Ordering::Relaxed) { None } else { Some(out) }
|
||||
if cancel.load(Ordering::Relaxed) { None } else { Some(output) }
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use materialcraft_image::Kind;
|
||||
use craft_texture::Kind;
|
||||
|
||||
#[test]
|
||||
fn renders_a_material_on_every_scene() {
|
||||
|
||||
@@ -77,8 +77,11 @@ fn batch_writes_every_material_graph_at_the_output_size() {
|
||||
assert!(export(&mut app, &settings));
|
||||
|
||||
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);
|
||||
}
|
||||
|
||||
|
||||
Loaded 100 of 110 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user