io_export_babylon.py 76 KB

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