4 * ***** BEGIN GPL LICENSE BLOCK *****
6 * This program is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU General Public License
8 * as published by the Free Software Foundation; either version 2
9 * of the License, or (at your option) any later version.
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
16 * You should have received a copy of the GNU General Public License
17 * along with this program; if not, write to the Free Software Foundation,
18 * Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
20 * Contributor(s): Martin Poirier
22 * ***** END GPL LICENSE BLOCK *****
23 * autoarmature.c: Interface for automagically manipulating armature (retarget, created, ...)
36 #include "MEM_guardedalloc.h"
41 #include "DNA_action_types.h"
42 #include "DNA_armature_types.h"
43 #include "DNA_constraint_types.h"
44 #include "DNA_mesh_types.h"
45 #include "DNA_meshdata_types.h"
46 #include "DNA_object_types.h"
47 #include "DNA_scene_types.h"
48 #include "DNA_view3d_types.h"
50 #include "BLI_blenlib.h"
51 #include "BLI_arithb.h"
52 #include "BLI_editVert.h"
53 #include "BLI_ghash.h"
54 #include "BLI_graph.h"
56 #include "BLI_threads.h"
58 //#include "BDR_editobject.h"
60 #include "BKE_global.h"
61 #include "BKE_utildefines.h"
62 #include "BKE_constraint.h"
63 #include "BKE_armature.h"
64 #include "BKE_context.h"
66 #include "ED_armature.h"
69 #include "BIF_retarget.h"
73 //#include "mydevice.h"
74 #include "reeb.h" // FIX ME
75 //#include "blendef.h"
77 #include "armature_intern.h"
79 /************ RIG RETARGET DATA STRUCTURES ***************/
81 typedef struct MemoNode {
86 typedef struct RetargetParam {
101 METHOD_BRUTE_FORCE = 0,
112 RigGraph *GLOBAL_RIGG = NULL;
114 /*******************************************************************************************************/
116 void *exec_retargetArctoArc(void *param);
118 static void RIG_calculateEdgeAngles(RigEdge *edge_first, RigEdge *edge_second);
119 float rollBoneByQuat(EditBone *bone, float old_up_axis[3], float qrot[4]);
122 #define SHAPE_LEVELS (SHAPE_RADIX * SHAPE_RADIX)
124 /*********************************** EDITBONE UTILS ****************************************************/
126 int countEditBoneChildren(ListBase *list, EditBone *parent)
131 for (ebone = list->first; ebone; ebone = ebone->next)
133 if (ebone->parent == parent)
142 EditBone* nextEditBoneChild(ListBase *list, EditBone *parent, int n)
146 for (ebone = list->first; ebone; ebone = ebone->next)
148 if (ebone->parent == parent)
161 void getEditBoneRollUpAxis(EditBone *bone, float roll, float up_axis[3])
163 float mat[3][3], nor[3];
165 VecSubf(nor, bone->tail, bone->head);
167 vec_roll_to_mat3(nor, roll, mat);
168 VECCOPY(up_axis, mat[2]);
171 float rollBoneByQuatAligned(EditBone *bone, float old_up_axis[3], float qrot[4], float qroll[4], float aligned_axis[3])
173 float nor[3], new_up_axis[3], x_axis[3], z_axis[3];
175 VECCOPY(new_up_axis, old_up_axis);
176 QuatMulVecf(qrot, new_up_axis);
178 VecSubf(nor, bone->tail, bone->head);
180 Crossf(x_axis, nor, aligned_axis);
181 Crossf(z_axis, x_axis, nor);
183 Normalize(new_up_axis);
187 if (Inpf(new_up_axis, x_axis) < 0)
192 if (Inpf(new_up_axis, z_axis) < 0)
197 if (NormalizedVecAngle2(x_axis, new_up_axis) < NormalizedVecAngle2(z_axis, new_up_axis))
199 RotationBetweenVectorsToQuat(qroll, new_up_axis, x_axis); /* set roll rotation quat */
200 return ED_rollBoneToVector(bone, x_axis);
204 RotationBetweenVectorsToQuat(qroll, new_up_axis, z_axis); /* set roll rotation quat */
205 return ED_rollBoneToVector(bone, z_axis);
209 float rollBoneByQuatJoint(RigEdge *edge, RigEdge *previous, float qrot[4], float qroll[4], float up_axis[3])
211 if (previous == NULL)
213 /* default to up_axis if no previous */
214 return rollBoneByQuatAligned(edge->bone, edge->up_axis, qrot, qroll, up_axis);
218 float new_up_axis[3];
219 float vec_first[3], vec_second[3], normal[3];
223 VecSubf(vec_first, previous->bone->tail, previous->bone->head);
225 else if (previous->prev->bone)
227 VecSubf(vec_first, edge->bone->head, previous->prev->bone->tail);
231 /* default to up_axis if first bone in the chain is an offset */
232 return rollBoneByQuatAligned(edge->bone, edge->up_axis, qrot, qroll, up_axis);
235 VecSubf(vec_second, edge->bone->tail, edge->bone->head);
237 Normalize(vec_first);
238 Normalize(vec_second);
240 Crossf(normal, vec_first, vec_second);
243 AxisAngleToQuat(qroll, vec_second, edge->up_angle);
245 QuatMulVecf(qroll, normal);
247 VECCOPY(new_up_axis, edge->up_axis);
248 QuatMulVecf(qrot, new_up_axis);
250 Normalize(new_up_axis);
252 /* real qroll between normal and up_axis */
253 RotationBetweenVectorsToQuat(qroll, new_up_axis, normal);
255 return ED_rollBoneToVector(edge->bone, normal);
259 float rollBoneByQuat(EditBone *bone, float old_up_axis[3], float qrot[4])
261 float new_up_axis[3];
263 VECCOPY(new_up_axis, old_up_axis);
264 QuatMulVecf(qrot, new_up_axis);
266 Normalize(new_up_axis);
268 return ED_rollBoneToVector(bone, new_up_axis);
271 /************************************ DESTRUCTORS ******************************************************/
273 void RIG_freeRigArc(BArc *arc)
275 BLI_freelistN(&((RigArc*)arc)->edges);
278 void RIG_freeRigGraph(BGraph *rg)
280 RigGraph *rigg = (RigGraph*)rg;
285 BLI_destroy_worker(rigg->worker);
290 REEB_freeGraph(rigg->link_mesh);
293 for (arc = rg->arcs.first; arc; arc = arc->next)
297 BLI_freelistN(&rg->arcs);
299 for (node = rg->nodes.first; node; node = node->next)
301 BLI_freeNode(rg, (BNode*)node);
303 BLI_freelistN(&rg->nodes);
305 BLI_freelistN(&rigg->controls);
307 BLI_ghash_free(rigg->bones_map, NULL, NULL);
308 BLI_ghash_free(rigg->controls_map, NULL, NULL);
310 if (rigg->flag & RIG_FREE_BONELIST)
312 BLI_freelistN(rigg->editbones);
313 MEM_freeN(rigg->editbones);
319 /************************************* ALLOCATORS ******************************************************/
321 static RigGraph *newRigGraph()
326 rg = MEM_callocN(sizeof(RigGraph), "rig graph");
330 rg->bones_map = BLI_ghash_new(BLI_ghashutil_strhash, BLI_ghashutil_strcmp);
331 rg->controls_map = BLI_ghash_new(BLI_ghashutil_strhash, BLI_ghashutil_strcmp);
333 rg->free_arc = RIG_freeRigArc;
334 rg->free_node = NULL;
337 // if(G.scene->r.mode & R_FIXED_THREADS)
339 // totthread = G.scene->r.threads;
343 totthread = BLI_system_thread_count();
346 rg->worker = BLI_create_worker(exec_retargetArctoArc, totthread, 20); /* fix number of threads */
352 static RigArc *newRigArc(RigGraph *rg)
356 arc = MEM_callocN(sizeof(RigArc), "rig arc");
358 BLI_addtail(&rg->arcs, arc);
363 static RigControl *newRigControl(RigGraph *rg)
367 ctrl = MEM_callocN(sizeof(RigControl), "rig control");
369 BLI_addtail(&rg->controls, ctrl);
374 static RigNode *newRigNodeHead(RigGraph *rg, RigArc *arc, float p[3])
377 node = MEM_callocN(sizeof(RigNode), "rig node");
378 BLI_addtail(&rg->nodes, node);
389 static void addRigNodeHead(RigGraph *rg, RigArc *arc, RigNode *node)
396 static RigNode *newRigNode(RigGraph *rg, float p[3])
399 node = MEM_callocN(sizeof(RigNode), "rig node");
400 BLI_addtail(&rg->nodes, node);
409 static RigNode *newRigNodeTail(RigGraph *rg, RigArc *arc, float p[3])
411 RigNode *node = newRigNode(rg, p);
419 static void RIG_appendEdgeToArc(RigArc *arc, RigEdge *edge)
421 BLI_addtail(&arc->edges, edge);
423 if (edge->prev == NULL)
425 VECCOPY(edge->head, arc->head->p);
429 RigEdge *last_edge = edge->prev;
430 VECCOPY(edge->head, last_edge->tail);
431 RIG_calculateEdgeAngles(last_edge, edge);
434 edge->length = VecLenf(edge->head, edge->tail);
436 arc->length += edge->length;
441 static void RIG_addEdgeToArc(RigArc *arc, float tail[3], EditBone *bone)
445 edge = MEM_callocN(sizeof(RigEdge), "rig edge");
447 VECCOPY(edge->tail, tail);
452 getEditBoneRollUpAxis(bone, bone->roll, edge->up_axis);
455 RIG_appendEdgeToArc(arc, edge);
457 /************************************** CLONING TEMPLATES **********************************************/
459 static void renameTemplateBone(char *name, char *template_name, ListBase *editbones, char *side_string, char *num_string)
463 for (i = 0, j = 0; template_name[i] != '\0' && i < 31 && j < 31; i++)
465 if (template_name[i] == '&')
467 if (template_name[i+1] == 'S' || template_name[i+1] == 's')
469 j += sprintf(name + j, side_string);
472 else if (template_name[i+1] == 'N' || template_name[i+1] == 'n')
474 j += sprintf(name + j, num_string);
479 name[j] = template_name[i];
485 name[j] = template_name[i];
492 unique_editbone_name(editbones, name, NULL);
495 static RigControl *cloneControl(RigGraph *rg, RigGraph *src_rg, RigControl *src_ctrl, GHash *ptr_hash, char *side_string, char *num_string)
500 ctrl = newRigControl(rg);
502 VECCOPY(ctrl->head, src_ctrl->head);
503 VECCOPY(ctrl->tail, src_ctrl->tail);
504 VECCOPY(ctrl->up_axis, src_ctrl->up_axis);
505 VECCOPY(ctrl->offset, src_ctrl->offset);
507 ctrl->tail_mode = src_ctrl->tail_mode;
508 ctrl->flag = src_ctrl->flag;
510 renameTemplateBone(name, src_ctrl->bone->name, rg->editbones, side_string, num_string);
511 ctrl->bone = duplicateEditBoneObjects(src_ctrl->bone, name, rg->editbones, src_rg->ob, rg->ob);
512 ctrl->bone->flag &= ~(BONE_TIPSEL|BONE_SELECTED|BONE_ROOTSEL|BONE_ACTIVE);
513 BLI_ghash_insert(ptr_hash, src_ctrl->bone, ctrl->bone);
515 ctrl->link = src_ctrl->link;
516 ctrl->link_tail = src_ctrl->link_tail;
521 static RigArc *cloneArc(RigGraph *rg, RigGraph *src_rg, RigArc *src_arc, GHash *ptr_hash, char *side_string, char *num_string)
528 arc->head = BLI_ghash_lookup(ptr_hash, src_arc->head);
529 arc->tail = BLI_ghash_lookup(ptr_hash, src_arc->tail);
534 arc->length = src_arc->length;
536 arc->count = src_arc->count;
538 for (src_edge = src_arc->edges.first; src_edge; src_edge = src_edge->next)
542 edge = MEM_callocN(sizeof(RigEdge), "rig edge");
544 VECCOPY(edge->head, src_edge->head);
545 VECCOPY(edge->tail, src_edge->tail);
546 VECCOPY(edge->up_axis, src_edge->up_axis);
548 edge->length = src_edge->length;
549 edge->angle = src_edge->angle;
550 edge->up_angle = src_edge->up_angle;
552 if (src_edge->bone != NULL)
555 renameTemplateBone(name, src_edge->bone->name, rg->editbones, side_string, num_string);
556 edge->bone = duplicateEditBoneObjects(src_edge->bone, name, rg->editbones, src_rg->ob, rg->ob);
557 edge->bone->flag &= ~(BONE_TIPSEL|BONE_SELECTED|BONE_ROOTSEL|BONE_ACTIVE);
558 BLI_ghash_insert(ptr_hash, src_edge->bone, edge->bone);
561 BLI_addtail(&arc->edges, edge);
567 static RigGraph *cloneRigGraph(RigGraph *src, ListBase *editbones, Object *ob, char *side_string, char *num_string)
575 ptr_hash = BLI_ghash_new(BLI_ghashutil_ptrhash, BLI_ghashutil_ptrcmp);
580 rg->editbones = editbones;
582 preEditBoneDuplicate(rg->editbones); /* prime bones for duplication */
583 preEditBoneDuplicate(src->editbones); /* prime bones for duplication */
586 for (node = src->nodes.first; node; node = node->next)
588 RigNode *cloned_node = newRigNode(rg, node->p);
589 BLI_ghash_insert(ptr_hash, node, cloned_node);
592 rg->head = BLI_ghash_lookup(ptr_hash, src->head);
595 for (arc = src->arcs.first; arc; arc = arc->next)
597 cloneArc(rg, src, arc, ptr_hash, side_string, num_string);
601 for (ctrl = src->controls.first; ctrl; ctrl = ctrl->next)
603 cloneControl(rg, src, ctrl, ptr_hash, side_string, num_string);
606 /* Relink bones properly */
607 for (arc = rg->arcs.first; arc; arc = arc->next)
611 for (edge = arc->edges.first; edge; edge = edge->next)
613 if (edge->bone != NULL)
617 updateDuplicateSubtargetObjects(edge->bone, src->editbones, src->ob, rg->ob);
619 if (edge->bone->parent)
621 bone = BLI_ghash_lookup(ptr_hash, edge->bone->parent);
625 edge->bone->parent = bone;
629 /* disconnect since parent isn't cloned
630 * this will only happen when cloning from selected bones
632 edge->bone->flag &= ~BONE_CONNECTED;
639 for (ctrl = rg->controls.first; ctrl; ctrl = ctrl->next)
643 updateDuplicateSubtargetObjects(ctrl->bone, src->editbones, src->ob, rg->ob);
645 if (ctrl->bone->parent)
647 bone = BLI_ghash_lookup(ptr_hash, ctrl->bone->parent);
651 ctrl->bone->parent = bone;
655 /* disconnect since parent isn't cloned
656 * this will only happen when cloning from selected bones
658 ctrl->bone->flag &= ~BONE_CONNECTED;
662 ctrl->link = BLI_ghash_lookup(ptr_hash, ctrl->link);
663 ctrl->link_tail = BLI_ghash_lookup(ptr_hash, ctrl->link_tail);
666 BLI_ghash_free(ptr_hash, NULL, NULL);
672 /*******************************************************************************************************/
674 static void RIG_calculateEdgeAngles(RigEdge *edge_first, RigEdge *edge_second)
676 float vec_first[3], vec_second[3];
678 VecSubf(vec_first, edge_first->tail, edge_first->head);
679 VecSubf(vec_second, edge_second->tail, edge_second->head);
681 Normalize(vec_first);
682 Normalize(vec_second);
684 edge_first->angle = NormalizedVecAngle2(vec_first, vec_second);
686 if (edge_second->bone != NULL)
690 Crossf(normal, vec_first, vec_second);
693 edge_second->up_angle = NormalizedVecAngle2(normal, edge_second->up_axis);
697 /************************************ CONTROL BONES ****************************************************/
699 static void RIG_addControlBone(RigGraph *rg, EditBone *bone)
701 RigControl *ctrl = newRigControl(rg);
703 VECCOPY(ctrl->head, bone->head);
704 VECCOPY(ctrl->tail, bone->tail);
705 getEditBoneRollUpAxis(bone, bone->roll, ctrl->up_axis);
706 ctrl->tail_mode = TL_NONE;
708 BLI_ghash_insert(rg->controls_map, bone->name, ctrl);
711 static int RIG_parentControl(RigControl *ctrl, EditBone *link)
718 VecSubf(offset, ctrl->bone->head, link->head);
720 /* if root matches, check for direction too */
721 if (Inpf(offset, offset) < 0.0001)
723 float vbone[3], vparent[3];
725 flag |= RIG_CTRL_FIT_ROOT;
727 VecSubf(vbone, ctrl->bone->tail, ctrl->bone->head);
728 VecSubf(vparent, link->tail, link->head);
730 /* test for opposite direction */
731 if (Inpf(vbone, vparent) > 0)
736 Crossf(nor, vbone, vparent);
738 len = Inpf(nor, nor);
741 flag |= RIG_CTRL_FIT_BONE;
746 /* Bail out if old one is automatically better */
747 if (flag < ctrl->flag)
752 /* if there's already a link
753 * overwrite only if new link is higher in the chain */
754 if (ctrl->link && flag == ctrl->flag)
756 EditBone *bone = NULL;
758 for (bone = ctrl->link; bone; bone = bone->parent)
760 /* if link is in the chain, break and use that one */
767 /* not in chain, don't update link */
778 VECCOPY(ctrl->offset, offset);
786 static void RIG_reconnectControlBones(RigGraph *rg)
791 /* first pass, link to deform bones */
792 for (ctrl = rg->controls.first; ctrl; ctrl = ctrl->next)
798 /* DO SOME MAGIC HERE */
799 for (pchan= rg->ob->pose->chanbase.first; pchan; pchan= pchan->next)
801 for (con= pchan->constraints.first; con; con= con->next)
803 bConstraintTypeInfo *cti= constraint_get_typeinfo(con);
804 ListBase targets = {NULL, NULL};
805 bConstraintTarget *ct;
807 /* constraint targets */
808 if (cti && cti->get_constraint_targets)
812 cti->get_constraint_targets(con, &targets);
814 for (target_index = 0, ct= targets.first; ct; target_index++, ct= ct->next)
816 if ((ct->tar == rg->ob) && strcmp(ct->subtarget, ctrl->bone->name) == 0)
818 /* SET bone link to bone corresponding to pchan */
819 EditBone *link = BLI_ghash_lookup(rg->bones_map, pchan->name);
821 /* Making sure bone is in this armature */
824 /* for pole targets, link to parent bone instead, if possible */
825 if (con->type == CONSTRAINT_TYPE_KINEMATIC && target_index == 1)
827 if (link->parent && BLI_ghash_haskey(rg->bones_map, link->parent->name))
833 found = RIG_parentControl(ctrl, link);
838 if (cti->flush_constraint_targets)
839 cti->flush_constraint_targets(con, &targets, 0);
844 /* if not found yet, check parent */
847 if (ctrl->bone->parent)
849 /* make sure parent is a deforming bone
852 EditBone *link = BLI_ghash_lookup(rg->bones_map, ctrl->bone->parent->name);
854 found = RIG_parentControl(ctrl, link);
857 /* check if bone is not superposed on another one */
860 RigArc *best_arc = NULL;
861 EditBone *link = NULL;
863 for (arc = rg->arcs.first; arc; arc = arc->next)
866 for (edge = arc->edges.first; edge; edge = edge->next)
872 fit = VecLenf(ctrl->bone->head, edge->bone->head) < 0.0001;
873 fit = fit || VecLenf(ctrl->bone->tail, edge->bone->tail) < 0.0001;
877 /* pick the bone on the arc with the lowest symmetry level
878 * means you connect control to the trunk of the skeleton */
879 if (best_arc == NULL || arc->symmetry_level < best_arc->symmetry_level)
889 found = RIG_parentControl(ctrl, link);
893 /* if not found yet, check child */
897 RigArc *best_arc = NULL;
898 EditBone *link = NULL;
900 for (arc = rg->arcs.first; arc; arc = arc->next)
903 for (edge = arc->edges.first; edge; edge = edge->next)
905 if (edge->bone && edge->bone->parent == ctrl->bone)
907 /* pick the bone on the arc with the lowest symmetry level
908 * means you connect control to the trunk of the skeleton */
909 if (best_arc == NULL || arc->symmetry_level < best_arc->symmetry_level)
918 found = RIG_parentControl(ctrl, link);
924 /* second pass, make chains in control bones */
929 for (ctrl = rg->controls.first; ctrl; ctrl = ctrl->next)
931 /* if control is not linked yet */
932 if (ctrl->link == NULL)
936 RigControl *ctrl_parent = NULL;
937 RigControl *ctrl_child;
940 if (ctrl->bone->parent)
942 ctrl_parent = BLI_ghash_lookup(rg->controls_map, ctrl->bone->parent->name);
945 /* check constraints first */
947 /* DO SOME MAGIC HERE */
948 for (pchan= rg->ob->pose->chanbase.first; pchan; pchan= pchan->next)
950 for (con= pchan->constraints.first; con; con= con->next)
952 bConstraintTypeInfo *cti= constraint_get_typeinfo(con);
953 ListBase targets = {NULL, NULL};
954 bConstraintTarget *ct;
956 /* constraint targets */
957 if (cti && cti->get_constraint_targets)
959 cti->get_constraint_targets(con, &targets);
961 for (ct= targets.first; ct; ct= ct->next)
963 if ((ct->tar == rg->ob) && strcmp(ct->subtarget, ctrl->bone->name) == 0)
965 /* SET bone link to ctrl corresponding to pchan */
966 RigControl *link = BLI_ghash_lookup(rg->controls_map, pchan->name);
968 /* if owner is a control bone, link with it */
969 if (link && link->link)
971 RIG_parentControl(ctrl, link->bone);
978 if (cti->flush_constraint_targets)
979 cti->flush_constraint_targets(con, &targets, 0);
986 /* check if parent is already linked */
987 if (ctrl_parent && ctrl_parent->link)
989 RIG_parentControl(ctrl, ctrl_parent->bone);
995 for (ctrl_child = rg->controls.first; ctrl_child; ctrl_child = ctrl_child->next)
997 /* if a child is linked, link to that one */
998 if (ctrl_child->link && ctrl_child->bone->parent == ctrl->bone)
1000 RIG_parentControl(ctrl, ctrl_child->bone);
1011 /* third pass, link control tails */
1012 for (ctrl = rg->controls.first; ctrl; ctrl = ctrl->next)
1014 /* fit bone already means full match, so skip those */
1015 if ((ctrl->flag & RIG_CTRL_FIT_BONE) == 0)
1019 /* look on deform bones first */
1020 BLI_ghashIterator_init(&ghi, rg->bones_map);
1022 for( ; !BLI_ghashIterator_isDone(&ghi); BLI_ghashIterator_step(&ghi))
1024 EditBone *bone = (EditBone*)BLI_ghashIterator_getValue(&ghi);
1026 /* don't link with parent */
1027 if (bone->parent != ctrl->bone)
1029 if (VecLenf(ctrl->bone->tail, bone->head) < 0.01)
1031 ctrl->tail_mode = TL_HEAD;
1032 ctrl->link_tail = bone;
1035 else if (VecLenf(ctrl->bone->tail, bone->tail) < 0.01)
1037 ctrl->tail_mode = TL_TAIL;
1038 ctrl->link_tail = bone;
1044 /* if we haven't found one yet, look in control bones */
1045 if (ctrl->tail_mode == TL_NONE)
1053 /*******************************************************************************************************/
1055 static void RIG_joinArcs(RigGraph *rg, RigNode *node, RigArc *joined_arc1, RigArc *joined_arc2)
1057 RigEdge *edge, *next_edge;
1059 /* ignore cases where joint is at start or end */
1060 if (joined_arc1->head == joined_arc2->head || joined_arc1->tail == joined_arc2->tail)
1065 /* swap arcs to make sure arc1 is before arc2 */
1066 if (joined_arc1->head == joined_arc2->tail)
1068 RigArc *tmp = joined_arc1;
1069 joined_arc1 = joined_arc2;
1073 for (edge = joined_arc2->edges.first; edge; edge = next_edge)
1075 next_edge = edge->next;
1077 RIG_appendEdgeToArc(joined_arc1, edge);
1080 joined_arc1->tail = joined_arc2->tail;
1082 joined_arc2->edges.first = joined_arc2->edges.last = NULL;
1084 BLI_removeArc((BGraph*)rg, (BArc*)joined_arc2);
1086 BLI_removeNode((BGraph*)rg, (BNode*)node);
1089 static void RIG_removeNormalNodes(RigGraph *rg)
1091 RigNode *node, *next_node;
1093 for (node = rg->nodes.first; node; node = next_node)
1095 next_node = node->next;
1097 if (node->degree == 2)
1099 RigArc *arc, *joined_arc1 = NULL, *joined_arc2 = NULL;
1101 for (arc = rg->arcs.first; arc; arc = arc->next)
1103 if (arc->head == node || arc->tail == node)
1105 if (joined_arc1 == NULL)
1117 RIG_joinArcs(rg, node, joined_arc1, joined_arc2);
1122 static void RIG_removeUneededOffsets(RigGraph *rg)
1126 for (arc = rg->arcs.first; arc; arc = arc->next)
1128 RigEdge *first_edge, *last_edge;
1130 first_edge = arc->edges.first;
1131 last_edge = arc->edges.last;
1133 if (first_edge->bone == NULL)
1135 if (first_edge->bone == NULL && VecLenf(first_edge->tail, arc->head->p) <= 0.001)
1137 BLI_remlink(&arc->edges, first_edge);
1138 MEM_freeN(first_edge);
1140 else if (arc->head->degree == 1)
1142 RigNode *new_node = (RigNode*)BLI_FindNodeByPosition((BGraph*)rg, first_edge->tail, 0.001);
1146 BLI_remlink(&arc->edges, first_edge);
1147 MEM_freeN(first_edge);
1148 BLI_replaceNodeInArc((BGraph*)rg, (BArc*)arc, (BNode*)new_node, (BNode*)arc->head);
1152 RigEdge *next_edge = first_edge->next;
1156 BLI_remlink(&arc->edges, first_edge);
1157 MEM_freeN(first_edge);
1159 VECCOPY(arc->head->p, next_edge->head);
1165 /* check if all arc connected start with a null edge */
1167 for (other_arc = rg->arcs.first; other_arc; other_arc = other_arc->next)
1169 if (other_arc != arc)
1172 if (other_arc->head == arc->head)
1174 test_edge = other_arc->edges.first;
1176 if (test_edge->bone != NULL)
1181 else if (other_arc->tail == arc->head)
1183 test_edge = other_arc->edges.last;
1185 if (test_edge->bone != NULL)
1193 if (other_arc == NULL)
1195 RigNode *new_node = (RigNode*)BLI_FindNodeByPosition((BGraph*)rg, first_edge->tail, 0.001);
1199 /* remove null edge in other arcs too */
1200 for (other_arc = rg->arcs.first; other_arc; other_arc = other_arc->next)
1202 if (other_arc != arc)
1205 if (other_arc->head == arc->head)
1207 BLI_replaceNodeInArc((BGraph*)rg, (BArc*)other_arc, (BNode*)new_node, (BNode*)other_arc->head);
1208 test_edge = other_arc->edges.first;
1209 BLI_remlink(&other_arc->edges, test_edge);
1210 MEM_freeN(test_edge);
1212 else if (other_arc->tail == arc->head)
1214 BLI_replaceNodeInArc((BGraph*)rg, (BArc*)other_arc, (BNode*)new_node, (BNode*)other_arc->tail);
1215 test_edge = other_arc->edges.last;
1216 BLI_remlink(&other_arc->edges, test_edge);
1217 MEM_freeN(test_edge);
1222 BLI_remlink(&arc->edges, first_edge);
1223 MEM_freeN(first_edge);
1224 BLI_replaceNodeInArc((BGraph*)rg, (BArc*)arc, (BNode*)new_node, (BNode*)arc->head);
1228 RigEdge *next_edge = first_edge->next;
1232 BLI_remlink(&arc->edges, first_edge);
1233 MEM_freeN(first_edge);
1235 VECCOPY(arc->head->p, next_edge->head);
1237 /* remove null edge in other arcs too */
1238 for (other_arc = rg->arcs.first; other_arc; other_arc = other_arc->next)
1240 if (other_arc != arc)
1243 if (other_arc->head == arc->head)
1245 test_edge = other_arc->edges.first;
1246 BLI_remlink(&other_arc->edges, test_edge);
1247 MEM_freeN(test_edge);
1249 else if (other_arc->tail == arc->head)
1251 test_edge = other_arc->edges.last;
1252 BLI_remlink(&other_arc->edges, test_edge);
1253 MEM_freeN(test_edge);
1263 if (last_edge->bone == NULL)
1265 if (VecLenf(last_edge->head, arc->tail->p) <= 0.001)
1267 BLI_remlink(&arc->edges, last_edge);
1268 MEM_freeN(last_edge);
1270 else if (arc->tail->degree == 1)
1272 RigNode *new_node = (RigNode*)BLI_FindNodeByPosition((BGraph*)rg, last_edge->head, 0.001);
1276 RigEdge *previous_edge = last_edge->prev;
1278 BLI_remlink(&arc->edges, last_edge);
1279 MEM_freeN(last_edge);
1280 BLI_replaceNodeInArc((BGraph*)rg, (BArc*)arc, (BNode*)new_node, (BNode*)arc->tail);
1282 /* set previous angle to 0, since there's no following edges */
1285 previous_edge->angle = 0;
1290 RigEdge *previous_edge = last_edge->prev;
1294 BLI_remlink(&arc->edges, last_edge);
1295 MEM_freeN(last_edge);
1297 VECCOPY(arc->tail->p, previous_edge->tail);
1298 previous_edge->angle = 0;
1306 static void RIG_arcFromBoneChain(RigGraph *rg, ListBase *list, EditBone *root_bone, RigNode *starting_node, int selected)
1308 EditBone *bone, *last_bone = root_bone;
1310 int contain_head = 0;
1312 for(bone = root_bone; bone; bone = nextEditBoneChild(list, bone, 0))
1316 if (selected == 0 || (bone->flag & BONE_SELECTED))
1318 if ((bone->flag & BONE_NO_DEFORM) == 0)
1320 BLI_ghash_insert(rg->bones_map, bone->name, bone);
1324 arc = newRigArc(rg);
1326 if (starting_node == NULL)
1328 starting_node = newRigNodeHead(rg, arc, root_bone->head);
1332 addRigNodeHead(rg, arc, starting_node);
1336 if (bone->parent && (bone->flag & BONE_CONNECTED) == 0)
1338 RIG_addEdgeToArc(arc, bone->head, NULL);
1341 RIG_addEdgeToArc(arc, bone->tail, bone);
1345 if (strcmp(bone->name, "head") == 0)
1350 else if ((bone->flag & BONE_EDITMODE_LOCKED) == 0) /* ignore locked bones */
1352 RIG_addControlBone(rg, bone);
1356 nb_children = countEditBoneChildren(list, bone);
1357 if (nb_children > 1)
1359 RigNode *end_node = NULL;
1364 end_node = newRigNodeTail(rg, arc, bone->tail);
1368 end_node = newRigNode(rg, bone->tail);
1371 for (i = 0; i < nb_children; i++)
1373 root_bone = nextEditBoneChild(list, bone, i);
1374 RIG_arcFromBoneChain(rg, list, root_bone, end_node, selected);
1377 /* arc ends here, break */
1382 /* If the loop exited without forking */
1383 if (arc != NULL && bone == NULL)
1385 newRigNodeTail(rg, arc, last_bone->tail);
1390 rg->head = arc->tail;
1394 /*******************************************************************************************************/
1395 static void RIG_findHead(RigGraph *rg)
1397 if (rg->head == NULL)
1399 if (BLI_countlist(&rg->arcs) == 1)
1401 RigArc *arc = rg->arcs.first;
1403 rg->head = (RigNode*)arc->head;
1409 for (arc = rg->arcs.first; arc; arc = arc->next)
1411 RigEdge *edge = arc->edges.last;
1413 if (edge->bone->flag & (BONE_TIPSEL|BONE_SELECTED))
1415 rg->head = arc->tail;
1421 if (rg->head == NULL)
1423 rg->head = rg->nodes.first;
1428 /*******************************************************************************************************/
1430 void RIG_printNode(RigNode *node, char name[])
1432 printf("%s %p %i <%0.3f, %0.3f, %0.3f>\n", name, node, node->degree, node->p[0], node->p[1], node->p[2]);
1434 if (node->symmetry_flag & SYM_TOPOLOGICAL)
1436 if (node->symmetry_flag & SYM_AXIAL)
1437 printf("Symmetry AXIAL\n");
1438 else if (node->symmetry_flag & SYM_RADIAL)
1439 printf("Symmetry RADIAL\n");
1441 printvecf("symmetry axis", node->symmetry_axis);
1445 void RIG_printArcBones(RigArc *arc)
1449 for (edge = arc->edges.first; edge; edge = edge->next)
1452 printf("%s ", edge->bone->name);
1459 void RIG_printCtrl(RigControl *ctrl, char *indent)
1463 printf("%sBone: %s\n", indent, ctrl->bone->name);
1464 printf("%sLink: %s\n", indent, ctrl->link ? ctrl->link->name : "!NONE!");
1466 sprintf(text, "%soffset", indent);
1467 printvecf(text, ctrl->offset);
1469 printf("%sFlag: %i\n", indent, ctrl->flag);
1472 void RIG_printLinkedCtrl(RigGraph *rg, EditBone *bone, int tabs)
1479 for (i = 0; i < tabs; i++)
1486 for (ctrl = rg->controls.first; ctrl; ctrl = ctrl->next)
1488 if (ctrl->link == bone)
1490 RIG_printCtrl(ctrl, indent);
1491 RIG_printLinkedCtrl(rg, ctrl->bone, tabs + 1);
1496 void RIG_printArc(RigGraph *rg, RigArc *arc)
1500 RIG_printNode((RigNode*)arc->head, "head");
1502 for (edge = arc->edges.first; edge; edge = edge->next)
1504 printf("\tinner joints %0.3f %0.3f %0.3f\n", edge->tail[0], edge->tail[1], edge->tail[2]);
1505 printf("\t\tlength %f\n", edge->length);
1506 printf("\t\tangle %f\n", edge->angle * 180 / M_PI);
1509 printf("\t\t%s\n", edge->bone->name);
1510 RIG_printLinkedCtrl(rg, edge->bone, 3);
1513 printf("symmetry level: %i flag: %i group %i\n", arc->symmetry_level, arc->symmetry_flag, arc->symmetry_group);
1515 RIG_printNode((RigNode*)arc->tail, "tail");
1518 void RIG_printGraph(RigGraph *rg)
1522 printf("---- ARCS ----\n");
1523 for (arc = rg->arcs.first; arc; arc = arc->next)
1525 RIG_printArc(rg, arc);
1531 RIG_printNode(rg->head, "HEAD NODE:");
1535 printf("HEAD NODE: NONE\n");
1539 /*******************************************************************************************************/
1541 RigGraph *RIG_graphFromArmature(const bContext *C, Object *ob, bArmature *arm)
1543 Object *obedit = CTX_data_edit_object(C);
1544 Scene *scene = CTX_data_scene(C);
1552 bArmature *arm = obedit->data;
1553 rg->editbones = arm->edbo;
1557 rg->editbones = MEM_callocN(sizeof(ListBase), "EditBones");
1558 make_boneList(rg->editbones, &arm->bonebase, NULL);
1559 rg->flag |= RIG_FREE_BONELIST;
1564 /* Do the rotations */
1565 for (ebone = rg->editbones->first; ebone; ebone=ebone->next){
1566 if (ebone->parent == NULL)
1568 RIG_arcFromBoneChain(rg, rg->editbones, ebone, NULL, 0);
1572 BLI_removeDoubleNodes((BGraph*)rg, 0.001);
1574 RIG_removeNormalNodes(rg);
1576 RIG_removeUneededOffsets(rg);
1578 BLI_buildAdjacencyList((BGraph*)rg);
1582 BLI_markdownSymmetry((BGraph*)rg, (BNode*)rg->head, scene->toolsettings->skgen_symmetry_limit);
1584 RIG_reconnectControlBones(rg); /* after symmetry, because we use levels to find best match */
1586 if (BLI_isGraphCyclic((BGraph*)rg))
1588 printf("armature cyclic\n");
1594 RigGraph *armatureSelectedToGraph(bContext *C, Object *ob, bArmature *arm)
1596 Object *obedit = CTX_data_edit_object(C);
1597 Scene *scene = CTX_data_scene(C);
1605 rg->editbones = arm->edbo;
1609 rg->editbones = MEM_callocN(sizeof(ListBase), "EditBones");
1610 make_boneList(rg->editbones, &arm->bonebase, NULL);
1611 rg->flag |= RIG_FREE_BONELIST;
1616 /* Do the rotations */
1617 for (ebone = rg->editbones->first; ebone; ebone=ebone->next){
1618 if (ebone->parent == NULL)
1620 RIG_arcFromBoneChain(rg, rg->editbones, ebone, NULL, 1);
1624 BLI_removeDoubleNodes((BGraph*)rg, 0.001);
1626 RIG_removeNormalNodes(rg);
1628 RIG_removeUneededOffsets(rg);
1630 BLI_buildAdjacencyList((BGraph*)rg);
1634 BLI_markdownSymmetry((BGraph*)rg, (BNode*)rg->head, scene->toolsettings->skgen_symmetry_limit);
1636 RIG_reconnectControlBones(rg); /* after symmetry, because we use levels to find best match */
1638 if (BLI_isGraphCyclic((BGraph*)rg))
1640 printf("armature cyclic\n");
1645 /************************************ GENERATING *****************************************************/
1648 static EditBone *add_editbonetolist(char *name, ListBase *list)
1650 EditBone *bone= MEM_callocN(sizeof(EditBone), "eBone");
1652 BLI_strncpy(bone->name, name, 32);
1653 unique_editbone_name(list, bone->name, NULL);
1655 BLI_addtail(list, bone);
1657 bone->flag |= BONE_TIPSEL;
1664 bone->rad_head= 0.10;
1665 bone->rad_tail= 0.05;
1667 bone->layer= 1;//arm->layer;
1673 void generateMissingArcsFromNode(RigGraph *rigg, ReebNode *node, int multi_level_limit)
1675 while (node->multi_level > multi_level_limit && node->link_up)
1677 node = node->link_up;
1680 while (node->multi_level < multi_level_limit && node->link_down)
1682 node = node->link_down;
1685 if (node->multi_level == multi_level_limit)
1689 for (i = 0; i < node->degree; i++)
1691 ReebArc *earc = node->arcs[i];
1693 if (earc->flag == ARC_FREE && earc->head == node)
1695 ReebNode *other = BIF_otherNodeFromIndex(earc, node);
1697 earc->flag = ARC_USED;
1699 //generateBonesForArc(rigg, earc, node, other);
1700 generateMissingArcsFromNode(rigg, other, multi_level_limit);
1706 void generateMissingArcs(RigGraph *rigg)
1708 ReebGraph *reebg = rigg->link_mesh;
1709 int multi_level_limit = 5;
1711 for (reebg = rigg->link_mesh; reebg; reebg = reebg->link_up)
1715 for (earc = reebg->arcs.first; earc; earc = earc->next)
1717 if (earc->flag == ARC_USED)
1719 generateMissingArcsFromNode(rigg, earc->head, multi_level_limit);
1720 generateMissingArcsFromNode(rigg, earc->tail, multi_level_limit);
1726 /************************************ RETARGETTING *****************************************************/
1728 static void repositionControl(RigGraph *rigg, RigControl *ctrl, float head[3], float tail[3], float qrot[4], float resize);
1730 static void repositionTailControl(RigGraph *rigg, RigControl *ctrl);
1732 static void finalizeControl(RigGraph *rigg, RigControl *ctrl, float resize)
1734 if ((ctrl->flag & RIG_CTRL_DONE) == RIG_CTRL_DONE)
1736 RigControl *ctrl_child;
1739 printf("CTRL: %s LINK: %s", ctrl->bone->name, ctrl->link->name);
1741 if (ctrl->link_tail)
1743 printf(" TAIL: %s", ctrl->link_tail->name);
1749 /* if there was a tail link: apply link, recalc resize factor and qrot */
1750 if (ctrl->tail_mode != TL_NONE)
1752 float *tail_vec = NULL;
1753 float v1[3], v2[3], qtail[4];
1755 if (ctrl->tail_mode == TL_TAIL)
1757 tail_vec = ctrl->link_tail->tail;
1759 else if (ctrl->tail_mode == TL_HEAD)
1761 tail_vec = ctrl->link_tail->head;
1764 VecSubf(v1, ctrl->bone->tail, ctrl->bone->head);
1765 VecSubf(v2, tail_vec, ctrl->bone->head);
1767 VECCOPY(ctrl->bone->tail, tail_vec);
1769 RotationBetweenVectorsToQuat(qtail, v1, v2);
1770 QuatMul(ctrl->qrot, qtail, ctrl->qrot);
1772 resize = VecLength(v2) / VecLenf(ctrl->head, ctrl->tail);
1775 ctrl->bone->roll = rollBoneByQuat(ctrl->bone, ctrl->up_axis, ctrl->qrot);
1777 /* Cascade to connected control bones */
1778 for (ctrl_child = rigg->controls.first; ctrl_child; ctrl_child = ctrl_child->next)
1780 if (ctrl_child->link == ctrl->bone)
1782 repositionControl(rigg, ctrl_child, ctrl->bone->head, ctrl->bone->tail, ctrl->qrot, resize);
1784 if (ctrl_child->link_tail == ctrl->bone)
1786 repositionTailControl(rigg, ctrl_child);
1792 static void repositionTailControl(RigGraph *rigg, RigControl *ctrl)
1794 ctrl->flag |= RIG_CTRL_TAIL_DONE;
1796 finalizeControl(rigg, ctrl, 1); /* resize will be recalculated anyway so we don't need it */
1799 static void repositionControl(RigGraph *rigg, RigControl *ctrl, float head[3], float tail[3], float qrot[4], float resize)
1801 float parent_offset[3], tail_offset[3];
1803 VECCOPY(parent_offset, ctrl->offset);
1804 VecMulf(parent_offset, resize);
1805 QuatMulVecf(qrot, parent_offset);
1807 VecAddf(ctrl->bone->head, head, parent_offset);
1809 ctrl->flag |= RIG_CTRL_HEAD_DONE;
1811 QUATCOPY(ctrl->qrot, qrot);
1813 if (ctrl->tail_mode == TL_NONE)
1815 VecSubf(tail_offset, ctrl->tail, ctrl->head);
1816 VecMulf(tail_offset, resize);
1817 QuatMulVecf(qrot, tail_offset);
1819 VecAddf(ctrl->bone->tail, ctrl->bone->head, tail_offset);
1821 ctrl->flag |= RIG_CTRL_TAIL_DONE;
1824 finalizeControl(rigg, ctrl, resize);
1827 static void repositionBone(bContext *C, RigGraph *rigg, RigEdge *edge, float vec0[3], float vec1[3], float up_axis[3])
1829 Scene *scene = CTX_data_scene(C);
1832 float qrot[4], resize;
1838 VecSubf(v1, edge->tail, edge->head);
1839 VecSubf(v2, vec1, vec0);
1846 RotationBetweenVectorsToQuat(qrot, v1, v2);
1848 VECCOPY(bone->head, vec0);
1849 VECCOPY(bone->tail, vec1);
1851 if (!VecIsNull(up_axis))
1855 if (scene->toolsettings->skgen_retarget_roll == SK_RETARGET_ROLL_VIEW)
1857 bone->roll = rollBoneByQuatAligned(bone, edge->up_axis, qrot, qroll, up_axis);
1859 else if (scene->toolsettings->skgen_retarget_roll == SK_RETARGET_ROLL_JOINT)
1861 bone->roll = rollBoneByQuatJoint(edge, edge->prev, qrot, qroll, up_axis);
1868 QuatMul(qrot, qroll, qrot);
1872 bone->roll = rollBoneByQuat(bone, edge->up_axis, qrot);
1875 for (ctrl = rigg->controls.first; ctrl; ctrl = ctrl->next)
1877 if (ctrl->link == bone)
1879 repositionControl(rigg, ctrl, vec0, vec1, qrot, resize);
1881 if (ctrl->link_tail == bone)
1883 repositionTailControl(rigg, ctrl);
1888 static RetargetMode detectArcRetargetMode(RigArc *arc);
1889 static void retargetArctoArcLength(bContext *C, RigGraph *rigg, RigArc *iarc, RigNode *inode_start);
1892 static RetargetMode detectArcRetargetMode(RigArc *iarc)
1894 RetargetMode mode = RETARGET_AGGRESSIVE;
1895 ReebArc *earc = iarc->link_mesh;
1897 int large_angle = 0;
1898 float avg_angle = 0;
1899 float avg_length = 0;
1903 for (edge = iarc->edges.first; edge; edge = edge->next)
1905 avg_angle += edge->angle;
1909 avg_angle /= nb_edges - 1; /* -1 because last edge doesn't have an angle */
1911 avg_length = iarc->length / nb_edges;
1916 for (edge = iarc->edges.first; edge; edge = edge->next)
1918 if (fabs(edge->angle - avg_angle) > M_PI / 6)
1924 else if (nb_edges == 2 && avg_angle > 0)
1930 if (large_angle == 0)
1932 mode = RETARGET_LENGTH;
1935 if (earc->bcount <= (iarc->count - 1))
1937 mode = RETARGET_LENGTH;
1940 mode = RETARGET_AGGRESSIVE;
1946 static void printMovesNeeded(int *positions, int nb_positions)
1951 for (i = 0; i < nb_positions; i++)
1953 moves += positions[i] - (i + 1);
1956 printf("%i moves needed\n", moves);
1959 static void printPositions(int *positions, int nb_positions)
1963 for (i = 0; i < nb_positions; i++)
1965 printf("%i ", positions[i]);
1971 #define MAX_COST FLT_MAX /* FIX ME */
1973 static float costDistance(BArcIterator *iter, float *vec0, float *vec1, int i0, int i1, float distance_weight)
1975 EmbedBucket *bucket = NULL;
1977 float v1[3], v2[3], c[3];
1980 if (distance_weight > 0)
1982 VecSubf(v1, vec0, vec1);
1984 v1_inpf = Inpf(v1, v1);
1989 for (j = i0 + 1; j < i1 - 1; j++)
1993 bucket = IT_peek(iter, j);
1995 VecSubf(v2, bucket->p, vec1);
1999 dist = Inpf(c, c) / v1_inpf;
2001 max_dist = dist > max_dist ? dist : max_dist;
2004 return distance_weight * max_dist;
2017 static float costAngle(float original_angle, float vec_first[3], float vec_second[3], float angle_weight)
2019 if (angle_weight > 0)
2021 float current_angle;
2023 if (!VecIsNull(vec_first) && !VecIsNull(vec_second))
2025 current_angle = saacos(Inpf(vec_first, vec_second));
2027 return angle_weight * fabs(current_angle - original_angle);
2031 return angle_weight * M_PI;
2040 static float costLength(float original_length, float current_length, float length_weight)
2042 if (current_length == 0)
2048 float length_ratio = fabs((current_length - original_length) / original_length);
2049 return length_weight * length_ratio * length_ratio;
2054 static float calcCostLengthDistance(BArcIterator *iter, float **vec_cache, RigEdge *edge, float *vec1, float *vec2, int i1, int i2)
2059 VecSubf(vec, vec2, vec1);
2060 length = Normalize(vec);
2062 return costLength(edge->length, length) + costDistance(iter, vec1, vec2, i1, i2);
2066 static float calcCostAngleLengthDistance(BArcIterator *iter, float **vec_cache, RigEdge *edge, float *vec0, float *vec1, float *vec2, int i1, int i2, float angle_weight, float length_weight, float distance_weight)
2068 float vec_second[3], vec_first[3];
2072 VecSubf(vec_second, vec2, vec1);
2073 length2 = Normalize(vec_second);
2079 VecSubf(vec_first, vec1, vec0);
2080 Normalize(vec_first);
2082 new_cost += costAngle(edge->prev->angle, vec_first, vec_second, angle_weight);
2086 new_cost += costLength(edge->length, length2, length_weight);
2089 new_cost += costDistance(iter, vec1, vec2, i1, i2, distance_weight);
2094 static int indexMemoNode(int nb_positions, int previous, int current, int joints_left)
2096 return joints_left * nb_positions * nb_positions + current * nb_positions + previous;
2099 static void copyMemoPositions(int *positions, MemoNode *table, int nb_positions, int joints_left)
2101 int previous = 0, current = 0;
2104 for (i = 0; joints_left > 0; joints_left--, i++)
2107 node = table + indexMemoNode(nb_positions, previous, current, joints_left);
2109 positions[i] = node->next;
2112 current = node->next;
2116 static MemoNode * solveJoints(MemoNode *table, BArcIterator *iter, float **vec_cache, int nb_joints, int nb_positions, int previous, int current, RigEdge *edge, int joints_left, float angle_weight, float length_weight, float distance_weight)
2119 int index = indexMemoNode(nb_positions, previous, current, joints_left);
2121 node = table + index;
2123 if (node->weight != 0)
2127 else if (joints_left == 0)
2129 float *vec0 = vec_cache[previous];
2130 float *vec1 = vec_cache[current];
2131 float *vec2 = vec_cache[nb_positions + 1];
2133 node->weight = calcCostAngleLengthDistance(iter, vec_cache, edge, vec0, vec1, vec2, current, iter->length, angle_weight, length_weight, distance_weight);
2139 MemoNode *min_node = NULL;
2140 float *vec0 = vec_cache[previous];
2141 float *vec1 = vec_cache[current];
2142 float min_weight= 0.0f;
2146 for (next = current + 1; next <= nb_positions - (joints_left - 1); next++)
2148 MemoNode *next_node;
2149 float *vec2 = vec_cache[next];
2150 float weight = 0.0f;
2152 /* ADD WEIGHT OF PREVIOUS - CURRENT - NEXT triple */
2153 weight = calcCostAngleLengthDistance(iter, vec_cache, edge, vec0, vec1, vec2, current, next, angle_weight, length_weight, distance_weight);
2155 if (weight >= MAX_COST)
2160 /* add node weight */
2161 next_node = solveJoints(table, iter, vec_cache, nb_joints, nb_positions, current, next, edge->next, joints_left - 1, angle_weight, length_weight, distance_weight);
2162 weight += next_node->weight;
2164 if (min_node == NULL || weight < min_weight)
2166 min_weight = weight;
2167 min_node = next_node;
2174 node->weight = min_weight;
2175 node->next = min_next;
2180 node->weight = MAX_COST;
2187 static int testFlipArc(RigArc *iarc, RigNode *inode_start)
2189 ReebArc *earc = iarc->link_mesh;
2190 ReebNode *enode_start = BIF_NodeFromIndex(earc, inode_start->link_mesh);
2192 /* no flip needed if both nodes are the same */
2193 if ((enode_start == earc->head && inode_start == iarc->head) || (enode_start == earc->tail && inode_start == iarc->tail))
2203 static void retargetArctoArcAggresive(bContext *C, RigGraph *rigg, RigArc *iarc, RigNode *inode_start)
2205 ReebArcIterator arc_iter;
2206 BArcIterator *iter = (BArcIterator*)&arc_iter;
2208 EmbedBucket *bucket = NULL;
2209 ReebNode *node_start, *node_end;
2210 ReebArc *earc = iarc->link_mesh;
2211 float angle_weight = 1.0; // GET FROM CONTEXT
2212 float length_weight = 1.0;
2213 float distance_weight = 1.0;
2214 float min_cost = FLT_MAX;
2216 int *best_positions;
2217 int nb_edges = BLI_countlist(&iarc->edges);
2218 int nb_joints = nb_edges - 1;
2219 RetargetMethod method = METHOD_MEMOIZE;
2222 if (nb_joints > earc->bcount)
2224 printf("NOT ENOUGH BUCKETS!\n");
2228 best_positions = MEM_callocN(sizeof(int) * nb_joints, "Best positions");
2230 if (testFlipArc(iarc, inode_start))
2232 node_start = earc->tail;
2233 node_end = earc->head;
2237 node_start = earc->head;
2238 node_end = earc->tail;
2241 /* equal number of joints and potential position, just fill them in */
2242 if (nb_joints == earc->bcount)
2246 /* init with first values */
2247 for (i = 0; i < nb_joints; i++)
2249 best_positions[i] = i + 1;
2252 if (method == METHOD_MEMOIZE)
2254 int nb_positions = earc->bcount;
2255 int nb_memo_nodes = nb_positions * nb_positions * (nb_joints + 1);
2256 MemoNode *table = MEM_callocN(nb_memo_nodes * sizeof(MemoNode), "memoization table");
2258 float **positions_cache = MEM_callocN(sizeof(float*) * (nb_positions + 2), "positions cache");
2261 positions_cache[0] = node_start->p;
2262 positions_cache[nb_positions + 1] = node_end->p;
2264 initArcIterator(iter, earc, node_start);
2266 for (i = 1; i <= nb_positions; i++)
2268 EmbedBucket *bucket = IT_peek(iter, i);
2269 positions_cache[i] = bucket->p;
2272 result = solveJoints(table, iter, positions_cache, nb_joints, earc->bcount, 0, 0, iarc->edges.first, nb_joints, angle_weight, length_weight, distance_weight);
2274 min_cost = result->weight;
2275 copyMemoPositions(best_positions, table, earc->bcount, nb_joints);
2278 MEM_freeN(positions_cache);
2281 vec0 = node_start->p;
2282 initArcIterator(iter, earc, node_start);
2285 printPositions(best_positions, nb_joints);
2286 printMovesNeeded(best_positions, nb_joints);
2287 printf("min_cost %f\n", min_cost);
2288 printf("buckets: %i\n", earc->bcount);
2291 /* set joints to best position */
2292 for (edge = iarc->edges.first, i = 0;
2294 edge = edge->next, i++)
2299 bucket = IT_peek(iter, best_positions[i]);
2311 repositionBone(C, rigg, edge, vec0, vec1, no);
2317 MEM_freeN(best_positions);
2320 static void retargetArctoArcLength(bContext *C, RigGraph *rigg, RigArc *iarc, RigNode *inode_start)
2322 ReebArcIterator arc_iter;
2323 BArcIterator *iter = (BArcIterator*)&arc_iter;
2324 ReebArc *earc = iarc->link_mesh;
2325 ReebNode *node_start, *node_end;
2327 EmbedBucket *bucket = NULL;
2328 float embedding_length = 0;
2331 float *previous_vec = NULL;
2334 if (testFlipArc(iarc, inode_start))
2336 node_start = (ReebNode*)earc->tail;
2337 node_end = (ReebNode*)earc->head;
2341 node_start = (ReebNode*)earc->head;
2342 node_end = (ReebNode*)earc->tail;
2345 initArcIterator(iter, earc, node_start);
2347 bucket = IT_next(iter);
2349 vec0 = node_start->p;
2351 while (bucket != NULL)
2355 embedding_length += VecLenf(vec0, vec1);
2358 bucket = IT_next(iter);
2361 embedding_length += VecLenf(node_end->p, vec1);
2364 initArcIterator(iter, earc, node_start);
2366 bucket = IT_next(iter);
2368 vec0 = node_start->p;
2369 previous_vec = vec0;
2372 for (edge = iarc->edges.first; edge; edge = edge->next)
2374 float new_bone_length = edge->length / iarc->length * embedding_length;
2378 while (bucket && new_bone_length > length)
2380 length += VecLenf(previous_vec, vec1);
2381 bucket = IT_next(iter);
2382 previous_vec = vec1;
2393 /* no need to move virtual edges (space between unconnected bones) */
2396 repositionBone(C, rigg, edge, vec0, vec1, no);
2400 previous_vec = vec1;
2404 static void retargetArctoArc(bContext *C, RigGraph *rigg, RigArc *iarc, RigNode *inode_start)
2407 RetargetParam *p = MEM_callocN(sizeof(RetargetParam), "RetargetParam");
2411 p->inode_start = inode_start;
2414 BLI_insert_work(rigg->worker, p);
2420 p.inode_start = inode_start;
2423 exec_retargetArctoArc(&p);
2427 void *exec_retargetArctoArc(void *param)
2429 RetargetParam *p = (RetargetParam*)param;
2430 RigGraph *rigg = p->rigg;
2431 RigArc *iarc = p->iarc;
2432 bContext *C = p->context;
2433 RigNode *inode_start = p->inode_start;
2434 ReebArc *earc = iarc->link_mesh;
2436 if (BLI_countlist(&iarc->edges) == 1)
2438 RigEdge *edge = iarc->edges.first;
2440 if (testFlipArc(iarc, inode_start))
2442 repositionBone(C, rigg, edge, earc->tail->p, earc->head->p, earc->head->no);
2446 repositionBone(C, rigg, edge, earc->head->p, earc->tail->p, earc->tail->no);
2451 RetargetMode mode = detectArcRetargetMode(iarc);
2453 if (mode == RETARGET_AGGRESSIVE)
2455 retargetArctoArcAggresive(C, rigg, iarc, inode_start);
2459 retargetArctoArcLength(C, rigg, iarc, inode_start);
2470 static void matchMultiResolutionNode(RigGraph *rigg, RigNode *inode, ReebNode *top_node)
2472 ReebNode *enode = top_node;
2473 ReebGraph *reebg = BIF_graphForMultiNode(rigg->link_mesh, enode);
2476 ishape = BLI_subtreeShape((BGraph*)rigg, (BNode*)inode, NULL, 0) % SHAPE_LEVELS;
2477 eshape = BLI_subtreeShape((BGraph*)reebg, (BNode*)enode, NULL, 0) % SHAPE_LEVELS;
2479 inode->link_mesh = enode;
2481 while (ishape == eshape && enode->link_down)
2483 inode->link_mesh = enode;
2485 enode = enode->link_down;
2486 reebg = BIF_graphForMultiNode(rigg->link_mesh, enode); /* replace with call to link_down once that exists */
2487 eshape = BLI_subtreeShape((BGraph*)reebg, (BNode*)enode, NULL, 0) % SHAPE_LEVELS;
2491 static void markMultiResolutionChildArc(ReebNode *end_enode, ReebNode *enode)
2495 for(i = 0; i < enode->degree; i++)
2497 ReebArc *earc = (ReebArc*)enode->arcs[i];
2499 if (earc->flag == ARC_FREE)
2501 earc->flag = ARC_TAKEN;
2503 if (earc->tail->degree > 1 && earc->tail != end_enode)
2505 markMultiResolutionChildArc(end_enode, earc->tail);
2512 static void markMultiResolutionArc(ReebArc *start_earc)
2514 if (start_earc->link_up)
2517 for (earc = start_earc->link_up ; earc; earc = earc->link_up)
2519 earc->flag = ARC_TAKEN;
2521 if (earc->tail->index != start_earc->tail->index)
2523 markMultiResolutionChildArc(earc->tail, earc->tail);
2529 static void matchMultiResolutionArc(RigGraph *rigg, RigNode *start_node, RigArc *next_iarc, ReebArc *next_earc)
2531 ReebNode *enode = next_earc->head;
2532 ReebGraph *reebg = BIF_graphForMultiNode(rigg->link_mesh, enode);
2535 ishape = BLI_subtreeShape((BGraph*)rigg, (BNode*)start_node, (BArc*)next_iarc, 1) % SHAPE_LEVELS;
2536 eshape = BLI_subtreeShape((BGraph*)reebg, (BNode*)enode, (BArc*)next_earc, 1) % SHAPE_LEVELS;
2538 while (ishape != eshape && next_earc->link_up)
2540 next_earc->flag = ARC_TAKEN; // mark previous as taken, to prevent backtrack on lower levels
2542 next_earc = next_earc->link_up;
2543 reebg = reebg->link_up;
2544 enode = next_earc->head;
2545 eshape = BLI_subtreeShape((BGraph*)reebg, (BNode*)enode, (BArc*)next_earc, 1) % SHAPE_LEVELS;
2548 next_earc->flag = ARC_USED;
2549 next_iarc->link_mesh = next_earc;
2551 /* mark all higher levels as taken too */
2552 markMultiResolutionArc(next_earc);
2553 // while (next_earc->link_up)
2555 // next_earc = next_earc->link_up;
2556 // next_earc->flag = ARC_TAKEN;
2560 static void matchMultiResolutionStartingNode(RigGraph *rigg, ReebGraph *reebg, RigNode *inode)
2565 enode = reebg->nodes.first;
2567 ishape = BLI_subtreeShape((BGraph*)rigg, (BNode*)inode, NULL, 0) % SHAPE_LEVELS;
2568 eshape = BLI_subtreeShape((BGraph*)rigg->link_mesh, (BNode*)enode, NULL, 0) % SHAPE_LEVELS;
2570 while (ishape != eshape && reebg->link_up)
2572 reebg = reebg->link_up;
2574 enode = reebg->nodes.first;
2576 eshape = BLI_subtreeShape((BGraph*)reebg, (BNode*)enode, NULL, 0) % SHAPE_LEVELS;
2579 inode->link_mesh = enode;
2582 static void findCorrespondingArc(RigGraph *rigg, RigArc *start_arc, RigNode *start_node, RigArc *next_iarc, int root)
2584 ReebNode *enode = start_node->link_mesh;
2586 int symmetry_level = next_iarc->symmetry_level;
2587 int symmetry_group = next_iarc->symmetry_group;
2588 int symmetry_flag = next_iarc->symmetry_flag;
2591 next_iarc->link_mesh = NULL;
2595 // printf("-----------------------\n");
2596 // printf("MATCHING LIMB\n");
2597 // RIG_printArcBones(next_iarc);
2600 for(i = 0; i < enode->degree; i++)
2602 next_earc = (ReebArc*)enode->arcs[i];
2604 // if (next_earc->flag == ARC_FREE)
2606 // printf("candidate (level %i ?= %i) (flag %i ?= %i) (group %i ?= %i)\n",
2607 // symmetry_level, next_earc->symmetry_level,
2608 // symmetry_flag, next_earc->symmetry_flag,
2609 // symmetry_group, next_earc->symmetry_flag);
2612 if (next_earc->flag == ARC_FREE &&
2613 next_earc->symmetry_flag == symmetry_flag &&
2614 next_earc->symmetry_group == symmetry_group &&
2615 next_earc->symmetry_level == symmetry_level)
2617 // printf("CORRESPONDING ARC FOUND\n");
2618 // printf("flag %i -- level %i -- flag %i -- group %i\n", next_earc->flag, next_earc->symmetry_level, next_earc->symmetry_flag, next_earc->symmetry_group);
2620 matchMultiResolutionArc(rigg, start_node, next_iarc, next_earc);
2625 /* not found, try at higher nodes (lower node might have filtered internal arcs, messing shape of tree */
2626 if (next_iarc->link_mesh == NULL)
2628 // printf("NO CORRESPONDING ARC FOUND - GOING TO HIGHER LEVELS\n");
2632 start_node->link_mesh = enode->link_up;
2633 findCorrespondingArc(rigg, start_arc, start_node, next_iarc, 0);
2637 /* still not found, print debug info */
2638 if (root && next_iarc->link_mesh == NULL)
2640 start_node->link_mesh = enode; /* linking back with root node */
2642 // printf("NO CORRESPONDING ARC FOUND\n");
2643 // RIG_printArcBones(next_iarc);
2645 // printf("ON NODE %i, multilevel %i\n", enode->index, enode->multi_level);
2647 // printf("LOOKING FOR\n");
2648 // printf("flag %i -- level %i -- flag %i -- group %i\n", ARC_FREE, symmetry_level, symmetry_flag, symmetry_group);
2650 // printf("CANDIDATES\n");
2651 // for(i = 0; i < enode->degree; i++)
2653 // next_earc = (ReebArc*)enode->arcs[i];
2654 // printf("flag %i -- level %i -- flag %i -- group %i\n", next_earc->flag, next_earc->symmetry_level, next_earc->symmetry_flag, next_earc->symmetry_group);
2657 /* Emergency matching */
2658 for(i = 0; i < enode->degree; i++)
2660 next_earc = (ReebArc*)enode->arcs[i];
2662 if (next_earc->flag == ARC_FREE && next_earc->symmetry_level == symmetry_level)
2664 // printf("USING: \n");
2665 // printf("flag %i -- level %i -- flag %i -- group %i\n", next_earc->flag, next_earc->symmetry_level, next_earc->symmetry_flag, next_earc->symmetry_group);
2666 matchMultiResolutionArc(rigg, start_node, next_iarc, next_earc);
2674 static void retargetSubgraph(bContext *C, RigGraph *rigg, RigArc *start_arc, RigNode *start_node)
2676 RigNode *inode = start_node;
2679 /* no start arc on first node */
2682 ReebNode *enode = start_node->link_mesh;
2683 ReebArc *earc = start_arc->link_mesh;
2685 retargetArctoArc(C, rigg, start_arc, start_node);
2687 enode = BIF_otherNodeFromIndex(earc, enode);
2688 inode = (RigNode*)BLI_otherNode((BArc*)start_arc, (BNode*)inode);
2690 /* match with lowest node with correct shape */
2691 matchMultiResolutionNode(rigg, inode, enode);
2694 for(i = 0; i < inode->degree; i++)
2696 RigArc *next_iarc = (RigArc*)inode->arcs[i];
2698 /* no back tracking */
2699 if (next_iarc != start_arc)
2701 findCorrespondingArc(rigg, start_arc, inode, next_iarc, 1);
2702 if (next_iarc->link_mesh)
2704 retargetSubgraph(C, rigg, next_iarc, inode);
2710 static void finishRetarget(RigGraph *rigg)
2713 BLI_end_worker(rigg->worker);
2717 static void adjustGraphs(bContext *C, RigGraph *rigg)
2719 Scene *scene = CTX_data_scene(C);
2720 bArmature *arm= rigg->ob->data;
2723 for (arc = rigg->arcs.first; arc; arc = arc->next)
2727 retargetArctoArc(C, rigg, arc, arc->head);
2731 finishRetarget(rigg);
2733 /* Turn the list into an armature */
2734 arm->edbo = rigg->editbones;
2735 ED_armature_from_edit(scene, rigg->ob);
2737 ED_undo_push(C, "Retarget Skeleton");
2740 static void retargetGraphs(bContext *C, RigGraph *rigg)
2742 Scene *scene = CTX_data_scene(C);
2743 bArmature *arm= rigg->ob->data;
2744 ReebGraph *reebg = rigg->link_mesh;
2747 /* flag all ReebArcs as free */
2748 BIF_flagMultiArcs(reebg, ARC_FREE);
2750 /* return to first level */
2751 reebg = rigg->link_mesh;
2755 matchMultiResolutionStartingNode(rigg, reebg, inode);
2757 retargetSubgraph(C, rigg, NULL, inode);
2759 //generateMissingArcs(rigg);
2761 finishRetarget(rigg);
2763 /* Turn the list into an armature */
2764 arm->edbo = rigg->editbones;
2765 ED_armature_from_edit(scene, rigg->ob);
2768 char *RIG_nameBone(RigGraph *rg, int arc_index, int bone_index)
2770 RigArc *arc = BLI_findlink(&rg->arcs, arc_index);
2778 if (bone_index == BLI_countlist(&arc->edges))
2780 return "Last joint";
2783 iedge = BLI_findlink(&arc->edges, bone_index);
2790 if (iedge->bone == NULL)
2792 return "Bone offset";
2795 return iedge->bone->name;
2798 int RIG_nbJoints(RigGraph *rg)
2803 total += BLI_countlist(&rg->nodes);
2805 for (arc = rg->arcs.first; arc; arc = arc->next)
2807 total += BLI_countlist(&arc->edges) - 1; /* -1 because end nodes are already counted */
2813 void BIF_freeRetarget()
2817 RIG_freeRigGraph((BGraph*)GLOBAL_RIGG);
2822 void BIF_retargetArmature(bContext *C)
2825 double start_time, end_time;
2826 double gstart_time, gend_time;
2827 double reeb_time, rig_time=0.0, retarget_time=0.0, total_time;
2829 gstart_time = start_time = PIL_check_seconds_timer();
2831 reebg = BIF_ReebGraphMultiFromEditMesh(C);
2833 end_time = PIL_check_seconds_timer();
2834 reeb_time = end_time - start_time;
2836 printf("Reeb Graph created\n");
2838 CTX_DATA_BEGIN(C, Base*, base, selected_editable_bases) {
2839 Object *ob = base->object;
2841 if (ob->type==OB_ARMATURE)
2848 /* Put the armature into editmode */
2851 start_time = PIL_check_seconds_timer();
2853 rigg = RIG_graphFromArmature(C, ob, arm);
2855 end_time = PIL_check_seconds_timer();
2856 rig_time = end_time - start_time;
2858 printf("Armature graph created\n");
2860 //RIG_printGraph(rigg);
2862 rigg->link_mesh = reebg;
2864 printf("retargetting %s\n", ob->id.name);
2866 start_time = PIL_check_seconds_timer();
2868 retargetGraphs(C, rigg);
2870 end_time = PIL_check_seconds_timer();
2871 retarget_time = end_time - start_time;
2877 break; /* only one armature at a time */
2883 gend_time = PIL_check_seconds_timer();