Export_3ds: Fixed secondary texture export
[blender-addons.git] / space_view3d_copy_attributes.py
blob279fd66d7c4c615229b3bba9fd098f65a5783087
1 # SPDX-FileCopyrightText: 2010-2023 Blender Foundation
3 # SPDX-License-Identifier: GPL-2.0-or-later
5 bl_info = {
6 "name": "Copy Attributes Menu",
7 "author": "Bassam Kurdali, Fabian Fricke, Adam Wiseman, Demeter Dzadik",
8 "version": (0, 6, 0),
9 "blender": (3, 4, 0),
10 "location": "View3D > Ctrl-C",
11 "description": "Copy Attributes Menu",
12 "doc_url": "{BLENDER_MANUAL_URL}/addons/interface/copy_attributes.html",
13 "category": "Interface",
16 import bpy
17 from mathutils import Matrix
18 from bpy.types import (
19 Operator,
20 Menu,
22 from bpy.props import (
23 BoolVectorProperty,
24 StringProperty,
27 # First part of the operator Info message
28 INFO_MESSAGE = "Copy Attributes: "
31 def build_exec(loopfunc, func):
32 """Generator function that returns exec functions for operators """
34 def exec_func(self, context):
35 loopfunc(self, context, func)
36 return {'FINISHED'}
37 return exec_func
40 def build_invoke(loopfunc, func):
41 """Generator function that returns invoke functions for operators"""
43 def invoke_func(self, context, event):
44 loopfunc(self, context, func)
45 return {'FINISHED'}
46 return invoke_func
49 def build_op(idname, label, description, fpoll, fexec, finvoke):
50 """Generator function that returns the basic operator"""
52 class myopic(Operator):
53 bl_idname = idname
54 bl_label = label
55 bl_description = description
56 execute = fexec
57 poll = fpoll
58 invoke = finvoke
59 return myopic
62 def genops(copylist, oplist, prefix, poll_func, loopfunc):
63 """Generate ops from the copy list and its associated functions"""
64 for op in copylist:
65 exec_func = build_exec(loopfunc, op[3])
66 invoke_func = build_invoke(loopfunc, op[3])
67 opclass = build_op(prefix + op[0], "Copy " + op[1], op[2],
68 poll_func, exec_func, invoke_func)
69 oplist.append(opclass)
72 def generic_copy(source, target, string=""):
73 """Copy attributes from source to target that have string in them"""
74 for attr in dir(source):
75 if attr.find(string) > -1:
76 try:
77 setattr(target, attr, getattr(source, attr))
78 except:
79 pass
80 return
83 def getmat(bone, active, context, ignoreparent):
84 """Helper function for visual transform copy,
85 gets the active transform in bone space
86 """
87 obj_bone = bone.id_data
88 obj_active = active.id_data
89 data_bone = obj_bone.data.bones[bone.name]
90 # all matrices are in armature space unless commented otherwise
91 active_to_selected = obj_bone.matrix_world.inverted() @ obj_active.matrix_world
92 active_matrix = active_to_selected @ active.matrix
93 otherloc = active_matrix # final 4x4 mat of target, location.
94 bonemat_local = data_bone.matrix_local.copy() # self rest matrix
95 if data_bone.parent:
96 parentposemat = obj_bone.pose.bones[data_bone.parent.name].matrix.copy()
97 parentbonemat = data_bone.parent.matrix_local.copy()
98 else:
99 parentposemat = parentbonemat = Matrix()
100 if parentbonemat == parentposemat or ignoreparent:
101 newmat = bonemat_local.inverted() @ otherloc
102 else:
103 bonemat = parentbonemat.inverted() @ bonemat_local
105 newmat = bonemat.inverted() @ parentposemat.inverted() @ otherloc
106 return newmat
109 def rotcopy(item, mat):
110 """Copy rotation to item from matrix mat depending on item.rotation_mode"""
111 if item.rotation_mode == 'QUATERNION':
112 item.rotation_quaternion = mat.to_3x3().to_quaternion()
113 elif item.rotation_mode == 'AXIS_ANGLE':
114 rot = mat.to_3x3().to_quaternion().to_axis_angle() # returns (Vector((x, y, z)), w)
115 axis_angle = rot[1], rot[0][0], rot[0][1], rot[0][2] # convert to w, x, y, z
116 item.rotation_axis_angle = axis_angle
117 else:
118 item.rotation_euler = mat.to_3x3().to_euler(item.rotation_mode)
121 def pLoopExec(self, context, funk):
122 """Loop over selected bones and execute funk on them"""
123 active = context.active_pose_bone
124 selected = context.selected_pose_bones
125 selected.remove(active)
126 for bone in selected:
127 funk(bone, active, context)
130 # The following functions are used to copy attributes from active to bone
132 def pLocLocExec(bone, active, context):
133 bone.location = active.location
136 def pLocRotExec(bone, active, context):
137 rotcopy(bone, active.matrix_basis.to_3x3())
140 def pLocScaExec(bone, active, context):
141 bone.scale = active.scale
144 def pVisLocExec(bone, active, context):
145 bone.location = getmat(bone, active, context, False).to_translation()
148 def pVisRotExec(bone, active, context):
149 obj_bone = bone.id_data
150 rotcopy(bone, getmat(bone, active,
151 context, not obj_bone.data.bones[bone.name].use_inherit_rotation))
154 def pVisScaExec(bone, active, context):
155 obj_bone = bone.id_data
156 bone.scale = getmat(bone, active, context,
157 not obj_bone.data.bones[bone.name].use_inherit_scale)\
158 .to_scale()
161 def pDrwExec(bone, active, context):
162 bone.custom_shape = active.custom_shape
163 bone.use_custom_shape_bone_size = active.use_custom_shape_bone_size
164 bone.custom_shape_translation = active.custom_shape_translation
165 bone.custom_shape_rotation_euler = active.custom_shape_rotation_euler
166 bone.custom_shape_scale_xyz = active.custom_shape_scale_xyz
167 bone.bone.show_wire = active.bone.show_wire
170 def pLokExec(bone, active, context):
171 for index, state in enumerate(active.lock_location):
172 bone.lock_location[index] = state
173 for index, state in enumerate(active.lock_rotation):
174 bone.lock_rotation[index] = state
175 bone.lock_rotations_4d = active.lock_rotations_4d
176 bone.lock_rotation_w = active.lock_rotation_w
177 for index, state in enumerate(active.lock_scale):
178 bone.lock_scale[index] = state
181 def pConExec(bone, active, context):
182 for old_constraint in active.constraints.values():
183 new_constraint = bone.constraints.new(old_constraint.type)
184 generic_copy(old_constraint, new_constraint)
187 def pIKsExec(bone, active, context):
188 generic_copy(active, bone, "ik_")
191 def pBBonesExec(bone, active, context):
192 object = active.id_data
193 generic_copy(
194 object.data.bones[active.name],
195 object.data.bones[bone.name],
196 "bbone_")
199 pose_copies = (
200 ('pose_loc_loc', "Local Location",
201 "Copy Location from Active to Selected", pLocLocExec),
202 ('pose_loc_rot', "Local Rotation",
203 "Copy Rotation from Active to Selected", pLocRotExec),
204 ('pose_loc_sca', "Local Scale",
205 "Copy Scale from Active to Selected", pLocScaExec),
206 ('pose_vis_loc', "Visual Location",
207 "Copy Location from Active to Selected", pVisLocExec),
208 ('pose_vis_rot', "Visual Rotation",
209 "Copy Rotation from Active to Selected", pVisRotExec),
210 ('pose_vis_sca', "Visual Scale",
211 "Copy Scale from Active to Selected", pVisScaExec),
212 ('pose_drw', "Bone Shape",
213 "Copy Bone Shape from Active to Selected", pDrwExec),
214 ('pose_lok', "Protected Transform",
215 "Copy Protected Transforms from Active to Selected", pLokExec),
216 ('pose_con', "Bone Constraints",
217 "Copy Object Constraints from Active to Selected", pConExec),
218 ('pose_iks', "IK Limits",
219 "Copy IK Limits from Active to Selected", pIKsExec),
220 ('bbone_settings', "BBone Settings",
221 "Copy BBone Settings from Active to Selected", pBBonesExec),
224 @classmethod
225 def pose_poll_func(cls, context):
226 return(context.mode == 'POSE')
229 def pose_invoke_func(self, context, event):
230 wm = context.window_manager
231 wm.invoke_props_dialog(self)
232 return {'RUNNING_MODAL'}
235 CustomPropSelectionBoolsProperty = BoolVectorProperty(
236 size=32,
237 options={'SKIP_SAVE'}
240 class CopySelection:
241 """Base class for copying properties from active to selected based on a selection."""
243 selection: CustomPropSelectionBoolsProperty
245 def draw_bools(self, button_names):
246 """Draws the boolean toggle list with a list of strings for the button texts."""
247 layout = self.layout
248 for idx, name in enumerate(button_names):
249 layout.prop(self, "selection", index=idx, text=name,
250 toggle=True)
252 def copy_custom_property(source, destination, prop_name):
253 """Copy a custom property called prop_name, from source to destination.
254 source and destination must be a Blender data type that can hold custom properties.
255 For a list of such data types, see:
256 https://docs.blender.org/manual/en/latest/files/data_blocks.html#files-data-blocks-custom-properties
259 # Create the property.
260 destination[prop_name] = source[prop_name]
261 # Copy the settings of the property.
262 try:
263 dst_prop_manager = destination.id_properties_ui(prop_name)
264 except TypeError:
265 # Python values like lists or dictionaries don't have any settings to copy.
266 # They just consist of a value and nothing else.
267 return
269 src_prop_manager = source.id_properties_ui(prop_name)
270 assert src_prop_manager, f'Property "{prop_name}" not found in {source}'
272 dst_prop_manager.update_from(src_prop_manager)
274 # Copy the Library Overridable flag, which is stored elsewhere.
275 prop_rna_path = f'["{prop_name}"]'
276 is_lib_overridable = source.is_property_overridable_library(prop_rna_path)
277 destination.property_overridable_library_set(prop_rna_path, is_lib_overridable)
279 class CopyCustomProperties(CopySelection):
280 """Base class for copying a selection of custom properties."""
282 def copy_selected_custom_props(self, active, selected):
283 keys = list(active.keys())
284 for item in selected:
285 if item == active:
286 continue
287 for index, is_selected in enumerate(self.selection):
288 if is_selected:
289 copy_custom_property(active, item, keys[index])
291 class CopySelectedBoneCustomProperties(CopyCustomProperties, Operator):
292 """Copy Chosen custom properties from active to selected"""
293 bl_idname = "pose.copy_selected_custom_props"
294 bl_label = "Copy Selected Custom Properties"
295 bl_options = {'REGISTER', 'UNDO'}
297 poll = pose_poll_func
298 invoke = pose_invoke_func
300 def draw(self, context):
301 self.draw_bools(context.active_pose_bone.keys())
303 def execute(self, context):
304 self.copy_selected_custom_props(context.active_pose_bone, context.selected_pose_bones)
305 return {'FINISHED'}
308 class CopySelectedPoseConstraints(Operator):
309 """Copy Chosen constraints from active to selected"""
310 bl_idname = "pose.copy_selected_constraints"
311 bl_label = "Copy Selected Constraints"
313 selection: BoolVectorProperty(
314 size=32,
315 options={'SKIP_SAVE'}
318 poll = pose_poll_func
319 invoke = pose_invoke_func
321 def draw(self, context):
322 layout = self.layout
323 for idx, const in enumerate(context.active_pose_bone.constraints):
324 layout.prop(self, "selection", index=idx, text=const.name,
325 toggle=True)
327 def execute(self, context):
328 active = context.active_pose_bone
329 selected = context.selected_pose_bones[:]
330 selected.remove(active)
331 for bone in selected:
332 for index, flag in enumerate(self.selection):
333 if flag:
334 bone.constraints.copy(active.constraints[index])
335 return {'FINISHED'}
338 pose_ops = [] # list of pose mode copy operators
339 genops(pose_copies, pose_ops, "pose.copy_", pose_poll_func, pLoopExec)
342 class VIEW3D_MT_posecopypopup(Menu):
343 bl_label = "Copy Attributes"
345 def draw(self, context):
346 layout = self.layout
347 layout.operator_context = 'INVOKE_REGION_WIN'
348 for op in pose_copies:
349 layout.operator("pose.copy_" + op[0])
350 layout.operator("pose.copy_selected_constraints")
351 layout.operator("pose.copy_selected_custom_props")
352 layout.operator("pose.copy", text="copy pose")
355 def obLoopExec(self, context, funk):
356 """Loop over selected objects and execute funk on them"""
357 active = context.active_object
358 selected = context.selected_objects[:]
359 selected.remove(active)
360 for obj in selected:
361 msg = funk(obj, active, context)
362 if msg:
363 self.report({msg[0]}, INFO_MESSAGE + msg[1])
366 def world_to_basis(active, ob, context):
367 """put world coords of active as basis coords of ob"""
368 local = ob.parent.matrix_world.inverted() @ active.matrix_world
369 P = ob.matrix_basis @ ob.matrix_local.inverted()
370 mat = P @ local
371 return(mat)
374 # The following functions are used to copy attributes from
375 # active to selected object
377 def obLoc(ob, active, context):
378 ob.location = active.location
381 def obRot(ob, active, context):
382 rotcopy(ob, active.matrix_local.to_3x3())
385 def obSca(ob, active, context):
386 ob.scale = active.scale
389 def obVisLoc(ob, active, context):
390 if ob.parent:
391 mat = world_to_basis(active, ob, context)
392 ob.location = mat.to_translation()
393 else:
394 ob.location = active.matrix_world.to_translation()
395 return('INFO', "Object location copied")
398 def obVisRot(ob, active, context):
399 if ob.parent:
400 mat = world_to_basis(active, ob, context)
401 rotcopy(ob, mat.to_3x3())
402 else:
403 rotcopy(ob, active.matrix_world.to_3x3())
404 return('INFO', "Object rotation copied")
407 def obVisSca(ob, active, context):
408 if ob.parent:
409 mat = world_to_basis(active, ob, context)
410 ob.scale = mat.to_scale()
411 else:
412 ob.scale = active.matrix_world.to_scale()
413 return('INFO', "Object scale copied")
416 def obDrw(ob, active, context):
417 ob.display_type = active.display_type
418 ob.show_axis = active.show_axis
419 ob.show_bounds = active.show_bounds
420 ob.display_bounds_type = active.display_bounds_type
421 ob.show_name = active.show_name
422 ob.show_texture_space = active.show_texture_space
423 ob.show_transparent = active.show_transparent
424 ob.show_wire = active.show_wire
425 ob.show_in_front = active.show_in_front
426 ob.empty_display_type = active.empty_display_type
427 ob.empty_display_size = active.empty_display_size
430 def obDup(ob, active, context):
431 generic_copy(active, ob, "instance_type")
432 return('INFO', "Duplication method copied")
435 def obCol(ob, active, context):
436 ob.color = active.color
439 def obLok(ob, active, context):
440 for index, state in enumerate(active.lock_location):
441 ob.lock_location[index] = state
442 for index, state in enumerate(active.lock_rotation):
443 ob.lock_rotation[index] = state
444 ob.lock_rotations_4d = active.lock_rotations_4d
445 ob.lock_rotation_w = active.lock_rotation_w
446 for index, state in enumerate(active.lock_scale):
447 ob.lock_scale[index] = state
448 return('INFO', "Transform locks copied")
451 def obCon(ob, active, context):
452 # for consistency with 2.49, delete old constraints first
453 for removeconst in ob.constraints:
454 ob.constraints.remove(removeconst)
455 for old_constraint in active.constraints.values():
456 new_constraint = ob.constraints.new(old_constraint.type)
457 generic_copy(old_constraint, new_constraint)
458 return('INFO', "Constraints copied")
461 def obTex(ob, active, context):
462 if 'texspace_location' in dir(ob.data) and 'texspace_location' in dir(
463 active.data):
464 ob.data.texspace_location[:] = active.data.texspace_location[:]
465 if 'texspace_size' in dir(ob.data) and 'texspace_size' in dir(active.data):
466 ob.data.texspace_size[:] = active.data.texspace_size[:]
467 return('INFO', "Texture space copied")
470 def obIdx(ob, active, context):
471 ob.pass_index = active.pass_index
472 return('INFO', "Pass index copied")
475 def obMod(ob, active, context):
476 for modifier in ob.modifiers:
477 # remove existing before adding new:
478 ob.modifiers.remove(modifier)
479 for old_modifier in active.modifiers.values():
480 new_modifier = ob.modifiers.new(name=old_modifier.name,
481 type=old_modifier.type)
482 generic_copy(old_modifier, new_modifier)
483 return('INFO', "Modifiers copied")
486 def obCollections(ob, active, context):
487 for collection in bpy.data.collections:
488 if active.name in collection.objects and ob.name not in collection.objects:
489 collection.objects.link(ob)
490 return('INFO', "Collections copied")
493 def obWei(ob, active, context):
494 # sanity check: are source and target both mesh objects?
495 if ob.type != 'MESH' or active.type != 'MESH':
496 return('ERROR', "objects have to be of mesh type, doing nothing")
497 me_source = active.data
498 me_target = ob.data
499 # sanity check: do source and target have the same amount of verts?
500 if len(me_source.vertices) != len(me_target.vertices):
501 return('ERROR', "objects have different vertex counts, doing nothing")
502 vgroups_IndexName = {}
503 for i in range(0, len(active.vertex_groups)):
504 groups = active.vertex_groups[i]
505 vgroups_IndexName[groups.index] = groups.name
506 data = {} # vert_indices, [(vgroup_index, weights)]
507 for v in me_source.vertices:
508 vg = v.groups
509 vi = v.index
510 if len(vg) > 0:
511 vgroup_collect = []
512 for i in range(0, len(vg)):
513 vgroup_collect.append((vg[i].group, vg[i].weight))
514 data[vi] = vgroup_collect
515 # write data to target
516 if ob != active:
517 # add missing vertex groups
518 for vgroup_name in vgroups_IndexName.values():
519 # check if group already exists...
520 already_present = 0
521 for i in range(0, len(ob.vertex_groups)):
522 if ob.vertex_groups[i].name == vgroup_name:
523 already_present = 1
524 # ... if not, then add
525 if already_present == 0:
526 ob.vertex_groups.new(name=vgroup_name)
527 # write weights
528 for v in me_target.vertices:
529 for vi_source, vgroupIndex_weight in data.items():
530 if v.index == vi_source:
532 for i in range(0, len(vgroupIndex_weight)):
533 groupName = vgroups_IndexName[vgroupIndex_weight[i][0]]
534 groups = ob.vertex_groups
535 for vgs in range(0, len(groups)):
536 if groups[vgs].name == groupName:
537 groups[vgs].add((v.index,),
538 vgroupIndex_weight[i][1], "REPLACE")
539 return('INFO', "Weights copied")
542 object_copies = (
543 # ('obj_loc', "Location",
544 # "Copy Location from Active to Selected", obLoc),
545 # ('obj_rot', "Rotation",
546 # "Copy Rotation from Active to Selected", obRot),
547 # ('obj_sca', "Scale",
548 # "Copy Scale from Active to Selected", obSca),
549 ('obj_vis_loc', "Location",
550 "Copy Location from Active to Selected", obVisLoc),
551 ('obj_vis_rot', "Rotation",
552 "Copy Rotation from Active to Selected", obVisRot),
553 ('obj_vis_sca', "Scale",
554 "Copy Scale from Active to Selected", obVisSca),
555 ('obj_drw', "Draw Options",
556 "Copy Draw Options from Active to Selected", obDrw),
557 ('obj_dup', "Instancing",
558 "Copy instancing properties from Active to Selected", obDup),
559 ('obj_col', "Object Color",
560 "Copy Object Color from Active to Selected", obCol),
561 # ('obj_dmp', "Damping",
562 # "Copy Damping from Active to Selected"),
563 # ('obj_all', "All Physical Attributes",
564 # "Copy Physical Attributes from Active to Selected"),
565 # ('obj_prp', "Properties",
566 # "Copy Properties from Active to Selected"),
567 ('obj_lok', "Protected Transform",
568 "Copy Protected Transforms from Active to Selected", obLok),
569 ('obj_con', "Object Constraints",
570 "Copy Object Constraints from Active to Selected", obCon),
571 # ('obj_nla', "NLA Strips",
572 # "Copy NLA Strips from Active to Selected"),
573 # ('obj_tex', "Texture Space",
574 # "Copy Texture Space from Active to Selected", obTex),
575 # ('obj_sub', "Subdivision Surface Settings",
576 # "Copy Subdivision Surface Settings from Active to Selected"),
577 # ('obj_smo', "AutoSmooth",
578 # "Copy AutoSmooth from Active to Selected"),
579 ('obj_idx', "Pass Index",
580 "Copy Pass Index from Active to Selected", obIdx),
581 ('obj_mod', "Modifiers",
582 "Copy Modifiers from Active to Selected", obMod),
583 ('obj_wei', "Vertex Weights",
584 "Copy vertex weights based on indices", obWei),
585 ('obj_grp', "Collection Links",
586 "Copy selected into active object's collection", obCollections)
590 @classmethod
591 def object_poll_func(cls, context):
592 return (len(context.selected_objects) > 1)
595 def object_invoke_func(self, context, event):
596 wm = context.window_manager
597 wm.invoke_props_dialog(self)
598 return {'RUNNING_MODAL'}
601 class CopySelectedObjectConstraints(Operator):
602 """Copy Chosen constraints from active to selected"""
603 bl_idname = "object.copy_selected_constraints"
604 bl_label = "Copy Selected Constraints"
606 selection: BoolVectorProperty(
607 size=32,
608 options={'SKIP_SAVE'}
611 poll = object_poll_func
612 invoke = object_invoke_func
614 def draw(self, context):
615 layout = self.layout
616 for idx, const in enumerate(context.active_object.constraints):
617 layout.prop(self, "selection", index=idx, text=const.name,
618 toggle=True)
620 def execute(self, context):
621 active = context.active_object
622 selected = context.selected_objects[:]
623 selected.remove(active)
624 for obj in selected:
625 for index, flag in enumerate(self.selection):
626 if flag:
627 obj.constraints.copy(active.constraints[index])
628 return{'FINISHED'}
631 class CopySelectedObjectModifiers(Operator):
632 """Copy Chosen modifiers from active to selected"""
633 bl_idname = "object.copy_selected_modifiers"
634 bl_label = "Copy Selected Modifiers"
636 selection: BoolVectorProperty(
637 size=32,
638 options={'SKIP_SAVE'}
641 poll = object_poll_func
642 invoke = object_invoke_func
644 def draw(self, context):
645 layout = self.layout
646 for idx, const in enumerate(context.active_object.modifiers):
647 layout.prop(self, 'selection', index=idx, text=const.name,
648 toggle=True)
650 def execute(self, context):
651 active = context.active_object
652 selected = context.selected_objects[:]
653 selected.remove(active)
654 for obj in selected:
655 for index, flag in enumerate(self.selection):
656 if flag:
657 old_modifier = active.modifiers[index]
658 new_modifier = obj.modifiers.new(
659 type=active.modifiers[index].type,
660 name=active.modifiers[index].name
662 generic_copy(old_modifier, new_modifier)
663 return{'FINISHED'}
666 class CopySelectedObjectCustomProperties(CopyCustomProperties, Operator):
667 """Copy Chosen custom properties from active to selected objects"""
668 bl_idname = "object.copy_selected_custom_props"
669 bl_label = "Copy Selected Custom Properties"
670 bl_options = {'REGISTER', 'UNDO'}
672 poll = object_poll_func
673 invoke = object_invoke_func
675 def draw(self, context):
676 self.draw_bools(context.object.keys())
678 def execute(self, context):
679 self.copy_selected_custom_props(context.object, context.selected_objects)
680 return {'FINISHED'}
682 object_ops = []
683 genops(object_copies, object_ops, "object.copy_", object_poll_func, obLoopExec)
686 class VIEW3D_MT_copypopup(Menu):
687 bl_label = "Copy Attributes"
689 def draw(self, context):
690 layout = self.layout
692 layout.operator_context = 'INVOKE_REGION_WIN'
693 layout.operator("view3d.copybuffer", icon="COPY_ID")
695 if (len(context.selected_objects) <= 1):
696 layout.separator()
697 layout.label(text="Please select at least two objects", icon="INFO")
698 layout.separator()
700 for entry, op in enumerate(object_copies):
701 if entry and entry % 4 == 0:
702 layout.separator()
703 layout.operator("object.copy_" + op[0])
704 layout.operator("object.copy_selected_constraints")
705 layout.operator("object.copy_selected_modifiers")
706 layout.operator("object.copy_selected_custom_props")
709 # Begin Mesh copy settings:
711 class MESH_MT_CopyFaceSettings(Menu):
712 bl_label = "Copy Face Settings"
714 @classmethod
715 def poll(cls, context):
716 return context.mode == 'EDIT_MESH'
718 def draw(self, context):
719 mesh = context.object.data
720 uv = len(mesh.uv_layers) > 1
721 vc = len(mesh.vertex_colors) > 1
723 layout = self.layout
725 op = layout.operator("mesh.copy_face_settings", text="Copy Material")
726 op['layer'] = ''
727 op['mode'] = 'MAT'
729 if mesh.uv_layers.active:
730 op = layout.operator("mesh.copy_face_settings", text="Copy Active UV Coords")
731 op['layer'] = ''
732 op['mode'] = 'UV'
734 if mesh.vertex_colors.active:
735 op = layout.operator("mesh.copy_face_settings", text="Copy Active Vertex Colors")
736 op['layer'] = ''
737 op['mode'] = 'VCOL'
739 if uv or vc:
740 layout.separator()
741 if uv:
742 layout.menu("MESH_MT_CopyUVCoordsFromLayer")
743 if vc:
744 layout.menu("MESH_MT_CopyVertexColorsFromLayer")
747 # Data (UV map, Image and Vertex color) menus calling MESH_OT_CopyFaceSettings
748 # Explicitly defined as using the generator code was broken in case of Menus
749 # causing issues with access and registration
752 class MESH_MT_CopyUVCoordsFromLayer(Menu):
753 bl_label = "Copy UV Coordinates from Layer"
755 @classmethod
756 def poll(cls, context):
757 obj = context.active_object
758 return obj and obj.mode == "EDIT_MESH" and len(
759 obj.data.uv_layers) > 1
761 def draw(self, context):
762 mesh = context.active_object.data
763 _buildmenu(self, mesh, 'UV', "GROUP_UVS")
766 class MESH_MT_CopyVertexColorsFromLayer(Menu):
767 bl_label = "Copy Vertex Colors from Layer"
769 @classmethod
770 def poll(cls, context):
771 obj = context.active_object
772 return obj and obj.mode == "EDIT_MESH" and len(
773 obj.data.vertex_colors) > 1
775 def draw(self, context):
776 mesh = context.active_object.data
777 _buildmenu(self, mesh, 'VCOL', "GROUP_VCOL")
780 def _buildmenu(self, mesh, mode, icon):
781 layout = self.layout
782 if mode == 'VCOL':
783 layers = mesh.vertex_colors
784 else:
785 layers = mesh.uv_layers
786 for layer in layers:
787 if not layer.active:
788 op = layout.operator("mesh.copy_face_settings",
789 text=layer.name, icon=icon)
790 op['layer'] = layer.name
791 op['mode'] = mode
794 class MESH_OT_CopyFaceSettings(Operator):
795 """Copy settings from active face to all selected faces"""
796 bl_idname = 'mesh.copy_face_settings'
797 bl_label = "Copy Face Settings"
798 bl_options = {'REGISTER', 'UNDO'}
800 mode: StringProperty(
801 name="Mode",
802 options={"HIDDEN"},
804 layer: StringProperty(
805 name="Layer",
806 options={"HIDDEN"},
809 @classmethod
810 def poll(cls, context):
811 return context.mode == 'EDIT_MESH'
813 def execute(self, context):
814 mode = getattr(self, 'mode', '')
815 if mode not in {'MAT', 'VCOL', 'UV'}:
816 self.report({'ERROR'}, "No mode specified or invalid mode")
817 return self._end(context, {'CANCELLED'})
818 layername = getattr(self, 'layer', '')
819 mesh = context.object.data
821 # Switching out of edit mode updates the selected state of faces and
822 # makes the data from the uv texture and vertex color layers available.
823 bpy.ops.object.editmode_toggle()
825 polys = mesh.polygons
826 if mode == 'MAT':
827 to_data = from_data = polys
828 else:
829 if mode == 'VCOL':
830 layers = mesh.vertex_colors
831 act_layer = mesh.vertex_colors.active
832 elif mode == 'UV':
833 layers = mesh.uv_layers
834 act_layer = mesh.uv_layers.active
835 if not layers or (layername and layername not in layers):
836 self.report({'ERROR'}, "Invalid UV or color layer. Operation Cancelled")
837 return self._end(context, {'CANCELLED'})
838 from_data = layers[layername or act_layer.name].data
839 to_data = act_layer.data
840 from_index = polys.active
842 for f in polys:
843 if f.select:
844 if to_data != from_data:
845 # Copying from another layer.
846 # from_face is to_face's counterpart from other layer.
847 from_index = f.index
848 elif f.index == from_index:
849 # Otherwise skip copying a face to itself.
850 continue
851 if mode == 'MAT':
852 f.material_index = polys[from_index].material_index
853 continue
854 if len(f.loop_indices) != len(polys[from_index].loop_indices):
855 self.report({'WARNING'}, "Different number of vertices.")
856 for i in range(len(f.loop_indices)):
857 to_vertex = f.loop_indices[i]
858 from_vertex = polys[from_index].loop_indices[i]
859 if mode == 'VCOL':
860 to_data[to_vertex].color = from_data[from_vertex].color
861 elif mode == 'UV':
862 to_data[to_vertex].uv = from_data[from_vertex].uv
864 return self._end(context, {'FINISHED'})
866 def _end(self, context, retval):
867 if context.mode != 'EDIT_MESH':
868 # Clean up by returning to edit mode like it was before.
869 bpy.ops.object.editmode_toggle()
870 return(retval)
873 classes = (
874 CopySelectedPoseConstraints,
875 CopySelectedBoneCustomProperties,
876 VIEW3D_MT_posecopypopup,
877 CopySelectedObjectConstraints,
878 CopySelectedObjectModifiers,
879 CopySelectedObjectCustomProperties,
880 VIEW3D_MT_copypopup,
881 MESH_MT_CopyFaceSettings,
882 MESH_MT_CopyUVCoordsFromLayer,
883 MESH_MT_CopyVertexColorsFromLayer,
884 MESH_OT_CopyFaceSettings,
885 *pose_ops,
886 *object_ops,
889 def register():
890 from bpy.utils import register_class
891 for cls in classes:
892 register_class(cls)
894 # mostly to get the keymap working
895 kc = bpy.context.window_manager.keyconfigs.addon
896 if kc:
897 km = kc.keymaps.new(name="Object Mode")
898 kmi = km.keymap_items.new('wm.call_menu', 'C', 'PRESS', ctrl=True)
899 kmi.properties.name = 'VIEW3D_MT_copypopup'
901 km = kc.keymaps.new(name="Pose")
902 kmi = km.keymap_items.get("pose.copy")
903 if kmi is not None:
904 kmi.idname = 'wm.call_menu'
905 else:
906 kmi = km.keymap_items.new('wm.call_menu', 'C', 'PRESS', ctrl=True)
907 kmi.properties.name = 'VIEW3D_MT_posecopypopup'
909 km = kc.keymaps.new(name="Mesh")
910 kmi = km.keymap_items.new('wm.call_menu', 'C', 'PRESS')
911 kmi.ctrl = True
912 kmi.properties.name = 'MESH_MT_CopyFaceSettings'
915 def unregister():
916 # mostly to remove the keymap
917 kc = bpy.context.window_manager.keyconfigs.addon
918 if kc:
919 kms = kc.keymaps.get('Pose')
920 if kms is not None:
921 for item in kms.keymap_items:
922 if item.name == 'Call Menu' and item.idname == 'wm.call_menu' and \
923 item.properties.name == 'VIEW3D_MT_posecopypopup':
924 item.idname = 'pose.copy'
925 break
927 km = kc.keymaps.get('Mesh')
928 if km is not None:
929 for kmi in km.keymap_items:
930 if kmi.idname == 'wm.call_menu':
931 if kmi.properties.name == 'MESH_MT_CopyFaceSettings':
932 km.keymap_items.remove(kmi)
934 km = kc.keymaps.get('Object Mode')
935 if km is not None:
936 for kmi in km.keymap_items:
937 if kmi.idname == 'wm.call_menu':
938 if kmi.properties.name == 'VIEW3D_MT_copypopup':
939 km.keymap_items.remove(kmi)
941 from bpy.utils import unregister_class
942 for cls in classes:
943 unregister_class(cls)
946 if __name__ == "__main__":
947 register()