-
Notifications
You must be signed in to change notification settings - Fork 18
/
m3export.py
2815 lines (2448 loc) · 147 KB
/
m3export.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
#!/usr/bin/python3
# -*- coding: utf-8 -*-
# ##### BEGIN GPL LICENSE BLOCK #####
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software Foundation,
# Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
# ##### END GPL LICENSE BLOCK #####
from typing import Iterable, List, Dict
from . import m3
from . import shared
from .shared import ExportError
from . import cm
from .common import mlog
import bpy
import mathutils
import os.path
import time
import math
actionTypeScene = "SCENE"
actionTypeArmature = "OBJECT"
class ExportErrorMODLVersionInsufficient(ExportError):
def __init__(self, minVersion: int, cause: str = None):
super().__init__(f'Unable to export in choosen version of m3 container, try version {minVersion} or higher. Reason: {cause}.')
class Exporter:
def __init__(self, scene: bpy.types.Scene, operator: bpy.types.Operator):
self.scene = scene
self.operator = operator
def export(self, m3FileName):
self.initStructureVersionMap()
self.selectAnimationsForExport()
self.isAnimationExport = m3FileName.endswith(".m3a")
if bpy.ops.object.mode_set.poll():
bpy.ops.object.mode_set(mode='OBJECT')
self.generatedAnimIdCounter = 0
self.boundingAnimId = 0x1f9bd2
if self.scene.render.fps != 30:
print("Warning: The currently configured frame rate is %s. For compability the model will be exported with a frame rate of 30." % self.scene.render.fps)
self.boneIndexToDefaultAbsoluteMatrixMap = {}
self.animationNameToFrameToBoneIndexToAbsoluteMatrixMap = {}
self.prepareAnimIdMaps()
self.nameToAnimIdToAnimDataMap = {}
self.restPositionsOfExportedBones = []
for animationIndex in self.animationIndicesToExport:
animation = self.scene.m3_animations[animationIndex]
if animation.name in self.nameToAnimIdToAnimDataMap:
raise ExportError("Animations must have unique names. Use number suffixes like 'Stand 01' and 'Stand 02'")
self.nameToAnimIdToAnimDataMap[animation.name] = {}
self.initOldReferenceIndicesInCorrectedOrder()
self.initMaterialNameToNewReferenceIndexMap()
model = self.createModel(m3FileName)
m3.saveAndInvalidateModel(model, m3FileName)
def initStructureVersionMap(self):
self.structureVersionMap = {}
if self.scene.m3_export_options.modlVersion == "29":
self.structureVersionMap["MODL"] = 29
self.structureVersionMap["EVNT"] = 2
self.structureVersionMap["SEQS"] = 2
self.structureVersionMap["LAYR"] = 26
self.structureVersionMap["MAT_"] = 20
self.structureVersionMap["PAR_"] = 24
self.structureVersionMap["PROJ"] = 5
self.structureVersionMap["PHSH"] = 3
self.structureVersionMap["PHRB"] = 4
self.structureVersionMap["RIB_"] = 9
elif self.scene.m3_export_options.modlVersion == "26":
self.structureVersionMap["MODL"] = 26
self.structureVersionMap["EVNT"] = 2
self.structureVersionMap["SEQS"] = 2
self.structureVersionMap["LAYR"] = 25
self.structureVersionMap["MAT_"] = 18
self.structureVersionMap["PAR_"] = 23
self.structureVersionMap["PROJ"] = 5
self.structureVersionMap["PHSH"] = 3
self.structureVersionMap["PHRB"] = 4
self.structureVersionMap["RIB_"] = 8
elif self.scene.m3_export_options.modlVersion == "23":
self.structureVersionMap["MODL"] = 23
self.structureVersionMap["EVNT"] = 1
self.structureVersionMap["SEQS"] = 1
self.structureVersionMap["LAYR"] = 22
self.structureVersionMap["MAT_"] = 15
self.structureVersionMap["PAR_"] = 12
self.structureVersionMap["PROJ"] = 4
self.structureVersionMap["PHSH"] = 1
self.structureVersionMap["PHRB"] = 2
self.structureVersionMap["RIB_"] = 6
else:
raise ExportError('Unsupported M3 container: V%s' % self.scene.m3_export_options.modlVersion)
self.structureVersionMap["BONE"] = 1
self.structureVersionMap["Vector3AnimationReference"] = 0
self.structureVersionMap["QuaternionAnimationReference"] = 0
self.structureVersionMap["SD3V"] = 0
self.structureVersionMap["SD4Q"] = 0
self.structureVersionMap["SD3V"] = 0
self.structureVersionMap["SDEV"] = 0
self.structureVersionMap["SDU6"] = 0
self.structureVersionMap["VertexFormat0x182027d"] = 0
self.structureVersionMap["VertexFormat0x182007d"] = 0
self.structureVersionMap["VertexFormat0x186007d"] = 0
self.structureVersionMap["VertexFormat0x186027d"] = 0
self.structureVersionMap["VertexFormat0x18e007d"] = 0
self.structureVersionMap["VertexFormat0x19e007d"] = 0
self.structureVersionMap["DIV_"] = 2
self.structureVersionMap["REGN"] = 3
self.structureVersionMap["BAT_"] = 1
self.structureVersionMap["Vector3As3Fixed8"] = 0
self.structureVersionMap["Vector2As2int16"] = 0
self.structureVersionMap["STG_"] = 0
self.structureVersionMap["STC_"] = 4
self.structureVersionMap["STS_"] = 0
self.structureVersionMap["CAM_"] = 3
self.structureVersionMap["SSGS"] = 1
self.structureVersionMap["PARC"] = 0
self.structureVersionMap["FOR_"] = 1
self.structureVersionMap["LITE"] = 7
self.structureVersionMap["BBSC"] = 0
self.structureVersionMap["ATT_"] = 1
self.structureVersionMap["ATVL"] = 0
self.structureVersionMap["COL"] = 0
self.structureVersionMap["Matrix44"] = 0
self.structureVersionMap["IREF"] = 0
self.structureVersionMap["DIS_"] = 4
self.structureVersionMap["CMP_"] = 2
self.structureVersionMap["CMS_"] = 0
self.structureVersionMap["TER_"] = 0
self.structureVersionMap["VOL_"] = 0
self.structureVersionMap["CREP"] = 0
self.structureVersionMap["VON_"] = 0
self.structureVersionMap["Vector2AnimationReference"] = 0
self.structureVersionMap["Int16AnimationReference"] = 0
self.structureVersionMap["UInt16AnimationReference"] = 0
self.structureVersionMap["UInt32AnimationReference"] = 0
self.structureVersionMap["FloatAnimationReference"] = 0
self.structureVersionMap["AnimationReferenceHeader"] = 0
self.structureVersionMap["MATM"] = 0
self.structureVersionMap["MSEC"] = 1
self.structureVersionMap["BNDSV0AnimationReference"] = 0
self.structureVersionMap["BNDS"] = 0
self.structureVersionMap["VEC4"] = 0
self.structureVersionMap["QUAT"] = 0
self.structureVersionMap["VEC3"] = 0
self.structureVersionMap["VEC2"] = 0
self.structureVersionMap["ColorAnimationReference"] = 0
self.structureVersionMap["SDCC"] = 0
self.structureVersionMap["SDR3"] = 0
self.structureVersionMap["SDS6"] = 0
self.structureVersionMap["FLAG"] = 0
self.structureVersionMap["SDMB"] = 0
self.structureVersionMap["SD2V"] = 0
self.structureVersionMap["FlagAnimationReference"] = 0
self.structureVersionMap["SVC3"] = 0
self.structureVersionMap["WRP_"] = 1
self.structureVersionMap["SRIB"] = 0
self.structureVersionMap["STBM"] = 0
self.structureVersionMap["SDFG"] = 0
self.structureVersionMap["SDU3"] = 0
self.structureVersionMap["IKJT"] = 0
self.structureVersionMap["TRGD"] = 0
self.structureVersionMap["PATU"] = 4
self.structureVersionMap["PHYJ"] = 0
def getVersionOf(self, structureName):
return self.structureVersionMap[structureName]
def createInstanceOf(self, structureName):
version = self.structureVersionMap[structureName]
structureDescription = m3.structures[structureName].getVersion(version)
return structureDescription.createInstance()
def selectAnimationsForExport(self):
scene = self.scene
animationExportAmount = scene.m3_export_options.animationExportAmount
if animationExportAmount == shared.exportAmountAllAnimations:
self.animationIndicesToExport = range(len(scene.m3_animations))
elif animationExportAmount == shared.exportAmountCurrentAnimation:
self.animationIndicesToExport = [scene.m3_animation_index]
elif animationExportAmount == shared.exportAmountNoAnimations:
self.animationIndicesToExport = []
else:
raise ExportError("Unsupported export amount option: %s" % scene.m3_export_options)
def createModel(self, m3FileName):
model = self.createInstanceOf("MODL")
model.modelName = os.path.basename(m3FileName)
self.initBones(model)
self.initMesh(model)
self.initMaterials(model)
self.initCameras(model)
self.initFuzzyHitTests(model)
self.initTighHitTest(model)
self.initParticles(model)
self.initRibbons(model)
self.initProjections(model)
self.initWarps(model)
self.initForces(model)
self.initRigidBodies(model)
self.initLights(model)
self.initBillboardBehaviors(model)
self.initIkChains(model)
self.initTurretBehaviors(model)
self.initPhysicsJoints(model)
self.initVisibilityTest(model)
# TODO remove call and method:
# self.initBoundings(model)
self.initAttachmentPoints(model)
self.prepareAnimationEndEvents()
self.initWithPreparedAnimationData(model)
model.uniqueUnknownNumber = self.getAnimIdFor(shared.animObjectIdModel, "")
self.updateAnimationIdsOfBlendFile()
return model
def prepareAnimIdMaps(self):
self.longAnimIdToAnimIdMap = {}
self.usedAnimIds = {self.boundingAnimId}
for animIdData in self.scene.m3_animation_ids:
animId = animIdData.animIdMinus2147483648 + 2147483648
longAnimId = animIdData.longAnimId
self.longAnimIdToAnimIdMap[longAnimId] = animId
self.usedAnimIds.add(animId)
def getAnimIdForLongAnimId(self, longAnimId):
animId = self.longAnimIdToAnimIdMap.get(longAnimId)
if animId is None:
animId = shared.getRandomAnimIdNotIn(self.usedAnimIds)
self.usedAnimIds.add(animId)
self.longAnimIdToAnimIdMap[longAnimId] = animId
return animId
def updateAnimationIdsOfBlendFile(self):
self.scene.m3_animation_ids.clear()
for longAnimId, animId in self.longAnimIdToAnimIdMap.items():
if animId in self.usedAnimIds:
animIdData = self.scene.m3_animation_ids.add()
animIdData.animIdMinus2147483648 = animId - 2147483648
animIdData.longAnimId = longAnimId
def getAnimIdFor(self, objectId, animPath):
longAnimId = shared.getLongAnimIdOf(objectId, animPath)
return self.getAnimIdForLongAnimId(longAnimId)
def createUniqueAnimId(self):
self.generatedAnimIdCounter += 1 # increase first since we don't want to use 0 as animation id
return self.generatedAnimIdCounter
def initBones(self, model):
self.boneNameToDefaultPoseMatrixMap = {}
self.boneNameToM3SpaceDefaultLocationMap = {}
self.boneNameToM3SpaceDefaultRotationMap = {}
self.boneNameToM3SpaceDefaultScaleMap = {}
self.boneNameToLeftCorrectionMatrix = {}
self.boneNameToRightCorrectionMatrix = {}
self.boneNameToBoneIndexMap = {} # map: bone name to index in model bone list
boneNameToAbsInvRestPoseMatrix = {}
self.boneIndexToAbsoluteInverseRestPoseMatrixFixedMap = {}
self.armatureObjectNameToBoneNamesMap: Dict[str, bpy.types.Object] = {}
# Place all bones at the default position by selecting no animation:
self.scene.m3_animation_index = -1
self.scene.frame_set(0)
for armatureObject in self.findArmatureObjects():
armature = armatureObject.data
objectToWorldMatrix = armatureObject.matrix_world
boneNamesOfArmature = list()
self.armatureObjectNameToBoneNamesMap[armatureObject.name] = boneNamesOfArmature
for blenderBoneIndex, blenderBone in enumerate(armature.bones):
boneIndex = len(model.bones)
boneName = blenderBone.name
if boneName in self.boneNameToBoneIndexMap:
raise ExportError("There are multiple bones with the name %s" % blenderBone.name)
boneNamesOfArmature.append(boneName)
self.boneNameToBoneIndexMap[boneName] = boneIndex
locationAnimPath = 'pose.bones["%s"].location' % boneName
rotationAnimPath = 'pose.bones["%s"].rotation_quaternion' % boneName
scaleAnimPath = 'pose.bones["%s"].scale' % boneName
locationAnimId = self.getAnimIdFor(shared.animObjectIdArmature, locationAnimPath)
rotationAnimId = self.getAnimIdFor(shared.animObjectIdArmature, rotationAnimPath)
scaleAnimId = self.getAnimIdFor(shared.animObjectIdArmature, scaleAnimPath)
bone = self.createInstanceOf("BONE")
bone.name = boneName
bone.flags = 0
bone.setNamedBit("flags", "real", True)
bone.location = self.createInstanceOf("Vector3AnimationReference")
bone.location.header = self.createNullAnimHeader(animId=locationAnimId, interpolationType=1)
bone.rotation = self.createInstanceOf("QuaternionAnimationReference")
bone.rotation.header = self.createNullAnimHeader(animId=rotationAnimId, interpolationType=1)
bone.scale = self.createInstanceOf("Vector3AnimationReference")
bone.scale.header = self.createNullAnimHeader(animId=scaleAnimId, interpolationType=1)
bone.ar1 = self.createNullUInt32AnimationReference(1)
model.bones.append(bone)
absRestPosMatrix = objectToWorldMatrix @ blenderBone.matrix_local
self.restPositionsOfExportedBones.append(absRestPosMatrix.translation.copy())
if not blenderBone.use_inherit_rotation:
raise ExportError("The setting inhertRotation=false of bone %s is not exportable!" % boneName)
if not blenderBone.use_inherit_scale:
raise ExportError("The setting inhertScale=false of bone %s is not exportable!" % boneName)
if blenderBone.parent is not None:
bone.parent = self.boneNameToBoneIndexMap[blenderBone.parent.name]
absInvRestPoseMatrixParent = boneNameToAbsInvRestPoseMatrix[blenderBone.parent.name]
relRestPosMatrix = absInvRestPoseMatrixParent @ absRestPosMatrix
else:
bone.parent = -1
relRestPosMatrix = absRestPosMatrix
poseBone: bpy.types.Bone = armatureObject.pose.bones[boneName]
poseMatrix = armatureObject.convert_space(
pose_bone=poseBone,
matrix=poseBone.matrix,
from_space='POSE',
to_space='LOCAL',
)
bindScaleInverted = mathutils.Vector((1.0 / blenderBone.m3_bind_scale[i] for i in range(3)))
bindScaleMatrixInverted = shared.scaleVectorToMatrix(bindScaleInverted)
if blenderBone.parent is not None:
parentBindMatrix = shared.scaleVectorToMatrix(blenderBone.parent.m3_bind_scale)
leftCorrectionMatrix = parentBindMatrix @ shared.rotFixMatrix @ relRestPosMatrix
else:
leftCorrectionMatrix = relRestPosMatrix
rightCorrectionMatrix = shared.rotFixMatrixInverted @ bindScaleMatrixInverted
m3PoseMatrix = leftCorrectionMatrix @ poseMatrix @ rightCorrectionMatrix
self.boneNameToLeftCorrectionMatrix[boneName] = leftCorrectionMatrix
self.boneNameToRightCorrectionMatrix[boneName] = rightCorrectionMatrix
m3SpaceLocation, m3SpaceRotation, m3SpaceScale = m3PoseMatrix.decompose()
bone.scale.initValue = self.createVector3FromBlenderVector(m3SpaceScale)
bone.scale.nullValue = self.createVector3(0.0, 0.0, 0.0)
bone.rotation.initValue = self.createQuaternionFromBlenderQuaternion(m3SpaceRotation)
bone.rotation.nullValue = self.createQuaternion(0.0, 0.0, 0.0, 1.0)
bone.location.initValue = self.createVector3FromBlenderVector(m3SpaceLocation)
bone.location.nullValue = self.createVector3(0.0, 0.0, 0.0)
self.boneNameToM3SpaceDefaultLocationMap[boneName] = m3SpaceLocation
self.boneNameToM3SpaceDefaultRotationMap[boneName] = m3SpaceRotation
self.boneNameToM3SpaceDefaultScaleMap[boneName] = m3SpaceScale
# calculate the bind matrix / absoluteInverseRestPoseMatrixFixed
absRestPosMatrixFixed = absRestPosMatrix @ shared.rotFixMatrixInverted
bindScale = blenderBone.m3_bind_scale
bindScaleMatrix = shared.scaleVectorToMatrix(bindScale)
absoluteInverseRestPoseMatrixFixed = absRestPosMatrixFixed.inverted()
absoluteInverseRestPoseMatrixFixed = bindScaleMatrix @ absoluteInverseRestPoseMatrixFixed
absoluteInverseBoneRestPos = self.createRestPositionFromBlender4x4Matrix(absoluteInverseRestPoseMatrixFixed)
model.absoluteInverseBoneRestPositions.append(absoluteInverseBoneRestPos)
self.boneIndexToAbsoluteInverseRestPoseMatrixFixedMap[boneIndex] = absoluteInverseRestPoseMatrixFixed
boneNameToAbsInvRestPoseMatrix[blenderBone.name] = absRestPosMatrix.inverted()
# Calculate the absolute matrix of this bone in default position
# for later default boundings calculation
absoluteBoneMatrix = m3PoseMatrix
if (bone.parent != -1):
# The parent matrix has it's absoluteInverseRestPoseMatrixFixed multiplied to it. It needs to be undone:
parentMatrix = self.boneIndexToDefaultAbsoluteMatrixMap[bone.parent] @ self.boneIndexToAbsoluteInverseRestPoseMatrixFixedMap[bone.parent].inverted()
absoluteBoneMatrix = parentMatrix @ absoluteBoneMatrix
absoluteBoneMatrix = absoluteBoneMatrix @ absoluteInverseRestPoseMatrixFixed
self.boneIndexToDefaultAbsoluteMatrixMap[boneIndex] = absoluteBoneMatrix
startTime = time.time()
self.initBoneAnimations(model)
endTime = time.time()
duration = endTime - startTime
print("Bone animation export took %s seconds" % duration)
def initBoneAnimations(self, model):
for animationIndex in self.animationIndicesToExport:
animation = self.scene.m3_animations[animationIndex]
print("Calculating bone movement done in animation %s" % animation.name)
self.scene.m3_animation_index = animationIndex
frames = set()
# For animated rotations all frames are needed,
# since Starcraft 2 isn't correcting the linearly interpolated values
# In addition the bone matrices are needed for each frame
# to calculate the mesh boundings in a later step
#
frames = self.allFramesOfAnimation(animation)
timeValuesInMS = self.allFramesToMSValues(frames)
frameToBoneIndexToAbsoluteMatrixMap = self.animationNameToFrameToBoneIndexToAbsoluteMatrixMap.get(animation.name)
if frameToBoneIndexToAbsoluteMatrixMap is None:
frameToBoneIndexToAbsoluteMatrixMap = {}
self.animationNameToFrameToBoneIndexToAbsoluteMatrixMap[animation.name] = frameToBoneIndexToAbsoluteMatrixMap
boneNameToLocations = {}
boneNameToRotations = {}
boneNameToScales = {}
for armatureObjectName, boneNamesOfArmature in self.armatureObjectNameToBoneNamesMap.items():
for boneName in boneNamesOfArmature:
boneNameToLocations[boneName] = []
boneNameToRotations[boneName] = []
boneNameToScales[boneName] = []
# Jog animation frame so that complicated bone constraints are given time to be properly calculated before proceeding
self.scene.frame_set(0)
for frame in frames:
self.scene.frame_set(frame)
for armatureObjectName, boneNamesOfArmature in self.armatureObjectNameToBoneNamesMap.items():
armatureObject = bpy.data.objects[armatureObjectName]
for boneName in boneNamesOfArmature:
boneIndex = self.boneNameToBoneIndexMap[boneName]
bone = model.bones[boneIndex]
poseBone = armatureObject.pose.bones[boneName]
leftCorrectionMatrix = self.boneNameToLeftCorrectionMatrix[boneName]
rightCorrectionMatrix = self.boneNameToRightCorrectionMatrix[boneName]
poseMatrix = armatureObject.convert_space(
pose_bone=poseBone,
matrix=poseBone.matrix,
from_space='POSE',
to_space='LOCAL',
)
m3PoseMatrix = leftCorrectionMatrix @ poseMatrix @ rightCorrectionMatrix
boneIndexToAbsoluteMatrixMap = frameToBoneIndexToAbsoluteMatrixMap.get(frame)
if boneIndexToAbsoluteMatrixMap is None:
boneIndexToAbsoluteMatrixMap = {}
frameToBoneIndexToAbsoluteMatrixMap[frame] = boneIndexToAbsoluteMatrixMap
absoluteBoneMatrix = m3PoseMatrix
if (bone.parent != -1):
# The parent matrix has it's absoluteInverseRestPoseMatrixFixed multiplied to it. It needs to be undone:
parentMatrix = boneIndexToAbsoluteMatrixMap[bone.parent] @ self.boneIndexToAbsoluteInverseRestPoseMatrixFixedMap[bone.parent].inverted()
absoluteBoneMatrix = parentMatrix @ absoluteBoneMatrix
absoluteInverseRestPoseMatrixFixed = self.boneIndexToAbsoluteInverseRestPoseMatrixFixedMap[boneIndex]
absoluteBoneMatrix = absoluteBoneMatrix @ absoluteInverseRestPoseMatrixFixed
boneIndexToAbsoluteMatrixMap[boneIndex] = absoluteBoneMatrix
locations = boneNameToLocations[boneName]
rotations = boneNameToRotations[boneName]
scales = boneNameToScales[boneName]
loc, rot, sca = m3PoseMatrix.decompose()
locations.append(loc)
rotations.append(rot)
scales.append(sca)
for armatureObjectName, boneNamesOfArmature in self.armatureObjectNameToBoneNamesMap.items():
for boneName in boneNamesOfArmature:
boneIndex = self.boneNameToBoneIndexMap[boneName]
bone = model.bones[boneIndex]
locations = boneNameToLocations[boneName]
rotations = boneNameToRotations[boneName]
scales = boneNameToScales[boneName]
self.makeQuaternionsInterpolatable(rotations)
animIdToAnimDataMap = self.nameToAnimIdToAnimDataMap[animation.name]
m3SpaceLocation = self.boneNameToM3SpaceDefaultLocationMap[boneName]
m3SpaceRotation = self.boneNameToM3SpaceDefaultRotationMap[boneName]
m3SpaceScale = self.boneNameToM3SpaceDefaultScaleMap[boneName]
locationAnimPath = 'pose.bones["%s"].location' % boneName
rotationAnimPath = 'pose.bones["%s"].rotation_quaternion' % boneName
scaleAnimPath = 'pose.bones["%s"].scale' % boneName
locationAnimId = self.getAnimIdFor(shared.animObjectIdArmature, locationAnimPath)
rotationAnimId = self.getAnimIdFor(shared.animObjectIdArmature, rotationAnimPath)
scaleAnimId = self.getAnimIdFor(shared.animObjectIdArmature, scaleAnimPath)
if self.isAnimationExport or self.vectorArrayContainsNotOnly(locations, m3SpaceLocation):
locationTimeValuesInMS, locations = shared.simplifyVectorAnimationWithInterpolation(timeValuesInMS, locations)
m3Locs = self.createVector3sFromBlenderVectors(locations)
m3AnimBlock = self.createInstanceOf("SD3V")
m3AnimBlock.frames = locationTimeValuesInMS
m3AnimBlock.flags = 0
m3AnimBlock.fend = self.frameToMS(animation.exlusiveEndFrame)
m3AnimBlock.keys = m3Locs
animIdToAnimDataMap[locationAnimId] = m3AnimBlock
bone.location.header.animFlags = shared.animFlagsForAnimatedProperty
bone.setNamedBit("flags", "animated", True)
if self.isAnimationExport or self.quaternionArrayContainsNotOnly(rotations, m3SpaceRotation):
rotationTimeValuesInMS, rotations = shared.simplifyQuaternionAnimationWithInterpolation(timeValuesInMS, rotations)
m3Rots = self.createQuaternionsFromBlenderQuaternions(rotations)
m3AnimBlock = self.createInstanceOf("SD4Q")
m3AnimBlock.frames = rotationTimeValuesInMS
m3AnimBlock.flags = 0
m3AnimBlock.fend = self.frameToMS(animation.exlusiveEndFrame)
m3AnimBlock.keys = m3Rots
animIdToAnimDataMap[rotationAnimId] = m3AnimBlock
bone.rotation.header.animFlags = shared.animFlagsForAnimatedProperty
bone.setNamedBit("flags", "animated", True)
if self.isAnimationExport or self.vectorArrayContainsNotOnly(scales, m3SpaceScale):
scaleTimeValuesInMS, scales = shared.simplifyVectorAnimationWithInterpolation(timeValuesInMS, scales)
m3Scas = self.createVector3sFromBlenderVectors(scales)
m3AnimBlock = self.createInstanceOf("SD3V")
m3AnimBlock.frames = scaleTimeValuesInMS
m3AnimBlock.flags = 0
m3AnimBlock.fend = self.frameToMS(animation.exlusiveEndFrame)
m3AnimBlock.keys = m3Scas
animIdToAnimDataMap[scaleAnimId] = m3AnimBlock
bone.scale.header.animFlags = shared.animFlagsForAnimatedProperty
bone.setNamedBit("flags", "animated", True)
def initVisibilityTest(self, model):
halfSize = self.scene.m3_visibility_test.size / 2.0
minBorder = self.scene.m3_visibility_test.center - halfSize
maxBorder = self.scene.m3_visibility_test.center + halfSize
model.boundings.radius = self.scene.m3_visibility_test.radius
model.boundings.minBorder = self.blenderToM3Vector(minBorder)
model.boundings.maxBorder = self.blenderToM3Vector(maxBorder)
def allFramesOfAnimation(self, animation):
# In Starcraft 2 there is one more key frame then there is usually in Blender:
# 3 Blender key frames at the times 0, 33, 67 give a an animation for the time 0 to 100 (at 30 FPS)
# For Starcraft 2 4 key frames are needed: 0, 33, 67 and 100.
# For a smooth loop the key frame data of 0 and 100 need to be the same.
return list(range(animation.startFrame, animation.exlusiveEndFrame + 1))
def vectorArrayContainsNotOnly(self, vectorArray, vector):
for v in vectorArray:
if not shared.vectorsAlmostEqual(vector, v):
return True
return False
def quaternionArrayContainsNotOnly(self, quaternionArray, quaternion):
for q in quaternionArray:
if not shared.quaternionsAlmostEqual(quaternion, q):
return True
return False
def initOldReferenceIndicesInCorrectedOrder(self):
scene = self.scene
materialNameToOldReferenceIndexMap = {}
for materialReferenceIndex, materialReference in enumerate(self.scene.m3_material_references):
materialNameToOldReferenceIndexMap[materialReference.name] = materialReferenceIndex
remainingMaterials = list(range(len(self.scene.m3_material_references)))
self.oldReferenceIndicesInCorrectedOrder = []
while len(remainingMaterials) > 0:
unableToDefineChildsFirst = True
for oldReferenceIndex in remainingMaterials:
reference = scene.m3_material_references[oldReferenceIndex]
canBeDefined = True
if reference.materialType == shared.compositeMaterialTypeIndex:
compositeMaterial = scene.m3_composite_materials[reference.materialIndex]
for sectionIndex, section in enumerate(compositeMaterial.sections):
oldChildReferenceIndex = materialNameToOldReferenceIndexMap.get(section.name)
if oldChildReferenceIndex is None:
raise ExportError("The composite material %s uses '%s' as material, but no m3 material with that name exist!" % (compositeMaterial.name, section.name))
if oldChildReferenceIndex not in self.oldReferenceIndicesInCorrectedOrder:
canBeDefined = False
if canBeDefined:
remainingMaterials.remove(oldReferenceIndex)
self.oldReferenceIndicesInCorrectedOrder.append(oldReferenceIndex)
unableToDefineChildsFirst = False
break
if unableToDefineChildsFirst:
raise Exception("Unable to define all sections before the actual composite material: Is there a loop back?")
def initMaterialNameToNewReferenceIndexMap(self):
self.materialNameToNewReferenceIndexMap = {}
for newRefeferenceIndex, oldReferenceIndex in enumerate(self.oldReferenceIndicesInCorrectedOrder):
materialReference = self.scene.m3_material_references[oldReferenceIndex]
self.materialNameToNewReferenceIndexMap[materialReference.name] = newRefeferenceIndex
def initMesh(self, model):
nonEmptyMeshObjects: List[bpy.types.Object] = []
uvCoordinatesPerVertex = 1 # Never saw a m3 model with at least 1 UV layer
for meshObject in shared.findMeshObjects(self.scene):
mesh: bpy.types.Mesh = meshObject.data
mesh.calc_loop_triangles()
if len(mesh.loop_triangles) > 0 and not mesh.m3_physics_mesh:
nonEmptyMeshObjects.append(meshObject)
uvCoordinatesPerVertex = max(uvCoordinatesPerVertex, len(mesh.uv_layers))
model.setNamedBit("flags", "hasMesh", len(nonEmptyMeshObjects) > 0)
model.boundings = self.createAlmostEmptyBoundingsWithRadius(2.0)
if len(nonEmptyMeshObjects) == 0:
model.numberOfBonesToCheckForSkin = 0
model.divisions = [self.createEmptyDivision()]
return
if uvCoordinatesPerVertex not in [1, 2, 3, 4]:
raise Exception("The m3 format seems to supports only 1-4 UV layers per mesh, not %d" % uvCoordinatesPerVertex)
model.vFlags = 0x182007d
if uvCoordinatesPerVertex >= 2:
model.setNamedBit("vFlags", "useUVChannel1", True)
if uvCoordinatesPerVertex >= 3:
model.setNamedBit("vFlags", "useUVChannel2", True)
if uvCoordinatesPerVertex >= 4:
model.setNamedBit("vFlags", "useUVChannel3", True)
rgbColorChannelName = "color"
alphaColorChannelName = "alpha"
exportVertexRGBA = False
for meshObjectToCheck in nonEmptyMeshObjects:
meshToCheck: bpy.types.Mesh = meshObjectToCheck.data
for vertexColorLayer in meshToCheck.vertex_colors:
vertexColorLayerName = vertexColorLayer.name
if vertexColorLayerName == rgbColorChannelName:
exportVertexRGBA = True
elif vertexColorLayerName == alphaColorChannelName:
exportVertexRGBA = True
else:
print("The mesh %s has has a color layer called %s. Only color layers with the names 'color' and 'alpha' can be exported" % (meshObjectToCheck.name, vertexColorLayerName))
model.setNamedBit("vFlags", "hasVertexColors", exportVertexRGBA)
m3VertexStructureDefinition = m3.structures["VertexFormat" + hex(model.vFlags)].getVersion(0)
division = self.createInstanceOf("DIV_")
model.divisions.append(division)
m3Vertices = []
for meshIndex, meshObject in enumerate(nonEmptyMeshObjects):
mesh: bpy.types.Mesh = meshObject.data
print("Exporting mesh object %s" % meshObject.name)
signGroup = mesh.polygon_layers_int.get("m3sign") or mesh.polygon_layers_int.new(name="m3sign")
if bpy.ops.object.mode_set.poll():
bpy.ops.object.mode_set(mode='OBJECT')
bpy.ops.object.select_all(action='DESELECT')
self.scene.view_layers[0].objects.active = meshObject
meshObject.select_set(True)
bpy.ops.object.duplicate()
meshObjectCopy = self.scene.view_layers[0].objects.active
bpy.ops.object.modifier_apply(modifier='EdgeSplit')
mesh = meshObjectCopy.data
meshObject = meshObjectCopy
mesh.update()
materialReferenceIndex = self.materialNameToNewReferenceIndexMap.get(mesh.m3_material_name)
if materialReferenceIndex is None:
raise ExportError("The mesh %s uses '%s' as material, but no m3 material with that name exist!" % (mesh.name, mesh.m3_material_name))
firstBoneLookupIndex = len(model.boneLookup)
staticMeshBoneName = "StaticMesh"
boneNameToBoneLookupIndexMap = {}
boneNamesOfArmature = set()
if len(meshObject.modifiers) == 0:
pass
elif len(meshObject.modifiers) == 1 and (meshObject.modifiers[0].type == "ARMATURE"):
modifier = meshObject.modifiers[0]
armatureObject = modifier.object
if armatureObject is not None:
armature = armatureObject.data
for blenderBoneIndex, blenderBone in enumerate(armature.bones):
boneNamesOfArmature.add(blenderBone.name)
else:
raise ExportError("The mesh %s has invalid modifiers: Mesh must have no modifiers except single one for the armature and one for edge split." % meshObject.name)
objectToWorldMatrix = meshObject.matrix_world
vertexColor = mesh.vertex_colors.get(rgbColorChannelName)
if vertexColor is not None:
vertexColorData = vertexColor.data
else:
vertexColorData = None
vertexAlpha = mesh.vertex_colors.get(alphaColorChannelName)
if vertexAlpha is not None:
vertexAlphaData = vertexAlpha.data
else:
vertexAlphaData = None
firstFaceVertexIndexIndex = len(division.faces)
firstVertexIndexIndex = len(m3Vertices)
regionFaceVertexIndices = []
regionVertices = []
vertexDataTupleToIndexMap = {}
nextVertexIndex = 0
numberOfBoneWeightPairsPerVertex = 0
staticMeshBoneLookupIndex = None
mesh.calc_loop_triangles()
def normalize(x, y, z):
length = math.sqrt(x * x + y * y + z * z)
if length == 0:
return 0.0, 0.0, 0.0
return (x / length, y / length, z / length)
for tri in mesh.loop_triangles:
assert(len(tri.vertices) == 3)
# Calculate tangents
vertex0 = meshObject.data.vertices[tri.vertices[0]]
vertex1 = meshObject.data.vertices[tri.vertices[1]]
vertex2 = meshObject.data.vertices[tri.vertices[2]]
uv0 = meshObject.data.uv_layers[0].data[tri.loops[0]].uv
uv1 = meshObject.data.uv_layers[0].data[tri.loops[1]].uv
uv2 = meshObject.data.uv_layers[0].data[tri.loops[2]].uv
v0 = uv0[1]
v1 = uv1[1]
v2 = uv2[1]
deltaV1 = v1 - v0
deltaV2 = v2 - v0
e1x = vertex1.co.x - vertex0.co.x
e1y = vertex1.co.y - vertex0.co.y
e1z = vertex1.co.z - vertex0.co.z
e2x = vertex2.co.x - vertex0.co.x
e2y = vertex2.co.y - vertex0.co.y
e2z = vertex2.co.z - vertex0.co.z
tx = (deltaV2 * e1x - deltaV1 * e2x)
ty = (deltaV2 * e1y - deltaV1 * e2y)
tz = (deltaV2 * e1z - deltaV1 * e2z)
tx, ty, tz = normalize(tx, ty, tz)
for faceRelativeVertexIndex, vertIndex in enumerate(tri.vertices):
blenderVertex = mesh.vertices[vertIndex]
m3Vertex = m3VertexStructureDefinition.createInstance()
absolutePosition = objectToWorldMatrix @ blenderVertex.co
m3Vertex.position = self.blenderToM3Vector(absolutePosition)
weightLookupIndexPairs = []
for gIndex, g in enumerate(blenderVertex.groups):
vertexGroupIndex = g.group
# It seems like the group data can become corrupted in Blender:
if vertexGroupIndex < len(meshObject.vertex_groups):
vertexGroup = meshObject.vertex_groups[vertexGroupIndex]
boneIndex = self.boneNameToBoneIndexMap.get(vertexGroup.name)
if boneIndex is not None and vertexGroup.name in boneNamesOfArmature:
boneLookupIndex = boneNameToBoneLookupIndexMap.get(vertexGroup.name)
if boneLookupIndex is None:
boneLookupIndex = len(model.boneLookup) - firstBoneLookupIndex
model.boneLookup.append(boneIndex)
boneNameToBoneLookupIndexMap[vertexGroup.name] = boneLookupIndex
bone = model.bones[boneIndex]
bone.setNamedBit("flags", "skinned", True)
boneWeight = sorted((round(g.weight * 255), 0, 255))[1]
if boneWeight != 0:
if len(weightLookupIndexPairs) < 4:
weightLookupIndexPairs.append((g.weight, boneLookupIndex))
totalWeight = 0
for weight, lookupIndex in weightLookupIndexPairs:
totalWeight += weight
# This algorithm is aiming at ensuring that roundedWeightSum is 255 at the end
# Since correctedWeightSum is 1.0000XXXXX at the end,
# roundedWeightSum will be exactly 255.
roundedWeightLookupIndexPairs = []
correctedWeightSum = 0.0
roundedWeightSum = 0
for weight, lookupIndex in weightLookupIndexPairs:
correctedWeight = weight / totalWeight
correctedWeightSum += correctedWeight
newRoundedWeithSum = round(correctedWeightSum * 255.0)
roundedWeight = newRoundedWeithSum - roundedWeightSum
roundedWeightSum = newRoundedWeithSum
roundedWeightLookupIndexPairs.append((roundedWeight, lookupIndex))
weightIndex = 0
for roundedWeight, lookupIndex in roundedWeightLookupIndexPairs:
setattr(m3Vertex, "boneWeight%d" % weightIndex, roundedWeight)
setattr(m3Vertex, "boneLookupIndex%d" % weightIndex, lookupIndex)
weightIndex += 1
isStaticVertex = (len(roundedWeightLookupIndexPairs) == 0)
if isStaticVertex:
staticMeshBoneIndex = self.boneNameToBoneIndexMap.get(staticMeshBoneName)
if staticMeshBoneIndex is None:
staticMeshBoneIndex = self.addBoneWithRestPosAndReturnIndex(model, staticMeshBoneName, realBone=True)
self.createBoneMatricesForStaticMeshBone(staticMeshBoneIndex)
if staticMeshBoneLookupIndex is None:
staticMeshBoneLookupIndex = boneNameToBoneLookupIndexMap.get(staticMeshBoneName)
if staticMeshBoneLookupIndex is None:
self.boneNameToBoneIndexMap[staticMeshBoneName] = staticMeshBoneIndex
staticMeshBoneLookupIndex = len(model.boneLookup) - firstBoneLookupIndex
model.boneLookup.append(staticMeshBoneIndex)
boneNameToBoneLookupIndexMap[staticMeshBoneName] = staticMeshBoneLookupIndex
bone = model.bones[staticMeshBoneIndex]
bone.setNamedBit("flags", "skinned", True)
roundedWeightLookupIndexPairs.append((255, staticMeshBoneLookupIndex))
usedBoneWeightSlots = len(roundedWeightLookupIndexPairs)
if usedBoneWeightSlots > numberOfBoneWeightPairsPerVertex:
numberOfBoneWeightPairsPerVertex = usedBoneWeightSlots
for uvLayerIndex in range(0, uvCoordinatesPerVertex):
m3AttributeName = "uv" + str(uvLayerIndex)
if len(mesh.uv_layers) > uvLayerIndex:
uvData = mesh.uv_layers[uvLayerIndex].data[tri.loops[faceRelativeVertexIndex]]
m3UVCoord = self.convertBlenderToM3UVCoordinates(uvData.uv)
setattr(m3Vertex, m3AttributeName, m3UVCoord)
else:
setattr(m3Vertex, m3AttributeName, self.createM3UVVector(0.0, 0.0))
m3Vertex.normal = self.blenderVector3ToVector3As3Fixed8(blenderVertex.normal)
if signGroup.data[tri.polygon_index].value == 1:
m3Vertex.sign = 1.0
m3Vertex.tangent.x = -tx
m3Vertex.tangent.y = -ty
m3Vertex.tangent.z = -tz
else:
m3Vertex.sign = -1.0
m3Vertex.tangent.x = tx
m3Vertex.tangent.y = ty
m3Vertex.tangent.z = tz
# TODO: unsure if this actually works as intended.. find a model for test
red = 1.0
green = 1.0
blue = 1.0
alpha = 1.0
if exportVertexRGBA:
if vertexColorData is not None:
blenderColor = vertexColorData[tri.loops[faceRelativeVertexIndex]].color
red = blenderColor[0]
green = blenderColor[1]
blue = blenderColor[2]
if vertexAlphaData is not None:
blenderColor = vertexAlphaData[tri.loops[faceRelativeVertexIndex]].color
alpha = (blenderColor[0] + blenderColor[1] + blenderColor[2]) / 3.0
m3Vertex.color = self.createColor(red, green, blue, alpha)
v = m3Vertex
vertexIdList = []
vertexIdList.extend((v.position.x, v.position.y, v.position.z))
vertexIdList.extend((v.boneWeight0, v.boneWeight1, v.boneWeight2, v.boneWeight3))
vertexIdList.extend((v.boneLookupIndex0, v.boneLookupIndex1, v.boneLookupIndex2, v.boneLookupIndex3))
vertexIdList.extend((v.normal.x, v.normal.y, v.normal.z))
if exportVertexRGBA:
vertexIdList.extend((red, green, blue, alpha))
for i in range(uvCoordinatesPerVertex):
uvAttribute = "uv" + str(i)
uvVector = getattr(v, uvAttribute)
vertexIdList.append(uvVector.x)
vertexIdList.append(uvVector.y)
vertexIdTuple = tuple(vertexIdList)
vertexIndex = vertexDataTupleToIndexMap.get(vertexIdTuple)
if vertexIndex is None:
vertexIndex = nextVertexIndex
vertexDataTupleToIndexMap[vertexIdTuple] = vertexIndex
nextVertexIndex += 1
regionVertices.append(m3Vertex)
m3VertexStructureDefinition.validateInstance(m3Vertex, "vertex")
regionFaceVertexIndices.append(vertexIndex)
division.faces.extend(regionFaceVertexIndices)
m3Vertices.extend(regionVertices)
region = self.createInstanceOf("REGN")
region.firstVertexIndex = firstVertexIndexIndex
region.numberOfVertices = len(regionVertices)
region.firstFaceVertexIndexIndex = firstFaceVertexIndexIndex
region.numberOfFaceVertexIndices = len(regionFaceVertexIndices)
region.numberOfBones = len(boneNameToBoneLookupIndexMap)
region.firstBoneLookupIndex = firstBoneLookupIndex
region.numberOfBoneLookupIndices = len(boneNameToBoneLookupIndexMap)
region.rootBoneIndex = model.boneLookup[firstBoneLookupIndex]
region.numberOfBoneWeightPairsPerVertex = numberOfBoneWeightPairsPerVertex
division.regions.append(region)
m3Object = self.createInstanceOf("BAT_")
m3Object.regionIndex = meshIndex
materialReferenceIndex = self.materialNameToNewReferenceIndexMap.get(mesh.m3_material_name)
if materialReferenceIndex is None:
raise ExportError("The mesh %s uses '%s' as material, but no m3 material with that name exist!" % (mesh.name, mesh.m3_material_name))
m3Object.materialReferenceIndex = materialReferenceIndex
division.objects.append(m3Object)
bpy.ops.object.delete()
numberOfBonesToCheckForSkin = 0
for boneIndex, bone in enumerate(model.bones):
if bone.getNamedBit("flags", "skinned"):
numberOfBonesToCheckForSkin = boneIndex + 1
model.numberOfBonesToCheckForSkin = numberOfBonesToCheckForSkin
model.vertices = m3VertexStructureDefinition.instancesToBytes(m3Vertices)
startTime = time.time()
self.initMeshBoundings(model, m3Vertices)
endTime = time.time()
duration = endTime - startTime
print("Mesh boundings animation export took %s seconds" % duration)
def initMeshBoundings(self, model, m3Vertices):
boundingsAnimRef = self.createInstanceOf("BNDSV0AnimationReference")
animHeader = self.createInstanceOf("AnimationReferenceHeader")
animHeader.interpolationType = 0
animHeader.animFlags = 0x0
animHeader.animId = self.boundingAnimId # boudings seem to have always this id
boundingsAnimRef.header = animHeader
self.initBoundingPointsOfExportedBonesList(model, m3Vertices)
defaultBoundingsVector = self.calculateBoundingsVector(model, m3Vertices, self.boneIndexToDefaultAbsoluteMatrixMap)
boundingsAnimRef.initValue = self.createBNDSFromVector(defaultBoundingsVector)
boundingsAnimRef.nullValue = self.createBoundings(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0)
for animationIndex in self.animationIndicesToExport:
animation = self.scene.m3_animations[animationIndex]
print("Calculating mesh boundings for animation %s" % animation.name)
frameToBoneIndexToAbsoluteMatrixMap = self.animationNameToFrameToBoneIndexToAbsoluteMatrixMap[animation.name]
boundingsVectorList = []
frames = self.allFramesOfAnimation(animation)
timeValuesInMS = self.allFramesToMSValues(frames)
for frame in frames:
boneIndexToAbsoluteMatrixMap = frameToBoneIndexToAbsoluteMatrixMap[frame]
b = self.calculateBoundingsVector(model, m3Vertices, boneIndexToAbsoluteMatrixMap)
boundingsVectorList.append(b)
if self.isAnimationExport or self.vectorArrayContainsNotOnly(boundingsVectorList, defaultBoundingsVector):
timeValuesInMS, boundingsVectorList = shared.simplifyVectorAnimationWithInterpolation(timeValuesInMS, boundingsVectorList)
boundingStructures = list(self.createBNDSFromVector(v) for v in boundingsVectorList)
m3AnimBlock = self.createInstanceOf("SDMB")
m3AnimBlock.frames = timeValuesInMS
m3AnimBlock.flags = 0
m3AnimBlock.fend = self.frameToMS(animation.exlusiveEndFrame)
m3AnimBlock.keys = boundingStructures
animIdToAnimDataMap = self.nameToAnimIdToAnimDataMap[animation.name]
animIdToAnimDataMap[self.boundingAnimId] = m3AnimBlock
boundingsAnimRef.header.animFlags = shared.animFlagsForAnimatedProperty
msec = self.createInstanceOf("MSEC")
msec.boundingsAnimation = boundingsAnimRef
model.divisions[0].msec.append(msec)
def createBoneMatricesForStaticMeshBone(self, staticMeshBoneIndex):
self.boneIndexToDefaultAbsoluteMatrixMap[staticMeshBoneIndex] = mathutils.Matrix()
for animationIndex in self.animationIndicesToExport:
animation = self.scene.m3_animations[animationIndex]
frameToBoneIndexToAbsoluteMatrixMap = self.animationNameToFrameToBoneIndexToAbsoluteMatrixMap.get(animation.name)
if frameToBoneIndexToAbsoluteMatrixMap is None:
frameToBoneIndexToAbsoluteMatrixMap = {}
self.animationNameToFrameToBoneIndexToAbsoluteMatrixMap[animation.name] = frameToBoneIndexToAbsoluteMatrixMap
for frame in self.allFramesOfAnimation(animation):
boneIndexToAbsoluteMatrixMap = frameToBoneIndexToAbsoluteMatrixMap.get(frame)
if boneIndexToAbsoluteMatrixMap is None:
boneIndexToAbsoluteMatrixMap = {}
frameToBoneIndexToAbsoluteMatrixMap[frame] = boneIndexToAbsoluteMatrixMap
boneIndexToAbsoluteMatrixMap[staticMeshBoneIndex] = mathutils.Matrix()
def createBNDSFromVector(self, vector):
minX = vector[0]
minY = vector[1]
minZ = vector[2]
maxX = vector[3]
maxY = vector[4]
maxZ = vector[5]
radius = vector[6]
b = self.createInstanceOf("BNDS")
b.minBorder = self.createVector3(minX, minY, minZ)
b.maxBorder = self.createVector3(maxX, maxY, maxZ)
b.radius = radius
return b
def calculateBoundingsVector(self, model, m3Vertices, boneIndexToAbsoluteMatrixMap):
minX2 = float("inf")
minY2 = float("inf")