-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathseadog_utils.py
More file actions
1491 lines (1101 loc) · 45.6 KB
/
seadog_utils.py
File metadata and controls
1491 lines (1101 loc) · 45.6 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
bl_info = {
"name": "SeaDogs Utils",
"version": (2, 2, 0),
"blender": (3, 6, 0),
"category": "Object",
"support": "COMMUNITY",
"author": "Wazar",
}
import bmesh
import bpy
from bpy.props import StringProperty, BoolProperty, PointerProperty, IntProperty, FloatProperty
import numpy
import sys
from mathutils import Vector, Matrix
from mathutils.bvhtree import BVHTree
import re
import random
from math import *
from io import StringIO
class CapturingInfo():
def __init__(self, report):
self.report = report
def __enter__(self):
self._stdout = sys.stdout
sys.stdout = self._stringio = StringIO()
return self
def __exit__(self, *args):
sys.stdout = self._stdout
for cur in self._stringio.getvalue().splitlines():
if cur.startswith('Debug: '):
self.report({'DEBUG'}, cur[len('Debug: '):])
elif cur.startswith('Info: '):
self.report({'INFO'}, cur[len('Info: '):])
elif cur.startswith('Warning: '):
self.report({'WARNING'}, cur[len('Warning: '):])
elif cur.startswith('Error: '):
self.report({'ERROR'}, cur[len('Error: '):])
elif cur.startswith('Critical: '):
self.report({'CRITICAL'}, cur[len('Critical: '):])
else:
print(cur)
del self._stringio # free up some memory
def remove_blender_name_postfix(name):
return re.sub(r'\.\d{3}', '', name)
def get_foam_object(root):
root_children = root.children
foams_locator = None
for child in root_children:
if child.type == 'EMPTY' and remove_blender_name_postfix(child.name) == 'foams':
foams_locator = child
break
if foams_locator is None:
collection = root.users_collection[0]
foams_locator_name = 'foams'
foams_locator = bpy.data.objects.new(foams_locator_name, None)
collection.objects.link(foams_locator)
foams_locator.parent = root
foams_locator['MaxFoamDistance'] = 1000
foams_locator['FoamDeltaY'] = 0.2
foams_locator['FoamDivides'] = 4
return foams_locator
def get_points_object(root):
root_children = root.children
locator = None
for child in root_children:
if child.type == 'EMPTY' and remove_blender_name_postfix(child.name) == 'points':
locator = child
break
return locator
def create_new_foam(foam_object):
collection = foam_object.users_collection[0]
locator_name = 'foam_{:04d}'.format(len(foam_object.children))
cur_foam_locator = bpy.data.objects.new(locator_name, None)
collection.objects.link(cur_foam_locator)
cur_foam_locator.parent = foam_object
cur_foam_locator['Alpha'] = '148, 196'
cur_foam_locator['Speed'] = '0.200, 0.250'
cur_foam_locator['Braking'] = '0.000, 0.000'
cur_foam_locator['Appear'] = '0.000, 0.000'
cur_foam_locator['TexScaleX'] = 0.100
cur_foam_locator['NumFoams'] = 2
cur_foam_locator['Texture'] = 'foam.tga'
cur_foam_locator['Type'] = 2
return cur_foam_locator
def add_key_to_foam(foam, vert, shift, seadogs_tool):
collection = foam.users_collection[0]
inverted = seadogs_tool.foam_inverted
cur_depth = seadogs_tool.foam_depth
cur_index = len(foam.children) // 2
base = vert.coord.to_2d()
norm = vert.get_direction()
shift_1 = cur_depth
shift_2 = 0
if inverted:
shift_1 = 0
shift_2 = cur_depth
if shift == 'near':
shift_1 -= 10
shift_2 -= 10
elif shift == 'far':
shift_1 += 7.8
shift_2 += 7.8
elif shift == 'farthest':
shift_1 += 9.6
shift_2 += 9.6
shift_1_vec = norm.normalized() * shift_1
shift_2_vec = norm.normalized() * shift_2
coord_1 = base + shift_1_vec
coord_2 = base + shift_2_vec
locator_1_name = 'key1_{:04d}'.format(cur_index)
locator_2_name = 'key2_{:04d}'.format(cur_index)
locator_1 = bpy.data.objects.new(locator_1_name, None)
collection.objects.link(locator_1)
locator_1.parent = foam
locator_1.empty_display_type = 'ARROWS'
locator_1.empty_display_size = 1.0
locator_1.matrix_basis = Matrix.Translation(coord_1.to_3d())
locator_2 = bpy.data.objects.new(locator_2_name, None)
collection.objects.link(locator_2)
locator_2.parent = foam
locator_2.empty_display_type = 'ARROWS'
locator_2.empty_display_size = 1.0
locator_2.matrix_basis = Matrix.Translation(coord_2.to_3d())
def vert_to_string(v):
return '{:.10f}:{:.10f}:{:.10f}'.format(v.co.x, v.co.y, v.co.z)
class Point:
def __init__(self, number, coord, normal, _points):
self.number = number
self.coord = coord
self.normal = normal
self.edges = []
self.passed = 0
self._points = _points
def set_pairs(self, pairs):
cur_pairs = set(self.edges)
new_pairs = set(pairs)
self.edges = list(cur_pairs.union(new_pairs))
for cur in pairs:
if cur == self.number:
bpy.context.scene.cursor.location = self.coord
raise ValueError('{} is setted as pair to itself'.format(cur))
def add_pair(self, pair):
cur_pairs = set(self.edges)
cur_pairs.add(pair)
self.edges = list(cur_pairs)
def get_direction(self):
edge_1 = self._points[self.edges[0]].coord.to_2d() - self.coord.to_2d()
edge_2 = None
if (len(self.edges) > 1):
edge_2= self._points[self.edges[1]].coord.to_2d() - self.coord.to_2d()
else:
edge_2 = -edge_1
norm = edge_1.normalized() + edge_2.normalized()
if norm.length == 0.0:
norm = edge_1.orthogonal()
if norm.dot(self.normal.to_2d()) < 0:
norm = -norm
return norm
def print(self):
print('{}: ({}) => {}'.format(self.number, self.coord, self.edges))
class SubGraph:
def __init__(self, points, is_cycle):
self.points = points
self.is_cycle = is_cycle
def print(self):
print('{}; is_cycle: {}'.format([p.number for p in self.points], self.is_cycle))
def get_sub_graphs(context, mesh, report):
points = {}
point_nums = []
coord_idx = {}
alias_idx = {}
sub_graphs = []
bm = bmesh.from_edit_mesh(mesh.data)
bm.verts.ensure_lookup_table()
print(len(bm.verts[:]))
print(len(bm.edges[:]))
for i, v in enumerate(bm.verts):
v.index = i
for i, v in enumerate(bm.verts):
if not v.select:
continue
cur_idx = v.index
if cur_idx in alias_idx:
cur_idx = alias_idx[cur_idx]
else:
vstr = vert_to_string(v)
if vstr in coord_idx:
cur_idx = coord_idx[vstr]
alias_idx[v.index] = cur_idx
else:
coord_idx[vstr] = cur_idx
alias_idx[cur_idx] = cur_idx
point_nums.append(cur_idx)
cur_point = Point(cur_idx, v.co.copy(), v.normal.copy(), points)
points[cur_idx] = cur_point
point_nums.sort()
print('=======P======')
for idx in point_nums:
cur_point = points[idx]
cur_point.print()
print('==================')
for i, v in enumerate(bm.verts):
if not v.select:
continue
cur_idx = alias_idx[v.index]
cur_point = points[cur_idx]
pairs = [e.other_vert(v) for e in v.link_edges if e.other_vert(v).select]
pair_idxs = [alias_idx[p.index] for p in pairs if alias_idx[p.index] != cur_idx]
cur_point.set_pairs(pair_idxs)
if (len(cur_point.edges) > 2):
report({'ERROR'}, '{}: vertex with more than two selected edges is selected'.format(cur_idx))
context.scene.cursor.location = v.co
return sub_graphs
for p in pair_idxs:
pair_point = points[p]
pair_point.add_pair(cur_idx)
if (len(pair_point.edges) > 2):
report({'ERROR'}, '{}: vertex with more than two selected edges is selected'.format(p))
context.scene.cursor.location = pair_point.coord
return sub_graphs
for idx in point_nums:
cur_point = points[idx]
if (len(cur_point.edges) == 0):
report({'ERROR'}, '{}: vertex without selected edges is selected'.format(cur_idx))
context.scene.cursor.location = v.co
return sub_graphs
#print('=======P======')
#for idx in point_nums:
# cur_point = points[idx]
# cur_point.print()
#print('==================')
for idx in point_nums:
cur_point = points[idx]
print('cur_point = {}; passed = {}'.format(idx, cur_point.passed))
if cur_point.passed != 0:
continue
start_point = cur_point
cur_point.passed = 1
prev_point = cur_point
is_cycle = False
cur_indexes = [cur_point.number]
print('start {}'.format(cur_point.number))
while True:
next_idx = cur_point.edges[0]
if next_idx == prev_point.number:
if len(cur_point.edges) > 1:
next_idx = cur_point.edges[1]
else:
print('cur_point.number = {}; prev_point.number = {} no next'.format(cur_point.number, prev_point.number))
break
next_point = points[next_idx]
print('next_point.number = {}; cur_point.number = {} ->'.format(next_point.number, cur_point.number))
cur_indexes.append(next_idx)
if (next_point.passed == 1):
is_cycle = True
print('cur_point.number = {}; prev_point.number = {} cycle'.format(next_point.number, cur_point.number))
break
prev_point = cur_point
cur_point = next_point
cur_point.passed = 1
if not is_cycle:
prev_points = []
if len(start_point.edges) > 1:
prev_point = start_point
next_idx = start_point.edges[1]
cur_point = points[next_idx]
while True:
next_idx = cur_point.edges[0]
print('next_idx = {}; prev_point.number = {}'.format(next_idx, prev_point.number))
if next_idx == prev_point.number:
if len(cur_point.edges) > 1:
next_idx = cur_point.edges[1]
else:
break
prev_point = cur_point
cur_point = points[next_idx]
prev_points = [cur_point.number]
prev_point = cur_point
cur_point.passed = 1
while True:
next_idx = cur_point.edges[0]
if next_idx == prev_point.number:
next_idx = cur_point.edges[1]
next_point = points[next_idx]
if (next_point.passed == 1):
break
prev_points.append(next_idx)
prev_point = cur_point
cur_point = next_point
cur_point.passed = 1
prev_points.extend(cur_indexes)
cur_indexes = prev_points
point_for_graph = [points[i] for i in cur_indexes]
cur_graph = SubGraph(point_for_graph, is_cycle)
sub_graphs.append(cur_graph)
#print('=====SG======')
#for sg in sub_graphs:
# sg.print()
#print('==================')
return sub_graphs
def generate_foam(context, mesh, root, shift, seadogs_tool, report):
sub_graphs = get_sub_graphs(context, mesh, report)
foam_object = get_foam_object(root)
for sg in sub_graphs:
cur_foam = create_new_foam(foam_object)
count = 0
for i, v in enumerate(sg.points):
add_key_to_foam(cur_foam, v, shift, seadogs_tool)
if count > seadogs_tool.max_foam_points and i < len(sg.points) - 2:
count = 0
print_foam_links(cur_foam, report)
cur_foam = create_new_foam(foam_object)
add_key_to_foam(cur_foam, v, shift, seadogs_tool)
count += 1
print_foam_links(cur_foam, report)
def print_foam_links(foam, report):
point_locators = []
points = []
for child in foam.children:
if child.type == 'EMPTY':
point_locators.append(child)
if len(point_locators) % 2 == 1:
report({'ERROR'}, 'point count should be even for locator "{}"'.format(foam.name))
return {'CANCELLED'}
key_count = len(point_locators) // 2
for i in range(key_count):
p = point_locators[i]
points.append([p, 0, point_locators[i+key_count]])
for i in range(key_count - 1):
point_locators[key_count + i].constraints.clear()
constraint = point_locators[key_count + i].constraints.new(type='TRACK_TO')
constraint.target = point_locators[key_count + i + 1]
constraint.name = 'link_{}_f'.format(i)
constraint = point_locators[i].constraints.new(type='TRACK_TO')
constraint.target = point_locators[i + 1]
constraint.name = 'link_{}_n'.format(i)
constraint = point_locators[key_count + i].constraints.new(type='TRACK_TO')
constraint.target = point_locators[i]
constraint.name = 'link_{}_s'.format(i)
i = key_count - 1
constraint = point_locators[key_count + i].constraints.new(type='TRACK_TO')
constraint.target = point_locators[i]
constraint.name = 'link_{}_s'.format(i)
def GenerateFoam(shift):
class GenerateFoamImpl(bpy.types.Operator):
bl_idname = "seadogs_util.generate_foam_"+shift
bl_label = "Generate foam ({})".format(shift)
bl_options = {'REGISTER', 'UNDO'}
@classmethod
def poll(cls, context):
return bpy.context.active_object != None and bpy.context.active_object.mode == 'EDIT'
def execute(self, context):
seadogs_tool = context.scene.seadogs_tool
mesh_object = bpy.context.view_layer.objects.active
selected_objects = [o for o in bpy.context.view_layer.objects.selected if o.name != mesh_object.name]
if (len(selected_objects) != 1 or remove_blender_name_postfix(selected_objects[0].name) != 'root' or selected_objects[0].type != 'EMPTY'):
self.report({'ERROR'}, 'Root of foam collection should be selected');
return {'CANCELLED'}
root_for_foam = selected_objects[0]
ret = generate_foam(context, mesh_object, root_for_foam, shift, seadogs_tool, self.report)
if ret is not None:
return {'CANCELLED'}
return {'FINISHED'}
return GenerateFoamImpl
def create_random_point(foam_root, bounds, bvh_tree, num):
seadogs_tool = bpy.context.scene.seadogs_tool
max_range = seadogs_tool.path_point_max_range
x_min, x_max, y_min, y_max = bounds
x_min -= max_range
y_min -= max_range
x_max += max_range
y_max += max_range
src_point = None
while True:
src_point = Vector((random.uniform(x_min, x_max), random.uniform(y_min, y_max), -100))
direction = Vector((0, 0, 1))
hit_location, hit_normal, face_index, distance = bvh_tree.ray_cast(src_point, direction)
if hit_location is None:
break
src_point[2] = 0
locator_name = 'pnt{:04d}'.format(num)
collection = foam_root.users_collection[0]
locator = bpy.data.objects.new(locator_name, None)
collection.objects.link(locator)
locator.parent = foam_root
locator.empty_display_type = 'ARROWS'
locator.empty_display_size = 0.5
locator.matrix_basis = Matrix.Translation(src_point)
def check_accessible(src, dst, bvh_tree):
src_point = src.matrix_world.translation.copy()
dst_point = dst.matrix_world.translation.copy()
src_point[2] = 0.1
dst_point[2] = 0.1
direction = dst_point - src_point
direction_norm = direction.normalized()
direction_length = direction.length
hit_location, hit_normal, face_index, distance = bvh_tree.ray_cast(src_point, direction_norm, direction_length)
if hit_location is None:
return True
return False
def create_path(src, dst, num):
src_name = remove_blender_name_postfix(src.name)
constraint = src.constraints.new(type='TRACK_TO')
constraint.target = dst
constraint.name = '{}_{:04d}'.format(src_name, num)
def remove_double_path(src, dst, report):
foam_object = src.parent
if foam_object is None:
report({'ERROR'}, 'points object not found')
return {'CANCELLED'}
for c in src.constraints:
if c.target is not None and c.target == dst:
src.constraints.remove(c)
for c in dst.constraints:
if c.target is not None and c.target == src:
dst.constraints.remove(c)
def create_double_path(src, dst, report):
foam_object = src.parent
if foam_object is None:
report({'ERROR'}, 'points object not found')
return {'CANCELLED'}
src_name = remove_blender_name_postfix(src.name)
dst_name = remove_blender_name_postfix(dst.name)
src_name_set = set()
dst_name_set = set()
src_cname = None
dst_cname = None
for cur in foam_object.children:
if cur.type != 'EMPTY':
continue
for c in cur.constraints:
cname = remove_blender_name_postfix(c.name)
if cname.startswith(src_name+'_'):
src_name_set.add(cname)
if cname.startswith(dst_name+'_'):
dst_name_set.add(cname)
for i in range(len(src_name_set)+1):
name = '{}_{:04d}'.format(src_name, i)
if name not in src_name_set:
src_cname = name
break
for i in range(len(dst_name_set)+1):
name = '{}_{:04d}'.format(dst_name, i)
if name not in dst_name_set:
dst_cname = name
break
constraint = src.constraints.new(type='TRACK_TO')
constraint.target = dst
constraint.name = src_cname
constraint = dst.constraints.new(type='TRACK_TO')
constraint.target = src
constraint.name = dst_cname
def generate_island_foam(context, root, mesh_root_list, seadogs_tool, report):
foam_object = get_points_object(root)
if foam_object is None:
report({'ERROR'}, 'points object not found')
return {'CANCELLED'}
num = 0
points = []
for cur in foam_object.children:
if cur.type != 'EMPTY':
continue
cur.name = 'pnt{:04d}'.format(num)
cur.matrix_world.translation[2] = 0
cur.constraints.clear()
num += 1
points.append(cur)
mesh_list = []
for cur in mesh_root_list:
print('meshes: {}'.format([o.name for o in cur.children if o.type == 'MESH']))
mesh_list.extend([o for o in cur.children if o.type == 'MESH'])
bm = bmesh.new()
for me in mesh_list:
bm.from_mesh(me.data)
bvh_tree = BVHTree.FromBMesh(bm, epsilon=0.0001)
for i in range(len(points)):
con_num = 0
for j in range(len(points)):
if i == j:
continue
source_point = points[i]
target_point = points[j]
if check_accessible(source_point, target_point, bvh_tree):
create_path(source_point, target_point, con_num)
con_num += 1
bm.free()
def get_2d_bounds(bm):
x_min = sys.float_info.max
x_max = sys.float_info.min
y_min = sys.float_info.max
y_max = sys.float_info.min
for v in bm.verts:
if x_min > v.co[0]:
x_min = v.co[0]
if x_max < v.co[0]:
x_max = v.co[0]
if y_min > v.co[1]:
y_min = v.co[1]
if y_max < v.co[1]:
y_max = v.co[1]
return (x_min, x_max, y_min, y_max)
def generate_island_foam_points(context, root, mesh_root_list, seadogs_tool, report):
foam_object = get_points_object(root)
if foam_object is None:
report({'ERROR'}, 'points object not found')
return {'CANCELLED'}
num = len(foam_object.children)
points = []
count = seadogs_tool.path_point_count
mesh_list = []
for cur in mesh_root_list:
print('meshes: {}'.format([o.name for o in cur.children if o.type == 'MESH']))
mesh_list.extend([o for o in cur.children if o.type == 'MESH'])
bm = bmesh.new()
for me in mesh_list:
bm.from_mesh(me.data)
bvh_tree = BVHTree.FromBMesh(bm, epsilon=0.0001)
bounds = get_2d_bounds(bm)
for i in range(count):
create_random_point(foam_object, bounds, bvh_tree, num+i)
bm.free()
class GenerateIslandFoam(bpy.types.Operator):
bl_idname = "seadogs_util.generate_island_foam"
bl_label = "Generate island foam"
bl_options = {'REGISTER', 'UNDO'}
def execute(self, context):
seadogs_tool = context.scene.seadogs_tool
foam_root = bpy.context.view_layer.objects.active
selected_objects = [o for o in bpy.context.view_layer.objects.selected if o.name != foam_root.name]
wrong_objects = [o for o in selected_objects if o.type != 'EMPTY' or remove_blender_name_postfix(o.name) != 'root']
if (len(wrong_objects) > 0) or foam_root.type != 'EMPTY' or remove_blender_name_postfix(foam_root.name) != 'root':
self.report({'ERROR'}, 'Selected objects should be root')
return {'CANCELLED'}
ret = generate_island_foam(context, foam_root, selected_objects, seadogs_tool, self.report)
if ret is not None:
return {'CANCELLED'}
return {'FINISHED'}
class GenerateIslandFoamPoints(bpy.types.Operator):
bl_idname = "seadogs_util.generate_island_foam_points"
bl_label = "Generate island foam"
bl_options = {'REGISTER', 'UNDO'}
def execute(self, context):
seadogs_tool = context.scene.seadogs_tool
foam_root = bpy.context.view_layer.objects.active
selected_objects = [o for o in bpy.context.view_layer.objects.selected if o.name != foam_root.name]
wrong_objects = [o for o in selected_objects if o.type != 'EMPTY' or remove_blender_name_postfix(o.name) != 'root']
if (len(wrong_objects) > 0) or foam_root.type != 'EMPTY' or remove_blender_name_postfix(foam_root.name) != 'root':
self.report({'ERROR'}, 'Selected objects should be root')
return {'CANCELLED'}
ret = generate_island_foam_points(context, foam_root, selected_objects, seadogs_tool, self.report)
if ret is not None:
return {'CANCELLED'}
return {'FINISHED'}
class AddPath(bpy.types.Operator):
bl_idname = "seadogs_util.add_path"
bl_label = "Add path"
bl_options = {'REGISTER', 'UNDO'}
@classmethod
def poll(cls, context):
return (len(context.view_layer.objects.selected) == 2
and context.view_layer.objects.selected[0].parent == context.view_layer.objects.selected[1].parent
and context.view_layer.objects.selected[0].type == 'EMPTY'
and context.view_layer.objects.selected[1].type == 'EMPTY'
and context.view_layer.objects.selected[0].parent is not None)
def execute(self, context):
seadogs_tool = context.scene.seadogs_tool
if len(context.view_layer.objects.selected) != 2:
self.report({'ERROR'}, 'Two locators should be selected')
return {'CANCELLED'}
ret = create_double_path(context.view_layer.objects.selected[0], context.view_layer.objects.selected[1], self.report)
if ret is not None:
return {'CANCELLED'}
return {'FINISHED'}
class RemovePath(bpy.types.Operator):
bl_idname = "seadogs_util.remove_path"
bl_label = "Remove path"
bl_options = {'REGISTER', 'UNDO'}
@classmethod
def poll(cls, context):
return (len(context.view_layer.objects.selected) == 2
and context.view_layer.objects.selected[0].parent == context.view_layer.objects.selected[1].parent
and context.view_layer.objects.selected[0].type == 'EMPTY'
and context.view_layer.objects.selected[1].type == 'EMPTY'
and context.view_layer.objects.selected[0].parent is not None)
def execute(self, context):
seadogs_tool = context.scene.seadogs_tool
if len(context.view_layer.objects.selected) != 2:
self.report({'ERROR'}, 'Two locators should be selected')
return {'CANCELLED'}
ret = remove_double_path(context.view_layer.objects.selected[0], context.view_layer.objects.selected[1], self.report)
if ret is not None:
return {'CANCELLED'}
return {'FINISHED'}
class MinMaxCollector:
def __init__(self):
self.x_min = sys.float_info.max
self.x_max = sys.float_info.min
self.y_min = sys.float_info.max
self.y_max = sys.float_info.min
self.z_min = sys.float_info.max
self.z_max = sys.float_info.min
def add_vertex(self, v):
if self.x_min > v.co[0]:
self.x_min = v.co[0]
if self.x_max < v.co[0]:
self.x_max = v.co[0]
if self.y_min > v.co[1]:
self.y_min = v.co[1]
if self.y_max < v.co[1]:
self.y_max = v.co[1]
if self.z_min > v.co[2]:
self.z_min = v.co[2]
if self.z_max < v.co[2]:
self.z_max = v.co[2]
def get_min(self):
return Vector((self.x_min, self.y_min, self.z_min))
def get_sizes(self):
return (self.x_max - self.x_min, self.y_max - self.y_min, self.z_max - self.z_min)
def consolidate_vertexes_from_buckets_with_ver(ver1, buckets, delta, counts, x, y, z):
moved = 0
x_s = x - 1 if x > 1 else x
x_f = x + 2 if x < counts[0] - 1 else x + 1
y_s = y - 1 if y > 1 else y
y_f = y + 2 if y < counts[1] - 1 else y + 1
z_s = z - 1 if z > 1 else z
z_f = z + 2 if z < counts[2] - 1 else z + 1
for i in range(x_s, x_f):
for j in range(y_s, y_f):
for k in range(z_s, z_f):
if buckets[get_coord(i, j, k, counts)] is None:
continue
for n in range(len(buckets[get_coord(i, j, k, counts)])):
ver2 = buckets[get_coord(i, j, k, counts)][n]
if (ver2.co-ver1.co).length <= delta and ver2.co != ver1.co:
ver2.co = ver1.co
moved += 1
return moved
def consolidate_vertexes_from_buckets(buckets, delta, counts):
total_moved = 0
for i in range(counts[0]):
print('i = {}/{}'.format(i, counts[0]))
for j in range(counts[1]):
for k in range(counts[2]):
if buckets[get_coord(i, j, k, counts)] is None:
continue
while True:
moved = 0
for n in range(len(buckets[get_coord(i, j, k, counts)])):
ver = buckets[get_coord(i, j, k, counts)][n]
moved += consolidate_vertexes_from_buckets_with_ver(ver, buckets, delta, counts, i, j, k)
if moved == 0:
break
else:
print('bucket[{}][{}][{}] moved {}'.format(i, j, k, moved))
total_moved += moved
print('consolidating finised. moved {} verts'.format(total_moved))
def get_coord(i, j, k, sizes):
return i*sizes[1]*sizes[2] + j*sizes[2] + k
def consolidate_vertexes(context, mesh_list, seadogs_tool, report):
delta = seadogs_tool.consolidate_delta
bucket_size = seadogs_tool.bucket_size
if len(mesh_list) == 0:
report({'WARNING'}, 'No meshes selected')
return None
bpy.ops.object.mode_set(mode='OBJECT')
bpy.ops.object.select_all(action='DESELECT')
for cur in mesh_list:
cur.select_set(True)
bpy.context.view_layer.objects.active = mesh_list[0]
bpy.ops.object.mode_set(mode='EDIT')
bms = [bmesh.from_edit_mesh(obj.data) for obj in mesh_list]
bounds = MinMaxCollector()
for cur in bms:
for v in cur.verts:
bounds.add_vertex(v)
counts = [int(dim / bucket_size) + 1 for dim in bounds.get_sizes()]
total_count = counts[0] * counts[1] * counts[2]
print('size={} buckets={}'.format(bounds.get_sizes(), counts))
print('allocating buckets...')
buckets = [None]*total_count
#for i in range(counts[0]):
# print('i = {}/{}'.format(i, counts[0]))
# buckets[i] = [None]*counts[1]
# for j in range(counts[1]):
# buckets[i][j] = [None]*counts[2]
print('done')
print('placing vertexes...')
for i in range(len(bms)):
cur = bms[i]
print('mesh {}/{}'.format(i, len(bms)))
for v in cur.verts:
x_bucket = int(v.co[0] / bucket_size)
y_bucket = int(v.co[1] / bucket_size)
z_bucket = int(v.co[2] / bucket_size)
if buckets[get_coord(x_bucket, y_bucket, z_bucket, counts)] is None:
buckets[get_coord(x_bucket, y_bucket, z_bucket, counts)] = []
buckets[get_coord(x_bucket, y_bucket, z_bucket, counts)].append(v)
print('done')
print('consolidating...')
consolidate_vertexes_from_buckets(buckets, delta, counts)
print('done')
for i in range(len(bms)):
bmesh.update_edit_mesh(mesh_list[i].data, loop_triangles=False, destructive=False)
def cleanup_cycle(bms, report):
for cur in bms:
for v in cur.verts:
v.select_set(True)
for v in cur.edges:
v.select_set(True)
for v in cur.faces:
v.select_set(True)
print('degenerate:')
with CapturingInfo(report) as _:
bpy.ops.mesh.dissolve_degenerate()
for cur in bms:
for v in cur.verts:
v.select_set(True)
for v in cur.edges:
v.select_set(True)
for v in cur.faces:
v.select_set(True)
print('delete_loose:')
with CapturingInfo(report) as _:
bpy.ops.mesh.delete_loose()
def remove_void_faces(context, mesh_list, seadogs_tool, report):
if len(mesh_list) == 0:
report({'WARNING'}, 'No meshes selected')
return None
bpy.ops.object.mode_set(mode='OBJECT')
bpy.ops.object.select_all(action='DESELECT')
for cur in mesh_list:
cur.select_set(True)
bpy.context.view_layer.objects.active = mesh_list[0]
bpy.ops.object.mode_set(mode='EDIT')
bms = [bmesh.from_edit_mesh(obj.data) for obj in mesh_list]
for cur in bms:
for v in cur.verts: