Import_3ds: Improved distance cue chunk import
[blender-addons.git] / animation_add_corrective_shape_key.py
blobe077685f4ab8301e2e33e54def51a10c88630ead
1 # SPDX-FileCopyrightText: 2010-2022 Blender Foundation
3 # SPDX-License-Identifier: GPL-2.0-or-later
5 bl_info = {
6 "name": "Corrective Shape Keys",
7 "author": "Ivo Grigull (loolarge), Tal Trachtman", "Tokikake"
8 "version": (1, 1, 1),
9 "blender": (2, 80, 0),
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",
16 """
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 )
43 """
46 import bpy
47 from mathutils import Vector, Matrix
49 iterations = 20
50 threshold = 1e-16
52 def update_mesh(ob):
53 depth = bpy.context.evaluated_depsgraph_get()
54 depth.update()
55 ob.update_tag()
56 bpy.context.view_layer.update()
57 ob.data.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
74 verts = mesh.vertices
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))]
77 mesh.user_clear()
78 bpy.data.meshes.remove(mesh)
79 update_mesh(ob)
80 return arr
84 def apply_vert_coords(ob, mesh, x):
85 for i, v in enumerate(mesh):
86 v.co = x[i]
87 update_mesh(ob)
90 def func_add_corrective_pose_shape(source, target, flag):
92 ob_1 = target
93 mesh_1 = target.data
94 ob_2 = source
95 mesh_2 = source.data
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()
102 basis.name = "Basis"
103 update_mesh(ob_1)
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
107 print(ob_1)
108 print(ob_1.active_shape_key)
109 active_key_name = ob_1.active_shape_key.name
111 if (flag == True):
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"
117 update_mesh(ob_1)
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)
123 if key_index == 0:
124 new_shapekey = ob_1.shape_key_add()
125 new_shapekey.name = "Shape_" + ob_2.name
126 update_mesh(ob_1)
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:
154 epsilon = 0.0
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])
177 x[i] += G @ Delmorph
179 apply_vert_coords(ob_1, mesh_1_key_verts, x)
181 ob_1.show_only_shape_key = True
183 if (flag == 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
191 update_mesh(ob_1)
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)
196 ob_1.data.update()
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
203 update_mesh(ob_1)
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"
215 @classmethod
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")
223 return {'CANCELLED'}
225 target = context.active_object
226 if context.active_object == selection[0]:
227 source = selection[1]
228 else:
229 source = selection[0]
231 delta_flag = False
233 func_add_corrective_pose_shape(source, target, delta_flag)
235 return {'FINISHED'}
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"
245 @classmethod
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")
253 return {'CANCELLED'}
255 target = context.active_object
256 if context.active_object == selection[0]:
257 source = selection[1]
258 else:
259 source = selection[0]
261 delta_flag = True
263 func_add_corrective_pose_shape(source, target, delta_flag)
265 return {'FINISHED'}
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)
276 return 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"
285 @classmethod
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)
294 # setup the context
295 bpy.ops.object.select_all(action='DESELECT')
297 context.view_layer.objects.active = new_object
298 new_object.select_set(True)
300 return {'FINISHED'}
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
310 meshData =obj.data
311 mesh = meshData
313 armData = armatureOb.data
315 pose = armatureOb.pose
316 pbones = pose.bones
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:
326 try:
327 name = obj.vertex_groups[n.group].name
328 weight = n.weight
329 is_bone = False
330 for i in armData.bones:
331 if i.name == name:
332 is_bone = True
333 break
334 # ignore non-bone vertex groups
335 if is_bone:
336 listOfBoneNameWeightPairs.append([name, weight])
337 except:
338 print('error')
339 pass
341 weightedAverageDictionary = {}
342 totalWeight = 0
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
349 else:
350 weightedAverageDictionary[pair[0]] = 0
352 # Matrix filled with zeros
353 sigma = Matrix()
354 sigma.zero()
356 list = []
357 for n in pbones:
358 list.append(n)
359 list.reverse()
361 for pbone in list:
362 if pbone.name in weightedAverageDictionary:
363 #~ print("found key %s", pbone.name)
364 vertexWeight = weightedAverageDictionary[pbone.name]
365 m = pbone.matrix_channel.copy()
366 #m.transpose()
367 sigma += (m - I) * vertexWeight
369 else:
370 pass
371 #~ print("no key for bone " + pbone.name)
373 sigma = I + sigma
374 sigma.invert()
375 psdMeshVert.co = sigma @ psdMeshVert.co
376 obj.update_tag()
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()
387 basis.name = "Basis"
388 target.data.update()
390 key_index = target.active_shape_key_index
392 if key_index == 0:
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
407 try:
408 vgroup = target.active_shape_key.vertex_group
409 target.active_shape_key.vertex_group = ''
410 except:
411 pass
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
417 target.update_tag()
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:
422 #~ print("got one")
423 n.use_bone_envelopes = False
424 n.use_deform_preserve_volume = False
425 n.use_vertex_groups = True
426 armature = n.object
427 unposeMesh(shape_key_verts, target, armature)
428 break
430 # set the new shape key value to 1.0, so we see the result instantly
431 target.active_shape_key.value = 1.0
433 try:
434 target.active_shape_key.vertex_group = vgroup
435 except:
436 pass
438 target.show_only_shape_key = False
439 target.update_tag()
440 bpy.context.view_layer.update()
442 target.data.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"
454 @classmethod
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")
462 return {'CANCELLED'}
464 target = context.active_object
465 if context.active_object == selection[0]:
466 source = selection[1]
467 else:
468 source = selection[0]
470 func_add_corrective_pose_shape_fast(source, target)
472 return {'FINISHED'}
476 # -----------------------------------------------------------------------------
477 # GUI
479 def vgroups_draw(self, context):
480 layout = self.layout
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):
493 pass
495 classes = (add_corrective_pose_shape, add_corrective_pose_shape_delta, object_duplicate_flatten_modifiers, add_corrective_pose_shape_fast)
496 def register():
497 from bpy.utils import register_class
498 for cls in classes:
499 register_class(cls)
500 bpy.types.MESH_MT_shape_key_context_menu.append(vgroups_draw)
501 bpy.types.DATA_PT_modifiers.append(modifiers_draw)
504 def unregister():
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__":
512 register()