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.

UV Editor core: UV topology, seams and pins, LSCM / least-stretch / polygroup / planar / unfold unwraps, UDIM packing, texel density, trim sheets, uv_* commands with undo

islandmed462e57261541
diff --git a/CMakeLists.txt b/CMakeLists.txt
index 3046f86f..46cdfc15 100644
--- a/CMakeLists.txt
+++ b/CMakeLists.txt
@@ -72,6 +72,10 @@ add_library(sculptforge_core STATIC
src/core/PaintLayer.cpp
src/core/Texture.cpp
src/core/TextureCommands.cpp
+ src/core/Uv.cpp
+ src/core/UvCommands.cpp
+ src/core/UvPack.cpp
+ src/core/UvUnwrap.cpp
src/core/TileImage.cpp
src/core/TextureChannels.cpp
src/core/TextureChannelCommands.cpp
diff --git a/src/core/Document.cpp b/src/core/Document.cpp
index a91260c7..afc2fa95 100644
--- a/src/core/Document.cpp
+++ b/src/core/Document.cpp
@@ -53,6 +53,7 @@ void Document::markClean() {
void Document::selectSubtool(int i) {
if (i < 0 || i >= subtoolCount() || i == activeSubtool) return;
+ uvSelection.clear();
// Check the active SubTool back in, then check `i` out. Swapping keeps each
// mesh's GPU dirty state, so the renderer doesn't re-upload anything.
auto swapIn = [this](SubTool& s) {
diff --git a/src/core/Document.h b/src/core/Document.h
index 347af152..374b3f62 100644
--- a/src/core/Document.h
+++ b/src/core/Document.h
@@ -12,6 +12,7 @@
#include "core/Splats.h"
#include "core/TextureChannels.h"
#include "core/Undo.h"
+#include "core/Uv.h"
#include "core/Vdm.h"
#include <map>
@@ -102,6 +103,9 @@ struct Document {
// QRemesh Guides of the active SubTool: curves QRemesh's edge loops follow (core/QRemeshGuides.h). Not part
// of undo (Delete Last / Clear remove them); editing them sets `modified`.
std::vector<QRemeshGuide> qremeshGuides;
+ // The UV Editor's selection on the active SubTool (core/Uv.h); dropped when another SubTool is picked or the
+ // triangles change (UvSelection::valid). Not part of undo.
+ UvSelection uvSelection;
void syncBvh() {
if (bvhDirty) bvh.build(mesh);
diff --git a/src/core/Mesh.cpp b/src/core/Mesh.cpp
index 24b344d3..726f25b0 100644
--- a/src/core/Mesh.cpp
+++ b/src/core/Mesh.cpp
@@ -155,6 +155,7 @@ void Mesh::sanitizeAttributes() {
if (!polygroups.empty() && polygroups.size() != triangles.size()) clearPolygroups();
if (!hidden.empty() && hidden.size() != triangles.size()) clearHidden();
if (!uvs.empty() && uvs.size() != triangles.size() * 3) std::vector<glm::vec2>().swap(uvs);
+ if (!uvFlags.empty() && uvFlags.size() != triangles.size() * 3) std::vector<uint8_t>().swap(uvFlags);
if (!quadPartners.empty() && quadPartners.size() != triangles.size()) clearQuads();
// Quad pairs must be mutual and share an edge: unpair anything an edit or a malformed file left behind.
bool anyQuad = false;
@@ -794,7 +795,7 @@ AABB Mesh::bounds() const {
size_t Mesh::memoryBytes() const {
auto bytes = [](const auto& v) { return v.capacity() * sizeof(v[0]); };
size_t n = bytes(positions) + bytes(normals) + bytes(triangles) + bytes(mask) + bytes(colors) + bytes(polygroups) +
- bytes(hidden) + bytes(uvs) + bytes(quadPartners) + bytes(base) + bytes(paintBase) + bytes(adjOffsets_) +
+ bytes(hidden) + bytes(uvs) + bytes(uvFlags) + bytes(quadPartners) + bytes(base) + bytes(paintBase) + bytes(adjOffsets_) +
bytes(adjList_) + bytes(vtOffsets_) + bytes(vtList_) + bytes(adjEnds_) + bytes(adjCaps_) + bytes(vtEnds_) + bytes(vtCaps_) + normalBits_.memoryBytes() + bytes(scratchVerts_) + bytes(dirtyBlocks) + bytes(dirtyBits);
for (const auto& l : layers) n += bytes(l.delta);
for (const auto& l : paintLayers) n += bytes(l.color) + bytes(l.alpha);
diff --git a/src/core/Mesh.h b/src/core/Mesh.h
index 29cd416c..f099e0a9 100644
--- a/src/core/Mesh.h
+++ b/src/core/Mesh.h
@@ -101,6 +101,9 @@ public:
std::vector<uint8_t> hidden;
// Per triangle corner (3 per triangle, in triangle order): texture coordinates.
std::vector<glm::vec2> uvs;
+ // Per triangle corner (empty = none): UV editing flags (core/Uv.h), kUvSeam on the edge from this corner to
+ // the next (a marked seam, kept on both sides of the edge) and kUvPin (the corner's UV stays put on Unwrap).
+ std::vector<uint8_t> uvFlags;
// Per triangle: the triangle it forms a quad with (kNoQuad = a plain triangle; empty = no quads). Imported
// quads are split into two triangles that keep each other here, so the wireframe and the exporters can
// show and write them as quads again. Pairs are symmetric and share one edge, wound oppositely;
@@ -113,6 +116,7 @@ public:
bool hasPolygroups() const { return !polygroups.empty(); }
bool hasHidden() const { return !hidden.empty(); }
bool hasUvs() const { return !uvs.empty(); }
+ bool hasUvFlags() const { return !uvFlags.empty(); }
bool hasQuads() const { return !quadPartners.empty(); }
float maskAt(uint32_t v) const { return mask.empty() ? 0.0f : mask[v]; }
diff --git a/src/core/Polypaint.cpp b/src/core/Polypaint.cpp
index 48b3abcc..815b3302 100644
--- a/src/core/Polypaint.cpp
+++ b/src/core/Polypaint.cpp
@@ -1,6 +1,7 @@
// SculptForge - open source digital sculpting
// SPDX-License-Identifier: GPL-3.0-or-later
#include "core/Polypaint.h"
+#include "core/Uv.h"
#include "core/MapExport.h"
#include "core/Commands.h"
@@ -403,6 +404,7 @@ void registerPaintCommands(CommandRegistry& registry) {
}});
registerPaintLayerCommands(registry); // paint_layer_* (core/PaintLayer.cpp)
registerTextureCommands(registry); // texture_*, uv_auto, paint_target (core/TextureCommands.cpp)
+ registerUvCommands(registry); // uv_unwrap, uv_pack, uv_seam, uv_select, ... (core/UvCommands.cpp)
registerTextureChannelCommands(registry); // texture_channels, paint_material, channel_view (core/TextureChannelCommands.cpp)
registerMapExportCommands(registry); // export_maps (core/MapExport.cpp)
}
diff --git a/src/core/Project.cpp b/src/core/Project.cpp
index 477849f5..c874ed19 100644
--- a/src/core/Project.cpp
+++ b/src/core/Project.cpp
@@ -349,6 +349,7 @@ void writeMesh(Writer& w, const std::string& prefix, const Mesh& m, Json& out, s
mesh.set("polygroups", w.uints(prefix + "mesh/polygroups.bin", m.polygroups.data(), m.polygroups.size(), 1));
if (m.hasHidden()) mesh.set("hidden", w.bytes(prefix + "mesh/hidden.bin", m.hidden));
if (m.hasUvs()) mesh.set("uvs", w.floats(prefix + "mesh/uvs.bin", &m.uvs[0].x, m.uvs.size(), 2));
+ if (m.hasUvFlags()) mesh.set("uv_flags", w.bytes(prefix + "mesh/uv_flags.bin", m.uvFlags)); // seams, pins (core/Uv.h)
// Optional and ignored by older readers, so no format version bump.
if (m.hasQuads())
mesh.set("quad_partners", w.uints(prefix + "mesh/quad_partners.bin", m.quadPartners.data(), m.quadPartners.size(), 1));
@@ -404,6 +405,9 @@ bool readMesh(Reader& r, const Json& mj, const Json& lj, Mesh& m, std::string& e
m.uvs.resize(nt * 3);
r.floats(mj["uvs"], "uvs", nt * 3, 2, nt ? &m.uvs[0].x : nullptr);
}
+ if (mj.has("uv_flags")) {
+ if (!r.bytes(mj["uv_flags"], "UV seams", nt * 3, m.uvFlags)) m.uvFlags.clear();
+ }
if (mj.has("quad_partners")) { // rebuildTopology() unpairs anything that isn't a valid pair
m.quadPartners.resize(nt);
r.uints(mj["quad_partners"], "quad partners", nt, 1, m.quadPartners.data());
diff --git a/src/core/Timeline.cpp b/src/core/Timeline.cpp
index e19fdb2c..02ad200c 100644
--- a/src/core/Timeline.cpp
+++ b/src/core/Timeline.cpp
@@ -65,7 +65,7 @@ Timeline::Kind Timeline::classify(const UndoRecord& r) {
bool Timeline::fastShape(const UndoRecord& r) {
return !r.positions.empty() && r.layer == -1 && r.layerOffsets.empty() && r.mask.empty() && r.colors.empty() &&
r.paintAlpha.empty() && !r.paint && r.hidden.empty() && r.polygroups.empty() && !r.textureTiles &&
- !r.texture && !r.mesh && !r.subdiv && !r.topology && !r.subtool;
+ !r.texture && !r.mesh && !r.subdiv && !r.topology && !r.subtool && !r.uv;
}
void Timeline::reset() {
@@ -758,7 +758,7 @@ struct Reader {
};
bool savable(const UndoRecord& r) {
- return !r.mesh && !r.subdiv && !r.topology && !r.subtool && !r.texture && !r.textureTiles && !r.paint &&
+ return !r.mesh && !r.subdiv && !r.topology && !r.subtool && !r.texture && !r.textureTiles && !r.paint && !r.uv &&
r.layerOffsets.empty() && r.layer == -1 && r.paintLayer == -1 && r.paintAlpha.empty();
}
diff --git a/src/core/Undo.cpp b/src/core/Undo.cpp
index de70cba5..f423bc10 100644
--- a/src/core/Undo.cpp
+++ b/src/core/Undo.cpp
@@ -11,7 +11,7 @@ size_t UndoRecord::approxBytes() const {
polygroups.bytes() + (paint ? paint->bytes() : 0) +
(textureTiles ? textureTiles->bytes() : 0) + (texture ? texture->bytes() : 0) +
(subdiv ? subdiv->bytes() : 0) + (topology ? topology->bytes() : 0) +
- (micro ? micro->bytes() : 0);
+ (micro ? micro->bytes() : 0) + (uv ? uv->bytes() : 0);
for (const auto& l : layerOffsets) bytes += l.bytes();
if (mesh)
bytes += mesh->vertexCount() * ((2 + (mesh->base.empty() ? 0 : 1 + mesh->layers.size())) * sizeof(glm::vec3) +
@@ -189,6 +189,7 @@ void UndoStack::apply(UndoRecord& r, Mesh& mesh, BVH& bvh) {
for (uint32_t v : r.mask.indices) mesh.markDirty(v);
}
if (r.paint) r.paint->swapWith(mesh);
+ if (r.uv) r.uv->swapWith(mesh);
if (r.texture) r.texture->swapWith(mesh);
if (r.textureTiles) r.textureTiles->swapWith(mesh);
if (!r.colors.empty()) {
@@ -214,6 +215,45 @@ void UndoStack::apply(UndoRecord& r, Mesh& mesh, BVH& bvh) {
}
}
+std::unique_ptr<UvUndo> UvUndo::capture(const Mesh& mesh) {
+ auto u = std::make_unique<UvUndo>();
+ u->uvs = mesh.uvs;
+ u->flags = mesh.uvFlags;
+ return u;
+}
+
+void UvUndo::commit(const Mesh& mesh) {
+ // Sparse when the arrays keep their sizes and under half of the corners changed.
+ if (sparse || uvs.size() != mesh.uvs.size() || flags.size() != mesh.uvFlags.size()) return;
+ UndoChannel<glm::vec2> cu;
+ UndoChannel<uint8_t> cf;
+ for (uint32_t c = 0; c < uvs.size(); ++c)
+ if (uvs[c] != mesh.uvs[c]) cu.add(c, uvs[c]);
+ for (uint32_t c = 0; c < flags.size(); ++c)
+ if (flags[c] != mesh.uvFlags[c]) cf.add(c, flags[c]);
+ if (cu.bytes() + cf.bytes() >= (uvs.size() * sizeof(glm::vec2) + flags.size()) / 2) return;
+ uvCorners = std::move(cu);
+ flagCorners = std::move(cf);
+ std::vector<glm::vec2>().swap(uvs);
+ std::vector<uint8_t>().swap(flags);
+ sparse = true;
+}
+
+void UvUndo::swapWith(Mesh& mesh) {
+ if (sparse) {
+ if (mesh.uvs.size() >= mesh.triangleCount() * 3) uvCorners.swapWith(mesh.uvs);
+ if (mesh.uvFlags.size() >= mesh.triangleCount() * 3) flagCorners.swapWith(mesh.uvFlags);
+ } else {
+ std::swap(uvs, mesh.uvs);
+ std::swap(flags, mesh.uvFlags);
+ }
+ mesh.facesDirty = true; // the renderer's per-triangle UVs
+}
+
+size_t UvUndo::bytes() const {
+ return uvs.size() * sizeof(glm::vec2) + flags.size() + uvCorners.bytes() + flagCorners.bytes();
+}
+
bool UndoStack::undo(Mesh& mesh, BVH& bvh) {
if (undo_.empty()) return false;
UndoRecord r = std::move(undo_.back());
diff --git a/src/core/Undo.h b/src/core/Undo.h
index b8c6420b..700a2902 100644
--- a/src/core/Undo.h
+++ b/src/core/Undo.h
@@ -101,6 +101,21 @@ struct TextureStackUndo {
size_t bytes() const;
};
+// The UVs and UV flags (seams, pins; core/Uv.h) before a UV edit. capture() holds the whole arrays; commit()
+// (with the mesh after the edit) keeps only the corners that changed when that is smaller. Applying swaps them
+// with the mesh's, so the record then holds the inverse.
+struct UvUndo {
+ bool sparse = false;
+ std::vector<glm::vec2> uvs; // whole: the old array (empty = the mesh had none)
+ std::vector<uint8_t> flags; // whole: the old flags (empty = none)
+ UndoChannel<glm::vec2> uvCorners; // sparse: old UVs of changed corners
+ UndoChannel<uint8_t> flagCorners; // sparse: old flags of changed corners
+ static std::unique_ptr<UvUndo> capture(const Mesh& mesh);
+ void commit(const Mesh& mesh);
+ void swapWith(Mesh& mesh);
+ size_t bytes() const;
+};
+
// Adding or removing a whole SubTool (Extract's Accept; core/Document.h). Applied by the undo / redo commands,
// which see the whole scene: the record itself leaves the mesh alone.
struct SubtoolStep;
@@ -145,11 +160,12 @@ struct UndoRecord {
std::unique_ptr<SubdivUndo> subdiv;
std::unique_ptr<TopologyUndo> topology;
std::shared_ptr<SubtoolStep> subtool; // (shared: SubtoolStep is defined in core/Document.h)
+ std::unique_ptr<UvUndo> uv; // UVs, seams and pins (UV Editor, core/Uv.h)
std::unique_ptr<MicroUndo> micro; // micro-displacement tiles of a stroke, or a micro level added / removed (core/Micro.h)
bool empty() const {
return positions.empty() && mask.empty() && colors.empty() && paintAlpha.empty() && hidden.empty() &&
- polygroups.empty() && !mesh && !paint && !textureTiles && !texture && !subdiv && !topology && !subtool && !micro;
+ polygroups.empty() && !mesh && !paint && !textureTiles && !texture && !subdiv && !topology && !subtool && !micro && !uv;
}
size_t approxBytes() const;
diff --git a/src/core/Uv.cpp b/src/core/Uv.cpp
new file mode 100644
index 00000000..cf3198c1
--- /dev/null
+++ b/src/core/Uv.cpp
@@ -0,0 +1,892 @@
+// SculptForge - open source digital sculpting
+// SPDX-License-Identifier: GPL-3.0-or-later
+#include "core/Uv.h"
+
+#include "core/Mesh.h"
+#include "core/ThreadPool.h"
+#include "core/UvInternal.h"
+
+#include <algorithm>
+#include <cmath>
+#include <limits>
+#include <map>
+#include <queue>
+#include <sstream>
+
+namespace sf {
+
+using namespace uvdetail;
+
+namespace uvdetail {
+
+std::vector<glm::vec2> convexHull(std::vector<glm::vec2> pts) {
+ std::sort(pts.begin(), pts.end(), [](glm::vec2 a, glm::vec2 b) { return a.x < b.x || (a.x == b.x && a.y < b.y); });
+ pts.erase(std::unique(pts.begin(), pts.end()), pts.end());
+ if (pts.size() < 3) return pts;
+ std::vector<glm::vec2> h(pts.size() * 2);
+ size_t k = 0;
+ for (size_t i = 0; i < pts.size(); ++i) {
+ while (k >= 2 && cross2(h[k - 1] - h[k - 2], pts[i] - h[k - 2]) <= 0.0f) --k;
+ h[k++] = pts[i];
+ }
+ for (size_t i = pts.size() - 1, lo = k + 1; i-- > 0;) {
+ while (k >= lo && cross2(h[k - 1] - h[k - 2], pts[i] - h[k - 2]) <= 0.0f) --k;
+ h[k++] = pts[i];
+ }
+ h.resize(k - 1);
+ return h;
+}
+
+float minAreaRectAngle(const std::vector<glm::vec2>& pts) {
+ const std::vector<glm::vec2> h = convexHull(pts);
+ if (h.size() < 3) {
+ if (h.size() == 2) return -std::atan2(h[1].y - h[0].y, h[1].x - h[0].x);
+ return 0.0f;
+ }
+ // Rotating calipers: the smallest box has a side on a hull edge.
+ float bestArea = std::numeric_limits<float>::max(), best = 0.0f;
+ for (size_t i = 0; i < h.size(); ++i) {
+ const glm::vec2 e = h[(i + 1) % h.size()] - h[i];
+ const float len = glm::length(e);
+ if (len <= 0.0f) continue;
+ const float c = e.x / len, s = -e.y / len; // rotation by -angle(e)
+ glm::vec2 lo(std::numeric_limits<float>::max()), hi(std::numeric_limits<float>::lowest());
+ for (const glm::vec2& p : h) {
+ const glm::vec2 q = rotate(p, c, s);
+ lo = glm::min(lo, q);
+ hi = glm::max(hi, q);
+ }
+ const glm::vec2 d = hi - lo;
+ const float area = d.x * d.y;
+ if (area < bestArea * 0.9999f) {
+ bestArea = area;
+ best = std::atan2(s, c);
+ if (d.y > d.x) best += 1.5707963f; // long side along u
+ }
+ }
+ return best;
+}
+
+void islandCorners(const UvTopology& topo, std::vector<uint32_t>& offsets, std::vector<uint32_t>& corners) {
+ offsets.assign(topo.islandCount + 1, 0);
+ for (uint32_t i = 0; i < topo.islandCount; ++i)
+ offsets[i + 1] = offsets[i] + 3 * (topo.islandOffsets[i + 1] - topo.islandOffsets[i]);
+ corners.resize(offsets.back());
+ poolFor(topo.islandCount, [&](size_t b, size_t e) {
+ for (size_t i = b; i < e; ++i) {
+ uint32_t at = offsets[i];
+ for (uint32_t k = topo.islandOffsets[i]; k < topo.islandOffsets[i + 1]; ++k) {
+ const uint32_t t = topo.islandTriangles[k];
+ for (uint32_t j = 0; j < 3; ++j) corners[at++] = t * 3 + j;
+ }
+ }
+ }, 64);
+}
+
+} // namespace uvdetail
+
+int udimTile(const glm::vec2& uv) {
+ const int u = std::clamp(int(std::floor(uv.x)), 0, 9);
+ const int v = std::max(int(std::floor(uv.y)), 0);
+ return 1001 + u + 10 * v;
+}
+
+glm::vec2 udimOrigin(int tile) {
+ const int i = std::max(tile - 1001, 0);
+ return {float(i % 10), float(i / 10)};
+}
+
+std::vector<uint32_t> cornerTwins(const Mesh& m) {
+ const size_t nt = m.triangleCount(), nv = m.vertexCount();
+ std::vector<uint32_t> twin(nt * 3, kNoCorner);
+ if (nt == 0) return twin;
+ // Corners bucketed by the lower vertex of their edge (a counting sort), then matched within each bucket.
+ std::vector<uint32_t> offsets(nv + 1, 0);
+ auto lower = [&](uint32_t c) {
+ const glm::uvec3& t = m.triangles[c / 3];
+ return std::min(t[c % 3], t[(c % 3 + 1) % 3]);
+ };
+ for (uint32_t c = 0; c < nt * 3; ++c) ++offsets[lower(c) + 1];
+ for (size_t v = 0; v < nv; ++v) offsets[v + 1] += offsets[v];
+ std::vector<uint32_t> fill(offsets.begin(), offsets.end() - 1), list(nt * 3);
+ for (uint32_t c = 0; c < nt * 3; ++c) list[fill[lower(c)]++] = c;
+ poolFor(nv, [&](size_t b, size_t e) {
+ for (size_t v = b; v < e; ++v) {
+ const uint32_t* first = list.data() + offsets[v];
+ const uint32_t n = offsets[v + 1] - offsets[v];
+ for (uint32_t i = 0; i < n; ++i) {
+ const uint32_t c = first[i];
+ const glm::uvec3& tc = m.triangles[c / 3];
+ const uint32_t a = tc[c % 3], bb = tc[(c % 3 + 1) % 3];
+ uint32_t match = kNoCorner, same = 0;
+ for (uint32_t j = 0; j < n; ++j) {
+ if (j == i) continue;
+ const uint32_t d = first[j];
+ const glm::uvec3& td = m.triangles[d / 3];
+ const uint32_t da = td[d % 3], db = td[(d % 3 + 1) % 3];
+ if (da == bb && db == a) {
+ match = match == kNoCorner ? d : kNoCorner - 1; // two opposite: non-manifold
+ } else if (da == a && db == bb) {
+ ++same;
+ }
+ }
+ twin[c] = (same == 0 && match < kNoCorner - 1) ? match : kNoCorner;
+ }
+ }
+ }, 1 << 12);
+ // Keep only mutual pairs.
+ for (uint32_t c = 0; c < nt * 3; ++c)
+ if (twin[c] != kNoCorner && twin[twin[c]] != c) twin[c] = kNoCorner;
+ return twin;
+}
+
+UvTopology buildUvTopology(const Mesh& m, std::vector<uint32_t> twin) {
+ UvTopology topo;
+ const size_t nt = m.triangleCount(), nc = nt * 3;
+ if (twin.size() != nc) twin = cornerTwins(m);
+ topo.twin = std::move(twin);
+ topo.border.assign(nc, 1);
+ const bool uvs = m.uvs.size() == nc;
+ const bool flags = m.uvFlags.size() == nc;
+ poolFor(nc, [&](size_t b, size_t e) {
+ for (size_t c = b; c < e; ++c) {
+ const uint32_t d = topo.twin[c];
+ if (d == kNoCorner) continue;
+ if (flags && ((m.uvFlags[c] | m.uvFlags[d]) & kUvSeam)) continue;
+ if (uvs && (m.uvs[c] != m.uvs[cornerNext(d)] || m.uvs[cornerNext(uint32_t(c))] != m.uvs[d])) continue;
+ topo.border[c] = 0;
+ }
+ }, 1 << 15);
+ DisjointSets corners(nc), tris(nt);
+ for (uint32_t c = 0; c < nc; ++c) {
+ if (topo.border[c]) continue;
+ const uint32_t d = topo.twin[c];
+ if (d < c) continue;
+ corners.unite(c, cornerNext(d));
+ corners.unite(cornerNext(c), d);
+ tris.unite(c / 3, d / 3);
+ }
+ topo.uvVertexCount = corners.labels(topo.uvVertex);
+ topo.islandCount = tris.labels(topo.island);
+ topo.islandOffsets.assign(topo.islandCount + 1, 0);
+ for (uint32_t t = 0; t < nt; ++t) ++topo.islandOffsets[topo.island[t] + 1];
+ for (uint32_t i = 0; i < topo.islandCount; ++i) topo.islandOffsets[i + 1] += topo.islandOffsets[i];
+ std::vector<uint32_t> at(topo.islandOffsets.begin(), topo.islandOffsets.end() - 1);
+ topo.islandTriangles.resize(nt);
+ for (uint32_t t = 0; t < nt; ++t) topo.islandTriangles[at[topo.island[t]]++] = t;
+ return topo;
+}
+
+// ---------------------------------------------------------------------------------------------------------------
+// Measures
+
+namespace {
+
+float area3(const Mesh& m, uint32_t t) {
+ const glm::uvec3& tri = m.triangles[t];
+ return 0.5f * glm::length(glm::cross(m.positions[tri.y] - m.positions[tri.x], m.positions[tri.z] - m.positions[tri.x]));
+}
+float signedAreaUv(const Mesh& m, uint32_t t) {
+ const glm::vec2* u = m.uvs.data() + size_t(t) * 3;
+ return 0.5f * cross2(u[1] - u[0], u[2] - u[0]);
+}
+
+} // namespace
+
+void uvTriangleDensity(const Mesh& m, int resolution, std::vector<float>& out) {
+ const size_t nt = m.triangleCount();
+ out.assign(nt, 0.0f);
+ if (m.uvs.size() != nt * 3) return;
+ poolFor(nt, [&](size_t b, size_t e) {
+ for (size_t t = b; t < e; ++t) {
+ const float a = area3(m, uint32_t(t));
+ out[t] = a > 0.0f ? std::sqrt(std::abs(signedAreaUv(m, uint32_t(t))) / a) * float(resolution) : 0.0f;
+ }
+ }, 1 << 14);
+}
+
+std::vector<float> uvIslandDensity(const Mesh& m, const UvTopology& topo, int resolution) {
+ std::vector<float> out(topo.islandCount, 0.0f);
+ if (m.uvs.size() != m.triangleCount() * 3) return out;
+ poolFor(topo.islandCount, [&](size_t b, size_t e) {
+ for (size_t i = b; i < e; ++i) {
+ double a = 0.0, u = 0.0;
+ for (uint32_t k = topo.islandOffsets[i]; k < topo.islandOffsets[i + 1]; ++k) {
+ const uint32_t t = topo.islandTriangles[k];
+ a += area3(m, t);
+ u += std::abs(signedAreaUv(m, t));
+ }
+ out[i] = a > 0.0 ? float(std::sqrt(u / a) * resolution) : 0.0f;
+ }
+ }, 64);
+ return out;
+}
+
+float uvMeshDensity(const Mesh& m, int resolution) {
+ const size_t nt = m.triangleCount();
+ if (m.uvs.size() != nt * 3 || nt == 0) return 0.0f;
+ double a = 0.0, u = 0.0;
+ for (uint32_t t = 0; t < nt; ++t) {
+ a += area3(m, t);
+ u += std::abs(signedAreaUv(m, t));
+ }
+ return a > 0.0 ? float(std::sqrt(u / a) * resolution) : 0.0f;
+}
+
+namespace {
+
+// Singular values (s1 >= s2) and orientation of triangle t's map from its surface to UV space.
+bool triangleJacobian(const Mesh& m, uint32_t t, float& s1, float& s2, bool& flipped) {
+ const glm::uvec3& tri = m.triangles[t];
+ const glm::vec3 e1 = m.positions[tri.y] - m.positions[tri.x], e2 = m.positions[tri.z] - m.positions[tri.x];
+ const float l1 = glm::length(e1);
+ const glm::vec3 n = glm::cross(e1, e2);
+ const float nl = glm::length(n);
+ if (l1 <= 0.0f || nl <= 0.0f) return false;
+ const glm::vec3 x = e1 / l1, y = glm::cross(n / nl, x);
+ // Surface triangle in its plane: (0,0), (l1,0), (q2x,q2y).
+ const float q2x = glm::dot(e2, x), q2y = glm::dot(e2, y);
+ const glm::vec2* u = m.uvs.data() + size_t(t) * 3;
+ const glm::vec2 d1 = u[1] - u[0], d2 = u[2] - u[0];
+ // J * [l1 q2x; 0 q2y] = [d1 d2] -> J = [d1 d2] * inverse.
+ if (std::abs(q2y) <= 0.0f) return false;
+ const glm::vec2 c0 = d1 / l1; // J's first column
+ const glm::vec2 c1 = (d2 - c0 * q2x) / q2y; // J's second column
+ const float a = c0.x, b = c1.x, c = c0.y, d = c1.y; // J = [a b; c d]
+ const float E = (a + d) * 0.5f, F = (a - d) * 0.5f, G = (c + b) * 0.5f, H = (c - b) * 0.5f;
+ const float Q = std::sqrt(E * E + H * H), R = std::sqrt(F * F + G * G);
+ s1 = Q + R;
+ s2 = std::abs(Q - R);
+ flipped = (a * d - b * c) < 0.0f;
+ return true;
+}
+
+} // namespace
+
+void uvTriangleStretch(const Mesh& m, std::vector<float>& out) {
+ const size_t nt = m.triangleCount();
+ out.assign(nt, 0.0f);
+ if (m.uvs.size() != nt * 3 || nt == 0) return;
+ // Measured against each island's own scale, so islands packed smaller or larger don't count as stretched; and
+ // against its own sense, so an island laid out mirrored as a whole is fine (only triangles folded over the
+ // rest of their island count as flipped).
+ const UvTopology topo = buildUvTopology(m);
+ std::vector<float> scale(topo.islandCount, 0.0f);
+ std::vector<uint8_t> mirrored(topo.islandCount, 0);
+ poolFor(topo.islandCount, [&](size_t b, size_t e) {
+ for (size_t i = b; i < e; ++i) {
+ double a = 0.0, u = 0.0, sense = 0.0;
+ for (uint32_t k = topo.islandOffsets[i]; k < topo.islandOffsets[i + 1]; ++k) {
+ const uint32_t t = topo.islandTriangles[k];
+ const float su = signedAreaUv(m, t);
+ a += area3(m, t);
+ u += std::abs(su);
+ sense += su;
+ }
+ scale[i] = a > 0.0 ? float(std::sqrt(u / a)) : 0.0f;
+ mirrored[i] = sense < 0.0;
+ }
+ }, 64);
+ poolFor(nt, [&](size_t b, size_t e) {
+ for (size_t t = b; t < e; ++t) {
+ float s1 = 0, s2 = 0;
+ bool flipped = false;
+ const uint32_t i = topo.island[t];
+ const float s = scale[i];
+ if (s <= 0.0f || !triangleJacobian(m, uint32_t(t), s1, s2, flipped)) continue;
+ out[t] = flipped != bool(mirrored[i]) ? -1.0f
+ : std::log2(std::max(std::max(s1 / s, 1e-6f), s / std::max(s2, 1e-6f * s)));
+ }
+ }, 1 << 14);
+}
+
+UvStretchStats uvStretchStats(const Mesh& m) {
+ UvStretchStats st;
+ std::vector<float> s;
+ uvTriangleStretch(m, s);
+ double wsum = 0.0, sum = 0.0, flipped = 0.0;
+ for (uint32_t t = 0; t < s.size(); ++t) {
+ const double w = std::abs(signedAreaUv(m, t));
+ wsum += w;
+ if (s[t] < 0.0f) {
+ flipped += w;
+ continue;
+ }
+ sum += w * s[t];
+ st.worst = std::max(st.worst, s[t]);
+ }
+ if (wsum > 0.0) {
+ st.mean = float(sum / wsum);
+ st.flipped = float(flipped / wsum);
+ }
+ return st;
+}
+
+glm::vec3 uvHeatColor(float x) {
+ x = std::clamp(x, -1.0f, 1.0f);
+ const glm::vec3 blue(0.18f, 0.42f, 0.95f), green(0.25f, 0.78f, 0.42f), yellow(0.98f, 0.82f, 0.25f), red(0.93f, 0.26f, 0.22f);
+ if (x < 0.0f) return glm::mix(green, blue, -x);
+ if (x < 0.5f) return glm::mix(green, yellow, x * 2.0f);
+ return glm::mix(yellow, red, (x - 0.5f) * 2.0f);
+}
+
+// ---------------------------------------------------------------------------------------------------------------
+// Selection
+
+const char* uvSelectModeId(UvSelectMode mode) {
+ switch (mode) {
+ case UvSelectMode::Vertex: return "vertex";
+ case UvSelectMode::Edge: return "edge";
+ case UvSelectMode::Face: return "face";
+ case UvSelectMode::Island: return "island";
+ }
+ return "island";
+}
+
+bool parseUvSelectMode(const std::string& id, UvSelectMode& mode) {
+ for (UvSelectMode m : {UvSelectMode::Vertex, UvSelectMode::Edge, UvSelectMode::Face, UvSelectMode::Island})
+ if (id == uvSelectModeId(m) || id == std::string(uvSelectModeId(m)) + "s") {
+ mode = m;
+ return true;
+ }
+ return false;
+}
+
+bool UvSelection::valid(const Mesh& m) const {
+ const bool faceMode = mode == UvSelectMode::Face || mode == UvSelectMode::Island;
+ return faceMode ? faces.size() == m.triangleCount() : corners.size() == m.triangleCount() * 3;
+}
+
+size_t UvSelection::count() const {
+ const bool faceMode = mode == UvSelectMode::Face || mode == UvSelectMode::Island;
+ const std::vector<uint8_t>& v = faceMode ? faces : corners;
+ return size_t(std::count_if(v.begin(), v.end(), [](uint8_t x) { return x != 0; }));
+}
+
+namespace {
+
+// Every corner of every UV vertex marked in `hit` (per UV vertex).
+std::vector<uint32_t> cornersOfUvVertices(const UvTopology& topo, const std::vector<uint8_t>& hit) {
+ std::vector<uint32_t> out;
+ for (uint32_t c = 0; c < topo.uvVertex.size(); ++c)
+ if (hit[topo.uvVertex[c]]) out.push_back(c);
+ return out;
+}
+
+} // namespace
+
+std::vector<uint32_t> uvSelectedCorners(const Mesh& m, const UvTopology& topo, const UvSelection& sel) {
+ const size_t nc = m.triangleCount() * 3;
+ if (!sel.valid(m) || topo.uvVertex.size() != nc) return {};
+ std::vector<uint8_t> hit(topo.uvVertexCount, 0);
+ switch (sel.mode) {
+ case UvSelectMode::Face:
+ case UvSelectMode::Island:
+ for (uint32_t t = 0; t < sel.faces.size(); ++t)
+ if (sel.faces[t])
+ for (uint32_t j = 0; j < 3; ++j) hit[topo.uvVertex[t * 3 + j]] = 1;
+ break;
+ case UvSelectMode::Vertex:
+ for (uint32_t c = 0; c < nc; ++c)
+ if (sel.corners[c]) hit[topo.uvVertex[c]] = 1;
+ break;
+ case UvSelectMode::Edge:
+ for (uint32_t c = 0; c < nc; ++c)
+ if (sel.corners[c]) hit[topo.uvVertex[c]] = hit[topo.uvVertex[cornerNext(c)]] = 1;
+ break;
+ }
+ return cornersOfUvVertices(topo, hit);
+}
+
+std::vector<uint8_t> uvSelectedIslands(const Mesh& m, const UvTopology& topo, const UvSelection& sel, bool allIfEmpty) {
+ std::vector<uint8_t> out(topo.islandCount, 0);
+ if (sel.valid(m)) {
+ if (sel.mode == UvSelectMode::Face || sel.mode == UvSelectMode::Island) {
+ for (uint32_t t = 0; t < sel.faces.size(); ++t)
+ if (sel.faces[t]) out[topo.island[t]] = 1;
+ } else {
+ for (uint32_t c = 0; c < sel.corners.size(); ++c)
+ if (sel.corners[c]) out[topo.island[c / 3]] = 1;
+ }
+ }
+ if (allIfEmpty && std::find(out.begin(), out.end(), uint8_t(1)) == out.end()) std::fill(out.begin(), out.end(), uint8_t(1));
+ return out;
+}
+
+void uvConvertSelection(const Mesh& m, const UvTopology& topo, UvSelection& sel, UvSelectMode to) {
+ const size_t nt = m.triangleCount(), nc = nt * 3;
+ const bool fromFaces = sel.mode == UvSelectMode::Face || sel.mode == UvSelectMode::Island;
+ const bool toFaces = to == UvSelectMode::Face || to == UvSelectMode::Island;
+ if (!sel.valid(m)) {
+ sel.clear();
+ sel.mode = to;
+ return;
+ }
+ if (fromFaces && toFaces) {
+ if (to == UvSelectMode::Island) {
+ const std::vector<uint8_t> isl = uvSelectedIslands(m, topo, sel, false);
+ for (uint32_t t = 0; t < nt; ++t) sel.faces[t] = isl[topo.island[t]];
+ }
+ sel.mode = to;
+ return;
+ }
+ if (fromFaces) { // faces -> their corners (vertex) or their edges (edge)
+ std::vector<uint8_t> corners(nc, 0);
+ if (to == UvSelectMode::Edge) {
+ for (uint32_t t = 0; t < nt; ++t)
+ if (sel.faces[t]) corners[t * 3] = corners[t * 3 + 1] = corners[t * 3 + 2] = 1;
+ } else {
+ for (uint32_t c : uvSelectedCorners(m, topo, sel)) corners[c] = 1;
+ }
+ sel.corners = std::move(corners);
+ std::vector<uint8_t>().swap(sel.faces);
+ sel.mode = to;
+ return;
+ }
+ // Corners -> faces whose three UV vertices are all touched (edge mode: their edges' ends).
+ std::vector<uint8_t> hit(topo.uvVertexCount, 0);
+ for (uint32_t c = 0; c < nc; ++c)
+ if (sel.corners[c]) {
+ hit[topo.uvVertex[c]] = 1;
+ if (sel.mode == UvSelectMode::Edge) hit[topo.uvVertex[cornerNext(c)]] = 1;
+ }
+ if (toFaces) {
+ sel.faces.assign(nt, 0);
+ for (uint32_t t = 0; t < nt; ++t)
+ sel.faces[t] = hit[topo.uvVertex[t * 3]] && hit[topo.uvVertex[t * 3 + 1]] && hit[topo.uvVertex[t * 3 + 2]];
+ std::vector<uint8_t>().swap(sel.corners);
+ sel.mode = UvSelectMode::Face;
+ if (to == UvSelectMode::Island) uvConvertSelection(m, topo, sel, to);
+ return;
+ }
+ std::vector<uint8_t> corners(nc, 0);
+ if (to == UvSelectMode::Vertex) {
+ for (uint32_t c = 0; c < nc; ++c) corners[c] = hit[topo.uvVertex[c]];
+ } else { // vertex -> edge: edges with both ends touched
+ for (uint32_t c = 0; c < nc; ++c) corners[c] = hit[topo.uvVertex[c]] && hit[topo.uvVertex[cornerNext(c)]];
+ }
+ sel.corners = std::move(corners);
+ sel.mode = to;
+}
+
+void uvFacesInRect(const Mesh& m, glm::vec2 lo, glm::vec2 hi, bool touch, std::vector<uint32_t>& out) {
+ out.clear();
+ const size_t nt = m.triangleCount();
+ if (m.uvs.size() != nt * 3) return;
+ const size_t block = 1 << 14, blocks = (nt + block - 1) / block;
+ std::vector<std::vector<uint32_t>> parts(blocks);
+ poolFor(nt, [&](size_t b, size_t e) {
+ std::vector<uint32_t>& part = parts[b / block];
+ for (size_t t = b; t < e; ++t) {
+ const glm::vec2* u = m.uvs.data() + t * 3;
+ if (m.triangleHidden(uint32_t(t))) continue;
+ const glm::vec2 tlo = glm::min(u[0], glm::min(u[1], u[2])), thi = glm::max(u[0], glm::max(u[1], u[2]));
+ const bool inside = touch ? (tlo.x <= hi.x && thi.x >= lo.x && tlo.y <= hi.y && thi.y >= lo.y)
+ : (tlo.x >= lo.x && thi.x <= hi.x && tlo.y >= lo.y && thi.y <= hi.y);
+ if (inside) part.push_back(uint32_t(t));
+ }
+ }, block);
+ for (auto& p : parts) out.insert(out.end(), p.begin(), p.end());
+}
+
+// ---------------------------------------------------------------------------------------------------------------
+// Editing
+
+void uvTransform(std::vector<glm::vec2>& uvs, const std::vector<uint32_t>& corners, const glm::mat2& mat, glm::vec2 pivot,
+ glm::vec2 offset) {
+ poolFor(corners.size(), [&](size_t b, size_t e) {
+ for (size_t i = b; i < e; ++i) {
+ glm::vec2& p = uvs[corners[i]];
+ p = mat * (p - pivot) + pivot + offset;
+ }
+ }, 1 << 15);
+}
+
+glm::vec2 uvCenter(const std::vector<glm::vec2>& uvs, const std::vector<uint32_t>& corners) {
+ if (corners.empty()) return glm::vec2(0.5f);
+ glm::vec2 lo(std::numeric_limits<float>::max()), hi(std::numeric_limits<float>::lowest());
+ for (uint32_t c : corners) {
+ lo = glm::min(lo, uvs[c]);
+ hi = glm::max(hi, uvs[c]);
+ }
+ return (lo + hi) * 0.5f;
+}
+
+namespace {
+std::vector<uint8_t>& ensureFlags(Mesh& m) {
+ if (m.uvFlags.size() != m.triangleCount() * 3) m.uvFlags.assign(m.triangleCount() * 3, 0);
+ return m.uvFlags;
+}
+void dropEmptyFlags(Mesh& m) {
+ if (std::all_of(m.uvFlags.begin(), m.uvFlags.end(), [](uint8_t f) { return f == 0; })) std::vector<uint8_t>().swap(m.uvFlags);
+}
+} // namespace
+
+void uvSetSeams(Mesh& m, const std::vector<uint32_t>& twin, const std::vector<uint32_t>& corners, bool on) {
+ std::vector<uint8_t>& f = ensureFlags(m);
+ for (uint32_t c : corners) {
+ if (c >= f.size()) continue;
+ const uint32_t d = c < twin.size() ? twin[c] : kNoCorner;
+ if (on) {
+ f[c] |= kUvSeam;
+ if (d != kNoCorner) f[d] |= kUvSeam;
+ } else {
+ f[c] &= uint8_t(~kUvSeam);
+ if (d != kNoCorner) f[d] &= uint8_t(~kUvSeam);
+ }
+ }
+ dropEmptyFlags(m);
+ m.facesDirty = true;
+}
+
+size_t uvSeamsFromPolygroups(Mesh& m, const std::vector<uint32_t>& twin) {
+ std::vector<uint32_t> cut;
+ for (uint32_t c = 0; c < twin.size(); ++c)
+ if (twin[c] != kNoCorner && twin[c] > c && m.polygroupAt(c / 3) != m.polygroupAt(twin[c] / 3)) cut.push_back(c);
+ uvSetSeams(m, twin, cut, true);
+ return cut.size();
+}
+
+size_t uvSeamsFromIslands(Mesh& m, const UvTopology& topo) {
+ std::vector<uint32_t> cut;
+ for (uint32_t c = 0; c < topo.twin.size(); ++c)
+ if (topo.border[c] && topo.twin[c] != kNoCorner && topo.twin[c] > c) cut.push_back(c);
+ uvSetSeams(m, topo.twin, cut, true);
+ return cut.size();
+}
+
+size_t uvSeamsFromAngle(Mesh& m, const std::vector<uint32_t>& twin, float degrees) {
+ const float cosLimit = std::cos(glm::radians(std::clamp(degrees, 0.0f, 180.0f)));
+ auto normal = [&](uint32_t t) {
+ const glm::uvec3& tri = m.triangles[t];
+ const glm::vec3 n = glm::cross(m.positions[tri.y] - m.positions[tri.x], m.positions[tri.z] - m.positions[tri.x]);
+ const float l = glm::length(n);
+ return l > 0.0f ? n / l : glm::vec3(0.0f);
+ };
+ std::vector<uint32_t> cut;
+ for (uint32_t c = 0; c < twin.size(); ++c)
+ if (twin[c] != kNoCorner && twin[c] > c && glm::dot(normal(c / 3), normal(twin[c] / 3)) < cosLimit) cut.push_back(c);
+ uvSetSeams(m, twin, cut, true);
+ return cut.size();
+}
+
+size_t uvSeamCount(const Mesh& m) {
+ if (m.uvFlags.size() != m.triangleCount() * 3) return 0;
+ size_t n = 0;
+ for (uint8_t f : m.uvFlags) n += (f & kUvSeam) != 0;
+ return (n + 1) / 2; // (open edges are marked on one side only)
+}
+
+void uvClearSeams(Mesh& m) {
+ if (m.uvFlags.empty()) return;
+ for (uint8_t& f : m.uvFlags) f &= uint8_t(~kUvSeam);
+ dropEmptyFlags(m);
+ m.facesDirty = true;
+}
+
+std::vector<uint32_t> uvFaceSetBorder(const Mesh& m, const std::vector<uint32_t>& twin, const std::vector<uint8_t>& faces) {
+ std::vector<uint32_t> out;
+ if (faces.size() != m.triangleCount()) return out;
+ for (uint32_t c = 0; c < twin.size(); ++c) {
+ if (!faces[c / 3]) continue;
+ const uint32_t d = twin[c];
+ if (d != kNoCorner && !faces[d / 3]) out.push_back(c);
+ }
+ return out;
+}
+
+std::vector<uint32_t> uvEdgePath(const Mesh& m, uint32_t a, uint32_t b) {
+ const size_t nv = m.vertexCount();
+ if (a >= nv || b >= nv || a == b) return {};
+ std::vector<float> dist(nv, std::numeric_limits<float>::max());
+ std::vector<uint32_t> from(nv, ~0u);
+ using Item = std::pair<float, uint32_t>;
+ std::priority_queue<Item, std::vector<Item>, std::greater<>> queue;
+ dist[a] = 0.0f;
+ queue.push({0.0f, a});
+ while (!queue.empty()) {
+ const auto [d, v] = queue.top();
+ queue.pop();
+ if (d > dist[v]) continue;
+ if (v == b) break;
+ for (uint32_t w : m.neighbors(v)) {
+ const float nd = d + glm::length(m.positions[w] - m.positions[v]);
+ if (nd < dist[w]) {
+ dist[w] = nd;
+ from[w] = v;
+ queue.push({nd, w});
+ }
+ }
+ }
+ if (from[b] == ~0u) return {};
+ std::vector<uint32_t> out;
+ for (uint32_t v = b; v != a; v = from[v]) {
+ const uint32_t u = from[v];
+ // A corner that starts the edge u -> v or v -> u.
+ uint32_t corner = kNoCorner;
+ for (uint32_t t : m.vertexTriangles(u)) {
+ for (uint32_t j = 0; j < 3 && corner == kNoCorner; ++j) {
+ const uint32_t x = m.triangles[t][j], y = m.triangles[t][(j + 1) % 3];
+ if ((x == u && y == v) || (x == v && y == u)) corner = t * 3 + j;
+ }
+ if (corner != kNoCorner) break;
+ }
+ if (corner != kNoCorner) out.push_back(corner);
+ }
+ std::reverse(out.begin(), out.end());
+ return out;
+}
+
+void uvSetPins(Mesh& m, const std::vector<uint32_t>& corners, bool on) {
+ std::vector<uint8_t>& f = ensureFlags(m);
+ for (uint32_t c : corners) {
+ if (c >= f.size()) continue;
+ if (on) f[c] |= kUvPin;
+ else f[c] &= uint8_t(~kUvPin);
+ }
+ dropEmptyFlags(m);
+}
+
+size_t uvWeld(Mesh& m, const UvTopology& topo, const std::vector<uint32_t>& corners) {
+ const size_t nc = m.triangleCount() * 3;
+ if (m.uvs.size() != nc || corners.empty()) return 0;
+ std::vector<uint8_t> inSet(nc, 0);
+ for (uint32_t c : corners) inSet[c] = 1;
+ auto vert = [&](uint32_t c) { return m.triangles[c / 3][c % 3]; };
+ // Corners in the set meet across an edge whose both ends are in the set: those become one UV vertex.
+ DisjointSets ds(nc);
+ for (uint32_t c = 0; c < nc; ++c) {
+ if (!topo.border[c] && topo.twin[c] != kNoCorner) { // already connected
+ ds.unite(c, cornerNext(topo.twin[c]));
+ ds.unite(cornerNext(c), topo.twin[c]);
+ }
+ }
+ std::vector<uint32_t> welded; // edges to clear the seam of
+ for (uint32_t c : corners) {
+ const uint32_t d = topo.twin[c];
+ if (d == kNoCorner) continue;
+ const uint32_t n = cornerNext(c);
+ // The edge c -> next(c) has both ends selected, and so does its twin's side.
+ if (!inSet[n] || !inSet[d] || !inSet[cornerNext(d)]) continue;
+ ds.unite(c, cornerNext(d));
+ ds.unite(n, d);
+ welded.push_back(c);
+ }
+ // Only the selected corners' groups are averaged.
+ std::map<uint32_t, std::pair<glm::dvec2, uint32_t>> sums;
+ for (uint32_t c : corners) sums[ds.find(c)];
+ for (uint32_t c = 0; c < nc; ++c) {
+ auto it = sums.find(ds.find(c));
+ if (it == sums.end()) continue;
+ auto& s = it->second;
+ s.first += glm::dvec2(m.uvs[c]);
+ ++s.second;
+ }
+ std::vector<uint32_t> verts;
+ for (uint32_t c = 0; c < nc; ++c) {
+ auto it = sums.find(ds.find(c));
+ if (it == sums.end()) continue;
+ m.uvs[c] = glm::vec2(it->second.first / double(it->second.second));
+ if (inSet[c]) verts.push_back(vert(c));
+ }
+ std::sort(verts.begin(), verts.end());
+ verts.erase(std::unique(verts.begin(), verts.end()), verts.end());
+ if (!welded.empty() && m.uvFlags.size() == nc) uvSetSeams(m, topo.twin, welded, false);
+ m.facesDirty = true;
+ return verts.size();
+}
+
+size_t uvSplit(Mesh& m, const UvTopology& topo, const UvSelection& sel) {
+ if (!sel.valid(m)) return 0;
+ std::vector<uint32_t> cut;
+ if (sel.mode == UvSelectMode::Edge) {
+ for (uint32_t c = 0; c < sel.corners.size(); ++c)
+ if (sel.corners[c] && topo.twin[c] != kNoCorner) cut.push_back(c);
+ } else if (sel.mode == UvSelectMode::Vertex) {
+ // Edges with both ends selected.
+ for (uint32_t c = 0; c < sel.corners.size(); ++c)
+ if (sel.corners[c] && sel.corners[cornerNext(c)] && topo.twin[c] != kNoCorner) cut.push_back(c);
+ } else {
+ cut = uvFaceSetBorder(m, topo.twin, sel.faces);
+ }
+ cut.erase(std::remove_if(cut.begin(), cut.end(), [&](uint32_t c) { return topo.border[c]; }), cut.end());
+ if (cut.empty()) return 0;
+ uvSetSeams(m, topo.twin, cut, true);
+ return cut.size();
+}
+
+size_t uvStraighten(Mesh& m, const UvTopology& topo, const std::vector<uint32_t>& corners) {
+ if (corners.size() < 2 || m.uvs.size() != m.triangleCount() * 3) return 0;
+ std::vector<uint8_t> seen(topo.uvVertexCount, 0);
+ std::vector<glm::vec2> pts;
+ for (uint32_t c : corners)
+ if (!seen[topo.uvVertex[c]]) {
+ seen[topo.uvVertex[c]] = 1;
+ pts.push_back(m.uvs[c]);
+ }
+ if (pts.size() < 2) return 0;
+ glm::dvec2 mean(0.0);
+ for (glm::vec2 p : pts) mean += glm::dvec2(p);
+ mean /= double(pts.size());
+ double sxx = 0, syy = 0;
+ for (glm::vec2 p : pts) {
+ const glm::dvec2 d = glm::dvec2(p) - mean;
+ sxx += d.x * d.x;
+ syy += d.y * d.y;
+ }
+ const bool horizontal = sxx >= syy;
+ for (uint32_t c : corners) {
+ if (horizontal) m.uvs[c].y = float(mean.y);
+ else m.uvs[c].x = float(mean.x);
+ }
+ m.facesDirty = true;
+ return pts.size();
+}
+
+void uvFlipIslands(Mesh& m, const UvTopology& topo, const std::vector<uint8_t>& islands, bool horizontal) {
+ std::vector<uint32_t> offsets, corners;
+ islandCorners(topo, offsets, corners);
+ for (uint32_t i = 0; i < topo.islandCount; ++i) {
+ if (!islands[i]) continue;
+ std::vector<uint32_t> cs(corners.begin() + offsets[i], corners.begin() + offsets[i + 1]);
+ const glm::vec2 c = uvCenter(m.uvs, cs);
+ uvTransform(m.uvs, cs, horizontal ? glm::mat2(-1, 0, 0, 1) : glm::mat2(1, 0, 0, -1), c, glm::vec2(0.0f));
+ }
+ m.facesDirty = true;
+}
+
+size_t uvSetDensity(Mesh& m, const UvTopology& topo, const std::vector<uint8_t>& islands, float density, int resolution) {
+ if (density <= 0.0f) return 0;
+ const std::vector<float> current = uvIslandDensity(m, topo, resolution);
+ std::vector<uint32_t> offsets, corners;
+ islandCorners(topo, offsets, corners);
+ size_t n = 0;
+ for (uint32_t i = 0; i < topo.islandCount; ++i) {
+ if (!islands[i] || current[i] <= 0.0f) continue;
+ std::vector<uint32_t> cs(corners.begin() + offsets[i], corners.begin() + offsets[i + 1]);
+ const float k = density / current[i];
+ uvTransform(m.uvs, cs, glm::mat2(k), uvCenter(m.uvs, cs), glm::vec2(0.0f));
+ ++n;
+ }
+ m.facesDirty = true;
+ return n;
+}
+
+std::vector<TrimStrip> equalTrimStrips(int count) {
+ count = std::clamp(count, 1, 64);
+ std::vector<TrimStrip> out;
+ for (int i = 0; i < count; ++i) {
+ TrimStrip s;
+ // Strip 1 at the top of the texture (v = 1), as trim sheets are drawn.
+ s.v1 = 1.0f - float(i) / float(count);
+ s.v0 = 1.0f - float(i + 1) / float(count);
+ s.name = "Strip " + std::to_string(i + 1);
+ out.push_back(s);
+ }
+ return out;
+}
+
+bool parseTrimStrips(const std::string& text, std::vector<TrimStrip>& out, std::string& error) {
+ out.clear();
+ std::string s;
+ for (char ch : text)
+ if (!std::isspace(static_cast<unsigned char>(ch))) s += ch;
+ if (s.empty()) {
+ error = "No trim strips given";
+ return false;
+ }
+ try {
+ if (s.find_first_of(",;-") == std::string::npos) {
+ const int n = std::stoi(s);
+ if (n < 1 || n > 64) throw std::out_of_range("count");
+ out = equalTrimStrips(n);
+ return true;
+ }
+ if (s.find('-') != std::string::npos) { // v ranges "a-b;c-d"
+ std::stringstream ss(s);
+ std::string part;
+ while (std::getline(ss, part, ';')) {
+ const size_t dash = part.find('-', 1);
+ if (dash == std::string::npos) throw std::invalid_argument("range");
+ TrimStrip st;
+ st.v0 = std::stof(part.substr(0, dash));
+ st.v1 = std::stof(part.substr(dash + 1));
+ if (st.v1 < st.v0) std::swap(st.v0, st.v1);
+ if (st.v0 < 0.0f || st.v1 > 1.0f || st.v1 - st.v0 <= 0.0f) throw std::out_of_range("range");
+ st.name = "Strip " + std::to_string(out.size() + 1);
+ out.push_back(st);
+ }
+ } else { // heights from the top "0.5,0.25,0.25"
+ std::stringstream ss(s);
+ std::string part;
+ std::vector<float> h;
+ while (std::getline(ss, part, ',')) {
+ h.push_back(std::stof(part));
+ if (h.back() <= 0.0f) throw std::out_of_range("height");
+ }
+ float total = 0.0f;
+ for (float x : h) total += x;
+ float top = 1.0f;
+ for (float x : h) {
+ TrimStrip st;
+ st.v1 = top;
+ top -= x / total;
+ st.v0 = std::max(top, 0.0f);
+ st.name = "Strip " + std::to_string(out.size() + 1);
+ out.push_back(st);
+ }
+ }
+ } catch (...) {
+ error = "Trim strips: give a count (4), heights from the top (0.5,0.25,0.25) or v ranges (0-0.5;0.5-1)";
+ out.clear();
+ return false;
+ }
+ if (out.empty()) {
+ error = "No trim strips given";
+ return false;
+ }
+ return true;
+}
+
+size_t uvTrimIslands(Mesh& m, const UvTopology& topo, const std::vector<uint8_t>& islands, const TrimStrip& strip,
+ bool fitWidth, float margin) {
+ if (m.uvs.size() != m.triangleCount() * 3) return 0;
+ const float height = (strip.v1 - strip.v0) - 2.0f * margin;
+ if (height <= 0.0f) return 0;
+ std::vector<uint32_t> offsets, corners;
+ islandCorners(topo, offsets, corners);
+ std::vector<uint32_t> row; // every corner placed, for fitWidth
+ float cursor = 0.0f;
+ size_t n = 0;
+ for (uint32_t i = 0; i < topo.islandCount; ++i) {
+ if (!islands[i]) continue;
+ std::vector<uint32_t> cs(corners.begin() + offsets[i], corners.begin() + offsets[i + 1]);
+ std::vector<glm::vec2> pts;
+ pts.reserve(cs.size());
+ for (uint32_t c : cs) pts.push_back(m.uvs[c]);
+ // Lengthwise along u.
+ const float a = minAreaRectAngle(pts);
+ const float ca = std::cos(a), sa = std::sin(a);
+ glm::vec2 lo(std::numeric_limits<float>::max()), hi(std::numeric_limits<float>::lowest());
+ for (glm::vec2& p : pts) {
+ p = rotate(p, ca, sa);
+ lo = glm::min(lo, p);
+ hi = glm::max(hi, p);
+ }
+ const glm::vec2 size = hi - lo;
+ if (size.y <= 0.0f || size.x <= 0.0f) continue;
+ const float k = height / size.y;
+ for (size_t j = 0; j < cs.size(); ++j)
+ m.uvs[cs[j]] = glm::vec2(cursor + (pts[j].x - lo.x) * k, strip.v0 + margin + (pts[j].y - lo.y) * k);
+ cursor += size.x * k + margin;
+ row.insert(row.end(), cs.begin(), cs.end());
+ ++n;
+ }
+ const float width = cursor - margin;
+ if (fitWidth && width > 0.0f)
+ for (uint32_t c : row) m.uvs[c].x /= width;
+ m.facesDirty = true;
+ return n;
+}
+
+} // namespace sf
diff --git a/src/core/Uv.h b/src/core/Uv.h
new file mode 100644
index 00000000..faf42ecb
--- /dev/null
+++ b/src/core/Uv.h
@@ -0,0 +1,247 @@
+// SculptForge - open source digital sculpting
+// SPDX-License-Identifier: GPL-3.0-or-later
+//
+// UV editing (the UV Editor, app/PanelUvEditor.cpp, and the uv_* commands, core/UvCommands.cpp).
+//
+// UVs are stored per triangle corner (Mesh::uvs). Two corners of the same vertex are one *UV vertex* when an
+// edge between their triangles is connected in UV space: both triangles have the same UVs at both ends of the
+// edge and it isn't a marked seam (Mesh::uvFlags, kUvSeam). *Islands* are the triangles connected that way.
+// Moving a UV vertex moves all of its corners, so islands stay connected while they are edited.
+//
+// Tiles follow the UDIM convention: tile 1001 is u, v in [0, 1), 1002 is u in [1, 2), ten tiles per row, so
+// tile = 1001 + floor(u) + 10 * floor(v).
+//
+// Everything here works on plain arrays and runs on all cores, so it stays interactive on million-triangle
+// meshes; nothing touches the GPU or the UI.
+#pragma once
+
+#include <glm/glm.hpp>
+
+#include <cstdint>
+#include <functional>
+#include <string>
+#include <vector>
+
+namespace sf {
+
+class Mesh;
+
+constexpr uint8_t kUvSeam = 1; // Mesh::uvFlags: the edge from this corner to the next is a marked seam
+constexpr uint8_t kUvPin = 2; // Mesh::uvFlags: this corner's UV is pinned (Unwrap keeps it)
+constexpr uint32_t kNoCorner = ~0u;
+
+inline uint32_t cornerNext(uint32_t c) { return c - c % 3 + (c % 3 + 1) % 3; }
+inline uint32_t cornerPrev(uint32_t c) { return c - c % 3 + (c % 3 + 2) % 3; }
+
+// UDIM tile number of a UV point, and the lower-left corner of a tile.
+int udimTile(const glm::vec2& uv);
+glm::vec2 udimOrigin(int tile);
+
+// Per corner c (the edge from c to cornerNext(c)): the corner of the other triangle that starts the same edge
+// the other way round, or kNoCorner on an open or non-manifold edge. Depends on the triangles only.
+std::vector<uint32_t> cornerTwins(const Mesh& mesh);
+
+// UV connectivity of a mesh with UVs (see the top of this file).
+struct UvTopology {
+ std::vector<uint32_t> twin; // cornerTwins
+ std::vector<uint32_t> uvVertex; // per corner: its UV vertex
+ uint32_t uvVertexCount = 0;
+ std::vector<uint32_t> island; // per triangle: its island (0 .. islandCount - 1)
+ uint32_t islandCount = 0;
+ std::vector<uint32_t> islandOffsets, islandTriangles; // triangles of island i: [offsets[i], offsets[i + 1])
+ std::vector<uint8_t> border; // per corner: its edge is an island border (seam, open edge or UV split)
+ bool connected(uint32_t corner) const { return !border[corner]; }
+};
+// `twin` may be passed in (cornerTwins of the same triangles) to save its computation.
+UvTopology buildUvTopology(const Mesh& mesh, std::vector<uint32_t> twin = {});
+
+// --- Measures ---
+
+// Texel density: texels per unit of surface length for a `resolution`-texel texture (the UVs' square root of
+// the area ratio). Per triangle (0 for degenerate ones), and per island (its area-weighted mean).
+void uvTriangleDensity(const Mesh& mesh, int resolution, std::vector<float>& out);
+std::vector<float> uvIslandDensity(const Mesh& mesh, const UvTopology& topo, int resolution);
+// The texel density of the whole mesh (total UV area over total surface area).
+float uvMeshDensity(const Mesh& mesh, int resolution);
+
+// Stretch of each triangle's mapping from the surface to UV space, from the singular values s1 >= s2 of its
+// Jacobian, measured against its island's mean scale: 0 = no stretch, 1 = twice or half as long in some
+// direction (log2 of the worst of s1 and 1/s2 over the mean). Triangles folded over their island get -1.
+void uvTriangleStretch(const Mesh& mesh, std::vector<float>& out);
+// Summary for the status line and the tests: area-weighted mean stretch, and the share of flipped triangles.
+struct UvStretchStats {
+ float mean = 0.0f, worst = 0.0f;
+ float flipped = 0.0f; // fraction of the UV area
+};
+UvStretchStats uvStretchStats(const Mesh& mesh);
+// Heat map colour (sRGB 0..1) of x in [-1, 1]: blue (-1, too few texels / compressed) through green (0) to red
+// (1, too many / stretched).
+glm::vec3 uvHeatColor(float x);
+
+// --- Selection ---
+
+enum class UvSelectMode { Vertex, Edge, Face, Island };
+const char* uvSelectModeId(UvSelectMode mode); // "vertex", "edge", "face", "island"
+bool parseUvSelectMode(const std::string& id, UvSelectMode& mode);
+
+// What the UV Editor has selected, on the active mesh: faces (Face and Island modes) or corners (Vertex mode: the
+// corners of the selected UV vertices; Edge mode: the corners that start the selected edges). Sizes that don't
+// match the mesh mean nothing is selected.
+struct UvSelection {
+ UvSelectMode mode = UvSelectMode::Island;
+ std::vector<uint8_t> faces; // per triangle
+ std::vector<uint8_t> corners; // per corner
+ void clear() {
+ std::vector<uint8_t>().swap(faces);
+ std::vector<uint8_t>().swap(corners);
+ }
+ bool valid(const Mesh& mesh) const;
+ size_t count() const; // selected faces or corners
+ bool empty() const { return count() == 0; }
+};
+
+// The corners the selection moves: every corner of every UV vertex it touches (all corners of the selected
+// faces in the face modes). Sorted.
+std::vector<uint32_t> uvSelectedCorners(const Mesh& mesh, const UvTopology& topo, const UvSelection& sel);
+// The islands the selection touches (all of them when `allIfEmpty` and nothing is selected), as flags.
+std::vector<uint8_t> uvSelectedIslands(const Mesh& mesh, const UvTopology& topo, const UvSelection& sel, bool allIfEmpty);
+// Grows face / corner flags so every element of a touched island is selected (Island mode), or converts the
+// selection between modes (the elements of the selected ones).
+void uvConvertSelection(const Mesh& mesh, const UvTopology& topo, UvSelection& sel, UvSelectMode to);
+// Faces whose UV triangle lies in (or crosses, `touch`) the rectangle lo..hi; used by box select.
+void uvFacesInRect(const Mesh& mesh, glm::vec2 lo, glm::vec2 hi, bool touch, std::vector<uint32_t>& out);
+
+// --- Editing ---
+
+// Moves `corners` by the affine map p -> m * (p - pivot) + pivot + offset.
+void uvTransform(std::vector<glm::vec2>& uvs, const std::vector<uint32_t>& corners, const glm::mat2& m, glm::vec2 pivot,
+ glm::vec2 offset);
+// Bounding box centre of `corners`.
+glm::vec2 uvCenter(const std::vector<glm::vec2>& uvs, const std::vector<uint32_t>& corners);
+
+// Marks (`on`) or clears the seam on the edges starting at `corners`, on both sides of each edge.
+void uvSetSeams(Mesh& mesh, const std::vector<uint32_t>& twin, const std::vector<uint32_t>& corners, bool on);
+// Seam presets: every polygroup border, every current island border, edges sharper than `degrees`.
+size_t uvSeamsFromPolygroups(Mesh& mesh, const std::vector<uint32_t>& twin);
+size_t uvSeamsFromIslands(Mesh& mesh, const UvTopology& topo);
+size_t uvSeamsFromAngle(Mesh& mesh, const std::vector<uint32_t>& twin, float degrees);
+size_t uvSeamCount(const Mesh& mesh); // marked edges (each counted once)
+void uvClearSeams(Mesh& mesh);
+// The corners on the border of the face set `faces` (edges whose other side isn't in it).
+std::vector<uint32_t> uvFaceSetBorder(const Mesh& mesh, const std::vector<uint32_t>& twin, const std::vector<uint8_t>& faces);
+// The shortest edge path from vertex `a` to vertex `b` over the surface, as the corners that start its edges
+// (empty when they aren't connected). For marking seams by clicking along a loop in 3D.
+std::vector<uint32_t> uvEdgePath(const Mesh& mesh, uint32_t a, uint32_t b);
+
+// Pins (`on`) or unpins `corners`.
+void uvSetPins(Mesh& mesh, const std::vector<uint32_t>& corners, bool on);
+
+// Weld: every mesh vertex among `corners` gets one UV (the average of its corners there) and the edges between
+// them lose their seams. Returns the vertices welded.
+size_t uvWeld(Mesh& mesh, const UvTopology& topo, const std::vector<uint32_t>& corners);
+// Split: the border of the selected faces (Face / Island modes), the selected edges (Edge mode) or the edges
+// between selected vertices (Vertex mode) become seams, so the faces can move apart. Returns the edges cut.
+size_t uvSplit(Mesh& mesh, const UvTopology& topo, const UvSelection& sel);
+// Straighten: the selected UV vertices (an edge loop, say) line up on one horizontal or vertical line (whichever
+// is closer to how they run), keeping their order along it. Returns the vertices moved.
+size_t uvStraighten(Mesh& mesh, const UvTopology& topo, const std::vector<uint32_t>& corners);
+// Flip the islands in `islands` in u (horizontal) or v about their centres.
+void uvFlipIslands(Mesh& mesh, const UvTopology& topo, const std::vector<uint8_t>& islands, bool horizontal);
+
+// Texel density: scales each island in `islands` about its centre to `density` texels per unit (at
+// `resolution`). Returns the islands scaled.
+size_t uvSetDensity(Mesh& mesh, const UvTopology& topo, const std::vector<uint8_t>& islands, float density, int resolution);
+
+// Trim sheets: horizontal strips of the texture, each a band of v (in the tile 0..1). Islands assigned to a strip
+// are turned lengthwise, scaled to the strip's height (less `margin` on each side, in UV units) and laid side
+// by side along u from 0; with `fitWidth` the row is then squeezed or stretched in u to fill 0..1 exactly,
+// otherwise it keeps its proportions (and may run past 1: trim textures repeat in u).
+struct TrimStrip {
+ float v0 = 0.0f, v1 = 0.25f;
+ std::string name;
+};
+// "4" (four equal strips), "0.5,0.25,0.25" (heights from the top, normalised), or "0-0.5;0.5-0.75" (v ranges).
+bool parseTrimStrips(const std::string& text, std::vector<TrimStrip>& out, std::string& error);
+std::vector<TrimStrip> equalTrimStrips(int count);
+size_t uvTrimIslands(Mesh& mesh, const UvTopology& topo, const std::vector<uint8_t>& islands, const TrimStrip& strip,
+ bool fitWidth, float margin);
+
+// --- Packing (core/UvPack.cpp) ---
+
+struct UvPackOptions {
+ int resolution = 2048; // texture size the margin is measured in
+ float marginPx = 8.0f; // texels between islands (and half of it at tile borders)
+ bool rotate = true; // turn islands to their smallest bounding box and allow 90-degree turns
+ int tiles = 1; // UDIM tiles to fill (1001, 1002, ... ten per row); ignored with `density`
+ bool equalDensity = true; // scale islands to one texel density first (off: keep their relative sizes)
+ float density = 0.0f; // > 0: keep exactly this texel density (texels per unit) and use as many tiles as
+ // it takes (up to 100) instead of fitting `tiles`
+ int firstTile = 1001; // where packing starts
+};
+struct UvPackResult {
+ size_t islands = 0;
+ int tilesUsed = 0;
+ float coverage = 0.0f; // UV area of the islands over the area of the tiles used
+ float density = 0.0f; // texel density after packing (the mean)
+};
+// Packs the islands in `islands` (all when empty) of `mesh` per `options`. Islands not packed stay where they
+// are (and may then overlap the packed ones). False with `error` when nothing could be packed.
+bool uvPack(Mesh& mesh, const UvTopology& topo, const std::vector<uint8_t>& islands, const UvPackOptions& options,
+ UvPackResult& result, std::string& error);
+
+// Lower-level packing of rectangles into unit tiles (exposed for the tests): sizes in, positions and 90-degree
+// turns out; returns the tiles used (0 when something doesn't fit even alone). Rectangles already include
+// their margin; `border` is kept free along each tile edge.
+int packRectangles(const std::vector<glm::vec2>& sizes, int maxTiles, bool allowTurn, float border,
+ std::vector<glm::vec2>& positions, std::vector<uint8_t>& turned, std::vector<int>& tile);
+
+// --- Unwrapping (core/UvUnwrap.cpp) ---
+
+enum class UvUnwrapMethod {
+ Auto, // xatlas: finds its own seams (core/AutoUv.h)
+ Conformal, // LSCM: angle-preserving, cut along the marked seams
+ Isometric, // LSCM then as-rigid-as-possible: keeps lengths too (least stretch), along the marked seams
+ Polygroups, // Isometric, cut along the polygroup borders as well as the marked seams
+ Planar, // each piece projected along its mean normal
+ Unfold, // the current islands flattened again in place (Isometric, honouring pins)
+};
+const char* uvUnwrapMethodId(UvUnwrapMethod m); // auto, conformal, isometric, polygroups, planar, unfold
+const char* uvUnwrapMethodLabel(UvUnwrapMethod m);
+bool parseUvUnwrapMethod(const std::string& id, UvUnwrapMethod& m);
+
+struct UvUnwrapOptions {
+ UvUnwrapMethod method = UvUnwrapMethod::Isometric;
+ int resolution = 2048;
+ int iterations = 10; // as-rigid-as-possible steps (Isometric, Polygroups, Unfold)
+ bool pack = true; // pack the new islands (UvPackOptions below); off for Unfold (fitted in place)
+ UvPackOptions packing;
+ const std::vector<uint8_t>* faces = nullptr; // only these triangles (null: all); the rest keep their UVs and
+ // the new islands are fitted where the old ones were
+};
+struct UvUnwrapResult {
+ std::vector<glm::vec2> uvs; // the mesh's new UVs (every corner)
+ size_t islands = 0; // pieces flattened
+ size_t extraCuts = 0; // edges cut automatically so closed or looped pieces could flatten
+ UvPackResult packing;
+};
+using UvProgress = std::function<bool(float fraction)>; // false: cancel
+// Unwraps `mesh` (its UVs, seams and pins are read; nothing is written). False with `error` on failure or cancel.
+bool uvUnwrap(const Mesh& mesh, const UvUnwrapOptions& options, UvUnwrapResult& result, std::string& error,
+ const UvProgress& progress = {});
+
+// The flattening solvers on their own (for the tests): `positions` / `triangles` form one piece that must be
+// a topological disk. Pinned vertices (`pins`, with their UVs in `uv`) stay; with fewer than two, two are chosen.
+// `uv` holds a starting guess when its size matches. Returns false if the piece isn't a disk.
+bool flattenConformal(const std::vector<glm::vec3>& positions, const std::vector<glm::uvec3>& triangles,
+ std::vector<glm::vec2>& uv, const std::vector<uint32_t>& pins = {});
+bool flattenIsometric(const std::vector<glm::vec3>& positions, const std::vector<glm::uvec3>& triangles,
+ std::vector<glm::vec2>& uv, int iterations, const std::vector<uint32_t>& pins = {});
+
+// --- Commands (core/UvCommands.cpp) ---
+
+class CommandRegistry;
+void registerUvCommands(CommandRegistry& registry); // uv_unwrap, uv_pack, uv_seam, uv_select, uv_transform, ...
+// One line about a mesh's UVs (islands, seams, pins, density, tiles, stretch), as uv_info prints it.
+std::string uvInfoText(const Mesh& mesh, int resolution);
+
+} // namespace sf
diff --git a/src/core/UvCommands.cpp b/src/core/UvCommands.cpp
new file mode 100644
index 00000000..125f57b3
--- /dev/null
+++ b/src/core/UvCommands.cpp
@@ -0,0 +1,519 @@
+// SculptForge - open source digital sculpting
+// SPDX-License-Identifier: GPL-3.0-or-later
+//
+// uv_* commands: the UV Editor's operations (app/PanelUvEditor.cpp) for scripts, the CLI, Python and the AI
+// assistant. Each is one undo step holding the old UVs and seams (UvUndo) and, when a painted texture is moved
+// onto the new layout (keep_texture), the texture too (core/TextureTransfer.h). Operations that work on "the
+// selection" use the UV Editor's (Document::uvSelection, set with uv_select) and the whole Part when nothing is
+// selected.
+#include "core/Commands.h"
+#include "core/Texture.h"
+#include "core/TextureTransfer.h"
+#include "core/Undo.h"
+#include "core/Uv.h"
+
+#include <algorithm>
+#include <cmath>
+#include <cstdio>
+
+namespace sf {
+
+namespace {
+
+using T = ParamSpec::Type;
+
+const char* kNoUvs = "The Part has no UVs: unwrap it first (UV Editor > Unwrap, or uv_unwrap)";
+
+// One undoable UV edit: captures the UVs (and the texture when it should follow) before, pushes the step after.
+class UvEdit {
+public:
+ UvEdit(Document& doc, std::string label, bool keepTexture) : doc_(doc), tex_(keepTexture && hasTexture(doc.mesh)) {
+ if (tex_) r_ = captureTexture(doc.mesh, label);
+ else r_.label = std::move(label);
+ r_.uv = UvUndo::capture(doc.mesh);
+ }
+ // Pushes the step if anything changed; returns the texture note (" ; paint moved ...").
+ std::string commit() {
+ Mesh& m = doc_.mesh;
+ if (m.uvs == r_.uv->uvs && m.uvFlags == r_.uv->flags) {
+ if (tex_) r_.texture->swapWith(m); // (put back the untouched original)
+ return {};
+ }
+ std::string note;
+ if (tex_ && m.uvs.size() == r_.uv->uvs.size() && m.uvs != r_.uv->uvs) {
+ std::vector<glm::vec2> fresh = std::move(m.uvs);
+ m.uvs = r_.uv->uvs;
+ note = setUvsKeepingTexture(m, std::move(fresh), true);
+ }
+ m.facesDirty = true;
+ r_.uv->commit(m);
+ if (tex_) finishTextureUndo(r_, m);
+ doc_.undo.push(std::move(r_));
+ return note;
+ }
+
+private:
+ Document& doc_;
+ bool tex_;
+ UndoRecord r_;
+};
+
+int resolutionArg(const Document& doc, const Args& a) {
+ if (a.contains("resolution")) return std::clamp(int(argNumber(a, "resolution", kDefaultTextureSize)), 64, 16384);
+ return doc.mesh.texture ? std::max(doc.mesh.texture->width, doc.mesh.texture->height) : kDefaultTextureSize;
+}
+
+std::string fmt(const char* f, double x) {
+ char buf[64];
+ std::snprintf(buf, sizeof buf, f, x);
+ return buf;
+}
+
+std::string plural(size_t n, const char* word) { return std::to_string(n) + " " + word + (n == 1 ? "" : "s"); }
+
+// The islands to work on: the selection's, or every island when nothing is selected.
+std::vector<uint8_t> targetIslands(const Document& doc, const UvTopology& topo) {
+ return uvSelectedIslands(doc.mesh, topo, doc.uvSelection, true);
+}
+
+// The corners to move: the selection's, or every corner.
+std::vector<uint32_t> targetCorners(const Document& doc, const UvTopology& topo) {
+ if (doc.uvSelection.valid(doc.mesh) && !doc.uvSelection.empty()) return uvSelectedCorners(doc.mesh, topo, doc.uvSelection);
+ std::vector<uint32_t> all(doc.mesh.uvs.size());
+ for (uint32_t c = 0; c < all.size(); ++c) all[c] = c;
+ return all;
+}
+
+UvPackOptions packOptions(const Document& doc, const Args& a) {
+ UvPackOptions o;
+ o.resolution = resolutionArg(doc, a);
+ o.marginPx = float(std::clamp(argNumber(a, "margin", 8.0), 0.0, 256.0));
+ o.rotate = argBool(a, "rotate", true);
+ o.tiles = std::clamp(int(argNumber(a, "tiles", 1)), 1, 100);
+ o.equalDensity = argBool(a, "equal_density", true);
+ o.density = float(std::max(argNumber(a, "density", 0.0), 0.0));
+ o.firstTile = std::clamp(int(argNumber(a, "first_tile", 1001)), 1001, 1100);
+ return o;
+}
+
+std::string packNote(const UvPackResult& p) {
+ std::string s = plural(p.islands, "island") + " packed";
+ if (p.tilesUsed > 1) s += " into " + std::to_string(p.tilesUsed) + " UDIM tiles";
+ s += ", " + fmt("%.0f", double(p.coverage) * 100.0) + "% of the space used, " + fmt("%.1f", double(p.density)) +
+ " texels per unit";
+ return s;
+}
+
+} // namespace
+
+std::string uvInfoText(const Mesh& m, int resolution) {
+ if (!m.hasUvs()) {
+ const size_t seams = uvSeamCount(m);
+ return "No UVs" + (seams ? "; " + plural(seams, "seam edge") + " marked" : std::string());
+ }
+ const UvTopology topo = buildUvTopology(m);
+ size_t pins = 0;
+ for (uint8_t f : m.uvFlags) pins += (f & kUvPin) != 0;
+ std::vector<int> tiles;
+ for (uint32_t i = 0; i < topo.islandCount; ++i) {
+ const uint32_t t = topo.islandTriangles[topo.islandOffsets[i]];
+ const glm::vec2 c = (m.uvs[t * 3] + m.uvs[t * 3 + 1] + m.uvs[t * 3 + 2]) / 3.0f;
+ tiles.push_back(udimTile(c));
+ }
+ std::sort(tiles.begin(), tiles.end());
+ tiles.erase(std::unique(tiles.begin(), tiles.end()), tiles.end());
+ const UvStretchStats st = uvStretchStats(m);
+ std::string s = plural(topo.islandCount, "island") + ", " + plural(uvSeamCount(m), "seam edge") + ", " +
+ plural(pins, "pinned corner") + "; " + fmt("%.1f", double(uvMeshDensity(m, resolution))) +
+ " texels per unit at " + std::to_string(resolution) + "; tiles";
+ for (int t : tiles) s += " " + std::to_string(t);
+ s += "; stretch " + fmt("%.3f", double(st.mean)) + " mean, " + fmt("%.2f", double(st.flipped) * 100.0) + "% flipped";
+ return s;
+}
+
+void registerUvCommands(CommandRegistry& reg) {
+ reg.add({"uv_unwrap",
+ "Unwrap the active Part's UVs (UV Editor > Unwrap). Methods: isometric (least stretch: angles and lengths, "
+ "along the marked seams; the default), conformal (LSCM: angles, along the seams), polygroups (cut along "
+ "the polygroup borders and the seams), planar (each piece projected flat), unfold (flatten the current "
+ "islands again in place, keeping pinned corners), auto (finds its own seams, xatlas). Pieces that are "
+ "closed or looped get extra cuts. The result is packed into the 0-1 tile, or across UDIM tiles. With a UV "
+ "selection only the selected faces are unwrapped (fitted where they were). A painted texture moves onto "
+ "the new UVs (keep_texture). One undo step.",
+ {{"method", T::String, "isometric (default), conformal, polygroups, planar, unfold or auto", false},
+ {"selected", T::Bool, "Only the UV Editor's selected faces (default true when something is selected)", false},
+ {"iterations", T::Number, "Least-stretch refinement steps (default 10; 0 = conformal)", false},
+ {"resolution", T::Number, "Texture size the margin is measured in (default: the texture's, or 2048)", false},
+ {"margin", T::Number, "Texels between packed islands (default 8)", false},
+ {"tiles", T::Number, "UDIM tiles to pack across (default 1)", false},
+ {"rotate", T::Bool, "Turn islands to fit better when packing (default true)", false},
+ {"density", T::Number, "Pack at exactly this texel density (texels per unit; uses as many tiles as needed)", false},
+ {"pack", T::Bool, "Pack the result (default true; false fits each island where its old UVs were)", false},
+ {"keep_texture", T::Bool, "Move a painted texture onto the new UVs (default true)", false}},
+ [](Document& doc, const Args& a) -> CommandResult {
+ Mesh& m = doc.mesh;
+ if (m.triangleCount() == 0) return {false, "There is no mesh to unwrap"};
+ UvUnwrapOptions o;
+ if (a.contains("method") && !parseUvUnwrapMethod(argString(a, "method"), o.method))
+ return {false, "method must be isometric, conformal, polygroups, planar, unfold or auto"};
+ o.resolution = resolutionArg(doc, a);
+ o.iterations = std::clamp(int(argNumber(a, "iterations", 10)), 0, 100);
+ o.packing = packOptions(doc, a);
+ o.pack = argBool(a, "pack", o.method != UvUnwrapMethod::Unfold);
+ const bool haveSel = doc.uvSelection.valid(m) && !doc.uvSelection.empty();
+ std::vector<uint8_t> faces;
+ if (argBool(a, "selected", haveSel) && haveSel && m.hasUvs()) {
+ const UvTopology topo = buildUvTopology(m);
+ faces.assign(m.triangleCount(), 0);
+ const std::vector<uint32_t> corners = uvSelectedCorners(m, topo, doc.uvSelection);
+ if (doc.uvSelection.mode == UvSelectMode::Face || doc.uvSelection.mode == UvSelectMode::Island) {
+ faces = doc.uvSelection.faces;
+ } else {
+ for (uint32_t c : corners) faces[c / 3] = 1;
+ }
+ o.faces = &faces;
+ }
+ UvUnwrapResult r;
+ std::string err;
+ if (!uvUnwrap(m, o, r, err)) return {false, err};
+ UvEdit edit(doc, std::string("Unwrap (") + uvUnwrapMethodLabel(o.method) + ")", argBool(a, "keep_texture", true));
+ m.uvs = std::move(r.uvs);
+ const std::string note = edit.commit();
+ std::string msg = std::string("Unwrapped (") + uvUnwrapMethodLabel(o.method) + "): " + plural(r.islands, "island");
+ if (r.extraCuts) msg += ", " + plural(r.extraCuts, "edge") + " cut automatically to flatten closed pieces";
+ if (r.packing.tilesUsed > 1) msg += ", " + std::to_string(r.packing.tilesUsed) + " UDIM tiles";
+ const UvStretchStats st = uvStretchStats(m);
+ msg += "; stretch " + fmt("%.3f", double(st.mean));
+ return {true, msg + note};
+ }});
+
+ reg.add({"uv_pack",
+ "Pack the active Part's UV islands (the selected ones, or all) into the 0-1 tile or across UDIM tiles: "
+ "each island turned to its smallest box, scaled to one texel density (equal_density) and laid out with a "
+ "margin, as large as fits. With density, keeps that texel density and uses as many tiles as it needs. "
+ "One undo step; a painted texture moves with the islands (keep_texture).",
+ {{"margin", T::Number, "Texels between islands (default 8)", false},
+ {"resolution", T::Number, "Texture size the margin and density are measured in (default: the texture's, or 2048)", false},
+ {"rotate", T::Bool, "Turn islands to fit better (default true)", false},
+ {"tiles", T::Number, "UDIM tiles to fill, 1001 onwards (default 1)", false},
+ {"first_tile", T::Number, "The UDIM tile to start at (default 1001)", false},
+ {"equal_density", T::Bool, "Scale islands to one texel density first (default true; false keeps their sizes relative)", false},
+ {"density", T::Number, "Keep exactly this texel density (texels per unit) and spill into more tiles", false},
+ {"keep_texture", T::Bool, "Move a painted texture with the islands (default true)", false}},
+ [](Document& doc, const Args& a) -> CommandResult {
+ Mesh& m = doc.mesh;
+ if (!m.hasUvs()) return {false, kNoUvs};
+ const UvTopology topo = buildUvTopology(m);
+ const std::vector<uint8_t> islands = targetIslands(doc, topo);
+ UvEdit edit(doc, "Pack UVs", argBool(a, "keep_texture", true));
+ UvPackResult r;
+ std::string err;
+ if (!uvPack(m, topo, islands, packOptions(doc, a), r, err)) return {false, err};
+ const std::string note = edit.commit();
+ return {true, packNote(r) + note};
+ }});
+
+ reg.add({"uv_seam",
+ "Mark or clear UV seams on the active Part (seams are where Unwrap cuts). op: mark / clear (the UV "
+ "Editor's selected edges, or the border of its selected faces), path (mark the shortest edge path from "
+ "vertex `from` to vertex `to`; clear=true clears it), polygroups (every polygroup border), islands (every "
+ "current UV island border), angle (edges sharper than `angle` degrees), clear_all. One undo step.",
+ {{"op", T::String, "mark, clear, path, polygroups, islands, angle or clear_all", true},
+ {"from", T::Number, "path: the vertex to start at", false},
+ {"to", T::Number, "path: the vertex to end at", false},
+ {"clear", T::Bool, "path: clear the seams along it instead of marking them", false},
+ {"angle", T::Number, "angle: the dihedral angle in degrees above which edges become seams (default 60)", false}},
+ [](Document& doc, const Args& a) -> CommandResult {
+ Mesh& m = doc.mesh;
+ if (m.triangleCount() == 0) return {false, "There is no mesh"};
+ const std::string op = argString(a, "op");
+ const size_t before = uvSeamCount(m);
+ UvEdit edit(doc, "UV Seams", false);
+ const std::vector<uint32_t> twin = cornerTwins(m);
+ if (op == "mark" || op == "clear") {
+ const UvSelection& sel = doc.uvSelection;
+ if (!sel.valid(m) || sel.empty()) return {false, "Select edges or faces in the UV Editor first"};
+ std::vector<uint32_t> corners;
+ if (sel.mode == UvSelectMode::Edge) {
+ for (uint32_t c = 0; c < sel.corners.size(); ++c)
+ if (sel.corners[c]) corners.push_back(c);
+ } else if (sel.mode == UvSelectMode::Vertex) {
+ for (uint32_t c = 0; c < sel.corners.size(); ++c)
+ if (sel.corners[c] && sel.corners[cornerNext(c)]) corners.push_back(c);
+ } else {
+ corners = uvFaceSetBorder(m, twin, sel.faces);
+ }
+ uvSetSeams(m, twin, corners, op == "mark");
+ } else if (op == "path") {
+ const double from = argNumber(a, "from", -1), to = argNumber(a, "to", -1);
+ if (from < 0 || to < 0 || from >= double(m.vertexCount()) || to >= double(m.vertexCount()))
+ return {false, "Give the path's `from` and `to` vertices (0-" + std::to_string(m.vertexCount() - 1) + ")"};
+ const std::vector<uint32_t> path = uvEdgePath(m, uint32_t(from), uint32_t(to));
+ if (path.empty()) return {false, "Those vertices aren't connected"};
+ uvSetSeams(m, twin, path, !argBool(a, "clear", false));
+ } else if (op == "polygroups") {
+ uvSeamsFromPolygroups(m, twin);
+ } else if (op == "islands") {
+ if (!m.hasUvs()) return {false, kNoUvs};
+ uvSeamsFromIslands(m, buildUvTopology(m, twin));
+ } else if (op == "angle") {
+ uvSeamsFromAngle(m, twin, float(argNumber(a, "angle", 60.0)));
+ } else if (op == "clear_all") {
+ uvClearSeams(m);
+ } else {
+ return {false, "op must be mark, clear, path, polygroups, islands, angle or clear_all"};
+ }
+ edit.commit();
+ const size_t after = uvSeamCount(m);
+ return {true, plural(after, "seam edge") + " (" + (after >= before ? "+" : "-") +
+ std::to_string(after >= before ? after - before : before - after) + ")"};
+ }});
+
+ reg.add({"uv_select",
+ "Set the UV Editor's selection on the active Part (what the other uv_* commands work on). op: all, none, "
+ "invert, island (the island of triangle `face`), face (triangle `face`), polygroup (every face of polygroup "
+ "`group`), rect (faces touching u0 v0 u1 v1), seams (the marked seam edges), mode (just switch to `mode`). "
+ "`mode` (vertex, edge, face, island) converts the selection; `add` adds to it instead of replacing it.",
+ {{"op", T::String, "all, none, invert, island, face, polygroup, rect, seams or mode", true},
+ {"mode", T::String, "vertex, edge, face or island", false},
+ {"face", T::Number, "island / face: a triangle index", false},
+ {"group", T::Number, "polygroup: its id", false},
+ {"u0", T::Number, "rect: lower u", false},
+ {"v0", T::Number, "rect: lower v", false},
+ {"u1", T::Number, "rect: upper u", false},
+ {"v1", T::Number, "rect: upper v", false},
+ {"add", T::Bool, "Add to the selection (default false)", false}},
+ [](Document& doc, const Args& a) -> CommandResult {
+ Mesh& m = doc.mesh;
+ if (!m.hasUvs()) return {false, kNoUvs};
+ UvSelection& sel = doc.uvSelection;
+ const UvTopology topo = buildUvTopology(m);
+ if (!sel.valid(m)) {
+ const UvSelectMode mode = sel.mode;
+ sel.clear();
+ sel.mode = mode;
+ }
+ if (a.contains("mode")) {
+ UvSelectMode mode;
+ if (!parseUvSelectMode(argString(a, "mode"), mode)) return {false, "mode must be vertex, edge, face or island"};
+ uvConvertSelection(m, topo, sel, mode);
+ }
+ const size_t nt = m.triangleCount();
+ const bool faceMode = sel.mode == UvSelectMode::Face || sel.mode == UvSelectMode::Island;
+ if (faceMode && sel.faces.size() != nt) sel.faces.assign(nt, 0);
+ if (!faceMode && sel.corners.size() != nt * 3) sel.corners.assign(nt * 3, 0);
+ const std::string op = argString(a, "op");
+ const bool add = argBool(a, "add", false);
+ // Faces picked by the op, converted to the mode.
+ auto pickFaces = [&](const std::vector<uint8_t>& faces) {
+ UvSelection pick;
+ pick.mode = UvSelectMode::Face;
+ pick.faces = faces;
+ uvConvertSelection(m, topo, pick, sel.mode);
+ std::vector<uint8_t>& dst = faceMode ? sel.faces : sel.corners;
+ const std::vector<uint8_t>& src = faceMode ? pick.faces : pick.corners;
+ if (!add) std::fill(dst.begin(), dst.end(), uint8_t(0));
+ for (size_t i = 0; i < src.size(); ++i) dst[i] = dst[i] || src[i];
+ };
+ std::vector<uint8_t>& flags = faceMode ? sel.faces : sel.corners;
+ if (op == "all") {
+ std::fill(flags.begin(), flags.end(), uint8_t(1));
+ } else if (op == "none") {
+ std::fill(flags.begin(), flags.end(), uint8_t(0));
+ } else if (op == "invert") {
+ for (uint8_t& f : flags) f = !f;
+ } else if (op == "island" || op == "face") {
+ const double f = argNumber(a, "face", -1);
+ if (f < 0 || f >= double(nt)) return {false, "Give `face`, a triangle index (0-" + std::to_string(nt - 1) + ")"};
+ std::vector<uint8_t> faces(nt, 0);
+ if (op == "island") {
+ const uint32_t isl = topo.island[uint32_t(f)];
+ for (uint32_t k = topo.islandOffsets[isl]; k < topo.islandOffsets[isl + 1]; ++k) faces[topo.islandTriangles[k]] = 1;
+ } else {
+ faces[uint32_t(f)] = 1;
+ }
+ pickFaces(faces);
+ } else if (op == "polygroup") {
+ const uint32_t g = uint32_t(std::max(argNumber(a, "group", 0), 0.0));
+ std::vector<uint8_t> faces(nt, 0);
+ for (uint32_t t = 0; t < nt; ++t) faces[t] = m.polygroupAt(t) == g;
+ pickFaces(faces);
+ } else if (op == "rect") {
+ const glm::vec2 p0(float(argNumber(a, "u0", 0)), float(argNumber(a, "v0", 0)));
+ const glm::vec2 p1(float(argNumber(a, "u1", 1)), float(argNumber(a, "v1", 1)));
+ std::vector<uint32_t> list;
+ uvFacesInRect(m, glm::min(p0, p1), glm::max(p0, p1), true, list);
+ std::vector<uint8_t> faces(nt, 0);
+ for (uint32_t t : list) faces[t] = 1;
+ pickFaces(faces);
+ } else if (op == "seams") {
+ uvConvertSelection(m, topo, sel, UvSelectMode::Edge);
+ sel.corners.assign(nt * 3, 0);
+ if (m.uvFlags.size() == nt * 3)
+ for (uint32_t c = 0; c < nt * 3; ++c) sel.corners[c] = (m.uvFlags[c] & kUvSeam) != 0;
+ } else if (op != "mode") {
+ return {false, "op must be all, none, invert, island, face, polygroup, rect, seams or mode"};
+ }
+ if (sel.mode == UvSelectMode::Island) uvConvertSelection(m, topo, sel, UvSelectMode::Island);
+ const size_t n = sel.count();
+ const char* what = sel.mode == UvSelectMode::Vertex ? "corner" : sel.mode == UvSelectMode::Edge ? "edge" : "face";
+ const std::vector<uint8_t> touched = uvSelectedIslands(m, topo, sel, false);
+ const size_t islands = size_t(std::count(touched.begin(), touched.end(), uint8_t(1)));
+ return {true, std::string("UV selection (") + uvSelectModeId(sel.mode) + "s): " + plural(n, what) + " in " +
+ plural(islands, "island")};
+ }});
+
+ reg.add({"uv_transform",
+ "Move, rotate and scale the UV Editor's selection (or every UV of the active Part when nothing is "
+ "selected) about its centre. One undo step; a painted texture follows the surface (keep_texture).",
+ {{"move_u", T::Number, "Offset in u", false},
+ {"move_v", T::Number, "Offset in v", false},
+ {"rotate", T::Number, "Degrees, counter-clockwise", false},
+ {"scale", T::Number, "Uniform scale (default 1)", false},
+ {"scale_u", T::Number, "Scale in u (times scale)", false},
+ {"scale_v", T::Number, "Scale in v (times scale)", false},
+ {"keep_texture", T::Bool, "Move a painted texture with the UVs, so the model looks the same (default true)", false}},
+ [](Document& doc, const Args& a) -> CommandResult {
+ Mesh& m = doc.mesh;
+ if (!m.hasUvs()) return {false, kNoUvs};
+ const UvTopology topo = buildUvTopology(m);
+ const std::vector<uint32_t> corners = targetCorners(doc, topo);
+ const float s = float(argNumber(a, "scale", 1.0));
+ const float su = s * float(argNumber(a, "scale_u", 1.0)), sv = s * float(argNumber(a, "scale_v", 1.0));
+ const float ang = glm::radians(float(argNumber(a, "rotate", 0.0)));
+ const glm::mat2 rot(std::cos(ang), std::sin(ang), -std::sin(ang), std::cos(ang));
+ const glm::mat2 mat = rot * glm::mat2(su, 0.0f, 0.0f, sv);
+ UvEdit edit(doc, "Transform UVs", argBool(a, "keep_texture", true));
+ uvTransform(m.uvs, corners, mat, uvCenter(m.uvs, corners),
+ glm::vec2(float(argNumber(a, "move_u", 0.0)), float(argNumber(a, "move_v", 0.0))));
+ const std::string note = edit.commit();
+ return {true, "Transformed " + plural(corners.size(), "UV corner") + note};
+ }});
+
+ reg.add({"uv_edit",
+ "UV Editor operations on its selection (the whole Part when nothing is selected, where that makes sense). "
+ "op: pin / unpin (selected corners keep their UVs on Unfold), clear_pins, weld (selected vertices, or the "
+ "edges between them, become one UV each, removing the seam), split (the selected edges, or the border of "
+ "the selected faces, become seams), straighten (selected vertices line up horizontally or vertically), "
+ "flip_u / flip_v (mirror the selected islands). One undo step.",
+ {{"op", T::String, "pin, unpin, clear_pins, weld, split, straighten, flip_u or flip_v", true},
+ {"keep_texture", T::Bool, "Move a painted texture with the UVs (default true)", false}},
+ [](Document& doc, const Args& a) -> CommandResult {
+ Mesh& m = doc.mesh;
+ if (!m.hasUvs()) return {false, kNoUvs};
+ const std::string op = argString(a, "op");
+ const UvTopology topo = buildUvTopology(m);
+ const bool haveSel = doc.uvSelection.valid(m) && !doc.uvSelection.empty();
+ const std::vector<uint32_t> corners = targetCorners(doc, topo);
+ UvEdit edit(doc, "UV " + op, argBool(a, "keep_texture", true));
+ std::string msg;
+ if (op == "pin" || op == "unpin") {
+ if (!haveSel) return {false, "Select the UVs to " + op + " first"};
+ uvSetPins(m, corners, op == "pin");
+ msg = (op == "pin" ? "Pinned " : "Unpinned ") + plural(corners.size(), "corner");
+ } else if (op == "clear_pins") {
+ std::vector<uint32_t> all(m.uvs.size());
+ for (uint32_t c = 0; c < all.size(); ++c) all[c] = c;
+ uvSetPins(m, all, false);
+ msg = "Cleared every pin";
+ } else if (op == "weld") {
+ if (!haveSel) return {false, "Select the vertices or edges to weld first"};
+ msg = "Welded " + plural(uvWeld(m, topo, corners), "vertex");
+ } else if (op == "split") {
+ if (!haveSel) return {false, "Select the edges or faces to split off first"};
+ msg = "Split along " + plural(uvSplit(m, topo, doc.uvSelection), "edge");
+ } else if (op == "straighten") {
+ if (!haveSel) return {false, "Select the vertices to straighten first (an edge loop)"};
+ msg = "Straightened " + plural(uvStraighten(m, topo, corners), "UV vertex");
+ } else if (op == "flip_u" || op == "flip_v") {
+ uvFlipIslands(m, topo, targetIslands(doc, topo), op == "flip_u");
+ msg = op == "flip_u" ? "Flipped horizontally" : "Flipped vertically";
+ } else {
+ return {false, "op must be pin, unpin, clear_pins, weld, split, straighten, flip_u or flip_v"};
+ }
+ return {true, msg + edit.commit()};
+ }});
+
+ reg.add({"uv_density",
+ "Texel density of the active Part's UV islands (the selected ones, or all), in texels per unit at the "
+ "texture's resolution. op: set (scale them to `value`), match (scale them all to their mean, or to the "
+ "first selected island's with match=first), info. One undo step.",
+ {{"op", T::String, "set, match or info", true},
+ {"value", T::Number, "set: texels per unit", false},
+ {"match", T::String, "match: mean (default) or first", false},
+ {"resolution", T::Number, "Texture size (default: the texture's, or 2048)", false},
+ {"keep_texture", T::Bool, "Move a painted texture with the UVs (default true)", false}},
+ [](Document& doc, const Args& a) -> CommandResult {
+ Mesh& m = doc.mesh;
+ if (!m.hasUvs()) return {false, kNoUvs};
+ const int res = resolutionArg(doc, a);
+ const UvTopology topo = buildUvTopology(m);
+ const std::vector<uint8_t> islands = targetIslands(doc, topo);
+ const std::vector<float> d = uvIslandDensity(m, topo, res);
+ double sum = 0.0, area = 0.0;
+ float lo = 1e30f, hi = 0.0f;
+ int first = -1;
+ for (uint32_t i = 0; i < topo.islandCount; ++i) {
+ if (!islands[i] || d[i] <= 0.0f) continue;
+ if (first < 0) first = int(i);
+ const double w = double(topo.islandOffsets[i + 1] - topo.islandOffsets[i]);
+ sum += double(d[i]) * w, area += w;
+ lo = std::min(lo, d[i]), hi = std::max(hi, d[i]);
+ }
+ if (area <= 0.0) return {false, "The islands have no area"};
+ const float mean = float(sum / area);
+ const std::string op = argString(a, "op");
+ if (op == "info")
+ return {true, "Texel density at " + std::to_string(res) + ": " + fmt("%.1f", double(mean)) + " mean, " +
+ fmt("%.1f", double(lo)) + " - " + fmt("%.1f", double(hi)) + " texels per unit"};
+ float target = 0.0f;
+ if (op == "set") target = float(argNumber(a, "value", 0.0));
+ else if (op == "match") target = argString(a, "match", "mean") == "first" ? d[size_t(first)] : mean;
+ else return {false, "op must be set, match or info"};
+ if (!(target > 0.0f)) return {false, "Give the texel density: value (texels per unit)"};
+ UvEdit edit(doc, "Texel Density", argBool(a, "keep_texture", true));
+ const size_t n = uvSetDensity(m, topo, islands, target, res);
+ const std::string note = edit.commit();
+ return {true, plural(n, "island") + " at " + fmt("%.1f", double(target)) + " texels per unit" + note};
+ }});
+
+ reg.add({"uv_trim",
+ "Trim sheets: lay the selected UV islands (or all) into one horizontal strip of the texture. Each island "
+ "is turned lengthwise and scaled to the strip's height, and they line up along u from 0 (fit_width "
+ "squeezes the row to 0-1; otherwise it keeps its proportions and may run past 1, as trim textures repeat "
+ "in u). The texture stays put (keep_texture is off by default: the islands pick up the strip's look).",
+ {{"strip", T::Number, "Which strip, 1 = the top one (default 1)", false},
+ {"strips", T::String, "The sheet: a count (4, the default), heights from the top (0.5,0.25,0.25), or v ranges (0-0.5;0.5-1)", false},
+ {"fit_width", T::Bool, "Fit the row to u 0-1 exactly (default false)", false},
+ {"margin", T::Number, "Texels kept free above and below inside the strip (default 4)", false},
+ {"resolution", T::Number, "Texture size the margin is measured in", false},
+ {"keep_texture", T::Bool, "Move a painted texture with the islands (default false)", false}},
+ [](Document& doc, const Args& a) -> CommandResult {
+ Mesh& m = doc.mesh;
+ if (!m.hasUvs()) return {false, kNoUvs};
+ std::vector<TrimStrip> strips;
+ std::string err;
+ const std::string spec = a.contains("strips") ? argString(a, "strips", "") : "4";
+ if (!parseTrimStrips(spec.empty() ? std::to_string(int(argNumber(a, "strips", 4))) : spec, strips, err))
+ return {false, err};
+ const int k = int(argNumber(a, "strip", 1));
+ if (k < 1 || k > int(strips.size())) return {false, "strip must be 1-" + std::to_string(strips.size())};
+ const UvTopology topo = buildUvTopology(m);
+ const std::vector<uint8_t> islands = targetIslands(doc, topo);
+ const float margin = float(std::max(argNumber(a, "margin", 4.0), 0.0)) / float(resolutionArg(doc, a));
+ UvEdit edit(doc, "Trim Sheet", argBool(a, "keep_texture", false));
+ const size_t n = uvTrimIslands(m, topo, islands, strips[size_t(k - 1)], argBool(a, "fit_width", false), margin);
+ if (!n) return {false, "Nothing to lay into the strip (it may be too thin for the margin)"};
+ const std::string note = edit.commit();
+ const TrimStrip& s = strips[size_t(k - 1)];
+ return {true, plural(n, "island") + " in " + s.name + " (v " + fmt("%.3f", double(s.v0)) + " - " +
+ fmt("%.3f", double(s.v1)) + ")" + note};
+ }});
+
+ reg.add({"uv_info",
+ "Describe the active Part's UVs: islands, seams, pins, texel density, the UDIM tiles used, stretch.",
+ {{"resolution", T::Number, "Texture size for the texel density (default: the texture's, or 2048)", false}},
+ [](Document& doc, const Args& a) -> CommandResult { return {true, uvInfoText(doc.mesh, resolutionArg(doc, a))}; }});
+}
+
+} // namespace sf
diff --git a/src/core/UvInternal.h b/src/core/UvInternal.h
new file mode 100644
index 00000000..327f7d1a
--- /dev/null
+++ b/src/core/UvInternal.h
@@ -0,0 +1,53 @@
+// SculptForge - open source digital sculpting
+// SPDX-License-Identifier: GPL-3.0-or-later
+//
+// Helpers shared by core/Uv.cpp, core/UvPack.cpp and core/UvUnwrap.cpp.
+#pragma once
+
+#include "core/Uv.h"
+
+#include <glm/glm.hpp>
+
+#include <numeric>
+#include <vector>
+
+namespace sf::uvdetail {
+
+inline float cross2(glm::vec2 a, glm::vec2 b) { return a.x * b.y - a.y * b.x; }
+
+// Union-find over [0, n) with path halving.
+struct DisjointSets {
+ std::vector<uint32_t> parent;
+ explicit DisjointSets(size_t n) : parent(n) { std::iota(parent.begin(), parent.end(), 0u); }
+ uint32_t find(uint32_t x) {
+ while (parent[x] != x) x = parent[x] = parent[parent[x]];
+ return x;
+ }
+ void unite(uint32_t a, uint32_t b) {
+ a = find(a), b = find(b);
+ if (a != b) parent[std::max(a, b)] = std::min(a, b);
+ }
+ // Compact labels 0..count-1 per element (in order of first appearance); returns the count.
+ uint32_t labels(std::vector<uint32_t>& out) {
+ out.assign(parent.size(), ~0u);
+ std::vector<uint32_t> id(parent.size(), ~0u);
+ uint32_t n = 0;
+ for (uint32_t i = 0; i < parent.size(); ++i) {
+ const uint32_t r = find(i);
+ if (id[r] == ~0u) id[r] = n++;
+ out[i] = id[r];
+ }
+ return n;
+ }
+};
+
+// Convex hull (counter-clockwise, no repeated first point) of `pts`.
+std::vector<glm::vec2> convexHull(std::vector<glm::vec2> pts);
+// The rotation (radians) that turns `pts` to their smallest-area bounding box, with the long side along u.
+float minAreaRectAngle(const std::vector<glm::vec2>& pts);
+inline glm::vec2 rotate(glm::vec2 p, float c, float s) { return {c * p.x - s * p.y, s * p.x + c * p.y}; }
+
+// The corners of each island, grouped: corners of island i are [offsets[i], offsets[i + 1]) of `corners`.
+void islandCorners(const UvTopology& topo, std::vector<uint32_t>& offsets, std::vector<uint32_t>& corners);
+
+} // namespace sf::uvdetail
diff --git a/src/core/UvPack.cpp b/src/core/UvPack.cpp
new file mode 100644
index 00000000..e786d724
--- /dev/null
+++ b/src/core/UvPack.cpp
@@ -0,0 +1,260 @@
+// SculptForge - open source digital sculpting
+// SPDX-License-Identifier: GPL-3.0-or-later
+//
+// Island packing (UV Editor > Pack, uv_pack): each island turned to its smallest bounding box, scaled to one texel
+// density (or kept as it is), and its box packed with a skyline packer into one tile or across UDIM tiles. The
+// scale is the largest that fits (found by bisection), or a fixed texel density that spills into as many tiles as
+// it needs.
+#include "core/Mesh.h"
+#include "core/ThreadPool.h"
+#include "core/Uv.h"
+#include "core/UvInternal.h"
+
+#include <algorithm>
+#include <cmath>
+#include <limits>
+#include <numeric>
+
+namespace sf {
+
+using namespace uvdetail;
+
+namespace {
+
+// Skyline of one unit tile: segments [x, x + w) at height y, left to right, covering [border, 1 - border].
+struct Skyline {
+ struct Segment {
+ float x, y, w;
+ };
+ std::vector<Segment> segs;
+ float border = 0.0f;
+ explicit Skyline(float b) : border(b) { segs.push_back({b, b, 1.0f - 2.0f * b}); }
+
+ // Lowest place for a w x h box: the top it would reach, and where (false when it doesn't fit).
+ bool find(float w, float h, float& bestTop, float& bestX, size_t& bestIndex) const {
+ bool found = false;
+ const float right = 1.0f - border + 1e-6f, top = 1.0f - border + 1e-6f;
+ for (size_t i = 0; i < segs.size(); ++i) {
+ const float x = segs[i].x;
+ if (x + w > right) break;
+ float y = 0.0f, covered = 0.0f;
+ for (size_t j = i; j < segs.size() && covered < w; ++j) {
+ y = std::max(y, segs[j].y);
+ covered = segs[j].x + segs[j].w - x;
+ }
+ if (covered + 1e-6f < w || y + h > top) continue;
+ if (!found || y + h < bestTop - 1e-7f || (y + h <= bestTop + 1e-7f && x < bestX)) {
+ found = true;
+ bestTop = y + h;
+ bestX = x;
+ bestIndex = i;
+ }
+ }
+ return found;
+ }
+ void place(size_t i, float w, float topY) {
+ const float x = segs[i].x, end = x + w;
+ std::vector<Segment> out;
+ out.reserve(segs.size() + 2);
+ out.insert(out.end(), segs.begin(), segs.begin() + std::ptrdiff_t(i));
+ out.push_back({x, topY, w});
+ for (size_t j = i; j < segs.size(); ++j) {
+ const float sEnd = segs[j].x + segs[j].w;
+ if (sEnd <= end + 1e-7f) continue;
+ if (segs[j].x < end) out.push_back({end, segs[j].y, sEnd - end});
+ else out.push_back(segs[j]);
+ }
+ // Merge neighbours at the same height.
+ segs.clear();
+ for (const Segment& s : out) {
+ if (!segs.empty() && std::abs(segs.back().y - s.y) < 1e-7f) segs.back().w = s.x + s.w - segs.back().x;
+ else segs.push_back(s);
+ }
+ }
+};
+
+} // namespace
+
+int packRectangles(const std::vector<glm::vec2>& sizes, int maxTiles, bool allowTurn, float border,
+ std::vector<glm::vec2>& positions, std::vector<uint8_t>& turned, std::vector<int>& tile) {
+ const size_t n = sizes.size();
+ positions.assign(n, glm::vec2(0.0f));
+ turned.assign(n, 0);
+ tile.assign(n, 0);
+ if (n == 0) return 1;
+ std::vector<uint32_t> order(n);
+ std::iota(order.begin(), order.end(), 0u);
+ // Tallest first (by the longer side when turning is allowed).
+ std::sort(order.begin(), order.end(), [&](uint32_t a, uint32_t b) {
+ const float ka = allowTurn ? std::max(sizes[a].x, sizes[a].y) : sizes[a].y;
+ const float kb = allowTurn ? std::max(sizes[b].x, sizes[b].y) : sizes[b].y;
+ return ka > kb || (ka == kb && a < b);
+ });
+ std::vector<Skyline> tiles;
+ tiles.emplace_back(border);
+ for (uint32_t r : order) {
+ glm::vec2 s = sizes[r];
+ // With turning, boxes lie down (wide) first: that suits a skyline.
+ bool turn = allowTurn && s.y > s.x;
+ bool placed = false;
+ for (size_t t = 0; !placed; ++t) {
+ if (t == tiles.size()) {
+ if (int(t) >= maxTiles) return 0;
+ tiles.emplace_back(border);
+ }
+ float bestTop = 0, bestX = 0;
+ size_t bestI = 0;
+ bool any = false, bestTurn = turn;
+ for (int k = 0; k < (allowTurn ? 2 : 1); ++k) {
+ const bool tr = k == 0 ? turn : !turn;
+ const glm::vec2 d = tr ? glm::vec2(s.y, s.x) : s;
+ float top = 0, x = 0;
+ size_t i = 0;
+ if (tiles[t].find(d.x, d.y, top, x, i) && (!any || top < bestTop - 1e-7f)) {
+ any = true;
+ bestTop = top, bestX = x, bestI = i, bestTurn = tr;
+ }
+ }
+ if (!any) {
+ if (t + 1 == tiles.size() && tiles[t].segs.size() == 1 && tiles[t].segs[0].y == border) return 0; // too big
+ continue;
+ }
+ const glm::vec2 d = bestTurn ? glm::vec2(s.y, s.x) : s;
+ positions[r] = glm::vec2(bestX, bestTop - d.y);
+ turned[r] = bestTurn;
+ tile[r] = int(t);
+ tiles[t].place(bestI, d.x, bestTop);
+ placed = true;
+ }
+ }
+ return int(tiles.size());
+}
+
+bool uvPack(Mesh& m, const UvTopology& topo, const std::vector<uint8_t>& islands, const UvPackOptions& o,
+ UvPackResult& result, std::string& error) {
+ result = UvPackResult();
+ const size_t nt = m.triangleCount();
+ if (m.uvs.size() != nt * 3 || topo.island.size() != nt) {
+ error = "The Part has no UVs to pack";
+ return false;
+ }
+ std::vector<uint32_t> list;
+ for (uint32_t i = 0; i < topo.islandCount; ++i)
+ if (islands.empty() || (i < islands.size() && islands[i])) list.push_back(i);
+ if (list.empty()) {
+ error = "No islands to pack";
+ return false;
+ }
+ std::vector<uint32_t> offsets, corners;
+ islandCorners(topo, offsets, corners);
+ const int res = std::clamp(o.resolution, 64, 16384);
+ const size_t n = list.size();
+ struct Piece {
+ float angle = 0.0f, k = 1.0f;
+ glm::vec2 lo{0.0f}, size{0.0f}; // rotated, before scaling by k
+ double area3 = 0.0, areaUv = 0.0;
+ };
+ std::vector<Piece> pieces(n);
+ poolFor(n, [&](size_t b, size_t e) {
+ for (size_t p = b; p < e; ++p) {
+ const uint32_t i = list[p];
+ Piece& pc = pieces[p];
+ for (uint32_t k = topo.islandOffsets[i]; k < topo.islandOffsets[i + 1]; ++k) {
+ const uint32_t t = topo.islandTriangles[k];
+ const glm::uvec3& tri = m.triangles[t];
+ pc.area3 += 0.5 * double(glm::length(glm::cross(m.positions[tri.y] - m.positions[tri.x], m.positions[tri.z] - m.positions[tri.x])));
+ const glm::vec2* u = m.uvs.data() + size_t(t) * 3;
+ pc.areaUv += 0.5 * std::abs(double(cross2(u[1] - u[0], u[2] - u[0])));
+ }
+ std::vector<glm::vec2> pts;
+ pts.reserve(offsets[i + 1] - offsets[i]);
+ for (uint32_t c = offsets[i]; c < offsets[i + 1]; ++c) pts.push_back(m.uvs[corners[c]]);
+ pc.angle = o.rotate ? minAreaRectAngle(pts) : 0.0f;
+ const float ca = std::cos(pc.angle), sa = std::sin(pc.angle);
+ glm::vec2 lo(std::numeric_limits<float>::max()), hi(std::numeric_limits<float>::lowest());
+ for (const glm::vec2& q : pts) {
+ const glm::vec2 r = rotate(q, ca, sa);
+ lo = glm::min(lo, r);
+ hi = glm::max(hi, r);
+ }
+ pc.lo = lo;
+ pc.size = glm::max(hi - lo, glm::vec2(0.0f));
+ const bool equal = o.equalDensity || o.density > 0.0f;
+ pc.k = equal && pc.areaUv > 1e-20 && pc.area3 > 0.0 ? float(std::sqrt(pc.area3 / pc.areaUv)) : 1.0f;
+ }
+ }, 16);
+ const float margin = std::max(o.marginPx, 0.0f) / float(res);
+ std::vector<glm::vec2> sizes(n), pos;
+ std::vector<uint8_t> turned;
+ std::vector<int> tileOf;
+ auto tryScale = [&](float s, int maxTiles) {
+ for (size_t p = 0; p < n; ++p) sizes[p] = pieces[p].size * pieces[p].k * s + glm::vec2(margin);
+ return packRectangles(sizes, maxTiles, o.rotate, 0.0f, pos, turned, tileOf);
+ };
+ float scale = 1.0f;
+ int used = 0;
+ if (o.density > 0.0f) {
+ scale = o.density / float(res); // UV units per surface unit
+ used = tryScale(scale, 100);
+ if (!used) {
+ error = "At that texel density an island is bigger than a tile (or it needs over 100 tiles): lower it";
+ return false;
+ }
+ } else {
+ const int tiles = std::clamp(o.tiles, 1, 100);
+ double boxes = 0.0;
+ for (const Piece& pc : pieces) boxes += double(pc.size.x * pc.k) * double(pc.size.y * pc.k);
+ if (boxes <= 0.0) {
+ error = "The islands have no area to pack";
+ return false;
+ }
+ float hi = float(std::sqrt(double(tiles) / boxes)), lo = 0.0f;
+ // The largest scale that fits, by bisection (lo always fits once found).
+ float fits = 0.0f;
+ for (int it = 0; it < 30 && fits == 0.0f; ++it) {
+ const float s = hi * std::pow(0.7f, float(it));
+ if (tryScale(s, tiles)) fits = s;
+ }
+ if (fits == 0.0f) {
+ error = "The islands don't fit: lower the margin or use more tiles";
+ return false;
+ }
+ lo = fits;
+ hi = std::min(hi, fits / 0.7f);
+ for (int it = 0; it < 14; ++it) {
+ const float mid = 0.5f * (lo + hi);
+ if (tryScale(mid, tiles)) lo = mid;
+ else hi = mid;
+ }
+ scale = lo;
+ used = tryScale(scale, tiles);
+ }
+ // Place: rotate, scale, move into the box (inset by half the margin), then into its tile.
+ const int columns = 10;
+ const int first = std::max(o.firstTile, 1001) - 1001;
+ poolFor(n, [&](size_t b, size_t e) {
+ for (size_t p = b; p < e; ++p) {
+ const uint32_t i = list[p];
+ const Piece& pc = pieces[p];
+ const float ca = std::cos(pc.angle), sa = std::sin(pc.angle), k = pc.k * scale;
+ const int t = first + tileOf[p];
+ const glm::vec2 origin(float(t % columns), float(t / columns));
+ const glm::vec2 box = pc.size * k;
+ for (uint32_t c = offsets[i]; c < offsets[i + 1]; ++c) {
+ glm::vec2 q = (rotate(m.uvs[corners[c]], ca, sa) - pc.lo) * k;
+ if (turned[p]) q = glm::vec2(box.y - q.y, q.x); // a quarter turn, staying in the box
+ m.uvs[corners[c]] = origin + pos[p] + glm::vec2(margin * 0.5f) + q;
+ }
+ }
+ }, 16);
+ double uvArea = 0.0;
+ for (size_t p = 0; p < n; ++p) uvArea += pieces[p].areaUv * double(pieces[p].k * scale) * double(pieces[p].k * scale);
+ result.islands = n;
+ result.tilesUsed = used;
+ result.coverage = float(uvArea / double(std::max(used, 1)));
+ result.density = uvMeshDensity(m, res);
+ m.facesDirty = true;
+ return true;
+}
+
+} // namespace sf
diff --git a/src/core/UvUnwrap.cpp b/src/core/UvUnwrap.cpp
new file mode 100644
index 00000000..8a4d20fa
--- /dev/null
+++ b/src/core/UvUnwrap.cpp
@@ -0,0 +1,929 @@
+// SculptForge - open source digital sculpting
+// SPDX-License-Identifier: GPL-3.0-or-later
+//
+// Unwrapping (UV Editor > Unwrap, uv_unwrap):
+//
+// 1. The surface is cut into pieces along the marked seams (with Polygroups, the polygroup borders too; Unfold
+// keeps the current islands). Without marked seams, a mesh that has UVs is cut along its island borders.
+// 2. A piece that isn't a topological disk (a closed shell, a tube, a handle) gets extra cuts: the edges no dual
+// spanning tree crosses, pruned back to the loops that matter; a closed shell is first split across its middle.
+// 3. Each piece is flattened: LSCM (least-squares conformal maps, Levy et al. 2002) solved by conjugate gradients
+// with an aggregation multigrid (core/QRemesh2Solver.h), or, for big pieces of Least Stretch, a Tutte embedding
+// (faster to solve); Least Stretch then refines it with as-rigid-as-possible local / global steps (Liu et al.
+// 2008), so lengths are kept as well as angles.
+// 4. The pieces are scaled to one texel density and packed (core/UvPack.cpp), or, for Unfold and for a
+// selection, fitted back where their old UVs were.
+//
+// Pieces are solved in parallel (big ones with parallel matrix products), so a million-triangle mesh unwraps in
+// seconds rather than minutes.
+#include "core/AutoUv.h"
+#include "core/QRemesh2Solver.h"
+#include "core/Mesh.h"
+#include "core/ThreadPool.h"
+#include "core/Uv.h"
+#include "core/UvInternal.h"
+
+#include <algorithm>
+#include <array>
+#include <complex>
+#include <memory>
+#include <atomic>
+#include <cmath>
+#include <limits>
+#include <mutex>
+#include <numeric>
+#include <queue>
+
+namespace sf {
+
+using namespace uvdetail;
+
+const char* uvUnwrapMethodId(UvUnwrapMethod m) {
+ switch (m) {
+ case UvUnwrapMethod::Auto: return "auto";
+ case UvUnwrapMethod::Conformal: return "conformal";
+ case UvUnwrapMethod::Isometric: return "isometric";
+ case UvUnwrapMethod::Polygroups: return "polygroups";
+ case UvUnwrapMethod::Planar: return "planar";
+ case UvUnwrapMethod::Unfold: return "unfold";
+ }
+ return "isometric";
+}
+
+const char* uvUnwrapMethodLabel(UvUnwrapMethod m) {
+ switch (m) {
+ case UvUnwrapMethod::Auto: return "Auto Seams";
+ case UvUnwrapMethod::Conformal: return "Conformal (LSCM)";
+ case UvUnwrapMethod::Isometric: return "Least Stretch";
+ case UvUnwrapMethod::Polygroups: return "By Polygroups";
+ case UvUnwrapMethod::Planar: return "Planar";
+ case UvUnwrapMethod::Unfold: return "Unfold Islands";
+ }
+ return "";
+}
+
+bool parseUvUnwrapMethod(const std::string& id, UvUnwrapMethod& m) {
+ for (UvUnwrapMethod x : {UvUnwrapMethod::Auto, UvUnwrapMethod::Conformal, UvUnwrapMethod::Isometric,
+ UvUnwrapMethod::Polygroups, UvUnwrapMethod::Planar, UvUnwrapMethod::Unfold})
+ if (id == uvUnwrapMethodId(x)) {
+ m = x;
+ return true;
+ }
+ if (id == "lscm" || id == "angle") return m = UvUnwrapMethod::Conformal, true;
+ if (id == "arap" || id == "stretch" || id == "least_stretch") return m = UvUnwrapMethod::Isometric, true;
+ if (id == "xatlas") return m = UvUnwrapMethod::Auto, true;
+ return false;
+}
+
+namespace {
+
+
+// ---------------------------------------------------------------------------------------------------------------
+// Sparse symmetric systems for one piece
+
+template <class F>
+void rowsFor(size_t n, bool parallel, F&& f) {
+ if (parallel) poolFor(n, [&](size_t b, size_t e) { f(b, e); }, 1 << 12);
+ else f(size_t(0), n);
+}
+
+// The triangle in its own plane: corners at (0,0), (l1,0), (x2,y2). False when degenerate.
+bool localTriangle(const glm::vec3& p0, const glm::vec3& p1, const glm::vec3& p2, glm::dvec2 q[3]) {
+ const glm::dvec3 e1 = glm::dvec3(p1 - p0), e2 = glm::dvec3(p2 - p0);
+ const double l1 = glm::length(e1);
+ const glm::dvec3 n = glm::cross(e1, e2);
+ const double nl = glm::length(n);
+ if (l1 <= 0.0 || nl <= 1e-30) return false;
+ const glm::dvec3 x = e1 / l1, y = glm::cross(n / nl, x);
+ q[0] = glm::dvec2(0.0);
+ q[1] = glm::dvec2(l1, 0.0);
+ q[2] = glm::dvec2(glm::dot(e2, x), glm::dot(e2, y));
+ return true;
+}
+
+// Planar projection along the piece's mean normal (right-handed, so the layout isn't mirrored).
+std::vector<glm::vec2> project(const std::vector<glm::vec3>& pos, const std::vector<glm::uvec3>& tris) {
+ glm::dvec3 n(0.0), centre(0.0);
+ double area = 0.0;
+ for (const glm::uvec3& t : tris) {
+ const glm::dvec3 c = glm::cross(glm::dvec3(pos[t.y] - pos[t.x]), glm::dvec3(pos[t.z] - pos[t.x]));
+ n += c;
+ area += glm::length(c);
+ }
+ for (const glm::vec3& p : pos) centre += glm::dvec3(p);
+ centre /= double(std::max<size_t>(pos.size(), 1));
+ if (glm::length(n) < 1e-3 * area || area <= 0.0) {
+ // A closed piece: project along its thinnest direction instead (the smallest spread).
+ glm::dvec3 lo(1e300), hi(-1e300);
+ for (const glm::vec3& p : pos) lo = glm::min(lo, glm::dvec3(p)), hi = glm::max(hi, glm::dvec3(p));
+ const glm::dvec3 d = hi - lo;
+ n = d.x <= d.y && d.x <= d.z ? glm::dvec3(1, 0, 0) : d.y <= d.z ? glm::dvec3(0, 1, 0) : glm::dvec3(0, 0, 1);
+ }
+ n = glm::normalize(n);
+ const glm::dvec3 helper = std::abs(n.z) < 0.9 ? glm::dvec3(0, 0, 1) : glm::dvec3(1, 0, 0);
+ const glm::dvec3 x = glm::normalize(glm::cross(helper, n)), y = glm::cross(n, x);
+ std::vector<glm::vec2> out(pos.size());
+ for (size_t i = 0; i < pos.size(); ++i) {
+ const glm::dvec3 d = glm::dvec3(pos[i]) - centre;
+ out[i] = glm::vec2(float(glm::dot(d, x)), float(glm::dot(d, y)));
+ }
+ return out;
+}
+
+// Two vertices far apart on the piece (its extremes along its longest axis).
+void autoPins(const std::vector<glm::vec3>& pos, uint32_t& a, uint32_t& b) {
+ glm::vec3 lo(std::numeric_limits<float>::max()), hi(std::numeric_limits<float>::lowest());
+ for (const glm::vec3& p : pos) lo = glm::min(lo, p), hi = glm::max(hi, p);
+ const glm::vec3 d = hi - lo;
+ const int axis = d.x >= d.y && d.x >= d.z ? 0 : d.y >= d.z ? 1 : 2;
+ a = b = 0;
+ for (uint32_t i = 0; i < pos.size(); ++i) {
+ if (pos[i][axis] < pos[a][axis]) a = i;
+ if (pos[i][axis] > pos[b][axis]) b = i;
+ }
+}
+
+// Solves the free unknowns of A x = rhs (A from `trips` over all `n` unknowns, Hermitian positive semidefinite)
+// with the `fixed` ones held at their values in x: A_ff x_f = rhs_f - A_fp x_p, by CG preconditioned with an
+// aggregation multigrid (core/QRemesh2Solver.h): a few dozen iterations where Jacobi took thousands.
+template <class S>
+struct PinnedSystem {
+ std::vector<uint32_t> freeIndex; // unknown -> free index (~0u = fixed)
+ std::vector<uint32_t> freeList;
+ qr2::SparseMatrix<S> A;
+ std::vector<std::pair<uint64_t, S>> coupling; // (free row << 32 | fixed unknown, value)
+ std::unique_ptr<qr2::Multigrid<S>> mg;
+
+ void build(size_t n, const std::vector<uint8_t>& fixed, const std::vector<std::pair<uint64_t, S>>& trips) {
+ freeIndex.assign(n, ~0u);
+ freeList.clear();
+ for (uint32_t i = 0; i < n; ++i)
+ if (!fixed[i]) {
+ freeIndex[i] = uint32_t(freeList.size());
+ freeList.push_back(i);
+ }
+ std::vector<std::pair<uint64_t, S>> ff;
+ ff.reserve(trips.size());
+ coupling.clear();
+ for (const auto& [key, v] : trips) {
+ const uint32_t r = uint32_t(key >> 32), c = uint32_t(key & 0xffffffffu);
+ if (freeIndex[r] == ~0u) continue;
+ if (freeIndex[c] != ~0u) ff.push_back({(uint64_t(freeIndex[r]) << 32) | freeIndex[c], v});
+ else coupling.push_back({(uint64_t(freeIndex[r]) << 32) | c, v});
+ }
+ A.build(freeList.size(), ff);
+ mg.reset();
+ if (freeList.size() > 600) {
+ mg = std::make_unique<qr2::Multigrid<S>>();
+ mg->build(A);
+ }
+ }
+ // x: every unknown (fixed ones hold their values); `rhs` (optional, per unknown) is the right-hand side.
+ void solve(std::vector<S>& x, const std::vector<S>* rhs, double tol, int maxIt) const {
+ const size_t nf = freeList.size();
+ if (nf == 0) return;
+ std::vector<S> b(nf, S{}), xf(nf);
+ for (size_t i = 0; i < nf; ++i) {
+ xf[i] = x[freeList[i]];
+ if (rhs) b[i] = (*rhs)[freeList[i]];
+ }
+ for (const auto& [key, v] : coupling) b[key >> 32] -= v * x[key & 0xffffffffu];
+ bool stop = false;
+ qr2::pcg<S>([&](const std::vector<S>& in, std::vector<S>& out) { A.mul(in, out); }, mg.get(), A.diag, b, xf, tol,
+ maxIt, {}, stop);
+ for (size_t i = 0; i < nf; ++i) x[freeList[i]] = xf[i];
+ }
+};
+
+bool flattenConformalImpl(const std::vector<glm::vec3>& pos, const std::vector<glm::uvec3>& tris, std::vector<glm::vec2>& uv,
+ std::vector<uint32_t> pins, bool) {
+ using C = std::complex<double>;
+ const size_t n = pos.size();
+ if (n < 3 || tris.empty()) return false;
+ const bool haveGuess = uv.size() == n;
+ std::vector<glm::vec2> guess = project(pos, tris);
+ if (pins.size() < 2) {
+ uint32_t a = 0, b = 0;
+ if (pins.size() == 1 && haveGuess) {
+ // The other pin: the vertex farthest from it, placed by the projection relative to it.
+ a = pins[0];
+ float far = -1.0f;
+ for (uint32_t i = 0; i < n; ++i)
+ if (const float d = glm::distance(pos[i], pos[a]); d > far) far = d, b = i;
+ for (uint32_t i = 0; i < n; ++i) guess[i] = guess[i] - guess[a] + uv[a];
+ uv[b] = guess[b];
+ pins.push_back(b);
+ } else {
+ autoPins(pos, a, b);
+ if (a == b) b = (a + 1) % uint32_t(n);
+ pins = {a, b};
+ }
+ }
+ std::vector<C> x(n);
+ for (uint32_t i = 0; i < n; ++i) {
+ const glm::vec2 g = haveGuess ? uv[i] : guess[i];
+ x[i] = C(g.x, g.y);
+ }
+ std::vector<uint8_t> fixed(n, 0);
+ for (uint32_t p : pins) fixed[p] = 1;
+ // |sum_j w_j U_j|^2 per triangle (U = u + i v): A_jk += conj(w_j) w_k.
+ std::vector<std::pair<uint64_t, C>> trips;
+ trips.reserve(tris.size() * 9);
+ for (const glm::uvec3& t : tris) {
+ glm::dvec2 q[3];
+ if (!localTriangle(pos[t.x], pos[t.y], pos[t.z], q)) continue;
+ const double dT = std::sqrt(std::abs((q[1].x - q[0].x) * (q[2].y - q[0].y) - (q[2].x - q[0].x) * (q[1].y - q[0].y)));
+ if (dT <= 0.0) continue;
+ C w[3];
+ for (int j = 0; j < 3; ++j) {
+ const glm::dvec2 d = q[(j + 2) % 3] - q[(j + 1) % 3];
+ w[j] = C(d.x, d.y) / dT;
+ }
+ for (int j = 0; j < 3; ++j)
+ for (int k = 0; k < 3; ++k) trips.push_back({(uint64_t(t[j]) << 32) | t[k], std::conj(w[j]) * w[k]});
+ }
+ PinnedSystem<C> sys;
+ sys.build(n, fixed, trips);
+ sys.solve(x, nullptr, 1e-8, 1500);
+ uv.resize(n);
+ for (uint32_t i = 0; i < n; ++i) uv[i] = glm::vec2(float(x[i].real()), float(x[i].imag()));
+ for (const glm::vec2& u : uv)
+ if (!std::isfinite(u.x) || !std::isfinite(u.y)) return false;
+ return true;
+}
+
+bool flattenIsometricImpl(const std::vector<glm::vec3>& pos, const std::vector<glm::uvec3>& tris, std::vector<glm::vec2>& uv,
+ int iterations, const std::vector<uint32_t>& pins, bool parallel) {
+ const size_t n = pos.size(), nt = tris.size();
+ // Big pieces without pins start from a Tutte embedding (the border on a circle, the inside harmonic: one
+ // well-conditioned solve, never folded) instead of LSCM, whose free border converges slowly; the
+ // as-rigid-as-possible steps then take it to the same kind of result.
+ const bool tutte = pins.size() < 2 && n > 3000 && iterations > 0;
+ if (!tutte) {
+ if (!flattenConformalImpl(pos, tris, uv, pins, parallel)) return false;
+ if (iterations <= 0) return true;
+ }
+ // LSCM's result is free in scale: bring it to the surface's before matching lengths.
+ if (!tutte && pins.size() < 2) {
+ double a3 = 0.0, au = 0.0;
+ for (const glm::uvec3& t : tris) {
+ a3 += 0.5 * glm::length(glm::cross(glm::dvec3(pos[t.y] - pos[t.x]), glm::dvec3(pos[t.z] - pos[t.x])));
+ au += 0.5 * std::abs(double(cross2(uv[t.y] - uv[t.x], uv[t.z] - uv[t.x])));
+ }
+ if (au > 0.0) {
+ const float k = float(std::sqrt(a3 / au));
+ for (glm::vec2& u : uv) u *= k;
+ }
+ }
+ std::vector<std::array<glm::dvec2, 3>> local(nt);
+ std::vector<std::array<double, 3>> cot(nt); // per triangle: half the cotangent at each corner (its opposite edge's weight)
+ std::vector<uint8_t> valid(nt, 0);
+ std::vector<std::pair<uint64_t, double>> trips;
+ trips.reserve(nt * 12);
+ for (size_t t = 0; t < nt; ++t) {
+ glm::dvec2 q[3];
+ if (!localTriangle(pos[tris[t].x], pos[tris[t].y], pos[tris[t].z], q)) continue;
+ valid[t] = 1;
+ for (int j = 0; j < 3; ++j) {
+ local[t][size_t(j)] = q[j];
+ const glm::dvec2 e1 = q[(j + 1) % 3] - q[j], e2 = q[(j + 2) % 3] - q[j];
+ const double s = std::abs(e1.x * e2.y - e1.y * e2.x);
+ const double c = glm::dot(e1, e2);
+ const double w = std::max(s > 1e-30 ? 0.5 * c / s : 0.0, 1e-3); // (clamped: keeps the system positive)
+ cot[t][size_t(j)] = w;
+ const uint64_t a = tris[t][(j + 1) % 3], b = tris[t][(j + 2) % 3];
+ trips.push_back({(a << 32) | a, w});
+ trips.push_back({(b << 32) | b, w});
+ trips.push_back({(a << 32) | b, -w});
+ trips.push_back({(b << 32) | a, -w});
+ }
+ }
+ if (tutte) {
+ // The border: half-edges whose reverse isn't in the piece, chained into a loop.
+ std::vector<std::pair<uint64_t, uint32_t>> half; // (a << 32 | b, ...)
+ half.reserve(nt * 3);
+ for (const glm::uvec3& t : tris)
+ for (int j = 0; j < 3; ++j) half.push_back({(uint64_t(t[j]) << 32) | t[(j + 1) % 3], 0});
+ std::sort(half.begin(), half.end());
+ std::vector<uint32_t> next(n, ~0u);
+ size_t borderEdges = 0;
+ for (const auto& h : half) {
+ const uint32_t a = uint32_t(h.first >> 32), b = uint32_t(h.first & 0xffffffffu);
+ const uint64_t rev = (uint64_t(b) << 32) | a;
+ if (std::binary_search(half.begin(), half.end(), std::pair<uint64_t, uint32_t>{rev, 0})) continue;
+ next[a] = b;
+ ++borderEdges;
+ }
+ std::vector<uint32_t> loop;
+ uint32_t start = ~0u;
+ for (uint32_t v = 0; v < n && start == ~0u; ++v)
+ if (next[v] != ~0u) start = v;
+ for (uint32_t v = start; v != ~0u && loop.size() <= borderEdges;) {
+ loop.push_back(v);
+ v = next[v];
+ if (v == start) break;
+ }
+ if (loop.size() < 3 || loop.size() != borderEdges) {
+ // Not one simple border loop: LSCM instead.
+ if (!flattenConformalImpl(pos, tris, uv, pins, parallel)) return false;
+ } else {
+ double length = 0.0;
+ std::vector<double> at(loop.size() + 1, 0.0);
+ for (size_t k = 0; k < loop.size(); ++k)
+ at[k + 1] = length += glm::distance(glm::dvec3(pos[loop[k]]), glm::dvec3(pos[loop[(k + 1) % loop.size()]]));
+ const double r = length / (2.0 * 3.14159265358979);
+ std::vector<uint8_t> border(n, 0);
+ std::vector<double> hu(n, 0.0), hv(n, 0.0);
+ for (size_t k = 0; k < loop.size(); ++k) {
+ const double a = 2.0 * 3.14159265358979 * at[k] / length;
+ border[loop[k]] = 1;
+ hu[loop[k]] = r * std::cos(a), hv[loop[k]] = r * std::sin(a);
+ }
+ PinnedSystem<double> harmonic;
+ harmonic.build(n, border, trips);
+ harmonic.solve(hu, nullptr, 1e-8, 300);
+ harmonic.solve(hv, nullptr, 1e-8, 300);
+ uv.resize(n);
+ for (uint32_t i = 0; i < n; ++i) uv[i] = glm::vec2(float(hu[i]), float(hv[i]));
+ iterations += 10; // (further from the result than LSCM: a few more steps)
+ }
+ }
+ std::vector<uint8_t> fixed(n, 0);
+ if (pins.empty()) fixed[0] = 1;
+ for (uint32_t p : pins) fixed[p] = 1;
+ PinnedSystem<double> sys;
+ sys.build(n, fixed, trips);
+ std::vector<double> xu(n), xv(n), bu(n), bv(n);
+ for (uint32_t i = 0; i < n; ++i) xu[i] = uv[i].x, xv[i] = uv[i].y;
+ std::vector<glm::dmat2> R(nt, glm::dmat2(1.0));
+ for (int it = 0; it < iterations; ++it) {
+ // Local step: each triangle's best rotation onto its current layout.
+ rowsFor(nt, parallel, [&](size_t b0, size_t e0) {
+ for (size_t t = b0; t < e0; ++t) {
+ if (!valid[t]) continue;
+ double s00 = 0, s01 = 0, s10 = 0, s11 = 0;
+ for (int j = 0; j < 3; ++j) {
+ const uint32_t a = tris[t][(j + 1) % 3], b = tris[t][(j + 2) % 3];
+ const double w = cot[t][size_t(j)];
+ const glm::dvec2 du(xu[a] - xu[b], xv[a] - xv[b]);
+ const glm::dvec2 dx = local[t][size_t((j + 1) % 3)] - local[t][size_t((j + 2) % 3)];
+ s00 += w * du.x * dx.x, s01 += w * du.x * dx.y, s10 += w * du.y * dx.x, s11 += w * du.y * dx.y;
+ }
+ const double th = std::atan2(s10 - s01, s00 + s11);
+ const double c = std::cos(th), s = std::sin(th);
+ R[t] = glm::dmat2(c, s, -s, c); // (column-major: [[c, -s], [s, c]])
+ }
+ });
+ // Global step: L u = the sum of each triangle's rotated edges.
+ std::fill(bu.begin(), bu.end(), 0.0);
+ std::fill(bv.begin(), bv.end(), 0.0);
+ for (size_t t = 0; t < nt; ++t) {
+ if (!valid[t]) continue;
+ for (int j = 0; j < 3; ++j) {
+ const uint32_t a = tris[t][(j + 1) % 3], b = tris[t][(j + 2) % 3];
+ const double w = cot[t][size_t(j)];
+ const glm::dvec2 e = R[t] * (local[t][size_t((j + 1) % 3)] - local[t][size_t((j + 2) % 3)]) * w;
+ bu[a] += e.x, bv[a] += e.y;
+ bu[b] -= e.x, bv[b] -= e.y;
+ }
+ }
+ sys.solve(xu, &bu, 1e-7, 200);
+ sys.solve(xv, &bv, 1e-7, 200);
+ }
+ for (uint32_t i = 0; i < n; ++i)
+ if (!std::isfinite(xu[i]) || !std::isfinite(xv[i])) return true; // keep the conformal result
+ for (uint32_t i = 0; i < n; ++i) uv[i] = glm::vec2(float(xu[i]), float(xv[i]));
+ return true;
+}
+
+// ---------------------------------------------------------------------------------------------------------------
+// Pieces
+
+struct Pieces {
+ std::vector<uint32_t> piece; // per triangle (kNoCorner: not unwrapped)
+ uint32_t count = 0;
+ std::vector<uint32_t> vertex; // per corner: its vertex of the cut surface (shared by the corners it joins)
+ uint32_t vertexCount = 0;
+};
+
+Pieces buildPieces(const Mesh& m, const std::vector<uint32_t>& twin, const std::vector<uint8_t>& cut,
+ const std::vector<uint8_t>* faces) {
+ const size_t nt = m.triangleCount(), nc = nt * 3;
+ Pieces p;
+ DisjointSets corners(nc), tris(nt);
+ for (uint32_t c = 0; c < nc; ++c) {
+ const uint32_t d = twin[c];
+ if (cut[c] || d == kNoCorner || d < c) continue;
+ if (faces && (!(*faces)[c / 3] || !(*faces)[d / 3])) continue;
+ corners.unite(c, cornerNext(d));
+ corners.unite(cornerNext(c), d);
+ tris.unite(c / 3, d / 3);
+ }
+ std::vector<uint32_t> label;
+ tris.labels(label);
+ p.piece.assign(nt, kNoCorner);
+ std::vector<uint32_t> id(nt, kNoCorner);
+ for (uint32_t t = 0; t < nt; ++t) {
+ if (faces && !(*faces)[t]) continue;
+ if (id[label[t]] == kNoCorner) id[label[t]] = p.count++;
+ p.piece[t] = id[label[t]];
+ }
+ p.vertexCount = corners.labels(p.vertex);
+ return p;
+}
+
+// The cut-graph edges (corners) that make piece `triangles` a disk, or empty when it already is one.
+std::vector<uint32_t> diskCuts(const Mesh& m, const std::vector<uint32_t>& twin, const std::vector<uint8_t>& cut,
+ const Pieces& pc, const std::vector<uint32_t>& triangles) {
+ // Local numbering of the piece's vertices.
+ std::vector<uint32_t> vlist;
+ for (uint32_t t : triangles)
+ for (uint32_t j = 0; j < 3; ++j) vlist.push_back(pc.vertex[t * 3 + j]);
+ std::sort(vlist.begin(), vlist.end());
+ vlist.erase(std::unique(vlist.begin(), vlist.end()), vlist.end());
+ auto local = [&](uint32_t c) { return uint32_t(std::lower_bound(vlist.begin(), vlist.end(), pc.vertex[c]) - vlist.begin()); };
+ const size_t V = vlist.size(), F = triangles.size();
+ auto isIn = [&](uint32_t t) { return std::binary_search(triangles.begin(), triangles.end(), t); };
+ size_t boundary = 0;
+ for (uint32_t t : triangles)
+ for (uint32_t j = 0; j < 3; ++j) {
+ const uint32_t c = t * 3 + j, d = twin[c];
+ if (cut[c] || d == kNoCorner || !isIn(d / 3)) ++boundary;
+ }
+ const long long E = (3 * (long long)F + (long long)boundary) / 2;
+ const long long chi = (long long)V - E + (long long)F;
+ if (chi == 1) return {};
+ // Dual spanning tree (breadth first from the first triangle) over the piece's inner edges.
+ auto inner = [&](uint32_t c) {
+ const uint32_t d = twin[c];
+ return !cut[c] && d != kNoCorner && isIn(d / 3);
+ };
+ std::vector<uint8_t> tree(m.triangleCount() * 3, 0);
+ {
+ std::vector<uint8_t> seen(F, 0);
+ auto index = [&](uint32_t t) { return size_t(std::lower_bound(triangles.begin(), triangles.end(), t) - triangles.begin()); };
+ std::queue<uint32_t> q;
+ q.push(triangles[0]);
+ seen[0] = 1;
+ while (!q.empty()) {
+ const uint32_t t = q.front();
+ q.pop();
+ for (uint32_t j = 0; j < 3; ++j) {
+ const uint32_t c = t * 3 + j;
+ if (!inner(c)) continue;
+ const uint32_t u = twin[c] / 3;
+ const size_t k = index(u);
+ if (seen[k]) continue;
+ seen[k] = 1;
+ tree[c] = tree[twin[c]] = 1;
+ q.push(u);
+ }
+ }
+ }
+ // Candidate cut edges: inner edges the tree doesn't cross. Prune those hanging off a vertex of degree one.
+ struct Edge {
+ uint32_t corner, a, b;
+ bool alive = true;
+ };
+ std::vector<Edge> edges;
+ std::vector<uint32_t> degree(V, 0);
+ for (uint32_t t : triangles)
+ for (uint32_t j = 0; j < 3; ++j) {
+ const uint32_t c = t * 3 + j;
+ const uint32_t a = local(c), b = local(cornerNext(c));
+ if (!inner(c)) {
+ ++degree[a], ++degree[b]; // a border half-edge (its loop gives each of its vertices two)
+ continue;
+ }
+ if (tree[c] || twin[c] < c) continue;
+ edges.push_back({c, a, b});
+ ++degree[a], ++degree[b];
+ }
+ std::vector<std::vector<uint32_t>> incident(V);
+ for (uint32_t e = 0; e < edges.size(); ++e) incident[edges[e].a].push_back(e), incident[edges[e].b].push_back(e);
+ std::vector<uint32_t> stack;
+ for (uint32_t v = 0; v < V; ++v)
+ if (degree[v] == 1) stack.push_back(v);
+ while (!stack.empty()) {
+ const uint32_t v = stack.back();
+ stack.pop_back();
+ if (degree[v] != 1) continue;
+ for (uint32_t e : incident[v]) {
+ if (!edges[e].alive) continue;
+ edges[e].alive = false;
+ const uint32_t o = edges[e].a == v ? edges[e].b : edges[e].a;
+ --degree[v], --degree[o];
+ if (degree[o] == 1) stack.push_back(o);
+ break;
+ }
+ }
+ std::vector<uint32_t> out;
+ for (const Edge& e : edges)
+ if (e.alive) out.push_back(e.corner);
+ if (!out.empty() || boundary > 0) return out;
+ // A closed shell (a sphere): cut in two across the middle of its longest side, so each half flattens like a
+ // dome (one cut along a path would leave the whole shell to unfold around it, with huge stretch). The halves
+ // are checked again in the next round.
+ {
+ glm::vec3 lo(std::numeric_limits<float>::max()), hi(std::numeric_limits<float>::lowest());
+ std::vector<float> key(F);
+ for (uint32_t t : triangles)
+ for (uint32_t j = 0; j < 3; ++j) lo = glm::min(lo, m.positions[m.triangles[t][j]]), hi = glm::max(hi, m.positions[m.triangles[t][j]]);
+ const glm::vec3 d = hi - lo;
+ const int axis = d.x >= d.y && d.x >= d.z ? 0 : d.y >= d.z ? 1 : 2;
+ for (size_t k = 0; k < F; ++k) {
+ const glm::uvec3 tri = m.triangles[triangles[k]];
+ key[k] = (m.positions[tri.x][axis] + m.positions[tri.y][axis] + m.positions[tri.z][axis]) / 3.0f;
+ }
+ std::vector<float> sorted = key;
+ std::nth_element(sorted.begin(), sorted.begin() + std::ptrdiff_t(F / 2), sorted.end());
+ const float mid = sorted[F / 2];
+ auto side = [&](uint32_t t) {
+ const size_t k = size_t(std::lower_bound(triangles.begin(), triangles.end(), t) - triangles.begin());
+ return key[k] >= mid;
+ };
+ for (uint32_t t : triangles)
+ for (uint32_t j = 0; j < 3; ++j) {
+ const uint32_t c = t * 3 + j;
+ if (inner(c) && twin[c] > c && side(t) != side(twin[c] / 3)) out.push_back(c);
+ }
+ if (!out.empty() && out.size() * 4 < 3 * F) return out;
+ out.clear();
+ }
+ // Too small to split: cut along the longest shortest path, between two far-apart vertices.
+ std::vector<std::vector<std::pair<uint32_t, uint32_t>>> adj(V); // (neighbour, corner)
+ std::vector<glm::vec3> vpos(V);
+ for (uint32_t t : triangles)
+ for (uint32_t j = 0; j < 3; ++j) {
+ const uint32_t c = t * 3 + j;
+ vpos[local(c)] = m.positions[m.triangles[t][j]];
+ if (inner(c) && twin[c] > c) {
+ const uint32_t a = local(c), b = local(cornerNext(c));
+ adj[a].push_back({b, c});
+ adj[b].push_back({a, c});
+ }
+ }
+ auto dijkstra = [&](uint32_t s, std::vector<uint32_t>& via) {
+ std::vector<float> dist(V, std::numeric_limits<float>::max());
+ via.assign(V, kNoCorner);
+ using Item = std::pair<float, uint32_t>;
+ std::priority_queue<Item, std::vector<Item>, std::greater<>> q;
+ dist[s] = 0.0f;
+ q.push({0.0f, s});
+ uint32_t far = s;
+ while (!q.empty()) {
+ const auto [d, v] = q.top();
+ q.pop();
+ if (d > dist[v]) continue;
+ far = v;
+ for (auto [w, c] : adj[v])
+ if (const float nd = d + glm::distance(vpos[v], vpos[w]); nd < dist[w]) {
+ dist[w] = nd;
+ via[w] = c;
+ q.push({nd, w});
+ }
+ }
+ return far;
+ };
+ std::vector<uint32_t> via;
+ const uint32_t a = dijkstra(0, via);
+ const uint32_t b = dijkstra(a, via);
+ for (uint32_t v = b; v != a && via[v] != kNoCorner;) {
+ const uint32_t c = via[v];
+ out.push_back(c);
+ const uint32_t x = local(c), y = local(cornerNext(c));
+ v = x == v ? y : x;
+ }
+ if (out.empty() && !adj[0].empty()) out.push_back(adj[0][0].second);
+ return out;
+}
+
+// The similarity (no mirror) that best maps `from` onto `to`: to ~ s R from + t.
+void fitSimilarity(const std::vector<glm::vec2>& from, const std::vector<glm::vec2>& to, float& scale, float& angle,
+ glm::vec2& cf, glm::vec2& ct, bool fixedCentres = false) {
+ glm::dvec2 a(cf), b(ct);
+ if (!fixedCentres) {
+ a = b = glm::dvec2(0.0);
+ for (size_t i = 0; i < from.size(); ++i) a += glm::dvec2(from[i]), b += glm::dvec2(to[i]);
+ a /= double(from.size()), b /= double(from.size());
+ }
+ double dotSum = 0.0, crossSum = 0.0, norm = 0.0;
+ for (size_t i = 0; i < from.size(); ++i) {
+ const glm::dvec2 p = glm::dvec2(from[i]) - a, q = glm::dvec2(to[i]) - b;
+ dotSum += p.x * q.x + p.y * q.y;
+ crossSum += p.x * q.y - p.y * q.x;
+ norm += p.x * p.x + p.y * p.y;
+ }
+ angle = float(std::atan2(crossSum, dotSum));
+ scale = norm > 0.0 ? float(std::sqrt(dotSum * dotSum + crossSum * crossSum) / norm) : 1.0f;
+ cf = glm::vec2(a);
+ ct = glm::vec2(b);
+}
+
+} // namespace
+
+bool flattenConformal(const std::vector<glm::vec3>& positions, const std::vector<glm::uvec3>& triangles, std::vector<glm::vec2>& uv,
+ const std::vector<uint32_t>& pins) {
+ return flattenConformalImpl(positions, triangles, uv, pins, positions.size() > 20000);
+}
+
+bool flattenIsometric(const std::vector<glm::vec3>& positions, const std::vector<glm::uvec3>& triangles, std::vector<glm::vec2>& uv,
+ int iterations, const std::vector<uint32_t>& pins) {
+ return flattenIsometricImpl(positions, triangles, uv, iterations, pins, positions.size() > 20000);
+}
+
+bool uvUnwrap(const Mesh& m, const UvUnwrapOptions& o, UvUnwrapResult& result, std::string& error, const UvProgress& progress) {
+ result = UvUnwrapResult();
+ const size_t nt = m.triangleCount(), nc = nt * 3;
+ if (nt == 0) {
+ error = "There is no mesh to unwrap";
+ return false;
+ }
+ const std::vector<uint8_t>* faces = o.faces && o.faces->size() == nt ? o.faces : nullptr;
+ if (faces && std::find(faces->begin(), faces->end(), uint8_t(1)) == faces->end()) faces = nullptr;
+ const bool hadUvs = m.uvs.size() == nc;
+ if (o.method == UvUnwrapMethod::Unfold && !hadUvs) {
+ error = "Unfold needs UVs to start from: unwrap first";
+ return false;
+ }
+ auto report = [&](float f) { return !progress || progress(std::clamp(f, 0.0f, 1.0f)); };
+
+ // Auto seams: xatlas on the whole mesh (or the selected triangles), then packed or fitted like the others.
+ if (o.method == UvUnwrapMethod::Auto) {
+ std::vector<uint32_t> list;
+ for (uint32_t t = 0; t < nt; ++t)
+ if (!faces || (*faces)[t]) list.push_back(t);
+ std::vector<glm::uvec3> tris(list.size());
+ for (size_t i = 0; i < list.size(); ++i) tris[i] = m.triangles[list[i]];
+ AutoUvResult r;
+ if (!computeAutoUv(m.positions, tris, o.resolution, r, error, [&](float f) { return report(f * 0.9f); })) return false;
+ result.uvs = hadUvs ? m.uvs : std::vector<glm::vec2>(nc, glm::vec2(0.0f));
+ for (size_t i = 0; i < list.size(); ++i)
+ for (uint32_t j = 0; j < 3; ++j) result.uvs[size_t(list[i]) * 3 + j] = r.uvs[i * 3 + j];
+ result.islands = size_t(r.charts);
+ Mesh tmp;
+ tmp.positions = m.positions;
+ tmp.triangles = m.triangles;
+ tmp.uvs = result.uvs;
+ const bool repack = !faces && (o.packing.tiles > 1 || o.packing.density > 0.0f);
+ if (repack || faces) {
+ UvTopology topo = buildUvTopology(tmp);
+ std::vector<uint8_t> isl(topo.islandCount, faces ? 0 : 1);
+ if (faces)
+ for (uint32_t t : list) isl[topo.island[t]] = 1;
+ UvPackOptions po = o.packing;
+ if (faces) po.tiles = 1, po.density = 0.0f;
+ if (!uvPack(tmp, topo, isl, po, result.packing, error)) return false;
+ if (faces && hadUvs) { // into the old place of the selection
+ glm::vec2 lo(1e30f), hi(-1e30f);
+ for (uint32_t t : list)
+ for (uint32_t j = 0; j < 3; ++j) lo = glm::min(lo, m.uvs[t * 3 + j]), hi = glm::max(hi, m.uvs[t * 3 + j]);
+ const float side = std::max(hi.x - lo.x, hi.y - lo.y);
+ if (side > 0.0f)
+ for (uint32_t t : list)
+ for (uint32_t j = 0; j < 3; ++j) {
+ glm::vec2& u = tmp.uvs[t * 3 + j];
+ u = lo + u * side;
+ }
+ }
+ result.uvs = std::move(tmp.uvs);
+ } else {
+ result.packing.islands = result.islands;
+ result.packing.tilesUsed = 1;
+ }
+ report(1.0f);
+ return true;
+ }
+
+ // 1. Cuts.
+ const std::vector<uint32_t> twin = cornerTwins(m);
+ const bool flags = m.uvFlags.size() == nc;
+ bool anySeam = false;
+ if (flags)
+ for (uint8_t f : m.uvFlags) anySeam = anySeam || (f & kUvSeam);
+ const bool useIslands = o.method == UvUnwrapMethod::Unfold || (!anySeam && hadUvs);
+ UvTopology topo;
+ if (useIslands) topo = buildUvTopology(m, twin);
+ std::vector<uint8_t> cut(nc, 0);
+ for (uint32_t c = 0; c < nc; ++c) {
+ const uint32_t d = twin[c];
+ bool x = d == kNoCorner;
+ if (!x && flags) x = (m.uvFlags[c] | m.uvFlags[d]) & kUvSeam;
+ if (!x && useIslands) x = topo.border[c];
+ if (!x && o.method == UvUnwrapMethod::Polygroups) x = m.polygroupAt(c / 3) != m.polygroupAt(d / 3);
+ cut[c] = x;
+ }
+ // 2. Pieces, with extra cuts until every piece is a disk.
+ Pieces pc;
+ std::vector<uint32_t> offsets, tris;
+ auto group = [&]() {
+ pc = buildPieces(m, twin, cut, faces);
+ offsets.assign(pc.count + 1, 0);
+ for (uint32_t t = 0; t < nt; ++t)
+ if (pc.piece[t] != kNoCorner) ++offsets[pc.piece[t] + 1];
+ for (uint32_t i = 0; i < pc.count; ++i) offsets[i + 1] += offsets[i];
+ std::vector<uint32_t> at(offsets.begin(), offsets.end() - 1);
+ tris.assign(offsets.back(), 0);
+ for (uint32_t t = 0; t < nt; ++t)
+ if (pc.piece[t] != kNoCorner) tris[at[pc.piece[t]]++] = t;
+ };
+ group();
+ if (o.method != UvUnwrapMethod::Planar)
+ for (int round = 0; round < 4; ++round) {
+ std::vector<std::vector<uint32_t>> extra(pc.count);
+ poolFor(pc.count, [&](size_t b, size_t e) {
+ for (size_t i = b; i < e; ++i) {
+ const std::vector<uint32_t> list(tris.begin() + offsets[i], tris.begin() + offsets[i + 1]);
+ extra[i] = diskCuts(m, twin, cut, pc, list);
+ }
+ }, 1);
+ size_t added = 0;
+ for (const auto& ex : extra)
+ for (uint32_t c : ex) {
+ cut[c] = 1;
+ if (twin[c] != kNoCorner) cut[twin[c]] = 1;
+ ++added;
+ }
+ if (!added) break;
+ result.extraCuts += added;
+ group();
+ }
+ if (!report(0.05f)) {
+ error = "Unwrap was cancelled";
+ return false;
+ }
+ // 3. Flatten each piece.
+ std::vector<glm::vec2> vuv(pc.vertexCount, glm::vec2(0.0f));
+ std::vector<uint8_t> pinnedPiece(pc.count, 0);
+ std::vector<uint32_t> pinCorner(pc.count, kNoCorner); // a piece with one pin: that corner (it stays put)
+ std::vector<uint32_t> order(pc.count);
+ std::iota(order.begin(), order.end(), 0u);
+ std::sort(order.begin(), order.end(), [&](uint32_t a, uint32_t b) { return offsets[a + 1] - offsets[a] > offsets[b + 1] - offsets[b]; });
+ std::atomic<size_t> done{0};
+ std::atomic<bool> cancelled{false};
+ std::mutex progressMutex;
+ const bool keepPins = hadUvs && flags && o.method != UvUnwrapMethod::Planar;
+ auto solve = [&](uint32_t i, bool parallel) {
+ if (cancelled) return;
+ const uint32_t b = offsets[i], e = offsets[i + 1];
+ std::vector<uint32_t> verts;
+ for (uint32_t k = b; k < e; ++k)
+ for (uint32_t j = 0; j < 3; ++j) verts.push_back(pc.vertex[tris[k] * 3 + j]);
+ std::sort(verts.begin(), verts.end());
+ verts.erase(std::unique(verts.begin(), verts.end()), verts.end());
+ auto local = [&](uint32_t c) { return uint32_t(std::lower_bound(verts.begin(), verts.end(), pc.vertex[c]) - verts.begin()); };
+ std::vector<glm::vec3> pos(verts.size());
+ std::vector<glm::uvec3> lt(e - b);
+ std::vector<glm::vec2> uv;
+ std::vector<uint32_t> pins;
+ std::vector<uint8_t> isPin(verts.size(), 0);
+ uint32_t firstPin = kNoCorner;
+ if (hadUvs) uv.assign(verts.size(), glm::vec2(0.0f));
+ for (uint32_t k = b; k < e; ++k) {
+ const uint32_t t = tris[k];
+ for (uint32_t j = 0; j < 3; ++j) {
+ const uint32_t c = t * 3 + j, l = local(c);
+ lt[k - b][int(j)] = l;
+ pos[l] = m.positions[m.triangles[t][j]];
+ if (hadUvs) uv[l] = m.uvs[c];
+ if (keepPins && (m.uvFlags[c] & kUvPin) && !isPin[l]) {
+ isPin[l] = 1;
+ pins.push_back(l);
+ if (firstPin == kNoCorner) firstPin = c;
+ }
+ }
+ }
+ if (pins.size() == 1) pinCorner[i] = firstPin; // (placed by the fit below, about the pin)
+ if (pins.size() < 2) { // (a starting guess only matters with pins)
+ uv.clear();
+ pins.clear();
+ }
+ bool ok = false;
+ if (o.method == UvUnwrapMethod::Planar) {
+ uv = project(pos, lt);
+ ok = true;
+ } else if (o.method == UvUnwrapMethod::Conformal) {
+ ok = flattenConformalImpl(pos, lt, uv, pins, parallel);
+ } else {
+ ok = flattenIsometricImpl(pos, lt, uv, std::max(o.iterations, 0), pins, parallel);
+ }
+ if (!ok) uv = project(pos, lt); // (a piece the solver can't flatten still gets UVs)
+ if (pins.size() < 2) {
+ // One texel density: UV area = surface area, centred.
+ double a3 = 0.0, au = 0.0;
+ for (const glm::uvec3& t : lt) {
+ a3 += 0.5 * glm::length(glm::cross(glm::dvec3(pos[t.y] - pos[t.x]), glm::dvec3(pos[t.z] - pos[t.x])));
+ au += double(cross2(uv[t.y] - uv[t.x], uv[t.z] - uv[t.x])) * 0.5;
+ }
+ if (au < 0.0) { // mirrored: turn it the right way round
+ for (glm::vec2& u : uv) u.x = -u.x;
+ au = -au;
+ }
+ const float k = au > 0.0 ? float(std::sqrt(a3 / au)) : 1.0f;
+ glm::vec2 lo(1e30f), hi(-1e30f);
+ for (const glm::vec2& u : uv) lo = glm::min(lo, u), hi = glm::max(hi, u);
+ const glm::vec2 mid = (lo + hi) * 0.5f;
+ for (glm::vec2& u : uv) u = (u - mid) * k;
+ } else {
+ pinnedPiece[i] = 1;
+ }
+ for (uint32_t l = 0; l < verts.size(); ++l) vuv[verts[l]] = uv[l];
+ const size_t d = done.fetch_add(e - b) + (e - b);
+ std::lock_guard lock(progressMutex);
+ if (!report(0.05f + 0.85f * float(double(d) / double(std::max<size_t>(tris.size(), 1))))) cancelled = true;
+ };
+ // Pieces in parallel; a piece holding most of the mesh first on its own, with parallel products.
+ size_t first = 0;
+ while (first < order.size() && size_t(offsets[order[first] + 1] - offsets[order[first]]) * 3 > tris.size() &&
+ offsets[order[first] + 1] - offsets[order[first]] > 20000)
+ solve(order[first++], true);
+ poolFor(order.size() - first, [&](size_t b, size_t e) {
+ for (size_t k = b; k < e; ++k) solve(order[first + k], false);
+ }, 1);
+ if (cancelled) {
+ error = "Unwrap was cancelled";
+ return false;
+ }
+ // 4. Into the mesh's UVs, then packed or fitted in place.
+ result.uvs = hadUvs ? m.uvs : std::vector<glm::vec2>(nc, glm::vec2(0.0f));
+ for (uint32_t t = 0; t < nt; ++t) {
+ if (pc.piece[t] == kNoCorner) continue;
+ for (uint32_t j = 0; j < 3; ++j) result.uvs[t * 3 + j] = vuv[pc.vertex[t * 3 + j]];
+ }
+ result.islands = pc.count;
+ const bool inPlace = hadUvs && (o.method == UvUnwrapMethod::Unfold || !o.pack);
+ if (inPlace) {
+ // Each piece fitted (turned, scaled, moved) onto where its old UVs were.
+ poolFor(pc.count, [&](size_t b, size_t e) {
+ for (size_t i = b; i < e; ++i) {
+ if (pinnedPiece[i]) continue;
+ std::vector<glm::vec2> from, to;
+ for (uint32_t k = offsets[i]; k < offsets[i + 1]; ++k)
+ for (uint32_t j = 0; j < 3; ++j) {
+ const uint32_t c = tris[k] * 3 + j;
+ from.push_back(result.uvs[c]);
+ to.push_back(m.uvs[c]);
+ }
+ float s = 1, a = 0;
+ glm::vec2 cf(0.0f), ct(0.0f);
+ const bool pinned = pinCorner[i] != kNoCorner;
+ if (pinned) cf = result.uvs[pinCorner[i]], ct = m.uvs[pinCorner[i]];
+ fitSimilarity(from, to, s, a, cf, ct, pinned);
+ if (!(s > 0.0f) || !std::isfinite(s)) s = 1.0f;
+ const float ca = std::cos(a), sa = std::sin(a);
+ for (uint32_t k = offsets[i]; k < offsets[i + 1]; ++k)
+ for (uint32_t j = 0; j < 3; ++j) {
+ glm::vec2& u = result.uvs[tris[k] * 3 + j];
+ u = ct + rotate(u - cf, ca, sa) * s;
+ }
+ }
+ }, 8);
+ result.packing.islands = pc.count;
+ result.packing.tilesUsed = 1;
+ } else {
+ Mesh tmp;
+ tmp.positions = m.positions;
+ tmp.triangles = m.triangles;
+ tmp.uvs = result.uvs;
+ UvTopology pt;
+ pt.island.assign(nt, 0);
+ // Islands for the packer: the pieces (and, when only some faces were unwrapped, one per other triangle,
+ // which isn't packed).
+ pt.islandCount = pc.count;
+ for (uint32_t t = 0; t < nt; ++t) pt.island[t] = pc.piece[t] == kNoCorner ? pc.count : pc.piece[t];
+ pt.islandCount = pc.count + (faces ? 1 : 0);
+ pt.islandOffsets.assign(pt.islandCount + 1, 0);
+ for (uint32_t t = 0; t < nt; ++t) ++pt.islandOffsets[pt.island[t] + 1];
+ for (uint32_t i = 0; i < pt.islandCount; ++i) pt.islandOffsets[i + 1] += pt.islandOffsets[i];
+ std::vector<uint32_t> at(pt.islandOffsets.begin(), pt.islandOffsets.end() - 1);
+ pt.islandTriangles.resize(nt);
+ for (uint32_t t = 0; t < nt; ++t) pt.islandTriangles[at[pt.island[t]]++] = t;
+ std::vector<uint8_t> isl(pt.islandCount, 1);
+ for (uint32_t i = 0; i < pc.count; ++i) isl[i] = !pinnedPiece[i];
+ if (faces) isl[pc.count] = 0;
+ UvPackOptions po = o.packing;
+ po.resolution = o.resolution;
+ if (faces && hadUvs) po.tiles = 1, po.density = 0.0f;
+ if (std::find(isl.begin(), isl.end(), uint8_t(1)) != isl.end() && !uvPack(tmp, pt, isl, po, result.packing, error))
+ return false;
+ if (faces && hadUvs) { // the selection's new islands go where its old ones were
+ glm::vec2 lo(1e30f), hi(-1e30f);
+ for (uint32_t t = 0; t < nt; ++t)
+ if ((*faces)[t])
+ for (uint32_t j = 0; j < 3; ++j) lo = glm::min(lo, m.uvs[t * 3 + j]), hi = glm::max(hi, m.uvs[t * 3 + j]);
+ const float side = std::max(hi.x - lo.x, hi.y - lo.y);
+ if (side > 0.0f)
+ for (uint32_t t = 0; t < nt; ++t)
+ if ((*faces)[t] && !pinnedPiece[pc.piece[t]])
+ for (uint32_t j = 0; j < 3; ++j) {
+ glm::vec2& u = tmp.uvs[t * 3 + j];
+ u = lo + u * side;
+ }
+ }
+ result.uvs = std::move(tmp.uvs);
+ }
+ report(1.0f);
+ return true;
+}
+
+} // namespace sf
diff --git a/tests/test_uv_editor.cpp b/tests/test_uv_editor.cpp
new file mode 100644
index 00000000..18bf1a22
--- /dev/null
+++ b/tests/test_uv_editor.cpp
@@ -0,0 +1,540 @@
+// SculptForge - open source digital sculpting
+// SPDX-License-Identifier: GPL-3.0-or-later
+//
+// UV Editor (core/Uv.h): UV topology, the unwrap solvers (LSCM, least stretch, polygroups, planar, unfold), cut
+// graphs for closed pieces, packing into one tile and across UDIM tiles, texel density, trim sheets, seams,
+// weld / split / straighten, the uv_* commands with undo, painted textures following the UVs, and the cost on
+// a million triangles.
+#include "TestHarness.h"
+
+#include "core/Commands.h"
+#include "core/Primitives.h"
+#include "core/Texture.h"
+#include "core/Uv.h"
+
+#include <algorithm>
+#include <chrono>
+#include <cmath>
+#include <cstdio>
+
+using namespace sf;
+
+namespace {
+
+double secondsSince(std::chrono::steady_clock::time_point t0) {
+ return std::chrono::duration<double>(std::chrono::steady_clock::now() - t0).count();
+}
+
+// Every UV inside [lo, hi] (with a little slack).
+bool uvsWithin(const Mesh& m, glm::vec2 lo, glm::vec2 hi) {
+ for (const glm::vec2& u : m.uvs)
+ if (u.x < lo.x - 1e-4f || u.y < lo.y - 1e-4f || u.x > hi.x + 1e-4f || u.y > hi.y + 1e-4f) return false;
+ return true;
+}
+
+// True when no two islands' UV bounding boxes overlap by more than `slack`.
+bool islandBoxesDisjoint(const Mesh& m, float slack = 1e-5f) {
+ const UvTopology topo = buildUvTopology(m);
+ std::vector<glm::vec2> lo(topo.islandCount, glm::vec2(1e30f)), hi(topo.islandCount, glm::vec2(-1e30f));
+ for (uint32_t c = 0; c < m.uvs.size(); ++c) {
+ const uint32_t i = topo.island[c / 3];
+ lo[i] = glm::min(lo[i], m.uvs[c]);
+ hi[i] = glm::max(hi[i], m.uvs[c]);
+ }
+ for (uint32_t a = 0; a < topo.islandCount; ++a)
+ for (uint32_t b = a + 1; b < topo.islandCount; ++b) {
+ const glm::vec2 o = glm::min(hi[a], hi[b]) - glm::max(lo[a], lo[b]);
+ if (o.x > slack && o.y > slack) return false;
+ }
+ return true;
+}
+
+size_t flippedTriangles(const Mesh& m) {
+ std::vector<float> s;
+ uvTriangleStretch(m, s);
+ return size_t(std::count(s.begin(), s.end(), -1.0f));
+}
+
+// A cube whose six sides are polygroups 1-6 (makeCube's), without UVs.
+Mesh cube(int res = 6) {
+ Mesh m = makeCube(res);
+ m.uvs.clear();
+ return m;
+}
+
+CommandResult run(Document& doc, const char* name, Args args = {}) {
+ static CommandRegistry reg;
+ return reg.execute(doc, name, args);
+}
+
+} // namespace
+
+TEST(uv_corner_twins_on_a_plane) {
+ const Mesh m = makePlane(4);
+ const std::vector<uint32_t> twin = cornerTwins(m);
+ size_t open = 0;
+ for (uint32_t c = 0; c < twin.size(); ++c) {
+ if (twin[c] == kNoCorner) {
+ ++open;
+ continue;
+ }
+ CHECK(twin[twin[c]] == c);
+ // The twin runs the same edge the other way.
+ CHECK(m.triangles[c / 3][c % 3] == m.triangles[twin[c] / 3][(twin[c] % 3 + 1) % 3]);
+ }
+ CHECK(open == 16); // 4 x 4 cells: 16 border edges
+}
+
+TEST(uv_topology_islands_and_seams) {
+ Mesh m = makePlane(4);
+ m.uvs.resize(m.triangleCount() * 3);
+ for (uint32_t t = 0; t < m.triangleCount(); ++t)
+ for (uint32_t j = 0; j < 3; ++j) {
+ const glm::vec3 p = m.positions[m.triangles[t][j]];
+ m.uvs[t * 3 + j] = glm::vec2(p.x, p.z) * 0.5f + 0.5f;
+ }
+ UvTopology topo = buildUvTopology(m);
+ CHECK(topo.islandCount == 1);
+ CHECK(topo.uvVertexCount == m.vertexCount());
+ // A seam right across splits it in two.
+ std::vector<uint32_t> cut;
+ for (uint32_t c = 0; c < topo.twin.size(); ++c) {
+ if (topo.twin[c] == kNoCorner) continue;
+ const glm::vec3 a = m.positions[m.triangles[c / 3][c % 3]], b = m.positions[m.triangles[c / 3][(c % 3 + 1) % 3]];
+ if (std::abs(a.x) < 1e-5f && std::abs(b.x) < 1e-5f) cut.push_back(c);
+ }
+ CHECK(!cut.empty());
+ uvSetSeams(m, topo.twin, cut, true);
+ CHECK(uvSeamCount(m) == 4);
+ topo = buildUvTopology(m);
+ CHECK(topo.islandCount == 2);
+ CHECK(topo.uvVertexCount == m.vertexCount() + 5); // the 5 vertices on the cut, once more
+ uvClearSeams(m);
+ CHECK(m.uvFlags.empty());
+ CHECK(buildUvTopology(m).islandCount == 1);
+}
+
+TEST(uv_lscm_flattens_a_plane_exactly) {
+ // A flat, irregular piece flattens to a similarity of itself: no stretch at all.
+ Mesh m = makePlane(12);
+ for (glm::vec3& p : m.positions) p += glm::vec3(0.05f * std::sin(7.0f * p.z), 0.0f, 0.04f * std::cos(5.0f * p.x));
+ std::vector<glm::vec2> uv;
+ CHECK(flattenConformal(m.positions, m.triangles, uv));
+ m.uvs.resize(m.triangleCount() * 3);
+ for (uint32_t t = 0; t < m.triangleCount(); ++t)
+ for (uint32_t j = 0; j < 3; ++j) m.uvs[t * 3 + j] = uv[m.triangles[t][j]];
+ const UvStretchStats st = uvStretchStats(m);
+ CHECK(st.mean < 1e-3f);
+ CHECK(st.flipped == 0.0f);
+}
+
+TEST(uv_least_stretch_beats_conformal_on_a_curved_piece) {
+ // A dome (a hemisphere's top): conformal keeps angles but shrinks the rim; least stretch keeps lengths better.
+ Mesh m = makeIcosphere(4);
+ std::vector<uint32_t> keep;
+ for (uint32_t t = 0; t < m.triangleCount(); ++t) {
+ const glm::uvec3 tri = m.triangles[t];
+ if (m.positions[tri.x].y > 0.5f && m.positions[tri.y].y > 0.5f && m.positions[tri.z].y > 0.5f) keep.push_back(t);
+ }
+ std::vector<glm::uvec3> tris;
+ for (uint32_t t : keep) tris.push_back(m.triangles[t]);
+ // Compact the vertices.
+ std::vector<uint32_t> remap(m.vertexCount(), ~0u);
+ std::vector<glm::vec3> pos;
+ for (glm::uvec3& t : tris)
+ for (int j = 0; j < 3; ++j) {
+ if (remap[t[j]] == ~0u) remap[t[j]] = uint32_t(pos.size()), pos.push_back(m.positions[t[j]]);
+ t[j] = remap[t[j]];
+ }
+ auto stretchOf = [&](const std::vector<glm::vec2>& uv) {
+ Mesh d;
+ d.positions = pos;
+ d.triangles = tris;
+ d.uvs.resize(tris.size() * 3);
+ for (size_t t = 0; t < tris.size(); ++t)
+ for (int j = 0; j < 3; ++j) d.uvs[t * 3 + size_t(j)] = uv[tris[t][j]];
+ return uvStretchStats(d);
+ };
+ std::vector<glm::vec2> conformal, isometric;
+ CHECK(flattenConformal(pos, tris, conformal));
+ CHECK(flattenIsometric(pos, tris, isometric, 10));
+ const UvStretchStats a = stretchOf(conformal), b = stretchOf(isometric);
+ std::printf(" dome: conformal stretch %.4f, least stretch %.4f\n", double(a.mean), double(b.mean));
+ CHECK(a.flipped == 0.0f);
+ CHECK(b.flipped == 0.0f);
+ CHECK(b.mean < a.mean);
+ CHECK(b.mean < 0.1f);
+}
+
+TEST(uv_unwrap_closed_sphere_gets_cut_automatically) {
+ Document doc = makeDoc(makeIcosphere(4));
+ doc.mesh.uvs.clear();
+ const CommandResult r = run(doc, "uv_unwrap", {{"method", std::string("isometric")}});
+ CHECK(r.ok);
+ std::printf(" %s\n", r.message.c_str());
+ CHECK(doc.mesh.hasUvs());
+ CHECK(r.message.find("cut automatically") != std::string::npos);
+ CHECK(buildUvTopology(doc.mesh).islandCount == 2); // split across the middle: two domes
+ CHECK(uvsWithin(doc.mesh, glm::vec2(0.0f), glm::vec2(1.0f)));
+ CHECK(flippedTriangles(doc.mesh) == 0);
+ CHECK(uvStretchStats(doc.mesh).mean < 0.3f);
+}
+
+TEST(uv_unwrap_by_polygroups_gives_one_flat_island_per_side) {
+ Document doc = makeDoc(cube());
+ const CommandResult r = run(doc, "uv_unwrap", {{"method", std::string("polygroups")}});
+ CHECK(r.ok);
+ const UvTopology topo = buildUvTopology(doc.mesh);
+ CHECK(topo.islandCount == 6);
+ const UvStretchStats st = uvStretchStats(doc.mesh);
+ CHECK(st.mean < 1e-3f); // flat sides: no stretch
+ CHECK(st.flipped == 0.0f);
+ CHECK(uvsWithin(doc.mesh, glm::vec2(0.0f), glm::vec2(1.0f)));
+ CHECK(islandBoxesDisjoint(doc.mesh));
+ // Equal texel density across the sides.
+ const std::vector<float> d = uvIslandDensity(doc.mesh, topo, 2048);
+ for (float x : d) CHECK(std::abs(x - d[0]) < d[0] * 0.01f);
+}
+
+TEST(uv_unwrap_planar_and_conformal_methods) {
+ for (const char* method : {"planar", "conformal", "auto"}) {
+ Document doc = makeDoc(cube(4));
+ uvSeamsFromPolygroups(doc.mesh, cornerTwins(doc.mesh));
+ const CommandResult r = run(doc, "uv_unwrap", {{"method", std::string(method)}});
+ CHECK(r.ok);
+ CHECK(doc.mesh.hasUvs());
+ CHECK(uvsWithin(doc.mesh, glm::vec2(0.0f), glm::vec2(1.0f)));
+ CHECK(flippedTriangles(doc.mesh) == 0);
+ if (std::string(method) != "auto") CHECK(buildUvTopology(doc.mesh).islandCount == 6);
+ }
+}
+
+TEST(uv_unfold_keeps_pins_and_layout) {
+ Document doc = makeDoc(cube(4));
+ CHECK(run(doc, "uv_unwrap", {{"method", std::string("polygroups")}}).ok);
+ const std::vector<glm::vec2> before = doc.mesh.uvs;
+ // Pin one corner after nudging it; Unfold keeps it there.
+ const UvTopology topo = buildUvTopology(doc.mesh);
+ std::vector<uint32_t> corners;
+ for (uint32_t c = 0; c < topo.uvVertex.size(); ++c)
+ if (topo.uvVertex[c] == topo.uvVertex[0]) corners.push_back(c);
+ for (uint32_t c : corners) doc.mesh.uvs[c] += glm::vec2(0.01f, 0.0f);
+ uvSetPins(doc.mesh, corners, true);
+ const glm::vec2 pinned = doc.mesh.uvs[0];
+ CHECK(run(doc, "uv_unwrap", {{"method", std::string("unfold")}}).ok);
+ CHECK(glm::distance(doc.mesh.uvs[0], pinned) < 1e-5f);
+ // The unpinned islands are fitted back where they were.
+ double moved = 0.0;
+ for (size_t c = 0; c < before.size(); ++c) moved = std::max(moved, double(glm::distance(before[c], doc.mesh.uvs[c])));
+ CHECK(moved < 0.05);
+}
+
+TEST(uv_pack_one_tile_and_udim_tiles) {
+ Document doc = makeDoc(cube());
+ CHECK(run(doc, "uv_unwrap", {{"method", std::string("polygroups")}}).ok);
+ // Across four UDIM tiles: six equal squares fit best four to a tile, so two tiles (1001, 1002) hold them
+ // at twice the size one tile would give.
+ CommandResult r = run(doc, "uv_pack", {{"tiles", 4.0}, {"margin", 16.0}});
+ CHECK(r.ok);
+ CHECK(r.message.find("2 UDIM tiles") != std::string::npos);
+ CHECK(uvsWithin(doc.mesh, glm::vec2(0.0f), glm::vec2(4.0f, 1.0f)));
+ const UvTopology topo = buildUvTopology(doc.mesh);
+ std::vector<int> tiles;
+ for (uint32_t t = 0; t < doc.mesh.triangleCount(); ++t)
+ tiles.push_back(udimTile((doc.mesh.uvs[t * 3] + doc.mesh.uvs[t * 3 + 1] + doc.mesh.uvs[t * 3 + 2]) / 3.0f));
+ std::sort(tiles.begin(), tiles.end());
+ tiles.erase(std::unique(tiles.begin(), tiles.end()), tiles.end());
+ CHECK(tiles.size() == 2);
+ CHECK(tiles.front() == 1001 && tiles.back() == 1002);
+ CHECK(islandBoxesDisjoint(doc.mesh));
+ // A fixed texel density spills into as many tiles as it needs.
+ r = run(doc, "uv_pack", {{"density", 256.0}, {"resolution", 1024.0}, {"margin", 4.0}});
+ CHECK(r.ok);
+ const float d = uvMeshDensity(doc.mesh, 1024);
+ CHECK(std::abs(d - 256.0f) < 256.0f * 0.01f);
+ CHECK(r.message.find("UDIM tiles") != std::string::npos);
+ // Back to one tile, with a margin: the islands keep 16 texels apart.
+ r = run(doc, "uv_pack", {{"margin", 16.0}, {"resolution", 1024.0}});
+ CHECK(r.ok);
+ CHECK(uvsWithin(doc.mesh, glm::vec2(0.0f), glm::vec2(1.0f)));
+ CHECK(islandBoxesDisjoint(doc.mesh, -15.0f / 1024.0f)); // boxes at least ~15 texels apart
+}
+
+TEST(uv_pack_rectangles) {
+ // Sixteen quarter-tile squares fill one tile; a seventeenth needs a second; an oversized one never fits.
+ std::vector<glm::vec2> sizes(16, glm::vec2(0.25f)), pos;
+ std::vector<uint8_t> turned;
+ std::vector<int> tile;
+ CHECK(packRectangles(sizes, 1, false, 0.0f, pos, turned, tile) == 1);
+ sizes.push_back(glm::vec2(0.25f));
+ CHECK(packRectangles(sizes, 1, false, 0.0f, pos, turned, tile) == 0);
+ CHECK(packRectangles(sizes, 2, false, 0.0f, pos, turned, tile) == 2);
+ CHECK(packRectangles({glm::vec2(1.5f, 0.1f)}, 4, true, 0.0f, pos, turned, tile) == 0);
+ // A tall strip lies down when turning is allowed.
+ CHECK(packRectangles({glm::vec2(0.1f, 0.9f), glm::vec2(0.9f, 0.9f)}, 1, true, 0.0f, pos, turned, tile) == 1);
+}
+
+TEST(uv_texel_density_set_and_match) {
+ Document doc = makeDoc(cube());
+ CHECK(run(doc, "uv_unwrap", {{"method", std::string("polygroups")}}).ok);
+ // Make the islands differ, then match them.
+ UvTopology topo = buildUvTopology(doc.mesh);
+ std::vector<uint8_t> one(topo.islandCount, 0);
+ one[0] = 1;
+ uvSetDensity(doc.mesh, topo, one, 100.0f, 1024);
+ CHECK(std::abs(uvIslandDensity(doc.mesh, topo, 1024)[0] - 100.0f) < 0.5f);
+ CHECK(run(doc, "uv_density", {{"op", std::string("match")}, {"resolution", 1024.0}}).ok);
+ topo = buildUvTopology(doc.mesh);
+ const std::vector<float> d = uvIslandDensity(doc.mesh, topo, 1024);
+ for (float x : d) CHECK(std::abs(x - d[0]) < d[0] * 0.005f);
+ CHECK(run(doc, "uv_density", {{"op", std::string("set")}, {"value", 512.0}, {"resolution", 1024.0}}).ok);
+ CHECK(std::abs(uvMeshDensity(doc.mesh, 1024) - 512.0f) < 2.0f);
+ CHECK(run(doc, "uv_density", {{"op", std::string("info")}}).message.find("texels per unit") != std::string::npos);
+}
+
+TEST(uv_density_and_stretch_measures) {
+ // A unit square face mapped to the whole 0-1 tile: 1024 texels per unit at 1K, no stretch; squashed 2:1 it
+ // stretches by log2(sqrt 2)... per axis, the worst: half a step.
+ Mesh m;
+ m.positions = {{0, 0, 0}, {1, 0, 0}, {1, 1, 0}, {0, 1, 0}};
+ m.triangles = {{0, 1, 2}, {0, 2, 3}};
+ m.uvs = {{0, 0}, {1, 0}, {1, 1}, {0, 0}, {1, 1}, {0, 1}};
+ std::vector<float> d, s;
+ uvTriangleDensity(m, 1024, d);
+ CHECK(std::abs(d[0] - 1024.0f) < 1e-2f);
+ uvTriangleStretch(m, s);
+ CHECK(std::abs(s[0]) < 1e-5f);
+ for (glm::vec2& u : m.uvs) u.y *= 0.5f;
+ uvTriangleStretch(m, s);
+ CHECK(std::abs(s[0] - 0.5f) < 1e-3f);
+ // Folding one triangle over the other (its own corner moved across the shared diagonal): flipped.
+ m.uvs[5] = glm::vec2(0.9f, 0.1f);
+ uvTriangleStretch(m, s);
+ CHECK(s[1] == -1.0f);
+ CHECK(s[0] >= 0.0f);
+ CHECK(uvHeatColor(-1.0f).z > uvHeatColor(-1.0f).x);
+ CHECK(uvHeatColor(1.0f).x > uvHeatColor(1.0f).y);
+}
+
+TEST(uv_trim_sheet_strips) {
+ std::vector<TrimStrip> strips;
+ std::string err;
+ CHECK(parseTrimStrips("4", strips, err) && strips.size() == 4);
+ CHECK(std::abs(strips[0].v1 - 1.0f) < 1e-6f && std::abs(strips[0].v0 - 0.75f) < 1e-6f);
+ CHECK(parseTrimStrips("0.5,0.25,0.25", strips, err) && strips.size() == 3 && std::abs(strips[0].v0 - 0.5f) < 1e-6f);
+ CHECK(parseTrimStrips("0-0.5;0.5-0.75", strips, err) && strips.size() == 2 && std::abs(strips[1].v1 - 0.75f) < 1e-6f);
+ CHECK(!parseTrimStrips("banana", strips, err));
+
+ Document doc = makeDoc(cube());
+ CHECK(run(doc, "uv_unwrap", {{"method", std::string("polygroups")}}).ok);
+ CHECK(run(doc, "uv_select", {{"op", std::string("polygroup")}, {"group", 1.0}, {"mode", std::string("island")}}).ok);
+ CommandResult r = run(doc, "uv_trim", {{"strip", 2.0}, {"strips", std::string("4")}, {"fit_width", true}});
+ CHECK(r.ok);
+ // The selected island sits in strip 2 (v 0.5 - 0.75) across u 0-1.
+ const UvTopology topo = buildUvTopology(doc.mesh);
+ glm::vec2 lo(1e30f), hi(-1e30f);
+ for (uint32_t t = 0; t < doc.mesh.triangleCount(); ++t) {
+ if (doc.mesh.polygroupAt(t) != 1) continue;
+ for (uint32_t j = 0; j < 3; ++j) lo = glm::min(lo, doc.mesh.uvs[t * 3 + j]), hi = glm::max(hi, doc.mesh.uvs[t * 3 + j]);
+ }
+ CHECK(lo.y >= 0.5f - 1e-4f && hi.y <= 0.75f + 1e-4f);
+ CHECK(std::abs(lo.x) < 1e-4f && std::abs(hi.x - 1.0f) < 1e-4f);
+ CHECK(hi.y - lo.y > 0.2f); // filled the strip's height (less the margin)
+}
+
+TEST(uv_seams_path_polygroups_and_angle) {
+ Document doc = makeDoc(cube(4));
+ CommandResult r = run(doc, "uv_seam", {{"op", std::string("polygroups")}});
+ CHECK(r.ok);
+ CHECK(uvSeamCount(doc.mesh) == 12 * 4); // 12 cube edges, 4 segments each
+ CHECK(run(doc, "uv_seam", {{"op", std::string("clear_all")}}).ok);
+ CHECK(uvSeamCount(doc.mesh) == 0);
+ CHECK(run(doc, "uv_seam", {{"op", std::string("angle")}, {"angle", 45.0}}).ok);
+ CHECK(uvSeamCount(doc.mesh) == 12 * 4);
+ CHECK(run(doc, "uv_seam", {{"op", std::string("clear_all")}}).ok);
+ // A path between opposite corners of the cube: at least 3 x 4 edges long.
+ uint32_t lo = 0, hi = 0;
+ for (uint32_t v = 0; v < doc.mesh.vertexCount(); ++v) {
+ const glm::vec3 p = doc.mesh.positions[v];
+ if (p.x + p.y + p.z < doc.mesh.positions[lo].x + doc.mesh.positions[lo].y + doc.mesh.positions[lo].z) lo = v;
+ if (p.x + p.y + p.z > doc.mesh.positions[hi].x + doc.mesh.positions[hi].y + doc.mesh.positions[hi].z) hi = v;
+ }
+ r = run(doc, "uv_seam", {{"op", std::string("path")}, {"from", double(lo)}, {"to", double(hi)}});
+ CHECK(r.ok);
+ CHECK(uvSeamCount(doc.mesh) >= 8);
+ // Undo takes the seams back.
+ CHECK(doc.undo.undo(doc.mesh, doc.bvh));
+ CHECK(uvSeamCount(doc.mesh) == 0);
+}
+
+TEST(uv_weld_split_straighten) {
+ Document doc = makeDoc(cube(4));
+ CHECK(run(doc, "uv_unwrap", {{"method", std::string("polygroups")}}).ok);
+ // Split one side's faces into two islands by its half.
+ UvTopology topo = buildUvTopology(doc.mesh);
+ const size_t before = topo.islandCount;
+ std::vector<uint8_t> faces(doc.mesh.triangleCount(), 0);
+ for (uint32_t t = 0; t < faces.size(); ++t) {
+ const glm::uvec3 tri = doc.mesh.triangles[t];
+ const glm::vec3 c = (doc.mesh.positions[tri.x] + doc.mesh.positions[tri.y] + doc.mesh.positions[tri.z]) / 3.0f;
+ faces[t] = doc.mesh.polygroupAt(t) == 1 && c.x + c.y + c.z > 0.0f;
+ }
+ doc.uvSelection.mode = UvSelectMode::Face;
+ doc.uvSelection.faces = faces;
+ CHECK(run(doc, "uv_edit", {{"op", std::string("split")}}).ok);
+ topo = buildUvTopology(doc.mesh);
+ CHECK(topo.islandCount == before + 1);
+ // Weld the seam just made: select its edges (vertex mode, both sides) and weld.
+ CHECK(run(doc, "uv_select", {{"op", std::string("seams")}}).ok);
+ CHECK(run(doc, "uv_select", {{"op", std::string("mode")}, {"mode", std::string("vertex")}}).ok);
+ CHECK(run(doc, "uv_edit", {{"op", std::string("weld")}}).ok);
+ CHECK(buildUvTopology(doc.mesh).islandCount == before);
+ // Straighten: some vertices line up.
+ CHECK(run(doc, "uv_select", {{"op", std::string("rect")}, {"u0", 0.0}, {"v0", 0.0}, {"u1", 0.2}, {"v1", 0.2},
+ {"mode", std::string("vertex")}}).ok);
+ if (!doc.uvSelection.empty()) {
+ CHECK(run(doc, "uv_edit", {{"op", std::string("straighten")}}).ok);
+ }
+ // Pins.
+ CHECK(run(doc, "uv_edit", {{"op", std::string("pin")}}).ok || doc.uvSelection.empty());
+ CHECK(run(doc, "uv_edit", {{"op", std::string("clear_pins")}}).ok);
+}
+
+TEST(uv_commands_undo_redo_exactly) {
+ Document doc = makeDoc(cube());
+ CHECK(run(doc, "uv_unwrap", {{"method", std::string("polygroups")}}).ok);
+ const std::vector<glm::vec2> a = doc.mesh.uvs;
+ CHECK(run(doc, "uv_transform", {{"rotate", 30.0}, {"scale", 0.5}, {"move_u", 0.1}}).ok);
+ const std::vector<glm::vec2> b = doc.mesh.uvs;
+ CHECK(a != b);
+ CHECK(run(doc, "uv_pack", {{"tiles", 2.0}}).ok);
+ const std::vector<glm::vec2> c = doc.mesh.uvs;
+ CHECK(doc.undo.undo(doc.mesh, doc.bvh));
+ CHECK(doc.mesh.uvs == b);
+ CHECK(doc.undo.undo(doc.mesh, doc.bvh));
+ CHECK(doc.mesh.uvs == a);
+ CHECK(doc.undo.undo(doc.mesh, doc.bvh)); // the unwrap: no UVs again
+ CHECK(!doc.mesh.hasUvs());
+ CHECK(doc.undo.redo(doc.mesh, doc.bvh));
+ CHECK(doc.mesh.uvs == a);
+ CHECK(doc.undo.redo(doc.mesh, doc.bvh));
+ CHECK(doc.undo.redo(doc.mesh, doc.bvh));
+ CHECK(doc.mesh.uvs == c);
+}
+
+TEST(uv_selection_modes_convert) {
+ Document doc = makeDoc(cube(4));
+ CHECK(run(doc, "uv_unwrap", {{"method", std::string("polygroups")}}).ok);
+ CHECK(run(doc, "uv_select", {{"op", std::string("face")}, {"face", 0.0}, {"mode", std::string("face")}}).ok);
+ CHECK(doc.uvSelection.count() == 1);
+ CHECK(run(doc, "uv_select", {{"op", std::string("mode")}, {"mode", std::string("island")}}).ok);
+ CHECK(doc.uvSelection.count() == doc.mesh.triangleCount() / 6);
+ CHECK(run(doc, "uv_select", {{"op", std::string("mode")}, {"mode", std::string("vertex")}}).ok);
+ CHECK(doc.uvSelection.count() > 0);
+ CHECK(run(doc, "uv_select", {{"op", std::string("invert")}}).ok);
+ CHECK(run(doc, "uv_select", {{"op", std::string("all")}, {"mode", std::string("edge")}}).ok);
+ CHECK(doc.uvSelection.count() == doc.mesh.triangleCount() * 3);
+ CHECK(run(doc, "uv_select", {{"op", std::string("none")}}).ok);
+ CHECK(doc.uvSelection.empty());
+ CHECK(run(doc, "uv_info").message.find("6 islands") != std::string::npos);
+}
+
+TEST(uv_painted_texture_follows_the_new_layout) {
+ // Paint each side of the cube its own colour, then repack: the model looks the same (keep_texture), but
+ // with keep_texture=false the colours slide.
+ Document doc = makeDoc(cube(4));
+ CHECK(run(doc, "uv_unwrap", {{"method", std::string("polygroups")}}).ok);
+ CHECK(run(doc, "texture_create", {{"size", std::string("1024")}}).ok);
+ Mesh& m = doc.mesh;
+ PaintTexture& tex = *m.texture;
+ bakeTexels(m, tex, [&](uint32_t t, float, float, float, int x, int y) {
+ uint8_t* px = &tex.pixels[(size_t(y) * size_t(tex.width) + size_t(x)) * 4];
+ const uint32_t g = m.polygroupAt(t);
+ px[0] = uint8_t(g * 40), px[1] = uint8_t(255 - g * 30), px[2] = uint8_t(g * 20), px[3] = 255;
+ }, true);
+ tex.markAllDirty();
+ auto colourAt = [&](uint32_t t) {
+ const glm::uvec3 tri = m.triangles[t];
+ const glm::vec3 c = (m.positions[tri.x] + m.positions[tri.y] + m.positions[tri.z]) / 3.0f;
+ return sampleTextureAt(m, t, c);
+ };
+ std::vector<glm::vec3> before;
+ for (uint32_t t = 0; t < m.triangleCount(); t += 7) before.push_back(colourAt(t));
+ const CommandResult r = run(doc, "uv_transform", {{"rotate", 90.0}, {"scale", 0.8}});
+ CHECK(r.ok);
+ CHECK(r.message.find("paint moved") != std::string::npos);
+ float worst = 0.0f;
+ size_t k = 0;
+ for (uint32_t t = 0; t < doc.mesh.triangleCount(); t += 7) worst = std::max(worst, glm::length(colourAt(t) - before[k++]));
+ std::printf(" texture after a UV rotate: worst colour change %.4f\n", double(worst));
+ CHECK(worst < 0.03f);
+ // Undo brings back both the UVs and the texels.
+ CHECK(doc.undo.undo(doc.mesh, doc.bvh));
+ k = 0;
+ worst = 0.0f;
+ for (uint32_t t = 0; t < doc.mesh.triangleCount(); t += 7) worst = std::max(worst, glm::length(colourAt(t) - before[k++]));
+ CHECK(worst < 1e-4f);
+}
+
+TEST(uv_project_round_trip_keeps_seams_and_pins) {
+ Document doc = makeDoc(cube(4));
+ CHECK(run(doc, "uv_seam", {{"op", std::string("polygroups")}}).ok);
+ CHECK(run(doc, "uv_unwrap", {{"method", std::string("conformal")}}).ok);
+ std::vector<uint32_t> corners = {0, 1, 2};
+ uvSetPins(doc.mesh, corners, true);
+ const std::string path = tempPath("sf_uv_editor_test.sfproj");
+ CommandRegistry reg;
+ CHECK(reg.execute(doc, "save_project", {{"path", path}}).ok);
+ Document loaded;
+ CHECK(reg.execute(loaded, "open_project", {{"path", path}}).ok);
+ CHECK(loaded.mesh.uvFlags == doc.mesh.uvFlags);
+ CHECK(uvSeamCount(loaded.mesh) == 12 * 4);
+ std::filesystem::remove(path);
+}
+
+TEST(uv_editor_million_triangles_stay_interactive) {
+ // An 8-level icosphere: 1.3M triangles. Topology, measures, a transform and a pack are each well under the
+ // time a frame or a click can take; a full unwrap by polygroups (in the background in the app) takes seconds.
+ Mesh m = makeIcosphere(8);
+ // Eight polygroups by octant, as seams.
+ m.ensurePolygroups();
+ for (uint32_t t = 0; t < m.triangleCount(); ++t) {
+ const glm::vec3 c = m.positions[m.triangles[t].x];
+ m.polygroups[t] = (c.x > 0) + 2 * (c.y > 0) + 4 * (c.z > 0);
+ }
+ std::printf(" %zu triangles\n", m.triangleCount());
+ UvUnwrapOptions o;
+ o.method = UvUnwrapMethod::Polygroups;
+ o.iterations = 4;
+ UvUnwrapResult r;
+ std::string err;
+ auto t0 = std::chrono::steady_clock::now();
+ CHECK(uvUnwrap(m, o, r, err));
+ const double unwrap = secondsSince(t0);
+ m.uvs = r.uvs;
+ t0 = std::chrono::steady_clock::now();
+ const UvTopology topo = buildUvTopology(m);
+ const double topoS = secondsSince(t0);
+ CHECK(topo.islandCount == 8);
+ t0 = std::chrono::steady_clock::now();
+ std::vector<float> s;
+ uvTriangleStretch(m, s);
+ const double stretchS = secondsSince(t0);
+ t0 = std::chrono::steady_clock::now();
+ std::vector<uint32_t> all(m.uvs.size());
+ for (uint32_t c = 0; c < all.size(); ++c) all[c] = c;
+ uvTransform(m.uvs, all, glm::mat2(0.9f), glm::vec2(0.5f), glm::vec2(0.0f));
+ const double moveS = secondsSince(t0);
+ t0 = std::chrono::steady_clock::now();
+ UvPackResult pr;
+ CHECK(uvPack(m, topo, {}, UvPackOptions(), pr, err));
+ const double packS = secondsSince(t0);
+ std::printf(" unwrap %.2f s, topology %.3f s, stretch %.3f s, move %.4f s, pack %.3f s; stretch %.3f\n", unwrap, topoS,
+ stretchS, moveS, packS, double(uvStretchStats(m).mean));
+ CHECK(topoS < 2.0);
+ CHECK(stretchS < 2.0);
+ CHECK(moveS < 0.2);
+ CHECK(packS < 2.0);
+ CHECK(unwrap < 60.0);
+ CHECK(flippedTriangles(m) < m.triangleCount() / 1000);
+}