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