Merge branch 'master' into blender2.8
[blender.git] / intern / cycles / blender / blender_sync.cpp
1 /*
2  * Copyright 2011-2013 Blender Foundation
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 #include "render/background.h"
18 #include "render/camera.h"
19 #include "render/film.h"
20 #include "render/graph.h"
21 #include "render/integrator.h"
22 #include "render/light.h"
23 #include "render/mesh.h"
24 #include "render/nodes.h"
25 #include "render/object.h"
26 #include "render/scene.h"
27 #include "render/shader.h"
28 #include "render/curves.h"
29
30 #include "device/device.h"
31
32 #include "blender/blender_sync.h"
33 #include "blender/blender_session.h"
34 #include "blender/blender_util.h"
35
36 #include "util/util_debug.h"
37 #include "util/util_foreach.h"
38 #include "util/util_opengl.h"
39 #include "util/util_hash.h"
40
41 CCL_NAMESPACE_BEGIN
42
43 static const char *cryptomatte_prefix = "Crypto";
44
45 /* Constructor */
46
47 BlenderSync::BlenderSync(BL::RenderEngine& b_engine,
48                          BL::BlendData& b_data,
49                          BL::Scene& b_scene,
50                          Scene *scene,
51                          bool preview,
52                          Progress &progress)
53 : b_engine(b_engine),
54   b_data(b_data),
55   b_scene(b_scene),
56   shader_map(&scene->shaders),
57   object_map(&scene->objects),
58   mesh_map(&scene->meshes),
59   light_map(&scene->lights),
60   particle_system_map(&scene->particle_systems),
61   world_map(NULL),
62   world_recalc(false),
63   scene(scene),
64   preview(preview),
65   experimental(false),
66   dicing_rate(1.0f),
67   max_subdivisions(12),
68   progress(progress)
69 {
70         PointerRNA cscene = RNA_pointer_get(&b_scene.ptr, "cycles");
71         dicing_rate = preview ? RNA_float_get(&cscene, "preview_dicing_rate") : RNA_float_get(&cscene, "dicing_rate");
72         max_subdivisions = RNA_int_get(&cscene, "max_subdivisions");
73 }
74
75 BlenderSync::~BlenderSync()
76 {
77 }
78
79 /* Sync */
80
81 void BlenderSync::sync_recalc(BL::Depsgraph& b_depsgraph)
82 {
83         /* Sync recalc flags from blender to cycles. Actual update is done separate,
84          * so we can do it later on if doing it immediate is not suitable. */
85
86         bool has_updated_objects = b_depsgraph.id_type_updated(BL::DriverTarget::id_type_OBJECT);
87         bool dicing_prop_changed = false;
88
89         if(experimental) {
90                 PointerRNA cscene = RNA_pointer_get(&b_scene.ptr, "cycles");
91
92                 float updated_dicing_rate = preview ? RNA_float_get(&cscene, "preview_dicing_rate")
93                                                     : RNA_float_get(&cscene, "dicing_rate");
94
95                 if(dicing_rate != updated_dicing_rate) {
96                         dicing_rate = updated_dicing_rate;
97                         dicing_prop_changed = true;
98                 }
99
100                 int updated_max_subdivisions = RNA_int_get(&cscene, "max_subdivisions");
101
102                 if(max_subdivisions != updated_max_subdivisions) {
103                         max_subdivisions = updated_max_subdivisions;
104                         dicing_prop_changed = true;
105                 }
106         }
107
108         /* Iterate over all IDs in this depsgraph. */
109         BL::Depsgraph::updates_iterator b_update;
110         for(b_depsgraph.updates.begin(b_update); b_update != b_depsgraph.updates.end(); ++b_update) {
111                 BL::ID b_id(b_update->id());
112
113                 /* Material */
114                 if(b_id.is_a(&RNA_Material)) {
115                         BL::Material b_mat(b_id);
116                         shader_map.set_recalc(b_mat);
117                 }
118                 /* Light */
119                 else if(b_id.is_a(&RNA_Light)) {
120                         BL::Light b_light(b_id);
121                         shader_map.set_recalc(b_light);
122                 }
123                 /* Object */
124                 else if(b_id.is_a(&RNA_Object)) {
125                         BL::Object b_ob(b_id);
126                         const bool updated_geometry = !b_update->is_dirty_geometry();
127
128                         if(!b_update->is_dirty_transform()) {
129                                 object_map.set_recalc(b_ob);
130                                 light_map.set_recalc(b_ob);
131                         }
132
133                         if(object_is_mesh(b_ob)) {
134                                 if(updated_geometry ||
135                                    (dicing_prop_changed && object_subdivision_type(b_ob, preview, experimental) != Mesh::SUBDIVISION_NONE))
136                                 {
137                                         BL::ID key = BKE_object_is_modified(b_ob)? b_ob: b_ob.data();
138                                         mesh_map.set_recalc(key);
139                                 }
140                         }
141                         else if(object_is_light(b_ob)) {
142                                 if(updated_geometry) {
143                                         light_map.set_recalc(b_ob);
144                                 }
145                         }
146
147                         if(updated_geometry) {
148                                 BL::Object::particle_systems_iterator b_psys;
149                                 for(b_ob.particle_systems.begin(b_psys); b_psys != b_ob.particle_systems.end(); ++b_psys)
150                                         particle_system_map.set_recalc(b_ob);
151                         }
152                 }
153                 /* Mesh */
154                 else if(b_id.is_a(&RNA_Mesh)) {
155                         BL::Mesh b_mesh(b_id);
156                         mesh_map.set_recalc(b_mesh);
157                 }
158                 /* World */
159                 else if(b_id.is_a(&RNA_World)) {
160                         BL::World b_world(b_id);
161                         if(world_map == b_world.ptr.data) {
162                                 world_recalc = true;
163                         }
164                 }
165         }
166
167         /* Updates shader with object dependency if objects changed. */
168         if(has_updated_objects) {
169                 if(scene->default_background->has_object_dependency) {
170                         world_recalc = true;
171                 }
172
173                 foreach(Shader *shader, scene->shaders) {
174                         if(shader->has_object_dependency) {
175                                 shader->need_sync_object = true;
176                         }
177                 }
178         }
179 }
180
181 void BlenderSync::sync_data(BL::RenderSettings& b_render,
182                             BL::Depsgraph& b_depsgraph,
183                             BL::SpaceView3D& b_v3d,
184                             BL::Object& b_override,
185                             int width, int height,
186                             void **python_thread_state)
187 {
188         BL::ViewLayer b_view_layer = b_depsgraph.view_layer_eval();
189
190         sync_view_layer(b_v3d, b_view_layer);
191         sync_integrator();
192         sync_film();
193         sync_shaders(b_depsgraph);
194         sync_images();
195         sync_curve_settings();
196
197         mesh_synced.clear(); /* use for objects and motion sync */
198
199         if(scene->need_motion() == Scene::MOTION_PASS ||
200            scene->need_motion() == Scene::MOTION_NONE ||
201            scene->camera->motion_position == Camera::MOTION_POSITION_CENTER)
202         {
203                 sync_objects(b_depsgraph);
204         }
205         sync_motion(b_render,
206                     b_depsgraph,
207                     b_override,
208                     width, height,
209                     python_thread_state);
210
211         mesh_synced.clear();
212
213         free_data_after_sync(b_depsgraph);
214 }
215
216 /* Integrator */
217
218 void BlenderSync::sync_integrator()
219 {
220         BL::RenderSettings r = b_scene.render();
221         PointerRNA cscene = RNA_pointer_get(&b_scene.ptr, "cycles");
222
223         experimental = (get_enum(cscene, "feature_set") != 0);
224
225         Integrator *integrator = scene->integrator;
226         Integrator previntegrator = *integrator;
227
228         integrator->max_bounce = get_int(cscene, "max_bounces");
229
230         integrator->max_diffuse_bounce = get_int(cscene, "diffuse_bounces");
231         integrator->max_glossy_bounce = get_int(cscene, "glossy_bounces");
232         integrator->max_transmission_bounce = get_int(cscene, "transmission_bounces");
233         integrator->max_volume_bounce = get_int(cscene, "volume_bounces");
234
235         integrator->transparent_max_bounce = get_int(cscene, "transparent_max_bounces");
236
237         integrator->volume_max_steps = get_int(cscene, "volume_max_steps");
238         integrator->volume_step_size = get_float(cscene, "volume_step_size");
239
240         integrator->caustics_reflective = get_boolean(cscene, "caustics_reflective");
241         integrator->caustics_refractive = get_boolean(cscene, "caustics_refractive");
242         integrator->filter_glossy = get_float(cscene, "blur_glossy");
243
244         integrator->seed = get_int(cscene, "seed");
245         if(get_boolean(cscene, "use_animated_seed")) {
246                 integrator->seed = hash_int_2d(b_scene.frame_current(),
247                                                get_int(cscene, "seed"));
248                 if(b_scene.frame_subframe() != 0.0f) {
249                         /* TODO(sergey): Ideally should be some sort of hash_merge,
250                          * but this is good enough for now.
251                          */
252                         integrator->seed += hash_int_2d((int)(b_scene.frame_subframe() * (float)INT_MAX),
253                                                         get_int(cscene, "seed"));
254                 }
255         }
256
257         integrator->sampling_pattern = (SamplingPattern)get_enum(
258                 cscene,
259                 "sampling_pattern",
260                 SAMPLING_NUM_PATTERNS,
261                 SAMPLING_PATTERN_SOBOL);
262
263         integrator->sample_clamp_direct = get_float(cscene, "sample_clamp_direct");
264         integrator->sample_clamp_indirect = get_float(cscene, "sample_clamp_indirect");
265         if(!preview) {
266                 if(integrator->motion_blur != r.use_motion_blur()) {
267                         scene->object_manager->tag_update(scene);
268                         scene->camera->tag_update();
269                 }
270
271                 integrator->motion_blur = r.use_motion_blur();
272         }
273
274         integrator->method = (Integrator::Method)get_enum(cscene,
275                                                           "progressive",
276                                                           Integrator::NUM_METHODS,
277                                                           Integrator::PATH);
278
279         integrator->sample_all_lights_direct = get_boolean(cscene, "sample_all_lights_direct");
280         integrator->sample_all_lights_indirect = get_boolean(cscene, "sample_all_lights_indirect");
281         integrator->light_sampling_threshold = get_float(cscene, "light_sampling_threshold");
282
283         int diffuse_samples = get_int(cscene, "diffuse_samples");
284         int glossy_samples = get_int(cscene, "glossy_samples");
285         int transmission_samples = get_int(cscene, "transmission_samples");
286         int ao_samples = get_int(cscene, "ao_samples");
287         int mesh_light_samples = get_int(cscene, "mesh_light_samples");
288         int subsurface_samples = get_int(cscene, "subsurface_samples");
289         int volume_samples = get_int(cscene, "volume_samples");
290
291         if(get_boolean(cscene, "use_square_samples")) {
292                 integrator->diffuse_samples = diffuse_samples * diffuse_samples;
293                 integrator->glossy_samples = glossy_samples * glossy_samples;
294                 integrator->transmission_samples = transmission_samples * transmission_samples;
295                 integrator->ao_samples = ao_samples * ao_samples;
296                 integrator->mesh_light_samples = mesh_light_samples * mesh_light_samples;
297                 integrator->subsurface_samples = subsurface_samples * subsurface_samples;
298                 integrator->volume_samples = volume_samples * volume_samples;
299         }
300         else {
301                 integrator->diffuse_samples = diffuse_samples;
302                 integrator->glossy_samples = glossy_samples;
303                 integrator->transmission_samples = transmission_samples;
304                 integrator->ao_samples = ao_samples;
305                 integrator->mesh_light_samples = mesh_light_samples;
306                 integrator->subsurface_samples = subsurface_samples;
307                 integrator->volume_samples = volume_samples;
308         }
309
310         if(b_scene.render().use_simplify()) {
311                 if(preview) {
312                         integrator->ao_bounces = get_int(cscene, "ao_bounces");
313                 }
314                 else {
315                         integrator->ao_bounces = get_int(cscene, "ao_bounces_render");
316                 }
317         }
318         else {
319                 integrator->ao_bounces = 0;
320         }
321
322         if(integrator->modified(previntegrator))
323                 integrator->tag_update(scene);
324 }
325
326 /* Film */
327
328 void BlenderSync::sync_film()
329 {
330         PointerRNA cscene = RNA_pointer_get(&b_scene.ptr, "cycles");
331
332         Film *film = scene->film;
333         Film prevfilm = *film;
334
335         film->exposure = get_float(cscene, "film_exposure");
336         film->filter_type = (FilterType)get_enum(cscene,
337                                                  "pixel_filter_type",
338                                                  FILTER_NUM_TYPES,
339                                                  FILTER_BLACKMAN_HARRIS);
340         film->filter_width = (film->filter_type == FILTER_BOX)? 1.0f: get_float(cscene, "filter_width");
341
342         if(b_scene.world()) {
343                 BL::WorldMistSettings b_mist = b_scene.world().mist_settings();
344
345                 film->mist_start = b_mist.start();
346                 film->mist_depth = b_mist.depth();
347
348                 switch(b_mist.falloff()) {
349                         case BL::WorldMistSettings::falloff_QUADRATIC:
350                                 film->mist_falloff = 2.0f;
351                                 break;
352                         case BL::WorldMistSettings::falloff_LINEAR:
353                                 film->mist_falloff = 1.0f;
354                                 break;
355                         case BL::WorldMistSettings::falloff_INVERSE_QUADRATIC:
356                                 film->mist_falloff = 0.5f;
357                                 break;
358                 }
359         }
360
361         if(film->modified(prevfilm))
362                 film->tag_update(scene);
363 }
364
365 /* Render Layer */
366
367 void BlenderSync::sync_view_layer(BL::SpaceView3D& /*b_v3d*/, BL::ViewLayer& b_view_layer)
368 {
369         /* render layer */
370         view_layer.name = b_view_layer.name();
371         view_layer.use_background_shader = b_view_layer.use_sky();
372         view_layer.use_background_ao = b_view_layer.use_ao();
373         view_layer.use_surfaces = b_view_layer.use_solid();
374         view_layer.use_hair = b_view_layer.use_strand();
375 }
376
377 /* Images */
378 void BlenderSync::sync_images()
379 {
380         /* Sync is a convention for this API, but currently it frees unused buffers. */
381
382         const bool is_interface_locked = b_engine.render() &&
383                                          b_engine.render().use_lock_interface();
384         if(is_interface_locked == false && BlenderSession::headless == false) {
385                 /* If interface is not locked, it's possible image is needed for
386                  * the display.
387                  */
388                 return;
389         }
390         /* Free buffers used by images which are not needed for render. */
391         BL::BlendData::images_iterator b_image;
392         for(b_data.images.begin(b_image);
393             b_image != b_data.images.end();
394             ++b_image)
395         {
396                 /* TODO(sergey): Consider making it an utility function to check
397                  * whether image is considered builtin.
398                  */
399                 const bool is_builtin = b_image->packed_file() ||
400                                         b_image->source() == BL::Image::source_GENERATED ||
401                                         b_image->source() == BL::Image::source_MOVIE ||
402                                         b_engine.is_preview();
403                 if(is_builtin == false) {
404                         b_image->buffers_free();
405                 }
406                 /* TODO(sergey): Free builtin images not used by any shader. */
407         }
408 }
409
410 /* Passes */
411 PassType BlenderSync::get_pass_type(BL::RenderPass& b_pass)
412 {
413         string name = b_pass.name();
414 #define MAP_PASS(passname, passtype) if(name == passname) return passtype;
415         /* NOTE: Keep in sync with defined names from DNA_scene_types.h */
416         MAP_PASS("Combined", PASS_COMBINED);
417         MAP_PASS("Depth", PASS_DEPTH);
418         MAP_PASS("Mist", PASS_MIST);
419         MAP_PASS("Normal", PASS_NORMAL);
420         MAP_PASS("IndexOB", PASS_OBJECT_ID);
421         MAP_PASS("UV", PASS_UV);
422         MAP_PASS("Vector", PASS_MOTION);
423         MAP_PASS("IndexMA", PASS_MATERIAL_ID);
424
425         MAP_PASS("DiffDir", PASS_DIFFUSE_DIRECT);
426         MAP_PASS("GlossDir", PASS_GLOSSY_DIRECT);
427         MAP_PASS("TransDir", PASS_TRANSMISSION_DIRECT);
428         MAP_PASS("SubsurfaceDir", PASS_SUBSURFACE_DIRECT);
429         MAP_PASS("VolumeDir", PASS_VOLUME_DIRECT);
430
431         MAP_PASS("DiffInd", PASS_DIFFUSE_INDIRECT);
432         MAP_PASS("GlossInd", PASS_GLOSSY_INDIRECT);
433         MAP_PASS("TransInd", PASS_TRANSMISSION_INDIRECT);
434         MAP_PASS("SubsurfaceInd", PASS_SUBSURFACE_INDIRECT);
435         MAP_PASS("VolumeInd", PASS_VOLUME_INDIRECT);
436
437         MAP_PASS("DiffCol", PASS_DIFFUSE_COLOR);
438         MAP_PASS("GlossCol", PASS_GLOSSY_COLOR);
439         MAP_PASS("TransCol", PASS_TRANSMISSION_COLOR);
440         MAP_PASS("SubsurfaceCol", PASS_SUBSURFACE_COLOR);
441
442         MAP_PASS("Emit", PASS_EMISSION);
443         MAP_PASS("Env", PASS_BACKGROUND);
444         MAP_PASS("AO", PASS_AO);
445         MAP_PASS("Shadow", PASS_SHADOW);
446
447 #ifdef __KERNEL_DEBUG__
448         MAP_PASS("Debug BVH Traversed Nodes", PASS_BVH_TRAVERSED_NODES);
449         MAP_PASS("Debug BVH Traversed Instances", PASS_BVH_TRAVERSED_INSTANCES);
450         MAP_PASS("Debug BVH Intersections", PASS_BVH_INTERSECTIONS);
451         MAP_PASS("Debug Ray Bounces", PASS_RAY_BOUNCES);
452 #endif
453         MAP_PASS("Debug Render Time", PASS_RENDER_TIME);
454         if(string_startswith(name, cryptomatte_prefix)) {
455                 return PASS_CRYPTOMATTE;
456         }
457 #undef MAP_PASS
458
459         return PASS_NONE;
460 }
461
462 int BlenderSync::get_denoising_pass(BL::RenderPass& b_pass)
463 {
464         string name = b_pass.name();
465
466         if(name == "Noisy Image") return DENOISING_PASS_COLOR;
467
468         if(name.substr(0, 10) != "Denoising ") {
469                 return -1;
470         }
471         name = name.substr(10);
472
473 #define MAP_PASS(passname, offset) if(name == passname) return offset;
474         MAP_PASS("Normal", DENOISING_PASS_NORMAL);
475         MAP_PASS("Normal Variance", DENOISING_PASS_NORMAL_VAR);
476         MAP_PASS("Albedo", DENOISING_PASS_ALBEDO);
477         MAP_PASS("Albedo Variance", DENOISING_PASS_ALBEDO_VAR);
478         MAP_PASS("Depth", DENOISING_PASS_DEPTH);
479         MAP_PASS("Depth Variance", DENOISING_PASS_DEPTH_VAR);
480         MAP_PASS("Shadow A", DENOISING_PASS_SHADOW_A);
481         MAP_PASS("Shadow B", DENOISING_PASS_SHADOW_B);
482         MAP_PASS("Image Variance", DENOISING_PASS_COLOR_VAR);
483         MAP_PASS("Clean", DENOISING_PASS_CLEAN);
484 #undef MAP_PASS
485
486         return -1;
487 }
488
489 vector<Pass> BlenderSync::sync_render_passes(BL::RenderLayer& b_rlay,
490                                              BL::ViewLayer& b_view_layer,
491                                              const SessionParams &session_params)
492 {
493         vector<Pass> passes;
494         Pass::add(PASS_COMBINED, passes);
495
496         if(!session_params.device.advanced_shading) {
497                 return passes;
498         }
499
500         /* loop over passes */
501         BL::RenderLayer::passes_iterator b_pass_iter;
502
503         for(b_rlay.passes.begin(b_pass_iter); b_pass_iter != b_rlay.passes.end(); ++b_pass_iter) {
504                 BL::RenderPass b_pass(*b_pass_iter);
505                 PassType pass_type = get_pass_type(b_pass);
506
507                 if(pass_type == PASS_MOTION && scene->integrator->motion_blur)
508                         continue;
509                 if(pass_type != PASS_NONE)
510                         Pass::add(pass_type, passes);
511         }
512
513         PointerRNA crp = RNA_pointer_get(&b_view_layer.ptr, "cycles");
514         bool use_denoising = get_boolean(crp, "use_denoising");
515         bool store_denoising_passes = get_boolean(crp, "denoising_store_passes");
516         scene->film->denoising_flags = 0;
517         if(use_denoising || store_denoising_passes) {
518 #define MAP_OPTION(name, flag) if(!get_boolean(crp, name)) scene->film->denoising_flags |= flag;
519                 MAP_OPTION("denoising_diffuse_direct",        DENOISING_CLEAN_DIFFUSE_DIR);
520                 MAP_OPTION("denoising_diffuse_indirect",      DENOISING_CLEAN_DIFFUSE_IND);
521                 MAP_OPTION("denoising_glossy_direct",         DENOISING_CLEAN_GLOSSY_DIR);
522                 MAP_OPTION("denoising_glossy_indirect",       DENOISING_CLEAN_GLOSSY_IND);
523                 MAP_OPTION("denoising_transmission_direct",   DENOISING_CLEAN_TRANSMISSION_DIR);
524                 MAP_OPTION("denoising_transmission_indirect", DENOISING_CLEAN_TRANSMISSION_IND);
525                 MAP_OPTION("denoising_subsurface_direct",     DENOISING_CLEAN_SUBSURFACE_DIR);
526                 MAP_OPTION("denoising_subsurface_indirect",   DENOISING_CLEAN_SUBSURFACE_IND);
527 #undef MAP_OPTION
528                 b_engine.add_pass("Noisy Image", 4, "RGBA", b_view_layer.name().c_str());
529         }
530
531         if(store_denoising_passes) {
532                 b_engine.add_pass("Denoising Normal",          3, "XYZ", b_view_layer.name().c_str());
533                 b_engine.add_pass("Denoising Normal Variance", 3, "XYZ", b_view_layer.name().c_str());
534                 b_engine.add_pass("Denoising Albedo",          3, "RGB", b_view_layer.name().c_str());
535                 b_engine.add_pass("Denoising Albedo Variance", 3, "RGB", b_view_layer.name().c_str());
536                 b_engine.add_pass("Denoising Depth",           1, "Z",   b_view_layer.name().c_str());
537                 b_engine.add_pass("Denoising Depth Variance",  1, "Z",   b_view_layer.name().c_str());
538                 b_engine.add_pass("Denoising Shadow A",        3, "XYV", b_view_layer.name().c_str());
539                 b_engine.add_pass("Denoising Shadow B",        3, "XYV", b_view_layer.name().c_str());
540                 b_engine.add_pass("Denoising Image Variance",  3, "RGB", b_view_layer.name().c_str());
541
542                 if(scene->film->denoising_flags & DENOISING_CLEAN_ALL_PASSES) {
543                         b_engine.add_pass("Denoising Clean",   3, "RGB", b_view_layer.name().c_str());
544                 }
545         }
546 #ifdef __KERNEL_DEBUG__
547         if(get_boolean(crp, "pass_debug_bvh_traversed_nodes")) {
548                 b_engine.add_pass("Debug BVH Traversed Nodes", 1, "X", b_view_layer.name().c_str());
549                 Pass::add(PASS_BVH_TRAVERSED_NODES, passes);
550         }
551         if(get_boolean(crp, "pass_debug_bvh_traversed_instances")) {
552                 b_engine.add_pass("Debug BVH Traversed Instances", 1, "X", b_view_layer.name().c_str());
553                 Pass::add(PASS_BVH_TRAVERSED_INSTANCES, passes);
554         }
555         if(get_boolean(crp, "pass_debug_bvh_intersections")) {
556                 b_engine.add_pass("Debug BVH Intersections", 1, "X", b_view_layer.name().c_str());
557                 Pass::add(PASS_BVH_INTERSECTIONS, passes);
558         }
559         if(get_boolean(crp, "pass_debug_ray_bounces")) {
560                 b_engine.add_pass("Debug Ray Bounces", 1, "X", b_view_layer.name().c_str());
561                 Pass::add(PASS_RAY_BOUNCES, passes);
562         }
563 #endif
564         if(get_boolean(crp, "pass_debug_render_time")) {
565                 b_engine.add_pass("Debug Render Time", 1, "X", b_view_layer.name().c_str());
566                 Pass::add(PASS_RENDER_TIME, passes);
567         }
568         if(get_boolean(crp, "use_pass_volume_direct")) {
569                 b_engine.add_pass("VolumeDir", 3, "RGB", b_view_layer.name().c_str());
570                 Pass::add(PASS_VOLUME_DIRECT, passes);
571         }
572         if(get_boolean(crp, "use_pass_volume_indirect")) {
573                 b_engine.add_pass("VolumeInd", 3, "RGB", b_view_layer.name().c_str());
574                 Pass::add(PASS_VOLUME_INDIRECT, passes);
575         }
576
577         /* Cryptomatte stores two ID/weight pairs per RGBA layer.
578          * User facing paramter is the number of pairs. */
579         int crypto_depth = min(16, get_int(crp, "pass_crypto_depth")) / 2;
580         scene->film->cryptomatte_depth = crypto_depth;
581         scene->film->cryptomatte_passes = CRYPT_NONE;
582         if(get_boolean(crp, "use_pass_crypto_object")) {
583                 for(int i = 0; i < crypto_depth; ++i) {
584                         string passname = cryptomatte_prefix + string_printf("Object%02d", i);
585                         b_engine.add_pass(passname.c_str(), 4, "RGBA", b_view_layer.name().c_str());
586                         Pass::add(PASS_CRYPTOMATTE, passes, passname.c_str());
587                 }
588                 scene->film->cryptomatte_passes = (CryptomatteType)(scene->film->cryptomatte_passes | CRYPT_OBJECT);
589         }
590         if(get_boolean(crp, "use_pass_crypto_material")) {
591                 for(int i = 0; i < crypto_depth; ++i) {
592                         string passname = cryptomatte_prefix + string_printf("Material%02d", i);
593                         b_engine.add_pass(passname.c_str(), 4, "RGBA", b_view_layer.name().c_str());
594                         Pass::add(PASS_CRYPTOMATTE, passes, passname.c_str());
595                 }
596                 scene->film->cryptomatte_passes = (CryptomatteType)(scene->film->cryptomatte_passes | CRYPT_MATERIAL);
597         }
598         if(get_boolean(crp, "use_pass_crypto_asset")) {
599                 for(int i = 0; i < crypto_depth; ++i) {
600                         string passname = cryptomatte_prefix + string_printf("Asset%02d", i);
601                         b_engine.add_pass(passname.c_str(), 4, "RGBA", b_view_layer.name().c_str());
602                         Pass::add(PASS_CRYPTOMATTE, passes, passname.c_str());
603                 }
604                 scene->film->cryptomatte_passes = (CryptomatteType)(scene->film->cryptomatte_passes | CRYPT_ASSET);
605         }
606         if(get_boolean(crp, "pass_crypto_accurate") && scene->film->cryptomatte_passes != CRYPT_NONE) {
607                 scene->film->cryptomatte_passes = (CryptomatteType)(scene->film->cryptomatte_passes | CRYPT_ACCURATE);
608         }
609
610         return passes;
611 }
612
613 void BlenderSync::free_data_after_sync(BL::Depsgraph& b_depsgraph)
614 {
615         /* When viewport display is not needed during render we can force some
616          * caches to be releases from blender side in order to reduce peak memory
617          * footprint during synchronization process.
618          */
619         const bool is_interface_locked = b_engine.render() &&
620                                          b_engine.render().use_lock_interface();
621         const bool can_free_caches = BlenderSession::headless || is_interface_locked;
622         if(!can_free_caches) {
623                 return;
624         }
625         /* TODO(sergey): We can actually remove the whole dependency graph,
626          * but that will need some API support first.
627          */
628         BL::Depsgraph::objects_iterator b_ob;
629         for(b_depsgraph.objects.begin(b_ob);
630             b_ob != b_depsgraph.objects.end();
631             ++b_ob)
632         {
633                 b_ob->cache_release();
634         }
635 }
636
637 /* Scene Parameters */
638
639 SceneParams BlenderSync::get_scene_params(BL::Scene& b_scene,
640                                           bool background)
641 {
642         BL::RenderSettings r = b_scene.render();
643         SceneParams params;
644         PointerRNA cscene = RNA_pointer_get(&b_scene.ptr, "cycles");
645         const bool shadingsystem = RNA_boolean_get(&cscene, "shading_system");
646
647         if(shadingsystem == 0)
648                 params.shadingsystem = SHADINGSYSTEM_SVM;
649         else if(shadingsystem == 1)
650                 params.shadingsystem = SHADINGSYSTEM_OSL;
651
652         if(background || DebugFlags().viewport_static_bvh)
653                 params.bvh_type = SceneParams::BVH_STATIC;
654         else
655                 params.bvh_type = SceneParams::BVH_DYNAMIC;
656
657         params.use_bvh_spatial_split = RNA_boolean_get(&cscene, "debug_use_spatial_splits");
658         params.use_bvh_unaligned_nodes = RNA_boolean_get(&cscene, "debug_use_hair_bvh");
659         params.num_bvh_time_steps = RNA_int_get(&cscene, "debug_bvh_time_steps");
660
661         if(background && params.shadingsystem != SHADINGSYSTEM_OSL)
662                 params.persistent_data = r.use_persistent_data();
663         else
664                 params.persistent_data = false;
665
666         int texture_limit;
667         if(background) {
668                 texture_limit = RNA_enum_get(&cscene, "texture_limit_render");
669         }
670         else {
671                 texture_limit = RNA_enum_get(&cscene, "texture_limit");
672         }
673         if(texture_limit > 0 && b_scene.render().use_simplify()) {
674                 params.texture_limit = 1 << (texture_limit + 6);
675         }
676         else {
677                 params.texture_limit = 0;
678         }
679
680         /* TODO(sergey): Once OSL supports per-microarchitecture optimization get
681          * rid of this.
682          */
683         if(params.shadingsystem == SHADINGSYSTEM_OSL) {
684                 params.bvh_layout = BVH_LAYOUT_BVH4;
685         }
686         else {
687                 params.bvh_layout = DebugFlags().cpu.bvh_layout;
688         }
689
690 #ifdef WITH_EMBREE
691         params.bvh_layout = RNA_boolean_get(&cscene, "use_bvh_embree") ? BVH_LAYOUT_EMBREE : params.bvh_layout;
692 #endif
693         return params;
694 }
695
696 /* Session Parameters */
697
698 bool BlenderSync::get_session_pause(BL::Scene& b_scene, bool background)
699 {
700         PointerRNA cscene = RNA_pointer_get(&b_scene.ptr, "cycles");
701         return (background)? false: get_boolean(cscene, "preview_pause");
702 }
703
704 SessionParams BlenderSync::get_session_params(BL::RenderEngine& b_engine,
705                                               BL::UserPreferences& b_userpref,
706                                               BL::Scene& b_scene,
707                                               bool background)
708 {
709         SessionParams params;
710         PointerRNA cscene = RNA_pointer_get(&b_scene.ptr, "cycles");
711
712         /* feature set */
713         params.experimental = (get_enum(cscene, "feature_set") != 0);
714
715         /* threads */
716         BL::RenderSettings b_r = b_scene.render();
717         if(b_r.threads_mode() == BL::RenderSettings::threads_mode_FIXED)
718                 params.threads = b_r.threads();
719         else
720                 params.threads = 0;
721
722         /* Background */
723         params.background = background;
724
725         /* device type */
726         vector<DeviceInfo>& devices = Device::available_devices();
727
728         /* device default CPU */
729         foreach(DeviceInfo& device, devices) {
730                 if(device.type == DEVICE_CPU) {
731                         params.device = device;
732                         break;
733                 }
734         }
735
736         if(get_enum(cscene, "device") == 2) {
737                 /* find network device */
738                 foreach(DeviceInfo& info, devices)
739                         if(info.type == DEVICE_NETWORK)
740                                 params.device = info;
741         }
742         else if(get_enum(cscene, "device") == 1) {
743                 PointerRNA b_preferences;
744
745                 BL::UserPreferences::addons_iterator b_addon_iter;
746                 for(b_userpref.addons.begin(b_addon_iter); b_addon_iter != b_userpref.addons.end(); ++b_addon_iter) {
747                         if(b_addon_iter->module() == "cycles") {
748                                 b_preferences = b_addon_iter->preferences().ptr;
749                                 break;
750                         }
751                 }
752
753                 enum ComputeDevice {
754                         COMPUTE_DEVICE_CPU = 0,
755                         COMPUTE_DEVICE_CUDA = 1,
756                         COMPUTE_DEVICE_OPENCL = 2,
757                         COMPUTE_DEVICE_NUM = 3,
758                 };
759
760                 ComputeDevice compute_device = (ComputeDevice)get_enum(b_preferences,
761                                                                        "compute_device_type",
762                                                                        COMPUTE_DEVICE_NUM,
763                                                                        COMPUTE_DEVICE_CPU);
764
765                 if(compute_device != COMPUTE_DEVICE_CPU) {
766                         vector<DeviceInfo> used_devices;
767                         RNA_BEGIN(&b_preferences, device, "devices") {
768                                 ComputeDevice device_type = (ComputeDevice)get_enum(device,
769                                                                                     "type",
770                                                                                     COMPUTE_DEVICE_NUM,
771                                                                                     COMPUTE_DEVICE_CPU);
772
773                                 if(get_boolean(device, "use") &&
774                                    (device_type == compute_device || device_type == COMPUTE_DEVICE_CPU)) {
775                                         string id = get_string(device, "id");
776                                         foreach(DeviceInfo& info, devices) {
777                                                 if(info.id == id) {
778                                                         used_devices.push_back(info);
779                                                         break;
780                                                 }
781                                         }
782                                 }
783                         } RNA_END;
784
785                         if(used_devices.size() == 1) {
786                                 params.device = used_devices[0];
787                         }
788                         else if(used_devices.size() > 1) {
789                                 params.device = Device::get_multi_device(used_devices,
790                                                                          params.threads,
791                                                                          params.background);
792                         }
793                         /* Else keep using the CPU device that was set before. */
794                 }
795         }
796
797         /* samples */
798         int samples = get_int(cscene, "samples");
799         int aa_samples = get_int(cscene, "aa_samples");
800         int preview_samples = get_int(cscene, "preview_samples");
801         int preview_aa_samples = get_int(cscene, "preview_aa_samples");
802
803         if(get_boolean(cscene, "use_square_samples")) {
804                 aa_samples = aa_samples * aa_samples;
805                 preview_aa_samples = preview_aa_samples * preview_aa_samples;
806
807                 samples = samples * samples;
808                 preview_samples = preview_samples * preview_samples;
809         }
810
811         if(get_enum(cscene, "progressive") == 0) {
812                 if(background) {
813                         params.samples = aa_samples;
814                 }
815                 else {
816                         params.samples = preview_aa_samples;
817                         if(params.samples == 0)
818                                 params.samples = INT_MAX;
819                 }
820         }
821         else {
822                 if(background) {
823                         params.samples = samples;
824                 }
825                 else {
826                         params.samples = preview_samples;
827                         if(params.samples == 0)
828                                 params.samples = INT_MAX;
829                 }
830         }
831
832         /* tiles */
833         const bool is_cpu = (params.device.type == DEVICE_CPU);
834         if(!is_cpu && !background) {
835                 /* currently GPU could be much slower than CPU when using tiles,
836                  * still need to be investigated, but meanwhile make it possible
837                  * to work in viewport smoothly
838                  */
839                 int debug_tile_size = get_int(cscene, "debug_tile_size");
840
841                 params.tile_size = make_int2(debug_tile_size, debug_tile_size);
842         }
843         else {
844                 int tile_x = b_engine.tile_x();
845                 int tile_y = b_engine.tile_y();
846
847                 params.tile_size = make_int2(tile_x, tile_y);
848         }
849
850         if((BlenderSession::headless == false) && background) {
851                 params.tile_order = (TileOrder)get_enum(cscene, "tile_order");
852         }
853         else {
854                 params.tile_order = TILE_BOTTOM_TO_TOP;
855         }
856
857         /* other parameters */
858         params.start_resolution = get_int(cscene, "preview_start_resolution");
859         params.pixel_size = b_engine.get_preview_pixel_size(b_scene);
860
861         /* other parameters */
862         params.cancel_timeout = (double)get_float(cscene, "debug_cancel_timeout");
863         params.reset_timeout = (double)get_float(cscene, "debug_reset_timeout");
864         params.text_timeout = (double)get_float(cscene, "debug_text_timeout");
865
866         /* progressive refine */
867         params.progressive_refine = (b_engine.is_preview() ||
868                                      get_boolean(cscene, "use_progressive_refine")) &&
869                                     !b_r.use_save_buffers();
870
871         if(params.progressive_refine) {
872                 BL::Scene::view_layers_iterator b_view_layer;
873                 for(b_scene.view_layers.begin(b_view_layer); b_view_layer != b_scene.view_layers.end(); ++b_view_layer) {
874                         PointerRNA crl = RNA_pointer_get(&b_view_layer->ptr, "cycles");
875                         if(get_boolean(crl, "use_denoising")) {
876                                 params.progressive_refine = false;
877                         }
878                 }
879         }
880
881         if(background) {
882                 if(params.progressive_refine)
883                         params.progressive = true;
884                 else
885                         params.progressive = false;
886
887                 params.start_resolution = INT_MAX;
888                 params.pixel_size = 1;
889         }
890         else
891                 params.progressive = true;
892
893         /* shading system - scene level needs full refresh */
894         const bool shadingsystem = RNA_boolean_get(&cscene, "shading_system");
895
896         if(shadingsystem == 0)
897                 params.shadingsystem = SHADINGSYSTEM_SVM;
898         else if(shadingsystem == 1)
899                 params.shadingsystem = SHADINGSYSTEM_OSL;
900
901         /* color managagement */
902         params.display_buffer_linear = b_engine.support_display_space_shader(b_scene);
903
904         if(b_engine.is_preview()) {
905                 /* For preview rendering we're using same timeout as
906                  * blender's job update.
907                  */
908                 params.progressive_update_timeout = 0.1;
909         }
910
911         params.use_profiling = params.device.has_profiling && !b_engine.is_preview() &&
912                                background && BlenderSession::print_render_stats;
913
914         return params;
915 }
916
917 CCL_NAMESPACE_END