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