io_export_babylon.py 101 KB

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