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