/
module3d.py
1188 lines (969 loc) · 42.3 KB
/
module3d.py
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
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
**Project Name:** MakeHuman
**Product Home Page:** http://www.makehuman.org/
**Code Home Page:** https://bitbucket.org/MakeHuman/makehuman/
**Authors:** Marc Flerackers, Glynn Clements, Jonas Hauquier
**Copyright(c):** MakeHuman Team 2001-2017
**Licensing:** AGPL3
This file is part of MakeHuman (www.makehuman.org).
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
Abstract
--------
TODO
"""
import weakref
import numpy as np
import unique # Bugfix for numpy.unique on older numpy versions
import material
class FaceGroup(object):
"""
A FaceGroup (a group of faces with a unique name).
Each Face object can be part of one FaceGroup. Each face object has an
attribute, *group*, storing the FaceGroup it is a member of.
The FaceGroup object contains a list of the faces in the group and must be
kept in sync with the FaceGroup references stored by the individual faces.
.. py:attribute:: name
The name. str
.. py:attribute:: parent
The parent. :py:class:`module3d.Object3D`
:param name: The name of the group.
:type name: str
"""
black = np.zeros(3, dtype=np.uint8)
def __init__(self, object, name, idx):
self.object = object
self.name = name
self.idx = idx
self.color = None
self.colorID = self.black.copy()
def __str__(self):
"""
This method returns a string containing the name of the FaceGroup. This
method is called when the object is passed to the 'print' function.
**Parameters:** This method has no parameters.
"""
return 'facegroup %s' % self.name
def setColor(self, rgba):
self.color = np.asarray(rgba, dtype = np.uint8)
def getObject(self):
if self.__object:
return self.__object()
else:
return None
def setObject(self, value):
if value is None:
self.__object = None
else:
# Ensure link to gui3d.object is weak to avoid circular references (which break garbage collection)
self.__object = weakref.ref(value)
object = property(getObject, setObject)
@property
def parent(self):
return self.object
class Object3D(object):
def __init__(self, objName, vertsPerPrimitive=4):
self.clear()
self.name = objName
self.vertsPerPrimitive = vertsPerPrimitive
self._faceGroups = []
self._groups_rev = {}
self.cameraMode = 0
self._visibility = True
self.pickable = False
self.calculateTangents = True # TODO disable when not needed by shader
self.object3d = None
self._priority = 0
self.MAX_FACES = 8
# Cache used for retrieving vertex colors multiplied with material diffuse color
self._old_diff = None
self._r_color_diff = None
self.__object = None
def clone(self, scale=1.0, filterMaskedVerts=False): # TODO it's also possible to add offset to the parameters
"""
Create a clone of this mesh, with adapted scale.
If filterVerts is True, all vertices that are not required (do not
belong to any visible face) are removed and vertex mapping is added to
cloned object (see filterMaskedVerts()). For a face mapping, the
facemask of the original mesh can be used.
By default cloning a mesh links it to the object of its parent, remove
the link by setting other.object to None before attaching it to a new
object.
"""
if self.getFaceCount(excludeMaskedFaces=filterMaskedVerts) == 0:
raise RuntimeError("Error cloning mesh %s. Cannot clone a mesh with 0 (unmasked) faces!", self.name)
other = type(self)(self.name, self.vertsPerPrimitive)
for prop in ['cameraMode', 'visibility', 'pickable',
'calculateTangents', 'priority', 'MAX_FACES', 'object']:
setattr(other, prop, getattr(self, prop))
for fg in self.faceGroups:
ofg = other.createFaceGroup(fg.name)
if fg.color is not None:
ofg.color = fg.color.copy()
else:
ofg.color = fg.color
if filterMaskedVerts:
self.filterMaskedVerts(other, update=False)
if scale != 1:
other.coord = scale * other.coord
else:
other.setCoords(scale * self.coord)
other.setColor(self.color.copy())
other.setUVs(self.texco.copy())
other.setFaces(self.fvert.copy(), self.fuvs.copy(), self.group.copy())
other.changeFaceMask(self.face_mask.copy())
other.calcNormals()
other.updateIndexBuffer()
return other
def transformed(self, transform_mat, filterMaskedVerts=False):
"""Create a clone of this mesh with its coordinates transformed
with the specified transformation matrix. filterMaskedVerts works the
same is for clone()
"""
if transform_mat.shape == (4,4):
translation = transform_mat[:3, 3]
transform_mat = transform_mat[:3,:3]
else:
translation = np.zeros(3, dtype=np.float32)
result = self.clone(filterMaskedVerts=filterMaskedVerts)
coords = np.dot(transform_mat, result.getCoords().T).T
coords += translation
result.changeCoords(coords)
result.calcNormals()
result.update()
return result
@property
def parent_map(self):
"""
Maps vertex indices from this mesh to its original parent mesh
(self.parent). This happens recursively to the topmost parent.
Forward vertex mapping (self -> self.parent):
parent_map[idx] = mIdx: self.coord[idx] -> self.parent.coord[mIdx]
Will return a (n, self.MAX_FACES) array if this chain of meshes
contains a subdivided mesh.
Note that vertex maps only support one subdivision in a chain of mesh
to parent meshes.
"""
if not hasattr(self, 'parent') or not self.parent:
return None
if not hasattr(self, '_parent_map'):
mapping = np.arange(self.getVertexCount(), dtype=np.uint32)
else:
mapping = self._parent_map
# Traverse to parent
pmap = self.parent.parent_map
if pmap is None:
return mapping
else:
# Combine mappings to topmost parent
return pmap[mapping]
@property
def parent_map_weights(self):
return np.ones(self.getVertexCount(), dtype=np.float32)
@property
def inverse_parent_map(self):
"""
Maps vertex indices from original parent mesh (self.parent) to
this mesh (-1 if vertex is removed in this mesh).
This happens recursively to the topmost parent.
Reverse vertex mapping:
inverse_parent_map[idx] = mIdx: self.parent.coord[idx] -> self.coord[mIdx]
Will return a (n, 1+self.MAX_FACES*2) array if this chain of meshes
contains a subdivided mesh.
Note that vertex maps only support one subdivision in a chain of mesh
to parent meshes.
"""
# TODO will require nxn matrix if subdivided (catmull-clark module)
if not hasattr(self, 'parent') or not self.parent:
return None
if not hasattr(self, '_inverse_parent_map'):
mapping = np.arange(self.parent.getVertexCount(), dtype=np.int32)
else:
mapping = self._inverse_parent_map
# Traverse to parent
pmap = self.parent.inverse_parent_map
if pmap is None:
return mapping
else:
# Combine mappings to topmost parent
if len(mapping.shape) > 1:
shape = (len(pmap), mapping.shape[1])
else:
shape = len(pmap)
result = - np.ones(shape, dtype=np.int32)
idx = np.where(pmap > -1)
result[idx] = mapping[ pmap[idx] ]
return result
def filterMaskedVerts(self, other, update=True):
"""
Set the vertices, faces and vertex attributes of other object to the
vertices and faces of this mesh object, with the hidden faces and
vertices filtered out.
The other mesh contains a parent_map which maps vertex indices from
the other to its original mesh and inverse_parent_map which maps vertex
indexes from original to other (-1 if removed).
other.parent is set to the original mesh.
"""
# TODO or build a chain of parents?
if hasattr(self, 'parent') and self.parent:
other.parent = self.parent
else:
other.parent = self
# Forward vertex mapping:
# _parent_map[idx] = mIdx: other.coord[idx] -> self.coord[mIdx]
other._parent_map = np.unique(self.getVerticesForFaceMask(self.face_mask))
# Reverse vertex mapping:
# _inverse_parent_map[idx] = mIdx: self.coord[idx] -> other.coord[mIdx]
other._inverse_parent_map = - np.ones(self.getVertexCount(), dtype=np.int32)
other._inverse_parent_map[other.parent_map] = np.arange(len(other._parent_map), dtype=np.int32)
#other._inverse_parent_map = np.ma.masked_less(other._inverse_parent_map, 0) # TODO might be useful
other.setCoords(self.coord[other.parent_map])
other.setColor(self.color[other.parent_map])
# Filter out and remap masked faces
fvert = self.fvert[self.face_mask]
for i in range(self.vertsPerPrimitive):
fvert[:,i] = other._inverse_parent_map[fvert[:,i]]
# Filter out and remap unused UVs
fuvs = self.fuvs[self.face_mask]
uv_idx = np.unique(fuvs.reshape(-1))
inverse_uv_idx = - np.ones(self.texco.shape[0], dtype=np.int32)
inverse_uv_idx[uv_idx] = np.arange(uv_idx.shape[0], dtype=np.int32)
for i in range(self.vertsPerPrimitive):
fuvs[:,i] = inverse_uv_idx[fuvs[:,i]]
other.setUVs(self.texco[uv_idx])
other.setFaces(fvert, fuvs, self.group[self.face_mask])
if update:
other.calcNormals()
other.updateIndexBuffer()
def getCenter(self):
"""
Get center position of mesh using center of its bounding box.
"""
bBox = self.calcBBox()
bmin = np.asarray(bBox[0], dtype=np.float32)
bmax = np.asarray(bBox[1], dtype=np.float32)
return -(bmin + ((bmax - bmin)/2))
def calcFaceNormals(self, ix = None):
"""
Calculate the face normals. A right-handed coordinate system is assumed,
which requires mesh faces to be defined with counter clock-wise vertex order.
Face normals are not normalized.
Faces are treated as if they were triangles (using only the 3 first verts),
so for quads with non co-planar points, inaccuracies may occur (even though
those have a high change of being corrected by neighbouring faces).
"""
# We assume counter clock-wise winding order
# (if your normals are inversed, you're using clock-wise winding order)
if ix is None:
ix = np.s_[:]
fvert = self.coord[self.fvert[ix]]
v1 = fvert[:,0,:]
v2 = fvert[:,1,:]
v3 = fvert[:,2,:]
va = v1 - v2
vb = v2 - v3
self.fnorm[ix] = np.cross(va, vb)
def calcVertexNormals(self, ix = None):
"""
Calculate per-vertex normals from the face normals for smooth shading
the model. Requires face normals to be calculated first.
"""
self.markCoords(ix, norm=True)
if ix is None:
ix = np.s_[:]
vface = self.vface[ix]
norms = self.fnorm[vface]
norms *= np.arange(self.MAX_FACES)[None,:,None] < self.nfaces[ix][:,None,None]
norms = np.sum(norms, axis=1)
norms /= np.sqrt(np.sum(norms ** 2, axis=-1))[:,None]
self.vnorm[ix] = norms
def calcVertexTangents(self, ix = None):
"""
Calculate vertex tangents using Lengyel’s Method.
"""
if not self.has_uv:
return
self.markCoords(ix, norm=True)
if ix is None:
ix = np.s_[:]
xLen = self.getVertexCount()
f_ix = np.s_[:]
else:
xLen = len(ix)
f_ix = np.unique(self.vface[ix])
# This implementation is based on
# http://www.terathon.com/code/tangent.html
tan = np.zeros((xLen, 2, 3), dtype=np.float32)
fvert = self.coord[self.fvert[f_ix]]
v1 = fvert[:,0,:]
v2 = fvert[:,1,:]
v3 = fvert[:,2,:]
x1 = v2[:,0] - v1[:,0]
x2 = v3[:,0] - v1[:,0]
y1 = v2[:,1] - v1[:,1]
y2 = v3[:,1] - v1[:,1]
z1 = v2[:,2] - v1[:,2]
z2 = v3[:,2] - v1[:,2]
fuv = self.texco[self.fuvs[f_ix]]
w1 = fuv[:,0,:]
w2 = fuv[:,1,:]
w3 = fuv[:,2,:]
s1 = w2[:,0] - w1[:,0]
s2 = w3[:,0] - w1[:,0]
t1 = w2[:,1] - w1[:,1]
t2 = w3[:,1] = w1[:,1]
# Prevent NANs because of borked up UV coordinates # TODO perhaps remove this
s1[np.argwhere(np.equal(s1, 0.0))] = 0.0000001
s2[np.argwhere(np.equal(s2, 0.0))] = 0.0000001
t1[np.argwhere(np.equal(t1, 0.0))] = 0.0000001
t2[np.argwhere(np.equal(t2, 0.0))] = 0.0000001
r = np.repeat(1.0, len(s1)) / ( (s1 * t2) - (s2 * t1) )
sdir = np.zeros((self.getFaceCount(),3), dtype=np.float32)
tdir = np.zeros((self.getFaceCount(),3), dtype=np.float32)
sdir[f_ix] = np.column_stack( [ ( (t2 * x1) - (t1 * x2) ) * r,
( (t2 * y1) - (t1 * y2) ) * r,
( (t2 * z1) - (t1 * z2) ) * r ] )
tdir[f_ix] = np.column_stack( [ ( (s1 * x2) - (s2 * x1) ) * r,
( (s1 * y2) - (s2 * y1) ) * r,
( (s1 * z2) - (s2 * z1) ) * r ] )
tan[:,0] = np.sum(sdir[self.vface[ix]])
tan[:,1] = np.sum(tdir[self.vface[ix]])
# Gramm-Schmidt orthogonalize
dotP = dot_v3(self.vnorm[ix], tan[:,0] )
# Duplicate dot product value in 3 columns because scalar * (n x 3)
# does not work
dotP = np.tile(dotP, (3,1)).transpose().reshape(len(tan),3)
self.vtang[ix,:3] = tan[:,0] - dotP * self.vnorm[ix]
# Normalize
self.vtang[ix,:3] /= np.sqrt(np.sum(self.vtang[ix,:3] ** 2, axis=-1))[:,None]
# Determine Handedness as w parameter
self.vtang[ix, 3] = 1.0
indx = np.argwhere(np.less(dot_v3( \
np.cross( \
self.vnorm[ix], \
tan[:,0]), \
tan[:,1]), \
0.0))
self.vtang[ix,3][indx] = -1.0
def getObject(self):
if self.__object:
return self.__object()
else:
return None
def setObject(self, value):
if value is None:
self.__object = None
else:
# Ensure link to gui3d.object is weak to avoid circular references (which break garbage collection)
self.__object = weakref.ref(value)
object = property(getObject, setObject)
@property
def faceGroups(self):
return iter(self._faceGroups)
@property
def faceGroupCount(self):
return len(self._faceGroups)
def clear(self):
"""
Clears both local and remote data to repurpose this object
"""
# Clear remote data
self._faceGroups = []
self._transparentPrimitives = 0
self.fvert = [] # Reference to vertex attributes (coordinate, normal, color, tang) that form the faces (idx = face idx)
self.fnorm = [] # Stores the face normal of the faces (idx = face idx)
self.fuvs = [] # References to UVs at the verts of the faces (idx = face idx) (NOTE: UVs are not tied to vertex IDs, and are not necessarily uniform per vertex, like the other attributes!)
self.group = [] # Determines facegroup per face (idx = face idx)
self.face_mask = [] # Determines visibility per face (idx = face idx)
self.texco = [] # UV coordinates (idx = uv idx)
self.coord = [] # Vertex coordinates (positions) (idx = vertex idx)
self.vnorm = [] # Vertex normals (idx = vertex idx)
self.vtang = [] # Vertex tangents (idx = vertex idx)
self.color = [] # Vertex colors (idx = vertex idx)
self.vface = [] # References the faces that a vertex belongs to (limited to MAX_FACES) (idx = vertex idx)
self.nfaces = 0 # Polycount
self.ucoor = False # Update flags for updating to OpenGL renderbuffers
self.unorm = False
self.utang = False
self.ucolr = False
self.utexc = False
self.has_uv = False
if hasattr(self, 'index'): del self.index
if hasattr(self, 'grpix'): del self.grpix
self.vmap = None # Maps unwelded vertices back to original welded ones (idx = unwelded vertex idx)
self.tmap = None # Maps unwelded vertex texture (UV) coordinates back to original ones (idx = unwelded vertex idx)
self._inverse_vmap = None # Cached inverse of vmap: maps original welded vert idx (coord) to one or multiple unwelded vert idxs (r_coord)
# Unwelded vertex buffers used by OpenGL
if hasattr(self, 'r_coord'): del self.r_coord
if hasattr(self, 'r_texco'): del self.r_texco
if hasattr(self, 'r_vnorm'): del self.r_vnorm
if hasattr(self, 'r_vtang'): del self.r_vtang
if hasattr(self, 'r_color'): del self.r_color
if hasattr(self, 'r_faces'): del self.r_faces
def setCoords(self, coords):
nverts = len(coords)
self.coord = np.asarray(coords, dtype=np.float32)
self.vnorm = np.zeros((nverts, 3), dtype=np.float32)
self.vtang = np.zeros((nverts, 4), dtype=np.float32)
self.color = np.zeros((nverts, 4), dtype=np.uint8) + 255
self.vface = np.zeros((nverts, self.MAX_FACES), dtype=np.uint32)
self.nfaces = np.zeros(nverts, dtype=np.uint8)
self.orig_coord = self.coord.copy() # Keep a copy of the original coordinates
self.ucoor = True
self.unorm = True
self.utang = True
self.ucolr = True
self.markCoords(None, True, True, True)
def getVertexCount(self, excludeMaskedVerts=False):
#return len(self.vface)
if excludeMaskedVerts:
return np.count_nonzero(self.getVertexMaskForFaceMask(self.getFaceMask()))
return len(self.coord)
def getCoords(self, indices = None):
if indices is None:
indices = np.s_[...]
return self.coord[indices]
def getNormals(self, indices = None):
if indices is None:
indices = np.s_[...]
return self.vnorm[indices]
def markCoords(self, indices = None, coor = False, norm = False, colr = False):
if isinstance(indices, tuple):
indices = indices[0]
nverts = len(self.coord)
if coor:
if indices is None:
self.ucoor = True
else:
if self.ucoor is False:
self.ucoor = np.zeros(nverts, dtype=bool)
if self.ucoor is not True:
self.ucoor[indices] = True
if norm:
if indices is None:
self.unorm = self.utang = True
else:
if self.unorm is False:
self.unorm = self.utang = np.zeros(nverts, dtype=bool)
if self.unorm is not True:
self.unorm[indices] = True
self.utang[indices] = True
if colr:
if indices is None:
self.ucolr = True
else:
if self.ucolr is False:
self.ucolr = np.zeros(nverts, dtype=bool)
if self.ucolr is not True:
self.ucolr[indices] = True
def changeCoords(self, coords, indices = None):
self.markCoords(indices, coor=True)
if indices is None:
indices = np.s_[...]
self.coord[indices] = coords
def setUVs(self, uvs):
self.texco = np.asarray(uvs, dtype=np.float32)
self.utexc = True
def getUVCount(self):
return len(self.texco)
def getUVs(self, indices = None):
if indices is None:
indices = np.s_[...]
return self.texco[indices]
def markUVs(self, indices = None):
if isinstance(indices, tuple):
indices = indices[0]
ntexco = len(self.texco)
if indices is None:
self.utexc = True
else:
if self.utexc is False:
self.utexc = np.zeros(ntexco, dtype=bool)
if self.utexc is not True:
self.utexc[indices] = True
def setFaces(self, verts, uvs = None, groups = None, skipUpdate = False):
nfaces = len(verts)
self.fvert = np.empty((nfaces, self.vertsPerPrimitive), dtype=np.uint32)
self.fnorm = np.zeros((nfaces, 3), dtype=np.float32)
self.fuvs = np.zeros(self.fvert.shape, dtype=np.uint32)
self.group = np.zeros(nfaces, dtype=np.uint16)
self.face_mask = np.ones(nfaces, dtype=bool)
if nfaces != 0:
self.fvert[...] = verts
if uvs is not None:
self.fuvs[...] = uvs
if groups is not None:
self.group[...] = groups
self.has_uv = uvs is not None
if not skipUpdate:
self._update_faces()
def changeFaceMask(self, mask, indices = None):
if indices is None:
indices = np.s_[...]
self.face_mask[indices] = mask
def getFaceMask(self, indices = None):
if indices is None:
indices = np.s_[...]
return self.face_mask[indices]
def hasUVs(self):
return self.has_uv
def getFaceCount(self, excludeMaskedFaces=False):
if excludeMaskedFaces:
return np.count_nonzero(self.getFaceMask())
return len(self.fvert)
def getFaceVerts(self, indices = None):
if indices is None:
indices = np.s_[...]
return self.fvert[indices]
def getFaceUVs(self, indices = None):
if indices is None:
indices = np.s_[...]
return self.fuvs[indices]
@property
def inverse_vmap(self):
"""
The inverse of vmap: a mapping of original welded (relating to UVs)
vertex (coord indices) to a set of unwelded vertices that represent the
same coordinate (r_coord indices).
"""
if self._inverse_vmap is None:
# TODO this loop is quite slow and could benefit from numpy optimization
originalToUnweldedMap = {}
for unweldedIdx, originalIdx in enumerate(self.vmap):
if originalIdx not in originalToUnweldedMap:
originalToUnweldedMap[originalIdx] = []
originalToUnweldedMap[originalIdx].append(unweldedIdx)
self._inverse_vmap = originalToUnweldedMap
return self._inverse_vmap
def _update_faces(self):
# Construct vface: arrange face indices for same v_idx in different columns
# Every row in the vface matrix contains a variable number of valid columns
# (the number of valid columns for each row is stored in the nfaces array)
map_ = np.argsort(self.fvert.flat)
vi = self.fvert.flat[map_]
# Map v_idx entries to row numbers of fvert (face_idx)
fi = np.mgrid[:self.fvert.shape[0],:self.fvert.shape[1]][0].flat[map_].astype(np.uint32)
del map_
ix, first = np.unique(vi, return_index=True)
n = first[1:] - first[:-1] # entry-skip count, or the number of occurences of every idx
n_last = len(vi) - first[-1] # Number of occurences of last idx
n = np.hstack((n, np.array([n_last]))) # Append last to complete n
# Store number of valid columns per line in vface
self.nfaces[ix] = n.astype(np.uint8)
try:
for i in range(len(ix)):
# Unfortunately these type of slices require a python loop
self.vface[ix[i],:n[i]] = fi[first[i]:][:n[i]]
except Exception as e:
import log
log.error("Failed to index faces of mesh %s, you are probably loading a mesh with mixed nb of verts per face (do not mix tris and quads). Or your mesh has too many faces attached to one vertex (the maximum is %s-poles). In the second case, either increase MAX_FACES for this mesh, or improve the mesh topology. Original error message: (%s) %s", self.name, self.MAX_FACES, type(e), format(str(e)))
raise RuntimeError('Incompatible mesh topology.')
def getVertexWeights(self, parentWeights):
"""
Map armature weights mapped to the root parent (original mesh) to this
child mesh. Returns parentWeights unaltered if this mesh has no parent.
If this is a proxy mesh, parentWeights should be the weights mapped
through the proxy.getVertexWeights() method first.
This particular vertex weights mapping is only used for exporting rigged
meshes, as in MakeHuman only unsubdivided meshes are posed, and then
smoothed in their posed state if required. Vertices are not removed
within MH when faces are hidden, either.
"""
if not hasattr(self, 'parent') or not self.parent:
return parentWeights
vmap = self.inverse_parent_map
vwmap = self.parent_map_weights
from collections import OrderedDict
weights = OrderedDict()
for bname, (verts,wghts) in list(parentWeights.data.items()):
vgroup = []
empty = True
for (v,wt) in zip(verts,wghts):
mvs = vmap[v]
if isinstance(mvs, (int, np.int32)):
mvs = [mvs]
for mv in mvs:
w = vwmap[mv]
if mv > -1:
vgroup.append((mv, w * wt))
empty = False
if not empty:
weights[bname] = vgroup
return parentWeights.create(weights, self.getVertexCount())
def updateIndexBuffer(self):
self.updateIndexBufferVerts()
self.updateIndexBufferFaces()
def updateIndexBufferVerts(self):
packed = self.fvert.astype(np.uint64) << 32
packed |= self.fuvs
packed = packed.reshape(-1)
u, rev = np.unique(packed, return_inverse=True)
del packed
unwelded = u[:,None] >> np.array([[32,0]], dtype=np.uint64)
unwelded = unwelded.astype(np.uint32)
nverts = len(unwelded)
iverts = rev.reshape(self.fvert.shape)
del rev, u
self.vmap = unwelded[:,0]
self.tmap = unwelded[:,1]
self._inverse_vmap = None
del unwelded
self.r_coord = np.empty((nverts, 3), dtype=np.float32)
self.r_texco = np.empty((nverts, 2), dtype=np.float32)
self.r_vnorm = np.zeros((nverts, 3), dtype=np.float32)
self.r_vtang = np.zeros((nverts, 4), dtype=np.float32)
self.r_color = np.zeros((nverts, 4), dtype=np.uint8) + 255
self.r_faces = np.array(iverts, dtype=np.uint32)
def updateIndexBufferFaces(self):
index = self.r_faces[self.face_mask]
group = self.group[self.face_mask]
if len(group) > 0:
order = np.argsort(group)
group = group[order]
index = index[order]
group, start = np.unique(group, return_index=True)
count = np.empty(len(start), dtype=np.uint32)
count[:-1] = start[1:] - start[:-1]
count[-1] = len(index) - start[-1]
grpix = np.zeros((max(self.group)+1,2), dtype=np.uint32)
grpix[group,0] = start
grpix[group,1] = count
else:
grpix = np.zeros((0,2), dtype=np.uint32)
self.index = index
self.grpix = grpix
self.ucoor = True
self.unorm = True
self.utang = True
self.ucolr = True
self.utexc = True
self.sync_all()
def sync_coord(self):
if self.ucoor is False:
return
if self.vmap is None or len(self.vmap) == 0:
return
if self.ucoor is True:
self.r_coord[...] = self.coord[self.vmap]
else:
self.r_coord[self.ucoor[self.vmap]] = self.coord[self.vmap][self.ucoor[self.vmap]]
self.ucoor = False
def sync_norms(self):
if self.unorm is False:
return
if self.vmap is None or len(self.vmap) == 0:
return
if self.unorm is True:
self.r_vnorm[...] = self.vnorm[self.vmap]
else:
self.r_vnorm[self.unorm[self.vmap]] = self.vnorm[self.vmap][self.unorm[self.vmap]]
self.unorm = False
def sync_tangents(self):
if not self.has_uv:
return
if self.utang is False:
return
if self.vmap is None or len(self.vmap) == 0:
return
if self.utang is True:
self.r_vtang[...] = self.vtang[self.vmap]
else:
self.r_vtang[self.utang[self.vmap]] = self.vtang[self.vmap][self.utang[self.vmap]]
self.utang = False
def sync_color(self):
if self.ucolr is False:
return
if self.vmap is None or len(self.vmap) == 0:
return
if self.ucolr is True:
self.r_color[...] = self.color[self.vmap]
else:
self.r_color[self.ucolr[self.vmap]] = self.color[self.vmap][self.ucolr[self.vmap]]
self.ucolr = False
self._r_color_diff = None
def sync_texco(self):
if not self.has_uv:
return
if self.utexc is False:
return
if self.tmap is None or len(self.tmap) == 0:
return
if self.utexc is True:
self.r_texco[...] = self.texco[self.tmap]
else:
self.r_texco[self.utexc[self.tmap]] = self.texco[self.tmap][self.utexc[self.tmap]]
self.utexc = False
def sync_all(self):
self.sync_coord()
self.sync_norms()
if self.calculateTangents:
self.sync_tangents()
self.sync_color()
self.sync_texco()
def createFaceGroup(self, name):
"""
Creates a new module3d.FaceGroup with the given name.
:param name: The name for the face group.
:type name: [float, float, float]
:return: The new face group.
:rtype: :py:class:`module3d.FaceGroup`
"""
idx = len(self._faceGroups)
fg = FaceGroup(self, name, idx)
self._groups_rev[name] = fg
self._faceGroups.append(fg)
return fg
def setColor(self, color):
"""
Sets the vertex colors for the entire object.
:param color: The color in rgba.
:type color: [byte, byte, byte, byte]
"""
color = np.asarray(color, dtype=np.uint8)
if len(color.shape) == 1: # One color for all vertices
if len(color) == 3:
# Add alpha component to simple RGB color
color = list(color) + [255]
self.color[:] = color
else:
self.color[...] = color[None,:]
self.markCoords(colr=True)
self.sync_color()
@property
def r_color_diff(self):
"""
Vertex colors multiplied with the diffuse material color.
"""
if self._r_color_diff is None:
self._r_color_diff = np.zeros(self.r_color.shape, dtype = np.uint8)
self._old_diff = None
diff = self.material.diffuseColor.values + [self.material.opacity]
if diff != self._old_diff:
# Update diffuse * vertex colors
self._r_color_diff[:] = diff * self.r_color
self._old_diff = diff
return self._r_color_diff
@property
def visibility(self):
return self._visibility
def setVisibility(self, visible):
self.visibility = visible
@visibility.setter
def visibility(self, visible):
"""
This method sets the visibility of the object.
:param visible: Whether or not the object is visible.
:type visible: Boolean
"""
self._visibility = visible
def setPickable(self, pickable):
"""
This method sets the pickable flag of the object.
:param pickable: Whether or not the object is pickable.
:type pickable: Boolean
"""
self.pickable = pickable
def getPriority(self):
"""
The rendering priority of this object.
Objects with higher priorities will be drawn later.
Common priorities used:
file description 2D/3D priority
core/mhmain.py background-gradient 2D -200
0_modeling_background.py background 2D -90
core/mhmain.py human 3D 0
3_libraries_clothes_chooser.py clothing 3D 10
3_libraries_polygon_hair_chooser.py hair 3D 20
2_posing_armature.py armature 3D 30
0_modeling_a_measurement.py measureMesh 2D 50
5_settings_censor.py censor rectangles 2D 80
apps/gui/guifiles.py black frame 2D 90
"""
return self._priority
def setPriority(self, priority):
"""
Set the rendering priority of this object.
Objects with higher priorities will be drawn later.
Common priorities used:
file description 2D/3D priority
0_modeling_background.py background 2D -90
core/mhmain.py human 3D 0
3_libraries_clothes_chooser.py clothing 3D 10
3_libraries_polygon_hair_chooser.py hair 3D 20
2_posing_armature.py armature 3D 30
0_modeling_a_measurement.py measureMesh 2D 50
5_settings_censor.py censor rectangles 2D 80
apps/gui/guifiles.py black frame 2D 90
"""
self._priority = priority
priority = property(getPriority, setPriority)
@property
def material(self):
if not self.object and hasattr(self, 'parent'):