io_export_babylon.py 78 KB

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