-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathMeshDisplay.py
More file actions
executable file
·1892 lines (1448 loc) · 74 KB
/
MeshDisplay.py
File metadata and controls
executable file
·1892 lines (1448 loc) · 74 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
# Visualize a mesh using openGL
# TODO check out this for drawing edges http://www2.imm.dtu.dk/pubdb/views/edoc_download.php/4884/pdf/imm4884.pdf
# OpenGL imports
from OpenGL.GL import *
from OpenGL.GLU import *
from OpenGL.GLUT import *
# System imports
import os
from math import *
import numpy as np
import matplotlib.cm # used for colormaps
from sys import platform
import random
# Our camera class encapsulating common camera transformations
from Camera import Camera
# Local imports
from Utilities import normalize, normalized
#from HalfEdgeMesh import HalfEdgeMesh, \
# Face, \
# Edge, \
# Vertex, \
# HalfEdge
from HalfEdgeMesh_ListImplementation import HalfEdgeMesh, \
Face, \
Edge, \
Vertex, \
HalfEdge
from TriSoupMesh import TriSoupMesh
from Utilities import normalize, norm, cross
from Camera import Camera
from Streamlines import generateStreamlines
# Use euclid for rotations
import euclid as eu
# TODO implement easier to use logic for when to update the data in buffers.
# Don't really want to update every time setXXX() is called, because that might
# be wasteful. However, it would be nice if that didn't need to be tracked externally.
# Maybe set a dirty flag then regenerate data as needed before a draw() call?
# Dictionary of known vertex shaders
vertShaders = {
'surf-draw': "shaders/surf-draw.vert",
'flat-draw': "shaders/flat-draw.vert",
}
# Dictionary of known fragment shaders
fragShaders = {
'surf-draw': "shaders/surf-draw.frag",
'flat-draw': "shaders/flat-draw.frag",
}
def readFile(relPath):
"""Reads from a file with a path relative to this script location"""
# Get the path to the shader directory.
# TODO this is supposedly not the right way to do paths... oh well
myLoc = os.path.realpath(__file__)
fullPath = myLoc[:myLoc.rfind(os.sep)] + os.sep + relPath
s = ""
for line in open(fullPath).readlines():
s += line
return s
class MeshDisplay(object):
# Useful colors
colors = {
'dark_grey':(0.15, 0.15, 0.15),
'grey':(0.5, 0.5, 0.5),
'light_grey':(0.75, 0.75, 0.75),
'black':(0.0,0.0,0.0),
'almost_white':(0.95, 0.95, 0.95),
'white': (1.0, 1.0, 1.0),
'light_blue': (0.2,0.6,1.0),
'red': (0.72, 0.0, 0.0),
'orange': (1.0, 0.45, 0.0)
}
def __init__(self, windowTitle='MeshDisplay', mesh=None,
width=1200, height=800, perfTarget = 'nicest'):
print("Creating MeshDisplay window")
### Members
# Visual options
self.shapeVertShader = 'shiny'
self.shapeFragShader = 'shiny'
self.edgeVertShader = 'edges'
self.edgeFragShader = 'edges'
self.shapeAlpha = 1.0 # NOTE this means order matters, and must be enabled in glInit() below
self.edgeAlpha = 1.0
self.lineWidthCoef = 0.05
self.lineWidthScaleCoef = 0.05
self.pointSize = 1.0 # TODO this is currently unused, pointsize is hardcoded in to the shader. Need to expose as a uniform.
self.nRadialPoints = 12
self.drawShape = True
self.drawEdges = False
self.drawVertices = False
self.drawVectors = False
self.drawStreamlines = False
if perfTarget not in ['nicest', 'fastest']:
raise ValueError("perfTarget must be either 'nicest' or 'fastest'")
self.perfTarget = perfTarget
# Data being displayed
self.mesh = None
self.nVerts = -1
self.nFaces = -1
self.nEdges = -1
self.dataCenter = np.array([0.0,0.0,0.0]) # A reasonable center for the data
self.scaleFactor = 1.0 # A scale factor for the magnitude of the data
self.medianEdgeLength = -1
# Display members
self.meshPrograms = []
self.shapeProg = None
self.edgeProg = None
self.vertProg = None
self.meshPickPrograms = []
self.shapePickProg = None
self.edgePickProg = None
self.vertPickProg = None
self.vectorProg = None
self.streamlineProg = None
self.camera = None
# Coloring options
self.colorMethod = 'constant' # other possibilites: 'rgbData','scalarData'
self.colorAttrName = None
self.colorDefinedOn = None # one of 'vertex', 'face', 'edge'
self.vMinMax = None
self.cmapName = None
# Members for picking
self.pickArray = None
self.pickInd = dict()
self.PICK_IND_MAX = 255
self.pickVertexCallback = None
self.pickFaceCallback = None
self.pickEdgeCallback = None
# Vector drawing options
self.vectorAttrName = None
self.vectorDefinedAt = None # One of 'vertex' or 'face'
self.vectorIsTangent = False
self.vectorIsUnit = False
self.vectorRefDirAttrName = None
self.vectorNsym = None # symmetry order of the data to be drawn
self.nVectorVerts = -1 # The size of the vertex buffer needed for
# specifying vector positions
self.kVectorPrism = 8 # Number of sides to use when drawing the vectors
self.vectorScaleFactor = None
self.vectorArrowCache = dict() # Save buffers for vectors to avoid recalculating them
# Streamline drawing options
# (always uses the same vector field and other settings as vectorAttrName)
self.streamlinesEnabled = False
self.nStreamlineSegments = -1
self.streamlineCache = dict() # Save buffers for vectors to avoid recalculating them
# Set window parameters
self.windowTitle = windowTitle
self.windowWidth = width
self.windowHeight = height
self.lastClickPos = None
# Initialize the GL/Glut environment
self.initGLUT()
print(" init'd GLUT")
self.initGL()
print(" init'd GL")
# Set up the camera
self.camera = Camera(width, height)
# Set up callbacks
glutDisplayFunc(self.redraw)
glutReshapeFunc(self.resize)
glutKeyboardFunc(self.keyfunc)
glutMouseFunc(self.mousefunc)
glutMotionFunc(self.motionfunc)
self.userKeyCallbacks = dict() # key => (function, docstring)
# Set colors
self.shapeColor = np.array(self.colors['orange'])
self.edgeColorLight = np.array(self.colors['almost_white'])
self.edgeColorDark = np.array(self.colors['dark_grey'])
self.edgeColor = self.edgeColorDark
# self.vertexDotColor = np.array(self.colors['dark_grey']) # just use edge color
self.vectorColor = np.array(self.colors['red'])
# Set up the mesh shader programs for drawing
self.prepareShapeProgram()
self.prepareEdgeProgram()
self.prepareVertexProgram()
# Set up the mesh shader programs for picking
self.prepareShapeProgram(pick=True)
self.prepareEdgePickProgram()
self.prepareVertexPickProgram()
if mesh is not None:
self.setMesh(mesh)
def preparePrettyShaderProgram(self):
"""Prepare a program which draws using positions/normals/colors with nice shading"""
prog = ShaderProgram(vertShaders['surf-draw'],
fragShaders['surf-draw'])
# Bind the output location for the fragment shader
glBindFragDataLocation(prog.handle, 0, "outputF");
# Create uniforms
prog.createUniform('projMatrix', 'u_projMatrix', 'matrix_4')
prog.createUniform('viewMatrix', 'u_viewMatrix', 'matrix_4')
prog.createUniform('alpha', 'u_alpha', 'scalar')
prog.createUniform('eyeLoc', 'u_eye', 'vector_3')
prog.createUniform('lightLoc', 'u_light', 'vector_3')
prog.createUniform('dataCenter', 'u_dataCenter', 'vector_3')
prog.createUniform('depthOffset', 'u_depthOffset', 'scalar')
# Make a VAO for the mesh
prog.createVAO('meshVAO')
# VBO for positions
prog.createVBO(
vboName = 'vertPos',
varName = 'a_position',
vaoName = 'meshVAO',
nPerVert = 3)
# VBO for colors
prog.createVBO(
vboName = 'vertColor',
varName = 'a_color',
vaoName = 'meshVAO',
nPerVert = 3)
# VBO for normals
prog.createVBO(
vboName = 'vertNorm',
varName = 'a_normal',
vaoName = 'meshVAO',
nPerVert = 3)
return prog
def prepareFlatShaderProgram(self):
"""
Prepare a program which draws using positions/colors without shading
(used for picking)
"""
prog = ShaderProgram(vertShaders['flat-draw'],
fragShaders['flat-draw'])
# Bind the output location for the fragment shader
glBindFragDataLocation(prog.handle, 0, "outputF");
# Create uniforms
prog.createUniform('projMatrix', 'u_projMatrix', 'matrix_4')
prog.createUniform('viewMatrix', 'u_viewMatrix', 'matrix_4')
prog.createUniform('alpha', 'u_alpha', 'scalar')
prog.createUniform('dataCenter', 'u_dataCenter', 'vector_3')
prog.createUniform('depthOffset', 'u_depthOffset', 'scalar')
# Make a VAO for the mesh
prog.createVAO('meshVAO')
# VBO for positions
prog.createVBO(
vboName = 'vertPos', varName = 'a_position', vaoName = 'meshVAO', nPerVert = 3)
# VBO for colors
prog.createVBO(
vboName = 'vertColor', varName = 'a_color', vaoName = 'meshVAO', nPerVert = 3)
return prog
def prepareShapeProgram(self, pick=False):
"""Create an openGL program and all associated buffers to render mesh triangles"""
if pick:
prog = self.prepareFlatShaderProgram()
else:
prog = self.preparePrettyShaderProgram()
def drawMesh():
glBindVertexArray(prog.vaoHandle['meshVAO'])
glDrawArrays(GL_TRIANGLES, 0, 3*self.nFaces)
prog.drawFunc = drawMesh
if pick:
self.meshPickPrograms.append(prog)
self.shapePickProg = prog
else:
self.meshPrograms.append(prog)
self.shapeProg = prog
def prepareEdgeProgram(self):
"""Create an openGL program and all associated buffers to render mesh edges"""
prog = self.preparePrettyShaderProgram()
def drawMesh():
glBindVertexArray(prog.vaoHandle['meshVAO'])
edgeArrLen = 6*self.nEdges if self.drawShape else 12*self.nEdges
glDrawArrays(GL_TRIANGLES, 0, edgeArrLen)
prog.drawFunc = drawMesh
self.meshPrograms.append(prog)
self.edgeProg = prog
def prepareEdgePickProgram(self):
"""Create an openGL program and all associated buffers to render mesh edges"""
prog = self.prepareFlatShaderProgram()
def drawMesh():
glBindVertexArray(prog.vaoHandle['meshVAO'])
edgeArrLen = 6*self.nEdges if self.drawShape else 12*self.nEdges
glDrawArrays(GL_TRIANGLES, 0, edgeArrLen)
prog.drawFunc = drawMesh
self.meshPickPrograms.append(prog)
self.edgePickProg = prog
def prepareVertexProgram(self):
"""Create an openGL program to draw a dot at every vertex"""
# Need to make sure we can adjust the size of the points first
glEnable( GL_PROGRAM_POINT_SIZE )
prog = self.preparePrettyShaderProgram()
def drawMesh():
# glPointSize(self.pointSize)
glBindVertexArray(prog.vaoHandle['meshVAO'])
vertArrLen = self.nVerts*self.nRadialPoints*3 if self.drawShape else 2*self.nVerts*self.nRadialPoints*3
glDrawArrays(GL_TRIANGLES, 0, vertArrLen)
prog.drawFunc = drawMesh
self.meshPrograms.append(prog)
self.vertProg = prog
def prepareVertexPickProgram(self):
"""Create an openGL program to draw a dot at every vertex"""
# Need to make sure we can adjust the size of the points first
glEnable( GL_PROGRAM_POINT_SIZE )
prog = self.prepareFlatShaderProgram()
def drawMesh():
# glPointSize(6*self.pointSize)
glBindVertexArray(prog.vaoHandle['meshVAO'])
vertArrLen = self.nVerts*self.nRadialPoints*3 if self.drawShape else 2*self.nVerts*self.nRadialPoints*3
glDrawArrays(GL_TRIANGLES, 0, vertArrLen)
prog.drawFunc = drawMesh
self.meshPickPrograms.append(prog)
self.vertPickProg = prog
def prepareVectorProgram(self):
"""Create an openGL program to draw vectors on the surface of a mesh"""
prog = self.preparePrettyShaderProgram()
def drawMesh():
glBindVertexArray(prog.vaoHandle['meshVAO'])
glDrawArrays(GL_TRIANGLES, 0, self.nVectorVerts)
prog.drawFunc = drawMesh
self.meshPrograms.append(prog)
self.vectorProg = prog
def prepareStreamlineProgram(self):
"""Create an openGl program to draw streamlines"""
prog = self.preparePrettyShaderProgram()
def drawMesh():
glBindVertexArray(prog.vaoHandle['meshVAO'])
edgeArrLen = 6*self.nStreamlineSegments
glDrawArrays(GL_TRIANGLES, 0, edgeArrLen)
prog.drawFunc = drawMesh
self.meshPrograms.append(prog)
self.streamlineProg = prog
def setMesh(self, mesh):
"""Set a mesh as the current mesh object to be drawn by this viewer"""
# TODO Properly deallocate buffers to make sure nothing is leaking if this
# is called many times
# Save and validate the mesh
self.mesh = mesh
self.checkMesh()
self.nFaces = len(mesh.faces)
self.nVerts = len(mesh.verts)
self.nEdges = len(mesh.edges)
# Compute scale and centering factors. These are stored in the uniforms
# and applied in the shaders
self.computeScale()
self.camera.zoomDist = self.scaleFactor
# Initial camera distance
self.camera.zoomDist = self.scaleFactor
# Clear caches
self.vectorArrowCache = dict()
self.streamlineCache = dict()
def checkMesh(self):
"""
Verify that the mesh has triangular faces and valid positions
"""
# Verify triangle Mesh
for he in self.mesh.halfEdges:
if he.next.next.next is not he:
print("ERROR: Halfedge {} does not have triangular connectivity.".format(str(he)))
raise ValueError("ERROR: MeshDisplay can only display triangular meshes")
# Verify non-nan and non-inf positions
for v in self.mesh.verts:
if np.any(np.isnan(v.position)) or np.any(np.isinf(v.position)):
print("ERROR: Invalid position value at vertex {} = {}".format(str(v),str(v.pos)))
raise ValueError("ERROR: Invalid (nan or inf) position value")
def setShapeColorToDefault(self):
self.colorMethod = 'constant'
self.colorDefinedOn = None
self.colorAttrName = None
self.vMinMax = None
self.cmapName = None
def setShapeColorFromRGB(self, colorAttrName, definedOn='vertex'):
"""Sets the mesh face color from RGB data defined on the vertices"""
# Validate input
if definedOn not in ['face', 'vertex']:
raise ValueError("ERROR: definedOn must be one of [vertex, face]")
self.colorMethod = 'rgbData'
self.colorDefinedOn = definedOn
self.colorAttrName = colorAttrName
def setShapeColorFromScalar(self,
colorScalarAttr,
definedOn='vertex',
vMinMax=None,
cmapName='OrRd'):
"""
Sets the mesh vertex color from a scalar field defined on the vertices
- vMinMax: tuple (min, max) giving the bounds colormap
for the scalar color scale
(the data min/max are used if None)
- cmapName: colormap to use for scalar colors (any matplotlib colormap name)
I recommend 'OrRd' for magnitude data and 'coolwarm' for
negative/positive data (classic blue/red)
"""
# Validate input
if definedOn not in ['face', 'vertex']:
raise ValueError("ERROR: definedOn must be one of [vertex, face]")
# Assign values
self.colorMethod = 'scalarData'
self.colorDefinedOn = definedOn
self.colorAttrName = colorScalarAttr
self.vMinMax = vMinMax
self.cmapName = cmapName
def setVectors(self,
vectorAttrName,
vectorDefinedAt='vertex',
isTangentVector=False,
vectorRefDirAttrName='referenceDirectionR3',
isUnit=False,
nSym=1,
scaleFactor=None):
"""Draws vectors on the surface of the mesh"""
# TODO: Right now we can only draw one type of vector at a time
# Validate input
if vectorDefinedAt not in ['face', 'vertex']:
raise ValueError("ERROR: vectorDefinedAt must be one of [vertex, face]")
if vectorAttrName is None:
self.vectorAttrName = None
self.vectorDefinedAt = None
self.vectorIsTangent = None
self.vectorRefDirAttrName = None
self.vectorIsUnit = None
self.vectorNsym = 1
self.vectorScaleFactor = None
else:
self.vectorAttrName = vectorAttrName
self.vectorDefinedAt = vectorDefinedAt
self.vectorIsTangent = isTangentVector
self.vectorRefDirAttrName = vectorRefDirAttrName
self.vectorIsUnit = isUnit
self.vectorNsym = nSym
self.vectorScaleFactor = scaleFactor
# Prepare a vector drawing program if we don't already have one
if self.vectorProg is None:
self.prepareVectorProgram()
def prepareToPick(self):
"""Sets up datastructures needed to pick from the current mesh"""
# Build forward and reverse lookup tables
self.pickArray = [None] + list(self.mesh.verts) + list(self.mesh.faces) + list(self.mesh.edges)
for i in range(len(self.pickArray)):
self.pickInd[self.pickArray[i]] = i
# Valid that we have enough indices to represent this
if len(self.pickArray) > self.PICK_IND_MAX**3:
raise("ERROR: Do not have enough indices to support picking on a mesh this large. Pack floats better in picking code")
def pickIndAsFloats(self, obj):
"""Return the pick index, represented as 3 floats for use as a color"""
ind = self.pickInd[obj]
v1 = ind / (self.PICK_IND_MAX**2)
ind -= (self.PICK_IND_MAX**2) * v1
v2 = ind / self.PICK_IND_MAX
ind -= self.PICK_IND_MAX * v2
v3 = ind
return np.array([v1,v2,v3], dtype=np.float32)/float(self.PICK_IND_MAX)
def pickResult(self, vals):
"""Return the object selected by a pick"""
ind1 = int(round(vals[0]*self.PICK_IND_MAX))
ind2 = int(round(vals[1]*self.PICK_IND_MAX))
ind3 = int(round(vals[2]*self.PICK_IND_MAX))
ind = ind1*self.PICK_IND_MAX*self.PICK_IND_MAX + ind2*self.PICK_IND_MAX + ind3
return self.pickArray[ind]
def generateAllMeshValues(self):
"""
Updates mesh values in the viewer (meaning positions and possibly colors),
assuming they have been changed on the mesh reference stored herein.
Normals and colormap things are recalculated internally automatically.
Note: The structure of the mesh MAY NOT be changed using this method.
(You may NOT add/remove/modify verts/edges, and this may fail badly)
"""
print("Filling buffers for visualization")
## The data used to generate the image which actually appears onscreen
self.generateFaceData()
self.generateEdgeData()
self.generateVertexData()
if self.vectorAttrName is not None:
self.generateVectorData()
if self.streamlinesEnabled and self.vectorAttrName is not None:
self.generateStreamlines()
## Extra buffers/shaders used to support picking
self.prepareToPick()
self.generateFaceData(pick=True)
self.generateEdgeData(pick=True)
self.generateVertexData(pick=True)
print("Done filling buffers for visualization")
def generateColorscale(self):
"""
Create a colormap and bounds for coloring from scalar data
"""
# Make sure we have valid bounds for the data
if self.vMinMax is not None:
if(self.vMinMax[0] >= self.vMinMax[1]):
raise ValueError("ERROR: min bound must be strictly less than max")
else:
vMin = float('inf')
vMax = -float('inf')
if self.colorDefinedOn == 'vertex':
for v in self.mesh.verts:
vMin = min((vMin, getattr(v, self.colorAttrName)))
vMax = max((vMax, getattr(v, self.colorAttrName)))
elif self.colorDefinedOn == 'face':
for f in self.mesh.faces:
vMin = min((vMin, getattr(f, self.colorAttrName)))
vMax = max((vMax, getattr(f, self.colorAttrName)))
elif self.colorDefinedOn == 'edge':
raise NotImplementedError("Edge shape color definitions not implemented yet")
vMinMax = [vMin, vMax]
# Make sure we don't go crazy if the data is a constant
scale = max((abs(vMinMax[0]),abs(vMinMax[1])))
#if (abs(vMinMax[0] - vMinMax[1]) / scale) < 0.0000001:
#if (abs(vMinMax[0] - vMinMax[1]) / scale) < 1.e-10:
# print("WARNING: mesh vertex color scalar was nearly constant, adjusting bounds slightly to draw")
# vMinMax = [vMinMax[0] - scale*0.01, vMinMax[1] + scale*0.01]
self.vMinMax = vMinMax
# Get color values from the colormap
self.scalarDataColorMap = matplotlib.cm.get_cmap(self.cmapName)
# Make a shorthand function for mapping values to colors
def mapValueToColor(x):
return np.array(self.scalarDataColorMap((x - self.vMinMax[0]) / (self.vMinMax[1]-self.vMinMax[0]))[0:3], dtype=np.float32)
self.scalarColorMapper = mapValueToColor
def generateFaceData(self, pick=False):
"""Generates the positions, normals, and colors for drawing faces"""
facePos = np.zeros((3*self.nFaces,3), dtype=np.float32)
faceNorm = np.zeros((3*self.nFaces,3), dtype=np.float32)
faceColor = np.zeros((3*self.nFaces,3), dtype=np.float32)
# If appropriate, make sure we have a colorscale and map.
# Create a shorthand function to map values to colors
if self.colorMethod == 'scalarData':
self.generateColorscale()
# Iterate through the faces to build arrays
for (i, face) in enumerate(self.mesh.faces):
v1 = face.anyHalfEdge.vertex
v2 = face.anyHalfEdge.next.vertex
v3 = face.anyHalfEdge.next.next.vertex
facePos[3*i ,:] = v1.position
facePos[3*i+1,:] = v2.position
facePos[3*i+2,:] = v3.position
faceNorm[3*i ,:] = v1.normal
faceNorm[3*i+1,:] = v2.normal
faceNorm[3*i+2,:] = v3.normal
# Select the appropriate color from the many possibile ways the
# mesh could be colored
if pick:
faceIndAsFloats = self.pickIndAsFloats(face)
faceColor[3*i, :] = faceIndAsFloats
faceColor[3*i+1,:] = faceIndAsFloats
faceColor[3*i+2,:] = faceIndAsFloats
else:
if self.colorMethod == 'constant':
faceColor[3*i, :] = self.shapeColor[0:3]
faceColor[3*i+1,:] = self.shapeColor[0:3]
faceColor[3*i+2,:] = self.shapeColor[0:3]
elif self.colorMethod == 'rgbData':
if self.colorDefinedOn == 'vertex':
faceColor[3*i, :] = getattr(v1, self.colorAttrName)
faceColor[3*i+1,:] = getattr(v2, self.colorAttrName)
faceColor[3*i+2,:] = getattr(v3, self.colorAttrName)
elif self.colorDefinedOn == 'face':
faceColor[3*i, :] = getattr(face, self.colorAttrName)
faceColor[3*i+1,:] = getattr(face, self.colorAttrName)
faceColor[3*i+2,:] = getattr(face, self.colorAttrName)
elif self.colorDefinedOn == 'edge':
raise NotImplementedError("Edge shape color definitions not implemented yet")
elif self.colorMethod == 'scalarData':
if self.colorDefinedOn == 'vertex':
faceColor[3*i, :] = self.scalarColorMapper(getattr(v1, self.colorAttrName))
faceColor[3*i+1,:] = self.scalarColorMapper(getattr(v2, self.colorAttrName))
faceColor[3*i+2,:] = self.scalarColorMapper(getattr(v3, self.colorAttrName))
elif self.colorDefinedOn == 'face':
faceColor[3*i, :] = self.scalarColorMapper(getattr(face, self.colorAttrName))
faceColor[3*i+1,:] = self.scalarColorMapper(getattr(face, self.colorAttrName))
faceColor[3*i+2,:] = self.scalarColorMapper(getattr(face, self.colorAttrName))
elif self.colorDefinedOn == 'edge':
raise NotImplementedError("Edge shape color definitions not implemented yet")
# Store this new data in the buffers
if pick:
glBindVertexArray(self.shapePickProg.vaoHandle['meshVAO'])
self.shapePickProg.setVBOData('vertPos', facePos)
self.shapePickProg.setVBOData('vertColor', faceColor)
else:
glBindVertexArray(self.shapeProg.vaoHandle['meshVAO'])
self.shapeProg.setVBOData('vertPos', facePos)
self.shapeProg.setVBOData('vertNorm', faceNorm)
self.shapeProg.setVBOData('vertColor', faceColor)
def generateEdgeData(self, pick=False):
"""Generates the positions, normals, and colors for drawing edges"""
edgePos = np.zeros((2*self.nEdges,3), dtype=np.float32)
edgeNorm = np.zeros((2*self.nEdges,3), dtype=np.float32)
edgeColor = np.zeros((2*self.nEdges,3), dtype=np.float32)
for (i, edge) in enumerate(self.mesh.edges):
v1 = edge.anyHalfEdge.vertex
v2 = edge.anyHalfEdge.twin.vertex
edgePos[2*i,:] = v1.position
edgePos[2*i+1,:] = v2.position
edgeNorm[2*i, :] = v1.normal
edgeNorm[2*i+1,:] = v2.normal
if pick:
edgeIndAsFloats = self.pickIndAsFloats(edge)
edgeColor[2*i, :] = edgeIndAsFloats
edgeColor[2*i+1,:] = edgeIndAsFloats
else:
edgeColor[2*i, :] = self.edgeColor
edgeColor[2*i+1,:] = self.edgeColor
# Expand the lines to strips (uncomment alternate verions to scale lines by line length)
if pick:
# stripPos, stripNorm, stripColor = self.expandLinesToStrips(edgePos, edgeNorm, edgeColor, lineWidthCoef=3*self.lineWidthCoef)
stripPos, stripNorm, stripColor = self.expandLinesToStrips(edgePos, edgeNorm, edgeColor,
lineWidth=self.lineWidthScaleCoef*self.medianEdgeLength, relativeWidths=False)
else:
# stripPos, stripNorm, stripColor = self.expandLinesToStrips(edgePos, edgeNorm, edgeColor, lineWidthCoef=self.lineWidthCoef)
stripPos, stripNorm, stripColor = self.expandLinesToStrips(edgePos, edgeNorm, edgeColor,
lineWidth=self.lineWidthScaleCoef*self.medianEdgeLength, relativeWidths=False)
# If we're looking at a wireframe, we need a second set of triangles so
# we get visibility in both directions
if not self.drawShape:
stripPos, stripNorm, stripColor = self.expandTrianglesToFaceBothWays(stripPos, stripNorm, stripColor)
# Store this new data in the buffers
if pick:
glBindVertexArray(self.edgePickProg.vaoHandle['meshVAO'])
self.edgePickProg.setVBOData('vertPos', stripPos)
self.edgePickProg.setVBOData('vertColor', stripColor)
else:
glBindVertexArray(self.edgeProg.vaoHandle['meshVAO'])
self.edgeProg.setVBOData('vertPos', stripPos)
self.edgeProg.setVBOData('vertNorm', stripNorm)
self.edgeProg.setVBOData('vertColor', stripColor)
def generateVertexData(self, pick=False):
"""Generates the positions, normals, and colors for drawing verts"""
vertPos = np.zeros((self.nVerts,3), dtype=np.float32)
vertNorm = np.zeros((self.nVerts,3), dtype=np.float32)
vertColor = np.zeros((self.nVerts,3), dtype=np.float32)
# Iterate through the vertices to fill arrays
for (i, vert) in enumerate(self.mesh.verts):
vertPos[i,:] = vert.position
vertNorm[i,:] = vert.normal
if pick:
vertColor[i,:] = self.pickIndAsFloats(vert)
else:
vertColor[i,:] = self.edgeColor
diskPos, diskNorm, diskColor = self.expandDotsToDisks(vertPos, vertNorm, vertColor, dotWidthCoef=self.lineWidthScaleCoef)
# If we're looking at a wireframe, we need a second set of triangles so
# we get visibility in both directions
if not self.drawShape:
diskPos, diskNorm, diskColor = self.expandTrianglesToFaceBothWays(diskPos, diskNorm, diskColor)
# Store this new data in the buffers
if pick:
glBindVertexArray(self.vertPickProg.vaoHandle['meshVAO'])
self.vertPickProg.setVBOData('vertPos', diskPos)
self.vertPickProg.setVBOData('vertColor', diskColor)
else:
glBindVertexArray(self.vertProg.vaoHandle['meshVAO'])
self.vertProg.setVBOData('vertPos', diskPos)
self.vertProg.setVBOData('vertNorm', diskNorm)
self.vertProg.setVBOData('vertColor', diskColor)
def generateVectorData(self, useCache=True):
"""Computes data for drawing vectors on the mesh, as instructed by setSurfaceDirections()"""
# Generate new vector data
if not useCache or self.vectorAttrName not in self.vectorArrowCache:
# Generate vector starts and ends for vectors in the tangent space
if self.vectorIsTangent:
# We only support vertex-defined directions here at the moment (TODO)
if not self.vectorDefinedAt == 'vertex':
raise ValueError("Vectors in the tangent space must be defined at vertices")
if not self.vectorIsUnit:
raise ValueError("Vectors in the tangent space must be interpreted as unit vectors")
nSym = self.vectorNsym
nTotalVector = self.nVerts * nSym
vecStart = np.zeros((nTotalVector,3), dtype=np.float32)
vecEnd = np.zeros((nTotalVector,3), dtype=np.float32)
# Compute a reasonable length for the direction vectors
# TODO make this vary by vertex
coef = 0.4 if nSym == 1 else 0.2 # lines should be shorter if we're drawing >1 per vertex
unitVectorLength = coef*self.medianEdgeLength
# Rotation increment for symmetric vectors
rotInc = 2.0 * pi / nSym
# Iterate over the vertices to fill the arrays
for (iVert, vert) in enumerate(self.mesh.verts):
for iRot in range(nSym):
# The base point
vecStart[(nSym*iVert + iRot),:] = vert.pos
# The draw-to point
theta = getattr(vert, self.vectorAttrName)
refDir = eu.Vector3(*getattr(vert, self.vectorRefDirAttrName))
vecDir = np.array(refDir.rotate_around(eu.Vector3(*vert.normal), theta + rotInc * iRot), dtype=np.float32)
vecEnd[(nSym*iVert + iRot),:] = vert.pos + normalized(vecDir) * unitVectorLength
# Generate vectors in R3
else:
# Warn if you try to use nSym other than 1 for now
if self.vectorNsym != 1:
raise ValueError("Symmetry not yet supported for vectors in R3")
# Build an array from data stored on vertices
if self.vectorDefinedAt == 'vertex':
nTotalVector = self.nVerts
vecStart = np.zeros((nTotalVector,3), dtype=np.float32)
vecEnd = np.zeros((nTotalVector,3), dtype=np.float32)
for (iVert, vert) in enumerate(self.mesh.verts):
vecStart[iVert,:] = vert.position
vecEnd[iVert,:] = vert.position + getattr(vert, self.vectorAttrName)
# Build an array from data stored on faces
elif self.vectorDefinedAt == 'face':
nTotalVector = self.nFaces
vecStart = np.zeros((nTotalVector,3), dtype=np.float32)
vecEnd = np.zeros((nTotalVector,3), dtype=np.float32)
for (iFace, face) in enumerate(self.mesh.faces):
vecStart[iFace,:] = face.center
vecEnd[iFace,:] = face.center + getattr(face, self.vectorAttrName)
else:
print("ERROR: Unrecognized value for vectorDefinedAt: " + str(self.vectorDefinedAt))
print(" Should be one of 'vertex', 'face'")
raise ValueError("ERROR: Unrecognized value for vectorDefinedAt: " + str(self.vectorDefinedAt))
# Rescale the vectors to a reasonable length
vec = vecEnd - vecStart
if self.vectorScaleFactor is None:
maxLen = np.max(norm(vec, axis=1))
vectorLen = 0.8 * self.medianEdgeLength
scaleFactor = vectorLen / maxLen
else:
scaleFactor = self.vectorScaleFactor
vecEnd = vecStart + (vecEnd - vecStart)*scaleFactor # kind of redundant way to do this...
# Expand the vectors in to prisms that look nice
coef = 0.8 if self.vectorIsTangent else 0.8
vertVecPos, vertVecNorm, vertVecColor = self.expandVectors(vecStart, vecEnd, coef*self.lineWidthScaleCoef*self.medianEdgeLength)
# Store these pretty vectors in the cache
self.vectorArrowCache[self.vectorAttrName] = (vertVecPos, vertVecNorm, vertVecColor)
# Read the vectors from the cache
else:
vertVecPos, vertVecNorm, vertVecColor = self.vectorArrowCache[self.vectorAttrName]
# Size of the ultimate buffer containing this vector data
self.nVectorVerts = vertVecPos.shape[0]
glBindVertexArray(self.vectorProg.vaoHandle['meshVAO'])
self.vectorProg.setVBOData('vertPos', vertVecPos)
self.vectorProg.setVBOData('vertNorm', vertVecNorm)
self.vectorProg.setVBOData('vertColor', vertVecColor)
def expandLinesToStrips(self, linePos, lineNorm, lineColor, lineWidth, relativeWidths=True):
"""
Some platforms (*cough* OSX *cough*) don't support setting linewidth. This function
takes what would be input to GL_LINES and transforms it to GL_TRIANGLES input as line strips
If relativeWidths=True, the line widths are set as a fraction of the line's lenght. Otherwise
the widths are a constant factor of the shape's scale.
"""
# TODO this is exactly what geometry shaders are meant for
# Allocate new arrays
nLines = linePos.shape[0]/2
stripPos = np.zeros((nLines*6,3), dtype=np.float32)
stripNorm = np.zeros((nLines*6,3), dtype=np.float32)
stripColor = np.zeros((nLines*6,3), dtype=np.float32)
# Directions which will be used in construction
forwardVec = linePos[1:2*nLines:2,:] - linePos[0:2*nLines:2,:] # Vector from i-->j along each line
crossI = np.cross(forwardVec, lineNorm[0:2*nLines:2,:]) # The vector for the width of the strip at i
crossJ = np.cross(forwardVec, lineNorm[1:2*nLines:2,:]) # The vector for the width of the strip at j
if relativeWidths:
# The widths for each line are a factor of the lenght the line
lineWidth = 0.1 * norm(forwardVec, axis=1)
crossI = (normalized(crossI).T*lineWidth/2.0).T
crossJ = (normalized(crossJ).T*lineWidth/2.0).T
else:
crossI = normalized(crossI)*lineWidth/2.0
crossJ = normalized(crossJ)*lineWidth/2.0
# Generate the 4 points which will make up triangles for each line
v0 = linePos[0:2*nLines:2,:] + crossI
v1 = linePos[0:2*nLines:2,:] - crossI
v2 = linePos[1:2*nLines:2,:] + crossJ
v3 = linePos[1:2*nLines:2,:] - crossJ
# The two triangles are (v0,v2,v3) and (v0,v3,v1)
stripPos[0:6*nLines:6,:] = v0
stripPos[1:6*nLines:6,:] = v2
stripPos[2:6*nLines:6,:] = v3
stripPos[3:6*nLines:6,:] = v0
stripPos[4:6*nLines:6,:] = v3
stripPos[5:6*nLines:6,:] = v1
## Assign normals and colors to match
stripNorm[0:6*nLines:6,:] = lineNorm[0:2*nLines:2,:]
stripNorm[1:6*nLines:6,:] = lineNorm[1:2*nLines:2,:]
stripNorm[2:6*nLines:6,:] = lineNorm[1:2*nLines:2,:]
stripNorm[3:6*nLines:6,:] = lineNorm[0:2*nLines:2,:]
stripNorm[4:6*nLines:6,:] = lineNorm[1:2*nLines:2,:]
stripNorm[5:6*nLines:6,:] = lineNorm[0:2*nLines:2,:]
stripColor[0:6*nLines:6,:] = lineColor[0:2*nLines:2,:]
stripColor[1:6*nLines:6,:] = lineColor[1:2*nLines:2,:]
stripColor[2:6*nLines:6,:] = lineColor[1:2*nLines:2,:]
stripColor[3:6*nLines:6,:] = lineColor[0:2*nLines:2,:]
stripColor[4:6*nLines:6,:] = lineColor[1:2*nLines:2,:]
stripColor[5:6*nLines:6,:] = lineColor[0:2*nLines:2,:]
return stripPos, stripNorm, stripColor
def expandDotsToDisks(self, dotPos, dotNorm, dotColor, dotWidthCoef=None):
"""
To fit well with expandLinesToStrips(), drawing ugly square points is probably
not sufficient. Use this to expand points to disks
"""
# TODO this is exactly what geometry shaders are meant for
# Size of radial points for each disk
nRad = self.nRadialPoints
dotRad = 2 * dotWidthCoef * self.medianEdgeLength
# Allocate new arrays
nDots = dotPos.shape[0]
diskPos = np.zeros((nDots*nRad*3,3), dtype=np.float32)
diskNorm = np.zeros((nDots*nRad*3,3), dtype=np.float32)
diskColor = np.zeros((nDots*nRad*3,3), dtype=np.float32)
# We need to pick an arbitrary x direction in the tangent space of each