forked from dairin0d/export-selected
/
io_export_selected.py
executable file
·463 lines (380 loc) · 15.2 KB
/
io_export_selected.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
# ***** BEGIN GPL LICENSE BLOCK *****
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
# ***** END GPL LICENSE BLOCK *****
# <pep8-80 compliant>
bl_info = {
"name": "Export Selected",
"author": "dairin0d, rking",
"version": (1, 2),
"blender": (2, 6, 0),
"location": "File > Export > Selected",
"description": "Export selected objects to a chosen format",
"warning": "",
"wiki_url": "http://wiki.blender.org/index.php/Extensions:2.6/Py/"\
"Scripts/Import-Export/Export_Selected",
"tracker_url": "http://projects.blender.org/tracker/"\
"?func=detail&aid=30942",
"category": "Import-Export"}
#============================================================================#
import bpy
from bpy_extras.io_utils import ExportHelper
join_before_export = {
"export_mesh.ply",
}
bpy_props = {
bpy.props.BoolProperty,
bpy.props.BoolVectorProperty,
bpy.props.IntProperty,
bpy.props.IntVectorProperty,
bpy.props.FloatProperty,
bpy.props.FloatVectorProperty,
bpy.props.StringProperty,
bpy.props.EnumProperty,
bpy.props.PointerProperty,
bpy.props.CollectionProperty,
}
def is_bpy_prop(value):
if isinstance(value, tuple) and (len(value) == 2):
if (value[0] in bpy_props) and isinstance(value[1], dict):
return True
return False
def iter_public_bpy_props(cls, exclude_hidden=False):
for key in dir(cls):
if key.startswith("_"):
continue
value = getattr(cls, key)
if is_bpy_prop(value):
if exclude_hidden:
options = value[1].get("options", "")
if 'HIDDEN' in options:
continue
yield (key, value)
def get_op(idname):
category_name, op_name = idname.split(".")
category = getattr(bpy.ops, category_name)
return getattr(category, op_name)
def iter_exporters():
#categories = dir(bpy.ops)
categories = ["export_anim", "export_mesh", "export_scene"]
for category_name in categories:
op_category = getattr(bpy.ops, category_name)
for name in dir(op_category):
total_name = category_name + "." + name
if total_name == ExportSelected.bl_idname:
continue
if "export" in total_name:
op = getattr(op_category, name)
yield total_name, op
class CurrentFormatProperties(bpy.types.PropertyGroup):
@classmethod
def _clear_props(cls):
keys_to_remove = list(cls._keys())
for key in keys_to_remove:
delattr(cls, key)
@classmethod
def _add_props(cls, template):
for key, value in iter_public_bpy_props(template):
setattr(cls, key, value)
@classmethod
def _keys(cls, exclude_hidden=False):
for kv in iter_public_bpy_props(cls, exclude_hidden):
yield kv[0]
class ExportSelected(bpy.types.Operator, ExportHelper):
'''Export selected objects to a chosen format'''
bl_idname = "export_scene.selected"
bl_label = "Export Selected"
filename_ext = bpy.props.StringProperty(
default="",
options={'HIDDEN'},
)
filter_glob = bpy.props.StringProperty(
default="*.*",
options={'HIDDEN'},
)
selection_mode = bpy.props.EnumProperty(
name="Selection Mode",
description="Limit/expand the selection",
default='SELECTED',
items=[
('SELECTED', "Selected", ""),
('VISIBLE', "Visible", ""),
('ALL', "All", ""),
],
)
include_children = bpy.props.BoolProperty(
name="Include Children",
description="Keep children even if they're not selected",
default=True,
)
remove_orphans = bpy.props.BoolProperty(
name="Remove Orphans",
description="Remove datablocks that have no users",
default=True,
)
keep_materials = bpy.props.BoolProperty(
name="Keep Materials",
description="Keep Materials",
default=True,
)
keep_textures = bpy.props.BoolProperty(
name="Keep Textures",
description="Keep Textures",
default=True,
)
keep_world_textures = bpy.props.BoolProperty(
name="Keep World Textures",
description="Keep World Textures",
default=False,
)
object_types = bpy.props.EnumProperty(
name="Object types",
description="Object type(s) to export",
default={'ALL'},
items=[
('ALL', "All", ""),
('MESH', "Mesh", ""),
('CURVE', "Curve", ""),
('SURFACE', "Surface", ""),
('META', "Meta", ""),
('FONT', "Font", ""),
('ARMATURE', "Armature", ""),
('LATTICE', "Lattice", ""),
('EMPTY', "Empty", ""),
('CAMERA', "Camera", ""),
('LAMP', "Lamp", ""),
('SPEAKER', "Speaker", ""),
],
options={'ENUM_FLAG'},
)
visible_name = bpy.props.StringProperty(
name="Format",
description="Export format",
options={'HIDDEN'},
)
format = bpy.props.StringProperty(
name="Format",
description="Export format",
options={'HIDDEN'},
)
format_props = bpy.props.PointerProperty(
type=CurrentFormatProperties,
options={'HIDDEN'},
)
@classmethod
def poll(cls, context):
return len(context.scene.objects) != 0
def invoke(self, context, event):
CurrentFormatProperties._clear_props()
if self.format:
op = get_op(self.format)
op_class = type(op.get_instance())
CurrentFormatProperties._add_props(op_class)
if self.format == "wm.collada_export":
# Special case: Collada (built-in) -- has no
# explicitly defined Python properties
CurrentFormatProperties.second_life = bpy.props.BoolProperty(
name="Export for Second Life",
description="Compatibility mode for Second Life",
default=False,
)
else:
self.visible_name = "Blend"
self.filename_ext = ".blend"
self.filter_glob = "*.blend"
self.filepath = context.object.name + self.filename_ext
return ExportHelper.invoke(self, context, event)
def clear_world(self, context):
bpy.ops.ed.undo_push(message="Delete unselected")
for scene in bpy.data.scenes:
if scene != context.scene:
bpy.data.scenes.remove(scene)
scene = context.scene
objs = set()
def add_obj(obj):
if self.object_types.intersection({'ALL', obj.type}):
objs.add(obj)
if self.include_children:
for child in obj.children:
add_obj(child)
for obj in scene.objects:
if (self.selection_mode == 'SELECTED') and obj.select:
add_obj(obj)
elif (self.selection_mode == 'VISIBLE') and obj.is_visible(scene):
obj.hide_select = False
add_obj(obj)
elif (self.selection_mode == 'ALL'):
obj.hide_select = False
add_obj(obj)
for obj in scene.objects:
if obj in objs:
obj.select = True
else:
scene.objects.unlink(obj)
bpy.data.objects.remove(obj)
scene.update()
if not self.format:
if not self.keep_materials:
for material in bpy.data.materials:
material.user_clear()
bpy.data.materials.remove(material)
if not self.keep_textures:
for world in bpy.data.worlds:
for i in range(len(world.texture_slots)):
world.texture_slots.clear(i)
for material in bpy.data.materials:
for i in range(len(material.texture_slots)):
material.texture_slots.clear(i)
for brush in bpy.data.brushes:
brush.texture = None
for texture in bpy.data.textures:
texture.user_clear()
bpy.data.textures.remove(texture)
elif not self.keep_world_textures:
for world in bpy.data.worlds:
for i in range(len(world.texture_slots)):
world.texture_slots.clear(i)
if self.remove_orphans:
datablocks_cleanup_order = [
#"window_managers",
#"screens",
"scenes",
"worlds",
"grease_pencil",
"fonts",
"scripts",
"texts",
"movieclips",
"actions",
"speakers",
"sounds",
"brushes",
"node_groups",
"groups",
"objects",
"armatures",
"cameras",
"lamps",
"lattices",
"shape_keys",
"meshes",
"metaballs",
"particles",
"curves",
"materials",
"textures",
"images",
"libraries",
]
for datablocks_name in datablocks_cleanup_order:
datablocks = getattr(bpy.data, datablocks_name)
if type(datablocks).__name__ == "bpy_prop_collection":
for datablock in datablocks:
if datablock.users == 0:
datablocks.remove(datablock)
if self.format in join_before_export:
bpy.ops.object.convert()
bpy.ops.object.join()
def execute(self, context):
self.clear_world(context)
if self.format:
props = {}
for key in CurrentFormatProperties._keys():
props[key] = getattr(self.format_props, key)
props["filepath"] = self.filepath
op = get_op(self.format)
op(**props)
else:
bpy.ops.wm.save_as_mainfile(
filepath=self.filepath,
copy=True,
)
bpy.ops.ed.undo()
bpy.ops.ed.undo_push(message="Export Selected")
return {'FINISHED'}
def draw(self, context):
layout = self.layout
layout.label("Export " + self.visible_name)
layout.prop(self, "selection_mode", text="")
layout.prop(self, "include_children")
layout.prop_menu_enum(self, "object_types")
layout.box()
if not self.format:
layout.prop(self, "remove_orphans")
layout.prop(self, "keep_materials")
layout.prop(self, "keep_textures")
sublayout = layout.row()
sublayout.enabled = self.keep_textures
sublayout.prop(self, "keep_world_textures")
return
op = get_op(self.format)
op_class = type(op.get_instance())
if 0:#hasattr(op_class, "draw"):
# Some bugs here
self.format_props.layout = layout
op_class.draw(self.format_props, context)
else:
for key in CurrentFormatProperties._keys(True):
layout.prop(self.format_props, key)
class OBJECT_MT_selected_export(bpy.types.Menu):
bl_idname = "OBJECT_MT_selected_export"
bl_label = "Selected"
def draw(self, context):
layout = self.layout
def def_op(visible_name, total_name="", layout=layout):
if visible_name.lower().startswith("export "):
visible_name = visible_name[len("export "):]
if total_name:
op = get_op(total_name)
if not op.poll():
layout = layout.row()
layout.enabled = False
op_info = layout.operator(
ExportSelected.bl_idname,
text=visible_name,
)
op_info.format = total_name
op_info.visible_name = visible_name
return op_info
# Special case: export to .blend (the default)
def_op("Blend")
# Special case: Collada is built-in, resides
# in an unconventional category, and has no
# explicit ext/glob properties defined
op_info = def_op("Collada", "wm.collada_export")
op_info.filename_ext = ".dae"
op_info.filter_glob = "*.dae"
for total_name, op in iter_exporters():
op_class = type(op.get_instance())
rna = op.get_rna()
op_info = def_op(rna.rna_type.name, total_name)
if hasattr(op_class, "filename_ext"):
op_info.filename_ext = op_class.filename_ext
if hasattr(rna, "filter_glob"):
op_info.filter_glob = rna.filter_glob
def menu_func_export(self, context):
self.layout.menu("OBJECT_MT_selected_export", text="Selected")
def register():
bpy.utils.register_class(CurrentFormatProperties)
bpy.utils.register_class(ExportSelected)
bpy.utils.register_class(OBJECT_MT_selected_export)
bpy.types.INFO_MT_file_export.prepend(menu_func_export)
def unregister():
bpy.types.INFO_MT_file_export.remove(menu_func_export)
bpy.utils.unregister_class(OBJECT_MT_selected_export)
bpy.utils.unregister_class(ExportSelected)
bpy.utils.unregister_class(CurrentFormatProperties)
if __name__ == "__main__":
register()