PageRenderTime 73ms CodeModel.GetById 19ms RepoModel.GetById 0ms app.codeStats 1ms

/io_export_ogreDotScene.py

https://bitbucket.org/alopex/blender2ogre
Python | 7730 lines | 7702 code | 2 blank | 26 comment | 55 complexity | e13047763a51daf0fc595ae55be523bc MD5 | raw file
Possible License(s): LGPL-2.1

Large files files are truncated, but you can click here to view the full file

  1. # Copyright (C) 2010 Brett Hartshorn
  2. #
  3. # This library is free software; you can redistribute it and/or
  4. # modify it under the terms of the GNU Lesser General Public
  5. # License as published by the Free Software Foundation; either
  6. # version 2.1 of the License, or (at your option) any later version.
  7. #
  8. # This library is distributed in the hope that it will be useful,
  9. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  11. # Lesser General Public License for more details.
  12. #
  13. # You should have received a copy of the GNU Lesser General Public
  14. # License along with this library; if not, write to the Free Software
  15. # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
  16. VERSION = '0.6.0'
  17. '''
  18. CHANGELOG
  19. 0.6.0
  20. * patched to work with 2.66.
  21. 0.5.9
  22. * apply patch from Thomas for Blender 2.6x support
  23. 0.5.8
  24. * Clean all names that will be used as filenames on disk. Adjust all places
  25. that use these names for refs instead of ob.name/ob.data.name. Replaced chars
  26. are \, /, :, *, ?, ", <, >, | and spaces. Tested on work with ogre
  27. material, mesh and skeleton writing/refs inside the files and txml refs.
  28. Shows warning at final report if we had to resort to the renaming so user
  29. can possibly rename the object.
  30. * Added silent auto update checks if blender2ogre was installed using
  31. the .exe installer. This will keep people up to date when new versions are out.
  32. * Fix tracker issue 48: Needs to check if outputting to /tmp or
  33. ~/.wine/drive_c/tmp on Linux. Thanks to vax456 for providing the patch,
  34. added him to contributors. Preview mesh's are now placed under /tmp
  35. on Linux systems if the OgreMeshy executable ends with .exe
  36. * Fix tracker issue 46: add operationtype to <submesh>
  37. * Implement a modal dialog that reports if material names have invalid
  38. characters and cant be saved on disk. This small popup will show until
  39. user presses left or right mouse (anywhere).
  40. * Fix tracker issue 44: XML Attributes not properly escaped in .scene file
  41. * Implemented reading OgreXmlConverter path from windows registry.
  42. The .exe installer will ship with certain tools so we can stop guessing
  43. and making the user install tools separately and setting up paths.
  44. * Fix bug that .mesh files were not generated while doing a .txml export.
  45. This was result of the late 2.63 mods that forgot to update object
  46. facecount before determining if mesh should be exported.
  47. * Fix bug that changed settings in the export dialog were forgotten when you
  48. re-exported without closing blender. Now settings should persist always
  49. from the last export. They are also stored to disk so the same settings
  50. are in use when if you restart Blender.
  51. * Fix bug that once you did a export, the next time the export location was
  52. forgotten. Now on sequential exports, the last export path is remembered in
  53. the export dialog.
  54. * Remove all local:// from asset refs and make them relative in .txml export.
  55. Having relative refs is the best for local preview and importing the txml
  56. to existing scenes.
  57. * Make .material generate what version of this plugins was used to generate
  58. the material file. Will be helpful in production to catch things.
  59. Added pretty printing line endings so the raw .material data is easier to read.
  60. * Improve console logging for the export stages. Run Blender from
  61. cmd prompt to see this information.
  62. * Clean/fix documentation in code for future development
  63. * Add todo to code for future development
  64. * Restructure/move code for easier readability
  65. * Remove extra white spaces and convert tabs to space
  66. 0.5.7
  67. * Update to Blender 2.6.3.
  68. * Fixed xz-y Skeleton rotation (again)
  69. * Added additional Keyframe at the end of each animation to prevent
  70. ogre from interpolating back to the start
  71. * Added option to ignore non-deformable bones
  72. * Added option to export nla-strips independently from each other
  73. TODO
  74. * Remove this section and integrate below with code :)
  75. * Fix terrain collision offset bug
  76. * Add realtime transform (rotation is missing)
  77. * Fix camera rotated -90 ogre-dot-scene
  78. * Set description field for all pyRNA
  79. '''
  80. bl_info = {
  81. "name": "OGRE Exporter (.scene, .mesh, .skeleton) and RealXtend (.txml)",
  82. "author": "Brett, S.Rombauts, F00bar, Waruck, Mind Calamity, Mr.Magne, Jonne Nauha, vax456",
  83. "version": (0, 6, 0),
  84. "blender": (2, 6, 6),
  85. "location": "File > Export...",
  86. "description": "Export to Ogre xml and binary formats",
  87. "wiki_url": "http://code.google.com/p/blender2ogre/w/list",
  88. "tracker_url": "http://code.google.com/p/blender2ogre/issues/list",
  89. "category": "Import-Export"
  90. }
  91. ## Public API
  92. ## Search for "Public API" to find more
  93. UI_CLASSES = []
  94. def UI(cls):
  95. ''' Toggles the Ogre interface panels '''
  96. if cls not in UI_CLASSES:
  97. UI_CLASSES.append(cls)
  98. return cls
  99. def hide_user_interface():
  100. for cls in UI_CLASSES:
  101. bpy.utils.unregister_class( cls )
  102. def uid(ob):
  103. if ob.uid == 0:
  104. high = 0
  105. multires = 0
  106. for o in bpy.data.objects:
  107. if o.uid > high: high = o.uid
  108. if o.use_multires_lod: multires += 1
  109. high += 1 + (multires*10)
  110. if high < 100: high = 100 # start at 100
  111. ob.uid = high
  112. return ob.uid
  113. ## Imports
  114. import os, sys, time, array, ctypes, math
  115. try:
  116. # Inside blender
  117. import bpy, mathutils
  118. from bpy.props import *
  119. except ImportError:
  120. # If we end up here we are outside blender (compile optional C module)
  121. assert __name__ == '__main__'
  122. print('Trying to compile Rpython C-library')
  123. assert sys.version_info.major == 2 # rpython only works from Python2
  124. print('...searching for rpythonic...')
  125. sys.path.append('../rpythonic')
  126. import rpythonic
  127. rpythonic.set_pypy_root( '../pypy' )
  128. import pypy.rpython.lltypesystem.rffi as rffi
  129. from pypy.rlib import streamio
  130. rpy = rpythonic.RPython( 'blender2ogre' )
  131. @rpy.bind(
  132. path=str,
  133. facesAddr=int,
  134. facesSmoothAddr=int,
  135. facesMatAddr=int,
  136. vertsPosAddr=int,
  137. vertsNorAddr=int,
  138. numFaces=int,
  139. numVerts=int,
  140. materialNames=str, # [str] is too tricky to convert py-list to rpy-list
  141. )
  142. def dotmesh( path, facesAddr, facesSmoothAddr, facesMatAddr, vertsPosAddr, vertsNorAddr, numFaces, numVerts, materialNames ):
  143. print('PATH----------------', path)
  144. materials = []
  145. for matname in materialNames.split(';'):
  146. print( 'Material Name: %s' %matname )
  147. materials.append( matname )
  148. file = streamio.open_file_as_stream( path, 'w')
  149. faces = rffi.cast( rffi.UINTP, facesAddr ) # face vertex indices
  150. facesSmooth = rffi.cast( rffi.CCHARP, facesSmoothAddr )
  151. facesMat = rffi.cast( rffi.USHORTP, facesMatAddr )
  152. vertsPos = rffi.cast( rffi.FLOATP, vertsPosAddr )
  153. vertsNor = rffi.cast( rffi.FLOATP, vertsNorAddr )
  154. VB = [
  155. '<sharedgeometry>',
  156. '<vertexbuffer positions="true" normals="true">'
  157. ]
  158. fastlookup = {}
  159. ogre_vert_index = 0
  160. triangles = []
  161. for fidx in range( numFaces ):
  162. smooth = ord( facesSmooth[ fidx ] ) # ctypes.c_bool > char > int
  163. matidx = facesMat[ fidx ]
  164. i = fidx*4
  165. ai = faces[ i ]; bi = faces[ i+1 ]
  166. ci = faces[ i+2 ]; di = faces[ i+3 ]
  167. triangle = []
  168. for J in [ai, bi, ci]:
  169. i = J*3
  170. x = rffi.cast( rffi.DOUBLE, vertsPos[ i ] )
  171. y = rffi.cast( rffi.DOUBLE, vertsPos[ i+1 ] )
  172. z = rffi.cast( rffi.DOUBLE, vertsPos[ i+2 ] )
  173. pos = (x,y,z)
  174. #if smooth:
  175. x = rffi.cast( rffi.DOUBLE, vertsNor[ i ] )
  176. y = rffi.cast( rffi.DOUBLE, vertsNor[ i+1 ] )
  177. z = rffi.cast( rffi.DOUBLE, vertsNor[ i+2 ] )
  178. nor = (x,y,z)
  179. SIG = (pos,nor)#, matidx)
  180. skip = False
  181. if J in fastlookup:
  182. for otherSIG in fastlookup[ J ]:
  183. if SIG == otherSIG:
  184. triangle.append( fastlookup[J][otherSIG] )
  185. skip = True
  186. break
  187. if not skip:
  188. triangle.append( ogre_vert_index )
  189. fastlookup[ J ][ SIG ] = ogre_vert_index
  190. else:
  191. triangle.append( ogre_vert_index )
  192. fastlookup[ J ] = { SIG : ogre_vert_index }
  193. if skip: continue
  194. xml = [
  195. '<vertex>',
  196. '<position x="%s" y="%s" z="%s" />' %pos, # funny that tuple is valid here
  197. '<normal x="%s" y="%s" z="%s" />' %nor,
  198. '</vertex>'
  199. ]
  200. VB.append( '\n'.join(xml) )
  201. ogre_vert_index += 1
  202. triangles.append( triangle )
  203. VB.append( '</vertexbuffer>' )
  204. VB.append( '</sharedgeometry>' )
  205. file.write( '\n'.join(VB) )
  206. del VB # free memory
  207. SMS = ['<submeshes>']
  208. #for matidx, matname in ...:
  209. SM = [
  210. '<submesh usesharedvertices="true" use32bitindexes="true" material="%s" operationtype="triangle_list">' % 'somemat',
  211. '<faces count="%s">' %'100',
  212. ]
  213. for tri in triangles:
  214. #x,y,z = tri # rpython bug, when in a new 'block' need to unpack/repack tuple
  215. #s = '<face v1="%s" v2="%s" v3="%s" />' %(x,y,z)
  216. assert isinstance(tri,tuple) #and len(tri)==3 # this also works
  217. s = '<face v1="%s" v2="%s" v3="%s" />' %tri # but tuple is not valid here
  218. SM.append( s )
  219. SM.append( '</faces>' )
  220. SM.append( '</submesh>' )
  221. file.write( '\n'.join(SM) )
  222. file.close()
  223. rpy.cache(refresh=1)
  224. sys.exit('OK: module compiled and cached')
  225. ## More imports now that Blender is imported
  226. import hashlib, getpass, tempfile, configparser, subprocess, pickle
  227. from xml.sax.saxutils import XMLGenerator, quoteattr
  228. class CMesh(object):
  229. def __init__(self, data):
  230. self.numVerts = N = len( data.vertices )
  231. self.numFaces = Nfaces = len(data.tessfaces)
  232. self.vertex_positions = (ctypes.c_float * (N * 3))()
  233. data.vertices.foreach_get( 'co', self.vertex_positions )
  234. v = self.vertex_positions
  235. self.vertex_normals = (ctypes.c_float * (N * 3))()
  236. data.vertices.foreach_get( 'normal', self.vertex_normals )
  237. self.faces = (ctypes.c_uint * (Nfaces * 4))()
  238. data.tessfaces.foreach_get( 'vertices_raw', self.faces )
  239. self.faces_normals = (ctypes.c_float * (Nfaces * 3))()
  240. data.tessfaces.foreach_get( 'normal', self.faces_normals )
  241. self.faces_smooth = (ctypes.c_bool * Nfaces)()
  242. data.tessfaces.foreach_get( 'use_smooth', self.faces_smooth )
  243. self.faces_material_index = (ctypes.c_ushort * Nfaces)()
  244. data.tessfaces.foreach_get( 'material_index', self.faces_material_index )
  245. self.vertex_colors = []
  246. if len( data.vertex_colors ):
  247. vc = data.vertex_colors[0]
  248. n = len(vc.data)
  249. # no colors_raw !!?
  250. self.vcolors1 = (ctypes.c_float * (n * 3))() # face1
  251. vc.data.foreach_get( 'color1', self.vcolors1 )
  252. self.vertex_colors.append( self.vcolors1 )
  253. self.vcolors2 = (ctypes.c_float * (n * 3))() # face2
  254. vc.data.foreach_get( 'color2', self.vcolors2 )
  255. self.vertex_colors.append( self.vcolors2 )
  256. self.vcolors3 = (ctypes.c_float * (n * 3))() # face3
  257. vc.data.foreach_get( 'color3', self.vcolors3 )
  258. self.vertex_colors.append( self.vcolors3 )
  259. self.vcolors4 = (ctypes.c_float * (n * 3))() # face4
  260. vc.data.foreach_get( 'color4', self.vcolors4 )
  261. self.vertex_colors.append( self.vcolors4 )
  262. self.uv_textures = []
  263. if data.uv_textures.active:
  264. for layer in data.uv_textures:
  265. n = len(layer.data) * 8
  266. a = (ctypes.c_float * n)()
  267. layer.data.foreach_get( 'uv_raw', a ) # 4 faces
  268. self.uv_textures.append( a )
  269. def save( blenderobject, path ):
  270. cmesh = Mesh( blenderobject.data )
  271. start = time.time()
  272. dotmesh(
  273. path,
  274. ctypes.addressof( cmesh.faces ),
  275. ctypes.addressof( cmesh.faces_smooth ),
  276. ctypes.addressof( cmesh.faces_material_index ),
  277. ctypes.addressof( cmesh.vertex_positions ),
  278. ctypes.addressof( cmesh.vertex_normals ),
  279. cmesh.numFaces,
  280. cmesh.numVerts,
  281. )
  282. print('Mesh dumped in %s seconds' % (time.time()-start))
  283. ## Make sure we can import from same directory
  284. SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))
  285. if SCRIPT_DIR not in sys.path:
  286. sys.path.append( SCRIPT_DIR )
  287. ## Avatar
  288. bpy.types.Object.use_avatar = BoolProperty(
  289. name='enable avatar',
  290. description='enables EC_Avatar',
  291. default=False)
  292. bpy.types.Object.avatar_reference = StringProperty(
  293. name='avatar reference',
  294. description='sets avatar reference URL',
  295. maxlen=128,
  296. default='')
  297. BoolProperty( name='enable avatar', description='enables EC_Avatar', default=False) # todo: is this used?
  298. # Tundra IDs
  299. bpy.types.Object.uid = IntProperty(
  300. name="unique ID",
  301. description="unique ID for Tundra",
  302. default=0, min=0, max=2**14)
  303. # Rendering
  304. bpy.types.Object.use_draw_distance = BoolProperty(
  305. name='enable draw distance',
  306. description='use LOD draw distance',
  307. default=False)
  308. bpy.types.Object.draw_distance = FloatProperty(
  309. name='draw distance',
  310. description='distance at which to begin drawing object',
  311. default=0.0, min=0.0, max=10000.0)
  312. bpy.types.Object.cast_shadows = BoolProperty(
  313. name='cast shadows',
  314. description='cast shadows',
  315. default=False)
  316. bpy.types.Object.use_multires_lod = BoolProperty(
  317. name='Enable Multires LOD',
  318. description='enables multires LOD',
  319. default=False)
  320. bpy.types.Object.multires_lod_range = FloatProperty(
  321. name='multires LOD range',
  322. description='far distance at which multires is set to base level',
  323. default=30.0, min=0.0, max=10000.0)
  324. ## Physics
  325. _physics_modes = [
  326. ('NONE', 'NONE', 'no physics'),
  327. ('RIGID_BODY', 'RIGID_BODY', 'rigid body'),
  328. ('SOFT_BODY', 'SOFT_BODY', 'soft body'),
  329. ]
  330. _collision_modes = [
  331. ('NONE', 'NONE', 'no collision'),
  332. ('PRIMITIVE', 'PRIMITIVE', 'primitive collision type'),
  333. ('MESH', 'MESH', 'triangle-mesh or convex-hull collision type'),
  334. ('DECIMATED', 'DECIMATED', 'auto-decimated collision type'),
  335. ('COMPOUND', 'COMPOUND', 'children primitive compound collision type'),
  336. ('TERRAIN', 'TERRAIN', 'terrain (height map) collision type'),
  337. ]
  338. bpy.types.Object.physics_mode = EnumProperty(
  339. items = _physics_modes,
  340. name = 'physics mode',
  341. description='physics mode',
  342. default='NONE')
  343. bpy.types.Object.physics_friction = FloatProperty(
  344. name='Simple Friction',
  345. description='physics friction',
  346. default=0.1, min=0.0, max=1.0)
  347. bpy.types.Object.physics_bounce = FloatProperty(
  348. name='Simple Bounce',
  349. description='physics bounce',
  350. default=0.01, min=0.0, max=1.0)
  351. bpy.types.Object.collision_terrain_x_steps = IntProperty(
  352. name="Ogre Terrain: x samples",
  353. description="resolution in X of height map",
  354. default=64, min=4, max=8192)
  355. bpy.types.Object.collision_terrain_y_steps = IntProperty(
  356. name="Ogre Terrain: y samples",
  357. description="resolution in Y of height map",
  358. default=64, min=4, max=8192)
  359. bpy.types.Object.collision_mode = EnumProperty(
  360. items = _collision_modes,
  361. name = 'primary collision mode',
  362. description='collision mode',
  363. default='NONE')
  364. bpy.types.Object.subcollision = BoolProperty(
  365. name="collision compound",
  366. description="member of a collision compound",
  367. default=False)
  368. ## Sound
  369. bpy.types.Speaker.play_on_load = BoolProperty(
  370. name='play on load',
  371. default=False)
  372. bpy.types.Speaker.loop = BoolProperty(
  373. name='loop sound',
  374. default=False)
  375. bpy.types.Speaker.use_spatial = BoolProperty(
  376. name='3D spatial sound',
  377. default=True)
  378. ## ImageMagick
  379. _IMAGE_FORMATS = [
  380. ('NONE','NONE', 'do not convert image'),
  381. ('bmp', 'bmp', 'bitmap format'),
  382. ('jpg', 'jpg', 'jpeg format'),
  383. ('gif', 'gif', 'gif format'),
  384. ('png', 'png', 'png format'),
  385. ('tga', 'tga', 'targa format'),
  386. ('dds', 'dds', 'nvidia dds format'),
  387. ]
  388. bpy.types.Image.use_convert_format = BoolProperty(
  389. name='use convert format',
  390. default=False
  391. )
  392. bpy.types.Image.convert_format = EnumProperty(
  393. name='convert to format',
  394. description='converts to image format using imagemagick',
  395. items=_IMAGE_FORMATS,
  396. default='NONE')
  397. bpy.types.Image.jpeg_quality = IntProperty(
  398. name="jpeg quality",
  399. description="quality of jpeg",
  400. default=80, min=0, max=100)
  401. bpy.types.Image.use_color_quantize = BoolProperty(
  402. name='use color quantize',
  403. default=False)
  404. bpy.types.Image.use_color_quantize_dither = BoolProperty(
  405. name='use color quantize dither',
  406. default=True)
  407. bpy.types.Image.color_quantize = IntProperty(
  408. name="color quantize",
  409. description="reduce to N colors (requires ImageMagick)",
  410. default=32, min=2, max=256)
  411. bpy.types.Image.use_resize_half = BoolProperty(
  412. name='resize by 1/2',
  413. default=False)
  414. bpy.types.Image.use_resize_absolute = BoolProperty(
  415. name='force image resize',
  416. default=False)
  417. bpy.types.Image.resize_x = IntProperty(
  418. name='resize X',
  419. description='only if image is larger than defined, use ImageMagick to resize it down',
  420. default=256, min=2, max=4096)
  421. bpy.types.Image.resize_y = IntProperty(
  422. name='resize Y',
  423. description='only if image is larger than defined, use ImageMagick to resize it down',
  424. default=256, min=2, max=4096)
  425. # Materials
  426. bpy.types.Material.ogre_depth_write = BoolProperty(
  427. # Material.ogre_depth_write = AUTO|ON|OFF
  428. name='depth write',
  429. default=True)
  430. bpy.types.Material.ogre_depth_check = BoolProperty(
  431. # If depth-buffer checking is on, whenever a pixel is about to be written to
  432. # the frame buffer the depth buffer is checked to see if the pixel is in front
  433. # of all other pixels written at that point. If not, the pixel is not written.
  434. # If depth checking is off, pixels are written no matter what has been rendered before.
  435. name='depth check',
  436. default=True)
  437. bpy.types.Material.ogre_alpha_to_coverage = BoolProperty(
  438. # Sets whether this pass will use 'alpha to coverage', a way to multisample alpha
  439. # texture edges so they blend more seamlessly with the background. This facility
  440. # is typically only available on cards from around 2006 onwards, but it is safe to
  441. # enable it anyway - Ogre will just ignore it if the hardware does not support it.
  442. # The common use for alpha to coverage is foliage rendering and chain-link fence style textures.
  443. name='multisample alpha edges',
  444. default=False)
  445. bpy.types.Material.ogre_light_scissor = BoolProperty(
  446. # This option is usually only useful if this pass is an additive lighting pass, and is
  447. # at least the second one in the technique. Ie areas which are not affected by the current
  448. # light(s) will never need to be rendered. If there is more than one light being passed to
  449. # the pass, then the scissor is defined to be the rectangle which covers all lights in screen-space.
  450. # Directional lights are ignored since they are infinite. This option does not need to be specified
  451. # if you are using a standard additive shadow mode, i.e. SHADOWTYPE_STENCIL_ADDITIVE or
  452. # SHADOWTYPE_TEXTURE_ADDITIVE, since it is the default behaviour to use a scissor for each additive
  453. # shadow pass. However, if you're not using shadows, or you're using Integrated Texture Shadows
  454. # where passes are specified in a custom manner, then this could be of use to you.
  455. name='light scissor',
  456. default=False)
  457. bpy.types.Material.ogre_light_clip_planes = BoolProperty(
  458. name='light clip planes',
  459. default=False)
  460. bpy.types.Material.ogre_normalise_normals = BoolProperty(
  461. name='normalise normals',
  462. default=False,
  463. description="Scaling objects causes normals to also change magnitude, which can throw off your lighting calculations. By default, the SceneManager detects this and will automatically re-normalise normals for any scaled object, but this has a cost. If you'd prefer to control this manually, call SceneManager::setNormaliseNormalsOnScale(false) and then use this option on materials which are sensitive to normals being resized.")
  464. bpy.types.Material.ogre_lighting = BoolProperty(
  465. # Sets whether or not dynamic lighting is turned on for this pass or not. If lighting is turned off,
  466. # all objects rendered using the pass will be fully lit. This attribute has no effect if a vertex program is used.
  467. name='dynamic lighting',
  468. default=True)
  469. bpy.types.Material.ogre_colour_write = BoolProperty(
  470. # If colour writing is off no visible pixels are written to the screen during this pass. You might think
  471. # this is useless, but if you render with colour writing off, and with very minimal other settings,
  472. # you can use this pass to initialise the depth buffer before subsequently rendering other passes which
  473. # fill in the colour data. This can give you significant performance boosts on some newer cards, especially
  474. # when using complex fragment programs, because if the depth check fails then the fragment program is never run.
  475. name='color-write',
  476. default=True)
  477. bpy.types.Material.use_fixed_pipeline = BoolProperty(
  478. # Fixed pipeline is oldschool
  479. # todo: whats the meaning of this?
  480. name='fixed pipeline',
  481. default=True)
  482. bpy.types.Material.use_material_passes = BoolProperty(
  483. # hidden option - gets turned on by operator
  484. # todo: What is a hidden option, is this needed?
  485. name='use ogre extra material passes (layers)',
  486. default=False)
  487. bpy.types.Material.use_in_ogre_material_pass = BoolProperty(
  488. name='Layer Toggle',
  489. default=True)
  490. bpy.types.Material.use_ogre_advanced_options = BoolProperty(
  491. name='Show Advanced Options',
  492. default=False)
  493. bpy.types.Material.use_ogre_parent_material = BoolProperty(
  494. name='Use Script Inheritance',
  495. default=False)
  496. bpy.types.Material.ogre_parent_material = EnumProperty(
  497. name="Script Inheritence",
  498. description='ogre parent material class', #default='NONE',
  499. items=[])
  500. bpy.types.Material.ogre_polygon_mode = EnumProperty(
  501. name='faces draw type',
  502. description="ogre face draw mode",
  503. items=[ ('solid', 'solid', 'SOLID'),
  504. ('wireframe', 'wireframe', 'WIREFRAME'),
  505. ('points', 'points', 'POINTS') ],
  506. default='solid')
  507. bpy.types.Material.ogre_shading = EnumProperty(
  508. name='hardware shading',
  509. description="Sets the kind of shading which should be used for representing dynamic lighting for this pass.",
  510. items=[ ('flat', 'flat', 'FLAT'),
  511. ('gouraud', 'gouraud', 'GOURAUD'),
  512. ('phong', 'phong', 'PHONG') ],
  513. default='gouraud')
  514. bpy.types.Material.ogre_cull_hardware = EnumProperty(
  515. name='hardware culling',
  516. description="If the option 'cull_hardware clockwise' is set, all triangles whose vertices are viewed in clockwise order from the camera will be culled by the hardware.",
  517. items=[ ('clockwise', 'clockwise', 'CLOCKWISE'),
  518. ('anticlockwise', 'anticlockwise', 'COUNTER CLOCKWISE'),
  519. ('none', 'none', 'NONE') ],
  520. default='clockwise')
  521. bpy.types.Material.ogre_transparent_sorting = EnumProperty(
  522. name='transparent sorting',
  523. description="By default all transparent materials are sorted such that renderables furthest away from the camera are rendered first. This is usually the desired behaviour but in certain cases this depth sorting may be unnecessary and undesirable. If for example it is necessary to ensure the rendering order does not change from one frame to the next. In this case you could set the value to 'off' to prevent sorting.",
  524. items=[ ('on', 'on', 'ON'),
  525. ('off', 'off', 'OFF'),
  526. ('force', 'force', 'FORCE ON') ],
  527. default='on')
  528. bpy.types.Material.ogre_illumination_stage = EnumProperty(
  529. name='illumination stage',
  530. description='When using an additive lighting mode (SHADOWTYPE_STENCIL_ADDITIVE or SHADOWTYPE_TEXTURE_ADDITIVE), the scene is rendered in 3 discrete stages, ambient (or pre-lighting), per-light (once per light, with shadowing) and decal (or post-lighting). Usually OGRE figures out how to categorise your passes automatically, but there are some effects you cannot achieve without manually controlling the illumination.',
  531. items=[ ('', '', 'autodetect'),
  532. ('ambient', 'ambient', 'ambient'),
  533. ('per_light', 'per_light', 'lights'),
  534. ('decal', 'decal', 'decal') ],
  535. default=''
  536. )
  537. _ogre_depth_func = [
  538. ('less_equal', 'less_equal', '<='),
  539. ('less', 'less', '<'),
  540. ('equal', 'equal', '=='),
  541. ('not_equal', 'not_equal', '!='),
  542. ('greater_equal', 'greater_equal', '>='),
  543. ('greater', 'greater', '>'),
  544. ('always_fail', 'always_fail', 'false'),
  545. ('always_pass', 'always_pass', 'true'),
  546. ]
  547. bpy.types.Material.ogre_depth_func = EnumProperty(
  548. items=_ogre_depth_func,
  549. name='depth buffer function',
  550. description='If depth checking is enabled (see depth_check) a comparison occurs between the depth value of the pixel to be written and the current contents of the buffer. This comparison is normally less_equal, i.e. the pixel is written if it is closer (or at the same distance) than the current contents',
  551. default='less_equal')
  552. _ogre_scene_blend_ops = [
  553. ('add', 'add', 'DEFAULT'),
  554. ('subtract', 'subtract', 'SUBTRACT'),
  555. ('reverse_subtract', 'reverse_subtract', 'REVERSE SUBTRACT'),
  556. ('min', 'min', 'MIN'),
  557. ('max', 'max', 'MAX'),
  558. ]
  559. bpy.types.Material.ogre_scene_blend_op = EnumProperty(
  560. items=_ogre_scene_blend_ops,
  561. name='scene blending operation',
  562. description='This directive changes the operation which is applied between the two components of the scene blending equation',
  563. default='add')
  564. _ogre_scene_blend_types = [
  565. ('one zero', 'one zero', 'DEFAULT'),
  566. ('alpha_blend', 'alpha_blend', "The alpha value of the rendering output is used as a mask. Equivalent to 'scene_blend src_alpha one_minus_src_alpha'"),
  567. ('add', 'add', "The colour of the rendering output is added to the scene. Good for explosions, flares, lights, ghosts etc. Equivalent to 'scene_blend one one'."),
  568. ('modulate', 'modulate', "The colour of the rendering output is multiplied with the scene contents. Generally colours and darkens the scene, good for smoked glass, semi-transparent objects etc. Equivalent to 'scene_blend dest_colour zero'"),
  569. ('colour_blend', 'colour_blend', 'Colour the scene based on the brightness of the input colours, but dont darken. Equivalent to "scene_blend src_colour one_minus_src_colour"'),
  570. ]
  571. for mode in 'dest_colour src_colour one_minus_dest_colour dest_alpha src_alpha one_minus_dest_alpha one_minus_src_alpha'.split():
  572. _ogre_scene_blend_types.append( ('one %s'%mode, 'one %s'%mode, '') )
  573. del mode
  574. bpy.types.Material.ogre_scene_blend = EnumProperty(
  575. items=_ogre_scene_blend_types,
  576. name='scene blend',
  577. description='blending operation of material to scene',
  578. default='one zero')
  579. ## FAQ
  580. _faq_ = '''
  581. Q: I have hundres of objects, is there a way i can merge them on export only?
  582. A: Yes, just add them to a group named starting with "merge", or link the group.
  583. Q: Can i use subsurf or multi-res on a mesh with an armature?
  584. A: Yes.
  585. Q: Can i use subsurf or multi-res on a mesh with shape animation?
  586. A: No.
  587. Q: I don't see any objects when i export?
  588. A: You must select the objects you wish to export.
  589. Q: I don't see my animations when exported?
  590. A: Make sure you created an NLA strip on the armature.
  591. Q: Do i need to bake my IK and other constraints into FK on my armature before export?
  592. A: No.
  593. '''
  594. ## DOCUMENTATION
  595. ''' todo: Update the nonsense C:\Tundra2 paths from defaul config and fix this doc.
  596. Additionally point to some doc how to build opengl only version on windows if that really is needed and
  597. remove the old Tundra 7z link. '''
  598. _doc_installing_ = '''
  599. Installing:
  600. Installing the Addon:
  601. You can simply copy io_export_ogreDotScene.py to your blender installation under blender/2.6x/scripts/addons/
  602. and enable it in the user-prefs interface (CTRL+ALT+U)
  603. Or you can use blenders interface, under user-prefs, click addons, and click 'install-addon'
  604. (its a good idea to delete the old version first)
  605. Required:
  606. 1. Blender 2.63
  607. 2. Install Ogre Command Line tools to the default path: C:\\OgreCommandLineTools from http://www.ogre3d.org/download/tools
  608. * These tools are used to create the binary Mesh from the .xml mesh generated by this plugin.
  609. * Linux users may use above and Wine, or install from source, or install via apt-get install ogre-tools.
  610. Optional:
  611. 3. Install NVIDIA DDS Legacy Utilities - Install them to default path.
  612. * http://developer.nvidia.com/object/dds_utilities_legacy.html
  613. * Linux users will need to use Wine.
  614. 4. Install Image Magick
  615. * http://www.imagemagick.org
  616. 5. Copy OgreMeshy to C:\\OgreMeshy
  617. * If your using 64bit Windows, you may need to download a 64bit OgreMeshy
  618. * Linux copy to your home folder.
  619. 6. realXtend Tundra
  620. * For latest Tundra releases see http://code.google.com/p/realxtend-naali/downloads/list
  621. - You may need to tweak the config to tell your Tundra path or install to C:\Tundra2
  622. * Old OpenGL only build can be found from http://blender2ogre.googlecode.com/files/realxtend-Tundra-2.1.2-OpenGL.7z
  623. - Windows: extract to C:\Tundra2
  624. - Linux: extract to ~/Tundra2
  625. '''
  626. ## Options
  627. AXIS_MODES = [
  628. ('xyz', 'xyz', 'no swapping'),
  629. ('xz-y', 'xz-y', 'ogre standard'),
  630. ('-xzy', '-xzy', 'non standard'),
  631. ]
  632. def swap(vec):
  633. if CONFIG['SWAP_AXIS'] == 'xyz': return vec
  634. elif CONFIG['SWAP_AXIS'] == 'xzy':
  635. if len(vec) == 3: return mathutils.Vector( [vec.x, vec.z, vec.y] )
  636. elif len(vec) == 4: return mathutils.Quaternion( [ vec.w, vec.x, vec.z, vec.y] )
  637. elif CONFIG['SWAP_AXIS'] == '-xzy':
  638. if len(vec) == 3: return mathutils.Vector( [-vec.x, vec.z, vec.y] )
  639. elif len(vec) == 4: return mathutils.Quaternion( [ vec.w, -vec.x, vec.z, vec.y] )
  640. elif CONFIG['SWAP_AXIS'] == 'xz-y':
  641. if len(vec) == 3: return mathutils.Vector( [vec.x, vec.z, -vec.y] )
  642. elif len(vec) == 4: return mathutils.Quaternion( [ vec.w, vec.x, vec.z, -vec.y] )
  643. else:
  644. print( 'unknown swap axis mode', CONFIG['SWAP_AXIS'] )
  645. assert 0
  646. ## Config
  647. CONFIG_PATH = bpy.utils.user_resource('CONFIG', path='scripts', create=True)
  648. CONFIG_FILENAME = 'blender2ogre.pickle'
  649. CONFIG_FILEPATH = os.path.join(CONFIG_PATH, CONFIG_FILENAME)
  650. _CONFIG_DEFAULTS_ALL = {
  651. 'TUNDRA_STREAMING' : True,
  652. 'COPY_SHADER_PROGRAMS' : True,
  653. 'MAX_TEXTURE_SIZE' : 4096,
  654. 'SWAP_AXIS' : 'xz-y', # ogre standard
  655. 'ONLY_DEFORMABLE_BONES' : False,
  656. 'ONLY_KEYFRAMED_BONES' : False,
  657. 'OGRE_INHERIT_SCALE' : False,
  658. 'FORCE_IMAGE_FORMAT' : 'NONE',
  659. 'TOUCH_TEXTURES' : True,
  660. 'SEP_MATS' : True,
  661. 'SCENE' : True,
  662. 'SELONLY' : True,
  663. 'EXPORT_HIDDEN' : True,
  664. 'FORCE_CAMERA' : True,
  665. 'FORCE_LAMPS' : True,
  666. 'MESH' : True,
  667. 'MESH_OVERWRITE' : True,
  668. 'ARM_ANIM' : True,
  669. 'SHAPE_ANIM' : True,
  670. 'ARRAY' : True,
  671. 'MATERIALS' : True,
  672. 'DDS_MIPS' : True,
  673. 'TRIM_BONE_WEIGHTS' : 0.01,
  674. 'lodLevels' : 0,
  675. 'lodDistance' : 300,
  676. 'lodPercent' : 40,
  677. 'nuextremityPoints' : 0,
  678. 'generateEdgeLists' : False,
  679. 'generateTangents' : True, # this is now safe - ignored if mesh is missing UVs
  680. 'tangentSemantic' : 'tangent', # used to default to "uvw" but that doesn't seem to work with anything and breaks shaders
  681. 'tangentUseParity' : 4,
  682. 'tangentSplitMirrored' : False,
  683. 'tangentSplitRotated' : False,
  684. 'reorganiseBuffers' : True,
  685. 'optimiseAnimations' : True,
  686. }
  687. _CONFIG_TAGS_ = 'OGRETOOLS_XML_CONVERTER OGRETOOLS_MESH_MAGICK TUNDRA_ROOT OGRE_MESHY IMAGE_MAGICK_CONVERT NVCOMPRESS NVIDIATOOLS_EXE USER_MATERIALS SHADER_PROGRAMS TUNDRA_STREAMING'.split()
  688. ''' todo: Change pretty much all of these windows ones. Make a smarter way of detecting
  689. Ogre tools and Tundra from various default folders. Also consider making a installer that
  690. ships Ogre cmd line tools to ease the setup steps for end users. '''
  691. _CONFIG_DEFAULTS_WINDOWS = {
  692. 'OGRETOOLS_XML_CONVERTER' : 'C:\\OgreCommandLineTools\\OgreXmlConverter.exe',
  693. 'OGRETOOLS_MESH_MAGICK' : 'C:\\OgreCommandLineTools\\MeshMagick.exe',
  694. 'TUNDRA_ROOT' : 'C:\\Tundra2',
  695. 'OGRE_MESHY' : 'C:\\OgreMeshy\\Ogre Meshy.exe',
  696. 'IMAGE_MAGICK_CONVERT' : 'C:\\Program Files\\ImageMagick\\convert.exe',
  697. 'NVIDIATOOLS_EXE' : 'C:\\Program Files\\NVIDIA Corporation\\DDS Utilities\\nvdxt.exe',
  698. 'USER_MATERIALS' : 'C:\\Tundra2\\media\\materials',
  699. 'SHADER_PROGRAMS' : 'C:\\Tundra2\\media\\materials\\programs',
  700. 'NVCOMPRESS' : 'C:\\nvcompress.exe'
  701. }
  702. _CONFIG_DEFAULTS_UNIX = {
  703. 'OGRETOOLS_XML_CONVERTER' : '/usr/local/bin/OgreXMLConverter', # source build is better
  704. 'OGRETOOLS_MESH_MAGICK' : '/usr/local/bin/MeshMagick',
  705. 'TUNDRA_ROOT' : '~/Tundra2',
  706. 'OGRE_MESHY' : '~/OgreMeshy/Ogre Meshy.exe',
  707. 'IMAGE_MAGICK_CONVERT' : '/usr/bin/convert',
  708. 'NVIDIATOOLS_EXE' : '~/.wine/drive_c/Program Files/NVIDIA Corporation/DDS Utilities',
  709. 'USER_MATERIALS' : '~/Tundra2/media/materials',
  710. 'SHADER_PROGRAMS' : '~/Tundra2/media/materials/programs',
  711. #'USER_MATERIALS' : '~/ogre_src_v1-7-3/Samples/Media/materials',
  712. #'SHADER_PROGRAMS' : '~/ogre_src_v1-7-3/Samples/Media/materials/programs',
  713. 'NVCOMPRESS' : '/usr/local/bin/nvcompress'
  714. }
  715. # Unix: Replace ~ with absolute home dir path
  716. if sys.platform.startswith('linux') or sys.platform.startswith('darwin') or sys.platform.startswith('freebsd'):
  717. for tag in _CONFIG_DEFAULTS_UNIX:
  718. path = _CONFIG_DEFAULTS_UNIX[ tag ]
  719. if path.startswith('~'):
  720. _CONFIG_DEFAULTS_UNIX[ tag ] = os.path.expanduser( path )
  721. elif tag.startswith('OGRETOOLS') and not os.path.isfile( path ):
  722. _CONFIG_DEFAULTS_UNIX[ tag ] = os.path.join( '/usr/bin', os.path.split( path )[-1] )
  723. del tag
  724. del path
  725. ## PUBLIC API continues
  726. CONFIG = {}
  727. def load_config():
  728. global CONFIG
  729. if os.path.isfile( CONFIG_FILEPATH ):
  730. try:
  731. with open( CONFIG_FILEPATH, 'rb' ) as f:
  732. CONFIG = pickle.load( f )
  733. except:
  734. print('[ERROR]: Can not read config from %s' %CONFIG_FILEPATH)
  735. for tag in _CONFIG_DEFAULTS_ALL:
  736. if tag not in CONFIG:
  737. CONFIG[ tag ] = _CONFIG_DEFAULTS_ALL[ tag ]
  738. for tag in _CONFIG_TAGS_:
  739. if tag not in CONFIG:
  740. if sys.platform.startswith('win'):
  741. CONFIG[ tag ] = _CONFIG_DEFAULTS_WINDOWS[ tag ]
  742. elif sys.platform.startswith('linux') or sys.platform.startswith('darwin') or sys.platform.startswith('freebsd'):
  743. CONFIG[ tag ] = _CONFIG_DEFAULTS_UNIX[ tag ]
  744. else:
  745. print( 'ERROR: unknown platform' )
  746. assert 0
  747. try:
  748. if sys.platform.startswith('win'):
  749. import winreg
  750. # Find the blender2ogre install path from windows registry
  751. registry_key = winreg.OpenKey(winreg.HKEY_CLASSES_ROOT, r'Software\blender2ogre', 0, winreg.KEY_READ)
  752. exe_install_dir = winreg.QueryValueEx(registry_key, "Path")[0]
  753. if exe_install_dir != "":
  754. # OgreXmlConverter
  755. if os.path.isfile(exe_install_dir + "OgreXmlConverter.exe"):
  756. print ("Using OgreXmlConverter from install path:", exe_install_dir + "OgreXmlConverter.exe")
  757. CONFIG['OGRETOOLS_XML_CONVERTER'] = exe_install_dir + "OgreXmlConverter.exe"
  758. # Run auto updater as silent. Notifies user if there is a new version out.
  759. # This will not show any UI if there are no update and will go to network
  760. # only once per 2 days so it wont be spending much resources either.
  761. # todo: Move this to a more appropriate place than load_config()
  762. if os.path.isfile(exe_install_dir + "check-for-updates.exe"):
  763. subprocess.Popen([exe_install_dir + "check-for-updates.exe", "/silent"])
  764. except Exception as e:
  765. print("Exception while reading windows registry:", e)
  766. # Setup temp hidden RNA to expose the file paths
  767. for tag in _CONFIG_TAGS_:
  768. default = CONFIG[ tag ]
  769. func = eval( 'lambda self,con: CONFIG.update( {"%s" : self.%s} )' %(tag,tag) )
  770. if type(default) is bool:
  771. prop = BoolProperty(
  772. name=tag, description='updates bool setting', default=default,
  773. options={'SKIP_SAVE'}, update=func
  774. )
  775. else:
  776. prop = StringProperty(
  777. name=tag, description='updates path setting', maxlen=128, default=default,
  778. options={'SKIP_SAVE'}, update=func
  779. )
  780. setattr( bpy.types.WindowManager, tag, prop )
  781. return CONFIG
  782. CONFIG = load_config()
  783. def save_config():
  784. #for key in CONFIG: print( '%s = %s' %(key, CONFIG[key]) )
  785. if os.path.isdir( CONFIG_PATH ):
  786. try:
  787. with open( CONFIG_FILEPATH, 'wb' ) as f:
  788. pickle.dump( CONFIG, f, -1 )
  789. except:
  790. print('[ERROR]: Can not write to %s' %CONFIG_FILEPATH)
  791. else:
  792. print('[ERROR:] Config directory does not exist %s' %CONFIG_PATH)
  793. class Blender2Ogre_ConfigOp(bpy.types.Operator):
  794. '''operator: saves current b2ogre configuration'''
  795. bl_idname = "ogre.save_config"
  796. bl_label = "save config file"
  797. bl_options = {'REGISTER'}
  798. @classmethod
  799. def poll(cls, context):
  800. return True
  801. def invoke(self, context, event):
  802. save_config()
  803. Report.reset()
  804. Report.messages.append('SAVED %s' %CONFIG_FILEPATH)
  805. Report.show()
  806. return {'FINISHED'}
  807. # Make default material for missing materials:
  808. # * Red flags for users so they can quickly see what they forgot to assign a material to.
  809. # * Do not crash if no material on object - thats annoying for the user.
  810. MISSING_MATERIAL = '''
  811. material _missing_material_
  812. {
  813. receive_shadows off
  814. technique
  815. {
  816. pass
  817. {
  818. ambient 0.1 0.1 0.1 1.0
  819. diffuse 0.8 0.0 0.0 1.0
  820. specular 0.5 0.5 0.5 1.0 12.5
  821. emissive 0.3 0.3 0.3 1.0
  822. }
  823. }
  824. }
  825. '''
  826. ## Helper functions
  827. def timer_diff_str(start):
  828. return "%0.2f" % (time.time()-start)
  829. def find_bone_index( ob, arm, groupidx): # sometimes the groups are out of order, this finds the right index.
  830. if groupidx < len(ob.vertex_groups): # reported by Slacker
  831. vg = ob.vertex_groups[ groupidx ]
  832. j = 0
  833. for i,bone in enumerate(arm.pose.bones):
  834. if not bone.bone.use_deform and CONFIG['ONLY_DEFORMABLE_BONES']:
  835. j+=1 # if we skip bones we need to adjust the id
  836. if bone.name == vg.name:
  837. return i-j
  838. else:
  839. print('WARNING: object vertex groups not in sync with armature', ob, arm, groupidx)
  840. def mesh_is_smooth( mesh ):
  841. for face in mesh.tessfaces:
  842. if face.use_smooth: return True
  843. def find_uv_layer_index( uvname, material=None ):
  844. # This breaks if users have uv layers with same name with different indices over different objects
  845. idx = 0
  846. for mesh in bpy.data.meshes:
  847. if material is None or material.name in mesh.materials:
  848. if mesh.uv_textures:
  849. names = [ uv.name for uv in mesh.uv_textures ]
  850. if uvname in names:
  851. idx = names.index( uvname )
  852. break # should we check all objects using material and enforce the same index?
  853. return idx
  854. def has_custom_property( a, name ):
  855. for prop in a.items():
  856. n,val = prop
  857. if n == name:
  858. return True
  859. def is_strictly_simple_terrain( ob ):
  860. # A default plane, with simple-subsurf and displace modifier on Z
  861. if len(ob.data.vertices) != 4 and len(ob.data.tessfaces) != 1:
  862. return False
  863. elif len(ob.modifiers) < 2:
  864. return False
  865. elif ob.modifiers[0].type != 'SUBSURF' or ob.modifiers[1].type != 'DISPLACE':
  866. return False
  867. elif ob.modifiers[0].subdivision_type != 'SIMPLE':
  868. return False
  869. elif ob.modifiers[1].direction != 'Z':
  870. return False # disallow NORMAL and other modes
  871. else:
  872. return True
  873. def get_image_textures( mat ):
  874. r = []
  875. for s in mat.texture_slots:
  876. if s and s.texture.type == 'IMAGE':
  877. r.append( s )
  878. return r
  879. def indent( level, *args ):
  880. if not args:
  881. return ' ' * level
  882. else:
  883. a = ''
  884. for line in args:
  885. a += ' ' * level
  886. a += line
  887. a += '\n'
  888. return a
  889. def gather_instances():
  890. instances = {}
  891. for ob in bpy.context.scene.objects:
  892. if ob.data and ob.data.users > 1:
  893. if ob.data not in instances:
  894. instances[ ob.data ] = []
  895. instances[ ob.data ].append( ob )
  896. return instances
  897. def select_instances( context, name ):
  898. for ob in bpy.context.scene.objects:
  899. ob.select = False
  900. ob = bpy.context.scene.objects[ name ]
  901. if ob.data:
  902. inst = gather_instances()
  903. for ob in inst[ ob.data ]: ob.select = True
  904. bpy.context.scene.objects.active = ob
  905. def select_group( context, name, options={} ):
  906. for ob in bpy.context.scene.objects:
  907. ob.select = False
  908. for grp in bpy.data.groups:
  909. if grp.name == name:
  910. # context.scene.objects.active = grp.objects
  911. # Note that the context is read-only. These values cannot be modified directly,
  912. # though they may be changed by running API functions or by using the data API.
  913. # So bpy.context.object = obj will raise an error. But bpy.context.scene.objects.active = obj
  914. # will work as expected. - http://wiki.blender.org/index.php?title=Dev:2.5/Py/API/Intro&useskin=monobook
  915. bpy.context.scene.objects.active = grp.objects[0]
  916. for ob in grp.objects:
  917. ob.select = True
  918. else:
  919. pass
  920. def get_objects_using_materials( mats ):
  921. obs = []
  922. for ob in bpy.data.objects:
  923. if ob.type == 'MESH':
  924. for mat in ob.data.materials:
  925. if mat in mats:
  926. if ob not in obs:
  927. obs.append( ob )
  928. break
  929. return obs
  930. def get_materials_using_image( img ):
  931. mats = []
  932. for mat in bpy.data.materials:
  933. for slot in get_image_textures( mat ):
  934. if slot.texture.image == img:
  935. if mat not in mats:
  936. mats.append( mat )
  937. return mats
  938. def get_parent_matrix( ob, objects ):
  939. if not ob.parent:
  940. return mathutils.Matrix(((1,0,0,0),(0,1,0,0),(0,0,1,0),(0,0,0,1))) # Requiered for Blender SVN > 2.56
  941. else:
  942. if ob.parent in objects:
  943. return ob.parent.matrix_world.copy()
  944. else:
  945. return get_parent_matrix(ob.parent, objects)
  946. def merge_group( group ):
  947. print('--------------- merge group ->', group )
  948. copies = []
  949. for ob in group.objects:
  950. if ob.type == 'MESH':
  951. print( '\t group member', ob.name )
  952. o2 = ob.copy(); copies.append( o2 )
  953. o2.data = o2.to_mesh(bpy.context.scene, True, "PREVIEW") # collaspe modifiers
  954. while o2.modifiers:
  955. o2.modifiers.remove( o2.modifiers[0] )
  956. bpy.context.scene.objects.link( o2 ) #; o2.select = True
  957. merged = merge( copies )
  958. merged.name = group.name
  959. merged.data.name = group.name
  960. return merged
  961. def merge_objects( objects, name='_temp_', transform=None ):
  962. assert objects
  963. copies = []
  964. for ob in objects:
  965. ob.select = False
  966. if ob.type == 'MESH':
  967. o2 = ob.copy(); copies.append( o2 )
  968. o2.data = o2.to_mesh(bpy.context.scene, True, "PREVIEW") # collaspe modifiers
  969. while o2.modifiers:
  970. o2.modifiers.remove( o2.modifiers[0] )
  971. if transform:
  972. o2.matrix_world = transform * o2.matrix_local
  973. bpy.context.scene.objects.link( o2 ) #; o2.select = True
  974. merged = merge( copies )
  975. merged.name = name
  976. merged.data.name = name
  977. return merged
  978. def merge( objects ):
  979. print('MERGE', objects)
  980. for ob in bpy.context.selected_objects:
  981. ob.select = False
  982. for ob in objects:
  983. print('\t'+ob.name)
  984. ob.select = True
  985. assert not ob.library
  986. bpy.context.scene.objects.active = ob
  987. bpy.ops.object.join()
  988. return bpy.context.active_object
  989. def get_merge_group( ob, prefix='merge' ):
  990. m = []
  991. for grp in ob.users_group:
  992. if grp.name.lower().startswith(prefix): m.append( grp )
  993. if len(m)==1:
  994. #if ob.data.users != 1:
  995. # print( 'WARNING: an instance can not be in a merge group' )
  996. # return
  997. return m[0]
  998. elif m:
  999. print('WARNING: an object can not be in two merge groups at the same time', ob)
  1000. return
  1001. def wordwrap( txt ):
  1002. r = ['']
  1003. for word in txt.split(' '): # do not split on tabs
  1004. word = word.replace('\t', ' '*3)
  1005. r[-1] += word + ' '
  1006. if len(r[-1]) > 90:
  1007. r.append( '' )
  1008. return r
  1009. ## RPython xml dom
  1010. class RElement(object):
  1011. def appendChild( self, child ):
  1012. self.childNodes.append( child )
  1013. def setAttribute( self, name, value ):
  1014. self.attributes[name]=value
  1015. def __init__(self, tag):
  1016. self.tagName = tag
  1017. self.childNodes = []
  1018. self.attributes = {}
  1019. def toprettyxml(self, lines, indent ):
  1020. s = '<%s ' % self.tagName
  1021. sortedNames = sorted( self.attributes.keys() )
  1022. for name in sortedNames:
  1023. value = self.attributes[name]
  1024. if not isinstance(value, str):
  1025. value = str(value)
  1026. s += '%s=%s ' % (name, quoteattr(value))
  1027. if not self.childNodes:
  1028. s += '/>'; lines.append( (' '*indent)+s )
  1029. else:
  1030. s += '>'; lines.append( (' '*indent)+s )
  1031. indent += 1
  1032. for child in self.childNodes:
  1033. child.toprettyxml( lines, indent )
  1034. indent -= 1
  1035. lines.append((' '*indent) + '</%s>' % self.tagName )
  1036. class RDocument(object):
  1037. def __init__(self):
  1038. self.documentElement = None
  1039. def appendChild(self, root):
  1040. self.documentElement = root
  1041. def createElement(self, tag):
  1042. e = RElement(tag)
  1043. e.document = self
  1044. return e
  1045. def toprettyxml(self):
  1046. indent = 0
  1047. lines = []
  1048. self.documentElement.toprettyxml(lines, indent)
  1049. return '\n'.join(lines)
  1050. class SimpleSaxWriter():
  1051. def __init__(self, output, root_tag, root_attrs):
  1052. self.output = output
  1053. self.root_tag = root_tag
  1054. self.indent=0
  1055. output.write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n")
  1056. self.start_tag(root_tag, root_attrs)
  1057. def _out_tag(self, name, attrs, isLeaf):
  1058. # sorted attributes -- don't want attributes output in random order, which is what the XMLGenerator class does
  1059. self.output.write(" " * self.indent)
  1060. self.output.write("<%s" % name)
  1061. sortedNames = sorted( attrs.keys() ) # sorted list of attribute names
  1062. for name in sortedNames:
  1063. value = attrs[ name ]
  1064. # if not of type string,
  1065. if not isinstance(value, str):
  1066. # turn it into a string
  1067. value = str(value)
  1068. self.output.write(" %s=%s" % (name, quoteattr(value)))
  1069. if isLeaf:
  1070. self.output.write("/")
  1071. else:
  1072. self.indent += 4
  1073. self.output.write(">\n")
  1074. def start_tag(self, name, attrs):
  1075. self._out_tag(name, attrs, False)
  1076. def end_tag(self, name):
  1077. self.indent -= 4
  1078. self.output.write(" " * self.indent)
  1079. self.output.write("</%s>\n" % name)
  1080. def leaf_tag(self, name, attrs):
  1081. self._out_tag(name, attrs, True)
  1082. def close(self):
  1083. self.end_tag( self.root_tag )
  1084. ## Report Hack
  1085. class ReportSingleton(object):
  1086. def __init__(self):
  1087. self.reset()
  1088. def show(self):
  1089. bpy.ops.wm.call_menu( name='MiniReport' )
  1090. def reset(self):
  1091. self.materials = []
  1092. self.meshes = []
  1093. self.lights = []
  1094. self.cameras = []
  1095. self.armatures = []
  1096. self.armature_animations = []
  1097. self.shape_animations = []
  1098. self.textures = []
  1099. self.vertices = 0
  1100. self.orig_vertices = 0
  1101. self.faces = 0
  1102. self.triangles = 0
  1103. self.warnings = []
  1104. self.errors = []
  1105. self.messages = []
  1106. self.paths = []
  1107. def report(self):
  1108. r = ['Report:']
  1109. ex = ['Extended Report:']
  1110. if self.errors:
  1111. r.append( ' ERRORS:' )
  1112. for a in self.errors: r.append( ' - %s' %a )
  1113. #if not bpy.context.selected_objects:
  1114. # self.warnings.append('YOU DID NOT SELECT ANYTHING TO EXPORT')
  1115. if

Large files files are truncated, but you can click here to view the full file