io_export_babylon.py 121 KB

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