svn merge ^/trunk/blender -r46100:46200
[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 *copy_scene(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= add_scene(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= copy_libblock(&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= copy_world(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 free_scene(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         seq_free_editing(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 *add_scene(const char *name)
336 {
337         Main *bmain= G.main;
338         Scene *sce;
339         ParticleEditSettings *pset;
340         int a;
341
342         sce= alloc_libblock(&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         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
520         sce->gm.flag = GAME_DISPLAY_LISTS;
521         sce->gm.matmode = GAME_MAT_MULTITEX;
522
523         sce->gm.obstacleSimulation= OBSTSIMULATION_NONE;
524         sce->gm.levelHeight = 2.f;
525
526         sce->gm.recastData.cellsize = 0.3f;
527         sce->gm.recastData.cellheight = 0.2f;
528         sce->gm.recastData.agentmaxslope = M_PI/2;
529         sce->gm.recastData.agentmaxclimb = 0.9f;
530         sce->gm.recastData.agentheight = 2.0f;
531         sce->gm.recastData.agentradius = 0.6f;
532         sce->gm.recastData.edgemaxlen = 12.0f;
533         sce->gm.recastData.edgemaxerror = 1.3f;
534         sce->gm.recastData.regionminsize = 8.f;
535         sce->gm.recastData.regionmergesize = 20.f;
536         sce->gm.recastData.vertsperpoly = 6;
537         sce->gm.recastData.detailsampledist = 6.0f;
538         sce->gm.recastData.detailsamplemaxerror = 1.0f;
539
540         sce->gm.exitkey = 218; // Blender key code for ESC
541
542         sound_create_scene(sce);
543
544         return sce;
545 }
546
547 Base *object_in_scene(Object *ob, Scene *sce)
548 {
549         Base *base;
550         
551         base= sce->base.first;
552         while (base) {
553                 if (base->object == ob) return base;
554                 base= base->next;
555         }
556         return NULL;
557 }
558
559 void set_scene_bg(Main *bmain, Scene *scene)
560 {
561         Scene *sce;
562         Base *base;
563         Object *ob;
564         Group *group;
565         GroupObject *go;
566         int flag;
567         
568         /* check for cyclic sets, for reading old files but also for definite security (py?) */
569         scene_check_setscene(bmain, scene);
570         
571         /* can happen when switching modes in other scenes */
572         if (scene->obedit && !(scene->obedit->mode & OB_MODE_EDIT))
573                 scene->obedit= NULL;
574
575         /* deselect objects (for dataselect) */
576         for (ob= bmain->object.first; ob; ob= ob->id.next)
577                 ob->flag &= ~(SELECT|OB_FROMGROUP);
578
579         /* group flags again */
580         for (group= bmain->group.first; group; group= group->id.next) {
581                 go= group->gobject.first;
582                 while (go) {
583                         if (go->ob) go->ob->flag |= OB_FROMGROUP;
584                         go= go->next;
585                 }
586         }
587
588         /* sort baselist */
589         DAG_scene_sort(bmain, scene);
590         
591         /* ensure dags are built for sets */
592         for (sce= scene->set; sce; sce= sce->set)
593                 if (sce->theDag==NULL)
594                         DAG_scene_sort(bmain, sce);
595
596         /* copy layers and flags from bases to objects */
597         for (base= scene->base.first; base; base= base->next) {
598                 ob= base->object;
599                 ob->lay= base->lay;
600                 
601                 /* group patch... */
602                 base->flag &= ~(OB_FROMGROUP);
603                 flag= ob->flag & (OB_FROMGROUP);
604                 base->flag |= flag;
605                 
606                 /* not too nice... for recovering objects with lost data */
607                 //if (ob->pose==NULL) base->flag &= ~OB_POSEMODE;
608                 ob->flag= base->flag;
609                 
610                 ob->ctime= -1234567.0;  /* force ipo to be calculated later */
611         }
612         /* no full animation update, this to enable render code to work (render code calls own animation updates) */
613 }
614
615 /* called from creator.c */
616 Scene *set_scene_name(Main *bmain, const char *name)
617 {
618         Scene *sce= (Scene *)find_id("SC", name);
619         if (sce) {
620                 set_scene_bg(bmain, sce);
621                 printf("Scene switch: '%s' in file: '%s'\n", name, G.main->name);
622                 return sce;
623         }
624
625         printf("Can't find scene: '%s' in file: '%s'\n", name, G.main->name);
626         return NULL;
627 }
628
629 void unlink_scene(Main *bmain, Scene *sce, Scene *newsce)
630 {
631         Scene *sce1;
632         bScreen *sc;
633
634         /* check all sets */
635         for (sce1= bmain->scene.first; sce1; sce1= sce1->id.next)
636                 if (sce1->set == sce)
637                         sce1->set= NULL;
638         
639         /* check all sequences */
640         clear_scene_in_allseqs(bmain, sce);
641
642         /* check render layer nodes in other scenes */
643         clear_scene_in_nodes(bmain, sce);
644         
645         /* al screens */
646         for (sc= bmain->screen.first; sc; sc= sc->id.next)
647                 if (sc->scene == sce)
648                         sc->scene= newsce;
649
650         free_libblock(&bmain->scene, sce);
651 }
652
653 /* used by metaballs
654  * doesnt return the original duplicated object, only dupli's
655  */
656 int next_object(Scene **scene, int val, Base **base, Object **ob)
657 {
658         static ListBase *duplilist= NULL;
659         static DupliObject *dupob;
660         static int fase= F_START, in_next_object= 0;
661         int run_again=1;
662         
663         /* init */
664         if (val==0) {
665                 fase= F_START;
666                 dupob= NULL;
667                 
668                 /* XXX particle systems with metas+dupligroups call this recursively */
669                 /* see bug #18725 */
670                 if (in_next_object) {
671                         printf("ERROR: Metaball generation called recursively, not supported\n");
672                         
673                         return F_ERROR;
674                 }
675         }
676         else {
677                 in_next_object= 1;
678                 
679                 /* run_again is set when a duplilist has been ended */
680                 while (run_again) {
681                         run_again= 0;
682
683                         /* the first base */
684                         if (fase==F_START) {
685                                 *base= (*scene)->base.first;
686                                 if (*base) {
687                                         *ob= (*base)->object;
688                                         fase= F_SCENE;
689                                 }
690                                 else {
691                                         /* exception: empty scene */
692                                         while ((*scene)->set) {
693                                                 (*scene)= (*scene)->set;
694                                                 if ((*scene)->base.first) {
695                                                         *base= (*scene)->base.first;
696                                                         *ob= (*base)->object;
697                                                         fase= F_SCENE;
698                                                         break;
699                                                 }
700                                         }
701                                 }
702                         }
703                         else {
704                                 if (*base && fase!=F_DUPLI) {
705                                         *base= (*base)->next;
706                                         if (*base) *ob= (*base)->object;
707                                         else {
708                                                 if (fase==F_SCENE) {
709                                                         /* (*scene) is finished, now do the set */
710                                                         while ((*scene)->set) {
711                                                                 (*scene)= (*scene)->set;
712                                                                 if ((*scene)->base.first) {
713                                                                         *base= (*scene)->base.first;
714                                                                         *ob= (*base)->object;
715                                                                         break;
716                                                                 }
717                                                         }
718                                                 }
719                                         }
720                                 }
721                         }
722                         
723                         if (*base == NULL) fase= F_START;
724                         else {
725                                 if (fase!=F_DUPLI) {
726                                         if ( (*base)->object->transflag & OB_DUPLI) {
727                                                 /* groups cannot be duplicated for mballs yet, 
728                                                  * this enters eternal loop because of 
729                                                  * makeDispListMBall getting called inside of group_duplilist */
730                                                 if ((*base)->object->dup_group == NULL) {
731                                                         duplilist= object_duplilist((*scene), (*base)->object);
732                                                         
733                                                         dupob= duplilist->first;
734
735                                                         if (!dupob)
736                                                                 free_object_duplilist(duplilist);
737                                                 }
738                                         }
739                                 }
740                                 /* handle dupli's */
741                                 if (dupob) {
742                                         
743                                         copy_m4_m4(dupob->ob->obmat, dupob->mat);
744                                         
745                                         (*base)->flag |= OB_FROMDUPLI;
746                                         *ob= dupob->ob;
747                                         fase= F_DUPLI;
748                                         
749                                         dupob= dupob->next;
750                                 }
751                                 else if (fase==F_DUPLI) {
752                                         fase= F_SCENE;
753                                         (*base)->flag &= ~OB_FROMDUPLI;
754                                         
755                                         for (dupob= duplilist->first; dupob; dupob= dupob->next) {
756                                                 copy_m4_m4(dupob->ob->obmat, dupob->omat);
757                                         }
758                                         
759                                         free_object_duplilist(duplilist);
760                                         duplilist= NULL;
761                                         run_again= 1;
762                                 }
763                         }
764                 }
765         }
766
767 #if 0
768         if (ob && *ob) {
769                 printf("Scene: '%s', '%s'\n", (*scene)->id.name+2, (*ob)->id.name+2);
770         }
771 #endif
772
773         /* reset recursion test */
774         in_next_object= 0;
775         
776         return fase;
777 }
778
779 Object *scene_find_camera(Scene *sc)
780 {
781         Base *base;
782         
783         for (base= sc->base.first; base; base= base->next)
784                 if (base->object->type==OB_CAMERA)
785                         return base->object;
786
787         return NULL;
788 }
789
790 #ifdef DURIAN_CAMERA_SWITCH
791 Object *scene_camera_switch_find(Scene *scene)
792 {
793         TimeMarker *m;
794         int cfra = scene->r.cfra;
795         int frame = -(MAXFRAME + 1);
796         Object *camera= NULL;
797
798         for (m= scene->markers.first; m; m= m->next) {
799                 if (m->camera && (m->camera->restrictflag & OB_RESTRICT_RENDER)==0 && (m->frame <= cfra) && (m->frame > frame)) {
800                         camera= m->camera;
801                         frame= m->frame;
802
803                         if (frame == cfra)
804                                 break;
805
806                 }
807         }
808         return camera;
809 }
810 #endif
811
812 int scene_camera_switch_update(Scene *scene)
813 {
814 #ifdef DURIAN_CAMERA_SWITCH
815         Object *camera= scene_camera_switch_find(scene);
816         if (camera) {
817                 scene->camera= camera;
818                 return 1;
819         }
820 #else
821         (void)scene;
822 #endif
823         return 0;
824 }
825
826 char *scene_find_marker_name(Scene *scene, int frame)
827 {
828         ListBase *markers= &scene->markers;
829         TimeMarker *m1, *m2;
830
831         /* search through markers for match */
832         for (m1=markers->first, m2=markers->last; m1 && m2; m1=m1->next, m2=m2->prev) {
833                 if (m1->frame==frame)
834                         return m1->name;
835
836                 if (m1 == m2)
837                         break;
838
839                 if (m2->frame==frame)
840                         return m2->name;
841         }
842
843         return NULL;
844 }
845
846 /* return the current marker for this frame,
847  * we can have more then 1 marker per frame, this just returns the first :/ */
848 char *scene_find_last_marker_name(Scene *scene, int frame)
849 {
850         TimeMarker *marker, *best_marker = NULL;
851         int best_frame = -MAXFRAME*2;
852         for (marker= scene->markers.first; marker; marker= marker->next) {
853                 if (marker->frame==frame) {
854                         return marker->name;
855                 }
856
857                 if ( marker->frame > best_frame && marker->frame < frame) {
858                         best_marker = marker;
859                         best_frame = marker->frame;
860                 }
861         }
862
863         return best_marker ? best_marker->name : NULL;
864 }
865
866
867 Base *scene_add_base(Scene *sce, Object *ob)
868 {
869         Base *b= MEM_callocN(sizeof(*b), "scene_add_base");
870         BLI_addhead(&sce->base, b);
871
872         b->object= ob;
873         b->flag= ob->flag;
874         b->lay= ob->lay;
875
876         return b;
877 }
878
879 void scene_deselect_all(Scene *sce)
880 {
881         Base *b;
882
883         for (b= sce->base.first; b; b= b->next) {
884                 b->flag&= ~SELECT;
885                 b->object->flag= b->flag;
886         }
887 }
888
889 void scene_select_base(Scene *sce, Base *selbase)
890 {
891         scene_deselect_all(sce);
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 scene_check_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_curframe(Scene *scene)
927 {
928         return BKE_frame_to_ctime(scene, scene->r.cfra);
929 }
930
931 /* This function is used to obtain arbitrary fractional frames */
932 float BKE_frame_to_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_curframe(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                 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
1008 /* this is called in main loop, doing tagged updates before redraw */
1009 void scene_update_tagged(Main *bmain, Scene *scene)
1010 {
1011         /* keep this first */
1012         BLI_exec_cb(bmain, &scene->id, BLI_CB_EVT_SCENE_UPDATE_PRE);
1013
1014         /* flush recalc flags to dependencies */
1015         DAG_ids_flush_tagged(bmain);
1016
1017         scene->physics_settings.quick_cache_step= 0;
1018
1019         /* update all objects: drivers, matrices, displists, etc. flags set
1020          * by depgraph or manual, no layer check here, gets correct flushed
1021          *
1022          * in the future this should handle updates for all datablocks, not
1023          * only objects and scenes. - brecht */
1024         scene_update_tagged_recursive(bmain, scene, scene);
1025
1026         /* extra call here to recalc scene animation (for sequencer) */
1027         {
1028                 AnimData *adt= BKE_animdata_from_id(&scene->id);
1029                 float ctime = BKE_curframe(scene);
1030                 
1031                 if (adt && (adt->recalc & ADT_RECALC_ANIM))
1032                         BKE_animsys_evaluate_animdata(scene, &scene->id, adt, ctime, 0);
1033         }
1034         
1035         /* quick point cache updates */
1036         if (scene->physics_settings.quick_cache_step)
1037                 BKE_ptcache_quick_cache_all(bmain, scene);
1038
1039         /* notify editors and python about recalc */
1040         BLI_exec_cb(bmain, &scene->id, BLI_CB_EVT_SCENE_UPDATE_POST);
1041         DAG_ids_check_recalc(bmain, scene, FALSE);
1042
1043         /* clear recalc flags */
1044         DAG_ids_clear_recalc(bmain);
1045 }
1046
1047 /* applies changes right away, does all sets too */
1048 void scene_update_for_newframe(Main *bmain, Scene *sce, unsigned int lay)
1049 {
1050         float ctime = BKE_curframe(sce);
1051         Scene *sce_iter;
1052
1053         /* keep this first */
1054         BLI_exec_cb(bmain, &sce->id, BLI_CB_EVT_FRAME_CHANGE_PRE);
1055         BLI_exec_cb(bmain, &sce->id, BLI_CB_EVT_SCENE_UPDATE_PRE);
1056
1057         sound_set_cfra(sce->r.cfra);
1058         
1059         /* clear animation overrides */
1060         // XXX TODO...
1061
1062         for (sce_iter= sce; sce_iter; sce_iter= sce_iter->set) {
1063                 if (sce_iter->theDag==NULL)
1064                         DAG_scene_sort(bmain, sce_iter);
1065         }
1066
1067         /* flush recalc flags to dependencies, if we were only changing a frame
1068          * this would not be necessary, but if a user or a script has modified
1069          * some datablock before scene_update_tagged was called, we need the flush */
1070         DAG_ids_flush_tagged(bmain);
1071
1072         /* Following 2 functions are recursive
1073          * so don't call within 'scene_update_tagged_recursive' */
1074         DAG_scene_update_flags(bmain, sce, lay, TRUE);   // only stuff that moves or needs display still
1075
1076         /* All 'standard' (i.e. without any dependencies) animation is handled here,
1077          * with an 'local' to 'macro' order of evaluation. This should ensure that
1078          * settings stored nestled within a hierarchy (i.e. settings in a Texture block
1079          * can be overridden by settings from Scene, which owns the Texture through a hierarchy
1080          * such as Scene->World->MTex/Texture) can still get correctly overridden.
1081          */
1082         BKE_animsys_evaluate_all_animation(bmain, sce, ctime);
1083         /*...done with recusrive funcs */
1084
1085         /* object_handle_update() on all objects, groups and sets */
1086         scene_update_tagged_recursive(bmain, sce, sce);
1087
1088         /* notify editors and python about recalc */
1089         BLI_exec_cb(bmain, &sce->id, BLI_CB_EVT_SCENE_UPDATE_POST);
1090         BLI_exec_cb(bmain, &sce->id, BLI_CB_EVT_FRAME_CHANGE_POST);
1091
1092         DAG_ids_check_recalc(bmain, sce, TRUE);
1093
1094         /* clear recalc flags */
1095         DAG_ids_clear_recalc(bmain);
1096 }
1097
1098 /* return default layer, also used to patch old files */
1099 SceneRenderLayer *scene_add_render_layer(Scene *sce, const char *name)
1100 {
1101         SceneRenderLayer *srl;
1102
1103         if (!name)
1104                 name= "RenderLayer";
1105
1106         srl= MEM_callocN(sizeof(SceneRenderLayer), "new render layer");
1107         BLI_strncpy(srl->name, name, sizeof(srl->name));
1108         BLI_uniquename(&sce->r.layers, srl, "RenderLayer", '.', offsetof(SceneRenderLayer, name), sizeof(srl->name));
1109         BLI_addtail(&sce->r.layers, srl);
1110
1111         /* note, this is also in render, pipeline.c, to make layer when scenedata doesnt have it */
1112         srl->lay= (1<<20) -1;
1113         srl->layflag= 0x7FFF;   /* solid ztra halo edge strand */
1114         srl->passflag= SCE_PASS_COMBINED|SCE_PASS_Z;
1115
1116         return srl;
1117 }
1118
1119 int scene_remove_render_layer(Main *bmain, Scene *scene, SceneRenderLayer *srl)
1120 {
1121         const int act= BLI_findindex(&scene->r.layers, srl);
1122         Scene *sce;
1123
1124         if (act == -1) {
1125                 return 0;
1126         }
1127         else if ( (scene->r.layers.first == scene->r.layers.last) &&
1128                   (scene->r.layers.first == srl))
1129         {
1130                 /* ensure 1 layer is kept */
1131                 return 0;
1132         }
1133
1134         BLI_remlink(&scene->r.layers, srl);
1135         MEM_freeN(srl);
1136
1137         scene->r.actlay= 0;
1138
1139         for (sce = bmain->scene.first; sce; sce = sce->id.next) {
1140                 if (sce->nodetree) {
1141                         bNode *node;
1142                         for (node = sce->nodetree->nodes.first; node; node = node->next) {
1143                                 if (node->type==CMP_NODE_R_LAYERS && (Scene*)node->id==scene) {
1144                                         if (node->custom1==act)
1145                                                 node->custom1= 0;
1146                                         else if (node->custom1>act)
1147                                                 node->custom1--;
1148                                 }
1149                         }
1150                 }
1151         }
1152
1153         return 1;
1154 }
1155
1156 /* render simplification */
1157
1158 int get_render_subsurf_level(RenderData *r, int lvl)
1159 {
1160         if (r->mode & R_SIMPLIFY)
1161                 return MIN2(r->simplify_subsurf, lvl);
1162         else
1163                 return lvl;
1164 }
1165
1166 int get_render_child_particle_number(RenderData *r, int num)
1167 {
1168         if (r->mode & R_SIMPLIFY)
1169                 return (int)(r->simplify_particles*num);
1170         else
1171                 return num;
1172 }
1173
1174 int get_render_shadow_samples(RenderData *r, int samples)
1175 {
1176         if ((r->mode & R_SIMPLIFY) && samples > 0)
1177                 return MIN2(r->simplify_shadowsamples, samples);
1178         else
1179                 return samples;
1180 }
1181
1182 float get_render_aosss_error(RenderData *r, float error)
1183 {
1184         if (r->mode & R_SIMPLIFY)
1185                 return ((1.0f-r->simplify_aosss)*10.0f + 1.0f)*error;
1186         else
1187                 return error;
1188 }
1189
1190 /* helper function for the SETLOOPER macro */
1191 Base *_setlooper_base_step(Scene **sce_iter, Base *base)
1192 {
1193         if (base && base->next) {
1194                 /* common case, step to the next */
1195                 return base->next;
1196         }
1197         else if (base==NULL && (*sce_iter)->base.first) {
1198                 /* first time looping, return the scenes first base */
1199                 return (Base *)(*sce_iter)->base.first;
1200         }
1201         else {
1202                 /* reached the end, get the next base in the set */
1203                 while ((*sce_iter= (*sce_iter)->set)) {
1204                         base= (Base *)(*sce_iter)->base.first;
1205                         if (base) {
1206                                 return base;
1207                         }
1208                 }
1209         }
1210
1211         return NULL;
1212 }
1213
1214 int scene_use_new_shading_nodes(Scene *scene)
1215 {
1216         RenderEngineType *type= RE_engines_find(scene->r.engine);
1217         return (type && type->flag & RE_USE_SHADING_NODES);
1218 }
1219