Momentum
A library for solving nonlinear optimization problems related to human body kinematics
Loading...
Searching...
No Matches
texture_classification.cpp
Go to the documentation of this file.
1/*
2 * Copyright (c) Meta Platforms, Inc. and affiliates.
3 *
4 * This source code is licensed under the MIT license found in the
5 * LICENSE file in the root directory of this source tree.
6 */
7
9
11
13
14#include <algorithm>
15#include <cmath>
16#include <unordered_map>
17#include <unordered_set>
18
19namespace momentum {
20
21namespace {
22
23struct BarycentricCoord {
24 float u;
25 float v;
26 float w;
27};
28
29std::vector<BarycentricCoord> getSamplePoints(int32_t numSamples) {
30 // The three triangle corners.
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};
34
35 constexpr float third = 1.0f / 3.0f;
36 constexpr BarycentricCoord centroid{third, third, third};
37
38 // Edge midpoints.
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};
42
43 // Interior points biased 75% toward each corner (the other two coords each get 12.5%).
44 // Note: `quarter * 0.5f` = 0.125, so each interior point sums to 1.0 (0.75 + 0.125 + 0.125).
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};
50
51 switch (numSamples) {
52 case 1:
53 return {centroid};
54 case 3:
55 return {v0, v1, v2};
56 case 4:
57 return {centroid, v0, v1, v2};
58 case 6:
59 return {v0, v1, v2, mid01, mid12, mid02};
60 case 7:
61 return {centroid, v0, v1, v2, mid01, mid12, mid02};
62 case 10:
63 return {centroid, v0, v1, v2, mid01, mid12, mid02, int0, int1, int2};
64 }
65 MT_THROW("Invalid num_samples value {}. Must be one of: 1, 3, 4, 6, 7, 10.", numSamples);
66}
67
68// Packs an RGB triple into a single integer key (R in bits 0-7, G in 8-15, B in 16-23) so it
69// can be used as the key in unordered_map / unordered_set lookups against region colors.
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);
72}
73
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;
80 }
81 return lookup;
82}
83
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;
89 result.insert(
90 packRgb(ptr[0 * colors.stride1], ptr[1 * colors.stride1], ptr[2 * colors.stride1]));
91 }
92 return result;
93}
94
95} // namespace
96
97std::vector<std::vector<int32_t>> classifyTrianglesByTexture(
98 const Mesh& mesh,
99 const TextureView& texture,
100 const RegionColorsView& regionColors,
101 float threshold,
102 int32_t numSamples) {
103 MT_THROW_IF(mesh.texcoords.empty(), "Mesh must have texture coordinates");
104 MT_THROW_IF(mesh.texcoord_faces.empty(), "Mesh must have texture coordinate faces");
105 MT_THROW_IF(threshold < 0.0f || threshold > 1.0f, "threshold must be in range [0, 1]");
106
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;
112
113 // threshold == 0 is treated as "any single sample is enough"; otherwise we ceil so a fractional
114 // threshold like 0.5 with 3 samples requires 2 (not 1) matching samples.
115 const int32_t minSamplesNeeded = (threshold == 0.0f)
116 ? 1
117 : static_cast<int32_t>(std::ceil(threshold * static_cast<float>(nSamples)));
118
119 std::vector<std::vector<int32_t>> regionTriangles(nRegions);
120 std::vector<int32_t> regionCounts(nRegions, 0);
121
122 for (int64_t triIdx = 0; triIdx < nTriangles; ++triIdx) {
123 std::fill(regionCounts.begin(), regionCounts.end(), 0);
124
125 const auto& texFace = mesh.texcoord_faces[triIdx];
126 const auto& uv0 = mesh.texcoords[texFace.x()];
127 const auto& uv1 = mesh.texcoords[texFace.y()];
128 const auto& uv2 = mesh.texcoords[texFace.z()];
129
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();
133
134 const auto col = std::clamp(
135 static_cast<int64_t>(std::lround(u * static_cast<float>(texture.width - 1))),
136 int64_t{0},
137 texture.width - 1);
138 const auto row = std::clamp(
139 static_cast<int64_t>(std::lround(v * static_cast<float>(texture.height - 1))),
140 int64_t{0},
141 texture.height - 1);
142
143 const auto* pixel = texture.data + row * texture.stride0 + col * texture.stride1;
144 const auto packedColor = packRgb(
145 pixel[0 * texture.stride2], pixel[1 * texture.stride2], pixel[2 * texture.stride2]);
146
147 auto it = colorLookup.find(packedColor);
148 if (it != colorLookup.end() && it->second >= 0 && it->second < nRegions) {
149 ++regionCounts[it->second];
150 }
151 }
152
153 for (int32_t regionIdx = 0; regionIdx < nRegions; ++regionIdx) {
154 if (regionCounts[regionIdx] >= minSamplesNeeded) {
155 regionTriangles[regionIdx].push_back(static_cast<int32_t>(triIdx));
156 }
157 }
158 }
159
160 return regionTriangles;
161}
162
163namespace {
164
165struct TextureSampler {
166 const TextureView& tex;
167 std::unordered_set<size_t> insideColors;
168
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))),
172 int64_t{0},
173 tex.width - 1);
174 const auto row = std::clamp(
175 static_cast<int64_t>(std::lround(uv.y() * static_cast<float>(tex.height - 1))),
176 int64_t{0},
177 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;
181 }
182
183 // Binary search along the UV segment uvA->uvB for the parameter t at which the sample
184 // transitions from inside (lo) to outside (hi). Caller must pass a segment where uvA is
185 // inside and uvB is outside; otherwise the returned t is meaningless.
186 float findCrossingT(const Eigen::Vector2f& uvA, const Eigen::Vector2f& uvB, int32_t numSteps)
187 const {
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)) {
193 lo = mid;
194 } else {
195 hi = mid;
196 }
197 }
198 return 0.5f * (lo + hi);
199 }
200};
201
202// Undirected edge represented by (smaller, larger) vertex index so {a,b} and {b,a} hash equally.
203using Edge = std::pair<int, int>;
204
205Edge makeEdge(int v1, int v2) {
206 return v1 < v2 ? Edge{v1, v2} : Edge{v2, v1};
207}
208
209struct HashEdge {
210 std::size_t operator()(const Edge& e) const {
211 // boost::hash_combine recipe: 0x9e3779b9 is the golden-ratio constant chosen to spread bits.
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));
215 }
216};
217
218struct GeomCacheEntry {
219 int vertexIndex;
220 float t;
221};
222
223// Returns the crossing parameter t in [0, 1] along the edge (geomV0 -> geomV1) such that
224// uv0 + t*(uv1 - uv0) lies on the region boundary. The cached t is always stored with respect to
225// the canonical orientation (smaller-index -> larger-index); we flip to (1 - t) when the caller's
226// orientation is reversed. If the cache misses, we orient the binary search so it always runs
227// inside -> outside (the precondition findCrossingT requires).
228float findEdgeCrossingT(
229 const TextureSampler& sampler,
230 const Eigen::Vector2f& uv0,
231 const Eigen::Vector2f& uv1,
232 int geomV0,
233 int geomV1,
234 bool v0IsInside,
235 const std::unordered_map<Edge, GeomCacheEntry, HashEdge>& geomCache,
236 int32_t numSteps) {
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);
242 }
243 if (v0IsInside) {
244 return sampler.findCrossingT(uv0, uv1, numSteps);
245 }
246 return 1.0f - sampler.findCrossingT(uv1, uv0, numSteps);
247}
248
249template <typename GetOrCreateGeomVertexFn, typename GetOrCreateTexVertexFn>
250void processMixedFace(
251 const Eigen::Vector3i& face,
252 const Eigen::Vector3i& texFace,
253 const std::array<bool, 3>& inside,
254 int nInside,
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) {
263 // Find the "solo" corner -- the lone inside vertex when nInside==1, or the lone outside vertex
264 // when nInside==2. We then re-index the triangle so k0=solo, k1/k2=the other two corners,
265 // making the two edges to clip always (k0->k1) and (k0->k2).
266 int solo = -1;
267 for (int k = 0; k < 3; ++k) {
268 if ((nInside == 1 && inside[k]) || (nInside == 2 && !inside[k])) {
269 solo = k;
270 break;
271 }
272 }
273
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];
277
278 // After reindexing, V0 is inside iff there was exactly one inside vertex (the solo case).
279 const bool v0IsInside = (nInside == 1);
280 const float t01 = findEdgeCrossingT(
281 sampler,
282 meshTexcoords[tV0],
283 meshTexcoords[tV1],
284 gV0,
285 gV1,
286 v0IsInside,
287 geomCache,
288 numBinarySearchSteps);
289 const float t02 = findEdgeCrossingT(
290 sampler,
291 meshTexcoords[tV0],
292 meshTexcoords[tV2],
293 gV0,
294 gV2,
295 v0IsInside,
296 geomCache,
297 numBinarySearchSteps);
298
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);
303
304 if (nInside == 1) {
305 // One inside corner: emit the single inside sub-triangle (V0, M01, M02).
306 newFaces.emplace_back(gV0, gM01, gM02);
307 newTexcoordFaces.emplace_back(tV0, tM01, tM02);
308 } else {
309 // Two inside corners: emit the inside quadrilateral as two triangles. The diagonal goes
310 // from V2 to M01 to keep both sub-triangles consistently wound with the original face.
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);
315 }
316}
317
318} // namespace
319
321 const Mesh& mesh,
322 const TextureView& texture,
323 const RegionColorsView& regionColors,
324 int32_t numBinarySearchSteps) {
325 MT_THROW_IF(mesh.texcoords.empty(), "Mesh must have texture coordinates");
326 MT_THROW_IF(mesh.texcoord_faces.empty(), "Mesh must have texture coordinate faces");
328 mesh.faces.size() != mesh.texcoord_faces.size(),
329 "faces and texcoord_faces must have the same size");
330
331 TextureSampler sampler{texture, buildInsideColorSet(regionColors)};
332
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]);
337 }
338
339 auto vertices = mesh.vertices;
340 auto normals = mesh.normals;
341 auto colors = mesh.colors;
342 auto confidence = mesh.confidence;
343 auto texcoords = mesh.texcoords;
344
345 std::vector<Eigen::Vector3i> newFaces;
346 std::vector<Eigen::Vector3i> newTexcoordFaces;
347 newFaces.reserve(mesh.faces.size());
348 newTexcoordFaces.reserve(mesh.faces.size());
349
350 std::unordered_map<Edge, GeomCacheEntry, HashEdge> geomCache;
351 std::unordered_map<Edge, int, HashEdge> texCache;
352
353 const bool hasNormals = !normals.empty();
354 const bool hasColors = !colors.empty();
355 const bool hasConfidence = !confidence.empty();
356
357 // Lazily mints (or reuses) a vertex along edge (geomA, geomB) at parameter t. The cached
358 // tOriented is always relative to the canonical (smaller -> larger) edge direction so the same
359 // boundary vertex is shared between the two faces incident to the edge, preserving a watertight
360 // split mesh.
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;
366 }
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]);
371 if (hasNormals) {
372 Eigen::Vector3f n =
373 ((1.0f - tOriented) * normals[edge.first] + tOriented * normals[edge.second])
374 .normalized();
375 normals.emplace_back(n);
376 }
377 if (hasColors) {
378 Eigen::Vector3f cf = (1.0f - tOriented) * colors[edge.first].cast<float>() +
379 tOriented * colors[edge.second].cast<float>();
380 colors.emplace_back(
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)));
384 }
385 if (hasConfidence) {
386 confidence.emplace_back(
387 (1.0f - tOriented) * confidence[edge.first] + tOriented * confidence[edge.second]);
388 }
389 geomCache[edge] = {newIdx, tOriented};
390 return newIdx;
391 };
392
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()) {
397 return it->second;
398 }
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;
404 return newIdx;
405 };
406
407 for (size_t fi = 0; fi < mesh.faces.size(); ++fi) {
408 const auto& face = mesh.faces[fi];
409 const auto& texFace = mesh.texcoord_faces[fi];
410
411 std::array<bool, 3> inside = {
412 texVertInside[texFace.x()], texVertInside[texFace.y()], texVertInside[texFace.z()]};
413 const int nInside =
414 static_cast<int>(inside[0]) + static_cast<int>(inside[1]) + static_cast<int>(inside[2]);
415
416 if (nInside == 3) {
417 newFaces.push_back(face);
418 newTexcoordFaces.push_back(texFace);
419 } else if (nInside > 0) {
420 processMixedFace(
421 face,
422 texFace,
423 inside,
424 nInside,
425 mesh.texcoords,
426 sampler,
427 numBinarySearchSteps,
428 geomCache,
429 getOrCreateGeomVertex,
430 getOrCreateTexVertex,
431 newFaces,
432 newTexcoordFaces);
433 }
434 }
435
436 Mesh result;
437 result.vertices = std::move(vertices);
438 result.normals = std::move(normals);
439 result.colors = std::move(colors);
440 result.confidence = std::move(confidence);
441 result.texcoords = std::move(texcoords);
442 result.faces = std::move(newFaces);
443 result.texcoord_faces = std::move(newTexcoordFaces);
444
445 if (result.faces.empty()) {
446 return Mesh{};
447 }
448
449 std::vector<bool> activeFaces(result.faces.size(), true);
450 return reduceMeshByFaces<float>(result, activeFaces);
451}
452
453} // namespace momentum
#define MT_THROW(...)
Throws a std::runtime_error with a formatted message.
Definition exception.h:31
#define MT_THROW_IF(Condition,...)
Conditionally throws a std::runtime_error with a formatted message if the condition is true.
Definition exception.h:55
std::vector< std::vector< int32_t > > classifyTrianglesByTexture(const Mesh &mesh, const TextureView &texture, const RegionColorsView &regionColors, 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)
MeshT< float > Mesh
Definition fwd.h:20
Mesh splitMeshByTextureRegion(const Mesh &mesh, const TextureView &texture, const RegionColorsView &regionColors, 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.
Definition mesh.h:55
std::vector< Eigen::Vector2f > texcoords
List of texture coordinates (UV coordinates).
Definition mesh.h:51
std::vector< T > confidence
List of per-vertex confidence values Higher values typically indicate higher confidence in the vertex...
Definition mesh.h:39
std::vector< Eigen::Vector3< T > > vertices
List of mesh vertices in 3D space.
Definition mesh.h:22
std::vector< Eigen::Vector3< T > > normals
List of vertex normals (same size as vertices when computed).
Definition mesh.h:25
std::vector< Eigen::Vector3i > faces
List of triangular faces defined by vertex indices.
Definition mesh.h:28
std::vector< Eigen::Vector3b > colors
List of per-vertex RGB colors (0-255 for each channel).
Definition mesh.h:35
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.