io_export_babylon.py 49 KB

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