io_export_babylon.py 102 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417
  1. bl_info = {
  2. 'name': 'Babylon.js',
  3. 'author': 'David Catuhe, Jeff Palmer',
  4. 'version': (3, 0, 4),
  5. 'blender': (2, 75, 0),
  6. 'location': 'File > Export > Babylon.js (.babylon)',
  7. 'description': 'Export Babylon.js scenes (.babylon)',
  8. 'wiki_url': 'https://github.com/BabylonJS/Babylon.js/tree/master/Exporters/Blender',
  9. 'tracker_url': '',
  10. 'category': 'Import-Export'}
  11. import base64
  12. import bpy
  13. import bpy_extras.io_utils
  14. import time
  15. import io
  16. import math
  17. import mathutils
  18. import os
  19. import shutil
  20. import sys, traceback # for writing errors to log file
  21. #===============================================================================
  22. # Registration the calling of the INFO_MT_file_export file selector
  23. def menu_func(self, context):
  24. self.layout.operator(Main.bl_idname, text = 'Babylon.js [.babylon]')
  25. def register():
  26. bpy.utils.register_module(__name__)
  27. bpy.types.INFO_MT_file_export.append(menu_func)
  28. def unregister():
  29. bpy.utils.unregister_module(__name__)
  30. bpy.types.INFO_MT_file_export.remove(menu_func)
  31. if __name__ == '__main__':
  32. register()
  33. #===============================================================================
  34. # output related constants
  35. MAX_VERTEX_ELEMENTS = 65535
  36. MAX_VERTEX_ELEMENTS_32Bit = 16777216
  37. VERTEX_OUTPUT_PER_LINE = 1000
  38. MAX_FLOAT_PRECISION = '%.4f'
  39. MAX_INFLUENCERS_PER_VERTEX = 4
  40. # used in World constructor, defined in BABYLON.Scene
  41. #FOGMODE_NONE = 0
  42. #FOGMODE_EXP = 1
  43. #FOGMODE_EXP2 = 2
  44. FOGMODE_LINEAR = 3
  45. # used in Mesh & Node constructors, defined in BABYLON.AbstractMesh
  46. BILLBOARDMODE_NONE = 0
  47. #BILLBOARDMODE_X = 1
  48. #BILLBOARDMODE_Y = 2
  49. #BILLBOARDMODE_Z = 4
  50. BILLBOARDMODE_ALL = 7
  51. # used in Mesh constructor, defined in BABYLON.PhysicsEngine
  52. SPHERE_IMPOSTER = 1
  53. BOX_IMPOSTER = 2
  54. #PLANE_IMPOSTER = 3
  55. MESH_IMPOSTER = 4
  56. CAPSULE_IMPOSTER = 5
  57. CONE_IMPOSTER = 6
  58. CYLINDER_IMPOSTER = 7
  59. CONVEX_HULL_IMPOSTER = 8
  60. # camera class names, never formally defined in Babylon, but used in babylonFileLoader
  61. ARC_ROTATE_CAM = 'ArcRotateCamera'
  62. DEV_ORIENT_CAM = 'DeviceOrientationCamera'
  63. FOLLOW_CAM = 'FollowCamera'
  64. FREE_CAM = 'FreeCamera'
  65. GAMEPAD_CAM = 'GamepadCamera'
  66. TOUCH_CAM = 'TouchCamera'
  67. V_JOYSTICKS_CAM = 'VirtualJoysticksCamera'
  68. VR_DEV_ORIENT_FREE_CAM ='VRDeviceOrientationFreeCamera'
  69. WEB_VR_FREE_CAM = 'WebVRFreeCamera'
  70. # 3D camera rigs, defined in BABYLON.Camera, must be strings to be in 'dropdown'
  71. RIG_MODE_NONE = '0'
  72. RIG_MODE_STEREOSCOPIC_ANAGLYPH = '10'
  73. RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = '11'
  74. RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = '12'
  75. RIG_MODE_STEREOSCOPIC_OVERUNDER = '13'
  76. RIG_MODE_VR = '20'
  77. # used in Light constructor, never formally defined in Babylon, but used in babylonFileLoader
  78. POINT_LIGHT = 0
  79. DIRECTIONAL_LIGHT = 1
  80. SPOT_LIGHT = 2
  81. HEMI_LIGHT = 3
  82. #used in ShadowGenerators
  83. NO_SHADOWS = 'NONE'
  84. STD_SHADOWS = 'STD'
  85. POISSON_SHADOWS = 'POISSON'
  86. VARIANCE_SHADOWS = 'VARIANCE'
  87. BLUR_VARIANCE_SHADOWS = 'BLUR_VARIANCE'
  88. # used in Texture constructor, defined in BABYLON.Texture
  89. CLAMP_ADDRESSMODE = 0
  90. WRAP_ADDRESSMODE = 1
  91. MIRROR_ADDRESSMODE = 2
  92. # used in Texture constructor, defined in BABYLON.Texture
  93. EXPLICIT_MODE = 0
  94. SPHERICAL_MODE = 1
  95. #PLANAR_MODE = 2
  96. CUBIC_MODE = 3
  97. #PROJECTION_MODE = 4
  98. #SKYBOX_MODE = 5
  99. # passed to Animation constructor from animatable objects, defined in BABYLON.Animation
  100. #ANIMATIONTYPE_FLOAT = 0
  101. ANIMATIONTYPE_VECTOR3 = 1
  102. ANIMATIONTYPE_QUATERNION = 2
  103. ANIMATIONTYPE_MATRIX = 3
  104. #ANIMATIONTYPE_COLOR3 = 4
  105. # passed to Animation constructor from animatable objects, defined in BABYLON.Animation
  106. #ANIMATIONLOOPMODE_RELATIVE = 0
  107. ANIMATIONLOOPMODE_CYCLE = 1
  108. #ANIMATIONLOOPMODE_CONSTANT = 2
  109. #===============================================================================
  110. # Panel displayed in Scene Tab of properties, so settings can be saved in a .blend file
  111. class ExporterSettingsPanel(bpy.types.Panel):
  112. bl_label = 'Exporter Settings'
  113. bl_space_type = 'PROPERTIES'
  114. bl_region_type = 'WINDOW'
  115. bl_context = 'scene'
  116. bpy.types.Scene.export_onlySelectedLayer = bpy.props.BoolProperty(
  117. name="Export only selected layers",
  118. description="Export only selected layers",
  119. default = False,
  120. )
  121. bpy.types.Scene.export_noVertexOpt = bpy.props.BoolProperty(
  122. name="No vertex sharing",
  123. description="Turns off an optimization which reduces vertices",
  124. default = True,
  125. )
  126. bpy.types.Scene.attachedSound = bpy.props.StringProperty(
  127. name='Sound',
  128. description='',
  129. default = ''
  130. )
  131. bpy.types.Scene.loopSound = bpy.props.BoolProperty(
  132. name='Loop sound',
  133. description='',
  134. default = True
  135. )
  136. bpy.types.Scene.autoPlaySound = bpy.props.BoolProperty(
  137. name='Auto play sound',
  138. description='',
  139. default = True
  140. )
  141. bpy.types.Scene.inlineTextures = bpy.props.BoolProperty(
  142. name="inline textures",
  143. description="turn textures into encoded strings, for direct inclusion into source code",
  144. default = False,
  145. )
  146. def draw(self, context):
  147. layout = self.layout
  148. scene = context.scene
  149. layout.prop(scene, "export_onlySelectedLayer")
  150. layout.prop(scene, "export_noVertexOpt")
  151. layout.prop(scene, "inlineTextures")
  152. box = layout.box()
  153. box.prop(scene, 'attachedSound')
  154. box.prop(scene, 'autoPlaySound')
  155. box.prop(scene, 'loopSound')
  156. #===============================================================================
  157. class Main(bpy.types.Operator, bpy_extras.io_utils.ExportHelper):
  158. bl_idname = 'scene.babylon' # module will not load with out it, also must have a dot
  159. bl_label = 'Export Babylon.js scene' # used on the label of the actual 'save' button
  160. filename_ext = '.babylon' # required to have one, although not really used
  161. filepath = bpy.props.StringProperty(subtype = 'FILE_PATH') # assigned once the file selector returns
  162. log_handler = None # assigned in execute
  163. nameSpace = None # assigned in execute
  164. # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  165. nWarnings = 0
  166. @staticmethod
  167. def warn(msg, numTabIndent = 1, noNewLine = False):
  168. Main.log('WARNING: ' + msg, numTabIndent, noNewLine)
  169. Main.nWarnings += 1
  170. @staticmethod
  171. def log(msg, numTabIndent = 1, noNewLine = False):
  172. for i in range(numTabIndent):
  173. Main.log_handler.write('\t')
  174. Main.log_handler.write(msg)
  175. if not noNewLine: Main.log_handler.write('\n')
  176. # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  177. def getMaterial(self, baseMaterialId):
  178. fullName = Main.nameSpace + '.' + baseMaterialId
  179. for material in self.materials:
  180. if material.name == fullName:
  181. return material
  182. return None
  183. # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  184. def getSourceMeshInstance(self, dataName):
  185. for mesh in self.meshesAndNodes:
  186. # nodes have no 'dataName', cannot be instanced in any case
  187. if hasattr(mesh, 'dataName') and mesh.dataName == dataName:
  188. return mesh
  189. return None
  190. # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  191. def execute(self, context):
  192. scene = context.scene
  193. self.scene = scene # reference for passing
  194. try:
  195. start_time = time.time()
  196. filepathDotExtension = self.filepath.rpartition('.')
  197. self.filepathMinusExtension = filepathDotExtension[0]
  198. # assign nameSpace, based on OS
  199. if self.filepathMinusExtension.find('\\') != -1:
  200. Main.nameSpace = legal_js_identifier(self.filepathMinusExtension.rpartition('\\')[2])
  201. else:
  202. Main.nameSpace = legal_js_identifier(self.filepathMinusExtension.rpartition('/')[2])
  203. # explicitly reset globals, in case there was an earlier export this session
  204. Main.nWarnings = 0
  205. Main.log_handler = io.open(self.filepathMinusExtension + '.log', 'w', encoding='utf8')
  206. version = bl_info['version']
  207. Main.log('Exporter version: ' + str(version[0]) + '.' + str(version[1]) + '.' + str(version[2]) +
  208. ', Blender version: ' + bpy.app.version_string)
  209. if bpy.ops.object.mode_set.poll():
  210. bpy.ops.object.mode_set(mode = 'OBJECT')
  211. Main.log('========= Conversion from Blender to Babylon.js =========', 0)
  212. self.world = World(scene)
  213. bpy.ops.screen.animation_cancel()
  214. currentFrame = bpy.context.scene.frame_current
  215. bpy.context.scene.frame_set(0)
  216. # Active camera
  217. if scene.camera != None:
  218. self.activeCamera = scene.camera.name
  219. else:
  220. Main.warn('No active camera has been assigned, or is not in a currently selected Blender layer')
  221. self.cameras = []
  222. self.lights = []
  223. self.shadowGenerators = []
  224. self.skeletons = []
  225. skeletonId = 0
  226. self.meshesAndNodes = []
  227. self.materials = []
  228. self.multiMaterials = []
  229. self.sounds = []
  230. # Scene level sound
  231. if scene.attachedSound != '':
  232. self.sounds.append(Sound(scene.attachedSound, scene.autoPlaySound, scene.loopSound))
  233. # exclude lamps in this pass, so ShadowGenerator constructor can be passed meshesAnNodes
  234. for object in [object for object in scene.objects]:
  235. if object.type == 'CAMERA':
  236. if object.is_visible(scene): # no isInSelectedLayer() required, is_visible() handles this for them
  237. self.cameras.append(Camera(object))
  238. else:
  239. Main.warn('The following camera not visible in scene thus ignored: ' + object.name)
  240. elif object.type == 'ARMATURE': #skeleton.pose.bones
  241. if object.is_visible(scene):
  242. self.skeletons.append(Skeleton(object, scene, skeletonId))
  243. skeletonId += 1
  244. else:
  245. Main.warn('The following armature not visible in scene thus ignored: ' + object.name)
  246. elif object.type == 'MESH':
  247. forcedParent = None
  248. nameID = ''
  249. nextStartFace = 0
  250. while True and self.isInSelectedLayer(object, scene):
  251. mesh = Mesh(object, scene, nextStartFace, forcedParent, nameID, self)
  252. if hasattr(mesh, 'instances'):
  253. self.meshesAndNodes.append(mesh)
  254. else:
  255. break
  256. if object.data.attachedSound != '':
  257. self.sounds.append(Sound(object.data.attachedSound, object.data.autoPlaySound, object.data.loopSound, object))
  258. nextStartFace = mesh.offsetFace
  259. if nextStartFace == 0:
  260. break
  261. if forcedParent is None:
  262. nameID = 0
  263. forcedParent = object
  264. Main.warn('The following mesh has exceeded the maximum # of vertex elements & will be broken into multiple Babylon meshes: ' + object.name)
  265. nameID = nameID + 1
  266. elif object.type == 'EMPTY':
  267. self.meshesAndNodes.append(Node(object))
  268. elif object.type != 'LAMP':
  269. Main.warn('The following object (type - ' + object.type + ') is not currently exportable thus ignored: ' + object.name)
  270. # Lamp / shadow Generator pass; meshesAnNodes complete & forceParents included
  271. for object in [object for object in scene.objects]:
  272. if object.type == 'LAMP':
  273. if object.is_visible(scene): # no isInSelectedLayer() required, is_visible() handles this for them
  274. bulb = Light(object)
  275. self.lights.append(bulb)
  276. if object.data.shadowMap != 'NONE':
  277. if bulb.light_type == DIRECTIONAL_LIGHT or bulb.light_type == SPOT_LIGHT:
  278. self.shadowGenerators.append(ShadowGenerator(object, self.meshesAndNodes, scene))
  279. else:
  280. Main.warn('Only directional (sun) and spot types of lamp are valid for shadows thus ignored: ' + object.name)
  281. else:
  282. Main.warn('The following lamp not visible in scene thus ignored: ' + object.name)
  283. bpy.context.scene.frame_set(currentFrame)
  284. # output file
  285. self.to_scene_file ()
  286. except:# catch *all* exceptions
  287. ex = sys.exc_info()
  288. Main.log('========= An error was encountered =========', 0)
  289. stack = traceback.format_tb(ex[2])
  290. for line in stack:
  291. Main.log_handler.write(line) # avoid tabs & extra newlines by not calling log() inside catch
  292. Main.log_handler.write('ERROR: ' + str(ex[1]) + '\n')
  293. raise
  294. finally:
  295. Main.log('========= end of processing =========', 0)
  296. elapsed_time = time.time() - start_time
  297. minutes = math.floor(elapsed_time / 60)
  298. seconds = elapsed_time - (minutes * 60)
  299. Main.log('elapsed time: ' + str(minutes) + ' min, ' + format_f(seconds) + ' secs', 0)
  300. Main.log_handler.close()
  301. if (Main.nWarnings > 0):
  302. self.report({'WARNING'}, 'Processing completed, but ' + str(Main.nWarnings) + ' WARNINGS were raised, see log file.')
  303. return {'FINISHED'}
  304. # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  305. def to_scene_file(self):
  306. Main.log('========= Writing of scene file started =========', 0)
  307. # Open file
  308. file_handler = io.open(self.filepathMinusExtension + '.babylon', 'w', encoding='utf8')
  309. file_handler.write('{')
  310. self.world.to_scene_file(file_handler)
  311. # Materials
  312. file_handler.write(',\n"materials":[')
  313. first = True
  314. for material in self.materials:
  315. if first != True:
  316. file_handler.write(',\n')
  317. first = False
  318. material.to_scene_file(file_handler)
  319. file_handler.write(']')
  320. # Multi-materials
  321. file_handler.write(',\n"multiMaterials":[')
  322. first = True
  323. for multimaterial in self.multiMaterials:
  324. if first != True:
  325. file_handler.write(',')
  326. first = False
  327. multimaterial.to_scene_file(file_handler)
  328. file_handler.write(']')
  329. # Armatures/Bones
  330. file_handler.write(',\n"skeletons":[')
  331. first = True
  332. for skeleton in self.skeletons:
  333. if first != True:
  334. file_handler.write(',')
  335. first = False
  336. skeleton.to_scene_file(file_handler)
  337. file_handler.write(']')
  338. # Meshes
  339. file_handler.write(',\n"meshes":[')
  340. first = True
  341. for m in range(0, len(self.meshesAndNodes)):
  342. mesh = self.meshesAndNodes[m]
  343. if first != True:
  344. file_handler.write(',')
  345. first = False
  346. mesh.to_scene_file(file_handler)
  347. file_handler.write(']')
  348. # Cameras
  349. file_handler.write(',\n"cameras":[')
  350. first = True
  351. for camera in self.cameras:
  352. if hasattr(camera, 'fatalProblem'): continue
  353. if first != True:
  354. file_handler.write(',')
  355. first = False
  356. camera.update_for_target_attributes(self.meshesAndNodes)
  357. camera.to_scene_file(file_handler)
  358. file_handler.write(']')
  359. # Active camera
  360. if hasattr(self, 'activeCamera'):
  361. write_string(file_handler, 'activeCamera', self.activeCamera)
  362. # Lights
  363. file_handler.write(',\n"lights":[')
  364. first = True
  365. for light in self.lights:
  366. if first != True:
  367. file_handler.write(',')
  368. first = False
  369. light.to_scene_file(file_handler)
  370. file_handler.write(']')
  371. # Shadow generators
  372. file_handler.write(',\n"shadowGenerators":[')
  373. first = True
  374. for shadowGen in self.shadowGenerators:
  375. if first != True:
  376. file_handler.write(',')
  377. first = False
  378. shadowGen.to_scene_file(file_handler)
  379. file_handler.write(']')
  380. # Sounds
  381. if len(self.sounds) > 0:
  382. file_handler.write('\n,"sounds":[')
  383. first = True
  384. for sound in self.sounds:
  385. if first != True:
  386. file_handler.write(',')
  387. first = False
  388. sound.to_scene_file(file_handler)
  389. file_handler.write(']')
  390. # Closing
  391. file_handler.write('\n}')
  392. file_handler.close()
  393. Main.log('========= Writing of scene file completed =========', 0)
  394. # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  395. def isInSelectedLayer(self, obj, scene):
  396. if not scene.export_onlySelectedLayer:
  397. return True
  398. for l in range(0, len(scene.layers)):
  399. if obj.layers[l] and scene.layers[l]:
  400. return True
  401. return False
  402. #===============================================================================
  403. class World:
  404. def __init__(self, scene):
  405. self.autoClear = True
  406. world = scene.world
  407. if world:
  408. self.ambient_color = world.ambient_color
  409. self.clear_color = world.horizon_color
  410. else:
  411. self.ambient_color = mathutils.Color((0.2, 0.2, 0.3))
  412. self.clear_color = mathutils.Color((0.0, 0.0, 0.0))
  413. self.gravity = scene.gravity
  414. if world and world.mist_settings.use_mist:
  415. self.fogMode = FOGMODE_LINEAR
  416. self.fogColor = world.horizon_color
  417. self.fogStart = world.mist_settings.start
  418. self.fogEnd = world.mist_settings.depth
  419. self.fogDensity = 0.1
  420. Main.log('Python World class constructor completed')
  421. # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  422. def to_scene_file(self, file_handler):
  423. write_bool(file_handler, 'autoClear', self.autoClear, True)
  424. write_color(file_handler, 'clearColor', self.clear_color)
  425. write_color(file_handler, 'ambientColor', self.ambient_color)
  426. write_vector(file_handler, 'gravity', self.gravity)
  427. if hasattr(self, 'fogMode'):
  428. write_int(file_handler, 'fogMode', self.fogMode)
  429. write_color(file_handler, 'fogColor', self.fogColor)
  430. write_float(file_handler, 'fogStart', self.fogStart)
  431. write_float(file_handler, 'fogEnd', self.fogEnd)
  432. write_float(file_handler, 'fogDensity', self.fogDensity)
  433. #===============================================================================
  434. class Sound:
  435. def __init__(self, name, autoplay, loop, connectedMesh = None):
  436. self.name = name;
  437. self.autoplay = autoplay
  438. self.loop = loop
  439. if connectedMesh != None:
  440. self.connectedMeshId = connectedMesh.name
  441. self.maxDistance = connectedMesh.data.maxSoundDistance
  442. # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  443. def to_scene_file(self, file_handler):
  444. file_handler.write('{')
  445. write_string(file_handler, 'name', self.name, True)
  446. write_bool(file_handler, 'autoplay', self.autoplay)
  447. write_bool(file_handler, 'loop', self.loop)
  448. if hasattr(self, 'connectedMeshId'):
  449. write_string(file_handler, 'connectedMeshId', self.connectedMeshId)
  450. write_float(file_handler, 'maxDistance', self.maxDistance)
  451. file_handler.write('}')
  452. #===============================================================================
  453. class FCurveAnimatable:
  454. def __init__(self, object, supportsRotation, supportsPosition, supportsScaling, xOffsetForRotation = 0):
  455. # just because a sub-class can be animatable does not mean it is
  456. self.animationsPresent = object.animation_data and object.animation_data.action
  457. rotAnim = False
  458. locAnim = False
  459. scaAnim = False
  460. useQuat = object.rotation_mode=='QUATERNION'
  461. if (self.animationsPresent):
  462. Main.log('FCurve animation processing begun for: ' + object.name, 1)
  463. self.animations = []
  464. for fcurve in object.animation_data.action.fcurves:
  465. if supportsRotation and fcurve.data_path == 'rotation_euler' and rotAnim == False and useQuat == False:
  466. self.animations.append(VectorAnimation(object, 'rotation_euler', 'rotation', -1, xOffsetForRotation))
  467. rotAnim = True
  468. elif supportsRotation and fcurve.data_path == 'rotation_quaternion' and rotAnim == False and useQuat == True:
  469. self.animations.append(QuaternionAnimation(object, 'rotation_quaternion', 'rotationQuaternion', 1, xOffsetForRotation))
  470. rotAnim = True
  471. elif supportsPosition and fcurve.data_path == 'location' and locAnim == False:
  472. self.animations.append(VectorAnimation(object, 'location', 'position', 1))
  473. locAnim = True
  474. elif supportsScaling and fcurve.data_path == 'scale' and scaAnim == False:
  475. self.animations.append(VectorAnimation(object, 'scale', 'scaling', 1))
  476. scaAnim = True
  477. #Set Animations
  478. if (hasattr(object.data, "autoAnimate") and object.data.autoAnimate):
  479. self.autoAnimate = True
  480. self.autoAnimateFrom = bpy.context.scene.frame_end
  481. self.autoAnimateTo = 0
  482. for animation in self.animations:
  483. if self.autoAnimateFrom > animation.get_first_frame():
  484. self.autoAnimateFrom = animation.get_first_frame()
  485. if self.autoAnimateTo < animation.get_last_frame():
  486. self.autoAnimateTo = animation.get_last_frame()
  487. self.autoAnimateLoop = True
  488. # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  489. def to_scene_file(self, file_handler):
  490. if (self.animationsPresent):
  491. file_handler.write('\n,"animations":[')
  492. first = True
  493. for animation in self.animations:
  494. if first == False:
  495. file_handler.write(',')
  496. animation.to_scene_file(file_handler)
  497. first = False
  498. file_handler.write(']')
  499. if (hasattr(self, "autoAnimate") and self.autoAnimate):
  500. write_bool(file_handler, 'autoAnimate', self.autoAnimate)
  501. write_int(file_handler, 'autoAnimateFrom', self.autoAnimateFrom)
  502. write_int(file_handler, 'autoAnimateTo', self.autoAnimateTo)
  503. write_bool(file_handler, 'autoAnimateLoop', self.autoAnimateLoop)
  504. #===============================================================================
  505. class Mesh(FCurveAnimatable):
  506. def __init__(self, object, scene, startFace, forcedParent, nameID, exporter):
  507. super().__init__(object, True, True, True) #Should animations be done when forcedParent
  508. self.name = object.name + str(nameID)
  509. Main.log('processing begun of mesh: ' + self.name)
  510. self.isVisible = not object.hide_render
  511. self.isEnabled = True
  512. self.useFlatShading = object.data.useFlatShading
  513. self.checkCollisions = object.data.checkCollisions
  514. self.receiveShadows = object.data.receiveShadows
  515. self.castShadows = object.data.castShadows
  516. self.freezeWorldMatrix = object.data.freezeWorldMatrix
  517. # hasSkeleton detection & skeletonID determination
  518. hasSkeleton = False
  519. objArmature = None # if there's an armature, this will be the one!
  520. if len(object.vertex_groups) > 0:
  521. objArmature = object.find_armature()
  522. if objArmature != None:
  523. hasSkeleton = True
  524. i = 0
  525. for obj in scene.objects:
  526. if obj.type == "ARMATURE":
  527. if obj == objArmature:
  528. self.skeletonId = i
  529. break
  530. else:
  531. i += 1
  532. # determine Position, rotation, & scaling
  533. if forcedParent is None:
  534. # Use local matrix
  535. locMatrix = object.matrix_local
  536. if objArmature != None:
  537. # unless the armature is the parent
  538. if object.parent and object.parent == objArmature:
  539. locMatrix = object.matrix_world * object.parent.matrix_world.inverted()
  540. loc, rot, scale = locMatrix.decompose()
  541. self.position = loc
  542. if object.rotation_mode == 'QUATERNION':
  543. self.rotationQuaternion = rot
  544. else:
  545. self.rotation = scale_vector(rot.to_euler('XYZ'), -1)
  546. self.scaling = scale
  547. else:
  548. # use defaults when not None
  549. self.position = mathutils.Vector((0, 0, 0))
  550. self.rotation = scale_vector(mathutils.Vector((0, 0, 0)), 1) # isn't scaling 0's by 1 same as 0?
  551. self.scaling = mathutils.Vector((1, 1, 1))
  552. # determine parent & dataName
  553. if forcedParent is None:
  554. self.dataName = object.data.name # used to support shared vertex instances in later passed
  555. if object.parent and object.parent.type != 'ARMATURE':
  556. self.parentId = object.parent.name
  557. else:
  558. self.dataName = self.name
  559. self.parentId = forcedParent.name
  560. # Get if this will be an instance of another, before processing materials, to avoid multi-bakes
  561. sourceMesh = exporter.getSourceMeshInstance(self.dataName)
  562. if sourceMesh is not None:
  563. #need to make sure rotation mode matches, since value initially copied in InstancedMesh constructor
  564. if hasattr(sourceMesh, 'rotationQuaternion'):
  565. instRot = None
  566. instRotq = rot
  567. else:
  568. instRot = scale_vector(rot.to_euler('XYZ'), -1)
  569. instRotq = None
  570. instance = MeshInstance(self.name, self.position, instRot, instRotq, self.scaling, self.freezeWorldMatrix)
  571. sourceMesh.instances.append(instance)
  572. Main.log('mesh is an instance of : ' + sourceMesh.name + '. Processing halted.', 2)
  573. return
  574. else:
  575. self.instances = []
  576. # Physics
  577. if object.rigid_body != None:
  578. shape_items = {'SPHERE' : SPHERE_IMPOSTER,
  579. 'BOX' : BOX_IMPOSTER,
  580. 'MESH' : MESH_IMPOSTER,
  581. 'CAPSULE' : CAPSULE_IMPOSTER,
  582. 'CONE' : CONE_IMPOSTER,
  583. 'CYLINDER' : CYLINDER_IMPOSTER,
  584. 'CONVEX_HULL': CONVEX_HULL_IMPOSTER}
  585. shape_type = shape_items[object.rigid_body.collision_shape]
  586. self.physicsImpostor = shape_type
  587. mass = object.rigid_body.mass
  588. if mass < 0.005:
  589. mass = 0
  590. self.physicsMass = mass
  591. self.physicsFriction = object.rigid_body.friction
  592. self.physicsRestitution = object.rigid_body.restitution
  593. # process all of the materials required
  594. maxVerts = MAX_VERTEX_ELEMENTS # change for multi-materials
  595. recipe = BakingRecipe(object)
  596. self.billboardMode = recipe.billboardMode
  597. if recipe.needsBaking:
  598. if recipe.multipleRenders:
  599. Main.warn('Mixing of Cycles & Blender Render in same mesh not supported. No materials exported.', 2)
  600. else:
  601. bakedMat = BakedMaterial(exporter, object, recipe)
  602. exporter.materials.append(bakedMat)
  603. self.materialId = bakedMat.name
  604. else:
  605. bjs_material_slots = []
  606. for slot in object.material_slots:
  607. # None will be returned when either the first encounter or must be unique due to baked textures
  608. material = exporter.getMaterial(slot.name)
  609. if (material != None):
  610. material.numOfUsers = material.numOfUsers + 1
  611. Main.log('registered as also a user of material: ' + slot.name, 2)
  612. else:
  613. material = StdMaterial(slot, exporter, object)
  614. exporter.materials.append(material)
  615. bjs_material_slots.append(material)
  616. if len(bjs_material_slots) == 1:
  617. self.materialId = bjs_material_slots[0].name
  618. elif len(bjs_material_slots) > 1:
  619. multimat = MultiMaterial(bjs_material_slots, len(exporter.multiMaterials))
  620. self.materialId = multimat.name
  621. exporter.multiMaterials.append(multimat)
  622. maxVerts = MAX_VERTEX_ELEMENTS_32Bit
  623. else:
  624. Main.warn('No materials have been assigned: ', 2)
  625. # Get mesh
  626. mesh = object.to_mesh(scene, True, 'PREVIEW')
  627. # Triangulate mesh if required
  628. Mesh.mesh_triangulate(mesh)
  629. # Getting vertices and indices
  630. self.positions = []
  631. self.normals = []
  632. self.uvs = [] # not always used
  633. self.uvs2 = [] # not always used
  634. self.colors = [] # not always used
  635. self.indices = []
  636. self.subMeshes = []
  637. hasUV = len(mesh.tessface_uv_textures) > 0
  638. if hasUV:
  639. which = len(mesh.tessface_uv_textures) - 1 if recipe.needsBaking else 0
  640. UVmap = mesh.tessface_uv_textures[which].data
  641. hasUV2 = len(mesh.tessface_uv_textures) > 1 and not recipe.needsBaking
  642. if hasUV2:
  643. UV2map = mesh.tessface_uv_textures[1].data
  644. hasVertexColor = len(mesh.vertex_colors) > 0
  645. if hasVertexColor:
  646. Colormap = mesh.tessface_vertex_colors.active.data
  647. if hasSkeleton:
  648. self.skeletonWeights = []
  649. self.skeletonIndicesCompressed = []
  650. # used tracking of vertices as they are received
  651. alreadySavedVertices = []
  652. vertices_Normals = []
  653. vertices_UVs = []
  654. vertices_UV2s = []
  655. vertices_Colors = []
  656. vertices_indices = []
  657. self.offsetFace = 0
  658. for v in range(0, len(mesh.vertices)):
  659. alreadySavedVertices.append(False)
  660. vertices_Normals.append([])
  661. vertices_UVs.append([])
  662. vertices_UV2s.append([])
  663. vertices_Colors.append([])
  664. vertices_indices.append([])
  665. materialsCount = 1 if recipe.needsBaking else max(1, len(object.material_slots))
  666. verticesCount = 0
  667. indicesCount = 0
  668. maxInfluencersExceeded = 0
  669. for materialIndex in range(materialsCount):
  670. if self.offsetFace != 0:
  671. break
  672. subMeshVerticesStart = verticesCount
  673. subMeshIndexStart = indicesCount
  674. for faceIndex in range(startFace, len(mesh.tessfaces)): # For each face
  675. face = mesh.tessfaces[faceIndex]
  676. if face.material_index != materialIndex and not recipe.needsBaking:
  677. continue
  678. if verticesCount + 3 > maxVerts:
  679. self.offsetFace = faceIndex
  680. break
  681. for v in range(3): # For each vertex in face
  682. vertex_index = face.vertices[v]
  683. vertex = mesh.vertices[vertex_index]
  684. position = vertex.co
  685. if (scene.export_noVertexOpt):
  686. normal = face.normal
  687. else:
  688. normal = vertex.normal
  689. #skeletons
  690. if hasSkeleton:
  691. matricesWeights = []
  692. matricesWeights.append(0.0)
  693. matricesWeights.append(0.0)
  694. matricesWeights.append(0.0)
  695. matricesWeights.append(0.0)
  696. matricesIndicesCompressed = 0
  697. # Getting influences
  698. i = 0
  699. offset = 0
  700. for group in vertex.groups:
  701. index = group.group
  702. weight = group.weight
  703. for boneIndex, bone in enumerate(objArmature.pose.bones):
  704. if object.vertex_groups[index].name == bone.name:
  705. if (i == MAX_INFLUENCERS_PER_VERTEX):
  706. maxInfluencersExceeded += 1
  707. break
  708. matricesWeights[i] = weight
  709. matricesIndicesCompressed += boneIndex << offset
  710. offset = offset + 8
  711. i = i + 1
  712. # Texture coordinates
  713. if hasUV:
  714. vertex_UV = UVmap[face.index].uv[v]
  715. if hasUV2:
  716. vertex_UV2 = UV2map[face.index].uv[v]
  717. # Vertex color
  718. if hasVertexColor:
  719. if v == 0:
  720. vertex_Color = Colormap[face.index].color1
  721. if v == 1:
  722. vertex_Color = Colormap[face.index].color2
  723. if v == 2:
  724. vertex_Color = Colormap[face.index].color3
  725. # Check if the current vertex is already saved
  726. alreadySaved = alreadySavedVertices[vertex_index] and not (hasSkeleton or scene.export_noVertexOpt)
  727. if alreadySaved:
  728. alreadySaved = False
  729. # UV
  730. index_UV = 0
  731. for savedIndex in vertices_indices[vertex_index]:
  732. vNormal = vertices_Normals[vertex_index][index_UV]
  733. if (normal.x != vNormal.x or normal.y != vNormal.y or normal.z != vNormal.z):
  734. continue;
  735. if hasUV:
  736. vUV = vertices_UVs[vertex_index][index_UV]
  737. if (vUV[0] != vertex_UV[0] or vUV[1] != vertex_UV[1]):
  738. continue
  739. if hasUV2:
  740. vUV2 = vertices_UV2s[vertex_index][index_UV]
  741. if (vUV2[0] != vertex_UV2[0] or vUV2[1] != vertex_UV2[1]):
  742. continue
  743. if hasVertexColor:
  744. vColor = vertices_Colors[vertex_index][index_UV]
  745. if (vColor.r != vertex_Color.r or vColor.g != vertex_Color.g or vColor.b != vertex_Color.b):
  746. continue
  747. if vertices_indices[vertex_index][index_UV] >= subMeshVerticesStart:
  748. alreadySaved = True
  749. break
  750. index_UV += 1
  751. if (alreadySaved):
  752. # Reuse vertex
  753. index = vertices_indices[vertex_index][index_UV]
  754. else:
  755. # Export new one
  756. index = verticesCount
  757. alreadySavedVertices[vertex_index] = True
  758. vertices_Normals[vertex_index].append(normal)
  759. self.normals.append(normal)
  760. if hasUV:
  761. vertices_UVs[vertex_index].append(vertex_UV)
  762. self.uvs.append(vertex_UV[0])
  763. self.uvs.append(vertex_UV[1])
  764. if hasUV2:
  765. vertices_UV2s[vertex_index].append(vertex_UV2)
  766. self.uvs2.append(vertex_UV2[0])
  767. self.uvs2.append(vertex_UV2[1])
  768. if hasVertexColor:
  769. vertices_Colors[vertex_index].append(vertex_Color)
  770. self.colors.append(vertex_Color.r)
  771. self.colors.append(vertex_Color.g)
  772. self.colors.append(vertex_Color.b)
  773. self.colors.append(1.0)
  774. if hasSkeleton:
  775. self.skeletonWeights.append(matricesWeights[0])
  776. self.skeletonWeights.append(matricesWeights[1])
  777. self.skeletonWeights.append(matricesWeights[2])
  778. self.skeletonWeights.append(matricesWeights[3])
  779. self.skeletonIndicesCompressed.append(matricesIndicesCompressed)
  780. vertices_indices[vertex_index].append(index)
  781. self.positions.append(position)
  782. verticesCount += 1
  783. self.indices.append(index)
  784. indicesCount += 1
  785. self.subMeshes.append(SubMesh(materialIndex, subMeshVerticesStart, subMeshIndexStart, verticesCount - subMeshVerticesStart, indicesCount - subMeshIndexStart))
  786. if verticesCount > MAX_VERTEX_ELEMENTS:
  787. warn('Due to multi-materials & this meshes size, 32bit indices must be used. This may not run on all hardware.', 2)
  788. if maxInfluencersExceeded > 0:
  789. Main.warn('Maximum # of influencers exceeded for ' + format_int(maxInfluencersExceeded) + ' vertices, extras ignored', 2)
  790. BakedMaterial.meshBakingClean(object)
  791. Main.log('num positions : ' + str(len(self.positions)), 2)
  792. Main.log('num normals : ' + str(len(self.normals )), 2)
  793. Main.log('num uvs : ' + str(len(self.uvs )), 2)
  794. Main.log('num uvs2 : ' + str(len(self.uvs2 )), 2)
  795. Main.log('num colors : ' + str(len(self.colors )), 2)
  796. Main.log('num indices : ' + str(len(self.indices )), 2)
  797. if hasattr(self, 'skeletonWeights'):
  798. Main.log('num skeletonWeights: ' + str(len(self.skeletonWeights)), 2)
  799. Main.log('num skeletonIndices: ' + str(len(self.skeletonIndicesCompressed * 4)), 2)
  800. numZeroAreaFaces = self.find_zero_area_faces()
  801. if numZeroAreaFaces > 0:
  802. Main.warn('# of 0 area faces found: ' + str(numZeroAreaFaces), 2)
  803. # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  804. def find_zero_area_faces(self):
  805. nFaces = int(len(self.indices) / 3)
  806. nZeroAreaFaces = 0
  807. for f in range(0, nFaces):
  808. faceOffset = f * 3
  809. p1 = self.positions[self.indices[faceOffset ]]
  810. p2 = self.positions[self.indices[faceOffset + 1]]
  811. p3 = self.positions[self.indices[faceOffset + 2]]
  812. if same_vertex(p1, p2) or same_vertex(p1, p3) or same_vertex(p2, p3): nZeroAreaFaces += 1
  813. return nZeroAreaFaces
  814. # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  815. @staticmethod
  816. def mesh_triangulate(mesh):
  817. try:
  818. import bmesh
  819. bm = bmesh.new()
  820. bm.from_mesh(mesh)
  821. bmesh.ops.triangulate(bm, faces = bm.faces)
  822. bm.to_mesh(mesh)
  823. mesh.calc_tessface()
  824. bm.free()
  825. except:
  826. pass
  827. # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  828. def to_scene_file(self, file_handler):
  829. file_handler.write('{')
  830. write_string(file_handler, 'name', self.name, True)
  831. write_string(file_handler, 'id', self.name)
  832. if hasattr(self, 'parentId'): write_string(file_handler, 'parentId', self.parentId)
  833. if hasattr(self, 'materialId'): write_string(file_handler, 'materialId', self.materialId)
  834. write_int(file_handler, 'billboardMode', self.billboardMode)
  835. write_vector(file_handler, 'position', self.position)
  836. if hasattr(self, "rotationQuaternion"):
  837. write_quaternion(file_handler, 'rotationQuaternion', self.rotationQuaternion)
  838. else:
  839. write_vector(file_handler, 'rotation', self.rotation)
  840. write_vector(file_handler, 'scaling', self.scaling)
  841. write_bool(file_handler, 'isVisible', self.isVisible)
  842. write_bool(file_handler, 'freezeWorldMatrix', self.freezeWorldMatrix)
  843. write_bool(file_handler, 'isEnabled', self.isEnabled)
  844. write_bool(file_handler, 'useFlatShading', self.useFlatShading)
  845. write_bool(file_handler, 'checkCollisions', self.checkCollisions)
  846. write_bool(file_handler, 'receiveShadows', self.receiveShadows)
  847. if hasattr(self, 'physicsImpostor'):
  848. write_int(file_handler, 'physicsImpostor', self.physicsImpostor)
  849. write_float(file_handler, 'physicsMass', self.physicsMass)
  850. write_float(file_handler, 'physicsFriction', self.physicsFriction)
  851. write_float(file_handler, 'physicsRestitution', self.physicsRestitution)
  852. # Geometry
  853. if hasattr(self, 'skeletonId'): write_int(file_handler, 'skeletonId', self.skeletonId)
  854. write_vector_array(file_handler, 'positions', self.positions)
  855. write_vector_array(file_handler, 'normals' , self.normals )
  856. if len(self.uvs) > 0:
  857. write_array(file_handler, 'uvs', self.uvs)
  858. if len(self.uvs2) > 0:
  859. write_array(file_handler, 'uvs2', self.uvs2)
  860. if len(self.colors) > 0:
  861. write_array(file_handler, 'colors', self.colors)
  862. if hasattr(self, 'skeletonWeights'):
  863. write_array(file_handler, 'matricesWeights', self.skeletonWeights)
  864. write_array(file_handler, 'matricesIndices', self.skeletonIndicesCompressed)
  865. write_array(file_handler, 'indices', self.indices)
  866. # Sub meshes
  867. file_handler.write('\n,"subMeshes":[')
  868. first = True
  869. for subMesh in self.subMeshes:
  870. if first == False:
  871. file_handler.write(',')
  872. subMesh.to_scene_file(file_handler)
  873. first = False
  874. file_handler.write(']')
  875. super().to_scene_file(file_handler) # Animations
  876. # Instances
  877. first = True
  878. file_handler.write('\n,"instances":[')
  879. for instance in self.instances:
  880. if first == False:
  881. file_handler.write(',')
  882. instance.to_scene_file(file_handler)
  883. first = False
  884. file_handler.write(']')
  885. # Close mesh
  886. file_handler.write('}\n')
  887. self.alreadyExported = True
  888. #===============================================================================
  889. class MeshInstance:
  890. def __init__(self, name, position, rotation, rotationQuaternion, scaling, freezeWorldMatrix):
  891. self.name = name
  892. self.position = position
  893. if rotation is not None:
  894. self.rotation = rotation
  895. if rotationQuaternion is not None:
  896. self.rotationQuaternion = rotationQuaternion
  897. self.scaling = scaling
  898. self.freezeWorldMatrix = freezeWorldMatrix
  899. # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  900. def to_scene_file(self, file_handler):
  901. file_handler.write('{')
  902. write_string(file_handler, 'name', self.name, True)
  903. write_vector(file_handler, 'position', self.position)
  904. if hasattr(self, 'rotation'):
  905. write_vector(file_handler, 'rotation', self.rotation)
  906. else:
  907. write_quaternion(file_handler, 'rotationQuaternion', self.rotationQuaternion)
  908. write_vector(file_handler, 'scaling', self.scaling)
  909. # freeze World Matrix currently ignored for instances
  910. write_bool(file_handler, 'freezeWorldMatrix', self.freezeWorldMatrix)
  911. file_handler.write('}')
  912. #===============================================================================
  913. class Node(FCurveAnimatable):
  914. def __init__(self, node):
  915. super().__init__(node, True, True, True) #Should animations be done when forcedParent
  916. Main.log('processing begun of node: ' + node.name)
  917. self.name = node.name
  918. if node.parent and node.parent.type != 'ARMATURE':
  919. self.parentId = node.parent.name
  920. loc, rot, scale = node.matrix_local.decompose()
  921. self.position = loc
  922. if node.rotation_mode == 'QUATERNION':
  923. self.rotationQuaternion = rot
  924. else:
  925. self.rotation = scale_vector(rot.to_euler('XYZ'), -1)
  926. self.scaling = scale
  927. self.isVisible = False
  928. self.isEnabled = True
  929. self.checkCollisions = False
  930. self.billboardMode = BILLBOARDMODE_NONE
  931. self.castShadows = False
  932. self.receiveShadows = False
  933. # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  934. def to_scene_file(self, file_handler):
  935. file_handler.write('{')
  936. write_string(file_handler, 'name', self.name, True)
  937. write_string(file_handler, 'id', self.name)
  938. if hasattr(self, 'parentId'): write_string(file_handler, 'parentId', self.parentId)
  939. write_vector(file_handler, 'position', self.position)
  940. if hasattr(self, "rotationQuaternion"):
  941. write_quaternion(file_handler, "rotationQuaternion", self.rotationQuaternion)
  942. else:
  943. write_vector(file_handler, 'rotation', self.rotation)
  944. write_vector(file_handler, 'scaling', self.scaling)
  945. write_bool(file_handler, 'isVisible', self.isVisible)
  946. write_bool(file_handler, 'isEnabled', self.isEnabled)
  947. write_bool(file_handler, 'checkCollisions', self.checkCollisions)
  948. write_int(file_handler, 'billboardMode', self.billboardMode)
  949. write_bool(file_handler, 'receiveShadows', self.receiveShadows)
  950. super().to_scene_file(file_handler) # Animations
  951. file_handler.write('}')
  952. #===============================================================================
  953. class SubMesh:
  954. def __init__(self, materialIndex, verticesStart, indexStart, verticesCount, indexCount):
  955. self.materialIndex = materialIndex
  956. self.verticesStart = verticesStart
  957. self.indexStart = indexStart
  958. self.verticesCount = verticesCount
  959. self.indexCount = indexCount
  960. # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  961. def to_scene_file(self, file_handler):
  962. file_handler.write('{')
  963. write_int(file_handler, 'materialIndex', self.materialIndex, True)
  964. write_int(file_handler, 'verticesStart', self.verticesStart)
  965. write_int(file_handler, 'verticesCount', self.verticesCount)
  966. write_int(file_handler, 'indexStart' , self.indexStart)
  967. write_int(file_handler, 'indexCount' , self.indexCount)
  968. file_handler.write('}')
  969. #===============================================================================
  970. class Bone:
  971. def __init__(self, bone, skeleton, scene, index):
  972. Main.log('processing begun of bone: ' + bone.name + ', index: '+ str(index))
  973. self.name = bone.name
  974. self.index = index
  975. matrix_world = skeleton.matrix_world
  976. self.matrix = Bone.get_matrix(bone, matrix_world)
  977. parentId = -1
  978. if (bone.parent):
  979. for parent in skeleton.pose.bones:
  980. parentId += 1
  981. if parent == bone.parent:
  982. break;
  983. self.parentBoneIndex = parentId
  984. #animation
  985. if (skeleton.animation_data):
  986. Main.log('animation begun of bone: ' + self.name)
  987. self.animation = Animation(ANIMATIONTYPE_MATRIX, scene.render.fps, ANIMATIONLOOPMODE_CYCLE, 'anim', '_matrix')
  988. start_frame = scene.frame_start
  989. end_frame = scene.frame_end
  990. previousBoneMatrix = None
  991. for frame in range(start_frame, end_frame + 1):
  992. bpy.context.scene.frame_set(frame)
  993. currentBoneMatrix = Bone.get_matrix(bone, matrix_world)
  994. if (frame != end_frame and currentBoneMatrix == previousBoneMatrix):
  995. continue
  996. self.animation.frames.append(frame)
  997. self.animation.values.append(Bone.get_matrix(bone, matrix_world))
  998. previousBoneMatrix = currentBoneMatrix
  999. bpy.context.scene.frame_set(start_frame)
  1000. # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  1001. @staticmethod
  1002. def get_matrix(bone, matrix_world):
  1003. SystemMatrix = mathutils.Matrix.Scale(-1, 4, mathutils.Vector((0, 0, 1))) * mathutils.Matrix.Rotation(math.radians(-90), 4, 'X')
  1004. if (bone.parent):
  1005. return (SystemMatrix * matrix_world * bone.parent.matrix).inverted() * (SystemMatrix * matrix_world * bone.matrix)
  1006. else:
  1007. return SystemMatrix * matrix_world * bone.matrix
  1008. # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  1009. def to_scene_file(self, file_handler):
  1010. file_handler.write('\n{')
  1011. write_string(file_handler, 'name', self.name, True)
  1012. write_int(file_handler, 'index', self.index)
  1013. write_matrix4(file_handler, 'matrix', self.matrix)
  1014. write_int(file_handler, 'parentBoneIndex', self.parentBoneIndex)
  1015. #animation
  1016. if hasattr(self, 'animation'):
  1017. file_handler.write(',"animation":')
  1018. self.animation.to_scene_file(file_handler)
  1019. file_handler.write('}')
  1020. #===============================================================================
  1021. class Skeleton:
  1022. def __init__(self, skeleton, scene, id):
  1023. Main.log('processing begun of skeleton: ' + skeleton.name + ', id: '+ str(id))
  1024. self.name = skeleton.name
  1025. self.id = id
  1026. self.bones = []
  1027. bones = skeleton.pose.bones
  1028. j = 0
  1029. for bone in bones:
  1030. self.bones.append(Bone(bone, skeleton, scene, j))
  1031. j = j + 1
  1032. Main.log('processing complete of skeleton: ' + skeleton.name)
  1033. # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  1034. def to_scene_file(self, file_handler):
  1035. file_handler.write('{')
  1036. write_string(file_handler, 'name', self.name, True)
  1037. write_int(file_handler, 'id', self.id) # keep int for legacy of original exporter
  1038. file_handler.write(',"bones":[')
  1039. first = True
  1040. for bone in self.bones:
  1041. if first != True:
  1042. file_handler.write(',')
  1043. first = False
  1044. bone.to_scene_file(file_handler)
  1045. file_handler.write(']')
  1046. file_handler.write('}')
  1047. #===============================================================================
  1048. class Camera(FCurveAnimatable):
  1049. def __init__(self, camera):
  1050. super().__init__(camera, True, True, False, math.pi / 2)
  1051. if camera.parent and camera.parent.type != 'ARMATURE':
  1052. self.parentId = camera.parent.name
  1053. self.CameraType = camera.data.CameraType
  1054. self.name = camera.name
  1055. Main.log('processing begun of camera (' + self.CameraType + '): ' + self.name)
  1056. self.position = camera.location
  1057. # for quaternions, convert to euler XYZ, otherwise, use the default rotation_euler
  1058. eul = camera.rotation_quaternion.to_euler("XYZ") if camera.rotation_mode == 'QUATERNION' else camera.rotation_euler
  1059. self.rotation = mathutils.Vector((-eul[0] + math.pi / 2, eul[1], -eul[2]))
  1060. self.fov = camera.data.angle
  1061. self.minZ = camera.data.clip_start
  1062. self.maxZ = camera.data.clip_end
  1063. self.speed = 1.0
  1064. self.inertia = 0.9
  1065. self.checkCollisions = camera.data.checkCollisions
  1066. self.applyGravity = camera.data.applyGravity
  1067. self.ellipsoid = camera.data.ellipsoid
  1068. self.Camera3DRig = camera.data.Camera3DRig
  1069. self.interaxialDistance = camera.data.interaxialDistance
  1070. for constraint in camera.constraints:
  1071. if constraint.type == 'TRACK_TO':
  1072. self.lockedTargetId = constraint.target.name
  1073. break
  1074. if self.CameraType == ARC_ROTATE_CAM or self.CameraType == FOLLOW_CAM:
  1075. if not hasattr(self, 'lockedTargetId'):
  1076. Main.warn('Camera type with manditory target specified, but no target to track set. Ignored', 2)
  1077. self.fatalProblem = True
  1078. # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  1079. def update_for_target_attributes(self, meshesAndNodes):
  1080. if not hasattr(self, 'lockedTargetId'): return
  1081. # find the actual mesh tracking, so properties can be derrived
  1082. targetFound = False
  1083. for mesh in meshesAndNodes:
  1084. if mesh.name == self.lockedTargetId:
  1085. targetMesh = mesh
  1086. targetFound = True
  1087. break;
  1088. xApart = 3 if not targetFound else self.position.x - targetMesh.position.x
  1089. yApart = 3 if not targetFound else self.position.y - targetMesh.position.y
  1090. zApart = 3 if not targetFound else self.position.z - targetMesh.position.z
  1091. distance3D = math.sqrt(xApart * xApart + yApart * yApart + zApart * zApart)
  1092. alpha = math.atan2(yApart, xApart);
  1093. beta = math.atan2(yApart, zApart);
  1094. if self.CameraType == FOLLOW_CAM:
  1095. self.followHeight = zApart
  1096. self.followDistance = distance3D
  1097. self.followRotation = 90 + (alpha * 180 / math.pi)
  1098. elif self.CameraType == self.CameraType == ARC_ROTATE_CAM:
  1099. self.arcRotAlpha = alpha
  1100. self.arcRotBeta = beta
  1101. self.arcRotRadius = distance3D
  1102. # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  1103. def to_scene_file(self, file_handler):
  1104. file_handler.write('{')
  1105. write_string(file_handler, 'name', self.name, True)
  1106. write_string(file_handler, 'id', self.name)
  1107. write_vector(file_handler, 'position', self.position)
  1108. write_vector(file_handler, 'rotation', self.rotation)
  1109. write_float(file_handler, 'fov', self.fov)
  1110. write_float(file_handler, 'minZ', self.minZ)
  1111. write_float(file_handler, 'maxZ', self.maxZ)
  1112. write_float(file_handler, 'speed', self.speed)
  1113. write_float(file_handler, 'inertia', self.inertia)
  1114. write_bool(file_handler, 'checkCollisions', self.checkCollisions)
  1115. write_bool(file_handler, 'applyGravity', self.applyGravity)
  1116. write_array3(file_handler, 'ellipsoid', self.ellipsoid)
  1117. # always assign rig, even when none, Reason: Could have VR camera with different Rig than default
  1118. write_int(file_handler, 'cameraRigMode', self.Camera3DRig)
  1119. write_float(file_handler, 'interaxial_distance', self.interaxialDistance)
  1120. write_string(file_handler, 'type', self.CameraType)
  1121. if hasattr(self, 'parentId'): write_string(file_handler, 'parentId', self.parentId)
  1122. if self.CameraType == FOLLOW_CAM:
  1123. write_float(file_handler, 'heightOffset', self.followHeight)
  1124. write_float(file_handler, 'radius', self.followDistance)
  1125. write_float(file_handler, 'rotationOffset', self.followRotation)
  1126. elif self.CameraType == ARC_ROTATE_CAM:
  1127. write_float(file_handler, 'alpha', self.arcRotAlpha)
  1128. write_float(file_handler, 'beta', self.arcRotBeta)
  1129. write_float(file_handler, 'radius', self.arcRotRadius)
  1130. if hasattr(self, 'lockedTargetId'):
  1131. write_string(file_handler, 'lockedTargetId', self.lockedTargetId)
  1132. super().to_scene_file(file_handler) # Animations
  1133. file_handler.write('}')
  1134. #===============================================================================
  1135. class Light(FCurveAnimatable):
  1136. def __init__(self, light):
  1137. super().__init__(light, False, True, False)
  1138. if light.parent and light.parent.type != 'ARMATURE':
  1139. self.parentId = light.parent.name
  1140. self.name = light.name
  1141. Main.log('processing begun of light (' + light.data.type + '): ' + self.name)
  1142. light_type_items = {'POINT': POINT_LIGHT, 'SUN': DIRECTIONAL_LIGHT, 'SPOT': SPOT_LIGHT, 'HEMI': HEMI_LIGHT, 'AREA': POINT_LIGHT}
  1143. self.light_type = light_type_items[light.data.type]
  1144. if self.light_type == POINT_LIGHT:
  1145. self.position = light.location
  1146. if hasattr(light.data, 'use_sphere'):
  1147. if light.data.use_sphere:
  1148. self.range = light.data.distance
  1149. elif self.light_type == DIRECTIONAL_LIGHT:
  1150. self.position = light.location
  1151. self.direction = Light.get_direction(light.matrix_local)
  1152. elif self.light_type == SPOT_LIGHT:
  1153. self.position = light.location
  1154. self.direction = Light.get_direction(light.matrix_local)
  1155. self.angle = light.data.spot_size
  1156. self.exponent = light.data.spot_blend * 2
  1157. if light.data.use_sphere:
  1158. self.range = light.data.distance
  1159. else:
  1160. # Hemi
  1161. matrix_local = light.matrix_local.copy()
  1162. matrix_local.translation = mathutils.Vector((0, 0, 0))
  1163. self.direction = (mathutils.Vector((0, 0, -1)) * matrix_local)
  1164. self.direction = scale_vector(self.direction, -1)
  1165. self.groundColor = mathutils.Color((0, 0, 0))
  1166. self.intensity = light.data.energy
  1167. self.diffuse = light.data.color if light.data.use_diffuse else mathutils.Color((0, 0, 0))
  1168. self.specular = light.data.color if light.data.use_specular else mathutils.Color((0, 0, 0))
  1169. # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  1170. def to_scene_file(self, file_handler):
  1171. file_handler.write('{')
  1172. write_string(file_handler, 'name', self.name, True)
  1173. write_string(file_handler, 'id', self.name)
  1174. write_float(file_handler, 'type', self.light_type)
  1175. if hasattr(self, 'parentId' ): write_string(file_handler, 'parentId' , self.parentId )
  1176. if hasattr(self, 'position' ): write_vector(file_handler, 'position' , self.position )
  1177. if hasattr(self, 'direction' ): write_vector(file_handler, 'direction' , self.direction )
  1178. if hasattr(self, 'angle' ): write_float (file_handler, 'angle' , self.angle )
  1179. if hasattr(self, 'exponent' ): write_float (file_handler, 'exponent' , self.exponent )
  1180. if hasattr(self, 'groundColor'): write_color (file_handler, 'groundColor', self.groundColor)
  1181. if hasattr(self, 'range' ): write_float (file_handler, 'range' , self.range )
  1182. write_float(file_handler, 'intensity', self.intensity)
  1183. write_color(file_handler, 'diffuse', self.diffuse)
  1184. write_color(file_handler, 'specular', self.specular)
  1185. super().to_scene_file(file_handler) # Animations
  1186. file_handler.write('}')
  1187. @staticmethod
  1188. def get_direction(matrix):
  1189. return (matrix.to_3x3() * mathutils.Vector((0.0, 0.0, -1.0))).normalized()
  1190. #===============================================================================
  1191. class ShadowGenerator:
  1192. def __init__(self, lamp, meshesAndNodes, scene):
  1193. Main.log('processing begun of shadows for light: ' + lamp.name)
  1194. self.lightId = lamp.name
  1195. self.mapSize = lamp.data.shadowMapSize
  1196. self.shadowBias = lamp.data.shadowBias
  1197. if lamp.data.shadowMap == VARIANCE_SHADOWS:
  1198. self.useVarianceShadowMap = True
  1199. elif lamp.data.shadowMap == POISSON_SHADOWS:
  1200. self.usePoissonSampling = True
  1201. elif lamp.data.shadowMap == BLUR_VARIANCE_SHADOWS:
  1202. self.useBlurVarianceShadowMap = True
  1203. self.shadowBlurScale = lamp.data.shadowBlurScale
  1204. self.shadowBlurBoxOffset = lamp.data.shadowBlurBoxOffset
  1205. # .babylon specific section
  1206. self.shadowCasters = []
  1207. for mesh in meshesAndNodes:
  1208. if (mesh.castShadows):
  1209. self.shadowCasters.append(mesh.name)
  1210. # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  1211. def to_scene_file(self, file_handler):
  1212. file_handler.write('{')
  1213. write_int(file_handler, 'mapSize', self.mapSize, True)
  1214. write_string(file_handler, 'lightId', self.lightId)
  1215. write_float(file_handler, 'bias', self.shadowBias)
  1216. if hasattr(self, 'useVarianceShadowMap') :
  1217. write_bool(file_handler, 'useVarianceShadowMap', self.useVarianceShadowMap)
  1218. elif hasattr(self, 'usePoissonSampling'):
  1219. write_bool(file_handler, 'usePoissonSampling', self.usePoissonSampling)
  1220. elif hasattr(self, 'useBlurVarianceShadowMap'):
  1221. write_bool(file_handler, 'useBlurVarianceShadowMap', self.useBlurVarianceShadowMap)
  1222. write_int(file_handler, 'blurScale', self.shadowBlurScale)
  1223. write_int(file_handler, 'blurBoxOffset', self.shadowBlurBoxOffset)
  1224. file_handler.write(',"renderList":[')
  1225. first = True
  1226. for caster in self.shadowCasters:
  1227. if first != True:
  1228. file_handler.write(',')
  1229. first = False
  1230. file_handler.write('"' + caster + '"')
  1231. file_handler.write(']')
  1232. file_handler.write('}')
  1233. #===============================================================================
  1234. class MultiMaterial:
  1235. def __init__(self, material_slots, idx):
  1236. self.name = Main.nameSpace + '.' + 'Multimaterial#' + str(idx)
  1237. Main.log('processing begun of multimaterial: ' + self.name, 2)
  1238. self.material_slots = material_slots
  1239. # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  1240. def to_scene_file(self, file_handler):
  1241. file_handler.write('{')
  1242. write_string(file_handler, 'name', self.name, True)
  1243. write_string(file_handler, 'id', self.name)
  1244. file_handler.write(',"materials":[')
  1245. first = True
  1246. for material in self.material_slots:
  1247. if first != True:
  1248. file_handler.write(',')
  1249. file_handler.write('"' + material.name +'"')
  1250. first = False
  1251. file_handler.write(']')
  1252. file_handler.write('}')
  1253. #===============================================================================
  1254. class Texture:
  1255. def __init__(self, slot, level, textureOrImage, mesh, exporter):
  1256. wasBaked = not hasattr(textureOrImage, 'uv_layer')
  1257. if wasBaked:
  1258. image = textureOrImage
  1259. texture = None
  1260. repeat = False
  1261. self.hasAlpha = False
  1262. self.coordinatesIndex = 0
  1263. else:
  1264. texture = textureOrImage
  1265. image = texture.texture.image
  1266. repeat = texture.texture.extension == 'REPEAT'
  1267. self.hasAlpha = texture.texture.use_alpha
  1268. usingMap = texture.uv_layer
  1269. if len(usingMap) == 0:
  1270. usingMap = mesh.data.uv_textures[0].name
  1271. Main.log('Image texture found, type: ' + slot + ', mapped using: "' + usingMap + '"', 3)
  1272. if mesh.data.uv_textures[0].name == usingMap:
  1273. self.coordinatesIndex = 0
  1274. elif mesh.data.uv_textures[1].name == usingMap:
  1275. self.coordinatesIndex = 1
  1276. else:
  1277. Main.warn('Texture is not mapped as UV or UV2, assigned 1', 4)
  1278. self.coordinatesIndex = 0
  1279. # always write the file out, since base64 encoding is easiest from a file
  1280. try:
  1281. imageFilepath = os.path.normpath(bpy.path.abspath(image.filepath))
  1282. basename = os.path.basename(imageFilepath)
  1283. targetdir = os.path.dirname(exporter.filepath)
  1284. internalImage = image.packed_file or wasBaked
  1285. # when coming from either a packed image or a baked image, then save_render
  1286. if internalImage:
  1287. if exporter.scene.inlineTextures:
  1288. textureFile = os.path.join(targetdir, basename + "temp")
  1289. else:
  1290. textureFile = os.path.join(targetdir, basename)
  1291. image.save_render(textureFile)
  1292. # when backed by an actual file, copy to target dir, unless inlining
  1293. else:
  1294. textureFile = bpy.path.abspath(image.filepath)
  1295. if not exporter.scene.inlineTextures:
  1296. shutil.copy(textureFile, targetdir)
  1297. except:
  1298. ex = sys.exc_info()
  1299. Main.log('Error encountered processing image file: ' + ', Error: '+ str(ex[1]))
  1300. if exporter.scene.inlineTextures:
  1301. # base64 is easiest from a file, so sometimes a temp file was made above; need to delete those
  1302. with open(textureFile, "rb") as image_file:
  1303. asString = base64.b64encode(image_file.read()).decode()
  1304. self.encoded_URI = 'data:image/' + image.file_format + ';base64,' + asString
  1305. if internalImage:
  1306. os.remove(textureFile)
  1307. # capture texture attributes
  1308. self.slot = slot
  1309. self.name = basename
  1310. self.level = level
  1311. if (texture and texture.mapping == 'CUBE'):
  1312. self.coordinatesMode = CUBIC_MODE
  1313. if (texture and texture.mapping == 'SPHERE'):
  1314. self.coordinatesMode = SPHERICAL_MODE
  1315. else:
  1316. self.coordinatesMode = EXPLICIT_MODE
  1317. self.uOffset = texture.offset.x if texture else 0.0
  1318. self.vOffset = texture.offset.y if texture else 0.0
  1319. self.uScale = texture.scale.x if texture else 1.0
  1320. self.vScale = texture.scale.y if texture else 1.0
  1321. self.uAng = 0
  1322. self.vAng = 0
  1323. self.wAng = 0
  1324. if (repeat):
  1325. if (texture.texture.use_mirror_x):
  1326. self.wrapU = MIRROR_ADDRESSMODE
  1327. else:
  1328. self.wrapU = WRAP_ADDRESSMODE
  1329. if (texture.texture.use_mirror_y):
  1330. self.wrapV = MIRROR_ADDRESSMODE
  1331. else:
  1332. self.wrapV = WRAP_ADDRESSMODE
  1333. else:
  1334. self.wrapU = CLAMP_ADDRESSMODE
  1335. self.wrapV = CLAMP_ADDRESSMODE
  1336. # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  1337. def to_scene_file(self, file_handler):
  1338. file_handler.write(', \n"' + self.slot + '":{')
  1339. write_string(file_handler, 'name', self.name, True)
  1340. write_float(file_handler, 'level', self.level)
  1341. write_float(file_handler, 'hasAlpha', self.hasAlpha)
  1342. write_int(file_handler, 'coordinatesMode', self.coordinatesMode)
  1343. write_float(file_handler, 'uOffset', self.uOffset)
  1344. write_float(file_handler, 'vOffset', self.vOffset)
  1345. write_float(file_handler, 'uScale', self.uScale)
  1346. write_float(file_handler, 'vScale', self.vScale)
  1347. write_float(file_handler, 'uAng', self.uAng)
  1348. write_float(file_handler, 'vAng', self.vAng)
  1349. write_float(file_handler, 'wAng', self.wAng)
  1350. write_int(file_handler, 'wrapU', self.wrapU)
  1351. write_int(file_handler, 'wrapV', self.wrapV)
  1352. write_int(file_handler, 'coordinatesIndex', self.coordinatesIndex)
  1353. if hasattr(self,'encoded_URI'):
  1354. write_string(file_handler, 'base64String', self.encoded_URI)
  1355. file_handler.write('}')
  1356. #===============================================================================
  1357. # need to evaluate the need to bake a mesh before even starting; class also stores specific types of bakes
  1358. class BakingRecipe:
  1359. def __init__(self, mesh, forceBaking = False):
  1360. # initialize all members
  1361. self.needsBaking = forceBaking
  1362. self.diffuseBaking = forceBaking
  1363. self.ambientBaking = False
  1364. self.opacityBaking = False
  1365. self.reflectionBaking = False
  1366. self.emissiveBaking = False
  1367. self.bumpBaking = False
  1368. self.specularBaking = False
  1369. # need to make sure a single render
  1370. self.cyclesRender = False
  1371. blenderRender = False
  1372. # transfer from Mesh custom properties
  1373. self.bakeSize = mesh.data.bakeSize
  1374. self.bakeQuality = mesh.data.bakeQuality # for lossy compression formats
  1375. # accumulators set by Blender Game
  1376. self.backFaceCulling = True # used only when baking
  1377. self.billboardMode = BILLBOARDMODE_ALL if len(mesh.material_slots) == 1 and mesh.material_slots[0].material.game_settings.face_orientation == 'BILLBOARD' else BILLBOARDMODE_NONE
  1378. # Cycles specific, need to get the node trees of each material
  1379. self.nodeTrees = []
  1380. for material_slot in mesh.material_slots:
  1381. # a material slot is not a reference to an actual material; need to look up
  1382. material = material_slot.material
  1383. self.backFaceCulling &= material.game_settings.use_backface_culling
  1384. # testing for Cycles renderer has to be different
  1385. if material.use_nodes == True:
  1386. self.needsBaking = True
  1387. self.cyclesRender = True
  1388. self.nodeTrees.append(material.node_tree)
  1389. for node in material.node_tree.nodes:
  1390. id = node.bl_idname
  1391. if id == 'ShaderNodeBsdfDiffuse':
  1392. self.diffuseBaking = True
  1393. if id == 'ShaderNodeAmbientOcclusion':
  1394. self.ambientBaking = True
  1395. # there is no opacity baking for Cycles AFAIK
  1396. if id == '':
  1397. self.opacityBaking = True
  1398. if id == 'ShaderNodeEmission':
  1399. self.emissiveBaking = True
  1400. if id == 'ShaderNodeNormal' or id == 'ShaderNodeNormalMap':
  1401. self.bumpBaking = True
  1402. if id == '':
  1403. self.specularBaking = True
  1404. else:
  1405. blenderRender = True
  1406. textures = [mtex for mtex in material.texture_slots if mtex and mtex.texture]
  1407. for mtex in textures:
  1408. if mtex.texture.type == 'IMAGE' or mtex.texture.type == 'NONE':
  1409. continue
  1410. self.needsBaking = True
  1411. if mtex.use_map_diffuse or mtex.use_map_color_diffuse:
  1412. if mtex.texture_coords == 'REFLECTION':
  1413. self.reflectionBaking = True
  1414. else:
  1415. self.diffuseBaking = True
  1416. if mtex.use_map_ambient:
  1417. self.ambientBaking = True
  1418. if mtex.use_map_alpha:
  1419. self.opacityBaking = True
  1420. if mtex.use_map_emit:
  1421. self.emissiveBaking = True
  1422. if mtex.use_map_normal:
  1423. self.bumpBaking = True
  1424. if mtex.use_map_color_spec:
  1425. self.specularBaking = True
  1426. self.multipleRenders = blenderRender and self.cyclesRender
  1427. # check for really old .blend file, eg. 2.49, to ensure that everything requires exists
  1428. if self.needsBaking and bpy.data.screens.find('UV Editing') == -1:
  1429. Main.warn('Contains material requiring baking, but resources not available. Probably .blend very old', 2)
  1430. self.needsBaking = False
  1431. #===============================================================================
  1432. # Not intended to be instanced directly
  1433. class Material:
  1434. def __init__(self):
  1435. # the number of users == 1 will cause the checkReadyOnlyOnce attribute to be set to true
  1436. self.numOfUsers = 1
  1437. # first pass of textures, either appending image type or recording types of bakes to do
  1438. self.textures = []
  1439. # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  1440. def to_scene_file(self, file_handler):
  1441. file_handler.write('{')
  1442. write_string(file_handler, 'name', self.name, True)
  1443. write_string(file_handler, 'id', self.name)
  1444. write_color(file_handler, 'ambient', self.ambient)
  1445. write_color(file_handler, 'diffuse', self.diffuse)
  1446. write_color(file_handler, 'specular', self.specular)
  1447. write_color(file_handler, 'emissive', self.emissive)
  1448. write_float(file_handler, 'specularPower', self.specularPower)
  1449. write_float(file_handler, 'alpha', self.alpha)
  1450. write_bool(file_handler, 'backFaceCulling', self.backFaceCulling)
  1451. if self.numOfUsers == 1:
  1452. write_bool(file_handler, 'checkReadyOnlyOnce', True)
  1453. for texSlot in self.textures:
  1454. texSlot.to_scene_file(file_handler)
  1455. file_handler.write('}')
  1456. #===============================================================================
  1457. class StdMaterial(Material):
  1458. def __init__(self, material_slot, exporter, mesh):
  1459. super().__init__()
  1460. self.name = Main.nameSpace + '.' + material_slot.name
  1461. Main.log('processing begun of Standard material: ' + material_slot.name, 2)
  1462. # a material slot is not a reference to an actual material; need to look up
  1463. material = material_slot.material
  1464. self.ambient = material.ambient * material.diffuse_color
  1465. self.diffuse = material.diffuse_intensity * material.diffuse_color
  1466. self.specular = material.specular_intensity * material.specular_color
  1467. self.emissive = material.emit * material.diffuse_color
  1468. self.specularPower = material.specular_hardness
  1469. self.alpha = material.alpha
  1470. self.backFaceCulling = material.game_settings.use_backface_culling
  1471. textures = [mtex for mtex in material.texture_slots if mtex and mtex.texture]
  1472. for mtex in textures:
  1473. # test should be un-neccessary, since should be a BakedMaterial; just for completeness
  1474. if (mtex.texture.type != 'IMAGE'):
  1475. continue
  1476. elif not mtex.texture.image:
  1477. Main.warn('Material has un-assigned image texture: "' + mtex.name + '" ignored', 3)
  1478. continue
  1479. elif len(mesh.data.uv_textures) == 0:
  1480. Main.warn('Mesh has no UV maps, material: "' + mtex.name + '" ignored', 3)
  1481. continue
  1482. if mtex.use_map_diffuse or mtex.use_map_color_diffuse:
  1483. if mtex.texture_coords == 'REFLECTION':
  1484. Main.log('Reflection texture found', 2)
  1485. self.textures.append(Texture('reflectionTexture', mtex.diffuse_color_factor, mtex, mesh, exporter))
  1486. else:
  1487. Main.log('Diffuse texture found', 2)
  1488. self.textures.append(Texture('diffuseTexture', mtex.diffuse_color_factor, mtex, mesh, exporter))
  1489. if mtex.use_map_ambient:
  1490. Main.log('Ambient texture found', 2)
  1491. self.textures.append(Texture('ambientTexture', mtex.ambient_factor, mtex, mesh, exporter))
  1492. if mtex.use_map_alpha:
  1493. Main.log('Opacity texture found', 2)
  1494. self.textures.append(Texture('opacityTexture', mtex.alpha_factor, mtex, mesh, exporter))
  1495. if mtex.use_map_emit:
  1496. Main.log('Emissive texture found', 2)
  1497. self.textures.append(Texture('emissiveTexture', mtex.emit_factor, mtex, mesh, exporter))
  1498. if mtex.use_map_normal:
  1499. Main.log('Bump texture found', 2)
  1500. self.textures.append(Texture('bumpTexture', 1.0 / mtex.normal_factor, mtex, mesh, exporter))
  1501. if mtex.use_map_color_spec:
  1502. Main.log('Specular texture found', 2)
  1503. self.textures.append(Texture('specularTexture', mtex.specular_color_factor, mtex, mesh, exporter))
  1504. #===============================================================================
  1505. class BakedMaterial(Material):
  1506. def __init__(self, exporter, mesh, recipe):
  1507. super().__init__()
  1508. self.name = Main.nameSpace + '.' + mesh.name
  1509. Main.log('processing begun of baked material: ' + mesh.name, 2)
  1510. # any baking already took in the values. Do not want to apply them again, but want shadows to show.
  1511. # These are the default values from StandardMaterials
  1512. self.ambient = mathutils.Color((0, 0, 0))
  1513. self.diffuse = mathutils.Color((0.8, 0.8, 0.8)) # needed for shadows, but not change anything else
  1514. self.specular = mathutils.Color((1, 1, 1))
  1515. self.emissive = mathutils.Color((0, 0, 0))
  1516. self.specularPower = 64
  1517. self.alpha = 1.0
  1518. self.backFaceCulling = recipe.backFaceCulling
  1519. # texture is baked from selected mesh(es), need to insure this mesh is only one selected
  1520. bpy.ops.object.select_all(action='DESELECT')
  1521. mesh.select = True
  1522. # store setting to restore
  1523. engine = exporter.scene.render.engine
  1524. # mode_set's only work when there is an active object
  1525. exporter.scene.objects.active = mesh
  1526. # you need UV on a mesh in order to bake image. This is not reqd for procedural textures, so may not exist
  1527. # need to look if it might already be created, as for a mesh with multi-materials
  1528. uv = None
  1529. for uvMap in mesh.data.uv_textures:
  1530. if uvMap.name == 'BakingUV':
  1531. uv = uvMap
  1532. break
  1533. if uv == None:
  1534. mesh.data.uv_textures.new('BakingUV')
  1535. uv = mesh.data.uv_textures['BakingUV']
  1536. uv.active = True
  1537. uv.active_render = True
  1538. # UV unwrap operates on mesh in only edit mode
  1539. # select all verticies of mesh, since smart_project works only with selected verticies
  1540. bpy.ops.object.mode_set(mode='EDIT')
  1541. bpy.ops.mesh.select_all(action='SELECT')
  1542. bpy.ops.uv.smart_project(angle_limit = 66.0, island_margin = 0.0, user_area_weight = 1.0, use_aspect = True)
  1543. # create a temporary image & link it to the UV/Image Editor so bake_image works
  1544. bpy.data.images.new(name = mesh.name + '_BJS_BAKE', width = recipe.bakeSize, height = recipe.bakeSize, alpha = False, float_buffer = False)
  1545. image = bpy.data.images[mesh.name + '_BJS_BAKE']
  1546. image.file_format = 'JPEG'
  1547. image.mapping = 'UV' # default value
  1548. image_settings = exporter.scene.render.image_settings
  1549. image_settings.file_format = 'JPEG'
  1550. image_settings.quality = recipe.bakeQuality # for lossy compression formats
  1551. # image_settings.compression = 100 # Amount of time to determine best compression: 0 = no compression with fast file output, 100 = maximum lossless compression with slow file output
  1552. # now go thru all the textures that need to be baked
  1553. if recipe.diffuseBaking:
  1554. self.bake('diffuseTexture', 'DIFFUSE_COLOR', 'TEXTURE', image, mesh, exporter, recipe)
  1555. if recipe.ambientBaking:
  1556. self.bake('ambientTexture', 'AO', 'AO', image, mesh, exporter, recipe)
  1557. if recipe.opacityBaking: # no eqivalent found for cycles
  1558. self.bake('opacityTexture', None, 'ALPHA', image, mesh, exporter, recipe)
  1559. if recipe.reflectionBaking:
  1560. self.bake('reflectionTexture', 'REFLECTION', 'MIRROR_COLOR', image, mesh, exporter, recipe)
  1561. if recipe.emissiveBaking:
  1562. self.bake('emissiveTexture', 'EMIT', 'EMIT', image, mesh, exporter, recipe)
  1563. if recipe.bumpBaking:
  1564. self.bake('bumpTexture', 'NORMAL', 'NORMALS', image, mesh, exporter, recipe)
  1565. if recipe.specularBaking:
  1566. self.bake('specularTexture', 'SPECULAR', 'SPEC_COLOR', image, mesh, exporter, recipe)
  1567. # Toggle vertex selection & mode, if setting changed their value
  1568. bpy.ops.mesh.select_all(action='TOGGLE') # still in edit mode toggle select back to previous
  1569. bpy.ops.object.mode_set(toggle=True) # change back to Object
  1570. bpy.ops.object.select_all(action='TOGGLE') # change scene selection back, not seeming to work
  1571. exporter.scene.render.engine = engine
  1572. # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  1573. def bake(self, bjs_type, cycles_type, internal_type, image, mesh, exporter, recipe):
  1574. if recipe.cyclesRender:
  1575. if cycles_type is None:
  1576. return
  1577. self.bakeCycles(cycles_type, image, recipe.nodeTrees)
  1578. else:
  1579. self.bakeInternal(internal_type, image)
  1580. self.textures.append(Texture(bjs_type, 1.0, image, mesh, exporter))
  1581. # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  1582. def bakeInternal(self, bake_type, image):
  1583. Main.log('Internal baking texture, type: ' + bake_type + ', mapped using: BakingUV', 3)
  1584. image.filepath = self.name + '_' + bake_type + '.jpg'
  1585. scene = bpy.context.scene
  1586. scene.render.engine = 'BLENDER_RENDER'
  1587. scene.render.bake_type = bake_type
  1588. # assign the image to the UV Editor, which does not have to shown
  1589. bpy.data.screens['UV Editing'].areas[1].spaces[0].image = image
  1590. renderer = scene.render
  1591. renderer.use_bake_selected_to_active = False
  1592. renderer.use_bake_to_vertex_color = False
  1593. renderer.use_bake_clear = True
  1594. renderer.bake_quad_split = 'AUTO'
  1595. renderer.bake_margin = 5
  1596. renderer.use_file_extension = True
  1597. renderer.use_bake_normalize = True
  1598. renderer.use_bake_antialiasing = True
  1599. bpy.ops.object.bake_image()
  1600. # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  1601. def bakeCycles(self, bake_type, image, nodeTrees):
  1602. Main.log('Cycles baking texture, type: ' + bake_type + ', mapped using: BakingUV', 3)
  1603. image.filepath = self.name + '_' + bake_type + '.jpg'
  1604. scene = bpy.context.scene
  1605. scene.render.engine = 'CYCLES'
  1606. # create an unlinked temporary node to bake to for each material
  1607. for tree in nodeTrees:
  1608. bakeNode = tree.nodes.new(type='ShaderNodeTexImage')
  1609. bakeNode.image = image
  1610. bakeNode.select = True
  1611. tree.nodes.active = bakeNode
  1612. bpy.ops.object.bake(type = bake_type, use_clear = True, margin = 5, use_selected_to_active = False)
  1613. for tree in nodeTrees:
  1614. tree.nodes.remove(tree.nodes.active)
  1615. # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  1616. @staticmethod
  1617. def meshBakingClean(mesh):
  1618. for uvMap in mesh.data.uv_textures:
  1619. if uvMap.name == 'BakingUV':
  1620. mesh.data.uv_textures.remove(uvMap)
  1621. break
  1622. # remove an image if it was baked
  1623. for image in bpy.data.images:
  1624. if image.name == mesh.name + '_BJS_BAKE':
  1625. image.user_clear() # cannot remove image unless 0 references
  1626. bpy.data.images.remove(image)
  1627. break
  1628. #===============================================================================
  1629. class Animation:
  1630. def __init__(self, dataType, framePerSecond, loopBehavior, name, propertyInBabylon):
  1631. self.dataType = dataType
  1632. self.framePerSecond = framePerSecond
  1633. self.loopBehavior = loopBehavior
  1634. self.name = name
  1635. self.propertyInBabylon = propertyInBabylon
  1636. #keys
  1637. self.frames = []
  1638. self.values = [] # vector3 for ANIMATIONTYPE_VECTOR3 & matrices for ANIMATIONTYPE_MATRIX
  1639. # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  1640. # for auto animate
  1641. def get_first_frame(self):
  1642. return self.frames[0] if len(self.frames) > 0 else -1
  1643. # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  1644. # for auto animate
  1645. def get_last_frame(self):
  1646. return self.frames[len(self.frames) - 1] if len(self.frames) > 0 else -1
  1647. # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  1648. def to_scene_file(self, file_handler):
  1649. file_handler.write('{')
  1650. write_int(file_handler, 'dataType', self.dataType, True)
  1651. write_int(file_handler, 'framePerSecond', self.framePerSecond)
  1652. file_handler.write(',"keys":[')
  1653. first = True
  1654. for frame_idx in range(len(self.frames)):
  1655. if first != True:
  1656. file_handler.write(',')
  1657. first = False
  1658. file_handler.write('{')
  1659. write_int(file_handler, 'frame', self.frames[frame_idx], True)
  1660. value_idx = self.values[frame_idx]
  1661. if self.dataType == ANIMATIONTYPE_MATRIX:
  1662. write_matrix4(file_handler, 'values', value_idx)
  1663. elif self.dataType == ANIMATIONTYPE_QUATERNION:
  1664. write_quaternion(file_handler, 'values', value_idx)
  1665. else:
  1666. write_vector(file_handler, 'values', value_idx)
  1667. file_handler.write('}')
  1668. file_handler.write(']') # close keys
  1669. # put this at the end to make less crazy looking ]}]]]}}}}}}}]]]],
  1670. # since animation is also at the end of the bone, mesh, camera, or light
  1671. write_int(file_handler, 'loopBehavior', self.loopBehavior)
  1672. write_string(file_handler, 'name', self.name)
  1673. write_string(file_handler, 'property', self.propertyInBabylon)
  1674. file_handler.write('}')
  1675. #===============================================================================
  1676. class VectorAnimation(Animation):
  1677. def __init__(self, object, attrInBlender, propertyInBabylon, mult, xOffset = 0):
  1678. super().__init__(ANIMATIONTYPE_VECTOR3, 30, ANIMATIONLOOPMODE_CYCLE, propertyInBabylon + ' animation', propertyInBabylon)
  1679. # capture built up from fcurves
  1680. frames = dict()
  1681. for fcurve in object.animation_data.action.fcurves:
  1682. if fcurve.data_path == attrInBlender:
  1683. for key in fcurve.keyframe_points:
  1684. frame = key.co.x
  1685. frames[frame] = 1
  1686. #for each frame (next step ==> set for key frames)
  1687. for Frame in sorted(frames):
  1688. self.frames.append(Frame)
  1689. bpy.context.scene.frame_set(int(Frame + bpy.context.scene.frame_start))
  1690. self.values.append(scale_vector(getattr(object, attrInBlender), mult, xOffset))
  1691. #===============================================================================
  1692. class QuaternionAnimation(Animation):
  1693. def __init__(self, object, attrInBlender, propertyInBabylon, mult, xOffset = 0):
  1694. super().__init__(ANIMATIONTYPE_QUATERNION, 30, ANIMATIONLOOPMODE_CYCLE, propertyInBabylon + ' animation', propertyInBabylon)
  1695. # capture built up from fcurves
  1696. frames = dict()
  1697. for fcurve in object.animation_data.action.fcurves:
  1698. if fcurve.data_path == attrInBlender:
  1699. for key in fcurve.keyframe_points:
  1700. frame = key.co.x
  1701. frames[frame] = 1
  1702. #for each frame (next step ==> set for key frames)
  1703. for Frame in sorted(frames):
  1704. self.frames.append(Frame)
  1705. bpy.context.scene.frame_set(int(Frame + bpy.context.scene.frame_start))
  1706. self.values.append(post_rotate_quaternion(getattr(object, attrInBlender), xOffset))
  1707. #===============================================================================
  1708. class QuaternionToEulerAnimation(Animation):
  1709. def __init__(self, object, attrInBlender, propertyInBabylon, mult, xOffset = 0):
  1710. super().__init__(ANIMATIONTYPE_VECTOR3, 30, ANIMATIONLOOPMODE_CYCLE, propertyInBabylon + ' animation', propertyInBabylon)
  1711. # capture built up from fcurves
  1712. frames = dict()
  1713. for fcurve in object.animation_data.action.fcurves:
  1714. if fcurve.data_path == attrInBlender:
  1715. for key in fcurve.keyframe_points:
  1716. frame = key.co.x
  1717. frames[frame] = 1
  1718. #for each frame (next step ==> set for key frames)
  1719. for Frame in sorted(frames):
  1720. self.frames.append(Frame)
  1721. bpy.context.scene.frame_set(int(Frame + bpy.context.scene.frame_start))
  1722. quat = getattr(object, attrInBlender)
  1723. eul = quat.to_euler("XYZ")
  1724. self.values.append(scale_vector(eul, mult, xOffset))
  1725. #===============================================================================
  1726. # module level formatting methods, called from multiple classes
  1727. #===============================================================================
  1728. def legal_js_identifier(input):
  1729. out = ''
  1730. prefix = ''
  1731. for char in input:
  1732. if len(out) == 0:
  1733. if char in '0123456789':
  1734. # cannot take the chance that leading numbers being chopped of cause name conflicts, e.g (01.R & 02.R)
  1735. prefix += char
  1736. continue
  1737. elif char.upper() not in 'ABCDEFGHIJKLMNOPQRSTUVWXYZ':
  1738. continue
  1739. legal = char if char.upper() in 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_' else '_'
  1740. out += legal
  1741. if len(prefix) > 0:
  1742. out += '_' + prefix
  1743. return out
  1744. def format_f(num):
  1745. s = MAX_FLOAT_PRECISION % num # rounds to N decimal places while changing to string
  1746. s = s.rstrip('0') # ignore trailing zeroes
  1747. s = s.rstrip('.') # ignore trailing .
  1748. return '0' if s == '-0' else s
  1749. def format_matrix4(matrix):
  1750. tempMatrix = matrix.copy()
  1751. tempMatrix.transpose()
  1752. ret = ''
  1753. first = True
  1754. for vect in tempMatrix:
  1755. if (first != True):
  1756. ret +=','
  1757. first = False;
  1758. ret += format_f(vect[0]) + ',' + format_f(vect[1]) + ',' + format_f(vect[2]) + ',' + format_f(vect[3])
  1759. return ret
  1760. def format_array3(array):
  1761. return format_f(array[0]) + ',' + format_f(array[1]) + ',' + format_f(array[2])
  1762. def format_array(array, max_per_line = MAX_VERTEX_ELEMENTS, indent = ''):
  1763. ret = ''
  1764. first = True
  1765. nOnLine = 0
  1766. for element in array:
  1767. if (first != True):
  1768. ret +=','
  1769. first = False;
  1770. ret += format_f(element)
  1771. nOnLine += 1
  1772. if nOnLine >= max_per_line:
  1773. ret += '\n' + indent
  1774. nOnLine = 0
  1775. return ret
  1776. def format_color(color):
  1777. return format_f(color.r) + ',' + format_f(color.g) + ',' + format_f(color.b)
  1778. def format_vector(vector):
  1779. return format_f(vector.x) + ',' + format_f(vector.z) + ',' + format_f(vector.y)
  1780. def format_vector_array(vectorArray, max_per_line = MAX_VERTEX_ELEMENTS, indent = ''):
  1781. ret = ''
  1782. first = True
  1783. nOnLine = 0
  1784. for vector in vectorArray:
  1785. if (first != True):
  1786. ret +=','
  1787. first = False;
  1788. ret += format_vector(vector)
  1789. nOnLine += 3
  1790. if nOnLine >= max_per_line:
  1791. ret += '\n' + indent
  1792. nOnLine = 0
  1793. return ret
  1794. def format_quaternion(quaternion):
  1795. return format_f(quaternion.x) + ',' + format_f(quaternion.z) + ',' + format_f(quaternion.y) + ',' + format_f(-quaternion.w)
  1796. def format_int(int):
  1797. candidate = str(int) # when int string of an int
  1798. if '.' in candidate:
  1799. return format_f(math.floor(int)) # format_f removes un-neccessary precision
  1800. else:
  1801. return candidate
  1802. def format_bool(bool):
  1803. if bool:
  1804. return 'true'
  1805. else:
  1806. return 'false'
  1807. def scale_vector(vector, mult, xOffset = 0):
  1808. ret = vector.copy()
  1809. ret.x *= mult
  1810. ret.x += xOffset
  1811. ret.z *= mult
  1812. ret.y *= mult
  1813. return ret
  1814. def same_vertex(vertA, vertB):
  1815. return vertA.x == vertB.x and vertA.y == vertB.y and vertA.z == vertB.z
  1816. #===============================================================================
  1817. # module level methods for writing JSON (.babylon) files
  1818. #===============================================================================
  1819. def write_matrix4(file_handler, name, matrix):
  1820. file_handler.write(',"' + name + '":[' + format_matrix4(matrix) + ']')
  1821. def write_array(file_handler, name, array):
  1822. file_handler.write('\n,"' + name + '":[' + format_array(array) + ']')
  1823. def write_array3(file_handler, name, array):
  1824. file_handler.write(',"' + name + '":[' + format_array3(array) + ']')
  1825. def write_color(file_handler, name, color):
  1826. file_handler.write(',"' + name + '":[' + format_color(color) + ']')
  1827. def write_vector(file_handler, name, vector):
  1828. file_handler.write(',"' + name + '":[' + format_vector(vector) + ']')
  1829. def write_vector_array(file_handler, name, vectorArray):
  1830. file_handler.write('\n,"' + name + '":[' + format_vector_array(vectorArray) + ']')
  1831. def write_quaternion(file_handler, name, quaternion):
  1832. file_handler.write(',"' + name +'":[' + format_quaternion(quaternion) + ']')
  1833. def write_string(file_handler, name, string, noComma = False):
  1834. if noComma == False:
  1835. file_handler.write(',')
  1836. file_handler.write('"' + name + '":"' + string + '"')
  1837. def write_float(file_handler, name, float):
  1838. file_handler.write(',"' + name + '":' + format_f(float))
  1839. def write_int(file_handler, name, int, noComma = False):
  1840. if noComma == False:
  1841. file_handler.write(',')
  1842. file_handler.write('"' + name + '":' + format_int(int))
  1843. def write_bool(file_handler, name, bool, noComma = False):
  1844. if noComma == False:
  1845. file_handler.write(',')
  1846. file_handler.write('"' + name + '":' + format_bool(bool))
  1847. #===============================================================================
  1848. # custom properties definition and display
  1849. #===============================================================================
  1850. bpy.types.Mesh.autoAnimate = bpy.props.BoolProperty(
  1851. name='Auto launch animations',
  1852. description='',
  1853. default = False
  1854. )
  1855. bpy.types.Mesh.useFlatShading = bpy.props.BoolProperty(
  1856. name='Use Flat Shading',
  1857. description='',
  1858. default = False
  1859. )
  1860. bpy.types.Mesh.checkCollisions = bpy.props.BoolProperty(
  1861. name='Check Collisions',
  1862. description='Indicates mesh should be checked that it does not run into anything.',
  1863. default = False
  1864. )
  1865. bpy.types.Mesh.castShadows = bpy.props.BoolProperty(
  1866. name='Cast Shadows',
  1867. description='',
  1868. default = False
  1869. )
  1870. bpy.types.Mesh.receiveShadows = bpy.props.BoolProperty(
  1871. name='Receive Shadows',
  1872. description='',
  1873. default = False
  1874. )
  1875. bpy.types.Mesh.bakeSize = bpy.props.IntProperty(
  1876. name='Texture Size',
  1877. description='',
  1878. default = 1024
  1879. )
  1880. bpy.types.Mesh.bakeQuality = bpy.props.IntProperty(
  1881. name='Quality 1-100',
  1882. description='The trade-off between Quality - File size(100 highest quality)',
  1883. default = 50
  1884. )
  1885. bpy.types.Mesh.freezeWorldMatrix = bpy.props.BoolProperty(
  1886. name='Freeze World Matrix',
  1887. description='Indicate the position, rotation, & scale do not change for performance reasons',
  1888. default = False
  1889. )
  1890. bpy.types.Mesh.attachedSound = bpy.props.StringProperty(
  1891. name='Sound',
  1892. description='',
  1893. default = ''
  1894. )
  1895. bpy.types.Mesh.loopSound = bpy.props.BoolProperty(
  1896. name='Loop sound',
  1897. description='',
  1898. default = True
  1899. )
  1900. bpy.types.Mesh.autoPlaySound = bpy.props.BoolProperty(
  1901. name='Auto play sound',
  1902. description='',
  1903. default = True
  1904. )
  1905. bpy.types.Mesh.maxSoundDistance = bpy.props.FloatProperty(
  1906. name='Max sound distance',
  1907. description='',
  1908. default = 100
  1909. )
  1910. #===============================================================================
  1911. bpy.types.Camera.autoAnimate = bpy.props.BoolProperty(
  1912. name='Auto launch animations',
  1913. description='',
  1914. default = False
  1915. )
  1916. bpy.types.Camera.CameraType = bpy.props.EnumProperty(
  1917. name='Camera Type',
  1918. description='',
  1919. # ONLY Append, or existing .blends will have their camera changed
  1920. items = (
  1921. (V_JOYSTICKS_CAM , 'Virtual Joysticks' , 'Use Virtual Joysticks Camera'),
  1922. (TOUCH_CAM , 'Touch' , 'Use Touch Camera'),
  1923. (GAMEPAD_CAM , 'Gamepad' , 'Use Gamepad Camera'),
  1924. (FREE_CAM , 'Free' , 'Use Free Camera'),
  1925. (FOLLOW_CAM , 'Follow' , 'Use Follow Camera'),
  1926. (DEV_ORIENT_CAM , 'Device Orientation' , 'Use Device Orientation Camera'),
  1927. (ARC_ROTATE_CAM , 'Arc Rotate' , 'Use Arc Rotate Camera'),
  1928. (VR_DEV_ORIENT_FREE_CAM , 'VR Dev Orientation Free' , 'Use VR Dev Orientation Free Camera'),
  1929. (WEB_VR_FREE_CAM , 'Web VR Free' , 'Use Web VR Free Camera')
  1930. ),
  1931. default = FREE_CAM
  1932. )
  1933. bpy.types.Camera.checkCollisions = bpy.props.BoolProperty(
  1934. name='Check Collisions',
  1935. description='',
  1936. default = False
  1937. )
  1938. bpy.types.Camera.applyGravity = bpy.props.BoolProperty(
  1939. name='Apply Gravity',
  1940. description='',
  1941. default = False
  1942. )
  1943. bpy.types.Camera.ellipsoid = bpy.props.FloatVectorProperty(
  1944. name='Ellipsoid',
  1945. description='',
  1946. default = mathutils.Vector((0.2, 0.9, 0.2))
  1947. )
  1948. bpy.types.Camera.Camera3DRig = bpy.props.EnumProperty(
  1949. name='Rig',
  1950. description='',
  1951. items = (
  1952. (RIG_MODE_NONE , 'None' , 'No 3D effects'),
  1953. (RIG_MODE_STEREOSCOPIC_ANAGLYPH , 'Anaaglph' , 'Stereoscopic Anagylph'),
  1954. (RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL , 'side-by-side Parallel' , 'Stereoscopic side-by-side parallel'),
  1955. (RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED, 'side-by-side crosseyed', 'Stereoscopic side-by-side crosseyed'),
  1956. (RIG_MODE_STEREOSCOPIC_OVERUNDER , 'over-under' , 'Stereoscopic over-under'),
  1957. (RIG_MODE_VR , 'VR distortion' , 'Use Web VR Free Camera')
  1958. ),
  1959. default = RIG_MODE_NONE
  1960. )
  1961. bpy.types.Camera.interaxialDistance = bpy.props.FloatProperty(
  1962. name='Interaxial Distance',
  1963. description='Distance between cameras. Used by all but VR 3D rigs.',
  1964. default = 0.0637
  1965. )
  1966. #===============================================================================
  1967. bpy.types.Lamp.autoAnimate = bpy.props.BoolProperty(
  1968. name='Auto launch animations',
  1969. description='',
  1970. default = False
  1971. )
  1972. bpy.types.Lamp.shadowMap = bpy.props.EnumProperty(
  1973. name='Shadow Map',
  1974. description='',
  1975. items = ((NO_SHADOWS , 'None' , 'No Shadow Maps'),
  1976. (STD_SHADOWS , 'Standard' , 'Use Standard Shadow Maps'),
  1977. (POISSON_SHADOWS , 'Poisson' , 'Use Poisson Sampling'),
  1978. (VARIANCE_SHADOWS , 'Variance' , 'Use Variance Shadow Maps'),
  1979. (BLUR_VARIANCE_SHADOWS, 'Blur Variance', 'Use Blur Variance Shadow Maps')
  1980. ),
  1981. default = NO_SHADOWS
  1982. )
  1983. bpy.types.Lamp.shadowMapSize = bpy.props.IntProperty(
  1984. name='Shadow Map Size',
  1985. description='',
  1986. default = 512
  1987. )
  1988. bpy.types.Lamp.shadowBias = bpy.props.FloatProperty(
  1989. name='Shadow Bias',
  1990. description='',
  1991. default = 0.00005
  1992. )
  1993. bpy.types.Lamp.shadowBlurScale = bpy.props.IntProperty(
  1994. name='Blur Scale',
  1995. description='',
  1996. default = 2
  1997. )
  1998. bpy.types.Lamp.shadowBlurBoxOffset = bpy.props.IntProperty(
  1999. name='Blur Box Offset',
  2000. description='',
  2001. default = 0
  2002. )
  2003. class ObjectPanel(bpy.types.Panel):
  2004. bl_label = 'Babylon.js'
  2005. bl_space_type = 'PROPERTIES'
  2006. bl_region_type = 'WINDOW'
  2007. bl_context = 'data'
  2008. def draw(self, context):
  2009. ob = context.object
  2010. if not ob or not ob.data:
  2011. return
  2012. layout = self.layout
  2013. isMesh = isinstance(ob.data, bpy.types.Mesh)
  2014. isCamera = isinstance(ob.data, bpy.types.Camera)
  2015. isLight = isinstance(ob.data, bpy.types.Lamp)
  2016. if isMesh:
  2017. layout.prop(ob.data, 'useFlatShading')
  2018. layout.prop(ob.data, 'checkCollisions')
  2019. layout.prop(ob.data, 'castShadows')
  2020. layout.prop(ob.data, 'receiveShadows')
  2021. layout.separator()
  2022. layout.prop(ob.data, 'autoAnimate')
  2023. box = layout.box()
  2024. box.label(text="Procedural Texture / Cycles Baking")
  2025. box.prop(ob.data, 'bakeSize')
  2026. box.prop(ob.data, 'bakeQuality')
  2027. layout.prop(ob.data, 'freezeWorldMatrix')
  2028. box = layout.box()
  2029. box.prop(ob.data, 'attachedSound')
  2030. box.prop(ob.data, 'autoPlaySound')
  2031. box.prop(ob.data, 'loopSound')
  2032. box.prop(ob.data, 'maxSoundDistance')
  2033. elif isCamera:
  2034. layout.prop(ob.data, 'CameraType')
  2035. layout.prop(ob.data, 'checkCollisions')
  2036. layout.prop(ob.data, 'applyGravity')
  2037. layout.prop(ob.data, 'ellipsoid')
  2038. box = layout.box()
  2039. box.label(text="3D Camera Rigs")
  2040. box.prop(ob.data, 'Camera3DRig')
  2041. box.prop(ob.data, 'interaxialDistance')
  2042. layout.prop(ob.data, 'autoAnimate')
  2043. elif isLight:
  2044. layout.prop(ob.data, 'shadowMap')
  2045. layout.prop(ob.data, 'shadowMapSize')
  2046. layout.prop(ob.data, 'shadowBias')
  2047. box = layout.box()
  2048. box.label(text="Blur Variance Shadows")
  2049. box.prop(ob.data, 'shadowBlurScale')
  2050. box.prop(ob.data, 'shadowBlurBoxOffset')
  2051. layout.prop(ob.data, 'autoAnimate')