-
Notifications
You must be signed in to change notification settings - Fork 0
/
io_export_unreal_psk_psa.py
3003 lines (2417 loc) · 107 KB
/
io_export_unreal_psk_psa.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 3 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, see <http://www.gnu.org/licenses/>.
# All rights reserved.
#
# ##### END GPL LICENSE BLOCK #####
bl_info = {
"name": "Export Unreal Engine Format(.psk/.psa)",
"author": "Darknet/Optimus_P-Fat/Active_Trash/Sinsoft/VendorX/Spoof",
"version": (2, 7, 1),
"blender": (2, 65, 4),
"location": "File > Export > Skeletal Mesh/Animation Data (.psk/.psa)",
"description": "Export Skeleletal Mesh/Animation Data",
"warning": "",
"wiki_url": "https://wiki.blender.org/index.php/Extensions:2.6/Py/"
"Scripts/Import-Export/Unreal_psk_psa",
"category": "Import-Export",
}
"""
-- Unreal Skeletal Mesh and Animation Export (.psk and .psa) export script v0.0.1 --<br>
- NOTES:
- This script Exports To Unreal's PSK and PSA file formats for Skeletal Meshes and Animations. <br>
- This script DOES NOT support vertex animation! These require completely different file formats. <br>
- v0.0.1
- Initial version
- v0.0.2
- This version adds support for more than one material index!
[ - Edit by: Darknet
- v0.0.3 - v0.0.12
- This will work on UT3 and it is a stable version that work with vehicle for testing.
- Main Bone fix no dummy needed to be there.
- Just bone issues position, rotation, and offset for psk.
- The armature bone position, rotation, and the offset of the bone is fix.
It was to deal with skeleton mesh export for psk.
- Animation is fix for position, offset, rotation bone support one rotation direction when armature build.
- It will convert your mesh into triangular when exporting to psk file.
- Did not work with psa export yet.
- v0.0.13
- The animatoin will support different bone rotations when export the animation.
- v0.0.14
- Fixed Action set keys frames when there is no pose keys and it will ignore it.
- v0.0.15
- Fixed multiple objects when exporting to psk. Select one mesh to export to psk.
- ]
- v0.1.1
- Blender 2.50 svn (Support)
Credit to:
- export_cal3d.py (Position of the Bones Format)
- blender2md5.py (Animation Translation Format)
- export_obj.py (Blender 2.5/Pyhton 3.x Format)
- freenode #blendercoder -> user -> ideasman42
- Give Credit to those who work on this script.
- http://sinsoft.com
"""
# ===========================================================================
"""
NOTES for Jan 2012 refactor (Spoof)
* THIS IS A WORK IN PROGRESS. These modifications were originally
intended for internal use and are incomplete. Use at your own risk! *
TODO
- (Blender 2.62) changes to Matrix math
- (Blender 2.62) check for long names
- option to manually set the root bone for export
CHANGES
- new bone parsing to allow advanced rigging
- identification of armature and mesh
- removed the need to apply an action to the armature
- fixed anim rate to work correctly in UDK (no more FPS fudging)
- progress reporting while processing smooth groups
- more informative logging
- code refactor for clarity and modularity
- naming conventions unified to use lowercase_with_underscore
- C++ datatypes and PSK/PSA classes remain CamelCaseStyle for clarity
- names such as 'ut' and 'unreal' unified to 'udk'
- simplification of code structure
- removed legacy code paths
USAGE
This version of the exporter is more selective over which bones are considered
part of the UDK skeletal mesh, and allows greater flexibility for adding
control bones to aid in animation.
Taking advantage of this script requires the following methodology:
* Place all exportable bones into a bone hierarchy extending from a single
root. This root bone must have use_deform enabled. All other root bones
in the armature must disable use_deform. *
The script searches for a root bone with use_deform set true and considers all
bones parented to it as part of the UDK skeletal mesh. Thus only these bones
are exported and all other bones are ignored.
This removes many restrictions on the rigger/animator, who can add control
bone hierarchies to the rig, and keyframe any element into actions. With this
approach you can build complex animation rigs in a similar vein to the Rigify
add-on, by Nathan Vegdahl. However...
* Rigify is incompatible with this script *
Rigify interlaces deformer bones within a single hierarchy making it difficult
to deconstruct for export. It also splits some meta-rig bones into multiple
deformer bones (bad for optimising a game character). I had partial success
writing a parser for the structure, but it was taking too much time and,
considering the other issues with Rigify, it was abandoned.
"""
# ===========================================================================
import bmesh
import os
import time
import bpy
import mathutils
import math
import operator
import sys
from bpy.props import (
BoolProperty,
CollectionProperty,
EnumProperty,
FloatProperty,
IntProperty,
StringProperty,
)
from bpy.types import (
Operator,
Panel,
UIList,
PropertyGroup,
AddonPreferences,
)
from struct import pack
# REFERENCE MATERIAL JUST IN CASE:
#
# U = x / sqrt(x^2 + y^2 + z^2)
# V = y / sqrt(x^2 + y^2 + z^2)
#
# Triangles specified counter clockwise for front face
#
# defines for sizeofs
SIZE_FQUAT = 16
SIZE_FVECTOR = 12
SIZE_VJOINTPOS = 44
SIZE_ANIMINFOBINARY = 168
SIZE_VCHUNKHEADER = 32
SIZE_VMATERIAL = 88
SIZE_VBONE = 120
SIZE_FNAMEDBONEBINARY = 120
SIZE_VRAWBONEINFLUENCE = 12
SIZE_VQUATANIMKEY = 32
SIZE_VVERTEX = 16
SIZE_VPOINT = 12
SIZE_VTRIANGLE = 12
MaterialName = []
# Python 3 doesn't have cmp anymore
def cmp(a, b):
return (a > b) - (a < b)
# ===========================================================================
# Custom exception class
# ===========================================================================
class Error(Exception):
def __init__(self, message):
self.message = message
# ===========================================================================
# Verbose logging with loop truncation
# ===========================================================================
def verbose(msg, iteration=-1, max_iterations=4, msg_truncated="..."):
if bpy.context.scene.udk_option_verbose is True:
# limit the number of times a loop can output messages
if iteration > max_iterations:
return
elif iteration == max_iterations:
print(msg_truncated)
return
print(msg)
# ===========================================================================
# Log header/separator
# ===========================================================================
def header(msg, justify='LEFT', spacer='_', cols=78):
if justify == 'LEFT':
s = '{:{spacer}<{cols}}'.format(msg + " ", spacer=spacer, cols=cols)
elif justify == 'RIGHT':
s = '{:{spacer}>{cols}}'.format(" " + msg, spacer=spacer, cols=cols)
else:
s = '{:{spacer}^{cols}}'.format(" " + msg + " ", spacer=spacer, cols=cols)
return "\n" + s + "\n"
# ===========================================================================
# Generic Object->Integer mapping
# the object must be usable as a dictionary key
# ===========================================================================
class ObjMap:
def __init__(self):
self.dict = {}
self.next = 0
def get(self, obj):
if obj in self.dict:
return self.dict[obj]
else:
id = self.next
self.next = self.next + 1
self.dict[obj] = id
return id
def items(self):
getval = operator.itemgetter(0)
getkey = operator.itemgetter(1)
return map(getval, sorted(self.dict.items(), key=getkey))
# ===========================================================================
# RG - UNREAL DATA STRUCTS - CONVERTED FROM C STRUCTS GIVEN ON UDN SITE
# provided here: http://udn.epicgames.com/Two/BinaryFormatSpecifications.html
# updated UDK (Unreal Engine 3): http://udn.epicgames.com/Three/BinaryFormatSpecifications.html
# ===========================================================================
class FQuat:
def __init__(self):
self.X = 0.0
self.Y = 0.0
self.Z = 0.0
self.W = 1.0
def dump(self):
return pack('ffff', self.X, self.Y, self.Z, self.W)
def __cmp__(self, other):
return cmp(self.X, other.X) or \
cmp(self.Y, other.Y) or \
cmp(self.Z, other.Z) or \
cmp(self.W, other.W)
def __hash__(self):
return hash(self.X) ^ hash(self.Y) ^ hash(self.Z) ^ hash(self.W)
def __str__(self):
return "[%f,%f,%f,%f](FQuat)" % (self.X, self.Y, self.Z, self.W)
class FVector(object):
def __init__(self, X=0.0, Y=0.0, Z=0.0):
self.X = X
self.Y = Y
self.Z = Z
def dump(self):
return pack('fff', self.X, self.Y, self.Z)
def __cmp__(self, other):
return cmp(self.X, other.X) or \
cmp(self.Y, other.Y) or \
cmp(self.Z, other.Z)
def _key(self):
return (type(self).__name__, self.X, self.Y, self.Z)
def __hash__(self):
return hash(self._key())
def __eq__(self, other):
if not hasattr(other, '_key'):
return False
return self._key() == other._key()
def dot(self, other):
return self.X * other.X + self.Y * other.Y + self.Z * other.Z
def cross(self, other):
return FVector(self.Y * other.Z - self.Z * other.Y,
self.Z * other.X - self.X * other.Z,
self.X * other.Y - self.Y * other.X)
def sub(self, other):
return FVector(self.X - other.X,
self.Y - other.Y,
self.Z - other.Z)
class VJointPos:
def __init__(self):
self.Orientation = FQuat()
self.Position = FVector()
self.Length = 0.0
self.XSize = 0.0
self.YSize = 0.0
self.ZSize = 0.0
def dump(self):
return self.Orientation.dump() + self.Position.dump() + \
pack('4f', self.Length, self.XSize, self.YSize, self.ZSize)
class AnimInfoBinary:
def __init__(self):
self.Name = "" # length=64
self.Group = "" # length=64
self.TotalBones = 0
self.RootInclude = 0
self.KeyCompressionStyle = 0
self.KeyQuotum = 0
self.KeyPrediction = 0.0
self.TrackTime = 0.0
self.AnimRate = 0.0
self.StartBone = 0
self.FirstRawFrame = 0
self.NumRawFrames = 0
def dump(self):
return pack('64s64siiiifffiii', str.encode(self.Name), str.encode(self.Group),
self.TotalBones, self.RootInclude, self.KeyCompressionStyle, self.KeyQuotum,
self.KeyPrediction, self.TrackTime, self.AnimRate, self.StartBone,
self.FirstRawFrame, self.NumRawFrames)
class VChunkHeader:
def __init__(self, name, type_size):
self.ChunkID = str.encode(name) # length=20
self.TypeFlag = 1999801 # special value
self.DataSize = type_size
self.DataCount = 0
def dump(self):
return pack('20siii', self.ChunkID, self.TypeFlag, self.DataSize, self.DataCount)
class VMaterial:
def __init__(self):
self.MaterialName = "" # length=64
self.TextureIndex = 0
self.PolyFlags = 0 # DWORD
self.AuxMaterial = 0
self.AuxFlags = 0 # DWORD
self.LodBias = 0
self.LodStyle = 0
def dump(self):
# print("DATA MATERIAL:",self.MaterialName)
return pack('64siLiLii', str.encode(self.MaterialName), self.TextureIndex,
self.PolyFlags, self.AuxMaterial, self.AuxFlags, self.LodBias, self.LodStyle)
class VBone:
def __init__(self):
self.Name = "" # length = 64
self.Flags = 0 # DWORD
self.NumChildren = 0
self.ParentIndex = 0
self.BonePos = VJointPos()
def dump(self):
return pack('64sLii', str.encode(self.Name), self.Flags,
self.NumChildren, self.ParentIndex) + self.BonePos.dump()
# same as above - whatever - this is how Epic does it...
class FNamedBoneBinary:
def __init__(self):
self.Name = "" # length = 64
self.Flags = 0 # DWORD
self.NumChildren = 0
self.ParentIndex = 0
self.BonePos = VJointPos()
self.IsRealBone = 0 # this is set to 1 when the bone is actually a bone in the mesh and not a dummy
def dump(self):
return pack('64sLii', str.encode(self.Name), self.Flags,
self.NumChildren, self.ParentIndex) + self.BonePos.dump()
class VRawBoneInfluence:
def __init__(self):
self.Weight = 0.0
self.PointIndex = 0
self.BoneIndex = 0
def dump(self):
return pack('fii', self.Weight, self.PointIndex, self.BoneIndex)
class VQuatAnimKey:
def __init__(self):
self.Position = FVector()
self.Orientation = FQuat()
self.Time = 0.0
def dump(self):
return self.Position.dump() + self.Orientation.dump() + pack('f', self.Time)
class VVertex(object):
def __init__(self):
self.PointIndex = 0 # WORD
self.U = 0.0
self.V = 0.0
self.MatIndex = 0 # BYTE
self.Reserved = 0 # BYTE
self.SmoothGroup = 0
def dump(self):
return pack('HHffBBH', self.PointIndex, 0, self.U, self.V, self.MatIndex, self.Reserved, 0)
def __cmp__(self, other):
return cmp(self.PointIndex, other.PointIndex) or\
cmp(self.U, other.U) or \
cmp(self.V, other.V) or \
cmp(self.MatIndex, other.MatIndex) or \
cmp(self.Reserved, other.Reserved) or \
cmp(self.SmoothGroup, other.SmoothGroup)
def _key(self):
return (type(self).__name__, self.PointIndex, self.U, self.V, self.MatIndex, self.Reserved)
def __hash__(self):
return hash(self._key())
def __eq__(self, other):
if not hasattr(other, '_key'):
return False
return self._key() == other._key()
class VPointSimple:
def __init__(self):
self.Point = FVector()
def __cmp__(self, other):
return cmp(self.Point, other.Point)
def __hash__(self):
return hash(self._key())
def _key(self):
return (type(self).__name__, self.Point)
def __eq__(self, other):
if not hasattr(other, '_key'):
return False
return self._key() == other._key()
class VPoint(object):
def __init__(self):
self.Point = FVector()
self.SmoothGroup = 0
def dump(self):
return self.Point.dump()
def __cmp__(self, other):
return cmp(self.Point, other.Point) \
or cmp(self.SmoothGroup, other.SmoothGroup)
def _key(self):
return (type(self).__name__, self.Point, self.SmoothGroup)
def __hash__(self):
return hash(self._key()) \
^ hash(self.SmoothGroup)
def __eq__(self, other):
if not hasattr(other, '_key'):
return False
return self._key() == other._key()
class VTriangle:
def __init__(self):
self.WedgeIndex0 = 0 # WORD
self.WedgeIndex1 = 0 # WORD
self.WedgeIndex2 = 0 # WORD
self.MatIndex = 0 # BYTE
self.AuxMatIndex = 0 # BYTE
self.SmoothingGroups = 0 # DWORD
def dump(self):
return pack('HHHBBL', self.WedgeIndex0, self.WedgeIndex1, self.WedgeIndex2,
self.MatIndex, self.AuxMatIndex, self.SmoothingGroups)
"""
print("smooth",self.SmoothingGroups)
return pack('HHHBBI', self.WedgeIndex0, self.WedgeIndex1, self.WedgeIndex2,
self.MatIndex, self.AuxMatIndex, self.SmoothingGroups)
"""
# END UNREAL DATA STRUCTS
# ===========================================================================
# ===========================================================================
# RG - helper class to handle the normal way the UT files are stored
# as sections consisting of a header and then a list of data structures
# ===========================================================================
class FileSection:
def __init__(self, name, type_size):
self.Header = VChunkHeader(name, type_size)
self.Data = [] # list of datatypes
def dump(self):
data = self.Header.dump()
for i in range(len(self.Data)):
data = data + self.Data[i].dump()
return data
def UpdateHeader(self):
self.Header.DataCount = len(self.Data)
# ===========================================================================
# PSK
# ===========================================================================
class PSKFile:
def __init__(self):
self.GeneralHeader = VChunkHeader("ACTRHEAD", 0)
self.Points = FileSection("PNTS0000", SIZE_VPOINT) # VPoint
self.Wedges = FileSection("VTXW0000", SIZE_VVERTEX) # VVertex
self.Faces = FileSection("FACE0000", SIZE_VTRIANGLE) # VTriangle
self.Materials = FileSection("MATT0000", SIZE_VMATERIAL) # VMaterial
self.Bones = FileSection("REFSKELT", SIZE_VBONE) # VBone
self.Influences = FileSection("RAWWEIGHTS", SIZE_VRAWBONEINFLUENCE) # VRawBoneInfluence
# RG - this mapping is not dumped, but is used internally to store the new point indices
# for vertex groups calculated during the mesh dump, so they can be used again
# to dump bone influences during the armature dump
#
# the key in this dictionary is the VertexGroup/Bone Name, and the value
# is a list of tuples containing the new point index and the weight, in that order
#
# Layout:
# { groupname : [ (index, weight), ... ], ... }
#
# example:
# {'MyVertexGroup' : [ (0, 1.0), (5, 1.0), (3, 0.5) ] , 'OtherGroup' : [(2, 1.0)]}
self.VertexGroups = {}
def AddPoint(self, p):
self.Points.Data.append(p)
def AddWedge(self, w):
self.Wedges.Data.append(w)
def AddFace(self, f):
self.Faces.Data.append(f)
def AddMaterial(self, m):
self.Materials.Data.append(m)
def AddBone(self, b):
self.Bones.Data.append(b)
def AddInfluence(self, i):
self.Influences.Data.append(i)
def UpdateHeaders(self):
self.Points.UpdateHeader()
self.Wedges.UpdateHeader()
self.Faces.UpdateHeader()
self.Materials.UpdateHeader()
self.Bones.UpdateHeader()
self.Influences.UpdateHeader()
def dump(self):
self.UpdateHeaders()
data = self.GeneralHeader.dump() + self.Points.dump() + self.Wedges.dump() + \
self.Faces.dump() + self.Materials.dump() + self.Bones.dump() + self.Influences.dump()
return data
def GetMatByIndex(self, mat_index):
if mat_index >= 0 and len(self.Materials.Data) > mat_index:
return self.Materials.Data[mat_index]
else:
m = VMaterial()
# modified by VendorX
m.MaterialName = MaterialName[mat_index]
self.AddMaterial(m)
return m
def PrintOut(self):
print("{:>16} {:}".format("Points", len(self.Points.Data)))
print("{:>16} {:}".format("Wedges", len(self.Wedges.Data)))
print("{:>16} {:}".format("Faces", len(self.Faces.Data)))
print("{:>16} {:}".format("Materials", len(self.Materials.Data)))
print("{:>16} {:}".format("Bones", len(self.Bones.Data)))
print("{:>16} {:}".format("Influences", len(self.Influences.Data)))
# ===========================================================================
# PSA
#
# Notes from UDN:
# The raw key array holds all the keys for all the bones in all the specified sequences,
# organized as follows:
# For each AnimInfoBinary's sequence there are [Number of bones] times [Number of frames keys]
# in the VQuatAnimKeys, laid out as tracks of [numframes] keys for each bone in the order of
# the bones as defined in the array of FnamedBoneBinary in the PSA.
#
# Once the data from the PSK (now digested into native skeletal mesh) and PSA (digested into
# a native animation object containing one or more sequences) are associated together at runtime,
# bones are linked up by name. Any bone in a skeleton (from the PSK) that finds no partner in
# the animation sequence (from the PSA) will assume its reference pose stance ( as defined in
# the offsets & rotations that are in the VBones making up the reference skeleton from the PSK)
# ===========================================================================
class PSAFile:
def __init__(self):
self.GeneralHeader = VChunkHeader("ANIMHEAD", 0)
self.Bones = FileSection("BONENAMES", SIZE_FNAMEDBONEBINARY) # FNamedBoneBinary
self.Animations = FileSection("ANIMINFO", SIZE_ANIMINFOBINARY) # AnimInfoBinary
self.RawKeys = FileSection("ANIMKEYS", SIZE_VQUATANIMKEY) # VQuatAnimKey
# this will take the format of key=Bone Name, value = (BoneIndex, Bone Object)
# THIS IS NOT DUMPED
self.BoneLookup = {}
def AddBone(self, b):
self.Bones.Data.append(b)
def AddAnimation(self, a):
self.Animations.Data.append(a)
def AddRawKey(self, k):
self.RawKeys.Data.append(k)
def UpdateHeaders(self):
self.Bones.UpdateHeader()
self.Animations.UpdateHeader()
self.RawKeys.UpdateHeader()
def GetBoneByIndex(self, bone_index):
if bone_index >= 0 and len(self.Bones.Data) > bone_index:
return self.Bones.Data[bone_index]
def IsEmpty(self):
return (len(self.Bones.Data) == 0 or len(self.Animations.Data) == 0)
def StoreBone(self, b):
self.BoneLookup[b.Name] = [-1, b]
def UseBone(self, bone_name):
if bone_name in self.BoneLookup:
bone_data = self.BoneLookup[bone_name]
if bone_data[0] == -1:
bone_data[0] = len(self.Bones.Data)
self.AddBone(bone_data[1])
# self.Bones.Data.append(bone_data[1])
return bone_data[0]
def GetBoneByName(self, bone_name):
if bone_name in self.BoneLookup:
bone_data = self.BoneLookup[bone_name]
return bone_data[1]
def GetBoneIndex(self, bone_name):
if bone_name in self.BoneLookup:
bone_data = self.BoneLookup[bone_name]
return bone_data[0]
def dump(self):
self.UpdateHeaders()
return self.GeneralHeader.dump() + self.Bones.dump() + self.Animations.dump() + self.RawKeys.dump()
def PrintOut(self):
print("{:>16} {:}".format("Bones", len(self.Bones.Data)))
print("{:>16} {:}".format("Animations", len(self.Animations.Data)))
print("{:>16} {:}".format("Raw keys", len(self.RawKeys.Data)))
# ===========================================================================
# Helpers to create bone structs
# ===========================================================================
def make_vbone(name, parent_index, child_count, orientation_quat, position_vect):
bone = VBone()
bone.Name = name
bone.ParentIndex = parent_index
bone.NumChildren = child_count
bone.BonePos.Orientation = orientation_quat
bone.BonePos.Position.X = position_vect.x
bone.BonePos.Position.Y = position_vect.y
bone.BonePos.Position.Z = position_vect.z
# these values seem to be ignored?
# bone.BonePos.Length = tail.length
# bone.BonePos.XSize = tail.x
# bone.BonePos.YSize = tail.y
# bone.BonePos.ZSize = tail.z
return bone
def make_namedbonebinary(name, parent_index, child_count, orientation_quat, position_vect, is_real):
bone = FNamedBoneBinary()
bone.Name = name
bone.ParentIndex = parent_index
bone.NumChildren = child_count
bone.BonePos.Orientation = orientation_quat
bone.BonePos.Position.X = position_vect.x
bone.BonePos.Position.Y = position_vect.y
bone.BonePos.Position.Z = position_vect.z
bone.IsRealBone = is_real
return bone
def make_fquat(bquat):
quat = FQuat()
# flip handedness for UT = set x,y,z to negative (rotate in other direction)
quat.X = -bquat.x
quat.Y = -bquat.y
quat.Z = -bquat.z
quat.W = bquat.w
return quat
def make_fquat_default(bquat):
quat = FQuat()
# print(dir(bquat))
quat.X = bquat.x
quat.Y = bquat.y
quat.Z = bquat.z
quat.W = bquat.w
return quat
# ===========================================================================
# RG - check to make sure face isnt a line
# ===========================================================================
def is_1d_face(face, mesh):
# ID Vertex of id point
v0 = face.vertices[0]
v1 = face.vertices[1]
v2 = face.vertices[2]
return (mesh.vertices[v0].co == mesh.vertices[v1].co or
mesh.vertices[v1].co == mesh.vertices[v2].co or
mesh.vertices[v2].co == mesh.vertices[v0].co)
return False
# ===========================================================================
# Smoothing group
# (renamed to separate it from VVertex.SmoothGroup)
# ===========================================================================
class SmoothingGroup:
static_id = 1
def __init__(self):
self.faces = []
self.neighboring_faces = []
self.neighboring_groups = []
self.id = -1
self.local_id = SmoothingGroup.static_id
SmoothingGroup.static_id += 1
def __cmp__(self, other):
if isinstance(other, SmoothingGroup):
return cmp(self.local_id, other.local_id)
return -1
def __hash__(self):
return hash(self.local_id)
# searches neighboring faces to determine which smoothing group ID can be used
def get_valid_smoothgroup_id(self):
temp_id = 1
for group in self.neighboring_groups:
if group is not None and group.id == temp_id:
if temp_id < 0x80000000:
temp_id = temp_id << 1
else:
raise Error("Smoothing Group ID Overflowed, "
"Smoothing Group evidently has more than 31 neighboring groups")
self.id = temp_id
return self.id
def make_neighbor(self, new_neighbor):
if new_neighbor not in self.neighboring_groups:
self.neighboring_groups.append(new_neighbor)
def contains_face(self, face):
return (face in self.faces)
def add_neighbor_face(self, face):
if face not in self.neighboring_faces:
self.neighboring_faces.append(face)
def add_face(self, face):
if face not in self.faces:
self.faces.append(face)
def determine_edge_sharing(mesh):
edge_sharing_list = dict()
for edge in mesh.edges:
edge_sharing_list[edge.key] = []
for face in mesh.tessfaces:
for key in face.edge_keys:
if face not in edge_sharing_list[key]:
edge_sharing_list[key].append(face) # mark this face as sharing this edge
return edge_sharing_list
def find_edges(mesh, key):
""" Temp replacement for mesh.findEdges().
This is painfully slow.
"""
for edge in mesh.edges:
v = edge.vertices
if key[0] == v[0] and key[1] == v[1]:
return edge.index
def add_face_to_smoothgroup(mesh, face, edge_sharing_list, smoothgroup):
if face in smoothgroup.faces:
return
smoothgroup.add_face(face)
for key in face.edge_keys:
edge_id = find_edges(mesh, key)
if edge_id is not None:
# not sharp
if not (mesh.edges[edge_id].use_edge_sharp):
for shared_face in edge_sharing_list[key]:
if shared_face != face:
# recursive
add_face_to_smoothgroup(mesh, shared_face, edge_sharing_list, smoothgroup)
# sharp
else:
for shared_face in edge_sharing_list[key]:
if shared_face != face:
smoothgroup.add_neighbor_face(shared_face)
def determine_smoothgroup_for_face(mesh, face, edge_sharing_list, smoothgroup_list):
for group in smoothgroup_list:
if (face in group.faces):
return
smoothgroup = SmoothingGroup()
add_face_to_smoothgroup(mesh, face, edge_sharing_list, smoothgroup)
if smoothgroup not in smoothgroup_list:
smoothgroup_list.append(smoothgroup)
def build_neighbors_tree(smoothgroup_list):
for group in smoothgroup_list:
for face in group.neighboring_faces:
for neighbor_group in smoothgroup_list:
if neighbor_group.contains_face(face) and neighbor_group not in group.neighboring_groups:
group.make_neighbor(neighbor_group)
neighbor_group.make_neighbor(group)
# ===========================================================================
# parse_smooth_groups
# ===========================================================================
def parse_smooth_groups(mesh):
print("Parsing smooth groups...")
t = time.clock()
smoothgroup_list = []
edge_sharing_list = determine_edge_sharing(mesh)
# print("faces:",len(mesh.tessfaces))
interval = math.floor(len(mesh.tessfaces) / 100)
if interval == 0: # if the faces are few do this
interval = math.floor(len(mesh.tessfaces) / 10)
# print("FACES:",len(mesh.tessfaces),"//100 =" "interval:",interval)
for face in mesh.tessfaces:
# print(dir(face))
determine_smoothgroup_for_face(mesh, face, edge_sharing_list, smoothgroup_list)
# progress indicator, writes to console without scrolling
if face.index > 0 and (face.index % interval) == 0:
print("Processing... {}%\r".format(int(face.index / len(mesh.tessfaces) * 100)), end='')
sys.stdout.flush()
print("Completed", ' ' * 20)
verbose("len(smoothgroup_list)={}".format(len(smoothgroup_list)))
build_neighbors_tree(smoothgroup_list)
for group in smoothgroup_list:
group.get_valid_smoothgroup_id()
print("Smooth group parsing completed in {:.2f}s".format(time.clock() - t))
return smoothgroup_list
# ===========================================================================
# http://en.wikibooks.org/wiki/Blender_3D:_Blending_Into_Python/Cookbook#Triangulate_NMesh
# blender 2.50 format using the Operators/command convert the mesh to tri mesh
# ===========================================================================
def triangulate_mesh(object):
verbose(header("triangulateNMesh"))
# print(type(object))
scene = bpy.context.scene
me_ob = object.copy()
me_ob.data = object.to_mesh(bpy.context.scene, True, 'PREVIEW') # write data object
bpy.context.scene.objects.link(me_ob)
bpy.context.scene.update()
bpy.ops.object.mode_set(mode='OBJECT')
for i in scene.objects:
i.select = False # deselect all objects
me_ob.select = True
scene.objects.active = me_ob
print("Copy and Convert mesh just incase any way...")
bpy.ops.object.mode_set(mode='EDIT')
bpy.ops.mesh.select_all(action='SELECT') # select all the face/vertex/edge
bpy.ops.object.mode_set(mode='EDIT')
bpy.ops.mesh.quads_convert_to_tris()
bpy.context.scene.update()