Depsgraph: Comb code to a better state all over
[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 #include "BKE_constraint.h"
55 #include "BKE_global.h"
56 }
57
58 #include <algorithm>
59 #include <cstring>
60
61 #include "DEG_depsgraph.h"
62 #include "DEG_depsgraph_debug.h"
63
64 #include "intern/depsgraph_update.h"
65
66 #include "intern/eval/deg_eval_copy_on_write.h"
67
68 #include "intern/node/deg_node.h"
69 #include "intern/node/deg_node_component.h"
70 #include "intern/node/deg_node_factory.h"
71 #include "intern/node/deg_node_id.h"
72 #include "intern/node/deg_node_operation.h"
73 #include "intern/node/deg_node_time.h"
74
75 #include "intern/depsgraph_physics.h"
76
77 namespace DEG {
78
79 /* TODO(sergey): Find a better place for this. */
80 template <typename T>
81 static void remove_from_vector(vector<T> *vector, const T& value)
82 {
83         vector->erase(std::remove(vector->begin(), vector->end(), value),
84                       vector->end());
85 }
86
87 Depsgraph::Depsgraph(Scene *scene,
88                      ViewLayer *view_layer,
89                      eEvaluationMode mode)
90   : time_source(NULL),
91     need_update(true),
92     scene(scene),
93     view_layer(view_layer),
94     mode(mode),
95     ctime(BKE_scene_frame_get(scene)),
96     scene_cow(NULL),
97     is_active(false),
98     debug_is_evaluating(false)
99 {
100         BLI_spin_init(&lock);
101         id_hash = BLI_ghash_ptr_new("Depsgraph id hash");
102         entry_tags = BLI_gset_ptr_new("Depsgraph entry_tags");
103         debug_flags = G.debug;
104         memset(id_type_updated, 0, sizeof(id_type_updated));
105         memset(physics_relations, 0, sizeof(physics_relations));
106 }
107
108 Depsgraph::~Depsgraph()
109 {
110         clear_id_nodes();
111         BLI_ghash_free(id_hash, NULL, NULL);
112         BLI_gset_free(entry_tags, NULL);
113         if (time_source != NULL) {
114                 OBJECT_GUARDED_DELETE(time_source, TimeSourceNode);
115         }
116         BLI_spin_end(&lock);
117 }
118
119 /* Query Conditions from RNA ----------------------- */
120
121 static bool pointer_to_component_node_criteria(
122         const PointerRNA *ptr,
123         const PropertyRNA *prop,
124         RNAPointerSource /*source*/,
125         ID **id,
126         NodeType *type,
127         const char **component_name,
128         OperationCode *operation_code,
129         const char **operation_name,
130         int *operation_name_tag)
131 {
132         if (ptr->type == NULL) {
133                 return false;
134         }
135         /* Set default values for returns. */
136         *id = (ID *)ptr->id.data;
137         *component_name = "";
138         *operation_code = OperationCode::OPERATION;
139         *operation_name = "";
140         *operation_name_tag = -1;
141         /* Handling of commonly known scenarios. */
142         if (ptr->type == &RNA_PoseBone) {
143                 bPoseChannel *pchan = (bPoseChannel *)ptr->data;
144                 if (prop != NULL && RNA_property_is_idprop(prop)) {
145                         *type = NodeType::PARAMETERS;
146                         *operation_code = OperationCode::ID_PROPERTY;
147                         *operation_name = RNA_property_identifier((PropertyRNA *)prop);
148                         *operation_name_tag = -1;
149                 }
150                 else {
151                         /* Bone - generally, we just want the bone component. */
152                         *type = NodeType::BONE;
153                         *component_name = pchan->name;
154                         /* But B-Bone properties should connect to the actual operation. */
155                         if (!ELEM(NULL, pchan->bone, prop) && pchan->bone->segments > 1 &&
156                             STRPREFIX(RNA_property_identifier(prop), "bbone_"))
157                         {
158                                 *operation_code = OperationCode::BONE_SEGMENTS;
159                         }
160                 }
161                 return true;
162         }
163         else if (ptr->type == &RNA_Bone) {
164                 Bone *bone = (Bone *)ptr->data;
165                 /* armature-level bone, but it ends up going to bone component anyway */
166                 // NOTE: the ID in this case will end up being bArmature.
167                 *type = NodeType::BONE;
168                 *component_name = bone->name;
169                 return true;
170         }
171         else if (RNA_struct_is_a(ptr->type, &RNA_Constraint)) {
172                 Object *object = (Object *)ptr->id.data;
173                 bConstraint *con = (bConstraint *)ptr->data;
174                 /* Check whether is object or bone constraint. */
175                 /* NOTE: Currently none of the area can address transform of an object
176                  * at a given constraint, but for rigging one might use constraint
177                  * influence to be used to drive some corrective shape keys or so. */
178                 if (BLI_findindex(&object->constraints, con) != -1) {
179                         *type = NodeType::TRANSFORM;
180                         *operation_code = OperationCode::TRANSFORM_LOCAL;
181                         return true;
182                 }
183                 else if (object->pose != NULL) {
184                         LISTBASE_FOREACH(bPoseChannel *, pchan, &object->pose->chanbase) {
185                                 if (BLI_findindex(&pchan->constraints, con) != -1) {
186                                         *type = NodeType::BONE;
187                                         *operation_code = OperationCode::BONE_LOCAL;
188                                         *component_name = pchan->name;
189                                         return true;
190                                 }
191                         }
192                 }
193         }
194         else if (ELEM(ptr->type, &RNA_ConstraintTarget, &RNA_ConstraintTargetBone)) {
195                 Object *object = (Object *)ptr->id.data;
196                 bConstraintTarget *tgt = (bConstraintTarget *)ptr->data;
197                 /* Check whether is object or bone constraint. */
198                 bPoseChannel *pchan = NULL;
199                 bConstraint *con = BKE_constraint_find_from_target(object, tgt, &pchan);
200                 if (con != NULL) {
201                         if (pchan != NULL) {
202                                 *type = NodeType::BONE;
203                                 *operation_code = OperationCode::BONE_LOCAL;
204                                 *component_name = pchan->name;
205                         }
206                         else {
207                                 *type = NodeType::TRANSFORM;
208                                 *operation_code = OperationCode::TRANSFORM_LOCAL;
209                         }
210                         return true;
211                 }
212         }
213         else if (RNA_struct_is_a(ptr->type, &RNA_Modifier)) {
214                 *type = NodeType::GEOMETRY;
215                 return true;
216         }
217         else if (ptr->type == &RNA_Object) {
218                 /* Transforms props? */
219                 if (prop != NULL) {
220                         const char *prop_identifier = RNA_property_identifier((PropertyRNA *)prop);
221                         /* TODO(sergey): How to optimize this? */
222                         if (strstr(prop_identifier, "location") ||
223                             strstr(prop_identifier, "rotation") ||
224                             strstr(prop_identifier, "scale") ||
225                             strstr(prop_identifier, "matrix_"))
226                         {
227                                 *type = NodeType::TRANSFORM;
228                                 return true;
229                         }
230                         else if (strstr(prop_identifier, "data")) {
231                                 /* We access object.data, most likely a geometry.
232                                  * Might be a bone tho. */
233                                 *type = NodeType::GEOMETRY;
234                                 return true;
235                         }
236                 }
237         }
238         else if (ptr->type == &RNA_ShapeKey) {
239                 KeyBlock *key_block = (KeyBlock *)ptr->data;
240                 *id = (ID *)ptr->id.data;
241                 *type = NodeType::PARAMETERS;
242                 *operation_code = OperationCode::PARAMETERS_EVAL;
243                 *operation_name = key_block->name;
244                 return true;
245         }
246         else if (ptr->type == &RNA_Key) {
247                 *id = (ID *)ptr->id.data;
248                 *type = NodeType::GEOMETRY;
249                 return true;
250         }
251         else if (RNA_struct_is_a(ptr->type, &RNA_Sequence)) {
252                 Sequence *seq = (Sequence *)ptr->data;
253                 /* Sequencer strip */
254                 *type = NodeType::SEQUENCER;
255                 *component_name = seq->name;
256                 return true;
257         }
258         else if (RNA_struct_is_a(ptr->type, &RNA_NodeSocket)) {
259                 *type = NodeType::SHADING;
260                 return true;
261         }
262         else if (RNA_struct_is_a(ptr->type, &RNA_ShaderNode)) {
263                 *type = NodeType::SHADING;
264                 return true;
265         }
266         else if (ELEM(ptr->type, &RNA_Curve, &RNA_TextCurve)) {
267                 *id = (ID *)ptr->id.data;
268                 *type = NodeType::GEOMETRY;
269                 return true;
270         }
271         if (prop != NULL) {
272                 /* All unknown data effectively falls under "parameter evaluation". */
273                 if (RNA_property_is_idprop(prop)) {
274                         *type = NodeType::PARAMETERS;
275                         *operation_code = OperationCode::ID_PROPERTY;
276                         *operation_name = RNA_property_identifier((PropertyRNA *)prop);
277                         *operation_name_tag = -1;
278                 }
279                 else {
280                         *type = NodeType::PARAMETERS;
281                         *operation_code = OperationCode::PARAMETERS_EVAL;
282                         *operation_name = "";
283                         *operation_name_tag = -1;
284                 }
285                 return true;
286         }
287         return false;
288 }
289
290 /* Convenience wrapper to find node given just pointer + property. */
291 Node *Depsgraph::find_node_from_pointer(const PointerRNA *ptr,
292                                         const PropertyRNA *prop,
293                                         RNAPointerSource source) const
294 {
295         ID *id;
296         NodeType node_type;
297         const char *component_name, *operation_name;
298         OperationCode operation_code;
299         int operation_name_tag;
300         if (pointer_to_component_node_criteria(
301                          ptr, prop, source,
302                          &id, &node_type, &component_name,
303                          &operation_code, &operation_name, &operation_name_tag))
304         {
305                 IDNode *id_node = find_id_node(id);
306                 if (id_node == NULL) {
307                         return NULL;
308                 }
309                 ComponentNode *comp_node =
310                         id_node->find_component(node_type, component_name);
311                 if (comp_node == NULL) {
312                         return NULL;
313                 }
314                 if (operation_code == OperationCode::OPERATION) {
315                         return comp_node;
316                 }
317                 return comp_node->find_operation(operation_code,
318                                                  operation_name,
319                                                  operation_name_tag);
320         }
321         return NULL;
322 }
323
324 /* Node Management ---------------------------- */
325
326 TimeSourceNode *Depsgraph::add_time_source()
327 {
328         if (time_source == NULL) {
329                 DepsNodeFactory *factory = type_get_factory(NodeType::TIMESOURCE);
330                 time_source = (TimeSourceNode *)factory->create_node(NULL, "", "Time Source");
331         }
332         return time_source;
333 }
334
335 TimeSourceNode *Depsgraph::find_time_source() const
336 {
337         return time_source;
338 }
339
340 IDNode *Depsgraph::find_id_node(const ID *id) const
341 {
342         return reinterpret_cast<IDNode *>(BLI_ghash_lookup(id_hash, id));
343 }
344
345 IDNode *Depsgraph::add_id_node(ID *id, ID *id_cow_hint)
346 {
347         BLI_assert((id->tag & LIB_TAG_COPIED_ON_WRITE) == 0);
348         IDNode *id_node = find_id_node(id);
349         if (!id_node) {
350                 DepsNodeFactory *factory = type_get_factory(NodeType::ID_REF);
351                 id_node = (IDNode *)factory->create_node(id, "", id->name);
352                 id_node->init_copy_on_write(id_cow_hint);
353                 /* Register node in ID hash.
354                  *
355                  * NOTE: We address ID nodes by the original ID pointer they are
356                  * referencing to. */
357                 BLI_ghash_insert(id_hash, id, id_node);
358                 id_nodes.push_back(id_node);
359         }
360         return id_node;
361 }
362
363 void Depsgraph::clear_id_nodes_conditional(const std::function <bool (ID_Type id_type)>& filter)
364 {
365         for (IDNode *id_node : id_nodes) {
366                 if (id_node->id_cow == NULL) {
367                         /* This means builder "stole" ownership of the copy-on-written
368                          * datablock for her own dirty needs. */
369                         continue;
370                 }
371                 if (!deg_copy_on_write_is_expanded(id_node->id_cow)) {
372                         continue;
373                 }
374                 const ID_Type id_type = GS(id_node->id_cow->name);
375                 if (filter(id_type)) {
376                         id_node->destroy();
377                 }
378         }
379 }
380
381 void Depsgraph::clear_id_nodes()
382 {
383         /* Free memory used by ID nodes. */
384
385         /* Stupid workaround to ensure we free IDs in a proper order. */
386         clear_id_nodes_conditional([](ID_Type id_type) { return id_type == ID_SCE; });
387         clear_id_nodes_conditional([](ID_Type id_type) { return id_type != ID_PA; });
388
389         for (IDNode *id_node : id_nodes) {
390                 OBJECT_GUARDED_DELETE(id_node, IDNode);
391         }
392         /* Clear containers. */
393         BLI_ghash_clear(id_hash, NULL, NULL);
394         id_nodes.clear();
395         /* Clear physics relation caches. */
396         clear_physics_relations(this);
397 }
398
399 /* Add new relation between two nodes */
400 Relation *Depsgraph::add_new_relation(Node *from, Node *to,
401                                       const char *description,
402                                       int flags)
403 {
404         Relation *rel = NULL;
405         if (flags & RELATION_CHECK_BEFORE_ADD) {
406                 rel = check_nodes_connected(from, to, description);
407         }
408         if (rel != NULL) {
409                 rel->flag |= flags;
410                 return rel;
411         }
412
413 #ifndef NDEBUG
414         if (from->type == NodeType::OPERATION &&
415             to->type == NodeType::OPERATION)
416         {
417                 OperationNode *operation_from = static_cast<OperationNode *>(from);
418                 OperationNode *operation_to = static_cast<OperationNode *>(to);
419                 BLI_assert(operation_to->owner->type != NodeType::COPY_ON_WRITE ||
420                            operation_from->owner->type == NodeType::COPY_ON_WRITE);
421         }
422 #endif
423
424         /* Create new relation, and add it to the graph. */
425         rel = OBJECT_GUARDED_NEW(Relation, from, to, description);
426         rel->flag |= flags;
427         return rel;
428 }
429
430 Relation *Depsgraph::check_nodes_connected(const Node *from,
431                                            const Node *to,
432                                            const char *description)
433 {
434         for (Relation *rel : from->outlinks) {
435                 BLI_assert(rel->from == from);
436                 if (rel->to != to) {
437                         continue;
438                 }
439                 if (description != NULL && !STREQ(rel->name, description)) {
440                         continue;
441                 }
442                 return rel;
443         }
444         return NULL;
445 }
446
447 /* ************************ */
448 /* Relationships Management */
449
450 Relation::Relation(Node *from, Node *to, const char *description)
451   : from(from),
452     to(to),
453     name(description),
454     flag(0)
455 {
456         /* Hook it up to the nodes which use it.
457          *
458          * NOTE: We register relation in the nodes which this link connects to here
459          * in constructor but we don't unregister it in the destructor.
460          *
461          * Reasoning:
462          *
463          * - Destructor is currently used on global graph destruction, so there's no
464          *   real need in avoiding dangling pointers, all the memory is to be freed
465          *   anyway.
466          *
467          * - Unregistering relation is not a cheap operation, so better to have it
468          *   as an explicit call if we need this. */
469         from->outlinks.push_back(this);
470         to->inlinks.push_back(this);
471 }
472
473 Relation::~Relation()
474 {
475         /* Sanity check. */
476         BLI_assert(from != NULL && to != NULL);
477 }
478
479 void Relation::unlink()
480 {
481         /* Sanity check. */
482         BLI_assert(from != NULL && to != NULL);
483         remove_from_vector(&from->outlinks, this);
484         remove_from_vector(&to->inlinks, this);
485 }
486
487 /* Low level tagging -------------------------------------- */
488
489 /* Tag a specific node as needing updates. */
490 void Depsgraph::add_entry_tag(OperationNode *node)
491 {
492         /* Sanity check. */
493         if (node == NULL) {
494                 return;
495         }
496         /* Add to graph-level set of directly modified nodes to start searching
497          * from.
498          * NOTE: this is necessary since we have several thousand nodes to play
499          * with. */
500         BLI_gset_insert(entry_tags, node);
501 }
502
503 void Depsgraph::clear_all_nodes()
504 {
505         clear_id_nodes();
506         if (time_source != NULL) {
507                 OBJECT_GUARDED_DELETE(time_source, TimeSourceNode);
508                 time_source = NULL;
509         }
510 }
511
512 ID *Depsgraph::get_cow_id(const ID *id_orig) const
513 {
514         IDNode *id_node = find_id_node(id_orig);
515         if (id_node == NULL) {
516                 /* This function is used from places where we expect ID to be either
517                  * already a copy-on-write version or have a corresponding copy-on-write
518                  * version.
519                  *
520                  * We try to enforce that in debug builds, for for release we play a bit
521                  * safer game here. */
522                 if ((id_orig->tag & LIB_TAG_COPIED_ON_WRITE) == 0) {
523                         /* TODO(sergey): This is nice sanity check to have, but it fails
524                          * in following situations:
525                          *
526                          * - Material has link to texture, which is not needed by new
527                          *   shading system and hence can be ignored at construction.
528                          * - Object or mesh has material at a slot which is not used (for
529                          *   example, object has material slot by materials are set to
530                          *   object data). */
531                         // BLI_assert(!"Request for non-existing copy-on-write ID");
532                 }
533                 return (ID *)id_orig;
534         }
535         return id_node->id_cow;
536 }
537
538 }  // namespace DEG
539
540 /* **************** */
541 /* Public Graph API */
542
543 /* Initialize a new Depsgraph */
544 Depsgraph *DEG_graph_new(Scene *scene,
545                          ViewLayer *view_layer,
546                          eEvaluationMode mode)
547 {
548         DEG::Depsgraph *deg_depsgraph = OBJECT_GUARDED_NEW(DEG::Depsgraph,
549                                                            scene,
550                                                            view_layer,
551                                                            mode);
552         return reinterpret_cast<Depsgraph *>(deg_depsgraph);
553 }
554
555 /* Free graph's contents and graph itself */
556 void DEG_graph_free(Depsgraph *graph)
557 {
558         using DEG::Depsgraph;
559         DEG::Depsgraph *deg_depsgraph = reinterpret_cast<DEG::Depsgraph *>(graph);
560         OBJECT_GUARDED_DELETE(deg_depsgraph, Depsgraph);
561 }
562
563 bool DEG_is_active(const struct Depsgraph *depsgraph)
564 {
565         if (depsgraph == NULL) {
566                 /* Happens for such cases as work object in what_does_obaction(),
567                  * and sine render pipeline parts. Shouldn't really be accepting
568                  * NULL depsgraph, but is quite hard to get proper one in those
569                  * cases. */
570                 return false;
571         }
572         const DEG::Depsgraph *deg_graph =
573                 reinterpret_cast<const DEG::Depsgraph *>(depsgraph);
574         return deg_graph->is_active;
575 }
576
577 void DEG_make_active(struct Depsgraph *depsgraph)
578 {
579         DEG::Depsgraph *deg_graph = reinterpret_cast<DEG::Depsgraph *>(depsgraph);
580         deg_graph->is_active = true;
581         /* TODO(sergey): Copy data from evaluated state to original. */
582 }
583
584 void DEG_make_inactive(struct Depsgraph *depsgraph)
585 {
586         DEG::Depsgraph *deg_graph = reinterpret_cast<DEG::Depsgraph *>(depsgraph);
587         deg_graph->is_active = false;
588 }