io_export_babylon.py 78 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754
  1. bl_info = {
  2. 'name': 'Babylon.js',
  3. 'author': 'David Catuhe, Jeff Palmer',
  4. 'version': (1, 7, 0),
  5. 'blender': (2, 72, 0),
  6. "location": "File > Export > Babylon.js (.babylon)",
  7. "description": "Export Babylon.js scenes (.babylon)",
  8. 'wiki_url': 'https://github.com/BabylonJS/Babylon.js/wiki/13-Blender',
  9. 'tracker_url': '',
  10. 'category': 'Import-Export'}
  11. import bpy
  12. import bpy_extras.io_utils
  13. import io
  14. import math
  15. import mathutils
  16. import os
  17. import shutil
  18. import sys, traceback # for writing errors to log file
  19. #===============================================================================
  20. # Registration the calling of the INFO_MT_file_export file selector
  21. def menu_func(self, context):
  22. self.layout.operator(BabylonExporter.bl_idname, text = 'Babylon.js [.babylon]')
  23. # store keymaps here to access after registration (commented out for now)
  24. #addon_keymaps = []
  25. def register():
  26. bpy.utils.register_module(__name__)
  27. bpy.types.INFO_MT_file_export.append(menu_func)
  28. # create the hotkey
  29. # kc = bpy.context.window_manager.keyconfigs.addon
  30. # km = kc.keymaps.new(name='3D View', space_type='VIEW_3D')
  31. # kmi = km.keymap_items.new('wm.call_menu', 'W', 'PRESS', alt=True)
  32. # kmi.properties.name = BabylonExporter.bl_idname
  33. # kmi.active = True
  34. # addon_keymaps.append((km, kmi))
  35. def unregister():
  36. bpy.utils.unregister_module(__name__)
  37. bpy.types.INFO_MT_file_export.remove(menu_func)
  38. # for km, kmi in addon_keymaps:
  39. # km.keymap_items.remove(kmi)
  40. # addon_keymaps.clear()
  41. if __name__ == '__main__':
  42. register()
  43. #===============================================================================
  44. # output related constants
  45. MAX_VERTEX_ELEMENTS = 65535
  46. VERTEX_OUTPUT_PER_LINE = 1000
  47. MAX_FLOAT_PRECISION = '%.4f'
  48. MAX_INFLUENCERS_PER_VERTEX = 4
  49. MATERIALS_PATH_VAR = 'materialsRootDir'
  50. # used in World constructor, defined in BABYLON.Scene
  51. #FOGMODE_NONE = 0
  52. #FOGMODE_EXP = 1
  53. #FOGMODE_EXP2 = 2
  54. FOGMODE_LINEAR = 3
  55. # used in Mesh & Node constructors, defined in BABYLON.AbstractMesh
  56. BILLBOARDMODE_NONE = 0
  57. #BILLBOARDMODE_X = 1
  58. #BILLBOARDMODE_Y = 2
  59. #BILLBOARDMODE_Z = 4
  60. BILLBOARDMODE_ALL = 7
  61. # used in Mesh constructor, defined in BABYLON.PhysicsEngine
  62. SPHERE_IMPOSTER = 1
  63. BOX_IMPOSTER = 2
  64. #PLANE_IMPOSTER = 3
  65. MESH_IMPOSTER = 4
  66. CAPSULE_IMPOSTER = 5
  67. CONE_IMPOSTER = 6
  68. CYLINDER_IMPOSTER = 7
  69. CONVEX_HULL_IMPOSTER = 8
  70. # camera class names, never formally defined in Babylon, but used in babylonFileLoader
  71. ANAGLYPH_ARC_CAM = 'AnaglyphArcRotateCamera'
  72. ANAGLYPH_FREE_CAM = 'AnaglyphFreeCamera'
  73. ARC_ROTATE_CAM = 'ArcRotateCamera'
  74. DEV_ORIENT_CAM = 'DeviceOrientationCamera'
  75. FOLLOW_CAM = 'FollowCamera'
  76. FREE_CAM = 'FreeCamera'
  77. GAMEPAD_CAM = 'GamepadCamera'
  78. OCULUS_CAM = 'OculusCamera'
  79. TOUCH_CAM = 'TouchCamera'
  80. V_JOYSTICKS_CAM = 'VirtualJoysticksCamera'
  81. OCULUS_GAMEPAD_CAM = 'OculusGamepadCamera'
  82. VR_DEV_ORIENT_CAM ='VRDeviceOrientationCamera'
  83. WEB_VR_CAM = 'WebVRCamera'
  84. # used in Light constructor, never formally defined in Babylon, but used in babylonFileLoader
  85. POINT_LIGHT = 0
  86. DIRECTIONAL_LIGHT = 1
  87. SPOT_LIGHT = 2
  88. HEMI_LIGHT = 3
  89. # used in Texture constructor, defined in BABYLON.Texture
  90. CLAMP_ADDRESSMODE = 0
  91. WRAP_ADDRESSMODE = 1
  92. MIRROR_ADDRESSMODE = 2
  93. # used in Texture constructor, defined in BABYLON.Texture
  94. EXPLICIT_MODE = 0
  95. SPHERICAL_MODE = 1
  96. #PLANAR_MODE = 2
  97. CUBIC_MODE = 3
  98. #PROJECTION_MODE = 4
  99. #SKYBOX_MODE = 5
  100. # passed to Animation constructor from animatable objects, defined in BABYLON.Animation
  101. #ANIMATIONTYPE_FLOAT = 0
  102. ANIMATIONTYPE_VECTOR3 = 1
  103. #ANIMATIONTYPE_QUATERNION = 2
  104. ANIMATIONTYPE_MATRIX = 3
  105. #ANIMATIONTYPE_COLOR3 = 4
  106. # passed to Animation constructor from animatable objects, defined in BABYLON.Animation
  107. #ANIMATIONLOOPMODE_RELATIVE = 0
  108. ANIMATIONLOOPMODE_CYCLE = 1
  109. #ANIMATIONLOOPMODE_CONSTANT = 2
  110. #===============================================================================
  111. class BabylonExporter(bpy.types.Operator, bpy_extras.io_utils.ExportHelper):
  112. bl_idname = 'scene.babylon' # module will not load with out it, also must have a dot
  113. bl_label = 'Export Babylon.js scene' # used on the label of the actual 'save' button
  114. filename_ext = '.babylon' # required to have one, although not really used
  115. filepath = bpy.props.StringProperty(subtype = 'FILE_PATH') # assigned once the file selector returns
  116. log_handler = None # assigned in execute
  117. nameSpace = None # assigned in execute
  118. # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  119. export_onlyCurrentLayer = bpy.props.BoolProperty(
  120. name="Export only current layer",
  121. description="Export only current layer",
  122. default = False,
  123. )
  124. def draw(self, context):
  125. layout = self.layout
  126. layout.prop(self, 'export_onlyCurrentLayer')
  127. # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  128. nWarnings = 0
  129. @staticmethod
  130. def warn(msg, numTabIndent = 1, noNewLine = False):
  131. BabylonExporter.log(msg, numTabIndent, noNewLine)
  132. BabylonExporter.nWarnings += 1
  133. @staticmethod
  134. def log(msg, numTabIndent = 1, noNewLine = False):
  135. for i in range(numTabIndent):
  136. BabylonExporter.log_handler.write('\t')
  137. BabylonExporter.log_handler.write(msg)
  138. if not noNewLine: BabylonExporter.log_handler.write('\n')
  139. # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  140. materials = []
  141. @staticmethod
  142. def uvRequiredForMaterial(baseMaterialId):
  143. fullName = BabylonExporter.nameSpace + '.' + baseMaterialId
  144. for material in BabylonExporter.materials:
  145. if material.name == fullName and len(material.textures) > 0:
  146. return True
  147. return False
  148. # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  149. def execute(self, context):
  150. try:
  151. filepathDotExtension = self.filepath.rpartition('.')
  152. self.filepathMinusExtension = filepathDotExtension[0]
  153. # assign nameSpace, based on OS
  154. if self.filepathMinusExtension.find('\\') != -1:
  155. BabylonExporter.nameSpace = legal_js_identifier(self.filepathMinusExtension.rpartition('\\')[2])
  156. else:
  157. BabylonExporter.nameSpace = legal_js_identifier(self.filepathMinusExtension.rpartition('/')[2])
  158. # explicitly reset globals, in case there was an earlier export this session
  159. BabylonExporter.nWarnings = 0
  160. BabylonExporter.materials = []
  161. BabylonExporter.log_handler = io.open(self.filepathMinusExtension + '.log', 'w', encoding='utf8')
  162. BabylonExporter_version = bl_info['version']
  163. BabylonExporter.log('Babylon.js Exporter version: ' + str(BabylonExporter_version[0]) + '.' + str(BabylonExporter_version[1]) + '.' + str(BabylonExporter_version[2]) +
  164. ', Blender version: ' + bpy.app.version_string)
  165. if bpy.ops.object.mode_set.poll():
  166. bpy.ops.object.mode_set(mode = 'OBJECT')
  167. scene = context.scene
  168. BabylonExporter.log('========= Conversion from Blender to Babylon.js =========', 0)
  169. self.world = World(scene)
  170. bpy.ops.screen.animation_cancel()
  171. currentFrame = bpy.context.scene.frame_current
  172. bpy.context.scene.frame_set(0)
  173. # Active camera
  174. if scene.camera != None:
  175. self.activeCamera = scene.camera.name
  176. else:
  177. BabylonExporter.warn('WARNING: No active camera has been assigned, or is not in a currently selected Blender layer')
  178. # Materials, static for ease of uvs requirement testing
  179. stuffs = [mat for mat in bpy.data.materials if mat.users >= 1]
  180. for material in stuffs:
  181. BabylonExporter.materials.append(Material(material, scene, self.filepath)) # need file path incase an image texture
  182. self.cameras = []
  183. self.lights = []
  184. self.shadowGenerators = []
  185. self.skeletons = []
  186. skeletonId = 0
  187. self.meshesAndNodes = []
  188. self.multiMaterials = []
  189. # exclude lamps in this pass, so ShadowGenerator constructor can be passed meshesAnNodes
  190. for object in [object for object in scene.objects]:
  191. if object.type == 'CAMERA':
  192. if object.is_visible(scene): # no isInSelectedLayer() required, is_visible() handles this for them
  193. self.cameras.append(Camera(object))
  194. else:
  195. BabylonExporter.warn('WARNING: The following camera not visible in scene thus ignored: ' + object.name)
  196. elif object.type == 'ARMATURE': #skeleton.pose.bones
  197. if object.is_visible(scene):
  198. self.skeletons.append(Skeleton(object, scene, skeletonId))
  199. skeletonId += 1
  200. else:
  201. BabylonExporter.warn('WARNING: The following armature not visible in scene thus ignored: ' + object.name)
  202. elif object.type == 'MESH':
  203. forcedParent = None
  204. nameID = ''
  205. nextStartFace = 0
  206. while True and self.isInSelectedLayer(object, scene):
  207. mesh = Mesh(object, scene, self.multiMaterials, nextStartFace, forcedParent, nameID)
  208. self.meshesAndNodes.append(mesh)
  209. nextStartFace = mesh.offsetFace
  210. if nextStartFace == 0:
  211. break
  212. if forcedParent is None:
  213. nameID = 0
  214. forcedParent = object
  215. BabylonExporter.warn('WARNING: The following mesh has exceeded the maximum # of vertex elements & will be broken into multiple Babylon meshes: ' + object.name)
  216. nameID = nameID + 1
  217. elif object.type == 'EMPTY':
  218. self.meshesAndNodes.append(Node(object))
  219. elif object.type != 'LAMP':
  220. BabylonExporter.warn('WARNING: The following object is not currently exportable thus ignored: ' + object.name)
  221. # Lamp / shadow Generator pass; meshesAnNodes complete & forceParents included
  222. for object in [object for object in scene.objects]:
  223. if object.type == 'LAMP':
  224. if object.is_visible(scene): # no isInSelectedLayer() required, is_visible() handles this for them
  225. bulb = Light(object)
  226. self.lights.append(bulb)
  227. if object.data.shadowMap != 'NONE':
  228. if bulb.light_type == DIRECTIONAL_LIGHT or bulb.light_type == SPOT_LIGHT:
  229. self.shadowGenerators.append(ShadowGenerator(object, self.meshesAndNodes, scene))
  230. else:
  231. BabylonExporter.warn('WARNING: Only directional (sun) and spot types of lamp are valid for shadows thus ignored: ' + object.name)
  232. else:
  233. BabylonExporter.warn('WARNING: The following lamp not visible in scene thus ignored: ' + object.name)
  234. bpy.context.scene.frame_set(currentFrame)
  235. # output file
  236. self.to_scene_file ()
  237. except:# catch *all* exceptions
  238. ex = sys.exc_info()
  239. BabylonExporter.log('========= An error was encountered =========', 0)
  240. stack = traceback.format_tb(ex[2])
  241. for line in stack:
  242. BabylonExporter.log_handler.write(line) # avoid tabs & extra newlines by not calling log() inside catch
  243. BabylonExporter.log_handler.write('ERROR: ' + str(ex[1]) + '\n')
  244. raise
  245. finally:
  246. BabylonExporter.log('========= end of processing =========', 0)
  247. BabylonExporter.log_handler.close()
  248. if (BabylonExporter.nWarnings > 0):
  249. self.report({'WARNING'}, 'Processing completed, but ' + str(BabylonExporter.nWarnings) + ' WARNINGS were raised, see log file.')
  250. return {'FINISHED'}
  251. # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  252. def to_scene_file(self):
  253. BabylonExporter.log('========= Writing of scene file started =========', 0)
  254. # Open file
  255. file_handler = io.open(self.filepathMinusExtension + '.babylon', 'w', encoding='utf8')
  256. file_handler.write('{')
  257. self.world.to_scene_file(file_handler)
  258. # Materials
  259. file_handler.write(',\n"materials":[')
  260. first = True
  261. for material in BabylonExporter.materials:
  262. if first != True:
  263. file_handler.write(',')
  264. first = False
  265. material.to_scene_file(file_handler)
  266. file_handler.write(']')
  267. # Multi-materials
  268. file_handler.write(',\n"multiMaterials":[')
  269. first = True
  270. for multimaterial in self.multiMaterials:
  271. if first != True:
  272. file_handler.write(',')
  273. first = False
  274. multimaterial.to_scene_file(file_handler)
  275. file_handler.write(']')
  276. # Armatures/Bones
  277. file_handler.write(',\n"skeletons":[')
  278. first = True
  279. for skeleton in self.skeletons:
  280. if first != True:
  281. file_handler.write(',')
  282. first = False
  283. skeleton.to_scene_file(file_handler)
  284. file_handler.write(']')
  285. # Meshes
  286. file_handler.write(',\n"meshes":[')
  287. first = True
  288. for m in range(0, len(self.meshesAndNodes)):
  289. mesh = self.meshesAndNodes[m]
  290. # skip if mesh already written by that name, since this one is an instance
  291. skip = False
  292. for n in range(0, m):
  293. skip |= hasattr(mesh, "dataName") and hasattr(self.meshesAndNodes[n], "dataName") and mesh.dataName == self.meshesAndNodes[n].dataName # nodes have no dataname, so no need to check for
  294. if skip: continue
  295. if first != True:
  296. file_handler.write(',')
  297. first = False
  298. mesh.to_scene_file(file_handler, self.meshesAndNodes)
  299. file_handler.write(']')
  300. # Cameras
  301. file_handler.write(',\n"cameras":[')
  302. first = True
  303. for camera in self.cameras:
  304. if hasattr(camera, 'fatalProblem'): continue
  305. if first != True:
  306. file_handler.write(',')
  307. first = False
  308. camera.update_for_target_attributes(self.meshesAndNodes)
  309. camera.to_scene_file(file_handler)
  310. file_handler.write(']')
  311. # Active camera
  312. if hasattr(self, 'activeCamera'):
  313. write_string(file_handler, 'activeCamera', self.activeCamera)
  314. # Lights
  315. file_handler.write(',\n"lights":[')
  316. first = True
  317. for light in self.lights:
  318. if first != True:
  319. file_handler.write(',')
  320. first = False
  321. light.to_scene_file(file_handler)
  322. file_handler.write(']')
  323. # Shadow generators
  324. file_handler.write(',\n"shadowGenerators":[')
  325. first = True
  326. for shadowGen in self.shadowGenerators:
  327. if first != True:
  328. file_handler.write(',')
  329. first = False
  330. shadowGen.to_scene_file(file_handler)
  331. file_handler.write(']')
  332. # Closing
  333. file_handler.write('}')
  334. file_handler.close()
  335. BabylonExporter.log('========= Writing of scene file completed =========', 0)
  336. # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  337. def isInSelectedLayer(self, obj, scene):
  338. return not self.export_onlyCurrentLayer or obj.layers[scene.active_layer]
  339. #===============================================================================
  340. class World:
  341. def __init__(self, scene):
  342. self.autoClear = True
  343. world = scene.world
  344. if world:
  345. self.world_ambient = world.ambient_color
  346. else:
  347. self.world_ambient = mathutils.Color((0.2, 0.2, 0.3))
  348. self.gravity = scene.gravity
  349. if world and world.mist_settings.use_mist:
  350. self.fogMode = FOGMODE_LINEAR
  351. self.fogColor = world.horizon_color
  352. self.fogStart = world.mist_settings.start
  353. self.fogEnd = world.mist_settings.depth
  354. self.fogDensity = 0.1
  355. BabylonExporter.log('Python World class constructor completed')
  356. # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  357. def to_scene_file(self, file_handler):
  358. write_bool(file_handler, 'autoClear', self.autoClear, True)
  359. write_color(file_handler, 'clearColor', self.world_ambient)
  360. write_color(file_handler, 'ambientColor', self.world_ambient)
  361. write_vector(file_handler, 'gravity', self.gravity)
  362. if hasattr(self, 'fogMode'):
  363. write_int(file_handler, 'fogMode', self.fogMode)
  364. write_color(file_handler, 'fogColor', self.fogColor)
  365. write_float(file_handler, 'fogStart', self.fogStart)
  366. write_float(file_handler, 'fogEnd', self.fogEnd)
  367. write_float(file_handler, 'fogDensity', self.fogDensity)
  368. #===============================================================================
  369. class FCurveAnimatable:
  370. def __init__(self, object, supportsRotation, supportsPosition, supportsScaling, xOffsetForRotation = 0):
  371. # just because a sub-class can be animatable does not mean it is
  372. self.animationsPresent = object.animation_data and object.animation_data.action
  373. rotAnim = False
  374. locAnim = False
  375. scaAnim = False
  376. if (self.animationsPresent):
  377. BabylonExporter.log('FCurve animation processing begun for: ' + object.name, 1)
  378. self.animations = []
  379. for fcurve in object.animation_data.action.fcurves:
  380. if supportsRotation and fcurve.data_path == 'rotation_euler' and rotAnim == False:
  381. self.animations.append(VectorAnimation(object, 'rotation_euler', 'rotation', -1, xOffsetForRotation))
  382. rotAnim = True
  383. elif supportsPosition and fcurve.data_path == 'location' and locAnim == False:
  384. self.animations.append(VectorAnimation(object, 'location', 'position', 1))
  385. locAnim = True
  386. elif supportsScaling and fcurve.data_path == 'scale' and scaAnim == False:
  387. self.animations.append(VectorAnimation(object, 'scale', 'scaling', 1))
  388. scaAnim = True
  389. #Set Animations
  390. if (hasattr(object.data, "autoAnimate") and object.data.autoAnimate):
  391. self.autoAnimate = True
  392. self.autoAnimateFrom = bpy.context.scene.frame_end
  393. self.autoAnimateTo = 0
  394. for animation in self.animations:
  395. if self.autoAnimateFrom > animation.get_first_frame():
  396. self.autoAnimateFrom = animation.get_first_frame()
  397. if self.autoAnimateTo < animation.get_last_frame():
  398. self.autoAnimateTo = animation.get_last_frame()
  399. self.autoAnimateLoop = True
  400. # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  401. def to_scene_file(self, file_handler):
  402. if (self.animationsPresent):
  403. file_handler.write('\n,"animations":[')
  404. first = True
  405. for animation in self.animations:
  406. if first == False:
  407. file_handler.write(',')
  408. animation.to_scene_file(file_handler)
  409. first = False
  410. file_handler.write(']')
  411. if (hasattr(self, "autoAnimate") and self.autoAnimate):
  412. write_bool(file_handler, 'autoAnimate', self.autoAnimate)
  413. write_int(file_handler, 'autoAnimateFrom', self.autoAnimateFrom)
  414. write_int(file_handler, 'autoAnimateTo', self.autoAnimateTo)
  415. write_bool(file_handler, 'autoAnimateLoop', self.autoAnimateLoop)
  416. #===============================================================================
  417. class Mesh(FCurveAnimatable):
  418. def __init__(self, object, scene, multiMaterials, startFace, forcedParent, nameID):
  419. super().__init__(object, True, True, True) #Should animations be done when foredParent
  420. self.name = object.name + str(nameID)
  421. BabylonExporter.log('processing begun of mesh: ' + self.name)
  422. self.isVisible = not object.hide_render
  423. self.isEnabled = True
  424. self.useFlatShading = object.data.useFlatShading
  425. self.checkCollisions = object.data.checkCollisions
  426. self.receiveShadows = object.data.receiveShadows
  427. self.castShadows = object.data.castShadows
  428. if forcedParent is None:
  429. self.dataName = object.data.name # used to support shared vertex instances in later passed
  430. if object.parent and object.parent.type != 'ARMATURE':
  431. self.parentId = object.parent.name
  432. else:
  433. self.dataName = self.name
  434. self.parentId = forcedParent.name
  435. # Physics
  436. if object.rigid_body != None:
  437. shape_items = {'SPHERE' : SPHERE_IMPOSTER,
  438. 'BOX' : BOX_IMPOSTER,
  439. 'MESH' : MESH_IMPOSTER,
  440. 'CAPSULE' : CAPSULE_IMPOSTER,
  441. 'CONE' : CONE_IMPOSTER,
  442. 'CYLINDER' : CYLINDER_IMPOSTER,
  443. 'CONVEX_HULL': CONVEX_HULL_IMPOSTER}
  444. shape_type = shape_items[object.rigid_body.collision_shape]
  445. self.physicsImpostor = shape_type
  446. mass = object.rigid_body.mass
  447. if mass < 0.005:
  448. mass = 0
  449. self.physicsMass = mass
  450. self.physicsFriction = object.rigid_body.friction
  451. self.physicsRestitution = object.rigid_body.restitution
  452. # hasSkeleton detection & skeletonID determination
  453. hasSkeleton = True if object.parent and object.parent.type == 'ARMATURE' and len(object.vertex_groups) > 0 else False
  454. if hasSkeleton:
  455. # determine the skeleton ID by iterating thru objects counting armatures until parent is found
  456. i = 0
  457. for obj in [object for object in scene.objects if object.is_visible(scene)]:
  458. if (obj.type == 'ARMATURE'):
  459. if (obj.name == object.parent.name):
  460. self.skeletonId = i
  461. break;
  462. else:
  463. i += 1
  464. # detect if any textures in the material slots, which would mean UV mapping is required
  465. uvRequired = False
  466. for slot in object.material_slots:
  467. uvRequired |= BabylonExporter.uvRequiredForMaterial(slot.name)
  468. if len(object.material_slots) == 1:
  469. self.materialId = BabylonExporter.nameSpace + '.' + object.material_slots[0].name
  470. self.billboardMode = BILLBOARDMODE_ALL if object.material_slots[0].material.game_settings.face_orientation == 'BILLBOARD' else BILLBOARDMODE_NONE;
  471. elif len(object.material_slots) > 1:
  472. multimat = MultiMaterial(object.material_slots, len(multiMaterials))
  473. self.materialId = multimat.name
  474. multiMaterials.append(multimat)
  475. self.billboardMode = BILLBOARDMODE_NONE
  476. else:
  477. self.billboardMode = BILLBOARDMODE_NONE
  478. BabylonExporter.warn('WARNING: No materials have been assigned: ', 2)
  479. # Get mesh
  480. mesh = object.to_mesh(scene, True, 'PREVIEW')
  481. world = object.matrix_world
  482. if object.parent and not hasSkeleton:
  483. world = object.matrix_local
  484. # use defaults when not None
  485. if forcedParent is None:
  486. loc, rot, scale = world.decompose()
  487. self.position = loc
  488. self.rotation = scale_vector(rot.to_euler('XYZ'), -1)
  489. self.scaling = scale
  490. else:
  491. self.position = mathutils.Vector((0, 0, 0))
  492. self.rotation = scale_vector(mathutils.Vector((0, 0, 0)), 1) # isn't scaling 0's by 1 same as 0?
  493. self.scaling = mathutils.Vector((1, 1, 1))
  494. # Triangulate mesh if required
  495. Mesh.mesh_triangulate(mesh)
  496. # Getting vertices and indices
  497. self.positions = []
  498. self.normals = []
  499. self.uvs = [] # not always used
  500. self.uvs2 = [] # not always used
  501. self.colors = [] # not always used
  502. self.indices = []
  503. self.subMeshes = []
  504. hasUV = len(mesh.tessface_uv_textures) > 0
  505. if hasUV:
  506. UVmap = mesh.tessface_uv_textures[0].data
  507. hasUV2 = len(mesh.tessface_uv_textures) > 1
  508. if hasUV2:
  509. UV2map = mesh.tessface_uv_textures[1].data
  510. hasVertexColor = len(mesh.vertex_colors) > 0
  511. if hasVertexColor:
  512. Colormap = mesh.tessface_vertex_colors.active.data
  513. if hasSkeleton:
  514. self.skeletonWeights = []
  515. self.skeletonIndicesCompressed = []
  516. # used tracking of vertices as they are received
  517. alreadySavedVertices = []
  518. vertices_UVs = []
  519. vertices_UV2s = []
  520. vertices_Colors = []
  521. vertices_indices = []
  522. self.offsetFace = 0
  523. for v in range(0, len(mesh.vertices)):
  524. alreadySavedVertices.append(False)
  525. vertices_UVs.append([])
  526. vertices_UV2s.append([])
  527. vertices_Colors.append([])
  528. vertices_indices.append([])
  529. materialsCount = max(1, len(object.material_slots))
  530. verticesCount = 0
  531. indicesCount = 0
  532. for materialIndex in range(materialsCount):
  533. if self.offsetFace != 0:
  534. break
  535. subMeshVerticesStart = verticesCount
  536. subMeshIndexStart = indicesCount
  537. for faceIndex in range(startFace, len(mesh.tessfaces)): # For each face
  538. face = mesh.tessfaces[faceIndex]
  539. if face.material_index != materialIndex:
  540. continue
  541. if verticesCount + 3 > MAX_VERTEX_ELEMENTS:
  542. self.offsetFace = faceIndex
  543. break
  544. for v in range(3): # For each vertex in face
  545. vertex_index = face.vertices[v]
  546. vertex = mesh.vertices[vertex_index]
  547. position = vertex.co
  548. normal = vertex.normal
  549. #skeletons
  550. if hasSkeleton:
  551. matricesWeights = []
  552. matricesWeights.append(0.0)
  553. matricesWeights.append(0.0)
  554. matricesWeights.append(0.0)
  555. matricesWeights.append(0.0)
  556. matricesIndicesCompressed = 0
  557. # Getting influences
  558. i = 0
  559. offset = 0
  560. for group in vertex.groups:
  561. index = group.group
  562. weight = group.weight
  563. for boneIndex, bone in enumerate(object.parent.pose.bones):
  564. if object.vertex_groups[index].name == bone.name:
  565. if (i == MAX_INFLUENCERS_PER_VERTEX):
  566. BabylonExporter.warn('WARNING: Maximum # of influencers exceeded for a vertex, extras ignored', 2)
  567. break
  568. matricesWeights[i] = weight
  569. matricesIndicesCompressed += boneIndex << offset
  570. offset = offset + 8
  571. i = i + 1
  572. # Texture coordinates
  573. if hasUV:
  574. vertex_UV = UVmap[face.index].uv[v]
  575. if hasUV2:
  576. vertex_UV2 = UV2map[face.index].uv[v]
  577. # Vertex color
  578. if hasVertexColor:
  579. if v == 0:
  580. vertex_Color = Colormap[face.index].color1
  581. if v == 1:
  582. vertex_Color = Colormap[face.index].color2
  583. if v == 2:
  584. vertex_Color = Colormap[face.index].color3
  585. # Check if the current vertex is already saved
  586. alreadySaved = alreadySavedVertices[vertex_index] and not hasSkeleton
  587. if alreadySaved:
  588. alreadySaved = False
  589. # UV
  590. index_UV = 0
  591. for savedIndex in vertices_indices[vertex_index]:
  592. if hasUV:
  593. vUV = vertices_UVs[vertex_index][index_UV]
  594. if (vUV[0] != vertex_UV[0] or vUV[1] != vertex_UV[1]):
  595. continue
  596. if hasUV2:
  597. vUV2 = vertices_UV2s[vertex_index][index_UV]
  598. if (vUV2[0] != vertex_UV2[0] or vUV2[1] != vertex_UV2[1]):
  599. continue
  600. if hasVertexColor:
  601. vColor = vertices_Colors[vertex_index][index_UV]
  602. if (vColor.r != vertex_Color.r or vColor.g != vertex_Color.g or vColor.b != vertex_Color.b):
  603. continue
  604. if vertices_indices[vertex_index][index_UV] >= subMeshVerticesStart:
  605. alreadySaved = True
  606. break
  607. index_UV += 1
  608. if (alreadySaved):
  609. # Reuse vertex
  610. index = vertices_indices[vertex_index][index_UV]
  611. else:
  612. # Export new one
  613. index = verticesCount
  614. alreadySavedVertices[vertex_index] = True
  615. if hasUV:
  616. vertices_UVs[vertex_index].append(vertex_UV)
  617. self.uvs.append(vertex_UV[0])
  618. self.uvs.append(vertex_UV[1])
  619. if hasUV2:
  620. vertices_UV2s[vertex_index].append(vertex_UV2)
  621. self.uvs2.append(vertex_UV2[0])
  622. self.uvs2.append(vertex_UV2[1])
  623. if hasVertexColor:
  624. vertices_Colors[vertex_index].append(vertex_Color)
  625. self.colors.append(vertex_Color.r)
  626. self.colors.append(vertex_Color.g)
  627. self.colors.append(vertex_Color.b)
  628. self.colors.append(1.0)
  629. if hasSkeleton:
  630. self.skeletonWeights.append(matricesWeights[0])
  631. self.skeletonWeights.append(matricesWeights[1])
  632. self.skeletonWeights.append(matricesWeights[2])
  633. self.skeletonWeights.append(matricesWeights[3])
  634. self.skeletonIndicesCompressed.append(matricesIndicesCompressed)
  635. vertices_indices[vertex_index].append(index)
  636. self.positions.append(position)
  637. self.normals.append(normal)
  638. verticesCount += 1
  639. self.indices.append(index)
  640. indicesCount += 1
  641. self.subMeshes.append(SubMesh(materialIndex, subMeshVerticesStart, subMeshIndexStart, verticesCount - subMeshVerticesStart, indicesCount - subMeshIndexStart))
  642. BabylonExporter.log('num positions : ' + str(len(self.positions)), 2)
  643. BabylonExporter.log('num normals : ' + str(len(self.normals )), 2)
  644. BabylonExporter.log('num uvs : ' + str(len(self.uvs )), 2)
  645. BabylonExporter.log('num uvs2 : ' + str(len(self.uvs2 )), 2)
  646. BabylonExporter.log('num colors : ' + str(len(self.colors )), 2)
  647. BabylonExporter.log('num indices : ' + str(len(self.indices )), 2)
  648. if hasattr(self, 'skeletonWeights'):
  649. BabylonExporter.log('num skeletonWeights: ' + str(len(self.skeletonWeights)), 2)
  650. BabylonExporter.log('num skeletonIndices: ' + str(len(self.skeletonIndicesCompressed * 4)), 2)
  651. if uvRequired and len(self.uvs) == 0:
  652. BabylonExporter.warn('WARNING: textures being used, but no UV Map found', 2)
  653. numZeroAreaFaces = self.find_zero_area_faces()
  654. if numZeroAreaFaces > 0:
  655. BabylonExporter.warn('WARNING: # of 0 area faces found: ' + str(numZeroAreaFaces), 2)
  656. # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  657. def find_zero_area_faces(self):
  658. nFaces = int(len(self.indices) / 3)
  659. nZeroAreaFaces = 0
  660. for f in range(0, nFaces):
  661. faceOffset = f * 3
  662. p1 = self.positions[self.indices[faceOffset ]]
  663. p2 = self.positions[self.indices[faceOffset + 1]]
  664. p3 = self.positions[self.indices[faceOffset + 2]]
  665. if same_vertex(p1, p2) or same_vertex(p1, p3) or same_vertex(p2, p3): nZeroAreaFaces += 1
  666. return nZeroAreaFaces
  667. # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  668. @staticmethod
  669. def mesh_triangulate(mesh):
  670. try:
  671. import bmesh
  672. bm = bmesh.new()
  673. bm.from_mesh(mesh)
  674. bmesh.ops.triangulate(bm, faces = bm.faces)
  675. bm.to_mesh(mesh)
  676. mesh.calc_tessface()
  677. bm.free()
  678. except:
  679. pass
  680. # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  681. def to_scene_file(self, file_handler, meshesAndNodes):
  682. file_handler.write('{')
  683. write_string(file_handler, 'name', self.name, True)
  684. write_string(file_handler, 'id', self.name)
  685. if hasattr(self, 'parentId'): write_string(file_handler, 'parentId', self.parentId)
  686. if hasattr(self, 'materialId'): write_string(file_handler, 'materialId', self.materialId)
  687. write_int(file_handler, 'billboardMode', self.billboardMode)
  688. write_vector(file_handler, 'position', self.position)
  689. write_vector(file_handler, 'rotation', self.rotation)
  690. write_vector(file_handler, 'scaling', self.scaling)
  691. write_bool(file_handler, 'isVisible', self.isVisible)
  692. write_bool(file_handler, 'isEnabled', self.isEnabled)
  693. write_bool(file_handler, 'useFlatShading', self.useFlatShading)
  694. write_bool(file_handler, 'checkCollisions', self.checkCollisions)
  695. write_bool(file_handler, 'receiveShadows', self.receiveShadows)
  696. if hasattr(self, 'physicsImpostor'):
  697. write_int(file_handler, 'physicsImpostor', self.physicsImpostor)
  698. write_float(file_handler, 'physicsMass', self.physicsMass)
  699. write_float(file_handler, 'physicsFriction', self.physicsFriction)
  700. write_float(file_handler, 'physicsRestitution', self.physicsRestitution)
  701. # Geometry
  702. if hasattr(self, 'skeletonId'): write_int(file_handler, 'skeletonId', self.skeletonId)
  703. write_vector_array(file_handler, 'positions', self.positions)
  704. write_vector_array(file_handler, 'normals' , self.normals )
  705. if len(self.uvs) > 0:
  706. write_array(file_handler, 'uvs', self.uvs)
  707. if len(self.uvs2) > 0:
  708. write_array(file_handler, 'uvs2', self.uvs2)
  709. if len(self.colors) > 0:
  710. write_array(file_handler, 'colors', self.colors)
  711. if hasattr(self, 'skeletonWeights'):
  712. write_array(file_handler, 'matricesWeights', self.skeletonWeights)
  713. write_array(file_handler, 'matricesIndices', self.skeletonIndicesCompressed)
  714. write_array(file_handler, 'indices', self.indices)
  715. # Sub meshes
  716. file_handler.write('\n,"subMeshes":[')
  717. first = True
  718. for subMesh in self.subMeshes:
  719. if first == False:
  720. file_handler.write(',')
  721. subMesh.to_scene_file(file_handler)
  722. first = False
  723. file_handler.write(']')
  724. super().to_scene_file(file_handler) # Animations
  725. # Instances
  726. first = True
  727. file_handler.write('\n,"instances":[')
  728. for mesh in meshesAndNodes:
  729. if hasattr(mesh, "dataName") and mesh.dataName == self.dataName and mesh != self: # nodes have no dataname, so no need to check for
  730. if first == False:
  731. file_handler.write(',')
  732. file_handler.write('{')
  733. write_string(file_handler, 'name', mesh.name, True)
  734. write_vector(file_handler, 'position', mesh.position)
  735. write_vector(file_handler, 'rotation', mesh.rotation)
  736. write_vector(file_handler, 'scaling', mesh.scaling)
  737. file_handler.write('}')
  738. first = False
  739. file_handler.write(']')
  740. # Close mesh
  741. file_handler.write('}\n')
  742. self.alreadyExported = True
  743. #===============================================================================
  744. class Node:
  745. def __init__(self, node):
  746. BabylonExporter.log('processing begun of node: ' + node.name)
  747. self.name = node.name
  748. world = node.matrix_world
  749. if (node.parent):
  750. world = node.parent.matrix_world.inverted() * node.matrix_world
  751. loc, rot, scale = world.decompose()
  752. if node.parent != None:
  753. self.parentId = node.parent.name
  754. self.position = loc
  755. self.rotation = scale_vector(rot.to_euler('XYZ'), -1)
  756. self.scaling = scale
  757. self.isVisible = False
  758. self.isEnabled = True
  759. self.checkCollisions = False
  760. self.billboardMode = BILLBOARDMODE_NONE
  761. self.castShadows = False
  762. self.receiveShadows = False
  763. # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  764. def get_proper_name(self):
  765. return legal_js_identifier(self.name)
  766. # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  767. def to_scene_file(self, file_handler, ignored):
  768. file_handler.write('{')
  769. write_string(file_handler, 'name', self.name, True)
  770. write_string(file_handler, 'id', self.name)
  771. if hasattr(self, 'parentId'): write_string(file_handler, 'parentId', self.parentId)
  772. write_vector(file_handler, 'position', self.position)
  773. write_vector(file_handler, 'rotation', self.rotation)
  774. write_vector(file_handler, 'scaling', self.scaling)
  775. write_bool(file_handler, 'isVisible', self.isVisible)
  776. write_bool(file_handler, 'isEnabled', self.isEnabled)
  777. write_bool(file_handler, 'checkCollisions', self.checkCollisions)
  778. write_int(file_handler, 'billboardMode', self.billboardMode)
  779. write_bool(file_handler, 'receiveShadows', self.receiveShadows)
  780. file_handler.write('}')
  781. #===============================================================================
  782. class SubMesh:
  783. def __init__(self, materialIndex, verticesStart, indexStart, verticesCount, indexCount):
  784. self.materialIndex = materialIndex
  785. self.verticesStart = verticesStart
  786. self.indexStart = indexStart
  787. self.verticesCount = verticesCount
  788. self.indexCount = indexCount
  789. # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  790. def to_scene_file(self, file_handler):
  791. file_handler.write('{')
  792. write_int(file_handler, 'materialIndex', self.materialIndex, True)
  793. write_int(file_handler, 'verticesStart', self.verticesStart)
  794. write_int(file_handler, 'verticesCount', self.verticesCount)
  795. write_int(file_handler, 'indexStart' , self.indexStart)
  796. write_int(file_handler, 'indexCount' , self.indexCount)
  797. file_handler.write('}')
  798. #===============================================================================
  799. class Bone:
  800. def __init__(self, bone, skeleton, scene, index):
  801. BabylonExporter.log('processing begun of bone: ' + bone.name + ', index: '+ str(index))
  802. self.name = bone.name
  803. self.index = index
  804. matrix_world = skeleton.matrix_world
  805. self.matrix = Bone.get_matrix(bone, matrix_world)
  806. parentId = -1
  807. if (bone.parent):
  808. for parent in skeleton.pose.bones:
  809. parentId += 1
  810. if parent == bone.parent:
  811. break;
  812. self.parentBoneIndex = parentId
  813. #animation
  814. if (skeleton.animation_data):
  815. BabylonExporter.log('animation begun of bone: ' + self.name)
  816. self.animation = Animation(ANIMATIONTYPE_MATRIX, scene.render.fps, ANIMATIONLOOPMODE_CYCLE, 'anim', '_matrix')
  817. start_frame = scene.frame_start
  818. end_frame = scene.frame_end
  819. previousBoneMatrix = None
  820. for frame in range(start_frame, end_frame + 1):
  821. bpy.context.scene.frame_set(frame)
  822. currentBoneMatrix = Bone.get_matrix(bone, skeleton.matrix_world)
  823. if (frame != end_frame and currentBoneMatrix == previousBoneMatrix):
  824. continue
  825. self.animation.frames.append(frame)
  826. self.animation.values.append(Bone.get_matrix(bone, matrix_world))
  827. previousBoneMatrix = currentBoneMatrix
  828. bpy.context.scene.frame_set(start_frame)
  829. # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  830. @staticmethod
  831. def get_matrix(bone, matrix_world):
  832. SystemMatrix = mathutils.Matrix.Scale(-1, 4, mathutils.Vector((0, 0, 1))) * mathutils.Matrix.Rotation(math.radians(-90), 4, 'X')
  833. if (bone.parent):
  834. return (SystemMatrix * matrix_world * bone.parent.matrix).inverted() * (SystemMatrix * matrix_world * bone.matrix)
  835. else:
  836. return SystemMatrix * matrix_world * bone.matrix
  837. # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  838. def to_scene_file(self, file_handler):
  839. file_handler.write('\n{')
  840. write_string(file_handler, 'name', self.name, True)
  841. write_int(file_handler, 'index', self.index)
  842. write_matrix4(file_handler, 'matrix', self.matrix)
  843. write_int(file_handler, 'parentBoneIndex', self.parentBoneIndex)
  844. #animation
  845. if hasattr(self, 'animation'):
  846. file_handler.write(',"animation":')
  847. self.animation.to_scene_file(file_handler)
  848. file_handler.write('}')
  849. #===============================================================================
  850. class Skeleton:
  851. def __init__(self, skeleton, scene, id):
  852. BabylonExporter.log('processing begun of skeleton: ' + skeleton.name + ', id: '+ str(id))
  853. self.name = skeleton.name
  854. self.id = id
  855. self.bones = []
  856. bones = skeleton.pose.bones
  857. j = 0
  858. for bone in bones:
  859. self.bones.append(Bone(bone, skeleton, scene, j))
  860. j = j + 1
  861. BabylonExporter.log('processing complete of skeleton: ' + skeleton.name)
  862. # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  863. def to_scene_file(self, file_handler):
  864. file_handler.write('{')
  865. write_string(file_handler, 'name', self.name, True)
  866. write_int(file_handler, 'id', self.id) # keep int for legacy of original exporter
  867. file_handler.write(',"bones":[')
  868. first = True
  869. for bone in self.bones:
  870. if first != True:
  871. file_handler.write(',')
  872. first = False
  873. bone.to_scene_file(file_handler)
  874. file_handler.write(']')
  875. file_handler.write('}')
  876. #===============================================================================
  877. class Camera(FCurveAnimatable):
  878. def __init__(self, camera):
  879. super().__init__(camera, True, True, False, math.pi / 2)
  880. self.CameraType = camera.data.CameraType
  881. self.name = camera.name
  882. BabylonExporter.log('processing begun of camera (' + self.CameraType + '): ' + self.name)
  883. self.position = camera.location
  884. self.rotation = mathutils.Vector((-camera.rotation_euler[0] + math.pi / 2, camera.rotation_euler[1], -camera.rotation_euler[2])) # extra parens needed
  885. self.fov = camera.data.angle
  886. self.minZ = camera.data.clip_start
  887. self.maxZ = camera.data.clip_end
  888. self.speed = 1.0
  889. self.inertia = 0.9
  890. self.checkCollisions = camera.data.checkCollisions
  891. self.applyGravity = camera.data.applyGravity
  892. self.ellipsoid = camera.data.ellipsoid
  893. for constraint in camera.constraints:
  894. if constraint.type == 'TRACK_TO':
  895. self.lockedTargetId = constraint.target.name
  896. break
  897. if self.CameraType == ANAGLYPH_ARC_CAM or self.CameraType == ANAGLYPH_FREE_CAM:
  898. self.anaglyphEyeSpace = camera.data.anaglyphEyeSpace
  899. if self.CameraType == ANAGLYPH_ARC_CAM or self.CameraType == ARC_ROTATE_CAM or self.CameraType == FOLLOW_CAM:
  900. if not hasattr(self, 'lockedTargetId'):
  901. BabylonExporter.warn('ERROR: Camera type with manditory target specified, but no target to track set', 2)
  902. self.fatalProblem = True
  903. # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  904. def update_for_target_attributes(self, meshesAndNodes):
  905. if not hasattr(self, 'lockedTargetId'): return
  906. # find the actual mesh tracking, so properties can be derrived
  907. targetFound = False
  908. for mesh in meshesAndNodes:
  909. if mesh.name == self.lockedTargetId:
  910. targetMesh = mesh
  911. targetFound = True
  912. break;
  913. xApart = 3 if not targetFound else self.position.x - targetMesh.position.x
  914. yApart = 3 if not targetFound else self.position.y - targetMesh.position.y
  915. zApart = 3 if not targetFound else self.position.z - targetMesh.position.z
  916. distance3D = math.sqrt(xApart * xApart + yApart * yApart + zApart * zApart)
  917. alpha = math.atan2(yApart, xApart);
  918. beta = math.atan2(yApart, zApart);
  919. if self.CameraType == FOLLOW_CAM:
  920. self.followHeight = zApart
  921. self.followDistance = distance3D
  922. self.followRotation = 90 + (alpha * 180 / math.pi)
  923. elif self.CameraType == ANAGLYPH_ARC_CAM or self.CameraType == ARC_ROTATE_CAM:
  924. self.arcRotAlpha = alpha
  925. self.arcRotBeta = beta
  926. self.arcRotRadius = distance3D
  927. # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  928. def to_scene_file(self, file_handler):
  929. file_handler.write('{')
  930. write_string(file_handler, 'name', self.name, True)
  931. write_string(file_handler, 'id', self.name)
  932. write_vector(file_handler, 'position', self.position)
  933. write_vector(file_handler, 'rotation', self.rotation)
  934. write_float(file_handler, 'fov', self.fov)
  935. write_float(file_handler, 'minZ', self.minZ)
  936. write_float(file_handler, 'maxZ', self.maxZ)
  937. write_float(file_handler, 'speed', self.speed)
  938. write_float(file_handler, 'inertia', self.inertia)
  939. write_bool(file_handler, 'checkCollisions', self.checkCollisions)
  940. write_bool(file_handler, 'applyGravity', self.applyGravity)
  941. write_array3(file_handler, 'ellipsoid', self.ellipsoid)
  942. write_string(file_handler, 'type', self.CameraType)
  943. if self.CameraType == FOLLOW_CAM:
  944. write_float(file_handler, 'heightOffset', self.followHeight)
  945. write_float(file_handler, 'radius', self.followDistance)
  946. write_float(file_handler, 'rotationOffset', self.followRotation)
  947. elif self.CameraType == ANAGLYPH_ARC_CAM or self.CameraType == ARC_ROTATE_CAM:
  948. write_float(file_handler, 'alpha', self.arcRotAlpha)
  949. write_float(file_handler, 'beta', self.arcRotBeta)
  950. write_float(file_handler, 'radius', self.arcRotRadius)
  951. if self.CameraType == ANAGLYPH_ARC_CAM:
  952. write_float(file_handler, 'eye_space', self.anaglyphEyeSpace)
  953. elif self.CameraType == ANAGLYPH_FREE_CAM:
  954. write_float(file_handler, 'eye_space', self.anaglyphEyeSpace)
  955. if hasattr(self, 'lockedTargetId'):
  956. write_string(file_handler, 'lockedTargetId', self.lockedTargetId)
  957. super().to_scene_file(file_handler) # Animations
  958. file_handler.write('}')
  959. #===============================================================================
  960. class Light(FCurveAnimatable):
  961. def __init__(self, light):
  962. super().__init__(light, False, True, False)
  963. self.name = light.name
  964. BabylonExporter.log('processing begun of light (' + light.data.type + '): ' + self.name)
  965. light_type_items = {'POINT': POINT_LIGHT, 'SUN': DIRECTIONAL_LIGHT, 'SPOT': SPOT_LIGHT, 'HEMI': HEMI_LIGHT, 'AREA': 0}
  966. self.light_type = light_type_items[light.data.type]
  967. if self.light_type == POINT_LIGHT:
  968. self.position = light.location
  969. if light.data.use_sphere:
  970. self.range = light.data.distance
  971. elif self.light_type == DIRECTIONAL_LIGHT:
  972. self.position = light.location
  973. self.direction = Light.get_direction(light.matrix_world)
  974. elif self.light_type == SPOT_LIGHT:
  975. self.position = light.location
  976. self.direction = Light.get_direction(light.matrix_world)
  977. self.angle = light.data.spot_size
  978. self.exponent = light.data.spot_blend * 2
  979. if light.data.use_sphere:
  980. self.range = light.data.distance
  981. else:
  982. # Hemi & Area
  983. matrix_world = light.matrix_world.copy()
  984. matrix_world.translation = mathutils.Vector((0, 0, 0))
  985. self.direction = (mathutils.Vector((0, 0, -1)) * matrix_world)
  986. self.direction = scale_vector(self.direction, -1)
  987. self.groundColor = mathutils.Color((0, 0, 0))
  988. self.intensity = light.data.energy
  989. self.diffuse = light.data.color if light.data.use_diffuse else mathutils.Color((0, 0, 0))
  990. self.specular = light.data.color if light.data.use_specular else mathutils.Color((0, 0, 0))
  991. # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  992. def to_scene_file(self, file_handler):
  993. file_handler.write('{')
  994. write_string(file_handler, 'name', self.name, True)
  995. write_string(file_handler, 'id', self.name)
  996. write_float(file_handler, 'type', self.light_type)
  997. if hasattr(self, 'position' ): write_vector(file_handler, 'position' , self.position )
  998. if hasattr(self, 'direction' ): write_vector(file_handler, 'direction' , self.direction )
  999. if hasattr(self, 'angle' ): write_float (file_handler, 'angle' , self.angle )
  1000. if hasattr(self, 'exponent' ): write_float (file_handler, 'exponent' , self.exponent )
  1001. if hasattr(self, 'groundColor'): write_color (file_handler, 'groundColor', self.groundColor)
  1002. if hasattr(self, 'range' ): write_float (file_handler, 'range' , self.range )
  1003. write_float(file_handler, 'intensity', self.intensity)
  1004. write_color(file_handler, 'diffuse', self.diffuse)
  1005. write_color(file_handler, 'specular', self.specular)
  1006. super().to_scene_file(file_handler) # Animations
  1007. file_handler.write('}')
  1008. @staticmethod
  1009. def get_direction(matrix):
  1010. return (matrix.to_3x3() * mathutils.Vector((0.0, 0.0, -1.0))).normalized()
  1011. #===============================================================================
  1012. class ShadowGenerator:
  1013. def __init__(self, lamp, meshesAndNodes, scene):
  1014. BabylonExporter.log('processing begun of shadows for light: ' + lamp.name)
  1015. self.useVarianceShadowMap = lamp.data.shadowMap == 'VAR' if True else False
  1016. self.mapSize = lamp.data.shadowMapSize
  1017. self.lightId = lamp.name
  1018. self.shadowCasters = []
  1019. for mesh in meshesAndNodes:
  1020. if (mesh.castShadows):
  1021. self.shadowCasters.append(mesh.name)
  1022. # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  1023. def to_scene_file(self, file_handler):
  1024. file_handler.write('{')
  1025. write_bool(file_handler, 'useVarianceShadowMap', self.useVarianceShadowMap, True)
  1026. write_int(file_handler, 'mapSize', self.mapSize)
  1027. write_string(file_handler, 'lightId', self.lightId)
  1028. file_handler.write(',"renderList":[')
  1029. first = True
  1030. for caster in self.shadowCasters:
  1031. if first != True:
  1032. file_handler.write(',')
  1033. first = False
  1034. file_handler.write('"' + caster + '"')
  1035. file_handler.write(']')
  1036. file_handler.write('}')
  1037. #===============================================================================
  1038. class MultiMaterial:
  1039. def __init__(self, material_slots, idx):
  1040. self.name = BabylonExporter.nameSpace + '.' + 'Multimaterial#' + str(idx)
  1041. BabylonExporter.log('processing begun of multimaterial: ' + self.name, 2)
  1042. self.materials = []
  1043. for mat in material_slots:
  1044. self.materials.append(BabylonExporter.nameSpace + '.' + mat.name)
  1045. # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  1046. def to_scene_file(self, file_handler):
  1047. file_handler.write('{')
  1048. write_string(file_handler, 'name', self.name, True)
  1049. write_string(file_handler, 'id', self.name)
  1050. file_handler.write(',"materials":[')
  1051. first = True
  1052. for materialName in self.materials:
  1053. if first != True:
  1054. file_handler.write(',')
  1055. file_handler.write('"' + materialName +'"')
  1056. first = False
  1057. file_handler.write(']')
  1058. file_handler.write('}')
  1059. #===============================================================================
  1060. class Texture:
  1061. def __init__(self, slot, level, texture, filepath):
  1062. # Copy image to output
  1063. try:
  1064. image = texture.texture.image
  1065. imageFilepath = os.path.normpath(bpy.path.abspath(image.filepath))
  1066. basename = os.path.basename(imageFilepath)
  1067. targetdir = os.path.dirname(filepath)
  1068. targetpath = os.path.join(targetdir, basename)
  1069. if image.packed_file:
  1070. image.save_render(targetpath)
  1071. else:
  1072. sourcepath = bpy.path.abspath(image.filepath)
  1073. shutil.copy(sourcepath, targetdir)
  1074. except:
  1075. ex = sys.exc_info()
  1076. BabylonExporter.log_handler.write('Error encountered processing image file: ' + imageFilepath + ', Error: '+ str(ex[1]) + '\n')
  1077. #pass
  1078. # Export
  1079. self.slot = slot
  1080. self.name = basename
  1081. self.level = level
  1082. self.hasAlpha = texture.texture.use_alpha
  1083. if (texture.mapping == 'CUBE'):
  1084. self.coordinatesMode = CUBIC_MODE
  1085. if (texture.mapping == 'SPHERE'):
  1086. self.coordinatesMode = SPHERICAL_MODE
  1087. else:
  1088. self.coordinatesMode = EXPLICIT_MODE
  1089. self.uOffset = texture.offset.x
  1090. self.vOffset = texture.offset.y
  1091. self.uScale = texture.scale.x
  1092. self.vScale = texture.scale.y
  1093. self.uAng = 0
  1094. self.vAng = 0
  1095. self.wAng = 0
  1096. if (texture.texture.extension == 'REPEAT'):
  1097. if (texture.texture.use_mirror_x):
  1098. self.wrapU = MIRROR_ADDRESSMODE
  1099. else:
  1100. self.wrapU = WRAP_ADDRESSMODE
  1101. if (texture.texture.use_mirror_y):
  1102. self.wrapV = MIRROR_ADDRESSMODE
  1103. else:
  1104. self.wrapV = WRAP_ADDRESSMODE
  1105. else:
  1106. self.wrapU = CLAMP_ADDRESSMODE
  1107. self.wrapV = CLAMP_ADDRESSMODE
  1108. self.coordinatesIndex = 0
  1109. # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  1110. def to_scene_file(self, file_handler):
  1111. file_handler.write(', "' + self.slot + '":{')
  1112. write_string(file_handler, 'name', self.name, True)
  1113. write_float(file_handler, 'level', self.level)
  1114. write_float(file_handler, 'hasAlpha', self.hasAlpha)
  1115. write_int(file_handler, 'coordinatesMode', self.coordinatesMode)
  1116. write_float(file_handler, 'uOffset', self.uOffset)
  1117. write_float(file_handler, 'vOffset', self.vOffset)
  1118. write_float(file_handler, 'uScale', self.uScale)
  1119. write_float(file_handler, 'vScale', self.vScale)
  1120. write_float(file_handler, 'uAng', self.uAng)
  1121. write_float(file_handler, 'vAng', self.vAng)
  1122. write_float(file_handler, 'wAng', self.wAng)
  1123. write_int(file_handler, 'wrapU', self.wrapU)
  1124. write_int(file_handler, 'wrapV', self.wrapV)
  1125. write_int(file_handler, 'coordinatesIndex', self.coordinatesIndex)
  1126. file_handler.write('}')
  1127. #===============================================================================
  1128. class Material:
  1129. def __init__(self, material, scene, filepath):
  1130. self.name = BabylonExporter.nameSpace + '.' + material.name
  1131. BabylonExporter.log('processing begun of material: ' + self.name)
  1132. self.ambient = material.ambient * material.diffuse_color
  1133. self.diffuse = material.diffuse_intensity * material.diffuse_color
  1134. self.specular = material.specular_intensity * material.specular_color
  1135. self.emissive = material.emit * material.diffuse_color
  1136. self.specularPower = material.specular_hardness
  1137. self.alpha = material.alpha
  1138. self.backFaceCulling = material.game_settings.use_backface_culling
  1139. # Textures
  1140. self.textures = []
  1141. textures = [mtex for mtex in material.texture_slots if mtex and mtex.texture]
  1142. for mtex in textures:
  1143. if mtex.texture.type == 'IMAGE':
  1144. if mtex.texture.image:
  1145. if (mtex.use_map_color_diffuse and (mtex.texture_coords != 'REFLECTION')):
  1146. # Diffuse
  1147. BabylonExporter.log('Diffuse texture found');
  1148. self.textures.append(Texture('diffuseTexture', mtex.diffuse_color_factor, mtex, filepath))
  1149. if mtex.use_map_ambient:
  1150. # Ambient
  1151. BabylonExporter.log('Ambient texture found');
  1152. self.textures.append(Texture('ambientTexture', mtex.ambient_factor, mtex, filepath))
  1153. if mtex.use_map_alpha:
  1154. # Opacity
  1155. BabylonExporter.log('Opacity texture found');
  1156. self.textures.append(Texture('opacityTexture', mtex.alpha_factor, mtex, filepath))
  1157. if mtex.use_map_color_diffuse and (mtex.texture_coords == 'REFLECTION'):
  1158. # Reflection
  1159. BabylonExporter.log('Reflection texture found');
  1160. self.textures.append(Texture('reflectionTexture', mtex.diffuse_color_factor, mtex, filepath))
  1161. if mtex.use_map_emit:
  1162. # Emissive
  1163. BabylonExporter.log('Emissive texture found');
  1164. self.textures.append(Texture('emissiveTexture', mtex.emit_factor, mtex, filepath))
  1165. if mtex.use_map_normal:
  1166. # Bump
  1167. BabylonExporter.log('Bump texture found');
  1168. self.textures.append(Texture('bumpTexture', mtex.normal_factor, mtex, filepath))
  1169. elif mtex.use_map_color_spec:
  1170. # Specular
  1171. BabylonExporter.log('Specular texture found');
  1172. self.textures.append(Texture('specularTexture', mtex.specular_color_factor, mtex, filepath))
  1173. else:
  1174. BabylonExporter.warn('WARNING image texture type not recognized: ' + str(mtex) + ', ignored.')
  1175. else:
  1176. BabylonExporter.warn('WARNING texture type not currently supported: ' + mtex.texture.type + ', ignored.')
  1177. # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  1178. def to_scene_file(self, file_handler):
  1179. file_handler.write('{')
  1180. write_string(file_handler, 'name', self.name, True)
  1181. write_string(file_handler, 'id', self.name)
  1182. write_color(file_handler, 'ambient', self.ambient)
  1183. write_color(file_handler, 'diffuse', self.diffuse)
  1184. write_color(file_handler, 'specular', self.specular)
  1185. write_color(file_handler, 'emissive', self.emissive)
  1186. write_float(file_handler, 'specularPower', self.specularPower)
  1187. write_float(file_handler, 'alpha', self.alpha)
  1188. write_bool(file_handler, 'backFaceCulling', self.backFaceCulling)
  1189. for texSlot in self.textures:
  1190. texSlot.to_scene_file(file_handler)
  1191. file_handler.write('}')
  1192. #===============================================================================
  1193. class Animation:
  1194. def __init__(self, dataType, framePerSecond, loopBehavior, name, propertyInBabylon):
  1195. self.dataType = dataType
  1196. self.framePerSecond = framePerSecond
  1197. self.loopBehavior = loopBehavior
  1198. self.name = name
  1199. self.propertyInBabylon = propertyInBabylon
  1200. #keys
  1201. self.frames = []
  1202. self.values = [] # vector3 for ANIMATIONTYPE_VECTOR3 & matrices for ANIMATIONTYPE_MATRIX
  1203. # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  1204. # for auto animate
  1205. def get_first_frame(self):
  1206. return self.frames[0] if len(self.frames) > 0 else -1
  1207. # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  1208. # for auto animate
  1209. def get_last_frame(self):
  1210. return self.frames[len(self.frames) - 1] if len(self.frames) > 0 else -1
  1211. # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  1212. def to_scene_file(self, file_handler):
  1213. file_handler.write('{')
  1214. write_int(file_handler, 'dataType', self.dataType, True)
  1215. write_int(file_handler, 'framePerSecond', self.framePerSecond)
  1216. file_handler.write(',"keys":[')
  1217. first = True
  1218. for frame_idx in range(len(self.frames)):
  1219. if first != True:
  1220. file_handler.write(',')
  1221. first = False
  1222. file_handler.write('{')
  1223. write_int(file_handler, 'frame', self.frames[frame_idx], True)
  1224. if self.dataType == ANIMATIONTYPE_MATRIX:
  1225. write_matrix4(file_handler, 'values', self.values[frame_idx])
  1226. else:
  1227. write_vector(file_handler, 'values', self.values[frame_idx])
  1228. file_handler.write('}')
  1229. file_handler.write(']') # close keys
  1230. # put this at the end to make less crazy looking ]}]]]}}}}}}}]]]],
  1231. # since animation is also at the end of the bone, mesh, camera, or light
  1232. write_int(file_handler, 'loopBehavior', self.loopBehavior)
  1233. write_string(file_handler, 'name', self.name)
  1234. write_string(file_handler, 'property', self.propertyInBabylon)
  1235. file_handler.write('}')
  1236. #===============================================================================
  1237. class VectorAnimation(Animation):
  1238. def __init__(self, object, attrInBlender, propertyInBabylon, mult, xOffset = 0):
  1239. super().__init__(ANIMATIONTYPE_VECTOR3, 30, ANIMATIONLOOPMODE_CYCLE, propertyInBabylon + ' animation', propertyInBabylon)
  1240. # capture built up from fcurves
  1241. frames = dict()
  1242. for fcurve in object.animation_data.action.fcurves:
  1243. if fcurve.data_path == attrInBlender:
  1244. for key in fcurve.keyframe_points:
  1245. frame = key.co.x
  1246. frames[frame] = 1
  1247. #for each frame (next step ==> set for key frames)
  1248. for Frame in sorted(frames):
  1249. self.frames.append(Frame)
  1250. bpy.context.scene.frame_set(int(Frame + bpy.context.scene.frame_start))
  1251. self.values.append(scale_vector(getattr(object, attrInBlender), mult, xOffset))
  1252. #===============================================================================
  1253. # module level formatting methods, called from multiple classes
  1254. #===============================================================================
  1255. def legal_js_identifier(input):
  1256. out = ''
  1257. prefix = ''
  1258. for char in input:
  1259. if len(out) == 0:
  1260. if char in '0123456789':
  1261. # cannot take the chance that leading numbers being chopped of cause name conflicts, e.g (01.R & 02.R)
  1262. prefix += char
  1263. continue
  1264. elif char.upper() not in 'ABCDEFGHIJKLMNOPQRSTUVWXYZ':
  1265. continue
  1266. legal = char if char.upper() in 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_' else '_'
  1267. out += legal
  1268. if len(prefix) > 0:
  1269. out += '_' + prefix
  1270. return out
  1271. def format_f(num):
  1272. s = MAX_FLOAT_PRECISION % num # rounds to N decimal places while changing to string
  1273. s = s.rstrip('0') # ignore trailing zeroes
  1274. s = s.rstrip('.') # ignore trailing .
  1275. return '0' if s == '-0' else s
  1276. def format_matrix4(matrix):
  1277. tempMatrix = matrix.copy()
  1278. tempMatrix.transpose()
  1279. ret = ''
  1280. first = True
  1281. for vect in tempMatrix:
  1282. if (first != True):
  1283. ret +=','
  1284. first = False;
  1285. ret += format_f(vect[0]) + ',' + format_f(vect[1]) + ',' + format_f(vect[2]) + ',' + format_f(vect[3])
  1286. return ret
  1287. def format_array3(array):
  1288. return format_f(array[0]) + ',' + format_f(array[1]) + ',' + format_f(array[2])
  1289. def format_array(array, max_per_line = MAX_VERTEX_ELEMENTS, indent = ''):
  1290. ret = ''
  1291. first = True
  1292. nOnLine = 0
  1293. for element in array:
  1294. if (first != True):
  1295. ret +=','
  1296. first = False;
  1297. ret += format_f(element)
  1298. nOnLine += 1
  1299. if nOnLine >= max_per_line:
  1300. ret += '\n' + indent
  1301. nOnLine = 0
  1302. return ret
  1303. def format_color(color):
  1304. return format_f(color.r) + ',' + format_f(color.g) + ',' + format_f(color.b)
  1305. def format_vector(vector):
  1306. return format_f(vector.x) + ',' + format_f(vector.z) + ',' + format_f(vector.y)
  1307. def format_vector_array(vectorArray, max_per_line = MAX_VERTEX_ELEMENTS, indent = ''):
  1308. ret = ''
  1309. first = True
  1310. nOnLine = 0
  1311. for vector in vectorArray:
  1312. if (first != True):
  1313. ret +=','
  1314. first = False;
  1315. ret += format_vector(vector)
  1316. nOnLine += 3
  1317. if nOnLine >= max_per_line:
  1318. ret += '\n' + indent
  1319. nOnLine = 0
  1320. return ret
  1321. def format_quaternion(quaternion):
  1322. return format_f(quaternion.x) + ',' + format_f(quaternion.z) + ',' + format_f(quaternion.y) + ',' + format_f(-quaternion.w)
  1323. def format_int(int):
  1324. candidate = str(int) # when int string of an int
  1325. if '.' in candidate:
  1326. return format_f(math.floor(int)) # format_f removes un-neccessary precision
  1327. else:
  1328. return candidate
  1329. def format_bool(bool):
  1330. if bool:
  1331. return 'true'
  1332. else:
  1333. return 'false'
  1334. def scale_vector(vector, mult, xOffset = 0):
  1335. ret = vector.copy()
  1336. ret.x *= mult
  1337. ret.x += xOffset
  1338. ret.z *= mult
  1339. ret.y *= mult
  1340. return ret
  1341. def same_vertex(vertA, vertB):
  1342. return vertA.x == vertB.x and vertA.y == vertB.y and vertA.z == vertB.z
  1343. #===============================================================================
  1344. # module level methods for writing JSON (.babylon) files
  1345. #===============================================================================
  1346. def write_matrix4(file_handler, name, matrix):
  1347. file_handler.write(',"' + name + '":[' + format_matrix4(matrix) + ']')
  1348. def write_array(file_handler, name, array):
  1349. file_handler.write('\n,"' + name + '":[' + format_array(array) + ']')
  1350. def write_array3(file_handler, name, array):
  1351. file_handler.write(',"' + name + '":[' + format_array3(array) + ']')
  1352. def write_color(file_handler, name, color):
  1353. file_handler.write(',"' + name + '":[' + format_color(color) + ']')
  1354. def write_vector(file_handler, name, vector):
  1355. file_handler.write(',"' + name + '":[' + format_vector(vector) + ']')
  1356. def write_vector_array(file_handler, name, vectorArray):
  1357. file_handler.write('\n,"' + name + '":[' + format_vector_array(vectorArray) + ']')
  1358. def write_quaternion(file_handler, name, quaternion):
  1359. file_handler.write(',"' + name +'":[' + format_quaternion(quaternion) + ']')
  1360. def write_string(file_handler, name, string, noComma = False):
  1361. if noComma == False:
  1362. file_handler.write(',')
  1363. file_handler.write('"' + name + '":"' + string + '"')
  1364. def write_float(file_handler, name, float):
  1365. file_handler.write(',"' + name + '":' + format_f(float))
  1366. def write_int(file_handler, name, int, noComma = False):
  1367. if noComma == False:
  1368. file_handler.write(',')
  1369. file_handler.write('"' + name + '":' + format_int(int))
  1370. def write_bool(file_handler, name, bool, noComma = False):
  1371. if noComma == False:
  1372. file_handler.write(',')
  1373. file_handler.write('"' + name + '":' + format_bool(bool))
  1374. #===============================================================================
  1375. # custom properties definition and display
  1376. #===============================================================================
  1377. bpy.types.Mesh.autoAnimate = bpy.props.BoolProperty(
  1378. name='Automatically launch animations',
  1379. description='',
  1380. default = False
  1381. )
  1382. bpy.types.Mesh.useFlatShading = bpy.props.BoolProperty(
  1383. name='Use Flat Shading',
  1384. description='',
  1385. default = False
  1386. )
  1387. bpy.types.Mesh.checkCollisions = bpy.props.BoolProperty(
  1388. name='Check Collisions',
  1389. description='Indicates mesh should be checked that it does not run into anything.',
  1390. default = False
  1391. )
  1392. bpy.types.Mesh.castShadows = bpy.props.BoolProperty(
  1393. name='Cast Shadows',
  1394. description='',
  1395. default = False
  1396. )
  1397. bpy.types.Mesh.receiveShadows = bpy.props.BoolProperty(
  1398. name='Receive Shadows',
  1399. description='',
  1400. default = False
  1401. )
  1402. #===============================================================================
  1403. bpy.types.Camera.autoAnimate = bpy.props.BoolProperty(
  1404. name='Automatically launch animations',
  1405. description='',
  1406. default = False
  1407. )
  1408. bpy.types.Camera.CameraType = bpy.props.EnumProperty(
  1409. name='Camera Type',
  1410. description='',
  1411. # ONLY Append, or existing .blends will have their camera changed
  1412. items = (
  1413. (V_JOYSTICKS_CAM , 'Virtual Joysticks' , 'Use Virtual Joysticks Camera'),
  1414. (TOUCH_CAM , 'Touch' , 'Use Touch Camera'),
  1415. (OCULUS_CAM , 'Oculus' , 'Use Oculus Camera'),
  1416. (GAMEPAD_CAM , 'Gamepad' , 'Use Gamepad Camera'),
  1417. (FREE_CAM , 'Free' , 'Use Free Camera'),
  1418. (FOLLOW_CAM , 'Follow' , 'Use Follow Camera'),
  1419. (DEV_ORIENT_CAM , 'Device Orientation' , 'Use Device Orientation Camera'),
  1420. (ARC_ROTATE_CAM , 'Arc Rotate' , 'Use Arc Rotate Camera'),
  1421. (ANAGLYPH_FREE_CAM , 'Anaglyph Free' , 'Use Anaglyph Free Camera'),
  1422. (ANAGLYPH_ARC_CAM , 'Anaglyph Arc Rotate', 'Use Anaglyph Arc Rotate Camera'),
  1423. (OCULUS_GAMEPAD_CAM, 'Oculus Gampad' , 'Use Oculus Gamepad Camera'),
  1424. (VR_DEV_ORIENT_CAM , 'VR Dev Orientation' , 'Use VR Dev Orientation Camera'),
  1425. (WEB_VR_CAM , 'Web VR' , 'Use Web VR Camera')
  1426. ),
  1427. default = FREE_CAM
  1428. )
  1429. bpy.types.Camera.checkCollisions = bpy.props.BoolProperty(
  1430. name='Check Collisions',
  1431. description='',
  1432. default = False
  1433. )
  1434. bpy.types.Camera.applyGravity = bpy.props.BoolProperty(
  1435. name='Apply Gravity',
  1436. description='',
  1437. default = False
  1438. )
  1439. bpy.types.Camera.ellipsoid = bpy.props.FloatVectorProperty(
  1440. name='Ellipsoid',
  1441. description='',
  1442. default = mathutils.Vector((0.2, 0.9, 0.2))
  1443. )
  1444. bpy.types.Camera.anaglyphEyeSpace = bpy.props.IntProperty(
  1445. name='Anaglyph Eye space',
  1446. description='Used by the Anaglyph Arc Rotate camera',
  1447. default = 1
  1448. )
  1449. #===============================================================================
  1450. bpy.types.Lamp.autoAnimate = bpy.props.BoolProperty(
  1451. name='Automatically launch animations',
  1452. description='',
  1453. default = False
  1454. )
  1455. bpy.types.Lamp.shadowMap = bpy.props.EnumProperty(
  1456. name='Shadow Map Type',
  1457. description='',
  1458. items = (('NONE', 'None', 'No Shadow Maps'), ('STD', 'Standard', 'Use Standard Shadow Maps'), ('VAR', 'Variance', 'Use Variance Shadow Maps')),
  1459. default = 'NONE'
  1460. )
  1461. bpy.types.Lamp.shadowMapSize = bpy.props.IntProperty(
  1462. name='Shadow Map Size',
  1463. description='',
  1464. default = 512
  1465. )
  1466. class ObjectPanel(bpy.types.Panel):
  1467. bl_label = 'Babylon.js'
  1468. bl_space_type = 'PROPERTIES'
  1469. bl_region_type = 'WINDOW'
  1470. bl_context = 'data'
  1471. def draw(self, context):
  1472. ob = context.object
  1473. if not ob or not ob.data:
  1474. return
  1475. layout = self.layout
  1476. isMesh = isinstance(ob.data, bpy.types.Mesh)
  1477. isCamera = isinstance(ob.data, bpy.types.Camera)
  1478. isLight = isinstance(ob.data, bpy.types.Lamp)
  1479. if isMesh:
  1480. layout.prop(ob.data, 'useFlatShading')
  1481. layout.prop(ob.data, 'checkCollisions')
  1482. layout.prop(ob.data, 'castShadows')
  1483. layout.prop(ob.data, 'receiveShadows')
  1484. layout.separator()
  1485. layout.prop(ob.data, 'autoAnimate')
  1486. elif isCamera:
  1487. layout.prop(ob.data, 'CameraType')
  1488. layout.prop(ob.data, 'checkCollisions')
  1489. layout.prop(ob.data, 'applyGravity')
  1490. layout.prop(ob.data, 'ellipsoid')
  1491. layout.separator()
  1492. layout.prop(ob.data, 'anaglyphEyeSpace')
  1493. layout.separator()
  1494. layout.prop(ob.data, 'autoAnimate')
  1495. elif isLight:
  1496. layout.prop(ob.data, 'shadowMap')
  1497. layout.prop(ob.data, 'shadowMapSize')
  1498. layout.separator()
  1499. layout.prop(ob.data, 'autoAnimate')