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
ZSpheres (#8): block out a base mesh from connected spheres
islandmeddf460541daec
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex f5636cd1..cc6b4eed 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -6,6 +6,9 @@ All notable changes to SculptForge are listed here. The format follows## [Unreleased]+### Added+- ZSpheres (Tool > ZSpheres, #8): block out a base mesh from connected spheres. Draw grows a sphere from another (the drag sets its size) or adds a joint on a link, Move and Scale set the proportions, Alt+click deletes, Symmetry mirrors every edit, Preview (A) shows the skin, and Make Mesh builds it as a new watertight quad SubTool with a polygroup per link, keeping the ZSpheres hidden to edit again. Undoable, saved in projects, and scriptable (zsphere_new, zsphere_add, zsphere_set, zsphere_delete, zsphere_insert, zsphere_preview, zsphere_make_mesh, zsphere_list).+## [0.9.4] - 2026-10-29### Fixeddiff --git a/CMakeLists.txt b/CMakeLists.txtindex ce4f6d43..c5159760 100644--- a/CMakeLists.txt+++ b/CMakeLists.txt@@ -73,6 +73,7 @@ add_library(sculptforge_core STATICsrc/core/SurfaceQuery.cppsrc/core/QRemesh.cppsrc/core/QRemeshGuides.cpp+ src/core/ZSpheres.cppsrc/core/Projection.cppsrc/core/RetopoCommands.cppthird_party/xatlas/xatlas.cpp@@ -231,6 +232,7 @@ if(SCULPTFORGE_BUILD_APP)src/app/Gizmo.cppsrc/app/PanelBake.cppsrc/app/PanelRetopo.cpp+ src/app/PanelZSpheres.cppsrc/app/PanelSplatTrain.cppsrc/app/PanelSculptable.cppsrc/app/PanelPerformance.cppdiff --git a/docs/guide/glossary.md b/docs/guide/glossary.mdindex edb4073d..008caf28 100644--- a/docs/guide/glossary.md+++ b/docs/guide/glossary.md@@ -13,7 +13,7 @@ for what is planned.| BPR render | Not yet as a renderer. Headless renders and turntables with `sculptforge --render` ([Scripting](scripting.md)) || Brush pop-up (B) | **Brush picker**, <kbd>B</kbd>, then type letters (B S T = Standard) || Clip brushes | Not yet. The **Trim** brush shaves to a plane |-| Curve brushes, IMM, ZModeler, ZSpheres | Not yet |+| Curve brushes, IMM, ZModeler | Not yet || Decimation Master | **Tool > Geometry > Decimate** (`decimate`). See [Geometry](geometry.md#decimate) || Del Hidden | **Tool > Visibility > Delete hidden** (`delete_hidden`) || Del Lower, Del Higher | **Tool > Geometry > Del Lower / Del Higher** (`subdiv_delete_lower`, `subdiv_delete_higher`). See [Subdivision levels](subdivision-levels.md) |@@ -68,6 +68,7 @@ for what is planned.| ZPlugin | No in-app plugin system yet. Automate with the Python module, `sculptforge-cli` and MCP ([Scripting](scripting.md)) || ZRemesher | **Tool > Geometry > QRemesh** (`qremesh`): Target Polygons, Half / Same / Double, Adaptive Size, Keep Groups, Use Polypaint, symmetry. No curve guides yet. See [Quad retopology](retopology.md) || ZScript | Script commands: the console (backtick key), script files, `sculptforge-cli`. See [Scripting](scripting.md) |+| ZSpheres, Adaptive Skin, Preview (A) | **Tool > ZSpheres**: Draw, Move, Scale, Alt+click deletes, **Preview** (<kbd>A</kbd>), **Make Mesh** (`zsphere_make_mesh`). See [ZSpheres](zspheres.md) || ZTL, ZPR files | Not read directly. Convert ZTools with the ZTool Export plug-in for ZBrush (then open the `.ZTL`), or use GoZ, OBJ, FBX or GLB; save work as `.sfproj` |## SculptForge termsdiff --git a/docs/guide/index.md b/docs/guide/index.mdindex a56437b1..6a712cab 100644--- a/docs/guide/index.md+++ b/docs/guide/index.md@@ -27,39 +27,40 @@ You can read it inside SculptForge (**Help > User Guide**, or <kbd>Shift</kbd>+<9. [Masking](masking.md)10. [Polygroups and visibility](polygroups.md)11. [SubTools](subtools.md)-12. [Polypaint and materials](polypaint.md)-13. [Texture painting](texture-painting.md)-14. [Sculpt layers and blend shapes](layers.md)-15. [Facial shapes and live face](facial-shapes.md)-16. [Subdivision levels](subdivision-levels.md)-17. [Dynamic topology](dynamic-topology.md)-18. [Moving, rotating and posing (Gizmo 3D)](gizmo.md)-19. [Subdivide, remesh, decimate and LODs](geometry.md)-20. [Quad retopology and detail projection](retopology.md)+12. [ZSpheres](zspheres.md)+13. [Polypaint and materials](polypaint.md)+14. [Texture painting](texture-painting.md)+15. [Sculpt layers and blend shapes](layers.md)+16. [Facial shapes and live face](facial-shapes.md)+17. [Subdivision levels](subdivision-levels.md)+18. [Dynamic topology](dynamic-topology.md)+19. [Moving, rotating and posing (Gizmo 3D)](gizmo.md)+20. [Subdivide, remesh, decimate and LODs](geometry.md)+21. [Quad retopology and detail projection](retopology.md)## AI and capture-21. [Image and text to 3D](generate-3d.md)-22. [Gaussian splats](splats.md)-23. [Scan an object into a splat](scan-to-splat.md)-24. [From scan to sculptable mesh](scan-to-sculptable.md)-25. [Phone capture and AR](phone-capture.md)+22. [Image and text to 3D](generate-3d.md)+23. [Gaussian splats](splats.md)+24. [Scan an object into a splat](scan-to-splat.md)+25. [From scan to sculptable mesh](scan-to-sculptable.md)+26. [Phone capture and AR](phone-capture.md)## Files and pipelines-26. [Baking normal and displacement maps](baking.md)-27. [Exporting, Unreal and ZBrush](exporting.md)-28. [Working with Blender](blender.md)-29. [Projects, autosave and QuickSave](projects.md)-30. [Scripting and automation](scripting.md)-31. [SculptForge for studios](studios.md)+27. [Baking normal and displacement maps](baking.md)+28. [Exporting, Unreal and ZBrush](exporting.md)+29. [Working with Blender](blender.md)+30. [Projects, autosave and QuickSave](projects.md)+31. [Scripting and automation](scripting.md)+32. [SculptForge for studios](studios.md)## Reference-32. [Keyboard and mouse](shortcuts.md)-33. [Performance and big meshes](performance.md)-34. [Troubleshooting and FAQ](troubleshooting.md)-35. [Glossary](glossary.md)+33. [Keyboard and mouse](shortcuts.md)+34. [Performance and big meshes](performance.md)+35. [Troubleshooting and FAQ](troubleshooting.md)+36. [Glossary](glossary.md)## Getting helpdiff --git a/docs/guide/shortcuts.md b/docs/guide/shortcuts.mdindex 62e9af3b..e11ea465 100644--- a/docs/guide/shortcuts.md+++ b/docs/guide/shortcuts.md@@ -125,6 +125,7 @@ action registry, the same source as the Controls window.| Invert Mask | <kbd>Ctrl</kbd>+<kbd>I</kbd> | Mask what is unmasked and unmask what is masked (also: Ctrl+click the background). || Lower Res | <kbd>Shift</kbd>+<kbd>D</kbd> | Step one subdivision level down (fewer polygons, for big forms). The detail of the higher levels is kept. || Mask All | <kbd>Ctrl</kbd>+<kbd>A</kbd> | Mask the whole visible SubTool. |+| Preview | <kbd>A</kbd> | Show the skin Make Mesh would build instead of the spheres (ZBrush's Preview). Turn it off to edit the spheres again. |### Transformdiff --git a/docs/guide/welcome.md b/docs/guide/welcome.mdindex bdc437bf..a9aa2caa 100644--- a/docs/guide/welcome.md+++ b/docs/guide/welcome.md@@ -52,7 +52,7 @@ still on the roadmap:- UV editing (seams, relax) and UDIM tiles.- Booleans and stencils.-Others are not on the roadmap: ZSpheres, ZModeler, the 2.5D canvas, and reading ZBrush's own `.ZTL` and `.ZPR`+Others are not on the roadmap: ZModeler, the 2.5D canvas, and reading ZBrush's own `.ZTL` and `.ZPR`files directly (bring models over with GoZ, the ZTool Export plug-in for ZBrush, or as OBJ, FBX or GLB).> **Not yet:** where a chapter describes a ZBrush feature SculptForge doesn't have, it says so in a calloutdiff --git a/docs/guide/zspheres.md b/docs/guide/zspheres.mdnew file mode 100644index 00000000..1ebf51fe--- /dev/null+++ b/docs/guide/zspheres.md@@ -0,0 +1,74 @@+# ZSpheres++ZSpheres block out an organic base mesh from connected spheres: start from one root sphere, grow a torso, a head,+limbs, fingers, a tail or branches from it, set the proportions, look at the skin over them, then turn it into a+mesh you sculpt as usual. It is the quickest way to get the structure of a character or creature before any detail.++> **ZBrush:** this is ZSpheres with Adaptive Skin: Draw, Move and Scale on the spheres, Alt+click to delete,+> **A** to preview the skin, and **Make Mesh** in place of Make Adaptive Skin. Rotate mode, ZSketch, the+> Topology and Rigging uses of ZSpheres and the link-sphere (magnet) tricks are not there.++## Make a ZSphere SubTool++**Tool > ZSpheres > New ZSphere** adds a ZSphere SubTool holding one root sphere at the centre and makes it active.+It sits in the SubTool list like any other SubTool, so you can block out a creature next to a model you already+have.++While a ZSphere SubTool is active, dragging on it edits the spheres instead of sculpting. Dragging the background+still navigates. The brush ring is hidden; the sphere under the cursor gets an outline instead.++## Edit the spheres++Pick the mode in **Tool > ZSpheres**:++| Mode | On a sphere | On a link |+|---|---|---|+| **Draw** | Drag to grow a new sphere from it. It starts on the surface where you pressed; how far you drag sets its size (a click makes one half the size of its parent) | Click to add a joint halfway along the link, and drag to place it |+| **Move** | Drag to move it across the screen. The links stretch to follow | Moves the sphere at the end of the link |+| **Scale** | Drag up or right to make it bigger, down or left to make it smaller | Scales the sphere at the end of the link |++In every mode, <kbd>Alt</kbd>+click a sphere to delete it together with everything that grows from it. The root+sphere (orange) always stays.++**Symmetry** (<kbd>X</kbd>) mirrors every edit: grow an arm on the right and the left one grows with it, move a+leg and its twin moves too. A sphere on the centre line stays on it.++Every drag is one step of the SubTool's undo history, so <kbd>Ctrl</kbd>+<kbd>Z</kbd> takes back the last sphere+you added, moved or scaled.++> **Tip:** build the structure first with few spheres (one per joint), set the proportions with Move and Scale,+> and add joints on links only where a limb needs to bend or swell.++## Preview the skin++**Preview** (<kbd>A</kbd>) shows the skin over the spheres instead of the spheres themselves, so you can judge the+volumes. The skin is a smooth union of the spheres and the cones between them, with the joints filled out a little.+Turn Preview off to edit the spheres again; while it is on, clicks on the model do nothing.++## Make Mesh++**Make Mesh** builds the skin as a new SubTool right below the ZSphere SubTool and makes it active:++- It is watertight and made of quads, ready for the brushes, [Dynamic topology](dynamic-topology.md),+ [Divide](subdivision-levels.md) or [QRemesh](retopology.md).+- Each link gets its own [polygroup](polygroups.md), so you can isolate or mask a limb straight away.+- **Resolution** sets how dense it is: cells across the model's longest side. 128 suits a blockout; raise it for+ thin fingers or tails that come out too thin or broken.++The ZSphere SubTool is hidden and kept. To change the proportions later, show and select it, edit the spheres and+Make Mesh again. The armature is saved with the project.++> **Tip:** for clean edge flow, run [QRemesh](retopology.md) on the new mesh, then Divide and sculpt.++## Scripting++The same operations are commands (see [Scripting](scripting.md)): `zsphere_new`, `zsphere_list`, `zsphere_add`,+`zsphere_set`, `zsphere_delete`, `zsphere_insert`, `zsphere_preview` and `zsphere_make_mesh`. For example, a+simple figure:++```+zsphere_new radius=0.5+zsphere_add parent=0 position=0,0.8,0 radius=0.3+zsphere_add parent=0 position=0.9,0.1,0 radius=0.2 symmetry=x+zsphere_make_mesh resolution=160+```diff --git a/src/app/App.cpp b/src/app/App.cppindex 7b72d0ba..2c5b34b9 100644--- a/src/app/App.cpp+++ b/src/app/App.cpp@@ -694,6 +694,7 @@ void App::onMouseDown(float x, float y, Uint8 button) {return;}if (button == SDL_BUTTON_LEFT) {+ if (zsphereMouseDown(x, y, mod)) return; // a ZSphere SubTool takes clicks on it (PanelZSpheres.cpp)if (polygroupMouseDown(x, y, mod)) return;if (maskSelectMouseDown(x, y, mod)) return;if (gizmoMouseDown(x, y, mod)) return; // Gizmo 3D handles, pivot clicks (Gizmo.cpp)@@ -784,6 +785,7 @@ void App::onMouseMove(float x, float y, float dx, float dy, bool fromPen) {case Drag::Gizmo: gizmoDragTo(x, y); break;case Drag::Guide: guideDragTo(x, y); break;case Drag::Sculptable: sculptableMouseMove(x, y); break;+ case Drag::ZSphere: zsphereDragTo(x, y); break;case Drag::None: break;}}@@ -827,6 +829,7 @@ void App::onMouseUp() {if (drag_ == Drag::SubToolClick) subtoolClickRelease();if (drag_ == Drag::Guide) guideRelease();if (drag_ == Drag::Sculptable) sculptableMouseUp();+ if (drag_ == Drag::ZSphere) zsphereRelease();gizmoRelease();drag_ = Drag::None;dragFromPen_ = false;@@ -1324,11 +1327,12 @@ void App::drawUi() {const ImVec2 mouse(mouseX_, mouseY_);drawGizmo(); // Gizmo 3D handles and panel (Gizmo.cpp)drawQRemeshGuides(); // QRemesh Guides curves (PanelRetopo.cpp)+ drawZSphereOverlay(); // the sphere under the cursor (PanelZSpheres.cpp)drawFaceOverlay(); // facial landmarks (PanelFace.cpp)drawSplatTrainOverlay(); // splat training progress (PanelSplatTrain.cpp)drawSculptableOverlay(); // Make sculptable: crop box, face landmarks (PanelSculptable.cpp)// In Gizmo mode (and with the QRemesh Guides brush) the brush ring shows only while Ctrl masks or Shift smooths.- const bool ringOff = gizmoActive() || (guidesMode_ && !(inputMods() & SDL_KMOD_SHIFT)) || sculptableHot();+ const bool ringOff = gizmoActive() || (guidesMode_ && !(inputMods() & SDL_KMOD_SHIFT)) || sculptableHot() || zsphereActive();if (((!ImGui::GetIO().WantCaptureMouse && canvasRect().contains(mouse.x, mouse.y)) || drag_ == Drag::Stroke) &&!hideBrushCursor_ && drag_ != Drag::Select && drag_ != Drag::Guide &&(!ringOff || drag_ == Drag::Stroke || ctrlDown(inputMods())))diff --git a/src/app/App.h b/src/app/App.hindex fec5058a..5d4d0d38 100644--- a/src/app/App.h+++ b/src/app/App.h@@ -103,7 +103,7 @@ public:void queueFile(FileAction action, std::string path);private:- enum class Drag { None, Stroke, Orbit, Pan, Zoom, Roll, MaskCanvas, SubToolClick, Select, Gizmo, Guide, Sculptable };+ enum class Drag { None, Stroke, Orbit, Pan, Zoom, Roll, MaskCanvas, SubToolClick, Select, Gizmo, Guide, Sculptable, ZSphere };void handleEvent(const SDL_Event& e);void onMouseDown(float x, float y, Uint8 button);@@ -598,6 +598,30 @@ private:// Which guide points face the camera (drawn solid; the others faint), cached per view and guide set.std::vector<std::vector<uint8_t>> guideVisible_;uint64_t guideVisibleKey_ = 0;+ // ZSpheres (PanelZSpheres.cpp, core/ZSpheres.h): while a ZSphere SubTool is active, clicks on it draw, move,+ // scale or delete spheres instead of sculpting; each drag is one undo step.+ enum class ZSphereMode { Draw, Move, Scale };+ void registerZSphereUiActions();+ void drawZSpheresContents(); // Tool > ZSpheres+ bool zsphereMouseDown(float x, float y, SDL_Keymod mod); // true if it took the click+ void zsphereDragTo(float x, float y);+ void zsphereRelease();+ void drawZSphereOverlay(); // the hovered sphere's outline+ bool zsphereActive() const { return !doc_.mesh.zspheres.empty(); }+ int zsphereAt(float x, float y, bool* link = nullptr) const; // sphere (or link's child) under the cursor, or -1+ float worldPerPixel(const glm::vec3& at) const; // world size of one canvas pixel at `at`'s depth+ ZSphereMode zsphereMode_ = ZSphereMode::Draw;+ int zsphereResolution_ = 128; // Make Mesh resolution+ struct ZSphereDrag {+ ZSphereMode op = ZSphereMode::Draw; // what this drag does (a Draw click on a link then moves the new joint)+ int sphere = -1; // the sphere being drawn, moved or scaled+ std::vector<ZSphere> start; // the armature when the drag began+ Mesh before; // the SubTool's mesh then (the undo step's old state)+ glm::vec3 grab{0.0f}; // Move: the centre's offset from the grab plane's hit+ float x = 0.0f, y = 0.0f; // where the press was+ bool changed = false;+ const char* label = "";+ } zsDrag_;const BrushRecipe* strokeRecipe() const; // recipe the current stroke sculpts with (none for Smooth / paint only)// ZBrush GoZ bridge and GoZ/STL files (PanelGoz.cpp).void drawGozMenu();diff --git a/src/app/Config.cpp b/src/app/Config.cppindex 6ee38d3d..2f9e57d7 100644--- a/src/app/Config.cpp+++ b/src/app/Config.cpp@@ -370,6 +370,7 @@ void App::initActions() {registerGizmoActions(); // Q W E R: Draw, and the Gizmo 3D's Move, Scale, Rotate (Gizmo.cpp)registerBakeUiActions(); // Tool > Bake (PanelBake.cpp)registerRetopoUiActions(); // Geometry > QRemesh, SubTool > ProjectAll (PanelRetopo.cpp)+ registerZSphereUiActions(); // Tool > ZSpheres (PanelZSpheres.cpp)registerSplatTrainUi(); // Splats > Train from capture (PanelSplatTrain.cpp)registerSculptableUiActions(); // Splats > Make sculptable (PanelSculptable.cpp)registerVdmActions(); // Brush > Vector Displacement (PanelVdm.cpp)diff --git a/src/app/Palettes.cpp b/src/app/Palettes.cppindex 1b8c552d..3ab0e0ef 100644--- a/src/app/Palettes.cpp+++ b/src/app/Palettes.cpp@@ -496,6 +496,12 @@ void App::drawPalette_Tool() {drawProjectContents(); // ProjectAll (PanelRetopo.cpp)Demo::popScope();}+ if (subpalette("tool.zspheres", "ZSpheres")) {+ tray::Section section;+ Demo::pushScope("ZSpheres");+ drawZSpheresContents(); // PanelZSpheres.cpp+ Demo::popScope();+ }if (subpalette("tool.layers", "Layers")) {tray::Section section;Demo::pushScope("Layers");diff --git a/src/app/PanelZSpheres.cpp b/src/app/PanelZSpheres.cppnew file mode 100644index 00000000..0718f79a--- /dev/null+++ b/src/app/PanelZSpheres.cpp@@ -0,0 +1,281 @@+// SculptForge - open source digital sculpting+// SPDX-License-Identifier: GPL-3.0-or-later+//+// Tool > ZSpheres and the ZSphere tool in the viewport (ZBrush's ZSpheres, core/ZSpheres.h). While a ZSphere+// SubTool is active a left-drag on it edits the armature instead of sculpting:+// Draw - drag on a sphere to grow a new one from it (the drag sets its size); click a link to add a joint there+// and drag to place it+// Move - drag a sphere to move it across the screen+// Scale - drag a sphere up/right to grow it, down/left to shrink it+// Alt+click a sphere deletes it with everything growing from it. Symmetry mirrors every edit.+// Dragging the background navigates as usual. Every drag is one undo step (the SubTool's mesh, which carries+// the armature, is replaced once at release); the panel's buttons run the zsphere_* commands.+#include "app/App.h"+#include "app/Palettes.h"+#include "app/Ui.h"++#include "core/ZSpheres.h"++#include <algorithm>+#include <cmath>++namespace sf {++namespace {++constexpr const char* kZSpheresPath = "Tool > ZSpheres";++const char* modeName(int m) { return m == 0 ? "Draw" : m == 1 ? "Move" : "Scale"; } // App::ZSphereMode order++// Where the ray o + t*d meets the plane through p with normal n (t clamped to stay in front).+glm::vec3 planeHit(const glm::vec3& o, const glm::vec3& d, const glm::vec3& p, const glm::vec3& n) {+ const float dn = glm::dot(d, n);+ const float t = std::abs(dn) > 1e-12f ? glm::dot(p - o, n) / dn : 0.0f;+ return o + d * std::max(t, 0.0f);+}++} // namespace++void App::registerZSphereUiActions() {+ auto add = [this](const char* id, const char* label, std::function<void()> run, std::function<bool()> enabled,+ std::function<bool()> checked, const char* description, const char* command = "",+ const char* shortcut = "") {+ Action a;+ a.id = id;+ a.label = label;+ a.palette = kZSpheresPath;+ a.run = std::move(run);+ a.enabled = std::move(enabled);+ a.checked = std::move(checked);+ a.description = description;+ a.command = command;+ a.shortcut = shortcut;+ actions_.add(std::move(a));+ };+ const auto active = [this] { return zsphereActive(); };+ add("zsphere.new", "New ZSphere", [this] { runCommand("zsphere_new"); }, nullptr, nullptr,+ "Add a ZSphere SubTool: one root sphere to block out a body, creature or plant from. Drag on a sphere to grow "+ "limbs from it, Move and Scale them into proportion, check the skin with Preview (A), then Make Mesh.",+ "zsphere_new");+ const auto mode = [this](ZSphereMode m) {+ return [this, m] {+ zsphereMode_ = m;+ status_ = std::string("ZSpheres: ") + modeName(int(m)) ++ (m == ZSphereMode::Draw ? " - drag on a sphere to grow a new one; click a link to add a joint"+ : m == ZSphereMode::Move ? " - drag a sphere to move it"+ : " - drag a sphere up or right to grow it, down or left to shrink it");+ };+ };+ add("zsphere.draw", "Draw", mode(ZSphereMode::Draw), active, [this] { return zsphereMode_ == ZSphereMode::Draw; },+ "Drag on a sphere to grow a new sphere from it (how far you drag sets its size). Click a link between two "+ "spheres to add a joint there, and drag to place it. Alt+click a sphere to delete it.");+ add("zsphere.move", "Move", mode(ZSphereMode::Move), active, [this] { return zsphereMode_ == ZSphereMode::Move; },+ "Drag a sphere to move it; the links stretch to follow. Symmetry moves its mirror twin too.");+ add("zsphere.scale", "Scale", mode(ZSphereMode::Scale), active, [this] { return zsphereMode_ == ZSphereMode::Scale; },+ "Drag a sphere up or right to make it bigger, down or left to make it smaller.");+ add("zsphere.preview", "Preview", [this] { runCommand("zsphere_preview"); }, active,+ [this] { return doc_.mesh.zspherePreview; },+ "Show the skin Make Mesh would build instead of the spheres (ZBrush's Preview). Turn it off to edit the "+ "spheres again.",+ "zsphere_preview", "A");+ add("zsphere.make_mesh", "Make Mesh",+ [this] { runCommand("zsphere_make_mesh", {{"resolution", double(zsphereResolution_)}}); }, active, nullptr,+ "Build the skin as a new, sculptable SubTool right below (watertight quads, one polygroup per link), like "+ "ZBrush's Make Adaptive Skin. The ZSphere SubTool is hidden and kept: show it to change the proportions and "+ "make a new mesh.",+ "zsphere_make_mesh");+}++void App::drawZSpheresContents() {+ const ImGuiStyle& style = ImGui::GetStyle();+ const float full = ImGui::GetContentRegionAvail().x;+ const float half = (full - style.ItemSpacing.x) * 0.5f;+ if (!zsphereActive()) {+ ui::ActionButton(*this, "zsphere.new", ImVec2(full, 0));+ ImGui::PushTextWrapPos(0.0f);+ ImGui::TextDisabled("Block out a base mesh from connected spheres, then Make Mesh to sculpt it.");+ ImGui::PopTextWrapPos();+ return;+ }+ tray::GroupLabel(*this, "Edit");+ const float third = (full - 2.0f * style.ItemSpacing.x) / 3.0f;+ ui::ActionButton(*this, "zsphere.draw", ImVec2(third, 0));+ ImGui::SameLine();+ ui::ActionButton(*this, "zsphere.move", ImVec2(third, 0));+ ImGui::SameLine();+ ui::ActionButton(*this, "zsphere.scale", ImVec2(-1, 0));+ ui::ActionButton(*this, "zsphere.preview", ImVec2(half, 0));+ ImGui::SameLine();+ ImGui::AlignTextToFramePadding();+ ImGui::TextDisabled("%zu %s", doc_.mesh.zspheres.size(), doc_.mesh.zspheres.size() == 1 ? "sphere" : "spheres");+ tray::GroupLabel(*this, "Make Mesh");+ ui::ActionButton(*this, "zsphere.make_mesh", ImVec2(half, 0));+ ImGui::SameLine();+ ImGui::SetNextItemWidth(-1);+ tray::SliderInt("##zsres", &zsphereResolution_, 32, 512, "Resolution %d");+ ui::HelpText("Resolution", nullptr,+ "How dense Make Mesh's skin is: cells across the model's longest side. 128 suits a blockout; raise it "+ "for thin fingers or tails.",+ kZSpheresPath);+ ui::ActionButton(*this, "zsphere.new", ImVec2(full, 0));+}++float App::worldPerPixel(const glm::vec3& at) const {+ ImVec2 sp;+ if (!gizmoProject(at, sp)) return 0.0f;+ glm::vec3 o0, d0, o1, d1;+ canvasRay(sp.x, sp.y, o0, d0);+ canvasRay(sp.x + 1.0f, sp.y, o1, d1);+ const glm::vec3 n = glm::normalize(d0);+ return glm::length(planeHit(o1, d1, at, n) - planeHit(o0, d0, at, n));+}++int App::zsphereAt(float x, float y, bool* link) const {+ RayHit hit;+ if (!zsphereActive() || doc_.mesh.zspherePreview || !pick(x, y, hit)) return -1;+ const int i = zsphereOfGroup(doc_.mesh.polygroupAt(hit.triangle), link);+ return i >= 0 && size_t(i) < doc_.mesh.zspheres.size() ? i : -1;+}++bool App::zsphereMouseDown(float x, float y, SDL_Keymod mod) {+ if (!zsphereActive()) return false;+ RayHit hit;+ if (!pick(x, y, hit)) return false; // the background navigates+ if (doc_.mesh.zspherePreview) {+ status_ = "ZSpheres: Preview is on (A turns it off to edit the spheres)";+ return true;+ }+ bool link = false;+ const int i = zsphereOfGroup(doc_.mesh.polygroupAt(hit.triangle), &link);+ if (i < 0 || size_t(i) >= doc_.mesh.zspheres.size()) return true;+ if (mod & SDL_KMOD_ALT) { // delete the sphere and what grows from it+ if (link || i == 0) {+ status_ = i == 0 && !link ? "ZSpheres: the root sphere stays" : "ZSpheres: Alt+click a sphere to delete it";+ return true;+ }+ std::vector<ZSphere> s = doc_.mesh.zspheres;+ const size_t before = s.size();+ zsphereDelete(s, i, symmetry_);+ doc_.replaceMeshUndoable(zsphereMesh(s, false), "ZSphere delete");+ status_ = "ZSpheres: deleted " + std::to_string(before - s.size()) + " spheres; " + std::to_string(s.size()) + " left";+ return true;+ }+ ZSphereDrag& d = zsDrag_;+ d = {};+ d.start = doc_.mesh.zspheres;+ d.before = doc_.mesh;+ d.x = x;+ d.y = y;+ d.op = zsphereMode_;+ d.sphere = i;+ if (d.op == ZSphereMode::Draw && link) { // a joint on the link, then the drag places it+ zsphereInsert(d.start, i, symmetry_, &d.sphere);+ d.op = ZSphereMode::Move;+ d.label = "ZSphere insert";+ d.changed = true;+ doc_.mesh = zsphereMesh(d.start, false);+ doc_.mesh.topologyDirty = true;+ doc_.bvh.build(doc_.mesh);+ } else if (d.op == ZSphereMode::Draw) {+ d.label = "ZSphere add";+ } else {+ d.label = d.op == ZSphereMode::Move ? "ZSphere move" : "ZSphere scale";+ }+ if (d.op == ZSphereMode::Move) {+ glm::vec3 o, dir;+ canvasRay(x, y, o, dir);+ const glm::vec3 c = d.start[size_t(d.sphere)].center;+ d.grab = c - planeHit(o, dir, c, glm::normalize(dir));+ }+ if (d.op == ZSphereMode::Draw) zsphereDragTo(x, y); // the new sphere appears at once, at half its parent's size+ drag_ = Drag::ZSphere;+ return true;+}++void App::zsphereDragTo(float x, float y) {+ ZSphereDrag& d = zsDrag_;+ if (d.sphere < 0) return;+ std::vector<ZSphere> s = d.start;+ const ZSphere& z = s[size_t(d.sphere)];+ const float moved = std::hypot(x - d.x, y - d.y);+ switch (d.op) {+ case ZSphereMode::Draw: {+ // The new sphere sits on the parent's surface where the drag started, sized by the drag.+ glm::vec3 o, dir;+ canvasRay(d.x, d.y, o, dir);+ glm::vec3 n = -glm::normalize(dir);+ const float tc = glm::dot(z.center - o, glm::normalize(dir));+ const glm::vec3 closest = o + glm::normalize(dir) * tc;+ const float off = glm::length(closest - z.center);+ if (off < z.radius) // the front of the sphere under the press+ n = glm::normalize(closest - glm::normalize(dir) * std::sqrt(z.radius * z.radius - off * off) - z.center);+ const glm::vec3 c = z.center + n * z.radius;+ const float wpp = worldPerPixel(c);+ const float r = moved > 3.0f * uiScale_ && wpp > 0.0f ? std::max(moved * wpp, 0.02f * z.radius) : 0.5f * z.radius;+ zsphereAdd(s, d.sphere, c, r, symmetry_);+ status_ = "ZSpheres: new sphere, radius " + std::to_string(r).substr(0, 5);+ break;+ }+ case ZSphereMode::Move: {+ glm::vec3 o, dir;+ canvasRay(x, y, o, dir);+ const glm::vec3 c = planeHit(o, dir, z.center, glm::normalize(dir)) + d.grab;+ zsphereSet(s, d.sphere, c, z.radius, symmetry_);+ break;+ }+ case ZSphereMode::Scale: {+ const float amount = ((x - d.x) - (y - d.y)) / (120.0f * uiScale_);+ zsphereSet(s, d.sphere, z.center, std::max(z.radius * std::exp(amount), 1e-4f), symmetry_);+ break;+ }+ }+ doc_.mesh = zsphereMesh(s, false);+ doc_.mesh.topologyDirty = true;+ doc_.bvh.build(doc_.mesh);+ d.changed = true;+}++void App::zsphereRelease() {+ ZSphereDrag& d = zsDrag_;+ if (d.changed) {+ Mesh after = std::move(doc_.mesh);+ doc_.mesh = std::move(d.before);+ doc_.replaceMeshUndoable(std::move(after), d.label);+ status_ = std::string("ZSpheres: ") + d.label + "; " + std::to_string(doc_.mesh.zspheres.size()) + " spheres";+ }+ d = {};+}++void App::drawZSphereOverlay() {+ if (!zsphereActive() || doc_.mesh.zspherePreview || !doc_.activeSubtoolInfo().visible) return;+ if (ImGui::GetIO().WantCaptureMouse) return;+ const CanvasRect cr = canvasRect();+ if (!cr.contains(mouseX_, mouseY_)) return;+ const bool dragging = drag_ == Drag::ZSphere;+ if (drag_ != Drag::None && !dragging) return;+ bool link = false;+ const int i = dragging ? zsDrag_.sphere : zsphereAt(mouseX_, mouseY_, &link);+ if (i < 0 || size_t(i) >= doc_.mesh.zspheres.size()) return;+ const bool alt = !dragging && (inputMods() & SDL_KMOD_ALT);+ ImDrawList* dl = ImGui::GetBackgroundDrawList();+ dl->PushClipRect(ImVec2(cr.x, cr.y), ImVec2(cr.x + cr.w, cr.y + cr.h), true);+ const float s = uiScale_;+ const ImU32 col = alt ? IM_COL32(255, 90, 80, 230) : IM_COL32(120, 200, 255, 230);+ if (link && !dragging) { // Draw: the joint a click would add+ const ZSphere& c = doc_.mesh.zspheres[size_t(i)];+ const ZSphere& p = doc_.mesh.zspheres[size_t(c.parent)];+ ImVec2 m;+ const glm::vec3 mid = (c.center + p.center) * 0.5f;+ const float wpp = worldPerPixel(mid);+ if (zsphereMode_ == ZSphereMode::Draw && gizmoProject(mid, m) && wpp > 0.0f)+ dl->AddCircle(m, 0.5f * (c.radius + p.radius) / wpp, IM_COL32(120, 200, 255, 160), 48, 1.5f * s);+ } else {+ const ZSphere& z = doc_.mesh.zspheres[size_t(i)];+ ImVec2 c;+ const float wpp = worldPerPixel(z.center);+ if (gizmoProject(z.center, c) && wpp > 0.0f) dl->AddCircle(c, z.radius / wpp, col, 64, 2.0f * s);+ }+ dl->PopClipRect();+}++} // namespace sfdiff --git a/src/app/UiTest.cpp b/src/app/UiTest.cppindex 680fd391..ab92758f 100644--- a/src/app/UiTest.cpp+++ b/src/app/UiTest.cpp@@ -11,6 +11,8 @@// key COMBO e.g. enter, escape, ctrl+z, ctrl+shift+z, 3, comma, backtick, tab, f3, space, minus// hold MODS ctrl / shift / alt / ctrl+shift ... or none (for strokes and drags)// stroke U0 V0 U1 V1 [S] brush stroke across the model (fractions of its on-screen bounds)+// view_drag X0 Y0 X1 Y1 [S] left-drag in the viewport at window fractions, gliding there first like stroke (same+// point twice = a click)// drag X0 Y0 X1 Y1 [S] [release] left-drag in window fractions (rectangle hide, sliders...); release:// let go of the held modifiers halfway (ZBrush's Alt-drag, release Alt to zoom)// drag_item LABEL DX DY [S] left-drag from the item by DX DY pixels (scrubbing, dragging a tile out)@@ -288,6 +290,13 @@ double Demo::query(const std::string& name, bool& known) const {return double(n);}if (name == "guides_mode") return app_.guidesMode_ ? 1.0 : 0.0;+ if (name == "zspheres") return double(m.zspheres.size());+ if (name == "zsphere_preview") return m.zspherePreview ? 1.0 : 0.0;+ if (name.rfind("zsphere_x", 0) == 0 || name.rfind("zsphere_r", 0) == 0) { // zsphere_x2, zsphere_r2: sphere 2's x / radius+ const size_t i = size_t(std::atoi(name.c_str() + 9));+ if (i >= m.zspheres.size()) return -1.0;+ return name[8] == 'x' ? double(m.zspheres[i].center.x) : double(m.zspheres[i].radius);+ }if (name == "quads") return double(m.quadCount());if (name == "quad_percent")return m.triangleCount() ? 100.0 * double(m.quadCount()) / double(m.triangleCount() - m.quadCount()) : 0.0;@@ -626,6 +635,18 @@ bool Demo::parseStep(int line, const std::vector<std::string>& w, std::string& e}, seconds);run([this] { SDL_SetModState(held_); });wait(0.1f);+ } else if (verb == "view_drag") {+ // view_drag x0 y0 x1 y1 [seconds]: press, drag and release at window fractions, gliding there first like+ // stroke (so the panels have let go of the mouse); the same point twice is a click.+ if (!need(4)) return false;+ const float x0 = num(1, 0), y0 = num(2, 0), x1 = num(3, 0), y1 = num(4, 0), seconds = num(5, 0.4f);+ stroke([this, x0, y0, x1, y1](float u) {+ int ww = 0, wh = 0;+ SDL_GetWindowSize(app_.window_, &ww, &wh);+ return ImVec2((x0 + (x1 - x0) * u) * float(ww), (y0 + (y1 - y0) * u) * float(wh));+ }, seconds);+ run([this] { SDL_SetModState(held_); });+ wait(0.1f);} else if (verb == "click_subtool") {if (!need(1)) return false;const std::string name = w[1];diff --git a/src/core/Commands.cpp b/src/core/Commands.cppindex 5d9184aa..817fa3d2 100644--- a/src/core/Commands.cpp+++ b/src/core/Commands.cpp@@ -21,6 +21,7 @@#include "core/Primitives.h"#include "core/Project.h"#include "core/QRemesh.h"+#include "core/ZSpheres.h"#include "core/Sculptable.h"#include "core/Splats.h"#include "core/TextureTransfer.h"@@ -580,6 +581,7 @@ CommandRegistry::CommandRegistry() {registerVdmCommands(*this); // vdm_set, vdm_capture, vdm_stamp, ... (Vdm.cpp)registerRetopoCommands(*this); // qremesh, project_all (RetopoCommands.cpp)registerQRemeshGuideCommands(*this); // qremesh_guide, ... (QRemeshGuides.cpp)+ registerZSphereCommands(*this); // zsphere_new, ... (ZSpheres.cpp)add({"stroke","Apply a brush along a path on the active SubTool, like dragging the cursor in the viewport (one undo "diff --git a/src/core/Mesh.h b/src/core/Mesh.hindex 98b7079c..cfbe9458 100644--- a/src/core/Mesh.h+++ b/src/core/Mesh.h@@ -77,6 +77,14 @@ struct SculptLayer {// a feature needs them, so plain meshes pay nothing. When present their size// always matches the vertex / triangle / corner count; rebuildTopology()// drops any that don't.+// One sphere of a ZSphere armature (core/ZSpheres.h): the root is index 0 with parent -1; every other sphere+// grows from `parent`.+struct ZSphere {+ glm::vec3 center{0.0f};+ float radius = 1.0f;+ int parent = -1;+};+class Mesh {public:std::vector<glm::vec3> positions;@@ -183,6 +191,11 @@ public:// copies of the mesh. Null = a plain mesh. sanitizeAttributes() drops it if the topology no longer fits.std::shared_ptr<MultiresStack> multires;+ // ZSpheres (core/ZSpheres.h): not empty = a ZSphere SubTool, whose triangles are made from this armature (the+ // spheres and their links, or the skin while `zspherePreview`). Copies, undo steps and projects carry it.+ std::vector<ZSphere> zspheres;+ bool zspherePreview = false;+size_t vertexCount() const { return positions.size(); }size_t triangleCount() const { return triangles.size(); }diff --git a/src/core/Project.cpp b/src/core/Project.cppindex 8841fa17..3375d5b5 100644--- a/src/core/Project.cpp+++ b/src/core/Project.cpp@@ -6,6 +6,7 @@#include "core/Texture.h"#include "core/ThreadPool.h"+#include "core/ZSpheres.h"#include "io/Zip.h"#include <algorithm>@@ -775,6 +776,10 @@ 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.zspheres.empty()) { // a ZSphere SubTool (core/ZSpheres.h); optional+ st.set("zspheres", zspheresToJson(m.zspheres));+ if (m.zspherePreview) st.set("zsphere_preview", true);+ }subtools.push(std::move(st));}manifest.set("subtools", std::move(subtools));@@ -883,6 +888,8 @@ bool loadProject(const std::string& path, Document& doc, std::string& error) {s.gozName = sj["goz_name"].asString();s.qremeshGuides = qremeshGuidesFromJson(sj["qremesh_guides"]);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);// The BVH builds (on the pool) while the levels and topology load (off it), then the normals.s.startBvh();r.parallelReads = !s.bvhBuilder.joinable();diff --git a/src/core/ZSpheres.cpp b/src/core/ZSpheres.cppnew file mode 100644index 00000000..17bd39d5--- /dev/null+++ b/src/core/ZSpheres.cpp@@ -0,0 +1,494 @@+// SculptForge - open source digital sculpting+// SPDX-License-Identifier: GPL-3.0-or-later+#include "core/ZSpheres.h"++#include "core/Commands.h"+#include "core/PathStroke.h"+#include "core/Primitives.h"+#include "core/ThreadPool.h"+#include "core/Voxel.h"++#include <algorithm>+#include <cmath>+#include <cstdio>+#include <limits>++namespace sf {++using glm::vec3;++namespace {++constexpr vec3 kSphereColor{0.62f, 0.60f, 0.56f};+constexpr vec3 kRootColor{0.80f, 0.55f, 0.36f};+constexpr vec3 kLinkColor{0.32f, 0.32f, 0.34f};+constexpr float kLinkThickness = 0.3f; // of each end's sphere radius+constexpr int kLinkSides = 12;++// Distance from p to a cone with rounded ends (spheres a/ra and b/rb), after Inigo Quilez's sdRoundCone.+// One sphere inside the other is just the bigger sphere.+float roundConeDistance(const vec3& p, const vec3& a, const vec3& b, float ra, float rb) {+ const vec3 ba = b - a;+ const float l2 = glm::dot(ba, ba);+ const float rr = ra - rb;+ const float a2 = l2 - rr * rr;+ if (a2 <= 1e-12f) return ra >= rb ? glm::length(p - a) - ra : glm::length(p - b) - rb;+ const float il2 = 1.0f / l2;+ const vec3 pa = p - a;+ const float y = glm::dot(pa, ba);+ const float z = y - l2;+ const vec3 xv = pa * l2 - ba * y;+ const float x2 = glm::dot(xv, xv);+ const float y2 = y * y * l2;+ const float z2 = z * z * l2;+ const float k = (rr > 0.0f ? 1.0f : rr < 0.0f ? -1.0f : 0.0f) * rr * rr * x2;+ const float sz = z > 0.0f ? 1.0f : z < 0.0f ? -1.0f : 0.0f;+ const float sy = y > 0.0f ? 1.0f : y < 0.0f ? -1.0f : 0.0f;+ if (sz * a2 * z2 > k) return std::sqrt(x2 + z2) * il2 - rb;+ if (sy * a2 * y2 < k) return std::sqrt(x2 + y2) * il2 - ra;+ return (std::sqrt(x2 * a2 * il2) + y * rr) * il2 - ra;+}++// Polynomial smooth minimum: blends over a band `k` wide.+float smoothMin(float a, float b, float k) {+ if (k <= 0.0f) return std::min(a, b);+ const float h = std::max(k - std::abs(a - b), 0.0f) / k;+ return std::min(a, b) - h * h * k * 0.25f;+}++// The pieces of the skin: one rounded cone per link, or the root alone.+struct Piece {+ vec3 a, b;+ float ra, rb;+ uint32_t group;+};++std::vector<Piece> skinPieces(const std::vector<ZSphere>& s) {+ std::vector<Piece> out;+ for (size_t i = 1; i < s.size(); ++i) {+ const ZSphere& p = s[size_t(s[i].parent)];+ out.push_back({p.center, s[i].center, p.radius, s[i].radius, kZSphereLinkGroup + uint32_t(i)});+ }+ if (out.empty() && !s.empty()) out.push_back({s[0].center, s[0].center, s[0].radius, s[0].radius, kZSphereGroup});+ return out;+}++float pieceDistance(const Piece& q, const vec3& p) { return roundConeDistance(p, q.a, q.b, q.ra, q.rb); }++// How wide the blend between two pieces is: a quarter of the thinner end, so joints fill out like ZBrush's skin.+float blendWidth(const Piece& q) { return 0.25f * std::min(q.ra, q.rb); }++// Mirrors of `sym` other than the identity.+std::vector<vec3> otherMirrors(Symmetry sym) {+ std::vector<vec3> m = Sculptor::mirrors(sym);+ m.erase(m.begin()); // mask 0: the identity+ return m;+}++bool validIndex(const std::vector<ZSphere>& s, int i) { return i >= 0 && size_t(i) < s.size(); }++// Every sphere in the subtrees rooted at `roots` (the roots too).+std::vector<char> subtrees(const std::vector<ZSphere>& s, const std::vector<int>& roots) {+ std::vector<char> gone(s.size(), 0);+ for (int r : roots) gone[size_t(r)] = 1;+ for (bool changed = true; changed;) { // parents may come after children (an inserted sphere), so until stable+ changed = false;+ for (size_t i = 1; i < s.size(); ++i)+ if (!gone[i] && gone[size_t(s[i].parent)]) gone[i] = 1, changed = true;+ }+ return gone;+}++// Appends `src` to `dst` (positions, triangles, one group, one colour).+void appendPart(Mesh& dst, const Mesh& src, uint32_t group, const vec3& color) {+ const uint32_t base = uint32_t(dst.positions.size());+ dst.positions.insert(dst.positions.end(), src.positions.begin(), src.positions.end());+ dst.colors.insert(dst.colors.end(), src.positions.size(), color);+ for (const glm::uvec3& t : src.triangles) dst.triangles.push_back(t + glm::uvec3(base));+ dst.polygroups.insert(dst.polygroups.end(), src.triangles.size(), group);+}++Mesh unitSphere() {+ static const Mesh sphere = makeIcosphere(3, 1.0f);+ return sphere;+}++// An open tapered tube from a (radius ra) to b (rb).+Mesh tube(const vec3& a, const vec3& b, float ra, float rb) {+ Mesh m;+ const vec3 axis = glm::normalize(b - a);+ const vec3 helper = std::abs(axis.y) < 0.9f ? vec3(0, 1, 0) : vec3(1, 0, 0);+ const vec3 u = glm::normalize(glm::cross(axis, helper)), v = glm::cross(axis, u);+ for (int i = 0; i < kLinkSides; ++i) {+ const float t = 6.28318530718f * float(i) / float(kLinkSides);+ const vec3 d = u * std::cos(t) + v * std::sin(t);+ m.positions.push_back(a + d * ra);+ m.positions.push_back(b + d * rb);+ }+ for (uint32_t i = 0; i < uint32_t(kLinkSides); ++i) {+ const uint32_t j = (i + 1) % uint32_t(kLinkSides);+ m.triangles.push_back({2 * i, 2 * j, 2 * i + 1});+ m.triangles.push_back({2 * j, 2 * j + 1, 2 * i + 1});+ }+ return m;+}++std::string fmt(const char* f, double a, double b = 0, double c = 0, double d = 0) {+ char buf[160];+ std::snprintf(buf, sizeof buf, f, a, b, c, d);+ return buf;+}++} // namespace++int zsphereOfGroup(uint32_t group, bool* link) {+ if (link) *link = group >= kZSphereLinkGroup;+ if (group >= kZSphereLinkGroup) return int(group - kZSphereLinkGroup);+ if (group >= kZSphereGroup) return int(group - kZSphereGroup);+ return -1;+}++std::string zspheresValidate(const std::vector<ZSphere>& s) {+ if (s.empty()) return "no spheres";+ if (s[0].parent != -1) return "sphere 0 must be the root (parent -1)";+ for (size_t i = 0; i < s.size(); ++i) {+ const ZSphere& z = s[i];+ if (!std::isfinite(z.center.x) || !std::isfinite(z.center.y) || !std::isfinite(z.center.z) ||+ !std::isfinite(z.radius) || !(z.radius > 0.0f))+ return "sphere " + std::to_string(i) + " has a bad position or size";+ if (i > 0 && (z.parent < 0 || size_t(z.parent) >= s.size() || size_t(z.parent) == i))+ return "sphere " + std::to_string(i) + " has a bad parent";+ }+ // Every sphere reaches the root.+ for (size_t i = 1; i < s.size(); ++i) {+ size_t at = i, steps = 0;+ while (at != 0 && steps++ <= s.size()) at = size_t(s[at].parent);+ if (at != 0) return "sphere " + std::to_string(i) + " is in a loop";+ }+ return {};+}++Mesh zsphereDisplayMesh(const std::vector<ZSphere>& s) {+ Mesh m;+ const Mesh& sphere = unitSphere();+ for (size_t i = 0; i < s.size(); ++i) {+ Mesh part = sphere;+ for (vec3& p : part.positions) p = s[i].center + p * s[i].radius;+ appendPart(m, part, kZSphereGroup + uint32_t(i), i == 0 ? kRootColor : kSphereColor);+ }+ for (size_t i = 1; i < s.size(); ++i) {+ const ZSphere& c = s[i];+ const ZSphere& p = s[size_t(c.parent)];+ if (glm::length(c.center - p.center) < 1e-6f * (c.radius + p.radius)) continue;+ appendPart(m, tube(p.center, c.center, kLinkThickness * p.radius, kLinkThickness * c.radius),+ kZSphereLinkGroup + uint32_t(i), kLinkColor);+ }+ m.rebuildTopology();+ m.recomputeAllNormals();+ m.zspheres = s;+ return m;+}++Mesh zsphereSkin(const std::vector<ZSphere>& s, int resolution, int smooth) {+ if (!zspheresValidate(s).empty()) return {};+ const std::vector<Piece> pieces = skinPieces(s);+ AABB box;+ float blend = 0.0f;+ for (const Piece& q : pieces) {+ const float pad = blendWidth(q);+ blend = std::max(blend, pad);+ box.expand(q.a - vec3(q.ra + pad)), box.expand(q.a + vec3(q.ra + pad));+ box.expand(q.b - vec3(q.rb + pad)), box.expand(q.b + vec3(q.rb + pad));+ }+ VoxelGrid grid;+ if (!makeVoxelGrid(box, std::clamp(resolution, 16, 1024), 2, grid)) return {};+ // Signed distance (negative inside), each piece only over its own box plus the blend band.+ std::vector<float> dist(grid.size(), std::numeric_limits<float>::max());+ const glm::ivec3 last = grid.dims - 1;+ for (const Piece& q : pieces) {+ const float pad = std::max(q.ra, q.rb) + blendWidth(q) + 2.0f * grid.cell;+ const vec3 lo = glm::min(q.a, q.b) - vec3(pad), hi = glm::max(q.a, q.b) + vec3(pad);+ const glm::ivec3 c0 = glm::clamp(glm::ivec3(glm::floor((lo - grid.origin) / grid.cell)), glm::ivec3(0), last);+ const glm::ivec3 c1 = glm::clamp(glm::ivec3(glm::ceil((hi - grid.origin) / grid.cell)), glm::ivec3(0), last);+ const float k = blendWidth(q);+ poolFor(size_t(c1.z - c0.z + 1), [&](size_t b, size_t e) {+ for (int z = c0.z + int(b); z < c0.z + int(e); ++z)+ for (int y = c0.y; y <= c1.y; ++y)+ for (int x = c0.x; x <= c1.x; ++x) {+ float& d = dist[grid.index(x, y, z)];+ d = smoothMin(d, pieceDistance(q, grid.position(x, y, z)), k);+ }+ }, 1);+ }+ for (float& d : dist) d = d == std::numeric_limits<float>::max() ? -1e9f : -d; // inside above iso 0+ Mesh m = meshFromField(grid, dist, 0.0f, std::max(0, smooth));+ // One polygroup per piece: the one each face is closest to.+ m.polygroups.resize(m.triangleCount());+ poolFor(m.triangleCount(), [&](size_t b, size_t e) {+ for (size_t t = b; t < e; ++t) {+ const glm::uvec3 tri = m.triangles[t];+ const vec3 c = (m.positions[tri.x] + m.positions[tri.y] + m.positions[tri.z]) / 3.0f;+ float best = std::numeric_limits<float>::max();+ for (const Piece& q : pieces)+ if (const float d = std::abs(pieceDistance(q, c)); d < best) best = d, m.polygroups[t] = q.group;+ }+ }, 1024);+ return m;+}++Mesh zsphereMesh(const std::vector<ZSphere>& s, bool preview) {+ Mesh m = preview ? zsphereSkin(s, kZSpherePreviewResolution, 2) : zsphereDisplayMesh(s);+ if (preview && m.triangleCount() == 0) m = zsphereDisplayMesh(s);+ m.zspheres = s;+ m.zspherePreview = preview && m.triangleCount() > 0;+ return m;+}++int zsphereMirror(const std::vector<ZSphere>& s, int i, const vec3& m) {+ if (!validIndex(s, i)) return -1;+ const vec3 want = s[size_t(i)].center * m;+ const float tol = 0.02f * s[size_t(i)].radius + 1e-6f;+ int best = -1;+ float bestD = tol;+ for (size_t j = 0; j < s.size(); ++j) {+ const float d = glm::length(s[j].center - want);+ if (d <= bestD && std::abs(s[j].radius - s[size_t(i)].radius) <= tol) best = int(j), bestD = d;+ }+ return best;+}++bool zsphereAdd(std::vector<ZSphere>& s, int parent, const vec3& center, float radius, Symmetry sym, int* added) {+ if (!validIndex(s, parent) || !(radius > 0.0f) || !std::isfinite(center.x + center.y + center.z)) return false;+ // Mirror parents come from the armature as it was, before the new spheres join it.+ std::vector<std::pair<int, vec3>> copies;+ for (const vec3& m : otherMirrors(sym)) {+ const vec3 c = center * m;+ if (glm::length(c - center) <= 0.02f * radius) continue; // on the plane: one sphere serves both sides+ int p = zsphereMirror(s, parent, m);+ if (p < 0) p = parent;+ bool dup = false;+ for (const auto& [q, cc] : copies) dup |= glm::length(cc - c) <= 0.02f * radius;+ if (!dup) copies.push_back({p, c});+ }+ if (added) *added = int(s.size());+ s.push_back({center, radius, parent});+ for (const auto& [p, c] : copies) s.push_back({c, radius, p});+ return true;+}++bool zsphereSet(std::vector<ZSphere>& s, int i, const vec3& center, float radius, Symmetry sym) {+ if (!validIndex(s, i) || !(radius > 0.0f) || !std::isfinite(center.x + center.y + center.z)) return false;+ std::vector<std::pair<int, vec3>> targets{{i, vec3(1.0f)}};+ for (const vec3& m : otherMirrors(sym))+ if (const int j = zsphereMirror(s, i, m); j >= 0) targets.push_back({j, m});+ vec3 c = center;+ for (const auto& [j, m] : targets) // a sphere that mirrors onto itself stays on that plane+ if (j == i)+ for (int a = 0; a < 3; ++a)+ if (m[a] < 0.0f) c[a] = 0.0f;+ for (const auto& [j, m] : targets) {+ if (j == i && m != vec3(1.0f)) continue;+ s[size_t(j)].center = c * m;+ s[size_t(j)].radius = radius;+ }+ return true;+}++bool zsphereDelete(std::vector<ZSphere>& s, int i, Symmetry sym) {+ if (!validIndex(s, i) || i == 0) return false;+ std::vector<int> roots{i};+ for (const vec3& m : otherMirrors(sym))+ if (const int j = zsphereMirror(s, i, m); j > 0) roots.push_back(j);+ const std::vector<char> gone = subtrees(s, roots);+ std::vector<int> remap(s.size(), -1);+ std::vector<ZSphere> kept;+ for (size_t j = 0; j < s.size(); ++j)+ if (!gone[j]) remap[j] = int(kept.size()), kept.push_back(s[j]);+ for (size_t j = 1; j < kept.size(); ++j) kept[j].parent = remap[size_t(kept[j].parent)];+ s = std::move(kept);+ return true;+}++bool zsphereInsert(std::vector<ZSphere>& s, int child, Symmetry sym, int* added) {+ if (!validIndex(s, child) || child == 0) return false;+ std::vector<int> children{child};+ for (const vec3& m : otherMirrors(sym))+ if (const int j = zsphereMirror(s, child, m); j > 0 && std::find(children.begin(), children.end(), j) == children.end())+ children.push_back(j);+ if (added) *added = int(s.size());+ for (int c : children) {+ const ZSphere& z = s[size_t(c)];+ const ZSphere& p = s[size_t(z.parent)];+ const ZSphere mid{(z.center + p.center) * 0.5f, (z.radius + p.radius) * 0.5f, z.parent};+ s[size_t(c)].parent = int(s.size());+ s.push_back(mid);+ }+ return true;+}++Json zspheresToJson(const std::vector<ZSphere>& s) {+ Json out = Json::array();+ for (const ZSphere& z : s) {+ for (int k = 0; k < 3; ++k) out.push(double(z.center[k]));+ out.push(double(z.radius));+ out.push(double(z.parent));+ }+ return out;+}++std::vector<ZSphere> zspheresFromJson(const Json& json) {+ std::vector<ZSphere> s;+ if (!json.isArray() || json.size() % 5 != 0) return s;+ for (size_t i = 0; i < json.size(); i += 5)+ s.push_back({vec3(float(json[i].asNumber(NAN)), float(json[i + 1].asNumber(NAN)), float(json[i + 2].asNumber(NAN))),+ float(json[i + 3].asNumber(NAN)), int(json[i + 4].asNumber(-2))});+ if (!zspheresValidate(s).empty()) s.clear();+ return s;+}++namespace {++constexpr const char* kNotZSphere = "The active SubTool is not a ZSphere SubTool (zsphere_new makes one)";++Symmetry symmetryArg(const Args& a) {+ Symmetry s{false, false, false};+ for (char c : argString(a, "symmetry")) {+ s.x |= c == 'x' || c == 'X';+ s.y |= c == 'y' || c == 'Y';+ s.z |= c == 'z' || c == 'Z';+ }+ return s;+}++CommandResult applyEdit(Document& doc, std::vector<ZSphere> s, const std::string& label, std::string message) {+ if (const std::string err = zspheresValidate(s); !err.empty()) return {false, "ZSpheres: " + err};+ doc.replaceMeshUndoable(zsphereMesh(s, doc.mesh.zspherePreview), label);+ return {true, message + "; " + std::to_string(s.size()) + " spheres"};+}++std::string describe(const std::vector<ZSphere>& s, size_t i) {+ const ZSphere& z = s[i];+ return std::to_string(i) + ": " + fmt("(%.4g, %.4g, %.4g) radius %.4g", z.center.x, z.center.y, z.center.z, z.radius) ++ (i == 0 ? " root" : ", from " + std::to_string(z.parent));+}++} // namespace++void registerZSphereCommands(CommandRegistry& reg) {+ using T = ParamSpec::Type;+ const ParamSpec symmetryParam{"symmetry", T::String,+ "Mirror the edit across these planes through the centre, e.g. \"x\". Default: none.",+ false};+ reg.add({"zsphere_new",+ "ZSpheres (ZBrush's ZSpheres): add a ZSphere SubTool holding one root sphere at the centre and make it "+ "active. Grow limbs from it with zsphere_add (or the ZSphere tool), see the skin with zsphere_preview, "+ "then zsphere_make_mesh turns it into a sculptable SubTool.",+ {{"name", T::String, "SubTool name (default \"ZSphere\").", false},+ {"radius", T::Number, "Root sphere radius (default 0.5).", false}},+ [](Document& doc, const Args& a) -> CommandResult {+ const float r = float(argNumber(a, "radius", 0.5));+ if (!(r > 0.0f) || !std::isfinite(r)) return {false, "radius must be above 0"};+ const std::string name = doc.uniqueSubtoolName(argString(a, "name", "ZSphere"));+ doc.addSubtool(zsphereMesh({{vec3(0.0f), r, -1}}, false), name);+ return {true, "Added ZSphere SubTool \"" + name + "\" with a root sphere (index 0)"};+ }});+ reg.add({"zsphere_list", "List the active ZSphere SubTool's spheres: index, centre, radius and parent.", {},+ [](Document& doc, const Args&) -> CommandResult {+ const auto& s = doc.mesh.zspheres;+ if (s.empty()) return {false, kNotZSphere};+ std::string out = std::to_string(s.size()) + " spheres" + (doc.mesh.zspherePreview ? " (skin preview on)" : "");+ for (size_t i = 0; i < s.size(); ++i) out += "\n" + describe(s, i);+ return {true, out};+ }});+ reg.add({"zsphere_add",+ "Grow a new sphere from sphere `parent` of the active ZSphere SubTool (a limb, finger or tail joint). "+ "Its index is reported; mirror copies (with symmetry) follow it.",+ {{"parent", T::Number, "Index of the sphere it grows from (0 = the root).", true},+ {"position", T::String, "Centre \"x,y,z\".", true},+ {"radius", T::Number, "Radius (default: the parent's).", false},+ symmetryParam},+ [](Document& doc, const Args& a) -> CommandResult {+ auto s = doc.mesh.zspheres;+ if (s.empty()) return {false, kNotZSphere};+ const int parent = int(argNumber(a, "parent", -1));+ if (!validIndex(s, parent)) return {false, "parent must be a sphere index from 0 to " + std::to_string(s.size() - 1)};+ vec3 c;+ if (!parseVec3(argString(a, "position"), c)) return {false, "position must be \"x,y,z\""};+ const float r = float(argNumber(a, "radius", s[size_t(parent)].radius));+ int added = -1;+ if (!zsphereAdd(s, parent, c, r, symmetryArg(a), &added)) return {false, "radius must be above 0"};+ return applyEdit(doc, std::move(s), "ZSphere add", "Added sphere " + std::to_string(added));+ }});+ reg.add({"zsphere_set", "Move and/or resize a sphere of the active ZSphere SubTool (ZBrush's Move and Scale).",+ {{"index", T::Number, "Sphere index.", true},+ {"position", T::String, "New centre \"x,y,z\" (default: unchanged).", false},+ {"radius", T::Number, "New radius (default: unchanged).", false},+ symmetryParam},+ [](Document& doc, const Args& a) -> CommandResult {+ auto s = doc.mesh.zspheres;+ if (s.empty()) return {false, kNotZSphere};+ const int i = int(argNumber(a, "index", -1));+ if (!validIndex(s, i)) return {false, "index must be from 0 to " + std::to_string(s.size() - 1)};+ vec3 c = s[size_t(i)].center;+ if (a.contains("position") && !parseVec3(argString(a, "position"), c))+ return {false, "position must be \"x,y,z\""};+ if (!zsphereSet(s, i, c, float(argNumber(a, "radius", s[size_t(i)].radius)), symmetryArg(a)))+ return {false, "radius must be above 0"};+ return applyEdit(doc, std::move(s), "ZSphere edit", "Changed sphere " + std::to_string(i));+ }});+ reg.add({"zsphere_delete", "Delete a sphere of the active ZSphere SubTool and every sphere growing from it.",+ {{"index", T::Number, "Sphere index (not 0, the root).", true}, symmetryParam},+ [](Document& doc, const Args& a) -> CommandResult {+ auto s = doc.mesh.zspheres;+ if (s.empty()) return {false, kNotZSphere};+ const int i = int(argNumber(a, "index", -1));+ if (!zsphereDelete(s, i, symmetryArg(a)))+ return {false, "index must be from 1 to " + std::to_string(s.size() - 1) + " (the root stays)"};+ return applyEdit(doc, std::move(s), "ZSphere delete", "Deleted sphere " + std::to_string(i));+ }});+ reg.add({"zsphere_insert",+ "Insert a sphere halfway along the link from sphere `index` to its parent (a new joint, like clicking "+ "a link in ZBrush's Draw mode).",+ {{"index", T::Number, "The child sphere whose link gets the new joint.", true}, symmetryParam},+ [](Document& doc, const Args& a) -> CommandResult {+ auto s = doc.mesh.zspheres;+ if (s.empty()) return {false, kNotZSphere};+ int added = -1;+ if (!zsphereInsert(s, int(argNumber(a, "index", -1)), symmetryArg(a), &added))+ return {false, "index must be from 1 to " + std::to_string(s.size() - 1)};+ return applyEdit(doc, std::move(s), "ZSphere insert", "Inserted sphere " + std::to_string(added));+ }});+ reg.add({"zsphere_preview",+ "Show the skin over the active ZSphere SubTool's spheres instead of the spheres (ZBrush's Preview, A).",+ {{"on", T::Bool, "Default: toggle.", false}},+ [](Document& doc, const Args& a) -> CommandResult {+ if (doc.mesh.zspheres.empty()) return {false, kNotZSphere};+ const bool on = argBool(a, "on", !doc.mesh.zspherePreview);+ if (on == doc.mesh.zspherePreview) return {true, on ? "Skin preview is on" : "Skin preview is off"};+ doc.replaceMeshUndoable(zsphereMesh(doc.mesh.zspheres, on), on ? "ZSphere preview" : "ZSphere spheres");+ return {true, on ? "Skin preview on" : "Skin preview off"};+ }});+ reg.add({"zsphere_make_mesh",+ "Make Mesh (ZBrush's Make Adaptive Skin): build the skin over the active ZSphere SubTool as a new, "+ "sculptable SubTool right below it, watertight quads with one polygroup per link. The ZSphere SubTool "+ "is hidden and kept so the proportions can still be changed and a new mesh made.",+ {{"resolution", T::Number, "Cells across the longest side (16-1024, default 128): higher is denser.", false},+ {"smooth", T::Number, "Smoothing passes (default 2).", false},+ {"keep", T::Bool, "Keep the ZSphere SubTool (hidden). Default true; false deletes it.", false}},+ [](Document& doc, const Args& a) -> CommandResult {+ if (doc.mesh.zspheres.empty()) return {false, kNotZSphere};+ const int res = int(argNumber(a, "resolution", 128));+ if (res < 16 || res > 1024) return {false, "resolution must be from 16 to 1024"};+ Mesh skin = zsphereSkin(doc.mesh.zspheres, res, int(argNumber(a, "smooth", 2)));+ if (skin.triangleCount() == 0) return {false, "ZSpheres: the skin came out empty (resolution too high?)"};+ const size_t faces = skin.triangleCount() - skin.quadCount();+ const int from = doc.activeSubtool;+ const std::string name = doc.uniqueSubtoolName(doc.subtools[size_t(from)].name + " Mesh");+ doc.addSubtool(std::move(skin), name, true, from + 1);+ if (argBool(a, "keep", true)) doc.subtools[size_t(from)].visible = false;+ else doc.removeSubtool(from);+ return {true, "Made \"" + name + "\" from the ZSpheres: " + std::to_string(faces) + " faces"};+ }});+}++} // namespace sfdiff --git a/src/core/ZSpheres.h b/src/core/ZSpheres.hnew file mode 100644index 00000000..f6c7ef91--- /dev/null+++ b/src/core/ZSpheres.h@@ -0,0 +1,69 @@+// SculptForge - open source digital sculpting+// SPDX-License-Identifier: GPL-3.0-or-later+//+// ZSpheres, ZBrush style: block out an organic base mesh as a tree of connected spheres (a root, then limbs,+// fingers, tails grown from it), see the skin over them, and turn it into a sculptable SubTool. A ZSphere SubTool+// keeps its armature in Mesh::zspheres; its triangles are generated from it (the spheres and their links, or the+// skin preview), so undo, SubTool switching and projects carry the armature with the mesh. Edits replace the mesh+// as one undo step each. The skin is a smooth union of rounded cones (one per link) meshed with surface nets+// (core/Voxel.h), so it comes out watertight and in quads, one polygroup per link.+#pragma once++#include "core/Json.h"+#include "core/Mesh.h"+#include "core/Sculpt.h"++#include <string>+#include <vector>++namespace sf {++class CommandRegistry;++// Polygroups of the armature's display mesh: sphere i is group kZSphereGroup + i, the link from child c to its+// parent is kZSphereLinkGroup + c.+constexpr uint32_t kZSphereGroup = 1;+constexpr uint32_t kZSphereLinkGroup = 1u << 20;+// The sphere (or, for a link, the child sphere) a display-mesh polygroup belongs to; -1 for neither.+int zsphereOfGroup(uint32_t group, bool* link = nullptr);++// The armature's display mesh: a sphere per ZSphere and a tapered link to each parent, with polygroups as above+// and the spheres coloured (the root a little warmer). Carries `spheres` in Mesh::zspheres.+Mesh zsphereDisplayMesh(const std::vector<ZSphere>& spheres);++// The skin over the armature: watertight quads, `resolution` cells across its longest side, `smooth` Taubin passes,+// one polygroup per link (the root sphere's own group when there are no links). A plain mesh (no zspheres).+Mesh zsphereSkin(const std::vector<ZSphere>& spheres, int resolution = 128, int smooth = 2);+constexpr int kZSpherePreviewResolution = 72;++// The mesh a ZSphere SubTool shows: the display mesh, or with `preview` the skin at kZSpherePreviewResolution;+// both carry `spheres` and the preview flag.+Mesh zsphereMesh(const std::vector<ZSphere>& spheres, bool preview);++// The sphere that mirrors `i` across `m` (one of Sculptor::mirrors): `i` itself when it sits on the mirror plane,+// -1 when there is none.+int zsphereMirror(const std::vector<ZSphere>& spheres, int i, const glm::vec3& m);++// Symmetric edits (`sym`: the planes to mirror across, as the sculpt symmetry). Each returns false and leaves+// `spheres` alone when the arguments are out of range.+// Adds a sphere growing from `parent`; `added` gets the new sphere's index (its mirror copies follow it).+bool zsphereAdd(std::vector<ZSphere>& spheres, int parent, const glm::vec3& center, float radius, Symmetry sym,+ int* added = nullptr);+// Moves and resizes sphere `i`; a sphere on a mirror plane stays on it.+bool zsphereSet(std::vector<ZSphere>& spheres, int i, const glm::vec3& center, float radius, Symmetry sym);+// Deletes sphere `i` and everything that grows from it (never the root).+bool zsphereDelete(std::vector<ZSphere>& spheres, int i, Symmetry sym);+// Inserts a sphere halfway along the link from `child` to its parent; `added` gets its index.+bool zsphereInsert(std::vector<ZSphere>& spheres, int child, Symmetry sym, int* added = nullptr);++// "x,y,z,radius,parent" per sphere, as a flat array; FromJson drops an armature that doesn't form a tree.+Json zspheresToJson(const std::vector<ZSphere>& spheres);+std::vector<ZSphere> zspheresFromJson(const Json& json);+// Empty when `spheres` is a valid armature: a root at 0, parents in range, no loops, finite positive sizes.+std::string zspheresValidate(const std::vector<ZSphere>& spheres);++// zsphere_new, zsphere_list, zsphere_add, zsphere_set, zsphere_delete, zsphere_insert, zsphere_preview,+// zsphere_make_mesh.+void registerZSphereCommands(CommandRegistry& registry);++} // namespace sfdiff --git a/tests/test_zspheres.cpp b/tests/test_zspheres.cppnew file mode 100644index 00000000..1c40f10f--- /dev/null+++ b/tests/test_zspheres.cpp@@ -0,0 +1,203 @@+// SculptForge - open source digital sculpting+// SPDX-License-Identifier: GPL-3.0-or-later+//+// ZSpheres (src/core/ZSpheres.cpp): the armature edits and their symmetry, the display mesh, the skin, the+// zsphere_* commands with undo, and projects.+#include "TestHarness.h"++#include "core/BVH.h"+#include "core/Commands.h"+#include "core/Project.h"+#include "core/ZSpheres.h"++#include <cmath>+#include <set>++using namespace sf;+using glm::vec3;++namespace {++// A small figure: root body, a head above, one arm out to +X mirrored to -X.+std::vector<ZSphere> figure(Symmetry sym = {true, false, false}) {+ std::vector<ZSphere> s{{vec3(0.0f), 0.5f, -1}};+ zsphereAdd(s, 0, vec3(0, 0.8f, 0), 0.3f, sym);+ zsphereAdd(s, 0, vec3(0.9f, 0.1f, 0), 0.2f, sym);+ return s;+}++bool watertight(const Mesh& m) {+ std::map<std::pair<uint32_t, uint32_t>, int> edges;+ for (const glm::uvec3& t : m.triangles)+ for (int k = 0; k < 3; ++k) {+ const uint32_t a = t[k], b = t[(k + 1) % 3];+ ++edges[{std::min(a, b), std::max(a, b)}];+ }+ for (const auto& [e, n] : edges)+ if (n != 2) return false;+ return !edges.empty();+}++} // namespace++TEST(zspheres_symmetric_edits) {+ const auto s = figure();+ // Head on the plane: one sphere. The arm: a sphere and its mirror.+ CHECK(s.size() == 4);+ CHECK(s[1].parent == 0 && std::abs(s[1].center.x) < 1e-6f);+ CHECK(s[2].center.x > 0.0f && s[3].center.x < 0.0f && s[3].parent == 0);+ CHECK(zsphereMirror(s, 2, vec3(-1, 1, 1)) == 3 && zsphereMirror(s, 1, vec3(-1, 1, 1)) == 1);+ CHECK(zspheresValidate(s).empty());++ // A hand on the arm: its mirror grows from the mirrored arm.+ auto t = s;+ int hand = -1;+ CHECK(zsphereAdd(t, 2, vec3(1.4f, 0.1f, 0), 0.15f, {true, false, false}, &hand));+ CHECK(hand == 4 && t.size() == 6 && t[5].parent == 3 && std::abs(t[5].center.x + 1.4f) < 1e-6f);++ // Moving the arm moves its mirror; the head stays on the plane when dragged across it.+ CHECK(zsphereSet(t, 2, vec3(1.0f, 0.3f, 0.1f), 0.25f, {true, false, false}));+ CHECK(glm::length(t[3].center - vec3(-1.0f, 0.3f, 0.1f)) < 1e-6f && std::abs(t[3].radius - 0.25f) < 1e-6f);+ CHECK(zsphereSet(t, 1, vec3(0.2f, 0.9f, 0), 0.3f, {true, false, false}));+ CHECK(t[1].center.x == 0.0f && std::abs(t[1].center.y - 0.9f) < 1e-6f);+ // Without symmetry only the one sphere moves.+ CHECK(zsphereSet(t, 2, vec3(1.2f, 0.3f, 0.1f), 0.25f, {false, false, false}));+ CHECK(std::abs(t[3].center.x + 1.0f) < 1e-6f);++ // Deleting the arm takes the hand, and with symmetry the other arm and hand; indices close up.+ auto d = s;+ zsphereAdd(d, 2, vec3(1.4f, 0.1f, 0), 0.15f, {true, false, false});+ CHECK(zsphereDelete(d, 2, {true, false, false}));+ CHECK(d.size() == 2 && zspheresValidate(d).empty());+ CHECK(!zsphereDelete(d, 0, {true, false, false})); // never the root+ CHECK(!zsphereAdd(d, 7, vec3(0.0f), 0.1f, {})); // bad parent: untouched+ CHECK(d.size() == 2);++ // Inserting on a link puts a joint halfway, between the child and its old parent (both sides).+ auto in = s;+ int joint = -1;+ CHECK(zsphereInsert(in, 2, {true, false, false}, &joint));+ CHECK(joint == 4 && in.size() == 6 && in[2].parent == 4 && in[4].parent == 0 && in[3].parent == 5);+ CHECK(glm::length(in[4].center - vec3(0.45f, 0.05f, 0)) < 1e-6f);+ CHECK(zspheresValidate(in).empty());+}++TEST(zspheres_validate_and_json) {+ const auto s = figure();+ const auto back = zspheresFromJson(zspheresToJson(s));+ CHECK(back.size() == s.size());+ for (size_t i = 0; i < s.size() && i < back.size(); ++i)+ CHECK(back[i].center == s[i].center && back[i].radius == s[i].radius && back[i].parent == s[i].parent);+ std::vector<ZSphere> loop{{vec3(0.0f), 1.0f, -1}, {vec3(1.0f), 1.0f, 2}, {vec3(2.0f), 1.0f, 1}};+ CHECK(!zspheresValidate(loop).empty());+ CHECK(zspheresFromJson(zspheresToJson(loop)).empty());+ CHECK(!zspheresValidate({{vec3(0.0f), 0.0f, -1}}).empty());+ CHECK(!zspheresValidate({{vec3(0.0f), 1.0f, 0}}).empty());+ CHECK(zspheresFromJson(Json::array()).empty());+}++TEST(zspheres_display_mesh_groups) {+ const auto s = figure();+ const Mesh m = zsphereDisplayMesh(s);+ CHECK(m.zspheres.size() == s.size() && m.colors.size() == m.vertexCount() && m.polygroups.size() == m.triangleCount());+ std::set<uint32_t> groups(m.polygroups.begin(), m.polygroups.end());+ CHECK(groups.size() == s.size() + (s.size() - 1)); // a group per sphere and per link+ bool link = true;+ CHECK(zsphereOfGroup(kZSphereGroup + 3, &link) == 3 && !link);+ CHECK(zsphereOfGroup(kZSphereLinkGroup + 2, &link) == 2 && link);+ CHECK(zsphereOfGroup(0) == -1);+ // A ray at the arm sphere's centre hits the arm sphere's group.+ BVH bvh;+ bvh.build(m);+ RayHit hit;+ CHECK(bvh.raycast(m, vec3(0.9f, 0.1f, 5.0f), vec3(0, 0, -1), hit));+ CHECK(zsphereOfGroup(m.polygroupAt(hit.triangle), &link) == 2 && !link);+}++TEST(zspheres_skin) {+ const auto s = figure();+ const Mesh skin = zsphereSkin(s, 64, 2);+ CHECK(skin.triangleCount() > 1000 && skin.zspheres.empty());+ CHECK(watertight(skin));+ CHECK(skin.quadCount() * 2 * 10 >= skin.triangleCount() * 9); // (nearly) all quads+ // Covers every sphere: the bounds reach the head top and both hands, give or take a cell.+ const AABB b = skin.bounds();+ const float cell = 2.0f * 1.25f / 64.0f;+ CHECK(std::abs(b.max.y - 1.1f) < 2.0f * cell);+ CHECK(std::abs(b.max.x - 1.1f) < 2.0f * cell && std::abs(b.min.x + 1.1f) < 2.0f * cell);+ // Symmetric across X like the armature.+ CHECK(std::abs(b.max.x + b.min.x) < cell);+ // One polygroup per link.+ std::set<uint32_t> groups(skin.polygroups.begin(), skin.polygroups.end());+ CHECK(groups.size() == s.size() - 1);+ // A lone root is a sphere.+ const Mesh ball = zsphereSkin({{vec3(1, 2, 3), 0.5f, -1}}, 48, 1);+ CHECK(ball.triangleCount() > 0 && watertight(ball));+ float worst = 0.0f;+ for (const vec3& p : ball.positions) worst = std::max(worst, std::abs(glm::length(p - vec3(1, 2, 3)) - 0.5f));+ CHECK(worst < 0.05f);+}++TEST(zspheres_commands_and_undo) {+ Document doc;+ CommandRegistry reg;+ CHECK(!reg.execute(doc, "zsphere_add", {{"parent", 0.0}, {"position", std::string("1,0,0")}}).ok); // not a ZSphere SubTool+ CHECK(reg.execute(doc, "zsphere_new", {{"radius", 0.5}}).ok);+ CHECK(doc.subtoolCount() == 2 && doc.subtools[1].name == "ZSphere" && doc.mesh.zspheres.size() == 1);+ CHECK(reg.execute(doc, "zsphere_add", {{"parent", 0.0}, {"position", std::string("0.9,0,0")}, {"radius", 0.25},+ {"symmetry", std::string("x")}}).ok);+ CHECK(doc.mesh.zspheres.size() == 3);+ CHECK(reg.execute(doc, "zsphere_set", {{"index", 1.0}, {"radius", 0.3}, {"symmetry", std::string("x")}}).ok);+ CHECK(std::abs(doc.mesh.zspheres[2].radius - 0.3f) < 1e-6f);+ CHECK(!reg.execute(doc, "zsphere_delete", {{"index", 0.0}}).ok);+ CHECK(reg.execute(doc, "zsphere_list").message.find("3 spheres") == 0);++ // Each edit is one undo step, and undo brings the armature back with the mesh.+ CHECK(doc.undo.undo(doc.mesh, doc.bvh));+ CHECK(std::abs(doc.mesh.zspheres[2].radius - 0.25f) < 1e-6f);+ CHECK(doc.undo.undo(doc.mesh, doc.bvh));+ CHECK(doc.mesh.zspheres.size() == 1);+ CHECK(doc.undo.redo(doc.mesh, doc.bvh) && doc.undo.redo(doc.mesh, doc.bvh));+ CHECK(doc.mesh.zspheres.size() == 3);++ // Preview swaps the spheres for the skin and back, keeping the armature.+ const size_t sphereTris = doc.mesh.triangleCount();+ CHECK(reg.execute(doc, "zsphere_preview", {{"on", true}}).ok);+ CHECK(doc.mesh.zspherePreview && doc.mesh.zspheres.size() == 3 && doc.mesh.triangleCount() != sphereTris);+ CHECK(reg.execute(doc, "zsphere_add", {{"parent", 0.0}, {"position", std::string("0,0.7,0")}}).ok);+ CHECK(doc.mesh.zspherePreview && doc.mesh.zspheres.size() == 4); // edits while previewing keep previewing+ CHECK(reg.execute(doc, "zsphere_preview").ok && !doc.mesh.zspherePreview);++ // Make Mesh: a new sculptable SubTool below, the ZSphere SubTool hidden and kept.+ CHECK(reg.execute(doc, "zsphere_make_mesh", {{"resolution", 48.0}}).ok);+ CHECK(doc.subtoolCount() == 3 && doc.activeSubtool == 2 && doc.subtools[2].name == "ZSphere Mesh");+ CHECK(doc.mesh.zspheres.empty() && watertight(doc.mesh));+ CHECK(!doc.subtools[1].visible && doc.subtoolMesh(1).zspheres.size() == 4);+ CHECK(!reg.execute(doc, "zsphere_make_mesh").ok); // the new mesh is not a ZSphere SubTool+ // keep=false replaces the ZSphere SubTool.+ doc.selectSubtool(1);+ CHECK(reg.execute(doc, "zsphere_make_mesh", {{"resolution", 32.0}, {"keep", false}}).ok);+ CHECK(doc.subtoolCount() == 3 && doc.subtools[doc.activeSubtool].name == "ZSphere Mesh 2");+ for (int i = 0; i < doc.subtoolCount(); ++i) CHECK(doc.subtoolMesh(i).zspheres.empty());+}++TEST(zspheres_project_roundtrip) {+ Document doc;+ CommandRegistry reg;+ CHECK(reg.execute(doc, "zsphere_new").ok);+ CHECK(reg.execute(doc, "zsphere_add", {{"parent", 0.0}, {"position", std::string("0.8,0.2,0")}, {"radius", 0.2},+ {"symmetry", std::string("x")}}).ok);+ CHECK(reg.execute(doc, "zsphere_preview", {{"on", true}}).ok);+ doc.selectSubtool(0); // the ZSphere SubTool saved while inactive too+ const std::string path = tempPath("sf_zspheres.sfproj");+ std::string err;+ CHECK(saveProject(path, doc, err));+ Document back;+ CHECK(loadProject(path, back, err));+ CHECK(back.subtoolCount() == 2 && back.subtoolMesh(0).zspheres.empty());+ const Mesh& z = back.subtoolMesh(1);+ CHECK(z.zspheres.size() == 3 && z.zspherePreview && z.triangleCount() == doc.subtoolMesh(1).triangleCount());+ back.selectSubtool(1);+ CHECK(reg.execute(back, "zsphere_preview", {{"on", false}}).ok && back.mesh.zspheres.size() == 3);+ std::filesystem::remove(path);+}diff --git a/tests/ui/zspheres.sfui b/tests/ui/zspheres.sfuinew file mode 100644index 00000000..ede686db--- /dev/null+++ b/tests/ui/zspheres.sfui@@ -0,0 +1,84 @@+# ZSpheres (ZBrush's ZSpheres, Tool > ZSpheres): a ZSphere SubTool with one root, Draw grows an arm from it with X+# symmetry (the mirror arm follows), Move pulls it out, Scale grows it and undo takes that back, a click on the link+# adds a joint (both sides), Alt+click deletes a limb, Preview (A) shows the skin, and Make Mesh builds a sculptable+# SubTool below with the ZSpheres hidden and kept. Dragging the background still navigates.+run zsphere_new radius=1+run subtool_visibility index=0 visible=false+wait 0.3+click "ZSpheres##tool.zspheres"+expect "ZSpheres/Draw"+expect_value zspheres == 1+expect_text "1 sphere"++# Ctrl-hover help.+hold ctrl+hover "ZSpheres/Draw"+expect_help "grow a new sphere"+hover "ZSpheres/Preview"+expect_help "skin"+hover "ZSpheres/Make Mesh"+expect_help "Adaptive Skin"+hold none++# Draw: drag near the root's right edge grows an arm there; symmetry adds its twin on the left.+view_drag 0.515 0.518 0.545 0.518+expect_value zspheres == 3+expect_value zsphere_x1 > 0.5+expect_value zsphere_x2 < -0.5+expect_status "ZSphere add"+shot zspheres-draw++# Move: pull the arm out to the right; the twin goes left.+click "ZSpheres/Move"+remember zsphere_x1 x+view_drag 0.530 0.518 0.600 0.518+expect_value zsphere_x1 > $x+expect_value zsphere_x2 < -1.0++# Scale: drag up on the arm to grow it; undo puts it back.+click "ZSpheres/Scale"+remember zsphere_r1 r+view_drag 0.600 0.518 0.600 0.45+expect_value zsphere_r1 > $r+key ctrl+z+expect_value zsphere_r1 == $r+key ctrl+shift+z+expect_value zsphere_r1 > $r+key ctrl+z++# Draw on the link between the root and the arm: a joint halfway, mirrored.+click "ZSpheres/Draw"+remember zsphere_x1 armx+view_drag 0.543 0.518 0.543 0.518 0.05+expect_value zspheres == 5+expect_status "ZSphere insert"+shot zspheres-joint++# Preview: the skin replaces the spheres; clicks on it do nothing.+key a+expect_value zsphere_preview == 1+expect_value zspheres == 5+shot zspheres-preview+view_drag 0.412 0.518 0.412 0.518 0.05+expect_status "Preview is on"+expect_value zspheres == 5+key a+expect_value zsphere_preview == 0++# Make Mesh: a new SubTool below, active and sculptable; the ZSpheres hidden and kept.+click "ZSpheres/Make Mesh"+expect_value subtools == 3+expect_value active_subtool == 2+expect_value zspheres == 0+expect_status "from the ZSpheres"+shot zspheres-mesh+remember triangles before+snapshot+stroke 0.38 0.45 0.44 0.55+expect_value moved > 0+expect_value triangles == $before++# The background still navigates.+remember camera_yaw yaw+view_drag 0.2 0.8 0.3 0.8+expect_value camera_yaw != $yaw