io_export_babylon.py 113 KB

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