Install bounded material bakes at the original drop target

This commit is contained in:
chasse20 committed 2026-11-18 04:05:53 -05:00
1 parent 0ef6f72f7c
commit 5290481844
12 files changed
+311 -142

No files matched your search

+54 -91
View File
@@ -8,12 +8,28 @@ use std::sync::Arc;
use serde_json::{Map, Value, json};
use texturecraft_core::{BakedMap, Channel, Fill, Layer, LayerId, LayerKind, LinkParam, MaterialLink, Source};
use texturecraft_formats::mcmat::{MCRAFT_EXT, is_mcraft, validate_mcmat};
use texturecraft_formats::mcmat::{MCRAFT_EXT, is_mcmat, is_mcraft, validate_mcmat};
use crate::commands::{CommandSpec, bad, boolp, has_layer, layer_param, strp};
use crate::materials::Place;
use crate::{EngineError, Result, Session, cmd};
#[cfg(not(target_arch = "wasm32"))]
mod cook_report;
mod cooked_map;
mod cooked_material;
mod image_input;
mod link_job;
#[cfg(not(target_arch = "wasm32"))]
mod map_file;
mod material_interface;
pub use cooked_map::CookedMap;
pub use cooked_material::CookedMaterial;
pub use image_input::ImageInput;
pub use link_job::LinkJob;
pub use material_interface::MaterialInterface;
/// The undo label of parameter edits and re-cooks (a re-cook merges into the edit before it).
const EDIT: &str = "Edit MaterialCraft material";
@@ -192,24 +208,6 @@ fn save_source(_: &mut Session, _: &Value) -> Result<Value> {
Err(EngineError::Other("file paths are not available in the browser".into()))
}
/// A re-cook of a linked layer, to run anywhere (a worker thread) and hand back to
/// [`Session::apply_link_cook`].
#[derive(Clone, Debug)]
pub struct LinkJob {
pub layer: LayerId,
pub package: Arc<Vec<u8>>,
/// The source package extension (`mcmat`, `mcraft` or `sbs`).
pub source_ext: &'static str,
/// The named graph in a linked material; direct package imports use its default.
pub graph: Option<String>,
/// Pixels across (the texture set's resolution).
pub size: u32,
/// Every parameter's value, by id, in MaterialCraft's typed form.
pub values: Map<String, Value>,
/// Graph inputs fed from baked mesh maps: identifier → 16-bit PNG.
pub inputs: Vec<(String, Vec<u8>)>,
}
/// A MaterialCraft executable: `$<env>`, else next to this program, else `name` on `PATH`.
#[cfg(not(target_arch = "wasm32"))]
pub fn materialcraft_tool(name: &str, env: &str) -> std::path::PathBuf {
@@ -251,69 +249,33 @@ pub fn source_extension(name: &str) -> &'static str {
}
}
#[derive(Clone, Debug, serde::Deserialize)]
pub struct MaterialInterface {
pub name: String,
pub graph: String,
pub parameters: Vec<LinkParam>,
pub inputs: Vec<ImageInput>,
pub presets: Vec<texturecraft_core::LinkPreset>,
}
#[derive(Clone, Debug, serde::Deserialize)]
pub struct ImageInput {
pub identifier: String,
}
#[derive(Clone, Debug)]
pub struct CookedMaterial {
pub interface: MaterialInterface,
pub maps: Vec<(String, Vec<u8>)>,
pub size: u32,
}
#[cfg(not(target_arch = "wasm32"))]
#[path = "link_cook.rs"]
mod link_cook;
#[cfg(target_arch = "wasm32")]
impl LinkJob {
pub fn run_for_import(&self, _: Option<&texturecraft_compose::BakedMaps>) -> Result<CookedMaterial> {
self.run()
}
pub fn run(&self) -> Result<CookedMaterial> {
Err(EngineError::Other("cooking a procedural material requires materialcraft-cli on a desktop".into()))
}
}
/// Prepare the first bake without borrowing the paint document. Its original archive is kept for future cooks.
fn cook_source(bytes: Vec<u8>, size: u32, baked: Option<&texturecraft_compose::BakedMaps>) -> Result<(LinkJob, CookedMaterial)> {
let source_ext = if is_mcraft(&bytes) {
let source_ext = if is_mcmat(&bytes) {
"mcmat"
} else if is_mcraft(&bytes) {
MCRAFT_EXT
} else {
validate_mcmat(&bytes).map_err(|e| EngineError::Other(e.to_string()))?;
"mcmat"
return Err(EngineError::Other("expected a MaterialCraft material or project archive".into()));
};
let job = LinkJob { layer: LayerId(0), package: Arc::new(bytes), source_ext, graph: None, size, values: Map::new(), inputs: Vec::new() };
let material = job.run_for_import(baked)?;
let material = job.run_for_import(baked).map_err(|error| {
// Older archives still need a republishing diagnostic when the desktop CLI is unavailable
if source_ext == "mcmat"
&& let Err(format) = validate_mcmat(&job.package)
{
return EngineError::Other(format.to_string());
}
error
})?;
Ok((job, material))
}
#[cfg(not(target_arch = "wasm32"))]
pub fn cook_link_file(path: &std::path::Path, size: u32, baked: Option<&texturecraft_compose::BakedMaps>) -> Result<(LinkJob, CookedMaterial)> {
cook_source(link_cook::read_bounded(path, 1 << 30)?, size, baked)
}
/// Decode every map of `m` (validating them) with the channel it feeds.
fn decoded_maps(m: &CookedMaterial) -> Result<Vec<(Channel, Vec<u8>, texturecraft_formats::DecodedImage)>> {
m.maps
.iter()
.filter_map(|(usage, bytes)| Some((Channel::ALL.into_iter().find(|c| c.id() == usage)?, bytes)))
.map(|(c, bytes)| {
let img = texturecraft_formats::decode_image(bytes).map_err(|e| EngineError::Other(format!("{} map: {e}", c.id())))?;
Ok((c, bytes.clone(), img))
})
.collect()
cook_source(link_job::read_bounded(path, link_job::MAX_COOK_BYTES)?, size, baked)
}
impl Session {
@@ -328,10 +290,10 @@ impl Session {
/// Install validated CLI output in one undo step. Keep the original source for future variations.
pub fn add_cooked_material(&mut self, m: &CookedMaterial, source: Arc<Vec<u8>>, source_ext: &str, place: Place) -> Result<LayerId> {
let maps = decoded_maps(m)?;
if maps.is_empty() {
if m.maps.is_empty() {
return Err(EngineError::Other(format!("{} has no maps TextureCraft can paint with", m.interface.name)));
}
let label = format!("Add {}", m.interface.name);
let (id, names) = self.edit(&label, |s| {
let ts = s.ts();
@@ -352,7 +314,7 @@ impl Session {
size: m.size,
};
let mut fill = Fill { link: Some(Box::new(link)), ..Fill::default() };
let names = put_maps(s, &stem, &maps, &mut fill);
let names = put_maps(s, &stem, &m.maps, &mut fill);
for c in fill.sources.keys() {
crate::set_cmds::add_channel(s, ts, *c)?;
}
@@ -365,7 +327,7 @@ impl Session {
s.target = crate::session::StackTarget::Content;
Ok((lid, names))
})?;
self.cache_decoded(names, maps);
self.cache_decoded(names, &m.maps);
Ok(id)
}
@@ -411,12 +373,10 @@ impl Session {
})
}
/// Swap in maps a [`LinkJob`] cooked (`.mcmat` bytes) and the values they were cooked with.
/// Install the maps and exposed values returned by a completed [`LinkJob`].
/// With `merge`, this folds into the previous undo step when that was an edit of the same kind
/// (a parameter set while the cook ran).
pub fn apply_link_cook(&mut self, id: LayerId, material: &CookedMaterial, merge: bool) -> Result<()> {
let maps = decoded_maps(material)?;
let names = self.edit_merging(EDIT, merge, |session| {
let LayerKind::Fill(mut fill) = session.doc.project.layer(id)?.kind.clone() else {
return Err(EngineError::Other(format!("layer {} is not a fill", id.0)));
@@ -432,7 +392,7 @@ impl Session {
let stem = texturecraft_formats::sanitize_resource_name(&link.name);
let old_names: Vec<String> =
fill.sources.values().filter_map(|source| if let Source::Image { name, .. } = source { Some(name.clone()) } else { None }).collect();
let names = put_maps(session, &stem, &maps, &mut fill);
let names = put_maps(session, &stem, &material.maps, &mut fill);
session.doc.project.layer_mut(id)?.kind = LayerKind::Fill(fill);
// Duplicated layers may still use the earlier maps
@@ -450,16 +410,16 @@ impl Session {
})?;
// Reuse the validated maps before synchronization considers decoding missing images
self.cache_decoded(names, maps);
self.cache_decoded(names, &material.maps);
self.sync_images();
Ok(())
}
/// Keep the images decoded while validating maps instead of decoding them again.
fn cache_decoded(&mut self, names: Vec<String>, maps: Vec<(Channel, Vec<u8>, texturecraft_formats::DecodedImage)>) {
for (name, (_, _, img)) in names.into_iter().zip(maps) {
self.images.insert(name, crate::resource_cmds::decoded(img));
fn cache_decoded(&mut self, names: Vec<String>, maps: &[CookedMap]) {
for (name, map) in names.into_iter().zip(maps) {
self.images.insert(name, Arc::clone(&map.image));
}
}
}
@@ -471,21 +431,24 @@ fn unique(s: &Session, name: &str) -> String {
/// Store `maps` as new resources (names carry a fresh id, so the decoded-image cache never
/// confuses two cooks) and point `fill`'s channels at them. Returns the names, in map order.
fn put_maps(s: &mut Session, stem: &str, maps: &[(Channel, Vec<u8>, texturecraft_formats::DecodedImage)], fill: &mut Fill) -> Vec<String> {
fn put_maps(s: &mut Session, stem: &str, maps: &[CookedMap], fill: &mut Fill) -> Vec<String> {
let cook = s.doc.project.alloc_id().0;
let mut names = Vec::new();
for (c, bytes, _) in maps {
let extension = if bytes.starts_with(&[0x76, 0x2f, 0x31, 0x01]) { "exr" } else { "png" };
let name = unique(s, &format!("{stem}_{}_{cook}.{extension}", c.id()));
s.doc.resources.insert(name.clone(), Arc::new(bytes.clone()));
// A normal map the user marked DirectX stays marked through re-cooks.
let normal_format = match fill.sources.get(c) {
for map in maps {
let channel = map.channel;
let extension = if map.bytes.starts_with(&[0x76, 0x2f, 0x31, 0x01]) { "exr" } else { "png" };
let name = unique(s, &format!("{stem}_{}_{cook}.{extension}", channel.id()));
s.doc.resources.insert(name.clone(), Arc::clone(&map.bytes));
// Preserve a normal convention the user chose for this layer
let normal_format = match fill.sources.get(&channel) {
Some(Source::Image { normal_format, .. }) => *normal_format,
_ => Default::default(),
};
fill.sources.insert(*c, Source::Image { name: name.clone(), normal_format });
fill.sources.insert(channel, Source::Image { name: name.clone(), normal_format });
names.push(name);
}
names
}
@@ -0,0 +1,8 @@
use super::{MaterialInterface, map_file::MapFile};
use serde::Deserialize;
#[derive(Deserialize)]
pub(super) struct CookReport {
pub(super) material: MaterialInterface,
pub(super) maps: Vec<MapFile>,
}
+45
View File
@@ -0,0 +1,45 @@
use std::sync::Arc;
use texturecraft_compose::ImageRes;
use texturecraft_core::Channel;
use crate::{EngineError, Result};
/// A validated bake ready to install in the document and decoded-image cache.
#[derive(Clone, Debug)]
pub struct CookedMap {
pub channel: Channel,
pub bytes: Arc<Vec<u8>>,
pub image: Arc<ImageRes>,
}
impl CookedMap {
/// Allow nine 4K RGBA maps across a single material import.
pub const MAX_TOTAL_TEXELS: u64 = 9 * 4096 * 4096;
pub fn decode(channel: Channel, bytes: Vec<u8>, remaining_texels: &mut u64) -> Result<Self> {
let limit = (*remaining_texels).min(texturecraft_formats::MAX_RESOURCE_TEXELS);
let image = texturecraft_formats::decode_image_within(&bytes, limit).map_err(|error| EngineError::Other(format!("{} map: {error}", channel.id())))?;
*remaining_texels -= u64::from(image.width) * u64::from(image.height);
Ok(Self { channel, bytes: Arc::new(bytes), image: crate::resource_cmds::decoded(image) })
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn each_retained_map_reduces_the_next_decoders_budget() {
let bytes = texturecraft_formats::gray16_png(4, 4, [0.5; 16].into_iter()).unwrap();
let mut remaining = 31;
let first = CookedMap::decode(Channel::Roughness, bytes.clone(), &mut remaining).unwrap();
let second = CookedMap::decode(Channel::Metallic, bytes, &mut remaining);
assert_eq!(first.image.rgba.len(), 16);
assert_eq!(remaining, 15);
assert!(second.unwrap_err().to_string().contains("15 texels"));
}
}
@@ -0,0 +1,8 @@
use super::{CookedMap, MaterialInterface};
#[derive(Clone, Debug)]
pub struct CookedMaterial {
pub interface: MaterialInterface,
pub maps: Vec<CookedMap>,
pub size: u32,
}
@@ -0,0 +1,4 @@
#[derive(Clone, Debug, serde::Deserialize)]
pub struct ImageInput {
pub identifier: String,
}
@@ -1,29 +1,63 @@
//! Cook a procedural source in a private directory. Only declared map files enter the paint document.
use super::{CookedMaterial, EngineError, LinkJob, MaterialInterface, Result, materialcraft_tool, quiet};
use serde::Deserialize;
use std::io::Read;
use std::path::Path;
use texturecraft_compose::BakedMaps;
use texturecraft_core::{BakedMap, Channel};
use std::sync::Arc;
use super::{CookedMaterial, EngineError, Result};
use serde_json::{Map, Value};
use texturecraft_core::LayerId;
#[cfg(not(target_arch = "wasm32"))]
use {
super::{CookedMap, MaterialInterface, cook_report::CookReport, materialcraft_tool, quiet},
std::{io::Read, path::Path},
texturecraft_compose::BakedMaps,
texturecraft_core::{BakedMap, Channel},
};
#[cfg(not(target_arch = "wasm32"))]
pub(super) const MAX_COOK_BYTES: u64 = 1 << 30;
/// A re-cook of a linked layer, to run anywhere (a worker thread) and hand back to
/// [`crate::Session::apply_link_cook`].
#[derive(Clone, Debug)]
pub struct LinkJob {
pub layer: LayerId,
pub package: Arc<Vec<u8>>,
/// The source package extension (`mcmat`, `mcraft` or `sbs`).
pub source_ext: &'static str,
/// The named graph in a linked material; direct package imports use its default.
pub graph: Option<String>,
/// Pixels across (the texture set's resolution).
pub size: u32,
/// Every parameter's value, by id, in MaterialCraft's typed form.
pub values: Map<String, Value>,
/// Graph inputs fed from baked mesh maps: identifier → 16-bit PNG.
pub inputs: Vec<(String, Vec<u8>)>,
}
#[cfg(not(target_arch = "wasm32"))]
fn io(error: impl std::fmt::Display) -> EngineError {
EngineError::Other(error.to_string())
}
#[cfg(not(target_arch = "wasm32"))]
pub(super) fn read_bounded(path: &Path, limit: u64) -> Result<Vec<u8>> {
let metadata = std::fs::symlink_metadata(path).map_err(io)?;
if !metadata.is_file() || metadata.len() > limit {
return Err(io(format!("invalid or oversized cook output: {}", path.display())));
}
let mut bytes = Vec::new();
std::fs::File::open(path).map_err(io)?.take(limit + 1).read_to_end(&mut bytes).map_err(io)?;
std::fs::File::open(path).map_err(io)?.take(limit.saturating_add(1)).read_to_end(&mut bytes).map_err(io)?;
if bytes.len() as u64 > limit {
return Err(io("cook output exceeds the remaining budget"));
}
Ok(bytes)
}
#[cfg(not(target_arch = "wasm32"))]
fn invoke(mut command: std::process::Command, dir: &Path) -> Result<Vec<u8>> {
const MAX_DIAGNOSTIC_BYTES: u64 = 1 << 20;
const MAX_REPORT_BYTES: u64 = 8 << 20;
let stdout = dir.join("reply.json");
let stderr = dir.join("diagnostic.txt");
let status = command
@@ -32,23 +66,16 @@ fn invoke(mut command: std::process::Command, dir: &Path) -> Result<Vec<u8>> {
.status()
.map_err(|e| io(format!("could not start materialcraft-cli: {e}. Install MaterialCraft or set MATERIALCRAFT_CLI")))?;
if !status.success() {
return Err(io(format!("MaterialCraft could not cook the material: {}", String::from_utf8_lossy(&read_bounded(&stderr, 1 << 20)?).trim())));
return Err(io(format!(
"MaterialCraft could not cook the material: {}",
String::from_utf8_lossy(&read_bounded(&stderr, MAX_DIAGNOSTIC_BYTES)?).trim()
)));
}
read_bounded(&stdout, 8 << 20)
}
#[derive(Deserialize)]
struct Reply {
material: MaterialInterface,
maps: Vec<MapFile>,
}
#[derive(Deserialize)]
struct MapFile {
usage: String,
file: String,
size: [u32; 2],
read_bounded(&stdout, MAX_REPORT_BYTES)
}
#[cfg(not(target_arch = "wasm32"))]
impl LinkJob {
pub fn run(&self) -> Result<CookedMaterial> {
self.run_for_import(None)
@@ -56,21 +83,19 @@ impl LinkJob {
pub(super) fn run_for_import(&self, baked: Option<&BakedMaps>) -> Result<CookedMaterial> {
let cli = materialcraft_tool("materialcraft-cli", "MATERIALCRAFT_CLI");
self.run_with_cli(&cli, baked)
}
fn run_with_cli(&self, cli: &Path, baked: Option<&BakedMaps>) -> Result<CookedMaterial> {
let temp = tempfile::Builder::new().prefix("texturecraft-material-").tempdir().map_err(io)?;
let dir = temp.path();
let ext = match self.source_ext {
"mcmat" | "sbs" | "mcraft" => self.source_ext,
_ => return Err(io("unknown linked source format")),
};
let source = dir.join(format!("source.{ext}"));
std::fs::write(&source, &*self.package).map_err(io)?;
let out = dir.join("maps");
let mut export = quiet(cli);
export.arg("export").arg(&source).arg(&out).args(["--profile", "maps", "--size"]).arg(self.size.to_string());
let mut export = quiet(&cli);
export.arg("export").arg(&source).arg(&out).args(["--profile", "maps", "--size"]).arg(format!("{}x{}", self.size, self.size));
if self.source_ext != "mcmat"
&& let Some(graph) = &self.graph
{
@@ -79,6 +104,7 @@ impl LinkJob {
for (id, value) in &self.values {
export.arg("--set").arg(format!("{id}={value}"));
}
let add_input = |export: &mut std::process::Command, index: usize, id: &str, data: &[u8]| -> Result<()> {
let file = dir.join(format!("input{index}.png"));
std::fs::write(&file, data).map_err(io)?;
@@ -88,8 +114,9 @@ impl LinkJob {
for (i, (id, bytes)) in self.inputs.iter().enumerate() {
add_input(&mut export, i, id, bytes)?;
}
if let Some(bakes) = baked {
let mut inspect = quiet(cli);
if let Some(bakes) = baked.filter(|bakes| !bakes.maps.is_empty()) {
let mut inspect = quiet(&cli);
if self.source_ext == "mcmat" {
inspect.arg("info").arg(&source);
} else {
@@ -105,26 +132,49 @@ impl LinkJob {
}
}
}
let reply: Reply = serde_json::from_slice(&invoke(export, dir)?).map_err(io)?;
let mut budget = 1u64 << 30;
let mut maps = Vec::new();
let reply: CookReport = serde_json::from_slice(&invoke(export, dir)?).map_err(io)?;
let mut remaining_bytes = MAX_COOK_BYTES;
let mut remaining_texels = CookedMap::MAX_TOTAL_TEXELS;
let mut maps = Vec::<CookedMap>::new();
let mut size = 0;
for map in reply.maps {
if !Channel::ALL.iter().any(|c| c.id() == map.usage) || maps.iter().any(|(usage, _)| usage == &map.usage) {
let Some(channel) = Channel::ALL.into_iter().find(|channel| channel.id() == map.usage) else { continue };
if maps.iter().any(|map| map.channel == channel) {
continue;
}
let path = Path::new(&map.file);
if path.file_name().and_then(|p| p.to_str()) != Some(&map.file) || map.file.contains(['\\', ':']) {
return Err(io("invalid map filename in MaterialCraft's export report"));
}
let data = read_bounded(&out.join(path), budget.min(512 << 20))?;
budget -= data.len() as u64;
size = size.max(map.size[0]).max(map.size[1]);
maps.push((map.usage, data));
let bytes = read_bounded(&out.join(path), remaining_bytes.min(crate::resource_cmds::MAX_BYTES as u64))?;
remaining_bytes -= bytes.len() as u64;
let decoded = CookedMap::decode(channel, bytes, &mut remaining_texels)?;
if [decoded.image.width, decoded.image.height] != map.size {
return Err(io(format!("{} map dimensions disagree with the export report", map.usage)));
}
size = size.max(decoded.image.width).max(decoded.image.height);
maps.push(decoded);
}
if maps.is_empty() {
return Err(io("MaterialCraft returned no paintable map usages"));
}
Ok(CookedMaterial { interface: reply.material, maps, size })
}
}
#[cfg(target_arch = "wasm32")]
impl LinkJob {
pub(super) fn run_for_import(&self, _: Option<&texturecraft_compose::BakedMaps>) -> Result<CookedMaterial> {
self.run()
}
pub fn run(&self) -> Result<CookedMaterial> {
Err(EngineError::Other("cooking a procedural material requires materialcraft-cli on a desktop".into()))
}
}
+8
View File
@@ -0,0 +1,8 @@
use serde::Deserialize;
#[derive(Deserialize)]
pub(super) struct MapFile {
pub(super) usage: String,
pub(super) file: String,
pub(super) size: [u32; 2],
}
@@ -0,0 +1,11 @@
use super::ImageInput;
use texturecraft_core::{LinkParam, LinkPreset};
#[derive(Clone, Debug, serde::Deserialize)]
pub struct MaterialInterface {
pub name: String,
pub graph: String,
pub parameters: Vec<LinkParam>,
pub inputs: Vec<ImageInput>,
pub presets: Vec<LinkPreset>,
}
+26 -7
View File
@@ -10,7 +10,7 @@ use texturecraft_engine::compose::BakedMaps;
use texturecraft_engine::core::{BakedMap, Channel, LayerId, LayerKind, NormalFormat, Source};
use texturecraft_engine::formats::mcmat::mesh_map_png;
use texturecraft_engine::geom::primitives;
use texturecraft_engine::link_cmds::CookedMaterial;
use texturecraft_engine::link_cmds::{CookedMap, CookedMaterial};
use texturecraft_engine::materials::Place;
use texturecraft_engine::{Session, execute};
@@ -39,14 +39,14 @@ fn cooked(roughness: f32, wear: f32) -> CookedMaterial {
],
"presets": [{"name": "Worn", "values": {"wear": {"t": "float", "v": 1.0}, "note": {"t": "text", "v": "x"}}}],
});
let mut remaining = CookedMap::MAX_TOTAL_TEXELS;
CookedMaterial {
interface: serde_json::from_value(interface).unwrap(),
size: 4,
maps: vec![
("baseColor".into(), mesh_map_png(4, 3, &[0.5; 48]).unwrap()),
("roughness".into(), gray(roughness)),
("ambientOcclusion".into(), gray(1.0)),
],
maps: [(Channel::BaseColor, mesh_map_png(4, 3, &[0.5; 48]).unwrap()), (Channel::Roughness, gray(roughness)), (Channel::AmbientOcclusion, gray(1.0))]
.into_iter()
.map(|(channel, bytes)| CookedMap::decode(channel, bytes, &mut remaining).unwrap())
.collect(),
}
}
@@ -207,9 +207,13 @@ fn cooks_through_materialcraft_cli_when_available() {
let ok = std::process::Command::new(&cli).args(["new", "pbr"]).arg(&pkg).args(["--size", "64"]).status().unwrap();
assert!(ok.success());
let exposed = dir.join("exposed.mcraft");
let rectangular = dir.join("rectangular.mcraft");
let resize =
std::process::Command::new(&cli).arg("run").arg(&pkg).args(["graph.size", r#"{"width":64,"height":32}"#, "-o"]).arg(&rectangular).status().unwrap();
assert!(resize.success());
let ok = std::process::Command::new(&cli)
.arg("run")
.arg(&pkg)
.arg(&rectangular)
.arg("graph.exposed.add")
.arg(r#"{"id":"wear","bind":{"node":5,"param":"color"}}"#)
.arg("-o")
@@ -238,6 +242,8 @@ fn cooks_through_materialcraft_cli_when_available() {
s.doc.baked.insert(0, BakedMaps { resolution: 16, maps: [(BakedMap::Curvature, Arc::new(vec![0.35; 256]))].into() });
let id = s.add_linked_material_bytes_at(&std::fs::read(&exposed).unwrap(), Place::Selection).unwrap();
assert_eq!(link(&s, id).size, 128, "cooked at the texture set's resolution");
let image = &s.images[&map_name(&s, id, Channel::Roughness)];
assert_eq!([image.width, image.height], [128, 128]);
assert!(link(&s, id).params.iter().any(|p| p.id == "wear"));
assert!((roughness(&mut s) - 0.5).abs() < 0.01);
assert!((s.caches[0].composite.value(Channel::Metallic, 64, 64)[0] - 0.35).abs() < 0.01);
@@ -267,3 +273,16 @@ fn cooks_through_materialcraft_cli_when_available() {
assert_eq!(result.interface.graph, expected_graph);
assert_eq!(result.size, 128);
}
#[test]
fn installing_a_bake_reuses_its_encoded_map_buffers() {
let material = cooked(0.25, 0.5);
let prepared = &material.maps[1];
let mut session = session();
let id = session.add_cooked_material(&material, Arc::new(Vec::new()), "mcmat", Place::Selection).unwrap();
let name = map_name(&session, id, Channel::Roughness);
assert!(Arc::ptr_eq(&session.doc.resources[&name], &prepared.bytes));
assert!(Arc::ptr_eq(&session.images[&name], &prepared.image));
}
+1 -1
View File
@@ -147,7 +147,7 @@ pub struct TextureCraftApp {
pub resize: Option<ResizeJob>,
pub link_cooks: Vec<LinkCook>,
#[cfg(not(target_arch = "wasm32"))]
link_imports: Vec<link_import::Import>,
link_imports: Vec<link_import::LinkImport>,
pub thumbs: thumbs::Thumbs,
/// The Layers panel's thumbnails and folded groups.
pub layer_panel: layer_panel::LayerPanel,
+58 -5
View File
@@ -7,7 +7,7 @@ use serde_json::{Value, json};
use texturecraft_engine::link_cmds::{CookedMaterial, LinkJob, cook_link_file};
use texturecraft_engine::materials::Place;
pub(super) struct Import {
pub(super) struct LinkImport {
mesh: u64,
set: usize,
resolution: u32,
@@ -22,17 +22,26 @@ pub(super) fn is_procedural(path: &str) -> bool {
impl TextureCraftApp {
pub(super) fn start_link_import(&mut self, path: &str, params: &Value) -> Option<Value> {
let set = self.session.ts();
let resolution = match self.session.doc.project.texture_set(set) {
Ok(set) => set.resolution,
let texture_set = match self.session.doc.project.texture_set(set) {
Ok(set) => set,
Err(error) => {
self.toast(error.to_string(), true);
return None;
}
};
// The artist can select a different layer while this import cooks
let place = match Place::from_params(params) {
Place::Selection => self.session.selected_layer().map_or(Place::Index(texture_set.stack.len()), |target| {
Place::Above(target, self.session.doc.project.layer(target).is_ok_and(|layer| layer.is_group()))
}),
explicit => explicit,
};
let resolution = texture_set.resolution;
let baked = self.session.baked(set).cloned();
let path = PathBuf::from(path);
let rx = super::spawn_worker("texturecraft-material-import", move || cook_link_file(&path, resolution, baked.as_ref()));
self.link_imports.push(Import { mesh: self.session.mesh_id, set, resolution, place: Place::from_params(params), result: rx });
self.link_imports.push(LinkImport { mesh: self.session.mesh_id, set, resolution, place, result: rx });
self.toast("Cooking MaterialCraft material", false);
Some(json!({"pending":true}))
}
@@ -41,6 +50,7 @@ impl TextureCraftApp {
if self.link_imports.is_empty() {
return;
}
ctx.request_repaint_after(std::time::Duration::from_millis(50));
for job in std::mem::take(&mut self.link_imports) {
let result = match job.result.try_recv() {
@@ -51,7 +61,8 @@ impl TextureCraftApp {
Err(TryRecvError::Disconnected) => Err(texturecraft_engine::EngineError::Other("the material import stopped".into())),
Ok(result) => result,
};
// Replacing a project or resizing its texture set invalidates the target captured at drop time.
// Replacing a project or resizing its texture set invalidates a pending bake
if job.mesh != self.session.mesh_id
|| job.set != self.session.ts()
|| !self.session.doc.project.texture_set(job.set).is_ok_and(|set| set.resolution == job.resolution)
@@ -59,6 +70,14 @@ impl TextureCraftApp {
self.toast("Material import canceled because the target texture set changed", true);
continue;
}
if let Place::Above(target, _) = job.place
&& !self.session.doc.project.locate(target).is_some_and(|(set, _, _)| set == job.set)
{
self.toast("Material import canceled because the target layer changed", true);
continue;
}
match result.and_then(|(source, cooked)| self.session.add_cooked_material(&cooked, source.package, source.source_ext, job.place)) {
Ok(_) => self.toast("Material imported", false),
Err(error) => self.toast(error.to_string(), true),
@@ -66,3 +85,37 @@ impl TextureCraftApp {
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::time::{Duration, Instant};
use texturecraft_engine::{Session, execute};
#[test]
fn pending_import_keeps_its_original_layer_position() {
let Some(cli) = std::env::var_os("MATERIALCRAFT_CLI") else { return };
let path = std::env::temp_dir().join(format!("texturecraft-pending-import-{}.mcraft", std::process::id()));
let source = std::process::Command::new(cli).args(["new", "pbr"]).arg(&path).args(["--size", "32"]).output().unwrap();
assert!(source.status.success());
let session = Session::new_project("Paint", texturecraft_engine::geom::primitives::cube(1.0), "builtin:cube", None, 128).unwrap();
let context = eframe::CreationContext::_new_kittest(egui::Context::default());
let mut app = TextureCraftApp::new(&context, session);
execute(&mut app.session, "layer.add.paint", &json!({"name":"Drop target"})).unwrap();
let target = app.session.selected_layer().unwrap();
app.start_link_import(path.to_str().unwrap(), &Value::Null).unwrap();
execute(&mut app.session, "layer.add.paint", &json!({"name":"Later selection"})).unwrap();
let later = app.session.selected_layer().unwrap();
let deadline = Instant::now() + Duration::from_secs(60);
while !app.link_imports.is_empty() && Instant::now() < deadline {
app.poll_link_imports(&context.egui_ctx);
std::thread::sleep(Duration::from_millis(10));
}
std::fs::remove_file(path).unwrap();
let imported = app.session.selected_layer().unwrap();
let stack = &app.session.doc.project.texture_sets[0].stack;
assert!(stack.ends_with(&[target, imported, later]), "{stack:?}");
}
}
+1 -1
View File
@@ -402,7 +402,7 @@ A v3 `.mcmat` holds a published SBS graph and its source assets. TextureCraft us
| `material.link.cook` | `{layer?}`: re-cook at the texture set's resolution with its baked mesh maps (after a bake or a resize) |
| `material.link.saveSource` | `{layer?, path}`: the original linked source with its `.mcmat`, `.mcraft` or `.sbs` extension |
TextureCraft requests `materialcraft-cli export source.mcmat maps --profile maps --size <pixels>` with repeated `--set` and `--input` arguments. It discovers the published image inputs through `info` when the texture set supplies mesh maps. The executable is resolved from
For a 1024-pixel texture set, TextureCraft requests `materialcraft-cli export source.mcmat maps --profile maps --size 1024x1024` with repeated `--set` and `--input` arguments. It discovers the published image inputs through `info` when the texture set supplies mesh maps. The desktop worker decodes the returned maps before installing the fill at its original drop target. The executable is resolved from
`$MATERIALCRAFT_CLI`, else `materialcraft-cli` next to the TextureCraft executable, else on `PATH`
(the app is `$MATERIALCRAFT` / `materialcraft`). Baked maps feed graph input nodes whose identifier
matches the map's shared id (`ambientOcclusion`, `curvature`, `thickness`, `position`,