Threaded object update and EvaluationContext
[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 #ifndef WIN32 
38 #include <unistd.h>
39 #else
40 #include <io.h>
41 #endif
42
43 #include "MEM_guardedalloc.h"
44
45 #include "DNA_anim_types.h"
46 #include "DNA_group_types.h"
47 #include "DNA_linestyle_types.h"
48 #include "DNA_node_types.h"
49 #include "DNA_object_types.h"
50 #include "DNA_rigidbody_types.h"
51 #include "DNA_scene_types.h"
52 #include "DNA_screen_types.h"
53 #include "DNA_sequence_types.h"
54
55 #include "BLI_math.h"
56 #include "BLI_blenlib.h"
57 #include "BLI_utildefines.h"
58 #include "BLI_callbacks.h"
59 #include "BLI_string.h"
60 #include "BLI_threads.h"
61 #include "BLI_task.h"
62
63 #include "BLF_translation.h"
64
65 #include "BKE_anim.h"
66 #include "BKE_animsys.h"
67 #include "BKE_action.h"
68 #include "BKE_colortools.h"
69 #include "BKE_depsgraph.h"
70 #include "BKE_fcurve.h"
71 #include "BKE_freestyle.h"
72 #include "BKE_global.h"
73 #include "BKE_group.h"
74 #include "BKE_idprop.h"
75 #include "BKE_image.h"
76 #include "BKE_library.h"
77 #include "BKE_main.h"
78 #include "BKE_mask.h"
79 #include "BKE_node.h"
80 #include "BKE_object.h"
81 #include "BKE_paint.h"
82 #include "BKE_pointcache.h"
83 #include "BKE_rigidbody.h"
84 #include "BKE_scene.h"
85 #include "BKE_sequencer.h"
86 #include "BKE_sound.h"
87 #include "BKE_world.h"
88
89 #include "RE_engine.h"
90
91 #include "PIL_time.h"
92
93 #include "IMB_colormanagement.h"
94
95 //XXX #include "BIF_previewrender.h"
96 //XXX #include "BIF_editseq.h"
97
98 #ifdef WIN32
99 #else
100 #include <sys/time.h>
101 #endif
102
103 void free_avicodecdata(AviCodecData *acd)
104 {
105         if (acd) {
106                 if (acd->lpFormat) {
107                         MEM_freeN(acd->lpFormat);
108                         acd->lpFormat = NULL;
109                         acd->cbFormat = 0;
110                 }
111                 if (acd->lpParms) {
112                         MEM_freeN(acd->lpParms);
113                         acd->lpParms = NULL;
114                         acd->cbParms = 0;
115                 }
116         }
117 }
118
119 void free_qtcodecdata(QuicktimeCodecData *qcd)
120 {
121         if (qcd) {
122                 if (qcd->cdParms) {
123                         MEM_freeN(qcd->cdParms);
124                         qcd->cdParms = NULL;
125                         qcd->cdSize = 0;
126                 }
127         }
128 }
129
130 static void remove_sequencer_fcurves(Scene *sce)
131 {
132         AnimData *adt = BKE_animdata_from_id(&sce->id);
133
134         if (adt && adt->action) {
135                 FCurve *fcu, *nextfcu;
136                 
137                 for (fcu = adt->action->curves.first; fcu; fcu = nextfcu) {
138                         nextfcu = fcu->next;
139                         
140                         if ((fcu->rna_path) && strstr(fcu->rna_path, "sequences_all")) {
141                                 action_groups_remove_channel(adt->action, fcu);
142                                 free_fcurve(fcu);
143                         }
144                 }
145         }
146 }
147
148 Scene *BKE_scene_copy(Scene *sce, int type)
149 {
150         Scene *scen;
151         SceneRenderLayer *srl, *new_srl;
152         ToolSettings *ts;
153         Base *base, *obase;
154         
155         if (type == SCE_COPY_EMPTY) {
156                 ListBase lb;
157                 /* XXX. main should become an arg */
158                 scen = BKE_scene_add(G.main, sce->id.name + 2);
159                 
160                 lb = scen->r.layers;
161                 scen->r = sce->r;
162                 scen->r.layers = lb;
163                 scen->r.actlay = 0;
164                 scen->unit = sce->unit;
165                 scen->physics_settings = sce->physics_settings;
166                 scen->gm = sce->gm;
167                 scen->audio = sce->audio;
168
169                 if (sce->id.properties)
170                         scen->id.properties = IDP_CopyProperty(sce->id.properties);
171
172                 MEM_freeN(scen->toolsettings);
173         }
174         else {
175                 scen = BKE_libblock_copy(&sce->id);
176                 BLI_duplicatelist(&(scen->base), &(sce->base));
177                 
178                 clear_id_newpoins();
179                 
180                 id_us_plus((ID *)scen->world);
181                 id_us_plus((ID *)scen->set);
182                 id_us_plus((ID *)scen->gm.dome.warptext);
183
184                 scen->ed = NULL;
185                 scen->theDag = NULL;
186                 scen->obedit = NULL;
187                 scen->stats = NULL;
188                 scen->fps_info = NULL;
189
190                 if (sce->rigidbody_world)
191                         scen->rigidbody_world = BKE_rigidbody_world_copy(sce->rigidbody_world);
192
193                 BLI_duplicatelist(&(scen->markers), &(sce->markers));
194                 BLI_duplicatelist(&(scen->transform_spaces), &(sce->transform_spaces));
195                 BLI_duplicatelist(&(scen->r.layers), &(sce->r.layers));
196                 BKE_keyingsets_copy(&(scen->keyingsets), &(sce->keyingsets));
197
198                 if (sce->nodetree) {
199                         /* ID's are managed on both copy and switch */
200                         scen->nodetree = ntreeCopyTree(sce->nodetree);
201                         ntreeSwitchID(scen->nodetree, &sce->id, &scen->id);
202                 }
203
204                 obase = sce->base.first;
205                 base = scen->base.first;
206                 while (base) {
207                         id_us_plus(&base->object->id);
208                         if (obase == sce->basact) scen->basact = base;
209         
210                         obase = obase->next;
211                         base = base->next;
212                 }
213
214                 /* copy color management settings */
215                 BKE_color_managed_display_settings_copy(&scen->display_settings, &sce->display_settings);
216                 BKE_color_managed_view_settings_copy(&scen->view_settings, &sce->view_settings);
217                 BKE_color_managed_view_settings_copy(&scen->r.im_format.view_settings, &sce->r.im_format.view_settings);
218
219                 BLI_strncpy(scen->sequencer_colorspace_settings.name, sce->sequencer_colorspace_settings.name,
220                             sizeof(scen->sequencer_colorspace_settings.name));
221
222                 /* remove animation used by sequencer */
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                 ts->particle.paintcursor = NULL;
261         }
262         
263         /* make a private copy of the avicodecdata */
264         if (sce->r.avicodecdata) {
265                 scen->r.avicodecdata = MEM_dupallocN(sce->r.avicodecdata);
266                 scen->r.avicodecdata->lpFormat = MEM_dupallocN(scen->r.avicodecdata->lpFormat);
267                 scen->r.avicodecdata->lpParms = MEM_dupallocN(scen->r.avicodecdata->lpParms);
268         }
269         
270         /* make a private copy of the qtcodecdata */
271         if (sce->r.qtcodecdata) {
272                 scen->r.qtcodecdata = MEM_dupallocN(sce->r.qtcodecdata);
273                 scen->r.qtcodecdata->cdParms = MEM_dupallocN(scen->r.qtcodecdata->cdParms);
274         }
275         
276         if (sce->r.ffcodecdata.properties) { /* intentionally check scen not sce. */
277                 scen->r.ffcodecdata.properties = IDP_CopyProperty(sce->r.ffcodecdata.properties);
278         }
279
280         /* NOTE: part of SCE_COPY_LINK_DATA and SCE_COPY_FULL operations
281          * are done outside of blenkernel with ED_objects_single_users! */
282
283         /*  camera */
284         if (type == SCE_COPY_LINK_DATA || type == SCE_COPY_FULL) {
285                 ID_NEW(scen->camera);
286         }
287         
288         /* before scene copy */
289         sound_create_scene(scen);
290
291         /* world */
292         if (type == SCE_COPY_FULL) {
293                 BKE_copy_animdata_id_action((ID *)scen);
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->scene, 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.ocres = 128;
454
455         /* OCIO_TODO: for forwards compatibility only, so if no tonecurve are used,
456          *            images would look in the same way as in current blender
457          *
458          *            perhaps at some point should be completely deprecated?
459          */
460         sce->r.color_mgt_flag |= R_COLOR_MANAGEMENT;
461
462         sce->r.gauss = 1.0;
463         
464         /* deprecated but keep for upwards compat */
465         sce->r.postgamma = 1.0;
466         sce->r.posthue = 0.0;
467         sce->r.postsat = 1.0;
468
469         sce->r.bake_mode = 1;    /* prevent to include render stuff here */
470         sce->r.bake_filter = 16;
471         sce->r.bake_osa = 5;
472         sce->r.bake_flag = R_BAKE_CLEAR;
473         sce->r.bake_normal_space = R_BAKE_SPACE_TANGENT;
474         sce->r.bake_samples = 256;
475         sce->r.bake_biasdist = 0.001;
476         sce->r.scemode = R_DOCOMP | R_DOSEQ | R_EXTENSION;
477         sce->r.stamp = R_STAMP_TIME | R_STAMP_FRAME | R_STAMP_DATE | R_STAMP_CAMERA | R_STAMP_SCENE | R_STAMP_FILENAME | R_STAMP_RENDERTIME;
478         sce->r.stamp_font_id = 12;
479         sce->r.fg_stamp[0] = sce->r.fg_stamp[1] = sce->r.fg_stamp[2] = 0.8f;
480         sce->r.fg_stamp[3] = 1.0f;
481         sce->r.bg_stamp[0] = sce->r.bg_stamp[1] = sce->r.bg_stamp[2] = 0.0f;
482         sce->r.bg_stamp[3] = 0.25f;
483         sce->r.raytrace_options = R_RAYTRACE_USE_INSTANCES;
484
485         sce->r.seq_prev_type = OB_SOLID;
486         sce->r.seq_rend_type = OB_SOLID;
487         sce->r.seq_flag = R_SEQ_GL_PREV;
488
489         sce->r.threads = 1;
490
491         sce->r.simplify_subsurf = 6;
492         sce->r.simplify_particles = 1.0f;
493         sce->r.simplify_shadowsamples = 16;
494         sce->r.simplify_aosss = 1.0f;
495
496         sce->r.border.xmin = 0.0f;
497         sce->r.border.ymin = 0.0f;
498         sce->r.border.xmax = 1.0f;
499         sce->r.border.ymax = 1.0f;
500         
501         sce->toolsettings = MEM_callocN(sizeof(struct ToolSettings), "Tool Settings Struct");
502         sce->toolsettings->doublimit = 0.001;
503         sce->toolsettings->uvcalc_margin = 0.001f;
504         sce->toolsettings->unwrapper = 1;
505         sce->toolsettings->select_thresh = 0.01f;
506
507         sce->toolsettings->selectmode = SCE_SELECT_VERTEX;
508         sce->toolsettings->uv_selectmode = UV_SELECT_VERTEX;
509         sce->toolsettings->normalsize = 0.1;
510         sce->toolsettings->autokey_mode = U.autokey_mode;
511
512         sce->toolsettings->snap_node_mode = SCE_SNAP_MODE_GRID;
513
514         sce->toolsettings->skgen_resolution = 100;
515         sce->toolsettings->skgen_threshold_internal     = 0.01f;
516         sce->toolsettings->skgen_threshold_external     = 0.01f;
517         sce->toolsettings->skgen_angle_limit            = 45.0f;
518         sce->toolsettings->skgen_length_ratio           = 1.3f;
519         sce->toolsettings->skgen_length_limit           = 1.5f;
520         sce->toolsettings->skgen_correlation_limit      = 0.98f;
521         sce->toolsettings->skgen_symmetry_limit         = 0.1f;
522         sce->toolsettings->skgen_postpro = SKGEN_SMOOTH;
523         sce->toolsettings->skgen_postpro_passes = 1;
524         sce->toolsettings->skgen_options = SKGEN_FILTER_INTERNAL | SKGEN_FILTER_EXTERNAL | SKGEN_FILTER_SMART | SKGEN_HARMONIC | SKGEN_SUB_CORRELATION | SKGEN_STICK_TO_EMBEDDING;
525         sce->toolsettings->skgen_subdivisions[0] = SKGEN_SUB_CORRELATION;
526         sce->toolsettings->skgen_subdivisions[1] = SKGEN_SUB_LENGTH;
527         sce->toolsettings->skgen_subdivisions[2] = SKGEN_SUB_ANGLE;
528
529         sce->toolsettings->statvis.overhang_axis = OB_NEGZ;
530         sce->toolsettings->statvis.overhang_min = 0;
531         sce->toolsettings->statvis.overhang_max = DEG2RADF(45.0f);
532         sce->toolsettings->statvis.thickness_max = 0.1f;
533         sce->toolsettings->statvis.thickness_samples = 1;
534         sce->toolsettings->statvis.distort_min = DEG2RADF(5.0f);
535         sce->toolsettings->statvis.distort_max = DEG2RADF(45.0f);
536
537         sce->toolsettings->statvis.sharp_min = DEG2RADF(90.0f);
538         sce->toolsettings->statvis.sharp_max = DEG2RADF(180.0f);
539
540         sce->toolsettings->proportional_size = 1.0f;
541
542         sce->physics_settings.gravity[0] = 0.0f;
543         sce->physics_settings.gravity[1] = 0.0f;
544         sce->physics_settings.gravity[2] = -9.81f;
545         sce->physics_settings.flag = PHYS_GLOBAL_GRAVITY;
546
547         sce->unit.scale_length = 1.0f;
548
549         pset = &sce->toolsettings->particle;
550         pset->flag = PE_KEEP_LENGTHS | PE_LOCK_FIRST | PE_DEFLECT_EMITTER | PE_AUTO_VELOCITY;
551         pset->emitterdist = 0.25f;
552         pset->totrekey = 5;
553         pset->totaddkey = 5;
554         pset->brushtype = PE_BRUSH_NONE;
555         pset->draw_step = 2;
556         pset->fade_frames = 2;
557         pset->selectmode = SCE_SELECT_PATH;
558         for (a = 0; a < PE_TOT_BRUSH; a++) {
559                 pset->brush[a].strength = 0.5;
560                 pset->brush[a].size = 50;
561                 pset->brush[a].step = 10;
562                 pset->brush[a].count = 10;
563         }
564         pset->brush[PE_BRUSH_CUT].strength = 100;
565
566         sce->r.ffcodecdata.audio_mixrate = 44100;
567         sce->r.ffcodecdata.audio_volume = 1.0f;
568         sce->r.ffcodecdata.audio_bitrate = 192;
569         sce->r.ffcodecdata.audio_channels = 2;
570
571         BLI_strncpy(sce->r.engine, "BLENDER_RENDER", sizeof(sce->r.engine));
572
573         sce->audio.distance_model = 2.0f;
574         sce->audio.doppler_factor = 1.0f;
575         sce->audio.speed_of_sound = 343.3f;
576         sce->audio.volume = 1.0f;
577
578         BLI_strncpy(sce->r.pic, U.renderdir, sizeof(sce->r.pic));
579
580         BLI_rctf_init(&sce->r.safety, 0.1f, 0.9f, 0.1f, 0.9f);
581         sce->r.osa = 8;
582
583         /* note; in header_info.c the scene copy happens..., if you add more to renderdata it has to be checked there */
584         BKE_scene_add_render_layer(sce, NULL);
585         
586         /* game data */
587         sce->gm.stereoflag = STEREO_NOSTEREO;
588         sce->gm.stereomode = STEREO_ANAGLYPH;
589         sce->gm.eyeseparation = 0.10;
590
591         sce->gm.dome.angle = 180;
592         sce->gm.dome.mode = DOME_FISHEYE;
593         sce->gm.dome.res = 4;
594         sce->gm.dome.resbuf = 1.0f;
595         sce->gm.dome.tilt = 0;
596
597         sce->gm.xplay = 640;
598         sce->gm.yplay = 480;
599         sce->gm.freqplay = 60;
600         sce->gm.depth = 32;
601
602         sce->gm.gravity = 9.8f;
603         sce->gm.physicsEngine = WOPHY_BULLET;
604         sce->gm.mode = 32; //XXX ugly harcoding, still not sure we should drop mode. 32 == 1 << 5 == use_occlusion_culling 
605         sce->gm.occlusionRes = 128;
606         sce->gm.ticrate = 60;
607         sce->gm.maxlogicstep = 5;
608         sce->gm.physubstep = 1;
609         sce->gm.maxphystep = 5;
610         sce->gm.lineardeactthreshold = 0.8f;
611         sce->gm.angulardeactthreshold = 1.0f;
612         sce->gm.deactivationtime = 0.0f;
613
614         sce->gm.flag = GAME_DISPLAY_LISTS;
615         sce->gm.matmode = GAME_MAT_MULTITEX;
616
617         sce->gm.obstacleSimulation = OBSTSIMULATION_NONE;
618         sce->gm.levelHeight = 2.f;
619
620         sce->gm.recastData.cellsize = 0.3f;
621         sce->gm.recastData.cellheight = 0.2f;
622         sce->gm.recastData.agentmaxslope = M_PI / 2;
623         sce->gm.recastData.agentmaxclimb = 0.9f;
624         sce->gm.recastData.agentheight = 2.0f;
625         sce->gm.recastData.agentradius = 0.6f;
626         sce->gm.recastData.edgemaxlen = 12.0f;
627         sce->gm.recastData.edgemaxerror = 1.3f;
628         sce->gm.recastData.regionminsize = 8.f;
629         sce->gm.recastData.regionmergesize = 20.f;
630         sce->gm.recastData.vertsperpoly = 6;
631         sce->gm.recastData.detailsampledist = 6.0f;
632         sce->gm.recastData.detailsamplemaxerror = 1.0f;
633
634         sce->gm.exitkey = 218; // Blender key code for ESC
635
636         sound_create_scene(sce);
637
638         /* color management */
639         colorspace_name = IMB_colormanagement_role_colorspace_name_get(COLOR_ROLE_DEFAULT_SEQUENCER);
640
641         BKE_color_managed_display_settings_init(&sce->display_settings);
642         BKE_color_managed_view_settings_init(&sce->view_settings);
643         BLI_strncpy(sce->sequencer_colorspace_settings.name, colorspace_name,
644                     sizeof(sce->sequencer_colorspace_settings.name));
645
646         return sce;
647 }
648
649 Base *BKE_scene_base_find(Scene *scene, Object *ob)
650 {
651         return BLI_findptr(&scene->base, ob, offsetof(Base, object));
652 }
653
654 void BKE_scene_set_background(Main *bmain, Scene *scene)
655 {
656         Scene *sce;
657         Base *base;
658         Object *ob;
659         Group *group;
660         GroupObject *go;
661         int flag;
662         
663         /* check for cyclic sets, for reading old files but also for definite security (py?) */
664         BKE_scene_validate_setscene(bmain, scene);
665         
666         /* can happen when switching modes in other scenes */
667         if (scene->obedit && !(scene->obedit->mode & OB_MODE_EDIT))
668                 scene->obedit = NULL;
669
670         /* deselect objects (for dataselect) */
671         for (ob = bmain->object.first; ob; ob = ob->id.next)
672                 ob->flag &= ~(SELECT | OB_FROMGROUP);
673
674         /* group flags again */
675         for (group = bmain->group.first; group; group = group->id.next) {
676                 for (go = group->gobject.first; go; go = go->next) {
677                         if (go->ob) {
678                                 go->ob->flag |= OB_FROMGROUP;
679                         }
680                 }
681         }
682
683         /* sort baselist for scene and sets */
684         for (sce = scene; sce; sce = sce->set)
685                 DAG_scene_relations_rebuild(bmain, sce);
686
687         /* copy layers and flags from bases to objects */
688         for (base = scene->base.first; base; base = base->next) {
689                 ob = base->object;
690                 ob->lay = base->lay;
691                 
692                 /* group patch... */
693                 base->flag &= ~(OB_FROMGROUP);
694                 flag = ob->flag & (OB_FROMGROUP);
695                 base->flag |= flag;
696                 
697                 /* not too nice... for recovering objects with lost data */
698                 //if (ob->pose == NULL) base->flag &= ~OB_POSEMODE;
699                 ob->flag = base->flag;
700         }
701         /* no full animation update, this to enable render code to work (render code calls own animation updates) */
702 }
703
704 /* called from creator.c */
705 Scene *BKE_scene_set_name(Main *bmain, const char *name)
706 {
707         Scene *sce = (Scene *)BKE_libblock_find_name(ID_SCE, name);
708         if (sce) {
709                 BKE_scene_set_background(bmain, sce);
710                 printf("Scene switch: '%s' in file: '%s'\n", name, G.main->name);
711                 return sce;
712         }
713
714         printf("Can't find scene: '%s' in file: '%s'\n", name, G.main->name);
715         return NULL;
716 }
717
718 void BKE_scene_unlink(Main *bmain, Scene *sce, Scene *newsce)
719 {
720         Scene *sce1;
721         bScreen *sc;
722
723         /* check all sets */
724         for (sce1 = bmain->scene.first; sce1; sce1 = sce1->id.next)
725                 if (sce1->set == sce)
726                         sce1->set = NULL;
727         
728         /* check render layer nodes in other scenes */
729         clear_scene_in_nodes(bmain, sce);
730         
731         /* al screens */
732         for (sc = bmain->screen.first; sc; sc = sc->id.next)
733                 if (sc->scene == sce)
734                         sc->scene = newsce;
735
736         BKE_libblock_free(&bmain->scene, sce);
737 }
738
739 /* used by metaballs
740  * doesn't return the original duplicated object, only dupli's
741  */
742 int BKE_scene_base_iter_next(EvaluationContext *eval_ctx, SceneBaseIter *iter,
743                              Scene **scene, int val, Base **base, Object **ob)
744 {
745         int run_again = 1;
746         
747         /* init */
748         if (val == 0) {
749                 iter->fase = F_START;
750                 iter->dupob = NULL;
751                 iter->duplilist = NULL;
752         }
753         else {
754                 /* run_again is set when a duplilist has been ended */
755                 while (run_again) {
756                         run_again = 0;
757
758                         /* the first base */
759                         if (iter->fase == F_START) {
760                                 *base = (*scene)->base.first;
761                                 if (*base) {
762                                         *ob = (*base)->object;
763                                         iter->fase = F_SCENE;
764                                 }
765                                 else {
766                                         /* exception: empty scene */
767                                         while ((*scene)->set) {
768                                                 (*scene) = (*scene)->set;
769                                                 if ((*scene)->base.first) {
770                                                         *base = (*scene)->base.first;
771                                                         *ob = (*base)->object;
772                                                         iter->fase = F_SCENE;
773                                                         break;
774                                                 }
775                                         }
776                                 }
777                         }
778                         else {
779                                 if (*base && iter->fase != F_DUPLI) {
780                                         *base = (*base)->next;
781                                         if (*base) {
782                                                 *ob = (*base)->object;
783                                         }
784                                         else {
785                                                 if (iter->fase == F_SCENE) {
786                                                         /* (*scene) is finished, now do the set */
787                                                         while ((*scene)->set) {
788                                                                 (*scene) = (*scene)->set;
789                                                                 if ((*scene)->base.first) {
790                                                                         *base = (*scene)->base.first;
791                                                                         *ob = (*base)->object;
792                                                                         break;
793                                                                 }
794                                                         }
795                                                 }
796                                         }
797                                 }
798                         }
799                         
800                         if (*base == NULL) {
801                                 iter->fase = F_START;
802                         }
803                         else {
804                                 if (iter->fase != F_DUPLI) {
805                                         if ( (*base)->object->transflag & OB_DUPLI) {
806                                                 /* groups cannot be duplicated for mballs yet, 
807                                                  * this enters eternal loop because of 
808                                                  * makeDispListMBall getting called inside of group_duplilist */
809                                                 if ((*base)->object->dup_group == NULL) {
810                                                         iter->duplilist = object_duplilist_ex(eval_ctx, (*scene), (*base)->object, false);
811                                                         
812                                                         iter->dupob = iter->duplilist->first;
813
814                                                         if (!iter->dupob)
815                                                                 free_object_duplilist(iter->duplilist);
816                                                 }
817                                         }
818                                 }
819                                 /* handle dupli's */
820                                 if (iter->dupob) {
821                                         
822                                         copy_m4_m4(iter->dupob->ob->obmat, iter->dupob->mat);
823                                         
824                                         (*base)->flag |= OB_FROMDUPLI;
825                                         *ob = iter->dupob->ob;
826                                         iter->fase = F_DUPLI;
827                                         
828                                         iter->dupob = iter->dupob->next;
829                                 }
830                                 else if (iter->fase == F_DUPLI) {
831                                         iter->fase = F_SCENE;
832                                         (*base)->flag &= ~OB_FROMDUPLI;
833                                         
834                                         for (iter->dupob = iter->duplilist->first; iter->dupob; iter->dupob = iter->dupob->next) {
835                                                 copy_m4_m4(iter->dupob->ob->obmat, iter->dupob->omat);
836                                         }
837                                         
838                                         free_object_duplilist(iter->duplilist);
839                                         iter->duplilist = NULL;
840                                         run_again = 1;
841                                 }
842                         }
843                 }
844         }
845
846 #if 0
847         if (ob && *ob) {
848                 printf("Scene: '%s', '%s'\n", (*scene)->id.name + 2, (*ob)->id.name + 2);
849         }
850 #endif
851
852         return iter->fase;
853 }
854
855 Object *BKE_scene_camera_find(Scene *sc)
856 {
857         Base *base;
858         
859         for (base = sc->base.first; base; base = base->next)
860                 if (base->object->type == OB_CAMERA)
861                         return base->object;
862
863         return NULL;
864 }
865
866 #ifdef DURIAN_CAMERA_SWITCH
867 Object *BKE_scene_camera_switch_find(Scene *scene)
868 {
869         TimeMarker *m;
870         int cfra = scene->r.cfra;
871         int frame = -(MAXFRAME + 1);
872         int min_frame = MAXFRAME + 1;
873         Object *camera = NULL;
874         Object *first_camera = NULL;
875
876         for (m = scene->markers.first; m; m = m->next) {
877                 if (m->camera && (m->camera->restrictflag & OB_RESTRICT_RENDER) == 0) {
878                         if ((m->frame <= cfra) && (m->frame > frame)) {
879                                 camera = m->camera;
880                                 frame = m->frame;
881
882                                 if (frame == cfra)
883                                         break;
884                         }
885
886                         if (m->frame < min_frame) {
887                                 first_camera = m->camera;
888                                 min_frame = m->frame;
889                         }
890                 }
891         }
892
893         if (camera == NULL) {
894                 /* If there's no marker to the left of current frame,
895                  * use camera from left-most marker to solve all sort
896                  * of Schrodinger uncertainties.
897                  */
898                 return first_camera;
899         }
900
901         return camera;
902 }
903 #endif
904
905 int BKE_scene_camera_switch_update(Scene *scene)
906 {
907 #ifdef DURIAN_CAMERA_SWITCH
908         Object *camera = BKE_scene_camera_switch_find(scene);
909         if (camera) {
910                 scene->camera = camera;
911                 return 1;
912         }
913 #else
914         (void)scene;
915 #endif
916         return 0;
917 }
918
919 char *BKE_scene_find_marker_name(Scene *scene, int frame)
920 {
921         ListBase *markers = &scene->markers;
922         TimeMarker *m1, *m2;
923
924         /* search through markers for match */
925         for (m1 = markers->first, m2 = markers->last; m1 && m2; m1 = m1->next, m2 = m2->prev) {
926                 if (m1->frame == frame)
927                         return m1->name;
928
929                 if (m1 == m2)
930                         break;
931
932                 if (m2->frame == frame)
933                         return m2->name;
934         }
935
936         return NULL;
937 }
938
939 /* return the current marker for this frame,
940  * we can have more than 1 marker per frame, this just returns the first :/ */
941 char *BKE_scene_find_last_marker_name(Scene *scene, int frame)
942 {
943         TimeMarker *marker, *best_marker = NULL;
944         int best_frame = -MAXFRAME * 2;
945         for (marker = scene->markers.first; marker; marker = marker->next) {
946                 if (marker->frame == frame) {
947                         return marker->name;
948                 }
949
950                 if (marker->frame > best_frame && marker->frame < frame) {
951                         best_marker = marker;
952                         best_frame = marker->frame;
953                 }
954         }
955
956         return best_marker ? best_marker->name : NULL;
957 }
958
959
960 Base *BKE_scene_base_add(Scene *sce, Object *ob)
961 {
962         Base *b = MEM_callocN(sizeof(*b), "BKE_scene_base_add");
963         BLI_addhead(&sce->base, b);
964
965         b->object = ob;
966         b->flag = ob->flag;
967         b->lay = ob->lay;
968
969         return b;
970 }
971
972 void BKE_scene_base_unlink(Scene *sce, Base *base)
973 {
974         /* remove rigid body constraint from world before removing object */
975         if (base->object->rigidbody_constraint)
976                 BKE_rigidbody_remove_constraint(sce, base->object);
977         /* remove rigid body object from world before removing object */
978         if (base->object->rigidbody_object)
979                 BKE_rigidbody_remove_object(sce, base->object);
980         
981         BLI_remlink(&sce->base, base);
982 }
983
984 void BKE_scene_base_deselect_all(Scene *sce)
985 {
986         Base *b;
987
988         for (b = sce->base.first; b; b = b->next) {
989                 b->flag &= ~SELECT;
990                 b->object->flag = b->flag;
991         }
992 }
993
994 void BKE_scene_base_select(Scene *sce, Base *selbase)
995 {
996         selbase->flag |= SELECT;
997         selbase->object->flag = selbase->flag;
998
999         sce->basact = selbase;
1000 }
1001
1002 /* checks for cycle, returns 1 if it's all OK */
1003 int BKE_scene_validate_setscene(Main *bmain, Scene *sce)
1004 {
1005         Scene *scene;
1006         int a, totscene;
1007         
1008         if (sce->set == NULL) return 1;
1009         
1010         totscene = 0;
1011         for (scene = bmain->scene.first; scene; scene = scene->id.next)
1012                 totscene++;
1013         
1014         for (a = 0, scene = sce; scene->set; scene = scene->set, a++) {
1015                 /* more iterations than scenes means we have a cycle */
1016                 if (a > totscene) {
1017                         /* the tested scene gets zero'ed, that's typically current scene */
1018                         sce->set = NULL;
1019                         return 0;
1020                 }
1021         }
1022
1023         return 1;
1024 }
1025
1026 /* This function is needed to cope with fractional frames - including two Blender rendering features
1027  * mblur (motion blur that renders 'subframes' and blurs them together), and fields rendering. 
1028  */
1029 float BKE_scene_frame_get(Scene *scene)
1030 {
1031         return BKE_scene_frame_get_from_ctime(scene, scene->r.cfra);
1032 }
1033
1034 /* This function is used to obtain arbitrary fractional frames */
1035 float BKE_scene_frame_get_from_ctime(Scene *scene, const float frame)
1036 {
1037         float ctime = frame;
1038         ctime += scene->r.subframe;
1039         ctime *= scene->r.framelen;
1040         
1041         return ctime;
1042 }
1043
1044 /**
1045  * Sets the frame int/float components.
1046  */
1047 void BKE_scene_frame_set(struct Scene *scene, double cfra)
1048 {
1049         double intpart;
1050         scene->r.subframe = modf(cfra, &intpart);
1051         scene->r.cfra = (int)intpart;
1052
1053         if (cfra < 0.0) {
1054                 scene->r.cfra -= 1;
1055                 scene->r.subframe = 1.0f + scene->r.subframe;
1056         }
1057 }
1058
1059 /* drivers support/hacks 
1060  *  - this method is called from scene_update_tagged_recursive(), so gets included in viewport + render
1061  *      - these are always run since the depsgraph can't handle non-object data
1062  *      - these happen after objects are all done so that we can read in their final transform values,
1063  *        though this means that objects can't refer to scene info for guidance...
1064  */
1065 static void scene_update_drivers(Main *UNUSED(bmain), Scene *scene)
1066 {
1067         SceneRenderLayer *srl;
1068         float ctime = BKE_scene_frame_get(scene);
1069         
1070         /* scene itself */
1071         if (scene->adt && scene->adt->drivers.first) {
1072                 BKE_animsys_evaluate_animdata(scene, &scene->id, scene->adt, ctime, ADT_RECALC_DRIVERS);
1073         }
1074
1075         /* world */
1076         /* TODO: what about world textures? but then those have nodes too... */
1077         if (scene->world) {
1078                 ID *wid = (ID *)scene->world;
1079                 AnimData *adt = BKE_animdata_from_id(wid);
1080                 
1081                 if (adt && adt->drivers.first)
1082                         BKE_animsys_evaluate_animdata(scene, wid, adt, ctime, ADT_RECALC_DRIVERS);
1083         }
1084         
1085         /* nodes */
1086         if (scene->nodetree) {
1087                 ID *nid = (ID *)scene->nodetree;
1088                 AnimData *adt = BKE_animdata_from_id(nid);
1089                 
1090                 if (adt && adt->drivers.first)
1091                         BKE_animsys_evaluate_animdata(scene, nid, adt, ctime, ADT_RECALC_DRIVERS);
1092         }
1093
1094         /* world nodes */
1095         if (scene->world && scene->world->nodetree) {
1096                 ID *nid = (ID *)scene->world->nodetree;
1097                 AnimData *adt = BKE_animdata_from_id(nid);
1098                 
1099                 if (adt && adt->drivers.first)
1100                         BKE_animsys_evaluate_animdata(scene, nid, adt, ctime, ADT_RECALC_DRIVERS);
1101         }
1102
1103         /* freestyle */
1104         for (srl = scene->r.layers.first; srl; srl = srl->next) {
1105                 FreestyleConfig *config = &srl->freestyleConfig;
1106                 FreestyleLineSet *lineset;
1107
1108                 for (lineset = config->linesets.first; lineset; lineset = lineset->next) {
1109                         if (lineset->linestyle) {
1110                                 ID *lid = &lineset->linestyle->id;
1111                                 AnimData *adt = BKE_animdata_from_id(lid);
1112
1113                                 if (adt && adt->drivers.first)
1114                                         BKE_animsys_evaluate_animdata(scene, lid, adt, ctime, ADT_RECALC_DRIVERS);
1115                         }
1116                 }
1117         }
1118 }
1119
1120 /* deps hack - do extra recalcs at end */
1121 static void scene_depsgraph_hack(EvaluationContext *eval_ctx, Scene *scene, Scene *scene_parent)
1122 {
1123         Base *base;
1124                 
1125         scene->customdata_mask = scene_parent->customdata_mask;
1126         
1127         /* sets first, we allow per definition current scene to have
1128          * dependencies on sets, but not the other way around. */
1129         if (scene->set)
1130                 scene_depsgraph_hack(eval_ctx, scene->set, scene_parent);
1131         
1132         for (base = scene->base.first; base; base = base->next) {
1133                 Object *ob = base->object;
1134                 
1135                 if (ob->depsflag) {
1136                         int recalc = 0;
1137                         // printf("depshack %s\n", ob->id.name + 2);
1138                         
1139                         if (ob->depsflag & OB_DEPS_EXTRA_OB_RECALC)
1140                                 recalc |= OB_RECALC_OB;
1141                         if (ob->depsflag & OB_DEPS_EXTRA_DATA_RECALC)
1142                                 recalc |= OB_RECALC_DATA;
1143                         
1144                         ob->recalc |= recalc;
1145                         BKE_object_handle_update(eval_ctx, scene_parent, ob);
1146                         
1147                         if (ob->dup_group && (ob->transflag & OB_DUPLIGROUP)) {
1148                                 GroupObject *go;
1149                                 
1150                                 for (go = ob->dup_group->gobject.first; go; go = go->next) {
1151                                         if (go->ob)
1152                                                 go->ob->recalc |= recalc;
1153                                 }
1154                                 BKE_group_handle_recalc_and_update(eval_ctx, scene_parent, ob, ob->dup_group);
1155                         }
1156                 }
1157         }
1158
1159 }
1160
1161 static void scene_rebuild_rbw_recursive(Scene *scene, float ctime)
1162 {
1163         if (scene->set)
1164                 scene_rebuild_rbw_recursive(scene->set, ctime);
1165
1166         if (BKE_scene_check_rigidbody_active(scene))
1167                 BKE_rigidbody_rebuild_world(scene, ctime);
1168 }
1169
1170 static void scene_do_rb_simulation_recursive(Scene *scene, float ctime)
1171 {
1172         if (scene->set)
1173                 scene_do_rb_simulation_recursive(scene->set, ctime);
1174
1175         if (BKE_scene_check_rigidbody_active(scene))
1176                 BKE_rigidbody_do_simulation(scene, ctime);
1177 }
1178
1179 /* Used to visualize CPU threads activity during threaded object update,
1180  * would pollute STDERR with whole bunch of timing information which then
1181  * could be parsed and nicely visualized.
1182  */
1183 #undef DETAILED_ANALYSIS_OUTPUT
1184
1185 /* Mballs evaluation uses BKE_scene_base_iter_next which calls
1186  * duplilist for all objects in the scene. This leads to conflict
1187  * accessing and writting same data from multipl threads.
1188  *
1189  * Ideally Mballs shouldn't do such an iteration and use DAG
1190  * queries instead. For the time being we've got new DAG
1191  * let's keep it simple and update mballs in a ingle thread.
1192  */
1193 #define MBALL_SINGLETHREAD_HACK
1194
1195 typedef struct StatisicsEntry {
1196         struct StatisicsEntry *next, *prev;
1197         Object *object;
1198         double start_time;
1199         double duration;
1200 } StatisicsEntry;
1201
1202 typedef struct ThreadedObjectUpdateState {
1203         /* TODO(sergey): We might want this to be per-thread object. */
1204         EvaluationContext *eval_ctx;
1205         Scene *scene;
1206         Scene *scene_parent;
1207         double base_time;
1208
1209         /* Execution statistics */
1210         ListBase statistics[BLENDER_MAX_THREADS];
1211         bool has_updated_objects;
1212
1213 #ifdef MBALL_SINGLETHREAD_HACK
1214         bool has_mballs;
1215 #endif
1216 } ThreadedObjectUpdateState;
1217
1218 static void scene_update_object_add_task(void *node, void *user_data);
1219
1220 static void scene_update_all_bases(EvaluationContext *eval_ctx, Scene *scene, Scene *scene_parent)
1221 {
1222         Base *base;
1223
1224         for (base = scene->base.first; base; base = base->next) {
1225                 Object *object = base->object;
1226
1227                 BKE_object_handle_update_ex(eval_ctx, scene_parent, object, scene->rigidbody_world);
1228
1229                 if (object->dup_group && (object->transflag & OB_DUPLIGROUP))
1230                         BKE_group_handle_recalc_and_update(eval_ctx, scene_parent, object, object->dup_group);
1231
1232                 /* always update layer, so that animating layers works (joshua july 2010) */
1233                 /* XXX commented out, this has depsgraph issues anyway - and this breaks setting scenes
1234                  * (on scene-set, the base-lay is copied to ob-lay (ton nov 2012) */
1235                 // base->lay = ob->lay;
1236         }
1237 }
1238
1239 static void scene_update_object_func(TaskPool *pool, void *taskdata, int threadid)
1240 {
1241 /* Disable print for now in favor of summary statistics at the end of update. */
1242 #define PRINT if (false) printf
1243
1244         ThreadedObjectUpdateState *state = (ThreadedObjectUpdateState *) BLI_task_pool_userdata(pool);
1245         void *node = taskdata;
1246         Object *object = DAG_get_node_object(node);
1247         EvaluationContext *eval_ctx = state->eval_ctx;
1248         Scene *scene = state->scene;
1249         Scene *scene_parent = state->scene_parent;
1250
1251 #ifdef MBALL_SINGLETHREAD_HACK
1252         if (object && object->type == OB_MBALL) {
1253                 state->has_mballs = true;
1254         }
1255         else
1256 #endif
1257         if (object) {
1258                 double start_time = 0.0;
1259                 bool add_to_stats = false;
1260
1261                 PRINT("Thread %d: update object %s\n", threadid, object->id.name);
1262
1263                 if (G.debug & G_DEBUG) {
1264                         start_time = PIL_check_seconds_timer();
1265
1266                         if (object->recalc & OB_RECALC_ALL) {
1267                                 state->has_updated_objects = true;
1268                                 add_to_stats = true;
1269                         }
1270                 }
1271
1272                 /* We only update object itself here, dupli-group will be updated
1273                  * separately from main thread because of we've got no idea about
1274                  * dependnecies inside the group.
1275                  */
1276                 BKE_object_handle_update_ex(eval_ctx, scene_parent, object, scene->rigidbody_world);
1277
1278                 /* Calculate statistics. */
1279                 if (add_to_stats) {
1280                         StatisicsEntry *entry;
1281
1282                         entry = MEM_mallocN(sizeof(StatisicsEntry), "update thread statistics");
1283                         entry->object = object;
1284                         entry->start_time = start_time;
1285                         entry->duration = PIL_check_seconds_timer() - start_time;
1286
1287                         BLI_addtail(&state->statistics[threadid], entry);
1288                 }
1289         }
1290         else {
1291                 PRINT("Threda %d: update node %s\n", threadid,
1292                       DAG_get_node_name(node));
1293         }
1294
1295         /* Update will decrease child's valency and schedule child with zero valency. */
1296         DAG_threaded_update_handle_node_updated(node,scene_update_object_add_task, pool);
1297
1298 #undef PRINT
1299 }
1300
1301 static void scene_update_object_add_task(void *node, void *user_data)
1302 {
1303         TaskPool *task_pool = user_data;
1304
1305         BLI_task_pool_push(task_pool, scene_update_object_func, node, false, TASK_PRIORITY_LOW);
1306 }
1307
1308 static void print_threads_statistics(ThreadedObjectUpdateState *state)
1309 {
1310         int i, tot_thread;
1311
1312         if ((G.debug & G_DEBUG) == 0) {
1313                 return;
1314         }
1315
1316 #ifdef DETAILED_ANALYSIS_OUTPUT
1317         if (state->has_updated_objects) {
1318                 tot_thread = BLI_system_thread_count();
1319
1320                 fprintf(stderr, "objects update base time %f\n", state->base_time);
1321
1322                 for (i = 0; i < tot_thread; i++) {
1323                         StatisicsEntry *entry;
1324                         for (entry = state->statistics[i].first;
1325                              entry;
1326                              entry = entry->next)
1327                         {
1328                                 fprintf(stderr, "thread %d object %s start_time %f duration %f\n",
1329                                         i, entry->object->id.name + 2,
1330                                         entry->start_time, entry->duration);
1331                         }
1332                         BLI_freelistN(&state->statistics[i]);
1333                 }
1334         }
1335 #else
1336         tot_thread = BLI_system_thread_count();
1337
1338         for (i = 0; i < tot_thread; i++) {
1339                 int total_objects = 0;
1340                 double total_time = 0.0;
1341                 StatisicsEntry *entry;
1342
1343                 if (state->has_updated_objects) {
1344                         /* Don't pollute output if no objects were updated. */
1345                         for (entry = state->statistics[i].first;
1346                              entry;
1347                              entry = entry->next)
1348                         {
1349                                 total_objects++;
1350                                 total_time += entry->duration;
1351                         }
1352
1353                         printf("Thread %d: total %d objects in %f sec.\n", i, total_objects, total_time);
1354
1355                         for (entry = state->statistics[i].first;
1356                              entry;
1357                              entry = entry->next)
1358                         {
1359                                 printf("  %s in %f sec\n", entry->object->id.name + 2, entry->duration);
1360                         }
1361                 }
1362
1363                 BLI_freelistN(&state->statistics[i]);
1364         }
1365 #endif
1366 }
1367
1368 static void scene_update_objects(EvaluationContext *eval_ctx, Scene *scene, Scene *scene_parent)
1369 {
1370         TaskScheduler *task_scheduler = BLI_task_scheduler_get();
1371         TaskPool *task_pool;
1372         ThreadedObjectUpdateState state;
1373
1374         state.eval_ctx = eval_ctx;
1375         state.scene = scene;
1376         state.scene_parent = scene_parent;
1377         memset(state.statistics, 0, sizeof(state.statistics));
1378         state.has_updated_objects = false;
1379         state.base_time = PIL_check_seconds_timer();
1380 #ifdef MBALL_SINGLETHREAD_HACK
1381         state.has_mballs = false;
1382 #endif
1383
1384         task_pool = BLI_task_pool_create(task_scheduler, &state);
1385
1386         DAG_threaded_update_begin(scene, scene_update_object_add_task, task_pool);
1387         BLI_task_pool_work_and_wait(task_pool);
1388         BLI_task_pool_free(task_pool);
1389
1390         if (G.debug & G_DEBUG) {
1391                 print_threads_statistics(&state);
1392         }
1393
1394 #ifdef MBALL_SINGLETHREAD_HACK
1395         if (state.has_mballs) {
1396                 scene_update_all_bases(eval_ctx, scene, scene_parent);
1397         }
1398 #endif
1399 }
1400
1401 static void scene_update_tagged_recursive(EvaluationContext *eval_ctx, Main *bmain, Scene *scene, Scene *scene_parent)
1402 {
1403         scene->customdata_mask = scene_parent->customdata_mask;
1404
1405         /* sets first, we allow per definition current scene to have
1406          * dependencies on sets, but not the other way around. */
1407         if (scene->set)
1408                 scene_update_tagged_recursive(eval_ctx, bmain, scene->set, scene_parent);
1409
1410         /* scene objects */
1411         scene_update_objects(eval_ctx, scene, scene_parent);
1412
1413         /* scene drivers... */
1414         scene_update_drivers(bmain, scene);
1415
1416         /* update sound system animation */
1417         sound_update_scene(scene);
1418
1419         /* update masking curves */
1420         BKE_mask_update_scene(bmain, scene);
1421         
1422 }
1423
1424 void BKE_scene_update_tagged(EvaluationContext *eval_ctx, Main *bmain, Scene *scene)
1425 {
1426         Scene *sce_iter;
1427         
1428         /* keep this first */
1429         BLI_callback_exec(bmain, &scene->id, BLI_CB_EVT_SCENE_UPDATE_PRE);
1430
1431         /* (re-)build dependency graph if needed */
1432         for (sce_iter = scene; sce_iter; sce_iter = sce_iter->set)
1433                 DAG_scene_relations_update(bmain, sce_iter);
1434
1435         /* flush recalc flags to dependencies */
1436         DAG_ids_flush_tagged(bmain);
1437
1438         /* removed calls to quick_cache, see pointcache.c */
1439         
1440         /* clear "LIB_DOIT" flag from all materials, to prevent infinite recursion problems later 
1441          * when trying to find materials with drivers that need evaluating [#32017] 
1442          */
1443         tag_main_idcode(bmain, ID_MA, FALSE);
1444         tag_main_idcode(bmain, ID_LA, FALSE);
1445
1446         /* update all objects: drivers, matrices, displists, etc. flags set
1447          * by depgraph or manual, no layer check here, gets correct flushed
1448          *
1449          * in the future this should handle updates for all datablocks, not
1450          * only objects and scenes. - brecht */
1451         scene_update_tagged_recursive(eval_ctx, bmain, scene, scene);
1452
1453         /* extra call here to recalc scene animation (for sequencer) */
1454         {
1455                 AnimData *adt = BKE_animdata_from_id(&scene->id);
1456                 float ctime = BKE_scene_frame_get(scene);
1457                 
1458                 if (adt && (adt->recalc & ADT_RECALC_ANIM))
1459                         BKE_animsys_evaluate_animdata(scene, &scene->id, adt, ctime, 0);
1460         }
1461         
1462         /* notify editors and python about recalc */
1463         BLI_callback_exec(bmain, &scene->id, BLI_CB_EVT_SCENE_UPDATE_POST);
1464         DAG_ids_check_recalc(bmain, scene, FALSE);
1465
1466         /* clear recalc flags */
1467         DAG_ids_clear_recalc(bmain);
1468 }
1469
1470 /* applies changes right away, does all sets too */
1471 void BKE_scene_update_for_newframe(EvaluationContext *eval_ctx, Main *bmain, Scene *sce, unsigned int lay)
1472 {
1473         float ctime = BKE_scene_frame_get(sce);
1474         Scene *sce_iter;
1475 #ifdef DETAILED_ANALYSIS_OUTPUT
1476         double start_time = PIL_check_seconds_timer();
1477 #endif
1478
1479         /* keep this first */
1480         BLI_callback_exec(bmain, &sce->id, BLI_CB_EVT_FRAME_CHANGE_PRE);
1481         BLI_callback_exec(bmain, &sce->id, BLI_CB_EVT_SCENE_UPDATE_PRE);
1482
1483         /* update animated image textures for particles, modifiers, gpu, etc,
1484          * call this at the start so modifiers with textures don't lag 1 frame */
1485         BKE_image_update_frame(bmain, sce->r.cfra);
1486         
1487         /* rebuild rigid body worlds before doing the actual frame update
1488          * this needs to be done on start frame but animation playback usually starts one frame later
1489          * we need to do it here to avoid rebuilding the world on every simulation change, which can be very expensive
1490          */
1491         scene_rebuild_rbw_recursive(sce, ctime);
1492
1493         sound_set_cfra(sce->r.cfra);
1494         
1495         /* clear animation overrides */
1496         /* XXX TODO... */
1497
1498         for (sce_iter = sce; sce_iter; sce_iter = sce_iter->set)
1499                 DAG_scene_relations_update(bmain, sce_iter);
1500
1501         /* flush recalc flags to dependencies, if we were only changing a frame
1502          * this would not be necessary, but if a user or a script has modified
1503          * some datablock before BKE_scene_update_tagged was called, we need the flush */
1504         DAG_ids_flush_tagged(bmain);
1505
1506         /* Following 2 functions are recursive
1507          * so don't call within 'scene_update_tagged_recursive' */
1508         DAG_scene_update_flags(bmain, sce, lay, TRUE);   // only stuff that moves or needs display still
1509
1510         BKE_mask_evaluate_all_masks(bmain, ctime, true);
1511
1512         /* All 'standard' (i.e. without any dependencies) animation is handled here,
1513          * with an 'local' to 'macro' order of evaluation. This should ensure that
1514          * settings stored nestled within a hierarchy (i.e. settings in a Texture block
1515          * can be overridden by settings from Scene, which owns the Texture through a hierarchy
1516          * such as Scene->World->MTex/Texture) can still get correctly overridden.
1517          */
1518         BKE_animsys_evaluate_all_animation(bmain, sce, ctime);
1519         /*...done with recursive funcs */
1520
1521         /* clear "LIB_DOIT" flag from all materials, to prevent infinite recursion problems later 
1522          * when trying to find materials with drivers that need evaluating [#32017] 
1523          */
1524         tag_main_idcode(bmain, ID_MA, FALSE);
1525         tag_main_idcode(bmain, ID_LA, FALSE);
1526
1527         /* run rigidbody sim */
1528         /* NOTE: current position is so that rigidbody sim affects other objects, might change in the future */
1529         scene_do_rb_simulation_recursive(sce, ctime);
1530
1531         /* BKE_object_handle_update() on all objects, groups and sets */
1532         scene_update_tagged_recursive(eval_ctx, bmain, sce, sce);
1533
1534         scene_depsgraph_hack(eval_ctx, sce, sce);
1535
1536         /* notify editors and python about recalc */
1537         BLI_callback_exec(bmain, &sce->id, BLI_CB_EVT_SCENE_UPDATE_POST);
1538         BLI_callback_exec(bmain, &sce->id, BLI_CB_EVT_FRAME_CHANGE_POST);
1539
1540         DAG_ids_check_recalc(bmain, sce, TRUE);
1541
1542         /* clear recalc flags */
1543         DAG_ids_clear_recalc(bmain);
1544
1545 #ifdef DETAILED_ANALYSIS_OUTPUT
1546         fprintf(stderr, "frame update start_time %f duration %f\n", start_time, PIL_check_seconds_timer() - start_time);
1547 #endif
1548 }
1549
1550 /* return default layer, also used to patch old files */
1551 SceneRenderLayer *BKE_scene_add_render_layer(Scene *sce, const char *name)
1552 {
1553         SceneRenderLayer *srl;
1554
1555         if (!name)
1556                 name = DATA_("RenderLayer");
1557
1558         srl = MEM_callocN(sizeof(SceneRenderLayer), "new render layer");
1559         BLI_strncpy(srl->name, name, sizeof(srl->name));
1560         BLI_uniquename(&sce->r.layers, srl, DATA_("RenderLayer"), '.', offsetof(SceneRenderLayer, name), sizeof(srl->name));
1561         BLI_addtail(&sce->r.layers, srl);
1562
1563         /* note, this is also in render, pipeline.c, to make layer when scenedata doesnt have it */
1564         srl->lay = (1 << 20) - 1;
1565         srl->layflag = 0x7FFF;   /* solid ztra halo edge strand */
1566         srl->passflag = SCE_PASS_COMBINED | SCE_PASS_Z;
1567         BKE_freestyle_config_init(&srl->freestyleConfig);
1568
1569         return srl;
1570 }
1571
1572 int BKE_scene_remove_render_layer(Main *bmain, Scene *scene, SceneRenderLayer *srl)
1573 {
1574         const int act = BLI_findindex(&scene->r.layers, srl);
1575         Scene *sce;
1576
1577         if (act == -1) {
1578                 return 0;
1579         }
1580         else if ( (scene->r.layers.first == scene->r.layers.last) &&
1581                   (scene->r.layers.first == srl))
1582         {
1583                 /* ensure 1 layer is kept */
1584                 return 0;
1585         }
1586
1587         BLI_remlink(&scene->r.layers, srl);
1588         MEM_freeN(srl);
1589
1590         scene->r.actlay = 0;
1591
1592         for (sce = bmain->scene.first; sce; sce = sce->id.next) {
1593                 if (sce->nodetree) {
1594                         bNode *node;
1595                         for (node = sce->nodetree->nodes.first; node; node = node->next) {
1596                                 if (node->type == CMP_NODE_R_LAYERS && (Scene *)node->id == scene) {
1597                                         if (node->custom1 == act)
1598                                                 node->custom1 = 0;
1599                                         else if (node->custom1 > act)
1600                                                 node->custom1--;
1601                                 }
1602                         }
1603                 }
1604         }
1605
1606         return 1;
1607 }
1608
1609 /* render simplification */
1610
1611 int get_render_subsurf_level(RenderData *r, int lvl)
1612 {
1613         if (r->mode & R_SIMPLIFY)
1614                 return min_ii(r->simplify_subsurf, lvl);
1615         else
1616                 return lvl;
1617 }
1618
1619 int get_render_child_particle_number(RenderData *r, int num)
1620 {
1621         if (r->mode & R_SIMPLIFY)
1622                 return (int)(r->simplify_particles * num);
1623         else
1624                 return num;
1625 }
1626
1627 int get_render_shadow_samples(RenderData *r, int samples)
1628 {
1629         if ((r->mode & R_SIMPLIFY) && samples > 0)
1630                 return min_ii(r->simplify_shadowsamples, samples);
1631         else
1632                 return samples;
1633 }
1634
1635 float get_render_aosss_error(RenderData *r, float error)
1636 {
1637         if (r->mode & R_SIMPLIFY)
1638                 return ((1.0f - r->simplify_aosss) * 10.0f + 1.0f) * error;
1639         else
1640                 return error;
1641 }
1642
1643 /* helper function for the SETLOOPER macro */
1644 Base *_setlooper_base_step(Scene **sce_iter, Base *base)
1645 {
1646         if (base && base->next) {
1647                 /* common case, step to the next */
1648                 return base->next;
1649         }
1650         else if (base == NULL && (*sce_iter)->base.first) {
1651                 /* first time looping, return the scenes first base */
1652                 return (Base *)(*sce_iter)->base.first;
1653         }
1654         else {
1655                 /* reached the end, get the next base in the set */
1656                 while ((*sce_iter = (*sce_iter)->set)) {
1657                         base = (Base *)(*sce_iter)->base.first;
1658                         if (base) {
1659                                 return base;
1660                         }
1661                 }
1662         }
1663
1664         return NULL;
1665 }
1666
1667 int BKE_scene_use_new_shading_nodes(Scene *scene)
1668 {
1669         RenderEngineType *type = RE_engines_find(scene->r.engine);
1670         return (type && type->flag & RE_USE_SHADING_NODES);
1671 }
1672
1673 void BKE_scene_base_flag_to_objects(struct Scene *scene)
1674 {
1675         Base *base = scene->base.first;
1676
1677         while (base) {
1678                 base->object->flag = base->flag;
1679                 base = base->next;
1680         }
1681 }
1682
1683 void BKE_scene_base_flag_from_objects(struct Scene *scene)
1684 {
1685         Base *base = scene->base.first;
1686
1687         while (base) {
1688                 base->flag = base->object->flag;
1689                 base = base->next;
1690         }
1691 }
1692
1693 void BKE_scene_disable_color_management(Scene *scene)
1694 {
1695         ColorManagedDisplaySettings *display_settings = &scene->display_settings;
1696         ColorManagedViewSettings *view_settings = &scene->view_settings;
1697         const char *view;
1698         const char *none_display_name;
1699
1700         none_display_name = IMB_colormanagement_display_get_none_name();
1701
1702         BLI_strncpy(display_settings->display_device, none_display_name, sizeof(display_settings->display_device));
1703
1704         view = IMB_colormanagement_view_get_default_name(display_settings->display_device);
1705
1706         if (view) {
1707                 BLI_strncpy(view_settings->view_transform, view, sizeof(view_settings->view_transform));
1708         }
1709 }
1710
1711 int BKE_scene_check_color_management_enabled(const Scene *scene)
1712 {
1713         return strcmp(scene->display_settings.display_device, "None") != 0;
1714 }
1715
1716 int BKE_scene_check_rigidbody_active(const Scene *scene)
1717 {
1718         return scene && scene->rigidbody_world && scene->rigidbody_world->group && !(scene->rigidbody_world->flag & RBW_FLAG_MUTED);
1719 }
1720
1721 int BKE_render_num_threads(const RenderData *rd)
1722 {
1723         int threads;
1724
1725         /* override set from command line? */
1726         threads = BLI_system_num_threads_override_get();
1727
1728         if (threads > 0)
1729                 return threads;
1730
1731         /* fixed number of threads specified in scene? */
1732         if (rd->mode & R_FIXED_THREADS)
1733                 threads = rd->threads;
1734         else
1735                 threads = BLI_system_thread_count();
1736         
1737         return max_ii(threads, 1);
1738 }
1739
1740 int BKE_scene_num_threads(const Scene *scene)
1741 {
1742         return BKE_render_num_threads(&scene->r);
1743 }
1744