== Clamp To Constraint - Depsgraph Fix Part2 ==
[blender-staging.git] / source / blender / blenkernel / intern / depsgraph.c
1 /**
2  * $Id$
3  *
4  * ***** BEGIN GPL/BL DUAL LICENSE BLOCK *****
5  *
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. The Blender
10  * Foundation also sells licenses for use in proprietary software under
11  * the Blender License.  See http://www.blender.org/BL/ for information
12  * about this.
13  *
14  * This program is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17  * GNU General Public License for more details.
18  *
19  * You should have received a copy of the GNU General Public License
20  * along with this program; if not, write to the Free Software Foundation,
21  * Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
22  *
23  * The Original Code is Copyright (C) 2004 Blender Foundation.
24  * All rights reserved.
25  *
26  * Contributor(s): none yet.
27  *
28  * ***** END GPL/BL DUAL LICENSE BLOCK *****
29  */
30  
31 #include <stdio.h>
32 #include <string.h>
33 #include <math.h>
34
35 #ifdef _WIN32
36 #include "BLI_winstuff.h"
37 #endif
38
39 //#include "BMF_Api.h"
40
41 #include "BLI_blenlib.h"
42 #include "BLI_arithb.h"
43
44 #include "DNA_action_types.h"
45 #include "DNA_armature_types.h"
46 #include "DNA_curve_types.h"
47 #include "DNA_ID.h"
48 #include "DNA_effect_types.h"
49 #include "DNA_group_types.h"
50 #include "DNA_lattice_types.h"
51 #include "DNA_key_types.h"
52 #include "DNA_mesh_types.h"
53 #include "DNA_modifier_types.h"
54 #include "DNA_nla_types.h"
55 #include "DNA_object_types.h"
56 #include "DNA_object_force.h"
57 #include "DNA_object_fluidsim.h"
58 #include "DNA_oops_types.h"
59 #include "DNA_scene_types.h"
60 #include "DNA_screen_types.h"
61 #include "DNA_space_types.h"
62 #include "DNA_view2d_types.h"
63 #include "DNA_view3d_types.h"
64
65 #include "BKE_action.h"
66 #include "BKE_effect.h"
67 #include "BKE_global.h"
68 #include "BKE_group.h"
69 #include "BKE_key.h"
70 #include "BKE_main.h"
71 #include "BKE_mball.h"
72 #include "BKE_modifier.h"
73 #include "BKE_object.h"
74 #include "BKE_scene.h"
75 #include "BKE_utildefines.h"
76
77 #include "MEM_guardedalloc.h"
78 #include "blendef.h"
79
80 #include "BPY_extern.h"
81
82  #include "depsgraph_private.h"
83  
84 /* Queue and stack operations for dag traversal 
85  *
86  * the queue store a list of freenodes to avoid successives alloc/dealloc
87  */
88
89 DagNodeQueue * queue_create (int slots) 
90 {
91         DagNodeQueue * queue;
92         DagNodeQueueElem * elem;
93         int i;
94         
95         queue = MEM_mallocN(sizeof(DagNodeQueue),"DAG queue");
96         queue->freenodes = MEM_mallocN(sizeof(DagNodeQueue),"DAG queue");
97         queue->count = 0;
98         queue->maxlevel = 0;
99         queue->first = queue->last = NULL;
100         elem = MEM_mallocN(sizeof(DagNodeQueueElem),"DAG queue elem3");
101         elem->node = NULL;
102         elem->next = NULL;
103         queue->freenodes->first = queue->freenodes->last = elem;
104         
105         for (i = 1; i <slots;i++) {
106                 elem = MEM_mallocN(sizeof(DagNodeQueueElem),"DAG queue elem4");
107                 elem->node = NULL;
108                 elem->next = NULL;
109                 queue->freenodes->last->next = elem;
110                 queue->freenodes->last = elem;
111         }
112         queue->freenodes->count = slots;
113         return queue;
114 }
115
116 void queue_raz(DagNodeQueue *queue)
117 {
118         DagNodeQueueElem * elem;
119         
120         elem = queue->first;
121         if (queue->freenodes->last)
122                 queue->freenodes->last->next = elem;
123         else
124                 queue->freenodes->first = queue->freenodes->last = elem;
125         
126         elem->node = NULL;
127         queue->freenodes->count++;
128         while (elem->next) {
129                 elem = elem->next;
130                 elem->node = NULL;
131                 queue->freenodes->count++;
132         }
133         queue->freenodes->last = elem;
134         queue->count = 0;
135 }
136
137 void queue_delete(DagNodeQueue *queue)
138 {
139         DagNodeQueueElem * elem;
140         DagNodeQueueElem * temp;
141         
142         elem = queue->first;
143         while (elem) {
144                 temp = elem;
145                 elem = elem->next;
146                 MEM_freeN(temp);
147         }
148         
149         elem = queue->freenodes->first;
150         while (elem) {
151                 temp = elem;
152                 elem = elem->next;
153                 MEM_freeN(temp);
154         }
155         
156         MEM_freeN(queue->freenodes);                    
157         MEM_freeN(queue);                       
158 }
159
160 /* insert in queue, remove in front */
161 void push_queue(DagNodeQueue *queue, DagNode *node)
162 {
163         DagNodeQueueElem * elem;
164         int i;
165
166         if (node == NULL) {
167                 fprintf(stderr,"pushing null node \n");
168                 return;
169         }
170         /*fprintf(stderr,"BFS push : %s %d\n",((ID *) node->ob)->name, queue->count);*/
171
172         elem = queue->freenodes->first;
173         if (elem != NULL) {
174                 queue->freenodes->first = elem->next;
175                 if ( queue->freenodes->last == elem) {
176                         queue->freenodes->last = NULL;
177                         queue->freenodes->first = NULL;
178                 }
179                 queue->freenodes->count--;
180         } else { /* alllocating more */         
181                 elem = MEM_mallocN(sizeof(DagNodeQueueElem),"DAG queue elem1");
182                 elem->node = NULL;
183                 elem->next = NULL;
184                 queue->freenodes->first = queue->freenodes->last = elem;
185
186                 for (i = 1; i <DAGQUEUEALLOC;i++) {
187                         elem = MEM_mallocN(sizeof(DagNodeQueueElem),"DAG queue elem2");
188                         elem->node = NULL;
189                         elem->next = NULL;
190                         queue->freenodes->last->next = elem;
191                         queue->freenodes->last = elem;
192                 }
193                 queue->freenodes->count = DAGQUEUEALLOC;
194                         
195                 elem = queue->freenodes->first; 
196                 queue->freenodes->first = elem->next;   
197         }
198         elem->next = NULL;
199         elem->node = node;
200         if (queue->last != NULL)
201                 queue->last->next = elem;
202         queue->last = elem;
203         if (queue->first == NULL) {
204                 queue->first = elem;
205         }
206         queue->count++;
207 }
208
209
210 /* insert in front, remove in front */
211 void push_stack(DagNodeQueue *queue, DagNode *node)
212 {
213         DagNodeQueueElem * elem;
214         int i;
215
216         elem = queue->freenodes->first; 
217         if (elem != NULL) {
218                 queue->freenodes->first = elem->next;
219                 if ( queue->freenodes->last == elem) {
220                         queue->freenodes->last = NULL;
221                         queue->freenodes->first = NULL;
222                 }
223                 queue->freenodes->count--;
224         } else { /* alllocating more */
225                 elem = MEM_mallocN(sizeof(DagNodeQueueElem),"DAG queue elem1");
226                 elem->node = NULL;
227                 elem->next = NULL;
228                 queue->freenodes->first = queue->freenodes->last = elem;
229
230                 for (i = 1; i <DAGQUEUEALLOC;i++) {
231                         elem = MEM_mallocN(sizeof(DagNodeQueueElem),"DAG queue elem2");
232                         elem->node = NULL;
233                         elem->next = NULL;
234                         queue->freenodes->last->next = elem;
235                         queue->freenodes->last = elem;
236                 }
237                 queue->freenodes->count = DAGQUEUEALLOC;
238                         
239                 elem = queue->freenodes->first; 
240                 queue->freenodes->first = elem->next;   
241         }
242         elem->next = queue->first;
243         elem->node = node;
244         queue->first = elem;
245         if (queue->last == NULL)
246                 queue->last = elem;
247         queue->count++;
248 }
249
250
251 DagNode * pop_queue(DagNodeQueue *queue)
252 {
253         DagNodeQueueElem * elem;
254         DagNode *node;
255
256         elem = queue->first;
257         if (elem) {
258                 queue->first = elem->next;
259                 if (queue->last == elem) {
260                         queue->last=NULL;
261                         queue->first=NULL;
262                 }
263                 queue->count--;
264                 if (queue->freenodes->last)
265                         queue->freenodes->last->next=elem;
266                 queue->freenodes->last=elem;
267                 if (queue->freenodes->first == NULL)
268                         queue->freenodes->first=elem;
269                 node = elem->node;
270                 elem->node = NULL;
271                 elem->next = NULL;
272                 queue->freenodes->count++;
273                 return node;
274         } else {
275                 fprintf(stderr,"return null \n");
276                 return NULL;
277         }
278 }
279
280 void    *pop_ob_queue(struct DagNodeQueue *queue) {
281         return(pop_queue(queue)->ob);
282 }
283
284 DagNode * get_top_node_queue(DagNodeQueue *queue) 
285 {
286         return queue->first->node;
287 }
288
289 int             queue_count(struct DagNodeQueue *queue){
290         return queue->count;
291 }
292
293
294 DagForest * dag_init()
295 {
296         DagForest *forest;
297         /* use callocN to init all zero */
298         forest = MEM_callocN(sizeof(DagForest),"DAG root");
299         return forest;
300 }
301
302 static void dag_add_driver_relation(Ipo *ipo, DagForest *dag, DagNode *node, int isdata)
303 {
304         IpoCurve *icu;
305         DagNode *node1;
306         
307         for(icu= ipo->curve.first; icu; icu= icu->next) {
308                 if(icu->driver) {
309
310                         if (icu->driver->type == IPO_DRIVER_TYPE_PYTHON) {
311
312                                 if ((icu->driver->flag & IPO_DRIVER_FLAG_INVALID) || (icu->driver->name[0] == '\0'))
313                                         continue; /* empty or invalid expression */
314                                 else {
315                                         /* now we need refs to all objects mentioned in this
316                                          * pydriver expression, to call 'dag_add_relation'
317                                          * for each of them */
318                                         Object **obarray = BPY_pydriver_get_objects(icu->driver);
319                                         if (obarray) {
320                                                 Object *ob, **oba = obarray;
321
322                                                 while (*oba) {
323                                                         ob = *oba;
324                                                         node1 = dag_get_node(dag, ob);
325                                                         if (ob->type == OB_ARMATURE)
326                                                                 dag_add_relation(dag, node1, node, isdata?DAG_RL_DATA_DATA:DAG_RL_DATA_OB);
327                                                         else
328                                                                 dag_add_relation(dag, node1, node, isdata?DAG_RL_OB_DATA:DAG_RL_OB_OB);
329                                                         oba++;
330                                                 }
331
332                                                 MEM_freeN(obarray);
333                                         }
334                                 }
335                         }
336                         else if (icu->driver->ob) {
337                                 node1 = dag_get_node(dag, icu->driver->ob);
338                                 if(icu->driver->blocktype==ID_AR)
339                                         dag_add_relation(dag, node1, node, isdata?DAG_RL_DATA_DATA:DAG_RL_DATA_OB);
340                                 else
341                                         dag_add_relation(dag, node1, node, isdata?DAG_RL_OB_DATA:DAG_RL_OB_OB);
342                         }
343                 }
344         }
345 }
346
347 static void build_dag_object(DagForest *dag, DagNode *scenenode, Object *ob, int mask)
348 {
349         bConstraint *con;
350         DagNode * node;
351         DagNode * node2;
352         DagNode * node3;
353         Key *key;
354         int addtoroot= 1;
355         
356         node = dag_get_node(dag, ob);
357         
358         if ((ob->data) && (mask&DAG_RL_DATA)) {
359                 node2 = dag_get_node(dag,ob->data);
360                 dag_add_relation(dag,node,node2,DAG_RL_DATA);
361                 node2->first_ancestor = ob;
362                 node2->ancestor_count += 1;
363         }
364         
365         if (ob->type == OB_ARMATURE) {
366                 if (ob->pose){
367                         bPoseChannel *pchan;
368                         bConstraint *con;
369                         Object * target;
370                         char *subtarget;
371                         
372                         for (pchan = ob->pose->chanbase.first; pchan; pchan=pchan->next){
373                                 for (con = pchan->constraints.first; con; con=con->next){
374                                         if (constraint_has_target(con)) {
375                                                 
376                                                 target = get_constraint_target(con, &subtarget);
377                                                 if (target!=ob) {
378                                                         // fprintf(stderr,"armature %s target :%s \n", ob->id.name, target->id.name);
379                                                         node3 = dag_get_node(dag, target);
380                                                         
381                                                         if(subtarget && subtarget[0])
382                                                                 dag_add_relation(dag,node3,node, DAG_RL_OB_DATA|DAG_RL_DATA_DATA);
383                                                         else if(ELEM(con->type, CONSTRAINT_TYPE_FOLLOWPATH, CONSTRAINT_TYPE_CLAMPTO))   
384                                                                 dag_add_relation(dag,node3,node, DAG_RL_DATA_DATA|DAG_RL_OB_DATA);
385                                                         else
386                                                                 dag_add_relation(dag,node3,node, DAG_RL_OB_DATA);
387                                                         
388                                                 }
389                                         }
390                                 }
391                         }
392                 }
393         }
394         
395         /* driver dependencies, nla modifiers */
396         if(ob->ipo) 
397                 dag_add_driver_relation(ob->ipo, dag, node, 0);
398         
399         key= ob_get_key(ob);
400         if(key && key->ipo)
401                 dag_add_driver_relation(key->ipo, dag, node, 1);
402         
403         if(ob->action) {
404                 bActionChannel *chan;
405                 bConstraintChannel *conchan;
406                 for (chan = ob->action->chanbase.first; chan; chan=chan->next){
407                         if(chan->ipo)
408                                 dag_add_driver_relation(chan->ipo, dag, node, 1);
409                         for (conchan=chan->constraintChannels.first; conchan; conchan=conchan->next)
410                                 if(conchan->ipo)
411                                         dag_add_driver_relation(conchan->ipo, dag, node, 1);
412                 }
413         }
414         if(ob->nlastrips.first) {
415                 bActionStrip *strip;
416                 bActionChannel *chan;
417                 for(strip= ob->nlastrips.first; strip; strip= strip->next) {
418                         if(strip->act && strip->act!=ob->action)
419                                 for (chan = strip->act->chanbase.first; chan; chan=chan->next)
420                                         if(chan->ipo)
421                                                 dag_add_driver_relation(chan->ipo, dag, node, 1);
422                         if(strip->modifiers.first) {
423                                 bActionModifier *amod;
424                                 for(amod= strip->modifiers.first; amod; amod= amod->next) {
425                                         if(amod->ob) {
426                                                 node2 = dag_get_node(dag, amod->ob);
427                                                 dag_add_relation(dag, node2, node, DAG_RL_DATA_DATA|DAG_RL_OB_DATA);
428                                         }
429                                 }
430                         }
431                 }
432         }
433         if (ob->modifiers.first) {
434                 ModifierData *md;
435                 
436                 for(md=ob->modifiers.first; md; md=md->next) {
437                         ModifierTypeInfo *mti = modifierType_getInfo(md->type);
438                         
439                         if (mti->updateDepgraph) mti->updateDepgraph(md, dag, ob, node);
440                 }
441         }
442         if (ob->parent) {
443                 node2 = dag_get_node(dag,ob->parent);
444                 
445                 switch(ob->partype) {
446                         case PARSKEL:
447                                 dag_add_relation(dag,node2,node,DAG_RL_DATA_DATA|DAG_RL_OB_OB);
448                                 break;
449                         case PARVERT1: case PARVERT3: case PARBONE:
450                                 dag_add_relation(dag,node2,node,DAG_RL_DATA_OB|DAG_RL_OB_OB);
451                                 break;
452                         default:
453                                 if(ob->parent->type==OB_LATTICE) 
454                                         dag_add_relation(dag,node2,node,DAG_RL_DATA_DATA|DAG_RL_OB_OB);
455                                 else if(ob->parent->type==OB_CURVE) {
456                                         Curve *cu= ob->parent->data;
457                                         if(cu->flag & CU_PATH) 
458                                                 dag_add_relation(dag,node2,node,DAG_RL_DATA_OB|DAG_RL_OB_OB);
459                                         else
460                                                 dag_add_relation(dag,node2,node,DAG_RL_OB_OB);
461                                 }
462                                         else
463                                                 dag_add_relation(dag,node2,node,DAG_RL_OB_OB);
464                 }
465                 /* exception case: parent is duplivert */
466                 if(ob->type==OB_MBALL && (ob->parent->transflag & OB_DUPLIVERTS)) {
467                         dag_add_relation(dag, node2, node, DAG_RL_DATA_DATA|DAG_RL_OB_OB);
468                 }
469                 
470                 addtoroot = 0;
471         }
472         if (ob->track) {
473                 node2 = dag_get_node(dag,ob->track);
474                 dag_add_relation(dag,node2,node,DAG_RL_OB_OB);
475                 addtoroot = 0;
476         }
477         if (ob->proxy) {
478                 node2 = dag_get_node(dag, ob->proxy);
479                 dag_add_relation(dag, node, node2, DAG_RL_DATA_DATA|DAG_RL_OB_OB);
480                 /* inverted relation, so addtoroot shouldn't be set to zero */
481         }
482         
483         if (ob->transflag & OB_DUPLI) {
484                 if((ob->transflag & OB_DUPLIGROUP) && ob->dup_group) {
485                         GroupObject *go;
486                         for(go= ob->dup_group->gobject.first; go; go= go->next) {
487                                 if(go->ob) {
488                                         node2 = dag_get_node(dag, go->ob);
489                                         /* node2 changes node1, this keeps animations updated in groups?? not logical? */
490                                         dag_add_relation(dag, node2, node, DAG_RL_OB_OB);
491                                 }
492                         }
493                 }
494         }
495     
496         /* softbody collision  */
497         if((ob->type==OB_MESH) || (ob->type==OB_CURVE) || (ob->type==OB_LATTICE)) {
498                 Base *base;
499                 if(modifiers_isSoftbodyEnabled(ob)){
500                         // would be nice to have a list of colliders here
501                         // so for now walk all objects in scene check 'same layer rule'
502                         for(base = G.scene->base.first; base; base= base->next) {
503                                 if( (base->lay & ob->lay) && base->object->pd) {
504                                         Object *ob1= base->object;
505                                         if((ob1->pd->deflect) && (ob1 != ob))  {
506                                                 node2 = dag_get_node(dag, ob1);                                 
507                                                 dag_add_relation(dag, node2, node, DAG_RL_DATA_DATA|DAG_RL_OB_DATA);                                            
508                                         }
509                                 }
510                         }
511                 }
512         }
513                 
514         if (ob->type==OB_MBALL) {
515                 Object *mom= find_basis_mball(ob);
516                 if(mom!=ob) {
517                         node2 = dag_get_node(dag, mom);
518                         dag_add_relation(dag,node,node2,DAG_RL_DATA_DATA|DAG_RL_OB_DATA);  // mom depends on children!
519                 }
520         }
521         else if (ob->type==OB_CURVE) {
522                 Curve *cu= ob->data;
523                 if(cu->bevobj) {
524                         node2 = dag_get_node(dag, cu->bevobj);
525                         dag_add_relation(dag,node2,node,DAG_RL_DATA_DATA|DAG_RL_OB_DATA);
526                 }
527                 if(cu->taperobj) {
528                         node2 = dag_get_node(dag, cu->taperobj);
529                         dag_add_relation(dag,node2,node,DAG_RL_DATA_DATA|DAG_RL_OB_DATA);
530                 }
531                 if(cu->ipo)
532                         dag_add_driver_relation(cu->ipo, dag, node, 1);
533
534         }
535         else if(ob->type==OB_FONT) {
536                 Curve *cu= ob->data;
537                 if(cu->textoncurve) {
538                         node2 = dag_get_node(dag, cu->textoncurve);
539                         dag_add_relation(dag,node2,node,DAG_RL_DATA_DATA|DAG_RL_OB_DATA);
540                 }
541         }
542         else if(ob->type==OB_MESH) {
543                 PartEff *paf= give_parteff(ob);
544                 if(paf) {
545                         ListBase *listb;
546                         pEffectorCache *ec;
547                         
548                         /* ob location depends on itself */
549                         if((paf->flag & PAF_STATIC)==0)
550                                 dag_add_relation(dag, node, node, DAG_RL_OB_DATA);
551                         
552                         listb= pdInitEffectors(ob, paf->group);         /* note, makes copy... */
553                         if(listb) {
554                                 for(ec= listb->first; ec; ec= ec->next) {
555                                         Object *ob1= ec->ob;
556                                         PartDeflect *pd= ob1->pd;
557                                                 
558                                         if(pd->forcefield) {
559                                                 node2 = dag_get_node(dag, ob1);
560                                                 if(pd->forcefield==PFIELD_GUIDE)
561                                                         dag_add_relation(dag, node2, node, DAG_RL_DATA_DATA|DAG_RL_OB_DATA);
562                                                 else
563                                                         dag_add_relation(dag, node2, node, DAG_RL_OB_DATA);
564                                         }
565                                 }
566                                 
567                                 pdEndEffectors(listb);  /* restores copy... */
568                         }
569                 }
570         }
571         
572         for (con = ob->constraints.first; con; con=con->next){
573                 if (constraint_has_target(con)) {
574                         char *str;
575                         Object *obt= get_constraint_target(con, &str);
576                         
577                         node2 = dag_get_node(dag, obt);
578                         if(ELEM(con->type, CONSTRAINT_TYPE_FOLLOWPATH, CONSTRAINT_TYPE_CLAMPTO))
579                                 dag_add_relation(dag, node2, node, DAG_RL_DATA_OB|DAG_RL_OB_OB);
580                         else {
581                                 if(obt->type==OB_ARMATURE && str[0])
582                                         dag_add_relation(dag, node2, node, DAG_RL_DATA_OB|DAG_RL_OB_OB);
583                                 else
584                                         dag_add_relation(dag, node2, node, DAG_RL_OB_OB);
585                         }
586                         addtoroot = 0;
587                 }
588         }
589
590         if (addtoroot == 1 )
591                 dag_add_relation(dag,scenenode,node,DAG_RL_SCENE);
592 }
593
594 struct DagForest *build_dag(struct Scene *sce, short mask) 
595 {
596         Base *base;
597         Object *ob;
598         Group *group;
599         GroupObject *go;
600         DagNode *node;
601         DagNode *scenenode;
602         DagForest *dag;
603         DagAdjList *itA;
604
605         dag = sce->theDag;
606         sce->dagisvalid=1;
607         if ( dag)
608                 free_forest( dag ); 
609         else {
610                 dag = dag_init();
611                 sce->theDag = dag;
612         }
613         
614         /* add base node for scene. scene is always the first node in DAG */
615         scenenode = dag_add_node(dag, sce);     
616         
617         /* add current scene objects */
618         for(base = sce->base.first; base; base= base->next) {
619                 ob= base->object;
620                 
621                 build_dag_object(dag, scenenode, ob, mask);
622                 if(ob->proxy)
623                         build_dag_object(dag, scenenode, ob->proxy, mask);
624                 
625                 /* handled in next loop */
626                 if(ob->dup_group) 
627                         ob->dup_group->id.flag |= LIB_DOIT;
628         }
629         
630         /* add groups used in current scene objects */
631         for(group= G.main->group.first; group; group= group->id.next) {
632                 if(group->id.flag & LIB_DOIT) {
633                         for(go= group->gobject.first; go; go= go->next) {
634                                 build_dag_object(dag, scenenode, go->ob, mask);
635                         }
636                         group->id.flag &= ~LIB_DOIT;
637                 }
638         }
639         
640         /* Now all relations were built, but we need to solve 1 exceptional case;
641            When objects have multiple "parents" (for example parent + constraint working on same object)
642            the relation type has to be synced. One of the parents can change, and should give same event to child */
643         
644         /* nodes were callocced, so we can use node->color for temporal storage */
645         for(node = sce->theDag->DagNode.first; node; node= node->next) {
646                 if(node->type==ID_OB) {
647                         for(itA = node->child; itA; itA= itA->next) {
648                                 if(itA->node->type==ID_OB) {
649                                         itA->node->color |= itA->type;
650                                 }
651                         }
652                 }
653         }
654         /* now set relations equal, so that when only one parent changes, the correct recalcs are found */
655         for(node = sce->theDag->DagNode.first; node; node= node->next) {
656                 if(node->type==ID_OB) {
657                         for(itA = node->child; itA; itA= itA->next) {
658                                 if(itA->node->type==ID_OB) {
659                                         itA->type |= itA->node->color;
660                                 }
661                         }
662                 }
663         }
664         
665         // cycle detection and solving
666         // solve_cycles(dag);   
667         
668         return dag;
669 }
670
671
672 void free_forest(DagForest *Dag) 
673 {  /* remove all nodes and deps */
674         DagNode *tempN;
675         DagAdjList *tempA;      
676         DagAdjList *itA;
677         DagNode *itN = Dag->DagNode.first;
678         
679         while (itN) {
680                 itA = itN->child;       
681                 while (itA) {
682                         tempA = itA;
683                         itA = itA->next;
684                         MEM_freeN(tempA);                       
685                 }
686                 
687                 itA = itN->parent;      
688                 while (itA) {
689                         tempA = itA;
690                         itA = itA->next;
691                         MEM_freeN(tempA);                       
692                 }
693                 
694                 tempN = itN;
695                 itN = itN->next;
696                 MEM_freeN(tempN);
697         }
698         Dag->DagNode.first = NULL;
699         Dag->DagNode.last = NULL;
700         Dag->numNodes = 0;
701
702 }
703
704 DagNode * dag_find_node (DagForest *forest,void * fob)
705 {
706         DagNode *node = forest->DagNode.first;
707         
708         while (node) {
709                 if (node->ob == fob)
710                         return node;
711                 node = node->next;
712         }
713         return NULL;
714 }
715
716 static int ugly_hack_sorry= 1;  // prevent type check
717
718 /* no checking of existance, use dag_find_node first or dag_get_node */
719 DagNode * dag_add_node (DagForest *forest, void * fob)
720 {
721         DagNode *node;
722                 
723         node = MEM_callocN(sizeof(DagNode),"DAG node");
724         if (node) {
725                 node->ob = fob;
726                 node->color = DAG_WHITE;
727
728                 if(ugly_hack_sorry) node->type = GS(((ID *) fob)->name);        // sorry, done for pose sorting
729                 if (forest->numNodes) {
730                         ((DagNode *) forest->DagNode.last)->next = node;
731                         forest->DagNode.last = node;
732                         forest->numNodes++;
733                 } else {
734                         forest->DagNode.last = node;
735                         forest->DagNode.first = node;
736                         forest->numNodes = 1;
737                 }
738         }
739         return node;
740 }
741
742 DagNode * dag_get_node (DagForest *forest,void * fob)
743 {
744         DagNode *node;
745         
746         node = dag_find_node (forest, fob);     
747         if (!node) 
748                 node = dag_add_node(forest, fob);
749         return node;
750 }
751
752
753
754 DagNode * dag_get_sub_node (DagForest *forest,void * fob)
755 {
756         DagNode *node;
757         DagAdjList *mainchild, *prev=NULL;
758         
759         mainchild = ((DagNode *) forest->DagNode.first)->child;
760         /* remove from first node (scene) adj list if present */
761         while (mainchild) {
762                 if (mainchild->node == fob) {
763                         if (prev) {
764                                 prev->next = mainchild->next;
765                                 MEM_freeN(mainchild);
766                                 break;
767                         } else {
768                                 ((DagNode *) forest->DagNode.first)->child = mainchild->next;
769                                 MEM_freeN(mainchild);
770                                 break;
771                         }
772                 }
773                 prev = mainchild;
774                 mainchild = mainchild->next;
775         }
776         node = dag_find_node (forest, fob);     
777         if (!node) 
778                 node = dag_add_node(forest, fob);
779         return node;
780 }
781
782 void dag_add_relation(DagForest *forest, DagNode *fob1, DagNode *fob2, short rel) 
783 {
784         DagAdjList *itA = fob1->child;
785         
786         while (itA) { /* search if relation exist already */
787                 if (itA->node == fob2) {
788                         itA->type |= rel;
789                         itA->count += 1;
790                         return;
791                 }
792                 itA = itA->next;
793         }
794         /* create new relation and insert at head. MALLOC alert! */
795         itA = MEM_mallocN(sizeof(DagAdjList),"DAG adj list");
796         itA->node = fob2;
797         itA->type = rel;
798         itA->count = 1;
799         itA->next = fob1->child;
800         fob1->child = itA;
801 }
802
803 static void dag_add_parent_relation(DagForest *forest, DagNode *fob1, DagNode *fob2, short rel) 
804 {
805         DagAdjList *itA = fob2->parent;
806         
807         while (itA) { /* search if relation exist already */
808                 if (itA->node == fob1) {
809                         itA->type |= rel;
810                         itA->count += 1;
811                         return;
812                 }
813                 itA = itA->next;
814         }
815         /* create new relation and insert at head. MALLOC alert! */
816         itA = MEM_mallocN(sizeof(DagAdjList),"DAG adj list");
817         itA->node = fob1;
818         itA->type = rel;
819         itA->count = 1;
820         itA->next = fob2->parent;
821         fob2->parent = itA;
822 }
823
824
825 /*
826  * MainDAG is the DAG of all objects in current scene
827  * used only for drawing there is one also in each scene
828  */
829 static DagForest * MainDag = NULL;
830
831 DagForest *getMainDag(void)
832 {
833         return MainDag;
834 }
835
836
837 void setMainDag(DagForest *dag)
838 {
839         MainDag = dag;
840 }
841
842
843 /*
844  * note for BFS/DFS
845  * in theory we should sweep the whole array
846  * but in our case the first node is the scene
847  * and is linked to every other object
848  *
849  * for general case we will need to add outer loop
850  */
851
852 /*
853  * ToDo : change pos kludge
854  */
855
856 /* adjust levels for drawing in oops space */
857 void graph_bfs(void)
858 {
859         DagNode *node;
860         DagNodeQueue *nqueue;
861         int pos[50];
862         int i;
863         DagAdjList *itA;
864         int minheight;
865         
866         /* fprintf(stderr,"starting BFS \n ------------\n"); */ 
867         nqueue = queue_create(DAGQUEUEALLOC);
868         for ( i=0; i<50; i++)
869                 pos[i] = 0;
870         
871         /* Init
872          * dagnode.first is alway the root (scene) 
873          */
874         node = MainDag->DagNode.first;
875         while(node) {
876                 node->color = DAG_WHITE;
877                 node->BFS_dist = 9999;
878                 node->k = 0;
879                 node = node->next;
880         }
881         
882         node = MainDag->DagNode.first;
883         if (node->color == DAG_WHITE) {
884                 node->color = DAG_GRAY;
885                 node->BFS_dist = 1;
886                 push_queue(nqueue,node);  
887                 while(nqueue->count) {
888                         node = pop_queue(nqueue);
889                         
890                         minheight = pos[node->BFS_dist];
891                         itA = node->child;
892                         while(itA != NULL) {
893                                 if((itA->node->color == DAG_WHITE) ) {
894                                         itA->node->color = DAG_GRAY;
895                                         itA->node->BFS_dist = node->BFS_dist + 1;
896                                         itA->node->k = (float) minheight;
897                                         push_queue(nqueue,itA->node);
898                                 }
899                                 
900                                  else {
901                                         fprintf(stderr,"bfs not dag tree edge color :%i \n",itA->node->color);
902                                 }
903                                  
904                                 
905                                 itA = itA->next;
906                         }
907                         if (pos[node->BFS_dist] > node->k ) {
908                                 pos[node->BFS_dist] += 1;                               
909                                 node->k = (float) pos[node->BFS_dist];
910                         } else {
911                                 pos[node->BFS_dist] = (int) node->k +1;
912                         }
913                         set_node_xy(node, node->BFS_dist*DEPSX*2, pos[node->BFS_dist]*DEPSY*2);
914                         node->color = DAG_BLACK;
915                         /*
916                          fprintf(stderr,"BFS node : %20s %i %5.0f %5.0f\n",((ID *) node->ob)->name,node->BFS_dist, node->x, node->y);   
917                          */
918                 }
919         }
920         queue_delete(nqueue);
921 }
922
923 int pre_and_post_BFS(DagForest *dag, short mask, graph_action_func pre_func, graph_action_func post_func, void **data) {
924         DagNode *node;
925         
926         node = dag->DagNode.first;
927         return pre_and_post_source_BFS(dag, mask,  node,  pre_func,  post_func, data);
928 }
929
930
931 int pre_and_post_source_BFS(DagForest *dag, short mask, DagNode *source, graph_action_func pre_func, graph_action_func post_func, void **data)
932 {
933         DagNode *node;
934         DagNodeQueue *nqueue;
935         DagAdjList *itA;
936         int     retval = 0;
937         /* fprintf(stderr,"starting BFS \n ------------\n"); */ 
938         
939         /* Init
940                 * dagnode.first is alway the root (scene) 
941                 */
942         node = dag->DagNode.first;
943         nqueue = queue_create(DAGQUEUEALLOC);
944         while(node) {
945                 node->color = DAG_WHITE;
946                 node->BFS_dist = 9999;
947                 node = node->next;
948         }
949         
950         node = source;
951         if (node->color == DAG_WHITE) {
952                 node->color = DAG_GRAY;
953                 node->BFS_dist = 1;
954                 pre_func(node->ob,data);
955                 
956                 while(nqueue->count) {
957                         node = pop_queue(nqueue);
958                         
959                         itA = node->child;
960                         while(itA != NULL) {
961                                 if((itA->node->color == DAG_WHITE) && (itA->type & mask)) {
962                                         itA->node->color = DAG_GRAY;
963                                         itA->node->BFS_dist = node->BFS_dist + 1;
964                                         push_queue(nqueue,itA->node);
965                                         pre_func(node->ob,data);
966                                 }
967                                 
968                                 else { // back or cross edge
969                                         retval = 1;
970                                 }
971                                 itA = itA->next;
972                         }
973                         post_func(node->ob,data);
974                         node->color = DAG_BLACK;
975                         /*
976                          fprintf(stderr,"BFS node : %20s %i %5.0f %5.0f\n",((ID *) node->ob)->name,node->BFS_dist, node->x, node->y);   
977                          */
978                 }
979         }
980         queue_delete(nqueue);
981         return retval;
982 }
983
984 /* non recursive version of DFS, return queue -- outer loop present to catch odd cases (first level cycles)*/
985 DagNodeQueue * graph_dfs(void)
986 {
987         DagNode *node;
988         DagNodeQueue *nqueue;
989         DagNodeQueue *retqueue;
990         int pos[50];
991         int i;
992         DagAdjList *itA;
993         int time;
994         int skip = 0;
995         int minheight;
996         int maxpos=0;
997         int     is_cycle = 0;
998         /*
999          *fprintf(stderr,"starting DFS \n ------------\n");
1000          */     
1001         nqueue = queue_create(DAGQUEUEALLOC);
1002         retqueue = queue_create(MainDag->numNodes);
1003         for ( i=0; i<50; i++)
1004                 pos[i] = 0;
1005         
1006         /* Init
1007          * dagnode.first is alway the root (scene) 
1008          */
1009         node = MainDag->DagNode.first;
1010         while(node) {
1011                 node->color = DAG_WHITE;
1012                 node->DFS_dist = 9999;
1013                 node->DFS_dvtm = node->DFS_fntm = 9999;
1014                 node->k = 0;
1015                 node =  node->next;
1016         }
1017         
1018         time = 1;
1019         
1020         node = MainDag->DagNode.first;
1021
1022         do {
1023         if (node->color == DAG_WHITE) {
1024                 node->color = DAG_GRAY;
1025                 node->DFS_dist = 1;
1026                 node->DFS_dvtm = time;
1027                 time++;
1028                 push_stack(nqueue,node);  
1029                         
1030                 while(nqueue->count) {
1031                         //graph_print_queue(nqueue);
1032
1033                          skip = 0;
1034                         node = get_top_node_queue(nqueue);
1035                         
1036                         minheight = pos[node->DFS_dist];
1037
1038                         itA = node->child;
1039                         while(itA != NULL) {
1040                                 if((itA->node->color == DAG_WHITE) ) {
1041                                         itA->node->DFS_dvtm = time;
1042                                         itA->node->color = DAG_GRAY;
1043
1044                                         time++;
1045                                         itA->node->DFS_dist = node->DFS_dist + 1;
1046                                         itA->node->k = (float) minheight;
1047                                         push_stack(nqueue,itA->node);
1048                                         skip = 1;
1049                                         break;
1050                                 } else { 
1051                                         if (itA->node->color == DAG_GRAY) { // back edge
1052                                                 fprintf(stderr,"dfs back edge :%15s %15s \n",((ID *) node->ob)->name, ((ID *) itA->node->ob)->name);
1053                                                 is_cycle = 1;
1054                                         } else if (itA->node->color == DAG_BLACK) {
1055                                                 ;
1056                                                 /* already processed node but we may want later to change distance either to shorter to longer.
1057                                                  * DFS_dist is the first encounter  
1058                                                 */
1059                                                 /*if (node->DFS_dist >= itA->node->DFS_dist)
1060                                                         itA->node->DFS_dist = node->DFS_dist + 1;
1061                                                         
1062                                                         fprintf(stderr,"dfs forward or cross edge :%15s %i-%i %15s %i-%i \n",
1063                                                                 ((ID *) node->ob)->name,
1064                                                                 node->DFS_dvtm, 
1065                                                                 node->DFS_fntm, 
1066                                                                 ((ID *) itA->node->ob)->name, 
1067                                                                 itA->node->DFS_dvtm,
1068                                                                 itA->node->DFS_fntm);
1069                                         */
1070                                         } else 
1071                                                 fprintf(stderr,"dfs unknown edge \n");
1072                                 }
1073                                 itA = itA->next;
1074                         }                       
1075
1076                         if (!skip) {
1077                                 node = pop_queue(nqueue);
1078                                 node->color = DAG_BLACK;
1079
1080                                 node->DFS_fntm = time;
1081                                 time++;
1082                                 if (node->DFS_dist > maxpos)
1083                                         maxpos = node->DFS_dist;
1084                                 if (pos[node->DFS_dist] > node->k ) {
1085                                         pos[node->DFS_dist] += 1;                               
1086                                         node->k = (float) pos[node->DFS_dist];
1087                                 } else {
1088                                         pos[node->DFS_dist] = (int) node->k +1;
1089                                 }
1090                                 set_node_xy(node, node->DFS_dist*DEPSX*2, pos[node->DFS_dist]*DEPSY*2);
1091                                 
1092                                 /*
1093                                  fprintf(stderr,"DFS node : %20s %i %i %i %i\n",((ID *) node->ob)->name,node->BFS_dist, node->DFS_dist, node->DFS_dvtm, node->DFS_fntm );       
1094                                 */
1095                                  push_stack(retqueue,node);
1096                                 
1097                         }
1098                 }
1099         }
1100                 node = node->next;
1101         } while (node);
1102 //        fprintf(stderr,"i size : %i \n", maxpos);
1103           
1104         queue_delete(nqueue);
1105           return(retqueue);
1106 }
1107
1108 /* unused */
1109 int pre_and_post_DFS(DagForest *dag, short mask, graph_action_func pre_func, graph_action_func post_func, void **data) {
1110         DagNode *node;
1111
1112         node = dag->DagNode.first;
1113         return pre_and_post_source_DFS(dag, mask,  node,  pre_func,  post_func, data);
1114 }
1115
1116 int pre_and_post_source_DFS(DagForest *dag, short mask, DagNode *source, graph_action_func pre_func, graph_action_func post_func, void **data)
1117 {
1118         DagNode *node;
1119         DagNodeQueue *nqueue;
1120         DagAdjList *itA;
1121         int time;
1122         int skip = 0;
1123         int retval = 0;
1124         /*
1125          *fprintf(stderr,"starting DFS \n ------------\n");
1126          */     
1127         nqueue = queue_create(DAGQUEUEALLOC);
1128         
1129         /* Init
1130                 * dagnode.first is alway the root (scene) 
1131                 */
1132         node = dag->DagNode.first;
1133         while(node) {
1134                 node->color = DAG_WHITE;
1135                 node->DFS_dist = 9999;
1136                 node->DFS_dvtm = node->DFS_fntm = 9999;
1137                 node->k = 0;
1138                 node =  node->next;
1139         }
1140         
1141         time = 1;
1142         
1143         node = source;
1144         do {
1145                 if (node->color == DAG_WHITE) {
1146                         node->color = DAG_GRAY;
1147                         node->DFS_dist = 1;
1148                         node->DFS_dvtm = time;
1149                         time++;
1150                         push_stack(nqueue,node);  
1151                         pre_func(node->ob,data);
1152
1153                         while(nqueue->count) {
1154                                 skip = 0;
1155                                 node = get_top_node_queue(nqueue);
1156                                                                 
1157                                 itA = node->child;
1158                                 while(itA != NULL) {
1159                                         if((itA->node->color == DAG_WHITE) && (itA->type & mask) ) {
1160                                                 itA->node->DFS_dvtm = time;
1161                                                 itA->node->color = DAG_GRAY;
1162                                                 
1163                                                 time++;
1164                                                 itA->node->DFS_dist = node->DFS_dist + 1;
1165                                                 push_stack(nqueue,itA->node);
1166                                                 pre_func(node->ob,data);
1167
1168                                                 skip = 1;
1169                                                 break;
1170                                         } else {
1171                                                 if (itA->node->color == DAG_GRAY) {// back edge
1172                                                         retval = 1;
1173                                                 }
1174 //                                              else if (itA->node->color == DAG_BLACK) { // cross or forward
1175 //                                                      ;
1176                                         }
1177                                         itA = itA->next;
1178                                 }                       
1179                                 
1180                                 if (!skip) {
1181                                         node = pop_queue(nqueue);
1182                                         node->color = DAG_BLACK;
1183                                         
1184                                         node->DFS_fntm = time;
1185                                         time++;
1186                                         post_func(node->ob,data);
1187                                 }
1188                         }
1189                 }
1190                 node = node->next;
1191         } while (node);
1192         queue_delete(nqueue);
1193         return(retval);
1194 }
1195
1196
1197 // used to get the obs owning a datablock
1198 struct DagNodeQueue *get_obparents(struct DagForest     *dag, void *ob) 
1199 {
1200         DagNode * node, *node1;
1201         DagNodeQueue *nqueue;
1202         DagAdjList *itA;
1203
1204         node = dag_find_node(dag,ob);
1205         if(node==NULL) {
1206                 return NULL;
1207         }
1208         else if (node->ancestor_count == 1) { // simple case
1209                 nqueue = queue_create(1);
1210                 push_queue(nqueue,node);
1211         } else {        // need to go over the whole dag for adj list
1212                 nqueue = queue_create(node->ancestor_count);
1213                 
1214                 node1 = dag->DagNode.first;
1215                 do {
1216                         if (node1->DFS_fntm > node->DFS_fntm) { // a parent is finished after child. must check adj list
1217                                 itA = node->child;
1218                                 while(itA != NULL) {
1219                                         if ((itA->node == node) && (itA->type == DAG_RL_DATA)) {
1220                                                 push_queue(nqueue,node);
1221                                         }
1222                                         itA = itA->next;
1223                                 }
1224                         }
1225                         node1 = node1->next;
1226                 } while (node1);
1227         }
1228         return nqueue;
1229 }
1230
1231 struct DagNodeQueue *get_first_ancestors(struct DagForest       *dag, void *ob)
1232 {
1233         DagNode * node, *node1;
1234         DagNodeQueue *nqueue;
1235         DagAdjList *itA;
1236         
1237         node = dag_find_node(dag,ob);
1238         
1239         // need to go over the whole dag for adj list
1240         nqueue = queue_create(node->ancestor_count);
1241         
1242         node1 = dag->DagNode.first;
1243         do {
1244                 if (node1->DFS_fntm > node->DFS_fntm) { 
1245                         itA = node->child;
1246                         while(itA != NULL) {
1247                                 if (itA->node == node) {
1248                                         push_queue(nqueue,node);
1249                                 }
1250                                 itA = itA->next;
1251                         }
1252                 }
1253                 node1 = node1->next;
1254         } while (node1);
1255         
1256         return nqueue;  
1257 }
1258
1259 // standard DFS list
1260 struct DagNodeQueue *get_all_childs(struct DagForest    *dag, void *ob)
1261 {
1262         DagNode *node;
1263         DagNodeQueue *nqueue;
1264         DagNodeQueue *retqueue;
1265         DagAdjList *itA;
1266         int time;
1267         int skip = 0;
1268
1269         nqueue = queue_create(DAGQUEUEALLOC);
1270         retqueue = queue_create(dag->numNodes); // was MainDag... why? (ton)
1271         
1272         node = dag->DagNode.first;
1273         while(node) {
1274                 node->color = DAG_WHITE;
1275                 node =  node->next;
1276         }
1277         
1278         time = 1;
1279         
1280         node = dag_find_node(dag, ob);   // could be done in loop above (ton)
1281         if(node) { // can be null for newly added objects
1282                 
1283                 node->color = DAG_GRAY;
1284                 time++;
1285                 push_stack(nqueue,node);  
1286                 
1287                 while(nqueue->count) {
1288                         
1289                         skip = 0;
1290                         node = get_top_node_queue(nqueue);
1291                                         
1292                         itA = node->child;
1293                         while(itA != NULL) {
1294                                 if((itA->node->color == DAG_WHITE) ) {
1295                                         itA->node->DFS_dvtm = time;
1296                                         itA->node->color = DAG_GRAY;
1297                                         
1298                                         time++;
1299                                         push_stack(nqueue,itA->node);
1300                                         skip = 1;
1301                                         break;
1302                                 } 
1303                                 itA = itA->next;
1304                         }                       
1305                         
1306                         if (!skip) {
1307                                 node = pop_queue(nqueue);
1308                                 node->color = DAG_BLACK;
1309                                 
1310                                 time++;
1311                                 push_stack(retqueue,node);                      
1312                         }
1313                 }
1314         }
1315         queue_delete(nqueue);
1316         return(retqueue);
1317 }
1318
1319 /* unused */
1320 short   are_obs_related(struct DagForest        *dag, void *ob1, void *ob2) {
1321         DagNode * node;
1322         DagAdjList *itA;
1323         
1324         node = dag_find_node(dag, ob1);
1325         
1326         itA = node->child;
1327         while(itA != NULL) {
1328                 if((itA->node->ob == ob2) ) {
1329                         return itA->node->type;
1330                 } 
1331                 itA = itA->next;
1332         }
1333         return DAG_NO_RELATION;
1334 }
1335
1336 int     is_acyclic( DagForest   *dag) {
1337         return dag->is_acyclic;
1338 }
1339
1340 void set_node_xy(DagNode *node, float x, float y)
1341 {
1342         node->x = x;
1343         node->y = y;
1344 }
1345
1346
1347 /* debug test functions */
1348
1349 void graph_print_queue(DagNodeQueue *nqueue)
1350 {       
1351         DagNodeQueueElem *queueElem;
1352         
1353         queueElem = nqueue->first;
1354         while(queueElem) {
1355                 fprintf(stderr,"** %s %i %i-%i ",((ID *) queueElem->node->ob)->name,queueElem->node->color,queueElem->node->DFS_dvtm,queueElem->node->DFS_fntm);
1356                 queueElem = queueElem->next;            
1357         }
1358         fprintf(stderr,"\n");
1359 }
1360
1361 void graph_print_queue_dist(DagNodeQueue *nqueue)
1362 {       
1363         DagNodeQueueElem *queueElem;
1364         int max, count;
1365         
1366         queueElem = nqueue->first;
1367         max = queueElem->node->DFS_fntm;
1368         count = 0;
1369         while(queueElem) {
1370                 fprintf(stderr,"** %25s %2.2i-%2.2i ",((ID *) queueElem->node->ob)->name,queueElem->node->DFS_dvtm,queueElem->node->DFS_fntm);
1371                 while (count < queueElem->node->DFS_dvtm-1) { fputc(' ',stderr); count++;}
1372                 fputc('|',stderr); 
1373                 while (count < queueElem->node->DFS_fntm-2) { fputc('-',stderr); count++;}
1374                 fputc('|',stderr);
1375                 fputc('\n',stderr);
1376                 count = 0;
1377                 queueElem = queueElem->next;            
1378         }
1379         fprintf(stderr,"\n");
1380 }
1381
1382 void graph_print_adj_list(void)
1383 {
1384         DagNode *node;
1385         DagAdjList *itA;
1386         
1387         node = (getMainDag())->DagNode.first;
1388         while(node) {
1389                 fprintf(stderr,"node : %s col: %i",((ID *) node->ob)->name, node->color);               
1390                 itA = node->child;
1391                 while (itA) {
1392                         fprintf(stderr,"-- %s ",((ID *) itA->node->ob)->name);
1393                         
1394                         itA = itA->next;
1395                 }
1396                 fprintf(stderr,"\n");
1397                 node = node->next;
1398         }
1399 }
1400
1401 /* ************************ API *********************** */
1402
1403 /* groups with objects in this scene need to be put in the right order as well */
1404 static void scene_sort_groups(Scene *sce)
1405 {
1406         Base *base;
1407         Group *group;
1408         GroupObject *go;
1409         Object *ob;
1410         
1411         /* test; are group objects all in this scene? */
1412         for(ob= G.main->object.first; ob; ob= ob->id.next) {
1413                 ob->id.flag &= ~LIB_DOIT;
1414                 ob->id.newid= NULL;     /* newid abuse for GroupObject */
1415         }
1416         for(base = sce->base.first; base; base= base->next)
1417                 base->object->id.flag |= LIB_DOIT;
1418         
1419         for(group= G.main->group.first; group; group= group->id.next) {
1420                 for(go= group->gobject.first; go; go= go->next) {
1421                         if((go->ob->id.flag & LIB_DOIT)==0)
1422                                 break;
1423                 }
1424                 /* this group is entirely in this scene */
1425                 if(go==NULL) {
1426                         ListBase listb= {NULL, NULL};
1427                         
1428                         for(go= group->gobject.first; go; go= go->next)
1429                                 go->ob->id.newid= (ID *)go;
1430                         
1431                         /* in order of sorted bases we reinsert group objects */
1432                         for(base = sce->base.first; base; base= base->next) {
1433                                 
1434                                 if(base->object->id.newid) {
1435                                         go= (GroupObject *)base->object->id.newid;
1436                                         base->object->id.newid= NULL;
1437                                         BLI_remlink( &group->gobject, go);
1438                                         BLI_addtail( &listb, go);
1439                                 }
1440                         }
1441                         /* copy the newly sorted listbase */
1442                         group->gobject= listb;
1443                 }
1444         }
1445 }
1446
1447 /* sort the base list on dependency order */
1448 void DAG_scene_sort(struct Scene *sce)
1449 {
1450         DagNode *node;
1451         DagNodeQueue *nqueue;
1452         DagAdjList *itA;
1453         int time;
1454         int skip = 0;
1455         ListBase tempbase;
1456         Base *base;
1457         
1458         tempbase.first= tempbase.last= NULL;
1459         
1460         build_dag(sce, DAG_RL_ALL_BUT_DATA);
1461         
1462         nqueue = queue_create(DAGQUEUEALLOC);
1463         
1464         for(node = sce->theDag->DagNode.first; node; node= node->next) {
1465                 node->color = DAG_WHITE;
1466         }
1467         
1468         time = 1;
1469         
1470         node = sce->theDag->DagNode.first;
1471         
1472         node->color = DAG_GRAY;
1473         time++;
1474         push_stack(nqueue,node);  
1475         
1476         while(nqueue->count) {
1477                 
1478                 skip = 0;
1479                 node = get_top_node_queue(nqueue);
1480                 
1481                 itA = node->child;
1482                 while(itA != NULL) {
1483                         if((itA->node->color == DAG_WHITE) ) {
1484                                 itA->node->DFS_dvtm = time;
1485                                 itA->node->color = DAG_GRAY;
1486                                 
1487                                 time++;
1488                                 push_stack(nqueue,itA->node);
1489                                 skip = 1;
1490                                 break;
1491                         } 
1492                         itA = itA->next;
1493                 }                       
1494                 
1495                 if (!skip) {
1496                         if (node) {
1497                                 node = pop_queue(nqueue);
1498                                 if (node->ob == sce)    // we are done
1499                                         break ;
1500                                 node->color = DAG_BLACK;
1501                                 
1502                                 time++;
1503                                 base = sce->base.first;
1504                                 while (base && base->object != node->ob)
1505                                         base = base->next;
1506                                 if(base) {
1507                                         BLI_remlink(&sce->base,base);
1508                                         BLI_addhead(&tempbase,base);
1509                                 }
1510                         }       
1511                 }
1512         }
1513         
1514         // temporal correction for circular dependancies
1515         base = sce->base.first;
1516         while (base) {
1517                 BLI_remlink(&sce->base,base);
1518                 BLI_addhead(&tempbase,base);
1519                 //if(G.f & G_DEBUG) 
1520                         printf("cyclic %s\n", base->object->id.name);
1521                 base = sce->base.first;
1522         }
1523         
1524         sce->base = tempbase;
1525         queue_delete(nqueue);
1526         
1527         /* all groups with objects in this scene gets resorted too */
1528         scene_sort_groups(sce);
1529         
1530         if(G.f & G_DEBUG) {
1531                 printf("\nordered\n");
1532                 for(base = sce->base.first; base; base= base->next) {
1533                         printf(" %s\n", base->object->id.name);
1534                 }
1535         }
1536         /* temporal...? */
1537         sce->recalc |= SCE_PRV_CHANGED; /* test for 3d preview */
1538 }
1539
1540 /* node was checked to have lasttime != curtime and is if type ID_OB */
1541 static void flush_update_node(DagNode *node, unsigned int layer, int curtime)
1542 {
1543         DagAdjList *itA;
1544         Object *ob, *obc;
1545         int oldflag, changed=0;
1546         unsigned int all_layer;
1547         
1548         node->lasttime= curtime;
1549         
1550         ob= node->ob;
1551         if(ob && (ob->recalc & OB_RECALC)) {
1552                 all_layer= ob->lay;
1553                 /* got an object node that changes, now check relations */
1554                 for(itA = node->child; itA; itA= itA->next) {
1555                         all_layer |= itA->lay;
1556                         /* the relationship is visible */
1557                         if(itA->lay & layer) {
1558                                 if(itA->node->type==ID_OB) {
1559                                         obc= itA->node->ob;
1560                                         oldflag= obc->recalc;
1561                                         
1562                                         /* got a ob->obc relation, now check if flag needs flush */
1563                                         if(ob->recalc & OB_RECALC_OB) {
1564                                                 if(itA->type & DAG_RL_OB_OB) {
1565                                                         //printf("ob %s changes ob %s\n", ob->id.name, obc->id.name);
1566                                                         obc->recalc |= OB_RECALC_OB;
1567                                                 }
1568                                                 if(itA->type & DAG_RL_OB_DATA) {
1569                                                         //printf("ob %s changes obdata %s\n", ob->id.name, obc->id.name);
1570                                                         obc->recalc |= OB_RECALC_DATA;
1571                                                 }
1572                                         }
1573                                         if(ob->recalc & OB_RECALC_DATA) {
1574                                                 if(itA->type & DAG_RL_DATA_OB) {
1575                                                         //printf("obdata %s changes ob %s\n", ob->id.name, obc->id.name);
1576                                                         obc->recalc |= OB_RECALC_OB;
1577                                                 }
1578                                                 if(itA->type & DAG_RL_DATA_DATA) {
1579                                                         //printf("obdata %s changes obdata %s\n", ob->id.name, obc->id.name);
1580                                                         obc->recalc |= OB_RECALC_DATA;
1581                                                 }
1582                                         }
1583                                         if(oldflag!=obc->recalc) changed= 1;
1584                                 }
1585                         }
1586                 }
1587                 /* even nicer, we can clear recalc flags...  */
1588                 if((all_layer & layer)==0) {
1589                         /* but existing displaylists or derivedmesh should be freed */
1590                         if(ob->recalc & OB_RECALC_DATA)
1591                                 object_free_display(ob);
1592                         
1593                         ob->recalc &= ~OB_RECALC;
1594                 }
1595         }
1596         
1597         /* check case where child changes and parent forcing obdata to change */
1598         /* should be done regardless if this ob has recalc set */
1599         /* could merge this in with loop above...? (ton) */
1600         for(itA = node->child; itA; itA= itA->next) {
1601                 /* the relationship is visible */
1602                 if(itA->lay & layer) {
1603                         if(itA->node->type==ID_OB) {
1604                                 obc= itA->node->ob;
1605                                 /* child moves */
1606                                 if((obc->recalc & OB_RECALC)==OB_RECALC_OB) {
1607                                         /* parent has deforming info */
1608                                         if(itA->type & (DAG_RL_OB_DATA|DAG_RL_DATA_DATA)) {
1609                                                 // printf("parent %s changes ob %s\n", ob->id.name, obc->id.name);
1610                                                 obc->recalc |= OB_RECALC_DATA;
1611                                         }
1612                                 }
1613                         }
1614                 }
1615         }
1616         
1617         /* we only go deeper if node not checked or something changed  */
1618         for(itA = node->child; itA; itA= itA->next) {
1619                 if(changed || itA->node->lasttime!=curtime) 
1620                         flush_update_node(itA->node, layer, curtime);
1621         }
1622         
1623 }
1624
1625 /* node was checked to have lasttime != curtime , and is of type ID_OB */
1626 static unsigned int flush_layer_node(DagNode *node, int curtime)
1627 {
1628         DagAdjList *itA;
1629         
1630         node->lasttime= curtime;
1631         node->lay= ((Object *)node->ob)->lay;
1632         
1633         for(itA = node->child; itA; itA= itA->next) {
1634                 if(itA->node->type==ID_OB) {
1635                         if(itA->node->lasttime!=curtime) {
1636                                 itA->lay= flush_layer_node(itA->node, curtime);  // lay is only set once for each relation
1637                                 //printf("layer %d for relation %s to %s\n", itA->lay, ((Object *)node->ob)->id.name, ((Object *)itA->node->ob)->id.name);
1638                         }
1639                         else itA->lay= itA->node->lay;
1640                         
1641                         node->lay |= itA->lay;
1642                 }
1643         }
1644
1645         return node->lay;
1646 }
1647
1648 /* flushes all recalc flags in objects down the dependency tree */
1649 void DAG_scene_flush_update(Scene *sce, unsigned int lay)
1650 {
1651         DagNode *firstnode;
1652         DagAdjList *itA;
1653         int lasttime;
1654         
1655         if(sce->theDag==NULL) {
1656                 printf("DAG zero... not allowed to happen!\n");
1657                 DAG_scene_sort(sce);
1658         }
1659         
1660         firstnode= sce->theDag->DagNode.first;  // always scene node
1661         
1662         /* first we flush the layer flags */
1663         sce->theDag->time++;    // so we know which nodes were accessed
1664         lasttime= sce->theDag->time;
1665         for(itA = firstnode->child; itA; itA= itA->next) {
1666                 if(itA->node->lasttime!=lasttime && itA->node->type==ID_OB) 
1667                         flush_layer_node(itA->node, lasttime);
1668         }
1669         
1670         /* then we use the relationships + layer info to flush update events */
1671         sce->theDag->time++;    // so we know which nodes were accessed
1672         lasttime= sce->theDag->time;
1673         for(itA = firstnode->child; itA; itA= itA->next) {
1674                 if(itA->node->lasttime!=lasttime && itA->node->type==ID_OB) 
1675                         flush_update_node(itA->node, lay, lasttime);
1676         }
1677 }
1678
1679 static int object_modifiers_use_time(Object *ob)
1680 {
1681         ModifierData *md;
1682
1683         for (md=ob->modifiers.first; md; md=md->next)
1684                 if (modifier_dependsOnTime(md))
1685                         return 1;
1686
1687         return 0;
1688 }
1689
1690 static int exists_channel(Object *ob, char *name)
1691 {
1692         bActionStrip *strip;
1693         
1694         if(ob->action)
1695                 if(get_action_channel(ob->action, name))
1696                         return 1;
1697         
1698         for (strip=ob->nlastrips.first; strip; strip=strip->next)
1699                 if(get_action_channel(strip->act, name))
1700                         return 1;
1701         return 0;
1702 }
1703
1704 static void dag_object_time_update_flags(Object *ob)
1705 {
1706         
1707         if(ob->ipo) ob->recalc |= OB_RECALC_OB;
1708         else if(ob->constraints.first) {
1709                 bConstraint *con;
1710                 for (con = ob->constraints.first; con; con=con->next){
1711                         if (constraint_has_target(con)) {
1712                                 ob->recalc |= OB_RECALC_OB;
1713                                 break;
1714                         }
1715                 }
1716         }
1717         else if(ob->scriptlink.totscript) ob->recalc |= OB_RECALC_OB;
1718         else if(ob->parent) {
1719                 /* motion path or bone child */
1720                 if(ob->parent->type==OB_CURVE || ob->parent->type==OB_ARMATURE) ob->recalc |= OB_RECALC_OB;
1721         }
1722         
1723         if(ob->action || ob->nlastrips.first) {
1724                 /* since actions now are mixed, we set the recalcs on the safe side */
1725                 ob->recalc |= OB_RECALC_OB;
1726                 if(ob->type==OB_ARMATURE)
1727                         ob->recalc |= OB_RECALC_DATA;
1728                 else if(exists_channel(ob, "Shape"))
1729                         ob->recalc |= OB_RECALC_DATA;
1730                 else if(ob->dup_group) {
1731                         bActionStrip *strip;
1732                         /* this case is for groups with nla, whilst nla target has no action or nla */
1733                         for(strip= ob->nlastrips.first; strip; strip= strip->next) {
1734                                 if(strip->object)
1735                                         strip->object->recalc |= OB_RECALC;
1736                         }
1737                 }
1738         }
1739         else if(modifiers_isSoftbodyEnabled(ob)) ob->recalc |= OB_RECALC_DATA;
1740         else if(object_modifiers_use_time(ob)) ob->recalc |= OB_RECALC_DATA;
1741         else {
1742                 Mesh *me;
1743                 Curve *cu;
1744                 Lattice *lt;
1745                 
1746                 switch(ob->type) {
1747                         case OB_MESH:
1748                                 me= ob->data;
1749                                 if(me->key) {
1750                                         if(!(ob->shapeflag & OB_SHAPE_LOCK)) {
1751                                                 ob->recalc |= OB_RECALC_DATA;
1752                                                 ob->shapeflag &= ~OB_SHAPE_TEMPLOCK;
1753                                         }
1754                                 }
1755                                 else if(ob->effect.first) {
1756                                         Effect *eff= ob->effect.first;
1757                                         PartEff *paf= give_parteff(ob);
1758                                         
1759                                         if(eff->type==EFF_WAVE) 
1760                                                 ob->recalc |= OB_RECALC_DATA;
1761                                         else if(paf && paf->keys==NULL)
1762                                                 ob->recalc |= OB_RECALC_DATA;
1763                                 }
1764                                 if((ob->fluidsimFlag & OB_FLUIDSIM_ENABLE) && (ob->fluidsimSettings)) {
1765                                         // fluidsimSettings might not be initialized during load...
1766                                         if(ob->fluidsimSettings->type & (OB_FLUIDSIM_DOMAIN|OB_FLUIDSIM_PARTICLE)) {
1767                                                 ob->recalc |= OB_RECALC_DATA; // NT FSPARTICLE
1768                                         }
1769                                 }
1770                                 break;
1771                         case OB_CURVE:
1772                         case OB_SURF:
1773                                 cu= ob->data;
1774                                 if(cu->key) {
1775                                         if(!(ob->shapeflag & OB_SHAPE_LOCK)) {
1776                                                 ob->recalc |= OB_RECALC_DATA;
1777                                                 ob->shapeflag &= ~OB_SHAPE_TEMPLOCK;
1778                                         }
1779                                 }
1780                                 break;
1781                         case OB_FONT:
1782                                 cu= ob->data;
1783                                 if(cu->nurb.first==NULL && cu->str && cu->vfont)
1784                                         ob->recalc |= OB_RECALC_DATA;
1785                                 break;
1786                         case OB_LATTICE:
1787                                 lt= ob->data;
1788                                 if(lt->key) {
1789                                         if(!(ob->shapeflag & OB_SHAPE_LOCK)) {
1790                                                 ob->recalc |= OB_RECALC_DATA;
1791                                                 ob->shapeflag &= ~OB_SHAPE_TEMPLOCK;
1792                                         }
1793                                 }
1794                                         break;
1795                         case OB_MBALL:
1796                                 if(ob->transflag & OB_DUPLI) ob->recalc |= OB_RECALC_DATA;
1797                                 break;
1798                 }
1799         }               
1800 }
1801
1802 /* flag all objects that need recalc, for changes in time for example */
1803 void DAG_scene_update_flags(Scene *scene, unsigned int lay)
1804 {
1805         Base *base;
1806         Object *ob;
1807         Group *group;
1808         GroupObject *go;
1809         Scene *sce;
1810         
1811         /* set ob flags where animated systems are */
1812         for(SETLOOPER(scene, base)) {
1813                 ob= base->object;
1814                 
1815                 /* now if DagNode were part of base, the node->lay could be checked... */
1816                 /* we do all now, since the scene_flush checks layers and clears recalc flags even */
1817                 dag_object_time_update_flags(ob);
1818                 
1819                 /* handled in next loop */
1820                 if(ob->dup_group) 
1821                         ob->dup_group->id.flag |= LIB_DOIT;
1822         }       
1823         
1824         /* we do groups each once */
1825         for(group= G.main->group.first; group; group= group->id.next) {
1826                 if(group->id.flag & LIB_DOIT) {
1827                         for(go= group->gobject.first; go; go= go->next) {
1828                                 dag_object_time_update_flags(go->ob);
1829                         }
1830                 }
1831         }
1832         
1833         for(sce= scene; sce; sce= sce->set)
1834                 DAG_scene_flush_update(sce, lay);
1835         
1836         /* test: set time flag, to disable baked systems to update */
1837         for(SETLOOPER(scene, base)) {
1838                 ob= base->object;
1839                 if(ob->recalc)
1840                         ob->recalc |= OB_RECALC_TIME;
1841         }
1842         
1843         /* hrmf... an exception to look at once, for invisible camera object we do it over */
1844         if(scene->camera)
1845                 dag_object_time_update_flags(scene->camera);
1846         
1847         /* and store the info in groupobject */
1848         for(group= G.main->group.first; group; group= group->id.next) {
1849                 if(group->id.flag & LIB_DOIT) {
1850                         for(go= group->gobject.first; go; go= go->next) {
1851                                 go->recalc= go->ob->recalc;
1852                                 // printf("ob %s recalc %d\n", go->ob->id.name, go->recalc);
1853                         }
1854                         group->id.flag &= ~LIB_DOIT;
1855                 }
1856         }
1857         
1858 }
1859
1860 /* for depgraph updating, all layers visible in a screen */
1861 /* this is a copy from editscreen.c... I need to think over a more proper solution for this */
1862 /* probably the DAG_object_flush_update() should give layer too? */
1863 /* or some kind of dag context... (DAG_set_layer) */
1864 static unsigned int dag_screen_view3d_layers(void)
1865 {
1866         ScrArea *sa;
1867         int layer= 0;
1868         
1869         for(sa= G.curscreen->areabase.first; sa; sa= sa->next) {
1870                 if(sa->spacetype==SPACE_VIEW3D)
1871                         layer |= ((View3D *)sa->spacedata.first)->lay;
1872         }
1873         return layer;
1874 }
1875
1876
1877 /* flag this object and all its relations to recalc */
1878 /* if you need to do more objects, tag object yourself and
1879    use DAG_scene_flush_update() in end */
1880 void DAG_object_flush_update(Scene *sce, Object *ob, short flag)
1881 {
1882         
1883         if(ob==NULL || sce->theDag==NULL) return;
1884         ob->recalc |= flag;
1885         
1886         /* all users of this ob->data should be checked */
1887         /* BUT! displists for curves are still only on cu */
1888         if(flag & OB_RECALC_DATA) {
1889                 if(ob->type!=OB_CURVE && ob->type!=OB_SURF) {
1890                         ID *id= ob->data;
1891                         if(id && id->us>1) {
1892                                 /* except when there's a key and shapes are locked */
1893                                 if(ob_get_key(ob) && (ob->shapeflag & (OB_SHAPE_LOCK|OB_SHAPE_TEMPLOCK)));
1894                                 else {
1895                                         Object *obt;
1896                                         for (obt=G.main->object.first; obt; obt= obt->id.next) {
1897                                                 if (obt->data==ob->data) {
1898                                                         obt->recalc |= OB_RECALC_DATA;
1899                                                 }
1900                                         }
1901                                 }
1902                         }
1903                 }
1904         }
1905         
1906         if(G.curscreen)
1907                 DAG_scene_flush_update(sce, dag_screen_view3d_layers());
1908         else
1909                 DAG_scene_flush_update(sce, sce->lay);
1910 }
1911
1912 /* recursively descends tree, each node only checked once */
1913 /* node is checked to be of type object */
1914 static int parent_check_node(DagNode *node, int curtime)
1915 {
1916         DagAdjList *itA;
1917         
1918         node->lasttime= curtime;
1919         
1920         if(node->color==DAG_GRAY)
1921                 return DAG_GRAY;
1922         
1923         for(itA = node->child; itA; itA= itA->next) {
1924                 if(itA->node->type==ID_OB) {
1925                         
1926                         if(itA->node->color==DAG_GRAY)
1927                                 return DAG_GRAY;
1928
1929                         /* descend if not done */
1930                         if(itA->node->lasttime!=curtime) {
1931                                 itA->node->color= parent_check_node(itA->node, curtime);
1932                         
1933                                 if(itA->node->color==DAG_GRAY)
1934                                         return DAG_GRAY;
1935                         }
1936                 }
1937         }
1938         
1939         return DAG_WHITE;
1940 }
1941
1942 /* all nodes that influence this object get tagged, for calculating the exact
1943    position of this object at a given timeframe */
1944 void DAG_object_update_flags(Scene *sce, Object *ob, unsigned int lay)
1945 {
1946         DagNode *node;
1947         DagAdjList *itA;
1948         
1949         /* tag nodes unchecked */
1950         for(node = sce->theDag->DagNode.first; node; node= node->next) 
1951                 node->color = DAG_WHITE;
1952         
1953         node= dag_find_node(sce->theDag, ob);
1954         
1955         /* object not in scene? then handle group exception. needs to be dagged once too */
1956         if(node==NULL) {
1957                 Group *group= find_group(ob);
1958                 if(group) {
1959                         GroupObject *go;
1960                         /* primitive; tag all... this call helps building groups for particles */
1961                         for(go= group->gobject.first; go; go= go->next)
1962                                 go->ob->recalc= OB_RECALC;
1963                 }
1964         }
1965         else {
1966                 
1967                 node->color = DAG_GRAY;
1968                 
1969                 sce->theDag->time++;
1970                 node= sce->theDag->DagNode.first;
1971                 for(itA = node->child; itA; itA= itA->next) {
1972                         if(itA->node->type==ID_OB && itA->node->lasttime!=sce->theDag->time)
1973                                 itA->node->color= parent_check_node(itA->node, sce->theDag->time);
1974                 }
1975                 
1976                 /* set recalcs and flushes */
1977                 DAG_scene_update_flags(sce, lay);
1978                 
1979                 /* now we clear recalcs, unless color is set */
1980                 for(node = sce->theDag->DagNode.first; node; node= node->next) {
1981                         if(node->type==ID_OB && node->color==DAG_WHITE) {
1982                                 Object *ob= node->ob;
1983                                 ob->recalc= 0;
1984                         }
1985                 }
1986         }
1987 }
1988
1989 /* ******************* DAG FOR ARMATURE POSE ***************** */
1990
1991 static int node_recurs_level(DagNode *node, int level)
1992 {
1993         DagAdjList *itA;
1994         
1995         node->color= DAG_BLACK; /* done */
1996         level++;
1997         
1998         for(itA= node->parent; itA; itA= itA->next) {
1999                 if(itA->node->color==DAG_WHITE)
2000                         itA->node->ancestor_count= node_recurs_level(itA->node, level);
2001         }
2002         
2003         return level;
2004 }
2005
2006 static void pose_check_cycle(DagForest *dag)
2007 {
2008         DagNode *node;
2009         DagAdjList *itA;
2010
2011         /* tag nodes unchecked */
2012         for(node = dag->DagNode.first; node; node= node->next)
2013                 node->color= DAG_WHITE;
2014         
2015         for(node = dag->DagNode.first; node; node= node->next) {
2016                 if(node->color==DAG_WHITE) {
2017                         node->ancestor_count= node_recurs_level(node, 0);
2018                 }
2019         }
2020         
2021         /* check relations, and print errors */
2022         for(node = dag->DagNode.first; node; node= node->next) {
2023                 for(itA= node->parent; itA; itA= itA->next) {
2024                         if(itA->node->ancestor_count > node->ancestor_count) {
2025                                 bPoseChannel *pchan= (bPoseChannel *)node->ob;
2026                                 bPoseChannel *parchan= (bPoseChannel *)itA->node->ob;
2027                                 
2028                                 if(pchan && parchan) 
2029                                         if(pchan->parent!=parchan)
2030                                                 printf("Cycle in %s to %s\n", pchan->name, parchan->name);
2031                         }
2032                 }
2033         }
2034 }
2035
2036 /* we assume its an armature with pose */
2037 void DAG_pose_sort(Object *ob)
2038 {
2039         bPose *pose= ob->pose;
2040         bPoseChannel *pchan;
2041         bConstraint *con;
2042         DagNode *node;
2043         DagNode *node2, *node3;
2044         DagNode *rootnode;
2045         DagForest *dag;
2046         DagNodeQueue *nqueue;
2047         DagAdjList *itA;
2048         ListBase tempbase;
2049         int skip = 0;
2050         
2051         dag = dag_init();
2052         ugly_hack_sorry= 0;     // no ID structs
2053
2054         rootnode = dag_add_node(dag, NULL);     // node->ob becomes NULL
2055         
2056         /* we add the hierarchy and the constraints */
2057         for(pchan = pose->chanbase.first; pchan; pchan= pchan->next) {
2058                 int addtoroot = 1;
2059                 
2060                 node = dag_get_node(dag, pchan);
2061                 
2062                 if(pchan->parent) {
2063                         node2 = dag_get_node(dag, pchan->parent);
2064                         dag_add_relation(dag, node2, node, 0);
2065                         dag_add_parent_relation(dag, node2, node, 0);
2066                         addtoroot = 0;
2067                 }
2068                 for (con = pchan->constraints.first; con; con=con->next){
2069                         if (constraint_has_target(con)) {
2070                                 char *subtarget;
2071                                 Object *target = get_constraint_target(con, &subtarget);
2072                                 
2073                                 if (target==ob && subtarget) {
2074                                         bPoseChannel *target= get_pose_channel(ob->pose, subtarget);
2075                                         if(target) {
2076                                                 node2= dag_get_node(dag, target);
2077                                                 dag_add_relation(dag, node2, node, 0);
2078                                                 dag_add_parent_relation(dag, node2, node, 0);
2079                                                 
2080                                                 if(con->type==CONSTRAINT_TYPE_KINEMATIC) {
2081                                                         bKinematicConstraint *data = (bKinematicConstraint*)con->data;
2082                                                         bPoseChannel *parchan;
2083                                                         int segcount= 0;
2084                                                         
2085                                                         /* exclude tip from chain? */
2086                                                         if(!(data->flag & CONSTRAINT_IK_TIP))
2087                                                                 parchan= pchan->parent;
2088                                                         else
2089                                                                 parchan= pchan;
2090                                                         
2091                                                         /* Walk to the chain's root */
2092                                                         while (parchan){
2093                                                                 node3= dag_get_node(dag, parchan);
2094                                                                 dag_add_relation(dag, node2, node3, 0);
2095                                                                 dag_add_parent_relation(dag, node2, node3, 0);
2096                                                                 
2097                                                                 segcount++;
2098                                                                 if(segcount==data->rootbone || segcount>255) break; // 255 is weak
2099                                                                 parchan= parchan->parent;
2100                                                         }
2101                                                 }
2102                                         }
2103                                 }
2104                         }
2105                 }
2106                 if (addtoroot == 1 ) {
2107                         dag_add_relation(dag, rootnode, node, 0);
2108                         dag_add_parent_relation(dag, rootnode, node, 0);
2109                 }
2110         }
2111
2112         pose_check_cycle(dag);
2113         
2114         /* now we try to sort... */
2115         tempbase.first= tempbase.last= NULL;
2116
2117         nqueue = queue_create(DAGQUEUEALLOC);
2118         
2119         /* tag nodes unchecked */
2120         for(node = dag->DagNode.first; node; node= node->next) 
2121                 node->color = DAG_WHITE;
2122         
2123         node = dag->DagNode.first;
2124         
2125         node->color = DAG_GRAY;
2126         push_stack(nqueue, node);  
2127         
2128         while(nqueue->count) {
2129                 
2130                 skip = 0;
2131                 node = get_top_node_queue(nqueue);
2132                 
2133                 itA = node->child;
2134                 while(itA != NULL) {
2135                         if((itA->node->color == DAG_WHITE) ) {
2136                                 itA->node->color = DAG_GRAY;
2137                                 push_stack(nqueue,itA->node);
2138                                 skip = 1;
2139                                 break;
2140                         } 
2141                         itA = itA->next;
2142                 }                       
2143                 
2144                 if (!skip) {
2145                         if (node) {
2146                                 node = pop_queue(nqueue);
2147                                 if (node->ob == NULL)   // we are done
2148                                         break ;
2149                                 node->color = DAG_BLACK;
2150                                 
2151                                 /* put node in new list */
2152                                 BLI_remlink(&pose->chanbase, node->ob);
2153                                 BLI_addhead(&tempbase, node->ob);
2154                         }       
2155                 }
2156         }
2157         
2158         // temporal correction for circular dependancies
2159         while(pose->chanbase.first) {
2160                 pchan= pose->chanbase.first;
2161                 BLI_remlink(&pose->chanbase, pchan);
2162                 BLI_addhead(&tempbase, pchan);
2163
2164                 printf("cyclic %s\n", pchan->name);
2165         }
2166         
2167         pose->chanbase = tempbase;
2168         queue_delete(nqueue);
2169         
2170 //      printf("\nordered\n");
2171 //      for(pchan = pose->chanbase.first; pchan; pchan= pchan->next) {
2172 //              printf(" %s\n", pchan->name);
2173 //      }
2174         
2175         free_forest( dag );
2176         MEM_freeN( dag );
2177         
2178         ugly_hack_sorry= 1;
2179 }
2180
2181
2182