2206770dfbd7b064bf54aac0d46f211c9f62e398
[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                 }
562                 /* exception case: parent is duplivert */
563                 if (ob->type == OB_MBALL && (ob->parent->transflag & OB_DUPLIVERTS)) {
564                         dag_add_relation(dag, node2, node, DAG_RL_DATA_DATA | DAG_RL_OB_OB, "Duplivert");
565                 }
566                 
567                 addtoroot = 0;
568         }
569         if (ob->proxy) {
570                 node2 = dag_get_node(dag, ob->proxy);
571                 dag_add_relation(dag, node, node2, DAG_RL_DATA_DATA | DAG_RL_OB_OB, "Proxy");
572                 /* inverted relation, so addtoroot shouldn't be set to zero */
573         }
574         
575         if (ob->transflag & OB_DUPLI) {
576                 if ((ob->transflag & OB_DUPLIGROUP) && ob->dup_group) {
577                         GroupObject *go;
578                         for (go = ob->dup_group->gobject.first; go; go = go->next) {
579                                 if (go->ob) {
580                                         node2 = dag_get_node(dag, go->ob);
581                                         /* node2 changes node1, this keeps animations updated in groups?? not logical? */
582                                         dag_add_relation(dag, node2, node, DAG_RL_OB_OB, "Dupligroup");
583                                 }
584                         }
585                 }
586         }
587
588         /* softbody collision  */
589         if ((ob->type == OB_MESH) || (ob->type == OB_CURVE) || (ob->type == OB_LATTICE)) {
590                 if (ob->particlesystem.first ||
591                     modifiers_isModifierEnabled(ob, eModifierType_Softbody) ||
592                     modifiers_isModifierEnabled(ob, eModifierType_Cloth) ||
593                     modifiers_isModifierEnabled(ob, eModifierType_DynamicPaint))
594                 {
595                         dag_add_collision_field_relation(dag, scene, ob, node, 0, false);  /* TODO: use effectorweight->group */
596                 }
597                 else if (modifiers_isModifierEnabled(ob, eModifierType_Smoke)) {
598                         dag_add_collision_field_relation(dag, scene, ob, node, PFIELD_SMOKEFLOW, false);
599                 }
600                 else if (ob->rigidbody_object) {
601                         dag_add_collision_field_relation(dag, scene, ob, node, 0, true);
602                 }
603         }
604         
605         /* object data drivers */
606         if (ob->data) {
607                 AnimData *adt = BKE_animdata_from_id((ID *)ob->data);
608                 if (adt)
609                         dag_add_driver_relation(adt, dag, node, 1);
610         }
611         
612         /* object type/data relationships */
613         switch (ob->type) {
614                 case OB_CAMERA:
615                 {
616                         Camera *cam = (Camera *)ob->data;
617                         
618                         if (cam->dof_ob) {
619                                 node2 = dag_get_node(dag, cam->dof_ob);
620                                 dag_add_relation(dag, node2, node, DAG_RL_OB_OB, "Camera DoF");
621                         }
622                 }
623                 break;
624                 case OB_MBALL: 
625                 {
626                         Object *mom = BKE_mball_basis_find(scene, ob);
627                         
628                         if (mom != ob) {
629                                 node2 = dag_get_node(dag, mom);
630                                 dag_add_relation(dag, node, node2, DAG_RL_DATA_DATA | DAG_RL_OB_DATA, "Metaball");  /* mom depends on children! */
631                         }
632                 }
633                 break;
634                 case OB_CURVE:
635                 case OB_FONT:
636                 {
637                         Curve *cu = ob->data;
638                         
639                         if (cu->bevobj) {
640                                 node2 = dag_get_node(dag, cu->bevobj);
641                                 dag_add_relation(dag, node2, node, DAG_RL_DATA_DATA | DAG_RL_OB_DATA, "Curve Bevel");
642                         }
643                         if (cu->taperobj) {
644                                 node2 = dag_get_node(dag, cu->taperobj);
645                                 dag_add_relation(dag, node2, node, DAG_RL_DATA_DATA | DAG_RL_OB_DATA, "Curve Taper");
646                         }
647                         if (ob->type == OB_FONT) {
648                                 if (cu->textoncurve) {
649                                         node2 = dag_get_node(dag, cu->textoncurve);
650                                         dag_add_relation(dag, node2, node, DAG_RL_DATA_DATA | DAG_RL_OB_DATA, "Texture On Curve");
651                                 }
652                         }
653                 }
654                 break;
655         }
656         
657         /* material drivers */
658         if (ob->totcol) {
659                 int a;
660                 
661                 for (a = 1; a <= ob->totcol; a++) {
662                         Material *ma = give_current_material(ob, a);
663                         
664                         if (ma) {
665                                 /* recursively figure out if there are drivers, and hook these up to this object */
666                                 dag_add_material_driver_relations(dag, node, ma);
667                         }
668                 }
669         }
670         else if (ob->type == OB_LAMP) {
671                 dag_add_lamp_driver_relations(dag, node, ob->data);
672         }
673         
674         /* particles */
675         psys = ob->particlesystem.first;
676         if (psys) {
677                 GroupObject *go;
678
679                 for (; psys; psys = psys->next) {
680                         BoidRule *rule = NULL;
681                         BoidState *state = NULL;
682                         ParticleSettings *part = psys->part;
683                         ListBase *effectors = NULL;
684                         EffectorCache *eff;
685
686                         dag_add_relation(dag, node, node, DAG_RL_OB_DATA, "Particle-Object Relation");
687
688                         if (!psys_check_enabled(ob, psys))
689                                 continue;
690
691                         if (ELEM(part->phystype, PART_PHYS_KEYED, PART_PHYS_BOIDS)) {
692                                 ParticleTarget *pt = psys->targets.first;
693
694                                 for (; pt; pt = pt->next) {
695                                         if (pt->ob && BLI_findlink(&pt->ob->particlesystem, pt->psys - 1)) {
696                                                 node2 = dag_get_node(dag, pt->ob);
697                                                 dag_add_relation(dag, node2, node, DAG_RL_DATA_DATA | DAG_RL_OB_DATA, "Particle Targets");
698                                         }
699                                 }
700                         }
701
702                         if (part->ren_as == PART_DRAW_OB && part->dup_ob) {
703                                 node2 = dag_get_node(dag, part->dup_ob);
704                                 /* note that this relation actually runs in the wrong direction, the problem
705                                  * is that dupli system all have this (due to parenting), and the render
706                                  * engine instancing assumes particular ordering of objects in list */
707                                 dag_add_relation(dag, node, node2, DAG_RL_OB_OB, "Particle Object Visualization");
708                                 if (part->dup_ob->type == OB_MBALL)
709                                         dag_add_relation(dag, node, node2, DAG_RL_DATA_DATA, "Particle Object Visualization");
710                         }
711
712                         if (part->ren_as == PART_DRAW_GR && part->dup_group) {
713                                 for (go = part->dup_group->gobject.first; go; go = go->next) {
714                                         node2 = dag_get_node(dag, go->ob);
715                                         dag_add_relation(dag, node2, node, DAG_RL_OB_OB, "Particle Group Visualization");
716                                 }
717                         }
718
719                         effectors = pdInitEffectors(scene, ob, psys, part->effector_weights);
720
721                         if (effectors) {
722                                 for (eff = effectors->first; eff; eff = eff->next) {
723                                         if (eff->psys) {
724                                                 node2 = dag_get_node(dag, eff->ob);
725                                                 dag_add_relation(dag, node2, node, DAG_RL_DATA_DATA | DAG_RL_OB_DATA, "Particle Field");
726                                         }
727                                 }
728                         }
729
730                         pdEndEffectors(&effectors);
731
732                         if (part->boids) {
733                                 for (state = part->boids->states.first; state; state = state->next) {
734                                         for (rule = state->rules.first; rule; rule = rule->next) {
735                                                 Object *ruleob = NULL;
736                                                 if (rule->type == eBoidRuleType_Avoid)
737                                                         ruleob = ((BoidRuleGoalAvoid *)rule)->ob;
738                                                 else if (rule->type == eBoidRuleType_FollowLeader)
739                                                         ruleob = ((BoidRuleFollowLeader *)rule)->ob;
740
741                                                 if (ruleob) {
742                                                         node2 = dag_get_node(dag, ruleob);
743                                                         dag_add_relation(dag, node2, node, DAG_RL_OB_DATA, "Boid Rule");
744                                                 }
745                                         }
746                                 }
747                         }
748                 }
749         }
750         
751         /* object constraints */
752         for (con = ob->constraints.first; con; con = con->next) {
753                 bConstraintTypeInfo *cti = BKE_constraint_get_typeinfo(con);
754                 ListBase targets = {NULL, NULL};
755                 bConstraintTarget *ct;
756                 
757                 if (!cti)
758                         continue;
759
760                 /* special case for camera tracking -- it doesn't use targets to define relations */
761                 if (ELEM3(cti->type, CONSTRAINT_TYPE_FOLLOWTRACK, CONSTRAINT_TYPE_CAMERASOLVER, CONSTRAINT_TYPE_OBJECTSOLVER)) {
762                         int depends_on_camera = 0;
763
764                         if (cti->type == CONSTRAINT_TYPE_FOLLOWTRACK) {
765                                 bFollowTrackConstraint *data = (bFollowTrackConstraint *)con->data;
766
767                                 if ((data->clip || data->flag & FOLLOWTRACK_ACTIVECLIP) && data->track[0])
768                                         depends_on_camera = 1;
769
770                                 if (data->depth_ob) {
771                                         node2 = dag_get_node(dag, data->depth_ob);
772                                         dag_add_relation(dag, node2, node, DAG_RL_DATA_OB | DAG_RL_OB_OB, cti->name);
773                                 }
774                         }
775                         else if (cti->type == CONSTRAINT_TYPE_OBJECTSOLVER)
776                                 depends_on_camera = 1;
777
778                         if (depends_on_camera && scene->camera) {
779                                 node2 = dag_get_node(dag, scene->camera);
780                                 dag_add_relation(dag, node2, node, DAG_RL_DATA_OB | DAG_RL_OB_OB, cti->name);
781                         }
782
783                         dag_add_relation(dag, scenenode, node, DAG_RL_SCENE, "Scene Relation");
784                         addtoroot = 0;
785                 }
786                 else if (cti->get_constraint_targets) {
787                         cti->get_constraint_targets(con, &targets);
788                         
789                         for (ct = targets.first; ct; ct = ct->next) {
790                                 Object *obt;
791                                 
792                                 if (ct->tar)
793                                         obt = ct->tar;
794                                 else
795                                         continue;
796                                 
797                                 node2 = dag_get_node(dag, obt);
798                                 if (ELEM(con->type, CONSTRAINT_TYPE_FOLLOWPATH, CONSTRAINT_TYPE_CLAMPTO))
799                                         dag_add_relation(dag, node2, node, DAG_RL_DATA_OB | DAG_RL_OB_OB, cti->name);
800                                 else {
801                                         if (ELEM3(obt->type, OB_ARMATURE, OB_MESH, OB_LATTICE) && (ct->subtarget[0])) {
802                                                 dag_add_relation(dag, node2, node, DAG_RL_DATA_OB | DAG_RL_OB_OB, cti->name);
803                                                 if (obt->type == OB_MESH)
804                                                         node2->customdata_mask |= CD_MASK_MDEFORMVERT;
805                                         }
806                                         else
807                                                 dag_add_relation(dag, node2, node, DAG_RL_OB_OB, cti->name);
808                                 }
809                                 addtoroot = 0;
810                         }
811                         
812                         if (cti->flush_constraint_targets)
813                                 cti->flush_constraint_targets(con, &targets, 1);
814                 }
815         }
816
817         if (addtoroot == 1)
818                 dag_add_relation(dag, scenenode, node, DAG_RL_SCENE, "Scene Relation");
819 }
820
821 DagForest *build_dag(Main *bmain, Scene *sce, short mask)
822 {
823         Base *base;
824         Object *ob;
825         Group *group;
826         GroupObject *go;
827         DagNode *node;
828         DagNode *scenenode;
829         DagForest *dag;
830         DagAdjList *itA;
831
832         dag = sce->theDag;
833         if (dag)
834                 free_forest(dag);
835         else {
836                 dag = dag_init();
837                 sce->theDag = dag;
838         }
839         
840         /* clear "LIB_DOIT" flag from all materials, to prevent infinite recursion problems later [#32017] */
841         tag_main_idcode(bmain, ID_MA, FALSE);
842         tag_main_idcode(bmain, ID_LA, FALSE);
843         
844         /* add base node for scene. scene is always the first node in DAG */
845         scenenode = dag_add_node(dag, sce);
846         
847         /* add current scene objects */
848         for (base = sce->base.first; base; base = base->next) {
849                 ob = base->object;
850                 
851                 build_dag_object(dag, scenenode, sce, ob, mask);
852                 if (ob->proxy)
853                         build_dag_object(dag, scenenode, sce, ob->proxy, mask);
854                 
855                 /* handled in next loop */
856                 if (ob->dup_group) 
857                         ob->dup_group->id.flag |= LIB_DOIT;
858         }
859         
860         /* add groups used in current scene objects */
861         for (group = bmain->group.first; group; group = group->id.next) {
862                 if (group->id.flag & LIB_DOIT) {
863                         for (go = group->gobject.first; go; go = go->next) {
864                                 build_dag_object(dag, scenenode, sce, go->ob, mask);
865                         }
866                         group->id.flag &= ~LIB_DOIT;
867                 }
868         }
869         
870         /* Now all relations were built, but we need to solve 1 exceptional case;
871          * When objects have multiple "parents" (for example parent + constraint working on same object)
872          * the relation type has to be synced. One of the parents can change, and should give same event to child */
873         
874         /* nodes were callocced, so we can use node->color for temporal storage */
875         for (node = sce->theDag->DagNode.first; node; node = node->next) {
876                 if (node->type == ID_OB) {
877                         for (itA = node->child; itA; itA = itA->next) {
878                                 if (itA->node->type == ID_OB) {
879                                         itA->node->color |= itA->type;
880                                 }
881                         }
882
883                         /* also flush custom data mask */
884                         ((Object *)node->ob)->customdata_mask = node->customdata_mask;
885                 }
886         }
887         /* now set relations equal, so that when only one parent changes, the correct recalcs are found */
888         for (node = sce->theDag->DagNode.first; node; node = node->next) {
889                 if (node->type == ID_OB) {
890                         for (itA = node->child; itA; itA = itA->next) {
891                                 if (itA->node->type == ID_OB) {
892                                         itA->type |= itA->node->color;
893                                 }
894                         }
895                 }
896         }
897         
898         /* cycle detection and solving */
899         // solve_cycles(dag);
900         
901         return dag;
902 }
903
904
905 void free_forest(DagForest *Dag) 
906 {  /* remove all nodes and deps */
907         DagNode *tempN;
908         DagAdjList *tempA;
909         DagAdjList *itA;
910         DagNode *itN = Dag->DagNode.first;
911         
912         while (itN) {
913                 itA = itN->child;
914                 while (itA) {
915                         tempA = itA;
916                         itA = itA->next;
917                         MEM_freeN(tempA);
918                 }
919                 
920                 itA = itN->parent;
921                 while (itA) {
922                         tempA = itA;
923                         itA = itA->next;
924                         MEM_freeN(tempA);
925                 }
926                 
927                 tempN = itN;
928                 itN = itN->next;
929                 MEM_freeN(tempN);
930         }
931
932         BLI_ghash_free(Dag->nodeHash, NULL, NULL);
933         Dag->nodeHash = NULL;
934         Dag->DagNode.first = NULL;
935         Dag->DagNode.last = NULL;
936         Dag->numNodes = 0;
937
938 }
939
940 DagNode *dag_find_node(DagForest *forest, void *fob)
941 {
942         if (forest->nodeHash)
943                 return BLI_ghash_lookup(forest->nodeHash, fob);
944
945         return NULL;
946 }
947
948 static int ugly_hack_sorry = 1;         /* prevent type check */
949 static int dag_print_dependencies = 0;  /* debugging */
950
951 /* no checking of existence, use dag_find_node first or dag_get_node */
952 DagNode *dag_add_node(DagForest *forest, void *fob)
953 {
954         DagNode *node;
955                 
956         node = MEM_callocN(sizeof(DagNode), "DAG node");
957         if (node) {
958                 node->ob = fob;
959                 node->color = DAG_WHITE;
960
961                 if (ugly_hack_sorry) node->type = GS(((ID *) fob)->name);  /* sorry, done for pose sorting */
962                 if (forest->numNodes) {
963                         ((DagNode *) forest->DagNode.last)->next = node;
964                         forest->DagNode.last = node;
965                         forest->numNodes++;
966                 }
967                 else {
968                         forest->DagNode.last = node;
969                         forest->DagNode.first = node;
970                         forest->numNodes = 1;
971                 }
972
973                 if (!forest->nodeHash)
974                         forest->nodeHash = BLI_ghash_ptr_new("dag_add_node gh");
975                 BLI_ghash_insert(forest->nodeHash, fob, node);
976         }
977
978         return node;
979 }
980
981 DagNode *dag_get_node(DagForest *forest, void *fob)
982 {
983         DagNode *node;
984         
985         node = dag_find_node(forest, fob);
986         if (!node) 
987                 node = dag_add_node(forest, fob);
988         return node;
989 }
990
991
992
993 DagNode *dag_get_sub_node(DagForest *forest, void *fob)
994 {
995         DagNode *node;
996         DagAdjList *mainchild, *prev = NULL;
997         
998         mainchild = ((DagNode *) forest->DagNode.first)->child;
999         /* remove from first node (scene) adj list if present */
1000         while (mainchild) {
1001                 if (mainchild->node == fob) {
1002                         if (prev) {
1003                                 prev->next = mainchild->next;
1004                                 MEM_freeN(mainchild);
1005                                 break;
1006                         }
1007                         else {
1008                                 ((DagNode *) forest->DagNode.first)->child = mainchild->next;
1009                                 MEM_freeN(mainchild);
1010                                 break;
1011                         }
1012                 }
1013                 prev = mainchild;
1014                 mainchild = mainchild->next;
1015         }
1016         node = dag_find_node(forest, fob);
1017         if (!node) 
1018                 node = dag_add_node(forest, fob);
1019         return node;
1020 }
1021
1022 static void dag_add_parent_relation(DagForest *UNUSED(forest), DagNode *fob1, DagNode *fob2, short rel, const char *name) 
1023 {
1024         DagAdjList *itA = fob2->parent;
1025         
1026         while (itA) { /* search if relation exist already */
1027                 if (itA->node == fob1) {
1028                         itA->type |= rel;
1029                         itA->count += 1;
1030                         return;
1031                 }
1032                 itA = itA->next;
1033         }
1034         /* create new relation and insert at head. MALLOC alert! */
1035         itA = MEM_mallocN(sizeof(DagAdjList), "DAG adj list");
1036         itA->node = fob1;
1037         itA->type = rel;
1038         itA->count = 1;
1039         itA->next = fob2->parent;
1040         itA->name = name;
1041         fob2->parent = itA;
1042 }
1043
1044 void dag_add_relation(DagForest *forest, DagNode *fob1, DagNode *fob2, short rel, const char *name) 
1045 {
1046         DagAdjList *itA = fob1->child;
1047         
1048         /* parent relation is for cycle checking */
1049         dag_add_parent_relation(forest, fob1, fob2, rel, name);
1050
1051         while (itA) { /* search if relation exist already */
1052                 if (itA->node == fob2) {
1053                         itA->type |= rel;
1054                         itA->count += 1;
1055                         return;
1056                 }
1057                 itA = itA->next;
1058         }
1059         /* create new relation and insert at head. MALLOC alert! */
1060         itA = MEM_mallocN(sizeof(DagAdjList), "DAG adj list");
1061         itA->node = fob2;
1062         itA->type = rel;
1063         itA->count = 1;
1064         itA->next = fob1->child;
1065         itA->name = name;
1066         fob1->child = itA;
1067 }
1068
1069 static const char *dag_node_name(DagNode *node)
1070 {
1071         if (node->ob == NULL)
1072                 return "null";
1073         else if (ugly_hack_sorry)
1074                 return ((ID *)(node->ob))->name + 2;
1075         else
1076                 return ((bPoseChannel *)(node->ob))->name;
1077 }
1078
1079 static void dag_node_print_dependencies(DagNode *node)
1080 {
1081         DagAdjList *itA;
1082
1083         printf("%s depends on:\n", dag_node_name(node));
1084
1085         for (itA = node->parent; itA; itA = itA->next)
1086                 printf("  %s through %s\n", dag_node_name(itA->node), itA->name);
1087         printf("\n");
1088 }
1089
1090 static int dag_node_print_dependency_recurs(DagNode *node, DagNode *endnode)
1091 {
1092         DagAdjList *itA;
1093
1094         if (node->color == DAG_BLACK)
1095                 return 0;
1096
1097         node->color = DAG_BLACK;
1098
1099         if (node == endnode)
1100                 return 1;
1101
1102         for (itA = node->parent; itA; itA = itA->next) {
1103                 if (dag_node_print_dependency_recurs(itA->node, endnode)) {
1104                         printf("  %s depends on %s through %s.\n", dag_node_name(node), dag_node_name(itA->node), itA->name);
1105                         return 1;
1106                 }
1107         }
1108
1109         return 0;
1110 }
1111
1112 static void dag_node_print_dependency_cycle(DagForest *dag, DagNode *startnode, DagNode *endnode, const char *name)
1113 {
1114         DagNode *node;
1115
1116         for (node = dag->DagNode.first; node; node = node->next)
1117                 node->color = DAG_WHITE;
1118
1119         printf("  %s depends on %s through %s.\n", dag_node_name(endnode), dag_node_name(startnode), name);
1120         dag_node_print_dependency_recurs(startnode, endnode);
1121         printf("\n");
1122 }
1123
1124 static int dag_node_recurs_level(DagNode *node, int level)
1125 {
1126         DagAdjList *itA;
1127         int newlevel;
1128
1129         node->color = DAG_BLACK; /* done */
1130         newlevel = ++level;
1131         
1132         for (itA = node->parent; itA; itA = itA->next) {
1133                 if (itA->node->color == DAG_WHITE) {
1134                         itA->node->ancestor_count = dag_node_recurs_level(itA->node, level);
1135                         newlevel = MAX2(newlevel, level + itA->node->ancestor_count);
1136                 }
1137                 else
1138                         newlevel = MAX2(newlevel, level + itA->node->ancestor_count);
1139         }
1140         
1141         return newlevel;
1142 }
1143
1144 static void dag_check_cycle(DagForest *dag)
1145 {
1146         DagNode *node;
1147         DagAdjList *itA;
1148
1149         /* debugging print */
1150         if (dag_print_dependencies)
1151                 for (node = dag->DagNode.first; node; node = node->next)
1152                         dag_node_print_dependencies(node);
1153
1154         /* tag nodes unchecked */
1155         for (node = dag->DagNode.first; node; node = node->next)
1156                 node->color = DAG_WHITE;
1157         
1158         for (node = dag->DagNode.first; node; node = node->next) {
1159                 if (node->color == DAG_WHITE) {
1160                         node->ancestor_count = dag_node_recurs_level(node, 0);
1161                 }
1162         }
1163         
1164         /* check relations, and print errors */
1165         for (node = dag->DagNode.first; node; node = node->next) {
1166                 for (itA = node->parent; itA; itA = itA->next) {
1167                         if (itA->node->ancestor_count > node->ancestor_count) {
1168                                 if (node->ob && itA->node->ob) {
1169                                         printf("Dependency cycle detected:\n");
1170                                         dag_node_print_dependency_cycle(dag, itA->node, node, itA->name);
1171                                 }
1172                         }
1173                 }
1174         }
1175
1176         /* parent relations are only needed for cycle checking, so free now */
1177         for (node = dag->DagNode.first; node; node = node->next) {
1178                 while (node->parent) {
1179                         itA = node->parent->next;
1180                         MEM_freeN(node->parent);
1181                         node->parent = itA;
1182                 }
1183         }
1184 }
1185
1186 /* debug test functions */
1187
1188 void graph_print_queue(DagNodeQueue *nqueue)
1189 {       
1190         DagNodeQueueElem *queueElem;
1191         
1192         queueElem = nqueue->first;
1193         while (queueElem) {
1194                 fprintf(stderr, "** %s %i %i-%i ", ((ID *) queueElem->node->ob)->name, queueElem->node->color, queueElem->node->DFS_dvtm, queueElem->node->DFS_fntm);
1195                 queueElem = queueElem->next;
1196         }
1197         fprintf(stderr, "\n");
1198 }
1199
1200 void graph_print_queue_dist(DagNodeQueue *nqueue)
1201 {       
1202         DagNodeQueueElem *queueElem;
1203         int count;
1204         
1205         queueElem = nqueue->first;
1206         count = 0;
1207         while (queueElem) {
1208                 fprintf(stderr, "** %25s %2.2i-%2.2i ", ((ID *) queueElem->node->ob)->name, queueElem->node->DFS_dvtm, queueElem->node->DFS_fntm);
1209                 while (count < queueElem->node->DFS_dvtm - 1) { fputc(' ', stderr); count++; }
1210                 fputc('|', stderr);
1211                 while (count < queueElem->node->DFS_fntm - 2) { fputc('-', stderr); count++; }
1212                 fputc('|', stderr);
1213                 fputc('\n', stderr);
1214                 count = 0;
1215                 queueElem = queueElem->next;
1216         }
1217         fprintf(stderr, "\n");
1218 }
1219
1220 void graph_print_adj_list(DagForest *dag)
1221 {
1222         DagNode *node;
1223         DagAdjList *itA;
1224         
1225         node = dag->DagNode.first;
1226         while (node) {
1227                 fprintf(stderr, "node : %s col: %i", ((ID *) node->ob)->name, node->color);
1228                 itA = node->child;
1229                 while (itA) {
1230                         fprintf(stderr, "-- %s ", ((ID *) itA->node->ob)->name);
1231                         
1232                         itA = itA->next;
1233                 }
1234                 fprintf(stderr, "\n");
1235                 node = node->next;
1236         }
1237 }
1238
1239 /* ************************ API *********************** */
1240
1241 /* mechanism to allow editors to be informed of depsgraph updates,
1242  * to do their own updates based on changes... */
1243 static void (*EditorsUpdateIDCb)(Main *bmain, ID *id) = NULL;
1244 static void (*EditorsUpdateSceneCb)(Main *bmain, Scene *scene, int updated) = NULL;
1245
1246 void DAG_editors_update_cb(void (*id_func)(Main *bmain, ID *id), void (*scene_func)(Main *bmain, Scene *scene, int updated))
1247 {
1248         EditorsUpdateIDCb = id_func;
1249         EditorsUpdateSceneCb = scene_func;
1250 }
1251
1252 static void dag_editors_id_update(Main *bmain, ID *id)
1253 {
1254         if (EditorsUpdateIDCb)
1255                 EditorsUpdateIDCb(bmain, id);
1256 }
1257
1258 static void dag_editors_scene_update(Main *bmain, Scene *scene, int updated)
1259 {
1260         if (EditorsUpdateSceneCb)
1261                 EditorsUpdateSceneCb(bmain, scene, updated);
1262 }
1263
1264 /* groups with objects in this scene need to be put in the right order as well */
1265 static void scene_sort_groups(Main *bmain, Scene *sce)
1266 {
1267         Base *base;
1268         Group *group;
1269         GroupObject *go;
1270         Object *ob;
1271         
1272         /* test; are group objects all in this scene? */
1273         for (ob = bmain->object.first; ob; ob = ob->id.next) {
1274                 ob->id.flag &= ~LIB_DOIT;
1275                 ob->id.newid = NULL; /* newid abuse for GroupObject */
1276         }
1277         for (base = sce->base.first; base; base = base->next)
1278                 base->object->id.flag |= LIB_DOIT;
1279         
1280         for (group = bmain->group.first; group; group = group->id.next) {
1281                 for (go = group->gobject.first; go; go = go->next) {
1282                         if ((go->ob->id.flag & LIB_DOIT) == 0)
1283                                 break;
1284                 }
1285                 /* this group is entirely in this scene */
1286                 if (go == NULL) {
1287                         ListBase listb = {NULL, NULL};
1288                         
1289                         for (go = group->gobject.first; go; go = go->next)
1290                                 go->ob->id.newid = (ID *)go;
1291                         
1292                         /* in order of sorted bases we reinsert group objects */
1293                         for (base = sce->base.first; base; base = base->next) {
1294                                 
1295                                 if (base->object->id.newid) {
1296                                         go = (GroupObject *)base->object->id.newid;
1297                                         base->object->id.newid = NULL;
1298                                         BLI_remlink(&group->gobject, go);
1299                                         BLI_addtail(&listb, go);
1300                                 }
1301                         }
1302                         /* copy the newly sorted listbase */
1303                         group->gobject = listb;
1304                 }
1305         }
1306 }
1307
1308 /* free the depency graph */
1309 static void dag_scene_free(Scene *sce)
1310 {
1311         if (sce->theDag) {
1312                 free_forest(sce->theDag);
1313                 MEM_freeN(sce->theDag);
1314                 sce->theDag = NULL;
1315         }
1316 }
1317
1318 /* sort the base list on dependency order */
1319 static void dag_scene_build(Main *bmain, Scene *sce)
1320 {
1321         DagNode *node, *rootnode;
1322         DagNodeQueue *nqueue;
1323         DagAdjList *itA;
1324         int time;
1325         int skip = 0;
1326         ListBase tempbase;
1327         Base *base;
1328
1329         tempbase.first = tempbase.last = NULL;
1330         
1331         build_dag(bmain, sce, DAG_RL_ALL_BUT_DATA);
1332         
1333         dag_check_cycle(sce->theDag);
1334
1335         nqueue = queue_create(DAGQUEUEALLOC);
1336         
1337         for (node = sce->theDag->DagNode.first; node; node = node->next) {
1338                 node->color = DAG_WHITE;
1339         }
1340         
1341         time = 1;
1342         
1343         rootnode = sce->theDag->DagNode.first;
1344         rootnode->color = DAG_GRAY;
1345         time++;
1346         push_stack(nqueue, rootnode);
1347         
1348         while (nqueue->count) {
1349                 
1350                 skip = 0;
1351                 node = get_top_node_queue(nqueue);
1352                 
1353                 itA = node->child;
1354                 while (itA != NULL) {
1355                         if (itA->node->color == DAG_WHITE) {
1356                                 itA->node->DFS_dvtm = time;
1357                                 itA->node->color = DAG_GRAY;
1358                                 
1359                                 time++;
1360                                 push_stack(nqueue, itA->node);
1361                                 skip = 1;
1362                                 break;
1363                         }
1364                         itA = itA->next;
1365                 }
1366                 
1367                 if (!skip) {
1368                         if (node) {
1369                                 node = pop_queue(nqueue);
1370                                 if (node->ob == sce)  /* we are done */
1371                                         break;
1372                                 node->color = DAG_BLACK;
1373                                 
1374                                 time++;
1375                                 base = sce->base.first;
1376                                 while (base && base->object != node->ob)
1377                                         base = base->next;
1378                                 if (base) {
1379                                         BLI_remlink(&sce->base, base);
1380                                         BLI_addhead(&tempbase, base);
1381                                 }
1382                         }
1383                 }
1384         }
1385         
1386         /* temporal correction for circular dependencies */
1387         base = sce->base.first;
1388         while (base) {
1389                 BLI_remlink(&sce->base, base);
1390                 BLI_addhead(&tempbase, base);
1391                 //if (G.debug & G_DEBUG)
1392                 printf("cyclic %s\n", base->object->id.name);
1393                 base = sce->base.first;
1394         }
1395         
1396         sce->base = tempbase;
1397         queue_delete(nqueue);
1398         
1399         /* all groups with objects in this scene gets resorted too */
1400         scene_sort_groups(bmain, sce);
1401         
1402         if (G.debug & G_DEBUG) {
1403                 printf("\nordered\n");
1404                 for (base = sce->base.first; base; base = base->next) {
1405                         printf(" %s\n", base->object->id.name);
1406                 }
1407         }
1408
1409         /* temporal...? */
1410         sce->recalc |= SCE_PRV_CHANGED; /* test for 3d preview */
1411 }
1412
1413 /* clear all dependency graphs */
1414 void DAG_relations_tag_update(Main *bmain)
1415 {
1416         Scene *sce;
1417
1418         for (sce = bmain->scene.first; sce; sce = sce->id.next)
1419                 dag_scene_free(sce);
1420 }
1421
1422 /* rebuild dependency graph only for a given scene */
1423 void DAG_scene_relations_rebuild(Main *bmain, Scene *sce)
1424 {
1425         dag_scene_free(sce);
1426         DAG_scene_relations_update(bmain, sce);
1427 }
1428
1429 /* create dependency graph if it was cleared or didn't exist yet */
1430 void DAG_scene_relations_update(Main *bmain, Scene *sce)
1431 {
1432         if (!sce->theDag)
1433                 dag_scene_build(bmain, sce);
1434 }
1435
1436 void DAG_scene_free(Scene *sce)
1437 {
1438         if (sce->theDag) {
1439                 free_forest(sce->theDag);
1440                 MEM_freeN(sce->theDag);
1441                 sce->theDag = NULL;
1442         }
1443 }
1444
1445 static void lib_id_recalc_tag(Main *bmain, ID *id)
1446 {
1447         id->flag |= LIB_ID_RECALC;
1448         DAG_id_type_tag(bmain, GS(id->name));
1449 }
1450
1451 static void lib_id_recalc_data_tag(Main *bmain, ID *id)
1452 {
1453         id->flag |= LIB_ID_RECALC_DATA;
1454         DAG_id_type_tag(bmain, GS(id->name));
1455 }
1456
1457 /* node was checked to have lasttime != curtime and is if type ID_OB */
1458 static void flush_update_node(Main *bmain, DagNode *node, unsigned int layer, int curtime)
1459 {
1460         DagAdjList *itA;
1461         Object *ob, *obc;
1462         int oldflag, changed = 0;
1463         unsigned int all_layer;
1464         
1465         node->lasttime = curtime;
1466         
1467         ob = node->ob;
1468         if (ob && (ob->recalc & OB_RECALC_ALL)) {
1469                 all_layer = node->scelay;
1470
1471                 /* got an object node that changes, now check relations */
1472                 for (itA = node->child; itA; itA = itA->next) {
1473                         all_layer |= itA->lay;
1474                         /* the relationship is visible */
1475                         if ((itA->lay & layer)) { // XXX || (itA->node->ob == obedit)
1476                                 if (itA->node->type == ID_OB) {
1477                                         obc = itA->node->ob;
1478                                         oldflag = obc->recalc;
1479                                         
1480                                         /* got a ob->obc relation, now check if flag needs flush */
1481                                         if (ob->recalc & OB_RECALC_OB) {
1482                                                 if (itA->type & DAG_RL_OB_OB) {
1483                                                         //printf("ob %s changes ob %s\n", ob->id.name, obc->id.name);
1484                                                         obc->recalc |= OB_RECALC_OB;
1485                                                         lib_id_recalc_tag(bmain, &obc->id);
1486                                                 }
1487                                                 if (itA->type & DAG_RL_OB_DATA) {
1488                                                         //printf("ob %s changes obdata %s\n", ob->id.name, obc->id.name);
1489                                                         obc->recalc |= OB_RECALC_DATA;
1490                                                         lib_id_recalc_data_tag(bmain, &obc->id);
1491                                                 }
1492                                         }
1493                                         if (ob->recalc & OB_RECALC_DATA) {
1494                                                 if (itA->type & DAG_RL_DATA_OB) {
1495                                                         //printf("obdata %s changes ob %s\n", ob->id.name, obc->id.name);
1496                                                         obc->recalc |= OB_RECALC_OB;
1497                                                         lib_id_recalc_tag(bmain, &obc->id);
1498                                                 }
1499                                                 if (itA->type & DAG_RL_DATA_DATA) {
1500                                                         //printf("obdata %s changes obdata %s\n", ob->id.name, obc->id.name);
1501                                                         obc->recalc |= OB_RECALC_DATA;
1502                                                         lib_id_recalc_data_tag(bmain, &obc->id);
1503                                                 }
1504                                         }
1505                                         if (oldflag != obc->recalc) changed = 1;
1506                                 }
1507                         }
1508                 }
1509                 /* even nicer, we can clear recalc flags...  */
1510                 if ((all_layer & layer) == 0) { // XXX && (ob != obedit)) {
1511                         /* but existing displaylists or derivedmesh should be freed */
1512                         if (ob->recalc & OB_RECALC_DATA)
1513                                 BKE_object_free_derived_caches(ob);
1514                         
1515                         ob->recalc &= ~OB_RECALC_ALL;
1516                 }
1517         }
1518         
1519         /* check case where child changes and parent forcing obdata to change */
1520         /* should be done regardless if this ob has recalc set */
1521         /* could merge this in with loop above...? (ton) */
1522         for (itA = node->child; itA; itA = itA->next) {
1523                 /* the relationship is visible */
1524                 if ((itA->lay & layer)) {       // XXX  || (itA->node->ob == obedit)
1525                         if (itA->node->type == ID_OB) {
1526                                 obc = itA->node->ob;
1527                                 /* child moves */
1528                                 if ((obc->recalc & OB_RECALC_ALL) == OB_RECALC_OB) {
1529                                         /* parent has deforming info */
1530                                         if (itA->type & (DAG_RL_OB_DATA | DAG_RL_DATA_DATA)) {
1531                                                 // printf("parent %s changes ob %s\n", ob->id.name, obc->id.name);
1532                                                 obc->recalc |= OB_RECALC_DATA;
1533                                                 lib_id_recalc_data_tag(bmain, &obc->id);
1534                                         }
1535                                 }
1536                         }
1537                 }
1538         }
1539         
1540         /* we only go deeper if node not checked or something changed  */
1541         for (itA = node->child; itA; itA = itA->next) {
1542                 if (changed || itA->node->lasttime != curtime)
1543                         flush_update_node(bmain, itA->node, layer, curtime);
1544         }
1545         
1546 }
1547
1548 /* node was checked to have lasttime != curtime, and is of type ID_OB */
1549 static unsigned int flush_layer_node(Scene *sce, DagNode *node, int curtime)
1550 {
1551         DagAdjList *itA;
1552         
1553         node->lasttime = curtime;
1554         node->lay = node->scelay;
1555         
1556         for (itA = node->child; itA; itA = itA->next) {
1557                 if (itA->node->type == ID_OB) {
1558                         if (itA->node->lasttime != curtime) {
1559                                 itA->lay = flush_layer_node(sce, itA->node, curtime);  /* lay is only set once for each relation */
1560                         }
1561                         else {
1562                                 itA->lay = itA->node->lay;
1563                         }
1564                         
1565                         node->lay |= itA->lay;
1566                 }
1567         }
1568
1569         return node->lay;
1570 }
1571
1572 /* node was checked to have lasttime != curtime, and is of type ID_OB */
1573 static void flush_pointcache_reset(Main *bmain, Scene *scene, DagNode *node, int curtime, int reset)
1574 {
1575         DagAdjList *itA;
1576         Object *ob;
1577         
1578         node->lasttime = curtime;
1579         
1580         for (itA = node->child; itA; itA = itA->next) {
1581                 if (itA->node->type == ID_OB) {
1582                         if (itA->node->lasttime != curtime) {
1583                                 ob = (Object *)(itA->node->ob);
1584
1585                                 if (reset || (ob->recalc & OB_RECALC_ALL)) {
1586                                         if (BKE_ptcache_object_reset(scene, ob, PTCACHE_RESET_DEPSGRAPH)) {
1587                                                 ob->recalc |= OB_RECALC_DATA;
1588                                                 lib_id_recalc_data_tag(bmain, &ob->id);
1589                                         }
1590
1591                                         flush_pointcache_reset(bmain, scene, itA->node, curtime, 1);
1592                                 }
1593                                 else
1594                                         flush_pointcache_reset(bmain, scene, itA->node, curtime, 0);
1595                         }
1596                 }
1597         }
1598 }
1599
1600 /* flush layer flags to dependencies */
1601 static void dag_scene_flush_layers(Scene *sce, int lay)
1602 {
1603         DagNode *node, *firstnode;
1604         DagAdjList *itA;
1605         Base *base;
1606         int lasttime;
1607
1608         firstnode = sce->theDag->DagNode.first;  /* always scene node */
1609
1610         for (itA = firstnode->child; itA; itA = itA->next)
1611                 itA->lay = 0;
1612
1613         sce->theDag->time++;  /* so we know which nodes were accessed */
1614         lasttime = sce->theDag->time;
1615
1616         /* update layer flags in nodes */
1617         for (base = sce->base.first; base; base = base->next) {
1618                 node = dag_get_node(sce->theDag, base->object);
1619                 node->scelay = base->object->lay;
1620         }
1621
1622         /* ensure cameras are set as if they are on a visible layer, because
1623          * they ared still used for rendering or setting the camera view
1624          *
1625          * XXX, this wont work for local view / unlocked camera's */
1626         if (sce->camera) {
1627                 node = dag_get_node(sce->theDag, sce->camera);
1628                 node->scelay |= lay;
1629         }
1630
1631 #ifdef DURIAN_CAMERA_SWITCH
1632         {
1633                 TimeMarker *m;
1634
1635                 for (m = sce->markers.first; m; m = m->next) {
1636                         if (m->camera) {
1637                                 node = dag_get_node(sce->theDag, m->camera);
1638                                 node->scelay |= lay;
1639                         }
1640                 }
1641         }
1642 #endif
1643
1644         /* flush layer nodes to dependencies */
1645         for (itA = firstnode->child; itA; itA = itA->next)
1646                 if (itA->node->lasttime != lasttime && itA->node->type == ID_OB)
1647                         flush_layer_node(sce, itA->node, lasttime);
1648 }
1649
1650 static void dag_tag_renderlayers(Scene *sce, unsigned int lay)
1651 {
1652         if (sce->nodetree) {
1653                 bNode *node;
1654                 Base *base;
1655                 unsigned int lay_changed = 0;
1656                 
1657                 for (base = sce->base.first; base; base = base->next)
1658                         if (base->lay & lay)
1659                                 if (base->object->recalc)
1660                                         lay_changed |= base->lay;
1661                         
1662                 for (node = sce->nodetree->nodes.first; node; node = node->next) {
1663                         if (node->id == (ID *)sce) {
1664                                 SceneRenderLayer *srl = BLI_findlink(&sce->r.layers, node->custom1);
1665                                 if (srl && (srl->lay & lay_changed))
1666                                         nodeUpdate(sce->nodetree, node);
1667                         }
1668                 }
1669         }
1670 }
1671
1672 /* flushes all recalc flags in objects down the dependency tree */
1673 void DAG_scene_flush_update(Main *bmain, Scene *sce, unsigned int lay, const short time)
1674 {
1675         DagNode *firstnode;
1676         DagAdjList *itA;
1677         Object *ob;
1678         int lasttime;
1679         
1680         if (sce->theDag == NULL) {
1681                 printf("DAG zero... not allowed to happen!\n");
1682                 DAG_scene_relations_update(bmain, sce);
1683         }
1684         
1685         firstnode = sce->theDag->DagNode.first;  /* always scene node */
1686
1687         /* first we flush the layer flags */
1688         dag_scene_flush_layers(sce, lay);
1689
1690         /* then we use the relationships + layer info to flush update events */
1691         sce->theDag->time++;  /* so we know which nodes were accessed */
1692         lasttime = sce->theDag->time;
1693         for (itA = firstnode->child; itA; itA = itA->next)
1694                 if (itA->node->lasttime != lasttime && itA->node->type == ID_OB)
1695                         flush_update_node(bmain, itA->node, lay, lasttime);
1696
1697         /* if update is not due to time change, do pointcache clears */
1698         if (!time) {
1699                 sce->theDag->time++;  /* so we know which nodes were accessed */
1700                 lasttime = sce->theDag->time;
1701                 for (itA = firstnode->child; itA; itA = itA->next) {
1702                         if (itA->node->lasttime != lasttime && itA->node->type == ID_OB) {
1703                                 ob = (Object *)(itA->node->ob);
1704
1705                                 if (ob->recalc & OB_RECALC_ALL) {
1706                                         if (BKE_ptcache_object_reset(sce, ob, PTCACHE_RESET_DEPSGRAPH)) {
1707                                                 ob->recalc |= OB_RECALC_DATA;
1708                                                 lib_id_recalc_data_tag(bmain, &ob->id);
1709                                         }
1710
1711                                         flush_pointcache_reset(bmain, sce, itA->node, lasttime, 1);
1712                                 }
1713                                 else
1714                                         flush_pointcache_reset(bmain, sce, itA->node, lasttime, 0);
1715                         }
1716                 }
1717         }
1718         
1719         dag_tag_renderlayers(sce, lay);
1720 }
1721
1722 static int object_modifiers_use_time(Object *ob)
1723 {
1724         ModifierData *md;
1725         
1726         /* check if a modifier in modifier stack needs time input */
1727         for (md = ob->modifiers.first; md; md = md->next)
1728                 if (modifier_dependsOnTime(md))
1729                         return 1;
1730         
1731         /* check whether any modifiers are animated */
1732         if (ob->adt) {
1733                 AnimData *adt = ob->adt;
1734                 FCurve *fcu;
1735                 
1736                 /* action - check for F-Curves with paths containing 'modifiers[' */
1737                 if (adt->action) {
1738                         for (fcu = adt->action->curves.first; fcu; fcu = fcu->next) {
1739                                 if (fcu->rna_path && strstr(fcu->rna_path, "modifiers["))
1740                                         return 1;
1741                         }
1742                 }
1743                 
1744                 /* This here allows modifier properties to get driven and still update properly
1745                  *
1746                  * Workaround to get [#26764] (e.g. subsurf levels not updating when animated/driven)
1747                  * working, without the updating problems ([#28525] [#28690] [#28774] [#28777]) caused
1748                  * by the RNA updates cache introduced in r.38649
1749                  */
1750                 for (fcu = adt->drivers.first; fcu; fcu = fcu->next) {
1751                         if (fcu->rna_path && strstr(fcu->rna_path, "modifiers["))
1752                                 return 1;
1753                 }
1754                 
1755                 /* XXX: also, should check NLA strips, though for now assume that nobody uses
1756                  * that and we can omit that for performance reasons... */
1757         }
1758         
1759         return 0;
1760 }
1761
1762 static short animdata_use_time(AnimData *adt)
1763 {
1764         NlaTrack *nlt;
1765         
1766         if (adt == NULL) return 0;
1767         
1768         /* check action - only if assigned, and it has anim curves */
1769         if (adt->action && adt->action->curves.first)
1770                 return 1;
1771         
1772         /* check NLA tracks + strips */
1773         for (nlt = adt->nla_tracks.first; nlt; nlt = nlt->next) {
1774                 if (nlt->strips.first)
1775                         return 1;
1776         }
1777         
1778         /* If we have drivers, more likely than not, on a frame change
1779          * they'll need updating because their owner changed
1780          * 
1781          * This is kindof a hack to get around a whole host of problems
1782          * involving drivers using non-object datablock data (which the 
1783          * depsgraph currently has no way of representing let alone correctly
1784          * dependency sort+tagging). By doing this, at least we ensure that 
1785          * some commonly attempted drivers (such as scene -> current frame;
1786          * see "Driver updates fail" thread on Bf-committers dated July 2)
1787          * will work correctly, and that other non-object datablocks will have
1788          * their drivers update at least on frame change.
1789          *
1790          * -- Aligorith, July 4 2011
1791          */
1792         if (adt->drivers.first)
1793                 return 1;
1794         
1795         return 0;
1796 }
1797
1798 static void dag_object_time_update_flags(Main *bmain, Scene *scene, Object *ob)
1799 {
1800         if (ob->constraints.first) {
1801                 bConstraint *con;
1802                 for (con = ob->constraints.first; con; con = con->next) {
1803                         bConstraintTypeInfo *cti = BKE_constraint_get_typeinfo(con);
1804                         ListBase targets = {NULL, NULL};
1805                         bConstraintTarget *ct;
1806                         
1807                         if (cti) {
1808                                 /* special case for camera tracking -- it doesn't use targets to define relations */
1809                                 if (ELEM3(cti->type, CONSTRAINT_TYPE_FOLLOWTRACK, CONSTRAINT_TYPE_CAMERASOLVER, CONSTRAINT_TYPE_OBJECTSOLVER)) {
1810                                         ob->recalc |= OB_RECALC_OB;
1811                                 }
1812                                 else if (cti->get_constraint_targets) {
1813                                         cti->get_constraint_targets(con, &targets);
1814                                         
1815                                         for (ct = targets.first; ct; ct = ct->next) {
1816                                                 if (ct->tar) {
1817                                                         ob->recalc |= OB_RECALC_OB;
1818                                                         break;
1819                                                 }
1820                                         }
1821                                         
1822                                         if (cti->flush_constraint_targets)
1823                                                 cti->flush_constraint_targets(con, &targets, 1);
1824                                 }
1825                                 
1826                         }
1827                 }
1828         }
1829         
1830         if (ob->parent) {
1831                 /* motion path or bone child */
1832                 if (ob->parent->type == OB_CURVE || ob->parent->type == OB_ARMATURE) ob->recalc |= OB_RECALC_OB;
1833         }
1834         
1835 #if 0 // XXX old animation system
1836         if (ob->nlastrips.first) {
1837                 if (ob->dup_group) {
1838                         bActionStrip *strip;
1839                         /* this case is for groups with nla, whilst nla target has no action or nla */
1840                         for (strip = ob->nlastrips.first; strip; strip = strip->next) {
1841                                 if (strip->object)
1842                                         strip->object->recalc |= OB_RECALC_ALL;
1843                         }
1844                 }
1845         }
1846 #endif // XXX old animation system
1847         
1848         if (animdata_use_time(ob->adt)) {
1849                 ob->recalc |= OB_RECALC_OB;
1850                 ob->adt->recalc |= ADT_RECALC_ANIM;
1851         }
1852         
1853         if ((ob->adt) && (ob->type == OB_ARMATURE)) ob->recalc |= OB_RECALC_DATA;
1854         
1855         if (object_modifiers_use_time(ob)) ob->recalc |= OB_RECALC_DATA;
1856         if ((ob->pose) && (ob->pose->flag & POSE_CONSTRAINTS_TIMEDEPEND)) ob->recalc |= OB_RECALC_DATA;
1857         
1858         // XXX: scene here may not be the scene that contains the rigidbody world affecting this!
1859         if (ob->rigidbody_object && BKE_scene_check_rigidbody_active(scene))
1860                 ob->recalc |= OB_RECALC_OB;
1861         
1862         {
1863                 AnimData *adt = BKE_animdata_from_id((ID *)ob->data);
1864                 Mesh *me;
1865                 Curve *cu;
1866                 Lattice *lt;
1867                 
1868                 switch (ob->type) {
1869                         case OB_MESH:
1870                                 me = ob->data;
1871                                 if (me->key) {
1872                                         if (!(ob->shapeflag & OB_SHAPE_LOCK)) {
1873                                                 ob->recalc |= OB_RECALC_DATA;
1874                                         }
1875                                 }
1876                                 if (ob->particlesystem.first)
1877                                         ob->recalc |= OB_RECALC_DATA;
1878                                 break;
1879                         case OB_CURVE:
1880                         case OB_SURF:
1881                                 cu = ob->data;
1882                                 if (cu->key) {
1883                                         if (!(ob->shapeflag & OB_SHAPE_LOCK)) {
1884                                                 ob->recalc |= OB_RECALC_DATA;
1885                                         }
1886                                 }
1887                                 break;
1888                         case OB_FONT:
1889                                 cu = ob->data;
1890                                 if (cu->nurb.first == NULL && cu->str && cu->vfont)
1891                                         ob->recalc |= OB_RECALC_DATA;
1892                                 break;
1893                         case OB_LATTICE:
1894                                 lt = ob->data;
1895                                 if (lt->key) {
1896                                         if (!(ob->shapeflag & OB_SHAPE_LOCK)) {
1897                                                 ob->recalc |= OB_RECALC_DATA;
1898                                         }
1899                                 }
1900                                 break;
1901                         case OB_MBALL:
1902                                 if (ob->transflag & OB_DUPLI) ob->recalc |= OB_RECALC_DATA;
1903                                 break;
1904                 }
1905                 
1906                 if (animdata_use_time(adt)) {
1907                         ob->recalc |= OB_RECALC_DATA;
1908                         adt->recalc |= ADT_RECALC_ANIM;
1909                 }
1910
1911                 if (ob->particlesystem.first) {
1912                         ParticleSystem *psys = ob->particlesystem.first;
1913
1914                         for (; psys; psys = psys->next) {
1915                                 if (psys_check_enabled(ob, psys)) {
1916                                         ob->recalc |= OB_RECALC_DATA;
1917                                         break;
1918                                 }
1919                         }
1920                 }
1921         }
1922
1923         if (ob->recalc & OB_RECALC_OB)
1924                 lib_id_recalc_tag(bmain, &ob->id);
1925         if (ob->recalc & OB_RECALC_DATA)
1926                 lib_id_recalc_data_tag(bmain, &ob->id);
1927
1928 }
1929 /* flag all objects that need recalc, for changes in time for example */
1930 /* do_time: make this optional because undo resets objects to their animated locations without this */
1931 void DAG_scene_update_flags(Main *bmain, Scene *scene, unsigned int lay, const short do_time)
1932 {
1933         Base *base;
1934         Object *ob;
1935         Group *group;
1936         GroupObject *go;
1937         Scene *sce_iter;
1938
1939         /* set ob flags where animated systems are */
1940         for (SETLOOPER(scene, sce_iter, base)) {
1941                 ob = base->object;
1942
1943                 if (do_time) {
1944                         /* now if DagNode were part of base, the node->lay could be checked... */
1945                         /* we do all now, since the scene_flush checks layers and clears recalc flags even */
1946                         
1947                         /* NOTE: "sce_iter" not "scene" so that rigidbodies in background scenes work 
1948                          * (i.e. muting + rbw availability can be checked and tagged properly) [#33970] 
1949                          */
1950                         dag_object_time_update_flags(bmain, sce_iter, ob);
1951                 }
1952
1953                 /* handled in next loop */
1954                 if (ob->dup_group)
1955                         ob->dup_group->id.flag |= LIB_DOIT;
1956         }
1957
1958         if (do_time) {
1959                 /* we do groups each once */
1960                 for (group = bmain->group.first; group; group = group->id.next) {
1961                         if (group->id.flag & LIB_DOIT) {
1962                                 for (go = group->gobject.first; go; go = go->next) {
1963                                         dag_object_time_update_flags(bmain, scene, go->ob);
1964                                 }
1965                         }
1966                 }
1967         }
1968
1969         for (sce_iter = scene; sce_iter; sce_iter = sce_iter->set)
1970                 DAG_scene_flush_update(bmain, sce_iter, lay, 1);
1971         
1972         if (do_time) {
1973                 /* test: set time flag, to disable baked systems to update */
1974                 for (SETLOOPER(scene, sce_iter, base)) {
1975                         ob = base->object;
1976                         if (ob->recalc)
1977                                 ob->recalc |= OB_RECALC_TIME;
1978                 }
1979
1980                 /* hrmf... an exception to look at once, for invisible camera object we do it over */
1981                 if (scene->camera)
1982                         dag_object_time_update_flags(bmain, scene, scene->camera);
1983         }
1984
1985         /* and store the info in groupobject */
1986         for (group = bmain->group.first; group; group = group->id.next) {
1987                 if (group->id.flag & LIB_DOIT) {
1988                         for (go = group->gobject.first; go; go = go->next) {
1989                                 go->recalc = go->ob->recalc;
1990                                 // printf("ob %s recalc %d\n", go->ob->id.name, go->recalc);
1991                         }
1992                         group->id.flag &= ~LIB_DOIT;
1993                 }
1994         }
1995         
1996 }
1997
1998 /* struct returned by DagSceneLayer */
1999 typedef struct DagSceneLayer {
2000         struct DagSceneLayer *next, *prev;
2001         Scene *scene;
2002         unsigned int layer;
2003 } DagSceneLayer;
2004
2005 /* returns visible scenes with valid DAG */
2006 static void dag_current_scene_layers(Main *bmain, ListBase *lb)
2007 {
2008         wmWindowManager *wm;
2009         wmWindow *win;
2010         
2011         lb->first = lb->last = NULL;
2012
2013         /* if we have a windowmanager, look into windows */
2014         if ((wm = bmain->wm.first)) {
2015                 
2016                 flag_listbase_ids(&bmain->scene, LIB_DOIT, 1);
2017
2018                 for (win = wm->windows.first; win; win = win->next) {
2019                         if (win->screen && win->screen->scene->theDag) {
2020                                 Scene *scene = win->screen->scene;
2021                                 
2022                                 if (scene->id.flag & LIB_DOIT) {
2023                                         DagSceneLayer *dsl = MEM_mallocN(sizeof(DagSceneLayer), "dag scene layer");
2024                                         
2025                                         BLI_addtail(lb, dsl);
2026                                         
2027                                         dsl->scene = scene;
2028                                         dsl->layer = BKE_screen_visible_layers(win->screen, scene);
2029                                         
2030                                         scene->id.flag &= ~LIB_DOIT;
2031                                 }
2032                         }
2033                 }
2034         }
2035         else {
2036                 /* if not, use the first sce */
2037                 DagSceneLayer *dsl = MEM_mallocN(sizeof(DagSceneLayer), "dag scene layer");
2038                 
2039                 BLI_addtail(lb, dsl);
2040                 
2041                 dsl->scene = bmain->scene.first;
2042                 dsl->layer = dsl->scene->lay;
2043
2044                 /* XXX for background mode, we should get the scene
2045                  * from somewhere, for the -S option, but it's in
2046                  * the context, how to get it here? */
2047         }
2048 }
2049
2050 void DAG_on_visible_update(Main *bmain, const short do_time)
2051 {
2052         ListBase listbase;
2053         DagSceneLayer *dsl;
2054         
2055         /* get list of visible scenes and layers */
2056         dag_current_scene_layers(bmain, &listbase);
2057         
2058         for (dsl = listbase.first; dsl; dsl = dsl->next) {
2059                 Scene *scene = dsl->scene;
2060                 Scene *sce_iter;
2061                 Base *base;
2062                 Object *ob;
2063                 Group *group;
2064                 GroupObject *go;
2065                 DagNode *node;
2066                 unsigned int lay = dsl->layer, oblay;
2067         
2068                 /* derivedmeshes and displists are not saved to file so need to be
2069                  * remade, tag them so they get remade in the scene update loop,
2070                  * note armature poses or object matrices are preserved and do not
2071                  * require updates, so we skip those */
2072                 dag_scene_flush_layers(scene, lay);
2073
2074                 for (SETLOOPER(scene, sce_iter, base)) {
2075                         ob = base->object;
2076                         node = (sce_iter->theDag) ? dag_get_node(sce_iter->theDag, ob) : NULL;
2077                         oblay = (node) ? node->lay : ob->lay;
2078
2079                         if ((oblay & lay) & ~scene->lay_updated) {
2080                                 if (ELEM6(ob->type, OB_MESH, OB_CURVE, OB_SURF, OB_FONT, OB_MBALL, OB_LATTICE))
2081                                         ob->recalc |= OB_RECALC_DATA;
2082                                 if (ob->dup_group) 
2083                                         ob->dup_group->id.flag |= LIB_DOIT;
2084                         }
2085                 }
2086
2087                 for (group = bmain->group.first; group; group = group->id.next) {
2088                         if (group->id.flag & LIB_DOIT) {
2089                                 for (go = group->gobject.first; go; go = go->next) {
2090                                         if (ELEM6(go->ob->type, OB_MESH, OB_CURVE, OB_SURF, OB_FONT, OB_MBALL, OB_LATTICE))
2091                                                 go->ob->recalc |= OB_RECALC_DATA;
2092                                         if (go->ob->proxy_from)
2093                                                 go->ob->recalc |= OB_RECALC_OB;
2094                                 }
2095                                 
2096                                 group->id.flag &= ~LIB_DOIT;
2097                         }
2098                 }
2099
2100                 /* now tag update flags, to ensure deformers get calculated on redraw */
2101                 DAG_scene_update_flags(bmain, scene, lay, do_time);
2102                 scene->lay_updated |= lay;
2103         }
2104         
2105         BLI_freelistN(&listbase);
2106
2107         /* hack to get objects updating on layer changes */
2108         DAG_id_type_tag(bmain, ID_OB);
2109
2110         /* so masks update on load */
2111         if (bmain->mask.first) {
2112                 Mask *mask;
2113
2114                 for (mask = bmain->mask.first; mask; mask = mask->id.next) {
2115                         DAG_id_tag_update(&mask->id, 0);
2116                 }
2117         }
2118 }
2119
2120 static void dag_id_flush_update__isDependentTexture(void *userData, Object *UNUSED(ob), ID **idpoin)
2121 {
2122         struct { ID *id; int is_dependent; } *data = userData;
2123         
2124         if (*idpoin && GS((*idpoin)->name) == ID_TE) {
2125                 if (data->id == (*idpoin))
2126                         data->is_dependent = 1;
2127         }
2128 }
2129
2130 static void dag_id_flush_update(Main *bmain, Scene *sce, ID *id)
2131 {
2132         Object *obt, *ob = NULL;
2133         short idtype;
2134
2135         /* here we flush a few things before actual scene wide flush, mostly
2136          * due to only objects and not other datablocks being in the depsgraph */
2137
2138         /* set flags & pointcache for object */
2139         if (GS(id->name) == ID_OB) {
2140                 ob = (Object *)id;
2141                 BKE_ptcache_object_reset(sce, ob, PTCACHE_RESET_DEPSGRAPH);
2142
2143                 if (ob->recalc & OB_RECALC_DATA) {
2144                         /* all users of this ob->data should be checked */
2145                         id = ob->data;
2146
2147                         /* no point in trying in this cases */
2148                         if (id && id->us <= 1) {
2149                                 dag_editors_id_update(bmain, id);
2150                                 id = NULL;
2151                         }
2152                 }
2153         }
2154
2155         /* set flags & pointcache for object data */
2156         if (id) {
2157                 idtype = GS(id->name);
2158
2159
2160                 if (OB_DATA_SUPPORT_ID(idtype)) {
2161                         for (obt = bmain->object.first; obt; obt = obt->id.next) {
2162                                 if (!(ob && obt == ob) && obt->data == id) {
2163                                         obt->recalc |= OB_RECALC_DATA;
2164                                         lib_id_recalc_data_tag(bmain, &obt->id);
2165                                         BKE_ptcache_object_reset(sce, obt, PTCACHE_RESET_DEPSGRAPH);
2166                                 }
2167                         }
2168                 }
2169                 
2170                 /* set flags based on textures - can influence depgraph via modifiers */
2171                 if (idtype == ID_TE) {
2172                         for (obt = bmain->object.first; obt; obt = obt->id.next) {
2173                                 struct { ID *id; int is_dependent; } data;
2174                                 data.id = id;
2175                                 data.is_dependent = 0;
2176
2177                                 modifiers_foreachIDLink(obt, dag_id_flush_update__isDependentTexture, &data);
2178                                 if (data.is_dependent) {
2179                                         obt->recalc |= OB_RECALC_DATA;
2180                                         lib_id_recalc_data_tag(bmain, &obt->id);
2181                                 }
2182
2183                                 /* particle settings can use the texture as well */
2184                                 if (obt->particlesystem.first) {
2185                                         ParticleSystem *psys = obt->particlesystem.first;
2186                                         MTex **mtexp, *mtex;
2187                                         int a;
2188                                         for (; psys; psys = psys->next) {
2189                                                 mtexp = psys->part->mtex;
2190                                                 for (a = 0; a < MAX_MTEX; a++, mtexp++) {
2191                                                         mtex = *mtexp;
2192                                                         if (mtex && mtex->tex == (Tex *)id) {
2193                                                                 obt->recalc |= OB_RECALC_DATA;
2194                                                                 lib_id_recalc_data_tag(bmain, &obt->id);
2195
2196                                                                 if (mtex->mapto & PAMAP_INIT)
2197                                                                         psys->recalc |= PSYS_RECALC_RESET;
2198                                                                 if (mtex->mapto & PAMAP_CHILD)
2199                                                                         psys->recalc |= PSYS_RECALC_CHILD;
2200
2201                                                                 BKE_ptcache_object_reset(sce, obt, PTCACHE_RESET_DEPSGRAPH);
2202                                                         }
2203                                                 }
2204                                         }
2205                                 }
2206                         }
2207                 }
2208                 
2209                 /* set flags based on ShapeKey */
2210                 if (idtype == ID_KE) {
2211                         for (obt = bmain->object.first; obt; obt = obt->id.next) {
2212                                 Key *key = BKE_key_from_object(obt);
2213                                 if (!(ob && obt == ob) && ((ID *)key == id)) {
2214                                         obt->flag |= (OB_RECALC_OB | OB_RECALC_DATA);
2215                                         lib_id_recalc_tag(bmain, &obt->id);
2216                                         lib_id_recalc_data_tag(bmain, &obt->id);
2217                                         BKE_ptcache_object_reset(sce, obt, PTCACHE_RESET_DEPSGRAPH);
2218                                 }
2219                         }
2220                 }
2221                 
2222                 /* set flags based on particle settings */
2223                 if (idtype == ID_PA) {
2224                         ParticleSystem *psys;
2225                         for (obt = bmain->object.first; obt; obt = obt->id.next)
2226                                 for (psys = obt->particlesystem.first; psys; psys = psys->next)
2227                                         if (&psys->part->id == id)
2228                                                 BKE_ptcache_object_reset(sce, obt, PTCACHE_RESET_DEPSGRAPH);
2229                 }
2230
2231                 if (idtype == ID_MC) {
2232                         MovieClip *clip = (MovieClip *) id;
2233
2234                         BKE_tracking_dopesheet_tag_update(&clip->tracking);
2235
2236                         for (obt = bmain->object.first; obt; obt = obt->id.next) {
2237                                 bConstraint *con;
2238                                 for (con = obt->constraints.first; con; con = con->next) {
2239                                         bConstraintTypeInfo *cti = BKE_constraint_get_typeinfo(con);
2240                                         if (ELEM3(cti->type, CONSTRAINT_TYPE_FOLLOWTRACK, CONSTRAINT_TYPE_CAMERASOLVER,
2241                                                   CONSTRAINT_TYPE_OBJECTSOLVER))
2242                                         {
2243                                                 obt->recalc |= OB_RECALC_OB;
2244                                                 break;
2245                                         }
2246                                 }
2247                         }
2248
2249                         if (sce->nodetree) {
2250                                 bNode *node;
2251
2252                                 for (node = sce->nodetree->nodes.first; node; node = node->next) {
2253                                         if (node->id == id) {
2254                                                 nodeUpdate(sce->nodetree, node);
2255                                         }
2256                                 }
2257                         }
2258                 }
2259
2260                 if (idtype == ID_MSK) {
2261                         if (sce->nodetree) {
2262                                 bNode *node;
2263
2264                                 for (node = sce->nodetree->nodes.first; node; node = node->next) {
2265                                         if (node->id == id) {
2266                                                 nodeUpdate(sce->nodetree, node);
2267                                         }
2268                                 }
2269                         }
2270                 }
2271
2272                 /* camera's matrix is used to orient reconstructed stuff,
2273                  * so it should happen tracking-related constraints recalculation
2274                  * when camera is changing (sergey) */
2275                 if (sce->camera && &sce->camera->id == id) {
2276                         MovieClip *clip = BKE_object_movieclip_get(sce, sce->camera, 1);
2277
2278                         if (clip)
2279                                 dag_id_flush_update(bmain, sce, &clip->id);
2280                 }
2281
2282                 /* update editors */
2283                 dag_editors_id_update(bmain, id);
2284         }
2285 }
2286
2287 void DAG_ids_flush_tagged(Main *bmain)
2288 {
2289         ListBase listbase;
2290         DagSceneLayer *dsl;
2291         ListBase *lbarray[MAX_LIBARRAY];
2292         int a, do_flush = FALSE;
2293         
2294         /* get list of visible scenes and layers */
2295         dag_current_scene_layers(bmain, &listbase);
2296
2297         if (listbase.first == NULL)
2298                 return;
2299
2300         /* loop over all ID types */
2301         a  = set_listbasepointers(bmain, lbarray);
2302
2303         while (a--) {
2304                 ListBase *lb = lbarray[a];
2305                 ID *id = lb->first;
2306
2307                 /* we tag based on first ID type character to avoid 
2308                  * looping over all ID's in case there are no tags */
2309                 if (id && bmain->id_tag_update[id->name[0]]) {
2310                         for (; id; id = id->next) {
2311                                 if (id->flag & (LIB_ID_RECALC | LIB_ID_RECALC_DATA)) {
2312                                         
2313                                         for (dsl = listbase.first; dsl; dsl = dsl->next)
2314                                                 dag_id_flush_update(bmain, dsl->scene, id);
2315                                         
2316                                         do_flush = TRUE;
2317                                 }
2318                         }
2319                 }
2320         }
2321
2322         /* flush changes to other objects */
2323         if (do_flush) {
2324                 for (dsl = listbase.first; dsl; dsl = dsl->next)
2325                         DAG_scene_flush_update(bmain, dsl->scene, dsl->layer, 0);
2326         }
2327         
2328         BLI_freelistN(&listbase);
2329 }
2330
2331 void DAG_ids_check_recalc(Main *bmain, Scene *scene, int time)
2332 {
2333         ListBase *lbarray[MAX_LIBARRAY];
2334         int a, updated = 0;
2335
2336         /* loop over all ID types */
2337         a  = set_listbasepointers(bmain, lbarray);
2338
2339         while (a--) {
2340                 ListBase *lb = lbarray[a];
2341                 ID *id = lb->first;
2342
2343                 /* we tag based on first ID type character to avoid 
2344                  * looping over all ID's in case there are no tags */
2345                 if (id &&
2346 #ifdef WITH_FREESTYLE
2347                     /* XXX very weak... added check for '27' to ignore freestyle added objects */
2348                     id->name[2] > 27 &&
2349 #endif
2350                     bmain->id_tag_update[id->name[0]])
2351                 {
2352                         updated = 1;
2353                         break;
2354                 }
2355         }
2356
2357         dag_editors_scene_update(bmain, scene, (updated || time));
2358 }
2359
2360 void DAG_ids_clear_recalc(Main *bmain)
2361 {
2362         ListBase *lbarray[MAX_LIBARRAY];
2363         bNodeTree *ntree;
2364         int a;
2365
2366         /* loop over all ID types */
2367         a  = set_listbasepointers(bmain, lbarray);
2368
2369         while (a--) {
2370                 ListBase *lb = lbarray[a];
2371                 ID *id = lb->first;
2372
2373                 /* we tag based on first ID type character to avoid 
2374                  * looping over all ID's in case there are no tags */
2375                 if (id && bmain->id_tag_update[id->name[0]]) {
2376                         for (; id; id = id->next) {
2377                                 if (id->flag & (LIB_ID_RECALC | LIB_ID_RECALC_DATA))
2378                                         id->flag &= ~(LIB_ID_RECALC | LIB_ID_RECALC_DATA);
2379
2380                                 /* some ID's contain semi-datablock nodetree */
2381                                 ntree = ntreeFromID(id);
2382                                 if (ntree && (ntree->id.flag & (LIB_ID_RECALC | LIB_ID_RECALC_DATA)))
2383                                         ntree->id.flag &= ~(LIB_ID_RECALC | LIB_ID_RECALC_DATA);
2384                         }
2385                 }
2386         }
2387
2388         memset(bmain->id_tag_update, 0, sizeof(bmain->id_tag_update));
2389 }
2390
2391 void DAG_id_tag_update_ex(Main *bmain, ID *id, short flag)
2392 {
2393         if (id == NULL) return;
2394
2395         /* tag ID for update */
2396         if (flag) {
2397                 if (flag & OB_RECALC_OB)
2398                         lib_id_recalc_tag(bmain, id);
2399                 if (flag & (OB_RECALC_DATA | PSYS_RECALC))
2400                         lib_id_recalc_data_tag(bmain, id);
2401         }
2402         else
2403                 lib_id_recalc_tag(bmain, id);
2404
2405         /* flag is for objects and particle systems */
2406         if (flag) {
2407                 Object *ob;
2408                 short idtype = GS(id->name);
2409
2410                 if (idtype == ID_OB) {
2411                         /* only quick tag */
2412                         ob = (Object *)id;
2413                         ob->recalc |= (flag & OB_RECALC_ALL);
2414                 }
2415                 else if (idtype == ID_PA) {
2416                         ParticleSystem *psys;
2417                         /* this is weak still, should be done delayed as well */
2418                         for (ob = bmain->object.first; ob; ob = ob->id.next) {
2419                                 for (psys = ob->particlesystem.first; psys; psys = psys->next) {
2420                                         if (&psys->part->id == id) {
2421                                                 ob->recalc |= (flag & OB_RECALC_ALL);
2422                                                 psys->recalc |= (flag & PSYS_RECALC);
2423                                                 lib_id_recalc_tag(bmain, &ob->id);
2424                                                 lib_id_recalc_data_tag(bmain, &ob->id);
2425                                         }
2426                                 }
2427                         }
2428                 }
2429                 else if (idtype == ID_VF) {
2430                         /* this is weak still, should be done delayed as well */
2431                         for (ob = bmain->object.first; ob; ob = ob->id.next) {
2432                                 if (ob->type == OB_FONT) {
2433                                         Curve *cu = ob->data;
2434
2435                                         if (ELEM4((struct VFont *)id, cu->vfont, cu->vfontb, cu->vfonti, cu->vfontbi)) {
2436                                                 ob->recalc |= (flag & OB_RECALC_ALL);
2437                                         }
2438                                 }
2439                         }
2440                 }
2441                 else {
2442                         /* disable because this is called on various ID types automatically.
2443                          * where printing warning is not useful. for now just ignore */
2444                         /* BLI_assert(!"invalid flag for this 'idtype'"); */
2445                 }
2446         }
2447 }
2448
2449 void DAG_id_tag_update(ID *id, short flag)
2450 {
2451         DAG_id_tag_update_ex(G.main, id, flag);
2452 }
2453
2454 void DAG_id_type_tag(Main *bmain, short idtype)
2455 {
2456         if (idtype == ID_NT) {
2457                 /* stupid workaround so parent datablocks of nested nodetree get looped
2458                  * over when we loop over tagged datablock types */
2459                 DAG_id_type_tag(bmain, ID_MA);
2460                 DAG_id_type_tag(bmain, ID_TE);
2461                 DAG_id_type_tag(bmain, ID_LA);
2462                 DAG_id_type_tag(bmain, ID_WO);
2463                 DAG_id_type_tag(bmain, ID_SCE);
2464         }
2465
2466         bmain->id_tag_update[((char *)&idtype)[0]] = 1;
2467 }
2468
2469 int DAG_id_type_tagged(Main *bmain, short idtype)
2470 {
2471         return bmain->id_tag_update[((char *)&idtype)[0]];
2472 }
2473
2474 #if 0 // UNUSED
2475 /* recursively descends tree, each node only checked once */
2476 /* node is checked to be of type object */
2477 static int parent_check_node(DagNode *node, int curtime)
2478 {
2479         DagAdjList *itA;
2480         
2481         node->lasttime = curtime;
2482         
2483         if (node->color == DAG_GRAY)
2484                 return DAG_GRAY;
2485         
2486         for (itA = node->child; itA; itA = itA->next) {
2487                 if (itA->node->type == ID_OB) {
2488                         
2489                         if (itA->node->color == DAG_GRAY)
2490                                 return DAG_GRAY;
2491
2492                         /* descend if not done */
2493                         if (itA->node->lasttime != curtime) {
2494                                 itA->node->color = parent_check_node(itA->node, curtime);
2495                         
2496                                 if (itA->node->color == DAG_GRAY)
2497                                         return DAG_GRAY;
2498                         }
2499                 }
2500         }
2501         
2502         return DAG_WHITE;
2503 }
2504 #endif
2505
2506 /* ******************* DAG FOR ARMATURE POSE ***************** */
2507
2508 /* we assume its an armature with pose */
2509 void DAG_pose_sort(Object *ob)
2510 {
2511         bPose *pose = ob->pose;
2512         bPoseChannel *pchan;
2513         bConstraint *con;
2514         DagNode *node;
2515         DagNode *node2, *node3;
2516         DagNode *rootnode;
2517         DagForest *dag;
2518         DagNodeQueue *nqueue;
2519         DagAdjList *itA;
2520         ListBase tempbase;
2521         int skip = 0;
2522         
2523         dag = dag_init();
2524         ugly_hack_sorry = 0;  /* no ID structs */
2525
2526         rootnode = dag_add_node(dag, NULL);  /* node->ob becomes NULL */
2527         
2528         /* we add the hierarchy and the constraints */
2529         for (pchan = pose->chanbase.first; pchan; pchan = pchan->next) {
2530                 int addtoroot = 1;
2531                 
2532                 node = dag_get_node(dag, pchan);
2533                 
2534                 if (pchan->parent) {
2535                         node2 = dag_get_node(dag, pchan->parent);
2536                         dag_add_relation(dag, node2, node, 0, "Parent Relation");
2537                         addtoroot = 0;
2538                 }
2539                 for (con = pchan->constraints.first; con; con = con->next) {
2540                         bConstraintTypeInfo *cti = BKE_constraint_get_typeinfo(con);
2541                         ListBase targets = {NULL, NULL};
2542                         bConstraintTarget *ct;
2543                         
2544                         if (cti && cti->get_constraint_targets) {
2545                                 cti->get_constraint_targets(con, &targets);
2546                                 
2547                                 for (ct = targets.first; ct; ct = ct->next) {
2548                                         if (ct->tar == ob && ct->subtarget[0]) {
2549                                                 bPoseChannel *target = BKE_pose_channel_find_name(ob->pose, ct->subtarget);
2550                                                 if (target) {
2551                                                         node2 = dag_get_node(dag, target);
2552                                                         dag_add_relation(dag, node2, node, 0, "Pose Constraint");
2553                                                         
2554                                                         if (con->type == CONSTRAINT_TYPE_KINEMATIC) {
2555                                                                 bKinematicConstraint *data = (bKinematicConstraint *)con->data;
2556                                                                 bPoseChannel *parchan;
2557                                                                 int segcount = 0;
2558                                                                 
2559                                                                 /* exclude tip from chain? */
2560                                                                 if (!(data->flag & CONSTRAINT_IK_TIP))
2561                                                                         parchan = pchan->parent;
2562                                                                 else
2563                                                                         parchan = pchan;
2564                                                                 
2565                                                                 /* Walk to the chain's root */
2566                                                                 while (parchan) {
2567                                                                         node3 = dag_get_node(dag, parchan);
2568                                                                         dag_add_relation(dag, node2, node3, 0, "IK Constraint");
2569                                                                         
2570                                                                         segcount++;
2571                                                                         if (segcount == data->rootbone || segcount > 255) break;  /* 255 is weak */
2572                                                                         parchan = parchan->parent;
2573                                                                 }
2574                                                         }
2575                                                 }
2576                                         }
2577                                 }
2578                                 
2579                                 if (cti->flush_constraint_targets)
2580                                         cti->flush_constraint_targets(con, &targets, 1);
2581                         }
2582                 }
2583                 if (addtoroot == 1) {
2584                         dag_add_relation(dag, rootnode, node, 0, "Root Bone Relation");
2585                 }
2586         }
2587
2588         dag_check_cycle(dag);
2589         
2590         /* now we try to sort... */
2591         tempbase.first = tempbase.last = NULL;
2592
2593         nqueue = queue_create(DAGQUEUEALLOC);
2594         
2595         /* tag nodes unchecked */
2596         for (node = dag->DagNode.first; node; node = node->next)
2597                 node->color = DAG_WHITE;
2598         
2599         rootnode->color = DAG_GRAY;
2600         push_stack(nqueue, rootnode);  
2601         
2602         while (nqueue->count) {
2603                 
2604                 skip = 0;
2605                 node = get_top_node_queue(nqueue);
2606                 
2607                 itA = node->child;
2608                 while (itA != NULL) {
2609                         if (itA->node->color == DAG_WHITE) {
2610                                 itA->node->color = DAG_GRAY;
2611                                 push_stack(nqueue, itA->node);
2612                                 skip = 1;
2613                                 break;
2614                         }
2615                         itA = itA->next;
2616                 }
2617                 
2618                 if (!skip) {
2619                         if (node) {
2620                                 node = pop_queue(nqueue);
2621                                 if (node->ob == NULL)  /* we are done */
2622                                         break;
2623                                 node->color = DAG_BLACK;
2624                                 
2625                                 /* put node in new list */
2626                                 BLI_remlink(&pose->chanbase, node->ob);
2627                                 BLI_addhead(&tempbase, node->ob);
2628                         }
2629                 }
2630         }
2631         
2632         /* temporal correction for circular dependencies */
2633         while (pose->chanbase.first) {
2634                 pchan = pose->chanbase.first;
2635                 BLI_remlink(&pose->chanbase, pchan);
2636                 BLI_addhead(&tempbase, pchan);
2637
2638                 printf("cyclic %s\n", pchan->name);
2639         }
2640         
2641         pose->chanbase = tempbase;
2642         queue_delete(nqueue);
2643         
2644 //      printf("\nordered\n");
2645 //      for (pchan = pose->chanbase.first; pchan; pchan = pchan->next) {
2646 //              printf(" %s\n", pchan->name);
2647 //      }
2648         
2649         free_forest(dag);
2650         MEM_freeN(dag);
2651         
2652         ugly_hack_sorry = 1;
2653 }
2654
2655 /* ************************ DAG DEBUGGING ********************* */
2656
2657 void DAG_print_dependencies(Main *bmain, Scene *scene, Object *ob)
2658 {
2659         /* utility for debugging dependencies */
2660         dag_print_dependencies = 1;
2661
2662         if (ob && (ob->mode & OB_MODE_POSE)) {
2663                 printf("\nDEPENDENCY RELATIONS for %s\n\n", ob->id.name + 2);
2664                 DAG_pose_sort(ob);
2665         }
2666         else {
2667                 printf("\nDEPENDENCY RELATIONS for %s\n\n", scene->id.name + 2);
2668                 DAG_scene_relations_rebuild(bmain, scene);
2669         }
2670         
2671         dag_print_dependencies = 0;
2672 }
2673