io_export_babylon.py 76 KB

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