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