-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathImport_Level.py
2083 lines (2002 loc) · 81.7 KB
/
Import_Level.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 bpy
from bpy.props import (StringProperty,
BoolProperty,
IntProperty,
FloatProperty,
FloatVectorProperty,
EnumProperty,
PointerProperty,
IntVectorProperty,
BoolVectorProperty
)
from bpy.types import (Panel,
Menu,
Operator,
PropertyGroup,
)
from array import array
import os
from struct import *
import sys
import math
from shutil import copy
from pathlib import Path
from types import ModuleType
from mathutils import Vector, Euler, Matrix, Quaternion
import re
from copy import deepcopy
from dataclasses import dataclass
#from SM64classes import *
bl_info = {
"name": "SM64 Decomp C Level Importer",
"description": "Import&Export levels for SM64 Decomp with Fast64",
"author": "scuttlebug_raiser",
"version": (1, 0, 0),
"blender": (2, 83, 0),
"location": "3D View > Tools",
"warning": "", # used for warning icon and text in addons panel
"wiki_url": "",
"tracker_url": "",
"category": "Import-Export"
}
Num2LevelName = {
4:'bbh',
5:"ccm",
7:'hmc',
8:'ssl',
9:'bob',
10:'sl',
11:'wdw',
12:'jrb',
13:'thi',
14:'ttc',
15:'rr',
16:"castle_grounds",
17:'bitdw',
18:'vcutm',
19:'bitfs',
20:'sa',
21:'bits',
22:'lll',
23:'ddd',
24:'wf',
25:'ending',
26:'castle_courtyard',
27:'pss',
28:'cotmc',
29:'totwc',
30:'bowser_1',
31:'wmotr',
33:'bowser_2',
34:'bowser_3',
36:'ttm'
}
#Levelname uses a different castle inside name which is dumb
Num2Name = {6:'castle_inside',**Num2LevelName}
class Area():
def __init__(self, root, geo, levelRoot, num, scene, col):
self.root = root
self.geo = geo.strip()
self.num = num
self.scene = scene
#Set level root as parent
Parent(levelRoot, root)
#set default vars
root.sm64_obj_type = 'Area Root'
root.areaIndex = num
self.objects = []
self.col = col
#self.OjbColl = bpy.data.collections.new("%s Area %d Objects"%(scene.LevelImp.Level,num))
def AddWarp(self,args):
#set context to the root
bpy.context.view_layer.objects.active = self.root
#call fast64s warp node creation operator
bpy.ops.bone.add_warp_node()
warp=self.root.warpNodes[0]
warp.warpID=args[0]
warp.destNode=args[3]
level=args[1].strip().replace("LEVEL_",'').lower()
if level=='castle':
level='castle_inside'
if level.isdigit():
level=Num2Name.get(eval(level))
if not level:
level='bob'
warp.destLevelEnum=level
warp.destArea=args[2]
chkpoint=args[-1].strip()
#Sorry for the hex users here
if 'WARP_NO_CHECKPOINT' in chkpoint or int(chkpoint.isdigit()*chkpoint+'0')==0:
warp.warpFlagEnum='WARP_NO_CHECKPOINT'
else:
warp.warpFlagEnum='WARP_CHECKPOINT'
def AddObject(self,args):
self.objects.append(args)
def PlaceObjects(self, col = None):
if not col:
col = self.col
else:
col = CreateCol(self.root.users_collection[0], col)
for a in self.objects:
self.PlaceObject(a, col)
def PlaceObject(self, args, col):
#print(args)
Obj = bpy.data.objects.new('Empty', None)
col.objects.link(Obj)
Parent(self.root, Obj)
Obj.name = "Object {} {}".format(args[8].strip(),args[0].strip())
Obj.sm64_obj_type= 'Object'
Obj.sm64_behaviour_enum= 'Custom'
Obj.sm64_obj_behaviour=args[8].strip()
#bparam was changed in newer version of fast64
if hasattr(Obj,"sm64_obj_bparam"):
Obj.sm64_obj_bparam=args[7]
else:
Obj.fast64.sm64.game_object.bparams = args[7]
Obj.sm64_obj_model=args[0]
loc = [eval(a.strip())/self.scene.blenderToSM64Scale for a in args[1:4]]
#rotate to fit sm64s axis
loc = [loc[0],-loc[2],loc[1]]
Obj.location = loc
#fast64 just rotations by 90 on x
rot = Euler( [math.radians(eval(a.strip())) for a in args[4:7]], "ZXY" )
rot = Rot2Blend(rot)
Obj.rotation_euler.rotate(rot)
#set act mask
mask = args[-1]
if type(mask) == str and mask.isdigit():
mask = eval(mask)
form = 'sm64_obj_use_act{}'
if mask == 31:
for i in range(1,7,1):
setattr(Obj,form.format(i),True)
else:
for i in range(1,7,1):
if mask & (1 << i):
setattr(Obj,form.format(i),True)
else:
setattr(Obj,form.format(i),False)
class Level():
def __init__(self, scr, scene, root):
self.script=scr
self.GetScripts()
self.scene = scene
self.Areas = {}
self.CurrArea = None
self.root = root
def ParseScript(self, entry, col = None):
Start = self.Scripts[entry]
scale = self.scene.blenderToSM64Scale
if not col:
col = self.scene.collection
for l in Start:
args = self.StripArgs(l)
LsW = l.startswith
#Find an area
if LsW("AREA"):
Root = bpy.data.objects.new('Empty',None)
if self.scene.LevelImp.UseCol:
a_col = bpy.data.collections.new(f"{self.scene.LevelImp.Level} area {args[0]}")
col.children.link(a_col)
else:
a_col = col
a_col.objects.link(Root)
Root.name = "{} Area Root {}".format(self.scene.LevelImp.Level, args[0])
self.Areas[args[0]] = Area(Root, args[1], self.root, int(args[0]), self.scene, a_col)
self.CurrArea = args[0]
continue
#End an area
if LsW("END_AREA"):
self.CurrArea = None
continue
#Jumps are only taken if they're in the script.c file for now
#continues script
elif LsW("JUMP_LINK"):
if self.Scripts.get(args[0]):
self.ParseScript(args[0], col = col)
continue
#ends script, I get arg -1 because sm74 has a different jump cmd
elif LsW("JUMP"):
Nentry = self.Scripts.get(args[-1])
if Nentry:
self.ParseScript(args[-1], col = col)
#for the sm74 port
if len(args)!=2:
break
#final exit of recursion
elif LsW("EXIT") or l.startswith("RETURN"):
return
#Now deal with data cmds rather than flow control ones
if LsW("WARP_NODE"):
self.Areas[self.CurrArea].AddWarp(args)
continue
if LsW("OBJECT_WITH_ACTS"):
#convert act mask from ORs of act names to a number
mask = args[-1].strip()
if not mask.isdigit():
mask = mask.replace("ACT_",'')
mask = mask.split('|')
#Attempt for safety I guess
try:
a=0
for m in mask:
a += 1 << int(m)
mask=a
except:
mask=31
self.Areas[self.CurrArea].AddObject([*args[:-1],mask])
continue
if LsW("OBJECT"):
#Only difference is act mask, which I set to 31 to mean all acts
self.Areas[self.CurrArea].AddObject([*args,31])
continue
#Don't support these for now
if LsW("MACRO_OBJECTS"):
continue
if LsW("TERRAIN_TYPE"):
if not args[0].isdigit():
self.Areas[self.CurrArea].root.terrainEnum = args[0].strip()
else:
terrains = {
0: "TERRAIN_GRASS",
1: "TERRAIN_STONE",
2: "TERRAIN_SNOW",
3: "TERRAIN_SAND",
4: "TERRAIN_SPOOKY",
5: "TERRAIN_WATER",
6: "TERRAIN_SLIDE",
7: "TERRAIN_MASK"
}
try:
num = eval(args[0])
self.Areas[self.CurrArea].root.terrainEnum = terrains.get(num)
except:
print("could not set terrain")
continue
if LsW("SHOW_DIALOG"):
rt = self.Areas[self.CurrArea].root
rt.showStartDialog = True
rt.startDialog = args[1].strip()
continue
if LsW("TERRAIN"):
self.Areas[self.CurrArea].terrain = args[0].strip()
continue
if LsW("SET_BACKGROUND_MUSIC") or LsW("SET_MENU_MUSIC"):
rt=self.Areas[self.CurrArea].root
rt.musicSeqEnum = 'Custom'
rt.music_seq = args[-1].strip()
return self.Areas
def StripArgs(self,cmd):
a = cmd.find("(")
end = cmd.rfind(")")-len(cmd)
return cmd[a+1:end].split(',')
def GetScripts(self):
#Get a dictionary made up with keys=level script names
#and values as an array of all the cmds inside.
self.Scripts={}
InlineReg="/\*((?!\*/).)*\*/"
currScr=0
skip=0
for l in self.script:
comment=l.rfind("//")
#double slash terminates line basically
if comment:
l=l[:comment]
#check for macro
if '#ifdef' in l:
skip=EvalMacro(l)
if '#elif' in l:
skip=EvalMacro(l)
if '#else' in l:
skip=0
#Now Check for level script starts
if "LevelScript" in l and not skip:
b=l.rfind('[]')
a=l.find('LevelScript')
var=l[a+11:b].strip()
self.Scripts[var] = ""
currScr=var
continue
if currScr and not skip:
#remove inline comments from line
while(True):
m=re.search(InlineReg,l)
if not m:
break
m=m.span()
l=l[:m[0]]+l[m[1]:]
#Check for end of Level Script array
if "};" in l:
currScr=0
#Add line to dict
else:
self.Scripts[currScr]+=l
#Now remove newlines from each script, and then split macro ends
#This makes each member of the array a single macro
for k,v in self.Scripts.items():
v=v.replace("\n",'')
arr=[]
x=0
stack=0
buf=""
app=0
while(x<len(v)):
char=v[x]
if char=="(":
stack+=1
app=1
if char==")":
stack-=1
if app==1 and stack==0:
app=0
buf+=v[x:x+2] #get the last parenthesis and comma
arr.append(buf.strip())
x+=2
buf=''
continue
buf+=char
x+=1
self.Scripts[k]=arr
return
class Collision():
def __init__(self,col,scale):
self.col=col
self.scale=scale
self.vertices=[]
#key=type,value=tri data
self.tris={}
self.type=None
self.SpecialObjs=[]
self.Types=[]
self.WaterBox=[]
def GetCollision(self):
for l in self.col:
args=self.StripArgs(l)
#to avoid catching COL_VERTEX_INIT
if l.startswith('COL_VERTEX') and len(args)==3:
self.vertices.append([eval(v)/self.scale for v in args])
continue
if l.startswith('COL_TRI_INIT'):
self.type=args[0]
if not self.tris.get(self.type):
self.tris[self.type]=[]
continue
if l.startswith('COL_TRI') and len(args)>2:
a=[eval(a) for a in args]
self.tris[self.type].append(a)
continue
if l.startswith('COL_WATER_BOX_INIT'):
continue
if l.startswith('COL_WATER_BOX'):
#id, x1, z1, x2, z2, y
self.WaterBox.append(args)
if l.startswith('SPECIAL_OBJECT'):
self.SpecialObjs.append(args)
#This will keep track of how to assign mats
a=0
for k,v in self.tris.items():
self.Types.append([a,k,v[0]])
a+=len(v)
self.Types.append([a,0])
def StripArgs(self,cmd):
a=cmd.find("(")
return cmd[a+1:-2].split(',')
def WriteWaterBoxes(self, scene, parent, name,col):
for i,w in enumerate(self.WaterBox):
Obj = bpy.data.objects.new('Empty',None)
scene.collection.objects.link(Obj)
Parent(parent, Obj)
Obj.name = "WaterBox_{}_{}".format(name,i)
Obj.sm64_obj_type= 'Water Box'
x1 = eval(w[1])/(self.scale)
x2 = eval(w[3])/(self.scale)
z1 = eval(w[2])/(self.scale)
z2 = eval(w[4])/(self.scale)
y = eval(w[5])/(self.scale)
Xwidth = abs(x2-x1)/(2)
Zwidth = abs(z2-z1)/(2)
loc=[x2-Xwidth,-(z2-Zwidth),y-1]
Obj.location=loc
scale = [Xwidth,Zwidth,1]
Obj.scale = scale
def WriteCollision(self, scene, name, parent, col = None):
if not col:
col = scene.collection
self.WriteWaterBoxes(scene, parent, name, col)
mesh = bpy.data.meshes.new(name+' data')
tris=[]
for t in self.tris.values():
#deal with special tris
if len(t[0])>3:
t = [a[0:3] for a in t]
tris.extend(t)
mesh.from_pydata(self.vertices, [], tris)
obj = bpy.data.objects.new(name+' Mesh',mesh)
col.objects.link(obj)
obj.ignore_render = True
if parent:
Parent(parent, obj)
RotateObj(-90, obj, world = 1)
polys = obj.data.polygons
x = 0
bpy.context.view_layer.objects.active = obj
max = len(polys)
for i,p in enumerate(polys):
a = self.Types[x][0]
if i >= a:
bpy.ops.object.create_f3d_mat() #the newest mat should be in slot[-1]
mat = obj.data.materials[x]
mat.collision_type_simple = 'Custom'
mat.collision_custom = self.Types[x][1]
mat.name = "Sm64_Col_Mat_{}".format(self.Types[x][1])
color = ((max-a)/(max),(max+a)/(2*max-a),a/max,1) #Just to give some variety
mat.f3d_mat.default_light_color = color
#check for param
if len(self.Types[x][2])>3:
mat.use_collision_param = True
mat.collision_param = str(self.Types[x][2][3])
x+=1
override = bpy.context.copy()
override["material"] = mat
bpy.ops.material.update_f3d_nodes(override)
p.material_index=x-1
return obj
#this will hold tile properties
class Tile():
pass
#this will hold texture properties
class Texture():
def __init__(self):
self.tile = -1
#This is simply a data storage class
class Mat():
def __init__(self):
self.TwoCycle = False
self.GeoSet = []
self.GeoClear = []
self.tiles = [Tile() for a in range(8)]
self.tex0 = None
self.tex1 = None
#calc the hash for an f3d mat and see if its equal to this mats hash
def MatHashF3d(self,f3d,textures):
#texture,1 cycle combiner, geo modes (once I implement them)
rdp = f3d.rdp_settings
if f3d.tex0.tex:
T = f3d.tex0.tex.name
else:
T = ''
F3Dprops = (T,f3d.combiner1.A,f3d.combiner1.B,f3d.combiner1.C,f3d.combiner1.D,
f3d.combiner1.A_alpha,f3d.combiner1.B_alpha,f3d.combiner1.C_alpha,f3d.combiner1.D_alpha)
if hasattr(self,'Combiner'):
MyT = ''
if hasattr(self,'Timg'):
MyT = textures.get(self.Timg)[0].split('/')[-1]
MyT=MyT.replace("#include ",'').replace('"','').replace("'",'').replace("inc.c","png")
else:
pass
MyProps = (MyT,*self.Combiner[0:8])
dupe = hash(MyProps) == hash(F3Dprops)
return dupe
return False
def MatHash(self,mat,textures):
return False
def LoadTexture(self, ForceNewTex, textures, path, tex):
Timg = textures.get(tex.Timg)[0].split('/')[-1]
Timg = Timg.replace("#include ",'').replace('"','').replace("'",'').replace("inc.c","png")
i = bpy.data.images.get(Timg)
if not i or ForceNewTex:
Timg = textures.get(tex.Timg)[0]
Timg = Timg.replace("#include ",'').replace('"','').replace("'",'').replace("inc.c","png")
#deal with duplicate pathing (such as /actors/actors etc.)
Extra = path.relative_to(Path(bpy.context.scene.decompPath))
for e in Extra.parts:
Timg = Timg.replace(e+'/','')
#deal with actor import path not working for shared textures
if 'textures' in Timg:
fp = Path(bpy.context.scene.decompPath) / Timg
else:
fp = path / Timg
return bpy.data.images.load(filepath=str(fp))
else:
return i
def ApplyPBSDFMat(self,mat,textures,path,layer):
nt = mat.node_tree
nodes = nt.nodes
links = nt.links
pbsdf = nodes.get('Principled BSDF')
tex = nodes.new("ShaderNodeTexImage")
links.new(pbsdf.inputs[0],tex.outputs[0])
links.new(pbsdf.inputs[19],tex.outputs[1])
i = self.LoadTexture(bpy.context.scene.LevelImp.ForceNewTex,textures,path)
if i:
tex.image = i
if layer>4:
mat.blend_method == 'BLEND'
def ApplyMatSettings(self,mat,textures,path,layer):
if bpy.context.scene.LevelImp.AsObj:
return self.ApplyPBSDFMat(mat,textures,path,layer)
#make combiner custom
f3d=mat.f3d_mat #This is kure's custom property class for materials
f3d.presetName="Custom"
self.SetCombiner(f3d,layer)
f3d.draw_layer.sm64 = layer
if int(layer)>4:
mat.blend_method == 'BLEND'
#I set these but they aren't properly stored because they're reset by fast64 or something
#its better to have defaults than random 2 cycles
self.SetGeoMode(f3d.rdp_settings,mat)
if self.TwoCycle:
f3d.rdp_settings.gdsft_cycletype = 'G_CYC_2CYCLE'
else:
f3d.rdp_settings.gdsft_cycletype = 'G_CYC_1CYCLE'
#Try to set an image
#texture 0 then texture 1
if self.tex0:
i = self.LoadTexture(bpy.context.scene.LevelImp.ForceNewTex,textures,path, self.tex0)
tex0 = f3d.tex0
tex0.tex_set = True
tex0.tex = i
tex0.tex_format = self.EvalFmt(self.tiles[0])
tex0.autoprop = False
Sflags = self.EvalFlags(self.tiles[0].Sflags)
for f in Sflags:
setattr(tex0.S,f,True)
Tflags = self.EvalFlags(self.tiles[0].Tflags)
for f in Sflags:
setattr(tex0.T,f,True)
tex0.S.low = self.tiles[0].Slow
tex0.T.low = self.tiles[0].Tlow
tex0.S.high = self.tiles[0].Shigh
tex0.T.high = self.tiles[0].Thigh
tex0.S.mask = eval(self.tiles[0].SMask)
tex0.T.mask = eval(self.tiles[0].TMask)
if self.tex1:
i = self.LoadTexture(bpy.context.scene.LevelImp.ForceNewTex,textures,path, self.tex1)
tex1 = f3d.tex1
tex1.tex_set = True
tex1.tex = i
tex1.tex_format = self.EvalFmt(self.tiles[1])
Sflags = self.EvalFlags(self.tiles[1].Sflags)
for f in Sflags:
setattr(tex1.S,f,True)
Tflags = self.EvalFlags(self.tiles[1].Tflags)
for f in Sflags:
setattr(tex1.T,f,True)
tex1.S.low = self.tiles[1].Slow
tex1.T.low = self.tiles[1].Tlow
tex1.S.high = self.tiles[1].Shigh
tex1.T.high = self.tiles[1].Thigh
tex1.S.mask = eval(self.tiles[0].SMask)
tex1.T.mask = eval(self.tiles[0].TMask)
#Update node values
override = bpy.context.copy()
override["material"] = mat
bpy.ops.material.update_f3d_nodes(override)
def EvalFlags(self, flags):
GBIflags = {
"G_TX_NOMIRROR": None,
"G_TX_WRAP": None,
"G_TX_MIRROR": ("mirror"),
"G_TX_CLAMP": ("clamp"),
"0": None,
"1": ("mirror"),
"2": ("clamp"),
"3": ("clamp","mirror")
}
x = []
fsplit = flags.split("|")
for f in fsplit:
z = GBIflags.get(f.strip(),0)
if z:
x.append(z)
return x
def SetGeoMode(self,rdp,mat):
for a in self.GeoSet:
try:
setattr(self,a.lower(),True)
except:
print(a.lower(),'set')
for a in self.GeoClear:
try:
setattr(self,a.lower(),False)
except:
print(a.lower(),'clear')
#Very lazy for now
def SetCombiner(self,f3d,layer):
if not hasattr(self,'Combiner'):
layer=eval(layer)
if layer<=4:
f3d.combiner1.A = 'TEXEL0'
f3d.combiner1.A_alpha = '0'
f3d.combiner1.C = 'SHADE'
f3d.combiner1.C_alpha = '0'
f3d.combiner1.D = '0'
f3d.combiner1.D_alpha = '1'
if layer==4:
f3d.combiner1.A = 'TEXEL0'
f3d.combiner1.A_alpha = 'TEXEL0'
f3d.combiner1.C = 'SHADE'
f3d.combiner1.C_alpha = 'SHADE'
f3d.combiner1.D = '0'
f3d.combiner1.D_alpha = '0'
if layer==5:
f3d.combiner1.A = 'TEXEL0'
f3d.combiner1.A_alpha = 'TEXEL0'
f3d.combiner1.C = 'SHADE'
f3d.combiner1.C_alpha = 'PRIMITIVE'
f3d.combiner1.D = '0'
f3d.combiner1.D_alpha = '0'
if layer>=6:
f3d.combiner1.A = 'TEXEL0'
f3d.combiner1.B = 'SHADE'
f3d.combiner1.A_alpha = '0'
f3d.combiner1.C = 'TEXEL0_ALPHA'
f3d.combiner1.C_alpha = '0'
f3d.combiner1.D = 'SHADE'
f3d.combiner1.D_alpha = 'ENVIRONMENT'
else:
f3d.combiner1.A = self.Combiner[0]
f3d.combiner1.B = self.Combiner[1]
f3d.combiner1.C = self.Combiner[2]
f3d.combiner1.D = self.Combiner[3]
f3d.combiner1.A_alpha = self.Combiner[4]
f3d.combiner1.B_alpha = self.Combiner[5]
f3d.combiner1.C_alpha = self.Combiner[6]
f3d.combiner1.D_alpha = self.Combiner[7]
f3d.combiner2.A = self.Combiner[8]
f3d.combiner2.B = self.Combiner[9]
f3d.combiner2.C = self.Combiner[10]
f3d.combiner2.D = self.Combiner[11]
f3d.combiner2.A_alpha = self.Combiner[12]
f3d.combiner2.B_alpha = self.Combiner[13]
f3d.combiner2.C_alpha = self.Combiner[14]
f3d.combiner2.D_alpha = self.Combiner[15]
def EvalFmt(self, tex):
GBIfmts = {
"G_IM_FMT_RGBA":"RGBA",
"G_IM_FMT_CI":"CI",
"G_IM_FMT_IA":"IA",
"G_IM_FMT_I":"I",
"0":"RGBA",
"2":"CI",
"3":"IA",
"4":"I"
}
GBIsiz = {
"G_IM_SIZ_4b":"4",
"G_IM_SIZ_8b":"8",
"G_IM_SIZ_16b":"16",
"G_IM_SIZ_32b":"32",
"0":"4",
"1":"8",
"2":"16",
"3":"32"
}
return GBIfmts.get(tex.Fmt,"RGBA")+GBIsiz.get(tex.Siz,"16")
class F3d():
def __init__(self,scene):
self.VB={}
self.Gfx={}
self.diff={}
self.amb={}
self.Lights={}
self.Textures={}
self.scene=scene
#Textures only contains the texture data found inside the model.inc.c file and the texture.inc.c file
def GetGenericTextures(self,path):
for t in ['cave.c','effect.c','fire.c','generic.c','grass.c','inside.c','machine.c','mountain.c','outside.c','sky.c','snow.c','spooky.c','water.c']:
t = path/'bin'/t
t=open(t,'r')
tex=t.readlines()
#For textures, try u8, and s16 aswell
self.Textures.update(FormatDat(tex,'Texture',[None,None]))
self.Textures.update(FormatDat(tex,'u8',[None,None]))
self.Textures.update(FormatDat(tex,'s16',[None,None]))
t.close()
#recursively parse the display list in order to return a bunch of model data
def GetDataFromModel(self,start):
DL = self.Gfx.get(start)
self.VertBuff = [0]*32 #If you're doing some fucky shit with a larger vert buffer it sucks to suck I guess
if not DL:
raise Exception("Could not find DL {}".format(start))
self.Verts = []
self.Tris = []
self.UVs = []
self.VCs = []
self.Mats = []
self.LastMat = Mat()
self.ParseDL(DL)
self.NewMat = 0
self.StartName=start
return [self.Verts,self.Tris]
def ParseDL(self,DL):
#This will be the equivalent of a giant switch case
x=-1
while(x<len(DL)):
#manaual iteration so I can skip certain children efficiently
x+=1
l=DL[x]
LsW=l.startswith
args=self.StripArgs(l)
#Deal with control flow first
if LsW('gsSPEndDisplayList'):
return
if LsW('gsSPBranchList'):
NewDL=self.Gfx.get(args[0].strip())
if not DL:
raise Exception("Could not find DL {} in levels/{}/{}leveldata.inc.c".format(NewDL,self.scene.LevelImp.Level,self.scene.LevelImp.Prefix))
self.ParseDL(NewDL)
break
if LsW('gsSPDisplayList'):
NewDL=self.Gfx.get(args[0].strip())
if not DL:
raise Exception("Could not find DL {} in levels/{}/{}leveldata.inc.c".format(NewDL,self.scene.LevelImp.Level,self.scene.LevelImp.Prefix))
self.ParseDL(NewDL)
continue
#Vertices
if LsW('gsSPVertex'):
#vertex references commonly use pointer arithmatic. I will deal with that case here, but not for other things unless it somehow becomes a problem later
if '+' in args[0]:
ref, add = args[0].split('+')
else:
ref = args[0]
add = '0'
VB = self.VB.get(ref.strip())
if not VB:
raise Exception("Could not find VB {} in levels/{}/{}leveldata.inc.c".format(ref,self.scene.LevelImp.Level,self.scene.LevelImp.Prefix))
Verts = VB[int(add.strip()):int(add.strip())+eval(args[1])] #If you use array indexing here then you deserve to have this not work
Verts = [self.ParseVert(v) for v in Verts]
for k,i in enumerate(range(eval(args[2]),eval(args[1]),1)):
self.VertBuff[i] = [Verts[k],eval(args[2])]
#These are all independent data blocks in blender
self.Verts.extend([v[0] for v in Verts])
self.UVs.extend([v[1] for v in Verts])
self.VCs.extend([v[2] for v in Verts])
self.LastLoad = eval(args[1])
continue
#Triangles
if LsW('gsSP2Triangles'):
self.MakeNewMat()
Tri1 = self.ParseTri(args[:3])
Tri2 = self.ParseTri(args[4:7])
self.Tris.append(Tri1)
self.Tris.append(Tri2)
continue
if LsW('gsSP1Triangle'):
self.MakeNewMat()
Tri = self.ParseTri(args[:3])
self.Tris.append(Tri)
continue
#materials
#Mats will be placed sequentially. The first item of the list is the triangle number
#The second is the material class
if LsW('gsSPClearGeometryMode'):
self.NewMat = 1
self.LastMat.GeoClear.append(args[0].strip())
continue
if LsW('gsSPSetGeometryMode'):
self.NewMat = 1
self.LastMat.GeoSet.append(args[0].strip())
continue
if LsW('gsSPGeometryMode'):
self.NewMat = 1
self.LastMat.GeoClear.append(args[0].strip())
self.LastMat.GeoSet.append(args[1].strip())
continue
if LsW('gsDPSetCycleType'):
self.LastMat.TwoCycle=True
continue
if LsW('gsDPSetCombineMode'):
self.NewMat = 1
self.LastMat.Combiner = self.EvalCombiner(args)
continue
if LsW('gsDPSetCombineLERP'):
self.NewMat = 1
self.LastMat.Combiner = [a.strip() for a in args]
continue
#tells us what tile the last loaded mat goes into
if LsW('gsDPLoadBlock'):
try:
tex = self.LastMat.loadtex
tile = self.EvalTile(args[0].strip())
tex.tile = tile
if tile == 7:
self.LastMat.tex0 = tex
elif tile == 6:
self.LastMat.tex1 = tex
#if loaded in block 5, it is a palette
#there shouldn't be a reason to not use these tiles
#other than something that probably won't work
#here anyway
except:
print("load block before set texture image. DL error??")
continue
if LsW('gsDPSetTextureImage'):
self.NewMat = 1
loadtex = Texture()
loadtex.Timg = args[3].strip()
loadtex.Fmt = args[0].strip()
loadtex.Siz = args[1].strip()
self.LastMat.loadtex = loadtex
continue
#catch tile size
if LsW('gsDPSetTileSize'):
tile = self.LastMat.tiles[self.EvalTile(args[0].strip())]
tile.Slow = self.EvalImFrac(args[1].strip()) / 4
tile.Tlow = self.EvalImFrac(args[2].strip()) / 4
tile.Shigh = self.EvalImFrac(args[3].strip()) / 4
tile.Thigh = self.EvalImFrac(args[4].strip()) / 4
continue
if LsW('gsDPSetTile'):
self.NewMat = 1
tile = self.LastMat.tiles[self.EvalTile(args[4].strip())]
tile.Fmt = args[0].strip()
tile.Siz = args[1].strip()
tile.Tflags = args[6].strip()
tile.TMask = args[7].strip()
tile.TShif = args[8].strip()
tile.Sflags = args[9].strip()
tile.SMask = args[10].strip()
tile.SShift = args[11].strip()
def EvalCombiner(self,arg):
#two args
GBI_CC_Macros = {
'G_CC_PRIMITIVE': ['0', '0', '0', 'PRIMITIVE', '0', '0', '0', 'PRIMITIVE'],
'G_CC_SHADE': ['0', '0', '0', 'SHADE', '0', '0', '0', 'SHADE'],
'G_CC_MODULATEI': ['TEXEL0', '0', 'SHADE', '0', '0', '0', '0', 'SHADE'],
'G_CC_MODULATEIDECALA': ['TEXEL0', '0', 'SHADE', '0', '0', '0', '0', 'TEXEL0'],
'G_CC_MODULATEIFADE': ['TEXEL0', '0', 'SHADE', '0', '0', '0', '0', 'ENVIRONMENT'],
'G_CC_MODULATERGB': ['TEXEL0', '0', 'SHADE', '0', '0', '0', '0', 'SHADE'],
'G_CC_MODULATERGBDECALA': ['TEXEL0', '0', 'SHADE', '0', '0', '0', '0', 'TEXEL0'],
'G_CC_MODULATERGBFADE': ['TEXEL0', '0', 'SHADE', '0', '0', '0', '0', 'ENVIRONMENT'],
'G_CC_MODULATEIA': ['TEXEL0', '0', 'SHADE', '0', 'TEXEL0', '0', 'SHADE', '0'],
'G_CC_MODULATEIFADEA': ['TEXEL0', '0', 'SHADE', '0', 'TEXEL0', '0', 'ENVIRONMENT', '0'],
'G_CC_MODULATEFADE': ['TEXEL0', '0', 'SHADE', '0', 'ENVIRONMENT', '0', 'TEXEL0', '0'],
'G_CC_MODULATERGBA': ['TEXEL0', '0', 'SHADE', '0', 'TEXEL0', '0', 'SHADE', '0'],
'G_CC_MODULATERGBFADEA': ['TEXEL0', '0', 'SHADE', '0', 'ENVIRONMENT', '0', 'TEXEL0', '0'],
'G_CC_MODULATEI_PRIM': ['TEXEL0', '0', 'PRIMITIVE', '0', '0', '0', '0', 'PRIMITIVE'],
'G_CC_MODULATEIA_PRIM': ['TEXEL0', '0', 'PRIMITIVE', '0', 'TEXEL0', '0', 'PRIMITIVE', '0'],
'G_CC_MODULATEIDECALA_PRIM': ['TEXEL0', '0', 'PRIMITIVE', '0', '0', '0', '0', 'TEXEL0'],
'G_CC_MODULATERGB_PRIM': ['TEXEL0', '0', 'PRIMITIVE', '0', 'TEXEL0', '0', 'PRIMITIVE', '0'],
'G_CC_MODULATERGBA_PRIM': ['TEXEL0', '0', 'PRIMITIVE', '0', 'TEXEL0', '0', 'PRIMITIVE', '0'],
'G_CC_MODULATERGBDECALA_PRIM': ['TEXEL0', '0', 'PRIMITIVE', '0', '0', '0', '0', 'TEXEL0'],
'G_CC_FADE': ['SHADE', '0', 'ENVIRONMENT', '0', 'SHADE', '0', 'ENVIRONMENT', '0'],
'G_CC_FADEA': ['TEXEL0', '0', 'ENVIRONMENT', '0', 'TEXEL0', '0', 'ENVIRONMENT', '0'],
'G_CC_DECALRGB': ['0', '0', '0', 'TEXEL0', '0', '0', '0', 'SHADE'],
'G_CC_DECALRGBA': ['0', '0', '0', 'TEXEL0', '0', '0', '0', 'TEXEL0'],
'G_CC_DECALFADE': ['0', '0', '0', 'TEXEL0', '0', '0', '0', 'ENVIRONMENT'],
'G_CC_DECALFADEA': ['0', '0', '0', 'TEXEL0', 'TEXEL0', '0', 'ENVIRONMENT', '0'],
'G_CC_BLENDI': ['ENVIRONMENT', 'SHADE', 'TEXEL0', 'SHADE', '0', '0', '0', 'SHADE'],
'G_CC_BLENDIA': ['ENVIRONMENT', 'SHADE', 'TEXEL0', 'SHADE', 'TEXEL0', '0', 'SHADE', '0'],
'G_CC_BLENDIDECALA': ['ENVIRONMENT', 'SHADE', 'TEXEL0', 'SHADE', '0', '0', '0', 'TEXEL0'],
'G_CC_BLENDRGBA': ['TEXEL0', 'SHADE', 'TEXEL0_ALPHA', 'SHADE', '0', '0', '0', 'SHADE'],
'G_CC_BLENDRGBDECALA': ['TEXEL0', 'SHADE', 'TEXEL0_ALPHA', 'SHADE', '0', '0', '0', 'TEXEL0'],
'G_CC_BLENDRGBFADEA': ['TEXEL0', 'SHADE', 'TEXEL0_ALPHA', 'SHADE', '0', '0', '0', 'ENVIRONMENT'],
'G_CC_ADDRGB': ['TEXEL0', '0', 'TEXEL0', 'SHADE', '0', '0', '0', 'SHADE'],
'G_CC_ADDRGBDECALA': ['TEXEL0', '0', 'TEXEL0', 'SHADE', '0', '0', '0', 'TEXEL0'],
'G_CC_ADDRGBFADE': ['TEXEL0', '0', 'TEXEL0', 'SHADE', '0', '0', '0', 'ENVIRONMENT'],
'G_CC_REFLECTRGB': ['ENVIRONMENT', '0', 'TEXEL0', 'SHADE', '0', '0', '0', 'SHADE'],
'G_CC_REFLECTRGBDECALA': ['ENVIRONMENT', '0', 'TEXEL0', 'SHADE', '0', '0', '0', 'TEXEL0'],
'G_CC_HILITERGB': ['PRIMITIVE', 'SHADE', 'TEXEL0', 'SHADE', '0', '0', '0', 'SHADE'],
'G_CC_HILITERGBA': ['PRIMITIVE', 'SHADE', 'TEXEL0', 'SHADE', 'PRIMITIVE', 'SHADE', 'TEXEL0', 'SHADE'],
'G_CC_HILITERGBDECALA': ['PRIMITIVE', 'SHADE', 'TEXEL0', 'SHADE', '0', '0', '0', 'TEXEL0'],
'G_CC_SHADEDECALA': ['0', '0', '0', 'SHADE', '0', '0', '0', 'TEXEL0'],
'G_CC_SHADEFADEA': ['0', '0', '0', 'SHADE', '0', '0', '0', 'ENVIRONMENT'],
'G_CC_BLENDPE': ['PRIMITIVE', 'ENVIRONMENT', 'TEXEL0', 'ENVIRONMENT', 'TEXEL0', '0', 'SHADE', '0'],
'G_CC_BLENDPEDECALA': ['PRIMITIVE', 'ENVIRONMENT', 'TEXEL0', 'ENVIRONMENT', '0', '0', '0', 'TEXEL0'],
'_G_CC_BLENDPE': ['ENVIRONMENT', 'PRIMITIVE', 'TEXEL0', 'PRIMITIVE', 'TEXEL0', '0', 'SHADE', '0'],
'_G_CC_BLENDPEDECALA': ['ENVIRONMENT', 'PRIMITIVE', 'TEXEL0', 'PRIMITIVE', '0', '0', '0', 'TEXEL0'],
'_G_CC_TWOCOLORTEX': ['PRIMITIVE', 'SHADE', 'TEXEL0', 'SHADE', '0', '0', '0', 'SHADE'],
'_G_CC_SPARSEST': ['PRIMITIVE', 'TEXEL0', 'LOD_FRACTION', 'TEXEL0', 'PRIMITIVE', 'TEXEL0', 'LOD_FRACTION', 'TEXEL0'],
'G_CC_TEMPLERP': ['TEXEL1', 'TEXEL0', 'PRIM_LOD_FRAC', 'TEXEL0', 'TEXEL1', 'TEXEL0', 'PRIM_LOD_FRAC', 'TEXEL0'],
'G_CC_TRILERP': ['TEXEL1', 'TEXEL0', 'LOD_FRACTION', 'TEXEL0', 'TEXEL1', 'TEXEL0', 'LOD_FRACTION', 'TEXEL0'],
'G_CC_INTERFERENCE': ['TEXEL0', '0', 'TEXEL1', '0', 'TEXEL0', '0', 'TEXEL1', '0'],
'G_CC_1CYUV2RGB': ['TEXEL0', 'K4', 'K5', 'TEXEL0', '0', '0', '0', 'SHADE'],
'G_CC_YUV2RGB': ['TEXEL1', 'K4', 'K5', 'TEXEL1', '0', '0', '0', '0'],
'G_CC_PASS2': ['0', '0', '0', 'COMBINED', '0', '0', '0', 'COMBINED'],
'G_CC_MODULATEI2': ['COMBINED', '0', 'SHADE', '0', '0', '0', '0', 'SHADE'],
'G_CC_MODULATEIA2': ['COMBINED', '0', 'SHADE', '0', 'COMBINED', '0', 'SHADE', '0'],
'G_CC_MODULATERGB2': ['COMBINED', '0', 'SHADE', '0', '0', '0', '0', 'SHADE'],
'G_CC_MODULATERGBA2': ['COMBINED', '0', 'SHADE', '0', 'COMBINED', '0', 'SHADE', '0'],
'G_CC_MODULATEI_PRIM2': ['COMBINED', '0', 'PRIMITIVE', '0', '0', '0', '0', 'PRIMITIVE'],
'G_CC_MODULATEIA_PRIM2': ['COMBINED', '0', 'PRIMITIVE', '0', 'COMBINED', '0', 'PRIMITIVE', '0'],
'G_CC_MODULATERGB_PRIM2': ['COMBINED', '0', 'PRIMITIVE', '0', '0', '0', '0', 'PRIMITIVE'],
'G_CC_MODULATERGBA_PRIM2': ['COMBINED', '0', 'PRIMITIVE', '0', 'COMBINED', '0', 'PRIMITIVE', '0'],
'G_CC_DECALRGB2': ['0', '0', '0', 'COMBINED', '0', '0', '0', 'SHADE'],
'G_CC_BLENDI2': ['ENVIRONMENT', 'SHADE', 'COMBINED', 'SHADE', '0', '0', '0', 'SHADE'],
'G_CC_BLENDIA2': ['ENVIRONMENT', 'SHADE', 'COMBINED', 'SHADE', 'COMBINED', '0', 'SHADE', '0'],
'G_CC_CHROMA_KEY2': ['TEXEL0', 'CENTER', 'SCALE', '0', '0', '0', '0', '0'],
'G_CC_HILITERGB2': ['ENVIRONMENT', 'COMBINED', 'TEXEL0', 'COMBINED', '0', '0', '0', 'SHADE'],
'G_CC_HILITERGBA2': ['ENVIRONMENT', 'COMBINED', 'TEXEL0', 'COMBINED', 'ENVIRONMENT', 'COMBINED', 'TEXEL0', 'COMBINED'],
'G_CC_HILITERGBDECALA2': ['ENVIRONMENT', 'COMBINED', 'TEXEL0', 'COMBINED', '0', '0', '0', 'TEXEL0'],
'G_CC_HILITERGBPASSA2': ['ENVIRONMENT', 'COMBINED', 'TEXEL0', 'COMBINED', '0', '0', '0', 'COMBINED'],
}
return GBI_CC_Macros.get(arg[0].strip(), ['TEXEL0', '0', 'SHADE', '0', 'TEXEL0', '0', 'SHADE', '0']) + \
GBI_CC_Macros.get(arg[1].strip(), ['TEXEL0', '0', 'SHADE', '0', 'TEXEL0', '0', 'SHADE', '0'])
def EvalImFrac(self, arg):
arg2 = arg.replace("G_TEXTURE_IMAGE_FRAC", "2")
return eval(arg2)
def EvalTile(self, arg):
#are ther more enums??
Tiles = {
"G_TX_LOADTILE": 7,
"G_TX_RENDERTILE": 0,
}
t = Tiles.get(arg)
if t == None:
t = int(arg)
return t
def MakeNewMat(self):
if self.NewMat:
self.NewMat = 0
self.Mats.append([len(self.Tris)-1, self.LastMat])
self.LastMat = deepcopy(self.LastMat) #for safety
def ParseVert(self,Vert):
v = Vert.replace('{','').replace('}','').split(',')
num = (lambda x: [eval(a) for a in x])
pos = num(v[:3])
uv = num(v[4:6])
vc = num(v[6:10])
return [pos,uv,vc]
def ParseTri(self,Tri):
L=len(self.Verts)
return [eval(a)+L-self.LastLoad for a in Tri]
def StripArgs(self,cmd):
a=cmd.find("(")
return cmd[a+1:-2].split(',')
def ApplyDat(self,obj,mesh,layer,path):
tris = mesh.polygons
bpy.context.view_layer.objects.active = obj
ind = -1
UVmap = obj.data.uv_layers.new(name='UVMap')
#try to make color attribute first, then do vertex color if it fails
try:
Vcol = obj.data.color_attributes.new(name='Col', type="FLOAT_COLOR", domain="CORNER")
Valph = obj.data.vertex_colors.new(name='Alpha', type="FLOAT_COLOR", domain="CORNER")
except:
Vcol = obj.data.vertex_colors.new(name = 'Col')
Valph = obj.data.vertex_colors.new(name = 'Alpha')
self.Mats.append([len(tris),0])
for i,t in enumerate(tris):
if i > self.Mats[ind+1][0]:
self.Create_new_f3d_mat(self.Mats[ind+1][1],self.Textures,mesh)
ind += 1
mat = mesh.materials[ind]
mat.name = "SM64 {} F3D Mat {}".format(self.StartName, ind)
self.Mats[ind][1].ApplyMatSettings(mat,self.Textures,path,layer)
#if somehow there is no material assigned to the triangle or something is lost
if ind != -1:
t.material_index = ind
#Get texture size or assume 32, 32 otherwise
i = mesh.materials[ind].f3d_mat.tex0.tex
if not i:
WH = (32, 32)
else:
WH = i.size
#Set UV data and Vertex Color Data
for v,l in zip(t.vertices,t.loop_indices):
uv = self.UVs[v]
vcol = self.VCs[v]
#scale verts. I just copy/pasted this from kirby tbh Idk
UVmap.data[l].uv = [a*(1/(32*b)) if b > 0 else a*.001*32 for a, b in zip(uv,WH)]
#increase vert UV pos by 1
UVmap.data[l].uv[1] -= 1
#idk why this is necessary. N64 thing or something?
UVmap.data[l].uv[1] = UVmap.data[l].uv[1]*-1
Vcol.data[l].color = [a/255 for a in vcol]