diff --git a/ATTRIBUTION.md b/ATTRIBUTION.md index c26f317a..5d607a5c 100644 --- a/ATTRIBUTION.md +++ b/ATTRIBUTION.md @@ -34,9 +34,9 @@ These come from Rust crate dependencies (not files in this repository) and keep | Phosphor Icons (regular), via the `egui-phosphor` crate (vendored in `vendor/egui-phosphor` for egui 0.37) | Every UI icon (tools, layers, panels) | Phosphor Icons (Helena Zhang, Tobias Fried) | https://phosphoricons.com, https://github.com/amPerl/egui-phosphor | MIT (icons); crate MIT OR Apache-2.0 | | egui default fonts (Ubuntu-Light, Hack, Noto Emoji, emoji-icon-font), via `epaint_default_fonts` | UI text; Ubuntu Light and Hack also as the built-in fonts for text alphas and decals | Canonical / Source Foundry / Google / Jessie Jung | https://github.com/emilk/egui | Ubuntu Font Licence 1.0, MIT + Bitstream Vera License, OFL 1.1, MIT | | Only in builds made with `CRAFT_FONTS_DIR`: Inter Regular and SemiBold (desktop and web), from storytold/craft-fonts' Latin catalog (`crates/ui-egui/build.rs`) | Interface text | The Inter Project Authors | https://github.com/storytold/craft-fonts (pinned sources in its `fonts/latin-manifest.txt` and `ATTRIBUTION.md`) | OFL 1.1 | -| Only in builds made with `CRAFT_FONTS_DIR`: BIZ UDPGothic Regular (desktop and web) and Noto Sans CJK SC Regular (desktop), from storytold/craft-fonts (`crates/ui-egui/build.rs`) | Japanese and Chinese UI text | The BIZ UDGothic Project Authors (Morisawa Inc.); The Noto Project Authors | https://github.com/storytold/craft-fonts (pinned sources in its `fonts/manifest.txt` and `ATTRIBUTION.md`) | OFL 1.1 | +| Only in builds made with `CRAFT_FONTS_DIR`: BIZ UDPGothic Regular (desktop and web), Noto Sans CJK SC Regular (desktop) and Noto Sans Arabic Regular (desktop and web), from storytold/craft-fonts (`crates/ui-egui/build.rs`) | Japanese, Chinese and Arabic UI text | The BIZ UDGothic Project Authors (Morisawa Inc.); The Noto Project Authors | https://github.com/storytold/craft-fonts (pinned sources in its `fonts/manifest.txt` and `ATTRIBUTION.md`) | OFL 1.1 | -Without craft-fonts, Chinese, Japanese and Korean UI text uses the operating system's fonts at run +Without craft-fonts, Chinese, Japanese, Korean and Arabic UI text uses the operating system's fonts at run time (nothing is bundled); see [docs/localization-parity.md](docs/localization-parity.md). ## Procedural content (no asset files) diff --git a/Cargo.lock b/Cargo.lock index 2b82f9d8..4db6022f 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -178,15 +178,6 @@ dependencies = [ "libc", ] -[[package]] -name = "arbitrary" -version = "1.5.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3bc62ac97cc33321f50863d514c3bc38a453947a8f9e781137e47c7401020aed" -dependencies = [ - "derive_arbitrary", -] - [[package]] name = "arboard" version = "3.6.1" @@ -572,7 +563,7 @@ dependencies = [ "maybe-owned", "rustix 1.1.5", "rustix-linux-procfs", - "windows-sys 0.61.2", + "windows-sys 0.60.2", "winx", ] @@ -870,17 +861,6 @@ dependencies = [ "syn 3.0.9", ] -[[package]] -name = "derive_arbitrary" -version = "1.5.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1b034bd7d5f032402a2479444dcc6f74e36a03f31854d41680fb240ef682a1ac" -dependencies = [ - "proc-macro2", - "quote", - "syn 3.0.9", -] - [[package]] name = "dispatch" version = "0.2.0" @@ -1191,7 +1171,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb" dependencies = [ "libc", - "windows-sys 0.61.2", + "windows-sys 0.52.0", ] [[package]] @@ -2410,6 +2390,18 @@ dependencies = [ "jni-sys 0.3.1", ] +[[package]] +name = "nix" +version = "0.31.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf20d2fde8ff38632c426f1165ed7436270b44f199fc55284c38276f9db47c3d" +dependencies = [ + "bitflags 2.13.2", + "cfg-if", + "cfg_aliases", + "libc", +] + [[package]] name = "nohash-hasher" version = "0.2.0" @@ -2820,7 +2812,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7d8fae84b431384b68627d0f9b3b1245fcf9f46f6c0e3dc902e9dce64edd1967" dependencies = [ "libc", - "windows-sys 0.61.2", + "windows-sys 0.52.0", ] [[package]] @@ -3422,7 +3414,7 @@ dependencies = [ "errno", "libc", "linux-raw-sys 0.12.1", - "windows-sys 0.61.2", + "windows-sys 0.52.0", ] [[package]] @@ -3721,7 +3713,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c3d1e2c7f27f8d4cb10542a02c49005dbd6e93095799d6f3be745fae9f8fedd4" dependencies = [ "libc", - "windows-sys 0.61.2", + "windows-sys 0.60.2", ] [[package]] @@ -3803,10 +3795,10 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd" dependencies = [ "fastrand", - "getrandom 0.4.3", + "getrandom 0.3.4", "once_cell", "rustix 1.1.5", - "windows-sys 0.61.2", + "windows-sys 0.52.0", ] [[package]] @@ -4257,6 +4249,12 @@ dependencies = [ "rustc-hash 2.1.3", ] +[[package]] +name = "typed-path" +version = "0.12.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "54ec2755506471f54baf5e4bb5499d8e510cc1caf271270e778a736bd2d7336c" + [[package]] name = "typeid" version = "1.0.3" @@ -4271,7 +4269,7 @@ checksum = "f2f6fb2847f6742cd76af783a2a2c49e9375d0a111c7bef6f71cd9e738c72d6e" dependencies = [ "memoffset", "tempfile", - "windows-sys 0.61.2", + "windows-sys 0.60.2", ] [[package]] @@ -4790,7 +4788,7 @@ version = "0.1.11" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22" dependencies = [ - "windows-sys 0.61.2", + "windows-sys 0.52.0", ] [[package]] @@ -5493,18 +5491,16 @@ dependencies = [ [[package]] name = "zip" -version = "2.4.2" +version = "9.0.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fabe6324e908f85a1c52063ce7aa26b68dcb7eb6dbc83a2d148403c9bc3eba50" +checksum = "6e04976da629d3b04204ba8105b396a193af8ad2583b2c79bfb3ab8af580a11e" dependencies = [ - "arbitrary", "crc32fast", - "crossbeam-utils", - "displaydoc", "flate2", "indexmap", "memchr", - "thiserror 2.0.21", + "nix", + "typed-path", "zopfli", ] diff --git a/Cargo.toml b/Cargo.toml index 9c44cd2f..b9dfc9aa 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -45,7 +45,7 @@ eframe = { version = "0.37", default-features = false } egui = "0.37" wgpu = "30" rfd = "0.17" -zip = { version = "2", default-features = false, features = ["deflate"] } +zip = { version = "9", default-features = false, features = ["deflate"] } gltf = { version = "1.4", default-features = false, features = ["import", "utils", "names", "KHR_materials_emissive_strength"] } tobj = { version = "4", default-features = false } flate2 = "1" diff --git a/README.md b/README.md index ea45b817..e6a08036 100644 --- a/README.md +++ b/README.md @@ -154,7 +154,7 @@ cargo xtask ci # fmt, clippy, test You need Rust 1.95 or newer. The app opens with a baked sample project; **File ▸ New project** starts from a built-in mesh, a project template or your own mesh file (UVs are generated if it has none). -Japanese, Chinese and Korean interface text uses the fonts of +Japanese, Chinese, Korean and Arabic interface text uses the fonts of [storytold/craft-fonts](https://github.com/storytold/craft-fonts) where it has them, an optional build input (releases always use it): `CRAFT_FONTS_DIR="$PWD/../craft-fonts" cargo run --release -p texturecraft` (an absolute path). Without it, the desktop app uses the installed system fonts. @@ -184,7 +184,7 @@ area, the remaining work and what's next. to end, weighted by how much of the day each area carries: importing meshes, texture sets and UDIM tiles, the layer stack with masks, effects and smart materials, every painting tool, baking, the PBR viewport and Rendering mode, export presets and templates, and the full menu set. The interface -speaks English, French, German, Spanish, Portuguese, Italian, Japanese, Chinese and Korean; +speaks English, French, German, Spanish, Portuguese, Italian, Japanese, Chinese, Korean and Arabic; [localization-parity.md](docs/localization-parity.md) has the details. The scores are self-assessed from our code against public documentation. diff --git a/ROADMAP.md b/ROADMAP.md index b632e821..8563db44 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -20,7 +20,7 @@ end to end today (engine + UI + automation + tests), not what is planned. | 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, channel / mesh-map / mask / UV checker views, 3D and 2D wireframes, 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** | 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, `$udim` tiles, 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) | -| UI and UX | 8 | 95% | 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, **shortcut editor** with conflict detection, tooltips with shortcuts; all menu items live ([docs/parity.md](docs/parity.md)); **9 UI languages** with CJK 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 | +| UI and UX | 8 | 95% | 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, **shortcut editor** with conflict detection, tooltips with shortcuts; 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 | 75% | 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** | **≈ 93%** | | | diff --git a/crates/formats/src/mesh_import/fbx.rs b/crates/formats/src/mesh_import/fbx.rs index 43fea71e..d7dd46fc 100644 --- a/crates/formats/src/mesh_import/fbx.rs +++ b/crates/formats/src/mesh_import/fbx.rs @@ -445,7 +445,7 @@ pub(crate) fn read(bytes: &[u8]) -> Result { if zip.len() > MAX_ZIP_ENTRIES { return Err(FormatError::TooLarge(format!("the FBX package has more than {MAX_ZIP_ENTRIES} entries"))); } - let name = zip.file_names().filter(|n| super::extension(n) == "fbx").min_by_key(|n| zip.index_for_name(n)).map(str::to_string); + let name = zip.file_names().flatten().filter(|n| super::extension(n) == "fbx").min_by_key(|n| zip.index_for_name(n)).map(Cow::into_owned); let name = name.ok_or_else(|| malformed(KIND, "the package contains no FBX file"))?; let fbx = zip_entry(&mut zip, &name, MAX_MESH_FILE_BYTES) .ok_or_else(|| FormatError::TooLarge("the packaged FBX is unreadable or larger than 2 GiB".into()))?; diff --git a/crates/formats/src/mesh_import/mod.rs b/crates/formats/src/mesh_import/mod.rs index 521cab30..361d7837 100644 --- a/crates/formats/src/mesh_import/mod.rs +++ b/crates/formats/src/mesh_import/mod.rs @@ -20,8 +20,8 @@ mod stl; pub(crate) mod tests; pub(crate) mod usd; -use std::collections::HashMap; use std::collections::hash_map::Entry; +use std::collections::{HashMap, HashSet}; use texturecraft_geom::glam::{Mat4, Vec2, Vec3, Vec4}; use texturecraft_geom::unwrap::{all_triangles_degenerate, auto_unwrap, weld_ids}; @@ -134,6 +134,8 @@ pub(crate) struct RawMesh { pub cameras: Vec, /// Materials whose base color is not plain white (glTF). pub base_colors: Vec, + /// Vertex pairs (smaller first) that [`RawMesh::polygon`] added to split polygons. + pub diagonals: HashSet<(u32, u32)>, } /// A material's base color as a file gives it: the linear factor and the encoded texture. @@ -159,6 +161,19 @@ impl RawMesh { pub fn triangle_count(&self) -> usize { self.groups.iter().map(|(_, _, g)| g.len() / 3).sum() } + + /// Fan-triangulate polygon `corners` (vertex indices) into `material`'s triangles in `part`, + /// remembering the diagonals so wireframes can show the polygon. + pub fn polygon(&mut self, material: &str, part: &str, corners: &[u32]) { + let Some((&first, rest)) = corners.split_first() else { return }; + let group = self.group(material, part); + for w in rest.windows(2) { + group.extend_from_slice(&[first, w[0], w[1]]); + } + for &v in rest.iter().skip(1).take(rest.len().saturating_sub(2)) { + self.diagonals.insert((first.min(v), first.max(v))); + } + } } /// One polygon corner of a scene format (FBX, COLLADA), already in world space. @@ -213,11 +228,7 @@ impl PolygonSink { }; self.polygon.push(id); } - let group = self.raw.group(material, &self.part); - let (first, rest) = self.polygon.split_first().unwrap_or((&0, &[])); - for w in rest.windows(2) { - group.extend_from_slice(&[*first, w[0], w[1]]); - } + self.raw.polygon(material, &self.part, &self.polygon); Ok(()) } @@ -365,7 +376,7 @@ fn read(file_name: &str, bytes: &[u8]) -> Result { /// Positions, submeshes (materials contiguous), normals and colors of a raw mesh, validated; /// plus its warnings and UVs (the mesh's UVs and tangents are left empty). fn geometry(raw: RawMesh) -> Result<(Mesh, Vec, Option>)> { - let RawMesh { positions, normals, uvs, colors, groups, warnings, .. } = raw; + let RawMesh { positions, normals, uvs, colors, groups, warnings, diagonals, .. } = raw; check_vertices(positions.len())?; check_triangles(0, groups.iter().map(|(_, _, g)| g.len() / 3).sum())?; let mut mesh = Mesh { positions, ..Mesh::default() }; @@ -390,6 +401,10 @@ fn geometry(raw: RawMesh) -> Result<(Mesh, Vec, Option>)> { if mesh.indices.is_empty() { return Err(FormatError::Invalid("the file contains no triangles".into())); } + if !diagonals.is_empty() { + let diagonal = |a: u32, b: u32| diagonals.contains(&(a.min(b), a.max(b))); + mesh.diagonals = mesh.indices.chunks_exact(3).map(|t| (0..3).map(|i| u8::from(diagonal(t[i], t[(i + 1) % 3])) << i).sum()).collect(); + } if let Some(bad) = mesh.indices.iter().find(|i| **i as usize >= mesh.positions.len()) { return Err(FormatError::Invalid(format!("vertex index {bad} out of range ({} vertices)", mesh.positions.len()))); } diff --git a/crates/formats/src/mesh_import/obj.rs b/crates/formats/src/mesh_import/obj.rs index ce259a5a..4cf36661 100644 --- a/crates/formats/src/mesh_import/obj.rs +++ b/crates/formats/src/mesh_import/obj.rs @@ -27,7 +27,8 @@ fn read_inner(bytes: &[u8]) -> Result { } let library: String = names.iter().map(|n| format!("newmtl {n}\n")).collect(); let source = format!("mtllib texturecraft-usemtl.mtl\n{text}"); - let opts = tobj::LoadOptions { single_index: true, triangulate: true, ignore_points: true, ignore_lines: true }; + // Polygons stay whole so the wireframe can show them; `RawMesh::polygon` triangulates. + let opts = tobj::LoadOptions { single_index: true, triangulate: false, ignore_points: true, ignore_lines: true }; let (models, materials) = tobj::load_obj_buf(&mut source.as_bytes(), &opts, |_| tobj::load_mtl_buf(&mut library.as_bytes())).map_err(|e| malformed(KIND, e))?; let materials = materials.unwrap_or_default(); @@ -39,7 +40,9 @@ fn read_inner(bytes: &[u8]) -> Result { let m = &model.mesh; let n = m.positions.len() / 3; check_vertices(raw.positions.len().saturating_add(n))?; - check_triangles(raw.triangle_count(), m.indices.len() / 3)?; + // Corners per face; without arities every face is a triangle. + let arities: Vec = if m.face_arities.is_empty() { vec![3; m.indices.len() / 3] } else { m.face_arities.iter().map(|a| *a as usize).collect() }; + check_triangles(raw.triangle_count(), arities.iter().map(|a| a.saturating_sub(2)).sum())?; let base = raw.positions.len() as u32; raw.positions.extend(m.positions.chunks_exact(3).map(|p| Vec3::new(p[0], p[1], p[2]))); if m.normals.len() == n * 3 { @@ -67,12 +70,18 @@ fn read_inner(bytes: &[u8]) -> Result { Some(id) => materials.get(id).map(|mat| mat.name.clone()).filter(|s| !s.is_empty()).unwrap_or_else(|| format!("Material_{id}")), None => "Default".to_string(), }; - let group = raw.group(&name, &model.name); - for &i in m.indices.get(..m.indices.len() / 3 * 3).unwrap_or_default() { - if i as usize >= n { - return Err(malformed(KIND, format!("face index {i} out of range"))); + if let Some(i) = m.indices.iter().find(|i| **i as usize >= n) { + return Err(malformed(KIND, format!("face index {i} out of range"))); + } + let (mut rest, mut corners) = (m.indices.as_slice(), Vec::new()); + for arity in arities { + let Some((face, tail)) = rest.split_at_checked(arity) else { break }; + rest = tail; + corners.clear(); + corners.extend(face.iter().map(|i| base + i)); + if arity >= 3 { + raw.polygon(&name, &model.name, &corners); } - group.push(base + i); } } if partial_uvs && models.iter().any(|m| !m.mesh.texcoords.is_empty()) { diff --git a/crates/formats/src/mesh_import/ply.rs b/crates/formats/src/mesh_import/ply.rs index 1452aa41..0a72b28e 100644 --- a/crates/formats/src/mesh_import/ply.rs +++ b/crates/formats/src/mesh_import/ply.rs @@ -117,7 +117,6 @@ pub(crate) fn read(bytes: &[u8]) -> Result { let mut body = Body { data: bytes.get(body_start..).unwrap_or_default(), pos: 0, enc }; let mut raw = RawMesh::default(); let (mut normals, mut uvs, mut colors) = (Vec::new(), Vec::new(), Vec::new()); - let mut faces: Vec = Vec::new(); let mut nverts = 0usize; for el in &elements { // Every item takes at least one byte, so the count can never exceed what is left. @@ -169,10 +168,8 @@ pub(crate) fn read(bytes: &[u8]) -> Result { } } if face_list == Some(k) && poly.len() >= 3 { - check_triangles(faces.len() / 3, poly.len() - 2)?; - for i in 1..poly.len() - 1 { - faces.extend_from_slice(&[poly[0], poly[i], poly[i + 1]]); - } + check_triangles(raw.triangle_count(), poly.len() - 2)?; + raw.polygon("Default", "", &poly); } } } @@ -202,7 +199,6 @@ pub(crate) fn read(bytes: &[u8]) -> Result { raw.normals = (normals.len() == n).then_some(normals); raw.uvs = (uvs.len() == n).then_some(uvs); raw.colors = (colors.len() == n).then_some(colors); - raw.groups.push(("Default".into(), String::new(), faces)); Ok(raw) } diff --git a/crates/formats/src/mesh_import/tests.rs b/crates/formats/src/mesh_import/tests.rs index a21e5d4a..752fa61b 100644 --- a/crates/formats/src/mesh_import/tests.rs +++ b/crates/formats/src/mesh_import/tests.rs @@ -235,6 +235,22 @@ fn obj_without_uvs_or_normals_is_completed() { assert!(n0.len() > 1 && n0.iter().all(|n| (*n - n0[0]).length() < 1e-5)); } +#[test] +fn polygons_keep_their_edges_for_the_wireframe() { + // An OBJ quad and pentagon (with UVs, so no unwrap splits them), a triangle, and a PLY quad. + let obj = "v 0 0 0\nv 1 0 0\nv 1 1 0\nv 0 1 0\nv 2 0 0\nv 3 0 0\nv 3 1 0\nv 2.5 2 0\nv 2 1 0\nvt 0 0\n\ + f 1/1 2/1 3/1 4/1\nf 5/1 6/1 7/1 8/1 9/1\nf 1/1 2/1 5/1\n"; + let m = import_mesh_bytes("p.obj", obj.as_bytes()).unwrap().mesh; + assert_eq!(m.triangle_count(), 2 + 3 + 1); + assert_eq!(m.wire_edges()[0].len(), 4 + 5 + 2, "the triangle adds edges 1-5 and 2-5"); + let ply = import_mesh_bytes("a.ply", ply_ascii().as_bytes()).unwrap().mesh; + assert_eq!(ply.wire_edges()[0].len(), 4); + // Triangles alone keep every edge. + let tris = import_mesh_bytes("t.obj", b"v 0 0 0\nv 1 0 0\nv 1 1 0\nv 0 1 0\nvt 0 0\nf 1/1 2/1 3/1\nf 1/1 3/1 4/1\n").unwrap().mesh; + assert!(tris.diagonals.is_empty()); + assert_eq!(tris.wire_edges()[0].len(), 5); +} + fn ply_ascii() -> String { "ply\nformat ascii 1.0\ncomment test\nelement vertex 4\nproperty float x\nproperty float y\nproperty float z\nproperty float s\nproperty float t\n\ element face 1\nproperty list uchar int vertex_indices\nend_header\n\ diff --git a/crates/formats/src/mesh_import/usd/mod.rs b/crates/formats/src/mesh_import/usd/mod.rs index fc1544bb..e7f9d0fe 100644 --- a/crates/formats/src/mesh_import/usd/mod.rs +++ b/crates/formats/src/mesh_import/usd/mod.rs @@ -228,8 +228,8 @@ fn read_usdz(bytes: &[u8]) -> Result<(Layer, Package<'_>)> { if zip.len() > MAX_ZIP_ENTRIES { return Err(FormatError::TooLarge(format!("the usdz package has more than {MAX_ZIP_ENTRIES} entries"))); } - let name = zip.file_names().filter(|n| matches!(super::extension(n).as_str(), "usda" | "usdc" | "usd")).min_by_key(|n| zip.index_for_name(n)); - let name = name.ok_or_else(|| malformed(KIND, "the usdz package contains no USD layer"))?.to_string(); + let name = zip.file_names().flatten().filter(|n| matches!(super::extension(n).as_str(), "usda" | "usdc" | "usd")).min_by_key(|n| zip.index_for_name(n)); + let name = name.ok_or_else(|| malformed(KIND, "the usdz package contains no USD layer"))?.into_owned(); let dir = name.rsplit_once('/').map_or("", |(d, _)| d).to_string(); let mut package = Package { zip, dir }; let data = package.read(&name, MAX_MESH_FILE_BYTES).ok_or_else(|| FormatError::TooLarge("the usdz layer is unreadable or larger than 2 GiB".into()))?; diff --git a/crates/formats/src/mesh_import/usd/tests.rs b/crates/formats/src/mesh_import/usd/tests.rs index 6cfd0a07..e5da5cb8 100644 --- a/crates/formats/src/mesh_import/usd/tests.rs +++ b/crates/formats/src/mesh_import/usd/tests.rs @@ -347,16 +347,16 @@ fn usda_usdc_and_usdz_round_trip_with_textures() { round_trip(&m, UsdFormat::Usdc, "usdc", &textures); let usdz = round_trip(&m, UsdFormat::Usdz, "usdz", &textures); let mut zip = zip::ZipArchive::new(std::io::Cursor::new(&usdz)).unwrap(); - let names: Vec = zip.file_names().map(str::to_string).collect(); + let names: Vec = zip.file_names().map(|n| n.unwrap().into_owned()).collect(); assert_eq!(names.first().map(String::as_str), Some("Test_scene.usdc")); assert_eq!(names.len(), 1 + 7, "the layer and every non-black texture"); for i in 0..zip.len() { let mut f = zip.by_index(i).unwrap(); assert_eq!(f.compression(), zip::CompressionMethod::Stored); - assert_eq!(f.data_start() % 64, 0, "usdz entries are 64-byte aligned"); + assert_eq!(f.data_start().unwrap() % 64, 0, "usdz entries are 64-byte aligned"); let mut data = Vec::new(); f.read_to_end(&mut data).unwrap(); - if f.name().ends_with(".png") { + if f.name().unwrap().ends_with(".png") { assert!(image::load_from_memory(&data).is_ok()); } } diff --git a/crates/formats/src/project_file/mod.rs b/crates/formats/src/project_file/mod.rs index bd8bd228..a0d6cb3b 100644 --- a/crates/formats/src/project_file/mod.rs +++ b/crates/formats/src/project_file/mod.rs @@ -333,7 +333,7 @@ fn load(reader: R) -> Result { }; for i in 0..zip.len() { let mut f = zip.by_index(i).map_err(zip_err)?; - let name = f.name().to_string(); + let name = f.name().map_err(zip_err)?.into_owned(); let size_of = |id: LayerId| texture_set_of(&pf.project, id).and_then(|ts| pf.project.texture_sets.get(ts)).map(|t| t.size()); if name == "thumbnail.png" { pf.thumbnail = Some(read_all(&mut f, MAX_THUMBNAIL, &mut budget, &name)?); diff --git a/crates/geom/src/mesh.rs b/crates/geom/src/mesh.rs index 2ba804b2..95d66b4e 100644 --- a/crates/geom/src/mesh.rs +++ b/crates/geom/src/mesh.rs @@ -40,6 +40,9 @@ pub struct Mesh { /// Index ranges per material and part (node / object); `name` is the part name. pub submeshes: Vec, pub materials: Vec, + /// Per triangle, bit `i` set when edge `i` (corner `i` to corner `i + 1`) is a diagonal the + /// importer added to split a polygon, which wireframes leave out. Empty: every edge is real. + pub diagonals: Vec, } /// Hard cap on mesh size accepted from files (triangles). @@ -74,6 +77,36 @@ impl Mesh { Some([i[0] as usize, i[1] as usize, i[2] as usize]) } + /// The edges wireframes draw: each vertex pair once (smaller index first), leaving out + /// polygon diagonals ([`Mesh::diagonals`]) unless only one triangle has the edge (a UV seam + /// split it from its twin), per material in `0..materials.len().max(1)`. + pub fn wire_edges(&self) -> Vec> { + (0..self.materials.len().max(1)) + .map(|m| { + // Edge → (real in some triangle, triangles using it), in first-seen order. + let mut edges: Vec<((u32, u32), bool, u8)> = Vec::new(); + let mut at: std::collections::HashMap<(u32, u32), usize> = std::collections::HashMap::new(); + for t in self.triangles_of(m) { + let Some(v) = self.indices.get(t * 3..t * 3 + 3) else { continue }; + let hidden = self.diagonals.get(t).copied().unwrap_or(0); + for (i, (a, b)) in [(v[0], v[1]), (v[1], v[2]), (v[2], v[0])].into_iter().enumerate() { + let key = (a.min(b), a.max(b)); + let real = hidden >> i & 1 == 0; + let e = *at.entry(key).or_insert_with(|| { + edges.push((key, false, 0)); + edges.len() - 1 + }); + if let Some((_, r, n)) = edges.get_mut(e) { + *r |= real; + *n = n.saturating_add(1); + } + } + } + edges.into_iter().filter(|(_, real, n)| *real || *n == 1).map(|(k, ..)| k).collect() + }) + .collect() + } + /// Material of triangle `t`. pub fn material_of(&self, t: usize) -> Option { let idx = (t * 3) as u32; @@ -270,6 +303,10 @@ impl Mesh { self.colors.resize(base as usize, Vec4::ONE); self.colors.extend(other.colors.iter().copied().chain(std::iter::repeat(Vec4::ONE)).take(other.positions.len())); } + if !(self.diagonals.is_empty() && other.diagonals.is_empty()) { + self.diagonals.resize(ibase as usize / 3, 0); + self.diagonals.extend(other.diagonals.iter().copied().chain(std::iter::repeat(0)).take(other.triangle_count())); + } self.indices.extend(other.indices.iter().map(|i| i + base)); self.materials.extend(other.materials.iter().cloned()); self.submeshes.extend(other.submeshes.iter().map(|s| SubMesh { @@ -302,6 +339,7 @@ impl Mesh { colors: Vec::new(), submeshes: vec![SubMesh { name: material.into(), material: 0, start: 0, count }], materials: vec![material.into()], + diagonals: Vec::new(), }; if m.normals.len() != m.positions.len() { m.compute_normals(); @@ -377,6 +415,24 @@ mod tests { assert_eq!(m.triangles_of(0).collect::>(), vec![0, 1]); } + #[test] + fn wire_edges_leave_out_polygon_diagonals() { + let mut m = quad(); + assert_eq!(m.wire_edges(), vec![vec![(0, 1), (1, 2), (0, 2), (2, 3), (0, 3)]], "triangles show every edge"); + // Edge 2 of (0, 1, 2) and edge 0 of (0, 2, 3) split the quad. + m.diagonals = vec![0b100, 0b001]; + assert_eq!(m.wire_edges(), vec![vec![(0, 1), (1, 2), (2, 3), (0, 3)]]); + // A diagonal whose twin a seam split off (vertex 4 copies vertex 0) stays. + let mut seam = m.clone(); + seam.indices[3] = 4; + assert_eq!(seam.wire_edges()[0].len(), 6); + // Appending keeps each side's diagonals on its own triangles. + let mut a = Mesh::from_parts(m.positions.clone(), None, m.uvs.clone(), vec![0, 1, 2], "A").unwrap(); + a.append(&m); + assert_eq!(a.diagonals, vec![0, 0b100, 0b001]); + assert_eq!(crate::primitives::plane(1.0, 2).wire_edges()[0].len(), 12, "a 2×2 grid of quads has 12 edges"); + } + #[test] fn validate_catches_bad_indices() { let mut m = quad(); diff --git a/crates/geom/src/primitives.rs b/crates/geom/src/primitives.rs index 7f07270c..6403faed 100644 --- a/crates/geom/src/primitives.rs +++ b/crates/geom/src/primitives.rs @@ -30,6 +30,8 @@ struct Builder { n: Vec, uv: Vec, idx: Vec, + /// Per triangle: its [`Mesh::diagonals`] bits. + diag: Vec, } impl Builder { @@ -55,6 +57,8 @@ impl Builder { let a = base + i * w + j; let (b, c, d) = (a + 1, a + w, a + w + 1); self.idx.extend_from_slice(&[a, c, d, a, d, b]); + // Edge d-a of the first triangle and a-d of the second split the quad. + self.diag.extend_from_slice(&[0b100, 0b001]); } } } @@ -70,6 +74,7 @@ impl Builder { colors: Vec::new(), submeshes: vec![SubMesh { name: material.into(), material: 0, start: 0, count }], materials: vec![material.into()], + diagonals: self.diag, }; m.compute_tangents(); m @@ -203,6 +208,7 @@ fn disk_into(b: &mut Builder, center: Vec3, radius: f32, up: bool, segs: usize, } else { b.idx.extend_from_slice(&[c, a, bb]); } + b.diag.push(0); } } diff --git a/crates/render/src/displace.rs b/crates/render/src/displace.rs index 287898c7..f2e2b19a 100644 --- a/crates/render/src/displace.rs +++ b/crates/render/src/displace.rs @@ -72,6 +72,7 @@ pub fn displaced(mesh: &Mesh, sets: &[TraceSet]) -> Option { }, indices, materials: mesh.materials.clone(), + diagonals: Vec::new(), }) } diff --git a/crates/render/src/renderer.rs b/crates/render/src/renderer.rs index 5fd4ac14..60a8c39c 100644 --- a/crates/render/src/renderer.rs +++ b/crates/render/src/renderer.rs @@ -1018,21 +1018,12 @@ impl Renderer { let vb = mk("tc_vb", bytemuck::cast_slice(&verts), wgpu::BufferUsages::VERTEX); let ib = mk("tc_ib", &idx_bytes, wgpu::BufferUsages::INDEX); let draws: Vec<(u32, u32, usize)> = mesh.submeshes.iter().map(|s| (s.start, s.count, s.material)).collect(); - // UV edges (each shared edge once) per material, for the 2D view wireframe. + // Mesh edges per material (polygons, not their triangles), for the wireframes. let mut line_idx: Vec = Vec::new(); let mut line_draws = Vec::new(); - for m in 0..mesh.materials.len().max(1) { + for (m, edges) in mesh.wire_edges().into_iter().enumerate() { let start = line_idx.len() as u32; - let mut seen = std::collections::HashSet::new(); - for t in mesh.triangles_of(m) { - let Some(v) = mesh.tri(t) else { continue }; - for (a, b) in [(v[0], v[1]), (v[1], v[2]), (v[2], v[0])] { - let key = (a.min(b), a.max(b)); - if seen.insert(key) { - line_idx.extend_from_slice(&[key.0 as u32, key.1 as u32]); - } - } - } + line_idx.extend(edges.into_iter().flat_map(|(a, b)| [a, b])); line_draws.push((start, line_idx.len() as u32 - start, m)); } let lines = mk("tc_lines", bytemuck::cast_slice(&line_idx), wgpu::BufferUsages::INDEX); diff --git a/crates/ui-egui/build.rs b/crates/ui-egui/build.rs index 4888d580..86168323 100644 --- a/crates/ui-egui/build.rs +++ b/crates/ui-egui/build.rs @@ -1,5 +1,5 @@ //! Embeds the optional craft-fonts UI fonts (storytold/craft-fonts) when `CRAFT_FONTS_DIR` points -//! at a checkout: Inter for the interface (from its Latin catalog) and the CJK +//! at a checkout: Inter for the interface (from its Latin catalog) and the CJK and Arabic //! faces; without it `CRAFT_FONTS` is empty and the UI uses egui's and the system's fonts. The //! recipe follows craft-fonts' `docs/integration.md`; no font file is committed here. The Latin //! faces are embedded without their Private Use Area ([`without_private_use`]). @@ -10,10 +10,12 @@ use std::path::PathBuf; /// The UI faces TextureCraft embeds (family, style) per manifest: desktop, then web (the web build /// has a download budget: of the CJK faces only the Japanese one, ~4.5 MB). const MANIFESTS: &[(&str, Faces, Faces)] = &[ - ("fonts/manifest.txt", &[("BIZ UDPGothic", "Regular"), ("Noto Sans CJK SC", "Regular")], &[("BIZ UDPGothic", "Regular")]), + ("fonts/manifest.txt", &[("BIZ UDPGothic", "Regular"), ("Noto Sans CJK SC", "Regular"), ARABIC], &[("BIZ UDPGothic", "Regular"), ARABIC]), // The interface font, regular and semibold (0.8 MB). (LATIN_MANIFEST, LATIN, LATIN), ]; +/// The Arabic face (0.8 MB, so the web build has it too). +const ARABIC: (&str, &str) = ("Noto Sans Arabic", "Regular"); /// Newer than the core catalog: a checkout without it keeps the default interface font. const LATIN_MANIFEST: &str = "fonts/latin-manifest.txt"; const LATIN: Faces = &[("Inter", "Regular"), ("Inter", "SemiBold")]; diff --git a/crates/ui-egui/src/dock.rs b/crates/ui-egui/src/dock.rs index 5bce3896..41332911 100644 --- a/crates/ui-egui/src/dock.rs +++ b/crates/ui-egui/src/dock.rs @@ -95,6 +95,22 @@ pub(crate) fn texture_set_list(app: &mut TextureCraftApp, ui: &mut Ui) { // --------------------------------------------------------------------------------------------- // Layers +/// The add-mask commands, for the selected layer or (`row`) the layer whose mask slot was clicked. +fn add_mask_menu(app: &mut TextureCraftApp, ui: &mut Ui, row: Option) { + let enabled = row.is_some() || app.session.selected_layer().is_some(); + for (label, id) in + [(tr("Add white mask"), "mask.add.white"), (tr("Add black mask"), "mask.add.black"), (tr("Add mask with color selection"), "mask.add.colorSelection")] + { + if ui.add_enabled(enabled, egui::Button::new(label)).clicked() { + if let Some(layer) = row { + app.run("layer.select", json!({ "layer": layer })); + } + app.run(id, Value::Null); + ui.close(); + } + } +} + pub(crate) fn layers(app: &mut TextureCraftApp, ui: &mut Ui) { let tk = Tokens::get(ui.ctx()); // Wraps in a narrow column instead of widening the rows below past the panel. @@ -108,7 +124,6 @@ pub(crate) fn layers(app: &mut TextureCraftApp, ui: &mut Ui) { ui.selectable_value(&mut app.ui.layer_channel, c, tr(c.label())); } }); - let has = app.session.selected_layer().is_some(); let selected = app.session.selected_layer().and_then(|id| app.session.doc.project.layers.get(&id)).cloned(); ui.menu_button(RichText::new(ic::MAGIC_WAND).size(14.0), |ui| match &selected { Some(l) => effect_menu(app, ui, l), @@ -118,20 +133,7 @@ pub(crate) fn layers(app: &mut TextureCraftApp, ui: &mut Ui) { }) .response .on_hover_text(tr("Add effect")); - ui.menu_button(RichText::new(ic::SELECTION_BACKGROUND).size(14.0), |ui| { - for (label, id) in [ - (tr("Add white mask"), "mask.add.white"), - (tr("Add black mask"), "mask.add.black"), - (tr("Add mask with color selection"), "mask.add.colorSelection"), - ] { - if ui.add_enabled(has, egui::Button::new(label)).clicked() { - app.run(id, Value::Null); - ui.close(); - } - } - }) - .response - .on_hover_text(tr("Add mask")); + ui.menu_button(RichText::new(ic::SELECTION_BACKGROUND).size(14.0), |ui| add_mask_menu(app, ui, None)).response.on_hover_text(tr("Add mask")); if icon_button(ui, ic::PAINT_BRUSH, tr("Add paint layer"), false, 22.0).clicked() { app.run("layer.add.paint", Value::Null); } @@ -374,7 +376,13 @@ fn layer_row(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, depth: usize p.rect_stroke(mask_rect.expand(2.0), 1.0, Stroke::new(1.5, tk.warning), egui::StrokeKind::Outside); } } else { - p.rect_stroke(mask_rect, 1.0, Stroke::new(1.0, tk.field_border), egui::StrokeKind::Inside); + // The empty slot adds a mask to this layer. + let slot = ui.interact(mask_rect, ui.scope_id().with(("mask_slot", layer.id.0)), Sense::click()).on_hover_text(tr("Add mask")); + p.rect_stroke(mask_rect, 1.0, Stroke::new(1.0, if slot.hovered() { tk.accent } else { tk.field_border }), egui::StrokeKind::Inside); + if slot.hovered() { + p.text(mask_rect.center(), egui::Align2::CENTER_CENTER, ic::PLUS, egui::FontId::proportional(12.0), tk.text); + } + egui::Popup::menu(&slot).show(|ui| add_mask_menu(app, ui, Some(layer.id.0))); } // Name (or rename editor). let name_rect = Rect::from_min_max(pos2(x, rect.top() + 4.0), pos2(mask_rect.left() - 4.0, rect.bottom() - 4.0)); diff --git a/crates/ui-egui/src/fonts.rs b/crates/ui-egui/src/fonts.rs index 444bcdfc..b31b423a 100644 --- a/crates/ui-egui/src/fonts.rs +++ b/crates/ui-egui/src/fonts.rs @@ -1,15 +1,17 @@ -//! CJK fallback fonts for the UI. egui's default fonts have no Japanese, Chinese or Korean -//! glyphs, so translated UIs (and CJK layer or file names) need more fonts. They come from: +//! CJK and Arabic fallback fonts for the UI. egui's default fonts have no Japanese, Chinese, +//! Korean or Arabic glyphs, so translated UIs (and such layer or file names) need more fonts. +//! They come from: //! //! 1. craft-fonts, embedded at build time when `CRAFT_FONTS_DIR` points at a checkout (optional; //! see `build.rs` and storytold/craft-fonts' `docs/integration.md`); -//! 2. on desktop, the operating system's CJK fonts (Windows, macOS, Linux and BSD paths). +//! 2. on desktop, the operating system's fonts (Windows, macOS, Linux and BSD paths). //! -//! Fonts load lazily: one script when the UI language needs it, all three while the language +//! Fonts load lazily: one script when the UI language needs it, all of them while the language //! picker shows every language's own name. They are appended after the app's fonts //! (`theme::font_definitions`), so Latin text and row heights keep the interface font; the current language's script goes first, so -//! shared Han characters take that language's glyph forms. In the browser only craft-fonts -//! can supply them (without it, a CJK language shows its English name in the picker). +//! shared Han characters take that language's glyph forms. egui shapes Arabic and orders +//! right-to-left runs itself. In the browser only craft-fonts can supply them (without it, the +//! language shows its English name in the picker). use std::sync::Arc; @@ -35,10 +37,11 @@ pub enum Script { Japanese, Chinese, Korean, + Arabic, } impl Script { - pub const ALL: [Script; 3] = [Script::Japanese, Script::Chinese, Script::Korean]; + pub const ALL: [Script; 4] = [Script::Japanese, Script::Chinese, Script::Korean, Script::Arabic]; /// The script a UI language needs beyond Latin. pub fn of_language(code: &str) -> Option