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