From 92e92ff779d888e66ff9fad07fdd0344698657ca Mon Sep 17 00:00:00 2001 From: bflatastic Date: Mon, 2 Nov 2026 18:20:21 +0700 Subject: [PATCH] OBJ export writes an MTL material library with each material's maps --- README.md | 2 +- ROADMAP.md | 4 +-- crates/automation/src/headless.rs | 2 +- crates/automation/src/server.rs | 4 +-- crates/engine/src/file_cmds.rs | 48 +++++++++++++++++++------ crates/engine/tests/udim.rs | 4 +++ crates/formats/src/lib.rs | 2 +- crates/formats/src/mesh_export.rs | 50 ++++++++++++++++++++++++--- crates/formats/src/mesh_export/usd.rs | 25 ++++++++++---- crates/ui-egui/src/i18n/ar.rs | 1 + crates/ui-egui/src/i18n/de.rs | 1 + crates/ui-egui/src/i18n/es.rs | 1 + crates/ui-egui/src/i18n/fr.rs | 1 + crates/ui-egui/src/i18n/it.rs | 1 + crates/ui-egui/src/i18n/ja.rs | 1 + crates/ui-egui/src/i18n/ko.rs | 1 + crates/ui-egui/src/i18n/pt_br.rs | 1 + crates/ui-egui/src/i18n/zh_hans.rs | 1 + crates/ui-egui/src/windows.rs | 2 +- docs/control-protocol.md | 2 +- docs/features.md | 4 ++- 21 files changed, 127 insertions(+), 31 deletions(-) diff --git a/README.md b/README.md index e37278a5..58f29227 100644 --- a/README.md +++ b/README.md @@ -125,7 +125,7 @@ traced on the GPU by `texturecraft-cli render`. - **Robust.** No panics in shipped code, every command tested with hostile input, unlimited undo from copy-on-write snapshots, and lossless `.tcraft` projects. - **Open.** glTF/GLB, FBX, COLLADA, USD, Alembic, OBJ, PLY and STL in; PNG, JPEG, TGA, TIFF, BMP, - WEBP, EXR and HDR textures out at 8, 16 or 32 bits, with UDIM tiles; OBJ, textured GLB and USD + WEBP, EXR and HDR textures out at 8, 16 or 32 bits, with UDIM tiles; textured OBJ, GLB and USD mesh export. Every material, environment, brush alpha and built-in mesh is procedural. - **Works with MaterialCraft.** Node-based materials from [MaterialCraft](https://github.com/storytold/materialcraft) (`.mcmat`, sent straight to the diff --git a/ROADMAP.md b/ROADMAP.md index 4e9bc96e..80f53f93 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -11,7 +11,7 @@ end to end today (engine + UI + automation + tests), not what is planned. | Area | Weight | Done | What works | Main gaps | |---|---:|---:|---|---| -| Project and files | 8 | 95% | New project from glTF/GLB, FBX (binary and ASCII, 6.x and 7.x), COLLADA, **USD (usda, usdc, usdz)**, **Alembic (Ogawa)**, OBJ, PLY, STL or built-in meshes (auto-unwrap when UVs are missing; a `.gltf`'s buffers and images and a loose USD layer's textures are read from its folder and kept in the project), **project templates** (built-in and saved from a project), `.tcraft` open/save/save as/save a copy, autosave, **asks to save unsaved changes** before quitting or replacing the project (in the browser too, and before the tab closes), recent files, drag and drop, reimport mesh **with strokes preserved on the surface**, **MaterialX import** (`file.importMaterialX`: a `.mtlx` material with `open_pbr_surface`, `standard_surface` or `gltf_pbr` becomes one fill layer with its textures and values), image resources, remove unused resources, OBJ, textured GLB and **USD** mesh export, browser open/save/download | HDF5 Alembic; Alembic animation (first sample only) | +| Project and files | 8 | 95% | New project from glTF/GLB, FBX (binary and ASCII, 6.x and 7.x), COLLADA, **USD (usda, usdc, usdz)**, **Alembic (Ogawa)**, OBJ, PLY, STL or built-in meshes (auto-unwrap when UVs are missing; a `.gltf`'s buffers and images and a loose USD layer's textures are read from its folder and kept in the project), **project templates** (built-in and saved from a project), `.tcraft` open/save/save as/save a copy, autosave, **asks to save unsaved changes** before quitting or replacing the project (in the browser too, and before the tab closes), recent files, drag and drop, reimport mesh **with strokes preserved on the surface**, **MaterialX import** (`file.importMaterialX`: a `.mtlx` material with `open_pbr_surface`, `standard_surface` or `gltf_pbr` becomes one fill layer with its textures and values), image resources, remove unused resources, textured OBJ (MTL), GLB and **USD** mesh export, browser open/save/download | HDF5 Alembic; Alembic animation (first sample only) | | Texture sets | 6 | 95% | One set per material, **UDIM / UV tiles** (auto-detected or switched on later with resampling, **a resolution per tile**, one texture per tile at its own size, `$udim` export), list with visibility (show or hide all, invert, **focus** on one set), sizes 128–8192 with resampling, add/remove channels (19 channel types incl. coat, sheen, anisotropy and scattering), height strength, normal format | Filter radii and height slopes of a tile smaller than its atlas block follow the block; mesh maps from images need a set without UV tiles | | Layer stack | 16 | 98% | Paint, fill, folder and **instance** layers; 32 per-channel blend modes and opacities; white/black/painted masks with **mask with height**; generator, fill, levels (with a histogram of its input), invert/threshold, color selection, compare, blur, sharpen and HSL effects on masks and layer content; anchor points; effects **dragged to reorder**, duplicated, and **copied, cut and pasted** across layers, masks and sets (Ctrl+C, Ctrl+X, Ctrl+V, Ctrl+D and Delete act on a selected effect); smart masks; mask view (Alt+click); Alt+click a material channel to keep it alone; duplicate, group, drag to reorder, rename, color tags, copy/cut/paste (also as instance) across sets, flatten, instantiate across sets, save layers as smart materials; **30 library filters** (adjustments incl. histogram scan, range and shift, blur/sharpen/high pass, bevel, glow, edge detect, warps, mosaic, baked lighting, material finishes); **geometry masks** (a layer on chosen mesh parts) | A few niche filters of the reference app's catalog | | Painting tools | 14 | 91% | Paint, eraser, projection with image stencils, polygon fill, **path** and **lasso fill**, smudge, clone, color picker, quick mask, Shift+click lines with preview, 2D view painting; size, flow, stroke opacity, spacing, hardness, angle, follow path, jitters, alignment, angle fade, backface culling, lazy mouse, **Ctrl+drag in a view for size, hardness, flow and angle**, X/Y/Z mirror and **radial symmetry**, pen pressure, procedural and image alphas, **text** in any installed font (as an alpha or a decal), **particle brush** | Pen tilt (not exposed by the windowing layer) | @@ -19,7 +19,7 @@ end to end today (engine + UI + automation + tests), not what is planned. | Baking | 10 | 100% | AO, curvature (also from the normal map), thickness, world normal, position, ID, normal, height, **bent normals, opacity, color map and world-space direction**; **high-poly meshes**, cage, frontal/rear distances, average normals, **skew correction** (`bake.skew.set`, painted in the 2D view with `bake.skew.paint` and saved in the project: a greyscale map over the atlas that turns the transfer rays onto the base normal, with hard-edge protection), **match by mesh name**; per-texture-set selection, common and per-map parameters, progress and cancel; **Auto-rebake** (`bake.autoRebake`: one map bakes itself again in the background when its bake settings, the low poly, the high polys or the skew map change); **mesh maps from images** (baked elsewhere or edited) dropped on a slot; high-poly base color textures embedded or in files beside a `.gltf`, FBX or USD layer | — | | Viewport and display | 12 | 95% | PBR with image-based lighting, 6 procedural environments or imported HDR/EXR panoramas with exposure, rotation, blur, opacity, ACES/linear tone mapping, HDR pipeline with bloom, vignette, sharpen and grain, key-light shadows, 4× MSAA plus idle temporal accumulation, the baked normal map under the painted normal, channel / mesh-map / mask / UV checker views, 3D and 2D wireframes of the mesh's own polygons, brush cursor, axis gizmos, subsurface scattering blur, **depth of field**, saved cameras and cameras from glTF, FBX, COLLADA and USD files, displacement (also in shadows and the path tracers), **path-traced Rendering mode** (F10, on the GPU or the CPU) with environment importance sampling and an edge-aware **denoiser**; picks a discrete GPU on multi-GPU machines (`--gpu`, `WGPU_ADAPTER_NAME`, `WGPU_POWER_PREF`), and display textures are made on demand so a mesh with many materials imports on a small GPU | Hardware ray tracing | | Shader | 6 | 100% | Metallic/roughness and specular/glossiness PBR, **clear coat, sheen, anisotropy and subsurface scattering** (viewport and path tracer), height-to-normal, painted normals, parallax occlusion, emissive, opacity (dithered), AO intensity | — | -| Export | 8 | 92% | 10 presets (incl. Godot 4 and **OpenPBR** with every shading lobe) plus **user output templates** (per-channel packing, converted maps, JSON import/export), PNG/JPEG/TGA/TIFF/BMP/WEBP/EXR/HDR, 8/16/32-bit, padding modes, size override, OpenGL/DirectX normals, **colour space** of the colour maps (sRGB, Linear Rec.709, ACEScg, ACES2065-1; data maps never converted; the chosen space is recorded in the file as an ICC profile in PNG, JPEG, TIFF and WebP and as chromaticities in EXR), `$udim` tiles, **MaterialX** (`file.exportTextures` with `materialX`: a `.mtlx` OpenPBR material per set, `` aware), OBJ, textured GLB (with clearcoat/sheen) and USD (with clear coat) mesh export, zip download in the browser | Sheen and anisotropy in USD (UsdPreviewSurface has no inputs for them; GLB and OpenPBR maps carry them) | +| Export | 8 | 92% | 10 presets (incl. Godot 4 and **OpenPBR** with every shading lobe) plus **user output templates** (per-channel packing, converted maps, JSON import/export), PNG/JPEG/TGA/TIFF/BMP/WEBP/EXR/HDR, 8/16/32-bit, padding modes, size override, OpenGL/DirectX normals, **colour space** of the colour maps (sRGB, Linear Rec.709, ACEScg, ACES2065-1; data maps never converted; the chosen space is recorded in the file as an ICC profile in PNG, JPEG, TIFF and WebP and as chromaticities in EXR), `$udim` tiles, **MaterialX** (`file.exportTextures` with `materialX`: a `.mtlx` OpenPBR material per set, `` aware), OBJ with MTL and maps, textured GLB (with clearcoat/sheen) and USD (with clear coat) mesh export, zip download in the browser | Sheen and anisotropy in USD (UsdPreviewSurface has no inputs for them; GLB and OpenPBR maps carry them) | | UI and UX | 8 | 97% | Painter-style layout with **dockable, tabbed, floating panels**, menus, tool shelf, tool bar, asset shelf, texture set list, layer stack with context menu, properties, display/shader/history/log panels, export dialog, new project dialog, bake mode, rendering mode, settings (interface scale, autosave, viewport texture resolution, system title bar), **own title bar** with the app icon and window buttons (Windows, GNOME; integrated with the macOS traffic lights), saved UI layouts, a **History** panel that jumps to any step (back or forward), a **start window** (new, open, recent projects), **shortcut editor** with conflict detection, tooltips with shortcuts, a compact color picker (saturation/value square, hue strip, copyable RGB); all menu items live ([docs/parity.md](docs/parity.md)); **10 UI languages** with CJK and Arabic fonts ([docs/localization-parity.md](docs/localization-parity.md)); closed panels reopen where they were; frame-budgeted compositing and uploads keep 8K sets responsive | Native-speaker review of the translations | | Platforms | 4 | 76% | Windows, macOS (universal, signed and notarized), Linux (AppImage, deb, rpm, tar.gz, Flatpak), FreeBSD and web release workflows | First real release run; web build polish | | **Total** | **100** | **≈ 94%** | | | diff --git a/crates/automation/src/headless.rs b/crates/automation/src/headless.rs index e907957d..87d58648 100644 --- a/crates/automation/src/headless.rs +++ b/crates/automation/src/headless.rs @@ -201,7 +201,7 @@ impl Headless { } /// Export the working mesh to `path` (obj, glb, usda, usdc or usdz, from `format` or the - /// extension); usda and usdc write their textures next to it. + /// extension); obj writes its .mtl and textures, usda and usdc their textures, next to it. pub fn export_mesh(&mut self, path: &str, format: Option<&str>) -> Result { let out = self.session.mesh_export(path, format)?; let dir = Path::new(&out.path).parent().and_then(|d| d.to_str()).filter(|d| !d.is_empty()).unwrap_or("."); diff --git a/crates/automation/src/server.rs b/crates/automation/src/server.rs index ae0e8fe2..0bd6f4df 100644 --- a/crates/automation/src/server.rs +++ b/crates/automation/src/server.rs @@ -133,8 +133,8 @@ pub struct ReimportParams { pub struct MeshExportParams { /// Output file relative to the write root; the format's extension is appended if missing. pub path: String, - /// obj, glb (textures embedded), usda, usdc (textures written next to it) or usdz (textures - /// packaged); default: from the extension, else obj. + /// obj (MTL and textures written next to it), glb (textures embedded), usda, usdc (textures + /// written next to it) or usdz (textures packaged); default: from the extension, else obj. #[serde(default, skip_serializing_if = "Option::is_none")] pub format: Option, } diff --git a/crates/engine/src/file_cmds.rs b/crates/engine/src/file_cmds.rs index a33c283a..37679bc3 100644 --- a/crates/engine/src/file_cmds.rs +++ b/crates/engine/src/file_cmds.rs @@ -51,7 +51,7 @@ pub fn specs() -> Vec { "Export Mesh...", ["File"], None, - "{path: .obj, .glb, .usda, .usdc or .usdz file, format?: obj|glb|usda|usdc|usdz (default: from the extension, else obj); usda/usdc write their textures next to the file} → {path, textures?}", + "{path: .obj, .glb, .usda, .usdc or .usdz file, format?: obj|glb|usda|usdc|usdz (default: from the extension, else obj); obj writes its .mtl and textures, usda/usdc their textures, next to the file} → {path, textures?}", always, export_mesh ), @@ -97,11 +97,20 @@ impl Session { texturecraft_formats::obj_bytes(&self.source_mesh(), &self.doc.project.name) } + /// [`Session::mesh_obj_bytes`] with an MTL material library and each material's maps (like + /// [`Session::mesh_usd`]'s), to write next to it. + pub fn mesh_obj_with_mtl(&mut self) -> Result<(Vec, texturecraft_formats::NamedFiles)> { + // shortcut: UV-tiled sets get no maps (the OBJ keeps the mesh's UDIM UVs and an MTL map is + // one image); their tiles export through Export textures with `$udim` names. + let files = self.material_files(texturecraft_formats::usd_export_options(), false)?; + Ok(texturecraft_formats::obj_with_mtl(&self.source_mesh(), &self.doc.project.name, &files)) + } + /// The working mesh as binary glTF with each material's textures (from its texture set's /// composite, through the texture export pipeline) embedded. glTF has no UV tiles: a /// UV-tiled set embeds its tile atlas, with the mesh's UVs in atlas space. pub fn mesh_glb_bytes(&mut self) -> Result> { - let files = self.material_files(texturecraft_formats::glb_export_options())?; + let files = self.material_files(texturecraft_formats::glb_export_options(), true)?; let textures: Vec<_> = files.into_iter().map(texturecraft_formats::GlbTextures::from_files).collect(); texturecraft_formats::glb_bytes(&self.mesh, &self.doc.project.name, &textures).map_err(fe) } @@ -109,17 +118,18 @@ impl Session { /// The working mesh as USD with a UsdPreviewSurface per material (textures like /// [`Session::mesh_glb_bytes`]): usdz packages them, usda / usdc list them to write alongside. pub fn mesh_usd(&mut self, format: texturecraft_formats::UsdFormat) -> Result { - let files = self.material_files(texturecraft_formats::usd_export_options())?; + let files = self.material_files(texturecraft_formats::usd_export_options(), true)?; texturecraft_formats::usd_bytes(&self.mesh, &self.doc.project.name, &files, format).map_err(fe) } - /// Each material's texture set rendered with `opts` (as a tile atlas for UV-tiled sets). - fn material_files(&mut self, opts: ExportOptions) -> Result>> { + /// Each material's texture set rendered with `opts` (as a tile atlas for UV-tiled sets, or + /// nothing for them without `tiled`). + fn material_files(&mut self, opts: ExportOptions, tiled: bool) -> Result>> { let opts = ExportOptions { atlas: true, ..opts }; (0..self.mesh.materials.len()) .map(|m| match self.doc.project.texture_sets.iter().position(|t| t.material == m) { - Some(ts) => self.export_files(&[ts], &opts), - None => Ok(Vec::new()), + Some(ts) if tiled || self.doc.project.texture_sets.get(ts).is_some_and(|t| t.tile_grid().is_none()) => self.export_files(&[ts], &opts), + _ => Ok(Vec::new()), }) .collect() } @@ -524,8 +534,8 @@ fn export_mesh(s: &mut Session, p: &Value) -> Result { /// The mesh formats `file.exportMesh` writes. pub const MESH_EXPORT_FORMATS: [&str; 5] = ["obj", "glb", "usda", "usdc", "usdz"]; -/// A mesh export: the mesh file's path (with its extension) and bytes, and (usda, usdc) the -/// textures it references, by file name, to write next to it. +/// A mesh export: the mesh file's path (with its extension) and bytes, and (obj, usda, usdc) the +/// files it references (textures, an OBJ's MTL), by file name, to write next to it. pub struct MeshExport { pub path: String, pub bytes: Vec, @@ -556,7 +566,7 @@ impl Session { let usd = self.mesh_usd(format)?; (usd.bytes, usd.textures) } - _ => (self.mesh_obj_bytes(), Vec::new()), + _ => self.mesh_obj_with_mtl()?, }; Ok(MeshExport { path, bytes, textures }) } @@ -601,6 +611,24 @@ mod tests { let base = dir.join("ball").display().to_string(); let obj = crate::execute(&mut s, "file.exportMesh", &json!({ "path": base })).unwrap(); assert!(obj["path"].as_str().unwrap().ends_with("ball.obj")); + // The OBJ names its MTL, which names every material and its maps, all written beside it. + let text = std::fs::read_to_string(obj["path"].as_str().unwrap()).unwrap(); + assert!(text.lines().any(|l| l == "mtllib t.mtl"), "{}", &text[..120]); + let files: Vec<_> = obj["textures"].as_array().unwrap().iter().map(|f| std::path::PathBuf::from(f.as_str().unwrap())).collect(); + assert!(files.iter().all(|f| f.is_file())); + let mtl = std::fs::read_to_string(&files[0]).unwrap(); + assert!(files[0].ends_with("t.mtl")); + for m in &s.mesh.materials { + assert!(mtl.contains(&format!("newmtl {m}")) && text.contains(&format!("usemtl {m}")), "{m}"); + } + for key in ["map_Kd", "map_Pr", "map_Pm", "norm"] { + assert_eq!(mtl.lines().filter(|l| l.starts_with(&format!("{key} "))).count(), s.mesh.materials.len(), "{key}"); + } + for f in &files[1..] { + assert!(mtl.contains(f.file_name().unwrap().to_str().unwrap()), "{f:?} is used"); + } + let back = texturecraft_formats::import_mesh_bytes("ball.obj", text.as_bytes()).unwrap(); + assert_eq!(back.mesh.triangle_count(), s.mesh.triangle_count()); let glb = crate::execute(&mut s, "file.exportMesh", &json!({ "path": base, "format": "glb" })).unwrap(); let bytes = std::fs::read(glb["path"].as_str().unwrap()).unwrap(); let back = texturecraft_formats::import_mesh_bytes("ball.glb", &bytes).unwrap(); diff --git a/crates/engine/tests/udim.rs b/crates/engine/tests/udim.rs index 54faa9c7..e50f0156 100644 --- a/crates/engine/tests/udim.rs +++ b/crates/engine/tests/udim.rs @@ -113,6 +113,10 @@ fn projects_round_trip_and_meshes_export_their_own_uvs() { let obj = String::from_utf8(s.mesh_obj_bytes()).unwrap(); let max_u = obj.lines().filter_map(|l| l.strip_prefix("vt ")).filter_map(|l| l.split_whitespace().next()?.parse::().ok()).fold(0.0f32, f32::max); assert!((max_u - 2.0).abs() < 1e-4, "{max_u}"); + // With its MTL: the same UVs, and no maps for the UV-tiled set (one image cannot hold them). + let (with_mtl, files) = s.mesh_obj_with_mtl().unwrap(); + assert!(String::from_utf8(with_mtl).unwrap().ends_with(obj.split_once("\no ").unwrap().1)); + assert_eq!(files.len(), 1, "the MTL alone"); } #[test] diff --git a/crates/formats/src/lib.rs b/crates/formats/src/lib.rs index 0facc486..31a6daea 100644 --- a/crates/formats/src/lib.rs +++ b/crates/formats/src/lib.rs @@ -42,7 +42,7 @@ pub use export::{ Dest, ExportInput, ExportOptions, ExportPreset, ExportedFile, FileFormat, MapSpec, Padding, PlannedFile, SourceRef, VirtualMap, list_outputs, render_maps, }; pub use image_res::{DecodedImage, coverage_png, decode_image, decode_image_within}; -pub use mesh_export::{GlbTextures, UsdExport, UsdFormat, glb_bytes, glb_export_options, obj_bytes, usd_bytes, usd_export_options}; +pub use mesh_export::{GlbTextures, NamedFiles, UsdExport, UsdFormat, glb_bytes, glb_export_options, obj_bytes, obj_with_mtl, usd_bytes, usd_export_options}; pub use mesh_import::{HighPolyMesh, ImportedMesh, MeshFile, MeshReport, import_high_poly_bytes, import_mesh_bytes, mesh_report, self_contained_mesh}; #[cfg(not(target_arch = "wasm32"))] pub use presets::load_preset; diff --git a/crates/formats/src/mesh_export.rs b/crates/formats/src/mesh_export.rs index b3fbdf82..a8547bb8 100644 --- a/crates/formats/src/mesh_export.rs +++ b/crates/formats/src/mesh_export.rs @@ -1,5 +1,5 @@ //! Mesh export of the working mesh: Wavefront OBJ (positions, UVs, normals, one group per -//! submesh), binary glTF (one primitive per submesh, a metallic-roughness material per +//! submesh; with an MTL material library and its maps, or alone), binary glTF (one primitive per submesh, a metallic-roughness material per //! material with its textures embedded) and USD (usda / usdc / usdz, see [`usd`]). pub(crate) mod usd; @@ -13,15 +13,57 @@ use texturecraft_core::{Channel, NormalFormat}; use texturecraft_geom::glam::Vec3; use texturecraft_geom::{Mesh, SubMesh}; +use crate::export::sanitize_file_stem; use crate::presets::{GLTF_BASE_COLOR, GLTF_CLEARCOAT, GLTF_EMISSIVE, GLTF_NORMAL, GLTF_ORM, GLTF_SHEEN, gltf_pbr_maps}; use crate::{ExportOptions, ExportPreset, ExportedFile, FileFormat, FormatError, Result}; -pub use usd::{UsdExport, UsdFormat, usd_bytes, usd_export_options}; +pub use usd::{NamedFiles, UsdExport, UsdFormat, usd_bytes, usd_export_options}; /// The mesh as OBJ text (UV v flipped back to OBJ's bottom-up convention). pub fn obj_bytes(mesh: &Mesh, name: &str) -> Vec { + obj_text(mesh, name, None).into_bytes() +} + +/// The mesh as OBJ with a material library: the OBJ (naming `.mtl`) and the files to write +/// next to it, the MTL first, then each material's maps (`textures[m]`, rendered with +/// [`usd_export_options`], named like USD's). Roughness, metallic, normal and coat maps use the +/// MTL PBR extension's keys. +pub fn obj_with_mtl(mesh: &Mesh, name: &str, textures: &[Vec]) -> (Vec, NamedFiles) { + let stem = sanitize_file_stem(name); + let (maps, mut files) = usd::material_maps(mesh, &stem, textures); + let mut mtl = format!("# {name}, exported by TextureCraft\n"); + for (material, maps) in mesh.materials.iter().zip(&maps) { + let _ = writeln!(mtl, "\nnewmtl {}\nKd 1 1 1", token(material)); + for (slot, file) in maps { + let keys: &[&str] = match usd::SLOTS.get(*slot).map_or("", |s| s.0) { + "BaseColor" => &["map_Kd"], + "Roughness" => &["map_Pr"], + "Metallic" => &["map_Pm"], + // `norm` is the PBR extension's key; many tools read a normal map from `map_Bump`. + "Normal" => &["norm", "map_Bump"], + // The emissive map scales `Ke`. + "Emissive" => &["Ke 1 1 1\nmap_Ke"], + "Opacity" => &["map_d"], + "Clearcoat" => &["map_Pc"], + "ClearcoatRoughness" => &["map_Pcr"], + _ => &[], + }; + for key in keys { + let _ = writeln!(mtl, "{key} {file}"); + } + } + } + files.insert(0, (format!("{stem}.mtl"), mtl.into_bytes())); + (obj_text(mesh, name, Some(&format!("{stem}.mtl"))).into_bytes(), files) +} + +fn obj_text(mesh: &Mesh, name: &str, mtllib: Option<&str>) -> String { let mut s = String::with_capacity(mesh.positions.len() * 96 + mesh.indices.len() * 12); - let _ = writeln!(s, "# {name}, exported by TextureCraft\no {}", token(name)); + let _ = writeln!(s, "# {name}, exported by TextureCraft"); + if let Some(lib) = mtllib { + let _ = writeln!(s, "mtllib {lib}"); + } + let _ = writeln!(s, "o {}", token(name)); for p in &mesh.positions { let _ = writeln!(s, "v {} {} {}", p.x, p.y, p.z); } @@ -55,7 +97,7 @@ pub fn obj_bytes(mesh: &Mesh, name: &str) -> Vec { s.push('\n'); } } - s.into_bytes() + s } /// The submeshes, or one covering the whole mesh when it has none. diff --git a/crates/formats/src/mesh_export/usd.rs b/crates/formats/src/mesh_export/usd.rs index 1e14039e..61f9527a 100644 --- a/crates/formats/src/mesh_export/usd.rs +++ b/crates/formats/src/mesh_export/usd.rs @@ -46,7 +46,7 @@ pub struct UsdExport { /// A UsdPreviewSurface input fed by a texture: (file stem, input, input type, texture output, /// sRGB). -const SLOTS: [(&str, &str, &str, &str, bool); 8] = [ +pub(crate) const SLOTS: [(&str, &str, &str, &str, bool); 8] = [ ("BaseColor", "diffuseColor", "color3f", "rgb", true), ("Roughness", "roughness", "float", "r", false), ("Metallic", "metallic", "float", "r", false), @@ -293,6 +293,22 @@ fn material(path: &str, id: &str, files: &[(usize, String)]) -> UsdPrim { /// to the layer; usdz embeds them. pub fn usd_bytes(mesh: &Mesh, name: &str, textures: &[Vec], format: UsdFormat) -> Result { let stem = sanitize_file_stem(name); + let (names, files) = material_maps(mesh, &stem, textures); + let layer = scene(mesh, name, &names)?; + Ok(match format { + UsdFormat::Usda => UsdExport { bytes: usda(&layer).into_bytes(), textures: files }, + UsdFormat::Usdc => UsdExport { bytes: super::usdc::write(&layer)?, textures: files }, + UsdFormat::Usdz => UsdExport { bytes: usdz(&format!("{stem}.usdc"), &super::usdc::write(&layer)?, &files)?, textures: Vec::new() }, + }) +} + +/// Files by name, with their bytes. +pub type NamedFiles = Vec<(String, Vec)>; + +/// The maps of each material worth writing (`textures[m]`, rendered with +/// [`usd_export_options`]): per material its [`SLOTS`] indices and file names +/// (`__.png`), and the files with their bytes. +pub(crate) fn material_maps(mesh: &Mesh, stem: &str, textures: &[Vec]) -> (Vec>, NamedFiles) { let mut files = Vec::new(); let mut names = Vec::with_capacity(mesh.materials.len()); for (m, material) in mesh.materials.iter().enumerate() { @@ -317,12 +333,7 @@ pub fn usd_bytes(mesh: &Mesh, name: &str, textures: &[Vec], format } names.push(slots); } - let layer = scene(mesh, name, &names)?; - Ok(match format { - UsdFormat::Usda => UsdExport { bytes: usda(&layer).into_bytes(), textures: files }, - UsdFormat::Usdc => UsdExport { bytes: super::usdc::write(&layer)?, textures: files }, - UsdFormat::Usdz => UsdExport { bytes: usdz(&format!("{stem}.usdc"), &super::usdc::write(&layer)?, &files)?, textures: Vec::new() }, - }) + (names, files) } /// A usdz package: the layer first, every entry stored uncompressed at a 64-byte aligned offset. diff --git a/crates/ui-egui/src/i18n/ar.rs b/crates/ui-egui/src/i18n/ar.rs index a42c15ae..e3ac030b 100644 --- a/crates/ui-egui/src/i18n/ar.rs +++ b/crates/ui-egui/src/i18n/ar.rs @@ -866,6 +866,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Voronoi", "فورونوي (Voronoi)"), ("Warp", "التواء (Warp)"), ("Warp Directional", "التواء اتجاهي"), + ("Wavefront OBJ with MTL, textures alongside", "Wavefront OBJ مع MTL، والخامات بجانبه"), ( "WebGPU isn't available in this browser, so TextureCraft runs on WebGL2: Rendering mode path traces on the CPU (slower) and large texture sets show at reduced resolution. A current Chrome, Edge or Safari has WebGPU.", "WebGPU غير متاح في هذا المتصفح، لذا يعمل TextureCraft على WebGL2: نمط التصيير يتتبع المسار على المعالج (أبطأ) ومجموعات الخامات الكبيرة تظهر بدقة مخفضة. يتوفر WebGPU في الإصدارات الحديثة من Chrome وEdge وSafari.", diff --git a/crates/ui-egui/src/i18n/de.rs b/crates/ui-egui/src/i18n/de.rs index d717d4fb..5ed3631c 100644 --- a/crates/ui-egui/src/i18n/de.rs +++ b/crates/ui-egui/src/i18n/de.rs @@ -911,6 +911,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Voronoi", "Voronoi"), ("Warp", "Verkrümmen"), ("Warp Directional", "Richtungsverkrümmung"), + ("Wavefront OBJ with MTL, textures alongside", "Wavefront OBJ mit MTL, Texturen daneben"), ( "WebGPU isn't available in this browser, so TextureCraft runs on WebGL2: Rendering mode path traces on the CPU (slower) and large texture sets show at reduced resolution. A current Chrome, Edge or Safari has WebGPU.", "WebGPU ist in diesem Browser nicht verfügbar, daher läuft TextureCraft mit WebGL2: Der Rendering-Modus berechnet Path Tracing auf der CPU (langsamer), und große Texturesets werden in reduzierter Auflösung angezeigt. Aktuelle Versionen von Chrome, Edge und Safari unterstützen WebGPU.", diff --git a/crates/ui-egui/src/i18n/es.rs b/crates/ui-egui/src/i18n/es.rs index ae7fca54..fa056c56 100644 --- a/crates/ui-egui/src/i18n/es.rs +++ b/crates/ui-egui/src/i18n/es.rs @@ -899,6 +899,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Voronoi", "Voronoi"), ("Warp", "Deformar"), ("Warp Directional", "Deformación direccional"), + ("Wavefront OBJ with MTL, textures alongside", "Wavefront OBJ con MTL, texturas al lado"), ( "WebGPU isn't available in this browser, so TextureCraft runs on WebGL2: Rendering mode path traces on the CPU (slower) and large texture sets show at reduced resolution. A current Chrome, Edge or Safari has WebGPU.", "WebGPU no está disponible en este navegador, así que TextureCraft usa WebGL2: el modo Renderizado calcula el trazado de trayectorias en la CPU (más lento) y los conjuntos de texturas grandes se muestran a resolución reducida. Las versiones actuales de Chrome, Edge y Safari admiten WebGPU.", diff --git a/crates/ui-egui/src/i18n/fr.rs b/crates/ui-egui/src/i18n/fr.rs index b73b79f2..93dc2cd9 100644 --- a/crates/ui-egui/src/i18n/fr.rs +++ b/crates/ui-egui/src/i18n/fr.rs @@ -920,6 +920,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Voronoi", "Voronoï"), ("Warp", "Distorsion"), ("Warp Directional", "Distorsion directionnelle"), + ("Wavefront OBJ with MTL, textures alongside", "Wavefront OBJ avec MTL, textures à côté"), ( "WebGPU isn't available in this browser, so TextureCraft runs on WebGL2: Rendering mode path traces on the CPU (slower) and large texture sets show at reduced resolution. A current Chrome, Edge or Safari has WebGPU.", "WebGPU n'est pas disponible dans ce navigateur : TextureCraft utilise WebGL2. Le mode Rendu calcule le tracé de chemins sur le CPU (plus lent) et les grands ensembles de textures s'affichent en résolution réduite. Une version récente de Chrome, Edge ou Safari prend en charge WebGPU.", diff --git a/crates/ui-egui/src/i18n/it.rs b/crates/ui-egui/src/i18n/it.rs index 0fb284f7..7abd04ac 100644 --- a/crates/ui-egui/src/i18n/it.rs +++ b/crates/ui-egui/src/i18n/it.rs @@ -908,6 +908,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Voronoi", "Voronoi"), ("Warp", "Deformazione"), ("Warp Directional", "Deformazione direzionale"), + ("Wavefront OBJ with MTL, textures alongside", "Wavefront OBJ con MTL, texture accanto"), ( "WebGPU isn't available in this browser, so TextureCraft runs on WebGL2: Rendering mode path traces on the CPU (slower) and large texture sets show at reduced resolution. A current Chrome, Edge or Safari has WebGPU.", "WebGPU non è disponibile in questo browser, quindi TextureCraft usa WebGL2: la modalità Rendering esegue il path tracing sulla CPU (più lento) e i set di texture grandi vengono mostrati a risoluzione ridotta. Le versioni recenti di Chrome, Edge e Safari supportano WebGPU.", diff --git a/crates/ui-egui/src/i18n/ja.rs b/crates/ui-egui/src/i18n/ja.rs index 53a63092..b0175c20 100644 --- a/crates/ui-egui/src/i18n/ja.rs +++ b/crates/ui-egui/src/i18n/ja.rs @@ -893,6 +893,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Voronoi", "ボロノイ"), ("Warp", "ワープ"), ("Warp Directional", "方向ワープ"), + ("Wavefront OBJ with MTL, textures alongside", "Wavefront OBJ(MTL付き)、テクスチャは別ファイル"), ( "WebGPU isn't available in this browser, so TextureCraft runs on WebGL2: Rendering mode path traces on the CPU (slower) and large texture sets show at reduced resolution. A current Chrome, Edge or Safari has WebGPU.", "このブラウザーでは WebGPU を利用できないため、TextureCraft は WebGL2 で動作しています。レンダリングモードのパストレーシングは CPU で行われ (低速)、大きなテクスチャセットは解像度を下げて表示されます。最新の Chrome、Edge、Safari は WebGPU に対応しています。", diff --git a/crates/ui-egui/src/i18n/ko.rs b/crates/ui-egui/src/i18n/ko.rs index 534eacdd..e9d8b634 100644 --- a/crates/ui-egui/src/i18n/ko.rs +++ b/crates/ui-egui/src/i18n/ko.rs @@ -878,6 +878,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Voronoi", "보로노이"), ("Warp", "워프"), ("Warp Directional", "방향성 워프"), + ("Wavefront OBJ with MTL, textures alongside", "Wavefront OBJ(MTL 포함), 텍스처는 옆에"), ( "WebGPU isn't available in this browser, so TextureCraft runs on WebGL2: Rendering mode path traces on the CPU (slower) and large texture sets show at reduced resolution. A current Chrome, Edge or Safari has WebGPU.", "이 브라우저에서는 WebGPU를 사용할 수 없어 TextureCraft가 WebGL2로 실행됩니다. 렌더링 모드의 패스 트레이싱은 CPU에서 수행되며(더 느림), 큰 텍스처 세트는 낮은 해상도로 표시됩니다. 최신 Chrome, Edge, Safari는 WebGPU를 지원합니다.", diff --git a/crates/ui-egui/src/i18n/pt_br.rs b/crates/ui-egui/src/i18n/pt_br.rs index 941a884d..5485fcad 100644 --- a/crates/ui-egui/src/i18n/pt_br.rs +++ b/crates/ui-egui/src/i18n/pt_br.rs @@ -896,6 +896,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Voronoi", "Voronoi"), ("Warp", "Deformar"), ("Warp Directional", "Deformar direcional"), + ("Wavefront OBJ with MTL, textures alongside", "Wavefront OBJ com MTL, texturas ao lado"), ( "WebGPU isn't available in this browser, so TextureCraft runs on WebGL2: Rendering mode path traces on the CPU (slower) and large texture sets show at reduced resolution. A current Chrome, Edge or Safari has WebGPU.", "O WebGPU não está disponível neste navegador, então o TextureCraft usa WebGL2: o modo de renderização faz path tracing na CPU (mais lento) e conjuntos de texturas grandes aparecem em resolução reduzida. As versões atuais do Chrome, Edge e Safari têm WebGPU.", diff --git a/crates/ui-egui/src/i18n/zh_hans.rs b/crates/ui-egui/src/i18n/zh_hans.rs index fa4ac037..34ce14a4 100644 --- a/crates/ui-egui/src/i18n/zh_hans.rs +++ b/crates/ui-egui/src/i18n/zh_hans.rs @@ -821,6 +821,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Voronoi", "沃罗诺伊"), ("Warp", "变形"), ("Warp Directional", "方向变形"), + ("Wavefront OBJ with MTL, textures alongside", "Wavefront OBJ(含 MTL),纹理单独存放"), ( "WebGPU isn't available in this browser, so TextureCraft runs on WebGL2: Rendering mode path traces on the CPU (slower) and large texture sets show at reduced resolution. A current Chrome, Edge or Safari has WebGPU.", "此浏览器不支持 WebGPU,因此 TextureCraft 使用 WebGL2 运行:渲染模式在 CPU 上进行路径追踪(较慢),大型纹理集以降低的分辨率显示。最新版 Chrome、Edge 和 Safari 支持 WebGPU。", diff --git a/crates/ui-egui/src/windows.rs b/crates/ui-egui/src/windows.rs index f4e486f7..8ecab281 100644 --- a/crates/ui-egui/src/windows.rs +++ b/crates/ui-egui/src/windows.rs @@ -1112,7 +1112,7 @@ pub fn file_action(app: &mut TextureCraftApp, _ctx: &egui::Context, id: &str) -> "file.exportMesh" => { let name = format!("{}.obj", texturecraft_engine::formats::export::sanitize_file_stem(&app.session.doc.project.name)); if let Some(p) = rfd::FileDialog::new() - .add_filter("Wavefront OBJ", &["obj"]) + .add_filter(tr("Wavefront OBJ with MTL, textures alongside"), &["obj"]) .add_filter(tr("glTF binary with textures"), &["glb"]) .add_filter(tr("USDZ with textures"), &["usdz"]) .add_filter(tr("USD text, textures alongside"), &["usda"]) diff --git a/docs/control-protocol.md b/docs/control-protocol.md index ec23c358..3d7c2206 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -135,7 +135,7 @@ takes a font family, not a path: it reads only the system's font folders. | `project_save` | `{path?}` | `.tcraft` (appended if missing), relative to the write root | | `mesh_import` | `{path, resolution?}` | New project from .glb/.gltf/.fbx/.dae/.usd/.usda/.usdc/.usdz/.abc/.obj/.ply/.stl; a .gltf's buffers and images and a loose USD layer's textures are read from its folder | | `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?}` | +| `mesh_export` | `{path, format?}` | The mesh as obj, glb, usda, usdc or usdz below the write root (obj: its .mtl and textures, 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`, 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 | diff --git a/docs/features.md b/docs/features.md index 281f97f0..3aedc3db 100644 --- a/docs/features.md +++ b/docs/features.md @@ -105,7 +105,9 @@ Everything TextureCraft does today, by area. What's still missing is in [`ROADMA override and OpenGL or DirectX normals. - **Output template editor:** build your own presets with per-channel packing and converted maps, and share them as JSON. -- **Mesh export** to OBJ, textured GLB (with clear coat and sheen) and USD (with clear coat). +- **Mesh export** to OBJ with an MTL material library and its maps (PBR extension keys for + roughness, metallic, normal and coat; UV-tiled sets keep their UDIM UVs and export their maps + through Export textures), textured GLB (with clear coat and sheen) and USD (with clear coat). ## The viewport