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