convert_to_threejs.py 66 KB

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