Color Management: RGB curves transform as a part of display transform
[blender-staging.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_scene_types.h"
50 #include "DNA_screen_types.h"
51 #include "DNA_sequence_types.h"
52
53 #include "BLI_math.h"
54 #include "BLI_blenlib.h"
55 #include "BLI_utildefines.h"
56 #include "BLI_callbacks.h"
57
58 #include "BKE_anim.h"
59 #include "BKE_animsys.h"
60 #include "BKE_colortools.h"
61 #include "BKE_depsgraph.h"
62 #include "BKE_global.h"
63 #include "BKE_group.h"
64 #include "BKE_idprop.h"
65 #include "BKE_library.h"
66 #include "BKE_main.h"
67 #include "BKE_mask.h"
68 #include "BKE_node.h"
69 #include "BKE_object.h"
70 #include "BKE_paint.h"
71 #include "BKE_pointcache.h"
72 #include "BKE_scene.h"
73 #include "BKE_sequencer.h"
74 #include "BKE_world.h"
75
76 #include "BKE_sound.h"
77
78 #include "RE_engine.h"
79
80 //XXX #include "BIF_previewrender.h"
81 //XXX #include "BIF_editseq.h"
82
83 #ifdef WIN32
84 #else
85 #include <sys/time.h>
86 #endif
87
88 void free_avicodecdata(AviCodecData *acd)
89 {
90         if (acd) {
91                 if (acd->lpFormat) {
92                         MEM_freeN(acd->lpFormat);
93                         acd->lpFormat = NULL;
94                         acd->cbFormat = 0;
95                 }
96                 if (acd->lpParms) {
97                         MEM_freeN(acd->lpParms);
98                         acd->lpParms = NULL;
99                         acd->cbParms = 0;
100                 }
101         }
102 }
103
104 void free_qtcodecdata(QuicktimeCodecData *qcd)
105 {
106         if (qcd) {
107                 if (qcd->cdParms) {
108                         MEM_freeN(qcd->cdParms);
109                         qcd->cdParms = NULL;
110                         qcd->cdSize = 0;
111                 }
112         }
113 }
114
115 Scene *BKE_scene_copy(Scene *sce, int type)
116 {
117         Scene *scen;
118         ToolSettings *ts;
119         Base *base, *obase;
120         
121         if (type == SCE_COPY_EMPTY) {
122                 ListBase lb;
123                 scen = BKE_scene_add(sce->id.name + 2);
124                 
125                 lb = scen->r.layers;
126                 scen->r = sce->r;
127                 scen->r.layers = lb;
128                 scen->unit = sce->unit;
129                 scen->physics_settings = sce->physics_settings;
130                 scen->gm = sce->gm;
131                 scen->audio = sce->audio;
132
133                 MEM_freeN(scen->toolsettings);
134         }
135         else {
136                 ImageFormatData *im_format, *im_formatn;
137
138                 scen = BKE_libblock_copy(&sce->id);
139                 BLI_duplicatelist(&(scen->base), &(sce->base));
140                 
141                 clear_id_newpoins();
142                 
143                 id_us_plus((ID *)scen->world);
144                 id_us_plus((ID *)scen->set);
145                 id_us_plus((ID *)scen->gm.dome.warptext);
146
147                 scen->ed = NULL;
148                 scen->theDag = NULL;
149                 scen->obedit = NULL;
150                 scen->stats = NULL;
151                 scen->fps_info = NULL;
152
153                 BLI_duplicatelist(&(scen->markers), &(sce->markers));
154                 BLI_duplicatelist(&(scen->transform_spaces), &(sce->transform_spaces));
155                 BLI_duplicatelist(&(scen->r.layers), &(sce->r.layers));
156                 BKE_keyingsets_copy(&(scen->keyingsets), &(sce->keyingsets));
157
158                 if (sce->nodetree) {
159                         /* ID's are managed on both copy and switch */
160                         scen->nodetree = ntreeCopyTree(sce->nodetree);
161                         ntreeSwitchID(scen->nodetree, &sce->id, &scen->id);
162                 }
163
164                 obase = sce->base.first;
165                 base = scen->base.first;
166                 while (base) {
167                         id_us_plus(&base->object->id);
168                         if (obase == sce->basact) scen->basact = base;
169         
170                         obase = obase->next;
171                         base = base->next;
172                 }
173
174                 /* copy color management settings */
175                 im_format = &sce->r.im_format;
176                 im_formatn = &scen->r.im_format;
177
178                 BKE_color_managed_display_settings_copy(&scen->display_settings, &sce->display_settings);
179                 BKE_color_managed_view_settings_copy(&scen->view_settings, &sce->view_settings);
180         }
181
182         /* tool settings */
183         scen->toolsettings = MEM_dupallocN(sce->toolsettings);
184
185         ts = scen->toolsettings;
186         if (ts) {
187                 if (ts->vpaint) {
188                         ts->vpaint = MEM_dupallocN(ts->vpaint);
189                         ts->vpaint->paintcursor = NULL;
190                         ts->vpaint->vpaint_prev = NULL;
191                         ts->vpaint->wpaint_prev = NULL;
192                         BKE_paint_copy(&ts->vpaint->paint, &ts->vpaint->paint);
193                 }
194                 if (ts->wpaint) {
195                         ts->wpaint = MEM_dupallocN(ts->wpaint);
196                         ts->wpaint->paintcursor = NULL;
197                         ts->wpaint->vpaint_prev = NULL;
198                         ts->wpaint->wpaint_prev = NULL;
199                         BKE_paint_copy(&ts->wpaint->paint, &ts->wpaint->paint);
200                 }
201                 if (ts->sculpt) {
202                         ts->sculpt = MEM_dupallocN(ts->sculpt);
203                         BKE_paint_copy(&ts->sculpt->paint, &ts->sculpt->paint);
204                 }
205
206                 BKE_paint_copy(&ts->imapaint.paint, &ts->imapaint.paint);
207                 ts->imapaint.paintcursor = NULL;
208                 ts->particle.paintcursor = NULL;
209         }
210         
211         /* make a private copy of the avicodecdata */
212         if (sce->r.avicodecdata) {
213                 scen->r.avicodecdata = MEM_dupallocN(sce->r.avicodecdata);
214                 scen->r.avicodecdata->lpFormat = MEM_dupallocN(scen->r.avicodecdata->lpFormat);
215                 scen->r.avicodecdata->lpParms = MEM_dupallocN(scen->r.avicodecdata->lpParms);
216         }
217         
218         /* make a private copy of the qtcodecdata */
219         if (sce->r.qtcodecdata) {
220                 scen->r.qtcodecdata = MEM_dupallocN(sce->r.qtcodecdata);
221                 scen->r.qtcodecdata->cdParms = MEM_dupallocN(scen->r.qtcodecdata->cdParms);
222         }
223         
224         if (sce->r.ffcodecdata.properties) { /* intentionally check scen not sce. */
225                 scen->r.ffcodecdata.properties = IDP_CopyProperty(sce->r.ffcodecdata.properties);
226         }
227
228         /* NOTE: part of SCE_COPY_LINK_DATA and SCE_COPY_FULL operations
229          * are done outside of blenkernel with ED_objects_single_users! */
230
231         /*  camera */
232         if (type == SCE_COPY_LINK_DATA || type == SCE_COPY_FULL) {
233                 ID_NEW(scen->camera);
234         }
235         
236         /* before scene copy */
237         sound_create_scene(scen);
238
239         /* world */
240         if (type == SCE_COPY_FULL) {
241                 BKE_copy_animdata_id_action((ID *)scen);
242                 if (scen->world) {
243                         id_us_plus((ID *)scen->world);
244                         scen->world = BKE_world_copy(scen->world);
245                         BKE_copy_animdata_id_action((ID *)scen->world);
246                 }
247
248                 if (sce->ed) {
249                         scen->ed = MEM_callocN(sizeof(Editing), "addseq");
250                         scen->ed->seqbasep = &scen->ed->seqbase;
251                         BKE_sequence_base_dupli_recursive(sce, scen, &scen->ed->seqbase, &sce->ed->seqbase, SEQ_DUPE_ALL);
252                 }
253         }
254
255         return scen;
256 }
257
258 /* do not free scene itself */
259 void BKE_scene_free(Scene *sce)
260 {
261         Base *base;
262
263         base = sce->base.first;
264         while (base) {
265                 base->object->id.us--;
266                 base = base->next;
267         }
268         /* do not free objects! */
269         
270         if (sce->gpd) {
271 #if 0   /* removed since this can be invalid memory when freeing everything */
272                 /* since the grease pencil data is freed before the scene.
273                  * since grease pencil data is not (yet?), shared between objects
274                  * its probably safe not to do this, some save and reload will free this. */
275                 sce->gpd->id.us--;
276 #endif
277                 sce->gpd = NULL;
278         }
279
280         BLI_freelistN(&sce->base);
281         BKE_sequencer_editing_free(sce);
282
283         BKE_free_animdata((ID *)sce);
284         BKE_keyingsets_free(&sce->keyingsets);
285         
286         if (sce->r.avicodecdata) {
287                 free_avicodecdata(sce->r.avicodecdata);
288                 MEM_freeN(sce->r.avicodecdata);
289                 sce->r.avicodecdata = NULL;
290         }
291         if (sce->r.qtcodecdata) {
292                 free_qtcodecdata(sce->r.qtcodecdata);
293                 MEM_freeN(sce->r.qtcodecdata);
294                 sce->r.qtcodecdata = NULL;
295         }
296         if (sce->r.ffcodecdata.properties) {
297                 IDP_FreeProperty(sce->r.ffcodecdata.properties);
298                 MEM_freeN(sce->r.ffcodecdata.properties);
299                 sce->r.ffcodecdata.properties = NULL;
300         }
301         
302         BLI_freelistN(&sce->markers);
303         BLI_freelistN(&sce->transform_spaces);
304         BLI_freelistN(&sce->r.layers);
305         
306         if (sce->toolsettings) {
307                 if (sce->toolsettings->vpaint) {
308                         BKE_paint_free(&sce->toolsettings->vpaint->paint);
309                         MEM_freeN(sce->toolsettings->vpaint);
310                 }
311                 if (sce->toolsettings->wpaint) {
312                         BKE_paint_free(&sce->toolsettings->wpaint->paint);
313                         MEM_freeN(sce->toolsettings->wpaint);
314                 }
315                 if (sce->toolsettings->sculpt) {
316                         BKE_paint_free(&sce->toolsettings->sculpt->paint);
317                         MEM_freeN(sce->toolsettings->sculpt);
318                 }
319                 if (sce->toolsettings->uvsculpt) {
320                         BKE_paint_free(&sce->toolsettings->uvsculpt->paint);
321                         MEM_freeN(sce->toolsettings->uvsculpt);
322                 }
323                 BKE_paint_free(&sce->toolsettings->imapaint.paint);
324
325                 MEM_freeN(sce->toolsettings);
326                 sce->toolsettings = NULL;       
327         }
328         
329         if (sce->theDag) {
330                 free_forest(sce->theDag);
331                 MEM_freeN(sce->theDag);
332         }
333         
334         if (sce->nodetree) {
335                 ntreeFreeTree(sce->nodetree);
336                 MEM_freeN(sce->nodetree);
337         }
338
339         if (sce->stats)
340                 MEM_freeN(sce->stats);
341         if (sce->fps_info)
342                 MEM_freeN(sce->fps_info);
343
344         sound_destroy_scene(sce);
345
346         BKE_color_managed_view_settings_free(&sce->view_settings);
347 }
348
349 Scene *BKE_scene_add(const char *name)
350 {
351         Main *bmain = G.main;
352         Scene *sce;
353         ParticleEditSettings *pset;
354         int a;
355
356         sce = BKE_libblock_alloc(&bmain->scene, ID_SCE, name);
357         sce->lay = sce->layact = 1;
358         
359         sce->r.mode = R_GAMMA | R_OSA | R_SHADOW | R_SSS | R_ENVMAP | R_RAYTRACE;
360         sce->r.cfra = 1;
361         sce->r.sfra = 1;
362         sce->r.efra = 250;
363         sce->r.frame_step = 1;
364         sce->r.xsch = 1920;
365         sce->r.ysch = 1080;
366         sce->r.xasp = 1;
367         sce->r.yasp = 1;
368         sce->r.xparts = 8;
369         sce->r.yparts = 8;
370         sce->r.mblur_samples = 1;
371         sce->r.filtertype = R_FILTER_MITCH;
372         sce->r.size = 50;
373
374         sce->r.im_format.planes = R_IMF_PLANES_RGB;
375         sce->r.im_format.imtype = R_IMF_IMTYPE_PNG;
376         sce->r.im_format.quality = 90;
377
378         sce->r.displaymode = R_OUTPUT_AREA;
379         sce->r.framapto = 100;
380         sce->r.images = 100;
381         sce->r.framelen = 1.0;
382         sce->r.blurfac = 0.5;
383         sce->r.frs_sec = 24;
384         sce->r.frs_sec_base = 1;
385         sce->r.edgeint = 10;
386         sce->r.ocres = 128;
387         sce->r.color_mgt_flag |= R_COLOR_MANAGEMENT;
388         sce->r.gauss = 1.0;
389         
390         /* deprecated but keep for upwards compat */
391         sce->r.postgamma = 1.0;
392         sce->r.posthue = 0.0;
393         sce->r.postsat = 1.0;
394
395         sce->r.bake_mode = 1;    /* prevent to include render stuff here */
396         sce->r.bake_filter = 2;
397         sce->r.bake_osa = 5;
398         sce->r.bake_flag = R_BAKE_CLEAR;
399         sce->r.bake_normal_space = R_BAKE_SPACE_TANGENT;
400         sce->r.scemode = R_DOCOMP | R_DOSEQ | R_EXTENSION;
401         sce->r.stamp = R_STAMP_TIME | R_STAMP_FRAME | R_STAMP_DATE | R_STAMP_CAMERA | R_STAMP_SCENE | R_STAMP_FILENAME | R_STAMP_RENDERTIME;
402         sce->r.stamp_font_id = 12;
403         sce->r.fg_stamp[0] = sce->r.fg_stamp[1] = sce->r.fg_stamp[2] = 0.8f;
404         sce->r.fg_stamp[3] = 1.0f;
405         sce->r.bg_stamp[0] = sce->r.bg_stamp[1] = sce->r.bg_stamp[2] = 0.0f;
406         sce->r.bg_stamp[3] = 0.25f;
407         sce->r.raytrace_options = R_RAYTRACE_USE_INSTANCES;
408
409         sce->r.seq_prev_type = OB_SOLID;
410         sce->r.seq_rend_type = OB_SOLID;
411         sce->r.seq_flag = R_SEQ_GL_PREV;
412
413         sce->r.threads = 1;
414
415         sce->r.simplify_subsurf = 6;
416         sce->r.simplify_particles = 1.0f;
417         sce->r.simplify_shadowsamples = 16;
418         sce->r.simplify_aosss = 1.0f;
419
420         sce->r.border.xmin = 0.0f;
421         sce->r.border.ymin = 0.0f;
422         sce->r.border.xmax = 1.0f;
423         sce->r.border.ymax = 1.0f;
424         
425         sce->toolsettings = MEM_callocN(sizeof(struct ToolSettings), "Tool Settings Struct");
426         sce->toolsettings->cornertype = 1;
427         sce->toolsettings->degr = 90; 
428         sce->toolsettings->step = 9;
429         sce->toolsettings->turn = 1;                            
430         sce->toolsettings->extr_offs = 1; 
431         sce->toolsettings->doublimit = 0.001;
432         sce->toolsettings->segments = 32;
433         sce->toolsettings->rings = 32;
434         sce->toolsettings->vertices = 32;
435         sce->toolsettings->uvcalc_radius = 1.0f;
436         sce->toolsettings->uvcalc_cubesize = 1.0f;
437         sce->toolsettings->uvcalc_mapdir = 1;
438         sce->toolsettings->uvcalc_mapalign = 1;
439         sce->toolsettings->unwrapper = 1;
440         sce->toolsettings->select_thresh = 0.01f;
441         sce->toolsettings->jointrilimit = 0.8f;
442
443         sce->toolsettings->selectmode = SCE_SELECT_VERTEX;
444         sce->toolsettings->uv_selectmode = UV_SELECT_VERTEX;
445         sce->toolsettings->normalsize = 0.1;
446         sce->toolsettings->autokey_mode = U.autokey_mode;
447
448         sce->toolsettings->skgen_resolution = 100;
449         sce->toolsettings->skgen_threshold_internal     = 0.01f;
450         sce->toolsettings->skgen_threshold_external     = 0.01f;
451         sce->toolsettings->skgen_angle_limit            = 45.0f;
452         sce->toolsettings->skgen_length_ratio           = 1.3f;
453         sce->toolsettings->skgen_length_limit           = 1.5f;
454         sce->toolsettings->skgen_correlation_limit      = 0.98f;
455         sce->toolsettings->skgen_symmetry_limit         = 0.1f;
456         sce->toolsettings->skgen_postpro = SKGEN_SMOOTH;
457         sce->toolsettings->skgen_postpro_passes = 1;
458         sce->toolsettings->skgen_options = SKGEN_FILTER_INTERNAL | SKGEN_FILTER_EXTERNAL | SKGEN_FILTER_SMART | SKGEN_HARMONIC | SKGEN_SUB_CORRELATION | SKGEN_STICK_TO_EMBEDDING;
459         sce->toolsettings->skgen_subdivisions[0] = SKGEN_SUB_CORRELATION;
460         sce->toolsettings->skgen_subdivisions[1] = SKGEN_SUB_LENGTH;
461         sce->toolsettings->skgen_subdivisions[2] = SKGEN_SUB_ANGLE;
462
463         sce->toolsettings->proportional_size = 1.0f;
464
465         sce->physics_settings.gravity[0] = 0.0f;
466         sce->physics_settings.gravity[1] = 0.0f;
467         sce->physics_settings.gravity[2] = -9.81f;
468         sce->physics_settings.flag = PHYS_GLOBAL_GRAVITY;
469
470         sce->unit.scale_length = 1.0f;
471
472         pset = &sce->toolsettings->particle;
473         pset->flag = PE_KEEP_LENGTHS | PE_LOCK_FIRST | PE_DEFLECT_EMITTER | PE_AUTO_VELOCITY;
474         pset->emitterdist = 0.25f;
475         pset->totrekey = 5;
476         pset->totaddkey = 5;
477         pset->brushtype = PE_BRUSH_NONE;
478         pset->draw_step = 2;
479         pset->fade_frames = 2;
480         pset->selectmode = SCE_SELECT_PATH;
481         for (a = 0; a < PE_TOT_BRUSH; a++) {
482                 pset->brush[a].strength = 0.5;
483                 pset->brush[a].size = 50;
484                 pset->brush[a].step = 10;
485                 pset->brush[a].count = 10;
486         }
487         pset->brush[PE_BRUSH_CUT].strength = 100;
488
489         sce->r.ffcodecdata.audio_mixrate = 44100;
490         sce->r.ffcodecdata.audio_volume = 1.0f;
491         sce->r.ffcodecdata.audio_bitrate = 192;
492         sce->r.ffcodecdata.audio_channels = 2;
493
494         BLI_strncpy(sce->r.engine, "BLENDER_RENDER", sizeof(sce->r.engine));
495
496         sce->audio.distance_model = 2.0f;
497         sce->audio.doppler_factor = 1.0f;
498         sce->audio.speed_of_sound = 343.3f;
499         sce->audio.volume = 1.0f;
500
501         BLI_strncpy(sce->r.pic, U.renderdir, sizeof(sce->r.pic));
502
503         BLI_rctf_init(&sce->r.safety, 0.1f, 0.9f, 0.1f, 0.9f);
504         sce->r.osa = 8;
505
506         /* note; in header_info.c the scene copy happens..., if you add more to renderdata it has to be checked there */
507         BKE_scene_add_render_layer(sce, NULL);
508         
509         /* game data */
510         sce->gm.stereoflag = STEREO_NOSTEREO;
511         sce->gm.stereomode = STEREO_ANAGLYPH;
512         sce->gm.eyeseparation = 0.10;
513
514         sce->gm.dome.angle = 180;
515         sce->gm.dome.mode = DOME_FISHEYE;
516         sce->gm.dome.res = 4;
517         sce->gm.dome.resbuf = 1.0f;
518         sce->gm.dome.tilt = 0;
519
520         sce->gm.xplay = 640;
521         sce->gm.yplay = 480;
522         sce->gm.freqplay = 60;
523         sce->gm.depth = 32;
524
525         sce->gm.gravity = 9.8f;
526         sce->gm.physicsEngine = WOPHY_BULLET;
527         sce->gm.mode = 32; //XXX ugly harcoding, still not sure we should drop mode. 32 == 1 << 5 == use_occlusion_culling 
528         sce->gm.occlusionRes = 128;
529         sce->gm.ticrate = 60;
530         sce->gm.maxlogicstep = 5;
531         sce->gm.physubstep = 1;
532         sce->gm.maxphystep = 5;
533         sce->gm.lineardeactthreshold = 0.8f;
534         sce->gm.angulardeactthreshold = 1.0f;
535         sce->gm.deactivationtime = 0.0f;
536
537         sce->gm.flag = GAME_DISPLAY_LISTS;
538         sce->gm.matmode = GAME_MAT_MULTITEX;
539
540         sce->gm.obstacleSimulation = OBSTSIMULATION_NONE;
541         sce->gm.levelHeight = 2.f;
542
543         sce->gm.recastData.cellsize = 0.3f;
544         sce->gm.recastData.cellheight = 0.2f;
545         sce->gm.recastData.agentmaxslope = M_PI / 2;
546         sce->gm.recastData.agentmaxclimb = 0.9f;
547         sce->gm.recastData.agentheight = 2.0f;
548         sce->gm.recastData.agentradius = 0.6f;
549         sce->gm.recastData.edgemaxlen = 12.0f;
550         sce->gm.recastData.edgemaxerror = 1.3f;
551         sce->gm.recastData.regionminsize = 8.f;
552         sce->gm.recastData.regionmergesize = 20.f;
553         sce->gm.recastData.vertsperpoly = 6;
554         sce->gm.recastData.detailsampledist = 6.0f;
555         sce->gm.recastData.detailsamplemaxerror = 1.0f;
556
557         sce->gm.exitkey = 218; // Blender key code for ESC
558
559         sound_create_scene(sce);
560
561         BKE_color_managed_display_settings_init(&sce->display_settings);
562         BKE_color_managed_view_settings_init(&sce->view_settings);
563
564         return sce;
565 }
566
567 Base *BKE_scene_base_find(Scene *scene, Object *ob)
568 {
569         return BLI_findptr(&scene->base, ob, offsetof(Base, object));
570 }
571
572 void BKE_scene_set_background(Main *bmain, Scene *scene)
573 {
574         Scene *sce;
575         Base *base;
576         Object *ob;
577         Group *group;
578         GroupObject *go;
579         int flag;
580         
581         /* check for cyclic sets, for reading old files but also for definite security (py?) */
582         BKE_scene_validate_setscene(bmain, scene);
583         
584         /* can happen when switching modes in other scenes */
585         if (scene->obedit && !(scene->obedit->mode & OB_MODE_EDIT))
586                 scene->obedit = NULL;
587
588         /* deselect objects (for dataselect) */
589         for (ob = bmain->object.first; ob; ob = ob->id.next)
590                 ob->flag &= ~(SELECT | OB_FROMGROUP);
591
592         /* group flags again */
593         for (group = bmain->group.first; group; group = group->id.next) {
594                 for (go = group->gobject.first; go; go = go->next) {
595                         if (go->ob) {
596                                 go->ob->flag |= OB_FROMGROUP;
597                         }
598                 }
599         }
600
601         /* sort baselist */
602         DAG_scene_sort(bmain, scene);
603         
604         /* ensure dags are built for sets */
605         for (sce = scene->set; sce; sce = sce->set)
606                 if (sce->theDag == NULL)
607                         DAG_scene_sort(bmain, sce);
608
609         /* copy layers and flags from bases to objects */
610         for (base = scene->base.first; base; base = base->next) {
611                 ob = base->object;
612                 ob->lay = base->lay;
613                 
614                 /* group patch... */
615                 base->flag &= ~(OB_FROMGROUP);
616                 flag = ob->flag & (OB_FROMGROUP);
617                 base->flag |= flag;
618                 
619                 /* not too nice... for recovering objects with lost data */
620                 //if (ob->pose == NULL) base->flag &= ~OB_POSEMODE;
621                 ob->flag = base->flag;
622         }
623         /* no full animation update, this to enable render code to work (render code calls own animation updates) */
624 }
625
626 /* called from creator.c */
627 Scene *BKE_scene_set_name(Main *bmain, const char *name)
628 {
629         Scene *sce = (Scene *)BKE_libblock_find_name(ID_SCE, name);
630         if (sce) {
631                 BKE_scene_set_background(bmain, sce);
632                 printf("Scene switch: '%s' in file: '%s'\n", name, G.main->name);
633                 return sce;
634         }
635
636         printf("Can't find scene: '%s' in file: '%s'\n", name, G.main->name);
637         return NULL;
638 }
639
640 void BKE_scene_unlink(Main *bmain, Scene *sce, Scene *newsce)
641 {
642         Scene *sce1;
643         bScreen *sc;
644
645         /* check all sets */
646         for (sce1 = bmain->scene.first; sce1; sce1 = sce1->id.next)
647                 if (sce1->set == sce)
648                         sce1->set = NULL;
649         
650         /* check all sequences */
651         BKE_sequencer_clear_scene_in_allseqs(bmain, sce);
652
653         /* check render layer nodes in other scenes */
654         clear_scene_in_nodes(bmain, sce);
655         
656         /* al screens */
657         for (sc = bmain->screen.first; sc; sc = sc->id.next)
658                 if (sc->scene == sce)
659                         sc->scene = newsce;
660
661         BKE_libblock_free(&bmain->scene, sce);
662 }
663
664 /* used by metaballs
665  * doesnt return the original duplicated object, only dupli's
666  */
667 int BKE_scene_base_iter_next(Scene **scene, int val, Base **base, Object **ob)
668 {
669         static ListBase *duplilist = NULL;
670         static DupliObject *dupob;
671         static int fase = F_START, in_next_object = 0;
672         int run_again = 1;
673         
674         /* init */
675         if (val == 0) {
676                 fase = F_START;
677                 dupob = NULL;
678                 
679                 /* XXX particle systems with metas+dupligroups call this recursively */
680                 /* see bug #18725 */
681                 if (in_next_object) {
682                         printf("ERROR: Metaball generation called recursively, not supported\n");
683                         
684                         return F_ERROR;
685                 }
686         }
687         else {
688                 in_next_object = 1;
689                 
690                 /* run_again is set when a duplilist has been ended */
691                 while (run_again) {
692                         run_again = 0;
693
694                         /* the first base */
695                         if (fase == F_START) {
696                                 *base = (*scene)->base.first;
697                                 if (*base) {
698                                         *ob = (*base)->object;
699                                         fase = F_SCENE;
700                                 }
701                                 else {
702                                         /* exception: empty scene */
703                                         while ((*scene)->set) {
704                                                 (*scene) = (*scene)->set;
705                                                 if ((*scene)->base.first) {
706                                                         *base = (*scene)->base.first;
707                                                         *ob = (*base)->object;
708                                                         fase = F_SCENE;
709                                                         break;
710                                                 }
711                                         }
712                                 }
713                         }
714                         else {
715                                 if (*base && fase != F_DUPLI) {
716                                         *base = (*base)->next;
717                                         if (*base) *ob = (*base)->object;
718                                         else {
719                                                 if (fase == F_SCENE) {
720                                                         /* (*scene) is finished, now do the set */
721                                                         while ((*scene)->set) {
722                                                                 (*scene) = (*scene)->set;
723                                                                 if ((*scene)->base.first) {
724                                                                         *base = (*scene)->base.first;
725                                                                         *ob = (*base)->object;
726                                                                         break;
727                                                                 }
728                                                         }
729                                                 }
730                                         }
731                                 }
732                         }
733                         
734                         if (*base == NULL) fase = F_START;
735                         else {
736                                 if (fase != F_DUPLI) {
737                                         if ( (*base)->object->transflag & OB_DUPLI) {
738                                                 /* groups cannot be duplicated for mballs yet, 
739                                                  * this enters eternal loop because of 
740                                                  * makeDispListMBall getting called inside of group_duplilist */
741                                                 if ((*base)->object->dup_group == NULL) {
742                                                         duplilist = object_duplilist((*scene), (*base)->object);
743                                                         
744                                                         dupob = duplilist->first;
745
746                                                         if (!dupob)
747                                                                 free_object_duplilist(duplilist);
748                                                 }
749                                         }
750                                 }
751                                 /* handle dupli's */
752                                 if (dupob) {
753                                         
754                                         copy_m4_m4(dupob->ob->obmat, dupob->mat);
755                                         
756                                         (*base)->flag |= OB_FROMDUPLI;
757                                         *ob = dupob->ob;
758                                         fase = F_DUPLI;
759                                         
760                                         dupob = dupob->next;
761                                 }
762                                 else if (fase == F_DUPLI) {
763                                         fase = F_SCENE;
764                                         (*base)->flag &= ~OB_FROMDUPLI;
765                                         
766                                         for (dupob = duplilist->first; dupob; dupob = dupob->next) {
767                                                 copy_m4_m4(dupob->ob->obmat, dupob->omat);
768                                         }
769                                         
770                                         free_object_duplilist(duplilist);
771                                         duplilist = NULL;
772                                         run_again = 1;
773                                 }
774                         }
775                 }
776         }
777
778 #if 0
779         if (ob && *ob) {
780                 printf("Scene: '%s', '%s'\n", (*scene)->id.name + 2, (*ob)->id.name + 2);
781         }
782 #endif
783
784         /* reset recursion test */
785         in_next_object = 0;
786         
787         return fase;
788 }
789
790 Object *BKE_scene_camera_find(Scene *sc)
791 {
792         Base *base;
793         
794         for (base = sc->base.first; base; base = base->next)
795                 if (base->object->type == OB_CAMERA)
796                         return base->object;
797
798         return NULL;
799 }
800
801 #ifdef DURIAN_CAMERA_SWITCH
802 Object *BKE_scene_camera_switch_find(Scene *scene)
803 {
804         TimeMarker *m;
805         int cfra = scene->r.cfra;
806         int frame = -(MAXFRAME + 1);
807         Object *camera = NULL;
808
809         for (m = scene->markers.first; m; m = m->next) {
810                 if (m->camera && (m->camera->restrictflag & OB_RESTRICT_RENDER) == 0 && (m->frame <= cfra) && (m->frame > frame)) {
811                         camera = m->camera;
812                         frame = m->frame;
813
814                         if (frame == cfra)
815                                 break;
816
817                 }
818         }
819         return camera;
820 }
821 #endif
822
823 int BKE_scene_camera_switch_update(Scene *scene)
824 {
825 #ifdef DURIAN_CAMERA_SWITCH
826         Object *camera = BKE_scene_camera_switch_find(scene);
827         if (camera) {
828                 scene->camera = camera;
829                 return 1;
830         }
831 #else
832         (void)scene;
833 #endif
834         return 0;
835 }
836
837 char *BKE_scene_find_marker_name(Scene *scene, int frame)
838 {
839         ListBase *markers = &scene->markers;
840         TimeMarker *m1, *m2;
841
842         /* search through markers for match */
843         for (m1 = markers->first, m2 = markers->last; m1 && m2; m1 = m1->next, m2 = m2->prev) {
844                 if (m1->frame == frame)
845                         return m1->name;
846
847                 if (m1 == m2)
848                         break;
849
850                 if (m2->frame == frame)
851                         return m2->name;
852         }
853
854         return NULL;
855 }
856
857 /* return the current marker for this frame,
858  * we can have more then 1 marker per frame, this just returns the first :/ */
859 char *BKE_scene_find_last_marker_name(Scene *scene, int frame)
860 {
861         TimeMarker *marker, *best_marker = NULL;
862         int best_frame = -MAXFRAME * 2;
863         for (marker = scene->markers.first; marker; marker = marker->next) {
864                 if (marker->frame == frame) {
865                         return marker->name;
866                 }
867
868                 if (marker->frame > best_frame && marker->frame < frame) {
869                         best_marker = marker;
870                         best_frame = marker->frame;
871                 }
872         }
873
874         return best_marker ? best_marker->name : NULL;
875 }
876
877
878 Base *BKE_scene_base_add(Scene *sce, Object *ob)
879 {
880         Base *b = MEM_callocN(sizeof(*b), "BKE_scene_base_add");
881         BLI_addhead(&sce->base, b);
882
883         b->object = ob;
884         b->flag = ob->flag;
885         b->lay = ob->lay;
886
887         return b;
888 }
889
890 void BKE_scene_base_deselect_all(Scene *sce)
891 {
892         Base *b;
893
894         for (b = sce->base.first; b; b = b->next) {
895                 b->flag &= ~SELECT;
896                 b->object->flag = b->flag;
897         }
898 }
899
900 void BKE_scene_base_select(Scene *sce, Base *selbase)
901 {
902         selbase->flag |= SELECT;
903         selbase->object->flag = selbase->flag;
904
905         sce->basact = selbase;
906 }
907
908 /* checks for cycle, returns 1 if it's all OK */
909 int BKE_scene_validate_setscene(Main *bmain, Scene *sce)
910 {
911         Scene *scene;
912         int a, totscene;
913         
914         if (sce->set == NULL) return 1;
915         
916         totscene = 0;
917         for (scene = bmain->scene.first; scene; scene = scene->id.next)
918                 totscene++;
919         
920         for (a = 0, scene = sce; scene->set; scene = scene->set, a++) {
921                 /* more iterations than scenes means we have a cycle */
922                 if (a > totscene) {
923                         /* the tested scene gets zero'ed, that's typically current scene */
924                         sce->set = NULL;
925                         return 0;
926                 }
927         }
928
929         return 1;
930 }
931
932 /* This function is needed to cope with fractional frames - including two Blender rendering features
933  * mblur (motion blur that renders 'subframes' and blurs them together), and fields rendering. 
934  */
935 float BKE_scene_frame_get(Scene *scene)
936 {
937         return BKE_scene_frame_get_from_ctime(scene, scene->r.cfra);
938 }
939
940 /* This function is used to obtain arbitrary fractional frames */
941 float BKE_scene_frame_get_from_ctime(Scene *scene, const float frame)
942 {
943         float ctime = frame;
944         ctime += scene->r.subframe;
945         ctime *= scene->r.framelen;     
946         
947         return ctime;
948 }
949
950 /* drivers support/hacks 
951  *  - this method is called from scene_update_tagged_recursive(), so gets included in viewport + render
952  *      - these are always run since the depsgraph can't handle non-object data
953  *      - these happen after objects are all done so that we can read in their final transform values,
954  *        though this means that objects can't refer to scene info for guidance...
955  */
956 static void scene_update_drivers(Main *UNUSED(bmain), Scene *scene)
957 {
958         float ctime = BKE_scene_frame_get(scene);
959         
960         /* scene itself */
961         if (scene->adt && scene->adt->drivers.first) {
962                 BKE_animsys_evaluate_animdata(scene, &scene->id, scene->adt, ctime, ADT_RECALC_DRIVERS);
963         }
964
965         /* world */
966         /* TODO: what about world textures? but then those have nodes too... */
967         if (scene->world) {
968                 ID *wid = (ID *)scene->world;
969                 AnimData *adt = BKE_animdata_from_id(wid);
970                 
971                 if (adt && adt->drivers.first)
972                         BKE_animsys_evaluate_animdata(scene, wid, adt, ctime, ADT_RECALC_DRIVERS);
973         }
974         
975         /* nodes */
976         if (scene->nodetree) {
977                 ID *nid = (ID *)scene->nodetree;
978                 AnimData *adt = BKE_animdata_from_id(nid);
979                 
980                 if (adt && adt->drivers.first)
981                         BKE_animsys_evaluate_animdata(scene, nid, adt, ctime, ADT_RECALC_DRIVERS);
982         }
983 }
984
985 static void scene_update_tagged_recursive(Main *bmain, Scene *scene, Scene *scene_parent)
986 {
987         Base *base;
988         
989         
990         scene->customdata_mask = scene_parent->customdata_mask;
991
992         /* sets first, we allow per definition current scene to have
993          * dependencies on sets, but not the other way around. */
994         if (scene->set)
995                 scene_update_tagged_recursive(bmain, scene->set, scene_parent);
996         
997         /* scene objects */
998         for (base = scene->base.first; base; base = base->next) {
999                 Object *ob = base->object;
1000                 
1001                 BKE_object_handle_update(scene_parent, ob);
1002                 
1003                 if (ob->dup_group && (ob->transflag & OB_DUPLIGROUP))
1004                         group_handle_recalc_and_update(scene_parent, ob, ob->dup_group);
1005                         
1006                 /* always update layer, so that animating layers works */
1007                 base->lay = ob->lay;
1008         }
1009         
1010         /* scene drivers... */
1011         scene_update_drivers(bmain, scene);
1012
1013         /* update sound system animation */
1014         sound_update_scene(scene);
1015
1016         /* update masking curves */
1017         BKE_mask_update_scene(bmain, scene, FALSE);
1018 }
1019
1020 /* this is called in main loop, doing tagged updates before redraw */
1021 void BKE_scene_update_tagged(Main *bmain, Scene *scene)
1022 {
1023         /* keep this first */
1024         BLI_callback_exec(bmain, &scene->id, BLI_CB_EVT_SCENE_UPDATE_PRE);
1025
1026         /* flush recalc flags to dependencies */
1027         DAG_ids_flush_tagged(bmain);
1028
1029         scene->physics_settings.quick_cache_step = 0;
1030         
1031         /* clear "LIB_DOIT" flag from all materials, to prevent infinite recursion problems later 
1032          * when trying to find materials with drivers that need evaluating [#32017] 
1033          */
1034         tag_main_idcode(bmain, ID_MA, FALSE);
1035
1036         /* update all objects: drivers, matrices, displists, etc. flags set
1037          * by depgraph or manual, no layer check here, gets correct flushed
1038          *
1039          * in the future this should handle updates for all datablocks, not
1040          * only objects and scenes. - brecht */
1041         scene_update_tagged_recursive(bmain, scene, scene);
1042
1043         /* extra call here to recalc scene animation (for sequencer) */
1044         {
1045                 AnimData *adt = BKE_animdata_from_id(&scene->id);
1046                 float ctime = BKE_scene_frame_get(scene);
1047                 
1048                 if (adt && (adt->recalc & ADT_RECALC_ANIM))
1049                         BKE_animsys_evaluate_animdata(scene, &scene->id, adt, ctime, 0);
1050         }
1051         
1052         /* quick point cache updates */
1053         if (scene->physics_settings.quick_cache_step)
1054                 BKE_ptcache_quick_cache_all(bmain, scene);
1055
1056         /* notify editors and python about recalc */
1057         BLI_callback_exec(bmain, &scene->id, BLI_CB_EVT_SCENE_UPDATE_POST);
1058         DAG_ids_check_recalc(bmain, scene, FALSE);
1059
1060         /* clear recalc flags */
1061         DAG_ids_clear_recalc(bmain);
1062 }
1063
1064 /* applies changes right away, does all sets too */
1065 void BKE_scene_update_for_newframe(Main *bmain, Scene *sce, unsigned int lay)
1066 {
1067         float ctime = BKE_scene_frame_get(sce);
1068         Scene *sce_iter;
1069
1070         /* keep this first */
1071         BLI_callback_exec(bmain, &sce->id, BLI_CB_EVT_FRAME_CHANGE_PRE);
1072         BLI_callback_exec(bmain, &sce->id, BLI_CB_EVT_SCENE_UPDATE_PRE);
1073
1074         sound_set_cfra(sce->r.cfra);
1075         
1076         /* clear animation overrides */
1077         /* XXX TODO... */
1078
1079         for (sce_iter = sce; sce_iter; sce_iter = sce_iter->set) {
1080                 if (sce_iter->theDag == NULL)
1081                         DAG_scene_sort(bmain, sce_iter);
1082         }
1083
1084         /* flush recalc flags to dependencies, if we were only changing a frame
1085          * this would not be necessary, but if a user or a script has modified
1086          * some datablock before BKE_scene_update_tagged was called, we need the flush */
1087         DAG_ids_flush_tagged(bmain);
1088
1089         /* Following 2 functions are recursive
1090          * so don't call within 'scene_update_tagged_recursive' */
1091         DAG_scene_update_flags(bmain, sce, lay, TRUE);   // only stuff that moves or needs display still
1092
1093         BKE_mask_evaluate_all_masks(bmain, ctime, TRUE);
1094
1095         /* All 'standard' (i.e. without any dependencies) animation is handled here,
1096          * with an 'local' to 'macro' order of evaluation. This should ensure that
1097          * settings stored nestled within a hierarchy (i.e. settings in a Texture block
1098          * can be overridden by settings from Scene, which owns the Texture through a hierarchy
1099          * such as Scene->World->MTex/Texture) can still get correctly overridden.
1100          */
1101         BKE_animsys_evaluate_all_animation(bmain, sce, ctime);
1102         /*...done with recusrive funcs */
1103
1104         /* BKE_object_handle_update() on all objects, groups and sets */
1105         scene_update_tagged_recursive(bmain, sce, sce);
1106
1107         /* notify editors and python about recalc */
1108         BLI_callback_exec(bmain, &sce->id, BLI_CB_EVT_SCENE_UPDATE_POST);
1109         BLI_callback_exec(bmain, &sce->id, BLI_CB_EVT_FRAME_CHANGE_POST);
1110
1111         DAG_ids_check_recalc(bmain, sce, TRUE);
1112
1113         /* clear recalc flags */
1114         DAG_ids_clear_recalc(bmain);
1115 }
1116
1117 /* return default layer, also used to patch old files */
1118 SceneRenderLayer *BKE_scene_add_render_layer(Scene *sce, const char *name)
1119 {
1120         SceneRenderLayer *srl;
1121
1122         if (!name)
1123                 name = "RenderLayer";
1124
1125         srl = MEM_callocN(sizeof(SceneRenderLayer), "new render layer");
1126         BLI_strncpy(srl->name, name, sizeof(srl->name));
1127         BLI_uniquename(&sce->r.layers, srl, "RenderLayer", '.', offsetof(SceneRenderLayer, name), sizeof(srl->name));
1128         BLI_addtail(&sce->r.layers, srl);
1129
1130         /* note, this is also in render, pipeline.c, to make layer when scenedata doesnt have it */
1131         srl->lay = (1 << 20) - 1;
1132         srl->layflag = 0x7FFF;   /* solid ztra halo edge strand */
1133         srl->passflag = SCE_PASS_COMBINED | SCE_PASS_Z;
1134
1135         return srl;
1136 }
1137
1138 int BKE_scene_remove_render_layer(Main *bmain, Scene *scene, SceneRenderLayer *srl)
1139 {
1140         const int act = BLI_findindex(&scene->r.layers, srl);
1141         Scene *sce;
1142
1143         if (act == -1) {
1144                 return 0;
1145         }
1146         else if ( (scene->r.layers.first == scene->r.layers.last) &&
1147                   (scene->r.layers.first == srl))
1148         {
1149                 /* ensure 1 layer is kept */
1150                 return 0;
1151         }
1152
1153         BLI_remlink(&scene->r.layers, srl);
1154         MEM_freeN(srl);
1155
1156         scene->r.actlay = 0;
1157
1158         for (sce = bmain->scene.first; sce; sce = sce->id.next) {
1159                 if (sce->nodetree) {
1160                         bNode *node;
1161                         for (node = sce->nodetree->nodes.first; node; node = node->next) {
1162                                 if (node->type == CMP_NODE_R_LAYERS && (Scene *)node->id == scene) {
1163                                         if (node->custom1 == act)
1164                                                 node->custom1 = 0;
1165                                         else if (node->custom1 > act)
1166                                                 node->custom1--;
1167                                 }
1168                         }
1169                 }
1170         }
1171
1172         return 1;
1173 }
1174
1175 /* render simplification */
1176
1177 int get_render_subsurf_level(RenderData *r, int lvl)
1178 {
1179         if (r->mode & R_SIMPLIFY)
1180                 return MIN2(r->simplify_subsurf, lvl);
1181         else
1182                 return lvl;
1183 }
1184
1185 int get_render_child_particle_number(RenderData *r, int num)
1186 {
1187         if (r->mode & R_SIMPLIFY)
1188                 return (int)(r->simplify_particles * num);
1189         else
1190                 return num;
1191 }
1192
1193 int get_render_shadow_samples(RenderData *r, int samples)
1194 {
1195         if ((r->mode & R_SIMPLIFY) && samples > 0)
1196                 return MIN2(r->simplify_shadowsamples, samples);
1197         else
1198                 return samples;
1199 }
1200
1201 float get_render_aosss_error(RenderData *r, float error)
1202 {
1203         if (r->mode & R_SIMPLIFY)
1204                 return ((1.0f - r->simplify_aosss) * 10.0f + 1.0f) * error;
1205         else
1206                 return error;
1207 }
1208
1209 /* helper function for the SETLOOPER macro */
1210 Base *_setlooper_base_step(Scene **sce_iter, Base *base)
1211 {
1212         if (base && base->next) {
1213                 /* common case, step to the next */
1214                 return base->next;
1215         }
1216         else if (base == NULL && (*sce_iter)->base.first) {
1217                 /* first time looping, return the scenes first base */
1218                 return (Base *)(*sce_iter)->base.first;
1219         }
1220         else {
1221                 /* reached the end, get the next base in the set */
1222                 while ((*sce_iter = (*sce_iter)->set)) {
1223                         base = (Base *)(*sce_iter)->base.first;
1224                         if (base) {
1225                                 return base;
1226                         }
1227                 }
1228         }
1229
1230         return NULL;
1231 }
1232
1233 int BKE_scene_use_new_shading_nodes(Scene *scene)
1234 {
1235         RenderEngineType *type = RE_engines_find(scene->r.engine);
1236         return (type && type->flag & RE_USE_SHADING_NODES);
1237 }
1238
1239 void BKE_scene_base_flag_to_objects(struct Scene *scene)
1240 {
1241         Base *base = scene->base.first;
1242
1243         while (base) {
1244                 base->object->flag = base->flag;
1245                 base = base->next;
1246         }
1247 }
1248
1249 void BKE_scene_base_flag_from_objects(struct Scene *scene)
1250 {
1251         Base *base = scene->base.first;
1252
1253         while (base) {
1254                 base->flag = base->object->flag;
1255                 base = base->next;
1256         }
1257 }