Merge branch 'master' into blender2.8
[blender.git] / source / blender / depsgraph / intern / depsgraph.cc
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) 2013 Blender Foundation.
19  * All rights reserved.
20  *
21  * Original Author: Joshua Leung
22  * Contributor(s): Sergey Sharybin
23  *
24  * ***** END GPL LICENSE BLOCK *****
25  */
26
27 /** \file blender/depsgraph/intern/depsgraph.cc
28  *  \ingroup depsgraph
29  *
30  * Core routines for how the Depsgraph works.
31  */
32
33 #include "intern/depsgraph.h" /* own include */
34
35 #include "MEM_guardedalloc.h"
36
37 #include "BLI_utildefines.h"
38 #include "BLI_console.h"
39 #include "BLI_hash.h"
40 #include "BLI_ghash.h"
41 #include "BLI_listbase.h"
42
43 extern "C" {
44 #include "DNA_action_types.h"
45 #include "DNA_armature_types.h"
46 #include "DNA_constraint_types.h"
47 #include "DNA_key_types.h"
48 #include "DNA_object_types.h"
49 #include "DNA_sequence_types.h"
50
51 #include "RNA_access.h"
52
53 #include "BKE_scene.h"
54 }
55
56 #include <algorithm>
57 #include <cstring>
58
59 #include "DEG_depsgraph.h"
60
61 #include "intern/eval/deg_eval_copy_on_write.h"
62
63 #include "intern/nodes/deg_node.h"
64 #include "intern/nodes/deg_node_component.h"
65 #include "intern/nodes/deg_node_id.h"
66 #include "intern/nodes/deg_node_operation.h"
67 #include "intern/nodes/deg_node_time.h"
68
69 #include "intern/depsgraph_intern.h"
70 #include "util/deg_util_foreach.h"
71
72 static bool use_copy_on_write = false;
73
74 bool DEG_depsgraph_use_copy_on_write(void)
75 {
76         return use_copy_on_write;
77 }
78
79 void DEG_depsgraph_enable_copy_on_write(void)
80 {
81         use_copy_on_write = true;
82 }
83
84 namespace DEG {
85
86 static DEG_EditorUpdateIDCb deg_editor_update_id_cb = NULL;
87 static DEG_EditorUpdateSceneCb deg_editor_update_scene_cb = NULL;
88
89 /* TODO(sergey): Find a better place for this. */
90 template <typename T>
91 static void remove_from_vector(vector<T> *vector, const T& value)
92 {
93         vector->erase(std::remove(vector->begin(), vector->end(), value),
94                       vector->end());
95 }
96
97 Depsgraph::Depsgraph(Scene *scene,
98                      ViewLayer *view_layer,
99                      eEvaluationMode mode)
100   : time_source(NULL),
101     need_update(true),
102     scene(scene),
103     view_layer(view_layer),
104     mode(mode),
105     ctime(BKE_scene_frame_get(scene))
106 {
107         BLI_spin_init(&lock);
108         id_hash = BLI_ghash_ptr_new("Depsgraph id hash");
109         entry_tags = BLI_gset_ptr_new("Depsgraph entry_tags");
110 }
111
112 Depsgraph::~Depsgraph()
113 {
114         clear_id_nodes();
115         BLI_ghash_free(id_hash, NULL, NULL);
116         BLI_gset_free(entry_tags, NULL);
117         if (time_source != NULL) {
118                 OBJECT_GUARDED_DELETE(time_source, TimeSourceDepsNode);
119         }
120         BLI_spin_end(&lock);
121 }
122
123 /* Query Conditions from RNA ----------------------- */
124
125 static bool pointer_to_component_node_criteria(
126         const PointerRNA *ptr,
127         const PropertyRNA *prop,
128         ID **id,
129         eDepsNode_Type *type,
130         const char **subdata,
131         eDepsOperation_Code *operation_code,
132         const char **operation_name,
133         int *operation_name_tag)
134 {
135         if (ptr->type == NULL) {
136                 return false;
137         }
138         /* Set default values for returns. */
139         *id = (ID *)ptr->id.data;
140         *subdata = "";
141         *operation_code = DEG_OPCODE_OPERATION;
142         *operation_name = "";
143         *operation_name_tag = -1;
144         /* Handling of commonly known scenarios. */
145         if (ptr->type == &RNA_PoseBone) {
146                 bPoseChannel *pchan = (bPoseChannel *)ptr->data;
147                 if (prop != NULL && RNA_property_is_idprop(prop)) {
148                         *type = DEG_NODE_TYPE_PARAMETERS;
149                         *subdata = "";
150                         *operation_code = DEG_OPCODE_PARAMETERS_EVAL;
151                         *operation_name = pchan->name;
152                 }
153                 else {
154                         /* Bone - generally, we just want the bone component. */
155                         *type = DEG_NODE_TYPE_BONE;
156                         *subdata = pchan->name;
157                 }
158                 return true;
159         }
160         else if (ptr->type == &RNA_Bone) {
161                 Bone *bone = (Bone *)ptr->data;
162                 /* armature-level bone, but it ends up going to bone component anyway */
163                 // NOTE: the ID in thise case will end up being bArmature.
164                 *type = DEG_NODE_TYPE_BONE;
165                 *subdata = bone->name;
166                 return true;
167         }
168         else if (RNA_struct_is_a(ptr->type, &RNA_Constraint)) {
169                 Object *object = (Object *)ptr->id.data;
170                 bConstraint *con = (bConstraint *)ptr->data;
171                 /* Check whether is object or bone constraint. */
172                 /* NOTE: Currently none of the area can address transform of an object
173                  * at a given constraint, but for rigging one might use constraint
174                  * influence to be used to drive some corrective shape keys or so.
175                  */
176                 if (BLI_findindex(&object->constraints, con) != -1) {
177                         *type = DEG_NODE_TYPE_TRANSFORM;
178                         *operation_code = DEG_OPCODE_TRANSFORM_LOCAL;
179                         return true;
180                 }
181                 else if (object->pose != NULL) {
182                         LISTBASE_FOREACH(bPoseChannel *, pchan, &object->pose->chanbase) {
183                                 if (BLI_findindex(&pchan->constraints, con) != -1) {
184                                         *type = DEG_NODE_TYPE_BONE;
185                                         *operation_code = DEG_OPCODE_BONE_LOCAL;
186                                         *subdata = pchan->name;
187                                         return true;
188                                 }
189                         }
190                 }
191         }
192         else if (RNA_struct_is_a(ptr->type, &RNA_Modifier)) {
193                 *type = DEG_NODE_TYPE_GEOMETRY;
194                 return true;
195         }
196         else if (ptr->type == &RNA_Object) {
197                 /* Transforms props? */
198                 if (prop != NULL) {
199                         const char *prop_identifier = RNA_property_identifier((PropertyRNA *)prop);
200                         /* TODO(sergey): How to optimize this? */
201                         if (strstr(prop_identifier, "location") ||
202                             strstr(prop_identifier, "rotation") ||
203                             strstr(prop_identifier, "scale") ||
204                             strstr(prop_identifier, "matrix_"))
205                         {
206                                 *type = DEG_NODE_TYPE_TRANSFORM;
207                                 return true;
208                         }
209                         else if (strstr(prop_identifier, "data")) {
210                                 /* We access object.data, most likely a geometry.
211                                  * Might be a bone tho..
212                                  */
213                                 *type = DEG_NODE_TYPE_GEOMETRY;
214                                 return true;
215                         }
216                 }
217         }
218         else if (ptr->type == &RNA_ShapeKey) {
219                 *id = (ID *)ptr->id.data;
220                 *type = DEG_NODE_TYPE_GEOMETRY;
221                 return true;
222         }
223         else if (ptr->type == &RNA_Key) {
224                 *id = (ID *)ptr->id.data;
225                 *type = DEG_NODE_TYPE_GEOMETRY;
226                 return true;
227         }
228         else if (RNA_struct_is_a(ptr->type, &RNA_Sequence)) {
229                 Sequence *seq = (Sequence *)ptr->data;
230                 /* Sequencer strip */
231                 *type = DEG_NODE_TYPE_SEQUENCER;
232                 *subdata = seq->name; // xxx?
233                 return true;
234         }
235         else if (RNA_struct_is_a(ptr->type, &RNA_NodeSocket)) {
236                 *type = DEG_NODE_TYPE_SHADING;
237                 return true;
238         }
239         else if (ptr->type == &RNA_Curve) {
240                 *id = (ID *)ptr->id.data;
241                 *type = DEG_NODE_TYPE_GEOMETRY;
242                 return true;
243         }
244         if (prop != NULL) {
245                 /* All unknown data effectively falls under "parameter evaluation". */
246                 if (RNA_property_is_idprop(prop)) {
247                         *type = DEG_NODE_TYPE_PARAMETERS;
248                         *operation_code = DEG_OPCODE_ID_PROPERTY;
249                         *operation_name = RNA_property_identifier((PropertyRNA *)prop);
250                         *operation_name_tag = -1;
251                 }
252                 else {
253                         *type = DEG_NODE_TYPE_PARAMETERS;
254                         *operation_code = DEG_OPCODE_PARAMETERS_EVAL;
255                         *operation_name = "";
256                         *operation_name_tag = -1;
257                 }
258                 return true;
259         }
260         return false;
261 }
262
263 /* Convenience wrapper to find node given just pointer + property. */
264 DepsNode *Depsgraph::find_node_from_pointer(const PointerRNA *ptr,
265                                             const PropertyRNA *prop) const
266 {
267         ID *id;
268         eDepsNode_Type node_type;
269         const char *component_name, *operation_name;
270         eDepsOperation_Code operation_code;
271         int operation_name_tag;
272
273         if (pointer_to_component_node_criteria(
274                          ptr, prop,
275                          &id, &node_type, &component_name,
276                          &operation_code, &operation_name, &operation_name_tag))
277         {
278                 IDDepsNode *id_node = find_id_node(id);
279                 if (id_node == NULL) {
280                         return NULL;
281                 }
282                 ComponentDepsNode *comp_node =
283                         id_node->find_component(node_type, component_name);
284                 if (comp_node == NULL) {
285                         return NULL;
286                 }
287                 if (operation_code == DEG_OPCODE_OPERATION) {
288                         return comp_node;
289                 }
290                 return comp_node->find_operation(operation_code,
291                                                  operation_name,
292                                                  operation_name_tag);
293         }
294         return NULL;
295 }
296
297 /* Node Management ---------------------------- */
298
299 TimeSourceDepsNode *Depsgraph::add_time_source()
300 {
301         if (time_source == NULL) {
302                 DepsNodeFactory *factory = deg_type_get_factory(DEG_NODE_TYPE_TIMESOURCE);
303                 time_source = (TimeSourceDepsNode *)factory->create_node(NULL, "", "Time Source");
304         }
305         return time_source;
306 }
307
308 TimeSourceDepsNode *Depsgraph::find_time_source() const
309 {
310         return time_source;
311 }
312
313 IDDepsNode *Depsgraph::find_id_node(const ID *id) const
314 {
315         return reinterpret_cast<IDDepsNode *>(BLI_ghash_lookup(id_hash, id));
316 }
317
318 IDDepsNode *Depsgraph::add_id_node(ID *id, ID *id_cow_hint)
319 {
320         BLI_assert((id->tag & LIB_TAG_COPY_ON_WRITE) == 0);
321         IDDepsNode *id_node = find_id_node(id);
322         if (!id_node) {
323                 DepsNodeFactory *factory = deg_type_get_factory(DEG_NODE_TYPE_ID_REF);
324                 id_node = (IDDepsNode *)factory->create_node(id, "", id->name);
325                 id_node->init_copy_on_write(id_cow_hint);
326                 /* Register node in ID hash.
327                  *
328                  * NOTE: We address ID nodes by the original ID pointer they are
329                  * referencing to.
330                  */
331                 BLI_ghash_insert(id_hash, id, id_node);
332                 id_nodes.push_back(id_node);
333         }
334         return id_node;
335 }
336
337 void Depsgraph::clear_id_nodes()
338 {
339         /* Free memory used by ID nodes. */
340         if (use_copy_on_write) {
341                 /* Stupid workaround to ensure we free IDs in a proper order. */
342                 foreach (IDDepsNode *id_node, id_nodes) {
343                         if (id_node->id_cow == NULL) {
344                                 /* This means builder "stole" ownership of the copy-on-written
345                                  * datablock for her own dirty needs.
346                                  */
347                                 continue;
348                         }
349                         if (!deg_copy_on_write_is_expanded(id_node->id_cow)) {
350                                 continue;
351                         }
352                         const ID_Type id_type = GS(id_node->id_cow->name);
353                         if (id_type != ID_PA) {
354                                 id_node->destroy();
355                         }
356                 }
357         }
358         foreach (IDDepsNode *id_node, id_nodes) {
359                 OBJECT_GUARDED_DELETE(id_node, IDDepsNode);
360         }
361         /* Clear containers. */
362         BLI_ghash_clear(id_hash, NULL, NULL);
363         id_nodes.clear();
364 }
365
366 /* Add new relationship between two nodes. */
367 DepsRelation *Depsgraph::add_new_relation(OperationDepsNode *from,
368                                           OperationDepsNode *to,
369                                           const char *description,
370                                           bool check_unique)
371 {
372         DepsRelation *rel = NULL;
373         if (check_unique) {
374                 rel = check_nodes_connected(from, to, description);
375         }
376         if (rel != NULL) {
377                 return rel;
378         }
379         /* Create new relation, and add it to the graph. */
380         rel = OBJECT_GUARDED_NEW(DepsRelation, from, to, description);
381         /* TODO(sergey): Find a better place for this. */
382 #ifdef WITH_OPENSUBDIV
383         ComponentDepsNode *comp_node = from->owner;
384         if (comp_node->type == DEG_NODE_TYPE_GEOMETRY) {
385                 IDDepsNode *id_to = to->owner->owner;
386                 IDDepsNode *id_from = from->owner->owner;
387                 if (id_to != id_from && (id_to->id_orig->recalc & ID_RECALC_ALL)) {
388                         if ((id_from->eval_flags & DAG_EVAL_NEED_CPU) == 0) {
389                                 id_from->tag_update(this);
390                                 id_from->eval_flags |= DAG_EVAL_NEED_CPU;
391                         }
392                 }
393         }
394 #endif
395         return rel;
396 }
397
398 /* Add new relation between two nodes */
399 DepsRelation *Depsgraph::add_new_relation(DepsNode *from, DepsNode *to,
400                                           const char *description,
401                                           bool check_unique)
402 {
403         DepsRelation *rel = NULL;
404         if (check_unique) {
405                 rel = check_nodes_connected(from, to, description);
406         }
407         if (rel != NULL) {
408                 return rel;
409         }
410         /* Create new relation, and add it to the graph. */
411         rel = OBJECT_GUARDED_NEW(DepsRelation, from, to, description);
412         return rel;
413 }
414
415 DepsRelation *Depsgraph::check_nodes_connected(const DepsNode *from,
416                                                const DepsNode *to,
417                                                const char *description)
418 {
419         foreach (DepsRelation *rel, from->outlinks) {
420                 BLI_assert(rel->from == from);
421                 if (rel->to != to) {
422                         continue;
423                 }
424                 if (description != NULL && !STREQ(rel->name, description)) {
425                         continue;
426                 }
427                 return rel;
428         }
429         return NULL;
430 }
431
432 /* ************************ */
433 /* Relationships Management */
434
435 DepsRelation::DepsRelation(DepsNode *from,
436                            DepsNode *to,
437                            const char *description)
438   : from(from),
439     to(to),
440     name(description),
441     flag(0)
442 {
443         /* Hook it up to the nodes which use it.
444          *
445          * NOTE: We register relation in the nodes which this link connects to here
446          * in constructor but we don't unregister it in the destructor.
447          *
448          * Reasoning:
449          *
450          * - Destructor is currently used on global graph destruction, so there's no
451          *   real need in avoiding dangling pointers, all the memory is to be freed
452          *   anyway.
453          *
454          * - Unregistering relation is not a cheap operation, so better to have it
455          *   as an explicit call if we need this.
456          */
457         from->outlinks.push_back(this);
458         to->inlinks.push_back(this);
459 }
460
461 DepsRelation::~DepsRelation()
462 {
463         /* Sanity check. */
464         BLI_assert(from != NULL && to != NULL);
465 }
466
467 void DepsRelation::unlink()
468 {
469         /* Sanity check. */
470         BLI_assert(from != NULL && to != NULL);
471         remove_from_vector(&from->outlinks, this);
472         remove_from_vector(&to->inlinks, this);
473 }
474
475 /* Low level tagging -------------------------------------- */
476
477 /* Tag a specific node as needing updates. */
478 void Depsgraph::add_entry_tag(OperationDepsNode *node)
479 {
480         /* Sanity check. */
481         if (node == NULL) {
482                 return;
483         }
484         /* Add to graph-level set of directly modified nodes to start searching from.
485          * NOTE: this is necessary since we have several thousand nodes to play with...
486          */
487         BLI_gset_insert(entry_tags, node);
488 }
489
490 void Depsgraph::clear_all_nodes()
491 {
492         clear_id_nodes();
493         if (time_source != NULL) {
494                 OBJECT_GUARDED_DELETE(time_source, TimeSourceDepsNode);
495                 time_source = NULL;
496         }
497 }
498
499 ID *Depsgraph::get_cow_id(const ID *id_orig) const
500 {
501         IDDepsNode *id_node = find_id_node(id_orig);
502         if (id_node == NULL) {
503                 /* This function is used from places where we expect ID to be either
504                  * already a copy-on-write version or have a corresponding copy-on-write
505                  * version.
506                  *
507                  * We try to enforce that in debug builds, for for release we play a bit
508                  * safer game here.
509                  */
510                 if ((id_orig->tag & LIB_TAG_COPY_ON_WRITE) == 0) {
511                         /* TODO(sergey): This is nice sanity check to have, but it fails
512                          * in following situations:
513                          *
514                          * - Material has link to texture, which is not needed by new
515                          *   shading system and hence can be ignored at construction.
516                          * - Object or mesh has material at a slot which is not used (for
517                          *   example, object has material slot by materials are set to
518                          *   object data).
519                          */
520                         // BLI_assert(!"Request for non-existing copy-on-write ID");
521                 }
522                 return (ID *)id_orig;
523         }
524         return id_node->id_cow;
525 }
526
527 void deg_editors_id_update(const DEGEditorUpdateContext *update_ctx, ID *id)
528 {
529         if (deg_editor_update_id_cb != NULL) {
530                 deg_editor_update_id_cb(update_ctx, id);
531         }
532 }
533
534 void deg_editors_scene_update(const DEGEditorUpdateContext *update_ctx,
535                               bool updated)
536 {
537         if (deg_editor_update_scene_cb != NULL) {
538                 deg_editor_update_scene_cb(update_ctx, updated);
539         }
540 }
541
542 bool deg_terminal_do_color(void)
543 {
544         return (G.debug & G_DEBUG_DEPSGRAPH_PRETTY) != 0;
545 }
546
547 string deg_color_for_pointer(const void *pointer)
548 {
549         if (!deg_terminal_do_color()) {
550                 return "";
551         }
552         int r, g, b;
553         BLI_hash_pointer_to_color(pointer, &r, &g, &b);
554         char buffer[64];
555         BLI_snprintf(buffer, sizeof(buffer), TRUECOLOR_ANSI_COLOR_FORMAT, r, g, b);
556         return string(buffer);
557 }
558
559 string deg_color_end(void)
560 {
561         if (!deg_terminal_do_color()) {
562                 return "";
563         }
564         return string(TRUECOLOR_ANSI_COLOR_FINISH);
565 }
566
567 }  // namespace DEG
568
569 /* **************** */
570 /* Public Graph API */
571
572 /* Initialize a new Depsgraph */
573 Depsgraph *DEG_graph_new(Scene *scene,
574                          ViewLayer *view_layer,
575                          eEvaluationMode mode)
576 {
577         DEG::Depsgraph *deg_depsgraph = OBJECT_GUARDED_NEW(DEG::Depsgraph,
578                                                            scene,
579                                                            view_layer,
580                                                            mode);
581         return reinterpret_cast<Depsgraph *>(deg_depsgraph);
582 }
583
584 /* Free graph's contents and graph itself */
585 void DEG_graph_free(Depsgraph *graph)
586 {
587         using DEG::Depsgraph;
588         DEG::Depsgraph *deg_depsgraph = reinterpret_cast<DEG::Depsgraph *>(graph);
589         OBJECT_GUARDED_DELETE(deg_depsgraph, Depsgraph);
590 }
591
592 /* Set callbacks which are being called when depsgraph changes. */
593 void DEG_editors_set_update_cb(DEG_EditorUpdateIDCb id_func,
594                                DEG_EditorUpdateSceneCb scene_func)
595 {
596         DEG::deg_editor_update_id_cb = id_func;
597         DEG::deg_editor_update_scene_cb = scene_func;
598 }
599
600 /* Evaluation and debug */
601
602 void DEG_debug_print_eval(const char *function_name,
603                           const char *object_name,
604                           const void *object_address)
605 {
606         if ((G.debug & G_DEBUG_DEPSGRAPH_EVAL) == 0) {
607                 return;
608         }
609         fprintf(stdout,
610                 "%s on %s %s(%p)%s\n",
611                 function_name,
612                 object_name,
613                 DEG::deg_color_for_pointer(object_address).c_str(),
614                 object_address,
615                 DEG::deg_color_end().c_str());
616         fflush(stdout);
617 }
618
619 void DEG_debug_print_eval_subdata(const char *function_name,
620                                   const char *object_name,
621                                   const void *object_address,
622                                   const char *subdata_comment,
623                                   const char *subdata_name,
624                                   const void *subdata_address)
625 {
626         if ((G.debug & G_DEBUG_DEPSGRAPH_EVAL) == 0) {
627                 return;
628         }
629         fprintf(stdout,
630                 "%s on %s %s(%p)%s %s %s %s(%p)%s\n",
631                 function_name,
632                 object_name,
633                 DEG::deg_color_for_pointer(object_address).c_str(),
634                 object_address,
635                 DEG::deg_color_end().c_str(),
636                 subdata_comment,
637                 subdata_name,
638                 DEG::deg_color_for_pointer(subdata_address).c_str(),
639                 subdata_address,
640                 DEG::deg_color_end().c_str());
641         fflush(stdout);
642 }
643
644 void DEG_debug_print_eval_subdata_index(const char *function_name,
645                                         const char *object_name,
646                                         const void *object_address,
647                                         const char *subdata_comment,
648                                         const char *subdata_name,
649                                         const void *subdata_address,
650                                         const int subdata_index)
651 {
652         if ((G.debug & G_DEBUG_DEPSGRAPH_EVAL) == 0) {
653                 return;
654         }
655         fprintf(stdout,
656                 "%s on %s %s(%p)^%s %s %s[%d] %s(%p)%s\n",
657                 function_name,
658                 object_name,
659                 DEG::deg_color_for_pointer(object_address).c_str(),
660                 object_address,
661                 DEG::deg_color_end().c_str(),
662                 subdata_comment,
663                 subdata_name,
664                 subdata_index,
665                 DEG::deg_color_for_pointer(subdata_address).c_str(),
666                 subdata_address,
667                 DEG::deg_color_end().c_str());
668         fflush(stdout);
669 }
670
671 void DEG_debug_print_eval_time(const char *function_name,
672                                const char *object_name,
673                                const void *object_address,
674                                float time)
675 {
676         if ((G.debug & G_DEBUG_DEPSGRAPH_EVAL) == 0) {
677                 return;
678         }
679         fprintf(stdout,
680                 "%s on %s %s(%p)%s at time %f\n",
681                 function_name,
682                 object_name,
683                 DEG::deg_color_for_pointer(object_address).c_str(),
684                 object_address,
685                 DEG::deg_color_end().c_str(),
686                 time);
687         fflush(stdout);
688 }