-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathimport_gm_full_ship.py
More file actions
2642 lines (2026 loc) · 97.3 KB
/
Copy pathimport_gm_full_ship.py
File metadata and controls
2642 lines (2026 loc) · 97.3 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
import os
import bpy, bmesh
import sys
import re
import subprocess
import fnmatch
import math
from math import cos, sin, radians
from mathutils import Vector, kdtree
import functools
from pathlib import Path
from io import StringIO
from bpy.props import StringProperty, BoolProperty, PointerProperty, IntProperty
from bpy.types import PropertyGroup, Panel, Scene, Operator
from bpy.utils import register_class, unregister_class
bl_info = {
"name" : "SeaDogs GM Ship Assemble, Export and other",
"author" : "Tosyk, Wazar",
"version" : (2, 2, 0),
"blender" : (3, 6, 0),
"location" : "View3d > Tool",
"warning" : "",
"wiki_url" : "",
"category" : "Import",
}
# ------------------------------------------------------------------------
# Scene Properties
# ------------------------------------------------------------------------
class MyProperties(PropertyGroup):
clear_scn_bool : BoolProperty(
name="Clear Scene before import new",
description="Clear Scene before import new",
default = True
)
sail_tex_def_str : StringProperty(
name="Sail texture",
description="Type default sail texture name (parus_common.tga).\nScript will look for it inside specified Texture folder",
default="parus_common.tga"
)
flag_tex_def_str : StringProperty(
name="Flag texture",
description="Type default flag texture name (parus_common.tga).\nScript will look for it inside specified Texture folder",
default="flagall.tga"
)
rope_tex_def_str : StringProperty(
name="Rope texture",
description="Type default rope texture name (rope.tga).\nScript will look for it inside specified Texture folder.\nSould be vertical texture",
default="rope.tga"
)
rope_type_int : IntProperty(
name = "Set rope type",
description="Set rope type.\nType 1: vertical texture.\nType 2: horizontal texture",
default = 1,
min = 1,
max = 2
)
flag_type_int : IntProperty(
name = "Set flag type",
description="Set flag type.\nType 1: old flag texture, low quality.\nType 2: new flag texture, high quality",
default = 1,
min = 1,
max = 2
)
flag_num_int : IntProperty(
name = "Set flag number",
description="Set flag number.\nChoose number of flag from texture",
default = 1,
min = 1,
max = 10
)
imp_ship_bool : BoolProperty(
name="Import ship geometry",
description="Import ship geometry",
default = True
)
load_multiple_coll_bool : BoolProperty(
name="Load to multiple collections",
description="Load to multiple collections for exporting",
default = False
)
gen_vants_bool : BoolProperty(
name="Generate vant(s) by given empties coordinates.",
description="Generate vant(s) by given empties coordinates.",
default = False
)
gen_rig_bool : BoolProperty(
name="Generate rig ropes by given empties coordinates.",
description="Generate rig ropes by given empties coordinates.",
default = False
)
gen_sails_bool : BoolProperty(
name="Generate sail plains by given empties coordinates.",
description="Generate sail plains by given empties coordinates.",
default = False
)
gen_flag_bool : BoolProperty(
name="Generate sail plains by given empties coordinates.",
description="Generate sail plains by given empties coordinates.",
default = False
)
gen_penn_bool : BoolProperty(
name="Generate sail plains by given empties coordinates.",
description="Generate sail plains by given empties coordinates.",
default = False
)
cloth_sail_bool : BoolProperty(
name="Apply cloth modifier to sail plains.",
description="Apply cloth modifier to sail plains.",
default = False
)
anim_sail_bool : BoolProperty(
name="Animate sail plains with Wind force.",
description="Animate sail plains with Wind force.",
default = False
)
ship_path : StringProperty(
name = "",
description="Choose a Ships directory:",
default="",
maxlen=1024,
subtype='DIR_PATH'
)
texs_path : StringProperty(
name = "",
description="Choose a Texture directory:",
default="",
maxlen=1024,
subtype='DIR_PATH'
)
hull_num_int : IntProperty(
name = "Set Hull Number",
description="Set Hull Number.\nYou can specify the number or not - script will handle anything",
default = 1,
min = 1,
max = 64
)
sail_quality_int : IntProperty(
name = "Set sail/flag subdivision",
description="Set sail/flag subdivision (8 - optimal)",
default = 4,
min = 0,
max = 10
)
#export
export_ship_path : StringProperty(
name = "",
description="Choose a export directory:",
default="",
maxlen=1024,
subtype='DIR_PATH'
)
export_triangulate: BoolProperty(
name="triangulate",
default=True,
)
export_smooth_out_normals: BoolProperty(
name="Smooth all normals (experimental)",
default=False,
)
export_smooth_out_normals_marked: BoolProperty(
name="Smooth marked normals (experimental)",
default=False,
)
export_prepare_uv: BoolProperty(
name="Prepare UV (experimental)",
default=False,
)
export_set_bsp_flag: BoolProperty(
name="Set BSP flag (experimental)",
default=False,
)
export_generate_bsp: BoolProperty(
name="Generate BSP (experimental)",
default=False,
)
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 find_principled_node(mtl):
principled_node = None
for node in mtl.node_tree.nodes:
if node.type == 'BSDF_PRINCIPLED':
principled_node = node
break
return principled_node
def find_specular_input(bsdf):
specular_input = None
for i, o in enumerate(bsdf.inputs):
if o.name == 'Specular IOR Level':
specular_input = o
return specular_input
def remove_blender_name_postfix(name):
return re.sub(r'\.\d{3}', '', name)
def get_root_for_collection(coll):
root_objects = [o for o in coll.objects if o.parent is None]
if len(root_objects) != 1:
raise TypeError('Wrong collenction "{}". Expect 1 child, found: {}'.format(coll.name, len(root_objects)))
return root_objects[0]
# ------------------------------------------------------------------------
# Operators
# ------------------------------------------------------------------------
class ImpSEShip_Button(Operator):
bl_label = "Build the ship"
bl_idname = "impseship.build_ship"
def execute(self, context):
#c = bpy.context
#ob = bpy.ops.object
#objects = bpy.data.objects
#scene = c.scene
mytool = bpy.context.scene.my_tool
import_and_assemble_ship(context, self.report)
return {'FINISHED'}
class ImpSEShip_ExportButton(Operator):
bl_label = "Export the ship"
bl_idname = "impseship.export_ship"
def execute(self, context):
#c = bpy.context
#ob = bpy.ops.object
#objects = bpy.data.objects
#scene = c.scene
mytool = bpy.context.scene.my_tool
export_ship(context, self.report)
return {'FINISHED'}
class ImpSEShip_MarkSkipBSP(Operator):
bl_label = "Mark to skip bsp"
bl_idname = "impseship.mark_skip_bsp"
def execute(self, context):
root_object = bpy.context.view_layer.objects.active
if (remove_blender_name_postfix(root_object.name) != 'root' or root_object.type != 'EMPTY'):
self.report({'ERROR'}, 'Root of model should be selected')
return {'CANCELLED'}
root_object['SkipBSP'] = True
return {'FINISHED'}
class ImpSEShip_UnmarkSkipBSP(Operator):
bl_label = "Unmark to skip bsp"
bl_idname = "impseship.unmark_skip_bsp"
def execute(self, context):
root_object = bpy.context.view_layer.objects.active
if (remove_blender_name_postfix(root_object.name) != 'root' or root_object.type != 'EMPTY'):
self.report({'ERROR'}, 'Root of model should be selected')
return {'CANCELLED'}
root_object['SkipBSP'] = False
return {'FINISHED'}
# ------------------------------------------------------------------------
# Panel in Object Mode
# ------------------------------------------------------------------------
class MAIN_PT_ImpSEShip:
#bl_label = "Import & Assemble Ship"
#bl_idname = "MAIN_PT_ImpSEShip"
bl_space_type = "VIEW_3D"
bl_region_type = "UI"
bl_category = "Import GM Ship"
#bl_context = "objectmode"
#bl_options = {'HIDE_HEADER'}
class SETUP_PT_ImpSEShip(MAIN_PT_ImpSEShip, Panel):
bl_label = "Import & Assemble Ship"
bl_idname = "SETUP_PT_ImpSEShip"
bl_icon = {'TOOL_SETTINGS'}
def draw_header(self, context):
# Example property to display a checkbox, can be anything
self.layout.label(text="", icon="MOD_OCEAN")
def draw(self, context):
layout = self.layout
scene = context.scene
mytool = scene.my_tool
row = layout.row()
layout.prop(mytool, "clear_scn_bool", text="Clear Scene First")
row = layout.row()
row.label(text = "Path and texture settings:", icon = 'TOOL_SETTINGS')
# display the properties
col = layout.column(align=True)
col.label(text = "Ship folder:")
col.prop(mytool, "ship_path", text="")
layout.row().separator()
box = layout.box()
row = box.row()
colT = row.column(align=False)
colT.label(text = "Texture folder:")
colT.prop(mytool, "texs_path", text="")
colT.label(text = "Sail texture name:")
colT.prop(mytool, "sail_tex_def_str", text="")
colT.label(text = "Rope texture name:")
colT.prop(mytool, "rope_tex_def_str", text="")
colT.prop(mytool, "rope_type_int", text="Rope Texture Vertical/Horizontal")
colT.label(text = "Flag texture name:")
colT.prop(mytool, "flag_tex_def_str", text="")
colT.prop(mytool, "flag_type_int", text="Flag Texture Type")
colT.prop(mytool, "flag_num_int", text="Flag Number on a Texture")
colT.prop(mytool, "hull_num_int", text="Ship Hull Texture Number")
layout.row().separator()
row = layout.row()
row.label(text = "Main settings:", icon = 'MOD_TINT')
layout.prop(mytool, "imp_ship_bool", text="Import Ship (*.gm files)")
box1 = layout.box()
row1 = box1.row()
colM = row1.column(align=False)
colM.prop(mytool, "load_multiple_coll_bool", text="Load to multiple collections")
colM.prop(mytool, "gen_rig_bool", text="Generate Rig (blender math)")
colM.prop(mytool, "gen_vants_bool", text="Generate Vants (blender math)")
colM.prop(mytool, "gen_sails_bool", text="Generate Sails (blender math)")
colM.prop(mytool, "gen_flag_bool", text="Generate Flags (blender math)")
colM.prop(mytool, "gen_penn_bool", text="Generate Pennants (blender math)")
colM.prop(mytool, "sail_quality_int", text="Sail/Flag Cloth Subdivision")
colM.prop(mytool, "cloth_sail_bool", text="Clothing Sails (Cloth modifier)")
colM.prop(mytool, "anim_sail_bool", text="Animate Sails (Blender physics)")
#layout.prop(mytool, "my_float", text="Float Property")
row = layout.row()
row.scale_y = 2.0
row.operator("impseship.build_ship")
layout.row().separator()
col = layout.column(align=True)
col.label(text = "Export folder:")
col.prop(mytool, "export_ship_path", text="")
box1 = layout.box()
row1 = box1.row()
colM = row1.column(align=False)
colM.prop(mytool, "export_triangulate", text="triangulate")
colM.prop(mytool, "export_smooth_out_normals", text="Smooth all normals (experimental)")
colM.prop(mytool, "export_smooth_out_normals_marked", text="Smooth marked normals (experimental)")
colM.prop(mytool, "export_prepare_uv", text="Prepare UV (experimental)")
colM.prop(mytool, "export_set_bsp_flag", text="Set BSP flag (experimental)")
colM.prop(mytool, "export_generate_bsp", text="Generate BSP (experimental)")
row = layout.row()
row.scale_y = 2.0
row.operator("impseship.export_ship")
row = layout.row()
row.operator("impseship.check_ship")
layout.row().separator()
row = layout.row()
colL = row.column(align=False)
colR = row.column(align=False)
colL.operator("impseship.mark_skip_bsp")
colL.operator("impseship.mark_smooth_normals")
colR.operator("impseship.unmark_skip_bsp")
colR.operator("impseship.unmark_smooth_normals")
row = layout.row()
row.operator("impseship.select_smoothed_normals")
# -----------------------------------------------------------
# Set variables
# -----------------------------------------------------------
"""
c = bpy.context
ob = bpy.ops.object
objects = bpy.data.objects
scene = c.scene
curves = bpy.data.curves
"""
# -----------------------------------------------------------
# Settings
# -----------------------------------------------------------
#import_ship = 'false' # import ship basic geometry or not
#generate_rig = 'false' # generate rig and ropes or not
#sail_quality = 0 # sail object quality, subdivision value
#gen_sails_bool = 'false' # should sail objects to be created or not
#cloth_sail_bool = 'false' # should cloth modifier to be added to the sail objects or not
#anim_sail_bool = 'false' # should sail objects to be animated or not
wind_dir = 'l' # wind direction (left(l), right(r) or center(c))
# ===========================================================
# Function: remove all from scene
# ===========================================================
def clear_scene():
for c in bpy.context.scene.collection.children:
bpy.context.scene.collection.children.unlink(c)
bpy.ops.object.select_all(action='SELECT')
bpy.ops.object.delete(use_global=False)
for c in bpy.data.collections:
if not c.users:
bpy.data.collections.remove(c)
bpy.ops.outliner.orphans_purge()
bpy.ops.outliner.orphans_purge()
bpy.ops.outliner.orphans_purge()
bpy.ops.outliner.orphans_purge()
bpy.ops.outliner.orphans_purge()
# ===========================================================
# Function: remove redundant collection
# ===========================================================
def rem_default_coll():
name = "Collection"
remove_collection_objects = True
#coll = c.collection #
coll = bpy.data.collections.get(name)
if coll:
if remove_collection_objects:
obs = [o for o in coll.objects if o.users == 1]
while obs:
bpy.data.objects.remove(obs.pop())
bpy.data.collections.remove(coll)
# ===========================================================
# Function: create tube curve for the rope
# ===========================================================
def make_tubes(context, obj, rig_obj_name, ship_name, length, bevel_depth=1.026, resolution=1):
my_tool = context.scene.my_tool
mesh = obj.data
curves = bpy.data.curves
curve_name = rig_obj_name
rope_type_int = my_tool.rope_type_int
hull_num_int = my_tool.hull_num_int
rope_tex_def_str = my_tool.rope_tex_def_str
texs_path = my_tool.texs_path
# -----------------------------------------------------------
# Create new cylinder
# -----------------------------------------------------------
# if exists, pick up else generate a new one
cu = curves.get(curve_name + '_mesh', curves.new(name=curve_name, type='CURVE'))
cu.dimensions = '3D'
cu.fill_mode = 'FULL'
cu.bevel_depth = bevel_depth
cu.bevel_resolution = resolution
cu_obj = bpy.data.objects.get(curve_name, bpy.data.objects.new(curve_name, cu))
# break down existing splines entirely.
if cu.splines:
cu.splines.clear()
# and rebuild
verts = mesh.vertices
for e in mesh.edges:
idx_v1, idx_v2 = e.vertices
v0, v1 = verts[idx_v1].co, verts[idx_v2].co
full_flat = [v0[0], v0[1], v0[2], 0.0, v1[0], v1[1], v1[2], 0.0]
# each spline has a default first coordinate but we need two.
segment = cu.splines.new('POLY')
segment.points.add(1)
segment.points.foreach_set('co', full_flat)
if not curve_name in bpy.context.scene.objects:
bpy.context.collection.objects.link(cu_obj)
# -----------------------------------------------------------
# Edit new cylinder UVs
# -----------------------------------------------------------
root_ob = bpy.context.scene.objects[curve_name] # Get the object
bpy.ops.object.select_all(action='DESELECT') # Deselect all objects
bpy.context.view_layer.objects.active = root_ob # Make the cube the active object
root_ob.select_set(True)
bpy.ops.object.convert(target='MESH')
o_uv = bpy.data.objects[curve_name]
for uvmap in o_uv.data.uv_layers : uvmap.name = 'UVMap'
uvMap = o_uv.data.uv_layers['UVMap']
# Rotate UV
rad = (radians(-90)) if rope_type_int == 1 else (radians(0))
anchor = (0.5, 0.5)
rot = make_rotation_transformation(rad, anchor)
for v in o_uv.data.loops :
uvMap.data[v.index].uv = rot(uvMap.data[v.index].uv )
# Scale UV
pivot = Vector( (0, 0) )
scale = Vector( (1, 1*length) ) if rope_type_int == 1 else (Vector( (1*length*2, 1) ))
ScaleUV( uvMap, scale, pivot )
# -----------------------------------------------------------
# Create material
# -----------------------------------------------------------
# Look for sail and flag textures if not found create default
texture_path_found = None
if rope_tex_def_str is not None:
# Set texture
mat_name = ship_name + '_Rope_Defaul_Mat'
texture_file = rope_tex_def_str
for ship_dir in Path(texs_path).rglob(f'**/{ship_name}'):
for hull_dir in ([f'hull{hull_num_int}',] if hull_num_int is not None else []) + ['hull1']:
if (ship_dir/hull_dir).exists() and (ship_dir/hull_dir/texture_file).exists():
texture_path_found = ship_dir/hull_dir/texture_file
break
if texture_path_found is not None:
break
if texture_path_found is None:
for ship_dir in Path(texs_path).rglob(f'**/{ship_name}'):
for tex_file in ship_dir.rglob(f'**/{texture_file}'):
texture_path_found = tex_file
break
if texture_path_found is not None:
break
if texture_path_found is None:
for ship_dir in Path(texs_path).rglob(f'**/{texture_file}'):
texture_path_found = ship_dir
break
texture_path_found = texture_path_found or os.path.join(texs_path, texture_file)
texture_path = str(texture_path_found)
print(curve_name, 'use this texture:', texture_path)
ac_ob = bpy.context.active_object
# Get material
mat = bpy.data.materials.get(mat_name)
if mat is None:
# create material
mat = bpy.data.materials.new(name = mat_name)
mat.use_nodes = True
mat.blend_method = 'CLIP'
bsdf = find_principled_node(mat)
if bsdf is None:
raise TypeError("No Principled BSDF node found in the material")
spec = find_specular_input(bsdf)
if spec is None:
raise TypeError("No Specular IOR Level input found in the material.")
spec.default_value = 0.0
texImage = mat.node_tree.nodes.new('ShaderNodeTexImage')
if texture_file in bpy.data.images:
texImage.image = bpy.data.images[texture_file]
else:
if os.path.isfile(texture_path):
texImage.image = bpy.data.images.load(texture_path)
else:
placeholder_image = bpy.data.images.new(texture_file, width=1, height=1)
placeholder_image.pixels = [0.5,0.5,0.5,1]
texImage.image = placeholder_image
mat.node_tree.links.new(bsdf.inputs['Base Color'], texImage.outputs['Color'])
mat.node_tree.links.new(bsdf.inputs['Alpha'], texImage.outputs['Alpha'])
# Assign it to object
if ac_ob.data.materials:
# assign to 1st material slot
ac_ob.data.materials[0] = mat
else:
# no slots
ac_ob.data.materials.append(mat)
def found_new_collection(coll_set, name_pattern):
result = None
for c in bpy.data.collections:
if c.name not in coll_set and remove_blender_name_postfix(c.name) == name_pattern:
result = c
break
return result
# ===========================================================
# Function: import ship parts from gm files
# ===========================================================
def is_locator_match(obj, name):
return (obj.type == 'EMPTY' and
remove_blender_name_postfix(obj.name).lower() == name.lower() and
obj.parent is not None and
remove_blender_name_postfix(obj.parent.name).lower() == 'geometry'
)
def find_the_same_name_objects(loc_name, obj_name):
return [o for o in bpy.context.scene.objects if o.name != loc_name and remove_blender_name_postfix(o.name).lower() == obj_name.lower()]
def find_children_geometry(obj, report):
geometry_locator = None
children = []
for o in obj.children:
if o.type == 'EMPTY' and remove_blender_name_postfix(o.name).lower() == 'geometry':
if geometry_locator is None:
geometry_locator = o
else:
report({'ERROR'}, 'multiple geometry object "{}" and "{}"'.format(geometry_locator.name, o.name))
return children
if geometry_locator is None:
return children
children = geometry_locator.children[:]
return children
def import_objects(o, obj_name, file, ship_name, my_tool, report):
load_multiple_coll_bool = my_tool.load_multiple_coll_bool
hull_num_int = my_tool.hull_num_int
texs_path = my_tool.texs_path
ship_path = my_tool.ship_path
d = ship_path
file_name = ship_name + '_' + obj_name
coll_set = set()
for c in bpy.data.collections:
coll_set.add(c.name)
children = []
print(obj_name, 'object found')
locator_name = o.name
#import_gm(bpy.context, hull_num_int, file_path = file, textures_path = texs_path, report_func = report)
with CapturingInfo(report) as _:
getattr(bpy.ops, 'import').gm(filepath = file, textures_path = texs_path, hull_num_int = hull_num_int)
coll_source = found_new_collection(coll_set, file_name)
print('coll_source name: "{}"'.format(coll_source.name))
root_source = get_root_for_collection(coll_source)
children = find_children_geometry(root_source, report)
root_name = root_source.name
print('root name: "{}"'.format(root_name))
# -----------------------------------------------------------
# Set selected objects from imported objects to a proper
# collection
# -----------------------------------------------------------
if not load_multiple_coll_bool:
# Set target collection to a known collection
coll_target = bpy.context.scene.collection.children.get(ship_name)
#select root and then its childrens
root_ob = bpy.context.scene.objects[root_name] # Get the object
bpy.ops.object.select_all(action='DESELECT') # Deselect all objects
bpy.context.view_layer.objects.active = root_ob # Make the cube the active object
root_ob.select_set(True)
bpy.ops.object.select_grouped(type='CHILDREN_RECURSIVE')
# List of object references
objs = bpy.context.selected_objects
# If target found and object list not empty
if coll_target and objs:
# Loop through all objects
for o in objs:
# Loop through all collections the obj is linked to
for coll in o.users_collection:
# Unlink the object
coll.objects.unlink(o)
# Link each object to the target collection
coll_target.objects.link(o)
# -----------------------------------------------------------
# Reposition imported object to a proper dummy
# -----------------------------------------------------------
target = bpy.data.objects[locator_name]
source = bpy.data.objects[root_name]
source.location += target.matrix_world.translation - source.matrix_world.translation
if not load_multiple_coll_bool:
# -----------------------------------------------------------
# Reparent imported object to a proper dummy
# -----------------------------------------------------------
parn = bpy.data.objects[locator_name]
chld = bpy.data.objects[root_name].children
bpy.ops.object.select_all(action='DESELECT')
for c in chld:
c.select_set(True)
bpy.ops.object.parent_clear(type='CLEAR_KEEP_TRANSFORM')
bpy.ops.object.select_all(action='DESELECT')
for c in chld:
c.select_set(True)
parn.select_set(True)
bpy.context.view_layer.objects.active = parn
bpy.ops.object.parent_set(type='OBJECT', keep_transform=True)
bpy.ops.object.select_all(action='DESELECT')
# -----------------------------------------------------------
# Remove redundant collection
# -----------------------------------------------------------
#deselect all
bpy.ops.object.select_all(action='DESELECT')
# Remove collection hierarchy
collection = bpy.data.collections.get(file_name)
for obj in collection.objects:
bpy.data.objects.remove(obj, do_unlink=True)
bpy.data.collections.remove(collection)
# -----------------------------------------------------------
# Rename internal dummy with same name to '*_rope'
# -----------------------------------------------------------
# Deselect all
bpy.ops.object.select_all(action='DESELECT')
# Rename object
rope_objects = find_the_same_name_objects(locator_name, obj_name)
if len(rope_objects):
for obj in rope_objects:
if obj.type == 'EMPTY' and len(obj.children) > 0:
obj.name = obj_name + '_ropes'
bpy.context.view_layer.update()
print('-------------------------------------------------------------------')
print('')
return children
def creating_rope(context, line_start, line_end, rope_num, rig_type, rig_dummy_name, ship_name, rig_obj_name, report):
# -----------------------------------------------------------
# Creating line between 2 points
# -----------------------------------------------------------
# Reference two cylinder objects
c1 = bpy.data.objects[line_start]
c2 = bpy.data.objects[line_end]
# Create new connector mesh and mesh object and link to scene
if rig_type == 'rope':
rig_obj_name = 'rope_' + rope_num
rope_width = 0.026
elif rig_type == 'fal':
rig_obj_name = 'fal_' + rope_num
rope_width = 0.026
elif rig_type == 'v_rope':
rope_width = 0.02
elif rig_type == 'stave':
rope_width = 0.02
# Calculate distance between 2 points to use for proper UV
length = math.dist(c1.matrix_world.translation, c2.matrix_world.translation)
#print(rig_obj_name, 'length:', length)
#print('Rope final name:', rig_obj_name)
#rig_obj_name_temp = 'EdgesObject'
m = bpy.data.meshes.new(rig_obj_name)
bm = bmesh.new()
v1 = bm.verts.new( c1.matrix_world.translation )
v2 = bm.verts.new( c2.matrix_world.translation )
e = bm.edges.new([v1,v2])
bm.to_mesh(m)
o = bpy.data.objects.new( rig_obj_name, m )
bpy.context.scene.collection.objects.link( o )
# Hook connector vertices to respective cylinders
for i, cyl in enumerate([ c1, c2 ]):
bpy.ops.object.select_all( action = 'DESELECT' )
cyl.select_set(True)
o.select_set(True)
bpy.context.view_layer.objects.active = o # Set connector as active
# Select vertex
bpy.ops.object.mode_set(mode='OBJECT')
o.data.vertices[i].select = True
bpy.ops.object.mode_set(mode='EDIT')
bpy.ops.object.hook_add_selob() # Hook to cylinder
bpy.ops.object.mode_set(mode='OBJECT')
o.data.vertices[i].select = False
# -----------------------------------------------------------
# Add modifiers to the rope V1
# -----------------------------------------------------------
"""
m = o.modifiers.new('Skin', 'SKIN')
for v in o.data.skin_vertices[0].data:
rad = 0.03
v.radius = rad, rad
# Make shading smooth
m.use_smooth_shade = True
# Add details to the rope, make it not rectangular
m = o.modifiers.new('Subsurf', 'SUBSURF' )
m.levels = 1
m.render_levels = 1
# Add simplifier modifier
m = o.modifiers.new('Decimate', 'DECIMATE' )
m.decimate_type = 'DISSOLVE'
m.angle_limit = 0.48 # arround 28 degree
bpy.ops.object.select_all( action = 'DESELECT' )
"""
# -----------------------------------------------------------
# Add modifiers to the rope V2
# -----------------------------------------------------------
b = bpy.data.objects[rig_obj_name]
b.name = rig_obj_name + '_temp'
make_tubes(context, b, rig_obj_name, ship_name, length, rope_width, 1)
bpy.data.objects.remove(b, do_unlink=True)
# -----------------------------------------------------------
# Parent rope to 'rig' dummy
# -----------------------------------------------------------
a = bpy.data.objects[rig_dummy_name]
b = bpy.data.objects[rig_obj_name]
b.parent = a
# -----------------------------------------------------------
# Add rope to ship collection
# -----------------------------------------------------------
# Set target collection to a known collection
coll_target = bpy.context.scene.collection.children.get(ship_name)
# Select rope
root_ob = bpy.context.scene.objects[rig_obj_name] # Get the object
bpy.ops.object.select_all(action='DESELECT') # Deselect all objects
bpy.context.view_layer.objects.active = root_ob # Make the cube the active object
root_ob.select_set(True)
# List of object references
objs = bpy.context.selected_objects
# If target found and object list not empty
if coll_target and objs:
# Loop through all objects
for o in objs:
# Loop through all collections the obj is linked to
for coll in o.users_collection:
# Unlink the object
coll.objects.unlink(o)
# Link each object to the target collection
coll_target.objects.link(o)
bpy.ops.object.select_all(action='DESELECT') # Deselect all objects
bpy.context.view_layer.update()
"""
# -----------------------------------------------------------
# Apply all modifiers
# -----------------------------------------------------------
#obj = bpy.data.objects['connector']
#obj.modifiers.remove(obj.modifiers.get('Skin.001'))
# pick any object
obj = bpy.data.objects['connector']
# set the object to active_object
c.view_layer.objects.active = obj
target_obj = c.active_object
for modifier in target_obj.modifiers:
bpy.ops.object.modifier_apply(modifier=modifier.name)
bpy.ops.object.mode_set(mode='EDIT')