forked from Oygron/SupCom_Import_Export_Blender
-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathsupcom-importer.py
1196 lines (896 loc) · 36 KB
/
supcom-importer.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
#**************************************************************************************************
# Supreme Commander Importer for Blender3D - www.blender3d.org
#
# Written by dan - www.sup-com.net
#
# History
# 0.1.0 06/06/06 - Initial version.
# 0.2.0 06/06/10 - Added SCA (Animation) support
# 0.3.0 06/07/02 - Alpha release
# 0.4.0 2014-07-13 - Adapted to Blender 2.71
# 0.5.0 2019-08-29 - Adapted to Blender 2.80
# 0.5.1 2019-10-13 - Added support for importing files with more vertices
# 0.5.2 2020-04-26 - Fixed the bone replacement dialogue not working for animations, and cleaned up a bit
# 0.5.3 2020-05-29 - Added Vague support for SCM v7 which is supcom 2 format.
#
# Todo
# - Material/uv map 2
# - Bone pos/rot for scm & sca. Not perfect to use gentle words.
# - Make sca loading independent of the scm_mesh. (e.g get bone pos/loc from armature instead)
# - GUI for loading
# - Progress bars
#
#**************************************************************************************************
bl_info = {
"name": "Supcom Importer 0.5.3",
"author": "dan & Brent & Oygron",
"version": (0,5,3),
"blender": (2, 80, 0),
"location": "File > Import-Export",
"description": "Imports Supcom files",
"warning": "",
"wiki_url": "https://github.com/Exotic-Retard/SupCom_Import_Export_Blender",
"category": "Import-Export",
}
DEBUGLOG = False
import bpy
#import Blender
#from Blender import NMesh, Scene, Object
from mathutils import *
from bgl import *
import os
from os import path
import struct
import string
import math
from math import *
from bpy_extras.io_utils import unpack_list, unpack_face_list
from string import *
from struct import *
from bpy.props import *
from time import sleep
VERSION = '5.3'
sca_filepath = [ "", "", "None"]
scm_filepath = [ "", "", "None"]
######################################################
# User defined behaviour, Select as you need
######################################################
#Enable Progress Bar ( 0 = faster )
PROG_BAR_ENABLE = 0
#how many steps a progress bar has (the lesser the faster)
PROG_BAR_STEP = 25
#LOG File for debuging
#Enable LOG File (0 = Disabled , 1 = Enabled )
LOG_ENABLE = 0
#Filename / Path. Default is blender directory Filename SC-E_LOG.txt
LOG_FILENAME = "SC-E_LOG.txt"
######################################################
# Init Supreme Commander SCM( _bone, _vertex, _mesh), SCA(_bone, _frame, _anim) Layout
######################################################
xy_to_xz_transform = Matrix(([1, 0, 0], [ 0, 0, 1], [ 0, -1, 0])).to_4x4()
# -1 0 0
# 0 0 1
# 0 1 0
#export matrix
xz_to_xy_transform = Matrix(([ 1, 0, 0],
[ 0, 0, -1],
[ 0, 1, 0])).to_4x4()
globMesh = []
MArmatureWorld = Matrix()
def my_popup(msg):
def draw(self, context):
self.layout.label(msg)
bpy.context.window_manager.popup_menu(draw, title="Error", icon='ERROR')
def my_popup_warn(msg):
def draw(self, context):
self.layout.label(msg)
bpy.context.window_manager.popup_menu(draw, title="Warning", icon='ERROR')
optionsList = [
("1","stuff 1","0"),("2","stuff 2","0"),("3","stuff 3","0")]
counter = 0
def uvtex_items(self, context):
return optionsList
# return [(t.name, t.name, t.name) for t in context.object.data.uv_textures]
def update_enum_options(self, context):
return global_bone_replacement_options_list
class OBJECT_OT_anim_replace_bone(bpy.types.Operator):
"""Tooltip description"""
bl_idname = "object.anim_replace_bone"
bl_label = "Animation Replacement"
#bl_options = {'REGISTER', 'UNDO'}
optsList : bpy.props.EnumProperty(name="Select Option", items=update_enum_options)
meshBones = None
anim = None
objBoneNames = None
bone_num = None
@classmethod
def poll(cls, context):
return True
def invoke(self, context, event):
return context.window_manager.invoke_props_dialog(self)
def draw(self, context):
layout = self.layout
col = layout.column()
col.prop(self, "optsList", expand=True)
def execute(self, context):
print("Replacement option selected:",self.optsList)
self.anim.bonenames[self.bone_num] = self.optsList
check_bone(self.meshBones,self.anim,self.objBoneNames,self.bone_num + 1)
return {'FINISHED'}
class scm_bone :
name = ""
#rest_pose_inv = []
rel_mat = Matrix()
rel_mat_inv = Matrix()
position = []
rotation = []
#abs_pos = []
parent = 0
parent_index = 0
rel_matrix_inv = []
#children = []
#numchildren = 0
#global xy_to_xz_transform
def __init__(self, name, rest_pose_inv = None, rotation = None, position = None, parent_index = 0):
self.name = name
#self.rest_pose_inv = [[0.0] * 4] * 4
#self.position = [0.0] * 3
#self.rotation = [0.0] * 4
self.parent_index = parent_index
if rest_pose_inv == None:
self.rel_mat_inv = Matrix(([0,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,0]))
self.rel_mat = Matrix(([0,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,0]))
else:
self.rel_mat_inv = rest_pose_inv
self.rel_mat = rest_pose_inv.inverted()
if rotation == None:
self.rotation = Quaternion((0,0,0,0))
else:
self.rotation = rotation
if position == None:
self.position = Vector((0,0,0))
else:
self.position = position
def load(self, file):
#global xy_to_xz_transform
bonestruct = '16f3f4f4l'
buffer = file.read(struct.calcsize(bonestruct))
readout = struct.unpack(bonestruct, buffer)
#supcom information:
readRPI = Matrix(([0,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,0]))
#// Inverse transform of the bone relative to the local origin of the mesh
#// 4x4 Matrix with row major (i.e. D3D default ordering)
for i in range(4):
readRPI[i] = readout[i*4:i*4+4]
self.rel_mat_inv = Matrix((readRPI[0], readRPI[1], readRPI[2], readRPI[3]))#*xy_to_xz_transform #note rot here changes pointing direction of spikie
self.rel_mat = self.rel_mat_inv.inverted()
#// Position relative to the parent bone.
pos = readout[16:19]
self.position = Vector((pos[0], pos[1], pos[2]))
#// Rotation relative to the parent bone.
rot = readout[19:23]
self.rotation = Quaternion(( rot[0], rot[1], rot[2], rot[3] ))
#// Index of the bone's parent in the SCM_BoneData array
self.parent_index = readout[24]
# Read bone name
#oldpos = file.tell()
#file.seek(bone[..], 0)
#self.name = file.readline()
#file.seek(oldpos, 0)
self.dump()
return self
def dump(self):
print( 'Bone ', self.name)
#print( 'Position ', self.position)
#print( 'Rotation ', self.rotation)
print( 'Parent Idx ', self.parent_index)
if (self.parent != 0):
print( 'Parent ', self.parent.name)
else:
print( 'Parent <NONE>')
#print( 'Rest Pose Inv.',self.rel_mat_inv)
#print( 'Rest Pose',self.rel_mat)
#for row in range(4):
#print( ' ', self.rest_pose_inv[row])
class scm_vertex :
position = []
tangent = []
normal = []
binormal = []
uv1 = []
uv2 = []
bone_index = []
def __init__(self):
self.position = Vector((0,0,0))
self.tangent = Vector((0,0,0))
self.normal = Vector((0,0,0))
self.binormal = Vector((0,0,0))
self.uv1 = Vector((0,0))
self.uv2 = Vector((0,0))
self.bone_index = [0]*4
def load(self, file):
vertstruct = '3f3f3f3f2f2f4B'
vertsize = struct.calcsize(vertstruct)
buffer = file.read(vertsize)
vertex = struct.unpack(vertstruct, buffer)
self.position = vertex[0:3]
self.tangent = vertex[3:6]
self.normal = vertex[6:9]
self.binormal = vertex[9:12]
self.uv1 = vertex[12:14]
self.uv2 = vertex[14:16]
self.bone_index = vertex[16:20]
return self
def dump(self):
print( 'position ', self.position)
print( 'tangent ', self.tangent)
print( 'normal ', self.normal)
print( 'binormal ', self.binormal)
print( 'uv1 ', self.uv1)
print( 'uv2 ', self.uv2)
print( 'bones ', self.bone_index)
class scm_mesh :
bones = []
vertices = []
faces = []
info = []
filename = ""
def __init__(self):
self.bones = []
self.vertices = []
self.faces = []
self.info = []
self.filename = ""
def load(self, filename):
global xy_to_xz_transform
self.filename = filename
scm = open(filename, 'rb')
# Read header
#headerstruct = '4s11L'
headerstruct = '4s11I'
buffer = scm.read(struct.calcsize(headerstruct))
header = struct.unpack(headerstruct, buffer)
#print("buffer",buffer)
for h in header:
print(h)
marker = header[0].decode('ascii')
version = header[1]
boneoffset = header[2]
bonecount = header[3]
vertoffset = header[4]
extravertoffset = header[5]
vertcount = header[6]
indexoffset = header[7]
indexcount = header[8]
tricount = indexcount // 3 #?
infooffset = header[9]
infocount = header[10]
totalbonecount = header[11]
#note: this is for SCM version 5. For SCM Version 7 (supcom 2) there are additional things in the header that arent decoded here, for instance material information.
if (marker != 'MODL'):
print( 'Not a valid scm')
my_popup("Not a valid scm")
return
if (version != 5):
print('Unsupported SCM Version detected, attempting to import it regardless. SCM Version:',version)
# Read bone names
scm.seek(pad(scm.tell()), 1)
length = (boneoffset - 4) - scm.tell()
# This should probably be handeled by the scm_bone reader as it contains the nameoffset. But I'm lazy
# and logic tells me it's written in the same order as the bones.
buffer = scm.read(length)
rawnames = struct.unpack(str(length)+'s',buffer)
b_bonenames = (rawnames[0].split(b'\0'))[:-1]
bonenames = [b.decode() for b in b_bonenames]
print("bonenames",bonenames)
# Read bones
scm.seek(boneoffset, 0)
for b in range(0, totalbonecount):
bone = scm_bone(bonenames[b])
bone.load(scm)
self.bones.append(bone)
#show them (for debug)
#for b in range(0, totalbonecount):
#print( "bone %d has %d children = " %(b, self.bones[b].numchildren))
# Set parent (this could probably be done in the other loop since parents are usually written to the file
# before the children. But you never know..
for bone in self.bones:
if (bone.parent_index != -1):
bone.parent = self.bones[bone.parent_index]
else:
bone.parent = 0
# the bone matrix relative to the parent.
if (bone.parent != 0):
mrel = (bone.rel_mat) @ Matrix(bone.parent.rel_mat).inverted() #* xy_to_xz_transform
bone.rel_matrix_inv = Matrix(mrel).inverted()
else:
mrel = bone.rel_mat @ xy_to_xz_transform #there is no parent
bone.rel_matrix_inv = Matrix(mrel).inverted()
# Read vertices
scm.seek(vertoffset, 0)
for b in range(0, vertcount):
vert = scm_vertex()
vert.load(scm)
self.vertices.append(vert)
# Read extra vertex data
# Not implemented in Sup Com 1.0!
# Read indices (triangles)
tristruct = '3h'
trisize = struct.calcsize(tristruct)
scm.seek(indexoffset, 0)
for t in range(tricount):
buffer = scm.read(trisize)
face = list(struct.unpack(tristruct, buffer))
for v in range(len(face)):
if face[v] < 0:
face[v] = face[v] + 32768*2 #supcom doesnt mind storing negative vertex indices due to overflow in the face data, but blender crashes
if face[v] < 0: #incase of some other insanity we dont know about yet
print('face vertex index below 0, setting to 0 to avoid crash: ',face[v])
face[v] = 0
self.faces.append(face+[0])
# Read info
if (infocount > 0):
scm.seek(infooffset)
buffer = scm.read(infocount)
rawinfo = struct.unpack(str(len(buffer))+'s',buffer)
b_info = rawinfo[0].split(b'\0')[:-1]
self.info = [b.decode("utf-8", "ignore") for b in b_info]
scm.close()
return self
def dump(self):
print( '')
print( 'Filename: ', self.filename)
print( 'Bones ', len(self.bones))
print( 'Verts ', len(self.vertices))
print( 'Faces ', len(self.faces))
print( '')
print( 'INFO: ')
for info in self.info:
print( ' ', info)
class sca_bone:
name = ''
position = []
rotation = []
#changed: rototation -> rotation
pose_pos = []
pose_rot = []
rel_matrix = []
pose_matrix = []
#rel_mat = None
def __init__(self, pos, rot, name_):
self.position = pos
self.rotation = rot
self.name = name_
self.rel_matrix = None
self.pose_matrix = None
#self.rel_mat = None
def dump(self):
print( 'Position ', self.position)
print( 'Rotation ', self.rotation)
class sca_frame:
keytime = 0.0
keyflags = 0
bones = []
anim = None
def __init__(self, anim):
self.keytime = 0.0
self.keyflags = 0
self.bones = []
self.anim = anim
def load(self, file,bonenames):
frameheader_fmt = 'fi'
frameheader_size = struct.calcsize(frameheader_fmt)
buffer = file.read(frameheader_size)
(self.keytime, self.keyflags) = struct.unpack(frameheader_fmt, buffer)
posrot_fmt = '3f4f'
posrot_size = struct.calcsize(posrot_fmt)
for b in range (0, self.anim.numbones) :
buffer = file.read(posrot_size)
posrot = struct.unpack(posrot_fmt, buffer)
bone = sca_bone(posrot[0:3], posrot[3:7],bonenames[b])
self.bones.append(bone)
def dump(self):
print( 'Time ', self.keytime)
print( 'Flags ', self.keyflags)
class sca_anim :
filename = ""
frames = []
bones = []
bonelinks = []
bonenames = []
numbones = 0
duration = 0.0
def __init__(self):
self.filename = ""
self.frames = []
self.bones = []
self.numbones = 0
self.bonelinks = []
self.bonenames = []
self.duration = 0.0
def calcAnimBoneMatrix(self, frame, bone_index, armature_bones, frame_index):
global xy_to_xz_transform
bone = frame.bones[bone_index];
parent_index = self.bonelinks[bone_index]
# note that the pos/rot of the armature_bones are still in relative supcom coordinates.
# so we can correct the relative pos-increase by the relative armature-increase
pose_rel_pos = Vector(bone.position)
pose_rel_rot = Quaternion(bone.rotation)
# the matrix representation... it's easier to work with matrix notation I think.
# the rotation:
pose_rel_matrix = pose_rel_rot.to_matrix()
pose_rel_matrix.resize_4x4()
pose_rel_matrix.transpose()
# the translation:
pose_rel_matrix.transpose()
pose_rel_matrix.translation = pose_rel_pos
pose_rel_matrix.transpose()
#if frame_index == 0 or frame_index == 40:
# print ('pose_rel1\n',pose_rel_matrix)
if (parent_index == -1) :
# for the root bone, this is already the absolution pos/rot, but,
# the root bone should be rotated into the blender coordinates
bone.rel_matrix = pose_rel_matrix @ xy_to_xz_transform
#testmat =(bone.rel_mat) * Matrix(bone.parent.rel_mat).invert()
if (parent_index >= 0):
# for all the children, they are seen relative to the parents.
bone.rel_matrix = pose_rel_matrix
# the (rendered) animation positions are relative to
# both the parent, and to the relative rest position of the bone.
#rechercher avec le nom, ici on a juste l'index, qui diffèrent entre le fichier de mesh et l'animation OK
restBone = None
for rBone in armature_bones:
#print ("name",rBone.name)
if rBone.name == bone.name:
restBone = rBone
break
if (restBone == None):
my_popup(bone.name + " not found")
print(bone.name + " not found")
#return
#bone.pose_matrix = Matrix(bone.rel_matrix * armature_bones[bone_index].rel_matrix_inv)#* xy_to_xz_transform)
#print ("bone.rel_matrix",bone.rel_matrix)
#print ("restBone.rel_matrix_inv",restBone.rel_matrix_inv)
bone.pose_matrix = Matrix(bone.rel_matrix @ restBone.rel_matrix_inv)#* xy_to_xz_transform)
# pose position relative to the armature
bone.pose_matrix.transpose()
bone.pose_pos = Vector(bone.pose_matrix.translation)
bone.pose_rot = bone.pose_matrix.to_quaternion()
#if frame_index == 0 or frame_index == 40:
# print ('rel\n',bone.rel_matrix)
# print ('inv\n',armature_bones[bone_index].rel_matrix_inv)
# print ('mat\n',bone.pose_matrix)
# print ("posInit",bone.position)
# print ("rotInit",bone.rotation)
# print ("posf",bone.pose_pos)
# print ("rotf",bone.pose_rot)
#frame.bones[bone_index] = bone;
def load(self, filename):
self.filename = filename
sca = open(filename, 'rb')
# Read header
headerstruct = '4siifiiiii'
buffer = sca.read(struct.calcsize(headerstruct))
header = struct.unpack(headerstruct, buffer)
print('header', header)
(magic, \
version, \
numframes, \
self.duration, \
self.numbones, \
namesoffset, \
linksoffset, \
animoffset, \
framesize) = struct.unpack(headerstruct, buffer)
if (magic != b'ANIM'):
print( 'Not a valid .sca animation file')
my_popup('Not a valid .sca animation file')
return
if (version != 5):
print( 'Unsupported sca version: %d' % version)
# Read bone names
sca.seek(namesoffset, 0)
length = linksoffset - namesoffset
buffer = sca.read(length)
rawnames = struct.unpack(str(length)+'s',buffer)
b_bonenames = rawnames[0].split(b'\0')[:-1]
self.bonenames = [b.decode() for b in b_bonenames]
# Read links
links_fmt = str(self.numbones)+'i'
links_size = struct.calcsize(links_fmt)
buffer = sca.read(links_size)
self.bonelinks = struct.unpack(links_fmt, buffer)
posrot_fmt = '3f4f'
posrot_size = struct.calcsize(posrot_fmt)
sca.seek(animoffset)
buffer = sca.read(posrot_size)
root_posrot = struct.unpack(posrot_fmt, buffer)
for f in range (0, numframes) :
frame = sca_frame(self)
frame.load(sca , self.bonenames)
self.frames.append(frame)
sca.close()
return self
def dump(self):
print( 'SCA: ', self.filename)
print( 'Duration: %fs' % self.duration)
print( 'Num loaded frames ', len(self.frames))
print( 'Bonelinks')
for link in self.bonelinks:
print( ' ', link)
print( 'Bone names')
for name in self.bonenames:
print( ' ', name)
def pad(size):
val = 32 - (size % 32)
if (val > 31):
return 0
return val
#**************************************************************************************************
# Blender Interface
#**************************************************************************************************
def read_scm() :
global xy_to_xz_transform
global scm_filepath # [0] both [1] path [2] name
global sca_filepath # [0] both [1] path [2] name
print( "=== LOADING Sup Com Model ===")
print( "")
scene = bpy.context.scene
layer = bpy.context.view_layer
mesh = scm_mesh()
if (mesh.load(scm_filepath[0]) == None):
print( 'Failed to load %s' %scm_filepath[2])
my_popup( 'Failed to load %s' %scm_filepath[2])
return
#ProgBarLSCM = ProgressBar( "Imp: load SCM", (2*len(mesh.vertices) + len(mesh.faces)))
armature_name = scm_filepath[2].rstrip(".scm")
print( "armature ", armature_name)
### CREATE ARMATURE
armData = bpy.data.armatures.new(armature_name)
armData.show_axes = True
armObj = bpy.data.objects.new(armature_name, armData)
scene.collection.objects.link(armObj)
layer.objects.active = armObj
#if not armObj.select_get():
armObj.select_set(True)
bpy.ops.object.mode_set(mode='EDIT')
for index in range(len(mesh.bones)):
bone = mesh.bones[index]
blender_bone = armData.edit_bones.new(bone.name)
#not nice parent may not exist, but usualy should exist (depends on storing in scm)
if (bone.parent != 0) :
blender_bone.parent = armData.edit_bones[bone.parent.name]
t_matrix = bone.rel_mat @ xy_to_xz_transform
loc,rot,sca = t_matrix.transposed().decompose()
blender_bone.head = loc
blender_bone.tail = (rot.to_matrix() @ Vector((0,1,0))) + blender_bone.head
blender_bone.matrix = t_matrix.transposed()
bpy.ops.object.mode_set(mode='OBJECT')
meshData = bpy.data.meshes.new('Mesh')
#add verts
vertlist = []
for vert in mesh.vertices:
vertlist.append(Vector(vert.position)@xy_to_xz_transform)
meshData.calc_loop_triangles()
meshData.vertices.add(len(vertlist))
meshData.polygons.add(len(mesh.faces))
meshData.vertices.foreach_set("co", unpack_list(vertlist))
faces_loop_start = []
lidx = 0
for f in mesh.faces:
nbr_vidx = 3
faces_loop_start.append(lidx)
lidx += nbr_vidx
n = len(vertlist)
num_polys = len(mesh.faces)
meshData.loops.add(num_polys * 3)
meshData.polygons.foreach_set("loop_start", faces_loop_start)
meshData.polygons.foreach_set("loop_total", (3,) * num_polys)
#take the vertex data from the faces and put them into one long list
faceVertexOrderedList = []
for f in mesh.faces:
for faceVertex in range(3):
faceVertexOrderedList.append(f[faceVertex])
meshData.polygons.foreach_set("vertices", faceVertexOrderedList)
meshData.uv_layers.new(name='UVMap')
#put all the vertex UVs into one long list
uvVertexList = []
for polygon in meshData.polygons:
for vertid in polygon.vertices:
uvVertexList.append(mesh.vertices[vertid].uv1[0])
uvVertexList.append(1.0-mesh.vertices[vertid].uv1[1])
for uv in meshData.uv_layers: # uv texture
uv.data.foreach_set('uv', uvVertexList)
mesh_obj = bpy.data.objects.new('Mesh', meshData)
scene.collection.objects.link(mesh_obj)
layer.objects.active = mesh_obj
mesh_obj.select_set(True)
meshData.update() #blender crashes when going into edit mode without these
#assigns vertex groups #mesh must be in object
for bone in mesh.bones:
mesh_obj.vertex_groups.new(name=bone.name)
for vgroup in mesh_obj.vertex_groups:
#print(vgroup.name, ":", vgroup.index)
for vertex_index in range(len(mesh.vertices)):
#bone index
vertex = mesh.vertices[vertex_index]
bone_index = vertex.bone_index[0]
boneName = mesh.bones[bone_index].name
if boneName == vgroup.name:
vgroup.add([vertex_index], 1.0, 'ADD')
meshData.update() #blender crashes when going into edit mode without these
bpy.context.view_layer.update()
bpy.ops.object.select_all(action='DESELECT')
mesh_obj.select_set(False)
armObj.select_set(False)
mesh_obj.select_set(True)
armObj.select_set(True)
layer.objects.active = armObj
bpy.ops.object.parent_set(type="ARMATURE")
if len(mesh.info):
print( "=== INFO ===")
for info in mesh.info:
print( "",info)
print( "=== COMPLETE ===")
global globMesh
globMesh = mesh
def iterate_bones(meshBones, bone, parent = None, scm_parent_index = -1):
global MArmatureWorld
global xz_to_xy_transform
if (parent != None and bone.parent.name != parent.name):
my_popup("Error: Invalid parenting in bone ... multiple parents?!")
print("Error: Invalid parenting in bone ... multiple parents?!")
#print( "Invalid parenting in bone", bone.name," and parent ", parent.name)
return
b_rest_pose = Matrix(([0,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,0]))
b_rest_pose_inv = Matrix(([0,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,0]))
b_rotation = Quaternion(( 0,0,0,0 ))
b_position = Vector(( 0,0,0 ))
b_index = len(meshBones)
bone_matrix = bone.matrix_local.transposed()
# Calculate the inverse rest pose for the bone #instead bonearmmat*worldmat = Matrix['BONESPACE']
b_rest_pose = bone_matrix @ MArmatureWorld
b_rest_pose_inv = ( b_rest_pose @ xz_to_xy_transform ).inverted()
if (parent == None):
rel_mat = b_rest_pose @ xz_to_xy_transform
#root pos is the same as the rest-pose
else:
parent_matrix_inv = Matrix( parent.matrix_local.transposed() ).inverted()
rel_mat = Matrix(bone_matrix @ parent_matrix_inv)
# must be BM * PMI in that order
# do not use an extra (absolute) extra rotation here, cause this is only relative
# Position & Rotation relative to parent (if there is a parent)
b_rotation = rel_mat.transposed().to_quaternion()#.normalize()
b_position = rel_mat.transposed().to_translation()
sc_bone = scm_bone( bone.name, b_rest_pose_inv, b_rotation, b_position, scm_parent_index )
meshBones.append(sc_bone)
# recursive call for all children
if (bone.children != None):
for child in bone.children:
iterate_bones( meshBones, child, bone, b_index )
def get_mesh_bones():
scene = bpy.context.scene
# Get Selected object(s)
selected_objects = bpy.context.selected_objects
# Priority to selected armature
arm_obj = None
for obj in selected_objects:
if obj.type == "ARMATURE":
arm_obj = obj
break
# Is there one armature? Take this one
if arm_obj == None :
for obj in scene.objects: #possibly change to layer.objects
if obj.type == "ARMATURE":
arm_obj = obj
break
if arm_obj == None:
popup("Error: Please select your armature.%t|OK")
return
MArmatureWorld = Matrix(arm_obj.matrix_world)
arm = arm_obj.data
meshBones = []
for bone in arm.bones.values():
if (bone.parent == None):
iterate_bones(meshBones, bone)
if meshBones == []:
print ('No bone in project')
my_popup('No bone in project')
return
for bone in meshBones:
if (bone.parent_index != -1):
bone.parent = meshBones[bone.parent_index]
else:
bone.parent = 0
# the bone matrix relative to the parent.
if (bone.parent != 0):
mrel = (bone.rel_mat) @ Matrix(bone.parent.rel_mat).inverted() #* xy_to_xz_transform
bone.rel_matrix_inv = Matrix(mrel).inverted()
else:
mrel = bone.rel_mat @ xy_to_xz_transform #there is no parent
bone.rel_matrix_inv = Matrix(mrel).inverted()
#debug
#for b in meshBones:
# print ("name",b.name)
# print ("inv",b.rel_matrix_inv)
# print ("inv0",b.rel_mat_inv)
return meshBones
def read_anim(mesh):
#TODO: faire en sorte que mesh soit importé de l'objet courant
#if mesh == []:
# print ('meshUndefined')
# my_popup('Mesh Undefined')
# return
#meshBones = mesh.bones
#for b in mesh.bones:
# print ("name",b.name)
# print ("inv",b.rel_matrix_inv)
# print ("inv0",b.rel_mat_inv)
global xy_to_xz_transform
global sca_filepath # [0] both [1] path [2] name
global MArmatureWorld
#xy_to_xz_quat = xy_to_xz_transform.toQuat()
print( "=== LOADING Sup Com Animation ===")
print( "")
anim = sca_anim()
anim.load(sca_filepath[0])
meshBones = get_mesh_bones()
objBoneNames = [rBone.name for rBone in meshBones]
return check_bone(meshBones,anim,objBoneNames,0)
#this is a mess, should be cleaned up. it creates a dialog option for bones which arent in the mesh.
def check_bone(meshBones,anim,objBoneNames,bone_num):
if (bone_num < len(anim.bonenames)):
#print("check_bone",anim.bonenames[bone_num])