Cleanup: quiet float argument to in type warning
[blender-addons.git] / space_view3d_copy_attributes.py
blobaf8cbae550a73c69a96f72e2b76d98c4cbb51ab4
1 # SPDX-License-Identifier: GPL-2.0-or-later
3 bl_info = {
4 "name": "Copy Attributes Menu",
5 "author": "Bassam Kurdali, Fabian Fricke, Adam Wiseman, Demeter Dzadik",
6 "version": (0, 6, 0),
7 "blender": (3, 4, 0),
8 "location": "View3D > Ctrl-C",
9 "description": "Copy Attributes Menu",
10 "doc_url": "{BLENDER_MANUAL_URL}/addons/interface/copy_attributes.html",
11 "category": "Interface",
14 import bpy
15 from mathutils import Matrix
16 from bpy.types import (
17 Operator,
18 Menu,
20 from bpy.props import (
21 BoolVectorProperty,
22 StringProperty,
25 # First part of the operator Info message
26 INFO_MESSAGE = "Copy Attributes: "
29 def build_exec(loopfunc, func):
30 """Generator function that returns exec functions for operators """
32 def exec_func(self, context):
33 loopfunc(self, context, func)
34 return {'FINISHED'}
35 return exec_func
38 def build_invoke(loopfunc, func):
39 """Generator function that returns invoke functions for operators"""
41 def invoke_func(self, context, event):
42 loopfunc(self, context, func)
43 return {'FINISHED'}
44 return invoke_func
47 def build_op(idname, label, description, fpoll, fexec, finvoke):
48 """Generator function that returns the basic operator"""
50 class myopic(Operator):
51 bl_idname = idname
52 bl_label = label
53 bl_description = description
54 execute = fexec
55 poll = fpoll
56 invoke = finvoke
57 return myopic
60 def genops(copylist, oplist, prefix, poll_func, loopfunc):
61 """Generate ops from the copy list and its associated functions"""
62 for op in copylist:
63 exec_func = build_exec(loopfunc, op[3])
64 invoke_func = build_invoke(loopfunc, op[3])
65 opclass = build_op(prefix + op[0], "Copy " + op[1], op[2],
66 poll_func, exec_func, invoke_func)
67 oplist.append(opclass)
70 def generic_copy(source, target, string=""):
71 """Copy attributes from source to target that have string in them"""
72 for attr in dir(source):
73 if attr.find(string) > -1:
74 try:
75 setattr(target, attr, getattr(source, attr))
76 except:
77 pass
78 return
81 def getmat(bone, active, context, ignoreparent):
82 """Helper function for visual transform copy,
83 gets the active transform in bone space
84 """
85 obj_bone = bone.id_data
86 obj_active = active.id_data
87 data_bone = obj_bone.data.bones[bone.name]
88 # all matrices are in armature space unless commented otherwise
89 active_to_selected = obj_bone.matrix_world.inverted() @ obj_active.matrix_world
90 active_matrix = active_to_selected @ active.matrix
91 otherloc = active_matrix # final 4x4 mat of target, location.
92 bonemat_local = data_bone.matrix_local.copy() # self rest matrix
93 if data_bone.parent:
94 parentposemat = obj_bone.pose.bones[data_bone.parent.name].matrix.copy()
95 parentbonemat = data_bone.parent.matrix_local.copy()
96 else:
97 parentposemat = parentbonemat = Matrix()
98 if parentbonemat == parentposemat or ignoreparent:
99 newmat = bonemat_local.inverted() @ otherloc
100 else:
101 bonemat = parentbonemat.inverted() @ bonemat_local
103 newmat = bonemat.inverted() @ parentposemat.inverted() @ otherloc
104 return newmat
107 def rotcopy(item, mat):
108 """Copy rotation to item from matrix mat depending on item.rotation_mode"""
109 if item.rotation_mode == 'QUATERNION':
110 item.rotation_quaternion = mat.to_3x3().to_quaternion()
111 elif item.rotation_mode == 'AXIS_ANGLE':
112 rot = mat.to_3x3().to_quaternion().to_axis_angle() # returns (Vector((x, y, z)), w)
113 axis_angle = rot[1], rot[0][0], rot[0][1], rot[0][2] # convert to w, x, y, z
114 item.rotation_axis_angle = axis_angle
115 else:
116 item.rotation_euler = mat.to_3x3().to_euler(item.rotation_mode)
119 def pLoopExec(self, context, funk):
120 """Loop over selected bones and execute funk on them"""
121 active = context.active_pose_bone
122 selected = context.selected_pose_bones
123 selected.remove(active)
124 for bone in selected:
125 funk(bone, active, context)
128 # The following functions are used to copy attributes from active to bone
130 def pLocLocExec(bone, active, context):
131 bone.location = active.location
134 def pLocRotExec(bone, active, context):
135 rotcopy(bone, active.matrix_basis.to_3x3())
138 def pLocScaExec(bone, active, context):
139 bone.scale = active.scale
142 def pVisLocExec(bone, active, context):
143 bone.location = getmat(bone, active, context, False).to_translation()
146 def pVisRotExec(bone, active, context):
147 obj_bone = bone.id_data
148 rotcopy(bone, getmat(bone, active,
149 context, not obj_bone.data.bones[bone.name].use_inherit_rotation))
152 def pVisScaExec(bone, active, context):
153 obj_bone = bone.id_data
154 bone.scale = getmat(bone, active, context,
155 not obj_bone.data.bones[bone.name].use_inherit_scale)\
156 .to_scale()
159 def pDrwExec(bone, active, context):
160 bone.custom_shape = active.custom_shape
161 bone.use_custom_shape_bone_size = active.use_custom_shape_bone_size
162 bone.custom_shape_translation = active.custom_shape_translation
163 bone.custom_shape_rotation_euler = active.custom_shape_rotation_euler
164 bone.custom_shape_scale_xyz = active.custom_shape_scale_xyz
165 bone.bone.show_wire = active.bone.show_wire
168 def pLokExec(bone, active, context):
169 for index, state in enumerate(active.lock_location):
170 bone.lock_location[index] = state
171 for index, state in enumerate(active.lock_rotation):
172 bone.lock_rotation[index] = state
173 bone.lock_rotations_4d = active.lock_rotations_4d
174 bone.lock_rotation_w = active.lock_rotation_w
175 for index, state in enumerate(active.lock_scale):
176 bone.lock_scale[index] = state
179 def pConExec(bone, active, context):
180 for old_constraint in active.constraints.values():
181 new_constraint = bone.constraints.new(old_constraint.type)
182 generic_copy(old_constraint, new_constraint)
185 def pIKsExec(bone, active, context):
186 generic_copy(active, bone, "ik_")
189 def pBBonesExec(bone, active, context):
190 object = active.id_data
191 generic_copy(
192 object.data.bones[active.name],
193 object.data.bones[bone.name],
194 "bbone_")
197 pose_copies = (
198 ('pose_loc_loc', "Local Location",
199 "Copy Location from Active to Selected", pLocLocExec),
200 ('pose_loc_rot', "Local Rotation",
201 "Copy Rotation from Active to Selected", pLocRotExec),
202 ('pose_loc_sca', "Local Scale",
203 "Copy Scale from Active to Selected", pLocScaExec),
204 ('pose_vis_loc', "Visual Location",
205 "Copy Location from Active to Selected", pVisLocExec),
206 ('pose_vis_rot', "Visual Rotation",
207 "Copy Rotation from Active to Selected", pVisRotExec),
208 ('pose_vis_sca', "Visual Scale",
209 "Copy Scale from Active to Selected", pVisScaExec),
210 ('pose_drw', "Bone Shape",
211 "Copy Bone Shape from Active to Selected", pDrwExec),
212 ('pose_lok', "Protected Transform",
213 "Copy Protected Transforms from Active to Selected", pLokExec),
214 ('pose_con', "Bone Constraints",
215 "Copy Object Constraints from Active to Selected", pConExec),
216 ('pose_iks', "IK Limits",
217 "Copy IK Limits from Active to Selected", pIKsExec),
218 ('bbone_settings', "BBone Settings",
219 "Copy BBone Settings from Active to Selected", pBBonesExec),
222 @classmethod
223 def pose_poll_func(cls, context):
224 return(context.mode == 'POSE')
227 def pose_invoke_func(self, context, event):
228 wm = context.window_manager
229 wm.invoke_props_dialog(self)
230 return {'RUNNING_MODAL'}
233 CustomPropSelectionBoolsProperty = BoolVectorProperty(
234 size=32,
235 options={'SKIP_SAVE'}
238 class CopySelection:
239 """Base class for copying properties from active to selected based on a selection."""
241 selection: CustomPropSelectionBoolsProperty
243 def draw_bools(self, button_names):
244 """Draws the boolean toggle list with a list of strings for the button texts."""
245 layout = self.layout
246 for idx, name in enumerate(button_names):
247 layout.prop(self, "selection", index=idx, text=name,
248 toggle=True)
250 def copy_custom_property(source, destination, prop_name):
251 """Copy a custom property called prop_name, from source to destination.
252 source and destination must be a Blender data type that can hold custom properties.
253 For a list of such data types, see:
254 https://docs.blender.org/manual/en/latest/files/data_blocks.html#files-data-blocks-custom-properties
257 # Create the property.
258 destination[prop_name] = source[prop_name]
259 # Copy the settings of the property.
260 try:
261 dst_prop_manager = destination.id_properties_ui(prop_name)
262 except TypeError:
263 # Python values like lists or dictionaries don't have any settings to copy.
264 # They just consist of a value and nothing else.
265 return
267 src_prop_manager = source.id_properties_ui(prop_name)
268 assert src_prop_manager, f'Property "{prop_name}" not found in {source}'
270 dst_prop_manager.update_from(src_prop_manager)
272 # Copy the Library Overridable flag, which is stored elsewhere.
273 prop_rna_path = f'["{prop_name}"]'
274 is_lib_overridable = source.is_property_overridable_library(prop_rna_path)
275 destination.property_overridable_library_set(prop_rna_path, is_lib_overridable)
277 class CopyCustomProperties(CopySelection):
278 """Base class for copying a selection of custom properties."""
280 def copy_selected_custom_props(self, active, selected):
281 keys = list(active.keys())
282 for item in selected:
283 if item == active:
284 continue
285 for index, is_selected in enumerate(self.selection):
286 if is_selected:
287 copy_custom_property(active, item, keys[index])
289 class CopySelectedBoneCustomProperties(CopyCustomProperties, Operator):
290 """Copy Chosen custom properties from active to selected"""
291 bl_idname = "pose.copy_selected_custom_props"
292 bl_label = "Copy Selected Custom Properties"
293 bl_options = {'REGISTER', 'UNDO'}
295 poll = pose_poll_func
296 invoke = pose_invoke_func
298 def draw(self, context):
299 self.draw_bools(context.active_pose_bone.keys())
301 def execute(self, context):
302 self.copy_selected_custom_props(context.active_pose_bone, context.selected_pose_bones)
303 return {'FINISHED'}
306 class CopySelectedPoseConstraints(Operator):
307 """Copy Chosen constraints from active to selected"""
308 bl_idname = "pose.copy_selected_constraints"
309 bl_label = "Copy Selected Constraints"
311 selection: BoolVectorProperty(
312 size=32,
313 options={'SKIP_SAVE'}
316 poll = pose_poll_func
317 invoke = pose_invoke_func
319 def draw(self, context):
320 layout = self.layout
321 for idx, const in enumerate(context.active_pose_bone.constraints):
322 layout.prop(self, "selection", index=idx, text=const.name,
323 toggle=True)
325 def execute(self, context):
326 active = context.active_pose_bone
327 selected = context.selected_pose_bones[:]
328 selected.remove(active)
329 for bone in selected:
330 for index, flag in enumerate(self.selection):
331 if flag:
332 bone.constraints.copy(active.constraints[index])
333 return {'FINISHED'}
336 pose_ops = [] # list of pose mode copy operators
337 genops(pose_copies, pose_ops, "pose.copy_", pose_poll_func, pLoopExec)
340 class VIEW3D_MT_posecopypopup(Menu):
341 bl_label = "Copy Attributes"
343 def draw(self, context):
344 layout = self.layout
345 layout.operator_context = 'INVOKE_REGION_WIN'
346 for op in pose_copies:
347 layout.operator("pose.copy_" + op[0])
348 layout.operator("pose.copy_selected_constraints")
349 layout.operator("pose.copy_selected_custom_props")
350 layout.operator("pose.copy", text="copy pose")
353 def obLoopExec(self, context, funk):
354 """Loop over selected objects and execute funk on them"""
355 active = context.active_object
356 selected = context.selected_objects[:]
357 selected.remove(active)
358 for obj in selected:
359 msg = funk(obj, active, context)
360 if msg:
361 self.report({msg[0]}, INFO_MESSAGE + msg[1])
364 def world_to_basis(active, ob, context):
365 """put world coords of active as basis coords of ob"""
366 local = ob.parent.matrix_world.inverted() @ active.matrix_world
367 P = ob.matrix_basis @ ob.matrix_local.inverted()
368 mat = P @ local
369 return(mat)
372 # The following functions are used to copy attributes from
373 # active to selected object
375 def obLoc(ob, active, context):
376 ob.location = active.location
379 def obRot(ob, active, context):
380 rotcopy(ob, active.matrix_local.to_3x3())
383 def obSca(ob, active, context):
384 ob.scale = active.scale
387 def obVisLoc(ob, active, context):
388 if ob.parent:
389 mat = world_to_basis(active, ob, context)
390 ob.location = mat.to_translation()
391 else:
392 ob.location = active.matrix_world.to_translation()
393 return('INFO', "Object location copied")
396 def obVisRot(ob, active, context):
397 if ob.parent:
398 mat = world_to_basis(active, ob, context)
399 rotcopy(ob, mat.to_3x3())
400 else:
401 rotcopy(ob, active.matrix_world.to_3x3())
402 return('INFO', "Object rotation copied")
405 def obVisSca(ob, active, context):
406 if ob.parent:
407 mat = world_to_basis(active, ob, context)
408 ob.scale = mat.to_scale()
409 else:
410 ob.scale = active.matrix_world.to_scale()
411 return('INFO', "Object scale copied")
414 def obDrw(ob, active, context):
415 ob.display_type = active.display_type
416 ob.show_axis = active.show_axis
417 ob.show_bounds = active.show_bounds
418 ob.display_bounds_type = active.display_bounds_type
419 ob.show_name = active.show_name
420 ob.show_texture_space = active.show_texture_space
421 ob.show_transparent = active.show_transparent
422 ob.show_wire = active.show_wire
423 ob.show_in_front = active.show_in_front
424 ob.empty_display_type = active.empty_display_type
425 ob.empty_display_size = active.empty_display_size
428 def obDup(ob, active, context):
429 generic_copy(active, ob, "instance_type")
430 return('INFO', "Duplication method copied")
433 def obCol(ob, active, context):
434 ob.color = active.color
437 def obLok(ob, active, context):
438 for index, state in enumerate(active.lock_location):
439 ob.lock_location[index] = state
440 for index, state in enumerate(active.lock_rotation):
441 ob.lock_rotation[index] = state
442 ob.lock_rotations_4d = active.lock_rotations_4d
443 ob.lock_rotation_w = active.lock_rotation_w
444 for index, state in enumerate(active.lock_scale):
445 ob.lock_scale[index] = state
446 return('INFO', "Transform locks copied")
449 def obCon(ob, active, context):
450 # for consistency with 2.49, delete old constraints first
451 for removeconst in ob.constraints:
452 ob.constraints.remove(removeconst)
453 for old_constraint in active.constraints.values():
454 new_constraint = ob.constraints.new(old_constraint.type)
455 generic_copy(old_constraint, new_constraint)
456 return('INFO', "Constraints copied")
459 def obTex(ob, active, context):
460 if 'texspace_location' in dir(ob.data) and 'texspace_location' in dir(
461 active.data):
462 ob.data.texspace_location[:] = active.data.texspace_location[:]
463 if 'texspace_size' in dir(ob.data) and 'texspace_size' in dir(active.data):
464 ob.data.texspace_size[:] = active.data.texspace_size[:]
465 return('INFO', "Texture space copied")
468 def obIdx(ob, active, context):
469 ob.pass_index = active.pass_index
470 return('INFO', "Pass index copied")
473 def obMod(ob, active, context):
474 for modifier in ob.modifiers:
475 # remove existing before adding new:
476 ob.modifiers.remove(modifier)
477 for old_modifier in active.modifiers.values():
478 new_modifier = ob.modifiers.new(name=old_modifier.name,
479 type=old_modifier.type)
480 generic_copy(old_modifier, new_modifier)
481 return('INFO', "Modifiers copied")
484 def obCollections(ob, active, context):
485 for collection in bpy.data.collections:
486 if active.name in collection.objects and ob.name not in collection.objects:
487 collection.objects.link(ob)
488 return('INFO', "Collections copied")
491 def obWei(ob, active, context):
492 # sanity check: are source and target both mesh objects?
493 if ob.type != 'MESH' or active.type != 'MESH':
494 return('ERROR', "objects have to be of mesh type, doing nothing")
495 me_source = active.data
496 me_target = ob.data
497 # sanity check: do source and target have the same amount of verts?
498 if len(me_source.vertices) != len(me_target.vertices):
499 return('ERROR', "objects have different vertex counts, doing nothing")
500 vgroups_IndexName = {}
501 for i in range(0, len(active.vertex_groups)):
502 groups = active.vertex_groups[i]
503 vgroups_IndexName[groups.index] = groups.name
504 data = {} # vert_indices, [(vgroup_index, weights)]
505 for v in me_source.vertices:
506 vg = v.groups
507 vi = v.index
508 if len(vg) > 0:
509 vgroup_collect = []
510 for i in range(0, len(vg)):
511 vgroup_collect.append((vg[i].group, vg[i].weight))
512 data[vi] = vgroup_collect
513 # write data to target
514 if ob != active:
515 # add missing vertex groups
516 for vgroup_name in vgroups_IndexName.values():
517 # check if group already exists...
518 already_present = 0
519 for i in range(0, len(ob.vertex_groups)):
520 if ob.vertex_groups[i].name == vgroup_name:
521 already_present = 1
522 # ... if not, then add
523 if already_present == 0:
524 ob.vertex_groups.new(name=vgroup_name)
525 # write weights
526 for v in me_target.vertices:
527 for vi_source, vgroupIndex_weight in data.items():
528 if v.index == vi_source:
530 for i in range(0, len(vgroupIndex_weight)):
531 groupName = vgroups_IndexName[vgroupIndex_weight[i][0]]
532 groups = ob.vertex_groups
533 for vgs in range(0, len(groups)):
534 if groups[vgs].name == groupName:
535 groups[vgs].add((v.index,),
536 vgroupIndex_weight[i][1], "REPLACE")
537 return('INFO', "Weights copied")
540 object_copies = (
541 # ('obj_loc', "Location",
542 # "Copy Location from Active to Selected", obLoc),
543 # ('obj_rot', "Rotation",
544 # "Copy Rotation from Active to Selected", obRot),
545 # ('obj_sca', "Scale",
546 # "Copy Scale from Active to Selected", obSca),
547 ('obj_vis_loc', "Location",
548 "Copy Location from Active to Selected", obVisLoc),
549 ('obj_vis_rot', "Rotation",
550 "Copy Rotation from Active to Selected", obVisRot),
551 ('obj_vis_sca', "Scale",
552 "Copy Scale from Active to Selected", obVisSca),
553 ('obj_drw', "Draw Options",
554 "Copy Draw Options from Active to Selected", obDrw),
555 ('obj_dup', "Instancing",
556 "Copy instancing properties from Active to Selected", obDup),
557 ('obj_col', "Object Color",
558 "Copy Object Color from Active to Selected", obCol),
559 # ('obj_dmp', "Damping",
560 # "Copy Damping from Active to Selected"),
561 # ('obj_all', "All Physical Attributes",
562 # "Copy Physical Attributes from Active to Selected"),
563 # ('obj_prp', "Properties",
564 # "Copy Properties from Active to Selected"),
565 ('obj_lok', "Protected Transform",
566 "Copy Protected Transforms from Active to Selected", obLok),
567 ('obj_con', "Object Constraints",
568 "Copy Object Constraints from Active to Selected", obCon),
569 # ('obj_nla', "NLA Strips",
570 # "Copy NLA Strips from Active to Selected"),
571 # ('obj_tex', "Texture Space",
572 # "Copy Texture Space from Active to Selected", obTex),
573 # ('obj_sub', "Subdivision Surface Settings",
574 # "Copy Subdivision Surface Settings from Active to Selected"),
575 # ('obj_smo', "AutoSmooth",
576 # "Copy AutoSmooth from Active to Selected"),
577 ('obj_idx', "Pass Index",
578 "Copy Pass Index from Active to Selected", obIdx),
579 ('obj_mod', "Modifiers",
580 "Copy Modifiers from Active to Selected", obMod),
581 ('obj_wei', "Vertex Weights",
582 "Copy vertex weights based on indices", obWei),
583 ('obj_grp', "Collection Links",
584 "Copy selected into active object's collection", obCollections)
588 @classmethod
589 def object_poll_func(cls, context):
590 return (len(context.selected_objects) > 1)
593 def object_invoke_func(self, context, event):
594 wm = context.window_manager
595 wm.invoke_props_dialog(self)
596 return {'RUNNING_MODAL'}
599 class CopySelectedObjectConstraints(Operator):
600 """Copy Chosen constraints from active to selected"""
601 bl_idname = "object.copy_selected_constraints"
602 bl_label = "Copy Selected Constraints"
604 selection: BoolVectorProperty(
605 size=32,
606 options={'SKIP_SAVE'}
609 poll = object_poll_func
610 invoke = object_invoke_func
612 def draw(self, context):
613 layout = self.layout
614 for idx, const in enumerate(context.active_object.constraints):
615 layout.prop(self, "selection", index=idx, text=const.name,
616 toggle=True)
618 def execute(self, context):
619 active = context.active_object
620 selected = context.selected_objects[:]
621 selected.remove(active)
622 for obj in selected:
623 for index, flag in enumerate(self.selection):
624 if flag:
625 obj.constraints.copy(active.constraints[index])
626 return{'FINISHED'}
629 class CopySelectedObjectModifiers(Operator):
630 """Copy Chosen modifiers from active to selected"""
631 bl_idname = "object.copy_selected_modifiers"
632 bl_label = "Copy Selected Modifiers"
634 selection: BoolVectorProperty(
635 size=32,
636 options={'SKIP_SAVE'}
639 poll = object_poll_func
640 invoke = object_invoke_func
642 def draw(self, context):
643 layout = self.layout
644 for idx, const in enumerate(context.active_object.modifiers):
645 layout.prop(self, 'selection', index=idx, text=const.name,
646 toggle=True)
648 def execute(self, context):
649 active = context.active_object
650 selected = context.selected_objects[:]
651 selected.remove(active)
652 for obj in selected:
653 for index, flag in enumerate(self.selection):
654 if flag:
655 old_modifier = active.modifiers[index]
656 new_modifier = obj.modifiers.new(
657 type=active.modifiers[index].type,
658 name=active.modifiers[index].name
660 generic_copy(old_modifier, new_modifier)
661 return{'FINISHED'}
664 class CopySelectedObjectCustomProperties(CopyCustomProperties, Operator):
665 """Copy Chosen custom properties from active to selected objects"""
666 bl_idname = "object.copy_selected_custom_props"
667 bl_label = "Copy Selected Custom Properties"
668 bl_options = {'REGISTER', 'UNDO'}
670 poll = object_poll_func
671 invoke = object_invoke_func
673 def draw(self, context):
674 self.draw_bools(context.object.keys())
676 def execute(self, context):
677 self.copy_selected_custom_props(context.object, context.selected_objects)
678 return {'FINISHED'}
680 object_ops = []
681 genops(object_copies, object_ops, "object.copy_", object_poll_func, obLoopExec)
684 class VIEW3D_MT_copypopup(Menu):
685 bl_label = "Copy Attributes"
687 def draw(self, context):
688 layout = self.layout
690 layout.operator_context = 'INVOKE_REGION_WIN'
691 layout.operator("view3d.copybuffer", icon="COPY_ID")
693 if (len(context.selected_objects) <= 1):
694 layout.separator()
695 layout.label(text="Please select at least two objects", icon="INFO")
696 layout.separator()
698 for entry, op in enumerate(object_copies):
699 if entry and entry % 4 == 0:
700 layout.separator()
701 layout.operator("object.copy_" + op[0])
702 layout.operator("object.copy_selected_constraints")
703 layout.operator("object.copy_selected_modifiers")
704 layout.operator("object.copy_selected_custom_props")
707 # Begin Mesh copy settings:
709 class MESH_MT_CopyFaceSettings(Menu):
710 bl_label = "Copy Face Settings"
712 @classmethod
713 def poll(cls, context):
714 return context.mode == 'EDIT_MESH'
716 def draw(self, context):
717 mesh = context.object.data
718 uv = len(mesh.uv_layers) > 1
719 vc = len(mesh.vertex_colors) > 1
721 layout = self.layout
723 op = layout.operator("mesh.copy_face_settings", text="Copy Material")
724 op['layer'] = ''
725 op['mode'] = 'MAT'
727 if mesh.uv_layers.active:
728 op = layout.operator("mesh.copy_face_settings", text="Copy Active UV Coords")
729 op['layer'] = ''
730 op['mode'] = 'UV'
732 if mesh.vertex_colors.active:
733 op = layout.operator("mesh.copy_face_settings", text="Copy Active Vertex Colors")
734 op['layer'] = ''
735 op['mode'] = 'VCOL'
737 if uv or vc:
738 layout.separator()
739 if uv:
740 layout.menu("MESH_MT_CopyUVCoordsFromLayer")
741 if vc:
742 layout.menu("MESH_MT_CopyVertexColorsFromLayer")
745 # Data (UV map, Image and Vertex color) menus calling MESH_OT_CopyFaceSettings
746 # Explicitly defined as using the generator code was broken in case of Menus
747 # causing issues with access and registration
750 class MESH_MT_CopyUVCoordsFromLayer(Menu):
751 bl_label = "Copy UV Coordinates from Layer"
753 @classmethod
754 def poll(cls, context):
755 obj = context.active_object
756 return obj and obj.mode == "EDIT_MESH" and len(
757 obj.data.uv_layers) > 1
759 def draw(self, context):
760 mesh = context.active_object.data
761 _buildmenu(self, mesh, 'UV', "GROUP_UVS")
764 class MESH_MT_CopyVertexColorsFromLayer(Menu):
765 bl_label = "Copy Vertex Colors from Layer"
767 @classmethod
768 def poll(cls, context):
769 obj = context.active_object
770 return obj and obj.mode == "EDIT_MESH" and len(
771 obj.data.vertex_colors) > 1
773 def draw(self, context):
774 mesh = context.active_object.data
775 _buildmenu(self, mesh, 'VCOL', "GROUP_VCOL")
778 def _buildmenu(self, mesh, mode, icon):
779 layout = self.layout
780 if mode == 'VCOL':
781 layers = mesh.vertex_colors
782 else:
783 layers = mesh.uv_layers
784 for layer in layers:
785 if not layer.active:
786 op = layout.operator("mesh.copy_face_settings",
787 text=layer.name, icon=icon)
788 op['layer'] = layer.name
789 op['mode'] = mode
792 class MESH_OT_CopyFaceSettings(Operator):
793 """Copy settings from active face to all selected faces"""
794 bl_idname = 'mesh.copy_face_settings'
795 bl_label = "Copy Face Settings"
796 bl_options = {'REGISTER', 'UNDO'}
798 mode: StringProperty(
799 name="Mode",
800 options={"HIDDEN"},
802 layer: StringProperty(
803 name="Layer",
804 options={"HIDDEN"},
807 @classmethod
808 def poll(cls, context):
809 return context.mode == 'EDIT_MESH'
811 def execute(self, context):
812 mode = getattr(self, 'mode', '')
813 if mode not in {'MAT', 'VCOL', 'UV'}:
814 self.report({'ERROR'}, "No mode specified or invalid mode")
815 return self._end(context, {'CANCELLED'})
816 layername = getattr(self, 'layer', '')
817 mesh = context.object.data
819 # Switching out of edit mode updates the selected state of faces and
820 # makes the data from the uv texture and vertex color layers available.
821 bpy.ops.object.editmode_toggle()
823 polys = mesh.polygons
824 if mode == 'MAT':
825 to_data = from_data = polys
826 else:
827 if mode == 'VCOL':
828 layers = mesh.vertex_colors
829 act_layer = mesh.vertex_colors.active
830 elif mode == 'UV':
831 layers = mesh.uv_layers
832 act_layer = mesh.uv_layers.active
833 if not layers or (layername and layername not in layers):
834 self.report({'ERROR'}, "Invalid UV or color layer. Operation Cancelled")
835 return self._end(context, {'CANCELLED'})
836 from_data = layers[layername or act_layer.name].data
837 to_data = act_layer.data
838 from_index = polys.active
840 for f in polys:
841 if f.select:
842 if to_data != from_data:
843 # Copying from another layer.
844 # from_face is to_face's counterpart from other layer.
845 from_index = f.index
846 elif f.index == from_index:
847 # Otherwise skip copying a face to itself.
848 continue
849 if mode == 'MAT':
850 f.material_index = polys[from_index].material_index
851 continue
852 if len(f.loop_indices) != len(polys[from_index].loop_indices):
853 self.report({'WARNING'}, "Different number of vertices.")
854 for i in range(len(f.loop_indices)):
855 to_vertex = f.loop_indices[i]
856 from_vertex = polys[from_index].loop_indices[i]
857 if mode == 'VCOL':
858 to_data[to_vertex].color = from_data[from_vertex].color
859 elif mode == 'UV':
860 to_data[to_vertex].uv = from_data[from_vertex].uv
862 return self._end(context, {'FINISHED'})
864 def _end(self, context, retval):
865 if context.mode != 'EDIT_MESH':
866 # Clean up by returning to edit mode like it was before.
867 bpy.ops.object.editmode_toggle()
868 return(retval)
871 classes = (
872 CopySelectedPoseConstraints,
873 CopySelectedBoneCustomProperties,
874 VIEW3D_MT_posecopypopup,
875 CopySelectedObjectConstraints,
876 CopySelectedObjectModifiers,
877 CopySelectedObjectCustomProperties,
878 VIEW3D_MT_copypopup,
879 MESH_MT_CopyFaceSettings,
880 MESH_MT_CopyUVCoordsFromLayer,
881 MESH_MT_CopyVertexColorsFromLayer,
882 MESH_OT_CopyFaceSettings,
883 *pose_ops,
884 *object_ops,
887 def register():
888 from bpy.utils import register_class
889 for cls in classes:
890 register_class(cls)
892 # mostly to get the keymap working
893 kc = bpy.context.window_manager.keyconfigs.addon
894 if kc:
895 km = kc.keymaps.new(name="Object Mode")
896 kmi = km.keymap_items.new('wm.call_menu', 'C', 'PRESS', ctrl=True)
897 kmi.properties.name = 'VIEW3D_MT_copypopup'
899 km = kc.keymaps.new(name="Pose")
900 kmi = km.keymap_items.get("pose.copy")
901 if kmi is not None:
902 kmi.idname = 'wm.call_menu'
903 else:
904 kmi = km.keymap_items.new('wm.call_menu', 'C', 'PRESS', ctrl=True)
905 kmi.properties.name = 'VIEW3D_MT_posecopypopup'
907 km = kc.keymaps.new(name="Mesh")
908 kmi = km.keymap_items.new('wm.call_menu', 'C', 'PRESS')
909 kmi.ctrl = True
910 kmi.properties.name = 'MESH_MT_CopyFaceSettings'
913 def unregister():
914 # mostly to remove the keymap
915 kc = bpy.context.window_manager.keyconfigs.addon
916 if kc:
917 kms = kc.keymaps.get('Pose')
918 if kms is not None:
919 for item in kms.keymap_items:
920 if item.name == 'Call Menu' and item.idname == 'wm.call_menu' and \
921 item.properties.name == 'VIEW3D_MT_posecopypopup':
922 item.idname = 'pose.copy'
923 break
925 km = kc.keymaps.get('Mesh')
926 if km is not None:
927 for kmi in km.keymap_items:
928 if kmi.idname == 'wm.call_menu':
929 if kmi.properties.name == 'MESH_MT_CopyFaceSettings':
930 km.keymap_items.remove(kmi)
932 km = kc.keymaps.get('Object Mode')
933 if km is not None:
934 for kmi in km.keymap_items:
935 if kmi.idname == 'wm.call_menu':
936 if kmi.properties.name == 'VIEW3D_MT_copypopup':
937 km.keymap_items.remove(kmi)
939 from bpy.utils import unregister_class
940 for cls in classes:
941 unregister_class(cls)
944 if __name__ == "__main__":
945 register()