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.

Extract (Tool > SubTool) and Mirror And Weld / Mirror (Tool > Geometry, Tool > Deformation), ZBrush style

islandmedd6bcfb88e6fb
diff --git a/CHANGELOG.md b/CHANGELOG.md
index fb357786..136025cc 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -6,6 +6,11 @@ All notable changes to SculptForge are listed here. The format follows
## [Unreleased]
+### Added
+- Extract (Tool > SubTool > Extract), as in ZBrush: the masked, visible part of a SubTool becomes a shell with Thick (a share of the SubTool's size; negative grows inward, 0 makes a single-sided surface), E Smt (smooths the stepped edge) and Double (both ways). Extract shows a preview below the source that follows the settings; Accept keeps it as a new SubTool with outer, inner and rim polygroups and the source's polypaint, as one undo step (undo removes the SubTool, redo puts it back). An unaccepted preview goes when the source changes and is never saved. Commands: extract, extract_accept, extract_cancel.
+- Mirror And Weld (Tool > Geometry > Modify Topology, X / Y / Z): keeps the + side of the plane through the origin, cuts polygons crossing it, mirrors the half and welds the seam into one watertight mesh, keeping polygroups, polypaint, mask, UVs, quads and sculpt layers (`mirror_and_weld`, with `side=negative` for the other half). Undoable.
+- Mirror (Tool > Deformation, X / Y / Z): flips the SubTool across the plane through the origin, or in place with `pivot=center` (`mirror`). Undoable.
+
## [0.9.5] - 2026-10-31
The day after launch, people filed ten issues. 0.9.5 answers all of them: ZSpheres for blocking out a base mesh,
diff --git a/CMakeLists.txt b/CMakeLists.txt
index 045ea1b2..cd971da9 100644
--- a/CMakeLists.txt
+++ b/CMakeLists.txt
@@ -42,6 +42,7 @@ add_library(sculptforge_core STATIC
src/core/Polygroups.cpp
src/core/ScreenSelect.cpp
src/core/SubTools.cpp
+ src/core/ExtractMirror.cpp
src/core/MeshTransform.cpp
src/core/TransformCommands.cpp
src/core/Decimate.cpp
@@ -247,6 +248,7 @@ if(SCULPTFORGE_BUILD_APP)
src/app/PanelPhone.cpp
src/app/PanelProject.cpp
src/app/PanelSubTools.cpp
+ src/app/PanelExtract.cpp
src/app/Tablet.cpp
src/app/SpaceMouse.cpp
src/app/Input.cpp
diff --git a/docs/guide/geometry.md b/docs/guide/geometry.md
index 9e9d0fc4..5cbfe73c 100644
--- a/docs/guide/geometry.md
+++ b/docs/guide/geometry.md
@@ -1,8 +1,8 @@
# Subdivide, remesh, decimate and LODs
These tools change the topology of the active SubTool: add resolution for detail, rebuild an even surface,
-reduce the triangle count, or make a chain of levels of detail for a game engine. This chapter explains what each
-one does to your mesh and its attributes, and when to use it.
+reduce the triangle count, make it symmetric, or make a chain of levels of detail for a game engine. This
+chapter explains what each one does to your mesh and its attributes, and when to use it.
All of them work on the **active SubTool** and, except the LOD preview, are undoable with
<kbd>Ctrl</kbd>+<kbd>Z</kbd>.
@@ -16,6 +16,7 @@ All of them work on the **active SubTool** and, except the LOD preview, are undo
| Voxel Remesh | **Tool > Remesh > Voxel Remesh** | Set by resolution | All quads (new ones) | Baked in | Yes (transferred) | No (reset); a texture is kept on new UVs with Keep Texture |
| QRemesh | **Tool > Geometry > QRemesh** | Set by Target Polygons | All quads, with edge loops | Baked in | Yes (transferred) | Polygroups with Keep Groups; no hidden faces; a texture is kept on new UVs with Keep Texture |
| Decimate | **Tool > Geometry > Decimate** | Reduced | No, all triangles | Yes | Yes | Yes |
+| Mirror And Weld | **Tool > Geometry > Modify Topology** | Twice the kept side | Yes | Yes | Yes (mirrored) | Yes (mirrored) |
| LOD chain | **Tool > Export** | One level per ratio step | LOD0 keeps them; lower levels are triangles | Yes, on every level | Yes | Yes |
## Quads and triangles
@@ -117,6 +118,31 @@ scan down to something you can work with.
> **Tip:** Decimate a duplicate SubTool (**Tool > SubTool > Duplicate**) when you want to keep the full-resolution
> sculpt in the same project.
+## Mirror And Weld
+
+**Mirror And Weld**, in **Tool > Geometry > Modify Topology**, makes a model symmetric: it keeps the half on the
++ side of the chosen axis (+X is the model's left, your right when you look at its face), mirrors it onto the
+other side and welds the two halves along the middle into one watertight mesh. Use it after sculpting one side
+without symmetry, to finish a half model, or to repair a model whose sides have drifted apart.
+
+![A head with a scar and a brow ridge on one side, then the same head after Mirror And Weld X](images/mirror-weld.jpg)
+
+- Pick the axis with **X**, **Y** and **Z** beside the button (X is on by default). With several on, they apply
+ one after the other.
+- The mirror plane goes through the world's origin, the same plane symmetry uses. Polygons that cross it are cut
+ on it, so the seam is clean wherever the model sits. Points on an open edge within 0.1% of the model's size
+ from the plane are welded onto it, which closes a half model whose seam isn't exactly at 0.
+- Polygroups, polypaint, the mask, UVs, quads and sculpt layers are kept; the mirrored side takes the kept side's.
+ Subdivision levels are removed (undo restores them), as with the other tools on this page.
+- To keep the **other** side, flip the model first with **Tool > Deformation > Mirror**, or run
+ `mirror_and_weld side=negative`.
+
+## Mirror
+
+**Tool > Deformation > Mirror** flips the SubTool across the plane through the origin on the chosen axes, with its
+surface still facing outward. Polygroups, polypaint, UVs and layers come along; subdivision levels are removed
+(undo restores them). `mirror pivot=center` flips it in place about its own centre instead.
+
## LOD chains
A level-of-detail chain is a series of lighter copies of the model for game engines: LOD0 is the full sculpt, and
@@ -149,9 +175,9 @@ See [Exporting](exporting.md) for these exports and their options.
## Undo and safety
-Subdivide, remesh, QRemesh, decimate and delete hidden are single undo steps on the active SubTool. They can use a lot of
-memory on dense meshes, and undo keeps a full copy of the previous mesh for each of them. Before a big change on a
-heavy sculpt:
+Subdivide, remesh, QRemesh, decimate, Mirror And Weld, Mirror and delete hidden are single undo steps on the
+active SubTool. They can use a lot of memory on dense meshes, and undo keeps a full copy of the previous mesh for
+each of them. Before a big change on a heavy sculpt:
- **QuickSave** (title strip) keeps a timestamped copy of the scene without touching your project file; see
[Projects](projects.md#quicksave).
@@ -165,6 +191,8 @@ heavy sculpt:
| `remesh` | `resolution` 32-512 voxels across the longest side (default 200); `keep_texture` (default true) |
| `decimate` | `ratio` 0.01-1 of the triangles to keep (default 0.5), or `triangles` for an exact target |
| `qremesh` | `target` quads (default 5000), `adaptive`, `keep_groups`, `detect_edges`, `use_polypaint`, `symmetry`, `keep_original`, `keep_texture`; see [Quad retopology](retopology.md#scripting) |
+| `mirror_and_weld` | `axis` x, y, z or several, e.g. `xz` (default x); `side` positive (default) or negative |
+| `mirror` | `axis` (default x); `pivot` origin (default) or center |
| `export_lods` | `path` (base name), `levels` 1-8 including LOD0 (default 4), `ratio` 0.1-0.9 (default 0.5) |
```sh
diff --git a/docs/guide/glossary.md b/docs/guide/glossary.md
index 008caf28..f409393d 100644
--- a/docs/guide/glossary.md
+++ b/docs/guide/glossary.md
@@ -21,6 +21,7 @@ for what is planned.
| Document, 2.5D canvas, pixols | Not planned: SculptForge is a 3D sculpting app only |
| Draw Size | **Draw Size** (top shelf, <kbd>S</kbd>, <kbd>[</kbd> / <kbd>]</kbd>) |
| DynaMesh | **Voxel Remesh** (**Tool > Remesh**, `remesh`). See [Geometry](geometry.md#voxel-remesh) |
+| Extract (Tool > SubTool > Extract) | **Tool > SubTool > Extract**: the masked part becomes a shell SubTool, with **Thick**, **E Smt** and **Double**; **Extract** previews, **Accept** keeps it (`extract`, `extract_accept`). See [SubTools](subtools.md#extract-a-shell) |
| Focal Shift | No slider for the built-in brushes. Custom brushes have **Hardness** and **Tip sharpness** in their recipe |
| Ghost, Transp | Not yet. Inactive SubTools are drawn slightly dimmed |
| GoZ | **GoZ**: `.GoZ` import and export and the GoZ bridge (**File > ZBrush (GoZ)**). See [Exporting](exporting.md) |
@@ -36,7 +37,9 @@ for what is planned.
| Mask by Cavity | **Tool > Masking > By cavity** (`mask_by_cavity`) |
| Masking (Ctrl) | Hold <kbd>Ctrl</kbd> to paint the mask, <kbd>Ctrl</kbd>+<kbd>Alt</kbd> to erase. See [Masking](masking.md) |
| MaskLasso, MaskRect | **Tool > Masking**: pick the shape, then <kbd>Ctrl</kbd>+drag (add <kbd>Alt</kbd> to unmask). See [Masking](masking.md) |
-| MatCap | **Material**: seven MatCaps, Sculpt the default, plus Studio (<kbd>M</kbd>). Custom MatCap images not yet. See [Polypaint](polypaint.md) |
+| MatCap | **Material**: the built-in MatCaps, Soft Clay the default, plus Studio (<kbd>M</kbd>), and your own with **Load MatCap...** (`load_matcap`). See [Polypaint](polypaint.md) |
+| Mirror (Tool > Deformation) | **Tool > Deformation > Mirror** with X Y Z (`mirror`): flips the SubTool across the plane through the origin. See [Geometry](geometry.md#mirror) |
+| Mirror And Weld | **Tool > Geometry > Modify Topology > Mirror And Weld** with X Y Z (`mirror_and_weld`): the + side mirrored onto the - side and welded into one watertight mesh, keeping polygroups and polypaint. See [Geometry](geometry.md#mirror-and-weld) |
| Morph target | A [sculpt layer](layers.md); exported as glTF morph targets and FBX/USD blend shapes |
| Mrgb, M (material channel) | Not yet: there is no per-vertex material channel |
| Polyframe (PolyF, Shift+F) | **PolyF** on the right shelf, or <kbd>Shift</kbd>+<kbd>F</kbd> |
diff --git a/docs/guide/images/extract.jpg b/docs/guide/images/extract.jpg
new file mode 100644
index 00000000..598aa627
Binary files /dev/null and b/docs/guide/images/extract.jpg differ
diff --git a/docs/guide/images/mirror-weld.jpg b/docs/guide/images/mirror-weld.jpg
new file mode 100644
index 00000000..377cb17f
Binary files /dev/null and b/docs/guide/images/mirror-weld.jpg differ
diff --git a/docs/guide/interface.md b/docs/guide/interface.md
index da9be7ba..44fb0ed9 100644
--- a/docs/guide/interface.md
+++ b/docs/guide/interface.md
@@ -68,7 +68,7 @@ Interface > Palettes strictly A-Z (ZBrush order)**.
| **Script** | Console, Run script file, Copy session as script, Clear console |
| **Splats** | Gaussian splat tools: show, flip, turn, fit, clean floaters, Make sculptable, sculpt to splats, save, clear |
| **Stroke** | The stroke types (Dots, DragRect, Spray, LazyMouse) and their settings |
-| **Tool** | The active SubTool with Open, Save and Import, and the SubTool, Layers, Paint Layers, Geometry, Remesh, Masking, Polygroups, Visibility, Export and Display sub-palettes |
+| **Tool** | The active SubTool with Open, Save and Import, and the SubTool, Layers, Paint Layers, Geometry, Remesh, Deformation, Masking, Polygroups, Visibility, Export and Display sub-palettes |
| **Transform** | Draw, Move, Scale and Rotate (the [Gizmo 3D](gizmo.md) with its pivot, axes, options and numeric entry), Symmetry X, Y and Z, Frame, Solo, PolyF |
| **Help** | Controls, User Guide, What's New, Command palette, Website & documentation, Report a problem, About SculptForge |
diff --git a/docs/guide/subtools.md b/docs/guide/subtools.md
index 48cb49bc..ba84021e 100644
--- a/docs/guide/subtools.md
+++ b/docs/guide/subtools.md
@@ -112,6 +112,32 @@ meshes the Auto UV takes a while. Scripts can skip it with `keep_texture=false`,
Both replace the active SubTool with the pieces. Because a merge keeps each original mesh in its own polygroup,
**Split groups** undoes a merge.
+## Extract a shell
+
+**Extract**, in **Tool > SubTool**, makes a new SubTool from the masked part of the active one: a helmet from the
+top of a head, a strap, a sleeve, a piece of armour that fits the surface exactly. It works as in ZBrush:
+
+1. Mask the part (hold <kbd>Ctrl</kbd> and paint, or use **MaskRect** / **MaskLasso**; see [Masking](masking.md)).
+2. Click **Extract**. The shell appears as a preview, a SubTool just below the active one.
+3. Change **Thick**, **E Smt** or **Double** and the preview follows. Click **Accept** to keep it.
+
+| Setting | What it does |
+|---|---|
+| **Thick** | The shell's thickness as a share of the SubTool's size: 0.015 (the default) is 1.5%. Negative grows it inward; 0 makes a single-sided surface |
+| **E Smt** | Smooths the extracted edge, which otherwise follows the mask's triangles in steps. 0 keeps it as masked |
+| **Double** | Grows the shell both inward and outward from the surface |
+
+![A cap extracted from the masked top of a sphere, shown with its polygroups: outer, inner and rim](images/extract.jpg)
+
+The new SubTool has three polygroups, the outer surface, the inner one and the rim between them (a band of quads),
+so you can mask, hide or [split](#split-a-subtool) them apart. Polypaint comes with it; hidden faces are left out.
+Accept is one undo step: <kbd>Ctrl</kbd>+<kbd>Z</kbd> on the source SubTool takes the extracted one away again,
+and redo brings it back. A preview you don't accept goes away as soon as you change the source SubTool or pick
+another one, and it is never saved.
+
+> **ZBrush:** the same Extract, E Smt, Thick, Double and Accept. ZBrush's TCorne and TBorder options are not
+> there yet.
+
## Delete a SubTool
Click **Delete...** (or right-click a row > **Delete...**) and confirm. The last SubTool can't be deleted, and a
@@ -151,6 +177,8 @@ used.
| `subtool_move direction=up` | Move a SubTool up or down the list |
| `subtool_merge_down` / `subtool_merge_visible` | Merge |
| `subtool_split_groups` / `subtool_split_parts` | Split |
+| `extract thickness=0.02 smooth=5 double=false` | Preview an Extract shell from the mask; `accept=true` keeps it at once |
+| `extract_accept` / `extract_cancel` | Keep or remove the Extract preview |
```text
subtool_append type=sphere name=EyeL size=0.12; subtool_duplicate; subtool_rename to=EyeR
diff --git a/docs/guide/whats-new.md b/docs/guide/whats-new.md
index e462ccdb..d2e7fb73 100644
--- a/docs/guide/whats-new.md
+++ b/docs/guide/whats-new.md
@@ -5,6 +5,21 @@ chapter opens by itself the first time you start a new version; you can always f
**Help > What's New**. Every detail is in the
[changelog](https://github.com/islandmed/SculptForge/blob/main/CHANGELOG.md).
+## Next version
+
+### Extract
+
+Mask part of a SubTool and **Tool > SubTool > Extract** turns it into a shell that fits the surface exactly: a
+helmet, a strap, a piece of armour. Set **Thick**, **E Smt** and **Double** while the preview shows, then
+**Accept** keeps it as a new SubTool (and <kbd>Ctrl</kbd>+<kbd>Z</kbd> takes it away again). See
+[Extract a shell](subtools.md#extract-a-shell).
+
+### Mirror And Weld
+
+**Tool > Geometry > Modify Topology > Mirror And Weld** mirrors one side of a model onto the other across X, Y
+or Z and welds the seam into one watertight mesh, keeping polygroups and polypaint. **Tool > Deformation >
+Mirror** flips a SubTool. See [Mirror And Weld](geometry.md#mirror-and-weld).
+
## Version 0.9.5
### ZSpheres
diff --git a/src/app/App.cpp b/src/app/App.cpp
index 5a1a4a8c..949d35e6 100644
--- a/src/app/App.cpp
+++ b/src/app/App.cpp
@@ -1488,6 +1488,8 @@ void App::updateTitle() {
// ---------------------------------------------------------------------------
void App::drawUi() {
+ // An Extract preview goes once its source changes or another SubTool is picked (strokes aren't commands).
+ if (doc_.extractPreview.id && !doc_.sculptor.strokeActive()) doc_.dropExtractPreview(true);
drawProjectPopups();
if (hideUi_) return; // demos: clean beauty shots
// Draw order (ui-spec §12): shells, LightBox, floating windows, then pop-ups and help.
diff --git a/src/app/App.h b/src/app/App.h
index a6229e05..96508499 100644
--- a/src/app/App.h
+++ b/src/app/App.h
@@ -867,6 +867,18 @@ private:
float sdivSlider_ = 1.0f; // the SDiv slider while dragged (1-based)
bool sdivHeld_ = false;
void drawSubToolsContents();
+ // PanelExtract.cpp: Tool > SubTool > Extract, Tool > Geometry > Modify Topology (Mirror And Weld) and
+ // Tool > Deformation (Mirror), as in ZBrush.
+ void drawExtractContents();
+ void drawModifyTopologyContents();
+ void drawDeformationContents();
+ void runExtract(); // Extract with the palette's settings (a preview; Accept keeps it)
+ static std::string axesText(const bool axes[3]); // "x", "xz", "" (the axis argument of mirror commands)
+ float extractThick_ = 0.015f; // Thick: fraction of the SubTool's size
+ int extractSmooth_ = 5; // E Smt
+ bool extractDouble_ = false; // Double
+ bool mirrorWeldAxes_[3] = {true, false, false}; // Mirror And Weld's X Y Z
+ bool mirrorAxes_[3] = {true, false, false}; // Deformation > Mirror's X Y Z
void pollAlphaFile();
ShellGeometry shell_; // this frame's regions (drawShell)
ImFont* fontSmall_ = nullptr, *fontTiny_ = nullptr, *fontIcons_ = nullptr, *fontBold_ = nullptr;
diff --git a/src/app/Config.cpp b/src/app/Config.cpp
index 30fe32b8..a379facb 100644
--- a/src/app/Config.cpp
+++ b/src/app/Config.cpp
@@ -261,6 +261,40 @@ void App::initActions() {
[this] { return subdivCurrentLevel(doc_.mesh) + 1 < subdivLevelCount(doc_.mesh); });
add("geometry.reconstruct", "Reconstruct Subdiv", "Tool > Geometry", nullptr, [this] { runCommand("subdiv_reconstruct"); },
nullptr, "subdiv_reconstruct", nullptr, [this] { return subdivCurrentLevel(doc_.mesh) == 0; });
+ // Tool > SubTool > Extract, Tool > Geometry > Modify Topology, Tool > Deformation (PanelExtract.cpp).
+ add("subtool.extract", "Extract", "Tool > SubTool", nullptr, [this] { runExtract(); }, nullptr, "extract", nullptr,
+ [this] { return doc_.mesh.hasMask(); },
+ "Make a shell from the masked part of the SubTool (a helmet, a strap, clothing), shown as a preview below it. "
+ "Change Thick, E Smt or Double and it updates; Accept keeps it as a new SubTool.");
+ add("subtool.extract_accept", "Accept", "Tool > SubTool", nullptr, [this] { runCommand("extract_accept"); }, nullptr,
+ "extract_accept", nullptr, [this] { return doc_.extractPreviewCurrent(); },
+ "Keep the Extract preview as a new SubTool below this one. Ctrl+Z takes it away again.");
+ add("subtool.extract_double", "Double", "Tool > SubTool", nullptr,
+ [this] {
+ extractDouble_ = !extractDouble_;
+ if (doc_.extractPreviewCurrent()) runExtract();
+ },
+ nullptr, nullptr, [this] { return extractDouble_; }, nullptr,
+ "Grow the extracted shell both inward and outward from the surface, instead of outward only.");
+ add("geometry.mirror_weld", "Mirror And Weld", "Tool > Geometry", nullptr,
+ [this] { runCommand("mirror_and_weld", {{"axis", axesText(mirrorWeldAxes_)}}); }, nullptr, "mirror_and_weld",
+ nullptr, [this] { return !axesText(mirrorWeldAxes_).empty() && doc_.mesh.triangleCount() > 0; },
+ "Mirror the + side of the SubTool onto the - side across the chosen axis and weld the seam into one "
+ "watertight mesh. Polygroups and polypaint come along. To keep the other side, Deformation > Mirror first.");
+ add("deformation.mirror", "Mirror", "Tool > Deformation", nullptr,
+ [this] { runCommand("mirror", {{"axis", axesText(mirrorAxes_)}}); }, nullptr, "mirror", nullptr,
+ [this] { return !axesText(mirrorAxes_).empty() && doc_.mesh.vertexCount() > 0; },
+ "Flip the SubTool across the chosen axis, through the origin (the plane symmetry and Mirror And Weld use).");
+ for (int k = 0; k < 3; ++k) {
+ static const char* const kWeldIds[3] = {"geometry.mirror_weld_x", "geometry.mirror_weld_y", "geometry.mirror_weld_z"};
+ static const char* const kMirrorIds[3] = {"deformation.mirror_x", "deformation.mirror_y", "deformation.mirror_z"};
+ static const char* const kNames[3] = {"X", "Y", "Z"};
+ add(kWeldIds[k], kNames[k], "Tool > Geometry", nullptr, [this, k] { mirrorWeldAxes_[k] = !mirrorWeldAxes_[k]; },
+ nullptr, nullptr, [this, k] { return mirrorWeldAxes_[k]; }, nullptr,
+ "An axis Mirror And Weld mirrors across (several: one after the other).");
+ add(kMirrorIds[k], kNames[k], "Tool > Deformation", nullptr, [this, k] { mirrorAxes_[k] = !mirrorAxes_[k]; }, nullptr,
+ nullptr, [this, k] { return mirrorAxes_[k]; }, nullptr, "An axis Mirror flips along (several: one after the other).");
+ }
add("file.new_sphere", "New Sphere", "File", "Ctrl+N", [this] { confirmDiscard([this] { runCommand("new_sphere"); }); },
ICON_LC_FILE_PLUS, "new_sphere");
add("file.new_plane", "New Plane", "File", nullptr, [this] { confirmDiscard([this] { runCommand("new_plane"); }); }, nullptr,
diff --git a/src/app/Palettes.cpp b/src/app/Palettes.cpp
index 7ecfd41b..f7a7df36 100644
--- a/src/app/Palettes.cpp
+++ b/src/app/Palettes.cpp
@@ -492,6 +492,7 @@ void App::drawPalette_Tool() {
Demo::pushScope("SubTools");
drawSubToolsContents();
Demo::popScope();
+ drawExtractContents(); // PanelExtract.cpp
Demo::pushScope("Project");
drawProjectContents(); // ProjectAll (PanelRetopo.cpp)
Demo::popScope();
@@ -548,6 +549,7 @@ void App::drawPalette_Tool() {
Demo::pushScope("QRemesh");
drawQRemeshContents(); // quad retopology (PanelRetopo.cpp)
Demo::popScope();
+ drawModifyTopologyContents(); // Mirror And Weld (PanelExtract.cpp)
}
if (subpalette("tool.remesh", "Remesh")) {
tray::Section section;
@@ -574,6 +576,12 @@ void App::drawPalette_Tool() {
drawKeepTextureCheckbox("Keep Texture##remesh", "Tool > Remesh"); // only for a painted SubTool
}
}
+ if (subpalette("tool.deformation", "Deformation")) {
+ tray::Section section;
+ Demo::pushScope("Deformation");
+ drawDeformationContents(); // Mirror (PanelExtract.cpp)
+ Demo::popScope();
+ }
if (subpalette("tool.masking", "Masking")) {
tray::Section section;
drawMaskingSection();
diff --git a/src/app/PanelExtract.cpp b/src/app/PanelExtract.cpp
new file mode 100644
index 00000000..da92039d
--- /dev/null
+++ b/src/app/PanelExtract.cpp
@@ -0,0 +1,81 @@
+// SculptForge - open source digital sculpting
+// SPDX-License-Identifier: GPL-3.0-or-later
+//
+// ZBrush's Extract (Tool > SubTool), Mirror And Weld (Tool > Geometry > Modify Topology) and Mirror
+// (Tool > Deformation). The work is done by the extract / mirror_and_weld / mirror commands (core/ExtractMirror.h).
+#include "app/App.h"
+#include "app/Demo.h"
+#include "app/Palettes.h"
+#include "app/Ui.h"
+
+#include <string>
+
+namespace sf {
+
+std::string App::axesText(const bool axes[3]) {
+ std::string s;
+ for (int k = 0; k < 3; ++k)
+ if (axes[k]) s += char('x' + k);
+ return s;
+}
+
+void App::runExtract() {
+ runCommand("extract", {{"thickness", double(extractThick_)}, {"smooth", double(extractSmooth_)}, {"double", extractDouble_}});
+}
+
+void App::drawExtractContents() {
+ Demo::pushScope("Extract");
+ tray::GroupLabel(*this, "Extract");
+ const float half = (ImGui::GetContentRegionAvail().x - ImGui::GetStyle().ItemSpacing.x) * 0.5f;
+ ui::ActionButton(*this, "subtool.extract", ImVec2(half, 0));
+ ui::HelpAction(*this, "subtool.extract");
+ ImGui::SameLine();
+ ui::ActionButton(*this, "subtool.extract_accept", ImVec2(-1, 0));
+ ui::HelpAction(*this, "subtool.extract_accept");
+
+ // The settings: changing one while the preview shows extracts again, so the preview follows.
+ bool changed = false;
+ ImGui::SetNextItemWidth(half);
+ tray::SliderInt("##extract_smooth", &extractSmooth_, 0, 20, "E Smt %d");
+ changed |= ImGui::IsItemDeactivatedAfterEdit();
+ ui::HelpText("E Smt", nullptr,
+ "Smooths the extracted edge, which otherwise follows the mask's triangles in steps (0 = as masked).",
+ "Tool > SubTool > Extract");
+ ImGui::SameLine();
+ ImGui::SetNextItemWidth(-1);
+ ui::SliderInside("##extract_thick", &extractThick_, -0.1f, 0.1f, "Thick %.3f");
+ changed |= ImGui::IsItemDeactivatedAfterEdit();
+ ui::HelpText("Thick", nullptr,
+ "Thickness of the shell, as a fraction of the SubTool's size (0.015 is 1.5%). Negative grows it "
+ "inward; 0 makes a single-sided surface.",
+ "Tool > SubTool > Extract");
+ ui::ActionButton(*this, "subtool.extract_double", ImVec2(half, 0));
+ ui::HelpAction(*this, "subtool.extract_double");
+ if (changed && doc_.extractPreviewCurrent()) runExtract();
+ Demo::popScope();
+}
+
+void App::drawModifyTopologyContents() {
+ Demo::pushScope("Modify Topology");
+ tray::GroupLabel(*this, "Modify Topology");
+ const ImGuiStyle& style = ImGui::GetStyle();
+ const float axisW = ImGui::GetFrameHeight() * 1.3f;
+ ui::ActionButton(*this, "geometry.mirror_weld",
+ ImVec2(ImGui::GetContentRegionAvail().x - 3.0f * axisW - 2.0f - style.ItemSpacing.x, 0));
+ ui::HelpAction(*this, "geometry.mirror_weld");
+ ImGui::SameLine();
+ ui::Segmented(*this, {"geometry.mirror_weld_x", "geometry.mirror_weld_y", "geometry.mirror_weld_z"}, -1.0f);
+ Demo::popScope();
+}
+
+void App::drawDeformationContents() {
+ const ImGuiStyle& style = ImGui::GetStyle();
+ const float axisW = ImGui::GetFrameHeight() * 1.3f;
+ ui::ActionButton(*this, "deformation.mirror",
+ ImVec2(ImGui::GetContentRegionAvail().x - 3.0f * axisW - 2.0f - style.ItemSpacing.x, 0));
+ ui::HelpAction(*this, "deformation.mirror");
+ ImGui::SameLine();
+ ui::Segmented(*this, {"deformation.mirror_x", "deformation.mirror_y", "deformation.mirror_z"}, -1.0f);
+}
+
+} // namespace sf
diff --git a/src/app/UiTest.cpp b/src/app/UiTest.cpp
index 2f7f3dbf..43dc15e6 100644
--- a/src/app/UiTest.cpp
+++ b/src/app/UiTest.cpp
@@ -55,6 +55,8 @@
// custom_matcaps (MatCaps loaded from images), material_custom (1 when the view uses
// one), matcap_files (images in the library's MatCaps folder),
// subtools (count), active_subtool (index, 0 = top), visible_subtools,
+// extract_preview (1 while an Extract preview waits for Accept), open_edges (edges of
+// the active SubTool with one triangle: 0 = watertight),
// edited_subtools (SubTools with undo history), user_brushes (brushes in the
// user library), library_files (.sfbrush files in it; UI tests get an empty
// one in --ui-out/brush-library), ui_config (1 once Store Config wrote ui.json),
@@ -482,6 +484,13 @@ double Demo::query(const std::string& name, bool& known) const {
const Document& doc = app_.doc_;
if (name == "subtools") return double(doc.subtoolCount());
if (name == "active_subtool") return double(doc.activeSubtool);
+ if (name == "extract_preview") return doc.extractPreviewCurrent() ? 1.0 : 0.0;
+ if (name == "open_edges") {
+ std::map<std::pair<uint32_t, uint32_t>, int> edges;
+ for (const auto& t : m.triangles)
+ for (int k = 0; k < 3; ++k) ++edges[{std::min(t[k], t[(k + 1) % 3]), std::max(t[k], t[(k + 1) % 3])}];
+ return double(std::count_if(edges.begin(), edges.end(), [](const auto& e) { return e.second == 1; }));
+ }
if (name == "visible_subtools")
return double(std::count_if(doc.subtools.begin(), doc.subtools.end(), [](const SubTool& s) { return s.visible; }));
if (name == "edited_subtools") { // SubTools with undo history (the active one's lives in doc.undo)
diff --git a/src/core/Commands.cpp b/src/core/Commands.cpp
index 817fa3d2..5af26762 100644
--- a/src/core/Commands.cpp
+++ b/src/core/Commands.cpp
@@ -9,6 +9,7 @@
#include "core/Decimate.h"
#include "core/Dyntopo.h"
#include "core/EnginePresets.h"
+#include "core/ExtractMirror.h"
#include "core/Face.h"
#include "core/ImageTo3D.h"
#include "core/Masking.h"
@@ -740,6 +741,7 @@ CommandRegistry::CommandRegistry() {
add({"undo", "Undo the last action.", {},
[](Document& doc, const Args&) -> CommandResult {
if (!doc.undo.undo(doc.mesh, doc.bvh)) return {false, "Nothing to undo"};
+ if (UndoRecord* r = doc.undo.lastRedo(); r && r->subtool) doc.applySubtoolStep(*r->subtool);
doc.modified = true;
return {true, "Undone"};
}});
@@ -747,6 +749,7 @@ CommandRegistry::CommandRegistry() {
add({"redo", "Redo the last undone action.", {},
[](Document& doc, const Args&) -> CommandResult {
if (!doc.undo.redo(doc.mesh, doc.bvh)) return {false, "Nothing to redo"};
+ if (UndoRecord* r = doc.undo.lastUndo(); r && r->subtool) doc.applySubtoolStep(*r->subtool);
doc.modified = true;
return {true, "Redone"};
}});
@@ -769,6 +772,7 @@ CommandRegistry::CommandRegistry() {
registerDyntopoCommands(*this); // dyntopo (core/DyntopoCommands.cpp)
registerSculptableCommands(*this); // splat_to_mesh, face_guides (core/Sculptable.h)
registerTransformCommands(*this); // transform (core/MeshTransform.h)
+ registerExtractMirrorCommands(*this); // extract, mirror_and_weld, mirror (core/ExtractMirror.h)
registerPerformanceCommands(*this); // perf_info, set_multithreading (core/Benchmark.cpp)
registerPaintCommands(*this); // core/Polypaint.cpp
registerGozCommands(*this); // goz_import/export/send/receive, export_stl (io/GozCommands.cpp)
@@ -792,6 +796,10 @@ CommandResult CommandRegistry::execute(Document& doc, const std::string& name, c
for (const auto& p : cmd->params)
if (p.required && !args.contains(p.name)) return {false, "Missing required argument: " + p.name};
doc.notice.clear();
+ // Extract's preview lasts until Accept or until anything else changes the scene (as in ZBrush); saving or
+ // exporting never writes it.
+ if (doc.extractPreview.id && name.rfind("extract", 0) != 0)
+ doc.dropExtractPreview(!(name.rfind("save", 0) == 0 || name.rfind("export", 0) == 0));
CommandResult r = cmd->run(doc, args);
if (const std::string notice = doc.takeNotice(); !notice.empty() && r.ok) r.message += ". " + notice;
return r;
diff --git a/src/core/Document.cpp b/src/core/Document.cpp
index 114d10a5..a91260c7 100644
--- a/src/core/Document.cpp
+++ b/src/core/Document.cpp
@@ -4,6 +4,7 @@
#include "core/Multires.h"
+#include <algorithm>
#include <cctype>
#include <filesystem>
#include <memory>
@@ -31,6 +32,7 @@ void Document::setMesh(Mesh m, std::string name, BVH* built) {
subtools.back().id = nextSubtoolId_++;
subtools.back().name = name.empty() ? "Sculpt" : std::move(name);
activeSubtool = 0;
+ extractPreview = {};
markClean();
}
@@ -116,6 +118,46 @@ void Document::moveSubtool(int i, int direction) {
modified = true;
}
+int Document::subtoolIndex(uint32_t id) const {
+ for (int i = 0; i < subtoolCount(); ++i)
+ if (subtools[size_t(i)].id == id) return i;
+ return -1;
+}
+
+bool Document::applySubtoolStep(SubtoolStep& step) {
+ if (step.stashed) { // redo: put it back where it was
+ const int at = std::clamp(step.at, 0, subtoolCount());
+ subtools.insert(subtools.begin() + at, std::move(*step.stashed));
+ step.stashed.reset();
+ if (at <= activeSubtool) ++activeSubtool;
+ subtools[size_t(at)].mesh.topologyDirty = true;
+ modified = true;
+ return true;
+ }
+ const int i = subtoolIndex(step.id);
+ if (i < 0 || i == activeSubtool || subtoolCount() <= 1) return false;
+ step.at = i;
+ step.stashed = std::make_unique<SubTool>(std::move(subtools[size_t(i)]));
+ subtools.erase(subtools.begin() + i);
+ if (activeSubtool > i) --activeSubtool;
+ modified = true;
+ return true;
+}
+
+bool Document::extractPreviewCurrent() const {
+ if (!extractPreview.id) return false;
+ const int i = subtoolIndex(extractPreview.id);
+ return i >= 0 && i != activeSubtool && activeSubtoolInfo().id == extractPreview.source &&
+ undo.revision() == extractPreview.revision;
+}
+
+void Document::dropExtractPreview(bool staleOnly) {
+ if (!extractPreview.id || (staleOnly && extractPreviewCurrent())) return;
+ const int i = subtoolIndex(extractPreview.id);
+ extractPreview = {};
+ if (i >= 0) removeSubtool(i);
+}
+
int Document::findSubtool(const std::string& name) const {
for (int i = 0; i < subtoolCount(); ++i)
if (subtools[size_t(i)].name == name) return i;
diff --git a/src/core/Document.h b/src/core/Document.h
index 6bba58ae..9ece67a3 100644
--- a/src/core/Document.h
+++ b/src/core/Document.h
@@ -46,6 +46,21 @@ struct SubTool {
std::vector<QRemeshGuide> qremeshGuides; // QRemesh Guides (core/QRemeshGuides.h)
};
+// An undo step that added SubTool `id` at list position `at` (UndoRecord::subtool): `stashed` holds the SubTool
+// while it's undone.
+struct SubtoolStep {
+ uint32_t id = 0;
+ int at = 0;
+ std::unique_ptr<SubTool> stashed;
+};
+
+// Extract's preview (core/ExtractMirror.h): SubTool `id`, made from the mask of SubTool `source` as it was at
+// that SubTool's undo revision `revision`, shown until Accept turns it into an undoable step. id 0 = none.
+struct ExtractPreview {
+ uint32_t id = 0, source = 0;
+ uint64_t revision = 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.
@@ -129,6 +144,19 @@ struct Document {
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;
+ // Index of the SubTool with this id, or -1.
+ int subtoolIndex(uint32_t id) const;
+ // Undoes or redoes a SubtoolStep: takes the SubTool out of the list into the step, or puts it back. False
+ // when there was nothing to do (the SubTool was deleted since, or it's the active or the last one).
+ bool applySubtoolStep(SubtoolStep& step);
+
+ // The Extract preview waiting for Accept, if any (see ExtractPreview).
+ ExtractPreview extractPreview;
+ // True while the preview SubTool exists, its source is active and unchanged since.
+ bool extractPreviewCurrent() const;
+ // Removes the preview SubTool (if any); `staleOnly`: only when it's no longer current.
+ void dropExtractPreview(bool staleOnly = false);
+
// A name not used by any SubTool yet ("Eye", "Eye 2", ...).
std::string uniqueSubtoolName(const std::string& wanted) const;
// Bounds of every visible SubTool.
diff --git a/src/core/ExtractMirror.cpp b/src/core/ExtractMirror.cpp
new file mode 100644
index 00000000..24c89bd5
--- /dev/null
+++ b/src/core/ExtractMirror.cpp
@@ -0,0 +1,504 @@
+// SculptForge - open source digital sculpting
+// SPDX-License-Identifier: GPL-3.0-or-later
+#include "core/ExtractMirror.h"
+
+#include "core/Commands.h"
+#include "core/Document.h"
+#include "core/PaintLayer.h"
+
+#include <algorithm>
+#include <array>
+#include <cctype>
+#include <cmath>
+#include <unordered_map>
+
+namespace sf {
+
+namespace {
+
+constexpr uint32_t kNone = ~0u;
+
+float largestSide(const Mesh& mesh) {
+ const AABB b = mesh.bounds();
+ if (!b.valid()) return 1.0f;
+ const glm::vec3 e = b.extent();
+ const float s = std::max({e.x, e.y, e.z});
+ return s > 0.0f ? s : 1.0f;
+}
+
+// The directed edges (a, b) of `tris` that no other triangle shares: the open boundary, wound as in the triangles.
+std::vector<std::pair<uint32_t, uint32_t>> boundaryEdges(const std::vector<glm::uvec3>& tris) {
+ std::vector<std::pair<uint64_t, uint32_t>> edges; // undirected key, directed edge index (3 * t + k)
+ edges.reserve(tris.size() * 3);
+ for (uint32_t t = 0; t < tris.size(); ++t)
+ for (uint32_t k = 0; k < 3; ++k) {
+ const uint32_t a = tris[t][k], b = tris[t][(k + 1) % 3];
+ edges.push_back({(uint64_t(std::min(a, b)) << 32) | std::max(a, b), 3 * t + k});
+ }
+ std::sort(edges.begin(), edges.end());
+ std::vector<std::pair<uint32_t, uint32_t>> out;
+ for (size_t i = 0; i < edges.size();) {
+ size_t j = i + 1;
+ while (j < edges.size() && edges[j].first == edges[i].first) ++j;
+ if (j - i == 1) {
+ const uint32_t t = edges[i].second / 3, k = edges[i].second % 3;
+ out.push_back({tris[t][k], tris[t][(k + 1) % 3]});
+ }
+ i = j;
+ }
+ return out;
+}
+
+int axisIndex(char c) { return c == 'x' ? 0 : c == 'y' ? 1 : c == 'z' ? 2 : -1; }
+const char* axisName(int axis) { return axis == 0 ? "X" : axis == 1 ? "Y" : "Z"; }
+
+// "x", "xz", "X, Y": the axes named, in order. False on anything else.
+bool parseAxes(const std::string& text, std::vector<int>& axes) {
+ for (char c : text) {
+ const char l = char(std::tolower(static_cast<unsigned char>(c)));
+ if (l == ',' || l == ' ') continue;
+ const int a = axisIndex(l);
+ if (a < 0) return false;
+ if (std::find(axes.begin(), axes.end(), a) == axes.end()) axes.push_back(a);
+ }
+ return !axes.empty();
+}
+
+} // namespace
+
+Mesh extractShell(const Mesh& mesh, const ExtractOptions& o, std::string& error) {
+ const size_t nv = mesh.vertexCount(), nt = mesh.triangleCount();
+ if (!mesh.zspheres.empty()) {
+ error = "Extract works on meshes; make the ZSpheres a mesh first";
+ return {};
+ }
+ // The patch: the visible triangles whose corners are masked (on average), with their own vertices.
+ std::vector<uint32_t> remap(nv, kNone), kept, patchOf(mesh.hasQuads() ? nt : 0, kNone);
+ std::vector<glm::uvec3> tris;
+ if (mesh.hasMask())
+ for (uint32_t t = 0; t < nt; ++t) {
+ const glm::uvec3 c = mesh.triangles[t];
+ if (mesh.triangleHidden(t) || (mesh.mask[c.x] + mesh.mask[c.y] + mesh.mask[c.z]) < 3.0f * o.threshold) continue;
+ glm::uvec3 nt3;
+ for (int k = 0; k < 3; ++k) {
+ uint32_t& r = remap[c[k]];
+ if (r == kNone) {
+ r = uint32_t(kept.size());
+ kept.push_back(c[k]);
+ }
+ nt3[k] = r;
+ }
+ if (!patchOf.empty()) patchOf[t] = uint32_t(tris.size());
+ tris.push_back(nt3);
+ }
+ if (tris.empty()) {
+ error = "Nothing to extract: mask the part first (Ctrl+drag on the surface)";
+ return {};
+ }
+ const uint32_t np = uint32_t(kept.size());
+ std::vector<glm::vec3> p(np);
+ for (uint32_t i = 0; i < np; ++i) p[i] = mesh.positions[kept[i]];
+
+ // E Smt: Taubin smoothing along the patch's edge, which follows the triangles' staircase, so it doesn't shrink.
+ const auto boundary = boundaryEdges(tris);
+ if (o.smooth > 0 && !boundary.empty()) {
+ std::vector<std::array<uint32_t, 2>> nb(np, {kNone, kNone});
+ std::vector<uint8_t> count(np, 0);
+ for (const auto& [a, b] : boundary)
+ for (const auto& [v, w] : {std::pair{a, b}, std::pair{b, a}}) {
+ if (count[v] < 2) nb[v][count[v]] = w;
+ count[v] = uint8_t(std::min(3, count[v] + 1));
+ }
+ std::vector<uint32_t> chain; // vertices on one simple boundary loop (pinch points stay put)
+ for (uint32_t v = 0; v < np; ++v)
+ if (count[v] == 2) chain.push_back(v);
+ std::vector<glm::vec3> moved(chain.size());
+ for (int it = 0; it < 4 * std::min(o.smooth, 50); ++it) // 4 passes a step: the steps span a few edges
+ for (float f : {0.5f, -0.53f}) {
+ for (size_t i = 0; i < chain.size(); ++i) {
+ const uint32_t v = chain[i];
+ const glm::vec3 mid = (p[nb[v][0]] + p[nb[v][1]]) * 0.5f;
+ moved[i] = p[v] + f * (mid - p[v]);
+ }
+ for (size_t i = 0; i < chain.size(); ++i) p[chain[i]] = moved[i];
+ }
+ }
+
+ Mesh patch;
+ patch.positions = p;
+ patch.triangles = tris;
+ patch.rebuildTopology();
+ patch.recomputeAllNormals();
+
+ const float t = o.thickness * largestSide(mesh);
+ const float outer = o.doubleSided ? std::abs(t) : std::max(t, 0.0f);
+ const float inner = o.doubleSided ? -std::abs(t) : std::min(t, 0.0f);
+ const bool single = outer == inner;
+ const uint32_t layers = single ? 1 : 2;
+ const uint32_t ntp = uint32_t(tris.size());
+
+ Mesh out;
+ out.positions.reserve(size_t(np) * layers);
+ for (uint32_t i = 0; i < np; ++i) out.positions.push_back(p[i] + patch.normals[i] * outer);
+ if (!single)
+ for (uint32_t i = 0; i < np; ++i) out.positions.push_back(p[i] + patch.normals[i] * inner);
+ if (mesh.hasColors()) {
+ out.colors.reserve(out.positions.size());
+ for (uint32_t l = 0; l < layers; ++l)
+ for (uint32_t v : kept) out.colors.push_back(mesh.colors[v]);
+ }
+ out.triangles = tris;
+ out.polygroups.assign(tris.size(), 1u);
+ if (!single) {
+ // The inner surface faces the other way; the rim joins the two along the patch's edge, one quad per edge.
+ for (const glm::uvec3& c : tris) out.triangles.push_back(glm::uvec3(c.x + np, c.z + np, c.y + np));
+ out.polygroups.resize(out.triangles.size(), 2u);
+ for (const auto& [u, v] : boundary) {
+ const uint32_t first = uint32_t(out.triangles.size());
+ out.triangles.push_back(glm::uvec3(v, u, u + np));
+ out.triangles.push_back(glm::uvec3(v, u + np, v + np));
+ out.polygroups.push_back(3u);
+ out.polygroups.push_back(3u);
+ out.pairQuad(first, first + 1);
+ }
+ }
+ // Quads of the source stay quads on both surfaces.
+ for (uint32_t t0 = 0; t0 < patchOf.size(); ++t0) {
+ const uint32_t u0 = mesh.quadPartnerAt(t0);
+ if (patchOf[t0] == kNone || u0 == Mesh::kNoQuad || u0 < t0 || patchOf[u0] == kNone) continue;
+ for (uint32_t l = 0; l < layers; ++l) out.pairQuad(patchOf[t0] + l * ntp, patchOf[u0] + l * ntp);
+ }
+ if (out.hasQuads()) out.quadPartners.resize(out.triangles.size(), Mesh::kNoQuad);
+ out.rebuildTopology();
+ out.recomputeAllNormals();
+ return out;
+}
+
+Mesh mirrorAndWeld(const Mesh& mesh, int axis, bool keepPositive, std::string& error) {
+ const size_t nv = mesh.vertexCount(), nt = mesh.triangleCount();
+ const float sign = keepPositive ? 1.0f : -1.0f;
+ const float size = largestSide(mesh);
+ // Signed distance to the plane on the kept side. Vertices on it (within a hair), and open edges' vertices
+ // close to it (a half model whose seam isn't quite at 0), are welded onto it.
+ std::vector<float> d(nv);
+ for (size_t v = 0; v < nv; ++v) {
+ d[v] = sign * mesh.positions[v][axis];
+ if (std::abs(d[v]) < 1e-5f * size) d[v] = 0.0f;
+ }
+ // (Only vertices near the plane are checked for an open edge, through the mesh's adjacency.)
+ for (uint32_t v = 0; v < nv; ++v) {
+ if (d[v] == 0.0f || std::abs(d[v]) >= 1e-3f * size) continue;
+ const IndexRing around = mesh.vertexTriangles(v);
+ for (uint32_t w : mesh.neighbors(v)) {
+ int shared = 0;
+ for (uint32_t t : around) {
+ const glm::uvec3 c = mesh.triangles[t];
+ shared += c.x == w || c.y == w || c.z == w;
+ }
+ if (shared == 1) {
+ d[v] = 0.0f;
+ break;
+ }
+ }
+ }
+
+ // The kept half: whole triangles on the kept side, and those crossing the plane cut on it.
+ struct Blend {
+ uint32_t a, b;
+ float t;
+ };
+ std::vector<Blend> verts;
+ std::vector<uint32_t> newOf(nv, kNone);
+ std::unordered_map<uint64_t, uint32_t> cuts;
+ auto keepVertex = [&](uint32_t v) {
+ if (newOf[v] == kNone) {
+ newOf[v] = uint32_t(verts.size());
+ verts.push_back({v, v, 0.0f});
+ }
+ return newOf[v];
+ };
+ auto cutVertex = [&](uint32_t a, uint32_t b) {
+ const uint64_t key = (uint64_t(std::min(a, b)) << 32) | std::max(a, b);
+ auto [it, added] = cuts.emplace(key, uint32_t(verts.size()));
+ if (added) verts.push_back({a, b, d[a] / (d[a] - d[b])});
+ return it->second;
+ };
+ struct Tri {
+ glm::uvec3 v;
+ uint32_t source;
+ std::array<glm::vec2, 3> uv;
+ };
+ std::vector<Tri> half;
+ std::vector<uint32_t> intact(mesh.hasQuads() ? nt : 0, kNone); // source triangle -> its uncut copy in `half`
+ const bool uvs = mesh.hasUvs();
+ for (uint32_t t = 0; t < nt; ++t) {
+ const glm::uvec3 c = mesh.triangles[t];
+ const float d0 = d[c.x], d1 = d[c.y], d2 = d[c.z];
+ std::array<glm::vec2, 3> uv{};
+ if (uvs) uv = {mesh.uvs[3 * t], mesh.uvs[3 * t + 1], mesh.uvs[3 * t + 2]};
+ if (d0 >= 0.0f && d1 >= 0.0f && d2 >= 0.0f) {
+ if (d0 == 0.0f && d1 == 0.0f && d2 == 0.0f) continue; // in the plane: the mirror would double it
+ if (!intact.empty()) intact[t] = uint32_t(half.size());
+ half.push_back({glm::uvec3(keepVertex(c.x), keepVertex(c.y), keepVertex(c.z)), t, uv});
+ continue;
+ }
+ if (d0 <= 0.0f && d1 <= 0.0f && d2 <= 0.0f) continue;
+ // Clip to the kept side (a triangle or a quad), then fan it into triangles.
+ std::array<uint32_t, 4> poly;
+ std::array<glm::vec2, 4> polyUv;
+ int n = 0;
+ for (int i = 0; i < 3; ++i) {
+ const int j = (i + 1) % 3;
+ const float di = d[c[i]], dj = d[c[j]];
+ if (di >= 0.0f) {
+ poly[n] = keepVertex(c[i]);
+ polyUv[n++] = uv[i];
+ }
+ if ((di > 0.0f && dj < 0.0f) || (di < 0.0f && dj > 0.0f)) {
+ const float f = di / (di - dj);
+ poly[n] = cutVertex(c[i], c[j]);
+ polyUv[n++] = glm::mix(uv[i], uv[j], f);
+ }
+ }
+ for (int k = 1; k + 1 < n; ++k)
+ half.push_back({glm::uvec3(poly[0], poly[k], poly[k + 1]), t, {polyUv[0], polyUv[k], polyUv[k + 1]}});
+ }
+ if (half.empty()) {
+ error = std::string("Nothing on the ") + (keepPositive ? "+" : "-") + axisName(axis) + " side to mirror";
+ return {};
+ }
+
+ // Vertices on the plane are shared by both halves (the weld); the others get a mirrored twin.
+ const uint32_t nh = uint32_t(verts.size());
+ std::vector<uint8_t> onPlane(nh);
+ std::vector<uint32_t> twin(nh);
+ std::vector<uint32_t> sourceOf; // twin index - nh -> half vertex
+ for (uint32_t k = 0; k < nh; ++k) {
+ onPlane[k] = verts[k].a != verts[k].b || d[verts[k].a] == 0.0f;
+ if (onPlane[k]) {
+ twin[k] = k;
+ } else {
+ twin[k] = nh + uint32_t(sourceOf.size());
+ sourceOf.push_back(k);
+ }
+ }
+ const size_t total = nh + sourceOf.size();
+ auto lerp3 = [&](const std::vector<glm::vec3>& src, const Blend& b) { return glm::mix(src[b.a], src[b.b], b.t); };
+ auto flip = [&](glm::vec3 v) {
+ v[axis] = -v[axis];
+ return v;
+ };
+ // A vec3 per vertex: positions, the layer base and offsets. On the plane the axis component is exactly 0.
+ auto vectorAttribute = [&](const std::vector<glm::vec3>& src, std::vector<glm::vec3>& dst) {
+ dst.resize(total);
+ for (uint32_t k = 0; k < nh; ++k) {
+ dst[k] = lerp3(src, verts[k]);
+ if (onPlane[k]) dst[k][axis] = 0.0f;
+ }
+ for (size_t i = 0; i < sourceOf.size(); ++i) dst[nh + i] = flip(dst[sourceOf[i]]);
+ };
+ // Anything else per vertex is interpolated and copied to the twin.
+ auto scalarAttribute = [&](const auto& src, auto& dst) {
+ dst.resize(total);
+ for (uint32_t k = 0; k < nh; ++k) dst[k] = src[verts[k].a] + (src[verts[k].b] - src[verts[k].a]) * verts[k].t;
+ for (size_t i = 0; i < sourceOf.size(); ++i) dst[nh + i] = dst[sourceOf[i]];
+ };
+
+ Mesh out;
+ vectorAttribute(mesh.positions, out.positions);
+ if (!mesh.layers.empty()) {
+ vectorAttribute(mesh.base, out.base);
+ for (const SculptLayer& l : mesh.layers) {
+ out.layers.push_back({l.name, {}, l.weight});
+ vectorAttribute(l.delta, out.layers.back().delta);
+ }
+ }
+ if (mesh.hasMask()) scalarAttribute(mesh.mask, out.mask);
+ if (mesh.hasColors()) scalarAttribute(mesh.colors, out.colors);
+ if (!mesh.paintLayers.empty() && mesh.paintBase.size() == nv) {
+ scalarAttribute(mesh.paintBase, out.paintBase);
+ for (const PaintLayer& l : mesh.paintLayers) {
+ PaintLayer nl = l;
+ scalarAttribute(l.color, nl.color);
+ scalarAttribute(l.alpha, nl.alpha);
+ out.paintLayers.push_back(std::move(nl));
+ }
+ out.activePaintLayer = mesh.activePaintLayer;
+ }
+ if (uvs) { // the texture fits both halves (the mirrored one reuses the UVs)
+ out.texture = mesh.texture;
+ out.paintToTexture = mesh.paintToTexture;
+ }
+
+ std::vector<uint32_t> mirrored(half.size(), kNone);
+ auto addTriangle = [&](const glm::uvec3& v, uint32_t source, const std::array<glm::vec2, 3>& uv) {
+ out.triangles.push_back(v);
+ if (mesh.hasPolygroups()) out.polygroups.push_back(mesh.polygroups[source]);
+ if (mesh.hasHidden()) out.hidden.push_back(mesh.hidden[source]);
+ if (uvs) out.uvs.insert(out.uvs.end(), uv.begin(), uv.end());
+ };
+ for (const Tri& t : half) addTriangle(t.v, t.source, t.uv);
+ for (size_t i = 0; i < half.size(); ++i) {
+ const Tri& t = half[i];
+ if (onPlane[t.v.x] && onPlane[t.v.y] && onPlane[t.v.z]) continue;
+ mirrored[i] = uint32_t(out.triangles.size());
+ addTriangle(glm::uvec3(twin[t.v.x], twin[t.v.z], twin[t.v.y]), t.source, {t.uv[0], t.uv[2], t.uv[1]});
+ }
+ for (uint32_t t = 0; t < intact.size(); ++t) {
+ const uint32_t u = mesh.quadPartners[t];
+ if (intact[t] == kNone || u >= nt || u < t || intact[u] == kNone) continue;
+ out.pairQuad(intact[t], intact[u]);
+ if (mirrored[intact[t]] != kNone && mirrored[intact[u]] != kNone)
+ out.pairQuad(mirrored[intact[t]], mirrored[intact[u]]);
+ }
+ if (out.hasQuads()) out.quadPartners.resize(out.triangles.size(), Mesh::kNoQuad);
+ out.rebuildTopology();
+ if (!out.layers.empty()) out.evaluateAll();
+ if (!out.paintLayers.empty()) compositePaintAll(out);
+ out.recomputeAllNormals();
+ return out;
+}
+
+Mesh mirrorFlip(const Mesh& mesh, int axis, float pivot) {
+ Mesh out = mesh;
+ out.multires.reset(); // the other levels aren't flipped
+ for (auto& p : out.positions) p[axis] = 2.0f * pivot - p[axis];
+ for (auto& p : out.base) p[axis] = 2.0f * pivot - p[axis];
+ for (auto& l : out.layers)
+ for (auto& v : l.delta) v[axis] = -v[axis];
+ for (auto& z : out.zspheres) z.center[axis] = 2.0f * pivot - z.center[axis];
+ for (auto& t : out.triangles) std::swap(t.y, t.z);
+ for (size_t t = 0; t * 3 + 2 < out.uvs.size(); ++t) std::swap(out.uvs[3 * t + 1], out.uvs[3 * t + 2]);
+ out.rebuildTopology();
+ out.recomputeAllNormals();
+ return out;
+}
+
+namespace {
+
+using T = ParamSpec::Type;
+
+std::string triangles(size_t n) { return std::to_string(n) + " triangles"; }
+
+CommandResult acceptPreview(Document& doc) {
+ if (!doc.extractPreviewCurrent()) {
+ doc.dropExtractPreview();
+ return {false, "Nothing to accept: press Extract first"};
+ }
+ const int i = doc.subtoolIndex(doc.extractPreview.id);
+ UndoRecord r;
+ r.label = "Extract";
+ r.subtool = std::make_shared<SubtoolStep>();
+ r.subtool->id = doc.extractPreview.id;
+ r.subtool->at = i;
+ doc.undo.push(std::move(r));
+ doc.extractPreview = {};
+ doc.modified = true;
+ return {true, "Extracted " + doc.subtools[size_t(i)].name + " (" + triangles(doc.subtoolMesh(i).triangleCount()) + ")"};
+}
+
+CommandResult runExtract(Document& doc, const Args& a) {
+ ExtractOptions o;
+ o.thickness = std::clamp(float(argNumber(a, "thickness", o.thickness)), -1.0f, 1.0f);
+ o.smooth = std::clamp(int(std::lround(argNumber(a, "smooth", o.smooth))), 0, 50);
+ o.doubleSided = argBool(a, "double", false);
+ std::string error;
+ Mesh shell = extractShell(doc.mesh, o, error);
+ if (shell.triangleCount() == 0) {
+ doc.dropExtractPreview();
+ return {false, error};
+ }
+ const size_t tris = shell.triangleCount();
+ doc.dropExtractPreview(true);
+ if (doc.extractPreview.id) { // Extract again (other settings): the preview is replaced
+ SubTool& s = doc.subtools[size_t(doc.subtoolIndex(doc.extractPreview.id))];
+ s.mesh = std::move(shell);
+ s.mesh.topologyDirty = true;
+ s.bvh.build(s.mesh);
+ s.bvhDirty = false;
+ } else {
+ const int i = doc.addSubtool(std::move(shell), "Extract", false, doc.activeSubtool + 1);
+ doc.extractPreview = {doc.subtools[size_t(i)].id, doc.activeSubtoolInfo().id, doc.undo.revision()};
+ }
+ if (argBool(a, "accept", false)) return acceptPreview(doc);
+ return {true, "Extract preview (" + triangles(tris) + "): Accept keeps it as a new SubTool"};
+}
+
+} // namespace
+
+void registerExtractMirrorCommands(CommandRegistry& reg) {
+ reg.add({"extract",
+ "ZBrush Extract (Tool > SubTool): make a shell from the masked, visible part of the active SubTool and "
+ "show it as a preview below it; extract_accept (or accept=true) keeps it as a new SubTool in one undo "
+ "step. Running it again replaces the preview.",
+ {{"thickness", T::Number,
+ "Thick: shell thickness as a fraction of the SubTool's largest side (default 0.015; negative grows "
+ "inward; 0 = a single-sided surface).",
+ false},
+ {"smooth", T::Number, "E Smt: smoothing passes along the extracted edge (0-50, default 5).", false},
+ {"double", T::Bool, "Double: grow the shell both inward and outward (default false).", false},
+ {"accept", T::Bool, "Accept at once instead of leaving a preview (default false).", false}},
+ runExtract});
+ reg.add({"extract_accept", "Keep the Extract preview as a new SubTool (undo removes it again).", {},
+ [](Document& doc, const Args&) { return acceptPreview(doc); }});
+ reg.add({"extract_cancel", "Remove the Extract preview.", {},
+ [](Document& doc, const Args&) -> CommandResult {
+ if (!doc.extractPreview.id) return {false, "There's no Extract preview"};
+ doc.dropExtractPreview();
+ return {true, "Extract cancelled"};
+ }});
+
+ reg.add({"mirror_and_weld",
+ "ZBrush Mirror And Weld (Tool > Geometry > Modify Topology): keep the half of the active SubTool on the "
+ "+ side of the plane through the origin, mirror it onto the other side and weld the seam into one "
+ "watertight mesh. Polygroups, polypaint, mask, UVs and sculpt layers are kept. One undo step.",
+ {{"axis", T::String, "Axis whose plane to mirror across: x (default), y or z; several (xz) in turn.", false},
+ {"side", T::String, "The side kept: positive (default) or negative.", false}},
+ [](Document& doc, const Args& a) -> CommandResult {
+ std::vector<int> axes;
+ if (!parseAxes(argString(a, "axis", "x"), axes)) return {false, "Bad axis (expected x, y, z or e.g. xz)"};
+ const std::string side = argString(a, "side", "positive");
+ const bool positive = side == "positive" || side == "+" || side == "pos";
+ if (!positive && side != "negative" && side != "-" && side != "neg")
+ return {false, "Bad side '" + side + "' (positive or negative)"};
+ if (!doc.mesh.zspheres.empty()) return {false, "Mirror And Weld works on meshes; make the ZSpheres a mesh first"};
+ if (doc.mesh.triangleCount() == 0) return {false, "The SubTool is empty"};
+ const size_t before = doc.mesh.triangleCount();
+ Mesh m = doc.mesh;
+ std::string names;
+ for (int axis : axes) {
+ std::string error;
+ m = mirrorAndWeld(m, axis, positive, error);
+ if (m.triangleCount() == 0) return {false, error};
+ names += axisName(axis);
+ }
+ const size_t after = m.triangleCount();
+ doc.replaceMeshUndoable(std::move(m), "Mirror And Weld");
+ return {true, "Mirror And Weld " + names + ": " + triangles(before) + " -> " + triangles(after)};
+ }});
+
+ reg.add({"mirror",
+ "ZBrush Mirror (Tool > Deformation): flip the active SubTool across a plane, by default the one through "
+ "the origin that symmetry and Mirror And Weld use. One undo step.",
+ {{"axis", T::String, "Axis to flip along: x (default), y or z; several (xz) in turn.", false},
+ {"pivot", T::String, "origin (default) or center (flip in place about the SubTool's centre).", false}},
+ [](Document& doc, const Args& a) -> CommandResult {
+ std::vector<int> axes;
+ if (!parseAxes(argString(a, "axis", "x"), axes)) return {false, "Bad axis (expected x, y, z or e.g. xz)"};
+ const std::string pivot = argString(a, "pivot", "origin");
+ const bool center = pivot == "center" || pivot == "centre";
+ if (!center && pivot != "origin") return {false, "Bad pivot '" + pivot + "' (origin or center)"};
+ if (doc.mesh.vertexCount() == 0) return {false, "The SubTool is empty"};
+ const glm::vec3 c = doc.mesh.bounds().center();
+ Mesh m = doc.mesh;
+ std::string names;
+ for (int axis : axes) {
+ m = mirrorFlip(m, axis, center ? c[axis] : 0.0f);
+ names += axisName(axis);
+ }
+ doc.replaceMeshUndoable(std::move(m), "Mirror");
+ return {true, "Mirrored across " + names + (center ? " (about its centre)" : "")};
+ }});
+}
+
+} // namespace sf
diff --git a/src/core/ExtractMirror.h b/src/core/ExtractMirror.h
new file mode 100644
index 00000000..5decbd60
--- /dev/null
+++ b/src/core/ExtractMirror.h
@@ -0,0 +1,45 @@
+// SculptForge - open source digital sculpting
+// SPDX-License-Identifier: GPL-3.0-or-later
+//
+// Two ZBrush mesh tools:
+// - Extract (Tool > SubTool > Extract): the masked part of a SubTool becomes a new SubTool, a shell with a
+// thickness (a helmet, a strap, a piece of clothing). Extract shows it as a preview; Accept keeps it as an
+// undoable step. Thick is a fraction of the SubTool's size (negative = inward), E Smt smooths the jagged edge
+// the mask's triangles leave, Double grows the shell both ways; Thick 0 gives a single-sided surface.
+// - Mirror And Weld (Tool > Geometry > Modify Topology): the half on the + side of a plane through the origin
+// is kept and mirrored onto the - side, and the seam welded into one watertight mesh. Triangles crossing the
+// plane are cut on it; polygroups, polypaint, mask, UVs and sculpt layers are carried over.
+// - Mirror (Tool > Deformation): flips the SubTool across a plane (normals stay outward).
+#pragma once
+
+#include "core/Mesh.h"
+
+#include <string>
+
+namespace sf {
+
+class CommandRegistry;
+
+struct ExtractOptions {
+ float thickness = 0.015f; // fraction of the SubTool's largest side; < 0 grows inward, 0 = a single surface
+ int smooth = 5; // E Smt: smoothing passes along the edge of the extracted part (0-50)
+ bool doubleSided = false; // Double: the shell grows both ways from the surface by the thickness
+ float threshold = 0.5f; // a triangle is extracted when its corners' mean mask reaches this
+};
+
+// The shell made from the masked, visible triangles of `mesh`: the outer surface (polygroup 1), the inner one
+// (polygroup 2) and the rim joining them (polygroup 3, quads), with the polypaint of the source. A single
+// surface (polygroup 1) when the thickness is 0. Empty (with `error`) when nothing is masked.
+Mesh extractShell(const Mesh& mesh, const ExtractOptions& options, std::string& error);
+
+// Mirror And Weld across the plane `axis` = 0 (X), 1 (Y) or 2 (Z) through the origin, keeping the + side (or
+// the - side when !keepPositive). Empty (with `error`) when nothing is on the kept side.
+Mesh mirrorAndWeld(const Mesh& mesh, int axis, bool keepPositive, std::string& error);
+
+// The mesh flipped across the plane `axis` through `pivot` (winding reversed, so it stays outward-facing).
+Mesh mirrorFlip(const Mesh& mesh, int axis, float pivot);
+
+// extract, extract_accept, extract_cancel, mirror_and_weld, mirror.
+void registerExtractMirrorCommands(CommandRegistry& registry);
+
+} // namespace sf
diff --git a/src/core/Undo.h b/src/core/Undo.h
index 861b2d7c..2f3e4de0 100644
--- a/src/core/Undo.h
+++ b/src/core/Undo.h
@@ -89,6 +89,10 @@ struct TextureStackUndo {
size_t bytes() const;
};
+// Adding or removing a whole SubTool (Extract's Accept; core/Document.h). Applied by the undo / redo commands,
+// which see the whole scene: the record itself leaves the mesh alone.
+struct SubtoolStep;
+
// "The active paint layer" for UndoRecord::captureColors.
inline constexpr int kActivePaintLayer = -2;
@@ -105,6 +109,7 @@ inline constexpr int kActivePaintLayer = -2;
// - textureTiles / texture: texture-paint tiles of one layer, or the whole texture
// - subdiv: a subdivision level step or level edit (core/Multires.h), applied on its own
// - topology: the slots a dynamic-topology stroke changed (core/Dyntopo.h), applied before the channels
+// - subtool: a SubTool added to the scene (Extract), taken out on undo and put back on redo
// Record old values before changing them (ensureX() the attribute first);
// undo allocates a missing attribute so values can always be restored.
struct UndoRecord {
@@ -126,10 +131,11 @@ struct UndoRecord {
std::unique_ptr<Mesh> mesh;
std::unique_ptr<SubdivUndo> subdiv;
std::unique_ptr<TopologyUndo> topology;
+ std::shared_ptr<SubtoolStep> subtool; // (shared: SubtoolStep is defined in core/Document.h)
bool empty() const {
return positions.empty() && mask.empty() && colors.empty() && paintAlpha.empty() && hidden.empty() &&
- polygroups.empty() && !mesh && !paint && !textureTiles && !texture && !subdiv && !topology;
+ polygroups.empty() && !mesh && !paint && !textureTiles && !texture && !subdiv && !topology && !subtool;
}
size_t approxBytes() const;
@@ -156,6 +162,9 @@ public:
const std::string& undoLabel() const { return undo_.back().label; }
const std::string& redoLabel() const { return redo_.back().label; }
size_t undoCount() const { return undo_.size(); }
+ // The step the next undo / redo applies (null if none): after undo() the undone step is lastRedo().
+ UndoRecord* lastUndo() { return undo_.empty() ? nullptr : &undo_.back(); }
+ UndoRecord* lastRedo() { return redo_.empty() ? nullptr : &redo_.back(); }
// Both rebuild/refit the BVH as needed.
bool undo(Mesh& mesh, BVH& bvh);
diff --git a/tests/test_extract_mirror.cpp b/tests/test_extract_mirror.cpp
new file mode 100644
index 00000000..6d40b0c9
--- /dev/null
+++ b/tests/test_extract_mirror.cpp
@@ -0,0 +1,252 @@
+// SculptForge - open source digital sculpting
+// SPDX-License-Identifier: GPL-3.0-or-later
+//
+// Extract (a shell from the mask, preview + Accept, undo), Mirror And Weld and Mirror (core/ExtractMirror.h).
+#include "TestHarness.h"
+
+#include "core/Commands.h"
+#include "core/ExtractMirror.h"
+#include "core/Polygroups.h"
+#include "core/Primitives.h"
+
+#include <algorithm>
+#include <cmath>
+#include <map>
+#include <set>
+
+using namespace sf;
+
+namespace {
+
+// Every edge shared by exactly two triangles, wound oppositely: closed and consistently oriented.
+bool watertight(const Mesh& m) {
+ std::map<std::pair<uint32_t, uint32_t>, int> directed;
+ for (const auto& t : m.triangles)
+ for (int k = 0; k < 3; ++k) ++directed[{t[k], t[(k + 1) % 3]}];
+ for (const auto& [e, n] : directed) {
+ if (n != 1) return false;
+ auto it = directed.find({e.second, e.first});
+ if (it == directed.end() || it->second != 1) return false;
+ }
+ return !m.triangles.empty();
+}
+
+// Six times the enclosed volume: positive when the triangles face outward.
+double signedVolume(const Mesh& m) {
+ double v = 0.0;
+ for (const auto& t : m.triangles)
+ v += double(glm::dot(m.positions[t.x], glm::cross(m.positions[t.y], m.positions[t.z])));
+ return v;
+}
+
+std::set<uint32_t> groups(const Mesh& m) {
+ std::set<uint32_t> ids;
+ for (uint32_t t = 0; t < m.triangleCount(); ++t) ids.insert(m.polygroupAt(t));
+ return ids;
+}
+
+// A sphere with its top (y > 0.5) masked and painted red.
+void maskedSphere(Document& doc, CommandRegistry& reg) {
+ CHECK(reg.execute(doc, "new_sphere", {{"subdivisions", 4.0}}).ok);
+ doc.mesh.ensureMask();
+ doc.mesh.ensureColors(glm::vec3(1.0f));
+ for (uint32_t v = 0; v < doc.mesh.vertexCount(); ++v)
+ if (doc.mesh.positions[v].y > 0.5f) {
+ doc.mesh.mask[v] = 1.0f;
+ doc.mesh.colors[v] = glm::vec3(1, 0, 0);
+ }
+}
+
+} // namespace
+
+TEST(extract_shell_preview_accept_undo) {
+ Document doc;
+ CommandRegistry reg;
+ CHECK(reg.execute(doc, "new_sphere", {{"subdivisions", 3.0}}).ok);
+ CHECK(!reg.execute(doc, "extract").ok); // nothing masked
+ CHECK(doc.subtoolCount() == 1);
+
+ maskedSphere(doc, reg);
+ const float radius = glm::length(doc.mesh.positions[0]);
+ const CommandResult r = reg.execute(doc, "extract");
+ CHECK(r.ok);
+ CHECK(r.message.find("preview") != std::string::npos);
+ CHECK(doc.subtoolCount() == 2 && doc.activeSubtool == 0); // the preview sits below; the source stays active
+ CHECK(doc.extractPreview.id != 0 && doc.extractPreviewCurrent());
+ CHECK(!doc.undo.canUndo()); // a preview isn't a step yet
+ const Mesh& shell = doc.subtoolMesh(1);
+ CHECK(doc.subtools[1].name == "Extract");
+ CHECK(watertight(shell));
+ CHECK(signedVolume(shell) > 0.0);
+ CHECK((groups(shell) == std::set<uint32_t>{1, 2, 3})); // outer, inner, rim
+ CHECK(shell.hasQuads()); // the rim
+ CHECK(!shell.hasMask());
+ // Thick 0.015 of the sphere's size (its side is 2 * radius) outward; the inner surface is the sphere's.
+ float rmax = 0.0f, rmin = 1e9f;
+ for (const auto& p : shell.positions) {
+ rmax = std::max(rmax, glm::length(p));
+ rmin = std::min(rmin, glm::length(p));
+ }
+ CHECK(std::abs(rmax - radius * (1.0f + 0.03f)) < radius * 0.01f);
+ CHECK(rmin > radius * 0.97f); // (E Smt pulls the edge in a little)
+ // Polypaint comes along.
+ CHECK(shell.hasColors() && shell.colors[0] == glm::vec3(1, 0, 0));
+
+ // Extract again with other settings: the preview is replaced, not added to.
+ const uint32_t previewId = doc.extractPreview.id;
+ CHECK(reg.execute(doc, "extract", {{"thickness", 0.05}, {"double", true}, {"smooth", 0.0}}).ok);
+ CHECK(doc.subtoolCount() == 2 && doc.extractPreview.id == previewId);
+ rmin = 1e9f;
+ for (const auto& p : doc.subtoolMesh(1).positions) rmin = std::min(rmin, glm::length(p));
+ CHECK(rmin < radius * 0.95f); // Double grows inward too
+
+ // Accept: one undo step on the source that takes the SubTool away and redo brings it back.
+ CHECK(reg.execute(doc, "extract_accept").ok);
+ CHECK(doc.extractPreview.id == 0 && doc.subtoolCount() == 2);
+ CHECK(doc.undo.canUndo() && doc.undo.undoLabel() == "Extract");
+ CHECK(!reg.execute(doc, "extract_accept").ok);
+ CHECK(reg.execute(doc, "undo").ok);
+ CHECK(doc.subtoolCount() == 1 && doc.activeSubtool == 0);
+ CHECK(reg.execute(doc, "redo").ok);
+ CHECK(doc.subtoolCount() == 2 && doc.subtools[1].id == previewId && doc.subtoolMesh(1).triangleCount() > 0);
+ CHECK(doc.dirty());
+
+ // A single-sided surface: Thick 0.
+ CHECK(reg.execute(doc, "extract", {{"thickness", 0.0}, {"accept", true}}).ok);
+ CHECK(doc.subtoolCount() == 3);
+ const Mesh& surface = doc.subtoolMesh(1); // right below the source
+ CHECK(!watertight(surface) && groups(surface) == std::set<uint32_t>{1});
+}
+
+TEST(extract_preview_goes_when_the_scene_changes) {
+ Document doc;
+ CommandRegistry reg;
+ maskedSphere(doc, reg);
+ CHECK(reg.execute(doc, "extract").ok && doc.subtoolCount() == 2);
+ CHECK(reg.execute(doc, "subtool_list").ok); // reading the scene leaves it
+ CHECK(doc.subtoolCount() == 2);
+ CHECK(reg.execute(doc, "extract_cancel").ok);
+ CHECK(doc.subtoolCount() == 1 && doc.extractPreview.id == 0);
+
+ CHECK(reg.execute(doc, "extract").ok);
+ CHECK(reg.execute(doc, "mask_invert").ok); // an edit of the source: the preview no longer matches
+ CHECK(reg.execute(doc, "subtool_list").ok);
+ CHECK(doc.subtoolCount() == 1 && doc.extractPreview.id == 0);
+
+ // Saving never writes a preview.
+ CHECK(reg.execute(doc, "extract").ok && doc.subtoolCount() == 2);
+ const std::string path = tempPath("sf_extract_preview.sfproj");
+ CHECK(reg.execute(doc, "save_project", {{"path", path}}).ok);
+ CHECK(doc.subtoolCount() == 1);
+ Document back;
+ CHECK(reg.execute(back, "open", {{"path", path}}).ok);
+ CHECK(back.subtoolCount() == 1);
+}
+
+TEST(mirror_and_weld_sphere) {
+ Document doc;
+ CommandRegistry reg;
+ maskedSphere(doc, reg);
+ // Off-centre, so the plane cuts triangles; groups 7 on +x, 9 elsewhere.
+ for (auto& p : doc.mesh.positions) p.x += 0.3f;
+ doc.mesh.ensurePolygroups(9);
+ for (uint32_t t = 0; t < doc.mesh.triangleCount(); ++t)
+ if (doc.mesh.positions[doc.mesh.triangles[t].x].x > 0.8f) doc.mesh.polygroups[t] = 7;
+ doc.mesh.recomputeAllNormals();
+ const size_t before = doc.mesh.triangleCount();
+
+ const CommandResult r = reg.execute(doc, "mirror_and_weld", {{"axis", std::string("x")}});
+ CHECK(r.ok);
+ const Mesh& m = doc.mesh;
+ CHECK(watertight(m));
+ CHECK(signedVolume(m) > 0.0);
+ const AABB b = m.bounds();
+ CHECK(std::abs(b.min.x + b.max.x) < 1e-5f);
+ CHECK((groups(m) == std::set<uint32_t>{7, 9}));
+ size_t red = 0;
+ for (const auto& c : m.colors) red += c == glm::vec3(1, 0, 0);
+ CHECK(red > 0 && m.hasMask() && m.mask.size() == m.vertexCount());
+ // Every vertex has its mirror image.
+ std::set<std::tuple<long, long, long>> keys;
+ auto key = [](const glm::vec3& p) { return std::tuple<long, long, long>(std::lround(p.x * 1e4f), std::lround(p.y * 1e4f), std::lround(p.z * 1e4f)); };
+ for (const auto& p : m.positions) keys.insert(key(p));
+ size_t missing = 0;
+ for (const auto& p : m.positions) missing += !keys.count(key(glm::vec3(-p.x, p.y, p.z)));
+ CHECK(missing == 0);
+
+ CHECK(doc.undo.undoLabel() == "Mirror And Weld");
+ CHECK(reg.execute(doc, "undo").ok);
+ CHECK(doc.mesh.triangleCount() == before);
+
+ // The other side, and bad arguments.
+ CHECK(reg.execute(doc, "mirror_and_weld", {{"side", std::string("negative")}}).ok);
+ CHECK(watertight(doc.mesh) && doc.mesh.bounds().max.x < 1.0f); // the smaller, -x side
+ CHECK(!reg.execute(doc, "mirror_and_weld", {{"axis", std::string("w")}}).ok);
+ for (auto& p : doc.mesh.positions) p.x += 5.0f; // all on +x
+ CHECK(!reg.execute(doc, "mirror_and_weld", {{"side", std::string("negative")}}).ok);
+}
+
+TEST(mirror_and_weld_keeps_quads_and_layers) {
+ // A cube whose grid lines lie on the planes: nothing is cut, so every quad and group survives exactly.
+ Mesh cube = makeCube(4, 2.0f);
+ const size_t quads = cube.quadCount();
+ cube.base = cube.positions;
+ cube.layers.push_back({"Bump", {}, 0.5f}); // an inflate: symmetric, so the planes still fall on grid lines
+ for (const auto& p : cube.positions) cube.layers[0].delta.push_back(0.1f * p);
+ cube.evaluateAll();
+ std::string error;
+ for (int axis = 0; axis < 3; ++axis) {
+ Mesh m = mirrorAndWeld(cube, axis, axis != 1, error);
+ CHECK(watertight(m));
+ CHECK(m.triangleCount() == cube.triangleCount() && m.vertexCount() == cube.vertexCount());
+ CHECK(m.quadCount() == quads);
+ CHECK(groups(m).size() == 5); // the far side takes the mirrored side's group
+ CHECK(m.layers.size() == 1 && m.layers[0].name == "Bump");
+ for (size_t v = 0; v < m.vertexCount(); ++v)
+ CHECK(glm::length(m.positions[v] - (m.base[v] + 0.5f * m.layers[0].delta[v])) < 1e-5f);
+ }
+ // Both meshes in X: welding gives back as many vertices as the halves share.
+ Mesh twice = mirrorAndWeld(mirrorAndWeld(cube, 0, true, error), 2, true, error);
+ CHECK(watertight(twice) && twice.vertexCount() == cube.vertexCount());
+}
+
+TEST(mirror_and_weld_closes_a_half_model) {
+ // The +x half of a cube, open along x = 0 and pushed a hair (0.05% of its size) off the plane, as a half model
+ // from another app might be: the open edge is welded onto the plane, so the result is closed.
+ Mesh cube = makeCube(4, 2.0f);
+ std::vector<uint8_t> keep(cube.triangleCount());
+ for (uint32_t t = 0; t < keep.size(); ++t) {
+ const glm::uvec3 c = cube.triangles[t];
+ keep[t] = cube.positions[c.x].x >= 0.0f && cube.positions[c.y].x >= 0.0f && cube.positions[c.z].x >= 0.0f;
+ }
+ Mesh half = extractTriangles(cube, keep);
+ for (auto& p : half.positions) p.x += 0.001f;
+ half.rebuildTopology();
+ CHECK(!watertight(half));
+ std::string error;
+ const Mesh whole = mirrorAndWeld(half, 0, true, error);
+ CHECK(watertight(whole));
+ CHECK(whole.triangleCount() == 2 * half.triangleCount());
+ CHECK(whole.vertexCount() == cube.vertexCount());
+}
+
+TEST(mirror_flip) {
+ Document doc;
+ CommandRegistry reg;
+ CHECK(reg.execute(doc, "new_sphere", {{"subdivisions", 3.0}}).ok);
+ for (auto& p : doc.mesh.positions) p += glm::vec3(0.5f, 0.0f, 0.0f);
+ doc.mesh.recomputeAllNormals();
+ const AABB before = doc.mesh.bounds();
+ const double volume = signedVolume(doc.mesh);
+ CHECK(reg.execute(doc, "mirror").ok);
+ AABB after = doc.mesh.bounds();
+ CHECK(std::abs(after.min.x + before.max.x) < 1e-5f && std::abs(after.max.x + before.min.x) < 1e-5f);
+ CHECK(std::abs(signedVolume(doc.mesh) - volume) < std::abs(volume) * 1e-4); // still outward
+ CHECK(doc.undo.undoLabel() == "Mirror");
+ CHECK(reg.execute(doc, "mirror", {{"pivot", std::string("center")}, {"axis", std::string("yz")}}).ok);
+ after = doc.mesh.bounds();
+ CHECK(std::abs(after.center().y - before.center().y) < 1e-5f);
+ CHECK(reg.execute(doc, "undo").ok && reg.execute(doc, "undo").ok);
+ CHECK(std::abs(doc.mesh.bounds().min.x - before.min.x) < 1e-6f);
+ CHECK(!reg.execute(doc, "mirror", {{"pivot", std::string("somewhere")}}).ok);
+}
diff --git a/tests/ui/extract_mirror.sfui b/tests/ui/extract_mirror.sfui
new file mode 100644
index 00000000..ed00bc9f
--- /dev/null
+++ b/tests/ui/extract_mirror.sfui
@@ -0,0 +1,93 @@
+# Extract (Tool > SubTool > Extract: preview, then Accept), Mirror And Weld (Tool > Geometry > Modify Topology)
+# and Mirror (Tool > Deformation), as in ZBrush; askNK's 0.9.5 review wishlist.
+
+# --- Extract: a cap from the masked top of a sphere.
+run new_sphere subdivisions=4
+run mask_rect y0=0.3
+expect_value masked > 0
+expect "Extract/Extract"
+expect "Extract/Accept"
+camera 25 25
+key f
+click "Extract/Extract"
+expect_status "Extract preview"
+expect_value subtools == 2
+expect_value active_subtool == 0
+expect_value extract_preview == 1
+shot extract-preview
+
+# The settings follow the preview: Double grows it both ways (still one preview).
+click "Extract/Double"
+expect_value subtools == 2
+expect_value extract_preview == 1
+shot extract-palette
+
+# Accept keeps it as a SubTool below the source; the source stays active.
+click "Extract/Accept"
+expect_status "Extracted Extract"
+expect_value extract_preview == 0
+expect_value subtools == 2
+expect_value can_undo == 1
+run mask_clear
+shot extract-accepted
+
+# The shell is closed: outer, inner and rim polygroups.
+run subtool_select index=1
+expect_value open_edges == 0
+expect_value groups == 3
+run subtool_select index=0
+
+# Ctrl+Z takes the extracted SubTool away again (after the mask_clear), redo brings it back.
+key ctrl+z
+key ctrl+z
+expect_value subtools == 1
+key ctrl+shift+z
+expect_value subtools == 2
+
+# A preview that isn't accepted goes when the source changes.
+click "Extract/Extract"
+expect_value subtools == 3
+run mask_invert
+wait_idle 5
+expect_value subtools == 2
+expect_value extract_preview == 0
+
+# --- Mirror And Weld: an off-centre sphere comes back symmetric and closed.
+run new_sphere subdivisions=4
+run transform translate=0.4,0,0 masked=0
+expect_value open_edges == 0
+wait 0.2
+click "Geometry##tool.geometry"
+expect "Modify Topology/Mirror And Weld"
+click "Modify Topology/Mirror And Weld"
+expect_status "Mirror And Weld X"
+expect_value open_edges == 0
+expect_value can_undo == 1
+camera 0 0
+key f
+shot mirror-weld-sphere
+
+# A head sculpted on one side only (a scar and a brow ridge on its right): Mirror And Weld gives the left side the same.
+run new_head
+run stroke points="0.035,0.005,0.2 0.06,-0.03,0.2 0.07,-0.07,0.2" brush=Standard radius=0.012 strength=1
+run stroke points="0.015,0.105,0.2 0.04,0.1,0.2 0.065,0.085,0.2" brush=Standard radius=0.014 strength=1
+camera 0 0
+key f
+shot head-before
+click "Modify Topology/Mirror And Weld"
+expect_status "Mirror And Weld X"
+shot head-mirror-weld
+click "Geometry##tool.geometry"
+
+# --- Deformation > Mirror flips it (undoable); the axis toggles pick the axes.
+click "Deformation##tool.deformation"
+expect "Deformation/Mirror"
+click "Deformation/Mirror"
+expect_status "Mirrored across X"
+shot deformation-palette
+click "Deformation/Y"
+click "Deformation/Mirror"
+expect_status "Mirrored across XY"
+key ctrl+z
+key ctrl+z
+expect_value can_undo == 1
diff --git a/tests/ui/whats_new.sfui b/tests/ui/whats_new.sfui
index f11b447f..b22b4ffc 100644
--- a/tests/ui/whats_new.sfui
+++ b/tests/ui/whats_new.sfui
@@ -4,10 +4,10 @@ click "Help##palette.help"
click "What's New##help.whats_new"
expect_value guide_open == 1
expect_guide whats-new.md
+expect_text "Next version"
+expect_text "Extract"
+expect_text "Mirror And Weld"
expect_text "Version 0.9.5"
-expect_text "ZSpheres"
-expect_text "Blender keys"
-expect_text "Flat shading"
expect_text "Version 0.9.4"
expect_text "Version 0.9.3"
expect_text "Version 0.9.2"
@@ -20,5 +20,5 @@ expect_text "Version 0.6"
expect_text "Version 0.5"
expect_text "Version 0.4.2"
# The newest section is on screen.
-expect_text "ZSpheres"
+expect_text "Mirror And Weld"
shot whats-new
diff --git a/tools/guide/make_images.py b/tools/guide/make_images.py
index 3c63c7de..1de4e8cd 100644
--- a/tools/guide/make_images.py
+++ b/tools/guide/make_images.py
@@ -52,6 +52,7 @@ CROPS = {
"polygroups": ("polygroups", (300, 100, 1600, 860), 960),
"splats": ("splats", (420, 46, 1600, 900), 960),
"user-guide": ("user-guide", (130, 140, 1190, 880), 1060),
+ "extract": ("extract", (380, 140, 1000, 740), 620),
"make-sculptable-panel": ("sculptable-panel", (1276, 500, 1600, 960), 324),
}
@@ -129,6 +130,20 @@ def remesh(shots: pathlib.Path):
return save(img, "remesh", 900)
+def mirror_weld(shots: pathlib.Path):
+ """A head sculpted on one side, then after Mirror And Weld X."""
+ box = (420, 150, 900, 850)
+ before = Image.open(shots / "mirror-weld-before.png").convert("RGB").crop(box)
+ after = Image.open(shots / "mirror-weld-after.png").convert("RGB").crop(box)
+ img = Image.new("RGB", (before.width * 2 + 12, before.height), (20, 20, 22))
+ img.paste(before, (0, 0))
+ img.paste(after, (before.width + 12, 0))
+ d = ImageDraw.Draw(img)
+ label(d, (before.width // 2, 24), "Sculpted on one side", 20, "mt")
+ label(d, (before.width + 12 + after.width // 2, 24), "After Mirror And Weld X", 20, "mt")
+ return save(img, "mirror-weld", 900)
+
+
def subdivision(shots: pathlib.Path):
box = (250, 125, 1070, 890)
names = [("sdiv-1", "SDiv 1: 108 triangles"), ("sdiv-3", "SDiv 3: 1,728"), ("sdiv-6", "SDiv 6: 110,592")]
@@ -207,7 +222,7 @@ def main() -> int:
OUT.mkdir(parents=True, exist_ok=True)
composed = {"interface-overview": overview, "remesh": remesh, "subdivision-levels": subdivision,
"qremesh-guides": qremesh_guides, "dynamic-topology": dyntopo,
- "make-sculptable": make_sculptable, "shading": shading}
+ "make-sculptable": make_sculptable, "shading": shading, "mirror-weld": mirror_weld}
wanted = lambda name: not args.only or name in args.only
made = [make(args.shots) for name, make in composed.items() if wanted(name)]
for name, (shot, box, width) in CROPS.items():
diff --git a/tools/guide/shots.sfui b/tools/guide/shots.sfui
index f030afbb..b4b11817 100644
--- a/tools/guide/shots.sfui
+++ b/tools/guide/shots.sfui
@@ -360,3 +360,26 @@ wait 0.2
shot custom-matcaps
key escape
run set_material name="Soft Clay"
+
+# Extract (subtools.md): a cap made from the masked top of a sphere, shown with its polygroups (outer, inner, rim).
+run new_sphere subdivisions=6
+run mask_rect y0=0.3
+run extract thickness=0.04 smooth=8 accept=true
+run mask_clear
+camera 30 25
+click "Groups##view.polygroups"
+wait 0.2
+shot extract
+click "Groups##view.polygroups"
+
+# Mirror And Weld (geometry.md): a head sculpted on one side, then mirrored and welded.
+run new_head
+run stroke points="0.035,0.005,0.2 0.06,-0.03,0.2 0.07,-0.07,0.2" brush=Standard radius=0.012 strength=1
+run stroke points="0.015,0.105,0.2 0.04,0.1,0.2 0.065,0.085,0.2" brush=Standard radius=0.014 strength=1
+camera 0 0
+zoom 1.4
+wait 0.2
+shot mirror-weld-before
+run mirror_and_weld axis=x
+wait 0.2
+shot mirror-weld-after