io_export_babylon.py 46 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100
  1. bl_info = {
  2. "name": "Babylon.js",
  3. "author": "David Catuhe",
  4. "version": (1, 1),
  5. "blender": (2, 67, 0),
  6. "location": "File > Export > Babylon.js (.babylon)",
  7. "description": "Export Babylon.js scenes (.babylon)",
  8. "warning": "",
  9. "wiki_url": "",
  10. "tracker_url": "",
  11. "category": "Import-Export"}
  12. import math
  13. import os
  14. import bpy
  15. import string
  16. import bpy_extras.io_utils
  17. from bpy.props import *
  18. import mathutils, math
  19. import struct
  20. import shutil
  21. from os import remove
  22. from bpy_extras.io_utils import (ExportHelper, axis_conversion)
  23. from bpy.props import (BoolProperty, FloatProperty, StringProperty, EnumProperty, FloatVectorProperty)
  24. from math import radians
  25. from mathutils import *
  26. MAX_VERTICES = 65535
  27. class SubMesh:
  28. materialIndex = 0
  29. verticesStart = 0
  30. verticesCount = 0
  31. indexStart = 0
  32. indexCount = 0
  33. class MultiMaterial:
  34. name = ""
  35. materials = []
  36. class Export_babylon(bpy.types.Operator, ExportHelper):
  37. """Export Babylon.js scene (.babylon)"""
  38. bl_idname = "scene.babylon"
  39. bl_label = "Export Babylon.js scene"
  40. filename_ext = ".babylon"
  41. filepath = ""
  42. # global_scale = FloatProperty(name="Scale", min=0.01, max=1000.0, default=1.0)
  43. def execute(self, context):
  44. return Export_babylon.save(self, context, **self.as_keywords(ignore=("check_existing", "filter_glob", "global_scale")))
  45. def mesh_triangulate(mesh):
  46. try:
  47. import bmesh
  48. bm = bmesh.new()
  49. bm.from_mesh(mesh)
  50. bmesh.ops.triangulate(bm, faces=bm.faces)
  51. bm.to_mesh(mesh)
  52. mesh.calc_tessface()
  53. bm.free()
  54. except:
  55. pass
  56. def write_matrix4(file_handler, name, matrix):
  57. file_handler.write(",\""+name+"\":[")
  58. tempMatrix = matrix.copy()
  59. tempMatrix.transpose()
  60. first = True
  61. for vect in tempMatrix:
  62. if (first != True):
  63. file_handler.write(",")
  64. first = False;
  65. file_handler.write("%.4f,%.4f,%.4f,%.4f"%(vect[0],vect[1], vect[2], vect[3]))
  66. file_handler.write("]")
  67. def write_array3(file_handler, name, array):
  68. file_handler.write(",\""+name+"\":[" + "%.4f,%.4f,%.4f"%(array[0],array[1],array[2]) + "]")
  69. def write_color(file_handler, name, color):
  70. file_handler.write(",\""+name+"\":[" + "%.4f,%.4f,%.4f"%(color.r,color.g,color.b) + "]")
  71. def write_vector(file_handler, name, vector):
  72. file_handler.write(",\""+name+"\":[" + "%.4f,%.4f,%.4f"%(vector.x,vector.z,vector.y) + "]")
  73. def write_quaternion(file_handler, name, quaternion):
  74. file_handler.write(",\""+name+"\":[" + "%.4f,%.4f,%.4f,%.4f"%(quaternion.x,quaternion.z,quaternion.y, -quaternion.w) + "]")
  75. def write_vectorScaled(file_handler, name, vector, mult):
  76. file_handler.write(",\""+name+"\":[" + "%.4f,%.4f,%.4f"%(vector.x * mult, vector.z * mult, vector.y * mult) + "]")
  77. def write_string(file_handler, name, string, noComma=False):
  78. if noComma == False:
  79. file_handler.write(",")
  80. file_handler.write("\""+name+"\":\"" + string + "\"")
  81. def write_float(file_handler, name, float):
  82. file_handler.write(",\""+name+"\":" + "%.4f"%(float))
  83. def write_int(file_handler, name, int, noComma=False):
  84. if noComma == False:
  85. file_handler.write(",")
  86. file_handler.write("\""+name+"\":" + str(int))
  87. def write_bool(file_handler, name, bool, noComma=False):
  88. if noComma == False:
  89. file_handler.write(",")
  90. if bool:
  91. file_handler.write("\""+name+"\":" + "true")
  92. else:
  93. file_handler.write("\""+name+"\":" + "false")
  94. def getDirection(matrix):
  95. return (matrix.to_3x3() * mathutils.Vector((0.0, 0.0, -1.0))).normalized()
  96. def export_camera(object, scene, file_handler):
  97. invWorld = object.matrix_world.copy()
  98. invWorld.invert()
  99. target = mathutils.Vector((0, 1, 0)) * invWorld
  100. file_handler.write("{")
  101. Export_babylon.write_string(file_handler, "name", object.name, True)
  102. Export_babylon.write_string(file_handler, "id", object.name)
  103. Export_babylon.write_vector(file_handler, "position", object.location)
  104. Export_babylon.write_vector(file_handler, "target", target)
  105. Export_babylon.write_float(file_handler, "fov", object.data.angle)
  106. Export_babylon.write_float(file_handler, "minZ", object.data.clip_start)
  107. Export_babylon.write_float(file_handler, "maxZ", object.data.clip_end)
  108. Export_babylon.write_float(file_handler, "speed", 1.0)
  109. Export_babylon.write_float(file_handler, "inertia", 0.9)
  110. Export_babylon.write_bool(file_handler, "checkCollisions", object.data.checkCollisions)
  111. Export_babylon.write_bool(file_handler, "applyGravity", object.data.applyGravity)
  112. Export_babylon.write_array3(file_handler, "ellipsoid", object.data.ellipsoid)
  113. locAnim = False
  114. coma = False
  115. if object.animation_data:
  116. if object.animation_data.action:
  117. file_handler.write(",\"animations\":[")
  118. for fcurve in object.animation_data.action.fcurves:
  119. if fcurve.data_path == "location" and locAnim == False:
  120. Export_babylon.export_animation(object, scene, file_handler, "location", "position", coma, 1)
  121. locAnim = coma = True
  122. file_handler.write("]")
  123. #Set Animations
  124. Export_babylon.write_bool(file_handler, "autoAnimate", True)
  125. Export_babylon.write_int(file_handler, "autoAnimateFrom", 0)
  126. Export_babylon.write_int(file_handler, "autoAnimateTo", bpy.context.scene.frame_end - bpy.context.scene.frame_start + 1)
  127. Export_babylon.write_bool(file_handler, "autoAnimateLoop", True)
  128. file_handler.write("}")
  129. def export_light(object, scene, file_handler):
  130. light_type_items = {'POINT': 0, 'SUN': 1, 'SPOT': 2, 'HEMI': 3, 'AREA': 0}
  131. light_type = light_type_items[object.data.type]
  132. file_handler.write("{")
  133. Export_babylon.write_string(file_handler, "name", object.name, True)
  134. Export_babylon.write_string(file_handler, "id", object.name)
  135. Export_babylon.write_float(file_handler, "type", light_type)
  136. if light_type == 0:
  137. Export_babylon.write_vector(file_handler, "position", object.location)
  138. elif light_type == 1:
  139. direction = Export_babylon.getDirection(object.matrix_world)
  140. Export_babylon.write_vector(file_handler, "position", object.location)
  141. Export_babylon.write_vector(file_handler, "direction", direction)
  142. elif light_type == 2:
  143. Export_babylon.write_vector(file_handler, "position", object.location)
  144. direction = Export_babylon.getDirection(object.matrix_world)
  145. Export_babylon.write_vector(file_handler, "direction", direction)
  146. Export_babylon.write_float(file_handler, "angle", object.data.spot_size)
  147. Export_babylon.write_float(file_handler, "exponent", object.data.spot_blend * 2)
  148. else:
  149. matrix_world = object.matrix_world.copy()
  150. matrix_world.translation = mathutils.Vector((0, 0, 0))
  151. direction = mathutils.Vector((0, 0, -1)) * matrix_world
  152. Export_babylon.write_vector(file_handler, "direction", -direction)
  153. Export_babylon.write_color(file_handler, "groundColor", mathutils.Color((0, 0, 0)))
  154. Export_babylon.write_float(file_handler, "intensity", object.data.energy)
  155. if object.data.use_diffuse:
  156. Export_babylon.write_color(file_handler, "diffuse", object.data.color)
  157. else:
  158. Export_babylon.write_color(file_handler, "diffuse", mathutils.Color((0, 0, 0)))
  159. if object.data.use_specular:
  160. Export_babylon.write_color(file_handler, "specular", object.data.color)
  161. else:
  162. Export_babylon.write_color(file_handler, "specular", mathutils.Color((0, 0, 0)))
  163. file_handler.write("}")
  164. def export_texture(slot, level, texture, scene, file_handler, filepath):
  165. # Copy image to output
  166. try:
  167. image = texture.texture.image
  168. imageFilepath = os.path.normpath(bpy.path.abspath(image.filepath))
  169. basename = os.path.basename(imageFilepath)
  170. targetdir = os.path.dirname(filepath)
  171. targetpath = os.path.join(targetdir, basename)
  172. if image.packed_file:
  173. image.save_render(targetpath)
  174. else:
  175. sourcepath = bpy.path.abspath(image.filepath)
  176. shutil.copy(sourcepath, targetdir)
  177. except:
  178. pass
  179. # Export
  180. file_handler.write(",\""+slot+"\":{")
  181. Export_babylon.write_string(file_handler, "name", basename, True)
  182. Export_babylon.write_float(file_handler, "level", level)
  183. Export_babylon.write_float(file_handler, "hasAlpha", texture.texture.use_alpha)
  184. coordinatesMode = 0;
  185. if (texture.mapping == "CUBE"):
  186. coordinatesMode = 3;
  187. if (texture.mapping == "SPHERE"):
  188. coordinatesMode = 1;
  189. Export_babylon.write_int(file_handler, "coordinatesMode", coordinatesMode)
  190. Export_babylon.write_float(file_handler, "uOffset", texture.offset.x)
  191. Export_babylon.write_float(file_handler, "vOffset", texture.offset.y)
  192. Export_babylon.write_float(file_handler, "uScale", texture.scale.x)
  193. Export_babylon.write_float(file_handler, "vScale", texture.scale.y)
  194. Export_babylon.write_float(file_handler, "uAng", 0)
  195. Export_babylon.write_float(file_handler, "vAng", 0)
  196. Export_babylon.write_float(file_handler, "wAng", 0)
  197. if (texture.texture.extension == "REPEAT"):
  198. Export_babylon.write_bool(file_handler, "wrapU", True)
  199. Export_babylon.write_bool(file_handler, "wrapV", True)
  200. else:
  201. Export_babylon.write_bool(file_handler, "wrapU", False)
  202. Export_babylon.write_bool(file_handler, "wrapV", False)
  203. Export_babylon.write_int(file_handler, "coordinatesIndex", 0)
  204. file_handler.write("}")
  205. def export_material(material, scene, file_handler, filepath):
  206. file_handler.write("{")
  207. Export_babylon.write_string(file_handler, "name", material.name, True)
  208. Export_babylon.write_string(file_handler, "id", material.name)
  209. Export_babylon.write_color(file_handler, "ambient", material.ambient * material.diffuse_color)
  210. Export_babylon.write_color(file_handler, "diffuse", material.diffuse_intensity * material.diffuse_color)
  211. Export_babylon.write_color(file_handler, "specular", material.specular_intensity * material.specular_color)
  212. Export_babylon.write_float(file_handler, "specularPower", material.specular_hardness)
  213. Export_babylon.write_color(file_handler, "emissive", material.emit * material.diffuse_color)
  214. Export_babylon.write_float(file_handler, "alpha", material.alpha)
  215. Export_babylon.write_bool(file_handler, "backFaceCulling", material.game_settings.use_backface_culling)
  216. # Textures
  217. for mtex in material.texture_slots:
  218. if mtex and mtex.texture and mtex.texture.type == 'IMAGE':
  219. if mtex.texture.image:
  220. if (mtex.use_map_color_diffuse and(mtex.texture_coords != 'REFLECTION')):
  221. # Diffuse
  222. Export_babylon.export_texture("diffuseTexture", mtex.diffuse_color_factor, mtex, scene, file_handler, filepath)
  223. if mtex.use_map_ambient:
  224. # Ambient
  225. Export_babylon.export_texture("ambientTexture", mtex.ambient_factor, mtex, scene, file_handler, filepath)
  226. if mtex.use_map_alpha:
  227. # Opacity
  228. Export_babylon.export_texture("opacityTexture", mtex.alpha_factor, mtex, scene, file_handler, filepath)
  229. if mtex.use_map_color_diffuse and (mtex.texture_coords == 'REFLECTION'):
  230. # Reflection
  231. Export_babylon.export_texture("reflectionTexture", mtex.diffuse_color_factor, mtex, scene, file_handler, filepath)
  232. if mtex.use_map_emit:
  233. # Emissive
  234. Export_babylon.export_texture("emissiveTexture", mtex.emit_factor, mtex, scene, file_handler, filepath)
  235. if mtex.use_map_normal:
  236. # Bump
  237. Export_babylon.export_texture("bumpTexture", mtex.emit_factor, mtex, scene, file_handler, filepath)
  238. file_handler.write("}")
  239. def export_multimaterial(multimaterial, scene, file_handler):
  240. file_handler.write("{")
  241. Export_babylon.write_string(file_handler, "name", multimaterial.name, True)
  242. Export_babylon.write_string(file_handler, "id", multimaterial.name)
  243. file_handler.write(",\"materials\":[")
  244. first = True
  245. for materialName in multimaterial.materials:
  246. if first != True:
  247. file_handler.write(",")
  248. file_handler.write("\"" + materialName +"\"")
  249. first = False
  250. file_handler.write("]")
  251. file_handler.write("}")
  252. def export_animation(object, scene, file_handler, typeBl, typeBa, coma, mult):
  253. if coma == True:
  254. file_handler.write(",")
  255. file_handler.write("{")
  256. Export_babylon.write_int(file_handler, "dataType", 1, True)
  257. Export_babylon.write_int(file_handler, "framePerSecond", 30)
  258. Export_babylon.write_int(file_handler, "loopBehavior", 1)
  259. Export_babylon.write_string(file_handler, "name", typeBa+" animation")
  260. Export_babylon.write_string(file_handler, "property", typeBa)
  261. file_handler.write(",\"keys\":[")
  262. frames = dict()
  263. for fcurve in object.animation_data.action.fcurves:
  264. if fcurve.data_path == typeBl:
  265. for key in fcurve.keyframe_points:
  266. frame = key.co.x
  267. frames[frame] = 1
  268. #for each frame (next step ==> set for key frames)
  269. i = 0
  270. for Frame in sorted(frames):
  271. if i == 0 and Frame != 0.0:
  272. file_handler.write("{")
  273. Export_babylon.write_int(file_handler, "frame", 0, True)
  274. bpy.context.scene.frame_set(int(Frame + bpy.context.scene.frame_start))
  275. Export_babylon.write_vectorScaled(file_handler, "values", getattr(object,typeBl), mult)
  276. file_handler.write("},")
  277. i = i + 1
  278. file_handler.write("{")
  279. Export_babylon.write_int(file_handler, "frame", Frame, True)
  280. bpy.context.scene.frame_set(int(Frame + bpy.context.scene.frame_start))
  281. Export_babylon.write_vectorScaled(file_handler, "values", getattr(object,typeBl), mult)
  282. file_handler.write("}")
  283. if i != len(frames):
  284. file_handler.write(",")
  285. else:
  286. file_handler.write(",{")
  287. Export_babylon.write_int(file_handler, "frame", bpy.context.scene.frame_end - bpy.context.scene.frame_start + 1, True)
  288. bpy.context.scene.frame_set(int(Frame + bpy.context.scene.frame_start))
  289. Export_babylon.write_vectorScaled(file_handler, "values", getattr(object,typeBl), mult)
  290. file_handler.write("}")
  291. file_handler.write("]}")
  292. def export_mesh(object, scene, file_handler, multiMaterials, startFace, forcedParent, nameID):
  293. # Get mesh
  294. mesh = object.to_mesh(scene, True, "PREVIEW")
  295. # Transform
  296. loc = mathutils.Vector((0, 0, 0))
  297. rot = mathutils.Quaternion((0, 0, 0, -1))
  298. scale = mathutils.Vector((1, 1, 1))
  299. hasSkeleton = False
  300. world = object.matrix_world
  301. if object.parent and object.parent.type == "ARMATURE" and len(object.vertex_groups) > 0:
  302. hasSkeleton = True
  303. else:
  304. if (object.parent):
  305. world = object.parent.matrix_world.inverted() * object.matrix_world
  306. loc, rot, scale = world.decompose()
  307. # Triangulate mesh if required
  308. Export_babylon.mesh_triangulate(mesh)
  309. # Getting vertices and indices
  310. positions=",\"positions\":["
  311. normals=",\"normals\":["
  312. indices=",\"indices\":["
  313. hasUV = True;
  314. hasUV2 = True;
  315. hasVertexColor = True
  316. if len(mesh.tessface_uv_textures) > 0:
  317. UVmap=mesh.tessface_uv_textures[0].data
  318. uvs=",\"uvs\":["
  319. else:
  320. hasUV = False
  321. if len(mesh.tessface_uv_textures) > 1:
  322. UV2map=mesh.tessface_uv_textures[1].data
  323. uvs2=",\"uvs2\":["
  324. else:
  325. hasUV2 = False
  326. if len(mesh.vertex_colors) > 0:
  327. Colormap = mesh.tessface_vertex_colors.active.data
  328. colors=",\"colors\":["
  329. else:
  330. hasVertexColor = False
  331. if hasSkeleton:
  332. skeletonWeight = ",\"matricesWeights\":["
  333. skeletonIndices = ",\"matricesIndices\":["
  334. alreadySavedVertices = []
  335. vertices_UVs=[]
  336. vertices_UV2s=[]
  337. vertices_Colors=[]
  338. vertices_indices=[]
  339. subMeshes = []
  340. offsetFace = 0
  341. for v in range(0, len(mesh.vertices)):
  342. alreadySavedVertices.append(False)
  343. vertices_UVs.append([])
  344. vertices_UV2s.append([])
  345. vertices_Colors.append([])
  346. vertices_indices.append([])
  347. materialsCount = max(1, len(object.material_slots))
  348. verticesCount = 0
  349. indicesCount = 0
  350. for materialIndex in range(materialsCount):
  351. if offsetFace != 0:
  352. break
  353. subMeshes.append(SubMesh())
  354. subMeshes[materialIndex].materialIndex = materialIndex
  355. subMeshes[materialIndex].verticesStart = verticesCount
  356. subMeshes[materialIndex].indexStart = indicesCount
  357. for faceIndex in range(startFace, len(mesh.tessfaces)): # For each face
  358. face = mesh.tessfaces[faceIndex]
  359. if face.material_index != materialIndex:
  360. continue
  361. if verticesCount + 3 > MAX_VERTICES:
  362. offsetFace = faceIndex
  363. break
  364. for v in range(3): # For each vertex in face
  365. vertex_index = face.vertices[v]
  366. vertex = mesh.vertices[vertex_index]
  367. position = vertex.co
  368. normal = vertex.normal
  369. #skeletons
  370. if hasSkeleton:
  371. matricesWeights = []
  372. matricesIndices = 0
  373. matricesWeights.append(0.0)
  374. matricesWeights.append(0.0)
  375. matricesWeights.append(0.0)
  376. matricesWeights.append(0.0)
  377. # Getting influences
  378. i = 0
  379. offset = 0
  380. for group in vertex.groups:
  381. index = group.group
  382. weight = group.weight
  383. for boneIndex, bone in enumerate(object.parent.pose.bones):
  384. if object.vertex_groups[index].name == bone.name:
  385. matricesWeights[i] = weight
  386. matricesIndices += boneIndex << offset
  387. offset = offset + 8
  388. i = i + 1
  389. if (i == 4):
  390. break;
  391. if (i == 4):
  392. break;
  393. # Texture coordinates
  394. if hasUV:
  395. vertex_UV = UVmap[face.index].uv[v]
  396. if hasUV2:
  397. vertex_UV2 = UV2map[face.index].uv[v]
  398. # Vertex color
  399. if hasVertexColor:
  400. if v == 0:
  401. vertex_Color = Colormap[face.index].color1
  402. if v == 1:
  403. vertex_Color = Colormap[face.index].color2
  404. if v == 2:
  405. vertex_Color = Colormap[face.index].color3
  406. # Check if the current vertex is already saved
  407. alreadySaved = alreadySavedVertices[vertex_index] and not hasSkeleton
  408. if alreadySaved:
  409. alreadySaved=False
  410. # UV
  411. index_UV = 0
  412. for savedIndex in vertices_indices[vertex_index]:
  413. if hasUV:
  414. vUV = vertices_UVs[vertex_index][index_UV]
  415. if (vUV[0]!=vertex_UV[0] or vUV[1]!=vertex_UV[1]):
  416. continue
  417. if hasUV2:
  418. vUV2 = vertices_UV2s[vertex_index][index_UV]
  419. if (vUV2[0]!=vertex_UV2[0] or vUV2[1]!=vertex_UV2[1]):
  420. continue
  421. if hasVertexColor:
  422. vColor = vertices_Colors[vertex_index][index_UV]
  423. if (vColor.r!=vertex_Color.r or vColor.g!=vertex_Color.g or vColor.b!=vertex_Color.b):
  424. continue
  425. if vertices_indices[vertex_index][index_UV] >= subMeshes[materialIndex].verticesStart:
  426. alreadySaved=True
  427. break
  428. index_UV+=1
  429. if (alreadySaved):
  430. # Reuse vertex
  431. index=vertices_indices[vertex_index][index_UV]
  432. else:
  433. # Export new one
  434. index=verticesCount
  435. alreadySavedVertices[vertex_index]=True
  436. if hasUV:
  437. vertices_UVs[vertex_index].append(vertex_UV)
  438. uvs+="%.4f,%.4f,"%(vertex_UV[0], vertex_UV[1])
  439. if hasUV2:
  440. vertices_UV2s[vertex_index].append(vertex_UV2)
  441. uvs2+="%.4f,%.4f,"%(vertex_UV2[0], vertex_UV2[1])
  442. if hasVertexColor:
  443. vertices_Colors[vertex_index].append(vertex_Color)
  444. colors+="%.4f,%.4f,%.4f,"%(vertex_Color.r,vertex_Color.g,vertex_Color.b)
  445. if hasSkeleton:
  446. skeletonWeight+="%.4f,%.4f,%.4f,%.4f,"%(matricesWeights[0], matricesWeights[1], matricesWeights[2], matricesWeights[3])
  447. skeletonIndices+="%i,"%(matricesIndices)
  448. vertices_indices[vertex_index].append(index)
  449. positions+="%.4f,%.4f,%.4f,"%(position.x,position.z,position.y)
  450. normals+="%.4f,%.4f,%.4f,"%(normal.x,normal.z,normal.y)
  451. verticesCount += 1
  452. indices+="%i,"%(index)
  453. indicesCount += 1
  454. subMeshes[materialIndex].verticesCount = verticesCount - subMeshes[materialIndex].verticesStart
  455. subMeshes[materialIndex].indexCount = indicesCount - subMeshes[materialIndex].indexStart
  456. positions=positions.rstrip(',')
  457. normals=normals.rstrip(',')
  458. indices=indices.rstrip(',')
  459. positions+="]\n"
  460. normals+="]\n"
  461. indices+="]\n"
  462. if hasUV:
  463. uvs=uvs.rstrip(',')
  464. uvs+="]\n"
  465. if hasUV2:
  466. uvs2=uvs2.rstrip(',')
  467. uvs2+="]\n"
  468. if hasVertexColor:
  469. colors=colors.rstrip(',')
  470. colors+="]\n"
  471. if hasSkeleton:
  472. skeletonWeight=skeletonWeight.rstrip(', ')
  473. skeletonWeight+="]\n"
  474. skeletonIndices= skeletonIndices.rstrip(', ')
  475. skeletonIndices+="]\n"
  476. # Writing mesh
  477. file_handler.write("{")
  478. Export_babylon.write_string(file_handler, "name", object.name + nameID, True)
  479. Export_babylon.write_string(file_handler, "id", object.name + nameID)
  480. if forcedParent is None:
  481. if object.parent != None:
  482. Export_babylon.write_string(file_handler, "parentId", object.parent.name)
  483. else:
  484. Export_babylon.write_string(file_handler, "parentId", forcedParent.name)
  485. if len(object.material_slots) == 1:
  486. material = object.material_slots[0].material
  487. Export_babylon.write_string(file_handler, "materialId", object.material_slots[0].name)
  488. if material.game_settings.face_orientation != "BILLBOARD":
  489. billboardMode = 0
  490. else:
  491. billboardMode = 7
  492. elif len(object.material_slots) > 1:
  493. multimat = MultiMaterial()
  494. multimat.name = "Multimaterial#" + str(len(multiMaterials))
  495. multimat.materials = []
  496. Export_babylon.write_string(file_handler, "materialId", multimat.name)
  497. for mat in object.material_slots:
  498. multimat.materials.append(mat.name)
  499. multiMaterials.append(multimat)
  500. billboardMode = 0
  501. else:
  502. billboardMode = 0
  503. if forcedParent is None:
  504. Export_babylon.write_vector(file_handler, "position", loc)
  505. Export_babylon.write_vectorScaled(file_handler, "rotation", rot.to_euler("XYZ"), -1)
  506. Export_babylon.write_vector(file_handler, "scaling", scale)
  507. else:
  508. Export_babylon.write_vector(file_handler, "position", mathutils.Vector((0, 0, 0)))
  509. Export_babylon.write_vectorScaled(file_handler, "rotation", mathutils.Vector((0, 0, 0)), 1)
  510. Export_babylon.write_vector(file_handler, "scaling", mathutils.Vector((1, 1, 1)))
  511. Export_babylon.write_bool(file_handler, "isVisible", object.is_visible(scene))
  512. Export_babylon.write_bool(file_handler, "isEnabled", True)
  513. Export_babylon.write_bool(file_handler, "useFlatShading", object.data.useFlatShading)
  514. Export_babylon.write_bool(file_handler, "checkCollisions", object.data.checkCollisions)
  515. Export_babylon.write_int(file_handler, "billboardMode", billboardMode)
  516. Export_babylon.write_bool(file_handler, "receiveShadows", object.data.receiveShadows)
  517. # Export Physics
  518. if object.rigid_body != None:
  519. shape_items = {'BOX': 1, 'SPHERE': 2}
  520. shape_type = shape_items[object.rigid_body.collision_shape]
  521. Export_babylon.write_int(file_handler, "physicsImpostor", shape_type)
  522. mass = object.rigid_body.mass
  523. if mass < 0.005:
  524. mass = 0
  525. Export_babylon.write_float(file_handler, "physicsMass", mass)
  526. Export_babylon.write_float(file_handler, "physicsFriction", object.rigid_body.friction)
  527. Export_babylon.write_float(file_handler, "physicsRestitution", object.rigid_body.restitution)
  528. # Geometry
  529. if hasSkeleton:
  530. i = 0
  531. for obj in [object for object in scene.objects if object.is_visible(scene)]:
  532. if (obj.type == 'ARMATURE'):
  533. if (obj.name == object.parent.name):
  534. Export_babylon.write_int(file_handler, "skeletonId", i)
  535. else:
  536. i = i+1
  537. file_handler.write(positions)
  538. file_handler.write(normals)
  539. if hasUV:
  540. file_handler.write(uvs)
  541. if hasUV2:
  542. file_handler.write(uvs2)
  543. if hasVertexColor:
  544. file_handler.write(colors)
  545. if hasSkeleton:
  546. file_handler.write(skeletonWeight)
  547. file_handler.write(skeletonIndices)
  548. file_handler.write(indices)
  549. # Sub meshes
  550. file_handler.write(",\"subMeshes\":[")
  551. first = True
  552. for subMesh in subMeshes:
  553. if first == False:
  554. file_handler.write(",")
  555. file_handler.write("{")
  556. Export_babylon.write_int(file_handler, "materialIndex", subMesh.materialIndex, True)
  557. Export_babylon.write_int(file_handler, "verticesStart", subMesh.verticesStart)
  558. Export_babylon.write_int(file_handler, "verticesCount", subMesh.verticesCount)
  559. Export_babylon.write_int(file_handler, "indexStart", subMesh.indexStart)
  560. Export_babylon.write_int(file_handler, "indexCount", subMesh.indexCount)
  561. file_handler.write("}")
  562. first = False
  563. file_handler.write("]")
  564. #Export Animations
  565. rotAnim = False
  566. locAnim = False
  567. scaAnim = False
  568. coma = False
  569. if object.animation_data:
  570. if object.animation_data.action:
  571. file_handler.write(",\"animations\":[")
  572. for fcurve in object.animation_data.action.fcurves:
  573. if fcurve.data_path == "rotation_euler" and rotAnim == False:
  574. Export_babylon.export_animation(object, scene, file_handler, "rotation_euler", "rotation", coma, -1)
  575. rotAnim = coma = True
  576. elif fcurve.data_path == "location" and locAnim == False:
  577. Export_babylon.export_animation(object, scene, file_handler, "location", "position", coma, 1)
  578. locAnim = coma = True
  579. elif fcurve.data_path == "scale" and scaAnim == False:
  580. Export_babylon.export_animation(object, scene, file_handler, "scale", "scaling", coma, 1)
  581. locAnim = coma = True
  582. file_handler.write("]")
  583. #Set Animations
  584. Export_babylon.write_bool(file_handler, "autoAnimate", True)
  585. Export_babylon.write_int(file_handler, "autoAnimateFrom", 0)
  586. Export_babylon.write_int(file_handler, "autoAnimateTo", bpy.context.scene.frame_end - bpy.context.scene.frame_start + 1)
  587. Export_babylon.write_bool(file_handler, "autoAnimateLoop", True)
  588. # Closing
  589. file_handler.write("}")
  590. return offsetFace
  591. def export_node(object, scene, file_handler):
  592. # Transform
  593. loc = mathutils.Vector((0, 0, 0))
  594. rot = mathutils.Quaternion((0, 0, 0, 1))
  595. scale = mathutils.Vector((1, 1, 1))
  596. world = object.matrix_world
  597. if (object.parent):
  598. world = object.parent.matrix_world.inverted() * object.matrix_world
  599. loc, rot, scale = world.decompose()
  600. # Writing node
  601. file_handler.write("{")
  602. Export_babylon.write_string(file_handler, "name", object.name, True)
  603. Export_babylon.write_string(file_handler, "id", object.name)
  604. if object.parent != None:
  605. Export_babylon.write_string(file_handler, "parentId", object.parent.name)
  606. Export_babylon.write_vector(file_handler, "position", loc)
  607. Export_babylon.write_vectorScaled(file_handler, "rotation", rot.to_euler("XYZ"), -1)
  608. Export_babylon.write_vector(file_handler, "scaling", scale)
  609. Export_babylon.write_bool(file_handler, "isVisible", False)
  610. Export_babylon.write_bool(file_handler, "isEnabled", True)
  611. Export_babylon.write_bool(file_handler, "checkCollisions", False)
  612. Export_babylon.write_int(file_handler, "billboardMode", 0)
  613. Export_babylon.write_bool(file_handler, "receiveShadows", False)
  614. # Closing
  615. file_handler.write("}")
  616. def export_shadowGenerator(lamp, scene, file_handler):
  617. file_handler.write("{")
  618. if lamp.data.shadowMap == 'VAR':
  619. Export_babylon.write_bool(file_handler, "useVarianceShadowMap", True, True)
  620. else:
  621. Export_babylon.write_bool(file_handler, "useVarianceShadowMap", False, True)
  622. Export_babylon.write_int(file_handler, "mapSize", lamp.data.shadowMapSize)
  623. Export_babylon.write_string(file_handler, "lightId", lamp.name)
  624. file_handler.write(",\"renderList\":[")
  625. multiMaterials = []
  626. first = True
  627. for object in [object for object in scene.objects]:
  628. if (object.type == 'MESH' and object.data.castShadows):
  629. if first != True:
  630. file_handler.write(",")
  631. first = False
  632. file_handler.write("\"" + object.name + "\"")
  633. file_handler.write("]")
  634. file_handler.write("}")
  635. def export_bone_matrix(armature, bone, label, file_handler):
  636. SystemMatrix = Matrix.Scale(-1, 4, Vector((0, 0, 1))) * Matrix.Rotation(radians(-90), 4, 'X')
  637. if (bone.parent):
  638. Export_babylon.write_matrix4(file_handler, label, (SystemMatrix * armature.matrix_world * bone.parent.matrix).inverted() * (SystemMatrix * armature.matrix_world * bone.matrix))
  639. else:
  640. Export_babylon.write_matrix4(file_handler, label, SystemMatrix * armature.matrix_world * bone.matrix)
  641. def export_bones(armature, scene, file_handler, id):
  642. file_handler.write("{")
  643. Export_babylon.write_string(file_handler, "name", armature.name, True)
  644. Export_babylon.write_int(file_handler, "id", id)
  645. file_handler.write(",\"bones\":[")
  646. bones = armature.pose.bones
  647. first = True
  648. j = 0
  649. for bone in bones:
  650. if first != True:
  651. file_handler.write(",")
  652. first = False
  653. file_handler.write("{")
  654. Export_babylon.write_string(file_handler, "name", bone.name, True)
  655. Export_babylon.write_int(file_handler, "index", j)
  656. Export_babylon.export_bone_matrix(armature, bone, "matrix", file_handler)
  657. if (bone.parent):
  658. parentId = 0
  659. for parent in bones:
  660. if parent == bone.parent:
  661. break;
  662. parentId += 1
  663. Export_babylon.write_int(file_handler, "parentBoneIndex", parentId)
  664. else:
  665. Export_babylon.write_int(file_handler, "parentBoneIndex", -1)
  666. #animation
  667. if (armature.animation_data.action):
  668. Export_babylon.export_bonesAnimation(armature, bone, scene, file_handler)
  669. j = j + 1
  670. file_handler.write("}")
  671. file_handler.write("]")
  672. file_handler.write("}")
  673. def export_bonesAnimation(armature, bone, scene, file_handler):
  674. file_handler.write(",\"animation\": {")
  675. start_frame = scene.frame_start
  676. end_frame = scene.frame_end
  677. fps = scene.render.fps
  678. Export_babylon.write_int(file_handler, "dataType", 3, True)
  679. Export_babylon.write_int(file_handler, "framePerSecond", fps)
  680. #keys
  681. file_handler.write(",\"keys\":[")
  682. for Frame in range(start_frame, end_frame + 1):
  683. file_handler.write("{")
  684. Export_babylon.write_int(file_handler, "frame", Frame, True)
  685. bpy.context.scene.frame_set(Frame)
  686. Export_babylon.export_bone_matrix(armature, bone, "values", file_handler)
  687. if Frame == end_frame:
  688. file_handler.write("}")
  689. else:
  690. file_handler.write("},")
  691. file_handler.write("]")
  692. Export_babylon.write_int(file_handler, "loopBehavior", 1)
  693. Export_babylon.write_string(file_handler, "name", "anim")
  694. Export_babylon.write_string(file_handler, "property", "_matrix")
  695. file_handler.write("}")
  696. bpy.context.scene.frame_set(start_frame)
  697. def save(operator, context, filepath="",
  698. use_apply_modifiers=False,
  699. use_triangulate=True,
  700. use_compress=False):
  701. # Open file
  702. file_handler = open(filepath, 'w')
  703. if bpy.ops.object.mode_set.poll():
  704. bpy.ops.object.mode_set(mode='OBJECT')
  705. # Writing scene
  706. scene=context.scene
  707. world = scene.world
  708. if world:
  709. world_ambient = world.ambient_color
  710. else:
  711. world_ambient = Color((0.0, 0.0, 0.0))
  712. bpy.ops.screen.animation_cancel()
  713. currentFrame = bpy.context.scene.frame_current
  714. bpy.context.scene.frame_set(0)
  715. file_handler.write("{")
  716. file_handler.write("\"autoClear\":true")
  717. Export_babylon.write_color(file_handler, "clearColor", world_ambient)
  718. Export_babylon.write_color(file_handler, "ambientColor", world_ambient)
  719. Export_babylon.write_vector(file_handler, "gravity", scene.gravity)
  720. if world and world.mist_settings.use_mist:
  721. Export_babylon.write_int(file_handler, "fogMode", 3)
  722. Export_babylon.write_color(file_handler, "fogColor", world.horizon_color)
  723. Export_babylon.write_float(file_handler, "fogStart", world.mist_settings.start)
  724. Export_babylon.write_float(file_handler, "fogEnd", world.mist_settings.depth)
  725. Export_babylon.write_float(file_handler, "fogDensity", 0.1)
  726. # Cameras
  727. file_handler.write(",\"cameras\":[")
  728. first = True
  729. for object in [object for object in scene.objects if object.is_visible(scene)]:
  730. if (object.type == 'CAMERA'):
  731. if first != True:
  732. file_handler.write(",")
  733. first = False
  734. data_string = Export_babylon.export_camera(object, scene, file_handler)
  735. file_handler.write("]")
  736. # Active camera
  737. if scene.camera != None:
  738. Export_babylon.write_string(file_handler, "activeCamera", scene.camera.name)
  739. # Lights
  740. file_handler.write(",\"lights\":[")
  741. first = True
  742. for object in [object for object in scene.objects if object.is_visible(scene)]:
  743. if (object.type == 'LAMP'):
  744. if first != True:
  745. file_handler.write(",")
  746. first = False
  747. data_string = Export_babylon.export_light(object, scene, file_handler)
  748. file_handler.write("]")
  749. # Materials
  750. materials = [mat for mat in bpy.data.materials if mat.users >= 1]
  751. file_handler.write(",\"materials\":[")
  752. first = True
  753. for material in materials:
  754. if first != True:
  755. file_handler.write(",")
  756. first = False
  757. data_string = Export_babylon.export_material(material, scene, file_handler, filepath)
  758. file_handler.write("]")
  759. # Meshes
  760. file_handler.write(",\"meshes\":[")
  761. multiMaterials = []
  762. first = True
  763. for object in [object for object in scene.objects]:
  764. if object.type == 'MESH' or object.type == 'EMPTY':
  765. if first != True:
  766. file_handler.write(",")
  767. first = False
  768. if object.type == 'MESH':
  769. forcedParent = None
  770. nameID = ""
  771. startFace = 0
  772. while True:
  773. startFace = Export_babylon.export_mesh(object, scene, file_handler, multiMaterials, startFace, forcedParent, str(nameID))
  774. if startFace == 0:
  775. break
  776. if forcedParent is None:
  777. nameID = 0
  778. forcedParent = object
  779. nameID = nameID + 1
  780. file_handler.write(",")
  781. else:
  782. data_string = Export_babylon.export_node(object, scene, file_handler)
  783. file_handler.write("]")
  784. # Multi-materials
  785. file_handler.write(",\"multiMaterials\":[")
  786. first = True
  787. for multimaterial in multiMaterials:
  788. if first != True:
  789. file_handler.write(",")
  790. first = False
  791. data_string = Export_babylon.export_multimaterial(multimaterial, scene, file_handler)
  792. file_handler.write("]")
  793. # Shadow generators
  794. file_handler.write(",\"shadowGenerators\":[")
  795. first = True
  796. for object in [object for object in scene.objects if object.is_visible(scene)]:
  797. if (object.type == 'LAMP' and object.data.shadowMap != 'NONE'):
  798. if first != True:
  799. file_handler.write(",")
  800. first = False
  801. data_string = Export_babylon.export_shadowGenerator(object, scene, file_handler)
  802. file_handler.write("]")
  803. # Armatures/Bones
  804. file_handler.write(",\"skeletons\":[")
  805. first = True
  806. i = 0
  807. for object in [object for object in scene.objects if object.is_visible(scene)]:
  808. if (object.type == 'ARMATURE'):
  809. if first != True:
  810. file_handler.write(",")
  811. first = False
  812. data_string = Export_babylon.export_bones(object, scene, file_handler, i)
  813. i = i+1
  814. file_handler.write("]")
  815. # Closing
  816. file_handler.write("}")
  817. file_handler.close()
  818. bpy.context.scene.frame_set(currentFrame)
  819. return {'FINISHED'}
  820. # UI
  821. bpy.types.Mesh.useFlatShading = BoolProperty(
  822. name="Use Flat Shading",
  823. default = False)
  824. bpy.types.Mesh.checkCollisions = BoolProperty(
  825. name="Check Collisions",
  826. default = False)
  827. bpy.types.Mesh.castShadows = BoolProperty(
  828. name="Cast Shadows",
  829. default = False)
  830. bpy.types.Mesh.receiveShadows = BoolProperty(
  831. name="Receive Shadows",
  832. default = False)
  833. bpy.types.Camera.checkCollisions = BoolProperty(
  834. name="Check Collisions",
  835. default = False)
  836. bpy.types.Camera.applyGravity = BoolProperty(
  837. name="Apply Gravity",
  838. default = False)
  839. bpy.types.Camera.ellipsoid = FloatVectorProperty(
  840. name="Ellipsoid",
  841. default = mathutils.Vector((0.2, 0.9, 0.2)))
  842. bpy.types.Lamp.shadowMap = EnumProperty(
  843. name="Shadow Map Type",
  844. items = (('NONE', "None", "No Shadow Maps"), ('STD', "Standard", "Use Standard Shadow Maps"), ('VAR', "Variance", "Use Variance Shadow Maps")),
  845. default = 'NONE')
  846. bpy.types.Lamp.shadowMapSize = IntProperty(
  847. name="Shadow Map Size",
  848. default = 512)
  849. class ObjectPanel(bpy.types.Panel):
  850. bl_label = "Babylon.js"
  851. bl_space_type = "PROPERTIES"
  852. bl_region_type = "WINDOW"
  853. bl_context = "data"
  854. def draw(self, context):
  855. ob = context.object
  856. if not ob or not ob.data:
  857. return
  858. layout = self.layout
  859. isMesh = isinstance(ob.data, bpy.types.Mesh)
  860. isCamera = isinstance(ob.data, bpy.types.Camera)
  861. isLight = isinstance(ob.data, bpy.types.Lamp)
  862. if isMesh:
  863. layout.prop(ob.data, 'useFlatShading')
  864. layout.prop(ob.data, 'checkCollisions')
  865. layout.prop(ob.data, 'castShadows')
  866. layout.prop(ob.data, 'receiveShadows')
  867. elif isCamera:
  868. layout.prop(ob.data, 'checkCollisions')
  869. layout.prop(ob.data, 'applyGravity')
  870. layout.prop(ob.data, 'ellipsoid')
  871. elif isLight:
  872. layout.prop(ob.data, 'shadowMap')
  873. layout.prop(ob.data, 'shadowMapSize')
  874. ### REGISTER ###
  875. def menu_func(self, context):
  876. self.layout.operator(Export_babylon.bl_idname, text="Babylon.js (.babylon)")
  877. def register():
  878. bpy.utils.register_module(__name__)
  879. bpy.types.INFO_MT_file_export.append(menu_func)
  880. def unregister():
  881. bpy.utils.unregister_module(__name__)
  882. bpy.types.INFO_MT_file_export.remove(menu_func)
  883. if __name__ == "__main__":
  884. register()