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
Selection Sets: named snapshots per Part of mask, polygroups, visibility, vertex paint, UVs and shape
islandmedb62ce369b282
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 25ce1993..d57729dd 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -6,6 +6,20 @@ All notable changes to SculptForge are listed here. The format follows## [Unreleased]+### Added+- Selection Sets (**Tool > Selection Sets**, `selection_set_*`): any number of named snapshots per Part of the mask,+ polygroups, visibility, vertex paint, UVs and shape, each holding the channels you tick. Store, restore, rename,+ delete, combine (union / intersect / subtract, also as restore modes onto the current mask and visibility) and a+ quick set from the visible faces, each one undo step. A set restores at any subdivision level of its Part (values+ carried through the levels as the stack carries attributes; shapes as offsets, so in-between detail stays). Stored+ compactly (runs of masked / painted / hidden elements, run-length polygroups) in projects under the optional+ `selection_sets` key (no format version bump; older versions skip it), in `.sfsets` files+ (`selection_sets_export` / `selection_sets_import`) and in USD exports as GeomSubsets and primvars, which USD import+ reads back. A set with its shape is a morph target: the new **Morph** brush pulls toward it (Alt pushes away) and+ `selection_set_morph` (Morph to Set) blends the whole Part toward it by an amount, within the mask. Python:+ `Document.selection_sets`, `selection_set(name)` and `set_selection_set(name, mask=..., ...)` push and pull sets as+ NumPy arrays.+## [0.10.4] - 2026-11-01### Addeddiff --git a/CMakeLists.txt b/CMakeLists.txtindex 3046f86f..43711738 100644--- a/CMakeLists.txt+++ b/CMakeLists.txt@@ -45,6 +45,7 @@ add_library(sculptforge_core STATICsrc/core/Document.cppsrc/core/Commands.cppsrc/core/Polygroups.cpp+ src/core/SelectionSets.cppsrc/core/ScreenSelect.cppsrc/core/SubTools.cppsrc/core/ExtractMirror.cpp@@ -259,6 +260,7 @@ if(SCULPTFORGE_BUILD_APP)src/app/AssetLibrary.cppsrc/app/PanelMasking.cppsrc/app/PanelPolygroups.cpp+ src/app/PanelSelectionSets.cppsrc/app/Selection.cppsrc/app/PanelBrushes.cppsrc/app/PanelVdm.cppdiff --git a/docs/guide/index.md b/docs/guide/index.mdindex 99ef9308..cfa84470 100644--- a/docs/guide/index.md+++ b/docs/guide/index.md@@ -26,46 +26,47 @@ You can read it inside SculptForge (**Help > User Guide**, or <kbd>Shift</kbd>+<8. [Brush Lab and sharing brushes](brush-lab.md)9. [Masking](masking.md)10. [Polygroups and visibility](polygroups.md)-11. [SubTools](subtools.md)-12. [ZSpheres](zspheres.md)-13. [Polypaint and materials](polypaint.md)-14. [Texture painting](texture-painting.md)-15. [Material painting (PBR)](pbr-painting.md)-16. [Sculpt layers and blend shapes](layers.md)-17. [Facial shapes and live face](facial-shapes.md)-18. [Subdivision levels](subdivision-levels.md)-19. [Micro levels: hundreds of millions of polygons](micro-levels.md)-20. [Dynamic topology](dynamic-topology.md)-21. [Sculpt Timeline and timelapse](timeline.md)-22. [Moving, rotating and posing (Gizmo 3D)](gizmo.md)-23. [Subdivide, remesh, decimate and LODs](geometry.md)-24. [Quad retopology and detail projection](retopology.md)+11. [Selection sets and morph targets](selection-sets.md)+12. [SubTools](subtools.md)+13. [ZSpheres](zspheres.md)+14. [Polypaint and materials](polypaint.md)+15. [Texture painting](texture-painting.md)+16. [Material painting (PBR)](pbr-painting.md)+17. [Sculpt layers and blend shapes](layers.md)+18. [Facial shapes and live face](facial-shapes.md)+19. [Subdivision levels](subdivision-levels.md)+20. [Micro levels: hundreds of millions of polygons](micro-levels.md)+21. [Dynamic topology](dynamic-topology.md)+22. [Sculpt Timeline and timelapse](timeline.md)+23. [Moving, rotating and posing (Gizmo 3D)](gizmo.md)+24. [Subdivide, remesh, decimate and LODs](geometry.md)+25. [Quad retopology and detail projection](retopology.md)## AI and capture-25. [Image and text to 3D](generate-3d.md)-26. [Gaussian splats](splats.md)-27. [Scan an object into a splat](scan-to-splat.md)-28. [From scan to sculptable mesh](scan-to-sculptable.md)-29. [Phone capture and AR](phone-capture.md)+26. [Image and text to 3D](generate-3d.md)+27. [Gaussian splats](splats.md)+28. [Scan an object into a splat](scan-to-splat.md)+29. [From scan to sculptable mesh](scan-to-sculptable.md)+30. [Phone capture and AR](phone-capture.md)## Files and pipelines-30. [Baking normal and displacement maps](baking.md)-31. [Exporting, Unreal and ZBrush](exporting.md)-32. [Export presets](export-presets.md)-33. [Working with Blender](blender.md)-34. [Working with Maya](maya.md)-35. [Projects, autosave and QuickSave](projects.md)-36. [Scripting and automation](scripting.md)-37. [SculptForge for studios](studios.md)+31. [Baking normal and displacement maps](baking.md)+32. [Exporting, Unreal and ZBrush](exporting.md)+33. [Export presets](export-presets.md)+34. [Working with Blender](blender.md)+35. [Working with Maya](maya.md)+36. [Projects, autosave and QuickSave](projects.md)+37. [Scripting and automation](scripting.md)+38. [SculptForge for studios](studios.md)## Reference-38. [Keyboard and mouse](shortcuts.md)-39. [Performance and big meshes](performance.md)-40. [Troubleshooting and FAQ](troubleshooting.md)-41. [Glossary](glossary.md)+39. [Keyboard and mouse](shortcuts.md)+40. [Performance and big meshes](performance.md)+41. [Troubleshooting and FAQ](troubleshooting.md)+42. [Glossary](glossary.md)## Getting helpdiff --git a/docs/guide/sculpting.md b/docs/guide/sculpting.mdindex 7dbdf2b4..9114ff54 100644--- a/docs/guide/sculpting.md+++ b/docs/guide/sculpting.md@@ -50,6 +50,7 @@ are on the bottom shelf by default and in the brush picker.| **KelvinScale** | | Press and drag left to pinch the surface toward that point, right to swell it. | The other way || **KelvinSnake** | | An elastic SnakeHook: smooth horns and tendrils that taper as they stretch. | No change || **DetailClone** | | Paints copies of a captured detail (the VDM brush's map) along the stroke, each turned to follow it. | Digs them in |+| **Morph** | | Pulls the surface back toward the morph target, a selection set with its shape ([Selection sets](selection-sets.md#morph-targets)). Does nothing until you pick one. | Pushes away from it || **Paint** | <kbd>P</kbd> | Paints colour without sculpting. See [Polypaint and materials](polypaint.md). | Paints back to white |Notes on particular brushes:diff --git a/docs/guide/selection-sets.md b/docs/guide/selection-sets.mdnew file mode 100644index 00000000..85314752--- /dev/null+++ b/docs/guide/selection-sets.md@@ -0,0 +1,140 @@+# Selection sets and morph targets++A selection set is a named snapshot of a Part's mask, polygroups, vertex paint, visibility (which faces are+hidden), UVs and shape. Store as many as you like, bring any of them back later, combine them, and use a stored+shape as the target of the **Morph** brush. Sets belong to the Part, travel with the project, and work across its+subdivision levels: store at one level, restore at any other.++## Store a set++Open **Tool > Selection Sets**.++1. Type a name in the field next to **Store** (it suggests "Set 1", then "Set 2" and so on).+2. Tick the channels the set should hold:++ | Channel | What it keeps | Command name |+ |---|---|---|+ | **Mask** | The mask, soft edges included. | `mask` |+ | **Groups** | The polygroups. | `polygroups` |+ | **Visibility** | Which faces are shown and which are hidden. | `visibility` |+ | **Vertex Paint** | The vertex colours. | `paint` |+ | **UVs** | The UV layout (only when the Part has UVs). | `uvs` |+ | **Shape** | The surface itself, as a morph target. | `morph` |++3. Click **Store**. Storing again under the same name replaces that set.++**From Visible** is the quick way: it stores the faces shown right now as a set called **Visible** (then+**Visible 2**, ...). Isolate a part with the <kbd>Ctrl</kbd>+<kbd>Shift</kbd> gestures+([Polygroups and visibility](polygroups.md)), click **From Visible**, and you can get back to exactly that view+whenever you need it.++There is no limit on the number of sets. They are kept compactly: masks, vertex paint and visibility store only the+parts that differ from an empty mask, white paint and a fully shown Part, and polygroups are run-length coded, so a+mask on a few million vertices usually costs a few kilobytes. Shapes and UVs are stored as they are.++## Restore, rename and delete++Select a set in the list (hover it to see its channels and the level it was stored at), then:++- **Restore** puts its channels back. The shape is not restored here: **Morph to Set** does that, so you can keep+ a set with a shape in it and still restore just its mask. Double-clicking a set restores it too.+- **Rename** edits its name; **Delete** removes it.++The menu next to **From Visible** sets how **Restore** meets what you have now, for the mask and visibility:++| Mode | Mask | Visibility |+|---|---|---|+| **Replace** | The set's mask. | The set's shown faces. |+| **Union** | Masked in either. | Shown in either. |+| **Intersect** | Masked in both. | Shown in both. |+| **Subtract** | Masked now but not in the set. | Shown now but not in the set. |++Every store, restore, rename, delete and combine is one undo step.++A set greyed out in the list no longer fits the Part: its topology changed since (a remesh, Dynamic topology,+Delete hidden). Undo the change, or delete the set.++## Combine sets++Pick a second set in the menu under **Restore**, choose **Union**, **Intersect** or **Subtract** above, and click+**Combine**: a new set ("Head + Arms", "Head & Arms" or "Head - Arms") holds the mask and visibility of the two+combined that way. Your current mask and visibility are not touched until you restore it.++## Subdivision levels++A set remembers the level it was stored at, and restores at any level of the same Part:++- going down, each vertex and face takes the value of the matching one on the level above, as the levels themselves+ do;+- going up, masks and vertex paint are interpolated, polygroups and visibility are inherited from the face they lie+ in, and UVs are interpolated across each face;+- a shape travels as its difference from that level's own surface, so the detail of the levels in between stays+ where it is.++So you can store a mask at SDiv 1, sculpt at SDiv 5 and restore the mask there, or keep a high-resolution polygroup+set and use it at the base cage. Sets survive **Divide**, **Del Lower**, **Del Higher** and **Reconstruct+Subdiv** as long as the level they were stored at still exists.++## Morph targets++Store a set with **Shape** ticked to keep the surface as it is now. Then:++- **Morph Target** makes it the target of the **Morph** brush and picks that brush. Strokes pull the surface back+ toward the stored shape, as much as the brush's strength; <kbd>Alt</kbd> pushes away from it. The set's name+ shows **[morph]** in the list; **Clear Morph Target** turns it off.+- **Morph to Set** moves the whole surface toward the set's shape by **Amount** (1 = all the way, 0.5 = halfway,+ negative values push away), respecting the mask, as one undo step.++Both work at any subdivision level, not only the one the shape was stored at, and with sculpt layers (the change+goes into the active layer). Use them to undo a sculpting session locally, to blend between two versions of a+form, or to keep a neutral pose while you sculpt an expression.++## Projects, files and other apps++Sets are saved in the project with each Part (older versions of SculptForge open such projects and leave the sets+out). To move them between Parts, scenes or tools, use the commands:++```+selection_sets_export path=head.sfsets # every set of the active Part (name=... for one)+selection_sets_import path=head.sfsets # into the active Part+```++A `.sfsets` file is a ZIP with a JSON manifest and one small binary file per set. Importing a set that was stored on+a different mesh keeps it, but it shows greyed out and can't be restored until the Part has a level it fits.++**USD** (`export_usd`) writes the sets of each Part inside its Mesh prim: the shown faces of each set as a+`GeomSubset` (`sculptforge_set0_visible`), its polygroups as a partition of `GeomSubset`s (`sculptforge_set0_group7`),+and its mask and vertex paint as vertex primvars (`primvars:sculptforge_set0_mask`, `..._color`), with the names in+`sculptforge:selectionSets`. Houdini, Maya, Blender and Omniverse read these as ordinary face sets and primvars, and+SculptForge turns them back into selection sets when it imports the file. UVs and shapes are not written to USD.++**OBJ, glTF / GLB, FBX, PLY and STL** have no place for named selections, so sets are not written to them (OBJ+still writes the current polygroups as `g` groups). Export the sets to a `.sfsets` file alongside the model instead.++## Scripting++Every button is a command, so scripts, `sculptforge-cli`, the MCP server and the AI assistant can use sets:++| Command | What it does |+|---|---|+| `selection_set_store name=Head channels=mask,visibility` | Store (or replace) a set. `channels` takes `mask`, `polygroups`, `paint`, `visibility`, `uvs`, `morph` or `all`. |+| `selection_set_restore name=Head mode=union` | Restore; `channels=` restores some of them (add `morph` to restore the shape). |+| `selection_set_rename name=Head to=Face` | Rename. |+| `selection_set_delete name=Head` | Delete. |+| `selection_set_list json=true` | List the sets with their channels and levels. |+| `selection_set_combine a=Head b=Ears op=union into=HeadEars` | Combine two sets into a new one. |+| `selection_set_from_visible` | The quick set from the visible faces. |+| `selection_set_morph_target name=Rest` | Make a set the Morph brush's target (empty name: none). |+| `selection_set_morph name=Rest amount=0.5` | Morph to Set. |+| `selection_sets_export` / `selection_sets_import` | `.sfsets` files. |++In Python (`import sculptforge as sf`), push and pull sets as NumPy arrays:++```python+doc.set_selection_set("Eyes", mask=eye_mask, hidden=hidden_faces) # store from arrays (one undo step)+doc.selection_sets # [{'name': 'Eyes', 'channels': [...], ...}]+arrays = doc.selection_set("Eyes") # {'mask': ..., 'hidden': ...} at this level+sf.run(doc, "selection_set_restore", name="Eyes")+```++See [Scripting and automation](scripting.md) for running commands.diff --git a/docs/guide/whats-new.md b/docs/guide/whats-new.mdindex d6455830..3c0282df 100644--- a/docs/guide/whats-new.md+++ b/docs/guide/whats-new.md@@ -5,6 +5,20 @@ 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).+## Version 0.10.5++- **Selection sets** (**Tool > Selection Sets**): store as many named snapshots of a Part's mask, polygroups,+ visibility, vertex paint, UVs and shape as you like, and restore them at any subdivision level, not only the one+ they were stored at. Combine two sets (union, intersect, subtract), restore one onto the current mask or+ visibility the same way, or take a quick set from the visible faces. Every step is one undo step, and the sets are+ saved with the project. See [Selection sets](selection-sets.md).+- **Morph brush and Morph to Set**: a set with its shape is a morph target. The new **Morph** brush pulls the+ surface back toward it (<kbd>Alt</kbd> pushes away), and **Morph to Set** blends the whole Part toward it by any+ amount, within the mask, at any subdivision level.+- **Sets for pipelines**: `selection_set_*` commands for scripts, `sculptforge-cli` and the AI assistant,+ `doc.selection_set()` / `doc.set_selection_set()` in Python, `.sfsets` files to move sets between Parts and+ scenes, and USD exports that carry them as GeomSubsets and primvars (read back on import).+## Version 0.10.4### From your requests on GitHubdiff --git a/docs/project-format.md b/docs/project-format.mdindex c8828b5f..ec86206f 100644--- a/docs/project-format.md+++ b/docs/project-format.md@@ -47,6 +47,21 @@ read by `loadProject` (src/core/Project.cpp). Commands: `save_project path=...`,Optional attributes are simply absent when the mesh doesn't have them.+### Selection sets+`subtools[i].selection_sets` (only for SubTools with sets; src/core/SelectionSets.h; added after 0.10.4 without a+format version bump, older readers ignore it) holds `version` (1), `morph_target` (the set the Morph brush uses, if+any) and `sets`: per set its `name`, `channels`, `level`, `vertex_count`, `triangle_count` (for people and tools;+readers rely on the data) and `data`, a `u8` blob under `subtools/i/sets/<k>.bin`. The blob is self-contained,+little-endian: `SFSS`, the set format version (1), the channel bits (1 mask, 2 polygroups, 4 vertex paint,+8 visibility, 16 UVs, 32 shape), the vertex and triangle counts and level it was stored at, the name (u32 length ++UTF-8), then one section per channel (u32 channel bit, u64 byte length, payload): runs (u64 count, then u32 start,+u32 length each) of masked vertices plus a u32 "all ones" flag and otherwise f32 values; run-length polygroups (u32+id, u32 length); runs of non-white vertices plus f32 x3 colours; runs of hidden triangles; f32 x2 UVs per triangle+corner; f32 x3 positions. Readers skip sections they don't know and leave out (with a notice) any set they can't+read; a set whose format version is newer than theirs is left out the same way. `.sfsets` files+(`selection_sets_export`) are stored ZIPs of a `manifest.json` (`format` = `"SculptForge selection sets"`,+`version` 1, `morph_target`, `sets` as above with `data` naming the entry) and the same blobs under `sets/`.+### Paint layers`subtools[i].paint_layers` (only written when the SubTool has paint layers; src/core/PaintLayer.h) holds`active` (the layer painting writes into, -1 = Base), `base` and `layers` (bottom to top). `blend` is one ofdiff --git a/src/app/App.h b/src/app/App.hindex 71a2d9b0..d0f6cb49 100644--- a/src/app/App.h+++ b/src/app/App.h@@ -1109,6 +1109,15 @@ private:float paintOpacityDrag_ = -1.0f; // opacity before the slider drag (-1 = not dragging)void drawGameExportContents();void drawVisibilitySection();+ // Tool > Selection Sets (PanelSelectionSets.cpp).+ void drawSelectionSetsSection();+ char setNameBuffer_[64] = "Set 1";+ uint32_t setChannels_ = 1 | 2 | 8; // kSetMask | kSetPolygroups | kSetVisibility (core/SelectionSets.h)+ std::string selectedSet_, combineWith_;+ int setMode_ = 0; // Replace, Union, Intersect, Subtract+ float morphAmount_ = 1.0f;+ bool renamingSet_ = false;+ char setRenameBuffer_[64] = "";void drawGeometrySection(); // PanelGeometry.cpp: Divide, SDiv, Lower / Higher Res, Del Lower / Higher, Reconstructbool smt_ = true; // Tool > Geometry > Smt: Divide smoothsfloat sdivSlider_ = 1.0f; // the SDiv slider while dragged (1-based)diff --git a/src/app/Palettes.cpp b/src/app/Palettes.cppindex 27a167f5..75db93ba 100644--- a/src/app/Palettes.cpp+++ b/src/app/Palettes.cpp@@ -668,6 +668,10 @@ void App::drawPalette_Tool() {tray::Section section;drawVisibilitySection();}+ if (subpalette("tool.selection_sets", "Selection Sets")) {+ tray::Section section;+ drawSelectionSetsSection();+ }if (subpalette("tool.export", "Export")) {tray::Section section;Demo::pushScope("Game Ready");diff --git a/src/app/PanelSelectionSets.cpp b/src/app/PanelSelectionSets.cppnew file mode 100644index 00000000..92f8f00a--- /dev/null+++ b/src/app/PanelSelectionSets.cpp@@ -0,0 +1,222 @@+// SculptForge - open source digital sculpting+// SPDX-License-Identifier: GPL-3.0-or-later+//+// Tool > Selection Sets: store, restore, rename, delete and combine named snapshots of the active Part's mask,+// polygroups, vertex paint, visibility, UVs and shape; pick one as the Morph brush's target or morph toward it.+// Every button runs a selection_set_* command (core/SelectionSets.h), so each is one undo step.+#include "app/App.h"++#include "app/I18n.h"+#include "app/Ui.h"++#include "core/Multires.h"+#include "core/SelectionSets.h"++#include <cstdio>+#include <cstring>++namespace sf {++namespace {++struct ChannelToggle {+ uint32_t bit;+ const char* label; // shown, and the command's channel name+ const char* channel;+ const char* help;+};+constexpr ChannelToggle kToggles[] = {+ {kSetMask, "Mask##setch", "mask", "The mask (masked and partly masked vertices)."},+ {kSetPolygroups, "Groups##setch", "polygroups", "The polygroups."},+ {kSetVisibility, "Visibility##setch", "visibility", "Which faces are shown and which are hidden."},+ {kSetPaint, "Vertex Paint##setch", "paint", "The vertex paint colours."},+ {kSetUvs, "UVs##setch", "uvs", "The UV layout (only when the Part has UVs)."},+ {kSetMorph, "Shape##setch", "morph", "The shape itself: a morph target for the Morph brush and Morph to Set."},+};++std::string channelArg(uint32_t channels) {+ std::string out;+ for (const auto& t : kToggles)+ if (channels & t.bit) out += (out.empty() ? "" : ",") + std::string(t.channel);+ return out;+}++const char* const kModes[] = {"Replace", "Union", "Intersect", "Subtract"};+const char* const kModeArgs[] = {"replace", "union", "intersect", "subtract"};++} // namespace++void App::drawSelectionSetsSection() {+ const SelectionSetList* list = doc_.mesh.selectionSets.get();+ const float avail = ImGui::GetContentRegionAvail().x, spacing = ImGui::GetStyle().ItemSpacing.x;+ const float half = (avail - spacing) * 0.5f, third = (avail - 2.0f * spacing) / 3.0f;++ // Store: a name and the channels the new set holds.+ ImGui::SetNextItemWidth(avail - third - spacing);+ ImGui::InputText("##setname", setNameBuffer_, sizeof setNameBuffer_);+ ui::HelpText("Set name", nullptr, "Name of the set Store makes; storing again with the same name replaces it.",+ "Tool > Selection Sets");+ ImGui::SameLine();+ if (ImGui::Button(tr("Store##selsets"), ImVec2(third, 0))) {+ std::string name = setNameBuffer_;+ if (name.empty()) name = "Set";+ runCommand("selection_set_store", {{"name", name}, {"channels", channelArg(setChannels_ ? setChannels_ : kSetMask)}});+ if (lastCommandOk_) {+ selectedSet_ = name;+ // Suggest the next name ("Set 1" -> "Set 2").+ const size_t digits = name.find_last_not_of("0123456789");+ int n = digits + 1 < name.size() ? std::atoi(name.c_str() + digits + 1) + 1 : 2;+ const std::string stem = digits + 1 < name.size() ? name.substr(0, digits + 1) : name + " ";+ std::snprintf(setNameBuffer_, sizeof setNameBuffer_, "%s%d", stem.c_str(), n);+ }+ }+ ui::HelpText("Store", nullptr,+ "Store the checked channels of this Part as a named set (one undo step). Sets restore at any "+ "subdivision level and are saved in the project.",+ "Tool > Selection Sets");+ for (size_t i = 0; i < std::size(kToggles); ++i) {+ if (i % 3) ImGui::SameLine();+ bool on = (setChannels_ & kToggles[i].bit) != 0;+ if (ImGui::Checkbox(tr(kToggles[i].label), &on)) setChannels_ = on ? setChannels_ | kToggles[i].bit : setChannels_ & ~kToggles[i].bit;+ const std::string title(kToggles[i].label, std::strchr(kToggles[i].label, '#'));+ ui::HelpText(title.c_str(), nullptr, kToggles[i].help, "Tool > Selection Sets");+ }+ if (ImGui::Button(tr("From Visible##selsets"), ImVec2(half, 0))) {+ runCommand("selection_set_from_visible");+ if (lastCommandOk_ && doc_.mesh.selectionSets) selectedSet_ = doc_.mesh.selectionSets->sets.back()->name;+ }+ ui::HelpText("From Visible", nullptr, "Quick set: store the faces shown right now (Visible, Visible 2, ...).",+ "Tool > Selection Sets");+ ImGui::SameLine();+ ImGui::SetNextItemWidth(-1);+ ImGui::Combo("##setmode", &setMode_, kModes, int(std::size(kModes)));+ ui::HelpText("Restore mode", nullptr,+ "How Restore meets the current mask and visibility: Replace them, or Union, Intersect or Subtract the "+ "set's. Combine uses the same mode (not Replace) to make a new set from two.",+ "Tool > Selection Sets");++ // The sets.+ if (!list || list->sets.empty()) {+ ImGui::TextDisabled("%s", tr("No sets yet: Store saves one."));+ return;+ }+ if (list->find(selectedSet_) < 0) selectedSet_ = list->sets.front()->name;+ const float rowH = ImGui::GetTextLineHeightWithSpacing();+ const int rows = std::min<int>(int(list->sets.size()), 6);+ std::string clicked;+ if (ImGui::BeginChild("##setlist", ImVec2(-1, rowH * float(rows) + ImGui::GetStyle().FramePadding.y * 2.0f),+ ImGuiChildFlags_Borders)) {+ for (size_t i = 0; i < list->sets.size(); ++i) {+ const SelectionSet& s = *list->sets[i];+ const bool fits = selectionSetFits(doc_.mesh, s);+ std::string label = s.name;+ if (s.name == list->morphTarget) label += " [morph]";+ label += "##set" + std::to_string(i);+ if (!fits) ImGui::PushStyleColor(ImGuiCol_Text, ImGui::GetStyle().Colors[ImGuiCol_TextDisabled]);+ if (ImGui::Selectable(label.c_str(), s.name == selectedSet_, ImGuiSelectableFlags_AllowDoubleClick)) {+ clicked = s.name;+ if (ImGui::IsMouseDoubleClicked(ImGuiMouseButton_Left)) {+ selectedSet_ = s.name;+ runCommand("selection_set_restore", {{"name", s.name}, {"mode", std::string(kModeArgs[setMode_])}});+ }+ }+ if (!fits) ImGui::PopStyleColor();+ if (ImGui::IsItemHovered()) {+ std::string tip = setChannelNames(s.channels);+ if (subdivLevelCount(doc_.mesh)) tip += "\nStored at SDiv " + std::to_string(s.level + 1);+ if (!fits) tip += "\nDoesn't fit this mesh (its topology changed)";+ tip += "\nDouble-click to restore";+ ImGui::SetTooltip("%s", tip.c_str());+ }+ }+ }+ ImGui::EndChild();+ if (!clicked.empty() && clicked != selectedSet_) {+ selectedSet_ = clicked;+ renamingSet_ = false;+ }+ const int index = list->find(selectedSet_);+ const SelectionSet& sel = *list->sets[size_t(index)];+ const std::string name = sel.name; // (the list may change under the buttons below)++ if (ImGui::Button(tr("Restore##selsets"), ImVec2(third, 0)))+ runCommand("selection_set_restore", {{"name", name}, {"mode", std::string(kModeArgs[setMode_])}});+ ui::HelpText("Restore", nullptr,+ "Put the selected set's channels back (not its shape: Morph to Set does that), carried to the current "+ "subdivision level. One undo step.",+ "Tool > Selection Sets");+ ImGui::SameLine();+ if (ImGui::Button(tr("Rename##selsets"), ImVec2(third, 0))) {+ renamingSet_ = true;+ std::snprintf(setRenameBuffer_, sizeof setRenameBuffer_, "%s", name.c_str());+ }+ ImGui::SameLine();+ if (ImGui::Button(tr("Delete##selsets"), ImVec2(third, 0))) {+ runCommand("selection_set_delete", {{"name", name}});+ return;+ }+ ui::HelpText("Delete", nullptr, "Delete the selected set (undo brings it back).", "Tool > Selection Sets");+ if (renamingSet_) {+ ImGui::SetNextItemWidth(avail - third - spacing);+ const bool enter = ImGui::InputText("##setrename", setRenameBuffer_, sizeof setRenameBuffer_,+ ImGuiInputTextFlags_EnterReturnsTrue | ImGuiInputTextFlags_AutoSelectAll);+ ImGui::SameLine();+ if (ImGui::Button(tr("OK##setrename"), ImVec2(third, 0)) || enter) {+ renamingSet_ = false;+ runCommand("selection_set_rename", {{"name", name}, {"to", std::string(setRenameBuffer_)}});+ if (lastCommandOk_) selectedSet_ = setRenameBuffer_;+ return;+ }+ }++ // Combine with another set (by mask and visibility) into a new one.+ if (list->sets.size() > 1) {+ if (list->find(combineWith_) < 0 || combineWith_ == name)+ for (const auto& s : list->sets)+ if (s->name != name) {+ combineWith_ = s->name;+ break;+ }+ ImGui::SetNextItemWidth(avail - third - spacing);+ if (ImGui::BeginCombo("##combinewith", combineWith_.c_str())) {+ for (const auto& s : list->sets)+ if (s->name != name && ImGui::Selectable(s->name.c_str(), s->name == combineWith_)) combineWith_ = s->name;+ ImGui::EndCombo();+ }+ ImGui::SameLine();+ ImGui::BeginDisabled(setMode_ == 0);+ if (ImGui::Button(tr("Combine##selsets"), ImVec2(third, 0)))+ runCommand("selection_set_combine", {{"a", name}, {"b", combineWith_}, {"op", std::string(kModeArgs[setMode_])}});+ ImGui::EndDisabled();+ ui::HelpText("Combine", nullptr,+ "Make a new set from the selected one and this one by their mask and visibility, with the mode "+ "above (Union, Intersect or Subtract).",+ "Tool > Selection Sets");+ }++ // The shape: the Morph brush's target, and Morph to Set.+ if (sel.has(kSetMorph)) {+ const bool target = list->morphTarget == name;+ if (ImGui::Button(target ? tr("Clear Morph Target##selsets") : tr("Morph Target##selsets"), ImVec2(half, 0))) {+ runCommand("selection_set_morph_target", {{"name", target ? std::string() : name}});+ if (lastCommandOk_ && !target)+ if (const Action* a = actions_.find("brush.morph"); a && a->run) a->run(); // ready to brush toward it+ }+ ui::HelpText("Morph Target", nullptr,+ "Make this set's shape the Morph brush's target and pick the Morph brush: strokes pull the surface "+ "back toward the stored shape (Alt pushes away), at any subdivision level.",+ "Tool > Selection Sets");+ ImGui::SameLine();+ if (ImGui::Button(tr("Morph to Set##selsets"), ImVec2(half, 0)))+ runCommand("selection_set_morph", {{"name", name}, {"amount", double(morphAmount_)}});+ ui::HelpText("Morph to Set", nullptr,+ "Move the whole surface toward the set's shape by the amount below, within the mask. One undo step.",+ "Tool > Selection Sets");+ ImGui::SetNextItemWidth(-1);+ ui::SliderInside("##morphamount", &morphAmount_, -1.0f, 1.0f, "Amount %.2f");+ } else {+ ImGui::TextDisabled("%s", tr("Store with Shape checked to morph toward a set."));+ }+}++} // namespace sfdiff --git a/src/app/Pickers.cpp b/src/app/Pickers.cppindex 6bb37b2e..e27a4032 100644--- a/src/app/Pickers.cpp+++ b/src/app/Pickers.cpp@@ -403,6 +403,9 @@ const char* brushTypeDescription(int type) {case BrushType::DetailClone:return "Paints copies of a captured detail along the stroke, each turned to follow it. Capture any detail on ""the model with Capture from view (Ctrl+Alt+C), or pick a VDM.";+ case BrushType::Morph:+ return "Pulls the surface back toward a stored shape: pick a selection set with Shape as the Morph Target in "+ "Tool > Selection Sets. Alt pushes away. Works at any subdivision level.";default:return "";}diff --git a/src/app/Shell.cpp b/src/app/Shell.cppindex 59481238..d5a032b1 100644--- a/src/app/Shell.cpp+++ b/src/app/Shell.cpp@@ -330,6 +330,8 @@ void App::registerShellActions() {"Elastic pinch / swell: drag left to pinch the surface toward where you pressed, right to swell it.","Elastic SnakeHook: pulls smooth, tapering horns and tendrils out along the stroke.","Stamps the VDM brush's map along the stroke, each copy turned to follow it. Capture one with Capture from view.",+ "Pulls the surface back toward the morph target, a selection set's shape (Tool > Selection Sets > Morph "+ "Target); Alt pushes away. Works at any subdivision level.",};static_assert(std::size(kBrushHelp) == size_t(BrushType::Count));for (int i = 0; i < int(BrushType::Count); ++i) {diff --git a/src/app/UiTest.cpp b/src/app/UiTest.cppindex d57c1394..16bb11e1 100644--- a/src/app/UiTest.cpp+++ b/src/app/UiTest.cpp@@ -191,6 +191,7 @@#include "core/Matcap.h"#include "core/Multires.h"#include "core/Script.h"+#include "core/SelectionSets.h"#include "core/ThreadPool.h"#include "core/Timeline.h"#include "link/HttpServer.h"@@ -385,6 +386,9 @@ double Demo::query(const std::string& name, bool& known) const {if (const double v = app_.sculptableTestValue(name); !std::isnan(v)) return v;if (name == "qremesh_running") return app_.qremesh_ ? 1.0 : 0.0;if (name == "qremesh_guides") return double(app_.doc_.qremeshGuides.size());+ if (name == "selection_sets") return m.selectionSets ? double(m.selectionSets->sets.size()) : 0.0;+ if (name == "morph_target") return m.selectionSets && !m.selectionSets->morphTarget.empty() ? 1.0 : 0.0;+ if (name == "morph_brush") return app_.brush_ == BrushType::Morph && app_.doc_.activeBrush < 0 ? 1.0 : 0.0;if (name == "qremesh_guide_loops") {size_t n = 0;for (const QRemeshGuide& g : app_.doc_.qremeshGuides) n += g.closed;diff --git a/src/app/UserGuide.cpp b/src/app/UserGuide.cppindex 84998eef..b975c0a4 100644--- a/src/app/UserGuide.cpp+++ b/src/app/UserGuide.cpp@@ -426,6 +426,7 @@ std::string UserGuide::chapterFor(const std::string& palette, const std::string&if (starts("Tool > Geometry") || starts("Tool > Remesh")) return "geometry.md";if (starts("Tool > Masking")) return "masking.md";if (starts("Tool > Polygroups") || starts("Tool > Visibility")) return "polygroups.md";+ if (starts("Tool > Selection Sets")) return "selection-sets.md";if (starts("Tool > Export")) return "exporting.md";if (starts("Tool > Display")) return "interface.md";if (starts("Tool")) return "subtools.md";diff --git a/src/core/Commands.cpp b/src/core/Commands.cppindex 4f29bd38..72943f31 100644--- a/src/core/Commands.cpp+++ b/src/core/Commands.cpp@@ -21,6 +21,7 @@#include "core/MeshTransform.h"#include "core/PathStroke.h"#include "core/Polygroups.h"+#include "core/SelectionSets.h"#include "core/SubTools.h"#include "core/Polypaint.h"#include "core/Primitives.h"@@ -801,6 +802,7 @@ CommandRegistry::CommandRegistry() {registerMaskingCommands(*this);registerPolygroupCommands(*this);+ registerSelectionSetCommands(*this); // selection_set_* (core/SelectionSets.h)registerSubToolCommands(*this);registerSubdivCommands(*this); // subdiv_* (core/MultiresCommands.cpp)registerMicroCommands(*this); // micro_* (core/MicroCommands.cpp)diff --git a/src/core/Document.cpp b/src/core/Document.cppindex a91260c7..8645d46d 100644--- a/src/core/Document.cpp+++ b/src/core/Document.cpp@@ -220,6 +220,7 @@ std::string Document::assetName() const {}void Document::replaceMeshUndoable(Mesh m, std::string label) {+ if (!m.selectionSets) m.selectionSets = mesh.selectionSets; // the Part keeps its sets (restoring checks they fit)if (m.multires && !subdivMatches(m)) m.multires.reset();if (mesh.multires && !m.multires) {// A tool rebuilt the mesh from the current level: the levels go, the undo step keeps them.diff --git a/src/core/Mesh.h b/src/core/Mesh.hindex 29cd416c..ebcb935c 100644--- a/src/core/Mesh.h+++ b/src/core/Mesh.h@@ -23,6 +23,7 @@ struct MultiresStack;struct SubdivTopology;struct ImplicitAdjacency;struct MicroMesh;+struct SelectionSetList;// The vertices or triangles around a vertex (Mesh::neighbors, Mesh::vertexTriangles), in ascending order: a view// of the mesh's adjacency lists or, where the mesh's adjacency is implicit, the list itself. Use it like a span@@ -204,6 +205,11 @@ public:std::vector<ZSphere> zspheres;bool zspherePreview = false;+ // Selection Sets (core/SelectionSets.h): named snapshots of the mask, polygroups, vertex paint, hidden faces, UVs+ // and shape, immutable and shared by copies of the mesh (undo steps swap the whole list). They belong to the+ // Part, not to one subdivision level: stepping levels keeps them. Null = none.+ std::shared_ptr<const SelectionSetList> selectionSets;+size_t vertexCount() const { return positions.size(); }size_t triangleCount() const { return triangles.size(); }diff --git a/src/core/Multires.cpp b/src/core/Multires.cppindex 715b9733..ba9f5fec 100644--- a/src/core/Multires.cpp+++ b/src/core/Multires.cpp@@ -940,6 +940,7 @@ void enterLevel(Mesh& mesh, int level, BVH* bvh, const SubdivLevel* leavingLevelif (!stack->cache) stack->cache = std::make_shared<SubdivLevelCache>();SubdivLevelCache& cache = *stack->cache;std::shared_ptr<PaintTexture> texture = mesh.texture;+ std::shared_ptr<const SelectionSetList> selectionSets = mesh.selectionSets; // (the Part's, not a level's)const bool toTexture = mesh.paintToTexture;const SubdivLevel& wantLevel = stack->levels[size_t(level)];const std::shared_ptr<Mesh> want = wantLevel.data;@@ -963,6 +964,7 @@ void enterLevel(Mesh& mesh, int level, BVH* bvh, const SubdivLevel* leavingLevelSubdivLevelCache::Entry e{std::move(leaving), std::move(leavingTopo), std::move(mesh), std::move(*bvh)};e.mesh.multires.reset();e.mesh.texture.reset();+ e.mesh.selectionSets.reset();cache.entries.push_back(std::move(e));while (cache.entries.size() > SubdivLevelCache::kMaxEntries) cache.entries.erase(cache.entries.begin());}@@ -989,6 +991,7 @@ void enterLevel(Mesh& mesh, int level, BVH* bvh, const SubdivLevel* leavingLevel}mesh.multires = std::move(stack);mesh.texture = std::move(texture);+ mesh.selectionSets = std::move(selectionSets);mesh.paintToTexture = toTexture;if (!taken) {mesh.rebuildTopology();@@ -2228,9 +2231,11 @@ void applySubdivUndo(SubdivUndo& r, Mesh& mesh, BVH& bvh) {return;} else if (r.plain) {std::shared_ptr<PaintTexture> texture = mesh.texture;+ std::shared_ptr<const SelectionSetList> selectionSets = mesh.selectionSets;const bool toTexture = mesh.paintToTexture;mesh = leanCopy(*r.plain);mesh.texture = std::move(texture);+ mesh.selectionSets = std::move(selectionSets);mesh.paintToTexture = toTexture;mesh.rebuildTopology();mesh.recomputeAllNormals();@@ -2321,4 +2326,102 @@ bool reconstructUndoable(Document& doc, std::string& message) {}, message, doc.mesh.multires ? -1 : 1);}+// --- Moving values between levels (Selection Sets, core/SelectionSets.h) ---++namespace {++bool mapLevelsValid(const Mesh& mesh, int from, int to) {+ const int n = subdivLevelCount(mesh);+ return n > 0 && from >= 0 && to >= 0 && from < n && to < n;+}++template <class T>+bool mapVertexValues(const Mesh& mesh, int from, int to, std::vector<T>& values, T fill, bool smooth) {+ if (from == to) return true;+ if (!mapLevelsValid(mesh, from, to)) return false;+ const MultiresStack& s = *mesh.multires;+ std::vector<T> next;+ std::vector<uint8_t> flags;+ for (int k = from; k > to; --k) { // down: each coarse vertex takes its child's value+ const SubdivTopology& tp = *s.levels[size_t(k)].topo;+ if (values.size() != tp.fineVertices) values.assign(tp.fineVertices, fill);+ next.clear();+ restrictVertices(tp, values, next, fill, nullptr, flags);+ values.swap(next);+ }+ for (int k = from + 1; k <= to; ++k) { // up: interpolated (or through the level's stencils)+ const SubdivTopology& tp = *s.levels[size_t(k)].topo;+ if (values.size() != tp.coarseVertices) values.assign(tp.coarseVertices, fill);+ next.clear();+ if (smooth) next = subdivideField(tp, tp.smooth, values);+ else prolongVertices(tp, values, next, fill, nullptr, flags);+ values.swap(next);+ }+ return true;+}++template <class T>+bool mapTriangleValues(const Mesh& mesh, int from, int to, std::vector<T>& values, T fill) {+ if (from == to) return true;+ if (!mapLevelsValid(mesh, from, to)) return false;+ const MultiresStack& s = *mesh.multires;+ std::vector<T> next;+ std::vector<uint8_t> flags;+ for (int k = from; k > to; --k) {+ const SubdivTopology& tp = *s.levels[size_t(k)].topo;+ if (values.size() != tp.fineTriangles) values.assign(tp.fineTriangles, fill);+ next.clear();+ restrictFaces(tp, values, next, s.levels[size_t(k) - 1].triangleCount(), fill, nullptr, flags);+ values.swap(next);+ }+ for (int k = from + 1; k <= to; ++k) {+ const SubdivTopology& tp = *s.levels[size_t(k)].topo;+ if (values.size() != s.levels[size_t(k) - 1].triangleCount()) values.assign(s.levels[size_t(k) - 1].triangleCount(), fill);+ next.clear();+ prolongFaces(tp, values, next, fill, nullptr, flags);+ values.swap(next);+ }+ return true;+}++} // namespace++bool subdivMapVertices(const Mesh& mesh, int from, int to, std::vector<float>& values) {+ return mapVertexValues(mesh, from, to, values, 0.0f, false);+}+bool subdivMapVertices(const Mesh& mesh, int from, int to, std::vector<glm::vec3>& values, glm::vec3 fill, bool smooth) {+ return mapVertexValues(mesh, from, to, values, fill, smooth);+}+bool subdivMapTriangles(const Mesh& mesh, int from, int to, std::vector<uint32_t>& values) {+ return mapTriangleValues(mesh, from, to, values, 0u);+}+bool subdivMapTriangles(const Mesh& mesh, int from, int to, std::vector<uint8_t>& values) {+ return mapTriangleValues(mesh, from, to, values, uint8_t(0));+}+bool subdivMapCorners(const Mesh& mesh, int from, int to, std::vector<glm::vec2>& values) {+ if (from == to) return true;+ if (!mapLevelsValid(mesh, from, to)) return false;+ const MultiresStack& s = *mesh.multires;+ std::vector<glm::vec2> next;+ std::vector<uint8_t> flags;+ std::vector<glm::uvec3> coarseTris;+ for (int k = from; k > to; --k) {+ const SubdivTopology& tp = *s.levels[size_t(k)].topo;+ if (values.size() != tp.fineTriangles * 3) values.assign(tp.fineTriangles * 3, glm::vec2(0.0f));+ subdivLevelFaces(mesh, k - 1, coarseTris);+ next.clear();+ restrictUvs(tp, coarseTris, values, next, nullptr, flags);+ values.swap(next);+ }+ for (int k = from + 1; k <= to; ++k) {+ const SubdivTopology& tp = *s.levels[size_t(k)].topo;+ const size_t coarse = s.levels[size_t(k) - 1].triangleCount() * 3;+ if (values.size() != coarse) values.assign(coarse, glm::vec2(0.0f));+ next.clear();+ prolongUvs(tp, values, next, nullptr, flags);+ values.swap(next);+ }+ return true;+}+} // namespace sfdiff --git a/src/core/Multires.h b/src/core/Multires.hindex a7dee720..75a622a3 100644--- a/src/core/Multires.h+++ b/src/core/Multires.h@@ -223,6 +223,18 @@ void subdivLevelFaces(const Mesh& mesh, int level, std::vector<glm::uvec3>& out)// True when the mesh holds no edits its stack hasn't folded in yet (its current level's data is the mesh).bool subdivInSync(const Mesh& mesh);+// --- Moving values between levels (Selection Sets, core/SelectionSets.h) ---+// Each carries `values`, laid out for level `from` (per vertex, per triangle or per triangle corner), to level `to`+// through the levels in between, as the stack passes attributes on: copied down to the parent elements,+// interpolated (vertices, UV corners) or inherited (triangles) up. `smooth` (vec3 per vertex): up through the+// levels' own subdivision stencils instead of linear interpolation (for offsets of the shape). False when the mesh+// has no such levels.+bool subdivMapVertices(const Mesh& mesh, int from, int to, std::vector<float>& values);+bool subdivMapVertices(const Mesh& mesh, int from, int to, std::vector<glm::vec3>& values, glm::vec3 fill, bool smooth);+bool subdivMapTriangles(const Mesh& mesh, int from, int to, std::vector<uint32_t>& values);+bool subdivMapTriangles(const Mesh& mesh, int from, int to, std::vector<uint8_t>& values);+bool subdivMapCorners(const Mesh& mesh, int from, int to, std::vector<glm::vec2>& values);+// --- Undoable document operations (one undo step each). Return a message for the status bar / console. ---bool divideUndoable(Document& doc, bool smooth, std::string& message);bool setSubdivLevelUndoable(Document& doc, int level, std::string& message);diff --git a/src/core/Project.cpp b/src/core/Project.cppindex 477849f5..cbd7a8c3 100644--- a/src/core/Project.cpp+++ b/src/core/Project.cpp@@ -7,6 +7,7 @@#include "core/Multires.h"#include "core/LayerStackIO.h"+#include "core/SelectionSets.h"#include "core/Texture.h"#include "core/ThreadPool.h"#include "core/ZSpheres.h"@@ -774,6 +775,54 @@ bool readSubdiv(Reader& r, const Json& sj, Mesh& m, std::string& error, bool worreturn true;}+// Selection Sets (core/SelectionSets.h): `selection_sets` = {"version", "morph_target", "sets": [summary + "data"]},+// each set one packed u8 blob under subtools/i/sets/. Optional, so no format version bump: older readers ignore it.+constexpr int kSelectionSetsVersion = 1;++Json writeSelectionSets(Writer& w, const std::string& prefix, const SelectionSetList& list) {+ Json j = Json::object();+ j.set("version", kSelectionSetsVersion);+ if (!list.morphTarget.empty()) j.set("morph_target", list.morphTarget);+ Json sets = Json::array();+ for (size_t k = 0; k < list.sets.size(); ++k) {+ Json one = selectionSetSummary(*list.sets[k]);+ std::vector<uint8_t> packed = packSelectionSet(*list.sets[k]);+ const size_t n = packed.size();+ one.set("data", w.add(prefix + "sets/" + std::to_string(k) + ".bin", Scalar::U8, 1, n, std::move(packed)));+ sets.push(std::move(one));+ }+ j.set("sets", std::move(sets));+ return j;+}++// Sets that can't be read (damaged, or from a newer set format) are left out and named in `skipped`; the rest of+// the project still loads.+void readSelectionSets(Reader& r, const Json& j, Mesh& m, std::string& skipped) {+ if (!j.isObject() || !j["sets"].isArray()) return;+ auto list = std::make_shared<SelectionSetList>();+ for (const Json& one : j["sets"].items()) {+ const Json& desc = one["data"];+ auto it = r.files.find(desc["file"].asString());+ const double count = desc["count"].asNumber(-1);+ std::vector<uint8_t> bytes;+ SelectionSet set;+ std::string why;+ const std::string saved = r.error;+ const bool ok = it != r.files.end() && count >= 0 && double(it->second.size) == count &&+ r.bytes(desc, "selection set", size_t(count), bytes) &&+ unpackSelectionSet(bytes.data(), bytes.size(), set, why) && list->find(set.name) < 0;+ r.error = saved;+ if (!ok) {+ skipped += (skipped.empty() ? "" : ", ") + ("'" + one["name"].asString() + "'");+ continue;+ }+ list->sets.push_back(std::make_shared<const SelectionSet>(std::move(set)));+ }+ list->morphTarget = j["morph_target"].asString();+ if (list->find(list->morphTarget) < 0) list->morphTarget.clear();+ if (!list->sets.empty()) m.selectionSets = std::move(list);+}+// A SubTool read from a project, before it joins the document.struct LoadedSubtool {std::string name, gozName;@@ -858,6 +907,8 @@ bool saveProject(const std::string& path, const Document& doc, std::string& erroif (!gozName.empty()) st.set("goz_name", gozName);const std::vector<QRemeshGuide>& guides = active ? doc.qremeshGuides : s.qremeshGuides;if (!guides.empty()) st.set("qremesh_guides", qremeshGuidesToJson(guides)); // (no format change: optional)+ if (const Mesh& m = doc.subtoolMesh(i); m.selectionSets && !m.selectionSets->sets.empty())+ st.set("selection_sets", writeSelectionSets(w, "subtools/" + std::to_string(i) + "/", *m.selectionSets));if (const Mesh& m = doc.subtoolMesh(i); !m.zspheres.empty()) { // a ZSphere SubTool (core/ZSpheres.h); optionalst.set("zspheres", zspheresToJson(m.zspheres));if (m.zspherePreview) st.set("zsphere_preview", true);@@ -963,6 +1014,7 @@ bool loadProject(const std::string& path, Document& doc, std::string& error) {// SubTools: version 1 has one mesh at the top level, version 2 a "subtools" list.std::deque<LoadedSubtool> subtools; // (stable addresses: BVH threads use them)+ std::string skippedSets; // selection sets that couldn't be readint activeSubtool = 0;if (version < 2) {LoadedSubtool& s = subtools.emplace_back();@@ -986,6 +1038,7 @@ bool loadProject(const std::string& path, Document& doc, std::string& error) {if (!readMesh(r, sj["mesh"], sj["layers"], s.mesh, error, false, false)) return false;s.mesh.zspheres = zspheresFromJson(sj["zspheres"]);s.mesh.zspherePreview = !s.mesh.zspheres.empty() && sj["zsphere_preview"].asBool(false);+ readSelectionSets(r, sj["selection_sets"], s.mesh, skippedSets);// The BVH builds (on the pool) while the levels and topology load (off it), then the normals.s.startBvh();r.parallelReads = !s.bvhBuilder.joinable();@@ -1089,6 +1142,8 @@ bool loadProject(const std::string& path, Document& doc, std::string& error) {doc.selectSubtool(activeSubtool);doc.splats = std::move(splats);doc.splatsChanged();+ if (!skippedSets.empty())+ doc.notice += (doc.notice.empty() ? "" : "; ") + std::string("Selection sets left out (unreadable): ") + skippedSets;for (const auto& b : manifest["brushes"].items()) {if (!b.isObject()) continue;// Brushes the library already has, unchanged, stay library brushes; the rest are the project's own.diff --git a/src/core/Sculpt.cpp b/src/core/Sculpt.cppindex 322b3c2b..2cb9f102 100644--- a/src/core/Sculpt.cpp+++ b/src/core/Sculpt.cpp@@ -34,6 +34,7 @@ const char* brushName(BrushType type) {case BrushType::KelvinScale: return "KelvinScale";case BrushType::KelvinSnake: return "KelvinSnake";case BrushType::DetailClone: return "DetailClone";+ case BrushType::Morph: return "Morph";default: return "?";}}@@ -492,6 +493,8 @@ UndoRecord Sculptor::endStroke() {void Sculptor::dab(Mesh& mesh, BVH& bvh, BrushType type, const DabParams& p, Symmetry sym) {if (!active_) return;+ // Morph: nothing without a target (Tool > Selection Sets > Morph Target); not on micro levels (no grid shapes).+ if (type == BrushType::Morph && (mesh.micro || !morphTarget(mesh))) return;if (isKelvinletBrush(type)) { // Kelvinlet.cpp (no remeshing: they move the surface, as Move does)dabKelvinlet(mesh, bvh, type, p, sym);return;@@ -508,7 +511,7 @@ void Sculptor::dab(Mesh& mesh, BVH& bvh, BrushType type, const DabParams& p, Sym++timings.dabs;return;}- if (type != BrushType::Move) {+ if (type != BrushType::Move && type != BrushType::Morph) { // (Morph needs the vertices the target has)const bool useAlpha = p.alpha && !p.alpha->empty(); // (the reach dabSingle gives the brush)const float reach = useAlpha ? kAlphaReach : type == BrushType::ClayBuildup ? 1.3f : 1.0f;remeshDab(mesh, bvh, p, sym, type == BrushType::Smooth ? 2.0f : 1.0f, reach);@@ -579,6 +582,8 @@ void Sculptor::dabSingle(Mesh& mesh, BVH& bvh, BrushType type, const DabParams&if (type == BrushType::Layer) prepareLayer(mesh, r * 0.08f * std::clamp(p.strength, 0.0f, 1.0f));const bool keepVolume = type == BrushType::Smooth && p.keepVolume;if (keepVolume) taubinShrink(mesh);+ const std::vector<glm::vec3>* morph = type == BrushType::Morph ? morphTarget(mesh) : nullptr;+ if (type == BrushType::Morph && !morph) return;scratch_.resize(verts_.size());// Each vertex's offset depends only on the positions before the dab (and, for Layer, on its own state).@@ -708,6 +713,10 @@ void Sculptor::dabSingle(Mesh& mesh, BVH& bvh, BrushType type, const DabParams&// Slide the surface sideways along the stroke without lifting it.d = projectOnPlane(p.strokeDelta, nrm[v]) * (f * std::min(1.0f, 0.4f + s));break;+ case BrushType::Morph:+ // Toward the morph target (away from it, by a quarter as much, with Alt).+ d = ((*morph)[v] - x) * (p.invert ? -0.25f * s * f : std::min(1.0f, s * f));+ break;default:break;}diff --git a/src/core/Sculpt.h b/src/core/Sculpt.hindex 482963eb..6a91eed5 100644--- a/src/core/Sculpt.h+++ b/src/core/Sculpt.h@@ -35,6 +35,7 @@ enum class BrushType {KelvinScale, // pinches (or swells) the surface toward the centreKelvinSnake, // multi-scale elastic SnakeHook: pulls tapering horns out along the strokeDetailClone, // stamps the VDM brush's map along the stroke, each stamp turned to follow it (Kelvinlet.cpp)+ Morph, // pulls the surface toward the Part's morph target, a selection set's shape (core/SelectionSets.h)Count};@@ -192,7 +193,17 @@ public:// started (the stroke stays open). DragRect re-stamps from scratch while dragging.void restoreStroke(Mesh& mesh, BVH& bvh);+ // Morph brush (core/SelectionSets.h): the shape it pulls toward at the mesh's current level, from the selection+ // set the Part names as its morph target. Null when there is none or it doesn't fit the mesh. Worked out on+ // first use and kept while the set, level and vertex count stay the same (defined in SelectionSets.cpp).+ const std::vector<glm::vec3>* morphTarget(const Mesh& mesh);+private:+ std::shared_ptr<const struct SelectionSet> morphSet_;+ int morphLevel_ = -1;+ size_t morphVertices_ = 0;+ std::vector<glm::vec3> morphMapped_;+ bool morphFits_ = false;void dabSingle(Mesh& mesh, BVH& bvh, BrushType type, const DabParams& p);void dabRecipeSingle(Mesh& mesh, BVH& bvh, const BrushRecipe& r, const DabParams& p);// The Vdm brush (defined in Vdm.cpp); `handedness` -1 for a mirrored pass, so the stamp mirrors exactly.diff --git a/src/core/SelectionSets.cpp b/src/core/SelectionSets.cppnew file mode 100644index 00000000..b4442160--- /dev/null+++ b/src/core/SelectionSets.cpp@@ -0,0 +1,1152 @@+// SculptForge - open source digital sculpting+// SPDX-License-Identifier: GPL-3.0-or-later+#include "core/SelectionSets.h"++#include "core/Commands.h"+#include "core/Document.h"+#include "core/Json.h"+#include "core/Multires.h"+#include "core/PaintLayer.h"+#include "core/Sculpt.h"+#include "io/Zip.h"++#include <algorithm>+#include <bit>+#include <cmath>+#include <cstring>+#include <sstream>++namespace sf {++namespace {++constexpr uint32_t kPackMagic = 0x53534653u; // "SFSS"+constexpr uint32_t kPackVersion = 1;+constexpr size_t kMaxNameBytes = 256;+constexpr const char* kSetsFormat = "SculptForge selection sets";+constexpr int kSetsFileVersion = 1;+constexpr size_t kMaxSets = 100000;+const glm::vec3 kWhite(1.0f);++struct ChannelName {+ uint32_t bit;+ const char* name;+};+constexpr ChannelName kChannelNames[] = {{kSetMask, "mask"}, {kSetPolygroups, "polygroups"}, {kSetPaint, "paint"},+ {kSetVisibility, "visibility"}, {kSetUvs, "uvs"}, {kSetMorph, "morph"}};++// --- Little-endian bytes ---++struct Out {+ std::vector<uint8_t> b;+ void u32(uint32_t v) {+ for (int i = 0; i < 4; ++i) b.push_back(uint8_t(v >> (8 * i)));+ }+ void u64(uint64_t v) {+ for (int i = 0; i < 8; ++i) b.push_back(uint8_t(v >> (8 * i)));+ }+ void words(const void* p, size_t n) { // n 32-bit values+ if constexpr (std::endian::native == std::endian::little) {+ const size_t at = b.size();+ b.resize(at + n * 4);+ if (n) std::memcpy(b.data() + at, p, n * 4);+ } else {+ const auto* w = static_cast<const uint32_t*>(p);+ for (size_t i = 0; i < n; ++i) u32(w[i]);+ }+ }+ void runs(const std::vector<SetRun>& r) {+ u64(r.size());+ static_assert(sizeof(SetRun) == 8);+ words(r.data(), r.size() * 2);+ }+ void section(uint32_t tag, const Out& payload) {+ u32(tag);+ u64(payload.b.size());+ b.insert(b.end(), payload.b.begin(), payload.b.end());+ }+};++struct In {+ const uint8_t* p = nullptr;+ size_t n = 0, at = 0;+ bool left(size_t bytes) const { return bytes <= n - at; }+ bool u32(uint32_t& v) {+ if (!left(4)) return false;+ v = uint32_t(p[at]) | uint32_t(p[at + 1]) << 8 | uint32_t(p[at + 2]) << 16 | uint32_t(p[at + 3]) << 24;+ at += 4;+ return true;+ }+ bool u64(uint64_t& v) {+ uint32_t lo = 0, hi = 0;+ if (!u32(lo) || !u32(hi)) return false;+ v = uint64_t(lo) | uint64_t(hi) << 32;+ return true;+ }+ // `count` 32-bit values into `out` (resized), refusing counts the remaining bytes can't hold.+ template <class T>+ bool words(uint64_t count, size_t perElement, std::vector<T>& out) {+ static_assert(sizeof(T) % 4 == 0);+ if (perElement * 4 != sizeof(T) || count > (n - at) / sizeof(T)) return false;+ out.resize(size_t(count));+ const size_t bytes = size_t(count) * sizeof(T);+ if constexpr (std::endian::native == std::endian::little) {+ if (bytes) std::memcpy(out.data(), p + at, bytes);+ at += bytes;+ } else {+ auto* w = reinterpret_cast<uint32_t*>(out.data());+ for (size_t i = 0; i < size_t(count) * perElement; ++i) u32(w[i]);+ }+ return true;+ }+ bool runs(std::vector<SetRun>& r) {+ uint64_t count = 0;+ return u64(count) && words(count, 2, r);+ }+};++// Runs of the elements [0, n) for which on(i) holds.+template <class On>+std::vector<SetRun> runsOf(size_t n, On on) {+ std::vector<SetRun> out;+ for (size_t i = 0; i < n;) {+ if (!on(i)) {+ ++i;+ continue;+ }+ size_t j = i + 1;+ while (j < n && on(j)) ++j;+ out.push_back({uint32_t(i), uint32_t(j - i)});+ i = j;+ }+ return out;+}++// Runs in ascending order, not overlapping, inside [0, count); returns how many elements they cover.+bool runsValid(const std::vector<SetRun>& runs, uint64_t count, uint64_t& covered) {+ uint64_t end = 0;+ covered = 0;+ for (const SetRun& r : runs) {+ if (r.length == 0 || r.start < end || uint64_t(r.start) + r.length > count) return false;+ end = uint64_t(r.start) + r.length;+ covered += r.length;+ }+ return true;+}++// Fills the set's channels from arrays (null = the default everywhere: unmasked, group 0, white, shown).+void encodeChannels(SelectionSet& s, const float* mask, const uint32_t* groups, const glm::vec3* colors,+ const uint8_t* hidden, const std::vector<glm::vec2>* uvs, const std::vector<glm::vec3>* positions) {+ const size_t nv = s.vertexCount, nt = s.triangleCount;+ if (s.has(kSetMask) && mask) {+ s.maskRuns = runsOf(nv, [&](size_t v) { return mask[v] != 0.0f; });+ bool ones = true;+ for (const SetRun& r : s.maskRuns)+ for (uint32_t k = 0; k < r.length && ones; ++k) ones = mask[r.start + k] == 1.0f;+ if (!ones)+ for (const SetRun& r : s.maskRuns) s.maskValues.insert(s.maskValues.end(), mask + r.start, mask + r.start + r.length);+ }+ if (s.has(kSetPolygroups)) {+ for (size_t t = 0; t < nt;) {+ const uint32_t id = groups ? groups[t] : 0u;+ size_t u = t + 1;+ while (u < nt && (groups ? groups[u] : 0u) == id) ++u;+ s.groupRuns.push_back({id, uint32_t(u - t)});+ t = u;+ }+ }+ if (s.has(kSetPaint) && colors) {+ s.paintRuns = runsOf(nv, [&](size_t v) { return colors[v] != kWhite; });+ for (const SetRun& r : s.paintRuns) s.paintValues.insert(s.paintValues.end(), colors + r.start, colors + r.start + r.length);+ }+ if (s.has(kSetVisibility) && hidden) s.hiddenRuns = runsOf(nt, [&](size_t t) { return hidden[t] != 0; });+ if (s.has(kSetUvs) && uvs) s.uvs = *uvs;+ if (s.has(kSetMorph) && positions) s.positions = *positions;+}++bool validName(const std::string& name, std::string& error) {+ if (name.empty()) {+ error = "A selection set needs a name";+ return false;+ }+ if (name.size() > kMaxNameBytes) {+ error = "Selection set names are at most " + std::to_string(kMaxNameBytes) + " bytes";+ return false;+ }+ for (unsigned char c : name)+ if (c < 0x20 || c == 0x7f) {+ error = "Selection set names can't hold control characters";+ return false;+ }+ return true;+}++std::string quote(const std::string& name) { return "'" + name + "'"; }++// The level of the mesh's stack whose counts the set has: the current one when it fits, else the one it was+// stored at, else any. -1 = none (another mesh, or the topology changed).+int setLevel(const Mesh& mesh, const SelectionSet& s) {+ const int cur = subdivCurrentLevel(mesh), n = subdivLevelCount(mesh);+ if (mesh.vertexCount() == s.vertexCount && mesh.triangleCount() == s.triangleCount) return cur;+ auto fits = [&](int k) {+ return k != cur && subdivLevelData(mesh, k).vertexCount() == s.vertexCount &&+ subdivLevel(mesh, k).triangleCount() == s.triangleCount;+ };+ if (n == 0) return -1;+ if (s.level >= 0 && s.level < n && fits(s.level)) return s.level;+ for (int k = 0; k < n; ++k)+ if (fits(k)) return k;+ return -1;+}++std::shared_ptr<SelectionSetList> editableList(const Mesh& mesh) {+ return mesh.selectionSets ? std::make_shared<SelectionSetList>(*mesh.selectionSets) : std::make_shared<SelectionSetList>();+}++// Makes `list` the active Part's (one undo step).+void commitList(Document& doc, std::shared_ptr<SelectionSetList> list, std::string label) {+ UndoRecord r;+ r.label = std::move(label);+ r.sets = std::make_unique<SelectionSetsUndo>();+ r.sets->list = doc.mesh.selectionSets;+ if (list->sets.empty()) list->morphTarget.clear();+ doc.mesh.selectionSets = list->sets.empty() ? nullptr : std::shared_ptr<const SelectionSetList>(std::move(list));+ doc.undo.push(std::move(r));+}++const SelectionSet* findSet(const Document& doc, const std::string& name, std::string& error) {+ const SelectionSetList* list = doc.mesh.selectionSets.get();+ const int i = list ? list->find(name) : -1;+ if (i < 0) {+ error = "No selection set " + quote(name) + (list && !list->sets.empty() ? "" : " (this Part has no sets yet)");+ return nullptr;+ }+ return list->sets[size_t(i)].get();+}++std::string uniqueSetName(const Mesh& mesh, const std::string& wanted) {+ const SelectionSetList* list = mesh.selectionSets.get();+ if (!list || list->find(wanted) < 0) return wanted;+ for (int k = 2;; ++k) {+ std::string candidate = wanted + " " + std::to_string(k);+ if (list->find(candidate) < 0) return candidate;+ }+}++// Moves the active Part's surface `amount` of the way to `target` (scaled by vertexInfluence: mask and hidden+// faces), recording the old values in `r`. Returns the vertices moved.+size_t applyShape(Document& doc, const std::vector<glm::vec3>& target, float amount, UndoRecord& r, std::string& error) {+ Mesh& m = doc.mesh;+ if (target.size() != m.vertexCount()) return 0;+ const int layer = doc.activeLayer >= 0 && doc.activeLayer < int(m.layers.size()) ? doc.activeLayer : -1;+ const float weight = m.layerTargetWeight(layer);+ if (std::abs(weight) < 1e-6f) {+ error = "The active sculpt layer's weight is 0, so its offsets would not show";+ return 0;+ }+ const bool layered = !m.layers.empty();+ std::vector<glm::vec3>& channel = m.layerTarget(layer);+ r.layer = layer;+ for (uint32_t v = 0; v < m.vertexCount(); ++v) {+ const float k = vertexInfluence(m, v) * amount;+ if (k == 0.0f) continue;+ const glm::vec3 d = (target[v] - m.positions[v]) * k;+ if (d == glm::vec3(0.0f)) continue;+ r.positions.add(v, channel[v]);+ if (layered) channel[v] += d / weight;+ else m.positions[v] += d;+ }+ const std::vector<uint32_t>& moved = r.positions.indices;+ if (moved.empty()) return 0;+ if (layered) m.evaluate(moved);+ m.updateNormals(moved);+ for (uint32_t v : moved) m.markDirty(v);+ if (moved.size() * 4 > m.vertexCount()) doc.bvh.refitAll(m);+ else doc.bvh.refit(m, moved);+ return moved.size();+}++} // namespace++// --- Channels and operations ---++bool parseSetChannels(const std::string& text, uint32_t& out, std::string& error) {+ out = 0;+ std::string word;+ auto take = [&]() {+ if (word.empty()) return true;+ std::string w;+ for (char c : word) w += char(std::tolower(static_cast<unsigned char>(c)));+ word.clear();+ if (w == "all") out |= kSetAllChannels;+ else if (w == "mask") out |= kSetMask;+ else if (w == "polygroups" || w == "groups" || w == "polygroup") out |= kSetPolygroups;+ else if (w == "paint" || w == "colors" || w == "colours" || w == "polypaint" || w == "vertex_paint") out |= kSetPaint;+ else if (w == "visibility" || w == "hidden" || w == "visible") out |= kSetVisibility;+ else if (w == "uvs" || w == "uv") out |= kSetUvs;+ else if (w == "morph" || w == "shape" || w == "positions") out |= kSetMorph;+ else {+ error = "Unknown channel '" + w + "' (use mask, polygroups, paint, visibility, uvs, morph or all)";+ return false;+ }+ return true;+ };+ for (char c : text) {+ if (c == ',' || c == ' ' || c == '+' || c == '|' || c == ';') {+ if (!take()) return false;+ } else {+ word += c;+ }+ }+ return take();+}++std::string setChannelNames(uint32_t channels) {+ std::string out;+ for (const auto& c : kChannelNames)+ if (channels & c.bit) out += (out.empty() ? "" : ", ") + std::string(c.name);+ return out.empty() ? "nothing" : out;+}++bool parseSetOp(const std::string& text, SetOp& out) {+ std::string w;+ for (char c : text) w += char(std::tolower(static_cast<unsigned char>(c)));+ if (w.empty() || w == "replace") out = SetOp::Replace;+ else if (w == "union" || w == "add" || w == "+") out = SetOp::Union;+ else if (w == "intersect" || w == "intersection" || w == "&") out = SetOp::Intersect;+ else if (w == "subtract" || w == "difference" || w == "-") out = SetOp::Subtract;+ else return false;+ return true;+}++const char* setOpName(SetOp op) {+ switch (op) {+ case SetOp::Union: return "union";+ case SetOp::Intersect: return "intersect";+ case SetOp::Subtract: return "subtract";+ default: return "replace";+ }+}++void combineMask(std::vector<float>& current, const std::vector<float>& other, SetOp op) {+ if (current.size() != other.size()) current.resize(other.size(), 0.0f);+ for (size_t v = 0; v < other.size(); ++v) {+ const float a = current[v], b = other[v];+ switch (op) {+ case SetOp::Replace: current[v] = b; break;+ case SetOp::Union: current[v] = std::max(a, b); break;+ case SetOp::Intersect: current[v] = std::min(a, b); break;+ case SetOp::Subtract: current[v] = std::min(a, 1.0f - b); break;+ }+ }+}++void combineHidden(std::vector<uint8_t>& current, const std::vector<uint8_t>& other, SetOp op) {+ if (current.size() != other.size()) current.resize(other.size(), 0);+ for (size_t t = 0; t < other.size(); ++t) {+ const bool a = current[t] == 0, b = other[t] == 0; // shown+ bool shown = b;+ switch (op) {+ case SetOp::Replace: shown = b; break;+ case SetOp::Union: shown = a || b; break;+ case SetOp::Intersect: shown = a && b; break;+ case SetOp::Subtract: shown = a && !b; break;+ }+ current[t] = shown ? 0 : 1;+ }+}++// --- Sets ---++size_t SelectionSet::bytes() const {+ return sizeof(SelectionSet) + name.size() ++ (maskRuns.size() + groupRuns.size() + paintRuns.size() + hiddenRuns.size()) * sizeof(SetRun) ++ maskValues.size() * sizeof(float) + paintValues.size() * sizeof(glm::vec3) + uvs.size() * sizeof(glm::vec2) ++ positions.size() * sizeof(glm::vec3);+}++int SelectionSetList::find(const std::string& name) const {+ for (size_t i = 0; i < sets.size(); ++i)+ if (sets[i]->name == name) return int(i);+ return -1;+}++size_t SelectionSetList::bytes() const {+ size_t total = 0;+ for (const auto& s : sets) total += s->bytes();+ return total;+}++SelectionSet captureSelectionSet(const Mesh& mesh, std::string name, uint32_t channels) {+ SelectionSet s;+ s.name = std::move(name);+ s.channels = channels & kSetAllChannels;+ if (!mesh.hasUvs() || mesh.uvs.size() != mesh.triangleCount() * 3) s.channels &= ~uint32_t(kSetUvs);+ s.level = subdivCurrentLevel(mesh);+ s.vertexCount = uint32_t(mesh.vertexCount());+ s.triangleCount = uint32_t(mesh.triangleCount());+ encodeChannels(s, mesh.hasMask() ? mesh.mask.data() : nullptr, mesh.hasPolygroups() ? mesh.polygroups.data() : nullptr,+ mesh.hasColors() ? mesh.colors.data() : nullptr, mesh.hasHidden() ? mesh.hidden.data() : nullptr,+ &mesh.uvs, &mesh.positions);+ return s;+}++bool makeSelectionSet(std::string name, const SelectionSetData& d, uint32_t vertexCount, uint32_t triangleCount, int level,+ SelectionSet& out, std::string& error) {+ if (!validName(name, error)) return false;+ auto check = [&](uint32_t bit, size_t have, size_t want, const char* what) {+ if (!(d.channels & bit) || have == want) return true;+ error = std::string(what) + ": expected " + std::to_string(want) + " values, got " + std::to_string(have);+ return false;+ };+ if (!check(kSetMask, d.mask.size(), vertexCount, "mask") ||+ !check(kSetPolygroups, d.polygroups.size(), triangleCount, "polygroups") ||+ !check(kSetPaint, d.colors.size(), vertexCount, "paint") ||+ !check(kSetVisibility, d.hidden.size(), triangleCount, "hidden") ||+ !check(kSetUvs, d.uvs.size(), size_t(triangleCount) * 3, "uvs") ||+ !check(kSetMorph, d.positions.size(), vertexCount, "positions"))+ return false;+ out = SelectionSet{};+ out.name = std::move(name);+ out.channels = d.channels & kSetAllChannels;+ out.level = level;+ out.vertexCount = vertexCount;+ out.triangleCount = triangleCount;+ encodeChannels(out, d.mask.empty() ? nullptr : d.mask.data(), d.polygroups.empty() ? nullptr : d.polygroups.data(),+ d.colors.empty() ? nullptr : d.colors.data(), d.hidden.empty() ? nullptr : d.hidden.data(), &d.uvs,+ &d.positions);+ return true;+}++void decodeSelectionSet(const SelectionSet& s, uint32_t channels, SelectionSetData& out) {+ out = SelectionSetData{};+ out.channels = channels & s.channels;+ if (out.channels & kSetMask) {+ out.mask.assign(s.vertexCount, 0.0f);+ size_t k = 0;+ for (const SetRun& r : s.maskRuns)+ for (uint32_t i = 0; i < r.length; ++i) out.mask[r.start + i] = s.maskValues.empty() ? 1.0f : s.maskValues[k++];+ }+ if (out.channels & kSetPolygroups) {+ out.polygroups.reserve(s.triangleCount);+ for (const SetRun& r : s.groupRuns) out.polygroups.insert(out.polygroups.end(), r.length, r.start);+ out.polygroups.resize(s.triangleCount, 0u);+ }+ if (out.channels & kSetPaint) {+ out.colors.assign(s.vertexCount, kWhite);+ size_t k = 0;+ for (const SetRun& r : s.paintRuns)+ for (uint32_t i = 0; i < r.length; ++i) out.colors[r.start + i] = s.paintValues[k++];+ }+ if (out.channels & kSetVisibility) {+ out.hidden.assign(s.triangleCount, 0);+ for (const SetRun& r : s.hiddenRuns) std::fill_n(out.hidden.begin() + r.start, r.length, uint8_t(1));+ }+ if (out.channels & kSetUvs) out.uvs = s.uvs;+ if (out.channels & kSetMorph) out.positions = s.positions;+}++bool selectionSetFits(const Mesh& mesh, const SelectionSet& s) { return setLevel(mesh, s) >= 0; }++bool selectionSetAt(const Mesh& mesh, const SelectionSet& s, uint32_t channels, SelectionSetData& out, std::string& error) {+ const int from = setLevel(mesh, s), to = subdivCurrentLevel(mesh);+ if (from < 0) {+ error = "Selection set " + quote(s.name) + " was stored on a mesh with " + std::to_string(s.vertexCount) ++ " vertices and " + std::to_string(s.triangleCount) + " triangles; this Part has " ++ std::to_string(mesh.vertexCount()) + " and " + std::to_string(mesh.triangleCount()) ++ (subdivLevelCount(mesh) ? " at this level, and no level of it fits" : "");+ return false;+ }+ decodeSelectionSet(s, channels, out);+ if (from == to) return true;+ bool ok = true;+ if (!out.mask.empty()) ok &= subdivMapVertices(mesh, from, to, out.mask);+ if (!out.colors.empty()) ok &= subdivMapVertices(mesh, from, to, out.colors, kWhite, false);+ if (!out.polygroups.empty()) ok &= subdivMapTriangles(mesh, from, to, out.polygroups);+ if (!out.hidden.empty()) ok &= subdivMapTriangles(mesh, from, to, out.hidden);+ if (!out.uvs.empty()) ok &= subdivMapCorners(mesh, from, to, out.uvs);+ if (!out.positions.empty()) {+ // The shape as an offset from level `from`'s own shape, carried through the levels' stencils and added to+ // this level's: the detail of the levels in between stays.+ const Mesh at = subdivLevelMesh(mesh, from);+ if (at.vertexCount() != out.positions.size()) {+ ok = false;+ } else {+ for (size_t v = 0; v < out.positions.size(); ++v) out.positions[v] -= at.positions[v];+ ok &= subdivMapVertices(mesh, from, to, out.positions, glm::vec3(0.0f), true);+ if (out.positions.size() == mesh.vertexCount())+ for (size_t v = 0; v < out.positions.size(); ++v) out.positions[v] += mesh.positions[v];+ }+ }+ if (!ok || (!out.mask.empty() && out.mask.size() != mesh.vertexCount()) ||+ (!out.positions.empty() && out.positions.size() != mesh.vertexCount()) ||+ (!out.hidden.empty() && out.hidden.size() != mesh.triangleCount())) {+ error = "Selection set " + quote(s.name) + " could not be carried to this subdivision level";+ return false;+ }+ return true;+}++// --- Binary form ---++std::vector<uint8_t> packSelectionSet(const SelectionSet& s) {+ Out o;+ o.u32(kPackMagic);+ o.u32(kPackVersion);+ o.u32(s.channels);+ o.u32(s.vertexCount);+ o.u32(s.triangleCount);+ o.u32(uint32_t(s.level));+ o.u32(uint32_t(s.name.size()));+ o.b.insert(o.b.end(), s.name.begin(), s.name.end());+ if (s.has(kSetMask)) {+ Out p;+ p.runs(s.maskRuns);+ p.u32(s.maskValues.empty() ? 1u : 0u);+ p.words(s.maskValues.data(), s.maskValues.size());+ o.section(kSetMask, p);+ }+ if (s.has(kSetPolygroups)) {+ Out p;+ p.runs(s.groupRuns);+ o.section(kSetPolygroups, p);+ }+ if (s.has(kSetPaint)) {+ Out p;+ p.runs(s.paintRuns);+ p.words(s.paintValues.data(), s.paintValues.size() * 3);+ o.section(kSetPaint, p);+ }+ if (s.has(kSetVisibility)) {+ Out p;+ p.runs(s.hiddenRuns);+ o.section(kSetVisibility, p);+ }+ if (s.has(kSetUvs)) {+ Out p;+ p.u64(s.uvs.size());+ p.words(s.uvs.data(), s.uvs.size() * 2);+ o.section(kSetUvs, p);+ }+ if (s.has(kSetMorph)) {+ Out p;+ p.u64(s.positions.size());+ p.words(s.positions.data(), s.positions.size() * 3);+ o.section(kSetMorph, p);+ }+ return std::move(o.b);+}++bool unpackSelectionSet(const uint8_t* data, size_t size, SelectionSet& out, std::string& error) {+ In in{data, size, 0};+ uint32_t magic = 0, version = 0, channels = 0, nv = 0, nt = 0, level = 0, nameBytes = 0;+ if (!in.u32(magic) || magic != kPackMagic || !in.u32(version)) {+ error = "not a selection set";+ return false;+ }+ if (version > kPackVersion) {+ error = "saved by a newer SculptForge (set format " + std::to_string(version) + ")";+ return false;+ }+ if (!in.u32(channels) || !in.u32(nv) || !in.u32(nt) || !in.u32(level) || !in.u32(nameBytes) ||+ nameBytes > kMaxNameBytes || !in.left(nameBytes)) {+ error = "the set's header is damaged";+ return false;+ }+ SelectionSet s;+ s.name.assign(reinterpret_cast<const char*>(data + in.at), nameBytes);+ in.at += nameBytes;+ s.channels = channels & kSetAllChannels;+ s.vertexCount = nv;+ s.triangleCount = nt;+ s.level = int(std::min<uint32_t>(level, 64));+ if (!validName(s.name, error)) return false;+ uint32_t found = 0;+ auto bad = [&](const char* what) {+ error = std::string("the set's ") + what + " is damaged";+ return false;+ };+ while (in.at < in.n) {+ uint32_t tag = 0;+ uint64_t length = 0;+ if (!in.u32(tag) || !in.u64(length) || !in.left(size_t(std::min<uint64_t>(length, SIZE_MAX)))) return bad("data");+ In p{data + in.at, size_t(length), 0};+ in.at += size_t(length);+ if (!(s.channels & tag) || (found & tag)) continue; // unknown or repeated sections are skipped+ found |= tag;+ uint64_t covered = 0;+ if (tag == kSetMask) {+ uint32_t ones = 0;+ if (!p.runs(s.maskRuns) || !runsValid(s.maskRuns, nv, covered) || !p.u32(ones) ||+ (!ones && !p.words(covered, 1, s.maskValues)))+ return bad("mask");+ } else if (tag == kSetPolygroups) {+ if (!p.runs(s.groupRuns)) return bad("polygroups");+ uint64_t total = 0;+ for (const SetRun& r : s.groupRuns) total += r.length;+ if (total != nt) return bad("polygroups");+ } else if (tag == kSetPaint) {+ if (!p.runs(s.paintRuns) || !runsValid(s.paintRuns, nv, covered) || !p.words(covered, 3, s.paintValues))+ return bad("paint");+ } else if (tag == kSetVisibility) {+ if (!p.runs(s.hiddenRuns) || !runsValid(s.hiddenRuns, nt, covered)) return bad("visibility");+ } else if (tag == kSetUvs) {+ uint64_t count = 0;+ if (!p.u64(count) || count != uint64_t(nt) * 3 || !p.words(count, 2, s.uvs)) return bad("UVs");+ } else if (tag == kSetMorph) {+ uint64_t count = 0;+ if (!p.u64(count) || count != nv || !p.words(count, 3, s.positions)) return bad("shape");+ }+ }+ if (found != s.channels) return bad("channel list");+ out = std::move(s);+ return true;+}++Json selectionSetSummary(const SelectionSet& s) {+ Json j = Json::object();+ j.set("name", s.name);+ Json channels = Json::array();+ for (const auto& c : kChannelNames)+ if (s.channels & c.bit) channels.push(c.name);+ j.set("channels", std::move(channels));+ j.set("level", s.level);+ j.set("vertex_count", double(s.vertexCount));+ j.set("triangle_count", double(s.triangleCount));+ j.set("bytes", double(s.bytes()));+ return j;+}++bool saveSelectionSets(const std::string& path, const SelectionSetList& list, std::string& error) {+ Json manifest = Json::object();+ manifest.set("format", kSetsFormat);+ manifest.set("version", kSetsFileVersion);+ if (!list.morphTarget.empty()) manifest.set("morph_target", list.morphTarget);+ Json sets = Json::array();+ std::vector<ZipEntry> entries;+ entries.push_back({"manifest.json", {}});+ for (size_t i = 0; i < list.sets.size(); ++i) {+ Json j = selectionSetSummary(*list.sets[i]);+ const std::string file = "sets/" + std::to_string(i) + ".bin";+ j.set("data", file);+ sets.push(std::move(j));+ entries.push_back({file, packSelectionSet(*list.sets[i])});+ }+ manifest.set("sets", std::move(sets));+ const std::string text = manifest.dump(true);+ entries[0].data.assign(text.begin(), text.end());+ return writeStoredZip(path, entries, 4, error);+}++bool loadSelectionSets(const std::string& path, SelectionSetList& out, std::string& error) {+ std::vector<ZipEntry> entries;+ if (!readStoredZip(path, entries, error)) return false;+ auto entry = [&](const std::string& name) -> const ZipEntry* {+ for (const auto& e : entries)+ if (e.name == name) return &e;+ return nullptr;+ };+ const ZipEntry* m = entry("manifest.json");+ Json manifest;+ if (!m || !Json::parse(std::string(m->bytes(), m->bytes() + m->size()), manifest, error) || !manifest.isObject() ||+ manifest["format"].asString() != kSetsFormat) {+ error = path + " is not a SculptForge selection sets file";+ return false;+ }+ if (manifest["version"].asNumber(0) > kSetsFileVersion) {+ error = path + " was saved by a newer SculptForge; please update to open it";+ return false;+ }+ const Json& sets = manifest["sets"];+ if (!sets.isArray() || sets.size() > kMaxSets) {+ error = path + " has no valid set list";+ return false;+ }+ SelectionSetList list;+ for (const Json& j : sets.items()) {+ const ZipEntry* e = entry(j["data"].asString());+ SelectionSet s;+ std::string why;+ if (!e || !unpackSelectionSet(e->bytes(), e->size(), s, why)) {+ error = path + ": set " + quote(j["name"].asString()) + " is unreadable" + (why.empty() ? "" : " (" + why + ")");+ return false;+ }+ if (list.find(s.name) >= 0) continue;+ list.sets.push_back(std::make_shared<const SelectionSet>(std::move(s)));+ }+ list.morphTarget = manifest["morph_target"].asString();+ if (list.find(list.morphTarget) < 0) list.morphTarget.clear();+ out = std::move(list);+ return true;+}++// --- Document operations ---++bool addSelectionSet(Document& doc, SelectionSet set, const std::string& label, std::string& message) {+ if (!validName(set.name, message)) return false;+ auto list = editableList(doc.mesh);+ const std::string name = set.name;+ const uint32_t channels = set.channels;+ const size_t bytes = set.bytes();+ auto shared = std::make_shared<const SelectionSet>(std::move(set));+ const int at = list->find(name);+ if (at >= 0) list->sets[size_t(at)] = std::move(shared);+ else list->sets.push_back(std::move(shared));+ if (list->morphTarget == name && !(channels & kSetMorph)) list->morphTarget.clear();+ commitList(doc, std::move(list), label);+ std::ostringstream s;+ s << (at >= 0 ? "Replaced" : "Stored") << " selection set " << quote(name) << " (" << setChannelNames(channels);+ if (subdivLevelCount(doc.mesh)) s << ", at " << subdivLevelText(doc.mesh);+ s << ", " << (bytes + 1023) / 1024 << " KB)";+ message = s.str();+ return true;+}++bool storeSelectionSet(Document& doc, const std::string& name, uint32_t channels, std::string& message) {+ if (!validName(name, message)) return false;+ if (!(channels & kSetAllChannels)) {+ message = "Choose at least one channel to store";+ return false;+ }+ SelectionSet s = captureSelectionSet(doc.mesh, name, channels);+ std::string note;+ if ((channels & kSetUvs) && !s.has(kSetUvs)) note = "; this Part has no UVs, so none were stored";+ if (!s.channels) {+ message = "This Part has no UVs to store";+ return false;+ }+ if (!addSelectionSet(doc, std::move(s), "Store set " + name, message)) return false;+ message += note;+ return true;+}++bool restoreSelectionSet(Document& doc, const std::string& name, uint32_t channels, SetOp op, std::string& message) {+ const SelectionSet* s = findSet(doc, name, message);+ if (!s) return false;+ const uint32_t wanted = channels ? channels : s->channels & ~uint32_t(kSetMorph);+ const uint32_t use = wanted & s->channels;+ if (!use) {+ message = "Selection set " + quote(name) + " holds " + setChannelNames(s->channels) + ", not " + setChannelNames(wanted);+ return false;+ }+ SelectionSetData d;+ if (!selectionSetAt(doc.mesh, *s, use, d, message)) return false;+ Mesh& m = doc.mesh;+ UndoRecord r;+ r.label = "Restore set " + name;+ if (use & kSetMask) {+ std::vector<float> next = d.mask;+ if (op != SetOp::Replace) {+ next = m.hasMask() ? m.mask : std::vector<float>(m.vertexCount(), 0.0f);+ combineMask(next, d.mask, op);+ }+ for (uint32_t v = 0; v < m.vertexCount(); ++v)+ if (m.maskAt(v) != next[v]) r.mask.add(v, m.maskAt(v));+ if (!r.mask.empty()) {+ std::vector<float>& mask = m.ensureMask();+ for (uint32_t v : r.mask.indices) {+ mask[v] = next[v];+ m.markDirty(v);+ }+ }+ }+ if (use & kSetVisibility) {+ std::vector<uint8_t> next = d.hidden;+ if (op != SetOp::Replace) {+ next.assign(m.triangleCount(), 0);+ for (uint32_t t = 0; t < m.triangleCount(); ++t) next[t] = m.triangleHidden(t);+ combineHidden(next, d.hidden, op);+ }+ for (uint32_t t = 0; t < m.triangleCount(); ++t)+ if (uint8_t(m.triangleHidden(t)) != next[t]) r.hidden.add(t, uint8_t(m.triangleHidden(t)));+ if (!r.hidden.empty()) {+ std::vector<uint8_t>& hidden = m.ensureHidden();+ for (uint32_t t : r.hidden.indices) hidden[t] = next[t];+ m.facesDirty = true;+ }+ }+ if (use & kSetPolygroups) {+ for (uint32_t t = 0; t < m.triangleCount(); ++t)+ if (m.polygroupAt(t) != d.polygroups[t]) r.polygroups.add(t, m.polygroupAt(t));+ if (!r.polygroups.empty()) {+ std::vector<uint32_t>& groups = m.ensurePolygroups();+ for (uint32_t t : r.polygroups.indices) groups[t] = d.polygroups[t];+ m.facesDirty = true;+ }+ }+ if (use & kSetPaint) {+ // Without paint layers into the vertex paint itself; with them into the Base layer (undo: paintLayer -1).+ const bool layered = !m.paintLayers.empty();+ r.paintLayer = -1;+ for (uint32_t v = 0; v < m.vertexCount(); ++v) {+ const glm::vec3 old = layered ? m.paintBase[v] : m.colorAt(v);+ if (old != d.colors[v]) r.colors.add(v, old);+ }+ if (!r.colors.empty()) {+ std::vector<glm::vec3>& target = layered ? m.paintBase : m.ensureColors();+ for (uint32_t v : r.colors.indices) target[v] = d.colors[v];+ compositePaint(m, r.colors.indices);+ }+ }+ if (use & kSetUvs) {+ const bool had = m.uvs.size() == m.triangleCount() * 3;+ for (uint32_t c = 0; c < d.uvs.size(); ++c) {+ const glm::vec2 old = had ? m.uvs[c] : glm::vec2(0.0f);+ if (!had || old != d.uvs[c]) r.uvs.add(c, old);+ }+ if (!r.uvs.empty()) {+ m.uvs = d.uvs;+ m.facesDirty = true;+ m.topologyDirty = true;+ }+ }+ if (use & kSetMorph) {+ std::string err;+ applyShape(doc, d.positions, 1.0f, r, err);+ if (!err.empty()) {+ message = err;+ r.positions = {};+ }+ }+ const bool changed = !r.empty();+ if (changed) doc.undo.push(std::move(r));+ message = (changed ? "Restored selection set " : "Selection set ") + quote(name) + (changed ? " (" : " already matches (") ++ setChannelNames(use) + (op != SetOp::Replace && (use & (kSetMask | kSetVisibility)) ? ", " + std::string(setOpName(op)) : "") ++ (subdivLevelCount(m) && s->level != subdivCurrentLevel(m) ? ", carried to " + subdivLevelText(m) : "") + ")";+ if ((wanted & ~s->channels) && channels) message += "; the set holds no " + setChannelNames(wanted & ~s->channels);+ return true;+}++bool renameSelectionSet(Document& doc, const std::string& name, const std::string& to, std::string& message) {+ if (!findSet(doc, name, message) || !validName(to, message)) return false;+ if (name == to) {+ message = "Selection set " + quote(name) + " already has that name";+ return true;+ }+ auto list = editableList(doc.mesh);+ if (list->find(to) >= 0) {+ message = "There is already a selection set " + quote(to);+ return false;+ }+ const int i = list->find(name);+ auto renamed = std::make_shared<SelectionSet>(*list->sets[size_t(i)]);+ renamed->name = to;+ list->sets[size_t(i)] = std::move(renamed);+ if (list->morphTarget == name) list->morphTarget = to;+ commitList(doc, std::move(list), "Rename set " + name);+ message = "Renamed selection set " + quote(name) + " to " + quote(to);+ return true;+}++bool deleteSelectionSet(Document& doc, const std::string& name, std::string& message) {+ if (!findSet(doc, name, message)) return false;+ auto list = editableList(doc.mesh);+ list->sets.erase(list->sets.begin() + list->find(name));+ if (list->morphTarget == name) list->morphTarget.clear();+ commitList(doc, std::move(list), "Delete set " + name);+ message = "Deleted selection set " + quote(name);+ return true;+}++bool combineSelectionSets(Document& doc, const std::string& a, const std::string& b, SetOp op, const std::string& into,+ std::string& message) {+ const SelectionSet* sa = findSet(doc, a, message);+ const SelectionSet* sb = sa ? findSet(doc, b, message) : nullptr;+ if (!sb) return false;+ if (op == SetOp::Replace) {+ message = "Combine with union, intersect or subtract";+ return false;+ }+ const uint32_t channels = sa->channels & sb->channels & (kSetMask | kSetVisibility);+ if (!channels) {+ message = "Sets combine by their mask and visibility, and " + quote(a) + " and " + quote(b) + " don't share either";+ return false;+ }+ SelectionSetData da, db;+ if (!selectionSetAt(doc.mesh, *sa, channels, da, message) || !selectionSetAt(doc.mesh, *sb, channels, db, message)) return false;+ if (channels & kSetMask) combineMask(da.mask, db.mask, op);+ if (channels & kSetVisibility) combineHidden(da.hidden, db.hidden, op);+ const char* sign = op == SetOp::Union ? " + " : op == SetOp::Intersect ? " & " : " - ";+ const std::string name = into.empty() ? uniqueSetName(doc.mesh, a + sign + b) : into;+ SelectionSet out;+ if (!makeSelectionSet(name, da, uint32_t(doc.mesh.vertexCount()), uint32_t(doc.mesh.triangleCount()),+ subdivCurrentLevel(doc.mesh), out, message))+ return false;+ return addSelectionSet(doc, std::move(out), std::string("Combine sets (") + setOpName(op) + ")", message);+}++bool morphToSelectionSet(Document& doc, const std::string& name, float amount, std::string& message) {+ const SelectionSet* s = findSet(doc, name, message);+ if (!s) return false;+ if (!s->has(kSetMorph)) {+ message = "Selection set " + quote(name) + " holds no shape (store it with the morph channel)";+ return false;+ }+ SelectionSetData d;+ if (!selectionSetAt(doc.mesh, *s, kSetMorph, d, message)) return false;+ UndoRecord r;+ r.label = "Morph to set " + name;+ std::string err;+ const size_t moved = applyShape(doc, d.positions, std::clamp(amount, -1.0f, 1.0f), r, err);+ if (!err.empty()) {+ message = err;+ return false;+ }+ if (!moved) {+ message = "The surface already matches selection set " + quote(name) + " (or it is all masked)";+ return true;+ }+ doc.undo.push(std::move(r));+ char buf[160];+ std::snprintf(buf, sizeof buf, "Morphed %zu vertices %.0f%% of the way to selection set ", moved, double(amount) * 100.0);+ message = buf + quote(name);+ return true;+}++bool setMorphTarget(Document& doc, const std::string& name, std::string& message) {+ if (name.empty()) {+ if (!doc.mesh.selectionSets || doc.mesh.selectionSets->morphTarget.empty()) {+ message = "No morph target to clear";+ return true;+ }+ auto list = editableList(doc.mesh);+ list->morphTarget.clear();+ commitList(doc, std::move(list), "Clear morph target");+ message = "The Morph brush has no target now";+ return true;+ }+ const SelectionSet* s = findSet(doc, name, message);+ if (!s) return false;+ if (!s->has(kSetMorph)) {+ message = "Selection set " + quote(name) + " holds no shape (store it with the morph channel)";+ return false;+ }+ if (!selectionSetFits(doc.mesh, *s)) {+ SelectionSetData d;+ selectionSetAt(doc.mesh, *s, kSetMorph, d, message);+ return false;+ }+ if (doc.mesh.selectionSets->morphTarget == name) {+ message = "Selection set " + quote(name) + " is already the morph target";+ return true;+ }+ auto list = editableList(doc.mesh);+ list->morphTarget = name;+ commitList(doc, std::move(list), "Morph target " + name);+ message = "The Morph brush now pulls toward selection set " + quote(name);+ return true;+}++// --- The Morph brush's target (Sculptor, core/Sculpt.h) ---++const std::vector<glm::vec3>* Sculptor::morphTarget(const Mesh& mesh) {+ const SelectionSetList* list = mesh.selectionSets.get();+ const int i = list && !list->morphTarget.empty() ? list->find(list->morphTarget) : -1;+ if (i < 0 || !list->sets[size_t(i)]->has(kSetMorph)) {+ morphSet_.reset();+ morphMapped_.clear();+ return nullptr;+ }+ const std::shared_ptr<const SelectionSet>& set = list->sets[size_t(i)];+ const int level = subdivCurrentLevel(mesh);+ if (set != morphSet_ || level != morphLevel_ || mesh.vertexCount() != morphVertices_) {+ morphSet_ = set;+ morphLevel_ = level;+ morphVertices_ = mesh.vertexCount();+ morphMapped_.clear();+ morphFits_ = false;+ if (set->vertexCount == mesh.vertexCount() && set->triangleCount == mesh.triangleCount()) {+ morphFits_ = true; // stored at this level: used as it is+ } else {+ SelectionSetData d;+ std::string error;+ if (selectionSetAt(mesh, *set, kSetMorph, d, error)) {+ morphMapped_ = std::move(d.positions);+ morphFits_ = true;+ }+ }+ }+ if (!morphFits_) return nullptr;+ return morphMapped_.empty() ? &set->positions : &morphMapped_;+}++// --- Commands ---++namespace {++bool channelsArg(const Args& a, const char* key, uint32_t fallback, uint32_t& out, std::string& error) {+ const std::string text = argString(a, key);+ if (text.empty()) {+ out = fallback;+ return true;+ }+ return parseSetChannels(text, out, error);+}++CommandResult result(bool ok, std::string message) { return {ok, std::move(message)}; }++} // namespace++void registerSelectionSetCommands(CommandRegistry& reg) {+ const std::string channelHelp = "Comma-separated channels: mask, polygroups, paint (vertex paint), visibility (hidden "+ "faces), uvs, morph (the shape), or all";+ reg.add({"selection_set_store",+ "Store a named selection set on the active Part: a snapshot of the channels you choose. Storing again with "+ "the same name replaces it. Sets restore at any subdivision level of the Part and are saved in projects.",+ {{"name", ParamSpec::Type::String, "Set name", true},+ {"channels", ParamSpec::Type::String, channelHelp + " (default mask,visibility)"}},+ [](Document& doc, const Args& a) {+ std::string msg;+ uint32_t channels = 0;+ if (!channelsArg(a, "channels", kSetMask | kSetVisibility, channels, msg)) return result(false, msg);+ const bool ok = storeSelectionSet(doc, argString(a, "name"), channels, msg);+ return result(ok, msg);+ }});+ reg.add({"selection_set_restore",+ "Restore a selection set's channels on the active Part (one undo step), carried to the current subdivision "+ "level. mode combines the mask and visibility with the current ones.",+ {{"name", ParamSpec::Type::String, "Set name", true},+ {"channels", ParamSpec::Type::String,+ channelHelp + " (default: everything the set holds but the shape; include morph to restore the shape)"},+ {"mode", ParamSpec::Type::String, "replace (default), union, intersect or subtract (mask and visibility)"}},+ [](Document& doc, const Args& a) {+ std::string msg;+ uint32_t channels = 0;+ SetOp op = SetOp::Replace;+ if (!channelsArg(a, "channels", 0, channels, msg)) return result(false, msg);+ if (!parseSetOp(argString(a, "mode"), op)) return result(false, "mode is replace, union, intersect or subtract");+ const bool ok = restoreSelectionSet(doc, argString(a, "name"), channels, op, msg);+ return result(ok, msg);+ }});+ reg.add({"selection_set_rename", "Rename a selection set of the active Part.",+ {{"name", ParamSpec::Type::String, "Set name", true}, {"to", ParamSpec::Type::String, "New name", true}},+ [](Document& doc, const Args& a) {+ std::string msg;+ const bool ok = renameSelectionSet(doc, argString(a, "name"), argString(a, "to"), msg);+ return result(ok, msg);+ }});+ reg.add({"selection_set_delete", "Delete a selection set of the active Part (undoable).",+ {{"name", ParamSpec::Type::String, "Set name", true}},+ [](Document& doc, const Args& a) {+ std::string msg;+ const bool ok = deleteSelectionSet(doc, argString(a, "name"), msg);+ return result(ok, msg);+ }});+ reg.add({"selection_set_list", "List the active Part's selection sets with their channels and levels.",+ {{"json", ParamSpec::Type::Bool, "Answer as JSON (for scripts)"}},+ [](Document& doc, const Args& a) {+ const SelectionSetList* list = doc.mesh.selectionSets.get();+ if (argBool(a, "json", false)) {+ Json j = Json::object();+ Json sets = Json::array();+ if (list)+ for (const auto& s : list->sets) {+ Json one = selectionSetSummary(*s);+ one.set("fits", selectionSetFits(doc.mesh, *s));+ sets.push(std::move(one));+ }+ j.set("sets", std::move(sets));+ j.set("morph_target", list ? list->morphTarget : std::string());+ return result(true, j.dump());+ }+ if (!list || list->sets.empty()) return result(true, "No selection sets on this Part");+ std::ostringstream s;+ s << list->sets.size() << " selection set" << (list->sets.size() == 1 ? "" : "s") << ":";+ for (const auto& set : list->sets) {+ s << "\n " << set->name << " (" << setChannelNames(set->channels);+ if (subdivLevelCount(doc.mesh)) s << ", SDiv " << set->level + 1;+ if (!selectionSetFits(doc.mesh, *set)) s << ", doesn't fit this mesh";+ if (set->name == list->morphTarget) s << ", morph target";+ s << ")";+ }+ return result(true, s.str());+ }});+ reg.add({"selection_set_combine",+ "Make a new selection set from two others by their mask and visibility: union, intersect or subtract.",+ {{"a", ParamSpec::Type::String, "First set", true},+ {"b", ParamSpec::Type::String, "Second set", true},+ {"op", ParamSpec::Type::String, "union, intersect or subtract (a minus b)", true},+ {"into", ParamSpec::Type::String, "Name of the new set (default \"a + b\", \"a & b\" or \"a - b\")"}},+ [](Document& doc, const Args& a) {+ std::string msg;+ SetOp op = SetOp::Replace;+ if (!parseSetOp(argString(a, "op"), op) || op == SetOp::Replace)+ return result(false, "op is union, intersect or subtract");+ const bool ok = combineSelectionSets(doc, argString(a, "a"), argString(a, "b"), op, argString(a, "into"), msg);+ return result(ok, msg);+ }});+ reg.add({"selection_set_from_visible",+ "Quick set: store the faces shown right now as a visibility set (named Visible, Visible 2, ... by default).",+ {{"name", ParamSpec::Type::String, "Set name (optional)"}},+ [](Document& doc, const Args& a) {+ std::string name = argString(a, "name");+ if (name.empty()) name = uniqueSetName(doc.mesh, "Visible");+ std::string msg;+ const bool ok = storeSelectionSet(doc, name, kSetVisibility, msg);+ return result(ok, msg);+ }});+ reg.add({"selection_set_morph_target",+ "Make a selection set's shape the Morph brush's target (empty name: none). The set must hold the morph "+ "channel; it works at any subdivision level of the Part.",+ {{"name", ParamSpec::Type::String, "Set name, or empty to clear"}},+ [](Document& doc, const Args& a) {+ std::string msg;+ const bool ok = setMorphTarget(doc, argString(a, "name"), msg);+ return result(ok, msg);+ }});+ reg.add({"selection_set_morph",+ "Morph to Set: move the whole surface toward a selection set's shape by amount (1 = all the way, negative "+ "pushes away), within the mask. One undo step.",+ {{"name", ParamSpec::Type::String, "Set name", true},+ {"amount", ParamSpec::Type::Number, "-1..1 (default 1)"}},+ [](Document& doc, const Args& a) {+ std::string msg;+ const bool ok = morphToSelectionSet(doc, argString(a, "name"), float(argNumber(a, "amount", 1.0)), msg);+ return result(ok, msg);+ }});+ reg.add({"selection_sets_export",+ "Write the active Part's selection sets (or one) to a .sfsets file, for pipelines and other Parts or files.",+ {{"path", ParamSpec::Type::String, "Output .sfsets file", true},+ {"name", ParamSpec::Type::String, "Only this set (default: all)"}},+ [](Document& doc, const Args& a) {+ const SelectionSetList* list = doc.mesh.selectionSets.get();+ if (!list || list->sets.empty()) return result(false, "This Part has no selection sets to export");+ SelectionSetList out = *list;+ if (const std::string name = argString(a, "name"); !name.empty()) {+ const int i = list->find(name);+ if (i < 0) return result(false, "No selection set " + quote(name));+ out.sets = {list->sets[size_t(i)]};+ if (out.morphTarget != name) out.morphTarget.clear();+ }+ const std::string path = argString(a, "path");+ std::string err;+ if (!saveSelectionSets(path, out, err)) return result(false, err);+ return result(true, "Exported " + std::to_string(out.sets.size()) + " selection set" ++ (out.sets.size() == 1 ? "" : "s") + " to " + path);+ }});+ reg.add({"selection_sets_import",+ "Read the selection sets of a .sfsets file into the active Part (one undo step). Sets with a name the Part "+ "has already replace it.",+ {{"path", ParamSpec::Type::String, ".sfsets file", true}},+ [](Document& doc, const Args& a) {+ SelectionSetList in;+ std::string err;+ if (!loadSelectionSets(argString(a, "path"), in, err)) return result(false, err);+ if (in.sets.empty()) return result(false, "The file holds no selection sets");+ auto list = editableList(doc.mesh);+ size_t fits = 0;+ for (const auto& s : in.sets) {+ fits += selectionSetFits(doc.mesh, *s);+ const int at = list->find(s->name);+ if (at >= 0) list->sets[size_t(at)] = s;+ else list->sets.push_back(s);+ }+ if (list->morphTarget.empty()) list->morphTarget = in.morphTarget;+ commitList(doc, std::move(list), "Import selection sets");+ std::string msg = "Imported " + std::to_string(in.sets.size()) + " selection set" + (in.sets.size() == 1 ? "" : "s");+ if (fits < in.sets.size()) msg += " (" + std::to_string(in.sets.size() - fits) + " don't fit this Part's mesh)";+ return result(true, msg);+ }});+}++} // namespace sfdiff --git a/src/core/SelectionSets.h b/src/core/SelectionSets.hnew file mode 100644index 00000000..952dd28f--- /dev/null+++ b/src/core/SelectionSets.h@@ -0,0 +1,148 @@+// SculptForge - open source digital sculpting+// SPDX-License-Identifier: GPL-3.0-or-later+//+// Selection Sets (Tool > Selection Sets): any number of named snapshots of a Part's mask, polygroups, vertex+// paint, visibility (hidden faces), UVs and shape (the morph target), each holding the channels it was stored+// with. A set is stored at the subdivision level the Part is at and restores at any level of the same stack: its+// values travel through the levels as the stack passes attributes on (core/Multires.h, subdivMapVertices ...),+// and the shape travels as an offset from the level's own shape, so the detail of the levels in between stays.+//+// Sets are compact: masks, vertex paint and visibility keep only runs of the elements that differ from the+// default (unmasked, white, shown), polygroups are run-length coded, UVs and shapes are kept as they are. A set is+// immutable once made and shared (std::shared_ptr) by every copy of the mesh, so undo steps cost a pointer.+//+// Beyond ZBrush: sets combine (union, intersect, subtract) into new sets or onto the current mask and visibility,+// a quick set takes the visible faces, the Morph brush and Morph to Set pull the surface toward any set's shape+// (at any level), and every operation is a command, so Python (`sculptforge`), sculptforge-cli, MCP and the AI+// assistant push and pull sets too. Sets travel with projects (.sfproj), as their own `.sfsets` files, and in+// USD exports (GeomSubsets for visibility and polygroups, primvars for the rest; read back on import).+#pragma once++#include "core/Mesh.h"++#include <glm/glm.hpp>++#include <cstdint>+#include <memory>+#include <string>+#include <vector>++namespace sf {++class CommandRegistry;+struct Document;+class Json;++// What a set holds (bits).+enum SetChannel : uint32_t {+ kSetMask = 1,+ kSetPolygroups = 2,+ kSetPaint = 4, // vertex paint (Mesh::colors)+ kSetVisibility = 8, // hidden faces+ kSetUvs = 16,+ kSetMorph = 32, // the shape (vertex positions): the Morph brush's target+ kSetAllChannels = 63,+};+// "mask,polygroups,paint,visibility,uvs,morph" (any order, also "all", "groups", "colors", "hidden", "shape").+bool parseSetChannels(const std::string& text, uint32_t& out, std::string& error);+std::string setChannelNames(uint32_t channels); // "mask, visibility"++// How a set's mask and visibility meet the current ones (restore) or another set's (combine). Visibility combines+// the shown faces: Union shows what either shows, Intersect what both show, Subtract what the first shows and the+// second doesn't.+enum class SetOp { Replace, Union, Intersect, Subtract };+bool parseSetOp(const std::string& text, SetOp& out);+const char* setOpName(SetOp op);++// Elements [start, start + length).+struct SetRun {+ uint32_t start = 0, length = 0;+};++struct SelectionSet {+ std::string name;+ uint32_t channels = 0;+ int level = 0; // the subdivision level it was stored at (0 without levels)+ uint32_t vertexCount = 0, triangleCount = 0; // of that level+ // Mask: runs of masked vertices and their values in run order (no values: every one is exactly 1).+ std::vector<SetRun> maskRuns;+ std::vector<float> maskValues;+ // Polygroups: runs of triangles with one id (start = the id, length = how many).+ std::vector<SetRun> groupRuns;+ // Vertex paint: runs of vertices that aren't white, and their colours (linear RGB).+ std::vector<SetRun> paintRuns;+ std::vector<glm::vec3> paintValues;+ // Visibility: runs of hidden triangles.+ std::vector<SetRun> hiddenRuns;+ std::vector<glm::vec2> uvs; // per triangle corner+ std::vector<glm::vec3> positions; // the shape++ bool has(uint32_t c) const { return (channels & c) != 0; }+ size_t bytes() const;+};++struct SelectionSetList {+ std::vector<std::shared_ptr<const SelectionSet>> sets; // in the order they were made+ std::string morphTarget; // the set the Morph brush pulls toward ("" = none)+ int find(const std::string& name) const; // index, or -1+ size_t bytes() const;+};++// A set's channels as plain arrays (only the channels in `channels`; the others stay empty).+struct SelectionSetData {+ uint32_t channels = 0;+ std::vector<float> mask;+ std::vector<uint32_t> polygroups;+ std::vector<glm::vec3> colors;+ std::vector<uint8_t> hidden;+ std::vector<glm::vec2> uvs;+ std::vector<glm::vec3> positions;+};++// The mesh's own channels (UVs only when it has them).+SelectionSet captureSelectionSet(const Mesh& mesh, std::string name, uint32_t channels);+// A set from arrays laid out for `vertexCount` / `triangleCount` (checked; error names the first that doesn't fit).+bool makeSelectionSet(std::string name, const SelectionSetData& data, uint32_t vertexCount, uint32_t triangleCount,+ int level, SelectionSet& out, std::string& error);+// The set's arrays at the level it was stored at.+void decodeSelectionSet(const SelectionSet& s, uint32_t channels, SelectionSetData& out);+// The set's arrays at the mesh's current level (any level of its stack whose counts the set fits; see the file+// comment). False with `error` when it was stored on a different mesh.+bool selectionSetAt(const Mesh& mesh, const SelectionSet& s, uint32_t channels, SelectionSetData& out, std::string& error);+// True when selectionSetAt can place the set on this mesh.+bool selectionSetFits(const Mesh& mesh, const SelectionSet& s);++void combineMask(std::vector<float>& current, const std::vector<float>& other, SetOp op);+void combineHidden(std::vector<uint8_t>& current, const std::vector<uint8_t>& other, SetOp op);++// Binary form of one set (projects and .sfsets files): versioned, little-endian, with tagged sections that newer+// readers may add to (unknown ones are skipped). Unpacking checks every count and run against the set's counts.+std::vector<uint8_t> packSelectionSet(const SelectionSet& s);+bool unpackSelectionSet(const uint8_t* data, size_t size, SelectionSet& out, std::string& error);+// Name, channels, level and counts, for manifests (readers rely on the packed data, not on this).+Json selectionSetSummary(const SelectionSet& s);++// .sfsets: a stored ZIP with manifest.json and one packed set per entry, for pipelines and other files.+bool saveSelectionSets(const std::string& path, const SelectionSetList& list, std::string& error);+bool loadSelectionSets(const std::string& path, SelectionSetList& out, std::string& error);++// --- Undoable operations on the active Part (one undo step each; `message` for the status line) ---+bool storeSelectionSet(Document& doc, const std::string& name, uint32_t channels, std::string& message);+// Adds (or replaces, by name) a ready-made set.+bool addSelectionSet(Document& doc, SelectionSet set, const std::string& label, std::string& message);+// Restores the set's channels in `channels` (0 = all it holds but the shape). The shape is restored only when asked+// for (kSetMorph), within the mask. `op` applies to the mask and visibility.+bool restoreSelectionSet(Document& doc, const std::string& name, uint32_t channels, SetOp op, std::string& message);+bool renameSelectionSet(Document& doc, const std::string& name, const std::string& to, std::string& message);+bool deleteSelectionSet(Document& doc, const std::string& name, std::string& message);+bool combineSelectionSets(Document& doc, const std::string& a, const std::string& b, SetOp op, const std::string& into,+ std::string& message);+// Moves the surface `amount` (0..1, negative pushes away) of the way to the set's shape, scaled by 1 - mask.+bool morphToSelectionSet(Document& doc, const std::string& name, float amount, std::string& message);+bool setMorphTarget(Document& doc, const std::string& name, std::string& message);++// selection_set_store, _restore, _rename, _delete, _list, _combine, _from_visible, _morph_target, _morph,+// selection_sets_export, selection_sets_import.+void registerSelectionSetCommands(CommandRegistry& registry);++} // namespace sfdiff --git a/src/core/Undo.cpp b/src/core/Undo.cppindex de70cba5..9e3f1009 100644--- a/src/core/Undo.cpp+++ b/src/core/Undo.cpp@@ -2,6 +2,8 @@// SPDX-License-Identifier: GPL-3.0-or-later#include "core/Undo.h"+#include "core/SelectionSets.h"+#include <utility>namespace sf {@@ -11,7 +13,7 @@ size_t UndoRecord::approxBytes() const {polygroups.bytes() + (paint ? paint->bytes() : 0) +(textureTiles ? textureTiles->bytes() : 0) + (texture ? texture->bytes() : 0) +(subdiv ? subdiv->bytes() : 0) + (topology ? topology->bytes() : 0) +- (micro ? micro->bytes() : 0);+ (micro ? micro->bytes() : 0) + uvs.bytes() + (sets ? sets->bytes() : 0);for (const auto& l : layerOffsets) bytes += l.bytes();if (mesh)bytes += mesh->vertexCount() * ((2 + (mesh->base.empty() ? 0 : 1 + mesh->layers.size())) * sizeof(glm::vec3) +@@ -155,6 +157,7 @@ void UndoStack::apply(UndoRecord& r, Mesh& mesh, BVH& bvh) {return;}if (r.micro) r.micro->swapWith(mesh); // (the base doesn't move: no BVH work)+ if (r.sets) std::swap(mesh.selectionSets, r.sets->list);if (r.mesh) {std::swap(*r.mesh, mesh);mesh.topologyDirty = true;@@ -212,6 +215,20 @@ void UndoStack::apply(UndoRecord& r, Mesh& mesh, BVH& bvh) {r.polygroups.swapWith(mesh.ensurePolygroups());mesh.facesDirty = true;}+ if (!r.uvs.empty()) {+ if (mesh.uvs.size() != mesh.triangleCount() * 3) mesh.uvs.assign(mesh.triangleCount() * 3, glm::vec2(0.0f));+ r.uvs.swapWith(mesh.uvs);+ mesh.facesDirty = true;+ mesh.topologyDirty = true;+ }+}++size_t SelectionSetsUndo::bytes() const {+ if (!list) return 0;+ size_t total = 0;+ for (const auto& s : list->sets)+ if (s.use_count() == 1) total += s->bytes();+ return total;}bool UndoStack::undo(Mesh& mesh, BVH& bvh) {diff --git a/src/core/Undo.h b/src/core/Undo.hindex b8c6420b..367e0d42 100644--- a/src/core/Undo.h+++ b/src/core/Undo.h@@ -101,6 +101,13 @@ struct TextureStackUndo {size_t bytes() const;};+// The Selection Sets list before a set was stored, renamed, deleted or picked as the Morph target+// (core/SelectionSets.h); applying swaps it with the mesh's. Sets are immutable and shared, so this holds pointers.+struct SelectionSetsUndo {+ std::shared_ptr<const SelectionSetList> list;+ size_t bytes() const; // what only this step keeps alive+};+// 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;@@ -123,6 +130,8 @@ inline constexpr int kActivePaintLayer = -2;// - 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// - micro: the grid tiles a stroke on a micro level changed, or a whole micro level (core/Micro.h)+// - uvs: per triangle corner texture coordinates (restoring a selection set's UVs)+// - sets: the Selection Sets list (core/SelectionSets.h)// Record old values before changing them (ensureX() the attribute first);// undo allocates a missing attribute so values can always be restored.struct UndoRecord {@@ -146,10 +155,13 @@ struct UndoRecord {std::unique_ptr<TopologyUndo> topology;std::shared_ptr<SubtoolStep> subtool; // (shared: SubtoolStep is defined in core/Document.h)std::unique_ptr<MicroUndo> micro; // micro-displacement tiles of a stroke, or a micro level added / removed (core/Micro.h)+ UndoChannel<glm::vec2> uvs; // per corner (index = triangle * 3 + corner)+ std::unique_ptr<SelectionSetsUndo> sets;bool empty() const {return positions.empty() && mask.empty() && colors.empty() && paintAlpha.empty() && hidden.empty() &&- polygroups.empty() && !mesh && !paint && !textureTiles && !texture && !subdiv && !topology && !subtool && !micro;+ polygroups.empty() && !mesh && !paint && !textureTiles && !texture && !subdiv && !topology && !subtool && !micro &&+ uvs.empty() && !sets;}size_t approxBytes() const;diff --git a/src/io/UsdIO.cpp b/src/io/UsdIO.cppindex f2209063..22331a06 100644--- a/src/io/UsdIO.cpp+++ b/src/io/UsdIO.cpp@@ -2,6 +2,7 @@// SPDX-License-Identifier: GPL-3.0-or-later#include "io/UsdIO.h"+#include "core/SelectionSets.h"#include "io/TextureExport.h"#include "io/Zip.h"@@ -101,6 +102,16 @@ struct Writer {};std::string quoted(const std::string& t) { return "\"" + t + "\""; }+// A string literal for any text (quotes, backslashes and control characters escaped).+std::string usdQuoted(const std::string& t) {+ std::string out = "\"";+ for (unsigned char c : t) {+ if (c == '"' || c == '\\') out += '\\';+ if (c < 0x20) out += ' ';+ else out += char(c);+ }+ return out + "\"";+}void writeExtent(Writer& w, const AABB& b) {w.indent();@@ -111,6 +122,79 @@ void writeExtent(Writer& w, const AABB& b) {w.s += "]\n";}+// Selection Sets (core/SelectionSets.h) of the mesh, inside its Mesh prim: their names and channels as+// `sculptforge:selectionSets` / `sculptforge:selectionSetChannels`, the mask and vertex paint of set k as vertex+// primvars `sculptforge_set<k>_mask` / `_color`, its shown faces as the GeomSubset `sculptforge_set<k>_visible` and+// its polygroups as a partition of GeomSubsets `sculptforge_set<k>_group<id>`. UVs and shapes aren't written (they+// travel in projects and .sfsets files). `triFace`: the face each triangle was written in.+void writeSelectionSets(Writer& w, const Mesh& mesh, std::vector<uint32_t> triFace, size_t faceCount) {+ if (!mesh.selectionSets || mesh.selectionSets->sets.empty()) return;+ for (uint32_t t = 0; t < triFace.size(); ++t) // the second half of a quad is in its partner's face+ if (triFace[t] == ~0u && mesh.quadPartnerAt(t) != Mesh::kNoQuad) triFace[t] = triFace[mesh.quadPartnerAt(t)];+ constexpr uint32_t kChannels = kSetMask | kSetPaint | kSetVisibility | kSetPolygroups;+ std::vector<std::string> names, channels;+ std::vector<SelectionSetData> data;+ for (const auto& set : mesh.selectionSets->sets) {+ SelectionSetData d;+ std::string error;+ if (!(set->channels & kChannels) || !selectionSetAt(mesh, *set, kChannels, d, error)) continue;+ names.push_back(set->name);+ channels.push_back(setChannelNames(d.channels));+ data.push_back(std::move(d));+ }+ if (names.empty()) return;+ w.array("uniform token[] sculptforge:selectionSets", names, [&](const std::string& n) { w.s += usdQuoted(n); });+ w.array("uniform token[] sculptforge:selectionSetChannels", channels, [&](const std::string& n) { w.s += usdQuoted(n); });+ auto faceSubset = [&](const std::string& name, const std::string& family, auto inSubset, bool partition) {+ std::vector<uint8_t> in(faceCount, 0);+ for (uint32_t t = 0; t < triFace.size(); ++t)+ if (triFace[t] < faceCount && inSubset(t)) in[triFace[t]] = 1;+ std::vector<uint32_t> indices;+ for (uint32_t f = 0; f < faceCount; ++f)+ if (in[f]) indices.push_back(f);+ w.s += '\n';+ w.open("def GeomSubset \"" + name + "\"");+ w.line("uniform token elementType = \"face\"");+ w.line("uniform token familyName = \"" + family + "\"");+ if (partition) w.line("uniform token familyType = \"partition\"");+ w.array("int[] indices", indices, [&](uint32_t f) { w.s += std::to_string(f); });+ w.close();+ };+ for (size_t k = 0; k < data.size(); ++k) {+ const SelectionSetData& d = data[k];+ const std::string base = "sculptforge_set" + std::to_string(k);+ if (!d.mask.empty()) {+ w.array("float[] primvars:" + base + "_mask", d.mask, [&](float v) { w.num(v); });+ w.s.pop_back();+ w.s += " (\n";+ w.line(" interpolation = \"vertex\"");+ w.line(")");+ }+ if (!d.colors.empty()) {+ w.array("color3f[] primvars:" + base + "_color", d.colors, [&](const glm::vec3& c) { w.vec3(c); });+ w.s.pop_back();+ w.s += " (\n";+ w.line(" interpolation = \"vertex\"");+ w.line(")");+ }+ }+ for (size_t k = 0; k < data.size(); ++k) {+ const SelectionSetData& d = data[k];+ const std::string base = "sculptforge_set" + std::to_string(k);+ if (!d.hidden.empty())+ faceSubset(base + "_visible", "sculptforge:set" + std::to_string(k) + ":visibility",+ [&](uint32_t t) { return d.hidden[t] == 0; }, false);+ if (!d.polygroups.empty()) {+ std::vector<uint32_t> ids = d.polygroups;+ std::sort(ids.begin(), ids.end());+ ids.erase(std::unique(ids.begin(), ids.end()), ids.end());+ for (uint32_t id : ids)+ faceSubset(base + "_group" + std::to_string(id), "sculptforge:set" + std::to_string(k) + ":polygroups",+ [&](uint32_t t) { return d.polygroups[t] == id; }, true);+ }+ }+}+// One mesh prim `prim` under the root (a SkelRoot holding the Mesh when it has blend shapes).void writeMesh(Writer& w, const Mesh& mesh, const std::string& root, const std::string& prim, const std::string& material,const MorphAnimation* animation) {@@ -147,11 +231,13 @@ void writeMesh(Writer& w, const Mesh& mesh, const std::string& root, const std::std::vector<int> counts;std::vector<glm::vec2> st;faces.reserve(mesh.triangleCount());+ std::vector<uint32_t> triFace(mesh.triangleCount(), ~0u); // the face each triangle is written in (selection sets)for (uint32_t t = 0; t < mesh.triangleCount(); ++t) {glm::uvec4 f;glm::vec2 fuv[4];const int corners = exportFaceUv(mesh, t, f, fuv);if (corners == 0) continue;+ triFace[t] = uint32_t(faces.size());faces.push_back(f);counts.push_back(corners);if (uvs) st.insert(st.end(), fuv, fuv + corners);@@ -185,6 +271,7 @@ void writeMesh(Writer& w, const Mesh& mesh, const std::string& root, const std::w.line(")");}w.line("uniform token subdivisionScheme = \"none\"");+ writeSelectionSets(w, mesh, triFace, faces.size());if (skinned) {w.array("uniform token[] skel:blendShapes", shapeNames, [&](const std::string& n) { w.s += quoted(n); });w.array("rel skel:blendShapeTargets", shapeNames, [&](const std::string& n) { w.s += "<" + meshPath + "/" + n + ">"; });@@ -777,6 +864,64 @@ private:}};+// The selection sets writeSelectionSets put in Mesh prim `mesh` (and its GeomSubset children), as arrays for its+// `vertices` and `triangles` (`faceTris`: each face's first triangle and count). Anything that doesn't fit is+// left out.+void readSelectionSets(const std::vector<Prim>& prims, size_t mesh, size_t vertices, size_t triangles,+ const std::vector<glm::uvec2>& faceTris, std::vector<std::pair<std::string, SelectionSetData>>& out) {+ const Prim& p = prims[mesh];+ const Value* names = p.get("sculptforge:selectionSets");+ const Value* channelList = p.get("sculptforge:selectionSetChannels");+ if (!names || !channelList || names->strs.size() != channelList->strs.size()) return;+ for (size_t k = 0; k < names->strs.size() && k < 100000; ++k) {+ uint32_t channels = 0;+ std::string error;+ if (!parseSetChannels(channelList->strs[k], channels, error)) continue;+ channels &= kSetMask | kSetPaint | kSetVisibility | kSetPolygroups;+ const std::string base = "sculptforge_set" + std::to_string(k);+ SelectionSetData d;+ d.channels = channels;+ if (channels & kSetMask) {+ const Value* v = p.get("primvars:" + base + "_mask");+ if (!v || v->nums.size() != vertices) continue;+ d.mask.assign(v->nums.begin(), v->nums.end());+ }+ if (channels & kSetPaint) {+ const Value* v = p.get("primvars:" + base + "_color");+ if (!v || v->nums.size() != vertices * 3) continue;+ d.colors.resize(vertices);+ for (size_t i = 0; i < vertices; ++i)+ d.colors[i] = glm::vec3(float(v->nums[i * 3]), float(v->nums[i * 3 + 1]), float(v->nums[i * 3 + 2]));+ }+ if (channels & kSetVisibility) d.hidden.assign(triangles, 1);+ if (channels & kSetPolygroups) d.polygroups.assign(triangles, 0u);+ bool visibleFound = false;+ for (const Prim& c : prims) {+ if (c.parent != int(mesh) || c.type != "GeomSubset") continue;+ const std::string name = c.path.substr(c.path.rfind('/') + 1);+ if (name.rfind(base + "_", 0) != 0) continue;+ const std::string rest = name.substr(base.size() + 1);+ const bool visible = rest == "visible";+ const bool group = rest.rfind("group", 0) == 0 && rest.size() > 5 && rest.size() < 16 &&+ std::all_of(rest.begin() + 5, rest.end(), [](char ch) { return ch >= '0' && ch <= '9'; });+ if ((!visible || !(channels & kSetVisibility)) && (!group || !(channels & kSetPolygroups))) continue;+ const uint32_t id = group ? uint32_t(std::min<unsigned long long>(std::stoull(rest.substr(5)), 0xFFFFFFFFull)) : 0u;+ visibleFound |= visible;+ if (const Value* idx = c.get("indices"))+ for (double f : idx->nums) {+ if (f < 0 || f >= double(faceTris.size())) continue;+ const glm::uvec2 ft = faceTris[size_t(f)];+ for (uint32_t t = ft.x; t < ft.x + ft.y && t < triangles; ++t) {+ if (visible) d.hidden[t] = 0;+ else d.polygroups[t] = id;+ }+ }+ }+ if ((channels & kSetVisibility) && !visibleFound) continue;+ out.emplace_back(names->strs[k], std::move(d));+ }+}+glm::mat4 axisRotation(char axis, float degrees) {const glm::vec3 a = axis == 'X' ? glm::vec3(1, 0, 0) : axis == 'Y' ? glm::vec3(0, 1, 0) : glm::vec3(0, 0, 1);return glm::rotate(glm::mat4(1.0f), glm::radians(degrees), a);@@ -887,6 +1032,8 @@ bool readUsdaText(const std::string& text, bool split, std::vector<MeshObject>&Mesh m;std::vector<SculptLayer> layers;bool uvs = false; // some prim had UVs (Mesh::uvs holds one per corner either way until the end)+ int meshPrims = 0;+ std::vector<std::pair<std::string, SelectionSetData>> sets; // selection sets SculptForge wrote (one prim only)};std::vector<Gathered> objects(split ? 0 : 1);bool splatsFound = false;@@ -906,7 +1053,7 @@ bool readUsdaText(const std::string& text, bool split, std::vector<MeshObject>&// Named after the prim, or after its SkelRoot (SculptForge writes <Name>/Mesh for blend shapes).const int parent = p.parent;const Prim& named = parent >= 0 && prims[size_t(parent)].type == "SkelRoot" ? prims[size_t(parent)] : p;- objects.push_back({named.path.substr(named.path.rfind('/') + 1), {}, {}, false});+ objects.push_back({named.path.substr(named.path.rfind('/') + 1), {}, {}, false, 0, {}});}Mesh& m = objects.back().m;std::vector<SculptLayer>& layers = objects.back().layers;@@ -959,6 +1106,7 @@ bool readUsdaText(const std::string& text, bool split, std::vector<MeshObject>&return e < st->nums.size() / 2 ? glm::vec2(float(st->nums[e * 2]), float(st->nums[e * 2 + 1])) : glm::vec2(0.0f);};size_t cursor = 0;+ std::vector<glm::uvec2> faceTris; // per face: its first triangle and how many (selection sets)for (double c : counts->nums) {const size_t n = size_t(std::max(0.0, c));if (cursor + n > indices->nums.size()) {@@ -983,8 +1131,11 @@ bool readUsdaText(const std::string& text, bool split, std::vector<MeshObject>&m.uvs.insert(m.uvs.end(), uv, uv + 3);}if (n == 4) m.pairQuad(firstTri, firstTri + 1); // a quad stays paired (Mesh::quadPartners)+ faceTris.push_back({firstTri, uint32_t(m.triangles.size()) - firstTri});cursor += n;}+ ++objects.back().meshPrims;+ readSelectionSets(prims, i, pts.size(), m.triangles.size(), faceTris, objects.back().sets);if (m.hasQuads()) m.quadPartners.resize(m.triangles.size(), Mesh::kNoQuad);for (auto& l : layers) l.delta.resize(m.positions.size(), glm::vec3(0.0f));// Blend shapes bound to this mesh.@@ -1044,6 +1195,20 @@ bool readUsdaText(const std::string& text, bool split, std::vector<MeshObject>&if (!o.uvs) o.m.uvs.clear();for (auto& l : o.layers) l.delta.resize(o.m.positions.size(), glm::vec3(0.0f));outMeshes.push_back({o.name, weldImported(o.m, o.layers)});+ // Sets come back when the mesh came from one prim and welding kept its vertices and triangles.+ Mesh& welded = outMeshes.back().mesh;+ if (o.meshPrims == 1 && !o.sets.empty() && welded.vertexCount() == o.m.vertexCount() &&+ welded.triangleCount() == o.m.triangleCount()) {+ auto list = std::make_shared<SelectionSetList>();+ for (auto& [name, data] : o.sets) {+ SelectionSet set;+ std::string error;+ if (list->find(name) < 0 && makeSelectionSet(name, data, uint32_t(welded.vertexCount()),+ uint32_t(welded.triangleCount()), 0, set, error))+ list->sets.push_back(std::make_shared<const SelectionSet>(std::move(set)));+ }+ if (!list->sets.empty()) welded.selectionSets = std::move(list);+ }}if (outMeshes.empty() && !splatsFound) {error = "No meshes or Gaussian splats found (references, payloads and binary .usdc layers are not supported yet)";diff --git a/src/python/module.cpp b/src/python/module.cppindex 2c2f6dba..a4a6a448 100644--- a/src/python/module.cpp+++ b/src/python/module.cpp@@ -10,11 +10,14 @@// sf.run(doc, "export_usd", path="/tmp/head.usdz")// verts, tris = doc.vertices, doc.triangles # (N, 3) float32, (M, 3) uint32// doc.mask, doc.colors, doc.polygroups # optional attributes, None when absent+// doc.set_selection_set("Eyes", mask=m) # push a selection set; doc.selection_set("Eyes") pulls it#include "ai/AiCommands.h"#include "ai/SplatTrainer.h"#include "core/BrushLibrary.h"#include "core/Commands.h"+#include "core/Multires.h"#include "core/Script.h"+#include "core/SelectionSets.h"#include <pybind11/numpy.h>#include <pybind11/pybind11.h>@@ -93,6 +96,25 @@ void setAttribute(std::vector<T>& dst, const py::object& value, size_t count, codst.assign(a.data(), a.data() + count);}+// An (n, k) float32 array of `count` rows (k = 1: 1-D), or a ValueError.+template <class T>+std::vector<T> rows(const py::object& value, size_t count, int k, const char* what) {+ auto a = py::array_t<float, py::array::c_style | py::array::forcecast>::ensure(value);+ const bool shape = a && ((k == 1 && a.ndim() == 1) || (k > 1 && a.ndim() == 2 && a.shape(1) == k));+ if (!shape || size_t(a.shape(0)) != count)+ throw py::value_error(std::string(what) + ": expected " + std::to_string(count) + (k > 1 ? " rows of " + std::to_string(k) : " values"));+ std::vector<T> out(count);+ std::memcpy(out.data(), a.data(), count * sizeof(T));+ return out;+}++template <class T>+py::array_t<float> floatRows(const std::vector<T>& v, int k) {+ py::array_t<float> a = k == 1 ? py::array_t<float>(py::ssize_t(v.size())) : py::array_t<float>({py::ssize_t(v.size()), py::ssize_t(k)});+ if (!v.empty()) std::memcpy(a.mutable_data(), v.data(), v.size() * sizeof(T));+ return a;+}+} // namespacePYBIND11_MODULE(sculptforge, m) {@@ -216,6 +238,82 @@ PYBIND11_MODULE(sculptforge, m) {},"Index of the SubTool that vertices, mask, layers... and editing commands refer to. Set it to an ""index or a SubTool name to select another one.")+ // Selection Sets (core/SelectionSets.h) of the active Part (SubTool): push and pull them as arrays.+ .def_property_readonly(+ "selection_sets",+ [](const Document& d) {+ py::list out;+ const SelectionSetList* list = d.mesh.selectionSets.get();+ if (list)+ for (const auto& s : list->sets) {+ py::list channels;+ for (const char* c : {"mask", "polygroups", "paint", "visibility", "uvs", "morph"}) {+ uint32_t bit = 0;+ std::string err;+ if (parseSetChannels(c, bit, err) && s->has(bit)) channels.append(c);+ }+ out.append(py::dict(py::arg("name") = s->name, py::arg("channels") = channels,+ py::arg("level") = s->level, py::arg("vertex_count") = s->vertexCount,+ py::arg("triangle_count") = s->triangleCount,+ py::arg("fits") = selectionSetFits(d.mesh, *s),+ py::arg("morph_target") = s->name == list->morphTarget));+ }+ return out;+ },+ "The active Part's selection sets, as dicts with name, channels, level, vertex_count, triangle_count, "+ "fits and morph_target.")+ .def(+ "selection_set",+ [](const Document& d, const std::string& name) {+ const SelectionSetList* list = d.mesh.selectionSets.get();+ const int i = list ? list->find(name) : -1;+ if (i < 0) throw py::key_error("no selection set " + name);+ SelectionSetData data;+ std::string err;+ if (!selectionSetAt(d.mesh, *list->sets[size_t(i)], kSetAllChannels, data, err)) throw CommandError(err);+ py::dict out;+ if (data.channels & kSetMask) out["mask"] = floatRows(data.mask, 1);+ if (data.channels & kSetPolygroups) out["polygroups"] = attributeArray(data.polygroups);+ if (data.channels & kSetPaint) out["colors"] = floatRows(data.colors, 3);+ if (data.channels & kSetVisibility) out["hidden"] = attributeArray(data.hidden);+ if (data.channels & kSetUvs) out["uvs"] = floatRows(data.uvs, 2);+ if (data.channels & kSetMorph) out["positions"] = floatRows(data.positions, 3);+ return out;+ },+ py::arg("name"),+ "A selection set's channels at the current subdivision level, as a dict of NumPy arrays (mask, polygroups, "+ "colors, hidden, uvs (per triangle corner), positions), only those the set holds.")+ .def(+ "set_selection_set",+ [](Document& d, const std::string& name, const py::object& mask, const py::object& polygroups,+ const py::object& colors, const py::object& hidden, const py::object& uvs, const py::object& positions) {+ const size_t nv = d.mesh.vertexCount(), nt = d.mesh.triangleCount();+ SelectionSetData data;+ if (!mask.is_none()) data.mask = rows<float>(mask, nv, 1, "mask"), data.channels |= kSetMask;+ if (!polygroups.is_none()) {+ setAttribute(data.polygroups, polygroups, nt, "polygroups");+ data.channels |= kSetPolygroups;+ }+ if (!colors.is_none()) data.colors = rows<glm::vec3>(colors, nv, 3, "colors"), data.channels |= kSetPaint;+ if (!hidden.is_none()) {+ setAttribute(data.hidden, hidden, nt, "hidden");+ data.channels |= kSetVisibility;+ }+ if (!uvs.is_none()) data.uvs = rows<glm::vec2>(uvs, nt * 3, 2, "uvs"), data.channels |= kSetUvs;+ if (!positions.is_none()) data.positions = rows<glm::vec3>(positions, nv, 3, "positions"), data.channels |= kSetMorph;+ if (!data.channels) throw py::value_error("give at least one of mask, polygroups, colors, hidden, uvs, positions");+ SelectionSet set;+ std::string msg;+ if (!makeSelectionSet(name, data, uint32_t(nv), uint32_t(nt), subdivCurrentLevel(d.mesh), set, msg) ||+ !addSelectionSet(d, std::move(set), "Store set " + name, msg))+ throw CommandError(msg);+ return msg;+ },+ py::arg("name"), py::kw_only(), py::arg("mask") = py::none(), py::arg("polygroups") = py::none(),+ py::arg("colors") = py::none(), py::arg("hidden") = py::none(), py::arg("uvs") = py::none(),+ py::arg("positions") = py::none(),+ "Store (or replace) a selection set on the active Part from arrays laid out for the current level "+ "(one undo step). Restore it with run(doc, 'selection_set_restore', name=...).").def("__repr__", [](const Document& d) {return "<sculptforge.Document " + std::to_string(d.mesh.vertexCount()) + " vertices, " +std::to_string(d.mesh.triangleCount()) + " triangles, " + std::to_string(d.mesh.layers.size()) +diff --git a/tests/test_integration_v02.cpp b/tests/test_integration_v02.cppindex 1cc555df..6e552635 100644--- a/tests/test_integration_v02.cpp+++ b/tests/test_integration_v02.cpp@@ -95,7 +95,7 @@ TEST(v02_every_brush_and_alpha_respects_painted_mask) {d.undo.push(d.sculptor.endStroke());CHECK(leftUnchanged(d.mesh, before));// A flat plane has nothing to smooth or flatten.- if (type != BrushType::Smooth && type != BrushType::Flatten) {+ if (type != BrushType::Smooth && type != BrushType::Flatten && type != BrushType::Morph) { // (Morph: no target)const bool changed = rightChanged(d.mesh, before);if (!changed) std::printf(" %s (%s alpha) did not sculpt\n", brushName(type), alpha);CHECK(changed);diff --git a/tests/test_python.py b/tests/test_python.pyindex cab9aba9..8434cc91 100644--- a/tests/test_python.py+++ b/tests/test_python.py@@ -72,4 +72,29 @@ doc.set_mesh([[0, 0, 0], [1, 0, 0], [0, 1, 0], [0, 0, 1]], [[0, 2, 1], [0, 1, 3]assert doc.triangles.shape == (4, 3)assert "Document" in repr(doc) and sf.__version__assert '"name":"remesh"' in sf.tool_schema()+# Selection sets: push arrays in, pull them back, restore through a command.+sf.run(doc, "new_sphere", subdivisions=3)+n = doc.vertices.shape[0]+top = [1.0 if v[1] > 0 else 0.0 for v in doc.vertices]+assert "Stored" in doc.set_selection_set("Top", mask=top, positions=doc.vertices)+assert [s["name"] for s in doc.selection_sets] == ["Top"]+assert doc.selection_sets[0]["channels"] == ["mask", "morph"] and doc.selection_sets[0]["fits"]+pulled = doc.selection_set("Top")+assert pulled["mask"].shape == (n,) and pulled["positions"].shape == (n, 3) and float(pulled["mask"].sum()) == sum(top)+sf.run(doc, "selection_set_restore", name="Top")+assert float(doc.mask.sum()) == sum(top)+sf.run(doc, "selection_set_store", name="Shown", channels="visibility")+assert doc.selection_set("Shown")["hidden"].sum() == 0+sets_path = os.path.join(tempfile.mkdtemp(), "sets.sfsets")+sf.run(doc, "selection_sets_export", path=sets_path)+other = sf.Document()+sf.run(other, "new_sphere", subdivisions=3)+sf.run(other, "selection_sets_import", path=sets_path)+assert len(other.selection_sets) == 2+try:+ doc.set_selection_set("Bad", mask=[1.0, 0.0])+ raise AssertionError("expected ValueError")+except ValueError:+ pass+print("python api ok:", sf.__version__)diff --git a/tests/test_selection_sets.cpp b/tests/test_selection_sets.cppnew file mode 100644index 00000000..f4003180--- /dev/null+++ b/tests/test_selection_sets.cpp@@ -0,0 +1,446 @@+// SculptForge - open source digital sculpting+// SPDX-License-Identifier: GPL-3.0-or-later+//+// Selection Sets (core/SelectionSets.h): store / restore / rename / delete with undo, compact storage and the+// binary form, combining, the quick set from visible faces, carrying sets across subdivision levels, the Morph+// brush and Morph to Set, projects (round trip, older projects, damaged sets), .sfsets files and USD.+#include "TestHarness.h"++#include "core/Commands.h"+#include "core/Json.h"+#include "core/Multires.h"+#include "core/Primitives.h"+#include "core/Project.h"+#include "core/SelectionSets.h"+#include "io/UsdIO.h"++#include <algorithm>+#include <cmath>+#include <cstring>+#include <filesystem>++using namespace sf;++namespace {++const CommandRegistry& registry() {+ static CommandRegistry r;+ return r;+}++CommandResult run(Document& d, const std::string& name, const Args& a = {}) {+ CommandResult r = registry().execute(d, name, a);+ if (!r.ok) std::printf(" (%s: %s)\n", name.c_str(), r.message.c_str());+ return r;+}++size_t setCount(const Mesh& m) { return m.selectionSets ? m.selectionSets->sets.size() : 0; }+const SelectionSet* setNamed(const Mesh& m, const std::string& name) {+ const int i = m.selectionSets ? m.selectionSets->find(name) : -1;+ return i < 0 ? nullptr : m.selectionSets->sets[size_t(i)].get();+}++// Mask the vertices above y = cut (soft values when `soft`), hide the triangles left of x = 0, groups by z.+void paintState(Mesh& m, float cut = 0.0f, bool soft = false) {+ m.ensureMask();+ for (size_t v = 0; v < m.vertexCount(); ++v) m.mask[v] = m.positions[v].y > cut ? (soft ? 0.5f : 1.0f) : 0.0f;+ m.ensureHidden();+ m.ensurePolygroups();+ for (size_t t = 0; t < m.triangleCount(); ++t) {+ const glm::vec3 c = (m.positions[m.triangles[t].x] + m.positions[m.triangles[t].y] + m.positions[m.triangles[t].z]) / 3.0f;+ m.hidden[t] = c.x < 0.0f;+ m.polygroups[t] = c.z > 0.0f ? 7u : 3u;+ }+ m.ensureColors();+ for (size_t v = 0; v < m.vertexCount(); ++v)+ if (m.positions[v].z > 0.5f) m.colors[v] = glm::vec3(0.8f, 0.1f, 0.2f);+}++size_t countHidden(const Mesh& m) {+ size_t n = 0;+ for (size_t t = 0; t < m.triangleCount(); ++t) n += m.triangleHidden(uint32_t(t));+ return n;+}++float maxDistance(const std::vector<glm::vec3>& a, const std::vector<glm::vec3>& b) {+ if (a.size() != b.size()) return 1e30f;+ float d = 0.0f;+ for (size_t i = 0; i < a.size(); ++i) d = std::max(d, glm::length(a[i] - b[i]));+ return d;+}++} // namespace++TEST(selection_sets_store_restore_undo) {+ Document d = makeDoc(makeIcosphere(4));+ paintState(d.mesh);+ const Mesh before = d.mesh;+ CHECK(run(d, "selection_set_store", {{"name", "Head"}, {"channels", "mask,polygroups,paint,visibility"}}).ok);+ CHECK(setCount(d.mesh) == 1);+ const SelectionSet* s = setNamed(d.mesh, "Head");+ CHECK(s && s->has(kSetMask) && s->has(kSetPaint) && s->has(kSetVisibility) && s->has(kSetPolygroups) && !s->has(kSetMorph));+ // Compact: a binary mask on half a sphere is a few runs and no values; groups are run-length coded.+ CHECK(s && s->maskValues.empty() && s->maskRuns.size() < s->vertexCount / 4);+ CHECK(s && s->groupRuns.size() < s->triangleCount / 2);+ CHECK(s && s->bytes() * 2 < d.mesh.vertexCount() * 16 + d.mesh.triangleCount() * 5); // under half the plain arrays++ // Change everything, then restore: back exactly; one undo step brings the changes back.+ d.mesh.clearMask();+ d.mesh.clearHidden();+ d.mesh.clearPolygroups();+ d.mesh.clearColors();+ CHECK(run(d, "selection_set_restore", {{"name", "Head"}}).ok);+ CHECK(d.mesh.mask == before.mask);+ CHECK(d.mesh.hidden == before.hidden);+ CHECK(d.mesh.polygroups == before.polygroups);+ CHECK(d.mesh.colors == before.colors);+ CHECK(run(d, "undo").ok);+ CHECK(!d.mesh.hasMask() || std::all_of(d.mesh.mask.begin(), d.mesh.mask.end(), [](float v) { return v == 0.0f; }));+ CHECK(countHidden(d.mesh) == 0);+ CHECK(run(d, "redo").ok);+ CHECK(d.mesh.mask == before.mask);++ // Only some channels.+ d.mesh.clearHidden();+ d.mesh.clearMask();+ CHECK(run(d, "selection_set_restore", {{"name", "Head"}, {"channels", "visibility"}}).ok);+ CHECK(d.mesh.hidden == before.hidden);+ CHECK(!d.mesh.hasMask() || std::all_of(d.mesh.mask.begin(), d.mesh.mask.end(), [](float v) { return v == 0.0f; }));++ // Storing is undoable too, and so are rename and delete.+ CHECK(run(d, "undo").ok); // the restore+ CHECK(run(d, "undo").ok); // ... and the earlier restore+ CHECK(run(d, "undo").ok); // the store+ CHECK(setCount(d.mesh) == 0);+ CHECK(run(d, "redo").ok);+ CHECK(setCount(d.mesh) == 1);+ CHECK(run(d, "selection_set_rename", {{"name", "Head"}, {"to", "Face"}}).ok);+ CHECK(setNamed(d.mesh, "Face") && !setNamed(d.mesh, "Head"));+ CHECK(run(d, "undo").ok);+ CHECK(setNamed(d.mesh, "Head"));+ CHECK(run(d, "selection_set_delete", {{"name", "Head"}}).ok);+ CHECK(setCount(d.mesh) == 0);+ CHECK(run(d, "undo").ok);+ CHECK(setCount(d.mesh) == 1);+ CHECK(!registry().execute(d, "selection_set_restore", {{"name", "Nope"}}).ok);+ CHECK(!registry().execute(d, "selection_set_store", {{"name", ""}}).ok);+ CHECK(!registry().execute(d, "selection_set_store", {{"name", "X"}, {"channels", "nonsense"}}).ok);+}++TEST(selection_sets_unlimited_and_list) {+ Document d = makeDoc(makeIcosphere(2));+ for (int i = 0; i < 300; ++i) {+ d.mesh.ensureMask();+ std::fill(d.mesh.mask.begin(), d.mesh.mask.end(), 0.0f);+ d.mesh.mask[size_t(i) % d.mesh.vertexCount()] = 1.0f;+ CHECK(run(d, "selection_set_store", {{"name", "S" + std::to_string(i)}, {"channels", "mask"}}).ok);+ }+ CHECK(setCount(d.mesh) == 300);+ CHECK(d.mesh.selectionSets->bytes() < 300 * 1024); // a one-vertex mask is a single run+ // Same name replaces.+ CHECK(run(d, "selection_set_store", {{"name", "S0"}, {"channels", "visibility"}}).ok);+ CHECK(setCount(d.mesh) == 300 && setNamed(d.mesh, "S0")->channels == kSetVisibility);+ const CommandResult list = run(d, "selection_set_list", {{"json", true}});+ Json j;+ std::string err;+ CHECK(list.ok && Json::parse(list.message, j, err) && j["sets"].size() == 300);+ CHECK(j["sets"][0]["name"].asString() == "S0" && j["sets"][0]["fits"].asBool());+}++TEST(selection_sets_pack_roundtrip_and_damage) {+ Mesh m = makePlane(12);+ paintState(m, -0.5f, true);+ const SelectionSet s = captureSelectionSet(m, "All", kSetAllChannels);+ CHECK(s.has(kSetUvs) == m.hasUvs());+ CHECK(!s.maskValues.empty()); // soft values are kept+ const std::vector<uint8_t> packed = packSelectionSet(s);+ SelectionSet back;+ std::string err;+ CHECK(unpackSelectionSet(packed.data(), packed.size(), back, err));+ SelectionSetData a, b;+ decodeSelectionSet(s, kSetAllChannels, a);+ decodeSelectionSet(back, kSetAllChannels, b);+ CHECK(back.name == "All" && back.channels == s.channels);+ CHECK(a.mask == b.mask && a.polygroups == b.polygroups && a.colors == b.colors && a.hidden == b.hidden);+ CHECK(a.uvs == b.uvs && a.positions == b.positions);+ CHECK(a.mask == m.mask && a.hidden == m.hidden && a.positions == m.positions);+ // Every truncation is refused, never read past the end.+ for (size_t n = 0; n + 1 < packed.size(); n += std::max<size_t>(1, packed.size() / 97)) {+ SelectionSet t;+ CHECK(!unpackSelectionSet(packed.data(), n, t, err));+ }+ // A run past the end is refused; a newer set format names itself.+ std::vector<uint8_t> bad = packed;+ bad[4] = 9; // version 9+ CHECK(!unpackSelectionSet(bad.data(), bad.size(), back, err) && err.find("newer") != std::string::npos);+ SelectionSet huge = s;+ huge.hiddenRuns.push_back({uint32_t(m.triangleCount()), 5});+ const std::vector<uint8_t> hp = packSelectionSet(huge);+ CHECK(!unpackSelectionSet(hp.data(), hp.size(), back, err));+}++TEST(selection_sets_combine_and_visible) {+ Document d = makeDoc(makeIcosphere(3));+ Mesh& m = d.mesh;+ auto maskWhere = [&](auto pred) {+ m.ensureMask();+ for (size_t v = 0; v < m.vertexCount(); ++v) m.mask[v] = pred(m.positions[v]) ? 1.0f : 0.0f;+ };+ maskWhere([](const glm::vec3& p) { return p.x > 0.0f; });+ CHECK(run(d, "selection_set_store", {{"name", "Right"}, {"channels", "mask"}}).ok);+ maskWhere([](const glm::vec3& p) { return p.y > 0.0f; });+ CHECK(run(d, "selection_set_store", {{"name", "Top"}, {"channels", "mask"}}).ok);+ auto count = [&](auto pred) {+ size_t n = 0;+ for (size_t v = 0; v < m.vertexCount(); ++v) n += pred(m.positions[v]);+ return n;+ };+ auto masked = [&] {+ size_t n = 0;+ for (float v : m.mask) n += v > 0.5f;+ return n;+ };+ CHECK(run(d, "selection_set_combine", {{"a", "Right"}, {"b", "Top"}, {"op", "intersect"}}).ok);+ CHECK(setNamed(d.mesh, "Right & Top"));+ CHECK(run(d, "selection_set_restore", {{"name", "Right & Top"}}).ok);+ CHECK(masked() == count([](const glm::vec3& p) { return p.x > 0.0f && p.y > 0.0f; }));+ CHECK(run(d, "selection_set_combine", {{"a", "Right"}, {"b", "Top"}, {"op", "subtract"}, {"into", "RightLow"}}).ok);+ CHECK(run(d, "selection_set_restore", {{"name", "RightLow"}}).ok);+ CHECK(masked() == count([](const glm::vec3& p) { return p.x > 0.0f && !(p.y > 0.0f); }));+ // Restore modes combine with the current mask.+ CHECK(run(d, "selection_set_restore", {{"name", "Top"}, {"mode", "union"}}).ok);+ CHECK(masked() == count([](const glm::vec3& p) { return p.x > 0.0f || p.y > 0.0f; }));+ CHECK(!registry().execute(d, "selection_set_combine", {{"a", "Right"}, {"b", "Top"}, {"op", "replace"}}).ok);++ // Quick set from the visible faces; visibility unions and subtracts by the shown faces.+ m.ensureHidden();+ for (size_t t = 0; t < m.triangleCount(); ++t) m.hidden[t] = m.positions[m.triangles[t].x].z < 0.0f;+ const std::vector<uint8_t> front = m.hidden;+ CHECK(run(d, "selection_set_from_visible").ok);+ CHECK(setNamed(d.mesh, "Visible") && setNamed(d.mesh, "Visible")->channels == kSetVisibility);+ CHECK(run(d, "show_all").ok);+ CHECK(run(d, "selection_set_restore", {{"name", "Visible"}}).ok);+ CHECK(m.hidden == front);+ CHECK(run(d, "selection_set_restore", {{"name", "Visible"}, {"mode", "subtract"}}).ok); // shown and not shown+ CHECK(countHidden(m) == m.triangleCount());+ CHECK(run(d, "selection_set_from_visible").ok);+ CHECK(setNamed(d.mesh, "Visible 2"));+}++TEST(selection_sets_across_levels) {+ Document d = makeDoc(makeCube(3));+ CHECK(run(d, "subdiv_divide").ok);+ CHECK(run(d, "subdiv_divide").ok); // levels 1..3, at the top+ Mesh& m = d.mesh;+ // A mask stored at the top restores at the base as the stack itself carries it down.+ m.ensureMask();+ for (size_t v = 0; v < m.vertexCount(); ++v) m.mask[v] = m.positions[v].y > 0.2f ? 1.0f : 0.0f;+ m.markAllDirty();+ CHECK(run(d, "selection_set_store", {{"name", "Top mask"}, {"channels", "mask,polygroups,visibility"}}).ok);+ CHECK(run(d, "subdiv_level", {{"level", 1.0}}).ok);+ const std::vector<float> reference = d.mesh.mask; // what the levels made of it+ CHECK(!reference.empty());+ d.mesh.clearMask();+ CHECK(run(d, "selection_set_restore", {{"name", "Top mask"}}).ok);+ CHECK(d.mesh.mask == reference);+ const CommandResult msg = run(d, "selection_set_restore", {{"name", "Top mask"}, {"channels", "mask"}});+ CHECK(msg.ok && msg.message.find("already matches") != std::string::npos);++ // A mask stored at the base restores at the top as the stack spreads it up.+ std::fill(d.mesh.mask.begin(), d.mesh.mask.end(), 0.0f);+ d.mesh.mask[0] = 1.0f;+ d.mesh.mask[1] = 0.5f;+ d.mesh.markAllDirty();+ CHECK(run(d, "selection_set_store", {{"name", "Base mask"}, {"channels", "mask"}}).ok);+ CHECK(run(d, "subdiv_level", {{"level", 3.0}}).ok);+ const std::vector<float> up = d.mesh.mask;+ d.mesh.clearMask();+ CHECK(run(d, "selection_set_restore", {{"name", "Base mask"}}).ok);+ CHECK(d.mesh.mask.size() == up.size());+ float diff = 0.0f;+ for (size_t v = 0; v < up.size() && v < d.mesh.mask.size(); ++v) diff = std::max(diff, std::abs(up[v] - d.mesh.mask[v]));+ CHECK(diff < 1e-5f);++ // The middle level, both ways; sets also survive stepping (they belong to the Part).+ CHECK(run(d, "subdiv_level", {{"level", 2.0}}).ok);+ CHECK(setCount(d.mesh) == 2);+ CHECK(run(d, "selection_set_restore", {{"name", "Top mask"}}).ok);+ CHECK(run(d, "selection_set_restore", {{"name", "Base mask"}}).ok);+ CHECK(d.mesh.mask.size() == d.mesh.vertexCount());+ // Undo across a level step brings the list along unchanged.+ CHECK(run(d, "undo").ok);+ CHECK(setCount(d.mesh) == 2);++ // A set that fits no level is refused with a message.+ Document other = makeDoc(makeIcosphere(2));+ CHECK(run(other, "selection_set_store", {{"name", "Other"}}).ok);+ SelectionSetData data;+ std::string err;+ CHECK(!selectionSetAt(d.mesh, *setNamed(other.mesh, "Other"), kSetMask, data, err) && !err.empty());+}++TEST(selection_sets_morph_brush_and_morph_to_set) {+ Document d = makeDoc(makeIcosphere(4));+ const std::vector<glm::vec3> original = d.mesh.positions;+ CHECK(!registry().execute(d, "selection_set_morph_target", {{"name", "Rest"}}).ok);+ CHECK(run(d, "selection_set_store", {{"name", "Rest"}, {"channels", "morph"}}).ok);+ // Sculpt: a bump.+ for (int i = 0; i < 3; ++i)+ CHECK(run(d, "stroke", {{"points", "-0.3,0,2 0.3,0,2"}, {"brush", "Standard"}, {"radius", 0.5}, {"strength", 1.0}}).ok);+ const float sculpted = maxDistance(d.mesh.positions, original);+ CHECK(sculpted > 0.01f);+ // Without a target the Morph brush leaves the surface alone.+ const std::vector<glm::vec3> bumped = d.mesh.positions;+ run(d, "stroke", {{"points", "-0.3,0,2 0.3,0,2"}, {"brush", "Morph"}, {"radius", 0.6}, {"strength", 1.0}});+ CHECK(d.mesh.positions == bumped);+ // With one it pulls the bump back.+ CHECK(run(d, "selection_set_morph_target", {{"name", "Rest"}}).ok);+ for (int i = 0; i < 4; ++i)+ CHECK(run(d, "stroke", {{"points", "-0.3,0,2 0.3,0,2"}, {"brush", "Morph"}, {"radius", 0.6}, {"strength", 1.0}}).ok);+ CHECK(maxDistance(d.mesh.positions, original) < sculpted * 0.5f);+ // Morph to Set: halfway, then all of the way, within the mask; undo puts it back.+ CHECK(run(d, "undo").ok);+ const std::vector<glm::vec3> start = d.mesh.positions;+ d.mesh.ensureMask();+ for (size_t v = 0; v < d.mesh.vertexCount(); ++v) d.mesh.mask[v] = d.mesh.positions[v].x > 0.1f ? 1.0f : 0.0f;+ CHECK(run(d, "selection_set_morph", {{"name", "Rest"}, {"amount", 1.0}}).ok);+ for (size_t v = 0; v < d.mesh.vertexCount(); ++v) {+ if (d.mesh.mask[v] == 1.0f) CHECK(d.mesh.positions[v] == start[v]);+ else CHECK(glm::length(d.mesh.positions[v] - original[v]) < 1e-5f);+ }+ CHECK(run(d, "undo").ok);+ CHECK(d.mesh.positions == start);+ d.mesh.clearMask();+ // Restoring the shape needs asking for it.+ CHECK(run(d, "selection_set_restore", {{"name", "Rest"}, {"channels", "morph"}}).ok);+ CHECK(maxDistance(d.mesh.positions, original) < 1e-5f);+ // The target goes with a delete (and comes back with its undo).+ CHECK(run(d, "selection_set_delete", {{"name", "Rest"}}).ok);+ CHECK(!d.mesh.selectionSets);+ CHECK(run(d, "undo").ok);+ CHECK(d.mesh.selectionSets && d.mesh.selectionSets->morphTarget == "Rest");+}++TEST(selection_sets_morph_across_levels) {+ Document d = makeDoc(makeCube(3));+ CHECK(run(d, "subdiv_divide").ok); // levels 1..2, at the top+ const std::vector<glm::vec3> topRest = d.mesh.positions;+ CHECK(run(d, "subdiv_level", {{"level", 1.0}}).ok);+ CHECK(run(d, "selection_set_store", {{"name", "Rest"}, {"channels", "morph"}}).ok); // stored at the base+ // Reshape the base, step up: the top moved too.+ for (glm::vec3& p : d.mesh.positions) p *= 1.3f;+ d.mesh.recomputeAllNormals();+ d.mesh.markAllDirty();+ d.bvhDirty = true;+ CHECK(run(d, "subdiv_level", {{"level", 2.0}}).ok);+ const float moved = maxDistance(d.mesh.positions, topRest);+ CHECK(moved > 0.1f);+ // Morph to Set at the top, from a set stored at the base: back to (nearly) the old top.+ CHECK(run(d, "selection_set_morph", {{"name", "Rest"}}).ok);+ CHECK(maxDistance(d.mesh.positions, topRest) < moved * 0.05f);+ // The Morph brush resolves the target at this level too.+ CHECK(run(d, "selection_set_morph_target", {{"name", "Rest"}}).ok);+ Sculptor probe;+ const std::vector<glm::vec3>* target = probe.morphTarget(d.mesh);+ CHECK(target && target->size() == d.mesh.vertexCount());+}++TEST(selection_sets_project_roundtrip) {+ Document d = makeDoc(makeIcosphere(3));+ paintState(d.mesh, 0.0f, true);+ CHECK(run(d, "selection_set_store", {{"name", "Everything"}, {"channels", "all"}}).ok);+ CHECK(run(d, "selection_set_store", {{"name", "Mask only"}, {"channels", "mask"}}).ok);+ CHECK(run(d, "selection_set_morph_target", {{"name", "Everything"}}).ok);+ const Mesh saved = d.mesh;+ // A second Part with its own set.+ d.addSubtool(makeCube(2), "Box");+ CHECK(run(d, "selection_set_from_visible", {{"name", "Box visible"}}).ok);+ const std::string path = tempPath("sf_selection_sets.sfproj");+ std::string err;+ CHECK(saveProject(path, d, err));+ Document back;+ CHECK(loadProject(path, back, err));+ CHECK(back.subtoolCount() == 2);+ back.selectSubtool(0);+ CHECK(setCount(back.mesh) == 2);+ CHECK(back.mesh.selectionSets && back.mesh.selectionSets->morphTarget == "Everything");+ SelectionSetData a, b;+ decodeSelectionSet(*setNamed(saved, "Everything"), kSetAllChannels, a);+ decodeSelectionSet(*setNamed(back.mesh, "Everything"), kSetAllChannels, b);+ CHECK(a.mask == b.mask && a.colors == b.colors && a.hidden == b.hidden && a.polygroups == b.polygroups &&+ a.positions == b.positions && a.uvs == b.uvs);+ back.selectSubtool(1);+ CHECK(setNamed(back.mesh, "Box visible"));+ // Undo isn't carried by projects: the loaded list is simply there.+ CHECK(!back.undo.canUndo());+ std::filesystem::remove(path);+}++TEST(selection_sets_old_projects) {+ // A project saved before selection sets existed loads without any, and gains them.+ Document d;+ std::string err;+ CHECK(loadProject(SF_TEST_DATA_DIR "/levels_v5_sphere.sfproj", d, err));+ CHECK(!d.mesh.selectionSets);+ CHECK(subdivLevelCount(d.mesh) > 1);+ CHECK(run(d, "selection_set_store", {{"name", "At level"}, {"channels", "mask,morph"}}).ok);+ const std::string path = tempPath("sf_selection_sets_levels.sfproj");+ CHECK(saveProject(path, d, err));+ Document back;+ CHECK(loadProject(path, back, err));+ CHECK(setCount(back.mesh) == 1 && setNamed(back.mesh, "At level")->level == subdivCurrentLevel(back.mesh));+ CHECK(run(back, "subdiv_level", {{"level", 1.0}}).ok);+ CHECK(run(back, "selection_set_restore", {{"name", "At level"}}).ok);+ std::filesystem::remove(path);+}++TEST(selection_sets_file_export_import) {+ Document d = makeDoc(makeIcosphere(3));+ paintState(d.mesh);+ CHECK(run(d, "selection_set_store", {{"name", "A"}, {"channels", "mask,visibility"}}).ok);+ CHECK(run(d, "selection_set_store", {{"name", "B"}, {"channels", "polygroups"}}).ok);+ const std::string path = tempPath("sf_sets.sfsets");+ CHECK(run(d, "selection_sets_export", {{"path", path}}).ok);+ Document other = makeDoc(makeIcosphere(3));+ CHECK(run(other, "selection_sets_import", {{"path", path}}).ok);+ CHECK(setCount(other.mesh) == 2);+ CHECK(run(other, "selection_set_restore", {{"name", "A"}}).ok);+ CHECK(other.mesh.mask == d.mesh.mask && other.mesh.hidden == d.mesh.hidden);+ CHECK(run(other, "undo").ok);+ CHECK(run(other, "undo").ok);+ CHECK(setCount(other.mesh) == 0);+ // One set only; a mesh it doesn't fit says so.+ CHECK(run(d, "selection_sets_export", {{"path", path}, {"name", "B"}}).ok);+ Document small = makeDoc(makeIcosphere(1));+ const CommandResult r = run(small, "selection_sets_import", {{"path", path}});+ CHECK(r.ok && r.message.find("don't fit") != std::string::npos && setCount(small.mesh) == 1);+ CHECK(!registry().execute(small, "selection_set_restore", {{"name", "B"}}).ok);+ CHECK(!registry().execute(small, "selection_sets_import", {{"path", tempPath("sf_sets_missing.sfsets")}}).ok);+ std::filesystem::remove(path);+}++TEST(selection_sets_usd_roundtrip) {+ Document d = makeDoc(makeIcosphere(3));+ paintState(d.mesh, 0.0f, true);+ CHECK(run(d, "selection_set_store", {{"name", "Front half"}, {"channels", "mask,polygroups,visibility,paint"}}).ok);+ const Mesh expected = d.mesh;+ const std::string path = tempPath("sf_sets.usda");+ std::string err;+ CHECK(saveUsd(path, &d.mesh, nullptr, "Sculpt", err));+ Mesh back;+ SplatCloud splats;+ CHECK(loadUsd(path, back, splats, err));+ CHECK(back.vertexCount() == expected.vertexCount() && back.triangleCount() == expected.triangleCount());+ const SelectionSet* s = setNamed(back, "Front half");+ CHECK(s && s->has(kSetMask) && s->has(kSetVisibility) && s->has(kSetPolygroups) && s->has(kSetPaint));+ if (s) {+ SelectionSetData a;+ decodeSelectionSet(*s, kSetAllChannels, a);+ CHECK(a.hidden == expected.hidden);+ CHECK(a.polygroups == expected.polygroups);+ float diff = 0.0f;+ for (size_t v = 0; v < a.mask.size() && v < expected.mask.size(); ++v) diff = std::max(diff, std::abs(a.mask[v] - expected.mask[v]));+ CHECK(a.mask.size() == expected.mask.size() && diff < 1e-5f);+ }+ std::filesystem::remove(path);+}diff --git a/tests/ui/selection_sets.sfui b/tests/ui/selection_sets.sfuinew file mode 100644index 00000000..c4fd86f7--- /dev/null+++ b/tests/ui/selection_sets.sfui@@ -0,0 +1,67 @@+# Tool > Selection Sets: store the mask under a name, clear it, restore it (one undo step), a quick set from the+# visible faces, and a shape set as the Morph brush's target pulling a sculpted bump back.+run new_sphere subdivisions=5+run mask_rect x0=-1 y0=0.3 x1=1 y1=1+expect_value masked > 100+remember masked stored+key f++click "Selection Sets##tool.selection_sets"+expect "Store##selsets"+expect_text No sets yet+hold ctrl+hover "Store##selsets"+expect_help "named set"+hold none+type "##setname" Head+click "Store##selsets"+expect_status Stored selection set 'Head'+expect_value selection_sets == 1+expect "Head##set0"++# Restore brings the mask back exactly; undo takes it away again, redo restores it.+run mask_clear+expect_value masked == 0+click "Restore##selsets"+expect_status Restored selection set 'Head'+expect_value masked == $stored+key ctrl+z+expect_value masked == 0+key ctrl+shift+z+expect_value masked == $stored+shot selection_sets_restored++# Quick set from the visible faces.+click "From Visible##selsets"+expect_status Stored selection set 'Visible'+expect_value selection_sets == 2++# A shape set: the Morph Target button picks the Morph brush, whose strokes pull a bump back.+run mask_clear+click "Shape##setch"+type "##setname" Rest+click "Store##selsets"+expect_value selection_sets == 3+click "Rest##set2"+click "Morph Target##selsets"+expect_status Morph brush now pulls toward selection set 'Rest'+expect_value morph_target == 1+expect_value morph_brush == 1+snapshot+run stroke points="-0.3,0,2 0.3,0,2" brush=Standard radius=0.4 strength=1+run stroke points="-0.3,0,2 0.3,0,2" brush=Standard radius=0.4 strength=1+expect_value moved_max > 0.01+remember moved_max bump+stroke 0.3 0.5 0.7 0.5+stroke 0.3 0.5 0.7 0.5+stroke 0.3 0.5 0.7 0.5+expect_value moved_max < $bump+shot selection_sets_morph++# Delete is undoable.+click "Delete##selsets"+expect_value selection_sets == 2+expect_value morph_target == 0+key ctrl+z+expect_value selection_sets == 3+expect_value morph_target == 1diff --git a/tests/ui/whats_new.sfui b/tests/ui/whats_new.sfuiindex 466eda30..b348453e 100644--- a/tests/ui/whats_new.sfui+++ b/tests/ui/whats_new.sfui@@ -4,8 +4,9 @@ click "Help##palette.help"click "What's New##help.whats_new"expect_value guide_open == 1expect_guide whats-new.md+expect_text "Version 0.10.5"+expect_text "Morph to Set"expect_text "Version 0.10.4"-expect_text "Keep Masked"expect_text "Version 0.10.3"expect_text "Version 0.10.2"expect_text "Version 0.9.6"@@ -23,7 +24,7 @@ expect_text "Version 0.6"expect_text "Version 0.5"expect_text "Version 0.4.2"# The newest section is on screen.-expect_text "Insert your own mesh"+expect_text "Selection sets"shot whats-new# The end of the chapter: a quiet line about supporting SculptForge; its button only asks for the website's page