Skip to content

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.

SubTools core: multiple meshes per scene, ZBrush style

islandmed9876c12f65fd
diff --git a/CMakeLists.txt b/CMakeLists.txt
index 69e63a53..7c1b5fe2 100644
--- a/CMakeLists.txt
+++ b/CMakeLists.txt
@@ -33,6 +33,7 @@ add_library(sculptforge_core STATIC
src/core/Document.cpp
src/core/Commands.cpp
src/core/Polygroups.cpp
+ src/core/SubTools.cpp
src/core/Decimate.cpp
src/core/Script.cpp
src/core/Json.cpp
diff --git a/src/core/Commands.cpp b/src/core/Commands.cpp
index a02511e2..6bbe9495 100644
--- a/src/core/Commands.cpp
+++ b/src/core/Commands.cpp
@@ -8,6 +8,7 @@
#include "core/ImageTo3D.h"
#include "core/Masking.h"
#include "core/Polygroups.h"
+#include "core/SubTools.h"
#include "core/Polypaint.h"
#include "core/Primitives.h"
#include "core/Project.h"
@@ -85,7 +86,7 @@ CommandRegistry::CommandRegistry() {
{{"subdivisions", T::Number, "Icosphere subdivision level (0-8). Default 6.", false}},
[](Document& doc, const Args& a) -> CommandResult {
int level = std::clamp(int(argNumber(a, "subdivisions", 6)), 0, 8);
- doc.setMesh(makeIcosphere(level));
+ doc.setMesh(makeIcosphere(level), "Sphere");
doc.path.clear();
return {true, "Created sphere with " + std::to_string(doc.mesh.triangleCount()) + " triangles"};
}});
@@ -95,7 +96,7 @@ CommandRegistry::CommandRegistry() {
{{"resolution", T::Number, "Grid cells per side (1-2000). Default 128.", false}},
[](Document& doc, const Args& a) -> CommandResult {
int res = std::clamp(int(argNumber(a, "resolution", 128)), 1, 2000);
- doc.setMesh(makePlane(res));
+ doc.setMesh(makePlane(res), "Plane");
doc.path.clear();
return {true, "Created plane with " + std::to_string(doc.mesh.triangleCount()) + " triangles"};
}});
@@ -143,7 +144,8 @@ CommandRegistry::CommandRegistry() {
std::string msg = "Opened " + path;
const bool hasMesh = m.triangleCount() > 0;
if (hasMesh) {
- doc.setMesh(std::move(m));
+ 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()));
doc.path = ext == ".obj" ? path : std::string(); // other formats are exported explicitly
if (ext == ".goz") doc.gozName = goz.name;
msg += " (" + std::to_string(doc.mesh.triangleCount()) + " triangles" +
@@ -617,6 +619,7 @@ CommandRegistry::CommandRegistry() {
registerMaskingCommands(*this);
registerPolygroupCommands(*this);
+ registerSubToolCommands(*this);
registerPaintCommands(*this); // core/Polypaint.cpp
registerGozCommands(*this); // goz_import/export/send/receive, export_stl (io/GozCommands.cpp)
registerProjectCommands(*this); // keep last (core/Project.cpp)
diff --git a/src/core/Document.cpp b/src/core/Document.cpp
index 44755451..77c1bb1f 100644
--- a/src/core/Document.cpp
+++ b/src/core/Document.cpp
@@ -7,15 +7,124 @@
namespace sf {
-void Document::setMesh(Mesh m) {
+Document::Document() {
+ subtools.emplace_back();
+ subtools.back().id = 1;
+ subtools.back().name = "Sculpt";
+}
+
+void Document::setMesh(Mesh m, std::string name) {
mesh = std::move(m);
mesh.topologyDirty = true;
bvh.build(mesh);
undo.clear();
- markClean();
activeLayer = -1;
bvhDirty = false;
gozName.clear();
+ subtools.clear();
+ subtools.push_back(SubTool{nextSubtoolId_++, name.empty() ? "Sculpt" : std::move(name)});
+ activeSubtool = 0;
+ markClean();
+}
+
+bool Document::dirty() const {
+ if (modified || undo.revision() != cleanRevision_ || splatsVersion != cleanSplatsVersion_) return true;
+ for (int i = 0; i < subtoolCount(); ++i)
+ if (i != activeSubtool && subtools[size_t(i)].undo.revision() != subtools[size_t(i)].cleanRevision) return true;
+ return false;
+}
+
+void Document::markClean() {
+ modified = false;
+ cleanRevision_ = undo.revision();
+ cleanSplatsVersion_ = splatsVersion;
+ for (int i = 0; i < subtoolCount(); ++i)
+ if (i != activeSubtool) subtools[size_t(i)].cleanRevision = subtools[size_t(i)].undo.revision();
+}
+
+void Document::selectSubtool(int i) {
+ if (i < 0 || i >= subtoolCount() || i == activeSubtool) return;
+ // Check the active SubTool back in, then check `i` out. Swapping keeps each
+ // mesh's GPU dirty state, so the renderer doesn't re-upload anything.
+ auto swapIn = [this](SubTool& s) {
+ std::swap(mesh, s.mesh);
+ std::swap(bvh, s.bvh);
+ std::swap(undo, s.undo);
+ std::swap(activeLayer, s.activeLayer);
+ std::swap(gozName, s.gozName);
+ std::swap(bvhDirty, s.bvhDirty);
+ std::swap(cleanRevision_, s.cleanRevision);
+ };
+ swapIn(subtools[size_t(activeSubtool)]);
+ activeSubtool = i;
+ swapIn(subtools[size_t(i)]);
+ if (bvh.nodeCount() == 0 && mesh.triangleCount()) bvhDirty = true; // built on first use
+ syncBvh();
+}
+
+int Document::addSubtool(Mesh m, std::string name, bool select, int at) {
+ SubTool s;
+ s.id = nextSubtoolId_++;
+ s.name = uniqueSubtoolName(name.empty() ? "SubTool" : name);
+ s.mesh = std::move(m);
+ s.mesh.topologyDirty = true;
+ s.bvh.build(s.mesh);
+ const int index = at < 0 || at > subtoolCount() ? subtoolCount() : at;
+ subtools.insert(subtools.begin() + index, std::move(s));
+ if (index <= activeSubtool) ++activeSubtool;
+ modified = true;
+ if (select) selectSubtool(index);
+ return index;
+}
+
+void Document::replaceActiveMesh(Mesh m) {
+ mesh = std::move(m);
+ mesh.topologyDirty = true;
+ bvh.build(mesh);
+ bvhDirty = false;
+ undo.clear();
+ cleanRevision_ = ~uint64_t(0); // unsaved until the next save
+ activeLayer = -1;
+ modified = true;
+}
+
+bool Document::removeSubtool(int i) {
+ if (subtoolCount() <= 1 || i < 0 || i >= subtoolCount()) return false;
+ if (i == activeSubtool) selectSubtool(i + 1 < subtoolCount() ? i + 1 : i - 1);
+ subtools.erase(subtools.begin() + i);
+ if (activeSubtool > i) --activeSubtool;
+ modified = true;
+ return true;
+}
+
+void Document::moveSubtool(int i, int direction) {
+ const int j = i + (direction < 0 ? -1 : 1);
+ if (i < 0 || j < 0 || i >= subtoolCount() || j >= subtoolCount()) return;
+ std::swap(subtools[size_t(i)], subtools[size_t(j)]);
+ if (activeSubtool == i) activeSubtool = j;
+ else if (activeSubtool == j) activeSubtool = i;
+ modified = true;
+}
+
+int Document::findSubtool(const std::string& name) const {
+ for (int i = 0; i < subtoolCount(); ++i)
+ if (subtools[size_t(i)].name == name) return i;
+ return -1;
+}
+
+std::string Document::uniqueSubtoolName(const std::string& wanted) const {
+ if (findSubtool(wanted) < 0) return wanted;
+ for (int n = 2;; ++n) {
+ std::string candidate = wanted + " " + std::to_string(n);
+ if (findSubtool(candidate) < 0) return candidate;
+ }
+}
+
+AABB Document::visibleBounds() const {
+ AABB b;
+ for (int i = 0; i < subtoolCount(); ++i)
+ if (subtools[size_t(i)].visible && subtoolMesh(i).vertexCount()) b.expand(subtoolMesh(i).bounds());
+ return b;
}
int Document::addBrush(BrushRecipe recipe) {
diff --git a/src/core/Document.h b/src/core/Document.h
index abf61c07..01b2f969 100644
--- a/src/core/Document.h
+++ b/src/core/Document.h
@@ -15,10 +15,30 @@
namespace sf {
+// One object in the scene, like a ZBrush SubTool: a body, the eyes, the
+// teeth, a sword. Each keeps its own mesh, attributes, layers and undo
+// history. The active SubTool is "checked out" into Document::mesh / bvh /
+// undo, so every tool and command keeps working on the active one; its slot
+// here holds only the name and flags until another SubTool is selected.
+struct SubTool {
+ uint32_t id = 0; // stable for the session (renderer slots, UI selection)
+ std::string name;
+ bool visible = true;
+ // Inactive SubTools only (empty while active).
+ Mesh mesh;
+ BVH bvh;
+ UndoStack undo;
+ int activeLayer = -1;
+ std::string gozName;
+ bool bvhDirty = false;
+ uint64_t cleanRevision = 0;
+};
+
// Everything that makes up the open scene: the mesh, its acceleration
// structure and edit history. UI-independent so it can be driven by tests,
// scripts or an AI assistant through the command registry.
struct Document {
+ // The active SubTool's working data (see SubTool).
Mesh mesh;
BVH bvh;
UndoStack undo;
@@ -54,24 +74,49 @@ struct Document {
// keeps it as loaded so CLI and scripts round-trip it unchanged.
Json projectSettings = Json::object();
- // Unsaved changes: any undoable edit, splat edit or `modified` since the
- // last markClean() (save, open, new scene).
- bool dirty() const {
- return modified || undo.revision() != cleanRevision_ || splatsVersion != cleanSplatsVersion_;
- }
- void markClean() {
- modified = false;
- cleanRevision_ = undo.revision();
- cleanSplatsVersion_ = splatsVersion;
- }
+ // Unsaved changes: any undoable edit (in any SubTool), splat edit or
+ // `modified` since the last markClean() (save, open, new scene).
+ bool dirty() const;
+ void markClean();
+
+ // --- SubTools. There is always at least one; `subtools[activeSubtool]` is the
+ // active one (its data lives in mesh / bvh / undo above). Adding, removing,
+ // reordering and merging SubTools is not undoable (as in ZBrush); it sets
+ // `modified`.
+ std::vector<SubTool> subtools; // one "Sculpt" SubTool to start with
+ Document();
+ int activeSubtool = 0;
+ int subtoolCount() const { return int(subtools.size()); }
+ SubTool& activeSubtoolInfo() { return subtools[size_t(activeSubtool)]; }
+ const SubTool& activeSubtoolInfo() const { return subtools[size_t(activeSubtool)]; }
+ // The mesh of SubTool `i`, active or not.
+ Mesh& subtoolMesh(int i) { return i == activeSubtool ? mesh : subtools[size_t(i)].mesh; }
+ const Mesh& subtoolMesh(int i) const { return i == activeSubtool ? mesh : subtools[size_t(i)].mesh; }
+ // Makes SubTool `i` the one tools and commands edit.
+ void selectSubtool(int i);
+ // Inserts a SubTool at `at` (-1 = end of the list), made active when `select`; returns its index.
+ int addSubtool(Mesh m, std::string name, bool select = true, int at = -1);
+ // Replaces the active SubTool's mesh outside undo (its history is cleared), e.g. after a merge.
+ void replaceActiveMesh(Mesh m);
+ // Removes SubTool `i` (never the last one); the active one moves to a neighbour if needed.
+ bool removeSubtool(int i);
+ // Moves SubTool `i` one place up (-1) or down (+1) in the list.
+ void moveSubtool(int i, int direction);
+ // Index of the SubTool called `name` (exact match, first one), or -1.
+ int findSubtool(const std::string& name) const;
+ // A name not used by any SubTool yet ("Eye", "Eye 2", ...).
+ std::string uniqueSubtoolName(const std::string& wanted) const;
+ // Bounds of every visible SubTool.
+ AABB visibleBounds() const;
- // Replaces the mesh and clears the edit history.
- void setMesh(Mesh m);
+ // Replaces the whole scene with one SubTool holding `m` and clears the edit history.
+ void setMesh(Mesh m, std::string name = "Sculpt");
// Replaces the mesh as an undoable topology change.
void replaceMeshUndoable(Mesh m, std::string label);
private:
uint64_t cleanRevision_ = 0, cleanSplatsVersion_ = 0;
+ uint32_t nextSubtoolId_ = 2;
};
} // namespace sf
diff --git a/src/core/Polygroups.cpp b/src/core/Polygroups.cpp
index b2ceb942..8a433a65 100644
--- a/src/core/Polygroups.cpp
+++ b/src/core/Polygroups.cpp
@@ -267,12 +267,19 @@ bool polygroupIsolated(const Mesh& mesh, uint32_t group) {
Mesh deleteHiddenTriangles(const Mesh& mesh) {
if (!mesh.hasHidden()) return mesh;
+ std::vector<uint8_t> keep(mesh.triangleCount());
+ for (uint32_t t = 0; t < keep.size(); ++t) keep[t] = !mesh.triangleHidden(t);
+ return extractTriangles(mesh, keep);
+}
+
+Mesh extractTriangles(const Mesh& mesh, const std::vector<uint8_t>& keep) {
const size_t nv = mesh.vertexCount(), nt = mesh.triangleCount();
std::vector<uint32_t> remap(nv, kUnassigned);
std::vector<uint32_t> kept;
Mesh out;
+ bool anyHidden = false;
for (uint32_t t = 0; t < nt; ++t) {
- if (mesh.triangleHidden(t)) continue;
+ if (t >= keep.size() || !keep[t]) continue;
glm::uvec3 tri;
for (int k = 0; k < 3; ++k) {
uint32_t& r = remap[mesh.triangles[t][k]];
@@ -283,6 +290,8 @@ Mesh deleteHiddenTriangles(const Mesh& mesh) {
tri[k] = r;
}
out.triangles.push_back(tri);
+ out.hidden.push_back(mesh.triangleHidden(t) ? 1 : 0);
+ anyHidden |= mesh.triangleHidden(t);
if (mesh.hasPolygroups()) out.polygroups.push_back(mesh.polygroups[t]);
if (mesh.hasUvs()) out.uvs.insert(out.uvs.end(), mesh.uvs.begin() + std::ptrdiff_t(t) * 3,
mesh.uvs.begin() + std::ptrdiff_t(t) * 3 + 3);
@@ -302,6 +311,7 @@ Mesh deleteHiddenTriangles(const Mesh& mesh) {
out.layers.push_back(std::move(nl));
}
}
+ if (!anyHidden) out.clearHidden();
out.rebuildTopology();
out.recomputeAllNormals();
return out;
diff --git a/src/core/Polygroups.h b/src/core/Polygroups.h
index e3854c48..40442c0b 100644
--- a/src/core/Polygroups.h
+++ b/src/core/Polygroups.h
@@ -57,6 +57,8 @@ bool polygroupIsolated(const Mesh& mesh, uint32_t group);
// Copy of `mesh` without its hidden triangles: unused vertices are removed and
// every attribute (mask, colours, polygroups, UVs, sculpt layers) compacted.
Mesh deleteHiddenTriangles(const Mesh& mesh);
+// Copy of the triangles with keep[t] != 0, compacted the same way (hidden flags are kept).
+Mesh extractTriangles(const Mesh& mesh, const std::vector<uint8_t>& keep);
// Adds the polygroup and visibility commands (polygroup_*, hide_polygroup,
// isolate_polygroup, show_all, invert_visibility, hide_rect, delete_hidden).
diff --git a/src/core/Primitives.cpp b/src/core/Primitives.cpp
index 0a34faef..e88f215b 100644
--- a/src/core/Primitives.cpp
+++ b/src/core/Primitives.cpp
@@ -74,6 +74,33 @@ Mesh makePlane(int resolution, float size) {
return m;
}
+Mesh makeCube(int resolution, float size) {
+ const int n = std::max(resolution, 1);
+ const float h = size * 0.5f;
+ Mesh raw;
+ // Each side: a grid spanned by axes u, v from its corner, wound to face outwards.
+ const glm::vec3 axes[6][3] = {{{1, 0, 0}, {0, 1, 0}, {0, 0, 1}}, {{-1, 0, 0}, {0, 1, 0}, {0, 0, -1}},
+ {{0, 1, 0}, {0, 0, 1}, {1, 0, 0}}, {{0, -1, 0}, {0, 0, 1}, {-1, 0, 0}},
+ {{0, 0, 1}, {1, 0, 0}, {0, 1, 0}}, {{0, 0, -1}, {1, 0, 0}, {0, -1, 0}}};
+ for (int f = 0; f < 6; ++f) {
+ const glm::vec3 normal = axes[f][0], u = axes[f][2], v = axes[f][1];
+ const uint32_t first = uint32_t(raw.positions.size());
+ for (int j = 0; j <= n; ++j)
+ for (int i = 0; i <= n; ++i)
+ raw.positions.push_back(h * (normal + (2.0f * float(i) / float(n) - 1.0f) * u +
+ (2.0f * float(j) / float(n) - 1.0f) * v));
+ for (int j = 0; j < n; ++j)
+ for (int i = 0; i < n; ++i) {
+ const uint32_t a = first + uint32_t(j * (n + 1) + i), b = a + 1, c = a + uint32_t(n + 1), d = c + 1;
+ raw.triangles.push_back({a, c, b}); // (v x u) = outward normal on every side
+ raw.triangles.push_back({b, c, d});
+ raw.polygroups.push_back(uint32_t(f + 1));
+ raw.polygroups.push_back(uint32_t(f + 1));
+ }
+ }
+ return weldImported(raw);
+}
+
Mesh loopSubdivide(const Mesh& src) {
const uint32_t nv = static_cast<uint32_t>(src.vertexCount());
diff --git a/src/core/Primitives.h b/src/core/Primitives.h
index 3b2d50ee..cbadd073 100644
--- a/src/core/Primitives.h
+++ b/src/core/Primitives.h
@@ -9,6 +9,8 @@ namespace sf {
// Returned meshes have topology and normals built.
Mesh makeIcosphere(int subdivisions, float radius = 1.0f);
Mesh makePlane(int resolution, float size = 2.0f);
+// Closed cube from -size/2 to size/2 with `resolution` cells per edge (welded, one polygroup per side).
+Mesh makeCube(int resolution, float size = 2.0f);
// Loop subdivision (smooth; boundaries follow the cubic B-spline rule).
// Layers are subdivided with the same stencils; mask/colours/UVs are
// interpolated linearly and polygroups/hidden flags are inherited.
diff --git a/src/core/SubTools.cpp b/src/core/SubTools.cpp
new file mode 100644
index 00000000..db9bfd20
--- /dev/null
+++ b/src/core/SubTools.cpp
@@ -0,0 +1,358 @@
+// SculptForge - open source digital sculpting
+// SPDX-License-Identifier: GPL-3.0-or-later
+#include "core/SubTools.h"
+
+#include "core/Commands.h"
+#include "core/Polygroups.h"
+#include "core/Primitives.h"
+
+#include <algorithm>
+#include <filesystem>
+#include <map>
+#include <numeric>
+
+namespace sf {
+
+Mesh mergeMeshes(const std::vector<const Mesh*>& meshes) {
+ Mesh out;
+ bool mask = false, colors = false, hidden = false, uvs = false;
+ std::vector<std::string> layerNames;
+ std::map<std::string, float> layerWeights;
+ for (const Mesh* m : meshes) {
+ mask |= m->hasMask();
+ colors |= m->hasColors();
+ hidden |= m->hasHidden();
+ uvs |= m->hasUvs();
+ for (const auto& l : m->layers)
+ if (layerWeights.emplace(l.name, l.weight).second) layerNames.push_back(l.name);
+ }
+ for (const auto& name : layerNames) out.layers.push_back({name, {}, layerWeights[name]});
+
+ uint32_t groupOffset = 0;
+ for (const Mesh* m : meshes) {
+ const uint32_t first = uint32_t(out.positions.size());
+ const size_t nv = m->vertexCount(), nt = m->triangleCount();
+ out.positions.insert(out.positions.end(), m->positions.begin(), m->positions.end());
+ for (const auto& t : m->triangles) out.triangles.push_back(t + glm::uvec3(first));
+ if (mask) {
+ if (m->hasMask()) out.mask.insert(out.mask.end(), m->mask.begin(), m->mask.end());
+ else out.mask.resize(out.mask.size() + nv, 0.0f);
+ }
+ if (colors) {
+ if (m->hasColors()) out.colors.insert(out.colors.end(), m->colors.begin(), m->colors.end());
+ else out.colors.resize(out.colors.size() + nv, glm::vec3(1.0f));
+ }
+ if (hidden) {
+ if (m->hasHidden()) out.hidden.insert(out.hidden.end(), m->hidden.begin(), m->hidden.end());
+ else out.hidden.resize(out.hidden.size() + nt, 0);
+ }
+ if (uvs) {
+ if (m->hasUvs()) out.uvs.insert(out.uvs.end(), m->uvs.begin(), m->uvs.end());
+ else out.uvs.resize(out.uvs.size() + nt * 3, glm::vec2(0.0f));
+ }
+ // Groups stay distinct per input, so "split by groups" gives the pieces back.
+ uint32_t maxGroup = 0;
+ for (uint32_t t = 0; t < nt; ++t) {
+ const uint32_t g = m->polygroupAt(t);
+ out.polygroups.push_back(groupOffset + g);
+ maxGroup = std::max(maxGroup, g);
+ }
+ groupOffset += maxGroup + 1;
+ if (!layerNames.empty()) {
+ const auto& base = m->basePositions();
+ out.base.insert(out.base.end(), base.begin(), base.end());
+ for (auto& ol : out.layers) {
+ auto it = std::find_if(m->layers.begin(), m->layers.end(), [&](const SculptLayer& l) { return l.name == ol.name; });
+ if (it != m->layers.end()) ol.delta.insert(ol.delta.end(), it->delta.begin(), it->delta.end());
+ else ol.delta.resize(ol.delta.size() + nv, glm::vec3(0.0f));
+ }
+ }
+ }
+ // Group ids start at 0 in the first input; shift so ids are 1-based like new groups elsewhere.
+ for (auto& g : out.polygroups) ++g;
+ out.rebuildTopology();
+ if (!out.layers.empty()) out.evaluateAll(); // weights of same-named layers may have differed
+ out.recomputeAllNormals();
+ return out;
+}
+
+Mesh mergedVisibleMesh(const Document& doc) {
+ if (doc.subtoolCount() == 1) return doc.mesh;
+ std::vector<const Mesh*> meshes;
+ for (int i = 0; i < doc.subtoolCount(); ++i)
+ if (doc.subtools[size_t(i)].visible && doc.subtoolMesh(i).triangleCount()) meshes.push_back(&doc.subtoolMesh(i));
+ if (meshes.empty()) return Mesh();
+ if (meshes.size() == 1) return *meshes.front();
+ return mergeMeshes(meshes);
+}
+
+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));
+ std::sort(ids.begin(), ids.end());
+ ids.erase(std::unique(ids.begin(), ids.end()), ids.end());
+ std::vector<Mesh> out;
+ if (ids.size() < 2) return out;
+ for (uint32_t id : ids) {
+ std::vector<uint8_t> keep(mesh.triangleCount());
+ for (uint32_t t = 0; t < keep.size(); ++t) keep[t] = mesh.polygroupAt(t) == id;
+ out.push_back(extractTriangles(mesh, keep));
+ }
+ return out;
+}
+
+std::vector<Mesh> splitIntoParts(const Mesh& mesh) {
+ // Union-find over vertices joined by triangles.
+ std::vector<uint32_t> parent(mesh.vertexCount());
+ std::iota(parent.begin(), parent.end(), 0u);
+ auto find = [&](uint32_t v) {
+ while (parent[v] != v) v = parent[v] = parent[parent[v]];
+ return v;
+ };
+ for (const auto& t : mesh.triangles) {
+ parent[find(t.y)] = find(t.x);
+ parent[find(t.z)] = find(t.x);
+ }
+ std::map<uint32_t, std::vector<uint8_t>> pieces;
+ for (uint32_t t = 0; t < mesh.triangleCount(); ++t) {
+ auto& keep = pieces[find(mesh.triangles[t].x)];
+ if (keep.empty()) keep.resize(mesh.triangleCount());
+ keep[t] = 1;
+ }
+ std::vector<Mesh> out;
+ if (pieces.size() < 2) return out;
+ for (const auto& [root, keep] : pieces) out.push_back(extractTriangles(mesh, keep));
+ std::stable_sort(out.begin(), out.end(), [](const Mesh& a, const Mesh& b) { return a.triangleCount() > b.triangleCount(); });
+ return out;
+}
+
+namespace {
+
+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());
+}
+
+std::string countText(size_t tris) { return std::to_string(tris) + " triangles"; }
+
+// The SubTool an argument names: index= (0-based) or name=, else the active one. -1 if not found.
+int targetSubtool(const Document& doc, const Args& a) {
+ if (a.contains("name")) return doc.findSubtool(argString(a, "name"));
+ if (a.contains("index")) {
+ const int i = int(argNumber(a, "index", -1));
+ return i >= 0 && i < doc.subtoolCount() ? i : -1;
+ }
+ return doc.activeSubtool;
+}
+
+CommandResult notFound(const Args& a) {
+ return {false, a.contains("name") ? "No SubTool named '" + argString(a, "name") + "'" : std::string("No such SubTool")};
+}
+
+// Replaces SubTool `index` by `pieces`, named after it ("Body 1", "Body 2", ...); the first piece is selected.
+void replaceWithPieces(Document& doc, int index, std::vector<Mesh> pieces) {
+ const std::string base = doc.subtools[size_t(index)].name;
+ const bool visible = doc.subtools[size_t(index)].visible;
+ for (size_t k = 0; k < pieces.size(); ++k) {
+ const int at = doc.addSubtool(std::move(pieces[k]), base + " " + std::to_string(k + 1), false, index + 1 + int(k));
+ doc.subtools[size_t(at)].visible = visible;
+ }
+ doc.selectSubtool(index + 1);
+ doc.removeSubtool(index);
+}
+
+} // namespace
+
+void registerSubToolCommands(CommandRegistry& reg) {
+ using T = ParamSpec::Type;
+ const ParamSpec indexParam{"index", T::Number, "SubTool index (0 = top of the list). Default: the active one.", false};
+ const ParamSpec nameParam{"name", T::String, "SubTool name (instead of index).", false};
+
+ reg.add({"subtool_list", "List the SubTools (separate meshes) in the scene.", {},
+ [](Document& doc, const Args&) -> CommandResult {
+ std::string out = std::to_string(doc.subtoolCount()) + " SubTool" + (doc.subtoolCount() == 1 ? "" : "s") + ":";
+ for (int i = 0; i < doc.subtoolCount(); ++i) {
+ const SubTool& s = doc.subtools[size_t(i)];
+ out += "\n" + std::to_string(i) + ". " + s.name + " (" + countText(doc.subtoolMesh(i).triangleCount());
+ if (i == doc.activeSubtool) out += ", active";
+ if (!s.visible) out += ", hidden";
+ out += ")";
+ }
+ return {true, out};
+ }});
+
+ reg.add({"subtool_select", "Make a SubTool the active one: brushes and commands work on it.", {indexParam, nameParam},
+ [](Document& doc, const Args& a) -> CommandResult {
+ if (!a.contains("index") && !a.contains("name")) return {false, "Give index= or name="};
+ const int i = targetSubtool(doc, a);
+ if (i < 0) return notFound(a);
+ doc.selectSubtool(i);
+ doc.subtools[size_t(i)].visible = true; // you can't sculpt what you can't see
+ return {true, "Active SubTool: " + doc.subtools[size_t(i)].name};
+ }});
+
+ reg.add({"subtool_append",
+ "Add a new SubTool: a primitive (sphere, cube, plane) placed beside the visible model, or a model file. "
+ "It becomes the active SubTool.",
+ {{"type", T::String, "'sphere' (default), 'cube' or 'plane'.", false},
+ {"path", T::String, "Model file to append instead of a primitive (.obj, .glb, .fbx, .ply, .stl, .usd...).", false},
+ {"name", T::String, "Name for the new SubTool.", false},
+ {"size", T::Number, "Primitive size relative to the visible model (0.05-2). Default 0.35.", false}},
+ [](Document& doc, const Args& a) -> CommandResult {
+ Mesh m;
+ std::string name;
+ if (a.contains("path")) {
+ // Load through `open` into a scratch document, so every format and its attributes work.
+ 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);
+ } else {
+ const std::string type = argString(a, "type", "sphere");
+ const AABB scene = doc.visibleBounds();
+ const float extent = scene.valid() ? std::max({scene.extent().x, scene.extent().y, scene.extent().z}) : 2.0f;
+ const float size = extent * float(std::clamp(argNumber(a, "size", 0.35), 0.05, 2.0));
+ if (type == "sphere") m = makeIcosphere(5, size * 0.5f);
+ else if (type == "cube") m = makeCube(48, size);
+ else if (type == "plane") m = makePlane(128, size);
+ else return {false, "Unknown primitive '" + type + "' (sphere, cube or plane)"};
+ // Beside the model on +X, at its middle height.
+ const glm::vec3 at = scene.valid() ? glm::vec3(scene.max.x + size * 0.6f, scene.center().y, scene.center().z)
+ : glm::vec3(0.0f);
+ for (auto& p : m.positions) p += at;
+ m.recomputeAllNormals();
+ name = type == "sphere" ? "Sphere" : type == "cube" ? "Cube" : "Plane";
+ }
+ if (a.contains("name")) name = argString(a, "name");
+ const size_t tris = m.triangleCount();
+ const int i = doc.addSubtool(std::move(m), name);
+ return {true, "Appended SubTool " + doc.subtools[size_t(i)].name + " (" + countText(tris) + ")"};
+ }});
+
+ reg.add({"subtool_duplicate", "Copy a SubTool (with its layers and attributes) and make the copy active.",
+ {indexParam, nameParam},
+ [](Document& doc, const Args& a) -> CommandResult {
+ const int i = targetSubtool(doc, a);
+ if (i < 0) return notFound(a);
+ Mesh copy = doc.subtoolMesh(i);
+ const int added = doc.addSubtool(std::move(copy), doc.subtools[size_t(i)].name + " copy", true, i + 1);
+ return {true, "Duplicated as " + doc.subtools[size_t(added)].name};
+ }});
+
+ reg.add({"subtool_delete", "Delete a SubTool (not undoable). The last SubTool can't be deleted.",
+ {indexParam, nameParam},
+ [](Document& doc, const Args& a) -> CommandResult {
+ const int i = targetSubtool(doc, a);
+ if (i < 0) return notFound(a);
+ if (doc.subtoolCount() == 1) return {false, "The scene needs at least one SubTool"};
+ const std::string name = doc.subtools[size_t(i)].name;
+ doc.removeSubtool(i);
+ return {true, "Deleted SubTool " + name};
+ }});
+
+ reg.add({"subtool_rename", "Rename a SubTool.",
+ {{"to", T::String, "The new name.", true}, indexParam, nameParam},
+ [](Document& doc, const Args& a) -> CommandResult {
+ const int i = targetSubtool(doc, a);
+ if (i < 0) return notFound(a);
+ std::string to = argString(a, "to");
+ if (to.empty()) return {false, "The name can't be empty"};
+ if (doc.subtools[size_t(i)].name != to) to = doc.uniqueSubtoolName(to);
+ doc.subtools[size_t(i)].name = to;
+ doc.modified = true;
+ return {true, "Renamed to " + to};
+ }});
+
+ reg.add({"subtool_visibility", "Show or hide a SubTool. Hidden SubTools aren't drawn, picked or exported.",
+ {{"visible", T::Bool, "true to show, false to hide. Default: toggle.", false}, indexParam, nameParam},
+ [](Document& doc, const Args& a) -> CommandResult {
+ const int i = targetSubtool(doc, a);
+ if (i < 0) return notFound(a);
+ SubTool& s = doc.subtools[size_t(i)];
+ s.visible = argBool(a, "visible", !s.visible);
+ doc.modified = true;
+ return {true, s.name + (s.visible ? " shown" : " hidden")};
+ }});
+
+ reg.add({"subtool_solo", "Show only the active SubTool, or (when it already is the only one shown) show all again.", {},
+ [](Document& doc, const Args&) -> CommandResult {
+ bool othersShown = false;
+ for (int i = 0; i < doc.subtoolCount(); ++i)
+ othersShown |= i != doc.activeSubtool && doc.subtools[size_t(i)].visible;
+ for (int i = 0; i < doc.subtoolCount(); ++i)
+ doc.subtools[size_t(i)].visible = i == doc.activeSubtool || !othersShown;
+ doc.modified = true;
+ return {true, othersShown ? "Solo: " + doc.activeSubtoolInfo().name : std::string("All SubTools shown")};
+ }});
+
+ reg.add({"subtool_show_all", "Show every SubTool.", {},
+ [](Document& doc, const Args&) -> CommandResult {
+ for (auto& s : doc.subtools) s.visible = true;
+ doc.modified = true;
+ return {true, "All SubTools shown"};
+ }});
+
+ reg.add({"subtool_move", "Move a SubTool up or down the list.",
+ {{"direction", T::String, "'up' or 'down'.", true}, indexParam, nameParam},
+ [](Document& doc, const Args& a) -> CommandResult {
+ const int i = targetSubtool(doc, a);
+ if (i < 0) return notFound(a);
+ const int dir = argString(a, "direction") == "up" ? -1 : 1;
+ if (i + dir < 0 || i + dir >= doc.subtoolCount()) return {false, "Already at the " + std::string(dir < 0 ? "top" : "bottom")};
+ doc.moveSubtool(i, dir);
+ return {true, "Moved " + doc.subtools[size_t(i + dir)].name + (dir < 0 ? " up" : " down")};
+ }});
+
+ reg.add({"subtool_merge_down",
+ "Merge the active SubTool with the one below it into one mesh (not undoable). Each keeps its own "
+ "polygroups, so subtool_split_groups can separate them again.", {},
+ [](Document& doc, const Args&) -> CommandResult {
+ const int i = doc.activeSubtool;
+ if (i + 1 >= doc.subtoolCount()) return {false, "There's no SubTool below " + doc.activeSubtoolInfo().name};
+ Mesh merged = mergeMeshes({&doc.subtoolMesh(i), &doc.subtoolMesh(i + 1)});
+ const std::string name = doc.subtools[size_t(i)].name, below = doc.subtools[size_t(i + 1)].name;
+ doc.removeSubtool(i + 1);
+ doc.replaceActiveMesh(std::move(merged));
+ return {true, "Merged " + below + " into " + name + " (" + countText(doc.mesh.triangleCount()) + ")"};
+ }});
+
+ reg.add({"subtool_merge_visible",
+ "Merge every visible SubTool into one new SubTool, replacing them (not undoable). Hidden SubTools stay "
+ "as they are.", {},
+ [](Document& doc, const Args&) -> CommandResult {
+ std::vector<int> visible;
+ for (int i = 0; i < doc.subtoolCount(); ++i)
+ if (doc.subtools[size_t(i)].visible) visible.push_back(i);
+ if (visible.size() < 2) return {false, "Show at least two SubTools to merge"};
+ Mesh merged = mergedVisibleMesh(doc);
+ const size_t tris = merged.triangleCount();
+ const int at = visible.front();
+ doc.addSubtool(std::move(merged), "Merged", true, at);
+ for (auto it = visible.rbegin(); it != visible.rend(); ++it) doc.removeSubtool(*it + 1);
+ return {true, "Merged " + std::to_string(visible.size()) + " SubTools into " +
+ doc.activeSubtoolInfo().name + " (" + countText(tris) + ")"};
+ }});
+
+ reg.add({"subtool_split_groups", "Split the active SubTool into one SubTool per polygroup (not undoable).", {},
+ [](Document& doc, const Args&) -> CommandResult {
+ auto pieces = splitByPolygroups(doc.mesh);
+ if (pieces.empty()) return {false, doc.activeSubtoolInfo().name + " has only one polygroup"};
+ const size_t n = pieces.size();
+ replaceWithPieces(doc, doc.activeSubtool, std::move(pieces));
+ return {true, "Split into " + std::to_string(n) + " SubTools"};
+ }});
+
+ reg.add({"subtool_split_parts", "Split the active SubTool into one SubTool per disconnected piece (not undoable).", {},
+ [](Document& doc, const Args&) -> CommandResult {
+ auto pieces = splitIntoParts(doc.mesh);
+ if (pieces.empty()) return {false, doc.activeSubtoolInfo().name + " is a single piece"};
+ const size_t n = pieces.size();
+ replaceWithPieces(doc, doc.activeSubtool, std::move(pieces));
+ return {true, "Split into " + std::to_string(n) + " SubTools"};
+ }});
+}
+
+} // namespace sf
diff --git a/src/core/SubTools.h b/src/core/SubTools.h
new file mode 100644
index 00000000..ff19ece8
--- /dev/null
+++ b/src/core/SubTools.h
@@ -0,0 +1,39 @@
+// SculptForge - open source digital sculpting
+// SPDX-License-Identifier: GPL-3.0-or-later
+//
+// SubTools, ZBrush style: a scene is a list of separate meshes (body, eyes,
+// teeth, armour) that are sculpted one at a time, shown or hidden, merged and
+// split. The data model lives in Document (see SubTool); this file holds the
+// mesh operations and the subtool_* commands.
+#pragma once
+
+#include "core/Document.h"
+
+#include <string>
+#include <vector>
+
+namespace sf {
+
+class CommandRegistry;
+
+// Concatenates meshes into one. Every attribute any input has is kept (inputs
+// without it get the default), polygroup ids are offset so each input keeps
+// its own groups (inputs without polygroups become one group each), and sculpt
+// layers are matched by name.
+Mesh mergeMeshes(const std::vector<const Mesh*>& meshes);
+
+// The visible SubTools merged into one mesh (for exporters that write a single
+// mesh). With one SubTool this is a copy of it, whether shown or not.
+Mesh mergedVisibleMesh(const Document& doc);
+
+// 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).
+std::vector<Mesh> splitIntoParts(const Mesh& mesh);
+
+// subtool_list, subtool_select, subtool_append, subtool_duplicate, subtool_delete,
+// subtool_rename, subtool_visibility, subtool_solo, subtool_show_all, subtool_move,
+// subtool_merge_down, subtool_merge_visible, subtool_split_groups, subtool_split_parts.
+void registerSubToolCommands(CommandRegistry& registry);
+
+} // namespace sf
diff --git a/src/core/Undo.h b/src/core/Undo.h
index 3f67aeb9..9307011a 100644
--- a/src/core/Undo.h
+++ b/src/core/Undo.h
@@ -64,6 +64,11 @@ struct UndoRecord {
class UndoStack {
public:
+ UndoStack() = default;
+ UndoStack(UndoStack&&) = default; // move-only (records own mesh snapshots)
+ UndoStack& operator=(UndoStack&&) = default;
+ UndoStack(const UndoStack&) = delete;
+ UndoStack& operator=(const UndoStack&) = delete;
void push(UndoRecord record);
bool canUndo() const { return !undo_.empty(); }
bool canRedo() const { return !redo_.empty(); }
diff --git a/tests/test_subtools.cpp b/tests/test_subtools.cpp
new file mode 100644
index 00000000..51799070
--- /dev/null
+++ b/tests/test_subtools.cpp
@@ -0,0 +1,188 @@
+// SculptForge - open source digital sculpting
+// SPDX-License-Identifier: GPL-3.0-or-later
+//
+// SubTools: the Document data model (select / add / remove / move, per-SubTool
+// undo and unsaved-changes tracking), mesh merge and split, the cube
+// primitive, and the subtool_* commands.
+#include "TestHarness.h"
+
+#include "core/Commands.h"
+#include "core/Polygroups.h"
+#include "core/Primitives.h"
+#include "core/SubTools.h"
+#include "io/ObjIO.h"
+
+#include <cmath>
+#include <set>
+
+using namespace sf;
+
+namespace {
+
+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();
+}
+
+} // namespace
+
+TEST(subtool_document_basics) {
+ Document doc;
+ CHECK(doc.subtoolCount() == 1 && doc.activeSubtoolInfo().name == "Sculpt");
+ CommandRegistry reg;
+ CHECK(reg.execute(doc, "new_sphere", {{"subdivisions", 3.0}}).ok);
+ CHECK(doc.subtoolCount() == 1 && doc.activeSubtoolInfo().name == "Sphere");
+ const size_t sphereTris = doc.mesh.triangleCount();
+ CHECK(!doc.dirty());
+
+ CHECK(reg.execute(doc, "subtool_append", {{"type", std::string("cube")}}).ok);
+ CHECK(doc.subtoolCount() == 2 && doc.activeSubtool == 1);
+ CHECK(doc.activeSubtoolInfo().name == "Cube");
+ CHECK(doc.mesh.triangleCount() == 48u * 48u * 12u);
+ CHECK(doc.subtoolMesh(0).triangleCount() == sphereTris); // checked in, intact
+ CHECK(doc.dirty());
+ // Placed beside the sphere, not inside it.
+ CHECK(doc.mesh.bounds().min.x > doc.subtoolMesh(0).bounds().max.x);
+
+ // Each SubTool keeps its own undo history.
+ doc.markClean();
+ CHECK(reg.execute(doc, "mask_all").ok);
+ CHECK(doc.undo.canUndo());
+ doc.selectSubtool(0);
+ CHECK(doc.mesh.triangleCount() == sphereTris);
+ CHECK(!doc.undo.canUndo());
+ CHECK(doc.dirty()); // the cube's edit is still unsaved
+ doc.selectSubtool(1);
+ CHECK(doc.undo.canUndo() && doc.mesh.hasMask());
+ CHECK(reg.execute(doc, "undo").ok);
+ CHECK(doc.mesh.maskAt(0) == 0.0f); // undone (the attribute may stay allocated)
+
+ // Picking needs the BVH of the selected SubTool.
+ RayHit hit;
+ const glm::vec3 c = doc.mesh.bounds().center();
+ CHECK(doc.bvh.raycast(doc.mesh, c + glm::vec3(0, 0, 10), glm::vec3(0, 0, -1), hit));
+
+ // Names stay unique; rename, move, visibility, solo.
+ CHECK(reg.execute(doc, "subtool_append", {{"type", std::string("cube")}}).ok);
+ CHECK(doc.activeSubtoolInfo().name == "Cube 2");
+ CHECK(reg.execute(doc, "subtool_rename", {{"to", std::string("Cube")}}).ok);
+ CHECK(doc.activeSubtoolInfo().name == "Cube 3"); // "Cube" is taken
+ CHECK(reg.execute(doc, "subtool_rename", {{"to", std::string("Helmet")}}).ok);
+ CHECK(reg.execute(doc, "subtool_move", {{"direction", std::string("up")}}).ok);
+ CHECK(doc.activeSubtool == 1 && doc.subtools[1].name == "Helmet" && doc.subtools[2].name == "Cube");
+ CHECK(reg.execute(doc, "subtool_solo").ok);
+ CHECK(!doc.subtools[0].visible && doc.subtools[1].visible && !doc.subtools[2].visible);
+ CHECK(reg.execute(doc, "subtool_solo").ok);
+ CHECK(doc.subtools[0].visible && doc.subtools[2].visible);
+ CHECK(reg.execute(doc, "subtool_visibility", {{"name", std::string("Cube")}, {"visible", false}}).ok);
+ CHECK(!doc.subtools[2].visible);
+ CHECK(reg.execute(doc, "subtool_select", {{"name", std::string("Cube")}}).ok);
+ CHECK(doc.activeSubtool == 2 && doc.subtools[2].visible); // selecting shows it
+ CHECK(!reg.execute(doc, "subtool_select", {{"name", std::string("Nope")}}).ok);
+ CHECK(reg.execute(doc, "subtool_list").message.find("2. Cube (") != std::string::npos);
+
+ // Delete; the last one stays.
+ CHECK(reg.execute(doc, "subtool_delete").ok);
+ CHECK(doc.subtoolCount() == 2 && doc.activeSubtool == 1 && doc.activeSubtoolInfo().name == "Helmet");
+ CHECK(reg.execute(doc, "subtool_delete", {{"index", 0.0}}).ok);
+ CHECK(doc.subtoolCount() == 1 && doc.activeSubtool == 0);
+ CHECK(!reg.execute(doc, "subtool_delete").ok);
+
+ // A new scene goes back to one SubTool.
+ CHECK(reg.execute(doc, "subtool_append").ok);
+ CHECK(reg.execute(doc, "new_plane", {{"resolution", 4.0}}).ok);
+ CHECK(doc.subtoolCount() == 1 && doc.activeSubtoolInfo().name == "Plane");
+}
+
+TEST(subtool_cube_primitive) {
+ Mesh cube = makeCube(4, 2.0f);
+ CHECK(cube.triangleCount() == 4u * 4u * 12u);
+ CHECK(cube.vertexCount() == 6u * 4u * 4u + 2u); // welded: V - E + F = 2
+ CHECK(groupCount(cube) == 6);
+ bool outward = true;
+ for (size_t v = 0; v < cube.vertexCount(); ++v) outward &= glm::dot(cube.normals[v], cube.positions[v]) > 0.0f;
+ CHECK(outward);
+ CHECK(std::abs(cube.bounds().max.x - 1.0f) < 1e-5f);
+ CHECK(splitIntoParts(cube).empty()); // one closed piece
+}
+
+TEST(subtool_merge_and_split) {
+ Mesh a = makeIcosphere(2);
+ Mesh b = makeCube(3);
+ for (auto& p : b.positions) p.x += 4.0f;
+ b.recomputeAllNormals();
+ a.ensureMask(0.75f);
+ b.ensureColors(glm::vec3(0.2f, 0.4f, 0.6f));
+ a.addLayer("Smile");
+ a.layers[0].delta.assign(a.vertexCount(), glm::vec3(0, 0.1f, 0));
+ a.setLayerWeight(0, 0.5f);
+
+ Mesh m = mergeMeshes({&a, &b});
+ CHECK(m.vertexCount() == a.vertexCount() + b.vertexCount());
+ CHECK(m.triangleCount() == a.triangleCount() + b.triangleCount());
+ CHECK(m.hasMask() && m.mask.front() == 0.75f && m.mask.back() == 0.0f);
+ CHECK(m.hasColors() && m.colors.front() == glm::vec3(1.0f) && m.colors.back() == glm::vec3(0.2f, 0.4f, 0.6f));
+ CHECK(m.layers.size() == 1 && m.layers[0].name == "Smile" && m.layers[0].delta.back() == glm::vec3(0.0f));
+ CHECK(std::abs(m.positions[0].y - a.positions[0].y) < 1e-5f); // layer at 0.5 survives the merge
+ CHECK(groupCount(m) == 1 + 6); // sphere's one group + the cube's six, kept apart
+
+ auto parts = splitIntoParts(m);
+ CHECK(parts.size() == 2 && parts[0].triangleCount() == a.triangleCount() && parts[1].triangleCount() == b.triangleCount());
+ auto groups = splitByPolygroups(m);
+ CHECK(groups.size() == 7 && groups[0].triangleCount() == a.triangleCount());
+ CHECK(groups[0].layers.size() == 1 && groups[0].hasMask());
+}
+
+TEST(subtool_merge_split_commands) {
+ Document doc;
+ CommandRegistry reg;
+ CHECK(reg.execute(doc, "new_sphere", {{"subdivisions", 2.0}}).ok);
+ const size_t sphereTris = doc.mesh.triangleCount();
+ CHECK(reg.execute(doc, "subtool_append", {{"type", std::string("cube")}}).ok);
+ const size_t cubeTris = doc.mesh.triangleCount();
+ CHECK(reg.execute(doc, "subtool_append", {{"type", std::string("sphere")}}).ok);
+ CHECK(reg.execute(doc, "subtool_visibility", {{"visible", false}}).ok); // hide the last one
+
+ // Exporters see only what's visible.
+ CHECK(mergedVisibleMesh(doc).triangleCount() == sphereTris + cubeTris);
+
+ CHECK(reg.execute(doc, "subtool_merge_visible").ok);
+ CHECK(doc.subtoolCount() == 2 && doc.activeSubtool == 0 && doc.activeSubtoolInfo().name == "Merged");
+ CHECK(doc.mesh.triangleCount() == sphereTris + cubeTris);
+ CHECK(!doc.subtools[1].visible); // the hidden one is untouched
+ CHECK(!doc.undo.canUndo());
+
+ CHECK(reg.execute(doc, "subtool_split_parts").ok);
+ CHECK(doc.subtoolCount() == 3 && doc.subtools[0].name == "Merged 1" && doc.subtools[1].name == "Merged 2");
+ CHECK(doc.activeSubtool == 0 && doc.mesh.triangleCount() == cubeTris); // largest piece first
+
+ // Merge down, then split by groups gives the pieces back (cube has 6 groups).
+ CHECK(reg.execute(doc, "subtool_merge_down").ok);
+ CHECK(doc.subtoolCount() == 2 && doc.mesh.triangleCount() == sphereTris + cubeTris);
+ CHECK(reg.execute(doc, "subtool_split_groups").ok);
+ CHECK(doc.subtoolCount() == 1 + 7);
+ CHECK(!reg.execute(doc, "subtool_split_parts").ok); // a cube side is one piece
+
+ // Duplicate sits right below the original and is independent.
+ CHECK(reg.execute(doc, "subtool_select", {{"index", 0.0}}).ok);
+ CHECK(reg.execute(doc, "subtool_duplicate").ok);
+ CHECK(doc.activeSubtool == 1 && doc.subtools[1].name.find("copy") != std::string::npos);
+ CHECK(reg.execute(doc, "mask_all").ok);
+ CHECK(!doc.subtoolMesh(0).hasMask());
+}
+
+TEST(subtool_append_file) {
+ Document doc;
+ CommandRegistry reg;
+ CHECK(reg.execute(doc, "new_sphere", {{"subdivisions", 2.0}}).ok);
+ const std::string path = tempPath("sf_subtool_eye.obj");
+ std::string err;
+ CHECK(saveObj(path, makeIcosphere(1, 0.2f), err));
+ CHECK(reg.execute(doc, "subtool_append", {{"path", path}}).ok);
+ CHECK(doc.subtoolCount() == 2 && doc.activeSubtoolInfo().name == "sf_subtool_eye");
+ CHECK(doc.mesh.triangleCount() == makeIcosphere(1).triangleCount());
+ CHECK(!reg.execute(doc, "subtool_append", {{"path", tempPath("sf_missing.obj")}}).ok);
+ CHECK(!reg.execute(doc, "subtool_append", {{"type", std::string("torus")}}).ok);
+ std::filesystem::remove(path);
+}