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
Insert your own mesh (#34): Append > Insert on the model > Active SubTool's copy... or From file... (OBJ, PLY, GLB), placed, sized, turned and mirrored like the shapes; insert_mesh command, unit and UI tests
islandmed8f0a541d36d6
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 64e83742..1d6b2ac4 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -20,6 +20,10 @@ All notable changes to SculptForge are listed here. The format follows- **Continuous** is also in the left shelf's stroke picker, under the stroke tiles (#43).- Insert on the model respects X / Y / Z symmetry (#43): a mirrored copy on the other side, one undo step(`insert_primitive symmetry=x`).+- Insert your own mesh (#34): **Append > Insert on the model > Active SubTool's copy...** (another SubTool) or+ **From file...** (`.obj`, `.ply`, `.glb`), dragged onto the surface like the shapes: centred, sized by the drag,+ its up axis along the normal, turned by the drag and mirrored by symmetry, one undo step+ (`insert_mesh subtool=<name>|file=<path>`).- SubTool thumbnails in the SubTool list (#43), drawn from each SubTool's existing GPU buffers (no upload, themotion proxy on dense meshes), one per frame at most and only once a change has settled, never during a stroke.diff --git a/docs/guide/subtools.md b/docs/guide/subtools.mdindex f3da7a84..a50f9185 100644--- a/docs/guide/subtools.md+++ b/docs/guide/subtools.md@@ -59,6 +59,10 @@ Click **Append** and choose:- **Insert on the model**: choose a shape, then drag on the active SubTool's surface to add it there as a newpolygroup (the drag sets its size and turns it). With **Symmetry** X, Y or Z on, a mirrored copy goes on the otherside too, in the same undo step; a shape inserted right on a mirror plane isn't doubled.+ To insert your own mesh, choose **Active SubTool's copy...** and pick another SubTool (it stays as it is), or+ **From file...** and pick an `.obj`, `.ply` or `.glb` file; then drag as with the shapes. The mesh is centred,+ scaled so its largest side matches the drag, and stood on the surface along its own up (+Y) axis. Esc stops+ inserting. (Command: `insert_mesh subtool=<name>` or `insert_mesh file=<path>`.)- **From file...**: a model (`.obj`, `.fbx`, `.glb`, `.gltf`, `.ply`, `.stl`, `.GoZ`, `.usda`, `.usd`, `.usdz`) ora project (`.sfproj`). A file with several objects adds one SubTool per object.diff --git a/src/app/App.cpp b/src/app/App.cppindex 8ff45b26..1dff8a1b 100644--- a/src/app/App.cpp+++ b/src/app/App.cpp@@ -1332,12 +1332,19 @@ void App::onMouseUp() {const float dist = glm::length(camera_.position() - insertAt_);const float worldPerPx = 2.0f * dist * std::tan(camera_.fovY * 0.5f) / std::max(canvasRect().h, 1.0f);const std::string symmetry = std::string(symmetry_.x ? "x" : "") + (symmetry_.y ? "y" : "") + (symmetry_.z ? "z" : "");- runCommand("insert_primitive", {{"type", insertType_}, {"symmetry", symmetry}, {"x", double(insertAt_.x)}, {"y", double(insertAt_.y)},- {"z", double(insertAt_.z)}, {"nx", double(insertNormal_.x)},- {"ny", double(insertNormal_.y)}, {"nz", double(insertNormal_.z)},- {"size", double(2.0f * px * worldPerPx)},- // the drag's direction on screen turns it about the normal- {"twist", insertPx_ > 4.0f ? double(glm::degrees(std::atan2(mouseY_ - insertY_, mouseX_ - insertX_))) : 0.0}});+ Args args{{"symmetry", symmetry}, {"x", double(insertAt_.x)}, {"y", double(insertAt_.y)},+ {"z", double(insertAt_.z)}, {"nx", double(insertNormal_.x)},+ {"ny", double(insertNormal_.y)}, {"nz", double(insertNormal_.z)},+ {"size", double(2.0f * px * worldPerPx)},+ // the drag's direction on screen turns it about the normal+ {"twist", insertPx_ > 4.0f ? double(glm::degrees(std::atan2(mouseY_ - insertY_, mouseX_ - insertX_))) : 0.0}};+ if (insertType_ == "mesh") { // your own mesh: a SubTool's copy or a file (insert_mesh)+ args[insertMeshKey_] = insertMeshValue_;+ runCommand("insert_mesh", args);+ } else {+ args["type"] = insertType_;+ runCommand("insert_primitive", args);+ }}if (drag_ == Drag::Stroke && maskClickPending_) maskClickRelease(); // Ctrl+click: blur / sharpen the maskelse if (drag_ == Drag::Stroke && asyncStroke_) {@@ -1729,7 +1736,8 @@ void SDLCALL onFileChosen(void* userdata, const char* const* files, int) {void App::queueFile(FileAction action, std::string path) {if (action != FileAction::OpenObj && action != FileAction::LoadBrush && action != FileAction::OpenImage &&- action != FileAction::AppendSubtool && action != FileAction::ComfyWorkflow && !path.empty() &&+ action != FileAction::AppendSubtool && action != FileAction::ComfyWorkflow && action != FileAction::InsertMesh &&+ !path.empty() &&std::filesystem::path(std::u8string(path.begin(), path.end())).extension().empty())path += action == FileAction::SaveObj ? ".obj": action == FileAction::SaveBrush ? ".sfbrush"@@ -1853,6 +1861,13 @@ void App::processPendingFiles() {break;case FileAction::ComfyWorkflow: setComfyWorkflow(f.path, comfyPickingText_); break;case FileAction::LoadMatcap: runCommand("load_matcap", {{"path", f.path}}); break;+ case FileAction::InsertMesh: // Append > Insert on the model > From file (#34): the next drag inserts it+ insertType_ = "mesh";+ insertMeshKey_ = "file";+ insertMeshValue_ = f.path;+ status_ = "Insert " + std::filesystem::path(std::u8string(f.path.begin(), f.path.end())).filename().string() ++ ": drag on the model (the drag sets its size). Esc stops.";+ break;case FileAction::Count: break;}}diff --git a/src/app/App.h b/src/app/App.hindex a7e74de5..a38b8d9d 100644--- a/src/app/App.h+++ b/src/app/App.h@@ -124,7 +124,7 @@ public:ThumbnailCache& thumbnails() { return thumbs_; }void shutdown();- enum class FileAction { OpenObj, SaveObj, ExportGlb, ExportLods, SaveBrush, LoadBrush, OpenImage, ExportUsd, SaveSplats, ExportUnreal, SaveProject, AppendSubtool, ComfyWorkflow, LoadMatcap, Count };+ enum class FileAction { OpenObj, SaveObj, ExportGlb, ExportLods, SaveBrush, LoadBrush, OpenImage, ExportUsd, SaveSplats, ExportUnreal, SaveProject, AppendSubtool, ComfyWorkflow, LoadMatcap, InsertMesh, Count };struct DialogRequest {App* app;FileAction action;@@ -1171,7 +1171,10 @@ private:std::array<AxisGizmoEnd, 6> axisGizmoLayout() const; // the gizmo's ends on screen now (AxisGizmo.h)bool axisGizmoMouseDown(float x, float y); // a click on an end: that side view (#43)// Insert on the model (#34): the primitive chosen in Append > Insert; a drag on the surface places it.+ // "mesh" inserts your own mesh instead: insertMeshKey_ is "subtool" (a SubTool's name) or "file" (a path+ // chosen in the file dialog), insertMeshValue_ the name or path (insert_mesh).std::string insertType_;+ std::string insertMeshKey_, insertMeshValue_;glm::vec3 insertAt_{0.0f}, insertNormal_{0.0f, 1.0f, 0.0f};float insertX_ = 0.0f, insertY_ = 0.0f, insertPx_ = 0.0f;bool readUiConfig(const std::string& path, std::string& err);diff --git a/src/app/PanelSubTools.cpp b/src/app/PanelSubTools.cppindex c94353d8..02209162 100644--- a/src/app/PanelSubTools.cpp+++ b/src/app/PanelSubTools.cpp@@ -35,6 +35,7 @@ constexpr ImVec4 kThumbWell = theme::rgb(0x000000, 0.22f); // behind a SubTool tconst SDL_DialogFileFilter kAppendFilters[] = {{"Models and projects", "obj;fbx;glb;gltf;ply;stl;GoZ;goz;usda;usd;usdz;sfproj"}, {"All files", "*"}};+const SDL_DialogFileFilter kInsertFilters[] = {{"Meshes (OBJ, PLY, GLB)", "obj;ply;glb;gltf"}, {"All files", "*"}};void SDLCALL onAppendChosen(void* userdata, const char* const* files, int) {wakeMainLoop(); // a file dialog answered (maybe on another thread): redraw now@@ -375,6 +376,28 @@ void App::drawSubToolsContents() {status_ = "Insert " + label + ": drag on the model (the drag sets its size). Esc stops.";}}+ ImGui::Separator();+ // Your own mesh (#34): a copy of another SubTool, or a model file you choose.+ if (ImGui::BeginMenu("Active SubTool's copy...", count > 1)) {+ for (int i = 0; i < count; ++i) {+ if (i == active) continue;+ const std::string& name = doc_.subtools[size_t(i)].name;+ const bool chosen = insertType_ == "mesh" && insertMeshKey_ == "subtool" && insertMeshValue_ == name;+ if (ImGui::MenuItem((name + "##insertcopy" + std::to_string(i)).c_str(), nullptr, chosen)) {+ insertType_ = "mesh";+ insertMeshKey_ = "subtool";+ insertMeshValue_ = name;+ status_ = "Insert a copy of " + name + ": drag on the model (the drag sets its size). Esc stops.";+ }+ }+ ImGui::EndMenu();+ }+ if (ImGui::IsItemHovered(ImGuiHoveredFlags_AllowWhenDisabled | ImGuiHoveredFlags_DelayNormal))+ ImGui::SetTooltip(count > 1 ? "Insert a copy of another SubTool into the active one"+ : "Append another SubTool first");+ if (ImGui::MenuItem("From file...##insert"))+ SDL_ShowOpenFileDialog(onAppendChosen, &dialogRequests_[int(FileAction::InsertMesh)], window_,+ kInsertFilters, 2, nullptr, false);ImGui::EndMenu();}if (ImGui::MenuItem("From file..."))diff --git a/src/app/UiTest.cpp b/src/app/UiTest.cppindex 2a0251b8..d367f8d9 100644--- a/src/app/UiTest.cpp+++ b/src/app/UiTest.cpp@@ -1164,6 +1164,19 @@ bool Demo::parseStep(int line, const std::vector<std::string>& w, std::string& eif (file.is_relative()) file = std::filesystem::path(std::u8string(scriptDir_.begin(), scriptDir_.end())) / file;const auto u8 = file.lexically_normal().u8string();run([this, path = std::string(u8.begin(), u8.end())] { app_.openPathConfirmed(path); });+ } else if (verb == "choose_file") { // choose_file insert|append <path>: what a native file dialog would answer+ if (!need(2)) return false;+ App::FileAction action;+ if (w[1] == "insert") action = App::FileAction::InsertMesh;+ else if (w[1] == "append") action = App::FileAction::AppendSubtool;+ else {+ error = "'choose_file' takes insert or append";+ return false;+ }+ auto file = std::filesystem::path(std::u8string(w[2].begin(), w[2].end()));+ if (file.is_relative()) file = std::filesystem::path(std::u8string(scriptDir_.begin(), scriptDir_.end())) / file;+ const auto u8 = file.lexically_normal().u8string();+ run([this, action, path = std::string(u8.begin(), u8.end())] { app_.queueFile(action, path); });} else if (verb == "copy") {if (!need(2)) return false;namespace fs = std::filesystem;diff --git a/src/core/SubTools.cpp b/src/core/SubTools.cppindex 99898cdf..ba452885 100644--- a/src/core/SubTools.cpp+++ b/src/core/SubTools.cpp@@ -9,6 +9,9 @@#include "core/Primitives.h"#include "core/Sculpt.h"#include "core/TextureTransfer.h"+#include "io/GltfIO.h"+#include "io/ObjIO.h"+#include "io/PlyIO.h"#include <cctype>#include <algorithm>@@ -196,6 +199,112 @@ void replaceWithPieces(Document& doc, int index, std::vector<Mesh> pieces) {doc.removeSubtool(index);}+// Reads the mesh in a model file for insert_mesh (#34): OBJ, PLY or GLB / glTF through the importers, every+// object in it as one mesh. Nothing but the file itself is read.+bool loadInsertMesh(const std::string& path, Mesh& out, std::string& error) {+ std::string ext = std::filesystem::path(std::u8string(path.begin(), path.end())).extension().string();+ for (char& ch : ext) ch = char(std::tolower(static_cast<unsigned char>(ch)));+ bool ok = false;+ if (ext == ".obj") ok = loadObj(path, out, error);+ else if (ext == ".glb" || ext == ".gltf") ok = loadGltf(path, out, error);+ else if (ext == ".ply") {+ SplatCloud splats;+ PlyContent content = PlyContent::Mesh;+ ok = loadPly(path, out, splats, content, error);+ if (ok && content != PlyContent::Mesh) {+ error = path + " holds splats or points, not a mesh";+ return false;+ }+ } else {+ error = "Insert takes .obj, .ply or .glb files";+ return false;+ }+ if (!ok && error.empty()) error = "Couldn't read " + path;+ return ok;+}++// The shape of `source` for inserting: its triangles and quads only (no mask, paint, UVs, layers or levels),+// centred on its bounds and scaled so its largest side is `size`. False if it has no triangles.+bool normalizedPiece(const Mesh& source, float size, Mesh& out) {+ if (source.triangleCount() == 0 || source.vertexCount() == 0) return false;+ out = Mesh();+ out.positions = source.positions;+ out.triangles = source.triangles;+ if (source.hasQuads()) out.quadPartners = source.quadPartners;+ out.polygroups.assign(out.triangles.size(), 0u);+ const AABB box = out.bounds();+ const glm::vec3 e = box.extent();+ const float largest = std::max({e.x, e.y, e.z});+ const float scale = largest > 1e-12f ? size / largest : 1.0f;+ const glm::vec3 centre = box.center();+ for (auto& p : out.positions) p = (p - centre) * scale;+ out.sanitizeAttributes();+ return true;+}++// Places `prim` (built around the origin, its axis +Y) where insert_primitive / insert_mesh say: on the surface+// point, +Y along the normal, turned by twist, with mirrored copies for symmetry; merged into the active+// SubTool as one new polygroup, one undo step.+CommandResult insertPiece(Document& doc, Mesh prim, const Args& a, const std::string& label) {+ Symmetry sym{false, false, false};+ for (char ch : argString(a, "symmetry")) {+ const char l = char(std::tolower(static_cast<unsigned char>(ch)));+ if (l == 'x') sym.x = true;+ else if (l == 'y') sym.y = true;+ else if (l == 'z') sym.z = true;+ else return {false, "symmetry takes the axes x, y and z"};+ }+ const float size = float(std::max(argNumber(a, "size", 0.2), 1e-4));+ glm::vec3 n(float(argNumber(a, "nx", 0.0)), float(argNumber(a, "ny", 1.0)), float(argNumber(a, "nz", 0.0)));+ n = glm::length(n) > 1e-8f ? glm::normalize(n) : glm::vec3(0, 1, 0);+ // Rotate +Y onto the normal.+ const glm::vec3 y(0, 1, 0);+ glm::mat3 rot(1.0f);+ const float c = glm::dot(y, n);+ if (c < -0.9999f) rot = glm::mat3(1, 0, 0, 0, -1, 0, 0, 0, -1);+ else if (c < 0.9999f) {+ const glm::vec3 v = glm::cross(y, n);+ const glm::mat3 k(0, v.z, -v.y, -v.z, 0, v.x, v.y, -v.x, 0);+ rot = glm::mat3(1.0f) + k + k * k * (1.0f / (1.0f + c));+ }+ const float twist = glm::radians(float(argNumber(a, "twist", 0.0)));+ if (twist != 0.0f) { // about the primitive's own axis (Y) first, then onto the normal+ const float cs = std::cos(twist), sn = std::sin(twist);+ rot = rot * glm::mat3(cs, 0, -sn, 0, 1, 0, sn, 0, cs);+ }+ const glm::vec3 at(float(argNumber(a, "x", 0.0)), float(argNumber(a, "y", 0.0)), float(argNumber(a, "z", 0.0)));+ for (auto& p : prim.positions) p = at + rot * p;+ uint32_t group = 0;+ for (uint32_t g : doc.mesh.polygroups) group = std::max(group, g);+ prim.polygroups.assign(prim.triangles.size(), group + 1);+ prim.recomputeAllNormals();+ // Symmetry: a mirrored copy across each enabled plane (through the centre, as the brushes mirror),+ // in the same polygroup and the same undo step. A copy that would land on one already there+ // (inserted on a plane itself) is left out.+ std::vector<Mesh> copies;+ std::vector<glm::vec3> placed{at};+ for (const glm::vec3& m : Sculptor::mirrors(sym)) {+ const glm::vec3 centre = at * m;+ if (std::any_of(placed.begin(), placed.end(),+ [&](const glm::vec3& p) { return glm::length(centre - p) < size * 0.25f; }))+ continue;+ placed.push_back(centre);+ Mesh copy = prim;+ for (auto& p : copy.positions) p *= m;+ if (m.x * m.y * m.z < 0.0f) // a reflection turns the triangles inside out: wind them back+ for (auto& t : copy.triangles) std::swap(t.y, t.z);+ copy.recomputeAllNormals();+ copies.push_back(std::move(copy));+ }+ std::vector<const Mesh*> parts{&doc.mesh, &prim};+ for (const Mesh& c2 : copies) parts.push_back(&c2);+ Mesh merged = mergeMeshes(parts);+ const size_t tris = prim.triangleCount() * (1 + copies.size());+ doc.replaceMeshUndoable(std::move(merged), "Insert " + label);+ return {true, "Inserted " + (copies.empty() ? "a " + label : std::to_string(copies.size() + 1) + " " + label + "s (mirrored)") ++ " (" + std::to_string(tris) + " triangles, polygroup " + std::to_string(group + 1) + ")"};+}+} // namespacevoid registerSubToolCommands(CommandRegistry& reg) {@@ -300,26 +409,21 @@ void registerSubToolCommands(CommandRegistry& reg) {return {true, "Appended SubTool " + doc.subtools[size_t(i)].name + " (" + countText(tris) + ")"};}});+ const std::vector<ParamSpec> placeParams{+ {"x", T::Number, "surface point x", true}, {"y", T::Number, "surface point y", true}, {"z", T::Number, "surface point z", true},+ {"nx", T::Number, "surface normal x", false}, {"ny", T::Number, "surface normal y", false}, {"nz", T::Number, "surface normal z", false},+ {"size", T::Number, "size in scene units (default 0.2)", false},+ {"twist", T::Number, "turn about the normal in degrees (default 0)", false},+ {"symmetry", T::String, "mirror axes, e.g. \"x\" or \"xz\": a mirrored copy across each plane (#43; default none)", false}};+ std::vector<ParamSpec> primitiveParams{{"type", T::String, "sphere, cube, cylinder, cone, torus, capsule or quadsphere", false}};+ primitiveParams.insert(primitiveParams.end(), placeParams.begin(), placeParams.end());reg.add({"insert_primitive","Insert a primitive into the active SubTool where the surface is (#34): its axis along the surface ""normal, its centre on the surface, as one new polygroup; one undoable step.",- {{"type", T::String, "sphere, cube, cylinder, cone, torus, capsule or quadsphere", false},- {"x", T::Number, "surface point x", true}, {"y", T::Number, "surface point y", true}, {"z", T::Number, "surface point z", true},- {"nx", T::Number, "surface normal x", false}, {"ny", T::Number, "surface normal y", false}, {"nz", T::Number, "surface normal z", false},- {"size", T::Number, "size in scene units (default 0.2)", false},- {"twist", T::Number, "turn about the normal in degrees (default 0)", false},- {"symmetry", T::String, "mirror axes, e.g. \"x\" or \"xz\": a mirrored copy across each plane (#43; default none)", false}},+ primitiveParams,[](Document& doc, const Args& a) -> CommandResult {const std::string blocked = dyntopoBlocker(doc.mesh);if (!blocked.empty()) return {false, "Can't insert: " + blocked};- Symmetry sym{false, false, false};- for (char ch : argString(a, "symmetry")) {- const char l = char(std::tolower(static_cast<unsigned char>(ch)));- if (l == 'x') sym.x = true;- else if (l == 'y') sym.y = true;- else if (l == 'z') sym.z = true;- else return {false, "symmetry takes the axes x, y and z"};- }const std::string type = argString(a, "type", "sphere");const float size = float(std::max(argNumber(a, "size", 0.2), 1e-4));Mesh prim;@@ -331,54 +435,39 @@ void registerSubToolCommands(CommandRegistry& reg) {else if (type == "capsule") prim = makeCapsule(24, size);else if (type == "quadsphere") prim = makeQuadSphere(8, size);else return {false, "Unknown primitive '" + type + "'"};- glm::vec3 n(float(argNumber(a, "nx", 0.0)), float(argNumber(a, "ny", 1.0)), float(argNumber(a, "nz", 0.0)));- n = glm::length(n) > 1e-8f ? glm::normalize(n) : glm::vec3(0, 1, 0);- // Rotate +Y onto the normal.- const glm::vec3 y(0, 1, 0);- glm::mat3 rot(1.0f);- const float c = glm::dot(y, n);- if (c < -0.9999f) rot = glm::mat3(1, 0, 0, 0, -1, 0, 0, 0, -1);- else if (c < 0.9999f) {- const glm::vec3 v = glm::cross(y, n);- const glm::mat3 k(0, v.z, -v.y, -v.z, 0, v.x, v.y, -v.x, 0);- rot = glm::mat3(1.0f) + k + k * k * (1.0f / (1.0f + c));- }- const float twist = glm::radians(float(argNumber(a, "twist", 0.0)));- if (twist != 0.0f) { // about the primitive's own axis (Y) first, then onto the normal- const float cs = std::cos(twist), sn = std::sin(twist);- rot = rot * glm::mat3(cs, 0, -sn, 0, 1, 0, sn, 0, cs);- }- const glm::vec3 at(float(argNumber(a, "x", 0.0)), float(argNumber(a, "y", 0.0)), float(argNumber(a, "z", 0.0)));- for (auto& p : prim.positions) p = at + rot * p;- uint32_t group = 0;- for (uint32_t g : doc.mesh.polygroups) group = std::max(group, g);- for (auto& g : prim.polygroups) g = group + 1;- prim.recomputeAllNormals();- // Symmetry: a mirrored copy across each enabled plane (through the centre, as the brushes mirror),- // in the same polygroup and the same undo step. A copy that would land on one already there- // (inserted on a plane itself) is left out.- std::vector<Mesh> copies;- std::vector<glm::vec3> placed{at};- for (const glm::vec3& m : Sculptor::mirrors(sym)) {- const glm::vec3 centre = at * m;- if (std::any_of(placed.begin(), placed.end(),- [&](const glm::vec3& p) { return glm::length(centre - p) < size * 0.25f; }))- continue;- placed.push_back(centre);- Mesh copy = prim;- for (auto& p : copy.positions) p *= m;- if (m.x * m.y * m.z < 0.0f) // a reflection turns the triangles inside out: wind them back- for (auto& t : copy.triangles) std::swap(t.y, t.z);- copy.recomputeAllNormals();- copies.push_back(std::move(copy));+ return insertPiece(doc, std::move(prim), a, type);+ }});++ std::vector<ParamSpec> meshParams{+ {"subtool", T::String, "insert a copy of this SubTool (by name)", false},+ {"file", T::String, "insert the mesh in this model file (.obj, .ply or .glb)", false}};+ meshParams.insert(meshParams.end(), placeParams.begin(), placeParams.end());+ reg.add({"insert_mesh",+ "Insert your own mesh into the active SubTool where the surface is (#34), placed like insert_primitive: "+ "a copy of another SubTool or a model file, scaled so its largest side is `size`, its up (+Y) axis "+ "along the surface normal, as one new polygroup; one undoable step.",+ meshParams,+ [](Document& doc, const Args& a) -> CommandResult {+ const std::string blocked = dyntopoBlocker(doc.mesh);+ if (!blocked.empty()) return {false, "Can't insert: " + blocked};+ if (a.contains("subtool") == a.contains("file")) return {false, "Give subtool= or file="};+ Mesh source;+ std::string label;+ if (a.contains("subtool")) {+ label = argString(a, "subtool");+ const int i = doc.findSubtool(label);+ if (i < 0) return {false, "No SubTool named '" + label + "'"};+ source = doc.subtoolMesh(i);+ } else {+ const std::string path = argString(a, "file");+ std::string error;+ if (!loadInsertMesh(path, source, error)) return {false, error};+ label = fileStem(path);}- std::vector<const Mesh*> parts{&doc.mesh, &prim};- for (const Mesh& c2 : copies) parts.push_back(&c2);- Mesh merged = mergeMeshes(parts);- const size_t tris = prim.triangleCount() * (1 + copies.size());- doc.replaceMeshUndoable(std::move(merged), "Insert " + type);- return {true, "Inserted " + (copies.empty() ? "a " + type : std::to_string(copies.size() + 1) + " " + type + "s (mirrored)") +- " (" + std::to_string(tris) + " triangles, polygroup " + std::to_string(group + 1) + ")"};+ Mesh piece;+ if (!normalizedPiece(source, float(std::max(argNumber(a, "size", 0.2), 1e-4)), piece))+ return {false, label + " has no mesh to insert"};+ return insertPiece(doc, std::move(piece), a, label);}});reg.add({"subtool_duplicate", "Copy a SubTool (with its layers and attributes) and make the copy active.",diff --git a/tests/test_primitives_insert.cpp b/tests/test_primitives_insert.cppindex c5a696cf..0363301f 100644--- a/tests/test_primitives_insert.cpp+++ b/tests/test_primitives_insert.cpp@@ -7,6 +7,14 @@#include "core/Document.h"#include "core/Json.h"#include "core/Primitives.h"+#include "io/GltfIO.h"+#include "io/ObjIO.h"+#include "io/PlyIO.h"++#include <algorithm>+#include <cmath>+#include <cstdio>+#include <map>#include <algorithm>#include <cmath>@@ -89,3 +97,91 @@ TEST(insert_primitive_mirrors_with_symmetry) {mirrored["symmetry"] = std::string("q");CHECK(!reg.execute(doc, "insert_primitive", mirrored).ok);}++// insert_mesh (#34): your own mesh, placed like a primitive.+namespace {+size_t groupTriangles(const Mesh& m, uint32_t g) {+ size_t n = 0;+ for (uint32_t t = 0; t < m.triangleCount(); ++t) n += m.polygroupAt(t) == g;+ return n;+}+uint32_t topGroup(const Mesh& m) {+ uint32_t g = 0;+ for (uint32_t x : m.polygroups) g = std::max(g, x);+ return g;+}+} // namespace++TEST(insert_mesh_from_subtool) {+ Document doc;+ CommandRegistry reg;+ CHECK(reg.execute(doc, "new_sphere", {{"subdivisions", 3.0}}).ok);+ // A tall, off-centre box SubTool to insert: it's centred and scaled so its largest side is `size`.+ CHECK(reg.execute(doc, "subtool_append", {{"type", std::string("cube")}, {"name", std::string("Stud")}}).ok);+ for (auto& p : doc.mesh.positions) p = glm::vec3(p.x, p.y * 4.0f, p.z) + glm::vec3(5.0f, 3.0f, 0.0f);+ const size_t studTris = doc.mesh.triangleCount();+ CHECK(reg.execute(doc, "subtool_select", {{"index", 0.0}}).ok);+ const size_t before = doc.mesh.triangleCount();+ CommandResult r = reg.execute(doc, "insert_mesh", {{"subtool", std::string("Stud")}, {"x", 1.0}, {"y", 0.0}, {"z", 0.0},+ {"nx", 1.0}, {"ny", 0.0}, {"nz", 0.0}, {"size", 0.4}});+ CHECK(r.ok);+ CHECK(doc.mesh.triangleCount() == before + studTris);+ CHECK(doc.subtoolCount() == 2); // the source SubTool stays+ // Its long (Y) axis lies along the normal (+X): it reaches 0.2 out from the surface point, 0.05 to the sides.+ const uint32_t g = topGroup(doc.mesh);+ CHECK(groupTriangles(doc.mesh, g) == studTris);+ AABB box;+ for (uint32_t t = 0; t < doc.mesh.triangleCount(); ++t)+ if (doc.mesh.polygroupAt(t) == g)+ for (int k = 0; k < 3; ++k) box.expand(doc.mesh.positions[doc.mesh.triangles[t][k]]);+ CHECK(std::abs(box.max.x - 1.2f) < 0.01f);+ CHECK(std::abs(box.min.x - 0.8f) < 0.01f);+ CHECK(std::abs(box.max.y - 0.05f) < 0.01f);+ CHECK(reg.execute(doc, "undo", {}).ok);+ CHECK(doc.mesh.triangleCount() == before);+ // Symmetry makes a mirrored copy, as with the primitives.+ CHECK(reg.execute(doc, "insert_mesh", {{"subtool", std::string("Stud")}, {"symmetry", std::string("x")}, {"x", 1.0},+ {"y", 0.0}, {"z", 0.0}, {"nx", 1.0}, {"ny", 0.0}, {"nz", 0.0}, {"size", 0.4}}).ok);+ CHECK(doc.mesh.triangleCount() == before + 2 * studTris);+ float minX = 0.0f;+ for (const auto& p : doc.mesh.positions) minX = std::min(minX, p.x);+ CHECK(minX < -1.1f);+ // Errors: nothing named, both named, an unknown SubTool.+ CHECK(!reg.execute(doc, "insert_mesh", {{"x", 0.0}, {"y", 0.0}, {"z", 0.0}}).ok);+ CHECK(!reg.execute(doc, "insert_mesh", {{"subtool", std::string("Stud")}, {"file", std::string("a.obj")}, {"x", 0.0},+ {"y", 0.0}, {"z", 0.0}}).ok);+ CHECK(!reg.execute(doc, "insert_mesh", {{"subtool", std::string("Nope")}, {"x", 0.0}, {"y", 0.0}, {"z", 0.0}}).ok);+}++TEST(insert_mesh_from_file) {+ Document doc;+ CommandRegistry reg;+ CHECK(reg.execute(doc, "new_sphere", {{"subdivisions", 3.0}}).ok);+ const size_t before = doc.mesh.triangleCount();+ // A small tetrahedron written as OBJ text (quads aren't needed).+ const std::string obj = tempPath("sf_insert_mesh.obj");+ if (FILE* f = std::fopen(obj.c_str(), "w")) {+ std::fputs("v 0 0 0\nv 1 0 0\nv 0 1 0\nv 0 0 1\nf 1 3 2\nf 1 2 4\nf 1 4 3\nf 2 3 4\n", f);+ std::fclose(f);+ }+ CHECK(reg.execute(doc, "insert_mesh", {{"file", obj}, {"x", 0.0}, {"y", 1.0}, {"z", 0.0}, {"size", 0.3}}).ok);+ CHECK(doc.mesh.triangleCount() == before + 4);+ float maxY = 0.0f;+ for (const auto& p : doc.mesh.positions) maxY = std::max(maxY, p.y);+ CHECK(std::abs(maxY - 1.15f) < 0.01f);+ // The same mesh as PLY and GLB, through their exporters.+ Mesh tet;+ std::string err;+ CHECK(loadObj(obj, tet, err));+ const std::string ply = tempPath("sf_insert_mesh.ply"), glb = tempPath("sf_insert_mesh.glb");+ CHECK(savePlyMesh(ply, tet, err));+ CHECK(saveGlb(glb, tet, "tet", err));+ CHECK(reg.execute(doc, "insert_mesh", {{"file", ply}, {"x", 0.0}, {"y", 1.0}, {"z", 0.0}}).ok);+ CHECK(reg.execute(doc, "insert_mesh", {{"file", glb}, {"x", 0.0}, {"y", 1.0}, {"z", 0.0}}).ok);+ CHECK(doc.mesh.triangleCount() == before + 12);+ // Only OBJ, PLY and GLB; a missing file is an error and changes nothing.+ CHECK(!reg.execute(doc, "insert_mesh", {{"file", tempPath("sf_insert_mesh.stl")}, {"x", 0.0}, {"y", 1.0}, {"z", 0.0}}).ok);+ CHECK(!reg.execute(doc, "insert_mesh", {{"file", tempPath("sf_insert_mesh_missing.obj")}, {"x", 0.0}, {"y", 1.0}, {"z", 0.0}}).ok);+ CHECK(doc.mesh.triangleCount() == before + 12);+ for (const std::string& p : {obj, ply, glb}) std::remove(p.c_str());+}diff --git a/tests/ui/data/stud.obj b/tests/ui/data/stud.objnew file mode 100644index 00000000..0b8964e2--- /dev/null+++ b/tests/ui/data/stud.obj@@ -0,0 +1,14 @@+v 0 1 0+v 1 0 0+v 0 0 1+v -1 0 0+v 0 0 -1+v 0 -1 0+f 1 3 2+f 1 4 3+f 1 5 4+f 1 2 5+f 6 2 3+f 6 3 4+f 6 4 5+f 6 5 2diff --git a/tests/ui/insert_mesh.sfui b/tests/ui/insert_mesh.sfuinew file mode 100644index 00000000..1bf3d814--- /dev/null+++ b/tests/ui/insert_mesh.sfui@@ -0,0 +1,34 @@+# #34: Append > Insert on the model with your own mesh: a copy of another SubTool, or a model file.+run new_sphere subdivisions=4+key f+click "SubTools/Append"+click "Cube"+expect_value subtools == 2+run subtool_select index=0+key f++# A copy of the Cube SubTool, dragged onto the sphere (X symmetry is on: a mirrored copy too), one undo step.+remember triangles base+click "SubTools/Append"+hover "Insert on the model"+hover "Active SubTool's copy..."+click "Cube##insertcopy1"+expect_status Insert a copy of Cube+stroke 0.8 0.45 0.86 0.45+expect_status 2 Cubes (mirrored)+expect_value triangles > $base+expect_value subtools == 2+shot insert_subtool_copy+key ctrl+z+expect_value triangles == $base++# From file: the path the file dialog answers with; the next drag inserts it.+choose_file insert data/stud.obj+wait 0.1+expect_status Insert stud.obj+stroke 0.8 0.45 0.86 0.45+expect_status 2 studs (mirrored)+expect_value triangles == $base+16+shot insert_file+key escape+expect_status Insert off