io_export_babylon.py 77 KB

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