-
Notifications
You must be signed in to change notification settings - Fork 3
/
__init__.py
1030 lines (809 loc) · 38.6 KB
/
__init__.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
bl_info = {
"name": "AutoMDL",
"author": "NvC_DmN_CH",
"version": (1, 0),
"blender": (4, 0, 0),
"location": "View3D > Sidebar > AutoMDL",
"description": "Compiles models for Source where the blend project file is",
"warning": "",
"wiki_url": "",
"category": "3D View"
}
import bpy
import os
import subprocess
import shutil
from pathlib import Path
import mathutils
import winreg
from bl_ui.generic_ui_list import draw_ui_list
import threading
from io import StringIO
game_select_method_is_dropdown = None
temp_path = bpy.app.tempdir
games_paths_list = []
game_path = None
steam_path = None
studiomdl_path = None
gameManualTextGameinfoPath = None
gameManualTextInputIsInvalid = False
massTextInputIsInvalid = False
visMeshInputIsInvalid = False
phyMeshInputIsInvalid = False
def defineGameSelectDropdown(self, context):
# game_select
game_select_items_enum = []
for i in range(len(games_paths_list)):
game_name = str(os.path.basename(os.path.dirname(games_paths_list[i])))
game_path = str(games_paths_list[i])
item = (game_path, game_name, "")
game_select_items_enum.append(item)
bpy.types.Scene.game_select = bpy.props.EnumProperty(
name = "Selected Option",
items = game_select_items_enum,
update = onGameDropdownChanged
)
def onGameDropdownChanged(self, context):
pass
def onMassTextInputChanged(self, context):
global massTextInputIsInvalid
massTextInputIsInvalid = not is_float(context.scene.mass_text_input)
def onGameManualTextInputChanged(self, context):
global gameManualTextInputIsInvalid
gameManualTextInputIsInvalid = False
in_folder = str(Path(os.path.join(context.scene.studiomdl_manual_input, ''))) # make sure to have a trailing slash, and its a string
subdir_studiomdl = os.path.join(in_folder, "studiomdl.exe")
has_studiomdl = os.path.exists( subdir_studiomdl )
if not has_studiomdl:
gameManualTextInputIsInvalid = True
print("ERROR: Couldn't find studiomdl.exe in specified folder")
return
base_path = Path(os.path.dirname(in_folder))
gameinfo_path = None
# oh no, code copy pasted from getGamesList()
# anyway
#
# although we need the path to the folder which contains the gameinfo
# so we need to iterate now again
_subdirectories = [x for x in base_path.iterdir() if x.is_dir()]
for k in range(len(_subdirectories)):
_subdir = _subdirectories[k]
has_gameinfo = os.path.exists( os.path.join(_subdir, "gameinfo.txt") )
# currently we're returning the first folder which has a gameinfo.txt, in alot of games there are multiple folders which match this criteria. todo: is this an issue?
if( has_gameinfo ):
gameinfo_path = str(_subdir)
break
if gameinfo_path == None:
gameManualTextInputIsInvalid = True
print("ERROR: Couldn't find gameinfo.txt in game")
return
gameManualTextGameinfoPath = gameinfo_path
def setGamePath(self, context, new_game_path_value):
global game_path
global studiomdl_path
game_path = new_game_path_value
studiomdl_path = os.path.join(os.path.dirname(game_path), "bin", "studiomdl.exe")
# returns list of source games which have a studiomdl.exe in the bin folder
def getGamesList():
global steam_path
common = Path(os.path.join(steam_path, r"steamapps/common"))
# get all subdirectories in common
subdirectories = [x for x in common.iterdir() if x.is_dir()]
# okay let's filter games
list = []
for i in range(len(subdirectories)):
subdir = subdirectories[i]
subdir_bin = os.path.join(subdir, "bin")
has_bin_folder = os.path.exists( subdir_bin )
if( not has_bin_folder ):
continue
subdir_studiomdl = os.path.join(subdir_bin, "studiomdl.exe")
has_studiomdl = os.path.exists( subdir_studiomdl )
if( not has_studiomdl ):
continue
# okay!
# although we need the path to the folder which contains the gameinfo
# so we need to iterate now again
_subdirectories = [x for x in subdir.iterdir() if x.is_dir()]
for k in range(len(_subdirectories)):
_subdir = _subdirectories[k]
has_gameinfo = os.path.exists( os.path.join(_subdir, "gameinfo.txt") )
# currently we're returning the first folder which has a gameinfo.txt, in alot of games there are multiple folders which match this criteria. todo: is this an issue?
if( has_gameinfo ):
list.append(_subdir)
break
return list
# attempt to figure out where steam is installed
def getSteamInstallationPath():
# windows specific attempts
if(os.name == 'nt'):
# check in registry (x86)
try:
with winreg.OpenKey(winreg.HKEY_CURRENT_USER, r"SOFTWARE\Valve\Steam") as key:
return winreg.QueryValueEx(key, "SteamPath")[0]
except Exception as e:
print(e)
# check in registry (x64)
try:
with winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, r"SOFTWARE\WOW6432Node\Valve\Steam") as key:
return winreg.QueryValueEx(key, "InstallPath")[0]
except Exception as e:
print(e)
# todo: linux specific attempts?
return None
def refreshGameSelectDropdown(self, context):
del bpy.types.Scene.game_select
defineGameSelectDropdown(None, context)
class AutoMDLOperator(bpy.types.Operator):
bl_idname = "wm.automdl"
bl_label = "Update MDL"
bl_description = "Compile model"
def execute(self, context):
if game_select_method_is_dropdown:
setGamePath(self, context, context.scene.game_select)
else:
setGamePath(self, context, gameManualTextGameinfoPath)
blend_path = bpy.data.filepath
# check if we have saved a blend file in the first place
if (len(blend_path) == 0):
self.report({'ERROR'}, "Please save the project inside a models folder")
return {'CANCELLED'}
has_collision = False
phy_mesh_obj = context.scene.phy_mesh
if phy_mesh_obj and phy_mesh_obj.name in bpy.data.objects:
has_collision = True
vis_mesh_valid = checkVisMeshHasMesh(context)
phy_mesh_valid = checkPhyMeshHasMesh(context)
# check if meshes aren't even meshes
if (not vis_mesh_valid):
self.report({'ERROR'}, "Please select a mesh for Visual mesh")
return {'CANCELLED'}
if (not phy_mesh_valid) and has_collision == True:
self.report({'ERROR'}, "Please select a mesh for Collision mesh")
return {'CANCELLED'}
# check if visual mesh and collision mesh point to valid objects in the scene
if (context.scene.vis_mesh != None) and context.scene.vis_mesh.name not in bpy.context.scene.objects:
self.report({'ERROR'}, "Visual mesh points to a deleted object!")
visMeshInputIsInvalid = True
vis_mesh_valid = False
return {'CANCELLED'}
if (context.scene.phy_mesh != None) and context.scene.phy_mesh.name not in bpy.context.scene.objects:
self.report({'ERROR'}, "Collision mesh points to a deleted object!")
phyMeshInputIsInvalid = True
phy_mesh_valid = False
return {'CANCELLED'}
mesh_ext = "smd"
qc_path = os.path.join(temp_path, "qc.qc")
qc_modelpath = to_models_relative_path(blend_path)
if(qc_modelpath is None):
self.report({'ERROR'}, "Please save the project inside a models folder")
return {'CANCELLED'}
qc_vismesh = os.path.basename(qc_modelpath) + "_ref"
qc_phymesh = os.path.basename(qc_modelpath) + "_phy"
qc_staticprop = context.scene.staticprop
qc_mass = context.scene.mass_text_input if not qc_staticprop else 1
if not is_float(qc_mass):
self.report({'ERROR'}, "Mass is invalid")
return {'CANCELLED'}
# wait do we need this check? shouldn't it be compared with None instead
if(qc_modelpath == -1):
self.report({'ERROR'}, "blend file must be inside a models folder")
return {'CANCELLED'}
# export smd
self.exportObjectToSmd(context.scene.vis_mesh, os.path.join(temp_path, qc_vismesh), False)
if(has_collision):
self.exportObjectToSmd(context.scene.phy_mesh, os.path.join(temp_path, qc_phymesh), True)
# set up qc
convex_pieces = 0
if has_collision:
convex_pieces = CountIslands(phy_mesh_obj)
qc_surfaceprop = context.scene.surfaceprop
qc_cdmaterials_list = []
has_materials = context.scene.vis_mesh.material_slots
if has_materials:
if context.scene.cdmaterials_type == '1':
# manual
for i in range(len(context.scene.cdmaterials_list)):
str = context.scene.cdmaterials_list[i].name
str = os.path.join(str, '', '').replace("\\", "/")
qc_cdmaterials_list.append(str)
else:
# auto
str = "models/" + os.path.dirname(qc_modelpath)
qc_cdmaterials_list.append(str)
qc_concave = convex_pieces > 1
qc_maxconvexpieces = convex_pieces
qc_mostlyopaque = context.scene.mostlyopaque
qc_inertia = 1
qc_damping = 0
qc_rotdamping = 0
#self.report({'ERROR'}, f"qc_maxconvexpieces: {qc_maxconvexpieces}") # debug
# write qc
with open(qc_path, "w") as file:
file.write(f"$modelname \"{qc_modelpath}.mdl\"\n")
file.write("\n")
file.write(f"$bodygroup \"Body\"\n{{\n\tstudio \"{qc_vismesh}.{mesh_ext}\"\n}}\n")
if(qc_staticprop):
file.write("\n")
file.write(f"$staticprop")
file.write("\n")
if(qc_mostlyopaque):
file.write("\n")
file.write(f"$mostlyopaque")
file.write("\n")
file.write("\n")
file.write(f"$surfaceprop \"{qc_surfaceprop}\"\n")
file.write("\n")
file.write("$contents \"solid\"\n")
file.write("\n")
for i in range(len(qc_cdmaterials_list)):
str = qc_cdmaterials_list[i]
file.write(f"$cdmaterials \"{str}\"\n")
if not has_materials:
file.write(f"$cdmaterials \"\"\n")
file.write("\n")
file.write(f"$sequence \"idle\" {{\n\t\"{qc_vismesh}.{mesh_ext}\"\n\tfps 30\n\tfadein 0.2\n\tfadeout 0.2\n\tloop\n}}\n")
file.write("\n")
if(has_collision == True):
str = f"$collisionmodel \"{qc_phymesh}.{mesh_ext}\" {{"
str += f"\n\t$concave\n\t$maxconvexpieces {qc_maxconvexpieces}" if qc_concave else ""
str += f"\n\t$mass {qc_mass}\n\t$inertia {qc_inertia}\n\t$damping {qc_damping}\n\t$rotdamping {qc_rotdamping}"
str += f"\n\t$rootbone \" \""
str += f"\n}}"
file.write(str)
# end of writing qc
# compile qc!
studiomdl_quiet = True
studiomdl_fastbuild = False # doesn't seem to have an effect
studiomdl_nowarnings = True
studiomdl_nox360 = True
studiomdl_args = [studiomdl_path, "-game", game_path, "-nop4"]
if(studiomdl_quiet):
studiomdl_args.append("-quiet")
if(studiomdl_fastbuild):
studiomdl_args.append("-fastbuild")
if(studiomdl_nowarnings):
studiomdl_args.append("-nowarnings")
if(studiomdl_nox360):
studiomdl_args.append("-nox360")
studiomdl_args.append(qc_path) # qc needs to be the last argument
#print(studiomdl_args)
subprocess.run(studiomdl_args)
# move compiled stuff
compile_path = os.path.join(game_path, "models", os.path.dirname(qc_modelpath))
move_path = os.path.dirname(blend_path)
compiled_model_name = Path(os.path.basename(qc_modelpath)).stem
compiled_exts = [".dx80.vtx", ".dx90.vtx", ".mdl", ".phy", ".sw.vtx", ".vvd"]
for i in range(len(compiled_exts)):
path_old = os.path.join(compile_path, compiled_model_name + compiled_exts[i])
path_new = os.path.join(move_path, compiled_model_name + compiled_exts[i])
if(os.path.isfile(path_old)):
shutil.move(path_old, path_new)
# delete folder in game if empty
if os.path.isdir(compile_path):
if(len(os.listdir(temp_path)) == 0):
os.rmdir(compile_path)
# delete temp folder contents
if False: # todo, important, notice: if we are going to not export everything everytime, we need to leave this off
for filename in os.listdir(temp_path):
file_path = os.path.join(temp_path, filename)
try:
if os.path.isfile(file_path):
os.remove(file_path)
elif os.path.isdir(file_path):
os.rmdir(file_path)
except Exception as e:
print(f"Error deleting {file_path}: {e}")
# create appropriate folders in materials
make_folders = bpy.context.preferences.addons[__package__].preferences.do_make_folders_for_cdmaterials
if has_materials and make_folders:
for i in range(len(qc_cdmaterials_list)):
entry = qc_cdmaterials_list[i]
root = os.path.dirname(get_models_path(blend_path))
fullpath = Path(os.path.join(root, "materials", entry).replace("\\", "/"))
try:
# make folder
os.mkdir(fullpath)
except:
pass
# only when "Same as MDL" option is selected:
# for each material in the visual mesh, make a VMT inside the folder
make_vmts = bpy.context.preferences.addons[__package__].preferences.do_make_vmts
if make_vmts:
if context.scene.cdmaterials_type == '0': # if "Same as MDL" is selected
# here qc_cdmaterials_list will contain only 1 item so we're good
for slot in context.scene.vis_mesh.material_slots:
vmt_path = os.path.join(fullpath, slot.name + '.vmt')
# don't override vmt if it already exists
if os.path.exists(vmt_path) is False:
with open(vmt_path, "w") as file:
vmt_basetexture = os.path.join(entry, "_PLACEHOLDER_").replace("\\", "/")
file.write(f"VertexLitGeneric\n{{\n\t$basetexture \"{vmt_basetexture}\"\n}}")
self.report({'INFO'}, f"If compile was successful, output should be in \"{os.path.join(move_path, '')}\"")
return {'FINISHED'}
def exportObjectToSmd(self, obj, path, is_collision_smd):
# switch to object mode
context_mode_snapshot = "null"
if bpy.context.mode != 'OBJECT':
context_mode_snapshot = bpy.context.active_object.mode
bpy.ops.object.mode_set(mode='OBJECT')
# todo: check if object obj exists?
# get mesh, apply modifiers
depsgraph = bpy.context.evaluated_depsgraph_get()
object_eval = obj.evaluated_get(depsgraph)
mesh = object_eval.to_mesh()
mesh.calc_loop_triangles()
# Apply object transform to the mesh vertices
mesh.transform(obj.matrix_world)
# write!
with open(path + ".smd", "w") as file:
# hardcoded but yea
file.write("version 1\nnodes\n0 \"root\" -1\nend\nskeleton\ntime 0\n0 0 0 0 0 0 0\nend\ntriangles\n")
sb = StringIO() # string builder
has_materials = len(obj.material_slots) > 0
# okay so now, i sacrifice everything that goes into making good code
# just to squeeze out some performance of out this
# because we REALLY do need the extra boost
# no need to check for every triangle whether or not its a collision smd or presence of materials
# so we check here and call the appropriate variant of the function
if is_collision_smd:
self.exportMeshToSmd_Collision(sb, mesh)
else:
if has_materials:
self.exportMeshToSmd_WithMaterials(sb, obj, mesh)
else:
self.exportMeshToSmd_NoMaterials(sb, mesh)
file.write(sb.getvalue())
file.write("end\n")
# switch mode back
if(context_mode_snapshot != "null"):
bpy.ops.object.mode_set(mode=context_mode_snapshot)
def exportMeshToSmd_Collision(self, sb, mesh):
for tri in mesh.loop_triangles:
material_name = "Phy"
# tri vertices
vert_a = mesh.vertices[tri.vertices[0]]
vert_b = mesh.vertices[tri.vertices[1]]
vert_c = mesh.vertices[tri.vertices[2]]
# tri positions
pos_a = vert_a.co
pos_b = vert_b.co
pos_c = vert_c.co
# tri normals (smooth shading)
normal_a = vert_a.normal
normal_b = vert_b.normal
normal_c = vert_c.normal
# tri uv coords
uv_a = mesh.uv_layers.active.data[tri.loops[0]].uv
uv_b = mesh.uv_layers.active.data[tri.loops[1]].uv
uv_c = mesh.uv_layers.active.data[tri.loops[2]].uv
sb.write(f"{material_name}\n0 {pos_a.x:.6f} {pos_a.y:.6f} {pos_a.z:.6f} {normal_a.x:.6f} {normal_a.y:.6f} {normal_a.z:.6f} {uv_a.x:.6f} {uv_a.y:.6f} 0\n0 {pos_b.x:.6f} {pos_b.y:.6f} {pos_b.z:.6f} {normal_b.x:.6f} {normal_b.y:.6f} {normal_b.z:.6f} {uv_b.x:.6f} {uv_b.y:.6f} 0\n0 {pos_c.x:.6f} {pos_c.y:.6f} {pos_c.z:.6f} {normal_c.x:.6f} {normal_c.y:.6f} {normal_c.z:.6f} {uv_c.x:.6f} {uv_c.y:.6f} 0\n")
def exportMeshToSmd_WithMaterials(self, sb, obj, mesh):
for tri in mesh.loop_triangles:
material_name = obj.material_slots[tri.material_index].name
# tri vertices
vert_a = mesh.vertices[tri.vertices[0]]
vert_b = mesh.vertices[tri.vertices[1]]
vert_c = mesh.vertices[tri.vertices[2]]
# tri positions
pos_a = vert_a.co
pos_b = vert_b.co
pos_c = vert_c.co
# tri normals
normal_a = vert_a.normal
normal_b = vert_b.normal
normal_c = vert_c.normal
if(tri.use_smooth == False):
normal = (pos_b - pos_a).cross(pos_c - pos_a).normalized()
normal_a = normal
normal_b = normal
normal_c = normal
# tri uv coords
uv_a = mesh.uv_layers.active.data[tri.loops[0]].uv
uv_b = mesh.uv_layers.active.data[tri.loops[1]].uv
uv_c = mesh.uv_layers.active.data[tri.loops[2]].uv
sb.write(f"{material_name}\n0 {pos_a.x:.6f} {pos_a.y:.6f} {pos_a.z:.6f} {normal_a.x:.6f} {normal_a.y:.6f} {normal_a.z:.6f} {uv_a.x:.6f} {uv_a.y:.6f} 0\n0 {pos_b.x:.6f} {pos_b.y:.6f} {pos_b.z:.6f} {normal_b.x:.6f} {normal_b.y:.6f} {normal_b.z:.6f} {uv_b.x:.6f} {uv_b.y:.6f} 0\n0 {pos_c.x:.6f} {pos_c.y:.6f} {pos_c.z:.6f} {normal_c.x:.6f} {normal_c.y:.6f} {normal_c.z:.6f} {uv_c.x:.6f} {uv_c.y:.6f} 0\n")
def exportMeshToSmd_NoMaterials(self, sb, mesh):
for tri in mesh.loop_triangles:
material_name = "None"
# tri vertices
vert_a = mesh.vertices[tri.vertices[0]]
vert_b = mesh.vertices[tri.vertices[1]]
vert_c = mesh.vertices[tri.vertices[2]]
# tri positions
pos_a = vert_a.co
pos_b = vert_b.co
pos_c = vert_c.co
# tri normals
normal_a = vert_a.normal
normal_b = vert_b.normal
normal_c = vert_c.normal
if(tri.use_smooth == False):
normal = (pos_b - pos_a).cross(pos_c - pos_a).normalized()
normal_a = normal
normal_b = normal
normal_c = normal
# tri uv coords
uv_a = mesh.uv_layers.active.data[tri.loops[0]].uv
uv_b = mesh.uv_layers.active.data[tri.loops[1]].uv
uv_c = mesh.uv_layers.active.data[tri.loops[2]].uv
sb.write(f"{material_name}\n0 {pos_a.x:.6f} {pos_a.y:.6f} {pos_a.z:.6f} {normal_a.x:.6f} {normal_a.y:.6f} {normal_a.z:.6f} {uv_a.x:.6f} {uv_a.y:.6f} 0\n0 {pos_b.x:.6f} {pos_b.y:.6f} {pos_b.z:.6f} {normal_b.x:.6f} {normal_b.y:.6f} {normal_b.z:.6f} {uv_b.x:.6f} {uv_b.y:.6f} 0\n0 {pos_c.x:.6f} {pos_c.y:.6f} {pos_c.z:.6f} {normal_c.x:.6f} {normal_c.y:.6f} {normal_c.z:.6f} {uv_c.x:.6f} {uv_c.y:.6f} 0\n")
class AutoMDLPanel(bpy.types.Panel):
bl_label = "AutoMDL"
bl_idname = "PT_AutoMDLPanel"
bl_space_type = 'VIEW_3D'
bl_region_type = 'UI'
bl_category = 'AutoMDL'
def draw(self, context):
layout = self.layout
vis_mesh_valid = checkVisMeshHasMesh(context)
phy_mesh_valid = checkPhyMeshHasMesh(context)
row = layout.row()
global steam_path
if(steam_path is not None):
row.label(text= "Choose compiler:")
row = layout.row()
row.prop(context.scene, "game_select", text="")
else:
row.label(text= "Directory containing studiomdl.exe:")
row = layout.row()
row.alert = gameManualTextInputIsInvalid
row.prop(context.scene, "studiomdl_manual_input")
row = layout.row()
row = layout.row()
row.enabled = vis_mesh_valid
row.operator("wm.automdl")
row = layout.row()
row = layout.row()
row.label(text= "Visual mesh:")
row.prop_search(context.scene, "vis_mesh", bpy.context.scene, "objects", text="")
row = layout.row()
row.label(text= "Collision mesh:")
row.prop_search(context.scene, "phy_mesh", bpy.context.scene, "objects", text="")
row = layout.row()
if vis_mesh_valid:
if phy_mesh_valid:
row = layout.row()
row.enabled = phy_mesh_valid
row.label(text= "Surface type:")
row.prop(context.scene, "surfaceprop", text="")
row = layout.row()
if( not context.scene.staticprop):
row.label(text= "Mass:")
row.alert = massTextInputIsInvalid
row.prop(context.scene, "mass_text_input")
else:
row.label(text= "No mass")
#row = layout.row()
#row.enabled = phy_mesh_valid
#row.prop(context.scene, "concave", text="Concave");
row = layout.row()
row.label(text= " ")
row = layout.row()
if vis_mesh_valid:
if context.scene.vis_mesh.material_slots:
row.label(text= "Path to VMT files will be:")
row = layout.row()
row.prop(context.scene, 'cdmaterials_type', expand=True)
row = layout.row()
if context.scene.cdmaterials_type == '0':
if len(bpy.data.filepath) != 0:
modelpath = to_models_relative_path(bpy.data.filepath)
if modelpath != None:
if vis_mesh_valid:
modelpath_dirname = os.path.dirname(modelpath)
for slot in context.scene.vis_mesh.material_slots:
row = layout.row()
row.label(text=os.path.join("materials/models/", modelpath_dirname, slot.name).replace("\\", "/") + ".vmt", icon='MATERIAL')
else:
row.label(text="Blend file is not inside a models folder", icon='ERROR')
else:
row.label(text="Blend file not saved", icon='ERROR')
else:
draw_ui_list(
layout,
context,
list_path="scene.cdmaterials_list",
active_index_path="scene.cdmaterials_list_active_index",
unique_id="cdmaterials_list_id",
)
else:
row.label(text="Visual mesh has no materials", icon='INFO')
row = layout.row()
row.label(text="")
row = layout.row()
row.label(text="General options:")
row = layout.row()
row.prop(context.scene, "mostlyopaque", text="Has Transparent Materials")
row = layout.row()
row.prop(context.scene, "staticprop", text="Static Prop")
# for cdmaterials list
class CdMaterialsPropGroup(bpy.types.PropertyGroup):
name: bpy.props.StringProperty()
class AddonPrefs(bpy.types.AddonPreferences):
bl_idname = __package__
do_make_folders_for_cdmaterials: bpy.props.BoolProperty(
name="Make Folders",
description="On compile, make the appropriate folders in the materials folder (make folders for each $cdmaterials)",
default=True
)
do_make_vmts: bpy.props.BoolProperty(
name="Make placeholder VMTs",
description="On compile, make placeholder VMT files named after the model's materials, placed inside appropriate folder inside the materials folder\nThis won't replace existing VMTs",
default=True
)
def draw(self, context):
layout = self.layout
row = layout.row()
row.prop(self, "do_make_folders_for_cdmaterials", text="Automatically make folders for materials locations")
row = layout.row()
row.enabled = self.do_make_folders_for_cdmaterials
row.prop(self, "do_make_vmts", text="Also make placeholder VMTs (Only when compiling with the \"Same as MDL\" option)")
classes = [
AutoMDLOperator,
AutoMDLPanel,
CdMaterialsPropGroup,
AddonPrefs
]
class_register, class_unregister = bpy.utils.register_classes_factory(classes)
def register():
from bpy.utils import register_class
for cls in classes:
register_class(cls)
# surfaceprop dropdown
bpy.types.Scene.surfaceprop_text_input = bpy.props.StringProperty(name="", default="")
# mass text input
bpy.types.Scene.mass_text_input = bpy.props.StringProperty(name="", default="35", description="Mass in kilograms (KG)\nBy default, the Player can +USE pick up 35KG max.\nThe gravgun can pick up 250KG max.\nThe portal gun can pick up 85KG max", update=onMassTextInputChanged)
# vis mesh
bpy.types.Scene.vis_mesh = bpy.props.PointerProperty(
type=bpy.types.Object,
name="Selected Object",
description="Select an object from the scene"
)
# col mesh
bpy.types.Scene.phy_mesh = bpy.props.PointerProperty(
type=bpy.types.Object,
name="Selected Object",
description="Select an object from the scene"
)
# surfaceprop
bpy.types.Scene.surfaceprop = bpy.props.EnumProperty(
name="Selected Option",
items = [
("Concrete", "Concrete", ""),
("Chainlink", "Chainlink", ""),
("Canister", "Canister", ""),
("Crowbar", "Crowbar", ""),
("Metal", "Metal", ""),
("Metalvent", "Metalvent", ""),
("Popcan", "Popcan", ""),
("Wood", "Wood", ""),
("Plaster", "Plaster", ""),
("Dirt", "Dirt", ""),
("Grass", "Grass", ""),
("Sand", "Sand", ""),
("Snow", "Snow", ""),
("Ice", "Ice", ""),
("Flesh", "Flesh", ""),
("Glass", "Glass", ""),
("Tile", "Tile", ""),
("Paper", "Paper", ""),
("Cardboard", "Cardboard", ""),
("Plastic_Box", "Plastic_Box", ""),
("Plastic_barrel", "Plastic_barrel", ""),
("Plastic", "Plastic", ""),
("Rubber", "Rubber", ""),
("Clay", "Clay", ""),
("Porcelain", "Porcelain", ""),
("Computer", "Computer", "")
]
)
# static prop
bpy.types.Scene.staticprop = bpy.props.BoolProperty(
name="Static Prop",
description="Enable if used as prop_static\n($staticprop in QC)",
default=False
)
# has transparency
bpy.types.Scene.mostlyopaque = bpy.props.BoolProperty(
name="Has Transparency",
description="Enabling this may fix sorting issues that come with using transparent materials. \nRenders model in 2 passes, one for opaque materials, and one for materials with transparency\n($mostlyopaque in QC)",
default=False
)
# radio buttons for choosing how to define cdmaterials
bpy.types.Scene.cdmaterials_type = bpy.props.EnumProperty(items =
(
('0','Same as MDL',''),
('1','Other','')
)
)
# cdmaterials list
bpy.types.Scene.cdmaterials_list = bpy.props.CollectionProperty(type=CdMaterialsPropGroup)
bpy.types.Scene.cdmaterials_list_active_index = bpy.props.IntProperty()
# steam path
global steam_path
global games_paths_list
global game_select_method_is_dropdown
steam_path = getSteamInstallationPath()
if(steam_path != None):
game_select_method_is_dropdown = True
steam_path = os.path.join(steam_path, "").replace("\\", "/")
games_paths_list = getGamesList()
defineGameSelectDropdown(None, bpy.context)
else:
game_select_method_is_dropdown = False
steam_path = None
bpy.types.Scene.studiomdl_manual_input = bpy.props.StringProperty(name="", default="", description="Path to the studiomdl.exe file", update=onGameManualTextInputChanged)
# call something after 1 second
bpy.app.timers.register(set_default_values, first_interval=1) # workaround for not being able to use context in register()
def set_default_values():
# set default of cdmaterials list
bpy.context.scene.cdmaterials_list.clear()
bpy.ops.uilist.entry_add(list_path="scene.cdmaterials_list", active_index_path="scene.cdmaterials_list_active_index")
bpy.context.scene.cdmaterials_list[0].name = "models/"
# we need to update the dropdown once to let the default value affect the rest of the program, as if we selected it manually
# before that let's select a default value for it
global game_select_method_is_dropdown
if game_select_method_is_dropdown:
# if certain games exist, select one of them instead of defaulting to selecting the game in the first option
chosen_game_path = None
recognized_game_path_gmod = None
recognized_game_path_hl2 = None
recognized_game_path_sdk = None
global games_paths_list
for i in range(len(games_paths_list)):
game_path = str(games_paths_list[i])
game_path_lowercase = game_path.lower()
# we're not checking for specific strings because from what i saw the names of the games aren't consistent across users
# like idk, i remember seeing "Half Life 2" as "Half-Life 2" and "Half Life: 2" which is weird but idk
# i may be wrong but, we do this for now and im actually happy with it
#
# checking smaller strings first for optimization (but not if its gonna be a very common string)
if "mod" in game_path_lowercase:
if "s" in game_path_lowercase:
if "garry" in game_path_lowercase:
# we are gonna assume its "GarrysMod" or something like that
recognized_game_path_gmod = game_path
continue
if "2" in game_path_lowercase:
if "half" in game_path_lowercase:
if "life" in game_path_lowercase:
# we are gonna assume its "Half-Life 2" or something like that (episodes, lost coast etc)
recognized_game_path_hl2 = game_path
continue
if "sdk" in game_path_lowercase:
if "2013" in game_path_lowercase:
# we are gonna assume its "Source SDK Base 2013 Singleplayer" or something like that
recognized_game_path_sdk = game_path
continue
# lets now define some sort of order so that we prefer some recognized games over others
# sdk > hl2 > gmod
if recognized_game_path_sdk is not None:
chosen_game_path = recognized_game_path_sdk
elif recognized_game_path_hl2 is not None:
chosen_game_path = recognized_game_path_hl2
elif recognized_game_path_gmod is not None:
chosen_game_path = recognized_game_path_gmod
# set value
if chosen_game_path != None:
bpy.context.scene.game_select = chosen_game_path
# update once to set up things ( i removed functionality there so not needed anymore )
onGameDropdownChanged(None, bpy.context)
else:
# update once to set up things
onGameManualTextInputChanged(None, bpy.context)
def unregister():
from bpy.utils import unregister_class
for cls in reversed(classes):
unregister_class(cls)
del bpy.types.Scene.surfaceprop_text_input
del bpy.types.Scene.vis_mesh
del bpy.types.Scene.phy_mesh
del bpy.types.Scene.surfaceprop
del bpy.types.Scene.staticprop
del bpy.types.Scene.mostlyopaque
del bpy.types.Scene.mass_text_input
if game_select_method_is_dropdown:
del bpy.types.Scene.game_select
else:
del bpy.types.Scene.studiomdl_manual_input
del bpy.types.Scene.cdmaterials_type
del bpy.types.Scene.cdmaterials_list
del bpy.types.Scene.cdmaterials_list_active_index
def checkVisMeshHasMesh(context):
vis_mesh_obj = context.scene.vis_mesh
return (vis_mesh_obj and vis_mesh_obj.type == 'MESH' and vis_mesh_obj.name in bpy.data.objects) == True
def checkPhyMeshHasMesh(context):
phy_mesh_obj = context.scene.phy_mesh
return (phy_mesh_obj and phy_mesh_obj.type == 'MESH' and phy_mesh_obj.name in bpy.data.objects) == True
def to_models_relative_path(file_path):
MODELS_FOLDER_NAME = "models"
# See if we can find a models folder up the chain
index = file_path.rfind(MODELS_FOLDER_NAME)
if index != -1:
root = file_path[:index + len(MODELS_FOLDER_NAME)]
else:
return None
return os.path.splitext(os.path.relpath(file_path, root))[0].replace("\\", "/")
def get_models_path(file_path):
MODELS_FOLDER_NAME = "models"
# See if we can find a models folder up the chain
index = file_path.rfind(MODELS_FOLDER_NAME)
if index != -1:
root = file_path[:index + len(MODELS_FOLDER_NAME)]
return root
return None
# lemon's answer in https://blender.stackexchange.com/questions/75332/how-to-find-the-number-of-loose-parts-with-blenders-python-api
# i would implement it myself but i haven't done much graph stuff, and speed is really needed right now, and first implementation would be slow. This here is an efficient alogrithm to count the number of loose parts inside a mesh
from collections import defaultdict
def MakeVertPaths( verts, edges ):
#Initialize the path with all vertices indexes
result = {v.index: set() for v in verts}
#Add the possible paths via edges
for e in edges:
result[e.vertices[0]].add(e.vertices[1])
result[e.vertices[1]].add(e.vertices[0])
return result
def FollowEdges( startingIndex, paths ):
current = [startingIndex]
follow = True
while follow:
#Get indexes that are still in the paths
eligible = set( [ind for ind in current if ind in paths] )
if len( eligible ) == 0:
follow = False #Stops if no more
else:
#Get the corresponding links
next = [paths[i] for i in eligible]
#Remove the previous from the paths
for key in eligible: paths.pop( key )
#Get the new links as new inputs
current = set( [ind for sub in next for ind in sub] )
def CountIslands( obj ):
#Prepare the paths/links from each vertex to others
paths = MakeVertPaths( obj.data.vertices, obj.data.edges )
found = True
n = 0
while found:
try:
#Get one input as long there is one
startingIndex = next( iter( paths.keys() ) )
n = n + 1
#Deplete the paths dictionary following this starting index
FollowEdges( startingIndex, paths )
except:
found = False
return n
def CountIslands2(obj):
mesh = obj.data
paths={v.index:set() for v in mesh.vertices}
for e in mesh.edges:
paths[e.vertices[0]].add(e.vertices[1])
paths[e.vertices[1]].add(e.vertices[0])
lparts=[]
while True: