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