Free, open-source 3D sculpting for Linux, macOS and Windows: dense meshes, remeshing, painting, built-in AI (image/text to 3D), Send to Unreal, game-ready LODs, Gaussian splats and OpenUSD.
C++ 3d3d-sculptingcppdear-imguidigital-sculptingfbxgame-developmentgaussian-splattinggltfimage-to-3dmcpopenglopenusdsculptingtext-to-3dunreal-engine
Mesh attributes foundation: mask, polypaint, polygroups, hidden, UVs
islandmed52113f6337d9
diff --git a/CMakeLists.txt b/CMakeLists.txtindex 8ca2aefe..4e439795 100644--- a/CMakeLists.txt+++ b/CMakeLists.txt@@ -258,7 +258,10 @@ endif()# --- Tests ---if(SCULPTFORGE_BUILD_TESTS)- add_executable(sculptforge_tests tests/test_main.cpp src/cli/McpServer.cpp)+ # tests/test_main.cpp plus every tests/test_*.cpp (add a file to add tests; see tests/TestHarness.h).+ file(GLOB SCULPTFORGE_TEST_SOURCES CONFIGURE_DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/tests/test_*.cpp)+ add_executable(sculptforge_tests ${SCULPTFORGE_TEST_SOURCES} src/cli/McpServer.cpp)+ target_include_directories(sculptforge_tests PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/tests)target_link_libraries(sculptforge_tests PRIVATE sculptforge_core sculptforge_ai)if(MSVC)target_compile_options(sculptforge_tests PRIVATE /utf-8)diff --git a/docs/architecture-attributes.md b/docs/architecture-attributes.mdnew file mode 100644index 00000000..c03387f0--- /dev/null+++ b/docs/architecture-attributes.md@@ -0,0 +1,60 @@+# Mesh attributes (v0.2 foundation)++`sf::Mesh` (src/core/Mesh.h) carries optional attributes, **empty until a feature needs them**+(no memory cost). When present, the size always matches the mesh.++| Attribute | Type | Size | Empty means |+|--------------|---------------------------|----------------|----------------------|+| `mask` | `std::vector<float>` | vertices | nothing masked |+| `colors` | `std::vector<glm::vec3>` | vertices | no polypaint |+| `polygroups` | `std::vector<uint32_t>` | triangles | every triangle in group 0 |+| `hidden` | `std::vector<uint8_t>` | triangles | all visible |+| `uvs` | `std::vector<glm::vec2>` | 3 x triangles | no UVs (corner order = triangle order) |++- Mask: 0 = free, 1 = fully masked. Colors: **linear** RGB 0..1 (OBJ/PLY convert from sRGB via+ `srgbToLinear`/`linearToSrgb`; glTF COLOR_0 is already linear).+- Read with `maskAt(v)`, `colorAt(v, fallback)`, `polygroupAt(t)`, `triangleHidden(t)`, `vertexHidden(v)`+ (all adjacent triangles hidden); safe on empty attributes. Write after `ensureMask()` /+ `ensureColors()` / `ensurePolygroups()` / `ensureHidden()`; `clearMask()` etc. free them again.+- `rebuildTopology()` drops wrongly sized attributes (`sanitizeAttributes()`): fill them first.++## Telling the renderer+- Vertex attributes (mask, colors): `mesh.markDirty(v)` per vertex or `markAllDirty()`.+- Triangle attributes (hidden, polygroups): set `mesh.facesDirty = true`.+- `RenderSettings` (src/render/Renderer.h): `showPolypaint` (colors replace the base colour),+ `showMask` (masked areas darken), `showPolygroups` (`polygroupColor(id)`, same hash as the shader).+ Hidden triangles are left out of the index buffer. Toggles live in the View menu.++## Preservation through topology changes+| Operation | mask / colors | polygroups / hidden | uvs |+|-----------|---------------|---------------------|-----|+| `loopSubdivide` (Primitives.cpp) | linear interpolation | children inherit | corner midpoints |+| `decimate` / `generateLods` (Decimate.cpp) | exact (vertices are a subset) | surviving faces keep theirs | follow kept vertex (approximate at seams) |+| `voxelRemesh` (Voxel.cpp) | nearest original vertex (`transferVertexAttributes`) | **reset** (visible, group 0) | dropped |+| `weldImported` (Mesh.cpp) | first vertex of each welded group | per kept triangle | per kept triangle |+| primitives, image relief/inflate | empty | empty | empty |++New topology operations must do the same (`transferVertexAttributes(src, dst)` for rebuilt surfaces).++## Undo (src/core/Undo.h)+`UndoRecord` holds sparse `UndoChannel`s: `positions` (layer target), `mask`, `colors`+(per vertex), `hidden`, `polygroups` (per triangle), or a full `mesh` snapshot. Snapshots+(`Document::replaceMeshUndoable`) copy every attribute. Undo allocates a missing attribute+before restoring, so recording values of an empty attribute is fine.+- Strokes: inside `Sculptor::beginStroke/endStroke`, call `sculptor.recordMask(mesh, v)` /+ `recordColor(mesh, v)` **before** writing `mesh.mask[v]` / `mesh.colors[v]`.+- Whole-attribute operations: `doc.undo.push(UndoRecord::captureMask(mesh, "Invert Mask"))`+ (also `captureColors`, `captureHidden`, `capturePolygroups`, optionally for a subset) before changing.++## Brush hooks (src/core/Sculpt.h/.cpp)+- `vertexInfluence(mesh, v)` = 0 for fully hidden vertices, else `1 - mask`.+ `Sculptor::displace` applies it, so **every displacement brush respects mask and hidden**+ (built-in, recipe and Move). Paint brushes should multiply by it; mask brushes must not.+- `brushVertices(mesh, bvh, center, radius, out)` = sphere query minus fully hidden vertices;+ use it instead of `BVH::queryVertices` in new brushes. `Sculptor::mirrors(sym)` gives symmetry.+- Picking: `BVH::raycast` skips hidden triangles, so `App::pick` never lands on them.++## Python and tests+`doc.mask` (N,) float32, `doc.colors` (N,3) float32, `doc.polygroups` (M,) uint32, `doc.hidden` (M,)+uint8: copies, `None` when absent, assignable (`None` clears). New tests: add `tests/test_<feature>.cpp`+including `TestHarness.h` (`TEST`/`CHECK`); CMake globs it. See tests/test_attributes.cpp.diff --git a/src/app/App.cpp b/src/app/App.cppindex ddb442f4..2125f4ba 100644--- a/src/app/App.cpp+++ b/src/app/App.cpp@@ -921,6 +921,9 @@ void App::drawMenuBar() {if (ImGui::BeginMenu("View")) {ImGui::MenuItem("Wireframe", "W", &renderSettings_.wireframe);ImGui::MenuItem("Show Mesh", nullptr, &renderSettings_.showMesh);+ ImGui::MenuItem("Show Polypaint", nullptr, &renderSettings_.showPolypaint);+ ImGui::MenuItem("Show Mask", nullptr, &renderSettings_.showMask);+ ImGui::MenuItem("Show Polygroups", nullptr, &renderSettings_.showPolygroups);ImGui::Separator();ImGui::MenuItem("Layers Panel", nullptr, &showLayersPanel_);ImGui::MenuItem("Game Ready Panel", nullptr, &showGamePanel_);diff --git a/src/core/BVH.cpp b/src/core/BVH.cppindex fd6f4241..d9001628 100644--- a/src/core/BVH.cpp+++ b/src/core/BVH.cpp@@ -127,6 +127,7 @@ uint32_t BVH::nextStamp(std::vector<uint32_t>& stamps, uint32_t& stamp) const {bool BVH::raycast(const Mesh& mesh, const glm::vec3& origin, const glm::vec3& dir, RayHit& hit) const {if (nodes_.empty()) return false;+ const bool skipHidden = mesh.hasHidden();// Avoid 0 * inf = NaN in the slab test for axis-aligned rays.glm::vec3 safeDir = dir;for (int i = 0; i < 3; ++i)@@ -144,6 +145,7 @@ bool BVH::raycast(const Mesh& mesh, const glm::vec3& origin, const glm::vec3& diif (!rayBox(n.box, origin, invDir, best)) continue;if (n.count > 0) {for (uint32_t i = n.first; i < n.first + n.count; ++i) {+ if (skipHidden && mesh.triangleHidden(triIndices_[i])) continue;const auto& t = mesh.triangles[triIndices_[i]];float tt;if (rayTriangle(origin, dir, mesh.positions[t.x], mesh.positions[t.y], mesh.positions[t.z], tt) &&diff --git a/src/core/BVH.h b/src/core/BVH.hindex 901d3730..aaf4b62f 100644--- a/src/core/BVH.h+++ b/src/core/BVH.h@@ -21,8 +21,10 @@ struct RayHit {class BVH {public:void build(const Mesh& mesh);+ // Nearest hit along the ray; hidden triangles (Mesh::hidden) are skipped.bool raycast(const Mesh& mesh, const glm::vec3& origin, const glm::vec3& dir, RayHit& hit) const;// Appends every vertex within `radius` of `center` to `out` (cleared first).+ // Ignores visibility; brushes use sf::brushVertices, which filters hidden ones.void queryVertices(const Mesh& mesh, const glm::vec3& center, float radius, std::vector<uint32_t>& out) const;// Updates bounds after the given vertices moved. Bounds only ever grow// conservatively for ancestors, which keeps queries correct.diff --git a/src/core/Decimate.cpp b/src/core/Decimate.cppindex be759c0c..d70490a7 100644--- a/src/core/Decimate.cpp+++ b/src/core/Decimate.cpp@@ -60,6 +60,7 @@ Mesh decimate(const Mesh& src, size_t targetTriangles) {const auto& P = src.positions;std::vector<glm::uvec3> F = src.triangles;+ std::vector<glm::vec2> FUV = src.uvs.size() == nt * 3 ? src.uvs : std::vector<glm::vec2>(); // per cornerstd::vector<char> faceAlive(nt, 1);std::vector<std::vector<uint32_t>> vFaces(nv);for (uint32_t f = 0; f < nt; ++f)@@ -170,6 +171,12 @@ Mesh decimate(const Mesh& src, size_t targetTriangles) {}if (!ok) continue;+ // Corners that move from u to v take v's UV from a collapsed face+ // (approximate across UV seams).+ glm::vec2 uvOfV(0.0f);+ if (!FUV.empty())+ for (int k = 0; k < 3; ++k)+ if (F[shared[0]][k] == v) uvOfV = FUV[size_t(shared[0]) * 3 + size_t(k)];for (uint32_t f : shared) {faceAlive[f] = 0;--liveFaces;@@ -177,7 +184,10 @@ Mesh decimate(const Mesh& src, size_t targetTriangles) {for (uint32_t f : vFaces[u]) {if (!faceAlive[f]) continue;for (int k = 0; k < 3; ++k)- if (F[f][k] == u) F[f][k] = v;+ if (F[f][k] == u) {+ F[f][k] = v;+ if (!FUV.empty()) FUV[size_t(f) * 3 + size_t(k)] = uvOfV;+ }vFaces[v].push_back(f);}vFaces[u].clear();@@ -208,9 +218,17 @@ Mesh decimate(const Mesh& src, size_t targetTriangles) {t[k] = r;}out.triangles.push_back(t);+ // Surviving faces keep their group, visibility and (updated) corner UVs.+ if (src.polygroups.size() == nt) out.polygroups.push_back(src.polygroups[f]);+ if (src.hidden.size() == nt) out.hidden.push_back(src.hidden[f]);+ if (!FUV.empty()) out.uvs.insert(out.uvs.end(), FUV.begin() + std::ptrdiff_t(f) * 3, FUV.begin() + std::ptrdiff_t(f) * 3 + 3);}out.positions.reserve(kept.size());for (uint32_t v : kept) out.positions.push_back(src.positions[v]);+ if (src.mask.size() == nv)+ for (uint32_t v : kept) out.mask.push_back(src.mask[v]);+ if (src.colors.size() == nv)+ for (uint32_t v : kept) out.colors.push_back(src.colors[v]);if (!src.layers.empty()) {for (uint32_t v : kept) out.base.push_back(src.base[v]);for (const auto& l : src.layers) {diff --git a/src/core/Decimate.h b/src/core/Decimate.hindex a0ea8e7c..af59bc86 100644--- a/src/core/Decimate.h+++ b/src/core/Decimate.h@@ -11,7 +11,9 @@ namespace sf {// Quadric-error-metric edge-collapse decimation (Garland & Heckbert), with// boundary preservation, normal-flip and manifold (link condition) checks.// Collapses keep one endpoint, so output vertices are a subset of the input's-// and sculpt layers / blend shapes carry over exactly.+// and sculpt layers / blend shapes, mask and colours carry over exactly;+// surviving triangles keep their polygroup and hidden flag, and corner UVs+// follow the kept vertex.Mesh decimate(const Mesh& src, size_t targetTriangles);// LOD chain: lods[0] is a copy of `src`, each following level hasdiff --git a/src/core/ImageTo3D.cpp b/src/core/ImageTo3D.cppindex 131056e4..d1bb92bd 100644--- a/src/core/ImageTo3D.cpp+++ b/src/core/ImageTo3D.cpp@@ -3,6 +3,7 @@#include "core/ImageTo3D.h"#include "core/Primitives.h"+#include "core/Sculpt.h"#include <algorithm>#include <cmath>@@ -74,7 +75,7 @@ size_t projectImage(Mesh& mesh, int layer, const Image& image, const glm::mat4&if (u < 0.0f || u > 1.0f || t < 0.0f || t > 1.0f) continue;float facing = glm::dot(mesh.normals[v], glm::normalize(cameraPos - p));float f = std::clamp((facing - 0.05f) / 0.25f, 0.0f, 1.0f); // fade at grazing angles- float h = heightAt(image, u, t, o.invert) * f;+ float h = heightAt(image, u, t, o.invert) * f * vertexInfluence(mesh, v); // respects mask/hidden like brushesif (h <= 0.0f) continue;glm::vec3 d = mesh.normals[v] * (o.depth * h);mesh.positions[v] += d;diff --git a/src/core/Mesh.cpp b/src/core/Mesh.cppindex cba43b86..2a9d5f14 100644--- a/src/core/Mesh.cpp+++ b/src/core/Mesh.cpp@@ -3,6 +3,7 @@#include "core/Mesh.h"#include <algorithm>+#include <cmath>#include <unordered_map>namespace sf {@@ -12,7 +13,45 @@ static glm::vec3 faceNormal(const std::vector<glm::vec3>& p, const glm::uvec3& treturn glm::cross(p[t.y] - p[t.x], p[t.z] - p[t.x]);}+bool Mesh::vertexHidden(uint32_t v) const {+ if (hidden.empty()) return false;+ auto tris = vertexTriangles(v);+ if (tris.empty()) return false;+ for (uint32_t t : tris)+ if (!hidden[t]) return false;+ return true;+}++std::vector<float>& Mesh::ensureMask(float fill) {+ if (mask.size() != positions.size()) mask.assign(positions.size(), fill);+ return mask;+}++std::vector<glm::vec3>& Mesh::ensureColors(const glm::vec3& fill) {+ if (colors.size() != positions.size()) colors.assign(positions.size(), fill);+ return colors;+}++std::vector<uint32_t>& Mesh::ensurePolygroups(uint32_t fill) {+ if (polygroups.size() != triangles.size()) polygroups.assign(triangles.size(), fill);+ return polygroups;+}++std::vector<uint8_t>& Mesh::ensureHidden() {+ if (hidden.size() != triangles.size()) hidden.assign(triangles.size(), 0);+ return hidden;+}++void Mesh::sanitizeAttributes() {+ if (!mask.empty() && mask.size() != positions.size()) clearMask();+ if (!colors.empty() && colors.size() != positions.size()) clearColors();+ 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);+}+void Mesh::rebuildTopology() {+ sanitizeAttributes();const size_t nv = positions.size();vtOffsets_.assign(nv + 1, 0);@@ -47,6 +86,7 @@ void Mesh::rebuildTopology() {stamp_ = 0;normals.resize(nv);topologyDirty = true;+ facesDirty = true;}uint32_t Mesh::nextStamp() {@@ -212,9 +252,21 @@ Mesh weldImported(const Mesh& m, const std::vector<SculptLayer>& layers) {}Mesh welded;for (uint32_t v : kept) welded.positions.push_back(m.positions[v]);- for (const auto& t : m.triangles) {- glm::uvec3 nt(remap[t.x], remap[t.y], remap[t.z]);- if (nt.x != nt.y && nt.y != nt.z && nt.x != nt.z) welded.triangles.push_back(nt);+ const bool vMask = m.mask.size() == m.positions.size(), vColors = m.colors.size() == m.positions.size();+ for (uint32_t v : kept) {+ if (vMask) welded.mask.push_back(m.mask[v]);+ if (vColors) welded.colors.push_back(m.colors[v]);+ }+ const size_t nt = m.triangles.size();+ const bool tGroups = m.polygroups.size() == nt, tHidden = m.hidden.size() == nt, tUvs = m.uvs.size() == nt * 3;+ for (size_t ti = 0; ti < nt; ++ti) {+ const auto& t = m.triangles[ti];+ glm::uvec3 nt3(remap[t.x], remap[t.y], remap[t.z]);+ if (nt3.x == nt3.y || nt3.y == nt3.z || nt3.x == nt3.z) continue;+ welded.triangles.push_back(nt3);+ if (tGroups) welded.polygroups.push_back(m.polygroups[ti]);+ if (tHidden) welded.hidden.push_back(m.hidden[ti]);+ if (tUvs) welded.uvs.insert(welded.uvs.end(), m.uvs.begin() + std::ptrdiff_t(ti * 3), m.uvs.begin() + std::ptrdiff_t(ti * 3 + 3));}if (!layers.empty()) {welded.base = welded.positions;@@ -231,4 +283,77 @@ Mesh weldImported(const Mesh& m, const std::vector<SculptLayer>& layers) {return welded;}+glm::vec3 srgbToLinear(const glm::vec3& c) {+ glm::vec3 out;+ for (int i = 0; i < 3; ++i) {+ const float x = std::clamp(c[i], 0.0f, 1.0f);+ out[i] = x <= 0.04045f ? x / 12.92f : std::pow((x + 0.055f) / 1.055f, 2.4f);+ }+ return out;+}++glm::vec3 linearToSrgb(const glm::vec3& c) {+ glm::vec3 out;+ for (int i = 0; i < 3; ++i) {+ const float x = std::clamp(c[i], 0.0f, 1.0f);+ out[i] = x <= 0.0031308f ? x * 12.92f : 1.055f * std::pow(x, 1.0f / 2.4f) - 0.055f;+ }+ return out;+}++void transferVertexAttributes(const Mesh& src, Mesh& dst) {+ const bool wantMask = src.mask.size() == src.positions.size() && !src.mask.empty();+ const bool wantColors = src.colors.size() == src.positions.size() && !src.colors.empty();+ if ((!wantMask && !wantColors) || dst.positions.empty()) return;++ // Uniform hash grid with about one source vertex per cell.+ const AABB box = src.bounds();+ const glm::vec3 ext = box.extent();+ const float longest = std::max({ext.x, ext.y, ext.z, 1e-12f});+ const float cell = std::max(longest / std::max(1.0f, std::cbrt(float(src.positions.size()))), longest * 1e-4f);+ constexpr int kOffset = 1 << 20;+ auto cellOf = [&](const glm::vec3& p) { return glm::ivec3(glm::floor((p - box.min) / cell)); };+ auto key = [](const glm::ivec3& c) {+ return (uint64_t(uint32_t(c.x + kOffset) & 0x1fffffu) << 42) | (uint64_t(uint32_t(c.y + kOffset) & 0x1fffffu) << 21) |+ uint64_t(uint32_t(c.z + kOffset) & 0x1fffffu);+ };+ std::unordered_map<uint64_t, std::vector<uint32_t>> grid;+ grid.reserve(src.positions.size());+ for (uint32_t v = 0; v < src.positions.size(); ++v) grid[key(cellOf(src.positions[v]))].push_back(v);+ const int gridCells = int(std::ceil(longest / cell)) + 2;++ if (wantMask) dst.mask.assign(dst.positions.size(), 0.0f);+ if (wantColors) dst.colors.assign(dst.positions.size(), glm::vec3(1.0f));+ for (size_t i = 0; i < dst.positions.size(); ++i) {+ const glm::vec3 p = dst.positions[i];+ const glm::ivec3 c = cellOf(p);+ const glm::vec3 outside = glm::max(glm::max(box.min - p, p - box.max), glm::vec3(0.0f));+ const int maxRing = gridCells + int(std::ceil(glm::length(outside) / cell));+ float best = std::numeric_limits<float>::max();+ uint32_t bestV = 0;+ // Search shells of growing Chebyshev radius; stop once nothing closer can remain.+ for (int r = 0; r <= maxRing; ++r) {+ for (int dz = -r; dz <= r; ++dz)+ for (int dy = -r; dy <= r; ++dy)+ for (int dx = -r; dx <= r; ++dx) {+ if (std::max({std::abs(dx), std::abs(dy), std::abs(dz)}) != r) continue;+ auto it = grid.find(key(c + glm::ivec3(dx, dy, dz)));+ if (it == grid.end()) continue;+ for (uint32_t v : it->second) {+ const glm::vec3 d = src.positions[v] - p;+ const float d2 = glm::dot(d, d);+ if (d2 < best) {+ best = d2;+ bestV = v;+ }+ }+ }+ if (best < std::numeric_limits<float>::max() && std::sqrt(best) <= float(r) * cell) break;+ }+ if (wantMask) dst.mask[i] = src.mask[bestV];+ if (wantColors) dst.colors[i] = src.colors[bestV];+ }+ dst.markAllDirty();+}+} // namespace sfdiff --git a/src/core/Mesh.h b/src/core/Mesh.hindex f362ef3e..b4cf630d 100644--- a/src/core/Mesh.h+++ b/src/core/Mesh.h@@ -38,12 +38,54 @@ struct SculptLayer {};// Triangle mesh with vertex adjacency, suitable for sculpting.+//+// Optional attributes (see docs/architecture-attributes.md) are empty until+// a feature needs them, so plain meshes pay nothing. When present their size+// always matches the vertex / triangle / corner count; rebuildTopology()+// drops any that don't.class Mesh {public:std::vector<glm::vec3> positions;std::vector<glm::vec3> normals;std::vector<glm::uvec3> triangles;+ // Per vertex: mask (0 = free, 1 = fully masked) and polypaint (linear RGB, 0..1).+ std::vector<float> mask;+ std::vector<glm::vec3> colors;+ // Per triangle: polygroup id (empty = everything in group 0) and hidden flag (empty = all visible).+ std::vector<uint32_t> polygroups;+ std::vector<uint8_t> hidden;+ // Per triangle corner (3 per triangle, in triangle order): texture coordinates.+ std::vector<glm::vec2> uvs;++ bool hasMask() const { return !mask.empty(); }+ bool hasColors() const { return !colors.empty(); }+ bool hasPolygroups() const { return !polygroups.empty(); }+ bool hasHidden() const { return !hidden.empty(); }+ bool hasUvs() const { return !uvs.empty(); }++ float maskAt(uint32_t v) const { return mask.empty() ? 0.0f : mask[v]; }+ glm::vec3 colorAt(uint32_t v, const glm::vec3& fallback = glm::vec3(1.0f)) const {+ return colors.empty() ? fallback : colors[v];+ }+ uint32_t polygroupAt(uint32_t t) const { return polygroups.empty() ? 0u : polygroups[t]; }+ bool triangleHidden(uint32_t t) const { return !hidden.empty() && hidden[t] != 0; }+ // True when every triangle around `v` is hidden (such vertices must not be edited).+ bool vertexHidden(uint32_t v) const;++ // Allocate an attribute (no-op if present); returns it for convenience.+ std::vector<float>& ensureMask(float fill = 0.0f);+ std::vector<glm::vec3>& ensureColors(const glm::vec3& fill = glm::vec3(1.0f));+ std::vector<uint32_t>& ensurePolygroups(uint32_t fill = 0);+ std::vector<uint8_t>& ensureHidden();+ // Free an attribute again once it holds only its default (e.g. after "clear mask" / "show all").+ void clearMask() { std::vector<float>().swap(mask); }+ void clearColors() { std::vector<glm::vec3>().swap(colors); }+ void clearPolygroups() { std::vector<uint32_t>().swap(polygroups); }+ void clearHidden() { std::vector<uint8_t>().swap(hidden); }+ // Drops attributes whose size no longer matches the mesh (called by rebuildTopology).+ void sanitizeAttributes();+// Sculpt layers. While any exist, `base` holds the positions with every// layer at zero and positions == base + sum(layer.weight * layer.delta).std::vector<glm::vec3> base;@@ -81,9 +123,12 @@ public:// GPU synchronisation state: [dirtyBegin, dirtyEnd) needs re-uploading,// topologyDirty means everything (including indices) does.+ // Vertex attributes (mask, colours) share the vertex range; facesDirty+ // means per-triangle state (hidden, polygroups) needs re-uploading.uint32_t dirtyBegin = std::numeric_limits<uint32_t>::max();uint32_t dirtyEnd = 0;bool topologyDirty = true;+ bool facesDirty = true;void markDirty(uint32_t v) {dirtyBegin = std::min(dirtyBegin, v);@@ -93,6 +138,12 @@ public:dirtyBegin = std::numeric_limits<uint32_t>::max();dirtyEnd = 0;topologyDirty = false;+ facesDirty = false;+ }+ void markAllDirty() {+ if (positions.empty()) return;+ dirtyBegin = 0;+ dirtyEnd = static_cast<uint32_t>(positions.size());}private:@@ -114,6 +165,17 @@ void taubinSmooth(Mesh& m, int iterations);// Merges coincident vertices (UV/normal seams from importers), drops// degenerate triangles and builds topology and normals. `layers` (optional)// hold per-vertex deltas indexed like m.positions and become sculpt layers.+// Optional attributes of `m` are carried over (vertex ones from the first+// vertex of each welded group, triangle/corner ones per kept triangle).Mesh weldImported(const Mesh& m, const std::vector<SculptLayer>& layers = {});+// Mesh::colors are linear RGB; files that store display colours (OBJ, PLY) convert.+glm::vec3 srgbToLinear(const glm::vec3& c);+glm::vec3 linearToSrgb(const glm::vec3& c);++// Gives every vertex of `dst` the mask and colour of the nearest vertex of+// `src` (only the attributes `src` has). For rebuilt surfaces such as voxel+// remesh or re-imported scans; needs no topology.+void transferVertexAttributes(const Mesh& src, Mesh& dst);+} // namespace sfdiff --git a/src/core/Primitives.cpp b/src/core/Primitives.cppindex c3a6a021..0a34faef 100644--- a/src/core/Primitives.cpp+++ b/src/core/Primitives.cpp@@ -4,6 +4,7 @@#include <cmath>#include <numbers>+#include <type_traits>#include <unordered_map>namespace sf {@@ -146,8 +147,22 @@ Mesh loopSubdivide(const Mesh& src) {for (const auto& l : src.layers) out.layers.push_back({l.name, subdivideAttribute(l.delta), l.weight});}- out.triangles.reserve(src.triangles.size() * 4);- for (const auto& t : src.triangles) {+ // Mask and polypaint are interpolated linearly (old vertices keep their+ // value, edge vertices take the average) so painted borders stay crisp.+ auto interpolateLinear = [&](const auto& A) {+ std::remove_cvref_t<decltype(A)> result(next);+ for (uint32_t v = 0; v < nv; ++v) result[v] = A[v];+ for (const auto& [key, e] : edges) result[e.index] = (A[uint32_t(key >> 32)] + A[uint32_t(key & 0xffffffffu)]) * 0.5f;+ return result;+ };+ if (src.mask.size() == nv) out.mask = interpolateLinear(src.mask);+ if (src.colors.size() == nv) out.colors = interpolateLinear(src.colors);++ const size_t nt = src.triangles.size();+ const bool groups = src.polygroups.size() == nt, hidden = src.hidden.size() == nt, uvs = src.uvs.size() == nt * 3;+ out.triangles.reserve(nt * 4);+ for (size_t ti = 0; ti < nt; ++ti) {+ const auto& t = src.triangles[ti];uint32_t ab = edges.at(edgeKey(t.x, t.y)).index;uint32_t bc = edges.at(edgeKey(t.y, t.z)).index;uint32_t ca = edges.at(edgeKey(t.z, t.x)).index;@@ -155,6 +170,14 @@ Mesh loopSubdivide(const Mesh& src) {out.triangles.push_back({t.y, bc, ab});out.triangles.push_back({t.z, ca, bc});out.triangles.push_back({ab, bc, ca});+ // Children inherit their parent's group and visibility.+ if (groups) out.polygroups.insert(out.polygroups.end(), 4, src.polygroups[ti]);+ if (hidden) out.hidden.insert(out.hidden.end(), 4, src.hidden[ti]);+ if (uvs) {+ const glm::vec2 ua = src.uvs[ti * 3], ub = src.uvs[ti * 3 + 1], uc = src.uvs[ti * 3 + 2];+ const glm::vec2 uab = (ua + ub) * 0.5f, ubc = (ub + uc) * 0.5f, uca = (uc + ua) * 0.5f;+ out.uvs.insert(out.uvs.end(), {ua, uab, uca, ub, ubc, uab, uc, uca, ubc, uab, ubc, uca});+ }}finalize(out);return out;diff --git a/src/core/Primitives.h b/src/core/Primitives.hindex cc965172..3b2d50ee 100644--- a/src/core/Primitives.h+++ b/src/core/Primitives.h@@ -10,6 +10,8 @@ namespace sf {Mesh makeIcosphere(int subdivisions, float radius = 1.0f);Mesh makePlane(int resolution, float size = 2.0f);// Loop subdivision (smooth; boundaries follow the cubic B-spline rule).+// Layers are subdivided with the same stencils; mask/colours/UVs are+// interpolated linearly and polygroups/hidden flags are inherited.Mesh loopSubdivide(const Mesh& mesh);} // namespace sfdiff --git a/src/core/Sculpt.cpp b/src/core/Sculpt.cppindex 36b1041f..760390da 100644--- a/src/core/Sculpt.cpp+++ b/src/core/Sculpt.cpp@@ -21,13 +21,18 @@ const char* brushName(BrushType type) {}}-namespace {--float falloff(float dist, float radius) {+float brushFalloff(float dist, float radius) {float t = std::clamp(1.0f - dist / radius, 0.0f, 1.0f);return t * t * (3.0f - 2.0f * t);}+void brushVertices(const Mesh& mesh, const BVH& bvh, const glm::vec3& center, float radius, std::vector<uint32_t>& out) {+ bvh.queryVertices(mesh, center, radius, out);+ if (mesh.hasHidden()) std::erase_if(out, [&](uint32_t v) { return mesh.vertexHidden(v); });+}++namespace {+glm::vec3 projectOnPlane(const glm::vec3& v, const glm::vec3& n) { return v - n * glm::dot(v, n); }// --- Procedural 3D patterns (deterministic, so texture sticks to the surface) ---@@ -127,10 +132,14 @@ bool Sculptor::beginStroke(const Mesh& mesh, std::string label, int layer) {record_.layer = layer;if (touchStamp_.size() != mesh.vertexCount()) {touchStamp_.assign(mesh.vertexCount(), 0);+ maskStamp_.assign(mesh.vertexCount(), 0);+ colorStamp_.assign(mesh.vertexCount(), 0);stamp_ = 0;}if (++stamp_ == 0) {std::fill(touchStamp_.begin(), touchStamp_.end(), 0);+ std::fill(maskStamp_.begin(), maskStamp_.end(), 0);+ std::fill(colorStamp_.begin(), colorStamp_.end(), 0);stamp_ = 1;}active_ = true;@@ -140,15 +149,30 @@ bool Sculptor::beginStroke(const Mesh& mesh, std::string label, int layer) {void Sculptor::touch(Mesh& mesh, uint32_t v) {if (touchStamp_[v] == stamp_) return;touchStamp_[v] = stamp_;- record_.indices.push_back(v);- record_.positions.push_back(mesh.layerTarget(layer_)[v]);+ record_.positions.add(v, mesh.layerTarget(layer_)[v]);+}++void Sculptor::recordMask(const Mesh& mesh, uint32_t v) {+ if (!active_ || maskStamp_[v] == stamp_) return;+ maskStamp_[v] = stamp_;+ record_.mask.add(v, mesh.maskAt(v));+}++void Sculptor::recordColor(const Mesh& mesh, uint32_t v) {+ if (!active_ || colorStamp_[v] == stamp_) return;+ colorStamp_[v] = stamp_;+ record_.colors.add(v, mesh.colorAt(v));}-// Moves a vertex and attributes the offset to the active layer.+// Moves a vertex and attributes the offset to the active layer. Masked and+// hidden vertices are attenuated here, once, for every brush.void Sculptor::displace(Mesh& mesh, uint32_t v, const glm::vec3& d) {+ const float k = vertexInfluence(mesh, v);+ if (k <= 0.0f) return;touch(mesh, v);- mesh.positions[v] += d;- if (!mesh.layers.empty()) mesh.layerTarget(layer_)[v] += d / mesh.layerTargetWeight(layer_);+ const glm::vec3 dk = d * k;+ mesh.positions[v] += dk;+ if (!mesh.layers.empty()) mesh.layerTarget(layer_)[v] += dk / mesh.layerTargetWeight(layer_);}UndoRecord Sculptor::endStroke() {@@ -168,7 +192,7 @@ void Sculptor::dab(Mesh& mesh, BVH& bvh, BrushType type, const DabParams& p, Sym}void Sculptor::dabSingle(Mesh& mesh, BVH& bvh, BrushType type, const DabParams& p) {- bvh.queryVertices(mesh, p.center, p.radius, verts_);+ brushVertices(mesh, bvh, p.center, p.radius, verts_);if (verts_.empty()) return;auto& pos = mesh.positions;@@ -183,7 +207,7 @@ void Sculptor::dabSingle(Mesh& mesh, BVH& bvh, BrushType type, const DabParams&glm::vec3 areaNormal(0.0f), areaCenter(0.0f);float wsum = 0.0f;for (uint32_t v : verts_) {- float w = falloff(glm::distance(pos[v], p.center), p.radius);+ float w = brushFalloff(glm::distance(pos[v], p.center), p.radius);areaNormal += nrm[v] * w;areaCenter += pos[v] * w;wsum += w;@@ -201,7 +225,7 @@ void Sculptor::dabSingle(Mesh& mesh, BVH& bvh, BrushType type, const DabParams&for (size_t i = 0; i < verts_.size(); ++i) {const uint32_t v = verts_[i];const glm::vec3& x = pos[v];- const float f = falloff(glm::distance(x, p.center), r);+ const float f = brushFalloff(glm::distance(x, p.center), r);glm::vec3 d(0.0f);switch (type) {@@ -268,7 +292,7 @@ void Sculptor::dabRecipe(Mesh& mesh, BVH& bvh, const BrushRecipe& recipe, const}void Sculptor::dabRecipeSingle(Mesh& mesh, BVH& bvh, const BrushRecipe& r, const DabParams& p) {- bvh.queryVertices(mesh, p.center, p.radius, verts_);+ brushVertices(mesh, bvh, p.center, p.radius, verts_);if (verts_.empty()) return;const auto& pos = mesh.positions;const auto& nrm = mesh.normals;@@ -387,9 +411,9 @@ void Sculptor::beginGrab(Mesh& mesh, BVH& bvh, const DabParams& p, Symmetry sym)if (!active_) return;for (const glm::vec3& m : mirrors(sym)) {glm::vec3 c = p.center * m;- bvh.queryVertices(mesh, c, p.radius, verts_);+ brushVertices(mesh, bvh, c, p.radius, verts_);for (uint32_t v : verts_) {- float w = falloff(glm::distance(mesh.positions[v], c), p.radius) *+ float w = brushFalloff(glm::distance(mesh.positions[v], c), p.radius) *std::clamp(p.strength * 2.0f, 0.0f, 1.0f);if (w <= 0.0f) continue;grab_.push_back({v, w, m});diff --git a/src/core/Sculpt.h b/src/core/Sculpt.hindex 6c58df4b..2aa1f97c 100644--- a/src/core/Sculpt.h+++ b/src/core/Sculpt.h@@ -31,6 +31,21 @@ struct Symmetry {bool x = true, y = false, z = false;};+// --- Shared brush helpers (every brush, including future paint/mask brushes, goes through these) ---++// Strength multiplier for vertex `v`: 0 if every triangle around it is+// hidden, otherwise 1 - mask. Applied centrally by Sculptor::displace, so+// all displacement brushes respect mask and visibility. Paint brushes should+// scale by it too; brushes that edit the mask itself must not.+inline float vertexInfluence(const Mesh& mesh, uint32_t v) {+ if (mesh.hasHidden() && mesh.vertexHidden(v)) return 0.0f;+ return 1.0f - mesh.maskAt(v);+}+// Vertices within `radius` of `center` that a brush may touch (fully hidden ones excluded).+void brushVertices(const Mesh& mesh, const BVH& bvh, const glm::vec3& center, float radius, std::vector<uint32_t>& out);+// Smoothstep brush falloff: 1 at the centre, 0 at `radius`.+float brushFalloff(float dist, float radius);+// Applies brush dabs to a mesh, keeping normals and the BVH in sync and// recording the original positions of every touched vertex for undo.class Sculptor {@@ -46,9 +61,18 @@ public:void beginGrab(Mesh& mesh, BVH& bvh, const DabParams& p, Symmetry sym);void grab(Mesh& mesh, BVH& bvh, const glm::vec3& delta);+ // Brushes that change mask or polypaint call these before writing+ // mesh.mask[v] / mesh.colors[v] (after ensureMask()/ensureColors()), so+ // the stroke's undo step restores them. Each vertex is recorded once per stroke.+ void recordMask(const Mesh& mesh, uint32_t v);+ void recordColor(const Mesh& mesh, uint32_t v);+UndoRecord endStroke();bool strokeActive() const { return active_; }+ // Mirror sign vectors for the enabled symmetry axes (always starts with (1,1,1)).+ static std::vector<glm::vec3> mirrors(Symmetry sym);+private:struct GrabEntry {uint32_t vertex;@@ -59,13 +83,13 @@ private:void dabSingle(Mesh& mesh, BVH& bvh, BrushType type, const DabParams& p);void dabRecipeSingle(Mesh& mesh, BVH& bvh, const BrushRecipe& r, const DabParams& p);void touch(Mesh& mesh, uint32_t v);+ // The one place brushes move vertices: scales `d` by vertexInfluence().void displace(Mesh& mesh, uint32_t v, const glm::vec3& d);- static std::vector<glm::vec3> mirrors(Symmetry sym);bool active_ = false;int layer_ = -1;UndoRecord record_;- std::vector<uint32_t> touchStamp_;+ std::vector<uint32_t> touchStamp_, maskStamp_, colorStamp_;uint32_t stamp_ = 0;std::vector<uint32_t> verts_;diff --git a/src/core/Undo.cpp b/src/core/Undo.cppindex 6c622230..263ecbe1 100644--- a/src/core/Undo.cpp+++ b/src/core/Undo.cpp@@ -7,14 +7,63 @@namespace sf {size_t UndoRecord::approxBytes() const {- size_t bytes = indices.size() * sizeof(uint32_t) + positions.size() * sizeof(glm::vec3);+ size_t bytes = positions.bytes() + mask.bytes() + colors.bytes() + hidden.bytes() + polygroups.bytes();if (mesh)bytes += mesh->vertexCount() * ((2 + (mesh->base.empty() ? 0 : 1 + mesh->layers.size())) * sizeof(glm::vec3) +8 * sizeof(uint32_t)) +- mesh->triangleCount() * (sizeof(glm::uvec3) + sizeof(glm::vec3) + 4 * sizeof(uint32_t));+ mesh->triangleCount() * (sizeof(glm::uvec3) + sizeof(glm::vec3) + 4 * sizeof(uint32_t)) ++ mesh->mask.size() * sizeof(float) + mesh->colors.size() * sizeof(glm::vec3) ++ mesh->polygroups.size() * sizeof(uint32_t) + mesh->hidden.size() + mesh->uvs.size() * sizeof(glm::vec2);return bytes;}+namespace {++// Records `get(i)` for the listed elements, or for all `count` when `which` is empty.+template <class T, class Get>+void captureChannel(UndoChannel<T>& ch, size_t count, std::span<const uint32_t> which, Get get) {+ if (which.empty()) {+ ch.indices.resize(count);+ ch.values.resize(count);+ for (uint32_t i = 0; i < count; ++i) {+ ch.indices[i] = i;+ ch.values[i] = get(i);+ }+ return;+ }+ for (uint32_t i : which) ch.add(i, get(i));+}++} // namespace++UndoRecord UndoRecord::captureMask(const Mesh& mesh, std::string label, std::span<const uint32_t> verts) {+ UndoRecord r;+ r.label = std::move(label);+ captureChannel(r.mask, mesh.vertexCount(), verts, [&](uint32_t v) { return mesh.maskAt(v); });+ return r;+}++UndoRecord UndoRecord::captureColors(const Mesh& mesh, std::string label, std::span<const uint32_t> verts) {+ UndoRecord r;+ r.label = std::move(label);+ captureChannel(r.colors, mesh.vertexCount(), verts, [&](uint32_t v) { return mesh.colorAt(v); });+ return r;+}++UndoRecord UndoRecord::captureHidden(const Mesh& mesh, std::string label, std::span<const uint32_t> tris) {+ UndoRecord r;+ r.label = std::move(label);+ captureChannel(r.hidden, mesh.triangleCount(), tris, [&](uint32_t t) { return uint8_t(mesh.triangleHidden(t)); });+ return r;+}++UndoRecord UndoRecord::capturePolygroups(const Mesh& mesh, std::string label, std::span<const uint32_t> tris) {+ UndoRecord r;+ r.label = std::move(label);+ captureChannel(r.polygroups, mesh.triangleCount(), tris, [&](uint32_t t) { return mesh.polygroupAt(t); });+ return r;+}+void UndoStack::push(UndoRecord record) {if (record.empty()) return;undo_.push_back(std::move(record));@@ -30,11 +79,29 @@ void UndoStack::apply(UndoRecord& r, Mesh& mesh, BVH& bvh) {bvh.build(mesh);return;}- auto& target = mesh.layerTarget(r.layer);- for (size_t i = 0; i < r.indices.size(); ++i) std::swap(target[r.indices[i]], r.positions[i]);- mesh.evaluate(r.indices);- mesh.updateNormals(r.indices);- bvh.refit(mesh, r.indices);+ if (!r.positions.empty()) {+ r.positions.swapWith(mesh.layerTarget(r.layer));+ mesh.evaluate(r.positions.indices);+ mesh.updateNormals(r.positions.indices);+ bvh.refit(mesh, r.positions.indices);+ }+ if (!r.mask.empty()) {+ r.mask.swapWith(mesh.ensureMask());+ for (uint32_t v : r.mask.indices) mesh.markDirty(v);+ }+ if (!r.colors.empty()) {+ r.colors.swapWith(mesh.ensureColors());+ for (uint32_t v : r.colors.indices) mesh.markDirty(v);+ }+ // Picking reads `hidden` directly, so the BVH needs no update.+ if (!r.hidden.empty()) {+ r.hidden.swapWith(mesh.ensureHidden());+ mesh.facesDirty = true;+ }+ if (!r.polygroups.empty()) {+ r.polygroups.swapWith(mesh.ensurePolygroups());+ mesh.facesDirty = true;+ }}bool UndoStack::undo(Mesh& mesh, BVH& bvh) {diff --git a/src/core/Undo.h b/src/core/Undo.hindex 3ad74f12..e8d0dbf0 100644--- a/src/core/Undo.h+++ b/src/core/Undo.h@@ -7,23 +7,59 @@#include <deque>#include <memory>+#include <span>#include <string>#include <vector>namespace sf {-// One undoable step. Either a sparse set of per-vertex values of the stroke's-// target array (positions, layer base or a layer's offsets; see-// Mesh::layerTarget) or a full mesh snapshot (topology/layer-set changes).+// Sparse old values of one mesh array: values[i] belongs to element indices[i].+template <class T>+struct UndoChannel {+ std::vector<uint32_t> indices;+ std::vector<T> values;++ bool empty() const { return indices.empty(); }+ void add(uint32_t index, const T& value) {+ indices.push_back(index);+ values.push_back(value);+ }+ // Exchanges the stored values with `target`, so the channel then holds the inverse.+ void swapWith(std::vector<T>& target) {+ for (size_t i = 0; i < indices.size(); ++i) std::swap(target[indices[i]], values[i]);+ }+ size_t bytes() const { return indices.size() * (sizeof(uint32_t) + sizeof(T)); }+};++// One undoable step: any mix of sparse channels, or a full mesh snapshot+// (topology/layer-set changes; the snapshot holds every attribute).+// - positions: the stroke's target array (positions, layer base or a layer's+// offsets; see Mesh::layerTarget), selected by `layer`+// - mask / colors: per-vertex mask and polypaint+// - hidden / polygroups: per-triangle visibility and group ids+// Record old values before changing them (ensureX() the attribute first);+// undo allocates a missing attribute so values can always be restored.struct UndoRecord {std::string label;int layer = -1;- std::vector<uint32_t> indices;- std::vector<glm::vec3> positions;+ UndoChannel<glm::vec3> positions;+ UndoChannel<float> mask;+ UndoChannel<glm::vec3> colors;+ UndoChannel<uint8_t> hidden;+ UndoChannel<uint32_t> polygroups;std::unique_ptr<Mesh> mesh;- bool empty() const { return indices.empty() && !mesh; }+ bool empty() const {+ return positions.empty() && mask.empty() && colors.empty() && hidden.empty() && polygroups.empty() && !mesh;+ }size_t approxBytes() const;++ // Convenience snapshots of whole attributes (or of `elements` only), e.g.+ // before "mask all", "invert mask", "fill color" or "hide group".+ static UndoRecord captureMask(const Mesh& mesh, std::string label, std::span<const uint32_t> verts = {});+ static UndoRecord captureColors(const Mesh& mesh, std::string label, std::span<const uint32_t> verts = {});+ static UndoRecord captureHidden(const Mesh& mesh, std::string label, std::span<const uint32_t> tris = {});+ static UndoRecord capturePolygroups(const Mesh& mesh, std::string label, std::span<const uint32_t> tris = {});};class UndoStack {diff --git a/src/core/Voxel.cpp b/src/core/Voxel.cppindex 81f17abb..7d21c9e8 100644--- a/src/core/Voxel.cpp+++ b/src/core/Voxel.cpp@@ -283,6 +283,9 @@ Mesh voxelRemesh(const Mesh& mesh, int resolution, std::string* error) {// Voxels touched by the surface count as solid, which puts the result half a voxel outside.for (size_t v = 0; v < out.vertexCount(); ++v) out.positions[v] -= out.normals[v] * (0.5f * grid.cell);out.recomputeAllNormals();+ // Mask and polypaint follow the nearest original vertex; polygroups, hidden+ // flags and UVs don't survive a rebuild (everything becomes visible group 0).+ transferVertexAttributes(mesh, out);return out;}diff --git a/src/core/Voxel.h b/src/core/Voxel.hindex 23dd0f66..50fd1dd7 100644--- a/src/core/Voxel.h+++ b/src/core/Voxel.h@@ -47,6 +47,8 @@ void rasterizeMeshShell(const Mesh& mesh, VoxelGrid& grid);// Rebuilds the mesh as an even, watertight surface (`resolution` cells across// its longest side). Overlapping parts are merged. Sculpt layers are baked.+// Mask and colours transfer from the nearest original vertex; polygroups,+// hidden flags and UVs reset (all visible, group 0, no UVs).Mesh voxelRemesh(const Mesh& mesh, int resolution, std::string* error = nullptr);} // namespace sfdiff --git a/src/io/GltfIO.cpp b/src/io/GltfIO.cppindex fc269454..f43612cf 100644--- a/src/io/GltfIO.cpp+++ b/src/io/GltfIO.cpp@@ -128,6 +128,8 @@ bool saveGlb(const std::string& path, const Mesh& mesh, const std::string& name,int posAcc = addVec3(baseMesh.positions, true);int nrmAcc = addVec3(baseMesh.normals, false);+ const bool colors = mesh.hasColors() && mesh.colors.size() == mesh.vertexCount();+ int colorAcc = colors ? addVec3(mesh.colors, false) : -1; // polypaint as COLOR_0 (linear)size_t idxOff = bin.append(mesh.triangles.data(), mesh.triangleCount() * sizeof(glm::uvec3));views.push_back({idxOff, mesh.triangleCount() * sizeof(glm::uvec3), true});@@ -142,7 +144,9 @@ bool saveGlb(const std::string& path, const Mesh& mesh, const std::string& name,json << "{\"asset\":{\"version\":\"2.0\",\"generator\":\"SculptForge\"},\"scene\":0,"<< "\"scenes\":[{\"nodes\":[0]}],\"nodes\":[{\"mesh\":0,\"name\":\"" << jsonEscape(name) << "\"}],"<< "\"meshes\":[{\"name\":\"" << jsonEscape(name) << "\",\"primitives\":[{\"attributes\":{\"POSITION\":"- << posAcc << ",\"NORMAL\":" << nrmAcc << "},\"indices\":" << idxAcc << ",\"mode\":4";+ << posAcc << ",\"NORMAL\":" << nrmAcc;+ if (colors) json << ",\"COLOR_0\":" << colorAcc;+ json << "},\"indices\":" << idxAcc << ",\"mode\":4";if (!mesh.layers.empty()) {json << ",\"targets\":[";for (size_t i = 0; i < targetAccs.size(); ++i) json << (i ? "," : "") << "{\"POSITION\":" << targetAccs[i] << "}";@@ -542,6 +546,21 @@ bool loadGltf(const std::string& path, Mesh& out, std::string& error, SplatCloud}const uint32_t baseIndex = uint32_t(m.positions.size());for (const auto& p : pos) m.positions.push_back(glm::vec3(world * glm::vec4(p, 1.0f)));+ // Vertex colours (COLOR_0 is linear RGB or RGBA); primitives without them are white.+ const Json& colorAcc = prim["attributes"]["COLOR_0"];+ if (colorAcc.isNumber()) {+ const int ci = int(colorAcc.asNumber());+ const int comps = r.doc["accessors"][size_t(ci)]["type"].asString() == "VEC4" ? 4 : 3;+ std::vector<float> c;+ if (!r.readFloats(ci, comps, c)) return false;+ m.colors.resize(baseIndex, glm::vec3(1.0f));+ for (size_t i = 0; i < pos.size(); ++i)+ m.colors.push_back(i * size_t(comps) + 2 < c.size()+ ? glm::vec3(c[i * size_t(comps)], c[i * size_t(comps) + 1], c[i * size_t(comps) + 2])+ : glm::vec3(1.0f));+ } else if (!m.colors.empty()) {+ m.colors.resize(m.positions.size(), glm::vec3(1.0f));+ }for (size_t t = 0; t + 2 < idx.size(); t += 3) {if (idx[t] >= pos.size() || idx[t + 1] >= pos.size() || idx[t + 2] >= pos.size())return r.fail("Index out of range");@@ -609,6 +628,7 @@ bool loadGltf(const std::string& path, Mesh& out, std::string& error, SplatCloudif (targetsConsistent)for (size_t k = 0; k < targetDeltas.size(); ++k)layers.push_back({targetNames[k], std::move(targetDeltas[k]), targetWeights[k]});+ if (!m.colors.empty()) m.colors.resize(m.positions.size(), glm::vec3(1.0f));Mesh welded = weldImported(m, layers);out = std::move(welded);return true;diff --git a/src/io/ObjIO.cpp b/src/io/ObjIO.cppindex a830ce81..78acac26 100644--- a/src/io/ObjIO.cpp+++ b/src/io/ObjIO.cpp@@ -57,6 +57,21 @@ bool loadObj(const std::string& path, Mesh& out, std::string& error) {}cur = next;}+ // Optional "v x y z r g b" vertex colours (MeshLab, scanners), 0..1 display RGB.+ glm::vec3 rgb;+ int channels = 0;+ for (; channels < 3; ++channels) {+ char* next;+ rgb[channels] = std::strtof(cur, &next);+ if (next == cur) break;+ cur = next;+ }+ if (channels == 3) {+ if (m.colors.size() < m.positions.size()) m.colors.resize(m.positions.size(), glm::vec3(1.0f));+ m.colors.push_back(srgbToLinear(rgb));+ } else if (!m.colors.empty()) {+ m.colors.push_back(glm::vec3(1.0f));+ }m.positions.push_back(v);} else if (s[0] == 'f' && (s[1] == ' ' || s[1] == '\t')) {poly.clear();@@ -83,6 +98,7 @@ bool loadObj(const std::string& path, Mesh& out, std::string& error) {error = "No faces found in " + path;return false;}+ if (!m.colors.empty()) m.colors.resize(m.positions.size(), glm::vec3(1.0f));m.rebuildTopology();m.recomputeAllNormals();out = std::move(m);@@ -99,8 +115,16 @@ bool saveObj(const std::string& path, const Mesh& mesh, std::string& error) {buf.reserve(mesh.vertexCount() * 40 + mesh.triangleCount() * 30);buf += "# Exported by SculptForge\n";char line[128];- for (const auto& v : mesh.positions) {- int n = std::snprintf(line, sizeof line, "v %.7g %.7g %.7g\n", v.x, v.y, v.z);+ const bool colors = mesh.colors.size() == mesh.positions.size() && mesh.hasColors();+ for (size_t i = 0; i < mesh.positions.size(); ++i) {+ const glm::vec3& v = mesh.positions[i];+ int n;+ if (colors) {+ const glm::vec3 c = linearToSrgb(mesh.colors[i]);+ n = std::snprintf(line, sizeof line, "v %.7g %.7g %.7g %.4f %.4f %.4f\n", v.x, v.y, v.z, c.x, c.y, c.z);+ } else {+ n = std::snprintf(line, sizeof line, "v %.7g %.7g %.7g\n", v.x, v.y, v.z);+ }buf.append(line, n);}for (const auto& t : mesh.triangles) {diff --git a/src/io/ObjIO.h b/src/io/ObjIO.hindex 62284ead..a3a9ec98 100644--- a/src/io/ObjIO.h+++ b/src/io/ObjIO.h@@ -9,6 +9,7 @@namespace sf {// Paths are UTF-8. Polygons are fan-triangulated; UVs and normals are ignored.+// "v x y z r g b" vertex colours are read into Mesh::colors and written back.bool loadObj(const std::string& path, Mesh& out, std::string& error);bool saveObj(const std::string& path, const Mesh& mesh, std::string& error);diff --git a/src/io/PlyIO.cpp b/src/io/PlyIO.cppindex 625406f4..414a3f86 100644--- a/src/io/PlyIO.cpp+++ b/src/io/PlyIO.cpp@@ -252,6 +252,10 @@ bool loadPly(const std::string& path, Mesh& mesh, SplatCloud& splats, PlyContentconst glm::vec3 pos{float(row[size_t(px)]), float(row[size_t(py)]), float(row[size_t(pz)])};if (isMesh) {m.positions.push_back(pos);+ if (rgb[0] >= 0 && rgb[1] >= 0 && rgb[2] >= 0) {+ const glm::vec3 c{float(row[size_t(rgb[0])]), float(row[size_t(rgb[1])]), float(row[size_t(rgb[2])])};+ m.colors.push_back(srgbToLinear(rgbIsByte ? c / 255.0f : c));+ }continue;}cloud.positions[r] = pos;@@ -286,7 +290,7 @@ bool loadPly(const std::string& path, Mesh& mesh, SplatCloud& splats, PlyContenterror = "PLY face index out of range";return false;}- mesh = weldImported(m);+ mesh = weldImported(m); // keeps vertex colours (scans, photogrammetry)if (mesh.triangleCount() == 0) {error = "The PLY mesh has no usable faces";return false;diff --git a/src/io/PlyIO.h b/src/io/PlyIO.hindex 382749a1..91e5e2e2 100644--- a/src/io/PlyIO.h+++ b/src/io/PlyIO.h@@ -15,7 +15,7 @@ namespace sf {enum class PlyContent { Mesh, Splats };-// Reads a mesh (if the file has faces), Gaussian splats (if it has splat+// Reads a mesh (if the file has faces; vertex colours kept), Gaussian splats (if it has splat// properties), or turns a plain point cloud into small round splats so it can// be converted to a mesh. `content` says which output was filled.bool loadPly(const std::string& path, Mesh& mesh, SplatCloud& splats, PlyContent& content, std::string& error);diff --git a/src/python/module.cpp b/src/python/module.cppindex e3019034..04e6047c 100644--- a/src/python/module.cpp+++ b/src/python/module.cpp@@ -9,6 +9,7 @@// sf.run(doc, "new_sphere", subdivisions=5)// sf.run(doc, "export_usd", path="/tmp/head.usdz")// verts, tris = doc.vertices, doc.triangles # (N, 3) float32, (M, 3) uint32+// doc.mask, doc.colors, doc.polygroups # optional attributes, None when absent#include "ai/AiCommands.h"#include "core/Commands.h"#include "core/Script.h"@@ -66,6 +67,28 @@ py::array_t<float> vec3Array(const std::vector<glm::vec3>& v) {return a;}+// Optional mesh attributes: None while absent, otherwise a copy.+template <class T>+py::object attributeArray(const std::vector<T>& v) {+ if (v.empty()) return py::none();+ py::array_t<T> a(py::ssize_t(v.size()));+ std::memcpy(a.mutable_data(), v.data(), v.size() * sizeof(T));+ return a;+}++// Replaces an optional attribute from a 1-D array of `count` values (None clears it).+template <class T>+void setAttribute(std::vector<T>& dst, const py::object& value, size_t count, const char* what) {+ if (value.is_none()) {+ std::vector<T>().swap(dst);+ return;+ }+ auto a = py::array_t<T, py::array::c_style | py::array::forcecast>::ensure(value);+ if (!a || a.ndim() != 1 || size_t(a.shape(0)) != count)+ throw py::value_error(std::string(what) + ": expected " + std::to_string(count) + " values or None");+ dst.assign(a.data(), a.data() + count);+}+} // namespacePYBIND11_MODULE(sculptforge, m) {@@ -80,6 +103,47 @@ PYBIND11_MODULE(sculptforge, m) {.def_property_readonly("base_vertices", [](const Document& d) { return vec3Array(d.mesh.basePositions()); },"Vertex positions with every layer at zero, (N, 3) float32.").def_property_readonly("normals", [](const Document& d) { return vec3Array(d.mesh.normals); })+ .def_property(+ "mask", [](const Document& d) { return attributeArray(d.mesh.mask); },+ [](Document& d, const py::object& v) {+ setAttribute(d.mesh.mask, v, d.mesh.vertexCount(), "mask");+ d.mesh.markAllDirty();+ d.modified = true;+ },+ "Per-vertex mask, (N,) float32 with 0 = free and 1 = fully masked; None if the mesh has no mask.")+ .def_property(+ "colors",+ [](const Document& d) -> py::object { return d.mesh.colors.empty() ? py::object(py::none()) : vec3Array(d.mesh.colors); },+ [](Document& d, const py::object& v) {+ if (v.is_none()) {+ d.mesh.clearColors();+ } else {+ auto a = py::array_t<float, py::array::c_style | py::array::forcecast>::ensure(v);+ if (!a || a.ndim() != 2 || a.shape(1) != 3 || size_t(a.shape(0)) != d.mesh.vertexCount())+ throw py::value_error("colors: expected (N, 3) linear RGB or None");+ d.mesh.colors.resize(d.mesh.vertexCount());+ std::memcpy(d.mesh.colors.data(), a.data(), d.mesh.colors.size() * sizeof(glm::vec3));+ }+ d.mesh.markAllDirty();+ d.modified = true;+ },+ "Per-vertex polypaint, (N, 3) float32 linear RGB in 0..1; None if unpainted.")+ .def_property(+ "polygroups", [](const Document& d) { return attributeArray(d.mesh.polygroups); },+ [](Document& d, const py::object& v) {+ setAttribute(d.mesh.polygroups, v, d.mesh.triangleCount(), "polygroups");+ d.mesh.facesDirty = true;+ d.modified = true;+ },+ "Per-triangle polygroup ids, (M,) uint32; None means every triangle is in group 0.")+ .def_property(+ "hidden", [](const Document& d) { return attributeArray(d.mesh.hidden); },+ [](Document& d, const py::object& v) {+ setAttribute(d.mesh.hidden, v, d.mesh.triangleCount(), "hidden");+ d.mesh.facesDirty = true;+ d.modified = true;+ },+ "Per-triangle hidden flags, (M,) uint8 (nonzero = hidden); None means all visible.").def_property_readonly("triangles",[](const Document& d) {diff --git a/src/render/GL.h b/src/render/GL.hindex 30459a85..a21e1137 100644--- a/src/render/GL.h+++ b/src/render/GL.h@@ -75,10 +75,12 @@ constexpr GLenum GL_RENDERBUFFER = 0x8D41;constexpr GLenum GL_ONE = 1;constexpr GLenum GL_TRIANGLE_STRIP = 0x0005;constexpr GLenum GL_TEXTURE0 = 0x84C0;+constexpr GLenum GL_TEXTURE1 = 0x84C1;constexpr GLenum GL_RGBA32F = 0x8814;constexpr GLenum GL_STREAM_DRAW = 0x88E0;constexpr GLenum GL_TEXTURE_BUFFER = 0x8C2A;constexpr GLenum GL_MAX_TEXTURE_BUFFER_SIZE = 0x8C2B;+constexpr GLenum GL_R32UI = 0x8236;constexpr GLbitfield GL_DEPTH_BUFFER_BIT = 0x0100;constexpr GLbitfield GL_COLOR_BUFFER_BIT = 0x4000;@@ -149,7 +151,10 @@ constexpr GLbitfield GL_COLOR_BUFFER_BIT = 0x4000;X(void, GetIntegerv, GLenum, GLint*) \X(void, Uniform1i, GLint, GLint) \X(void, Uniform1f, GLint, GLfloat) \- X(void, Uniform2f, GLint, GLfloat, GLfloat)+ X(void, Uniform2f, GLint, GLfloat, GLfloat) \+ X(void, DisableVertexAttribArray, GLuint) \+ X(void, VertexAttrib1f, GLuint, GLfloat) \+ X(void, VertexAttrib3f, GLuint, GLfloat, GLfloat, GLfloat)namespace gl {diff --git a/src/render/Renderer.cpp b/src/render/Renderer.cppindex 639dda16..54cb15ea 100644--- a/src/render/Renderer.cpp+++ b/src/render/Renderer.cpp@@ -16,15 +16,21 @@ const char* kMeshVS = R"(#version 330 corelayout(location = 0) in vec3 aPos;layout(location = 1) in vec3 aNormal;layout(location = 2) in float aCurvature;+layout(location = 3) in vec3 aColor; // polypaint (constant white when the mesh has none)+layout(location = 4) in float aMask; // constant 0 when the mesh has no maskuniform mat4 uView;uniform mat4 uProj;out vec3 vNormal;out vec3 vPos;out float vCurvature;+out vec3 vColor;+out float vMask;void main() {vec4 p = uView * vec4(aPos, 1.0);vPos = p.xyz;vCurvature = aCurvature;+ vColor = aColor;+ vMask = aMask;vNormal = mat3(uView) * aNormal;gl_Position = uProj * p;}@@ -36,9 +42,31 @@ const char* kMeshFS = R"(#version 330 corein vec3 vNormal;in vec3 vPos;in float vCurvature;-uniform vec3 uColor;+in vec3 vColor;+in float vMask;+uniform vec3 uBaseColor;+uniform int uPaint; // 1: vertex colours replace the base colour+uniform int uShowMask; // 1: darken masked areas+uniform int uGroups; // 0: off, 1: per-triangle ids from uGroupIds, 2: everything is group 0+uniform usamplerBuffer uGroupIds;out vec4 fragColor;+// Keep in sync with sf::polygroupColor.+vec3 groupColor(uint id) {+ uint h = id * 0x9E3779B1u;+ h ^= h >> 15;+ h *= 0x85EBCA77u;+ h ^= h >> 13;+ float hue = float(h & 0xFFFFu) / 65536.0;+ float sat = 0.45 + 0.25 * float((h >> 16) & 0xFFu) / 255.0;+ float val = 0.70 + 0.25 * float((h >> 24) & 0xFFu) / 255.0;+ vec3 rgb = clamp(abs(fract(hue + vec3(0.0, 2.0 / 3.0, 1.0 / 3.0)) * 6.0 - 3.0) - 1.0, 0.0, 1.0);+ return val * mix(vec3(1.0), rgb, sat);+}void main() {+ vec3 albedo = uBaseColor;+ if (uGroups == 1) albedo = groupColor(texelFetch(uGroupIds, gl_PrimitiveID).r);+ else if (uGroups == 2) albedo = groupColor(0u);+ else if (uPaint == 1) albedo = vColor;vec3 n = normalize(vNormal);if (!gl_FrontFacing) n = -n;vec3 v = normalize(-vPos);@@ -55,10 +83,11 @@ void main() {float crease = smoothstep(0.0, 0.16, vCurvature);float ridge = smoothstep(0.0, 0.2, -vCurvature);float cavity = 1.0 - 0.62 * crease;- vec3 c = uColor * (0.12 * hemi + 0.95 * diff * diff + fillL * vec3(0.7, 0.8, 1.0)) * mix(0.7, 1.0, facing) * cavity;+ vec3 c = albedo * (0.12 * hemi + 0.95 * diff * diff + fillL * vec3(0.7, 0.8, 1.0)) * mix(0.7, 1.0, facing) * cavity;c *= mix(vec3(1.0), vec3(0.72, 0.55, 0.5), crease * 0.7); // warm, deeper colour in the cracks- c += uColor * ridge * 0.3 * diff; // ridges catch the key light+ c += albedo * ridge * 0.3 * diff; // ridges catch the key lightc += vec3(spec) * (1.0 - crease) + rim * vec3(0.8, 0.85, 1.0);+ if (uShowMask == 1) c *= 1.0 - 0.75 * clamp(vMask, 0.0, 1.0);fragColor = vec4(pow(c, vec3(1.0 / 2.2)), 1.0);})";@@ -189,6 +218,19 @@ GLuint link(const char* vs, const char* fs, std::string& error) {} // namespace+glm::vec3 polygroupColor(uint32_t id) {+ uint32_t h = id * 0x9E3779B1u;+ h ^= h >> 15;+ h *= 0x85EBCA77u;+ h ^= h >> 13;+ const float hue = float(h & 0xFFFFu) / 65536.0f;+ const float sat = 0.45f + 0.25f * float((h >> 16) & 0xFFu) / 255.0f;+ const float val = 0.70f + 0.25f * float((h >> 24) & 0xFFu) / 255.0f;+ const glm::vec3 rgb = glm::clamp(glm::abs(glm::fract(hue + glm::vec3(0.0f, 2.0f / 3.0f, 1.0f / 3.0f)) * 6.0f - 3.0f) - 1.0f,+ 0.0f, 1.0f);+ return val * glm::mix(glm::vec3(1.0f), rgb, sat);+}+bool Renderer::init(std::string& error) {meshProgram_ = link(kMeshVS, kMeshFS, error);if (!meshProgram_) return false;@@ -227,8 +269,18 @@ bool Renderer::init(std::string& error) {gl::BindBuffer(GL_ARRAY_BUFFER, curvBuffer_);gl::EnableVertexAttribArray(2);gl::VertexAttribPointer(2, 1, GL_FLOAT, GL_FALSE, sizeof(float), nullptr);+ // Colour (3) and mask (4) arrays are only enabled while the mesh has them.+ gl::GenBuffers(1, &colorBuffer_);+ gl::BindBuffer(GL_ARRAY_BUFFER, colorBuffer_);+ gl::VertexAttribPointer(3, 3, GL_FLOAT, GL_FALSE, sizeof(glm::vec3), nullptr);+ gl::GenBuffers(1, &maskBuffer_);+ gl::BindBuffer(GL_ARRAY_BUFFER, maskBuffer_);+ gl::VertexAttribPointer(4, 1, GL_FLOAT, GL_FALSE, sizeof(float), nullptr);gl::BindBuffer(GL_ELEMENT_ARRAY_BUFFER, indexBuffer_);gl::BindVertexArray(0);+ gl::BindBuffer(GL_ARRAY_BUFFER, 0);+ gl::GenBuffers(1, &groupData_);+ gl::GenTextures(1, &groupTexture_);return true;}@@ -236,6 +288,10 @@ void Renderer::shutdown() {gl::DeleteBuffers(1, &posBuffer_);gl::DeleteBuffers(1, &nrmBuffer_);gl::DeleteBuffers(1, &curvBuffer_);+ gl::DeleteBuffers(1, &colorBuffer_);+ gl::DeleteBuffers(1, &maskBuffer_);+ gl::DeleteBuffers(1, &groupData_);+ gl::DeleteTextures(1, &groupTexture_);gl::DeleteBuffers(1, &indexBuffer_);gl::DeleteVertexArrays(1, &vao_);gl::DeleteVertexArrays(1, &emptyVao_);@@ -350,34 +406,99 @@ void Renderer::updateCurvature(const Mesh& mesh, uint32_t begin, uint32_t end) {}}+// Index buffer without hidden triangles, plus the polygroup id of every drawn+// triangle in draw order (looked up by gl_PrimitiveID).+void Renderer::uploadFaces(const Mesh& mesh) {+ const size_t nt = mesh.triangleCount();+ const bool hidden = mesh.hidden.size() == nt && nt > 0;+ const bool groups = mesh.polygroups.size() == nt && nt > 0;+ const glm::uvec3* tris = mesh.triangles.data();+ size_t drawn = nt;+ visibleGroups_.clear();+ if (hidden) {+ visibleTris_.clear();+ for (size_t t = 0; t < nt; ++t) {+ if (mesh.hidden[t]) continue;+ visibleTris_.push_back(mesh.triangles[t]);+ if (groups) visibleGroups_.push_back(mesh.polygroups[t]);+ }+ tris = visibleTris_.data();+ drawn = visibleTris_.size();+ } else {+ std::vector<glm::uvec3>().swap(visibleTris_);+ if (groups) visibleGroups_ = mesh.polygroups;+ }+ gl::BindVertexArray(vao_);+ gl::BufferData(GL_ELEMENT_ARRAY_BUFFER, GLsizeiptr(drawn * sizeof(glm::uvec3)), tris, GL_STATIC_DRAW);+ gl::BindVertexArray(0);+ indexCount_ = GLsizei(drawn * 3);++ GLint maxTexels = 0;+ gl::GetIntegerv(GL_MAX_TEXTURE_BUFFER_SIZE, &maxTexels);+ hasGroups_ = groups && !visibleGroups_.empty() && visibleGroups_.size() <= size_t(std::max(maxTexels, 0));+ if (hasGroups_) {+ gl::BindBuffer(GL_TEXTURE_BUFFER, groupData_);+ gl::BufferData(GL_TEXTURE_BUFFER, GLsizeiptr(visibleGroups_.size() * sizeof(uint32_t)), visibleGroups_.data(),+ GL_STATIC_DRAW);+ gl::BindTexture(GL_TEXTURE_BUFFER, groupTexture_);+ gl::TexBuffer(GL_TEXTURE_BUFFER, GL_R32UI, groupData_);+ gl::BindTexture(GL_TEXTURE_BUFFER, 0);+ gl::BindBuffer(GL_TEXTURE_BUFFER, 0);+ }+}+void Renderer::sync(Mesh& mesh) {const size_t nv = mesh.vertexCount();- if (mesh.topologyDirty || nv != vertexCapacity_) {+ const bool full = mesh.topologyDirty || nv != vertexCapacity_;+ const bool ranged = !full && mesh.dirtyBegin < mesh.dirtyEnd && mesh.dirtyEnd <= nv;+ const GLintptr off3 = ranged ? GLintptr(mesh.dirtyBegin * sizeof(glm::vec3)) : 0;+ const GLsizeiptr size3 = ranged ? GLsizeiptr((mesh.dirtyEnd - mesh.dirtyBegin) * sizeof(glm::vec3)) : 0;+ const GLintptr off1 = ranged ? GLintptr(mesh.dirtyBegin * sizeof(float)) : 0;+ const GLsizeiptr size1 = ranged ? GLsizeiptr((mesh.dirtyEnd - mesh.dirtyBegin) * sizeof(float)) : 0;+ if (full) {updateCurvature(mesh, 0, uint32_t(nv));- gl::BindVertexArray(vao_);gl::BindBuffer(GL_ARRAY_BUFFER, posBuffer_);gl::BufferData(GL_ARRAY_BUFFER, GLsizeiptr(nv * sizeof(glm::vec3)), mesh.positions.data(), GL_DYNAMIC_DRAW);gl::BindBuffer(GL_ARRAY_BUFFER, nrmBuffer_);gl::BufferData(GL_ARRAY_BUFFER, GLsizeiptr(nv * sizeof(glm::vec3)), mesh.normals.data(), GL_DYNAMIC_DRAW);gl::BindBuffer(GL_ARRAY_BUFFER, curvBuffer_);gl::BufferData(GL_ARRAY_BUFFER, GLsizeiptr(nv * sizeof(float)), curvature_.data(), GL_DYNAMIC_DRAW);- gl::BufferData(GL_ELEMENT_ARRAY_BUFFER, GLsizeiptr(mesh.triangleCount() * sizeof(glm::uvec3)),- mesh.triangles.data(), GL_STATIC_DRAW);- gl::BindVertexArray(0);- indexCount_ = GLsizei(mesh.triangleCount() * 3);+ uploadFaces(mesh);vertexCapacity_ = nv;- } else if (mesh.dirtyBegin < mesh.dirtyEnd) {- const GLintptr offset = GLintptr(mesh.dirtyBegin * sizeof(glm::vec3));- const GLsizeiptr size = GLsizeiptr((mesh.dirtyEnd - mesh.dirtyBegin) * sizeof(glm::vec3));+ } else if (ranged) {gl::BindBuffer(GL_ARRAY_BUFFER, posBuffer_);- gl::BufferSubData(GL_ARRAY_BUFFER, offset, size, mesh.positions.data() + mesh.dirtyBegin);+ gl::BufferSubData(GL_ARRAY_BUFFER, off3, size3, mesh.positions.data() + mesh.dirtyBegin);gl::BindBuffer(GL_ARRAY_BUFFER, nrmBuffer_);- gl::BufferSubData(GL_ARRAY_BUFFER, offset, size, mesh.normals.data() + mesh.dirtyBegin);+ gl::BufferSubData(GL_ARRAY_BUFFER, off3, size3, mesh.normals.data() + mesh.dirtyBegin);updateCurvature(mesh, mesh.dirtyBegin, mesh.dirtyEnd);gl::BindBuffer(GL_ARRAY_BUFFER, curvBuffer_);- gl::BufferSubData(GL_ARRAY_BUFFER, GLintptr(mesh.dirtyBegin * sizeof(float)),- GLsizeiptr((mesh.dirtyEnd - mesh.dirtyBegin) * sizeof(float)), curvature_.data() + mesh.dirtyBegin);+ gl::BufferSubData(GL_ARRAY_BUFFER, off1, size1, curvature_.data() + mesh.dirtyBegin);}+ if (!full && mesh.facesDirty) uploadFaces(mesh);++ // Optional per-vertex attributes: a full upload when they appear (or the+ // mesh changed), the dirty range otherwise, and a disabled array when absent.+ auto syncAttribute = [&](GLuint buffer, GLuint location, bool& uploaded, const void* data, size_t elementSize,+ bool present, GLintptr offset, GLsizeiptr size) {+ gl::BindBuffer(GL_ARRAY_BUFFER, buffer);+ if (present && (full || !uploaded)) {+ gl::BufferData(GL_ARRAY_BUFFER, GLsizeiptr(nv * elementSize), data, GL_DYNAMIC_DRAW);+ } else if (present && ranged) {+ gl::BufferSubData(GL_ARRAY_BUFFER, offset, size, static_cast<const uint8_t*>(data) + size_t(offset));+ } else if (!present && uploaded) {+ gl::BufferData(GL_ARRAY_BUFFER, 0, nullptr, GL_DYNAMIC_DRAW);+ }+ if (present != uploaded) {+ gl::BindVertexArray(vao_);+ if (present) gl::EnableVertexAttribArray(location);+ else gl::DisableVertexAttribArray(location);+ gl::BindVertexArray(0);+ }+ uploaded = present;+ };+ syncAttribute(colorBuffer_, 3, hasColors_, mesh.colors.data(), sizeof(glm::vec3), nv > 0 && mesh.colors.size() == nv,+ off3, size3);+ syncAttribute(maskBuffer_, 4, hasMask_, mesh.mask.data(), sizeof(float), nv > 0 && mesh.mask.size() == nv, off1, size1);gl::BindBuffer(GL_ARRAY_BUFFER, 0);mesh.clearDirty();}@@ -506,11 +627,24 @@ void Renderer::draw(const Camera& camera, int fbWidth, int fbHeight, const Rende};setMatrices(meshProgram_);- gl::Uniform3fv(gl::GetUniformLocation(meshProgram_, "uColor"), 1, glm::value_ptr(settings.baseColor));+ gl::Uniform3fv(gl::GetUniformLocation(meshProgram_, "uBaseColor"), 1, glm::value_ptr(settings.baseColor));+ gl::Uniform1i(gl::GetUniformLocation(meshProgram_, "uPaint"), settings.showPolypaint && hasColors_ ? 1 : 0);+ gl::Uniform1i(gl::GetUniformLocation(meshProgram_, "uShowMask"), settings.showMask && hasMask_ ? 1 : 0);+ gl::Uniform1i(gl::GetUniformLocation(meshProgram_, "uGroups"), settings.showPolygroups ? (hasGroups_ ? 1 : 2) : 0);+ gl::Uniform1i(gl::GetUniformLocation(meshProgram_, "uGroupIds"), 1);+ // Constant values for the attribute arrays that are disabled.+ if (!hasColors_) gl::VertexAttrib3f(3, 1.0f, 1.0f, 1.0f);+ if (!hasMask_) gl::VertexAttrib1f(4, 0.0f);+ gl::ActiveTexture(GL_TEXTURE1);+ gl::BindTexture(GL_TEXTURE_BUFFER, hasGroups_ ? groupTexture_ : 0);+ gl::ActiveTexture(GL_TEXTURE0);gl::Enable(GL_POLYGON_OFFSET_FILL);gl::PolygonOffset(1.0f, 1.0f);gl::DrawElements(GL_TRIANGLES, indexCount_, GL_UNSIGNED_INT, nullptr);gl::Disable(GL_POLYGON_OFFSET_FILL);+ gl::ActiveTexture(GL_TEXTURE1);+ gl::BindTexture(GL_TEXTURE_BUFFER, 0);+ gl::ActiveTexture(GL_TEXTURE0);if (settings.wireframe) {setMatrices(wireProgram_);diff --git a/src/render/Renderer.h b/src/render/Renderer.hindex 3d302064..95c7c650 100644--- a/src/render/Renderer.h+++ b/src/render/Renderer.h@@ -16,11 +16,22 @@ namespace sf {struct RenderSettings {bool wireframe = false;glm::vec3 baseColor{0.80f, 0.55f, 0.45f}; // clay+ bool showPolypaint = true; // vertex colours replace baseColor when the mesh has them+ bool showMask = true; // masked areas render darker (ZBrush style)+ bool showPolygroups = false; // colour each polygroup (see polygroupColor)bool showMesh = true;bool showSplats = true;float splatOpacity = 1.0f; // global fade for using a capture as reference};+// Display colour of a polygroup id (linear RGB): a stable hash spread over+// pleasant hues. The mesh shader uses the same formula.+glm::vec3 polygroupColor(uint32_t id);++// Mesh drawing honours the optional Mesh attributes: colours (polypaint), mask+// (darkening), polygroups (group colours) and hidden triangles (not drawn).+// Mark changed vertices dirty for colour/mask edits and set Mesh::facesDirty+// after changing `hidden` or `polygroups`.class Renderer {public:bool init(std::string& error);@@ -53,8 +64,14 @@ private:int captureW_ = 0, captureH_ = 0;GLuint vao_ = 0, emptyVao_ = 0;void updateCurvature(const Mesh& mesh, uint32_t begin, uint32_t end);+ void uploadFaces(const Mesh& mesh);GLuint posBuffer_ = 0, nrmBuffer_ = 0, curvBuffer_ = 0, indexBuffer_ = 0;+ GLuint colorBuffer_ = 0, maskBuffer_ = 0;+ GLuint groupData_ = 0, groupTexture_ = 0; // polygroup id per drawn triangle (texture buffer)+ bool hasColors_ = false, hasMask_ = false, hasGroups_ = false;std::vector<float> curvature_;+ std::vector<glm::uvec3> visibleTris_;+ std::vector<uint32_t> visibleGroups_;GLsizei indexCount_ = 0;size_t vertexCapacity_ = 0;};diff --git a/tests/TestHarness.h b/tests/TestHarness.hnew file mode 100644index 00000000..1813fbbb--- /dev/null+++ b/tests/TestHarness.h@@ -0,0 +1,59 @@+// SculptForge - open source digital sculpting+// SPDX-License-Identifier: GPL-3.0-or-later+//+// Dependency-free test harness. Each tests/test_*.cpp file includes this and+// defines TEST(name) { CHECK(...); } cases; tests/test_main.cpp runs them all.+// New test files are picked up by CMake automatically (re-run cmake).+#pragma once++#include "core/Document.h"++#include <cstdio>+#include <filesystem>+#include <functional>+#include <string>+#include <vector>++namespace sf::test {++inline int g_failures = 0;+inline int g_checks = 0;++struct TestCase {+ const char* name;+ std::function<void()> fn;+};+inline std::vector<TestCase>& registry() {+ static std::vector<TestCase> r;+ return r;+}+struct Register {+ Register(const char* n, std::function<void()> f) { registry().push_back({n, std::move(f)}); }+};++inline Document makeDoc(Mesh m) {+ Document d;+ d.setMesh(std::move(m));+ return d;+}++inline std::string tempPath(const char* name) { return (std::filesystem::temp_directory_path() / name).string(); }++} // namespace sf::test++#define CHECK(cond) \+ do { \+ ++::sf::test::g_checks; \+ if (!(cond)) { \+ ++::sf::test::g_failures; \+ std::printf(" FAILED %s:%d: %s\n", __FILE__, __LINE__, #cond); \+ } \+ } while (0)++#define TEST(name) \+ static void name(); \+ static ::sf::test::Register reg_##name(#name, name); \+ static void name()++using sf::test::makeDoc;+using sf::test::tempPath;diff --git a/tests/test_attributes.cpp b/tests/test_attributes.cppnew file mode 100644index 00000000..29c0d795--- /dev/null+++ b/tests/test_attributes.cpp@@ -0,0 +1,323 @@+// SculptForge - open source digital sculpting+// SPDX-License-Identifier: GPL-3.0-or-later+//+// Optional mesh attributes (mask, polypaint, polygroups, hidden, UVs): helpers,+// preservation through topology changes and undo, brush hooks and IO.+#include "TestHarness.h"++#include "core/Commands.h"+#include "core/Decimate.h"+#include "core/Primitives.h"+#include "core/Sculpt.h"+#include "core/Voxel.h"+#include "io/GltfIO.h"+#include "io/ObjIO.h"++#include <algorithm>+#include <cmath>+#include <filesystem>++using namespace sf;++namespace {++// Mask = 1 on the upper half (y > 0), red paint on the +x half, polygroup 1 on+// triangles whose centre has z > 0, the lowest triangle hidden.+void paintTestAttributes(Mesh& m) {+ m.ensureMask();+ m.ensureColors();+ for (uint32_t v = 0; v < m.vertexCount(); ++v) {+ m.mask[v] = m.positions[v].y > 0.0f ? 1.0f : 0.0f;+ m.colors[v] = m.positions[v].x > 0.0f ? glm::vec3(1, 0, 0) : glm::vec3(1);+ }+ m.ensurePolygroups();+ m.ensureHidden();+ for (uint32_t t = 0; t < m.triangleCount(); ++t) {+ const auto& tri = m.triangles[t];+ glm::vec3 c = (m.positions[tri.x] + m.positions[tri.y] + m.positions[tri.z]) / 3.0f;+ m.polygroups[t] = c.z > 0.0f ? 1u : 0u;+ m.hidden[t] = c.y < -0.97f ? 1 : 0;+ }+ m.uvs.resize(m.triangleCount() * 3);+ for (size_t i = 0; i < m.uvs.size(); ++i) {+ const glm::vec3& p = m.positions[m.triangles[i / 3][int(i % 3)]];+ m.uvs[i] = glm::vec2(p.x, p.y) * 0.5f + 0.5f;+ }+}++bool allIn(const std::vector<float>& v, float lo, float hi) {+ return std::all_of(v.begin(), v.end(), [&](float x) { return x >= lo && x <= hi; });+}++} // namespace++TEST(attribute_helpers_default_empty) {+ Mesh m = makeIcosphere(2);+ CHECK(!m.hasMask() && !m.hasColors() && !m.hasPolygroups() && !m.hasHidden() && !m.hasUvs());+ CHECK(m.maskAt(3) == 0.0f && m.polygroupAt(5) == 0u && !m.triangleHidden(5) && !m.vertexHidden(0));+ CHECK(m.colorAt(0, glm::vec3(0.5f)) == glm::vec3(0.5f));+ m.ensureMask(0.25f);+ CHECK(m.mask.size() == m.vertexCount() && m.maskAt(7) == 0.25f);+ m.ensureMask(0.9f); // already present: unchanged+ CHECK(m.maskAt(7) == 0.25f);+ m.ensureHidden();+ for (uint32_t t : m.vertexTriangles(0)) m.hidden[t] = 1;+ uint32_t opposite = 0;+ for (uint32_t v = 0; v < m.vertexCount(); ++v)+ if (glm::distance(m.positions[v], m.positions[0]) > glm::distance(m.positions[opposite], m.positions[0])) opposite = v;+ CHECK(m.vertexHidden(0) && !m.vertexHidden(opposite) && m.triangleHidden(m.vertexTriangles(0)[0]));+ m.clearMask();+ CHECK(!m.hasMask() && m.mask.capacity() == 0);+ // Stale attributes are dropped instead of being read out of range.+ m.colors.resize(3);+ m.rebuildTopology();+ CHECK(!m.hasColors() && m.hasHidden());+}++TEST(attributes_survive_subdivision) {+ Mesh m = makeIcosphere(2);+ paintTestAttributes(m);+ Mesh s = loopSubdivide(m);+ CHECK(s.mask.size() == s.vertexCount() && s.colors.size() == s.vertexCount());+ CHECK(s.polygroups.size() == s.triangleCount() && s.hidden.size() == s.triangleCount());+ CHECK(s.uvs.size() == s.triangleCount() * 3);+ for (uint32_t v = 0; v < m.vertexCount(); ++v) CHECK(s.mask[v] == m.mask[v] && s.colors[v] == m.colors[v]);+ CHECK(allIn(s.mask, 0.0f, 1.0f));+ for (uint32_t t = 0; t < m.triangleCount(); ++t)+ for (int k = 0; k < 4; ++k) {+ CHECK(s.polygroups[t * 4 + k] == m.polygroups[t]);+ CHECK(s.hidden[t * 4 + k] == m.hidden[t]);+ }+ // The first child keeps the parent's first corner UV; midpoints average.+ CHECK(s.uvs[0] == m.uvs[0]);+ CHECK(glm::distance(s.uvs[1], (m.uvs[0] + m.uvs[1]) * 0.5f) < 1e-6f);++ Document d = makeDoc(makeIcosphere(2));+ paintTestAttributes(d.mesh);+ CommandRegistry reg;+ CHECK(reg.execute(d, "subdivide", {{"levels", 2.0}}).ok);+ CHECK(d.mesh.mask.size() == d.mesh.vertexCount() && d.mesh.polygroups.size() == d.mesh.triangleCount());+}++TEST(attributes_survive_decimation) {+ Mesh m = loopSubdivide(makeIcosphere(3));+ paintTestAttributes(m);+ Mesh dm = decimate(m, m.triangleCount() / 4);+ CHECK(dm.triangleCount() < m.triangleCount() / 2);+ CHECK(dm.mask.size() == dm.vertexCount() && dm.colors.size() == dm.vertexCount());+ CHECK(dm.polygroups.size() == dm.triangleCount() && dm.hidden.size() == dm.triangleCount());+ CHECK(dm.uvs.size() == dm.triangleCount() * 3);+ // Kept vertices carry their exact values (vertices are a subset of the input).+ int mismatches = 0;+ for (uint32_t v = 0; v < dm.vertexCount(); ++v) {+ const glm::vec3& p = dm.positions[v];+ if ((p.y > 0.0f ? 1.0f : 0.0f) != dm.mask[v]) ++mismatches;+ if ((p.x > 0.0f ? glm::vec3(1, 0, 0) : glm::vec3(1)) != dm.colors[v]) ++mismatches;+ }+ CHECK(mismatches == 0);+ std::vector<Mesh> lods = generateLods(m, 3, 0.5f);+ CHECK(lods.size() == 3 && lods[2].mask.size() == lods[2].vertexCount() &&+ lods[2].polygroups.size() == lods[2].triangleCount());+}++TEST(attributes_transfer_through_remesh) {+ Mesh m = makeIcosphere(4);+ paintTestAttributes(m);+ std::string err;+ Mesh r = voxelRemesh(m, 48, &err);+ CHECK(r.triangleCount() > 0);+ CHECK(r.mask.size() == r.vertexCount() && r.colors.size() == r.vertexCount());+ CHECK(!r.hasPolygroups() && !r.hasHidden() && !r.hasUvs()); // documented reset+ int wrong = 0, checked = 0;+ for (uint32_t v = 0; v < r.vertexCount(); ++v) {+ const glm::vec3& p = r.positions[v];+ if (std::abs(p.y) > 0.15f) {+ ++checked;+ if (r.mask[v] != (p.y > 0.0f ? 1.0f : 0.0f)) ++wrong;+ }+ if (std::abs(p.x) > 0.15f && r.colors[v] != (p.x > 0.0f ? glm::vec3(1, 0, 0) : glm::vec3(1))) ++wrong;+ }+ CHECK(checked > 100 && wrong == 0);+}++TEST(attributes_carried_by_weld_and_snapshot_undo) {+ // Two triangles sharing an edge, with the shared vertices duplicated (a UV seam).+ Mesh raw;+ raw.positions = {{0, 0, 0}, {1, 0, 0}, {0, 1, 0}, {1, 0, 0}, {1, 1, 0}, {0, 1, 0}};+ raw.triangles = {{0, 1, 2}, {3, 4, 5}};+ raw.colors = {{1, 0, 0}, {0, 1, 0}, {0, 0, 1}, {1, 1, 0}, {1, 1, 1}, {0, 1, 1}};+ raw.polygroups = {4, 9};+ raw.uvs = {{0, 0}, {1, 0}, {0, 1}, {0.5f, 0}, {1, 1}, {0, 0.5f}};+ Mesh w = weldImported(raw);+ CHECK(w.vertexCount() == 4 && w.colors.size() == 4 && w.colors[1] == glm::vec3(0, 1, 0));+ CHECK(w.polygroups == std::vector<uint32_t>({4, 9}) && w.uvs.size() == 6 && w.uvs[3] == glm::vec2(0.5f, 0));++ Document d = makeDoc(makeIcosphere(2));+ paintTestAttributes(d.mesh);+ const Mesh before = d.mesh;+ CommandRegistry reg;+ CHECK(reg.execute(d, "remesh", {{"resolution", 40.0}}).ok);+ CHECK(d.undo.undo(d.mesh, d.bvh));+ CHECK(d.mesh.mask == before.mask && d.mesh.colors == before.colors && d.mesh.polygroups == before.polygroups &&+ d.mesh.hidden == before.hidden && d.mesh.uvs == before.uvs);+ CHECK(d.undo.redo(d.mesh, d.bvh));+ CHECK(d.mesh.vertexCount() != before.vertexCount() && d.mesh.mask.size() == d.mesh.vertexCount());+}++TEST(mask_and_color_stroke_undo) {+ Document d = makeDoc(makeIcosphere(3));+ // A paint/mask stroke: record before writing, through the sculptor.+ CHECK(d.sculptor.beginStroke(d.mesh, "Paint"));+ d.mesh.ensureMask();+ d.mesh.ensureColors();+ for (uint32_t v = 0; v < 10; ++v) {+ d.sculptor.recordMask(d.mesh, v);+ d.sculptor.recordColor(d.mesh, v);+ d.mesh.mask[v] = 0.5f;+ d.sculptor.recordMask(d.mesh, v); // recorded once per stroke+ d.mesh.mask[v] = 1.0f;+ d.mesh.colors[v] = glm::vec3(0, 0, 1);+ }+ UndoRecord r = d.sculptor.endStroke();+ CHECK(r.mask.indices.size() == 10 && r.colors.indices.size() == 10 && r.positions.empty() && !r.empty());+ d.undo.push(std::move(r));+ CHECK(d.undo.undo(d.mesh, d.bvh));+ CHECK(d.mesh.maskAt(3) == 0.0f && d.mesh.colorAt(3) == glm::vec3(1));+ CHECK(d.undo.redo(d.mesh, d.bvh));+ CHECK(d.mesh.maskAt(3) == 1.0f && d.mesh.colorAt(3) == glm::vec3(0, 0, 1));++ // Whole-attribute snapshots for operations like "clear mask" or "hide group".+ d.undo.push(UndoRecord::captureMask(d.mesh, "Clear Mask"));+ d.mesh.clearMask();+ d.undo.push(UndoRecord::captureHidden(d.mesh, "Hide"));+ d.mesh.ensureHidden()[0] = 1;+ d.undo.push(UndoRecord::capturePolygroups(d.mesh, "Group", std::vector<uint32_t>{2}));+ d.mesh.ensurePolygroups()[2] = 7;+ CHECK(d.undo.undo(d.mesh, d.bvh) && d.mesh.polygroupAt(2) == 0u);+ CHECK(d.undo.undo(d.mesh, d.bvh) && !d.mesh.triangleHidden(0));+ CHECK(d.undo.undo(d.mesh, d.bvh) && d.mesh.maskAt(3) == 1.0f);+ CHECK(d.undo.redo(d.mesh, d.bvh) && d.mesh.maskAt(3) == 0.0f);+}++TEST(brushes_respect_mask) {+ for (BrushType type : {BrushType::Standard, BrushType::Inflate, BrushType::Smooth, BrushType::Clay}) {+ Document d = makeDoc(makeIcosphere(4));+ d.mesh.ensureMask();+ for (uint32_t v = 0; v < d.mesh.vertexCount(); ++v) d.mesh.mask[v] = d.mesh.positions[v].x > 0.0f ? 1.0f : 0.0f;+ const std::vector<glm::vec3> before = d.mesh.positions;+ DabParams p;+ p.center = glm::vec3(0, 0, 1);+ p.radius = 0.6f;+ p.strength = 1.0f;+ d.sculptor.beginStroke(d.mesh, "Masked");+ for (int i = 0; i < 4; ++i) d.sculptor.dab(d.mesh, d.bvh, type, p, Symmetry{false, false, false});+ UndoRecord r = d.sculptor.endStroke();+ bool maskedStill = true, freeMoved = false;+ for (uint32_t v = 0; v < d.mesh.vertexCount(); ++v) {+ if (d.mesh.mask[v] == 1.0f) maskedStill &= d.mesh.positions[v] == before[v];+ else freeMoved |= d.mesh.positions[v] != before[v];+ }+ CHECK(maskedStill && freeMoved);+ for (uint32_t v : r.positions.indices) CHECK(d.mesh.mask[v] < 1.0f); // fully masked vertices aren't even recorded+ }+ // Partial mask scales the displacement; recipe and move brushes go through the same hook.+ Document d = makeDoc(makeIcosphere(4));+ d.mesh.ensureMask(0.5f);+ DabParams p;+ p.center = glm::vec3(0, 0, 1);+ p.radius = 0.4f;+ p.strength = 1.0f;+ d.sculptor.beginStroke(d.mesh, "Move");+ d.sculptor.beginGrab(d.mesh, d.bvh, p, Symmetry{false, false, false});+ d.sculptor.grab(d.mesh, d.bvh, glm::vec3(0, 0, 0.5f));+ d.sculptor.endStroke();+ float maxZ = 0;+ for (const auto& v : d.mesh.positions) maxZ = std::max(maxZ, v.z);+ CHECK(std::abs(maxZ - 1.25f) < 0.01f);+ d.mesh.ensureMask(); // already present+ std::fill(d.mesh.mask.begin(), d.mesh.mask.end(), 1.0f);+ const std::vector<glm::vec3> before = d.mesh.positions;+ d.sculptor.beginStroke(d.mesh, "Recipe");+ d.sculptor.dabRecipe(d.mesh, d.bvh, d.brushes.front(), p, Symmetry{});+ CHECK(d.sculptor.endStroke().empty() && d.mesh.positions == before);+}++TEST(hidden_triangles_skip_picking_and_brushes) {+ Document d = makeDoc(makeIcosphere(4));+ d.mesh.ensureHidden();+ for (uint32_t t = 0; t < d.mesh.triangleCount(); ++t) {+ const auto& tri = d.mesh.triangles[t];+ d.mesh.hidden[t] = d.mesh.positions[tri.x].z + d.mesh.positions[tri.y].z + d.mesh.positions[tri.z].z > 0.0f;+ }+ RayHit hit;+ CHECK(d.bvh.raycast(d.mesh, glm::vec3(0, 0, 5), glm::vec3(0, 0, -1), hit));+ CHECK(hit.position.z < -0.9f); // went through the hidden front to the visible back+ const std::vector<glm::vec3> before = d.mesh.positions;+ DabParams p;+ p.center = glm::vec3(0, 0, 1);+ p.radius = 0.5f;+ p.strength = 1.0f;+ d.sculptor.beginStroke(d.mesh, "Hidden");+ d.sculptor.dab(d.mesh, d.bvh, BrushType::Standard, p, Symmetry{false, false, false});+ d.sculptor.endStroke();+ for (uint32_t v = 0; v < d.mesh.vertexCount(); ++v)+ if (d.mesh.vertexHidden(v)) CHECK(d.mesh.positions[v] == before[v]);+ std::vector<uint32_t> verts;+ brushVertices(d.mesh, d.bvh, p.center, p.radius, verts);+ CHECK(verts.empty());+ std::fill(d.mesh.hidden.begin(), d.mesh.hidden.end(), uint8_t(1));+ CHECK(!d.bvh.raycast(d.mesh, glm::vec3(0, 0, 5), glm::vec3(0, 0, -1), hit));+}++TEST(mask_with_sculpt_layers) {+ Document d = makeDoc(makeIcosphere(3));+ CommandRegistry reg;+ CHECK(reg.execute(d, "layer_add", {{"name", std::string("Masked")}}).ok);+ d.mesh.ensureMask();+ for (uint32_t v = 0; v < d.mesh.vertexCount(); ++v) d.mesh.mask[v] = d.mesh.positions[v].x > 0.0f ? 1.0f : 0.0f;+ DabParams p;+ p.center = glm::vec3(0, 0, 1);+ p.radius = 0.6f;+ p.strength = 1.0f;+ d.sculptor.beginStroke(d.mesh, "Layer", d.activeLayer);+ d.sculptor.dab(d.mesh, d.bvh, BrushType::Standard, p, Symmetry{false, false, false});+ d.undo.push(d.sculptor.endStroke());+ bool ok = true;+ for (uint32_t v = 0; v < d.mesh.vertexCount(); ++v)+ if (d.mesh.mask[v] == 1.0f) ok &= d.mesh.layers[0].delta[v] == glm::vec3(0.0f);+ CHECK(ok);+ CHECK(reg.execute(d, "subdivide").ok); // layers and mask both subdivide+ CHECK(d.mesh.layers.size() == 1 && d.mesh.layers[0].delta.size() == d.mesh.vertexCount() &&+ d.mesh.mask.size() == d.mesh.vertexCount());+}++TEST(vertex_colors_in_obj_and_gltf) {+ Mesh m = makeIcosphere(2);+ m.ensureColors();+ for (uint32_t v = 0; v < m.vertexCount(); ++v) m.colors[v] = glm::vec3(float(v % 5) / 4.0f, 0.5f, 0.25f);+ std::string err;+ const std::string obj = tempPath("sculptforge_colors.obj");+ CHECK(saveObj(obj, m, err));+ Mesh o;+ CHECK(loadObj(obj, o, err));+ CHECK(o.colors.size() == o.vertexCount() && o.vertexCount() == m.vertexCount());+ float worst = 0.0f;+ for (uint32_t v = 0; v < o.vertexCount(); ++v) worst = std::max(worst, glm::length(o.colors[v] - m.colors[v]));+ CHECK(worst < 2e-3f);+ std::filesystem::remove(obj);++ const std::string glb = tempPath("sculptforge_colors.glb");+ CHECK(saveGlb(glb, m, "Painted", err));+ Mesh g;+ CHECK(loadGltf(glb, g, err));+ CHECK(g.colors.size() == g.vertexCount() && g.vertexCount() == m.vertexCount());+ worst = 0.0f;+ for (uint32_t v = 0; v < g.vertexCount(); ++v) worst = std::max(worst, glm::length(g.colors[v] - m.colors[v]));+ CHECK(worst < 1e-6f);+ std::filesystem::remove(glb);++ Mesh plain;+ CHECK(saveObj(obj, makeIcosphere(1), err) && loadObj(obj, plain, err) && !plain.hasColors());+ std::filesystem::remove(obj);+ CHECK(glm::length(linearToSrgb(srgbToLinear(glm::vec3(0.2f, 0.5f, 0.9f))) - glm::vec3(0.2f, 0.5f, 0.9f)) < 1e-5f);+}diff --git a/tests/test_core.cpp b/tests/test_core.cppnew file mode 100644index 00000000..8d7fc25b--- /dev/null+++ b/tests/test_core.cpp@@ -0,0 +1,1272 @@+// SculptForge - open source digital sculpting+// SPDX-License-Identifier: GPL-3.0-or-later+//+// Unit tests for the core library, IO, AI request plumbing and links.+#include "TestHarness.h"++#include "ai/BrushAssistant.h"+#include "ai/GradioClient.h"+#include "ai/ImageTo3DService.h"+#include "cli/McpServer.h"+#include "core/BrushRecipe.h"+#include "core/Commands.h"+#include "core/Json.h"+#include "core/Decimate.h"+#include "core/ImageTo3D.h"+#include "core/Script.h"+#include "io/GltfIO.h"+#include "core/Primitives.h"+#include "core/Sculpt.h"+#include "io/ObjIO.h"+#include "io/FbxIO.h"+#include "io/PlyIO.h"+#include "core/EnginePresets.h"+#include "link/UnrealLink.h"+#include "io/UsdIO.h"+#include "io/Zip.h"+#include "core/Splats.h"+#include "core/Voxel.h"++#include <cmath>+#include <algorithm>+#include <cstring>+#include <glm/gtc/matrix_transform.hpp>+#include <cstdio>+#include <filesystem>+#include <fstream>+#include <functional>+#include <map>+#include <string>+#include <vector>++using namespace sf;++TEST(icosphere_counts) {+ Mesh m = makeIcosphere(3);+ CHECK(m.triangleCount() == 20u * 64u);+ // Closed genus-0 surface: V - E + F = 2 with E = 3F/2.+ CHECK(long(m.vertexCount()) - long(m.triangleCount() * 3 / 2) + long(m.triangleCount()) == 2);+ for (const auto& p : m.positions) CHECK(std::abs(glm::length(p) - 1.0f) < 1e-5f);+ for (uint32_t v = 0; v < m.vertexCount(); ++v) CHECK(glm::dot(m.normals[v], m.positions[v]) > 0.99f);+}++TEST(bvh_raycast_and_query) {+ Mesh m = makeIcosphere(4);+ BVH bvh;+ bvh.build(m);+ RayHit hit;+ CHECK(bvh.raycast(m, glm::vec3(0, 0, 5), glm::vec3(0, 0, -1), hit));+ CHECK(std::abs(hit.position.z - 1.0f) < 0.01f);+ CHECK(!bvh.raycast(m, glm::vec3(0, 3, 5), glm::vec3(0, 0, -1), hit));++ std::vector<uint32_t> found;+ glm::vec3 c(0, 0, 1);+ bvh.queryVertices(m, c, 0.3f, found);+ size_t brute = 0;+ for (const auto& p : m.positions) brute += glm::distance(p, c) <= 0.3f;+ CHECK(found.size() == brute);+ CHECK(brute > 0);+}++TEST(standard_brush_raises_surface_with_symmetry) {+ Document d = makeDoc(makeIcosphere(4));+ DabParams p;+ p.center = glm::normalize(glm::vec3(0.5f, 0.2f, 0.8f));+ p.viewDir = -p.center;+ p.radius = 0.3f;+ p.strength = 1.0f;+ d.sculptor.beginStroke(d.mesh, "Standard");+ d.sculptor.dab(d.mesh, d.bvh, BrushType::Standard, p, Symmetry{true, false, false});+ UndoRecord r = d.sculptor.endStroke();+ CHECK(!r.empty());++ float maxR = 0, maxMirroredR = 0;+ for (const auto& v : d.mesh.positions) {+ if (v.x > 0.2f) maxR = std::max(maxR, glm::length(v));+ if (v.x < -0.2f) maxMirroredR = std::max(maxMirroredR, glm::length(v));+ }+ CHECK(maxR > 1.01f);+ CHECK(std::abs(maxR - maxMirroredR) < 1e-4f);++ // BVH must still find the raised surface.+ RayHit hit;+ CHECK(d.bvh.raycast(d.mesh, p.center * 5.0f, -p.center, hit));+ CHECK(glm::length(hit.position) > 1.005f);+}++TEST(undo_redo_restores_positions) {+ Document d = makeDoc(makeIcosphere(3));+ const std::vector<glm::vec3> original = d.mesh.positions;+ DabParams p;+ p.center = glm::vec3(0, 0, 1);+ p.viewDir = glm::vec3(0, 0, -1);+ p.radius = 0.5f;+ for (BrushType t : {BrushType::Standard, BrushType::Clay, BrushType::Inflate, BrushType::Crease}) {+ d.sculptor.beginStroke(d.mesh, brushName(t));+ d.sculptor.dab(d.mesh, d.bvh, t, p, Symmetry{});+ d.undo.push(d.sculptor.endStroke());+ }+ const std::vector<glm::vec3> sculpted = d.mesh.positions;+ CHECK(sculpted != original);+ while (d.undo.canUndo()) d.undo.undo(d.mesh, d.bvh);+ CHECK(d.mesh.positions == original);+ while (d.undo.canRedo()) d.undo.redo(d.mesh, d.bvh);+ CHECK(d.mesh.positions == sculpted);+}++TEST(smooth_reduces_noise) {+ Document d = makeDoc(makeIcosphere(4));+ for (size_t i = 0; i < d.mesh.vertexCount(); ++i)+ d.mesh.positions[i] *= 1.0f + 0.05f * float((i * 2654435761u) % 7) / 7.0f;+ d.mesh.recomputeAllNormals();+ d.bvh.build(d.mesh);+ // Roughness: mean distance of each vertex from its neighbours' average.+ auto spread = [&] {+ float sum = 0;+ int n = 0;+ for (uint32_t v = 0; v < d.mesh.vertexCount(); ++v) {+ if (d.mesh.positions[v].z < 0.95f) continue;+ glm::vec3 avg(0.0f);+ for (uint32_t u : d.mesh.neighbors(v)) avg += d.mesh.positions[u];+ avg /= float(d.mesh.neighbors(v).size());+ sum += glm::distance(avg, d.mesh.positions[v]);+ ++n;+ }+ return sum / float(n);+ };+ float before = spread();+ DabParams p;+ p.center = glm::vec3(0, 0, 1);+ p.radius = 0.6f;+ p.strength = 1.0f;+ d.sculptor.beginStroke(d.mesh, "Smooth");+ for (int i = 0; i < 5; ++i) d.sculptor.dab(d.mesh, d.bvh, BrushType::Smooth, p, Symmetry{false, false, false});+ d.sculptor.endStroke();+ CHECK(spread() < before * 0.5f);+}++TEST(move_brush_drags_region) {+ Document d = makeDoc(makeIcosphere(4));+ DabParams p;+ p.center = glm::vec3(0, 0, 1);+ p.radius = 0.4f;+ p.strength = 1.0f;+ d.sculptor.beginStroke(d.mesh, "Move");+ d.sculptor.beginGrab(d.mesh, d.bvh, p, Symmetry{false, false, false});+ d.sculptor.grab(d.mesh, d.bvh, glm::vec3(0, 0, 0.5f));+ d.sculptor.endStroke();+ float maxZ = 0;+ for (const auto& v : d.mesh.positions) maxZ = std::max(maxZ, v.z);+ CHECK(std::abs(maxZ - 1.5f) < 0.01f);+}++TEST(loop_subdivision) {+ Mesh m = makeIcosphere(2);+ Mesh s = loopSubdivide(m);+ CHECK(s.triangleCount() == m.triangleCount() * 4);+ CHECK(s.vertexCount() == m.vertexCount() + m.triangleCount() * 3 / 2);+ for (const auto& p : s.positions) CHECK(glm::length(p) > 0.9f && glm::length(p) < 1.01f);++ Mesh plane = makePlane(4);+ Mesh sp = loopSubdivide(plane);+ CHECK(sp.triangleCount() == plane.triangleCount() * 4);+ for (const auto& p : sp.positions) CHECK(std::abs(p.y) < 1e-6f); // stays flat+ // Corners are kept in place.+ AABB b = sp.bounds();+ CHECK(std::abs(b.min.x + 1.0f) < 1e-5f && std::abs(b.max.z - 1.0f) < 1e-5f);+}++TEST(obj_roundtrip) {+ const std::string in = tempPath("sculptforge_test_in.obj");+ {+ std::ofstream f(in);+ f << "# quad + negative indices\nv 0 0 0\nv 1 0 0\nv 1 1 0\nv 0 1 0\nvt 0 0\n"+ "f 1/1 2/1 3/1 4/1\nv 2 0 0\nf -4 -1 -3\n";+ }+ Mesh m;+ std::string err;+ CHECK(loadObj(in, m, err));+ CHECK(m.vertexCount() == 5);+ CHECK(m.triangleCount() == 3);++ const std::string out = tempPath("sculptforge_test_out.obj");+ CHECK(saveObj(out, m, err));+ Mesh back;+ CHECK(loadObj(out, back, err));+ CHECK(back.positions == m.positions);+ CHECK(back.triangles == m.triangles);++ CHECK(!loadObj(tempPath("does_not_exist_sculptforge.obj"), back, err));+ {+ std::ofstream f(in);+ f << "v 0 0 0\nf 1 2 3\n";+ }+ CHECK(!loadObj(in, back, err));+ std::filesystem::remove(in);+ std::filesystem::remove(out);+}++TEST(commands_and_tool_schema) {+ CommandRegistry reg;+ Document d;+ CHECK(reg.execute(d, "new_sphere", {{"subdivisions", 2.0}}).ok);+ CHECK(d.mesh.triangleCount() == 320);+ CHECK(reg.execute(d, "subdivide").ok);+ CHECK(d.mesh.triangleCount() == 1280);+ CHECK(reg.execute(d, "undo").ok);+ CHECK(d.mesh.triangleCount() == 320);+ CHECK(reg.execute(d, "redo").ok);+ CHECK(d.mesh.triangleCount() == 1280);+ CHECK(!reg.execute(d, "open_obj").ok); // missing required path+ CHECK(!reg.execute(d, "no_such_command").ok);++ std::string schema = reg.toolSchemaJson();+ CHECK(schema.front() == '[' && schema.back() == ']');+ CHECK(schema.find("\"name\":\"subdivide\"") != std::string::npos);+ CHECK(schema.find("\"required\":[\"path\"]") != std::string::npos);+}++TEST(sculpt_layers_blend_and_undo) {+ Document d = makeDoc(makeIcosphere(3));+ const std::vector<glm::vec3> original = d.mesh.positions;+ int smile = d.mesh.addLayer("Smile");+ DabParams p;+ p.center = glm::vec3(0, 0, 1);+ p.viewDir = glm::vec3(0, 0, -1);+ p.radius = 0.5f;+ p.strength = 1.0f;+ CHECK(d.sculptor.beginStroke(d.mesh, "Standard", smile));+ d.sculptor.dab(d.mesh, d.bvh, BrushType::Standard, p, Symmetry{false, false, false});+ d.undo.push(d.sculptor.endStroke());+ const std::vector<glm::vec3> sculpted = d.mesh.positions;+ CHECK(sculpted != original);+ CHECK(d.mesh.base == original); // stroke went into the layer, not the base++ d.mesh.setLayerWeight(smile, 0.0f);+ for (size_t i = 0; i < original.size(); ++i) CHECK(glm::distance(d.mesh.positions[i], original[i]) < 1e-6f);+ d.mesh.setLayerWeight(smile, 0.5f);+ for (size_t i = 0; i < original.size(); ++i)+ CHECK(glm::distance(d.mesh.positions[i], (original[i] + sculpted[i]) * 0.5f) < 1e-5f);++ // Undo after changing the weight removes exactly the stroke's offsets.+ d.undo.undo(d.mesh, d.bvh);+ for (size_t i = 0; i < original.size(); ++i) CHECK(glm::distance(d.mesh.positions[i], original[i]) < 1e-6f);++ // A layer at weight 0 refuses strokes.+ d.mesh.setLayerWeight(smile, 0.0f);+ CHECK(!d.sculptor.beginStroke(d.mesh, "Standard", smile));+}++TEST(layers_survive_subdivision) {+ Mesh m = makeIcosphere(2);+ int l = m.addLayer("Bulge");+ for (size_t v = 0; v < m.vertexCount(); ++v) m.layers[l].delta[v] = m.positions[v] * 0.1f;+ m.setLayerWeight(l, 0.7f);+ Mesh s = loopSubdivide(m);+ CHECK(s.layers.size() == 1 && s.layers[0].weight == 0.7f);+ for (size_t v = 0; v < s.vertexCount(); ++v)+ CHECK(glm::distance(s.positions[v], s.base[v] + 0.7f * s.layers[0].delta[v]) < 1e-5f);+}++TEST(decimation_and_lods) {+ Mesh m = makeIcosphere(5); // 20480 tris+ Mesh d = decimate(m, 2000);+ CHECK(d.triangleCount() <= 2000 && d.triangleCount() > 1800);+ // Still closed and manifold: V - E + F = 2.+ CHECK(long(d.vertexCount()) - long(d.triangleCount() * 3 / 2) + long(d.triangleCount()) == 2);+ for (const auto& p : d.positions) CHECK(std::abs(glm::length(p) - 1.0f) < 1e-4f); // subset of sphere verts+ float minR = 1e9f;+ for (const auto& t : d.triangles)+ minR = std::min(minR, glm::length((d.positions[t.x] + d.positions[t.y] + d.positions[t.z]) / 3.0f));+ CHECK(minR > 0.95f); // shape preserved++ m.addLayer("Blink");+ auto lods = generateLods(m, 4, 0.5f);+ CHECK(lods.size() == 4);+ CHECK(lods[3].triangleCount() <= lods[0].triangleCount() / 8 + 8);+ for (const auto& lod : lods) CHECK(lod.layers.size() == 1 && lod.layers[0].delta.size() == lod.vertexCount());++ Mesh plane = makePlane(32);+ Mesh dp = decimate(plane, 200);+ AABB b = dp.bounds();+ CHECK(std::abs(b.min.x + 1.0f) < 1e-5f && std::abs(b.max.x - 1.0f) < 1e-5f); // boundary kept+}++TEST(glb_export) {+ Mesh m = makeIcosphere(1);+ int l = m.addLayer("Smile");+ m.layers[l].delta[0] = glm::vec3(0, 0.1f, 0);+ const std::string path = tempPath("sculptforge_test.glb");+ std::string err;+ CHECK(saveGlb(path, m, "Head", err));+ std::ifstream f(path, std::ios::binary);+ std::string data((std::istreambuf_iterator<char>(f)), std::istreambuf_iterator<char>());+ CHECK(data.size() > 20 && data.substr(0, 4) == "glTF");+ uint32_t total = 0, jsonLen = 0;+ std::memcpy(&total, data.data() + 8, 4);+ std::memcpy(&jsonLen, data.data() + 12, 4);+ CHECK(total == data.size());+ CHECK(jsonLen % 4 == 0);+ std::string json = data.substr(20, jsonLen);+ CHECK(json.find("\"targets\"") != std::string::npos);+ CHECK(json.find("\"targetNames\":[\"Smile\"]") != std::string::npos);+ f.close();+ std::filesystem::remove(path);+}++TEST(script_windows_paths) {+ std::vector<ScriptStatement> st;+ std::string err;+ const std::string windowsPath = R"(open path="C:\Users\me\sculpts\head.obj")";+ CHECK(parseScript(windowsPath, st, err));+ CHECK(st.size() == 1 && std::get<std::string>(st[0].args["path"]) == "C:\\Users\\me\\sculpts\\head.obj");+ const std::string quoted = R"(brush_ai prompt="say \"hi\"")";+ CHECK(parseScript(quoted, st, err) && std::get<std::string>(st[0].args["prompt"]) == "say \"hi\"");+}++TEST(script_parser_and_pipeline) {+ std::vector<ScriptStatement> st;+ std::string err;+ CHECK(parseScript("new_sphere subdivisions=2; layer_add name=\"Big Smile\"\n# comment\ndecimate ratio=0.5", st, err));+ CHECK(st.size() == 3);+ CHECK(st[0].command == "new_sphere" && std::get<double>(st[0].args["subdivisions"]) == 2.0);+ CHECK(std::get<std::string>(st[1].args["name"]) == "Big Smile");+ CHECK(!parseScript("subdivide oops", st, err));++ CommandRegistry reg;+ Document d;+ CHECK(parseScript("new_sphere subdivisions=4; layer_add name=Smile; decimate ratio=0.25", st, err));+ for (const auto& s : st) CHECK(reg.execute(d, s.command, s.args).ok);+ CHECK(d.mesh.layers.size() == 1);+ CHECK(d.mesh.triangleCount() <= 1280);+ const std::string base = tempPath("sculptforge_lod.glb");+ CHECK(reg.execute(d, "export_lods", {{"path", base}, {"levels", 3.0}}).ok);+ for (int i = 0; i < 3; ++i) {+ auto p = std::filesystem::temp_directory_path() / ("sculptforge_lod_LOD" + std::to_string(i) + ".glb");+ CHECK(std::filesystem::exists(p));+ std::filesystem::remove(p);+ }+}++TEST(json_roundtrip) {+ Json j;+ std::string err;+ const std::string text = "{\"a\":[1,2.5,-3e2],\"b\":{\"c\":\"x\\\"y\xc3\xa9\\n\"},\"d\":true,\"e\":null}";+ CHECK(Json::parse(text, j, err));+ CHECK(j["a"].size() == 3 && j["a"][1].asNumber() == 2.5 && j["a"][2].asNumber() == -300.0);+ CHECK(j["b"]["c"].asString() == "x\"y\xc3\xa9\n");+ CHECK(j["d"].asBool() && j["e"].isNull() && j["missing"].isNull());+ Json back;+ CHECK(Json::parse(j.dump(), back, err));+ CHECK(back.dump() == j.dump());+ CHECK(!Json::parse("{\"a\":}", back, err));+ CHECK(!Json::parse("[1,2", back, err));+ CHECK(!Json::parse("{} trailing", back, err));+}++TEST(brush_recipe_roundtrip_and_clamp) {+ auto presets = builtinBrushRecipes();+ CHECK(presets.size() >= 6);+ for (const auto& r : presets) {+ BrushRecipe back = BrushRecipe::fromJson(r.toJson());+ CHECK(back.toJson().dump() == r.toJson().dump());+ }+ Json wild;+ std::string err;+ CHECK(Json::parse(R"({"name":"Wild","depth":7,"pattern":"scales","plane":"bogus","spacing":-1})", wild, err));+ BrushRecipe r = BrushRecipe::fromJson(wild);+ CHECK(r.depth == 1.0f && r.spacing == 0.02f);+ CHECK(r.pattern == BrushRecipe::Pattern::Scales && r.plane == BrushRecipe::Plane::None);++ const std::string path = tempPath("sculptforge_test.sfbrush");+ CHECK(presets[2].save(path, err));+ BrushRecipe loaded;+ CHECK(BrushRecipe::load(path, loaded, err));+ CHECK(loaded.name == presets[2].name && loaded.pattern == presets[2].pattern);+ std::filesystem::remove(path);++ // Schema lists every parameter as required (structured-output compatible).+ Json schema = recipeJsonSchema();+ CHECK(schema["required"].size() == recipeParams().size() + 2);+ CHECK(schema["additionalProperties"].isBool() && !schema["additionalProperties"].asBool());+}++TEST(recipe_brushes_sculpt) {+ for (const auto& recipe : builtinBrushRecipes()) {+ Document d = makeDoc(makeIcosphere(5));+ const auto before = d.mesh.positions;+ DabParams p;+ p.center = glm::vec3(0, 0, 1);+ p.viewDir = glm::vec3(0, 0, -1);+ p.radius = 0.4f;+ p.strength = 1.0f;+ p.strokeDelta = glm::vec3(0.05f, 0, 0);+ CHECK(d.sculptor.beginStroke(d.mesh, recipe.name));+ for (int i = 0; i < 3; ++i) d.sculptor.dabRecipe(d.mesh, d.bvh, recipe, p, Symmetry{false, false, false});+ UndoRecord rec = d.sculptor.endStroke();+ CHECK(!rec.empty());+ bool finite = true;+ float moved = 0;+ for (size_t i = 0; i < before.size(); ++i) {+ finite = finite && std::isfinite(d.mesh.positions[i].x) && std::isfinite(d.mesh.positions[i].y);+ moved = std::max(moved, glm::distance(before[i], d.mesh.positions[i]));+ }+ CHECK(finite);+ if (moved <= 1e-5f) std::printf(" recipe '%s' did not move the surface\n", recipe.name.c_str());+ CHECK(moved > 1e-5f);+ }+ // Carving vs building: depth sign controls direction.+ BrushRecipe carve;+ carve.depth = -1.0f;+ Document d = makeDoc(makeIcosphere(4));+ DabParams p;+ p.center = glm::vec3(0, 0, 1);+ p.viewDir = glm::vec3(0, 0, -1);+ p.radius = 0.4f;+ p.strength = 1.0f;+ d.sculptor.beginStroke(d.mesh, "Carve");+ d.sculptor.dabRecipe(d.mesh, d.bvh, carve, p, Symmetry{false, false, false});+ d.sculptor.endStroke();+ float minR = 2.0f;+ for (const auto& v : d.mesh.positions) minR = std::min(minR, glm::length(v));+ CHECK(minR < 0.99f);+}++TEST(brush_commands) {+ CommandRegistry reg;+ Document d;+ CHECK(reg.execute(d, "brush_create", {{"name", std::string("Lizard Skin")}, {"pattern", std::string("scales")},+ {"patternAmount", 0.8}, {"depth", 0.3}}).ok);+ CHECK(d.activeBrush >= 0 && d.brushes[d.activeBrush].name == "Lizard Skin");+ CHECK(d.brushes[d.activeBrush].pattern == BrushRecipe::Pattern::Scales);+ const std::string path = tempPath("sculptforge_lizard.sfbrush");+ CHECK(reg.execute(d, "brush_save", {{"path", path}}).ok);+ Document d2;+ CHECK(reg.execute(d2, "brush_load", {{"path", path}}).ok);+ CHECK(d2.brushes[d2.activeBrush].patternAmount == 0.8f);+ std::filesystem::remove(path);+ CHECK(reg.toolSchemaJson().find("\"tipSharpness\"") != std::string::npos);+}++TEST(ai_request_and_response_parsing) {+ using namespace sf::ai;+ AiSettings anth = AiSettings::defaults(AiSettings::Provider::Anthropic);+ anth.apiKey = "test-key";+ BrushRecipe current = builtinBrushRecipes()[0];+ std::vector<ChatMessage> history = {composeUserMessage("make it sharper", ¤t)};+ std::string body = buildRequestBody(anth, history);+ Json req;+ std::string err;+ CHECK(Json::parse(body, req, err));+ CHECK(req["model"].asString() == "claude-opus-5-5");+ CHECK(req["output_config"]["format"]["type"].asString() == "json_schema");+ CHECK(req["output_config"]["effort"].asString() == "low");+ CHECK(req["fallbacks"].asString() == "default");+ CHECK(req["messages"][0]["content"].asString().find("Wrinkle") != std::string::npos);+ auto headers = requestHeaders(anth);+ CHECK(std::find(headers.begin(), headers.end(), "x-api-key: test-key") != headers.end());+ CHECK(std::find(headers.begin(), headers.end(), "anthropic-version: 2023-06-01") != headers.end());++ // Anthropic response with an (empty) thinking block followed by the JSON text.+ Json resp = Json::object();+ resp.set("stop_reason", "end_turn");+ Json content = Json::array();+ Json thinking = Json::object();+ thinking.set("type", "thinking");+ thinking.set("thinking", "");+ content.push(thinking);+ Json text = Json::object();+ text.set("type", "text");+ text.set("text", R"({"reply":"Sharper now.","brush":{"name":"Wrinkle","depth":-0.7,"tipSharpness":0.9}})");+ content.push(text);+ resp.set("content", content);+ std::string raw;+ BrushSuggestion s = parseResponse(anth, 200, resp.dump(), &raw);+ CHECK(s.ok && s.reply == "Sharper now." && s.recipe.tipSharpness == 0.9f && s.recipe.depth == -0.7f);+ CHECK(raw.find("Sharper") != std::string::npos);++ resp.set("stop_reason", "refusal");+ CHECK(!parseResponse(anth, 200, resp.dump()).ok);+ CHECK(parseResponse(anth, 401, R"({"type":"error","error":{"message":"invalid x-api-key"}})").error.find("rejected") !=+ std::string::npos);++ // OpenAI-compatible (e.g. Ollama) reply wrapped in a code fence.+ AiSettings local = AiSettings::defaults(AiSettings::Provider::OpenAICompatible);+ Json req2;+ CHECK(Json::parse(buildRequestBody(local, history), req2, err));+ CHECK(req2["messages"][0]["role"].asString() == "system");+ std::string fenced = "Here you go:\n```json\n{\"reply\":\"Gritty!\",\"brush\":{\"name\":\"Grit\",\"pattern\":\"noise\","+ "\"patternAmount\":0.9}}\n```";+ Json oresp = Json::object();+ Json choices = Json::array();+ Json choice = Json::object();+ Json msg = Json::object();+ msg.set("content", fenced);+ choice.set("message", msg);+ choices.push(choice);+ oresp.set("choices", choices);+ BrushSuggestion s2 = parseResponse(local, 200, oresp.dump());+ CHECK(s2.ok && s2.recipe.name == "Grit" && s2.recipe.pattern == BrushRecipe::Pattern::Noise);+}++namespace {++Image makeImage(int w, int h, const std::function<glm::vec4(float, float)>& f) {+ Image img;+ img.width = w;+ img.height = h;+ img.rgba.resize(size_t(w) * size_t(h) * 4);+ for (int y = 0; y < h; ++y)+ for (int x = 0; x < w; ++x) {+ glm::vec4 c = glm::clamp(f((x + 0.5f) / w, (y + 0.5f) / h), 0.0f, 1.0f) * 255.0f;+ for (int k = 0; k < 4; ++k) img.rgba[(size_t(y) * w + x) * 4 + k] = uint8_t(c[k] + 0.5f);+ }+ return img;+}++// Minimal 32-bit BMP writer so command tests can load real files.+void writeBmp(const std::string& path, const Image& img) {+ std::ofstream f(path, std::ios::binary);+ auto u32 = [&](uint32_t v) { f.write(reinterpret_cast<const char*>(&v), 4); };+ auto u16 = [&](uint16_t v) { f.write(reinterpret_cast<const char*>(&v), 2); };+ const uint32_t dataSize = uint32_t(img.width * img.height * 4);+ f.write("BM", 2);+ u32(54 + dataSize); u32(0); u32(54);+ u32(40); u32(uint32_t(img.width)); u32(uint32_t(-img.height)); u16(1); u16(32); u32(0); u32(dataSize);+ u32(2835); u32(2835); u32(0); u32(0);+ for (size_t i = 0; i < img.rgba.size(); i += 4) {+ const char px[4] = {char(img.rgba[i + 2]), char(img.rgba[i + 1]), char(img.rgba[i]), char(255)};+ f.write(px, 4);+ }+}++} // namespace++TEST(image_relief) {+ Image ramp = makeImage(64, 32, [](float u, float) { return glm::vec4(u, u, u, 1.0f); });+ ReliefOptions o;+ o.resolution = 64;+ Mesh m = makeImageRelief(ramp, o);+ AABB b = m.bounds();+ CHECK(std::abs(b.extent().x - 2.0f) < 1e-4f && std::abs(b.extent().y - 1.0f) < 1e-4f); // keeps aspect+ float leftZ = 0, rightZ = 0;+ for (const auto& p : m.positions) {+ if (p.x < -0.95f) leftZ = std::max(leftZ, p.z);+ if (p.x > 0.95f) rightZ = std::max(rightZ, p.z);+ }+ CHECK(rightZ > leftZ + 0.1f); // light side is higher+}++TEST(image_inflate_silhouette) {+ // A disk on a transparent background inflates into a closed, symmetric, ball-like shape.+ Image disk = makeImage(96, 96, [](float u, float v) {+ float d = glm::length(glm::vec2(u, v) - 0.5f);+ return glm::vec4(0.2f, 0.2f, 0.2f, d < 0.4f ? 1.0f : 0.0f);+ });+ InflateOptions o;+ o.resolution = 64;+ o.subdivisions = 0;+ std::string err;+ Mesh m = inflateSilhouette(disk, o, &err);+ CHECK(m.triangleCount() > 100);+ {+ std::map<std::pair<uint32_t, uint32_t>, int> edges;+ for (const auto& t : m.triangles)+ for (int k = 0; k < 3; ++k) ++edges[std::minmax(t[k], t[(k + 1) % 3])];+ bool manifold = true;+ for (const auto& [e, n] : edges) manifold = manifold && n == 2;+ CHECK(manifold); // closed, no pinches+ CHECK(long(m.vertexCount()) - long(edges.size()) + long(m.triangleCount()) == 2); // sphere topology+ }+ AABB b = m.bounds();+ CHECK(b.extent().z > b.extent().x * 0.6f); // round, not flat+ CHECK(std::abs(b.max.z + b.min.z) < 0.02f * b.extent().z); // front/back symmetric++ // Dark shape on a white page (no transparency) also works.+ Image sketch = makeImage(80, 60, [](float u, float v) {+ bool in = std::abs(u - 0.5f) < 0.3f && std::abs(v - 0.5f) < 0.2f;+ return in ? glm::vec4(0, 0, 0, 1) : glm::vec4(1, 1, 1, 1);+ });+ CHECK(inflateSilhouette(sketch, o, &err).triangleCount() > 0);+ Image blank = makeImage(32, 32, [](float, float) { return glm::vec4(1); });+ CHECK(inflateSilhouette(blank, o, &err).triangleCount() == 0 && !err.empty());+}++TEST(image_projection) {+ Mesh m = makeIcosphere(4);+ const auto before = m.positions;+ Image white = makeImage(16, 16, [](float, float) { return glm::vec4(1); });+ glm::vec3 eye(0, 0, 5);+ glm::mat4 vp = glm::perspective(glm::radians(35.0f), 1.0f, 0.1f, 20.0f) *+ glm::lookAt(eye, glm::vec3(0), glm::vec3(0, 1, 0));+ ProjectOptions o;+ o.depth = 0.1f;+ size_t n = projectImage(m, -1, white, vp, 1.0f, eye, o);+ CHECK(n > 0);+ bool backUntouched = true, frontRaised = false;+ for (size_t i = 0; i < before.size(); ++i) {+ if (before[i].z < -0.1f) backUntouched = backUntouched && m.positions[i] == before[i];+ if (before[i].z > 0.95f) frontRaised = frontRaised || glm::length(m.positions[i]) > 1.05f;+ }+ CHECK(backUntouched && frontRaised);+}++TEST(gltf_roundtrip_with_layers) {+ Mesh m = makeIcosphere(3);+ int l = m.addLayer("Smile");+ for (size_t v = 0; v < m.vertexCount(); ++v) m.layers[l].delta[v] = glm::vec3(0, m.positions[v].y * 0.1f, 0);+ m.setLayerWeight(l, 0.25f);+ const std::string path = tempPath("sculptforge_roundtrip.glb");+ std::string err;+ CHECK(saveGlb(path, m, "Head", err));+ Mesh back;+ CHECK(loadGltf(path, back, err));+ CHECK(back.vertexCount() == m.vertexCount() && back.triangleCount() == m.triangleCount());+ CHECK(back.layers.size() == 1 && back.layers[0].name == "Smile" && std::abs(back.layers[0].weight - 0.25f) < 1e-6f);+ for (size_t v = 0; v < m.vertexCount(); ++v) CHECK(glm::distance(back.positions[v], m.positions[v]) < 1e-5f);+ std::filesystem::remove(path);++ CommandRegistry reg;+ Document d;+ CHECK(reg.execute(d, "new_sphere", {{"subdivisions", 2.0}}).ok);+ CHECK(reg.execute(d, "export_glb", {{"path", path}}).ok);+ CHECK(reg.execute(d, "open", {{"path", path}}).ok);+ CHECK(d.mesh.triangleCount() == 320);+ std::filesystem::remove(path);+}++TEST(image_commands) {+ const std::string bmp = tempPath("sculptforge_sketch.bmp");+ writeBmp(bmp, makeImage(64, 64, [](float u, float v) {+ float d = glm::length(glm::vec2(u, v) - 0.5f);+ return d < 0.35f ? glm::vec4(0.1f, 0.1f, 0.1f, 1) : glm::vec4(1, 1, 1, 1);+ }));+ CommandRegistry reg;+ Document d;+ CommandResult r = reg.execute(d, "image_inflate", {{"path", bmp}});+ CHECK(r.ok);+ if (!r.ok) std::printf(" %s\n", r.message.c_str());+ CHECK(d.mesh.triangleCount() > 500);+ CHECK(reg.execute(d, "image_project", {{"path", bmp}, {"depth", 0.02}}).ok);+ CHECK(reg.execute(d, "undo").ok);+ CHECK(reg.execute(d, "image_relief", {{"path", bmp}, {"resolution", 64.0}}).ok);+ CHECK(d.mesh.triangleCount() == 64u * 64u * 2u);+ CHECK(!reg.execute(d, "image_relief", {{"path", tempPath("missing_sculptforge.png")}}).ok);+ std::filesystem::remove(bmp);+}++// --- Voxel remesh, splats, PLY, USD, glTF splats, MCP, image-to-3D services ---++bool isClosedManifold(const Mesh& m) {+ std::map<std::pair<uint32_t, uint32_t>, int> edges;+ for (const auto& t : m.triangles)+ for (int k = 0; k < 3; ++k) ++edges[std::minmax(t[k], t[(k + 1) % 3])];+ for (const auto& [e, n] : edges)+ if (n != 2) return false;+ return !edges.empty();+}++double signedVolume(const Mesh& m) {+ double v = 0.0;+ for (const auto& t : m.triangles)+ v += double(glm::dot(m.positions[t.x], glm::cross(m.positions[t.y], m.positions[t.z]))) / 6.0;+ return v;+}++TEST(voxel_remesh) {+ Mesh sphere = makeIcosphere(4);+ std::string err;+ Mesh r = voxelRemesh(sphere, 64, &err);+ CHECK(r.triangleCount() > 1000);+ CHECK(isClosedManifold(r));+ const double vol = signedVolume(r);+ CHECK(vol > 0.0); // faces point outwards+ CHECK(std::abs(vol - 4.18879) < 0.04 * 4.18879); // unit-sphere volume preserved within 4%+ float worst = 0.0f;+ for (const auto& p : r.positions) worst = std::max(worst, std::abs(glm::length(p) - 1.0f));+ CHECK(worst < 0.03f);++ // Two overlapping spheres merge into one closed surface.+ Mesh a = makeIcosphere(3), b = makeIcosphere(3), both;+ for (auto& p : b.positions) p += glm::vec3(1.2f, 0, 0);+ both.positions = a.positions;+ both.positions.insert(both.positions.end(), b.positions.begin(), b.positions.end());+ both.triangles = a.triangles;+ for (auto t : b.triangles) both.triangles.push_back(t + glm::uvec3(uint32_t(a.vertexCount())));+ both.rebuildTopology();+ Mesh merged = voxelRemesh(both, 80, &err);+ CHECK(isClosedManifold(merged));+ CHECK(long(merged.vertexCount()) - long(merged.triangleCount() * 3 / 2) + long(merged.triangleCount()) == 2); // one piece++ CommandRegistry reg;+ Document d;+ CHECK(reg.execute(d, "new_sphere", {{"subdivisions", 3.0}}).ok);+ CHECK(reg.execute(d, "remesh", {{"resolution", 48.0}}).ok);+ CHECK(reg.execute(d, "undo").ok && d.mesh.triangleCount() == 1280);+ CHECK(!voxelRemesh(Mesh(), 64, &err).triangleCount() && !err.empty());+}++TEST(splats_mesh_conversions) {+ Mesh sphere = makeIcosphere(4);+ MeshToSplatsOptions o;+ o.count = 40000;+ SplatCloud c = meshToSplats(sphere, o);+ CHECK(c.size() == 40000 && c.validate().empty());+ bool onSurface = true, flat = true;+ for (size_t i = 0; i < c.size(); ++i) {+ onSurface = onSurface && std::abs(glm::length(c.positions[i]) - 1.0f) < 0.01f;+ const glm::vec3 n = glm::mat3_cast(c.rotations[i])[2]; // thin axis+ flat = flat && std::abs(glm::dot(n, glm::normalize(c.positions[i]))) > 0.98f && c.scales[i].z < c.scales[i].x * 0.2f;+ }+ CHECK(onSurface && flat);++ std::string err;+ SplatToMeshOptions so;+ so.resolution = 64;+ Mesh back = splatsToMesh(c, so, &err);+ CHECK(back.triangleCount() > 1000);+ CHECK(isClosedManifold(back));+ CHECK(signedVolume(back) > 0.0);+ const AABB b = back.bounds();+ CHECK(std::abs(b.extent().x - 2.0f) < 0.15f && std::abs(b.center().y) < 0.05f);++ // Floaters are dropped: only the largest solid survives.+ SplatCloud noisy = c;+ noisy.positions.push_back(glm::vec3(0, 3, 0));+ noisy.rotations.push_back(glm::quat(1, 0, 0, 0));+ noisy.scales.push_back(glm::vec3(0.1f));+ noisy.opacities.push_back(1.0f);+ noisy.sh.push_back(glm::vec3(0));+ so.keepFraction = 1.0f;+ CHECK(splatsToMesh(noisy, so, &err).bounds().max.y < 1.2f);++ // Placement: rotate/fit keep the data, bake applies it.+ SplatCloud t = c;+ t.transform = glm::translate(glm::mat4(1.0f), glm::vec3(5, 0, 0)) * glm::scale(glm::mat4(1.0f), glm::vec3(3.0f));+ fitSplats(t);+ CHECK(glm::length(t.bounds(0.9f).center()) < 0.05f);+ CHECK(std::abs(t.bounds(0.9f).extent().x - 2.0f) < 0.05f);+ t.bakeTransform();+ CHECK(t.transform == glm::mat4(1.0f) && glm::length(t.bounds(0.9f).center()) < 0.05f);+ CHECK(cleanSplats(noisy, 0.05f, 0.9f) > 0);+}++SplatCloud testCloud(int degree) {+ SplatCloud c;+ c.resize(50, degree);+ for (size_t i = 0; i < c.size(); ++i) {+ const float f = float(i);+ c.positions[i] = glm::vec3(std::sin(f), std::cos(f * 0.7f), f * 0.01f);+ c.rotations[i] = glm::normalize(glm::quat(1.0f, 0.1f * f, -0.05f * f, 0.3f));+ c.scales[i] = glm::vec3(0.01f + 0.001f * f, 0.02f, 0.005f);+ c.opacities[i] = 0.1f + 0.015f * f;+ for (int k = 0; k < c.shCount(); ++k) c.sh[i * size_t(c.shCount()) + size_t(k)] = glm::vec3(0.1f * float(k), -0.2f * f / 50.0f, 0.3f);+ }+ return c;+}++bool sameRotation(const glm::quat& a, const glm::quat& b, float tol) { return std::abs(std::abs(glm::dot(a, b)) - 1.0f) < tol; }++TEST(splat_ply_and_dot_splat_roundtrip) {+ for (int degree : {0, 1, 3}) {+ SplatCloud c = testCloud(degree);+ const std::string path = tempPath("sculptforge_splats.ply");+ std::string err;+ CHECK(saveSplatPly(path, c, err));+ Mesh m;+ SplatCloud back;+ PlyContent content;+ CHECK(loadPly(path, m, back, content, err) && content == PlyContent::Splats);+ CHECK(back.size() == c.size() && back.shDegree == degree);+ bool same = true;+ for (size_t i = 0; i < c.size(); ++i) {+ same = same && glm::distance(back.positions[i], c.positions[i]) < 1e-6f;+ same = same && glm::distance(back.scales[i], c.scales[i]) < 1e-6f;+ same = same && std::abs(back.opacities[i] - c.opacities[i]) < 1e-5f;+ same = same && sameRotation(back.rotations[i], c.rotations[i], 1e-6f);+ }+ for (size_t k = 0; k < c.sh.size(); ++k) same = same && glm::distance(back.sh[k], c.sh[k]) < 1e-6f;+ CHECK(same);+ std::filesystem::remove(path);+ }+ SplatCloud c = testCloud(0);+ const std::string path = tempPath("sculptforge_splats.splat");+ std::string err;+ CHECK(saveDotSplat(path, c, err));+ SplatCloud back;+ CHECK(loadDotSplat(path, back, err) && back.size() == c.size());+ bool close = true;+ for (size_t i = 0; i < c.size(); ++i) {+ close = close && glm::distance(back.positions[i], c.positions[i]) < 1e-6f;+ close = close && glm::distance(back.color(i), glm::clamp(c.color(i), 0.0f, 1.0f)) < 0.01f;+ close = close && sameRotation(back.rotations[i], c.rotations[i], 0.01f);+ }+ CHECK(close);+ std::filesystem::remove(path);+}++TEST(ply_mesh_and_point_cloud) {+ const std::string path = tempPath("sculptforge_quad.ply");+ {+ std::ofstream f(path);+ f << "ply\nformat ascii 1.0\ncomment a unit quad pyramid\nelement vertex 5\nproperty float x\nproperty float y\n"+ "property float z\nelement face 5\nproperty list uchar int vertex_indices\nend_header\n"+ "0 0 0\n1 0 0\n1 1 0\n0 1 0\n0.5 0.5 1\n4 3 2 1 0\n3 0 1 4\n3 1 2 4\n3 2 3 4\n3 3 0 4\n";+ }+ Mesh m;+ SplatCloud s;+ PlyContent content;+ std::string err;+ CHECK(loadPly(path, m, s, content, err) && content == PlyContent::Mesh);+ CHECK(m.vertexCount() == 5 && m.triangleCount() == 6 && isClosedManifold(m));+ {+ std::ofstream f(path, std::ios::binary);+ f << "ply\nformat binary_big_endian 1.0\nelement vertex 2\nproperty double x\nproperty double y\nproperty double z\n"+ "property uchar red\nproperty uchar green\nproperty uchar blue\nend_header\n";+ auto be = [&](double d) {+ uint64_t u;+ std::memcpy(&u, &d, 8);+ for (int k = 7; k >= 0; --k) f.put(char((u >> (k * 8)) & 0xFF));+ };+ be(1); be(2); be(3); f.put(char(255)); f.put(0); f.put(0);+ be(-1); be(0); be(0); f.put(0); f.put(0); f.put(char(255));+ }+ CHECK(loadPly(path, m, s, content, err) && content == PlyContent::Splats);+ CHECK(s.size() == 2 && s.positions[0] == glm::vec3(1, 2, 3) && glm::distance(s.color(0), glm::vec3(1, 0, 0)) < 1e-5f);+ std::filesystem::remove(path);+ CHECK(!loadPly(tempPath("missing_sculptforge.ply"), m, s, content, err));+}++TEST(zip_and_usdz_alignment) {+ const char* digits = "123456789";+ CHECK(crc32(reinterpret_cast<const uint8_t*>(digits), 9) == 0xCBF43926u);+ const std::string path = tempPath("sculptforge_test.zip");+ std::vector<ZipEntry> entries = {{"a.usda", std::vector<uint8_t>(100, 'a')}, {"textures/b.png", std::vector<uint8_t>(7, 'b')}};+ std::string err;+ CHECK(writeStoredZip(path, entries, 64, err));+ std::vector<uint8_t> z;+ {+ std::ifstream f(path, std::ios::binary); // closed before remove(): Windows can't delete open files+ z.assign(std::istreambuf_iterator<char>(f), std::istreambuf_iterator<char>());+ }+ // Find each entry's data via the local headers and check 64-byte alignment.+ size_t p = 0, aligned = 0;+ while (p + 30 <= z.size() && z[p] == 'P' && z[p + 1] == 'K' && z[p + 2] == 3 && z[p + 3] == 4) {+ const size_t nameLen = z[p + 26] | z[p + 27] << 8, extra = z[p + 28] | z[p + 29] << 8;+ const size_t size = z[p + 18] | z[p + 19] << 8 | z[p + 20] << 16 | size_t(z[p + 21]) << 24;+ const size_t data = p + 30 + nameLen + extra;+ aligned += data % 64 == 0;+ p = data + size;+ }+ CHECK(aligned == 2);+ std::vector<ZipEntry> back;+ CHECK(readStoredZip(path, back, err) && back.size() == 2 && back[1].name == "textures/b.png" && back[0].data == entries[0].data);+ std::filesystem::remove(path);+}++TEST(usd_roundtrip_mesh_layers_splats) {+ Mesh m = makeIcosphere(2);+ int smile = m.addLayer("Smile 2");+ int blink = m.addLayer("Blink");+ for (size_t v = 0; v < m.vertexCount(); ++v)+ if (m.positions[v].y > 0.5f) m.layers[smile].delta[v] = glm::vec3(0, 0.1f, 0);+ m.layers[blink].delta[3] = glm::vec3(0.2f, 0, 0);+ m.setLayerWeight(smile, 0.75f);+ m.setLayerWeight(blink, 0.0f);+ SplatCloud c = testCloud(1);+ c.transform = glm::translate(glm::mat4(1.0f), glm::vec3(0, 2, 0));++ for (const char* name : {"sculptforge_test.usda", "sculptforge_test.usdz"}) {+ const std::string path = tempPath(name);+ std::string err;+ CHECK(saveUsd(path, &m, &c, "Hero Head", err));+ Mesh back;+ SplatCloud sback;+ CHECK(loadUsd(path, back, sback, err));+ if (!err.empty()) std::printf(" %s\n", err.c_str());+ CHECK(back.vertexCount() == m.vertexCount() && back.triangleCount() == m.triangleCount());+ CHECK(back.layers.size() == 2 && back.layers[0].name == "Smile_2" && std::abs(back.layers[0].weight - 0.75f) < 1e-6f);+ bool same = true;+ for (size_t v = 0; v < m.vertexCount(); ++v) {+ same = same && glm::distance(back.base[v], m.base[v]) < 1e-6f;+ same = same && glm::distance(back.layers[0].delta[v], m.layers[0].delta[v]) < 1e-6f;+ same = same && glm::distance(back.layers[1].delta[v], m.layers[1].delta[v]) < 1e-6f;+ same = same && glm::distance(back.positions[v], m.positions[v]) < 1e-5f;+ }+ CHECK(same);+ CHECK(sback.size() == c.size() && sback.shDegree == 1);+ bool splatsSame = true;+ for (size_t i = 0; i < c.size(); ++i) {+ splatsSame = splatsSame && glm::distance(sback.worldPosition(i), c.worldPosition(i)) < 1e-5f;+ splatsSame = splatsSame && sameRotation(sback.rotations[i], c.rotations[i], 1e-6f);+ splatsSame = splatsSame && std::abs(sback.opacities[i] - c.opacities[i]) < 1e-6f;+ }+ for (size_t k = 0; k < c.sh.size(); ++k) splatsSame = splatsSame && glm::distance(sback.sh[k], c.sh[k]) < 1e-6f;+ CHECK(splatsSame);+ std::filesystem::remove(path);+ }+ CHECK(usdIdentifier("3 eyes!") == "_3_eyes_");+}++TEST(usd_reader_handles_foreign_files) {+ const std::string path = tempPath("sculptforge_foreign.usda");+ {+ std::ofstream f(path);+ f << R"(#usda 1.0+(+ doc = """A multi-line+ doc with { braces } and "quotes" """+ upAxis = "Z"+ customLayerData = { string creator = "test" }+)++class "Template" { def Mesh "Ignored" { point3f[] points = [(9,9,9),(9,9,8),(9,8,9)] int[] faceVertexCounts = [3] int[] faceVertexIndices = [0,1,2] } }++def Xform "World" (+ kind = "assembly"+)+{+ double3 xformOp:translate = (0, 0, 10) # moved up 10 in Z-up+ float3 xformOp:scale = (2, 2, 2)+ uniform token[] xformOpOrder = ["xformOp:translate", "xformOp:scale"]++ def Mesh "Quad" (+ prepend apiSchemas = ["MaterialBindingAPI"]+ )+ {+ uniform token orientation = "leftHanded"+ int[] faceVertexCounts = [4]+ int[] faceVertexIndices = [0, 1, 2, 3]+ point3f[] points.timeSamples = {+ 1: [(0, 0, 0), (1, 0, 0), (1, 1, 0), (0, 1, 0)],+ 2: [(5, 5, 5), (6, 5, 5), (6, 6, 5), (5, 6, 5)],+ }+ color3f[] primvars:displayColor = [(1, 0, 0)] (+ interpolation = "constant"+ )+ rel material:binding = </World/Looks/Red>+ }++ variantSet "lod" = {+ "high" { def Mesh "Variant" { point3f[] points = [(7,7,7)] } }+ }+}+)";+ }+ Mesh m;+ SplatCloud s;+ std::string err;+ CHECK(loadUsd(path, m, s, err));+ if (!err.empty()) std::printf(" %s\n", err.c_str());+ CHECK(m.vertexCount() == 4 && m.triangleCount() == 2 && s.empty());+ const AABB b = m.bounds();+ // Z-up converted to Y-up: translate (0,0,10) becomes +10 in Y; scale 2 makes the quad 2x2 in the X/-Z plane.+ CHECK(std::abs(b.min.y - 10.0f) < 1e-5f && std::abs(b.max.y - 10.0f) < 1e-5f);+ CHECK(std::abs(b.extent().x - 2.0f) < 1e-5f && std::abs(b.extent().z - 2.0f) < 1e-5f);+ // Left-handed winding was flipped: the quad (CCW in XY seen from +Z) now faces -Z-up = ... down after conversion.+ const glm::vec3 n = glm::cross(m.positions[m.triangles[0].y] - m.positions[m.triangles[0].x],+ m.positions[m.triangles[0].z] - m.positions[m.triangles[0].x]);+ CHECK(n.y < 0.0f);+ {+ std::ofstream f(path, std::ios::binary);+ f << "PXR-USDC binary";+ }+ CHECK(!loadUsd(path, m, s, err) && err.find("usdc") != std::string::npos);+ std::filesystem::remove(path);+}++TEST(gltf_gaussian_splatting_roundtrip) {+ SplatCloud c = testCloud(2);+ c.transform = glm::translate(glm::mat4(1.0f), glm::vec3(1, 2, 3)) * glm::scale(glm::mat4(1.0f), glm::vec3(0.5f));+ const std::string path = tempPath("sculptforge_splats.glb");+ std::string err;+ CHECK(saveSplatGlb(path, c, err));+ Mesh m;+ SplatCloud back;+ CHECK(loadGltf(path, m, err, &back));+ CHECK(m.triangleCount() == 0 && back.size() == c.size() && back.shDegree == 2);+ bool same = true;+ for (size_t i = 0; i < c.size(); ++i) {+ same = same && glm::distance(back.worldPosition(i), c.worldPosition(i)) < 1e-5f;+ same = same && sameRotation(back.rotations[i], c.rotations[i], 1e-6f);+ same = same && glm::distance(back.scales[i], c.scales[i]) < 1e-7f;+ }+ for (size_t k = 0; k < c.sh.size(); ++k) same = same && glm::distance(back.sh[k], c.sh[k]) < 1e-6f;+ CHECK(same);+ // Opening it as a document keeps the mesh and adds the splats.+ CommandRegistry reg;+ Document d;+ CHECK(reg.execute(d, "new_sphere", {{"subdivisions", 1.0}}).ok);+ CHECK(reg.execute(d, "open", {{"path", path}}).ok && d.splats.size() == c.size() && d.mesh.triangleCount() == 80);+ CHECK(!loadGltf(path, m, err)); // without a splat target, a splat-only file has no meshes+ std::filesystem::remove(path);+}++TEST(splat_commands) {+ CommandRegistry reg;+ Document d;+ CHECK(!reg.execute(d, "splat_to_mesh").ok); // nothing loaded+ CHECK(reg.execute(d, "new_sphere", {{"subdivisions", 3.0}}).ok);+ const uint64_t v0 = d.splatsVersion;+ CHECK(reg.execute(d, "mesh_to_splats", {{"count", 20000.0}}).ok && d.splats.size() == 20000 && d.splatsVersion != v0);+ CHECK(reg.execute(d, "splat_transform", {{"rotate_x", 180.0}, {"fit", true}}).ok);+ CHECK(reg.execute(d, "splat_clean", {{"min_opacity", 0.5}}).ok);+ CHECK(reg.execute(d, "splat_to_mesh", {{"resolution", 48.0}}).ok && isClosedManifold(d.mesh));+ CHECK(reg.execute(d, "undo").ok && d.mesh.triangleCount() == 1280);+ for (const char* ext : {".ply", ".splat", ".glb", ".usda", ".usdz"}) {+ const std::string path = tempPath((std::string("sculptforge_cmd_splats") + ext).c_str());+ CHECK(reg.execute(d, "splat_save", {{"path", path}}).ok);+ Document e;+ CHECK(reg.execute(e, "open", {{"path", path}}).ok && e.splats.size() == d.splats.size());+ std::filesystem::remove(path);+ }+ CHECK(!reg.execute(d, "splat_save", {{"path", tempPath("sculptforge_bad.txt")}}).ok);+ const std::string usd = tempPath("sculptforge_cmd.usdz");+ CHECK(reg.execute(d, "export_usd", {{"path", usd}}).ok);+ std::filesystem::remove(usd);+ CHECK(reg.execute(d, "splat_clear").ok && d.splats.empty());+}++TEST(mcp_server_protocol) {+ CommandRegistry reg;+ Document d;+ auto call = [&](const std::string& line) {+ Json j;+ std::string err;+ const std::string out = handleMcpMessage(reg, d, line);+ if (!out.empty()) Json::parse(out, j, err);+ return j;+ };+ Json init = call(R"({"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-06-18","capabilities":{},"clientInfo":{"name":"t","version":"1"}}})");+ CHECK(init["result"]["protocolVersion"].asString() == "2025-06-18");+ CHECK(init["result"]["serverInfo"]["name"].asString() == "sculptforge" && init["result"]["capabilities"]["tools"].isObject());+ CHECK(handleMcpMessage(reg, d, R"({"jsonrpc":"2.0","method":"notifications/initialized"})").empty());+ Json list = call(R"({"jsonrpc":"2.0","id":2,"method":"tools/list"})");+ bool hasRemesh = false, schemasOk = true;+ for (const auto& t : list["result"]["tools"].items()) {+ hasRemesh = hasRemesh || t["name"].asString() == "remesh";+ schemasOk = schemasOk && t["inputSchema"]["type"].asString() == "object";+ }+ CHECK(hasRemesh && schemasOk && list["result"]["tools"].size() == reg.all().size());+ Json ok = call(R"({"jsonrpc":"2.0","id":"a","method":"tools/call","params":{"name":"new_sphere","arguments":{"subdivisions":2}}})");+ CHECK(ok["id"].asString() == "a" && !ok["result"]["isError"].asBool(true) && d.mesh.triangleCount() == 320);+ CHECK(ok["result"]["content"][0]["text"].asString().find("320") != std::string::npos);+ Json bad = call(R"({"jsonrpc":"2.0","id":4,"method":"tools/call","params":{"name":"open","arguments":{"path":"/nonexistent/x.obj"}}})");+ CHECK(bad["result"]["isError"].asBool(false));+ CHECK(call(R"({"jsonrpc":"2.0","id":5,"method":"nope"})")["error"]["code"].asNumber() == -32601);+ CHECK(call("not json")["error"]["code"].asNumber() == -32700);+ CHECK(call(R"({"jsonrpc":"2.0","id":6,"method":"ping"})")["result"].isObject());+}++TEST(image_to_3d_service_requests) {+ const uint8_t man[] = {'M', 'a', 'n'};+ CHECK(ai::base64Encode(man, 3) == "TWFu" && ai::base64Encode(man, 2) == "TWE=" && ai::base64Encode(man, 1) == "TQ==");+ Json body;+ std::string err;+ CHECK(Json::parse(ai::falSubmitBody("fal-ai/trellis-2", "data:x"), body, err) && body["image_url"].asString() == "data:x");+ CHECK(Json::parse(ai::falSubmitBody("fal-ai/hunyuan-3d/v3.1/rapid/image-to-3d", "data:x"), body, err) &&+ body["input_image_url"].asString() == "data:x" && body["enable_geometry"].asBool());+ CHECK(Json::parse(ai::meshySubmitBody("", "data:x"), body, err) && body["ai_model"].asString() == "latest" &&+ !body["should_texture"].asBool(true) && body["target_formats"][0].asString() == "glb");++ std::string ext;+ Json r;+ Json::parse(R"({"model_glb":{"url":"https://cdn/x/model.glb","content_type":"model/gltf-binary"}})", r, err);+ CHECK(ai::findModelUrl(r, &ext) == "https://cdn/x/model.glb" && ext == ".glb");+ Json::parse(R"({"model_glb":{"url":"https://cdn/x/mesh.obj?sig=1","content_type":"text/plain"}})", r, err);+ CHECK(ai::findModelUrl(r, &ext) == "https://cdn/x/mesh.obj?sig=1" && ext == ".obj");+ Json::parse(R"({"model_urls":{"glb":"https://assets.meshy.ai/t/model.glb?Expires=1","fbx":"https://a/b.fbx"}})", r, err);+ CHECK(ai::findModelUrl(r, &ext) == "https://assets.meshy.ai/t/model.glb?Expires=1");+ Json::parse(R"({"outputs":[{"file":{"href":"https://x/deep.glb"}}]})", r, err);+ CHECK(ai::findModelUrl(r, &ext) == "https://x/deep.glb");+ Json::parse(R"({"images":[]})", r, err);+ CHECK(ai::findModelUrl(r, &ext).empty());++ // A small character on a big transparent canvas is cropped and centred on a square.+ Image canvas = makeImage(400, 200, [](float u, float v) {+ const bool body = u > 0.1f && u < 0.2f && v > 0.5f && v < 0.9f;+ return glm::vec4(1, 0, 0, body ? 1.0f : 0.0f);+ });+ Image framed = canvas.framedSubject(0.08f);+ CHECK(framed.width == framed.height && framed.width < 120 && framed.width > 80);+ CHECK(framed.rgba[(size_t(framed.height / 2) * size_t(framed.width) + size_t(framed.width / 2)) * 4 + 3] == 255);+ Image big = makeImage(3000, 1500, [](float, float) { return glm::vec4(0.5f, 0.5f, 0.5f, 1); });+ Image small = big.downscaled(1024);+ CHECK(small.width == 1024 && small.height == 512 && small.rgba[0] > 120 && small.rgba[0] < 135);+ std::vector<uint8_t> png;+ CHECK(small.encodePng(png) && png.size() > 8 && png[1] == 'P' && png[2] == 'N' && png[3] == 'G');++ // Missing keys fail fast with a helpful message, without touching the network.+ ai::AiSettings s;+ s.falKey.clear();+ s.generatorService = "fal";+ if (!std::getenv("FAL_KEY")) {+ ai::GeneratorResult g = ai::generate3D(s, "unused.png", tempPath("sculptforge_gen"));+ CHECK(!g.ok && g.error.find("fal.ai") != std::string::npos);+ }+ // Settings survive a save/load.+ s.generatorService = "meshy";+ s.falModel = "fal-ai/hunyuan-3d/v3.1/pro/image-to-3d";+ ai::AiSettings loaded = ai::AiSettings::fromJson(s.toJson());+ CHECK(loaded.generatorService == "meshy" && loaded.falModel == s.falModel && loaded.meshyEndpoint == "https://api.meshy.ai");+}++// --- FBX export/import, Unreal preset and link ---++TEST(fbx_roundtrip_layers_and_lods) {+ Mesh m = makeIcosphere(3);+ int smile = m.addLayer("Smile");+ for (size_t v = 0; v < m.vertexCount(); ++v)+ if (m.positions[v].y > 0.3f) m.layers[smile].delta[v] = glm::vec3(0.0f, 0.05f, 0.02f);+ m.setLayerWeight(smile, 0.3f);+ const std::string path = tempPath("sculptforge_test.fbx");+ std::string err;+ FbxExportOptions o;+ o.scale = 100.0f; // metres -> centimetres+ CHECK(saveFbx(path, "Head", {&m}, o, err));+ {+ std::ifstream f(path, std::ios::binary);+ std::vector<char> head(27);+ f.read(head.data(), 27);+ CHECK(std::memcmp(head.data(), "Kaydara FBX Binary \0\x1a\0", 23) == 0);+ uint32_t version;+ std::memcpy(&version, head.data() + 23, 4);+ CHECK(version == 7400);+ }+ Mesh back;+ CHECK(loadFbx(path, back, err));+ if (!err.empty()) std::printf(" %s\n", err.c_str());+ CHECK(back.vertexCount() == m.vertexCount() && back.triangleCount() == m.triangleCount());+ CHECK(back.layers.size() == 1 && back.layers[0].name == "Smile" && std::abs(back.layers[0].weight - 0.3f) < 1e-5f);+ bool same = true;+ for (size_t v = 0; v < m.vertexCount(); ++v) {+ same = same && glm::distance(back.base[v], m.base[v]) < 1e-5f;+ same = same && glm::distance(back.layers[0].delta[v], m.layers[0].delta[v]) < 1e-5f;+ }+ CHECK(same);+ CHECK(signedVolume(back) > 0.0); // winding survives the trip++ // LOD group: import takes LOD0 only.+ std::vector<Mesh> lods = generateLods(makeIcosphere(4), 3, 0.5f);+ CHECK(saveFbx(path, "Rock", {&lods[0], &lods[1], &lods[2]}, o, err));+ CHECK(loadFbx(path, back, err) && back.triangleCount() == lods[0].triangleCount());+ CHECK(!saveFbx(path, "Empty", {}, o, err));+ std::filesystem::remove(path);+ CHECK(!loadFbx(tempPath("missing_sculptforge.fbx"), back, err));+}++TEST(unreal_export_preset) {+ Document d;+ CommandRegistry reg;+ CHECK(reg.execute(d, "new_sphere", {{"subdivisions", 3.0}}).ok);+ const std::string folder = tempPath("sculptforge_unreal_test");+ UnrealExportOptions o;+ o.folder = folder;+ o.heightCm = 180.0f;+ o.lods = 3;+ UnrealExportResult r;+ std::string err;+ CHECK(exportForUnreal(d, o, r, err));+ CHECK(r.assetName == "SM_Sculpt" && !r.skeletal && r.lodCount == 3 && std::abs(r.scale - 90.0f) < 1e-3f);+ Mesh back;+ CHECK(loadFbx(r.path, back, err) && std::abs(back.bounds().extent().y - 1.8f) < 1e-3f); // 180 cm = 1.8 m++ CHECK(reg.execute(d, "layer_add", {{"name", std::string("Blink")}}).ok);+ CHECK(exportForUnreal(d, o, r, err));+ CHECK(r.assetName == "SK_Sculpt" && r.skeletal && r.lodCount == 1); // morph targets need a skeletal mesh+ o.assetName = "My Rock!";+ CHECK(exportForUnreal(d, o, r, err) && r.assetName == "My_Rock_");+ CHECK(reg.execute(d, "export_unreal", {{"folder", folder}, {"lods", 2.0}}).ok);+ CHECK(reg.execute(d, "export_fbx", {{"path", folder + "/plain.fbx"}, {"lods", 2.0}}).ok);+ std::filesystem::remove_all(folder);+}++TEST(unreal_link_messages_and_script) {+ Json msg;+ std::string err;+ CHECK(Json::parse(link::unrealMessage("ping", "abc", "", ""), msg, err));+ CHECK(msg["version"].asNumber() == 1 && msg["magic"].asString() == "ue_py" && msg["type"].asString() == "ping" &&+ msg["source"].asString() == "abc" && !msg.has("dest") && !msg.has("data"));+ CHECK(Json::parse(link::unrealMessage("open_connection", "a", "b", R"({"command_ip":"127.0.0.1","command_port":6776})"), msg, err));+ CHECK(msg["dest"].asString() == "b" && msg["data"]["command_port"].asNumber() == 6776);++ link::UnrealImport im;+ im.fbxPath = "C:\\Art\\it's.fbx";+ im.assetName = "SK_Head";+ im.skeletal = true;+ std::string py = link::unrealImportScript(im);+ CHECK(py.find("'C:\\\\Art\\\\it\\'s.fbx'") != std::string::npos); // escaped Python literal+ CHECK(py.find("FBXIT_SKELETAL_MESH") != std::string::npos && py.find("import_morph_targets', True") != std::string::npos);+ CHECK(py.find("automated_import_should_detect_type', False") != std::string::npos);+ CHECK(py.find("SCULPTFORGE_IMPORTED") != std::string::npos && py.find("urllib") == std::string::npos);+ im.skeletal = false;+ im.lods = true;+ im.downloadUrl = "http://10.0.0.5:5000/token/SM_Rock.fbx";+ py = link::unrealImportScript(im);+ CHECK(py.find("import_mesh_lo_ds', True") != std::string::npos && py.find("FBXIT_STATIC_MESH") != std::string::npos);+ CHECK(py.find("urlopen('http://10.0.0.5:5000/token/SM_Rock.fbx'") != std::string::npos);++ link::UnrealEditor ed;+ ed.address = "127.0.0.1";+ CHECK(ed.local());+ ed.address = "192.0.2.10";+ ed.machine = "some-other-machine-name";+ CHECK(!ed.local());+ CHECK(link::UnrealEndpoint().multicastTtl == 0 && link::UnrealEndpoint::network().multicastTtl == 1);+}++TEST(free_huggingface_models) {+ const auto& presets = ai::hfPresets();+ CHECK(presets.size() >= 4);+ bool wellFormed = true, usesImage = true;+ for (const auto& p : presets) {+ wellFormed = wellFormed && std::string(p.space).rfind("https://", 0) == 0 && !p.steps.empty();+ bool image = false;+ for (const auto& step : p.steps)+ for (const auto& a : step.args) {+ image = image || a == "$IMG";+ if (a != "$IMG" && a.rfind("$OUT", 0) != 0) {+ Json v;+ std::string err;+ wellFormed = wellFormed && Json::parse(a, v, err); // literal args must be valid JSON+ }+ }+ usesImage = usesImage && image;+ }+ CHECK(wellFormed && usesImage);+ ai::AiSettings defaults;+ CHECK(defaults.generatorService == "huggingface" && defaults.hfModel == presets[0].id);+ defaults.hfModel = "trellis-2";+ defaults.hfToken = "hf_test";+ ai::AiSettings loaded = ai::AiSettings::fromJson(defaults.toJson());+ CHECK(loaded.hfModel == "trellis-2" && loaded.resolvedHfToken() == "hf_test");+ CHECK(ai::friendlyGradioError("You have exceeded your ZeroGPU quota (120s requested vs. 0s left).").find("free GPU time") !=+ std::string::npos);+ CHECK(ai::friendlyGradioError("some other failure") == "some other failure");+ std::string png, err;+ CHECK(!ai::prepareImagePng(tempPath("missing_sculptforge.png"), png, err));++ // Text to 3D.+ CHECK(!ai::hfTextPresets().empty());+ bool usesPrompt = true;+ for (const auto& p : ai::hfTextPresets()) {+ bool prompt = false;+ for (const auto& step : p.steps)+ for (const auto& a : step.args) prompt = prompt || a == "$PROMPT";+ usesPrompt = usesPrompt && prompt;+ }+ CHECK(usesPrompt);+ Json body;+ CHECK(Json::parse(ai::meshyTextBody("", "a fox"), body, err) && body["mode"].asString() == "preview" &&+ body["prompt"].asString() == "a fox" && body["ai_model"].asString() == "latest");+ CHECK(Json::parse(ai::falTextBody(std::string(300, 'x')), body, err) && body["prompt"].asString().size() == 200 &&+ body["enable_geometry"].asBool());+ ai::AiSettings offline;+ offline.generatorService = "inflate";+ CHECK(!ai::generate3DFromText(offline, "a fox", tempPath("sf_text")).ok);+ CHECK(!ai::generate3DFromText(offline, " ", tempPath("sf_text")).ok);+ Json r;+ Json::parse(R"({"model_obj":{"url":"https://cdn/x/model.obj"},"model_urls":{"obj":"https://cdn/x/model.obj"}})", r, err);+ std::string ext;+ CHECK(ai::findModelUrl(r, &ext) == "https://cdn/x/model.obj" && ext == ".obj");+}diff --git a/tests/test_main.cpp b/tests/test_main.cppindex 27f8782c..2dfac195 100644--- a/tests/test_main.cpp+++ b/tests/test_main.cpp@@ -1,1315 +1,14 @@// SculptForge - open source digital sculpting// SPDX-License-Identifier: GPL-3.0-or-later//-// Dependency-free unit tests for the core library.-#include "ai/BrushAssistant.h"-#include "ai/GradioClient.h"-#include "ai/ImageTo3DService.h"-#include "cli/McpServer.h"-#include "core/BrushRecipe.h"-#include "core/Commands.h"-#include "core/Json.h"-#include "core/Decimate.h"-#include "core/ImageTo3D.h"-#include "core/Script.h"-#include "io/GltfIO.h"-#include "core/Primitives.h"-#include "core/Sculpt.h"-#include "io/ObjIO.h"-#include "io/FbxIO.h"-#include "io/PlyIO.h"-#include "core/EnginePresets.h"-#include "link/UnrealLink.h"-#include "io/UsdIO.h"-#include "io/Zip.h"-#include "core/Splats.h"-#include "core/Voxel.h"+// Runs every TEST registered by the tests/test_*.cpp files.+#include "TestHarness.h"-#include <cmath>-#include <algorithm>-#include <cstring>-#include <glm/gtc/matrix_transform.hpp>#include <cstdio>-#include <filesystem>-#include <fstream>-#include <functional>-#include <map>-#include <string>-#include <vector>--using namespace sf;--namespace {--int g_failures = 0;-int g_checks = 0;--#define CHECK(cond) \- do { \- ++g_checks; \- if (!(cond)) { \- ++g_failures; \- std::printf(" FAILED %s:%d: %s\n", __FILE__, __LINE__, #cond); \- } \- } while (0)--struct TestCase {- const char* name;- std::function<void()> fn;-};-std::vector<TestCase>& registry() {- static std::vector<TestCase> r;- return r;-}-struct Register {- Register(const char* n, std::function<void()> f) { registry().push_back({n, std::move(f)}); }-};-#define TEST(name) \- static void name(); \- static Register reg_##name(#name, name); \- static void name()--Document makeDoc(Mesh m) {- Document d;- d.setMesh(std::move(m));- return d;-}--std::string tempPath(const char* name) { return (std::filesystem::temp_directory_path() / name).string(); }--} // namespace--TEST(icosphere_counts) {- Mesh m = makeIcosphere(3);- CHECK(m.triangleCount() == 20u * 64u);- // Closed genus-0 surface: V - E + F = 2 with E = 3F/2.- CHECK(long(m.vertexCount()) - long(m.triangleCount() * 3 / 2) + long(m.triangleCount()) == 2);- for (const auto& p : m.positions) CHECK(std::abs(glm::length(p) - 1.0f) < 1e-5f);- for (uint32_t v = 0; v < m.vertexCount(); ++v) CHECK(glm::dot(m.normals[v], m.positions[v]) > 0.99f);-}--TEST(bvh_raycast_and_query) {- Mesh m = makeIcosphere(4);- BVH bvh;- bvh.build(m);- RayHit hit;- CHECK(bvh.raycast(m, glm::vec3(0, 0, 5), glm::vec3(0, 0, -1), hit));- CHECK(std::abs(hit.position.z - 1.0f) < 0.01f);- CHECK(!bvh.raycast(m, glm::vec3(0, 3, 5), glm::vec3(0, 0, -1), hit));-- std::vector<uint32_t> found;- glm::vec3 c(0, 0, 1);- bvh.queryVertices(m, c, 0.3f, found);- size_t brute = 0;- for (const auto& p : m.positions) brute += glm::distance(p, c) <= 0.3f;- CHECK(found.size() == brute);- CHECK(brute > 0);-}--TEST(standard_brush_raises_surface_with_symmetry) {- Document d = makeDoc(makeIcosphere(4));- DabParams p;- p.center = glm::normalize(glm::vec3(0.5f, 0.2f, 0.8f));- p.viewDir = -p.center;- p.radius = 0.3f;- p.strength = 1.0f;- d.sculptor.beginStroke(d.mesh, "Standard");- d.sculptor.dab(d.mesh, d.bvh, BrushType::Standard, p, Symmetry{true, false, false});- UndoRecord r = d.sculptor.endStroke();- CHECK(!r.empty());-- float maxR = 0, maxMirroredR = 0;- for (const auto& v : d.mesh.positions) {- if (v.x > 0.2f) maxR = std::max(maxR, glm::length(v));- if (v.x < -0.2f) maxMirroredR = std::max(maxMirroredR, glm::length(v));- }- CHECK(maxR > 1.01f);- CHECK(std::abs(maxR - maxMirroredR) < 1e-4f);-- // BVH must still find the raised surface.- RayHit hit;- CHECK(d.bvh.raycast(d.mesh, p.center * 5.0f, -p.center, hit));- CHECK(glm::length(hit.position) > 1.005f);-}--TEST(undo_redo_restores_positions) {- Document d = makeDoc(makeIcosphere(3));- const std::vector<glm::vec3> original = d.mesh.positions;- DabParams p;- p.center = glm::vec3(0, 0, 1);- p.viewDir = glm::vec3(0, 0, -1);- p.radius = 0.5f;- for (BrushType t : {BrushType::Standard, BrushType::Clay, BrushType::Inflate, BrushType::Crease}) {- d.sculptor.beginStroke(d.mesh, brushName(t));- d.sculptor.dab(d.mesh, d.bvh, t, p, Symmetry{});- d.undo.push(d.sculptor.endStroke());- }- const std::vector<glm::vec3> sculpted = d.mesh.positions;- CHECK(sculpted != original);- while (d.undo.canUndo()) d.undo.undo(d.mesh, d.bvh);- CHECK(d.mesh.positions == original);- while (d.undo.canRedo()) d.undo.redo(d.mesh, d.bvh);- CHECK(d.mesh.positions == sculpted);-}--TEST(smooth_reduces_noise) {- Document d = makeDoc(makeIcosphere(4));- for (size_t i = 0; i < d.mesh.vertexCount(); ++i)- d.mesh.positions[i] *= 1.0f + 0.05f * float((i * 2654435761u) % 7) / 7.0f;- d.mesh.recomputeAllNormals();- d.bvh.build(d.mesh);- // Roughness: mean distance of each vertex from its neighbours' average.- auto spread = [&] {- float sum = 0;- int n = 0;- for (uint32_t v = 0; v < d.mesh.vertexCount(); ++v) {- if (d.mesh.positions[v].z < 0.95f) continue;- glm::vec3 avg(0.0f);- for (uint32_t u : d.mesh.neighbors(v)) avg += d.mesh.positions[u];- avg /= float(d.mesh.neighbors(v).size());- sum += glm::distance(avg, d.mesh.positions[v]);- ++n;- }- return sum / float(n);- };- float before = spread();- DabParams p;- p.center = glm::vec3(0, 0, 1);- p.radius = 0.6f;- p.strength = 1.0f;- d.sculptor.beginStroke(d.mesh, "Smooth");- for (int i = 0; i < 5; ++i) d.sculptor.dab(d.mesh, d.bvh, BrushType::Smooth, p, Symmetry{false, false, false});- d.sculptor.endStroke();- CHECK(spread() < before * 0.5f);-}--TEST(move_brush_drags_region) {- Document d = makeDoc(makeIcosphere(4));- DabParams p;- p.center = glm::vec3(0, 0, 1);- p.radius = 0.4f;- p.strength = 1.0f;- d.sculptor.beginStroke(d.mesh, "Move");- d.sculptor.beginGrab(d.mesh, d.bvh, p, Symmetry{false, false, false});- d.sculptor.grab(d.mesh, d.bvh, glm::vec3(0, 0, 0.5f));- d.sculptor.endStroke();- float maxZ = 0;- for (const auto& v : d.mesh.positions) maxZ = std::max(maxZ, v.z);- CHECK(std::abs(maxZ - 1.5f) < 0.01f);-}--TEST(loop_subdivision) {- Mesh m = makeIcosphere(2);- Mesh s = loopSubdivide(m);- CHECK(s.triangleCount() == m.triangleCount() * 4);- CHECK(s.vertexCount() == m.vertexCount() + m.triangleCount() * 3 / 2);- for (const auto& p : s.positions) CHECK(glm::length(p) > 0.9f && glm::length(p) < 1.01f);-- Mesh plane = makePlane(4);- Mesh sp = loopSubdivide(plane);- CHECK(sp.triangleCount() == plane.triangleCount() * 4);- for (const auto& p : sp.positions) CHECK(std::abs(p.y) < 1e-6f); // stays flat- // Corners are kept in place.- AABB b = sp.bounds();- CHECK(std::abs(b.min.x + 1.0f) < 1e-5f && std::abs(b.max.z - 1.0f) < 1e-5f);-}--TEST(obj_roundtrip) {- const std::string in = tempPath("sculptforge_test_in.obj");- {- std::ofstream f(in);- f << "# quad + negative indices\nv 0 0 0\nv 1 0 0\nv 1 1 0\nv 0 1 0\nvt 0 0\n"- "f 1/1 2/1 3/1 4/1\nv 2 0 0\nf -4 -1 -3\n";- }- Mesh m;- std::string err;- CHECK(loadObj(in, m, err));- CHECK(m.vertexCount() == 5);- CHECK(m.triangleCount() == 3);-- const std::string out = tempPath("sculptforge_test_out.obj");- CHECK(saveObj(out, m, err));- Mesh back;- CHECK(loadObj(out, back, err));- CHECK(back.positions == m.positions);- CHECK(back.triangles == m.triangles);-- CHECK(!loadObj(tempPath("does_not_exist_sculptforge.obj"), back, err));- {- std::ofstream f(in);- f << "v 0 0 0\nf 1 2 3\n";- }- CHECK(!loadObj(in, back, err));- std::filesystem::remove(in);- std::filesystem::remove(out);-}--TEST(commands_and_tool_schema) {- CommandRegistry reg;- Document d;- CHECK(reg.execute(d, "new_sphere", {{"subdivisions", 2.0}}).ok);- CHECK(d.mesh.triangleCount() == 320);- CHECK(reg.execute(d, "subdivide").ok);- CHECK(d.mesh.triangleCount() == 1280);- CHECK(reg.execute(d, "undo").ok);- CHECK(d.mesh.triangleCount() == 320);- CHECK(reg.execute(d, "redo").ok);- CHECK(d.mesh.triangleCount() == 1280);- CHECK(!reg.execute(d, "open_obj").ok); // missing required path- CHECK(!reg.execute(d, "no_such_command").ok);-- std::string schema = reg.toolSchemaJson();- CHECK(schema.front() == '[' && schema.back() == ']');- CHECK(schema.find("\"name\":\"subdivide\"") != std::string::npos);- CHECK(schema.find("\"required\":[\"path\"]") != std::string::npos);-}--TEST(sculpt_layers_blend_and_undo) {- Document d = makeDoc(makeIcosphere(3));- const std::vector<glm::vec3> original = d.mesh.positions;- int smile = d.mesh.addLayer("Smile");- DabParams p;- p.center = glm::vec3(0, 0, 1);- p.viewDir = glm::vec3(0, 0, -1);- p.radius = 0.5f;- p.strength = 1.0f;- CHECK(d.sculptor.beginStroke(d.mesh, "Standard", smile));- d.sculptor.dab(d.mesh, d.bvh, BrushType::Standard, p, Symmetry{false, false, false});- d.undo.push(d.sculptor.endStroke());- const std::vector<glm::vec3> sculpted = d.mesh.positions;- CHECK(sculpted != original);- CHECK(d.mesh.base == original); // stroke went into the layer, not the base-- d.mesh.setLayerWeight(smile, 0.0f);- for (size_t i = 0; i < original.size(); ++i) CHECK(glm::distance(d.mesh.positions[i], original[i]) < 1e-6f);- d.mesh.setLayerWeight(smile, 0.5f);- for (size_t i = 0; i < original.size(); ++i)- CHECK(glm::distance(d.mesh.positions[i], (original[i] + sculpted[i]) * 0.5f) < 1e-5f);-- // Undo after changing the weight removes exactly the stroke's offsets.- d.undo.undo(d.mesh, d.bvh);- for (size_t i = 0; i < original.size(); ++i) CHECK(glm::distance(d.mesh.positions[i], original[i]) < 1e-6f);-- // A layer at weight 0 refuses strokes.- d.mesh.setLayerWeight(smile, 0.0f);- CHECK(!d.sculptor.beginStroke(d.mesh, "Standard", smile));-}--TEST(layers_survive_subdivision) {- Mesh m = makeIcosphere(2);- int l = m.addLayer("Bulge");- for (size_t v = 0; v < m.vertexCount(); ++v) m.layers[l].delta[v] = m.positions[v] * 0.1f;- m.setLayerWeight(l, 0.7f);- Mesh s = loopSubdivide(m);- CHECK(s.layers.size() == 1 && s.layers[0].weight == 0.7f);- for (size_t v = 0; v < s.vertexCount(); ++v)- CHECK(glm::distance(s.positions[v], s.base[v] + 0.7f * s.layers[0].delta[v]) < 1e-5f);-}--TEST(decimation_and_lods) {- Mesh m = makeIcosphere(5); // 20480 tris- Mesh d = decimate(m, 2000);- CHECK(d.triangleCount() <= 2000 && d.triangleCount() > 1800);- // Still closed and manifold: V - E + F = 2.- CHECK(long(d.vertexCount()) - long(d.triangleCount() * 3 / 2) + long(d.triangleCount()) == 2);- for (const auto& p : d.positions) CHECK(std::abs(glm::length(p) - 1.0f) < 1e-4f); // subset of sphere verts- float minR = 1e9f;- for (const auto& t : d.triangles)- minR = std::min(minR, glm::length((d.positions[t.x] + d.positions[t.y] + d.positions[t.z]) / 3.0f));- CHECK(minR > 0.95f); // shape preserved-- m.addLayer("Blink");- auto lods = generateLods(m, 4, 0.5f);- CHECK(lods.size() == 4);- CHECK(lods[3].triangleCount() <= lods[0].triangleCount() / 8 + 8);- for (const auto& lod : lods) CHECK(lod.layers.size() == 1 && lod.layers[0].delta.size() == lod.vertexCount());-- Mesh plane = makePlane(32);- Mesh dp = decimate(plane, 200);- AABB b = dp.bounds();- CHECK(std::abs(b.min.x + 1.0f) < 1e-5f && std::abs(b.max.x - 1.0f) < 1e-5f); // boundary kept-}--TEST(glb_export) {- Mesh m = makeIcosphere(1);- int l = m.addLayer("Smile");- m.layers[l].delta[0] = glm::vec3(0, 0.1f, 0);- const std::string path = tempPath("sculptforge_test.glb");- std::string err;- CHECK(saveGlb(path, m, "Head", err));- std::ifstream f(path, std::ios::binary);- std::string data((std::istreambuf_iterator<char>(f)), std::istreambuf_iterator<char>());- CHECK(data.size() > 20 && data.substr(0, 4) == "glTF");- uint32_t total = 0, jsonLen = 0;- std::memcpy(&total, data.data() + 8, 4);- std::memcpy(&jsonLen, data.data() + 12, 4);- CHECK(total == data.size());- CHECK(jsonLen % 4 == 0);- std::string json = data.substr(20, jsonLen);- CHECK(json.find("\"targets\"") != std::string::npos);- CHECK(json.find("\"targetNames\":[\"Smile\"]") != std::string::npos);- f.close();- std::filesystem::remove(path);-}--TEST(script_windows_paths) {- std::vector<ScriptStatement> st;- std::string err;- const std::string windowsPath = R"(open path="C:\Users\me\sculpts\head.obj")";- CHECK(parseScript(windowsPath, st, err));- CHECK(st.size() == 1 && std::get<std::string>(st[0].args["path"]) == "C:\\Users\\me\\sculpts\\head.obj");- const std::string quoted = R"(brush_ai prompt="say \"hi\"")";- CHECK(parseScript(quoted, st, err) && std::get<std::string>(st[0].args["prompt"]) == "say \"hi\"");-}--TEST(script_parser_and_pipeline) {- std::vector<ScriptStatement> st;- std::string err;- CHECK(parseScript("new_sphere subdivisions=2; layer_add name=\"Big Smile\"\n# comment\ndecimate ratio=0.5", st, err));- CHECK(st.size() == 3);- CHECK(st[0].command == "new_sphere" && std::get<double>(st[0].args["subdivisions"]) == 2.0);- CHECK(std::get<std::string>(st[1].args["name"]) == "Big Smile");- CHECK(!parseScript("subdivide oops", st, err));-- CommandRegistry reg;- Document d;- CHECK(parseScript("new_sphere subdivisions=4; layer_add name=Smile; decimate ratio=0.25", st, err));- for (const auto& s : st) CHECK(reg.execute(d, s.command, s.args).ok);- CHECK(d.mesh.layers.size() == 1);- CHECK(d.mesh.triangleCount() <= 1280);- const std::string base = tempPath("sculptforge_lod.glb");- CHECK(reg.execute(d, "export_lods", {{"path", base}, {"levels", 3.0}}).ok);- for (int i = 0; i < 3; ++i) {- auto p = std::filesystem::temp_directory_path() / ("sculptforge_lod_LOD" + std::to_string(i) + ".glb");- CHECK(std::filesystem::exists(p));- std::filesystem::remove(p);- }-}--TEST(json_roundtrip) {- Json j;- std::string err;- const std::string text = "{\"a\":[1,2.5,-3e2],\"b\":{\"c\":\"x\\\"y\xc3\xa9\\n\"},\"d\":true,\"e\":null}";- CHECK(Json::parse(text, j, err));- CHECK(j["a"].size() == 3 && j["a"][1].asNumber() == 2.5 && j["a"][2].asNumber() == -300.0);- CHECK(j["b"]["c"].asString() == "x\"y\xc3\xa9\n");- CHECK(j["d"].asBool() && j["e"].isNull() && j["missing"].isNull());- Json back;- CHECK(Json::parse(j.dump(), back, err));- CHECK(back.dump() == j.dump());- CHECK(!Json::parse("{\"a\":}", back, err));- CHECK(!Json::parse("[1,2", back, err));- CHECK(!Json::parse("{} trailing", back, err));-}--TEST(brush_recipe_roundtrip_and_clamp) {- auto presets = builtinBrushRecipes();- CHECK(presets.size() >= 6);- for (const auto& r : presets) {- BrushRecipe back = BrushRecipe::fromJson(r.toJson());- CHECK(back.toJson().dump() == r.toJson().dump());- }- Json wild;- std::string err;- CHECK(Json::parse(R"({"name":"Wild","depth":7,"pattern":"scales","plane":"bogus","spacing":-1})", wild, err));- BrushRecipe r = BrushRecipe::fromJson(wild);- CHECK(r.depth == 1.0f && r.spacing == 0.02f);- CHECK(r.pattern == BrushRecipe::Pattern::Scales && r.plane == BrushRecipe::Plane::None);-- const std::string path = tempPath("sculptforge_test.sfbrush");- CHECK(presets[2].save(path, err));- BrushRecipe loaded;- CHECK(BrushRecipe::load(path, loaded, err));- CHECK(loaded.name == presets[2].name && loaded.pattern == presets[2].pattern);- std::filesystem::remove(path);-- // Schema lists every parameter as required (structured-output compatible).- Json schema = recipeJsonSchema();- CHECK(schema["required"].size() == recipeParams().size() + 2);- CHECK(schema["additionalProperties"].isBool() && !schema["additionalProperties"].asBool());-}--TEST(recipe_brushes_sculpt) {- for (const auto& recipe : builtinBrushRecipes()) {- Document d = makeDoc(makeIcosphere(5));- const auto before = d.mesh.positions;- DabParams p;- p.center = glm::vec3(0, 0, 1);- p.viewDir = glm::vec3(0, 0, -1);- p.radius = 0.4f;- p.strength = 1.0f;- p.strokeDelta = glm::vec3(0.05f, 0, 0);- CHECK(d.sculptor.beginStroke(d.mesh, recipe.name));- for (int i = 0; i < 3; ++i) d.sculptor.dabRecipe(d.mesh, d.bvh, recipe, p, Symmetry{false, false, false});- UndoRecord rec = d.sculptor.endStroke();- CHECK(!rec.empty());- bool finite = true;- float moved = 0;- for (size_t i = 0; i < before.size(); ++i) {- finite = finite && std::isfinite(d.mesh.positions[i].x) && std::isfinite(d.mesh.positions[i].y);- moved = std::max(moved, glm::distance(before[i], d.mesh.positions[i]));- }- CHECK(finite);- if (moved <= 1e-5f) std::printf(" recipe '%s' did not move the surface\n", recipe.name.c_str());- CHECK(moved > 1e-5f);- }- // Carving vs building: depth sign controls direction.- BrushRecipe carve;- carve.depth = -1.0f;- Document d = makeDoc(makeIcosphere(4));- DabParams p;- p.center = glm::vec3(0, 0, 1);- p.viewDir = glm::vec3(0, 0, -1);- p.radius = 0.4f;- p.strength = 1.0f;- d.sculptor.beginStroke(d.mesh, "Carve");- d.sculptor.dabRecipe(d.mesh, d.bvh, carve, p, Symmetry{false, false, false});- d.sculptor.endStroke();- float minR = 2.0f;- for (const auto& v : d.mesh.positions) minR = std::min(minR, glm::length(v));- CHECK(minR < 0.99f);-}--TEST(brush_commands) {- CommandRegistry reg;- Document d;- CHECK(reg.execute(d, "brush_create", {{"name", std::string("Lizard Skin")}, {"pattern", std::string("scales")},- {"patternAmount", 0.8}, {"depth", 0.3}}).ok);- CHECK(d.activeBrush >= 0 && d.brushes[d.activeBrush].name == "Lizard Skin");- CHECK(d.brushes[d.activeBrush].pattern == BrushRecipe::Pattern::Scales);- const std::string path = tempPath("sculptforge_lizard.sfbrush");- CHECK(reg.execute(d, "brush_save", {{"path", path}}).ok);- Document d2;- CHECK(reg.execute(d2, "brush_load", {{"path", path}}).ok);- CHECK(d2.brushes[d2.activeBrush].patternAmount == 0.8f);- std::filesystem::remove(path);- CHECK(reg.toolSchemaJson().find("\"tipSharpness\"") != std::string::npos);-}--TEST(ai_request_and_response_parsing) {- using namespace sf::ai;- AiSettings anth = AiSettings::defaults(AiSettings::Provider::Anthropic);- anth.apiKey = "test-key";- BrushRecipe current = builtinBrushRecipes()[0];- std::vector<ChatMessage> history = {composeUserMessage("make it sharper", ¤t)};- std::string body = buildRequestBody(anth, history);- Json req;- std::string err;- CHECK(Json::parse(body, req, err));- CHECK(req["model"].asString() == "claude-opus-5-5");- CHECK(req["output_config"]["format"]["type"].asString() == "json_schema");- CHECK(req["output_config"]["effort"].asString() == "low");- CHECK(req["fallbacks"].asString() == "default");- CHECK(req["messages"][0]["content"].asString().find("Wrinkle") != std::string::npos);- auto headers = requestHeaders(anth);- CHECK(std::find(headers.begin(), headers.end(), "x-api-key: test-key") != headers.end());- CHECK(std::find(headers.begin(), headers.end(), "anthropic-version: 2023-06-01") != headers.end());-- // Anthropic response with an (empty) thinking block followed by the JSON text.- Json resp = Json::object();- resp.set("stop_reason", "end_turn");- Json content = Json::array();- Json thinking = Json::object();- thinking.set("type", "thinking");- thinking.set("thinking", "");- content.push(thinking);- Json text = Json::object();- text.set("type", "text");- text.set("text", R"({"reply":"Sharper now.","brush":{"name":"Wrinkle","depth":-0.7,"tipSharpness":0.9}})");- content.push(text);- resp.set("content", content);- std::string raw;- BrushSuggestion s = parseResponse(anth, 200, resp.dump(), &raw);- CHECK(s.ok && s.reply == "Sharper now." && s.recipe.tipSharpness == 0.9f && s.recipe.depth == -0.7f);- CHECK(raw.find("Sharper") != std::string::npos);-- resp.set("stop_reason", "refusal");- CHECK(!parseResponse(anth, 200, resp.dump()).ok);- CHECK(parseResponse(anth, 401, R"({"type":"error","error":{"message":"invalid x-api-key"}})").error.find("rejected") !=- std::string::npos);-- // OpenAI-compatible (e.g. Ollama) reply wrapped in a code fence.- AiSettings local = AiSettings::defaults(AiSettings::Provider::OpenAICompatible);- Json req2;- CHECK(Json::parse(buildRequestBody(local, history), req2, err));- CHECK(req2["messages"][0]["role"].asString() == "system");- std::string fenced = "Here you go:\n```json\n{\"reply\":\"Gritty!\",\"brush\":{\"name\":\"Grit\",\"pattern\":\"noise\","- "\"patternAmount\":0.9}}\n```";- Json oresp = Json::object();- Json choices = Json::array();- Json choice = Json::object();- Json msg = Json::object();- msg.set("content", fenced);- choice.set("message", msg);- choices.push(choice);- oresp.set("choices", choices);- BrushSuggestion s2 = parseResponse(local, 200, oresp.dump());- CHECK(s2.ok && s2.recipe.name == "Grit" && s2.recipe.pattern == BrushRecipe::Pattern::Noise);-}--namespace {--Image makeImage(int w, int h, const std::function<glm::vec4(float, float)>& f) {- Image img;- img.width = w;- img.height = h;- img.rgba.resize(size_t(w) * size_t(h) * 4);- for (int y = 0; y < h; ++y)- for (int x = 0; x < w; ++x) {- glm::vec4 c = glm::clamp(f((x + 0.5f) / w, (y + 0.5f) / h), 0.0f, 1.0f) * 255.0f;- for (int k = 0; k < 4; ++k) img.rgba[(size_t(y) * w + x) * 4 + k] = uint8_t(c[k] + 0.5f);- }- return img;-}--// Minimal 32-bit BMP writer so command tests can load real files.-void writeBmp(const std::string& path, const Image& img) {- std::ofstream f(path, std::ios::binary);- auto u32 = [&](uint32_t v) { f.write(reinterpret_cast<const char*>(&v), 4); };- auto u16 = [&](uint16_t v) { f.write(reinterpret_cast<const char*>(&v), 2); };- const uint32_t dataSize = uint32_t(img.width * img.height * 4);- f.write("BM", 2);- u32(54 + dataSize); u32(0); u32(54);- u32(40); u32(uint32_t(img.width)); u32(uint32_t(-img.height)); u16(1); u16(32); u32(0); u32(dataSize);- u32(2835); u32(2835); u32(0); u32(0);- for (size_t i = 0; i < img.rgba.size(); i += 4) {- const char px[4] = {char(img.rgba[i + 2]), char(img.rgba[i + 1]), char(img.rgba[i]), char(255)};- f.write(px, 4);- }-}--} // namespace--TEST(image_relief) {- Image ramp = makeImage(64, 32, [](float u, float) { return glm::vec4(u, u, u, 1.0f); });- ReliefOptions o;- o.resolution = 64;- Mesh m = makeImageRelief(ramp, o);- AABB b = m.bounds();- CHECK(std::abs(b.extent().x - 2.0f) < 1e-4f && std::abs(b.extent().y - 1.0f) < 1e-4f); // keeps aspect- float leftZ = 0, rightZ = 0;- for (const auto& p : m.positions) {- if (p.x < -0.95f) leftZ = std::max(leftZ, p.z);- if (p.x > 0.95f) rightZ = std::max(rightZ, p.z);- }- CHECK(rightZ > leftZ + 0.1f); // light side is higher-}--TEST(image_inflate_silhouette) {- // A disk on a transparent background inflates into a closed, symmetric, ball-like shape.- Image disk = makeImage(96, 96, [](float u, float v) {- float d = glm::length(glm::vec2(u, v) - 0.5f);- return glm::vec4(0.2f, 0.2f, 0.2f, d < 0.4f ? 1.0f : 0.0f);- });- InflateOptions o;- o.resolution = 64;- o.subdivisions = 0;- std::string err;- Mesh m = inflateSilhouette(disk, o, &err);- CHECK(m.triangleCount() > 100);- {- std::map<std::pair<uint32_t, uint32_t>, int> edges;- for (const auto& t : m.triangles)- for (int k = 0; k < 3; ++k) ++edges[std::minmax(t[k], t[(k + 1) % 3])];- bool manifold = true;- for (const auto& [e, n] : edges) manifold = manifold && n == 2;- CHECK(manifold); // closed, no pinches- CHECK(long(m.vertexCount()) - long(edges.size()) + long(m.triangleCount()) == 2); // sphere topology- }- AABB b = m.bounds();- CHECK(b.extent().z > b.extent().x * 0.6f); // round, not flat- CHECK(std::abs(b.max.z + b.min.z) < 0.02f * b.extent().z); // front/back symmetric-- // Dark shape on a white page (no transparency) also works.- Image sketch = makeImage(80, 60, [](float u, float v) {- bool in = std::abs(u - 0.5f) < 0.3f && std::abs(v - 0.5f) < 0.2f;- return in ? glm::vec4(0, 0, 0, 1) : glm::vec4(1, 1, 1, 1);- });- CHECK(inflateSilhouette(sketch, o, &err).triangleCount() > 0);- Image blank = makeImage(32, 32, [](float, float) { return glm::vec4(1); });- CHECK(inflateSilhouette(blank, o, &err).triangleCount() == 0 && !err.empty());-}--TEST(image_projection) {- Mesh m = makeIcosphere(4);- const auto before = m.positions;- Image white = makeImage(16, 16, [](float, float) { return glm::vec4(1); });- glm::vec3 eye(0, 0, 5);- glm::mat4 vp = glm::perspective(glm::radians(35.0f), 1.0f, 0.1f, 20.0f) *- glm::lookAt(eye, glm::vec3(0), glm::vec3(0, 1, 0));- ProjectOptions o;- o.depth = 0.1f;- size_t n = projectImage(m, -1, white, vp, 1.0f, eye, o);- CHECK(n > 0);- bool backUntouched = true, frontRaised = false;- for (size_t i = 0; i < before.size(); ++i) {- if (before[i].z < -0.1f) backUntouched = backUntouched && m.positions[i] == before[i];- if (before[i].z > 0.95f) frontRaised = frontRaised || glm::length(m.positions[i]) > 1.05f;- }- CHECK(backUntouched && frontRaised);-}--TEST(gltf_roundtrip_with_layers) {- Mesh m = makeIcosphere(3);- int l = m.addLayer("Smile");- for (size_t v = 0; v < m.vertexCount(); ++v) m.layers[l].delta[v] = glm::vec3(0, m.positions[v].y * 0.1f, 0);- m.setLayerWeight(l, 0.25f);- const std::string path = tempPath("sculptforge_roundtrip.glb");- std::string err;- CHECK(saveGlb(path, m, "Head", err));- Mesh back;- CHECK(loadGltf(path, back, err));- CHECK(back.vertexCount() == m.vertexCount() && back.triangleCount() == m.triangleCount());- CHECK(back.layers.size() == 1 && back.layers[0].name == "Smile" && std::abs(back.layers[0].weight - 0.25f) < 1e-6f);- for (size_t v = 0; v < m.vertexCount(); ++v) CHECK(glm::distance(back.positions[v], m.positions[v]) < 1e-5f);- std::filesystem::remove(path);-- CommandRegistry reg;- Document d;- CHECK(reg.execute(d, "new_sphere", {{"subdivisions", 2.0}}).ok);- CHECK(reg.execute(d, "export_glb", {{"path", path}}).ok);- CHECK(reg.execute(d, "open", {{"path", path}}).ok);- CHECK(d.mesh.triangleCount() == 320);- std::filesystem::remove(path);-}--TEST(image_commands) {- const std::string bmp = tempPath("sculptforge_sketch.bmp");- writeBmp(bmp, makeImage(64, 64, [](float u, float v) {- float d = glm::length(glm::vec2(u, v) - 0.5f);- return d < 0.35f ? glm::vec4(0.1f, 0.1f, 0.1f, 1) : glm::vec4(1, 1, 1, 1);- }));- CommandRegistry reg;- Document d;- CommandResult r = reg.execute(d, "image_inflate", {{"path", bmp}});- CHECK(r.ok);- if (!r.ok) std::printf(" %s\n", r.message.c_str());- CHECK(d.mesh.triangleCount() > 500);- CHECK(reg.execute(d, "image_project", {{"path", bmp}, {"depth", 0.02}}).ok);- CHECK(reg.execute(d, "undo").ok);- CHECK(reg.execute(d, "image_relief", {{"path", bmp}, {"resolution", 64.0}}).ok);- CHECK(d.mesh.triangleCount() == 64u * 64u * 2u);- CHECK(!reg.execute(d, "image_relief", {{"path", tempPath("missing_sculptforge.png")}}).ok);- std::filesystem::remove(bmp);-}--// --- Voxel remesh, splats, PLY, USD, glTF splats, MCP, image-to-3D services -----bool isClosedManifold(const Mesh& m) {- std::map<std::pair<uint32_t, uint32_t>, int> edges;- for (const auto& t : m.triangles)- for (int k = 0; k < 3; ++k) ++edges[std::minmax(t[k], t[(k + 1) % 3])];- for (const auto& [e, n] : edges)- if (n != 2) return false;- return !edges.empty();-}--double signedVolume(const Mesh& m) {- double v = 0.0;- for (const auto& t : m.triangles)- v += double(glm::dot(m.positions[t.x], glm::cross(m.positions[t.y], m.positions[t.z]))) / 6.0;- return v;-}--TEST(voxel_remesh) {- Mesh sphere = makeIcosphere(4);- std::string err;- Mesh r = voxelRemesh(sphere, 64, &err);- CHECK(r.triangleCount() > 1000);- CHECK(isClosedManifold(r));- const double vol = signedVolume(r);- CHECK(vol > 0.0); // faces point outwards- CHECK(std::abs(vol - 4.18879) < 0.04 * 4.18879); // unit-sphere volume preserved within 4%- float worst = 0.0f;- for (const auto& p : r.positions) worst = std::max(worst, std::abs(glm::length(p) - 1.0f));- CHECK(worst < 0.03f);-- // Two overlapping spheres merge into one closed surface.- Mesh a = makeIcosphere(3), b = makeIcosphere(3), both;- for (auto& p : b.positions) p += glm::vec3(1.2f, 0, 0);- both.positions = a.positions;- both.positions.insert(both.positions.end(), b.positions.begin(), b.positions.end());- both.triangles = a.triangles;- for (auto t : b.triangles) both.triangles.push_back(t + glm::uvec3(uint32_t(a.vertexCount())));- both.rebuildTopology();- Mesh merged = voxelRemesh(both, 80, &err);- CHECK(isClosedManifold(merged));- CHECK(long(merged.vertexCount()) - long(merged.triangleCount() * 3 / 2) + long(merged.triangleCount()) == 2); // one piece-- CommandRegistry reg;- Document d;- CHECK(reg.execute(d, "new_sphere", {{"subdivisions", 3.0}}).ok);- CHECK(reg.execute(d, "remesh", {{"resolution", 48.0}}).ok);- CHECK(reg.execute(d, "undo").ok && d.mesh.triangleCount() == 1280);- CHECK(!voxelRemesh(Mesh(), 64, &err).triangleCount() && !err.empty());-}--TEST(splats_mesh_conversions) {- Mesh sphere = makeIcosphere(4);- MeshToSplatsOptions o;- o.count = 40000;- SplatCloud c = meshToSplats(sphere, o);- CHECK(c.size() == 40000 && c.validate().empty());- bool onSurface = true, flat = true;- for (size_t i = 0; i < c.size(); ++i) {- onSurface = onSurface && std::abs(glm::length(c.positions[i]) - 1.0f) < 0.01f;- const glm::vec3 n = glm::mat3_cast(c.rotations[i])[2]; // thin axis- flat = flat && std::abs(glm::dot(n, glm::normalize(c.positions[i]))) > 0.98f && c.scales[i].z < c.scales[i].x * 0.2f;- }- CHECK(onSurface && flat);-- std::string err;- SplatToMeshOptions so;- so.resolution = 64;- Mesh back = splatsToMesh(c, so, &err);- CHECK(back.triangleCount() > 1000);- CHECK(isClosedManifold(back));- CHECK(signedVolume(back) > 0.0);- const AABB b = back.bounds();- CHECK(std::abs(b.extent().x - 2.0f) < 0.15f && std::abs(b.center().y) < 0.05f);-- // Floaters are dropped: only the largest solid survives.- SplatCloud noisy = c;- noisy.positions.push_back(glm::vec3(0, 3, 0));- noisy.rotations.push_back(glm::quat(1, 0, 0, 0));- noisy.scales.push_back(glm::vec3(0.1f));- noisy.opacities.push_back(1.0f);- noisy.sh.push_back(glm::vec3(0));- so.keepFraction = 1.0f;- CHECK(splatsToMesh(noisy, so, &err).bounds().max.y < 1.2f);-- // Placement: rotate/fit keep the data, bake applies it.- SplatCloud t = c;- t.transform = glm::translate(glm::mat4(1.0f), glm::vec3(5, 0, 0)) * glm::scale(glm::mat4(1.0f), glm::vec3(3.0f));- fitSplats(t);- CHECK(glm::length(t.bounds(0.9f).center()) < 0.05f);- CHECK(std::abs(t.bounds(0.9f).extent().x - 2.0f) < 0.05f);- t.bakeTransform();- CHECK(t.transform == glm::mat4(1.0f) && glm::length(t.bounds(0.9f).center()) < 0.05f);- CHECK(cleanSplats(noisy, 0.05f, 0.9f) > 0);-}--SplatCloud testCloud(int degree) {- SplatCloud c;- c.resize(50, degree);- for (size_t i = 0; i < c.size(); ++i) {- const float f = float(i);- c.positions[i] = glm::vec3(std::sin(f), std::cos(f * 0.7f), f * 0.01f);- c.rotations[i] = glm::normalize(glm::quat(1.0f, 0.1f * f, -0.05f * f, 0.3f));- c.scales[i] = glm::vec3(0.01f + 0.001f * f, 0.02f, 0.005f);- c.opacities[i] = 0.1f + 0.015f * f;- for (int k = 0; k < c.shCount(); ++k) c.sh[i * size_t(c.shCount()) + size_t(k)] = glm::vec3(0.1f * float(k), -0.2f * f / 50.0f, 0.3f);- }- return c;-}--bool sameRotation(const glm::quat& a, const glm::quat& b, float tol) { return std::abs(std::abs(glm::dot(a, b)) - 1.0f) < tol; }--TEST(splat_ply_and_dot_splat_roundtrip) {- for (int degree : {0, 1, 3}) {- SplatCloud c = testCloud(degree);- const std::string path = tempPath("sculptforge_splats.ply");- std::string err;- CHECK(saveSplatPly(path, c, err));- Mesh m;- SplatCloud back;- PlyContent content;- CHECK(loadPly(path, m, back, content, err) && content == PlyContent::Splats);- CHECK(back.size() == c.size() && back.shDegree == degree);- bool same = true;- for (size_t i = 0; i < c.size(); ++i) {- same = same && glm::distance(back.positions[i], c.positions[i]) < 1e-6f;- same = same && glm::distance(back.scales[i], c.scales[i]) < 1e-6f;- same = same && std::abs(back.opacities[i] - c.opacities[i]) < 1e-5f;- same = same && sameRotation(back.rotations[i], c.rotations[i], 1e-6f);- }- for (size_t k = 0; k < c.sh.size(); ++k) same = same && glm::distance(back.sh[k], c.sh[k]) < 1e-6f;- CHECK(same);- std::filesystem::remove(path);- }- SplatCloud c = testCloud(0);- const std::string path = tempPath("sculptforge_splats.splat");- std::string err;- CHECK(saveDotSplat(path, c, err));- SplatCloud back;- CHECK(loadDotSplat(path, back, err) && back.size() == c.size());- bool close = true;- for (size_t i = 0; i < c.size(); ++i) {- close = close && glm::distance(back.positions[i], c.positions[i]) < 1e-6f;- close = close && glm::distance(back.color(i), glm::clamp(c.color(i), 0.0f, 1.0f)) < 0.01f;- close = close && sameRotation(back.rotations[i], c.rotations[i], 0.01f);- }- CHECK(close);- std::filesystem::remove(path);-}--TEST(ply_mesh_and_point_cloud) {- const std::string path = tempPath("sculptforge_quad.ply");- {- std::ofstream f(path);- f << "ply\nformat ascii 1.0\ncomment a unit quad pyramid\nelement vertex 5\nproperty float x\nproperty float y\n"- "property float z\nelement face 5\nproperty list uchar int vertex_indices\nend_header\n"- "0 0 0\n1 0 0\n1 1 0\n0 1 0\n0.5 0.5 1\n4 3 2 1 0\n3 0 1 4\n3 1 2 4\n3 2 3 4\n3 3 0 4\n";- }- Mesh m;- SplatCloud s;- PlyContent content;- std::string err;- CHECK(loadPly(path, m, s, content, err) && content == PlyContent::Mesh);- CHECK(m.vertexCount() == 5 && m.triangleCount() == 6 && isClosedManifold(m));- {- std::ofstream f(path, std::ios::binary);- f << "ply\nformat binary_big_endian 1.0\nelement vertex 2\nproperty double x\nproperty double y\nproperty double z\n"- "property uchar red\nproperty uchar green\nproperty uchar blue\nend_header\n";- auto be = [&](double d) {- uint64_t u;- std::memcpy(&u, &d, 8);- for (int k = 7; k >= 0; --k) f.put(char((u >> (k * 8)) & 0xFF));- };- be(1); be(2); be(3); f.put(char(255)); f.put(0); f.put(0);- be(-1); be(0); be(0); f.put(0); f.put(0); f.put(char(255));- }- CHECK(loadPly(path, m, s, content, err) && content == PlyContent::Splats);- CHECK(s.size() == 2 && s.positions[0] == glm::vec3(1, 2, 3) && glm::distance(s.color(0), glm::vec3(1, 0, 0)) < 1e-5f);- std::filesystem::remove(path);- CHECK(!loadPly(tempPath("missing_sculptforge.ply"), m, s, content, err));-}--TEST(zip_and_usdz_alignment) {- const char* digits = "123456789";- CHECK(crc32(reinterpret_cast<const uint8_t*>(digits), 9) == 0xCBF43926u);- const std::string path = tempPath("sculptforge_test.zip");- std::vector<ZipEntry> entries = {{"a.usda", std::vector<uint8_t>(100, 'a')}, {"textures/b.png", std::vector<uint8_t>(7, 'b')}};- std::string err;- CHECK(writeStoredZip(path, entries, 64, err));- std::vector<uint8_t> z;- {- std::ifstream f(path, std::ios::binary); // closed before remove(): Windows can't delete open files- z.assign(std::istreambuf_iterator<char>(f), std::istreambuf_iterator<char>());- }- // Find each entry's data via the local headers and check 64-byte alignment.- size_t p = 0, aligned = 0;- while (p + 30 <= z.size() && z[p] == 'P' && z[p + 1] == 'K' && z[p + 2] == 3 && z[p + 3] == 4) {- const size_t nameLen = z[p + 26] | z[p + 27] << 8, extra = z[p + 28] | z[p + 29] << 8;- const size_t size = z[p + 18] | z[p + 19] << 8 | z[p + 20] << 16 | size_t(z[p + 21]) << 24;- const size_t data = p + 30 + nameLen + extra;- aligned += data % 64 == 0;- p = data + size;- }- CHECK(aligned == 2);- std::vector<ZipEntry> back;- CHECK(readStoredZip(path, back, err) && back.size() == 2 && back[1].name == "textures/b.png" && back[0].data == entries[0].data);- std::filesystem::remove(path);-}--TEST(usd_roundtrip_mesh_layers_splats) {- Mesh m = makeIcosphere(2);- int smile = m.addLayer("Smile 2");- int blink = m.addLayer("Blink");- for (size_t v = 0; v < m.vertexCount(); ++v)- if (m.positions[v].y > 0.5f) m.layers[smile].delta[v] = glm::vec3(0, 0.1f, 0);- m.layers[blink].delta[3] = glm::vec3(0.2f, 0, 0);- m.setLayerWeight(smile, 0.75f);- m.setLayerWeight(blink, 0.0f);- SplatCloud c = testCloud(1);- c.transform = glm::translate(glm::mat4(1.0f), glm::vec3(0, 2, 0));-- for (const char* name : {"sculptforge_test.usda", "sculptforge_test.usdz"}) {- const std::string path = tempPath(name);- std::string err;- CHECK(saveUsd(path, &m, &c, "Hero Head", err));- Mesh back;- SplatCloud sback;- CHECK(loadUsd(path, back, sback, err));- if (!err.empty()) std::printf(" %s\n", err.c_str());- CHECK(back.vertexCount() == m.vertexCount() && back.triangleCount() == m.triangleCount());- CHECK(back.layers.size() == 2 && back.layers[0].name == "Smile_2" && std::abs(back.layers[0].weight - 0.75f) < 1e-6f);- bool same = true;- for (size_t v = 0; v < m.vertexCount(); ++v) {- same = same && glm::distance(back.base[v], m.base[v]) < 1e-6f;- same = same && glm::distance(back.layers[0].delta[v], m.layers[0].delta[v]) < 1e-6f;- same = same && glm::distance(back.layers[1].delta[v], m.layers[1].delta[v]) < 1e-6f;- same = same && glm::distance(back.positions[v], m.positions[v]) < 1e-5f;- }- CHECK(same);- CHECK(sback.size() == c.size() && sback.shDegree == 1);- bool splatsSame = true;- for (size_t i = 0; i < c.size(); ++i) {- splatsSame = splatsSame && glm::distance(sback.worldPosition(i), c.worldPosition(i)) < 1e-5f;- splatsSame = splatsSame && sameRotation(sback.rotations[i], c.rotations[i], 1e-6f);- splatsSame = splatsSame && std::abs(sback.opacities[i] - c.opacities[i]) < 1e-6f;- }- for (size_t k = 0; k < c.sh.size(); ++k) splatsSame = splatsSame && glm::distance(sback.sh[k], c.sh[k]) < 1e-6f;- CHECK(splatsSame);- std::filesystem::remove(path);- }- CHECK(usdIdentifier("3 eyes!") == "_3_eyes_");-}--TEST(usd_reader_handles_foreign_files) {- const std::string path = tempPath("sculptforge_foreign.usda");- {- std::ofstream f(path);- f << R"(#usda 1.0-(- doc = """A multi-line- doc with { braces } and "quotes" """- upAxis = "Z"- customLayerData = { string creator = "test" }-)--class "Template" { def Mesh "Ignored" { point3f[] points = [(9,9,9),(9,9,8),(9,8,9)] int[] faceVertexCounts = [3] int[] faceVertexIndices = [0,1,2] } }--def Xform "World" (- kind = "assembly"-)-{- double3 xformOp:translate = (0, 0, 10) # moved up 10 in Z-up- float3 xformOp:scale = (2, 2, 2)- uniform token[] xformOpOrder = ["xformOp:translate", "xformOp:scale"]-- def Mesh "Quad" (- prepend apiSchemas = ["MaterialBindingAPI"]- )- {- uniform token orientation = "leftHanded"- int[] faceVertexCounts = [4]- int[] faceVertexIndices = [0, 1, 2, 3]- point3f[] points.timeSamples = {- 1: [(0, 0, 0), (1, 0, 0), (1, 1, 0), (0, 1, 0)],- 2: [(5, 5, 5), (6, 5, 5), (6, 6, 5), (5, 6, 5)],- }- color3f[] primvars:displayColor = [(1, 0, 0)] (- interpolation = "constant"- )- rel material:binding = </World/Looks/Red>- }-- variantSet "lod" = {- "high" { def Mesh "Variant" { point3f[] points = [(7,7,7)] } }- }-}-)";- }- Mesh m;- SplatCloud s;- std::string err;- CHECK(loadUsd(path, m, s, err));- if (!err.empty()) std::printf(" %s\n", err.c_str());- CHECK(m.vertexCount() == 4 && m.triangleCount() == 2 && s.empty());- const AABB b = m.bounds();- // Z-up converted to Y-up: translate (0,0,10) becomes +10 in Y; scale 2 makes the quad 2x2 in the X/-Z plane.- CHECK(std::abs(b.min.y - 10.0f) < 1e-5f && std::abs(b.max.y - 10.0f) < 1e-5f);- CHECK(std::abs(b.extent().x - 2.0f) < 1e-5f && std::abs(b.extent().z - 2.0f) < 1e-5f);- // Left-handed winding was flipped: the quad (CCW in XY seen from +Z) now faces -Z-up = ... down after conversion.- const glm::vec3 n = glm::cross(m.positions[m.triangles[0].y] - m.positions[m.triangles[0].x],- m.positions[m.triangles[0].z] - m.positions[m.triangles[0].x]);- CHECK(n.y < 0.0f);- {- std::ofstream f(path, std::ios::binary);- f << "PXR-USDC binary";- }- CHECK(!loadUsd(path, m, s, err) && err.find("usdc") != std::string::npos);- std::filesystem::remove(path);-}--TEST(gltf_gaussian_splatting_roundtrip) {- SplatCloud c = testCloud(2);- c.transform = glm::translate(glm::mat4(1.0f), glm::vec3(1, 2, 3)) * glm::scale(glm::mat4(1.0f), glm::vec3(0.5f));- const std::string path = tempPath("sculptforge_splats.glb");- std::string err;- CHECK(saveSplatGlb(path, c, err));- Mesh m;- SplatCloud back;- CHECK(loadGltf(path, m, err, &back));- CHECK(m.triangleCount() == 0 && back.size() == c.size() && back.shDegree == 2);- bool same = true;- for (size_t i = 0; i < c.size(); ++i) {- same = same && glm::distance(back.worldPosition(i), c.worldPosition(i)) < 1e-5f;- same = same && sameRotation(back.rotations[i], c.rotations[i], 1e-6f);- same = same && glm::distance(back.scales[i], c.scales[i]) < 1e-7f;- }- for (size_t k = 0; k < c.sh.size(); ++k) same = same && glm::distance(back.sh[k], c.sh[k]) < 1e-6f;- CHECK(same);- // Opening it as a document keeps the mesh and adds the splats.- CommandRegistry reg;- Document d;- CHECK(reg.execute(d, "new_sphere", {{"subdivisions", 1.0}}).ok);- CHECK(reg.execute(d, "open", {{"path", path}}).ok && d.splats.size() == c.size() && d.mesh.triangleCount() == 80);- CHECK(!loadGltf(path, m, err)); // without a splat target, a splat-only file has no meshes- std::filesystem::remove(path);-}--TEST(splat_commands) {- CommandRegistry reg;- Document d;- CHECK(!reg.execute(d, "splat_to_mesh").ok); // nothing loaded- CHECK(reg.execute(d, "new_sphere", {{"subdivisions", 3.0}}).ok);- const uint64_t v0 = d.splatsVersion;- CHECK(reg.execute(d, "mesh_to_splats", {{"count", 20000.0}}).ok && d.splats.size() == 20000 && d.splatsVersion != v0);- CHECK(reg.execute(d, "splat_transform", {{"rotate_x", 180.0}, {"fit", true}}).ok);- CHECK(reg.execute(d, "splat_clean", {{"min_opacity", 0.5}}).ok);- CHECK(reg.execute(d, "splat_to_mesh", {{"resolution", 48.0}}).ok && isClosedManifold(d.mesh));- CHECK(reg.execute(d, "undo").ok && d.mesh.triangleCount() == 1280);- for (const char* ext : {".ply", ".splat", ".glb", ".usda", ".usdz"}) {- const std::string path = tempPath((std::string("sculptforge_cmd_splats") + ext).c_str());- CHECK(reg.execute(d, "splat_save", {{"path", path}}).ok);- Document e;- CHECK(reg.execute(e, "open", {{"path", path}}).ok && e.splats.size() == d.splats.size());- std::filesystem::remove(path);- }- CHECK(!reg.execute(d, "splat_save", {{"path", tempPath("sculptforge_bad.txt")}}).ok);- const std::string usd = tempPath("sculptforge_cmd.usdz");- CHECK(reg.execute(d, "export_usd", {{"path", usd}}).ok);- std::filesystem::remove(usd);- CHECK(reg.execute(d, "splat_clear").ok && d.splats.empty());-}--TEST(mcp_server_protocol) {- CommandRegistry reg;- Document d;- auto call = [&](const std::string& line) {- Json j;- std::string err;- const std::string out = handleMcpMessage(reg, d, line);- if (!out.empty()) Json::parse(out, j, err);- return j;- };- Json init = call(R"({"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-06-18","capabilities":{},"clientInfo":{"name":"t","version":"1"}}})");- CHECK(init["result"]["protocolVersion"].asString() == "2025-06-18");- CHECK(init["result"]["serverInfo"]["name"].asString() == "sculptforge" && init["result"]["capabilities"]["tools"].isObject());- CHECK(handleMcpMessage(reg, d, R"({"jsonrpc":"2.0","method":"notifications/initialized"})").empty());- Json list = call(R"({"jsonrpc":"2.0","id":2,"method":"tools/list"})");- bool hasRemesh = false, schemasOk = true;- for (const auto& t : list["result"]["tools"].items()) {- hasRemesh = hasRemesh || t["name"].asString() == "remesh";- schemasOk = schemasOk && t["inputSchema"]["type"].asString() == "object";- }- CHECK(hasRemesh && schemasOk && list["result"]["tools"].size() == reg.all().size());- Json ok = call(R"({"jsonrpc":"2.0","id":"a","method":"tools/call","params":{"name":"new_sphere","arguments":{"subdivisions":2}}})");- CHECK(ok["id"].asString() == "a" && !ok["result"]["isError"].asBool(true) && d.mesh.triangleCount() == 320);- CHECK(ok["result"]["content"][0]["text"].asString().find("320") != std::string::npos);- Json bad = call(R"({"jsonrpc":"2.0","id":4,"method":"tools/call","params":{"name":"open","arguments":{"path":"/nonexistent/x.obj"}}})");- CHECK(bad["result"]["isError"].asBool(false));- CHECK(call(R"({"jsonrpc":"2.0","id":5,"method":"nope"})")["error"]["code"].asNumber() == -32601);- CHECK(call("not json")["error"]["code"].asNumber() == -32700);- CHECK(call(R"({"jsonrpc":"2.0","id":6,"method":"ping"})")["result"].isObject());-}--TEST(image_to_3d_service_requests) {- const uint8_t man[] = {'M', 'a', 'n'};- CHECK(ai::base64Encode(man, 3) == "TWFu" && ai::base64Encode(man, 2) == "TWE=" && ai::base64Encode(man, 1) == "TQ==");- Json body;- std::string err;- CHECK(Json::parse(ai::falSubmitBody("fal-ai/trellis-2", "data:x"), body, err) && body["image_url"].asString() == "data:x");- CHECK(Json::parse(ai::falSubmitBody("fal-ai/hunyuan-3d/v3.1/rapid/image-to-3d", "data:x"), body, err) &&- body["input_image_url"].asString() == "data:x" && body["enable_geometry"].asBool());- CHECK(Json::parse(ai::meshySubmitBody("", "data:x"), body, err) && body["ai_model"].asString() == "latest" &&- !body["should_texture"].asBool(true) && body["target_formats"][0].asString() == "glb");-- std::string ext;- Json r;- Json::parse(R"({"model_glb":{"url":"https://cdn/x/model.glb","content_type":"model/gltf-binary"}})", r, err);- CHECK(ai::findModelUrl(r, &ext) == "https://cdn/x/model.glb" && ext == ".glb");- Json::parse(R"({"model_glb":{"url":"https://cdn/x/mesh.obj?sig=1","content_type":"text/plain"}})", r, err);- CHECK(ai::findModelUrl(r, &ext) == "https://cdn/x/mesh.obj?sig=1" && ext == ".obj");- Json::parse(R"({"model_urls":{"glb":"https://assets.meshy.ai/t/model.glb?Expires=1","fbx":"https://a/b.fbx"}})", r, err);- CHECK(ai::findModelUrl(r, &ext) == "https://assets.meshy.ai/t/model.glb?Expires=1");- Json::parse(R"({"outputs":[{"file":{"href":"https://x/deep.glb"}}]})", r, err);- CHECK(ai::findModelUrl(r, &ext) == "https://x/deep.glb");- Json::parse(R"({"images":[]})", r, err);- CHECK(ai::findModelUrl(r, &ext).empty());-- // A small character on a big transparent canvas is cropped and centred on a square.- Image canvas = makeImage(400, 200, [](float u, float v) {- const bool body = u > 0.1f && u < 0.2f && v > 0.5f && v < 0.9f;- return glm::vec4(1, 0, 0, body ? 1.0f : 0.0f);- });- Image framed = canvas.framedSubject(0.08f);- CHECK(framed.width == framed.height && framed.width < 120 && framed.width > 80);- CHECK(framed.rgba[(size_t(framed.height / 2) * size_t(framed.width) + size_t(framed.width / 2)) * 4 + 3] == 255);- Image big = makeImage(3000, 1500, [](float, float) { return glm::vec4(0.5f, 0.5f, 0.5f, 1); });- Image small = big.downscaled(1024);- CHECK(small.width == 1024 && small.height == 512 && small.rgba[0] > 120 && small.rgba[0] < 135);- std::vector<uint8_t> png;- CHECK(small.encodePng(png) && png.size() > 8 && png[1] == 'P' && png[2] == 'N' && png[3] == 'G');-- // Missing keys fail fast with a helpful message, without touching the network.- ai::AiSettings s;- s.falKey.clear();- s.generatorService = "fal";- if (!std::getenv("FAL_KEY")) {- ai::GeneratorResult g = ai::generate3D(s, "unused.png", tempPath("sculptforge_gen"));- CHECK(!g.ok && g.error.find("fal.ai") != std::string::npos);- }- // Settings survive a save/load.- s.generatorService = "meshy";- s.falModel = "fal-ai/hunyuan-3d/v3.1/pro/image-to-3d";- ai::AiSettings loaded = ai::AiSettings::fromJson(s.toJson());- CHECK(loaded.generatorService == "meshy" && loaded.falModel == s.falModel && loaded.meshyEndpoint == "https://api.meshy.ai");-}--// --- FBX export/import, Unreal preset and link -----TEST(fbx_roundtrip_layers_and_lods) {- Mesh m = makeIcosphere(3);- int smile = m.addLayer("Smile");- for (size_t v = 0; v < m.vertexCount(); ++v)- if (m.positions[v].y > 0.3f) m.layers[smile].delta[v] = glm::vec3(0.0f, 0.05f, 0.02f);- m.setLayerWeight(smile, 0.3f);- const std::string path = tempPath("sculptforge_test.fbx");- std::string err;- FbxExportOptions o;- o.scale = 100.0f; // metres -> centimetres- CHECK(saveFbx(path, "Head", {&m}, o, err));- {- std::ifstream f(path, std::ios::binary);- std::vector<char> head(27);- f.read(head.data(), 27);- CHECK(std::memcmp(head.data(), "Kaydara FBX Binary \0\x1a\0", 23) == 0);- uint32_t version;- std::memcpy(&version, head.data() + 23, 4);- CHECK(version == 7400);- }- Mesh back;- CHECK(loadFbx(path, back, err));- if (!err.empty()) std::printf(" %s\n", err.c_str());- CHECK(back.vertexCount() == m.vertexCount() && back.triangleCount() == m.triangleCount());- CHECK(back.layers.size() == 1 && back.layers[0].name == "Smile" && std::abs(back.layers[0].weight - 0.3f) < 1e-5f);- bool same = true;- for (size_t v = 0; v < m.vertexCount(); ++v) {- same = same && glm::distance(back.base[v], m.base[v]) < 1e-5f;- same = same && glm::distance(back.layers[0].delta[v], m.layers[0].delta[v]) < 1e-5f;- }- CHECK(same);- CHECK(signedVolume(back) > 0.0); // winding survives the trip-- // LOD group: import takes LOD0 only.- std::vector<Mesh> lods = generateLods(makeIcosphere(4), 3, 0.5f);- CHECK(saveFbx(path, "Rock", {&lods[0], &lods[1], &lods[2]}, o, err));- CHECK(loadFbx(path, back, err) && back.triangleCount() == lods[0].triangleCount());- CHECK(!saveFbx(path, "Empty", {}, o, err));- std::filesystem::remove(path);- CHECK(!loadFbx(tempPath("missing_sculptforge.fbx"), back, err));-}--TEST(unreal_export_preset) {- Document d;- CommandRegistry reg;- CHECK(reg.execute(d, "new_sphere", {{"subdivisions", 3.0}}).ok);- const std::string folder = tempPath("sculptforge_unreal_test");- UnrealExportOptions o;- o.folder = folder;- o.heightCm = 180.0f;- o.lods = 3;- UnrealExportResult r;- std::string err;- CHECK(exportForUnreal(d, o, r, err));- CHECK(r.assetName == "SM_Sculpt" && !r.skeletal && r.lodCount == 3 && std::abs(r.scale - 90.0f) < 1e-3f);- Mesh back;- CHECK(loadFbx(r.path, back, err) && std::abs(back.bounds().extent().y - 1.8f) < 1e-3f); // 180 cm = 1.8 m-- CHECK(reg.execute(d, "layer_add", {{"name", std::string("Blink")}}).ok);- CHECK(exportForUnreal(d, o, r, err));- CHECK(r.assetName == "SK_Sculpt" && r.skeletal && r.lodCount == 1); // morph targets need a skeletal mesh- o.assetName = "My Rock!";- CHECK(exportForUnreal(d, o, r, err) && r.assetName == "My_Rock_");- CHECK(reg.execute(d, "export_unreal", {{"folder", folder}, {"lods", 2.0}}).ok);- CHECK(reg.execute(d, "export_fbx", {{"path", folder + "/plain.fbx"}, {"lods", 2.0}}).ok);- std::filesystem::remove_all(folder);-}--TEST(unreal_link_messages_and_script) {- Json msg;- std::string err;- CHECK(Json::parse(link::unrealMessage("ping", "abc", "", ""), msg, err));- CHECK(msg["version"].asNumber() == 1 && msg["magic"].asString() == "ue_py" && msg["type"].asString() == "ping" &&- msg["source"].asString() == "abc" && !msg.has("dest") && !msg.has("data"));- CHECK(Json::parse(link::unrealMessage("open_connection", "a", "b", R"({"command_ip":"127.0.0.1","command_port":6776})"), msg, err));- CHECK(msg["dest"].asString() == "b" && msg["data"]["command_port"].asNumber() == 6776);-- link::UnrealImport im;- im.fbxPath = "C:\\Art\\it's.fbx";- im.assetName = "SK_Head";- im.skeletal = true;- std::string py = link::unrealImportScript(im);- CHECK(py.find("'C:\\\\Art\\\\it\\'s.fbx'") != std::string::npos); // escaped Python literal- CHECK(py.find("FBXIT_SKELETAL_MESH") != std::string::npos && py.find("import_morph_targets', True") != std::string::npos);- CHECK(py.find("automated_import_should_detect_type', False") != std::string::npos);- CHECK(py.find("SCULPTFORGE_IMPORTED") != std::string::npos && py.find("urllib") == std::string::npos);- im.skeletal = false;- im.lods = true;- im.downloadUrl = "http://10.0.0.5:5000/token/SM_Rock.fbx";- py = link::unrealImportScript(im);- CHECK(py.find("import_mesh_lo_ds', True") != std::string::npos && py.find("FBXIT_STATIC_MESH") != std::string::npos);- CHECK(py.find("urlopen('http://10.0.0.5:5000/token/SM_Rock.fbx'") != std::string::npos);-- link::UnrealEditor ed;- ed.address = "127.0.0.1";- CHECK(ed.local());- ed.address = "192.0.2.10";- ed.machine = "some-other-machine-name";- CHECK(!ed.local());- CHECK(link::UnrealEndpoint().multicastTtl == 0 && link::UnrealEndpoint::network().multicastTtl == 1);-}--TEST(free_huggingface_models) {- const auto& presets = ai::hfPresets();- CHECK(presets.size() >= 4);- bool wellFormed = true, usesImage = true;- for (const auto& p : presets) {- wellFormed = wellFormed && std::string(p.space).rfind("https://", 0) == 0 && !p.steps.empty();- bool image = false;- for (const auto& step : p.steps)- for (const auto& a : step.args) {- image = image || a == "$IMG";- if (a != "$IMG" && a.rfind("$OUT", 0) != 0) {- Json v;- std::string err;- wellFormed = wellFormed && Json::parse(a, v, err); // literal args must be valid JSON- }- }- usesImage = usesImage && image;- }- CHECK(wellFormed && usesImage);- ai::AiSettings defaults;- CHECK(defaults.generatorService == "huggingface" && defaults.hfModel == presets[0].id);- defaults.hfModel = "trellis-2";- defaults.hfToken = "hf_test";- ai::AiSettings loaded = ai::AiSettings::fromJson(defaults.toJson());- CHECK(loaded.hfModel == "trellis-2" && loaded.resolvedHfToken() == "hf_test");- CHECK(ai::friendlyGradioError("You have exceeded your ZeroGPU quota (120s requested vs. 0s left).").find("free GPU time") !=- std::string::npos);- CHECK(ai::friendlyGradioError("some other failure") == "some other failure");- std::string png, err;- CHECK(!ai::prepareImagePng(tempPath("missing_sculptforge.png"), png, err));-- // Text to 3D.- CHECK(!ai::hfTextPresets().empty());- bool usesPrompt = true;- for (const auto& p : ai::hfTextPresets()) {- bool prompt = false;- for (const auto& step : p.steps)- for (const auto& a : step.args) prompt = prompt || a == "$PROMPT";- usesPrompt = usesPrompt && prompt;- }- CHECK(usesPrompt);- Json body;- CHECK(Json::parse(ai::meshyTextBody("", "a fox"), body, err) && body["mode"].asString() == "preview" &&- body["prompt"].asString() == "a fox" && body["ai_model"].asString() == "latest");- CHECK(Json::parse(ai::falTextBody(std::string(300, 'x')), body, err) && body["prompt"].asString().size() == 200 &&- body["enable_geometry"].asBool());- ai::AiSettings offline;- offline.generatorService = "inflate";- CHECK(!ai::generate3DFromText(offline, "a fox", tempPath("sf_text")).ok);- CHECK(!ai::generate3DFromText(offline, " ", tempPath("sf_text")).ok);- Json r;- Json::parse(R"({"model_obj":{"url":"https://cdn/x/model.obj"},"model_urls":{"obj":"https://cdn/x/model.obj"}})", r, err);- std::string ext;- CHECK(ai::findModelUrl(r, &ext) == "https://cdn/x/model.obj" && ext == ".obj");-}+#include <exception>int main() {+ using namespace sf::test;for (const auto& t : registry()) {std::printf("[ RUN] %s\n", t.name);std::fflush(stdout); // so a crash still shows which test was runningdiff --git a/tests/test_python.py b/tests/test_python.pyindex 374af46c..73d3737d 100644--- a/tests/test_python.py+++ b/tests/test_python.py@@ -11,6 +11,25 @@ verts, tris = doc.vertices, doc.trianglesassert verts.shape == (642, 3) and str(verts.dtype) == "float32", verts.shapeassert tris.shape == (1280, 3) and str(tris.dtype) == "uint32", tris.shape+# Optional attributes: None until set, then NumPy copies; they survive subdivision.+assert doc.mask is None and doc.colors is None and doc.polygroups is None and doc.hidden is None+doc.mask = [1.0 if v[1] > 0 else 0.0 for v in verts]+doc.colors = [[1.0, 0.0, 0.0]] * len(verts)+doc.polygroups = [i % 3 for i in range(len(tris))]+assert doc.mask.shape == (642,) and str(doc.mask.dtype) == "float32" and doc.colors.shape == (642, 3)+assert doc.polygroups.shape == (1280,) and str(doc.polygroups.dtype) == "uint32"+sf.run(doc, "subdivide")+assert doc.mask.shape == (doc.vertices.shape[0],) and doc.polygroups.shape == (doc.triangles.shape[0],)+try:+ doc.mask = [0.0, 1.0]+ raise AssertionError("expected ValueError")+except ValueError:+ pass+doc.colors = None+assert doc.colors is None+sf.run(doc, "new_sphere", subdivisions=3)+verts = doc.vertices+sf.run(doc, "layer_add", name="Smile")assert doc.layers == [("Smile", 1.0)], doc.layersassert doc.layer_delta(0).shape == (642, 3)