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
Map baking core: normal (MikkTSpace), object normal, displacement, AO, cavity and colour from a high-poly onto the low-poly's UVs
islandmed2658065ad2ea
diff --git a/CMakeLists.txt b/CMakeLists.txtindex 4c70174e..5b5d95b2 100644--- a/CMakeLists.txt+++ b/CMakeLists.txt@@ -57,6 +57,10 @@ add_library(sculptforge_core STATICsrc/core/TextureCommands.cppsrc/core/AutoUv.cppthird_party/xatlas/xatlas.cpp+ src/core/Bake.cpp+ src/core/BakeImage.cpp+ src/core/Tangents.cpp+ third_party/mikktspace/mikktspace.csrc/core/Matcap.cppsrc/core/Project.cppsrc/core/Guide.cpp@@ -72,12 +76,12 @@ add_library(sculptforge_core STATICsrc/io/GozCommands.cppsrc/io/StlIO.cpp)-target_include_directories(sculptforge_core PUBLIC src PRIVATE third_party/stb third_party/ufbx third_party/xatlas)+target_include_directories(sculptforge_core PUBLIC src PRIVATE third_party/stb third_party/ufbx third_party/xatlas third_party/mikktspace)# Third-party C code: compile quietly.if(MSVC)- set_source_files_properties(third_party/ufbx/ufbx.c third_party/xatlas/xatlas.cpp PROPERTIES COMPILE_OPTIONS "/w")+ set_source_files_properties(third_party/ufbx/ufbx.c third_party/xatlas/xatlas.cpp third_party/mikktspace/mikktspace.c PROPERTIES COMPILE_OPTIONS "/w")else()- set_source_files_properties(third_party/ufbx/ufbx.c third_party/xatlas/xatlas.cpp PROPERTIES COMPILE_OPTIONS "-w")+ set_source_files_properties(third_party/ufbx/ufbx.c third_party/xatlas/xatlas.cpp third_party/mikktspace/mikktspace.c PROPERTIES COMPILE_OPTIONS "-w")endif()target_link_libraries(sculptforge_core PUBLIC glm::glm)target_compile_definitions(sculptforge_core PUBLIC GLM_FORCE_XYZW_ONLY)diff --git a/src/core/Bake.cpp b/src/core/Bake.cppnew file mode 100644index 00000000..47eaaf62--- /dev/null+++ b/src/core/Bake.cpp@@ -0,0 +1,1207 @@+// SculptForge - open source digital sculpting+// SPDX-License-Identifier: GPL-3.0-or-later+#include "core/Bake.h"++#include "core/BakeImage.h"+#include "core/Document.h"+#include "core/Tangents.h"+#include "core/Texture.h"++#include <algorithm>+#include <atomic>+#include <cctype>+#include <cstdlib>+#include <limits>+#include <chrono>+#include <cmath>+#include <cstring>+#include <filesystem>+#include <mutex>+#include <sstream>+#include <thread>++namespace sf {++namespace {++using Clock = std::chrono::steady_clock;+double secondsSince(Clock::time_point t) { return std::chrono::duration<double>(Clock::now() - t).count(); }++std::filesystem::path fsPath(const std::string& s) { return std::filesystem::path(std::u8string(s.begin(), s.end())); }+std::string utf8(const std::filesystem::path& p) {+ const std::u8string s = p.u8string();+ return std::string(s.begin(), s.end());+}++// ---------------------------------------------------------------------------+// Ray BVH: binned-SAH tree over the source triangles. Queries are const and keep their state on the stack,+// so any number of threads can cast at once.+// ---------------------------------------------------------------------------++struct RayHitInfo {+ float t = 0, u = 0, v = 0;+ uint32_t tri = 0;+};++class RayBvh {+public:+ void build(const std::vector<glm::vec3>& pos, const std::vector<glm::uvec3>& tris) {+ const size_t n = tris.size();+ nodes_.clear();+ order_.resize(n);+ std::vector<glm::vec3> centroid(n);+ std::vector<Box> box(n);+ for (size_t i = 0; i < n; ++i) {+ order_[i] = uint32_t(i);+ const glm::vec3 &a = pos[tris[i].x], &b = pos[tris[i].y], &c = pos[tris[i].z];+ box[i].lo = glm::min(a, glm::min(b, c));+ box[i].hi = glm::max(a, glm::max(b, c));+ centroid[i] = (box[i].lo + box[i].hi) * 0.5f;+ }+ nodes_.reserve(n ? 2 * n / kLeaf + 16 : 1);+ nodes_.push_back({});+ if (n == 0) {+ nodes_[0].lo = nodes_[0].hi = glm::vec3(0.0f);+ return;+ }+ struct Job {+ uint32_t node, first, count;+ };+ std::vector<Job> stack = {{0, 0, uint32_t(n)}};+ while (!stack.empty()) {+ const Job j = stack.back();+ stack.pop_back();+ Box nb, cb;+ for (uint32_t i = j.first; i < j.first + j.count; ++i) {+ nb.grow(box[order_[i]]);+ cb.grow(centroid[order_[i]]);+ }+ nodes_[j.node].lo = nb.lo;+ nodes_[j.node].hi = nb.hi;+ uint32_t mid = 0;+ if (j.count > kLeaf && split(j.first, j.count, nb, cb, box, centroid, mid)) {+ const uint32_t left = uint32_t(nodes_.size());+ nodes_.push_back({});+ nodes_.push_back({});+ nodes_[j.node].index = left;+ nodes_[j.node].count = 0;+ stack.push_back({left, j.first, mid - j.first});+ stack.push_back({left + 1, mid, j.first + j.count - mid});+ } else {+ nodes_[j.node].index = j.first;+ nodes_[j.node].count = j.count;+ }+ }+ tris_.resize(n);+ for (size_t i = 0; i < n; ++i) {+ const glm::uvec3& t = tris[order_[i]];+ tris_[i] = {pos[t.x], pos[t.y] - pos[t.x], pos[t.z] - pos[t.x]};+ }+ }++ // The hit with t in [tmin, tmax] nearest to `target`.+ bool nearest(const glm::vec3& o, const glm::vec3& d, float tmin, float tmax, float target, RayHitInfo& hit) const {+ if (tris_.empty()) return false;+ const glm::vec3 inv = invDir(d);+ float best = std::numeric_limits<float>::max();+ bool found = false;+ uint32_t stack[64];+ int sp = 0;+ float tn, tf;+ if (!slab(nodes_[0], o, inv, tmin, tmax, tn, tf)) return false;+ stack[sp++] = 0;+ while (sp) {+ const Node& n = nodes_[stack[--sp]];+ if (!slab(n, o, inv, tmin, tmax, tn, tf) || bound(tn, tf, target) >= best) continue;+ if (n.count) {+ for (uint32_t i = n.index; i < n.index + n.count; ++i) {+ float t, u, v;+ if (!intersect(tris_[i], o, d, t, u, v) || t < tmin || t > tmax) continue;+ const float e = std::abs(t - target);+ if (e < best) {+ best = e;+ hit = {t, u, v, order_[i]};+ found = true;+ }+ }+ continue;+ }+ float an, af, bn, bf;+ const bool ha = slab(nodes_[n.index], o, inv, tmin, tmax, an, af);+ const bool hb = slab(nodes_[n.index + 1], o, inv, tmin, tmax, bn, bf);+ const float la = ha ? bound(an, af, target) : best, lb = hb ? bound(bn, bf, target) : best;+ // Push the less promising child first so the better one is visited next.+ if (la < best && lb < best) {+ if (sp + 2 > 64) continue;+ if (la <= lb) {+ stack[sp++] = n.index + 1;+ stack[sp++] = n.index;+ } else {+ stack[sp++] = n.index;+ stack[sp++] = n.index + 1;+ }+ } else if (la < best && sp < 64) {+ stack[sp++] = n.index;+ } else if (lb < best && sp < 64) {+ stack[sp++] = n.index + 1;+ }+ }+ return found;+ }++ // Any hit with t in [tmin, tmax].+ bool occluded(const glm::vec3& o, const glm::vec3& d, float tmin, float tmax) const {+ if (tris_.empty()) return false;+ const glm::vec3 inv = invDir(d);+ uint32_t stack[64];+ int sp = 0;+ stack[sp++] = 0;+ float tn, tf;+ while (sp) {+ const Node& n = nodes_[stack[--sp]];+ if (!slab(n, o, inv, tmin, tmax, tn, tf)) continue;+ if (n.count) {+ for (uint32_t i = n.index; i < n.index + n.count; ++i) {+ float t, u, v;+ if (intersect(tris_[i], o, d, t, u, v) && t >= tmin && t <= tmax) return true;+ }+ continue;+ }+ if (sp + 2 <= 64) {+ stack[sp++] = n.index + 1;+ stack[sp++] = n.index;+ }+ }+ return false;+ }++private:+ static constexpr uint32_t kLeaf = 4;+ static constexpr int kBins = 16;+ struct Box {+ glm::vec3 lo{std::numeric_limits<float>::max()}, hi{std::numeric_limits<float>::lowest()};+ void grow(const glm::vec3& p) { lo = glm::min(lo, p), hi = glm::max(hi, p); }+ void grow(const Box& b) { lo = glm::min(lo, b.lo), hi = glm::max(hi, b.hi); }+ float area() const {+ if (lo.x > hi.x) return 0.0f;+ const glm::vec3 e = hi - lo;+ return e.x * e.y + e.y * e.z + e.z * e.x;+ }+ };+ struct Node {+ glm::vec3 lo{0.0f};+ uint32_t index = 0; // leaf: first triangle, inner: left child (right = index + 1)+ glm::vec3 hi{0.0f};+ uint32_t count = 0; // > 0 for leaves+ };+ struct Tri {+ glm::vec3 v0, e1, e2;+ };++ bool split(uint32_t first, uint32_t count, const Box& nb, const Box& cb, const std::vector<Box>& box,+ const std::vector<glm::vec3>& centroid, uint32_t& mid) {+ float bestCost = std::numeric_limits<float>::max();+ int bestAxis = -1, bestBin = 0;+ const glm::vec3 ext = cb.hi - cb.lo;+ for (int axis = 0; axis < 3; ++axis) {+ if (ext[axis] <= 0.0f) continue;+ Box bins[kBins];+ uint32_t cnt[kBins] = {};+ const float k = float(kBins) * 0.9999f / ext[axis];+ for (uint32_t i = first; i < first + count; ++i) {+ const int b = std::min(kBins - 1, int((centroid[order_[i]][axis] - cb.lo[axis]) * k));+ bins[b].grow(box[order_[i]]);+ ++cnt[b];+ }+ float rightArea[kBins];+ uint32_t rightCount[kBins];+ Box acc;+ uint32_t c = 0;+ for (int b = kBins - 1; b > 0; --b) {+ acc.grow(bins[b]);+ c += cnt[b];+ rightArea[b] = acc.area();+ rightCount[b] = c;+ }+ acc = Box();+ c = 0;+ for (int b = 0; b < kBins - 1; ++b) {+ acc.grow(bins[b]);+ c += cnt[b];+ if (!c || !rightCount[b + 1]) continue;+ const float cost = acc.area() * float(c) + rightArea[b + 1] * float(rightCount[b + 1]);+ if (cost < bestCost) {+ bestCost = cost;+ bestAxis = axis;+ bestBin = b;+ }+ }+ }+ if (bestAxis < 0) { // all centroids in one spot: split in the middle of the list+ if (count <= 16) return false;+ mid = first + count / 2;+ return true;+ }+ // A leaf costs about one intersection per triangle; stop when splitting doesn't pay.+ if (count <= 8 && bestCost >= nb.area() * float(count)) return false;+ const float k = float(kBins) * 0.9999f / ext[bestAxis];+ auto* b = order_.data() + first;+ auto* e = b + count;+ auto* m = std::partition(b, e, [&](uint32_t t) {+ return std::min(kBins - 1, int((centroid[t][bestAxis] - cb.lo[bestAxis]) * k)) <= bestBin;+ });+ mid = uint32_t(m - order_.data());+ if (mid == first || mid == first + count) mid = first + count / 2;+ return true;+ }++ static glm::vec3 invDir(const glm::vec3& d) {+ auto inv = [](float x) { return std::abs(x) > 1e-20f ? 1.0f / x : (x < 0 ? -1e20f : 1e20f); };+ return {inv(d.x), inv(d.y), inv(d.z)};+ }+ static bool slab(const Node& n, const glm::vec3& o, const glm::vec3& inv, float tmin, float tmax, float& tn, float& tf) {+ const glm::vec3 t0 = (n.lo - o) * inv, t1 = (n.hi - o) * inv;+ const glm::vec3 a = glm::min(t0, t1), b = glm::max(t0, t1);+ tn = std::max(std::max(a.x, a.y), std::max(a.z, tmin));+ tf = std::min(std::min(b.x, b.y), std::min(b.z, tmax));+ return tn <= tf;+ }+ static float bound(float tn, float tf, float target) { return target < tn ? tn - target : target > tf ? target - tf : 0.0f; }+ // Two-sided Moller-Trumbore.+ static bool intersect(const Tri& tr, const glm::vec3& o, const glm::vec3& d, float& t, float& u, float& v) {+ const glm::vec3 p = glm::cross(d, tr.e2);+ const float det = glm::dot(tr.e1, p);+ if (std::abs(det) < 1e-20f) return false;+ const float inv = 1.0f / det;+ const glm::vec3 s = o - tr.v0;+ u = glm::dot(s, p) * inv;+ if (u < 0.0f || u > 1.0f) return false;+ const glm::vec3 q = glm::cross(s, tr.e1);+ v = glm::dot(d, q) * inv;+ if (v < 0.0f || u + v > 1.0f) return false;+ t = glm::dot(tr.e2, q) * inv;+ return true;+ }++ std::vector<Node> nodes_;+ std::vector<uint32_t> order_;+ std::vector<Tri> tris_;+};++// ---------------------------------------------------------------------------+// The high-poly side: every source mesh's visible triangles in one list.+// ---------------------------------------------------------------------------++struct Source {+ std::vector<glm::vec3> pos, nrm;+ std::vector<glm::uvec3> tris;+ std::vector<uint32_t> triMesh, triLocal; // which source mesh / which of its triangles+ std::vector<uint32_t> vertexOffset; // first vertex of each source mesh+ std::vector<float> curvature; // per vertex, normalised to about -1..1 (cavity map)+ std::vector<const Mesh*> meshes;+};++// Cavity per vertex: a mean-curvature-like value (how far the one-ring's centre lies above the vertex along+// its normal, relative to the ring's size; > 0 in creases), lightly smoothed, minus a broadly smoothed copy so+// only the sculpted detail remains (the overall shape is neither cavity nor ridge). Divided by its 99.5th+// percentile (at least 0.01) so the map uses its range whatever the mesh's density.+void computeCurvature(Source& s) {+ s.curvature.assign(s.pos.size(), 0.0f);+ for (size_t m = 0; m < s.meshes.size(); ++m) {+ const Mesh& mesh = *s.meshes[m];+ const uint32_t off = s.vertexOffset[m];+ const size_t nv = mesh.vertexCount();+ std::vector<float> c(nv, 0.0f), tmp(nv);+ for (uint32_t v = 0; v < nv; ++v) {+ const auto ring = mesh.neighbors(v);+ if (ring.empty()) continue;+ glm::vec3 avg(0.0f);+ float edge = 0.0f;+ for (uint32_t n : ring) {+ avg += mesh.positions[n];+ edge += glm::distance(mesh.positions[n], mesh.positions[v]);+ }+ avg /= float(ring.size());+ edge /= float(ring.size());+ c[v] = edge > 0.0f ? glm::dot(mesh.normals[v], avg - mesh.positions[v]) / edge : 0.0f;+ }+ auto smooth = [&](std::vector<float>& f, int iterations) {+ for (int it = 0; it < iterations; ++it) {+ for (uint32_t v = 0; v < nv; ++v) {+ const auto ring = mesh.neighbors(v);+ float sum = f[v];+ for (uint32_t n : ring) sum += f[n];+ tmp[v] = sum / float(ring.size() + 1);+ }+ f.swap(tmp);+ }+ };+ smooth(c, 2);+ std::vector<float> broad = c;+ smooth(broad, 24);+ for (size_t v = 0; v < nv; ++v) s.curvature[off + v] = c[v] - broad[v];+ }+ if (s.curvature.empty()) return;+ std::vector<float> mag(s.curvature.size());+ for (size_t i = 0; i < mag.size(); ++i) mag[i] = std::abs(s.curvature[i]);+ const size_t k = std::min(mag.size() - 1, size_t(double(mag.size()) * 0.995));+ std::nth_element(mag.begin(), mag.begin() + std::ptrdiff_t(k), mag.end());+ const float scale = std::max(mag[k], 0.01f);+ for (float& c : s.curvature) c = std::clamp(c / scale, -1.0f, 1.0f);+}++// ---------------------------------------------------------------------------+// Sample rasterisation: texel (x, y) has samples (x * s + i, y * s + j) of a grid s times finer, at their+// centres. Fixed point (1/256 sample) with a top-left rule, so a sample on an edge two triangles share is+// baked once.+// ---------------------------------------------------------------------------++constexpr int64_t kSub = 256;++struct SampleTri {+ int64_t px[3], py[3];+ int order[3] = {0, 1, 2};+ int64_t area = 0;+ bool topLeft[3] = {};+ bool valid = false;+ int sx0 = 0, sy0 = 0, sx1 = -1, sy1 = -1; // inclusive sample bounds++ SampleTri(const glm::vec2* uv, int gw, int gh) {+ float minX = 1e30f, minY = 1e30f, maxX = -1e30f, maxY = -1e30f;+ for (int i = 0; i < 3; ++i) {+ if (!std::isfinite(uv[i].x) || !std::isfinite(uv[i].y)) return;+ const double x = std::clamp(double(uv[i].x), -4.0, 5.0) * gw, y = std::clamp(double(uv[i].y), -4.0, 5.0) * gh;+ px[i] = std::llround(x * kSub);+ py[i] = std::llround(y * kSub);+ minX = std::min(minX, float(x)), maxX = std::max(maxX, float(x));+ minY = std::min(minY, float(y)), maxY = std::max(maxY, float(y));+ }+ area = (px[1] - px[0]) * (py[2] - py[0]) - (py[1] - py[0]) * (px[2] - px[0]);+ if (area == 0) return;+ if (area < 0) {+ std::swap(px[1], px[2]);+ std::swap(py[1], py[2]);+ std::swap(order[1], order[2]);+ area = -area;+ }+ for (int i = 0; i < 3; ++i) {+ const int a = (i + 1) % 3, b = (i + 2) % 3;+ const int64_t dx = px[b] - px[a], dy = py[b] - py[a];+ topLeft[i] = dy < 0 || (dy == 0 && dx < 0);+ }+ sx0 = std::max(0, int(std::floor(minX - 0.5f)));+ sy0 = std::max(0, int(std::floor(minY - 0.5f)));+ sx1 = std::min(gw - 1, int(std::ceil(maxX - 0.5f)));+ sy1 = std::min(gh - 1, int(std::ceil(maxY - 0.5f)));+ valid = sx0 <= sx1 && sy0 <= sy1;+ }+ int64_t edge(int i, int64_t X, int64_t Y) const {+ const int a = (i + 1) % 3, b = (i + 2) % 3;+ return (px[b] - px[a]) * (Y - py[a]) - (py[b] - py[a]) * (X - px[a]);+ }+};++// ---------------------------------------------------------------------------+// Small helpers+// ---------------------------------------------------------------------------++inline uint32_t hash32(uint32_t x) {+ x ^= x >> 16;+ x *= 0x7feb352dU;+ x ^= x >> 15;+ x *= 0x846ca68bU;+ x ^= x >> 16;+ return x;+}+inline float radicalInverse(uint32_t b) {+ b = (b << 16u) | (b >> 16u);+ b = ((b & 0x55555555u) << 1u) | ((b & 0xAAAAAAAAu) >> 1u);+ b = ((b & 0x33333333u) << 2u) | ((b & 0xCCCCCCCCu) >> 2u);+ b = ((b & 0x0F0F0F0Fu) << 4u) | ((b & 0xF0F0F0F0u) >> 4u);+ b = ((b & 0x00FF00FFu) << 8u) | ((b & 0xFF00FF00u) >> 8u);+ return float(b) * 2.3283064365386963e-10f;+}+// Orthonormal basis around a unit normal (Duff et al. 2017).+inline void basis(const glm::vec3& n, glm::vec3& t, glm::vec3& b) {+ const float sign = std::copysign(1.0f, n.z);+ const float a = -1.0f / (sign + n.z);+ const float bb = n.x * n.y * a;+ t = glm::vec3(1.0f + sign * n.x * n.x * a, sign * bb, -sign * n.x);+ b = glm::vec3(bb, sign + n.y * n.y * a, -n.y);+}+inline uint8_t unorm8(float x) { return uint8_t(std::lround(std::clamp(x, 0.0f, 1.0f) * 255.0f)); }+inline glm::vec3 safeNormalize(const glm::vec3& v, const glm::vec3& fallback) {+ const float l = glm::length(v);+ return l > 1e-12f ? v / l : fallback;+}++// Runs fn(worker) on `threads` threads (the caller is worker 0).+template <class Fn>+void runWorkers(int threads, Fn fn) {+ std::vector<std::thread> pool;+ for (int i = 1; i < threads; ++i) pool.emplace_back([&fn, i] { fn(i); });+ fn(0);+ for (auto& t : pool) t.join();+}++int threadCount(int wanted) {+ const int hw = int(std::max(1u, std::thread::hardware_concurrency()));+ return std::clamp(wanted > 0 ? wanted : hw, 1, 64);+}++std::mutex g_listenerMutex;+BakeListener g_listener;++} // namespace++// ---------------------------------------------------------------------------+// Names+// ---------------------------------------------------------------------------++const char* bakeMapId(BakeMap m) {+ switch (m) {+ case BakeMap::Normal: return "normal";+ case BakeMap::ObjectNormal: return "object_normal";+ case BakeMap::Displacement: return "displacement";+ case BakeMap::AmbientOcclusion: return "ao";+ case BakeMap::Cavity: return "cavity";+ case BakeMap::Color: return "color";+ }+ return "";+}++const char* bakeMapLabel(BakeMap m) {+ switch (m) {+ case BakeMap::Normal: return "Normal (tangent)";+ case BakeMap::ObjectNormal: return "Normal (object)";+ case BakeMap::Displacement: return "Displacement";+ case BakeMap::AmbientOcclusion: return "Ambient Occlusion";+ case BakeMap::Cavity: return "Cavity";+ case BakeMap::Color: return "Colour";+ }+ return "";+}++bool parseBakeMaps(const std::string& list, uint32_t& maps, std::string& error) {+ maps = 0;+ std::string item;+ std::stringstream ss(list);+ while (std::getline(ss, item, ',')) {+ std::string s;+ for (char c : item)+ if (!std::isspace(static_cast<unsigned char>(c))) s += char(std::tolower(static_cast<unsigned char>(c)));+ if (s.empty()) continue;+ if (s == "all") {+ maps = (1u << kBakeMapCount) - 1;+ continue;+ }+ // Common aliases.+ if (s == "normals" || s == "tangent" || s == "tangent_normal" || s == "nm") s = "normal";+ if (s == "object" || s == "objectnormal" || s == "object_space" || s == "world_normal") s = "object_normal";+ if (s == "disp" || s == "height") s = "displacement";+ if (s == "occlusion" || s == "ambient_occlusion") s = "ao";+ if (s == "curvature") s = "cavity";+ if (s == "colour" || s == "polypaint" || s == "albedo" || s == "texture") s = "color";+ bool found = false;+ for (int i = 0; i < kBakeMapCount; ++i)+ if (s == bakeMapId(BakeMap(i))) {+ maps |= 1u << i;+ found = true;+ }+ if (!found) {+ error = "Unknown map '" + item + "' (use normal, object_normal, displacement, ao, cavity, color or all)";+ return false;+ }+ }+ if (!maps) {+ error = "Choose at least one map";+ return false;+ }+ return true;+}++// ---------------------------------------------------------------------------+// The bake+// ---------------------------------------------------------------------------++bool bakeMaps(const Mesh& low, const std::vector<const Mesh*>& sources, const BakeSettings& settingsIn, BakeResult& out,+ std::string& error, const BakeProgress& progress) {+ const auto start = Clock::now();+ BakeSettings st = settingsIn;+ out = BakeResult();+ const size_t nt = low.triangleCount();+ if (nt == 0) {+ error = "The low-poly SubTool is empty";+ return false;+ }+ if (low.uvs.size() != nt * 3) {+ error = "The low-poly SubTool has no UVs: import it with UVs or run Auto UV (Tool > Texture Map)";+ return false;+ }+ if (low.normals.size() != low.vertexCount()) {+ error = "The low-poly SubTool has no normals";+ return false;+ }+ if (st.size < 64 || st.size > 8192) {+ error = "Map size must be between 64 and 8192";+ return false;+ }+ if (!st.maps) {+ error = "Choose at least one map";+ return false;+ }+ st.samples = std::clamp(st.samples, 1, 4);+ st.padding = std::clamp(st.padding, 0, 64);+ st.aoRays = std::clamp(st.aoRays, 1, 1024);++ // --- Gather the source triangles ---+ Source src;+ for (const Mesh* m : sources) {+ if (!m || m == &low || m->triangleCount() == 0 || m->normals.size() != m->vertexCount()) continue;+ const uint32_t mi = uint32_t(src.meshes.size()), off = uint32_t(src.pos.size());+ src.meshes.push_back(m);+ src.vertexOffset.push_back(off);+ src.pos.insert(src.pos.end(), m->positions.begin(), m->positions.end());+ src.nrm.insert(src.nrm.end(), m->normals.begin(), m->normals.end());+ for (uint32_t t = 0; t < m->triangleCount(); ++t) {+ if (m->triangleHidden(t)) continue;+ src.tris.push_back(m->triangles[t] + glm::uvec3(off));+ src.triMesh.push_back(mi);+ src.triLocal.push_back(t);+ }+ }+ if (src.tris.empty()) {+ error = "There is no high-poly source to bake from (show the SubTools to bake, or name one)";+ return false;+ }+ bool anyColor = false;+ for (const Mesh* m : src.meshes) anyColor = anyColor || hasTexture(*m) || m->hasColors();+ if ((st.maps & bakeBit(BakeMap::Color)) && !anyColor) {+ st.maps &= ~bakeBit(BakeMap::Color);+ if (!st.maps) {+ error = "The source has no polypaint or texture to transfer";+ return false;+ }+ }+ const auto bvhStart = Clock::now();+ RayBvh bvh;+ bvh.build(src.pos, src.tris);+ if (st.maps & bakeBit(BakeMap::Cavity)) computeCurvature(src);+ out.bvhSeconds = secondsSince(bvhStart);+ out.sourceTriangles = src.tris.size();++ const bool wantNormal = st.maps & bakeBit(BakeMap::Normal);+ const bool wantObject = st.maps & bakeBit(BakeMap::ObjectNormal);+ const bool wantDisp = st.maps & bakeBit(BakeMap::Displacement);+ const bool wantAo = st.maps & bakeBit(BakeMap::AmbientOcclusion);+ const bool wantCavity = st.maps & bakeBit(BakeMap::Cavity);+ const bool wantColor = st.maps & bakeBit(BakeMap::Color);++ AABB lb = low.bounds();+ AABB all = lb;+ for (const glm::vec3& p : src.pos) all.expand(p);+ const float diag = std::max(glm::length(lb.extent()), 1e-6f);+ const float sceneDiag = std::max(glm::length(all.extent()), 1e-6f);+ out.diagonal = diag;+ const float eps = sceneDiag * 2e-6f;++ // MikkTSpace tangents of the low-poly (the tangent-space map and the viewport preview).+ if (wantNormal) out.tangents = computeTangents(low);++ // Smooth surface point and normal of the low-poly.+ auto lowPoint = [&](uint32_t t, const glm::vec3& b, glm::vec3& p, glm::vec3& n) {+ const glm::uvec3& tv = low.triangles[t];+ p = low.positions[tv.x] * b.x + low.positions[tv.y] * b.y + low.positions[tv.z] * b.z;+ const glm::vec3 face = glm::cross(low.positions[tv.y] - low.positions[tv.x], low.positions[tv.z] - low.positions[tv.x]);+ n = safeNormalize(low.normals[tv.x] * b.x + low.normals[tv.y] * b.y + low.normals[tv.z] * b.z,+ safeNormalize(face, glm::vec3(0, 1, 0)));+ };++ // --- Ray range: measured from a sample of low-poly points when automatic ---+ if (st.autoDistance) {+ const float probe = diag * 0.1f;+ const uint32_t probes = uint32_t(std::clamp<size_t>(nt * 16, 20000, 200000));+ const int pt = threadCount(st.threads);+ std::vector<float> outMax(size_t(pt), 0.0f), inMax(size_t(pt), 0.0f);+ runWorkers(pt, [&](int w) {+ for (uint32_t i = uint32_t(w); i < probes; i += uint32_t(pt)) {+ const uint32_t t = hash32(i * 2654435761u + 17u) % uint32_t(nt);+ float r1 = radicalInverse(i + 1), r2 = float(hash32(i + 99u) & 0xFFFFFF) / float(0x1000000);+ if (r1 + r2 > 1.0f) r1 = 1.0f - r1, r2 = 1.0f - r2;+ glm::vec3 p, n;+ lowPoint(t, glm::vec3(1.0f - r1 - r2, r1, r2), p, n);+ RayHitInfo h;+ if (!bvh.nearest(p + n * probe, -n, 0.0f, 2.0f * probe, probe, h)) continue;+ const float d = probe - h.t;+ float& m = d >= 0 ? outMax[size_t(w)] : inMax[size_t(w)];+ m = std::max(m, std::abs(d));+ }+ });+ // The farthest the high-poly strays each way, plus a margin (small features between probes).+ const float floor = diag * 0.004f;+ st.front = std::min(probe, std::max(*std::max_element(outMax.begin(), outMax.end()) * 1.2f, floor)) / diag;+ st.rear = std::min(probe, std::max(*std::max_element(inMax.begin(), inMax.end()) * 1.2f, floor)) / diag;+ }+ const float front = std::max(st.front, 0.0f) * diag, rear = std::max(st.rear, 0.0f) * diag;+ out.front = front;+ out.rear = rear;+ if (front + rear <= 0.0f) {+ error = "Front and rear distances are both zero";+ return false;+ }+ const float aoDist = std::max(st.aoDistance, 1e-4f) * diag;++ // --- Output planes ---+ const int W = st.size, H = st.size, S = st.samples;+ const size_t texels = size_t(W) * size_t(H);+ out.width = W;+ out.height = H;+ out.maps = st.maps;+ out.flipGreen = st.flipGreen;+ if (wantNormal) out.normal.assign(texels * 3, 0);+ if (wantObject) out.objectNormal.assign(texels * 3, 0);+ if (wantColor) out.color.assign(texels * 3, 0);+ if (wantAo) out.ao.assign(texels, 255);+ if (wantCavity) out.cavity.assign(texels, 128);+ if (wantDisp) out.displacement.assign(texels, 0.0f);+ out.coverage.assign(texels, 0);+ // Float copies of the normals for padding (averaged and renormalised there), only while baking.+ std::vector<glm::vec3> nTs, nOs, col;+ std::vector<float> aoF, cavF;++ // --- Bin low-poly triangles into tiles ---+ constexpr int kTile = 32;+ const int tilesX = (W + kTile - 1) / kTile, tilesY = (H + kTile - 1) / kTile;+ const int gw = W * S, gh = H * S;+ std::vector<uint32_t> binCount(size_t(tilesX) * size_t(tilesY) + 1, 0);+ std::vector<glm::ivec4> triTiles(nt, glm::ivec4(0, 0, -1, -1));+ for (uint32_t t = 0; t < nt; ++t) {+ const SampleTri s(&low.uvs[size_t(t) * 3], gw, gh);+ if (!s.valid) continue;+ const glm::ivec4 r(s.sx0 / S / kTile, s.sy0 / S / kTile, s.sx1 / S / kTile, s.sy1 / S / kTile);+ triTiles[t] = r;+ for (int ty = r.y; ty <= r.w; ++ty)+ for (int tx = r.x; tx <= r.z; ++tx) ++binCount[size_t(ty) * size_t(tilesX) + size_t(tx) + 1];+ }+ for (size_t i = 1; i < binCount.size(); ++i) binCount[i] += binCount[i - 1];+ std::vector<uint32_t> binTris(binCount.back());+ {+ std::vector<uint32_t> fill(binCount.begin(), binCount.end() - 1);+ for (uint32_t t = 0; t < nt; ++t) {+ const glm::ivec4 r = triTiles[t];+ for (int ty = r.y; ty <= r.w; ++ty)+ for (int tx = r.x; tx <= r.z; ++tx) binTris[fill[size_t(ty) * size_t(tilesX) + size_t(tx)]++] = t;+ }+ }+ std::vector<uint32_t> work; // tiles with triangles, the busiest first for better load balance+ for (uint32_t i = 0; i + 1 < binCount.size(); ++i)+ if (binCount[i + 1] > binCount[i]) work.push_back(i);++ const int threads = threadCount(st.threads);+ std::atomic<size_t> next{0}, done{0}, island{0}, missed{0};+ std::atomic<bool> cancel{false};+ std::mutex rangeMutex;+ float dMin = std::numeric_limits<float>::max(), dMax = std::numeric_limits<float>::lowest();+ const int aoPerSample = std::max(1, (st.aoRays + S * S - 1) / (S * S));++ runWorkers(threads, [&](int worker) {+ struct Acc {+ glm::vec3 ts{0}, os{0}, color{0}, lowN{0};+ float disp = 0, ao = 0, cav = 0;+ uint16_t hits = 0, samples = 0;+ };+ std::vector<Acc> acc(size_t(kTile) * kTile);+ float localMin = std::numeric_limits<float>::max(), localMax = std::numeric_limits<float>::lowest();+ size_t localIsland = 0, localMissed = 0;+ for (;;) {+ if (cancel.load(std::memory_order_relaxed)) break;+ const size_t wi = next.fetch_add(1);+ if (wi >= work.size()) break;+ const uint32_t tile = work[wi];+ const int tx = int(tile % uint32_t(tilesX)), ty = int(tile / uint32_t(tilesX));+ const int x0 = tx * kTile, y0 = ty * kTile;+ const int x1 = std::min(W, x0 + kTile), y1 = std::min(H, y0 + kTile);+ std::fill(acc.begin(), acc.end(), Acc());+ for (uint32_t k = binCount[tile]; k < binCount[tile + 1]; ++k) {+ const uint32_t t = binTris[k];+ const SampleTri s(&low.uvs[size_t(t) * 3], gw, gh);+ const int sx0 = std::max(s.sx0, x0 * S), sx1 = std::min(s.sx1, x1 * S - 1);+ const int sy0 = std::max(s.sy0, y0 * S), sy1 = std::min(s.sy1, y1 * S - 1);+ const double inv = 1.0 / double(s.area);+ for (int sy = sy0; sy <= sy1; ++sy) {+ const int64_t Y = int64_t(sy) * kSub + kSub / 2;+ for (int sx = sx0; sx <= sx1; ++sx) {+ const int64_t X = int64_t(sx) * kSub + kSub / 2;+ int64_t e[3];+ bool inside = true;+ for (int i = 0; i < 3 && inside; ++i) {+ e[i] = s.edge(i, X, Y);+ inside = e[i] > 0 || (e[i] == 0 && s.topLeft[i]);+ }+ if (!inside) continue;+ float bw[3];+ for (int i = 0; i < 3; ++i) bw[s.order[i]] = float(double(e[i]) * inv);+ const glm::vec3 b(bw[0], bw[1], bw[2]);+ const int x = sx / S, y = sy / S;+ Acc& a = acc[size_t(y - y0) * kTile + size_t(x - x0)];+ a.samples = uint16_t(std::min(a.samples + 1, 65535));++ glm::vec3 p, n;+ lowPoint(t, b, p, n);+ a.lowN += n;+ RayHitInfo h;+ if (!bvh.nearest(p + n * front, -n, 0.0f, front + rear, front, h)) continue;+ a.hits = uint16_t(std::min(a.hits + 1, 65535));+ const glm::uvec3& ht = src.tris[h.tri];+ const float w0 = 1.0f - h.u - h.v;+ const glm::vec3 geo = glm::cross(src.pos[ht.y] - src.pos[ht.x], src.pos[ht.z] - src.pos[ht.x]);+ glm::vec3 nh = safeNormalize(src.nrm[ht.x] * w0 + src.nrm[ht.y] * h.u + src.nrm[ht.z] * h.v,+ safeNormalize(geo, n));+ const glm::vec3 hp = p + n * (front - h.t);+ if (wantNormal) {+ // The exact inverse of the shader's normalize(tn.x * T + tn.y * B + tn.z * N), with+ // B = sign * cross(N, T) per pixel (MikkTSpace's recommended setup).+ const glm::vec4 &t0 = out.tangents[size_t(t) * 3], &t1 = out.tangents[size_t(t) * 3 + 1],+ &t2 = out.tangents[size_t(t) * 3 + 2];+ glm::vec3 T = glm::vec3(t0) * b.x + glm::vec3(t1) * b.y + glm::vec3(t2) * b.z;+ T = safeNormalize(T - n * glm::dot(n, T), glm::vec3(1, 0, 0));+ const float sign = t0.w < 0.0f ? -1.0f : 1.0f;+ const glm::vec3 B = sign * glm::cross(n, T);+ a.ts += glm::vec3(glm::dot(nh, T), glm::dot(nh, B), glm::dot(nh, n));+ }+ if (wantObject) a.os += nh;+ if (wantDisp) {+ const float d = front - h.t;+ a.disp += d;+ localMin = std::min(localMin, d);+ localMax = std::max(localMax, d);+ }+ if (wantCavity)+ a.cav += src.curvature[ht.x] * w0 + src.curvature[ht.y] * h.u + src.curvature[ht.z] * h.v;+ if (wantColor) {+ const Mesh& m = *src.meshes[src.triMesh[h.tri]];+ const uint32_t lt = src.triLocal[h.tri];+ glm::vec3 c(0.5f);+ if (hasTexture(m)) {+ const glm::vec2 uv = m.uvs[size_t(lt) * 3] * w0 + m.uvs[size_t(lt) * 3 + 1] * h.u ++ m.uvs[size_t(lt) * 3 + 2] * h.v;+ c = sampleTexture(*m.texture, uv);+ if (m.hasColors()) {+ const glm::uvec3& mt = m.triangles[lt];+ c *= m.colors[mt.x] * w0 + m.colors[mt.y] * h.u + m.colors[mt.z] * h.v;+ }+ } else if (m.hasColors()) {+ const glm::uvec3& mt = m.triangles[lt];+ c = m.colors[mt.x] * w0 + m.colors[mt.y] * h.u + m.colors[mt.z] * h.v;+ }+ a.color += c;+ }+ if (wantAo) {+ // Cosine-weighted hemisphere rays from the high-poly point (Hammersley points with a+ // per-sample rotation).+ if (glm::dot(nh, n) < 0.0f) nh = -nh; // face the side the ray came from+ glm::vec3 bt, bb;+ basis(nh, bt, bb);+ const uint32_t seed = hash32(uint32_t(sx) * 73856093u ^ uint32_t(sy) * 19349663u);+ const float r1 = float(seed & 0xFFFF) / 65536.0f, r2 = float(seed >> 16) / 65536.0f;+ const glm::vec3 o = hp + nh * (eps * 4.0f);+ int hits = 0;+ for (int r = 0; r < aoPerSample; ++r) {+ float u1 = (float(r) + 0.5f) / float(aoPerSample) + r1, u2 = radicalInverse(uint32_t(r)) + r2;+ u1 -= std::floor(u1);+ u2 -= std::floor(u2);+ const float rad = std::sqrt(u1), phi = 6.2831853f * u2;+ const glm::vec3 dir = bt * (rad * std::cos(phi)) + bb * (rad * std::sin(phi)) ++ nh * std::sqrt(std::max(0.0f, 1.0f - u1));+ if (bvh.occluded(o, dir, eps, aoDist)) ++hits;+ }+ a.ao += 1.0f - float(hits) / float(aoPerSample);+ }+ }+ }+ }+ // Resolve the tile.+ for (int y = y0; y < y1; ++y)+ for (int x = x0; x < x1; ++x) {+ const Acc& a = acc[size_t(y - y0) * kTile + size_t(x - x0)];+ if (!a.samples) continue;+ const size_t i = size_t(y) * size_t(W) + size_t(x);+ out.coverage[i] = 1;+ ++localIsland;+ if (!a.hits) {+ ++localMissed;+ if (wantNormal) out.normal[i * 3] = out.normal[i * 3 + 1] = 128, out.normal[i * 3 + 2] = 255;+ if (wantObject) { // the low-poly's own normal+ const glm::vec3 on = safeNormalize(a.lowN, glm::vec3(0, 1, 0));+ for (int c = 0; c < 3; ++c) out.objectNormal[i * 3 + size_t(c)] = unorm8(on[c] * 0.5f + 0.5f);+ }+ continue;+ }+ const float inv = 1.0f / float(a.hits);+ if (wantNormal) {+ glm::vec3 tn = safeNormalize(a.ts, glm::vec3(0, 0, 1));+ if (st.flipGreen) tn.y = -tn.y;+ for (int c = 0; c < 3; ++c) out.normal[i * 3 + size_t(c)] = unorm8(tn[c] * 0.5f + 0.5f);+ }+ if (wantObject) {+ const glm::vec3 on = safeNormalize(a.os, glm::vec3(0, 1, 0));+ for (int c = 0; c < 3; ++c) out.objectNormal[i * 3 + size_t(c)] = unorm8(on[c] * 0.5f + 0.5f);+ }+ if (wantDisp) out.displacement[i] = a.disp * inv;+ if (wantAo) out.ao[i] = unorm8(a.ao * inv);+ if (wantCavity) out.cavity[i] = unorm8(0.5f - 0.5f * a.cav * inv);+ if (wantColor) {+ const glm::vec3 c = linearToSrgb(glm::clamp(a.color * inv, 0.0f, 1.0f));+ for (int k = 0; k < 3; ++k) out.color[i * 3 + size_t(k)] = unorm8(c[k]);+ }+ }+ const size_t d = done.fetch_add(1) + 1;+ if (worker == 0 && progress && !progress(0.95f * float(d) / float(work.size()))) cancel = true;+ }+ island += localIsland;+ missed += localMissed;+ std::lock_guard lock(rangeMutex);+ dMin = std::min(dMin, localMin);+ dMax = std::max(dMax, localMax);+ });+ if (cancel) {+ error = "Cancelled";+ out = BakeResult();+ return false;+ }+ out.islandTexels = island;+ out.missedTexels = missed;+ if (wantDisp && dMin <= dMax) {+ out.displacementMin = dMin;+ out.displacementMax = dMax;+ }+ out.displacementScale = st.displacementScale > 0.0f ? st.displacementScale+ : std::max({std::abs(out.displacementMin), std::abs(out.displacementMax), diag * 1e-5f});++ // --- Padding: ring by ring, each empty texel next to filled ones takes their average ---+ if (st.padding > 0) {+ std::vector<uint8_t> ring(texels, 255);+ for (size_t i = 0; i < texels; ++i)+ if (out.coverage[i]) ring[i] = 0;+ std::vector<uint32_t> front;+ std::vector<std::vector<uint32_t>> perThread(static_cast<size_t>(threads));+ for (int k = 1; k <= st.padding; ++k) {+ // 1) Which empty texels touch a filled one (read-only pass).+ std::atomic<int> rowNext{0};+ for (auto& v : perThread) v.clear();+ runWorkers(threads, [&](int w) {+ for (;;) {+ const int y = rowNext.fetch_add(1);+ if (y >= H) break;+ for (int x = 0; x < W; ++x) {+ const size_t i = size_t(y) * size_t(W) + size_t(x);+ if (ring[i] != 255) continue;+ bool touch = false;+ for (int dy = -1; dy <= 1 && !touch; ++dy)+ for (int dx = -1; dx <= 1 && !touch; ++dx) {+ const int nx = x + dx, ny = y + dy;+ if (nx < 0 || ny < 0 || nx >= W || ny >= H) continue;+ touch = ring[size_t(ny) * size_t(W) + size_t(nx)] < k;+ }+ if (touch) perThread[size_t(w)].push_back(uint32_t(i));+ }+ }+ });+ front.clear();+ for (auto& v : perThread) front.insert(front.end(), v.begin(), v.end());+ if (front.empty()) break;+ // 2) Fill them from texels of earlier rings only (none of which is written here).+ std::atomic<size_t> idx{0};+ runWorkers(threads, [&](int) {+ for (;;) {+ const size_t f = idx.fetch_add(256);+ if (f >= front.size()) break;+ for (size_t q = f; q < std::min(front.size(), f + 256); ++q) {+ const size_t i = front[q];+ const int x = int(i % size_t(W)), y = int(i / size_t(W));+ glm::vec3 ts(0), os(0), cl(0);+ float dp = 0, ao = 0, cv = 0;+ int n = 0;+ for (int dy = -1; dy <= 1; ++dy)+ for (int dx = -1; dx <= 1; ++dx) {+ const int nx = x + dx, ny = y + dy;+ if (nx < 0 || ny < 0 || nx >= W || ny >= H) continue;+ const size_t j = size_t(ny) * size_t(W) + size_t(nx);+ if (ring[j] >= k) continue;+ ++n;+ if (wantNormal)+ ts += glm::vec3(out.normal[j * 3], out.normal[j * 3 + 1], out.normal[j * 3 + 2]) / 127.5f - 1.0f;+ if (wantObject)+ os += glm::vec3(out.objectNormal[j * 3], out.objectNormal[j * 3 + 1], out.objectNormal[j * 3 + 2]) / 127.5f - 1.0f;+ if (wantColor) cl += glm::vec3(out.color[j * 3], out.color[j * 3 + 1], out.color[j * 3 + 2]);+ if (wantDisp) dp += out.displacement[j];+ if (wantAo) ao += out.ao[j];+ if (wantCavity) cv += out.cavity[j];+ }+ if (!n) continue;+ const float inv = 1.0f / float(n);+ if (wantNormal) {+ const glm::vec3 v = safeNormalize(ts, glm::vec3(0, 0, 1));+ for (int c = 0; c < 3; ++c) out.normal[i * 3 + size_t(c)] = unorm8(v[c] * 0.5f + 0.5f);+ }+ if (wantObject) {+ const glm::vec3 v = safeNormalize(os, glm::vec3(0, 1, 0));+ for (int c = 0; c < 3; ++c) out.objectNormal[i * 3 + size_t(c)] = unorm8(v[c] * 0.5f + 0.5f);+ }+ if (wantColor)+ for (int c = 0; c < 3; ++c) out.color[i * 3 + size_t(c)] = uint8_t(std::lround(cl[c] * inv));+ if (wantDisp) out.displacement[i] = dp * inv;+ if (wantAo) out.ao[i] = uint8_t(std::lround(ao * inv));+ if (wantCavity) out.cavity[i] = uint8_t(std::lround(cv * inv));+ }+ }+ });+ for (uint32_t i : front) {+ ring[i] = uint8_t(k);+ out.coverage[i] = 2;+ }+ }+ }+ // Texels nobody reached: neutral values.+ for (size_t i = 0; i < texels; ++i) {+ if (out.coverage[i]) continue;+ if (wantNormal) out.normal[i * 3] = out.normal[i * 3 + 1] = 128, out.normal[i * 3 + 2] = 255;+ if (wantObject) out.objectNormal[i * 3] = out.objectNormal[i * 3 + 1] = out.objectNormal[i * 3 + 2] = 128;+ }+ if (progress) progress(1.0f);+ out.seconds = secondsSince(start);+ return true;+}++// ---------------------------------------------------------------------------+// Images and files+// ---------------------------------------------------------------------------++std::vector<uint16_t> displacement16(const BakeResult& r) {+ std::vector<uint16_t> px;+ if (!r.has(BakeMap::Displacement) || r.displacement.size() != size_t(r.width) * size_t(r.height)) return px;+ px.resize(r.displacement.size());+ const float k = r.displacementScale > 0.0f ? 0.5f / r.displacementScale : 0.0f;+ for (int y = 0; y < r.height; ++y)+ for (int x = 0; x < r.width; ++x) {+ const float v = std::clamp(0.5f + r.displacement[size_t(y) * size_t(r.width) + size_t(x)] * k, 0.0f, 1.0f);+ px[size_t(r.height - 1 - y) * size_t(r.width) + size_t(x)] = uint16_t(std::lround(v * 65535.0f));+ }+ return px;+}++Image bakeMapImage(const BakeResult& r, BakeMap map) {+ Image img;+ if (!r.has(map) || r.width <= 0) return img;+ img.width = r.width;+ img.height = r.height;+ img.rgba.assign(size_t(r.width) * size_t(r.height) * 4, 255);+ const std::vector<uint8_t>* rgb = map == BakeMap::Normal ? &r.normal : map == BakeMap::ObjectNormal ? &r.objectNormal+ : map == BakeMap::Color ? &r.color : nullptr;+ const std::vector<uint8_t>* grey = map == BakeMap::AmbientOcclusion ? &r.ao : map == BakeMap::Cavity ? &r.cavity : nullptr;+ const float k = r.displacementScale > 0.0f ? 0.5f / r.displacementScale : 0.0f;+ for (int y = 0; y < r.height; ++y)+ for (int x = 0; x < r.width; ++x) {+ const size_t i = size_t(y) * size_t(r.width) + size_t(x);+ uint8_t* p = &img.rgba[(size_t(r.height - 1 - y) * size_t(r.width) + size_t(x)) * 4];+ if (rgb) {+ p[0] = (*rgb)[i * 3], p[1] = (*rgb)[i * 3 + 1], p[2] = (*rgb)[i * 3 + 2];+ } else if (grey) {+ p[0] = p[1] = p[2] = (*grey)[i];+ } else {+ p[0] = p[1] = p[2] = unorm8(0.5f + r.displacement[i] * k);+ }+ }+ return img;+}++std::string bakeFileName(const std::string& base, BakeMap map, const char* ext) {+ const char* suffix = map == BakeMap::ObjectNormal ? "normal_object" : bakeMapId(map);+ return base + "_" + suffix + ext;+}++bool saveBakeMaps(const BakeResult& r, const std::string& folder, const std::string& base, bool exr,+ std::vector<std::string>& written, std::string& error) {+ written.clear();+ std::error_code ec;+ const std::filesystem::path dir = fsPath(folder.empty() ? std::string(".") : folder);+ std::filesystem::create_directories(dir, ec);+ for (int i = 0; i < kBakeMapCount; ++i) {+ const BakeMap m = BakeMap(i);+ if (!r.has(m)) continue;+ const std::string path = utf8(dir / fsPath(bakeFileName(base, m)));+ if (m == BakeMap::Displacement) {+ if (!savePng16(path, r.width, r.height, 1, displacement16(r), error)) return false;+ written.push_back(path);+ if (exr) {+ std::vector<float> f(r.displacement.size());+ for (int y = 0; y < r.height; ++y)+ std::memcpy(&f[size_t(r.height - 1 - y) * size_t(r.width)], &r.displacement[size_t(y) * size_t(r.width)],+ size_t(r.width) * sizeof(float));+ const std::string exrPath = utf8(dir / fsPath(bakeFileName(base, m, ".exr")));+ if (!saveExr(exrPath, r.width, r.height, 1, f, error)) return false;+ written.push_back(exrPath);+ }+ continue;+ }+ if (!bakeMapImage(r, m).savePng(path, error)) return false;+ written.push_back(path);+ }+ return true;+}++std::string bakeSummary(const BakeResult& r) {+ std::ostringstream s;+ s.setf(std::ios::fixed);+ s.precision(1);+ std::string names;+ for (int i = 0; i < kBakeMapCount; ++i)+ if (r.has(BakeMap(i))) names += std::string(names.empty() ? "" : ", ") + bakeMapId(BakeMap(i));+ s << "Baked " << names << " at " << r.width << "x" << r.height << " from " << r.sourceTriangles << " triangles in "+ << r.seconds << " s";+ s.precision(4);+ s << "; rays " << r.front << " in front, " << r.rear << " behind";+ if (r.has(BakeMap::Displacement))+ s << "; displacement " << r.displacementMin << " to " << r.displacementMax << ", PNG mid-grey = 0, white = +"+ << r.displacementScale << ", black = -" << r.displacementScale;+ if (r.missRatio() >= 0.0005f) {+ s.precision(1);+ s << "; " << 100.0f * r.missRatio() << "% of texels found no surface (raise Front / Rear)";+ }+ return s.str();+}++bool bakeSourceSubtools(const Document& doc, const std::string& source, std::vector<int>& indices, std::string& error) {+ indices.clear();+ if (source.empty() || source == "all" || source == "visible") {+ for (int i = 0; i < doc.subtoolCount(); ++i)+ if (i != doc.activeSubtool && doc.subtools[size_t(i)].visible && doc.subtoolMesh(i).triangleCount())+ indices.push_back(i);+ if (indices.empty()) error = "No other visible SubTool to bake from: show the high-poly SubTool(s), or append one";+ return !indices.empty();+ }+ const int i = doc.findSubtool(source);+ if (i < 0) {+ error = "No SubTool called '" + source + "'";+ return false;+ }+ if (i == doc.activeSubtool) {+ error = "'" + source + "' is the active SubTool (the low-poly the maps go onto): pick another source";+ return false;+ }+ indices.push_back(i);+ return true;+}++std::string defaultBakeFolder(const Document& doc) {+ if (!doc.path.empty()) {+ const std::filesystem::path p = fsPath(doc.path).parent_path();+ if (!p.empty()) return utf8(p);+ }+ return ".";+}++void setBakeListener(BakeListener listener) {+ std::lock_guard lock(g_listenerMutex);+ g_listener = std::move(listener);+}++void notifyBakeListener(const Document& doc, std::shared_ptr<const BakeResult> result) {+ BakeListener l;+ {+ std::lock_guard lock(g_listenerMutex);+ l = g_listener;+ }+ if (l) l(doc, std::move(result));+}++// ---------------------------------------------------------------------------+// Command+// ---------------------------------------------------------------------------++void registerBakeCommands(CommandRegistry& reg) {+ using T = ParamSpec::Type;+ reg.add({"bake",+ "Bake maps from a high-poly source onto the active SubTool's UVs (the low-poly): tangent-space normal "+ "(MikkTSpace), object-space normal, displacement (16-bit PNG + 32-bit EXR), ambient occlusion, cavity and "+ "colour. Rays go along the low-poly's smooth normals from 'front' in front of it to 'rear' behind it. "+ "Writes <name>_<map>.png into the output folder.",+ {{"source", T::String, "SubTool to bake from, or all (default: every visible SubTool but the active one).", false},+ {"maps", T::String, "Comma list: normal, object_normal, displacement, ao, cavity, color, or all. Default normal.", false},+ {"size", T::Number, "Map size in texels: 512, 1024, 2048 (default), 4096 or 8192 (1k...8k also work).", false},+ {"out", T::String, "Output folder (default: the project's folder, or the current folder).", false},+ {"name", T::String, "File name prefix (default: the active SubTool's name).", false},+ {"front", T::String, "Ray start in front of the low-poly, as a fraction of its size (e.g. 0.02), or auto (default).", false},+ {"rear", T::String, "How far behind the low-poly rays look, as a fraction of its size, or auto (default).", false},+ {"samples", T::Number, "Anti-aliasing: samples x samples rays per texel, 1-4. Default 2.", false},+ {"padding", T::Number, "Texels filled around each UV island, 0-64. Default 8.", false},+ {"ao_rays", T::Number, "Ambient occlusion rays per texel. Default 48.", false},+ {"ao_distance", T::Number, "How far occluders count, as a fraction of the size. Default 0.05.", false},+ {"green", T::String, "Normal map convention: opengl (default; Blender, Unity, Godot) or directx (Unreal).", false},+ {"displacement_scale", T::Number, "World units at white in the displacement PNG (default: the largest distance).", false},+ {"exr", T::Bool, "Also write the displacement as a 32-bit float EXR in world units. Default true.", false}},+ [](Document& doc, const Args& a) -> CommandResult {+ BakeSettings st;+ std::string err;+ if (!parseBakeMaps(argString(a, "maps", "normal"), st.maps, err)) return {false, err};+ if (a.contains("size")) {+ std::string text = argString(a, "size", "");+ if (text.empty()) text = std::to_string(int(argNumber(a, "size", 2048)));+ for (char& c : text) c = char(std::tolower(static_cast<unsigned char>(c)));+ int n = 0;+ try {+ n = !text.empty() && text.back() == 'k' ? std::stoi(text.substr(0, text.size() - 1)) * 1024 : std::stoi(text);+ } catch (...) {+ n = 0;+ }+ if (n != 256 && n != 512 && n != 1024 && n != 2048 && n != 4096 && n != 8192)+ return {false, "size must be 256, 512, 1024, 2048, 4096 or 8192"};+ st.size = n;+ }+ auto distance = [&](const char* key, float& value) -> bool {+ if (!a.contains(key)) return true;+ std::string s = argString(a, key, "");+ if (s == "auto") return true;+ const double v = s.empty() ? argNumber(a, key, -1) : std::atof(s.c_str());+ if (!(v > 0.0 && v <= 1.0)) return false;+ value = float(v);+ st.autoDistance = false;+ return true;+ };+ if (!distance("front", st.front) || !distance("rear", st.rear))+ return {false, "front and rear are fractions of the model's size between 0 and 1 (e.g. 0.02), or auto"};+ if (!st.autoDistance) { // one given, the other auto: keep the given one and default the other+ if (!a.contains("front") || argString(a, "front", "") == "auto") st.front = 0.02f;+ if (!a.contains("rear") || argString(a, "rear", "") == "auto") st.rear = 0.02f;+ }+ st.samples = int(argNumber(a, "samples", st.samples));+ st.padding = int(argNumber(a, "padding", st.padding));+ st.aoRays = int(argNumber(a, "ao_rays", st.aoRays));+ st.aoDistance = float(argNumber(a, "ao_distance", st.aoDistance));+ st.displacementScale = float(argNumber(a, "displacement_scale", 0.0));+ const std::string green = argString(a, "green", "opengl");+ if (green != "opengl" && green != "directx") return {false, "green must be opengl or directx"};+ st.flipGreen = green == "directx";++ std::vector<int> idx;+ if (!bakeSourceSubtools(doc, argString(a, "source", "all"), idx, err)) return {false, err};+ std::vector<const Mesh*> sources;+ for (int i : idx) sources.push_back(&doc.subtoolMesh(i));+ auto result = std::make_shared<BakeResult>();+ if (!bakeMaps(doc.mesh, sources, st, *result, err)) return {false, err};+ std::string name = argString(a, "name", doc.activeSubtoolInfo().name);+ for (char& c : name)+ if (c == '/' || c == '\\' || c == ':' || c == '*' || c == '?' || c == '"' || c == '<' || c == '>' || c == '|')+ c = '_';+ if (name.empty()) name = "bake";+ const std::string folder = argString(a, "out", defaultBakeFolder(doc));+ std::vector<std::string> written;+ if (!saveBakeMaps(*result, folder, name, argBool(a, "exr", true), written, err)) return {false, err};+ notifyBakeListener(doc, result);+ std::string files;+ for (const std::string& w : written) files += "\n " + w;+ return {true, bakeSummary(*result) + "\nWrote:" + files};+ }});+}++} // namespace sfdiff --git a/src/core/Bake.h b/src/core/Bake.hnew file mode 100644index 00000000..5fc0f2fa--- /dev/null+++ b/src/core/Bake.h@@ -0,0 +1,114 @@+// SculptForge - open source digital sculpting+// SPDX-License-Identifier: GPL-3.0-or-later+//+// Map baking: the detail of a high-poly sculpt (one or more SubTools) captured as images on the UVs of a+// low-poly SubTool, for game engines and renderers. Maps: tangent-space normal (MikkTSpace, core/Tangents.h,+// so Blender, Unreal, Unity and Godot show it right), object-space normal, displacement, ambient occlusion,+// cavity and colour (polypaint or the source's painted texture).+//+// How it works, as xNormal and Substance do it: every texel sample on the low-poly surface casts a ray along+// its smooth (interpolated) normal through a "cage" from `front` in front of the surface to `rear` behind it,+// and takes the high-poly hit nearest to the low-poly surface. Distances are fractions of the low-poly's+// bounding-box diagonal; "auto" measures how far the high-poly strays from the low-poly first. Texels are+// supersampled (samples x samples rays each), and `padding` texels around each UV island are filled from the+// island's edge so seams don't show once mipmapped. The work runs on every core, tile by tile, with progress+// and cancel, over a BVH built for the bake (thread-safe, unlike the brush BVH).+//+// Rows are bottom-up (row 0 is v = 0), as PaintTexture's; saving flips them.+#pragma once++#include "core/Commands.h"+#include "core/Image.h"+#include "core/Mesh.h"++#include <glm/glm.hpp>++#include <cstdint>+#include <functional>+#include <memory>+#include <string>+#include <vector>++namespace sf {++enum class BakeMap : int { Normal, ObjectNormal, Displacement, AmbientOcclusion, Cavity, Color };+constexpr int kBakeMapCount = 6;+constexpr uint32_t bakeBit(BakeMap m) { return 1u << int(m); }+const char* bakeMapId(BakeMap m); // "normal", "object_normal", "displacement", "ao", "cavity", "color"+const char* bakeMapLabel(BakeMap m); // "Normal (tangent)", ...+// A comma-separated list of ids ("normal,ao", or "all"); false + error naming the bad entry.+bool parseBakeMaps(const std::string& list, uint32_t& maps, std::string& error);++struct BakeSettings {+ int size = 2048; // square map, 512..8192+ uint32_t maps = bakeBit(BakeMap::Normal);+ bool autoDistance = true; // measure front / rear from the meshes (they are reported back)+ float front = 0.02f, rear = 0.02f; // ray range in front of / behind the low-poly, x bounding-box diagonal+ int samples = 2; // supersampling: samples x samples rays per texel (1..4)+ int padding = 8; // texels filled around each UV island (0..64)+ int aoRays = 48; // per texel+ float aoDistance = 0.05f; // how far occluders count, x bounding-box diagonal+ bool flipGreen = false; // DirectX-style normal map (green = down), as Unreal expects natively+ float displacementScale = 0.0f; // world units that map to white in the PNG; 0 = the largest distance found+ int threads = 0; // 0 = every core+};++struct BakeResult {+ int width = 0, height = 0;+ uint32_t maps = 0;+ bool flipGreen = false;+ // Present for the maps baked. RGB8 / grey8, rows bottom-up.+ std::vector<uint8_t> normal, objectNormal, color, ao, cavity;+ std::vector<float> displacement; // world units along the low-poly normal, + = the high-poly is outside+ std::vector<uint8_t> coverage; // 1 = inside a UV island, 2 = padding, 0 = empty+ std::vector<glm::vec4> tangents; // MikkTSpace tangent + sign per low-poly corner (for previews)+ float front = 0, rear = 0; // ray range used (world units)+ float diagonal = 0; // the low-poly's bounding-box diagonal+ float displacementMin = 0, displacementMax = 0; // range found (world units)+ float displacementScale = 0; // world units at white / black of the 16-bit PNG (mid-grey = 0)+ size_t islandTexels = 0, missedTexels = 0; // texels inside islands, and those whose rays found nothing+ size_t sourceTriangles = 0;+ double seconds = 0, bvhSeconds = 0;+ bool has(BakeMap m) const { return (maps & bakeBit(m)) != 0; }+ float missRatio() const { return islandTexels ? float(missedTexels) / float(islandTexels) : 0.0f; }+};++// Progress 0..1; return false to cancel (bakeMaps then fails with "Cancelled").+using BakeProgress = std::function<bool(float)>;++// Bakes `sources` (meshes, hidden triangles skipped) onto the UVs of `low`. Needs UVs on `low`, valid normals+// on every mesh. Colour comes from each source's texture when it has one, else its polypaint.+bool bakeMaps(const Mesh& low, const std::vector<const Mesh*>& sources, const BakeSettings& settings, BakeResult& result,+ std::string& error, const BakeProgress& progress = {});++// A baked map as a top-down 8-bit image (displacement mid-grey = 0, +/- displacementScale at white / black).+Image bakeMapImage(const BakeResult& result, BakeMap map);+// The displacement as 16-bit grey (top-down; 32768 = 0) and as floats in world units (top-down).+std::vector<uint16_t> displacement16(const BakeResult& result);++// File name of a map: "<base>_normal.png", "<base>_normal_object.png", "<base>_displacement.png" (+ .exr),+// "<base>_ao.png", "<base>_cavity.png", "<base>_color.png".+std::string bakeFileName(const std::string& base, BakeMap map, const char* extension = ".png");+// Writes every baked map into `folder` (created if needed); `written` gets the paths. Displacement goes out as+// a 16-bit PNG and, with `exr`, as a 32-bit float EXR in world units.+bool saveBakeMaps(const BakeResult& result, const std::string& folder, const std::string& base, bool exr,+ std::vector<std::string>& written, std::string& error);++// One line for people: what was baked, the ranges, the displacement scale and the time.+std::string bakeSummary(const BakeResult& result);++// The SubTools a "source" argument names for baking onto the active SubTool: "all" (or empty) = every visible+// SubTool but the active one, "visible" likewise, otherwise a SubTool name. False + error when none qualify.+bool bakeSourceSubtools(const Document& doc, const std::string& source, std::vector<int>& indices, std::string& error);+// Where maps go when no folder is given: the project's folder, else the current folder.+std::string defaultBakeFolder(const Document& doc);++// Called after the bake command succeeds (the app shows the normal map on the model).+using BakeListener = std::function<void(const Document&, std::shared_ptr<const BakeResult>)>;+void setBakeListener(BakeListener listener);+void notifyBakeListener(const Document& doc, std::shared_ptr<const BakeResult> result);++// bake+void registerBakeCommands(CommandRegistry& registry);++} // namespace sfdiff --git a/src/core/BakeImage.cpp b/src/core/BakeImage.cppnew file mode 100644index 00000000..39b85169--- /dev/null+++ b/src/core/BakeImage.cpp@@ -0,0 +1,334 @@+// SculptForge - open source digital sculpting+// SPDX-License-Identifier: GPL-3.0-or-later+#include "core/BakeImage.h"++#include <array>+#include <cstdlib>+#include <cstring>+#include <filesystem>+#include <fstream>+#include <iterator>+#include <map>++// Declarations only: the implementations are compiled in core/Image.cpp.+#define STBI_NO_STDIO+#include "stb_image.h"+// Compiled with stb_image_write's implementation in core/Image.cpp (not declared by its header).+extern "C" unsigned char* stbi_zlib_compress(unsigned char* data, int data_len, int* out_len, int quality);++namespace sf {++namespace {++std::filesystem::path fsPath(const std::string& s) { return std::filesystem::path(std::u8string(s.begin(), s.end())); }++bool writeFile(const std::string& path, const std::vector<uint8_t>& bytes, std::string& error) {+ std::ofstream f(fsPath(path), std::ios::binary);+ if (f) f.write(reinterpret_cast<const char*>(bytes.data()), std::streamsize(bytes.size()));+ if (!f) {+ error = "Cannot write " + path;+ return false;+ }+ return true;+}++bool readFile(const std::string& path, std::vector<uint8_t>& bytes, std::string& error) {+ std::ifstream f(fsPath(path), std::ios::binary);+ if (!f) {+ error = "Cannot open " + path;+ return false;+ }+ bytes.assign(std::istreambuf_iterator<char>(f), std::istreambuf_iterator<char>());+ return true;+}++// --- PNG ---++uint32_t crc32(const uint8_t* data, size_t n, uint32_t crc = 0) {+ static const std::array<uint32_t, 256> table = [] {+ std::array<uint32_t, 256> t{};+ for (uint32_t i = 0; i < 256; ++i) {+ uint32_t c = i;+ for (int k = 0; k < 8; ++k) c = c & 1 ? 0xEDB88320u ^ (c >> 1) : c >> 1;+ t[i] = c;+ }+ return t;+ }();+ crc = ~crc;+ for (size_t i = 0; i < n; ++i) crc = table[(crc ^ data[i]) & 0xFF] ^ (crc >> 8);+ return ~crc;+}++void putBe32(std::vector<uint8_t>& out, uint32_t v) {+ out.insert(out.end(), {uint8_t(v >> 24), uint8_t(v >> 16), uint8_t(v >> 8), uint8_t(v)});+}++void chunk(std::vector<uint8_t>& out, const char* type, const uint8_t* data, size_t n) {+ putBe32(out, uint32_t(n));+ const size_t start = out.size();+ out.insert(out.end(), type, type + 4);+ if (n) out.insert(out.end(), data, data + n);+ putBe32(out, crc32(&out[start], n + 4));+}++// --- EXR ---++void put32(std::vector<uint8_t>& out, uint32_t v) {+ out.insert(out.end(), {uint8_t(v), uint8_t(v >> 8), uint8_t(v >> 16), uint8_t(v >> 24)});+}+void putF(std::vector<uint8_t>& out, float f) {+ uint32_t v;+ std::memcpy(&v, &f, 4);+ put32(out, v);+}+void attribute(std::vector<uint8_t>& out, const char* name, const char* type, const std::vector<uint8_t>& value) {+ out.insert(out.end(), name, name + std::strlen(name) + 1);+ out.insert(out.end(), type, type + std::strlen(type) + 1);+ put32(out, uint32_t(value.size()));+ out.insert(out.end(), value.begin(), value.end());+}++float halfToFloat(uint16_t h) {+ const uint32_t s = uint32_t(h >> 15) << 31, e = (h >> 10) & 0x1F, m = h & 0x3FF;+ uint32_t bits;+ if (e == 0) {+ if (m == 0) {+ bits = s;+ } else { // subnormal+ int ee = -1;+ uint32_t mm = m;+ do {+ ++ee;+ mm <<= 1;+ } while (!(mm & 0x400));+ bits = s | (uint32_t(127 - 15 - ee) << 23) | ((mm & 0x3FF) << 13);+ }+ } else if (e == 31) {+ bits = s | 0x7F800000u | (m << 13);+ } else {+ bits = s | ((e + 127 - 15) << 23) | (m << 13);+ }+ float f;+ std::memcpy(&f, &bits, 4);+ return f;+}++// The EXR channel names for `channels` values per pixel, in the file's (alphabetical) order, and where each+// comes from in an interleaved pixel.+std::vector<std::pair<const char*, int>> exrChannels(int channels) {+ if (channels == 1) return {{"Y", 0}};+ return {{"B", 2}, {"G", 1}, {"R", 0}};+}++} // namespace++bool savePng16(const std::string& path, int width, int height, int channels, const std::vector<uint16_t>& px,+ std::string& error) {+ if (width <= 0 || height <= 0 || (channels != 1 && channels != 3) ||+ px.size() != size_t(width) * size_t(height) * size_t(channels)) {+ error = "Bad 16-bit image";+ return false;+ }+ // Rows with the "Up" filter (good for smooth maps), samples big-endian.+ const size_t rowBytes = size_t(width) * size_t(channels) * 2;+ std::vector<uint8_t> raw((rowBytes + 1) * size_t(height));+ std::vector<uint8_t> prev(rowBytes, 0), cur(rowBytes);+ for (int y = 0; y < height; ++y) {+ const uint16_t* src = &px[size_t(y) * size_t(width) * size_t(channels)];+ for (size_t i = 0; i < size_t(width) * size_t(channels); ++i) {+ cur[i * 2] = uint8_t(src[i] >> 8);+ cur[i * 2 + 1] = uint8_t(src[i]);+ }+ uint8_t* dst = &raw[size_t(y) * (rowBytes + 1)];+ dst[0] = 2; // Up+ for (size_t i = 0; i < rowBytes; ++i) dst[i + 1] = uint8_t(cur[i] - prev[i]);+ prev.swap(cur);+ }+ int zlen = 0;+ unsigned char* z = stbi_zlib_compress(raw.data(), int(raw.size()), &zlen, 6);+ if (!z) {+ error = "PNG compression failed";+ return false;+ }+ std::vector<uint8_t> out = {0x89, 'P', 'N', 'G', '\r', '\n', 0x1A, '\n'};+ std::vector<uint8_t> ihdr;+ putBe32(ihdr, uint32_t(width));+ putBe32(ihdr, uint32_t(height));+ ihdr.insert(ihdr.end(), {16, uint8_t(channels == 1 ? 0 : 2), 0, 0, 0});+ chunk(out, "IHDR", ihdr.data(), ihdr.size());+ chunk(out, "IDAT", z, size_t(zlen));+ std::free(z);+ chunk(out, "IEND", nullptr, 0);+ return writeFile(path, out, error);+}++bool loadPng16(const std::string& path, int& width, int& height, int& channels, std::vector<uint16_t>& pixels,+ std::string& error) {+ std::vector<uint8_t> bytes;+ if (!readFile(path, bytes, error)) return false;+ int w = 0, h = 0, n = 0;+ stbi_us* data = stbi_load_16_from_memory(bytes.data(), int(bytes.size()), &w, &h, &n, 0);+ if (!data) {+ error = "Cannot decode " + path;+ return false;+ }+ width = w, height = h, channels = n;+ pixels.assign(data, data + size_t(w) * size_t(h) * size_t(n));+ stbi_image_free(data);+ return true;+}++bool saveExr(const std::string& path, int width, int height, int channels, const std::vector<float>& px, std::string& error) {+ if (width <= 0 || height <= 0 || (channels != 1 && channels != 3) ||+ px.size() != size_t(width) * size_t(height) * size_t(channels)) {+ error = "Bad float image";+ return false;+ }+ const auto chans = exrChannels(channels);+ std::vector<uint8_t> out;+ put32(out, 20000630); // magic+ put32(out, 2); // version 2, single-part scanline+ std::vector<uint8_t> v;+ for (const auto& [name, src] : chans) {+ v.insert(v.end(), name, name + std::strlen(name) + 1);+ put32(v, 2); // FLOAT+ v.insert(v.end(), {0, 0, 0, 0}); // pLinear + reserved+ put32(v, 1); // x sampling+ put32(v, 1); // y sampling+ }+ v.push_back(0);+ attribute(out, "channels", "chlist", v);+ attribute(out, "compression", "compression", {0});+ v.clear();+ for (int i : {0, 0, width - 1, height - 1}) put32(v, uint32_t(i));+ attribute(out, "dataWindow", "box2i", v);+ attribute(out, "displayWindow", "box2i", v);+ attribute(out, "lineOrder", "lineOrder", {0});+ v.clear();+ putF(v, 1.0f);+ attribute(out, "pixelAspectRatio", "float", v);+ v.clear();+ putF(v, 0.0f);+ putF(v, 0.0f);+ attribute(out, "screenWindowCenter", "v2f", v);+ v.clear();+ putF(v, 1.0f);+ attribute(out, "screenWindowWidth", "float", v);+ out.push_back(0); // end of header+ const size_t lineBytes = size_t(width) * size_t(channels) * 4;+ const size_t table = out.size(), first = table + size_t(height) * 8;+ out.resize(first + size_t(height) * (8 + lineBytes));+ for (int y = 0; y < height; ++y) {+ const uint64_t off = first + size_t(y) * (8 + lineBytes);+ for (int b = 0; b < 8; ++b) out[table + size_t(y) * 8 + size_t(b)] = uint8_t(off >> (8 * b));+ uint8_t* p = &out[off];+ const uint32_t hdr[2] = {uint32_t(y), uint32_t(lineBytes)};+ for (int k = 0; k < 2; ++k)+ for (int b = 0; b < 4; ++b) *p++ = uint8_t(hdr[k] >> (8 * b));+ for (const auto& [name, src] : chans)+ for (int x = 0; x < width; ++x) {+ const float f = px[(size_t(y) * size_t(width) + size_t(x)) * size_t(channels) + size_t(src)];+ std::memcpy(p, &f, 4); // EXR is little-endian, as every platform we build for+ p += 4;+ }+ }+ return writeFile(path, out, error);+}++bool loadExr(const std::string& path, int& width, int& height, int& channels, std::vector<float>& pixels,+ std::string& error) {+ std::vector<uint8_t> b;+ if (!readFile(path, b, error)) return false;+ size_t pos = 0;+ auto bad = [&](const char* why) {+ error = std::string("Not a supported EXR (") + why + "): " + path;+ return false;+ };+ auto u32 = [&](size_t at) {+ return uint32_t(b[at]) | uint32_t(b[at + 1]) << 8 | uint32_t(b[at + 2]) << 16 | uint32_t(b[at + 3]) << 24;+ };+ if (b.size() < 8 || u32(0) != 20000630) return bad("magic");+ if ((u32(4) & 0xFF) != 2 || (u32(4) & 0x1E00)) return bad("only single-part scanline files");+ pos = 8;+ struct Chan {+ std::string name;+ int type;+ };+ std::vector<Chan> chans;+ int compression = -1, x0 = 0, y0 = 0, x1 = -1, y1 = -1;+ for (;;) {+ if (pos >= b.size()) return bad("truncated header");+ if (b[pos] == 0) {+ ++pos;+ break;+ }+ auto str = [&]() {+ std::string s;+ while (pos < b.size() && b[pos]) s += char(b[pos++]);+ ++pos;+ return s;+ };+ const std::string name = str(), type = str();+ if (pos + 4 > b.size()) return bad("truncated header");+ const uint32_t size = u32(pos);+ pos += 4;+ if (pos + size > b.size()) return bad("truncated header");+ const size_t end = pos + size;+ if (name == "channels") {+ while (pos < end && b[pos]) {+ Chan c;+ c.name = str();+ if (pos + 16 > end) return bad("channel list");+ c.type = int(u32(pos));+ chans.push_back(c);+ pos += 16;+ }+ } else if (name == "compression") {+ compression = b[pos];+ } else if (name == "dataWindow" && size == 16) {+ x0 = int(u32(pos)), y0 = int(u32(pos + 4)), x1 = int(u32(pos + 8)), y1 = int(u32(pos + 12));+ }+ pos = end;+ }+ if (compression != 0) return bad("compressed");+ width = x1 - x0 + 1, height = y1 - y0 + 1;+ if (width <= 0 || height <= 0 || chans.empty() || width > 65536 || height > 65536) return bad("size");+ // Map file channels to output channels: Y alone -> 1, else R, G, B -> 3.+ std::map<std::string, int> slot = {{"Y", 0}, {"R", 0}, {"G", 1}, {"B", 2}};+ const bool rgb = chans.size() >= 3;+ channels = rgb ? 3 : 1;+ size_t pixelBytes = 0;+ for (const Chan& c : chans) {+ if (c.type != 1 && c.type != 2) return bad("unsupported pixel type");+ pixelBytes += c.type == 1 ? 2 : 4;+ }+ pixels.assign(size_t(width) * size_t(height) * size_t(channels), 0.0f);+ const size_t table = pos;+ if (table + size_t(height) * 8 > b.size()) return bad("offset table");+ for (int line = 0; line < height; ++line) {+ uint64_t off = 0;+ for (int k = 0; k < 8; ++k) off |= uint64_t(b[table + size_t(line) * 8 + size_t(k)]) << (8 * k);+ if (off + 8 + pixelBytes * size_t(width) > b.size()) return bad("scanline");+ const int y = int(u32(size_t(off))) - y0;+ if (y < 0 || y >= height) return bad("scanline y");+ size_t p = size_t(off) + 8;+ for (const Chan& c : chans) {+ const auto it = slot.find(c.name);+ const int dst = it == slot.end() || (!rgb && c.name != "Y" && chans.size() > 1) ? -1 : it->second;+ for (int x = 0; x < width; ++x) {+ float f;+ if (c.type == 2) {+ std::memcpy(&f, &b[p], 4);+ p += 4;+ } else {+ f = halfToFloat(uint16_t(b[p] | b[p + 1] << 8));+ p += 2;+ }+ if (dst >= 0 && dst < channels) pixels[(size_t(y) * size_t(width) + size_t(x)) * size_t(channels) + size_t(dst)] = f;+ }+ }+ }+ return true;+}++} // namespace sfdiff --git a/src/core/BakeImage.h b/src/core/BakeImage.hnew file mode 100644index 00000000..1fc82826--- /dev/null+++ b/src/core/BakeImage.h@@ -0,0 +1,28 @@+// SculptForge - open source digital sculpting+// SPDX-License-Identifier: GPL-3.0-or-later+//+// High-precision image files for baked maps (core/Bake.h): 16-bit greyscale or RGB PNG and 32-bit float+// OpenEXR (uncompressed scanlines, one Y channel or R/G/B), plus readers for both so tests and tools can+// check what was written. Pixel rows are top-down, as in the files.+#pragma once++#include <cstdint>+#include <string>+#include <vector>++namespace sf {++// `channels` is 1 (grey) or 3 (RGB); `pixels` holds width * height * channels values.+bool savePng16(const std::string& path, int width, int height, int channels, const std::vector<uint16_t>& pixels,+ std::string& error);+// Reads any PNG as 16 bits per channel (8-bit files are scaled up); `channels` is what the file has.+bool loadPng16(const std::string& path, int& width, int& height, int& channels, std::vector<uint16_t>& pixels,+ std::string& error);++bool saveExr(const std::string& path, int width, int height, int channels, const std::vector<float>& pixels,+ std::string& error);+// Reads uncompressed float or half EXR scanline files (what saveExr writes, and other tools' "no compression").+bool loadExr(const std::string& path, int& width, int& height, int& channels, std::vector<float>& pixels,+ std::string& error);++} // namespace sfdiff --git a/src/core/Commands.cpp b/src/core/Commands.cppindex 06c299ca..c2e8c493 100644--- a/src/core/Commands.cpp+++ b/src/core/Commands.cpp@@ -2,6 +2,7 @@// SPDX-License-Identifier: GPL-3.0-or-later#include "core/Commands.h"+#include "core/Bake.h"#include "core/BrushAlpha.h"#include "core/BrushLibrary.h"#include "core/Decimate.h"@@ -755,6 +756,7 @@ CommandRegistry::CommandRegistry() {registerSubToolCommands(*this);registerPaintCommands(*this); // core/Polypaint.cppregisterGozCommands(*this); // goz_import/export/send/receive, export_stl (io/GozCommands.cpp)+ registerBakeCommands(*this); // bake (core/Bake.cpp)registerProjectCommands(*this); // keep last (core/Project.cpp)}diff --git a/src/core/Tangents.cpp b/src/core/Tangents.cppnew file mode 100644index 00000000..6e5efafb--- /dev/null+++ b/src/core/Tangents.cpp@@ -0,0 +1,60 @@+// SculptForge - open source digital sculpting+// SPDX-License-Identifier: GPL-3.0-or-later+#include "core/Tangents.h"++extern "C" {+#include "mikktspace.h"+}++namespace sf {++namespace {++struct MikkMesh {+ const Mesh* mesh;+ std::vector<glm::vec4>* out;+};++const Mesh& meshOf(const SMikkTSpaceContext* c) { return *static_cast<const MikkMesh*>(c->m_pUserData)->mesh; }++int numFaces(const SMikkTSpaceContext* c) { return int(meshOf(c).triangleCount()); }+int numVerts(const SMikkTSpaceContext*, const int) { return 3; }+void position(const SMikkTSpaceContext* c, float out[], const int f, const int v) {+ const Mesh& m = meshOf(c);+ const glm::vec3& p = m.positions[m.triangles[size_t(f)][v]];+ out[0] = p.x, out[1] = p.y, out[2] = p.z;+}+void normal(const SMikkTSpaceContext* c, float out[], const int f, const int v) {+ const Mesh& m = meshOf(c);+ const glm::vec3& n = m.normals[m.triangles[size_t(f)][v]];+ out[0] = n.x, out[1] = n.y, out[2] = n.z;+}+void texCoord(const SMikkTSpaceContext* c, float out[], const int f, const int v) {+ const glm::vec2& t = meshOf(c).uvs[size_t(f) * 3 + size_t(v)];+ out[0] = t.x, out[1] = t.y;+}+void setTangent(const SMikkTSpaceContext* c, const float t[], const float sign, const int f, const int v) {+ (*static_cast<const MikkMesh*>(c->m_pUserData)->out)[size_t(f) * 3 + size_t(v)] = glm::vec4(t[0], t[1], t[2], sign);+}++} // namespace++std::vector<glm::vec4> computeTangents(const Mesh& mesh) {+ std::vector<glm::vec4> out;+ const size_t nt = mesh.triangleCount();+ if (nt == 0 || mesh.uvs.size() != nt * 3 || mesh.normals.size() != mesh.vertexCount()) return out;+ out.assign(nt * 3, glm::vec4(1, 0, 0, 1));+ SMikkTSpaceInterface iface{};+ iface.m_getNumFaces = numFaces;+ iface.m_getNumVerticesOfFace = numVerts;+ iface.m_getPosition = position;+ iface.m_getNormal = normal;+ iface.m_getTexCoord = texCoord;+ iface.m_setTSpaceBasic = setTangent;+ MikkMesh user{&mesh, &out};+ SMikkTSpaceContext ctx{&iface, &user};+ genTangSpaceDefault(&ctx);+ return out;+}++} // namespace sfdiff --git a/src/core/Tangents.h b/src/core/Tangents.hnew file mode 100644index 00000000..3e4c8c17--- /dev/null+++ b/src/core/Tangents.h@@ -0,0 +1,22 @@+// SculptForge - open source digital sculpting+// SPDX-License-Identifier: GPL-3.0-or-later+//+// MikkTSpace tangents (third_party/mikktspace, zlib): the tangent frame Blender, Unreal, Unity, Godot,+// Substance and xNormal all compute for a mesh with UVs, so a tangent-space normal map baked against it+// shows the same in every one of them.+#pragma once++#include "core/Mesh.h"++#include <glm/glm.hpp>++#include <vector>++namespace sf {++// One tangent per triangle corner (3 per triangle, like Mesh::uvs): xyz is the unit tangent, w the+// bitangent sign (bitangent = w * cross(normal, tangent)), computed from the positions, the vertex normals+// (Mesh::normals) and the UVs. Empty when the mesh has no UVs.+std::vector<glm::vec4> computeTangents(const Mesh& mesh);++} // namespace sfdiff --git a/tests/test_bake.cpp b/tests/test_bake.cppnew file mode 100644index 00000000..d06e2998--- /dev/null+++ b/tests/test_bake.cpp@@ -0,0 +1,411 @@+// SculptForge - open source digital sculpting+// SPDX-License-Identifier: GPL-3.0-or-later+//+// Map baking (core/Bake.h): a finely subdivided sphere with a bump, a dent and a groove baked onto a low+// sphere. The tangent-space normal map decodes (with the same MikkTSpace frame a game engine uses) to the+// high-poly's normals, displacement has the right sign and scale in the float data, the 16-bit PNG and the+// EXR, AO is darker in the groove, UV islands are padded, and the bake command writes its files. Also the+// 16-bit PNG / EXR writers, MikkTSpace on a plane, and the time of a 4K bake from a million triangles.+#include "TestHarness.h"++#include "core/AutoUv.h"+#include "core/Bake.h"+#include "core/BakeImage.h"+#include "core/Commands.h"+#include "core/Primitives.h"+#include "core/Tangents.h"+#include "core/Texture.h"++#include <chrono>+#include <cmath>+#include <cstdio>+#include <filesystem>++using namespace sf;++namespace {++const glm::vec3 kBumpDir = glm::normalize(glm::vec3(0.0f, 0.0f, 1.0f));+const glm::vec3 kDentDir = glm::normalize(glm::vec3(0.0f, 0.0f, -1.0f));+constexpr float kBump = 0.15f, kDent = 0.10f, kGrooveY = 0.6f;++// Radius of the high-poly in direction `d` (unit): a sphere with a Gaussian bump towards +Z, a dent towards -Z+// and a narrow groove around the latitude y = 0.6.+float highRadius(const glm::vec3& d) {+ const float aBump = std::acos(std::clamp(glm::dot(d, kBumpDir), -1.0f, 1.0f));+ const float aDent = std::acos(std::clamp(glm::dot(d, kDentDir), -1.0f, 1.0f));+ return 1.0f + kBump * std::exp(-std::pow(aBump / 0.35f, 2.0f)) - kDent * std::exp(-std::pow(aDent / 0.35f, 2.0f)) -+ 0.06f * std::exp(-std::pow((d.y - kGrooveY) / 0.03f, 2.0f));+}++Mesh highPoly(int level) {+ Mesh m = makeIcosphere(level, 1.0f);+ for (glm::vec3& p : m.positions) p = glm::normalize(p) * highRadius(glm::normalize(p));+ m.recomputeAllNormals();+ return m;+}++Mesh lowPoly() {+ Mesh m = makeIcosphere(3, 1.0f);+ AutoUvResult uv;+ std::string err;+ computeAutoUv(m.positions, m.triangles, 512, uv, err);+ m.uvs = uv.uvs;+ return m;+}++// Texel -> (low triangle, barycentrics) for the island texels of a w x w map.+struct TexelMap {+ std::vector<int32_t> tri;+ std::vector<glm::vec3> bary;+};+TexelMap texelMap(const Mesh& low, int w) {+ TexelMap tm;+ tm.tri.assign(size_t(w) * size_t(w), -1);+ tm.bary.resize(tm.tri.size());+ for (uint32_t t = 0; t < low.triangleCount(); ++t)+ rasterizeUvTriangle(low.uvs[t * 3], low.uvs[t * 3 + 1], low.uvs[t * 3 + 2], w, w, [&](int x, int y, float b0, float b1, float b2) {+ tm.tri[size_t(y) * size_t(w) + size_t(x)] = int32_t(t);+ tm.bary[size_t(y) * size_t(w) + size_t(x)] = glm::vec3(b0, b1, b2);+ });+ return tm;+}++glm::vec3 lowPointOf(const Mesh& low, uint32_t t, const glm::vec3& b, glm::vec3* normal = nullptr) {+ const glm::uvec3& tv = low.triangles[t];+ if (normal) *normal = glm::normalize(low.normals[tv.x] * b.x + low.normals[tv.y] * b.y + low.normals[tv.z] * b.z);+ return low.positions[tv.x] * b.x + low.positions[tv.y] * b.y + low.positions[tv.z] * b.z;+}++// The analytic high-poly normal in direction d (finite differences of the radius function).+glm::vec3 highNormal(const glm::vec3& d) {+ glm::vec3 t, b;+ t = glm::normalize(glm::cross(std::abs(d.y) < 0.9f ? glm::vec3(0, 1, 0) : glm::vec3(1, 0, 0), d));+ b = glm::cross(d, t);+ const float h = 1e-3f;+ auto P = [&](const glm::vec3& dir) { return glm::normalize(dir) * highRadius(glm::normalize(dir)); };+ const glm::vec3 du = P(d + t * h) - P(d - t * h), dv = P(d + b * h) - P(d - b * h);+ glm::vec3 n = glm::normalize(glm::cross(du, dv));+ return glm::dot(n, d) < 0 ? -n : n;+}++float angleDeg(const glm::vec3& a, const glm::vec3& b) {+ return std::acos(std::clamp(glm::dot(glm::normalize(a), glm::normalize(b)), -1.0f, 1.0f)) * 57.29578f;+}++} // namespace++TEST(bake_mikktspace_plane) {+ Mesh m = makePlane(4, 2.0f); // in the XZ plane, normal +Y+ m.uvs.resize(m.triangleCount() * 3);+ for (size_t t = 0; t < m.triangleCount(); ++t)+ for (int c = 0; c < 3; ++c) {+ const glm::vec3 p = m.positions[m.triangles[t][c]];+ m.uvs[t * 3 + size_t(c)] = glm::vec2(p.x * 0.5f + 0.5f, p.z * 0.5f + 0.5f);+ }+ const auto tan = computeTangents(m);+ CHECK(tan.size() == m.triangleCount() * 3);+ bool ok = true;+ for (size_t i = 0; i < tan.size(); ++i) {+ // u grows along +X; v along +Z, and cross(N=+Y, T=+X) = -Z, so the sign is -1.+ ok = ok && glm::length(glm::vec3(tan[i]) - glm::vec3(1, 0, 0)) < 1e-4f && tan[i].w == -1.0f;+ }+ CHECK(ok);+ Mesh noUv = makePlane(2);+ CHECK(computeTangents(noUv).empty());+}++TEST(bake_png16_and_exr_round_trip) {+ const int w = 37, h = 11;+ std::vector<uint16_t> px(size_t(w) * h);+ std::vector<float> f(size_t(w) * h * 3);+ for (size_t i = 0; i < px.size(); ++i) {+ px[i] = uint16_t((i * 2654435761u) >> 16);+ for (int c = 0; c < 3; ++c) f[i * 3 + size_t(c)] = float(i) * 0.25f - 30.0f + float(c) * 1e-3f;+ }+ std::string err;+ const std::string png = tempPath("sf_bake16.png"), exr = tempPath("sf_bake.exr");+ CHECK(savePng16(png, w, h, 1, px, err));+ int rw = 0, rh = 0, rc = 0;+ std::vector<uint16_t> back;+ CHECK(loadPng16(png, rw, rh, rc, back, err));+ CHECK(rw == w && rh == h && rc == 1 && back == px);+ CHECK(saveExr(exr, w, h, 3, f, err));+ std::vector<float> fb;+ CHECK(loadExr(exr, rw, rh, rc, fb, err));+ CHECK(rw == w && rh == h && rc == 3 && fb == f);+ std::filesystem::remove(png);+ std::filesystem::remove(exr);+}++TEST(bake_bumpy_sphere_maps) {+ const Mesh high = highPoly(6); // 82k triangles+ const Mesh low = lowPoly();+ CHECK(low.hasUvs());+ BakeSettings st;+ st.size = 256;+ st.maps = bakeBit(BakeMap::Normal) | bakeBit(BakeMap::ObjectNormal) | bakeBit(BakeMap::Displacement) |+ bakeBit(BakeMap::AmbientOcclusion) | bakeBit(BakeMap::Cavity);+ st.aoRays = 64;+ st.aoDistance = 0.1f;+ BakeResult r;+ std::string err;+ CHECK(bakeMaps(low, {&high}, st, r, err));+ std::printf(" %s\n", bakeSummary(r).c_str());+ CHECK(r.width == 256 && r.normal.size() == 256 * 256 * 3 && r.displacement.size() == 256 * 256);+ CHECK(r.missedTexels * 100 < r.islandTexels); // auto distances catch (almost) everything+ // Auto range covers the bump (outside) and the dent (inside).+ CHECK(r.front > kBump * 0.9f && r.rear > kDent * 0.9f);++ const TexelMap tm = texelMap(low, r.width);+ double worstFlat = 0, sumErr = 0;+ int n = 0, bumpTexels = 0, dentTexels = 0;+ float bumpTop = -1, dentBottom = 1;+ float aoGroove = 0, aoFlat = 0, cavGroove = 0, cavFlat = 0;+ int nGroove = 0, nFlat = 0;+ for (size_t i = 0; i < tm.tri.size(); ++i) {+ if (tm.tri[i] < 0 || r.coverage[i] != 1) continue;+ const int x = int(i % size_t(r.width)), y = int(i / size_t(r.width));+ // Skip texels on island borders: their value mixes samples of neighbouring triangles.+ bool interior = x > 0 && y > 0 && x + 1 < r.width && y + 1 < r.height;+ for (int dy = -1; dy <= 1 && interior; ++dy)+ for (int dx = -1; dx <= 1 && interior; ++dx) interior = tm.tri[size_t(y + dy) * size_t(r.width) + size_t(x + dx)] >= 0;+ if (!interior) continue;+ const uint32_t t = uint32_t(tm.tri[i]);+ glm::vec3 nLow;+ const glm::vec3 p = lowPointOf(low, t, tm.bary[i], &nLow);+ const glm::vec3 dir = glm::normalize(p);+ // Decode the tangent-space normal the way a shader does.+ const glm::vec3 b = tm.bary[i];+ const glm::vec4 &t0 = r.tangents[t * 3], &t1 = r.tangents[t * 3 + 1], &t2 = r.tangents[t * 3 + 2];+ glm::vec3 T = glm::vec3(t0) * b.x + glm::vec3(t1) * b.y + glm::vec3(t2) * b.z;+ T = glm::normalize(T - nLow * glm::dot(nLow, T));+ const glm::vec3 B = t0.w * glm::cross(nLow, T);+ const glm::vec3 tn = glm::vec3(r.normal[i * 3], r.normal[i * 3 + 1], r.normal[i * 3 + 2]) / 127.5f - 1.0f;+ const glm::vec3 world = glm::normalize(tn.x * T + tn.y * B + tn.z * nLow);+ // Where the low-poly's ray meets the high-poly: about the same direction from the centre.+ const float e = angleDeg(world, highNormal(dir));+ const float bumpA = std::acos(glm::dot(dir, kBumpDir)), dentA = std::acos(glm::dot(dir, kDentDir));+ if (std::abs(dir.y - kGrooveY) > 0.12f) { // the groove is narrower than a texel: leave it out+ sumErr += e;+ ++n;+ worstFlat = std::max(worstFlat, double(e));+ }+ const float d = r.displacement[i];+ if (bumpA < 0.05f) bumpTop = std::max(bumpTop, d), ++bumpTexels;+ if (dentA < 0.05f) dentBottom = std::min(dentBottom, d), ++dentTexels;+ // The bump's flank tilts the normal away from the bump's centre: check the decoded direction.+ if (bumpA > 0.25f && bumpA < 0.35f) {+ const glm::vec3 away = glm::normalize(dir - kBumpDir * glm::dot(dir, kBumpDir));+ CHECK(glm::dot(world - nLow, away) > 0.05f);+ }+ if (std::abs(dir.y - kGrooveY) < 0.02f) aoGroove += r.ao[i] / 255.0f, cavGroove += r.cavity[i] / 255.0f, ++nGroove;+ if (std::abs(dir.y - 0.0f) < 0.05f && bumpA > 0.8f && dentA > 0.8f)+ aoFlat += r.ao[i] / 255.0f, cavFlat += r.cavity[i] / 255.0f, ++nFlat;+ }+ const double meanErr = sumErr / std::max(n, 1);+ std::printf(" normal map: mean error %.2f deg, worst %.2f deg over %d texels\n", meanErr, worstFlat, n);+ CHECK(n > 1000);+ CHECK(meanErr < 2.0);+ CHECK(worstFlat < 12.0);+ // Displacement: + at the bump (by about its height), - at the dent.+ CHECK(bumpTexels > 0 && dentTexels > 0);+ std::printf(" displacement: bump %.4f (expect ~%.3f), dent %.4f (expect ~-%.3f), scale %.4f\n", bumpTop, kBump,+ dentBottom, kDent, r.displacementScale);+ CHECK(std::abs(bumpTop - kBump) < 0.02f);+ CHECK(std::abs(dentBottom + kDent) < 0.02f);+ CHECK(std::abs(r.displacementScale - std::max(std::abs(r.displacementMin), r.displacementMax)) < 1e-6f);+ // AO: darker in the groove than on the open sphere.+ CHECK(nGroove > 0 && nFlat > 0);+ aoGroove /= float(std::max(nGroove, 1));+ aoFlat /= float(std::max(nFlat, 1));+ std::printf(" AO: groove %.3f, open surface %.3f\n", aoGroove, aoFlat);+ CHECK(aoFlat > 0.95f);+ CHECK(aoGroove < aoFlat - 0.1f);+ // Cavity: mid-grey on the open sphere (its overall curvature isn't detail), dark in the groove.+ cavGroove /= float(std::max(nGroove, 1));+ cavFlat /= float(std::max(nFlat, 1));+ std::printf(" cavity: groove %.3f, open surface %.3f\n", cavGroove, cavFlat);+ CHECK(std::abs(cavFlat - 0.5f) < 0.1f);+ CHECK(cavGroove < cavFlat - 0.15f);++ // Padding: texels beyond the islands got filled with their neighbours' values.+ size_t padded = 0, adjacent = 0, paddedOk = 0;+ for (size_t i = 0; i < r.coverage.size(); ++i) {+ if (r.coverage[i] != 2) continue;+ ++padded;+ const int x = int(i % size_t(r.width)), y = int(i / size_t(r.width));+ bool touches = false, ok = false;+ for (int dy = -1; dy <= 1; ++dy)+ for (int dx = -1; dx <= 1; ++dx) {+ const int nx = x + dx, ny = y + dy;+ if (nx < 0 || ny < 0 || nx >= r.width || ny >= r.height) continue;+ const size_t j = size_t(ny) * size_t(r.width) + size_t(nx);+ if (r.coverage[j] != 1) continue;+ touches = true;+ const float d = std::abs(r.displacement[i] - r.displacement[j]);+ ok = ok || (d < 0.02f && std::abs(int(r.normal[i * 3 + 2]) - int(r.normal[j * 3 + 2])) < 24);+ }+ adjacent += touches;+ paddedOk += touches && ok;+ }+ std::printf(" padding: %zu texels, %zu next to an island, %zu of those continue it\n", padded, adjacent, paddedOk);+ CHECK(padded > adjacent && adjacent > 0);+ CHECK(paddedOk > adjacent * 95 / 100); // padding next to an island continues it+ // No padding: nothing beyond the islands, and the empty texels are a flat normal.+ BakeSettings st0 = st;+ st0.padding = 0;+ st0.maps = bakeBit(BakeMap::Normal);+ BakeResult r0;+ CHECK(bakeMaps(low, {&high}, st0, r0, err));+ size_t c2 = 0;+ for (uint8_t c : r0.coverage) c2 += c == 2;+ CHECK(c2 == 0);+ bool flat = true;+ for (size_t i = 0; i < r0.coverage.size(); ++i)+ if (!r0.coverage[i]) flat = flat && r0.normal[i * 3] == 128 && r0.normal[i * 3 + 1] == 128 && r0.normal[i * 3 + 2] == 255;+ CHECK(flat);+ // A wider padding reaches further.+ BakeSettings st16 = st0;+ st16.padding = 16;+ BakeResult r16;+ CHECK(bakeMaps(low, {&high}, st16, r16, err));+ size_t p16 = 0;+ for (uint8_t c : r16.coverage) p16 += c == 2;+ CHECK(p16 > padded);++ // DirectX convention flips green only.+ BakeSettings dx = st0;+ dx.flipGreen = true;+ BakeResult rdx;+ CHECK(bakeMaps(low, {&high}, dx, rdx, err));+ bool flipped = true;+ for (size_t i = 0; i < rdx.coverage.size(); ++i)+ if (rdx.coverage[i] == 1)+ flipped = flipped && rdx.normal[i * 3] == r0.normal[i * 3] && std::abs(int(rdx.normal[i * 3 + 1]) - (255 - int(r0.normal[i * 3 + 1]))) <= 1;+ CHECK(flipped);++ // Files: the 16-bit PNG decodes to the float displacement (mid-grey = 0), the EXR holds it exactly.+ const std::string dir = tempPath("sf_bake_maps");+ std::filesystem::remove_all(dir);+ std::vector<std::string> written;+ CHECK(saveBakeMaps(r, dir, "Low", true, written, err));+ CHECK(written.size() == 6); // normal, object normal, displacement png + exr, ao, cavity+ int w = 0, h = 0, c = 0;+ std::vector<uint16_t> d16;+ CHECK(loadPng16(dir + "/Low_displacement.png", w, h, c, d16, err));+ std::vector<float> dexr;+ int ew = 0, eh = 0, ec = 0;+ CHECK(loadExr(dir + "/Low_displacement.exr", ew, eh, ec, dexr, err));+ CHECK(w == 256 && h == 256 && c == 1 && ew == 256 && ec == 1);+ double worst16 = 0, worstExr = 0;+ for (int y = 0; y < h; ++y)+ for (int x = 0; x < w; ++x) {+ const float want = r.displacement[size_t(h - 1 - y) * size_t(w) + size_t(x)]; // files are top-down+ const float got = (float(d16[size_t(y) * size_t(w) + size_t(x)]) / 65535.0f - 0.5f) * 2.0f * r.displacementScale;+ worst16 = std::max(worst16, double(std::abs(got - want)));+ worstExr = std::max(worstExr, double(std::abs(dexr[size_t(y) * size_t(w) + size_t(x)] - want)));+ }+ CHECK(worst16 < r.displacementScale * 1e-4);+ CHECK(worstExr == 0.0);+ Image nm;+ CHECK(Image::load(dir + "/Low_normal.png", nm, err));+ CHECK(nm.width == 256);+ std::filesystem::remove_all(dir);+}++TEST(bake_errors) {+ const Mesh high = highPoly(3);+ Mesh noUv = makeIcosphere(2);+ BakeSettings st;+ st.size = 128;+ BakeResult r;+ std::string err;+ CHECK(!bakeMaps(noUv, {&high}, st, r, err));+ CHECK(err.find("UVs") != std::string::npos);+ const Mesh low = lowPoly();+ CHECK(!bakeMaps(low, {}, st, r, err));+ CHECK(!bakeMaps(low, {&low}, st, r, err)); // a mesh can't be its own source+ st.maps = bakeBit(BakeMap::Color);+ CHECK(!bakeMaps(low, {&high}, st, r, err)); // nothing to transfer+ uint32_t maps = 0;+ CHECK(parseBakeMaps("normal, AO,disp", maps, err));+ CHECK(maps == (bakeBit(BakeMap::Normal) | bakeBit(BakeMap::AmbientOcclusion) | bakeBit(BakeMap::Displacement)));+ CHECK(parseBakeMaps("all", maps, err) && maps == 63u);+ CHECK(!parseBakeMaps("normal,specular", maps, err));+ // Cancelling stops it.+ st.maps = bakeBit(BakeMap::Normal);+ CHECK(!bakeMaps(low, {&high}, st, r, err, [](float) { return false; }));+ CHECK(err == "Cancelled");+}++TEST(bake_color_transfer) {+ Mesh high = highPoly(4);+ high.ensureColors();+ for (size_t v = 0; v < high.vertexCount(); ++v) high.colors[v] = high.positions[v].x > 0 ? glm::vec3(1, 0, 0) : glm::vec3(0, 0, 1);+ const Mesh low = lowPoly();+ BakeSettings st;+ st.size = 128;+ st.maps = bakeBit(BakeMap::Color);+ BakeResult r;+ std::string err;+ CHECK(bakeMaps(low, {&high}, st, r, err));+ const TexelMap tm = texelMap(low, 128);+ int good = 0, total = 0;+ for (size_t i = 0; i < tm.tri.size(); ++i) {+ if (tm.tri[i] < 0) continue;+ const glm::vec3 p = lowPointOf(low, uint32_t(tm.tri[i]), tm.bary[i]);+ if (std::abs(p.x) < 0.2f) continue;+ ++total;+ const bool red = r.color[i * 3] > 200 && r.color[i * 3 + 2] < 50, blue = r.color[i * 3 + 2] > 200 && r.color[i * 3] < 50;+ good += p.x > 0 ? red : blue;+ }+ CHECK(total > 100 && good > total * 95 / 100);+}++TEST(bake_command) {+ Document doc = makeDoc(highPoly(4));+ doc.subtools[0].name = "High";+ doc.addSubtool(lowPoly(), "Low");+ CommandRegistry reg;+ const std::string dir = tempPath("sf_bake_cmd");+ std::filesystem::remove_all(dir);+ std::shared_ptr<const BakeResult> seen;+ setBakeListener([&](const Document&, std::shared_ptr<const BakeResult> r) { seen = r; });+ CommandResult res = reg.execute(doc, "bake", {{"source", std::string("all")}, {"maps", std::string("normal,ao,displacement")},+ {"size", 256.0}, {"out", dir}, {"ao_rays", 8.0}});+ std::printf(" %s\n", res.message.c_str());+ CHECK(res.ok);+ CHECK(res.message.find("mid-grey = 0") != std::string::npos);+ CHECK(seen && seen->width == 256 && seen->has(BakeMap::AmbientOcclusion));+ for (const char* f : {"Low_normal.png", "Low_ao.png", "Low_displacement.png", "Low_displacement.exr"})+ CHECK(std::filesystem::exists(std::filesystem::path(dir) / f));+ res = reg.execute(doc, "bake", {{"source", std::string("High")}, {"size", std::string("1k")}, {"out", dir}, {"name", std::string("x")},+ {"front", 0.05}, {"rear", std::string("0.05")}, {"samples", 1.0}});+ CHECK(res.ok);+ CHECK(std::filesystem::exists(std::filesystem::path(dir) / "x_normal.png"));+ CHECK(!reg.execute(doc, "bake", {{"source", std::string("Low")}, {"out", dir}}).ok); // the active one+ CHECK(!reg.execute(doc, "bake", {{"source", std::string("Nope")}, {"out", dir}}).ok);+ CHECK(!reg.execute(doc, "bake", {{"size", 300.0}, {"out", dir}}).ok);+ CHECK(!reg.execute(doc, "bake", {{"green", std::string("purple")}, {"out", dir}}).ok);+ doc.subtools[0].visible = false; // nothing visible to bake from+ CHECK(!reg.execute(doc, "bake", {{"out", dir}}).ok);+ setBakeListener({});+ std::filesystem::remove_all(dir);+}++// The brief's timing: 4K maps from a source of more than a million triangles.+TEST(bake_perf_4k_from_1m_triangles) {+ const Mesh high = highPoly(8); // 1.31M triangles+ const Mesh low = lowPoly();+ BakeSettings st;+ st.size = 4096;+ st.maps = bakeBit(BakeMap::Normal) | bakeBit(BakeMap::Displacement);+ BakeResult r;+ std::string err;+ CHECK(bakeMaps(low, {&high}, st, r, err));+ std::printf(" 4K normal + displacement, 2x2 samples, from %zu triangles: %.2f s (BVH %.2f s), %zu island texels\n",+ r.sourceTriangles, r.seconds, r.bvhSeconds, r.islandTexels);+ CHECK(r.sourceTriangles > 1000000);+ CHECK(r.seconds < 60.0);+}diff --git a/third_party/mikktspace/SOURCE.txt b/third_party/mikktspace/SOURCE.txtnew file mode 100644index 00000000..748af2fb--- /dev/null+++ b/third_party/mikktspace/SOURCE.txt@@ -0,0 +1 @@+mikktspace.c, mikktspace.h from https://github.com/mmikk/MikkTSpace commit 3e895b49d05ea07e4c2133156cfa94369e19e409 (zlib licence; the licence text is at the top of both files)diff --git a/third_party/mikktspace/mikktspace.c b/third_party/mikktspace/mikktspace.cnew file mode 100644index 00000000..0342ae01--- /dev/null+++ b/third_party/mikktspace/mikktspace.c@@ -0,0 +1,1899 @@+/** \file mikktspace/mikktspace.c+ * \ingroup mikktspace+ */+/**+ * Copyright (C) 2011 by Morten S. Mikkelsen+ *+ * This software is provided 'as-is', without any express or implied+ * warranty. In no event will the authors be held liable for any damages+ * arising from the use of this software.+ *+ * Permission is granted to anyone to use this software for any purpose,+ * including commercial applications, and to alter it and redistribute it+ * freely, subject to the following restrictions:+ *+ * 1. The origin of this software must not be misrepresented; you must not+ * claim that you wrote the original software. If you use this software+ * in a product, an acknowledgment in the product documentation would be+ * appreciated but is not required.+ * 2. Altered source versions must be plainly marked as such, and must not be+ * misrepresented as being the original software.+ * 3. This notice may not be removed or altered from any source distribution.+ */++#include <assert.h>+#include <stdio.h>+#include <math.h>+#include <string.h>+#include <float.h>+#include <stdlib.h>++#include "mikktspace.h"++#define TFALSE 0+#define TTRUE 1++#ifndef M_PI+#define M_PI 3.1415926535897932384626433832795+#endif++#define INTERNAL_RND_SORT_SEED 39871946++// internal structure+typedef struct {+ float x, y, z;+} SVec3;++static tbool veq( const SVec3 v1, const SVec3 v2 )+{+ return (v1.x == v2.x) && (v1.y == v2.y) && (v1.z == v2.z);+}++static SVec3 vadd( const SVec3 v1, const SVec3 v2 )+{+ SVec3 vRes;++ vRes.x = v1.x + v2.x;+ vRes.y = v1.y + v2.y;+ vRes.z = v1.z + v2.z;++ return vRes;+}+++static SVec3 vsub( const SVec3 v1, const SVec3 v2 )+{+ SVec3 vRes;++ vRes.x = v1.x - v2.x;+ vRes.y = v1.y - v2.y;+ vRes.z = v1.z - v2.z;++ return vRes;+}++static SVec3 vscale(const float fS, const SVec3 v)+{+ SVec3 vRes;++ vRes.x = fS * v.x;+ vRes.y = fS * v.y;+ vRes.z = fS * v.z;++ return vRes;+}++static float LengthSquared( const SVec3 v )+{+ return v.x*v.x + v.y*v.y + v.z*v.z;+}++static float Length( const SVec3 v )+{+ return sqrtf(LengthSquared(v));+}++static SVec3 Normalize( const SVec3 v )+{+ return vscale(1 / Length(v), v);+}++static float vdot( const SVec3 v1, const SVec3 v2)+{+ return v1.x*v2.x + v1.y*v2.y + v1.z*v2.z;+}+++static tbool NotZero(const float fX)+{+ // could possibly use FLT_EPSILON instead+ return fabsf(fX) > FLT_MIN;+}++static tbool VNotZero(const SVec3 v)+{+ // might change this to an epsilon based test+ return NotZero(v.x) || NotZero(v.y) || NotZero(v.z);+}++++typedef struct {+ int iNrFaces;+ int * pTriMembers;+} SSubGroup;++typedef struct {+ int iNrFaces;+ int * pFaceIndices;+ int iVertexRepresentitive;+ tbool bOrientPreservering;+} SGroup;++//+#define MARK_DEGENERATE 1+#define QUAD_ONE_DEGEN_TRI 2+#define GROUP_WITH_ANY 4+#define ORIENT_PRESERVING 8++++typedef struct {+ int FaceNeighbors[3];+ SGroup * AssignedGroup[3];++ // normalized first order face derivatives+ SVec3 vOs, vOt;+ float fMagS, fMagT; // original magnitudes++ // determines if the current and the next triangle are a quad.+ int iOrgFaceNumber;+ int iFlag, iTSpacesOffs;+ unsigned char vert_num[4];+} STriInfo;++typedef struct {+ SVec3 vOs;+ float fMagS;+ SVec3 vOt;+ float fMagT;+ int iCounter; // this is to average back into quads.+ tbool bOrient;+} STSpace;++static int GenerateInitialVerticesIndexList(STriInfo pTriInfos[], int piTriList_out[], const SMikkTSpaceContext * pContext, const int iNrTrianglesIn);+static void GenerateSharedVerticesIndexList(int piTriList_in_and_out[], const SMikkTSpaceContext * pContext, const int iNrTrianglesIn);+static void InitTriInfo(STriInfo pTriInfos[], const int piTriListIn[], const SMikkTSpaceContext * pContext, const int iNrTrianglesIn);+static int Build4RuleGroups(STriInfo pTriInfos[], SGroup pGroups[], int piGroupTrianglesBuffer[], const int piTriListIn[], const int iNrTrianglesIn);+static tbool GenerateTSpaces(STSpace psTspace[], const STriInfo pTriInfos[], const SGroup pGroups[],+ const int iNrActiveGroups, const int piTriListIn[], const float fThresCos,+ const SMikkTSpaceContext * pContext);++static int MakeIndex(const int iFace, const int iVert)+{+ assert(iVert>=0 && iVert<4 && iFace>=0);+ return (iFace<<2) | (iVert&0x3);+}++static void IndexToData(int * piFace, int * piVert, const int iIndexIn)+{+ piVert[0] = iIndexIn&0x3;+ piFace[0] = iIndexIn>>2;+}++static STSpace AvgTSpace(const STSpace * pTS0, const STSpace * pTS1)+{+ STSpace ts_res;++ // this if is important. Due to floating point precision+ // averaging when ts0==ts1 will cause a slight difference+ // which results in tangent space splits later on+ if (pTS0->fMagS==pTS1->fMagS && pTS0->fMagT==pTS1->fMagT &&+ veq(pTS0->vOs,pTS1->vOs) && veq(pTS0->vOt, pTS1->vOt))+ {+ ts_res.fMagS = pTS0->fMagS;+ ts_res.fMagT = pTS0->fMagT;+ ts_res.vOs = pTS0->vOs;+ ts_res.vOt = pTS0->vOt;+ }+ else+ {+ ts_res.fMagS = 0.5f*(pTS0->fMagS+pTS1->fMagS);+ ts_res.fMagT = 0.5f*(pTS0->fMagT+pTS1->fMagT);+ ts_res.vOs = vadd(pTS0->vOs,pTS1->vOs);+ ts_res.vOt = vadd(pTS0->vOt,pTS1->vOt);+ if ( VNotZero(ts_res.vOs) ) ts_res.vOs = Normalize(ts_res.vOs);+ if ( VNotZero(ts_res.vOt) ) ts_res.vOt = Normalize(ts_res.vOt);+ }++ return ts_res;+}++++static SVec3 GetPosition(const SMikkTSpaceContext * pContext, const int index);+static SVec3 GetNormal(const SMikkTSpaceContext * pContext, const int index);+static SVec3 GetTexCoord(const SMikkTSpaceContext * pContext, const int index);+++// degen triangles+static void DegenPrologue(STriInfo pTriInfos[], int piTriList_out[], const int iNrTrianglesIn, const int iTotTris);+static void DegenEpilogue(STSpace psTspace[], STriInfo pTriInfos[], int piTriListIn[], const SMikkTSpaceContext * pContext, const int iNrTrianglesIn, const int iTotTris);+++tbool genTangSpaceDefault(const SMikkTSpaceContext * pContext)+{+ return genTangSpace(pContext, 180.0f);+}++tbool genTangSpace(const SMikkTSpaceContext * pContext, const float fAngularThreshold)+{+ // count nr_triangles+ int * piTriListIn = NULL, * piGroupTrianglesBuffer = NULL;+ STriInfo * pTriInfos = NULL;+ SGroup * pGroups = NULL;+ STSpace * psTspace = NULL;+ int iNrTrianglesIn = 0, f=0, t=0, i=0;+ int iNrTSPaces = 0, iTotTris = 0, iDegenTriangles = 0, iNrMaxGroups = 0;+ int iNrActiveGroups = 0, index = 0;+ const int iNrFaces = pContext->m_pInterface->m_getNumFaces(pContext);+ tbool bRes = TFALSE;+ const float fThresCos = (float) cos((fAngularThreshold*(float)M_PI)/180.0f);++ // verify all call-backs have been set+ if ( pContext->m_pInterface->m_getNumFaces==NULL ||+ pContext->m_pInterface->m_getNumVerticesOfFace==NULL ||+ pContext->m_pInterface->m_getPosition==NULL ||+ pContext->m_pInterface->m_getNormal==NULL ||+ pContext->m_pInterface->m_getTexCoord==NULL )+ return TFALSE;++ // count triangles on supported faces+ for (f=0; f<iNrFaces; f++)+ {+ const int verts = pContext->m_pInterface->m_getNumVerticesOfFace(pContext, f);+ if (verts==3) ++iNrTrianglesIn;+ else if (verts==4) iNrTrianglesIn += 2;+ }+ if (iNrTrianglesIn<=0) return TFALSE;++ // allocate memory for an index list+ piTriListIn = (int *) malloc(sizeof(int)*3*iNrTrianglesIn);+ pTriInfos = (STriInfo *) malloc(sizeof(STriInfo)*iNrTrianglesIn);+ if (piTriListIn==NULL || pTriInfos==NULL)+ {+ if (piTriListIn!=NULL) free(piTriListIn);+ if (pTriInfos!=NULL) free(pTriInfos);+ return TFALSE;+ }++ // make an initial triangle --> face index list+ iNrTSPaces = GenerateInitialVerticesIndexList(pTriInfos, piTriListIn, pContext, iNrTrianglesIn);++ // make a welded index list of identical positions and attributes (pos, norm, texc)+ //printf("gen welded index list begin\n");+ GenerateSharedVerticesIndexList(piTriListIn, pContext, iNrTrianglesIn);+ //printf("gen welded index list end\n");++ // Mark all degenerate triangles+ iTotTris = iNrTrianglesIn;+ iDegenTriangles = 0;+ for (t=0; t<iTotTris; t++)+ {+ const int i0 = piTriListIn[t*3+0];+ const int i1 = piTriListIn[t*3+1];+ const int i2 = piTriListIn[t*3+2];+ const SVec3 p0 = GetPosition(pContext, i0);+ const SVec3 p1 = GetPosition(pContext, i1);+ const SVec3 p2 = GetPosition(pContext, i2);+ if (veq(p0,p1) || veq(p0,p2) || veq(p1,p2)) // degenerate+ {+ pTriInfos[t].iFlag |= MARK_DEGENERATE;+ ++iDegenTriangles;+ }+ }+ iNrTrianglesIn = iTotTris - iDegenTriangles;++ // mark all triangle pairs that belong to a quad with only one+ // good triangle. These need special treatment in DegenEpilogue().+ // Additionally, move all good triangles to the start of+ // pTriInfos[] and piTriListIn[] without changing order and+ // put the degenerate triangles last.+ DegenPrologue(pTriInfos, piTriListIn, iNrTrianglesIn, iTotTris);+++ // evaluate triangle level attributes and neighbor list+ //printf("gen neighbors list begin\n");+ InitTriInfo(pTriInfos, piTriListIn, pContext, iNrTrianglesIn);+ //printf("gen neighbors list end\n");+++ // based on the 4 rules, identify groups based on connectivity+ iNrMaxGroups = iNrTrianglesIn*3;+ pGroups = (SGroup *) malloc(sizeof(SGroup)*iNrMaxGroups);+ piGroupTrianglesBuffer = (int *) malloc(sizeof(int)*iNrTrianglesIn*3);+ if (pGroups==NULL || piGroupTrianglesBuffer==NULL)+ {+ if (pGroups!=NULL) free(pGroups);+ if (piGroupTrianglesBuffer!=NULL) free(piGroupTrianglesBuffer);+ free(piTriListIn);+ free(pTriInfos);+ return TFALSE;+ }+ //printf("gen 4rule groups begin\n");+ iNrActiveGroups =+ Build4RuleGroups(pTriInfos, pGroups, piGroupTrianglesBuffer, piTriListIn, iNrTrianglesIn);+ //printf("gen 4rule groups end\n");++ //++ psTspace = (STSpace *) malloc(sizeof(STSpace)*iNrTSPaces);+ if (psTspace==NULL)+ {+ free(piTriListIn);+ free(pTriInfos);+ free(pGroups);+ free(piGroupTrianglesBuffer);+ return TFALSE;+ }+ memset(psTspace, 0, sizeof(STSpace)*iNrTSPaces);+ for (t=0; t<iNrTSPaces; t++)+ {+ psTspace[t].vOs.x=1.0f; psTspace[t].vOs.y=0.0f; psTspace[t].vOs.z=0.0f; psTspace[t].fMagS = 1.0f;+ psTspace[t].vOt.x=0.0f; psTspace[t].vOt.y=1.0f; psTspace[t].vOt.z=0.0f; psTspace[t].fMagT = 1.0f;+ }++ // make tspaces, each group is split up into subgroups if necessary+ // based on fAngularThreshold. Finally a tangent space is made for+ // every resulting subgroup+ //printf("gen tspaces begin\n");+ bRes = GenerateTSpaces(psTspace, pTriInfos, pGroups, iNrActiveGroups, piTriListIn, fThresCos, pContext);+ //printf("gen tspaces end\n");++ // clean up+ free(pGroups);+ free(piGroupTrianglesBuffer);++ if (!bRes) // if an allocation in GenerateTSpaces() failed+ {+ // clean up and return false+ free(pTriInfos); free(piTriListIn); free(psTspace);+ return TFALSE;+ }+++ // degenerate quads with one good triangle will be fixed by copying a space from+ // the good triangle to the coinciding vertex.+ // all other degenerate triangles will just copy a space from any good triangle+ // with the same welded index in piTriListIn[].+ DegenEpilogue(psTspace, pTriInfos, piTriListIn, pContext, iNrTrianglesIn, iTotTris);++ free(pTriInfos); free(piTriListIn);++ index = 0;+ for (f=0; f<iNrFaces; f++)+ {+ const int verts = pContext->m_pInterface->m_getNumVerticesOfFace(pContext, f);+ if (verts!=3 && verts!=4) continue;+++ // I've decided to let degenerate triangles and group-with-anythings+ // vary between left/right hand coordinate systems at the vertices.+ // All healthy triangles on the other hand are built to always be either or.++ /*// force the coordinate system orientation to be uniform for every face.+ // (this is already the case for good triangles but not for+ // degenerate ones and those with bGroupWithAnything==true)+ bool bOrient = psTspace[index].bOrient;+ if (psTspace[index].iCounter == 0) // tspace was not derived from a group+ {+ // look for a space created in GenerateTSpaces() by iCounter>0+ bool bNotFound = true;+ int i=1;+ while (i<verts && bNotFound)+ {+ if (psTspace[index+i].iCounter > 0) bNotFound=false;+ else ++i;+ }+ if (!bNotFound) bOrient = psTspace[index+i].bOrient;+ }*/++ // set data+ for (i=0; i<verts; i++)+ {+ const STSpace * pTSpace = &psTspace[index];+ float tang[] = {pTSpace->vOs.x, pTSpace->vOs.y, pTSpace->vOs.z};+ float bitang[] = {pTSpace->vOt.x, pTSpace->vOt.y, pTSpace->vOt.z};+ if (pContext->m_pInterface->m_setTSpace!=NULL)+ pContext->m_pInterface->m_setTSpace(pContext, tang, bitang, pTSpace->fMagS, pTSpace->fMagT, pTSpace->bOrient, f, i);+ if (pContext->m_pInterface->m_setTSpaceBasic!=NULL)+ pContext->m_pInterface->m_setTSpaceBasic(pContext, tang, pTSpace->bOrient==TTRUE ? 1.0f : (-1.0f), f, i);++ ++index;+ }+ }++ free(psTspace);+++ return TTRUE;+}++///////////////////////////////////////////////////////////////////////////////////////////////////////////////////++typedef struct {+ float vert[3];+ int index;+} STmpVert;++static const int g_iCells = 2048;++#ifdef _MSC_VER+# define NOINLINE __declspec(noinline)+#else+# define NOINLINE __attribute__ ((noinline))+#endif++// it is IMPORTANT that this function is called to evaluate the hash since+// inlining could potentially reorder instructions and generate different+// results for the same effective input value fVal.+static NOINLINE int FindGridCell(const float fMin, const float fMax, const float fVal)+{+ const float fIndex = g_iCells * ((fVal-fMin)/(fMax-fMin));+ const int iIndex = (int)fIndex;+ return iIndex < g_iCells ? (iIndex >= 0 ? iIndex : 0) : (g_iCells - 1);+}++static void MergeVertsFast(int piTriList_in_and_out[], STmpVert pTmpVert[], const SMikkTSpaceContext * pContext, const int iL_in, const int iR_in);+static void MergeVertsSlow(int piTriList_in_and_out[], const SMikkTSpaceContext * pContext, const int pTable[], const int iEntries);+static void GenerateSharedVerticesIndexListSlow(int piTriList_in_and_out[], const SMikkTSpaceContext * pContext, const int iNrTrianglesIn);++static void GenerateSharedVerticesIndexList(int piTriList_in_and_out[], const SMikkTSpaceContext * pContext, const int iNrTrianglesIn)+{++ // Generate bounding box+ int * piHashTable=NULL, * piHashCount=NULL, * piHashOffsets=NULL, * piHashCount2=NULL;+ STmpVert * pTmpVert = NULL;+ int i=0, iChannel=0, k=0, e=0;+ int iMaxCount=0;+ SVec3 vMin = GetPosition(pContext, 0), vMax = vMin, vDim;+ float fMin, fMax;+ for (i=1; i<(iNrTrianglesIn*3); i++)+ {+ const int index = piTriList_in_and_out[i];++ const SVec3 vP = GetPosition(pContext, index);+ if (vMin.x > vP.x) vMin.x = vP.x;+ else if (vMax.x < vP.x) vMax.x = vP.x;+ if (vMin.y > vP.y) vMin.y = vP.y;+ else if (vMax.y < vP.y) vMax.y = vP.y;+ if (vMin.z > vP.z) vMin.z = vP.z;+ else if (vMax.z < vP.z) vMax.z = vP.z;+ }++ vDim = vsub(vMax,vMin);+ iChannel = 0;+ fMin = vMin.x; fMax=vMax.x;+ if (vDim.y>vDim.x && vDim.y>vDim.z)+ {+ iChannel=1;+ fMin = vMin.y;+ fMax = vMax.y;+ }+ else if (vDim.z>vDim.x)+ {+ iChannel=2;+ fMin = vMin.z;+ fMax = vMax.z;+ }++ // make allocations+ piHashTable = (int *) malloc(sizeof(int)*iNrTrianglesIn*3);+ piHashCount = (int *) malloc(sizeof(int)*g_iCells);+ piHashOffsets = (int *) malloc(sizeof(int)*g_iCells);+ piHashCount2 = (int *) malloc(sizeof(int)*g_iCells);++ if (piHashTable==NULL || piHashCount==NULL || piHashOffsets==NULL || piHashCount2==NULL)+ {+ if (piHashTable!=NULL) free(piHashTable);+ if (piHashCount!=NULL) free(piHashCount);+ if (piHashOffsets!=NULL) free(piHashOffsets);+ if (piHashCount2!=NULL) free(piHashCount2);+ GenerateSharedVerticesIndexListSlow(piTriList_in_and_out, pContext, iNrTrianglesIn);+ return;+ }+ memset(piHashCount, 0, sizeof(int)*g_iCells);+ memset(piHashCount2, 0, sizeof(int)*g_iCells);++ // count amount of elements in each cell unit+ for (i=0; i<(iNrTrianglesIn*3); i++)+ {+ const int index = piTriList_in_and_out[i];+ const SVec3 vP = GetPosition(pContext, index);+ const float fVal = iChannel==0 ? vP.x : (iChannel==1 ? vP.y : vP.z);+ const int iCell = FindGridCell(fMin, fMax, fVal);+ ++piHashCount[iCell];+ }++ // evaluate start index of each cell.+ piHashOffsets[0]=0;+ for (k=1; k<g_iCells; k++)+ piHashOffsets[k]=piHashOffsets[k-1]+piHashCount[k-1];++ // insert vertices+ for (i=0; i<(iNrTrianglesIn*3); i++)+ {+ const int index = piTriList_in_and_out[i];+ const SVec3 vP = GetPosition(pContext, index);+ const float fVal = iChannel==0 ? vP.x : (iChannel==1 ? vP.y : vP.z);+ const int iCell = FindGridCell(fMin, fMax, fVal);+ int * pTable = NULL;++ assert(piHashCount2[iCell]<piHashCount[iCell]);+ pTable = &piHashTable[piHashOffsets[iCell]];+ pTable[piHashCount2[iCell]] = i; // vertex i has been inserted.+ ++piHashCount2[iCell];+ }+ for (k=0; k<g_iCells; k++)+ assert(piHashCount2[k] == piHashCount[k]); // verify the count+ free(piHashCount2);++ // find maximum amount of entries in any hash entry+ iMaxCount = piHashCount[0];+ for (k=1; k<g_iCells; k++)+ if (iMaxCount<piHashCount[k])+ iMaxCount=piHashCount[k];+ pTmpVert = (STmpVert *) malloc(sizeof(STmpVert)*iMaxCount);+++ // complete the merge+ for (k=0; k<g_iCells; k++)+ {+ // extract table of cell k and amount of entries in it+ int * pTable = &piHashTable[piHashOffsets[k]];+ const int iEntries = piHashCount[k];+ if (iEntries < 2) continue;++ if (pTmpVert!=NULL)+ {+ for (e=0; e<iEntries; e++)+ {+ int i = pTable[e];+ const SVec3 vP = GetPosition(pContext, piTriList_in_and_out[i]);+ pTmpVert[e].vert[0] = vP.x; pTmpVert[e].vert[1] = vP.y;+ pTmpVert[e].vert[2] = vP.z; pTmpVert[e].index = i;+ }+ MergeVertsFast(piTriList_in_and_out, pTmpVert, pContext, 0, iEntries-1);+ }+ else+ MergeVertsSlow(piTriList_in_and_out, pContext, pTable, iEntries);+ }++ if (pTmpVert!=NULL) { free(pTmpVert); }+ free(piHashTable);+ free(piHashCount);+ free(piHashOffsets);+}++static void MergeVertsFast(int piTriList_in_and_out[], STmpVert pTmpVert[], const SMikkTSpaceContext * pContext, const int iL_in, const int iR_in)+{+ // make bbox+ int c=0, l=0, channel=0;+ float fvMin[3], fvMax[3];+ float dx=0, dy=0, dz=0, fSep=0;+ for (c=0; c<3; c++)+ { fvMin[c]=pTmpVert[iL_in].vert[c]; fvMax[c]=fvMin[c]; }+ for (l=(iL_in+1); l<=iR_in; l++) {+ for (c=0; c<3; c++) {+ if (fvMin[c]>pTmpVert[l].vert[c]) fvMin[c]=pTmpVert[l].vert[c];+ if (fvMax[c]<pTmpVert[l].vert[c]) fvMax[c]=pTmpVert[l].vert[c];+ }+ }++ dx = fvMax[0]-fvMin[0];+ dy = fvMax[1]-fvMin[1];+ dz = fvMax[2]-fvMin[2];++ channel = 0;+ if (dy>dx && dy>dz) channel=1;+ else if (dz>dx) channel=2;++ fSep = 0.5f*(fvMax[channel]+fvMin[channel]);++ // stop if all vertices are NaNs+ if (!isfinite(fSep))+ return;++ // terminate recursion when the separation/average value+ // is no longer strictly between fMin and fMax values.+ if (fSep>=fvMax[channel] || fSep<=fvMin[channel])+ {+ // complete the weld+ for (l=iL_in; l<=iR_in; l++)+ {+ int i = pTmpVert[l].index;+ const int index = piTriList_in_and_out[i];+ const SVec3 vP = GetPosition(pContext, index);+ const SVec3 vN = GetNormal(pContext, index);+ const SVec3 vT = GetTexCoord(pContext, index);++ tbool bNotFound = TTRUE;+ int l2=iL_in, i2rec=-1;+ while (l2<l && bNotFound)+ {+ const int i2 = pTmpVert[l2].index;+ const int index2 = piTriList_in_and_out[i2];+ const SVec3 vP2 = GetPosition(pContext, index2);+ const SVec3 vN2 = GetNormal(pContext, index2);+ const SVec3 vT2 = GetTexCoord(pContext, index2);+ i2rec=i2;++ //if (vP==vP2 && vN==vN2 && vT==vT2)+ if (vP.x==vP2.x && vP.y==vP2.y && vP.z==vP2.z &&+ vN.x==vN2.x && vN.y==vN2.y && vN.z==vN2.z &&+ vT.x==vT2.x && vT.y==vT2.y && vT.z==vT2.z)+ bNotFound = TFALSE;+ else+ ++l2;+ }++ // merge if previously found+ if (!bNotFound)+ piTriList_in_and_out[i] = piTriList_in_and_out[i2rec];+ }+ }+ else+ {+ int iL=iL_in, iR=iR_in;+ assert((iR_in-iL_in)>0); // at least 2 entries++ // separate (by fSep) all points between iL_in and iR_in in pTmpVert[]+ while (iL < iR)+ {+ tbool bReadyLeftSwap = TFALSE, bReadyRightSwap = TFALSE;+ while ((!bReadyLeftSwap) && iL<iR)+ {+ assert(iL>=iL_in && iL<=iR_in);+ bReadyLeftSwap = !(pTmpVert[iL].vert[channel]<fSep);+ if (!bReadyLeftSwap) ++iL;+ }+ while ((!bReadyRightSwap) && iL<iR)+ {+ assert(iR>=iL_in && iR<=iR_in);+ bReadyRightSwap = pTmpVert[iR].vert[channel]<fSep;+ if (!bReadyRightSwap) --iR;+ }+ assert( (iL<iR) || !(bReadyLeftSwap && bReadyRightSwap) );++ if (bReadyLeftSwap && bReadyRightSwap)+ {+ const STmpVert sTmp = pTmpVert[iL];+ assert(iL<iR);+ pTmpVert[iL] = pTmpVert[iR];+ pTmpVert[iR] = sTmp;+ ++iL; --iR;+ }+ }++ assert(iL==(iR+1) || (iL==iR));+ if (iL==iR)+ {+ const tbool bReadyRightSwap = pTmpVert[iR].vert[channel]<fSep;+ if (bReadyRightSwap) ++iL;+ else --iR;+ }++ // only need to weld when there is more than 1 instance of the (x,y,z)+ if (iL_in < iR)+ MergeVertsFast(piTriList_in_and_out, pTmpVert, pContext, iL_in, iR); // weld all left of fSep+ if (iL < iR_in)+ MergeVertsFast(piTriList_in_and_out, pTmpVert, pContext, iL, iR_in); // weld all right of (or equal to) fSep+ }+}++static void MergeVertsSlow(int piTriList_in_and_out[], const SMikkTSpaceContext * pContext, const int pTable[], const int iEntries)+{+ // this can be optimized further using a tree structure or more hashing.+ int e=0;+ for (e=0; e<iEntries; e++)+ {+ int i = pTable[e];+ const int index = piTriList_in_and_out[i];+ const SVec3 vP = GetPosition(pContext, index);+ const SVec3 vN = GetNormal(pContext, index);+ const SVec3 vT = GetTexCoord(pContext, index);++ tbool bNotFound = TTRUE;+ int e2=0, i2rec=-1;+ while (e2<e && bNotFound)+ {+ const int i2 = pTable[e2];+ const int index2 = piTriList_in_and_out[i2];+ const SVec3 vP2 = GetPosition(pContext, index2);+ const SVec3 vN2 = GetNormal(pContext, index2);+ const SVec3 vT2 = GetTexCoord(pContext, index2);+ i2rec = i2;++ if (veq(vP,vP2) && veq(vN,vN2) && veq(vT,vT2))+ bNotFound = TFALSE;+ else+ ++e2;+ }++ // merge if previously found+ if (!bNotFound)+ piTriList_in_and_out[i] = piTriList_in_and_out[i2rec];+ }+}++static void GenerateSharedVerticesIndexListSlow(int piTriList_in_and_out[], const SMikkTSpaceContext * pContext, const int iNrTrianglesIn)+{+ int iNumUniqueVerts = 0, t=0, i=0;+ for (t=0; t<iNrTrianglesIn; t++)+ {+ for (i=0; i<3; i++)+ {+ const int offs = t*3 + i;+ const int index = piTriList_in_and_out[offs];++ const SVec3 vP = GetPosition(pContext, index);+ const SVec3 vN = GetNormal(pContext, index);+ const SVec3 vT = GetTexCoord(pContext, index);++ tbool bFound = TFALSE;+ int t2=0, index2rec=-1;+ while (!bFound && t2<=t)+ {+ int j=0;+ while (!bFound && j<3)+ {+ const int index2 = piTriList_in_and_out[t2*3 + j];+ const SVec3 vP2 = GetPosition(pContext, index2);+ const SVec3 vN2 = GetNormal(pContext, index2);+ const SVec3 vT2 = GetTexCoord(pContext, index2);++ if (veq(vP,vP2) && veq(vN,vN2) && veq(vT,vT2))+ bFound = TTRUE;+ else+ ++j;+ }+ if (!bFound) ++t2;+ }++ assert(bFound);+ // if we found our own+ if (index2rec == index) { ++iNumUniqueVerts; }++ piTriList_in_and_out[offs] = index2rec;+ }+ }+}++static int GenerateInitialVerticesIndexList(STriInfo pTriInfos[], int piTriList_out[], const SMikkTSpaceContext * pContext, const int iNrTrianglesIn)+{+ int iTSpacesOffs = 0, f=0, t=0;+ int iDstTriIndex = 0;+ for (f=0; f<pContext->m_pInterface->m_getNumFaces(pContext); f++)+ {+ const int verts = pContext->m_pInterface->m_getNumVerticesOfFace(pContext, f);+ if (verts!=3 && verts!=4) continue;++ pTriInfos[iDstTriIndex].iOrgFaceNumber = f;+ pTriInfos[iDstTriIndex].iTSpacesOffs = iTSpacesOffs;++ if (verts==3)+ {+ unsigned char * pVerts = pTriInfos[iDstTriIndex].vert_num;+ pVerts[0]=0; pVerts[1]=1; pVerts[2]=2;+ piTriList_out[iDstTriIndex*3+0] = MakeIndex(f, 0);+ piTriList_out[iDstTriIndex*3+1] = MakeIndex(f, 1);+ piTriList_out[iDstTriIndex*3+2] = MakeIndex(f, 2);+ ++iDstTriIndex; // next+ }+ else+ {+ {+ pTriInfos[iDstTriIndex+1].iOrgFaceNumber = f;+ pTriInfos[iDstTriIndex+1].iTSpacesOffs = iTSpacesOffs;+ }++ {+ // need an order independent way to evaluate+ // tspace on quads. This is done by splitting+ // along the shortest diagonal.+ const int i0 = MakeIndex(f, 0);+ const int i1 = MakeIndex(f, 1);+ const int i2 = MakeIndex(f, 2);+ const int i3 = MakeIndex(f, 3);+ const SVec3 T0 = GetTexCoord(pContext, i0);+ const SVec3 T1 = GetTexCoord(pContext, i1);+ const SVec3 T2 = GetTexCoord(pContext, i2);+ const SVec3 T3 = GetTexCoord(pContext, i3);+ const float distSQ_02 = LengthSquared(vsub(T2,T0));+ const float distSQ_13 = LengthSquared(vsub(T3,T1));+ tbool bQuadDiagIs_02;+ if (distSQ_02<distSQ_13)+ bQuadDiagIs_02 = TTRUE;+ else if (distSQ_13<distSQ_02)+ bQuadDiagIs_02 = TFALSE;+ else+ {+ const SVec3 P0 = GetPosition(pContext, i0);+ const SVec3 P1 = GetPosition(pContext, i1);+ const SVec3 P2 = GetPosition(pContext, i2);+ const SVec3 P3 = GetPosition(pContext, i3);+ const float distSQ_02 = LengthSquared(vsub(P2,P0));+ const float distSQ_13 = LengthSquared(vsub(P3,P1));++ bQuadDiagIs_02 = distSQ_13<distSQ_02 ? TFALSE : TTRUE;+ }++ if (bQuadDiagIs_02)+ {+ {+ unsigned char * pVerts_A = pTriInfos[iDstTriIndex].vert_num;+ pVerts_A[0]=0; pVerts_A[1]=1; pVerts_A[2]=2;+ }+ piTriList_out[iDstTriIndex*3+0] = i0;+ piTriList_out[iDstTriIndex*3+1] = i1;+ piTriList_out[iDstTriIndex*3+2] = i2;+ ++iDstTriIndex; // next+ {+ unsigned char * pVerts_B = pTriInfos[iDstTriIndex].vert_num;+ pVerts_B[0]=0; pVerts_B[1]=2; pVerts_B[2]=3;+ }+ piTriList_out[iDstTriIndex*3+0] = i0;+ piTriList_out[iDstTriIndex*3+1] = i2;+ piTriList_out[iDstTriIndex*3+2] = i3;+ ++iDstTriIndex; // next+ }+ else+ {+ {+ unsigned char * pVerts_A = pTriInfos[iDstTriIndex].vert_num;+ pVerts_A[0]=0; pVerts_A[1]=1; pVerts_A[2]=3;+ }+ piTriList_out[iDstTriIndex*3+0] = i0;+ piTriList_out[iDstTriIndex*3+1] = i1;+ piTriList_out[iDstTriIndex*3+2] = i3;+ ++iDstTriIndex; // next+ {+ unsigned char * pVerts_B = pTriInfos[iDstTriIndex].vert_num;+ pVerts_B[0]=1; pVerts_B[1]=2; pVerts_B[2]=3;+ }+ piTriList_out[iDstTriIndex*3+0] = i1;+ piTriList_out[iDstTriIndex*3+1] = i2;+ piTriList_out[iDstTriIndex*3+2] = i3;+ ++iDstTriIndex; // next+ }+ }+ }++ iTSpacesOffs += verts;+ assert(iDstTriIndex<=iNrTrianglesIn);+ }++ for (t=0; t<iNrTrianglesIn; t++)+ pTriInfos[t].iFlag = 0;++ // return total amount of tspaces+ return iTSpacesOffs;+}++static SVec3 GetPosition(const SMikkTSpaceContext * pContext, const int index)+{+ int iF, iI;+ SVec3 res; float pos[3];+ IndexToData(&iF, &iI, index);+ pContext->m_pInterface->m_getPosition(pContext, pos, iF, iI);+ res.x=pos[0]; res.y=pos[1]; res.z=pos[2];+ return res;+}++static SVec3 GetNormal(const SMikkTSpaceContext * pContext, const int index)+{+ int iF, iI;+ SVec3 res; float norm[3];+ IndexToData(&iF, &iI, index);+ pContext->m_pInterface->m_getNormal(pContext, norm, iF, iI);+ res.x=norm[0]; res.y=norm[1]; res.z=norm[2];+ return res;+}++static SVec3 GetTexCoord(const SMikkTSpaceContext * pContext, const int index)+{+ int iF, iI;+ SVec3 res; float texc[2];+ IndexToData(&iF, &iI, index);+ pContext->m_pInterface->m_getTexCoord(pContext, texc, iF, iI);+ res.x=texc[0]; res.y=texc[1]; res.z=1.0f;+ return res;+}++/////////////////////////////////////////////////////////////////////////////////////////////////////+/////////////////////////////////////////////////////////////////////////////////////////////////////++typedef union {+ struct+ {+ int i0, i1, f;+ };+ int array[3];+} SEdge;++static void BuildNeighborsFast(STriInfo pTriInfos[], SEdge * pEdges, const int piTriListIn[], const int iNrTrianglesIn);+static void BuildNeighborsSlow(STriInfo pTriInfos[], const int piTriListIn[], const int iNrTrianglesIn);++// returns the texture area times 2+static float CalcTexArea(const SMikkTSpaceContext * pContext, const int indices[])+{+ const SVec3 t1 = GetTexCoord(pContext, indices[0]);+ const SVec3 t2 = GetTexCoord(pContext, indices[1]);+ const SVec3 t3 = GetTexCoord(pContext, indices[2]);++ const float t21x = t2.x-t1.x;+ const float t21y = t2.y-t1.y;+ const float t31x = t3.x-t1.x;+ const float t31y = t3.y-t1.y;++ const float fSignedAreaSTx2 = t21x*t31y - t21y*t31x;++ return fSignedAreaSTx2<0 ? (-fSignedAreaSTx2) : fSignedAreaSTx2;+}++static void InitTriInfo(STriInfo pTriInfos[], const int piTriListIn[], const SMikkTSpaceContext * pContext, const int iNrTrianglesIn)+{+ int f=0, i=0, t=0;+ // pTriInfos[f].iFlag is cleared in GenerateInitialVerticesIndexList() which is called before this function.++ // generate neighbor info list+ for (f=0; f<iNrTrianglesIn; f++)+ for (i=0; i<3; i++)+ {+ pTriInfos[f].FaceNeighbors[i] = -1;+ pTriInfos[f].AssignedGroup[i] = NULL;++ pTriInfos[f].vOs.x=0.0f; pTriInfos[f].vOs.y=0.0f; pTriInfos[f].vOs.z=0.0f;+ pTriInfos[f].vOt.x=0.0f; pTriInfos[f].vOt.y=0.0f; pTriInfos[f].vOt.z=0.0f;+ pTriInfos[f].fMagS = 0;+ pTriInfos[f].fMagT = 0;++ // assumed bad+ pTriInfos[f].iFlag |= GROUP_WITH_ANY;+ }++ // evaluate first order derivatives+ for (f=0; f<iNrTrianglesIn; f++)+ {+ // initial values+ const SVec3 v1 = GetPosition(pContext, piTriListIn[f*3+0]);+ const SVec3 v2 = GetPosition(pContext, piTriListIn[f*3+1]);+ const SVec3 v3 = GetPosition(pContext, piTriListIn[f*3+2]);+ const SVec3 t1 = GetTexCoord(pContext, piTriListIn[f*3+0]);+ const SVec3 t2 = GetTexCoord(pContext, piTriListIn[f*3+1]);+ const SVec3 t3 = GetTexCoord(pContext, piTriListIn[f*3+2]);++ const float t21x = t2.x-t1.x;+ const float t21y = t2.y-t1.y;+ const float t31x = t3.x-t1.x;+ const float t31y = t3.y-t1.y;+ const SVec3 d1 = vsub(v2,v1);+ const SVec3 d2 = vsub(v3,v1);++ const float fSignedAreaSTx2 = t21x*t31y - t21y*t31x;+ //assert(fSignedAreaSTx2!=0);+ SVec3 vOs = vsub(vscale(t31y,d1), vscale(t21y,d2)); // eq 18+ SVec3 vOt = vadd(vscale(-t31x,d1), vscale(t21x,d2)); // eq 19++ pTriInfos[f].iFlag |= (fSignedAreaSTx2>0 ? ORIENT_PRESERVING : 0);++ if ( NotZero(fSignedAreaSTx2) )+ {+ const float fAbsArea = fabsf(fSignedAreaSTx2);+ const float fLenOs = Length(vOs);+ const float fLenOt = Length(vOt);+ const float fS = (pTriInfos[f].iFlag&ORIENT_PRESERVING)==0 ? (-1.0f) : 1.0f;+ if ( NotZero(fLenOs) ) pTriInfos[f].vOs = vscale(fS/fLenOs, vOs);+ if ( NotZero(fLenOt) ) pTriInfos[f].vOt = vscale(fS/fLenOt, vOt);++ // evaluate magnitudes prior to normalization of vOs and vOt+ pTriInfos[f].fMagS = fLenOs / fAbsArea;+ pTriInfos[f].fMagT = fLenOt / fAbsArea;++ // if this is a good triangle+ if ( NotZero(pTriInfos[f].fMagS) && NotZero(pTriInfos[f].fMagT))+ pTriInfos[f].iFlag &= (~GROUP_WITH_ANY);+ }+ }++ // force otherwise healthy quads to a fixed orientation+ while (t<(iNrTrianglesIn-1))+ {+ const int iFO_a = pTriInfos[t].iOrgFaceNumber;+ const int iFO_b = pTriInfos[t+1].iOrgFaceNumber;+ if (iFO_a==iFO_b) // this is a quad+ {+ const tbool bIsDeg_a = (pTriInfos[t].iFlag&MARK_DEGENERATE)!=0 ? TTRUE : TFALSE;+ const tbool bIsDeg_b = (pTriInfos[t+1].iFlag&MARK_DEGENERATE)!=0 ? TTRUE : TFALSE;++ // bad triangles should already have been removed by+ // DegenPrologue(), but just in case check bIsDeg_a and bIsDeg_a are false+ if ((bIsDeg_a||bIsDeg_b)==TFALSE)+ {+ const tbool bOrientA = (pTriInfos[t].iFlag&ORIENT_PRESERVING)!=0 ? TTRUE : TFALSE;+ const tbool bOrientB = (pTriInfos[t+1].iFlag&ORIENT_PRESERVING)!=0 ? TTRUE : TFALSE;+ // if this happens the quad has extremely bad mapping!!+ if (bOrientA!=bOrientB)+ {+ //printf("found quad with bad mapping\n");+ tbool bChooseOrientFirstTri = TFALSE;+ if ((pTriInfos[t+1].iFlag&GROUP_WITH_ANY)!=0) bChooseOrientFirstTri = TTRUE;+ else if ( CalcTexArea(pContext, &piTriListIn[t*3+0]) >= CalcTexArea(pContext, &piTriListIn[(t+1)*3+0]) )+ bChooseOrientFirstTri = TTRUE;++ // force match+ {+ const int t0 = bChooseOrientFirstTri ? t : (t+1);+ const int t1 = bChooseOrientFirstTri ? (t+1) : t;+ pTriInfos[t1].iFlag &= (~ORIENT_PRESERVING); // clear first+ pTriInfos[t1].iFlag |= (pTriInfos[t0].iFlag&ORIENT_PRESERVING); // copy bit+ }+ }+ }+ t += 2;+ }+ else+ ++t;+ }++ // match up edge pairs+ {+ SEdge * pEdges = (SEdge *) malloc(sizeof(SEdge)*iNrTrianglesIn*3);+ if (pEdges==NULL)+ BuildNeighborsSlow(pTriInfos, piTriListIn, iNrTrianglesIn);+ else+ {+ BuildNeighborsFast(pTriInfos, pEdges, piTriListIn, iNrTrianglesIn);++ free(pEdges);+ }+ }+}++/////////////////////////////////////////////////////////////////////////////////////////////////////+/////////////////////////////////////////////////////////////////////////////////////////////////////++static tbool AssignRecur(const int piTriListIn[], STriInfo psTriInfos[], const int iMyTriIndex, SGroup * pGroup);+static void AddTriToGroup(SGroup * pGroup, const int iTriIndex);++static int Build4RuleGroups(STriInfo pTriInfos[], SGroup pGroups[], int piGroupTrianglesBuffer[], const int piTriListIn[], const int iNrTrianglesIn)+{+ const int iNrMaxGroups = iNrTrianglesIn*3;+ int iNrActiveGroups = 0;+ int iOffset = 0, f=0, i=0;+ (void)iNrMaxGroups; /* quiet warnings in non debug mode */+ for (f=0; f<iNrTrianglesIn; f++)+ {+ for (i=0; i<3; i++)+ {+ // if not assigned to a group+ if ((pTriInfos[f].iFlag&GROUP_WITH_ANY)==0 && pTriInfos[f].AssignedGroup[i]==NULL)+ {+ tbool bOrPre;+ int neigh_indexL, neigh_indexR;+ const int vert_index = piTriListIn[f*3+i];+ assert(iNrActiveGroups<iNrMaxGroups);+ pTriInfos[f].AssignedGroup[i] = &pGroups[iNrActiveGroups];+ pTriInfos[f].AssignedGroup[i]->iVertexRepresentitive = vert_index;+ pTriInfos[f].AssignedGroup[i]->bOrientPreservering = (pTriInfos[f].iFlag&ORIENT_PRESERVING)!=0;+ pTriInfos[f].AssignedGroup[i]->iNrFaces = 0;+ pTriInfos[f].AssignedGroup[i]->pFaceIndices = &piGroupTrianglesBuffer[iOffset];+ ++iNrActiveGroups;++ AddTriToGroup(pTriInfos[f].AssignedGroup[i], f);+ bOrPre = (pTriInfos[f].iFlag&ORIENT_PRESERVING)!=0 ? TTRUE : TFALSE;+ neigh_indexL = pTriInfos[f].FaceNeighbors[i];+ neigh_indexR = pTriInfos[f].FaceNeighbors[i>0?(i-1):2];+ if (neigh_indexL>=0) // neighbor+ {+ const tbool bAnswer =+ AssignRecur(piTriListIn, pTriInfos, neigh_indexL,+ pTriInfos[f].AssignedGroup[i] );++ const tbool bOrPre2 = (pTriInfos[neigh_indexL].iFlag&ORIENT_PRESERVING)!=0 ? TTRUE : TFALSE;+ const tbool bDiff = bOrPre!=bOrPre2 ? TTRUE : TFALSE;+ assert(bAnswer || bDiff);+ (void)bAnswer, (void)bDiff; /* quiet warnings in non debug mode */+ }+ if (neigh_indexR>=0) // neighbor+ {+ const tbool bAnswer =+ AssignRecur(piTriListIn, pTriInfos, neigh_indexR,+ pTriInfos[f].AssignedGroup[i] );++ const tbool bOrPre2 = (pTriInfos[neigh_indexR].iFlag&ORIENT_PRESERVING)!=0 ? TTRUE : TFALSE;+ const tbool bDiff = bOrPre!=bOrPre2 ? TTRUE : TFALSE;+ assert(bAnswer || bDiff);+ (void)bAnswer, (void)bDiff; /* quiet warnings in non debug mode */+ }++ // update offset+ iOffset += pTriInfos[f].AssignedGroup[i]->iNrFaces;+ // since the groups are disjoint a triangle can never+ // belong to more than 3 groups. Subsequently something+ // is completely screwed if this assertion ever hits.+ assert(iOffset <= iNrMaxGroups);+ }+ }+ }++ return iNrActiveGroups;+}++static void AddTriToGroup(SGroup * pGroup, const int iTriIndex)+{+ pGroup->pFaceIndices[pGroup->iNrFaces] = iTriIndex;+ ++pGroup->iNrFaces;+}++static tbool AssignRecur(const int piTriListIn[], STriInfo psTriInfos[],+ const int iMyTriIndex, SGroup * pGroup)+{+ STriInfo * pMyTriInfo = &psTriInfos[iMyTriIndex];++ // track down vertex+ const int iVertRep = pGroup->iVertexRepresentitive;+ const int * pVerts = &piTriListIn[3*iMyTriIndex+0];+ int i=-1;+ if (pVerts[0]==iVertRep) i=0;+ else if (pVerts[1]==iVertRep) i=1;+ else if (pVerts[2]==iVertRep) i=2;+ assert(i>=0 && i<3);++ // early out+ if (pMyTriInfo->AssignedGroup[i] == pGroup) return TTRUE;+ else if (pMyTriInfo->AssignedGroup[i]!=NULL) return TFALSE;+ if ((pMyTriInfo->iFlag&GROUP_WITH_ANY)!=0)+ {+ // first to group with a group-with-anything triangle+ // determines it's orientation.+ // This is the only existing order dependency in the code!!+ if ( pMyTriInfo->AssignedGroup[0] == NULL &&+ pMyTriInfo->AssignedGroup[1] == NULL &&+ pMyTriInfo->AssignedGroup[2] == NULL )+ {+ pMyTriInfo->iFlag &= (~ORIENT_PRESERVING);+ pMyTriInfo->iFlag |= (pGroup->bOrientPreservering ? ORIENT_PRESERVING : 0);+ }+ }+ {+ const tbool bOrient = (pMyTriInfo->iFlag&ORIENT_PRESERVING)!=0 ? TTRUE : TFALSE;+ if (bOrient != pGroup->bOrientPreservering) return TFALSE;+ }++ AddTriToGroup(pGroup, iMyTriIndex);+ pMyTriInfo->AssignedGroup[i] = pGroup;++ {+ const int neigh_indexL = pMyTriInfo->FaceNeighbors[i];+ const int neigh_indexR = pMyTriInfo->FaceNeighbors[i>0?(i-1):2];+ if (neigh_indexL>=0)+ AssignRecur(piTriListIn, psTriInfos, neigh_indexL, pGroup);+ if (neigh_indexR>=0)+ AssignRecur(piTriListIn, psTriInfos, neigh_indexR, pGroup);+ }++++ return TTRUE;+}++/////////////////////////////////////////////////////////////////////////////////////////////////////+/////////////////////////////////////////////////////////////////////////////////////////////////////++static tbool CompareSubGroups(const SSubGroup * pg1, const SSubGroup * pg2);+static void QuickSort(int* pSortBuffer, int iLeft, int iRight, unsigned int uSeed);+static STSpace EvalTspace(int face_indices[], const int iFaces, const int piTriListIn[], const STriInfo pTriInfos[], const SMikkTSpaceContext * pContext, const int iVertexRepresentitive);++static tbool GenerateTSpaces(STSpace psTspace[], const STriInfo pTriInfos[], const SGroup pGroups[],+ const int iNrActiveGroups, const int piTriListIn[], const float fThresCos,+ const SMikkTSpaceContext * pContext)+{+ STSpace * pSubGroupTspace = NULL;+ SSubGroup * pUniSubGroups = NULL;+ int * pTmpMembers = NULL;+ int iMaxNrFaces=0, iUniqueTspaces=0, g=0, i=0;+ for (g=0; g<iNrActiveGroups; g++)+ if (iMaxNrFaces < pGroups[g].iNrFaces)+ iMaxNrFaces = pGroups[g].iNrFaces;++ if (iMaxNrFaces == 0) return TTRUE;++ // make initial allocations+ pSubGroupTspace = (STSpace *) malloc(sizeof(STSpace)*iMaxNrFaces);+ pUniSubGroups = (SSubGroup *) malloc(sizeof(SSubGroup)*iMaxNrFaces);+ pTmpMembers = (int *) malloc(sizeof(int)*iMaxNrFaces);+ if (pSubGroupTspace==NULL || pUniSubGroups==NULL || pTmpMembers==NULL)+ {+ if (pSubGroupTspace!=NULL) free(pSubGroupTspace);+ if (pUniSubGroups!=NULL) free(pUniSubGroups);+ if (pTmpMembers!=NULL) free(pTmpMembers);+ return TFALSE;+ }+++ iUniqueTspaces = 0;+ for (g=0; g<iNrActiveGroups; g++)+ {+ const SGroup * pGroup = &pGroups[g];+ int iUniqueSubGroups = 0, s=0;++ for (i=0; i<pGroup->iNrFaces; i++) // triangles+ {+ const int f = pGroup->pFaceIndices[i]; // triangle number+ int index=-1, iVertIndex=-1, iOF_1=-1, iMembers=0, j=0, l=0;+ SSubGroup tmp_group;+ tbool bFound;+ SVec3 n, vOs, vOt;+ if (pTriInfos[f].AssignedGroup[0]==pGroup) index=0;+ else if (pTriInfos[f].AssignedGroup[1]==pGroup) index=1;+ else if (pTriInfos[f].AssignedGroup[2]==pGroup) index=2;+ assert(index>=0 && index<3);++ iVertIndex = piTriListIn[f*3+index];+ assert(iVertIndex==pGroup->iVertexRepresentitive);++ // is normalized already+ n = GetNormal(pContext, iVertIndex);++ // project+ vOs = vsub(pTriInfos[f].vOs, vscale(vdot(n,pTriInfos[f].vOs), n));+ vOt = vsub(pTriInfos[f].vOt, vscale(vdot(n,pTriInfos[f].vOt), n));+ if ( VNotZero(vOs) ) vOs = Normalize(vOs);+ if ( VNotZero(vOt) ) vOt = Normalize(vOt);++ // original face number+ iOF_1 = pTriInfos[f].iOrgFaceNumber;++ iMembers = 0;+ for (j=0; j<pGroup->iNrFaces; j++)+ {+ const int t = pGroup->pFaceIndices[j]; // triangle number+ const int iOF_2 = pTriInfos[t].iOrgFaceNumber;++ // project+ SVec3 vOs2 = vsub(pTriInfos[t].vOs, vscale(vdot(n,pTriInfos[t].vOs), n));+ SVec3 vOt2 = vsub(pTriInfos[t].vOt, vscale(vdot(n,pTriInfos[t].vOt), n));+ if ( VNotZero(vOs2) ) vOs2 = Normalize(vOs2);+ if ( VNotZero(vOt2) ) vOt2 = Normalize(vOt2);++ {+ const tbool bAny = ( (pTriInfos[f].iFlag | pTriInfos[t].iFlag) & GROUP_WITH_ANY )!=0 ? TTRUE : TFALSE;+ // make sure triangles which belong to the same quad are joined.+ const tbool bSameOrgFace = iOF_1==iOF_2 ? TTRUE : TFALSE;++ const float fCosS = vdot(vOs,vOs2);+ const float fCosT = vdot(vOt,vOt2);++ assert(f!=t || bSameOrgFace); // sanity check+ if (bAny || bSameOrgFace || (fCosS>fThresCos && fCosT>fThresCos))+ pTmpMembers[iMembers++] = t;+ }+ }++ // sort pTmpMembers+ tmp_group.iNrFaces = iMembers;+ tmp_group.pTriMembers = pTmpMembers;+ if (iMembers>1)+ {+ unsigned int uSeed = INTERNAL_RND_SORT_SEED; // could replace with a random seed?+ QuickSort(pTmpMembers, 0, iMembers-1, uSeed);+ }++ // look for an existing match+ bFound = TFALSE;+ l=0;+ while (l<iUniqueSubGroups && !bFound)+ {+ bFound = CompareSubGroups(&tmp_group, &pUniSubGroups[l]);+ if (!bFound) ++l;+ }++ // assign tangent space index+ assert(bFound || l==iUniqueSubGroups);+ //piTempTangIndices[f*3+index] = iUniqueTspaces+l;++ // if no match was found we allocate a new subgroup+ if (!bFound)+ {+ // insert new subgroup+ int * pIndices = (int *) malloc(sizeof(int)*iMembers);+ if (pIndices==NULL)+ {+ // clean up and return false+ int s=0;+ for (s=0; s<iUniqueSubGroups; s++)+ free(pUniSubGroups[s].pTriMembers);+ free(pUniSubGroups);+ free(pTmpMembers);+ free(pSubGroupTspace);+ return TFALSE;+ }+ pUniSubGroups[iUniqueSubGroups].iNrFaces = iMembers;+ pUniSubGroups[iUniqueSubGroups].pTriMembers = pIndices;+ memcpy(pIndices, tmp_group.pTriMembers, iMembers*sizeof(int));+ pSubGroupTspace[iUniqueSubGroups] =+ EvalTspace(tmp_group.pTriMembers, iMembers, piTriListIn, pTriInfos, pContext, pGroup->iVertexRepresentitive);+ ++iUniqueSubGroups;+ }++ // output tspace+ {+ const int iOffs = pTriInfos[f].iTSpacesOffs;+ const int iVert = pTriInfos[f].vert_num[index];+ STSpace * pTS_out = &psTspace[iOffs+iVert];+ assert(pTS_out->iCounter<2);+ assert(((pTriInfos[f].iFlag&ORIENT_PRESERVING)!=0) == pGroup->bOrientPreservering);+ if (pTS_out->iCounter==1)+ {+ *pTS_out = AvgTSpace(pTS_out, &pSubGroupTspace[l]);+ pTS_out->iCounter = 2; // update counter+ pTS_out->bOrient = pGroup->bOrientPreservering;+ }+ else+ {+ assert(pTS_out->iCounter==0);+ *pTS_out = pSubGroupTspace[l];+ pTS_out->iCounter = 1; // update counter+ pTS_out->bOrient = pGroup->bOrientPreservering;+ }+ }+ }++ // clean up and offset iUniqueTspaces+ for (s=0; s<iUniqueSubGroups; s++)+ free(pUniSubGroups[s].pTriMembers);+ iUniqueTspaces += iUniqueSubGroups;+ }++ // clean up+ free(pUniSubGroups);+ free(pTmpMembers);+ free(pSubGroupTspace);++ return TTRUE;+}++static STSpace EvalTspace(int face_indices[], const int iFaces, const int piTriListIn[], const STriInfo pTriInfos[],+ const SMikkTSpaceContext * pContext, const int iVertexRepresentitive)+{+ STSpace res;+ float fAngleSum = 0;+ int face=0;+ res.vOs.x=0.0f; res.vOs.y=0.0f; res.vOs.z=0.0f;+ res.vOt.x=0.0f; res.vOt.y=0.0f; res.vOt.z=0.0f;+ res.fMagS = 0; res.fMagT = 0;++ for (face=0; face<iFaces; face++)+ {+ const int f = face_indices[face];++ // only valid triangles get to add their contribution+ if ( (pTriInfos[f].iFlag&GROUP_WITH_ANY)==0 )+ {+ SVec3 n, vOs, vOt, p0, p1, p2, v1, v2;+ float fCos, fAngle, fMagS, fMagT;+ int i=-1, index=-1, i0=-1, i1=-1, i2=-1;+ if (piTriListIn[3*f+0]==iVertexRepresentitive) i=0;+ else if (piTriListIn[3*f+1]==iVertexRepresentitive) i=1;+ else if (piTriListIn[3*f+2]==iVertexRepresentitive) i=2;+ assert(i>=0 && i<3);++ // project+ index = piTriListIn[3*f+i];+ n = GetNormal(pContext, index);+ vOs = vsub(pTriInfos[f].vOs, vscale(vdot(n,pTriInfos[f].vOs), n));+ vOt = vsub(pTriInfos[f].vOt, vscale(vdot(n,pTriInfos[f].vOt), n));+ if ( VNotZero(vOs) ) vOs = Normalize(vOs);+ if ( VNotZero(vOt) ) vOt = Normalize(vOt);++ i2 = piTriListIn[3*f + (i<2?(i+1):0)];+ i1 = piTriListIn[3*f + i];+ i0 = piTriListIn[3*f + (i>0?(i-1):2)];++ p0 = GetPosition(pContext, i0);+ p1 = GetPosition(pContext, i1);+ p2 = GetPosition(pContext, i2);+ v1 = vsub(p0,p1);+ v2 = vsub(p2,p1);++ // project+ v1 = vsub(v1, vscale(vdot(n,v1),n)); if ( VNotZero(v1) ) v1 = Normalize(v1);+ v2 = vsub(v2, vscale(vdot(n,v2),n)); if ( VNotZero(v2) ) v2 = Normalize(v2);++ // weight contribution by the angle+ // between the two edge vectors+ fCos = vdot(v1,v2); fCos=fCos>1?1:(fCos<(-1) ? (-1) : fCos);+ fAngle = (float) acos(fCos);+ fMagS = pTriInfos[f].fMagS;+ fMagT = pTriInfos[f].fMagT;++ res.vOs=vadd(res.vOs, vscale(fAngle,vOs));+ res.vOt=vadd(res.vOt,vscale(fAngle,vOt));+ res.fMagS+=(fAngle*fMagS);+ res.fMagT+=(fAngle*fMagT);+ fAngleSum += fAngle;+ }+ }++ // normalize+ if ( VNotZero(res.vOs) ) res.vOs = Normalize(res.vOs);+ if ( VNotZero(res.vOt) ) res.vOt = Normalize(res.vOt);+ if (fAngleSum>0)+ {+ res.fMagS /= fAngleSum;+ res.fMagT /= fAngleSum;+ }++ return res;+}++static tbool CompareSubGroups(const SSubGroup * pg1, const SSubGroup * pg2)+{+ tbool bStillSame=TTRUE;+ int i=0;+ if (pg1->iNrFaces!=pg2->iNrFaces) return TFALSE;+ while (i<pg1->iNrFaces && bStillSame)+ {+ bStillSame = pg1->pTriMembers[i]==pg2->pTriMembers[i] ? TTRUE : TFALSE;+ if (bStillSame) ++i;+ }+ return bStillSame;+}++static void QuickSort(int* pSortBuffer, int iLeft, int iRight, unsigned int uSeed)+{+ int iL, iR, n, index, iMid, iTmp;++ // Random+ unsigned int t=uSeed&31;+ t=(uSeed<<t)|(uSeed>>(32-t));+ uSeed=uSeed+t+3;+ // Random end++ iL=iLeft; iR=iRight;+ n = (iR-iL)+1;+ assert(n>=0);+ index = (int) (uSeed%n);++ iMid=pSortBuffer[index + iL];+++ do+ {+ while (pSortBuffer[iL] < iMid)+ ++iL;+ while (pSortBuffer[iR] > iMid)+ --iR;++ if (iL <= iR)+ {+ iTmp = pSortBuffer[iL];+ pSortBuffer[iL] = pSortBuffer[iR];+ pSortBuffer[iR] = iTmp;+ ++iL; --iR;+ }+ }+ while (iL <= iR);++ if (iLeft < iR)+ QuickSort(pSortBuffer, iLeft, iR, uSeed);+ if (iL < iRight)+ QuickSort(pSortBuffer, iL, iRight, uSeed);+}++/////////////////////////////////////////////////////////////////////////////////////////////+/////////////////////////////////////////////////////////////////////////////////////////////++static void QuickSortEdges(SEdge * pSortBuffer, int iLeft, int iRight, const int channel, unsigned int uSeed);+static void GetEdge(int * i0_out, int * i1_out, int * edgenum_out, const int indices[], const int i0_in, const int i1_in);++static void BuildNeighborsFast(STriInfo pTriInfos[], SEdge * pEdges, const int piTriListIn[], const int iNrTrianglesIn)+{+ // build array of edges+ unsigned int uSeed = INTERNAL_RND_SORT_SEED; // could replace with a random seed?+ int iEntries=0, iCurStartIndex=-1, f=0, i=0;+ for (f=0; f<iNrTrianglesIn; f++)+ for (i=0; i<3; i++)+ {+ const int i0 = piTriListIn[f*3+i];+ const int i1 = piTriListIn[f*3+(i<2?(i+1):0)];+ pEdges[f*3+i].i0 = i0 < i1 ? i0 : i1; // put minimum index in i0+ pEdges[f*3+i].i1 = !(i0 < i1) ? i0 : i1; // put maximum index in i1+ pEdges[f*3+i].f = f; // record face number+ }++ // sort over all edges by i0, this is the pricy one.+ QuickSortEdges(pEdges, 0, iNrTrianglesIn*3-1, 0, uSeed); // sort channel 0 which is i0++ // sub sort over i1, should be fast.+ // could replace this with a 64 bit int sort over (i0,i1)+ // with i0 as msb in the quicksort call above.+ iEntries = iNrTrianglesIn*3;+ iCurStartIndex = 0;+ for (i=1; i<iEntries; i++)+ {+ if (pEdges[iCurStartIndex].i0 != pEdges[i].i0)+ {+ const int iL = iCurStartIndex;+ const int iR = i-1;+ //const int iElems = i-iL;+ iCurStartIndex = i;+ QuickSortEdges(pEdges, iL, iR, 1, uSeed); // sort channel 1 which is i1+ }+ }++ // sub sort over f, which should be fast.+ // this step is to remain compliant with BuildNeighborsSlow() when+ // more than 2 triangles use the same edge (such as a butterfly topology).+ iCurStartIndex = 0;+ for (i=1; i<iEntries; i++)+ {+ if (pEdges[iCurStartIndex].i0 != pEdges[i].i0 || pEdges[iCurStartIndex].i1 != pEdges[i].i1)+ {+ const int iL = iCurStartIndex;+ const int iR = i-1;+ //const int iElems = i-iL;+ iCurStartIndex = i;+ QuickSortEdges(pEdges, iL, iR, 2, uSeed); // sort channel 2 which is f+ }+ }++ // pair up, adjacent triangles+ for (i=0; i<iEntries; i++)+ {+ const int i0=pEdges[i].i0;+ const int i1=pEdges[i].i1;+ const int f = pEdges[i].f;+ tbool bUnassigned_A;++ int i0_A, i1_A;+ int edgenum_A, edgenum_B=0; // 0,1 or 2+ GetEdge(&i0_A, &i1_A, &edgenum_A, &piTriListIn[f*3], i0, i1); // resolve index ordering and edge_num+ bUnassigned_A = pTriInfos[f].FaceNeighbors[edgenum_A] == -1 ? TTRUE : TFALSE;++ if (bUnassigned_A)+ {+ // get true index ordering+ int j=i+1, t;+ tbool bNotFound = TTRUE;+ while (j<iEntries && i0==pEdges[j].i0 && i1==pEdges[j].i1 && bNotFound)+ {+ tbool bUnassigned_B;+ int i0_B, i1_B;+ t = pEdges[j].f;+ // flip i0_B and i1_B+ GetEdge(&i1_B, &i0_B, &edgenum_B, &piTriListIn[t*3], pEdges[j].i0, pEdges[j].i1); // resolve index ordering and edge_num+ //assert(!(i0_A==i1_B && i1_A==i0_B));+ bUnassigned_B = pTriInfos[t].FaceNeighbors[edgenum_B]==-1 ? TTRUE : TFALSE;+ if (i0_A==i0_B && i1_A==i1_B && bUnassigned_B)+ bNotFound = TFALSE;+ else+ ++j;+ }++ if (!bNotFound)+ {+ int t = pEdges[j].f;+ pTriInfos[f].FaceNeighbors[edgenum_A] = t;+ //assert(pTriInfos[t].FaceNeighbors[edgenum_B]==-1);+ pTriInfos[t].FaceNeighbors[edgenum_B] = f;+ }+ }+ }+}++static void BuildNeighborsSlow(STriInfo pTriInfos[], const int piTriListIn[], const int iNrTrianglesIn)+{+ int f=0, i=0;+ for (f=0; f<iNrTrianglesIn; f++)+ {+ for (i=0; i<3; i++)+ {+ // if unassigned+ if (pTriInfos[f].FaceNeighbors[i] == -1)+ {+ const int i0_A = piTriListIn[f*3+i];+ const int i1_A = piTriListIn[f*3+(i<2?(i+1):0)];++ // search for a neighbor+ tbool bFound = TFALSE;+ int t=0, j=0;+ while (!bFound && t<iNrTrianglesIn)+ {+ if (t!=f)+ {+ j=0;+ while (!bFound && j<3)+ {+ // in rev order+ const int i1_B = piTriListIn[t*3+j];+ const int i0_B = piTriListIn[t*3+(j<2?(j+1):0)];+ //assert(!(i0_A==i1_B && i1_A==i0_B));+ if (i0_A==i0_B && i1_A==i1_B)+ bFound = TTRUE;+ else+ ++j;+ }+ }++ if (!bFound) ++t;+ }++ // assign neighbors+ if (bFound)+ {+ pTriInfos[f].FaceNeighbors[i] = t;+ //assert(pTriInfos[t].FaceNeighbors[j]==-1);+ pTriInfos[t].FaceNeighbors[j] = f;+ }+ }+ }+ }+}++static void QuickSortEdges(SEdge * pSortBuffer, int iLeft, int iRight, const int channel, unsigned int uSeed)+{+ unsigned int t;+ int iL, iR, n, index, iMid;++ // early out+ SEdge sTmp;+ const int iElems = iRight-iLeft+1;+ if (iElems<2) return;+ else if (iElems==2)+ {+ if (pSortBuffer[iLeft].array[channel] > pSortBuffer[iRight].array[channel])+ {+ sTmp = pSortBuffer[iLeft];+ pSortBuffer[iLeft] = pSortBuffer[iRight];+ pSortBuffer[iRight] = sTmp;+ }+ return;+ }++ // Random+ t=uSeed&31;+ t=(uSeed<<t)|(uSeed>>(32-t));+ uSeed=uSeed+t+3;+ // Random end++ iL = iLeft;+ iR = iRight;+ n = (iR-iL)+1;+ assert(n>=0);+ index = (int) (uSeed%n);++ iMid=pSortBuffer[index + iL].array[channel];++ do+ {+ while (pSortBuffer[iL].array[channel] < iMid)+ ++iL;+ while (pSortBuffer[iR].array[channel] > iMid)+ --iR;++ if (iL <= iR)+ {+ sTmp = pSortBuffer[iL];+ pSortBuffer[iL] = pSortBuffer[iR];+ pSortBuffer[iR] = sTmp;+ ++iL; --iR;+ }+ }+ while (iL <= iR);++ if (iLeft < iR)+ QuickSortEdges(pSortBuffer, iLeft, iR, channel, uSeed);+ if (iL < iRight)+ QuickSortEdges(pSortBuffer, iL, iRight, channel, uSeed);+}++// resolve ordering and edge number+static void GetEdge(int * i0_out, int * i1_out, int * edgenum_out, const int indices[], const int i0_in, const int i1_in)+{+ *edgenum_out = -1;++ // test if first index is on the edge+ if (indices[0]==i0_in || indices[0]==i1_in)+ {+ // test if second index is on the edge+ if (indices[1]==i0_in || indices[1]==i1_in)+ {+ edgenum_out[0]=0; // first edge+ i0_out[0]=indices[0];+ i1_out[0]=indices[1];+ }+ else+ {+ edgenum_out[0]=2; // third edge+ i0_out[0]=indices[2];+ i1_out[0]=indices[0];+ }+ }+ else+ {+ // only second and third index is on the edge+ edgenum_out[0]=1; // second edge+ i0_out[0]=indices[1];+ i1_out[0]=indices[2];+ }+}+++/////////////////////////////////////////////////////////////////////////////////////////////+/////////////////////////////////// Degenerate triangles ////////////////////////////////////++static void DegenPrologue(STriInfo pTriInfos[], int piTriList_out[], const int iNrTrianglesIn, const int iTotTris)+{+ int iNextGoodTriangleSearchIndex=-1;+ tbool bStillFindingGoodOnes;++ // locate quads with only one good triangle+ int t=0;+ while (t<(iTotTris-1))+ {+ const int iFO_a = pTriInfos[t].iOrgFaceNumber;+ const int iFO_b = pTriInfos[t+1].iOrgFaceNumber;+ if (iFO_a==iFO_b) // this is a quad+ {+ const tbool bIsDeg_a = (pTriInfos[t].iFlag&MARK_DEGENERATE)!=0 ? TTRUE : TFALSE;+ const tbool bIsDeg_b = (pTriInfos[t+1].iFlag&MARK_DEGENERATE)!=0 ? TTRUE : TFALSE;+ if ((bIsDeg_a^bIsDeg_b)!=0)+ {+ pTriInfos[t].iFlag |= QUAD_ONE_DEGEN_TRI;+ pTriInfos[t+1].iFlag |= QUAD_ONE_DEGEN_TRI;+ }+ t += 2;+ }+ else+ ++t;+ }++ // reorder list so all degen triangles are moved to the back+ // without reordering the good triangles+ iNextGoodTriangleSearchIndex = 1;+ t=0;+ bStillFindingGoodOnes = TTRUE;+ while (t<iNrTrianglesIn && bStillFindingGoodOnes)+ {+ const tbool bIsGood = (pTriInfos[t].iFlag&MARK_DEGENERATE)==0 ? TTRUE : TFALSE;+ if (bIsGood)+ {+ if (iNextGoodTriangleSearchIndex < (t+2))+ iNextGoodTriangleSearchIndex = t+2;+ }+ else+ {+ int t0, t1;+ // search for the first good triangle.+ tbool bJustADegenerate = TTRUE;+ while (bJustADegenerate && iNextGoodTriangleSearchIndex<iTotTris)+ {+ const tbool bIsGood = (pTriInfos[iNextGoodTriangleSearchIndex].iFlag&MARK_DEGENERATE)==0 ? TTRUE : TFALSE;+ if (bIsGood) bJustADegenerate=TFALSE;+ else ++iNextGoodTriangleSearchIndex;+ }++ t0 = t;+ t1 = iNextGoodTriangleSearchIndex;+ ++iNextGoodTriangleSearchIndex;+ assert(iNextGoodTriangleSearchIndex > (t+1));++ // swap triangle t0 and t1+ if (!bJustADegenerate)+ {+ int i=0;+ for (i=0; i<3; i++)+ {+ const int index = piTriList_out[t0*3+i];+ piTriList_out[t0*3+i] = piTriList_out[t1*3+i];+ piTriList_out[t1*3+i] = index;+ }+ {+ const STriInfo tri_info = pTriInfos[t0];+ pTriInfos[t0] = pTriInfos[t1];+ pTriInfos[t1] = tri_info;+ }+ }+ else+ bStillFindingGoodOnes = TFALSE; // this is not supposed to happen+ }++ if (bStillFindingGoodOnes) ++t;+ }++ assert(bStillFindingGoodOnes); // code will still work.+ assert(iNrTrianglesIn == t);+}++static void DegenEpilogue(STSpace psTspace[], STriInfo pTriInfos[], int piTriListIn[], const SMikkTSpaceContext * pContext, const int iNrTrianglesIn, const int iTotTris)+{+ int t=0, i=0;+ // deal with degenerate triangles+ // punishment for degenerate triangles is O(N^2)+ for (t=iNrTrianglesIn; t<iTotTris; t++)+ {+ // degenerate triangles on a quad with one good triangle are skipped+ // here but processed in the next loop+ const tbool bSkip = (pTriInfos[t].iFlag&QUAD_ONE_DEGEN_TRI)!=0 ? TTRUE : TFALSE;++ if (!bSkip)+ {+ for (i=0; i<3; i++)+ {+ const int index1 = piTriListIn[t*3+i];+ // search through the good triangles+ tbool bNotFound = TTRUE;+ int j=0;+ while (bNotFound && j<(3*iNrTrianglesIn))+ {+ const int index2 = piTriListIn[j];+ if (index1==index2) bNotFound=TFALSE;+ else ++j;+ }++ if (!bNotFound)+ {+ const int iTri = j/3;+ const int iVert = j%3;+ const int iSrcVert=pTriInfos[iTri].vert_num[iVert];+ const int iSrcOffs=pTriInfos[iTri].iTSpacesOffs;+ const int iDstVert=pTriInfos[t].vert_num[i];+ const int iDstOffs=pTriInfos[t].iTSpacesOffs;++ // copy tspace+ psTspace[iDstOffs+iDstVert] = psTspace[iSrcOffs+iSrcVert];+ }+ }+ }+ }++ // deal with degenerate quads with one good triangle+ for (t=0; t<iNrTrianglesIn; t++)+ {+ // this triangle belongs to a quad where the+ // other triangle is degenerate+ if ( (pTriInfos[t].iFlag&QUAD_ONE_DEGEN_TRI)!=0 )+ {+ SVec3 vDstP;+ int iOrgF=-1, i=0;+ tbool bNotFound;+ unsigned char * pV = pTriInfos[t].vert_num;+ int iFlag = (1<<pV[0]) | (1<<pV[1]) | (1<<pV[2]);+ int iMissingIndex = 0;+ if ((iFlag&2)==0) iMissingIndex=1;+ else if ((iFlag&4)==0) iMissingIndex=2;+ else if ((iFlag&8)==0) iMissingIndex=3;++ iOrgF = pTriInfos[t].iOrgFaceNumber;+ vDstP = GetPosition(pContext, MakeIndex(iOrgF, iMissingIndex));+ bNotFound = TTRUE;+ i=0;+ while (bNotFound && i<3)+ {+ const int iVert = pV[i];+ const SVec3 vSrcP = GetPosition(pContext, MakeIndex(iOrgF, iVert));+ if (veq(vSrcP, vDstP)==TTRUE)+ {+ const int iOffs = pTriInfos[t].iTSpacesOffs;+ psTspace[iOffs+iMissingIndex] = psTspace[iOffs+iVert];+ bNotFound=TFALSE;+ }+ else+ ++i;+ }+ assert(!bNotFound);+ }+ }+}diff --git a/third_party/mikktspace/mikktspace.h b/third_party/mikktspace/mikktspace.hnew file mode 100644index 00000000..52c44a71--- /dev/null+++ b/third_party/mikktspace/mikktspace.h@@ -0,0 +1,145 @@+/** \file mikktspace/mikktspace.h+ * \ingroup mikktspace+ */+/**+ * Copyright (C) 2011 by Morten S. Mikkelsen+ *+ * This software is provided 'as-is', without any express or implied+ * warranty. In no event will the authors be held liable for any damages+ * arising from the use of this software.+ *+ * Permission is granted to anyone to use this software for any purpose,+ * including commercial applications, and to alter it and redistribute it+ * freely, subject to the following restrictions:+ *+ * 1. The origin of this software must not be misrepresented; you must not+ * claim that you wrote the original software. If you use this software+ * in a product, an acknowledgment in the product documentation would be+ * appreciated but is not required.+ * 2. Altered source versions must be plainly marked as such, and must not be+ * misrepresented as being the original software.+ * 3. This notice may not be removed or altered from any source distribution.+ */++#ifndef __MIKKTSPACE_H__+#define __MIKKTSPACE_H__+++#ifdef __cplusplus+extern "C" {+#endif++/* Author: Morten S. Mikkelsen+ * Version: 1.0+ *+ * The files mikktspace.h and mikktspace.c are designed to be+ * stand-alone files and it is important that they are kept this way.+ * Not having dependencies on structures/classes/libraries specific+ * to the program, in which they are used, allows them to be copied+ * and used as is into any tool, program or plugin.+ * The code is designed to consistently generate the same+ * tangent spaces, for a given mesh, in any tool in which it is used.+ * This is done by performing an internal welding step and subsequently an order-independent evaluation+ * of tangent space for meshes consisting of triangles and quads.+ * This means faces can be received in any order and the same is true for+ * the order of vertices of each face. The generated result will not be affected+ * by such reordering. Additionally, whether degenerate (vertices or texture coordinates)+ * primitives are present or not will not affect the generated results either.+ * Once tangent space calculation is done the vertices of degenerate primitives will simply+ * inherit tangent space from neighboring non degenerate primitives.+ * The analysis behind this implementation can be found in my master's thesis+ * which is available for download --> http://image.diku.dk/projects/media/morten.mikkelsen.08.pdf+ * Note that though the tangent spaces at the vertices are generated in an order-independent way,+ * by this implementation, the interpolated tangent space is still affected by which diagonal is+ * chosen to split each quad. A sensible solution is to have your tools pipeline always+ * split quads by the shortest diagonal. This choice is order-independent and works with mirroring.+ * If these have the same length then compare the diagonals defined by the texture coordinates.+ * XNormal which is a tool for baking normal maps allows you to write your own tangent space plugin+ * and also quad triangulator plugin.+ */+++typedef int tbool;+typedef struct SMikkTSpaceContext SMikkTSpaceContext;++typedef struct {+ // Returns the number of faces (triangles/quads) on the mesh to be processed.+ int (*m_getNumFaces)(const SMikkTSpaceContext * pContext);++ // Returns the number of vertices on face number iFace+ // iFace is a number in the range {0, 1, ..., getNumFaces()-1}+ int (*m_getNumVerticesOfFace)(const SMikkTSpaceContext * pContext, const int iFace);++ // returns the position/normal/texcoord of the referenced face of vertex number iVert.+ // iVert is in the range {0,1,2} for triangles and {0,1,2,3} for quads.+ void (*m_getPosition)(const SMikkTSpaceContext * pContext, float fvPosOut[], const int iFace, const int iVert);+ void (*m_getNormal)(const SMikkTSpaceContext * pContext, float fvNormOut[], const int iFace, const int iVert);+ void (*m_getTexCoord)(const SMikkTSpaceContext * pContext, float fvTexcOut[], const int iFace, const int iVert);++ // either (or both) of the two setTSpace callbacks can be set.+ // The call-back m_setTSpaceBasic() is sufficient for basic normal mapping.++ // This function is used to return the tangent and fSign to the application.+ // fvTangent is a unit length vector.+ // For normal maps it is sufficient to use the following simplified version of the bitangent which is generated at pixel/vertex level.+ // bitangent = fSign * cross(vN, tangent);+ // Note that the results are returned unindexed. It is possible to generate a new index list+ // But averaging/overwriting tangent spaces by using an already existing index list WILL produce INCRORRECT results.+ // DO NOT! use an already existing index list.+ void (*m_setTSpaceBasic)(const SMikkTSpaceContext * pContext, const float fvTangent[], const float fSign, const int iFace, const int iVert);++ // This function is used to return tangent space results to the application.+ // fvTangent and fvBiTangent are unit length vectors and fMagS and fMagT are their+ // true magnitudes which can be used for relief mapping effects.+ // fvBiTangent is the "real" bitangent and thus may not be perpendicular to fvTangent.+ // However, both are perpendicular to the vertex normal.+ // For normal maps it is sufficient to use the following simplified version of the bitangent which is generated at pixel/vertex level.+ // fSign = bIsOrientationPreserving ? 1.0f : (-1.0f);+ // bitangent = fSign * cross(vN, tangent);+ // Note that the results are returned unindexed. It is possible to generate a new index list+ // But averaging/overwriting tangent spaces by using an already existing index list WILL produce INCRORRECT results.+ // DO NOT! use an already existing index list.+ void (*m_setTSpace)(const SMikkTSpaceContext * pContext, const float fvTangent[], const float fvBiTangent[], const float fMagS, const float fMagT,+ const tbool bIsOrientationPreserving, const int iFace, const int iVert);+} SMikkTSpaceInterface;++struct SMikkTSpaceContext+{+ SMikkTSpaceInterface * m_pInterface; // initialized with callback functions+ void * m_pUserData; // pointer to client side mesh data etc. (passed as the first parameter with every interface call)+};++// these are both thread safe!+tbool genTangSpaceDefault(const SMikkTSpaceContext * pContext); // Default (recommended) fAngularThreshold is 180 degrees (which means threshold disabled)+tbool genTangSpace(const SMikkTSpaceContext * pContext, const float fAngularThreshold);+++// To avoid visual errors (distortions/unwanted hard edges in lighting), when using sampled normal maps, the+// normal map sampler must use the exact inverse of the pixel shader transformation.+// The most efficient transformation we can possibly do in the pixel shader is+// achieved by using, directly, the "unnormalized" interpolated tangent, bitangent and vertex normal: vT, vB and vN.+// pixel shader (fast transform out)+// vNout = normalize( vNt.x * vT + vNt.y * vB + vNt.z * vN );+// where vNt is the tangent space normal. The normal map sampler must likewise use the+// interpolated and "unnormalized" tangent, bitangent and vertex normal to be compliant with the pixel shader.+// sampler does (exact inverse of pixel shader):+// float3 row0 = cross(vB, vN);+// float3 row1 = cross(vN, vT);+// float3 row2 = cross(vT, vB);+// float fSign = dot(vT, row0)<0 ? -1 : 1;+// vNt = normalize( fSign * float3(dot(vNout,row0), dot(vNout,row1), dot(vNout,row2)) );+// where vNout is the sampled normal in some chosen 3D space.+//+// Should you choose to reconstruct the bitangent in the pixel shader instead+// of the vertex shader, as explained earlier, then be sure to do this in the normal map sampler also.+// Finally, beware of quad triangulations. If the normal map sampler doesn't use the same triangulation of+// quads as your renderer then problems will occur since the interpolated tangent spaces will differ+// eventhough the vertex level tangent spaces match. This can be solved either by triangulating before+// sampling/exporting or by using the order-independent choice of diagonal for splitting quads suggested earlier.+// However, this must be used both by the sampler and your tools/rendering pipeline.++#ifdef __cplusplus+}+#endif++#endif