-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy path__init__.py
More file actions
2696 lines (2150 loc) · 87.1 KB
/
__init__.py
File metadata and controls
2696 lines (2150 loc) · 87.1 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
from __future__ import annotations
import re
from copy import deepcopy
import sys
import time
import math
import operator
from random import randint
from .tools import num
from .importer import *
from typing import List, Tuple, Generator
import warnings
class Convert:
"""
Converts strings to usable instances
"""
@staticmethod
def string_to_vertex(string: str) -> Vertex:
reg = re.sub(r'[(){}<>\[\],]', '', string).split()
return Vertex(num(reg[0]), num(reg[1]), num(reg[2]))
@staticmethod
def string_to_3x_vertex(string: str) -> List[Vertex, Vertex, Vertex]:
reg = re.sub(r'[(){}<>]', '', string).split()
clean = []
for i in reg:
clean.append(num(i))
return [Vertex(clean[0], clean[1], clean[2]),
Vertex(clean[3], clean[4], clean[5]),
Vertex(clean[6], clean[7], clean[8])]
@staticmethod
def string_to_color(string: str) -> Color:
temp = string.split()
return Color(int(temp[0]), int(temp[1]), int(temp[2]))
@staticmethod
def string_to_color_light(string: str) -> ColorLight:
temp = string.split()
return ColorLight(int(temp[0]), int(temp[1]), int(temp[2]), int(temp[3]))
@staticmethod
def string_to_uvaxis(string: str) -> UVaxis:
reg = re.sub(r'[\[\]]', '', string).split()
return UVaxis(*reg)
class Common:
"""
The parent class to all VMF classes that need to be exported to the .VMF file.
"""
ID = 0
def export(self):
"""
Gets all the variables than need to be exported into the .VMF file
:return: All predefined (in `export_list`) variable names and their associated values
:rtype: :obj:`dict`, :obj:`dict`
"""
d = {}
for item in self.export_list:
t = getattr(self, item)
d[item] = t
return d, self.other
def export_children(self):
"""
Gets all the children classes
:return: All predefined children classes
:rtype: :obj:`list` of :class:`Common` instances
"""
return []
def copy(self):
"""
Copies the class using :func:`~copy.deepcopy`
:return: A deepcopy of itself
:rtype: :class:`Common` instance
"""
return deepcopy(self)
def ids(self):
Common.ID += 1
return Common.ID
def _dic_and_children(self, dic, children):
if dic is None:
dic = {}
if children is None:
children = []
return dic, children
def _dic(self, dic):
if dic is None:
dic = {}
return dic
class Color:
"""
Simple RGB color class
:param r: Value for RED between 0 and 255
:type r: :obj:`int`
:param g: Value for GREEN between 0 and 255
:type g: :obj:`int`
:param b: Value for BLUE between 0 and 255
:type b: :obj:`int`
"""
def __init__(self, r: int = 255, g: int = 255, b: int = 255):
self.r = 0
self.g = 0
self.b = 0
self.set(r, g, b)
def __str__(self):
return f"{self.r} {self.g} {self.b}"
def set(self, r: int = -1, g: int = -1, b: int = -1):
"""
Sets the color
:param r: Value for RED between 0 and 255, if equals to -1 keeps previous value
:type r: :obj:`int`
:param g: Value for GREEN between 0 and 255, if equals to -1 keeps previous value
:type g: :obj:`int`
:param b: Value for BLUE between 0 and 255, if equals to -1 keeps previous value
:type b: :obj:`int`
"""
if r != -1 and 0 <= r < 256:
self.r = r
if g != -1 and 0 <= g < 256:
self.g = g
if b != -1 and 0 <= b < 256:
self.b = b
def random(self):
"""
Sets a random color
"""
self.set(randint(0, 255), randint(0, 255), randint(0, 255))
def export(self) -> Tuple[int, int, int]:
return self.r, self.g, self.b
class ColorLight(Color):
"""
Simple RGB color class with brightness (used for lights)
:param r: Value for RED between 0 and 255
:type r: :obj:`int`
:param g: Value for GREEN between 0 and 255
:type g: :obj:`int`
:param b: Value for BLUE between 0 and 255
:type b: :obj:`int`
:param brightness: Value for brightness, above 0
:type brightness: :obj:`int`
"""
def __init__(self, r: int = 255, g: int = 255, b: int = 255, brightness: int = 200):
super(ColorLight, self).__init__(r, g, b)
self.brightness = brightness
def __str__(self):
return f"{self.r} {self.g} {self.b} {self.brightness}"
def set_brightness(self, brightness: int):
"""
:param brightness: New brightness value
:type brightness: :obj:`int`
"""
self.brightness = brightness
def export(self) -> Tuple[int, int, int, int]:
return self.r, self.g, self.b, self.brightness
class VersionInfo(Common):
NAME = "versioninfo"
def __init__(self, dic: dict = None):
dic = self._dic(dic)
self.editorversion = dic.pop("editorversion", 400)
self.editorbuild = dic.pop("editorbuild", 8075)
self.mapversion = dic.pop("mapversion", 7)
self.formatversion = dic.pop("formatversion", 100)
self.prefab = dic.pop("prefab", 0)
self.other = dic
self.export_list = ["editorversion", "editorbuild", "mapversion", "formatversion", "prefab"]
class VisGroups(Common):
NAME = "visgroups"
def __init__(self, dic: dict = None, children: list = None):
dic, children = self._dic_and_children(dic, children)
self.other = dic
self.export_list = []
self.visgroup = []
for child in children:
self.visgroup.append(VisGroup(child.dic, child.children))
def new_visgroup(self, name: str) -> VisGroup:
v = VisGroup({"name": name})
self.visgroup.append(v)
return v
def get_visgroups(self) -> List[VisGroup]:
return self.visgroup
def export_children(self) -> Tuple[VisGroup, ...]:
return (*self.visgroup,)
class VisGroup(Common):
NAME = "visgroup"
def __init__(self, dic: dict = None, children: list = None):
dic, children = self._dic_and_children(dic, children)
self.name = dic.pop("name", "default")
self.visgroupid = dic.pop("visgroupid", self.ids())
self.color = dic.pop("color", "0 0 0")
self.other = dic
self.export_list = ["name", "visgroupid", "color"]
self.visgroup = []
for child in children:
if str(child) == VisGroup.NAME:
self.visgroup.append(VisGroup(child.dic, child.children))
def export_children(self):
return (*self.visgroup,)
class ViewSettings(Common):
NAME = "viewsettings"
def __init__(self, dic: dict = None):
dic = self._dic(dic)
self.bSnapToGrid = dic.pop("bSnapToGrid", 1)
self.bShowGrid = dic.pop("bShowGrid", 1)
self.bShowLogicalGrid = dic.pop("bShowLogicalGrid", 0)
self.nGridSpacing = dic.pop("nGridSpacing", 64)
self.bShow3DGrid = dic.pop("bShow3DGrid", 0)
self.other = dic
self.export_list = ["bSnapToGrid", "bShowGrid", "bShowLogicalGrid", "nGridSpacing", "bShow3DGrid"]
class World(Common):
NAME = "world"
def __init__(self, dic: dict = None, children: list = None):
dic, children = self._dic_and_children(dic, children)
self.id = dic.pop("id", self.ids())
self.mapversion = dic.pop("mapversion", 1)
self.classname = dic.pop("classname", "worldspawn")
self.detailmaterial = dic.pop("detailmaterial", "detail/detailsprites")
self.detailvbsp = dic.pop("detailvbsp", "detail.vsbp")
self.maxpropscreenwidth = dic.pop("maxpropscreenwidth", -1)
self.skyname = dic.pop("skyname", "sky_dust")
self.other = dic
self.export_list = ["id", "mapversion", "classname", "detailmaterial", "detailvbsp", "maxpropscreenwidth",
"skyname"]
self.solids = []
self.hidden = []
self.group = []
for child in children:
if str(child) == Solid.NAME:
self.solids.append(Solid(child.dic, child.children))
elif str(child) == Hidden.NAME:
self.hidden.append(Hidden(child.dic, child.children))
elif str(child) == Group.NAME:
self.group.append(Group(child.dic, child.children))
def export_children(self):
return (*self.solids, *self.hidden, *self.group)
class Vertex(Common): # Vertex has to be above the Solid class (see: set_pos_vertex function)
"""
Corresponds to a single position on the Hammer grid
:param x: x position
:type x: :obj:`int` or :obj:`float`
:param y: y position
:type y: :obj:`int` or :obj:`float`
:param z: z position
:type z: :obj:`int` or :obj:`float`
"""
def __init__(self, x=0, y=0, z=0):
self.x = x
self.y = y
self.z = z
self.sorting = 0 # Used in solid get_3d_extremity
self.normal = 0 # Vertices are represented differently in the VMF depending on the class
def __str__(self):
if not self.normal:
return f"{self.x} {self.y} {self.z}"
elif self.normal == 1:
return f"[{self.x} {self.y} {self.z}]"
elif self.normal == 2:
return f"({self.x} {self.y} {self.z})"
def __eq__(self, other):
return self.x == other.x and self.y == other.y and self.z == other.z
def __add__(self, other):
return Vertex(self.x + other.x, self.y + other.y, self.z + other.z)
def __sub__(self, other):
return Vertex(self.x - other.x, self.y - other.y, self.z - other.z)
def similar(self, other, accuracy=0.001) -> bool:
"""
Compares the current vertex with the given one to see if they are similar
:param other:
:type other: :class:`Vertex`
:param accuracy: Distance from the current vertex to be considered similar (in Hammer units)
:type accuracy: :obj:`float`
:return: If the given vertex is within the proximity of the current vertex
:rtype: :obj:`bool`
"""
return ((abs(self.x - other.x) < accuracy) and
(abs(self.y - other.y) < accuracy) and
(abs(self.z - other.z) < accuracy))
def multiply(self, amount):
"""
Multiplies all the axes uniformly by the given amount
:param amount: How much to multiply each axis by
:type amount: :obj:`int` or :obj:`float`
"""
self.x *= amount
self.y *= amount
self.z *= amount
def divide(self, amount):
"""
Divides all the axes uniformly by the given amount (for separate division see :func:`~Vertex.divide_separate`)
:param amount: How much to divide each axis by
:type amount: :obj:`int` or :obj:`float`
"""
self.x /= amount
self.y /= amount
self.z /= amount
def divide_separate(self, x, y, z):
"""
Divides all the axes separatedly by the given amounts (for uniform division see :func:`~Vertex.divide`)
:param x: Amount to divide x axis by
:type x: :obj:`int` or :obj:`float`
:param y: Amount to divide y axis by
:type y: :obj:`int` or :obj:`float`
:param z: Amount to divide z axis by
:type z: :obj:`int` or :obj:`float`
"""
self.x /= x
self.y /= y
self.z /= z
def diff(self, other) -> Vertex:
"""
:param other: The vertex to differentiate with
:return: The difference in distance between 2 vertices
:rtype: :class:`Vertex`
"""
return self - other
def move(self, x, y, z):
"""
Moves the vertex by the given amount
:param x: Amount to move the x axis by
:type x: :obj:`int` or :obj:`float`
:param y: Amount to move the y axis by
:type y: :obj:`int` or :obj:`float`
:param z: Amount to move the z axis by
:type z: :obj:`int` or :obj:`float`
"""
self.x += x
self.y += y
self.z += z
def set(self, x, y, z):
"""
Sets the vertex position to the given position
:param x: New x position
:type x: :obj:`int` or :obj:`float`
:param y: New y position
:type y: :obj:`int` or :obj:`float`
:param z: New z position
:type z: :obj:`int` or :obj:`float`
"""
self.x = x
self.y = y
self.z = z
def rotate_z(self, center: Vertex, angle):
"""
Rotates the vertex around the z axis
:param center: The point to rotate around
:type center: :class:`Vertex`
:param angle: How much to rotate in degrees
:type angle: :obj:`int` or :obj:`float`
"""
a = math.radians(angle)
new_x = center.x + (self.x - center.x) * math.cos(a) - (self.y - center.y) * math.sin(a)
new_y = center.y + (self.x - center.x) * math.sin(a) + (self.y - center.y) * math.cos(a)
self.set(new_x, new_y, self.z)
def rotate_y(self, center: Vertex, angle):
"""
Rotates the vertex around the y axis
:param center: The point to rotate around
:type center: :class:`Vertex`
:param angle: How much to rotate in degrees
:type angle: :obj:`int` or :obj:`float`
"""
a = math.radians(angle)
new_x = center.x + (self.x - center.x) * math.cos(a) - (self.z - center.z) * math.sin(a)
new_z = center.z + (self.x - center.x) * math.sin(a) + (self.z - center.z) * math.cos(a)
self.set(new_x, self.y, new_z)
def rotate_x(self, center: Vertex, angle):
"""
Rotates the vertex around the x axis
:param center: The point to rotate around
:type center: :class:`Vertex`
:param angle: How much to rotate in degrees
:type angle: :obj:`int` or :obj:`float`
"""
a = math.radians(angle)
new_y = center.y + (self.y - center.y) * math.cos(a) - (self.z - center.z) * math.sin(a)
new_z = center.z + (self.y - center.y) * math.sin(a) + (self.z - center.z) * math.cos(a)
self.set(self.x, new_y, new_z)
def flip(self, x=None, y=None, z=None):
if x is not None:
self.x += 2 * (x - self.x)
if y is not None:
self.y += 2 * (y - self.y)
if z is not None:
self.z += 2 * (z - self.z)
def align_to_grid(self):
"""
Turns x, y and z into integers
"""
self.x = round(self.x)
self.y = round(self.y)
self.z = round(self.z)
def export(self) -> Tuple[int, int, int]:
return (self.x,
self.y,
self.z)
class Solid(Common):
"""
Corresponds to an individual solid just like in Hammer
:param dic: All the values to be initialized, if empty default values are used.
:type dic: :obj:`dict`
:param children: The :class:`Side`\'s and :class:`Editor` to be initialized
:type children: :obj:`list`
"""
NAME = "solid"
def __init__(self, dic: dict = None, children: list = None):
dic, children = self._dic_and_children(dic, children)
self.id = dic.pop("id", self.ids())
self.other = dic
self.export_list = ["id"]
self.side = []
self.editor = None
for child in children:
if str(child) == Side.NAME:
self.side.append(Side(child.dic, child.children))
elif str(child) == Editor.NAME:
self.editor = Editor(child.dic)
def add_sides(self, *args: Side):
"""
Adds sides to the solid, note that no checks are made for validity
:param args: List of sides to be added
:type args: :obj:`list` of :class:`Side`
"""
self.side.extend(args)
def move(self, x, y, z):
"""
Moves all sides of the solid by the given amount in Hammer units
:param x:
:type x: :obj:`int` or :obj:`float`
:param y:
:type y: :obj:`int` or :obj:`float`
:param z:
:type z: :obj:`int` or :obj:`float`
"""
for side in self.side:
for vert in side.plane:
vert.move(x, y, z)
def get_linked_vertices(self, vertex: Vertex, similar=0.0) -> List[Vertex, ...]:
"""
:param vertex: The vertex to check against
:type vertex: :class:`Vertex`
:param similar: Distance between vertices to be considered similar (in Hammer units)
:type similar: :obj:`float`
:return: All vertices that are in close proximity to the given vertex itself included
:rtype: :obj:`list` of :class:`Vertex`
"""
li = []
for vert in self.get_all_vertices():
if similar == 0.0:
if vertex == vert:
li.append(vert)
else:
if vertex.similar(vert, similar):
li.append(vert)
return li
def rotate_x(self, center: Vertex, angle):
"""
Rotates the solid around the x axis
:param center: The point to rotate around
:type center: :class:`Vertex`
:param angle: How much to rotate in degrees
:type angle: :obj:`int` or :obj:`float`
"""
for side in self.side:
side.rotate_x(center, angle)
def rotate_y(self, center: Vertex, angle):
"""
Rotates the solid around the y axis
:param center: The point to rotate around
:type center: :class:`Vertex`
:param angle: How much to rotate in degrees
:type angle: :obj:`int` or :obj:`float`
"""
for side in self.side:
side.rotate_y(center, angle)
def rotate_z(self, center: Vertex, angle):
"""
Rotates the solid around the z axis
:param center: The point to rotate around
:type center: :class:`Vertex`
:param angle: How much to rotate in degrees
:type angle: :obj:`int` or :obj:`float`
"""
for side in self.side:
side.rotate_z(center, angle)
def flip(self, x=None, y=None, z=None):
for vert in self.get_all_vertices():
vert.flip(x, y, z)
def scale(self, center: Vertex, x=1.0, y=1.0, z=1.0):
"""
Scales the solid using ratios.
For example using the center of the solid and values of 2 makes it twice as big
:param center: The point from which the scaling is based, use the center of the solid for traditional scaling
:type center: :class:`Vertex`
:param x: Scale ratio on the x axis
:type x: :obj:`int` or :obj:`float`
:param y: Scale ratio on the y axis
:type y: :obj:`int` or :obj:`float`
:param z: Scale ratio on the z axis
:type z: :obj:`int` or :obj:`float`
"""
x -= 1
y -= 1
z -= 1
for vertex in self.get_all_vertices():
diff = vertex.diff(center)
fixed_diff = (diff.x * x, diff.y * y, diff.z * z)
vertex.move(*fixed_diff)
@property
def center(self) -> Vertex:
"""
Finds the center of the solid based on the average of all vertices.
**Can behave unpredictably** as faces only consists of 3 verticies so the center might be off by a tiny amount
For a more reliable option see :func:`~Solid.center_geo`
:return: The average center of the solid
:rtype: :class:`Vertex`
"""
v = Vertex()
vert_list = self.get_only_unique_vertices()
for vert in vert_list:
v = v + vert
v.divide(len(vert_list))
return v
@center.setter
def center(self, vertex: Vertex):
"""
Moves the solid based on it's center to the new position
:param vertex: The new position assumed by the solid center
:type vertex: :class:`Vertex`
"""
self.move(*vertex.diff(self.center).export())
@property
def center_geo(self) -> Vertex:
"""
Finds the center of the solid based on the extremities of all 3 axes.
More reliable than :func:`~Solid.center`
:return: The geometric center of the solid
:rtype: :class:`Vertex`
"""
v = Vertex()
x = self.get_axis_extremity(x=False).x
y = self.get_axis_extremity(y=False).y
z = self.get_axis_extremity(z=False).z
size = self.size
size.divide(2)
v.set(x, y, z)
v.move(*size.export())
return v
def get_axis_extremity(self, x: bool = None, y: bool = None, z: bool = None) -> Vertex:
"""
Finds the vertex that is the furthest on the given axis, **only 1 axis per method call**,
see :func:`~Solid.get_3d_extremity`
:param x: False for negative side of the axis, True for positive side
:type x: :obj:`bool`
:param y: False for negative side of the axis, True for positive side
:type y: :obj:`bool`
:param z: False for negative side of the axis, True for positive side
:type z: :obj:`bool`
:return: The vertex the furthest most on the given axis
:rtype: :class:`Vertex`
"""
verts = self.get_only_unique_vertices()
if x is not None:
lx = sorted(verts, key=operator.attrgetter("x"))
return lx[int(not x) - 1]
elif y is not None:
ly = sorted(verts, key=operator.attrgetter("y"))
return ly[int(not y) - 1]
elif z is not None:
lz = sorted(verts, key=operator.attrgetter("z"))
return lz[int(not z) - 1]
raise ValueError("No axis given")
def get_3d_extremity(self, x: bool = None, y: bool = None, z: bool = None) -> Tuple[Vertex, List[Vertex, ...]]:
"""
Finds the vertices that are the furthest on the given axes, as well as ties
:param x: False for negative side of the axis, True for positive side
:type x: :obj:`bool`
:param y: False for negative side of the axis, True for positive side
:type y: :obj:`bool`
:param z: False for negative side of the axis, True for positive side
:type z: :obj:`bool`
:return: The vertex furthest most on the given axes, and the ties, **the champion vertex is included**
:rtype: :class:`Vertex`, :obj:`list` of :class:`Vertex`
"""
verts = self.get_only_unique_vertices()
for vert in verts:
vert.sorting = 0
if x is not None:
if x:
vert.sorting += vert.x
else:
vert.sorting -= vert.x
if y is not None:
if y:
vert.sorting += vert.y
else:
vert.sorting -= vert.y
if z is not None:
if z:
vert.sorting += vert.z
else:
vert.sorting -= vert.z
sort = sorted(verts, key=operator.attrgetter("sorting"))
best = sort[-1]
ties = []
for vert in sort:
if vert.sorting == best.sorting:
ties.append(vert)
return best, ties
def get_all_vertices(self) -> List[Vertex, ...]:
"""
Finds all vertices on the solid, including overlapping ones from the different sides, for only unique vertices
use :func:`~Solid.get_only_unique_vertices`
:return: All the vertices on the solid
:rtype: :obj:`list` of :class:`Vertex`
"""
vertex_list = []
for side in self.side:
vertex_list.extend(side.plane)
return vertex_list
def get_sides(self) -> List[Side, ...]:
"""
:return: All the sides on the solid
:rtype: :obj:`list` of :class:`Side`
"""
return self.side
@property
def size(self) -> Vertex:
"""
:return: The total size of the bounding rectangle around the solid
:rtype: :class:`Vertex`
"""
x = []
y = []
z = []
for vert in self.get_all_vertices():
x.append(vert.x)
y.append(vert.y)
z.append(vert.z)
return Vertex(max(x) - min(x), max(y) - min(y), max(z) - min(z))
def get_displacement_sides(self) -> List[Side]:
"""
Gets the sides that have displacements, use :func:`~Solid.get_displacement_matrix_sides` to get the matrices
directly instead
:return: The sides with displacements on them
:rtype: :obj:`list` of :class:`Side`
"""
li = []
for side in self.side:
if side.dispinfo is not None:
li.append(side)
return li
def get_displacement_matrix_sides(self) -> List[Matrix, ...]:
"""
Gets the matrices from all the sides that have displacements, use :func:`~Solid.get_displacement_sides` to get
the sides instead
:return: The matrices from the sides with displacements on them
:type: :obj:`list` of :class:`Matrix`
"""
li = []
for side in self.get_displacement_sides():
li.append(side.dispinfo.matrix)
return li
def get_texture_sides(self, name: str, exact=False) -> List[Side, ...]:
"""
:param name: The name of the texture including path (ex: tools/toolsnodraw)
:type name: :obj:`string`
:param exact: Determines if the material has to be letter for letter the same or just contain the string
:type exact: :obj:`bool`
:return: The sides using the given texture
:rtype: :obj:`list` of :class:`Side`
"""
li = []
for side in self.side:
if not exact:
if name.upper() in side.material:
li.append(side)
else:
if side.material == name.upper():
li.append(side)
return li
def get_only_unique_vertices(self) -> List[Vertex, ...]:
"""
Finds all unique vertices on the solid, **you should not use this for vertex manipulation as changing one
doesn't change all of them**. See :func:`~Solid.get_all_vertices`
:return: all unique vertices
:rtype: :obj:`list` of :class:`Vertex`
"""
vertex_list = []
for side in self.side:
for vertex in side.plane:
if vertex not in vertex_list:
vertex_list.append(vertex)
return vertex_list
def has_texture(self, name: str, exact=False) -> bool:
"""
:param name: The name of the texture including path (ex: tools/toolsnodraw)
:type name: :obj:`string`
:param exact: Determines if the material has to be letter for letter the same or just contain the string
:type exact: :obj:`bool`
:return: if any sides of the solid contain the given texture
:rtype: :obj:`bool`
"""
for side in self.side:
if not exact:
if name.upper() in side.material:
return True
else:
if side.material == name.upper():
return True
return False
def replace_texture(self, old_material: str, new_material: str):
"""
Checks all the sides if they have the given texture, if so replace it
:param old_material: The texture to check
:type old_material: :obj:`String`
:param new_material: The texture to replace the old one with
:type new_material: :obj:`String`
"""
for side in self.side:
if side.material == old_material:
side.material = new_material
def naive_subdivide(self, x=1, y=1, z=1) -> List[Solid, ...]:
"""
Naively subdivides a copy of the solid, works best for rectangular shapes. It's naive because it scales down
the solid then creates an array from that
:param x: Amount of cuts on the x axis
:type x: :obj:`int`
:param y: Amount of cuts on the y axis
:type y: :obj:`int`
:param z: Amount of cuts on the z axis
:type z: :obj:`int`
:return: Solids from a subdivided solid
:rtype: :obj:`list` of :class:`Solid`
"""
li = []
s = self.copy()
half_size = s.size
half_size.divide(2)
ratio = (1 / x, 1 / y, 1 / z)
s.scale(s.center, *ratio)
move_amount = s.size
s.move(-half_size.x, half_size.y, half_size.z)
s.move(move_amount.x / 2, -move_amount.y / 2, -move_amount.z / 2)
for iz in range(z):
for iy in range(y):
for ix in range(x):
s2 = s.copy()
s2.move(ix * move_amount.x, -iy * move_amount.y, -iz * move_amount.z)
li.append(s2)
return li
def window(self, direction: Vertex = None) -> List[Solid, Solid, Solid, Solid]:
"""
Creates a hole in the wall, only works on 90 degree blocks
:param direction: If set defines the direction the hole will be made, requires exactly 2 non-zero values
:type direction: :class:`Vertex`
:return: The 4 blocks surrounding the hole
:rtype: :obj:`list` of :class:`Solid`
"""
dim = [0, 0, 0]
div_amount = 3
smallest_pos = 0
if direction is None:
size = self.size.export()
smallest = min(size)
cube_check = False
for i, pos in enumerate(size):
if pos == smallest and not cube_check:
dim[i] = 1
smallest_pos = i
cube_check = True
else:
dim[i] = div_amount
else:
error = 0
for i, pos in enumerate(direction.export()):
if pos != 0:
dim[i] = div_amount
smallest_pos = i
error += 1
else:
dim[i] = 1
if error != 2:
raise ValueError("Only 2 directions are accepted, please read the docs")
sub = self.naive_subdivide(*dim)
req = [sub[1], sub[3], sub[5], sub[7]]
s1 = req[0]
s2 = req[-1]
if smallest_pos == 0:
s1.scale(s1.center, 1, div_amount)
s2.scale(s2.center, 1, div_amount)
else:
s1.scale(s1.center, div_amount)
s2.scale(s2.center, div_amount)
return req
def is_simple_solid(self) -> bool:
"""
:return: A solid is considered simple if it has 6 or less sides
:rtype: :obj:`bool`
"""
return len(self.side) <= 6
def link_vertices(self, similar=0.0):
"""
Tries to link all the vertices that are similiar
:param similar:
"""
vertex_list = []
for side in self.get_sides():
for i, vertex in enumerate(side.get_vertices()):
for vertex_check in vertex_list:
if vertex.similar(vertex_check, similar):
side.plane[i] = vertex_check
else:
vertex_list.append(vertex)
def set_texture(self, new_material: str):
"""
Sets the given texture on all sides
:param new_material: The texture to replace them all
:type new_material: :obj:`str`