io_export_babylon.py 77 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738
  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.isEnabled = True
  756. self.checkCollisions = False
  757. self.billboardMode = BILLBOARDMODE_NONE
  758. self.receiveShadows = False
  759. # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  760. def get_proper_name(self):
  761. return legal_js_identifier(self.name)
  762. # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  763. def to_scene_file(self, file_handler, ignored):
  764. file_handler.write('{')
  765. write_string(file_handler, 'name', self.name, True)
  766. write_string(file_handler, 'id', self.name)
  767. if hasattr(self, 'parentId'): write_string(file_handler, 'parentId', self.parentId)
  768. write_vector(file_handler, 'position', self.position)
  769. write_vector(file_handler, 'rotation', self.rotation)
  770. write_vector(file_handler, 'scaling', self.scaling)
  771. write_bool(file_handler, 'isVisible', self.isVisible)
  772. write_bool(file_handler, 'isEnabled', self.isEnabled)
  773. write_bool(file_handler, 'checkCollisions', self.checkCollisions)
  774. write_int(file_handler, 'billboardMode', self.billboardMode)
  775. write_bool(file_handler, 'receiveShadows', self.receiveShadows)
  776. file_handler.write('}')
  777. #===============================================================================
  778. class SubMesh:
  779. def __init__(self, materialIndex, verticesStart, indexStart, verticesCount, indexCount):
  780. self.materialIndex = materialIndex
  781. self.verticesStart = verticesStart
  782. self.indexStart = indexStart
  783. self.verticesCount = verticesCount
  784. self.indexCount = indexCount
  785. # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  786. def to_scene_file(self, file_handler):
  787. file_handler.write('{')
  788. write_int(file_handler, 'materialIndex', self.materialIndex, True)
  789. write_int(file_handler, 'verticesStart', self.verticesStart)
  790. write_int(file_handler, 'verticesCount', self.verticesCount)
  791. write_int(file_handler, 'indexStart' , self.indexStart)
  792. write_int(file_handler, 'indexCount' , self.indexCount)
  793. file_handler.write('}')
  794. #===============================================================================
  795. class Bone:
  796. def __init__(self, bone, skeleton, scene, index):
  797. BabylonExporter.log('processing begun of bone: ' + bone.name + ', index: '+ str(index))
  798. self.name = bone.name
  799. self.index = index
  800. matrix_world = skeleton.matrix_world
  801. self.matrix = Bone.get_matrix(bone, matrix_world)
  802. parentId = -1
  803. if (bone.parent):
  804. for parent in skeleton.pose.bones:
  805. parentId += 1
  806. if parent == bone.parent:
  807. break;
  808. self.parentBoneIndex = parentId
  809. #animation
  810. if (skeleton.animation_data):
  811. BabylonExporter.log('animation begun of bone: ' + self.name)
  812. self.animation = Animation(ANIMATIONTYPE_MATRIX, scene.render.fps, ANIMATIONLOOPMODE_CYCLE, 'anim', '_matrix')
  813. start_frame = scene.frame_start
  814. end_frame = scene.frame_end
  815. previousBoneMatrix = None
  816. for frame in range(start_frame, end_frame + 1):
  817. bpy.context.scene.frame_set(frame)
  818. currentBoneMatrix = Bone.get_matrix(bone, skeleton.matrix_world)
  819. if (frame != end_frame and currentBoneMatrix == previousBoneMatrix):
  820. continue
  821. self.animation.frames.append(frame)
  822. self.animation.values.append(Bone.get_matrix(bone, matrix_world))
  823. previousBoneMatrix = currentBoneMatrix
  824. bpy.context.scene.frame_set(start_frame)
  825. # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  826. @staticmethod
  827. def get_matrix(bone, matrix_world):
  828. SystemMatrix = mathutils.Matrix.Scale(-1, 4, mathutils.Vector((0, 0, 1))) * mathutils.Matrix.Rotation(math.radians(-90), 4, 'X')
  829. if (bone.parent):
  830. return (SystemMatrix * matrix_world * bone.parent.matrix).inverted() * (SystemMatrix * matrix_world * bone.matrix)
  831. else:
  832. return SystemMatrix * matrix_world * bone.matrix
  833. # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  834. def to_scene_file(self, file_handler):
  835. file_handler.write('\n{')
  836. write_string(file_handler, 'name', self.name, True)
  837. write_int(file_handler, 'index', self.index)
  838. write_matrix4(file_handler, 'matrix', self.matrix)
  839. write_int(file_handler, 'parentBoneIndex', self.parentBoneIndex)
  840. #animation
  841. if hasattr(self, 'animation'):
  842. file_handler.write(',"animation":')
  843. self.animation.to_scene_file(file_handler)
  844. file_handler.write('}')
  845. #===============================================================================
  846. class Skeleton:
  847. def __init__(self, skeleton, scene, id):
  848. BabylonExporter.log('processing begun of skeleton: ' + skeleton.name + ', id: '+ str(id))
  849. self.name = skeleton.name
  850. self.id = id
  851. self.bones = []
  852. bones = skeleton.pose.bones
  853. j = 0
  854. for bone in bones:
  855. self.bones.append(Bone(bone, skeleton, scene, j))
  856. j = j + 1
  857. BabylonExporter.log('processing complete of skeleton: ' + skeleton.name)
  858. # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  859. def to_scene_file(self, file_handler):
  860. file_handler.write('{')
  861. write_string(file_handler, 'name', self.name, True)
  862. write_int(file_handler, 'id', self.id) # keep int for legacy of original exporter
  863. file_handler.write(',"bones":[')
  864. first = True
  865. for bone in self.bones:
  866. if first != True:
  867. file_handler.write(',')
  868. first = False
  869. bone.to_scene_file(file_handler)
  870. file_handler.write(']')
  871. file_handler.write('}')
  872. #===============================================================================
  873. class Camera(FCurveAnimatable):
  874. def __init__(self, camera):
  875. super().__init__(camera, True, True, False, math.pi / 2)
  876. self.CameraType = camera.data.CameraType
  877. self.name = camera.name
  878. BabylonExporter.log('processing begun of camera (' + self.CameraType + '): ' + self.name)
  879. self.position = camera.location
  880. self.rotation = mathutils.Vector((-camera.rotation_euler[0] + math.pi / 2, camera.rotation_euler[1], -camera.rotation_euler[2])) # extra parens needed
  881. self.fov = camera.data.angle
  882. self.minZ = camera.data.clip_start
  883. self.maxZ = camera.data.clip_end
  884. self.speed = 1.0
  885. self.inertia = 0.9
  886. self.checkCollisions = camera.data.checkCollisions
  887. self.applyGravity = camera.data.applyGravity
  888. self.ellipsoid = camera.data.ellipsoid
  889. for constraint in camera.constraints:
  890. if constraint.type == 'TRACK_TO':
  891. self.lockedTargetId = constraint.target.name
  892. break
  893. if self.CameraType == ANAGLYPH_ARC_CAM or self.CameraType == ANAGLYPH_FREE_CAM:
  894. self.anaglyphEyeSpace = camera.data.anaglyphEyeSpace
  895. if self.CameraType == ANAGLYPH_ARC_CAM or self.CameraType == ARC_ROTATE_CAM or self.CameraType == FOLLOW_CAM:
  896. if not hasattr(self, 'lockedTargetId'):
  897. BabylonExporter.warn('ERROR: Camera type with manditory target specified, but no target to track set', 2)
  898. self.fatalProblem = True
  899. # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  900. def update_for_target_attributes(self, meshesAndNodes):
  901. if not hasattr(self, 'lockedTargetId'): return
  902. # find the actual mesh tracking, so properties can be derrived
  903. targetFound = False
  904. for mesh in meshesAndNodes:
  905. if mesh.name == self.lockedTargetId:
  906. targetMesh = mesh
  907. targetFound = True
  908. break;
  909. xApart = 3 if not targetFound else self.position.x - targetMesh.position.x
  910. yApart = 3 if not targetFound else self.position.y - targetMesh.position.y
  911. zApart = 3 if not targetFound else self.position.z - targetMesh.position.z
  912. distance3D = math.sqrt(xApart * xApart + yApart * yApart + zApart * zApart)
  913. alpha = math.atan2(yApart, xApart);
  914. beta = math.atan2(yApart, zApart);
  915. if self.CameraType == FOLLOW_CAM:
  916. self.followHeight = zApart
  917. self.followDistance = distance3D
  918. self.followRotation = 90 + (alpha * 180 / math.pi)
  919. elif self.CameraType == ANAGLYPH_ARC_CAM or self.CameraType == ARC_ROTATE_CAM:
  920. self.arcRotAlpha = alpha
  921. self.arcRotBeta = beta
  922. self.arcRotRadius = distance3D
  923. # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  924. def to_scene_file(self, file_handler):
  925. file_handler.write('{')
  926. write_string(file_handler, 'name', self.name, True)
  927. write_string(file_handler, 'id', self.name)
  928. write_vector(file_handler, 'position', self.position)
  929. write_vector(file_handler, 'rotation', self.rotation)
  930. write_float(file_handler, 'fov', self.fov)
  931. write_float(file_handler, 'minZ', self.minZ)
  932. write_float(file_handler, 'maxZ', self.maxZ)
  933. write_float(file_handler, 'speed', self.speed)
  934. write_float(file_handler, 'inertia', self.inertia)
  935. write_bool(file_handler, 'checkCollisions', self.checkCollisions)
  936. write_bool(file_handler, 'applyGravity', self.applyGravity)
  937. write_array3(file_handler, 'ellipsoid', self.ellipsoid)
  938. write_string(file_handler, 'type', self.CameraType)
  939. if self.CameraType == FOLLOW_CAM:
  940. write_float(file_handler, 'heightOffset', self.followHeight)
  941. write_float(file_handler, 'radius', self.followDistance)
  942. write_float(file_handler, 'rotationOffset', self.followRotation)
  943. elif self.CameraType == ANAGLYPH_ARC_CAM or self.CameraType == ARC_ROTATE_CAM:
  944. write_float(file_handler, 'alpha', self.arcRotAlpha)
  945. write_float(file_handler, 'beta', self.arcRotBeta)
  946. write_float(file_handler, 'radius', self.arcRotRadius)
  947. if self.CameraType == ANAGLYPH_ARC_CAM:
  948. write_float(file_handler, 'eye_space', self.anaglyphEyeSpace)
  949. elif self.CameraType == ANAGLYPH_FREE_CAM:
  950. write_float(file_handler, 'eye_space', self.anaglyphEyeSpace)
  951. if hasattr(self, 'lockedTargetId'):
  952. write_string(file_handler, 'lockedTargetId', self.lockedTargetId)
  953. super().to_scene_file(file_handler) # Animations
  954. file_handler.write('}')
  955. #===============================================================================
  956. class Light(FCurveAnimatable):
  957. def __init__(self, light):
  958. super().__init__(light, False, True, False)
  959. self.name = light.name
  960. BabylonExporter.log('processing begun of light (' + light.data.type + '): ' + self.name)
  961. light_type_items = {'POINT': POINT_LIGHT, 'SUN': DIRECTIONAL_LIGHT, 'SPOT': SPOT_LIGHT, 'HEMI': HEMI_LIGHT, 'AREA': 0}
  962. self.light_type = light_type_items[light.data.type]
  963. if self.light_type == POINT_LIGHT:
  964. self.position = light.location
  965. if light.data.use_sphere:
  966. self.range = light.data.distance
  967. elif self.light_type == DIRECTIONAL_LIGHT:
  968. self.position = light.location
  969. self.direction = Light.get_direction(light.matrix_world)
  970. elif self.light_type == SPOT_LIGHT:
  971. self.position = light.location
  972. self.direction = Light.get_direction(light.matrix_world)
  973. self.angle = light.data.spot_size
  974. self.exponent = light.data.spot_blend * 2
  975. if light.data.use_sphere:
  976. self.range = light.data.distance
  977. else:
  978. # Hemi & Area
  979. matrix_world = light.matrix_world.copy()
  980. matrix_world.translation = mathutils.Vector((0, 0, 0))
  981. self.direction = (mathutils.Vector((0, 0, -1)) * matrix_world)
  982. self.groundColor = mathutils.Color((0, 0, 0))
  983. self.intensity = light.data.energy
  984. self.diffuse = light.data.color if light.data.use_diffuse else mathutils.Color((0, 0, 0))
  985. self.specular = light.data.color if light.data.use_specular else mathutils.Color((0, 0, 0))
  986. # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  987. def to_scene_file(self, file_handler):
  988. file_handler.write('{')
  989. write_string(file_handler, 'name', self.name, True)
  990. write_string(file_handler, 'id', self.name)
  991. write_float(file_handler, 'type', self.light_type)
  992. if hasattr(self, 'position' ): write_vector(file_handler, 'position' , self.position )
  993. if hasattr(self, 'direction' ): write_vector(file_handler, 'direction' , self.direction )
  994. if hasattr(self, 'angle' ): write_float (file_handler, 'angle' , self.angle )
  995. if hasattr(self, 'exponent' ): write_float (file_handler, 'exponent' , self.exponent )
  996. if hasattr(self, 'groundColor'): write_color (file_handler, 'groundColor', self.groundColor)
  997. if hasattr(self, 'range' ): write_float (file_handler, 'range' , self.range )
  998. write_float(file_handler, 'intensity', self.intensity)
  999. write_color(file_handler, 'diffuse', self.diffuse)
  1000. write_color(file_handler, 'specular', self.specular)
  1001. super().to_scene_file(file_handler) # Animations
  1002. file_handler.write('}')
  1003. @staticmethod
  1004. def get_direction(matrix):
  1005. return (matrix.to_3x3() * mathutils.Vector((0.0, 0.0, -1.0))).normalized()
  1006. #===============================================================================
  1007. class ShadowGenerator:
  1008. def __init__(self, lamp, meshesAndNodes, scene):
  1009. BabylonExporter.log('processing begun of shadows for light: ' + lamp.name)
  1010. self.useVarianceShadowMap = lamp.data.shadowMap == 'VAR' if True else False
  1011. self.mapSize = lamp.data.shadowMapSize
  1012. self.lightId = lamp.name
  1013. self.shadowCasters = []
  1014. for mesh in meshesAndNodes:
  1015. if (mesh.castShadows):
  1016. self.shadowCasters.append(mesh.name)
  1017. # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  1018. def to_scene_file(self, file_handler):
  1019. file_handler.write('{')
  1020. write_bool(file_handler, 'useVarianceShadowMap', self.useVarianceShadowMap, True)
  1021. write_int(file_handler, 'mapSize', self.mapSize)
  1022. write_string(file_handler, 'lightId', self.lightId)
  1023. file_handler.write(',"renderList":[')
  1024. first = True
  1025. for caster in self.shadowCasters:
  1026. if first != True:
  1027. file_handler.write(',')
  1028. first = False
  1029. file_handler.write('"' + caster + '"')
  1030. file_handler.write(']')
  1031. file_handler.write('}')
  1032. #===============================================================================
  1033. class MultiMaterial:
  1034. def __init__(self, material_slots, idx):
  1035. self.name = BabylonExporter.nameSpace + '.' + 'Multimaterial#' + str(idx)
  1036. BabylonExporter.log('processing begun of multimaterial: ' + self.name, 2)
  1037. self.materials = []
  1038. for mat in material_slots:
  1039. self.materials.append(BabylonExporter.nameSpace + '.' + mat.name)
  1040. # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  1041. def to_scene_file(self, file_handler):
  1042. file_handler.write('{')
  1043. write_string(file_handler, 'name', self.name, True)
  1044. write_string(file_handler, 'id', self.name)
  1045. file_handler.write(',"materials":[')
  1046. first = True
  1047. for materialName in self.materials:
  1048. if first != True:
  1049. file_handler.write(',')
  1050. file_handler.write('"' + materialName +'"')
  1051. first = False
  1052. file_handler.write(']')
  1053. file_handler.write('}')
  1054. #===============================================================================
  1055. class Texture:
  1056. def __init__(self, slot, level, texture, filepath):
  1057. # Copy image to output
  1058. try:
  1059. image = texture.texture.image
  1060. imageFilepath = os.path.normpath(bpy.path.abspath(image.filepath))
  1061. basename = os.path.basename(imageFilepath)
  1062. targetdir = os.path.dirname(filepath)
  1063. targetpath = os.path.join(targetdir, basename)
  1064. if image.packed_file:
  1065. image.save_render(targetpath)
  1066. else:
  1067. sourcepath = bpy.path.abspath(image.filepath)
  1068. shutil.copy(sourcepath, targetdir)
  1069. except:
  1070. ex = sys.exc_info()
  1071. BabylonExporter.log_handler.write('Error encountered processing image file: ' + imageFilepath + ', Error: '+ str(ex[1]) + '\n')
  1072. #pass
  1073. # Export
  1074. self.slot = slot
  1075. self.name = basename
  1076. self.level = level
  1077. self.hasAlpha = texture.texture.use_alpha
  1078. if (texture.mapping == 'CUBE'):
  1079. self.coordinatesMode = CUBIC_MODE
  1080. if (texture.mapping == 'SPHERE'):
  1081. self.coordinatesMode = SPHERICAL_MODE
  1082. else:
  1083. self.coordinatesMode = EXPLICIT_MODE
  1084. self.uOffset = texture.offset.x
  1085. self.vOffset = texture.offset.y
  1086. self.uScale = texture.scale.x
  1087. self.vScale = texture.scale.y
  1088. self.uAng = 0
  1089. self.vAng = 0
  1090. self.wAng = 0
  1091. if (texture.texture.extension == 'REPEAT'):
  1092. if (texture.texture.use_mirror_x):
  1093. self.wrapU = MIRROR_ADDRESSMODE
  1094. else:
  1095. self.wrapU = WRAP_ADDRESSMODE
  1096. if (texture.texture.use_mirror_y):
  1097. self.wrapV = MIRROR_ADDRESSMODE
  1098. else:
  1099. self.wrapV = WRAP_ADDRESSMODE
  1100. else:
  1101. self.wrapU = CLAMP_ADDRESSMODE
  1102. self.wrapV = CLAMP_ADDRESSMODE
  1103. self.coordinatesIndex = 0
  1104. # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  1105. def to_scene_file(self, file_handler):
  1106. file_handler.write(', "' + self.slot + '":{')
  1107. write_string(file_handler, 'name', self.name, True)
  1108. write_float(file_handler, 'level', self.level)
  1109. write_float(file_handler, 'hasAlpha', self.hasAlpha)
  1110. write_int(file_handler, 'coordinatesMode', self.coordinatesMode)
  1111. write_float(file_handler, 'uOffset', self.uOffset)
  1112. write_float(file_handler, 'vOffset', self.vOffset)
  1113. write_float(file_handler, 'uScale', self.uScale)
  1114. write_float(file_handler, 'vScale', self.vScale)
  1115. write_float(file_handler, 'uAng', self.uAng)
  1116. write_float(file_handler, 'vAng', self.vAng)
  1117. write_float(file_handler, 'wAng', self.wAng)
  1118. write_int(file_handler, 'wrapU', self.wrapU)
  1119. write_int(file_handler, 'wrapV', self.wrapV)
  1120. write_int(file_handler, 'coordinatesIndex', self.coordinatesIndex)
  1121. file_handler.write('}')
  1122. #===============================================================================
  1123. class Material:
  1124. def __init__(self, material, scene, filepath):
  1125. self.name = BabylonExporter.nameSpace + '.' + material.name
  1126. BabylonExporter.log('processing begun of material: ' + self.name)
  1127. self.ambient = material.ambient * material.diffuse_color
  1128. self.diffuse = material.diffuse_intensity * material.diffuse_color
  1129. self.specular = material.specular_intensity * material.specular_color
  1130. self.emissive = material.emit * material.diffuse_color
  1131. self.specularPower = material.specular_hardness
  1132. self.alpha = material.alpha
  1133. self.backFaceCulling = material.game_settings.use_backface_culling
  1134. # Textures
  1135. self.textures = []
  1136. textures = [mtex for mtex in material.texture_slots if mtex and mtex.texture]
  1137. for mtex in textures:
  1138. if mtex.texture.type == 'IMAGE':
  1139. if mtex.texture.image:
  1140. if (mtex.use_map_color_diffuse and (mtex.texture_coords != 'REFLECTION')):
  1141. # Diffuse
  1142. BabylonExporter.log('Diffuse texture found');
  1143. self.textures.append(Texture('diffuseTexture', mtex.diffuse_color_factor, mtex, filepath))
  1144. if mtex.use_map_ambient:
  1145. # Ambient
  1146. BabylonExporter.log('Ambient texture found');
  1147. self.textures.append(Texture('ambientTexture', mtex.ambient_factor, mtex, filepath))
  1148. if mtex.use_map_alpha:
  1149. # Opacity
  1150. BabylonExporter.log('Opacity texture found');
  1151. self.textures.append(Texture('opacityTexture', mtex.alpha_factor, mtex, filepath))
  1152. if mtex.use_map_color_diffuse and (mtex.texture_coords == 'REFLECTION'):
  1153. # Reflection
  1154. BabylonExporter.log('Reflection texture found');
  1155. self.textures.append(Texture('reflectionTexture', mtex.diffuse_color_factor, mtex, filepath))
  1156. if mtex.use_map_emit:
  1157. # Emissive
  1158. BabylonExporter.log('Emissive texture found');
  1159. self.textures.append(Texture('emissiveTexture', mtex.emit_factor, mtex, filepath))
  1160. if mtex.use_map_normal:
  1161. # Bump
  1162. BabylonExporter.log('Bump texture found');
  1163. self.textures.append(Texture('bumpTexture', mtex.normal_factor, mtex, filepath))
  1164. else:
  1165. BabylonExporter.warn('WARNING texture type not currently supported: ' + mtex.texture.type + ', ignored.')
  1166. # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  1167. def to_scene_file(self, file_handler):
  1168. file_handler.write('{')
  1169. write_string(file_handler, 'name', self.name, True)
  1170. write_string(file_handler, 'id', self.name)
  1171. write_color(file_handler, 'ambient', self.ambient)
  1172. write_color(file_handler, 'diffuse', self.diffuse)
  1173. write_color(file_handler, 'specular', self.specular)
  1174. write_color(file_handler, 'emissive', self.emissive)
  1175. write_float(file_handler, 'specularPower', self.specularPower)
  1176. write_float(file_handler, 'alpha', self.alpha)
  1177. write_bool(file_handler, 'backFaceCulling', self.backFaceCulling)
  1178. for texSlot in self.textures:
  1179. texSlot.to_scene_file(file_handler)
  1180. file_handler.write('}')
  1181. #===============================================================================
  1182. class Animation:
  1183. def __init__(self, dataType, framePerSecond, loopBehavior, name, propertyInBabylon):
  1184. self.dataType = dataType
  1185. self.framePerSecond = framePerSecond
  1186. self.loopBehavior = loopBehavior
  1187. self.name = name
  1188. self.propertyInBabylon = propertyInBabylon
  1189. #keys
  1190. self.frames = []
  1191. self.values = [] # vector3 for ANIMATIONTYPE_VECTOR3 & matrices for ANIMATIONTYPE_MATRIX
  1192. # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  1193. # for auto animate
  1194. def get_first_frame(self):
  1195. return self.frames[0] if len(self.frames) > 0 else -1
  1196. # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  1197. # for auto animate
  1198. def get_last_frame(self):
  1199. return self.frames[len(self.frames) - 1] if len(self.frames) > 0 else -1
  1200. # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  1201. def to_scene_file(self, file_handler):
  1202. file_handler.write('{')
  1203. write_int(file_handler, 'dataType', self.dataType, True)
  1204. write_int(file_handler, 'framePerSecond', self.framePerSecond)
  1205. file_handler.write(',"keys":[')
  1206. first = True
  1207. for frame_idx in range(len(self.frames)):
  1208. if first != True:
  1209. file_handler.write(',')
  1210. first = False
  1211. file_handler.write('{')
  1212. write_int(file_handler, 'frame', self.frames[frame_idx], True)
  1213. if self.dataType == ANIMATIONTYPE_MATRIX:
  1214. write_matrix4(file_handler, 'values', self.values[frame_idx])
  1215. else:
  1216. write_vector(file_handler, 'values', self.values[frame_idx])
  1217. file_handler.write('}')
  1218. file_handler.write(']') # close keys
  1219. # put this at the end to make less crazy looking ]}]]]}}}}}}}]]]],
  1220. # since animation is also at the end of the bone, mesh, camera, or light
  1221. write_int(file_handler, 'loopBehavior', self.loopBehavior)
  1222. write_string(file_handler, 'name', self.name)
  1223. write_string(file_handler, 'property', self.propertyInBabylon)
  1224. file_handler.write('}')
  1225. #===============================================================================
  1226. class VectorAnimation(Animation):
  1227. def __init__(self, object, attrInBlender, propertyInBabylon, mult, xOffset = 0):
  1228. super().__init__(ANIMATIONTYPE_VECTOR3, 30, ANIMATIONLOOPMODE_CYCLE, propertyInBabylon + ' animation', propertyInBabylon)
  1229. # capture built up from fcurves
  1230. frames = dict()
  1231. for fcurve in object.animation_data.action.fcurves:
  1232. if fcurve.data_path == attrInBlender:
  1233. for key in fcurve.keyframe_points:
  1234. frame = key.co.x
  1235. frames[frame] = 1
  1236. #for each frame (next step ==> set for key frames)
  1237. for Frame in sorted(frames):
  1238. self.frames.append(Frame)
  1239. bpy.context.scene.frame_set(int(Frame + bpy.context.scene.frame_start))
  1240. self.values.append(scale_vector(getattr(object, attrInBlender), mult, xOffset))
  1241. #===============================================================================
  1242. # module level formatting methods, called from multiple classes
  1243. #===============================================================================
  1244. def legal_js_identifier(input):
  1245. out = ''
  1246. prefix = ''
  1247. for char in input:
  1248. if len(out) == 0:
  1249. if char in '0123456789':
  1250. # cannot take the chance that leading numbers being chopped of cause name conflicts, e.g (01.R & 02.R)
  1251. prefix += char
  1252. continue
  1253. elif char.upper() not in 'ABCDEFGHIJKLMNOPQRSTUVWXYZ':
  1254. continue
  1255. legal = char if char.upper() in 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_' else '_'
  1256. out += legal
  1257. if len(prefix) > 0:
  1258. out += '_' + prefix
  1259. return out
  1260. def format_f(num):
  1261. s = MAX_FLOAT_PRECISION % num # rounds to N decimal places while changing to string
  1262. s = s.rstrip('0') # ignore trailing zeroes
  1263. s = s.rstrip('.') # ignore trailing .
  1264. return '0' if s == '-0' else s
  1265. def format_matrix4(matrix):
  1266. tempMatrix = matrix.copy()
  1267. tempMatrix.transpose()
  1268. ret = ''
  1269. first = True
  1270. for vect in tempMatrix:
  1271. if (first != True):
  1272. ret +=','
  1273. first = False;
  1274. ret += format_f(vect[0]) + ',' + format_f(vect[1]) + ',' + format_f(vect[2]) + ',' + format_f(vect[3])
  1275. return ret
  1276. def format_array3(array):
  1277. return format_f(array[0]) + ',' + format_f(array[1]) + ',' + format_f(array[2])
  1278. def format_array(array, max_per_line = MAX_VERTEX_ELEMENTS, indent = ''):
  1279. ret = ''
  1280. first = True
  1281. nOnLine = 0
  1282. for element in array:
  1283. if (first != True):
  1284. ret +=','
  1285. first = False;
  1286. ret += format_f(element)
  1287. nOnLine += 1
  1288. if nOnLine >= max_per_line:
  1289. ret += '\n' + indent
  1290. nOnLine = 0
  1291. return ret
  1292. def format_color(color):
  1293. return format_f(color.r) + ',' + format_f(color.g) + ',' + format_f(color.b)
  1294. def format_vector(vector):
  1295. return format_f(vector.x) + ',' + format_f(vector.z) + ',' + format_f(vector.y)
  1296. def format_vector_array(vectorArray, max_per_line = MAX_VERTEX_ELEMENTS, indent = ''):
  1297. ret = ''
  1298. first = True
  1299. nOnLine = 0
  1300. for vector in vectorArray:
  1301. if (first != True):
  1302. ret +=','
  1303. first = False;
  1304. ret += format_vector(vector)
  1305. nOnLine += 3
  1306. if nOnLine >= max_per_line:
  1307. ret += '\n' + indent
  1308. nOnLine = 0
  1309. return ret
  1310. def format_quaternion(quaternion):
  1311. return format_f(quaternion.x) + ',' + format_f(quaternion.z) + ',' + format_f(quaternion.y) + ',' + format_f(-quaternion.w)
  1312. def format_int(int):
  1313. candidate = str(int) # when int string of an int
  1314. if '.' in candidate:
  1315. return format_f(math.floor(int)) # format_f removes un-neccessary precision
  1316. else:
  1317. return candidate
  1318. def format_bool(bool):
  1319. if bool:
  1320. return 'true'
  1321. else:
  1322. return 'false'
  1323. def scale_vector(vector, mult, xOffset = 0):
  1324. ret = vector.copy()
  1325. ret.x *= mult
  1326. ret.x += xOffset
  1327. ret.z *= mult
  1328. ret.y *= mult
  1329. return ret
  1330. def same_vertex(vertA, vertB):
  1331. return vertA.x == vertB.x and vertA.y == vertB.y and vertA.z == vertB.z
  1332. #===============================================================================
  1333. # module level methods for writing JSON (.babylon) files
  1334. #===============================================================================
  1335. def write_matrix4(file_handler, name, matrix):
  1336. file_handler.write(',"' + name + '":[' + format_matrix4(matrix) + ']')
  1337. def write_array(file_handler, name, array):
  1338. file_handler.write('\n,"' + name + '":[' + format_array(array) + ']')
  1339. def write_array3(file_handler, name, array):
  1340. file_handler.write(',"' + name + '":[' + format_array3(array) + ']')
  1341. def write_color(file_handler, name, color):
  1342. file_handler.write(',"' + name + '":[' + format_color(color) + ']')
  1343. def write_vector(file_handler, name, vector):
  1344. file_handler.write(',"' + name + '":[' + format_vector(vector) + ']')
  1345. def write_vector_array(file_handler, name, vectorArray):
  1346. file_handler.write('\n,"' + name + '":[' + format_vector_array(vectorArray) + ']')
  1347. def write_quaternion(file_handler, name, quaternion):
  1348. file_handler.write(',"' + name +'":[' + format_quaternion(quaternion) + ']')
  1349. def write_string(file_handler, name, string, noComma = False):
  1350. if noComma == False:
  1351. file_handler.write(',')
  1352. file_handler.write('"' + name + '":"' + string + '"')
  1353. def write_float(file_handler, name, float):
  1354. file_handler.write(',"' + name + '":' + format_f(float))
  1355. def write_int(file_handler, name, int, noComma = False):
  1356. if noComma == False:
  1357. file_handler.write(',')
  1358. file_handler.write('"' + name + '":' + format_int(int))
  1359. def write_bool(file_handler, name, bool, noComma = False):
  1360. if noComma == False:
  1361. file_handler.write(',')
  1362. file_handler.write('"' + name + '":' + format_bool(bool))
  1363. #===============================================================================
  1364. # custom properties definition and display
  1365. #===============================================================================
  1366. bpy.types.Mesh.autoAnimate = bpy.props.BoolProperty(
  1367. name='Automatically launch animations',
  1368. description='',
  1369. default = False
  1370. )
  1371. bpy.types.Mesh.useFlatShading = bpy.props.BoolProperty(
  1372. name='Use Flat Shading',
  1373. description='',
  1374. default = False
  1375. )
  1376. bpy.types.Mesh.checkCollisions = bpy.props.BoolProperty(
  1377. name='Check Collisions',
  1378. description='Indicates mesh should be checked that it does not run into anything.',
  1379. default = False
  1380. )
  1381. bpy.types.Mesh.castShadows = bpy.props.BoolProperty(
  1382. name='Cast Shadows',
  1383. description='',
  1384. default = False
  1385. )
  1386. bpy.types.Mesh.receiveShadows = bpy.props.BoolProperty(
  1387. name='Receive Shadows',
  1388. description='',
  1389. default = False
  1390. )
  1391. #===============================================================================
  1392. bpy.types.Camera.autoAnimate = bpy.props.BoolProperty(
  1393. name='Automatically launch animations',
  1394. description='',
  1395. default = False
  1396. )
  1397. bpy.types.Camera.CameraType = bpy.props.EnumProperty(
  1398. name='Camera Type',
  1399. description='',
  1400. items = (
  1401. (V_JOYSTICKS_CAM , 'Virtual Joysticks' , 'Use Virtual Joysticks Camera'),
  1402. (TOUCH_CAM , 'Touch' , 'Use Touch Camera'),
  1403. (OCULUS_CAM , 'Oculus' , 'Use Oculus Camera'),
  1404. (GAMEPAD_CAM , 'Gamepad' , 'Use Gamepad Camera'),
  1405. (FREE_CAM , 'Free' , 'Use Free Camera'),
  1406. (FOLLOW_CAM , 'Follow' , 'Use Follow Camera'),
  1407. (DEV_ORIENT_CAM , 'Device Orientation' , 'Use Device Orientation Camera'),
  1408. (ARC_ROTATE_CAM , 'Arc Rotate' , 'Use Arc Rotate Camera'),
  1409. (ANAGLYPH_FREE_CAM, 'Anaglyph Free' , 'Use Anaglyph Free Camera'),
  1410. (ANAGLYPH_ARC_CAM , 'Anaglyph Arc Rotate', 'Use Anaglyph Arc Rotate Camera')
  1411. ),
  1412. default = FREE_CAM
  1413. )
  1414. bpy.types.Camera.checkCollisions = bpy.props.BoolProperty(
  1415. name='Check Collisions',
  1416. description='',
  1417. default = False
  1418. )
  1419. bpy.types.Camera.applyGravity = bpy.props.BoolProperty(
  1420. name='Apply Gravity',
  1421. description='',
  1422. default = False
  1423. )
  1424. bpy.types.Camera.ellipsoid = bpy.props.FloatVectorProperty(
  1425. name='Ellipsoid',
  1426. description='',
  1427. default = mathutils.Vector((0.2, 0.9, 0.2))
  1428. )
  1429. bpy.types.Camera.anaglyphEyeSpace = bpy.props.IntProperty(
  1430. name='Anaglyph Eye space',
  1431. description='Used by the Anaglyph Arc Rotate camera',
  1432. default = 1
  1433. )
  1434. #===============================================================================
  1435. bpy.types.Lamp.autoAnimate = bpy.props.BoolProperty(
  1436. name='Automatically launch animations',
  1437. description='',
  1438. default = False
  1439. )
  1440. bpy.types.Lamp.shadowMap = bpy.props.EnumProperty(
  1441. name='Shadow Map Type',
  1442. description='',
  1443. items = (('NONE', 'None', 'No Shadow Maps'), ('STD', 'Standard', 'Use Standard Shadow Maps'), ('VAR', 'Variance', 'Use Variance Shadow Maps')),
  1444. default = 'NONE'
  1445. )
  1446. bpy.types.Lamp.shadowMapSize = bpy.props.IntProperty(
  1447. name='Shadow Map Size',
  1448. description='',
  1449. default = 512
  1450. )
  1451. class ObjectPanel(bpy.types.Panel):
  1452. bl_label = 'Babylon.js'
  1453. bl_space_type = 'PROPERTIES'
  1454. bl_region_type = 'WINDOW'
  1455. bl_context = 'data'
  1456. def draw(self, context):
  1457. ob = context.object
  1458. if not ob or not ob.data:
  1459. return
  1460. layout = self.layout
  1461. isMesh = isinstance(ob.data, bpy.types.Mesh)
  1462. isCamera = isinstance(ob.data, bpy.types.Camera)
  1463. isLight = isinstance(ob.data, bpy.types.Lamp)
  1464. if isMesh:
  1465. layout.prop(ob.data, 'useFlatShading')
  1466. layout.prop(ob.data, 'checkCollisions')
  1467. layout.prop(ob.data, 'castShadows')
  1468. layout.prop(ob.data, 'receiveShadows')
  1469. layout.separator()
  1470. layout.prop(ob.data, 'autoAnimate')
  1471. elif isCamera:
  1472. layout.prop(ob.data, 'CameraType')
  1473. layout.prop(ob.data, 'checkCollisions')
  1474. layout.prop(ob.data, 'applyGravity')
  1475. layout.prop(ob.data, 'ellipsoid')
  1476. layout.separator()
  1477. layout.prop(ob.data, 'anaglyphEyeSpace')
  1478. layout.separator()
  1479. layout.prop(ob.data, 'autoAnimate')
  1480. elif isLight:
  1481. layout.prop(ob.data, 'shadowMap')
  1482. layout.prop(ob.data, 'shadowMapSize')
  1483. layout.separator()
  1484. layout.prop(ob.data, 'autoAnimate')