Rename any instance of scene layer or render layer in code with view layer
[blender.git] / source / blender / depsgraph / intern / eval / deg_eval_copy_on_write.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) 20137Blender Foundation.
19  * All rights reserved.
20  *
21  * Original Author: Sergey Sharybin
22  * Contributor(s): None Yet
23  *
24  * ***** END GPL LICENSE BLOCK *****
25  */
26
27
28 /** \file blender/depsgraph/intern/eval/deg_eval_copy_on_write.cc
29  *  \ingroup depsgraph
30  */
31
32 /* Enable special; trickery to treat nested owned IDs (such as nodetree of
33  * material) to be handled in same way as "real" datablocks, even tho some
34  * internal BKE routines doesn't treat them like that.
35  *
36  * TODO(sergey): Re-evaluate that after new ID handling is in place.
37  */
38 #define NESTED_ID_NASTY_WORKAROUND
39
40 #include "intern/eval/deg_eval_copy_on_write.h"
41
42 #include <cstring>
43
44 #include "BLI_utildefines.h"
45 #include "BLI_threads.h"
46 #include "BLI_string.h"
47
48 #include "BKE_global.h"
49 #include "BKE_layer.h"
50 #include "BKE_library.h"
51 #include "BKE_main.h"
52 #include "BKE_scene.h"
53
54 #include "DEG_depsgraph.h"
55
56 #include "MEM_guardedalloc.h"
57
58 extern "C" {
59 #include "DNA_ID.h"
60 #include "DNA_mesh_types.h"
61 #include "DNA_scene_types.h"
62 #include "DNA_object_types.h"
63
64 #ifdef NESTED_ID_NASTY_WORKAROUND
65 #  include "DNA_key_types.h"
66 #  include "DNA_lamp_types.h"
67 #  include "DNA_linestyle_types.h"
68 #  include "DNA_material_types.h"
69 #  include "DNA_node_types.h"
70 #  include "DNA_texture_types.h"
71 #  include "DNA_world_types.h"
72 #endif
73
74 #include "BKE_action.h"
75 #include "BKE_editmesh.h"
76 #include "BKE_library_query.h"
77 #include "BKE_object.h"
78 }
79
80 #include "intern/depsgraph.h"
81 #include "intern/builder/deg_builder_nodes.h"
82 #include "intern/nodes/deg_node.h"
83
84 namespace DEG {
85
86 #define DEBUG_PRINT if (G.debug & G_DEBUG_DEPSGRAPH) printf
87
88 namespace {
89
90 #ifdef NESTED_ID_NASTY_WORKAROUND
91 union NestedIDHackTempStorage {
92         FreestyleLineStyle linestyle;
93         Lamp lamp;
94         Material material;
95         Mesh mesh;
96         Scene scene;
97         Tex tex;
98         World world;
99 };
100
101 /* Set nested owned ID pointers to NULL. */
102 void nested_id_hack_discard_pointers(ID *id_cow)
103 {
104         switch (GS(id_cow->name)) {
105 #  define SPECIAL_CASE(id_type, dna_type, field)  \
106                 case id_type:                             \
107                 {                                         \
108                         ((dna_type *)id_cow)->field = NULL;   \
109                         break;                                \
110                 }
111
112                 SPECIAL_CASE(ID_LS, FreestyleLineStyle, nodetree)
113                 SPECIAL_CASE(ID_LA, Lamp, nodetree)
114                 SPECIAL_CASE(ID_MA, Material, nodetree)
115                 SPECIAL_CASE(ID_SCE, Scene, nodetree)
116                 SPECIAL_CASE(ID_TE, Tex, nodetree)
117                 SPECIAL_CASE(ID_WO, World, nodetree)
118
119                 SPECIAL_CASE(ID_ME, Mesh, key)
120
121 #  undef SPECIAL_CASE
122
123                 default:
124                         break;
125         }
126 }
127
128 /* Set ID pointer of nested owned IDs (nodetree, key) to NULL.
129  *
130  * Return pointer to a new ID to be used.
131  */
132 const ID *nested_id_hack_get_discarded_pointers(NestedIDHackTempStorage *storage,
133                                                 const ID *id)
134 {
135         switch (GS(id->name)) {
136 #  define SPECIAL_CASE(id_type, dna_type, field, variable)  \
137                 case id_type:                                       \
138                 {                                                   \
139                         storage->variable = *(dna_type *)id;            \
140                         storage->variable.field = NULL;                 \
141                         return &storage->variable.id;                   \
142                 }
143
144                 SPECIAL_CASE(ID_LS, FreestyleLineStyle, nodetree, linestyle)
145                 SPECIAL_CASE(ID_LA, Lamp, nodetree, lamp)
146                 SPECIAL_CASE(ID_MA, Material, nodetree, material)
147                 SPECIAL_CASE(ID_SCE, Scene, nodetree, scene)
148                 SPECIAL_CASE(ID_TE, Tex, nodetree, tex)
149                 SPECIAL_CASE(ID_WO, World, nodetree, world)
150
151                 SPECIAL_CASE(ID_ME, Mesh, key, mesh)
152
153 #  undef SPECIAL_CASE
154
155                 default:
156                         break;
157         }
158         return id;
159 }
160
161 /* Set ID pointer of nested owned IDs (nodetree, key) to the original value. */
162 void nested_id_hack_restore_pointers(const ID *old_id, ID *new_id)
163 {
164         if (new_id == NULL) {
165                 return;
166         }
167         switch (GS(old_id->name)) {
168 #  define SPECIAL_CASE(id_type, dna_type, field)    \
169                 case id_type:                               \
170                 {                                           \
171                         ((dna_type *)(new_id))->field =         \
172                                 ((dna_type *)(old_id))->field;  \
173                         break;                                  \
174                 }
175
176                 SPECIAL_CASE(ID_LS, FreestyleLineStyle, nodetree)
177                 SPECIAL_CASE(ID_LA, Lamp, nodetree)
178                 SPECIAL_CASE(ID_MA, Material, nodetree)
179                 SPECIAL_CASE(ID_SCE, Scene, nodetree)
180                 SPECIAL_CASE(ID_TE, Tex, nodetree)
181                 SPECIAL_CASE(ID_WO, World, nodetree)
182
183                 SPECIAL_CASE(ID_ME, Mesh, key)
184
185 #undef SPECIAL_CASE
186                 default:
187                         break;
188         }
189 }
190
191 /* Remap pointer of nested owned IDs (nodetree. key) to the new ID values. */
192 void ntree_hack_remap_pointers(const Depsgraph *depsgraph, ID *id_cow)
193 {
194         switch (GS(id_cow->name)) {
195 #  define SPECIAL_CASE(id_type, dna_type, field, field_type)                   \
196                 case id_type:                                                          \
197                 {                                                                      \
198                         dna_type *data = (dna_type *)id_cow;                               \
199                         if (data->field != NULL) {                                         \
200                                 ID *ntree_id_cow = depsgraph->get_cow_id(&data->field->id);    \
201                                 if (ntree_id_cow != NULL) {                                    \
202                                         DEG_COW_PRINT("    Remapping datablock for %s: id_orig=%p id_cow=%p\n", \
203                                                       data->field->id.name,                        \
204                                                       data->field,                                 \
205                                                       ntree_id_cow);                               \
206                                         data->field = (field_type *)ntree_id_cow;                  \
207                                 }                                                              \
208                         }                                                                  \
209                         break;                                                             \
210                 }
211
212                 SPECIAL_CASE(ID_LS, FreestyleLineStyle, nodetree, bNodeTree)
213                 SPECIAL_CASE(ID_LA, Lamp, nodetree, bNodeTree)
214                 SPECIAL_CASE(ID_MA, Material, nodetree, bNodeTree)
215                 SPECIAL_CASE(ID_SCE, Scene, nodetree, bNodeTree)
216                 SPECIAL_CASE(ID_TE, Tex, nodetree, bNodeTree)
217                 SPECIAL_CASE(ID_WO, World, nodetree, bNodeTree)
218
219                 SPECIAL_CASE(ID_ME, Mesh, key, Key)
220
221 #undef SPECIAL_CASE
222                 default:
223                         break;
224         }
225 }
226 #endif  /* NODETREE_NASTY_WORKAROUND */
227
228 struct ValidateData {
229         bool is_valid;
230 };
231
232 /* Similar to generic id_copy() but does not require main and assumes pointer
233  * is already allocated,
234  */
235 bool id_copy_inplace_no_main(const ID *id, ID *newid)
236 {
237         const ID *id_for_copy = id;
238
239 #ifdef NESTED_ID_NASTY_WORKAROUND
240         NestedIDHackTempStorage id_hack_storage;
241         id_for_copy = nested_id_hack_get_discarded_pointers(&id_hack_storage, id);
242 #endif
243
244         bool result = BKE_id_copy_ex(NULL,
245                                      (ID *)id_for_copy,
246                                      &newid,
247                                      LIB_ID_CREATE_NO_MAIN |
248                                      LIB_ID_CREATE_NO_USER_REFCOUNT |
249                                      LIB_ID_CREATE_NO_ALLOCATE |
250                                      LIB_ID_CREATE_NO_DEG_TAG,
251                                      false);
252
253 #ifdef NESTED_ID_NASTY_WORKAROUND
254         if (result) {
255                 nested_id_hack_restore_pointers(id, newid);
256         }
257 #endif
258
259         return result;
260 }
261
262 /* Similar to BKE_scene_copy() but does not require main and assumes pointer
263  * is already allocated.
264  */
265 bool scene_copy_inplace_no_main(const Scene *scene, Scene *new_scene)
266 {
267         const ID *id_for_copy = &scene->id;
268
269 #ifdef NESTED_ID_NASTY_WORKAROUND
270         NestedIDHackTempStorage id_hack_storage;
271         id_for_copy = nested_id_hack_get_discarded_pointers(&id_hack_storage,
272                                                             &scene->id);
273 #endif
274
275         bool result = BKE_id_copy_ex(NULL,
276                                      id_for_copy,
277                                      (ID **)&new_scene,
278                                      LIB_ID_COPY_ACTIONS |
279                                      LIB_ID_CREATE_NO_MAIN |
280                                      LIB_ID_CREATE_NO_USER_REFCOUNT |
281                                      LIB_ID_CREATE_NO_ALLOCATE |
282                                      LIB_ID_CREATE_NO_DEG_TAG,
283                                      false);
284
285 #ifdef NESTED_ID_NASTY_WORKAROUND
286         if (result) {
287                 nested_id_hack_restore_pointers(&scene->id, &new_scene->id);
288         }
289 #endif
290
291         return result;
292 }
293
294 /* Check whether given ID is expanded or still a shallow copy. */
295 BLI_INLINE bool check_datablock_expanded(const ID *id_cow)
296 {
297         return (id_cow->name[0] != '\0');
298 }
299
300 /* Check whether datablock was already expanded during depsgraph
301  * construction.
302  */
303 static bool check_datablock_expanded_at_construction(const ID *id_orig)
304 {
305         const ID_Type id_type = GS(id_orig->name);
306         return (id_type == ID_SCE) ||
307                (id_type == ID_OB && ((Object *)id_orig)->type == OB_ARMATURE) ||
308                (id_type == ID_AR);
309 }
310
311 /* Those are datablocks which are not covered by dependency graph and hence
312  * does not need any remapping or anything.
313  *
314  * TODO(sergey): How to make it more robust for the future, so we don't have
315  * to maintain exception lists all over the code?
316  */
317 static bool check_datablocks_copy_on_writable(const ID *id_orig)
318 {
319         const ID_Type id_type = GS(id_orig->name);
320         /* We shouldn't bother if copied ID is same as original one. */
321         if (!deg_copy_on_write_is_needed(id_orig)) {
322                 return false;
323         }
324         return !ELEM(id_type, ID_BR,
325                               ID_LS,
326                               ID_AC,
327                               ID_GR,
328                               ID_PAL);
329 }
330
331 /* Callback for BKE_library_foreach_ID_link which remaps original ID pointer
332  * with the one created by CoW system.
333  */
334
335 struct RemapCallbackUserData {
336         /* Dependency graph for which remapping is happening. */
337         const Depsgraph *depsgraph;
338         /* Temporarily allocated memory for copying purposes. This ID will
339          * be discarded after expanding is done, so need to make sure temp_id
340          * is replaced with proper real_id.
341          *
342          * NOTE: This is due to our logic of "inplace" duplication, where we
343          * use generic duplication routines (which gives us new ID) which then
344          * is followed with copying data to a placeholder we prepared before and
345          * discarding pointer returned by duplication routines.
346          */
347         const ID *temp_id;
348         ID *real_id;
349         /* Create placeholder for ID nodes for cases when we need to remap original
350          * ID to it[s CoW version but we don't have required ID node yet.
351          *
352          * This happens when expansion happens a ta construction time.
353          */
354         DepsgraphNodeBuilder *node_builder;
355         bool create_placeholders;
356 };
357
358 int foreach_libblock_remap_callback(void *user_data_v,
359                                     ID *id_self,
360                                     ID **id_p,
361                                     int /*cb_flag*/)
362 {
363         RemapCallbackUserData *user_data = (RemapCallbackUserData *)user_data_v;
364         const Depsgraph *depsgraph = user_data->depsgraph;
365         if (*id_p != NULL) {
366                 ID *id_orig = *id_p;
367                 if (id_orig == user_data->temp_id) {
368                         DEG_COW_PRINT("    Remapping datablock for %s: id_temp=%p id_cow=%p\n",
369                                       id_orig->name, id_orig, user_data->real_id);
370                         *id_p = user_data->real_id;
371                 }
372                 else if (check_datablocks_copy_on_writable(id_orig)) {
373                         ID *id_cow;
374                         if (user_data->create_placeholders) {
375                                 /* Special workaround to stop creating temp datablocks for
376                                  * objects which are coming from scene's collection and which
377                                  * are never linked to any of layers.
378                                  *
379                                  * TODO(sergey): Ideally we need to tell ID looper to ignore
380                                  * those or at least make it more reliable check where the
381                                  * pointer is coming from.
382                                  */
383                                 const ID_Type id_type = GS(id_orig->name);
384                                 const ID_Type id_type_self = GS(id_self->name);
385                                 if (id_type == ID_OB && id_type_self == ID_SCE) {
386                                         IDDepsNode *id_node = depsgraph->find_id_node(id_orig);
387                                         if (id_node == NULL) {
388                                                 id_cow = id_orig;
389                                         }
390                                         else {
391                                                 id_cow = id_node->id_cow;
392                                         }
393                                 }
394                                 else {
395                                         id_cow = user_data->node_builder->ensure_cow_id(id_orig);
396                                 }
397                         }
398                         else {
399                                 id_cow = depsgraph->get_cow_id(id_orig);
400                         }
401                         BLI_assert(id_cow != NULL);
402                         DEG_COW_PRINT("    Remapping datablock for %s: id_orig=%p id_cow=%p\n",
403                                       id_orig->name, id_orig, id_cow);
404                         *id_p = id_cow;
405                 }
406         }
407         return IDWALK_RET_NOP;
408 }
409
410 /* Do some special treatment of data transfer from original ID to it's
411  * CoW complementary part.
412  *
413  * Only use for the newly created CoW datablocks.
414  */
415 void update_special_pointers(const Depsgraph *depsgraph,
416                              const ID *id_orig, ID *id_cow)
417 {
418         const ID_Type type = GS(id_orig->name);
419         switch (type) {
420                 case ID_OB:
421                 {
422                         /* Ensure we don't drag someone's else derived mesh to the
423                          * new copy of the object.
424                          */
425                         Object *object_cow = (Object *)id_cow;
426                         const Object *object_orig = (const Object *)id_orig;
427                         (void) object_cow;  /* Ignored for release builds. */
428                         BLI_assert(object_cow->derivedFinal == NULL);
429                         BLI_assert(object_cow->derivedDeform == NULL);
430                         object_cow->mode = object_orig->mode;
431                         break;
432                 }
433                 case ID_ME:
434                 {
435                         /* For meshes we need to update edit_btmesh to make it to point
436                          * to the CoW version of object.
437                          *
438                          * This is kind of confusing, because actual bmesh is not owned by
439                          * the CoW object, so need to be accurate about using link from
440                          * edit_btmesh to object.
441                          */
442                         const Mesh *mesh_orig = (const Mesh *)id_orig;
443                         Mesh *mesh_cow = (Mesh *)id_cow;
444                         if (mesh_orig->edit_btmesh != NULL) {
445                                 mesh_cow->edit_btmesh = (BMEditMesh *)MEM_dupallocN(mesh_orig->edit_btmesh);
446                                 mesh_cow->edit_btmesh->ob =
447                                         (Object *)depsgraph->get_cow_id(&mesh_orig->edit_btmesh->ob->id);
448                                 mesh_cow->edit_btmesh->derivedFinal = NULL;
449                                 mesh_cow->edit_btmesh->derivedCage = NULL;
450                         }
451                         break;
452                 }
453                 case ID_SCE:
454                 {
455                         const Scene *scene_orig = (const Scene *)id_orig;
456                         Scene *scene_cow = (Scene *)id_cow;
457                         if (scene_orig->obedit != NULL) {
458                                 scene_cow->obedit = (Object *)depsgraph->get_cow_id(&scene_orig->obedit->id);
459                         }
460                         else {
461                                 scene_cow->obedit = NULL;
462                         }
463                         break;
464                 }
465                 default:
466                         break;
467         }
468 }
469
470 /* Update copy-on-write version of scene from original scene. */
471 void update_copy_on_write_scene(const Depsgraph *depsgraph,
472                                 Scene *scene_cow,
473                                 const Scene *scene_orig)
474 {
475         // Some non-pointer data sync, current frame for now.
476         // TODO(sergey): Are we missing something here?
477         scene_cow->r.cfra = scene_orig->r.cfra;
478         scene_cow->r.subframe = scene_orig->r.subframe;
479         // Update bases.
480         const ViewLayer *view_layer_orig = (ViewLayer *)scene_orig->view_layers.first;
481         ViewLayer *view_layer_cow = (ViewLayer *)scene_cow->view_layers.first;
482         while (view_layer_orig != NULL) {
483                 // Update pointers to active base.
484                 if (view_layer_orig->basact == NULL) {
485                         view_layer_cow->basact = NULL;
486                 }
487                 else {
488                         const Object *obact_orig = view_layer_orig->basact->object;
489                         Object *obact_cow = (Object *)depsgraph->get_cow_id(&obact_orig->id);
490                         view_layer_cow->basact = BKE_view_layer_base_find(view_layer_cow, obact_cow);
491                 }
492                 // Update base flags.
493                 //
494                 // TODO(sergey): We should probably check visibled/selectabled
495                 // flag here?
496                 const Base *base_orig = (Base *)view_layer_orig->object_bases.first;
497                 Base *base_cow = (Base *)view_layer_cow->object_bases.first;;
498                 while (base_orig != NULL) {
499                         base_cow->flag = base_orig->flag;
500                         base_orig = base_orig->next;
501                         base_cow = base_cow->next;
502                 }
503                 view_layer_orig = view_layer_orig->next;
504                 view_layer_cow = view_layer_cow->next;
505         }
506         // Update edit object pointer.
507         if (scene_orig->obedit != NULL) {
508                 scene_cow->obedit = (Object *)depsgraph->get_cow_id(&scene_orig->obedit->id);
509         }
510         else {
511                 scene_cow->obedit = NULL;
512         }
513         /* Synchronize active render engine. */
514         BLI_strncpy(scene_cow->view_render.engine_id,
515                     scene_orig->view_render.engine_id,
516                     sizeof(scene_cow->view_render.engine_id));
517         /* TODO(sergey): What else do we need here? */
518 }
519
520 /* Update copy-on-write version of armature object from original scene. */
521 void update_copy_on_write_object(const Depsgraph * /*depsgraph*/,
522                                  Object *object_cow,
523                                  const Object *object_orig)
524 {
525         /* TODO(sergey): This function might be split into a smaller ones,
526          * reused for different updates. And maybe even moved to BKE.
527          */
528         /* Update armature/pose related flags. */
529         bPose *pose_cow = object_cow->pose;
530         const bPose *pose_orig = object_orig->pose;
531         extract_pose_from_pose(pose_cow, pose_orig);
532         /* Update object itself. */
533         BKE_object_transform_copy(object_cow, object_orig);
534         object_cow->mode = object_orig->mode;
535 }
536
537 /* Update copy-on-write version of datablock from it's original ID without re-building
538  * the whole datablock from scratch.
539  *
540  * Used for such special cases as scene collections and armatures, which can not use full
541  * re-alloc due to pointers used as function bindings.
542  */
543 void update_copy_on_write_datablock(const Depsgraph *depsgraph,
544                                     const ID *id_orig, ID *id_cow)
545 {
546         bool ok = false;
547         const ID_Type id_type = GS(id_orig->name);
548         switch (id_type) {
549                 case ID_SCE: {
550                         const Scene *scene_orig = (const Scene *)id_orig;
551                         Scene *scene_cow = (Scene *)id_cow;
552                         update_copy_on_write_scene(depsgraph, scene_cow, scene_orig);
553                         ok = true;
554                         break;
555                 }
556                 case ID_OB: {
557                         const Object *object_orig = (const Object *)id_orig;
558                         Object *object_cow = (Object *)id_cow;
559                         if (object_orig->type == OB_ARMATURE) {
560                                 update_copy_on_write_object(depsgraph,
561                                                             object_cow,
562                                                             object_orig);
563                                 ok = true;
564                         }
565                         break;
566                 }
567                 case ID_AR:
568                         /* Nothing to do currently. */
569                         ok = true;
570                         break;
571                 default:
572                         break;
573         }
574         // TODO(sergey): Other ID types here.
575         if (!ok) {
576                 BLI_assert(!"Missing update logic of expanded datablock");
577         }
578 }
579
580 /* This callback is used to validate that all nested ID datablocks are
581  * properly expanded.
582  */
583 int foreach_libblock_validate_callback(void *user_data,
584                                        ID * /*id_self*/,
585                                        ID **id_p,
586                                        int /*cb_flag*/)
587 {
588         ValidateData *data = (ValidateData *)user_data;
589         if (*id_p != NULL) {
590                 if (!check_datablock_expanded(*id_p)) {
591                         data->is_valid = false;
592                         /* TODO(sergey): Store which is is not valid? */
593                 }
594         }
595         return IDWALK_RET_NOP;
596 }
597
598 }  // namespace
599
600 /* Actual implementation of logic which "expands" all the data which was not
601  * yet copied-on-write.
602  *
603  * NOTE: Expects that CoW datablock is empty.
604  */
605 ID *deg_expand_copy_on_write_datablock(const Depsgraph *depsgraph,
606                                        const IDDepsNode *id_node,
607                                        DepsgraphNodeBuilder *node_builder,
608                                        bool create_placeholders)
609 {
610         BLI_assert(!create_placeholders ||
611                    check_datablock_expanded_at_construction(id_node->id_orig));
612         const ID *id_orig = id_node->id_orig;
613         ID *id_cow = id_node->id_cow;
614         /* No need to expand such datablocks, their copied ID is same as original
615          * one already.
616          */
617         if (!deg_copy_on_write_is_needed(id_orig)) {
618                 return id_cow;
619         }
620         DEG_COW_PRINT("Expanding datablock for %s: id_orig=%p id_cow=%p\n",
621                       id_orig->name, id_orig, id_cow);
622         /* Sanity checks. */
623         /* NOTE: Disabled for now, conflicts when re-using evaluated datablock when
624          * rebuilding dependencies.
625          */
626         if (check_datablock_expanded(id_cow) && create_placeholders) {
627                 deg_free_copy_on_write_datablock(id_cow);
628         }
629         // BLI_assert(check_datablock_expanded(id_cow) == false);
630         /* Copy data from original ID to a copied version. */
631         /* TODO(sergey): Avoid doing full ID copy somehow, make Mesh to reference
632          * original geometry arrays for until those are modified.
633          */
634         /* TODO(sergey): We do some trickery with temp bmain and extra ID pointer
635          * just to be able to use existing API. Ideally we need to replace this with
636          * in-place copy from existing datablock to a prepared memory.
637          *
638          * NOTE: We don't use BKE_main_{new,free} because:
639          * - We don't want heap-allocations here.
640          * - We don't want bmain's content to be freed when main is freed.
641          */
642         bool done = false;
643         /* Need to make sure the possibly temporary allocated memory is correct for
644          * until we are fully done with remapping original pointers with copied on
645          * write ones.
646          */
647         ID *newid = NULL;
648         /* First we handle special cases which are not covered by id_copy() yet.
649          * or cases where we want to do something smarter than simple datablock
650          * copy.
651          */
652         const ID_Type id_type = GS(id_orig->name);
653         switch (id_type) {
654                 case ID_SCE:
655                 {
656                         done = scene_copy_inplace_no_main((Scene *)id_orig, (Scene*)id_cow);
657                         break;
658                 }
659                 case ID_ME:
660                 {
661                         /* TODO(sergey): Ideally we want to handle meshes in a special
662                          * manner here to avoid initial copy of all the geometry arrays.
663                          */
664                         break;
665                 }
666                 default:
667                         break;
668         }
669         if (!done) {
670                 done = id_copy_inplace_no_main(id_orig, id_cow);
671         }
672         if (!done) {
673                 BLI_assert(!"No idea how to perform CoW on datablock");
674         }
675         /* Update pointers to nested ID datablocks. */
676         DEG_COW_PRINT("  Remapping ID links for %s: id_orig=%p id_cow=%p\n",
677                       id_orig->name, id_orig, id_cow);
678
679 #ifdef NESTED_ID_NASTY_WORKAROUND
680         ntree_hack_remap_pointers(depsgraph, id_cow);
681 #endif
682         /* Do it now, so remapping will understand that possibly remapped self ID
683          * is not to be remapped again.
684          */
685         deg_tag_copy_on_write_id(id_cow, id_orig);
686         /* Perform remapping of the nodes. */
687         RemapCallbackUserData user_data;
688         user_data.depsgraph = depsgraph;
689         user_data.temp_id = newid;
690         user_data.real_id = id_cow;
691         user_data.node_builder = node_builder;
692         user_data.create_placeholders = create_placeholders;
693         BKE_library_foreach_ID_link(NULL,
694                                     id_cow,
695                                     foreach_libblock_remap_callback,
696                                     (void *)&user_data,
697                                     IDWALK_NOP);
698         /* Correct or tweak some pointers which are not taken care by foreach
699          * from above.
700          */
701         update_special_pointers(depsgraph, id_orig, id_cow);
702         /* Now we can safely discard temporary memory used for copying. */
703         if (newid != NULL) {
704                 MEM_freeN(newid);
705         }
706         return id_cow;
707 }
708
709 /* NOTE: Depsgraph is supposed to have ID node already. */
710 ID *deg_expand_copy_on_write_datablock(const Depsgraph *depsgraph,
711                                        ID *id_orig,
712                                        DepsgraphNodeBuilder *node_builder,
713                                        bool create_placeholders)
714 {
715         DEG::IDDepsNode *id_node = depsgraph->find_id_node(id_orig);
716         BLI_assert(id_node != NULL);
717         return deg_expand_copy_on_write_datablock(depsgraph,
718                                                   id_node,
719                                                   node_builder,
720                                                   create_placeholders);
721 }
722
723 ID *deg_update_copy_on_write_datablock(const Depsgraph *depsgraph,
724                                        const IDDepsNode *id_node)
725 {
726         const ID *id_orig = id_node->id_orig;
727         const ID_Type id_type = GS(id_orig->name);
728         ID *id_cow = id_node->id_cow;
729         /* Similar to expansion, no need to do anything here. */
730         if (!deg_copy_on_write_is_needed(id_orig)) {
731                 return id_cow;
732         }
733         /* Special case for datablocks which are expanded at the dependency graph
734          * construction time. This datablocks must never change pointers of their
735          * nested data since it is used for function bindings.
736          */
737         if (check_datablock_expanded_at_construction(id_orig)) {
738                 BLI_assert(check_datablock_expanded(id_cow) == true);
739                 update_copy_on_write_datablock(depsgraph, id_orig, id_cow);
740                 return id_cow;
741         }
742         /* For the rest if datablock types we use simple logic:
743          * - Free previously expanded data, if any.
744          * - Perform full datablock copy.
745          *
746          * Note that we never free GPU materials from here since that's not
747          * safe for threading and GPU materials are likely to be re-used.
748          */
749         ListBase gpumaterial_backup;
750         ListBase *gpumaterial_ptr = NULL;
751         Mesh *mesh_evaluated = NULL;
752         if (check_datablock_expanded(id_cow)) {
753                 switch (id_type) {
754                         case ID_MA:
755                         {
756                                 Material *material = (Material *)id_cow;
757                                 gpumaterial_ptr = &material->gpumaterial;
758                                 break;
759                         }
760                         case ID_WO:
761                         {
762                                 World *world = (World *)id_cow;
763                                 gpumaterial_ptr = &world->gpumaterial;
764                                 break;
765                         }
766                         case ID_OB:
767                         {
768                                 Object *object = (Object *)id_cow;
769                                 /* Store evaluated mesh, make sure we don't free it. */
770                                 mesh_evaluated = object->mesh_evaluated;
771                                 object->mesh_evaluated = NULL;
772                                 /* Currently object update will override actual object->data
773                                  * to an evaluated version. Need to make sure we don't have
774                                  * data set to evaluated one before free anything.
775                                  */
776                                 if (mesh_evaluated != NULL) {
777                                         if (object->data == mesh_evaluated) {
778                                                 object->data = mesh_evaluated->id.newid;
779                                         }
780                                 }
781                                 break;
782                         }
783                         default:
784                                 break;
785                 }
786                 if (gpumaterial_ptr != NULL) {
787                         gpumaterial_backup = *gpumaterial_ptr;
788                         gpumaterial_ptr->first = gpumaterial_ptr->last = NULL;
789                 }
790         }
791         deg_free_copy_on_write_datablock(id_cow);
792         deg_expand_copy_on_write_datablock(depsgraph, id_node);
793         /* Restore GPU materials. */
794         if (gpumaterial_ptr != NULL) {
795                 *gpumaterial_ptr = gpumaterial_backup;
796         }
797         if (id_type == ID_OB) {
798                 if (mesh_evaluated != NULL) {
799                         Object *object = (Object *)id_cow;
800                         object->mesh_evaluated = mesh_evaluated;
801                         /* Do same thing as object update: override actual object data
802                          * pointer with evaluated datablock.
803                          */
804                         if (object->type == OB_MESH) {
805                                 object->data = mesh_evaluated;
806                                 /* Evaluated mesh simply copied edit_btmesh pointer from
807                                  * original mesh during update, need to make sure no dead
808                                  * pointers are left behind.
809                                  */
810                                 mesh_evaluated->edit_btmesh =
811                                         ((Mesh *)mesh_evaluated->id.newid)->edit_btmesh;
812                         }
813                 }
814         }
815         return id_cow;
816 }
817
818 /* NOTE: Depsgraph is supposed to have ID node already. */
819 ID *deg_update_copy_on_write_datablock(const Depsgraph *depsgraph,
820                                        ID *id_orig)
821 {
822         DEG::IDDepsNode *id_node = depsgraph->find_id_node(id_orig);
823         BLI_assert(id_node != NULL);
824         return deg_update_copy_on_write_datablock(depsgraph, id_node);
825 }
826
827 /* Free content of the CoW datablock
828  * Notes:
829  * - Does not recurs into nested ID datablocks.
830  * - Does not free datablock itself.
831  */
832 void deg_free_copy_on_write_datablock(ID *id_cow)
833 {
834         if (!check_datablock_expanded(id_cow)) {
835                 /* Actual content was never copied on top of CoW block, we have
836                  * nothing to free.
837                  */
838                 return;
839         }
840         const ID_Type type = GS(id_cow->name);
841 #ifdef NESTED_ID_NASTY_WORKAROUND
842         nested_id_hack_discard_pointers(id_cow);
843 #endif
844         switch (type) {
845                 case ID_OB:
846                 {
847                         /* TODO(sergey): This workaround is only to prevent free derived
848                          * caches from modifying object->data. This is currently happening
849                          * due to mesh/curve datablock boundbox tagging dirty.
850                          */
851                         Object *ob_cow = (Object *)id_cow;
852                         ob_cow->data = NULL;
853                         break;
854                 }
855                 case ID_ME:
856                 {
857                         Mesh *mesh_cow = (Mesh *)id_cow;
858                         if (mesh_cow->edit_btmesh != NULL) {
859                                 BKE_editmesh_free_derivedmesh(mesh_cow->edit_btmesh);
860                                 MEM_freeN(mesh_cow->edit_btmesh);
861                                 mesh_cow->edit_btmesh = NULL;
862                         }
863                         break;
864                 }
865                 case ID_SCE:
866                 {
867                         /* Special case for scene: we use explicit function call which
868                          * ensures no access to other datablocks is done.
869                          */
870                         Scene *scene = (Scene *)id_cow;
871                         BKE_scene_free_ex(scene, false);
872                         BKE_libblock_free_data(id_cow, false);
873                         id_cow->name[0] = '\0';
874                         return;
875                 }
876                 default:
877                         break;
878         }
879         BKE_libblock_free_datablock(id_cow, 0);
880         BKE_libblock_free_data(id_cow, false);
881         /* Signal datablock as not being expanded. */
882         id_cow->name[0] = '\0';
883 }
884
885 void deg_evaluate_copy_on_write(const EvaluationContext * /*eval_ctx*/,
886                                 const Depsgraph *depsgraph,
887                                 const IDDepsNode *id_node)
888 {
889         DEBUG_PRINT("%s on %s\n", __func__, id_node->id_orig->name);
890         deg_update_copy_on_write_datablock(depsgraph, id_node);
891 }
892
893 bool deg_validate_copy_on_write_datablock(ID *id_cow)
894 {
895         if (id_cow == NULL) {
896                 return false;
897         }
898         ValidateData data;
899         data.is_valid = true;
900         BKE_library_foreach_ID_link(NULL,
901                                     id_cow,
902                                     foreach_libblock_validate_callback,
903                                     &data,
904                                     IDWALK_NOP);
905         return data.is_valid;
906 }
907
908 void deg_tag_copy_on_write_id(ID *id_cow, const ID *id_orig)
909 {
910         id_cow->tag |= LIB_TAG_COPY_ON_WRITE;
911         /* TODO(sergey): Is it safe to re-use newid for original ID link? */
912         id_cow->newid = (ID *)id_orig;
913 }
914
915 bool deg_copy_on_write_is_expanded(const ID *id_cow)
916 {
917         return check_datablock_expanded(id_cow);
918 }
919
920 bool deg_copy_on_write_is_needed(const ID *id_orig)
921 {
922         const ID_Type id_type = GS(id_orig->name);
923         return !ELEM(id_type, ID_IM);
924 }
925
926 }  // namespace DEG