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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
20 * Contributor(s): Martin Poirier
22 * ***** END GPL LICENSE BLOCK *****
23 * autoarmature.c: Interface for automagically manipulating armature (retarget, created, ...)
32 #include "MEM_guardedalloc.h"
36 #include "DNA_armature_types.h"
37 #include "DNA_constraint_types.h"
38 #include "DNA_scene_types.h"
39 #include "DNA_object_types.h"
41 #include "BLI_blenlib.h"
43 #include "BLI_editVert.h"
44 #include "BLI_utildefines.h"
45 #include "BLI_ghash.h"
46 #include "BLI_graph.h"
48 #include "BLI_threads.h"
50 //#include "BDR_editobject.h"
52 #include "BKE_constraint.h"
53 #include "BKE_armature.h"
54 #include "BKE_context.h"
56 #include "ED_armature.h"
59 #include "BIF_retarget.h"
62 //#include "mydevice.h"
63 #include "reeb.h" // FIX ME
64 //#include "blendef.h"
66 #include "armature_intern.h"
68 /************ RIG RETARGET DATA STRUCTURES ***************/
70 typedef struct MemoNode {
75 typedef struct RetargetParam {
90 METHOD_BRUTE_FORCE = 0,
101 RigGraph *GLOBAL_RIGG = NULL;
103 /*******************************************************************************************************/
105 void *exec_retargetArctoArc(void *param);
107 static void RIG_calculateEdgeAngles(RigEdge *edge_first, RigEdge *edge_second);
108 float rollBoneByQuat(EditBone *bone, float old_up_axis[3], float qrot[4]);
111 #define SHAPE_LEVELS (SHAPE_RADIX * SHAPE_RADIX)
113 /*********************************** EDITBONE UTILS ****************************************************/
115 int countEditBoneChildren(ListBase *list, EditBone *parent)
120 for (ebone = list->first; ebone; ebone = ebone->next)
122 if (ebone->parent == parent)
131 EditBone* nextEditBoneChild(ListBase *list, EditBone *parent, int n)
135 for (ebone = list->first; ebone; ebone = ebone->next)
137 if (ebone->parent == parent)
150 void getEditBoneRollUpAxis(EditBone *bone, float roll, float up_axis[3])
152 float mat[3][3], nor[3];
154 sub_v3_v3v3(nor, bone->tail, bone->head);
156 vec_roll_to_mat3(nor, roll, mat);
157 VECCOPY(up_axis, mat[2]);
160 float rollBoneByQuatAligned(EditBone *bone, float old_up_axis[3], float qrot[4], float qroll[4], float aligned_axis[3])
162 float nor[3], new_up_axis[3], x_axis[3], z_axis[3];
164 VECCOPY(new_up_axis, old_up_axis);
165 mul_qt_v3(qrot, new_up_axis);
167 sub_v3_v3v3(nor, bone->tail, bone->head);
169 cross_v3_v3v3(x_axis, nor, aligned_axis);
170 cross_v3_v3v3(z_axis, x_axis, nor);
172 normalize_v3(new_up_axis);
173 normalize_v3(x_axis);
174 normalize_v3(z_axis);
176 if (dot_v3v3(new_up_axis, x_axis) < 0)
181 if (dot_v3v3(new_up_axis, z_axis) < 0)
186 if (angle_normalized_v3v3(x_axis, new_up_axis) < angle_normalized_v3v3(z_axis, new_up_axis))
188 rotation_between_vecs_to_quat(qroll, new_up_axis, x_axis); /* set roll rotation quat */
189 return ED_rollBoneToVector(bone, x_axis, FALSE);
193 rotation_between_vecs_to_quat(qroll, new_up_axis, z_axis); /* set roll rotation quat */
194 return ED_rollBoneToVector(bone, z_axis, FALSE);
198 float rollBoneByQuatJoint(RigEdge *edge, RigEdge *previous, float qrot[4], float qroll[4], float up_axis[3])
200 if (previous == NULL)
202 /* default to up_axis if no previous */
203 return rollBoneByQuatAligned(edge->bone, edge->up_axis, qrot, qroll, up_axis);
207 float new_up_axis[3];
208 float vec_first[3], vec_second[3], normal[3];
212 sub_v3_v3v3(vec_first, previous->bone->tail, previous->bone->head);
214 else if (previous->prev->bone)
216 sub_v3_v3v3(vec_first, edge->bone->head, previous->prev->bone->tail);
220 /* default to up_axis if first bone in the chain is an offset */
221 return rollBoneByQuatAligned(edge->bone, edge->up_axis, qrot, qroll, up_axis);
224 sub_v3_v3v3(vec_second, edge->bone->tail, edge->bone->head);
226 normalize_v3(vec_first);
227 normalize_v3(vec_second);
229 cross_v3_v3v3(normal, vec_first, vec_second);
230 normalize_v3(normal);
232 axis_angle_to_quat(qroll, vec_second, edge->up_angle);
234 mul_qt_v3(qroll, normal);
236 VECCOPY(new_up_axis, edge->up_axis);
237 mul_qt_v3(qrot, new_up_axis);
239 normalize_v3(new_up_axis);
241 /* real qroll between normal and up_axis */
242 rotation_between_vecs_to_quat(qroll, new_up_axis, normal);
244 return ED_rollBoneToVector(edge->bone, normal, FALSE);
248 float rollBoneByQuat(EditBone *bone, float old_up_axis[3], float qrot[4])
250 float new_up_axis[3];
252 VECCOPY(new_up_axis, old_up_axis);
253 mul_qt_v3(qrot, new_up_axis);
255 return ED_rollBoneToVector(bone, new_up_axis, FALSE);
258 /************************************ DESTRUCTORS ******************************************************/
260 void RIG_freeRigArc(BArc *arc)
262 BLI_freelistN(&((RigArc*)arc)->edges);
265 void RIG_freeRigGraph(BGraph *rg)
267 RigGraph *rigg = (RigGraph*)rg;
272 BLI_destroy_worker(rigg->worker);
277 REEB_freeGraph(rigg->link_mesh);
280 for (arc = rg->arcs.first; arc; arc = arc->next)
284 BLI_freelistN(&rg->arcs);
286 for (node = rg->nodes.first; node; node = node->next)
288 BLI_freeNode(rg, (BNode*)node);
290 BLI_freelistN(&rg->nodes);
292 BLI_freelistN(&rigg->controls);
294 BLI_ghash_free(rigg->bones_map, NULL, NULL);
295 BLI_ghash_free(rigg->controls_map, NULL, NULL);
297 if (rigg->flag & RIG_FREE_BONELIST)
299 BLI_freelistN(rigg->editbones);
300 MEM_freeN(rigg->editbones);
306 /************************************* ALLOCATORS ******************************************************/
308 static RigGraph *newRigGraph(void)
313 rg = MEM_callocN(sizeof(RigGraph), "rig graph");
317 rg->bones_map = BLI_ghash_new(BLI_ghashutil_strhash, BLI_ghashutil_strcmp, "newRigGraph bones gh");
318 rg->controls_map = BLI_ghash_new(BLI_ghashutil_strhash, BLI_ghashutil_strcmp, "newRigGraph cont gh");
320 rg->free_arc = RIG_freeRigArc;
321 rg->free_node = NULL;
324 // if(G.scene->r.mode & R_FIXED_THREADS)
326 // totthread = G.scene->r.threads;
330 totthread = BLI_system_thread_count();
333 rg->worker = BLI_create_worker(exec_retargetArctoArc, totthread, 20); /* fix number of threads */
339 static RigArc *newRigArc(RigGraph *rg)
343 arc = MEM_callocN(sizeof(RigArc), "rig arc");
345 BLI_addtail(&rg->arcs, arc);
350 static RigControl *newRigControl(RigGraph *rg)
354 ctrl = MEM_callocN(sizeof(RigControl), "rig control");
356 BLI_addtail(&rg->controls, ctrl);
361 static RigNode *newRigNodeHead(RigGraph *rg, RigArc *arc, float p[3])
364 node = MEM_callocN(sizeof(RigNode), "rig node");
365 BLI_addtail(&rg->nodes, node);
376 static void addRigNodeHead(RigGraph *UNUSED(rg), RigArc *arc, RigNode *node)
383 static RigNode *newRigNode(RigGraph *rg, float p[3])
386 node = MEM_callocN(sizeof(RigNode), "rig node");
387 BLI_addtail(&rg->nodes, node);
396 static RigNode *newRigNodeTail(RigGraph *rg, RigArc *arc, float p[3])
398 RigNode *node = newRigNode(rg, p);
406 static void RIG_appendEdgeToArc(RigArc *arc, RigEdge *edge)
408 BLI_addtail(&arc->edges, edge);
410 if (edge->prev == NULL)
412 VECCOPY(edge->head, arc->head->p);
416 RigEdge *last_edge = edge->prev;
417 VECCOPY(edge->head, last_edge->tail);
418 RIG_calculateEdgeAngles(last_edge, edge);
421 edge->length = len_v3v3(edge->head, edge->tail);
423 arc->length += edge->length;
428 static void RIG_addEdgeToArc(RigArc *arc, float tail[3], EditBone *bone)
432 edge = MEM_callocN(sizeof(RigEdge), "rig edge");
434 VECCOPY(edge->tail, tail);
439 getEditBoneRollUpAxis(bone, bone->roll, edge->up_axis);
442 RIG_appendEdgeToArc(arc, edge);
444 /************************************** CLONING TEMPLATES **********************************************/
446 static void renameTemplateBone(char *name, char *template_name, ListBase *editbones, char *side_string, char *num_string)
450 for (i = 0, j = 0; template_name[i] != '\0' && i < 31 && j < 31; i++)
452 if (template_name[i] == '&')
454 if (template_name[i+1] == 'S' || template_name[i+1] == 's')
456 j += sprintf(name + j, "%s", side_string);
459 else if (template_name[i+1] == 'N' || template_name[i+1] == 'n')
461 j += sprintf(name + j, "%s", num_string);
466 name[j] = template_name[i];
472 name[j] = template_name[i];
479 unique_editbone_name(editbones, name, NULL);
482 static RigControl *cloneControl(RigGraph *rg, RigGraph *src_rg, RigControl *src_ctrl, GHash *ptr_hash, char *side_string, char *num_string)
487 ctrl = newRigControl(rg);
489 VECCOPY(ctrl->head, src_ctrl->head);
490 VECCOPY(ctrl->tail, src_ctrl->tail);
491 VECCOPY(ctrl->up_axis, src_ctrl->up_axis);
492 VECCOPY(ctrl->offset, src_ctrl->offset);
494 ctrl->tail_mode = src_ctrl->tail_mode;
495 ctrl->flag = src_ctrl->flag;
497 renameTemplateBone(name, src_ctrl->bone->name, rg->editbones, side_string, num_string);
498 ctrl->bone = duplicateEditBoneObjects(src_ctrl->bone, name, rg->editbones, src_rg->ob, rg->ob);
499 ctrl->bone->flag &= ~(BONE_TIPSEL|BONE_SELECTED|BONE_ROOTSEL);
500 BLI_ghash_insert(ptr_hash, src_ctrl->bone, ctrl->bone);
502 ctrl->link = src_ctrl->link;
503 ctrl->link_tail = src_ctrl->link_tail;
508 static RigArc *cloneArc(RigGraph *rg, RigGraph *src_rg, RigArc *src_arc, GHash *ptr_hash, char *side_string, char *num_string)
515 arc->head = BLI_ghash_lookup(ptr_hash, src_arc->head);
516 arc->tail = BLI_ghash_lookup(ptr_hash, src_arc->tail);
521 arc->length = src_arc->length;
523 arc->count = src_arc->count;
525 for (src_edge = src_arc->edges.first; src_edge; src_edge = src_edge->next)
529 edge = MEM_callocN(sizeof(RigEdge), "rig edge");
531 VECCOPY(edge->head, src_edge->head);
532 VECCOPY(edge->tail, src_edge->tail);
533 VECCOPY(edge->up_axis, src_edge->up_axis);
535 edge->length = src_edge->length;
536 edge->angle = src_edge->angle;
537 edge->up_angle = src_edge->up_angle;
539 if (src_edge->bone != NULL)
542 renameTemplateBone(name, src_edge->bone->name, rg->editbones, side_string, num_string);
543 edge->bone = duplicateEditBoneObjects(src_edge->bone, name, rg->editbones, src_rg->ob, rg->ob);
544 edge->bone->flag &= ~(BONE_TIPSEL|BONE_SELECTED|BONE_ROOTSEL);
545 BLI_ghash_insert(ptr_hash, src_edge->bone, edge->bone);
548 BLI_addtail(&arc->edges, edge);
554 static RigGraph *cloneRigGraph(RigGraph *src, ListBase *editbones, Object *ob, char *side_string, char *num_string)
562 ptr_hash = BLI_ghash_new(BLI_ghashutil_ptrhash, BLI_ghashutil_ptrcmp, "cloneRigGraph gh");
567 rg->editbones = editbones;
569 preEditBoneDuplicate(rg->editbones); /* prime bones for duplication */
570 preEditBoneDuplicate(src->editbones); /* prime bones for duplication */
573 for (node = src->nodes.first; node; node = node->next)
575 RigNode *cloned_node = newRigNode(rg, node->p);
576 BLI_ghash_insert(ptr_hash, node, cloned_node);
579 rg->head = BLI_ghash_lookup(ptr_hash, src->head);
582 for (arc = src->arcs.first; arc; arc = arc->next)
584 cloneArc(rg, src, arc, ptr_hash, side_string, num_string);
588 for (ctrl = src->controls.first; ctrl; ctrl = ctrl->next)
590 cloneControl(rg, src, ctrl, ptr_hash, side_string, num_string);
593 /* Relink bones properly */
594 for (arc = rg->arcs.first; arc; arc = arc->next)
598 for (edge = arc->edges.first; edge; edge = edge->next)
600 if (edge->bone != NULL)
604 updateDuplicateSubtargetObjects(edge->bone, src->editbones, src->ob, rg->ob);
606 if (edge->bone->parent)
608 bone = BLI_ghash_lookup(ptr_hash, edge->bone->parent);
612 edge->bone->parent = bone;
616 /* disconnect since parent isn't cloned
617 * this will only happen when cloning from selected bones
619 edge->bone->flag &= ~BONE_CONNECTED;
626 for (ctrl = rg->controls.first; ctrl; ctrl = ctrl->next)
630 updateDuplicateSubtargetObjects(ctrl->bone, src->editbones, src->ob, rg->ob);
632 if (ctrl->bone->parent)
634 bone = BLI_ghash_lookup(ptr_hash, ctrl->bone->parent);
638 ctrl->bone->parent = bone;
642 /* disconnect since parent isn't cloned
643 * this will only happen when cloning from selected bones
645 ctrl->bone->flag &= ~BONE_CONNECTED;
649 ctrl->link = BLI_ghash_lookup(ptr_hash, ctrl->link);
650 ctrl->link_tail = BLI_ghash_lookup(ptr_hash, ctrl->link_tail);
653 BLI_ghash_free(ptr_hash, NULL, NULL);
659 /*******************************************************************************************************/
661 static void RIG_calculateEdgeAngles(RigEdge *edge_first, RigEdge *edge_second)
663 float vec_first[3], vec_second[3];
665 sub_v3_v3v3(vec_first, edge_first->tail, edge_first->head);
666 sub_v3_v3v3(vec_second, edge_second->tail, edge_second->head);
668 normalize_v3(vec_first);
669 normalize_v3(vec_second);
671 edge_first->angle = angle_normalized_v3v3(vec_first, vec_second);
673 if (edge_second->bone != NULL)
677 cross_v3_v3v3(normal, vec_first, vec_second);
678 normalize_v3(normal);
680 edge_second->up_angle = angle_normalized_v3v3(normal, edge_second->up_axis);
684 /************************************ CONTROL BONES ****************************************************/
686 static void RIG_addControlBone(RigGraph *rg, EditBone *bone)
688 RigControl *ctrl = newRigControl(rg);
690 VECCOPY(ctrl->head, bone->head);
691 VECCOPY(ctrl->tail, bone->tail);
692 getEditBoneRollUpAxis(bone, bone->roll, ctrl->up_axis);
693 ctrl->tail_mode = TL_NONE;
695 BLI_ghash_insert(rg->controls_map, bone->name, ctrl);
698 static int RIG_parentControl(RigControl *ctrl, EditBone *link)
705 sub_v3_v3v3(offset, ctrl->bone->head, link->head);
707 /* if root matches, check for direction too */
708 if (dot_v3v3(offset, offset) < 0.0001)
710 float vbone[3], vparent[3];
712 flag |= RIG_CTRL_FIT_ROOT;
714 sub_v3_v3v3(vbone, ctrl->bone->tail, ctrl->bone->head);
715 sub_v3_v3v3(vparent, link->tail, link->head);
717 /* test for opposite direction */
718 if (dot_v3v3(vbone, vparent) > 0)
723 cross_v3_v3v3(nor, vbone, vparent);
725 len = dot_v3v3(nor, nor);
728 flag |= RIG_CTRL_FIT_BONE;
733 /* Bail out if old one is automatically better */
734 if (flag < ctrl->flag)
739 /* if there's already a link
740 * overwrite only if new link is higher in the chain */
741 if (ctrl->link && flag == ctrl->flag)
743 EditBone *bone = NULL;
745 for (bone = ctrl->link; bone; bone = bone->parent)
747 /* if link is in the chain, break and use that one */
754 /* not in chain, don't update link */
765 VECCOPY(ctrl->offset, offset);
773 static void RIG_reconnectControlBones(RigGraph *rg)
778 /* first pass, link to deform bones */
779 for (ctrl = rg->controls.first; ctrl; ctrl = ctrl->next)
785 /* DO SOME MAGIC HERE */
786 for (pchan= rg->ob->pose->chanbase.first; pchan; pchan= pchan->next)
788 for (con= pchan->constraints.first; con; con= con->next)
790 bConstraintTypeInfo *cti= constraint_get_typeinfo(con);
791 ListBase targets = {NULL, NULL};
792 bConstraintTarget *ct;
794 /* constraint targets */
795 if (cti && cti->get_constraint_targets)
799 cti->get_constraint_targets(con, &targets);
801 for (target_index = 0, ct= targets.first; ct; target_index++, ct= ct->next)
803 if ((ct->tar == rg->ob) && strcmp(ct->subtarget, ctrl->bone->name) == 0)
805 /* SET bone link to bone corresponding to pchan */
806 EditBone *link = BLI_ghash_lookup(rg->bones_map, pchan->name);
808 /* Making sure bone is in this armature */
811 /* for pole targets, link to parent bone instead, if possible */
812 if (con->type == CONSTRAINT_TYPE_KINEMATIC && target_index == 1)
814 if (link->parent && BLI_ghash_haskey(rg->bones_map, link->parent->name))
820 found = RIG_parentControl(ctrl, link);
825 if (cti->flush_constraint_targets)
826 cti->flush_constraint_targets(con, &targets, 0);
831 /* if not found yet, check parent */
834 if (ctrl->bone->parent)
836 /* make sure parent is a deforming bone
839 EditBone *link = BLI_ghash_lookup(rg->bones_map, ctrl->bone->parent->name);
841 found = RIG_parentControl(ctrl, link);
844 /* check if bone is not superposed on another one */
847 RigArc *best_arc = NULL;
848 EditBone *link = NULL;
850 for (arc = rg->arcs.first; arc; arc = arc->next)
853 for (edge = arc->edges.first; edge; edge = edge->next)
859 fit = len_v3v3(ctrl->bone->head, edge->bone->head) < 0.0001;
860 fit = fit || len_v3v3(ctrl->bone->tail, edge->bone->tail) < 0.0001;
864 /* pick the bone on the arc with the lowest symmetry level
865 * means you connect control to the trunk of the skeleton */
866 if (best_arc == NULL || arc->symmetry_level < best_arc->symmetry_level)
876 found = RIG_parentControl(ctrl, link);
880 /* if not found yet, check child */
884 RigArc *best_arc = NULL;
885 EditBone *link = NULL;
887 for (arc = rg->arcs.first; arc; arc = arc->next)
890 for (edge = arc->edges.first; edge; edge = edge->next)
892 if (edge->bone && edge->bone->parent == ctrl->bone)
894 /* pick the bone on the arc with the lowest symmetry level
895 * means you connect control to the trunk of the skeleton */
896 if (best_arc == NULL || arc->symmetry_level < best_arc->symmetry_level)
905 found = RIG_parentControl(ctrl, link);
911 /* second pass, make chains in control bones */
916 for (ctrl = rg->controls.first; ctrl; ctrl = ctrl->next)
918 /* if control is not linked yet */
919 if (ctrl->link == NULL)
923 RigControl *ctrl_parent = NULL;
924 RigControl *ctrl_child;
927 if (ctrl->bone->parent)
929 ctrl_parent = BLI_ghash_lookup(rg->controls_map, ctrl->bone->parent->name);
932 /* check constraints first */
934 /* DO SOME MAGIC HERE */
935 for (pchan= rg->ob->pose->chanbase.first; pchan; pchan= pchan->next)
937 for (con= pchan->constraints.first; con; con= con->next)
939 bConstraintTypeInfo *cti= constraint_get_typeinfo(con);
940 ListBase targets = {NULL, NULL};
941 bConstraintTarget *ct;
943 /* constraint targets */
944 if (cti && cti->get_constraint_targets)
946 cti->get_constraint_targets(con, &targets);
948 for (ct= targets.first; ct; ct= ct->next)
950 if ((ct->tar == rg->ob) && strcmp(ct->subtarget, ctrl->bone->name) == 0)
952 /* SET bone link to ctrl corresponding to pchan */
953 RigControl *link = BLI_ghash_lookup(rg->controls_map, pchan->name);
955 /* if owner is a control bone, link with it */
956 if (link && link->link)
958 RIG_parentControl(ctrl, link->bone);
965 if (cti->flush_constraint_targets)
966 cti->flush_constraint_targets(con, &targets, 0);
973 /* check if parent is already linked */
974 if (ctrl_parent && ctrl_parent->link)
976 RIG_parentControl(ctrl, ctrl_parent->bone);
982 for (ctrl_child = rg->controls.first; ctrl_child; ctrl_child = ctrl_child->next)
984 /* if a child is linked, link to that one */
985 if (ctrl_child->link && ctrl_child->bone->parent == ctrl->bone)
987 RIG_parentControl(ctrl, ctrl_child->bone);
998 /* third pass, link control tails */
999 for (ctrl = rg->controls.first; ctrl; ctrl = ctrl->next)
1001 /* fit bone already means full match, so skip those */
1002 if ((ctrl->flag & RIG_CTRL_FIT_BONE) == 0)
1006 /* look on deform bones first */
1007 BLI_ghashIterator_init(&ghi, rg->bones_map);
1009 for( ; !BLI_ghashIterator_isDone(&ghi); BLI_ghashIterator_step(&ghi))
1011 EditBone *bone = (EditBone*)BLI_ghashIterator_getValue(&ghi);
1013 /* don't link with parent */
1014 if (bone->parent != ctrl->bone)
1016 if (len_v3v3(ctrl->bone->tail, bone->head) < 0.01)
1018 ctrl->tail_mode = TL_HEAD;
1019 ctrl->link_tail = bone;
1022 else if (len_v3v3(ctrl->bone->tail, bone->tail) < 0.01)
1024 ctrl->tail_mode = TL_TAIL;
1025 ctrl->link_tail = bone;
1031 /* if we haven't found one yet, look in control bones */
1032 if (ctrl->tail_mode == TL_NONE)
1040 /*******************************************************************************************************/
1042 static void RIG_joinArcs(RigGraph *rg, RigNode *node, RigArc *joined_arc1, RigArc *joined_arc2)
1044 RigEdge *edge, *next_edge;
1046 /* ignore cases where joint is at start or end */
1047 if (joined_arc1->head == joined_arc2->head || joined_arc1->tail == joined_arc2->tail)
1052 /* swap arcs to make sure arc1 is before arc2 */
1053 if (joined_arc1->head == joined_arc2->tail)
1055 RigArc *tmp = joined_arc1;
1056 joined_arc1 = joined_arc2;
1060 for (edge = joined_arc2->edges.first; edge; edge = next_edge)
1062 next_edge = edge->next;
1064 RIG_appendEdgeToArc(joined_arc1, edge);
1067 joined_arc1->tail = joined_arc2->tail;
1069 joined_arc2->edges.first = joined_arc2->edges.last = NULL;
1071 BLI_removeArc((BGraph*)rg, (BArc*)joined_arc2);
1073 BLI_removeNode((BGraph*)rg, (BNode*)node);
1076 static void RIG_removeNormalNodes(RigGraph *rg)
1078 RigNode *node, *next_node;
1080 for (node = rg->nodes.first; node; node = next_node)
1082 next_node = node->next;
1084 if (node->degree == 2)
1086 RigArc *arc, *joined_arc1 = NULL, *joined_arc2 = NULL;
1088 for (arc = rg->arcs.first; arc; arc = arc->next)
1090 if (arc->head == node || arc->tail == node)
1092 if (joined_arc1 == NULL)
1104 RIG_joinArcs(rg, node, joined_arc1, joined_arc2);
1109 static void RIG_removeUneededOffsets(RigGraph *rg)
1113 for (arc = rg->arcs.first; arc; arc = arc->next)
1115 RigEdge *first_edge, *last_edge;
1117 first_edge = arc->edges.first;
1118 last_edge = arc->edges.last;
1120 if (first_edge->bone == NULL)
1122 if (first_edge->bone == NULL && len_v3v3(first_edge->tail, arc->head->p) <= 0.001)
1124 BLI_remlink(&arc->edges, first_edge);
1125 MEM_freeN(first_edge);
1127 else if (arc->head->degree == 1)
1129 RigNode *new_node = (RigNode*)BLI_FindNodeByPosition((BGraph*)rg, first_edge->tail, 0.001);
1133 BLI_remlink(&arc->edges, first_edge);
1134 MEM_freeN(first_edge);
1135 BLI_replaceNodeInArc((BGraph*)rg, (BArc*)arc, (BNode*)new_node, (BNode*)arc->head);
1139 RigEdge *next_edge = first_edge->next;
1143 BLI_remlink(&arc->edges, first_edge);
1144 MEM_freeN(first_edge);
1146 VECCOPY(arc->head->p, next_edge->head);
1152 /* check if all arc connected start with a null edge */
1154 for (other_arc = rg->arcs.first; other_arc; other_arc = other_arc->next)
1156 if (other_arc != arc)
1159 if (other_arc->head == arc->head)
1161 test_edge = other_arc->edges.first;
1163 if (test_edge->bone != NULL)
1168 else if (other_arc->tail == arc->head)
1170 test_edge = other_arc->edges.last;
1172 if (test_edge->bone != NULL)
1180 if (other_arc == NULL)
1182 RigNode *new_node = (RigNode*)BLI_FindNodeByPosition((BGraph*)rg, first_edge->tail, 0.001);
1186 /* remove null edge in other arcs too */
1187 for (other_arc = rg->arcs.first; other_arc; other_arc = other_arc->next)
1189 if (other_arc != arc)
1192 if (other_arc->head == arc->head)
1194 BLI_replaceNodeInArc((BGraph*)rg, (BArc*)other_arc, (BNode*)new_node, (BNode*)other_arc->head);
1195 test_edge = other_arc->edges.first;
1196 BLI_remlink(&other_arc->edges, test_edge);
1197 MEM_freeN(test_edge);
1199 else if (other_arc->tail == arc->head)
1201 BLI_replaceNodeInArc((BGraph*)rg, (BArc*)other_arc, (BNode*)new_node, (BNode*)other_arc->tail);
1202 test_edge = other_arc->edges.last;
1203 BLI_remlink(&other_arc->edges, test_edge);
1204 MEM_freeN(test_edge);
1209 BLI_remlink(&arc->edges, first_edge);
1210 MEM_freeN(first_edge);
1211 BLI_replaceNodeInArc((BGraph*)rg, (BArc*)arc, (BNode*)new_node, (BNode*)arc->head);
1215 RigEdge *next_edge = first_edge->next;
1219 BLI_remlink(&arc->edges, first_edge);
1220 MEM_freeN(first_edge);
1222 VECCOPY(arc->head->p, next_edge->head);
1224 /* remove null edge in other arcs too */
1225 for (other_arc = rg->arcs.first; other_arc; other_arc = other_arc->next)
1227 if (other_arc != arc)
1230 if (other_arc->head == arc->head)
1232 test_edge = other_arc->edges.first;
1233 BLI_remlink(&other_arc->edges, test_edge);
1234 MEM_freeN(test_edge);
1236 else if (other_arc->tail == arc->head)
1238 test_edge = other_arc->edges.last;
1239 BLI_remlink(&other_arc->edges, test_edge);
1240 MEM_freeN(test_edge);
1250 if (last_edge->bone == NULL)
1252 if (len_v3v3(last_edge->head, arc->tail->p) <= 0.001)
1254 BLI_remlink(&arc->edges, last_edge);
1255 MEM_freeN(last_edge);
1257 else if (arc->tail->degree == 1)
1259 RigNode *new_node = (RigNode*)BLI_FindNodeByPosition((BGraph*)rg, last_edge->head, 0.001);
1263 RigEdge *previous_edge = last_edge->prev;
1265 BLI_remlink(&arc->edges, last_edge);
1266 MEM_freeN(last_edge);
1267 BLI_replaceNodeInArc((BGraph*)rg, (BArc*)arc, (BNode*)new_node, (BNode*)arc->tail);
1269 /* set previous angle to 0, since there's no following edges */
1272 previous_edge->angle = 0;
1277 RigEdge *previous_edge = last_edge->prev;
1281 BLI_remlink(&arc->edges, last_edge);
1282 MEM_freeN(last_edge);
1284 VECCOPY(arc->tail->p, previous_edge->tail);
1285 previous_edge->angle = 0;
1293 static void RIG_arcFromBoneChain(RigGraph *rg, ListBase *list, EditBone *root_bone, RigNode *starting_node, int selected)
1295 EditBone *bone, *last_bone = root_bone;
1297 int contain_head = 0;
1299 for(bone = root_bone; bone; bone = nextEditBoneChild(list, bone, 0))
1303 if (selected == 0 || (bone->flag & BONE_SELECTED))
1305 if ((bone->flag & BONE_NO_DEFORM) == 0)
1307 BLI_ghash_insert(rg->bones_map, bone->name, bone);
1311 arc = newRigArc(rg);
1313 if (starting_node == NULL)
1315 starting_node = newRigNodeHead(rg, arc, root_bone->head);
1319 addRigNodeHead(rg, arc, starting_node);
1323 if (bone->parent && (bone->flag & BONE_CONNECTED) == 0)
1325 RIG_addEdgeToArc(arc, bone->head, NULL);
1328 RIG_addEdgeToArc(arc, bone->tail, bone);
1332 if (strcmp(bone->name, "head") == 0)
1337 else if ((bone->flag & BONE_EDITMODE_LOCKED) == 0) /* ignore locked bones */
1339 RIG_addControlBone(rg, bone);
1343 nb_children = countEditBoneChildren(list, bone);
1344 if (nb_children > 1)
1346 RigNode *end_node = NULL;
1351 end_node = newRigNodeTail(rg, arc, bone->tail);
1355 end_node = newRigNode(rg, bone->tail);
1358 for (i = 0; i < nb_children; i++)
1360 root_bone = nextEditBoneChild(list, bone, i);
1361 RIG_arcFromBoneChain(rg, list, root_bone, end_node, selected);
1364 /* arc ends here, break */
1369 /* If the loop exited without forking */
1370 if (arc != NULL && bone == NULL)
1372 newRigNodeTail(rg, arc, last_bone->tail);
1377 rg->head = arc->tail;
1381 /*******************************************************************************************************/
1382 static void RIG_findHead(RigGraph *rg)
1384 if (rg->head == NULL)
1386 if (BLI_countlist(&rg->arcs) == 1)
1388 RigArc *arc = rg->arcs.first;
1390 rg->head = (RigNode*)arc->head;
1396 for (arc = rg->arcs.first; arc; arc = arc->next)
1398 RigEdge *edge = arc->edges.last;
1400 if (edge->bone->flag & (BONE_TIPSEL|BONE_SELECTED))
1402 rg->head = arc->tail;
1408 if (rg->head == NULL)
1410 rg->head = rg->nodes.first;
1415 /*******************************************************************************************************/
1417 void RIG_printNode(RigNode *node, const char name[])
1419 printf("%s %p %i <%0.3f, %0.3f, %0.3f>\n", name, (void *)node, node->degree, node->p[0], node->p[1], node->p[2]);
1421 if (node->symmetry_flag & SYM_TOPOLOGICAL)
1423 if (node->symmetry_flag & SYM_AXIAL)
1424 printf("Symmetry AXIAL\n");
1425 else if (node->symmetry_flag & SYM_RADIAL)
1426 printf("Symmetry RADIAL\n");
1428 print_v3("symmetry axis", node->symmetry_axis);
1432 void RIG_printArcBones(RigArc *arc)
1436 for (edge = arc->edges.first; edge; edge = edge->next)
1439 printf("%s ", edge->bone->name);
1446 void RIG_printCtrl(RigControl *ctrl, char *indent)
1450 printf("%sBone: %s\n", indent, ctrl->bone->name);
1451 printf("%sLink: %s\n", indent, ctrl->link ? ctrl->link->name : "!NONE!");
1453 sprintf(text, "%soffset", indent);
1454 print_v3(text, ctrl->offset);
1456 printf("%sFlag: %i\n", indent, ctrl->flag);
1459 void RIG_printLinkedCtrl(RigGraph *rg, EditBone *bone, int tabs)
1466 for (i = 0; i < tabs; i++)
1473 for (ctrl = rg->controls.first; ctrl; ctrl = ctrl->next)
1475 if (ctrl->link == bone)
1477 RIG_printCtrl(ctrl, indent);
1478 RIG_printLinkedCtrl(rg, ctrl->bone, tabs + 1);
1483 void RIG_printArc(RigGraph *rg, RigArc *arc)
1487 RIG_printNode((RigNode*)arc->head, "head");
1489 for (edge = arc->edges.first; edge; edge = edge->next)
1491 printf("\tinner joints %0.3f %0.3f %0.3f\n", edge->tail[0], edge->tail[1], edge->tail[2]);
1492 printf("\t\tlength %f\n", edge->length);
1493 printf("\t\tangle %f\n", edge->angle * 180 / M_PI);
1496 printf("\t\t%s\n", edge->bone->name);
1497 RIG_printLinkedCtrl(rg, edge->bone, 3);
1500 printf("symmetry level: %i flag: %i group %i\n", arc->symmetry_level, arc->symmetry_flag, arc->symmetry_group);
1502 RIG_printNode((RigNode*)arc->tail, "tail");
1505 void RIG_printGraph(RigGraph *rg)
1509 printf("---- ARCS ----\n");
1510 for (arc = rg->arcs.first; arc; arc = arc->next)
1512 RIG_printArc(rg, arc);
1518 RIG_printNode(rg->head, "HEAD NODE:");
1522 printf("HEAD NODE: NONE\n");
1526 /*******************************************************************************************************/
1528 RigGraph *RIG_graphFromArmature(const bContext *C, Object *ob, bArmature *arm)
1530 Object *obedit = CTX_data_edit_object(C);
1531 Scene *scene = CTX_data_scene(C);
1539 rg->editbones = ((bArmature *)obedit->data)->edbo;
1543 rg->editbones = MEM_callocN(sizeof(ListBase), "EditBones");
1544 make_boneList(rg->editbones, &arm->bonebase, NULL, NULL);
1545 rg->flag |= RIG_FREE_BONELIST;
1550 /* Do the rotations */
1551 for (ebone = rg->editbones->first; ebone; ebone=ebone->next){
1552 if (ebone->parent == NULL)
1554 RIG_arcFromBoneChain(rg, rg->editbones, ebone, NULL, 0);
1558 BLI_removeDoubleNodes((BGraph*)rg, 0.001);
1560 RIG_removeNormalNodes(rg);
1562 RIG_removeUneededOffsets(rg);
1564 BLI_buildAdjacencyList((BGraph*)rg);
1568 BLI_markdownSymmetry((BGraph*)rg, (BNode*)rg->head, scene->toolsettings->skgen_symmetry_limit);
1570 RIG_reconnectControlBones(rg); /* after symmetry, because we use levels to find best match */
1572 if (BLI_isGraphCyclic((BGraph*)rg))
1574 printf("armature cyclic\n");
1580 RigGraph *armatureSelectedToGraph(bContext *C, Object *ob, bArmature *arm)
1582 Object *obedit = CTX_data_edit_object(C);
1583 Scene *scene = CTX_data_scene(C);
1591 rg->editbones = arm->edbo;
1595 rg->editbones = MEM_callocN(sizeof(ListBase), "EditBones");
1596 make_boneList(rg->editbones, &arm->bonebase, NULL, NULL);
1597 rg->flag |= RIG_FREE_BONELIST;
1602 /* Do the rotations */
1603 for (ebone = rg->editbones->first; ebone; ebone=ebone->next){
1604 if (ebone->parent == NULL)
1606 RIG_arcFromBoneChain(rg, rg->editbones, ebone, NULL, 1);
1610 BLI_removeDoubleNodes((BGraph*)rg, 0.001);
1612 RIG_removeNormalNodes(rg);
1614 RIG_removeUneededOffsets(rg);
1616 BLI_buildAdjacencyList((BGraph*)rg);
1620 BLI_markdownSymmetry((BGraph*)rg, (BNode*)rg->head, scene->toolsettings->skgen_symmetry_limit);
1622 RIG_reconnectControlBones(rg); /* after symmetry, because we use levels to find best match */
1624 if (BLI_isGraphCyclic((BGraph*)rg))
1626 printf("armature cyclic\n");
1631 /************************************ GENERATING *****************************************************/
1634 static EditBone *add_editbonetolist(char *name, ListBase *list)
1636 EditBone *bone= MEM_callocN(sizeof(EditBone), "eBone");
1638 BLI_strncpy(bone->name, name, sizeof(bone->name));
1639 unique_editbone_name(list, bone->name, NULL);
1641 BLI_addtail(list, bone);
1643 bone->flag |= BONE_TIPSEL;
1650 bone->rad_head= 0.10;
1651 bone->rad_tail= 0.05;
1653 bone->layer= 1;//arm->layer;
1659 void generateMissingArcsFromNode(RigGraph *rigg, ReebNode *node, int multi_level_limit)
1661 while (node->multi_level > multi_level_limit && node->link_up)
1663 node = node->link_up;
1666 while (node->multi_level < multi_level_limit && node->link_down)
1668 node = node->link_down;
1671 if (node->multi_level == multi_level_limit)
1675 for (i = 0; i < node->degree; i++)
1677 ReebArc *earc = node->arcs[i];
1679 if (earc->flag == ARC_FREE && earc->head == node)
1681 ReebNode *other = BIF_otherNodeFromIndex(earc, node);
1683 earc->flag = ARC_USED;
1685 //generateBonesForArc(rigg, earc, node, other);
1686 generateMissingArcsFromNode(rigg, other, multi_level_limit);
1692 void generateMissingArcs(RigGraph *rigg)
1695 int multi_level_limit = 5;
1697 for (reebg = rigg->link_mesh; reebg; reebg = reebg->link_up)
1701 for (earc = reebg->arcs.first; earc; earc = earc->next)
1703 if (earc->flag == ARC_USED)
1705 generateMissingArcsFromNode(rigg, earc->head, multi_level_limit);
1706 generateMissingArcsFromNode(rigg, earc->tail, multi_level_limit);
1712 /************************************ RETARGETTING *****************************************************/
1714 static void repositionControl(RigGraph *rigg, RigControl *ctrl, float head[3], float tail[3], float qrot[4], float resize);
1716 static void repositionTailControl(RigGraph *rigg, RigControl *ctrl);
1718 static void finalizeControl(RigGraph *rigg, RigControl *ctrl, float resize)
1720 if ((ctrl->flag & RIG_CTRL_DONE) == RIG_CTRL_DONE)
1722 RigControl *ctrl_child;
1725 printf("CTRL: %s LINK: %s", ctrl->bone->name, ctrl->link->name);
1727 if (ctrl->link_tail)
1729 printf(" TAIL: %s", ctrl->link_tail->name);
1735 /* if there was a tail link: apply link, recalc resize factor and qrot */
1736 if (ctrl->tail_mode != TL_NONE)
1738 float *tail_vec = NULL;
1739 float v1[3], v2[3], qtail[4];
1741 if (ctrl->tail_mode == TL_TAIL)
1743 tail_vec = ctrl->link_tail->tail;
1745 else if (ctrl->tail_mode == TL_HEAD)
1747 tail_vec = ctrl->link_tail->head;
1750 sub_v3_v3v3(v1, ctrl->bone->tail, ctrl->bone->head);
1751 sub_v3_v3v3(v2, tail_vec, ctrl->bone->head);
1753 VECCOPY(ctrl->bone->tail, tail_vec);
1755 rotation_between_vecs_to_quat(qtail, v1, v2);
1756 mul_qt_qtqt(ctrl->qrot, qtail, ctrl->qrot);
1758 resize = len_v3(v2) / len_v3v3(ctrl->head, ctrl->tail);
1761 ctrl->bone->roll = rollBoneByQuat(ctrl->bone, ctrl->up_axis, ctrl->qrot);
1763 /* Cascade to connected control bones */
1764 for (ctrl_child = rigg->controls.first; ctrl_child; ctrl_child = ctrl_child->next)
1766 if (ctrl_child->link == ctrl->bone)
1768 repositionControl(rigg, ctrl_child, ctrl->bone->head, ctrl->bone->tail, ctrl->qrot, resize);
1770 if (ctrl_child->link_tail == ctrl->bone)
1772 repositionTailControl(rigg, ctrl_child);
1778 static void repositionTailControl(RigGraph *rigg, RigControl *ctrl)
1780 ctrl->flag |= RIG_CTRL_TAIL_DONE;
1782 finalizeControl(rigg, ctrl, 1); /* resize will be recalculated anyway so we don't need it */
1785 static void repositionControl(RigGraph *rigg, RigControl *ctrl, float head[3], float UNUSED(tail[3]), float qrot[4], float resize)
1787 float parent_offset[3], tail_offset[3];
1789 VECCOPY(parent_offset, ctrl->offset);
1790 mul_v3_fl(parent_offset, resize);
1791 mul_qt_v3(qrot, parent_offset);
1793 add_v3_v3v3(ctrl->bone->head, head, parent_offset);
1795 ctrl->flag |= RIG_CTRL_HEAD_DONE;
1797 QUATCOPY(ctrl->qrot, qrot);
1799 if (ctrl->tail_mode == TL_NONE)
1801 sub_v3_v3v3(tail_offset, ctrl->tail, ctrl->head);
1802 mul_v3_fl(tail_offset, resize);
1803 mul_qt_v3(qrot, tail_offset);
1805 add_v3_v3v3(ctrl->bone->tail, ctrl->bone->head, tail_offset);
1807 ctrl->flag |= RIG_CTRL_TAIL_DONE;
1810 finalizeControl(rigg, ctrl, resize);
1813 static void repositionBone(bContext *C, RigGraph *rigg, RigEdge *edge, float vec0[3], float vec1[3], float up_axis[3])
1815 Scene *scene = CTX_data_scene(C);
1818 float qrot[4], resize;
1824 sub_v3_v3v3(v1, edge->tail, edge->head);
1825 sub_v3_v3v3(v2, vec1, vec0);
1827 l1 = normalize_v3(v1);
1828 l2 = normalize_v3(v2);
1832 rotation_between_vecs_to_quat(qrot, v1, v2);
1834 VECCOPY(bone->head, vec0);
1835 VECCOPY(bone->tail, vec1);
1837 if (!is_zero_v3(up_axis))
1841 if (scene->toolsettings->skgen_retarget_roll == SK_RETARGET_ROLL_VIEW)
1843 bone->roll = rollBoneByQuatAligned(bone, edge->up_axis, qrot, qroll, up_axis);
1845 else if (scene->toolsettings->skgen_retarget_roll == SK_RETARGET_ROLL_JOINT)
1847 bone->roll = rollBoneByQuatJoint(edge, edge->prev, qrot, qroll, up_axis);
1854 mul_qt_qtqt(qrot, qroll, qrot);
1858 bone->roll = rollBoneByQuat(bone, edge->up_axis, qrot);
1861 for (ctrl = rigg->controls.first; ctrl; ctrl = ctrl->next)
1863 if (ctrl->link == bone)
1865 repositionControl(rigg, ctrl, vec0, vec1, qrot, resize);
1867 if (ctrl->link_tail == bone)
1869 repositionTailControl(rigg, ctrl);
1874 static RetargetMode detectArcRetargetMode(RigArc *arc);
1875 static void retargetArctoArcLength(bContext *C, RigGraph *rigg, RigArc *iarc, RigNode *inode_start);
1878 static RetargetMode detectArcRetargetMode(RigArc *iarc)
1880 RetargetMode mode = RETARGET_AGGRESSIVE;
1881 ReebArc *earc = iarc->link_mesh;
1883 int large_angle = 0;
1884 float avg_angle = 0;
1885 float avg_length = 0;
1889 for (edge = iarc->edges.first; edge; edge = edge->next)
1891 avg_angle += edge->angle;
1895 avg_angle /= nb_edges - 1; /* -1 because last edge doesn't have an angle */
1897 avg_length = iarc->length / nb_edges;
1902 for (edge = iarc->edges.first; edge; edge = edge->next)
1904 if (fabs(edge->angle - avg_angle) > M_PI / 6)
1910 else if (nb_edges == 2 && avg_angle > 0)
1916 if (large_angle == 0)
1918 mode = RETARGET_LENGTH;
1921 if (earc->bcount <= (iarc->count - 1))
1923 mode = RETARGET_LENGTH;
1930 static void printMovesNeeded(int *positions, int nb_positions)
1935 for (i = 0; i < nb_positions; i++)
1937 moves += positions[i] - (i + 1);
1940 printf("%i moves needed\n", moves);
1943 static void printPositions(int *positions, int nb_positions)
1947 for (i = 0; i < nb_positions; i++)
1949 printf("%i ", positions[i]);
1955 #define MAX_COST FLT_MAX /* FIX ME */
1957 static float costDistance(BArcIterator *iter, float *vec0, float *vec1, int i0, int i1, float distance_weight)
1959 EmbedBucket *bucket = NULL;
1961 float v1[3], v2[3], c[3];
1964 if (distance_weight > 0)
1966 sub_v3_v3v3(v1, vec0, vec1);
1968 v1_inpf = dot_v3v3(v1, v1);
1973 for (j = i0 + 1; j < i1 - 1; j++)
1977 bucket = IT_peek(iter, j);
1979 sub_v3_v3v3(v2, bucket->p, vec1);
1981 cross_v3_v3v3(c, v1, v2);
1983 dist = dot_v3v3(c, c) / v1_inpf;
1985 max_dist = dist > max_dist ? dist : max_dist;
1988 return distance_weight * max_dist;
2001 static float costAngle(float original_angle, float vec_first[3], float vec_second[3], float angle_weight)
2003 if (angle_weight > 0)
2005 float current_angle;
2007 if (!is_zero_v3(vec_first) && !is_zero_v3(vec_second))
2009 current_angle = saacos(dot_v3v3(vec_first, vec_second));
2011 return angle_weight * fabs(current_angle - original_angle);
2015 return angle_weight * M_PI;
2024 static float costLength(float original_length, float current_length, float length_weight)
2026 if (current_length == 0)
2032 float length_ratio = fabs((current_length - original_length) / original_length);
2033 return length_weight * length_ratio * length_ratio;
2038 static float calcCostLengthDistance(BArcIterator *iter, float **vec_cache, RigEdge *edge, float *vec1, float *vec2, int i1, int i2)
2043 sub_v3_v3v3(vec, vec2, vec1);
2044 length = normalize_v3(vec);
2046 return costLength(edge->length, length) + costDistance(iter, vec1, vec2, i1, i2);
2050 static float calcCostAngleLengthDistance(BArcIterator *iter, float **UNUSED(vec_cache), RigEdge *edge, float *vec0, float *vec1, float *vec2, int i1, int i2, float angle_weight, float length_weight, float distance_weight)
2052 float vec_second[3], vec_first[3];
2056 sub_v3_v3v3(vec_second, vec2, vec1);
2057 length2 = normalize_v3(vec_second);
2063 sub_v3_v3v3(vec_first, vec1, vec0);
2064 normalize_v3(vec_first);
2066 new_cost += costAngle(edge->prev->angle, vec_first, vec_second, angle_weight);
2070 new_cost += costLength(edge->length, length2, length_weight);
2073 new_cost += costDistance(iter, vec1, vec2, i1, i2, distance_weight);
2078 static int indexMemoNode(int nb_positions, int previous, int current, int joints_left)
2080 return joints_left * nb_positions * nb_positions + current * nb_positions + previous;
2083 static void copyMemoPositions(int *positions, MemoNode *table, int nb_positions, int joints_left)
2085 int previous = 0, current = 0;
2088 for (i = 0; joints_left > 0; joints_left--, i++)
2091 node = table + indexMemoNode(nb_positions, previous, current, joints_left);
2093 positions[i] = node->next;
2096 current = node->next;
2100 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)
2103 int index = indexMemoNode(nb_positions, previous, current, joints_left);
2105 node = table + index;
2107 if (node->weight != 0)
2111 else if (joints_left == 0)
2113 float *vec0 = vec_cache[previous];
2114 float *vec1 = vec_cache[current];
2115 float *vec2 = vec_cache[nb_positions + 1];
2117 node->weight = calcCostAngleLengthDistance(iter, vec_cache, edge, vec0, vec1, vec2, current, iter->length, angle_weight, length_weight, distance_weight);
2123 MemoNode *min_node = NULL;
2124 float *vec0 = vec_cache[previous];
2125 float *vec1 = vec_cache[current];
2126 float min_weight= 0.0f;
2130 for (next = current + 1; next <= nb_positions - (joints_left - 1); next++)
2132 MemoNode *next_node;
2133 float *vec2 = vec_cache[next];
2134 float weight = 0.0f;
2136 /* ADD WEIGHT OF PREVIOUS - CURRENT - NEXT triple */
2137 weight = calcCostAngleLengthDistance(iter, vec_cache, edge, vec0, vec1, vec2, current, next, angle_weight, length_weight, distance_weight);
2139 if (weight >= MAX_COST)
2144 /* add node weight */
2145 next_node = solveJoints(table, iter, vec_cache, nb_joints, nb_positions, current, next, edge->next, joints_left - 1, angle_weight, length_weight, distance_weight);
2146 weight += next_node->weight;
2148 if (min_node == NULL || weight < min_weight)
2150 min_weight = weight;
2151 min_node = next_node;
2158 node->weight = min_weight;
2159 node->next = min_next;
2164 node->weight = MAX_COST;
2171 static int testFlipArc(RigArc *iarc, RigNode *inode_start)
2173 ReebArc *earc = iarc->link_mesh;
2174 ReebNode *enode_start = BIF_NodeFromIndex(earc, inode_start->link_mesh);
2176 /* no flip needed if both nodes are the same */
2177 if ((enode_start == earc->head && inode_start == iarc->head) || (enode_start == earc->tail && inode_start == iarc->tail))
2187 static void retargetArctoArcAggresive(bContext *C, RigGraph *rigg, RigArc *iarc, RigNode *inode_start)
2189 ReebArcIterator arc_iter;
2190 BArcIterator *iter = (BArcIterator*)&arc_iter;
2192 EmbedBucket *bucket = NULL;
2193 ReebNode *node_start, *node_end;
2194 ReebArc *earc = iarc->link_mesh;
2195 float angle_weight = 1.0; // GET FROM CONTEXT
2196 float length_weight = 1.0;
2197 float distance_weight = 1.0;
2198 float min_cost = FLT_MAX;
2200 int *best_positions;
2201 int nb_edges = BLI_countlist(&iarc->edges);
2202 int nb_joints = nb_edges - 1;
2203 RetargetMethod method = METHOD_MEMOIZE;
2206 if (nb_joints > earc->bcount)
2208 printf("NOT ENOUGH BUCKETS!\n");
2212 best_positions = MEM_callocN(sizeof(int) * nb_joints, "Best positions");
2214 if (testFlipArc(iarc, inode_start))
2216 node_start = earc->tail;
2217 node_end = earc->head;
2221 node_start = earc->head;
2222 node_end = earc->tail;
2225 /* equal number of joints and potential position, just fill them in */
2226 if (nb_joints == earc->bcount)
2230 /* init with first values */
2231 for (i = 0; i < nb_joints; i++)
2233 best_positions[i] = i + 1;
2236 if (method == METHOD_MEMOIZE)
2238 int nb_positions = earc->bcount;
2239 int nb_memo_nodes = nb_positions * nb_positions * (nb_joints + 1);
2240 MemoNode *table = MEM_callocN(nb_memo_nodes * sizeof(MemoNode), "memoization table");
2242 float **positions_cache = MEM_callocN(sizeof(float*) * (nb_positions + 2), "positions cache");
2245 positions_cache[0] = node_start->p;
2246 positions_cache[nb_positions + 1] = node_end->p;
2248 initArcIterator(iter, earc, node_start);
2250 for (i = 1; i <= nb_positions; i++)
2252 EmbedBucket *bucket = IT_peek(iter, i);
2253 positions_cache[i] = bucket->p;
2256 result = solveJoints(table, iter, positions_cache, nb_joints, earc->bcount, 0, 0, iarc->edges.first, nb_joints, angle_weight, length_weight, distance_weight);
2258 min_cost = result->weight;
2259 copyMemoPositions(best_positions, table, earc->bcount, nb_joints);
2262 MEM_freeN(positions_cache);
2265 vec0 = node_start->p;
2266 initArcIterator(iter, earc, node_start);
2269 printPositions(best_positions, nb_joints);
2270 printMovesNeeded(best_positions, nb_joints);
2271 printf("min_cost %f\n", min_cost);
2272 printf("buckets: %i\n", earc->bcount);
2275 /* set joints to best position */
2276 for (edge = iarc->edges.first, i = 0;
2278 edge = edge->next, i++)
2283 bucket = IT_peek(iter, best_positions[i]);
2295 repositionBone(C, rigg, edge, vec0, vec1, no);
2301 MEM_freeN(best_positions);
2304 static void retargetArctoArcLength(bContext *C, RigGraph *rigg, RigArc *iarc, RigNode *inode_start)
2306 ReebArcIterator arc_iter;
2307 BArcIterator *iter = (BArcIterator*)&arc_iter;
2308 ReebArc *earc = iarc->link_mesh;
2309 ReebNode *node_start, *node_end;
2311 EmbedBucket *bucket = NULL;
2312 float embedding_length = 0;
2315 float *previous_vec = NULL;
2318 if (testFlipArc(iarc, inode_start))
2320 node_start = (ReebNode*)earc->tail;
2321 node_end = (ReebNode*)earc->head;
2325 node_start = (ReebNode*)earc->head;
2326 node_end = (ReebNode*)earc->tail;
2329 initArcIterator(iter, earc, node_start);
2331 bucket = IT_next(iter);
2333 vec0 = node_start->p;
2335 while (bucket != NULL)
2339 embedding_length += len_v3v3(vec0, vec1);
2342 bucket = IT_next(iter);
2345 embedding_length += len_v3v3(node_end->p, vec1);
2348 initArcIterator(iter, earc, node_start);
2350 bucket = IT_next(iter);
2352 vec0 = node_start->p;
2353 previous_vec = vec0;
2356 for (edge = iarc->edges.first; edge; edge = edge->next)
2358 float new_bone_length = edge->length / iarc->length * embedding_length;
2362 while (bucket && new_bone_length > length)
2364 length += len_v3v3(previous_vec, vec1);
2365 bucket = IT_next(iter);
2366 previous_vec = vec1;
2377 /* no need to move virtual edges (space between unconnected bones) */
2380 repositionBone(C, rigg, edge, vec0, vec1, no);
2384 previous_vec = vec1;
2388 static void retargetArctoArc(bContext *C, RigGraph *rigg, RigArc *iarc, RigNode *inode_start)
2391 RetargetParam *p = MEM_callocN(sizeof(RetargetParam), "RetargetParam");
2395 p->inode_start = inode_start;
2398 BLI_insert_work(rigg->worker, p);
2404 p.inode_start = inode_start;
2407 exec_retargetArctoArc(&p);
2411 void *exec_retargetArctoArc(void *param)
2413 RetargetParam *p = (RetargetParam*)param;
2414 RigGraph *rigg = p->rigg;
2415 RigArc *iarc = p->iarc;
2416 bContext *C = p->context;
2417 RigNode *inode_start = p->inode_start;
2418 ReebArc *earc = iarc->link_mesh;
2420 if (BLI_countlist(&iarc->edges) == 1)
2422 RigEdge *edge = iarc->edges.first;
2424 if (testFlipArc(iarc, inode_start))
2426 repositionBone(C, rigg, edge, earc->tail->p, earc->head->p, earc->head->no);
2430 repositionBone(C, rigg, edge, earc->head->p, earc->tail->p, earc->tail->no);
2435 RetargetMode mode = detectArcRetargetMode(iarc);
2437 if (mode == RETARGET_AGGRESSIVE)
2439 retargetArctoArcAggresive(C, rigg, iarc, inode_start);
2443 retargetArctoArcLength(C, rigg, iarc, inode_start);
2454 static void matchMultiResolutionNode(RigGraph *rigg, RigNode *inode, ReebNode *top_node)
2456 ReebNode *enode = top_node;
2457 ReebGraph *reebg = BIF_graphForMultiNode(rigg->link_mesh, enode);
2460 ishape = BLI_subtreeShape((BGraph*)rigg, (BNode*)inode, NULL, 0) % SHAPE_LEVELS;
2461 eshape = BLI_subtreeShape((BGraph*)reebg, (BNode*)enode, NULL, 0) % SHAPE_LEVELS;
2463 inode->link_mesh = enode;
2465 while (ishape == eshape && enode->link_down)
2467 inode->link_mesh = enode;
2469 enode = enode->link_down;
2470 reebg = BIF_graphForMultiNode(rigg->link_mesh, enode); /* replace with call to link_down once that exists */
2471 eshape = BLI_subtreeShape((BGraph*)reebg, (BNode*)enode, NULL, 0) % SHAPE_LEVELS;
2475 static void markMultiResolutionChildArc(ReebNode *end_enode, ReebNode *enode)
2479 for(i = 0; i < enode->degree; i++)
2481 ReebArc *earc = (ReebArc*)enode->arcs[i];
2483 if (earc->flag == ARC_FREE)
2485 earc->flag = ARC_TAKEN;
2487 if (earc->tail->degree > 1 && earc->tail != end_enode)
2489 markMultiResolutionChildArc(end_enode, earc->tail);
2496 static void markMultiResolutionArc(ReebArc *start_earc)
2498 if (start_earc->link_up)
2501 for (earc = start_earc->link_up ; earc; earc = earc->link_up)
2503 earc->flag = ARC_TAKEN;
2505 if (earc->tail->index != start_earc->tail->index)
2507 markMultiResolutionChildArc(earc->tail, earc->tail);
2513 static void matchMultiResolutionArc(RigGraph *rigg, RigNode *start_node, RigArc *next_iarc, ReebArc *next_earc)
2515 ReebNode *enode = next_earc->head;
2516 ReebGraph *reebg = BIF_graphForMultiNode(rigg->link_mesh, enode);
2519 ishape = BLI_subtreeShape((BGraph*)rigg, (BNode*)start_node, (BArc*)next_iarc, 1) % SHAPE_LEVELS;
2520 eshape = BLI_subtreeShape((BGraph*)reebg, (BNode*)enode, (BArc*)next_earc, 1) % SHAPE_LEVELS;
2522 while (ishape != eshape && next_earc->link_up)
2524 next_earc->flag = ARC_TAKEN; // mark previous as taken, to prevent backtrack on lower levels
2526 next_earc = next_earc->link_up;
2527 reebg = reebg->link_up;
2528 enode = next_earc->head;
2529 eshape = BLI_subtreeShape((BGraph*)reebg, (BNode*)enode, (BArc*)next_earc, 1) % SHAPE_LEVELS;
2532 next_earc->flag = ARC_USED;
2533 next_iarc->link_mesh = next_earc;
2535 /* mark all higher levels as taken too */
2536 markMultiResolutionArc(next_earc);
2537 // while (next_earc->link_up)
2539 // next_earc = next_earc->link_up;
2540 // next_earc->flag = ARC_TAKEN;
2544 static void matchMultiResolutionStartingNode(RigGraph *rigg, ReebGraph *reebg, RigNode *inode)
2549 enode = reebg->nodes.first;
2551 ishape = BLI_subtreeShape((BGraph*)rigg, (BNode*)inode, NULL, 0) % SHAPE_LEVELS;
2552 eshape = BLI_subtreeShape((BGraph*)rigg->link_mesh, (BNode*)enode, NULL, 0) % SHAPE_LEVELS;
2554 while (ishape != eshape && reebg->link_up)
2556 reebg = reebg->link_up;
2558 enode = reebg->nodes.first;
2560 eshape = BLI_subtreeShape((BGraph*)reebg, (BNode*)enode, NULL, 0) % SHAPE_LEVELS;
2563 inode->link_mesh = enode;
2566 static void findCorrespondingArc(RigGraph *rigg, RigArc *start_arc, RigNode *start_node, RigArc *next_iarc, int root)
2568 ReebNode *enode = start_node->link_mesh;
2570 int symmetry_level = next_iarc->symmetry_level;
2571 int symmetry_group = next_iarc->symmetry_group;
2572 int symmetry_flag = next_iarc->symmetry_flag;
2575 next_iarc->link_mesh = NULL;
2579 // printf("-----------------------\n");
2580 // printf("MATCHING LIMB\n");
2581 // RIG_printArcBones(next_iarc);
2584 for(i = 0; i < enode->degree; i++)
2586 next_earc = (ReebArc*)enode->arcs[i];
2588 // if (next_earc->flag == ARC_FREE)
2590 // printf("candidate (level %i ?= %i) (flag %i ?= %i) (group %i ?= %i)\n",
2591 // symmetry_level, next_earc->symmetry_level,
2592 // symmetry_flag, next_earc->symmetry_flag,
2593 // symmetry_group, next_earc->symmetry_flag);
2596 if (next_earc->flag == ARC_FREE &&
2597 next_earc->symmetry_flag == symmetry_flag &&
2598 next_earc->symmetry_group == symmetry_group &&
2599 next_earc->symmetry_level == symmetry_level)
2601 // printf("CORRESPONDING ARC FOUND\n");
2602 // 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);
2604 matchMultiResolutionArc(rigg, start_node, next_iarc, next_earc);
2609 /* not found, try at higher nodes (lower node might have filtered internal arcs, messing shape of tree */
2610 if (next_iarc->link_mesh == NULL)
2612 // printf("NO CORRESPONDING ARC FOUND - GOING TO HIGHER LEVELS\n");
2616 start_node->link_mesh = enode->link_up;
2617 findCorrespondingArc(rigg, start_arc, start_node, next_iarc, 0);
2621 /* still not found, print debug info */
2622 if (root && next_iarc->link_mesh == NULL)
2624 start_node->link_mesh = enode; /* linking back with root node */
2626 // printf("NO CORRESPONDING ARC FOUND\n");
2627 // RIG_printArcBones(next_iarc);
2629 // printf("ON NODE %i, multilevel %i\n", enode->index, enode->multi_level);
2631 // printf("LOOKING FOR\n");
2632 // printf("flag %i -- level %i -- flag %i -- group %i\n", ARC_FREE, symmetry_level, symmetry_flag, symmetry_group);
2634 // printf("CANDIDATES\n");
2635 // for(i = 0; i < enode->degree; i++)
2637 // next_earc = (ReebArc*)enode->arcs[i];
2638 // 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);
2641 /* Emergency matching */
2642 for(i = 0; i < enode->degree; i++)
2644 next_earc = (ReebArc*)enode->arcs[i];
2646 if (next_earc->flag == ARC_FREE && next_earc->symmetry_level == symmetry_level)
2648 // printf("USING: \n");
2649 // 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);
2650 matchMultiResolutionArc(rigg, start_node, next_iarc, next_earc);
2658 static void retargetSubgraph(bContext *C, RigGraph *rigg, RigArc *start_arc, RigNode *start_node)
2660 RigNode *inode = start_node;
2663 /* no start arc on first node */
2666 ReebNode *enode = start_node->link_mesh;
2667 ReebArc *earc = start_arc->link_mesh;
2669 retargetArctoArc(C, rigg, start_arc, start_node);
2671 enode = BIF_otherNodeFromIndex(earc, enode);
2672 inode = (RigNode*)BLI_otherNode((BArc*)start_arc, (BNode*)inode);
2674 /* match with lowest node with correct shape */
2675 matchMultiResolutionNode(rigg, inode, enode);
2678 for(i = 0; i < inode->degree; i++)
2680 RigArc *next_iarc = (RigArc*)inode->arcs[i];
2682 /* no back tracking */
2683 if (next_iarc != start_arc)
2685 findCorrespondingArc(rigg, start_arc, inode, next_iarc, 1);
2686 if (next_iarc->link_mesh)
2688 retargetSubgraph(C, rigg, next_iarc, inode);
2694 static void finishRetarget(RigGraph *rigg)
2697 BLI_end_worker(rigg->worker);
2701 static void adjustGraphs(bContext *C, RigGraph *rigg)
2703 bArmature *arm= rigg->ob->data;
2706 for (arc = rigg->arcs.first; arc; arc = arc->next)
2710 retargetArctoArc(C, rigg, arc, arc->head);
2714 finishRetarget(rigg);
2716 /* Turn the list into an armature */
2717 arm->edbo = rigg->editbones;
2718 ED_armature_from_edit(rigg->ob);
2720 ED_undo_push(C, "Retarget Skeleton");
2723 static void retargetGraphs(bContext *C, RigGraph *rigg)
2725 bArmature *arm= rigg->ob->data;
2726 ReebGraph *reebg = rigg->link_mesh;
2729 /* flag all ReebArcs as free */
2730 BIF_flagMultiArcs(reebg, ARC_FREE);
2732 /* return to first level */
2733 reebg = rigg->link_mesh;
2737 matchMultiResolutionStartingNode(rigg, reebg, inode);
2739 retargetSubgraph(C, rigg, NULL, inode);
2741 //generateMissingArcs(rigg);
2743 finishRetarget(rigg);
2745 /* Turn the list into an armature */
2746 arm->edbo = rigg->editbones;
2747 ED_armature_from_edit(rigg->ob);
2750 const char *RIG_nameBone(RigGraph *rg, int arc_index, int bone_index)
2752 RigArc *arc = BLI_findlink(&rg->arcs, arc_index);
2760 if (bone_index == BLI_countlist(&arc->edges))
2762 return "Last joint";
2765 iedge = BLI_findlink(&arc->edges, bone_index);
2772 if (iedge->bone == NULL)
2774 return "Bone offset";
2777 return iedge->bone->name;
2780 int RIG_nbJoints(RigGraph *rg)
2785 total += BLI_countlist(&rg->nodes);
2787 for (arc = rg->arcs.first; arc; arc = arc->next)
2789 total += BLI_countlist(&arc->edges) - 1; /* -1 because end nodes are already counted */
2795 void BIF_freeRetarget(void)
2799 RIG_freeRigGraph((BGraph*)GLOBAL_RIGG);
2804 void BIF_retargetArmature(bContext *C)
2807 double start_time, end_time;
2808 double gstart_time, gend_time;
2809 double reeb_time, rig_time=0.0, retarget_time=0.0, total_time;
2811 gstart_time = start_time = PIL_check_seconds_timer();
2813 reebg = BIF_ReebGraphMultiFromEditMesh(C);
2815 end_time = PIL_check_seconds_timer();
2816 reeb_time = end_time - start_time;
2818 printf("Reeb Graph created\n");
2820 CTX_DATA_BEGIN(C, Base*, base, selected_editable_bases) {
2821 Object *ob = base->object;
2823 if (ob->type==OB_ARMATURE)
2830 /* Put the armature into editmode */
2833 start_time = PIL_check_seconds_timer();
2835 rigg = RIG_graphFromArmature(C, ob, arm);
2837 end_time = PIL_check_seconds_timer();
2838 rig_time = end_time - start_time;
2840 printf("Armature graph created\n");
2842 //RIG_printGraph(rigg);
2844 rigg->link_mesh = reebg;
2846 printf("retargetting %s\n", ob->id.name);
2848 start_time = PIL_check_seconds_timer();
2850 retargetGraphs(C, rigg);
2852 end_time = PIL_check_seconds_timer();
2853 retarget_time = end_time - start_time;
2859 break; /* only one armature at a time */
2865 gend_time = PIL_check_seconds_timer();
2867 total_time = gend_time - gstart_time;
2869 printf("-----------\n");
2870 printf("runtime: \t%.3f\n", total_time);
2871 printf("reeb: \t\t%.3f (%.1f%%)\n", reeb_time, reeb_time / total_time * 100);
2872 printf("rig: \t\t%.3f (%.1f%%)\n", rig_time, rig_time / total_time * 100);
2873 printf("retarget: \t%.3f (%.1f%%)\n", retarget_time, retarget_time / total_time * 100);
2874 printf("-----------\n");