Blender V4.3
mikktspace.hh
Go to the documentation of this file.
1/* SPDX-FileCopyrightText: 2011 Morten S. Mikkelsen
2 * SPDX-FileCopyrightText: 2022 Blender Authors
3 *
4 * SPDX-License-Identifier: Apache-2.0 */
5
10#include <algorithm>
11#include <cassert>
12#include <unordered_map>
13
14#ifdef WITH_TBB
15# include <tbb/parallel_for.h>
16#endif
17
19#include "mikk_float3.hh"
20#include "mikk_util.hh"
21
22namespace mikk {
23
24static constexpr uint UNSET_ENTRY = 0xffffffffu;
25
26template<typename Mesh> class Mikktspace {
27 struct Triangle {
28 /* Stores neighboring triangle for group assignment. */
29 std::array<uint, 3> neighbor;
30 /* Stores assigned group of each vertex. */
31 std::array<uint, 3> group;
32 /* Stores vertex indices that make up the triangle. */
33 std::array<uint, 3> vertices;
34
35 /* Computed face tangent, will be accumulated into group. */
36 float3 tangent;
37
38 /* Index of the face that this triangle belongs to. */
39 uint faceIdx;
40 /* Index of the first of this triangle's vertices' TSpaces. */
41 uint tSpaceIdx;
42
43 /* Stores mapping from this triangle's vertices to the original
44 * face's vertices (relevant for quads). */
45 std::array<uint8_t, 3> faceVertex;
46
47 // flags
48 bool markDegenerate : 1;
49 bool quadOneDegenTri : 1;
50 bool groupWithAny : 1;
51 bool orientPreserving : 1;
52
53 Triangle(uint faceIdx_, uint tSpaceIdx_)
54 : tangent{0.0f},
55 faceIdx{faceIdx_},
56 tSpaceIdx{tSpaceIdx_},
57 markDegenerate{false},
58 quadOneDegenTri{false},
59 groupWithAny{true},
60 orientPreserving{false}
61 {
62 neighbor.fill(UNSET_ENTRY);
63 group.fill(UNSET_ENTRY);
64 }
65
66 void setVertices(uint8_t i0, uint8_t i1, uint8_t i2)
67 {
68 faceVertex[0] = i0;
69 faceVertex[1] = i1;
70 faceVertex[2] = i2;
71 vertices[0] = pack_index(faceIdx, i0);
72 vertices[1] = pack_index(faceIdx, i1);
73 vertices[2] = pack_index(faceIdx, i2);
74 }
75 };
76
77 struct Group {
78 float3 tangent;
79 uint vertexRepresentative;
80 bool orientPreserving;
81
82 Group(uint vertexRepresentative_, bool orientPreserving_)
83 : tangent{0.0f},
84 vertexRepresentative{vertexRepresentative_},
85 orientPreserving{orientPreserving_}
86 {
87 }
88
89 void normalizeTSpace()
90 {
91 tangent = tangent.normalize();
92 }
93
94 void accumulateTSpaceAtomic(float3 v_tangent)
95 {
96 float_add_atomic(&tangent.x, v_tangent.x);
97 float_add_atomic(&tangent.y, v_tangent.y);
98 float_add_atomic(&tangent.z, v_tangent.z);
99 }
100
101 void accumulateTSpace(float3 v_tangent)
102 {
103 tangent += v_tangent;
104 }
105 };
106
107 struct TSpace {
108 float3 tangent = float3(1.0f, 0.0f, 0.0f);
109 uint counter = 0;
110 bool orientPreserving = false;
111
112 void accumulateGroup(const Group &group)
113 {
114 assert(counter < 2);
115
116 if (counter == 0) {
117 tangent = group.tangent;
118 }
119 else if (tangent == group.tangent) {
120 // this if is important. Due to floating point precision
121 // averaging when ts0==ts1 will cause a slight difference
122 // which results in tangent space splits later on, so do nothing
123 }
124 else {
125 tangent = (tangent + group.tangent).normalize();
126 }
127
128 counter++;
129 orientPreserving = group.orientPreserving;
130 }
131 };
132
133 Mesh &mesh;
134
135 std::vector<Triangle> triangles;
136 std::vector<TSpace> tSpaces;
137 std::vector<Group> groups;
138
139 uint nrTSpaces, nrFaces, nrTriangles, totalTriangles;
140
141 int nrThreads;
142 bool isParallel;
143
144 public:
145 Mikktspace(Mesh &mesh_) : mesh(mesh_) {}
146
148 {
149 nrFaces = uint(mesh.GetNumFaces());
150
151#ifdef WITH_TBB
152 nrThreads = tbb::this_task_arena::max_concurrency();
153 isParallel = (nrThreads > 1) && (nrFaces > 10000);
154#else
155 nrThreads = 1;
156 isParallel = false;
157#endif
158
159 // make an initial triangle --> face index list
161
162 if (nrTriangles == 0) {
163 return;
164 }
165
166 // make a welded index list of identical positions and attributes (pos, norm, texc)
168
169 // mark all triangle pairs that belong to a quad with only one
170 // good triangle. These need special treatment in degenEpilogue().
171 // Additionally, move all good triangles to the start of
172 // triangles[] without changing order and
173 // put the degenerate triangles last.
175
176 if (nrTriangles == 0) {
177 // No point in building tangents if there are no non-degenerate triangles, so just zero them
178 tSpaces.resize(nrTSpaces);
179 }
180 else {
181 // evaluate triangle level attributes and neighbor list
182 initTriangle();
183
184 // match up edge pairs
186
187 // based on the 4 rules, identify groups based on connectivity
189
190 // make tspaces, each group is split up into subgroups.
191 // Finally a tangent space is made for every resulting subgroup
193
194 // degenerate quads with one good triangle will be fixed by copying a space from
195 // the good triangle to the coinciding vertex.
196 // all other degenerate triangles will just copy a space from any good triangle
197 // with the same welded index in vertices[].
199 }
200
201 uint index = 0;
202 for (uint f = 0; f < nrFaces; f++) {
203 const uint verts = mesh.GetNumVerticesOfFace(f);
204 if (verts != 3 && verts != 4) {
205 continue;
206 }
207
208 // set data
209 for (uint i = 0; i < verts; i++) {
210 const TSpace &tSpace = tSpaces[index++];
211 mesh.SetTangentSpace(f, i, tSpace.tangent, tSpace.orientPreserving);
212 }
213 }
214 }
215
216 protected:
217 template<typename F> void runParallel(uint start, uint end, F func)
218 {
219#ifdef WITH_TBB
220 if (isParallel) {
221 tbb::parallel_for(start, end, func);
222 }
223 else
224#endif
225 {
226 for (uint i = start; i < end; i++) {
227 func(i);
228 }
229 }
230 }
231
234
236 {
237 uint f, v;
238 unpack_index(f, v, vertexID);
239 return mesh.GetPosition(f, v);
240 }
241
243 {
244 uint f, v;
245 unpack_index(f, v, vertexID);
246 return mesh.GetNormal(f, v);
247 }
248
250 {
251 uint f, v;
252 unpack_index(f, v, vertexID);
253 return mesh.GetTexCoord(f, v);
254 }
255
258
260 {
261 nrTriangles = 0;
262 for (uint f = 0; f < nrFaces; f++) {
263 const uint verts = mesh.GetNumVerticesOfFace(f);
264 if (verts == 3) {
265 nrTriangles += 1;
266 }
267 else if (verts == 4) {
268 nrTriangles += 2;
269 }
270 }
271
272 triangles.reserve(nrTriangles);
273
274 nrTSpaces = 0;
275 for (uint f = 0; f < nrFaces; f++) {
276 const uint verts = mesh.GetNumVerticesOfFace(f);
277 if (verts != 3 && verts != 4) {
278 continue;
279 }
280
281 uint tA = uint(triangles.size());
282 triangles.emplace_back(f, nrTSpaces);
283 Triangle &triA = triangles[tA];
284
285 if (verts == 3) {
286 triA.setVertices(0, 1, 2);
287 }
288 else {
289 uint tB = uint(triangles.size());
290 triangles.emplace_back(f, nrTSpaces);
291 Triangle &triB = triangles[tB];
292
293 // need an order independent way to evaluate
294 // tspace on quads. This is done by splitting
295 // along the shortest diagonal.
296 float distSQ_02 = (mesh.GetTexCoord(f, 2) - mesh.GetTexCoord(f, 0)).length_squared();
297 float distSQ_13 = (mesh.GetTexCoord(f, 3) - mesh.GetTexCoord(f, 1)).length_squared();
298 bool quadDiagIs_02;
299 if (distSQ_02 != distSQ_13) {
300 quadDiagIs_02 = (distSQ_02 < distSQ_13);
301 }
302 else {
303 distSQ_02 = (mesh.GetPosition(f, 2) - mesh.GetPosition(f, 0)).length_squared();
304 distSQ_13 = (mesh.GetPosition(f, 3) - mesh.GetPosition(f, 1)).length_squared();
305 quadDiagIs_02 = !(distSQ_13 < distSQ_02);
306 }
307
308 if (quadDiagIs_02) {
309 triA.setVertices(0, 1, 2);
310 triB.setVertices(0, 2, 3);
311 }
312 else {
313 triA.setVertices(0, 1, 3);
314 triB.setVertices(1, 2, 3);
315 }
316 }
317
318 nrTSpaces += verts;
319 }
320 }
321
322 struct VertexHash {
324 inline uint operator()(const uint &k) const
325 {
326 return hash_float3x3(mikk->getPosition(k), mikk->getNormal(k), mikk->getTexCoord(k));
327 }
328 };
329
330 struct VertexEqual {
332 inline bool operator()(const uint &kA, const uint &kB) const
333 {
334 return mikk->getTexCoord(kA) == mikk->getTexCoord(kB) &&
335 mikk->getNormal(kA) == mikk->getNormal(kB) &&
336 mikk->getPosition(kA) == mikk->getPosition(kB);
337 }
338 };
339
340 /* Merge identical vertices.
341 * To find vertices with identical position, normal and texcoord, we calculate a hash of the 9
342 * values. Then, by sorting based on that hash, identical elements (having identical hashes) will
343 * be moved next to each other. Since there might be hash collisions, the elements of each block
344 * are then compared with each other and duplicates are merged.
345 */
346 template<bool isAtomic> void generateSharedVerticesIndexList_impl()
347 {
348 uint numVertices = nrTriangles * 3;
350 runParallel(0u, nrTriangles, [&](uint t) {
351 for (uint i = 0; i < 3; i++) {
352 auto res = set.emplace(triangles[t].vertices[i]);
353 if (!res.second) {
354 triangles[t].vertices[i] = res.first;
355 }
356 }
357 });
358 }
360 {
361 if (isParallel) {
363 }
364 else {
366 }
367 }
368
371
373 {
374 // Mark all degenerate triangles
375 totalTriangles = nrTriangles;
376 std::atomic<uint> degenTriangles(0);
377 runParallel(0u, totalTriangles, [&](uint t) {
378 const float3 p0 = getPosition(triangles[t].vertices[0]);
379 const float3 p1 = getPosition(triangles[t].vertices[1]);
380 const float3 p2 = getPosition(triangles[t].vertices[2]);
381 if (p0 == p1 || p0 == p2 || p1 == p2) // degenerate
382 {
383 triangles[t].markDegenerate = true;
384 degenTriangles.fetch_add(1);
385 }
386 });
387 nrTriangles -= degenTriangles.load();
388
389 if (totalTriangles == nrTriangles) {
390 return;
391 }
392
393 // locate quads with only one good triangle
394 runParallel(0u, totalTriangles - 1, [&](uint t) {
395 Triangle &triangleA = triangles[t], &triangleB = triangles[t + 1];
396 if (triangleA.faceIdx != triangleB.faceIdx) {
397 /* Individual triangle, skip. */
398 return;
399 }
400 if (triangleA.markDegenerate != triangleB.markDegenerate) {
401 triangleA.quadOneDegenTri = true;
402 triangleB.quadOneDegenTri = true;
403 }
404 });
405
406 std::stable_partition(triangles.begin(), triangles.end(), [](const Triangle &tri) {
407 return !tri.markDegenerate;
408 });
409 }
410
412 {
413 if (nrTriangles == totalTriangles) {
414 return;
415 }
416
417 std::unordered_map<uint, uint> goodTriangleMap;
418 for (uint t = 0; t < nrTriangles; t++) {
419 for (uint i = 0; i < 3; i++) {
420 goodTriangleMap.emplace(triangles[t].vertices[i], pack_index(t, i));
421 }
422 }
423
424 // deal with degenerate triangles
425 // punishment for degenerate triangles is O(nrTriangles) extra memory.
426 for (uint t = nrTriangles; t < totalTriangles; t++) {
427 // degenerate triangles on a quad with one good triangle are skipped
428 // here but processed in the next loop
429 if (triangles[t].quadOneDegenTri) {
430 continue;
431 }
432
433 for (uint i = 0; i < 3; i++) {
434 const auto entry = goodTriangleMap.find(triangles[t].vertices[i]);
435 if (entry == goodTriangleMap.end()) {
436 // Matching vertex from good triangle is not found.
437 continue;
438 }
439
440 uint tSrc, iSrc;
441 unpack_index(tSrc, iSrc, entry->second);
442 const uint iSrcVert = triangles[tSrc].faceVertex[iSrc];
443 const uint iSrcOffs = triangles[tSrc].tSpaceIdx;
444 const uint iDstVert = triangles[t].faceVertex[i];
445 const uint iDstOffs = triangles[t].tSpaceIdx;
446 // copy tspace
447 tSpaces[iDstOffs + iDstVert] = tSpaces[iSrcOffs + iSrcVert];
448 }
449 }
450
451 // deal with degenerate quads with one good triangle
452 for (uint t = 0; t < nrTriangles; t++) {
453 // this triangle belongs to a quad where the
454 // other triangle is degenerate
455 if (!triangles[t].quadOneDegenTri) {
456 continue;
457 }
458 uint vertFlag = (1u << triangles[t].faceVertex[0]) | (1u << triangles[t].faceVertex[1]) |
459 (1u << triangles[t].faceVertex[2]);
460 uint missingFaceVertex = 0;
461 if ((vertFlag & 2) == 0) {
462 missingFaceVertex = 1;
463 }
464 else if ((vertFlag & 4) == 0) {
465 missingFaceVertex = 2;
466 }
467 else if ((vertFlag & 8) == 0) {
468 missingFaceVertex = 3;
469 }
470
471 uint faceIdx = triangles[t].faceIdx;
472 float3 dstP = mesh.GetPosition(faceIdx, missingFaceVertex);
473 bool found = false;
474 for (uint i = 0; i < 3; i++) {
475 const uint faceVertex = triangles[t].faceVertex[i];
476 const float3 srcP = mesh.GetPosition(faceIdx, faceVertex);
477 if (srcP == dstP) {
478 const uint offset = triangles[t].tSpaceIdx;
479 tSpaces[offset + missingFaceVertex] = tSpaces[offset + faceVertex];
480 found = true;
481 break;
482 }
483 }
484 assert(found);
485 (void)found;
486 }
487 }
488
491
492 // returns the texture area times 2
493 float calcTexArea(uint tri)
494 {
495 const float3 t1 = getTexCoord(triangles[tri].vertices[0]);
496 const float3 t2 = getTexCoord(triangles[tri].vertices[1]);
497 const float3 t3 = getTexCoord(triangles[tri].vertices[2]);
498
499 const float t21x = t2.x - t1.x;
500 const float t21y = t2.y - t1.y;
501 const float t31x = t3.x - t1.x;
502 const float t31y = t3.y - t1.y;
503
504 const float signedAreaSTx2 = t21x * t31y - t21y * t31x;
505 return fabsf(signedAreaSTx2);
506 }
507
509 {
510 // triangles[f].iFlag is cleared in generateInitialVerticesIndexList()
511 // which is called before this function.
512
513 // evaluate first order derivatives
514 runParallel(0u, nrTriangles, [&](uint t) {
515 Triangle &triangle = triangles[t];
516
517 // initial values
518 const float3 v1 = getPosition(triangle.vertices[0]);
519 const float3 v2 = getPosition(triangle.vertices[1]);
520 const float3 v3 = getPosition(triangle.vertices[2]);
521 const float3 t1 = getTexCoord(triangle.vertices[0]);
522 const float3 t2 = getTexCoord(triangle.vertices[1]);
523 const float3 t3 = getTexCoord(triangle.vertices[2]);
524
525 const float t21x = t2.x - t1.x;
526 const float t21y = t2.y - t1.y;
527 const float t31x = t3.x - t1.x;
528 const float t31y = t3.y - t1.y;
529 const float3 d1 = v2 - v1, d2 = v3 - v1;
530
531 const float signedAreaSTx2 = t21x * t31y - t21y * t31x;
532 const float3 vOs = (t31y * d1) - (t21y * d2); // eq 18
533 const float3 vOt = (-t31x * d1) + (t21x * d2); // eq 19
534
535 triangle.orientPreserving = (signedAreaSTx2 > 0);
536
537 if (not_zero(signedAreaSTx2)) {
538 const float lenOs2 = vOs.length_squared();
539 const float lenOt2 = vOt.length_squared();
540 const float fS = triangle.orientPreserving ? 1.0f : (-1.0f);
541 if (not_zero(lenOs2)) {
542 triangle.tangent = vOs * (fS / sqrtf(lenOs2));
543 }
544
545 // if this is a good triangle
546 if (not_zero(lenOs2) && not_zero(lenOt2)) {
547 triangle.groupWithAny = false;
548 }
549 }
550 });
551
552 // force otherwise healthy quads to a fixed orientation
553 runParallel(0u, nrTriangles - 1, [&](uint t) {
554 Triangle &triangleA = triangles[t], &triangleB = triangles[t + 1];
555 if (triangleA.faceIdx != triangleB.faceIdx) {
556 // this is not a quad
557 return;
558 }
559
560 // bad triangles should already have been removed by
561 // degenPrologue(), but just in case check that neither are degenerate
562 if (!(triangleA.markDegenerate || triangleB.markDegenerate)) {
563 // if this happens the quad has extremely bad mapping!!
564 if (triangleA.orientPreserving != triangleB.orientPreserving) {
565 bool chooseOrientFirstTri = false;
566 if (triangleB.groupWithAny) {
567 chooseOrientFirstTri = true;
568 }
569 else if (calcTexArea(t) >= calcTexArea(t + 1)) {
570 chooseOrientFirstTri = true;
571 }
572
573 // force match
574 const uint t0 = chooseOrientFirstTri ? t : (t + 1);
575 const uint t1 = chooseOrientFirstTri ? (t + 1) : t;
576 triangles[t1].orientPreserving = triangles[t0].orientPreserving;
577 }
578 }
579 });
580 }
581
584
586 struct Entry {
587 Entry(uint32_t key_, uint data_) : key(key_), data(data_) {}
588 uint key, data;
589 };
590 std::vector<Entry> entries;
591
592 NeighborShard(size_t capacity)
593 {
594 entries.reserve(capacity);
595 }
596
598 {
599 /* Entries are added by iterating over t, so by using a stable sort,
600 * we don't have to compare based on t as well. */
601 {
602 std::vector<Entry> tempEntries(entries.size(), {0, 0});
603 radixsort(entries, tempEntries, [](const Entry &e) { return e.key; });
604 }
605
606 for (uint i = 0; i < entries.size(); i++) {
607 const Entry &a = entries[i];
608 uint tA, iA;
609 unpack_index(tA, iA, a.data);
610 Mikktspace<Mesh>::Triangle &triA = mikk->triangles[tA];
611
612 if (triA.neighbor[iA] != UNSET_ENTRY) {
613 continue;
614 }
615
616 uint i0A = triA.vertices[iA], i1A = triA.vertices[(iA != 2) ? (iA + 1) : 0];
617 for (uint j = i + 1; j < entries.size(); j++) {
618 const Entry &b = entries[j];
619 uint tB, iB;
620 unpack_index(tB, iB, b.data);
621 Mikktspace<Mesh>::Triangle &triB = mikk->triangles[tB];
622
623 if (b.key != a.key)
624 break;
625
626 if (triB.neighbor[iB] != UNSET_ENTRY) {
627 continue;
628 }
629
630 uint i1B = triB.vertices[iB], i0B = triB.vertices[(iB != 2) ? (iB + 1) : 0];
631 if (i0A == i0B && i1A == i1B) {
632 triA.neighbor[iA] = tB;
633 triB.neighbor[iB] = tA;
634 break;
635 }
636 }
637 }
638 }
639 };
640
642 {
643 /* In order to parallelize the processing, we divide the vertices into shards.
644 * Since only vertex pairs with the same key will be checked, we can process
645 * shards independently as long as we ensure that all vertices with the same
646 * key go into the same shard.
647 * This is done by hashing the key to get the shard index of each vertex.
648 */
649 // TODO: Two-step filling that first counts and then fills? Could be parallel then.
650 uint targetNrShards = isParallel ? uint(4 * nrThreads) : 1;
651 uint nrShards = 1, hashShift = 32;
652 while (nrShards < targetNrShards) {
653 nrShards *= 2;
654 hashShift -= 1;
655 }
656
657 /* Reserve 25% extra to account for variation due to hashing. */
658 size_t reserveSize = size_t(double(3 * nrTriangles) * 1.25 / nrShards);
659 std::vector<NeighborShard> shards(nrShards, {reserveSize});
660
661 for (uint t = 0; t < nrTriangles; t++) {
662 Triangle &triangle = triangles[t];
663 for (uint i = 0; i < 3; i++) {
664 const uint i0 = triangle.vertices[i];
665 const uint i1 = triangle.vertices[(i != 2) ? (i + 1) : 0];
666 const uint high = std::max(i0, i1), low = std::min(i0, i1);
667 const uint hash = hash_uint3(high, low, 0);
668 /* TODO: Reusing the hash here means less hash space inside each shard.
669 * Computing a second hash with a different seed it probably not worth it? */
670 const uint shard = isParallel ? (hash >> hashShift) : 0;
671 shards[shard].entries.emplace_back(hash, pack_index(t, i));
672 }
673 }
674
675 runParallel(0u, nrShards, [&](uint s) { shards[s].buildNeighbors(this); });
676 }
677
680
681 void assignRecur(const uint t, uint groupId)
682 {
683 if (t == UNSET_ENTRY) {
684 return;
685 }
686
687 Triangle &triangle = triangles[t];
688 Group &group = groups[groupId];
689
690 // track down vertex
691 const uint vertRep = group.vertexRepresentative;
692 uint i = 3;
693 if (triangle.vertices[0] == vertRep) {
694 i = 0;
695 }
696 else if (triangle.vertices[1] == vertRep) {
697 i = 1;
698 }
699 else if (triangle.vertices[2] == vertRep) {
700 i = 2;
701 }
702 assert(i < 3);
703
704 // early out
705 if (triangle.group[i] != UNSET_ENTRY) {
706 return;
707 }
708
709 if (triangle.groupWithAny) {
710 // first to group with a group-with-anything triangle
711 // determines its orientation.
712 // This is the only existing order dependency in the code!!
713 if (triangle.group[0] == UNSET_ENTRY && triangle.group[1] == UNSET_ENTRY &&
714 triangle.group[2] == UNSET_ENTRY)
715 {
716 triangle.orientPreserving = group.orientPreserving;
717 }
718 }
719
720 if (triangle.orientPreserving != group.orientPreserving) {
721 return;
722 }
723
724 triangle.group[i] = groupId;
725
726 const uint t_L = triangle.neighbor[i];
727 const uint t_R = triangle.neighbor[i > 0 ? (i - 1) : 2];
728 assignRecur(t_L, groupId);
729 assignRecur(t_R, groupId);
730 }
731
733 {
734 /* NOTE: This could be parallelized by grouping all [t, i] pairs into
735 * shards by hash(triangles[t].vertices[i]). This way, each shard can be processed
736 * independently and in parallel.
737 * However, the `groupWithAny` logic needs special handling (e.g. lock a mutex when
738 * encountering a `groupWithAny` triangle, then sort it out, then unlock and proceed). */
739 for (uint t = 0; t < nrTriangles; t++) {
740 Triangle &triangle = triangles[t];
741 for (uint i = 0; i < 3; i++) {
742 // if not assigned to a group
743 if (triangle.groupWithAny || triangle.group[i] != UNSET_ENTRY) {
744 continue;
745 }
746
747 const uint newGroupId = uint(groups.size());
748 triangle.group[i] = newGroupId;
749
750 groups.emplace_back(triangle.vertices[i], bool(triangle.orientPreserving));
751
752 const uint t_L = triangle.neighbor[i];
753 const uint t_R = triangle.neighbor[i > 0 ? (i - 1) : 2];
754 assignRecur(t_L, newGroupId);
755 assignRecur(t_R, newGroupId);
756 }
757 }
758 }
759
762
763 template<bool atomic> void accumulateTSpaces(uint t)
764 {
765 const Triangle &triangle = triangles[t];
766 // only valid triangles get to add their contribution
767 if (triangle.groupWithAny) {
768 return;
769 }
770
771 /* TODO: Vectorize?
772 * Also: Could add special case for flat shading, when all normals are equal half of the fCos
773 * projections and two of the three tangent projections are unnecessary. */
774 std::array<float3, 3> n, p;
775 for (uint i = 0; i < 3; i++) {
776 n[i] = getNormal(triangle.vertices[i]);
777 p[i] = getPosition(triangle.vertices[i]);
778 }
779
780 std::array<float, 3> fCos = {dot(project(n[0], p[1] - p[0]), project(n[0], p[2] - p[0])),
781 dot(project(n[1], p[2] - p[1]), project(n[1], p[0] - p[1])),
782 dot(project(n[2], p[0] - p[2]), project(n[2], p[1] - p[2]))};
783
784 for (uint i = 0; i < 3; i++) {
785 uint groupId = triangle.group[i];
786 if (groupId != UNSET_ENTRY) {
787 float3 tangent = project(n[i], triangle.tangent) *
788 fast_acosf(std::clamp(fCos[i], -1.0f, 1.0f));
789 if constexpr (atomic) {
790 groups[groupId].accumulateTSpaceAtomic(tangent);
791 }
792 else {
793 groups[groupId].accumulateTSpace(tangent);
794 }
795 }
796 }
797 }
798
800 {
801 if (isParallel) {
802 runParallel(0u, nrTriangles, [&](uint t) { accumulateTSpaces<true>(t); });
803 }
804 else {
805 for (uint t = 0; t < nrTriangles; t++) {
806 accumulateTSpaces<false>(t);
807 }
808 }
809
810 /* TODO: Worth parallelizing? Probably not. */
811 for (Group &group : groups) {
812 group.normalizeTSpace();
813 }
814
815 tSpaces.resize(nrTSpaces);
816
817 for (uint t = 0; t < nrTriangles; t++) {
818 Triangle &triangle = triangles[t];
819 for (uint i = 0; i < 3; i++) {
820 uint groupId = triangle.group[i];
821 if (groupId == UNSET_ENTRY) {
822 continue;
823 }
824 const Group group = groups[groupId];
825 assert(triangle.orientPreserving == group.orientPreserving);
826
827 // output tspace
828 const uint offset = triangle.tSpaceIdx;
829 const uint faceVertex = triangle.faceVertex[i];
830 tSpaces[offset + faceVertex].accumulateGroup(group);
831 }
832 }
833 }
834};
835
836} // namespace mikk
unsigned int uint
ATTR_WARN_UNUSED_RESULT const BMVert * v2
ATTR_WARN_UNUSED_RESULT const BMVert const BMEdge * e
ATTR_WARN_UNUSED_RESULT const BMVert * v
btScalar getPosition(int row) const
int numVertices() const
SIMD_FORCE_INLINE btVector3 & normalize()
Normalize this vector x^2 + y^2 + z^2 = 1.
Definition btVector3.h:303
void assignRecur(const uint t, uint groupId)
void generateSharedVerticesIndexList_impl()
float3 getPosition(uint vertexID)
void generateSharedVerticesIndexList()
void runParallel(uint start, uint end, F func)
void build4RuleGroups()
Mikktspace(Mesh &mesh_)
void generateInitialVerticesIndexList()
float3 getNormal(uint vertexID)
float calcTexArea(uint tri)
float3 getTexCoord(uint vertexID)
void accumulateTSpaces(uint t)
local_group_size(16, 16) .push_constant(Type b
#define fabsf(x)
#define sqrtf(x)
node_ attributes set("label", ss.str())
static float verts[][3]
static uint hash_uint3(uint kx, uint ky, uint kz)
Definition mikk_util.hh:61
float dot(const float3 &a, const float3 &b)
static uint pack_index(const uint face, const uint vert)
Definition mikk_util.hh:26
bool not_zero(const float fX)
Definition mikk_util.hh:20
float3 project(const float3 &n, const float3 &v)
static void unpack_index(uint &face, uint &vert, const uint indexIn)
Definition mikk_util.hh:32
static uint hash_float3x3(const float3 &x, const float3 &y, const float3 &z)
Definition mikk_util.hh:98
static void float_add_atomic(float *val, float add)
Definition mikk_util.hh:142
void radixsort(std::vector< T > &data, std::vector< T > &data2, KeyGetter getKey)
Definition mikk_util.hh:106
float fast_acosf(float x)
Definition mikk_util.hh:39
static constexpr uint UNSET_ENTRY
Definition mikktspace.hh:24
#define hash
Definition noise.c:154
unsigned int uint32_t
Definition stdint.h:80
unsigned char uint8_t
Definition stdint.h:78
Entry(uint32_t key_, uint data_)
std::vector< Entry > entries
void buildNeighbors(Mikktspace< Mesh > *mikk)
Mikktspace< Mesh > * mikk
bool operator()(const uint &kA, const uint &kB) const
uint operator()(const uint &k) const
Mikktspace< Mesh > * mikk
float length_squared() const