io_export_babylon.py 48 KB

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