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