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