convert_to_threejs.py 74 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135
  1. # @author zfedoran / http://github.com/zfedoran
  2. import os
  3. import sys
  4. import math
  5. import operator
  6. import re
  7. import json
  8. import types
  9. import shutil
  10. # #####################################################
  11. # Globals
  12. # #####################################################
  13. option_triangulate = True
  14. option_textures = True
  15. option_prefix = True
  16. option_geometry = False
  17. option_default_camera = False
  18. option_default_light = False
  19. option_pretty_print = False
  20. converter = None
  21. inputFolder = ""
  22. outputFolder = ""
  23. # #####################################################
  24. # Pretty Printing Hacks
  25. # #####################################################
  26. # Force an array to be printed fully on a single line
  27. class NoIndent(object):
  28. def __init__(self, value, separator = ','):
  29. self.separator = separator
  30. self.value = value
  31. def encode(self):
  32. if not self.value:
  33. return None
  34. return '[ %s ]' % self.separator.join(str(f) for f in self.value)
  35. # Force an array into chunks rather than printing each element on a new line
  36. class ChunkedIndent(object):
  37. def __init__(self, value, chunk_size = 15, force_rounding = False):
  38. self.value = value
  39. self.size = chunk_size
  40. self.force_rounding = force_rounding
  41. def encode(self):
  42. # Turn the flat array into an array of arrays where each subarray is of
  43. # length chunk_size. Then string concat the values in the chunked
  44. # arrays, delimited with a ', ' and round the values finally append
  45. # '{CHUNK}' so that we can find the strings with regex later
  46. if not self.value:
  47. return None
  48. if self.force_rounding:
  49. return ['{CHUNK}%s' % ', '.join(str(round(f, 6)) for f in self.value[i:i+self.size]) for i in range(0, len(self.value), self.size)]
  50. else:
  51. return ['{CHUNK}%s' % ', '.join(str(f) for f in self.value[i:i+self.size]) for i in range(0, len(self.value), self.size)]
  52. # This custom encoder looks for instances of NoIndent or ChunkedIndent.
  53. # When it finds
  54. class CustomEncoder(json.JSONEncoder):
  55. def default(self, obj):
  56. if isinstance(obj, NoIndent) or isinstance(obj, ChunkedIndent):
  57. return obj.encode()
  58. else:
  59. return json.JSONEncoder.default(self, obj)
  60. def executeRegexHacks(output_string):
  61. # turn strings of arrays into arrays (remove the double quotes)
  62. output_string = re.sub(':\s*\"(\[.*\])\"', r': \1', output_string)
  63. output_string = re.sub('(\n\s*)\"(\[.*\])\"', r'\1\2', output_string)
  64. output_string = re.sub('(\n\s*)\"{CHUNK}(.*)\"', r'\1\2', output_string)
  65. # replace '0metadata' with metadata
  66. output_string = re.sub('0metadata', r'metadata', output_string)
  67. # replace 'zchildren' with children
  68. output_string = re.sub('zchildren', r'children', output_string)
  69. # add an extra newline after '"children": {'
  70. output_string = re.sub('(children.*{\s*\n)', r'\1\n', output_string)
  71. # add an extra newline after '},'
  72. output_string = re.sub('},\s*\n', r'},\n\n', output_string)
  73. # add an extra newline after '\n\s*],'
  74. output_string = re.sub('(\n\s*)],\s*\n', r'\1],\n\n', output_string)
  75. return output_string
  76. # #####################################################
  77. # Object Serializers
  78. # #####################################################
  79. # FbxVector2 is not JSON serializable
  80. def serializeVector2(v, round_vector = False):
  81. # JSON does not support NaN or Inf
  82. if math.isnan(v[0]) or math.isinf(v[0]):
  83. v[0] = 0
  84. if math.isnan(v[1]) or math.isinf(v[1]):
  85. v[1] = 0
  86. if round_vector or option_pretty_print:
  87. v = (round(v[0], 5), round(v[1], 5))
  88. if option_pretty_print:
  89. return NoIndent([v[0], v[1]], ', ')
  90. else:
  91. return [v[0], v[1]]
  92. # FbxVector3 is not JSON serializable
  93. def serializeVector3(v, round_vector = False):
  94. # JSON does not support NaN or Inf
  95. if math.isnan(v[0]) or math.isinf(v[0]):
  96. v[0] = 0
  97. if math.isnan(v[1]) or math.isinf(v[1]):
  98. v[1] = 0
  99. if math.isnan(v[2]) or math.isinf(v[2]):
  100. v[2] = 0
  101. if round_vector or option_pretty_print:
  102. v = (round(v[0], 5), round(v[1], 5), round(v[2], 5))
  103. if option_pretty_print:
  104. return NoIndent([v[0], v[1], v[2]], ', ')
  105. else:
  106. return [v[0], v[1], v[2]]
  107. # FbxVector4 is not JSON serializable
  108. def serializeVector4(v, round_vector = False):
  109. # JSON does not support NaN or Inf
  110. if math.isnan(v[0]) or math.isinf(v[0]):
  111. v[0] = 0
  112. if math.isnan(v[1]) or math.isinf(v[1]):
  113. v[1] = 0
  114. if math.isnan(v[2]) or math.isinf(v[2]):
  115. v[2] = 0
  116. if math.isnan(v[3]) or math.isinf(v[3]):
  117. v[3] = 0
  118. if round_vector or option_pretty_print:
  119. v = (round(v[0], 5), round(v[1], 5), round(v[2], 5), round(v[3], 5))
  120. if option_pretty_print:
  121. return NoIndent([v[0], v[1], v[2], v[3]], ', ')
  122. else:
  123. return [v[0], v[1], v[2], v[3]]
  124. # #####################################################
  125. # Helpers
  126. # #####################################################
  127. def getRadians(v):
  128. return ((v[0]*math.pi)/180, (v[1]*math.pi)/180, (v[2]*math.pi)/180)
  129. def getHex(c):
  130. color = (int(c[0]*255) << 16) + (int(c[1]*255) << 8) + int(c[2]*255)
  131. return int(color)
  132. def setBit(value, position, on):
  133. if on:
  134. mask = 1 << position
  135. return (value | mask)
  136. else:
  137. mask = ~(1 << position)
  138. return (value & mask)
  139. def generate_uvs(uv_layers):
  140. layers = []
  141. for uvs in uv_layers:
  142. tmp = []
  143. for uv in uvs:
  144. tmp.append(uv[0])
  145. tmp.append(uv[1])
  146. if option_pretty_print:
  147. layer = ChunkedIndent(tmp)
  148. else:
  149. layer = tmp
  150. layers.append(layer)
  151. return layers
  152. # #####################################################
  153. # Object Name Helpers
  154. # #####################################################
  155. def hasUniqueName(o, class_id):
  156. scene = o.GetScene()
  157. object_name = o.GetName()
  158. object_id = o.GetUniqueID()
  159. object_count = scene.GetSrcObjectCount(class_id)
  160. for i in range(object_count):
  161. other = scene.GetSrcObject(class_id, i)
  162. other_id = other.GetUniqueID()
  163. other_name = other.GetName()
  164. if other_id == object_id:
  165. continue
  166. if other_name == object_name:
  167. return False
  168. return True
  169. def getObjectName(o, force_prefix = False):
  170. if not o:
  171. return ""
  172. object_name = o.GetName()
  173. object_id = o.GetUniqueID()
  174. if not force_prefix:
  175. force_prefix = not hasUniqueName(o, FbxNode.ClassId)
  176. prefix = ""
  177. if option_prefix or force_prefix:
  178. prefix = "Object_%s_" % object_id
  179. return prefix + object_name
  180. def getMaterialName(o, force_prefix = False):
  181. object_name = o.GetName()
  182. object_id = o.GetUniqueID()
  183. if not force_prefix:
  184. force_prefix = not hasUniqueName(o, FbxSurfaceMaterial.ClassId)
  185. prefix = ""
  186. if option_prefix or force_prefix:
  187. prefix = "Material_%s_" % object_id
  188. return prefix + object_name
  189. def getTextureName(t, force_prefix = False):
  190. if type(t) is FbxFileTexture:
  191. texture_file = t.GetFileName()
  192. texture_id = os.path.splitext(os.path.basename(texture_file))[0]
  193. else:
  194. texture_id = t.GetName()
  195. if texture_id == "_empty_":
  196. texture_id = ""
  197. prefix = ""
  198. if option_prefix or force_prefix:
  199. prefix = "Texture_%s_" % t.GetUniqueID()
  200. if len(texture_id) == 0:
  201. prefix = prefix[0:len(prefix)-1]
  202. return prefix + texture_id
  203. def getMtlTextureName(texture_name, texture_id, force_prefix = False):
  204. texture_name = os.path.splitext(texture_name)[0]
  205. prefix = ""
  206. if option_prefix or force_prefix:
  207. prefix = "Texture_%s_" % texture_id
  208. return prefix + texture_name
  209. def getPrefixedName(o, prefix):
  210. return (prefix + '_%s_') % o.GetUniqueID() + o.GetName()
  211. # #####################################################
  212. # Triangulation
  213. # #####################################################
  214. def triangulate_node_hierarchy(node):
  215. node_attribute = node.GetNodeAttribute();
  216. if node_attribute:
  217. if node_attribute.GetAttributeType() == FbxNodeAttribute.eMesh or \
  218. node_attribute.GetAttributeType() == FbxNodeAttribute.eNurbs or \
  219. node_attribute.GetAttributeType() == FbxNodeAttribute.eNurbsSurface or \
  220. node_attribute.GetAttributeType() == FbxNodeAttribute.ePatch:
  221. converter.TriangulateInPlace(node);
  222. child_count = node.GetChildCount()
  223. for i in range(child_count):
  224. triangulate_node_hierarchy(node.GetChild(i))
  225. def triangulate_scene(scene):
  226. node = scene.GetRootNode()
  227. if node:
  228. for i in range(node.GetChildCount()):
  229. triangulate_node_hierarchy(node.GetChild(i))
  230. # #####################################################
  231. # Generate Material Object
  232. # #####################################################
  233. def generate_texture_bindings(material_property, material_params):
  234. # FBX to Three.js texture types
  235. binding_types = {
  236. "DiffuseColor": "map",
  237. "DiffuseFactor": "diffuseFactor",
  238. "EmissiveColor": "emissiveMap",
  239. "EmissiveFactor": "emissiveFactor",
  240. "AmbientColor": "ambientMap",
  241. "AmbientFactor": "ambientFactor",
  242. "SpecularColor": "specularMap",
  243. "SpecularFactor": "specularFactor",
  244. "ShininessExponent": "shininessExponent",
  245. "NormalMap": "normalMap",
  246. "Bump": "bumpMap",
  247. "TransparentColor": "transparentMap",
  248. "TransparencyFactor": "transparentFactor",
  249. "ReflectionColor": "reflectionMap",
  250. "ReflectionFactor": "reflectionFactor",
  251. "DisplacementColor": "displacementMap",
  252. "VectorDisplacementColor": "vectorDisplacementMap"
  253. }
  254. if material_property.IsValid():
  255. #Here we have to check if it's layeredtextures, or just textures:
  256. layered_texture_count = material_property.GetSrcObjectCount(FbxLayeredTexture.ClassId)
  257. if layered_texture_count > 0:
  258. for j in range(layered_texture_count):
  259. layered_texture = material_property.GetSrcObject(FbxLayeredTexture.ClassId, j)
  260. texture_count = layered_texture.GetSrcObjectCount(FbxTexture.ClassId)
  261. for k in range(texture_count):
  262. texture = layered_texture.GetSrcObject(FbxTexture.ClassId,k)
  263. if texture:
  264. texture_id = getTextureName(texture, True)
  265. material_params[binding_types[str(material_property.GetName())]] = texture_id
  266. else:
  267. # no layered texture simply get on the property
  268. texture_count = material_property.GetSrcObjectCount(FbxTexture.ClassId)
  269. for j in range(texture_count):
  270. texture = material_property.GetSrcObject(FbxTexture.ClassId,j)
  271. if texture:
  272. texture_id = getTextureName(texture, True)
  273. material_params[binding_types[str(material_property.GetName())]] = texture_id
  274. def generate_material_object(material):
  275. #Get the implementation to see if it's a hardware shader.
  276. implementation = GetImplementation(material, "ImplementationHLSL")
  277. implementation_type = "HLSL"
  278. if not implementation:
  279. implementation = GetImplementation(material, "ImplementationCGFX")
  280. implementation_type = "CGFX"
  281. output = None
  282. material_params = None
  283. material_type = None
  284. if implementation:
  285. print("Shader materials are not supported")
  286. elif material.GetClassId().Is(FbxSurfaceLambert.ClassId):
  287. ambient = getHex(material.Ambient.Get())
  288. diffuse = getHex(material.Diffuse.Get())
  289. emissive = getHex(material.Emissive.Get())
  290. opacity = 1.0 - material.TransparencyFactor.Get()
  291. opacity = 1.0 if opacity == 0 else opacity
  292. opacity = opacity
  293. transparent = False
  294. reflectivity = 1
  295. material_type = 'MeshLambertMaterial'
  296. material_params = {
  297. 'color' : diffuse,
  298. 'ambient' : ambient,
  299. 'emissive' : emissive,
  300. 'reflectivity' : reflectivity,
  301. 'transparent' : transparent,
  302. 'opacity' : opacity
  303. }
  304. elif material.GetClassId().Is(FbxSurfacePhong.ClassId):
  305. ambient = getHex(material.Ambient.Get())
  306. diffuse = getHex(material.Diffuse.Get())
  307. emissive = getHex(material.Emissive.Get())
  308. specular = getHex(material.Specular.Get())
  309. opacity = 1.0 - material.TransparencyFactor.Get()
  310. opacity = 1.0 if opacity == 0 else opacity
  311. opacity = opacity
  312. shininess = material.Shininess.Get()
  313. transparent = False
  314. reflectivity = 1
  315. bumpScale = 1
  316. material_type = 'MeshPhongMaterial'
  317. material_params = {
  318. 'color' : diffuse,
  319. 'ambient' : ambient,
  320. 'emissive' : emissive,
  321. 'specular' : specular,
  322. 'shininess' : shininess,
  323. 'bumpScale' : bumpScale,
  324. 'reflectivity' : reflectivity,
  325. 'transparent' : transparent,
  326. 'opacity' : opacity
  327. }
  328. else:
  329. print "Unknown type of Material", getMaterialName(material)
  330. # default to Lambert Material if the current Material type cannot be handeled
  331. if not material_type:
  332. ambient = getHex((0,0,0))
  333. diffuse = getHex((0.5,0.5,0.5))
  334. emissive = getHex((0,0,0))
  335. opacity = 1
  336. transparent = False
  337. reflectivity = 1
  338. material_type = 'MeshLambertMaterial'
  339. material_params = {
  340. 'color' : diffuse,
  341. 'ambient' : ambient,
  342. 'emissive' : emissive,
  343. 'reflectivity' : reflectivity,
  344. 'transparent' : transparent,
  345. 'opacity' : opacity
  346. }
  347. if option_textures:
  348. texture_count = FbxLayerElement.sTypeTextureCount()
  349. for texture_index in range(texture_count):
  350. material_property = material.FindProperty(FbxLayerElement.sTextureChannelNames(texture_index))
  351. generate_texture_bindings(material_property, material_params)
  352. material_params['wireframe'] = False
  353. material_params['wireframeLinewidth'] = 1
  354. output = {
  355. 'type' : material_type,
  356. 'parameters' : material_params
  357. }
  358. return output
  359. def generate_proxy_material_object(node, material_names):
  360. material_type = 'MeshFaceMaterial'
  361. material_params = {
  362. 'materials' : material_names
  363. }
  364. output = {
  365. 'type' : material_type,
  366. 'parameters' : material_params
  367. }
  368. return output
  369. # #####################################################
  370. # Find Scene Materials
  371. # #####################################################
  372. def extract_materials_from_node(node, material_dict):
  373. name = node.GetName()
  374. mesh = node.GetNodeAttribute()
  375. node = None
  376. if mesh:
  377. node = mesh.GetNode()
  378. if node:
  379. material_count = node.GetMaterialCount()
  380. material_names = []
  381. for l in range(mesh.GetLayerCount()):
  382. materials = mesh.GetLayer(l).GetMaterials()
  383. if materials:
  384. if materials.GetReferenceMode() == FbxLayerElement.eIndex:
  385. #Materials are in an undefined external table
  386. continue
  387. for i in range(material_count):
  388. material = node.GetMaterial(i)
  389. material_names.append(getMaterialName(material))
  390. if material_count > 1:
  391. proxy_material = generate_proxy_material_object(node, material_names)
  392. proxy_name = getMaterialName(node, True)
  393. material_dict[proxy_name] = proxy_material
  394. def generate_materials_from_hierarchy(node, material_dict):
  395. if node.GetNodeAttribute() == None:
  396. pass
  397. else:
  398. attribute_type = (node.GetNodeAttribute().GetAttributeType())
  399. if attribute_type == FbxNodeAttribute.eMesh:
  400. extract_materials_from_node(node, material_dict)
  401. for i in range(node.GetChildCount()):
  402. generate_materials_from_hierarchy(node.GetChild(i), material_dict)
  403. def generate_material_dict(scene):
  404. material_dict = {}
  405. # generate all materials for this scene
  406. material_count = scene.GetSrcObjectCount(FbxSurfaceMaterial.ClassId)
  407. for i in range(material_count):
  408. material = scene.GetSrcObject(FbxSurfaceMaterial.ClassId, i)
  409. material_object = generate_material_object(material)
  410. material_name = getMaterialName(material)
  411. material_dict[material_name] = material_object
  412. # generate material porxies
  413. # Three.js does not support meshs with multiple materials, however it does
  414. # support materials with multiple submaterials
  415. node = scene.GetRootNode()
  416. if node:
  417. for i in range(node.GetChildCount()):
  418. generate_materials_from_hierarchy(node.GetChild(i), material_dict)
  419. return material_dict
  420. # #####################################################
  421. # Generate Texture Object
  422. # #####################################################
  423. def generate_texture_object(texture):
  424. #TODO: extract more texture properties
  425. wrap_u = texture.GetWrapModeU()
  426. wrap_v = texture.GetWrapModeV()
  427. offset = texture.GetUVTranslation()
  428. if type(texture) is FbxFileTexture:
  429. url = texture.GetFileName()
  430. else:
  431. url = getTextureName( texture )
  432. url = replace_inFolder2OutFolder( url )
  433. output = {
  434. 'url': url,
  435. 'repeat': serializeVector2( (1,1) ),
  436. 'offset': serializeVector2( texture.GetUVTranslation() ),
  437. 'magFilter': 'LinearFilter',
  438. 'minFilter': 'LinearMipMapLinearFilter',
  439. 'anisotropy': True
  440. }
  441. return output
  442. # #####################################################
  443. # Replace Texture input path to output
  444. # #####################################################
  445. def replace_inFolder2OutFolder(url):
  446. folderIndex = url.find(inputFolder)
  447. if folderIndex != -1:
  448. url = url[ len(inputFolder): ]
  449. url = outputFolder + url
  450. return url
  451. # #####################################################
  452. # Replace Texture output path to input
  453. # #####################################################
  454. def replace_OutFolder2inFolder(url):
  455. folderIndex = url.find(outputFolder)
  456. if folderIndex != -1:
  457. url = url[ len(outputFolder): ]
  458. url = inputFolder + url
  459. return url
  460. # #####################################################
  461. # Find Scene Textures
  462. # #####################################################
  463. def extract_material_textures(material_property, texture_dict):
  464. if material_property.IsValid():
  465. #Here we have to check if it's layeredtextures, or just textures:
  466. layered_texture_count = material_property.GetSrcObjectCount(FbxLayeredTexture.ClassId)
  467. if layered_texture_count > 0:
  468. for j in range(layered_texture_count):
  469. layered_texture = material_property.GetSrcObject(FbxLayeredTexture.ClassId, j)
  470. texture_count = layered_texture.GetSrcObjectCount(FbxTexture.ClassId)
  471. for k in range(texture_count):
  472. texture = layered_texture.GetSrcObject(FbxTexture.ClassId,k)
  473. if texture:
  474. texture_object = generate_texture_object(texture)
  475. texture_name = getTextureName( texture, True )
  476. texture_dict[texture_name] = texture_object
  477. else:
  478. # no layered texture simply get on the property
  479. texture_count = material_property.GetSrcObjectCount(FbxTexture.ClassId)
  480. for j in range(texture_count):
  481. texture = material_property.GetSrcObject(FbxTexture.ClassId,j)
  482. if texture:
  483. texture_object = generate_texture_object(texture)
  484. texture_name = getTextureName( texture, True )
  485. texture_dict[texture_name] = texture_object
  486. def extract_textures_from_node(node, texture_dict):
  487. name = node.GetName()
  488. mesh = node.GetNodeAttribute()
  489. #for all materials attached to this mesh
  490. material_count = mesh.GetNode().GetSrcObjectCount(FbxSurfaceMaterial.ClassId)
  491. for material_index in range(material_count):
  492. material = mesh.GetNode().GetSrcObject(FbxSurfaceMaterial.ClassId, material_index)
  493. #go through all the possible textures types
  494. if material:
  495. texture_count = FbxLayerElement.sTypeTextureCount()
  496. for texture_index in range(texture_count):
  497. material_property = material.FindProperty(FbxLayerElement.sTextureChannelNames(texture_index))
  498. extract_material_textures(material_property, texture_dict)
  499. def generate_textures_from_hierarchy(node, texture_dict):
  500. if node.GetNodeAttribute() == None:
  501. pass
  502. else:
  503. attribute_type = (node.GetNodeAttribute().GetAttributeType())
  504. if attribute_type == FbxNodeAttribute.eMesh:
  505. extract_textures_from_node(node, texture_dict)
  506. for i in range(node.GetChildCount()):
  507. generate_textures_from_hierarchy(node.GetChild(i), texture_dict)
  508. def generate_texture_dict(scene):
  509. if not option_textures:
  510. return {}
  511. texture_dict = {}
  512. node = scene.GetRootNode()
  513. if node:
  514. for i in range(node.GetChildCount()):
  515. generate_textures_from_hierarchy(node.GetChild(i), texture_dict)
  516. return texture_dict
  517. # #####################################################
  518. # Extract Fbx SDK Mesh Data
  519. # #####################################################
  520. def extract_fbx_vertex_positions(mesh):
  521. control_points_count = mesh.GetControlPointsCount()
  522. control_points = mesh.GetControlPoints()
  523. positions = []
  524. for i in range(control_points_count):
  525. tmp = control_points[i]
  526. tmp = [tmp[0], tmp[1], tmp[2]]
  527. positions.append(tmp)
  528. node = mesh.GetNode()
  529. if node:
  530. t = node.GeometricTranslation.Get()
  531. t = FbxVector4(t[0], t[1], t[2], 1)
  532. r = node.GeometricRotation.Get()
  533. r = FbxVector4(r[0], r[1], r[2], 1)
  534. s = node.GeometricScaling.Get()
  535. s = FbxVector4(s[0], s[1], s[2], 1)
  536. hasGeometricTransform = False
  537. if t[0] != 0 or t[1] != 0 or t[2] != 0 or \
  538. r[0] != 0 or r[1] != 0 or r[2] != 0 or \
  539. s[0] != 1 or s[1] != 1 or s[2] != 1:
  540. hasGeometricTransform = True
  541. if hasGeometricTransform:
  542. geo_transform = FbxMatrix(t,r,s)
  543. else:
  544. geo_transform = FbxMatrix()
  545. transform = None
  546. if option_geometry:
  547. # FbxMeshes are local to their node, we need the vertices in global space
  548. # when scene nodes are not exported
  549. transform = node.EvaluateGlobalTransform()
  550. transform = FbxMatrix(transform) * geo_transform
  551. elif hasGeometricTransform:
  552. transform = geo_transform
  553. if transform:
  554. for i in range(len(positions)):
  555. v = positions[i]
  556. position = FbxVector4(v[0], v[1], v[2])
  557. position = transform.MultNormalize(position)
  558. positions[i] = [position[0], position[1], position[2]]
  559. return positions
  560. def extract_fbx_vertex_normals(mesh):
  561. # eNone The mapping is undetermined.
  562. # eByControlPoint There will be one mapping coordinate for each surface control point/vertex.
  563. # 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.
  564. # eByPolygon There can be only one mapping coordinate for the whole polygon.
  565. # eByEdge There will be one mapping coordinate for each unique edge in the mesh. This is meant to be used with smoothing layer elements.
  566. # eAllSame There can be only one mapping coordinate for the whole surface.
  567. layered_normal_indices = []
  568. layered_normal_values = []
  569. poly_count = mesh.GetPolygonCount()
  570. control_points = mesh.GetControlPoints()
  571. for l in range(mesh.GetLayerCount()):
  572. mesh_normals = mesh.GetLayer(l).GetNormals()
  573. if not mesh_normals:
  574. continue
  575. normals_array = mesh_normals.GetDirectArray()
  576. normals_count = normals_array.GetCount()
  577. if normals_count == 0:
  578. continue
  579. normal_indices = []
  580. normal_values = []
  581. # values
  582. for i in range(normals_count):
  583. normal = normals_array.GetAt(i)
  584. normal = [normal[0], normal[1], normal[2]]
  585. normal_values.append(normal)
  586. node = mesh.GetNode()
  587. if node:
  588. t = node.GeometricTranslation.Get()
  589. t = FbxVector4(t[0], t[1], t[2], 1)
  590. r = node.GeometricRotation.Get()
  591. r = FbxVector4(r[0], r[1], r[2], 1)
  592. s = node.GeometricScaling.Get()
  593. s = FbxVector4(s[0], s[1], s[2], 1)
  594. hasGeometricTransform = False
  595. if t[0] != 0 or t[1] != 0 or t[2] != 0 or \
  596. r[0] != 0 or r[1] != 0 or r[2] != 0 or \
  597. s[0] != 1 or s[1] != 1 or s[2] != 1:
  598. hasGeometricTransform = True
  599. if hasGeometricTransform:
  600. geo_transform = FbxMatrix(t,r,s)
  601. else:
  602. geo_transform = FbxMatrix()
  603. transform = None
  604. if option_geometry:
  605. # FbxMeshes are local to their node, we need the vertices in global space
  606. # when scene nodes are not exported
  607. transform = node.EvaluateGlobalTransform()
  608. transform = FbxMatrix(transform) * geo_transform
  609. elif hasGeometricTransform:
  610. transform = geo_transform
  611. if transform:
  612. t = FbxVector4(0,0,0,1)
  613. transform.SetRow(3, t)
  614. for i in range(len(normal_values)):
  615. n = normal_values[i]
  616. normal = FbxVector4(n[0], n[1], n[2])
  617. normal = transform.MultNormalize(normal)
  618. normal.Normalize()
  619. normal = [normal[0], normal[1], normal[2]]
  620. normal_values[i] = normal
  621. # indices
  622. vertexId = 0
  623. for p in range(poly_count):
  624. poly_size = mesh.GetPolygonSize(p)
  625. poly_normals = []
  626. for v in range(poly_size):
  627. control_point_index = mesh.GetPolygonVertex(p, v)
  628. # mapping mode is by control points. The mesh should be smooth and soft.
  629. # we can get normals by retrieving each control point
  630. if mesh_normals.GetMappingMode() == FbxLayerElement.eByControlPoint:
  631. # reference mode is direct, the normal index is same as vertex index.
  632. # get normals by the index of control vertex
  633. if mesh_normals.GetReferenceMode() == FbxLayerElement.eDirect:
  634. poly_normals.append(control_point_index)
  635. elif mesh_normals.GetReferenceMode() == FbxLayerElement.eIndexToDirect:
  636. index = mesh_normals.GetIndexArray().GetAt(control_point_index)
  637. poly_normals.append(index)
  638. # mapping mode is by polygon-vertex.
  639. # we can get normals by retrieving polygon-vertex.
  640. elif mesh_normals.GetMappingMode() == FbxLayerElement.eByPolygonVertex:
  641. if mesh_normals.GetReferenceMode() == FbxLayerElement.eDirect:
  642. poly_normals.append(vertexId)
  643. elif mesh_normals.GetReferenceMode() == FbxLayerElement.eIndexToDirect:
  644. index = mesh_normals.GetIndexArray().GetAt(vertexId)
  645. poly_normals.append(index)
  646. elif mesh_normals.GetMappingMode() == FbxLayerElement.eByPolygon or \
  647. mesh_normals.GetMappingMode() == FbxLayerElement.eAllSame or \
  648. mesh_normals.GetMappingMode() == FbxLayerElement.eNone:
  649. print("unsupported normal mapping mode for polygon vertex")
  650. vertexId += 1
  651. normal_indices.append(poly_normals)
  652. layered_normal_values.append(normal_values)
  653. layered_normal_indices.append(normal_indices)
  654. normal_values = []
  655. normal_indices = []
  656. # Three.js only supports one layer of normals
  657. if len(layered_normal_values) > 0:
  658. normal_values = layered_normal_values[0]
  659. normal_indices = layered_normal_indices[0]
  660. return normal_values, normal_indices
  661. def extract_fbx_vertex_colors(mesh):
  662. # eNone The mapping is undetermined.
  663. # eByControlPoint There will be one mapping coordinate for each surface control point/vertex.
  664. # 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.
  665. # eByPolygon There can be only one mapping coordinate for the whole polygon.
  666. # eByEdge There will be one mapping coordinate for each unique edge in the mesh. This is meant to be used with smoothing layer elements.
  667. # eAllSame There can be only one mapping coordinate for the whole surface.
  668. layered_color_indices = []
  669. layered_color_values = []
  670. poly_count = mesh.GetPolygonCount()
  671. control_points = mesh.GetControlPoints()
  672. for l in range(mesh.GetLayerCount()):
  673. mesh_colors = mesh.GetLayer(l).GetVertexColors()
  674. if not mesh_colors:
  675. continue
  676. colors_array = mesh_colors.GetDirectArray()
  677. colors_count = colors_array.GetCount()
  678. if colors_count == 0:
  679. continue
  680. color_indices = []
  681. color_values = []
  682. # values
  683. for i in range(colors_count):
  684. color = colors_array.GetAt(i)
  685. color = [color.mRed, color.mGreen, color.mBlue, color.mAlpha]
  686. color_values.append(color)
  687. # indices
  688. vertexId = 0
  689. for p in range(poly_count):
  690. poly_size = mesh.GetPolygonSize(p)
  691. poly_colors = []
  692. for v in range(poly_size):
  693. control_point_index = mesh.GetPolygonVertex(p, v)
  694. if mesh_colors.GetMappingMode() == FbxLayerElement.eByControlPoint:
  695. if mesh_colors.GetReferenceMode() == FbxLayerElement.eDirect:
  696. poly_colors.append(control_point_index)
  697. elif mesh_colors.GetReferenceMode() == FbxLayerElement.eIndexToDirect:
  698. index = mesh_colors.GetIndexArray().GetAt(control_point_index)
  699. poly_colors.append(index)
  700. elif mesh_colors.GetMappingMode() == FbxLayerElement.eByPolygonVertex:
  701. if mesh_colors.GetReferenceMode() == FbxLayerElement.eDirect:
  702. poly_colors.append(vertexId)
  703. elif mesh_colors.GetReferenceMode() == FbxLayerElement.eIndexToDirect:
  704. index = mesh_colors.GetIndexArray().GetAt(vertexId)
  705. poly_colors.append(index)
  706. elif mesh_colors.GetMappingMode() == FbxLayerElement.eByPolygon or \
  707. mesh_colors.GetMappingMode() == FbxLayerElement.eAllSame or \
  708. mesh_colors.GetMappingMode() == FbxLayerElement.eNone:
  709. print("unsupported color mapping mode for polygon vertex")
  710. vertexId += 1
  711. color_indices.append(poly_colors)
  712. color_values = []
  713. color_indices = []
  714. # Three.js only supports one layer of colors
  715. if len(layered_color_values) > 0:
  716. color_values = layered_color_values[0]
  717. color_indices = layered_color_indices[0]
  718. '''
  719. # The Fbx SDK defaults mesh.Color to (0.8, 0.8, 0.8)
  720. # This causes most models to receive incorrect vertex colors
  721. if len(color_values) == 0:
  722. color = mesh.Color.Get()
  723. color_values = [[color[0], color[1], color[2]]]
  724. color_indices = []
  725. for p in range(poly_count):
  726. poly_size = mesh.GetPolygonSize(p)
  727. color_indices.append([0] * poly_size)
  728. '''
  729. return color_values, color_indices
  730. def extract_fbx_vertex_uvs(mesh):
  731. # eNone The mapping is undetermined.
  732. # eByControlPoint There will be one mapping coordinate for each surface control point/vertex.
  733. # 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.
  734. # eByPolygon There can be only one mapping coordinate for the whole polygon.
  735. # eByEdge There will be one mapping coordinate for each unique edge in the mesh. This is meant to be used with smoothing layer elements.
  736. # eAllSame There can be only one mapping coordinate for the whole surface.
  737. layered_uv_indices = []
  738. layered_uv_values = []
  739. poly_count = mesh.GetPolygonCount()
  740. control_points = mesh.GetControlPoints()
  741. for l in range(mesh.GetLayerCount()):
  742. mesh_uvs = mesh.GetLayer(l).GetUVs()
  743. if not mesh_uvs:
  744. continue
  745. uvs_array = mesh_uvs.GetDirectArray()
  746. uvs_count = uvs_array.GetCount()
  747. if uvs_count == 0:
  748. continue
  749. uv_indices = []
  750. uv_values = []
  751. # values
  752. for i in range(uvs_count):
  753. uv = uvs_array.GetAt(i)
  754. uv = [uv[0], uv[1]]
  755. uv_values.append(uv)
  756. # indices
  757. vertexId = 0
  758. for p in range(poly_count):
  759. poly_size = mesh.GetPolygonSize(p)
  760. poly_uvs = []
  761. for v in range(poly_size):
  762. control_point_index = mesh.GetPolygonVertex(p, v)
  763. if mesh_uvs.GetMappingMode() == FbxLayerElement.eByControlPoint:
  764. if mesh_uvs.GetReferenceMode() == FbxLayerElement.eDirect:
  765. poly_uvs.append(control_point_index)
  766. elif mesh_uvs.GetReferenceMode() == FbxLayerElement.eIndexToDirect:
  767. index = mesh_uvs.GetIndexArray().GetAt(control_point_index)
  768. poly_uvs.append(index)
  769. elif mesh_uvs.GetMappingMode() == FbxLayerElement.eByPolygonVertex:
  770. # uv_texture_index = mesh.GetTextureUVIndex(p, v) # comment for fix COLLADA uv bug
  771. uv_texture_index = mesh_uvs.GetIndexArray().GetAt(vertexId)
  772. if mesh_uvs.GetReferenceMode() == FbxLayerElement.eDirect or \
  773. mesh_uvs.GetReferenceMode() == FbxLayerElement.eIndexToDirect:
  774. poly_uvs.append(uv_texture_index)
  775. elif mesh_uvs.GetMappingMode() == FbxLayerElement.eByPolygon or \
  776. mesh_uvs.GetMappingMode() == FbxLayerElement.eAllSame or \
  777. mesh_uvs.GetMappingMode() == FbxLayerElement.eNone:
  778. print("unsupported uv mapping mode for polygon vertex")
  779. vertexId += 1
  780. uv_indices.append(poly_uvs)
  781. layered_uv_values.append(uv_values)
  782. layered_uv_indices.append(uv_indices)
  783. return layered_uv_values, layered_uv_indices
  784. # #####################################################
  785. # Process Mesh Geometry
  786. # #####################################################
  787. def generate_normal_key(normal):
  788. return (round(normal[0], 6), round(normal[1], 6), round(normal[2], 6))
  789. def generate_color_key(color):
  790. return getHex(color)
  791. def generate_uv_key(uv):
  792. return (round(uv[0], 6), round(uv[1], 6))
  793. def append_non_duplicate_uvs(source_uvs, dest_uvs, counts):
  794. source_layer_count = len(source_uvs)
  795. for layer_index in range(source_layer_count):
  796. dest_layer_count = len(dest_uvs)
  797. if dest_layer_count <= layer_index:
  798. dest_uv_layer = {}
  799. count = 0
  800. dest_uvs.append(dest_uv_layer)
  801. counts.append(count)
  802. else:
  803. dest_uv_layer = dest_uvs[layer_index]
  804. count = counts[layer_index]
  805. source_uv_layer = source_uvs[layer_index]
  806. for uv in source_uv_layer:
  807. key = generate_uv_key(uv)
  808. if key not in dest_uv_layer:
  809. dest_uv_layer[key] = count
  810. count += 1
  811. counts[layer_index] = count
  812. return counts
  813. def generate_unique_normals_dictionary(mesh_list):
  814. normals_dictionary = {}
  815. nnormals = 0
  816. # Merge meshes, remove duplicate data
  817. for mesh in mesh_list:
  818. node = mesh.GetNode()
  819. normal_values, normal_indices = extract_fbx_vertex_normals(mesh)
  820. if len(normal_values) > 0:
  821. for normal in normal_values:
  822. key = generate_normal_key(normal)
  823. if key not in normals_dictionary:
  824. normals_dictionary[key] = nnormals
  825. nnormals += 1
  826. return normals_dictionary
  827. def generate_unique_colors_dictionary(mesh_list):
  828. colors_dictionary = {}
  829. ncolors = 0
  830. # Merge meshes, remove duplicate data
  831. for mesh in mesh_list:
  832. color_values, color_indices = extract_fbx_vertex_colors(mesh)
  833. if len(color_values) > 0:
  834. for color in color_values:
  835. key = generate_color_key(color)
  836. if key not in colors_dictionary:
  837. colors_dictionary[key] = ncolors
  838. ncolors += 1
  839. return colors_dictionary
  840. def generate_unique_uvs_dictionary_layers(mesh_list):
  841. uvs_dictionary_layers = []
  842. nuvs_list = []
  843. # Merge meshes, remove duplicate data
  844. for mesh in mesh_list:
  845. uv_values, uv_indices = extract_fbx_vertex_uvs(mesh)
  846. if len(uv_values) > 0:
  847. nuvs_list = append_non_duplicate_uvs(uv_values, uvs_dictionary_layers, nuvs_list)
  848. return uvs_dictionary_layers
  849. def generate_normals_from_dictionary(normals_dictionary):
  850. normal_values = []
  851. for key, index in sorted(normals_dictionary.items(), key = operator.itemgetter(1)):
  852. normal_values.append(key)
  853. return normal_values
  854. def generate_colors_from_dictionary(colors_dictionary):
  855. color_values = []
  856. for key, index in sorted(colors_dictionary.items(), key = operator.itemgetter(1)):
  857. color_values.append(key)
  858. return color_values
  859. def generate_uvs_from_dictionary_layers(uvs_dictionary_layers):
  860. uv_values = []
  861. for uvs_dictionary in uvs_dictionary_layers:
  862. uv_values_layer = []
  863. for key, index in sorted(uvs_dictionary.items(), key = operator.itemgetter(1)):
  864. uv_values_layer.append(key)
  865. uv_values.append(uv_values_layer)
  866. return uv_values
  867. def generate_normal_indices_for_poly(poly_index, mesh_normal_values, mesh_normal_indices, normals_to_indices):
  868. if len(mesh_normal_indices) <= 0:
  869. return []
  870. poly_normal_indices = mesh_normal_indices[poly_index]
  871. poly_size = len(poly_normal_indices)
  872. output_poly_normal_indices = []
  873. for v in range(poly_size):
  874. normal_index = poly_normal_indices[v]
  875. normal_value = mesh_normal_values[normal_index]
  876. key = generate_normal_key(normal_value)
  877. output_index = normals_to_indices[key]
  878. output_poly_normal_indices.append(output_index)
  879. return output_poly_normal_indices
  880. def generate_color_indices_for_poly(poly_index, mesh_color_values, mesh_color_indices, colors_to_indices):
  881. if len(mesh_color_indices) <= 0:
  882. return []
  883. poly_color_indices = mesh_color_indices[poly_index]
  884. poly_size = len(poly_color_indices)
  885. output_poly_color_indices = []
  886. for v in range(poly_size):
  887. color_index = poly_color_indices[v]
  888. color_value = mesh_color_values[color_index]
  889. key = generate_color_key(color_value)
  890. output_index = colors_to_indices[key]
  891. output_poly_color_indices.append(output_index)
  892. return output_poly_color_indices
  893. def generate_uv_indices_for_poly(poly_index, mesh_uv_values, mesh_uv_indices, uvs_to_indices):
  894. if len(mesh_uv_indices) <= 0:
  895. return []
  896. poly_uv_indices = mesh_uv_indices[poly_index]
  897. poly_size = len(poly_uv_indices)
  898. output_poly_uv_indices = []
  899. for v in range(poly_size):
  900. uv_index = poly_uv_indices[v]
  901. uv_value = mesh_uv_values[uv_index]
  902. key = generate_uv_key(uv_value)
  903. output_index = uvs_to_indices[key]
  904. output_poly_uv_indices.append(output_index)
  905. return output_poly_uv_indices
  906. def process_mesh_vertices(mesh_list):
  907. vertex_offset = 0
  908. vertex_offset_list = [0]
  909. vertices = []
  910. for mesh in mesh_list:
  911. node = mesh.GetNode()
  912. mesh_vertices = extract_fbx_vertex_positions(mesh)
  913. vertices.extend(mesh_vertices[:])
  914. vertex_offset += len(mesh_vertices)
  915. vertex_offset_list.append(vertex_offset)
  916. return vertices, vertex_offset_list
  917. def process_mesh_materials(mesh_list):
  918. material_offset = 0
  919. material_offset_list = [0]
  920. materials_list = []
  921. #TODO: remove duplicate mesh references
  922. for mesh in mesh_list:
  923. node = mesh.GetNode()
  924. material_count = node.GetMaterialCount()
  925. if material_count > 0:
  926. for l in range(mesh.GetLayerCount()):
  927. materials = mesh.GetLayer(l).GetMaterials()
  928. if materials:
  929. if materials.GetReferenceMode() == FbxLayerElement.eIndex:
  930. #Materials are in an undefined external table
  931. continue
  932. for i in range(material_count):
  933. material = node.GetMaterial(i)
  934. materials_list.append( material )
  935. material_offset += material_count
  936. material_offset_list.append(material_offset)
  937. return materials_list, material_offset_list
  938. def process_mesh_polygons(mesh_list, normals_to_indices, colors_to_indices, uvs_to_indices_list, vertex_offset_list, material_offset_list):
  939. faces = []
  940. for mesh_index in range(len(mesh_list)):
  941. mesh = mesh_list[mesh_index]
  942. flipWindingOrder = False
  943. node = mesh.GetNode()
  944. if node:
  945. local_scale = node.EvaluateLocalScaling()
  946. if local_scale[0] < 0 or local_scale[1] < 0 or local_scale[2] < 0:
  947. flipWindingOrder = True
  948. poly_count = mesh.GetPolygonCount()
  949. control_points = mesh.GetControlPoints()
  950. normal_values, normal_indices = extract_fbx_vertex_normals(mesh)
  951. color_values, color_indices = extract_fbx_vertex_colors(mesh)
  952. uv_values_layers, uv_indices_layers = extract_fbx_vertex_uvs(mesh)
  953. for poly_index in range(poly_count):
  954. poly_size = mesh.GetPolygonSize(poly_index)
  955. face_normals = generate_normal_indices_for_poly(poly_index, normal_values, normal_indices, normals_to_indices)
  956. face_colors = generate_color_indices_for_poly(poly_index, color_values, color_indices, colors_to_indices)
  957. face_uv_layers = []
  958. for l in range(len(uv_indices_layers)):
  959. uv_values = uv_values_layers[l]
  960. uv_indices = uv_indices_layers[l]
  961. face_uv_indices = generate_uv_indices_for_poly(poly_index, uv_values, uv_indices, uvs_to_indices_list[l])
  962. face_uv_layers.append(face_uv_indices)
  963. face_vertices = []
  964. for vertex_index in range(poly_size):
  965. control_point_index = mesh.GetPolygonVertex(poly_index, vertex_index)
  966. face_vertices.append(control_point_index)
  967. #TODO: assign a default material to any mesh without one
  968. if len(material_offset_list) <= mesh_index:
  969. material_offset = 0
  970. else:
  971. material_offset = material_offset_list[mesh_index]
  972. vertex_offset = vertex_offset_list[mesh_index]
  973. if poly_size > 4:
  974. new_face_normals = []
  975. new_face_colors = []
  976. new_face_uv_layers = []
  977. for i in range(poly_size - 2):
  978. new_face_vertices = [face_vertices[0], face_vertices[i+1], face_vertices[i+2]]
  979. if len(face_normals):
  980. new_face_normals = [face_normals[0], face_normals[i+1], face_normals[i+2]]
  981. if len(face_colors):
  982. new_face_colors = [face_colors[0], face_colors[i+1], face_colors[i+2]]
  983. if len(face_uv_layers):
  984. new_face_uv_layers = []
  985. for layer in face_uv_layers:
  986. new_face_uv_layers.append([layer[0], layer[i+1], layer[i+2]])
  987. face = generate_mesh_face(mesh,
  988. poly_index,
  989. new_face_vertices,
  990. new_face_normals,
  991. new_face_colors,
  992. new_face_uv_layers,
  993. vertex_offset,
  994. material_offset,
  995. flipWindingOrder)
  996. faces.append(face)
  997. else:
  998. face = generate_mesh_face(mesh,
  999. poly_index,
  1000. face_vertices,
  1001. face_normals,
  1002. face_colors,
  1003. face_uv_layers,
  1004. vertex_offset,
  1005. material_offset,
  1006. flipWindingOrder)
  1007. faces.append(face)
  1008. return faces
  1009. def generate_mesh_face(mesh, polygon_index, vertex_indices, normals, colors, uv_layers, vertex_offset, material_offset, flipOrder):
  1010. isTriangle = ( len(vertex_indices) == 3 )
  1011. nVertices = 3 if isTriangle else 4
  1012. hasMaterial = False
  1013. for l in range(mesh.GetLayerCount()):
  1014. materials = mesh.GetLayer(l).GetMaterials()
  1015. if materials:
  1016. hasMaterial = True
  1017. break
  1018. hasFaceUvs = False
  1019. hasFaceVertexUvs = len(uv_layers) > 0
  1020. hasFaceNormals = False
  1021. hasFaceVertexNormals = len(normals) > 0
  1022. hasFaceColors = False
  1023. hasFaceVertexColors = len(colors) > 0
  1024. faceType = 0
  1025. faceType = setBit(faceType, 0, not isTriangle)
  1026. faceType = setBit(faceType, 1, hasMaterial)
  1027. faceType = setBit(faceType, 2, hasFaceUvs)
  1028. faceType = setBit(faceType, 3, hasFaceVertexUvs)
  1029. faceType = setBit(faceType, 4, hasFaceNormals)
  1030. faceType = setBit(faceType, 5, hasFaceVertexNormals)
  1031. faceType = setBit(faceType, 6, hasFaceColors)
  1032. faceType = setBit(faceType, 7, hasFaceVertexColors)
  1033. faceData = []
  1034. # order is important, must match order in JSONLoader
  1035. # face type
  1036. # vertex indices
  1037. # material index
  1038. # face uvs index
  1039. # face vertex uvs indices
  1040. # face color index
  1041. # face vertex colors indices
  1042. faceData.append(faceType)
  1043. if flipOrder:
  1044. if nVertices == 3:
  1045. vertex_indices = [vertex_indices[0], vertex_indices[2], vertex_indices[1]]
  1046. if hasFaceVertexNormals:
  1047. normals = [normals[0], normals[2], normals[1]]
  1048. if hasFaceVertexColors:
  1049. colors = [colors[0], colors[2], colors[1]]
  1050. if hasFaceVertexUvs:
  1051. tmp = []
  1052. for polygon_uvs in uv_layers:
  1053. tmp.append([polygon_uvs[0], polygon_uvs[2], polygon_uvs[1]])
  1054. uv_layers = tmp
  1055. else:
  1056. vertex_indices = [vertex_indices[0], vertex_indices[3], vertex_indices[2], vertex_indices[1]]
  1057. if hasFaceVertexNormals:
  1058. normals = [normals[0], normals[3], normals[2], normals[1]]
  1059. if hasFaceVertexColors:
  1060. colors = [colors[0], colors[3], colors[2], colors[1]]
  1061. if hasFaceVertexUvs:
  1062. tmp = []
  1063. for polygon_uvs in uv_layers:
  1064. tmp.append([polygon_uvs[0], polygon_uvs[3], polygon_uvs[2], polygon_uvs[3]])
  1065. uv_layers = tmp
  1066. for i in range(nVertices):
  1067. index = vertex_indices[i] + vertex_offset
  1068. faceData.append(index)
  1069. if hasMaterial:
  1070. material_id = 0
  1071. for l in range(mesh.GetLayerCount()):
  1072. materials = mesh.GetLayer(l).GetMaterials()
  1073. if materials:
  1074. material_id = materials.GetIndexArray().GetAt(polygon_index)
  1075. break
  1076. material_id += material_offset
  1077. faceData.append( material_id )
  1078. if hasFaceVertexUvs:
  1079. for polygon_uvs in uv_layers:
  1080. for i in range(nVertices):
  1081. index = polygon_uvs[i]
  1082. faceData.append(index)
  1083. if hasFaceVertexNormals:
  1084. for i in range(nVertices):
  1085. index = normals[i]
  1086. faceData.append(index)
  1087. if hasFaceVertexColors:
  1088. for i in range(nVertices):
  1089. index = colors[i]
  1090. faceData.append(index)
  1091. return faceData
  1092. # #####################################################
  1093. # Generate Mesh Object (for scene output format)
  1094. # #####################################################
  1095. def generate_scene_output(node):
  1096. mesh = node.GetNodeAttribute()
  1097. # This is done in order to keep the scene output and non-scene output code DRY
  1098. mesh_list = [ mesh ]
  1099. # Extract the mesh data into arrays
  1100. vertices, vertex_offsets = process_mesh_vertices(mesh_list)
  1101. materials, material_offsets = process_mesh_materials(mesh_list)
  1102. normals_to_indices = generate_unique_normals_dictionary(mesh_list)
  1103. colors_to_indices = generate_unique_colors_dictionary(mesh_list)
  1104. uvs_to_indices_list = generate_unique_uvs_dictionary_layers(mesh_list)
  1105. normal_values = generate_normals_from_dictionary(normals_to_indices)
  1106. color_values = generate_colors_from_dictionary(colors_to_indices)
  1107. uv_values = generate_uvs_from_dictionary_layers(uvs_to_indices_list)
  1108. # Generate mesh faces for the Three.js file format
  1109. faces = process_mesh_polygons(mesh_list,
  1110. normals_to_indices,
  1111. colors_to_indices,
  1112. uvs_to_indices_list,
  1113. vertex_offsets,
  1114. material_offsets)
  1115. # Generate counts for uvs, vertices, normals, colors, and faces
  1116. nuvs = []
  1117. for layer_index, uvs in enumerate(uv_values):
  1118. nuvs.append(str(len(uvs)))
  1119. nvertices = len(vertices)
  1120. nnormals = len(normal_values)
  1121. ncolors = len(color_values)
  1122. nfaces = len(faces)
  1123. # Flatten the arrays, currently they are in the form of [[0, 1, 2], [3, 4, 5], ...]
  1124. vertices = [val for v in vertices for val in v]
  1125. normal_values = [val for n in normal_values for val in n]
  1126. color_values = [c for c in color_values]
  1127. faces = [val for f in faces for val in f]
  1128. uv_values = generate_uvs(uv_values)
  1129. # Disable automatic json indenting when pretty printing for the arrays
  1130. if option_pretty_print:
  1131. nuvs = NoIndent(nuvs)
  1132. vertices = ChunkedIndent(vertices, 15, True)
  1133. normal_values = ChunkedIndent(normal_values, 15, True)
  1134. color_values = ChunkedIndent(color_values, 15)
  1135. faces = ChunkedIndent(faces, 30)
  1136. metadata = {
  1137. 'vertices' : nvertices,
  1138. 'normals' : nnormals,
  1139. 'colors' : ncolors,
  1140. 'faces' : nfaces,
  1141. 'uvs' : nuvs
  1142. }
  1143. output = {
  1144. 'scale' : 1,
  1145. 'materials' : [],
  1146. 'vertices' : vertices,
  1147. 'normals' : [] if nnormals <= 0 else normal_values,
  1148. 'colors' : [] if ncolors <= 0 else color_values,
  1149. 'uvs' : uv_values,
  1150. 'faces' : faces
  1151. }
  1152. if option_pretty_print:
  1153. output['0metadata'] = metadata
  1154. else:
  1155. output['metadata'] = metadata
  1156. return output
  1157. # #####################################################
  1158. # Generate Mesh Object (for non-scene output)
  1159. # #####################################################
  1160. def generate_non_scene_output(scene):
  1161. mesh_list = generate_mesh_list(scene)
  1162. # Extract the mesh data into arrays
  1163. vertices, vertex_offsets = process_mesh_vertices(mesh_list)
  1164. materials, material_offsets = process_mesh_materials(mesh_list)
  1165. normals_to_indices = generate_unique_normals_dictionary(mesh_list)
  1166. colors_to_indices = generate_unique_colors_dictionary(mesh_list)
  1167. uvs_to_indices_list = generate_unique_uvs_dictionary_layers(mesh_list)
  1168. normal_values = generate_normals_from_dictionary(normals_to_indices)
  1169. color_values = generate_colors_from_dictionary(colors_to_indices)
  1170. uv_values = generate_uvs_from_dictionary_layers(uvs_to_indices_list)
  1171. # Generate mesh faces for the Three.js file format
  1172. faces = process_mesh_polygons(mesh_list,
  1173. normals_to_indices,
  1174. colors_to_indices,
  1175. uvs_to_indices_list,
  1176. vertex_offsets,
  1177. material_offsets)
  1178. # Generate counts for uvs, vertices, normals, colors, and faces
  1179. nuvs = []
  1180. for layer_index, uvs in enumerate(uv_values):
  1181. nuvs.append(str(len(uvs)))
  1182. nvertices = len(vertices)
  1183. nnormals = len(normal_values)
  1184. ncolors = len(color_values)
  1185. nfaces = len(faces)
  1186. # Flatten the arrays, currently they are in the form of [[0, 1, 2], [3, 4, 5], ...]
  1187. vertices = [val for v in vertices for val in v]
  1188. normal_values = [val for n in normal_values for val in n]
  1189. color_values = [c for c in color_values]
  1190. faces = [val for f in faces for val in f]
  1191. uv_values = generate_uvs(uv_values)
  1192. # Disable json indenting when pretty printing for the arrays
  1193. if option_pretty_print:
  1194. nuvs = NoIndent(nuvs)
  1195. vertices = NoIndent(vertices)
  1196. normal_values = NoIndent(normal_values)
  1197. color_values = NoIndent(color_values)
  1198. faces = NoIndent(faces)
  1199. metadata = {
  1200. 'formatVersion' : 3,
  1201. 'type' : 'geometry',
  1202. 'generatedBy' : 'convert-to-threejs.py',
  1203. 'vertices' : nvertices,
  1204. 'normals' : nnormals,
  1205. 'colors' : ncolors,
  1206. 'faces' : nfaces,
  1207. 'uvs' : nuvs
  1208. }
  1209. output = {
  1210. 'scale' : 1,
  1211. 'materials' : [],
  1212. 'vertices' : vertices,
  1213. 'normals' : [] if nnormals <= 0 else normal_values,
  1214. 'colors' : [] if ncolors <= 0 else color_values,
  1215. 'uvs' : uv_values,
  1216. 'faces' : faces
  1217. }
  1218. if option_pretty_print:
  1219. output['0metadata'] = metadata
  1220. else:
  1221. output['metadata'] = metadata
  1222. return output
  1223. def generate_mesh_list_from_hierarchy(node, mesh_list):
  1224. if node.GetNodeAttribute() == None:
  1225. pass
  1226. else:
  1227. attribute_type = (node.GetNodeAttribute().GetAttributeType())
  1228. if attribute_type == FbxNodeAttribute.eMesh or \
  1229. attribute_type == FbxNodeAttribute.eNurbs or \
  1230. attribute_type == FbxNodeAttribute.eNurbsSurface or \
  1231. attribute_type == FbxNodeAttribute.ePatch:
  1232. if attribute_type != FbxNodeAttribute.eMesh:
  1233. converter.TriangulateInPlace(node);
  1234. mesh_list.append(node.GetNodeAttribute())
  1235. for i in range(node.GetChildCount()):
  1236. generate_mesh_list_from_hierarchy(node.GetChild(i), mesh_list)
  1237. def generate_mesh_list(scene):
  1238. mesh_list = []
  1239. node = scene.GetRootNode()
  1240. if node:
  1241. for i in range(node.GetChildCount()):
  1242. generate_mesh_list_from_hierarchy(node.GetChild(i), mesh_list)
  1243. return mesh_list
  1244. # #####################################################
  1245. # Generate Embed Objects
  1246. # #####################################################
  1247. def generate_embed_dict_from_hierarchy(node, embed_dict):
  1248. if node.GetNodeAttribute() == None:
  1249. pass
  1250. else:
  1251. attribute_type = (node.GetNodeAttribute().GetAttributeType())
  1252. if attribute_type == FbxNodeAttribute.eMesh or \
  1253. attribute_type == FbxNodeAttribute.eNurbs or \
  1254. attribute_type == FbxNodeAttribute.eNurbsSurface or \
  1255. attribute_type == FbxNodeAttribute.ePatch:
  1256. if attribute_type != FbxNodeAttribute.eMesh:
  1257. converter.TriangulateInPlace(node);
  1258. embed_object = generate_scene_output(node)
  1259. embed_name = getPrefixedName(node, 'Embed')
  1260. embed_dict[embed_name] = embed_object
  1261. for i in range(node.GetChildCount()):
  1262. generate_embed_dict_from_hierarchy(node.GetChild(i), embed_dict)
  1263. def generate_embed_dict(scene):
  1264. embed_dict = {}
  1265. node = scene.GetRootNode()
  1266. if node:
  1267. for i in range(node.GetChildCount()):
  1268. generate_embed_dict_from_hierarchy(node.GetChild(i), embed_dict)
  1269. return embed_dict
  1270. # #####################################################
  1271. # Generate Geometry Objects
  1272. # #####################################################
  1273. def generate_geometry_object(node):
  1274. output = {
  1275. 'type' : 'embedded',
  1276. 'id' : getPrefixedName( node, 'Embed' )
  1277. }
  1278. return output
  1279. def generate_geometry_dict_from_hierarchy(node, geometry_dict):
  1280. if node.GetNodeAttribute() == None:
  1281. pass
  1282. else:
  1283. attribute_type = (node.GetNodeAttribute().GetAttributeType())
  1284. if attribute_type == FbxNodeAttribute.eMesh:
  1285. geometry_object = generate_geometry_object(node)
  1286. geometry_name = getPrefixedName( node, 'Geometry' )
  1287. geometry_dict[geometry_name] = geometry_object
  1288. for i in range(node.GetChildCount()):
  1289. generate_geometry_dict_from_hierarchy(node.GetChild(i), geometry_dict)
  1290. def generate_geometry_dict(scene):
  1291. geometry_dict = {}
  1292. node = scene.GetRootNode()
  1293. if node:
  1294. for i in range(node.GetChildCount()):
  1295. generate_geometry_dict_from_hierarchy(node.GetChild(i), geometry_dict)
  1296. return geometry_dict
  1297. # #####################################################
  1298. # Generate Light Node Objects
  1299. # #####################################################
  1300. def generate_default_light():
  1301. direction = (1,1,1)
  1302. color = (1,1,1)
  1303. intensity = 80.0
  1304. output = {
  1305. 'type': 'DirectionalLight',
  1306. 'color': getHex(color),
  1307. 'intensity': intensity/100.00,
  1308. 'direction': serializeVector3( direction ),
  1309. 'target': getObjectName( None )
  1310. }
  1311. return output
  1312. def generate_light_object(node):
  1313. light = node.GetNodeAttribute()
  1314. light_types = ["point", "directional", "spot", "area", "volume"]
  1315. light_type = light_types[light.LightType.Get()]
  1316. transform = node.EvaluateLocalTransform()
  1317. position = transform.GetT()
  1318. output = None
  1319. if light_type == "directional":
  1320. # Three.js directional lights emit light from a point in 3d space to a target node or the origin.
  1321. # When there is no target, we need to take a point, one unit away from the origin, and move it
  1322. # into the right location so that the origin acts like the target
  1323. if node.GetTarget():
  1324. direction = position
  1325. else:
  1326. translation = FbxVector4(0,0,0,0)
  1327. scale = FbxVector4(1,1,1,1)
  1328. rotation = transform.GetR()
  1329. matrix = FbxMatrix(translation, rotation, scale)
  1330. direction = matrix.MultNormalize(FbxVector4(0,1,0,1))
  1331. output = {
  1332. 'type': 'DirectionalLight',
  1333. 'color': getHex(light.Color.Get()),
  1334. 'intensity': light.Intensity.Get()/100.0,
  1335. 'direction': serializeVector3( direction ),
  1336. 'target': getObjectName( node.GetTarget() )
  1337. }
  1338. elif light_type == "point":
  1339. output = {
  1340. 'type': 'PointLight',
  1341. 'color': getHex(light.Color.Get()),
  1342. 'intensity': light.Intensity.Get()/100.0,
  1343. 'position': serializeVector3( position ),
  1344. 'distance': light.FarAttenuationEnd.Get()
  1345. }
  1346. elif light_type == "spot":
  1347. output = {
  1348. 'type': 'SpotLight',
  1349. 'color': getHex(light.Color.Get()),
  1350. 'intensity': light.Intensity.Get()/100.0,
  1351. 'position': serializeVector3( position ),
  1352. 'distance': light.FarAttenuationEnd.Get(),
  1353. 'angle': light.OuterAngle.Get()*math.pi/180,
  1354. 'exponent': light.DecayType.Get(),
  1355. 'target': getObjectName( node.GetTarget() )
  1356. }
  1357. return output
  1358. def generate_ambient_light(scene):
  1359. scene_settings = scene.GetGlobalSettings()
  1360. ambient_color = scene_settings.GetAmbientColor()
  1361. ambient_color = (ambient_color.mRed, ambient_color.mGreen, ambient_color.mBlue)
  1362. if ambient_color[0] == 0 and ambient_color[1] == 0 and ambient_color[2] == 0:
  1363. return None
  1364. output = {
  1365. 'type': 'AmbientLight',
  1366. 'color': getHex(ambient_color)
  1367. }
  1368. return output
  1369. # #####################################################
  1370. # Generate Camera Node Objects
  1371. # #####################################################
  1372. def generate_default_camera():
  1373. position = (100, 100, 100)
  1374. near = 0.1
  1375. far = 1000
  1376. fov = 75
  1377. output = {
  1378. 'type': 'PerspectiveCamera',
  1379. 'fov': fov,
  1380. 'near': near,
  1381. 'far': far,
  1382. 'position': serializeVector3( position )
  1383. }
  1384. return output
  1385. def generate_camera_object(node):
  1386. camera = node.GetNodeAttribute()
  1387. position = camera.Position.Get()
  1388. projection_types = [ "perspective", "orthogonal" ]
  1389. projection = projection_types[camera.ProjectionType.Get()]
  1390. near = camera.NearPlane.Get()
  1391. far = camera.FarPlane.Get()
  1392. name = getObjectName( node )
  1393. output = {}
  1394. if projection == "perspective":
  1395. aspect = camera.PixelAspectRatio.Get()
  1396. fov = camera.FieldOfView.Get()
  1397. output = {
  1398. 'type': 'PerspectiveCamera',
  1399. 'fov': fov,
  1400. 'aspect': aspect,
  1401. 'near': near,
  1402. 'far': far,
  1403. 'position': serializeVector3( position )
  1404. }
  1405. elif projection == "orthogonal":
  1406. left = ""
  1407. right = ""
  1408. top = ""
  1409. bottom = ""
  1410. output = {
  1411. 'type': 'PerspectiveCamera',
  1412. 'left': left,
  1413. 'right': right,
  1414. 'top': top,
  1415. 'bottom': bottom,
  1416. 'near': near,
  1417. 'far': far,
  1418. 'position': serializeVector3( position )
  1419. }
  1420. return output
  1421. # #####################################################
  1422. # Generate Camera Names
  1423. # #####################################################
  1424. def generate_camera_name_list_from_hierarchy(node, camera_list):
  1425. if node.GetNodeAttribute() == None:
  1426. pass
  1427. else:
  1428. attribute_type = (node.GetNodeAttribute().GetAttributeType())
  1429. if attribute_type == FbxNodeAttribute.eCamera:
  1430. camera_string = getObjectName(node)
  1431. camera_list.append(camera_string)
  1432. for i in range(node.GetChildCount()):
  1433. generate_camera_name_list_from_hierarchy(node.GetChild(i), camera_list)
  1434. def generate_camera_name_list(scene):
  1435. camera_list = []
  1436. node = scene.GetRootNode()
  1437. if node:
  1438. for i in range(node.GetChildCount()):
  1439. generate_camera_name_list_from_hierarchy(node.GetChild(i), camera_list)
  1440. return camera_list
  1441. # #####################################################
  1442. # Generate Mesh Node Object
  1443. # #####################################################
  1444. def generate_mesh_object(node):
  1445. mesh = node.GetNodeAttribute()
  1446. transform = node.EvaluateLocalTransform()
  1447. position = transform.GetT()
  1448. scale = transform.GetS()
  1449. rotation = getRadians(transform.GetR())
  1450. quaternion = transform.GetQ()
  1451. material_count = node.GetMaterialCount()
  1452. material_name = ""
  1453. if material_count > 0:
  1454. material_names = []
  1455. for l in range(mesh.GetLayerCount()):
  1456. materials = mesh.GetLayer(l).GetMaterials()
  1457. if materials:
  1458. if materials.GetReferenceMode() == FbxLayerElement.eIndex:
  1459. #Materials are in an undefined external table
  1460. continue
  1461. for i in range(material_count):
  1462. material = node.GetMaterial(i)
  1463. material_names.append( getMaterialName(material) )
  1464. if not material_count > 1 and not len(material_names) > 0:
  1465. material_names.append('')
  1466. #If this mesh has more than one material, use a proxy material
  1467. material_name = getMaterialName( node, True) if material_count > 1 else material_names[0]
  1468. output = {
  1469. 'geometry': getPrefixedName( node, 'Geometry' ),
  1470. 'material': material_name,
  1471. 'position': serializeVector3( position ),
  1472. 'quaternion': serializeVector4( quaternion ),
  1473. 'scale': serializeVector3( scale ),
  1474. 'visible': True,
  1475. }
  1476. return output
  1477. # #####################################################
  1478. # Generate Node Object
  1479. # #####################################################
  1480. def generate_object(node):
  1481. node_types = ["Unknown", "Null", "Marker", "Skeleton", "Mesh", "Nurbs", "Patch", "Camera",
  1482. "CameraStereo", "CameraSwitcher", "Light", "OpticalReference", "OpticalMarker", "NurbsCurve",
  1483. "TrimNurbsSurface", "Boundary", "NurbsSurface", "Shape", "LODGroup", "SubDiv", "CachedEffect", "Line"]
  1484. transform = node.EvaluateLocalTransform()
  1485. position = transform.GetT()
  1486. scale = transform.GetS()
  1487. rotation = getRadians(transform.GetR())
  1488. quaternion = transform.GetQ()
  1489. node_type = ""
  1490. if node.GetNodeAttribute() == None:
  1491. node_type = "Null"
  1492. else:
  1493. node_type = node_types[node.GetNodeAttribute().GetAttributeType()]
  1494. name = getObjectName( node )
  1495. output = {
  1496. 'fbx_type': node_type,
  1497. 'position': serializeVector3( position ),
  1498. 'quaternion': serializeVector4( quaternion ),
  1499. 'scale': serializeVector3( scale ),
  1500. 'visible': True
  1501. }
  1502. return output
  1503. # #####################################################
  1504. # Parse Scene Node Objects
  1505. # #####################################################
  1506. def generate_object_hierarchy(node, object_dict):
  1507. object_count = 0
  1508. if node.GetNodeAttribute() == None:
  1509. object_data = generate_object(node)
  1510. else:
  1511. attribute_type = (node.GetNodeAttribute().GetAttributeType())
  1512. if attribute_type == FbxNodeAttribute.eMesh:
  1513. object_data = generate_mesh_object(node)
  1514. elif attribute_type == FbxNodeAttribute.eLight:
  1515. object_data = generate_light_object(node)
  1516. elif attribute_type == FbxNodeAttribute.eCamera:
  1517. object_data = generate_camera_object(node)
  1518. else:
  1519. object_data = generate_object(node)
  1520. object_count += 1
  1521. object_name = getObjectName(node)
  1522. object_children = {}
  1523. for i in range(node.GetChildCount()):
  1524. object_count += generate_object_hierarchy(node.GetChild(i), object_children)
  1525. if node.GetChildCount() > 0:
  1526. # Having 'children' above other attributes is hard to read.
  1527. # We can send it to the bottom using the last letter of the alphabet 'z'.
  1528. # This letter is removed from the final output.
  1529. if option_pretty_print:
  1530. object_data['zchildren'] = object_children
  1531. else:
  1532. object_data['children'] = object_children
  1533. object_dict[object_name] = object_data
  1534. return object_count
  1535. def generate_scene_objects(scene):
  1536. object_count = 0
  1537. object_dict = {}
  1538. ambient_light = generate_ambient_light(scene)
  1539. if ambient_light:
  1540. object_dict['AmbientLight'] = ambient_light
  1541. object_count += 1
  1542. if option_default_light:
  1543. default_light = generate_default_light()
  1544. object_dict['DefaultLight'] = default_light
  1545. object_count += 1
  1546. if option_default_camera:
  1547. default_camera = generate_default_camera()
  1548. object_dict['DefaultCamera'] = default_camera
  1549. object_count += 1
  1550. node = scene.GetRootNode()
  1551. if node:
  1552. for i in range(node.GetChildCount()):
  1553. object_count += generate_object_hierarchy(node.GetChild(i), object_dict)
  1554. return object_dict, object_count
  1555. # #####################################################
  1556. # Generate Scene Output
  1557. # #####################################################
  1558. def extract_scene(scene, filename):
  1559. global_settings = scene.GetGlobalSettings()
  1560. objects, nobjects = generate_scene_objects(scene)
  1561. textures = generate_texture_dict(scene)
  1562. materials = generate_material_dict(scene)
  1563. geometries = generate_geometry_dict(scene)
  1564. embeds = generate_embed_dict(scene)
  1565. ntextures = len(textures)
  1566. nmaterials = len(materials)
  1567. ngeometries = len(geometries)
  1568. position = serializeVector3( (0,0,0) )
  1569. rotation = serializeVector3( (0,0,0) )
  1570. scale = serializeVector3( (1,1,1) )
  1571. camera_names = generate_camera_name_list(scene)
  1572. scene_settings = scene.GetGlobalSettings()
  1573. # This does not seem to be any help here
  1574. # global_settings.GetDefaultCamera()
  1575. defcamera = camera_names[0] if len(camera_names) > 0 else ""
  1576. if option_default_camera:
  1577. defcamera = 'default_camera'
  1578. metadata = {
  1579. 'formatVersion': 3.2,
  1580. 'type': 'scene',
  1581. 'generatedBy': 'convert-to-threejs.py',
  1582. 'objects': nobjects,
  1583. 'geometries': ngeometries,
  1584. 'materials': nmaterials,
  1585. 'textures': ntextures
  1586. }
  1587. transform = {
  1588. 'position' : position,
  1589. 'rotation' : rotation,
  1590. 'scale' : scale
  1591. }
  1592. defaults = {
  1593. 'bgcolor' : 0,
  1594. 'camera' : defcamera,
  1595. 'fog' : ''
  1596. }
  1597. output = {
  1598. 'objects': objects,
  1599. 'geometries': geometries,
  1600. 'materials': materials,
  1601. 'textures': textures,
  1602. 'embeds': embeds,
  1603. 'transform': transform,
  1604. 'defaults': defaults,
  1605. }
  1606. if option_pretty_print:
  1607. output['0metadata'] = metadata
  1608. else:
  1609. output['metadata'] = metadata
  1610. return output
  1611. # #####################################################
  1612. # Generate Non-Scene Output
  1613. # #####################################################
  1614. def extract_geometry(scene, filename):
  1615. output = generate_non_scene_output(scene)
  1616. return output
  1617. # #####################################################
  1618. # File Helpers
  1619. # #####################################################
  1620. def write_file(filepath, content):
  1621. out = open(filepath, "w")
  1622. out.write(content.encode('utf8', 'replace'))
  1623. out.close()
  1624. def read_file(filepath):
  1625. f = open(filepath)
  1626. content = f.readlines()
  1627. f.close()
  1628. return content
  1629. def copy_textures(textures):
  1630. for key in textures:
  1631. url = textures[key]['url']
  1632. src = replace_OutFolder2inFolder(url)
  1633. shutil.copyfile(src, url)
  1634. def findFilesWithExt(directory, ext, include_path = True):
  1635. ext = ext.lower()
  1636. found = []
  1637. for root, dirs, files in os.walk(directory):
  1638. for filename in files:
  1639. current_ext = os.path.splitext(filename)[1].lower()
  1640. if current_ext == ext:
  1641. if include_path:
  1642. found.append(os.path.join(root, filename))
  1643. else:
  1644. found.append(filename)
  1645. return found
  1646. # #####################################################
  1647. # main
  1648. # #####################################################
  1649. if __name__ == "__main__":
  1650. from optparse import OptionParser
  1651. try:
  1652. from FbxCommon import *
  1653. except ImportError:
  1654. import platform
  1655. msg = 'Could not locate the python FBX SDK!\n'
  1656. msg += 'You need to copy the FBX SDK into your python install folder such as '
  1657. if platform.system() == 'Windows' or platform.system() == 'Microsoft':
  1658. msg += '"Python26/Lib/site-packages"'
  1659. elif platform.system() == 'Linux':
  1660. msg += '"/usr/local/lib/python2.6/site-packages"'
  1661. elif platform.system() == 'Darwin':
  1662. msg += '"/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages"'
  1663. msg += ' folder.'
  1664. print(msg)
  1665. sys.exit(1)
  1666. usage = "Usage: %prog [source_file.fbx] [output_file.js] [options]"
  1667. parser = OptionParser(usage=usage)
  1668. parser.add_option('-t', '--triangulate', action='store_true', dest='triangulate', help="force quad geometry into triangles", default=False)
  1669. parser.add_option('-x', '--ignore-textures', action='store_true', dest='notextures', help="don't include texture references in output file", default=False)
  1670. parser.add_option('-u', '--force-prefix', action='store_true', dest='prefix', help="prefix all object names in output file to ensure uniqueness", default=False)
  1671. parser.add_option('-f', '--flatten-scene', action='store_true', dest='geometry', help="merge all geometries and apply node transforms", default=False)
  1672. parser.add_option('-c', '--add-camera', action='store_true', dest='defcamera', help="include default camera in output scene", default=False)
  1673. parser.add_option('-l', '--add-light', action='store_true', dest='deflight', help="include default light in output scene", default=False)
  1674. parser.add_option('-p', '--pretty-print', action='store_true', dest='pretty', help="prefix all object names in output file", default=False)
  1675. (options, args) = parser.parse_args()
  1676. option_triangulate = options.triangulate
  1677. option_textures = True if not options.notextures else False
  1678. option_prefix = options.prefix
  1679. option_geometry = options.geometry
  1680. option_default_camera = options.defcamera
  1681. option_default_light = options.deflight
  1682. option_pretty_print = options.pretty
  1683. # Prepare the FBX SDK.
  1684. sdk_manager, scene = InitializeSdkObjects()
  1685. converter = FbxGeometryConverter(sdk_manager)
  1686. # The converter takes an FBX file as an argument.
  1687. if len(args) > 1:
  1688. print("\nLoading file: %s" % args[0])
  1689. result = LoadScene(sdk_manager, scene, args[0])
  1690. else:
  1691. result = False
  1692. print("\nUsage: convert_fbx_to_threejs [source_file.fbx] [output_file.js]\n")
  1693. if not result:
  1694. print("\nAn error occurred while loading the file...")
  1695. else:
  1696. if option_triangulate:
  1697. print("\nForcing geometry to triangles")
  1698. triangulate_scene(scene)
  1699. # According to asset's coordinate to convert scene
  1700. upVector = scene.GetGlobalSettings().GetAxisSystem().GetUpVector();
  1701. axis_system = FbxAxisSystem.MayaYUp
  1702. if upVector[0] == 3:
  1703. axis_system = FbxAxisSystem.MayaZUp
  1704. axis_system.ConvertScene(scene)
  1705. inputFolder = args[0].replace( "\\", "/" );
  1706. index = args[0].rfind( "/" );
  1707. inputFolder = inputFolder[:index+1]
  1708. outputFolder = args[1].replace( "\\", "/" );
  1709. index = args[1].rfind( "/" );
  1710. outputFolder = outputFolder[:index+1]
  1711. if option_geometry:
  1712. output_content = extract_geometry(scene, os.path.basename(args[0]))
  1713. else:
  1714. output_content = extract_scene(scene, os.path.basename(args[0]))
  1715. if option_pretty_print:
  1716. output_string = json.dumps(output_content, indent=4, cls=CustomEncoder, separators=(',', ': '), sort_keys=True)
  1717. output_string = executeRegexHacks(output_string)
  1718. else:
  1719. output_string = json.dumps(output_content, separators=(',', ': '), sort_keys=True)
  1720. output_path = os.path.join(os.getcwd(), args[1])
  1721. write_file(output_path, output_string)
  1722. copy_textures( output_content['textures'] )
  1723. print("\nExported Three.js file to:\n%s\n" % output_path)
  1724. # Destroy all objects created by the FBX SDK.
  1725. sdk_manager.Destroy()
  1726. sys.exit(0)