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