-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathexport_im.py
1830 lines (1484 loc) · 75.2 KB
/
export_im.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
import os
import io
import struct
import bmesh
import bpy
import math
import mathutils
import bl_math
from mathutils import Matrix, Vector, Color
from bpy_extras import io_utils, node_shader_utils
import bmesh
from bpy_extras.wm_utils.progress_report import (
ProgressReport,
ProgressReportSubstep,
)
def name_compat(name):
if name is None:
return 'None'
else:
return name.replace(' ', '_')
def mesh_triangulate(me):
#import bmesh
bm = bmesh.new()
bm.from_mesh(me)
bmesh.ops.triangulate(bm, faces=bm.faces)
bm.to_mesh(me)
bm.free()
def veckey2d(v):
return round(v[0], 4), round(v[1], 4)
def veckey3d(v):
return round(v[0], 4), round(v[1], 4), round(v[2], 4)
def power_of_two(n):
return (n & (n-1) == 0) and n != 0
def remove_scale_from_matrix(mat):
loc, rot, scale = mat.decompose()
return mathutils.Matrix.Translation(loc) @ rot.to_matrix().to_4x4()
#def split_obj(split_objects, obj):
# print("Too many vertices on object " + obj.name + "! Splitting.")
# objcount = len(obj.vertices) % 65535
# for i in range(objcount):
# baseIndex = i * 65535
# bm = bmesh.new()
# bm.from_mesh(me)
# #new_obj.data = obj.data.copy()
# bm.vertices = obj.vertices[baseIndex : baseIndex + 65535]
#
#new_obj = src_obj.copy()
#new_obj.data = src_obj.data.copy()
def sanitize_filename(str):
outstr = ''
for c in str:
outchar = c
if c == '{' or c == '}' or c == '<' or c == '>':
outchar = '_'
outstr += outchar
return outstr
GLOBAL_WIDE_STRINGS = False
def jet_str(f, str, wide=False):
global GLOBAL_WIDE_STRINGS
wide = wide or GLOBAL_WIDE_STRINGS
encoded_name = bytearray(str.encode('utf-16le' if wide else 'utf-8'))
#wacky Jet byte alignment
str_length = len(encoded_name)
numTerminators = 4 - str_length % 4 if str_length % 4 != 0 else 0
encoded_name += bytes('\0' * numTerminators, 'utf-8')
len_bytes = bytearray(struct.pack("<I", len(encoded_name)))
if(wide):
len_bytes[3] = 0x40
f.write(len_bytes)
f.write(encoded_name)
def texture_file(type, img_path, target_dir, is_npo2, alpha):
basename = os.path.basename(img_path).lower()
texturepath = sanitize_filename(target_dir + '\\' + os.path.splitext(basename)[0] + ".texture")
txtpath = texturepath + ".txt"
print("write to " + txtpath)
with open(txtpath, "w") as f:
f.write("Primary=" + basename + "\n")
if alpha:
f.write("Alpha=" + basename + "\n")
f.write("Tile=st" + "\n")
if is_npo2:
f.write("nonpoweroftwo=1\n")
if type == 8:
f.write("NormalMapHint=normalmap\n")
return texturepath
# https://blenderartists.org/t/converting-textures-to-another-format/568064/4
def convert_image(image, dest):
# backup image settings
backup_file_format = bpy.context.scene.render.image_settings.file_format
backup_color_mode = bpy.context.scene.render.image_settings.color_mode
# update file format and color format to what we want
bpy.context.scene.render.image_settings.file_format = 'TARGA_RAW'
bpy.context.scene.render.image_settings.color_mode = 'RGBA'
# convert and save the texture: the name of the method is a bit misleading: it doesn't
# render anything. It just saves the image using the settings in bpy.context.scene.render.image_settings
image.save_render(dest)
# restore image settings
bpy.context.scene.render.image_settings.file_format = backup_file_format
bpy.context.scene.render.image_settings.color_mode = backup_color_mode
def chunk_ver(f, ver):
f.write(struct.pack("<I", ver))
def end_chunk(f, chunk):
f.write(struct.pack("<I", chunk.tell()))
f.write(chunk.getbuffer())
def recursive_writebone(chnk, srcBone, bones_flat, EXPORT_ALL_BONES):
bones_flat.append(srcBone)
relevant_children = []
for child in srcBone.children:
if "b.r." in child.name or EXPORT_ALL_BONES:
relevant_children.append(child)
chnk.write('BONE'.encode('utf-8'))
with io.BytesIO() as bone:
chunk_ver(bone, 100)
#BoneName
bone_name = srcBone.name
if not bone_name.startswith("b.r."):
bone_name = "b.r." + bone_name
jet_str(bone, bone_name)
#NumChildren
bone.write(struct.pack("<I", len(relevant_children)))
#BoneList
for child in relevant_children:
recursive_writebone(bone, child, bones_flat, EXPORT_ALL_BONES)
end_chunk(chnk, bone)
#Recursive SKEL for embedded .im export
def recursive_writebone_skel(chnk, srcBone, armature, EXPORT_GLOBAL_MATRIX, EXPORT_ALL_BONES):
relevant_children = []
for child in srcBone.children:
if "b.r." in child.name or EXPORT_ALL_BONES:
relevant_children.append(child)
chnk.write('BONE'.encode('utf-8'))
with io.BytesIO() as bone:
chunk_ver(bone, 100)
#BoneName
bone_name = srcBone.name
if not bone_name.startswith("b.r."):
bone_name = "b.r." + bone_name
jet_str(bone, bone_name)
if srcBone.parent == None:
boneMat = srcBone.matrix_local
else:
#convert bone transforms into world space and remove the scale
parentMatrix = srcBone.parent.matrix_local
parentMatrix = remove_scale_from_matrix(parentMatrix)
childMatrix = srcBone.matrix_local
childMatrix = remove_scale_from_matrix(childMatrix)
boneMat = parentMatrix.inverted() @ childMatrix
if armature != None:
boneMat = EXPORT_GLOBAL_MATRIX @ armature.matrix_world @ boneMat
else:
boneMat = EXPORT_GLOBAL_MATRIX @ boneMat
position, rotation, scale = boneMat.decompose()
# Shouldn't be necessary to invert the rotation for .im SKEL.
# rotation = rotation.inverted()
#Position
bone.write(struct.pack("<fff", *position))
#Orientation
bone.write(struct.pack("<ffff", rotation.x, rotation.y, rotation.z, rotation.w))
#NumChildren
bone.write(struct.pack("<I", len(relevant_children)))
#BoneList
for child in relevant_children:
recursive_writebone_skel(bone, child, armature, EXPORT_GLOBAL_MATRIX, EXPORT_ALL_BONES)
end_chunk(chnk, bone)
def write_kin(filepath, bones, armature, frame_start, frame_end, framerate, events, EXPORT_GLOBAL_MATRIX, EXPORT_ANIM_SCALE, EXPORT_ANIM_RELATIVE_POSITIONING, EXPORT_ALL_BONES):
print("Writing .kin to " + filepath)
scene = bpy.context.scene
NumFrames = frame_end - frame_start + 1
armatureMat = mathutils.Matrix.Identity(4)
if armature != None:
armatureMat = armature.matrix_world
_, _, armatureScale = armatureMat.decompose()
root_bone = None
for key in bones:
bonegroup = bones[key]
bone = bonegroup["srcBone"]
if bone.parent is None:
root_bone = bone
break
if root_bone is None:
print("Could not find a root bone!")
return
with open(filepath, "wb") as f:
#JIRF, filesize
f.write('JIRF'.encode('utf-8'))
with io.BytesIO() as rf: #resource file
rf.write('ANIM'.encode('utf-8'))
rf.write('INFO'.encode('utf-8'))
with io.BytesIO() as info:
version_needed = 100
if EXPORT_ANIM_SCALE or EXPORT_ANIM_RELATIVE_POSITIONING:
version_needed = 102
# if EXPORT_ANIM_RELATIVE_POSITIONING:
# version_needed = 257
flags_needed = version_needed >= 102
chunk_ver(info, version_needed)
#FileName
jet_str(info, os.path.basename(filepath).lower())
#NumFrames
info.write(struct.pack("<I", NumFrames))
#FrameRate
info.write(struct.pack("<I", framerate))
#MetricScale
info.write(struct.pack("<f", 1.0))
#Flags
if flags_needed:
flags = 0
if EXPORT_ANIM_SCALE:
flags |= 0x2
if EXPORT_ANIM_RELATIVE_POSITIONING:
flags |= 0x1
#flags |= 0x8
info.write(struct.pack("<I", flags))
end_chunk(rf, info)
# AFAIK, supported event types are AET_SOUND_EVENT (0), and AET_GENERIC_EVENT (4)
# sound events will play the entry of the same name within the soundscript container in the config - best example of this is the PB interior coalman (<kuid:-25:696>)
# generic events are probably used by script
#Events
rf.write('EVNT'.encode('utf-8'))
with io.BytesIO() as evnt:
chunk_ver(evnt, 100)
#NumEvents
#evnt.write(struct.pack("<I", 0))
evnt.write(struct.pack("<I", len(events)))
for evt in events:
typeid = 4 #AET_GENERIC_EVENT
if(evt["type"] == "sound"):
typeid = 0 #AET_SOUND_EVENT
evnt.write(struct.pack("<I", evt["frame"]))
evnt.write(struct.pack("<I", typeid))
jet_str(evnt, evt["name"])
end_chunk(rf, evnt)
bones_flat = []
#Skeleton
rf.write('SKEL'.encode('utf-8'))
with io.BytesIO() as skel:
chunk_ver(skel, 100)
#SkeletonBlock
recursive_writebone(skel, root_bone, bones_flat, EXPORT_ALL_BONES)
#skel.write(struct.pack("<I", 0))
end_chunk(rf, skel)
posebones_flat = []
if armature != None:
for bone in bones_flat:
print("bone " + bone.name)
for posebone in armature.pose.bones:
if posebone.name == bone.name:
posebones_flat.append(posebone)
break
objbones_flat = []
for obj in bones_flat:
if hasattr(obj, 'type') and (obj.type == 'EMPTY' or obj.type == 'LATTICE' or obj.type == 'MESH'):
objbones_flat.append(obj)
#pose_bone = (b for b in armature.pose.bones if b.bone is bone)
#posebones_flat.append(pose_bone)
if armature != None:
print("Found " + str(len(posebones_flat)) + "/" + str(len(armature.pose.bones)) + " pose bones")
print("Found " + str(len(objbones_flat)) + " object bones")
#FrameList
for i in range(frame_start, frame_end + 1):
scene.frame_set(i)
rf.write('FRAM'.encode('utf-8'))
with io.BytesIO() as fram:
if not EXPORT_ANIM_SCALE:
chunk_ver(fram, 100)
else:
chunk_ver(fram, 101)
#version 101 fixes a lot of things - bone matrices are parent relative rather than global, and rotations aren't backwards anymore
#game may not bother animating if this is outside 0 to NumFrames - 1
#FrameNum
fram.write(struct.pack("<I", i - frame_start))
#BoneDataList
for pose_bone in posebones_flat:
#mat = pose_bone.matrix_basis
# if not EXPORT_ANIM_RELATIVE_POSITIONING or pose_bone.parent is None:
# mat = mat @ pose_bone.matrix
# else:
# mat = mat @ pose_bone.parent.matrix.inverted() @ pose_bone.matrix
if not EXPORT_ANIM_RELATIVE_POSITIONING:
mat = armatureMat @ pose_bone.matrix
else:
if pose_bone.parent == None:
# limitation here where the root node will ignore scaling data
# we can't remove the scaling from the armature matrix alone as that will break the world space conversion of the root node's matrix
mat = remove_scale_from_matrix(armatureMat @ pose_bone.matrix)
#mat = pose_bone.matrix
else:
#convert bone transforms into world space and remove the scale if necessary
parentMatrix = pose_bone.parent.matrix
childMatrix = pose_bone.matrix
# if not EXPORT_ANIM_SCALE:
# parentMatrix = remove_scale_from_matrix(parentMatrix)
# childMatrix = remove_scale_from_matrix(childMatrix)
mat = parentMatrix.inverted() @ childMatrix
mat = EXPORT_GLOBAL_MATRIX @ mat
position, rotation, scale = mat.decompose()
if EXPORT_ANIM_RELATIVE_POSITIONING: # and pose_bone.parent != None
position = position * armatureScale
#scale = scale * armatureScale
if not EXPORT_ANIM_RELATIVE_POSITIONING:
rotation = rotation.inverted()
#Position
fram.write(struct.pack("<fff", *position))
#Orientation
fram.write(struct.pack("<ffff", rotation.x, rotation.y, rotation.z, rotation.w))
if EXPORT_ANIM_SCALE:
#Scale
fram.write(struct.pack("<fff", scale.x, scale.y, scale.z))
for obj_bone in objbones_flat:
#objMat = obj_bone.matrix_world
#if obj_bone.parent != None:
#objMat = obj_bone.parent.matrix_world.inverted() @ objMat
#objMat = EXPORT_GLOBAL_MATRIX @ objMat
objMat = obj_bone.matrix_world
if EXPORT_ANIM_RELATIVE_POSITIONING:
objMat = obj_bone.matrix_local
objMat = EXPORT_GLOBAL_MATRIX @ objMat
position, rotation, scale = objMat.decompose()
if not EXPORT_ANIM_RELATIVE_POSITIONING:
rotation = rotation.inverted()
#Position
fram.write(struct.pack("<fff", *position))
#Orientation
fram.write(struct.pack("<ffff", rotation.x, rotation.y, rotation.z, rotation.w))
if EXPORT_ANIM_SCALE:
#Scale
fram.write(struct.pack("<fff", scale.x, scale.y, scale.z))
end_chunk(rf, fram)
end_chunk(f, rf)
def gather_curve_data(me, obj, objectParent, parentBone, material, EXPORT_BOUNDS, bounds_set, meshes):
if len(me.uv_layers) == 0:
uv_layer = None
else:
uv_layer = me.uv_layers.active.data[:]
print("Processing curve...")
#should be final - edge split, etc
vertgroups = obj.vertex_groups
#uv dictionary must be per object, otherwise duplicate objects (with similar normals and uvs) get merged
uv_dict = {}
uv = uv_key = uv_val = None
unique_verts = []
indices = []
normals = []
influence_bones = []
for i, edge in enumerate(me.edges):
for v in edge.vertices:
vert = me.vertices[v]
#texcoords are transformed 1.0 - y
uv = [0, 1]
no = vert.normal
uv_key = v, veckey3d(no)
uv_val = uv_dict.get(uv_key)
if uv_val is None:
uv_dict[uv_key] = len(unique_verts)
influences = {}
for group in vertgroups:
try:
weight = group.weight(v)
except RuntimeError:
weight = 0.0
if weight != 0.0:
influences[group.name] = weight
if group.name not in influence_bones:
influence_bones.append(group.name)
unique_verts.append([vert.co[:], uv[:], influences])
normals.append(no.normalized())
if EXPORT_BOUNDS:
if bounds_set:
bounds_min.x = min(bounds_min.x, vert.co.x)
bounds_min.y = min(bounds_min.y, vert.co.y)
bounds_min.z = min(bounds_min.z, vert.co.z)
bounds_max.x = max(bounds_max.x, vert.co.x)
bounds_max.y = max(bounds_max.y, vert.co.y)
bounds_max.z = max(bounds_max.z, vert.co.z)
else:
bounds_set = True
bounds_min = mathutils.Vector(vert.co)
bounds_max = mathutils.Vector(vert.co)
indices.append(uv_dict[uv_key])
if len(unique_verts) > 65532 or len(indices) // 3 > 65535:
#apply and update
mesh_data = {
"obj": obj,
"material": material,
"unique_verts": unique_verts.copy(),
"indices": indices.copy(),
"normals": normals.copy(),
"face_normals": [],
"face_list": [],
"tangents": [],
"area": 0.0,
"uv_layer": uv_layer,
"parent": objectParent,
"parent_bone": parentBone,
"is_curve": True,
"max_influence": len(influence_bones)
}
meshes.append(mesh_data)
unique_verts.clear()
indices.clear()
normals.clear()
uv_dict.clear()
uv = uv_key = uv_val = None
influence_bones.clear()
print("Block split.")
if len(unique_verts) > 0:
mesh_data = {
"obj": obj,
"material": material,
"unique_verts": unique_verts.copy(),
"indices": indices.copy(),
"normals": normals.copy(),
"face_normals": [],
"face_list": [],
"tangents": [],
"area": 0.0,
"uv_layer": uv_layer,
"parent": objectParent,
"parent_bone": parentBone,
"is_curve": True,
"max_influence": len(influence_bones)
}
meshes.append(mesh_data)
def write_file(self, filepath, objects, scene,
EXPORT_APPLY_MODIFIERS=True,
EXPORT_CURVES=False,
EXPORT_TEXTURETXT=True,
EXPORT_CONVERT_TGA=False,
EXPORT_TANGENTS=True,
EXPORT_BOUNDS=True,
EXPORT_VERTEX_COLORS=False,
EXPORT_NEIGHBOR_INFO=False,
EXPORT_SUBSURF_AMBIENT=False,
EXPORT_CUSTOM_PROPERTIES=False,
EXPORT_KIN=True,
EXPORT_BLENDER_FRAMERATE=False,
EXPORT_SKEL=False,
EXPORT_ANIM_SCALE=False,
EXPORT_ANIM_RELATIVE_POSITIONING=False,
EXPORT_ALL_BONES=False,
EXPORT_ANIM_NLA=False,
EXPORT_ANIM_EVENTS=True,
EXPORT_EXPLICIT_VERSIONING=False,
EXPORT_INFO_VERSION=None,
EXPORT_MATL_VERSION=None,
EXPORT_GEOM_VERSION=None,
EXPORT_SEL_ONLY=False,
EXPORT_GLOBAL_MATRIX=None,
EXPORT_PATH_MODE='AUTO',
#progress=ProgressReport(),
):
if EXPORT_GLOBAL_MATRIX is None:
EXPORT_GLOBAL_MATRIX = Matrix()
#split objects
meshes = []
hold_meshes = [] #prevent garbage collection of bmeshes
#set to defaults
bounds_set = False
bounds_min = mathutils.Vector((0.0, 0.0, 0.0))
bounds_max = mathutils.Vector((0.0, 0.0, 0.0))
use_anim_bounds = EXPORT_KIN and EXPORT_BOUNDS
max_vert_influences = 0
max_chunk_influences = 0
material_groups = {}
curves = []
if use_anim_bounds:
for i in range(scene.frame_start, scene.frame_end + 1):
scene.frame_set(i)
for obj in objects:
for coord in obj.bound_box:
co_vector = mathutils.Vector((coord[0], coord[1], coord[2], 1.0))
co_vector = EXPORT_GLOBAL_MATRIX @ obj.matrix_world @ co_vector
if bounds_set:
bounds_min.x = min(bounds_min.x, co_vector.x)
bounds_min.y = min(bounds_min.y, co_vector.y)
bounds_min.z = min(bounds_min.z, co_vector.z)
bounds_max.x = max(bounds_max.x, co_vector.x)
bounds_max.y = max(bounds_max.y, co_vector.y)
bounds_max.z = max(bounds_max.z, co_vector.z)
else:
bounds_set = True
bounds_min = mathutils.Vector(co_vector)
bounds_max = mathutils.Vector(co_vector)
scene.frame_set(scene.frame_start)
for obj in objects:
#curves can be converted into meshes
is_curve = obj.type == 'CURVE'
if not EXPORT_CURVES and is_curve:
continue
if EXPORT_APPLY_MODIFIERS:
armature_modifiers = {}
if EXPORT_KIN:
# temporarily disable Armature modifiers if exporting skins
for idx, modifier in enumerate(obj.modifiers):
if modifier.type == 'ARMATURE':
armature_modifiers[idx] = modifier.show_viewport
modifier.show_viewport = False
# Force all meshes to triangulate themselves.
triangle_mod = obj.modifiers.new('im', 'TRIANGULATE')
depsgraph = bpy.context.evaluated_depsgraph_get()
final = obj.evaluated_get(depsgraph)
try:
me = final.to_mesh(preserve_all_data_layers=True, depsgraph=depsgraph).copy()
except RuntimeError:
me = None
if triangle_mod != None:
obj.modifiers.remove(triangle_mod)
if EXPORT_KIN:
# restore Armature modifiers
for idx, show_viewport in armature_modifiers.items():
obj.modifiers[idx].show_viewport = show_viewport
else:
me = obj.data
if me is None:
continue
#uv_layer = me.uv_layers.active.data
#mesh_triangulate(me)
objectParent = None #empty and lattice parents
parentBone = None
#meshes can be nodes themselves
if "b.r." in obj.name:
objectParent = obj
elif obj.parent != None:
if "b.r." in obj.parent.name:
objectParent = obj.parent
if obj.parent_bone != None:
if "b.r." in obj.parent_bone:
parentBone = obj.parent_bone
print("Pre-processing object " + obj.name)
me.transform(EXPORT_GLOBAL_MATRIX @ obj.matrix_world)
if bpy.app.version < (4, 1, 0):
me.calc_normals_split()
use_tangents = EXPORT_TANGENTS
if EXPORT_TANGENTS:
if len(me.uv_layers) > 0 or me.uv_layers.active: # or len(me.uv_layers.active.data) < len(me.loops)
try:
me.calc_tangents()
except Exception:
self.report({'INFO'}, 'Mesh \'' + obj.name + '\' has polygons with more than 4 vertices. Unable to calculate tangents.')
use_tangents = False
else:
self.report({'WARNING'}, 'Object \'' + obj.name + '\' is missing UV data, which is required for tangent generation.')
use_tangents = False
materials = me.materials[:]
print("object contains " + str(len(materials)) + " materials")
if len(materials) == 0:
materials.append(None)
if EXPORT_CURVES and is_curve:
gather_curve_data(me, obj, objectParent, parentBone, materials[0], EXPORT_BOUNDS, bounds_set, meshes)
continue
me.calc_loop_triangles()
mats_2_faces = {}
edges_2_faces = {}
invalid_material_indices = {}
for face in me.loop_triangles:
mat_index = face.material_index
if mat_index is None:
mat_index = 0
if mat_index < 0 or mat_index >= len(materials):
mat_index = 0
if mat_index not in invalid_material_indices:
invalid_material_indices[mat_index] = True
self.report({'WARNING'}, f'Object \'{obj.name}\' contains an invalid material index {face.material_index}.')
mat = materials[mat_index]
if mat not in mats_2_faces:
mats_2_faces[mat] = []
mats_2_faces[mat].append(face)
if EXPORT_NEIGHBOR_INFO:
for l in face.loops:
edge_index = me.loops[l].edge_index
if not edge_index in edges_2_faces:
edges_2_faces[edge_index] = []
edges_2_faces[edge_index].append(face)
for mat in materials:
#if objects have a different parent (animation) they shouldn't be collated
mat_key = mat, use_tangents, objectParent, parentBone
if mat_key not in material_groups:
material_groups[mat_key] = []
#if the material doesn't have any faces assigned to it, don't bother giving it a chunk
if mat not in mats_2_faces:
continue
obj_data = {
"me": me,
"obj": final,
"materials": materials,
"faces": mats_2_faces[mat],
"edges_2_faces": edges_2_faces,
"parent": objectParent,
"parent_bone": parentBone
}
material_groups[mat_key].append(obj_data)
neighbor_map = {}
face_2_index_map = {}
for mat_key, group in material_groups.items():
material = mat_key[0]
use_tangents = mat_key[1]
print("Processing material")
#per-chunk data
unique_verts = []
indices = []
normals = []
face_normals = []
face_list = []
tangents = []
colors = []
area = 0.0
influence_bones = []
for obj_data in group:
me = obj_data["me"]
obj = obj_data["obj"]
materials = obj_data["materials"]
obj_faces = obj_data["faces"]
edges_2_faces = obj_data["edges_2_faces"]
objectParent = obj_data["parent"]
parentBone = obj_data["parent_bone"]
if len(me.uv_layers) == 0:
uv_layer = None
else:
uv_layer = me.uv_layers.active.data[:]
me_verts = me.vertices[:]
me_edges = me.edges[:]
if EXPORT_VERTEX_COLORS and len(me.vertex_colors) != 0:
# Blender 4.0 TODO: this is broken
color_layer = me.vertex_colors.active.data[:]
else:
color_layer = None
print("Processing mesh...")
#should be final - edge split, etc
vertgroups = obj.vertex_groups
#uv dictionary must be per object, otherwise duplicate objects (with similar normals and uvs) get merged
uv_dict = {}
uv = uv_key = uv_val = None
for i, face in enumerate(obj_faces):
area += face.area
face_normals.append(face.normal.normalized())
neighbors = []
if EXPORT_NEIGHBOR_INFO:
#store the face's parent chunk
neighbor_map[face] = [f for e in face.loops
for f in edges_2_faces[me.loops[e].edge_index] if f is not face]
face_2_index_map[face] = {
"index": len(face_list),
"attribute": len(meshes)
}
face_list.append(face)
for uv_index, l_index in enumerate(face.loops):
loop = me.loops[l_index]
vert = me_verts[loop.vertex_index]
#no = loop.normal
if bpy.app.version < (4, 1, 0):
no = mathutils.Vector(face.split_normals[uv_index])
else:
no = me.corner_normals[l_index].vector
tg = loop.tangent
color = color_layer[l_index].color if color_layer else [1, 1, 1, 1]
uv = uv_layer[l_index].uv if uv_layer != None else [0, 0]
uv_key = loop.vertex_index, veckey2d(uv), veckey3d(no), veckey3d(color)
# todo - is this necessary? probably not, tangents don't seem to be affected by split normals
# veckey3d(tg),
uv_val = uv_dict.get(uv_key)
if uv_val is None:
uv_dict[uv_key] = len(unique_verts)
influences = {}
for group in vertgroups:
try:
weight = group.weight(loop.vertex_index)
except RuntimeError:
weight = 0.0
if weight != 0.0:
influences[group.name] = weight
if group.name not in influence_bones:
influence_bones.append(group.name)
max_vert_influences = max(max_vert_influences, len(influences))
unique_verts.append([vert.co[:], uv[:], influences])
normals.append(no.normalized())
if use_tangents:
tangents.append(tg.normalized())
if EXPORT_VERTEX_COLORS:
colors.append(color)
if EXPORT_BOUNDS and not use_anim_bounds:
if bounds_set:
bounds_min.x = min(bounds_min.x, vert.co.x)
bounds_min.y = min(bounds_min.y, vert.co.y)
bounds_min.z = min(bounds_min.z, vert.co.z)
bounds_max.x = max(bounds_max.x, vert.co.x)
bounds_max.y = max(bounds_max.y, vert.co.y)
bounds_max.z = max(bounds_max.z, vert.co.z)
else:
bounds_set = True
bounds_min = mathutils.Vector(vert.co)
bounds_max = mathutils.Vector(vert.co)
indices.append(uv_dict[uv_key])
if len(unique_verts) > 65532 or len(indices) // 3 > 65535:
#apply and update
mesh_data = {
"obj": obj,
"material": material,
"unique_verts": unique_verts.copy(),
"indices": indices.copy(),
"normals": normals.copy(),
"face_normals": face_normals.copy(),
"face_list": face_list.copy(),
"tangents": tangents.copy(),
"colors": colors.copy(),
"area": area,
"uv_layer": uv_layer,
"parent": objectParent,
"parent_bone": parentBone,
"is_curve": False,
"max_influence": len(influence_bones)
}
meshes.append(mesh_data)
unique_verts.clear()
indices.clear()
normals.clear()
face_normals.clear()
face_list.clear()
tangents.clear()
colors.clear()
area = 0.0
uv_dict.clear()
uv = uv_key = uv_val = None
max_chunk_influences = max(max_chunk_influences, len(influence_bones))
influence_bones.clear()
print("Block split.")
#Add remaining verts
if len(unique_verts) > 0:
mesh_data = {
"obj": obj,
"material": material,
"unique_verts": unique_verts.copy(),
"indices": indices.copy(),
"normals": normals.copy(),
"face_normals": face_normals.copy(),
"face_list": face_list.copy(),
"tangents": tangents.copy(),
"colors": colors.copy(),
"area": area,
"uv_layer": uv_layer,
"parent": objectParent,
"parent_bone": parentBone,
"is_curve": False,
"max_influence": len(influence_bones)
}
meshes.append(mesh_data)
max_chunk_influences = max(max_chunk_influences, len(influence_bones))
print("Complete.")
#bm.free()
active_armature = None
bones = {}
root_bone = None
for ob in objects:
if ob.type != 'ARMATURE':
continue
active_armature = ob
break
if active_armature is None:
print("No armature in scene.")
#EXPORT_KIN = False
else:
for bone in active_armature.data.bones:
if "b.r." in bone.name or EXPORT_ALL_BONES:
#bone, chunk influences
if bone.parent == None:
boneMat = active_armature.matrix_world @ bone.matrix_local
else:
#convert bone transforms into world space and remove the scale
parentMatrix = active_armature.matrix_world @ bone.parent.matrix_local
parentMatrix = remove_scale_from_matrix(parentMatrix)
childMatrix = active_armature.matrix_world @ bone.matrix_local
childMatrix = remove_scale_from_matrix(childMatrix)
boneMat = parentMatrix.inverted() @ childMatrix
boneMat = EXPORT_GLOBAL_MATRIX @ boneMat
worldMat = EXPORT_GLOBAL_MATRIX @ remove_scale_from_matrix(active_armature.matrix_world @ bone.matrix_local)
bone_data = {
"srcBone": bone,
"matrix": boneMat,
"worldMatrix": worldMat,
"infl": [[] for _ in range(len(meshes))]
}
bones[bone.name] = bone_data
if bone.parent == None:
root_bone = bone
#legacy empty, lattice support
for ob in objects:
if "b.r." in ob.name:
print("Found bone object " + ob.name)
if ob.parent == None:
boneMat = ob.matrix_world
else:
boneMat = ob.matrix_parent_inverse @ ob.matrix_world
boneMat = EXPORT_GLOBAL_MATRIX @ boneMat
worldMat = EXPORT_GLOBAL_MATRIX @ ob.matrix_world
bone_data = {
"srcBone": ob,
"matrix": boneMat,