/
volmesh.py
4209 lines (3419 loc) · 123 KB
/
volmesh.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
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from itertools import product
from random import sample
from compas.datastructures.datastructure import Datastructure
from compas.datastructures.attributes import VertexAttributeView
from compas.datastructures.attributes import EdgeAttributeView
from compas.datastructures.attributes import FaceAttributeView
from compas.datastructures.attributes import CellAttributeView
from compas.datastructures import Mesh
from compas.files import OBJ
from compas.geometry import Point
from compas.geometry import Vector
from compas.geometry import Line
from compas.geometry import Polygon
from compas.geometry import Polyhedron
from compas.geometry import Box
from compas.geometry import add_vectors
from compas.geometry import bestfit_plane
from compas.geometry import centroid_points
from compas.geometry import centroid_polygon
from compas.geometry import centroid_polyhedron
from compas.geometry import distance_point_point
from compas.geometry import length_vector
from compas.geometry import normal_polygon
from compas.geometry import normalize_vector
from compas.geometry import project_point_plane
from compas.geometry import scale_vector
from compas.geometry import subtract_vectors
from compas.geometry import bounding_box
from compas.geometry import transform_points
from compas.geometry import oriented_bounding_box
from compas.itertools import linspace
from compas.itertools import pairwise
from compas.tolerance import TOL
def iter_edges_from_vertices(vertices):
for i, u in enumerate(vertices):
j = (i + 1) % len(vertices)
yield u, vertices[j]
class VolMesh(Datastructure):
"""Geometric implementation of a face data structure for volumetric meshes.
Parameters
----------
default_vertex_attributes : dict, optional
Default values for vertex attributes.
default_edge_attributes : dict, optional
Default values for edge attributes.
default_face_attributes : dict, optional
Default values for face attributes.
default_cell_attributes : dict, optional
Default values for cell attributes.
name : str, optional
The name of the volmesh.
**kwargs : dict, optional
Additional keyword arguments, which are stored in the attributes dict.
Attributes
----------
default_vertex_attributes : dict[str, Any]
Default attributes of the vertices.
default_edge_attributes : dict[str, Any]
Default values for edge attributes.
default_face_attributes : dict[str, Any]
Default values for face attributes.
default_cell_attributes : dict[str, Any]
Default values for cell attributes.
"""
DATASCHEMA = {
"type": "object",
"properties": {
"attributes": {"type": "object"},
"default_vertex_attributes": {"type": "object"},
"default_edge_attributes": {"type": "object"},
"default_face_attributes": {"type": "object"},
"default_cell_attributes": {"type": "object"},
"vertex": {
"type": "object",
"patternProperties": {"^[0-9]+$": {"type": "object"}},
"additionalProperties": False,
},
"cell": {
"type": "object",
"patternProperties": {
"^[0-9]+$": {
"type": "array",
"minItems": 4,
"items": {
"type": "array",
"minItems": 3,
"items": {"type": "integer", "minimum": 0},
},
}
},
"additionalProperties": False,
},
"edge_data": {
"type": "object",
"patternProperties": {"^\\([0-9]+, [0-9]+\\)$": {"type": "object"}},
"additionalProperties": False,
},
"face_data": {
"type": "object",
"patternProperties": {"^\\([0-9]+(, [0-9]+){3, }\\)$": {"type": "object"}},
"additionalProperties": False,
},
"cell_data": {
"type": "object",
"patternProperties": {"^[0-9]+$": {"type": "object"}},
"additionalProperties": False,
},
"max_vertex": {"type": "number", "minimum": -1},
"max_face": {"type": "number", "minimum": -1},
"max_cell": {"type": "number", "minimum": -1},
},
"required": [
"attributes",
"default_vertex_attributes",
"default_edge_attributes",
"default_face_attributes",
"vertex",
"cell",
"edge_data",
"face_data",
"cell_data",
"max_vertex",
"max_face",
"max_cell",
],
}
@property
def __data__(self):
_cell = {}
for c in self._cell:
faces = []
for u in sorted(self._cell[c]):
for v in sorted(self._cell[c][u]):
faces.append(self._halfface[self._cell[c][u][v]])
_cell[c] = faces
return {
"attributes": self.attributes,
"default_vertex_attributes": self.default_vertex_attributes,
"default_edge_attributes": self.default_edge_attributes,
"default_face_attributes": self.default_face_attributes,
"default_cell_attributes": self.default_cell_attributes,
"vertex": {str(vertex): attr for vertex, attr in self._vertex.items()},
"cell": {str(cell): faces for cell, faces in _cell.items()},
"edge_data": self._edge_data,
"face_data": self._face_data,
"cell_data": {str(cell): attr for cell, attr in self._cell_data},
"max_vertex": self._max_vertex,
"max_face": self._max_face,
"max_cell": self._max_cell,
}
@classmethod
def __from_data__(cls, data):
volmesh = cls(
default_vertex_attributes=data.get("default_vertex_attributes"),
default_edge_attributes=data.get("default_edge_attributes"),
default_face_attributes=data.get("default_face_attributes"),
default_cell_attributes=data.get("default_cell_attributes"),
)
volmesh.attributes.update(data["attributes"] or {})
vertex = data["vertex"] or {}
cell = data["cell"] or {}
edge_data = data.get("edge_data") or {}
face_data = data.get("face_data") or {}
cell_data = data.get("cell_data") or {}
for key, attr in iter(vertex.items()):
volmesh.add_vertex(key=key, attr_dict=attr)
for ckey, faces in iter(cell.items()):
volmesh.add_cell(faces, ckey=ckey, attr_dict=cell_data.get(ckey))
for edge in edge_data:
volmesh._edge_data[edge] = edge_data[edge] or {}
for face in face_data:
volmesh._face_data[face] = face_data[face] or {}
volmesh._max_vertex = data.get("max_vertex", volmesh._max_vertex)
volmesh._max_face = data.get("max_face", volmesh._max_face)
volmesh._max_cell = data.get("max_cell", volmesh._max_cell)
return volmesh
def __init__(self, default_vertex_attributes=None, default_edge_attributes=None, default_face_attributes=None, default_cell_attributes=None, name=None, **kwargs): # fmt: skip
super(VolMesh, self).__init__(kwargs, name=name)
self._max_vertex = -1
self._max_face = -1
self._max_cell = -1
self._vertex = {}
self._halfface = {}
self._cell = {}
self._plane = {}
self._edge_data = {}
self._face_data = {}
self._cell_data = {}
self.default_vertex_attributes = {"x": 0.0, "y": 0.0, "z": 0.0}
self.default_edge_attributes = {}
self.default_face_attributes = {}
self.default_cell_attributes = {}
if default_vertex_attributes:
self.default_vertex_attributes.update(default_vertex_attributes)
if default_edge_attributes:
self.default_edge_attributes.update(default_edge_attributes)
if default_face_attributes:
self.default_face_attributes.update(default_face_attributes)
if default_cell_attributes:
self.default_cell_attributes.update(default_cell_attributes)
def __str__(self):
tpl = "<VolMesh with {} vertices, {} faces, {} cells, {} edges>"
return tpl.format(
self.number_of_vertices(),
self.number_of_faces(),
self.number_of_cells(),
self.number_of_edges(),
)
# --------------------------------------------------------------------------
# Customisation
# --------------------------------------------------------------------------
# --------------------------------------------------------------------------
# Special properties
# --------------------------------------------------------------------------
# --------------------------------------------------------------------------
# Constructors
# --------------------------------------------------------------------------
@classmethod
def from_meshgrid(cls, dx=10, dy=None, dz=None, nx=10, ny=None, nz=None):
"""Construct a volmesh from a 3D meshgrid.
Parameters
----------
dx : float, optional
The size of the grid in the x direction.
dy : float, optional
The size of the grid in the y direction.
Defaults to the value of `dx`.
dz : float, optional
The size of the grid in the z direction.
Defaults to the value of `dx`.
nx : int, optional
The number of elements in the x direction.
ny : int, optional
The number of elements in the y direction.
Defaults to the value of `nx`.
nz : int, optional
The number of elements in the z direction.
Defaults to the value of `nx`.
Returns
-------
:class:`compas.datastructures.VolMesh`
See Also
--------
:meth:`from_obj`, :meth:`from_vertices_and_cells`
"""
dy = dy or dx
dz = dz or dx
ny = ny or nx
nz = nz or nx
vertices = [
[x, y, z]
for z, x, y in product(
linspace(0, dz, nz + 1),
linspace(0, dx, nx + 1),
linspace(0, dy, ny + 1),
)
]
cells = []
for k, i, j in product(range(nz), range(nx), range(ny)):
a = k * ((nx + 1) * (ny + 1)) + i * (ny + 1) + j
b = k * ((nx + 1) * (ny + 1)) + (i + 1) * (ny + 1) + j
c = k * ((nx + 1) * (ny + 1)) + (i + 1) * (ny + 1) + j + 1
d = k * ((nx + 1) * (ny + 1)) + i * (ny + 1) + j + 1
aa = (k + 1) * ((nx + 1) * (ny + 1)) + i * (ny + 1) + j
bb = (k + 1) * ((nx + 1) * (ny + 1)) + (i + 1) * (ny + 1) + j
cc = (k + 1) * ((nx + 1) * (ny + 1)) + (i + 1) * (ny + 1) + j + 1
dd = (k + 1) * ((nx + 1) * (ny + 1)) + i * (ny + 1) + j + 1
bottom = [d, c, b, a]
front = [a, b, bb, aa]
right = [b, c, cc, bb]
left = [a, aa, dd, d]
back = [c, d, dd, cc]
top = [aa, bb, cc, dd]
cells.append([bottom, front, left, back, right, top])
return cls.from_vertices_and_cells(vertices, cells)
@classmethod
def from_obj(cls, filepath, precision=None):
"""Construct a volmesh object from the data described in an OBJ file.
Parameters
----------
filepath : path string | file-like object | URL string
A path, a file-like object or a URL pointing to a file.
precision: str, optional
The precision of the geometric map that is used to connect the lines.
Returns
-------
:class:`compas.datastructures.VolMesh`
A volmesh object.
See Also
--------
:meth:`to_obj`
:meth:`from_meshgrid`, :meth:`from_vertices_and_cells`
:class:`compas.files.OBJ`
"""
obj = OBJ(filepath, precision)
vertices = obj.parser.vertices or [] # type: ignore
faces = obj.parser.faces or [] # type: ignore
groups = obj.parser.groups or [] # type: ignore
cells = []
for name in groups:
group = groups[name]
cell = []
for item in group:
if item[0] != "f":
continue
face = faces[item[1]]
cell.append(face)
cells.append(cell)
return cls.from_vertices_and_cells(vertices, cells)
@classmethod
def from_vertices_and_cells(cls, vertices, cells):
"""Construct a volmesh object from vertices and cells.
Parameters
----------
vertices : list[list[float]]
Ordered list of vertices, represented by their XYZ coordinates.
cells : list[list[list[int]]]
List of cells defined by their faces.
Returns
-------
:class:`compas.datastructures.VolMesh`
A volmesh object.
See Also
--------
:meth:`to_vertices_and_cells`
:meth:`from_obj`, :meth:`from_meshgrid`
"""
volmesh = cls()
for x, y, z in vertices:
volmesh.add_vertex(x=x, y=y, z=z)
for cell in cells:
volmesh.add_cell(cell)
return volmesh
# --------------------------------------------------------------------------
# Conversions
# --------------------------------------------------------------------------
def to_obj(self, filepath, precision=None, **kwargs):
"""Write the volmesh to an OBJ file.
Parameters
----------
filepath : path string | file-like object
A path or a file-like object pointing to a file.
precision: str, optional
The precision of the geometric map that is used to connect the lines.
unweld : bool, optional
If True, all faces have their own unique vertices.
If False, vertices are shared between faces if this is also the case in the mesh.
Default is False.
Returns
-------
None
See Also
--------
:meth:`from_obj`
Warnings
--------
This function only writes geometric data about the vertices and
the faces to the file.
"""
obj = OBJ(filepath, precision=precision)
obj.write(self, **kwargs)
def to_vertices_and_cells(self):
"""Return the vertices and cells of a volmesh.
Returns
-------
list[list[float]]
A list of vertices, represented by their XYZ coordinates.
list[list[list[int]]]
A list of cells, with each cell a list of faces, and each face a list of vertex indices.
See Also
--------
:meth:`from_vertices_and_cells`
"""
vertex_index = self.vertex_index()
vertices = [self.vertex_coordinates(vertex) for vertex in self.vertices()]
cells = []
for cell in self.cells():
faces = [
[vertex_index[vertex] for vertex in self.halfface_vertices(face)] for face in self.cell_faces(cell)
]
cells.append(faces)
return vertices, cells
def cell_to_mesh(self, cell):
"""Construct a mesh object from from a cell of a volmesh.
Parameters
----------
cell : int
Identifier of the cell.
Returns
-------
:class:`compas.datastructures.Mesh`
A mesh object.
See Also
--------
:meth:`cell_to_vertices_and_faces`
"""
vertices, faces = self.cell_to_vertices_and_faces(cell)
return Mesh.from_vertices_and_faces(vertices, faces)
def cell_to_vertices_and_faces(self, cell):
"""Return the vertices and faces of a cell.
Parameters
----------
cell : int
Identifier of the cell.
Returns
-------
list[list[float]]
A list of vertices, represented by their XYZ coordinates,
list[list[int]]
A list of faces, with each face a list of vertex indices.
See Also
--------
:meth:`cell_to_mesh`
"""
vertices = self.cell_vertices(cell)
faces = self.cell_faces(cell)
vertex_index = dict((vertex, index) for index, vertex in enumerate(vertices))
vertices = [self.vertex_coordinates(vertex) for vertex in vertices]
faces = [[vertex_index[vertex] for vertex in self.halfface_vertices(face)] for face in faces]
return vertices, faces
# --------------------------------------------------------------------------
# Helpers
# --------------------------------------------------------------------------
def clear(self):
"""Clear all the volmesh data.
Returns
-------
None
"""
del self._vertex
del self._halfface
del self._cell
del self._plane
del self._edge_data
del self._face_data
del self._cell_data
self._vertex = {}
self._halfface = {}
self._cell = {}
self._plane = {}
self._edge_data = {}
self._face_data = {}
self._cell_data = {}
self._max_vertex = -1
self._max_face = -1
self._max_cell = -1
def vertex_sample(self, size=1):
"""Get the identifiers of a set of random vertices.
Parameters
----------
size : int, optional
The size of the sample.
Returns
-------
list[int]
The identifiers of the vertices.
See Also
--------
:meth:`edge_sample`, :meth:`face_sample`, :meth:`cell_sample`
"""
return sample(list(self.vertices()), size)
def edge_sample(self, size=1):
"""Get the identifiers of a set of random edges.
Parameters
----------
size : int, optional
The size of the sample.
Returns
-------
list[tuple[int, int]]
The identifiers of the edges.
See Also
--------
:meth:`vertex_sample`, :meth:`face_sample`, :meth:`cell_sample`
"""
return sample(list(self.edges()), size)
def face_sample(self, size=1):
"""Get the identifiers of a set of random faces.
Parameters
----------
size : int, optional
The size of the sample.
Returns
-------
list[int]
The identifiers of the faces.
See Also
--------
:meth:`vertex_sample`, :meth:`edge_sample`, :meth:`cell_sample`
"""
return sample(list(self.faces()), size)
def cell_sample(self, size=1):
"""Get the identifiers of a set of random cells.
Parameters
----------
size : int, optional
The size of the sample.
Returns
-------
list[int]
The identifiers of the cells.
See Also
--------
:meth:`vertex_sample`, :meth:`edge_sample`, :meth:`face_sample`
"""
return sample(list(self.cells()), size)
def vertex_index(self):
"""Returns a dictionary that maps vertex dictionary keys to the
corresponding index in a vertex list or array.
Returns
-------
dict[int, int]
A dictionary of vertex-index pairs.
See Also
--------
:meth:`index_vertex`
"""
return {key: index for index, key in enumerate(self.vertices())}
def index_vertex(self):
"""Returns a dictionary that maps the indices of a vertex list to
keys in the vertex dictionary.
Returns
-------
dict[int, int]
A dictionary of index-vertex pairs.
See Also
--------
:meth:`vertex_index`
"""
return dict(enumerate(self.vertices()))
def vertex_gkey(self, precision=None):
"""Returns a dictionary that maps vertex dictionary keys to the corresponding
*geometric key* up to a certain precision.
Parameters
----------
precision : int, optional
Precision for converting numbers to strings.
Default is :attr:`TOL.precision`.
Returns
-------
dict[int, str]
A dictionary of vertex-geometric key pairs.
See Also
--------
:meth:`gkey_vertex`
"""
gkey = TOL.geometric_key
xyz = self.vertex_coordinates
return {vertex: gkey(xyz(vertex), precision) for vertex in self.vertices()}
def gkey_vertex(self, precision=None):
"""Returns a dictionary that maps *geometric keys* of a certain precision
to the keys of the corresponding vertices.
Parameters
----------
precision : int, optional
Precision for converting numbers to strings.
Default is :attr:`TOL.precision`.
Returns
-------
dict[str, int]
A dictionary of geometric key-vertex pairs.
See Also
--------
:meth:`vertex_gkey`
"""
gkey = TOL.geometric_key
xyz = self.vertex_coordinates
return {gkey(xyz(vertex), precision): vertex for vertex in self.vertices()}
# --------------------------------------------------------------------------
# Builders & Modifiers
# --------------------------------------------------------------------------
def add_vertex(self, key=None, attr_dict=None, **kwattr):
"""Add a vertex to the volmesh object.
Parameters
----------
key : int, optional
The vertex identifier.
attr_dict : dict[str, Any], optional
dictionary of vertex attributes.
**kwattr : dict[str, Any], optional
A dictionary of additional attributes compiled of remaining named arguments.
Returns
-------
int
The identifier of the vertex.
See Also
--------
:meth:`add_halfface`, :meth:`add_cell`
Notes
-----
If no key is provided for the vertex, one is generated
automatically. An automatically generated key is an integer that increments
the highest integer value of any key used so far by 1.
If a key with an integer value is provided that is higher than the current
highest integer key value, then the highest integer value is updated accordingly.
"""
if key is None:
key = self._max_vertex = self._max_vertex + 1
key = int(key)
if key > self._max_vertex:
self._max_vertex = key
if key not in self._vertex:
self._vertex[key] = {}
self._plane[key] = {}
attr = attr_dict or {}
attr.update(kwattr)
self._vertex[key].update(attr)
return key
def add_halfface(self, vertices, fkey=None, attr_dict=None, **kwattr):
"""Add a face to the volmesh object.
Parameters
----------
vertices : list[int]
A list of ordered vertex keys representing the face.
For every vertex that does not yet exist, a new vertex is created.
fkey : int, optional
The face identifier.
attr_dict : dict[str, Any], optional
dictionary of halfface attributes.
**kwattr : dict[str, Any], optional
A dictionary of additional attributes compiled of remaining named arguments.
Returns
-------
int
The key of the face.
See Also
--------
:meth:`add_vertex`, :meth:`add_cell`
Notes
-----
If no key is provided for the face, one is generated
automatically. An automatically generated key is an integer that increments
the highest integer value of any key used so far by 1.
If a key with an integer value is provided that is higher than the current
highest integer key value, then the highest integer value is updated accordingly.
"""
if len(vertices) < 3:
return
if vertices[-1] == vertices[0]:
vertices = vertices[:-1]
vertices = [int(key) for key in vertices]
if fkey is None:
fkey = self._max_face = self._max_face + 1
fkey = int(fkey)
if fkey > self._max_face:
self._max_face = fkey
attr = attr_dict or {}
attr.update(kwattr)
self._halfface[fkey] = vertices
for name, value in attr.items():
self.face_attribute(fkey, name, value)
for u, v in iter_edges_from_vertices(vertices):
if v not in self._plane[u]:
self._plane[u][v] = {}
self._plane[u][v][fkey] = None
if u not in self._plane[v]:
self._plane[v][u] = {}
self._plane[v][u][fkey] = None
return fkey
def add_cell(self, faces, ckey=None, attr_dict=None, **kwattr):
"""Add a cell to the volmesh object.
Parameters
----------
faces : list[list[int]]
The faces of the cell defined as lists of vertices.
ckey : int, optional
The cell identifier.
attr_dict : dict[str, Any], optional
A dictionary of cell attributes.
**kwattr : dict[str, Any], optional
A dictionary of additional attributes compiled of remaining named arguments.
Returns
-------
int
The key of the cell.
Raises
------
TypeError
If the provided cell key is of an unhashable type.
See also
--------
:meth:`add_vertex`, :meth:`add_halfface`
Notes
-----
If no key is provided for the cell, one is generated
automatically. An automatically generated key is an integer that increments
the highest integer value of any key used so far by 1.
If a key with an integer value is provided that is higher than the current
highest integer key value, then the highest integer value is updated accordingly.
"""
if ckey is None:
ckey = self._max_cell = self._max_cell + 1
ckey = int(ckey)
if ckey > self._max_cell:
self._max_cell = ckey
attr = attr_dict or {}
attr.update(kwattr)
self._cell[ckey] = {}
for name, value in attr.items():
self.cell_attribute(ckey, name, value)
for vertices in faces:
fkey = self.add_halfface(vertices)
vertices = self.halfface_vertices(fkey)
for u, v in iter_edges_from_vertices(vertices):
if u not in self._cell[ckey]:
self._cell[ckey][u] = {}
self._plane[u][v][fkey] = ckey
self._cell[ckey][u][v] = fkey
return ckey
def delete_vertex(self, vertex):
"""Delete a vertex from the volmesh and everything that is attached to it.
Parameters
----------
vertex : int
The identifier of the vertex.
Returns
-------
None
See Also
--------
:meth:`delete_halfface`, :meth:`delete_cell`
"""
for cell in self.vertex_cells(vertex):
self.delete_cell(cell)
def delete_cell(self, cell):
"""Delete a cell from the volmesh.
Parameters
----------
cell : int
The identifier of the cell.
Returns
-------
None
See Also
--------
:meth:`delete_vertex`, :meth:`delete_halfface`
"""
cell_vertices = self.cell_vertices(cell)
cell_faces = self.cell_faces(cell)
for face in cell_faces:
for edge in self.halfface_halfedges(face):
u, v = edge
if (u, v) in self._edge_data:
del self._edge_data[u, v]
if (v, u) in self._edge_data:
del self._edge_data[v, u]
for vertex in cell_vertices:
if len(self.vertex_cells(vertex)) == 1:
del self._vertex[vertex]
for face in cell_faces:
vertices = self.halfface_vertices(face)
for u, v in iter_edges_from_vertices(vertices):
self._plane[u][v][face] = None
if self._plane[v][u][face] is None:
del self._plane[u][v][face]
del self._plane[v][u][face]
del self._halfface[face]
key = "-".join(map(str, sorted(vertices)))
if key in self._face_data:
del self._face_data[key]
del self._cell[cell]
if cell in self._cell_data:
del self._cell_data[cell]
def remove_unused_vertices(self):
"""Remove all unused vertices from the volmesh object.
Returns
-------
None
"""
for vertex in list(self.vertices()):
if vertex not in self._plane:
del self._vertex[vertex]
else:
if not self._plane[vertex]:
del self._vertex[vertex]
del self._plane[vertex]
# --------------------------------------------------------------------------
# Volmesh Geometry
# --------------------------------------------------------------------------
def centroid(self):
"""Compute the centroid of the volmesh.
Returns
-------
:class:`compas.geometry.Point`
The point at the centroid.
"""
return Point(*centroid_points([self.vertex_coordinates(vertex) for vertex in self.vertices()]))
def aabb(self):
"""Calculate the axis aligned bounding box of the mesh.
Returns
-------
:class:`compas.geometry.Box`
"""
xyz = self.vertices_attributes("xyz")
return Box.from_bounding_box(bounding_box(xyz))
def obb(self):
"""Calculate the oriented bounding box of the datastructure.
Returns
-------
:class:`compas.geometry.Box`
"""
xyz = self.vertices_attributes("xyz")
return Box.from_bounding_box(oriented_bounding_box(xyz))
# --------------------------------------------------------------------------
# VolMesh Topology
# --------------------------------------------------------------------------
def number_of_vertices(self):
"""Count the number of vertices in the volmesh.
Returns
-------
int
The number of vertices.
See Also
--------
:meth:`number_of_edges`, :meth:`number_of_faces`, :meth:`number_of_cells`
"""
return len(list(self.vertices()))
def number_of_edges(self):
"""Count the number of edges in the volmesh.
Returns
-------
int
The number of edges.
See Also
--------
:meth:`number_of_vertices`, :meth:`number_of_faces`, :meth:`number_of_cells`
"""
return len(list(self.edges()))
def number_of_faces(self):
"""Count the number of faces in the volmesh.