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