Cleanup: strip trailing space, remove BOM
[blender-addons.git] / space_view3d_copy_attributes.py
blob2d1fff59da2135c1fa0f5cda5fbf7736b25429d9
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, 9),
25 "blender": (2, 80, 0),
26 "location": "View3D > Ctrl-C",
27 "description": "Copy Attributes Menu from Blender 2.4",
28 "doc_url": "{BLENDER_MANUAL_URL}/addons/interface/copy_attributes.html",
29 "category": "Interface",
32 import bpy
33 from mathutils import Matrix
34 from bpy.types import (
35 Operator,
36 Menu,
38 from bpy.props import (
39 BoolVectorProperty,
40 StringProperty,
43 # First part of the operator Info message
44 INFO_MESSAGE = "Copy Attributes: "
47 def build_exec(loopfunc, func):
48 """Generator function that returns exec functions for operators """
50 def exec_func(self, context):
51 loopfunc(self, context, func)
52 return {'FINISHED'}
53 return exec_func
56 def build_invoke(loopfunc, func):
57 """Generator function that returns invoke functions for operators"""
59 def invoke_func(self, context, event):
60 loopfunc(self, context, func)
61 return {'FINISHED'}
62 return invoke_func
65 def build_op(idname, label, description, fpoll, fexec, finvoke):
66 """Generator function that returns the basic operator"""
68 class myopic(Operator):
69 bl_idname = idname
70 bl_label = label
71 bl_description = description
72 execute = fexec
73 poll = fpoll
74 invoke = finvoke
75 return myopic
78 def genops(copylist, oplist, prefix, poll_func, loopfunc):
79 """Generate ops from the copy list and its associated functions"""
80 for op in copylist:
81 exec_func = build_exec(loopfunc, op[3])
82 invoke_func = build_invoke(loopfunc, op[3])
83 opclass = build_op(prefix + op[0], "Copy " + op[1], op[2],
84 poll_func, exec_func, invoke_func)
85 oplist.append(opclass)
88 def generic_copy(source, target, string=""):
89 """Copy attributes from source to target that have string in them"""
90 for attr in dir(source):
91 if attr.find(string) > -1:
92 try:
93 setattr(target, attr, getattr(source, attr))
94 except:
95 pass
96 return
99 def getmat(bone, active, context, ignoreparent):
100 """Helper function for visual transform copy,
101 gets the active transform in bone space
103 obj_bone = bone.id_data
104 obj_active = active.id_data
105 data_bone = obj_bone.data.bones[bone.name]
106 # all matrices are in armature space unless commented otherwise
107 active_to_selected = obj_bone.matrix_world.inverted() @ obj_active.matrix_world
108 active_matrix = active_to_selected @ active.matrix
109 otherloc = active_matrix # final 4x4 mat of target, location.
110 bonemat_local = data_bone.matrix_local.copy() # self rest matrix
111 if data_bone.parent:
112 parentposemat = obj_bone.pose.bones[data_bone.parent.name].matrix.copy()
113 parentbonemat = data_bone.parent.matrix_local.copy()
114 else:
115 parentposemat = parentbonemat = Matrix()
116 if parentbonemat == parentposemat or ignoreparent:
117 newmat = bonemat_local.inverted() @ otherloc
118 else:
119 bonemat = parentbonemat.inverted() @ bonemat_local
121 newmat = bonemat.inverted() @ parentposemat.inverted() @ otherloc
122 return newmat
125 def rotcopy(item, mat):
126 """Copy rotation to item from matrix mat depending on item.rotation_mode"""
127 if item.rotation_mode == 'QUATERNION':
128 item.rotation_quaternion = mat.to_3x3().to_quaternion()
129 elif item.rotation_mode == 'AXIS_ANGLE':
130 rot = mat.to_3x3().to_quaternion().to_axis_angle() # returns (Vector((x, y, z)), w)
131 axis_angle = rot[1], rot[0][0], rot[0][1], rot[0][2] # convert to w, x, y, z
132 item.rotation_axis_angle = axis_angle
133 else:
134 item.rotation_euler = mat.to_3x3().to_euler(item.rotation_mode)
137 def pLoopExec(self, context, funk):
138 """Loop over selected bones and execute funk on them"""
139 active = context.active_pose_bone
140 selected = context.selected_pose_bones
141 selected.remove(active)
142 for bone in selected:
143 funk(bone, active, context)
146 # The following functions are used to copy attributes from active to bone
148 def pLocLocExec(bone, active, context):
149 bone.location = active.location
152 def pLocRotExec(bone, active, context):
153 rotcopy(bone, active.matrix_basis.to_3x3())
156 def pLocScaExec(bone, active, context):
157 bone.scale = active.scale
160 def pVisLocExec(bone, active, context):
161 bone.location = getmat(bone, active, context, False).to_translation()
164 def pVisRotExec(bone, active, context):
165 obj_bone = bone.id_data
166 rotcopy(bone, getmat(bone, active,
167 context, not obj_bone.data.bones[bone.name].use_inherit_rotation))
170 def pVisScaExec(bone, active, context):
171 obj_bone = bone.id_data
172 bone.scale = getmat(bone, active, context,
173 not obj_bone.data.bones[bone.name].use_inherit_scale)\
174 .to_scale()
177 def pDrwExec(bone, active, context):
178 bone.custom_shape = active.custom_shape
179 bone.use_custom_shape_bone_size = active.use_custom_shape_bone_size
180 bone.custom_shape_translation = active.custom_shape_translation
181 bone.custom_shape_rotation_euler = active.custom_shape_rotation_euler
182 bone.custom_shape_scale_xyz = active.custom_shape_scale_xyz
183 bone.bone.show_wire = active.bone.show_wire
186 def pLokExec(bone, active, context):
187 for index, state in enumerate(active.lock_location):
188 bone.lock_location[index] = state
189 for index, state in enumerate(active.lock_rotation):
190 bone.lock_rotation[index] = state
191 bone.lock_rotations_4d = active.lock_rotations_4d
192 bone.lock_rotation_w = active.lock_rotation_w
193 for index, state in enumerate(active.lock_scale):
194 bone.lock_scale[index] = state
197 def pConExec(bone, active, context):
198 for old_constraint in active.constraints.values():
199 new_constraint = bone.constraints.new(old_constraint.type)
200 generic_copy(old_constraint, new_constraint)
203 def pIKsExec(bone, active, context):
204 generic_copy(active, bone, "ik_")
207 def pBBonesExec(bone, active, context):
208 object = active.id_data
209 generic_copy(
210 object.data.bones[active.name],
211 object.data.bones[bone.name],
212 "bbone_")
215 pose_copies = (
216 ('pose_loc_loc', "Local Location",
217 "Copy Location from Active to Selected", pLocLocExec),
218 ('pose_loc_rot', "Local Rotation",
219 "Copy Rotation from Active to Selected", pLocRotExec),
220 ('pose_loc_sca', "Local Scale",
221 "Copy Scale from Active to Selected", pLocScaExec),
222 ('pose_vis_loc', "Visual Location",
223 "Copy Location from Active to Selected", pVisLocExec),
224 ('pose_vis_rot', "Visual Rotation",
225 "Copy Rotation from Active to Selected", pVisRotExec),
226 ('pose_vis_sca', "Visual Scale",
227 "Copy Scale from Active to Selected", pVisScaExec),
228 ('pose_drw', "Bone Shape",
229 "Copy Bone Shape from Active to Selected", pDrwExec),
230 ('pose_lok', "Protected Transform",
231 "Copy Protected Transforms from Active to Selected", pLokExec),
232 ('pose_con', "Bone Constraints",
233 "Copy Object Constraints from Active to Selected", pConExec),
234 ('pose_iks', "IK Limits",
235 "Copy IK Limits from Active to Selected", pIKsExec),
236 ('bbone_settings', "BBone Settings",
237 "Copy BBone Settings from Active to Selected", pBBonesExec),
240 @classmethod
241 def pose_poll_func(cls, context):
242 return(context.mode == 'POSE')
245 def pose_invoke_func(self, context, event):
246 wm = context.window_manager
247 wm.invoke_props_dialog(self)
248 return {'RUNNING_MODAL'}
251 class CopySelectedPoseConstraints(Operator):
252 """Copy Chosen constraints from active to selected"""
253 bl_idname = "pose.copy_selected_constraints"
254 bl_label = "Copy Selected Constraints"
256 selection: BoolVectorProperty(
257 size=32,
258 options={'SKIP_SAVE'}
261 poll = pose_poll_func
262 invoke = pose_invoke_func
264 def draw(self, context):
265 layout = self.layout
266 for idx, const in enumerate(context.active_pose_bone.constraints):
267 layout.prop(self, "selection", index=idx, text=const.name,
268 toggle=True)
270 def execute(self, context):
271 active = context.active_pose_bone
272 selected = context.selected_pose_bones[:]
273 selected.remove(active)
274 for bone in selected:
275 for index, flag in enumerate(self.selection):
276 if flag:
277 bone.constraints.copy(active.constraints[index])
278 return {'FINISHED'}
281 pose_ops = [] # list of pose mode copy operators
282 genops(pose_copies, pose_ops, "pose.copy_", pose_poll_func, pLoopExec)
285 class VIEW3D_MT_posecopypopup(Menu):
286 bl_label = "Copy Attributes"
288 def draw(self, context):
289 layout = self.layout
290 layout.operator_context = 'INVOKE_REGION_WIN'
291 for op in pose_copies:
292 layout.operator("pose.copy_" + op[0])
293 layout.operator("pose.copy_selected_constraints")
294 layout.operator("pose.copy", text="copy pose")
297 def obLoopExec(self, context, funk):
298 """Loop over selected objects and execute funk on them"""
299 active = context.active_object
300 selected = context.selected_objects[:]
301 selected.remove(active)
302 for obj in selected:
303 msg = funk(obj, active, context)
304 if msg:
305 self.report({msg[0]}, INFO_MESSAGE + msg[1])
308 def world_to_basis(active, ob, context):
309 """put world coords of active as basis coords of ob"""
310 local = ob.parent.matrix_world.inverted() @ active.matrix_world
311 P = ob.matrix_basis @ ob.matrix_local.inverted()
312 mat = P @ local
313 return(mat)
316 # The following functions are used to copy attributes from
317 # active to selected object
319 def obLoc(ob, active, context):
320 ob.location = active.location
323 def obRot(ob, active, context):
324 rotcopy(ob, active.matrix_local.to_3x3())
327 def obSca(ob, active, context):
328 ob.scale = active.scale
331 def obVisLoc(ob, active, context):
332 if ob.parent:
333 mat = world_to_basis(active, ob, context)
334 ob.location = mat.to_translation()
335 else:
336 ob.location = active.matrix_world.to_translation()
337 return('INFO', "Object location copied")
340 def obVisRot(ob, active, context):
341 if ob.parent:
342 mat = world_to_basis(active, ob, context)
343 rotcopy(ob, mat.to_3x3())
344 else:
345 rotcopy(ob, active.matrix_world.to_3x3())
346 return('INFO', "Object rotation copied")
349 def obVisSca(ob, active, context):
350 if ob.parent:
351 mat = world_to_basis(active, ob, context)
352 ob.scale = mat.to_scale()
353 else:
354 ob.scale = active.matrix_world.to_scale()
355 return('INFO', "Object scale copied")
358 def obDrw(ob, active, context):
359 ob.display_type = active.display_type
360 ob.show_axis = active.show_axis
361 ob.show_bounds = active.show_bounds
362 ob.display_bounds_type = active.display_bounds_type
363 ob.show_name = active.show_name
364 ob.show_texture_space = active.show_texture_space
365 ob.show_transparent = active.show_transparent
366 ob.show_wire = active.show_wire
367 ob.show_in_front = active.show_in_front
368 ob.empty_display_type = active.empty_display_type
369 ob.empty_display_size = active.empty_display_size
372 def obOfs(ob, active, context):
373 ob.time_offset = active.time_offset
374 return('INFO', "Time offset copied")
377 def obDup(ob, active, context):
378 generic_copy(active, ob, "dupli")
379 return('INFO', "Duplication method copied")
382 def obCol(ob, active, context):
383 ob.color = active.color
386 def obLok(ob, active, context):
387 for index, state in enumerate(active.lock_location):
388 ob.lock_location[index] = state
389 for index, state in enumerate(active.lock_rotation):
390 ob.lock_rotation[index] = state
391 ob.lock_rotations_4d = active.lock_rotations_4d
392 ob.lock_rotation_w = active.lock_rotation_w
393 for index, state in enumerate(active.lock_scale):
394 ob.lock_scale[index] = state
395 return('INFO', "Transform locks copied")
398 def obCon(ob, active, context):
399 # for consistency with 2.49, delete old constraints first
400 for removeconst in ob.constraints:
401 ob.constraints.remove(removeconst)
402 for old_constraint in active.constraints.values():
403 new_constraint = ob.constraints.new(old_constraint.type)
404 generic_copy(old_constraint, new_constraint)
405 return('INFO', "Constraints copied")
408 def obTex(ob, active, context):
409 if 'texspace_location' in dir(ob.data) and 'texspace_location' in dir(
410 active.data):
411 ob.data.texspace_location[:] = active.data.texspace_location[:]
412 if 'texspace_size' in dir(ob.data) and 'texspace_size' in dir(active.data):
413 ob.data.texspace_size[:] = active.data.texspace_size[:]
414 return('INFO', "Texture space copied")
417 def obIdx(ob, active, context):
418 ob.pass_index = active.pass_index
419 return('INFO', "Pass index copied")
422 def obMod(ob, active, context):
423 for modifier in ob.modifiers:
424 # remove existing before adding new:
425 ob.modifiers.remove(modifier)
426 for old_modifier in active.modifiers.values():
427 new_modifier = ob.modifiers.new(name=old_modifier.name,
428 type=old_modifier.type)
429 generic_copy(old_modifier, new_modifier)
430 return('INFO', "Modifiers copied")
433 def obGrp(ob, active, context):
434 for grp in bpy.data.collections:
435 if active.name in grp.objects and ob.name not in grp.objects:
436 grp.objects.link(ob)
437 return('INFO', "Groups copied")
440 def obWei(ob, active, context):
441 # sanity check: are source and target both mesh objects?
442 if ob.type != 'MESH' or active.type != 'MESH':
443 return('ERROR', "objects have to be of mesh type, doing nothing")
444 me_source = active.data
445 me_target = ob.data
446 # sanity check: do source and target have the same amount of verts?
447 if len(me_source.vertices) != len(me_target.vertices):
448 return('ERROR', "objects have different vertex counts, doing nothing")
449 vgroups_IndexName = {}
450 for i in range(0, len(active.vertex_groups)):
451 groups = active.vertex_groups[i]
452 vgroups_IndexName[groups.index] = groups.name
453 data = {} # vert_indices, [(vgroup_index, weights)]
454 for v in me_source.vertices:
455 vg = v.groups
456 vi = v.index
457 if len(vg) > 0:
458 vgroup_collect = []
459 for i in range(0, len(vg)):
460 vgroup_collect.append((vg[i].group, vg[i].weight))
461 data[vi] = vgroup_collect
462 # write data to target
463 if ob != active:
464 # add missing vertex groups
465 for vgroup_name in vgroups_IndexName.values():
466 # check if group already exists...
467 already_present = 0
468 for i in range(0, len(ob.vertex_groups)):
469 if ob.vertex_groups[i].name == vgroup_name:
470 already_present = 1
471 # ... if not, then add
472 if already_present == 0:
473 ob.vertex_groups.new(name=vgroup_name)
474 # write weights
475 for v in me_target.vertices:
476 for vi_source, vgroupIndex_weight in data.items():
477 if v.index == vi_source:
479 for i in range(0, len(vgroupIndex_weight)):
480 groupName = vgroups_IndexName[vgroupIndex_weight[i][0]]
481 groups = ob.vertex_groups
482 for vgs in range(0, len(groups)):
483 if groups[vgs].name == groupName:
484 groups[vgs].add((v.index,),
485 vgroupIndex_weight[i][1], "REPLACE")
486 return('INFO', "Weights copied")
489 object_copies = (
490 # ('obj_loc', "Location",
491 # "Copy Location from Active to Selected", obLoc),
492 # ('obj_rot', "Rotation",
493 # "Copy Rotation from Active to Selected", obRot),
494 # ('obj_sca', "Scale",
495 # "Copy Scale from Active to Selected", obSca),
496 ('obj_vis_loc', "Location",
497 "Copy Location from Active to Selected", obVisLoc),
498 ('obj_vis_rot', "Rotation",
499 "Copy Rotation from Active to Selected", obVisRot),
500 ('obj_vis_sca', "Scale",
501 "Copy Scale from Active to Selected", obVisSca),
502 ('obj_drw', "Draw Options",
503 "Copy Draw Options from Active to Selected", obDrw),
504 ('obj_ofs', "Time Offset",
505 "Copy Time Offset from Active to Selected", obOfs),
506 ('obj_dup', "Dupli",
507 "Copy Dupli from Active to Selected", obDup),
508 ('obj_col', "Object Color",
509 "Copy Object Color from Active to Selected", obCol),
510 # ('obj_dmp', "Damping",
511 # "Copy Damping from Active to Selected"),
512 # ('obj_all', "All Physical Attributes",
513 # "Copy Physical Attributes from Active to Selected"),
514 # ('obj_prp', "Properties",
515 # "Copy Properties from Active to Selected"),
516 # ('obj_log', "Logic Bricks",
517 # "Copy Logic Bricks from Active to Selected"),
518 ('obj_lok', "Protected Transform",
519 "Copy Protected Transforms from Active to Selected", obLok),
520 ('obj_con', "Object Constraints",
521 "Copy Object Constraints from Active to Selected", obCon),
522 # ('obj_nla', "NLA Strips",
523 # "Copy NLA Strips from Active to Selected"),
524 # ('obj_tex', "Texture Space",
525 # "Copy Texture Space from Active to Selected", obTex),
526 # ('obj_sub', "Subdivision Surface Settings",
527 # "Copy Subdivision Surface Settings from Active to Selected"),
528 # ('obj_smo', "AutoSmooth",
529 # "Copy AutoSmooth from Active to Selected"),
530 ('obj_idx', "Pass Index",
531 "Copy Pass Index from Active to Selected", obIdx),
532 ('obj_mod', "Modifiers",
533 "Copy Modifiers from Active to Selected", obMod),
534 ('obj_wei', "Vertex Weights",
535 "Copy vertex weights based on indices", obWei),
536 ('obj_grp', "Group Links",
537 "Copy selected into active object's groups", obGrp)
541 @classmethod
542 def object_poll_func(cls, context):
543 return (len(context.selected_objects) > 1)
546 def object_invoke_func(self, context, event):
547 wm = context.window_manager
548 wm.invoke_props_dialog(self)
549 return {'RUNNING_MODAL'}
552 class CopySelectedObjectConstraints(Operator):
553 """Copy Chosen constraints from active to selected"""
554 bl_idname = "object.copy_selected_constraints"
555 bl_label = "Copy Selected Constraints"
557 selection: BoolVectorProperty(
558 size=32,
559 options={'SKIP_SAVE'}
562 poll = object_poll_func
563 invoke = object_invoke_func
565 def draw(self, context):
566 layout = self.layout
567 for idx, const in enumerate(context.active_object.constraints):
568 layout.prop(self, "selection", index=idx, text=const.name,
569 toggle=True)
571 def execute(self, context):
572 active = context.active_object
573 selected = context.selected_objects[:]
574 selected.remove(active)
575 for obj in selected:
576 for index, flag in enumerate(self.selection):
577 if flag:
578 old_constraint = active.constraints[index]
579 new_constraint = obj.constraints.new(
580 active.constraints[index].type
582 generic_copy(old_constraint, new_constraint)
583 return{'FINISHED'}
586 class CopySelectedObjectModifiers(Operator):
587 """Copy Chosen modifiers from active to selected"""
588 bl_idname = "object.copy_selected_modifiers"
589 bl_label = "Copy Selected Modifiers"
591 selection: BoolVectorProperty(
592 size=32,
593 options={'SKIP_SAVE'}
596 poll = object_poll_func
597 invoke = object_invoke_func
599 def draw(self, context):
600 layout = self.layout
601 for idx, const in enumerate(context.active_object.modifiers):
602 layout.prop(self, 'selection', index=idx, text=const.name,
603 toggle=True)
605 def execute(self, context):
606 active = context.active_object
607 selected = context.selected_objects[:]
608 selected.remove(active)
609 for obj in selected:
610 for index, flag in enumerate(self.selection):
611 if flag:
612 old_modifier = active.modifiers[index]
613 new_modifier = obj.modifiers.new(
614 type=active.modifiers[index].type,
615 name=active.modifiers[index].name
617 generic_copy(old_modifier, new_modifier)
618 return{'FINISHED'}
621 object_ops = []
622 genops(object_copies, object_ops, "object.copy_", object_poll_func, obLoopExec)
625 class VIEW3D_MT_copypopup(Menu):
626 bl_label = "Copy Attributes"
628 def draw(self, context):
629 layout = self.layout
631 layout.operator_context = 'INVOKE_REGION_WIN'
632 layout.operator("view3d.copybuffer", icon="COPY_ID")
634 if (len(context.selected_objects) <= 1):
635 layout.separator()
636 layout.label(text="Please select at least two objects", icon="INFO")
637 layout.separator()
639 for entry, op in enumerate(object_copies):
640 if entry and entry % 4 == 0:
641 layout.separator()
642 layout.operator("object.copy_" + op[0])
643 layout.operator("object.copy_selected_constraints")
644 layout.operator("object.copy_selected_modifiers")
647 # Begin Mesh copy settings:
649 class MESH_MT_CopyFaceSettings(Menu):
650 bl_label = "Copy Face Settings"
652 @classmethod
653 def poll(cls, context):
654 return context.mode == 'EDIT_MESH'
656 def draw(self, context):
657 mesh = context.object.data
658 uv = len(mesh.uv_layers) > 1
659 vc = len(mesh.vertex_colors) > 1
661 layout = self.layout
663 op = layout.operator(MESH_OT_CopyFaceSettings.bl_idname,
664 text="Copy Material")
665 op['layer'] = ''
666 op['mode'] = 'MAT'
668 if mesh.uv_layers.active:
669 op = layout.operator(MESH_OT_CopyFaceSettings.bl_idname,
670 text="Copy Active UV Coords")
671 op['layer'] = ''
672 op['mode'] = 'UV'
674 if mesh.vertex_colors.active:
675 op = layout.operator(MESH_OT_CopyFaceSettings.bl_idname,
676 text="Copy Active Vertex Colors")
677 op['layer'] = ''
678 op['mode'] = 'VCOL'
680 if uv or vc:
681 layout.separator()
682 if uv:
683 layout.menu("MESH_MT_CopyImagesFromLayer")
684 layout.menu("MESH_MT_CopyUVCoordsFromLayer")
685 if vc:
686 layout.menu("MESH_MT_CopyVertexColorsFromLayer")
689 # Data (UV map, Image and Vertex color) menus calling MESH_OT_CopyFaceSettings
690 # Explicitly defined as using the generator code was broken in case of Menus
691 # causing issues with access and registration
694 class MESH_MT_CopyUVCoordsFromLayer(Menu):
695 bl_label = "Copy Other UV Coord Layers"
697 @classmethod
698 def poll(cls, context):
699 obj = context.active_object
700 return obj and obj.mode == "EDIT_MESH" and len(
701 obj.data.uv_layers) > 1
703 def draw(self, context):
704 mesh = context.active_object.data
705 _buildmenu(self, mesh, 'UV', "GROUP_UVS")
708 class MESH_MT_CopyVertexColorsFromLayer(Menu):
709 bl_label = "Copy Other Vertex Colors Layers"
711 @classmethod
712 def poll(cls, context):
713 obj = context.active_object
714 return obj and obj.mode == "EDIT_MESH" and len(
715 obj.data.vertex_colors) > 1
717 def draw(self, context):
718 mesh = context.active_object.data
719 _buildmenu(self, mesh, 'VCOL', "GROUP_VCOL")
722 def _buildmenu(self, mesh, mode, icon):
723 layout = self.layout
724 if mode == 'VCOL':
725 layers = mesh.vertex_colors
726 else:
727 layers = mesh.uv_layers
728 for layer in layers:
729 if not layer.active:
730 op = layout.operator(MESH_OT_CopyFaceSettings.bl_idname,
731 text=layer.name, icon=icon)
732 op['layer'] = layer.name
733 op['mode'] = mode
736 class MESH_OT_CopyFaceSettings(Operator):
737 """Copy settings from active face to all selected faces"""
738 bl_idname = 'mesh.copy_face_settings'
739 bl_label = "Copy Face Settings"
740 bl_options = {'REGISTER', 'UNDO'}
742 mode: StringProperty(
743 name="Mode",
744 options={"HIDDEN"},
746 layer: StringProperty(
747 name="Layer",
748 options={"HIDDEN"},
751 @classmethod
752 def poll(cls, context):
753 return context.mode == 'EDIT_MESH'
755 def execute(self, context):
756 mode = getattr(self, 'mode', '')
757 if mode not in {'MAT', 'VCOL', 'UV'}:
758 self.report({'ERROR'}, "No mode specified or invalid mode")
759 return self._end(context, {'CANCELLED'})
760 layername = getattr(self, 'layer', '')
761 mesh = context.object.data
763 # Switching out of edit mode updates the selected state of faces and
764 # makes the data from the uv texture and vertex color layers available.
765 bpy.ops.object.editmode_toggle()
767 polys = mesh.polygons
768 if mode == 'MAT':
769 to_data = from_data = polys
770 else:
771 if mode == 'VCOL':
772 layers = mesh.vertex_colors
773 act_layer = mesh.vertex_colors.active
774 elif mode == 'UV':
775 layers = mesh.uv_layers
776 act_layer = mesh.uv_layers.active
777 if not layers or (layername and layername not in layers):
778 self.report({'ERROR'}, "Invalid UV or color layer. Operation Cancelled")
779 return self._end(context, {'CANCELLED'})
780 from_data = layers[layername or act_layer.name].data
781 to_data = act_layer.data
782 from_index = polys.active
784 for f in polys:
785 if f.select:
786 if to_data != from_data:
787 # Copying from another layer.
788 # from_face is to_face's counterpart from other layer.
789 from_index = f.index
790 elif f.index == from_index:
791 # Otherwise skip copying a face to itself.
792 continue
793 if mode == 'MAT':
794 f.material_index = polys[from_index].material_index
795 continue
796 if len(f.loop_indices) != len(polys[from_index].loop_indices):
797 self.report({'WARNING'}, "Different number of vertices.")
798 for i in range(len(f.loop_indices)):
799 to_vertex = f.loop_indices[i]
800 from_vertex = polys[from_index].loop_indices[i]
801 if mode == 'VCOL':
802 to_data[to_vertex].color = from_data[from_vertex].color
803 elif mode == 'UV':
804 to_data[to_vertex].uv = from_data[from_vertex].uv
806 return self._end(context, {'FINISHED'})
808 def _end(self, context, retval):
809 if context.mode != 'EDIT_MESH':
810 # Clean up by returning to edit mode like it was before.
811 bpy.ops.object.editmode_toggle()
812 return(retval)
815 classes = (
816 CopySelectedPoseConstraints,
817 VIEW3D_MT_posecopypopup,
818 CopySelectedObjectConstraints,
819 CopySelectedObjectModifiers,
820 VIEW3D_MT_copypopup,
821 MESH_MT_CopyFaceSettings,
822 MESH_MT_CopyUVCoordsFromLayer,
823 MESH_MT_CopyVertexColorsFromLayer,
824 MESH_OT_CopyFaceSettings,
825 *pose_ops,
826 *object_ops,
829 def register():
830 from bpy.utils import register_class
831 for cls in classes:
832 register_class(cls)
834 # mostly to get the keymap working
835 kc = bpy.context.window_manager.keyconfigs.addon
836 if kc:
837 km = kc.keymaps.new(name="Object Mode")
838 kmi = km.keymap_items.new('wm.call_menu', 'C', 'PRESS', ctrl=True)
839 kmi.properties.name = 'VIEW3D_MT_copypopup'
841 km = kc.keymaps.new(name="Pose")
842 kmi = km.keymap_items.get("pose.copy")
843 if kmi is not None:
844 kmi.idname = 'wm.call_menu'
845 else:
846 kmi = km.keymap_items.new('wm.call_menu', 'C', 'PRESS', ctrl=True)
847 kmi.properties.name = 'VIEW3D_MT_posecopypopup'
849 km = kc.keymaps.new(name="Mesh")
850 kmi = km.keymap_items.new('wm.call_menu', 'C', 'PRESS')
851 kmi.ctrl = True
852 kmi.properties.name = 'MESH_MT_CopyFaceSettings'
855 def unregister():
856 # mostly to remove the keymap
857 kc = bpy.context.window_manager.keyconfigs.addon
858 if kc:
859 kms = kc.keymaps.get('Pose')
860 if kms is not None:
861 for item in kms.keymap_items:
862 if item.name == 'Call Menu' and item.idname == 'wm.call_menu' and \
863 item.properties.name == 'VIEW3D_MT_posecopypopup':
864 item.idname = 'pose.copy'
865 break
867 km = kc.keymaps.get('Mesh')
868 if km is not None:
869 for kmi in km.keymap_items:
870 if kmi.idname == 'wm.call_menu':
871 if kmi.properties.name == 'MESH_MT_CopyFaceSettings':
872 km.keymap_items.remove(kmi)
874 km = kc.keymaps.get('Object Mode')
875 if km is not None:
876 for kmi in km.keymap_items:
877 if kmi.idname == 'wm.call_menu':
878 if kmi.properties.name == 'VIEW3D_MT_copypopup':
879 km.keymap_items.remove(kmi)
881 from bpy.utils import unregister_class
882 for cls in classes:
883 unregister_class(cls)
886 if __name__ == "__main__":
887 register()