io_export_babylon.py 121 KB

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