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