io_export_babylon.py 120 KB

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