io_export_babylon.py 119 KB

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