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