-
Notifications
You must be signed in to change notification settings - Fork 69
/
f3d_parser.py
2419 lines (2006 loc) · 97 KB
/
f3d_parser.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
from typing import Union, Optional, Callable, Any, TYPE_CHECKING
import bmesh, bpy, mathutils, re, math, traceback
from mathutils import Vector
from bpy.utils import register_class, unregister_class
from .f3d_gbi import *
from .f3d_material import (
createF3DMat,
update_preset_manual,
all_combiner_uses,
ootEnumDrawLayers,
TextureProperty,
F3DMaterialProperty,
update_node_values_of_material,
F3DMaterialHash,
)
from .f3d_writer import BufferVertex, F3DVert
from ..utility import *
import ast
from .f3d_material_helpers import F3DMaterial_UpdateLock
if TYPE_CHECKING:
from .f3d_material import RDPSettings
colorCombinationCommands = [
0x03, # load lighting data
0xB6, # clear geometry params
0xB7, # set geometry params
0xBB, # set texture scaling factor
0xF3, # set texture size
0xF5, # set texture properties
0xF7, # set fill color
0xF8, # set fog color
0xFB, # set env color
0xFC, # set color combination
0xFD, # load texture
]
drawCommands = [0x04, 0xBF] # load vertex data # draw triangle
def getAxisVector(enumValue):
sign = -1 if enumValue[0] == "-" else 1
axis = enumValue[0] if sign == 1 else enumValue[1]
return (sign if axis == "X" else 0, sign if axis == "Y" else 0, sign if axis == "Z" else 0)
def getExportRotation(forwardAxisEnum, convertTransformMatrix):
if "Z" in forwardAxisEnum:
print("Z axis reserved for verticals.")
return None
elif forwardAxisEnum == "X":
rightAxisEnum = "-Y"
elif forwardAxisEnum == "-Y":
rightAxisEnum = "-X"
elif forwardAxisEnum == "-X":
rightAxisEnum = "Y"
else:
rightAxisEnum = "X"
forwardAxis = getAxisVector(forwardAxisEnum)
rightAxis = getAxisVector(rightAxisEnum)
upAxis = (0, 0, 1)
# Z assumed to be up
columns = [rightAxis, forwardAxis, upAxis]
localToBlenderRotation = mathutils.Matrix(
[[col[0] for col in columns], [col[1] for col in columns], [col[2] for col in columns]]
).to_quaternion()
return convertTransformMatrix.to_quaternion() @ localToBlenderRotation
def F3DtoBlenderObject(romfile, startAddress, scene, newname, transformMatrix, segmentData, shadeSmooth):
mesh = bpy.data.meshes.new(newname + "-mesh")
obj = bpy.data.objects.new(newname, mesh)
scene.collection.objects.link(obj)
createBlankMaterial(obj)
bMesh = bmesh.new()
bMesh.from_mesh(mesh)
parseF3DBinary(romfile, startAddress, scene, bMesh, obj, transformMatrix, newname, segmentData, [None] * 16 * 16)
# bmesh.ops.rotate(bMesh, cent = [0,0,0],
# matrix = blenderToSM64Rotation,
# verts = bMesh.verts)
bMesh.to_mesh(mesh)
bMesh.free()
mesh.update()
if shadeSmooth:
bpy.ops.object.select_all(action="DESELECT")
obj.select_set(True)
bpy.ops.object.shade_smooth()
return obj
def cmdToPositiveInt(cmd):
return cmd if cmd >= 0 else 256 + cmd
def parseF3DBinary(romfile, startAddress, scene, bMesh, obj, transformMatrix, groupName, segmentData, vertexBuffer):
f3d = F3D("F3D")
currentAddress = startAddress
romfile.seek(currentAddress)
command = romfile.read(8)
faceSeq = bMesh.faces
vertSeq = bMesh.verts
uv_layer = bMesh.loops.layers.uv.verify()
deform_layer = bMesh.verts.layers.deform.verify()
vertexGroup = getOrMakeVertexGroup(obj, groupName)
groupIndex = vertexGroup.index
textureSize = [32, 32]
currentTextureAddr = -1
jumps = [startAddress]
# Used for remove_double op at end
vertList = []
while len(jumps) > 0:
# FD, FC, B7 (tex, shader, geomode)
# print(format(command[0], '#04x') + ' at ' + hex(currentAddress))
if command[0] == cmdToPositiveInt(f3d.G_TRI1):
try:
newVerts = interpretDrawTriangle(
command, vertexBuffer, faceSeq, vertSeq, uv_layer, deform_layer, groupIndex
)
vertList.extend(newVerts)
except TypeError:
print("Ignoring triangle from unloaded vertices.")
elif command[0] == cmdToPositiveInt(f3d.G_VTX):
interpretLoadVertices(romfile, vertexBuffer, transformMatrix, command, segmentData)
# Note: size can usually be indicated in LoadTile / LoadBlock.
elif command[0] == cmdToPositiveInt(f3d.G_SETTILESIZE):
textureSize = interpretSetTileSize(int.from_bytes(command[4:8], "big"))
elif command[0] == cmdToPositiveInt(f3d.G_DL):
if command[1] == 0:
jumps.append(currentAddress)
currentAddress = decodeSegmentedAddr(command[4:8], segmentData=segmentData)
romfile.seek(currentAddress)
command = romfile.read(8)
continue
elif command[0] == cmdToPositiveInt(f3d.G_ENDDL):
currentAddress = jumps.pop()
elif command[0] == cmdToPositiveInt(f3d.G_SETGEOMETRYMODE):
pass
elif command[0] == cmdToPositiveInt(f3d.G_SETCOMBINE):
pass
elif command[0] == cmdToPositiveInt(f3d.G_SETTIMG):
currentTextureAddr = interpretSetTImage(command, segmentData)
elif command[0] == cmdToPositiveInt(f3d.G_LOADBLOCK):
# for now only 16bit RGBA is supported.
interpretLoadBlock(command, romfile, currentTextureAddr, textureSize, "RGBA", 16)
elif command[0] == cmdToPositiveInt(f3d.G_SETTILE):
interpretSetTile(int.from_bytes(command[4:8], "big"), None)
else:
pass
# print(format(command[0], '#04x') + ' at ' + hex(currentAddress))
currentAddress += 8
romfile.seek(currentAddress)
command = romfile.read(8)
bmesh.ops.remove_doubles(bMesh, verts=vertList, dist=0.0001)
return vertexBuffer
def getPosition(vertexBuffer, index):
xStart = index * 16 + 0
yStart = index * 16 + 2
zStart = index * 16 + 4
xBytes = vertexBuffer[xStart : xStart + 2]
yBytes = vertexBuffer[yStart : yStart + 2]
zBytes = vertexBuffer[zStart : zStart + 2]
x = int.from_bytes(xBytes, "big", signed=True) / bpy.context.scene.fast64.sm64.blender_to_sm64_scale
y = int.from_bytes(yBytes, "big", signed=True) / bpy.context.scene.fast64.sm64.blender_to_sm64_scale
z = int.from_bytes(zBytes, "big", signed=True) / bpy.context.scene.fast64.sm64.blender_to_sm64_scale
return (x, y, z)
def getNormalorColor(vertexBuffer, index, isNormal=True):
xByte = bytes([vertexBuffer[index * 16 + 12]])
yByte = bytes([vertexBuffer[index * 16 + 13]])
zByte = bytes([vertexBuffer[index * 16 + 14]])
wByte = bytes([vertexBuffer[index * 16 + 15]])
if isNormal:
x = int.from_bytes(xByte, "big", signed=True)
y = int.from_bytes(yByte, "big", signed=True)
z = int.from_bytes(zByte, "big", signed=True)
return (x, y, z)
else: # vertex color
r = int.from_bytes(xByte, "big") / 255
g = int.from_bytes(yByte, "big") / 255
b = int.from_bytes(zByte, "big") / 255
a = int.from_bytes(wByte, "big") / 255
return (r, g, b, a)
def getUV(vertexBuffer, index, textureDimensions=[32, 32]):
uStart = index * 16 + 8
vStart = index * 16 + 10
uBytes = vertexBuffer[uStart : uStart + 2]
vBytes = vertexBuffer[vStart : vStart + 2]
u = int.from_bytes(uBytes, "big", signed=True) / 32
v = int.from_bytes(vBytes, "big", signed=True) / 32
# We don't know texture size, so assume 32x32.
u /= textureDimensions[0]
v /= textureDimensions[1]
v = 1 - v
return (u, v)
def interpretSetTile(data, texture):
clampMirrorFlags = bitMask(data, 18, 2)
def interpretSetTileSize(data):
hVal = bitMask(data, 0, 12)
wVal = bitMask(data, 12, 12)
height = hVal >> 2 + 1
width = wVal >> 2 + 1
return (width, height)
def interpretLoadVertices(romfile, vertexBuffer, transformMatrix, command, segmentData=None):
command = int.from_bytes(command, "big", signed=True)
numVerts = bitMask(command, 52, 4) + 1
startIndex = bitMask(command, 48, 4)
dataLength = bitMask(command, 32, 16)
segmentedAddr = bitMask(command, 0, 32)
dataStartAddr = decodeSegmentedAddr(segmentedAddr.to_bytes(4, "big"), segmentData=segmentData)
romfile.seek(dataStartAddr)
data = romfile.read(dataLength)
for i in range(numVerts):
vert = Vector(readVectorFromShorts(data, i * 16))
vert = transformMatrix @ vert
transformedVert = bytearray(6)
writeVectorToShorts(transformedVert, 0, vert)
start = (startIndex + i) * 16
vertexBuffer[start : start + 6] = transformedVert
vertexBuffer[start + 6 : start + 16] = data[i * 16 + 6 : i * 16 + 16]
# Note the divided by 0x0A, which is due to the way BF command stores indices.
# Without this the triangles are drawn incorrectly.
def interpretDrawTriangle(command, vertexBuffer, faceSeq, vertSeq, uv_layer, deform_layer, groupIndex):
verts = [None, None, None]
index0 = int(command[5] / 0x0A)
index1 = int(command[6] / 0x0A)
index2 = int(command[7] / 0x0A)
vert0 = Vector(getPosition(vertexBuffer, index0))
vert1 = Vector(getPosition(vertexBuffer, index1))
vert2 = Vector(getPosition(vertexBuffer, index2))
verts[0] = vertSeq.new(vert0)
verts[1] = vertSeq.new(vert1)
verts[2] = vertSeq.new(vert2)
tri = faceSeq.new(verts)
# Assign vertex group
for vert in tri.verts:
vert[deform_layer][groupIndex] = 1
loopIndex = 0
for loop in tri.loops:
loop[uv_layer].uv = Vector(getUV(vertexBuffer, int(command[5 + loopIndex] / 0x0A)))
loopIndex += 1
return verts
def interpretSetTImage(command, levelData):
segmentedAddr = command[4:8]
return decodeSegmentedAddr(segmentedAddr, levelData)
def interpretLoadBlock(command, romfile, textureStart, textureSize, colorFormat, colorDepth):
numTexels = ((int.from_bytes(command[6:8], "big")) >> 12) + 1
# This is currently broken.
# createNewTextureMaterial(romfile, textureStart, textureSize, numTexels, colorFormat, colorDepth, obj)
def printvbuf(vertexBuffer):
for i in range(0, int(len(vertexBuffer) / 16)):
print(getPosition(vertexBuffer, i))
print(getNormalorColor(vertexBuffer, i))
print(getUV(vertexBuffer, i))
def createBlankMaterial(obj):
material = createF3DMat(obj)
update_preset_manual(material, bpy.context)
def createNewTextureMaterial(romfile, textureStart, textureSize, texelCount, colorFormat, colorDepth, obj):
newMat = bpy.data.materials.new("f3d_material")
newTex = bpy.data.textures.new("f3d_texture", "IMAGE")
newImg = bpy.data.images.new("f3d_texture", *textureSize, True, True)
newTex.image = newImg
newSlot = newMat.texture_slots.add()
newSlot.texture = newTex
obj.data.materials.append(newMat)
romfile.seek(textureStart)
texelSize = int(colorDepth / 8)
dataLength = texelCount * texelSize
textureData = romfile.read(dataLength)
if colorDepth != 16:
print("Warning: Only 16bit RGBA supported, input was " + str(colorDepth) + "bit " + colorFormat)
else:
print(str(texelSize) + " " + str(colorDepth))
for n in range(0, dataLength, texelSize):
oldPixel = textureData[n : n + texelSize]
newImg.pixels[n : n + 4] = read16bitRGBA(int.from_bytes(oldPixel, "big"))
def math_eval(s, f3d):
if isinstance(s, int):
return s
s = s.strip()
node = ast.parse(s, mode="eval")
def _eval(node):
if isinstance(node, ast.Expression):
return _eval(node.body)
elif isinstance(node, ast.Str):
return node.s
elif isinstance(node, ast.Name):
if hasattr(f3d, node.id):
return getattr(f3d, node.id)
else:
return node.id
elif isinstance(node, ast.Num):
return node.n
elif isinstance(node, ast.UnaryOp):
if isinstance(node.op, ast.USub):
return -1 * _eval(node.operand)
elif isinstance(node.op, ast.Invert):
return ~_eval(node.operand)
else:
raise Exception("Unsupported type {}".format(node.op))
elif isinstance(node, ast.BinOp):
return binOps[type(node.op)](_eval(node.left), _eval(node.right))
elif isinstance(node, ast.Call):
args = list(map(_eval, node.args))
funcName = _eval(node.func)
return funcName(*args)
else:
raise Exception("Unsupported type {}".format(node))
return _eval(node.body)
def bytesToNormal(normal):
return [int.from_bytes([round(value)], "big", signed=True) / 128 if value > 0 else value / 128 for value in normal]
def getTileFormat(value, f3d):
data = math_eval(value, f3d)
return ["G_IM_FMT_RGBA", "G_IM_FMT_YUV", "G_IM_FMT_CI", "G_IM_FMT_IA", "G_IM_FMT_I"][data]
def getTileSize(value, f3d):
data = math_eval(value, f3d)
return ["G_IM_SIZ_4b", "G_IM_SIZ_8b", "G_IM_SIZ_16b", "G_IM_SIZ_32b", "G_IM_SIZ_32b", "G_IM_SIZ_DD"][data]
def getTileClampMirror(value, f3d):
data = math_eval(value, f3d)
return [(data & f3d.G_TX_CLAMP) != 0, (data & f3d.G_TX_MIRROR) != 0]
def getTileMask(value, f3d):
data = math_eval(value, f3d)
return data
def getTileShift(value, f3d):
data = math_eval(value, f3d)
if data > 10:
return data - 16
else:
return data
def renderModeMask(rendermode, cycle, blendOnly):
nonBlend = (((1 << 13) - 1) << 3) if not blendOnly else 0
if cycle == 1:
return rendermode & (3 << 30 | 3 << 26 | 3 << 22 | 3 << 18 | nonBlend)
else:
return rendermode & (3 << 28 | 3 << 24 | 3 << 20 | 3 << 16 | nonBlend)
def convertF3DUV(value, maxSize):
try:
valueBytes = int.to_bytes(round(value), 2, "big", signed=True)
except OverflowError:
valueBytes = int.to_bytes(round(value), 2, "big", signed=False)
return ((int.from_bytes(valueBytes, "big", signed=True) / 32) + 0.5) / (maxSize if maxSize > 0 else 1)
class F3DTextureReference:
def __init__(self, name, width):
self.name = name
self.width = width
class F3DParsedCommands:
def __init__(self, name: str, commands: "list[ParsedMacro]", index: int):
self.name = name
self.commands = commands
self.index = index
def currentCommand(self):
return self.commands[self.index]
class F3DContext:
def __init__(self, f3d: F3D, basePath: str, materialContext: bpy.types.Material):
self.f3d: F3D = f3d
self.basePath: str = basePath
self.materialContext: bpy.types.Material = materialContext
self.materialContext.f3d_update_flag = True # Don't want visual updates while parsing
# If this is not disabled, then tex_scale will auto-update on manual node update.
self.materialContext.f3d_mat.scale_autoprop = False
self.initContext()
# This is separate as we want to call __init__ in clearGeometry, but don't want same behaviour for child classes
def initContext(self):
self.vertexBuffer: list[None | BufferVertex] = [None] * self.f3d.vert_load_size
self.clearMaterial()
mat: F3DMaterialProperty = self.mat()
mat.set_combiner = False
self.materials: list[bpy.types.Material] = [] # current material list
self.materialDict: dict[F3DMaterialHash, bpy.types.Material] = {} # cached materials for all imports
self.triMatIndices: list[int] = [] # material indices per triangle
self.materialChanged: bool = True # indicates if the material changed since the last triangle
self.lastMaterialIndex: bool = None
self.vertexData: dict[str, list[F3DVert]] = {} # c name : parsed data
self.textureData: dict[str, bpy.types.Image] = {} # c name : blender texture
self.tlutAppliedTextures: str = [] # c name
self.currentTextureName: str | None = None
self.imagesDontApplyTlut: set[bpy.types.Image] = set() # image
# Determines if images in CI formats loaded from png files,
# should have the TLUT set by the dlist applied on top of them (False),
# or if the image file should just be loaded as is with no further change (True)
# OoT64 and SM64 stores CI images as pngs in actual colors (with the TLUT accounted for),
# So for now this can be always True.
# In the future this could be an option if for example pngs for CI images were grayscale to represent the palette index.
self.ciImageFilesStoredAsFullColor: bool = True # determines whether to apply tlut to file or import as is
# This macro has all the tile setting properties, so we reuse it
self.tileSettings: list[DPSetTile] = [
DPSetTile("G_IM_FMT_RGBA", "G_IM_SIZ_16b", 5, 0, i, 0, [False, False], 0, 0, [False, False], 0, 0)
for i in range(8)
]
self.tileSizes: list[DPSetTileSize] = [DPSetTileSize(i, 0, 0, 32, 32) for i in range(8)]
# When a tile is loaded, store dict of tmem : texture name
self.tmemDict: dict[int, str] = {}
# This should be modified before parsing f3d
self.matrixData: dict[str, mathutils.Matrix] = {} # bone name : matrix
self.currentTransformName: str | None = None
self.limbToBoneName: dict[str, str] = {} # limb name (c variable) : bone name (blender vertex group)
# data for Mesh.from_pydata, list of BufferVertex tuples
# use BufferVertex to also form uvs / normals / colors
self.verts: list[F3DVert] = []
self.limbGroups: dict[str, list[int]] = {} # dict of groupName : vertex indices
self.lights: Lights = Lights("lights_context", self.f3d)
# Here these are ints, but when parsing the values will be normalized.
self.lights.l = [
Light([0, 0, 0], [0x49, 0x49, 0x49]),
Light([0, 0, 0], [0x49, 0x49, 0x49]),
Light([0, 0, 0], [0x49, 0x49, 0x49]),
Light([0, 0, 0], [0x49, 0x49, 0x49]),
Light([0, 0, 0], [0x49, 0x49, 0x49]),
Light([0, 0, 0], [0x49, 0x49, 0x49]),
Light([0, 0, 0], [0x49, 0x49, 0x49]),
]
self.lights.a = Ambient([0, 0, 0])
self.numLights: int = 0
self.lightData: dict[Light, bpy.types.Object] = {} # Light : blender light object
"""
Restarts context, but keeps cached materials/textures.
Warning: calls initContext, make sure to save/restore preserved fields
"""
def clearGeometry(self):
savedMaterialDict = self.materialDict
savedTextureData = self.textureData
savedTlutAppliedTextures = self.tlutAppliedTextures
savedImagesDontApplyTlut = self.imagesDontApplyTlut
savedLightData = self.lightData
self.initContext()
self.materialDict = savedMaterialDict
self.textureData = savedTextureData
self.tlutAppliedTextures = savedTlutAppliedTextures
self.imagesDontApplyTlut = savedImagesDontApplyTlut
self.lightData = savedLightData
def clearMaterial(self):
mat = self.mat()
mat.set_prim = False
mat.set_lights = False
mat.set_env = False
mat.set_blend = False
mat.set_key = False
mat.set_k0_5 = False
for i in range(1, 8):
setattr(mat, "f3d_light" + str(i), None)
mat.tex0.tex = None
mat.tex1.tex = None
mat.tex0.tex_set = False
mat.tex1.tex_set = False
mat.tex0.autoprop = False
mat.tex1.autoprop = False
mat.tex0.tex_format = "RGBA16"
mat.tex1.tex_format = "RGBA16"
self.tmemDict = {}
self.tileSettings = [
DPSetTile("G_IM_FMT_RGBA", "G_IM_SIZ_16b", 5, 0, i, 0, [False, False], 0, 0, [False, False], 0, 0)
for i in range(8)
]
self.tileSizes = [DPSetTileSize(i, 0, 0, 32, 32) for i in range(8)]
self.lights = Lights("lights_context", self.f3d)
self.lights.l = [
Light([0, 0, 0], [0x49, 0x49, 0x49]),
Light([0, 0, 0], [0x49, 0x49, 0x49]),
Light([0, 0, 0], [0x49, 0x49, 0x49]),
Light([0, 0, 0], [0x49, 0x49, 0x49]),
Light([0, 0, 0], [0x49, 0x49, 0x49]),
Light([0, 0, 0], [0x49, 0x49, 0x49]),
Light([0, 0, 0], [0x49, 0x49, 0x49]),
]
self.lights.a = Ambient([0, 0, 0])
self.numLights = 0
mat.presetName = "Custom"
def mat(self) -> F3DMaterialProperty:
return self.materialContext.f3d_mat
def vertexFormatPatterns(self, data):
# position, uv, color/normal
return [
# decomp format
"\{\s*\{\s*"
+ "\{([^,\}]*),([^,\}]*),([^,\}]*)\}\s*,"
+ "([^,\}]*),\s*"
+ "\{([^,\}]*),([^,\}]*)\}\s*,\s*"
+ "\{([^,\}]*),([^,\}]*),([^,\}]*),([^,\}]*)\}\s*"
+ "\}\s*\}",
# nusys format
"\{\s*"
+ "([^,\}]*),([^,\}]*),([^,\}]*),"
+ "([^,\}]*),"
+ "([^,\}]*),([^,\}]*),"
+ "([^,\}]*),([^,\}]*),([^,\}]*),([^,\}]*)\s*"
+ "\}",
]
def addMatrix(self, name, matrix):
self.matrixData[name] = matrix
self.limbToBoneName[name] = name
# For game specific instance, override this to be able to identify which verts belong to which bone.
def setCurrentTransform(self, name, flagList="G_MTX_NOPUSH | G_MTX_LOAD | G_MTX_MODELVIEW"):
flags = [value.strip() for value in flagList.split("|")]
if "G_MTX_MUL" in flags:
tempName = name + "_x_" + str(self.currentTransformName)
self.addMatrix(tempName, self.matrixData[name] @ self.matrixData[self.currentTransformName])
self.limbToBoneName[tempName] = tempName
self.currentTransformName = tempName
else:
self.currentTransformName = name
def getTransformedVertex(self, index: int):
bufferVert = self.vertexBuffer[index]
# NOTE: The groupIndex here does NOT correspond to a vertex group, but to the name of the limb (c variable)
matrixName = bufferVert.groupIndex
if matrixName in self.matrixData:
transform = self.matrixData[matrixName]
else:
print(self.matrixData)
raise PluginError("Transform matrix not specified for " + matrixName)
mat = self.mat()
f3dVert = bufferVert.f3dVert
position = transform @ Vector(f3dVert.position)
if mat.tex0.tex is not None:
texDimensions = mat.tex0.tex.size
elif mat.tex0.use_tex_reference:
texDimensions = mat.tex0.tex_reference_size
elif mat.tex1.tex is not None:
texDimensions = mat.tex1.tex.size
elif mat.tex1.use_tex_reference:
texDimensions = mat.tex1.tex_reference_size
else:
texDimensions = [32, 32]
uv = [convertF3DUV(f3dVert.uv[i], texDimensions[i]) for i in range(2)]
uv[1] = 1 - uv[1]
has_rgb, has_normal, has_packed_normals = getRgbNormalSettings(self.mat())
rgb = Vector([v / 0xFF for v in f3dVert.rgb]) if has_rgb else Vector([1.0, 1.0, 1.0])
alpha = f3dVert.alpha / 0xFF
normal = Vector([0.0, 0.0, 0.0]) # Zero normal makes normals_split_custom_set use auto
if has_normal:
if has_packed_normals:
normal = f3dVert.normal
else:
normal = Vector([v - 0x100 if v >= 0x80 else v for v in f3dVert.rgb]).normalized()
normal = (transform.inverted().transposed() @ normal).normalized()
# NOTE: The groupIndex here does NOT correspond to a vertex group, but to the name of the limb (c variable)
return BufferVertex(F3DVert(position, uv, rgb, normal, alpha), bufferVert.groupIndex, bufferVert.materialIndex)
def addVertices(self, num, start, vertexDataName, vertexDataOffset):
vertexData = self.vertexData[vertexDataName]
# TODO: material index not important?
count = math_eval(num, self.f3d)
start = math_eval(start, self.f3d)
if start + count > len(self.vertexBuffer):
raise PluginError(
"Vertex buffer of size "
+ str(len(self.vertexBuffer))
+ " too small, attempting load into "
+ str(start)
+ ", "
+ str(start + count)
)
if vertexDataOffset + count > len(vertexData):
raise PluginError(
f"Attempted to read vertex data out of bounds.\n"
f"{vertexDataName} is of size {len(vertexData)}, "
f"attemped read from ({vertexDataOffset}, {vertexDataOffset + count})"
)
for i in range(count):
self.vertexBuffer[start + i] = BufferVertex(vertexData[vertexDataOffset + i], self.currentTransformName, 0)
def addTriangle(self, indices, dlData):
if self.materialChanged:
region = None
tileSettings = self.tileSettings[0]
tileSizeSettings = self.tileSizes[0]
if tileSettings.tmem in self.tmemDict:
textureName = self.tmemDict[tileSettings.tmem]
self.loadTexture(dlData, textureName, region, tileSettings, False)
self.applyTileToMaterial(0, tileSettings, tileSizeSettings, dlData)
tileSettings = self.tileSettings[1]
tileSizeSettings = self.tileSizes[1]
if tileSettings.tmem in self.tmemDict:
textureName = self.tmemDict[tileSettings.tmem]
self.loadTexture(dlData, textureName, region, tileSettings, False)
self.applyTileToMaterial(1, tileSettings, tileSizeSettings, dlData)
self.applyLights()
self.lastMaterialIndex = self.getMaterialIndex()
self.materialChanged = False
verts = [self.getTransformedVertex(math_eval(index, self.f3d)) for index in indices]
# if verts[0].groupIndex != verts[1].groupIndex or\
# verts[0].groupIndex != verts[2].groupIndex or\
# verts[2].groupIndex != verts[1].groupIndex:
# return
for i in range(len(verts)):
vert = verts[i]
# NOTE: The groupIndex here does NOT correspond to a vertex group, but to the name of the limb (c variable)
if vert.groupIndex not in self.limbGroups:
self.limbGroups[vert.groupIndex] = []
self.limbGroups[vert.groupIndex].append(len(self.verts) + i)
self.verts.extend([vert.f3dVert for vert in verts])
for i in range(int(len(indices) / 3)):
self.triMatIndices.append(self.lastMaterialIndex)
# Add items to this tuple in child classes
def getMaterialKey(self, material: bpy.types.Material):
return material.f3d_mat.key()
def getMaterialIndex(self):
key = self.getMaterialKey(self.materialContext)
if key in self.materialDict:
material = self.materialDict[key]
if material in self.materials:
return self.materials.index(material)
else:
self.materials.append(material)
return len(self.materials) - 1
self.addMaterial()
return len(self.materials) - 1
def getImageName(self, image):
for name, otherImage in self.textureData.items():
if image == otherImage:
return name
return None
# override this to handle applying tlut to other texture
# ex. in oot, apply to flipbook textures
def handleApplyTLUT(
self,
material: bpy.types.Material,
texProp: TextureProperty,
tlut: bpy.types.Image,
index: int,
):
self.applyTLUT(texProp.tex, tlut)
self.tlutAppliedTextures.append(texProp.tex)
# we only want to apply tlut to an existing image under specific conditions.
# however we always want to record the changing tlut for texture references.
def applyTLUTToIndex(self, index):
mat = self.mat()
texProp = getattr(mat, "tex" + str(index))
combinerUses = all_combiner_uses(mat)
if texProp.tex_format[:2] == "CI":
# Only handles TLUT at 256
tlutName = self.tmemDict[256]
if 256 in self.tmemDict and tlutName is not None:
tlut = self.textureData[tlutName]
# print(f"TLUT: {tlutName}, {isinstance(tlut, F3DTextureReference)}")
if isinstance(tlut, F3DTextureReference) or texProp.use_tex_reference:
if not texProp.use_tex_reference:
texProp.use_tex_reference = True
imageName = self.getImageName(texProp.tex)
if imageName is not None:
texProp.tex_reference = imageName
else:
print("Cannot find name of texture " + str(texProp.tex))
if isinstance(tlut, F3DTextureReference):
texProp.pal_reference = tlut.name
texProp.pal_reference_size = tlut.width
else:
texProp.pal_reference = tlutName
texProp.pal_reference_size = min(tlut.size[0] * tlut.size[1], 256)
if (
not isinstance(tlut, F3DTextureReference)
and combinerUses["Texture " + str(index)]
and (texProp.tex is not None)
and texProp.tex_set
and (texProp.tex not in self.tlutAppliedTextures or texProp.use_tex_reference)
and (
texProp.tex not in self.imagesDontApplyTlut or not self.ciImageFilesStoredAsFullColor
) # oot currently stores CI textures in full color pngs
):
# print(f"Apply tlut {tlutName} ({str(tlut)}) to {self.getImageName(texProp.tex)}")
# print(f"Size: {str(tlut.size[0])} x {str(tlut.size[1])}, Data: {str(len(tlut.pixels))}")
self.handleApplyTLUT(self.materialContext, texProp, tlut, index)
else:
print("Ignoring TLUT.")
def addMaterial(self):
self.applyTLUTToIndex(0)
self.applyTLUTToIndex(1)
materialCopy = self.materialContext.copy()
# disable flag so that we can lock it, then unlock after update
materialCopy.f3d_update_flag = False
with F3DMaterial_UpdateLock(materialCopy) as material:
assert material is not None
update_node_values_of_material(material, bpy.context)
material.f3d_mat.presetName = "Custom"
self.materials.append(materialCopy)
self.materialDict[self.getMaterialKey(materialCopy)] = materialCopy
def getSizeMacro(self, size: str, suffix: str):
if hasattr(self.f3d, size):
return getattr(self.f3d, size + suffix)
else:
return getattr(self.f3d, self.f3d.IM_SIZ[size] + suffix)
def getImagePathFromInclude(self, path):
if self.basePath is None:
raise PluginError("Cannot load texture from " + path + " without any provided base path.")
imagePathRelative = path[:-5] + "png"
imagePath = os.path.join(self.basePath, imagePathRelative)
# handle custom imports, where relative paths don't make sense
if not os.path.exists(imagePath):
imagePath = os.path.join(self.basePath, os.path.basename(imagePathRelative))
return imagePath
def getVTXPathFromInclude(self, path):
if self.basePath is None:
raise PluginError("Cannot load VTX from " + path + " without any provided base path.")
vtxPath = os.path.join(self.basePath, path)
# handle custom imports, where relative paths don't make sense
if not os.path.exists(vtxPath):
vtxPath = os.path.join(self.basePath, os.path.basename(path))
return vtxPath
def setGeoFlags(self, command: "ParsedMacro", value: bool):
mat = self.mat()
bitFlags = math_eval(command.params[0], self.f3d)
rdp_settings: "RDPSettings" = mat.rdp_settings
if bitFlags & self.f3d.G_ZBUFFER:
rdp_settings.g_zbuffer = value
if bitFlags & self.f3d.G_SHADE:
rdp_settings.g_shade = value
if bitFlags & self.f3d.G_CULL_FRONT:
rdp_settings.g_cull_front = value
if bitFlags & self.f3d.G_CULL_BACK:
rdp_settings.g_cull_back = value
if self.f3d.F3DEX_GBI_3:
if bitFlags & self.f3d.G_AMBOCCLUSION:
rdp_settings.g_ambocclusion = value
if bitFlags & self.f3d.G_ATTROFFSET_Z_ENABLE:
rdp_settings.g_attroffset_z_enable = value
if bitFlags & self.f3d.G_ATTROFFSET_ST_ENABLE:
rdp_settings.g_attroffset_st_enable = value
if bitFlags & self.f3d.G_PACKED_NORMALS:
rdp_settings.g_packed_normals = value
if bitFlags & self.f3d.G_LIGHTTOALPHA:
rdp_settings.g_lighttoalpha = value
if bitFlags & self.f3d.G_LIGHTING_SPECULAR:
rdp_settings.g_lighting_specular = value
if bitFlags & self.f3d.G_FRESNEL_COLOR:
rdp_settings.g_fresnel_color = value
if bitFlags & self.f3d.G_FRESNEL_ALPHA:
rdp_settings.g_fresnel_alpha = value
if bitFlags & self.f3d.G_FOG:
rdp_settings.g_fog = value
if bitFlags & self.f3d.G_LIGHTING:
rdp_settings.g_lighting = value
if bitFlags & self.f3d.G_TEXTURE_GEN:
rdp_settings.g_tex_gen = value
if bitFlags & self.f3d.G_TEXTURE_GEN_LINEAR:
rdp_settings.g_tex_gen_linear = value
if bitFlags & self.f3d.G_LOD:
rdp_settings.g_lod = value
if bitFlags & self.f3d.G_SHADING_SMOOTH:
rdp_settings.g_shade_smooth = value
if bitFlags & self.f3d.G_CLIPPING:
rdp_settings.g_clipping = value
def loadGeoFlags(self, command: "ParsedMacro"):
mat = self.mat()
bitFlags = math_eval(command.params[0], self.f3d)
rdp_settings: "RDPSettings" = mat.rdp_settings
rdp_settings.g_zbuffer = bitFlags & self.f3d.G_ZBUFFER != 0
rdp_settings.g_shade = bitFlags & self.f3d.G_SHADE != 0
rdp_settings.g_cull_front = bitFlags & self.f3d.G_CULL_FRONT != 0
rdp_settings.g_cull_back = bitFlags & self.f3d.G_CULL_BACK != 0
if self.f3d.F3DEX_GBI_3:
rdp_settings.g_ambocclusion = bitFlags & self.f3d.G_AMBOCCLUSION != 0
rdp_settings.g_attroffset_z_enable = bitFlags & self.f3d.G_ATTROFFSET_Z_ENABLE != 0
rdp_settings.g_attroffset_st_enable = bitFlags & self.f3d.G_ATTROFFSET_ST_ENABLE != 0
rdp_settings.g_packed_normals = bitFlags & self.f3d.G_PACKED_NORMALS != 0
rdp_settings.g_lighttoalpha = bitFlags & self.f3d.G_LIGHTTOALPHA != 0
rdp_settings.g_lighting_specular = bitFlags & self.f3d.G_LIGHTING_SPECULAR != 0
rdp_settings.g_fresnel_color = bitFlags & self.f3d.G_FRESNEL_COLOR != 0
rdp_settings.g_fresnel_alpha = bitFlags & self.f3d.G_FRESNEL_ALPHA != 0
else:
rdp_settings.g_ambocclusion = False
rdp_settings.g_attroffset_z_enable = False
rdp_settings.g_attroffset_st_enable = False
rdp_settings.g_packed_normals = False
rdp_settings.g_lighttoalpha = False
rdp_settings.g_lighting_specular = False
rdp_settings.g_fresnel_color = False
rdp_settings.g_fresnel_alpha = False
rdp_settings.g_fog = bitFlags & self.f3d.G_FOG != 0
rdp_settings.g_lighting = bitFlags & self.f3d.G_LIGHTING != 0
rdp_settings.g_tex_gen = bitFlags & self.f3d.G_TEXTURE_GEN != 0
rdp_settings.g_tex_gen_linear = bitFlags & self.f3d.G_TEXTURE_GEN_LINEAR != 0
rdp_settings.g_lod = bitFlags & self.f3d.G_LOD != 0
rdp_settings.g_shade_smooth = bitFlags & self.f3d.G_SHADING_SMOOTH != 0
rdp_settings.g_clipping = bitFlags & self.f3d.G_CLIPPING != 0
def setCombineLerp(self, lerp0, lerp1):
mat = self.mat()
if len(lerp0) < 8 or len(lerp1) < 8:
print("Incorrect combiner param count: " + str(lerp0) + " " + str(lerp1))
return
lerp0 = [value.strip() for value in lerp0]
lerp1 = [value.strip() for value in lerp1]
# Padding since index can go up to 31
combinerAList = ["COMBINED", "TEXEL0", "TEXEL1", "PRIMITIVE", "SHADE", "ENVIRONMENT", "1", "NOISE"] + ["0"] * 24
combinerBList = ["COMBINED", "TEXEL0", "TEXEL1", "PRIMITIVE", "SHADE", "ENVIRONMENT", "CENTER", "K4"] + [
"0"
] * 24
combinerCList = [
"COMBINED",
"TEXEL0",
"TEXEL1",
"PRIMITIVE",
"SHADE",
"ENVIRONMENT",
"SCALE",
"COMBINED_ALPHA",
"TEXEL0_ALPHA",
"TEXEL1_ALPHA",
"PRIMITIVE_ALPHA",
"SHADE_ALPHA",
"ENV_ALPHA",
"LOD_FRACTION",
"PRIM_LOD_FRAC",
"K5",
] + ["0"] * 16
combinerDList = ["COMBINED", "TEXEL0", "TEXEL1", "PRIMITIVE", "SHADE", "ENVIRONMENT", "1", "0"] + ["0"] * 24
combinerAAlphaList = ["COMBINED", "TEXEL0", "TEXEL1", "PRIMITIVE", "SHADE", "ENVIRONMENT", "1", "0"]
combinerBAlphaList = ["COMBINED", "TEXEL0", "TEXEL1", "PRIMITIVE", "SHADE", "ENVIRONMENT", "1", "0"]
combinerCAlphaList = [
"LOD_FRACTION",
"TEXEL0",
"TEXEL1",
"PRIMITIVE",
"SHADE",
"ENVIRONMENT",
"PRIM_LOD_FRAC",
"0",
]
combinerDAlphaList = ["COMBINED", "TEXEL0", "TEXEL1", "PRIMITIVE", "SHADE", "ENVIRONMENT", "1", "0"]
for i in range(0, 4):
lerp0[i] = math_eval("G_CCMUX_" + lerp0[i], self.f3d)