-
Notifications
You must be signed in to change notification settings - Fork 1
/
io_m3_import.py
1846 lines (1459 loc) · 85 KB
/
io_m3_import.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
# ##### 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 #####
import math
import traceback
import bpy
import bmesh
import mathutils
from . import io_m3
from . import io_shared
from . import shared
from .m3_animations import set_default_value, ob_anim_data_set
FRAME_RATE = 30
def to_bl_frame(m3_ms):
return round(m3_ms / 1000 * FRAME_RATE)
def to_bl_uv(m3_uv, uv_multiply, uv_offset):
return (
m3_uv.x * uv_multiply / 32768 + uv_offset,
-m3_uv.y * uv_multiply / 32768 - uv_offset + 1
)
def to_bl_vec2(m3_vector):
return mathutils.Vector((m3_vector.x, m3_vector.y))
def to_bl_vec3(m3_vector):
return mathutils.Vector((m3_vector.x, m3_vector.y, m3_vector.z))
def to_bl_vec4(m3_vector):
return mathutils.Vector((m3_vector.w, m3_vector.x, m3_vector.y, m3_vector.z))
def to_bl_quat(m3_vector):
return mathutils.Quaternion((m3_vector.w, m3_vector.x, m3_vector.y, m3_vector.z))
def to_bl_color(m3_color):
return mathutils.Vector((m3_color.r / 255, m3_color.g / 255, m3_color.b / 255, m3_color.a / 255))
def to_bl_matrix(m3_matrix):
return mathutils.Matrix((
(m3_matrix.x.x, m3_matrix.y.x, m3_matrix.z.x, m3_matrix.w.x),
(m3_matrix.x.y, m3_matrix.y.y, m3_matrix.z.y, m3_matrix.w.y),
(m3_matrix.x.z, m3_matrix.y.z, m3_matrix.z.z, m3_matrix.w.z),
(m3_matrix.x.w, m3_matrix.y.w, m3_matrix.z.w, m3_matrix.w.w),
))
class M3InputProcessor:
def __init__(self, importer, bl, m3):
self.importer = importer
self.bl = bl
self.m3 = m3
self.version = m3.desc.version
def boolean(self, field, since_version=None, till_version=None):
if (till_version is not None) and (self.version > till_version):
return
if (since_version is not None) and (self.version < since_version):
return
setattr(self.bl, field, False if getattr(self.m3, field) == 0 else True)
def bit(self, field, name, since_version=None):
if (since_version is not None) and (self.version < since_version):
return
setattr(self.bl, name, self.m3.bit_get(field, name))
def bits_16(self, field):
val = getattr(self.m3, field)
vector = getattr(self.bl, field)
for ii in range(0, 16):
mask = 1 << ii
vector[ii] = (mask & val) > 0
def bits_32(self, field):
val = getattr(self.m3, field)
vector = getattr(self.bl, field)
for ii in range(0, 32):
mask = 1 << ii
vector[ii] = (mask & val) > 0
def integer(self, field, since_version=None, till_version=None):
if (till_version is not None) and (self.version > till_version):
return
if (since_version is not None) and (self.version < since_version):
return
setattr(self.bl, field, getattr(self.m3, field))
def float(self, field, since_version=None, till_version=None):
if (till_version is not None) and (self.version > till_version):
return
if (since_version is not None) and (self.version < since_version):
return
setattr(self.bl, field, getattr(self.m3, field))
def vec3(self, field, since_version=None):
if (since_version is not None) and (self.version < since_version):
return
setattr(self.bl, field, to_bl_vec3(getattr(self.m3, field)))
def vec4(self, field, since_version=None):
if (since_version is not None) and (self.version < since_version):
return
setattr(self.bl, field, to_bl_vec4(getattr(self.m3, field)))
def color(self, field, since_version=None):
if (since_version is not None) and (self.version < since_version):
return
setattr(self.bl, field, to_bl_color(getattr(self.m3, field)))
def enum(self, field, since_version=None, till_version=None):
if (till_version is not None) and (self.version > till_version):
return
if (since_version is not None) and (self.version < since_version):
return
if getattr(self.m3, field) == 0xFFFFFFFF:
return
try:
value = self.bl.bl_rna.properties[field].enum_items[getattr(self.m3, field)].identifier
setattr(self.bl, field, value)
except IndexError:
self.importer.warn_strings.append(f'Could not set {self.bl}.{field} due to the m3 value ({getattr(self.m3, field)}) being out of range ({len(self.bl.bl_rna.properties[field].enum_items)})')
def anim_boolean_flag(self, field):
self.anim_integer(field)
def anim_integer(self, field):
anim_ref = getattr(self.m3, field)
setattr(self.bl, field, anim_ref.default)
key_fcurves(self.importer.stc_id_data, self.bl, field, anim_ref.header, (anim_ref.default,))
def anim_int16(self, field):
self.anim_integer(field)
def anim_uint16(self, field):
self.anim_integer(field)
def anim_uint32(self, field):
self.anim_integer(field)
def anim_float(self, field, since_version=None):
if (since_version is not None) and (self.version < since_version):
return
anim_ref = getattr(self.m3, field)
setattr(self.bl, field, anim_ref.default)
key_fcurves(self.importer.stc_id_data, self.bl, field, anim_ref.header, (anim_ref.default,))
def anim_vec2(self, field):
anim_ref = getattr(self.m3, field)
default = to_bl_vec2(anim_ref.default)
setattr(self.bl, field, default)
key_fcurves(self.importer.stc_id_data, self.bl, field, anim_ref.header, default)
def anim_vec3(self, field, since_version=None):
if (since_version is not None) and (self.version < since_version):
return
anim_ref = getattr(self.m3, field)
default = to_bl_vec3(anim_ref.default)
setattr(self.bl, field, default)
key_fcurves(self.importer.stc_id_data, self.bl, field, anim_ref.header, default)
def anim_color(self, field, since_version=None):
if (since_version is not None) and (self.version < since_version):
return
anim_ref = getattr(self.m3, field)
default = to_bl_color(anim_ref.default)
setattr(self.bl, field, default)
key_fcurves(self.importer.stc_id_data, self.bl, field, anim_ref.header, default)
def m3_key_collect_evnt(key_frames, key_values):
pass # handle these specially
def m3_key_collect_real(key_frames, key_values):
ll = ([],)
for key_frame, key_value in zip(key_frames, key_values):
ll[0].extend((key_frame, key_value))
return ll
def m3_key_collect_vec2(key_frames, key_values):
ll = ([], [])
for key_frame, key_value in zip(key_frames, key_values):
ll[0].extend((key_frame, key_value.x))
ll[1].extend((key_frame, key_value.y))
return ll
def m3_key_collect_vec3(key_frames, key_values):
ll = ([], [], [])
for key_frame, key_value in zip(key_frames, key_values):
ll[0].extend((key_frame, key_value.x))
ll[1].extend((key_frame, key_value.y))
ll[2].extend((key_frame, key_value.z))
return ll
def m3_key_collect_quat(key_frames, key_values):
ll = ([], [], [], [])
for key_frame, key_value in zip(key_frames, key_values):
ll[0].extend((key_frame, key_value.w))
ll[1].extend((key_frame, key_value.x))
ll[2].extend((key_frame, key_value.y))
ll[3].extend((key_frame, key_value.z))
return ll
def m3_key_collect_colo(key_frames, key_values):
ll = ([], [], [], [])
for key_frame, key_value in zip(key_frames, key_values):
ll[0].append(key_frame)
ll[0].append(key_value.r / 255)
ll[1].append(key_frame)
ll[1].append(key_value.g / 255)
ll[2].append(key_frame)
ll[2].append(key_value.b / 255)
ll[3].append(key_frame)
ll[3].append(key_value.a / 255)
return ll
def m3_key_collect_sd08(key_frames, key_values):
pass # undefined
def m3_key_collect_bnds(key_frames, key_values):
pass # handle these specially
m3_key_type_collection_method = [
m3_key_collect_evnt, m3_key_collect_vec2, m3_key_collect_vec3, m3_key_collect_quat, m3_key_collect_colo, m3_key_collect_real, m3_key_collect_sd08,
m3_key_collect_real, m3_key_collect_real, m3_key_collect_real, m3_key_collect_real, m3_key_collect_real, m3_key_collect_bnds,
]
def key_fcurves(stc_dict, bl, field, header, default):
if not hasattr(bl, field):
return
path = bl.path_from_id(field)
for ii, val in enumerate(default):
set_default_value(bl.id_data.m3_animations_default, path, ii, val)
if type(header) == shared.M3AnimHeaderProp:
anim_id_data = stc_dict.get(int(header.hex_id, 16))
else:
anim_id_data = stc_dict.get(header.id)
bl_header = getattr(bl, field + '_header')
bl_header.hex_id = hex(header.id)[2:]
if not anim_id_data:
bl_header.interpolation = 'AUTO'
bl_header.flags = -1
return
bl_header.interpolation = 'LINEAR' if header.interpolation else 'CONSTANT'
bl_header.flags = header.flags if header.flags else -1
if not anim_id_data:
return
for action_name in anim_id_data.keys():
anim_id_action_data = anim_id_data[action_name]
points_len = len(anim_id_action_data[0]) // 2
if type(header) == shared.M3AnimHeaderProp:
interp_seq = [0 if header.interpolation == 'CONSTANT' else 1] * points_len # TODO calculate AUTO based on field name
else:
interp_seq = [header.interpolation] * points_len
key_sel_seq = [False] * points_len
for index, index_data in enumerate(anim_id_action_data):
fcurves = bpy.data.actions.get(action_name).fcurves
fcurve = fcurves.new(path, index=index)
fcurve.select = False
fcurve.keyframe_points.add(points_len)
fcurve.keyframe_points.foreach_set('co', index_data)
fcurve.keyframe_points.foreach_set('interpolation', interp_seq)
fcurve.keyframe_points.foreach_set('select_control_point', key_sel_seq)
fcurve.keyframe_points.foreach_set('select_left_handle', key_sel_seq)
fcurve.keyframe_points.foreach_set('select_right_handle', key_sel_seq)
def armature_object_new():
scene = bpy.context.scene
arm = bpy.data.armatures.new(name='Armature')
ob = bpy.data.objects.new('Armature', arm)
ob.location = scene.cursor.location
scene.collection.objects.link(ob)
return ob
class Importer:
def __init__(self, bl_op=None):
self.filepath = ''
self.bl_op = bl_op
self.warn_strings = []
self.exception_trace = ''
def do_report(self):
if len(self.warn_strings):
warning = f'The following warnings were given during the M3 import operation of {self.filepath}:\n' + '\n'.join(self.warn_strings)
print(warning) # not for debugging
if self.bl_op:
self.bl_op.report({"WARNING"}, warning)
self.warn_strings = [] # reset warnings
if self.exception_trace:
print(self.exception_trace)
if self.bl_op:
self.bl_op.report({"ERROR"}, self.exception_trace)
self.exception_trace = ''
def m3_import(self, filepath, ob=None, opts=None):
self.filepath = filepath
# TODO make fps an import option
bpy.context.scene.render.fps = FRAME_RATE
self.get_rig, self.get_anims, self.get_mesh, self.get_effects = opts if opts != None else [True] * 4
self.m3 = io_m3.M3SectionList.load(filepath)
self.m3_model = self.m3[self.m3[0][0].model][0]
self.m3_division = self.m3[self.m3_model.divisions][0]
self.m3_bl_ref = {}
self.bl_ref_objects = []
self.stc_id_data = {}
self.final_bone_names = {}
self.is_new_object = not ob
self.ob = ob or armature_object_new()
anims_len = len(self.ob.m3_animation_groups)
matref_len = len(self.ob.m3_materialrefs)
self.anim_index = lambda x: anims_len + x
self.matref_index = lambda x: matref_len + x
self.m3_struct_version_set_from_ref('m3_model_version', self.m3[0][0].model)
if self.get_rig:
if self.get_anims:
self.create_animations()
self.create_bones()
self.create_attachments()
self.create_hittests()
self.create_rigid_bodies()
self.create_rigid_body_joints()
self.create_cameras()
self.create_billboards()
self.create_ik_joints()
self.create_turrets()
self.create_shadow_boxes()
self.create_tmd()
if self.get_rig and self.get_mesh:
self.create_bounding()
if self.get_mesh or self.get_effects:
self.create_materials()
if self.get_mesh:
self.create_mesh()
if self.get_mesh and self.get_rig:
self.create_cloths()
if self.get_effects:
self.create_lights()
self.create_particles()
self.create_ribbons()
self.create_projections()
self.create_forces()
self.create_warps()
if self.is_new_object:
ob_anim_data_set(bpy.context.scene, self.ob, None)
bpy.context.view_layer.objects.active = self.ob
self.ob.select_set(True)
# lazy way to filter out materials unused by the imported data, but it works
user_matref_index = self.ob.m3_materialrefs_index
for ii in reversed(range(len(self.ob.m3_materialrefs))[matref_len:]):
self.ob.m3_materialrefs_index = ii
bpy.ops.m3.material_remove('INVOKE_DEFAULT', quiet=True)
self.ob.m3_materialrefs_index = user_matref_index
def m3a_import(self, filepath, ob):
def get_m3_id_props():
hex_id_to_props = {}
collections = [
ob.m3_cameras, ob.m3_forces, ob.m3_lights, ob.m3_materiallayers, ob.m3_materials_standard, ob.m3_materials_displacement,
ob.m3_materials_composite, ob.m3_materials_volume, ob.m3_materials_volumenoise, ob.m3_materials_reflection, ob.m3_materials_lensflare,
ob.m3_particlesystems, ob.m3_particlecopies, ob.m3_projections, ob.m3_ribbons, ob.m3_ribbonsplines, ob.m3_shadowboxes, ob.m3_warps,
]
def get_anim_ids(collection):
for item in collection:
for key in type(item).__annotations__.keys():
prop = getattr(item, key)
if type(prop) == shared.M3AnimHeaderProp:
prop_path = prop.path_from_id()[:-7] # removing the _header suffix
prop_id_int = int(prop.hex_id, 16)
try:
hex_id_to_props[prop_id_int].append(prop_path)
except KeyError:
hex_id_to_props[prop_id_int] = [prop_path]
elif str(type(prop)) == '<class \'bpy_prop_collection_idprop\'>':
get_anim_ids(prop)
for collection in collections:
get_anim_ids(collection)
return hex_id_to_props
# TODO make fps an import options
bpy.context.scene.render.fps = FRAME_RATE
ob_anim_data_set(bpy.context.scene, ob, None)
self.is_new_object = False
self.ob = ob
self.m3 = io_m3.M3SectionList.load(filepath)
self.m3_model = self.m3[self.m3[0][0].model][0]
self.stc_id_data = {}
anims_len = len(self.ob.m3_animation_groups)
self.anim_index = lambda x: anims_len + x
self.create_animations()
m3_id_prop_paths = get_m3_id_props()
for anim_id_data, paths in m3_id_prop_paths.items():
rs = paths[0].rsplit('.', 1)
prop = ob.path_resolve(paths[0])
try: # put prop in a tuple if it is not already
key_fcurves(self.stc_id_data, ob.path_resolve(rs[0]), rs[1], ob.path_resolve(paths[0] + '_header'), prop)
except TypeError:
key_fcurves(self.stc_id_data, ob.path_resolve(rs[0]), rs[1], ob.path_resolve(paths[0] + '_header'), (prop,))
bind_mats = {}
for pb in ob.pose.bones:
db = ob.data.bones.get(pb.name)
# "exporting" bone matrix to get default bone pose in m3 terms
bind_scale_inv = mathutils.Vector((1.0 / pb.m3_bind_scale[ii] for ii in range(3)))
bind_scale_inv_matrix = mathutils.Matrix.LocRotScale(None, None, bind_scale_inv.yxz)
if pb.parent:
parent_bind_mat = mathutils.Matrix.LocRotScale(None, None, pb.parent.m3_bind_scale.yxz)
left_out_mat = parent_bind_mat @ io_shared.rot_fix_matrix @ db.parent.matrix_local.inverted() @ db.matrix_local
else:
left_out_mat = db.matrix_local
right_out_mat = io_shared.rot_fix_matrix_transpose @ bind_scale_inv_matrix
pose_mat = ob.convert_space(pose_bone=pb, matrix=pb.matrix, from_space='LOCAL', to_space='POSE')
defaults = (left_out_mat @ pose_mat @ right_out_mat).decompose()
# now importing with the m3 defaults of the current pose
rel_mat = db.matrix_local.inverted() if not pb.parent else (db.parent.matrix_local.inverted() @ db.matrix_local).inverted()
bind_mat = bind_mats[pb] = mathutils.Matrix.LocRotScale(None, None, pb.m3_bind_scale.yxz)
anim_ids = (int(pb.m3_location_hex_id, 16), int(pb.m3_rotation_hex_id, 16), int(pb.m3_scale_hex_id, 16), int(pb.m3_batching_hex_id, 16))
left_in_mat = rel_mat if not pb.parent else rel_mat @ io_shared.rot_fix_matrix_transpose @ bind_mats[pb.parent].inverted()
right_in_mat = bind_mat @ io_shared.rot_fix_matrix
self.animate_pose_bone(anim_ids, defaults, pb, left_in_mat, right_in_mat)
def m3_struct_version_set_from_ref(self, version_attr, ref):
if ref.index and ref.entries:
version_val = self.m3[ref].desc.version
if not self.is_new_object:
setattr(self.ob, version_attr, str(max(int(getattr(self.ob, version_attr)), version_val)))
else:
setattr(self.ob, version_attr, str(version_val))
def m3_get_bone_name(self, bone_index):
if bone_index < 0:
return None
imported_bone_name = self.final_bone_names.get(bone_index)
if imported_bone_name:
return imported_bone_name
m3_bone = self.m3[self.m3_model.bones][bone_index]
return self.m3[m3_bone.name].content_to_string()
def animate_pose_bone(self, anim_ids, defaults, pose_bone, left_mat, right_mat):
id_data_loc = self.stc_id_data.get(anim_ids[0], {})
id_data_rot = self.stc_id_data.get(anim_ids[1], {})
id_data_scl = self.stc_id_data.get(anim_ids[2], {})
action_name_set = set().union(id_data_loc.keys(), id_data_rot.keys(), id_data_scl.keys())
default_loc, default_rot, default_scl = defaults
for action_name in action_name_set:
anim_data_loc = id_data_loc.get(action_name, None)
anim_data_rot = id_data_rot.get(action_name, None)
anim_data_scl = id_data_scl.get(action_name, None)
anim_data_loc_none = not anim_data_loc
if anim_data_loc_none:
anim_data_loc = [[0, default_loc.x], [0, default_loc.y], [0, default_loc.z]]
anim_data_rot_none = not anim_data_rot
if anim_data_rot_none:
anim_data_rot = [[0, default_rot.w], [0, default_rot.x], [0, default_rot.y], [0, default_rot.z]]
anim_data_scl_none = not anim_data_scl
if anim_data_scl_none:
anim_data_scl = [[0, default_scl.x], [0, default_scl.y], [0, default_scl.z]]
anim_frames = [anim_data_loc[0][::2], anim_data_rot[0][::2], anim_data_scl[0][::2]]
anim_frames_set = set().union(*anim_frames)
if not anim_frames_set:
return
# we put in original data first so that we can evaluate the fcurves.
# blender interpolates the data we need to apply the correction matrices for us.
# * can we interpolate based on interpolation of m3 anim header?
fcurves = bpy.data.actions.get(action_name).fcurves
# store fcurve references so that we don't have to find them later
fcurves_loc = []
for index, index_data in enumerate(anim_data_loc):
points_len = len(index_data) // 2
fcurve = fcurves.new(pose_bone.path_from_id('location'), index=index, action_group=pose_bone.name)
fcurve.select = False
fcurve.keyframe_points.add(points_len)
fcurve.keyframe_points.foreach_set('co', index_data)
fcurve.keyframe_points.foreach_set('interpolation', [1] * points_len)
fcurve.keyframe_points.foreach_set('select_control_point', key_sel := [False] * points_len)
fcurve.keyframe_points.foreach_set('select_left_handle', key_sel)
fcurve.keyframe_points.foreach_set('select_right_handle', key_sel)
fcurves_loc.append(fcurve)
fcurves_rot = []
for index, index_data in enumerate(anim_data_rot):
points_len = len(index_data) // 2
fcurve = fcurves.new(pose_bone.path_from_id('rotation_quaternion'), index=index, action_group=pose_bone.name)
fcurve.select = False
fcurve.keyframe_points.add(points_len)
fcurve.keyframe_points.foreach_set('co', index_data)
fcurve.keyframe_points.foreach_set('interpolation', [1] * points_len)
fcurve.keyframe_points.foreach_set('select_control_point', key_sel := [False] * points_len)
fcurve.keyframe_points.foreach_set('select_left_handle', key_sel)
fcurve.keyframe_points.foreach_set('select_right_handle', key_sel)
fcurves_rot.append(fcurve)
fcurves_scl = []
for index, index_data in enumerate(anim_data_scl):
points_len = len(index_data) // 2
fcurve = fcurves.new(pose_bone.path_from_id('scale'), index=index, action_group=pose_bone.name)
fcurve.select = False
fcurve.keyframe_points.add(points_len)
fcurve.keyframe_points.foreach_set('co', index_data)
fcurve.keyframe_points.foreach_set('interpolation', [1] * points_len)
fcurve.keyframe_points.foreach_set('select_control_point', key_sel := [False] * points_len)
fcurve.keyframe_points.foreach_set('select_left_handle', key_sel)
fcurve.keyframe_points.foreach_set('select_right_handle', key_sel)
fcurves_scl.append(fcurve)
new_anim_data = [[], [], []]
pre_rot = None
for frame in sorted(list(anim_frames_set)):
eval_loc = mathutils.Vector([fcurve.evaluate(frame) for fcurve in fcurves_loc])
eval_rot = mathutils.Quaternion([fcurve.evaluate(frame) for fcurve in fcurves_rot])
eval_scl = mathutils.Vector([fcurve.evaluate(frame) for fcurve in fcurves_scl])
loc, rot, scl = (left_mat @ mathutils.Matrix.LocRotScale(eval_loc, eval_rot, eval_scl) @ right_mat).decompose()
if pre_rot:
rot.make_compatible(pre_rot)
pre_rot = rot
if frame in anim_frames[0]:
new_anim_data[0].append(loc)
if frame in anim_frames[1]:
new_anim_data[1].append(rot)
if frame in anim_frames[2]:
new_anim_data[2].append(scl)
# second pass animation data, after evaluation
new_anim_data_loc = m3_key_collect_vec3(anim_frames[0], new_anim_data[0])
new_anim_data_rot = m3_key_collect_quat(anim_frames[1], new_anim_data[1])
new_anim_data_scl = m3_key_collect_vec3(anim_frames[2], new_anim_data[2])
for index, index_data in enumerate(new_anim_data_loc):
fcurve = fcurves_loc[index]
if anim_data_loc_none:
fcurves.remove(fcurve)
else:
fcurve.keyframe_points.foreach_set('co', index_data)
for index, index_data in enumerate(new_anim_data_rot):
fcurve = fcurves_rot[index]
if anim_data_rot_none:
fcurves.remove(fcurve)
else:
fcurve.keyframe_points.foreach_set('co', index_data)
for index, index_data in enumerate(new_anim_data_scl):
fcurve = fcurves_scl[index]
if anim_data_scl_none:
fcurves.remove(fcurve)
else:
fcurve.keyframe_points.foreach_set('co', index_data)
# import bone batching flag
id_data_render = self.stc_id_data.get(anim_ids[3], {})
if id_data_render:
for action_name in id_data_render.keys():
action = bpy.data.actions.get(action_name)
key_frame_points_len = len(id_data_render[action_name][0]) // 2
fcurve = action.fcurves.new(pose_bone.path_from_id('m3_batching'), action_group=pose_bone.name)
fcurve.select = False
fcurve.keyframe_points.add(key_frame_points_len)
fcurve.keyframe_points.foreach_set('co', id_data_render[action_name][0])
fcurve.keyframe_points.foreach_set('interpolation', [0] * key_frame_points_len)
def create_animations(self):
ob = self.ob
if self.is_new_object:
ob.m3_animations_default = bpy.data.actions.new(ob.name + '_DEFAULTS')
for m3_seq, m3_stg in zip(self.m3[self.m3_model.sequences], self.m3[self.m3_model.sequence_transformation_groups]):
anim_group_name = self.m3[m3_seq.name].content_to_string()
anim_group = shared.m3_item_add(ob.m3_animation_groups, anim_group_name)
seq_processor = M3InputProcessor(self, anim_group, m3_seq)
io_shared.io_anim_group(seq_processor)
anim_group['frame_start'] = to_bl_frame(m3_seq.anim_ms_start)
anim_group['frame_end'] = to_bl_frame(m3_seq.anim_ms_end)
for m3_stc_index in self.m3[m3_stg.stc_indices]:
m3_stc = self.m3[self.m3_model.sequence_transformation_collections][m3_stc_index]
if not m3_stc.name.index:
continue
anim_name = self.m3[m3_stc.name].content_to_string().replace(anim_group_name, '')[1:]
anim = shared.m3_item_add(anim_group.animations, anim_name)
anim['concurrent'] = m3_stc.concurrent
anim['priority'] = m3_stc.priority
anim['action'] = bpy.data.actions.new(f'{ob.name}_{anim_group.name}_{anim.name}')
m3_key_type_collection_list = [
m3_stc.sdev, m3_stc.sd2v, m3_stc.sd3v, m3_stc.sd4q, m3_stc.sdcc, m3_stc.sdr3, m3_stc.sd08,
m3_stc.sds6, m3_stc.sdu6, m3_stc.sds3, m3_stc.sdu3, m3_stc.sdfg, m3_stc.sdmb,
]
for stc_id, stc_ref in zip(self.m3[m3_stc.anim_ids], self.m3[m3_stc.anim_refs]):
anim_type = stc_ref >> 16
anim_index = stc_ref & 0xffff
m3_key_type_collection = m3_key_type_collection_list[anim_type]
m3_key_entries = self.m3[m3_key_type_collection][anim_index]
frames = []
ignored_indices = []
for ii, ms in enumerate(self.m3[m3_key_entries.frames]):
frame = to_bl_frame(ms)
if frame not in frames:
frames.append(frame)
else:
frames[-1] = frame
ignored_indices.append(ii - 1)
m3_keys = self.m3[m3_key_entries.keys]
keys = [m3_keys[ii] for ii in range(len(m3_keys)) if ii not in ignored_indices]
try:
self.stc_id_data[stc_id][anim.action.name] = m3_key_type_collection_method[anim_type](frames, keys)
except KeyError:
self.stc_id_data[stc_id] = {}
self.stc_id_data[stc_id][anim.action.name] = m3_key_type_collection_method[anim_type](frames, keys)
# consider making a dedicated property type and collection list for events
if m3_key_type_collection == m3_stc.sdev:
for ii, frame in enumerate(frames):
key = keys[ii]
event_name = self.m3[key.name].content_to_string()
if event_name == 'Evt_Simulate':
anim_group['simulate'] = True
anim_group['simulate_frame'] = frame
anim_group['animations_index'] = len(anim_group.animations) - 1
def create_bones(self):
def get_bone_tails(m3_bones, bone_heads, bone_vectors):
child_bone_indices = [[] for ii in m3_bones]
for bone_index, bone_entry in enumerate(m3_bones):
if bone_entry.parent != -1:
child_bone_indices[bone_entry.parent].append(bone_index)
tails = []
for m3_bone, child_indices, head, vector in zip(m3_bones, child_bone_indices, bone_heads, bone_vectors):
length = 0.1
for child_index in child_indices:
head_to_child_head = bone_heads[child_index] - head
if head_to_child_head.length >= 0.01 and abs(head_to_child_head.angle(vector)) < 0.1:
length = head_to_child_head.length
tail_offset = length * vector
tail = head + tail_offset
while (tail - head).length == 0:
tail_offset *= 2
tail = head + tail_offset
tails.append(tail)
return tails
def get_bone_rolls(bone_rests, bone_heads, bone_tails):
rolls = []
for iref, head, tail in zip(bone_rests, bone_heads, bone_tails):
v = (tail - head).normalized()
target = mathutils.Vector((0, 1, 0))
axis = target.cross(v)
if axis.dot(axis) > 0.000001:
axis.normalize()
theta = target.angle(v)
b_matrix = mathutils.Matrix.Rotation(theta, 3, axis)
else:
sign = 1 if target.dot(v) > 0 else -1
b_matrix = mathutils.Matrix((
(sign, 0, 0),
(0, sign, 0),
(0, 0, 1),
))
rot_matrix = mathutils.Matrix.Rotation(0, 3, v) @ b_matrix
rot_matrix = rot_matrix.to_4x4()
rot_matrix.translation = head
matrix33 = rot_matrix.to_3x3()
z_x = matrix33.col[2].angle(iref.col[0].to_3d())
z_z = matrix33.col[2].angle(iref.col[2].to_3d())
roll_angle = z_z if z_x > math.pi / 2 else -z_z
rolls.append(roll_angle)
return rolls
def get_edit_bones(m3_bones, bone_heads, bone_tails, bone_rolls):
edit_bones = []
for index, m3_bone in enumerate(m3_bones):
m3_bone_name = self.m3[m3_bone.name].content_to_string()
edit_bone = self.ob.data.edit_bones.new(m3_bone_name)
self.final_bone_names[index] = edit_bone.name
edit_bones.append(edit_bone)
for index, m3_bone in enumerate(m3_bones):
edit_bone = edit_bones[index]
edit_bone.head = bone_heads[index]
edit_bone.tail = bone_tails[index]
edit_bone.roll = bone_rolls[index]
edit_bone.select_tail = False
if m3_bone.parent != -1:
parent_edit_bone = self.ob.data.edit_bones[m3_bone.parent]
edit_bone.parent = parent_edit_bone
parent_child_vector = parent_edit_bone.tail - edit_bone.head
if parent_child_vector.length < 0.000001:
edit_bone.use_connect = True
return edit_bones
def get_edit_bone_relations(m3_bones, edit_bones):
rel_mats = []
for m3_bone, edit_bone in zip(m3_bones, edit_bones):
if m3_bone.parent != -1:
parent_edit_bone = self.ob.data.edit_bones.get(self.m3_get_bone_name(m3_bone.parent))
rel_mats.append((parent_edit_bone.matrix.inverted() @ edit_bone.matrix).inverted())
else:
rel_mats.append(edit_bone.matrix.inverted())
return rel_mats
def adjust_pose_bones(m3_bones, edit_bone_relations, bind_scales, bind_matrices):
for ii, m3_bone, rel_mat, bind_scl, bind_mat in zip(range(len(m3_bones)), m3_bones, edit_bone_relations, bind_scales, bind_matrices):
if m3_bone.parent != -1:
bind_mat.transpose()
left_mat = rel_mat if m3_bone.parent == -1 else rel_mat @ io_shared.rot_fix_matrix_transpose @ bind_matrices[m3_bone.parent].inverted()
right_mat = bind_mat @ io_shared.rot_fix_matrix
bone_mat_comp = to_bl_vec3(m3_bone.location.default), to_bl_quat(m3_bone.rotation.default), to_bl_vec3(m3_bone.scale.default)
bone_mat = mathutils.Matrix.LocRotScale(*bone_mat_comp)
pose_bone = self.ob.pose.bones.get(self.m3_get_bone_name(ii))
pose_bone.matrix_basis = left_mat @ bone_mat @ right_mat
pose_bone.bl_handle = shared.m3_handle_gen()
pose_bone.m3_bind_scale = (bind_scl[1], bind_scl[0], bind_scl[2])
bone_id_lock = self.ob.m3_bone_id_lockers.add()
bone_id_lock.bone = pose_bone.bl_handle
pose_bone.m3_batching = bool(m3_bone.batching.default)
pose_bone.m3_location_hex_id = hex(m3_bone.location.header.id)[2:]
pose_bone.m3_rotation_hex_id = hex(m3_bone.rotation.header.id)[2:]
pose_bone.m3_scale_hex_id = hex(m3_bone.scale.header.id)[2:]
pose_bone.m3_batching_hex_id = hex(m3_bone.batching.header.id)[2:]
m3_anim_ids = (m3_bone.location.header.id, m3_bone.rotation.header.id, m3_bone.scale.header.id, m3_bone.batching.header.id)
m3_defaults = (m3_bone.location.default, m3_bone.rotation.default, m3_bone.scale.default)
set_default_value(self.ob.m3_animations_default, pose_bone.path_from_id('location'), 0, pose_bone.location[0])
set_default_value(self.ob.m3_animations_default, pose_bone.path_from_id('location'), 1, pose_bone.location[1])
set_default_value(self.ob.m3_animations_default, pose_bone.path_from_id('location'), 2, pose_bone.location[2])
set_default_value(self.ob.m3_animations_default, pose_bone.path_from_id('rotation_quaternion'), 0, pose_bone.rotation_quaternion[0])
set_default_value(self.ob.m3_animations_default, pose_bone.path_from_id('rotation_quaternion'), 1, pose_bone.rotation_quaternion[1])
set_default_value(self.ob.m3_animations_default, pose_bone.path_from_id('rotation_quaternion'), 2, pose_bone.rotation_quaternion[2])
set_default_value(self.ob.m3_animations_default, pose_bone.path_from_id('rotation_quaternion'), 3, pose_bone.rotation_quaternion[3])
set_default_value(self.ob.m3_animations_default, pose_bone.path_from_id('scale'), 0, pose_bone.scale[0])
set_default_value(self.ob.m3_animations_default, pose_bone.path_from_id('scale'), 1, pose_bone.scale[1])
set_default_value(self.ob.m3_animations_default, pose_bone.path_from_id('scale'), 2, pose_bone.scale[2])
set_default_value(self.ob.m3_animations_default, pose_bone.path_from_id('m3_batching'), 0, pose_bone.m3_batching)
self.animate_pose_bone(m3_anim_ids, m3_defaults, pose_bone, left_mat, right_mat)
bpy.context.view_layer.objects.active = self.ob
bl_irefs = []
bone_rests = []
bind_scales = []
bind_matrices = []
bone_heads = []
bone_vectors = []
m3_bones = self.m3[self.m3_model.bones]
for iref, m3_bone in zip(self.m3[self.m3_model.bone_rests], m3_bones):
orig_mat = to_bl_matrix(iref.matrix)
mat = orig_mat.copy()
mat_scale = mat.to_scale()
for ii in range(3):
if mat_scale[ii] < 0:
mat[ii] = -mat[ii]
bl_irefs.append(mat)
try:
bone_rests.append(mat.inverted() @ io_shared.rot_fix_matrix)
except ValueError:
bone_rests.append(mathutils.Matrix() @ io_shared.rot_fix_matrix)
bind_scales.append((orig_mat @ io_shared.rot_fix_matrix_transpose).to_scale().yxz)
bone_heads.append(bone_rests[-1].translation)
bone_vectors.append(bone_rests[-1].col[1].to_3d().normalized())
bone_tails = get_bone_tails(m3_bones, bone_heads, bone_vectors)
bone_rolls = get_bone_rolls(bone_rests, bone_heads, bone_tails)
bpy.ops.object.mode_set(mode='EDIT', toggle=False)
edit_bones = get_edit_bones(m3_bones, bone_heads, bone_tails, bone_rolls)
edit_bone_relations = get_edit_bone_relations(m3_bones, edit_bones)
bpy.ops.object.mode_set(mode='OBJECT', toggle=False)
# this fixes the scale of bone rest matrices that use an unusual matrix form
for ii, m3_bone in enumerate(m3_bones):
db = self.ob.data.bones.get(self.m3[m3_bone.name].content_to_string())
bone_local_inv_matrix = (db.matrix_local @ io_shared.rot_fix_matrix_transpose).inverted()
iref = bl_irefs[ii]
out_iref = mathutils.Matrix.LocRotScale(None, None, bind_scales[ii]) @ bone_local_inv_matrix
# hacky solution for certain import problems, could cause problems elsewhere
sub_x = abs(abs(sum(iref[0])) - abs(sum(out_iref[0]))) + 1
sub_y = abs(abs(sum(iref[1])) - abs(sum(out_iref[1]))) + 1
sub_z = abs(abs(sum(iref[2])) - abs(sum(out_iref[2]))) + 1
div_x = sum(iref[0]) / sum(out_iref[0]) if (sum(iref[0]) and sum(out_iref[0])) else 1
div_y = sum(iref[1]) / sum(out_iref[1]) if (sum(iref[1]) and sum(out_iref[1])) else 1
div_z = sum(iref[2]) / sum(out_iref[2]) if (sum(iref[2]) and sum(out_iref[2])) else 1
if abs(sum((sub_x, sub_y, sub_z))) < abs(sum((div_x, div_y, div_z))):
bind_fac_x = abs(abs(sum(iref[0])) - abs(sum(out_iref[0]))) + 1
bind_fac_y = abs(abs(sum(iref[1])) - abs(sum(out_iref[1]))) + 1
bind_fac_z = abs(abs(sum(iref[2])) - abs(sum(out_iref[2]))) + 1
else:
bind_fac_x = abs(sum(iref[0]) / sum(out_iref[0])) if (sum(iref[0]) and sum(out_iref[0])) else 1
bind_fac_y = abs(sum(iref[1]) / sum(out_iref[1])) if (sum(iref[1]) and sum(out_iref[1])) else 1
bind_fac_z = abs(sum(iref[2]) / sum(out_iref[2])) if (sum(iref[2]) and sum(out_iref[2])) else 1
bind_scales[ii][0] = bind_scales[ii][0] * bind_fac_x
bind_scales[ii][1] = bind_scales[ii][1] * bind_fac_y
bind_scales[ii][2] = bind_scales[ii][2] * bind_fac_z
bind_matrices.append(mathutils.Matrix.LocRotScale(None, None, bind_scales[ii]))
adjust_pose_bones(m3_bones, edit_bone_relations, bind_scales, bind_matrices)
def create_materials(self):
ob = self.ob
if self.m3[self.m3_model.materials_standard]:
standard_m3_version = self.m3[self.m3_model.materials_standard].desc.version
standard_bl_version = int(self.ob.m3_materials_standard_version)
if standard_m3_version > 16 and standard_bl_version <= 16:
for mat in self.ob.m3_materials_standard:
mat.geometry_visible = True
self.warn_strings.append(f'Existing material {mat.name} "Geometry Visible" flag automatically checked, due to material version upgrade.')
self.m3_struct_version_set_from_ref('m3_materials_standard_version', self.m3_model.materials_standard)
standard_bl_version = int(self.ob.m3_materials_standard_version)
if hasattr(self.m3_model, 'materials_reflection'):
self.m3_struct_version_set_from_ref('m3_materials_reflection_version', self.m3_model.materials_reflection)
layer_section_to_index = {}
for m3_matref in self.m3[self.m3_model.material_references]:
m3_mat = self.m3[getattr(self.m3_model, shared.material_type_to_model_reference[m3_matref.type])][m3_matref.material_index]
mat_col = getattr(ob, shared.material_collections[m3_matref.type])
matref = shared.m3_item_add(ob.m3_materialrefs, item_name=self.m3[m3_mat.name].content_to_string())
mat = shared.m3_item_add(mat_col, item_name=matref.name)
processor = M3InputProcessor(self, mat, m3_mat)
io_shared.material_type_io_method[m3_matref.type](processor)
matref.mat_type = shared.material_collections[m3_matref.type]
matref.mat_handle = mat.bl_handle
if m3_matref.type == 1: # standard materials
if standard_m3_version <= 16 and standard_bl_version > 16:
mat.geometry_visible = True
self.warn_strings.append(f'Imported material {matref.name} "Geometry Visible" flag automatically checked, due to material version upgrade.')
elif m3_matref.type == 11: # lens flare materials
for m3_starburst in self.m3[m3_mat.starbursts]:
starburst = shared.m3_item_add(mat.starbursts)
processor = M3InputProcessor(self, starburst, m3_starburst)
io_shared.io_starburst(processor)
elif m3_matref.type == 12: # buffer (madd) materials
for schr in self.m3[m3_mat.texture_paths]:
m3_texture_path = self.m3[schr.path]
if m3_texture_path:
texture_path = mat.texture_paths.add()
texture_path['name'] = self.m3[schr.path].content_to_string()
for layer_name in shared.material_type_to_layers[m3_matref.type]:
m3_layer_field = getattr(m3_mat, 'layer_' + layer_name, None)
if not m3_layer_field:
continue
if m3_layer_field.index in layer_section_to_index.keys():
layer = ob.m3_materiallayers[layer_section_to_index[m3_layer_field.index]]
setattr(mat, 'layer_' + layer_name, layer.bl_handle)