io_export_babylon.py 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738
  1. bl_info = {
  2. "name": "Babylon.js",
  3. "author": "David Catuhe",
  4. "version": (1, 0),
  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. class SubMesh:
  25. materialIndex = 0
  26. verticesStart = 0
  27. verticesCount = 0
  28. indexStart = 0
  29. indexCount = 0
  30. class MultiMaterial:
  31. name = ""
  32. materials = []
  33. class Export_babylon(bpy.types.Operator, ExportHelper):
  34. """Export Babylon.js scene (.babylon)"""
  35. bl_idname = "scene.babylon"
  36. bl_label = "Export Babylon.js scene"
  37. filename_ext = ".babylon"
  38. filepath = ""
  39. # global_scale = FloatProperty(name="Scale", min=0.01, max=1000.0, default=1.0)
  40. def execute(self, context):
  41. return Export_babylon.save(self, context, **self.as_keywords(ignore=("check_existing", "filter_glob", "global_scale")))
  42. def mesh_triangulate(mesh):
  43. import bmesh
  44. bm = bmesh.new()
  45. bm.from_mesh(mesh)
  46. bmesh.ops.triangulate(bm, faces=bm.faces)
  47. bm.to_mesh(mesh)
  48. mesh.calc_tessface()
  49. bm.free()
  50. def write_array3(file_handler, name, array):
  51. file_handler.write(",\""+name+"\":[" + "%.4f,%.4f,%.4f"%(array[0],array[1],array[2]) + "]")
  52. def write_color(file_handler, name, color):
  53. file_handler.write(",\""+name+"\":[" + "%.4f,%.4f,%.4f"%(color.r,color.g,color.b) + "]")
  54. def write_vector(file_handler, name, vector):
  55. file_handler.write(",\""+name+"\":[" + "%.4f,%.4f,%.4f"%(vector.x,vector.z,vector.y) + "]")
  56. def write_string(file_handler, name, string, noComma=False):
  57. if noComma == False:
  58. file_handler.write(",")
  59. file_handler.write("\""+name+"\":\"" + string + "\"")
  60. def write_float(file_handler, name, float):
  61. file_handler.write(",\""+name+"\":" + "%.4f"%(float))
  62. def write_int(file_handler, name, int, noComma=False):
  63. if noComma == False:
  64. file_handler.write(",")
  65. file_handler.write("\""+name+"\":" + str(int))
  66. def write_bool(file_handler, name, bool, noComma=False):
  67. if noComma == False:
  68. file_handler.write(",")
  69. if bool:
  70. file_handler.write("\""+name+"\":" + "true")
  71. else:
  72. file_handler.write("\""+name+"\":" + "false")
  73. def getDirection(matrix):
  74. return (matrix.to_3x3() * mathutils.Vector((0.0, 0.0, -1.0))).normalized()
  75. def export_camera(object, scene, file_handler):
  76. invWorld = object.matrix_world.copy()
  77. invWorld.invert()
  78. target = mathutils.Vector((0, 1, 0)) * invWorld
  79. file_handler.write("{")
  80. Export_babylon.write_string(file_handler, "name", object.name, True)
  81. Export_babylon.write_string(file_handler, "id", object.name)
  82. Export_babylon.write_vector(file_handler, "position", object.location)
  83. Export_babylon.write_vector(file_handler, "target", target)
  84. Export_babylon.write_float(file_handler, "fov", object.data.angle)
  85. Export_babylon.write_float(file_handler, "minZ", object.data.clip_start)
  86. Export_babylon.write_float(file_handler, "maxZ", object.data.clip_end)
  87. Export_babylon.write_float(file_handler, "speed", 1.0)
  88. Export_babylon.write_float(file_handler, "inertia", 0.9)
  89. Export_babylon.write_bool(file_handler, "checkCollisions", object.data.checkCollisions)
  90. Export_babylon.write_bool(file_handler, "applyGravity", object.data.applyGravity)
  91. Export_babylon.write_array3(file_handler, "ellipsoid", object.data.ellipsoid)
  92. file_handler.write("}")
  93. def export_light(object, scene, file_handler):
  94. light_type_items = {'POINT': 0, 'SUN': 1, 'SPOT': 2, 'HEMI': 3, 'AREA': 0}
  95. light_type = light_type_items[object.data.type]
  96. file_handler.write("{")
  97. Export_babylon.write_string(file_handler, "name", object.name, True)
  98. Export_babylon.write_string(file_handler, "id", object.name)
  99. Export_babylon.write_float(file_handler, "type", light_type)
  100. if light_type == 0:
  101. Export_babylon.write_vector(file_handler, "position", object.location)
  102. elif light_type == 1:
  103. direction = Export_babylon.getDirection(object.matrix_world)
  104. Export_babylon.write_vector(file_handler, "position", object.location)
  105. Export_babylon.write_vector(file_handler, "direction", direction)
  106. elif light_type == 2:
  107. Export_babylon.write_vector(file_handler, "position", object.location)
  108. direction = Export_babylon.getDirection(object.matrix_world)
  109. Export_babylon.write_vector(file_handler, "direction", direction)
  110. Export_babylon.write_float(file_handler, "angle", object.data.spot_size)
  111. Export_babylon.write_float(file_handler, "exponent", object.data.spot_blend * 2)
  112. else:
  113. matrix_world = object.matrix_world.copy()
  114. matrix_world.translation = mathutils.Vector((0, 0, 0))
  115. direction = mathutils.Vector((0, 0, -1)) * matrix_world
  116. Export_babylon.write_vector(file_handler, "direction", -direction)
  117. Export_babylon.write_color(file_handler, "groundColor", mathutils.Color((0, 0, 0)))
  118. Export_babylon.write_float(file_handler, "intensity", object.data.energy)
  119. if object.data.use_diffuse:
  120. Export_babylon.write_color(file_handler, "diffuse", object.data.color)
  121. else:
  122. Export_babylon.write_color(file_handler, "diffuse", mathutils.Color((0, 0, 0)))
  123. if object.data.use_specular:
  124. Export_babylon.write_color(file_handler, "specular", object.data.color)
  125. else:
  126. Export_babylon.write_color(file_handler, "specular", mathutils.Color((0, 0, 0)))
  127. file_handler.write("}")
  128. def export_texture(slot, level, texture, scene, file_handler, filepath):
  129. # Copy image to output
  130. try:
  131. image = texture.texture.image
  132. imageFilepath = os.path.normpath(bpy.path.abspath(image.filepath))
  133. basename = os.path.basename(imageFilepath)
  134. targetdir = os.path.dirname(filepath)
  135. targetpath = os.path.join(targetdir, basename)
  136. if image.packed_file:
  137. image.save_render(targetpath)
  138. else:
  139. sourcepath = bpy.path.abspath(image.filepath)
  140. shutil.copy(sourcepath, targetdir)
  141. except:
  142. pass
  143. # Export
  144. file_handler.write(",\""+slot+"\":{")
  145. Export_babylon.write_string(file_handler, "name", basename, True)
  146. Export_babylon.write_float(file_handler, "level", level)
  147. Export_babylon.write_float(file_handler, "hasAlpha", texture.texture.use_alpha)
  148. coordinatesMode = 0;
  149. if (texture.mapping == "CUBE"):
  150. coordinatesMode = 3;
  151. if (texture.mapping == "SPHERE"):
  152. coordinatesMode = 1;
  153. Export_babylon.write_int(file_handler, "coordinatesMode", coordinatesMode)
  154. Export_babylon.write_float(file_handler, "uOffset", texture.offset.x)
  155. Export_babylon.write_float(file_handler, "vOffset", texture.offset.y)
  156. Export_babylon.write_float(file_handler, "uScale", texture.scale.x)
  157. Export_babylon.write_float(file_handler, "vScale", texture.scale.y)
  158. Export_babylon.write_float(file_handler, "uAng", 0)
  159. Export_babylon.write_float(file_handler, "vAng", 0)
  160. Export_babylon.write_float(file_handler, "wAng", 0)
  161. if (texture.texture.extension == "REPEAT"):
  162. Export_babylon.write_bool(file_handler, "wrapU", True)
  163. Export_babylon.write_bool(file_handler, "wrapV", True)
  164. else:
  165. Export_babylon.write_bool(file_handler, "wrapU", False)
  166. Export_babylon.write_bool(file_handler, "wrapV", False)
  167. Export_babylon.write_int(file_handler, "coordinatesIndex", 0)
  168. file_handler.write("}")
  169. def export_material(material, scene, file_handler, filepath):
  170. file_handler.write("{")
  171. Export_babylon.write_string(file_handler, "name", material.name, True)
  172. Export_babylon.write_string(file_handler, "id", material.name)
  173. Export_babylon.write_color(file_handler, "ambient", material.ambient * material.diffuse_color)
  174. Export_babylon.write_color(file_handler, "diffuse", material.diffuse_intensity * material.diffuse_color)
  175. Export_babylon.write_color(file_handler, "specular", material.specular_intensity * material.specular_color)
  176. Export_babylon.write_float(file_handler, "specularPower", material.specular_hardness)
  177. Export_babylon.write_color(file_handler, "emissive", material.emit * material.diffuse_color)
  178. Export_babylon.write_float(file_handler, "alpha", material.alpha)
  179. Export_babylon.write_bool(file_handler, "backFaceCulling", material.game_settings.use_backface_culling)
  180. # Textures
  181. for mtex in material.texture_slots:
  182. if mtex and mtex.texture and mtex.texture.type == 'IMAGE':
  183. if mtex.texture.image:
  184. if (mtex.use_map_color_diffuse and(mtex.texture_coords != 'REFLECTION')):
  185. # Diffuse
  186. Export_babylon.export_texture("diffuseTexture", mtex.diffuse_color_factor, mtex, scene, file_handler, filepath)
  187. if mtex.use_map_ambient:
  188. # Ambient
  189. Export_babylon.export_texture("ambientTexture", mtex.ambient_factor, mtex, scene, file_handler, filepath)
  190. if mtex.use_map_alpha:
  191. # Opacity
  192. Export_babylon.export_texture("opacityTexture", mtex.alpha_factor, mtex, scene, file_handler, filepath)
  193. if mtex.use_map_color_diffuse and (mtex.texture_coords == 'REFLECTION'):
  194. # Reflection
  195. Export_babylon.export_texture("reflectionTexture", mtex.diffuse_color_factor, mtex, scene, file_handler, filepath)
  196. if mtex.use_map_emit:
  197. # Emissive
  198. Export_babylon.export_texture("emissiveTexture", mtex.emit_factor, mtex, scene, file_handler, filepath)
  199. if mtex.use_map_normal:
  200. # Bump
  201. Export_babylon.export_texture("bumpTexture", mtex.emit_factor, mtex, scene, file_handler, filepath)
  202. file_handler.write("}")
  203. def export_multimaterial(multimaterial, scene, file_handler):
  204. file_handler.write("{")
  205. Export_babylon.write_string(file_handler, "name", multimaterial.name, True)
  206. Export_babylon.write_string(file_handler, "id", multimaterial.name)
  207. file_handler.write(",\"materials\":[")
  208. first = True
  209. for materialName in multimaterial.materials:
  210. if first != True:
  211. file_handler.write(",")
  212. file_handler.write("\"" + materialName +"\"")
  213. first = False
  214. file_handler.write("]")
  215. file_handler.write("}")
  216. def export_animation(object, scene, file_handler, typeBl, typeBa, coma):
  217. if coma == True:
  218. file_handler.write(",")
  219. file_handler.write("{")
  220. Export_babylon.write_int(file_handler, "dataType", 1, True)
  221. Export_babylon.write_int(file_handler, "framePerSecond", 30)
  222. Export_babylon.write_int(file_handler, "loopBehavior", 1)
  223. Export_babylon.write_string(file_handler, "name", typeBa+" animation")
  224. Export_babylon.write_string(file_handler, "property", typeBa)
  225. file_handler.write(",\"keys\":[")
  226. frames = dict()
  227. for fcurve in object.animation_data.action.fcurves:
  228. if fcurve.data_path == typeBl:
  229. for key in fcurve.keyframe_points:
  230. frame = key.co.x
  231. frames[frame] = 1
  232. #for each frame (next step ==> set for key frames)
  233. i = 0
  234. for Frame in sorted(frames):
  235. if i == 0 and Frame != 0.0:
  236. file_handler.write("{")
  237. Export_babylon.write_int(file_handler, "frame", 0, True)
  238. bpy.context.scene.frame_set(int(Frame + bpy.context.scene.frame_start))
  239. Export_babylon.write_vector(file_handler, "values", getattr(object,typeBl))
  240. file_handler.write("},")
  241. i = i + 1
  242. file_handler.write("{")
  243. Export_babylon.write_int(file_handler, "frame", Frame, True)
  244. bpy.context.scene.frame_set(int(Frame + bpy.context.scene.frame_start))
  245. Export_babylon.write_vector(file_handler, "values", getattr(object,typeBl))
  246. file_handler.write("}")
  247. if i != len(frames):
  248. file_handler.write(",")
  249. else:
  250. file_handler.write(",{")
  251. Export_babylon.write_int(file_handler, "frame", bpy.context.scene.frame_end - bpy.context.scene.frame_start + 1, True)
  252. bpy.context.scene.frame_set(int(Frame + bpy.context.scene.frame_start))
  253. Export_babylon.write_vector(file_handler, "values", getattr(object,typeBl))
  254. file_handler.write("}")
  255. file_handler.write("]}")
  256. def export_mesh(object, scene, file_handler, multiMaterials):
  257. # Get mesh
  258. mesh = object.to_mesh(scene, True, "PREVIEW")
  259. # Transform
  260. matrix_world = object.matrix_world.copy()
  261. matrix_world.translation = mathutils.Vector((0, 0, 0))
  262. mesh.transform(matrix_world)
  263. # Triangulate mesh if required
  264. Export_babylon.mesh_triangulate(mesh)
  265. # Getting vertices and indices
  266. vertices=",\"vertices\":["
  267. indices=",\"indices\":["
  268. hasUV = True;
  269. hasUV2 = True;
  270. if len(mesh.tessface_uv_textures) > 0:
  271. UVmap=mesh.tessface_uv_textures[0].data
  272. else:
  273. hasUV = False
  274. if len(mesh.tessface_uv_textures) > 1:
  275. UV2map=mesh.tessface_uv_textures[1].data
  276. else:
  277. hasUV2 = False
  278. alreadySavedVertices = []
  279. vertices_UVs=[]
  280. vertices_UV2s=[]
  281. vertices_indices=[]
  282. subMeshes = []
  283. for v in range(0, len(mesh.vertices)):
  284. alreadySavedVertices.append(False)
  285. vertices_UVs.append([])
  286. vertices_UV2s.append([])
  287. vertices_indices.append([])
  288. materialsCount = max(1, len(object.material_slots))
  289. verticesCount = 0
  290. indicesCount = 0
  291. for materialIndex in range(materialsCount):
  292. subMeshes.append(SubMesh())
  293. subMeshes[materialIndex].materialIndex = materialIndex
  294. subMeshes[materialIndex].verticesStart = verticesCount
  295. subMeshes[materialIndex].indexStart = indicesCount
  296. for face in mesh.tessfaces: # For each face
  297. if face.material_index != materialIndex:
  298. continue
  299. for v in range(3): # For each vertex in face
  300. vertex_index = face.vertices[v]
  301. vertex = mesh.vertices[vertex_index]
  302. position = vertex.co
  303. normal = vertex.normal
  304. if hasUV:
  305. vertex_UV = UVmap[face.index].uv[v]
  306. if hasUV2:
  307. vertex_UV2 = UV2map[face.index].uv[v]
  308. # Check if the current vertex is already saved
  309. alreadySaved = alreadySavedVertices[vertex_index]
  310. index_UV = 0
  311. if alreadySaved:
  312. alreadySaved=False
  313. if hasUV:
  314. for vUV in vertices_UVs[vertex_index]:
  315. if (vUV[0]==vertex_UV[0] and vUV[1]==vertex_UV[1]):
  316. if hasUV2:
  317. vUV2 = vertices_UV2s[vertex_index][index_UV]
  318. if (vUV2[0]==vertex_UV2[0] and vUV2[1]==vertex_UV2[1]):
  319. if vertices_indices[vertex_index][index_UV] >= subMeshes[materialIndex].verticesStart:
  320. alreadySaved=True
  321. break
  322. else:
  323. alreadySaved=True
  324. break
  325. index_UV+=1
  326. else:
  327. for savedIndex in vertices_indices[vertex_index]:
  328. if savedIndex >= subMeshes[materialIndex].verticesStart:
  329. alreadySaved=True
  330. break
  331. index_UV+=1
  332. if (alreadySaved):
  333. # Reuse vertex
  334. index=vertices_indices[vertex_index][index_UV]
  335. else:
  336. # Export new one
  337. index=verticesCount
  338. alreadySavedVertices[vertex_index]=True
  339. if hasUV:
  340. vertices_UVs[vertex_index].append(vertex_UV)
  341. if hasUV2:
  342. vertices_UV2s[vertex_index].append(vertex_UV2)
  343. vertices_indices[vertex_index].append(index)
  344. vertices+="%.4f,%.4f,%.4f,"%(position.x,position.z,position.y)
  345. vertices+="%.4f,%.4f,%.4f,"%(normal.x,normal.z,normal.y)
  346. if hasUV:
  347. vertices+="%.4f,%.4f,"%(vertex_UV[0], vertex_UV[1])
  348. if hasUV2:
  349. vertices+="%.4f,%.4f,"%(vertex_UV2[0], vertex_UV2[1])
  350. verticesCount += 1
  351. indices+="%i,"%(index)
  352. indicesCount += 1
  353. subMeshes[materialIndex].verticesCount = verticesCount - subMeshes[materialIndex].verticesStart
  354. subMeshes[materialIndex].indexCount = indicesCount - subMeshes[materialIndex].indexStart
  355. vertices=vertices.rstrip(',')
  356. indices=indices.rstrip(',')
  357. vertices+="]\n"
  358. indices+="]\n"
  359. # Writing mesh
  360. file_handler.write("{")
  361. Export_babylon.write_string(file_handler, "name", object.name, True)
  362. Export_babylon.write_string(file_handler, "id", object.name)
  363. if object.parent != None:
  364. Export_babylon.write_string(file_handler, "parentId", object.parent.name)
  365. if len(object.material_slots) == 1:
  366. material = object.material_slots[0].material
  367. Export_babylon.write_string(file_handler, "materialId", object.material_slots[0].name)
  368. if material.game_settings.face_orientation != "BILLBOARD":
  369. billboardMode = 0
  370. else:
  371. billboardMode = 7
  372. elif len(object.material_slots) > 1:
  373. multimat = MultiMaterial()
  374. multimat.name = "Multimaterial#" + str(len(multiMaterials))
  375. Export_babylon.write_string(file_handler, "materialId", multimat.name)
  376. for mat in object.material_slots:
  377. multimat.materials.append(mat.name)
  378. multiMaterials.append(multimat)
  379. billboardMode = 0
  380. else:
  381. billboardMode = 0
  382. Export_babylon.write_vector(file_handler, "position", object.location)
  383. Export_babylon.write_vector(file_handler, "rotation", mathutils.Vector((0, 0, 0)))
  384. Export_babylon.write_vector(file_handler, "scaling", mathutils.Vector((1, 1, 1)))
  385. Export_babylon.write_bool(file_handler, "isVisible", object.is_visible(scene))
  386. Export_babylon.write_bool(file_handler, "isEnabled", True)
  387. Export_babylon.write_bool(file_handler, "checkCollisions", object.data.checkCollisions)
  388. Export_babylon.write_int(file_handler, "billboardMode", billboardMode)
  389. Export_babylon.write_bool(file_handler, "receiveShadows", object.data.receiveShadows)
  390. if hasUV and hasUV2:
  391. Export_babylon.write_int(file_handler, "uvCount", 2)
  392. elif hasUV:
  393. Export_babylon.write_int(file_handler, "uvCount", 1)
  394. else:
  395. Export_babylon.write_int(file_handler, "uvCount", 0)
  396. file_handler.write(vertices)
  397. file_handler.write(indices)
  398. # Sub meshes
  399. file_handler.write(",\"subMeshes\":[")
  400. first = True
  401. for subMesh in subMeshes:
  402. if first == False:
  403. file_handler.write(",")
  404. file_handler.write("{")
  405. Export_babylon.write_int(file_handler, "materialIndex", subMesh.materialIndex, True)
  406. Export_babylon.write_int(file_handler, "verticesStart", subMesh.verticesStart)
  407. Export_babylon.write_int(file_handler, "verticesCount", subMesh.verticesCount)
  408. Export_babylon.write_int(file_handler, "indexStart", subMesh.indexStart)
  409. Export_babylon.write_int(file_handler, "indexCount", subMesh.indexCount)
  410. file_handler.write("}")
  411. first = False
  412. file_handler.write("]")
  413. #Export Animations
  414. rotAnim = False
  415. locAnim = False
  416. scaAnim = False
  417. coma = False
  418. if object.animation_data:
  419. if object.animation_data.action:
  420. file_handler.write(",\"animations\":[")
  421. for fcurve in object.animation_data.action.fcurves:
  422. if fcurve.data_path == "rotation_euler" and rotAnim == False:
  423. Export_babylon.export_animation(object, scene, file_handler, "rotation_euler", "rotation", coma)
  424. rotAnim = coma = True
  425. elif fcurve.data_path == "location" and locAnim == False:
  426. Export_babylon.export_animation(object, scene, file_handler, "location", "position", coma)
  427. locAnim = coma = True
  428. elif fcurve.data_path == "scale" and scaAnim == False:
  429. Export_babylon.export_animation(object, scene, file_handler, "scale", "scaling", coma)
  430. locAnim = coma = True
  431. file_handler.write("]")
  432. #Set Animations
  433. Export_babylon.write_bool(file_handler, "autoAnimate", True)
  434. Export_babylon.write_int(file_handler, "autoAnimateFrom", 0)
  435. Export_babylon.write_int(file_handler, "autoAnimateTo", bpy.context.scene.frame_end - bpy.context.scene.frame_start + 1)
  436. Export_babylon.write_bool(file_handler, "autoAnimateLoop", True)
  437. # Closing
  438. file_handler.write("}")
  439. def export_shadowGenerator(lamp, scene, file_handler):
  440. file_handler.write("{")
  441. if lamp.data.shadowMap == 'VAR':
  442. Export_babylon.write_bool(file_handler, "useVarianceShadowMap", True, True)
  443. else:
  444. Export_babylon.write_bool(file_handler, "useVarianceShadowMap", False, True)
  445. Export_babylon.write_int(file_handler, "mapSize", lamp.data.shadowMapSize)
  446. Export_babylon.write_string(file_handler, "lightId", lamp.name)
  447. file_handler.write(",\"renderList\":[")
  448. multiMaterials = []
  449. first = True
  450. for object in [object for object in scene.objects]:
  451. if (object.type == 'MESH' and object.data.castShadows):
  452. if first != True:
  453. file_handler.write(",")
  454. first = False
  455. file_handler.write("\"" + object.name + "\"")
  456. file_handler.write("]")
  457. file_handler.write("}")
  458. def save(operator, context, filepath="",
  459. use_apply_modifiers=False,
  460. use_triangulate=True,
  461. use_compress=False):
  462. # Open file
  463. file_handler = open(filepath, 'w')
  464. if bpy.ops.object.mode_set.poll():
  465. bpy.ops.object.mode_set(mode='OBJECT')
  466. # Writing scene
  467. scene=context.scene
  468. world = scene.world
  469. if world:
  470. world_ambient = world.ambient_color
  471. else:
  472. world_ambient = Color((0.0, 0.0, 0.0))
  473. file_handler.write("{")
  474. file_handler.write("\"autoClear\":true")
  475. Export_babylon.write_color(file_handler, "clearColor", world_ambient)
  476. Export_babylon.write_color(file_handler, "ambientColor", world_ambient)
  477. Export_babylon.write_vector(file_handler, "gravity", scene.gravity)
  478. if world and world.mist_settings.use_mist:
  479. Export_babylon.write_int(file_handler, "fogMode", 3)
  480. Export_babylon.write_color(file_handler, "fogColor", world.horizon_color)
  481. Export_babylon.write_float(file_handler, "fogStart", world.mist_settings.start)
  482. Export_babylon.write_float(file_handler, "fogEnd", world.mist_settings.depth)
  483. Export_babylon.write_float(file_handler, "fogDensity", 0.1)
  484. # Cameras
  485. file_handler.write(",\"cameras\":[")
  486. first = True
  487. for object in [object for object in scene.objects if object.is_visible(scene)]:
  488. if (object.type == 'CAMERA'):
  489. if first != True:
  490. file_handler.write(",")
  491. first = False
  492. data_string = Export_babylon.export_camera(object, scene, file_handler)
  493. file_handler.write("]")
  494. # Active camera
  495. if scene.camera != None:
  496. Export_babylon.write_string(file_handler, "activeCamera", scene.camera.name)
  497. # Lights
  498. file_handler.write(",\"lights\":[")
  499. first = True
  500. for object in [object for object in scene.objects if object.is_visible(scene)]:
  501. if (object.type == 'LAMP'):
  502. if first != True:
  503. file_handler.write(",")
  504. first = False
  505. data_string = Export_babylon.export_light(object, scene, file_handler)
  506. file_handler.write("]")
  507. # Materials
  508. materials = [mat for mat in bpy.data.materials if mat.users >= 1]
  509. file_handler.write(",\"materials\":[")
  510. first = True
  511. for material in materials:
  512. if first != True:
  513. file_handler.write(",")
  514. first = False
  515. data_string = Export_babylon.export_material(material, scene, file_handler, filepath)
  516. file_handler.write("]")
  517. # Meshes
  518. file_handler.write(",\"meshes\":[")
  519. multiMaterials = []
  520. first = True
  521. for object in [object for object in scene.objects]:
  522. if (object.type == 'MESH'):
  523. if first != True:
  524. file_handler.write(",")
  525. first = False
  526. data_string = Export_babylon.export_mesh(object, scene, file_handler, multiMaterials)
  527. file_handler.write("]")
  528. # Multi-materials
  529. file_handler.write(",\"multiMaterials\":[")
  530. first = True
  531. for multimaterial in multiMaterials:
  532. if first != True:
  533. file_handler.write(",")
  534. first = False
  535. data_string = Export_babylon.export_multimaterial(multimaterial, scene, file_handler)
  536. file_handler.write("]")
  537. # Shadow generators
  538. file_handler.write(",\"shadowGenerators\":[")
  539. first = True
  540. for object in [object for object in scene.objects if object.is_visible(scene)]:
  541. if (object.type == 'LAMP' and object.data.shadowMap != 'NONE'):
  542. if first != True:
  543. file_handler.write(",")
  544. first = False
  545. data_string = Export_babylon.export_shadowGenerator(object, scene, file_handler)
  546. file_handler.write("]")
  547. # Closing
  548. file_handler.write("}")
  549. file_handler.close()
  550. return {'FINISHED'}
  551. # UI
  552. bpy.types.Mesh.checkCollisions = BoolProperty(
  553. name="Check Collisions",
  554. default = False)
  555. bpy.types.Mesh.castShadows = BoolProperty(
  556. name="Cast Shadows",
  557. default = False)
  558. bpy.types.Mesh.receiveShadows = BoolProperty(
  559. name="Receive Shadows",
  560. default = False)
  561. bpy.types.Camera.checkCollisions = BoolProperty(
  562. name="Check Collisions",
  563. default = False)
  564. bpy.types.Camera.applyGravity = BoolProperty(
  565. name="Apply Gravity",
  566. default = False)
  567. bpy.types.Camera.ellipsoid = FloatVectorProperty(
  568. name="Ellipsoid",
  569. default = mathutils.Vector((0.2, 0.9, 0.2)))
  570. bpy.types.Lamp.shadowMap = EnumProperty(
  571. name="Shadow Map Type",
  572. items = (('NONE', "None", "No Shadow Maps"), ('STD', "Standard", "Use Standard Shadow Maps"), ('VAR', "Variance", "Use Variance Shadow Maps")),
  573. default = 'NONE')
  574. bpy.types.Lamp.shadowMapSize = IntProperty(
  575. name="Shadow Map Size",
  576. default = 512)
  577. class ObjectPanel(bpy.types.Panel):
  578. bl_label = "Babylon.js"
  579. bl_space_type = "PROPERTIES"
  580. bl_region_type = "WINDOW"
  581. bl_context = "data"
  582. def draw(self, context):
  583. ob = context.object
  584. if not ob or not ob.data:
  585. return
  586. layout = self.layout
  587. isMesh = isinstance(ob.data, bpy.types.Mesh)
  588. isCamera = isinstance(ob.data, bpy.types.Camera)
  589. isLight = isinstance(ob.data, bpy.types.Lamp)
  590. if isMesh:
  591. layout.prop(ob.data, 'checkCollisions')
  592. layout.prop(ob.data, 'castShadows')
  593. layout.prop(ob.data, 'receiveShadows')
  594. elif isCamera:
  595. layout.prop(ob.data, 'checkCollisions')
  596. layout.prop(ob.data, 'applyGravity')
  597. layout.prop(ob.data, 'ellipsoid')
  598. elif isLight:
  599. layout.prop(ob.data, 'shadowMap')
  600. layout.prop(ob.data, 'shadowMapSize')
  601. ### REGISTER ###
  602. def menu_func(self, context):
  603. self.layout.operator(Export_babylon.bl_idname, text="Babylon.js (.babylon)")
  604. def register():
  605. bpy.utils.register_module(__name__)
  606. bpy.types.INFO_MT_file_export.append(menu_func)
  607. def unregister():
  608. bpy.utils.unregister_module(__name__)
  609. bpy.types.INFO_MT_file_export.remove(menu_func)
  610. if __name__ == "__main__":
  611. register()