9002003d380fbcedb60d0c411dd64d94e37b72ff
[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 #include "MEM_guardedalloc.h"
38
39 #include "DNA_anim_types.h"
40 #include "DNA_group_types.h"
41 #include "DNA_linestyle_types.h"
42 #include "DNA_mesh_types.h"
43 #include "DNA_node_types.h"
44 #include "DNA_object_types.h"
45 #include "DNA_rigidbody_types.h"
46 #include "DNA_scene_types.h"
47 #include "DNA_screen_types.h"
48 #include "DNA_sequence_types.h"
49 #include "DNA_space_types.h"
50 #include "DNA_view3d_types.h"
51 #include "DNA_windowmanager_types.h"
52 #include "DNA_gpencil_types.h"
53
54 #include "BLI_math.h"
55 #include "BLI_blenlib.h"
56 #include "BLI_utildefines.h"
57 #include "BLI_callbacks.h"
58 #include "BLI_string.h"
59 #include "BLI_string_utils.h"
60 #include "BLI_threads.h"
61 #include "BLI_task.h"
62
63 #include "BLT_translation.h"
64
65 #include "BKE_anim.h"
66 #include "BKE_animsys.h"
67 #include "BKE_action.h"
68 #include "BKE_armature.h"
69 #include "BKE_cachefile.h"
70 #include "BKE_colortools.h"
71 #include "BKE_depsgraph.h"
72 #include "BKE_editmesh.h"
73 #include "BKE_fcurve.h"
74 #include "BKE_freestyle.h"
75 #include "BKE_global.h"
76 #include "BKE_gpencil.h"
77 #include "BKE_group.h"
78 #include "BKE_icons.h"
79 #include "BKE_idprop.h"
80 #include "BKE_image.h"
81 #include "BKE_library.h"
82 #include "BKE_library_remap.h"
83 #include "BKE_linestyle.h"
84 #include "BKE_main.h"
85 #include "BKE_mask.h"
86 #include "BKE_node.h"
87 #include "BKE_object.h"
88 #include "BKE_paint.h"
89 #include "BKE_rigidbody.h"
90 #include "BKE_scene.h"
91 #include "BKE_screen.h"
92 #include "BKE_sequencer.h"
93 #include "BKE_sound.h"
94 #include "BKE_unit.h"
95 #include "BKE_world.h"
96
97 #include "DEG_depsgraph.h"
98
99 #include "RE_engine.h"
100
101 #include "PIL_time.h"
102
103 #include "IMB_colormanagement.h"
104 #include "IMB_imbuf.h"
105
106 #include "bmesh.h"
107
108 const char *RE_engine_id_BLENDER_RENDER = "BLENDER_RENDER";
109 const char *RE_engine_id_BLENDER_GAME = "BLENDER_GAME";
110 const char *RE_engine_id_CYCLES = "CYCLES";
111
112 void free_avicodecdata(AviCodecData *acd)
113 {
114         if (acd) {
115                 if (acd->lpFormat) {
116                         MEM_freeN(acd->lpFormat);
117                         acd->lpFormat = NULL;
118                         acd->cbFormat = 0;
119                 }
120                 if (acd->lpParms) {
121                         MEM_freeN(acd->lpParms);
122                         acd->lpParms = NULL;
123                         acd->cbParms = 0;
124                 }
125         }
126 }
127
128 void free_qtcodecdata(QuicktimeCodecData *qcd)
129 {
130         if (qcd) {
131                 if (qcd->cdParms) {
132                         MEM_freeN(qcd->cdParms);
133                         qcd->cdParms = NULL;
134                         qcd->cdSize = 0;
135                 }
136         }
137 }
138
139 static void remove_sequencer_fcurves(Scene *sce)
140 {
141         AnimData *adt = BKE_animdata_from_id(&sce->id);
142
143         if (adt && adt->action) {
144                 FCurve *fcu, *nextfcu;
145                 
146                 for (fcu = adt->action->curves.first; fcu; fcu = nextfcu) {
147                         nextfcu = fcu->next;
148                         
149                         if ((fcu->rna_path) && strstr(fcu->rna_path, "sequences_all")) {
150                                 action_groups_remove_channel(adt->action, fcu);
151                                 free_fcurve(fcu);
152                         }
153                 }
154         }
155 }
156
157 /**
158  * Only copy internal data of Scene ID from source to already allocated/initialized destination.
159  * You probably nerver want to use that directly, use id_copy or BKE_id_copy_ex for typical needs.
160  *
161  * WARNING! This function will not handle ID user count!
162  *
163  * \param flag  Copying options (see BKE_library.h's LIB_ID_COPY_... flags for more).
164  */
165 void BKE_scene_copy_data(Main *bmain, Scene *sce_dst, const Scene *sce_src, const int flag)
166 {
167         /* We never handle usercount here for own data. */
168         const int flag_subdata = flag | LIB_ID_CREATE_NO_USER_REFCOUNT;
169
170         sce_dst->ed = NULL;
171         sce_dst->theDag = NULL;
172         sce_dst->depsgraph = NULL;
173         sce_dst->obedit = NULL;
174         sce_dst->stats = NULL;
175         sce_dst->fps_info = NULL;
176
177         BLI_duplicatelist(&(sce_dst->base), &(sce_src->base));
178         for (Base *base_dst = sce_dst->base.first, *base_src = sce_src->base.first;
179              base_dst;
180              base_dst = base_dst->next, base_src = base_src->next)
181         {
182                 if (base_src == sce_src->basact) {
183                         sce_dst->basact = base_dst;
184                 }
185         }
186
187         BLI_duplicatelist(&(sce_dst->markers), &(sce_src->markers));
188         BLI_duplicatelist(&(sce_dst->transform_spaces), &(sce_src->transform_spaces));
189         BLI_duplicatelist(&(sce_dst->r.layers), &(sce_src->r.layers));
190         BLI_duplicatelist(&(sce_dst->r.views), &(sce_src->r.views));
191         BKE_keyingsets_copy(&(sce_dst->keyingsets), &(sce_src->keyingsets));
192
193         if (sce_src->nodetree) {
194                 BKE_id_copy_ex(bmain, (ID *)sce_src->nodetree, (ID **)&sce_dst->nodetree, flag, false);
195                 BKE_libblock_relink_ex(bmain, sce_dst->nodetree, (void *)(&sce_src->id), &sce_dst->id, false);
196         }
197
198         if (sce_src->rigidbody_world) {
199                 sce_dst->rigidbody_world = BKE_rigidbody_world_copy(sce_src->rigidbody_world, flag_subdata);
200         }
201
202         /* copy Freestyle settings */
203         for (SceneRenderLayer *srl_dst = sce_dst->r.layers.first, *srl_src = sce_src->r.layers.first;
204              srl_src;
205              srl_dst = srl_dst->next, srl_src = srl_src->next)
206         {
207                 if (srl_dst->prop != NULL) {
208                         srl_dst->prop = IDP_CopyProperty_ex(srl_dst->prop, flag_subdata);
209                 }
210                 BKE_freestyle_config_copy(&srl_dst->freestyleConfig, &srl_src->freestyleConfig, flag_subdata);
211         }
212
213         /* copy color management settings */
214         BKE_color_managed_display_settings_copy(&sce_dst->display_settings, &sce_src->display_settings);
215         BKE_color_managed_view_settings_copy(&sce_dst->view_settings, &sce_src->view_settings);
216         BKE_color_managed_colorspace_settings_copy(&sce_dst->sequencer_colorspace_settings, &sce_src->sequencer_colorspace_settings);
217
218         BKE_color_managed_display_settings_copy(&sce_dst->r.im_format.display_settings, &sce_src->r.im_format.display_settings);
219         BKE_color_managed_view_settings_copy(&sce_dst->r.im_format.view_settings, &sce_src->r.im_format.view_settings);
220
221         BKE_color_managed_display_settings_copy(&sce_dst->r.bake.im_format.display_settings, &sce_src->r.bake.im_format.display_settings);
222         BKE_color_managed_view_settings_copy(&sce_dst->r.bake.im_format.view_settings, &sce_src->r.bake.im_format.view_settings);
223
224         curvemapping_copy_data(&sce_dst->r.mblur_shutter_curve, &sce_src->r.mblur_shutter_curve);
225
226         /* tool settings */
227         if (sce_dst->toolsettings != NULL) {
228                 ToolSettings *ts = sce_dst->toolsettings = MEM_dupallocN(sce_dst->toolsettings);
229                 if (ts->vpaint) {
230                         ts->vpaint = MEM_dupallocN(ts->vpaint);
231                         ts->vpaint->paintcursor = NULL;
232                         ts->vpaint->vpaint_prev = NULL;
233                         ts->vpaint->wpaint_prev = NULL;
234                         BKE_paint_copy(&ts->vpaint->paint, &ts->vpaint->paint, flag_subdata);
235                 }
236                 if (ts->wpaint) {
237                         ts->wpaint = MEM_dupallocN(ts->wpaint);
238                         ts->wpaint->paintcursor = NULL;
239                         ts->wpaint->vpaint_prev = NULL;
240                         ts->wpaint->wpaint_prev = NULL;
241                         BKE_paint_copy(&ts->wpaint->paint, &ts->wpaint->paint, flag_subdata);
242                 }
243                 if (ts->sculpt) {
244                         ts->sculpt = MEM_dupallocN(ts->sculpt);
245                         BKE_paint_copy(&ts->sculpt->paint, &ts->sculpt->paint, flag_subdata);
246                 }
247                 if (ts->uvsculpt) {
248                         ts->uvsculpt = MEM_dupallocN(ts->uvsculpt);
249                         BKE_paint_copy(&ts->uvsculpt->paint, &ts->uvsculpt->paint, flag_subdata);
250                 }
251
252                 BKE_paint_copy(&ts->imapaint.paint, &ts->imapaint.paint, flag_subdata);
253                 ts->imapaint.paintcursor = NULL;
254                 ts->particle.paintcursor = NULL;
255                 ts->particle.scene = NULL;
256                 ts->particle.object = NULL;
257
258                 /* duplicate Grease Pencil Drawing Brushes */
259                 BLI_listbase_clear(&ts->gp_brushes);
260                 for (bGPDbrush *brush = sce_src->toolsettings->gp_brushes.first; brush; brush = brush->next) {
261                         bGPDbrush *newbrush = BKE_gpencil_brush_duplicate(brush);
262                         BLI_addtail(&ts->gp_brushes, newbrush);
263                 }
264
265                 /* duplicate Grease Pencil interpolation curve */
266                 ts->gp_interpolate.custom_ipo = curvemapping_copy(ts->gp_interpolate.custom_ipo);
267         }
268
269         /* make a private copy of the avicodecdata */
270         if (sce_src->r.avicodecdata) {
271                 sce_dst->r.avicodecdata = MEM_dupallocN(sce_src->r.avicodecdata);
272                 sce_dst->r.avicodecdata->lpFormat = MEM_dupallocN(sce_dst->r.avicodecdata->lpFormat);
273                 sce_dst->r.avicodecdata->lpParms = MEM_dupallocN(sce_dst->r.avicodecdata->lpParms);
274         }
275
276         /* make a private copy of the qtcodecdata */
277         if (sce_src->r.qtcodecdata) {
278                 sce_dst->r.qtcodecdata = MEM_dupallocN(sce_src->r.qtcodecdata);
279                 sce_dst->r.qtcodecdata->cdParms = MEM_dupallocN(sce_dst->r.qtcodecdata->cdParms);
280         }
281
282         if (sce_src->r.ffcodecdata.properties) { /* intentionally check sce_dst not sce_src. */  /* XXX ??? comment outdated... */
283                 sce_dst->r.ffcodecdata.properties = IDP_CopyProperty_ex(sce_src->r.ffcodecdata.properties, flag_subdata);
284         }
285
286         /* before scene copy */
287         BKE_sound_create_scene(sce_dst);
288
289         /* Copy sequencer, this is local data! */
290         if (sce_src->ed) {
291                 sce_dst->ed = MEM_callocN(sizeof(*sce_dst->ed), __func__);
292                 sce_dst->ed->seqbasep = &sce_dst->ed->seqbase;
293                 BKE_sequence_base_dupli_recursive(
294                             sce_src, sce_dst, &sce_dst->ed->seqbase, &sce_src->ed->seqbase, SEQ_DUPE_ALL, flag_subdata);
295         }
296
297         if ((flag & LIB_ID_COPY_NO_PREVIEW) == 0) {
298                 BKE_previewimg_id_copy(&sce_dst->id, &sce_src->id);
299         }
300         else {
301                 sce_dst->preview = NULL;
302         }
303 }
304
305 Scene *BKE_scene_copy(Main *bmain, Scene *sce, int type)
306 {
307         Scene *sce_copy;
308
309         /* TODO this should/could most likely be replaced by call to more generic code at some point...
310          * But for now, let's keep it well isolated here. */
311         if (type == SCE_COPY_EMPTY) {
312                 ToolSettings *ts;
313                 ListBase rl, rv;
314
315                 sce_copy = BKE_scene_add(bmain, sce->id.name + 2);
316                 
317                 rl = sce_copy->r.layers;
318                 rv = sce_copy->r.views;
319                 curvemapping_free_data(&sce_copy->r.mblur_shutter_curve);
320                 sce_copy->r = sce->r;
321                 sce_copy->r.layers = rl;
322                 sce_copy->r.actlay = 0;
323                 sce_copy->r.views = rv;
324                 sce_copy->unit = sce->unit;
325                 sce_copy->physics_settings = sce->physics_settings;
326                 sce_copy->gm = sce->gm;
327                 sce_copy->audio = sce->audio;
328
329                 if (sce->id.properties)
330                         sce_copy->id.properties = IDP_CopyProperty(sce->id.properties);
331
332                 MEM_freeN(sce_copy->toolsettings);
333                 BKE_sound_destroy_scene(sce_copy);
334
335                 /* copy color management settings */
336                 BKE_color_managed_display_settings_copy(&sce_copy->display_settings, &sce->display_settings);
337                 BKE_color_managed_view_settings_copy(&sce_copy->view_settings, &sce->view_settings);
338                 BKE_color_managed_colorspace_settings_copy(&sce_copy->sequencer_colorspace_settings, &sce->sequencer_colorspace_settings);
339
340                 BKE_color_managed_display_settings_copy(&sce_copy->r.im_format.display_settings, &sce->r.im_format.display_settings);
341                 BKE_color_managed_view_settings_copy(&sce_copy->r.im_format.view_settings, &sce->r.im_format.view_settings);
342
343                 BKE_color_managed_display_settings_copy(&sce_copy->r.bake.im_format.display_settings, &sce->r.bake.im_format.display_settings);
344                 BKE_color_managed_view_settings_copy(&sce_copy->r.bake.im_format.view_settings, &sce->r.bake.im_format.view_settings);
345
346                 curvemapping_copy_data(&sce_copy->r.mblur_shutter_curve, &sce->r.mblur_shutter_curve);
347
348                 /* tool settings */
349                 sce_copy->toolsettings = MEM_dupallocN(sce->toolsettings);
350
351                 ts = sce_copy->toolsettings;
352                 if (ts) {
353                         if (ts->vpaint) {
354                                 ts->vpaint = MEM_dupallocN(ts->vpaint);
355                                 ts->vpaint->paintcursor = NULL;
356                                 ts->vpaint->vpaint_prev = NULL;
357                                 ts->vpaint->wpaint_prev = NULL;
358                                 BKE_paint_copy(&ts->vpaint->paint, &ts->vpaint->paint, 0);
359                         }
360                         if (ts->wpaint) {
361                                 ts->wpaint = MEM_dupallocN(ts->wpaint);
362                                 ts->wpaint->paintcursor = NULL;
363                                 ts->wpaint->vpaint_prev = NULL;
364                                 ts->wpaint->wpaint_prev = NULL;
365                                 BKE_paint_copy(&ts->wpaint->paint, &ts->wpaint->paint, 0);
366                         }
367                         if (ts->sculpt) {
368                                 ts->sculpt = MEM_dupallocN(ts->sculpt);
369                                 BKE_paint_copy(&ts->sculpt->paint, &ts->sculpt->paint, 0);
370                         }
371                         if (ts->uvsculpt) {
372                                 ts->uvsculpt = MEM_dupallocN(ts->uvsculpt);
373                                 BKE_paint_copy(&ts->uvsculpt->paint, &ts->uvsculpt->paint, 0);
374                         }
375
376                         BKE_paint_copy(&ts->imapaint.paint, &ts->imapaint.paint, 0);
377                         ts->imapaint.paintcursor = NULL;
378                         id_us_plus((ID *)ts->imapaint.stencil);
379                         id_us_plus((ID *)ts->imapaint.clone);
380                         id_us_plus((ID *)ts->imapaint.canvas);
381                         ts->particle.paintcursor = NULL;
382                         ts->particle.scene = NULL;
383                         ts->particle.object = NULL;
384
385                         /* duplicate Grease Pencil Drawing Brushes */
386                         BLI_listbase_clear(&ts->gp_brushes);
387                         for (bGPDbrush *brush = sce->toolsettings->gp_brushes.first; brush; brush = brush->next) {
388                                 bGPDbrush *newbrush = BKE_gpencil_brush_duplicate(brush);
389                                 BLI_addtail(&ts->gp_brushes, newbrush);
390                         }
391
392                         /* duplicate Grease Pencil interpolation curve */
393                         ts->gp_interpolate.custom_ipo = curvemapping_copy(ts->gp_interpolate.custom_ipo);
394                 }
395
396                 /* make a private copy of the avicodecdata */
397                 if (sce->r.avicodecdata) {
398                         sce_copy->r.avicodecdata = MEM_dupallocN(sce->r.avicodecdata);
399                         sce_copy->r.avicodecdata->lpFormat = MEM_dupallocN(sce_copy->r.avicodecdata->lpFormat);
400                         sce_copy->r.avicodecdata->lpParms = MEM_dupallocN(sce_copy->r.avicodecdata->lpParms);
401                 }
402
403                 /* make a private copy of the qtcodecdata */
404                 if (sce->r.qtcodecdata) {
405                         sce_copy->r.qtcodecdata = MEM_dupallocN(sce->r.qtcodecdata);
406                         sce_copy->r.qtcodecdata->cdParms = MEM_dupallocN(sce_copy->r.qtcodecdata->cdParms);
407                 }
408
409                 if (sce->r.ffcodecdata.properties) { /* intentionally check scen not sce. */
410                         sce_copy->r.ffcodecdata.properties = IDP_CopyProperty(sce->r.ffcodecdata.properties);
411                 }
412
413                 /* before scene copy */
414                 BKE_sound_create_scene(sce_copy);
415
416                 /* grease pencil */
417                 sce_copy->gpd = NULL;
418
419                 sce_copy->preview = NULL;
420
421                 return sce_copy;
422         }
423         else {
424                 BKE_id_copy_ex(bmain, (ID *)sce, (ID **)&sce_copy, LIB_ID_COPY_ACTIONS, false);
425
426                 /* Extra actions, most notably SCE_FULL_COPY also duplicates several 'children' datablocks... */
427
428                 if (type == SCE_COPY_FULL) {
429                         /* Copy Freestyle LineStyle datablocks. */
430                         for (SceneRenderLayer *srl_dst = sce_copy->r.layers.first; srl_dst; srl_dst = srl_dst->next) {
431                                 for (FreestyleLineSet *lineset = srl_dst->freestyleConfig.linesets.first; lineset; lineset = lineset->next) {
432                                         if (lineset->linestyle) {
433                                                 /* XXX Not copying anim/actions here? */
434                                                 BKE_id_copy_ex(bmain, (ID *)lineset->linestyle, (ID **)&lineset->linestyle, 0, false);
435                                         }
436                                 }
437                         }
438
439                         /* Full copy of world (included animations) */
440                         if (sce_copy->world) {
441                                 BKE_id_copy_ex(bmain, (ID *)sce_copy->world, (ID **)&sce_copy->world, LIB_ID_COPY_ACTIONS, false);
442                         }
443
444                         /* Full copy of GreasePencil. */
445                         /* XXX Not copying anim/actions here? */
446                         if (sce_copy->gpd) {
447                                 BKE_id_copy_ex(bmain, (ID *)sce_copy->gpd, (ID **)&sce_copy->gpd, 0, false);
448                         }
449                 }
450                 else {
451                         /* Remove sequencer if not full copy */
452                         /* XXX Why in Hell? :/ */
453                         remove_sequencer_fcurves(sce_copy);
454                         BKE_sequencer_editing_free(sce_copy);
455                 }
456
457                 /* NOTE: part of SCE_COPY_LINK_DATA and SCE_COPY_FULL operations
458                  * are done outside of blenkernel with ED_objects_single_users! */
459
460                 /*  camera */
461                 if (ELEM(type, SCE_COPY_LINK_DATA, SCE_COPY_FULL)) {
462                         ID_NEW_REMAP(sce_copy->camera);
463                 }
464
465                 return sce_copy;
466         }
467 }
468
469 void BKE_scene_groups_relink(Scene *sce)
470 {
471         if (sce->rigidbody_world)
472                 BKE_rigidbody_world_groups_relink(sce->rigidbody_world);
473 }
474
475 void BKE_scene_make_local(Main *bmain, Scene *sce, const bool lib_local)
476 {
477         /* For now should work, may need more work though to support all possible corner cases
478          * (also scene_copy probably needs some love). */
479         BKE_id_make_local_generic(bmain, &sce->id, true, lib_local);
480 }
481
482 /** Free (or release) any data used by this scene (does not free the scene itself). */
483 void BKE_scene_free(Scene *sce)
484 {
485         SceneRenderLayer *srl;
486
487         BKE_animdata_free((ID *)sce, false);
488
489         /* check all sequences */
490         BKE_sequencer_clear_scene_in_allseqs(G.main, sce);
491
492         sce->basact = NULL;
493         BLI_freelistN(&sce->base);
494         BKE_sequencer_editing_free(sce);
495
496         BKE_keyingsets_free(&sce->keyingsets);
497
498         /* is no lib link block, but scene extension */
499         if (sce->nodetree) {
500                 ntreeFreeTree(sce->nodetree);
501                 MEM_freeN(sce->nodetree);
502                 sce->nodetree = NULL;
503         }
504
505         if (sce->rigidbody_world) {
506                 BKE_rigidbody_free_world(sce->rigidbody_world);
507                 sce->rigidbody_world = NULL;
508         }
509
510         if (sce->r.avicodecdata) {
511                 free_avicodecdata(sce->r.avicodecdata);
512                 MEM_freeN(sce->r.avicodecdata);
513                 sce->r.avicodecdata = NULL;
514         }
515         if (sce->r.qtcodecdata) {
516                 free_qtcodecdata(sce->r.qtcodecdata);
517                 MEM_freeN(sce->r.qtcodecdata);
518                 sce->r.qtcodecdata = NULL;
519         }
520         if (sce->r.ffcodecdata.properties) {
521                 IDP_FreeProperty(sce->r.ffcodecdata.properties);
522                 MEM_freeN(sce->r.ffcodecdata.properties);
523                 sce->r.ffcodecdata.properties = NULL;
524         }
525
526         for (srl = sce->r.layers.first; srl; srl = srl->next) {
527                 if (srl->prop != NULL) {
528                         IDP_FreeProperty(srl->prop);
529                         MEM_freeN(srl->prop);
530                 }
531                 BKE_freestyle_config_free(&srl->freestyleConfig);
532         }
533
534         BLI_freelistN(&sce->markers);
535         BLI_freelistN(&sce->transform_spaces);
536         BLI_freelistN(&sce->r.layers);
537         BLI_freelistN(&sce->r.views);
538         
539         if (sce->toolsettings) {
540                 if (sce->toolsettings->vpaint) {
541                         BKE_paint_free(&sce->toolsettings->vpaint->paint);
542                         MEM_freeN(sce->toolsettings->vpaint);
543                 }
544                 if (sce->toolsettings->wpaint) {
545                         BKE_paint_free(&sce->toolsettings->wpaint->paint);
546                         MEM_freeN(sce->toolsettings->wpaint);
547                 }
548                 if (sce->toolsettings->sculpt) {
549                         BKE_paint_free(&sce->toolsettings->sculpt->paint);
550                         MEM_freeN(sce->toolsettings->sculpt);
551                 }
552                 if (sce->toolsettings->uvsculpt) {
553                         BKE_paint_free(&sce->toolsettings->uvsculpt->paint);
554                         MEM_freeN(sce->toolsettings->uvsculpt);
555                 }
556                 BKE_paint_free(&sce->toolsettings->imapaint.paint);
557                 
558                 /* free Grease Pencil Drawing Brushes */
559                 BKE_gpencil_free_brushes(&sce->toolsettings->gp_brushes);
560                 BLI_freelistN(&sce->toolsettings->gp_brushes);
561                 
562                 /* free Grease Pencil interpolation curve */
563                 if (sce->toolsettings->gp_interpolate.custom_ipo) {
564                         curvemapping_free(sce->toolsettings->gp_interpolate.custom_ipo);
565                 }
566                 
567                 MEM_freeN(sce->toolsettings);
568                 sce->toolsettings = NULL;
569         }
570         
571         DAG_scene_free(sce);
572         if (sce->depsgraph)
573                 DEG_graph_free(sce->depsgraph);
574         
575         MEM_SAFE_FREE(sce->stats);
576         MEM_SAFE_FREE(sce->fps_info);
577
578         BKE_sound_destroy_scene(sce);
579
580         BKE_color_managed_view_settings_free(&sce->view_settings);
581
582         BKE_previewimg_free(&sce->preview);
583         curvemapping_free_data(&sce->r.mblur_shutter_curve);
584 }
585
586 void BKE_scene_init(Scene *sce)
587 {
588         ParticleEditSettings *pset;
589         int a;
590         const char *colorspace_name;
591         SceneRenderView *srv;
592         CurveMapping *mblur_shutter_curve;
593
594         BLI_assert(MEMCMP_STRUCT_OFS_IS_ZERO(sce, id));
595
596         sce->lay = sce->layact = 1;
597         
598         sce->r.mode = R_GAMMA | R_OSA | R_SHADOW | R_SSS | R_ENVMAP | R_RAYTRACE;
599         sce->r.cfra = 1;
600         sce->r.sfra = 1;
601         sce->r.efra = 250;
602         sce->r.frame_step = 1;
603         sce->r.xsch = 1920;
604         sce->r.ysch = 1080;
605         sce->r.xasp = 1;
606         sce->r.yasp = 1;
607         sce->r.tilex = 256;
608         sce->r.tiley = 256;
609         sce->r.mblur_samples = 1;
610         sce->r.filtertype = R_FILTER_MITCH;
611         sce->r.size = 50;
612
613         sce->r.im_format.planes = R_IMF_PLANES_RGBA;
614         sce->r.im_format.imtype = R_IMF_IMTYPE_PNG;
615         sce->r.im_format.depth = R_IMF_CHAN_DEPTH_8;
616         sce->r.im_format.quality = 90;
617         sce->r.im_format.compress = 15;
618
619         sce->r.displaymode = R_OUTPUT_AREA;
620         sce->r.framapto = 100;
621         sce->r.images = 100;
622         sce->r.framelen = 1.0;
623         sce->r.blurfac = 0.5;
624         sce->r.frs_sec = 24;
625         sce->r.frs_sec_base = 1;
626         sce->r.edgeint = 10;
627         sce->r.ocres = 128;
628
629         /* OCIO_TODO: for forwards compatibility only, so if no tonecurve are used,
630          *            images would look in the same way as in current blender
631          *
632          *            perhaps at some point should be completely deprecated?
633          */
634         sce->r.color_mgt_flag |= R_COLOR_MANAGEMENT;
635
636         sce->r.gauss = 1.0;
637         
638         /* deprecated but keep for upwards compat */
639         sce->r.postgamma = 1.0;
640         sce->r.posthue = 0.0;
641         sce->r.postsat = 1.0;
642
643         sce->r.bake_mode = 1;    /* prevent to include render stuff here */
644         sce->r.bake_filter = 16;
645         sce->r.bake_osa = 5;
646         sce->r.bake_flag = R_BAKE_CLEAR;
647         sce->r.bake_normal_space = R_BAKE_SPACE_TANGENT;
648         sce->r.bake_samples = 256;
649         sce->r.bake_biasdist = 0.001;
650
651         sce->r.bake.flag = R_BAKE_CLEAR;
652         sce->r.bake.pass_filter = R_BAKE_PASS_FILTER_ALL;
653         sce->r.bake.width = 512;
654         sce->r.bake.height = 512;
655         sce->r.bake.margin = 16;
656         sce->r.bake.normal_space = R_BAKE_SPACE_TANGENT;
657         sce->r.bake.normal_swizzle[0] = R_BAKE_POSX;
658         sce->r.bake.normal_swizzle[1] = R_BAKE_POSY;
659         sce->r.bake.normal_swizzle[2] = R_BAKE_POSZ;
660         BLI_strncpy(sce->r.bake.filepath, U.renderdir, sizeof(sce->r.bake.filepath));
661
662         sce->r.bake.im_format.planes = R_IMF_PLANES_RGBA;
663         sce->r.bake.im_format.imtype = R_IMF_IMTYPE_PNG;
664         sce->r.bake.im_format.depth = R_IMF_CHAN_DEPTH_8;
665         sce->r.bake.im_format.quality = 90;
666         sce->r.bake.im_format.compress = 15;
667
668         sce->r.scemode = R_DOCOMP | R_DOSEQ | R_EXTENSION;
669         sce->r.stamp = R_STAMP_TIME | R_STAMP_FRAME | R_STAMP_DATE | R_STAMP_CAMERA | R_STAMP_SCENE | R_STAMP_FILENAME | R_STAMP_RENDERTIME | R_STAMP_MEMORY;
670         sce->r.stamp_font_id = 12;
671         sce->r.fg_stamp[0] = sce->r.fg_stamp[1] = sce->r.fg_stamp[2] = 0.8f;
672         sce->r.fg_stamp[3] = 1.0f;
673         sce->r.bg_stamp[0] = sce->r.bg_stamp[1] = sce->r.bg_stamp[2] = 0.0f;
674         sce->r.bg_stamp[3] = 0.25f;
675         sce->r.raytrace_options = R_RAYTRACE_USE_INSTANCES;
676
677         sce->r.seq_prev_type = OB_SOLID;
678         sce->r.seq_rend_type = OB_SOLID;
679         sce->r.seq_flag = R_SEQ_GL_PREV;
680
681         sce->r.threads = 1;
682
683         sce->r.simplify_subsurf = 6;
684         sce->r.simplify_particles = 1.0f;
685         sce->r.simplify_shadowsamples = 16;
686         sce->r.simplify_aosss = 1.0f;
687
688         sce->r.border.xmin = 0.0f;
689         sce->r.border.ymin = 0.0f;
690         sce->r.border.xmax = 1.0f;
691         sce->r.border.ymax = 1.0f;
692
693         sce->r.preview_start_resolution = 64;
694         
695         sce->r.line_thickness_mode = R_LINE_THICKNESS_ABSOLUTE;
696         sce->r.unit_line_thickness = 1.0f;
697
698         mblur_shutter_curve = &sce->r.mblur_shutter_curve;
699         curvemapping_set_defaults(mblur_shutter_curve, 1, 0.0f, 0.0f, 1.0f, 1.0f);
700         curvemapping_initialize(mblur_shutter_curve);
701         curvemap_reset(mblur_shutter_curve->cm,
702                        &mblur_shutter_curve->clipr,
703                        CURVE_PRESET_MAX,
704                        CURVEMAP_SLOPE_POS_NEG);
705
706         sce->toolsettings = MEM_callocN(sizeof(struct ToolSettings), "Tool Settings Struct");
707         sce->toolsettings->doublimit = 0.001;
708         sce->toolsettings->vgroup_weight = 1.0f;
709         sce->toolsettings->uvcalc_margin = 0.001f;
710         sce->toolsettings->unwrapper = 1;
711         sce->toolsettings->select_thresh = 0.01f;
712
713         sce->toolsettings->selectmode = SCE_SELECT_VERTEX;
714         sce->toolsettings->uv_selectmode = UV_SELECT_VERTEX;
715         sce->toolsettings->normalsize = 0.1;
716         sce->toolsettings->autokey_mode = U.autokey_mode;
717
718         sce->toolsettings->snap_node_mode = SCE_SNAP_MODE_GRID;
719
720         sce->toolsettings->skgen_resolution = 100;
721         sce->toolsettings->skgen_threshold_internal     = 0.01f;
722         sce->toolsettings->skgen_threshold_external     = 0.01f;
723         sce->toolsettings->skgen_angle_limit            = 45.0f;
724         sce->toolsettings->skgen_length_ratio           = 1.3f;
725         sce->toolsettings->skgen_length_limit           = 1.5f;
726         sce->toolsettings->skgen_correlation_limit      = 0.98f;
727         sce->toolsettings->skgen_symmetry_limit         = 0.1f;
728         sce->toolsettings->skgen_postpro = SKGEN_SMOOTH;
729         sce->toolsettings->skgen_postpro_passes = 1;
730         sce->toolsettings->skgen_options = SKGEN_FILTER_INTERNAL | SKGEN_FILTER_EXTERNAL | SKGEN_FILTER_SMART | SKGEN_HARMONIC | SKGEN_SUB_CORRELATION | SKGEN_STICK_TO_EMBEDDING;
731         sce->toolsettings->skgen_subdivisions[0] = SKGEN_SUB_CORRELATION;
732         sce->toolsettings->skgen_subdivisions[1] = SKGEN_SUB_LENGTH;
733         sce->toolsettings->skgen_subdivisions[2] = SKGEN_SUB_ANGLE;
734
735         sce->toolsettings->curve_paint_settings.curve_type = CU_BEZIER;
736         sce->toolsettings->curve_paint_settings.flag |= CURVE_PAINT_FLAG_CORNERS_DETECT;
737         sce->toolsettings->curve_paint_settings.error_threshold = 8;
738         sce->toolsettings->curve_paint_settings.radius_max = 1.0f;
739         sce->toolsettings->curve_paint_settings.corner_angle = DEG2RADF(70.0f);
740
741         sce->toolsettings->statvis.overhang_axis = OB_NEGZ;
742         sce->toolsettings->statvis.overhang_min = 0;
743         sce->toolsettings->statvis.overhang_max = DEG2RADF(45.0f);
744         sce->toolsettings->statvis.thickness_max = 0.1f;
745         sce->toolsettings->statvis.thickness_samples = 1;
746         sce->toolsettings->statvis.distort_min = DEG2RADF(5.0f);
747         sce->toolsettings->statvis.distort_max = DEG2RADF(45.0f);
748
749         sce->toolsettings->statvis.sharp_min = DEG2RADF(90.0f);
750         sce->toolsettings->statvis.sharp_max = DEG2RADF(180.0f);
751
752         sce->toolsettings->proportional_size = 1.0f;
753
754         sce->toolsettings->imapaint.paint.flags |= PAINT_SHOW_BRUSH;
755         sce->toolsettings->imapaint.normal_angle = 80;
756         sce->toolsettings->imapaint.seam_bleed = 2;
757
758         sce->physics_settings.gravity[0] = 0.0f;
759         sce->physics_settings.gravity[1] = 0.0f;
760         sce->physics_settings.gravity[2] = -9.81f;
761         sce->physics_settings.flag = PHYS_GLOBAL_GRAVITY;
762
763         sce->unit.scale_length = 1.0f;
764
765         pset = &sce->toolsettings->particle;
766         pset->flag = PE_KEEP_LENGTHS | PE_LOCK_FIRST | PE_DEFLECT_EMITTER | PE_AUTO_VELOCITY;
767         pset->emitterdist = 0.25f;
768         pset->totrekey = 5;
769         pset->totaddkey = 5;
770         pset->brushtype = PE_BRUSH_NONE;
771         pset->draw_step = 2;
772         pset->fade_frames = 2;
773         pset->selectmode = SCE_SELECT_PATH;
774         for (a = 0; a < PE_TOT_BRUSH; a++) {
775                 pset->brush[a].strength = 0.5f;
776                 pset->brush[a].size = 50;
777                 pset->brush[a].step = 10;
778                 pset->brush[a].count = 10;
779         }
780         pset->brush[PE_BRUSH_CUT].strength = 1.0f;
781
782         sce->r.ffcodecdata.audio_mixrate = 48000;
783         sce->r.ffcodecdata.audio_volume = 1.0f;
784         sce->r.ffcodecdata.audio_bitrate = 192;
785         sce->r.ffcodecdata.audio_channels = 2;
786
787         BLI_strncpy(sce->r.engine, RE_engine_id_BLENDER_RENDER, sizeof(sce->r.engine));
788
789         sce->audio.distance_model = 2.0f;
790         sce->audio.doppler_factor = 1.0f;
791         sce->audio.speed_of_sound = 343.3f;
792         sce->audio.volume = 1.0f;
793
794         BLI_strncpy(sce->r.pic, U.renderdir, sizeof(sce->r.pic));
795
796         BLI_rctf_init(&sce->r.safety, 0.1f, 0.9f, 0.1f, 0.9f);
797         sce->r.osa = 8;
798
799         /* note; in header_info.c the scene copy happens..., if you add more to renderdata it has to be checked there */
800         BKE_scene_add_render_layer(sce, NULL);
801
802         /* multiview - stereo */
803         BKE_scene_add_render_view(sce, STEREO_LEFT_NAME);
804         srv = sce->r.views.first;
805         BLI_strncpy(srv->suffix, STEREO_LEFT_SUFFIX, sizeof(srv->suffix));
806
807         BKE_scene_add_render_view(sce, STEREO_RIGHT_NAME);
808         srv = sce->r.views.last;
809         BLI_strncpy(srv->suffix, STEREO_RIGHT_SUFFIX, sizeof(srv->suffix));
810
811         /* game data */
812         sce->gm.stereoflag = STEREO_NOSTEREO;
813         sce->gm.stereomode = STEREO_ANAGLYPH;
814         sce->gm.eyeseparation = 0.10;
815
816         sce->gm.dome.angle = 180;
817         sce->gm.dome.mode = DOME_FISHEYE;
818         sce->gm.dome.res = 4;
819         sce->gm.dome.resbuf = 1.0f;
820         sce->gm.dome.tilt = 0;
821
822         sce->gm.xplay = 640;
823         sce->gm.yplay = 480;
824         sce->gm.freqplay = 60;
825         sce->gm.depth = 32;
826
827         sce->gm.gravity = 9.8f;
828         sce->gm.physicsEngine = WOPHY_BULLET;
829         sce->gm.mode = 32; //XXX ugly harcoding, still not sure we should drop mode. 32 == 1 << 5 == use_occlusion_culling 
830         sce->gm.occlusionRes = 128;
831         sce->gm.ticrate = 60;
832         sce->gm.maxlogicstep = 5;
833         sce->gm.physubstep = 1;
834         sce->gm.maxphystep = 5;
835         sce->gm.lineardeactthreshold = 0.8f;
836         sce->gm.angulardeactthreshold = 1.0f;
837         sce->gm.deactivationtime = 0.0f;
838
839         sce->gm.flag = GAME_DISPLAY_LISTS;
840         sce->gm.matmode = GAME_MAT_MULTITEX;
841
842         sce->gm.obstacleSimulation = OBSTSIMULATION_NONE;
843         sce->gm.levelHeight = 2.f;
844
845         sce->gm.recastData.cellsize = 0.3f;
846         sce->gm.recastData.cellheight = 0.2f;
847         sce->gm.recastData.agentmaxslope = M_PI_4;
848         sce->gm.recastData.agentmaxclimb = 0.9f;
849         sce->gm.recastData.agentheight = 2.0f;
850         sce->gm.recastData.agentradius = 0.6f;
851         sce->gm.recastData.edgemaxlen = 12.0f;
852         sce->gm.recastData.edgemaxerror = 1.3f;
853         sce->gm.recastData.regionminsize = 8.f;
854         sce->gm.recastData.regionmergesize = 20.f;
855         sce->gm.recastData.vertsperpoly = 6;
856         sce->gm.recastData.detailsampledist = 6.0f;
857         sce->gm.recastData.detailsamplemaxerror = 1.0f;
858
859         sce->gm.lodflag = SCE_LOD_USE_HYST;
860         sce->gm.scehysteresis = 10;
861
862         sce->gm.exitkey = 218; // Blender key code for ESC
863
864         BKE_sound_create_scene(sce);
865
866         /* color management */
867         colorspace_name = IMB_colormanagement_role_colorspace_name_get(COLOR_ROLE_DEFAULT_SEQUENCER);
868
869         BKE_color_managed_display_settings_init(&sce->display_settings);
870         BKE_color_managed_view_settings_init(&sce->view_settings);
871         BLI_strncpy(sce->sequencer_colorspace_settings.name, colorspace_name,
872                     sizeof(sce->sequencer_colorspace_settings.name));
873
874         /* Safe Areas */
875         copy_v2_fl2(sce->safe_areas.title, 3.5f / 100.0f, 3.5f / 100.0f);
876         copy_v2_fl2(sce->safe_areas.action, 10.0f / 100.0f, 5.0f / 100.0f);
877         copy_v2_fl2(sce->safe_areas.title_center, 17.5f / 100.0f, 5.0f / 100.0f);
878         copy_v2_fl2(sce->safe_areas.action_center, 15.0f / 100.0f, 5.0f / 100.0f);
879
880         sce->preview = NULL;
881         
882         /* GP Sculpt brushes */
883         {
884                 GP_BrushEdit_Settings *gset = &sce->toolsettings->gp_sculpt;
885                 GP_EditBrush_Data *gp_brush;
886                 
887                 gp_brush = &gset->brush[GP_EDITBRUSH_TYPE_SMOOTH];
888                 gp_brush->size = 25;
889                 gp_brush->strength = 0.3f;
890                 gp_brush->flag = GP_EDITBRUSH_FLAG_USE_FALLOFF | GP_EDITBRUSH_FLAG_SMOOTH_PRESSURE;
891                 
892                 gp_brush = &gset->brush[GP_EDITBRUSH_TYPE_THICKNESS];
893                 gp_brush->size = 25;
894                 gp_brush->strength = 0.5f;
895                 gp_brush->flag = GP_EDITBRUSH_FLAG_USE_FALLOFF;
896                 
897                 gp_brush = &gset->brush[GP_EDITBRUSH_TYPE_STRENGTH];
898                 gp_brush->size = 25;
899                 gp_brush->strength = 0.5f;
900                 gp_brush->flag = GP_EDITBRUSH_FLAG_USE_FALLOFF;
901
902                 gp_brush = &gset->brush[GP_EDITBRUSH_TYPE_GRAB];
903                 gp_brush->size = 50;
904                 gp_brush->strength = 0.3f;
905                 gp_brush->flag = GP_EDITBRUSH_FLAG_USE_FALLOFF;
906                 
907                 gp_brush = &gset->brush[GP_EDITBRUSH_TYPE_PUSH];
908                 gp_brush->size = 25;
909                 gp_brush->strength = 0.3f;
910                 gp_brush->flag = GP_EDITBRUSH_FLAG_USE_FALLOFF;
911                 
912                 gp_brush = &gset->brush[GP_EDITBRUSH_TYPE_TWIST];
913                 gp_brush->size = 50;
914                 gp_brush->strength = 0.3f; // XXX?
915                 gp_brush->flag = GP_EDITBRUSH_FLAG_USE_FALLOFF;
916                 
917                 gp_brush = &gset->brush[GP_EDITBRUSH_TYPE_PINCH];
918                 gp_brush->size = 50;
919                 gp_brush->strength = 0.5f; // XXX?
920                 gp_brush->flag = GP_EDITBRUSH_FLAG_USE_FALLOFF;
921                 
922                 gp_brush = &gset->brush[GP_EDITBRUSH_TYPE_RANDOMIZE];
923                 gp_brush->size = 25;
924                 gp_brush->strength = 0.5f;
925                 gp_brush->flag = GP_EDITBRUSH_FLAG_USE_FALLOFF;
926         }
927         
928         /* GP Stroke Placement */
929         sce->toolsettings->gpencil_v3d_align = GP_PROJECT_VIEWSPACE;
930         sce->toolsettings->gpencil_v2d_align = GP_PROJECT_VIEWSPACE;
931         sce->toolsettings->gpencil_seq_align = GP_PROJECT_VIEWSPACE;
932         sce->toolsettings->gpencil_ima_align = GP_PROJECT_VIEWSPACE;
933 }
934
935 Scene *BKE_scene_add(Main *bmain, const char *name)
936 {
937         Scene *sce;
938
939         sce = BKE_libblock_alloc(bmain, ID_SCE, name, 0);
940         id_us_min(&sce->id);
941         id_us_ensure_real(&sce->id);
942
943         BKE_scene_init(sce);
944
945         return sce;
946 }
947
948 Base *BKE_scene_base_find_by_name(struct Scene *scene, const char *name)
949 {
950         Base *base;
951
952         for (base = scene->base.first; base; base = base->next) {
953                 if (STREQ(base->object->id.name + 2, name)) {
954                         break;
955                 }
956         }
957
958         return base;
959 }
960
961 Base *BKE_scene_base_find(Scene *scene, Object *ob)
962 {
963         return BLI_findptr(&scene->base, ob, offsetof(Base, object));
964 }
965
966 /**
967  * Sets the active scene, mainly used when running in background mode (``--scene`` command line argument).
968  * This is also called to set the scene directly, bypassing windowing code.
969  * Otherwise #ED_screen_set_scene is used when changing scenes by the user.
970  */
971 void BKE_scene_set_background(Main *bmain, Scene *scene)
972 {
973         Scene *sce;
974         Base *base;
975         Object *ob;
976         Group *group;
977         GroupObject *go;
978         int flag;
979         
980         /* check for cyclic sets, for reading old files but also for definite security (py?) */
981         BKE_scene_validate_setscene(bmain, scene);
982         
983         /* can happen when switching modes in other scenes */
984         if (scene->obedit && !(scene->obedit->mode & OB_MODE_EDIT))
985                 scene->obedit = NULL;
986
987         /* deselect objects (for dataselect) */
988         for (ob = bmain->object.first; ob; ob = ob->id.next)
989                 ob->flag &= ~(SELECT | OB_FROMGROUP);
990
991         /* group flags again */
992         for (group = bmain->group.first; group; group = group->id.next) {
993                 for (go = group->gobject.first; go; go = go->next) {
994                         if (go->ob) {
995                                 go->ob->flag |= OB_FROMGROUP;
996                         }
997                 }
998         }
999
1000         /* sort baselist for scene and sets */
1001         for (sce = scene; sce; sce = sce->set)
1002                 DAG_scene_relations_rebuild(bmain, sce);
1003
1004         /* copy layers and flags from bases to objects */
1005         for (base = scene->base.first; base; base = base->next) {
1006                 ob = base->object;
1007                 ob->lay = base->lay;
1008                 
1009                 /* group patch... */
1010                 base->flag &= ~(OB_FROMGROUP);
1011                 flag = ob->flag & (OB_FROMGROUP);
1012                 base->flag |= flag;
1013                 
1014                 /* not too nice... for recovering objects with lost data */
1015                 //if (ob->pose == NULL) base->flag &= ~OB_POSEMODE;
1016                 ob->flag = base->flag;
1017         }
1018         /* no full animation update, this to enable render code to work (render code calls own animation updates) */
1019 }
1020
1021 /* called from creator_args.c */
1022 Scene *BKE_scene_set_name(Main *bmain, const char *name)
1023 {
1024         Scene *sce = (Scene *)BKE_libblock_find_name_ex(bmain, ID_SCE, name);
1025         if (sce) {
1026                 BKE_scene_set_background(bmain, sce);
1027                 printf("Scene switch for render: '%s' in file: '%s'\n", name, bmain->name);
1028                 return sce;
1029         }
1030
1031         printf("Can't find scene: '%s' in file: '%s'\n", name, bmain->name);
1032         return NULL;
1033 }
1034
1035 /* Used by metaballs, return *all* objects (including duplis) existing in the scene (including scene's sets) */
1036 int BKE_scene_base_iter_next(EvaluationContext *eval_ctx, SceneBaseIter *iter,
1037                              Scene **scene, int val, Base **base, Object **ob)
1038 {
1039         bool run_again = true;
1040         
1041         /* init */
1042         if (val == 0) {
1043                 iter->phase = F_START;
1044                 iter->dupob = NULL;
1045                 iter->duplilist = NULL;
1046                 iter->dupli_refob = NULL;
1047         }
1048         else {
1049                 /* run_again is set when a duplilist has been ended */
1050                 while (run_again) {
1051                         run_again = false;
1052
1053                         /* the first base */
1054                         if (iter->phase == F_START) {
1055                                 *base = (*scene)->base.first;
1056                                 if (*base) {
1057                                         *ob = (*base)->object;
1058                                         iter->phase = F_SCENE;
1059                                 }
1060                                 else {
1061                                         /* exception: empty scene */
1062                                         while ((*scene)->set) {
1063                                                 (*scene) = (*scene)->set;
1064                                                 if ((*scene)->base.first) {
1065                                                         *base = (*scene)->base.first;
1066                                                         *ob = (*base)->object;
1067                                                         iter->phase = F_SCENE;
1068                                                         break;
1069                                                 }
1070                                         }
1071                                 }
1072                         }
1073                         else {
1074                                 if (*base && iter->phase != F_DUPLI) {
1075                                         *base = (*base)->next;
1076                                         if (*base) {
1077                                                 *ob = (*base)->object;
1078                                         }
1079                                         else {
1080                                                 if (iter->phase == F_SCENE) {
1081                                                         /* (*scene) is finished, now do the set */
1082                                                         while ((*scene)->set) {
1083                                                                 (*scene) = (*scene)->set;
1084                                                                 if ((*scene)->base.first) {
1085                                                                         *base = (*scene)->base.first;
1086                                                                         *ob = (*base)->object;
1087                                                                         break;
1088                                                                 }
1089                                                         }
1090                                                 }
1091                                         }
1092                                 }
1093                         }
1094                         
1095                         if (*base == NULL) {
1096                                 iter->phase = F_START;
1097                         }
1098                         else {
1099                                 if (iter->phase != F_DUPLI) {
1100                                         if ( (*base)->object->transflag & OB_DUPLI) {
1101                                                 /* groups cannot be duplicated for mballs yet, 
1102                                                  * this enters eternal loop because of 
1103                                                  * makeDispListMBall getting called inside of group_duplilist */
1104                                                 if ((*base)->object->dup_group == NULL) {
1105                                                         iter->duplilist = object_duplilist_ex(eval_ctx, (*scene), (*base)->object, false);
1106                                                         
1107                                                         iter->dupob = iter->duplilist->first;
1108
1109                                                         if (!iter->dupob) {
1110                                                                 free_object_duplilist(iter->duplilist);
1111                                                                 iter->duplilist = NULL;
1112                                                         }
1113                                                         iter->dupli_refob = NULL;
1114                                                 }
1115                                         }
1116                                 }
1117                                 /* handle dupli's */
1118                                 if (iter->dupob) {
1119                                         (*base)->flag |= OB_FROMDUPLI;
1120                                         *ob = iter->dupob->ob;
1121                                         iter->phase = F_DUPLI;
1122
1123                                         if (iter->dupli_refob != *ob) {
1124                                                 if (iter->dupli_refob) {
1125                                                         /* Restore previous object's real matrix. */
1126                                                         copy_m4_m4(iter->dupli_refob->obmat, iter->omat);
1127                                                 }
1128                                                 /* Backup new object's real matrix. */
1129                                                 iter->dupli_refob = *ob;
1130                                                 copy_m4_m4(iter->omat, iter->dupli_refob->obmat);
1131                                         }
1132                                         copy_m4_m4((*ob)->obmat, iter->dupob->mat);
1133
1134                                         iter->dupob = iter->dupob->next;
1135                                 }
1136                                 else if (iter->phase == F_DUPLI) {
1137                                         iter->phase = F_SCENE;
1138                                         (*base)->flag &= ~OB_FROMDUPLI;
1139                                         
1140                                         if (iter->dupli_refob) {
1141                                                 /* Restore last object's real matrix. */
1142                                                 copy_m4_m4(iter->dupli_refob->obmat, iter->omat);
1143                                                 iter->dupli_refob = NULL;
1144                                         }
1145                                         
1146                                         free_object_duplilist(iter->duplilist);
1147                                         iter->duplilist = NULL;
1148                                         run_again = true;
1149                                 }
1150                         }
1151                 }
1152         }
1153
1154 #if 0
1155         if (ob && *ob) {
1156                 printf("Scene: '%s', '%s'\n", (*scene)->id.name + 2, (*ob)->id.name + 2);
1157         }
1158 #endif
1159
1160         return iter->phase;
1161 }
1162
1163 Object *BKE_scene_camera_find(Scene *sc)
1164 {
1165         Base *base;
1166         
1167         for (base = sc->base.first; base; base = base->next)
1168                 if (base->object->type == OB_CAMERA)
1169                         return base->object;
1170
1171         return NULL;
1172 }
1173
1174 #ifdef DURIAN_CAMERA_SWITCH
1175 Object *BKE_scene_camera_switch_find(Scene *scene)
1176 {
1177         TimeMarker *m;
1178         int cfra = scene->r.cfra;
1179         int frame = -(MAXFRAME + 1);
1180         int min_frame = MAXFRAME + 1;
1181         Object *camera = NULL;
1182         Object *first_camera = NULL;
1183
1184         for (m = scene->markers.first; m; m = m->next) {
1185                 if (m->camera && (m->camera->restrictflag & OB_RESTRICT_RENDER) == 0) {
1186                         if ((m->frame <= cfra) && (m->frame > frame)) {
1187                                 camera = m->camera;
1188                                 frame = m->frame;
1189
1190                                 if (frame == cfra)
1191                                         break;
1192                         }
1193
1194                         if (m->frame < min_frame) {
1195                                 first_camera = m->camera;
1196                                 min_frame = m->frame;
1197                         }
1198                 }
1199         }
1200
1201         if (camera == NULL) {
1202                 /* If there's no marker to the left of current frame,
1203                  * use camera from left-most marker to solve all sort
1204                  * of Schrodinger uncertainties.
1205                  */
1206                 return first_camera;
1207         }
1208
1209         return camera;
1210 }
1211 #endif
1212
1213 int BKE_scene_camera_switch_update(Scene *scene)
1214 {
1215 #ifdef DURIAN_CAMERA_SWITCH
1216         Object *camera = BKE_scene_camera_switch_find(scene);
1217         if (camera) {
1218                 scene->camera = camera;
1219                 return 1;
1220         }
1221 #else
1222         (void)scene;
1223 #endif
1224         return 0;
1225 }
1226
1227 char *BKE_scene_find_marker_name(Scene *scene, int frame)
1228 {
1229         ListBase *markers = &scene->markers;
1230         TimeMarker *m1, *m2;
1231
1232         /* search through markers for match */
1233         for (m1 = markers->first, m2 = markers->last; m1 && m2; m1 = m1->next, m2 = m2->prev) {
1234                 if (m1->frame == frame)
1235                         return m1->name;
1236
1237                 if (m1 == m2)
1238                         break;
1239
1240                 if (m2->frame == frame)
1241                         return m2->name;
1242         }
1243
1244         return NULL;
1245 }
1246
1247 /* return the current marker for this frame,
1248  * we can have more than 1 marker per frame, this just returns the first :/ */
1249 char *BKE_scene_find_last_marker_name(Scene *scene, int frame)
1250 {
1251         TimeMarker *marker, *best_marker = NULL;
1252         int best_frame = -MAXFRAME * 2;
1253         for (marker = scene->markers.first; marker; marker = marker->next) {
1254                 if (marker->frame == frame) {
1255                         return marker->name;
1256                 }
1257
1258                 if (marker->frame > best_frame && marker->frame < frame) {
1259                         best_marker = marker;
1260                         best_frame = marker->frame;
1261                 }
1262         }
1263
1264         return best_marker ? best_marker->name : NULL;
1265 }
1266
1267
1268 Base *BKE_scene_base_add(Scene *sce, Object *ob)
1269 {
1270         Base *b = MEM_callocN(sizeof(*b), __func__);
1271         BLI_addhead(&sce->base, b);
1272
1273         b->object = ob;
1274         b->flag = ob->flag;
1275         b->lay = ob->lay;
1276
1277         return b;
1278 }
1279
1280 void BKE_scene_base_unlink(Scene *sce, Base *base)
1281 {
1282         /* remove rigid body constraint from world before removing object */
1283         if (base->object->rigidbody_constraint)
1284                 BKE_rigidbody_remove_constraint(sce, base->object);
1285         /* remove rigid body object from world before removing object */
1286         if (base->object->rigidbody_object)
1287                 BKE_rigidbody_remove_object(sce, base->object);
1288         
1289         BLI_remlink(&sce->base, base);
1290         if (sce->basact == base)
1291                 sce->basact = NULL;
1292 }
1293
1294 void BKE_scene_base_deselect_all(Scene *sce)
1295 {
1296         Base *b;
1297
1298         for (b = sce->base.first; b; b = b->next) {
1299                 b->flag &= ~SELECT;
1300                 b->object->flag = b->flag;
1301         }
1302 }
1303
1304 void BKE_scene_base_select(Scene *sce, Base *selbase)
1305 {
1306         selbase->flag |= SELECT;
1307         selbase->object->flag = selbase->flag;
1308
1309         sce->basact = selbase;
1310 }
1311
1312 /* checks for cycle, returns 1 if it's all OK */
1313 bool BKE_scene_validate_setscene(Main *bmain, Scene *sce)
1314 {
1315         Scene *sce_iter;
1316         int a, totscene;
1317
1318         if (sce->set == NULL) return true;
1319         totscene = BLI_listbase_count(&bmain->scene);
1320         
1321         for (a = 0, sce_iter = sce; sce_iter->set; sce_iter = sce_iter->set, a++) {
1322                 /* more iterations than scenes means we have a cycle */
1323                 if (a > totscene) {
1324                         /* the tested scene gets zero'ed, that's typically current scene */
1325                         sce->set = NULL;
1326                         return false;
1327                 }
1328         }
1329
1330         return true;
1331 }
1332
1333 /* This function is needed to cope with fractional frames - including two Blender rendering features
1334  * mblur (motion blur that renders 'subframes' and blurs them together), and fields rendering. 
1335  */
1336 float BKE_scene_frame_get(const Scene *scene)
1337 {
1338         return BKE_scene_frame_get_from_ctime(scene, scene->r.cfra);
1339 }
1340
1341 /* This function is used to obtain arbitrary fractional frames */
1342 float BKE_scene_frame_get_from_ctime(const Scene *scene, const float frame)
1343 {
1344         float ctime = frame;
1345         ctime += scene->r.subframe;
1346         ctime *= scene->r.framelen;
1347         
1348         return ctime;
1349 }
1350
1351 /**
1352  * Sets the frame int/float components.
1353  */
1354 void BKE_scene_frame_set(struct Scene *scene, double cfra)
1355 {
1356         double intpart;
1357         scene->r.subframe = modf(cfra, &intpart);
1358         scene->r.cfra = (int)intpart;
1359 }
1360
1361 #ifdef WITH_LEGACY_DEPSGRAPH
1362 /* drivers support/hacks 
1363  *  - this method is called from scene_update_tagged_recursive(), so gets included in viewport + render
1364  *      - these are always run since the depsgraph can't handle non-object data
1365  *      - these happen after objects are all done so that we can read in their final transform values,
1366  *        though this means that objects can't refer to scene info for guidance...
1367  */
1368 static void scene_update_drivers(Main *UNUSED(bmain), Scene *scene)
1369 {
1370         SceneRenderLayer *srl;
1371         float ctime = BKE_scene_frame_get(scene);
1372         
1373         /* scene itself */
1374         if (scene->adt && scene->adt->drivers.first) {
1375                 BKE_animsys_evaluate_animdata(scene, &scene->id, scene->adt, ctime, ADT_RECALC_DRIVERS);
1376         }
1377
1378         /* world */
1379         /* TODO: what about world textures? but then those have nodes too... */
1380         if (scene->world) {
1381                 ID *wid = (ID *)scene->world;
1382                 AnimData *adt = BKE_animdata_from_id(wid);
1383                 
1384                 if (adt && adt->drivers.first)
1385                         BKE_animsys_evaluate_animdata(scene, wid, adt, ctime, ADT_RECALC_DRIVERS);
1386         }
1387         
1388         /* nodes */
1389         if (scene->nodetree) {
1390                 ID *nid = (ID *)scene->nodetree;
1391                 AnimData *adt = BKE_animdata_from_id(nid);
1392                 
1393                 if (adt && adt->drivers.first)
1394                         BKE_animsys_evaluate_animdata(scene, nid, adt, ctime, ADT_RECALC_DRIVERS);
1395         }
1396
1397         /* world nodes */
1398         if (scene->world && scene->world->nodetree) {
1399                 ID *nid = (ID *)scene->world->nodetree;
1400                 AnimData *adt = BKE_animdata_from_id(nid);
1401                 
1402                 if (adt && adt->drivers.first)
1403                         BKE_animsys_evaluate_animdata(scene, nid, adt, ctime, ADT_RECALC_DRIVERS);
1404         }
1405
1406         /* freestyle */
1407         for (srl = scene->r.layers.first; srl; srl = srl->next) {
1408                 FreestyleConfig *config = &srl->freestyleConfig;
1409                 FreestyleLineSet *lineset;
1410
1411                 for (lineset = config->linesets.first; lineset; lineset = lineset->next) {
1412                         if (lineset->linestyle) {
1413                                 ID *lid = &lineset->linestyle->id;
1414                                 AnimData *adt = BKE_animdata_from_id(lid);
1415
1416                                 if (adt && adt->drivers.first)
1417                                         BKE_animsys_evaluate_animdata(scene, lid, adt, ctime, ADT_RECALC_DRIVERS);
1418                         }
1419                 }
1420         }
1421 }
1422
1423 /* deps hack - do extra recalcs at end */
1424 static void scene_depsgraph_hack(EvaluationContext *eval_ctx, Scene *scene, Scene *scene_parent)
1425 {
1426         Base *base;
1427                 
1428         scene->customdata_mask = scene_parent->customdata_mask;
1429         
1430         /* sets first, we allow per definition current scene to have
1431          * dependencies on sets, but not the other way around. */
1432         if (scene->set)
1433                 scene_depsgraph_hack(eval_ctx, scene->set, scene_parent);
1434         
1435         for (base = scene->base.first; base; base = base->next) {
1436                 Object *ob = base->object;
1437                 
1438                 if (ob->depsflag) {
1439                         int recalc = 0;
1440                         // printf("depshack %s\n", ob->id.name + 2);
1441                         
1442                         if (ob->depsflag & OB_DEPS_EXTRA_OB_RECALC)
1443                                 recalc |= OB_RECALC_OB;
1444                         if (ob->depsflag & OB_DEPS_EXTRA_DATA_RECALC)
1445                                 recalc |= OB_RECALC_DATA;
1446                         
1447                         ob->recalc |= recalc;
1448                         BKE_object_handle_update(eval_ctx, scene_parent, ob);
1449                         
1450                         if (ob->dup_group && (ob->transflag & OB_DUPLIGROUP)) {
1451                                 GroupObject *go;
1452                                 
1453                                 for (go = ob->dup_group->gobject.first; go; go = go->next) {
1454                                         if (go->ob)
1455                                                 go->ob->recalc |= recalc;
1456                                 }
1457                                 BKE_group_handle_recalc_and_update(eval_ctx, scene_parent, ob, ob->dup_group);
1458                         }
1459                 }
1460         }
1461 }
1462 #endif  /* WITH_LEGACY_DEPSGRAPH */
1463
1464 /* That's like really a bummer, because currently animation data for armatures
1465  * might want to use pose, and pose might be missing on the object.
1466  * This happens when changing visible layers, which leads to situations when
1467  * pose is missing or marked for recalc, animation will change it and then
1468  * object update will restore the pose.
1469  *
1470  * This could be solved by the new dependency graph, but for until then we'll
1471  * do an extra pass on the objects to ensure it's all fine.
1472  */
1473 #define POSE_ANIMATION_WORKAROUND
1474
1475 #ifdef POSE_ANIMATION_WORKAROUND
1476 static void scene_armature_depsgraph_workaround(Main *bmain)
1477 {
1478         Object *ob;
1479         if (BLI_listbase_is_empty(&bmain->armature) || !DAG_id_type_tagged(bmain, ID_OB)) {
1480                 return;
1481         }
1482         for (ob = bmain->object.first; ob; ob = ob->id.next) {
1483                 if (ob->type == OB_ARMATURE && ob->adt && ob->adt->recalc & ADT_RECALC_ANIM) {
1484                         if (ob->pose == NULL || (ob->pose->flag & POSE_RECALC)) {
1485                                 BKE_pose_rebuild(ob, ob->data);
1486                         }
1487                 }
1488         }
1489 }
1490 #endif
1491
1492 #ifdef WITH_LEGACY_DEPSGRAPH
1493 static void scene_rebuild_rbw_recursive(Scene *scene, float ctime)
1494 {
1495         if (scene->set)
1496                 scene_rebuild_rbw_recursive(scene->set, ctime);
1497
1498         if (BKE_scene_check_rigidbody_active(scene))
1499                 BKE_rigidbody_rebuild_world(scene, ctime);
1500 }
1501
1502 static void scene_do_rb_simulation_recursive(Scene *scene, float ctime)
1503 {
1504         if (scene->set)
1505                 scene_do_rb_simulation_recursive(scene->set, ctime);
1506
1507         if (BKE_scene_check_rigidbody_active(scene))
1508                 BKE_rigidbody_do_simulation(scene, ctime);
1509 }
1510 #endif
1511
1512 /* Used to visualize CPU threads activity during threaded object update,
1513  * would pollute STDERR with whole bunch of timing information which then
1514  * could be parsed and nicely visualized.
1515  */
1516 #ifdef WITH_LEGACY_DEPSGRAPH
1517 #  undef DETAILED_ANALYSIS_OUTPUT
1518 #else
1519 /* ALWAYS KEEY DISABLED! */
1520 #  undef DETAILED_ANALYSIS_OUTPUT
1521 #endif
1522
1523 /* Mballs evaluation uses BKE_scene_base_iter_next which calls
1524  * duplilist for all objects in the scene. This leads to conflict
1525  * accessing and writing same data from multiple threads.
1526  *
1527  * Ideally Mballs shouldn't do such an iteration and use DAG
1528  * queries instead. For the time being we've got new DAG
1529  * let's keep it simple and update mballs in a single thread.
1530  */
1531 #define MBALL_SINGLETHREAD_HACK
1532
1533 #ifdef WITH_LEGACY_DEPSGRAPH
1534 typedef struct StatisicsEntry {
1535         struct StatisicsEntry *next, *prev;
1536         Object *object;
1537         double start_time;
1538         double duration;
1539 } StatisicsEntry;
1540
1541 typedef struct ThreadedObjectUpdateState {
1542         /* TODO(sergey): We might want this to be per-thread object. */
1543         EvaluationContext *eval_ctx;
1544         Scene *scene;
1545         Scene *scene_parent;
1546         double base_time;
1547
1548 #ifdef MBALL_SINGLETHREAD_HACK
1549         bool has_mballs;
1550 #endif
1551
1552         /* Execution statistics */
1553         bool has_updated_objects;
1554         ListBase *statistics;
1555 } ThreadedObjectUpdateState;
1556
1557 static void scene_update_object_add_task(void *node, void *user_data);
1558
1559 static void scene_update_all_bases(EvaluationContext *eval_ctx, Scene *scene, Scene *scene_parent)
1560 {
1561         Base *base;
1562
1563         for (base = scene->base.first; base; base = base->next) {
1564                 Object *object = base->object;
1565
1566                 BKE_object_handle_update_ex(eval_ctx, scene_parent, object, scene->rigidbody_world, true);
1567
1568                 if (object->dup_group && (object->transflag & OB_DUPLIGROUP))
1569                         BKE_group_handle_recalc_and_update(eval_ctx, scene_parent, object, object->dup_group);
1570
1571                 /* always update layer, so that animating layers works (joshua july 2010) */
1572                 /* XXX commented out, this has depsgraph issues anyway - and this breaks setting scenes
1573                  * (on scene-set, the base-lay is copied to ob-lay (ton nov 2012) */
1574                 // base->lay = ob->lay;
1575         }
1576 }
1577
1578 static void scene_update_object_func(TaskPool * __restrict pool, void *taskdata, int threadid)
1579 {
1580 /* Disable print for now in favor of summary statistics at the end of update. */
1581 #define PRINT if (false) printf
1582
1583         ThreadedObjectUpdateState *state = (ThreadedObjectUpdateState *) BLI_task_pool_userdata(pool);
1584         void *node = taskdata;
1585         Object *object = DAG_get_node_object(node);
1586         EvaluationContext *eval_ctx = state->eval_ctx;
1587         Scene *scene = state->scene;
1588         Scene *scene_parent = state->scene_parent;
1589
1590 #ifdef MBALL_SINGLETHREAD_HACK
1591         if (object && object->type == OB_MBALL) {
1592                 state->has_mballs = true;
1593         }
1594         else
1595 #endif
1596         if (object) {
1597                 double start_time = 0.0;
1598                 bool add_to_stats = false;
1599
1600                 if (G.debug & G_DEBUG_DEPSGRAPH) {
1601                         if (object->recalc & OB_RECALC_ALL) {
1602                                 printf("Thread %d: update object %s\n", threadid, object->id.name);
1603                         }
1604
1605                         start_time = PIL_check_seconds_timer();
1606
1607                         if (object->recalc & OB_RECALC_ALL) {
1608                                 state->has_updated_objects = true;
1609                                 add_to_stats = true;
1610                         }
1611                 }
1612
1613                 /* We only update object itself here, dupli-group will be updated
1614                  * separately from main thread because of we've got no idea about
1615                  * dependencies inside the group.
1616                  */
1617                 BKE_object_handle_update_ex(eval_ctx, scene_parent, object, scene->rigidbody_world, false);
1618
1619                 /* Calculate statistics. */
1620                 if (add_to_stats) {
1621                         StatisicsEntry *entry;
1622
1623                         entry = MEM_mallocN(sizeof(StatisicsEntry), "update thread statistics");
1624                         entry->object = object;
1625                         entry->start_time = start_time;
1626                         entry->duration = PIL_check_seconds_timer() - start_time;
1627
1628                         BLI_addtail(&state->statistics[threadid], entry);
1629                 }
1630         }
1631         else {
1632                 PRINT("Threda %d: update node %s\n", threadid,
1633                       DAG_get_node_name(scene, node));
1634         }
1635
1636         /* Update will decrease child's valency and schedule child with zero valency. */
1637         DAG_threaded_update_handle_node_updated(node, scene_update_object_add_task, pool);
1638
1639 #undef PRINT
1640 }
1641
1642 static void scene_update_object_add_task(void *node, void *user_data)
1643 {
1644         TaskPool *task_pool = user_data;
1645
1646         BLI_task_pool_push(task_pool, scene_update_object_func, node, false, TASK_PRIORITY_LOW);
1647 }
1648
1649 static void print_threads_statistics(ThreadedObjectUpdateState *state)
1650 {
1651         int i, tot_thread;
1652         double finish_time;
1653
1654         if ((G.debug & G_DEBUG_DEPSGRAPH) == 0) {
1655                 return;
1656         }
1657
1658 #ifdef DETAILED_ANALYSIS_OUTPUT
1659         if (state->has_updated_objects) {
1660                 tot_thread = BLI_system_thread_count();
1661
1662                 fprintf(stderr, "objects update base time %f\n", state->base_time);
1663
1664                 for (i = 0; i < tot_thread; i++) {
1665                         StatisicsEntry *entry;
1666                         for (entry = state->statistics[i].first;
1667                              entry;
1668                              entry = entry->next)
1669                         {
1670                                 fprintf(stderr, "thread %d object %s start_time %f duration %f\n",
1671                                         i, entry->object->id.name + 2,
1672                                         entry->start_time, entry->duration);
1673                         }
1674                         BLI_freelistN(&state->statistics[i]);
1675                 }
1676         }
1677 #else
1678         finish_time = PIL_check_seconds_timer();
1679         tot_thread = BLI_system_thread_count();
1680         int total_objects = 0;
1681
1682         for (i = 0; i < tot_thread; i++) {
1683                 int thread_total_objects = 0;
1684                 double thread_total_time = 0.0;
1685                 StatisicsEntry *entry;
1686
1687                 if (state->has_updated_objects) {
1688                         /* Don't pollute output if no objects were updated. */
1689                         for (entry = state->statistics[i].first;
1690                              entry;
1691                              entry = entry->next)
1692                         {
1693                                 thread_total_objects++;
1694                                 thread_total_time += entry->duration;
1695                         }
1696
1697                         printf("Thread %d: total %d objects in %f sec.\n",
1698                                i,
1699                                thread_total_objects,
1700                                thread_total_time);
1701
1702                         for (entry = state->statistics[i].first;
1703                              entry;
1704                              entry = entry->next)
1705                         {
1706                                 printf("  %s in %f sec\n", entry->object->id.name + 2, entry->duration);
1707                         }
1708
1709                         total_objects += thread_total_objects;
1710                 }
1711
1712                 BLI_freelistN(&state->statistics[i]);
1713         }
1714         if (state->has_updated_objects) {
1715                 printf("Scene updated %d objects in %f sec\n",
1716                        total_objects,
1717                        finish_time - state->base_time);
1718         }
1719 #endif
1720 }
1721
1722 static bool scene_need_update_objects(Main *bmain)
1723 {
1724         return
1725                 /* Object datablocks themselves (for OB_RECALC_OB) */
1726                 DAG_id_type_tagged(bmain, ID_OB) ||
1727
1728                 /* Objects data datablocks (for OB_RECALC_DATA) */
1729                 DAG_id_type_tagged(bmain, ID_ME)  ||  /* Mesh */
1730                 DAG_id_type_tagged(bmain, ID_CU)  ||  /* Curve */
1731                 DAG_id_type_tagged(bmain, ID_MB)  ||  /* MetaBall */
1732                 DAG_id_type_tagged(bmain, ID_LA)  ||  /* Lamp */
1733                 DAG_id_type_tagged(bmain, ID_LT)  ||  /* Lattice */
1734                 DAG_id_type_tagged(bmain, ID_CA)  ||  /* Camera */
1735                 DAG_id_type_tagged(bmain, ID_KE)  ||  /* KE */
1736                 DAG_id_type_tagged(bmain, ID_SPK) ||  /* Speaker */
1737                 DAG_id_type_tagged(bmain, ID_AR);     /* Armature */
1738 }
1739
1740 static void scene_update_objects(EvaluationContext *eval_ctx, Main *bmain, Scene *scene, Scene *scene_parent)
1741 {
1742         TaskScheduler *task_scheduler;
1743         TaskPool *task_pool;
1744         ThreadedObjectUpdateState state;
1745         bool need_singlethread_pass;
1746         bool need_free_scheduler;
1747
1748         /* Early check for whether we need to invoke all the task-based
1749          * things (spawn new ppol, traverse dependency graph and so on).
1750          *
1751          * Basically if there's no ID datablocks tagged for update which
1752          * corresponds to object->recalc flags (which are checked in
1753          * BKE_object_handle_update() then we do nothing here.
1754          */
1755         if (!scene_need_update_objects(bmain)) {
1756                 return;
1757         }
1758
1759         state.eval_ctx = eval_ctx;
1760         state.scene = scene;
1761         state.scene_parent = scene_parent;
1762
1763         if (G.debug & G_DEBUG_DEPSGRAPH_NO_THREADS) {
1764                 task_scheduler = BLI_task_scheduler_create(1);
1765                 need_free_scheduler = true;
1766         }
1767         else {
1768                 task_scheduler = BLI_task_scheduler_get();
1769                 need_free_scheduler = false;
1770         }
1771
1772         /* Those are only needed when blender is run with --debug argument. */
1773         if (G.debug & G_DEBUG_DEPSGRAPH) {
1774                 const int tot_thread = BLI_task_scheduler_num_threads(task_scheduler);
1775                 state.statistics = MEM_callocN(tot_thread * sizeof(*state.statistics),
1776                                                "scene update objects stats");
1777                 state.has_updated_objects = false;
1778                 state.base_time = PIL_check_seconds_timer();
1779         }
1780
1781 #ifdef MBALL_SINGLETHREAD_HACK
1782         state.has_mballs = false;
1783 #endif
1784
1785         task_pool = BLI_task_pool_create(task_scheduler, &state);
1786
1787         DAG_threaded_update_begin(scene, scene_update_object_add_task, task_pool);
1788         BLI_task_pool_work_and_wait(task_pool);
1789         BLI_task_pool_free(task_pool);
1790
1791         if (G.debug & G_DEBUG_DEPSGRAPH) {
1792                 print_threads_statistics(&state);
1793                 MEM_freeN(state.statistics);
1794         }
1795
1796         /* We do single thread pass to update all the objects which are in cyclic dependency.
1797          * Such objects can not be handled by a generic DAG traverse and it's really tricky
1798          * to detect whether cycle could be solved or not.
1799          *
1800          * In this situation we simply update all remaining objects in a single thread and
1801          * it'll happen in the same exact order as it was in single-threaded DAG.
1802          *
1803          * We couldn't use threaded update for objects which are in cycle because they might
1804          * access data of each other which is being re-evaluated.
1805          *
1806          * Also, as was explained above, for now we also update all the mballs in single thread.
1807          *
1808          *                                                                   - sergey -
1809          */
1810         need_singlethread_pass = DAG_is_acyclic(scene) == false;
1811 #ifdef MBALL_SINGLETHREAD_HACK
1812         need_singlethread_pass |= state.has_mballs;
1813 #endif
1814
1815         if (need_singlethread_pass) {
1816                 scene_update_all_bases(eval_ctx, scene, scene_parent);
1817         }
1818
1819         if (need_free_scheduler) {
1820                 BLI_task_scheduler_free(task_scheduler);
1821         }
1822 }
1823
1824 static void scene_update_tagged_recursive(EvaluationContext *eval_ctx, Main *bmain, Scene *scene, Scene *scene_parent)
1825 {
1826         scene->customdata_mask = scene_parent->customdata_mask;
1827
1828         /* sets first, we allow per definition current scene to have
1829          * dependencies on sets, but not the other way around. */
1830         if (scene->set)
1831                 scene_update_tagged_recursive(eval_ctx, bmain, scene->set, scene_parent);
1832
1833         /* scene objects */
1834         scene_update_objects(eval_ctx, bmain, scene, scene_parent);
1835
1836         /* scene drivers... */
1837         scene_update_drivers(bmain, scene);
1838
1839         /* update masking curves */
1840         BKE_mask_update_scene(bmain, scene);
1841         
1842 }
1843 #endif  /* WITH_LEGACY_DEPSGRAPH */
1844
1845 static bool check_rendered_viewport_visible(Main *bmain)
1846 {
1847         wmWindowManager *wm = bmain->wm.first;
1848         wmWindow *window;
1849         for (window = wm->windows.first; window != NULL; window = window->next) {
1850                 bScreen *screen = window->screen;
1851                 ScrArea *area;
1852                 for (area = screen->areabase.first; area != NULL; area = area->next) {
1853                         View3D *v3d = area->spacedata.first;
1854                         if (area->spacetype != SPACE_VIEW3D) {
1855                                 continue;
1856                         }
1857                         if (v3d->drawtype == OB_RENDER) {
1858                                 return true;
1859                         }
1860                 }
1861         }
1862         return false;
1863 }
1864
1865 static void prepare_mesh_for_viewport_render(Main *bmain, Scene *scene)
1866 {
1867         /* This is needed to prepare mesh to be used by the render
1868          * engine from the viewport rendering. We do loading here
1869          * so all the objects which shares the same mesh datablock
1870          * are nicely tagged for update and updated.
1871          *
1872          * This makes it so viewport render engine doesn't need to
1873          * call loading of the edit data for the mesh objects.
1874          */
1875
1876         Object *obedit = scene->obedit;
1877         if (obedit) {
1878                 Mesh *mesh = obedit->data;
1879                 if ((obedit->type == OB_MESH) &&
1880                     ((obedit->id.tag & LIB_TAG_ID_RECALC_ALL) ||
1881                      (mesh->id.tag & LIB_TAG_ID_RECALC_ALL)))
1882                 {
1883                         if (check_rendered_viewport_visible(bmain)) {
1884                                 BMesh *bm = mesh->edit_btmesh->bm;
1885                                 BM_mesh_bm_to_me(bm, mesh, (&(struct BMeshToMeshParams){0}));
1886                                 DAG_id_tag_update(&mesh->id, 0);
1887                         }
1888                 }
1889         }
1890 }
1891
1892 void BKE_scene_update_tagged(EvaluationContext *eval_ctx, Main *bmain, Scene *scene)
1893 {
1894         Scene *sce_iter;
1895 #ifdef WITH_LEGACY_DEPSGRAPH
1896         bool use_new_eval = !DEG_depsgraph_use_legacy();
1897 #endif
1898
1899         /* keep this first */
1900         BLI_callback_exec(bmain, &scene->id, BLI_CB_EVT_SCENE_UPDATE_PRE);
1901
1902         /* (re-)build dependency graph if needed */
1903         for (sce_iter = scene; sce_iter; sce_iter = sce_iter->set) {
1904                 DAG_scene_relations_update(bmain, sce_iter);
1905                 /* Uncomment this to check if graph was properly tagged for update. */
1906 #if 0
1907 #ifdef WITH_LEGACY_DEPSGRAPH
1908                 if (use_new_eval)
1909 #endif
1910                 {
1911                         DAG_scene_relations_validate(bmain, sce_iter);
1912                 }
1913 #endif
1914         }
1915
1916         /* flush editing data if needed */
1917         prepare_mesh_for_viewport_render(bmain, scene);
1918
1919         /* flush recalc flags to dependencies */
1920         DAG_ids_flush_tagged(bmain);
1921
1922         /* removed calls to quick_cache, see pointcache.c */
1923         
1924         /* clear "LIB_TAG_DOIT" flag from all materials, to prevent infinite recursion problems later
1925          * when trying to find materials with drivers that need evaluating [#32017] 
1926          */
1927         BKE_main_id_tag_idcode(bmain, ID_MA, LIB_TAG_DOIT, false);
1928         BKE_main_id_tag_idcode(bmain, ID_LA, LIB_TAG_DOIT, false);
1929
1930         /* update all objects: drivers, matrices, displists, etc. flags set
1931          * by depgraph or manual, no layer check here, gets correct flushed
1932          *
1933          * in the future this should handle updates for all datablocks, not
1934          * only objects and scenes. - brecht */
1935 #ifdef WITH_LEGACY_DEPSGRAPH
1936         if (!use_new_eval) {
1937                 scene_update_tagged_recursive(eval_ctx, bmain, scene, scene);
1938         }
1939         else
1940 #endif
1941         {
1942                 DEG_evaluate_on_refresh(eval_ctx, scene->depsgraph, scene);
1943                 /* TODO(sergey): This is to beocme a node in new depsgraph. */
1944                 BKE_mask_update_scene(bmain, scene);
1945         }
1946
1947         /* update sound system animation (TODO, move to depsgraph) */
1948         BKE_sound_update_scene(bmain, scene);
1949
1950         /* extra call here to recalc scene animation (for sequencer) */
1951         {
1952                 AnimData *adt = BKE_animdata_from_id(&scene->id);
1953                 float ctime = BKE_scene_frame_get(scene);
1954                 
1955                 if (adt && (adt->recalc & ADT_RECALC_ANIM))
1956                         BKE_animsys_evaluate_animdata(scene, &scene->id, adt, ctime, 0);
1957         }
1958
1959         /* Extra call here to recalc material animation.
1960          *
1961          * Need to do this so changing material settings from the graph/dopesheet
1962          * will update stuff in the viewport.
1963          */
1964 #ifdef WITH_LEGACY_DEPSGRAPH
1965         if (!use_new_eval && DAG_id_type_tagged(bmain, ID_MA)) {
1966                 Material *material;
1967                 float ctime = BKE_scene_frame_get(scene);
1968
1969                 for (material = bmain->mat.first;
1970                      material;
1971                      material = material->id.next)
1972                 {
1973                         AnimData *adt = BKE_animdata_from_id(&material->id);
1974                         if (adt && (adt->recalc & ADT_RECALC_ANIM))
1975                                 BKE_animsys_evaluate_animdata(scene, &material->id, adt, ctime, 0);
1976                 }
1977         }
1978
1979         /* Also do the same for node trees. */
1980         if (!use_new_eval && DAG_id_type_tagged(bmain, ID_NT)) {
1981                 float ctime = BKE_scene_frame_get(scene);
1982
1983                 FOREACH_NODETREE(bmain, ntree, id)
1984                 {
1985                         AnimData *adt = BKE_animdata_from_id(&ntree->id);
1986                         if (adt && (adt->recalc & ADT_RECALC_ANIM))
1987                                 BKE_animsys_evaluate_animdata(scene, &ntree->id, adt, ctime, 0);
1988                 }
1989                 FOREACH_NODETREE_END
1990         }
1991 #endif
1992
1993         /* notify editors and python about recalc */
1994         BLI_callback_exec(bmain, &scene->id, BLI_CB_EVT_SCENE_UPDATE_POST);
1995
1996         /* Inform editors about possible changes. */
1997         DAG_ids_check_recalc(bmain, scene, false);
1998
1999         /* clear recalc flags */
2000         DAG_ids_clear_recalc(bmain);
2001 }
2002
2003 /* applies changes right away, does all sets too */
2004 void BKE_scene_update_for_newframe(EvaluationContext *eval_ctx, Main *bmain, Scene *sce, unsigned int lay)
2005 {
2006         BKE_scene_update_for_newframe_ex(eval_ctx, bmain, sce, lay, false);
2007 }
2008
2009 void BKE_scene_update_for_newframe_ex(EvaluationContext *eval_ctx, Main *bmain, Scene *sce, unsigned int lay, bool do_invisible_flush)
2010 {
2011         float ctime = BKE_scene_frame_get(sce);
2012         Scene *sce_iter;
2013 #ifdef DETAILED_ANALYSIS_OUTPUT
2014         double start_time = PIL_check_seconds_timer();
2015 #endif
2016 #ifdef WITH_LEGACY_DEPSGRAPH
2017         bool use_new_eval = !DEG_depsgraph_use_legacy();
2018 #else
2019         /* TODO(sergey): Pass to evaluation routines instead of storing layer in the graph? */
2020         (void) do_invisible_flush;
2021 #endif
2022
2023         DAG_editors_update_pre(bmain, sce, true);
2024
2025         /* keep this first */
2026         BLI_callback_exec(bmain, &sce->id, BLI_CB_EVT_FRAME_CHANGE_PRE);
2027         BLI_callback_exec(bmain, &sce->id, BLI_CB_EVT_SCENE_UPDATE_PRE);
2028
2029         /* update animated image textures for particles, modifiers, gpu, etc,
2030          * call this at the start so modifiers with textures don't lag 1 frame */
2031         BKE_image_update_frame(bmain, sce->r.cfra);
2032         
2033 #ifdef WITH_LEGACY_DEPSGRAPH
2034         /* rebuild rigid body worlds before doing the actual frame update
2035          * this needs to be done on start frame but animation playback usually starts one frame later
2036          * we need to do it here to avoid rebuilding the world on every simulation change, which can be very expensive
2037          */
2038         if (!use_new_eval) {
2039                 scene_rebuild_rbw_recursive(sce, ctime);
2040         }
2041 #endif
2042         
2043         BKE_sound_set_cfra(sce->r.cfra);
2044         
2045         /* clear animation overrides */
2046         /* XXX TODO... */
2047
2048         for (sce_iter = sce; sce_iter; sce_iter = sce_iter->set)
2049                 DAG_scene_relations_update(bmain, sce_iter);
2050
2051 #ifdef WITH_LEGACY_DEPSGRAPH
2052         if (!use_new_eval) {
2053                 /* flush recalc flags to dependencies, if we were only changing a frame
2054                  * this would not be necessary, but if a user or a script has modified
2055                  * some datablock before BKE_scene_update_tagged was called, we need the flush */
2056                 DAG_ids_flush_tagged(bmain);
2057
2058                 /* Following 2 functions are recursive
2059                  * so don't call within 'scene_update_tagged_recursive' */
2060                 DAG_scene_update_flags(bmain, sce, lay, true, do_invisible_flush);   // only stuff that moves or needs display still
2061         }
2062 #endif
2063
2064         BKE_mask_evaluate_all_masks(bmain, ctime, true);
2065
2066         /* Update animated cache files for modifiers. */
2067         BKE_cachefile_update_frame(bmain, sce, ctime, (((double)sce->r.frs_sec) / (double)sce->r.frs_sec_base));
2068
2069 #ifdef POSE_ANIMATION_WORKAROUND
2070         scene_armature_depsgraph_workaround(bmain);
2071 #endif
2072
2073         /* All 'standard' (i.e. without any dependencies) animation is handled here,
2074          * with an 'local' to 'macro' order of evaluation. This should ensure that
2075          * settings stored nestled within a hierarchy (i.e. settings in a Texture block
2076          * can be overridden by settings from Scene, which owns the Texture through a hierarchy
2077          * such as Scene->World->MTex/Texture) can still get correctly overridden.
2078          */
2079 #ifdef WITH_LEGACY_DEPSGRAPH
2080         if (!use_new_eval) {
2081                 BKE_animsys_evaluate_all_animation(bmain, sce, ctime);
2082                 /*...done with recursive funcs */
2083         }
2084 #endif
2085
2086         /* clear "LIB_TAG_DOIT" flag from all materials, to prevent infinite recursion problems later
2087          * when trying to find materials with drivers that need evaluating [#32017] 
2088          */
2089         BKE_main_id_tag_idcode(bmain, ID_MA, LIB_TAG_DOIT, false);
2090         BKE_main_id_tag_idcode(bmain, ID_LA, LIB_TAG_DOIT, false);
2091
2092         /* run rigidbody sim */
2093         /* NOTE: current position is so that rigidbody sim affects other objects, might change in the future */
2094 #ifdef WITH_LEGACY_DEPSGRAPH
2095         if (!use_new_eval) {
2096                 scene_do_rb_simulation_recursive(sce, ctime);
2097         }
2098 #endif
2099         
2100         /* BKE_object_handle_update() on all objects, groups and sets */
2101 #ifdef WITH_LEGACY_DEPSGRAPH
2102         if (use_new_eval) {
2103                 DEG_evaluate_on_framechange(eval_ctx, bmain, sce->depsgraph, ctime, lay);
2104         }
2105         else {
2106                 scene_update_tagged_recursive(eval_ctx, bmain, sce, sce);
2107         }
2108 #else
2109         DEG_evaluate_on_framechange(eval_ctx, bmain, sce->depsgraph, ctime, lay);
2110 #endif
2111
2112         /* update sound system animation (TODO, move to depsgraph) */
2113         BKE_sound_update_scene(bmain, sce);
2114
2115 #ifdef WITH_LEGACY_DEPSGRAPH
2116         if (!use_new_eval) {
2117                 scene_depsgraph_hack(eval_ctx, sce, sce);
2118         }
2119 #endif
2120
2121         /* notify editors and python about recalc */
2122         BLI_callback_exec(bmain, &sce->id, BLI_CB_EVT_SCENE_UPDATE_POST);
2123         BLI_callback_exec(bmain, &sce->id, BLI_CB_EVT_FRAME_CHANGE_POST);
2124
2125         /* Inform editors about possible changes. */
2126         DAG_ids_check_recalc(bmain, sce, true);
2127
2128         /* clear recalc flags */
2129         DAG_ids_clear_recalc(bmain);
2130
2131 #ifdef DETAILED_ANALYSIS_OUTPUT
2132         fprintf(stderr, "frame update start_time %f duration %f\n", start_time, PIL_check_seconds_timer() - start_time);
2133 #endif
2134 }
2135
2136 /* return default layer, also used to patch old files */
2137 SceneRenderLayer *BKE_scene_add_render_layer(Scene *sce, const char *name)
2138 {
2139         SceneRenderLayer *srl;
2140
2141         if (!name)
2142                 name = DATA_("RenderLayer");
2143
2144         srl = MEM_callocN(sizeof(SceneRenderLayer), "new render layer");
2145         BLI_strncpy(srl->name, name, sizeof(srl->name));
2146         BLI_uniquename(&sce->r.layers, srl, DATA_("RenderLayer"), '.', offsetof(SceneRenderLayer, name), sizeof(srl->name));
2147         BLI_addtail(&sce->r.layers, srl);
2148
2149         /* note, this is also in render, pipeline.c, to make layer when scenedata doesnt have it */
2150         srl->lay = (1 << 20) - 1;
2151         srl->layflag = 0x7FFF;   /* solid ztra halo edge strand */
2152         srl->passflag = SCE_PASS_COMBINED | SCE_PASS_Z;
2153         srl->pass_alpha_threshold = 0.5f;
2154         BKE_freestyle_config_init(&srl->freestyleConfig);
2155
2156         return srl;
2157 }
2158
2159 bool BKE_scene_remove_render_layer(Main *bmain, Scene *scene, SceneRenderLayer *srl)
2160 {
2161         const int act = BLI_findindex(&scene->r.layers, srl);
2162         Scene *sce;
2163
2164         if (act == -1) {
2165                 return false;
2166         }
2167         else if ( (scene->r.layers.first == scene->r.layers.last) &&
2168                   (scene->r.layers.first == srl))
2169         {
2170                 /* ensure 1 layer is kept */
2171                 return false;
2172         }
2173
2174         BKE_freestyle_config_free(&srl->freestyleConfig);
2175
2176         if (srl->prop) {
2177                 IDP_FreeProperty(srl->prop);
2178                 MEM_freeN(srl->prop);
2179         }
2180
2181         BLI_remlink(&scene->r.layers, srl);
2182         MEM_freeN(srl);
2183
2184         scene->r.actlay = 0;
2185
2186         for (sce = bmain->scene.first; sce; sce = sce->id.next) {
2187                 if (sce->nodetree) {
2188                         bNode *node;
2189                         for (node = sce->nodetree->nodes.first; node; node = node->next) {
2190                                 if (node->type == CMP_NODE_R_LAYERS && (Scene *)node->id == scene) {
2191                                         if (node->custom1 == act)
2192                                                 node->custom1 = 0;
2193                                         else if (node->custom1 > act)
2194                                                 node->custom1--;
2195                                 }
2196                         }
2197                 }
2198         }
2199
2200         return true;
2201 }
2202
2203 /* return default view */
2204 SceneRenderView *BKE_scene_add_render_view(Scene *sce, const char *name)
2205 {
2206         SceneRenderView *srv;
2207
2208         if (!name)
2209                 name = DATA_("RenderView");
2210
2211         srv = MEM_callocN(sizeof(SceneRenderView), "new render view");
2212         BLI_strncpy(srv->name, name, sizeof(srv->name));
2213         BLI_uniquename(&sce->r.views, srv, DATA_("RenderView"), '.', offsetof(SceneRenderView, name), sizeof(srv->name));
2214         BLI_addtail(&sce->r.views, srv);
2215
2216         return srv;
2217 }
2218
2219 bool BKE_scene_remove_render_view(Scene *scene, SceneRenderView *srv)
2220 {
2221         const int act = BLI_findindex(&scene->r.views, srv);
2222
2223         if (act == -1) {
2224                 return false;
2225         }
2226         else if (scene->r.views.first == scene->r.views.last) {
2227                 /* ensure 1 view is kept */
2228                 return false;
2229         }
2230
2231         BLI_remlink(&scene->r.views, srv);
2232         MEM_freeN(srv);
2233
2234         scene->r.actview = 0;
2235
2236         return true;
2237 }
2238
2239 /* render simplification */
2240
2241 int get_render_subsurf_level(const RenderData *r, int lvl, bool for_render)
2242 {
2243         if (r->mode & R_SIMPLIFY) {
2244                 if (for_render)
2245                         return min_ii(r->simplify_subsurf_render, lvl);
2246                 else
2247                         return min_ii(r->simplify_subsurf, lvl);
2248         }
2249         else {
2250                 return lvl;
2251         }
2252 }
2253
2254 int get_render_child_particle_number(const RenderData *r, int num, bool for_render)
2255 {
2256         if (r->mode & R_SIMPLIFY) {
2257                 if (for_render)
2258                         return (int)(r->simplify_particles_render * num);
2259                 else
2260                         return (int)(r->simplify_particles * num);
2261         }
2262         else {
2263                 return num;
2264         }
2265 }
2266
2267 int get_render_shadow_samples(const RenderData *r, int samples)
2268 {
2269         if ((r->mode & R_SIMPLIFY) && samples > 0)
2270                 return min_ii(r->simplify_shadowsamples, samples);
2271         else
2272                 return samples;
2273 }
2274
2275 float get_render_aosss_error(const RenderData *r, float error)
2276 {
2277         if (r->mode & R_SIMPLIFY)
2278                 return ((1.0f - r->simplify_aosss) * 10.0f + 1.0f) * error;
2279         else
2280                 return error;
2281 }
2282
2283 /* helper function for the SETLOOPER macro */
2284 Base *_setlooper_base_step(Scene **sce_iter, Base *base)
2285 {
2286         if (base && base->next) {
2287                 /* common case, step to the next */
2288                 return base->next;
2289         }
2290         else if (base == NULL && (*sce_iter)->base.first) {
2291                 /* first time looping, return the scenes first base */
2292                 return (Base *)(*sce_iter)->base.first;
2293         }
2294         else {
2295                 /* reached the end, get the next base in the set */
2296                 while ((*sce_iter = (*sce_iter)->set)) {
2297                         base = (Base *)(*sce_iter)->base.first;
2298                         if (base) {
2299                                 return base;
2300                         }
2301                 }
2302         }
2303
2304         return NULL;
2305 }
2306
2307 bool BKE_scene_use_new_shading_nodes(const Scene *scene)
2308 {
2309         const RenderEngineType *type = RE_engines_find(scene->r.engine);
2310         return (type && type->flag & RE_USE_SHADING_NODES);
2311 }
2312
2313 bool BKE_scene_use_shading_nodes_custom(Scene *scene)
2314 {
2315         RenderEngineType *type = RE_engines_find(scene->r.engine);
2316         return (type && type->flag & RE_USE_SHADING_NODES_CUSTOM);
2317 }
2318
2319 bool BKE_scene_use_world_space_shading(Scene *scene)
2320 {
2321         const RenderEngineType *type = RE_engines_find(scene->r.engine);
2322         return ((scene->r.mode & R_USE_WS_SHADING) ||
2323                 (type && (type->flag & RE_USE_SHADING_NODES)));
2324 }
2325
2326 bool BKE_scene_use_spherical_stereo(Scene *scene)
2327 {
2328         RenderEngineType *type = RE_engines_find(scene->r.engine);
2329         return (type && type->flag & RE_USE_SPHERICAL_STEREO);
2330 }
2331
2332 bool BKE_scene_uses_blender_internal(const  Scene *scene)
2333 {
2334         return STREQ(scene->r.engine, RE_engine_id_BLENDER_RENDER);
2335 }
2336
2337 bool BKE_scene_uses_blender_game(const Scene *scene)
2338 {
2339         return STREQ(scene->r.engine, RE_engine_id_BLENDER_GAME);
2340 }
2341
2342 void BKE_scene_base_flag_to_objects(struct Scene *scene)
2343 {
2344         Base *base = scene->base.first;
2345
2346         while (base) {
2347                 base->object->flag = base->flag;
2348                 base = base->next;
2349         }
2350 }
2351
2352 void BKE_scene_base_flag_from_objects(struct Scene *scene)
2353 {
2354         Base *base = scene->base.first;
2355
2356         while (base) {
2357                 base->flag = base->object->flag;
2358                 base = base->next;
2359         }
2360 }
2361
2362 void BKE_scene_disable_color_management(Scene *scene)
2363 {
2364         ColorManagedDisplaySettings *display_settings = &scene->display_settings;
2365         ColorManagedViewSettings *view_settings = &scene->view_settings;
2366         const char *view;
2367         const char *none_display_name;
2368
2369         none_display_name = IMB_colormanagement_display_get_none_name();
2370
2371         BLI_strncpy(display_settings->display_device, none_display_name, sizeof(display_settings->display_device));
2372
2373         view = IMB_colormanagement_view_get_default_name(display_settings->display_device);
2374
2375         if (view) {
2376                 BLI_strncpy(view_settings->view_transform, view, sizeof(view_settings->view_transform));
2377         }
2378 }
2379
2380 bool BKE_scene_check_color_management_enabled(const Scene *scene)
2381 {
2382         return !STREQ(scene->display_settings.display_device, "None");
2383 }
2384
2385 bool BKE_scene_check_rigidbody_active(const Scene *scene)
2386 {
2387         return scene && scene->rigidbody_world && scene->rigidbody_world->group && !(scene->rigidbody_world->flag & RBW_FLAG_MUTED);
2388 }
2389
2390 int BKE_render_num_threads(const RenderData *rd)
2391 {
2392         int threads;
2393
2394         /* override set from command line? */
2395         threads = BLI_system_num_threads_override_get();
2396
2397         if (threads > 0)
2398                 return threads;
2399
2400         /* fixed number of threads specified in scene? */
2401         if (rd->mode & R_FIXED_THREADS)
2402                 threads = rd->threads;
2403         else
2404                 threads = BLI_system_thread_count();
2405         
2406         return max_ii(threads, 1);
2407 }
2408
2409 int BKE_scene_num_threads(const Scene *scene)
2410 {
2411         return BKE_render_num_threads(&scene->r);
2412 }
2413
2414 /* Apply the needed correction factor to value, based on unit_type (only length-related are affected currently)
2415  * and unit->scale_length.
2416  */
2417 double BKE_scene_unit_scale(const UnitSettings *unit, const int unit_type, double value)
2418 {
2419         if (unit->system == USER_UNIT_NONE) {
2420                 /* Never apply scale_length when not using a unit setting! */
2421                 return value;
2422         }
2423
2424         switch (unit_type) {
2425                 case B_UNIT_LENGTH:
2426                         return value * (double)unit->scale_length;
2427                 case B_UNIT_AREA:
2428                         return value * pow(unit->scale_length, 2);
2429                 case B_UNIT_VOLUME:
2430                         return value * pow(unit->scale_length, 3);
2431                 case B_UNIT_MASS:
2432                         return value * pow(unit->scale_length, 3);
2433                 case B_UNIT_CAMERA:  /* *Do not* use scene's unit scale for camera focal lens! See T42026. */
2434                 default:
2435                         return value;
2436         }
2437 }
2438
2439 /******************** multiview *************************/
2440
2441 int BKE_scene_multiview_num_views_get(const RenderData *rd)
2442 {
2443         SceneRenderView *srv;
2444         int totviews = 0;
2445
2446         if ((rd->scemode & R_MULTIVIEW) == 0)
2447                 return 1;
2448
2449         if (rd->views_format == SCE_VIEWS_FORMAT_STEREO_3D) {
2450                 srv = BLI_findstring(&rd->views, STEREO_LEFT_NAME, offsetof(SceneRenderView, name));
2451                 if ((srv && srv->viewflag & SCE_VIEW_DISABLE) == 0) {
2452                         totviews++;
2453                 }
2454
2455                 srv = BLI_findstring(&rd->views, STEREO_RIGHT_NAME, offsetof(SceneRenderView, name));
2456                 if ((srv && srv->viewflag & SCE_VIEW_DISABLE) == 0) {
2457                         totviews++;
2458                 }
2459         }
2460         else {
2461                 for (srv = rd->views.first; srv; srv = srv->next) {
2462                         if ((srv->viewflag & SCE_VIEW_DISABLE) == 0) {
2463                                 totviews++;
2464                         }
2465                 }
2466         }
2467         return totviews;
2468 }
2469
2470 bool BKE_scene_multiview_is_stereo3d(const RenderData *rd)
2471 {
2472         SceneRenderView *srv[2];
2473
2474         if ((rd->scemode & R_MULTIVIEW) == 0)
2475                 return false;
2476
2477         srv[0] = (SceneRenderView *)BLI_findstring(&rd->views, STEREO_LEFT_NAME, offsetof(SceneRenderView, name));
2478         srv[1] = (SceneRenderView *)BLI_findstring(&rd->views, STEREO_RIGHT_NAME, offsetof(SceneRenderView, name));
2479
2480         return (srv[0] && ((srv[0]->viewflag & SCE_VIEW_DISABLE) == 0) &&
2481                 srv[1] && ((srv[1]->viewflag & SCE_VIEW_DISABLE) == 0));
2482 }
2483
2484 /* return whether to render this SceneRenderView */
2485 bool BKE_scene_multiview_is_render_view_active(const RenderData *rd, const SceneRenderView *srv)
2486 {
2487         if (srv == NULL)
2488                 return false;
2489
2490         if ((rd->scemode & R_MULTIVIEW) == 0)
2491                 return false;
2492
2493         if ((srv->viewflag & SCE_VIEW_DISABLE))
2494                 return false;
2495
2496         if (rd->views_format == SCE_VIEWS_FORMAT_MULTIVIEW)
2497                 return true;
2498
2499         /* SCE_VIEWS_SETUP_BASIC */
2500         if (STREQ(srv->name, STEREO_LEFT_NAME) ||
2501             STREQ(srv->name, STEREO_RIGHT_NAME))
2502         {
2503                 return true;
2504         }
2505
2506         return false;
2507 }
2508
2509 /* return true if viewname is the first or if the name is NULL or not found */
2510 bool BKE_scene_multiview_is_render_view_first(const RenderData *rd, const char *viewname)
2511 {
2512         SceneRenderView *srv;
2513
2514         if ((rd->scemode & R_MULTIVIEW) == 0)
2515                 return true;
2516
2517         if ((!viewname) || (!viewname[0]))
2518                 return true;
2519
2520         for (srv = rd->views.first; srv; srv = srv->next) {
2521                 if (BKE_scene_multiview_is_render_view_active(rd, srv)) {
2522                         return STREQ(viewname, srv->name);
2523                 }
2524         }
2525
2526         return true;
2527 }
2528
2529 /* return true if viewname is the last or if the name is NULL or not found */
2530 bool BKE_scene_multiview_is_render_view_last(const RenderData *rd, const char *viewname)
2531 {
2532         SceneRenderView *srv;
2533
2534         if ((rd->scemode & R_MULTIVIEW) == 0)
2535                 return true;
2536
2537         if ((!viewname) || (!viewname[0]))
2538                 return true;
2539
2540         for (srv = rd->views.last; srv; srv = srv->prev) {
2541                 if (BKE_scene_multiview_is_render_view_active(rd, srv)) {
2542                         return STREQ(viewname, srv->name);
2543                 }
2544         }
2545
2546         return true;
2547 }
2548
2549 SceneRenderView *BKE_scene_multiview_render_view_findindex(const RenderData *rd, const int view_id)
2550 {
2551         SceneRenderView *srv;
2552         size_t nr;
2553
2554         if ((rd->scemode & R_MULTIVIEW) == 0)
2555                 return NULL;
2556
2557         for (srv = rd->views.first, nr = 0; srv; srv = srv->next) {
2558                 if (BKE_scene_multiview_is_render_view_active(rd, srv)) {
2559                         if (nr++ == view_id)
2560                                 return srv;
2561                 }
2562         }
2563         return srv;
2564 }
2565
2566 const char *BKE_scene_multiview_render_view_name_get(const RenderData *rd, const int view_id)
2567 {
2568         SceneRenderView *srv = BKE_scene_multiview_render_view_findindex(rd, view_id);
2569
2570         if (srv)
2571                 return srv->name;
2572         else
2573                 return "";
2574 }
2575
2576 int BKE_scene_multiview_view_id_get(const RenderData *rd, const char *viewname)
2577 {
2578         SceneRenderView *srv;
2579         size_t nr;
2580
2581         if ((!rd) || ((rd->scemode & R_MULTIVIEW) == 0))
2582                 return 0;
2583
2584         if ((!viewname) || (!viewname[0]))
2585                 return 0;
2586
2587         for (srv = rd->views.first, nr = 0; srv; srv = srv->next) {
2588                 if (BKE_scene_multiview_is_render_view_active(rd, srv)) {
2589                         if (STREQ(viewname, srv->name)) {
2590                                 return nr;
2591                         }
2592                         else {
2593                                 nr += 1;
2594                         }
2595                 }
2596         }
2597
2598         return 0;
2599 }
2600
2601 void BKE_scene_multiview_filepath_get(
2602         SceneRenderView *srv, const char *filepath,
2603         char *r_filepath)
2604 {
2605         BLI_strncpy(r_filepath, filepath, FILE_MAX);
2606         BLI_path_suffix(r_filepath, FILE_MAX, srv->suffix, "");
2607 }
2608
2609 /**
2610  * When multiview is not used the filepath is as usual (e.g., ``Image.jpg``).
2611  * When multiview is on, even if only one view is enabled the view is incorporated
2612  * into the file name (e.g., ``Image_L.jpg``). That allows for the user to re-render
2613  * individual views.
2614  */
2615 void BKE_scene_multiview_view_filepath_get(
2616         const RenderData *rd, const char *filepath, const char *viewname,
2617         char *r_filepath)
2618 {
2619         SceneRenderView *srv;
2620         char suffix[FILE_MAX];
2621
2622         srv = BLI_findstring(&rd->views, viewname, offsetof(SceneRenderView, name));
2623         if (srv)
2624                 BLI_strncpy(suffix, srv->suffix, sizeof(suffix));
2625         else
2626                 BLI_strncpy(suffix, viewname, sizeof(suffix));
2627
2628         BLI_strncpy(r_filepath, filepath, FILE_MAX);
2629         BLI_path_suffix(r_filepath, FILE_MAX, suffix, "");
2630 }
2631
2632 const char *BKE_scene_multiview_view_suffix_get(const RenderData *rd, const char *viewname)
2633 {
2634         SceneRenderView *srv;
2635
2636         if ((viewname == NULL) || (viewname[0] == '\0'))
2637                 return viewname;
2638
2639         srv = BLI_findstring(&rd->views, viewname, offsetof(SceneRenderView, name));
2640         if (srv)
2641                 return srv->suffix;
2642         else
2643                 return viewname;
2644 }
2645
2646 const char *BKE_scene_multiview_view_id_suffix_get(const RenderData *rd, const int view_id)
2647 {
2648         if ((rd->scemode & R_MULTIVIEW) == 0) {
2649                 return "";
2650         }
2651         else {
2652                 const char *viewname = BKE_scene_multiview_render_view_name_get(rd, view_id);
2653                 return BKE_scene_multiview_view_suffix_get(rd, viewname);
2654         }
2655 }
2656
2657 void BKE_scene_multiview_view_prefix_get(Scene *scene, const char *name, char *rprefix, const char **rext)
2658 {
2659         SceneRenderView *srv;
2660         size_t index_act;
2661         const char *suf_act;
2662         const char delims[] = {'.', '\0'};
2663
2664         rprefix[0] = '\0';
2665
2666         /* begin of extension */
2667         index_act = BLI_str_rpartition(name, delims, rext, &suf_act);
2668         if (*rext == NULL)
2669                 return;
2670         BLI_assert(index_act > 0);
2671         UNUSED_VARS_NDEBUG(index_act);
2672
2673         for (srv = scene->r.views.first; srv; srv = srv->next) {
2674                 if (BKE_scene_multiview_is_render_view_active(&scene->r, srv)) {
2675                         size_t len = strlen(srv->suffix);
2676                         if (strlen(*rext) >= len && STREQLEN(*rext - len, srv->suffix, len)) {
2677                                 BLI_strncpy(rprefix, name, strlen(name) - strlen(*rext) - len + 1);
2678                                 break;
2679                         }
2680                 }
2681         }
2682 }
2683
2684 void BKE_scene_multiview_videos_dimensions_get(
2685         const RenderData *rd, const size_t width, const size_t height,
2686         size_t *r_width, size_t *r_height)
2687 {
2688         if ((rd->scemode & R_MULTIVIEW) &&
2689             rd->im_format.views_format == R_IMF_VIEWS_STEREO_3D)
2690         {
2691                 IMB_stereo3d_write_dimensions(
2692                         rd->im_format.stereo3d_format.display_mode,
2693                         (rd->im_format.stereo3d_format.flag & S3D_SQUEEZED_FRAME) != 0,
2694                         width, height,
2695                         r_width, r_height);
2696         }
2697         else {
2698                 *r_width = width;
2699                 *r_height = height;
2700         }
2701 }
2702
2703 int BKE_scene_multiview_num_videos_get(const RenderData *rd)
2704 {
2705         if (BKE_imtype_is_movie(rd->im_format.imtype) == false)
2706                 return 0;
2707
2708         if ((rd->scemode & R_MULTIVIEW) == 0)
2709                 return 1;
2710
2711         if (rd->im_format.views_format == R_IMF_VIEWS_STEREO_3D) {
2712                 return 1;
2713         }
2714         else {
2715                 /* R_IMF_VIEWS_INDIVIDUAL */
2716                 return BKE_scene_multiview_num_views_get(rd);
2717         }
2718 }