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