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