-
Notifications
You must be signed in to change notification settings - Fork 232
Expand file tree
/
Copy pathsurface_mesh.cpp
More file actions
1997 lines (1591 loc) · 66.4 KB
/
surface_mesh.cpp
File metadata and controls
1997 lines (1591 loc) · 66.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2017-2023, Nicholas Sharp and the Polyscope contributors. https://polyscope.run
#include "polyscope/surface_mesh.h"
#include "polyscope/combining_hash_functions.h"
#include "polyscope/elementary_geometry.h"
#include "polyscope/pick.h"
#include "polyscope/polyscope.h"
#include "polyscope/render/engine.h"
#include "imgui.h"
#include "polyscope/types.h"
#include "polyscope/utilities.h"
#include <unordered_map>
#include <utility>
namespace polyscope {
// Initialize statics
const std::string SurfaceMesh::structureTypeName = "Surface Mesh";
SurfaceMesh::SurfaceMesh(std::string name_)
: QuantityStructure<SurfaceMesh>(name_, typeName()),
// clang-format off
// == managed quantities
// positions
vertexPositions( this, uniquePrefix() + "vertexPositions", vertexPositionsData),
// connectivity / indices
// (triangle and face inds are always computed initially when we triangulate the mesh)
triangleVertexInds( this, uniquePrefix() + "triangleVertexInds", triangleVertexIndsData),
triangleFaceInds( this, uniquePrefix() + "triangleFaceInds", triangleFaceIndsData),
triangleCornerInds( this, uniquePrefix() + "triangleCornerInds", triangleCornerIndsData, std::bind(&SurfaceMesh::computeTriangleCornerInds, this)),
triangleAllVertexInds( this, uniquePrefix() + "triangleAllVertexInds", triangleAllVertexIndsData, std::bind(&SurfaceMesh::computeTriangleAllVertexInds, this)),
triangleAllEdgeInds( this, uniquePrefix() + "triangleAllEdgeInds", triangleAllEdgeIndsData, std::bind(&SurfaceMesh::computeTriangleAllEdgeInds, this)),
triangleAllHalfedgeInds( this, uniquePrefix() + "triangleHalfedgeInds", triangleAllHalfedgeIndsData, std::bind(&SurfaceMesh::computeTriangleAllHalfedgeInds, this)),
triangleAllCornerInds( this, uniquePrefix() + "triangleAllCornerInds", triangleAllCornerIndsData, std::bind(&SurfaceMesh::computeTriangleAllCornerInds, this)),
// internal triangle data for rendering
baryCoord( this, uniquePrefix() + "baryCoord", baryCoordData),
edgeIsReal( this, uniquePrefix() + "edgeIsReal", edgeIsRealData),
// other internally-computed geometry
faceNormals( this, uniquePrefix() + "faceNormals", faceNormalsData, std::bind(&SurfaceMesh::computeFaceNormals, this)),
faceCenters( this, uniquePrefix() + "faceCenters", faceCentersData, std::bind(&SurfaceMesh::computeFaceCenters, this)),
faceAreas( this, uniquePrefix() + "faceAreas", faceAreasData, std::bind(&SurfaceMesh::computeFaceAreas, this)),
vertexNormals( this, uniquePrefix() + "vertexNormals", vertexNormalsData, std::bind(&SurfaceMesh::computeVertexNormals, this)),
vertexAreas( this, uniquePrefix() + "vertexAreas", vertexAreasData, std::bind(&SurfaceMesh::computeVertexAreas, this)),
// tangent spaces
defaultFaceTangentBasisX( this, uniquePrefix() + "defaultFaceTangentBasisX", defaultFaceTangentBasisXData, std::bind(&SurfaceMesh::computeDefaultFaceTangentBasisX, this)),
defaultFaceTangentBasisY( this, uniquePrefix() + "defaultFaceTangentBasisY", defaultFaceTangentBasisYData, std::bind(&SurfaceMesh::computeDefaultFaceTangentBasisY, this)),
// == persistent options
surfaceColor( uniquePrefix() + "surfaceColor", getNextUniqueColor()),
edgeColor( uniquePrefix() + "edgeColor", glm::vec3{0., 0., 0.}), material(uniquePrefix() + "material", "clay"),
edgeWidth( uniquePrefix() + "edgeWidth", 0.),
backFacePolicy( uniquePrefix() + "backFacePolicy", BackFacePolicy::Different),
backFaceColor( uniquePrefix() + "backFaceColor", glm::vec3(1.f - surfaceColor.get().r, 1.f - surfaceColor.get().g, 1.f - surfaceColor.get().b)),
shadeStyle( uniquePrefix() + "shadeStyle", MeshShadeStyle::Flat),
selectionMode( uniquePrefix() + "selectionMode", MeshSelectionMode::Auto)
// clang-format on
{}
SurfaceMesh::SurfaceMesh(std::string name_, const std::vector<glm::vec3>& vertexPositions_,
const std::vector<uint32_t>& faceIndsEntries_, const std::vector<uint32_t>& faceIndsStart_)
: SurfaceMesh(name_) {
vertexPositionsData = vertexPositions_;
faceIndsEntries = faceIndsEntries_;
faceIndsStart = faceIndsStart_;
vertexPositions.checkInvalidValues();
computeConnectivityData();
updateObjectSpaceBounds();
}
SurfaceMesh::SurfaceMesh(std::string name_, const std::vector<glm::vec3>& vertexPositions_,
const std::vector<std::vector<size_t>>& facesIn)
: SurfaceMesh(name_) {
vertexPositionsData = vertexPositions_;
nestedFacesToFlat(facesIn);
vertexPositions.checkInvalidValues();
computeConnectivityData();
updateObjectSpaceBounds();
}
void SurfaceMesh::nestedFacesToFlat(const std::vector<std::vector<size_t>>& nestedInds) {
faceIndsStart.clear();
faceIndsEntries.clear();
faceIndsStart.push_back(0);
for (const std::vector<size_t>& face : nestedInds) {
for (size_t iV : face) {
faceIndsEntries.push_back(iV);
}
faceIndsStart.push_back(faceIndsEntries.size());
}
}
void SurfaceMesh::computeConnectivityData() {
// some number-of-elements arithmetic
size_t numFaces = faceIndsStart.size() - 1;
nCornersCount = faceIndsEntries.size();
nFacesTriangulationCount = nCornersCount - 2 * numFaces;
// fill out these buffers as we construct the triangulation
triangleVertexIndsData.clear();
triangleVertexIndsData.resize(3 * nFacesTriangulationCount);
triangleFaceIndsData.clear();
triangleFaceIndsData.resize(3 * nFacesTriangulationCount);
baryCoordData.clear();
baryCoordData.resize(3 * nFacesTriangulationCount);
edgeIsRealData.clear();
edgeIsRealData.resize(3 * nFacesTriangulationCount);
// validate the face-vertex indices
for (size_t iV : faceIndsEntries) {
if (iV >= vertexPositions.size())
exception("SurfaceMesh " + name + " has face vertex index " + std::to_string(iV) +
" out of bounds for number of vertices " + std::to_string(vertexPositions.size()));
}
// construct the triangualted draw list and all other related data
size_t iTriFace = 0;
for (size_t iF = 0; iF < numFaces; iF++) {
size_t D = faceIndsStart[iF + 1] - faceIndsStart[iF];
size_t iStart = faceIndsStart[iF];
uint32_t vRoot = faceIndsEntries[iStart];
// implicitly triangulate from root
for (size_t j = 1; (j + 1) < D; j++) {
uint32_t vB = faceIndsEntries[iStart + j];
uint32_t vC = faceIndsEntries[iStart + ((j + 1) % D)];
// triangle vertex indices
triangleVertexIndsData[3 * iTriFace + 0] = vRoot;
triangleVertexIndsData[3 * iTriFace + 1] = vB;
triangleVertexIndsData[3 * iTriFace + 2] = vC;
// triangle face indices
for (size_t k = 0; k < 3; k++) triangleFaceIndsData[3 * iTriFace + k] = iF;
// barycentric coordinates
baryCoordData[3 * iTriFace + 0] = glm::vec3{1., 0., 0.};
baryCoordData[3 * iTriFace + 1] = glm::vec3{0., 1., 0.};
baryCoordData[3 * iTriFace + 2] = glm::vec3{0., 0., 1.};
// internal edges for triangulated polygons
glm::vec3 edgeRealV{0., 1., 0.};
if (j == 1) {
edgeRealV.x = 1.;
}
if (j + 2 == D) {
edgeRealV.z = 1.;
}
for (size_t k = 0; k < 3; k++) edgeIsRealData[3 * iTriFace + k] = edgeRealV;
iTriFace++;
}
}
vertexDataSize = nVertices();
faceDataSize = nFaces();
// edgeDataSize = ... we don't know this yet, gets set below
halfedgeDataSize = nHalfedges();
cornerDataSize = nCorners();
triangleVertexInds.markHostBufferUpdated();
triangleFaceInds.markHostBufferUpdated();
baryCoord.markHostBufferUpdated();
edgeIsReal.markHostBufferUpdated();
}
// =================================================
// ===== Lazily-Populated Connectivity ========
// =================================================
void SurfaceMesh::computeTriangleAllEdgeInds() {
// WARNING: logic duplicated in countEdges()
if (edgePerm.empty())
exception("SurfaceMesh " + name +
" performed an operation which requires edge indices to be specified, but none have been set. "
"Call setEdgePermutation().");
triangleVertexInds.ensureHostBufferPopulated();
triangleAllEdgeInds.data.resize(3 * 3 * nFacesTriangulation());
halfedgeEdgeCorrespondence.resize(nHalfedges());
// used to loop over edges
std::unordered_map<std::pair<size_t, size_t>, size_t, polyscope::hash_combine::hash<std::pair<size_t, size_t>>>
seenEdgeInds;
auto createEdgeKey = [&](size_t a, size_t b) -> std::pair<size_t, size_t> {
return std::make_pair(std::min(a, b), std::max(a, b));
};
size_t psEdgeInd = 0; // polyscope's edge index, iterated according to Polyscope's canonical ordering
for (size_t iF = 0; iF < nFaces(); iF++) {
size_t start = faceIndsStart[iF];
size_t D = faceIndsStart[iF + 1] - start;
// TODO why can't we use edges on non triangular meshes? Implement it.
if (D != 3) {
exception("SurfaceMesh " + name +
" attempted to access triangle-edge indices, but it has non-triangular faces. These indices are "
"only well-defined on a pure-triangular mesh.");
}
glm::uvec3 thisTriInds{0, 0, 0};
for (size_t j = 0; j < 3; j++) {
size_t vA = triangleVertexInds.data[3 * iF + j];
size_t vB = triangleVertexInds.data[3 * iF + ((j + 1) % 3)];
std::pair<size_t, size_t> key = createEdgeKey(vA, vB);
size_t thisEdgeInd;
if (seenEdgeInds.find(key) == seenEdgeInds.end()) {
// process a new edge in the canonical ordering
if (psEdgeInd >= edgePerm.size()) {
exception("SurfaceMesh " + name +
" edge indexing out of bounds. Did you pass an edge ordering that is too short?");
}
thisEdgeInd = edgePerm[psEdgeInd];
seenEdgeInds[key] = thisEdgeInd;
psEdgeInd++;
} else {
// we've processed this edge before, retrieve its assigned index
thisEdgeInd = seenEdgeInds[key];
}
halfedgeEdgeCorrespondence[start + j] = thisEdgeInd;
thisTriInds[j] = thisEdgeInd;
}
for (size_t j = 0; j < 3; j++) {
for (size_t k = 0; k < 3; k++) {
triangleAllEdgeInds.data[9 * iF + 3 * j + k] = thisTriInds[k];
}
}
}
nEdgesCount = psEdgeInd;
triangleAllEdgeInds.markHostBufferUpdated();
}
void SurfaceMesh::countEdges() {
// WARNING: logic duplicated in computeTriangleAllEdgeInds()
// used to loop over edges
std::unordered_map<std::pair<size_t, size_t>, size_t, polyscope::hash_combine::hash<std::pair<size_t, size_t>>>
seenEdgeInds;
auto createEdgeKey = [&](size_t a, size_t b) -> std::pair<size_t, size_t> {
return std::make_pair(std::min(a, b), std::max(a, b));
};
size_t psEdgeInd = 0; // polyscope's edge index, iterated according to Polyscope's canonical ordering
for (size_t iF = 0; iF < nFaces(); iF++) {
size_t start = faceIndsStart[iF];
size_t D = faceIndsStart[iF + 1] - start;
if (D != 3) {
exception("SurfaceMesh " + name +
" attempted to count edges, but mesh has non-triangular faces. Edge functions are only implemented on "
"a pure-triangular mesh.");
}
for (size_t j = 0; j < 3; j++) {
size_t vA = triangleVertexInds.data[3 * iF + j];
size_t vB = triangleVertexInds.data[3 * iF + ((j + 1) % 3)];
std::pair<size_t, size_t> key = createEdgeKey(vA, vB);
if (seenEdgeInds.find(key) == seenEdgeInds.end()) {
size_t thisEdgeInd = psEdgeInd;
seenEdgeInds[key] = thisEdgeInd;
psEdgeInd++;
}
}
}
nEdgesCount = psEdgeInd;
}
size_t SurfaceMesh::nEdges() {
if (nEdgesCount == INVALID_IND) countEdges();
return nEdgesCount;
}
void SurfaceMesh::computeTriangleCornerInds() {
triangleCornerInds.data.clear();
triangleCornerInds.data.reserve(3 * nFacesTriangulation());
for (size_t iF = 0; iF < nFaces(); iF++) {
size_t iStart = faceIndsStart[iF];
size_t D = faceIndsStart[iF + 1] - iStart;
// emit the data for triangles triangulating this face
for (size_t j = 1; (j + 1) < D; j++) {
uint32_t c0 = iStart;
uint32_t c1 = iStart + j;
uint32_t c2 = iStart + j + 1;
triangleCornerInds.data.push_back(c0);
triangleCornerInds.data.push_back(c1);
triangleCornerInds.data.push_back(c2);
}
}
triangleCornerInds.markHostBufferUpdated();
}
void SurfaceMesh::computeTriangleAllVertexInds() {
triangleAllVertexInds.data.clear();
triangleAllVertexInds.data.reserve(3 * 3 * nFacesTriangulation());
for (size_t iF = 0; iF < nFaces(); iF++) {
size_t iStart = faceIndsStart[iF];
size_t D = faceIndsStart[iF + 1] - iStart;
uint32_t vRoot = faceIndsEntries[iStart];
// implicitly triangulate from root
for (size_t j = 1; (j + 1) < D; j++) {
uint32_t vB = faceIndsEntries[iStart + j];
uint32_t vC = faceIndsEntries[iStart + ((j + 1) % D)];
// triangle vertex indices, all three values-each
for (size_t k = 0; k < 3; k++) {
triangleAllVertexInds.data.push_back(vRoot);
triangleAllVertexInds.data.push_back(vB);
triangleAllVertexInds.data.push_back(vC);
}
}
}
triangleAllVertexInds.markHostBufferUpdated();
}
void SurfaceMesh::computeTriangleAllHalfedgeInds() {
triangleAllHalfedgeInds.data.clear();
triangleAllHalfedgeInds.data.reserve(3 * 3 * nFacesTriangulation());
bool haveCustomIndex = !halfedgePerm.empty();
for (size_t iF = 0; iF < nFaces(); iF++) {
size_t iStart = faceIndsStart[iF];
size_t D = faceIndsStart[iF + 1] - iStart;
// emit the data for triangles triangulating this face
for (size_t j = 1; (j + 1) < D; j++) {
// FORNOW: for polygonal faces, substitute the opposite-edge value for all internal edges of the triangulation
uint32_t he0 = iStart + j; // this is a dummy value due to triangulation of polygons
uint32_t he1 = iStart + j; // this is the actual right value for the opposite edge
uint32_t he2 = iStart + j; // this is a dummy value due to triangulation of polygons
// substitute non-dummy values for first and last edge if this is not an internal tri
if (j == 1) he0 = iStart;
if (j + 2 == D) he2 = iStart + D - 1;
if (haveCustomIndex) {
he0 = halfedgePerm[he0];
he1 = halfedgePerm[he1];
he2 = halfedgePerm[he2];
}
for (size_t k = 0; k < 3; k++) {
triangleAllHalfedgeInds.data.push_back(he0);
triangleAllHalfedgeInds.data.push_back(he1);
triangleAllHalfedgeInds.data.push_back(he2);
}
}
}
triangleAllHalfedgeInds.markHostBufferUpdated();
}
void SurfaceMesh::computeTriangleAllCornerInds() {
triangleAllCornerInds.data.clear();
triangleAllCornerInds.data.reserve(3 * nFacesTriangulation());
bool haveCustomIndex = !cornerPerm.empty();
for (size_t iF = 0; iF < nFaces(); iF++) {
size_t iStart = faceIndsStart[iF];
size_t D = faceIndsStart[iF + 1] - iStart;
// emit the data for triangles triangulating this face
for (size_t j = 1; (j + 1) < D; j++) {
uint32_t c0 = iStart;
uint32_t c1 = iStart + j;
uint32_t c2 = iStart + j + 1;
if (haveCustomIndex) {
c0 = cornerPerm[c0];
c1 = cornerPerm[c1];
c2 = cornerPerm[c2];
}
for (size_t k = 0; k < 3; k++) {
triangleAllCornerInds.data.push_back(c0);
triangleAllCornerInds.data.push_back(c1);
triangleAllCornerInds.data.push_back(c2);
}
}
}
triangleAllCornerInds.markHostBufferUpdated();
}
// =================================================
// ======== Geometric Quantities ==========
// =================================================
size_t SurfaceMesh::nVertices() { return vertexPositions.size(); }
void SurfaceMesh::computeFaceNormals() {
vertexPositions.ensureHostBufferPopulated();
faceNormals.data.resize(nFaces());
for (size_t iF = 0; iF < nFaces(); iF++) {
size_t iStart = faceIndsStart[iF];
size_t D = faceIndsStart[iF + 1] - iStart;
glm::vec3 fN{0., 0., 0.};
if (D == 3) {
glm::vec3 pA = vertexPositions.data[faceIndsEntries[iStart + 0]];
glm::vec3 pB = vertexPositions.data[faceIndsEntries[iStart + 1]];
glm::vec3 pC = vertexPositions.data[faceIndsEntries[iStart + 2]];
fN = glm::cross(pB - pA, pC - pA);
} else {
for (size_t j = 0; j < D; j++) {
glm::vec3 pA = vertexPositions.data[faceIndsEntries[iStart + j]];
glm::vec3 pB = vertexPositions.data[faceIndsEntries[iStart + (j + 1) % D]];
glm::vec3 pC = vertexPositions.data[faceIndsEntries[iStart + (j + 2) % D]];
fN += glm::cross(pC - pB, pA - pB);
}
}
fN = glm::normalize(fN);
faceNormals.data[iF] = fN;
}
faceNormals.markHostBufferUpdated();
}
void SurfaceMesh::computeFaceCenters() {
vertexPositions.ensureHostBufferPopulated();
faceCenters.data.resize(nFaces());
for (size_t iF = 0; iF < nFaces(); iF++) {
size_t start = faceIndsStart[iF];
size_t D = faceIndsStart[iF + 1] - start;
glm::vec3 faceCenter{0., 0., 0.};
for (size_t j = 0; j < D; j++) {
glm::vec3 pA = vertexPositions.data[faceIndsEntries[start + j]];
faceCenter += pA;
}
faceCenter /= D;
faceCenters.data[iF] = faceCenter;
}
faceCenters.markHostBufferUpdated();
}
void SurfaceMesh::computeFaceAreas() {
vertexPositions.ensureHostBufferPopulated();
faceAreas.data.resize(nFaces());
// Loop over faces to compute face-valued quantities
for (size_t iF = 0; iF < nFaces(); iF++) {
size_t start = faceIndsStart[iF];
size_t D = faceIndsStart[iF + 1] - start;
// Compute a face normal
double fA;
if (D == 3) {
glm::vec3 pA = vertexPositions.data[faceIndsEntries[start + 0]];
glm::vec3 pB = vertexPositions.data[faceIndsEntries[start + 1]];
glm::vec3 pC = vertexPositions.data[faceIndsEntries[start + 2]];
glm::vec3 fN = glm::cross(pB - pA, pC - pA);
fA = 0.5 * glm::length(fN);
} else {
fA = 0;
glm::vec3 pRoot = vertexPositions.data[faceIndsEntries[start]];
for (size_t j = 1; j + 1 < D; j++) {
glm::vec3 pA = vertexPositions.data[faceIndsEntries[start + j]];
glm::vec3 pB = vertexPositions.data[faceIndsEntries[start + j + 1]];
fA += 0.5 * glm::length(glm::cross(pA - pRoot, pB - pRoot));
}
}
faceAreas.data[iF] = fA;
}
faceAreas.markHostBufferUpdated();
}
void SurfaceMesh::computeVertexNormals() {
faceNormals.ensureHostBufferPopulated();
faceAreas.ensureHostBufferPopulated();
vertexNormals.data.resize(nVertices());
const glm::vec3 zero{0., 0., 0.};
std::fill(vertexNormals.data.begin(), vertexNormals.data.end(), zero);
// Accumulate quantities from each face
for (size_t iF = 0; iF < nFaces(); iF++) {
size_t start = faceIndsStart[iF];
size_t D = faceIndsStart[iF + 1] - start;
for (size_t j = 0; j < D; j++) {
size_t iV = faceIndsEntries[start + j];
vertexNormals.data[iV] += faceNormals.data[iF] * static_cast<float>(faceAreas.data[iF]);
}
}
// Normalize
for (size_t iV = 0; iV < nVertices(); iV++) {
vertexNormals.data[iV] = glm::normalize(vertexNormals.data[iV]);
}
vertexNormals.markHostBufferUpdated();
}
void SurfaceMesh::computeVertexAreas() {
faceAreas.ensureHostBufferPopulated();
vertexAreas.data.resize(nVertices());
std::fill(vertexAreas.data.begin(), vertexAreas.data.end(), 0.);
// Accumulate quantities from each face
for (size_t iF = 0; iF < nFaces(); iF++) {
size_t D = faceIndsStart[iF + 1] - faceIndsStart[iF];
size_t start = faceIndsStart[iF];
for (size_t j = 0; j < D; j++) {
size_t iV = faceIndsEntries[start + j];
vertexAreas.data[iV] += faceAreas.data[iF] / D;
}
}
vertexAreas.markHostBufferUpdated();
}
void SurfaceMesh::computeDefaultFaceTangentBasisX() {
// NOTE: this function is weirdly duplicated into an 'X' and 'Y' paradigm to fit the compute-function-per-buffer
// paradigm
vertexPositions.ensureHostBufferPopulated();
faceNormals.ensureHostBufferPopulated();
defaultFaceTangentBasisX.data.resize(nFaces());
for (size_t iF = 0; iF < nFaces(); iF++) {
size_t D = faceIndsStart[iF + 1] - faceIndsStart[iF];
if (D != 3) exception("Default face tangent spaces only available for pure-triangular meshes");
size_t start = faceIndsStart[iF];
glm::vec3 pA = vertexPositions.data[faceIndsEntries[start + 0]];
glm::vec3 pB = vertexPositions.data[faceIndsEntries[start + 1]];
glm::vec3 N = faceNormals.data[iF];
glm::vec3 basisX = pB - pA;
basisX = glm::normalize(basisX - N * glm::dot(N, basisX));
glm::vec3 basisY = glm::normalize(-glm::cross(basisX, N));
defaultFaceTangentBasisX.data[iF] = basisX;
}
defaultFaceTangentBasisX.markHostBufferUpdated();
}
void SurfaceMesh::computeDefaultFaceTangentBasisY() {
// NOTE: this function is weirdly duplicated into an 'X' and 'Y' paradigm to fit the compute-function-per-buffer
// paradigm
vertexPositions.ensureHostBufferPopulated();
faceNormals.ensureHostBufferPopulated();
defaultFaceTangentBasisY.data.resize(nFaces());
for (size_t iF = 0; iF < nFaces(); iF++) {
size_t D = faceIndsStart[iF + 1] - faceIndsStart[iF];
if (D != 3) exception("Default face tangent spaces only available for pure-triangular meshes");
size_t start = faceIndsStart[iF];
glm::vec3 pA = vertexPositions.data[faceIndsEntries[start + 0]];
glm::vec3 pB = vertexPositions.data[faceIndsEntries[start + 1]];
glm::vec3 N = faceNormals.data[iF];
glm::vec3 basisX = pB - pA;
basisX = glm::normalize(basisX - N * glm::dot(N, basisX));
glm::vec3 basisY = glm::normalize(-glm::cross(basisX, N));
defaultFaceTangentBasisY.data[iF] = basisY;
}
defaultFaceTangentBasisY.markHostBufferUpdated();
}
// === Edge Lengths ===
// void SurfaceMesh::computeEdgeLengths() {
//
// vertexPositions.ensureHostBufferPopulated();
//
// edgeLengths.data.resize(nEdges());
//
// // Compute edge lengths
// for (size_t iF = 0; iF < nFaces(); iF++) {
// size_t D = faceIndsStart[iF + 1] - faceIndsStart[iF];
// size_t start = faceIndsStart[iF];
// for (size_t j = 0; j < D; j++) {
// size_t iA = faceIndsEntries[start + j];
// size_t iB = faceIndsEntries[start + (j + 1) % D];
// glm::vec3 pA = vertexPositions.data[iA];
// glm::vec3 pB = vertexPositions.data[iB];
// edgeLengths.data[edgeIndices[iF][j]] = glm::length(pA - pB);
// }
// }
//
// edgeLengths.markHostBufferUpdated();
// }
void SurfaceMesh::checkTriangular() {
if (nFacesTriangulation() != nFaces()) {
exception("Cannot proceed, SurfaceMesh " + name + " is not a triangular mesh.");
}
}
void SurfaceMesh::ensureHaveManifoldConnectivity() {
if (!twinHalfedge.empty()) return; // already populated
triangleVertexInds.ensureHostBufferPopulated();
twinHalfedge.resize(nHalfedges());
// Maps from edge (sorted) to all halfedges incident on that edge
std::unordered_map<std::pair<size_t, size_t>, std::vector<size_t>,
polyscope::hash_combine::hash<std::pair<size_t, size_t>>>
edgeInds;
// Fill out faceForHalfedge and populate edge lookup map
for (size_t iF = 0; iF < nFacesTriangulation(); iF++) {
for (size_t j = 0; j < 3; j++) {
size_t iV = triangleVertexInds.data[3 * iF + j];
size_t iVNext = triangleVertexInds.data[3 * iF + ((j + 1) % 3)];
size_t iHe = 3 * iF + j;
std::pair<size_t, size_t> edgeKey(std::min(iV, iVNext), std::max(iV, iVNext));
// Make sure the key is populated
auto it = edgeInds.find(edgeKey);
if (it == edgeInds.end()) {
it = edgeInds.insert(it, {edgeKey, std::vector<size_t>()});
}
// Add this halfedge to the entry
it->second.push_back(iHe);
}
}
// Second walk through, setting twins
for (size_t iF = 0; iF < nFacesTriangulation(); iF++) {
for (size_t j = 0; j < 3; j++) {
size_t iV = triangleVertexInds.data[3 * iF + j];
size_t iVNext = triangleVertexInds.data[3 * iF + ((j + 1) % 3)];
size_t iHe = 3 * iF + j;
std::pair<size_t, size_t> edgeKey(std::min(iV, iVNext), std::max(iV, iVNext));
std::vector<size_t>& edgeHalfedges = edgeInds.find(edgeKey)->second;
// Pick the first halfedge we find which is not this one
size_t myTwin = INVALID_IND;
for (size_t t : edgeHalfedges) {
if (t != iHe) {
myTwin = t;
break;
}
}
twinHalfedge[iHe] = myTwin;
}
}
}
void SurfaceMesh::draw() {
if (!isEnabled()) {
return;
}
render::engine->setBackfaceCull(backFacePolicy.get() == BackFacePolicy::Cull);
// If no quantity is drawing the surface, we should draw it
if (dominantQuantity == nullptr) {
if (program == nullptr) {
prepare();
// do this now to reduce lag when picking later
// preparePick();
}
// Set uniforms
setStructureUniforms(*program);
setSurfaceMeshUniforms(*program);
program->setUniform("u_baseColor", getSurfaceColor());
render::engine->setMaterialUniforms(*program, getMaterial());
program->draw();
}
// Draw the quantities
for (auto& x : quantities) {
x.second->draw();
}
render::engine->setBackfaceCull(); // return to default setting
for (auto& x : floatingQuantities) {
x.second->draw();
}
}
void SurfaceMesh::drawDelayed() {
if (!isEnabled()) {
return;
}
render::engine->setBackfaceCull(backFacePolicy.get() == BackFacePolicy::Cull);
for (auto& x : quantities) {
x.second->drawDelayed();
}
render::engine->setBackfaceCull(); // return to default setting
for (auto& x : floatingQuantities) {
x.second->drawDelayed();
}
}
void SurfaceMesh::drawPick() {
if (!isEnabled()) {
return;
}
if (pickProgram == nullptr) {
preparePick();
}
render::engine->setBackfaceCull(backFacePolicy.get() == BackFacePolicy::Cull);
// Set uniforms
setStructureUniforms(*pickProgram);
if (usingSimplePick) {
float radVal;
switch (selectionMode.get()) {
case MeshSelectionMode::Auto:
radVal = 0.2;
break;
case MeshSelectionMode::VerticesOnly:
radVal = 1.;
break;
case MeshSelectionMode::FacesOnly:
radVal = 0.;
break;
}
pickProgram->setUniform("u_vertPickRadius", radVal);
}
pickProgram->draw();
for (auto& x : quantities) {
x.second->drawPick();
}
render::engine->setBackfaceCull(); // return to default setting
for (auto& x : floatingQuantities) {
x.second->drawPick();
}
}
void SurfaceMesh::drawPickDelayed() {
if (!isEnabled()) {
return;
}
for (auto& x : quantities) {
x.second->drawPickDelayed();
}
for (auto& x : floatingQuantities) {
x.second->drawPickDelayed();
}
}
void SurfaceMesh::prepare() {
// clang-format off
program = render::engine->requestShader( "MESH",
render::engine->addMaterialRules(getMaterial(),
addSurfaceMeshRules({"SHADE_BASECOLOR"})
)
);
// clang-format on
// Populate draw buffers
setMeshGeometryAttributes(*program);
render::engine->setMaterial(*program, getMaterial());
}
void SurfaceMesh::preparePick() {
switch (selectionMode.get()) {
case MeshSelectionMode::Auto:
usingSimplePick = !(edgesHaveBeenUsed || halfedgesHaveBeenUsed || cornersHaveBeenUsed);
break;
case MeshSelectionMode::VerticesOnly:
usingSimplePick = true;
break;
case MeshSelectionMode::FacesOnly:
usingSimplePick = true;
break;
}
if (usingSimplePick) {
pickProgram =
render::engine->requestShader("MESH", addSurfaceMeshRules({"MESH_PROPAGATE_PICK_SIMPLE"}, true, false),
render::ShaderReplacementDefaults::Pick);
} else {
pickProgram = render::engine->requestShader("MESH", addSurfaceMeshRules({"MESH_PROPAGATE_PICK"}, true, false),
render::ShaderReplacementDefaults::Pick);
}
// Populate draw buffers
setMeshGeometryAttributes(*pickProgram);
setMeshPickAttributes(*pickProgram);
}
void SurfaceMesh::setMeshGeometryAttributes(render::ShaderProgram& p) {
if (p.hasAttribute("a_vertexPositions")) {
p.setAttribute("a_vertexPositions", vertexPositions.getIndexedRenderAttributeBuffer(triangleVertexInds));
}
if (p.hasAttribute("a_vertexNormals")) {
if (getShadeStyle() == MeshShadeStyle::Smooth) {
p.setAttribute("a_vertexNormals", vertexNormals.getIndexedRenderAttributeBuffer(triangleVertexInds));
} else {
// these aren't actually used in in the automatically-generated case, but the shader is set up in a lazy way so
// it is still needed
p.setAttribute("a_vertexNormals", faceNormals.getIndexedRenderAttributeBuffer(triangleFaceInds));
}
}
if (p.hasAttribute("a_normal")) {
p.setAttribute("a_normal", faceNormals.getIndexedRenderAttributeBuffer(triangleFaceInds));
}
if (p.hasAttribute("a_barycoord")) {
p.setAttribute("a_barycoord", baryCoord.getRenderAttributeBuffer());
}
if (p.hasAttribute("a_edgeIsReal")) {
p.setAttribute("a_edgeIsReal", edgeIsReal.getRenderAttributeBuffer());
}
if (wantsCullPosition()) {
p.setAttribute("a_cullPos", faceCenters.getIndexedRenderAttributeBuffer(triangleFaceInds));
}
if (transparencyQuantityName != "") {
SurfaceScalarQuantity& transparencyQ = resolveTransparencyQuantity();
p.setAttribute("a_valueAlpha", transparencyQ.getAttributeBuffer());
}
}
void SurfaceMesh::setMeshPickAttributes(render::ShaderProgram& p) {
// TODO in principle all of the data this shader needs is already available on the GPU via the [...]Inds attribute
// buffers. We could move the encoding / offsetting logic to happen in a shader with some uniforms, and avoid any
// CPU-side processing. Maybe the solution is to directly render ints?
// make sure we have the relevant indexing data
triangleVertexInds.ensureHostBufferPopulated();
triangleFaceInds.ensureHostBufferPopulated();
if (edgesHaveBeenUsed) triangleAllEdgeInds.ensureHostBufferPopulated();
if (halfedgesHaveBeenUsed) triangleAllHalfedgeInds.ensureHostBufferPopulated();
if (cornersHaveBeenUsed) triangleCornerInds.ensureHostBufferPopulated();
// nEdges() requires computing number of edges, which is expensive and might not even be implemented for polygonal
// meshes. This way we only call it if actually needed, and use 0 otherwise.
size_t nEdgesSafe = edgesHaveBeenUsed ? nEdges() : 0;
// Get element indices
size_t totalPickElements = nVertices() + nFaces() + nEdgesSafe + nHalfedges() + nCorners();
// In "local" indices, indexing elements only within this mesh, used for reading later
facePickIndStart = nVertices();
edgePickIndStart = facePickIndStart + nFaces();
halfedgePickIndStart = edgePickIndStart + nEdgesSafe;
cornerPickIndStart = halfedgePickIndStart + nHalfedges();
// In "global" indices, indexing all elements in the scene, used to fill buffers for drawing here
size_t pickStart = pick::requestPickBufferRange(this, totalPickElements);
size_t vertexGlobalPickIndStart = pickStart;
size_t faceGlobalPickIndStart = pickStart + facePickIndStart;
size_t edgeGlobalPickIndStart = pickStart + edgePickIndStart;
size_t halfedgeGlobalPickIndStart = pickStart + halfedgePickIndStart;
size_t cornerGlobalPickIndStart = pickStart + cornerPickIndStart;
// == Fill buffers
std::vector<std::array<glm::vec3, 3>> vertexColors, halfedgeColors, cornerColors;
std::vector<glm::vec3> faceColor;
// Reserve space
vertexColors.reserve(3 * nFacesTriangulation());
faceColor.reserve(3 * nFacesTriangulation());
if (!usingSimplePick) {
halfedgeColors.reserve(3 * nFacesTriangulation());
cornerColors.reserve(3 * nFacesTriangulation());
}
// Build all quantities in each face
size_t iFTri = 0;
for (size_t iF = 0; iF < nFaces(); iF++) {
size_t D = faceIndsStart[iF + 1] - faceIndsStart[iF];
glm::vec3 fColor = pick::indToVec(iF + faceGlobalPickIndStart);
for (size_t j = 1; (j + 1) < D; j++) {
// == Build face & vertex index data
// clang-format off
std::array<glm::vec3, 3> vColor = {
pick::indToVec(triangleVertexInds.data[3*iFTri + 0] + vertexGlobalPickIndStart),
pick::indToVec(triangleVertexInds.data[3*iFTri + 1] + vertexGlobalPickIndStart),
pick::indToVec(triangleVertexInds.data[3*iFTri + 2] + vertexGlobalPickIndStart),
};
// clang-format on
for (int j = 0; j < 3; j++) {
faceColor.push_back(fColor);
vertexColors.push_back(vColor);
}
// Second half does halfedges/edges/corners, not used for simple mode
if (usingSimplePick) {
iFTri++;
continue;
}
// Fill the halfedge buffer with edge or halfedge data, depending on which are in use
// In the pick function we will use the halfedge to look up the edge if needed
// (this is an optimization to use one less array of values, because we hit implementation limits in the shader)
// == Build edge index data, if needed
if (!usingSimplePick) {
if (edgesHaveBeenUsed || halfedgesHaveBeenUsed) {
const std::vector<uint32_t>& eDataVec =
(edgesHaveBeenUsed && !halfedgesHaveBeenUsed) ? triangleAllEdgeInds.data : triangleAllHalfedgeInds.data;