Free, open-source 3D sculpting for Linux, macOS and Windows: dense meshes, remeshing, painting, built-in AI (image/text to 3D), Send to Unreal, game-ready LODs, Gaussian splats and OpenUSD.
C++ 3d3d-sculptingcppdear-imguidigital-sculptingfbxgame-developmentgaussian-splattinggltfimage-to-3dmcpopenglopenusdsculptingtext-to-3dunreal-engine
SubTools in every file path: projects, exporters, importers, GoZ
islandmedc4642e76eeaf
diff --git a/docs/goz.md b/docs/goz.mdindex 92cd8d13..64897508 100644--- a/docs/goz.md+++ b/docs/goz.md@@ -18,10 +18,10 @@ Code: `src/io/GozIO.h/.cpp` (format + bridge), `src/io/StlIO.h/.cpp`, `src/io/Go| Command | What it does ||---------|--------------|| `goz_import path=` | Open a `.GoZ` file (`open` does the same for `.GoZ`) |-| `goz_export path= [name=] [quads=true]` | Write a `.GoZ` file |-| `goz_send [name=] [folder=] [launch=true] [zbrush=]` | Send the mesh to ZBrush through the bridge |-| `goz_receive [folder=]` | Load what ZBrush last sent (undoable; several SubTools are merged) |-| `export_stl path=` | Binary STL (`open` reads binary and ASCII `.stl`) |+| `goz_export path= [name=] [quads=true]` | Write a `.GoZ` file; with several visible SubTools, one `<stem>_<SubTool>.GoZ` each beside `path` |+| `goz_send [name=] [folder=] [launch=true] [zbrush=]` | Send every visible SubTool to ZBrush through the bridge (`name=` only for a single one) |+| `goz_receive [folder=]` | Load what ZBrush last sent: each object updates its SubTool (undoable) or becomes a new one |+| `export_stl path=` | Binary STL of the visible SubTools merged (`open` reads binary and ASCII `.stl`) |All of them are available in `sculptforge-cli`, the MCP server and Python, like every other command.@@ -68,8 +68,9 @@ faces with out-of-range indices are dropped, so a broken file cannot read past i- **Polygroups.** The 16-bit ids are stored as they are in `Mesh::polygroups`. On export, ids above 65535keep only their low 16 bits.- **Hidden faces.** GoZ has no hidden flag, so hidden triangles are exported like any others.-- The object name (`GozInfo::name`) is remembered in `Document::gozName`, so `goz_send` updates the- SubTool the mesh came from.+- The object name (`GozInfo::name`) is remembered per SubTool (`Document::gozName` for the active one,+ `SubTool::gozName` for the others, saved in projects), so `goz_send` updates the ZBrush SubTool the+ mesh came from and `goz_receive` updates the SculptForge SubTool it was sent from.## The bridge (Windows, macOS)@@ -82,10 +83,14 @@ GoZ apps exchange files through a shared folder:field in File > ZBrush (GoZ)), such as a Wine prefix's `drive_c/users/Public/Pixologic`, makes thebridge work anyway.-**Send** (`goz_send`), following GoB's `GoB_OT_export.execute`:+**Send** (`goz_send`), following GoB's `GoB_OT_export.execute`. Every visible SubTool is one GoZ object,+named after the GoZ name it came with, else its SubTool name (`gozObjectName`; duplicates get `_2`,+`_3`...), so ZBrush gets them as separate SubTools:-1. Write `GoZProjects/Default/<Name>.GoZ`, plus `<Name>.ztn`, which holds the object path without its extension.-2. Write that path (forward slashes, no extension) as the only line of `GoZBrush/GoZ_ObjectList.txt`.+1. Write `GoZProjects/Default/<Name>.GoZ` for each object, plus `<Name>.ztn`, which holds the object path+ without its extension.+2. Write those paths (forward slashes, no extension), one line per object in SubTool order, to+ `GoZBrush/GoZ_ObjectList.txt`.3. Write `GoZBrush/GoZ_Application.txt` = `SculptForge` and `GoZBrush/GoZ_ProjectPath.txt`.4. Register SculptForge as a GoZ application: `GoZApps/SculptForge/GoZ_Info.txt` (same keys as GoB's`Blender/GoZ_Info.txt`) and `GoZ_Config.txt` (`PATH = "<sculptforge executable>"`, written by the app).@@ -96,8 +101,15 @@ GoZ apps exchange files through a shared folder:ZScript, so after a fresh start you press GoZ in ZBrush.**Receive** (`goz_receive`), following GoB's `GoB_OT_import.execute`: read `GoZ_ObjectList.txt`, append-`.GoZ` to each line and load every object. The objects are merged into one mesh, and the result replaces the-current mesh as an undoable step.+`.GoZ` to each line and load every object. Each object then:++- replaces the mesh of the SubTool whose GoZ name matches (an undoable step in that SubTool's history),+- or, for the first object when the scene is a single SubTool that didn't come from ZBrush (e.g. a new+ scene), replaces that SubTool, as receiving did before SubTools,+- or else is added as a new SubTool named after the object.++The active SubTool stays selected. `gozReceive(root, Mesh&)` still offers the objects merged into one+mesh for callers that want that.In the app, **Receive automatically** checks the object list's modification time once a second andreceives when ZBrush rewrites it, which is what GoB's auto-import timer does. Sending turns it on anddiff --git a/docs/project-format.md b/docs/project-format.mdindex f47a26c9..305f617b 100644--- a/docs/project-format.md+++ b/docs/project-format.md@@ -4,37 +4,58 @@ A `.sfproj` is an uncompressed ("stored") ZIP (src/io/Zip.cpp) written by `savePread by `loadProject` (src/core/Project.cpp). Commands: `save_project path=...`,`open_project path=...`; `open` also recognises `.sfproj`.-## Layout-- `manifest.json`: always first. `format` = `"SculptForge project"`, `version` (integer, currently 1),- `app_version`, then `mesh`, `layers`, `active_layer`, `brushes` (recipe JSON), `active_brush`- (name), optional `splats`, and app-owned keys (`camera`, `render`, `brush`, `symmetry`).+## Layout (version 2)+- `manifest.json`: always first. `format` = `"SculptForge project"`, `version` (integer, currently 2),+ `app_version`, then `subtools` (one entry per SubTool, in list order), `active_subtool` (index),+ `brushes` (recipe JSON), `active_brush` (name), optional `splats`, and app-owned keys (`camera`,+ `render`, `brush`, `symmetry`).+- Each `subtools[i]` holds `name`, `visible` (bool), `mesh`, `layers`, `active_layer` (sculpt layer+ strokes go into, -1 = base) and, for a mesh that came from ZBrush, `goz_name` (the GoZ object name+ that `goz_send` / `goz_receive` match on).- Blobs are little-endian arrays. The manifest describes each one as- `{"file", "type": "f32"|"u32"|"u8", "components", "count"}`; readers check all four.+ `{"file", "type": "f32"|"u32"|"u8", "components", "count"}`; readers check all four. SubTool `i`'s+ blobs live under `subtools/<i>/` (the file name comes from the descriptor, so readers don't rely+ on it).-| Manifest key | File | Layout |+| Manifest key (in `subtools[i]`) | File | Layout |+|--------------|------|--------|+| `mesh.positions` | subtools/i/mesh/positions.bin | f32 x3 per vertex (current blend) |+| `mesh.triangles` | subtools/i/mesh/triangles.bin | u32 x3 per triangle |+| `mesh.base` | subtools/i/mesh/base.bin | f32 x3 per vertex (only with layers) |+| `mesh.mask` / `colors` | subtools/i/mesh/mask.bin, colors.bin | f32 x1 / x3 per vertex (linear RGB) |+| `mesh.polygroups` / `hidden` | subtools/i/mesh/polygroups.bin, hidden.bin | u32 / u8 per triangle |+| `mesh.uvs` | subtools/i/mesh/uvs.bin | f32 x2 per triangle corner |+| `layers[k].delta` | subtools/i/layers/<k>.bin | f32 x3 per vertex, plus `name`, `weight` |++| Manifest key (top level) | File | Layout ||--------------|------|--------|-| `mesh.positions` | mesh/positions.bin | f32 x3 per vertex (current blend) |-| `mesh.triangles` | mesh/triangles.bin | u32 x3 per triangle |-| `mesh.base` | mesh/base.bin | f32 x3 per vertex (only with layers) |-| `mesh.mask` / `colors` | mesh/mask.bin, colors.bin | f32 x1 / x3 per vertex (linear RGB) |-| `mesh.polygroups` / `hidden` | mesh/polygroups.bin, hidden.bin | u32 / u8 per triangle |-| `mesh.uvs` | mesh/uvs.bin | f32 x2 per triangle corner |-| `layers[i].delta` | layers/<i>.bin | f32 x3 per vertex, plus `name`, `weight` || `splats.*` | splats/*.bin | positions x3, rotations x4 (x,y,z,w), scales x3, opacities x1, sh x3 per coefficient; plus `count`, `sh_degree`, `name`, `transform` (16 floats, column-major) |Optional attributes are simply absent when the mesh doesn't have them.+Loading replaces the scene: every SubTool comes back with its name, visibility, attributes, layers,+active layer and GoZ name, the saved active SubTool is selected, every SubTool starts with an empty+undo history and the document is clean. A file is refused (and the open scene left alone) when the+SubTool list is missing or empty, or any SubTool's mesh is broken; an out-of-range `active_subtool`+selects the first one.++## Version 1+Version 1 files (SculptForge 0.2 and earlier) have one mesh at the top level instead of `subtools`:+`mesh` and `layers` as above (blobs under `mesh/` and `layers/`) and `active_layer`. They still load,+as a single SubTool called "Sculpt". Saving always writes version 2.+## Compatibility rules- Unknown keys and files are ignored. Unknown **top-level** keys are kept in`Document::projectSettings` and written back, so older builds don't drop newer settings.- A file whose `version` is greater than `kProjectVersion` is refused with a message naming the appversion that wrote it. Bump `kProjectVersion` only for changes old readers would misread;adding a new optional blob does not need a bump.-- New mesh attributes: add a blob in `saveProject` and read it in `loadProject` (size-checked).+- New mesh attributes: add a blob in `writeMesh` and read it in `readMesh` (size-checked); both+ are used for every SubTool.## App behaviour (src/app/PanelProject.cpp)-- `Document::dirty()` = any undo push/undo/redo, splat edit or `modified` since `markClean()`- (save, open, new). The window title shows `*` while dirty.+- `Document::dirty()` = any undo push/undo/redo (in any SubTool), splat edit or `modified` since+ `markClean()` (save, open, new). The window title shows `*` while dirty.- New / Open / Open Recent / drop / Quit / window close ask Save / Don't Save / Cancel when dirty(never in `--render`, `--record` or demos).- The pref dir (`SDL_GetPrefPath`) holds `project.json` (10 recent files, autosave interval),diff --git a/docs/unreal.md b/docs/unreal.mdindex 92635981..3299ada5 100644--- a/docs/unreal.md+++ b/docs/unreal.md@@ -9,6 +9,7 @@ write an Unreal-ready FBX for you to import by hand.|---|---|| No sculpt layers | **Static mesh** `SM_<Name>` with LOD0–LODn from **Game Ready → LODs** (one file, imported as LODs automatically) || Sculpt layers | **Skeletal mesh** `SK_<Name>` with one **morph target** per layer (Unreal adds a single root bone) |+| Several visible SubTools | One FBX model per SubTool, combined into one asset on import (*Combine Meshes*). Static meshes get a LOD group per SubTool, each decimated on its own, and Unreal puts level *n* of every SubTool into LOD *n*; layers on any visible SubTool make the asset skeletal || Any | Material slot `M_Clay`, real-world size from **Height (cm)** |Sending the same asset again **updates it in place** (same name and folder), sodiff --git a/src/cli/McpServer.cpp b/src/cli/McpServer.cppindex 64a70151..b4da1956 100644--- a/src/cli/McpServer.cpp+++ b/src/cli/McpServer.cpp@@ -87,6 +87,8 @@ std::string handleMcpMessage(const CommandRegistry& registry, Document& doc, con"SculptForge is a digital sculpting tool. One scene is kept for the whole session: start with ""new_sphere, open (models, Gaussian-splat captures, USD) or image_to_3d, shape it with ""subdivide/remesh/layers/decimate, then export_glb, export_usd, export_lods or splat_save. "+ "A scene can hold several SubTools (separate meshes, see subtool_list): edits apply to the active "+ "one, exports write every visible one. ""Use mesh_info and splat_info to check results. File paths are on the user's machine.");return reply(id, result).dump();}diff --git a/src/core/Commands.cpp b/src/core/Commands.cppindex 6bbe9495..e6aa494e 100644--- a/src/core/Commands.cpp+++ b/src/core/Commands.cpp@@ -63,6 +63,16 @@ std::string lowerExtension(const std::string& path) {return ext;}+std::string fileStem(const std::string& path) {+ const auto stem = std::filesystem::path(std::u8string(path.begin(), path.end())).stem().u8string();+ return std::string(stem.begin(), stem.end());+}++// " (3 SubTools)" for a multi-object export, else nothing.+std::string objectCountText(const std::vector<MeshObjectRef>& objects) {+ return objects.size() > 1 ? " (" + std::to_string(objects.size()) + " SubTools)" : std::string();+}+std::string jsonEscape(const std::string& s) {std::string out;for (char c : s) {@@ -106,50 +116,60 @@ CommandRegistry::CommandRegistry() {{{"path", T::String, "File path (UTF-8).", true}},[](Document& doc, const Args& a) -> CommandResult {std::string path = argString(a, "path");- Mesh m;+ std::vector<MeshObject> objects;std::string err;- if (!loadObj(path, m, err)) return {false, err};- doc.setMesh(std::move(m));+ if (!loadObj(path, objects, err)) return {false, err};+ const size_t count = objects.size();+ setSceneObjects(doc, std::move(objects), fileStem(path));doc.path = path;- return {true, "Loaded " + path};+ return {true, "Loaded " + path + (count > 1 ? " (" + std::to_string(count) + " SubTools)" : "")};}});add({"open","Open a file: models (.obj, .fbx, .glb, .gltf, .ply, .stl, .usda, .usdz, ZBrush .GoZ) replace the scene; Gaussian splats ""(.ply/.splat captures, KHR_gaussian_splatting .glb, USD ParticleField) load as a reference next to the sculpt. "- "glTF morph targets and FBX/USD blend shapes become sculpt layers. SculptForge projects (.sfproj) "+ "glTF morph targets and FBX/USD blend shapes become sculpt layers. Files with several objects (OBJ `o`, "+ "glTF nodes, FBX models, USD meshes) open as one SubTool each. SculptForge projects (.sfproj) ""restore the whole scene.",{{"path", T::String, "File path (UTF-8).", true}},[](Document& doc, const Args& a) -> CommandResult {std::string path = argString(a, "path");if (isProjectPath(path)) return openProjectCommand(doc, path);const std::string ext = lowerExtension(path);+ std::vector<MeshObject> objects; // one per object in the file (OBJ `o`, glTF node, FBX model, USD prim)Mesh m;SplatCloud splats;std::string err;GozInfo goz;bool ok;- if (ext == ".glb" || ext == ".gltf") ok = loadGltf(path, m, err, &splats);- else if (ext == ".usda" || ext == ".usd" || ext == ".usdz") ok = loadUsd(path, m, splats, err);+ if (ext == ".glb" || ext == ".gltf") ok = loadGltf(path, objects, err, &splats);+ else if (ext == ".usda" || ext == ".usd" || ext == ".usdz") ok = loadUsd(path, objects, splats, err);else if (ext == ".splat") ok = loadDotSplat(path, splats, err);- else if (ext == ".fbx") ok = loadFbx(path, m, err);+ else if (ext == ".fbx") ok = loadFbx(path, objects, err);else if (ext == ".goz") ok = loadGoz(path, m, err, &goz);else if (ext == ".stl") ok = loadStl(path, m, err);else if (ext == ".ztl" || ext == ".zpr" || ext == ".zbr") return {false, zbrushProprietaryMessage(ext)};else if (ext == ".ply") {PlyContent content;ok = loadPly(path, m, splats, content, err);- } else ok = loadObj(path, m, err);+ } else ok = loadObj(path, objects, err);if (!ok) return {false, err};+ if (m.triangleCount() > 0) objects.push_back({"", std::move(m)});+ std::erase_if(objects, [](const MeshObject& o) { return o.mesh.triangleCount() == 0; });std::string msg = "Opened " + path;- const bool hasMesh = m.triangleCount() > 0;+ const bool hasMesh = !objects.empty();if (hasMesh) {- const auto stem = std::filesystem::path(std::u8string(path.begin(), path.end())).stem().u8string();- doc.setMesh(std::move(m), ext == ".goz" && !goz.name.empty() ? goz.name : std::string(stem.begin(), stem.end()));+ size_t tris = 0, layers = 0;+ for (const auto& o : objects) {+ tris += o.mesh.triangleCount();+ layers = std::max(layers, o.mesh.layers.size());+ }+ const size_t count = objects.size();+ setSceneObjects(doc, std::move(objects), ext == ".goz" && !goz.name.empty() ? goz.name : fileStem(path));doc.path = ext == ".obj" ? path : std::string(); // other formats are exported explicitlyif (ext == ".goz") doc.gozName = goz.name;- msg += " (" + std::to_string(doc.mesh.triangleCount()) + " triangles" +- (doc.mesh.layers.empty() ? "" : ", " + std::to_string(doc.mesh.layers.size()) + " layers") + ")";+ msg += " (" + (count > 1 ? std::to_string(count) + " SubTools, " : std::string()) + std::to_string(tris) ++ " triangles" + (layers == 0 ? "" : ", " + std::to_string(layers) + " layers") + ")";}if (!splats.empty()) {doc.splats = std::move(splats);@@ -245,16 +265,19 @@ CommandRegistry::CommandRegistry() {}});add({"save_obj",- "Export the mesh as a Wavefront OBJ file. OBJ cannot hold the mask, polygroups, visibility, sculpt layers "- "or splats, so this is an export: the document keeps its path and unsaved-changes state.",+ "Export the visible SubTools as a Wavefront OBJ file (one `o` object each, polygroups as `g` groups). OBJ "+ "cannot hold the mask, visibility, sculpt layers or splats, so this is an export: the document keeps its "+ "path and unsaved-changes state.",{{"path", T::String, "File path (UTF-8). Defaults to the current document path unless that is a project.", false}},[](Document& doc, const Args& a) -> CommandResult {std::string path = argString(a, "path", isProjectPath(doc.path) ? std::string() : doc.path);if (path.empty()) return {false, "No path given"};if (isProjectPath(path)) return {false, "Use save_project for .sfproj files"};std::string err;- if (!saveObj(path, doc.mesh, err)) return {false, err};- return {true, "Saved " + path};+ const auto objects = visibleSubtoolObjects(doc);+ if (objects.empty()) return {false, "Nothing visible to export"};+ if (!saveObj(path, objects, err)) return {false, err};+ return {true, "Saved " + path + objectCountText(objects)};}});add({"subdivide",@@ -333,17 +356,21 @@ CommandRegistry::CommandRegistry() {}});add({"export_glb",- "Export a game-ready binary glTF (.glb). Sculpt layers become morph targets (blend shapes).",+ "Export a game-ready binary glTF (.glb), one node and mesh per visible SubTool. Sculpt layers become "+ "morph targets (blend shapes).",{{"path", T::String, "Output .glb path (UTF-8).", true}},[](Document& doc, const Args& a) -> CommandResult {std::string path = argString(a, "path");std::string err;- if (!saveGlb(path, doc.mesh, doc.assetName(), err)) return {false, err};- return {true, "Exported " + path};+ const auto objects = visibleSubtoolObjects(doc);+ if (objects.empty()) return {false, "Nothing visible to export"};+ if (!saveGlb(path, objects, doc.assetName(), err)) return {false, err};+ return {true, "Exported " + path + objectCountText(objects)};}});add({"export_usd",- "Export OpenUSD (.usda text, or .usdz package for AR Quick Look / Vision Pro). Sculpt layers become "+ "Export OpenUSD (.usda text, or .usdz package for AR Quick Look / Vision Pro), one Mesh prim per visible "+ "SubTool. Sculpt layers become ""UsdSkel blend shapes with their current weights; loaded Gaussian splats are included as a ""ParticleField3DGaussianSplat prim.",{{"path", T::String, "Output .usda, .usd or .usdz path (UTF-8).", true},@@ -352,37 +379,47 @@ CommandRegistry::CommandRegistry() {std::string path = argString(a, "path");std::string err;const SplatCloud* splats = argBool(a, "splats", true) && !doc.splats.empty() ? &doc.splats : nullptr;- if (!saveUsd(path, &doc.mesh, splats, doc.assetName(), err)) return {false, err};- return {true, "Exported " + path + (splats ? " (mesh + " + std::to_string(splats->size()) + " splats)" : "")};+ const auto objects = visibleSubtoolObjects(doc);+ if (!saveUsd(path, objects, splats, doc.assetName(), err)) return {false, err};+ return {true, "Exported " + path + objectCountText(objects) ++ (splats ? " (mesh + " + std::to_string(splats->size()) + " splats)" : "")};}});add({"export_fbx",- "Export binary FBX: sculpt layers become blend shapes; with lods > 1 the LOD chain is written as an FBX "- "LOD group in the same file.",+ "Export binary FBX, one model per visible SubTool: sculpt layers become blend shapes; with lods > 1 each "+ "SubTool's LOD chain is written as an FBX LOD group in the same file.",{{"path", T::String, "Output .fbx path (UTF-8).", true},{"lods", T::Number, "LOD levels including LOD0 (1-8). Default 1.", false},{"ratio", T::Number, "Triangle ratio between LODs (0.1-0.9). Default 0.5.", false},{"scale", T::Number, "Multiply positions (FBX units are centimetres). Default 100 (1 unit = 1 m).", false}},[](Document& doc, const Args& a) -> CommandResult {const int levels = std::clamp(int(argNumber(a, "lods", 1)), 1, 8);- std::vector<Mesh> lods;- std::vector<const Mesh*> meshes = {&doc.mesh};- if (levels > 1) {- lods = generateLods(doc.mesh, levels, float(std::clamp(argNumber(a, "ratio", 0.5), 0.1, 0.9)));- meshes.clear();- for (const auto& l : lods) meshes.push_back(&l);+ const auto objects = visibleSubtoolObjects(doc);+ if (objects.empty()) return {false, "Nothing visible to export"};+ // One model per visible SubTool; with lods > 1 each gets its own LOD group (see FbxIO.h).+ std::vector<std::vector<Mesh>> lods(objects.size());+ std::vector<FbxObject> fbxObjects;+ for (size_t i = 0; i < objects.size(); ++i) {+ FbxObject fo{objects[i].name, {objects[i].mesh}};+ if (levels > 1) {+ lods[i] = generateLods(*objects[i].mesh, levels, float(std::clamp(argNumber(a, "ratio", 0.5), 0.1, 0.9)));+ fo.lods.clear();+ for (const auto& l : lods[i]) fo.lods.push_back(&l);+ }+ fbxObjects.push_back(std::move(fo));}FbxExportOptions o;o.scale = float(argNumber(a, "scale", 100.0));std::string err;const std::string path = argString(a, "path");- if (!saveFbx(path, doc.assetName(), meshes, o, err)) return {false, err};- return {true, "Exported " + path};+ if (!saveFbx(path, fbxObjects, o, err)) return {false, err};+ return {true, "Exported " + path + objectCountText(objects)};}});add({"export_unreal","Export an Unreal Engine-ready FBX: centimetres, SM_/SK_ naming, LOD chain packed for automatic LOD "- "import; a sculpt with layers becomes a skeletal mesh with morph targets.",+ "import; a sculpt with layers becomes a skeletal mesh with morph targets. Every visible SubTool is its own "+ "model (Unreal's Combine Meshes makes them one asset).",{{"folder", T::String, "Output folder (UTF-8). The file is named after the asset.", true},{"name", T::String, "Asset name (default SM_<document> or SK_<document>).", false},{"height_cm", T::Number, "Model height in Unreal, in cm. Default: 1 unit = 1 m.", false},@@ -398,12 +435,15 @@ CommandRegistry::CommandRegistry() {UnrealExportResult r;std::string err;if (!exportForUnreal(doc, o, r, err)) return {false, err};- return {true, "Exported " + r.path + " (" + (r.skeletal ? "skeletal mesh, " + std::to_string(doc.mesh.layers.size()) + " morph targets"+ size_t morphs = 0;+ for (const auto& obj : visibleSubtoolObjects(doc)) morphs += obj.mesh->layers.size();+ return {true, "Exported " + r.path + " (" + (r.skeletal ? "skeletal mesh, " + std::to_string(morphs) + " morph targets": "static mesh, " + std::to_string(r.lodCount) + " LODs") + ")"};}});add({"export_lods",- "Generate a LOD chain and export each level as <name>_LOD<n>.glb next to `path`. Blend shapes are kept on every LOD.",+ "Generate a LOD chain of every visible SubTool and export each level as <name>_LOD<n>.glb next to `path`. "+ "Blend shapes are kept on every LOD.",{{"path", T::String, "Base output path, e.g. /assets/rock.glb.", true},{"levels", T::Number, "Number of LODs including LOD0 (1-8). Default 4.", false},{"ratio", T::Number, "Triangle ratio between consecutive LODs (0.1-0.9). Default 0.5.", false}},@@ -412,18 +452,29 @@ CommandRegistry::CommandRegistry() {std::filesystem::path base(std::u8string(pathArg.begin(), pathArg.end()));int levels = std::clamp(int(argNumber(a, "levels", 4)), 1, 8);float ratio = float(std::clamp(argNumber(a, "ratio", 0.5), 0.1, 0.9));- auto lods = generateLods(doc.mesh, levels, ratio);+ const auto objects = visibleSubtoolObjects(doc);+ if (objects.empty()) return {false, "Nothing visible to export"};+ // Every visible SubTool is decimated on its own; LOD n of each goes into <name>_LOD<n>.glb.+ std::vector<std::vector<Mesh>> lods;+ for (const auto& o : objects) lods.push_back(generateLods(*o.mesh, levels, ratio));auto stemU8 = base.stem().u8string();std::string stem(stemU8.begin(), stemU8.end());std::ostringstream msg;msg << "Exported";- for (size_t i = 0; i < lods.size(); ++i) {+ for (size_t i = 0; i < lods[0].size(); ++i) {std::string fileName = stem + "_LOD" + std::to_string(i) + ".glb";auto out = (base.parent_path() / std::u8string(fileName.begin(), fileName.end())).u8string();std::string outPath(out.begin(), out.end());std::string err;- if (!saveGlb(outPath, lods[i], stem + "_LOD" + std::to_string(i), err)) return {false, err};- msg << " LOD" << i << " (" << lods[i].triangleCount() << " tris)";+ std::vector<MeshObjectRef> level;+ size_t tris = 0;+ for (size_t k = 0; k < objects.size(); ++k) {+ const Mesh& l = lods[k][std::min(i, lods[k].size() - 1)];+ level.push_back({objects.size() == 1 ? stem + "_LOD" + std::to_string(i) : objects[k].name, &l});+ tris += l.triangleCount();+ }+ if (!saveGlb(outPath, level, stem + "_LOD" + std::to_string(i), err)) return {false, err};+ msg << " LOD" << i << " (" << tris << " tris)";}return {true, msg.str()};}});@@ -570,16 +621,18 @@ CommandRegistry::CommandRegistry() {}});add({"mesh_to_splats",- "Turn the sculpt into Gaussian splats (flat oriented surfels with baked clay shading), replacing any "+ "Turn the visible SubTools into Gaussian splats (flat oriented surfels with baked clay shading), replacing any ""loaded splats - for splat viewers, web scenes and engines that render 3DGS.",{{"count", T::Number, "Number of splats (1000-5000000). Default 250000.", false},{"shading", T::Bool, "Bake soft lighting and cavity darkening into the colour. Default true.", false}},[](Document& doc, const Args& a) -> CommandResult {- if (doc.mesh.triangleCount() == 0) return {false, "The mesh is empty"};+ Mesh merged; // no copy for a single SubTool+ const Mesh& visible = doc.subtoolCount() == 1 ? doc.mesh : (merged = mergedVisibleMesh(doc));+ if (visible.triangleCount() == 0) return {false, "The mesh is empty"};MeshToSplatsOptions o;o.count = size_t(std::clamp(argNumber(a, "count", 250000), 1000.0, 5000000.0));o.shading = argBool(a, "shading", true);- doc.splats = meshToSplats(doc.mesh, o);+ doc.splats = meshToSplats(visible, o);doc.splats.name = doc.assetName();doc.splatsChanged();return {true, "Made " + std::to_string(doc.splats.size()) + " splats from the sculpt"};diff --git a/src/core/EnginePresets.cpp b/src/core/EnginePresets.cppindex 3ebaffd5..1ab71d9c 100644--- a/src/core/EnginePresets.cpp+++ b/src/core/EnginePresets.cpp@@ -3,6 +3,7 @@#include "core/EnginePresets.h"#include "core/Decimate.h"+#include "core/SubTools.h"#include "io/FbxIO.h"#include <algorithm>@@ -23,26 +24,39 @@ std::string unrealName(const std::string& text) {} // namespacebool exportForUnreal(const Document& doc, const UnrealExportOptions& o, UnrealExportResult& r, std::string& error) {- const Mesh& mesh = doc.mesh;- if (mesh.triangleCount() == 0) {+ const std::vector<MeshObjectRef> objects = visibleSubtoolObjects(doc);+ if (objects.empty()) {error = "The mesh is empty";return false;}// Morph targets only exist on skeletal meshes in Unreal; a skeletal mesh can't use an FBX LOD group- // the same way, so layered sculpts export LOD0 only.- r.skeletal = !mesh.layers.empty();+ // the same way, so layered sculpts (any visible SubTool with layers) export LOD0 only.+ r.skeletal = false;+ AABB bounds;+ for (const auto& obj : objects) {+ r.skeletal |= !obj.mesh->layers.empty();+ bounds.expand(obj.mesh->bounds());+ }r.assetName = !o.assetName.empty() ? unrealName(o.assetName) : (r.skeletal ? "SK_" : "SM_") + unrealName(doc.assetName());- const float height = mesh.bounds().extent().y;+ const float height = bounds.extent().y;r.scale = o.heightCm > 0.0f && height > 0.0f ? o.heightCm / height : 100.0f;- std::vector<Mesh> lods;- std::vector<const Mesh*> levels = {&mesh};- if (!r.skeletal && o.lods > 1) {- lods = generateLods(mesh, std::clamp(o.lods, 2, 8), std::clamp(o.ratio, 0.1f, 0.9f));- levels.clear();- for (const auto& l : lods) levels.push_back(&l);+ // Every visible SubTool is its own FBX model (Unreal: one material section each with "Combine Meshes",+ // or one asset each without). Static meshes get a LOD group per SubTool, each decimated on its own, so+ // small parts (eyes, teeth) keep their share of triangles; Unreal's combined import gathers level n of+ // every group into its LOD n.+ std::vector<std::vector<Mesh>> lods(objects.size());+ std::vector<FbxObject> fbxObjects;+ for (size_t i = 0; i < objects.size(); ++i) {+ FbxObject fo{objects.size() == 1 ? r.assetName : unrealName(objects[i].name), {objects[i].mesh}};+ if (!r.skeletal && o.lods > 1) {+ lods[i] = generateLods(*objects[i].mesh, std::clamp(o.lods, 2, 8), std::clamp(o.ratio, 0.1f, 0.9f));+ fo.lods.clear();+ for (const auto& l : lods[i]) fo.lods.push_back(&l);+ }+ fbxObjects.push_back(std::move(fo));}- r.lodCount = int(levels.size());+ r.lodCount = int(fbxObjects.front().lods.size());std::filesystem::path folder(std::u8string(o.folder.begin(), o.folder.end()));if (folder.empty()) folder = std::filesystem::temp_directory_path();@@ -53,7 +67,7 @@ bool exportForUnreal(const Document& doc, const UnrealExportOptions& o, UnrealExFbxExportOptions fo;fo.scale = r.scale;- return saveFbx(r.path, r.assetName, levels, fo, error);+ return saveFbx(r.path, fbxObjects, fo, error);}} // namespace sfdiff --git a/src/core/Polypaint.cpp b/src/core/Polypaint.cppindex 4d091160..84016f24 100644--- a/src/core/Polypaint.cpp+++ b/src/core/Polypaint.cpp@@ -3,6 +3,7 @@#include "core/Polypaint.h"#include "core/Commands.h"+#include "core/SubTools.h"#include "io/PlyIO.h"#include <algorithm>@@ -323,13 +324,16 @@ void registerPaintCommands(CommandRegistry& registry) {}});registry.add({"export_ply",- "Export the mesh as a binary PLY with vertex colours (polypaint), for scan tools, MeshLab, Blender.",+ "Export the visible SubTools as one binary PLY mesh with vertex colours (polypaint), for scan tools, MeshLab, Blender.",{{"path", T::String, "Output .ply path (UTF-8).", true}},[](Document& doc, const Args& a) -> CommandResult {const std::string path = argString(a, "path");std::string err;- if (!savePlyMesh(path, doc.mesh, err)) return {false, err};- return {true, "Exported " + path + (doc.mesh.hasColors() ? " (with polypaint)" : "")};+ Mesh merged; // no copy for a single SubTool+ const Mesh& mesh = doc.subtoolCount() == 1 ? doc.mesh : (merged = mergedVisibleMesh(doc));+ if (mesh.triangleCount() == 0) return {false, "Nothing visible to export"};+ if (!savePlyMesh(path, mesh, err)) return {false, err};+ return {true, "Exported " + path + (mesh.hasColors() ? " (with polypaint)" : "")};}});}diff --git a/src/core/Project.cpp b/src/core/Project.cppindex cd9141c9..8a4f06ce 100644--- a/src/core/Project.cpp+++ b/src/core/Project.cpp@@ -22,10 +22,11 @@ namespace {constexpr const char* kFormatName = "SculptForge project";constexpr const char* kManifestName = "manifest.json";-// Top-level manifest keys owned by the core; every other key belongs to+// Top-level manifest keys owned by the core (mesh, layers and active_layer are+// version 1); every other key belongs to// Document::projectSettings (camera, render, brush, symmetry, ...).const char* const kCoreKeys[] = {"format", "version", "app_version", "mesh", "layers", "active_layer",- "brushes", "active_brush", "splats"};+ "subtools", "active_subtool", "brushes", "active_brush", "splats"};std::filesystem::path fsPath(const std::string& p) { return std::filesystem::path(std::u8string(p.begin(), p.end())); }@@ -138,6 +139,98 @@ size_t countOf(const Json& j) {return n >= 0 && n < 4.0e9 ? size_t(n) : size_t(-1);}++// Writes a mesh's blobs under `prefix` ("subtools/0/") and sets `mesh` and `layers` in `out`.+void writeMesh(Writer& w, const std::string& prefix, const Mesh& m, Json& out) {+ Json mesh = Json::object();+ mesh.set("vertex_count", double(m.vertexCount()));+ mesh.set("triangle_count", double(m.triangleCount()));+ mesh.set("positions", w.vec3s(prefix + "mesh/positions.bin", m.positions));+ mesh.set("triangles", w.uints(prefix + "mesh/triangles.bin", m.triangles.empty() ? nullptr : &m.triangles[0].x,+ m.triangleCount(), 3));+ if (!m.layers.empty()) mesh.set("base", w.vec3s(prefix + "mesh/base.bin", m.base));+ if (m.hasMask()) mesh.set("mask", w.floats(prefix + "mesh/mask.bin", m.mask.data(), m.mask.size(), 1));+ if (m.hasColors()) mesh.set("colors", w.vec3s(prefix + "mesh/colors.bin", m.colors));+ if (m.hasPolygroups())+ mesh.set("polygroups", w.uints(prefix + "mesh/polygroups.bin", m.polygroups.data(), m.polygroups.size(), 1));+ if (m.hasHidden()) mesh.set("hidden", w.bytes(prefix + "mesh/hidden.bin", m.hidden));+ if (m.hasUvs()) mesh.set("uvs", w.floats(prefix + "mesh/uvs.bin", &m.uvs[0].x, m.uvs.size(), 2));+ out.set("mesh", std::move(mesh));++ Json layers = Json::array();+ for (size_t i = 0; i < m.layers.size(); ++i) {+ Json l = Json::object();+ l.set("name", m.layers[i].name);+ l.set("weight", double(m.layers[i].weight));+ l.set("delta", w.vec3s(prefix + "layers/" + std::to_string(i) + ".bin", m.layers[i].delta));+ layers.push(std::move(l));+ }+ out.set("layers", std::move(layers));+}++// Reads a mesh from its `mesh` and `layers` manifest entries (size-checked against the blobs).+bool readMesh(Reader& r, const Json& mj, const Json& lj, Mesh& m, std::string& error) {+ const size_t nv = countOf(mj["vertex_count"]), nt = countOf(mj["triangle_count"]);+ if (nv == size_t(-1) || nt == size_t(-1)) {+ error = "Project mesh has no valid vertex/triangle count";+ return false;+ }+ m.triangles.resize(nt);+ if (!r.vec3s(mj["positions"], "positions", nv, m.positions) ||+ !r.uints(mj["triangles"], "triangles", nt, 3, nt ? &m.triangles[0].x : nullptr)) {+ error = r.error;+ return false;+ }+ for (const auto& t : m.triangles)+ if (t.x >= nv || t.y >= nv || t.z >= nv) {+ error = "Project triangles reference missing vertices";+ return false;+ }+ if (mj.has("mask")) {+ m.mask.resize(nv);+ r.floats(mj["mask"], "mask", nv, 1, m.mask.data());+ }+ if (mj.has("colors")) r.vec3s(mj["colors"], "colors", nv, m.colors);+ if (mj.has("polygroups")) {+ m.polygroups.resize(nt);+ r.uints(mj["polygroups"], "polygroups", nt, 1, m.polygroups.data());+ }+ if (mj.has("hidden")) {+ if (const uint8_t* p = r.blob(mj["hidden"], "hidden flags", Scalar::U8, 1, nt)) m.hidden.assign(p, p + nt);+ }+ if (mj.has("uvs")) {+ m.uvs.resize(nt * 3);+ r.floats(mj["uvs"], "uvs", nt * 3, 2, nt ? &m.uvs[0].x : nullptr);+ }+ if (lj.size()) {+ r.vec3s(mj["base"], "base positions", nv, m.base);+ for (size_t i = 0; i < lj.size() && r.error.empty(); ++i) {+ SculptLayer layer;+ layer.name = lj[i]["name"].asString();+ layer.weight = float(lj[i]["weight"].asNumber(1.0));+ r.vec3s(lj[i]["delta"], "layer offsets", nv, layer.delta);+ m.layers.push_back(std::move(layer));+ }+ }+ if (!r.error.empty()) {+ error = r.error;+ return false;+ }+ m.rebuildTopology();+ if (!m.layers.empty()) m.evaluateAll();+ m.recomputeAllNormals();+ return true;+}++// A SubTool read from a project, before it joins the document.+struct LoadedSubtool {+ std::string name, gozName;+ bool visible = true;+ int activeLayer = -1;+ Mesh mesh;+};++constexpr size_t kMaxProjectSubtools = 100000;} // namespacebool isProjectPath(const std::string& path) {@@ -147,37 +240,28 @@ bool isProjectPath(const std::string& path) {}bool saveProject(const std::string& path, const Document& doc, std::string& error) {- const Mesh& m = doc.mesh;Writer w;Json manifest = Json::object();manifest.set("format", kFormatName);manifest.set("version", kProjectVersion);manifest.set("app_version", SCULPTFORGE_VERSION);- Json mesh = Json::object();- mesh.set("vertex_count", double(m.vertexCount()));- mesh.set("triangle_count", double(m.triangleCount()));- mesh.set("positions", w.vec3s("mesh/positions.bin", m.positions));- mesh.set("triangles", w.uints("mesh/triangles.bin", m.triangles.empty() ? nullptr : &m.triangles[0].x,- m.triangleCount(), 3));- if (!m.layers.empty()) mesh.set("base", w.vec3s("mesh/base.bin", m.base));- if (m.hasMask()) mesh.set("mask", w.floats("mesh/mask.bin", m.mask.data(), m.mask.size(), 1));- if (m.hasColors()) mesh.set("colors", w.vec3s("mesh/colors.bin", m.colors));- if (m.hasPolygroups()) mesh.set("polygroups", w.uints("mesh/polygroups.bin", m.polygroups.data(), m.polygroups.size(), 1));- if (m.hasHidden()) mesh.set("hidden", w.bytes("mesh/hidden.bin", m.hidden));- if (m.hasUvs()) mesh.set("uvs", w.floats("mesh/uvs.bin", &m.uvs[0].x, m.uvs.size(), 2));- manifest.set("mesh", std::move(mesh));-- Json layers = Json::array();- for (size_t i = 0; i < m.layers.size(); ++i) {- Json l = Json::object();- l.set("name", m.layers[i].name);- l.set("weight", double(m.layers[i].weight));- l.set("delta", w.vec3s("layers/" + std::to_string(i) + ".bin", m.layers[i].delta));- layers.push(std::move(l));+ // Every SubTool with its mesh, layers and state; blobs live under subtools/<i>/.+ Json subtools = Json::array();+ for (int i = 0; i < doc.subtoolCount(); ++i) {+ const SubTool& s = doc.subtools[size_t(i)];+ const bool active = i == doc.activeSubtool;+ Json st = Json::object();+ st.set("name", s.name);+ st.set("visible", s.visible);+ writeMesh(w, "subtools/" + std::to_string(i) + "/", doc.subtoolMesh(i), st);+ st.set("active_layer", active ? doc.activeLayer : s.activeLayer);+ const std::string& gozName = active ? doc.gozName : s.gozName;+ if (!gozName.empty()) st.set("goz_name", gozName);+ subtools.push(std::move(st));}- manifest.set("layers", std::move(layers));- manifest.set("active_layer", doc.activeLayer);+ manifest.set("subtools", std::move(subtools));+ manifest.set("active_subtool", doc.activeSubtool);Json brushes = Json::array();for (const auto& b : doc.brushes) brushes.push(b.toJson());@@ -255,59 +339,34 @@ bool loadProject(const std::string& path, Document& doc, std::string& error) {return false;}- // Mesh- const Json& mj = manifest["mesh"];- const size_t nv = countOf(mj["vertex_count"]), nt = countOf(mj["triangle_count"]);- if (nv == size_t(-1) || nt == size_t(-1)) {- error = "Project mesh has no valid vertex/triangle count";- return false;- }- Mesh m;- m.triangles.resize(nt);- if (!r.vec3s(mj["positions"], "positions", nv, m.positions) ||- !r.uints(mj["triangles"], "triangles", nt, 3, nt ? &m.triangles[0].x : nullptr)) {- error = r.error;- return false;- }- for (const auto& t : m.triangles)- if (t.x >= nv || t.y >= nv || t.z >= nv) {- error = "Project triangles reference missing vertices";+ // SubTools: version 1 has one mesh at the top level, version 2 a "subtools" list.+ std::vector<LoadedSubtool> subtools;+ int activeSubtool = 0;+ if (version < 2) {+ LoadedSubtool s;+ s.name = "Sculpt";+ if (!readMesh(r, manifest["mesh"], manifest["layers"], s.mesh, error)) return false;+ s.activeLayer = int(manifest["active_layer"].asNumber(-1));+ subtools.push_back(std::move(s));+ } else {+ const Json& list = manifest["subtools"];+ if (!list.isArray() || list.size() == 0 || list.size() > kMaxProjectSubtools) {+ error = "Project has no valid SubTool list";return false;}- if (mj.has("mask")) {- m.mask.resize(nv);- r.floats(mj["mask"], "mask", nv, 1, m.mask.data());- }- if (mj.has("colors")) r.vec3s(mj["colors"], "colors", nv, m.colors);- if (mj.has("polygroups")) {- m.polygroups.resize(nt);- r.uints(mj["polygroups"], "polygroups", nt, 1, m.polygroups.data());- }- if (mj.has("hidden")) {- if (const uint8_t* p = r.blob(mj["hidden"], "hidden flags", Scalar::U8, 1, nt)) m.hidden.assign(p, p + nt);- }- if (mj.has("uvs")) {- m.uvs.resize(nt * 3);- r.floats(mj["uvs"], "uvs", nt * 3, 2, nt ? &m.uvs[0].x : nullptr);- }- const Json& lj = manifest["layers"];- if (lj.size()) {- r.vec3s(mj["base"], "base positions", nv, m.base);- for (size_t i = 0; i < lj.size(); ++i) {- SculptLayer layer;- layer.name = lj[i]["name"].asString();- layer.weight = float(lj[i]["weight"].asNumber(1.0));- r.vec3s(lj[i]["delta"], "layer offsets", nv, layer.delta);- m.layers.push_back(std::move(layer));+ for (const Json& sj : list.items()) {+ LoadedSubtool s;+ s.name = sj["name"].asString();+ if (s.name.empty()) s.name = "SubTool";+ s.visible = sj["visible"].asBool(true);+ s.gozName = sj["goz_name"].asString();+ if (!readMesh(r, sj["mesh"], sj["layers"], s.mesh, error)) return false;+ s.activeLayer = int(sj["active_layer"].asNumber(-1));+ subtools.push_back(std::move(s));}+ const double active = manifest["active_subtool"].asNumber(0);+ activeSubtool = active >= 0 && active < double(subtools.size()) ? int(active) : 0;}- if (!r.error.empty()) {- error = r.error;- return false;- }- m.rebuildTopology();- if (!m.layers.empty()) m.evaluateAll();- m.recomputeAllNormals();// SplatsSplatCloud splats;@@ -334,12 +393,23 @@ bool loadProject(const std::string& path, Document& doc, std::string& error) {for (size_t i = 0; i < n; ++i) splats.rotations[i] = glm::quat(rot[i * 4 + 3], rot[i * 4], rot[i * 4 + 1], rot[i * 4 + 2]);}- // Everything parsed: replace the scene.- doc.setMesh(std::move(m));+ // Everything parsed: replace the scene. SubTool 0 is checked out first; the others are added+ // behind it, given their layer and GoZ name, and the saved active SubTool is selected last.+ auto validLayer = [](int layer, const Mesh& m) { return layer >= 0 && layer < int(m.layers.size()) ? layer : -1; };+ doc.setMesh(std::move(subtools[0].mesh), subtools[0].name);+ doc.activeLayer = validLayer(subtools[0].activeLayer, doc.mesh);+ doc.gozName = subtools[0].gozName;+ doc.subtools[0].visible = subtools[0].visible;+ for (size_t i = 1; i < subtools.size(); ++i) {+ const int at = doc.addSubtool(std::move(subtools[i].mesh), subtools[i].name, false);+ SubTool& s = doc.subtools[size_t(at)];+ s.visible = subtools[i].visible;+ s.activeLayer = validLayer(subtools[i].activeLayer, s.mesh);+ s.gozName = subtools[i].gozName;+ }+ doc.selectSubtool(activeSubtool);doc.splats = std::move(splats);doc.splatsChanged();- const int active = int(manifest["active_layer"].asNumber(-1));- doc.activeLayer = active >= 0 && active < int(doc.mesh.layers.size()) ? active : -1;for (const auto& b : manifest["brushes"].items())if (b.isObject()) doc.addBrush(BrushRecipe::fromJson(b));doc.activeBrush = -1;@@ -357,12 +427,20 @@ bool loadProject(const std::string& path, Document& doc, std::string& error) {CommandResult openProjectCommand(Document& doc, const std::string& path) {std::string err;if (!loadProject(path, doc, err)) return {false, err};- std::string msg = "Opened project " + path + " (" + std::to_string(doc.mesh.triangleCount()) + " triangles";- if (!doc.mesh.layers.empty()) msg += ", " + std::to_string(doc.mesh.layers.size()) + " layers";+ std::string msg = "Opened project " + path + " (";+ if (doc.subtoolCount() > 1) msg += std::to_string(doc.subtoolCount()) + " SubTools, ";+ size_t tris = 0, layers = 0;+ for (int i = 0; i < doc.subtoolCount(); ++i) {+ tris += doc.subtoolMesh(i).triangleCount();+ layers += doc.subtoolMesh(i).layers.size();+ }+ msg += std::to_string(tris) + " triangles";+ if (layers) msg += ", " + std::to_string(layers) + " layers";if (!doc.splats.empty()) msg += ", " + std::to_string(doc.splats.size()) + " splats";return {true, msg + ")"};}+void registerProjectCommands(CommandRegistry& registry) {using T = ParamSpec::Type;registry.add({"save_project",diff --git a/src/core/Project.h b/src/core/Project.hindex d47cee6c..ed506cc6 100644--- a/src/core/Project.h+++ b/src/core/Project.h@@ -2,8 +2,8 @@// SPDX-License-Identifier: GPL-3.0-or-later//// Native project files (.sfproj): an uncompressed ZIP holding a JSON manifest-// ("manifest.json") and little-endian binary blobs for the mesh, its optional-// attributes, sculpt layers and any loaded Gaussian splats.+// ("manifest.json") and little-endian binary blobs for every SubTool (mesh,+// optional attributes, sculpt layers) and any loaded Gaussian splats.//// The manifest names every blob with its element type and count, so readers// ignore anything they don't know (forward compatible) and refuse files whose@@ -19,17 +19,20 @@namespace sf {-constexpr int kProjectVersion = 1;+// 1: one mesh. 2: a list of SubTools (version 1 files still load, as one SubTool).+constexpr int kProjectVersion = 2;constexpr const char* kProjectExtension = ".sfproj";// True for paths ending in .sfproj (any case).bool isProjectPath(const std::string& path);-// Writes `doc` (mesh, attributes, layers, splats, brush library, active layer+// Writes `doc` (every SubTool with its name, visibility, mesh, attributes,+// layers, active layer and GoZ name; the active SubTool; splats, brush library// and doc.projectSettings) to `path`. Does not change the document.bool saveProject(const std::string& path, const Document& doc, std::string& error);// Replaces the scene with the project at `path`. On failure `doc` is untouched.-// Sets doc.path, clears the edit history and marks the document clean.+// Restores the active SubTool, sets doc.path, gives every SubTool an empty+// edit history and marks the document clean.bool loadProject(const std::string& path, Document& doc, std::string& error);// loadProject wrapped as a command result (open_project, and `open` for .sfproj paths).CommandResult openProjectCommand(Document& doc, const std::string& path);diff --git a/src/core/SubTools.cpp b/src/core/SubTools.cppindex db9bfd20..5ed2e9a0 100644--- a/src/core/SubTools.cpp+++ b/src/core/SubTools.cpp@@ -86,6 +86,31 @@ Mesh mergedVisibleMesh(const Document& doc) {return mergeMeshes(meshes);}+std::vector<MeshObjectRef> visibleSubtoolObjects(const Document& doc) {+ if (doc.subtoolCount() == 1) {+ if (doc.mesh.triangleCount() == 0) return {};+ return {{doc.assetName(), &doc.mesh}};+ }+ std::vector<MeshObjectRef> out;+ for (int i = 0; i < doc.subtoolCount(); ++i)+ if (doc.subtools[size_t(i)].visible && doc.subtoolMesh(i).triangleCount())+ out.push_back({doc.subtools[size_t(i)].name, &doc.subtoolMesh(i)});+ return out;+}++void setSceneObjects(Document& doc, std::vector<MeshObject> objects, const std::string& fallbackName) {+ if (objects.empty()) {+ doc.setMesh(Mesh(), fallbackName);+ return;+ }+ auto nameOf = [&](size_t i) {+ return objects.size() == 1 || objects[i].name.empty() ? fallbackName : objects[i].name;+ };+ doc.setMesh(std::move(objects[0].mesh), nameOf(0));+ for (size_t i = 1; i < objects.size(); ++i) doc.addSubtool(std::move(objects[i].mesh), nameOf(i), false);+ doc.markClean();+}+std::vector<Mesh> splitByPolygroups(const Mesh& mesh) {std::vector<uint32_t> ids;for (uint32_t t = 0; t < mesh.triangleCount(); ++t) ids.push_back(mesh.polygroupAt(t));@@ -202,14 +227,27 @@ void registerSubToolCommands(CommandRegistry& reg) {Mesh m;std::string name;if (a.contains("path")) {- // Load through `open` into a scratch document, so every format and its attributes work.+ // Load through `open` into a scratch document, so every format and its attributes work;+ // each object in the file becomes its own SubTool.Document scratch;const std::string path = argString(a, "path");CommandResult r = CommandRegistry().execute(scratch, "open", {{"path", path}});if (!r.ok) return r;- if (scratch.mesh.triangleCount() == 0) return {false, path + " has no mesh to append"};- m = mergedVisibleMesh(scratch);- name = fileStem(path);+ if (scratch.subtoolCount() == 1) {+ if (scratch.mesh.triangleCount() == 0) return {false, path + " has no mesh to append"};+ m = std::move(scratch.mesh);+ name = fileStem(path);+ } else {+ const int first = doc.subtoolCount();+ size_t tris = 0;+ for (int i = 0; i < scratch.subtoolCount(); ++i) {+ tris += scratch.subtoolMesh(i).triangleCount();+ doc.addSubtool(std::move(scratch.subtoolMesh(i)), scratch.subtools[size_t(i)].name, false);+ }+ doc.selectSubtool(first);+ return {true, "Appended " + std::to_string(scratch.subtoolCount()) + " SubTools from " + path + " (" ++ countText(tris) + ")"};+ }} else {const std::string type = argString(a, "type", "sphere");const AABB scene = doc.visibleBounds();diff --git a/src/core/SubTools.h b/src/core/SubTools.hindex ff19ece8..ada2259a 100644--- a/src/core/SubTools.h+++ b/src/core/SubTools.h@@ -8,6 +8,7 @@#pragma once#include "core/Document.h"+#include "io/MeshObject.h"#include <string>#include <vector>@@ -26,6 +27,17 @@ Mesh mergeMeshes(const std::vector<const Mesh*>& meshes);// mesh). With one SubTool this is a copy of it, whether shown or not.Mesh mergedVisibleMesh(const Document& doc);+// The visible SubTools that have triangles, in list order and named after+// them, for exporters that write one object per SubTool. With a single SubTool+// it is that one (shown or not) named doc.assetName(), so one-object exports+// stay as they were.+std::vector<MeshObjectRef> visibleSubtoolObjects(const Document& doc);++// Replaces the scene with one SubTool per object (the first one active), named+// after the objects. A single object, or an unnamed one, is named+// `fallbackName` (e.g. the file name). Clears the edit history like setMesh.+void setSceneObjects(Document& doc, std::vector<MeshObject> objects, const std::string& fallbackName);+// One mesh per polygroup, in increasing group id order (empty if there's only one group).std::vector<Mesh> splitByPolygroups(const Mesh& mesh);// One mesh per connected piece, largest first (empty if the mesh is one piece).diff --git a/src/io/FbxIO.cpp b/src/io/FbxIO.cppindex 691fda91..4e8314d9 100644--- a/src/io/FbxIO.cpp+++ b/src/io/FbxIO.cpp@@ -4,6 +4,7 @@#include "ufbx.h"+#include <algorithm>#include <cstring>#include <map>#include <filesystem>@@ -270,10 +271,21 @@ Node makeModel(int64_t id, const std::string& name, const std::string& type) {bool saveFbx(const std::string& path, const std::string& name, const std::vector<const Mesh*>& lods,const FbxExportOptions& o, std::string& error) {- if (lods.empty() || !lods[0] || lods[0]->triangleCount() == 0) {+ return saveFbx(path, std::vector<FbxObject>{{name, lods}}, o, error);+}++bool saveFbx(const std::string& path, const std::vector<FbxObject>& fbxObjects, const FbxExportOptions& o,+ std::string& error) {+ if (fbxObjects.empty()) {error = "The mesh is empty";return false;}+ for (const auto& obj : fbxObjects)+ if (obj.lods.empty() || !obj.lods[0] || obj.lods[0]->triangleCount() == 0 ||+ std::find(obj.lods.begin(), obj.lods.end(), nullptr) != obj.lods.end()) {+ error = "The mesh is empty";+ return false;+ }Ids ids;Node root;addHeader(root);@@ -292,7 +304,7 @@ bool saveFbx(const std::string& path, const std::string& name, const std::vectorNode connections("Connections");int models = 0, geometries = 0, deformers = 0, attributes = 0;- // Material shared by every LOD.+ // Material shared by every object and LOD.const int64_t materialId = ids();{Node& mat = objects.add("Material").i64(materialId).objName(o.materialName, "Material").str("");@@ -307,99 +319,103 @@ bool saveFbx(const std::string& path, const std::string& name, const std::vectorprop70(p70, "ShininessExponent", "double", "Number", "").f64(20.0);}- const bool grouped = lods.size() > 1;- int64_t parentId = 0;- if (grouped) {- const int64_t groupId = ids(), attrId = ids();- Node attr("NodeAttribute");- attr.i64(attrId).objName("", "NodeAttribute").str("LodGroup");- Node& p70 = attr.add("Properties70");- prop70(p70, "MinMaxDistance", "bool", "", "").i32(0);- prop70(p70, "MinDistance", "double", "Number", "").f64(-100.0);- prop70(p70, "MaxDistance", "double", "Number", "").f64(100.0);- prop70(p70, "WorldSpace", "bool", "", "").i32(0);- prop70(p70, "ThresholdsUsedAsPercentage", "bool", "", "").i32(1);- for (size_t i = 1; i < lods.size(); ++i)- prop70(p70, "Thresholds|Level" + std::to_string(i - 1), "Distance", "", "")- .f32(100.0f / float(1u << i))- .str("cm");- for (size_t i = 0; i < lods.size(); ++i)- prop70(p70, "DisplayLevels|Level" + std::to_string(i), "enum", "", "").i32(0);- attr.add("TypeFlags").str("LodGroup");- objects.children.push_back(std::move(attr));- objects.children.push_back(makeModel(groupId, name, "LodGroup"));- addConnection(connections, "OO", attrId, groupId);- addConnection(connections, "OO", groupId, 0);- parentId = groupId;- ++models;- ++attributes;- }-- for (size_t level = 0; level < lods.size(); ++level) {- const Mesh& mesh = *lods[level];- const std::string meshName = grouped ? name + "_LOD" + std::to_string(level) : name;- const int64_t modelId = ids(), geometryId = ids();- objects.children.push_back(makeGeometry(geometryId, meshName, mesh, o.scale));- objects.children.push_back(makeModel(modelId, meshName, "Mesh"));- addConnection(connections, "OO", geometryId, modelId);- addConnection(connections, "OO", materialId, modelId);+ for (const FbxObject& object : fbxObjects) {+ const std::string& name = object.name;+ const std::vector<const Mesh*>& lods = object.lods;+ const bool grouped = lods.size() > 1;+ int64_t parentId = 0;if (grouped) {- // Like Maya/FBX SDK files: LOD group -> one Null per level -> the level's mesh.- const int64_t levelId = ids(), levelAttrId = ids();+ const int64_t groupId = ids(), attrId = ids();Node attr("NodeAttribute");- attr.i64(levelAttrId).objName("", "NodeAttribute").str("Null");- attr.add("TypeFlags").str("Null");+ attr.i64(attrId).objName("", "NodeAttribute").str("LodGroup");+ Node& p70 = attr.add("Properties70");+ prop70(p70, "MinMaxDistance", "bool", "", "").i32(0);+ prop70(p70, "MinDistance", "double", "Number", "").f64(-100.0);+ prop70(p70, "MaxDistance", "double", "Number", "").f64(100.0);+ prop70(p70, "WorldSpace", "bool", "", "").i32(0);+ prop70(p70, "ThresholdsUsedAsPercentage", "bool", "", "").i32(1);+ for (size_t i = 1; i < lods.size(); ++i)+ prop70(p70, "Thresholds|Level" + std::to_string(i - 1), "Distance", "", "")+ .f32(100.0f / float(1u << i))+ .str("cm");+ for (size_t i = 0; i < lods.size(); ++i)+ prop70(p70, "DisplayLevels|Level" + std::to_string(i), "enum", "", "").i32(0);+ attr.add("TypeFlags").str("LodGroup");objects.children.push_back(std::move(attr));- objects.children.push_back(makeModel(levelId, "LOD_" + std::to_string(level), "Null"));- addConnection(connections, "OO", levelAttrId, levelId);- addConnection(connections, "OO", levelId, parentId);- addConnection(connections, "OO", modelId, levelId);+ objects.children.push_back(makeModel(groupId, name, "LodGroup"));+ addConnection(connections, "OO", attrId, groupId);+ addConnection(connections, "OO", groupId, 0);+ parentId = groupId;++models;++attributes;- } else {- addConnection(connections, "OO", modelId, parentId);}- ++models;- ++geometries;-- // Sculpt layers -> blend shape channels (LOD0 only).- if (level == 0 && o.layers && !mesh.layers.empty()) {- const int64_t blendId = ids();- Node& blend = objects.add("Deformer").i64(blendId).objName(meshName, "Deformer").str("BlendShape");- blend.add("Version").i32(100);- addConnection(connections, "OO", blendId, geometryId);- ++deformers;- for (const auto& layer : mesh.layers) {- const int64_t channelId = ids(), shapeId = ids();- Node& channel = objects.add("Deformer").i64(channelId).objName(layer.name, "SubDeformer").str("BlendShapeChannel");- channel.add("Version").i32(100);- channel.add("DeformPercent").f64(double(layer.weight) * 100.0);-- std::vector<int32_t> indexes;- std::vector<double> offsets;- for (uint32_t v = 0; v < layer.delta.size(); ++v) {- if (layer.delta[v] == glm::vec3(0.0f)) continue;- indexes.push_back(int32_t(v));- const glm::vec3 d = layer.delta[v] * o.scale;- offsets.insert(offsets.end(), {double(d.x), double(d.y), double(d.z)});- }- if (indexes.empty()) {- indexes.push_back(0);- offsets.insert(offsets.end(), {0.0, 0.0, 0.0});- }- channel.add("FullWeights").f64s(std::vector<double>(indexes.size(), 100.0));- Node& shape = objects.add("Geometry").i64(shapeId).objName(layer.name, "Geometry").str("Shape");- shape.add("Properties70");- shape.add("Version").i32(100);- shape.add("Indexes").i32s(indexes);- shape.add("Vertices").f64s(offsets);- std::vector<double> shapeNormals(offsets.size(), 0.0);- shapeNormals[0] = 1.1e-6; // all-zero shape normals break some importers (Unity)- shape.add("Normals").f64s(shapeNormals);- addConnection(connections, "OO", shapeId, channelId);- addConnection(connections, "OO", channelId, blendId);++ for (size_t level = 0; level < lods.size(); ++level) {+ const Mesh& mesh = *lods[level];+ const std::string meshName = grouped ? name + "_LOD" + std::to_string(level) : name;+ const int64_t modelId = ids(), geometryId = ids();+ objects.children.push_back(makeGeometry(geometryId, meshName, mesh, o.scale));+ objects.children.push_back(makeModel(modelId, meshName, "Mesh"));+ addConnection(connections, "OO", geometryId, modelId);+ addConnection(connections, "OO", materialId, modelId);+ if (grouped) {+ // Like Maya/FBX SDK files: LOD group -> one Null per level -> the level's mesh.+ const int64_t levelId = ids(), levelAttrId = ids();+ Node attr("NodeAttribute");+ attr.i64(levelAttrId).objName("", "NodeAttribute").str("Null");+ attr.add("TypeFlags").str("Null");+ objects.children.push_back(std::move(attr));+ objects.children.push_back(makeModel(levelId, "LOD_" + std::to_string(level), "Null"));+ addConnection(connections, "OO", levelAttrId, levelId);+ addConnection(connections, "OO", levelId, parentId);+ addConnection(connections, "OO", modelId, levelId);+ ++models;+ ++attributes;+ } else {+ addConnection(connections, "OO", modelId, parentId);+ }+ ++models;+ ++geometries;++ // Sculpt layers -> blend shape channels (LOD0 only).+ if (level == 0 && o.layers && !mesh.layers.empty()) {+ const int64_t blendId = ids();+ Node& blend = objects.add("Deformer").i64(blendId).objName(meshName, "Deformer").str("BlendShape");+ blend.add("Version").i32(100);+ addConnection(connections, "OO", blendId, geometryId);++deformers;- ++geometries;+ for (const auto& layer : mesh.layers) {+ const int64_t channelId = ids(), shapeId = ids();+ Node& channel = objects.add("Deformer").i64(channelId).objName(layer.name, "SubDeformer").str("BlendShapeChannel");+ channel.add("Version").i32(100);+ channel.add("DeformPercent").f64(double(layer.weight) * 100.0);++ std::vector<int32_t> indexes;+ std::vector<double> offsets;+ for (uint32_t v = 0; v < layer.delta.size(); ++v) {+ if (layer.delta[v] == glm::vec3(0.0f)) continue;+ indexes.push_back(int32_t(v));+ const glm::vec3 d = layer.delta[v] * o.scale;+ offsets.insert(offsets.end(), {double(d.x), double(d.y), double(d.z)});+ }+ if (indexes.empty()) {+ indexes.push_back(0);+ offsets.insert(offsets.end(), {0.0, 0.0, 0.0});+ }+ channel.add("FullWeights").f64s(std::vector<double>(indexes.size(), 100.0));+ Node& shape = objects.add("Geometry").i64(shapeId).objName(layer.name, "Geometry").str("Shape");+ shape.add("Properties70");+ shape.add("Version").i32(100);+ shape.add("Indexes").i32s(indexes);+ shape.add("Vertices").f64s(offsets);+ std::vector<double> shapeNormals(offsets.size(), 0.0);+ shapeNormals[0] = 1.1e-6; // all-zero shape normals break some importers (Unity)+ shape.add("Normals").f64s(shapeNormals);+ addConnection(connections, "OO", shapeId, channelId);+ addConnection(connections, "OO", channelId, blendId);+ ++deformers;+ ++geometries;+ }}}}@@ -470,9 +486,15 @@ bool isLowerLod(const ufbx_node* node) {glm::vec3 toVec(const ufbx_vec3& v) { return {float(v.x), float(v.y), float(v.z)}; }-} // namespace+// An object's name: its LOD group's for a LOD0 mesh, else the node's.+std::string objectName(const ufbx_node* node) {+ for (const ufbx_node* p = node->parent; p; p = p->parent)+ if (p->attrib_type == UFBX_ELEMENT_LOD_GROUP && p->name.length) return std::string(p->name.data, p->name.length);+ return std::string(node->name.data, node->name.length);+}-bool loadFbx(const std::string& path, Mesh& out, std::string& error) {+// Merges every mesh node into one object, or (split) makes one object per node.+bool readFbx(const std::string& path, bool split, std::vector<MeshObject>& out, std::string& error) {ufbx_load_opts opts = {};opts.target_axes = ufbx_axes_right_handed_y_up;opts.target_unit_meters = 1.0;@@ -485,14 +507,22 @@ bool loadFbx(const std::string& path, Mesh& out, std::string& error) {error = "Cannot read FBX: " + std::string(buf);return false;}- Mesh m;- std::vector<SculptLayer> layers;- std::map<std::string, size_t> layerIndex;+ struct Gathered {+ std::string name;+ Mesh m;+ std::vector<SculptLayer> layers;+ std::map<std::string, size_t> layerIndex;+ };+ std::vector<Gathered> objects(split ? 0 : 1);std::vector<uint32_t> tri;for (size_t ni = 0; ni < scene->nodes.count; ++ni) {const ufbx_node* node = scene->nodes.data[ni];const ufbx_mesh* mesh = node->mesh;if (!mesh || !node->visible || isLowerLod(node)) continue;+ if (split) objects.push_back({objectName(node), {}, {}, {}});+ Mesh& m = objects.back().m;+ std::vector<SculptLayer>& layers = objects.back().layers;+ std::map<std::string, size_t>& layerIndex = objects.back().layerIndex;const uint32_t base = uint32_t(m.positions.size());const ufbx_matrix& xf = node->geometry_to_world;const ufbx_vec3 zero = {};@@ -526,13 +556,30 @@ bool loadFbx(const std::string& path, Mesh& out, std::string& error) {}}ufbx_free_scene(scene);- if (m.triangles.empty()) {+ out.clear();+ for (auto& o : objects) {+ if (o.m.triangles.empty()) continue;+ for (auto& l : o.layers) l.delta.resize(o.m.positions.size(), glm::vec3(0.0f));+ out.push_back({o.name, weldImported(o.m, o.layers)});+ }+ if (out.empty()) {error = "No meshes found in " + path;return false;}- for (auto& l : layers) l.delta.resize(m.positions.size(), glm::vec3(0.0f));- out = weldImported(m, layers);return true;}+} // namespace++bool loadFbx(const std::string& path, Mesh& out, std::string& error) {+ std::vector<MeshObject> objects;+ if (!readFbx(path, false, objects, error)) return false;+ out = std::move(objects.front().mesh);+ return true;+}++bool loadFbx(const std::string& path, std::vector<MeshObject>& out, std::string& error) {+ return readFbx(path, true, out, error);+}+} // namespace sfdiff --git a/src/io/FbxIO.h b/src/io/FbxIO.hindex 22741831..bcfb678f 100644--- a/src/io/FbxIO.h+++ b/src/io/FbxIO.h@@ -12,6 +12,7 @@#pragma once#include "core/Mesh.h"+#include "io/MeshObject.h"#include <string>#include <vector>@@ -31,9 +32,24 @@ struct FbxExportOptions {bool saveFbx(const std::string& path, const std::string& name, const std::vector<const Mesh*>& lods,const FbxExportOptions& options, std::string& error);+// One object (SubTool) of a multi-object export: its LOD chain (lods[0] = full resolution).+struct FbxObject {+ std::string name;+ std::vector<const Mesh*> lods;+};+// Every object becomes its own model under the scene root, named after it,+// with its own blend shapes. An object with several LODs becomes its own LOD+// group (`name`, children `name_LOD0..N`); Unreal's "Combine Meshes" then+// builds one static mesh whose LOD n holds every object's level n.+bool saveFbx(const std::string& path, const std::vector<FbxObject>& objects, const FbxExportOptions& options,+ std::string& error);+// Reads .fbx (binary or ASCII, any version) via ufbx: all visible meshes are// merged in world space (Y-up, 1 unit = 1 m, matching saveFbx with scale 100),// only LOD0 of LOD groups is taken, and blend shapes become sculpt layers.bool loadFbx(const std::string& path, Mesh& out, std::string& error);+// The same, but each visible mesh node is its own object, named after the+// node (or after its LOD group, for a LOD0 mesh).+bool loadFbx(const std::string& path, std::vector<MeshObject>& out, std::string& error);} // namespace sfdiff --git a/src/io/GltfIO.cpp b/src/io/GltfIO.cppindex f43612cf..b19f25f6 100644--- a/src/io/GltfIO.cpp+++ b/src/io/GltfIO.cpp@@ -91,17 +91,20 @@ bool writeGlbFile(const std::string& path, std::string jsonStr, const std::vecto} // namespacebool saveGlb(const std::string& path, const Mesh& mesh, const std::string& name, std::string& error) {- if (mesh.triangleCount() == 0) {- error = "Mesh is empty";+ return saveGlb(path, std::vector<MeshObjectRef>{{name, &mesh}}, name, error);+}++bool saveGlb(const std::string& path, const std::vector<MeshObjectRef>& objects, const std::string& sceneName,+ std::string& error) {+ if (objects.empty()) {+ error = "Nothing to export";return false;}-- // Base shape and its normals.- Mesh baseMesh;- baseMesh.positions = mesh.basePositions();- baseMesh.triangles = mesh.triangles;- baseMesh.rebuildTopology();- baseMesh.recomputeAllNormals();+ for (const auto& o : objects)+ if (!o.mesh || o.mesh->triangleCount() == 0) {+ error = "Mesh is empty";+ return false;+ }BinWriter bin;struct View {@@ -109,7 +112,7 @@ bool saveGlb(const std::string& path, const Mesh& mesh, const std::string& name,bool indices;};std::vector<View> views;- std::ostringstream accessors;+ std::ostringstream accessors, meshes, nodes;int accessorCount = 0;auto addVec3 = [&](const std::vector<glm::vec3>& v, bool withMinMax) {@@ -126,42 +129,61 @@ bool saveGlb(const std::string& path, const Mesh& mesh, const std::string& name,return accessorCount++;};- int posAcc = addVec3(baseMesh.positions, true);- int nrmAcc = addVec3(baseMesh.normals, false);- const bool colors = mesh.hasColors() && mesh.colors.size() == mesh.vertexCount();- int colorAcc = colors ? addVec3(mesh.colors, false) : -1; // polypaint as COLOR_0 (linear)-- size_t idxOff = bin.append(mesh.triangles.data(), mesh.triangleCount() * sizeof(glm::uvec3));- views.push_back({idxOff, mesh.triangleCount() * sizeof(glm::uvec3), true});- accessors << ",{\"bufferView\":" << views.size() - 1 << ",\"componentType\":5125,\"count\":"- << mesh.triangleCount() * 3 << ",\"type\":\"SCALAR\"}";- int idxAcc = accessorCount++;-- std::vector<int> targetAccs;- for (const auto& l : mesh.layers) targetAccs.push_back(addVec3(l.delta, true));+ // One node and one mesh per object, each with its own morph targets.+ for (size_t oi = 0; oi < objects.size(); ++oi) {+ const Mesh& mesh = *objects[oi].mesh;+ const std::string& name = objects[oi].name;+ // Base shape and its normals.+ Mesh baseMesh;+ baseMesh.positions = mesh.basePositions();+ baseMesh.triangles = mesh.triangles;+ baseMesh.rebuildTopology();+ baseMesh.recomputeAllNormals();++ int posAcc = addVec3(baseMesh.positions, true);+ int nrmAcc = addVec3(baseMesh.normals, false);+ const bool colors = mesh.hasColors() && mesh.colors.size() == mesh.vertexCount();+ int colorAcc = colors ? addVec3(mesh.colors, false) : -1; // polypaint as COLOR_0 (linear)++ size_t idxOff = bin.append(mesh.triangles.data(), mesh.triangleCount() * sizeof(glm::uvec3));+ views.push_back({idxOff, mesh.triangleCount() * sizeof(glm::uvec3), true});+ accessors << ",{\"bufferView\":" << views.size() - 1 << ",\"componentType\":5125,\"count\":"+ << mesh.triangleCount() * 3 << ",\"type\":\"SCALAR\"}";+ int idxAcc = accessorCount++;++ std::vector<int> targetAccs;+ for (const auto& l : mesh.layers) targetAccs.push_back(addVec3(l.delta, true));++ nodes << (oi ? "," : "") << "{\"mesh\":" << oi << ",\"name\":\"" << jsonEscape(name) << "\"}";+ std::ostringstream& json = meshes; // this object's entry in "meshes"+ json << (oi ? "," : "") << "{\"name\":\"" << jsonEscape(name) << "\",\"primitives\":[{\"attributes\":{\"POSITION\":"+ << posAcc << ",\"NORMAL\":" << nrmAcc;+ if (colors) json << ",\"COLOR_0\":" << colorAcc;+ json << "},\"indices\":" << idxAcc << ",\"mode\":4";+ if (!mesh.layers.empty()) {+ json << ",\"targets\":[";+ for (size_t i = 0; i < targetAccs.size(); ++i) json << (i ? "," : "") << "{\"POSITION\":" << targetAccs[i] << "}";+ json << "]";+ }+ json << "}]";+ if (!mesh.layers.empty()) {+ json << ",\"weights\":[";+ for (size_t i = 0; i < mesh.layers.size(); ++i) json << (i ? "," : "") << mesh.layers[i].weight;+ json << "],\"extras\":{\"targetNames\":[";+ for (size_t i = 0; i < mesh.layers.size(); ++i)+ json << (i ? "," : "") << "\"" << jsonEscape(mesh.layers[i].name) << "\"";+ json << "]}";+ }+ json << "}";+ }std::ostringstream json;- json << "{\"asset\":{\"version\":\"2.0\",\"generator\":\"SculptForge\"},\"scene\":0,"- << "\"scenes\":[{\"nodes\":[0]}],\"nodes\":[{\"mesh\":0,\"name\":\"" << jsonEscape(name) << "\"}],"- << "\"meshes\":[{\"name\":\"" << jsonEscape(name) << "\",\"primitives\":[{\"attributes\":{\"POSITION\":"- << posAcc << ",\"NORMAL\":" << nrmAcc;- if (colors) json << ",\"COLOR_0\":" << colorAcc;- json << "},\"indices\":" << idxAcc << ",\"mode\":4";- if (!mesh.layers.empty()) {- json << ",\"targets\":[";- for (size_t i = 0; i < targetAccs.size(); ++i) json << (i ? "," : "") << "{\"POSITION\":" << targetAccs[i] << "}";- json << "]";- }- json << "}]";- if (!mesh.layers.empty()) {- json << ",\"weights\":[";- for (size_t i = 0; i < mesh.layers.size(); ++i) json << (i ? "," : "") << mesh.layers[i].weight;- json << "],\"extras\":{\"targetNames\":[";- for (size_t i = 0; i < mesh.layers.size(); ++i)- json << (i ? "," : "") << "\"" << jsonEscape(mesh.layers[i].name) << "\"";- json << "]}";- }- json << "}],\"accessors\":[" << accessors.str() << "],\"bufferViews\":[";+ json << "{\"asset\":{\"version\":\"2.0\",\"generator\":\"SculptForge\"},\"scene\":0,\"scenes\":[{";+ if (objects.size() > 1) json << "\"name\":\"" << jsonEscape(sceneName) << "\",";+ json << "\"nodes\":[";+ for (size_t i = 0; i < objects.size(); ++i) json << (i ? "," : "") << i;+ json << "]}],\"nodes\":[" << nodes.str() << "],\"meshes\":[" << meshes.str() << "],\"accessors\":["+ << accessors.str() << "],\"bufferViews\":[";for (size_t i = 0; i < views.size(); ++i)json << (i ? "," : "") << "{\"buffer\":0,\"byteOffset\":" << views[i].offset << ",\"byteLength\":"<< views[i].length << ",\"target\":" << (views[i].indices ? 34963 : 34962) << "}";@@ -403,7 +425,20 @@ glm::mat4 nodeMatrix(const Json& node) {} // namespace-bool loadGltf(const std::string& path, Mesh& out, std::string& error, SplatCloud* splatsOut) {+namespace {++// Triangles gathered for one object (a node with a mesh, or the whole file when merging).+struct GltfObject {+ std::string name;+ Mesh m;+ std::vector<std::vector<glm::vec3>> targetDeltas;+ std::vector<std::string> targetNames;+ std::vector<float> targetWeights;+ bool targetsConsistent = true;+};++bool readGltf(const std::string& path, bool split, std::vector<MeshObject>& out, std::string& error,+ SplatCloud* splatsOut) {const std::filesystem::path fsPath(std::u8string(path.begin(), path.end()));std::vector<uint8_t> file;if (!readFile(fsPath, file)) {@@ -466,11 +501,7 @@ bool loadGltf(const std::string& path, Mesh& out, std::string& error, SplatCloudr.buffers.push_back(std::move(data));}- Mesh m;- std::vector<std::vector<glm::vec3>> targetDeltas;- std::vector<std::string> targetNames;- std::vector<float> targetWeights;- bool targetsConsistent = true;+ std::vector<GltfObject> objects(1);SplatCloud splats;auto readSplats = [&](const Json& prim, const glm::mat4& world) -> bool {@@ -527,6 +558,19 @@ bool loadGltf(const std::string& path, Mesh& out, std::string& error, SplatCloudconst glm::mat3 linear(world);if (node["mesh"].isNumber()) {const Json& mesh = r.doc["meshes"][size_t(node["mesh"].asNumber())];+ // Splitting: every node with a mesh is its own object (its primitives are material slots).+ if (split && (objects.size() > 1 || !objects[0].m.triangles.empty() || !objects[0].name.empty()))+ objects.emplace_back();+ GltfObject& o = objects.back();+ if (split && o.name.empty()) {+ o.name = node["name"].isString() ? node["name"].asString() : mesh["name"].asString();+ if (o.name.empty()) o.name = "Mesh " + std::to_string(objects.size());+ }+ Mesh& m = o.m;+ auto& targetDeltas = o.targetDeltas;+ auto& targetNames = o.targetNames;+ auto& targetWeights = o.targetWeights;+ bool& targetsConsistent = o.targetsConsistent;for (const Json& prim : mesh["primitives"].items()) {const Json& gs = prim["extensions"]["KHR_gaussian_splatting"];if (gs.isObject()) {@@ -613,25 +657,36 @@ bool loadGltf(const std::string& path, Mesh& out, std::string& error, SplatCloudauto stem = std::filesystem::path(fsPath).stem().u8string();splats.name = std::string(stem.begin(), stem.end());*splatsOut = std::move(splats);- if (m.triangles.empty()) {- out = Mesh();- return true;- }}- if (m.triangles.empty()) {+ out.clear();+ for (auto& o : objects) {+ if (o.m.triangles.empty()) continue;+ // Weld vertices split along UV/normal seams so strokes don't tear the surface.+ std::vector<SculptLayer> layers;+ if (o.targetsConsistent)+ for (size_t k = 0; k < o.targetDeltas.size(); ++k)+ layers.push_back({o.targetNames[k], std::move(o.targetDeltas[k]), o.targetWeights[k]});+ if (!o.m.colors.empty()) o.m.colors.resize(o.m.positions.size(), glm::vec3(1.0f));+ out.push_back({o.name, weldImported(o.m, layers)});+ }+ if (out.empty() && !(splatsOut && !splatsOut->empty())) {error = r.error.empty() ? "No triangle meshes found in " + path : r.error;return false;}+ return true;+}- // Weld vertices split along UV/normal seams so strokes don't tear the surface.- std::vector<SculptLayer> layers;- if (targetsConsistent)- for (size_t k = 0; k < targetDeltas.size(); ++k)- layers.push_back({targetNames[k], std::move(targetDeltas[k]), targetWeights[k]});- if (!m.colors.empty()) m.colors.resize(m.positions.size(), glm::vec3(1.0f));- Mesh welded = weldImported(m, layers);- out = std::move(welded);+} // namespace++bool loadGltf(const std::string& path, Mesh& out, std::string& error, SplatCloud* splatsOut) {+ std::vector<MeshObject> objects;+ if (!readGltf(path, false, objects, error, splatsOut)) return false;+ out = objects.empty() ? Mesh() : std::move(objects.front().mesh);return true;}+bool loadGltf(const std::string& path, std::vector<MeshObject>& out, std::string& error, SplatCloud* splatsOut) {+ return readGltf(path, true, out, error, splatsOut);+}+} // namespace sfdiff --git a/src/io/GltfIO.h b/src/io/GltfIO.hindex 7d2503f6..417d467e 100644--- a/src/io/GltfIO.h+++ b/src/io/GltfIO.h@@ -4,6 +4,7 @@#include "core/Mesh.h"#include "core/Splats.h"+#include "io/MeshObject.h"#include <string>@@ -14,6 +15,10 @@ namespace sf {// the default, and target names stored in mesh.extras.targetNames (the// convention read by Blender, Unity, Unreal, Godot and three.js).bool saveGlb(const std::string& path, const Mesh& mesh, const std::string& name, std::string& error);+// One node and mesh per object (SubTool), each with its own morph targets;+// with several, the scene is called `sceneName`.+bool saveGlb(const std::string& path, const std::vector<MeshObjectRef>& objects, const std::string& sceneName,+ std::string& error);// Reads .glb or .gltf (embedded/data-URI or external buffers). All triangle// primitives in the default scene are merged with their node transforms@@ -22,6 +27,9 @@ bool saveGlb(const std::string& path, const Mesh& mesh, const std::string& name,// With `splats`, a KHR_gaussian_splatting primitive is read into it too (the// first one found); a file with only splats then succeeds with an empty mesh.bool loadGltf(const std::string& path, Mesh& out, std::string& error, SplatCloud* splats = nullptr);+// The same, but each node with a mesh is its own object (named after the node,+// else its mesh), in world space. A splat-only file gives no objects.+bool loadGltf(const std::string& path, std::vector<MeshObject>& out, std::string& error, SplatCloud* splats = nullptr);// Writes Gaussian splats as a KHR_gaussian_splatting POINTS primitive (with a// COLOR_0 point-cloud fallback for viewers without splat support).diff --git a/src/io/GozCommands.cpp b/src/io/GozCommands.cppindex fbb47828..6a422537 100644--- a/src/io/GozCommands.cpp+++ b/src/io/GozCommands.cpp@@ -2,9 +2,11 @@// SPDX-License-Identifier: GPL-3.0-or-later#include "io/GozCommands.h"+#include "core/SubTools.h"#include "io/GozIO.h"#include "io/StlIO.h"+#include <algorithm>#include <filesystem>namespace sf {@@ -33,6 +35,24 @@ std::string sendName(const Document& doc, const Args& a) {return name;}+// The GoZ name of SubTool `i` (active or not).+std::string& subtoolGozName(Document& doc, int i) {+ return i == doc.activeSubtool ? doc.gozName : doc.subtools[size_t(i)].gozName;+}++// Visible SubTools with triangles, as the GoZ objects to write: the name each came from ZBrush with,+// else its SubTool name. `indices` receives the SubTool of each object.+std::vector<MeshObjectRef> gozObjects(Document& doc, std::vector<int>& indices) {+ std::vector<MeshObjectRef> out;+ for (int i = 0; i < doc.subtoolCount(); ++i) {+ if (!doc.subtools[size_t(i)].visible || doc.subtoolMesh(i).triangleCount() == 0) continue;+ const std::string& goz = subtoolGozName(doc, i);+ out.push_back({goz.empty() ? doc.subtools[size_t(i)].name : goz, &doc.subtoolMesh(i)});+ indices.push_back(i);+ }+ return out;+}+} // namespacevoid registerGozCommands(CommandRegistry& reg) {@@ -48,16 +68,18 @@ void registerGozCommands(CommandRegistry& reg) {GozInfo info;std::string err;if (!loadGoz(path, m, err, &info)) return {false, err};- doc.setMesh(std::move(m));+ const std::string name = info.name.empty() ? fileStem(path) : info.name;+ doc.setMesh(std::move(m), name);doc.path.clear();- doc.gozName = info.name.empty() ? fileStem(path) : info.name;+ doc.gozName = name;std::string msg = "Opened GoZ " + doc.gozName + " (" + meshSummary(doc.mesh) + ")";if (!err.empty()) msg += "; " + err;return {true, msg};}});reg.add({"goz_export",- "Export the mesh as a ZBrush GoZ file (.GoZ) with polygroups, UVs, mask and polypaint.",+ "Export the mesh as a ZBrush GoZ file (.GoZ) with polygroups, UVs, mask and polypaint. With several "+ "visible SubTools, each is written next to `path` as <name>_<SubTool>.GoZ.",{{"path", T::String, "Output .GoZ path (UTF-8).", true},{"name", T::String, "SubTool name. Default: the name it came from ZBrush with, else the document name.", false},{"quads", T::Bool, "Rebuild quads from triangle pairs made by GoZ import. Default true.", false}},@@ -66,56 +88,110 @@ void registerGozCommands(CommandRegistry& reg) {GozWriteOptions o;o.quads = argBool(a, "quads", true);std::string err;- const std::string name = argString(a, "name", doc.gozName.empty() ? fileStem(path) : doc.gozName);- if (!saveGoz(path, doc.mesh, name, err, o)) return {false, err};- return {true, "Exported " + path};+ std::vector<int> indices;+ const auto objects = gozObjects(doc, indices);+ if (doc.subtoolCount() == 1 || objects.size() == 1) {+ const int i = objects.size() == 1 ? indices[0] : doc.activeSubtool;+ const std::string& goz = subtoolGozName(doc, i);+ const std::string name = argString(a, "name", goz.empty() ? fileStem(path) : goz);+ if (!saveGoz(path, doc.subtoolMesh(i), name, err, o)) return {false, err};+ return {true, "Exported " + path};+ }+ if (objects.empty()) return {false, "Nothing visible to export"};+ // One file per SubTool beside `path`: <stem>_<object>.GoZ.+ const std::filesystem::path base(std::u8string(path.begin(), path.end()));+ std::vector<std::string> used;+ for (const auto& obj : objects) {+ std::string name = gozObjectName(obj.name);+ const std::string wanted = name;+ for (int k = 2; std::find(used.begin(), used.end(), name) != used.end(); ++k) name = wanted + "_" + std::to_string(k);+ used.push_back(name);+ const std::string file = fileStem(path) + "_" + name + ".GoZ";+ const auto out = (base.parent_path() / std::u8string(file.begin(), file.end())).u8string();+ if (!saveGoz(std::string(out.begin(), out.end()), *obj.mesh, name, err, o)) return {false, err};+ }+ return {true, "Exported " + std::to_string(objects.size()) + " SubTools as " + fileStem(path) + "_*.GoZ"};}});reg.add({"goz_send",- "Send the mesh to ZBrush through the GoZ bridge (Windows/macOS): writes it to the shared GoZ folder, "- "lists it in GoZ_ObjectList.txt and notifies or starts ZBrush. Sending a mesh received from ZBrush "- "updates that SubTool.",- {{"name", T::String, "SubTool name. Default: the name it came from ZBrush with, else the document name.", false},+ "Send the visible SubTools to ZBrush through the GoZ bridge (Windows/macOS): writes each to the shared "+ "GoZ folder, lists them in GoZ_ObjectList.txt and notifies or starts ZBrush. Sending meshes received "+ "from ZBrush updates those SubTools.",+ {{"name", T::String, "SubTool name (single SubTool only). Default: the name it came from ZBrush with, else the document name.", false},{"folder", T::String, "GoZ root folder (contains GoZBrush/ and GoZProjects/). Default: the public Pixologic folder.", false},{"launch", T::Bool, "Notify or start ZBrush. Default true.", false},{"zbrush", T::String, "ZBrush executable to start if GoZ's notifier is missing (optional).", false}},[](Document& doc, const Args& a) -> CommandResult {GozSendOptions o;o.root = argString(a, "folder");- o.name = sendName(doc, a);o.launch = argBool(a, "launch", true);o.zbrushPath = argString(a, "zbrush");std::string msg;- const bool ok = gozSend(doc.mesh, o, msg);- if (ok) doc.gozName = gozObjectName(o.name);+ if (doc.subtoolCount() == 1) {+ o.name = sendName(doc, a);+ const bool ok = gozSend(doc.mesh, o, msg);+ if (ok) doc.gozName = gozObjectName(o.name);+ return {ok, msg};+ }+ std::vector<int> indices;+ auto objects = gozObjects(doc, indices);+ if (objects.size() == 1 && a.contains("name")) objects[0].name = argString(a, "name");+ std::vector<std::string> sent;+ const bool ok = gozSend(objects, o, msg, &sent);+ // Remember the names, so ZBrush's next send updates these SubTools.+ if (ok)+ for (size_t k = 0; k < sent.size() && k < indices.size(); ++k) subtoolGozName(doc, indices[k]) = sent[k];return {ok, msg};}});reg.add({"goz_receive",- "Receive what ZBrush last sent with GoZ (the objects in GoZ_ObjectList.txt), replacing the mesh as an "- "undoable step. Several SubTools are merged into one mesh.",+ "Receive what ZBrush last sent with GoZ (the objects in GoZ_ObjectList.txt). Each object updates the "+ "SubTool it was sent from (an undoable step on that SubTool), or becomes a new SubTool; a single object "+ "replaces a scene of one SubTool that didn't come from ZBrush.",{{"folder", T::String, "GoZ root folder. Default: the public Pixologic folder.", false}},[](Document& doc, const Args& a) -> CommandResult {- Mesh m;+ std::vector<MeshObject> objects;std::string msg;- std::vector<std::string> names;- if (!gozReceive(argString(a, "folder"), m, msg, &names)) return {false, msg};- if (doc.mesh.triangleCount()) doc.replaceMeshUndoable(std::move(m), "Receive from ZBrush");- else doc.setMesh(std::move(m));+ if (!gozReceive(argString(a, "folder"), objects, msg)) return {false, msg};+ const int original = doc.activeSubtool; // new SubTools go to the end, so this index stays valid+ auto findGoz = [&](const std::string& name) {+ for (int i = 0; i < doc.subtoolCount(); ++i)+ if (!name.empty() && subtoolGozName(doc, i) == name) return i;+ return -1;+ };+ for (size_t k = 0; k < objects.size(); ++k) {+ MeshObject& obj = objects[k];+ int target = findGoz(obj.name);+ // The first object sent into a fresh scene (one SubTool, not from ZBrush) replaces it.+ const bool fresh = target < 0 && k == 0 && doc.subtoolCount() == 1 && doc.gozName.empty();+ if (fresh) target = 0;+ if (target < 0) {+ const int i = doc.addSubtool(std::move(obj.mesh), obj.name, false);+ subtoolGozName(doc, i) = obj.name;+ continue;+ }+ doc.selectSubtool(target);+ if (doc.mesh.triangleCount()) doc.replaceMeshUndoable(std::move(obj.mesh), "Receive from ZBrush");+ else doc.replaceActiveMesh(std::move(obj.mesh));+ doc.gozName = obj.name;+ if (fresh && objects.size() > 1) doc.activeSubtoolInfo().name = doc.uniqueSubtoolName(obj.name);+ }+ doc.selectSubtool(original);doc.path.clear();- doc.gozName = names.size() == 1 ? names.front() : std::string();doc.modified = true;return {true, msg};}});reg.add({"export_stl",- "Export the mesh as binary STL (for 3D printing).",+ "Export the visible SubTools as one binary STL mesh (for 3D printing).",{{"path", T::String, "Output .stl path (UTF-8).", true}},[](Document& doc, const Args& a) -> CommandResult {const std::string path = argString(a, "path");std::string err;- if (!saveStl(path, doc.mesh, err)) return {false, err};- return {true, "Exported " + path + " (" + std::to_string(doc.mesh.triangleCount()) + " triangles)"};+ Mesh merged; // no copy for a single SubTool+ const Mesh& mesh = doc.subtoolCount() == 1 ? doc.mesh : (merged = mergedVisibleMesh(doc));+ if (!saveStl(path, mesh, err)) return {false, err};+ return {true, "Exported " + path + " (" + std::to_string(mesh.triangleCount()) + " triangles)"};}});}diff --git a/src/io/GozIO.cpp b/src/io/GozIO.cppindex b29deeac..860a5df4 100644--- a/src/io/GozIO.cpp+++ b/src/io/GozIO.cpp@@ -539,6 +539,11 @@ bool gozShellSafePath(const std::string& path) {}bool gozSend(const Mesh& mesh, const GozSendOptions& o, std::string& message) {+ return gozSend(std::vector<MeshObjectRef>{{o.name.empty() ? "SculptForge" : o.name, &mesh}}, o, message);+}++bool gozSend(const std::vector<MeshObjectRef>& objects, const GozSendOptions& o, std::string& message,+ std::vector<std::string>* sentNames) {const std::string root = o.root.empty() ? gozDefaultRoot() : o.root;if (root.empty()) {message = gozUnavailableMessage();@@ -560,10 +565,15 @@ bool gozSend(const Mesh& mesh, const GozSendOptions& o, std::string& message) {}}}- if (mesh.triangleCount() == 0) {- message = "Nothing to send: the mesh is empty";+ if (objects.empty()) {+ message = "Nothing to send: no visible SubTools";return false;}+ for (const auto& obj : objects)+ if (!obj.mesh || obj.mesh->triangleCount() == 0) {+ message = "Nothing to send: the mesh is empty";+ return false;+ }const fs::path rootPath = utf8Path(root);const fs::path brush = rootPath / "GoZBrush";const fs::path project = rootPath / "GoZProjects" / "Default";@@ -573,16 +583,26 @@ bool gozSend(const Mesh& mesh, const GozSendOptions& o, std::string& message) {message = "Cannot create the GoZ folder " + pathUtf8(project);return false;}- const std::string name = gozObjectName(o.name.empty() ? "SculptForge" : o.name);- // Object paths are written without the .GoZ extension, ZBrush appends it.- const std::string base = genericUtf8(project / name);- std::string err;- if (!saveGoz(pathUtf8(project / (name + ".GoZ")), mesh, name, err)) {- message = err;- return false;+ // One .GoZ per object (ZBrush makes each a SubTool), all listed in GoZ_ObjectList.txt.+ std::vector<std::string> names;+ std::string list;+ bool ok = true;+ for (const auto& obj : objects) {+ const std::string wanted = gozObjectName(obj.name.empty() ? "SculptForge" : obj.name);+ std::string name = wanted;+ for (int k = 2; std::find(names.begin(), names.end(), name) != names.end(); ++k) name = wanted + "_" + std::to_string(k);+ names.push_back(name);+ // Object paths are written without the .GoZ extension, ZBrush appends it.+ const std::string base = genericUtf8(project / name);+ std::string err;+ if (!saveGoz(pathUtf8(project / (name + ".GoZ")), *obj.mesh, name, err)) {+ message = err;+ return false;+ }+ ok = ok && writeText(project / (name + ".ztn"), base);+ list += base + "\n";}- bool ok = writeText(project / (name + ".ztn"), base) && writeText(brush / "GoZ_ObjectList.txt", base + "\n") &&- writeText(brush / "GoZ_Application.txt", "SculptForge") &&+ ok = ok && writeText(brush / "GoZ_ObjectList.txt", list) && writeText(brush / "GoZ_Application.txt", "SculptForge") &&writeText(brush / "GoZ_ProjectPath.txt", genericUtf8(project) + "/");// Register SculptForge in ZBrush's GoZ application list.if (!fs::exists(app / "GoZ_Info.txt", ec))@@ -596,7 +616,9 @@ bool gozSend(const Mesh& mesh, const GozSendOptions& o, std::string& message) {message = "Cannot write the GoZ bridge files in " + root;return false;}- message = "Sent " + name + " to " + pathUtf8(project);+ message = "Sent " + names.front() + (names.size() > 1 ? " and " + std::to_string(names.size() - 1) + " more SubTools" : "") ++ " to " + pathUtf8(project);+ if (sentNames) *sentNames = names;if (!o.launch) return true;// Official GoZ plug-ins notify a running ZBrush with GoZBrushFromApp; GoB@@ -651,7 +673,7 @@ void appendMesh(Mesh& dst, const Mesh& src) {} // namespace-bool gozReceive(const std::string& rootIn, Mesh& out, std::string& message, std::vector<std::string>* names) {+bool gozReceive(const std::string& rootIn, std::vector<MeshObject>& out, std::string& message) {const std::string root = rootIn.empty() ? gozDefaultRoot() : rootIn;if (root.empty()) {message = gozUnavailableMessage();@@ -662,8 +684,7 @@ bool gozReceive(const std::string& rootIn, Mesh& out, std::string& message, std:message = "Nothing to receive: " + gozObjectListPath(root) + " does not exist (press GoZ in ZBrush first)";return false;}- Mesh merged;- std::vector<std::string> loaded;+ std::vector<MeshObject> loaded;std::string line, problems;while (std::getline(list, line)) {while (!line.empty() && (line.back() == '\r' || line.back() == ' ' || line.back() == '\0')) line.pop_back();@@ -679,21 +700,38 @@ bool gozReceive(const std::string& rootIn, Mesh& out, std::string& message, std:problems += (problems.empty() ? "" : "; ") + err;continue;}- loaded.push_back(info.name.empty() ? pathUtf8(utf8Path(path).stem()) : info.name);- appendMesh(merged, m);+ loaded.push_back({info.name.empty() ? pathUtf8(utf8Path(path).stem()) : info.name, std::move(m)});}if (loaded.empty()) {message = problems.empty() ? "Nothing to receive: GoZ_ObjectList.txt is empty" : problems;return false;}+ size_t tris = 0;+ for (const auto& obj : loaded) tris += obj.mesh.triangleCount();+ message = "Received " + loaded.front().name;+ if (loaded.size() > 1) message += " and " + std::to_string(loaded.size() - 1) + " more SubTools";+ message += " from ZBrush (" + std::to_string(tris) + " triangles)";+ if (!problems.empty()) message += "; skipped: " + problems;+ out = std::move(loaded);+ return true;+}++bool gozReceive(const std::string& root, Mesh& out, std::string& message, std::vector<std::string>* names) {+ std::vector<MeshObject> objects;+ if (!gozReceive(root, objects, message)) return false;+ Mesh merged;+ if (names) names->clear();+ for (const auto& obj : objects) {+ appendMesh(merged, obj.mesh);+ if (names) names->push_back(obj.name);+ }merged.rebuildTopology();merged.recomputeAllNormals();out = std::move(merged);- message = "Received " + loaded.front();- if (loaded.size() > 1) message += " and " + std::to_string(loaded.size() - 1) + " more SubTools (merged)";- message += " from ZBrush (" + std::to_string(out.triangleCount()) + " triangles)";- if (!problems.empty()) message += "; skipped: " + problems;- if (names) *names = std::move(loaded);+ if (objects.size() > 1) {+ const size_t from = message.find(" more SubTools");+ if (from != std::string::npos) message.insert(from + 14, " (merged)");+ }return true;}diff --git a/src/io/GozIO.h b/src/io/GozIO.hindex f6724ee0..3e4e1e1d 100644--- a/src/io/GozIO.h+++ b/src/io/GozIO.h@@ -12,6 +12,7 @@#pragma once#include "core/Mesh.h"+#include "io/MeshObject.h"#include <cstdint>#include <span>@@ -75,9 +76,17 @@ bool gozShellSafePath(const std::string& path);// With `launch`, a `zbrushPath` must name an existing ZBrush (its file name// contains "zbrush") and it and `root` must pass gozShellSafePath.bool gozSend(const Mesh& mesh, const GozSendOptions& options, std::string& message);+// Sends several objects at once (ZBrush gets one SubTool each): every object is+// written as <name>.GoZ (gozObjectName, made unique with _2, _3...) and listed+// in GoZ_ObjectList.txt in order; options.name is not used. `sentNames`+// receives the object names written.+bool gozSend(const std::vector<MeshObjectRef>& objects, const GozSendOptions& options, std::string& message,+ std::vector<std::string>* sentNames = nullptr);// Reads every object in <root>/GoZBrush/GoZ_ObjectList.txt (what ZBrush last-// sent) into one mesh. Several SubTools are merged.+// sent), one per listed SubTool, named after it.+bool gozReceive(const std::string& root, std::vector<MeshObject>& out, std::string& message);+// The same merged into one mesh.bool gozReceive(const std::string& root, Mesh& out, std::string& message, std::vector<std::string>* names = nullptr);// Path of the object list ZBrush rewrites on every send (for polling).diff --git a/src/io/MeshObject.h b/src/io/MeshObject.hnew file mode 100644index 00000000..4f7871d9--- /dev/null+++ b/src/io/MeshObject.h@@ -0,0 +1,28 @@+// SculptForge - open source digital sculpting+// SPDX-License-Identifier: GPL-3.0-or-later+//+// Named meshes for model files that hold several objects (OBJ `o` blocks,+// glTF nodes, FBX models, USD Mesh prims, GoZ object lists). Each object+// becomes one SubTool on import, and each visible SubTool one object on export.+#pragma once++#include "core/Mesh.h"++#include <string>+#include <vector>++namespace sf {++// An object read from a file.+struct MeshObject {+ std::string name; // as stored in the file (may be empty)+ Mesh mesh;+};++// An object to write: its name and a mesh owned by the caller.+struct MeshObjectRef {+ std::string name;+ const Mesh* mesh = nullptr;+};++} // namespace sfdiff --git a/src/io/ObjIO.cpp b/src/io/ObjIO.cppindex 78acac26..a6d376be 100644--- a/src/io/ObjIO.cpp+++ b/src/io/ObjIO.cpp@@ -2,10 +2,12 @@// SPDX-License-Identifier: GPL-3.0-or-later#include "io/ObjIO.h"+#include <algorithm>#include <cstdio>#include <cstdlib>#include <filesystem>#include <fstream>+#include <map>#include <sstream>namespace sf {@@ -21,9 +23,37 @@ const char* skipSpace(const char* p, const char* end) {return p;}-} // namespace+// True for a "<c> ..." or bare "<c>" statement.+bool isStatement(const char* s, char c) { return s[0] == c && (s[1] == ' ' || s[1] == '\t' || s[1] == '\r' || s[1] == 0); }-bool loadObj(const std::string& path, Mesh& out, std::string& error) {+// The text after a one-letter statement, without surrounding blanks.+std::string statementName(const char* s) {+ std::string name(s + 1);+ while (!name.empty() && (name.back() == ' ' || name.back() == '\t' || name.back() == '\r')) name.pop_back();+ size_t start = 0;+ while (start < name.size() && (name[start] == ' ' || name[start] == '\t')) ++start;+ return name.substr(start);+}++// One `o` object while parsing: triangles index the file's global vertex list.+struct ObjObject {+ std::string name;+ std::vector<glm::uvec3> triangles;+ std::vector<uint32_t> groups; // per triangle: index into groupNames+ std::vector<std::string> groupNames; // `g` names in order of first use ("" = before any `g`)+ std::map<std::string, uint32_t> groupIndex;+ std::string pendingGroup; // the last `g`, registered by its first face (unused names don't count)+ uint32_t currentGroup = ~0u;+};++// Polygroups from `g` names: only when the object uses two or more (ids 1, 2, ... in order of first use).+void applyGroups(const ObjObject& o, Mesh& m) {+ if (o.groupNames.size() < 2) return;+ m.polygroups.resize(o.groups.size());+ for (size_t t = 0; t < o.groups.size(); ++t) m.polygroups[t] = o.groups[t] + 1;+}++bool parseObj(const std::string& path, bool splitObjects, std::vector<MeshObject>& out, std::string& error) {std::ifstream file(utf8Path(path), std::ios::binary);if (!file) {error = "Cannot open " + path;@@ -31,12 +61,20 @@ bool loadObj(const std::string& path, Mesh& out, std::string& error) {}std::string data((std::istreambuf_iterator<char>(file)), std::istreambuf_iterator<char>());- Mesh m;+ std::vector<glm::vec3> positions, colors; // colours: empty until a vertex has one+ std::vector<uint8_t> colored; // per vertex (while colours exist): had an explicit colour+ std::vector<ObjObject> objects(1);std::vector<uint32_t> poly;const char* p = data.c_str();const char* end = p + data.size();size_t lineNo = 0;+ auto groupFor = [](ObjObject& o, const std::string& name) {+ auto [it, inserted] = o.groupIndex.try_emplace(name, uint32_t(o.groupNames.size()));+ if (inserted) o.groupNames.push_back(name);+ o.currentGroup = it->second;+ };+while (p < end) {const char* lineEnd = p;while (lineEnd < end && *lineEnd != '\n') ++lineEnd;@@ -67,12 +105,17 @@ bool loadObj(const std::string& path, Mesh& out, std::string& error) {cur = next;}if (channels == 3) {- if (m.colors.size() < m.positions.size()) m.colors.resize(m.positions.size(), glm::vec3(1.0f));- m.colors.push_back(srgbToLinear(rgb));- } else if (!m.colors.empty()) {- m.colors.push_back(glm::vec3(1.0f));+ if (colors.size() < positions.size()) {+ colors.resize(positions.size(), glm::vec3(1.0f));+ colored.resize(positions.size(), 0);+ }+ colors.push_back(srgbToLinear(rgb));+ colored.push_back(1);+ } else if (!colors.empty()) {+ colors.push_back(glm::vec3(1.0f));+ colored.push_back(0);}- m.positions.push_back(v);+ positions.push_back(v);} else if (s[0] == 'f' && (s[1] == ' ' || s[1] == '\t')) {poly.clear();char* cur = const_cast<char*>(s + 1);@@ -82,7 +125,7 @@ bool loadObj(const std::string& path, Mesh& out, std::string& error) {if (next == cur) break;cur = next;while (*cur && *cur != ' ' && *cur != '\t' && *cur != '\r') ++cur; // skip /vt/vn- long n = static_cast<long>(m.positions.size());+ long n = static_cast<long>(positions.size());long resolved = idx > 0 ? idx - 1 : n + idx;if (idx == 0 || resolved < 0 || resolved >= n) {error = "Invalid face index on line " + std::to_string(lineNo);@@ -90,46 +133,154 @@ bool loadObj(const std::string& path, Mesh& out, std::string& error) {}poly.push_back(static_cast<uint32_t>(resolved));}- for (size_t i = 2; i < poly.size(); ++i) m.triangles.push_back({poly[0], poly[i - 1], poly[i]});+ ObjObject& o = objects.back();+ if (poly.size() >= 3 && o.currentGroup == ~0u) groupFor(o, o.pendingGroup);+ for (size_t i = 2; i < poly.size(); ++i) {+ o.triangles.push_back({poly[0], poly[i - 1], poly[i]});+ o.groups.push_back(o.currentGroup);+ }+ } else if (isStatement(s, 'g')) {+ objects.back().pendingGroup = statementName(s);+ objects.back().currentGroup = ~0u;+ } else if (isStatement(s, 'o') && splitObjects) {+ // A new object; an `o` before any faces just names the current one.+ if (!objects.back().triangles.empty()) objects.emplace_back();+ objects.back() = ObjObject{};+ objects.back().name = statementName(s);}}- if (m.triangles.empty()) {+ size_t withFaces = 0;+ for (const auto& o : objects) withFaces += !o.triangles.empty();+ if (withFaces == 0) {error = "No faces found in " + path;return false;}- if (!m.colors.empty()) m.colors.resize(m.positions.size(), glm::vec3(1.0f));- m.rebuildTopology();- m.recomputeAllNormals();- out = std::move(m);+ if (!colors.empty()) {+ colors.resize(positions.size(), glm::vec3(1.0f));+ colored.resize(positions.size(), 0);+ }+ out.clear();+ if (withFaces == 1) {+ // One object: every vertex is kept, as stored.+ for (auto& o : objects) {+ if (o.triangles.empty()) continue;+ MeshObject obj;+ obj.name = o.name;+ obj.mesh.positions = std::move(positions);+ obj.mesh.colors = std::move(colors);+ obj.mesh.triangles = std::move(o.triangles);+ applyGroups(o, obj.mesh);+ out.push_back(std::move(obj));+ }+ } else {+ // Several: each object gets the vertices its faces use.+ std::vector<uint32_t> local(positions.size(), ~0u);+ for (auto& o : objects) {+ if (o.triangles.empty()) continue;+ MeshObject obj;+ obj.name = o.name;+ Mesh& m = obj.mesh;+ // Vertices keep their file order (so an object written as one block reads back unchanged).+ std::vector<uint32_t> used;+ for (const auto& t : o.triangles)+ for (int k = 0; k < 3; ++k)+ if (local[t[k]] == ~0u) {+ local[t[k]] = 0;+ used.push_back(t[k]);+ }+ std::sort(used.begin(), used.end());+ bool anyColor = false;+ for (size_t i = 0; i < used.size(); ++i) {+ local[used[i]] = uint32_t(i);+ anyColor |= !colored.empty() && colored[used[i]];+ }+ for (auto& t : o.triangles)+ for (int k = 0; k < 3; ++k) t[k] = local[t[k]];+ m.positions.reserve(used.size());+ for (uint32_t v : used) m.positions.push_back(positions[v]);+ if (anyColor)+ for (uint32_t v : used) m.colors.push_back(colors[v]);+ for (uint32_t v : used) local[v] = ~0u;+ m.triangles = std::move(o.triangles);+ applyGroups(o, m);+ out.push_back(std::move(obj));+ }+ }+ for (auto& obj : out) {+ obj.mesh.rebuildTopology();+ obj.mesh.recomputeAllNormals();+ }return true;}+} // namespace++bool loadObj(const std::string& path, Mesh& out, std::string& error) {+ std::vector<MeshObject> objects;+ if (!parseObj(path, false, objects, error)) return false;+ out = std::move(objects.front().mesh);+ return true;+}++bool loadObj(const std::string& path, std::vector<MeshObject>& out, std::string& error) {+ return parseObj(path, true, out, error);+}+bool saveObj(const std::string& path, const Mesh& mesh, std::string& error) {+ return saveObj(path, std::vector<MeshObjectRef>{{"", &mesh}}, error);+}++bool saveObj(const std::string& path, const std::vector<MeshObjectRef>& objects, std::string& error) {+ if (objects.empty()) {+ error = "Nothing to export";+ return false;+ }std::ofstream file(utf8Path(path), std::ios::binary);if (!file) {error = "Cannot write " + path;return false;}std::string buf;- buf.reserve(mesh.vertexCount() * 40 + mesh.triangleCount() * 30);+ size_t reserve = 0;+ for (const auto& o : objects) reserve += o.mesh->vertexCount() * 40 + o.mesh->triangleCount() * 30;+ buf.reserve(reserve);buf += "# Exported by SculptForge\n";char line[128];- const bool colors = mesh.colors.size() == mesh.positions.size() && mesh.hasColors();- for (size_t i = 0; i < mesh.positions.size(); ++i) {- const glm::vec3& v = mesh.positions[i];- int n;- if (colors) {- const glm::vec3 c = linearToSrgb(mesh.colors[i]);- n = std::snprintf(line, sizeof line, "v %.7g %.7g %.7g %.4f %.4f %.4f\n", v.x, v.y, v.z, c.x, c.y, c.z);- } else {- n = std::snprintf(line, sizeof line, "v %.7g %.7g %.7g\n", v.x, v.y, v.z);+ uint32_t first = 1; // OBJ indices are 1-based and global across objects+ for (const auto& o : objects) {+ const Mesh& mesh = *o.mesh;+ if (objects.size() > 1) {+ std::string name = o.name.empty() ? std::string("Object") : o.name;+ for (char& c : name)+ if (c == '\n' || c == '\r') c = ' ';+ buf += "o " + name + "\n";}- buf.append(line, n);- }- for (const auto& t : mesh.triangles) {- int n = std::snprintf(line, sizeof line, "f %u %u %u\n", t.x + 1, t.y + 1, t.z + 1);- buf.append(line, n);+ const bool colors = mesh.colors.size() == mesh.positions.size() && mesh.hasColors();+ for (size_t i = 0; i < mesh.positions.size(); ++i) {+ const glm::vec3& v = mesh.positions[i];+ int n;+ if (colors) {+ const glm::vec3 c = linearToSrgb(mesh.colors[i]);+ n = std::snprintf(line, sizeof line, "v %.7g %.7g %.7g %.4f %.4f %.4f\n", v.x, v.y, v.z, c.x, c.y, c.z);+ } else {+ n = std::snprintf(line, sizeof line, "v %.7g %.7g %.7g\n", v.x, v.y, v.z);+ }+ buf.append(line, n);+ }+ // Polygroups as `g` groups (ZBrush's OBJ convention), when there is more than one.+ bool groups = false;+ for (uint32_t t = 1; t < mesh.triangleCount() && !groups; ++t) groups = mesh.polygroupAt(t) != mesh.polygroupAt(0);+ for (uint32_t t = 0; t < mesh.triangleCount(); ++t) {+ if (groups && (t == 0 || mesh.polygroupAt(t) != mesh.polygroupAt(t - 1))) {+ const int n = std::snprintf(line, sizeof line, "g group%u\n", mesh.polygroupAt(t));+ buf.append(line, n);+ }+ const glm::uvec3& tri = mesh.triangles[t];+ const int n = std::snprintf(line, sizeof line, "f %u %u %u\n", tri.x + first, tri.y + first, tri.z + first);+ buf.append(line, n);+ }+ first += uint32_t(mesh.vertexCount());}file.write(buf.data(), static_cast<std::streamsize>(buf.size()));if (!file) {diff --git a/src/io/ObjIO.h b/src/io/ObjIO.hindex a3a9ec98..808ff7e1 100644--- a/src/io/ObjIO.h+++ b/src/io/ObjIO.h@@ -3,14 +3,27 @@#pragma once#include "core/Mesh.h"+#include "io/MeshObject.h"#include <string>+#include <vector>namespace sf {// Paths are UTF-8. Polygons are fan-triangulated; UVs and normals are ignored.// "v x y z r g b" vertex colours are read into Mesh::colors and written back.+// `g` groups become polygroups (when an object uses two or more), as ZBrush+// writes them; `o` starts a new object, as Blender and ZBrush write SubTools.++// Reads every object into one mesh.bool loadObj(const std::string& path, Mesh& out, std::string& error);+// Reads each `o` object as its own mesh (objects without faces are skipped).+// A file without `o` lines, or with one object, gives exactly what loadObj gives.+bool loadObj(const std::string& path, std::vector<MeshObject>& out, std::string& error);+bool saveObj(const std::string& path, const Mesh& mesh, std::string& error);+// Several objects are written as `o name` blocks; a single one as a plain mesh.+// Polygroups (two or more) are written as `g` groups.+bool saveObj(const std::string& path, const std::vector<MeshObjectRef>& objects, std::string& error);} // namespace sfdiff --git a/src/io/UsdIO.cpp b/src/io/UsdIO.cppindex c24a417f..7482682c 100644--- a/src/io/UsdIO.cpp+++ b/src/io/UsdIO.cpp@@ -103,9 +103,10 @@ void writeExtent(Writer& w, const AABB& b) {w.s += "]\n";}-void writeMesh(Writer& w, const Mesh& mesh, const std::string& root, const std::string& material) {+// One mesh prim `prim` under the root (a SkelRoot holding the Mesh when it has blend shapes).+void writeMesh(Writer& w, const Mesh& mesh, const std::string& root, const std::string& prim, const std::string& material) {const bool skinned = !mesh.layers.empty();- const std::string meshPath = skinned ? "/" + root + "/Sculpt/Mesh" : "/" + root + "/Sculpt";+ const std::string meshPath = skinned ? "/" + root + "/" + prim + "/Mesh" : "/" + root + "/" + prim;// Unique, valid names for the blend shapes.std::vector<std::string> shapeNames;std::set<std::string> used;@@ -122,8 +123,8 @@ void writeMesh(Writer& w, const Mesh& mesh, const std::string& root, const std::base.rebuildTopology();base.recomputeAllNormals();- if (skinned) w.open("def SkelRoot \"Sculpt\"");- w.line(std::string("def Mesh \"") + (skinned ? "Mesh" : "Sculpt") + "\" (");+ if (skinned) w.open("def SkelRoot \"" + prim + "\"");+ w.line("def Mesh \"" + (skinned ? std::string("Mesh") : prim) + "\" (");w.line(skinned ? " prepend apiSchemas = [\"SkelBindingAPI\", \"MaterialBindingAPI\"]": " prepend apiSchemas = [\"MaterialBindingAPI\"]");w.line(")");@@ -156,7 +157,7 @@ void writeMesh(Writer& w, const Mesh& mesh, const std::string& root, const std::if (skinned) {w.array("uniform token[] skel:blendShapes", shapeNames, [&](const std::string& n) { w.s += quoted(n); });w.array("rel skel:blendShapeTargets", shapeNames, [&](const std::string& n) { w.s += "<" + meshPath + "/" + n + ">"; });- w.line("rel skel:skeleton = </" + root + "/Sculpt/Skel>");+ w.line("rel skel:skeleton = </" + root + "/" + prim + "/Skel>");for (size_t k = 0; k < mesh.layers.size(); ++k) {// Sparse: only the points the layer actually moves.std::vector<uint32_t> idx;@@ -184,7 +185,7 @@ void writeMesh(Writer& w, const Mesh& mesh, const std::string& root, const std::w.line("uniform matrix4d[] bindTransforms = []");w.line("uniform token[] joints = []");w.line("uniform matrix4d[] restTransforms = []");- w.line("rel skel:animationSource = </" + root + "/Sculpt/Skel/Weights>");+ w.line("rel skel:animationSource = </" + root + "/" + prim + "/Skel/Weights>");w.s += '\n';w.open("def SkelAnimation \"Weights\"");w.array("uniform token[] blendShapes", shapeNames, [&](const std::string& n) { w.s += quoted(n); });@@ -225,9 +226,37 @@ void writeSplats(Writer& w, const SplatCloud& c) {w.close();}-std::string buildUsda(const Mesh* mesh, const SplatCloud* splats, const std::string& name) {+// A UsdPreviewSurface clay material; `painted` reads the polypaint primvar for its colour.+void writeMaterial(Writer& w, const std::string& path, const std::string& name, bool painted) {+ w.open("def Material " + quoted(name));+ w.line("token outputs:surface.connect = <" + path + "/PreviewSurface.outputs:surface>");+ w.s += '\n';+ w.open("def Shader \"PreviewSurface\"");+ w.line("uniform token info:id = \"UsdPreviewSurface\"");+ if (painted) w.line("color3f inputs:diffuseColor.connect = <" + path + "/Polypaint.outputs:result>");+ else w.line("color3f inputs:diffuseColor = (0.8, 0.55, 0.45)");+ w.line("float inputs:metallic = 0");+ w.line("float inputs:roughness = 0.65");+ w.line("token outputs:surface");+ w.close();+ if (painted) {+ w.s += '\n';+ w.open("def Shader \"Polypaint\"");+ w.line("uniform token info:id = \"UsdPrimvarReader_float3\"");+ w.line("string inputs:varname = \"displayColor\"");+ w.line("float3 outputs:result");+ w.close();+ }+ w.close();+}++std::string buildUsda(const std::vector<MeshObjectRef>& meshes, const SplatCloud* splats, const std::string& name) {const std::string root = usdIdentifier(name.empty() ? "Sculpt" : name);- const std::string material = "/" + root + "/Materials/Clay";+ // Polypainted meshes bind a material that reads their colours; with a mix, plain ones bind "Clay".+ size_t painted = 0;+ for (const auto& m : meshes) painted += m.mesh->hasColors();+ const bool mixed = painted && painted < meshes.size();+ const std::string clay = "/" + root + "/Materials/Clay", paintedClay = "/" + root + "/Materials/PaintedClay";Writer w;w.line("#usda 1.0");w.line("(");@@ -242,34 +271,30 @@ std::string buildUsda(const Mesh* mesh, const SplatCloud* splats, const std::strw.line(")");w.line("{");++w.depth;- if (mesh && mesh->triangleCount()) {- writeMesh(w, *mesh, root, material);- w.s += '\n';+ if (!meshes.empty()) {+ // One prim per object: "Sculpt" for a single one, else valid unique names from the objects.+ std::set<std::string> used = {"Materials", "Splats"};+ for (const auto& m : meshes) {+ std::string prim = "Sculpt";+ if (meshes.size() > 1) {+ const std::string base = usdIdentifier(m.name.empty() ? "Mesh" : m.name);+ prim = base;+ for (int k = 2; used.count(prim); ++k) prim = base + "_" + std::to_string(k);+ }+ used.insert(prim);+ writeMesh(w, *m.mesh, root, prim, mixed && m.mesh->hasColors() ? paintedClay : clay);+ w.s += '\n';+ }w.open("def Scope \"Materials\"");- w.open("def Material \"Clay\"");- w.line("token outputs:surface.connect = <" + material + "/PreviewSurface.outputs:surface>");- w.s += '\n';- w.open("def Shader \"PreviewSurface\"");- w.line("uniform token info:id = \"UsdPreviewSurface\"");- if (mesh->hasColors()) w.line("color3f inputs:diffuseColor.connect = <" + material + "/Polypaint.outputs:result>");- else w.line("color3f inputs:diffuseColor = (0.8, 0.55, 0.45)");- w.line("float inputs:metallic = 0");- w.line("float inputs:roughness = 0.65");- w.line("token outputs:surface");- w.close();- if (mesh->hasColors()) {+ writeMaterial(w, clay, "Clay", painted && !mixed);+ if (mixed) {w.s += '\n';- w.open("def Shader \"Polypaint\"");- w.line("uniform token info:id = \"UsdPrimvarReader_float3\"");- w.line("string inputs:varname = \"displayColor\"");- w.line("float3 outputs:result");- w.close();+ writeMaterial(w, paintedClay, "PaintedClay", true);}w.close();- w.close();}if (splats && !splats->empty()) {- if (mesh && mesh->triangleCount()) w.s += '\n';+ if (!meshes.empty()) w.s += '\n';writeSplats(w, *splats);}w.close();@@ -618,7 +643,27 @@ std::vector<glm::vec3> vec3s(const Value* v) {return out;}-bool readUsdaText(const std::string& text, Mesh& outMesh, SplatCloud& outSplats, std::string& error) {+// A point index from a USD array, or `size` when it is negative, fractional junk or too large.+size_t indexValue(double v, size_t size) { return v >= 0.0 && v < double(size) ? size_t(v) : size; }++// The SkelAnimation driving a mesh: skel:skeleton on the mesh or an ancestor, then its animationSource.+const Prim* skelAnimation(const std::vector<Prim>& prims, const std::map<std::string, size_t>& byPath, size_t mesh) {+ for (int i = int(mesh); i >= 0; i = prims[size_t(i)].parent) {+ const Value* skel = prims[size_t(i)].get("skel:skeleton");+ if (!skel || skel->strs.empty()) continue;+ auto s = byPath.find(skel->strs[0]);+ if (s == byPath.end()) return nullptr;+ const Value* anim = prims[s->second].get("skel:animationSource");+ if (!anim || anim->strs.empty()) return nullptr;+ auto a = byPath.find(anim->strs[0]);+ return a == byPath.end() ? nullptr : &prims[a->second];+ }+ return nullptr;+}++// Merges every Mesh prim into one object, or (split) makes one object per prim.+bool readUsdaText(const std::string& text, bool split, std::vector<MeshObject>& outMeshes, SplatCloud& outSplats,+ std::string& error) {Parser parser(text);if (!parser.parse()) {error = parser.error;@@ -649,16 +694,12 @@ bool readUsdaText(const std::string& text, Mesh& outMesh, SplatCloud& outSplats,weights.try_emplace(names->strs[k], float(w->nums[k]));}- Mesh m;- std::vector<SculptLayer> layers;- auto layerFor = [&](const std::string& name) -> SculptLayer& {- for (auto& l : layers)- if (l.name == name) return l;- auto it = weights.find(name);- layers.push_back({name, std::vector<glm::vec3>(m.positions.size(), glm::vec3(0.0f)),- it == weights.end() ? 0.0f : it->second});- return layers.back();+ struct Gathered {+ std::string name;+ Mesh m;+ std::vector<SculptLayer> layers;};+ std::vector<Gathered> objects(split ? 0 : 1);bool splatsFound = false;SplatCloud cloud;@@ -672,6 +713,31 @@ bool readUsdaText(const std::string& text, Mesh& outMesh, SplatCloud& outSplats,if (pts.empty() || !counts || !indices) continue;const Value* orient = p.get("orientation");const bool leftHanded = orient && !orient->strs.empty() && orient->strs[0] == "leftHanded";+ if (split) {+ // Named after the prim, or after its SkelRoot (SculptForge writes <Name>/Mesh for blend shapes).+ const int parent = p.parent;+ const Prim& named = parent >= 0 && prims[size_t(parent)].type == "SkelRoot" ? prims[size_t(parent)] : p;+ objects.push_back({named.path.substr(named.path.rfind('/') + 1), {}, {}});+ }+ Mesh& m = objects.back().m;+ std::vector<SculptLayer>& layers = objects.back().layers;+ // Layer weights from the mesh's own SkelAnimation, else from any animation naming the shape.+ std::map<std::string, float> ownWeights;+ if (const Prim* anim = skelAnimation(prims, byPath, i)) {+ const Value* names = anim->get("blendShapes");+ const Value* w = anim->get("blendShapeWeights");+ for (size_t k = 0; names && w && k < names->strs.size() && k < w->nums.size(); ++k)+ ownWeights.try_emplace(names->strs[k], float(w->nums[k]));+ }+ auto layerFor = [&](const std::string& name) -> SculptLayer& {+ for (auto& l : layers)+ if (l.name == name) return l;+ auto own = ownWeights.find(name);+ auto it = weights.find(name);+ layers.push_back({name, std::vector<glm::vec3>(m.positions.size(), glm::vec3(0.0f)),+ own != ownWeights.end() ? own->second : it == weights.end() ? 0.0f : it->second});+ return layers.back();+ };const uint32_t baseIndex = uint32_t(m.positions.size());for (const auto& q : pts) m.positions.push_back(glm::vec3(world[i] * glm::vec4(q, 1.0f)));size_t cursor = 0;@@ -682,8 +748,9 @@ bool readUsdaText(const std::string& text, Mesh& outMesh, SplatCloud& outSplats,return false;}for (size_t k = 1; k + 1 < n; ++k) {- glm::uvec3 t(uint32_t(indices->nums[cursor]), uint32_t(indices->nums[cursor + k]),- uint32_t(indices->nums[cursor + k + 1]));+ glm::uvec3 t(uint32_t(indexValue(indices->nums[cursor], pts.size())),+ uint32_t(indexValue(indices->nums[cursor + k], pts.size())),+ uint32_t(indexValue(indices->nums[cursor + k + 1], pts.size())));if (t.x >= pts.size() || t.y >= pts.size() || t.z >= pts.size()) {error = "Mesh " + p.path + " has a face index out of range";return false;@@ -710,7 +777,7 @@ bool readUsdaText(const std::string& text, Mesh& outMesh, SplatCloud& outSplats,SculptLayer& layer = layerFor(names->strs[k]);layer.delta.resize(m.positions.size(), glm::vec3(0.0f));for (size_t o = 0; o < offsets.size(); ++o) {- const size_t v = pointIndices ? (o < pointIndices->nums.size() ? size_t(pointIndices->nums[o]) : pts.size())+ const size_t v = pointIndices ? (o < pointIndices->nums.size() ? indexValue(pointIndices->nums[o], pts.size()) : pts.size()): o;if (v < pts.size()) layer.delta[baseIndex + v] = linear * offsets[o];}@@ -745,11 +812,16 @@ bool readUsdaText(const std::string& text, Mesh& outMesh, SplatCloud& outSplats,}}- if (m.triangles.empty() && !splatsFound) {+ outMeshes.clear();+ for (auto& o : objects) {+ if (o.m.triangles.empty()) continue;+ for (auto& l : o.layers) l.delta.resize(o.m.positions.size(), glm::vec3(0.0f));+ outMeshes.push_back({o.name, weldImported(o.m, o.layers)});+ }+ if (outMeshes.empty() && !splatsFound) {error = "No meshes or Gaussian splats found (references, payloads and binary .usdc layers are not supported yet)";return false;}- outMesh = m.triangles.empty() ? Mesh() : weldImported(m, layers);outSplats = splatsFound ? std::move(cloud) : SplatCloud();return true;}@@ -765,9 +837,18 @@ std::string usdIdentifier(const std::string& text) {bool saveUsd(const std::string& path, const Mesh* mesh, const SplatCloud* splats, const std::string& name,std::string& error) {- const bool hasMesh = mesh && mesh->triangleCount() > 0;+ std::vector<MeshObjectRef> meshes;+ if (mesh && mesh->triangleCount() > 0) meshes.push_back({name, mesh});+ return saveUsd(path, meshes, splats, name, error);+}++bool saveUsd(const std::string& path, const std::vector<MeshObjectRef>& meshesIn, const SplatCloud* splats,+ const std::string& name, std::string& error) {+ std::vector<MeshObjectRef> meshes;+ for (const auto& m : meshesIn)+ if (m.mesh && m.mesh->triangleCount() > 0) meshes.push_back(m);const bool hasSplats = splats && !splats->empty();- if (!hasMesh && !hasSplats) {+ if (meshes.empty() && !hasSplats) {error = "Nothing to export";return false;}@@ -777,7 +858,7 @@ bool saveUsd(const std::string& path, const Mesh* mesh, const SplatCloud* splatsreturn false;}}- const std::string text = buildUsda(hasMesh ? mesh : nullptr, hasSplats ? splats : nullptr, name);+ const std::string text = buildUsda(meshes, hasSplats ? splats : nullptr, name);const std::string ext = lowerExtension(path);if (ext == ".usdz") {std::string inner = usdIdentifier(name.empty() ? "Sculpt" : name) + ".usda";@@ -795,7 +876,10 @@ bool saveUsd(const std::string& path, const Mesh* mesh, const SplatCloud* splatsreturn true;}-bool loadUsd(const std::string& path, Mesh& mesh, SplatCloud& splats, std::string& error) {+namespace {++bool readUsdFile(const std::string& path, bool split, std::vector<MeshObject>& meshes, SplatCloud& splats,+ std::string& error) {std::string text;if (lowerExtension(path) == ".usdz") {std::vector<ZipEntry> entries;@@ -821,7 +905,20 @@ bool loadUsd(const std::string& path, Mesh& mesh, SplatCloud& splats, std::strinerror = path + " is not a text USD layer";return false;}- return readUsdaText(text, mesh, splats, error);+ return readUsdaText(text, split, meshes, splats, error);+}++} // namespace++bool loadUsd(const std::string& path, Mesh& mesh, SplatCloud& splats, std::string& error) {+ std::vector<MeshObject> meshes;+ if (!readUsdFile(path, false, meshes, splats, error)) return false;+ mesh = meshes.empty() ? Mesh() : std::move(meshes.front().mesh);+ return true;+}++bool loadUsd(const std::string& path, std::vector<MeshObject>& meshes, SplatCloud& splats, std::string& error) {+ return readUsdFile(path, true, meshes, splats, error);}} // namespace sfdiff --git a/src/io/UsdIO.h b/src/io/UsdIO.hindex 93caf301..f3e631c0 100644--- a/src/io/UsdIO.h+++ b/src/io/UsdIO.h@@ -15,6 +15,7 @@#include "core/Mesh.h"#include "core/Splats.h"+#include "io/MeshObject.h"#include <string>@@ -23,10 +24,17 @@ namespace sf {// Either pointer may be null (or empty) but not both. Format by extension.bool saveUsd(const std::string& path, const Mesh* mesh, const SplatCloud* splats, const std::string& name,std::string& error);+// One Mesh prim per object (SubTool) under the root Xform `name`, each with its+// own blend shapes: a single object is the prim "Sculpt" as above, several are+// named after the objects (made valid and unique).+bool saveUsd(const std::string& path, const std::vector<MeshObjectRef>& meshes, const SplatCloud* splats,+ const std::string& name, std::string& error);// Fills whichever of `mesh` / `splats` the file contains (the other is left-// empty). Fails if it contains neither.+// empty; every Mesh prim is merged). Fails if it contains neither.bool loadUsd(const std::string& path, Mesh& mesh, SplatCloud& splats, std::string& error);+// The same with one object per Mesh prim, named after the prim (or its SkelRoot).+bool loadUsd(const std::string& path, std::vector<MeshObject>& meshes, SplatCloud& splats, std::string& error);// A valid USD prim name from arbitrary text ("Smile 2" -> "Smile_2").std::string usdIdentifier(const std::string& text);diff --git a/src/python/module.cpp b/src/python/module.cppindex 04e6047c..ff18491a 100644--- a/src/python/module.cpp+++ b/src/python/module.cpp@@ -184,6 +184,28 @@ PYBIND11_MODULE(sculptforge, m) {},py::arg("vertices"), py::arg("triangles"), "Replace the sculpt with your own mesh (clears undo).").def_property_readonly("splat_count", [](const Document& d) { return d.splats.size(); })+ // SubTools: the mesh properties above are the active SubTool's.+ .def_property_readonly("subtools",+ [](const Document& d) {+ py::list out;+ for (int i = 0; i < d.subtoolCount(); ++i)+ out.append(py::dict(py::arg("name") = d.subtools[size_t(i)].name,+ py::arg("visible") = d.subtools[size_t(i)].visible,+ py::arg("triangles") = d.subtoolMesh(i).triangleCount()));+ return out;+ },+ "The SubTools (separate meshes) in list order, as dicts with name, visible and triangles.")+ .def_property(+ "active_subtool", [](const Document& d) { return d.activeSubtool; },+ [](Document& d, const py::object& v) {+ int index = -1;+ if (py::isinstance<py::str>(v)) index = d.findSubtool(v.cast<std::string>());+ else index = v.cast<int>();+ if (index < 0 || index >= d.subtoolCount()) throw py::index_error("no such SubTool");+ d.selectSubtool(index);+ },+ "Index of the SubTool that vertices, mask, layers... and editing commands refer to. Set it to an "+ "index or a SubTool name to select another one.").def("__repr__", [](const Document& d) {return "<sculptforge.Document " + std::to_string(d.mesh.vertexCount()) + " vertices, " +std::to_string(d.mesh.triangleCount()) + " triangles, " + std::to_string(d.mesh.layers.size()) +diff --git a/tests/test_goz.cpp b/tests/test_goz.cppindex 36655a35..a4f292a2 100644--- a/tests/test_goz.cpp+++ b/tests/test_goz.cpp@@ -269,7 +269,7 @@ TEST(goz_bridge_send_and_receive) {CHECK(std::string(list.begin(), list.end()) == expected);CHECK(doc.gozName == "Sphere_1");- // ZBrush sends two SubTools back: they are merged into one undoable step.+ // ZBrush sends two SubTools back: the first replaces the fresh scene (undoably), the second is added.Mesh second = makeIcosphere(1);for (auto& p : second.positions) p += glm::vec3(3, 0, 0);std::string err;@@ -281,11 +281,26 @@ TEST(goz_bridge_send_and_receive) {Document back = makeDoc(makeIcosphere(0));r = reg.execute(back, "goz_receive", {{"folder", folder}});CHECK(r.ok && r.message.find("Sphere_1") != std::string::npos);- CHECK(back.mesh.vertexCount() == m.vertexCount() + second.vertexCount());- CHECK(back.mesh.triangleCount() == m.triangleCount() + second.triangleCount());+ CHECK(back.subtoolCount() == 2 && back.activeSubtool == 0);+ CHECK(back.subtools[0].name == "Sphere_1" && back.gozName == "Sphere_1");+ CHECK(back.subtools[1].name == "Other" && back.subtools[1].gozName == "Other");+ CHECK(back.mesh.vertexCount() == m.vertexCount() && back.mesh.triangleCount() == m.triangleCount());+ CHECK(back.subtoolMesh(1).triangleCount() == second.triangleCount());CHECK(back.mesh.mask.size() == back.mesh.vertexCount() && back.mesh.polygroups.size() == back.mesh.triangleCount());CHECK(back.mesh.uvs.size() == back.mesh.triangleCount() * 3);CHECK(back.undo.canUndo());+ // Receiving again updates the same SubTools (matched by GoZ name) instead of adding more.+ r = reg.execute(back, "goz_receive", {{"folder", folder}});+ CHECK(r.ok && back.subtoolCount() == 2 && back.activeSubtool == 0);+ back.selectSubtool(1);+ CHECK(back.undo.canUndo() && back.mesh.triangleCount() == second.triangleCount());+ back.selectSubtool(0);+ // Sending both back writes one .GoZ per SubTool, listed in order.+ r = reg.execute(back, "goz_send", {{"folder", folder}, {"launch", false}});+ CHECK(r.ok);+ list = readFile((root / "GoZBrush" / "GoZ_ObjectList.txt").string());+ CHECK(std::string(list.begin(), list.end()) ==+ (project / "Sphere_1").generic_string() + "\n" + (project / "Other").generic_string() + "\n");// Missing object list explains what to do.fs::remove(root / "GoZBrush" / "GoZ_ObjectList.txt");diff --git a/tests/test_project.cpp b/tests/test_project.cppindex a8ae414f..d55714d2 100644--- a/tests/test_project.cpp+++ b/tests/test_project.cpp@@ -90,6 +90,21 @@ bool editManifest(const std::string& path, const std::function<void(Json&)>& edireturn writeStoredZip(path, entries, 1, err);}+// Applies `edit` to the "mesh" object of the first SubTool in a manifest.+void editFirstMesh(Json& j, const std::function<void(Json&)>& edit) {+ Json subtools = Json::array();+ for (size_t i = 0; i < j["subtools"].size(); ++i) {+ Json st = j["subtools"][i];+ if (i == 0) {+ Json mesh = st["mesh"];+ edit(mesh);+ st.set("mesh", std::move(mesh));+ }+ subtools.push(std::move(st));+ }+ j.set("subtools", std::move(subtools));+}+} // namespaceTEST(project_round_trip_every_attribute) {@@ -184,15 +199,13 @@ TEST(project_version_handling) {std::string err;CHECK(saveProject(path, doc, err));const std::string manifest = readManifest(path);- CHECK(manifest.find("\"version\": 1") != std::string::npos || manifest.find("\"version\":1") != std::string::npos);+ CHECK(manifest.find("\"version\": 2") != std::string::npos || manifest.find("\"version\":2") != std::string::npos);CHECK(manifest.find("app_version") != std::string::npos);// Unknown fields (top level and inside the mesh) are ignored.CHECK(editManifest(path, [](Json& j) {j.set("shiny_new_thing", Json::object());- Json mesh = j["mesh"];- mesh.set("creases", "future blob");- j.set("mesh", std::move(mesh));+ editFirstMesh(j, [](Json& mesh) { mesh.set("creases", "future blob"); });}));Document back;CHECK(loadProject(path, back, err));@@ -215,9 +228,7 @@ TEST(project_version_handling) {CHECK(!loadProject(path, keep, err));CHECK(saveProject(path, doc, err));CHECK(editManifest(path, [](Json& j) {- Json mesh = j["mesh"];- mesh.set("vertex_count", double(j["mesh"]["vertex_count"].asNumber() + 1));- j.set("mesh", std::move(mesh));+ editFirstMesh(j, [](Json& mesh) { mesh.set("vertex_count", mesh["vertex_count"].asNumber() + 1); });}));err.clear();CHECK(!loadProject(path, keep, err) && !err.empty());diff --git a/tests/test_python.py b/tests/test_python.pyindex 73d3737d..cab9aba9 100644--- a/tests/test_python.py+++ b/tests/test_python.py@@ -48,6 +48,25 @@ try:except sf.CommandError:pass+# SubTools: the mesh properties follow the active one; exports write every visible one.+sf.run(doc, "new_sphere", subdivisions=2)+sf.run(doc, "subtool_append", type="cube", name="Box")+assert [s["name"] for s in doc.subtools] == ["Sphere", "Box"] and doc.active_subtool == 1+box_tris = doc.triangles.shape[0]+doc.active_subtool = "Sphere"+assert doc.active_subtool == 0 and doc.triangles.shape[0] == 320 and doc.subtools[1]["triangles"] == box_tris+try:+ doc.active_subtool = 5+ raise AssertionError("expected IndexError")+except IndexError:+ pass+with tempfile.TemporaryDirectory() as d:+ out = os.path.join(d, "scene.obj")+ sf.run(doc, "save_obj", path=out)+ back = sf.Document()+ sf.run(back, "open", path=out)+ assert [s["name"] for s in back.subtools] == ["Sphere", "Box"], back.subtools+# Bring your own mesh in from a pipeline.doc.set_mesh([[0, 0, 0], [1, 0, 0], [0, 1, 0], [0, 0, 1]], [[0, 2, 1], [0, 1, 3], [0, 3, 2], [1, 2, 3]])assert doc.triangles.shape == (4, 3)diff --git a/tests/test_subtool_io.cpp b/tests/test_subtool_io.cppnew file mode 100644index 00000000..a9fb0c24--- /dev/null+++ b/tests/test_subtool_io.cpp@@ -0,0 +1,600 @@+// SculptForge - open source digital sculpting+// SPDX-License-Identifier: GPL-3.0-or-later+//+// SubTools in every file path: project files (version 2 round trip, version 1+// still loading), exporters writing one object per visible SubTool (OBJ, glTF,+// FBX incl. LOD groups and the Unreal preset, USD, GoZ) or the merged visible+// mesh (PLY, STL, splats), importers giving the objects back as SubTools, and+// single-object files behaving as before.+#include "TestHarness.h"++#include "core/Commands.h"+#include "core/EnginePresets.h"+#include "core/Json.h"+#include "core/Primitives.h"+#include "core/Project.h"+#include "core/SubTools.h"+#include "io/FbxIO.h"+#include "io/GltfIO.h"+#include "io/GozIO.h"+#include "io/ObjIO.h"+#include "io/PlyIO.h"+#include "io/StlIO.h"+#include "io/UsdIO.h"+#include "io/Zip.h"++#include <cmath>+#include <filesystem>+#include <fstream>+#include <functional>+#include <set>+#include <sstream>++using namespace sf;++namespace {++std::string readText(const std::string& path) {+ std::ifstream f(std::filesystem::path(path), std::ios::binary);+ std::stringstream s;+ s << f.rdbuf();+ return s.str();+}++void writeText(const std::string& path, const std::string& text) {+ std::ofstream f(std::filesystem::path(path), std::ios::binary);+ f << text;+}++size_t countOf(const std::string& text, const std::string& what) {+ size_t n = 0;+ for (size_t at = text.find(what); at != std::string::npos; at = text.find(what, at + what.size())) ++n;+ return n;+}++size_t groupCount(const Mesh& m) {+ std::set<uint32_t> ids;+ for (uint32_t t = 0; t < m.triangleCount(); ++t) ids.insert(m.polygroupAt(t));+ return ids.size();+}++bool near(const glm::vec3& a, const glm::vec3& b, float eps = 1e-3f) { return glm::length(a - b) < eps; }++// A body with every attribute and two layers (Smile active), a hidden eye from ZBrush, a sword with+// polygroups; the eye is the active SubTool.+Document makeScene() {+ Mesh body = makeIcosphere(2);+ body.ensureMask();+ body.ensureColors(glm::vec3(0.2f, 0.4f, 0.6f));+ body.ensurePolygroups(3);+ for (uint32_t t = 0; t < body.triangleCount(); t += 2) body.polygroups[t] = 7;+ body.ensureHidden();+ body.hidden[5] = 1;+ body.uvs.assign(body.triangleCount() * 3, glm::vec2(0.25f, 0.75f));+ for (uint32_t v = 0; v < body.vertexCount(); ++v) body.mask[v] = float(v % 5) * 0.25f;+ body.addLayer("Smile");+ body.addLayer("Blink");+ for (uint32_t v = 0; v < body.vertexCount(); v += 3) body.layers[0].delta[v] = glm::vec3(0.0f, 0.1f, 0.0f);+ for (uint32_t v = 1; v < body.vertexCount(); v += 4) body.layers[1].delta[v] = glm::vec3(0.05f, 0.0f, 0.0f);+ body.setLayerWeight(0, 0.5f);+ body.setLayerWeight(1, 1.0f);++ Mesh eye = makeIcosphere(1, 0.2f);+ for (auto& p : eye.positions) p += glm::vec3(0.4f, 0.5f, 0.8f);+ eye.recomputeAllNormals();++ Mesh sword = makeCube(4, 0.5f);+ for (auto& p : sword.positions) p += glm::vec3(2.0f, 0.0f, 0.0f);+ sword.polygroups.assign(sword.triangleCount(), 1);+ for (uint32_t t = 0; t < sword.triangleCount() / 2; ++t) sword.polygroups[t] = 2;+ sword.recomputeAllNormals();++ Document doc;+ doc.setMesh(std::move(body), "Body");+ doc.activeLayer = 0;+ doc.addSubtool(std::move(eye), "Eye", true);+ doc.gozName = "Eye_ZB";+ doc.activeSubtoolInfo().visible = false;+ doc.addSubtool(std::move(sword), "Sword", false);+ doc.path = tempPath("sf_subtool_scene.sfproj");+ return doc;+}++// A scene of the body (with layers) and the sword, both visible, the eye hidden.+Document makeExportScene() {+ Document doc = makeScene();+ doc.selectSubtool(0);+ return doc;+}++void checkSameMesh(const Mesh& a, const Mesh& b) {+ CHECK(a.positions == b.positions);+ CHECK(a.triangles == b.triangles);+ CHECK(a.mask == b.mask && a.colors == b.colors && a.polygroups == b.polygroups);+ CHECK(a.hidden == b.hidden && a.uvs == b.uvs);+ CHECK(a.layers.size() == b.layers.size());+ for (size_t i = 0; i < a.layers.size() && i < b.layers.size(); ++i) {+ CHECK(a.layers[i].name == b.layers[i].name && a.layers[i].weight == b.layers[i].weight);+ CHECK(a.layers[i].delta == b.layers[i].delta);+ }+ CHECK(a.basePositions() == b.basePositions());+}++// Rewrites the manifest of a project with `edit` applied.+bool editManifest(const std::string& path, const std::function<void(Json&)>& edit) {+ std::vector<ZipEntry> entries;+ std::string err;+ if (!readStoredZip(path, entries, err)) return false;+ for (auto& e : entries) {+ if (e.name != "manifest.json") continue;+ Json j;+ if (!Json::parse(std::string(e.data.begin(), e.data.end()), j, err)) return false;+ edit(j);+ const std::string text = j.dump();+ e.data.assign(text.begin(), text.end());+ }+ return writeStoredZip(path, entries, 1, err);+}++size_t visibleTriangles(const Document& doc) {+ size_t n = 0;+ for (int i = 0; i < doc.subtoolCount(); ++i)+ if (doc.subtools[size_t(i)].visible) n += doc.subtoolMesh(i).triangleCount();+ return n;+}++} // namespace++TEST(subtool_project_v2_round_trip) {+ Document doc = makeScene();+ const std::string path = tempPath("sf_subtool_project.sfproj");+ std::string err;+ CHECK(saveProject(path, doc, err));++ Document back;+ CHECK(loadProject(path, back, err));+ CHECK(back.subtoolCount() == 3);+ CHECK(back.activeSubtool == 1 && back.activeSubtoolInfo().name == "Eye");+ CHECK(back.subtools[0].name == "Body" && back.subtools[1].name == "Eye" && back.subtools[2].name == "Sword");+ CHECK(back.subtools[0].visible && !back.subtools[1].visible && back.subtools[2].visible);+ CHECK(back.gozName == "Eye_ZB");+ CHECK(!back.dirty() && back.path == path);+ for (int i = 0; i < 3; ++i) checkSameMesh(back.subtoolMesh(i), doc.subtoolMesh(i));+ CHECK(groupCount(back.subtoolMesh(2)) == 2);+ // Every SubTool starts with an empty history; the active layer is per SubTool.+ for (int i = 0; i < 3; ++i) {+ back.selectSubtool(i);+ CHECK(!back.undo.canUndo() && !back.undo.canRedo());+ CHECK(back.activeLayer == (i == 0 ? 0 : -1));+ }+ CHECK(!back.dirty());+ // The BVH of a SubTool selected after loading works for picking.+ back.selectSubtool(2);+ RayHit hit;+ const glm::vec3 c = back.mesh.bounds().center();+ CHECK(back.bvh.raycast(back.mesh, c + glm::vec3(0, 0, 10), glm::vec3(0, 0, -1), hit));++ // The manifest lists the SubTools and the active one.+ std::vector<ZipEntry> entries;+ CHECK(readStoredZip(path, entries, err));+ Json manifest;+ CHECK(!entries.empty() && Json::parse(std::string(entries[0].data.begin(), entries[0].data.end()), manifest, err));+ CHECK(manifest["version"].asNumber() == 2 && manifest["subtools"].size() == 3);+ CHECK(manifest["active_subtool"].asNumber() == 1 && !manifest.has("mesh"));+ CHECK(manifest["subtools"][1]["goz_name"].asString() == "Eye_ZB");++ // open_project through the command reports the SubTools.+ CommandRegistry reg;+ Document third;+ CommandResult r = reg.execute(third, "open_project", {{"path", path}});+ CHECK(r.ok && r.message.find("3 SubTools") != std::string::npos);+ std::filesystem::remove(path);+}++TEST(subtool_project_version1_still_loads) {+ // Write a single-SubTool project, then turn its manifest into the version 1 layout.+ Document doc = makeDoc(makeIcosphere(2));+ doc.mesh.ensureColors(glm::vec3(0.5f));+ Mesh m = doc.mesh;+ m.addLayer("Smile");+ m.layers[0].delta[3] = glm::vec3(0, 0.2f, 0);+ m.setLayerWeight(0, 0.75f);+ doc.setMesh(std::move(m));+ const std::string path = tempPath("sf_subtool_v1.sfproj");+ std::string err;+ CHECK(saveProject(path, doc, err));+ CHECK(editManifest(path, [](Json& j) {+ const Json st = j["subtools"][0];+ j.set("version", 1);+ j.set("mesh", st["mesh"]);+ j.set("layers", st["layers"]);+ j.set("active_layer", 0);+ j.set("subtools", Json());+ j.set("active_subtool", Json());+ }));+ Document back;+ CHECK(loadProject(path, back, err));+ CHECK(back.subtoolCount() == 1 && back.activeSubtoolInfo().name == "Sculpt");+ checkSameMesh(back.mesh, doc.mesh);+ CHECK(back.activeLayer == 0 && !back.dirty());++ // A version 2 file without SubTools, or with a broken one, is refused and leaves the scene alone.+ Document keep = makeDoc(makePlane(4));+ const size_t tris = keep.mesh.triangleCount();+ CHECK(saveProject(path, doc, err));+ CHECK(editManifest(path, [](Json& j) { j.set("subtools", Json::array()); }));+ err.clear();+ CHECK(!loadProject(path, keep, err) && !err.empty());+ CHECK(saveProject(path, makeScene(), err));+ CHECK(editManifest(path, [](Json& j) {+ Json list = Json::array();+ for (size_t i = 0; i < j["subtools"].size(); ++i) {+ Json st = j["subtools"][i];+ if (i == 2) {+ Json mesh = st["mesh"];+ mesh.set("triangle_count", mesh["triangle_count"].asNumber() + 5);+ st.set("mesh", std::move(mesh));+ }+ list.push(std::move(st));+ }+ j.set("subtools", std::move(list));+ j.set("active_subtool", 99.0); // out of range would fall back to 0, but the broken mesh fails first+ }));+ err.clear();+ CHECK(!loadProject(path, keep, err) && !err.empty());+ CHECK(keep.subtoolCount() == 1 && keep.mesh.triangleCount() == tris);+ std::filesystem::remove(path);+}++TEST(subtool_obj_export_import) {+ Document doc = makeExportScene();+ CommandRegistry reg;+ const std::string path = tempPath("sf_subtool_scene.obj");+ CommandResult r = reg.execute(doc, "save_obj", {{"path", path}});+ CHECK(r.ok && r.message.find("2 SubTools") != std::string::npos);+ const std::string text = readText(path);+ CHECK(countOf(text, "\no ") == 2);+ CHECK(text.find("\no Body\n") != std::string::npos && text.find("\no Sword\n") != std::string::npos);+ CHECK(text.find("Eye") == std::string::npos); // hidden SubTools are skipped+ CHECK(countOf(text, "\ng ") >= 4); // polygroups as `g` groups (two per mesh at least)++ std::vector<MeshObject> objects;+ std::string err;+ CHECK(loadObj(path, objects, err));+ CHECK(objects.size() == 2 && objects[0].name == "Body" && objects[1].name == "Sword");+ if (objects.size() == 2) {+ CHECK(objects[0].mesh.vertexCount() == doc.subtoolMesh(0).vertexCount());+ for (size_t v = 0; v < objects[0].mesh.vertexCount() && v < doc.subtoolMesh(0).vertexCount(); ++v)+ if (!near(objects[0].mesh.positions[v], doc.subtoolMesh(0).positions[v], 1e-5f)) {+ CHECK(false);+ break;+ }+ CHECK(objects[0].mesh.triangles == doc.subtoolMesh(0).triangles);+ CHECK(objects[1].mesh.vertexCount() == doc.subtoolMesh(2).vertexCount());+ CHECK(groupCount(objects[0].mesh) == 2 && groupCount(objects[1].mesh) == 2);+ CHECK(objects[0].mesh.hasColors() && !objects[1].mesh.hasColors());+ }++ // open: one SubTool per object; the single-mesh loader still merges everything.+ Document back;+ r = reg.execute(back, "open", {{"path", path}});+ CHECK(r.ok && back.subtoolCount() == 2 && back.subtools[0].name == "Body" && back.subtools[1].name == "Sword");+ CHECK(!back.dirty() && back.path == path);+ Mesh merged;+ CHECK(loadObj(path, merged, err));+ CHECK(merged.triangleCount() == visibleTriangles(doc));++ // subtool_append adds each object as its own SubTool.+ Document target = makeDoc(makeIcosphere(1));+ r = reg.execute(target, "subtool_append", {{"path", path}});+ CHECK(r.ok && target.subtoolCount() == 3 && target.activeSubtool == 1);+ CHECK(target.subtools[1].name == "Body" && target.subtools[2].name == "Sword");++ // A file whose `o` lines name objects without faces, and faces before any `o`.+ writeText(path, "v 0 0 0\nv 1 0 0\nv 0 1 0\nv 0 0 1\nf 1 2 3\no Empty\no Tip\nf 1 2 4\nf -1 -2 -3\no Lines\nl 1 2\n");+ CHECK(loadObj(path, objects, err));+ CHECK(objects.size() == 2 && objects[0].name.empty() && objects[1].name == "Tip");+ if (objects.size() == 2) CHECK(objects[0].mesh.vertexCount() == 3 && objects[1].mesh.triangleCount() == 2);+ std::filesystem::remove(path);+}++TEST(subtool_obj_single_object_unchanged) {+ Document doc = makeDoc(makeIcosphere(2));+ CommandRegistry reg;+ const std::string path = tempPath("sf_subtool_single.obj");+ CHECK(reg.execute(doc, "save_obj", {{"path", path}}).ok);+ const std::string text = readText(path);+ CHECK(text.find("\no ") == std::string::npos && text.find("\ng ") == std::string::npos);+ Document back;+ CHECK(reg.execute(back, "open", {{"path", path}}).ok);+ CHECK(back.subtoolCount() == 1 && back.activeSubtoolInfo().name == "sf_subtool_single");+ CHECK(back.mesh.vertexCount() == doc.mesh.vertexCount() && !back.mesh.hasPolygroups());++ // One `o` object: every vertex kept (also unused ones), named after the file.+ writeText(path, "o Thing\nv 0 0 0\nv 1 0 0\nv 0 1 0\nv 5 5 5\nf 1 2 3\n");+ CHECK(reg.execute(back, "open", {{"path", path}}).ok);+ CHECK(back.subtoolCount() == 1 && back.mesh.vertexCount() == 4 && back.activeSubtoolInfo().name == "sf_subtool_single");+ // `g` groups (ZBrush) become polygroups; a single group does not.+ writeText(path, "v 0 0 0\nv 1 0 0\nv 0 1 0\nv 0 0 1\ng default\ng Face\nf 1 2 3\ng Back\nf 1 2 4\ng Face\nf 2 3 4\n");+ Mesh m;+ std::string err;+ CHECK(loadObj(path, m, err) && m.hasPolygroups() && groupCount(m) == 2);+ CHECK(m.polygroups.size() == 3 && m.polygroups[0] == m.polygroups[2] && m.polygroups[0] != m.polygroups[1]);+ writeText(path, "v 0 0 0\nv 1 0 0\nv 0 1 0\ng default\ng Only\nf 1 2 3\n");+ CHECK(loadObj(path, m, err) && !m.hasPolygroups());+ std::filesystem::remove(path);+}++TEST(subtool_glb_export_import) {+ Document doc = makeExportScene();+ CommandRegistry reg;+ const std::string path = tempPath("sf_subtool_scene.glb");+ CHECK(reg.execute(doc, "export_glb", {{"path", path}}).ok);+ std::vector<MeshObject> objects;+ std::string err;+ CHECK(loadGltf(path, objects, err));+ CHECK(objects.size() == 2);+ if (objects.size() == 2) {+ CHECK(objects[0].name == "Body" && objects[1].name == "Sword");+ const Mesh& body = objects[0].mesh;+ CHECK(body.layers.size() == 2 && body.layers[0].name == "Smile" && body.layers[1].name == "Blink");+ CHECK(body.layers.size() == 2 && std::abs(body.layers[0].weight - 0.5f) < 1e-6f);+ CHECK(objects[1].mesh.layers.empty()); // each mesh has its own morph targets+ CHECK(body.triangleCount() == doc.subtoolMesh(0).triangleCount());+ CHECK(near(body.bounds().min, doc.subtoolMesh(0).bounds().min) && near(objects[1].mesh.bounds().max, doc.subtoolMesh(2).bounds().max));+ CHECK(body.hasColors());+ }+ Mesh merged;+ CHECK(loadGltf(path, merged, err) && merged.triangleCount() == visibleTriangles(doc));++ Document back;+ CHECK(reg.execute(back, "open", {{"path", path}}).ok);+ CHECK(back.subtoolCount() == 2 && back.subtools[1].name == "Sword" && back.mesh.layers.size() == 2);++ // Node transforms still apply per object.+ const std::string gltf = tempPath("sf_subtool_nodes.gltf");+ writeText(gltf,+ R"({"asset":{"version":"2.0"},"scene":0,"scenes":[{"nodes":[0,1]}],)"+ R"("nodes":[{"name":"Left","mesh":0,"translation":[-5,0,0]},{"mesh":0,"translation":[5,0,0]}],)"+ R"("meshes":[{"name":"Tri","primitives":[{"attributes":{"POSITION":0}}]}],)"+ R"("accessors":[{"bufferView":0,"componentType":5126,"count":3,"type":"VEC3"}],)"+ R"("bufferViews":[{"buffer":0,"byteLength":36}],)"+ R"("buffers":[{"byteLength":36,"uri":"data:application/octet-stream;base64,AAAAAAAAAAAAAAAAAACAPwAAAAAAAAAAAAAAAAAAgD8AAAAA"}]})");+ CHECK(loadGltf(gltf, objects, err));+ CHECK(objects.size() == 2 && objects[0].name == "Left" && objects[1].name == "Tri");+ if (objects.size() == 2) CHECK(objects[0].mesh.bounds().max.x < -3.0f && objects[1].mesh.bounds().min.x > 3.0f);+ std::filesystem::remove(path);+ std::filesystem::remove(gltf);+}++TEST(subtool_glb_single_object_unchanged) {+ Document doc = makeDoc(makeIcosphere(2));+ doc.path = tempPath("Head.obj");+ CommandRegistry reg;+ const std::string path = tempPath("sf_subtool_single.glb");+ CHECK(reg.execute(doc, "export_glb", {{"path", path}}).ok);+ std::vector<MeshObject> objects;+ std::string err;+ CHECK(loadGltf(path, objects, err) && objects.size() == 1 && objects[0].name == "Head");+ Document back;+ CHECK(reg.execute(back, "open", {{"path", path}}).ok);+ CHECK(back.subtoolCount() == 1 && back.activeSubtoolInfo().name == "sf_subtool_single");+ std::filesystem::remove(path);+}++TEST(subtool_fbx_export_import) {+ Document doc = makeExportScene();+ CommandRegistry reg;+ const std::string path = tempPath("sf_subtool_scene.fbx");+ CHECK(reg.execute(doc, "export_fbx", {{"path", path}}).ok);+ std::vector<MeshObject> objects;+ std::string err;+ CHECK(loadFbx(path, objects, err));+ CHECK(objects.size() == 2);+ if (objects.size() == 2) {+ CHECK(objects[0].name == "Body" && objects[1].name == "Sword");+ CHECK(objects[0].mesh.layers.size() == 2 && objects[1].mesh.layers.empty());+ CHECK(objects[0].mesh.triangleCount() == doc.subtoolMesh(0).triangleCount());+ CHECK(near(objects[1].mesh.bounds().center(), doc.subtoolMesh(2).bounds().center()));+ }++ // LODs: a LOD group per SubTool; import takes LOD0 of each, named after its group.+ CHECK(reg.execute(doc, "export_fbx", {{"path", path}, {"lods", 3.0}}).ok);+ CHECK(loadFbx(path, objects, err));+ CHECK(objects.size() == 2);+ if (objects.size() == 2) {+ CHECK(objects[0].name == "Body" && objects[1].name == "Sword");+ CHECK(objects[0].mesh.triangleCount() == doc.subtoolMesh(0).triangleCount());+ CHECK(objects[1].mesh.triangleCount() == doc.subtoolMesh(2).triangleCount());+ }+ Document back;+ CHECK(reg.execute(back, "open", {{"path", path}}).ok);+ CHECK(back.subtoolCount() == 2 && back.subtools[0].name == "Body");++ // Unreal preset: one model per visible SubTool; layers on any of them make it skeletal (LOD0 only).+ UnrealExportOptions uo;+ uo.folder = std::filesystem::temp_directory_path().string();+ UnrealExportResult ur;+ CHECK(exportForUnreal(doc, uo, ur, err));+ CHECK(ur.skeletal && ur.lodCount == 1);+ CHECK(loadFbx(ur.path, objects, err) && objects.size() == 2);+ std::filesystem::remove(ur.path);+ doc.subtools[0].visible = false; // the layered body (active, but hidden from export)+ doc.subtools[1].visible = true;+ CHECK(exportForUnreal(doc, uo, ur, err));+ CHECK(!ur.skeletal && ur.lodCount == 4);+ CHECK(loadFbx(ur.path, objects, err) && objects.size() == 2);+ if (objects.size() == 2) CHECK(objects[0].name == "Eye" && objects[1].name == "Sword");+ std::filesystem::remove(ur.path);+ std::filesystem::remove(path);+}++TEST(subtool_usd_export_import) {+ Document doc = makeExportScene();+ doc.path = tempPath("Hero.sfproj");+ CommandRegistry reg;+ const std::string path = tempPath("sf_subtool_scene.usda");+ CHECK(reg.execute(doc, "export_usd", {{"path", path}}).ok);+ const std::string text = readText(path);+ // One Mesh prim per visible SubTool under the root; the layered body sits in its own SkelRoot.+ CHECK(text.find("defaultPrim = \"Hero\"") != std::string::npos);+ CHECK(text.find("def SkelRoot \"Body\"") != std::string::npos && text.find("def Mesh \"Sword\"") != std::string::npos);+ CHECK(countOf(text, "def Mesh ") == 2 && text.find("Eye") == std::string::npos);+ CHECK(text.find("</Hero/Body/Skel>") != std::string::npos && text.find("</Hero/Body/Skel/Weights>") != std::string::npos);+ // Polypaint on the body only: it binds the painted material, the sword the plain clay.+ CHECK(text.find("rel material:binding = </Hero/Materials/PaintedClay>") != std::string::npos);+ CHECK(text.find("rel material:binding = </Hero/Materials/Clay>") != std::string::npos);+ CHECK(countOf(text, "{") == countOf(text, "}") && countOf(text, "[") == countOf(text, "]"));++ std::vector<MeshObject> objects;+ SplatCloud splats;+ std::string err;+ CHECK(loadUsd(path, objects, splats, err));+ CHECK(objects.size() == 2);+ if (objects.size() == 2) {+ CHECK(objects[0].name == "Body" && objects[1].name == "Sword");+ CHECK(objects[0].mesh.layers.size() == 2 && objects[1].mesh.layers.empty());+ if (objects[0].mesh.layers.size() == 2) CHECK(std::abs(objects[0].mesh.layers[0].weight - 0.5f) < 1e-6f);+ CHECK(objects[0].mesh.triangleCount() == doc.subtoolMesh(0).triangleCount());+ }+ Document back;+ CHECK(reg.execute(back, "open", {{"path", path}}).ok);+ CHECK(back.subtoolCount() == 2 && back.subtools[1].name == "Sword");++ // USDZ too, and names that aren't USD identifiers stay valid and unique.+ doc.subtools[0].name = "Body 1";+ doc.subtools[2].name = "Body+1";+ const std::string usdz = tempPath("sf_subtool_scene.usdz");+ CHECK(reg.execute(doc, "export_usd", {{"path", usdz}}).ok);+ CHECK(loadUsd(usdz, objects, splats, err) && objects.size() == 2);+ if (objects.size() == 2) CHECK(objects[0].name == "Body_1" && objects[1].name == "Body_1_2");++ // A single SubTool is still the prim "Sculpt".+ Document single = makeDoc(makeIcosphere(1));+ CHECK(reg.execute(single, "export_usd", {{"path", path}}).ok);+ CHECK(readText(path).find("def Mesh \"Sculpt\"") != std::string::npos);+ std::filesystem::remove(path);+ std::filesystem::remove(usdz);+}++TEST(subtool_goz_send_receive_and_export) {+ namespace fs = std::filesystem;+ const fs::path root = fs::temp_directory_path() / "sf_subtool_goz";+ fs::remove_all(root);+ Document doc = makeExportScene();+ CommandRegistry reg;+ CommandResult r = reg.execute(doc, "goz_send", {{"folder", root.string()}, {"launch", false}});+ CHECK(r.ok && r.message.find("1 more SubTools") != std::string::npos);+ CHECK(doc.gozName == "Body" && doc.subtools[2].gozName == "Sword" && doc.subtools[1].gozName == "Eye_ZB");+ const fs::path project = root / "GoZProjects" / "Default";+ CHECK(fs::exists(project / "Body.GoZ") && fs::exists(project / "Sword.GoZ") && !fs::exists(project / "Eye_ZB.GoZ"));++ // Receiving into a new scene gives the SubTools back with polygroups, mask and polypaint.+ Document back;+ r = reg.execute(back, "goz_receive", {{"folder", root.string()}});+ CHECK(r.ok && back.subtoolCount() == 2);+ CHECK(back.subtools[0].name == "Body" && back.subtools[1].name == "Sword");+ CHECK(back.gozName == "Body" && back.subtools[1].gozName == "Sword");+ CHECK(back.mesh.triangleCount() == doc.subtoolMesh(0).triangleCount() && back.mesh.hasColors() && back.mesh.hasMask());+ CHECK(groupCount(back.subtoolMesh(1)) == 2);++ // The merged form for callers that want one mesh.+ Mesh merged;+ std::string msg;+ CHECK(gozReceive(root.string(), merged, msg) && msg.find("(merged)") != std::string::npos);+ CHECK(merged.triangleCount() == visibleTriangles(doc));++ // goz_export: one file per visible SubTool beside the path.+ const std::string out = (root / "Scene.GoZ").string();+ CHECK(reg.execute(doc, "goz_export", {{"path", out}}).ok);+ Mesh body, sword;+ std::string err;+ GozInfo info;+ CHECK(loadGoz((root / "Scene_Body.GoZ").string(), body, err, &info) && info.name == "Body");+ CHECK(loadGoz((root / "Scene_Sword.GoZ").string(), sword, err) && sword.triangleCount() == doc.subtoolMesh(2).triangleCount());+ fs::remove_all(root);+}++TEST(subtool_merged_exports) {+ Document doc = makeExportScene();+ CommandRegistry reg;+ const size_t tris = visibleTriangles(doc);+ std::string err;+ const std::string stl = tempPath("sf_subtool_scene.stl");+ CHECK(reg.execute(doc, "export_stl", {{"path", stl}}).ok);+ Mesh m;+ CHECK(loadStl(stl, m, err) && m.triangleCount() == tris);+ const std::string ply = tempPath("sf_subtool_scene.ply");+ CHECK(reg.execute(doc, "export_ply", {{"path", ply}}).ok);+ SplatCloud splats;+ PlyContent content;+ CHECK(loadPly(ply, m, splats, content, err) && content == PlyContent::Mesh && m.triangleCount() == tris);+ // Splats cover every visible SubTool (the sword lies at x = 2).+ CHECK(reg.execute(doc, "mesh_to_splats", {{"count", 4000.0}}).ok);+ CHECK(doc.splats.bounds(1.0f).max.x > 2.0f);+ // Nothing visible: exporters say so.+ for (auto& s : doc.subtools) s.visible = false;+ CHECK(!reg.execute(doc, "export_glb", {{"path", tempPath("sf_subtool_none.glb")}}).ok);+ CHECK(!reg.execute(doc, "save_obj", {{"path", tempPath("sf_subtool_none.obj")}}).ok);+ CHECK(!reg.execute(doc, "export_ply", {{"path", ply}}).ok);+ std::filesystem::remove(stl);+ std::filesystem::remove(ply);+}++TEST(subtool_export_lods_per_subtool) {+ Document doc = makeExportScene();+ CommandRegistry reg;+ const std::string base = tempPath("sf_subtool_rock.glb");+ CHECK(reg.execute(doc, "export_lods", {{"path", base}, {"levels", 2.0}}).ok);+ std::vector<MeshObject> objects;+ std::string err;+ const std::string lod1 = tempPath("sf_subtool_rock_LOD1.glb");+ CHECK(loadGltf(lod1, objects, err) && objects.size() == 2);+ if (objects.size() == 2) CHECK(objects[0].name == "Body" && objects[0].mesh.triangleCount() < doc.subtoolMesh(0).triangleCount());+ std::filesystem::remove(tempPath("sf_subtool_rock_LOD0.glb"));+ std::filesystem::remove(lod1);+}++TEST(subtool_loaders_survive_malformed_objects) {+ std::string err;+ std::vector<MeshObject> objects;+ SplatCloud splats;+ const std::string obj = tempPath("sf_subtool_bad.obj");+ // Bad indices in a later object, empty names, nothing but `o` lines.+ for (const char* text : {"o A\nv 0 0 0\nv 1 0 0\nv 0 1 0\nf 1 2 3\no B\nf 1 2 9\n", "o\no\no\n", "o A\r\nv 0 0 0\r\nf 1 1 1\r\n",+ "v 0 0 0\nv 1 0 0\nv 0 1 0\no X\nf -1 -2 -3\no Y\nf -4 1 2\n", "g\ng\nv 1 1 1\nf 1 1 1 1 1\n"}) {+ writeText(obj, text);+ loadObj(obj, objects, err); // either outcome; no crash+ Mesh m;+ loadObj(obj, m, err);+ }+ std::filesystem::remove(obj);++ const std::string usda = tempPath("sf_subtool_bad.usda");+ for (const char* text :+ {"#usda 1.0\ndef Mesh \"A\" { point3f[] points = [(0,0,0),(1,0,0),(0,1,0)] int[] faceVertexCounts = [3] "+ "int[] faceVertexIndices = [0, -1, 2] }\n",+ "#usda 1.0\ndef Mesh \"A\" { point3f[] points = [(0,0,0),(1,0,0),(0,1,0)] int[] faceVertexCounts = [3] "+ "int[] faceVertexIndices = [0, 1, 2] uniform token[] skel:blendShapes = [\"S\"] rel skel:blendShapeTargets = [<S>] "+ "rel skel:skeleton = </Nowhere> def BlendShape \"S\" { uniform vector3f[] offsets = [(1,1,1)] "+ "uniform int[] pointIndices = [-7] } }\n",+ "#usda 1.0\ndef SkelRoot \"R\" { def Mesh \"M\" { point3f[] points = [(0,0,0),(1,0,0),(0,1,0)] "+ "int[] faceVertexCounts = [3] int[] faceVertexIndices = [0, 1, 2] rel skel:skeleton = </R/K> } "+ "def Skeleton \"K\" { rel skel:animationSource = </R> } }\n"}) {+ writeText(usda, text);+ loadUsd(usda, objects, splats, err);+ Mesh m;+ loadUsd(usda, m, splats, err);+ }+ // The second file loads: the stray point index is ignored.+ writeText(usda, "#usda 1.0\ndef SkelRoot \"Rig\" { def Mesh \"Mesh\" { point3f[] points = [(0,0,0),(1,0,0),(0,1,0)] "+ "int[] faceVertexCounts = [3] int[] faceVertexIndices = [0, 1, 2] } }\n");+ CHECK(loadUsd(usda, objects, splats, err) && objects.size() == 1 && objects[0].name == "Rig");+ std::filesystem::remove(usda);++ const std::string gltf = tempPath("sf_subtool_bad.gltf");+ writeText(gltf, R"({"asset":{"version":"2.0"},"scenes":[{"nodes":[0,1,7]}],"nodes":[{"mesh":5},{"mesh":0}],"meshes":[{"primitives":[{"attributes":{"POSITION":3}}]}]})");+ loadGltf(gltf, objects, err);+ std::filesystem::remove(gltf);+ CHECK(true);+}