PLY: add missing type: short
[blender-addons.git] / space_view3d_copy_attributes.py
blob57e1a69e7027964426c121108ec31c4bf82033af
1 # ##### BEGIN GPL LICENSE BLOCK #####
3 # This program is free software; you can redistribute it and/or
4 # modify it under the terms of the GNU General Public License
5 # as published by the Free Software Foundation; either version 2
6 # of the License, or (at your option) any later version.
8 # This program 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
11 # GNU General Public License for more details.
13 # You should have received a copy of the GNU General Public License
14 # along with this program; if not, write to the Free Software Foundation,
15 # Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
17 # ##### END GPL LICENSE BLOCK #####
19 # <pep8 compliant>
21 bl_info = {
22 "name": "Copy Attributes Menu",
23 "author": "Bassam Kurdali, Fabian Fricke, Adam Wiseman",
24 "version": (0, 4, 7),
25 "blender": (2, 63, 0),
26 "location": "View3D > Ctrl-C",
27 "description": "Copy Attributes Menu from Blender 2.4",
28 "wiki_url": "http://wiki.blender.org/index.php/Extensions:2.6/Py/"
29 "Scripts/3D_interaction/Copy_Attributes_Menu",
30 "category": "3D View",
33 import bpy
34 from mathutils import Matrix
37 def build_exec(loopfunc, func):
38 """Generator function that returns exec functions for operators """
40 def exec_func(self, context):
41 loopfunc(self, context, func)
42 return {'FINISHED'}
43 return exec_func
46 def build_invoke(loopfunc, func):
47 """Generator function that returns invoke functions for operators"""
49 def invoke_func(self, context, event):
50 loopfunc(self, context, func)
51 return {'FINISHED'}
52 return invoke_func
55 def build_op(idname, label, description, fpoll, fexec, finvoke):
56 """Generator function that returns the basic operator"""
58 class myopic(bpy.types.Operator):
59 bl_idname = idname
60 bl_label = label
61 bl_description = description
62 execute = fexec
63 poll = fpoll
64 invoke = finvoke
65 return myopic
68 def genops(copylist, oplist, prefix, poll_func, loopfunc):
69 """Generate ops from the copy list and its associated functions """
70 for op in copylist:
71 exec_func = build_exec(loopfunc, op[3])
72 invoke_func = build_invoke(loopfunc, op[3])
73 opclass = build_op(prefix + op[0], "Copy " + op[1], op[2],
74 poll_func, exec_func, invoke_func)
75 oplist.append(opclass)
78 def generic_copy(source, target, string=""):
79 """ copy attributes from source to target that have string in them """
80 for attr in dir(source):
81 if attr.find(string) > -1:
82 try:
83 setattr(target, attr, getattr(source, attr))
84 except:
85 pass
86 return
89 def getmat(bone, active, context, ignoreparent):
90 """Helper function for visual transform copy,
91 gets the active transform in bone space
92 """
93 obj_act = context.active_object
94 data_bone = obj_act.data.bones[bone.name]
95 #all matrices are in armature space unless commented otherwise
96 otherloc = active.matrix # final 4x4 mat of target, location.
97 bonemat_local = data_bone.matrix_local.copy() # self rest matrix
98 if data_bone.parent:
99 parentposemat = obj_act.pose.bones[data_bone.parent.name].matrix.copy()
100 parentbonemat = data_bone.parent.matrix_local.copy()
101 else:
102 parentposemat = parentbonemat = Matrix()
103 if parentbonemat == parentposemat or ignoreparent:
104 newmat = bonemat_local.inverted() * otherloc
105 else:
106 bonemat = parentbonemat.inverted() * bonemat_local
108 newmat = bonemat.inverted() * parentposemat.inverted() * otherloc
109 return newmat
112 def rotcopy(item, mat):
113 """copy rotation to item from matrix mat depending on item.rotation_mode"""
114 if item.rotation_mode == 'QUATERNION':
115 item.rotation_quaternion = mat.to_3x3().to_quaternion()
116 elif item.rotation_mode == 'AXIS_ANGLE':
117 rot = mat.to_3x3().to_quaternion().to_axis_angle() # returns (Vector((x, y, z)), w)
118 axis_angle = rot[1], rot[0][0], rot[0][1], rot[0][2] # convert to w, x, y, z
119 item.rotation_axis_angle = axis_angle
120 else:
121 item.rotation_euler = mat.to_3x3().to_euler(item.rotation_mode)
124 def pLoopExec(self, context, funk):
125 """Loop over selected bones and execute funk on them"""
126 active = context.active_pose_bone
127 selected = context.selected_pose_bones
128 selected.remove(active)
129 for bone in selected:
130 funk(bone, active, context)
132 #The following functions are used o copy attributes frome active to bone
135 def pLocLocExec(bone, active, context):
136 bone.location = active.location
139 def pLocRotExec(bone, active, context):
140 rotcopy(bone, active.matrix_basis.to_3x3())
143 def pLocScaExec(bone, active, context):
144 bone.scale = active.scale
147 def pVisLocExec(bone, active, context):
148 bone.location = getmat(bone, active, context, False).to_translation()
151 def pVisRotExec(bone, active, context):
152 rotcopy(bone, getmat(bone, active,
153 context, not context.active_object.data.bones[bone.name].use_inherit_rotation))
156 def pVisScaExec(bone, active, context):
157 bone.scale = getmat(bone, active, context,
158 not context.active_object.data.bones[bone.name].use_inherit_scale)\
159 .to_scale()
162 def pDrwExec(bone, active, context):
163 bone.custom_shape = active.custom_shape
164 bone.bone.show_wire = active.bone.show_wire
167 def pLokExec(bone, active, context):
168 for index, state in enumerate(active.lock_location):
169 bone.lock_location[index] = state
170 for index, state in enumerate(active.lock_rotation):
171 bone.lock_rotation[index] = state
172 bone.lock_rotations_4d = active.lock_rotations_4d
173 bone.lock_rotation_w = active.lock_rotation_w
174 for index, state in enumerate(active.lock_scale):
175 bone.lock_scale[index] = state
178 def pConExec(bone, active, context):
179 for old_constraint in active.constraints.values():
180 new_constraint = bone.constraints.new(old_constraint.type)
181 generic_copy(old_constraint, new_constraint)
184 def pIKsExec(bone, active, context):
185 generic_copy(active, bone, "ik_")
188 def pBBonesExec(bone, active, context):
189 object = active.id_data
190 generic_copy(
191 object.data.bones[active.name],
192 object.data.bones[bone.name],
193 "bbone_")
195 pose_copies = (('pose_loc_loc', "Local Location",
196 "Copy Location from Active to Selected", pLocLocExec),
197 ('pose_loc_rot', "Local Rotation",
198 "Copy Rotation from Active to Selected", pLocRotExec),
199 ('pose_loc_sca', "Local Scale",
200 "Copy Scale from Active to Selected", pLocScaExec),
201 ('pose_vis_loc', "Visual Location",
202 "Copy Location from Active to Selected", pVisLocExec),
203 ('pose_vis_rot', "Visual Rotation",
204 "Copy Rotation from Active to Selected", pVisRotExec),
205 ('pose_vis_sca', "Visual Scale",
206 "Copy Scale from Active to Selected", pVisScaExec),
207 ('pose_drw', "Bone Shape",
208 "Copy Bone Shape from Active to Selected", pDrwExec),
209 ('pose_lok', "Protected Transform",
210 "Copy Protected Tranforms from Active to Selected", pLokExec),
211 ('pose_con', "Bone Constraints",
212 "Copy Object Constraints from Active to Selected", pConExec),
213 ('pose_iks', "IK Limits",
214 "Copy IK Limits from Active to Selected", pIKsExec),
215 ('bbone_settings', "BBone Settings",
216 "Copy BBone Settings from Active to Selected", pBBonesExec),)
219 @classmethod
220 def pose_poll_func(cls, context):
221 return(context.mode == 'POSE')
224 def pose_invoke_func(self, context, event):
225 wm = context.window_manager
226 wm.invoke_props_dialog(self)
227 return {'RUNNING_MODAL'}
230 class CopySelectedPoseConstraints(bpy.types.Operator):
231 """Copy Chosen constraints from active to selected"""
232 bl_idname = "pose.copy_selected_constraints"
233 bl_label = "Copy Selected Constraints"
234 selection = bpy.props.BoolVectorProperty(size=32, options={'SKIP_SAVE'})
236 poll = pose_poll_func
237 invoke = pose_invoke_func
239 def draw(self, context):
240 layout = self.layout
241 for idx, const in enumerate(context.active_pose_bone.constraints):
242 layout.prop(self, "selection", index=idx, text=const.name,
243 toggle=True)
245 def execute(self, context):
246 active = context.active_pose_bone
247 selected = context.selected_pose_bones[:]
248 selected.remove(active)
249 for bone in selected:
250 for index, flag in enumerate(self.selection):
251 if flag:
252 old_constraint = active.constraints[index]
253 new_constraint = bone.constraints.new(\
254 active.constraints[index].type)
255 generic_copy(old_constraint, new_constraint)
256 return {'FINISHED'}
258 pose_ops = [] # list of pose mode copy operators
260 genops(pose_copies, pose_ops, "pose.copy_", pose_poll_func, pLoopExec)
263 class VIEW3D_MT_posecopypopup(bpy.types.Menu):
264 bl_label = "Copy Attributes"
266 def draw(self, context):
267 layout = self.layout
268 layout.operator_context = 'INVOKE_REGION_WIN'
269 for op in pose_copies:
270 layout.operator("pose.copy_" + op[0])
271 layout.operator("pose.copy_selected_constraints")
272 layout.operator("pose.copy", text="copy pose")
275 def obLoopExec(self, context, funk):
276 """Loop over selected objects and execute funk on them"""
277 active = context.active_object
278 selected = context.selected_objects[:]
279 selected.remove(active)
280 for obj in selected:
281 msg = funk(obj, active, context)
282 if msg:
283 self.report({msg[0]}, msg[1])
286 def world_to_basis(active, ob, context):
287 """put world coords of active as basis coords of ob"""
288 local = ob.parent.matrix_world.inverted() * active.matrix_world
289 P = ob.matrix_basis * ob.matrix_local.inverted()
290 mat = P * local
291 return(mat)
293 #The following functions are used o copy attributes from
294 #active to selected object
297 def obLoc(ob, active, context):
298 ob.location = active.location
301 def obRot(ob, active, context):
302 rotcopy(ob, active.matrix_local.to_3x3())
305 def obSca(ob, active, context):
306 ob.scale = active.scale
309 def obVisLoc(ob, active, context):
310 if ob.parent:
311 mat = world_to_basis(active, ob, context)
312 ob.location = mat.to_translation()
313 else:
314 ob.location = active.matrix_world.to_translation()
317 def obVisRot(ob, active, context):
318 if ob.parent:
319 mat = world_to_basis(active, ob, context)
320 rotcopy(ob, mat.to_3x3())
321 else:
322 rotcopy(ob, active.matrix_world.to_3x3())
325 def obVisSca(ob, active, context):
326 if ob.parent:
327 mat = world_to_basis(active, ob, context)
328 ob.scale = mat.to_scale()
329 else:
330 ob.scale = active.matrix_world.to_scale()
333 def obDrw(ob, active, context):
334 ob.draw_type = active.draw_type
335 ob.show_axis = active.show_axis
336 ob.show_bounds = active.show_bounds
337 ob.draw_bounds_type = active.draw_bounds_type
338 ob.show_name = active.show_name
339 ob.show_texture_space = active.show_texture_space
340 ob.show_transparent = active.show_transparent
341 ob.show_wire = active.show_wire
342 ob.show_x_ray = active.show_x_ray
343 ob.empty_draw_type = active.empty_draw_type
344 ob.empty_draw_size = active.empty_draw_size
347 def obOfs(ob, active, context):
348 ob.time_offset = active.time_offset
349 return('INFO', "time offset copied")
352 def obDup(ob, active, context):
353 generic_copy(active, ob, "dupli")
354 return('INFO', "duplication method copied")
357 def obCol(ob, active, context):
358 ob.color = active.color
361 def obMas(ob, active, context):
362 ob.game.mass = active.game.mass
363 return('INFO', "mass copied")
366 def obLok(ob, active, context):
367 for index, state in enumerate(active.lock_location):
368 ob.lock_location[index] = state
369 for index, state in enumerate(active.lock_rotation):
370 ob.lock_rotation[index] = state
371 ob.lock_rotations_4d = active.lock_rotations_4d
372 ob.lock_rotation_w = active.lock_rotation_w
373 for index, state in enumerate(active.lock_scale):
374 ob.lock_scale[index] = state
375 return('INFO', "transform locks copied")
378 def obCon(ob, active, context):
379 #for consistency with 2.49, delete old constraints first
380 for removeconst in ob.constraints:
381 ob.constraints.remove(removeconst)
382 for old_constraint in active.constraints.values():
383 new_constraint = ob.constraints.new(old_constraint.type)
384 generic_copy(old_constraint, new_constraint)
385 return('INFO', "constraints copied")
388 def obTex(ob, active, context):
389 if 'texspace_location' in dir(ob.data) and 'texspace_location' in dir(
390 active.data):
391 ob.data.texspace_location[:] = active.data.texspace_location[:]
392 if 'texspace_size' in dir(ob.data) and 'texspace_size' in dir(active.data):
393 ob.data.texspace_size[:] = active.data.texspace_size[:]
394 return('INFO', "texture space copied")
397 def obIdx(ob, active, context):
398 ob.pass_index = active.pass_index
399 return('INFO', "pass index copied")
402 def obMod(ob, active, context):
403 for modifier in ob.modifiers:
404 #remove existing before adding new:
405 ob.modifiers.remove(modifier)
406 for old_modifier in active.modifiers.values():
407 new_modifier = ob.modifiers.new(name=old_modifier.name,
408 type=old_modifier.type)
409 generic_copy(old_modifier, new_modifier)
410 return('INFO', "modifiers copied")
413 def obGrp(ob, active, context):
414 for grp in bpy.data.groups:
415 if active.name in grp.objects and ob.name not in grp.objects:
416 grp.objects.link(ob)
417 return('INFO', "groups copied")
420 def obWei(ob, active, context):
421 me_source = active.data
422 me_target = ob.data
423 # sanity check: do source and target have the same amount of verts?
424 if len(me_source.vertices) != len(me_target.vertices):
425 return('ERROR', "objects have different vertex counts, doing nothing")
426 vgroups_IndexName = {}
427 for i in range(0, len(active.vertex_groups)):
428 groups = active.vertex_groups[i]
429 vgroups_IndexName[groups.index] = groups.name
430 data = {} # vert_indices, [(vgroup_index, weights)]
431 for v in me_source.vertices:
432 vg = v.groups
433 vi = v.index
434 if len(vg) > 0:
435 vgroup_collect = []
436 for i in range(0, len(vg)):
437 vgroup_collect.append((vg[i].group, vg[i].weight))
438 data[vi] = vgroup_collect
439 # write data to target
440 if ob != active:
441 # add missing vertex groups
442 for vgroup_name in vgroups_IndexName.values():
443 #check if group already exists...
444 already_present = 0
445 for i in range(0, len(ob.vertex_groups)):
446 if ob.vertex_groups[i].name == vgroup_name:
447 already_present = 1
448 # ... if not, then add
449 if already_present == 0:
450 ob.vertex_groups.new(name=vgroup_name)
451 # write weights
452 for v in me_target.vertices:
453 for vi_source, vgroupIndex_weight in data.items():
454 if v.index == vi_source:
456 for i in range(0, len(vgroupIndex_weight)):
457 groupName = vgroups_IndexName[vgroupIndex_weight[i][0]]
458 groups = ob.vertex_groups
459 for vgs in range(0, len(groups)):
460 if groups[vgs].name == groupName:
461 groups[vgs].add((v.index,),
462 vgroupIndex_weight[i][1], "REPLACE")
463 return('INFO', "weights copied")
465 object_copies = (
466 #('obj_loc', "Location",
467 #"Copy Location from Active to Selected", obLoc),
468 #('obj_rot', "Rotation",
469 #"Copy Rotation from Active to Selected", obRot),
470 #('obj_sca', "Scale",
471 #"Copy Scale from Active to Selected", obSca),
472 ('obj_vis_loc', "Location",
473 "Copy Location from Active to Selected", obVisLoc),
474 ('obj_vis_rot', "Rotation",
475 "Copy Rotation from Active to Selected", obVisRot),
476 ('obj_vis_sca', "Scale",
477 "Copy Scale from Active to Selected", obVisSca),
478 ('obj_drw', "Draw Options",
479 "Copy Draw Options from Active to Selected", obDrw),
480 ('obj_ofs', "Time Offset",
481 "Copy Time Offset from Active to Selected", obOfs),
482 ('obj_dup', "Dupli",
483 "Copy Dupli from Active to Selected", obDup),
484 ('obj_col', "Object Color",
485 "Copy Object Color from Active to Selected", obCol),
486 ('obj_mas', "Mass",
487 "Copy Mass from Active to Selected", obMas),
488 #('obj_dmp', "Damping",
489 #"Copy Damping from Active to Selected"),
490 #('obj_all', "All Physical Attributes",
491 #"Copy Physical Attributes from Active to Selected"),
492 #('obj_prp', "Properties",
493 #"Copy Properties from Active to Selected"),
494 #('obj_log', "Logic Bricks",
495 #"Copy Logic Bricks from Active to Selected"),
496 ('obj_lok', "Protected Transform",
497 "Copy Protected Tranforms from Active to Selected", obLok),
498 ('obj_con', "Object Constraints",
499 "Copy Object Constraints from Active to Selected", obCon),
500 #('obj_nla', "NLA Strips",
501 #"Copy NLA Strips from Active to Selected"),
502 #('obj_tex', "Texture Space",
503 #"Copy Texture Space from Active to Selected", obTex),
504 #('obj_sub', "Subsurf Settings",
505 #"Copy Subsurf Setings from Active to Selected"),
506 #('obj_smo', "AutoSmooth",
507 #"Copy AutoSmooth from Active to Selected"),
508 ('obj_idx', "Pass Index",
509 "Copy Pass Index from Active to Selected", obIdx),
510 ('obj_mod', "Modifiers",
511 "Copy Modifiers from Active to Selected", obMod),
512 ('obj_wei', "Vertex Weights",
513 "Copy vertex weights based on indices", obWei),
514 ('obj_grp', "Group Links",
515 "Copy selected into active object's groups", obGrp))
518 @classmethod
519 def object_poll_func(cls, context):
520 return(len(context.selected_objects) > 1)
523 def object_invoke_func(self, context, event):
524 wm = context.window_manager
525 wm.invoke_props_dialog(self)
526 return {'RUNNING_MODAL'}
529 class CopySelectedObjectConstraints(bpy.types.Operator):
530 """Copy Chosen constraints from active to selected"""
531 bl_idname = "object.copy_selected_constraints"
532 bl_label = "Copy Selected Constraints"
533 selection = bpy.props.BoolVectorProperty(size=32, options={'SKIP_SAVE'})
535 poll = object_poll_func
537 invoke = object_invoke_func
539 def draw(self, context):
540 layout = self.layout
541 for idx, const in enumerate(context.active_object.constraints):
542 layout.prop(self, "selection", index=idx, text=const.name,
543 toggle=True)
545 def execute(self, context):
546 active = context.active_object
547 selected = context.selected_objects[:]
548 selected.remove(active)
549 for obj in selected:
550 for index, flag in enumerate(self.selection):
551 if flag:
552 old_constraint = active.constraints[index]
553 new_constraint = obj.constraints.new(\
554 active.constraints[index].type)
555 generic_copy(old_constraint, new_constraint)
556 return{'FINISHED'}
559 class CopySelectedObjectModifiers(bpy.types.Operator):
560 """Copy Chosen modifiers from active to selected"""
561 bl_idname = "object.copy_selected_modifiers"
562 bl_label = "Copy Selected Modifiers"
563 selection = bpy.props.BoolVectorProperty(size=32, options={'SKIP_SAVE'})
565 poll = object_poll_func
567 invoke = object_invoke_func
569 def draw(self, context):
570 layout = self.layout
571 for idx, const in enumerate(context.active_object.modifiers):
572 layout.prop(self, 'selection', index=idx, text=const.name,
573 toggle=True)
575 def execute(self, context):
576 active = context.active_object
577 selected = context.selected_objects[:]
578 selected.remove(active)
579 for obj in selected:
580 for index, flag in enumerate(self.selection):
581 if flag:
582 old_modifier = active.modifiers[index]
583 new_modifier = obj.modifiers.new(\
584 type=active.modifiers[index].type,
585 name=active.modifiers[index].name)
586 generic_copy(old_modifier, new_modifier)
587 return{'FINISHED'}
589 object_ops = []
590 genops(object_copies, object_ops, "object.copy_", object_poll_func, obLoopExec)
593 class VIEW3D_MT_copypopup(bpy.types.Menu):
594 bl_label = "Copy Attributes"
596 def draw(self, context):
597 layout = self.layout
598 layout.operator_context = 'INVOKE_REGION_WIN'
599 for op in object_copies:
600 layout.operator("object.copy_" + op[0])
601 layout.operator("object.copy_selected_constraints")
602 layout.operator("object.copy_selected_modifiers")
604 #Begin Mesh copy settings:
607 class MESH_MT_CopyFaceSettings(bpy.types.Menu):
608 bl_label = "Copy Face Settings"
610 @classmethod
611 def poll(cls, context):
612 return context.mode == 'EDIT_MESH'
614 def draw(self, context):
615 mesh = context.object.data
616 uv = len(mesh.uv_textures) > 1
617 vc = len(mesh.vertex_colors) > 1
618 layout = self.layout
620 op = layout.operator(MESH_OT_CopyFaceSettings.bl_idname,
621 text="Copy Material")
622 op['layer'] = ''
623 op['mode'] = 'MAT'
624 if mesh.uv_textures.active:
625 op = layout.operator(MESH_OT_CopyFaceSettings.bl_idname,
626 text="Copy Image")
627 op['layer'] = ''
628 op['mode'] = 'IMAGE'
629 op = layout.operator(MESH_OT_CopyFaceSettings.bl_idname,
630 text="Copy UV Coords")
631 op['layer'] = ''
632 op['mode'] = 'UV'
633 if mesh.vertex_colors.active:
634 op = layout.operator(MESH_OT_CopyFaceSettings.bl_idname,
635 text="Copy Vertex Colors")
636 op['layer'] = ''
637 op['mode'] = 'VCOL'
638 if uv or vc:
639 layout.separator()
640 if uv:
641 layout.menu("MESH_MT_CopyImagesFromLayer")
642 layout.menu("MESH_MT_CopyUVCoordsFromLayer")
643 if vc:
644 layout.menu("MESH_MT_CopyVertexColorsFromLayer")
647 def _buildmenu(self, mesh, mode):
648 layout = self.layout
649 if mode == 'VCOL':
650 layers = mesh.vertex_colors
651 else:
652 layers = mesh.uv_textures
653 for layer in layers:
654 if not layer.active:
655 op = layout.operator(MESH_OT_CopyFaceSettings.bl_idname,
656 text=layer.name)
657 op['layer'] = layer.name
658 op['mode'] = mode
661 @classmethod
662 def _poll_layer_uvs(cls, context):
663 return context.mode == "EDIT_MESH" and len(
664 context.object.data.uv_layers) > 1
667 @classmethod
668 def _poll_layer_vcols(cls, context):
669 return context.mode == "EDIT_MESH" and len(
670 context.object.data.vertex_colors) > 1
673 def _build_draw(mode):
674 return (lambda self, context: _buildmenu(self, context.object.data, mode))
676 _layer_menu_data = (("UV Coords", _build_draw("UV"), _poll_layer_uvs),
677 ("Images", _build_draw("IMAGE"), _poll_layer_uvs),
678 ("Vertex Colors", _build_draw("VCOL"), _poll_layer_vcols))
679 _layer_menus = []
680 for name, draw_func, poll_func in _layer_menu_data:
681 classname = "MESH_MT_Copy" + "".join(name.split()) + "FromLayer"
682 menuclass = type(classname, (bpy.types.Menu,),
683 dict(bl_label="Copy " + name + " from layer",
684 bl_idname=classname,
685 draw=draw_func,
686 poll=poll_func))
687 _layer_menus.append(menuclass)
690 class MESH_OT_CopyFaceSettings(bpy.types.Operator):
691 """Copy settings from active face to all selected faces"""
692 bl_idname = 'mesh.copy_face_settings'
693 bl_label = "Copy Face Settings"
694 bl_options = {'REGISTER', 'UNDO'}
696 mode = bpy.props.StringProperty(name="mode")
697 layer = bpy.props.StringProperty(name="layer")
699 @classmethod
700 def poll(cls, context):
701 return context.mode == 'EDIT_MESH'
703 def execute(self, context):
704 mode = getattr(self, 'mode', '')
705 if not mode in {'MAT', 'VCOL', 'IMAGE', 'UV'}:
706 self.report({'ERROR'}, "No mode specified or invalid mode.")
707 return self._end(context, {'CANCELLED'})
708 layername = getattr(self, 'layer', '')
709 mesh = context.object.data
711 # Switching out of edit mode updates the selected state of faces and
712 # makes the data from the uv texture and vertex color layers available.
713 bpy.ops.object.editmode_toggle()
715 polys = mesh.polygons
716 if mode == 'MAT':
717 to_data = from_data = polys
718 else:
719 if mode == 'VCOL':
720 layers = mesh.vertex_colors
721 act_layer = mesh.vertex_colors.active
722 elif mode == 'IMAGE':
723 layers = mesh.uv_textures
724 act_layer = mesh.uv_textures.active
725 elif mode == 'UV':
726 layers = mesh.uv_layers
727 act_layer = mesh.uv_layers.active
728 if not layers or (layername and not layername in layers):
729 self.report({'ERROR'}, "Invalid UV or color layer.")
730 return self._end(context, {'CANCELLED'})
731 from_data = layers[layername or act_layer.name].data
732 to_data = act_layer.data
733 from_index = polys.active
735 for f in polys:
736 if f.select:
737 if to_data != from_data:
738 # Copying from another layer.
739 # from_face is to_face's counterpart from other layer.
740 from_index = f.index
741 elif f.index == from_index:
742 # Otherwise skip copying a face to itself.
743 continue
744 if mode == 'MAT':
745 f.material_index = polys[from_index].material_index
746 continue
747 elif mode == 'IMAGE':
748 to_data[f.index].image = from_data[from_index].image
749 continue
750 if len(f.loop_indices) != len(polys[from_index].loop_indices):
751 self.report({'WARNING'}, "Different number of vertices.")
752 for i in range(len(f.loop_indices)):
753 to_vertex = f.loop_indices[i]
754 from_vertex = polys[from_index].loop_indices[i]
755 if mode == 'VCOL':
756 to_data[to_vertex].color = from_data[from_vertex].color
757 elif mode == 'UV':
758 to_data[to_vertex].uv = from_data[from_vertex].uv
760 return self._end(context, {'FINISHED'})
762 def _end(self, context, retval):
763 if context.mode != 'EDIT_MESH':
764 # Clean up by returning to edit mode like it was before.
765 bpy.ops.object.editmode_toggle()
766 return(retval)
769 def register():
770 bpy.utils.register_module(__name__)
772 ''' mostly to get the keymap working '''
773 kc = bpy.context.window_manager.keyconfigs.addon
774 if kc:
775 km = kc.keymaps.new(name="Object Mode")
776 kmi = km.keymap_items.new('wm.call_menu', 'C', 'PRESS', ctrl=True)
777 kmi.properties.name = 'VIEW3D_MT_copypopup'
779 km = kc.keymaps.new(name="Pose")
780 kmi = km.keymap_items.get("pose.copy")
781 if kmi is not None:
782 kmi.idname = 'wm.call_menu'
783 else:
784 kmi = km.keymap_items.new('wm.call_menu', 'C', 'PRESS', ctrl=True)
785 kmi.properties.name = 'VIEW3D_MT_posecopypopup'
786 for menu in _layer_menus:
787 bpy.utils.register_class(menu)
789 km = kc.keymaps.new(name="Mesh")
790 kmi = km.keymap_items.new('wm.call_menu', 'C', 'PRESS')
791 kmi.ctrl = True
792 kmi.properties.name = 'MESH_MT_CopyFaceSettings'
795 def unregister():
796 bpy.utils.unregister_module(__name__)
798 ''' mostly to remove the keymap '''
799 kc = bpy.context.window_manager.keyconfigs.addon
800 if kc:
801 kms = kc.keymaps['Pose']
802 for item in kms.keymap_items:
803 if item.name == 'Call Menu' and item.idname == 'wm.call_menu' and \
804 item.properties.name == 'VIEW3D_MT_posecopypopup':
805 item.idname = 'pose.copy'
806 break
807 for menu in _layer_menus:
808 bpy.utils.unregister_class(menu)
809 km = kc.keymaps['Mesh']
810 for kmi in km.keymap_items:
811 if kmi.idname == 'wm.call_menu':
812 if kmi.properties.name == 'MESH_MT_CopyFaceSettings':
813 km.keymap_items.remove(kmi)
815 km = kc.keymaps['Object Mode']
816 for kmi in km.keymap_items:
817 if kmi.idname == 'wm.call_menu':
818 if kmi.properties.name == 'VIEW3D_MT_copypopup':
819 km.keymap_items.remove(kmi)
821 if __name__ == "__main__":
822 register()