-
Notifications
You must be signed in to change notification settings - Fork 302
/
fbx2gltf.py
1580 lines (1347 loc) · 57.5 KB
/
fbx2gltf.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python
# ############################################
# fbx to glTF2.0 converter
# glTF spec : https://github.com/KhronosGroup/glTF/blob/master/specification/2.0
# fbx version 2018.1.1
# http://github.com/pissang/
# ############################################
import sys, struct, json, os.path, math, argparse, shutil
try:
from FbxCommon import *
except ImportError:
import platform
msg = 'You need to copy the content in compatible subfolder under /lib/python<version> into your python install folder such as '
if platform.system() == 'Windows' or platform.system() == 'Microsoft':
msg += '"Python33/Lib/site-packages"'
elif platform.system() == 'Linux':
msg += '"/usr/local/lib/python3.3/site-packages"'
elif platform.system() == 'Darwin':
msg += '"/Library/Frameworks/Python.framework/Versions/3.3/lib/python3.3/site-packages"'
msg += ' folder.'
print(msg)
sys.exit(1)
lib_materials = []
lib_images = []
lib_samplers = []
lib_textures = []
# attributes, indices, anim_parameters will be merged in accessors
lib_attributes_accessors = []
lib_indices_accessors = []
lib_animation_accessors = []
lib_ibm_accessors = []
lib_accessors = []
lib_buffer_views = []
lib_buffers = []
lib_cameras = []
lib_meshes = []
lib_nodes = []
lib_scenes = []
lib_skins = []
lib_animations = []
# Only python 3 support bytearray ?
# http://dabeaz.blogspot.jp/2010/01/few-useful-bytearray-tricks.html
attributeBuffer = bytearray()
indicesBuffer = bytearray()
invBindMatricesBuffer = bytearray()
animationBuffer = bytearray()
GL_RGBA = 0x1908
GL_BYTE = 5120
GL_UNSIGNED_BYTE = 5121
GL_SHORT = 5122
GL_UNSIGNED_SHORT = 5123
GL_UNSIGNED_INT = 5125
GL_FLOAT = 5126
GL_TEXTURE_2D = 0x0DE1
GL_TEXTURE_CUBE_MAP = 0x8513
GL_REPEAT = 0x2901
GL_CLAMP_TO_EDGE = 0x812F
GL_NEAREST = 0x2600
GL_LINEAR = 0x2601
GL_NEAREST_MIPMAP_NEAREST = 0x2700
GL_LINEAR_MIPMAP_NEAREST = 0x2701
GL_NEAREST_MIPMAP_LINEAR = 0x2702
GL_LINEAR_MIPMAP_LINEAR = 0x2703
GL_ARRAY_BUFFER = 0x8892
GL_ELEMENT_ARRAY_BUFFER = 0x8893
ENV_QUANTIZE = False
ENV_FLIP_V = True
_id = 0
def GetId():
global _id
_id = _id + 1
return _id
def ListFromM4(m):
return [m[0][0], m[0][1], m[0][2], m[0][3], m[1][0], m[1][1], m[1][2], m[1][3], m[2][0], m[2][1], m[2][2], m[2][3], m[3][0], m[3][1], m[3][2], m[3][3]]
def MatGetOpacity(pMaterial):
lFactor = pMaterial.TransparencyFactor.Get()
lColor = pMaterial.TransparentColor.Get()
return 1.0 - lFactor * (lColor[0] + lColor[1] + lColor[2]) / 3.0;
def quantize(pList, pStride, pMin, pMax):
lRange = range(pStride)
lMultiplier = []
lDivider = []
# TODO dynamic precision? may lose info?
lPrecision = float(1e6)
for i in lRange:
pMax[i] = math.ceil(pMax[i] * lPrecision) / lPrecision;
pMin[i] = math.floor(pMin[i] * lPrecision) / lPrecision;
if pMax[i] == pMin[i]:
lMultiplier.append(0.0)
lDivider.append(0.0)
else:
lDividerTmp = (pMax[i] - pMin[i]) / 65535.0;
lDividerTmp = math.ceil(lDividerTmp * lPrecision) / lPrecision
lDivider.append(lDividerTmp)
lMultiplier.append(1.0 / lDividerTmp)
lNewList = []
for item in pList:
if pStride == 1:
lNewList.append(int((item - pMin[0]) * lMultiplier[0]))
else:
lNewItem = []
for i in lRange:
lNewItem.append(int((item[i] - pMin[i]) * lMultiplier[i]))
lNewList.append(lNewItem)
# TODO
if pStride == 1:
lDecodeMatrix = [
lDivider[0], 0,
pMin[0], 1
]
elif pStride == 2:
lDecodeMatrix = [
lDivider[0], 0, 0,
0, lDivider[1], 0,
pMin[0], pMin[1], 1
]
elif pStride == 3:
lDecodeMatrix = [
lDivider[0], 0, 0, 0,
0, lDivider[1], 0, 0,
0, 0, lDivider[2], 0,
pMin[0], pMin[1], pMin[2], 1
]
elif pStride == 4:
lDecodeMatrix = [
lDivider[0], 0, 0, 0, 0,
0, lDivider[1], 0, 0, 0,
0, 0, lDivider[2], 0, 0,
0, 0, 0, lDivider[3], 0,
pMin[0], pMin[1], pMin[2], pMin[3], 1
]
return lNewList, lDecodeMatrix, pMin, pMax
def CreateAccessorBuffer(pList, pType, pStride, pMinMax=False, pQuantize=False, pNormalize=False):
lGLTFAccessor = {}
if pMinMax:
if len(pList) > 0:
if pStride == 1:
lMin = [pList[0]]
lMax = [pList[0]]
elif pStride == 16:
lMin = ListFromM4(pList[0])
lMax = ListFromM4(pList[0])
else:
lMin = list(pList[0])[:pStride]
lMax = list(pList[0])[:pStride]
else:
lMax = [0] * pStride
lMin = [0] * pStride
lRange = range(pStride)
for item in pList:
if pStride == 1:
for i in lRange:
lMin[i] = min(lMin[i], item)
lMax[i] = max(lMax[i], item)
else:
if pStride == 16:
item = ListFromM4(item)
for i in lRange:
lMin[i] = min(lMin[i], item[i])
lMax[i] = max(lMax[i], item[i])
if pQuantize and pType == 'f' and pStride <= 4:
pList, lDecodeMatrix, lDecodedMin, lDecodedMax = quantize(pList, pStride, lMin[0:], lMax[0:])
pType = 'H'
# https://github.com/KhronosGroup/glTF/blob/master/extensions/Vendor/WEB3D_quantized_attributes
lGLTFAccessor['extensions'] = {
'WEB3D_quantized_attributes': {
'decodedMin': lDecodedMin,
'decodedMax': lDecodedMax,
'decodeMatrix': lDecodeMatrix
}
}
lPackType = '<' + pType * pStride
lData = []
#TODO: Other method to write binary buffer ?
for item in pList:
if pStride == 1:
lData.append(struct.pack(lPackType, item))
elif pStride == 2:
lData.append(struct.pack(lPackType, item[0], item[1]))
elif pStride == 3:
lData.append(struct.pack(lPackType, item[0], item[1], item[2]))
elif pStride == 4:
lData.append(struct.pack(lPackType, item[0], item[1], item[2], item[3]))
elif pStride == 16:
m = item
lData.append(struct.pack(lPackType, m[0][0], m[0][1], m[0][2], m[0][3], m[1][0], m[1][1], m[1][2], m[1][3], m[2][0], m[2][1], m[2][2], m[2][3], m[3][0], m[3][1], m[3][2], m[3][3]))
if pType == 'f':
lGLTFAccessor['componentType'] = GL_FLOAT
# Unsigned Int
elif pType == 'I':
lGLTFAccessor['componentType'] = GL_UNSIGNED_INT
# Unsigned Short
elif pType == 'H':
lGLTFAccessor['componentType'] = GL_UNSIGNED_SHORT
# Unsigned Byte
elif pType == 'B':
lGLTFAccessor['componentType'] = GL_UNSIGNED_BYTE
if pStride == 1:
lGLTFAccessor['type'] = 'SCALAR'
elif pStride == 2:
lGLTFAccessor['type'] = 'VEC2'
elif pStride == 3:
lGLTFAccessor['type'] = 'VEC3'
elif pStride == 4:
lGLTFAccessor['type'] = 'VEC4'
elif pStride == 9:
lGLTFAccessor['type'] = 'MAT3'
elif pStride == 16:
lGLTFAccessor['type'] = 'MAT4'
lGLTFAccessor['byteOffset'] = 0
lGLTFAccessor['count'] = len(pList)
if pMinMax:
lGLTFAccessor['max'] = lMax
lGLTFAccessor['min'] = lMin
if pNormalize:
lGLTFAccessor['normalized'] = True
return b''.join(lData), lGLTFAccessor
def appendToBuffer(pType, pBuffer, pData, pObj):
lByteOffset = len(pBuffer)
if pType == 'f' or pType == 'I':
# should be a multiple of 4 for alignment
if lByteOffset % 4 == 2:
pBuffer.extend(b'\x00\x00')
lByteOffset += 2
pObj['byteOffset'] = lByteOffset
pBuffer.extend(pData)
def CreateAttributeBuffer(pList, pType, pStride, pNormalize=False):
lData, lGLTFAttribute = CreateAccessorBuffer(pList, pType, pStride, True, ENV_QUANTIZE, pNormalize)
appendToBuffer(pType, attributeBuffer, lData, lGLTFAttribute)
idx = len(lib_accessors)
lib_attributes_accessors.append(lGLTFAttribute)
lib_accessors.append(lGLTFAttribute)
return idx
def CreateIndicesBuffer(pList, pType):
# Sketchfab needs all accessor have min, max?
lData, lGLTFIndices = CreateAccessorBuffer(pList, pType, 1, True)
appendToBuffer(pType, indicesBuffer, lData, lGLTFIndices)
idx = len(lib_accessors)
lib_indices_accessors.append(lGLTFIndices)
lib_accessors.append(lGLTFIndices)
return idx
def CreateAnimationBuffer(pList, pType, pStride):
lData, lGLTFAnimSampler = CreateAccessorBuffer(pList, pType, pStride, True)
# PENDING
# lAllSame = True
# for i in range(pStride):
# if lGLTFAnimSampler['min'][i] != lGLTFAnimSampler['max'][i]:
# lAllSame = False
# # Just ignore it.
# if lAllSame:
# return -1
appendToBuffer(pType, animationBuffer, lData, lGLTFAnimSampler)
idx = len(lib_accessors)
lib_animation_accessors.append(lGLTFAnimSampler)
lib_accessors.append(lGLTFAnimSampler)
return idx
def CreateIBMBuffer(pList):
lData, lGLTFIBM = CreateAccessorBuffer(pList, 'f', 16, True)
appendToBuffer('f', invBindMatricesBuffer, lData, lGLTFIBM)
idx = len(lib_accessors)
lib_ibm_accessors.append(lGLTFIBM)
lib_accessors.append(lGLTFIBM)
return idx
def CreateImage(pPath):
lImageIndices = [idx for idx in range(len(lib_images)) if lib_images[idx]['uri'] == pPath]
if len(lImageIndices):
return lImageIndices[0]
lImageIdx = len(lib_images)
lib_images.append({
'uri' : pPath
})
return lImageIdx
def HashSampler(pTexture):
lHashStr = []
# Wrap S
lHashStr.append(str(pTexture.WrapModeU.Get()))
# Wrap T
lHashStr.append(str(pTexture.WrapModeV.Get()))
return ' '.join(lHashStr)
def ConvertWrapMode(pWrap):
if pWrap == FbxTexture.eRepeat:
return GL_REPEAT
elif pWrap == FbxTexture.eClamp:
return GL_CLAMP_TO_EDGE
_samplerHashMap = {}
def CreateSampler(pTexture):
lHashKey = HashSampler(pTexture)
if lHashKey in _samplerHashMap:
return _samplerHashMap[lHashKey]
else:
lSamplerIdx = len(lib_samplers)
lib_samplers.append({
'wrapS' : ConvertWrapMode(pTexture.WrapModeU.Get()),
'wrapT' : ConvertWrapMode(pTexture.WrapModeV.Get()),
# Texture filter in fbx ?
'minFilter' : GL_LINEAR_MIPMAP_LINEAR,
'magFilter' : GL_LINEAR
})
_samplerHashMap[lHashKey] = lSamplerIdx
return lSamplerIdx
_textureHashMap = {}
def CreateTexture(pProperty):
lTextureList = []
lFileTextures = []
lLayeredTextureCount = pProperty.GetSrcObjectCount(FbxCriteria.ObjectType(FbxLayeredTexture.ClassId))
lScaleU = 1
lScaleV = 1
lTranslationU = 0
lTranslationV = 0
if lLayeredTextureCount > 0:
for i in range(lLayeredTextureCount):
lLayeredTexture = pProperty.GetSrcObject(FbxCriteria.ObjectType(FbxLayeredTexture.ClassId), i)
for j in range(lLayeredTexture.GetSrcObjectCount(FbxCriteria.ObjectType(FbxTexture.ClassId))):
lTexture = lLayeredTexture.GetSrcObject(FbxCriteria.ObjectType(FbxTexture.ClassId), j)
if lTexture and lTexture.__class__ == FbxFileTexture:
lFileTextures.append(lTexture)
else:
lTextureCount = pProperty.GetSrcObjectCount(FbxCriteria.ObjectType(FbxTexture.ClassId))
for t in range(lTextureCount):
lTexture = pProperty.GetSrcObject(FbxCriteria.ObjectType(FbxTexture.ClassId), t)
if lTexture and lTexture.__class__ == FbxFileTexture:
lFileTextures.append(lTexture)
for lTexture in lFileTextures:
try:
lTextureFileName = lTexture.GetFileName()
except UnicodeDecodeError:
print('Get texture file name error.')
continue
# TODO rotation
lScaleU = lTexture.GetScaleU()
lScaleV = lTexture.GetScaleV()
lTranslationU = lTexture.GetTranslationU()
lTranslationV = lTexture.GetTranslationV()
lImageIdx = CreateImage(lTextureFileName)
lSamplerIdx = CreateSampler(lTexture)
lHashKey = (lImageIdx, lSamplerIdx)
if lHashKey in _textureHashMap:
lTextureList.append(_textureHashMap[lHashKey])
else:
lTextureIdx = len(lib_textures)
lib_textures.append({
'format' : GL_RGBA,
'internalFormat' : GL_RGBA,
'sampler' : lSamplerIdx,
'source' : lImageIdx,
'target' : GL_TEXTURE_2D
})
_textureHashMap[lHashKey] = lTextureIdx
lTextureList.append(lTextureIdx)
# PENDING Return the first texture ?
if len(lTextureList) > 0:
return lTextureList[0], lScaleU, lScaleV, lTranslationU, lTranslationV
else:
return None, lScaleU, lScaleV, lTranslationU, lTranslationV
def GetRoughnessFromExponentShininess(pShininess):
# PENDING Is max 1024?
lGlossiness = math.log(pShininess) / math.log(1024.0)
return min(max(1 - lGlossiness, 0), 1)
def GetMetalnessFromSpecular(pSpecular, pBaseColor):
# x = pSpecular[0]
# y = pBaseColor[0]
# a = 0.04
# b = x + y - 0.08
# c = 0.04 - x
# k = b * b - 4 * a * c
# if k >= 0:
# return math.sqrt(k)
# return 0
# PENDING
if pSpecular[0] > 0.5:
return 1
else:
return 0
def ScaleV3(v3, scale):
v3[0] *= scale
v3[1] *= scale
v3[2] *= scale
def ConvertToPBRMaterial(pMaterial):
lMaterialName = pMaterial.GetName()
lShading = str(pMaterial.ShadingModel.Get()).lower()
lScaleU = 1
lScaleV = 1
lTranslationU = 0
lTranslationV = 0
lGLTFMaterial = {
"name" : lMaterialName,
"pbrMetallicRoughness": {
"baseColorFactor": [1, 1, 1, 1],
"metallicFactor": 0,
"roughnessFactor": 1
}
}
lValues = lGLTFMaterial["pbrMetallicRoughness"]
lMaterialIdx = len(lib_materials)
lSpecularColor = [0, 0, 0]
# print(dir(pMaterial))
if hasattr(pMaterial, 'Emissive'):
lGLTFMaterial['emissiveFactor'] = list(pMaterial.Emissive.Get())
ScaleV3(lGLTFMaterial['emissiveFactor'], pMaterial.EmissiveFactor.Get())
if hasattr(pMaterial, 'TransparencyFactor'):
lTransparency = MatGetOpacity(pMaterial)
if lTransparency < 1:
lGLTFMaterial['alphaMode'] = 'BLEND'
lValues['baseColorFactor'][3] = lTransparency
if hasattr(pMaterial, 'Diffuse'):
if pMaterial.Diffuse.GetSrcObjectCount() > 0:
# TODO other textures ?
lTextureIdx, lScaleU, lScaleV, lTranslationU, lTranslationV = CreateTexture(pMaterial.Diffuse)
if not lTextureIdx == None:
lValues['baseColorTexture'] = {
"index": lTextureIdx,
"texCoord": 0
}
else:
lValues['baseColorFactor'][0:3] = list(pMaterial.Diffuse.Get())
if hasattr(pMaterial, 'Specular'):
lSpecularColor = list(pMaterial.Specular.Get())
ScaleV3(lSpecularColor, pMaterial.SpecularFactor.Get())
if hasattr(pMaterial, 'Bump'):
if pMaterial.Bump.GetSrcObjectCount() > 0:
lTextureIdx, lScaleU, lScaleV, lTranslationU, lTranslationV = CreateTexture(pMaterial.Bump)
if not lTextureIdx == None:
lGLTFMaterial['normalTexture'] = {
"index": lTextureIdx,
"texCoord": 0
}
if hasattr(pMaterial, 'NormalMap'):
if pMaterial.NormalMap.GetSrcObjectCount() > 0:
lTextureIdx, lScaleU, lScaleV, lTranslationU, lTranslationV = CreateTexture(pMaterial.NormalMap)
if not lTextureIdx == None:
lGLTFMaterial['normalTexture'] = {
"index": lTextureIdx,
"texCoord": 0
}
if hasattr(pMaterial, 'NormalMShininessap'):
lValues['roughnessFactor'] = GetRoughnessFromExponentShininess(pMaterial.Shininess.Get())
lib_materials.append(lGLTFMaterial)
if lShading == 'unknown':
# Maybe shading of VRay
lProp = pMaterial.GetFirstProperty()
lCount = 0
while lProp:
lPropName = lProp.GetName()
if lPropName == '' or lCount >= 100:
break
# TODO texture
if lPropName == 'EmissiveColor':
# Need to cast to double3
# https://forums.autodesk.com/t5/fbx-forum/fbxproperty-get-in-2013-1-python/td-p/4243290
lGLTFMaterial['emissiveFactor'] = list(FbxPropertyDouble3(lProp).Get())
elif lPropName == 'DiffuseColor':
lValues['baseColorFactor'][0:3] = list(FbxPropertyDouble3(lProp).Get())
elif lPropName == 'SpecularColor':
lSpecularColor = list(FbxPropertyDouble3(lProp).Get())
elif lPropName == 'SpecularFactor':
ScaleV3(lSpecularColor, FbxPropertyDouble1(lProp).Get())
elif lPropName == 'ShininessExponent':
lValues['roughnessFactor'] = GetRoughnessFromExponentShininess(FbxPropertyDouble1(lProp).Get())
lProp = pMaterial.GetNextProperty(lProp)
lCount += 1
lValues['metallicFactor'] = GetMetalnessFromSpecular(lSpecularColor, lValues['baseColorFactor'][0:3])
return lMaterialIdx, lScaleU, lScaleV, lTranslationU, lTranslationV
def CreateSkin():
lSkinIdx = len(lib_skins)
# https://github.com/KhronosGroup/glTF/issues/100
lib_skins.append({
'joints' : [],
})
return lSkinIdx
_defaultMaterialName = 'DEFAULT_MAT_'
def CreateDefaultMaterial(pScene):
lMat = FbxSurfacePhong.Create(pScene, _defaultMaterialName + str(len(lib_materials)))
return lMat
def ProcessUV(uv, scaleU, scaleV, translationU, translationV):
for i in range(len(uv)):
uv[i] = [
uv[i][0] * scaleU + translationU,
uv[i][1] * scaleV + translationV
]
if ENV_FLIP_V:
# glTF2.0 don't flipY. So flip the uv.
uv[i][1] = 1.0 - uv[i][1]
def GetSkinningData(pMesh, pSkin, pClusters, pNode):
moreThanFourJoints = False
lMaxJointCount = 0
lControlPointsCount = pMesh.GetControlPointsCount()
lWeights = []
lJoints = []
# Count joint number of each vertex
lJointCounts = []
for i in range(lControlPointsCount):
lWeights.append([0, 0, 0, 0])
# -1 can't used in UNSIGNED_SHORT
lJoints.append([0, 0, 0, 0])
lJointCounts.append(0)
for i in range(pMesh.GetDeformerCount(FbxDeformer.eSkin)):
lDeformer = pMesh.GetDeformer(i, FbxDeformer.eSkin)
for i2 in range(lDeformer.GetClusterCount()):
lCluster = lDeformer.GetCluster(i2)
lNode = lCluster.GetLink()
lJointIndex = -1
lNodeIdx = GetNodeIdx(lNode)
if not lNodeIdx in pSkin['joints']:
lJointIndex = len(pSkin['joints'])
pSkin['joints'].append(lNodeIdx)
pClusters[lNodeIdx] = lCluster
else:
lJointIndex = pSkin['joints'].index(lNodeIdx)
lControlPointIndices = lCluster.GetControlPointIndices()
lControlPointWeights = lCluster.GetControlPointWeights()
for i3 in range(lCluster.GetControlPointIndicesCount()):
lControlPointIndex = lControlPointIndices[i3]
lControlPointWeight = lControlPointWeights[i3]
lJointCount = lJointCounts[lControlPointIndex]
# At most binding four joint per vertex
if lJointCount <= 3:
# Joint index
lJoints[lControlPointIndex][lJointCount] = lJointIndex
lWeights[lControlPointIndex][lJointCount] = lControlPointWeight
else:
moreThanFourJoints = True
# More than four joints, replace joint of minimum Weight
lMinW, lMinIdx = min((lWeights[lControlPointIndex][i], i) for i in range(len(lWeights[lControlPointIndex])))
lJoints[lControlPointIndex][lMinIdx] = lJointIndex
lWeights[lControlPointIndex][lMinIdx] = lControlPointWeight
lMaxJointCount = max(lMaxJointCount, lJointIndex)
lJointCounts[lControlPointIndex] += 1
if moreThanFourJoints:
print('More than 4 joints (%d joints) bound to per vertex in %s. ' %(lMaxJointCount, pNode.GetName()))
return lJoints, lWeights
def CreatePrimitiveRaw(matIndex, useTexcoords1=False, scaleU=1, scaleV=1,translationU=0, translationV=1):
return {
"normals": [],
"texcoords0": [],
"texcoords1": [],
"indices": [],
"positions": [],
"vertexColors": [],
"joints": [],
"weights": [],
"material": matIndex,
# Should use texcoord in layer2 if material is in layer2
# PENDING
"useTexcoords1": useTexcoords1,
"indicesMap": {},
"scaleU": scaleU,
"scaleV": scaleV,
"translationU": translationU,
"translationV": translationV
}
def GetVertexAttribute(pLayer, pControlPointIdx, pPolygonVertexIndex):
if pLayer.GetMappingMode() == FbxLayerElement.eByControlPoint:
if pLayer.GetReferenceMode() == FbxLayerElement.eDirect:
return pLayer.GetDirectArray().GetAt(pControlPointIdx)
elif pLayer.GetReferenceMode() == FbxLayerElement.eIndexToDirect:
return pLayer.GetDirectArray().GetAt(pLayer.GetIndexArray().GetAt(pControlPointIdx))
elif pLayer.GetMappingMode() == FbxLayerElement.eByPolygonVertex:
if pLayer.GetReferenceMode() == FbxLayerElement.eDirect:
return pLayer.GetDirectArray().GetAt(pPolygonVertexIndex)
elif pLayer.GetReferenceMode() == FbxLayerElement.eDirect or\
pLayer.GetReferenceMode() == FbxLayerElement.eIndexToDirect:
return pLayer.GetDirectArray().GetAt(pLayer.GetIndexArray().GetAt(pPolygonVertexIndex))
else:
pass
# Unknown
def ConvertMesh(pScene, pMesh, pNode, pSkin, pClusters):
lPrimitivesList = []
lWeights = []
lJoints = []
lLayer = pMesh.GetLayer(0)
lLayer2 = pMesh.GetLayer(1)
lSecondMaterialLayer = None
if lLayer2:
lSecondMaterialLayer = lLayer2.GetMaterials()
lNormalLayer = pMesh.GetElementNormal(0)
lVertexColorLayer = pMesh.GetElementVertexColor(0)
lUvLayer = pMesh.GetElementUV(0)
lUv2Layer = pMesh.GetElementUV(1)
hasSkin = False
# Handle Skinning data
if (pMesh.GetDeformerCount(FbxDeformer.eSkin) > 0):
hasSkin = True
lJoints, lWeights = GetSkinningData(pMesh, pSkin, pClusters, pNode)
lPositions = pMesh.GetControlPoints()
# Prepare materials
lAllSameMaterial = True
lAllSameMaterialIndex = -1
for i in range(pMesh.GetElementMaterialCount()):
lMaterialLayer = pMesh.GetElementMaterial(i)
if not lMaterialLayer.GetMappingMode() == FbxLayerElement.eAllSame:
lIndexArray = lMaterialLayer.GetIndexArray()
for k in range(pMesh.GetPolygonCount()):
if not lIndexArray.GetAt(k) == lIndexArray.GetAt(0):
lAllSameMaterial = False
break
if lAllSameMaterial:
lAllSameMaterialIndex = lMaterialLayer.GetIndexArray().GetAt(0)
if lAllSameMaterial:
lMaterial = pNode.GetMaterial(lAllSameMaterialIndex)
if not lMaterial:
lMaterial = CreateDefaultMaterial(pScene)
lTmpIndex, lScaleU, lScaleV, lTranslationU, lTranslationV = ConvertToPBRMaterial(lMaterial)
lPrimitivesList.append(CreatePrimitiveRaw(
lTmpIndex, False,
lScaleU, lScaleV, lTranslationU, lTranslationV
))
else:
lMaterialIndices = [-1]*pMesh.GetPolygonCount()
lMaterialsPrimitivesMap = {}
lIsMaterialInSecondLayer = {}
for i in range(pMesh.GetElementMaterialCount()):
lMaterialLayer = pMesh.GetElementMaterial(i)
lIndexArray = lMaterialLayer.GetIndexArray()
lIsInSecondLayer = lMaterialLayer == lSecondMaterialLayer
if lMaterialLayer.GetMappingMode() == FbxLayerElement.eByPolygon:
for k in range(len(lMaterialIndices)):
if lIndexArray.GetAt(k) >= 0:
# index in top material layer will overwrite the bottom material layer
lMaterialIndices[k] = lIndexArray.GetAt(k)
lIsMaterialInSecondLayer[lIndexArray.GetAt(k)] = lIsInSecondLayer
elif lMaterialLayer.GetMappingMode() == FbxLayerElement.eAllSame:
lIdx = lIndexArray.GetAt(0)
if lIdx:
if lIdx >= 0:
for k in range(len(lMaterialIndices)):
lMaterialIndices[k] = lIdx
lIsMaterialInSecondLayer[lIdx] = lIsInSecondLayer
for lIdx in lMaterialIndices:
if not lIdx in lMaterialsPrimitivesMap:
lMaterial = pNode.GetMaterial(lIdx)
if not lMaterial:
lMaterial = CreateDefaultMaterial(pScene)
lGLTFMaterialIdx, lScaleU, lScaleV, lTranslationU, lTranslationV = ConvertToPBRMaterial(lMaterial)
lMaterialsPrimitivesMap[lIdx] = len(lPrimitivesList)
lPrimitivesList.append(CreatePrimitiveRaw(
lGLTFMaterialIdx, lIsMaterialInSecondLayer[lIdx],
lScaleU, lScaleV, lTranslationU, lTranslationV
))
range3 = range(3)
lVertexCount = 0
lNeedHash = False
if lNormalLayer:
if lNormalLayer.GetMappingMode() == FbxLayerElement.eByPolygonVertex:
lNeedHash = True
if lVertexColorLayer:
if lVertexColorLayer.GetMappingMode() == FbxLayerElement.eByPolygonVertex:
lNeedHash = True
if lUvLayer:
if lUvLayer.GetMappingMode() == FbxLayerElement.eByPolygonVertex:
lNeedHash = True
if lUv2Layer:
if lUv2Layer.GetMappingMode() == FbxLayerElement.eByPolygonVertex:
lNeedHash = True
for i in range(pMesh.GetPolygonCount()):
if lAllSameMaterial:
lPrimitive = lPrimitivesList[0]
else:
lMaterialIndex = lMaterialIndices[i]
lPrimitive = lPrimitivesList[lMaterialsPrimitivesMap[lMaterialIndex]]
# Mesh should be triangulated
for j in range3:
lControlPointIndex = pMesh.GetPolygonVertex(i, j)
if lNeedHash:
vertexKeyList = []
vertexKeyList += lPositions[lControlPointIndex]
if lNormalLayer:
lNormal = GetVertexAttribute(lNormalLayer, lControlPointIndex, lVertexCount)
if lNeedHash:
vertexKeyList += lNormal
if lVertexColorLayer:
lVertexColor = GetVertexAttribute(lVertexColorLayer, lControlPointIndex, lVertexCount)
lVertexColor = [lVertexColor.mRed, lVertexColor.mGreen, lVertexColor.mBlue, lVertexColor.mAlpha]
lVertexColor = [round(i * 255) for i in lVertexColor]
if lNeedHash:
vertexKeyList += lVertexColor
if lUvLayer:
# PENDING GetTextureUVIndex?
lUv = GetVertexAttribute(lUvLayer, lControlPointIndex, lVertexCount)
if lNeedHash:
vertexKeyList += lUv
if lUv2Layer:
lUv2 = GetVertexAttribute(lUv2Layer, lControlPointIndex, lVertexCount)
if lNeedHash:
vertexKeyList += lUv2
lVertexCount += 1
if lNeedHash:
vertexKey = tuple(vertexKeyList)
else:
vertexKey = lControlPointIndex
if not vertexKey in lPrimitive['indicesMap']:
lIndex = len(lPrimitive['positions'])
lPrimitive['positions'].append(lPositions[lControlPointIndex])
if lNormalLayer and lNormal: # incase unsupported mapping mode returns none.
lPrimitive['normals'].append(lNormal)
if lVertexColorLayer and lVertexColor: # incase unsupported mapping mode returns none.
lPrimitive['vertexColors'].append(lVertexColor)
# PENDING
# Texcoord may be put in the second layer
if lPrimitive['useTexcoords1']:
if lUv2Layer:
if lUv2: # incase unsupported mapping mode returns none.
lPrimitive['texcoords0'].append(lUv2)
else:
if lUv: # incase unsupported mapping mode returns none.
lPrimitive['texcoords0'].append(lUv)
else:
if lUvLayer:
if lUv: # incase unsupported mapping mode returns none.
lPrimitive['texcoords0'].append(lUv)
if lUv2Layer:
if lUv2: # incase unsupported mapping mode returns none.
lPrimitive['texcoords1'].append(lUv2)
if hasSkin:
lPrimitive['joints'].append(lJoints[lControlPointIndex])
lPrimitive['weights'].append(lWeights[lControlPointIndex])
lPrimitive['indicesMap'][vertexKey] = lIndex
else:
lIndex = lPrimitive['indicesMap'][vertexKey]
lPrimitive['indices'].append(lIndex)
lGLTFPrimitivesList = []
for i in range(len(lPrimitivesList)):
lPrimitive = lPrimitivesList[i]
lGLTFPrimitive = {
'attributes': {
'POSITION': CreateAttributeBuffer(lPrimitive['positions'], 'f', 3)
},
'material': lPrimitive['material']
}
if len(lPrimitive['normals']) > 0:
lGLTFPrimitive['attributes']['NORMAL'] = CreateAttributeBuffer(lPrimitive['normals'], 'f', 3)
if len(lPrimitive['vertexColors']) > 0:
lGLTFPrimitive['attributes']['COLOR_0'] = CreateAttributeBuffer(lPrimitive['vertexColors'], 'B', 4, True)
if len(lPrimitive['texcoords0']) > 0:
ProcessUV(
lPrimitive['texcoords0'],
lPrimitive['scaleU'], lPrimitive['scaleV'],
lPrimitive['translationU'], lPrimitive['translationV']
)
lGLTFPrimitive['attributes']['TEXCOORD_0'] = CreateAttributeBuffer(lPrimitive['texcoords0'], 'f', 2)
if len(lPrimitive['texcoords1']) > 0:
ProcessUV(
lPrimitive['texcoords1'],
lPrimitive['scaleU'], lPrimitive['scaleV'],
lPrimitive['translationU'], lPrimitive['translationV']
)
lGLTFPrimitive['attributes']['TEXCOORD_1'] = CreateAttributeBuffer(lPrimitive['texcoords1'], 'f', 2)
if len(lPrimitive['joints']) > 0:
# PENDING UNSIGNED_SHORT will have bug.
lGLTFPrimitive['attributes']['JOINTS_0'] = CreateAttributeBuffer(lPrimitive['joints'], 'H', 4)
# TODO Seems most engines needs VEC4 weights.
lGLTFPrimitive['attributes']['WEIGHTS_0'] = CreateAttributeBuffer(lPrimitive['weights'], 'f', 4)
if len(lPrimitive['positions']) >= 0xffff:
#Use unsigned int in element indices
lIndicesType = 'I'
else:
lIndicesType = 'H'
lGLTFPrimitive['indices'] = CreateIndicesBuffer(lPrimitive['indices'], lIndicesType)
lGLTFPrimitivesList.append(lGLTFPrimitive)
return lGLTFPrimitivesList
def ConvertCamera(pCamera):
lGLTFCamera = {}
if pCamera.ProjectionType.Get() == FbxCamera.ePerspective:
lGLTFCamera['type'] = 'perspective'
lGLTFCamera['perspective'] = {
"yfov": pCamera.FieldOfView.Get(),
"znear": pCamera.NearPlane.Get(),
"zfar": pCamera.FarPlane.Get()
}
elif pCamera.ProjectionType.Get() == FbxCamera.eOrthogonal:
lGLTFCamera['type'] = 'orthographic'
lGLTFCamera['orthographic'] = {
# PENDING
"xmag": pCamera.OrthoZoom.Get(),
"ymag": pCamera.OrthoZoom.Get(),
"znear": pCamera.NearPlane.Get(),
"zfar": pCamera.FarPlane.Get()
}
lCameraIdx = len(lib_cameras)
lib_cameras.append(lGLTFCamera)
return lCameraIdx
def ConvertSceneNode(pScene, pNode, pPoseTime):
lGLTFNode = {}
lNodeName = pNode.GetName()
lGLTFNode['name'] = pNode.GetName()
lib_nodes.append(lGLTFNode)
# Transform matrix
lGLTFNode['matrix'] = ListFromM4(pNode.EvaluateLocalTransform(pPoseTime, FbxNode.eDestinationPivot))
#PENDING : Triangulate and split all geometry not only the default one ?
#PENDING : Multiple node use the same mesh ?
lMesh = pNode.GetMesh()
# PENDING If invisible node will have all children invisible.
if pNode.GetVisibility() and lMesh:
lMeshKey = lNodeName
lMeshName = lMesh.GetName()
if lMeshName == '':
lMeshName = lMeshKey
lGLTFMesh = {'name' : lMeshName, "primitives": []}
# If any attribute of this node have skinning data
# (Mesh splitted by material may have multiple MeshAttribute in one node)
lHasSkin = lMesh.GetDeformerCount(FbxDeformer.eSkin) > 0
lGLTFSkin = None
lClusters = {}
if lHasSkin:
lSkinIdx = CreateSkin()
lGLTFSkin = lib_skins[lSkinIdx]
lGLTFNode['skin'] = lSkinIdx
if lMesh.GetLayer(0):
for i in range(pNode.GetNodeAttributeCount()):
lNodeAttribute = pNode.GetNodeAttributeByIndex(i)
if lNodeAttribute.GetAttributeType() == FbxNodeAttribute.eMesh:
lGLTFMesh['primitives'] += ConvertMesh(pScene, lNodeAttribute, pNode, lGLTFSkin, lClusters)
lMeshIdx = len(lib_meshes)
lib_meshes.append(lGLTFMesh)
lGLTFNode['mesh'] = lMeshIdx
if lHasSkin:
lClusterGlobalInitMatrix = FbxAMatrix()
lReferenceGlobalInitMatrix = FbxAMatrix()
lIBM = []
for i in range(len(lGLTFSkin['joints'])):
lJointIdx = lGLTFSkin['joints'][i]
lCluster = lClusters[lJointIdx]
# Inverse Bind Pose Matrix
# Matrix of Mesh
lCluster.GetTransformMatrix(lReferenceGlobalInitMatrix)
# Matrix of Joint
lCluster.GetTransformLinkMatrix(lClusterGlobalInitMatrix)
# http://blog.csdn.net/bugrunner/article/details/7232291
# http://help.autodesk.com/view/FBX/2017/ENU/?guid=__cpp_ref__view_scene_2_draw_scene_8cxx_example_html
m = lClusterGlobalInitMatrix.Inverse() * lReferenceGlobalInitMatrix
lIBM.append(m)
lGLTFSkin['inverseBindMatrices'] = CreateIBMBuffer(lIBM)
elif pNode.GetCamera():
# Camera attribute
lCameraKey = ConvertCamera(pNode.GetCamera())
lGLTFNode['camera'] = lCameraKey
if pNode.GetChildCount() > 0:
lGLTFNode['children'] = []
for i in range(pNode.GetChildCount()):
lChildNodeIdx = ConvertSceneNode(pScene, pNode.GetChild(i), pPoseTime)
if lChildNodeIdx >= 0:
lGLTFNode['children'].append(lChildNodeIdx)
return GetNodeIdx(pNode)
def ConvertScene(pScene, pPoseTime):
lRoot = pScene.GetRootNode()
lGLTFScene = {'nodes' : []}
lSceneIdx = len(lib_scenes)
lib_scenes.append(lGLTFScene)
for i in range(lRoot.GetChildCount()):
lNodeIdx = ConvertSceneNode(pScene, lRoot.GetChild(i), pPoseTime)
if lNodeIdx >= 0:
lGLTFScene['nodes'].append(lNodeIdx)
return lSceneIdx
def CreateAnimation(pName):
lAnimIdx = len(lib_animations)
lGLTFAnimation = {
'name': pName,
'channels' : [],
'samplers' : []
}