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