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