io_export_babylon.py 122 KB

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