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