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