sun_position: fix warning from deleted prop in User Preferences
[blender-addons.git] / space_view3d_copy_attributes.py
blobf06ec3d152d42fdfd7990c15d5126e41520be60e
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 "wiki_url": "https://docs.blender.org/manual/en/dev/addons/"
29 "interface/copy_attributes.html",
30 "category": "Interface",
33 import bpy
34 from mathutils import Matrix
35 from bpy.types import (
36 Operator,
37 Menu,
39 from bpy.props import (
40 BoolVectorProperty,
41 StringProperty,
44 # First part of the operator Info message
45 INFO_MESSAGE = "Copy Attributes: "
48 def build_exec(loopfunc, func):
49 """Generator function that returns exec functions for operators """
51 def exec_func(self, context):
52 loopfunc(self, context, func)
53 return {'FINISHED'}
54 return exec_func
57 def build_invoke(loopfunc, func):
58 """Generator function that returns invoke functions for operators"""
60 def invoke_func(self, context, event):
61 loopfunc(self, context, func)
62 return {'FINISHED'}
63 return invoke_func
66 def build_op(idname, label, description, fpoll, fexec, finvoke):
67 """Generator function that returns the basic operator"""
69 class myopic(Operator):
70 bl_idname = idname
71 bl_label = label
72 bl_description = description
73 execute = fexec
74 poll = fpoll
75 invoke = finvoke
76 return myopic
79 def genops(copylist, oplist, prefix, poll_func, loopfunc):
80 """Generate ops from the copy list and its associated functions"""
81 for op in copylist:
82 exec_func = build_exec(loopfunc, op[3])
83 invoke_func = build_invoke(loopfunc, op[3])
84 opclass = build_op(prefix + op[0], "Copy " + op[1], op[2],
85 poll_func, exec_func, invoke_func)
86 oplist.append(opclass)
89 def generic_copy(source, target, string=""):
90 """Copy attributes from source to target that have string in them"""
91 for attr in dir(source):
92 if attr.find(string) > -1:
93 try:
94 setattr(target, attr, getattr(source, attr))
95 except:
96 pass
97 return
100 def getmat(bone, active, context, ignoreparent):
101 """Helper function for visual transform copy,
102 gets the active transform in bone space
104 obj_bone = bone.id_data
105 obj_active = active.id_data
106 data_bone = obj_bone.data.bones[bone.name]
107 # all matrices are in armature space unless commented otherwise
108 active_to_selected = obj_bone.matrix_world.inverted() @ obj_active.matrix_world
109 active_matrix = active_to_selected @ active.matrix
110 otherloc = active_matrix # final 4x4 mat of target, location.
111 bonemat_local = data_bone.matrix_local.copy() # self rest matrix
112 if data_bone.parent:
113 parentposemat = obj_bone.pose.bones[data_bone.parent.name].matrix.copy()
114 parentbonemat = data_bone.parent.matrix_local.copy()
115 else:
116 parentposemat = parentbonemat = Matrix()
117 if parentbonemat == parentposemat or ignoreparent:
118 newmat = bonemat_local.inverted() @ otherloc
119 else:
120 bonemat = parentbonemat.inverted() @ bonemat_local
122 newmat = bonemat.inverted() @ parentposemat.inverted() @ otherloc
123 return newmat
126 def rotcopy(item, mat):
127 """Copy rotation to item from matrix mat depending on item.rotation_mode"""
128 if item.rotation_mode == 'QUATERNION':
129 item.rotation_quaternion = mat.to_3x3().to_quaternion()
130 elif item.rotation_mode == 'AXIS_ANGLE':
131 rot = mat.to_3x3().to_quaternion().to_axis_angle() # returns (Vector((x, y, z)), w)
132 axis_angle = rot[1], rot[0][0], rot[0][1], rot[0][2] # convert to w, x, y, z
133 item.rotation_axis_angle = axis_angle
134 else:
135 item.rotation_euler = mat.to_3x3().to_euler(item.rotation_mode)
138 def pLoopExec(self, context, funk):
139 """Loop over selected bones and execute funk on them"""
140 active = context.active_pose_bone
141 selected = context.selected_pose_bones
142 selected.remove(active)
143 for bone in selected:
144 funk(bone, active, context)
147 # The following functions are used to copy attributes from active to bone
149 def pLocLocExec(bone, active, context):
150 bone.location = active.location
153 def pLocRotExec(bone, active, context):
154 rotcopy(bone, active.matrix_basis.to_3x3())
157 def pLocScaExec(bone, active, context):
158 bone.scale = active.scale
161 def pVisLocExec(bone, active, context):
162 bone.location = getmat(bone, active, context, False).to_translation()
165 def pVisRotExec(bone, active, context):
166 obj_bone = bone.id_data
167 rotcopy(bone, getmat(bone, active,
168 context, not obj_bone.data.bones[bone.name].use_inherit_rotation))
171 def pVisScaExec(bone, active, context):
172 obj_bone = bone.id_data
173 bone.scale = getmat(bone, active, context,
174 not obj_bone.data.bones[bone.name].use_inherit_scale)\
175 .to_scale()
178 def pDrwExec(bone, active, context):
179 bone.custom_shape = active.custom_shape
180 bone.use_custom_shape_bone_size = active.use_custom_shape_bone_size
181 bone.custom_shape_scale = active.custom_shape_scale
182 bone.bone.show_wire = active.bone.show_wire
185 def pLokExec(bone, active, context):
186 for index, state in enumerate(active.lock_location):
187 bone.lock_location[index] = state
188 for index, state in enumerate(active.lock_rotation):
189 bone.lock_rotation[index] = state
190 bone.lock_rotations_4d = active.lock_rotations_4d
191 bone.lock_rotation_w = active.lock_rotation_w
192 for index, state in enumerate(active.lock_scale):
193 bone.lock_scale[index] = state
196 def pConExec(bone, active, context):
197 for old_constraint in active.constraints.values():
198 new_constraint = bone.constraints.new(old_constraint.type)
199 generic_copy(old_constraint, new_constraint)
202 def pIKsExec(bone, active, context):
203 generic_copy(active, bone, "ik_")
206 def pBBonesExec(bone, active, context):
207 object = active.id_data
208 generic_copy(
209 object.data.bones[active.name],
210 object.data.bones[bone.name],
211 "bbone_")
214 pose_copies = (
215 ('pose_loc_loc', "Local Location",
216 "Copy Location from Active to Selected", pLocLocExec),
217 ('pose_loc_rot', "Local Rotation",
218 "Copy Rotation from Active to Selected", pLocRotExec),
219 ('pose_loc_sca', "Local Scale",
220 "Copy Scale from Active to Selected", pLocScaExec),
221 ('pose_vis_loc', "Visual Location",
222 "Copy Location from Active to Selected", pVisLocExec),
223 ('pose_vis_rot', "Visual Rotation",
224 "Copy Rotation from Active to Selected", pVisRotExec),
225 ('pose_vis_sca', "Visual Scale",
226 "Copy Scale from Active to Selected", pVisScaExec),
227 ('pose_drw', "Bone Shape",
228 "Copy Bone Shape from Active to Selected", pDrwExec),
229 ('pose_lok', "Protected Transform",
230 "Copy Protected Transforms from Active to Selected", pLokExec),
231 ('pose_con', "Bone Constraints",
232 "Copy Object Constraints from Active to Selected", pConExec),
233 ('pose_iks', "IK Limits",
234 "Copy IK Limits from Active to Selected", pIKsExec),
235 ('bbone_settings', "BBone Settings",
236 "Copy BBone Settings from Active to Selected", pBBonesExec),
239 @classmethod
240 def pose_poll_func(cls, context):
241 return(context.mode == 'POSE')
244 def pose_invoke_func(self, context, event):
245 wm = context.window_manager
246 wm.invoke_props_dialog(self)
247 return {'RUNNING_MODAL'}
250 class CopySelectedPoseConstraints(Operator):
251 """Copy Chosen constraints from active to selected"""
252 bl_idname = "pose.copy_selected_constraints"
253 bl_label = "Copy Selected Constraints"
255 selection: BoolVectorProperty(
256 size=32,
257 options={'SKIP_SAVE'}
260 poll = pose_poll_func
261 invoke = pose_invoke_func
263 def draw(self, context):
264 layout = self.layout
265 for idx, const in enumerate(context.active_pose_bone.constraints):
266 layout.prop(self, "selection", index=idx, text=const.name,
267 toggle=True)
269 def execute(self, context):
270 active = context.active_pose_bone
271 selected = context.selected_pose_bones[:]
272 selected.remove(active)
273 for bone in selected:
274 for index, flag in enumerate(self.selection):
275 if flag:
276 old_constraint = active.constraints[index]
277 new_constraint = bone.constraints.new(
278 active.constraints[index].type
280 generic_copy(old_constraint, new_constraint)
281 return {'FINISHED'}
284 pose_ops = [] # list of pose mode copy operators
285 genops(pose_copies, pose_ops, "pose.copy_", pose_poll_func, pLoopExec)
288 class VIEW3D_MT_posecopypopup(Menu):
289 bl_label = "Copy Attributes"
291 def draw(self, context):
292 layout = self.layout
293 layout.operator_context = 'INVOKE_REGION_WIN'
294 for op in pose_copies:
295 layout.operator("pose.copy_" + op[0])
296 layout.operator("pose.copy_selected_constraints")
297 layout.operator("pose.copy", text="copy pose")
300 def obLoopExec(self, context, funk):
301 """Loop over selected objects and execute funk on them"""
302 active = context.active_object
303 selected = context.selected_objects[:]
304 selected.remove(active)
305 for obj in selected:
306 msg = funk(obj, active, context)
307 if msg:
308 self.report({msg[0]}, INFO_MESSAGE + msg[1])
311 def world_to_basis(active, ob, context):
312 """put world coords of active as basis coords of ob"""
313 local = ob.parent.matrix_world.inverted() @ active.matrix_world
314 P = ob.matrix_basis @ ob.matrix_local.inverted()
315 mat = P @ local
316 return(mat)
319 # The following functions are used to copy attributes from
320 # active to selected object
322 def obLoc(ob, active, context):
323 ob.location = active.location
326 def obRot(ob, active, context):
327 rotcopy(ob, active.matrix_local.to_3x3())
330 def obSca(ob, active, context):
331 ob.scale = active.scale
334 def obVisLoc(ob, active, context):
335 if ob.parent:
336 mat = world_to_basis(active, ob, context)
337 ob.location = mat.to_translation()
338 else:
339 ob.location = active.matrix_world.to_translation()
340 return('INFO', "Object location copied")
343 def obVisRot(ob, active, context):
344 if ob.parent:
345 mat = world_to_basis(active, ob, context)
346 rotcopy(ob, mat.to_3x3())
347 else:
348 rotcopy(ob, active.matrix_world.to_3x3())
349 return('INFO', "Object rotation copied")
352 def obVisSca(ob, active, context):
353 if ob.parent:
354 mat = world_to_basis(active, ob, context)
355 ob.scale = mat.to_scale()
356 else:
357 ob.scale = active.matrix_world.to_scale()
358 return('INFO', "Object scale copied")
361 def obDrw(ob, active, context):
362 ob.display_type = active.display_type
363 ob.show_axis = active.show_axis
364 ob.show_bounds = active.show_bounds
365 ob.display_bounds_type = active.display_bounds_type
366 ob.show_name = active.show_name
367 ob.show_texture_space = active.show_texture_space
368 ob.show_transparent = active.show_transparent
369 ob.show_wire = active.show_wire
370 ob.show_in_front = active.show_in_front
371 ob.empty_display_type = active.empty_display_type
372 ob.empty_display_size = active.empty_display_size
375 def obOfs(ob, active, context):
376 ob.time_offset = active.time_offset
377 return('INFO', "Time offset copied")
380 def obDup(ob, active, context):
381 generic_copy(active, ob, "dupli")
382 return('INFO', "Duplication method copied")
385 def obCol(ob, active, context):
386 ob.color = active.color
389 def obLok(ob, active, context):
390 for index, state in enumerate(active.lock_location):
391 ob.lock_location[index] = state
392 for index, state in enumerate(active.lock_rotation):
393 ob.lock_rotation[index] = state
394 ob.lock_rotations_4d = active.lock_rotations_4d
395 ob.lock_rotation_w = active.lock_rotation_w
396 for index, state in enumerate(active.lock_scale):
397 ob.lock_scale[index] = state
398 return('INFO', "Transform locks copied")
401 def obCon(ob, active, context):
402 # for consistency with 2.49, delete old constraints first
403 for removeconst in ob.constraints:
404 ob.constraints.remove(removeconst)
405 for old_constraint in active.constraints.values():
406 new_constraint = ob.constraints.new(old_constraint.type)
407 generic_copy(old_constraint, new_constraint)
408 return('INFO', "Constraints copied")
411 def obTex(ob, active, context):
412 if 'texspace_location' in dir(ob.data) and 'texspace_location' in dir(
413 active.data):
414 ob.data.texspace_location[:] = active.data.texspace_location[:]
415 if 'texspace_size' in dir(ob.data) and 'texspace_size' in dir(active.data):
416 ob.data.texspace_size[:] = active.data.texspace_size[:]
417 return('INFO', "Texture space copied")
420 def obIdx(ob, active, context):
421 ob.pass_index = active.pass_index
422 return('INFO', "Pass index copied")
425 def obMod(ob, active, context):
426 for modifier in ob.modifiers:
427 # remove existing before adding new:
428 ob.modifiers.remove(modifier)
429 for old_modifier in active.modifiers.values():
430 new_modifier = ob.modifiers.new(name=old_modifier.name,
431 type=old_modifier.type)
432 generic_copy(old_modifier, new_modifier)
433 return('INFO', "Modifiers copied")
436 def obGrp(ob, active, context):
437 for grp in bpy.data.collections:
438 if active.name in grp.objects and ob.name not in grp.objects:
439 grp.objects.link(ob)
440 return('INFO', "Groups copied")
443 def obWei(ob, active, context):
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', "Subsurf Settings",
527 # "Copy Subsurf 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()