-
Notifications
You must be signed in to change notification settings - Fork 0
/
__init__.py
2545 lines (2259 loc) · 93.7 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
import sys
import tempfile
import copy
import shutil
import bpy
import traceback
import os
from pathlib import Path
from .fast64_internal import *
import cProfile
import pstats
# info about add on
bl_info = {
"name": "Fast64 + METAL Composer JSON",
"category": "Object",
"blender": (2, 82, 0),
}
axis_enums = [
('X', 'X', 'X'),
('Y', 'Y', 'Y'),
('-X', '-X', '-X'),
('-Y', '-Y', '-Y'),
]
enumExportType = [
('C', 'C', 'C'),
('Binary', 'Binary', 'Binary'),
('Insertable Binary', 'Insertable Binary', 'Insertable Binary')
]
enumExportTypeAnimation = [
('C', 'C', 'C'),
('Binary', 'Binary', 'Binary'),
('Insertable Binary', 'Insertable Binary', 'Insertable Binary'),
('METAL Composer JSON', 'METAL Composer JSON', 'METAL Composer JSON')
]
enumRefreshVer = [
("Refresh 3", "Refresh 3", "Refresh 3"),
("Refresh 4", "Refresh 4", "Refresh 4"),
("Refresh 5", "Refresh 5", "Refresh 5"),
("Refresh 6", "Refresh 6", "Refresh 6"),
("Refresh 7", "Refresh 7", "Refresh 7"),
("Refresh 8", "Refresh 8", "Refresh 8"),
("Refresh 10", "Refresh 10", "Refresh 10"),
("Refresh 11", "Refresh 11", "Refresh 11"),
("Refresh 12", "Refresh 12", "Refresh 12"),
("Refresh 13", "Refresh 13", "Refresh 13"),
]
enumHUDExportLocation = [
('HUD', 'HUD', 'Exports to src/game/hud.c'),
('Menu', 'Menu', 'Exports to src/game/ingame_menu.c')
]
# filepath, function to insert before
enumHUDPaths = {
"HUD" : ('src/game/hud.c', 'void render_hud(void)'),
'Menu' : ('src/game/ingame_menu.c', 's16 render_menus_and_dialogs()'),
}
enumExportHeaderType = [
#('None', 'None', 'Headers are not written'),
('Actor', 'Actor Data', 'Headers are written to a group in actors/'),
('Level', 'Level Data', 'Headers are written to a specific level in levels/')
]
enumCompressionFormat = [
('mio0', 'MIO0', 'MIO0'),
('yay0', 'YAY0', 'YAY0'),
]
panelSeparatorSize = 5
def checkExpanded(filepath):
size = os.path.getsize(filepath)
if size < 9000000: # check if 8MB
raise PluginError("ROM at " + filepath + " is too small. You may be using an unexpanded ROM. You can expand a ROM by opening it in SM64 Editor or ROM Manager.")
def getPathAndLevel(customExport, exportPath, levelName, levelOption):
if customExport:
exportPath = bpy.path.abspath(exportPath)
levelName = levelName
else:
exportPath = bpy.path.abspath(bpy.context.scene.decompPath)
if levelOption == 'custom':
levelName = levelName
else:
levelName = levelOption
return exportPath, levelName
class ArmatureApplyWithMesh(bpy.types.Operator):
# set bl_ properties
bl_description = 'Applies current pose as default pose. Useful for ' + \
"rigging an armature that is not in T/A pose. Note that when using " +\
" with an SM64 armature, you must revert to the default pose after " +\
"skinning."
bl_idname = 'object.armature_apply_w_mesh'
bl_label = "Apply As Rest Pose"
bl_options = {'REGISTER', 'UNDO', 'PRESET'}
# Called on demand (i.e. button press, menu item)
# Can also be called from operator search menu (Spacebar)
def execute(self, context):
try:
if context.mode != 'OBJECT' and context.mode != 'POSE':
raise PluginError("Operator can only be used in object or pose mode.")
elif context.mode == 'POSE':
bpy.ops.object.mode_set(mode = "OBJECT")
if len(context.selected_objects) == 0:
raise PluginError("Armature not selected.")
elif type(context.selected_objects[0].data) is not\
bpy.types.Armature:
raise PluginError("Armature not selected.")
armatureObj = context.selected_objects[0]
for child in armatureObj.children:
if type(child.data) is not bpy.types.Mesh:
continue
armatureModifier = None
for modifier in child.modifiers:
if isinstance(modifier, bpy.types.ArmatureModifier):
armatureModifier = modifier
if armatureModifier is None:
continue
print(armatureModifier.name)
bpy.ops.object.select_all(action = "DESELECT")
context.view_layer.objects.active = child
bpy.ops.object.modifier_copy(modifier=armatureModifier.name)
print(len(child.modifiers))
bpy.ops.object.modifier_apply(modifier=armatureModifier.name)
bpy.ops.object.select_all(action = "DESELECT")
context.view_layer.objects.active = armatureObj
bpy.ops.object.mode_set(mode = "POSE")
bpy.ops.pose.armature_apply()
except Exception as e:
raisePluginError(self, e)
return {"CANCELLED"}
self.report({'INFO'}, 'Applied armature with mesh.')
return {'FINISHED'} # must return a set
class AddBoneGroups(bpy.types.Operator):
# set bl_ properties
bl_description = 'Add bone groups respresenting other node types in ' +\
'SM64 geolayouts (ex. Shadow, Switch, Function).'
bl_idname = 'object.add_bone_groups'
bl_label = "Add Bone Groups"
bl_options = {'REGISTER', 'UNDO', 'PRESET'}
# Called on demand (i.e. button press, menu item)
# Can also be called from operator search menu (Spacebar)
def execute(self, context):
try:
if context.mode != 'OBJECT' and context.mode != 'POSE':
raise PluginError("Operator can only be used in object or pose mode.")
elif context.mode == 'POSE':
bpy.ops.object.mode_set(mode = "OBJECT")
if len(context.selected_objects) == 0:
raise PluginError("Armature not selected.")
elif type(context.selected_objects[0].data) is not\
bpy.types.Armature:
raise PluginError("Armature not selected.")
armatureObj = context.selected_objects[0]
createBoneGroups(armatureObj)
except Exception as e:
raisePluginError(self, e)
return {"CANCELLED"}
self.report({'INFO'}, 'Created bone groups.')
return {'FINISHED'} # must return a set
class CreateMetarig(bpy.types.Operator):
# set bl_ properties
bl_description = 'SM64 imported armatures are usually not good for ' + \
'rigging. There are often intermediate bones between deform bones ' + \
'and they don\'t usually point to their children. This operator ' +\
'creates a metarig on armature layer 4 useful for IK.'
bl_idname = 'object.create_metarig'
bl_label = "Create Animatable Metarig"
bl_options = {'REGISTER', 'UNDO', 'PRESET'}
# Called on demand (i.e. button press, menu item)
# Can also be called from operator search menu (Spacebar)
def execute(self, context):
try:
if context.mode != 'OBJECT' and context.mode != 'POSE':
raise PluginError("Operator can only be used in object or pose mode.")
elif context.mode == 'POSE':
bpy.ops.object.mode_set(mode = "OBJECT")
if len(context.selected_objects) == 0:
raise PluginError("Armature not selected.")
elif type(context.selected_objects[0].data) is not\
bpy.types.Armature:
raise PluginError("Armature not selected.")
armatureObj = context.selected_objects[0]
generateMetarig(armatureObj)
except Exception as e:
raisePluginError(self, e)
return {"CANCELLED"}
self.report({'INFO'}, 'Created metarig.')
return {'FINISHED'} # must return a set
class N64_AddF3dMat(bpy.types.Operator):
# set bl_ properties
bl_idname = 'object.add_f3d_mat'
bl_label = "Add Fast3D Material"
bl_options = {'REGISTER', 'UNDO', 'PRESET'}
# Called on demand (i.e. button press, menu item)
# Can also be called from operator search menu (Spacebar)
def execute(self, context):
try:
if context.mode != 'OBJECT':
raise PluginError("Operator can only be used in object mode.")
if len(context.selected_objects) == 0:
raise PluginError("Mesh not selected.")
elif type(context.selected_objects[0].data) is not\
bpy.types.Mesh:
raise PluginError("Mesh not selected.")
obj = context.selected_objects[0]
createF3DMat(obj)
except Exception as e:
raisePluginError(self, e)
return {"CANCELLED"}
self.report({'INFO'}, 'Created F3D material.')
return {'FINISHED'} # must return a set
class SM64_AddrConv(bpy.types.Operator):
# set bl_ properties
bl_idname = 'object.addr_conv'
bl_label = "Convert Address"
bl_options = {'REGISTER', 'UNDO', 'PRESET'}
segToVirt : bpy.props.BoolProperty()
def execute(self, context):
romfileSrc = None
try:
address = int(context.scene.convertibleAddr, 16)
importRom = context.scene.importRom
romfileSrc = open(bpy.path.abspath(importRom), 'rb')
checkExpanded(bpy.path.abspath(importRom))
levelParsed = parseLevelAtPointer(romfileSrc,
level_pointers[context.scene.levelConvert])
segmentData = levelParsed.segmentData
if self.segToVirt:
ptr = decodeSegmentedAddr(
address.to_bytes(4, 'big'), segmentData)
self.report({'INFO'},
'Virtual pointer is 0x' + format(ptr, '08X'))
else:
ptr = int.from_bytes(
encodeSegmentedAddr(address, segmentData), 'big')
self.report({'INFO'},
'Segmented pointer is 0x' + format(ptr, '08X'))
romfileSrc.close()
return {'FINISHED'}
except Exception as e:
if romfileSrc is not None:
romfileSrc.close()
raisePluginError(self, e)
return {'CANCELLED'} # must return a set
# See SM64GeoLayoutPtrsByLevels.txt by VLTone
class SM64_ImportGeolayout(bpy.types.Operator):
# set bl_ properties
bl_idname = 'object.sm64_import_geolayout'
bl_label = "Import Geolayout"
bl_options = {'REGISTER', 'UNDO', 'PRESET'}
# Called on demand (i.e. button press, menu item)
# Can also be called from operator search menu (Spacebar)
def execute(self, context):
romfileSrc = None
try:
geoImportAddr = context.scene.geoImportAddr
generateArmature = context.scene.generateArmature
levelGeoImport = context.scene.levelGeoImport
importRom = context.scene.importRom
ignoreSwitch = context.scene.ignoreSwitch
#finalTransform = mathutils.Matrix.Rotation(math.radians(-90), 4, 'X')
finalTransform = mathutils.Matrix.Identity(4)
if context.mode != 'OBJECT':
raise PluginError("Operator can only be used in object mode.")
except Exception as e:
raisePluginError(self, e)
return {'CANCELLED'}
try:
romfileSrc = open(bpy.path.abspath(importRom), 'rb')
checkExpanded(bpy.path.abspath(importRom))
armatureObj = None
# Get segment data
levelParsed = parseLevelAtPointer(romfileSrc,
level_pointers[levelGeoImport])
segmentData = levelParsed.segmentData
geoStart = int(geoImportAddr, 16)
if context.scene.geoIsSegPtr:
geoStart = decodeSegmentedAddr(
geoStart.to_bytes(4, 'big'), segmentData)
# Armature mesh groups includes armatureObj.
armatureMeshGroups, armatureObj = parseGeoLayout(romfileSrc,
geoStart,
context.scene, segmentData,
finalTransform, generateArmature,
ignoreSwitch, True, context.scene.f3d_type,
context.scene.isHWv1)
romfileSrc.close()
bpy.ops.object.select_all(action = 'DESELECT')
if armatureObj is not None:
for armatureMeshGroup in armatureMeshGroups:
armatureMeshGroup[0].select_set(True)
doRotation(math.radians(-90), 'X')
for armatureMeshGroup in armatureMeshGroups:
bpy.ops.object.select_all(action = 'DESELECT')
armatureMeshGroup[0].select_set(True)
bpy.context.view_layer.objects.active = armatureMeshGroup[0]
bpy.ops.object.make_single_user(obdata = True)
bpy.ops.object.transform_apply(location = False,
rotation = True, scale = False, properties = False)
else:
doRotation(math.radians(-90), 'X')
bpy.ops.object.select_all(action = 'DESELECT')
#objs[-1].select_set(True)
self.report({'INFO'}, 'Generic import succeeded.')
return {'FINISHED'} # must return a set
except Exception as e:
if context.mode != 'OBJECT':
bpy.ops.object.mode_set(mode = 'OBJECT')
if romfileSrc is not None:
romfileSrc.close()
raisePluginError(self, e)
return {'CANCELLED'} # must return a set
class SM64_ImportGeolayoutPanel(bpy.types.Panel):
bl_idname = "SM64_PT_import_geolayout"
bl_label = "SM64 Geolayout Importer"
bl_space_type = 'VIEW_3D'
bl_region_type = 'UI'
bl_category = 'Fast64'
@classmethod
def poll(cls, context):
return True
# called every frame
def draw(self, context):
col = self.layout.column()
propsGeoI = col.operator(SM64_ImportGeolayout.bl_idname)
#col.prop(context.scene, 'rotationOrder')
#col.prop(context.scene, 'rotationAxis')
#col.prop(context.scene, 'rotationAngle')
prop_split(col, context.scene, 'geoImportAddr', 'Start Address')
col.prop(context.scene, 'geoIsSegPtr')
col.prop(context.scene, 'levelGeoImport')
col.prop(context.scene, 'generateArmature')
col.prop(context.scene, 'ignoreSwitch')
if not context.scene.ignoreSwitch:
boxLayout = col.box()
boxLayout.label(text = "WARNING: May take a long time.")
boxLayout.label(text = "Switch nodes won't be setup.")
col.box().label(text = "Only Fast3D mesh importing allowed.")
for i in range(panelSeparatorSize):
col.separator()
class SM64_ExportGeolayoutObject(bpy.types.Operator):
# set bl_ properties
bl_idname = 'object.sm64_export_geolayout_object'
bl_label = "Export Object Geolayout"
bl_options = {'REGISTER', 'UNDO', 'PRESET'}
# Called on demand (i.e. button press, menu item)
# Can also be called from operator search menu (Spacebar)
def execute(self, context):
romfileOutput = None
tempROM = None
try:
obj = None
if context.mode != 'OBJECT':
raise PluginError("Operator can only be used in object mode.")
if len(context.selected_objects) == 0:
raise PluginError("Object not selected.")
obj = context.active_object
if type(obj.data) is not bpy.types.Mesh and \
not (obj.data is None and (obj.sm64_obj_type == 'None' or obj.sm64_obj_type == 'Switch')):
raise PluginError("Selected object must be a mesh or an empty with the \"None\" or \"Switch\" type.")
#if context.scene.saveCameraSettings and \
# context.scene.levelCamera is None:
# raise PluginError("Cannot save camera settings with no camera provided.")
#levelCamera = context.scene.levelCamera if \
# context.scene.saveCameraSettings else None
finalTransform = mathutils.Matrix.Identity(4)
scaleValue = bpy.context.scene.blenderToSM64Scale
finalTransform = mathutils.Matrix.Diagonal(mathutils.Vector((
scaleValue, scaleValue, scaleValue))).to_4x4()
except Exception as e:
raisePluginError(self, e)
return {'CANCELLED'}
try:
# Rotate all armatures 90 degrees
applyRotation([obj], math.radians(90), 'X')
if context.scene.geoExportType == 'C':
exportPath, levelName = getPathAndLevel(context.scene.geoCustomExport,
context.scene.geoExportPath, context.scene.geoLevelName,
context.scene.geoLevelOption)
if not context.scene.geoCustomExport:
applyBasicTweaks(exportPath)
exportGeolayoutObjectC(obj, finalTransform,
context.scene.f3d_type, context.scene.isHWv1,
exportPath,
bpy.context.scene.geoTexDir,
bpy.context.scene.geoSaveTextures or bpy.context.scene.ignoreTextureRestrictions,
bpy.context.scene.geoSeparateTextureDef,
None, bpy.context.scene.geoGroupName,
context.scene.geoExportHeaderType,
context.scene.geoName, context.scene.geoStructName, levelName, context.scene.geoCustomExport, "Static")
self.report({'INFO'}, 'Success!')
elif context.scene.geoExportType == 'Insertable Binary':
exportGeolayoutObjectInsertableBinary(obj,
finalTransform, context.scene.f3d_type,
context.scene.isHWv1,
bpy.path.abspath(bpy.context.scene.geoInsertableBinaryPath),
None)
self.report({'INFO'}, 'Success! Data at ' + \
context.scene.geoInsertableBinaryPath)
else:
tempROM = tempName(context.scene.outputRom)
checkExpanded(bpy.path.abspath(context.scene.exportRom))
romfileExport = open(
bpy.path.abspath(context.scene.exportRom), 'rb')
shutil.copy(bpy.path.abspath(context.scene.exportRom),
bpy.path.abspath(tempROM))
romfileExport.close()
romfileOutput = open(bpy.path.abspath(tempROM), 'rb+')
levelParsed = parseLevelAtPointer(romfileOutput,
level_pointers[context.scene.levelGeoExport])
segmentData = levelParsed.segmentData
if context.scene.extendBank4:
ExtendBank0x04(romfileOutput, segmentData,
defaultExtendSegment4)
exportRange = [int(context.scene.geoExportStart, 16),
int(context.scene.geoExportEnd, 16)]
textDumpFilePath = \
bpy.path.abspath(context.scene.textDumpGeoPath) \
if context.scene.textDumpGeo else None
if context.scene.overwriteModelLoad:
modelLoadInfo = \
(int(context.scene.modelLoadLevelScriptCmd, 16),
int(context.scene.modelID,16))
else:
modelLoadInfo = (None, None)
if context.scene.geoUseBank0:
addrRange, startRAM, geoStart = \
exportGeolayoutObjectBinaryBank0(
romfileOutput, obj, exportRange,
finalTransform, *modelLoadInfo, textDumpFilePath,
context.scene.f3d_type, context.scene.isHWv1,
getAddressFromRAMAddress(int(
context.scene.geoRAMAddr, 16)),
None)
else:
addrRange, segPointer = exportGeolayoutObjectBinary(
romfileOutput, obj,
exportRange, finalTransform, segmentData,
*modelLoadInfo, textDumpFilePath,
context.scene.f3d_type, context.scene.isHWv1,
None)
romfileOutput.close()
bpy.ops.object.select_all(action = 'DESELECT')
obj.select_set(True)
context.view_layer.objects.active = obj
if os.path.exists(bpy.path.abspath(context.scene.outputRom)):
os.remove(bpy.path.abspath(context.scene.outputRom))
os.rename(bpy.path.abspath(tempROM),
bpy.path.abspath(context.scene.outputRom))
if context.scene.geoUseBank0:
self.report({'INFO'}, 'Success! Geolayout at (' + \
hex(addrRange[0]) + ', ' + hex(addrRange[1]) + \
'), to write to RAM Address ' + hex(startRAM) + \
', with geolayout starting at ' + hex(geoStart))
else:
self.report({'INFO'}, 'Success! Geolayout at (' + \
hex(addrRange[0]) + ', ' + hex(addrRange[1]) + \
') (Seg. ' + segPointer + ').')
applyRotation([obj], math.radians(-90), 'X')
return {'FINISHED'} # must return a set
except Exception as e:
if context.mode != 'OBJECT':
bpy.ops.object.mode_set(mode = 'OBJECT')
applyRotation([obj], math.radians(-90), 'X')
if context.scene.geoExportType == 'Binary':
if romfileOutput is not None:
romfileOutput.close()
if tempROM is not None and os.path.exists(bpy.path.abspath(tempROM)):
os.remove(bpy.path.abspath(tempROM))
raisePluginError(self, e)
return {'CANCELLED'} # must return a set
class SM64_ExportGeolayoutArmature(bpy.types.Operator):
# set bl_ properties
bl_idname = 'object.sm64_export_geolayout_armature'
bl_label = "Export Armature Geolayout"
bl_options = {'REGISTER', 'UNDO', 'PRESET'}
# Called on demand (i.e. button press, menu item)
# Can also be called from operator search menu (Spacebar)
def execute(self, context):
romfileOutput = None
tempROM = None
try:
armatureObj = None
if context.mode != 'OBJECT':
raise PluginError("Operator can only be used in object mode.")
if len(context.selected_objects) == 0:
raise PluginError("Armature not selected.")
armatureObj = context.active_object
if type(armatureObj.data) is not bpy.types.Armature:
raise PluginError("Armature not selected.")
if len(armatureObj.children) == 0 or \
not isinstance(armatureObj.children[0].data, bpy.types.Mesh):
raise PluginError("Armature does not have any mesh children, or " +\
'has a non-mesh child.')
#if context.scene.saveCameraSettings and \
# context.scene.levelCamera is None:
# raise PluginError("Cannot save camera settings with no camera provided.")
#levelCamera = context.scene.levelCamera if \
# context.scene.saveCameraSettings else None
obj = armatureObj.children[0]
finalTransform = mathutils.Matrix.Identity(4)
# get all switch option armatures as well
linkedArmatures = [armatureObj]
getAllArmatures(armatureObj, linkedArmatures)
linkedArmatureDict = {}
for linkedArmature in linkedArmatures:
# IMPORTANT: Do this BEFORE rotation
optionObjs = []
for childObj in linkedArmature.children:
if isinstance(childObj.data, bpy.types.Mesh):
optionObjs.append(childObj)
if len(optionObjs) > 1:
raise PluginError('Error: ' + linkedArmature.name +\
' has more than one mesh child.')
elif len(optionObjs) < 1:
raise PluginError('Error: ' + linkedArmature.name +\
' has no mesh children.')
linkedMesh = optionObjs[0]
prepareGeolayoutExport(linkedArmature, linkedMesh)
linkedArmatureDict[linkedArmature] = linkedMesh
except Exception as e:
raisePluginError(self, e)
return {'CANCELLED'}
try:
# Rotate all armatures 90 degrees
applyRotation([armatureObj] + linkedArmatures,
math.radians(90), 'X')
# You must ALSO apply object rotation after armature rotation.
bpy.ops.object.select_all(action = "DESELECT")
for linkedArmature, linkedMesh in linkedArmatureDict.items():
linkedMesh.select_set(True)
obj.select_set(True)
bpy.context.view_layer.objects.active = obj
bpy.ops.object.transform_apply(location = False, rotation = True,
scale = True, properties = False)
if context.scene.geoExportType == 'C':
exportPath, levelName = getPathAndLevel(context.scene.geoCustomExport,
context.scene.geoExportPath, context.scene.geoLevelName,
context.scene.geoLevelOption)
if not context.scene.geoCustomExport:
applyBasicTweaks(exportPath)
exportGeolayoutArmatureC(armatureObj, obj, finalTransform,
context.scene.f3d_type, context.scene.isHWv1,
exportPath,
bpy.context.scene.geoTexDir,
bpy.context.scene.geoSaveTextures or bpy.context.scene.ignoreTextureRestrictions,
bpy.context.scene.geoSeparateTextureDef,
None, bpy.context.scene.geoGroupName, context.scene.geoExportHeaderType,
context.scene.geoName, context.scene.geoStructName, levelName, context.scene.geoCustomExport, "Static")
self.report({'INFO'}, 'Success!')
elif context.scene.geoExportType == 'Insertable Binary':
exportGeolayoutArmatureInsertableBinary(armatureObj, obj,
finalTransform, context.scene.f3d_type,
context.scene.isHWv1,
bpy.path.abspath(bpy.context.scene.geoInsertableBinaryPath),
None)
self.report({'INFO'}, 'Success! Data at ' + \
context.scene.geoInsertableBinaryPath)
else:
tempROM = tempName(context.scene.outputRom)
checkExpanded(bpy.path.abspath(context.scene.exportRom))
romfileExport = open(
bpy.path.abspath(context.scene.exportRom), 'rb')
shutil.copy(bpy.path.abspath(context.scene.exportRom),
bpy.path.abspath(tempROM))
romfileExport.close()
romfileOutput = open(bpy.path.abspath(tempROM), 'rb+')
levelParsed = parseLevelAtPointer(romfileOutput,
level_pointers[context.scene.levelGeoExport])
segmentData = levelParsed.segmentData
if context.scene.extendBank4:
ExtendBank0x04(romfileOutput, segmentData,
defaultExtendSegment4)
exportRange = [int(context.scene.geoExportStart, 16),
int(context.scene.geoExportEnd, 16)]
textDumpFilePath = \
bpy.path.abspath(context.scene.textDumpGeoPath) \
if context.scene.textDumpGeo else None
if context.scene.overwriteModelLoad:
modelLoadInfo = \
(int(context.scene.modelLoadLevelScriptCmd, 16),
int(context.scene.modelID, 16))
else:
modelLoadInfo = (None, None)
if context.scene.geoUseBank0:
addrRange, startRAM, geoStart = \
exportGeolayoutArmatureBinaryBank0(
romfileOutput, armatureObj, obj, exportRange,
finalTransform, *modelLoadInfo, textDumpFilePath,
context.scene.f3d_type, context.scene.isHWv1,
getAddressFromRAMAddress(int(
context.scene.geoRAMAddr, 16)), None)
else:
addrRange, segPointer = exportGeolayoutArmatureBinary(
romfileOutput, armatureObj, obj,
exportRange, finalTransform, segmentData,
*modelLoadInfo, textDumpFilePath,
context.scene.f3d_type, context.scene.isHWv1,
None)
romfileOutput.close()
bpy.ops.object.select_all(action = 'DESELECT')
armatureObj.select_set(True)
context.view_layer.objects.active = armatureObj
if os.path.exists(bpy.path.abspath(context.scene.outputRom)):
os.remove(bpy.path.abspath(context.scene.outputRom))
os.rename(bpy.path.abspath(tempROM),
bpy.path.abspath(context.scene.outputRom))
if context.scene.geoUseBank0:
self.report({'INFO'}, 'Success! Geolayout at (' + \
hex(addrRange[0]) + ', ' + hex(addrRange[1]) + \
'), to write to RAM Address ' + hex(startRAM) + \
', with geolayout starting at ' + hex(geoStart))
else:
self.report({'INFO'}, 'Success! Geolayout at (' + \
hex(addrRange[0]) + ', ' + hex(addrRange[1]) + \
') (Seg. ' + segPointer + ').')
applyRotation([armatureObj] + linkedArmatures,
math.radians(-90), 'X')
return {'FINISHED'} # must return a set
except Exception as e:
if context.mode != 'OBJECT':
bpy.ops.object.mode_set(mode = 'OBJECT')
applyRotation([armatureObj] + linkedArmatures,
math.radians(-90), 'X')
if context.scene.geoExportType == 'Binary':
if romfileOutput is not None:
romfileOutput.close()
if tempROM is not None and os.path.exists(bpy.path.abspath(tempROM)):
os.remove(bpy.path.abspath(tempROM))
if armatureObj is not None:
armatureObj.select_set(True)
context.view_layer.objects.active = armatureObj
raisePluginError(self, e)
return {'CANCELLED'} # must return a set
class SM64_ExportGeolayoutPanel(bpy.types.Panel):
bl_idname = "SM64_PT_export_geolayout"
bl_label = "SM64 Geolayout Exporter"
bl_space_type = 'VIEW_3D'
bl_region_type = 'UI'
bl_category = 'Fast64'
@classmethod
def poll(cls, context):
return True
# called every frame
def draw(self, context):
col = self.layout.column()
propsGeoE = col.operator(SM64_ExportGeolayoutArmature.bl_idname)
propsGeoE = col.operator(SM64_ExportGeolayoutObject.bl_idname)
col.prop(context.scene, 'geoExportType')
if context.scene.geoExportType == 'C':
if not bpy.context.scene.ignoreTextureRestrictions:
col.prop(context.scene, 'geoSaveTextures')
if context.scene.geoSaveTextures:
if context.scene.geoCustomExport:
prop_split(col, context.scene, 'geoTexDir', 'Texture Include Path')
col.prop(context.scene, 'geoSeparateTextureDef')
col.prop(context.scene, 'geoCustomExport')
if context.scene.geoCustomExport:
col.prop(context.scene, 'geoExportPath')
prop_split(col, context.scene, 'geoName', 'Folder Name')
prop_split(col, context.scene, 'geoStructName', 'Geolayout Name')
customExportWarning(col)
else:
prop_split(col, context.scene, 'geoExportHeaderType', 'Export Type')
if context.scene.geoExportHeaderType == 'Actor':
prop_split(col, context.scene, 'geoGroupName', 'Group Name')
'''
if context.scene.geoName == 'marios_cap' or\
context.scene.geoName == 'marios_metal_cap' or\
context.scene.geoName == 'marios_wing_cap' or\
context.scene.geoName == 'marios_winged_metal_cap':
col.prop(context.scene, 'modifyOldGeo')
elif context.scene.geoName == 'mario_cap':
warningBox = col.box()
warningBox.label(text = 'WARNING: DO NOT REPLACE THIS ACTOR.', icon = "QUESTION")
warningBox.label(text = 'This contains geolayouts for all cap types.')
warningBox.label(text = 'Use one of these geolayout names instead:')
warningBox.label(text = ' - marios_cap')
warningBox.label(text = ' - marios_metal_cap')
warningBox.label(text = ' - marios_wing_cap')
warningBox.label(text = ' - marios_winged_metal_cap')
if context.scene.geoName == 'koopa_with_shell' or\
context.scene.geoName == 'koopa_without_shell':
col.prop(context.scene, 'modifyOldGeo')
elif context.scene.geoName == 'koopa':
warningBox = col.box()
warningBox.label(text = 'WARNING: DO NOT REPLACE THIS ACTOR.', icon = "QUESTION")
warningBox.label(text = 'This contains geolayouts for both koopa with and without shell.')
warningBox.label(text = 'Use one of these geolayout names instead:')
warningBox.label(text = ' - koopa_with_shell')
warningBox.label(text = ' - koopa_without_shell')
if context.scene.geoName == 'black_bobomb' or\
context.scene.geoName == 'bobomb_buddy':
col.prop(context.scene, 'modifyOldGeo')
elif context.scene.geoName == 'bobomb':
warningBox = col.box()
warningBox.label(text = 'WARNING: DO NOT REPLACE THIS ACTOR.', icon = "QUESTION")
warningBox.label(text = 'This contains geolayouts for both red and black bobombs.')
warningBox.label(text = 'Also note that this contains a display list used in bowling_ball.')
warningBox.label(text = 'Use one of these geolayout names instead:')
warningBox.label(text = ' - black_bobomb')
warningBox.label(text = ' - bobomb_buddy')
if context.scene.geoName == 'purple_marble':
col.prop(context.scene, 'modifyOldGeo')
elif context.scene.geoName == 'bubble':
warningBox = col.box()
warningBox.label(text = 'WARNING: SECONDARY GEOLAYOUTS.', icon = "QUESTION")
warningBox.label(text = 'If you replace this you must also replace purple_marble.')
warningBox.label(text = 'Otherwise you will get a compilation error.')
'''
elif context.scene.geoExportHeaderType == 'Level':
prop_split(col, context.scene, 'geoLevelOption', 'Level')
if context.scene.geoLevelOption == 'custom':
prop_split(col, context.scene, 'geoLevelName', 'Level Name')
prop_split(col, context.scene, 'geoName', 'Folder Name')
prop_split(col, context.scene, 'geoStructName', 'Geolayout Name')
if context.scene.geoExportHeaderType == 'Actor':
if context.scene.geoName == 'star':
col.prop(context.scene, 'replaceStarRefs')
if context.scene.geoName == 'transparent_star':
col.prop(context.scene, 'replaceTransparentStarRefs')
if context.scene.geoName == 'marios_cap':
col.prop(context.scene, 'replaceCapRefs')
infoBox = col.box()
infoBox.label(text = 'If a geolayout file contains multiple actors,')
infoBox.label(text = 'all other actors must also be replaced (with unique folder names)')
infoBox.label(text = 'to prevent compilation errors.')
decompFolderMessage(col)
writeBox = makeWriteInfoBox(col)
writeBoxExportType(writeBox, context.scene.geoExportHeaderType,
context.scene.geoName, context.scene.geoLevelName,
context.scene.geoLevelOption)
extendedRAMLabel(col)
elif context.scene.geoExportType == 'Insertable Binary':
col.prop(context.scene, 'geoInsertableBinaryPath')
else:
prop_split(col, context.scene, 'geoExportStart', 'Start Address')
prop_split(col, context.scene, 'geoExportEnd', 'End Address')
col.prop(context.scene, 'geoUseBank0')
if context.scene.geoUseBank0:
prop_split(col, context.scene, 'geoRAMAddr', 'RAM Address')
else:
col.prop(context.scene, 'levelGeoExport')
col.prop(context.scene, 'overwriteModelLoad')
if context.scene.overwriteModelLoad:
prop_split(col, context.scene, 'modelLoadLevelScriptCmd', 'Model Load Command')
prop_split(col, context.scene, 'modelID', 'Model ID')
col.prop(context.scene, 'textDumpGeo')
if context.scene.textDumpGeo:
col.prop(context.scene, 'textDumpGeoPath')
#col.prop(context.scene, 'saveCameraSettings')
#if context.scene.saveCameraSettings:
# prop_split(col, context.scene, 'levelCamera', 'Level Camera')
for i in range(panelSeparatorSize):
col.separator()
class SM64_ArmatureToolsPanel(bpy.types.Panel):
bl_idname = "SM64_PT_armature_tools"
bl_label = "SM64 Armature Tools"
bl_space_type = 'VIEW_3D'
bl_region_type = 'UI'
bl_category = 'Fast64'
@classmethod
def poll(cls, context):
return True
# called every frame
def draw(self, context):
col = self.layout.column()
col.operator(ArmatureApplyWithMesh.bl_idname)
col.operator(AddBoneGroups.bl_idname)
col.operator(CreateMetarig.bl_idname)
#col.operator(N64_AddF3dMat.bl_idname)
for i in range(panelSeparatorSize):
col.separator()
class SM64_ImportDL(bpy.types.Operator):
# set bl_ properties
bl_idname = 'object.sm64_import_dl'
bl_label = "Import Display List"
bl_options = {'REGISTER', 'UNDO', 'PRESET'}
# Called on demand (i.e. button press, menu item)
# Can also be called from operator search menu (Spacebar)
def execute(self, context):
romfileSrc = None
try:
if context.mode != 'OBJECT':
raise PluginError("Operator can only be used in object mode.")
except Exception as e:
raisePluginError(self, e)
return {'CANCELLED'}
try:
checkExpanded(bpy.path.abspath(context.scene.importRom))
romfileSrc = open(bpy.path.abspath(context.scene.importRom), 'rb')
levelParsed = parseLevelAtPointer(romfileSrc,
level_pointers[context.scene.levelDLImport])
segmentData = levelParsed.segmentData
start = decodeSegmentedAddr(
int(context.scene.DLImportStart, 16).to_bytes(4, 'big'),
segmentData) if context.scene.isSegmentedAddrDLImport else \
int(context.scene.DLImportStart, 16)
readObj = F3DtoBlenderObject(romfileSrc, start,
context.scene, 'sm64_mesh',
Matrix.Identity(4),
segmentData, True)
applyRotation([readObj], math.radians(-90), 'X')
romfileSrc.close()
self.report({'INFO'}, 'Generic import succeeded.')
return {'FINISHED'} # must return a set
except Exception as e:
if context.mode != 'OBJECT':
bpy.ops.object.mode_set(mode = 'OBJECT')
if romfileSrc is not None:
romfileSrc.close()
raisePluginError(self, e)
return {'CANCELLED'}
class SM64_ImportDLPanel(bpy.types.Panel):
bl_idname = "SM64_PT_import_dl"
bl_label = "SM64 DL Importer"
bl_space_type = 'VIEW_3D'
bl_region_type = 'UI'
bl_category = 'Fast64'
@classmethod
def poll(cls, context):
return True
# called every frame
def draw(self, context):
col = self.layout.column()
propsDLI = col.operator(SM64_ImportDL.bl_idname)
prop_split(col, context.scene, 'DLImportStart', 'Start Address')
col.prop(context.scene, 'levelDLImport')
col.prop(context.scene, 'isSegmentedAddrDLImport')
col.box().label(text = "Only Fast3D mesh importing allowed.")
for i in range(panelSeparatorSize):
col.separator()
class SM64_ExportDL(bpy.types.Operator):
# set bl_ properties
bl_idname = 'object.sm64_export_dl'
bl_label = "Export Display List"
bl_options = {'REGISTER', 'UNDO', 'PRESET'}
# Called on demand (i.e. button press, menu item)
# Can also be called from operator search menu (Spacebar)
def execute(self, context):
romfileOutput = None
tempROM = None
try:
if context.mode != 'OBJECT':
raise PluginError("Operator can only be used in object mode.")
allObjs = context.selected_objects
if len(allObjs) == 0:
raise PluginError("No objects selected.")
obj = context.selected_objects[0]
if not isinstance(obj.data, bpy.types.Mesh):
raise PluginError("Object is not a mesh.")
#T, R, S = obj.matrix_world.decompose()
#objTransform = R.to_matrix().to_4x4() @ \
# mathutils.Matrix.Diagonal(S).to_4x4()
#finalTransform = (blenderToSM64Rotation * \
# (bpy.context.scene.blenderToSM64Scale)).to_4x4()
#finalTransform = mathutils.Matrix.Identity(4)
scaleValue = bpy.context.scene.blenderToSM64Scale
finalTransform = mathutils.Matrix.Diagonal(mathutils.Vector((
scaleValue, scaleValue, scaleValue))).to_4x4()
#cProfile.runctx('exportF3DtoC(bpy.path.abspath(context.scene.DLExportPath), obj,' +\
# 'context.scene.DLExportisStatic, finalTransform,' +\
# 'context.scene.f3d_type, context.scene.isHWv1,' +\
# 'bpy.context.scene.DLTexDir,' +\
# 'bpy.context.scene.DLSaveTextures,' +\
# 'bpy.context.scene.DLSeparateTextureDef, bpy.context.scene.DLName)',
# globals(), locals(), "E:/Non-Steam Games/emulators/Project 64 1.6/SM64 Romhack Tools/_Data/blender.prof")
#p = pstats.Stats("E:/Non-Steam Games/emulators/Project 64 1.6/SM64 Romhack Tools/_Data/blender.prof")
#p.sort_stats("cumulative").print_stats(2000)
except Exception as e:
raisePluginError(self, e)
return {"CANCELLED"}
try:
applyRotation([obj], math.radians(90), 'X')
if context.scene.DLExportType == 'C':
exportPath, levelName = getPathAndLevel(context.scene.DLCustomExport,
context.scene.DLExportPath, context.scene.DLLevelName,
context.scene.DLLevelOption)
if not context.scene.DLCustomExport:
applyBasicTweaks(exportPath)