convert_to_threejs.py 63 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822
  1. # @author zfedoran / http://github.com/zfedoran
  2. import os
  3. import sys
  4. import math
  5. import operator
  6. # #####################################################
  7. # Globals
  8. # #####################################################
  9. option_triangulate = True
  10. option_textures = True
  11. option_prefix = True
  12. option_geometry = False
  13. option_default_camera = False
  14. option_default_light = False
  15. converter = None
  16. global_up_vector = None
  17. # #####################################################
  18. # Templates
  19. # #####################################################
  20. def Vector2String(v, no_brackets = False):
  21. if no_brackets:
  22. return '%g,%g' % (v[0], v[1])
  23. else:
  24. return '[ %g, %g ]' % (v[0], v[1])
  25. def Vector3String(v, no_brackets = False):
  26. if no_brackets:
  27. return '%g,%g,%g' % (v[0], v[1], v[2])
  28. else:
  29. return '[ %g, %g, %g ]' % (v[0], v[1], v[2])
  30. def ColorString(c, no_brackets = False):
  31. if no_brackets:
  32. return '%g, %g, %g' % (c[0], c[1], c[2])
  33. else:
  34. return '[ %g, %g, %g ]' % (c[0], c[1], c[2])
  35. def LabelString(s):
  36. return '"%s"' % s
  37. def ArrayString(s):
  38. return '[ %s ]' % s
  39. def PaddingString(n):
  40. output = ""
  41. for i in range(n):
  42. output += "\t"
  43. return output
  44. def BoolString(value):
  45. if value:
  46. return "true"
  47. return "false"
  48. # #####################################################
  49. # Helpers
  50. # #####################################################
  51. def getObjectName(o, force_prefix = False):
  52. if not o:
  53. return ""
  54. prefix = ""
  55. if option_prefix or force_prefix:
  56. prefix = "Object_%s_" % o.GetUniqueID()
  57. return prefix + o.GetName()
  58. def getGeometryName(g, force_prefix = False):
  59. prefix = ""
  60. if option_prefix or force_prefix:
  61. prefix = "Geometry_%s_" % g.GetUniqueID()
  62. return prefix + g.GetName()
  63. def getEmbedName(e, force_prefix = False):
  64. prefix = ""
  65. if option_prefix or force_prefix:
  66. prefix = "Embed_%s_" % e.GetUniqueID()
  67. return prefix + e.GetName()
  68. def getMaterialName(m, force_prefix = False):
  69. prefix = ""
  70. if option_prefix or force_prefix:
  71. prefix = "Material_%s_" % m.GetUniqueID()
  72. return prefix + m.GetName()
  73. def getTextureName(t, force_prefix = False):
  74. texture_file = t.GetFileName()
  75. texture_id = os.path.splitext(os.path.basename(texture_file))[0]
  76. prefix = ""
  77. if option_prefix or force_prefix:
  78. prefix = "Texture_%s_" % t.GetUniqueID()
  79. return prefix + texture_id
  80. def getFogName(f, force_prefix = False):
  81. prefix = ""
  82. if option_prefix or force_prefix:
  83. prefix = "Fog_%s_" % f.GetUniqueID()
  84. return prefix + f.GetName()
  85. def getObjectVisible(n):
  86. return BoolString(True)
  87. def getRadians(v):
  88. return ((v[0]*math.pi)/180, (v[1]*math.pi)/180, (v[2]*math.pi)/180)
  89. def getHex(c):
  90. color = (int(c[0]*255) << 16) + (int(c[1]*255) << 8) + int(c[2]*255)
  91. return color
  92. def setBit(value, position, on):
  93. if on:
  94. mask = 1 << position
  95. return (value | mask)
  96. else:
  97. mask = ~(1 << position)
  98. return (value & mask)
  99. def convert_fbx_color(color):
  100. return [color.mRed, color.mGreen, color.mBlue, color.mAlpha]
  101. def convert_fbx_vec2(v):
  102. return [v[0], v[1]]
  103. def convert_fbx_vec3(v):
  104. return [v[0], v[1], v[2]]
  105. def generate_uvs(uv_layers):
  106. layers = []
  107. for uvs in uv_layers:
  108. layer = ",".join(Vector2String(n, True) for n in uvs)
  109. layers.append(layer)
  110. return ",".join("[%s]" % n for n in layers)
  111. def generateMultiLineString(lines, separator, padding):
  112. cleanLines = []
  113. for i in range(len(lines)):
  114. line = lines[i]
  115. line = PaddingString(padding) + line
  116. cleanLines.append(line)
  117. return separator.join(cleanLines)
  118. def get_up_vector(scene):
  119. global_settings = scene.GetGlobalSettings()
  120. axis_system = global_settings.GetAxisSystem()
  121. up_vector = axis_system.GetUpVector()
  122. tmp = [0,0,0]
  123. tmp[up_vector[0] - 1] = up_vector[1] * 1
  124. return FbxVector4(tmp[0], tmp[1], tmp[2], 1)
  125. # #####################################################
  126. # Generate - Triangles
  127. # #####################################################
  128. def triangulate_node_hierarchy(node):
  129. node_attribute = node.GetNodeAttribute();
  130. if node_attribute:
  131. if node_attribute.GetAttributeType() == FbxNodeAttribute.eMesh or \
  132. node_attribute.GetAttributeType() == FbxNodeAttribute.eNurbs or \
  133. node_attribute.GetAttributeType() == FbxNodeAttribute.eNurbsSurface or \
  134. node_attribute.GetAttributeType() == FbxNodeAttribute.ePatch:
  135. converter.TriangulateInPlace(node);
  136. child_count = node.GetChildCount()
  137. for i in range(child_count):
  138. triangulate_node_hierarchy(node.GetChild(i))
  139. def triangulate_scene(scene):
  140. node = scene.GetRootNode()
  141. if node:
  142. for i in range(node.GetChildCount()):
  143. triangulate_node_hierarchy(node.GetChild(i))
  144. # #####################################################
  145. # Generate - Material String
  146. # #####################################################
  147. def generate_texture_bindings(material_property, texture_list):
  148. binding_types = {
  149. "DiffuseColor": "map", "DiffuseFactor": "diffuseFactor", "EmissiveColor": "emissiveMap",
  150. "EmissiveFactor": "emissiveFactor", "AmbientColor": "ambientMap", "AmbientFactor": "ambientFactor",
  151. "SpecularColor": "specularMap", "SpecularFactor": "specularFactor", "ShininessExponent": "shininessExponent",
  152. "NormalMap": "normalMap", "Bump": "bumpMap", "TransparentColor": "transparentMap",
  153. "TransparencyFactor": "transparentFactor", "ReflectionColor": "reflectionMap",
  154. "ReflectionFactor": "reflectionFactor", "DisplacementColor": "displacementMap",
  155. "VectorDisplacementColor": "vectorDisplacementMap"
  156. }
  157. if material_property.IsValid():
  158. #Here we have to check if it's layeredtextures, or just textures:
  159. layered_texture_count = material_property.GetSrcObjectCount(FbxLayeredTexture.ClassId)
  160. if layered_texture_count > 0:
  161. for j in range(layered_texture_count):
  162. layered_texture = material_property.GetSrcObject(FbxLayeredTexture.ClassId, j)
  163. texture_count = layered_texture.GetSrcObjectCount(FbxTexture.ClassId)
  164. for k in range(texture_count):
  165. texture = layered_texture.GetSrcObject(FbxTexture.ClassId,k)
  166. if texture:
  167. texture_id = getTextureName(texture, True)
  168. texture_binding = ' "%s": "%s",' % (binding_types[str(material_property.GetName())], texture_id)
  169. texture_list.append(texture_binding)
  170. else:
  171. # no layered texture simply get on the property
  172. texture_count = material_property.GetSrcObjectCount(FbxTexture.ClassId)
  173. for j in range(texture_count):
  174. texture = material_property.GetSrcObject(FbxTexture.ClassId,j)
  175. if texture:
  176. texture_id = getTextureName(texture, True)
  177. texture_binding = ' "%s": "%s",' % (binding_types[str(material_property.GetName())], texture_id)
  178. texture_list.append(texture_binding)
  179. def generate_material_string(material):
  180. #Get the implementation to see if it's a hardware shader.
  181. implementation = GetImplementation(material, "ImplementationHLSL")
  182. implementation_type = "HLSL"
  183. if not implementation:
  184. implementation = GetImplementation(material, "ImplementationCGFX")
  185. implementation_type = "CGFX"
  186. output = []
  187. if implementation:
  188. # This material is a hardware shader, skip it
  189. print("Shader materials are not supported")
  190. return ''
  191. elif material.GetClassId().Is(FbxSurfaceLambert.ClassId):
  192. ambient = str(getHex(material.Ambient.Get()))
  193. diffuse = str(getHex(material.Diffuse.Get()))
  194. emissive = str(getHex(material.Emissive.Get()))
  195. opacity = 1.0 - material.TransparencyFactor.Get()
  196. opacity = 1.0 if opacity == 0 else opacity
  197. opacity = str(opacity)
  198. transparent = BoolString(False)
  199. reflectivity = "1"
  200. output = [
  201. '\t' + LabelString( getMaterialName( material ) ) + ': {',
  202. ' "type" : "MeshLambertMaterial",',
  203. ' "parameters" : {',
  204. ' "color" : ' + diffuse + ',',
  205. ' "ambient" : ' + ambient + ',',
  206. ' "emissive" : ' + emissive + ',',
  207. ' "reflectivity" : ' + reflectivity + ',',
  208. ' "transparent" : ' + transparent + ',',
  209. ' "opacity" : ' + opacity + ',',
  210. ]
  211. elif material.GetClassId().Is(FbxSurfacePhong.ClassId):
  212. ambient = str(getHex(material.Ambient.Get()))
  213. diffuse = str(getHex(material.Diffuse.Get()))
  214. emissive = str(getHex(material.Emissive.Get()))
  215. specular = str(getHex(material.Specular.Get()))
  216. opacity = 1.0 - material.TransparencyFactor.Get()
  217. opacity = 1.0 if opacity == 0 else opacity
  218. opacity = str(opacity)
  219. shininess = str(material.Shininess.Get())
  220. transparent = BoolString(False)
  221. reflectivity = "1"
  222. bumpScale = "1"
  223. output = [
  224. '\t' + LabelString( getMaterialName( material ) ) + ': {',
  225. ' "type" : "MeshPhongMaterial",',
  226. ' "parameters" : {',
  227. ' "color" : ' + diffuse + ',',
  228. ' "ambient" : ' + ambient + ',',
  229. ' "emissive" : ' + emissive + ',',
  230. ' "specular" : ' + specular + ',',
  231. ' "shininess" : ' + shininess + ',',
  232. ' "bumpScale" : ' + bumpScale + ',',
  233. ' "reflectivity" : ' + reflectivity + ',',
  234. ' "transparent" : ' + transparent + ',',
  235. ' "opacity" : ' + opacity + ',',
  236. ]
  237. else:
  238. print("Unknown type of Material")
  239. return ''
  240. if option_textures:
  241. texture_list = []
  242. texture_count = FbxLayerElement.sTypeTextureCount()
  243. for texture_index in range(texture_count):
  244. material_property = material.FindProperty(FbxLayerElement.sTextureChannelNames(texture_index))
  245. generate_texture_bindings(material_property, texture_list)
  246. output += texture_list
  247. wireframe = BoolString(False)
  248. wireframeLinewidth = "1"
  249. output.append(' "wireframe" : ' + wireframe + ',')
  250. output.append(' "wireframeLinewidth" : ' + wireframeLinewidth)
  251. output.append(' }')
  252. output.append('}')
  253. return generateMultiLineString( output, '\n\t\t', 0 )
  254. def generate_proxy_material_string(node, material_names):
  255. output = [
  256. '\t' + LabelString( getMaterialName( node, True ) ) + ': {',
  257. ' "type" : "MeshFaceMaterial",',
  258. ' "parameters" : {',
  259. ' "materials" : ' + ArrayString( ",".join(LabelString(m) for m in material_names) ),
  260. ' }',
  261. '}'
  262. ]
  263. return generateMultiLineString( output, '\n\t\t', 0 )
  264. # #####################################################
  265. # Parse - Materials
  266. # #####################################################
  267. def extract_materials_from_node(node, material_list):
  268. name = node.GetName()
  269. mesh = node.GetNodeAttribute()
  270. node = None
  271. if mesh:
  272. node = mesh.GetNode()
  273. if node:
  274. material_count = node.GetMaterialCount()
  275. material_names = []
  276. for l in range(mesh.GetLayerCount()):
  277. materials = mesh.GetLayer(l).GetMaterials()
  278. if materials:
  279. if materials.GetReferenceMode() == FbxLayerElement.eIndex:
  280. #Materials are in an undefined external table
  281. continue
  282. for i in range(material_count):
  283. material = node.GetMaterial(i)
  284. material_names.append(getMaterialName(material))
  285. material_string = generate_material_string(material)
  286. material_list.append(material_string)
  287. if material_count > 1:
  288. proxy_material = generate_proxy_material_string(node, material_names)
  289. material_list.append(proxy_material)
  290. def generate_materials_from_hierarchy(node, material_list):
  291. if node.GetNodeAttribute() == None:
  292. pass
  293. else:
  294. attribute_type = (node.GetNodeAttribute().GetAttributeType())
  295. if attribute_type == FbxNodeAttribute.eMesh:
  296. extract_materials_from_node(node, material_list)
  297. for i in range(node.GetChildCount()):
  298. generate_materials_from_hierarchy(node.GetChild(i), material_list)
  299. def generate_material_list(scene):
  300. material_list = []
  301. node = scene.GetRootNode()
  302. if node:
  303. for i in range(node.GetChildCount()):
  304. generate_materials_from_hierarchy(node.GetChild(i), material_list)
  305. return material_list
  306. # #####################################################
  307. # Generate - Texture String
  308. # #####################################################
  309. def generate_texture_string(texture):
  310. #TODO: extract more texture properties
  311. wrap_u = texture.GetWrapModeU()
  312. wrap_v = texture.GetWrapModeV()
  313. offset = texture.GetUVTranslation()
  314. output = [
  315. '\t' + LabelString( getTextureName( texture, True ) ) + ': {',
  316. ' "url" : "' + texture.GetFileName() + '",',
  317. ' "repeat" : ' + Vector2String( (1,1) ) + ',',
  318. ' "offset" : ' + Vector2String( texture.GetUVTranslation() ) + ',',
  319. ' "magFilter" : ' + LabelString( "LinearFilter" ) + ',',
  320. ' "minFilter" : ' + LabelString( "LinearMipMapLinearFilter" ) + ',',
  321. ' "anisotropy" : ' + BoolString( True ),
  322. '}'
  323. ]
  324. return generateMultiLineString( output, '\n\t\t', 0 )
  325. # #####################################################
  326. # Parse - Textures
  327. # #####################################################
  328. def extract_material_textures(material_property, texture_list):
  329. if material_property.IsValid():
  330. #Here we have to check if it's layeredtextures, or just textures:
  331. layered_texture_count = material_property.GetSrcObjectCount(FbxLayeredTexture.ClassId)
  332. if layered_texture_count > 0:
  333. for j in range(layered_texture_count):
  334. layered_texture = material_property.GetSrcObject(FbxLayeredTexture.ClassId, j)
  335. texture_count = layered_texture.GetSrcObjectCount(FbxTexture.ClassId)
  336. for k in range(texture_count):
  337. texture = layered_texture.GetSrcObject(FbxTexture.ClassId,k)
  338. if texture:
  339. texture_string = generate_texture_string(texture)
  340. texture_list.append(texture_string)
  341. else:
  342. # no layered texture simply get on the property
  343. texture_count = material_property.GetSrcObjectCount(FbxTexture.ClassId)
  344. for j in range(texture_count):
  345. texture = material_property.GetSrcObject(FbxTexture.ClassId,j)
  346. if texture:
  347. texture_string = generate_texture_string(texture)
  348. texture_list.append(texture_string)
  349. def extract_textures_from_node(node, texture_list):
  350. name = node.GetName()
  351. mesh = node.GetNodeAttribute()
  352. #for all materials attached to this mesh
  353. material_count = mesh.GetNode().GetSrcObjectCount(FbxSurfaceMaterial.ClassId)
  354. for material_index in range(material_count):
  355. material = mesh.GetNode().GetSrcObject(FbxSurfaceMaterial.ClassId, material_index)
  356. #go through all the possible textures types
  357. if material:
  358. texture_count = FbxLayerElement.sTypeTextureCount()
  359. for texture_index in range(texture_count):
  360. material_property = material.FindProperty(FbxLayerElement.sTextureChannelNames(texture_index))
  361. extract_material_textures(material_property, texture_list)
  362. def generate_textures_from_hierarchy(node, texture_list):
  363. if node.GetNodeAttribute() == None:
  364. pass
  365. else:
  366. attribute_type = (node.GetNodeAttribute().GetAttributeType())
  367. if attribute_type == FbxNodeAttribute.eMesh:
  368. extract_textures_from_node(node, texture_list)
  369. for i in range(node.GetChildCount()):
  370. generate_textures_from_hierarchy(node.GetChild(i), texture_list)
  371. def generate_texture_list(scene):
  372. if not option_textures:
  373. return []
  374. texture_list = []
  375. node = scene.GetRootNode()
  376. if node:
  377. for i in range(node.GetChildCount()):
  378. generate_textures_from_hierarchy(node.GetChild(i), texture_list)
  379. return texture_list
  380. # #####################################################
  381. # Extract - Fbx Mesh data
  382. # #####################################################
  383. def extract_fbx_vertex_positions(mesh):
  384. control_points_count = mesh.GetControlPointsCount()
  385. control_points = mesh.GetControlPoints()
  386. positions = []
  387. for i in range(control_points_count):
  388. positions.append(convert_fbx_vec3(control_points[i]))
  389. return positions
  390. def extract_fbx_vertex_normals(mesh):
  391. # eNone The mapping is undetermined.
  392. # eByControlPoint There will be one mapping coordinate for each surface control point/vertex.
  393. # eByPolygonVertex There will be one mapping coordinate for each vertex, for every polygon of which it is a part. This means that a vertex will have as many mapping coordinates as polygons of which it is a part.
  394. # eByPolygon There can be only one mapping coordinate for the whole polygon.
  395. # eByEdge There will be one mapping coordinate for each unique edge in the mesh. This is meant to be used with smoothing layer elements.
  396. # eAllSame There can be only one mapping coordinate for the whole surface.
  397. layered_normal_indices = []
  398. layered_normal_values = []
  399. poly_count = mesh.GetPolygonCount()
  400. control_points = mesh.GetControlPoints()
  401. for l in range(mesh.GetLayerCount()):
  402. mesh_normals = mesh.GetLayer(l).GetNormals()
  403. if not mesh_normals:
  404. continue
  405. normals_array = mesh_normals.GetDirectArray()
  406. normals_count = normals_array.GetCount()
  407. if normals_count == 0:
  408. continue
  409. normal_indices = []
  410. normal_values = []
  411. # values
  412. for i in range(normals_count):
  413. normal = convert_fbx_vec3(normals_array.GetAt(i))
  414. normal_values.append(normal)
  415. # indices
  416. vertexId = 0
  417. for p in range(poly_count):
  418. poly_size = mesh.GetPolygonSize(p)
  419. poly_normals = []
  420. for v in range(poly_size):
  421. control_point_index = mesh.GetPolygonVertex(p, v)
  422. if mesh_normals.GetMappingMode() == FbxLayerElement.eByControlPoint:
  423. if mesh_normals.GetReferenceMode() == FbxLayerElement.eDirect:
  424. poly_normals.append(control_point_index)
  425. elif mesh_normals.GetReferenceMode() == FbxLayerElement.eIndexToDirect:
  426. index = mesh_normals.GetIndexArray().GetAt(control_point_index)
  427. poly_normals.append(index)
  428. elif mesh_normals.GetMappingMode() == FbxLayerElement.eByPolygonVertex:
  429. if mesh_normals.GetReferenceMode() == FbxLayerElement.eDirect:
  430. poly_normals.append(vertexId)
  431. elif mesh_normals.GetReferenceMode() == FbxLayerElement.eIndexToDirect:
  432. index = mesh_normals.GetIndexArray().GetAt(vertexId)
  433. poly_normals.append(index)
  434. elif mesh_normals.GetMappingMode() == FbxLayerElement.eByPolygon or \
  435. mesh_normals.GetMappingMode() == FbxLayerElement.eAllSame or \
  436. mesh_normals.GetMappingMode() == FbxLayerElement.eNone:
  437. print("unsupported normal mapping mode for polygon vertex")
  438. vertexId += 1
  439. normal_indices.append(poly_normals)
  440. layered_normal_values.append(normal_values)
  441. layered_normal_indices.append(normal_indices)
  442. normal_values = []
  443. normal_indices = []
  444. # Three.js only supports one layer of normals
  445. if len(layered_normal_values) > 0:
  446. normal_values = layered_normal_values[0]
  447. normal_indices = layered_normal_indices[0]
  448. return normal_values, normal_indices
  449. def extract_fbx_vertex_colors(mesh):
  450. # eNone The mapping is undetermined.
  451. # eByControlPoint There will be one mapping coordinate for each surface control point/vertex.
  452. # eByPolygonVertex There will be one mapping coordinate for each vertex, for every polygon of which it is a part. This means that a vertex will have as many mapping coordinates as polygons of which it is a part.
  453. # eByPolygon There can be only one mapping coordinate for the whole polygon.
  454. # eByEdge There will be one mapping coordinate for each unique edge in the mesh. This is meant to be used with smoothing layer elements.
  455. # eAllSame There can be only one mapping coordinate for the whole surface.
  456. layered_color_indices = []
  457. layered_color_values = []
  458. poly_count = mesh.GetPolygonCount()
  459. control_points = mesh.GetControlPoints()
  460. for l in range(mesh.GetLayerCount()):
  461. mesh_colors = mesh.GetLayer(l).GetVertexColors()
  462. if not mesh_colors:
  463. continue
  464. colors_array = mesh_colors.GetDirectArray()
  465. colors_count = colors_array.GetCount()
  466. if colors_count == 0:
  467. continue
  468. color_indices = []
  469. color_values = []
  470. # values
  471. for i in range(colors_count):
  472. color = convert_fbx_color(colors_array.GetAt(i))
  473. color_values.append(color)
  474. # indices
  475. vertexId = 0
  476. for p in range(poly_count):
  477. poly_size = mesh.GetPolygonSize(p)
  478. poly_colors = []
  479. for v in range(poly_size):
  480. control_point_index = mesh.GetPolygonVertex(p, v)
  481. if mesh_colors.GetMappingMode() == FbxLayerElement.eByControlPoint:
  482. if mesh_colors.GetReferenceMode() == FbxLayerElement.eDirect:
  483. poly_colors.append(control_point_index)
  484. elif mesh_colors.GetReferenceMode() == FbxLayerElement.eIndexToDirect:
  485. index = mesh_colors.GetIndexArray().GetAt(control_point_index)
  486. poly_colors.append(index)
  487. elif mesh_colors.GetMappingMode() == FbxLayerElement.eByPolygonVertex:
  488. if mesh_colors.GetReferenceMode() == FbxLayerElement.eDirect:
  489. poly_colors.append(vertexId)
  490. elif mesh_colors.GetReferenceMode() == FbxLayerElement.eIndexToDirect:
  491. index = mesh_colors.GetIndexArray().GetAt(vertexId)
  492. poly_colors.append(index)
  493. elif mesh_colors.GetMappingMode() == FbxLayerElement.eByPolygon or \
  494. mesh_colors.GetMappingMode() == FbxLayerElement.eAllSame or \
  495. mesh_colors.GetMappingMode() == FbxLayerElement.eNone:
  496. print("unsupported color mapping mode for polygon vertex")
  497. vertexId += 1
  498. color_indices.append(poly_colors)
  499. color_values = []
  500. color_indices = []
  501. # Three.js only supports one layer of colors
  502. if len(layered_color_values) > 0:
  503. color_values = layered_color_values[0]
  504. color_indices = layered_color_indices[0]
  505. return color_values, color_indices
  506. def extract_fbx_vertex_uvs(mesh):
  507. # eNone The mapping is undetermined.
  508. # eByControlPoint There will be one mapping coordinate for each surface control point/vertex.
  509. # eByPolygonVertex There will be one mapping coordinate for each vertex, for every polygon of which it is a part. This means that a vertex will have as many mapping coordinates as polygons of which it is a part.
  510. # eByPolygon There can be only one mapping coordinate for the whole polygon.
  511. # eByEdge There will be one mapping coordinate for each unique edge in the mesh. This is meant to be used with smoothing layer elements.
  512. # eAllSame There can be only one mapping coordinate for the whole surface.
  513. layered_uv_indices = []
  514. layered_uv_values = []
  515. poly_count = mesh.GetPolygonCount()
  516. control_points = mesh.GetControlPoints()
  517. for l in range(mesh.GetLayerCount()):
  518. mesh_uvs = mesh.GetLayer(l).GetUVs()
  519. if not mesh_uvs:
  520. continue
  521. uvs_array = mesh_uvs.GetDirectArray()
  522. uvs_count = uvs_array.GetCount()
  523. if uvs_count == 0:
  524. continue
  525. uv_indices = []
  526. uv_values = []
  527. # values
  528. for i in range(uvs_count):
  529. uv = convert_fbx_vec2(uvs_array.GetAt(i))
  530. uv_values.append(uv)
  531. # indices
  532. vertexId = 0
  533. for p in range(poly_count):
  534. poly_size = mesh.GetPolygonSize(p)
  535. poly_uvs = []
  536. for v in range(poly_size):
  537. control_point_index = mesh.GetPolygonVertex(p, v)
  538. if mesh_uvs.GetMappingMode() == FbxLayerElement.eByControlPoint:
  539. if mesh_uvs.GetReferenceMode() == FbxLayerElement.eDirect:
  540. poly_uvs.append(control_point_index)
  541. elif mesh_uvs.GetReferenceMode() == FbxLayerElement.eIndexToDirect:
  542. index = mesh_uvs.GetIndexArray().GetAt(control_point_index)
  543. poly_uvs.append(index)
  544. elif mesh_uvs.GetMappingMode() == FbxLayerElement.eByPolygonVertex:
  545. uv_texture_index = mesh.GetTextureUVIndex(p, v)
  546. if mesh_uvs.GetReferenceMode() == FbxLayerElement.eDirect or \
  547. mesh_uvs.GetReferenceMode() == FbxLayerElement.eIndexToDirect:
  548. poly_uvs.append(uv_texture_index)
  549. elif mesh_uvs.GetMappingMode() == FbxLayerElement.eByPolygon or \
  550. mesh_uvs.GetMappingMode() == FbxLayerElement.eAllSame or \
  551. mesh_uvs.GetMappingMode() == FbxLayerElement.eNone:
  552. print("unsupported uv mapping mode for polygon vertex")
  553. vertexId += 1
  554. uv_indices.append(poly_uvs)
  555. layered_uv_values.append(uv_values)
  556. layered_uv_indices.append(uv_indices)
  557. return layered_uv_values, layered_uv_indices
  558. # #####################################################
  559. # Generate - Mesh String
  560. # #####################################################
  561. def generate_mesh_bounding_box(mesh):
  562. control_points_count = mesh.GetControlPointsCount()
  563. control_points = mesh.GetControlPoints()
  564. minx = 0
  565. miny = 0
  566. minz = 0
  567. maxx = 0
  568. maxy = 0
  569. maxz = 0
  570. for i in range(control_points_count):
  571. vertex = control_points[i]
  572. if vertex[0] < minx:
  573. minx = vertex[0]
  574. if vertex[1] < miny:
  575. miny = vertex[1]
  576. if vertex[2] < minz:
  577. minz = vertex[2]
  578. if vertex[0] > maxx:
  579. maxx = vertex[0]
  580. if vertex[1] > maxy:
  581. maxy = vertex[1]
  582. if vertex[2] > maxz:
  583. maxz = vertex[2]
  584. return [minx, miny, minz], [maxx, maxy, maxz]
  585. def generate_scene_mesh_string(node):
  586. mesh = node.GetNodeAttribute()
  587. mesh_list = [ mesh ]
  588. # These functions merge multiple meshes into one
  589. vertices, vertex_offsets = process_mesh_vertices(mesh_list)
  590. materials, material_offsets = process_mesh_materials(mesh_list)
  591. # These functions merge meshes and remove duplicate data
  592. normal_values, normal_indices = process_mesh_normals(mesh_list)
  593. color_values, color_indices = process_mesh_colors(mesh_list)
  594. uv_values, uv_indices = process_mesh_uv_layers(mesh_list)
  595. faces = process_mesh_polygons(mesh_list, normal_indices, color_indices, uv_indices, vertex_offsets, material_offsets)
  596. nuvs = []
  597. for layer_index, uvs in enumerate(uv_values):
  598. nuvs.append(str(len(uvs)))
  599. nvertices = len(vertices)
  600. nnormals = len(normal_values)
  601. ncolors = len(color_values)
  602. nfaces = len(faces)
  603. nuvs = ",".join(nuvs)
  604. vertices = ",".join(Vector3String(v, True) for v in vertices)
  605. normals = ",".join(Vector3String(v, True) for v in normal_values)
  606. colors = ",".join(Vector3String(v, True) for v in color_values)
  607. faces = ",".join(faces)
  608. uvs = generate_uvs(uv_values)
  609. #TODO: this should take in the vertices array
  610. aabb_min, aabb_max = generate_mesh_bounding_box(mesh)
  611. aabb_min = ",".join(str(f) for f in aabb_min)
  612. aabb_max = ",".join(str(f) for f in aabb_max)
  613. output = [
  614. '\t' + LabelString( getEmbedName( node, True ) ) + ' : {',
  615. ' "metadata" : {',
  616. ' "vertices" : ' + str(nvertices) + ',',
  617. ' "normals" : ' + str(nnormals) + ',',
  618. ' "colors" : ' + str(ncolors) + ',',
  619. ' "faces" : ' + str(nfaces) + ',',
  620. ' "uvs" : ' + ArrayString(nuvs),
  621. ' },',
  622. ' "boundingBox" : {',
  623. ' "min" : ' + ArrayString(aabb_min) + ',',
  624. ' "max" : ' + ArrayString(aabb_max),
  625. ' },',
  626. ' "scale" : ' + str( 1 ) + ',',
  627. ' "materials" : ' + ArrayString("") + ',',
  628. ' "vertices" : ' + ArrayString(vertices) + ',',
  629. ' "normals" : ' + ArrayString(normals) + ',',
  630. ' "colors" : ' + ArrayString(colors) + ',',
  631. ' "uvs" : ' + ArrayString(uvs) + ',',
  632. ' "faces" : ' + ArrayString(faces),
  633. '}'
  634. ]
  635. return generateMultiLineString( output, '\n\t\t', 0 )
  636. # #####################################################
  637. # Process - Mesh Geometry
  638. # #####################################################
  639. def generate_normal_key(normal):
  640. return (round(normal[0], 6), round(normal[1], 6), round(normal[2], 6))
  641. def generate_color_key(color):
  642. return getHex(color)
  643. def generate_uv_key(uv):
  644. return (round(uv[0], 6), round(uv[1], 6))
  645. def append_non_duplicate_normals(source_normals, dest_normals, count):
  646. for normal in source_normals:
  647. key = generate_normal_key(normal)
  648. if key not in dest_normals:
  649. dest_normals[key] = count
  650. count += 1
  651. return count
  652. def append_non_duplicate_colors(source_colors, dest_colors, count):
  653. for color in source_colors:
  654. key = generate_color_key(color)
  655. if key not in dest_colors:
  656. dest_colors[key] = count
  657. count += 1
  658. return count
  659. def append_non_duplicate_uvs(source_uvs, dest_uvs, counts):
  660. source_layer_count = len(source_uvs)
  661. for layer_index in range(source_layer_count):
  662. dest_layer_count = len(dest_uvs)
  663. if dest_layer_count <= layer_index:
  664. dest_uv_layer = {}
  665. count = 0
  666. dest_uvs.append(dest_uv_layer)
  667. counts.append(count)
  668. else:
  669. dest_uv_layer = dest_uvs[layer_index]
  670. count = nuvs[layer_index]
  671. source_uv_layer = source_uvs[layer_index]
  672. for uv in source_uv_layer:
  673. key = generate_uv_key(uv)
  674. if key not in dest_uv_layer:
  675. dest_uv_layer[key] = count
  676. count += 1
  677. counts[layer_index] = count
  678. return counts
  679. def process_mesh_normals(mesh_list):
  680. normals_dictionary = {}
  681. nnormals = 0
  682. # Merge meshes, remove duplicate data
  683. for mesh in mesh_list:
  684. normal_values, normal_indices = extract_fbx_vertex_normals(mesh)
  685. # Remove the Fbx indices, we will make our own
  686. mesh_normals = []
  687. for poly in normal_indices:
  688. for index in poly:
  689. mesh_normals.append(normal_values[index])
  690. if len(mesh_normals) > 0:
  691. nnormals = append_non_duplicate_normals(mesh_normals, normals_dictionary, nnormals)
  692. # Build index list
  693. merged_normal_indices = []
  694. for mesh in mesh_list:
  695. normal_values, normal_indices = extract_fbx_vertex_normals(mesh)
  696. for source_poly in normal_indices:
  697. dest_poly = []
  698. for source_index in source_poly:
  699. normal = normal_values[source_index]
  700. key = generate_normal_key(normal)
  701. dest_index = normals_dictionary[key]
  702. dest_poly.append(dest_index)
  703. merged_normal_indices.append(dest_poly)
  704. # Build values array
  705. merged_normal_values = []
  706. for key, index in sorted(normals_dictionary.items(), key = operator.itemgetter(1)):
  707. merged_normal_values.append(key)
  708. return merged_normal_values, merged_normal_indices
  709. def process_mesh_colors(mesh_list):
  710. colors_dictionary = {}
  711. ncolors = 0
  712. # Merge meshes, remove duplicate data
  713. for mesh in mesh_list:
  714. color_values, color_indices = extract_fbx_vertex_colors(mesh)
  715. # Remove the Fbx indices, we will make our own
  716. mesh_colors = []
  717. for poly in color_indices:
  718. for index in poly:
  719. mesh_colors.append(color_values[index])
  720. if len(mesh_colors) > 0:
  721. ncolors = append_non_duplicate_colors(mesh_colors, colors_dictionary, ncolors)
  722. # Build index list
  723. merged_color_indices = []
  724. for mesh in mesh_list:
  725. color_values, color_indices = extract_fbx_vertex_colors(mesh)
  726. for source_poly in color_indices:
  727. dest_poly = []
  728. for source_index in source_poly:
  729. color = color_values[source_index]
  730. key = generate_color_key(color)
  731. dest_index = colors_dictionary[key]
  732. dest_poly.append(dest_index)
  733. merged_color_indices.append(dest_poly)
  734. # Build values array
  735. merged_color_values = []
  736. for key, index in sorted(colors_dictionary.items(), key = operator.itemgetter(1)):
  737. merged_color_values.append(key)
  738. return merged_color_values, merged_color_indices
  739. def process_mesh_uv_layers(mesh_list):
  740. uvs_dictionary_layers = []
  741. nuvs_list = []
  742. # Merge meshes, remove duplicate data
  743. for mesh in mesh_list:
  744. uv_values, uv_indices = extract_fbx_vertex_uvs(mesh)
  745. # Remove the Fbx indices, we will make our own
  746. mesh_uvs = []
  747. for l in range(len(uv_indices)):
  748. dest_uv_indices_layer = []
  749. source_uv_values_layer = uv_values[l]
  750. source_uv_indices_layer = uv_indices[l]
  751. for source_poly in source_uv_indices_layer:
  752. for source_index in source_poly:
  753. dest_uv_indices_layer.append(source_uv_values_layer[source_index])
  754. mesh_uvs.append(dest_uv_indices_layer)
  755. if len(mesh_uvs) > 0:
  756. nuvs_list = append_non_duplicate_uvs(mesh_uvs, uvs_dictionary_layers, nuvs_list)
  757. # Build index list
  758. merged_uv_indices = []
  759. for mesh in mesh_list:
  760. uv_values, uv_indices = extract_fbx_vertex_uvs(mesh)
  761. for layer_index in range(len(uv_indices)):
  762. dest_uv_indices_layer = []
  763. source_uv_values_layer = uv_values[layer_index]
  764. source_uv_indices_layer = uv_indices[layer_index]
  765. uvs_dictionary = uvs_dictionary_layers[layer_index]
  766. for source_poly in source_uv_indices_layer:
  767. dest_poly = []
  768. for source_index in source_poly:
  769. uv = source_uv_values_layer[source_index]
  770. key = generate_uv_key(uv)
  771. dest_index = uvs_dictionary[key]
  772. dest_poly.append(dest_index)
  773. dest_uv_indices_layer.append(dest_poly)
  774. merged_uv_indices.append(dest_uv_indices_layer)
  775. # Build values array
  776. merged_uv_values = []
  777. for uvs_dictionary in uvs_dictionary_layers:
  778. merged_uv_values_layer = []
  779. for key, index in sorted(uvs_dictionary.items(), key = operator.itemgetter(1)):
  780. merged_uv_values_layer.append(key)
  781. merged_uv_values.append(merged_uv_values_layer)
  782. return merged_uv_values, merged_uv_indices
  783. def process_mesh_vertices(mesh_list):
  784. vertex_offset = 0
  785. vertex_offset_list = [0]
  786. vertices = []
  787. for mesh in mesh_list:
  788. node = mesh.GetNode()
  789. mesh_vertices = extract_fbx_vertex_positions(mesh)
  790. if option_geometry:
  791. # FbxMeshes are local to their node, we need the vertices in global space
  792. # when scene nodes are not exported
  793. transform = node.EvaluateGlobalTransform()
  794. transform = FbxMatrix(transform)
  795. for i in range(len(mesh_vertices)):
  796. v = mesh_vertices[i]
  797. position = FbxVector4(v[0], v[1], v[2])
  798. position = transform.MultNormalize(position)
  799. mesh_vertices[i] = convert_fbx_vec3(position)
  800. vertices.extend(mesh_vertices[:])
  801. vertex_offset += len(mesh_vertices)
  802. vertex_offset_list.append(vertex_offset)
  803. return vertices, vertex_offset_list
  804. def process_mesh_materials(mesh_list):
  805. material_offset = 0
  806. material_offset_list = [0]
  807. materials_list = []
  808. #TODO: remove duplicate mesh references
  809. for mesh in mesh_list:
  810. node = mesh.GetNode()
  811. material_count = node.GetMaterialCount()
  812. if material_count > 0:
  813. for l in range(mesh.GetLayerCount()):
  814. materials = mesh.GetLayer(l).GetMaterials()
  815. if materials:
  816. if materials.GetReferenceMode() == FbxLayerElement.eIndex:
  817. #Materials are in an undefined external table
  818. continue
  819. for i in range(material_count):
  820. material = node.GetMaterial(i)
  821. materials_list.append( material )
  822. material_offset += material_count
  823. material_offset_list.append(material_offset)
  824. return materials_list, material_offset_list
  825. def process_mesh_polygons(mesh_list, normals, colors, uv_layers, vertex_offset_list, material_offset_list):
  826. faces = []
  827. for mesh_index in range(len(mesh_list)):
  828. mesh = mesh_list[mesh_index]
  829. poly_count = mesh.GetPolygonCount()
  830. control_points = mesh.GetControlPoints()
  831. for poly_index in range(poly_count):
  832. poly_size = mesh.GetPolygonSize(poly_index)
  833. vertex_indices = []
  834. for vertex_index in range(poly_size):
  835. control_point_index = mesh.GetPolygonVertex(poly_index, vertex_index)
  836. vertex_indices.append(control_point_index)
  837. vertex_offset = vertex_offset_list[mesh_index]
  838. material_offset = material_offset_list[mesh_index]
  839. face = generate_mesh_face(mesh,
  840. poly_index,
  841. vertex_indices,
  842. normals, colors,
  843. uv_layers,
  844. vertex_offset,
  845. material_offset)
  846. faces.append(face)
  847. return faces
  848. def generate_mesh_face(mesh, polygon_index, vertex_indices, normals, colors, uv_layers, vertex_offset, material_offset):
  849. isTriangle = ( len(vertex_indices) == 3 )
  850. nVertices = 3 if isTriangle else 4
  851. hasMaterial = False
  852. for l in range(mesh.GetLayerCount()):
  853. materials = mesh.GetLayer(l).GetMaterials()
  854. if materials:
  855. hasMaterial = True
  856. break
  857. hasFaceUvs = False
  858. hasFaceVertexUvs = len(uv_layers) > 0
  859. hasFaceNormals = False
  860. hasFaceVertexNormals = len(normals) > 0
  861. hasFaceColors = False
  862. hasFaceVertexColors = len(colors) > 0
  863. faceType = 0
  864. faceType = setBit(faceType, 0, not isTriangle)
  865. faceType = setBit(faceType, 1, hasMaterial)
  866. faceType = setBit(faceType, 2, hasFaceUvs)
  867. faceType = setBit(faceType, 3, hasFaceVertexUvs)
  868. faceType = setBit(faceType, 4, hasFaceNormals)
  869. faceType = setBit(faceType, 5, hasFaceVertexNormals)
  870. faceType = setBit(faceType, 6, hasFaceColors)
  871. faceType = setBit(faceType, 7, hasFaceVertexColors)
  872. faceData = []
  873. # order is important, must match order in JSONLoader
  874. # face type
  875. # vertex indices
  876. # material index
  877. # face uvs index
  878. # face vertex uvs indices
  879. # face color index
  880. # face vertex colors indices
  881. faceData.append(faceType)
  882. for i in range(nVertices):
  883. index = vertex_indices[i] + vertex_offset
  884. faceData.append(index)
  885. if hasMaterial:
  886. material_id = 0
  887. for l in range(mesh.GetLayerCount()):
  888. materials = mesh.GetLayer(l).GetMaterials()
  889. if materials:
  890. material_id = materials.GetIndexArray().GetAt(polygon_index)
  891. break
  892. material_id += material_offset
  893. faceData.append( material_id )
  894. if hasFaceVertexUvs:
  895. for layer_index, uvs in enumerate(uv_layers):
  896. polygon_uvs = uvs[polygon_index]
  897. for i in range(nVertices):
  898. index = polygon_uvs[i]
  899. faceData.append(index)
  900. if hasFaceVertexNormals:
  901. polygon_normals = normals[polygon_index]
  902. for i in range(nVertices):
  903. index = polygon_normals[i]
  904. faceData.append(index)
  905. if hasFaceVertexColors:
  906. polygon_colors = colors[polygon_index]
  907. for i in range(nVertices):
  908. index = polygon_colors[i]
  909. faceData.append(index)
  910. return ",".join( map(str, faceData) )
  911. # #####################################################
  912. # Generate - Mesh List
  913. # #####################################################
  914. def generate_mesh_list_from_hierarchy(node, mesh_list):
  915. if node.GetNodeAttribute() == None:
  916. pass
  917. else:
  918. attribute_type = (node.GetNodeAttribute().GetAttributeType())
  919. if attribute_type == FbxNodeAttribute.eMesh or \
  920. attribute_type == FbxNodeAttribute.eNurbs or \
  921. attribute_type == FbxNodeAttribute.eNurbsSurface or \
  922. attribute_type == FbxNodeAttribute.ePatch:
  923. if attribute_type != FbxNodeAttribute.eMesh:
  924. converter.TriangulateInPlace(node);
  925. mesh_list.append(node)
  926. for i in range(node.GetChildCount()):
  927. generate_embed_list_from_hierarchy(node.GetChild(i), mesh_list)
  928. def generate_mesh_list(scene):
  929. mesh_list = []
  930. node = scene.GetRootNode()
  931. if node:
  932. for i in range(node.GetChildCount()):
  933. generate_mesh_list_from_hierarchy(node.GetChild(i), mesh_list)
  934. return embed_list
  935. # #####################################################
  936. # Generate - Embeds
  937. # #####################################################
  938. def generate_embed_list_from_hierarchy(node, embed_list):
  939. if node.GetNodeAttribute() == None:
  940. pass
  941. else:
  942. attribute_type = (node.GetNodeAttribute().GetAttributeType())
  943. if attribute_type == FbxNodeAttribute.eMesh or \
  944. attribute_type == FbxNodeAttribute.eNurbs or \
  945. attribute_type == FbxNodeAttribute.eNurbsSurface or \
  946. attribute_type == FbxNodeAttribute.ePatch:
  947. if attribute_type != FbxNodeAttribute.eMesh:
  948. converter.TriangulateInPlace(node);
  949. embed_string = generate_scene_mesh_string(node)
  950. embed_list.append(embed_string)
  951. for i in range(node.GetChildCount()):
  952. generate_embed_list_from_hierarchy(node.GetChild(i), embed_list)
  953. def generate_embed_list(scene):
  954. embed_list = []
  955. node = scene.GetRootNode()
  956. if node:
  957. for i in range(node.GetChildCount()):
  958. generate_embed_list_from_hierarchy(node.GetChild(i), embed_list)
  959. return embed_list
  960. # #####################################################
  961. # Generate - Geometries
  962. # #####################################################
  963. def generate_geometry_string(node):
  964. output = [
  965. '\t' + LabelString( getGeometryName( node, True ) ) + ' : {',
  966. ' "type" : "embedded",',
  967. ' "id" : ' + LabelString( getEmbedName( node, True ) ),
  968. '}'
  969. ]
  970. return generateMultiLineString( output, '\n\t\t', 0 )
  971. def generate_geometry_list_from_hierarchy(node, geometry_list):
  972. if node.GetNodeAttribute() == None:
  973. pass
  974. else:
  975. attribute_type = (node.GetNodeAttribute().GetAttributeType())
  976. if attribute_type == FbxNodeAttribute.eMesh:
  977. geometry_string = generate_geometry_string(node)
  978. geometry_list.append(geometry_string)
  979. for i in range(node.GetChildCount()):
  980. generate_geometry_list_from_hierarchy(node.GetChild(i), geometry_list)
  981. def generate_geometry_list(scene):
  982. geometry_list = []
  983. node = scene.GetRootNode()
  984. if node:
  985. for i in range(node.GetChildCount()):
  986. generate_geometry_list_from_hierarchy(node.GetChild(i), geometry_list)
  987. return geometry_list
  988. # #####################################################
  989. # Generate - Camera Names
  990. # #####################################################
  991. def generate_camera_name_list_from_hierarchy(node, camera_list):
  992. if node.GetNodeAttribute() == None:
  993. pass
  994. else:
  995. attribute_type = (node.GetNodeAttribute().GetAttributeType())
  996. if attribute_type == FbxNodeAttribute.eCamera:
  997. camera_string = getObjectName(node)
  998. camera_list.append(camera_string)
  999. for i in range(node.GetChildCount()):
  1000. generate_camera_name_list_from_hierarchy(node.GetChild(i), camera_list)
  1001. def generate_camera_name_list(scene):
  1002. camera_list = []
  1003. node = scene.GetRootNode()
  1004. if node:
  1005. for i in range(node.GetChildCount()):
  1006. generate_camera_name_list_from_hierarchy(node.GetChild(i), camera_list)
  1007. return camera_list
  1008. # #####################################################
  1009. # Generate - Light Object
  1010. # #####################################################
  1011. def generate_default_light_string(padding):
  1012. direction = (1,1,1)
  1013. color = (1,1,1)
  1014. intensity = 80.0
  1015. output = [
  1016. '\t\t' + LabelString( 'default_light' ) + ' : {',
  1017. ' "type" : "DirectionalLight",',
  1018. ' "color" : ' + str(getHex(color)) + ',',
  1019. ' "intensity" : ' + str(intensity/100.0) + ',',
  1020. ' "direction" : ' + Vector3String( direction ) + ',',
  1021. ' "target" : ' + LabelString( getObjectName( None ) ),
  1022. ' }'
  1023. ]
  1024. return generateMultiLineString( output, '\n\t\t', padding )
  1025. def generate_light_string(node, padding):
  1026. light = node.GetNodeAttribute()
  1027. light_types = ["point", "directional", "spot", "area", "volume"]
  1028. light_type = light_types[light.LightType.Get()]
  1029. transform = node.EvaluateLocalTransform()
  1030. position = transform.GetT()
  1031. output = []
  1032. if light_type == "directional":
  1033. # Three.js directional lights emit light from a point in 3d space to a target node or the origin.
  1034. # When there is no target, we need to take a point, one unit away from the origin, and move it
  1035. # into the right location so that the origin acts like the target
  1036. if node.GetTarget():
  1037. direction = position
  1038. else:
  1039. translation = FbxVector4(0,0,0,0)
  1040. scale = FbxVector4(1,1,1,1)
  1041. rotation = transform.GetR()
  1042. matrix = FbxMatrix(translation, rotation, scale)
  1043. direction = matrix.MultNormalize(global_up_vector)
  1044. output = [
  1045. '\t\t' + LabelString( getObjectName( node ) ) + ' : {',
  1046. ' "type" : "DirectionalLight",',
  1047. ' "color" : ' + str(getHex(light.Color.Get())) + ',',
  1048. ' "intensity" : ' + str(light.Intensity.Get()/100.0) + ',',
  1049. ' "direction" : ' + Vector3String( direction ) + ',',
  1050. ' "target" : ' + LabelString( getObjectName( node.GetTarget() ) ) + ( ',' if node.GetChildCount() > 0 else '' )
  1051. ]
  1052. elif light_type == "point":
  1053. output = [
  1054. '\t\t' + LabelString( getObjectName( node ) ) + ' : {',
  1055. ' "type" : "PointLight",',
  1056. ' "color" : ' + str(getHex(light.Color.Get())) + ',',
  1057. ' "intensity" : ' + str(light.Intensity.Get()/100.0) + ',',
  1058. ' "position" : ' + Vector3String( position ) + ',',
  1059. ' "distance" : ' + str(light.FarAttenuationEnd.Get()) + ( ',' if node.GetChildCount() > 0 else '' )
  1060. ]
  1061. elif light_type == "spot":
  1062. output = [
  1063. '\t\t' + LabelString( getObjectName( node ) ) + ' : {',
  1064. ' "type" : "SpotLight",',
  1065. ' "color" : ' + str(getHex(light.Color.Get())) + ',',
  1066. ' "intensity" : ' + str(light.Intensity.Get()/100.0) + ',',
  1067. ' "position" : ' + Vector3String( position ) + ',',
  1068. ' "distance" : ' + str(light.FarAttenuationEnd.Get()) + ',',
  1069. ' "angle" : ' + str((light.OuterAngle.Get()*math.pi)/180) + ',',
  1070. ' "exponent" : ' + str(light.DecayType.Get()) + ',',
  1071. ' "target" : ' + LabelString( getObjectName( node.GetTarget() ) ) + ( ',' if node.GetChildCount() > 0 else '' )
  1072. ]
  1073. return generateMultiLineString( output, '\n\t\t', padding )
  1074. def generate_ambient_light_string(scene):
  1075. scene_settings = scene.GetGlobalSettings()
  1076. ambient_color = scene_settings.GetAmbientColor()
  1077. ambient_color = (ambient_color.mRed, ambient_color.mGreen, ambient_color.mBlue)
  1078. if ambient_color[0] == 0 and ambient_color[1] == 0 and ambient_color[2] == 0:
  1079. return None
  1080. class AmbientLight:
  1081. def GetName(self):
  1082. return "AmbientLight"
  1083. node = AmbientLight()
  1084. output = [
  1085. '\t\t' + LabelString( getObjectName( node ) ) + ' : {',
  1086. ' "type" : "AmbientLight",',
  1087. ' "color" : ' + str(getHex(ambient_color)),
  1088. '}'
  1089. ]
  1090. return generateMultiLineString( output, '\n\t\t', 0 )
  1091. # #####################################################
  1092. # Generate - Camera Object
  1093. # #####################################################
  1094. def generate_default_camera_string(padding):
  1095. position = (100, 100, 100)
  1096. near = 0.1
  1097. far = 1000
  1098. fov = 75
  1099. output = [
  1100. '\t\t' + LabelString( 'default_camera' ) + ' : {',
  1101. ' "type" : "PerspectiveCamera",',
  1102. ' "fov" : ' + str(fov) + ',',
  1103. ' "near" : ' + str(near) + ',',
  1104. ' "far" : ' + str(far) + ',',
  1105. ' "position" : ' + Vector3String( position ),
  1106. ' }'
  1107. ]
  1108. return generateMultiLineString( output, '\n\t\t', padding )
  1109. def generate_camera_string(node, padding):
  1110. camera = node.GetNodeAttribute()
  1111. target_node = node.GetTarget()
  1112. target = ""
  1113. if target_node:
  1114. transform = target.EvaluateLocalTransform()
  1115. target = transform.GetT()
  1116. else:
  1117. target = camera.InterestPosition.Get()
  1118. position = camera.Position.Get()
  1119. projection_types = [ "perspective", "orthogonal" ]
  1120. projection = projection_types[camera.ProjectionType.Get()]
  1121. near = camera.NearPlane.Get()
  1122. far = camera.FarPlane.Get()
  1123. output = []
  1124. if projection == "perspective":
  1125. aspect = camera.PixelAspectRatio.Get()
  1126. fov = camera.FieldOfView.Get()
  1127. output = [
  1128. '\t\t' + LabelString( getObjectName( node ) ) + ' : {',
  1129. ' "type" : "PerspectiveCamera",',
  1130. ' "fov" : ' + str(fov) + ',',
  1131. ' "aspect" : ' + str(aspect) + ',',
  1132. ' "near" : ' + str(near) + ',',
  1133. ' "far" : ' + str(far) + ',',
  1134. ' "position" : ' + Vector3String( position ) + ( ',' if node.GetChildCount() > 0 else '' )
  1135. ]
  1136. elif projection == "orthogonal":
  1137. left = ""
  1138. right = ""
  1139. top = ""
  1140. bottom = ""
  1141. output = [
  1142. '\t\t' + LabelString( getObjectName( node ) ) + ' : {',
  1143. ' "type" : "OrthographicCamera",',
  1144. ' "left" : ' + left + ',',
  1145. ' "right" : ' + right + ',',
  1146. ' "top" : ' + top + ',',
  1147. ' "bottom" : ' + bottom + ',',
  1148. ' "near" : ' + str(near) + ',',
  1149. ' "far" : ' + str(far) + ',',
  1150. ' "position" : ' + Vector3String( position ) + ( ',' if node.GetChildCount() > 0 else '' )
  1151. ]
  1152. return generateMultiLineString( output, '\n\t\t', padding )
  1153. # #####################################################
  1154. # Generate - Mesh Object
  1155. # #####################################################
  1156. def generate_mesh_object_string(node, padding):
  1157. mesh = node.GetNodeAttribute()
  1158. transform = node.EvaluateLocalTransform()
  1159. position = transform.GetT()
  1160. scale = transform.GetS()
  1161. rotation = getRadians(transform.GetR())
  1162. material_count = node.GetMaterialCount()
  1163. material_name = ""
  1164. if material_count > 0:
  1165. material_names = []
  1166. for l in range(mesh.GetLayerCount()):
  1167. materials = mesh.GetLayer(l).GetMaterials()
  1168. if materials:
  1169. if materials.GetReferenceMode() == FbxLayerElement.eIndex:
  1170. #Materials are in an undefined external table
  1171. continue
  1172. for i in range(material_count):
  1173. material = node.GetMaterial(i)
  1174. material_names.append( getMaterialName(material) )
  1175. #If this mesh has more than one material, use a proxy material
  1176. material_name = getMaterialName( node, True) if material_count > 1 else material_names[0]
  1177. output = [
  1178. '\t\t' + LabelString( getObjectName( node ) ) + ' : {',
  1179. ' "geometry" : ' + LabelString( getGeometryName( node, True ) ) + ',',
  1180. ' "material" : ' + LabelString( material_name ) + ',',
  1181. ' "position" : ' + Vector3String( position ) + ',',
  1182. ' "rotation" : ' + Vector3String( rotation ) + ',',
  1183. ' "scale" : ' + Vector3String( scale ) + ',',
  1184. ' "visible" : ' + getObjectVisible( node ) + ( ',' if node.GetChildCount() > 0 else '' )
  1185. ]
  1186. return generateMultiLineString( output, '\n\t\t', padding )
  1187. # #####################################################
  1188. # Generate - Object
  1189. # #####################################################
  1190. def generate_object_string(node, padding):
  1191. node_types = ["Unknown", "Null", "Marker", "Skeleton", "Mesh", "Nurbs", "Patch", "Camera",
  1192. "CameraStereo", "CameraSwitcher", "Light", "OpticalReference", "OpticalMarker", "NurbsCurve",
  1193. "TrimNurbsSurface", "Boundary", "NurbsSurface", "Shape", "LODGroup", "SubDiv", "CachedEffect", "Line"]
  1194. transform = node.EvaluateLocalTransform()
  1195. position = transform.GetT()
  1196. scale = transform.GetS()
  1197. rotation = getRadians(transform.GetR())
  1198. node_type = ""
  1199. if node.GetNodeAttribute() == None:
  1200. node_type = "Null"
  1201. else:
  1202. node_type = node_types[node.GetNodeAttribute().GetAttributeType()]
  1203. output = [
  1204. '\t\t' + LabelString( getObjectName( node ) ) + ' : {',
  1205. ' "fbx_type" : ' + LabelString( node_type ) + ',',
  1206. ' "position" : ' + Vector3String( position ) + ',',
  1207. ' "rotation" : ' + Vector3String( rotation ) + ',',
  1208. ' "scale" : ' + Vector3String( scale ) + ',',
  1209. ' "visible" : ' + getObjectVisible( node ) + ( ',' if node.GetChildCount() > 0 else '' )
  1210. ]
  1211. return generateMultiLineString( output, '\n\t\t', padding )
  1212. # #####################################################
  1213. # Parse - Objects
  1214. # #####################################################
  1215. def generate_object_hierarchy(node, object_list, pad, siblings_left):
  1216. object_count = 0
  1217. if node.GetNodeAttribute() == None:
  1218. object_string = generate_object_string(node, pad)
  1219. object_list.append(object_string)
  1220. object_count += 1
  1221. else:
  1222. attribute_type = (node.GetNodeAttribute().GetAttributeType())
  1223. if attribute_type == FbxNodeAttribute.eMesh:
  1224. object_string = generate_mesh_object_string(node, pad)
  1225. object_list.append(object_string)
  1226. object_count += 1
  1227. elif attribute_type == FbxNodeAttribute.eLight:
  1228. object_string = generate_light_string(node, pad)
  1229. object_list.append(object_string)
  1230. object_count += 1
  1231. elif attribute_type == FbxNodeAttribute.eCamera:
  1232. object_string = generate_camera_string(node, pad)
  1233. object_list.append(object_string)
  1234. object_count += 1
  1235. else:
  1236. object_string = generate_object_string(node, pad)
  1237. object_list.append(object_string)
  1238. object_count += 1
  1239. if node.GetChildCount() > 0:
  1240. object_list.append( PaddingString( pad + 1 ) + '\t\t"children" : {\n' )
  1241. for i in range(node.GetChildCount()):
  1242. object_count += generate_object_hierarchy(node.GetChild(i), object_list, pad + 2, node.GetChildCount() - i - 1)
  1243. object_list.append( PaddingString( pad + 1 ) + '\t\t}' )
  1244. object_list.append( PaddingString( pad ) + '\t\t}' + (',\n' if siblings_left > 0 else ''))
  1245. return object_count
  1246. def generate_scene_objects_string(scene):
  1247. object_count = 0
  1248. object_list = []
  1249. ambient_light = generate_ambient_light_string(scene)
  1250. if ambient_light:
  1251. if scene.GetNodeCount() > 0 or option_default_light or option_default_camera:
  1252. ambient_light += (',\n')
  1253. object_list.append(ambient_light)
  1254. object_count += 1
  1255. if option_default_light:
  1256. default_light = generate_default_light_string(0)
  1257. if scene.GetNodeCount() > 0 or option_default_camera:
  1258. default_light += (',\n')
  1259. object_list.append(default_light)
  1260. object_count += 1
  1261. if option_default_camera:
  1262. default_camera = generate_default_camera_string(0)
  1263. if scene.GetNodeCount() > 0:
  1264. default_camera += (',\n')
  1265. object_list.append(default_camera)
  1266. object_count += 1
  1267. node = scene.GetRootNode()
  1268. if node:
  1269. for i in range(node.GetChildCount()):
  1270. object_count += generate_object_hierarchy(node.GetChild(i), object_list, 0, node.GetChildCount() - i - 1)
  1271. return "\n".join(object_list), object_count
  1272. # #####################################################
  1273. # Parse - Geometry
  1274. # #####################################################
  1275. def extract_geometry(scene, filename):
  1276. embeds_list = generate_embed_list(scene)
  1277. #TODO: update the Three.js Geometry Format to support multiple geometries?
  1278. embeds = [ embeds_list[0] ] if len(embeds_list) > 0 else []
  1279. embeds = generateMultiLineString( embeds_list, ",\n\n\t", 0 )
  1280. output = [
  1281. '{',
  1282. ' "metadata": {',
  1283. ' "formatVersion" : 3.2,',
  1284. ' "type" : "geometry",',
  1285. ' "generatedBy" : "convert-to-threejs.py"',
  1286. ' },',
  1287. '',
  1288. '\t' + embeds,
  1289. '}'
  1290. ]
  1291. return "\n".join(output)
  1292. # #####################################################
  1293. # Parse - Scene
  1294. # #####################################################
  1295. def extract_scene(scene, filename):
  1296. global_settings = scene.GetGlobalSettings()
  1297. objects, nobjects = generate_scene_objects_string(scene)
  1298. textures = generate_texture_list(scene)
  1299. materials = generate_material_list(scene)
  1300. geometries = generate_geometry_list(scene)
  1301. embeds = generate_embed_list(scene)
  1302. fogs = []
  1303. ntextures = len(textures)
  1304. nmaterials = len(materials)
  1305. ngeometries = len(geometries)
  1306. #TODO: extract actual root/scene data here
  1307. position = Vector3String( (0,0,0) )
  1308. rotation = Vector3String( (0,0,0) )
  1309. scale = Vector3String( (1,1,1) )
  1310. camera_names = generate_camera_name_list(scene)
  1311. scene_settings = scene.GetGlobalSettings()
  1312. #TODO: this might exist as part of the FBX spec
  1313. bgcolor = Vector3String( (0.667,0.667,0.667) )
  1314. bgalpha = 1
  1315. # This does not seem to be any help here
  1316. # global_settings.GetDefaultCamera()
  1317. defcamera = LabelString(camera_names[0] if len(camera_names) > 0 else "")
  1318. if option_default_camera:
  1319. defcamera = LabelString('default_camera')
  1320. #TODO: extract fog info from scene
  1321. deffog = LabelString("")
  1322. geometries = generateMultiLineString( geometries, ",\n\n\t", 0 )
  1323. materials = generateMultiLineString( materials, ",\n\n\t", 0 )
  1324. textures = generateMultiLineString( textures, ",\n\n\t", 0 )
  1325. embeds = generateMultiLineString( embeds, ",\n\n\t", 0 )
  1326. fogs = generateMultiLineString( fogs, ",\n\n\t", 0 )
  1327. output = [
  1328. '{',
  1329. ' "metadata": {',
  1330. ' "formatVersion" : 3.2,',
  1331. ' "type" : "scene",',
  1332. ' "generatedBy" : "convert-to-threejs.py",',
  1333. ' "objects" : ' + str(nobjects) + ',',
  1334. ' "geometries" : ' + str(ngeometries) + ',',
  1335. ' "materials" : ' + str(nmaterials) + ',',
  1336. ' "textures" : ' + str(ntextures),
  1337. ' },',
  1338. '',
  1339. ' "urlBaseType": "relativeToScene",',
  1340. '',
  1341. ' "objects" :',
  1342. ' {',
  1343. objects,
  1344. ' },',
  1345. '',
  1346. ' "geometries" :',
  1347. ' {',
  1348. '\t' + geometries,
  1349. ' },',
  1350. '',
  1351. ' "materials" :',
  1352. ' {',
  1353. '\t' + materials,
  1354. ' },',
  1355. '',
  1356. ' "textures" :',
  1357. ' {',
  1358. '\t' + textures,
  1359. ' },',
  1360. '',
  1361. ' "embeds" :',
  1362. ' {',
  1363. '\t' + embeds,
  1364. ' },',
  1365. '',
  1366. ' "fogs" :',
  1367. ' {',
  1368. '\t' + fogs,
  1369. ' },',
  1370. '',
  1371. ' "transform" :',
  1372. ' {',
  1373. ' "position" : ' + position + ',',
  1374. ' "rotation" : ' + rotation + ',',
  1375. ' "scale" : ' + scale,
  1376. ' },',
  1377. '',
  1378. ' "defaults" :',
  1379. ' {',
  1380. ' "bgcolor" : ' + str(bgcolor) + ',',
  1381. ' "bgalpha" : ' + str(bgalpha) + ',',
  1382. ' "camera" : ' + defcamera + ',',
  1383. ' "fog" : ' + deffog,
  1384. ' }',
  1385. '}'
  1386. ]
  1387. return "\n".join(output)
  1388. # #####################################################
  1389. # file helpers
  1390. # #####################################################
  1391. def write_file(fname, content):
  1392. out = open(fname, "w")
  1393. out.write(content)
  1394. out.close()
  1395. # #####################################################
  1396. # main
  1397. # #####################################################
  1398. if __name__ == "__main__":
  1399. from optparse import OptionParser
  1400. try:
  1401. from FbxCommon import *
  1402. except ImportError:
  1403. import platform
  1404. msg = 'Could not locate the python FBX SDK!\n'
  1405. msg += 'You need to copy the FBX SDK into your python install folder such as '
  1406. if platform.system() == 'Windows' or platform.system() == 'Microsoft':
  1407. msg += '"Python26/Lib/site-packages"'
  1408. elif platform.system() == 'Linux':
  1409. msg += '"/usr/local/lib/python2.6/site-packages"'
  1410. elif platform.system() == 'Darwin':
  1411. msg += '"/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages"'
  1412. msg += ' folder.'
  1413. print(msg)
  1414. sys.exit(1)
  1415. usage = "Usage: %prog [source_file.fbx] [output_file.js] [options]"
  1416. parser = OptionParser(usage=usage)
  1417. parser.add_option('-t', '--triangulate', action='store_true', dest='triangulate', help="force quad geometry into triangles", default=False)
  1418. parser.add_option('-x', '--no-textures', action='store_true', dest='notextures', help="don't include texture references in output file", default=False)
  1419. parser.add_option('-p', '--prefix', action='store_true', dest='prefix', help="prefix object names in output file", default=False)
  1420. parser.add_option('-g', '--geometry-only', action='store_true', dest='geometry', help="output geometry only", default=False)
  1421. parser.add_option('-c', '--default-camera', action='store_true', dest='defcamera', help="include default camera in output scene", default=False)
  1422. parser.add_option('-l', '--defualt-light', action='store_true', dest='deflight', help="include default light in output scene", default=False)
  1423. (options, args) = parser.parse_args()
  1424. option_triangulate = options.triangulate
  1425. option_textures = True if not options.notextures else False
  1426. option_prefix = options.prefix
  1427. option_geometry = options.geometry
  1428. option_default_camera = options.defcamera
  1429. option_default_light = options.deflight
  1430. # Prepare the FBX SDK.
  1431. sdk_manager, scene = InitializeSdkObjects()
  1432. converter = FbxGeometryConverter(sdk_manager)
  1433. global_up_vector = get_up_vector(scene)
  1434. # The converter takes an FBX file as an argument.
  1435. if len(args) > 1:
  1436. print("\nLoading file: %s" % args[0])
  1437. result = LoadScene(sdk_manager, scene, args[0])
  1438. else:
  1439. result = False
  1440. print("\nUsage: convert_fbx_to_threejs [source_file.fbx] [output_file.js]\n")
  1441. if not result:
  1442. print("\nAn error occurred while loading the file...")
  1443. else:
  1444. if option_triangulate:
  1445. print("\nForcing geometry to triangles")
  1446. triangulate_scene(scene)
  1447. if option_geometry:
  1448. output_content = extract_geometry(scene, os.path.basename(args[0]))
  1449. else:
  1450. output_content = extract_scene(scene, os.path.basename(args[0]))
  1451. output_path = os.path.join(os.getcwd(), args[1])
  1452. write_file(output_path, output_content)
  1453. print("\nExported Three.js file to:\n%s\n" % output_path)
  1454. # Destroy all objects created by the FBX SDK.
  1455. sdk_manager.Destroy()
  1456. sys.exit(0)