io_export_babylon.py 81 KB

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