1 # SPDX-FileCopyrightText: 2010-2022 Blender Foundation
3 # SPDX-License-Identifier: GPL-2.0-or-later
6 "name": "Corrective Shape Keys",
7 "author": "Ivo Grigull (loolarge), Tal Trachtman", "Tokikake"
10 "location": "Object Data > Shape Keys Specials or Search",
11 "description": "Creates a corrective shape key for the current pose",
12 "doc_url": "{BLENDER_MANUAL_URL}/addons/animation/corrective_shape_keys.html",
13 "category": "Animation",
17 This script transfer the shape from an object (base mesh without
18 modifiers) to another object with modifiers (i.e. posed Armature).
19 Only two objects must be selected.
20 The first selected object will be added to the second selected
21 object as a new shape key.
23 - Original 2.4x script by Brecht
24 - Unpose-function reused from a script by Tal Trachtman in 2007
25 http://www.apexbow.com/randd.html
26 - Converted to Blender 2.5 by Ivo Grigull
27 - Converted to Blender 2.8 by Tokikake
28 ("fast" option was removed, add new "delta" option
29 which count currently used shape key values of armature mesh when transfer)
31 Limitations and new delta option for 2.8
32 - Target mesh may not have any transformation at object level,
33 it will be set to zero.
35 - new "delta" option usage, when you hope to make new shape-key with keep currently visible other shape keys value.
36 it can generate new shape key, with value as 1.00. then deform target shape as source shape with keep other shape key values relative.
38 - If overwrite shape key,<select active shape key of target as non "base shape">
39 current shape key value is ignored and turn as 1.00.
41 then if active shape key was driven (bone rotation etc), you may get un-expected result. When transfer, I recommend, keep set active-shape key as base. so transferred shape key do not "overwrite". but generate new shape key.
42 if active-shape key have no driver, you can overwrite it (but as 1.00 value )
47 from mathutils
import Vector
, Matrix
53 depth
= bpy
.context
.evaluated_depsgraph_get()
56 bpy
.context
.view_layer
.update()
60 def reset_transform(ob
):
61 ob
.matrix_local
.identity()
63 # this version is for shape_key data
64 def extract_vert_coords(verts
):
65 return [v
.co
.copy() for v
in verts
]
67 def extract_mapped_coords(ob
, shape_verts
):
68 depth
= bpy
.context
.evaluated_depsgraph_get()
69 eobj
= ob
.evaluated_get(depth
)
70 mesh
= bpy
.data
.meshes
.new_from_object(eobj
)
72 # cheating, the original mapped verts happen
73 # to be at the end of the vertex array
75 #arr = [verts[i].co.copy() for i in range(len(verts) - totvert, len(verts))]
76 arr
= [verts
[i
].co
.copy() for i
in range(0, len(verts
))]
78 bpy
.data
.meshes
.remove(mesh
)
84 def apply_vert_coords(ob
, mesh
, x
):
85 for i
, v
in enumerate(mesh
):
90 def func_add_corrective_pose_shape(source
, target
, flag
):
97 reset_transform(target
)
99 # If target object doesn't have Base shape key, create it.
100 if not mesh_1
.shape_keys
:
101 basis
= ob_1
.shape_key_add()
104 ob_1
.active_shape_key_index
= 0
105 ob_1
.show_only_shape_key
= False
106 key_index
= ob_1
.active_shape_key_index
108 print(ob_1
.active_shape_key
)
109 active_key_name
= ob_1
.active_shape_key
.name
112 # Make mix shape key from currently used shape keys
113 if not key_index
== 0:
114 ob_1
.active_shape_key
.value
= 0
115 mix_shape
= ob_1
.shape_key_add(from_mix
= True)
116 mix_shape
.name
= "Mix_shape"
118 keys
= ob_1
.data
.shape_keys
.key_blocks
.keys()
119 ob_1
.active_shape_key_index
= keys
.index(active_key_name
)
121 print("active_key_name: ", active_key_name
)
124 new_shapekey
= ob_1
.shape_key_add()
125 new_shapekey
.name
= "Shape_" + ob_2
.name
127 keys
= ob_1
.data
.shape_keys
.key_blocks
.keys()
128 ob_1
.active_shape_key_index
= keys
.index(new_shapekey
.name
)
130 # else, the active shape will be used (updated)
132 ob_1
.show_only_shape_key
= True
134 vgroup
= ob_1
.active_shape_key
.vertex_group
135 ob_1
.active_shape_key
.vertex_group
= ""
137 #mesh_1_key_verts = mesh_1.shape_keys.key_blocks[key_index].data
138 mesh_1_key_verts
= ob_1
.active_shape_key
.data
140 x
= extract_vert_coords(mesh_1_key_verts
)
142 targetx
= extract_vert_coords(mesh_2
.vertices
)
144 for iteration
in range(0, iterations
):
145 dx
= [[], [], [], [], [], []]
147 mapx
= extract_mapped_coords(ob_1
, mesh_1_key_verts
)
149 # finite differencing in X/Y/Z to get approximate gradient
150 for i
in range(0, len(mesh_1
.vertices
)):
151 epsilon
= (targetx
[i
] - mapx
[i
]).length
153 if epsilon
< threshold
:
156 dx
[0] += [x
[i
] + 0.5 * epsilon
* Vector((1, 0, 0))]
157 dx
[1] += [x
[i
] + 0.5 * epsilon
* Vector((-1, 0, 0))]
158 dx
[2] += [x
[i
] + 0.5 * epsilon
* Vector((0, 1, 0))]
159 dx
[3] += [x
[i
] + 0.5 * epsilon
* Vector((0, -1, 0))]
160 dx
[4] += [x
[i
] + 0.5 * epsilon
* Vector((0, 0, 1))]
161 dx
[5] += [x
[i
] + 0.5 * epsilon
* Vector((0, 0, -1))]
163 for j
in range(0, 6):
164 apply_vert_coords(ob_1
, mesh_1_key_verts
, dx
[j
])
165 dx
[j
] = extract_mapped_coords(ob_1
, mesh_1_key_verts
)
167 # take a step in the direction of the gradient
168 for i
in range(0, len(mesh_1
.vertices
)):
169 epsilon
= (targetx
[i
] - mapx
[i
]).length
171 if epsilon
>= threshold
:
172 Gx
= list((dx
[0][i
] - dx
[1][i
]) / epsilon
)
173 Gy
= list((dx
[2][i
] - dx
[3][i
]) / epsilon
)
174 Gz
= list((dx
[4][i
] - dx
[5][i
]) / epsilon
)
175 G
= Matrix((Gx
, Gy
, Gz
))
176 Delmorph
= (targetx
[i
] - mapx
[i
])
179 apply_vert_coords(ob_1
, mesh_1_key_verts
, x
)
181 ob_1
.show_only_shape_key
= True
184 # remove delta of mix-shape key values from new shape key
185 key_index
= ob_1
.active_shape_key_index
186 active_key_name
= ob_1
.active_shape_key
.name
187 shape_data
= ob_1
.active_shape_key
.data
188 mix_data
= mix_shape
.data
189 for i
in range(0, len(mesh_1
.vertices
)):
190 shape_data
[i
].co
= mesh_1
.vertices
[i
].co
+ shape_data
[i
].co
- mix_data
[i
].co
193 ob_1
.active_shape_key_index
= ob_1
.data
.shape_keys
.key_blocks
.keys().index("Mix_shape")
194 bpy
.ops
.object.shape_key_remove()
195 ob_1
.active_shape_key_index
= ob_1
.data
.shape_keys
.key_blocks
.keys().index(active_key_name
)
197 ob_1
.show_only_shape_key
= False
199 ob_1
.active_shape_key
.vertex_group
= vgroup
201 # set the new shape key value to 1.0, so we see the result instantly
202 ob_1
.active_shape_key
.value
= 1.0
207 class add_corrective_pose_shape(bpy
.types
.Operator
):
208 """Adds first object as shape to second object for the current pose """ \
209 """while maintaining modifiers """ \
210 """(i.e. anisculpt, avoiding crazy space) Beware of slowness!"""
212 bl_idname
= "object.add_corrective_pose_shape"
213 bl_label
= "Add object as corrective pose shape"
216 def poll(cls
, context
):
217 return context
.active_object
is not None
219 def execute(self
, context
):
220 selection
= context
.selected_objects
221 if len(selection
) != 2:
222 self
.report({'ERROR'}, "Select source and target objects")
225 target
= context
.active_object
226 if context
.active_object
== selection
[0]:
227 source
= selection
[1]
229 source
= selection
[0]
233 func_add_corrective_pose_shape(source
, target
, delta_flag
)
237 class add_corrective_pose_shape_delta (bpy
.types
.Operator
):
238 """Adds first object as shape to second object for the current pose """ \
239 """while maintaining modifiers and currently used other shape keys""" \
240 """with keep other shape key value, generate new shape key which deform to source shape """
242 bl_idname
= "object.add_corrective_pose_shape_delta"
243 bl_label
= "Add object as corrective pose shape delta"
246 def poll(cls
, context
):
247 return context
.active_object
is not None
249 def execute(self
, context
):
250 selection
= context
.selected_objects
251 if len(selection
) != 2:
252 self
.report({'ERROR'}, "Select source and target objects")
255 target
= context
.active_object
256 if context
.active_object
== selection
[0]:
257 source
= selection
[1]
259 source
= selection
[0]
263 func_add_corrective_pose_shape(source
, target
, delta_flag
)
268 def func_object_duplicate_flatten_modifiers(context
, ob
):
269 depth
= bpy
.context
.evaluated_depsgraph_get()
270 eobj
= ob
.evaluated_get(depth
)
271 mesh
= bpy
.data
.meshes
.new_from_object(eobj
)
272 name
= ob
.name
+ "_clean"
273 new_object
= bpy
.data
.objects
.new(name
, mesh
)
274 new_object
.data
= mesh
275 bpy
.context
.collection
.objects
.link(new_object
)
279 class object_duplicate_flatten_modifiers(bpy
.types
.Operator
):
280 #Duplicates the selected object with modifiers applied
282 bl_idname
= "object.object_duplicate_flatten_modifiers"
283 bl_label
= "Duplicate and apply all"
286 def poll(cls
, context
):
287 return context
.active_object
is not None
289 def execute(self
, context
):
290 obj_act
= context
.active_object
292 new_object
= func_object_duplicate_flatten_modifiers(context
, obj_act
)
295 bpy
.ops
.object.select_all(action
='DESELECT')
297 context
.view_layer
.objects
.active
= new_object
298 new_object
.select_set(True)
302 #these old functions and class not work correctly just keep code for others try to edit
304 def unposeMesh(meshObToUnpose
, obj
, armatureOb
):
305 psdMeshData
= meshObToUnpose
307 psdMesh
= psdMeshData
308 I
= Matrix() # identity matrix
313 armData
= armatureOb
.data
315 pose
= armatureOb
.pose
318 for index
, v
in enumerate(mesh
.vertices
):
319 # above is python shortcut for:index goes up from 0 to tot num of
320 # verts in mesh, with index incrementing by 1 each iteration
322 psdMeshVert
= psdMesh
[index
]
324 listOfBoneNameWeightPairs
= []
325 for n
in mesh
.vertices
[index
].groups
:
327 name
= obj
.vertex_groups
[n
.group
].name
330 for i
in armData
.bones
:
334 # ignore non-bone vertex groups
336 listOfBoneNameWeightPairs
.append([name
, weight
])
341 weightedAverageDictionary
= {}
343 for pair
in listOfBoneNameWeightPairs
:
344 totalWeight
+= pair
[1]
346 for pair
in listOfBoneNameWeightPairs
:
347 if totalWeight
> 0: # avoid divide by zero!
348 weightedAverageDictionary
[pair
[0]] = pair
[1] / totalWeight
350 weightedAverageDictionary
[pair
[0]] = 0
352 # Matrix filled with zeros
362 if pbone
.name
in weightedAverageDictionary
:
363 #~ print("found key %s", pbone.name)
364 vertexWeight
= weightedAverageDictionary
[pbone
.name
]
365 m
= pbone
.matrix_channel
.copy()
367 sigma
+= (m
- I
) * vertexWeight
371 #~ print("no key for bone " + pbone.name)
375 psdMeshVert
.co
= sigma
@ psdMeshVert
.co
377 bpy
.context
.view_layer
.update()
381 def func_add_corrective_pose_shape_fast(source
, target
):
382 reset_transform(target
)
384 # If target object doesn't have Basis shape key, create it.
385 if not target
.data
.shape_keys
:
386 basis
= target
.shape_key_add()
390 key_index
= target
.active_shape_key_index
394 # Insert new shape key
395 new_shapekey
= target
.shape_key_add()
396 new_shapekey
.name
= "Shape_" + source
.name
398 key_index
= len(target
.data
.shape_keys
.key_blocks
) - 1
399 target
.active_shape_key_index
= key_index
401 # else, the active shape will be used (updated)
403 target
.show_only_shape_key
= True
405 shape_key_verts
= target
.data
.shape_keys
.key_blocks
[key_index
].data
408 vgroup
= target
.active_shape_key
.vertex_group
409 target
.active_shape_key
.vertex_group
= ''
413 # copy the local vertex positions to the new shape
414 verts
= source
.data
.vertices
415 for n
in range(len(verts
)):
416 shape_key_verts
[n
].co
= verts
[n
].co
418 bpy
.context
.view_layer
.update()
419 # go to all armature modifies and unpose the shape
420 for n
in target
.modifiers
:
421 if n
.type == 'ARMATURE' and n
.show_viewport
:
423 n
.use_bone_envelopes
= False
424 n
.use_deform_preserve_volume
= False
425 n
.use_vertex_groups
= True
427 unposeMesh(shape_key_verts
, target
, armature
)
430 # set the new shape key value to 1.0, so we see the result instantly
431 target
.active_shape_key
.value
= 1.0
434 target
.active_shape_key
.vertex_group
= vgroup
438 target
.show_only_shape_key
= False
440 bpy
.context
.view_layer
.update()
448 class add_corrective_pose_shape_fast(bpy
.types
.Operator
):
449 #Adds 1st object as shape to 2nd object as pose shape (only 1 armature)
451 bl_idname
= "object.add_corrective_pose_shape_fast"
452 bl_label
= "Add object as corrective shape faster"
455 def poll(cls
, context
):
456 return context
.active_object
is not None
458 def execute(self
, context
):
459 selection
= context
.selected_objects
460 if len(selection
) != 2:
461 self
.report({'ERROR'}, "Select source and target objects")
464 target
= context
.active_object
465 if context
.active_object
== selection
[0]:
466 source
= selection
[1]
468 source
= selection
[0]
470 func_add_corrective_pose_shape_fast(source
, target
)
476 # -----------------------------------------------------------------------------
479 def vgroups_draw(self
, context
):
482 layout
.operator("object.object_duplicate_flatten_modifiers",
483 text
='Create duplicate for editing')
484 layout
.operator("object.add_corrective_pose_shape",
485 text
='Add as corrective pose-shape (slow, all modifiers)',
486 icon
='COPY_ID') # icon is not ideal
487 layout
.operator("object.add_corrective_pose_shape_delta",
488 text
='Add as corrective pose-shape delta" (slow, all modifiers + other shape key values)',
489 icon
='COPY_ID') # icon is not ideal
492 def modifiers_draw(self
, context
):
495 classes
= (add_corrective_pose_shape
, add_corrective_pose_shape_delta
, object_duplicate_flatten_modifiers
, add_corrective_pose_shape_fast
)
497 from bpy
.utils
import register_class
500 bpy
.types
.MESH_MT_shape_key_context_menu
.append(vgroups_draw
)
501 bpy
.types
.DATA_PT_modifiers
.append(modifiers_draw
)
505 from bpy
.utils
import unregister_class
506 for cls
in reversed(classes
):
507 unregister_class(cls
)
508 bpy
.types
.MESH_MT_shape_key_context_menu
.remove(vgroups_draw
)
509 bpy
.types
.DATA_PT_modifiers
.remove(modifiers_draw
)
511 if __name__
== "__main__":