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