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