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