16#include <unordered_map>
17#include <unordered_set>
23struct BarycentricCoord {
29std::vector<BarycentricCoord> getSamplePoints(int32_t numSamples) {
31 constexpr BarycentricCoord v0{1.0f, 0.0f, 0.0f};
32 constexpr BarycentricCoord v1{0.0f, 1.0f, 0.0f};
33 constexpr BarycentricCoord v2{0.0f, 0.0f, 1.0f};
35 constexpr float third = 1.0f / 3.0f;
36 constexpr BarycentricCoord centroid{third, third, third};
39 constexpr BarycentricCoord mid01{0.5f, 0.5f, 0.0f};
40 constexpr BarycentricCoord mid12{0.0f, 0.5f, 0.5f};
41 constexpr BarycentricCoord mid02{0.5f, 0.0f, 0.5f};
45 constexpr float quarter = 0.25f;
46 constexpr float threeQuarters = 0.75f;
47 constexpr BarycentricCoord int0{threeQuarters, quarter * 0.5f, quarter * 0.5f};
48 constexpr BarycentricCoord int1{quarter * 0.5f, threeQuarters, quarter * 0.5f};
49 constexpr BarycentricCoord int2{quarter * 0.5f, quarter * 0.5f, threeQuarters};
57 return {centroid, v0, v1, v2};
59 return {v0, v1, v2, mid01, mid12, mid02};
61 return {centroid, v0, v1, v2, mid01, mid12, mid02};
63 return {centroid, v0, v1, v2, mid01, mid12, mid02, int0, int1, int2};
65 MT_THROW(
"Invalid num_samples value {}. Must be one of: 1, 3, 4, 6, 7, 10.", numSamples);
70inline size_t packRgb(uint8_t r, uint8_t g, uint8_t b) {
71 return static_cast<size_t>(r) | (
static_cast<size_t>(g) << 8) | (
static_cast<size_t>(b) << 16);
74std::unordered_map<size_t, int32_t> buildColorLookup(
const RegionColorsView& colors) {
75 std::unordered_map<size_t, int32_t> lookup;
76 lookup.reserve(colors.nRegions);
77 for (int32_t i = 0; i < colors.nRegions; ++i) {
78 const uint8_t* ptr = colors.data + i * colors.stride0;
79 lookup[packRgb(ptr[0 * colors.stride1], ptr[1 * colors.stride1], ptr[2 * colors.stride1])] = i;
84std::unordered_set<size_t> buildInsideColorSet(
const RegionColorsView& colors) {
85 std::unordered_set<size_t> result;
86 result.reserve(colors.nRegions);
87 for (int32_t i = 0; i < colors.nRegions; ++i) {
88 const uint8_t* ptr = colors.data + i * colors.stride0;
90 packRgb(ptr[0 * colors.stride1], ptr[1 * colors.stride1], ptr[2 * colors.stride1]));
102 int32_t numSamples) {
105 MT_THROW_IF(threshold < 0.0f || threshold > 1.0f,
"threshold must be in range [0, 1]");
107 const auto samplePoints = getSamplePoints(numSamples);
108 const auto nSamples =
static_cast<int32_t
>(samplePoints.size());
109 const auto colorLookup = buildColorLookup(regionColors);
110 const auto nTriangles =
static_cast<int64_t
>(mesh.
faces.size());
111 const auto nRegions = regionColors.
nRegions;
115 const int32_t minSamplesNeeded = (threshold == 0.0f)
117 :
static_cast<int32_t
>(std::ceil(threshold *
static_cast<float>(nSamples)));
119 std::vector<std::vector<int32_t>> regionTriangles(nRegions);
120 std::vector<int32_t> regionCounts(nRegions, 0);
122 for (int64_t triIdx = 0; triIdx < nTriangles; ++triIdx) {
123 std::fill(regionCounts.begin(), regionCounts.end(), 0);
126 const auto& uv0 = mesh.
texcoords[texFace.x()];
127 const auto& uv1 = mesh.
texcoords[texFace.y()];
128 const auto& uv2 = mesh.
texcoords[texFace.z()];
130 for (
const auto& bary : samplePoints) {
131 const float u = bary.u * uv0.x() + bary.v * uv1.x() + bary.w * uv2.x();
132 const float v = bary.u * uv0.y() + bary.v * uv1.y() + bary.w * uv2.y();
134 const auto col = std::clamp(
135 static_cast<int64_t
>(std::lround(u *
static_cast<float>(texture.
width - 1))),
138 const auto row = std::clamp(
139 static_cast<int64_t
>(std::lround(v *
static_cast<float>(texture.
height - 1))),
144 const auto packedColor = packRgb(
147 auto it = colorLookup.find(packedColor);
148 if (it != colorLookup.end() && it->second >= 0 && it->second < nRegions) {
149 ++regionCounts[it->second];
153 for (int32_t regionIdx = 0; regionIdx < nRegions; ++regionIdx) {
154 if (regionCounts[regionIdx] >= minSamplesNeeded) {
155 regionTriangles[regionIdx].push_back(
static_cast<int32_t
>(triIdx));
160 return regionTriangles;
165struct TextureSampler {
166 const TextureView& tex;
167 std::unordered_set<size_t> insideColors;
169 bool isInside(
const Eigen::Vector2f& uv)
const {
170 const auto col = std::clamp(
171 static_cast<int64_t
>(std::lround(uv.x() *
static_cast<float>(tex.width - 1))),
174 const auto row = std::clamp(
175 static_cast<int64_t
>(std::lround(uv.y() *
static_cast<float>(tex.height - 1))),
178 const auto* pixel = tex.data + row * tex.stride0 + col * tex.stride1;
179 return insideColors.count(
180 packRgb(pixel[0 * tex.stride2], pixel[1 * tex.stride2], pixel[2 * tex.stride2])) > 0;
186 float findCrossingT(
const Eigen::Vector2f& uvA,
const Eigen::Vector2f& uvB, int32_t numSteps)
188 float lo = 0.0f, hi = 1.0f;
189 for (int32_t i = 0; i < numSteps; ++i) {
190 const float mid = 0.5f * (lo + hi);
191 const Eigen::Vector2f uvMid = (1.0f - mid) * uvA + mid * uvB;
192 if (isInside(uvMid)) {
198 return 0.5f * (lo + hi);
203using Edge = std::pair<int, int>;
205Edge makeEdge(
int v1,
int v2) {
206 return v1 < v2 ? Edge{v1, v2} : Edge{v2, v1};
210 std::size_t operator()(
const Edge& e)
const {
212 std::size_t h1 = std::hash<int>{}(e.first);
213 std::size_t h2 = std::hash<int>{}(e.second);
214 return h1 ^ (h2 + 0x9e3779b9 + (h1 << 6) + (h1 >> 2));
218struct GeomCacheEntry {
228float findEdgeCrossingT(
229 const TextureSampler& sampler,
230 const Eigen::Vector2f& uv0,
231 const Eigen::Vector2f& uv1,
235 const std::unordered_map<Edge, GeomCacheEntry, HashEdge>& geomCache,
237 const auto edge = makeEdge(geomV0, geomV1);
238 auto it = geomCache.find(edge);
239 if (it != geomCache.end()) {
240 float tOriented = it->second.t;
241 return (geomV0 < geomV1) ? tOriented : (1.0f - tOriented);
244 return sampler.findCrossingT(uv0, uv1, numSteps);
246 return 1.0f - sampler.findCrossingT(uv1, uv0, numSteps);
249template <
typename GetOrCreateGeomVertexFn,
typename GetOrCreateTexVertexFn>
250void processMixedFace(
251 const Eigen::Vector3i& face,
252 const Eigen::Vector3i& texFace,
253 const std::array<bool, 3>& inside,
255 const std::vector<Eigen::Vector2f>& meshTexcoords,
256 const TextureSampler& sampler,
257 int32_t numBinarySearchSteps,
258 const std::unordered_map<Edge, GeomCacheEntry, HashEdge>& geomCache,
259 GetOrCreateGeomVertexFn& getOrCreateGeomVertex,
260 GetOrCreateTexVertexFn& getOrCreateTexVertex,
261 std::vector<Eigen::Vector3i>& newFaces,
262 std::vector<Eigen::Vector3i>& newTexcoordFaces) {
267 for (
int k = 0; k < 3; ++k) {
268 if ((nInside == 1 && inside[k]) || (nInside == 2 && !inside[k])) {
274 const int k0 = solo, k1 = (solo + 1) % 3, k2 = (solo + 2) % 3;
275 const int gV0 = face[k0], gV1 = face[k1], gV2 = face[k2];
276 const int tV0 = texFace[k0], tV1 = texFace[k1], tV2 = texFace[k2];
279 const bool v0IsInside = (nInside == 1);
280 const float t01 = findEdgeCrossingT(
288 numBinarySearchSteps);
289 const float t02 = findEdgeCrossingT(
297 numBinarySearchSteps);
299 const int gM01 = getOrCreateGeomVertex(gV0, gV1, t01);
300 const int gM02 = getOrCreateGeomVertex(gV0, gV2, t02);
301 const int tM01 = getOrCreateTexVertex(tV0, tV1, t01);
302 const int tM02 = getOrCreateTexVertex(tV0, tV2, t02);
306 newFaces.emplace_back(gV0, gM01, gM02);
307 newTexcoordFaces.emplace_back(tV0, tM01, tM02);
311 newFaces.emplace_back(gV1, gV2, gM01);
312 newTexcoordFaces.emplace_back(tV1, tV2, tM01);
313 newFaces.emplace_back(gV2, gM02, gM01);
314 newTexcoordFaces.emplace_back(tV2, tM02, tM01);
324 int32_t numBinarySearchSteps) {
329 "faces and texcoord_faces must have the same size");
331 TextureSampler sampler{texture, buildInsideColorSet(regionColors)};
333 const auto nTexVerts =
static_cast<int>(mesh.
texcoords.size());
334 std::vector<bool> texVertInside(nTexVerts);
335 for (
int i = 0; i < nTexVerts; ++i) {
336 texVertInside[i] = sampler.isInside(mesh.
texcoords[i]);
341 auto colors = mesh.
colors;
345 std::vector<Eigen::Vector3i> newFaces;
346 std::vector<Eigen::Vector3i> newTexcoordFaces;
347 newFaces.reserve(mesh.
faces.size());
348 newTexcoordFaces.reserve(mesh.
faces.size());
350 std::unordered_map<Edge, GeomCacheEntry, HashEdge> geomCache;
351 std::unordered_map<Edge, int, HashEdge> texCache;
353 const bool hasNormals = !normals.empty();
354 const bool hasColors = !colors.empty();
355 const bool hasConfidence = !confidence.empty();
361 auto getOrCreateGeomVertex = [&](
int geomA,
int geomB,
float t) ->
int {
362 const auto edge = makeEdge(geomA, geomB);
363 auto it = geomCache.find(edge);
364 if (it != geomCache.end()) {
365 return it->second.vertexIndex;
367 float tOriented = (geomA < geomB) ? t : (1.0f - t);
368 const int newIdx =
static_cast<int>(vertices.size());
369 vertices.emplace_back(
370 (1.0f - tOriented) * vertices[edge.first] + tOriented * vertices[edge.second]);
373 ((1.0f - tOriented) * normals[edge.first] + tOriented * normals[edge.second])
375 normals.emplace_back(n);
378 Eigen::Vector3f cf = (1.0f - tOriented) * colors[edge.first].cast<
float>() +
379 tOriented * colors[edge.second].cast<
float>();
381 static_cast<uint8_t
>(std::clamp(cf.x(), 0.0f, 255.0f)),
382 static_cast<uint8_t
>(std::clamp(cf.y(), 0.0f, 255.0f)),
383 static_cast<uint8_t
>(std::clamp(cf.z(), 0.0f, 255.0f)));
386 confidence.emplace_back(
387 (1.0f - tOriented) * confidence[edge.first] + tOriented * confidence[edge.second]);
389 geomCache[edge] = {newIdx, tOriented};
393 auto getOrCreateTexVertex = [&](
int texA,
int texB,
float t) ->
int {
394 const auto edge = makeEdge(texA, texB);
395 auto it = texCache.find(edge);
396 if (it != texCache.end()) {
399 float tOriented = (texA < texB) ? t : (1.0f - t);
400 const int newIdx =
static_cast<int>(texcoords.size());
401 texcoords.emplace_back(
402 (1.0f - tOriented) * texcoords[edge.first] + tOriented * texcoords[edge.second]);
403 texCache[edge] = newIdx;
407 for (
size_t fi = 0; fi < mesh.
faces.size(); ++fi) {
408 const auto& face = mesh.
faces[fi];
411 std::array<bool, 3> inside = {
412 texVertInside[texFace.x()], texVertInside[texFace.y()], texVertInside[texFace.z()]};
414 static_cast<int>(inside[0]) +
static_cast<int>(inside[1]) +
static_cast<int>(inside[2]);
417 newFaces.push_back(face);
418 newTexcoordFaces.push_back(texFace);
419 }
else if (nInside > 0) {
427 numBinarySearchSteps,
429 getOrCreateGeomVertex,
430 getOrCreateTexVertex,
437 result.
vertices = std::move(vertices);
438 result.
normals = std::move(normals);
439 result.
colors = std::move(colors);
442 result.
faces = std::move(newFaces);
445 if (result.
faces.empty()) {
449 std::vector<bool> activeFaces(result.
faces.size(),
true);
#define MT_THROW(...)
Throws a std::runtime_error with a formatted message.
#define MT_THROW_IF(Condition,...)
Conditionally throws a std::runtime_error with a formatted message if the condition is true.
std::vector< std::vector< int32_t > > classifyTrianglesByTexture(const Mesh &mesh, const TextureView &texture, const RegionColorsView ®ionColors, float threshold, int32_t numSamples)
Classify mesh triangles into regions based on texture colors.
template MeshT< float > reduceMeshByFaces< float >(const MeshT< float > &mesh, const std::vector< bool > &activeFaces)
Mesh splitMeshByTextureRegion(const Mesh &mesh, const TextureView &texture, const RegionColorsView ®ionColors, int32_t numBinarySearchSteps)
Split mesh triangles along texture region boundaries.
std::vector< Eigen::Vector3i > texcoord_faces
List of texture coordinate indices per face Maps each face to its corresponding texture coordinates.
std::vector< Eigen::Vector2f > texcoords
List of texture coordinates (UV coordinates).
std::vector< T > confidence
List of per-vertex confidence values Higher values typically indicate higher confidence in the vertex...
std::vector< Eigen::Vector3< T > > vertices
List of mesh vertices in 3D space.
std::vector< Eigen::Vector3< T > > normals
List of vertex normals (same size as vertices when computed).
std::vector< Eigen::Vector3i > faces
List of triangular faces defined by vertex indices.
std::vector< Eigen::Vector3b > colors
List of per-vertex RGB colors (0-255 for each channel).
View into a contiguous array of RGB region colors (non-owning).
View into a contiguous RGB texture image (non-owning).
int64_t stride2
Channel stride in bytes.
int64_t stride1
Column stride in bytes.
int64_t stride0
Row stride in bytes.