Merge branch 'master' into blender2.8
[blender.git] / source / blender / blenkernel / intern / scene.c
1 /*
2  * ***** BEGIN GPL LICENSE BLOCK *****
3  *
4  * This program is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU General Public License
6  * as published by the Free Software Foundation; either version 2
7  * of the License, or (at your option) any later version.
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program; if not, write to the Free Software Foundation,
16  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
17  *
18  * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
19  * All rights reserved.
20  *
21  * The Original Code is: all of this file.
22  *
23  * Contributor(s): none yet.
24  *
25  * ***** END GPL LICENSE BLOCK *****
26  */
27
28 /** \file blender/blenkernel/intern/scene.c
29  *  \ingroup bke
30  */
31
32
33 #include <stddef.h>
34 #include <stdio.h>
35 #include <string.h>
36
37 #include "MEM_guardedalloc.h"
38
39 #include "DNA_anim_types.h"
40 #include "DNA_group_types.h"
41 #include "DNA_linestyle_types.h"
42 #include "DNA_mesh_types.h"
43 #include "DNA_node_types.h"
44 #include "DNA_object_types.h"
45 #include "DNA_rigidbody_types.h"
46 #include "DNA_scene_types.h"
47 #include "DNA_screen_types.h"
48 #include "DNA_sequence_types.h"
49 #include "DNA_space_types.h"
50 #include "DNA_view3d_types.h"
51 #include "DNA_windowmanager_types.h"
52 #include "DNA_workspace_types.h"
53 #include "DNA_gpencil_types.h"
54
55 #include "BLI_math.h"
56 #include "BLI_blenlib.h"
57 #include "BLI_utildefines.h"
58 #include "BLI_callbacks.h"
59 #include "BLI_string.h"
60 #include "BLI_string_utils.h"
61 #include "BLI_threads.h"
62 #include "BLI_task.h"
63
64 #include "BLT_translation.h"
65
66 #include "BKE_anim.h"
67 #include "BKE_animsys.h"
68 #include "BKE_action.h"
69 #include "BKE_armature.h"
70 #include "BKE_cachefile.h"
71 #include "BKE_collection.h"
72 #include "BKE_colortools.h"
73 #include "BKE_editmesh.h"
74 #include "BKE_fcurve.h"
75 #include "BKE_freestyle.h"
76 #include "BKE_global.h"
77 #include "BKE_gpencil.h"
78 #include "BKE_group.h"
79 #include "BKE_icons.h"
80 #include "BKE_idprop.h"
81 #include "BKE_image.h"
82 #include "BKE_layer.h"
83 #include "BKE_library.h"
84 #include "BKE_library_remap.h"
85 #include "BKE_linestyle.h"
86 #include "BKE_main.h"
87 #include "BKE_mask.h"
88 #include "BKE_node.h"
89 #include "BKE_object.h"
90 #include "BKE_paint.h"
91 #include "BKE_rigidbody.h"
92 #include "BKE_scene.h"
93 #include "BKE_screen.h"
94 #include "BKE_sequencer.h"
95 #include "BKE_sound.h"
96 #include "BKE_unit.h"
97 #include "BKE_workspace.h"
98 #include "BKE_world.h"
99
100 #include "DEG_depsgraph.h"
101 #include "DEG_depsgraph_build.h"
102 #include "DEG_depsgraph_debug.h"
103 #include "DEG_depsgraph_query.h"
104
105 #include "RE_engine.h"
106
107 #include "PIL_time.h"
108
109 #include "IMB_colormanagement.h"
110 #include "IMB_imbuf.h"
111
112 #include "bmesh.h"
113
114 const char *RE_engine_id_BLENDER_RENDER = "BLENDER_RENDER";
115 const char *RE_engine_id_BLENDER_GAME = "BLENDER_GAME";
116 const char *RE_engine_id_BLENDER_CLAY = "BLENDER_CLAY";
117 const char *RE_engine_id_BLENDER_EEVEE = "BLENDER_EEVEE";
118 const char *RE_engine_id_CYCLES = "CYCLES";
119
120 void free_avicodecdata(AviCodecData *acd)
121 {
122         if (acd) {
123                 if (acd->lpFormat) {
124                         MEM_freeN(acd->lpFormat);
125                         acd->lpFormat = NULL;
126                         acd->cbFormat = 0;
127                 }
128                 if (acd->lpParms) {
129                         MEM_freeN(acd->lpParms);
130                         acd->lpParms = NULL;
131                         acd->cbParms = 0;
132                 }
133         }
134 }
135
136 static void remove_sequencer_fcurves(Scene *sce)
137 {
138         AnimData *adt = BKE_animdata_from_id(&sce->id);
139
140         if (adt && adt->action) {
141                 FCurve *fcu, *nextfcu;
142                 
143                 for (fcu = adt->action->curves.first; fcu; fcu = nextfcu) {
144                         nextfcu = fcu->next;
145                         
146                         if ((fcu->rna_path) && strstr(fcu->rna_path, "sequences_all")) {
147                                 action_groups_remove_channel(adt->action, fcu);
148                                 free_fcurve(fcu);
149                         }
150                 }
151         }
152 }
153
154 /**
155  * Only copy internal data of Scene ID from source to already allocated/initialized destination.
156  * You probably nerver want to use that directly, use id_copy or BKE_id_copy_ex for typical needs.
157  *
158  * WARNING! This function will not handle ID user count!
159  *
160  * \param flag  Copying options (see BKE_library.h's LIB_ID_COPY_... flags for more).
161  */
162 void BKE_scene_copy_data(Main *bmain, Scene *sce_dst, const Scene *sce_src, const int flag)
163 {
164         /* We never handle usercount here for own data. */
165         const int flag_subdata = flag | LIB_ID_CREATE_NO_USER_REFCOUNT;
166
167         sce_dst->ed = NULL;
168         sce_dst->depsgraph_hash = NULL;
169         sce_dst->fps_info = NULL;
170
171         /* layers and collections */
172         sce_dst->collection = MEM_dupallocN(sce_src->collection);
173         SceneCollection *mc_src = BKE_collection_master(&sce_src->id);
174         SceneCollection *mc_dst = BKE_collection_master(&sce_dst->id);
175
176         /* Recursively creates a new SceneCollection tree. */
177         BKE_collection_copy_data(mc_dst, mc_src, flag_subdata);
178
179         IDPropertyTemplate val = {0};
180         BLI_duplicatelist(&sce_dst->view_layers, &sce_src->view_layers);
181         for (ViewLayer *view_layer_src = sce_src->view_layers.first, *view_layer_dst = sce_dst->view_layers.first;
182              view_layer_src;
183              view_layer_src = view_layer_src->next, view_layer_dst = view_layer_dst->next)
184         {
185                 BKE_view_layer_copy_data(view_layer_dst, view_layer_src, mc_dst, mc_src, flag_subdata);
186         }
187
188         sce_dst->collection_properties = IDP_New(IDP_GROUP, &val, ROOT_PROP);
189         if (sce_src->collection_properties) {
190                 IDP_MergeGroup_ex(sce_dst->collection_properties, sce_src->collection_properties, true, flag_subdata);
191         }
192         sce_dst->layer_properties = IDP_New(IDP_GROUP, &val, ROOT_PROP);
193         if (sce_src->layer_properties) {
194                 IDP_MergeGroup_ex(sce_dst->layer_properties, sce_src->layer_properties, true, flag_subdata);
195         }
196
197         BLI_duplicatelist(&(sce_dst->markers), &(sce_src->markers));
198         BLI_duplicatelist(&(sce_dst->r.views), &(sce_src->r.views));
199         BKE_keyingsets_copy(&(sce_dst->keyingsets), &(sce_src->keyingsets));
200
201         if (sce_src->nodetree) {
202                 /* Note: nodetree is *not* in bmain, however this specific case is handled at lower level
203                  *       (see BKE_libblock_copy_ex()). */
204                 BKE_id_copy_ex(bmain, (ID *)sce_src->nodetree, (ID **)&sce_dst->nodetree, flag, false);
205                 BKE_libblock_relink_ex(bmain, sce_dst->nodetree, (void *)(&sce_src->id), &sce_dst->id, false);
206         }
207
208         if (sce_src->rigidbody_world) {
209                 sce_dst->rigidbody_world = BKE_rigidbody_world_copy(sce_src->rigidbody_world, flag_subdata);
210         }
211
212         /* copy color management settings */
213         BKE_color_managed_display_settings_copy(&sce_dst->display_settings, &sce_src->display_settings);
214         BKE_color_managed_view_settings_copy(&sce_dst->view_settings, &sce_src->view_settings);
215         BKE_color_managed_colorspace_settings_copy(&sce_dst->sequencer_colorspace_settings, &sce_src->sequencer_colorspace_settings);
216
217         BKE_color_managed_display_settings_copy(&sce_dst->r.im_format.display_settings, &sce_src->r.im_format.display_settings);
218         BKE_color_managed_view_settings_copy(&sce_dst->r.im_format.view_settings, &sce_src->r.im_format.view_settings);
219
220         BKE_color_managed_display_settings_copy(&sce_dst->r.bake.im_format.display_settings, &sce_src->r.bake.im_format.display_settings);
221         BKE_color_managed_view_settings_copy(&sce_dst->r.bake.im_format.view_settings, &sce_src->r.bake.im_format.view_settings);
222
223         curvemapping_copy_data(&sce_dst->r.mblur_shutter_curve, &sce_src->r.mblur_shutter_curve);
224
225         /* tool settings */
226         if (sce_dst->toolsettings != NULL) {
227                 ToolSettings *ts = sce_dst->toolsettings = MEM_dupallocN(sce_dst->toolsettings);
228                 if (ts->vpaint) {
229                         ts->vpaint = MEM_dupallocN(ts->vpaint);
230                         BKE_paint_copy(&ts->vpaint->paint, &ts->vpaint->paint, flag_subdata);
231                 }
232                 if (ts->wpaint) {
233                         ts->wpaint = MEM_dupallocN(ts->wpaint);
234                         BKE_paint_copy(&ts->wpaint->paint, &ts->wpaint->paint, flag_subdata);
235                 }
236                 if (ts->sculpt) {
237                         ts->sculpt = MEM_dupallocN(ts->sculpt);
238                         BKE_paint_copy(&ts->sculpt->paint, &ts->sculpt->paint, flag_subdata);
239                 }
240                 if (ts->uvsculpt) {
241                         ts->uvsculpt = MEM_dupallocN(ts->uvsculpt);
242                         BKE_paint_copy(&ts->uvsculpt->paint, &ts->uvsculpt->paint, flag_subdata);
243                 }
244
245                 BKE_paint_copy(&ts->imapaint.paint, &ts->imapaint.paint, flag_subdata);
246                 ts->imapaint.paintcursor = NULL;
247                 ts->particle.paintcursor = NULL;
248                 ts->particle.scene = NULL;
249                 ts->particle.object = NULL;
250
251                 /* duplicate Grease Pencil Drawing Brushes */
252                 BLI_listbase_clear(&ts->gp_brushes);
253                 for (bGPDbrush *brush = sce_src->toolsettings->gp_brushes.first; brush; brush = brush->next) {
254                         bGPDbrush *newbrush = BKE_gpencil_brush_duplicate(brush);
255                         BLI_addtail(&ts->gp_brushes, newbrush);
256                 }
257
258                 /* duplicate Grease Pencil interpolation curve */
259                 ts->gp_interpolate.custom_ipo = curvemapping_copy(ts->gp_interpolate.custom_ipo);
260         }
261
262         /* make a private copy of the avicodecdata */
263         if (sce_src->r.avicodecdata) {
264                 sce_dst->r.avicodecdata = MEM_dupallocN(sce_src->r.avicodecdata);
265                 sce_dst->r.avicodecdata->lpFormat = MEM_dupallocN(sce_dst->r.avicodecdata->lpFormat);
266                 sce_dst->r.avicodecdata->lpParms = MEM_dupallocN(sce_dst->r.avicodecdata->lpParms);
267         }
268
269         if (sce_src->r.ffcodecdata.properties) { /* intentionally check sce_dst not sce_src. */  /* XXX ??? comment outdated... */
270                 sce_dst->r.ffcodecdata.properties = IDP_CopyProperty_ex(sce_src->r.ffcodecdata.properties, flag_subdata);
271         }
272
273         /* before scene copy */
274         BKE_sound_create_scene(sce_dst);
275
276         /* Copy sequencer, this is local data! */
277         if (sce_src->ed) {
278                 sce_dst->ed = MEM_callocN(sizeof(*sce_dst->ed), __func__);
279                 sce_dst->ed->seqbasep = &sce_dst->ed->seqbase;
280                 BKE_sequence_base_dupli_recursive(
281                             sce_src, sce_dst, &sce_dst->ed->seqbase, &sce_src->ed->seqbase, SEQ_DUPE_ALL, flag_subdata);
282         }
283
284         if ((flag & LIB_ID_COPY_NO_PREVIEW) == 0) {
285                 BKE_previewimg_id_copy(&sce_dst->id, &sce_src->id);
286         }
287         else {
288                 sce_dst->preview = NULL;
289         }
290 }
291
292 Scene *BKE_scene_copy(Main *bmain, Scene *sce, int type)
293 {
294         Scene *sce_copy;
295
296         /* TODO this should/could most likely be replaced by call to more generic code at some point...
297          * But for now, let's keep it well isolated here. */
298         if (type == SCE_COPY_EMPTY) {
299                 ToolSettings *ts;
300                 ListBase rv;
301
302                 sce_copy = BKE_scene_add(bmain, sce->id.name + 2);
303
304                 rv = sce_copy->r.views;
305                 curvemapping_free_data(&sce_copy->r.mblur_shutter_curve);
306                 sce_copy->r = sce->r;
307                 sce_copy->active_view_layer = 0;
308                 sce_copy->r.views = rv;
309                 sce_copy->unit = sce->unit;
310                 sce_copy->physics_settings = sce->physics_settings;
311                 sce_copy->gm = sce->gm;
312                 sce_copy->audio = sce->audio;
313
314                 if (sce->id.properties)
315                         sce_copy->id.properties = IDP_CopyProperty(sce->id.properties);
316
317                 MEM_freeN(sce_copy->toolsettings);
318                 BKE_sound_destroy_scene(sce_copy);
319
320                 /* copy color management settings */
321                 BKE_color_managed_display_settings_copy(&sce_copy->display_settings, &sce->display_settings);
322                 BKE_color_managed_view_settings_copy(&sce_copy->view_settings, &sce->view_settings);
323                 BKE_color_managed_colorspace_settings_copy(&sce_copy->sequencer_colorspace_settings, &sce->sequencer_colorspace_settings);
324
325                 BKE_color_managed_display_settings_copy(&sce_copy->r.im_format.display_settings, &sce->r.im_format.display_settings);
326                 BKE_color_managed_view_settings_copy(&sce_copy->r.im_format.view_settings, &sce->r.im_format.view_settings);
327
328                 BKE_color_managed_display_settings_copy(&sce_copy->r.bake.im_format.display_settings, &sce->r.bake.im_format.display_settings);
329                 BKE_color_managed_view_settings_copy(&sce_copy->r.bake.im_format.view_settings, &sce->r.bake.im_format.view_settings);
330
331                 curvemapping_copy_data(&sce_copy->r.mblur_shutter_curve, &sce->r.mblur_shutter_curve);
332
333                 /* tool settings */
334                 sce_copy->toolsettings = MEM_dupallocN(sce->toolsettings);
335
336                 ts = sce_copy->toolsettings;
337                 if (ts) {
338                         if (ts->vpaint) {
339                                 ts->vpaint = MEM_dupallocN(ts->vpaint);
340                                 BKE_paint_copy(&ts->vpaint->paint, &ts->vpaint->paint, 0);
341                         }
342                         if (ts->wpaint) {
343                                 ts->wpaint = MEM_dupallocN(ts->wpaint);
344                                 BKE_paint_copy(&ts->wpaint->paint, &ts->wpaint->paint, 0);
345                         }
346                         if (ts->sculpt) {
347                                 ts->sculpt = MEM_dupallocN(ts->sculpt);
348                                 BKE_paint_copy(&ts->sculpt->paint, &ts->sculpt->paint, 0);
349                         }
350                         if (ts->uvsculpt) {
351                                 ts->uvsculpt = MEM_dupallocN(ts->uvsculpt);
352                                 BKE_paint_copy(&ts->uvsculpt->paint, &ts->uvsculpt->paint, 0);
353                         }
354
355                         BKE_paint_copy(&ts->imapaint.paint, &ts->imapaint.paint, 0);
356                         ts->imapaint.paintcursor = NULL;
357                         id_us_plus((ID *)ts->imapaint.stencil);
358                         id_us_plus((ID *)ts->imapaint.clone);
359                         id_us_plus((ID *)ts->imapaint.canvas);
360                         ts->particle.paintcursor = NULL;
361                         ts->particle.scene = NULL;
362                         ts->particle.object = NULL;
363
364                         /* duplicate Grease Pencil Drawing Brushes */
365                         BLI_listbase_clear(&ts->gp_brushes);
366                         for (bGPDbrush *brush = sce->toolsettings->gp_brushes.first; brush; brush = brush->next) {
367                                 bGPDbrush *newbrush = BKE_gpencil_brush_duplicate(brush);
368                                 BLI_addtail(&ts->gp_brushes, newbrush);
369                         }
370
371                         /* duplicate Grease Pencil interpolation curve */
372                         ts->gp_interpolate.custom_ipo = curvemapping_copy(ts->gp_interpolate.custom_ipo);
373                 }
374
375                 /* make a private copy of the avicodecdata */
376                 if (sce->r.avicodecdata) {
377                         sce_copy->r.avicodecdata = MEM_dupallocN(sce->r.avicodecdata);
378                         sce_copy->r.avicodecdata->lpFormat = MEM_dupallocN(sce_copy->r.avicodecdata->lpFormat);
379                         sce_copy->r.avicodecdata->lpParms = MEM_dupallocN(sce_copy->r.avicodecdata->lpParms);
380                 }
381
382                 if (sce->r.ffcodecdata.properties) { /* intentionally check scen not sce. */
383                         sce_copy->r.ffcodecdata.properties = IDP_CopyProperty(sce->r.ffcodecdata.properties);
384                 }
385
386                 /* before scene copy */
387                 BKE_sound_create_scene(sce_copy);
388
389                 /* grease pencil */
390                 sce_copy->gpd = NULL;
391
392                 sce_copy->preview = NULL;
393
394                 return sce_copy;
395         }
396         else {
397                 BKE_id_copy_ex(bmain, (ID *)sce, (ID **)&sce_copy, LIB_ID_COPY_ACTIONS, false);
398                 id_us_min(&sce_copy->id);
399                 id_us_ensure_real(&sce_copy->id);
400
401                 /* Extra actions, most notably SCE_FULL_COPY also duplicates several 'children' datablocks... */
402
403                 if (type == SCE_COPY_FULL) {
404                         /* Copy Freestyle LineStyle datablocks. */
405                         for (ViewLayer *view_layer_dst = sce_copy->view_layers.first; view_layer_dst; view_layer_dst = view_layer_dst->next) {
406                                 for (FreestyleLineSet *lineset = view_layer_dst->freestyle_config.linesets.first; lineset; lineset = lineset->next) {
407                                         if (lineset->linestyle) {
408                                                 /* XXX Not copying anim/actions here? */
409                                                 BKE_id_copy_ex(bmain, (ID *)lineset->linestyle, (ID **)&lineset->linestyle, 0, false);
410                                         }
411                                 }
412                         }
413
414                         /* Full copy of world (included animations) */
415                         if (sce_copy->world) {
416                                 BKE_id_copy_ex(bmain, (ID *)sce_copy->world, (ID **)&sce_copy->world, LIB_ID_COPY_ACTIONS, false);
417                         }
418
419                         /* Full copy of GreasePencil. */
420                         /* XXX Not copying anim/actions here? */
421                         if (sce_copy->gpd) {
422                                 BKE_id_copy_ex(bmain, (ID *)sce_copy->gpd, (ID **)&sce_copy->gpd, 0, false);
423                         }
424                 }
425                 else {
426                         /* Remove sequencer if not full copy */
427                         /* XXX Why in Hell? :/ */
428                         remove_sequencer_fcurves(sce_copy);
429                         BKE_sequencer_editing_free(sce_copy);
430                 }
431
432                 /* NOTE: part of SCE_COPY_LINK_DATA and SCE_COPY_FULL operations
433                  * are done outside of blenkernel with ED_objects_single_users! */
434
435                 /*  camera */
436                 if (ELEM(type, SCE_COPY_LINK_DATA, SCE_COPY_FULL)) {
437                         ID_NEW_REMAP(sce_copy->camera);
438                 }
439
440                 return sce_copy;
441         }
442 }
443
444 void BKE_scene_groups_relink(Scene *sce)
445 {
446         if (sce->rigidbody_world)
447                 BKE_rigidbody_world_groups_relink(sce->rigidbody_world);
448 }
449
450 void BKE_scene_make_local(Main *bmain, Scene *sce, const bool lib_local)
451 {
452         /* For now should work, may need more work though to support all possible corner cases
453          * (also scene_copy probably needs some love). */
454         BKE_id_make_local_generic(bmain, &sce->id, true, lib_local);
455 }
456
457 /** Free (or release) any data used by this scene (does not free the scene itself). */
458 void BKE_scene_free_ex(Scene *sce, const bool do_id_user)
459 {
460         BKE_animdata_free((ID *)sce, false);
461
462         /* check all sequences */
463         BKE_sequencer_clear_scene_in_allseqs(G.main, sce);
464
465         BKE_sequencer_editing_free(sce);
466
467         BKE_keyingsets_free(&sce->keyingsets);
468
469         /* is no lib link block, but scene extension */
470         if (sce->nodetree) {
471                 ntreeFreeTree(sce->nodetree);
472                 MEM_freeN(sce->nodetree);
473                 sce->nodetree = NULL;
474         }
475
476         if (sce->rigidbody_world) {
477                 BKE_rigidbody_free_world(sce->rigidbody_world);
478                 sce->rigidbody_world = NULL;
479         }
480
481         if (sce->r.avicodecdata) {
482                 free_avicodecdata(sce->r.avicodecdata);
483                 MEM_freeN(sce->r.avicodecdata);
484                 sce->r.avicodecdata = NULL;
485         }
486         if (sce->r.ffcodecdata.properties) {
487                 IDP_FreeProperty(sce->r.ffcodecdata.properties);
488                 MEM_freeN(sce->r.ffcodecdata.properties);
489                 sce->r.ffcodecdata.properties = NULL;
490         }
491
492         BLI_freelistN(&sce->markers);
493         BLI_freelistN(&sce->r.views);
494         
495         if (sce->toolsettings) {
496                 if (sce->toolsettings->vpaint) {
497                         BKE_paint_free(&sce->toolsettings->vpaint->paint);
498                         MEM_freeN(sce->toolsettings->vpaint);
499                 }
500                 if (sce->toolsettings->wpaint) {
501                         BKE_paint_free(&sce->toolsettings->wpaint->paint);
502                         MEM_freeN(sce->toolsettings->wpaint);
503                 }
504                 if (sce->toolsettings->sculpt) {
505                         BKE_paint_free(&sce->toolsettings->sculpt->paint);
506                         MEM_freeN(sce->toolsettings->sculpt);
507                 }
508                 if (sce->toolsettings->uvsculpt) {
509                         BKE_paint_free(&sce->toolsettings->uvsculpt->paint);
510                         MEM_freeN(sce->toolsettings->uvsculpt);
511                 }
512                 BKE_paint_free(&sce->toolsettings->imapaint.paint);
513                 
514                 /* free Grease Pencil Drawing Brushes */
515                 BKE_gpencil_free_brushes(&sce->toolsettings->gp_brushes);
516                 BLI_freelistN(&sce->toolsettings->gp_brushes);
517                 
518                 /* free Grease Pencil interpolation curve */
519                 if (sce->toolsettings->gp_interpolate.custom_ipo) {
520                         curvemapping_free(sce->toolsettings->gp_interpolate.custom_ipo);
521                 }
522                 
523                 MEM_freeN(sce->toolsettings);
524                 sce->toolsettings = NULL;
525         }
526         
527         BKE_scene_free_depsgraph_hash(sce);
528
529         MEM_SAFE_FREE(sce->fps_info);
530
531         BKE_sound_destroy_scene(sce);
532
533         BKE_color_managed_view_settings_free(&sce->view_settings);
534
535         BKE_previewimg_free(&sce->preview);
536         curvemapping_free_data(&sce->r.mblur_shutter_curve);
537
538         for (ViewLayer *view_layer = sce->view_layers.first, *view_layer_next; view_layer; view_layer = view_layer_next) {
539                 view_layer_next = view_layer->next;
540
541                 BLI_remlink(&sce->view_layers, view_layer);
542                 BKE_view_layer_free_ex(view_layer, do_id_user);
543         }
544
545         /* Master Collection */
546         BKE_collection_master_free(&sce->id, do_id_user);
547         MEM_freeN(sce->collection);
548         sce->collection = NULL;
549
550         /* LayerCollection engine settings. */
551         if (sce->collection_properties) {
552                 IDP_FreeProperty(sce->collection_properties);
553                 MEM_freeN(sce->collection_properties);
554                 sce->collection_properties = NULL;
555         }
556
557         /* Render engine setting. */
558         if (sce->layer_properties) {
559                 IDP_FreeProperty(sce->layer_properties);
560                 MEM_freeN(sce->layer_properties);
561                 sce->layer_properties = NULL;
562         }
563 }
564
565 void BKE_scene_free(Scene *sce)
566 {
567         BKE_scene_free_ex(sce, true);
568 }
569
570 void BKE_scene_init(Scene *sce)
571 {
572         ParticleEditSettings *pset;
573         int a;
574         const char *colorspace_name;
575         SceneRenderView *srv;
576         CurveMapping *mblur_shutter_curve;
577
578         BLI_assert(MEMCMP_STRUCT_OFS_IS_ZERO(sce, id));
579
580         sce->lay = sce->layact = 1;
581         
582         sce->r.mode = R_GAMMA | R_OSA | R_SHADOW | R_SSS | R_ENVMAP | R_RAYTRACE;
583         sce->r.cfra = 1;
584         sce->r.sfra = 1;
585         sce->r.efra = 250;
586         sce->r.frame_step = 1;
587         sce->r.xsch = 1920;
588         sce->r.ysch = 1080;
589         sce->r.xasp = 1;
590         sce->r.yasp = 1;
591         sce->r.tilex = 256;
592         sce->r.tiley = 256;
593         sce->r.mblur_samples = 1;
594         sce->r.filtertype = R_FILTER_MITCH;
595         sce->r.size = 50;
596
597         sce->r.im_format.planes = R_IMF_PLANES_RGBA;
598         sce->r.im_format.imtype = R_IMF_IMTYPE_PNG;
599         sce->r.im_format.depth = R_IMF_CHAN_DEPTH_8;
600         sce->r.im_format.quality = 90;
601         sce->r.im_format.compress = 15;
602
603         sce->r.displaymode = R_OUTPUT_AREA;
604         sce->r.framapto = 100;
605         sce->r.images = 100;
606         sce->r.framelen = 1.0;
607         sce->r.blurfac = 0.5;
608         sce->r.frs_sec = 24;
609         sce->r.frs_sec_base = 1;
610         sce->r.edgeint = 10;
611         sce->r.ocres = 128;
612
613         /* OCIO_TODO: for forwards compatibility only, so if no tonecurve are used,
614          *            images would look in the same way as in current blender
615          *
616          *            perhaps at some point should be completely deprecated?
617          */
618         sce->r.color_mgt_flag |= R_COLOR_MANAGEMENT;
619
620         sce->r.gauss = 1.5f;
621         
622         /* deprecated but keep for upwards compat */
623         sce->r.postgamma = 1.0;
624         sce->r.posthue = 0.0;
625         sce->r.postsat = 1.0;
626
627         sce->r.bake_mode = 1;    /* prevent to include render stuff here */
628         sce->r.bake_filter = 16;
629         sce->r.bake_osa = 5;
630         sce->r.bake_flag = R_BAKE_CLEAR;
631         sce->r.bake_normal_space = R_BAKE_SPACE_TANGENT;
632         sce->r.bake_samples = 256;
633         sce->r.bake_biasdist = 0.001;
634
635         sce->r.bake.flag = R_BAKE_CLEAR;
636         sce->r.bake.pass_filter = R_BAKE_PASS_FILTER_ALL;
637         sce->r.bake.width = 512;
638         sce->r.bake.height = 512;
639         sce->r.bake.margin = 16;
640         sce->r.bake.normal_space = R_BAKE_SPACE_TANGENT;
641         sce->r.bake.normal_swizzle[0] = R_BAKE_POSX;
642         sce->r.bake.normal_swizzle[1] = R_BAKE_POSY;
643         sce->r.bake.normal_swizzle[2] = R_BAKE_POSZ;
644         BLI_strncpy(sce->r.bake.filepath, U.renderdir, sizeof(sce->r.bake.filepath));
645
646         sce->r.bake.im_format.planes = R_IMF_PLANES_RGBA;
647         sce->r.bake.im_format.imtype = R_IMF_IMTYPE_PNG;
648         sce->r.bake.im_format.depth = R_IMF_CHAN_DEPTH_8;
649         sce->r.bake.im_format.quality = 90;
650         sce->r.bake.im_format.compress = 15;
651
652         sce->r.scemode = R_DOCOMP | R_DOSEQ | R_EXTENSION;
653         sce->r.stamp = R_STAMP_TIME | R_STAMP_FRAME | R_STAMP_DATE | R_STAMP_CAMERA | R_STAMP_SCENE | R_STAMP_FILENAME | R_STAMP_RENDERTIME | R_STAMP_MEMORY;
654         sce->r.stamp_font_id = 12;
655         sce->r.fg_stamp[0] = sce->r.fg_stamp[1] = sce->r.fg_stamp[2] = 0.8f;
656         sce->r.fg_stamp[3] = 1.0f;
657         sce->r.bg_stamp[0] = sce->r.bg_stamp[1] = sce->r.bg_stamp[2] = 0.0f;
658         sce->r.bg_stamp[3] = 0.25f;
659         sce->r.raytrace_options = R_RAYTRACE_USE_INSTANCES;
660
661         sce->r.seq_prev_type = OB_SOLID;
662         sce->r.seq_rend_type = OB_SOLID;
663         sce->r.seq_flag = 0;
664
665         sce->r.threads = 1;
666
667         sce->r.simplify_subsurf = 6;
668         sce->r.simplify_particles = 1.0f;
669         sce->r.simplify_shadowsamples = 16;
670         sce->r.simplify_aosss = 1.0f;
671
672         sce->r.border.xmin = 0.0f;
673         sce->r.border.ymin = 0.0f;
674         sce->r.border.xmax = 1.0f;
675         sce->r.border.ymax = 1.0f;
676
677         sce->r.preview_start_resolution = 64;
678         
679         sce->r.line_thickness_mode = R_LINE_THICKNESS_ABSOLUTE;
680         sce->r.unit_line_thickness = 1.0f;
681
682         mblur_shutter_curve = &sce->r.mblur_shutter_curve;
683         curvemapping_set_defaults(mblur_shutter_curve, 1, 0.0f, 0.0f, 1.0f, 1.0f);
684         curvemapping_initialize(mblur_shutter_curve);
685         curvemap_reset(mblur_shutter_curve->cm,
686                        &mblur_shutter_curve->clipr,
687                        CURVE_PRESET_MAX,
688                        CURVEMAP_SLOPE_POS_NEG);
689
690         sce->toolsettings = MEM_callocN(sizeof(struct ToolSettings), "Tool Settings Struct");
691         sce->toolsettings->doublimit = 0.001;
692         sce->toolsettings->vgroup_weight = 1.0f;
693         sce->toolsettings->uvcalc_margin = 0.001f;
694         sce->toolsettings->unwrapper = 1;
695         sce->toolsettings->select_thresh = 0.01f;
696
697         sce->toolsettings->selectmode = SCE_SELECT_VERTEX;
698         sce->toolsettings->uv_selectmode = UV_SELECT_VERTEX;
699         sce->toolsettings->normalsize = 0.1;
700         sce->toolsettings->autokey_mode = U.autokey_mode;
701
702         sce->toolsettings->snap_node_mode = SCE_SNAP_MODE_GRID;
703
704         sce->toolsettings->skgen_resolution = 100;
705         sce->toolsettings->skgen_threshold_internal     = 0.01f;
706         sce->toolsettings->skgen_threshold_external     = 0.01f;
707         sce->toolsettings->skgen_angle_limit            = 45.0f;
708         sce->toolsettings->skgen_length_ratio           = 1.3f;
709         sce->toolsettings->skgen_length_limit           = 1.5f;
710         sce->toolsettings->skgen_correlation_limit      = 0.98f;
711         sce->toolsettings->skgen_symmetry_limit         = 0.1f;
712         sce->toolsettings->skgen_postpro = SKGEN_SMOOTH;
713         sce->toolsettings->skgen_postpro_passes = 1;
714         sce->toolsettings->skgen_options = SKGEN_FILTER_INTERNAL | SKGEN_FILTER_EXTERNAL | SKGEN_FILTER_SMART | SKGEN_HARMONIC | SKGEN_SUB_CORRELATION | SKGEN_STICK_TO_EMBEDDING;
715         sce->toolsettings->skgen_subdivisions[0] = SKGEN_SUB_CORRELATION;
716         sce->toolsettings->skgen_subdivisions[1] = SKGEN_SUB_LENGTH;
717         sce->toolsettings->skgen_subdivisions[2] = SKGEN_SUB_ANGLE;
718
719         sce->toolsettings->curve_paint_settings.curve_type = CU_BEZIER;
720         sce->toolsettings->curve_paint_settings.flag |= CURVE_PAINT_FLAG_CORNERS_DETECT;
721         sce->toolsettings->curve_paint_settings.error_threshold = 8;
722         sce->toolsettings->curve_paint_settings.radius_max = 1.0f;
723         sce->toolsettings->curve_paint_settings.corner_angle = DEG2RADF(70.0f);
724
725         sce->toolsettings->statvis.overhang_axis = OB_NEGZ;
726         sce->toolsettings->statvis.overhang_min = 0;
727         sce->toolsettings->statvis.overhang_max = DEG2RADF(45.0f);
728         sce->toolsettings->statvis.thickness_max = 0.1f;
729         sce->toolsettings->statvis.thickness_samples = 1;
730         sce->toolsettings->statvis.distort_min = DEG2RADF(5.0f);
731         sce->toolsettings->statvis.distort_max = DEG2RADF(45.0f);
732
733         sce->toolsettings->statvis.sharp_min = DEG2RADF(90.0f);
734         sce->toolsettings->statvis.sharp_max = DEG2RADF(180.0f);
735
736         sce->toolsettings->proportional_size = 1.0f;
737
738         sce->toolsettings->imapaint.paint.flags |= PAINT_SHOW_BRUSH;
739         sce->toolsettings->imapaint.normal_angle = 80;
740         sce->toolsettings->imapaint.seam_bleed = 2;
741
742         sce->physics_settings.gravity[0] = 0.0f;
743         sce->physics_settings.gravity[1] = 0.0f;
744         sce->physics_settings.gravity[2] = -9.81f;
745         sce->physics_settings.flag = PHYS_GLOBAL_GRAVITY;
746
747         sce->unit.scale_length = 1.0f;
748
749         pset = &sce->toolsettings->particle;
750         pset->flag = PE_KEEP_LENGTHS | PE_LOCK_FIRST | PE_DEFLECT_EMITTER | PE_AUTO_VELOCITY;
751         pset->emitterdist = 0.25f;
752         pset->totrekey = 5;
753         pset->totaddkey = 5;
754         pset->brushtype = PE_BRUSH_NONE;
755         pset->draw_step = 2;
756         pset->fade_frames = 2;
757         pset->selectmode = SCE_SELECT_PATH;
758
759         for (a = 0; a < ARRAY_SIZE(pset->brush); a++) {
760                 pset->brush[a].strength = 0.5f;
761                 pset->brush[a].size = 50;
762                 pset->brush[a].step = 10;
763                 pset->brush[a].count = 10;
764         }
765         pset->brush[PE_BRUSH_CUT].strength = 1.0f;
766
767         sce->r.ffcodecdata.audio_mixrate = 48000;
768         sce->r.ffcodecdata.audio_volume = 1.0f;
769         sce->r.ffcodecdata.audio_bitrate = 192;
770         sce->r.ffcodecdata.audio_channels = 2;
771
772         BKE_viewrender_init(&sce->view_render);
773
774         sce->audio.distance_model = 2.0f;
775         sce->audio.doppler_factor = 1.0f;
776         sce->audio.speed_of_sound = 343.3f;
777         sce->audio.volume = 1.0f;
778
779         BLI_strncpy(sce->r.pic, U.renderdir, sizeof(sce->r.pic));
780
781         BLI_rctf_init(&sce->r.safety, 0.1f, 0.9f, 0.1f, 0.9f);
782         sce->r.osa = 8;
783
784         /* note; in header_info.c the scene copy happens..., if you add more to renderdata it has to be checked there */
785
786         /* multiview - stereo */
787         BKE_scene_add_render_view(sce, STEREO_LEFT_NAME);
788         srv = sce->r.views.first;
789         BLI_strncpy(srv->suffix, STEREO_LEFT_SUFFIX, sizeof(srv->suffix));
790
791         BKE_scene_add_render_view(sce, STEREO_RIGHT_NAME);
792         srv = sce->r.views.last;
793         BLI_strncpy(srv->suffix, STEREO_RIGHT_SUFFIX, sizeof(srv->suffix));
794
795         /* game data */
796         sce->gm.stereoflag = STEREO_NOSTEREO;
797         sce->gm.stereomode = STEREO_ANAGLYPH;
798         sce->gm.eyeseparation = 0.10;
799
800         sce->gm.dome.angle = 180;
801         sce->gm.dome.mode = DOME_FISHEYE;
802         sce->gm.dome.res = 4;
803         sce->gm.dome.resbuf = 1.0f;
804         sce->gm.dome.tilt = 0;
805
806         sce->gm.xplay = 640;
807         sce->gm.yplay = 480;
808         sce->gm.freqplay = 60;
809         sce->gm.depth = 32;
810
811         sce->gm.gravity = 9.8f;
812         sce->gm.physicsEngine = WOPHY_BULLET;
813         sce->gm.mode = 32; //XXX ugly harcoding, still not sure we should drop mode. 32 == 1 << 5 == use_occlusion_culling 
814         sce->gm.occlusionRes = 128;
815         sce->gm.ticrate = 60;
816         sce->gm.maxlogicstep = 5;
817         sce->gm.physubstep = 1;
818         sce->gm.maxphystep = 5;
819         sce->gm.lineardeactthreshold = 0.8f;
820         sce->gm.angulardeactthreshold = 1.0f;
821         sce->gm.deactivationtime = 0.0f;
822
823         sce->gm.flag = 0;
824         sce->gm.matmode = GAME_MAT_MULTITEX;
825
826         sce->gm.obstacleSimulation = OBSTSIMULATION_NONE;
827         sce->gm.levelHeight = 2.f;
828
829         sce->gm.recastData.cellsize = 0.3f;
830         sce->gm.recastData.cellheight = 0.2f;
831         sce->gm.recastData.agentmaxslope = M_PI_4;
832         sce->gm.recastData.agentmaxclimb = 0.9f;
833         sce->gm.recastData.agentheight = 2.0f;
834         sce->gm.recastData.agentradius = 0.6f;
835         sce->gm.recastData.edgemaxlen = 12.0f;
836         sce->gm.recastData.edgemaxerror = 1.3f;
837         sce->gm.recastData.regionminsize = 8.f;
838         sce->gm.recastData.regionmergesize = 20.f;
839         sce->gm.recastData.vertsperpoly = 6;
840         sce->gm.recastData.detailsampledist = 6.0f;
841         sce->gm.recastData.detailsamplemaxerror = 1.0f;
842
843         sce->gm.lodflag = SCE_LOD_USE_HYST;
844         sce->gm.scehysteresis = 10;
845
846         sce->gm.exitkey = 218; // Blender key code for ESC
847
848         BKE_sound_create_scene(sce);
849
850         /* color management */
851         colorspace_name = IMB_colormanagement_role_colorspace_name_get(COLOR_ROLE_DEFAULT_SEQUENCER);
852
853         BKE_color_managed_display_settings_init(&sce->display_settings);
854         BKE_color_managed_view_settings_init(&sce->view_settings);
855         BLI_strncpy(sce->sequencer_colorspace_settings.name, colorspace_name,
856                     sizeof(sce->sequencer_colorspace_settings.name));
857
858         /* Safe Areas */
859         copy_v2_fl2(sce->safe_areas.title, 3.5f / 100.0f, 3.5f / 100.0f);
860         copy_v2_fl2(sce->safe_areas.action, 10.0f / 100.0f, 5.0f / 100.0f);
861         copy_v2_fl2(sce->safe_areas.title_center, 17.5f / 100.0f, 5.0f / 100.0f);
862         copy_v2_fl2(sce->safe_areas.action_center, 15.0f / 100.0f, 5.0f / 100.0f);
863
864         sce->preview = NULL;
865         
866         /* GP Sculpt brushes */
867         {
868                 GP_BrushEdit_Settings *gset = &sce->toolsettings->gp_sculpt;
869                 GP_EditBrush_Data *gp_brush;
870                 
871                 gp_brush = &gset->brush[GP_EDITBRUSH_TYPE_SMOOTH];
872                 gp_brush->size = 25;
873                 gp_brush->strength = 0.3f;
874                 gp_brush->flag = GP_EDITBRUSH_FLAG_USE_FALLOFF | GP_EDITBRUSH_FLAG_SMOOTH_PRESSURE;
875                 
876                 gp_brush = &gset->brush[GP_EDITBRUSH_TYPE_THICKNESS];
877                 gp_brush->size = 25;
878                 gp_brush->strength = 0.5f;
879                 gp_brush->flag = GP_EDITBRUSH_FLAG_USE_FALLOFF;
880                 
881                 gp_brush = &gset->brush[GP_EDITBRUSH_TYPE_STRENGTH];
882                 gp_brush->size = 25;
883                 gp_brush->strength = 0.5f;
884                 gp_brush->flag = GP_EDITBRUSH_FLAG_USE_FALLOFF;
885
886                 gp_brush = &gset->brush[GP_EDITBRUSH_TYPE_GRAB];
887                 gp_brush->size = 50;
888                 gp_brush->strength = 0.3f;
889                 gp_brush->flag = GP_EDITBRUSH_FLAG_USE_FALLOFF;
890                 
891                 gp_brush = &gset->brush[GP_EDITBRUSH_TYPE_PUSH];
892                 gp_brush->size = 25;
893                 gp_brush->strength = 0.3f;
894                 gp_brush->flag = GP_EDITBRUSH_FLAG_USE_FALLOFF;
895                 
896                 gp_brush = &gset->brush[GP_EDITBRUSH_TYPE_TWIST];
897                 gp_brush->size = 50;
898                 gp_brush->strength = 0.3f; // XXX?
899                 gp_brush->flag = GP_EDITBRUSH_FLAG_USE_FALLOFF;
900                 
901                 gp_brush = &gset->brush[GP_EDITBRUSH_TYPE_PINCH];
902                 gp_brush->size = 50;
903                 gp_brush->strength = 0.5f; // XXX?
904                 gp_brush->flag = GP_EDITBRUSH_FLAG_USE_FALLOFF;
905                 
906                 gp_brush = &gset->brush[GP_EDITBRUSH_TYPE_RANDOMIZE];
907                 gp_brush->size = 25;
908                 gp_brush->strength = 0.5f;
909                 gp_brush->flag = GP_EDITBRUSH_FLAG_USE_FALLOFF;
910         }
911         
912         /* GP Stroke Placement */
913         sce->toolsettings->gpencil_v3d_align = GP_PROJECT_VIEWSPACE;
914         sce->toolsettings->gpencil_v2d_align = GP_PROJECT_VIEWSPACE;
915         sce->toolsettings->gpencil_seq_align = GP_PROJECT_VIEWSPACE;
916         sce->toolsettings->gpencil_ima_align = GP_PROJECT_VIEWSPACE;
917
918         /* Master Collection */
919         sce->collection = MEM_callocN(sizeof(SceneCollection), "Master Collection");
920         BLI_strncpy(sce->collection->name, "Master Collection", sizeof(sce->collection->name));
921
922         /* Engine settings */
923         IDPropertyTemplate val = {0};
924         sce->collection_properties = IDP_New(IDP_GROUP, &val, ROOT_PROP);
925         BKE_layer_collection_engine_settings_create(sce->collection_properties);
926
927         sce->layer_properties = IDP_New(IDP_GROUP, &val, ROOT_PROP);
928         BKE_view_layer_engine_settings_create(sce->layer_properties);
929
930         BKE_view_layer_add(sce, "View Layer");
931 }
932
933 Scene *BKE_scene_add(Main *bmain, const char *name)
934 {
935         Scene *sce;
936
937         sce = BKE_libblock_alloc(bmain, ID_SCE, name, 0);
938         id_us_min(&sce->id);
939         id_us_ensure_real(&sce->id);
940
941         BKE_scene_init(sce);
942
943         return sce;
944 }
945
946 /**
947  * Check if there is any intance of the object in the scene
948  */
949 bool BKE_scene_object_find(Scene *scene, Object *ob)
950 {
951         for (ViewLayer *view_layer = scene->view_layers.first; view_layer; view_layer = view_layer->next) {
952                 if (BLI_findptr(&view_layer->object_bases, ob, offsetof(Base, object))) {
953                     return true;
954                 }
955         }
956         return false;
957 }
958
959 Object *BKE_scene_object_find_by_name(Scene *scene, const char *name)
960 {
961         for (ViewLayer *view_layer = scene->view_layers.first; view_layer; view_layer = view_layer->next) {
962                 for (Base *base = view_layer->object_bases.first; base; base = base->next) {
963                         if (STREQ(base->object->id.name + 2, name)) {
964                                 return base->object;
965                         }
966                 }
967         }
968         return NULL;
969 }
970
971 /**
972  * Sets the active scene, mainly used when running in background mode (``--scene`` command line argument).
973  * This is also called to set the scene directly, bypassing windowing code.
974  * Otherwise #WM_window_change_active_scene is used when changing scenes by the user.
975  */
976 void BKE_scene_set_background(Main *bmain, Scene *scene)
977 {
978         Object *ob;
979         Group *group;
980         
981         /* check for cyclic sets, for reading old files but also for definite security (py?) */
982         BKE_scene_validate_setscene(bmain, scene);
983         
984         /* deselect objects (for dataselect) */
985         for (ob = bmain->object.first; ob; ob = ob->id.next)
986                 ob->flag &= ~(SELECT | OB_FROMGROUP);
987
988         /* group flags again */
989         for (group = bmain->group.first; group; group = group->id.next) {
990                 FOREACH_GROUP_OBJECT(group, object)
991                 {
992                         object->flag |= OB_FROMGROUP;
993                 }
994                 FOREACH_GROUP_OBJECT_END
995         }
996
997         /* copy layers and flags from bases to objects */
998         for (ViewLayer *view_layer = scene->view_layers.first; view_layer; view_layer = view_layer->next) {
999                 for (Base *base = view_layer->object_bases.first; base; base = base->next) {
1000                         ob = base->object;
1001                         /* group patch... */
1002                         BKE_scene_object_base_flag_sync_from_base(base);
1003                 }
1004         }
1005         /* no full animation update, this to enable render code to work (render code calls own animation updates) */
1006 }
1007
1008 /* called from creator_args.c */
1009 Scene *BKE_scene_set_name(Main *bmain, const char *name)
1010 {
1011         Scene *sce = (Scene *)BKE_libblock_find_name_ex(bmain, ID_SCE, name);
1012         if (sce) {
1013                 BKE_scene_set_background(bmain, sce);
1014                 printf("Scene switch for render: '%s' in file: '%s'\n", name, bmain->name);
1015                 return sce;
1016         }
1017
1018         printf("Can't find scene: '%s' in file: '%s'\n", name, bmain->name);
1019         return NULL;
1020 }
1021
1022 /* Used by metaballs, return *all* objects (including duplis) existing in the scene (including scene's sets) */
1023 int BKE_scene_base_iter_next(
1024         const EvaluationContext *eval_ctx, SceneBaseIter *iter,
1025         Scene **scene, int val, Base **base, Object **ob)
1026 {
1027         bool run_again = true;
1028         
1029         /* init */
1030         if (val == 0) {
1031                 iter->phase = F_START;
1032                 iter->dupob = NULL;
1033                 iter->duplilist = NULL;
1034                 iter->dupli_refob = NULL;
1035         }
1036         else {
1037                 /* run_again is set when a duplilist has been ended */
1038                 while (run_again) {
1039                         run_again = false;
1040
1041                         /* the first base */
1042                         if (iter->phase == F_START) {
1043                                 ViewLayer *view_layer = eval_ctx->view_layer;
1044                                 *base = view_layer->object_bases.first;
1045                                 if (*base) {
1046                                         *ob = (*base)->object;
1047                                         iter->phase = F_SCENE;
1048                                 }
1049                                 else {
1050                                         /* exception: empty scene layer */
1051                                         while ((*scene)->set) {
1052                                                 (*scene) = (*scene)->set;
1053                                                 ViewLayer *view_layer_set = BKE_view_layer_from_scene_get((*scene));
1054                                                 if (view_layer_set->object_bases.first) {
1055                                                         *base = view_layer_set->object_bases.first;
1056                                                         *ob = (*base)->object;
1057                                                         iter->phase = F_SCENE;
1058                                                         break;
1059                                                 }
1060                                         }
1061                                 }
1062                         }
1063                         else {
1064                                 if (*base && iter->phase != F_DUPLI) {
1065                                         *base = (*base)->next;
1066                                         if (*base) {
1067                                                 *ob = (*base)->object;
1068                                         }
1069                                         else {
1070                                                 if (iter->phase == F_SCENE) {
1071                                                         /* (*scene) is finished, now do the set */
1072                                                         while ((*scene)->set) {
1073                                                                 (*scene) = (*scene)->set;
1074                                                                 ViewLayer *view_layer_set = BKE_view_layer_from_scene_get((*scene));
1075                                                                 if (view_layer_set->object_bases.first) {
1076                                                                         *base = view_layer_set->object_bases.first;
1077                                                                         *ob = (*base)->object;
1078                                                                         break;
1079                                                                 }
1080                                                         }
1081                                                 }
1082                                         }
1083                                 }
1084                         }
1085                         
1086                         if (*base == NULL) {
1087                                 iter->phase = F_START;
1088                         }
1089                         else {
1090                                 if (iter->phase != F_DUPLI) {
1091                                         if ( (*base)->object->transflag & OB_DUPLI) {
1092                                                 /* groups cannot be duplicated for mballs yet, 
1093                                                  * this enters eternal loop because of 
1094                                                  * makeDispListMBall getting called inside of group_duplilist */
1095                                                 if ((*base)->object->dup_group == NULL) {
1096                                                         iter->duplilist = object_duplilist_ex(eval_ctx, (*scene), (*base)->object, false);
1097                                                         
1098                                                         iter->dupob = iter->duplilist->first;
1099
1100                                                         if (!iter->dupob) {
1101                                                                 free_object_duplilist(iter->duplilist);
1102                                                                 iter->duplilist = NULL;
1103                                                         }
1104                                                         iter->dupli_refob = NULL;
1105                                                 }
1106                                         }
1107                                 }
1108                                 /* handle dupli's */
1109                                 if (iter->dupob) {
1110                                         (*base)->flag_legacy |= OB_FROMDUPLI;
1111                                         *ob = iter->dupob->ob;
1112                                         iter->phase = F_DUPLI;
1113
1114                                         if (iter->dupli_refob != *ob) {
1115                                                 if (iter->dupli_refob) {
1116                                                         /* Restore previous object's real matrix. */
1117                                                         copy_m4_m4(iter->dupli_refob->obmat, iter->omat);
1118                                                 }
1119                                                 /* Backup new object's real matrix. */
1120                                                 iter->dupli_refob = *ob;
1121                                                 copy_m4_m4(iter->omat, iter->dupli_refob->obmat);
1122                                         }
1123                                         copy_m4_m4((*ob)->obmat, iter->dupob->mat);
1124
1125                                         iter->dupob = iter->dupob->next;
1126                                 }
1127                                 else if (iter->phase == F_DUPLI) {
1128                                         iter->phase = F_SCENE;
1129                                         (*base)->flag_legacy &= ~OB_FROMDUPLI;
1130                                         
1131                                         if (iter->dupli_refob) {
1132                                                 /* Restore last object's real matrix. */
1133                                                 copy_m4_m4(iter->dupli_refob->obmat, iter->omat);
1134                                                 iter->dupli_refob = NULL;
1135                                         }
1136                                         
1137                                         free_object_duplilist(iter->duplilist);
1138                                         iter->duplilist = NULL;
1139                                         run_again = true;
1140                                 }
1141                         }
1142                 }
1143         }
1144
1145 #if 0
1146         if (ob && *ob) {
1147                 printf("Scene: '%s', '%s'\n", (*scene)->id.name + 2, (*ob)->id.name + 2);
1148         }
1149 #endif
1150
1151         return iter->phase;
1152 }
1153
1154 Scene *BKE_scene_find_from_collection(const Main *bmain, const SceneCollection *scene_collection)
1155 {
1156         for (Scene *scene = bmain->scene.first; scene; scene = scene->id.next) {
1157                 for (ViewLayer *layer = scene->view_layers.first; layer; layer = layer->next) {
1158                         if (BKE_view_layer_has_collection(layer, scene_collection)) {
1159                                 return scene;
1160                         }
1161                 }
1162         }
1163
1164         return NULL;
1165 }
1166
1167 #ifdef DURIAN_CAMERA_SWITCH
1168 Object *BKE_scene_camera_switch_find(Scene *scene)
1169 {
1170         if (scene->r.mode & R_NO_CAMERA_SWITCH) {
1171                 return NULL;
1172         }
1173
1174         TimeMarker *m;
1175         int cfra = scene->r.cfra;
1176         int frame = -(MAXFRAME + 1);
1177         int min_frame = MAXFRAME + 1;
1178         Object *camera = NULL;
1179         Object *first_camera = NULL;
1180
1181         for (m = scene->markers.first; m; m = m->next) {
1182                 if (m->camera && (m->camera->restrictflag & OB_RESTRICT_RENDER) == 0) {
1183                         if ((m->frame <= cfra) && (m->frame > frame)) {
1184                                 camera = m->camera;
1185                                 frame = m->frame;
1186
1187                                 if (frame == cfra)
1188                                         break;
1189                         }
1190
1191                         if (m->frame < min_frame) {
1192                                 first_camera = m->camera;
1193                                 min_frame = m->frame;
1194                         }
1195                 }
1196         }
1197
1198         if (camera == NULL) {
1199                 /* If there's no marker to the left of current frame,
1200                  * use camera from left-most marker to solve all sort
1201                  * of Schrodinger uncertainties.
1202                  */
1203                 return first_camera;
1204         }
1205
1206         return camera;
1207 }
1208 #endif
1209
1210 int BKE_scene_camera_switch_update(Scene *scene)
1211 {
1212 #ifdef DURIAN_CAMERA_SWITCH
1213         Object *camera = BKE_scene_camera_switch_find(scene);
1214         if (camera) {
1215                 scene->camera = camera;
1216                 return 1;
1217         }
1218 #else
1219         (void)scene;
1220 #endif
1221         return 0;
1222 }
1223
1224 char *BKE_scene_find_marker_name(Scene *scene, int frame)
1225 {
1226         ListBase *markers = &scene->markers;
1227         TimeMarker *m1, *m2;
1228
1229         /* search through markers for match */
1230         for (m1 = markers->first, m2 = markers->last; m1 && m2; m1 = m1->next, m2 = m2->prev) {
1231                 if (m1->frame == frame)
1232                         return m1->name;
1233
1234                 if (m1 == m2)
1235                         break;
1236
1237                 if (m2->frame == frame)
1238                         return m2->name;
1239         }
1240
1241         return NULL;
1242 }
1243
1244 /* return the current marker for this frame,
1245  * we can have more than 1 marker per frame, this just returns the first :/ */
1246 char *BKE_scene_find_last_marker_name(Scene *scene, int frame)
1247 {
1248         TimeMarker *marker, *best_marker = NULL;
1249         int best_frame = -MAXFRAME * 2;
1250         for (marker = scene->markers.first; marker; marker = marker->next) {
1251                 if (marker->frame == frame) {
1252                         return marker->name;
1253                 }
1254
1255                 if (marker->frame > best_frame && marker->frame < frame) {
1256                         best_marker = marker;
1257                         best_frame = marker->frame;
1258                 }
1259         }
1260
1261         return best_marker ? best_marker->name : NULL;
1262 }
1263
1264 void BKE_scene_remove_rigidbody_object(Scene *scene, Object *ob)
1265 {
1266         /* remove rigid body constraint from world before removing object */
1267         if (ob->rigidbody_constraint)
1268                 BKE_rigidbody_remove_constraint(scene, ob);
1269         /* remove rigid body object from world before removing object */
1270         if (ob->rigidbody_object)
1271                 BKE_rigidbody_remove_object(scene, ob);
1272 }
1273
1274 /* checks for cycle, returns 1 if it's all OK */
1275 bool BKE_scene_validate_setscene(Main *bmain, Scene *sce)
1276 {
1277         Scene *sce_iter;
1278         int a, totscene;
1279
1280         if (sce->set == NULL) return true;
1281         totscene = BLI_listbase_count(&bmain->scene);
1282         
1283         for (a = 0, sce_iter = sce; sce_iter->set; sce_iter = sce_iter->set, a++) {
1284                 /* more iterations than scenes means we have a cycle */
1285                 if (a > totscene) {
1286                         /* the tested scene gets zero'ed, that's typically current scene */
1287                         sce->set = NULL;
1288                         return false;
1289                 }
1290         }
1291
1292         return true;
1293 }
1294
1295 /* This function is needed to cope with fractional frames - including two Blender rendering features
1296  * mblur (motion blur that renders 'subframes' and blurs them together), and fields rendering. 
1297  */
1298 float BKE_scene_frame_get(const Scene *scene)
1299 {
1300         return BKE_scene_frame_get_from_ctime(scene, scene->r.cfra);
1301 }
1302
1303 /* This function is used to obtain arbitrary fractional frames */
1304 float BKE_scene_frame_get_from_ctime(const Scene *scene, const float frame)
1305 {
1306         float ctime = frame;
1307         ctime += scene->r.subframe;
1308         ctime *= scene->r.framelen;
1309         
1310         return ctime;
1311 }
1312
1313 /**
1314  * Sets the frame int/float components.
1315  */
1316 void BKE_scene_frame_set(struct Scene *scene, double cfra)
1317 {
1318         double intpart;
1319         scene->r.subframe = modf(cfra, &intpart);
1320         scene->r.cfra = (int)intpart;
1321 }
1322
1323 /* That's like really a bummer, because currently animation data for armatures
1324  * might want to use pose, and pose might be missing on the object.
1325  * This happens when changing visible layers, which leads to situations when
1326  * pose is missing or marked for recalc, animation will change it and then
1327  * object update will restore the pose.
1328  *
1329  * This could be solved by the new dependency graph, but for until then we'll
1330  * do an extra pass on the objects to ensure it's all fine.
1331  */
1332 #define POSE_ANIMATION_WORKAROUND
1333
1334 #ifdef POSE_ANIMATION_WORKAROUND
1335 static void scene_armature_depsgraph_workaround(Main *bmain)
1336 {
1337         Object *ob;
1338         if (BLI_listbase_is_empty(&bmain->armature) || !DEG_id_type_tagged(bmain, ID_OB)) {
1339                 return;
1340         }
1341         for (ob = bmain->object.first; ob; ob = ob->id.next) {
1342                 if (ob->type == OB_ARMATURE && ob->adt && ob->adt->recalc & ADT_RECALC_ANIM) {
1343                         if (ob->pose == NULL || (ob->pose->flag & POSE_RECALC)) {
1344                                 BKE_pose_rebuild(ob, ob->data);
1345                         }
1346                 }
1347         }
1348 }
1349 #endif
1350
1351 static bool check_rendered_viewport_visible(Main *bmain)
1352 {
1353         wmWindowManager *wm = bmain->wm.first;
1354         wmWindow *window;
1355         for (window = wm->windows.first; window != NULL; window = window->next) {
1356                 const bScreen *screen = BKE_workspace_active_screen_get(window->workspace_hook);
1357                 WorkSpace *workspace = BKE_workspace_active_get(window->workspace_hook);
1358                 Scene *scene = window->scene;
1359                 ViewRender *view_render = BKE_viewrender_get(scene, workspace);
1360                 ScrArea *area;
1361                 RenderEngineType *type = RE_engines_find(view_render->engine_id);
1362                 if ((type->draw_engine != NULL) || (type->render_to_view == NULL)) {
1363                         continue;
1364                 }
1365                 const bool use_legacy = (type->flag & RE_USE_LEGACY_PIPELINE) != 0;
1366                 for (area = screen->areabase.first; area != NULL; area = area->next) {
1367                         View3D *v3d = area->spacedata.first;
1368                         if (area->spacetype != SPACE_VIEW3D) {
1369                                 continue;
1370                         }
1371                         if (v3d->drawtype == OB_RENDER || !use_legacy) {
1372                                 return true;
1373                         }
1374                 }
1375         }
1376         return false;
1377 }
1378
1379 static void prepare_mesh_for_viewport_render(Main *bmain, const EvaluationContext *eval_ctx)
1380 {
1381         /* This is needed to prepare mesh to be used by the render
1382          * engine from the viewport rendering. We do loading here
1383          * so all the objects which shares the same mesh datablock
1384          * are nicely tagged for update and updated.
1385          *
1386          * This makes it so viewport render engine doesn't need to
1387          * call loading of the edit data for the mesh objects.
1388          */
1389
1390         Object *obedit = OBEDIT_FROM_EVAL_CTX(eval_ctx);
1391         if (obedit) {
1392                 Mesh *mesh = obedit->data;
1393                 if ((obedit->type == OB_MESH) &&
1394                     ((obedit->id.recalc & ID_RECALC_ALL) ||
1395                      (mesh->id.recalc & ID_RECALC_ALL)))
1396                 {
1397                         if (check_rendered_viewport_visible(bmain)) {
1398                                 BMesh *bm = mesh->edit_btmesh->bm;
1399                                 BM_mesh_bm_to_me(
1400                                         bm, mesh,
1401                                         (&(struct BMeshToMeshParams){
1402                                             .calc_object_remap = true,
1403                                         }));
1404                                 DEG_id_tag_update(&mesh->id, 0);
1405                         }
1406                 }
1407         }
1408 }
1409
1410 /* TODO(sergey): This actually should become view_layer_graph or so.
1411  * Same applies to update_for_newframe.
1412  */
1413 void BKE_scene_graph_update_tagged(EvaluationContext *eval_ctx,
1414                                    Depsgraph *depsgraph,
1415                                    Main *bmain,
1416                                    Scene *scene,
1417                                    ViewLayer *view_layer)
1418 {
1419         /* TODO(sergey): Temporary solution for until pipeline.c is ported. */
1420         if (view_layer == NULL) {
1421                 view_layer = DEG_get_evaluated_view_layer(depsgraph);
1422                 BLI_assert(view_layer != NULL);
1423         }
1424         /* TODO(sergey): Some functions here are changing global state,
1425          * for example, clearing update tags from bmain.
1426          */
1427         /* (Re-)build dependency graph if needed. */
1428         DEG_graph_relations_update(depsgraph, bmain, scene, view_layer);
1429         /* Uncomment this to check if graph was properly tagged for update. */
1430         // DEG_debug_graph_relations_validate(depsgraph, bmain, scene);
1431         /* Flush editing data if needed. */
1432         prepare_mesh_for_viewport_render(bmain, eval_ctx);
1433         /* Flush recalc flags to dependencies. */
1434         DEG_graph_flush_update(bmain, depsgraph);
1435         /* Update all objects: drivers, matrices, displists, etc. flags set
1436          * by depgraph or manual, no layer check here, gets correct flushed.
1437          */
1438         DEG_evaluate_on_refresh(eval_ctx, depsgraph);
1439         /* Update sound system animation (TODO, move to depsgraph). */
1440         BKE_sound_update_scene(bmain, scene);
1441         /* Inform editors about possible changes. */
1442         DEG_ids_check_recalc(bmain, depsgraph, scene, view_layer, false);
1443         /* Clear recalc flags. */
1444         DEG_ids_clear_recalc(bmain);
1445 }
1446
1447 /* applies changes right away, does all sets too */
1448 void BKE_scene_graph_update_for_newframe(EvaluationContext *eval_ctx,
1449                                          Depsgraph *depsgraph,
1450                                          Main *bmain,
1451                                          Scene *scene,
1452                                          ViewLayer *view_layer)
1453 {
1454         /* TODO(sergey): Temporary solution for until pipeline.c is ported. */
1455         if (view_layer == NULL) {
1456                 view_layer = DEG_get_evaluated_view_layer(depsgraph);
1457                 BLI_assert(view_layer != NULL);
1458         }
1459         /* TODO(sergey): Some functions here are changing global state,
1460          * for example, clearing update tags from bmain.
1461          */
1462         const float ctime = BKE_scene_frame_get(scene);
1463         /* Keep this first. */
1464         BLI_callback_exec(bmain, &scene->id, BLI_CB_EVT_FRAME_CHANGE_PRE);
1465         /* Update animated image textures for particles, modifiers, gpu, etc,
1466          * call this at the start so modifiers with textures don't lag 1 frame.
1467          */
1468         BKE_image_update_frame(bmain, scene->r.cfra);
1469         BKE_sound_set_cfra(scene->r.cfra);
1470         DEG_graph_relations_update(depsgraph, bmain, scene, view_layer);
1471         /* Update animated cache files for modifiers.
1472          *
1473          * TODO(sergey): Make this a depsgraph node?
1474          */
1475         BKE_cachefile_update_frame(bmain, scene, ctime,
1476                                    (((double)scene->r.frs_sec) / (double)scene->r.frs_sec_base));
1477 #ifdef POSE_ANIMATION_WORKAROUND
1478         scene_armature_depsgraph_workaround(bmain);
1479 #endif
1480         /* Update all objects: drivers, matrices, displists, etc. flags set
1481          * by depgraph or manual, no layer check here, gets correct flushed.
1482          */
1483         DEG_evaluate_on_framechange(eval_ctx, bmain, depsgraph, ctime);
1484         /* Update sound system animation (TODO, move to depsgraph). */
1485         BKE_sound_update_scene(bmain, scene);
1486         /* Notify editors and python about recalc. */
1487         BLI_callback_exec(bmain, &scene->id, BLI_CB_EVT_FRAME_CHANGE_POST);
1488         /* Inform editors about possible changes. */
1489         DEG_ids_check_recalc(bmain, depsgraph, scene, view_layer, true);
1490         /* clear recalc flags */
1491         DEG_ids_clear_recalc(bmain);
1492 }
1493
1494 /* return default view */
1495 SceneRenderView *BKE_scene_add_render_view(Scene *sce, const char *name)
1496 {
1497         SceneRenderView *srv;
1498
1499         if (!name)
1500                 name = DATA_("RenderView");
1501
1502         srv = MEM_callocN(sizeof(SceneRenderView), "new render view");
1503         BLI_strncpy(srv->name, name, sizeof(srv->name));
1504         BLI_uniquename(&sce->r.views, srv, DATA_("RenderView"), '.', offsetof(SceneRenderView, name), sizeof(srv->name));
1505         BLI_addtail(&sce->r.views, srv);
1506
1507         return srv;
1508 }
1509
1510 bool BKE_scene_remove_render_view(Scene *scene, SceneRenderView *srv)
1511 {
1512         const int act = BLI_findindex(&scene->r.views, srv);
1513
1514         if (act == -1) {
1515                 return false;
1516         }
1517         else if (scene->r.views.first == scene->r.views.last) {
1518                 /* ensure 1 view is kept */
1519                 return false;
1520         }
1521
1522         BLI_remlink(&scene->r.views, srv);
1523         MEM_freeN(srv);
1524
1525         scene->r.actview = 0;
1526
1527         return true;
1528 }
1529
1530 /* render simplification */
1531
1532 int get_render_subsurf_level(const RenderData *r, int lvl, bool for_render)
1533 {
1534         if (r->mode & R_SIMPLIFY) {
1535                 if (for_render)
1536                         return min_ii(r->simplify_subsurf_render, lvl);
1537                 else
1538                         return min_ii(r->simplify_subsurf, lvl);
1539         }
1540         else {
1541                 return lvl;
1542         }
1543 }
1544
1545 int get_render_child_particle_number(const RenderData *r, int num, bool for_render)
1546 {
1547         if (r->mode & R_SIMPLIFY) {
1548                 if (for_render)
1549                         return (int)(r->simplify_particles_render * num);
1550                 else
1551                         return (int)(r->simplify_particles * num);
1552         }
1553         else {
1554                 return num;
1555         }
1556 }
1557
1558 int get_render_shadow_samples(const RenderData *r, int samples)
1559 {
1560         if ((r->mode & R_SIMPLIFY) && samples > 0)
1561                 return min_ii(r->simplify_shadowsamples, samples);
1562         else
1563                 return samples;
1564 }
1565
1566 float get_render_aosss_error(const RenderData *r, float error)
1567 {
1568         if (r->mode & R_SIMPLIFY)
1569                 return ((1.0f - r->simplify_aosss) * 10.0f + 1.0f) * error;
1570         else
1571                 return error;
1572 }
1573
1574 /**
1575   * Helper function for the SETLOOPER and SETLOOPER_VIEW_LAYER macros
1576   *
1577   * It iterates over the bases of the active layer and then the bases
1578   * of the active layer of the background (set) scenes recursively.
1579   */
1580 Base *_setlooper_base_step(Scene **sce_iter, ViewLayer *view_layer, Base *base)
1581 {
1582         if (base && base->next) {
1583                 /* Common case, step to the next. */
1584                 return base->next;
1585         }
1586         else if ((base == NULL) && (view_layer != NULL)) {
1587                 /* First time looping, return the scenes first base. */
1588                 /* For the first loop we should get the layer from workspace when available. */
1589                 if (view_layer->object_bases.first) {
1590                         return (Base *)view_layer->object_bases.first;
1591                 }
1592                 /* No base on this scene layer. */
1593                 goto next_set;
1594         }
1595         else {
1596 next_set:
1597                 /* Reached the end, get the next base in the set. */
1598                 while ((*sce_iter = (*sce_iter)->set)) {
1599                         ViewLayer *view_layer_set = BKE_view_layer_from_scene_get((*sce_iter));
1600                         base = (Base *)view_layer_set->object_bases.first;
1601
1602                         if (base) {
1603                                 return base;
1604                         }
1605                 }
1606         }
1607
1608         return NULL;
1609 }
1610
1611 bool BKE_scene_use_new_shading_nodes(const Scene *scene)
1612 {
1613         return BKE_viewrender_use_new_shading_nodes(&scene->view_render);
1614 }
1615
1616 bool BKE_scene_use_shading_nodes_custom(Scene *scene)
1617 {
1618         return BKE_viewrender_use_shading_nodes_custom(&scene->view_render);
1619 }
1620
1621 bool BKE_scene_use_world_space_shading(Scene *scene)
1622 {
1623         RenderEngineType *type = RE_engines_find(scene->view_render.engine_id);
1624         return ((scene->r.mode & R_USE_WS_SHADING) ||
1625                 (type && (type->flag & RE_USE_SHADING_NODES)));
1626 }
1627
1628 bool BKE_scene_use_spherical_stereo(Scene *scene)
1629 {
1630         return BKE_viewrender_use_spherical_stereo(&scene->view_render);
1631 }
1632
1633 bool BKE_scene_uses_blender_internal(const Scene *scene)
1634 {
1635         return BKE_viewrender_uses_blender_internal(&scene->view_render);
1636 }
1637
1638 bool BKE_scene_uses_blender_game(const Scene *scene)
1639 {
1640         return BKE_viewrender_uses_blender_game(&scene->view_render);
1641 }
1642
1643 bool BKE_scene_uses_blender_eevee(const Scene *scene)
1644 {
1645         return BKE_viewrender_uses_blender_eevee(&scene->view_render);
1646 }
1647
1648 void BKE_scene_base_flag_to_objects(ViewLayer *view_layer)
1649 {
1650         Base *base = view_layer->object_bases.first;
1651
1652         while (base) {
1653                 BKE_scene_object_base_flag_sync_from_base(base);
1654                 base = base->next;
1655         }
1656 }
1657
1658 void BKE_scene_object_base_flag_sync_from_base(Base *base)
1659 {
1660         Object *ob = base->object;
1661
1662         /* keep the object only flags untouched */
1663         int flag = ob->flag & OB_FROMGROUP;
1664
1665         ob->flag = base->flag;
1666         ob->flag |= flag;
1667
1668         if ((base->flag & BASE_SELECTED) != 0) {
1669                 ob->flag |= SELECT;
1670         }
1671         else {
1672                 ob->flag &= ~SELECT;
1673         }
1674 }
1675
1676 void BKE_scene_object_base_flag_sync_from_object(Base *base)
1677 {
1678         Object *ob = base->object;
1679         base->flag = ob->flag;
1680
1681         if ((ob->flag & SELECT) != 0) {
1682                 base->flag |= BASE_SELECTED;
1683                 BLI_assert((base->flag & BASE_SELECTABLED) != 0);
1684         }
1685         else {
1686                 base->flag &= ~BASE_SELECTED;
1687         }
1688 }
1689
1690 void BKE_scene_disable_color_management(Scene *scene)
1691 {
1692         ColorManagedDisplaySettings *display_settings = &scene->display_settings;
1693         ColorManagedViewSettings *view_settings = &scene->view_settings;
1694         const char *view;
1695         const char *none_display_name;
1696
1697         none_display_name = IMB_colormanagement_display_get_none_name();
1698
1699         BLI_strncpy(display_settings->display_device, none_display_name, sizeof(display_settings->display_device));
1700
1701         view = IMB_colormanagement_view_get_default_name(display_settings->display_device);
1702
1703         if (view) {
1704                 BLI_strncpy(view_settings->view_transform, view, sizeof(view_settings->view_transform));
1705         }
1706 }
1707
1708 bool BKE_scene_check_color_management_enabled(const Scene *scene)
1709 {
1710         return !STREQ(scene->display_settings.display_device, "None");
1711 }
1712
1713 bool BKE_scene_check_rigidbody_active(const Scene *scene)
1714 {
1715         return scene && scene->rigidbody_world && scene->rigidbody_world->group && !(scene->rigidbody_world->flag & RBW_FLAG_MUTED);
1716 }
1717
1718 int BKE_render_num_threads(const RenderData *rd)
1719 {
1720         int threads;
1721
1722         /* override set from command line? */
1723         threads = BLI_system_num_threads_override_get();
1724
1725         if (threads > 0)
1726                 return threads;
1727
1728         /* fixed number of threads specified in scene? */
1729         if (rd->mode & R_FIXED_THREADS)
1730                 threads = rd->threads;
1731         else
1732                 threads = BLI_system_thread_count();
1733         
1734         return max_ii(threads, 1);
1735 }
1736
1737 int BKE_scene_num_threads(const Scene *scene)
1738 {
1739         return BKE_render_num_threads(&scene->r);
1740 }
1741
1742 int BKE_render_preview_pixel_size(const RenderData *r)
1743 {
1744         if (r->preview_pixel_size == 0) {
1745                 return (U.pixelsize > 1.5f) ? 2 : 1;
1746         }
1747         return r->preview_pixel_size;
1748 }
1749
1750 /* ***************************************************** */
1751 /* render engine settings */
1752
1753 ViewRender *BKE_viewrender_get(Scene *scene, WorkSpace *workspace)
1754 {
1755         if (workspace == NULL || BKE_workspace_use_scene_settings_get(workspace)) {
1756                 return &scene->view_render;
1757         }
1758         return BKE_workspace_view_render_get(workspace);
1759 }
1760
1761 /**
1762  * Initialize a static created struct for WorkSpace and Scene to store the viewport
1763  * related drawing data.
1764  */
1765 void BKE_viewrender_init(ViewRender *view_render)
1766 {
1767         BLI_strncpy(view_render->engine_id, RE_engine_id_BLENDER_EEVEE, sizeof(view_render->engine_id));
1768 }
1769
1770 /**
1771  * Do not free ViewRender itself since it's not even allocated.
1772  */
1773 void BKE_viewrender_free(ViewRender *UNUSED(view_render))
1774 {
1775         /* Do nothing. */
1776 }
1777
1778 /**
1779  * Copy used by libblock copying.
1780  */
1781 void BKE_viewrender_copy(ViewRender *to, const ViewRender *from)
1782 {
1783         *to = *from;
1784 }
1785
1786 bool BKE_viewrender_use_new_shading_nodes(const ViewRender *view_render)
1787 {
1788         RenderEngineType *type = RE_engines_find(view_render->engine_id);
1789         return (type && type->flag & RE_USE_SHADING_NODES);
1790 }
1791
1792 bool BKE_viewrender_use_shading_nodes_custom(const ViewRender *view_render)
1793 {
1794         RenderEngineType *type = RE_engines_find(view_render->engine_id);
1795         return (type && type->flag & RE_USE_SHADING_NODES_CUSTOM);
1796 }
1797
1798 bool BKE_viewrender_use_spherical_stereo(const ViewRender *view_render)
1799 {
1800         const char *engine_id = view_render->engine_id;
1801         RenderEngineType *type = RE_engines_find(engine_id);
1802         return (type && type->flag & RE_USE_SPHERICAL_STEREO);
1803 }
1804
1805 bool BKE_viewrender_uses_blender_internal(const ViewRender *view_render)
1806 {
1807         const char *engine_id = view_render->engine_id;
1808         return STREQ(engine_id, RE_engine_id_BLENDER_RENDER);
1809 }
1810
1811 bool BKE_viewrender_uses_blender_game(const ViewRender *view_render)
1812 {
1813         const char *engine_id = view_render->engine_id;
1814         return STREQ(engine_id, RE_engine_id_BLENDER_GAME);
1815 }
1816
1817 bool BKE_viewrender_uses_blender_eevee(const ViewRender *view_render)
1818 {
1819         const char *engine_id = view_render->engine_id;
1820         return STREQ(engine_id, RE_engine_id_BLENDER_EEVEE);
1821 }
1822
1823 /* ***************************************************** */
1824
1825 /* Apply the needed correction factor to value, based on unit_type (only length-related are affected currently)
1826  * and unit->scale_length.
1827  */
1828 double BKE_scene_unit_scale(const UnitSettings *unit, const int unit_type, double value)
1829 {
1830         if (unit->system == USER_UNIT_NONE) {
1831                 /* Never apply scale_length when not using a unit setting! */
1832                 return value;
1833         }
1834
1835         switch (unit_type) {
1836                 case B_UNIT_LENGTH:
1837                         return value * (double)unit->scale_length;
1838                 case B_UNIT_AREA:
1839                         return value * pow(unit->scale_length, 2);
1840                 case B_UNIT_VOLUME:
1841                         return value * pow(unit->scale_length, 3);
1842                 case B_UNIT_MASS:
1843                         return value * pow(unit->scale_length, 3);
1844                 case B_UNIT_CAMERA:  /* *Do not* use scene's unit scale for camera focal lens! See T42026. */
1845                 default:
1846                         return value;
1847         }
1848 }
1849
1850 /******************** multiview *************************/
1851
1852 int BKE_scene_multiview_num_views_get(const RenderData *rd)
1853 {
1854         SceneRenderView *srv;
1855         int totviews = 0;
1856
1857         if ((rd->scemode & R_MULTIVIEW) == 0)
1858                 return 1;
1859
1860         if (rd->views_format == SCE_VIEWS_FORMAT_STEREO_3D) {
1861                 srv = BLI_findstring(&rd->views, STEREO_LEFT_NAME, offsetof(SceneRenderView, name));
1862                 if ((srv && srv->viewflag & SCE_VIEW_DISABLE) == 0) {
1863                         totviews++;
1864                 }
1865
1866                 srv = BLI_findstring(&rd->views, STEREO_RIGHT_NAME, offsetof(SceneRenderView, name));
1867                 if ((srv && srv->viewflag & SCE_VIEW_DISABLE) == 0) {
1868                         totviews++;
1869                 }
1870         }
1871         else {
1872                 for (srv = rd->views.first; srv; srv = srv->next) {
1873                         if ((srv->viewflag & SCE_VIEW_DISABLE) == 0) {
1874                                 totviews++;
1875                         }
1876                 }
1877         }
1878         return totviews;
1879 }
1880
1881 bool BKE_scene_multiview_is_stereo3d(const RenderData *rd)
1882 {
1883         SceneRenderView *srv[2];
1884
1885         if ((rd->scemode & R_MULTIVIEW) == 0)
1886                 return false;
1887
1888         srv[0] = (SceneRenderView *)BLI_findstring(&rd->views, STEREO_LEFT_NAME, offsetof(SceneRenderView, name));
1889         srv[1] = (SceneRenderView *)BLI_findstring(&rd->views, STEREO_RIGHT_NAME, offsetof(SceneRenderView, name));
1890
1891         return (srv[0] && ((srv[0]->viewflag & SCE_VIEW_DISABLE) == 0) &&
1892                 srv[1] && ((srv[1]->viewflag & SCE_VIEW_DISABLE) == 0));
1893 }
1894
1895 /* return whether to render this SceneRenderView */
1896 bool BKE_scene_multiview_is_render_view_active(const RenderData *rd, const SceneRenderView *srv)
1897 {
1898         if (srv == NULL)
1899                 return false;
1900
1901         if ((rd->scemode & R_MULTIVIEW) == 0)
1902                 return false;
1903
1904         if ((srv->viewflag & SCE_VIEW_DISABLE))
1905                 return false;
1906
1907         if (rd->views_format == SCE_VIEWS_FORMAT_MULTIVIEW)
1908                 return true;
1909
1910         /* SCE_VIEWS_SETUP_BASIC */
1911         if (STREQ(srv->name, STEREO_LEFT_NAME) ||
1912             STREQ(srv->name, STEREO_RIGHT_NAME))
1913         {
1914                 return true;
1915         }
1916
1917         return false;
1918 }
1919
1920 /* return true if viewname is the first or if the name is NULL or not found */
1921 bool BKE_scene_multiview_is_render_view_first(const RenderData *rd, const char *viewname)
1922 {
1923         SceneRenderView *srv;
1924
1925         if ((rd->scemode & R_MULTIVIEW) == 0)
1926                 return true;
1927
1928         if ((!viewname) || (!viewname[0]))
1929                 return true;
1930
1931         for (srv = rd->views.first; srv; srv = srv->next) {
1932                 if (BKE_scene_multiview_is_render_view_active(rd, srv)) {
1933                         return STREQ(viewname, srv->name);
1934                 }
1935         }
1936
1937         return true;
1938 }
1939
1940 /* return true if viewname is the last or if the name is NULL or not found */
1941 bool BKE_scene_multiview_is_render_view_last(const RenderData *rd, const char *viewname)
1942 {
1943         SceneRenderView *srv;
1944
1945         if ((rd->scemode & R_MULTIVIEW) == 0)
1946                 return true;
1947
1948         if ((!viewname) || (!viewname[0]))
1949                 return true;
1950
1951         for (srv = rd->views.last; srv; srv = srv->prev) {
1952                 if (BKE_scene_multiview_is_render_view_active(rd, srv)) {
1953                         return STREQ(viewname, srv->name);
1954                 }
1955         }
1956
1957         return true;
1958 }
1959
1960 SceneRenderView *BKE_scene_multiview_render_view_findindex(const RenderData *rd, const int view_id)
1961 {
1962         SceneRenderView *srv;
1963         size_t nr;
1964
1965         if ((rd->scemode & R_MULTIVIEW) == 0)
1966                 return NULL;
1967
1968         for (srv = rd->views.first, nr = 0; srv; srv = srv->next) {
1969                 if (BKE_scene_multiview_is_render_view_active(rd, srv)) {
1970                         if (nr++ == view_id)
1971                                 return srv;
1972                 }
1973         }
1974         return srv;
1975 }
1976
1977 const char *BKE_scene_multiview_render_view_name_get(const RenderData *rd, const int view_id)
1978 {
1979         SceneRenderView *srv = BKE_scene_multiview_render_view_findindex(rd, view_id);
1980
1981         if (srv)
1982                 return srv->name;
1983         else
1984                 return "";
1985 }
1986
1987 int BKE_scene_multiview_view_id_get(const RenderData *rd, const char *viewname)
1988 {
1989         SceneRenderView *srv;
1990         size_t nr;
1991
1992         if ((!rd) || ((rd->scemode & R_MULTIVIEW) == 0))
1993                 return 0;
1994
1995         if ((!viewname) || (!viewname[0]))
1996                 return 0;
1997
1998         for (srv = rd->views.first, nr = 0; srv; srv = srv->next) {
1999                 if (BKE_scene_multiview_is_render_view_active(rd, srv)) {
2000                         if (STREQ(viewname, srv->name)) {
2001                                 return nr;
2002                         }
2003                         else {
2004                                 nr += 1;
2005                         }
2006                 }
2007         }
2008
2009         return 0;
2010 }
2011
2012 void BKE_scene_multiview_filepath_get(
2013         SceneRenderView *srv, const char *filepath,
2014         char *r_filepath)
2015 {
2016         BLI_strncpy(r_filepath, filepath, FILE_MAX);
2017         BLI_path_suffix(r_filepath, FILE_MAX, srv->suffix, "");
2018 }
2019
2020 /**
2021  * When multiview is not used the filepath is as usual (e.g., ``Image.jpg``).
2022  * When multiview is on, even if only one view is enabled the view is incorporated
2023  * into the file name (e.g., ``Image_L.jpg``). That allows for the user to re-render
2024  * individual views.
2025  */
2026 void BKE_scene_multiview_view_filepath_get(
2027         const RenderData *rd, const char *filepath, const char *viewname,
2028         char *r_filepath)
2029 {
2030         SceneRenderView *srv;
2031         char suffix[FILE_MAX];
2032
2033         srv = BLI_findstring(&rd->views, viewname, offsetof(SceneRenderView, name));
2034         if (srv)
2035                 BLI_strncpy(suffix, srv->suffix, sizeof(suffix));
2036         else
2037                 BLI_strncpy(suffix, viewname, sizeof(suffix));
2038
2039         BLI_strncpy(r_filepath, filepath, FILE_MAX);
2040         BLI_path_suffix(r_filepath, FILE_MAX, suffix, "");
2041 }
2042
2043 const char *BKE_scene_multiview_view_suffix_get(const RenderData *rd, const char *viewname)
2044 {
2045         SceneRenderView *srv;
2046
2047         if ((viewname == NULL) || (viewname[0] == '\0'))
2048                 return viewname;
2049
2050         srv = BLI_findstring(&rd->views, viewname, offsetof(SceneRenderView, name));
2051         if (srv)
2052                 return srv->suffix;
2053         else
2054                 return viewname;
2055 }
2056
2057 const char *BKE_scene_multiview_view_id_suffix_get(const RenderData *rd, const int view_id)
2058 {
2059         if ((rd->scemode & R_MULTIVIEW) == 0) {
2060                 return "";
2061         }
2062         else {
2063                 const char *viewname = BKE_scene_multiview_render_view_name_get(rd, view_id);
2064                 return BKE_scene_multiview_view_suffix_get(rd, viewname);
2065         }
2066 }
2067
2068 void BKE_scene_multiview_view_prefix_get(Scene *scene, const char *name, char *rprefix, const char **rext)
2069 {
2070         SceneRenderView *srv;
2071         size_t index_act;
2072         const char *suf_act;
2073         const char delims[] = {'.', '\0'};
2074
2075         rprefix[0] = '\0';
2076
2077         /* begin of extension */
2078         index_act = BLI_str_rpartition(name, delims, rext, &suf_act);
2079         if (*rext == NULL)
2080                 return;
2081         BLI_assert(index_act > 0);
2082         UNUSED_VARS_NDEBUG(index_act);
2083
2084         for (srv = scene->r.views.first; srv; srv = srv->next) {
2085                 if (BKE_scene_multiview_is_render_view_active(&scene->r, srv)) {
2086                         size_t len = strlen(srv->suffix);
2087                         if (strlen(*rext) >= len && STREQLEN(*rext - len, srv->suffix, len)) {
2088                                 BLI_strncpy(rprefix, name, strlen(name) - strlen(*rext) - len + 1);
2089                                 break;
2090                         }
2091                 }
2092         }
2093 }
2094
2095 void BKE_scene_multiview_videos_dimensions_get(
2096         const RenderData *rd, const size_t width, const size_t height,
2097         size_t *r_width, size_t *r_height)
2098 {
2099         if ((rd->scemode & R_MULTIVIEW) &&
2100             rd->im_format.views_format == R_IMF_VIEWS_STEREO_3D)
2101         {
2102                 IMB_stereo3d_write_dimensions(
2103                         rd->im_format.stereo3d_format.display_mode,
2104                         (rd->im_format.stereo3d_format.flag & S3D_SQUEEZED_FRAME) != 0,
2105                         width, height,
2106                         r_width, r_height);
2107         }
2108         else {
2109                 *r_width = width;
2110                 *r_height = height;
2111         }
2112 }
2113
2114 int BKE_scene_multiview_num_videos_get(const RenderData *rd)
2115 {
2116         if (BKE_imtype_is_movie(rd->im_format.imtype) == false)
2117                 return 0;
2118
2119         if ((rd->scemode & R_MULTIVIEW) == 0)
2120                 return 1;
2121
2122         if (rd->im_format.views_format == R_IMF_VIEWS_STEREO_3D) {
2123                 return 1;
2124         }
2125         else {
2126                 /* R_IMF_VIEWS_INDIVIDUAL */
2127                 return BKE_scene_multiview_num_views_get(rd);
2128         }
2129 }
2130
2131 /* Manipulation of depsgraph storage. */
2132
2133 /* This is a key which identifies depsgraph. */
2134 typedef struct DepsgraphKey {
2135         ViewLayer *view_layer;
2136         /* TODO(sergey): Need to include window somehow (same layer might be in a
2137          * different states in different windows).
2138          */
2139 } DepsgraphKey;
2140
2141 static unsigned int depsgraph_key_hash(const void *key_v)
2142 {
2143         const DepsgraphKey *key = key_v;
2144         unsigned int hash = BLI_ghashutil_ptrhash(key->view_layer);
2145         /* TODO(sergey): Include hash from other fields in the key. */
2146         return hash;
2147 }
2148
2149 static bool depsgraph_key_compare(const void *key_a_v, const void *key_b_v)
2150 {
2151         const DepsgraphKey *key_a = key_a_v;
2152         const DepsgraphKey *key_b = key_b_v;
2153         /* TODO(sergey): Compare rest of  */
2154         return !(key_a->view_layer == key_b->view_layer);
2155 }
2156
2157 static void depsgraph_key_free(void *key_v)
2158 {
2159         DepsgraphKey *key = key_v;
2160         MEM_freeN(key);
2161 }
2162
2163 static void depsgraph_key_value_free(void *value)
2164 {
2165         Depsgraph *depsgraph = value;
2166         DEG_graph_free(depsgraph);
2167 }
2168
2169 void BKE_scene_allocate_depsgraph_hash(Scene *scene)
2170 {
2171         scene->depsgraph_hash = BLI_ghash_new(depsgraph_key_hash,
2172                                               depsgraph_key_compare,
2173                                               "Scene Depsgraph Hash");
2174 }
2175
2176 void BKE_scene_ensure_depsgraph_hash(Scene *scene)
2177 {
2178         if (scene->depsgraph_hash == NULL) {
2179                 BKE_scene_allocate_depsgraph_hash(scene);
2180         }
2181 }
2182
2183 void BKE_scene_free_depsgraph_hash(Scene *scene)
2184 {
2185         if (scene->depsgraph_hash == NULL) {
2186                 return;
2187         }
2188         BLI_ghash_free(scene->depsgraph_hash,
2189                        depsgraph_key_free,
2190                        depsgraph_key_value_free);
2191 }
2192
2193 /* Query depsgraph for a specific contexts. */
2194
2195 Depsgraph *BKE_scene_get_depsgraph(Scene *scene,
2196                                    ViewLayer *view_layer,
2197                                    bool allocate)
2198 {
2199         BLI_assert(scene != NULL);
2200         BLI_assert(view_layer != NULL);
2201         /* Make sure hash itself exists. */
2202         if (allocate) {
2203                 BKE_scene_ensure_depsgraph_hash(scene);
2204         }
2205         if (scene->depsgraph_hash == NULL) {
2206                 return NULL;
2207         }
2208         /* Either ensure item is in the hash or simply return NULL if it's not,
2209          * depending on whether caller wants us to create depsgraph or not.
2210          */
2211         DepsgraphKey key;
2212         key.view_layer = view_layer;
2213         Depsgraph *depsgraph;
2214         if (allocate) {
2215                 DepsgraphKey **key_ptr;
2216                 Depsgraph **depsgraph_ptr;
2217                 if (!BLI_ghash_ensure_p_ex(scene->depsgraph_hash,
2218                                            &key,
2219                                            (void ***)&key_ptr,
2220                                            (void ***)&depsgraph_ptr))
2221                 {
2222                         *key_ptr = MEM_mallocN(sizeof(DepsgraphKey), __func__);
2223                         **key_ptr = key;
2224                         *depsgraph_ptr = DEG_graph_new();
2225                 }
2226                 depsgraph = *depsgraph_ptr;
2227         }
2228         else {
2229                 depsgraph = BLI_ghash_lookup(scene->depsgraph_hash, &key);
2230         }
2231         return depsgraph;
2232 }