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