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