Skip to content

Free, open-source 3D sculpting for Linux, macOS and Windows: dense meshes, remeshing, painting, built-in AI (image/text to 3D), Send to Unreal, game-ready LODs, Gaussian splats and OpenUSD.

Geometry > QRemesh (background job, progress, cancel) and SubTool > Project > ProjectAll in the app, with a UI test

islandmed8832226b5e55
diff --git a/CMakeLists.txt b/CMakeLists.txt
index a72952a3..7be84df1 100644
--- a/CMakeLists.txt
+++ b/CMakeLists.txt
@@ -164,6 +164,7 @@ if(SCULPTFORGE_BUILD_APP)
src/app/PanelPolypaint.cpp
src/app/PanelPaintLayers.cpp
src/app/PanelTexture.cpp
+ src/app/PanelRetopo.cpp
src/app/PanelGoz.cpp
src/app/PanelProject.cpp
src/app/PanelSubTools.cpp
diff --git a/src/app/App.cpp b/src/app/App.cpp
index 598b35e1..ba1af278 100644
--- a/src/app/App.cpp
+++ b/src/app/App.cpp
@@ -340,6 +340,7 @@ int App::runUiTest(int w, int h, int fps) {
pollUnreal();
pollGenerator();
pollAutoUv();
+ pollQRemesh();
updateCameraAspect();
Demo::beginFrame();
@@ -492,6 +493,7 @@ int App::runRecording() {
pollBrushRequest();
pollUnreal();
pollAutoUv();
+ pollQRemesh();
updateCameraAspect();
Demo::beginFrame();
@@ -556,6 +558,7 @@ int App::run() {
pollUnreal();
pollGoz();
pollAutoUv();
+ pollQRemesh();
int fbW = 0, fbH = 0, winW = 0, winH = 0;
SDL_GetWindowSizeInPixels(window_, &fbW, &fbH);
diff --git a/src/app/App.h b/src/app/App.h
index 0dfc4869..040769b1 100644
--- a/src/app/App.h
+++ b/src/app/App.h
@@ -20,6 +20,7 @@
#include "core/Image.h"
#include "core/Document.h"
#include "core/AutoUv.h"
+#include "core/QRemesh.h"
#include "core/Stroke.h"
#include "core/Tablet.h"
#include "core/Texture.h"
@@ -406,6 +407,33 @@ private:
// Cached UV wireframe of the active SubTool for the UV view: segments in 0..1 UV space.
std::vector<glm::vec2> uvLines_;
uint64_t uvLinesKey_ = 0;
+ // Geometry > QRemesh (quad retopology on a worker thread) and SubTool > Project (ProjectAll); PanelRetopo.cpp.
+ void registerRetopoUiActions();
+ void drawQRemeshContents();
+ void drawProjectContents();
+ void startQRemesh();
+ void pollQRemesh();
+ struct QRemeshJob {
+ std::future<bool> done;
+ std::shared_ptr<std::atomic<float>> progress;
+ std::shared_ptr<std::atomic<bool>> cancel;
+ std::shared_ptr<Mesh> result;
+ std::shared_ptr<QRemeshStats> stats;
+ std::shared_ptr<std::string> error;
+ uint32_t subtool = 0; // SubTool id it remeshes
+ size_t triangles = 0; // the mesh must still have this many triangles when it finishes
+ bool keepOriginal = false;
+ Args args; // the equivalent qremesh command, for the console
+ };
+ std::unique_ptr<QRemeshJob> qremesh_;
+ struct RetopoSettings {
+ int target = 5000;
+ float adaptive = 0.5f;
+ bool keepGroups = false, detectEdges = true, usePolypaint = false, symmetry = false, keepOriginal = false;
+ float projectDist = 0.02f;
+ int projectBlur = 0;
+ bool projectMean = false, projectGeometry = true, projectPolypaint = true;
+ } retopo_;
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.cpp
index 9af3f796..464f96a3 100644
--- a/src/app/Config.cpp
+++ b/src/app/Config.cpp
@@ -307,6 +307,7 @@ void App::initActions() {
// the same id and own P (Paint), the symmetry toggles and Tab.
registerShellActions();
registerTextureUiActions(); // Tool > Texture Map, the Vertex / Texture paint target (PanelTexture.cpp)
+ registerRetopoUiActions(); // Geometry > QRemesh, SubTool > ProjectAll (PanelRetopo.cpp)
// Every command, so the command palette finds anything scriptable.
actions_.registerCommands(
diff --git a/src/app/Palettes.cpp b/src/app/Palettes.cpp
index 563a96c7..0014c304 100644
--- a/src/app/Palettes.cpp
+++ b/src/app/Palettes.cpp
@@ -341,6 +341,9 @@ void App::drawPalette_Tool() {
Demo::pushScope("SubTools");
drawSubToolsContents();
Demo::popScope();
+ Demo::pushScope("Project");
+ drawProjectContents(); // ProjectAll (PanelRetopo.cpp)
+ Demo::popScope();
}
if (subpalette("tool.layers", "Layers")) {
Demo::pushScope("Layers");
@@ -367,6 +370,9 @@ void App::drawPalette_Tool() {
ImGui::SetNextItemWidth(-1);
ui::SliderInside("##decimate", &decimateRatio_, 0.05f, 0.95f, "Keep %.2f");
ui::HelpText("Keep", nullptr, "Fraction of the triangles Decimate keeps.", "Tool > Geometry");
+ Demo::pushScope("QRemesh");
+ drawQRemeshContents(); // quad retopology (PanelRetopo.cpp)
+ Demo::popScope();
}
if (subpalette("tool.remesh", "Remesh")) {
const float half = (ImGui::GetContentRegionAvail().x - ImGui::GetStyle().ItemSpacing.x) * 0.5f;
diff --git a/src/app/PanelRetopo.cpp b/src/app/PanelRetopo.cpp
new file mode 100644
index 00000000..67bb19d4
--- /dev/null
+++ b/src/app/PanelRetopo.cpp
@@ -0,0 +1,238 @@
+// SculptForge - open source digital sculpting
+// SPDX-License-Identifier: GPL-3.0-or-later
+//
+// Geometry > QRemesh and SubTool > Project: ZBrush's ZRemesher and ProjectAll. QRemesh (core/QRemesh.h) runs
+// on a worker thread with a progress bar and Cancel, then replaces the SubTool as one undo step (optionally
+// keeping the original as a hidden SubTool below it). ProjectAll (core/Projection.h) is quick, so it runs
+// as the project_all command. The console shows both as script lines.
+#include "app/App.h"
+#include "app/Demo.h"
+#include "app/Ui.h"
+
+#include <algorithm>
+#include <thread>
+
+namespace sf {
+
+namespace {
+
+constexpr const char* kQRemeshPath = "Tool > Geometry > QRemesh";
+constexpr const char* kProjectPath = "Tool > SubTool > Project";
+
+// Faces as a modeller counts them: quads once, plus loose triangles.
+size_t faceCount(const Mesh& m) { return m.triangleCount() - m.quadCount(); }
+
+int symmetryAxis(const Symmetry& s) { return s.y && !s.x ? 1 : s.z && !s.x && !s.y ? 2 : 0; }
+
+} // namespace
+
+void App::registerRetopoUiActions() {
+ auto add = [this](const char* id, const char* label, const char* palette, std::function<void()> run,
+ std::function<bool()> enabled, const char* description, const char* command) {
+ Action a;
+ a.id = id;
+ a.label = label;
+ a.palette = palette;
+ a.run = std::move(run);
+ a.enabled = std::move(enabled);
+ a.description = description;
+ a.command = command;
+ actions_.add(std::move(a));
+ };
+ add("geometry.qremesh", "QRemesh", kQRemeshPath, [this] { startQRemesh(); },
+ [this] { return !qremesh_ && doc_.mesh.triangleCount() > 0; },
+ "Automatic quad retopology, like ZBrush's ZRemesher: rebuilds the SubTool as clean, all-quad topology whose "
+ "edge loops follow the forms, close to Target Polygons. Runs in the background (Cancel stops it); undoable. "
+ "Then divide it and use SubTool > Project > ProjectAll to bring the detail back.",
+ "qremesh");
+ add("subtool.project_all", "ProjectAll", kProjectPath, [this] {
+ runCommand("project_all", {{"distance", double(retopo_.projectDist)}, {"mean", retopo_.projectMean},
+ {"blur", double(retopo_.projectBlur)}, {"geometry", retopo_.projectGeometry},
+ {"polypaint", retopo_.projectPolypaint}});
+ },
+ [this] {
+ for (int i = 0; i < doc_.subtoolCount(); ++i)
+ if (i != doc_.activeSubtool && doc_.subtools[size_t(i)].visible) return true;
+ return false;
+ },
+ "Project the shape and polypaint of every other visible SubTool onto this one: each vertex moves along its "
+ "normal to the nearest surface within Dist. The mask holds vertices back. Typical use: QRemesh a copy, divide "
+ "it a few times, show the original, ProjectAll.",
+ "project_all");
+}
+
+void App::startQRemesh() {
+ if (qremesh_ || doc_.mesh.triangleCount() == 0) return;
+ if (doc_.sculptor.strokeActive()) endStroke();
+ QRemeshOptions o;
+ o.targetQuads = std::clamp(retopo_.target, 16, 2'000'000);
+ o.adaptive = retopo_.adaptive;
+ o.keepGroups = retopo_.keepGroups;
+ o.detectEdges = retopo_.detectEdges;
+ o.usePolypaint = retopo_.usePolypaint;
+ o.symmetryAxis = retopo_.symmetry ? symmetryAxis(symmetry_) : -1;
+
+ auto job = std::make_unique<QRemeshJob>();
+ job->progress = std::make_shared<std::atomic<float>>(0.0f);
+ job->cancel = std::make_shared<std::atomic<bool>>(false);
+ job->result = std::make_shared<Mesh>();
+ job->stats = std::make_shared<QRemeshStats>();
+ job->error = std::make_shared<std::string>();
+ job->subtool = doc_.activeSubtoolInfo().id;
+ job->triangles = doc_.mesh.triangleCount();
+ job->keepOriginal = retopo_.keepOriginal;
+ job->args = {{"target", double(o.targetQuads)}, {"adaptive", double(o.adaptive)}};
+ if (o.keepGroups) job->args["keep_groups"] = true;
+ if (!o.detectEdges) job->args["detect_edges"] = false;
+ if (o.usePolypaint) job->args["use_polypaint"] = true;
+ if (o.symmetryAxis >= 0) job->args["symmetry"] = std::string(1, char('x' + o.symmetryAxis));
+ if (job->keepOriginal) job->args["keep_original"] = true;
+
+ std::promise<bool> promise;
+ job->done = promise.get_future();
+ std::thread([promise = std::move(promise), source = std::make_shared<Mesh>(doc_.mesh), o, progress = job->progress,
+ cancel = job->cancel, result = job->result, stats = job->stats, error = job->error]() mutable {
+ const bool ok = qremesh(*source, o, *result, *error, [&](float f) {
+ progress->store(f);
+ return !cancel->load();
+ }, stats.get());
+ promise.set_value(ok);
+ }).detach();
+ qremesh_ = std::move(job);
+ status_ = "QRemesh: " + std::to_string(faceCount(doc_.mesh)) + " polygons to about " + std::to_string(o.targetQuads) +
+ " quads...";
+}
+
+void App::pollQRemesh() {
+ if (!qremesh_) return;
+ if (qremesh_->done.wait_for(std::chrono::seconds(0)) != std::future_status::ready) {
+ status_ = "QRemesh: " + std::to_string(int(qremesh_->progress->load() * 100.0f)) + "%";
+ return;
+ }
+ const std::unique_ptr<QRemeshJob> job = std::move(qremesh_);
+ if (!job->done.get()) {
+ status_ = *job->error;
+ return;
+ }
+ // The SubTool may be inactive now, or changed topology meanwhile.
+ int index = -1;
+ for (int i = 0; i < doc_.subtoolCount(); ++i)
+ if (doc_.subtools[size_t(i)].id == job->subtool) index = i;
+ if (index < 0 || doc_.subtoolMesh(index).triangleCount() != job->triangles) {
+ status_ = "QRemesh skipped: the SubTool changed while it was being remeshed";
+ return;
+ }
+ if (index != doc_.activeSubtool) doc_.selectSubtool(index);
+ if (doc_.sculptor.strokeActive()) endStroke();
+ CommandResult r{true, applyQRemesh(doc_, std::move(*job->result), job->keepOriginal, *job->stats)};
+ status_ = r.message;
+ lastCommandOk_ = true;
+ clearLods();
+ playingLayer_ = -1;
+ updateTitle();
+ consoleEcho("qremesh", job->args, r);
+}
+
+void App::drawQRemeshContents() {
+ const ImGuiStyle& style = ImGui::GetStyle();
+ ImGui::SeparatorText("QRemesh");
+ const float full = ImGui::GetContentRegionAvail().x;
+ const float half = (full - style.ItemSpacing.x) * 0.5f;
+ const float third = (full - 2.0f * style.ItemSpacing.x) / 3.0f;
+
+ if (qremesh_) {
+ ImGui::ProgressBar(qremesh_->progress->load(), ImVec2(half, 0), "Remeshing...");
+ ui::HelpText("QRemesh", nullptr, "Remeshing in the background. The result replaces the SubTool when it's done.",
+ kQRemeshPath);
+ ImGui::SameLine();
+ if (ImGui::Button("Cancel", ImVec2(-1, 0))) qremesh_->cancel->store(true);
+ ui::HelpText("Cancel", nullptr, "Stop QRemesh; the SubTool stays as it is.", kQRemeshPath);
+ } else {
+ ui::ActionButton(*this, "geometry.qremesh", ImVec2(half, 0));
+ ImGui::SameLine();
+ ImGui::AlignTextToFramePadding();
+ ImGui::TextDisabled("%zu polygons", faceCount(doc_.mesh));
+ }
+
+ ImGui::SetNextItemWidth(-1);
+ ImGui::SliderInt("##qtarget", &retopo_.target, 100, 200000, "Target Polygons %d", ImGuiSliderFlags_Logarithmic);
+ ui::HelpText("Target Polygons", nullptr,
+ "About how many quads QRemesh makes (Ctrl+click to type a number). Half / Same / Double set it from "
+ "the SubTool's current polygon count.",
+ kQRemeshPath);
+ const size_t faces = faceCount(doc_.mesh);
+ auto setTarget = [&](double k) { retopo_.target = int(std::clamp(double(faces) * k, 100.0, 2'000'000.0)); };
+ if (ImGui::Button("Half", ImVec2(third, 0))) setTarget(0.5);
+ ui::HelpText("Half", nullptr, "Target half the SubTool's current polygon count.", kQRemeshPath);
+ ImGui::SameLine();
+ if (ImGui::Button("Same", ImVec2(third, 0))) setTarget(1.0);
+ ui::HelpText("Same", nullptr, "Target the SubTool's current polygon count (to clean up topology without changing its density).",
+ kQRemeshPath);
+ ImGui::SameLine();
+ if (ImGui::Button("Double", ImVec2(-1, 0))) setTarget(2.0);
+ ui::HelpText("Double", nullptr, "Target twice the SubTool's current polygon count.", kQRemeshPath);
+
+ ImGui::SetNextItemWidth(-1);
+ ui::SliderInside("##qadaptive", &retopo_.adaptive, 0.0f, 1.0f, "Adaptive Size %.2f");
+ ui::HelpText("Adaptive Size", nullptr,
+ "0: quads all about the same size. Higher: smaller quads where the surface curves, bigger ones on "
+ "flat areas (the count stays near the target).",
+ kQRemeshPath);
+
+ ImGui::Checkbox("Keep Groups", &retopo_.keepGroups);
+ ui::HelpText("Keep Groups", nullptr,
+ "Edge loops follow the polygroup borders exactly and the result keeps the polygroups. Paint groups "
+ "where you want loops (around the eyes, the mouth) to guide the flow.",
+ kQRemeshPath);
+ ImGui::SameLine(half + style.ItemSpacing.x);
+ ImGui::Checkbox("Detect Edges", &retopo_.detectEdges);
+ ui::HelpText("Detect Edges", nullptr, "Hard edges (faces meeting at more than 50 degrees) get an edge loop, so they stay sharp.",
+ kQRemeshPath);
+ ImGui::Checkbox("Use Polypaint", &retopo_.usePolypaint);
+ ui::HelpText("Use Polypaint", nullptr,
+ "Paint where you want density: red areas get up to 4 times the quads, blue areas down to a quarter, "
+ "white is unchanged.",
+ kQRemeshPath);
+ ImGui::SameLine(half + style.ItemSpacing.x);
+ ImGui::Checkbox("Symmetry", &retopo_.symmetry);
+ const char axis = char('X' + symmetryAxis(symmetry_));
+ const std::string symHelp = std::string("Mirror the topology across the ") + axis +
+ " plane through the origin (the Transform palette's symmetry axis), welded on the seam.";
+ ui::HelpText("Symmetry", nullptr, symHelp.c_str(), kQRemeshPath);
+ ImGui::Checkbox("Keep Original", &retopo_.keepOriginal);
+ ui::HelpText("Keep Original", nullptr,
+ "Keep the SubTool as it was, hidden, right below the new one (\"<name> Original\"), ready to "
+ "ProjectAll its detail back. Off: replace it, as ZBrush does (undo brings it back).",
+ kQRemeshPath);
+}
+
+void App::drawProjectContents() {
+ const ImGuiStyle& style = ImGui::GetStyle();
+ ImGui::SeparatorText("Project");
+ const float half = (ImGui::GetContentRegionAvail().x - style.ItemSpacing.x) * 0.5f;
+ ui::ActionButton(*this, "subtool.project_all", ImVec2(half, 0));
+ ImGui::SameLine();
+ ImGui::SetNextItemWidth(-1);
+ ui::SliderInside("##pdist", &retopo_.projectDist, 0.001f, 0.2f, "Dist %.3f", ImGuiSliderFlags_Logarithmic);
+ ui::HelpText("Dist", nullptr,
+ "How far each vertex looks for the source surface, along its normal, as a fraction of the SubTool's "
+ "size. Raise it if parts don't pick up the detail; lower it where surfaces are close together.",
+ kProjectPath);
+ ImGui::SetNextItemWidth(half);
+ ImGui::SliderInt("##pblur", &retopo_.projectBlur, 0, 10, "PA Blur %d");
+ ui::HelpText("PA Blur", nullptr, "Smooth the projected result this many times (softens noise from the source).",
+ kProjectPath);
+ ImGui::SameLine();
+ ImGui::Checkbox("Mean", &retopo_.projectMean);
+ ui::HelpText("Mean", nullptr,
+ "Where the source is found on both sides of a vertex, settle halfway between instead of on the nearest.",
+ kProjectPath);
+ ImGui::Checkbox("Geometry", &retopo_.projectGeometry);
+ ui::HelpText("Geometry", nullptr, "Project the shape (into the active sculpt layer).", kProjectPath);
+ ImGui::SameLine(half + style.ItemSpacing.x);
+ ImGui::Checkbox("Polypaint", &retopo_.projectPolypaint);
+ ui::HelpText("Polypaint", nullptr, "Project the polypaint (into the active paint layer) when a source has any.",
+ kProjectPath);
+}
+
+} // namespace sf
diff --git a/src/app/UiTest.cpp b/src/app/UiTest.cpp
index 1d16a240..48c69cad 100644
--- a/src/app/UiTest.cpp
+++ b/src/app/UiTest.cpp
@@ -55,7 +55,8 @@
// painting goes into the texture), texture_layers, active_texture_layer,
// texture_painted (texels of the texture composite that aren't white),
// texture_mean_r / texture_mean_g / texture_mean_b (mean composite, sRGB 0-255),
-// auto_uv_running
+// auto_uv_running, qremesh_running (QRemesh working in the background),
+// quads (quad pairs in the active SubTool), quad_percent (quads among its polygons)
// (mesh values are the active SubTool's)
// snapshot remember the active mesh's vertices (for the moved* values)
// remember VALUE NAME keep VALUE's current value as $NAME
@@ -223,6 +224,10 @@ double Demo::query(const std::string& name, bool& known) const {
if (name == "texture_layers") return hasTexture(m) ? double(m.texture->layers.size()) : 0.0;
if (name == "active_texture_layer") return hasTexture(m) && !m.texture->layers.empty() ? double(m.texture->activeLayer) : -1.0;
if (name == "auto_uv_running") return app_.autoUv_ ? 1.0 : 0.0;
+ if (name == "qremesh_running") return app_.qremesh_ ? 1.0 : 0.0;
+ 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;
if (name == "texture_painted" || name.rfind("texture_mean_", 0) == 0) {
if (!hasTexture(m)) return 0.0;
const std::vector<uint8_t>& px = m.texture->pixels;
@@ -685,7 +690,8 @@ bool Demo::parseStep(int line, const std::vector<std::string>& w, std::string& e
steps_.push_back([this, line, timeout](float t) {
const bool idle = !busy(app_.pendingBrush_) && !busy(app_.pendingGenerator_) && !busy(app_.pendingModels_) &&
!busy(app_.pendingUnreal_) && !busy(app_.pendingComfyCheck_) && !app_.galleryBusy() &&
- !app_.thumbs_.busy() && !app_.libraryScanner_.busy() && !app_.autoUv_;
+ !app_.thumbs_.busy() && !app_.libraryScanner_.busy() && !app_.autoUv_ &&
+ !app_.qremesh_;
if (idle) return true;
SDL_Delay(10); // real work runs in real time
if (t > timeout) fail(line, "still busy after " + number(timeout) + " s");
diff --git a/src/core/QRemesh.cpp b/src/core/QRemesh.cpp
index cc2438a2..78baa013 100644
--- a/src/core/QRemesh.cpp
+++ b/src/core/QRemesh.cpp
@@ -106,15 +106,16 @@ inline float compatIndex(const vec3& v0, const vec3& n0, const vec3& q0, const v
const vec3 t0 = glm::cross(n0, q0), t1 = glm::cross(n1, q1);
const vec3 mid = middlePoint(v0, n0, v1, n1);
const ivec2 b0 = floorIndex(o0, q0, t0, 1.0f / s0, mid), b1 = floorIndex(o1, q1, t1, 1.0f / s1, mid);
+ vec3 p1[4];
+ for (int b = 0; b < 4; ++b) p1[b] = latticePoint(o1, q1, t1, s1, b1 + ivec2(b & 1, b >> 1));
float best = std::numeric_limits<float>::max();
for (int a = 0; a < 4; ++a) {
const ivec2 c0 = b0 + ivec2(a & 1, a >> 1);
const vec3 p0 = latticePoint(o0, q0, t0, s0, c0);
for (int b = 0; b < 4; ++b) {
- const ivec2 c1 = b1 + ivec2(b & 1, b >> 1);
- const vec3 d = p0 - latticePoint(o1, q1, t1, s1, c1);
+ const vec3 d = p0 - p1[b];
const float cost = glm::dot(d, d);
- if (cost < best) best = cost, i0 = c0, i1 = c1;
+ if (cost < best) best = cost, i0 = c0, i1 = b1 + ivec2(b & 1, b >> 1);
}
}
return best;
@@ -344,23 +345,63 @@ Level buildFinest(const WorkMesh& m, bool keepGroups, float sharpCos, std::vecto
uint32_t t0, t1;
int count;
};
- std::unordered_map<uint64_t, uint32_t> edgeIndex;
- edgeIndex.reserve(m.T.size() * 2);
+ // Each edge found from its lower vertex: the triangles around a vertex, their edges to higher vertices.
+ std::vector<uint32_t> vtOff(nv + 1, 0), vt(m.T.size() * 3);
+ for (const glm::uvec3& t : m.T)
+ for (int k = 0; k < 3; ++k) ++vtOff[t[k] + 1];
+ for (size_t i = 0; i < nv; ++i) vtOff[i + 1] += vtOff[i];
+ {
+ std::vector<uint32_t> fill(vtOff.begin(), vtOff.end() - 1);
+ for (uint32_t t = 0; t < m.T.size(); ++t)
+ for (int k = 0; k < 3; ++k) vt[fill[m.T[t][k]]++] = t;
+ }
+ std::vector<uint32_t> edgeOff(nv + 1, 0);
std::vector<EdgeInfo> edges;
- edges.reserve(m.T.size() * 3 / 2 + 16);
- for (uint32_t t = 0; t < m.T.size(); ++t)
- for (int k = 0; k < 3; ++k) {
- const uint32_t a = m.T[t][k], b = m.T[t][(k + 1) % 3];
- if (a == b) continue;
- auto [it, inserted] = edgeIndex.try_emplace(edgeKey(a, b), uint32_t(edges.size()));
- if (inserted)
- edges.push_back({std::min(a, b), std::max(a, b), t, kNone, 1});
+ auto vertexEdges = [&](uint32_t a, auto&& emit) {
+ std::pair<uint32_t, uint32_t> local[64]; // (other vertex, triangle)
+ std::vector<std::pair<uint32_t, uint32_t>> big;
+ size_t n = 0;
+ auto push = [&](uint32_t b, uint32_t t) {
+ if (n < 64) local[n++] = {b, t};
else {
- EdgeInfo& e = edges[it->second];
- if (e.count == 1) e.t1 = t;
- ++e.count;
+ if (big.empty()) big.assign(local, local + 64);
+ big.push_back({b, t});
+ ++n;
}
+ };
+ for (uint32_t k = vtOff[a]; k < vtOff[a + 1]; ++k) {
+ const uint32_t t = vt[k];
+ for (int e = 0; e < 3; ++e) {
+ const uint32_t x = m.T[t][e], y = m.T[t][(e + 1) % 3];
+ if (x == y) continue;
+ if (x == a && y > a) push(y, t);
+ else if (y == a && x > a) push(x, t);
+ }
+ }
+ std::pair<uint32_t, uint32_t>* p = big.empty() ? local : big.data();
+ std::sort(p, p + n);
+ for (size_t i = 0; i < n;) {
+ size_t j = i;
+ while (j < n && p[j].first == p[i].first) ++j;
+ emit(EdgeInfo{a, p[i].first, p[i].second, j - i > 1 ? p[i + 1].second : kNone, int(j - i)});
+ i = j;
+ }
+ };
+ parallelFor(nv, [&](size_t b0, size_t e0) {
+ for (size_t a = b0; a < e0; ++a) {
+ uint32_t count = 0;
+ vertexEdges(uint32_t(a), [&](const EdgeInfo&) { ++count; });
+ edgeOff[a + 1] = count;
+ }
+ });
+ for (size_t i = 0; i < nv; ++i) edgeOff[i + 1] += edgeOff[i];
+ edges.resize(edgeOff[nv]);
+ parallelFor(nv, [&](size_t b0, size_t e0) {
+ for (size_t a = b0; a < e0; ++a) {
+ uint32_t at = edgeOff[a];
+ vertexEdges(uint32_t(a), [&](const EdgeInfo& e) { edges[at++] = e; });
}
+ });
// CSR adjacency.
l.off.assign(nv + 1, 0);
for (const EdgeInfo& e : edges) ++l.off[e.a + 1], ++l.off[e.b + 1];
@@ -491,30 +532,50 @@ bool downsample(Level& f, Level& c) {
const size_t nc = c.V.size();
if (nc >= n) return false;
- // Coarse adjacency: neighbours' parents, weights summed.
- std::vector<std::vector<std::pair<uint32_t, float>>> lists(nc);
- for (uint32_t i = 0; i < n; ++i)
- for (uint32_t k = f.off[i]; k < f.off[i + 1]; ++k) {
- const uint32_t a = up[i], b = up[f.adj[k]];
- if (a != b) lists[a].push_back({b, f.w[k]});
+ // Coarse adjacency: the children's neighbours' parents, weights summed (per coarse vertex, in parallel).
+ std::vector<uint32_t> chOff(nc + 1, 0), ch(n);
+ for (uint32_t i = 0; i < n; ++i) ++chOff[up[i] + 1];
+ for (size_t v = 0; v < nc; ++v) chOff[v + 1] += chOff[v];
+ {
+ std::vector<uint32_t> fill(chOff.begin(), chOff.end() - 1);
+ for (uint32_t i = 0; i < n; ++i) ch[fill[up[i]]++] = i;
+ }
+ auto gather = [&](uint32_t v, std::vector<std::pair<uint32_t, float>>& l) {
+ l.clear();
+ for (uint32_t k = chOff[v]; k < chOff[v + 1]; ++k) {
+ const uint32_t i = ch[k];
+ for (uint32_t a = f.off[i]; a < f.off[i + 1]; ++a)
+ if (const uint32_t b = up[f.adj[a]]; b != v) l.push_back({b, f.w[a]});
}
- c.off.assign(nc + 1, 0);
- c.adj.clear();
- c.w.clear();
- for (uint32_t v = 0; v < nc; ++v) {
- auto& l = lists[v];
std::sort(l.begin(), l.end(), [](auto& x, auto& y) { return x.first < y.first; });
+ size_t w = 0;
for (size_t k = 0; k < l.size(); ++k) {
- if (!c.adj.empty() && c.off[v] < c.adj.size() && c.adj.back() == l[k].first) {
- c.w.back() += l[k].second;
- continue;
+ if (w > 0 && l[w - 1].first == l[k].first) l[w - 1].second += l[k].second;
+ else l[w++] = l[k];
+ }
+ l.resize(w);
+ };
+ c.off.assign(nc + 1, 0);
+ parallelFor(nc, [&](size_t b0, size_t e0) {
+ std::vector<std::pair<uint32_t, float>> l;
+ for (size_t v = b0; v < e0; ++v) {
+ gather(uint32_t(v), l);
+ c.off[v + 1] = uint32_t(l.size());
+ }
+ });
+ for (size_t v = 0; v < nc; ++v) c.off[v + 1] += c.off[v];
+ c.adj.resize(c.off[nc]);
+ c.w.resize(c.off[nc]);
+ parallelFor(nc, [&](size_t b0, size_t e0) {
+ std::vector<std::pair<uint32_t, float>> l;
+ for (size_t v = b0; v < e0; ++v) {
+ gather(uint32_t(v), l);
+ for (size_t k = 0; k < l.size(); ++k) {
+ c.adj[c.off[v] + k] = l[k].first;
+ c.w[c.off[v] + k] = l[k].second;
}
- c.adj.push_back(l[k].first);
- c.w.push_back(l[k].second);
}
- c.off[v + 1] = uint32_t(c.adj.size());
- std::vector<std::pair<uint32_t, float>>().swap(l);
- }
+ });
computeMeanEdge(c);
return true;
}
@@ -1076,6 +1137,11 @@ bool qremesh(const Mesh& source, const QRemeshOptions& opt, Mesh& out, std::stri
}
return true;
};
+ auto mark = [&](const char* what) {
+ if (timing)
+ std::fprintf(stderr, " %-28s %.3f s\n", what,
+ std::chrono::duration<double>(std::chrono::steady_clock::now() - start).count());
+ };
if (source.triangleCount() == 0) {
error = "QRemesh: the SubTool is empty";
return false;
@@ -1112,8 +1178,10 @@ bool qremesh(const Mesh& source, const QRemeshOptions& opt, Mesh& out, std::stri
const float wantEdge = spacing / (adaptive ? 6.0f : 4.0f);
// Surface the quads snap to (before any subdivision for density: same surface).
+ mark("prepare");
TriangleBVH surface;
surface.build(work.P, work.T);
+ mark("surface bvh");
if (!report(0.05f)) return false;
std::vector<std::pair<vec3, vec3>> boundarySegs, borderSegs;
@@ -1121,7 +1189,9 @@ bool qremesh(const Mesh& source, const QRemeshOptions& opt, Mesh& out, std::stri
work = refineLongEdges(std::move(work), 1.5f * wantEdge, std::max<size_t>(4'000'000, work.T.size()));
std::vector<Level> levels;
const float sharpCos = opt.detectEdges ? std::cos(glm::radians(50.0f)) : 2.0f;
+ mark("refine");
levels.push_back(buildFinest(work, opt.keepGroups, sharpCos, boundarySegs, boundaryIsCut, borderSegs, axis));
+ mark("finest level");
if (!report(0.10f)) return false;
// Hierarchy down to a few vertices; fields are solved from the top to the finest level dense enough.
while (levels.back().size() > 64 && levels.size() < 40) {
@@ -1133,6 +1203,7 @@ bool qremesh(const Mesh& source, const QRemeshOptions& opt, Mesh& out, std::stri
}
levels.push_back(std::move(c));
}
+ mark("hierarchy");
size_t base = 0;
while (base + 1 < levels.size() && levels[base + 1].meanEdge <= wantEdge) ++base;
if (!report(0.20f)) return false;
diff --git a/src/core/RetopoCommands.cpp b/src/core/RetopoCommands.cpp
index 6dc49e2d..f44f0449 100644
--- a/src/core/RetopoCommands.cpp
+++ b/src/core/RetopoCommands.cpp
@@ -55,6 +55,8 @@ void registerRetopoCommands(CommandRegistry& reg) {
{"adaptive", T::Number, "Adaptive Size 0-1: 0 = even quads, 1 = small quads in curved areas, big "
"ones on flat areas. Default 0.5.", false},
{"keep_groups", T::Bool, "Keep Groups: edge loops follow the polygroup borders and the groups are kept.", false},
+ {"detect_edges", T::Bool, "Detect Edges: hard edges (faces meeting at more than 50 degrees) get an edge "
+ "loop. Default true.", false},
{"use_polypaint", T::Bool, "Use the polypaint as a density guide: red areas get up to 4x the quads, blue "
"areas down to a quarter.", false},
{"symmetry", T::String, "Mirror the topology across x, y or z (the plane through the origin). Default: none.", false},
@@ -67,6 +69,7 @@ void registerRetopoCommands(CommandRegistry& reg) {
o.targetQuads = int(std::clamp(argNumber(a, "target", 5000), 16.0, 2'000'000.0));
o.adaptive = float(std::clamp(argNumber(a, "adaptive", 0.5), 0.0, 1.0));
o.keepGroups = argBool(a, "keep_groups", false);
+ o.detectEdges = argBool(a, "detect_edges", true);
o.usePolypaint = argBool(a, "use_polypaint", false);
o.symmetryAxis = symmetryAxisArg(argString(a, "symmetry"));
o.smoothIterations = int(std::clamp(argNumber(a, "smooth", 6), 0.0, 30.0));
diff --git a/tests/ui/retopo.sfui b/tests/ui/retopo.sfui
new file mode 100644
index 00000000..d4bcdbed
--- /dev/null
+++ b/tests/ui/retopo.sfui
@@ -0,0 +1,104 @@
+# Quad retopology and detail projection: Geometry > QRemesh (ZBrush's ZRemesher) rebuilds a sculpted sphere as
+# clean quads in the background, keeping the original as a hidden SubTool; after dividing the retopo twice,
+# SubTool > Project > ProjectAll brings the sculpted detail back.
+run new_sphere subdivisions=6
+run stroke points="-0.6,0.35,2 0,0.55,2 0.6,0.35,2" brush=Standard radius=0.16 strength=1
+run stroke points="-0.55,-0.35,2 0.55,-0.4,2" brush=Crease radius=0.12 strength=1
+run stroke points="0,0.15,2 0.1,-0.1,2" brush=Clay radius=0.22 strength=1 invert=true
+stroke 0.5 0.15 0.5 0.85
+click "Geometry##tool.geometry"
+expect "QRemesh/QRemesh"
+expect "QRemesh/##qadaptive"
+expect_value quads == 0
+
+# Ctrl-hover help on the new controls.
+hold ctrl
+hover "QRemesh/QRemesh"
+expect_help "ZRemesher"
+hover "QRemesh/Keep Groups"
+expect_help "polygroup borders"
+hover "QRemesh/Double"
+expect_help "twice"
+hover "QRemesh/##qtarget"
+expect_help "how many quads"
+hold none
+
+# Target Polygons about 3000 (drag the slider), keep the original.
+drag_item "QRemesh/##qtarget" -16 0
+expect_text "Target Polygons 3"
+click "QRemesh/Keep Original"
+remember triangles sculpt_tris
+click "QRemesh/QRemesh"
+wait_idle 120
+expect_status "quads"
+expect_status "100% quads"
+expect_value quad_percent == 100
+expect_value quads > 2400
+expect_value quads < 4400
+expect_value subtools == 2
+expect_value visible_subtools == 1
+click "PolyF##view.polyf"
+shot qremesh-polyf
+click "PolyF##view.polyf"
+
+# One undo step; redo brings the quads back.
+key ctrl+z
+expect_value quads == 0
+expect_value triangles == $sculpt_tris
+key ctrl+shift+z
+expect_value quads > 2400
+
+# Half / Same / Double set the target from the current polygon count.
+click "QRemesh/Double"
+expect_text "Target Polygons 6"
+
+# Divide twice, show the original and project its detail back.
+run subdivide levels=2
+run subtool_visibility index=1 visible=true
+click "SubTool##tool.subtool"
+expect "Project/ProjectAll"
+hold ctrl
+hover "Project/ProjectAll"
+expect_help "nearest surface within Dist"
+hover "Project/##pdist"
+expect_help "fraction of the SubTool's size"
+hold none
+snapshot
+click "Project/ProjectAll"
+expect_status "vertices projected"
+expect_value moved > 20000
+run subtool_visibility index=1 visible=false
+click "PolyF##view.polyf"
+shot projected-polyf
+click "PolyF##view.polyf"
+shot projected
+key ctrl+z
+expect_value moved == 0
+
+# Cancel: a big target on the sculpt stops part way and leaves it as it was.
+run subtool_select index=1
+run subtool_visibility index=1 visible=true
+click "Geometry##tool.geometry"
+click "QRemesh/Keep Original"
+click "QRemesh/Same"
+remember triangles before_cancel
+click "QRemesh/QRemesh"
+expect_value qremesh_running == 1
+click "QRemesh/Cancel"
+wait_idle 60
+expect_status "cancelled"
+expect_value triangles == $before_cancel
+expect_value quads == 0
+
+# The bundled lion bust: 47k triangles of sculpt to 5000 quads, edge loops following the mane.
+drop ../../assets/demo/lion-head.glb
+wait_idle 30
+click "QRemesh/Keep Original"
+drag_item "QRemesh/##qtarget" 6 0
+expect_text "Target Polygons 5"
+click "QRemesh/QRemesh"
+wait_idle 120
+expect_status "100% quads"
+expect_value quad_percent == 100
+click "PolyF##view.polyf"
+shot lion-qremesh-polyf