diff --git a/crates/engine/src/commands.rs b/crates/engine/src/commands.rs index 8b8683b0..66256332 100644 --- a/crates/engine/src/commands.rs +++ b/crates/engine/src/commands.rs @@ -63,6 +63,7 @@ pub fn command_specs() -> &'static [CommandSpec] { v.extend(crate::camera_cmds::specs()); v.extend(crate::quick_mask::specs()); v.extend(crate::set_cmds::specs()); + v.extend(crate::meshmap_cmds::specs()); v.extend(crate::uv_tile_cmds::specs()); v.extend(crate::template_cmds::specs()); v.extend(crate::project_cmds::specs()); diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index a3a621ea..e790cd0e 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -23,6 +23,7 @@ pub mod mask_cmds; pub mod material_lib; pub mod materials; pub mod materialx_cmds; +pub mod meshmap_cmds; pub mod painting; pub mod path_tool; // Mesh reimport reads files: native only. diff --git a/crates/engine/src/meshmap_cmds.rs b/crates/engine/src/meshmap_cmds.rs new file mode 100644 index 00000000..1a42a362 --- /dev/null +++ b/crates/engine/src/meshmap_cmds.rs @@ -0,0 +1,98 @@ +//! Mesh map slots of the Texture Set Settings: use an image resource as a mesh map (baked in +//! another app, or edited by hand) instead of baking it, or clear a slot. + +use std::sync::Arc; + +use rayon::prelude::*; +use serde_json::{Value, json}; +use texturecraft_compose::ImageRes; +use texturecraft_core::{BakedMap, MAX_RESOLUTION, NormalFormat}; + +use crate::commands::{CommandSpec, always, bad, strp}; +use crate::set_cmds::ts_param; +use crate::{Result, Session, cmd}; + +pub fn specs() -> Vec { + vec![ + cmd!( + "textureSet.meshMap.set", + "Use image as mesh map", + [], + None, + "{ts?, map: mesh map id (normal_base, ambient_occlusion, curvature, id, height…), image: resource name} → {map, resolution} — resampled to the size of the set's other mesh maps (or its bake size); a normal map is read in the project's normal format", + always, + set + ), + cmd!("textureSet.meshMap.clear", "Clear mesh map", [], None, "{ts?, map}", always, clear), + ] +} + +fn map_param(p: &Value, cmd: &str) -> Result { + let id = strp(p, "map").ok_or_else(|| bad(cmd, "`map` is required"))?; + BakedMap::parse(id).ok_or_else(|| bad(cmd, format!("unknown mesh map `{id}`"))) +} + +fn set(s: &mut Session, p: &Value) -> Result { + const CMD: &str = "textureSet.meshMap.set"; + let ts = ts_param(s, p, CMD)?; + let map = map_param(p, CMD)?; + let name = strp(p, "image").ok_or_else(|| bad(CMD, "`image` (an image resource name) is required"))?; + let img = s.images.get(name).cloned().ok_or_else(|| bad(CMD, format!("no image resource `{name}`")))?; + let set = s.doc.project.texture_set(ts)?; + // shortcut: one image spans the whole set; UV-tiled sets would need one image per tile. + if !set.uv_tiles.is_empty() { + return Err(bad(CMD, format!("\"{}\" has UV tiles: mesh maps from images need a set without them", set.name))); + } + // Every mesh map of a set shares one size: the other maps', or what a bake would make. + let res = s.doc.baked.get(&ts).filter(|b| !b.maps.is_empty()).map_or(set.bake.resolution, |b| b.resolution); + if !(1..=MAX_RESOLUTION).contains(&res) { + return Err(bad(CMD, format!("mesh map size {res} is not in 1..={MAX_RESOLUTION}"))); + } + let directx = map == BakedMap::Normal && s.doc.project.normal_format == NormalFormat::DirectX; + let data = resample(&img, map.components(), res, directx); + s.edit("Use image as mesh map", |s| { + let entry = s.doc.baked.entry(ts).or_default(); + entry.resolution = res; + entry.maps.insert(map, Arc::new(data)); + s.doc.project.texture_set_mut(ts)?.baked.insert(map); + Ok(()) + })?; + Ok(json!({ "map": map.id(), "resolution": res })) +} + +/// `img` as `res` × `res` texels of `comps` values each, as stored in the file (mesh maps hold +/// data, not colors, so nothing is linearized); `flip_green` reads a DirectX normal map. +fn resample(img: &ImageRes, comps: usize, res: u32, flip_green: bool) -> Vec { + let n = res as usize; + let mut out = vec![0.0; n * n * comps]; + out.par_chunks_mut(n * comps).enumerate().for_each(|(y, row)| { + let v = (y as f32 + 0.5) / res as f32; + for (x, texel) in row.chunks_exact_mut(comps).enumerate() { + let mut c = img.sample((x as f32 + 0.5) / res as f32, v); + if flip_green { + c[1] = 1.0 - c[1]; + } + for (o, c) in texel.iter_mut().zip(c) { + *o = c; + } + } + }); + out +} + +fn clear(s: &mut Session, p: &Value) -> Result { + const CMD: &str = "textureSet.meshMap.clear"; + let ts = ts_param(s, p, CMD)?; + let map = map_param(p, CMD)?; + if !s.doc.baked.get(&ts).is_some_and(|b| b.maps.contains_key(&map)) { + return Err(bad(CMD, format!("texture set {ts} has no {} map", map.label()))); + } + s.edit("Clear mesh map", |s| { + if let Some(b) = s.doc.baked.get_mut(&ts) { + b.maps.remove(&map); + } + s.doc.project.texture_set_mut(ts)?.baked.remove(&map); + Ok(()) + })?; + Ok(Value::Null) +} diff --git a/crates/engine/tests/painter_gaps.rs b/crates/engine/tests/painter_gaps.rs index 48f0b3de..f6fbfdc2 100644 --- a/crates/engine/tests/painter_gaps.rs +++ b/crates/engine/tests/painter_gaps.rs @@ -1,6 +1,6 @@ //! The filter library, geometry decals, cloning from the selected layer, placing saved smart -//! materials, anchors inside a content stack and instances across texture set resolutions, -//! through engine commands. +//! materials, anchors inside a content stack, instances across texture set resolutions and mesh +//! maps from images, through engine commands. use serde_json::{Value, json}; use texturecraft_engine::core::{Channel, EffectKind, Filter, LayerId, LayerKind, Projection}; @@ -375,3 +375,37 @@ fn geometry_mask_tool_toggles_the_clicked_part() { assert_eq!(s.doc.project.layer(layer).unwrap().geometry_mask, Some(vec!["Lid".to_string()])); assert!(execute(&mut s, "tool.click", &json!({"x": 1, "y": 1})).is_err(), "nothing under the point"); } + +#[test] +fn images_fill_mesh_map_slots() { + use texturecraft_engine::core::BakedMap; + let mut s = session(); + // Dark on the left, light on the right. + let ao = s.import_resource_bytes("ao.png", png(8, 8, |x, _| if x < 4 { [64, 64, 64, 255] } else { [192, 192, 192, 255] })).unwrap(); + let r = execute(&mut s, "textureSet.meshMap.set", &json!({"map": "ambient_occlusion", "image": ao})).unwrap(); + let res = s.doc.project.texture_sets[0].bake.resolution; + assert_eq!(r, json!({"map": "ambient_occlusion", "resolution": res})); + assert!(s.doc.project.texture_sets[0].baked.contains(&BakedMap::AmbientOcclusion)); + let sample = |s: &Session, m: BakedMap, x: u32| s.baked(0).unwrap().sample(m, x, 50, 100).unwrap(); + assert!((sample(&s, BakedMap::AmbientOcclusion, 10)[0] - 64.0 / 255.0).abs() < 1e-3, "raw file values, not linearized"); + assert!((sample(&s, BakedMap::AmbientOcclusion, 90)[0] - 192.0 / 255.0).abs() < 1e-3); + // A normal map is read in the project's normal format (DirectX: green flipped). + execute(&mut s, "textureSet.settings", &json!({"normalFormat": "directX"})).unwrap(); + let n = s.import_resource_bytes("n.png", png(2, 2, |_, _| [128, 64, 255, 255])).unwrap(); + execute(&mut s, "textureSet.meshMap.set", &json!({"map": "normal", "image": n})).unwrap(); + let v = sample(&s, BakedMap::Normal, 50); + assert!((v[1] - (1.0 - 64.0 / 255.0)).abs() < 1e-3 && (v[2] - 1.0).abs() < 1e-3, "{v:?}"); + // Clearing empties the slot (one undo step); bad params are errors. + execute(&mut s, "textureSet.meshMap.clear", &json!({"map": "ambient_occlusion"})).unwrap(); + assert!(s.baked(0).unwrap().sample(BakedMap::AmbientOcclusion, 0, 0, 100).is_none()); + assert!(!s.doc.project.texture_sets[0].baked.contains(&BakedMap::AmbientOcclusion)); + assert!(execute(&mut s, "textureSet.meshMap.clear", &json!({"map": "ambient_occlusion"})).is_err(), "already empty"); + execute(&mut s, "edit.undo", &Value::Null).unwrap(); + assert!(s.doc.project.texture_sets[0].baked.contains(&BakedMap::AmbientOcclusion)); + assert!(execute(&mut s, "textureSet.meshMap.set", &json!({"map": "nope", "image": ao})).is_err()); + assert!(execute(&mut s, "textureSet.meshMap.set", &json!({"map": "curvature", "image": "missing.png"})).is_err()); + assert!(execute(&mut s, "textureSet.meshMap.set", &json!({"map": "curvature"})).is_err()); + // The maps are saved with the project. + let back = Session::from_project_bytes(&s.to_project_bytes().unwrap()).unwrap(); + assert_eq!(back.doc.baked, s.doc.baked); +} diff --git a/crates/ui-egui/src/dock.rs b/crates/ui-egui/src/dock.rs index ba2ddcfd..0a3c947d 100644 --- a/crates/ui-egui/src/dock.rs +++ b/crates/ui-egui/src/dock.rs @@ -762,10 +762,10 @@ pub(crate) fn texture_set_settings(app: &mut TextureCraftApp, ui: &mut Ui) { } }); }); - let baked = app.session.doc.baked.get(&ts); + let images: Vec = app.session.doc.resources.keys().cloned().collect(); for m in BakedMap::ALL { - let present = baked.is_some_and(|b| b.maps.contains_key(&m)); - ui.horizontal(|ui| { + let present = app.session.doc.baked.get(&ts).is_some_and(|b| b.maps.contains_key(&m)); + let row = ui.horizontal(|ui| { let (r, _) = ui.allocate_exact_size(vec2(26.0, 26.0), Sense::hover()); ui.painter().rect_filled(r, 2.0, if present { mesh_map_color(m) } else { tk.button }); ui.vertical(|ui| { @@ -776,7 +776,36 @@ pub(crate) fn texture_set_settings(app: &mut TextureCraftApp, ui: &mut Ui) { .color(tk.text_dim), ); }); + // An image resource instead of a bake, or no map. + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + ui.menu_button(RichText::new(ic::DOTS_THREE).size(13.0), |ui| { + ui.label(caption(tr("Images"))); + for name in &images { + if ui.button(name).clicked() { + app.run("textureSet.meshMap.set", json!({"ts": ts, "map": m.id(), "image": name})); + ui.close(); + } + } + if ui.button(tr("Import...")).clicked() { + crate::menus::invoke(app, ui.ctx(), "resource.import"); + ui.close(); + } + ui.separator(); + if ui.add_enabled(present, egui::Button::new(tr("Clear"))).clicked() { + app.run("textureSet.meshMap.clear", json!({"ts": ts, "map": m.id()})); + ui.close(); + } + }); + }); }); + // A shelf image dropped on the row becomes this mesh map. + let resp = row.response.interact(Sense::hover()).on_hover_text(tr("Drop an image from the Assets panel here to use it as this mesh map")); + if resp.dnd_hover_payload::().is_some_and(|d| matches!(d.asset, Asset::Texture(_))) { + ui.painter().rect_stroke(resp.rect.shrink(1.0), 3.0, Stroke::new(2.0, tk.accent), egui::StrokeKind::Inside); + } + if let Some(Asset::Texture(name)) = dnd_release::(&resp).map(|d| d.asset.clone()) { + app.run("textureSet.meshMap.set", json!({"ts": ts, "map": m.id(), "image": name})); + } } }); } diff --git a/crates/ui-egui/src/i18n/ar.rs b/crates/ui-egui/src/i18n/ar.rs index 868cec7b..97de8552 100644 --- a/crates/ui-egui/src/i18n/ar.rs +++ b/crates/ui-egui/src/i18n/ar.rs @@ -263,6 +263,7 @@ pub const TABLE: &[(&str, &str)] = &[ "Drag the frame to move the decal, a corner to scale it, the round handle to turn it", "اسحب الإطار لتحريك الملصق، أو الزاوية لتغيير حجمه، أو المقبض الدائري لتدويره", ), + ("Drop an image from the Assets panel here to use it as this mesh map", "أفلت صورة من لوحة الأصول هنا لاستخدامها كخريطة المجسم هذه"), ("Dry streaks", "خطوط جافة"), ("Duplicate layer(s)", "تكرار الطبقة (الطبقات)"), ("Duplicate the selected template", "تكرار القالب المحدد"), diff --git a/crates/ui-egui/src/i18n/de.rs b/crates/ui-egui/src/i18n/de.rs index 7beb09bd..43c55e96 100644 --- a/crates/ui-egui/src/i18n/de.rs +++ b/crates/ui-egui/src/i18n/de.rs @@ -281,6 +281,10 @@ pub const TABLE: &[(&str, &str)] = &[ "Drag the frame to move the decal, a corner to scale it, the round handle to turn it", "Rahmen ziehen, um das Decal zu verschieben, eine Ecke zum Skalieren, den runden Griff zum Drehen", ), + ( + "Drop an image from the Assets panel here to use it as this mesh map", + "Ein Bild aus dem Assets-Panel hier ablegen, um es als diese Mesh-Map zu verwenden", + ), ("Dry streaks", "Trockene Schlieren"), ("Duplicate layer(s)", "Ebene(n) duplizieren"), ("Duplicate the selected template", "Ausgewählte Vorlage duplizieren"), diff --git a/crates/ui-egui/src/i18n/es.rs b/crates/ui-egui/src/i18n/es.rs index 30e7a968..971a85ea 100644 --- a/crates/ui-egui/src/i18n/es.rs +++ b/crates/ui-egui/src/i18n/es.rs @@ -278,6 +278,7 @@ pub const TABLE: &[(&str, &str)] = &[ "Drag the frame to move the decal, a corner to scale it, the round handle to turn it", "Arrastra el marco para mover la calcomanía, una esquina para escalarla y el tirador redondo para girarla", ), + ("Drop an image from the Assets panel here to use it as this mesh map", "Suelta aquí una imagen del panel Recursos para usarla como este mapa de malla"), ("Dry streaks", "Trazos secos"), ("Duplicate layer(s)", "Duplicar capa(s)"), ("Duplicate the selected template", "Duplicar la plantilla seleccionada"), diff --git a/crates/ui-egui/src/i18n/fr.rs b/crates/ui-egui/src/i18n/fr.rs index aee1fdc1..0ca8388c 100644 --- a/crates/ui-egui/src/i18n/fr.rs +++ b/crates/ui-egui/src/i18n/fr.rs @@ -281,6 +281,10 @@ pub const TABLE: &[(&str, &str)] = &[ "Drag the frame to move the decal, a corner to scale it, the round handle to turn it", "Faites glisser le cadre pour déplacer le décalque, un coin pour le mettre à l'échelle, la poignée ronde pour le faire pivoter", ), + ( + "Drop an image from the Assets panel here to use it as this mesh map", + "Déposez ici une image du panneau Ressources pour l'utiliser comme cette carte de maillage", + ), ("Dry streaks", "Traînées sèches"), ("Duplicate layer(s)", "Dupliquer le(s) calque(s)"), ("Duplicate the selected template", "Dupliquer le modèle sélectionné"), diff --git a/crates/ui-egui/src/i18n/it.rs b/crates/ui-egui/src/i18n/it.rs index 36077997..d39ce92a 100644 --- a/crates/ui-egui/src/i18n/it.rs +++ b/crates/ui-egui/src/i18n/it.rs @@ -284,6 +284,7 @@ pub const TABLE: &[(&str, &str)] = &[ "Drag the frame to move the decal, a corner to scale it, the round handle to turn it", "Trascina il riquadro per spostare la decal, un angolo per scalarla, la maniglia rotonda per ruotarla", ), + ("Drop an image from the Assets panel here to use it as this mesh map", "Rilascia qui un'immagine dal pannello Risorse per usarla come questa mappa mesh"), ("Dry streaks", "Striature secche"), ("Duplicate layer(s)", "Duplica livello/i"), ("Duplicate the selected template", "Duplica il modello selezionato"), diff --git a/crates/ui-egui/src/i18n/ja.rs b/crates/ui-egui/src/i18n/ja.rs index 5aa8f2e9..bfe6bff9 100644 --- a/crates/ui-egui/src/i18n/ja.rs +++ b/crates/ui-egui/src/i18n/ja.rs @@ -272,6 +272,7 @@ pub const TABLE: &[(&str, &str)] = &[ "Draws {name} of texture set \"{set}\". Edits to the source show in every instance.", "テクスチャセット「{set}」の {name} を描画します。ソースへの編集はすべてのインスタンスに反映されます。", ), + ("Drop an image from the Assets panel here to use it as this mesh map", "アセットパネルから画像をここにドロップすると、このメッシュマップとして使用します"), ("Dry streaks", "かすれ"), ("Duplicate layer(s)", "レイヤーを複製"), ("Duplicate the selected template", "選択中のテンプレートを複製"), diff --git a/crates/ui-egui/src/i18n/ko.rs b/crates/ui-egui/src/i18n/ko.rs index dbd5cfad..6218c9dd 100644 --- a/crates/ui-egui/src/i18n/ko.rs +++ b/crates/ui-egui/src/i18n/ko.rs @@ -269,6 +269,7 @@ pub const TABLE: &[(&str, &str)] = &[ "Draws {name} of texture set \"{set}\". Edits to the source show in every instance.", "텍스처 세트 \"{set}\"의 {name}을(를) 그립니다. 원본을 편집하면 모든 인스턴스에 반영됩니다.", ), + ("Drop an image from the Assets panel here to use it as this mesh map", "에셋 패널의 이미지를 여기에 놓으면 이 메시 맵으로 사용합니다"), ("Dry streaks", "마른 붓자국"), ("Duplicate layer(s)", "레이어 복제"), ("Duplicate the selected template", "선택한 템플릿을 복제합니다"), diff --git a/crates/ui-egui/src/i18n/pt_br.rs b/crates/ui-egui/src/i18n/pt_br.rs index 458edc29..5de39087 100644 --- a/crates/ui-egui/src/i18n/pt_br.rs +++ b/crates/ui-egui/src/i18n/pt_br.rs @@ -278,6 +278,7 @@ pub const TABLE: &[(&str, &str)] = &[ "Drag the frame to move the decal, a corner to scale it, the round handle to turn it", "Arraste o quadro para mover o decalque, um canto para redimensioná-lo e a alça redonda para girá-lo", ), + ("Drop an image from the Assets panel here to use it as this mesh map", "Solte aqui uma imagem do painel Recursos para usá-la como este mapa de malha"), ("Dry streaks", "Estrias secas"), ("Duplicate layer(s)", "Duplicar camada(s)"), ("Duplicate the selected template", "Duplicar o modelo selecionado"), diff --git a/crates/ui-egui/src/i18n/zh_hans.rs b/crates/ui-egui/src/i18n/zh_hans.rs index be279d5e..9c2052b1 100644 --- a/crates/ui-egui/src/i18n/zh_hans.rs +++ b/crates/ui-egui/src/i18n/zh_hans.rs @@ -239,6 +239,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Drag the frame to move the decal, a corner to scale it, the round handle to turn it", "拖动边框移动贴花,拖动角缩放,拖动圆形手柄旋转"), ("Drags the layer stack's values along the stroke into the selected layer.", "沿笔画将图层堆栈的值拖入所选图层。"), ("Draws {name} of texture set \"{set}\". Edits to the source show in every instance.", "绘制纹理集“{set}”的 {name}。对源的编辑会显示在每个实例中。"), + ("Drop an image from the Assets panel here to use it as this mesh map", "将资产面板中的图像拖放到此处,用作此网格贴图"), ("Dry streaks", "干笔条纹"), ("Duplicate layer(s)", "创建图层副本"), ("Duplicate the selected template", "创建所选模板的副本"), diff --git a/crates/ui-egui/tests/ui_snapshots.rs b/crates/ui-egui/tests/ui_snapshots.rs index 2a44f4ff..ee2d8676 100644 --- a/crates/ui-egui/tests/ui_snapshots.rs +++ b/crates/ui-egui/tests/ui_snapshots.rs @@ -62,6 +62,11 @@ fn window_snapshots() { h.state_mut().ui.windows.settings = true; save(&mut h, &dir, "window-settings"); h.state_mut().ui.windows.settings = false; + // The mesh map slots, each with its menu of images (a tall window shows them all). + h.state_mut().ui.dock.focus(Panel::TextureSetSettings); + h.set_size(egui::vec2(1600.0, 1800.0)); + save(&mut h, &dir, "panel-texture-set-settings"); + h.set_size(egui::vec2(1600.0, 960.0)); // A mask's levels effect over clouds: the histogram in Properties. let s = &mut h.state_mut().session; for (id, p) in [ diff --git a/docs/control-protocol.md b/docs/control-protocol.md index 86d84ea2..f8048861 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -129,7 +129,7 @@ takes a font family, not a path: it reads only the system's font folders. | `mesh_reimport` | `{path?, preserveStrokes?}` | Reimport the mesh from a file, or (no path) from the project's own copy; bridge mode supports only the latter | | `mesh_export` | `{path, format?}` | The mesh as obj, glb, usda, usdc or usdz below the write root (usda / usdc textures next to it) → `{path, textures?}` | | `bake_mesh_add` | `{path, cage?}` | Add a high-definition mesh for baking, or set the cage → `{name, meshes}` | -| `resource_import` | `{path}` | Image resource (png, jpg, tga, tif, bmp, webp, exr, hdr) → its name, for `layer.add.image` / `tool.stencil` | +| `resource_import` | `{path}` | Image resource (png, jpg, tga, tif, bmp, webp, exr, hdr) → its name, for `layer.add.image` / `tool.stencil`, or as a mesh map instead of baking it: `textureSet.meshMap.set {ts?, map, image}` (`textureSet.meshMap.clear {ts?, map}` empties the slot) | | `material_save` | `{path, layer?, name?}` | A layer or folder as a `.tcmat` smart material below the write root | | `material_load` | `{path}` | Add a `.tcmat` smart material above the selection | | `textures_export` | `{dir, preset?, ts?, format?, padding?, size?}` | Writes files below the write root | diff --git a/docs/features.md b/docs/features.md index 5043fcac..7b858cfe 100644 --- a/docs/features.md +++ b/docs/features.md @@ -79,7 +79,9 @@ Everything TextureCraft does today, by area. What's still missing is in [`ROADMA - **Bake mesh maps** on the GPU (ray traced, about 12× the CPU path) or on every CPU core: ambient occlusion, curvature, thickness, world-space normal, position, ID, bent normals, opacity, color and direction maps, and normal and height maps from high-poly meshes, with a cage, ray distances - and matching by mesh name. + and matching by mesh name. Or **use your own images** as mesh maps (baked in another app, or + edited): drop one from the Assets panel on a slot of the Texture Set Settings, or pick it from + the slot's menu. - **Export presets** for glTF PBR Metal Roughness, Unreal Engine (packed), Unity HDRP (mask map), Unity Standard, Blender (Principled BSDF), Godot 4 (ORM), OpenPBR (with the coat, fuzz, anisotropy, transmission and subsurface maps), separate maps, mesh maps and document channels, in