io_export_babylon.py 45 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083
  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_INT = 1000000000
  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, minVertex, maxVertex):
  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. world = object.matrix_world
  300. if object.parent and object.parent.type == "ARMATURE" and len(object.vertex_groups) > 0:
  301. hasSkeleton = True
  302. else:
  303. hasSkeleton = False
  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. finish = True
  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. subMeshes.append(SubMesh())
  352. subMeshes[materialIndex].materialIndex = materialIndex
  353. subMeshes[materialIndex].verticesStart = verticesCount
  354. subMeshes[materialIndex].indexStart = indicesCount
  355. for face in mesh.tessfaces: # For each face
  356. if face.material_index != materialIndex:
  357. continue
  358. if face.vertices[0] < minVertex and face.vertices[1] < minVertex and face.vertices[2] < minVertex:
  359. continue
  360. if face.vertices[0] > maxVertex or face.vertices[1] > maxVertex or face.vertices[2] > maxVertex:
  361. finish = False
  362. continue
  363. for v in range(3): # For each vertex in face
  364. vertex_index = face.vertices[v]
  365. vertex = mesh.vertices[vertex_index]
  366. position = vertex.co
  367. normal = vertex.normal
  368. #skeletons
  369. if hasSkeleton:
  370. matricesWeights = []
  371. matricesIndices = 0
  372. matricesWeights.append(0.0)
  373. matricesWeights.append(0.0)
  374. matricesWeights.append(0.0)
  375. matricesWeights.append(0.0)
  376. # Getting influences
  377. i = 0
  378. offset = 0
  379. for group in vertex.groups:
  380. index = group.group
  381. weight = group.weight
  382. for boneIndex, bone in enumerate(object.parent.pose.bones):
  383. if object.vertex_groups[index].name == bone.name:
  384. matricesWeights[i] = weight
  385. matricesIndices += boneIndex << offset
  386. offset = offset + 8
  387. i = i + 1
  388. if (i == 4):
  389. break;
  390. if (i == 4):
  391. break;
  392. # Texture coordinates
  393. if hasUV:
  394. vertex_UV = UVmap[face.index].uv[v]
  395. if hasUV2:
  396. vertex_UV2 = UV2map[face.index].uv[v]
  397. # Vertex color
  398. if hasVertexColor:
  399. if v == 0:
  400. vertex_Color = Colormap[face.index].color1
  401. if v == 1:
  402. vertex_Color = Colormap[face.index].color2
  403. if v == 2:
  404. vertex_Color = Colormap[face.index].color3
  405. # Check if the current vertex is already saved
  406. alreadySaved = alreadySavedVertices[vertex_index] and not hasSkeleton
  407. if alreadySaved:
  408. alreadySaved=False
  409. # UV
  410. index_UV = 0
  411. for savedIndex in vertices_indices[vertex_index]:
  412. if hasUV:
  413. vUV = vertices_UVs[vertex_index][index_UV]
  414. if (vUV[0]!=vertex_UV[0] or vUV[1]!=vertex_UV[1]):
  415. continue
  416. if hasUV2:
  417. vUV2 = vertices_UV2s[vertex_index][index_UV]
  418. if (vUV2[0]!=vertex_UV2[0] or vUV2[1]!=vertex_UV2[1]):
  419. continue
  420. if hasVertexColor:
  421. vColor = vertices_Colors[vertex_index][index_UV]
  422. if (vColor.r!=vertex_Color.r or vColor.g!=vertex_Color.g or vColor.b!=vertex_Color.b):
  423. continue
  424. if vertices_indices[vertex_index][index_UV] >= subMeshes[materialIndex].verticesStart:
  425. alreadySaved=True
  426. break
  427. index_UV+=1
  428. if (alreadySaved):
  429. # Reuse vertex
  430. index=vertices_indices[vertex_index][index_UV]
  431. else:
  432. # Export new one
  433. index=verticesCount
  434. alreadySavedVertices[vertex_index]=True
  435. if hasUV:
  436. vertices_UVs[vertex_index].append(vertex_UV)
  437. uvs+="%.4f,%.4f,"%(vertex_UV[0], vertex_UV[1])
  438. if hasUV2:
  439. vertices_UV2s[vertex_index].append(vertex_UV2)
  440. uvs2+="%.4f,%.4f,"%(vertex_UV2[0], vertex_UV2[1])
  441. if hasVertexColor:
  442. vertices_Colors[vertex_index].append(vertex_Color)
  443. colors+="%.4f,%.4f,%.4f,"%(vertex_Color.r,vertex_Color.g,vertex_Color.b)
  444. if hasSkeleton:
  445. skeletonWeight+="%.4f,%.4f,%.4f,%.4f,"%(matricesWeights[0], matricesWeights[1], matricesWeights[2], matricesWeights[3])
  446. skeletonIndices+="%i,"%(matricesIndices)
  447. vertices_indices[vertex_index].append(index)
  448. positions+="%.4f,%.4f,%.4f,"%(position.x,position.z,position.y)
  449. normals+="%.4f,%.4f,%.4f,"%(normal.x,normal.z,normal.y)
  450. verticesCount += 1
  451. indices+="%i,"%(index)
  452. indicesCount += 1
  453. subMeshes[materialIndex].verticesCount = verticesCount - subMeshes[materialIndex].verticesStart
  454. subMeshes[materialIndex].indexCount = indicesCount - subMeshes[materialIndex].indexStart
  455. positions=positions.rstrip(',')
  456. normals=normals.rstrip(',')
  457. indices=indices.rstrip(',')
  458. positions+="]\n"
  459. normals+="]\n"
  460. indices+="]\n"
  461. if hasUV:
  462. uvs=uvs.rstrip(',')
  463. uvs+="]\n"
  464. if hasUV2:
  465. uvs2=uvs2.rstrip(',')
  466. uvs2+="]\n"
  467. if hasVertexColor:
  468. colors=colors.rstrip(',')
  469. colors+="]\n"
  470. if hasSkeleton:
  471. skeletonWeight=skeletonWeight.rstrip(', ')
  472. skeletonWeight+="]\n"
  473. skeletonIndices= skeletonIndices.rstrip(', ')
  474. skeletonIndices+="]\n"
  475. # Writing mesh
  476. file_handler.write("{")
  477. Export_babylon.write_string(file_handler, "name", object.name, True)
  478. Export_babylon.write_string(file_handler, "id", object.name)
  479. if object.parent != None:
  480. Export_babylon.write_string(file_handler, "parentId", object.parent.name)
  481. if len(object.material_slots) == 1:
  482. material = object.material_slots[0].material
  483. Export_babylon.write_string(file_handler, "materialId", object.material_slots[0].name)
  484. if material.game_settings.face_orientation != "BILLBOARD":
  485. billboardMode = 0
  486. else:
  487. billboardMode = 7
  488. elif len(object.material_slots) > 1:
  489. multimat = MultiMaterial()
  490. multimat.name = "Multimaterial#" + str(len(multiMaterials))
  491. multimat.materials = []
  492. Export_babylon.write_string(file_handler, "materialId", multimat.name)
  493. for mat in object.material_slots:
  494. multimat.materials.append(mat.name)
  495. multiMaterials.append(multimat)
  496. billboardMode = 0
  497. else:
  498. billboardMode = 0
  499. Export_babylon.write_vector(file_handler, "position", loc)
  500. Export_babylon.write_vectorScaled(file_handler, "rotation", rot.to_euler("XYZ"), -1)
  501. Export_babylon.write_vector(file_handler, "scaling", scale)
  502. Export_babylon.write_bool(file_handler, "isVisible", object.is_visible(scene))
  503. Export_babylon.write_bool(file_handler, "isEnabled", True)
  504. Export_babylon.write_bool(file_handler, "useFlatShading", object.data.useFlatShading)
  505. Export_babylon.write_bool(file_handler, "checkCollisions", object.data.checkCollisions)
  506. Export_babylon.write_int(file_handler, "billboardMode", billboardMode)
  507. Export_babylon.write_bool(file_handler, "receiveShadows", object.data.receiveShadows)
  508. # Export Physics
  509. if object.rigid_body != None:
  510. shape_items = {'BOX': 1, 'SPHERE': 2}
  511. shape_type = shape_items[object.rigid_body.collision_shape]
  512. Export_babylon.write_int(file_handler, "physicsImpostor", shape_type)
  513. mass = object.rigid_body.mass
  514. if mass < 0.005:
  515. mass = 0
  516. Export_babylon.write_float(file_handler, "physicsMass", mass)
  517. Export_babylon.write_float(file_handler, "physicsFriction", object.rigid_body.friction)
  518. Export_babylon.write_float(file_handler, "physicsRestitution", object.rigid_body.restitution)
  519. # Geometry
  520. if hasSkeleton:
  521. i = 0
  522. for obj in [object for object in scene.objects if object.is_visible(scene)]:
  523. if (obj.type == 'ARMATURE'):
  524. if (obj.name == object.parent.name):
  525. Export_babylon.write_int(file_handler, "skeletonId", i)
  526. else:
  527. i = i+1
  528. file_handler.write(positions)
  529. file_handler.write(normals)
  530. if hasUV:
  531. file_handler.write(uvs)
  532. if hasUV2:
  533. file_handler.write(uvs2)
  534. if hasVertexColor:
  535. file_handler.write(colors)
  536. if hasSkeleton:
  537. file_handler.write(skeletonWeight)
  538. file_handler.write(skeletonIndices)
  539. file_handler.write(indices)
  540. # Sub meshes
  541. file_handler.write(",\"subMeshes\":[")
  542. first = True
  543. for subMesh in subMeshes:
  544. if first == False:
  545. file_handler.write(",")
  546. file_handler.write("{")
  547. Export_babylon.write_int(file_handler, "materialIndex", subMesh.materialIndex, True)
  548. Export_babylon.write_int(file_handler, "verticesStart", subMesh.verticesStart)
  549. Export_babylon.write_int(file_handler, "verticesCount", subMesh.verticesCount)
  550. Export_babylon.write_int(file_handler, "indexStart", subMesh.indexStart)
  551. Export_babylon.write_int(file_handler, "indexCount", subMesh.indexCount)
  552. file_handler.write("}")
  553. first = False
  554. file_handler.write("]")
  555. #Export Animations
  556. rotAnim = False
  557. locAnim = False
  558. scaAnim = False
  559. coma = False
  560. if object.animation_data:
  561. if object.animation_data.action:
  562. file_handler.write(",\"animations\":[")
  563. for fcurve in object.animation_data.action.fcurves:
  564. if fcurve.data_path == "rotation_euler" and rotAnim == False:
  565. Export_babylon.export_animation(object, scene, file_handler, "rotation_euler", "rotation", coma, -1)
  566. rotAnim = coma = True
  567. elif fcurve.data_path == "location" and locAnim == False:
  568. Export_babylon.export_animation(object, scene, file_handler, "location", "position", coma, 1)
  569. locAnim = coma = True
  570. elif fcurve.data_path == "scale" and scaAnim == False:
  571. Export_babylon.export_animation(object, scene, file_handler, "scale", "scaling", coma, 1)
  572. locAnim = coma = True
  573. file_handler.write("]")
  574. #Set Animations
  575. Export_babylon.write_bool(file_handler, "autoAnimate", True)
  576. Export_babylon.write_int(file_handler, "autoAnimateFrom", 0)
  577. Export_babylon.write_int(file_handler, "autoAnimateTo", bpy.context.scene.frame_end - bpy.context.scene.frame_start + 1)
  578. Export_babylon.write_bool(file_handler, "autoAnimateLoop", True)
  579. # Closing
  580. file_handler.write("}")
  581. return finish
  582. def export_node(object, scene, file_handler):
  583. # Transform
  584. loc = mathutils.Vector((0, 0, 0))
  585. rot = mathutils.Quaternion((0, 0, 0, 1))
  586. scale = mathutils.Vector((1, 1, 1))
  587. world = object.matrix_world
  588. if (object.parent):
  589. world = object.parent.matrix_world.inverted() * object.matrix_world
  590. loc, rot, scale = world.decompose()
  591. # Writing node
  592. file_handler.write("{")
  593. Export_babylon.write_string(file_handler, "name", object.name, True)
  594. Export_babylon.write_string(file_handler, "id", object.name)
  595. if object.parent != None:
  596. Export_babylon.write_string(file_handler, "parentId", object.parent.name)
  597. Export_babylon.write_vector(file_handler, "position", loc)
  598. Export_babylon.write_vectorScaled(file_handler, "rotation", rot.to_euler("XYZ"), -1)
  599. Export_babylon.write_vector(file_handler, "scaling", scale)
  600. Export_babylon.write_bool(file_handler, "isVisible", False)
  601. Export_babylon.write_bool(file_handler, "isEnabled", True)
  602. Export_babylon.write_bool(file_handler, "checkCollisions", False)
  603. Export_babylon.write_int(file_handler, "billboardMode", 0)
  604. Export_babylon.write_bool(file_handler, "receiveShadows", False)
  605. # Closing
  606. file_handler.write("}")
  607. def export_shadowGenerator(lamp, scene, file_handler):
  608. file_handler.write("{")
  609. if lamp.data.shadowMap == 'VAR':
  610. Export_babylon.write_bool(file_handler, "useVarianceShadowMap", True, True)
  611. else:
  612. Export_babylon.write_bool(file_handler, "useVarianceShadowMap", False, True)
  613. Export_babylon.write_int(file_handler, "mapSize", lamp.data.shadowMapSize)
  614. Export_babylon.write_string(file_handler, "lightId", lamp.name)
  615. file_handler.write(",\"renderList\":[")
  616. multiMaterials = []
  617. first = True
  618. for object in [object for object in scene.objects]:
  619. if (object.type == 'MESH' and object.data.castShadows):
  620. if first != True:
  621. file_handler.write(",")
  622. first = False
  623. file_handler.write("\"" + object.name + "\"")
  624. file_handler.write("]")
  625. file_handler.write("}")
  626. def export_bone_matrix(armature, bone, label, file_handler):
  627. SystemMatrix = Matrix.Scale(-1, 4, Vector((0, 0, 1))) * Matrix.Rotation(radians(-90), 4, 'X')
  628. if (bone.parent):
  629. Export_babylon.write_matrix4(file_handler, label, (SystemMatrix * armature.matrix_world * bone.parent.matrix).inverted() * (SystemMatrix * armature.matrix_world * bone.matrix))
  630. else:
  631. Export_babylon.write_matrix4(file_handler, label, SystemMatrix * armature.matrix_world * bone.matrix)
  632. def export_bones(armature, scene, file_handler, id):
  633. file_handler.write("{")
  634. Export_babylon.write_string(file_handler, "name", armature.name, True)
  635. Export_babylon.write_int(file_handler, "id", id)
  636. file_handler.write(",\"bones\":[")
  637. bones = armature.pose.bones
  638. first = True
  639. j = 0
  640. for bone in bones:
  641. if first != True:
  642. file_handler.write(",")
  643. first = False
  644. file_handler.write("{")
  645. Export_babylon.write_string(file_handler, "name", bone.name, True)
  646. Export_babylon.write_int(file_handler, "index", j)
  647. Export_babylon.export_bone_matrix(armature, bone, "matrix", file_handler)
  648. if (bone.parent):
  649. parentId = 0
  650. for parent in bones:
  651. if parent == bone.parent:
  652. break;
  653. parentId += 1
  654. Export_babylon.write_int(file_handler, "parentBoneIndex", parentId)
  655. else:
  656. Export_babylon.write_int(file_handler, "parentBoneIndex", -1)
  657. #animation
  658. if (armature.animation_data.action):
  659. Export_babylon.export_bonesAnimation(armature, bone, scene, file_handler)
  660. j = j + 1
  661. file_handler.write("}")
  662. file_handler.write("]")
  663. file_handler.write("}")
  664. def export_bonesAnimation(armature, bone, scene, file_handler):
  665. file_handler.write(",\"animation\": {")
  666. start_frame = scene.frame_start
  667. end_frame = scene.frame_end
  668. fps = scene.render.fps
  669. Export_babylon.write_int(file_handler, "dataType", 3, True)
  670. Export_babylon.write_int(file_handler, "framePerSecond", fps)
  671. #keys
  672. file_handler.write(",\"keys\":[")
  673. for Frame in range(start_frame, end_frame + 1):
  674. file_handler.write("{")
  675. Export_babylon.write_int(file_handler, "frame", Frame, True)
  676. bpy.context.scene.frame_set(Frame)
  677. Export_babylon.export_bone_matrix(armature, bone, "values", file_handler)
  678. if Frame == end_frame:
  679. file_handler.write("}")
  680. else:
  681. file_handler.write("},")
  682. file_handler.write("]")
  683. Export_babylon.write_int(file_handler, "loopBehavior", 1)
  684. Export_babylon.write_string(file_handler, "name", "anim")
  685. Export_babylon.write_string(file_handler, "property", "_matrix")
  686. file_handler.write("}")
  687. bpy.context.scene.frame_set(start_frame)
  688. def save(operator, context, filepath="",
  689. use_apply_modifiers=False,
  690. use_triangulate=True,
  691. use_compress=False):
  692. # Open file
  693. file_handler = open(filepath, 'w')
  694. if bpy.ops.object.mode_set.poll():
  695. bpy.ops.object.mode_set(mode='OBJECT')
  696. # Writing scene
  697. scene=context.scene
  698. world = scene.world
  699. if world:
  700. world_ambient = world.ambient_color
  701. else:
  702. world_ambient = Color((0.0, 0.0, 0.0))
  703. bpy.ops.screen.animation_cancel()
  704. currentFrame = bpy.context.scene.frame_current
  705. bpy.context.scene.frame_set(0)
  706. file_handler.write("{")
  707. file_handler.write("\"autoClear\":true")
  708. Export_babylon.write_color(file_handler, "clearColor", world_ambient)
  709. Export_babylon.write_color(file_handler, "ambientColor", world_ambient)
  710. Export_babylon.write_vector(file_handler, "gravity", scene.gravity)
  711. if world and world.mist_settings.use_mist:
  712. Export_babylon.write_int(file_handler, "fogMode", 3)
  713. Export_babylon.write_color(file_handler, "fogColor", world.horizon_color)
  714. Export_babylon.write_float(file_handler, "fogStart", world.mist_settings.start)
  715. Export_babylon.write_float(file_handler, "fogEnd", world.mist_settings.depth)
  716. Export_babylon.write_float(file_handler, "fogDensity", 0.1)
  717. # Cameras
  718. file_handler.write(",\"cameras\":[")
  719. first = True
  720. for object in [object for object in scene.objects if object.is_visible(scene)]:
  721. if (object.type == 'CAMERA'):
  722. if first != True:
  723. file_handler.write(",")
  724. first = False
  725. data_string = Export_babylon.export_camera(object, scene, file_handler)
  726. file_handler.write("]")
  727. # Active camera
  728. if scene.camera != None:
  729. Export_babylon.write_string(file_handler, "activeCamera", scene.camera.name)
  730. # Lights
  731. file_handler.write(",\"lights\":[")
  732. first = True
  733. for object in [object for object in scene.objects if object.is_visible(scene)]:
  734. if (object.type == 'LAMP'):
  735. if first != True:
  736. file_handler.write(",")
  737. first = False
  738. data_string = Export_babylon.export_light(object, scene, file_handler)
  739. file_handler.write("]")
  740. # Materials
  741. materials = [mat for mat in bpy.data.materials if mat.users >= 1]
  742. file_handler.write(",\"materials\":[")
  743. first = True
  744. for material in materials:
  745. if first != True:
  746. file_handler.write(",")
  747. first = False
  748. data_string = Export_babylon.export_material(material, scene, file_handler, filepath)
  749. file_handler.write("]")
  750. # Meshes
  751. file_handler.write(",\"meshes\":[")
  752. multiMaterials = []
  753. first = True
  754. for object in [object for object in scene.objects]:
  755. if object.type == 'MESH' or object.type == 'EMPTY':
  756. if first != True:
  757. file_handler.write(",")
  758. first = False
  759. if object.type == 'MESH':
  760. maxVertex = 65535
  761. minVertex = 0
  762. while True:
  763. finish = Export_babylon.export_mesh(object, scene, file_handler, multiMaterials, minVertex, maxVertex)
  764. if finish:
  765. break
  766. minVertex = maxVertex
  767. maxVertex = minVertex + 65535
  768. file_handler.write(",")
  769. else:
  770. data_string = Export_babylon.export_node(object, scene, file_handler)
  771. file_handler.write("]")
  772. # Multi-materials
  773. file_handler.write(",\"multiMaterials\":[")
  774. first = True
  775. for multimaterial in multiMaterials:
  776. if first != True:
  777. file_handler.write(",")
  778. first = False
  779. data_string = Export_babylon.export_multimaterial(multimaterial, scene, file_handler)
  780. file_handler.write("]")
  781. # Shadow generators
  782. file_handler.write(",\"shadowGenerators\":[")
  783. first = True
  784. for object in [object for object in scene.objects if object.is_visible(scene)]:
  785. if (object.type == 'LAMP' and object.data.shadowMap != 'NONE'):
  786. if first != True:
  787. file_handler.write(",")
  788. first = False
  789. data_string = Export_babylon.export_shadowGenerator(object, scene, file_handler)
  790. file_handler.write("]")
  791. # Armatures/Bones
  792. file_handler.write(",\"skeletons\":[")
  793. first = True
  794. i = 0
  795. for object in [object for object in scene.objects if object.is_visible(scene)]:
  796. if (object.type == 'ARMATURE'):
  797. if first != True:
  798. file_handler.write(",")
  799. first = False
  800. data_string = Export_babylon.export_bones(object, scene, file_handler, i)
  801. i = i+1
  802. file_handler.write("]")
  803. # Closing
  804. file_handler.write("}")
  805. file_handler.close()
  806. bpy.context.scene.frame_set(currentFrame)
  807. return {'FINISHED'}
  808. # UI
  809. bpy.types.Mesh.useFlatShading = BoolProperty(
  810. name="Use Flat Shading",
  811. default = False)
  812. bpy.types.Mesh.checkCollisions = BoolProperty(
  813. name="Check Collisions",
  814. default = False)
  815. bpy.types.Mesh.castShadows = BoolProperty(
  816. name="Cast Shadows",
  817. default = False)
  818. bpy.types.Mesh.receiveShadows = BoolProperty(
  819. name="Receive Shadows",
  820. default = False)
  821. bpy.types.Camera.checkCollisions = BoolProperty(
  822. name="Check Collisions",
  823. default = False)
  824. bpy.types.Camera.applyGravity = BoolProperty(
  825. name="Apply Gravity",
  826. default = False)
  827. bpy.types.Camera.ellipsoid = FloatVectorProperty(
  828. name="Ellipsoid",
  829. default = mathutils.Vector((0.2, 0.9, 0.2)))
  830. bpy.types.Lamp.shadowMap = EnumProperty(
  831. name="Shadow Map Type",
  832. items = (('NONE', "None", "No Shadow Maps"), ('STD', "Standard", "Use Standard Shadow Maps"), ('VAR', "Variance", "Use Variance Shadow Maps")),
  833. default = 'NONE')
  834. bpy.types.Lamp.shadowMapSize = IntProperty(
  835. name="Shadow Map Size",
  836. default = 512)
  837. class ObjectPanel(bpy.types.Panel):
  838. bl_label = "Babylon.js"
  839. bl_space_type = "PROPERTIES"
  840. bl_region_type = "WINDOW"
  841. bl_context = "data"
  842. def draw(self, context):
  843. ob = context.object
  844. if not ob or not ob.data:
  845. return
  846. layout = self.layout
  847. isMesh = isinstance(ob.data, bpy.types.Mesh)
  848. isCamera = isinstance(ob.data, bpy.types.Camera)
  849. isLight = isinstance(ob.data, bpy.types.Lamp)
  850. if isMesh:
  851. layout.prop(ob.data, 'useFlatShading')
  852. layout.prop(ob.data, 'checkCollisions')
  853. layout.prop(ob.data, 'castShadows')
  854. layout.prop(ob.data, 'receiveShadows')
  855. elif isCamera:
  856. layout.prop(ob.data, 'checkCollisions')
  857. layout.prop(ob.data, 'applyGravity')
  858. layout.prop(ob.data, 'ellipsoid')
  859. elif isLight:
  860. layout.prop(ob.data, 'shadowMap')
  861. layout.prop(ob.data, 'shadowMapSize')
  862. ### REGISTER ###
  863. def menu_func(self, context):
  864. self.layout.operator(Export_babylon.bl_idname, text="Babylon.js (.babylon)")
  865. def register():
  866. bpy.utils.register_module(__name__)
  867. bpy.types.INFO_MT_file_export.append(menu_func)
  868. def unregister():
  869. bpy.utils.unregister_module(__name__)
  870. bpy.types.INFO_MT_file_export.remove(menu_func)
  871. if __name__ == "__main__":
  872. register()