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