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