Merge branch 'blender2.7'
[blender.git] / intern / cycles / blender / blender_session.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 <stdlib.h>
18
19 #include "render/background.h"
20 #include "render/buffers.h"
21 #include "render/camera.h"
22 #include "device/device.h"
23 #include "render/integrator.h"
24 #include "render/film.h"
25 #include "render/light.h"
26 #include "render/mesh.h"
27 #include "render/object.h"
28 #include "render/scene.h"
29 #include "render/session.h"
30 #include "render/shader.h"
31 #include "render/stats.h"
32
33 #include "util/util_color.h"
34 #include "util/util_foreach.h"
35 #include "util/util_function.h"
36 #include "util/util_hash.h"
37 #include "util/util_logging.h"
38 #include "util/util_murmurhash.h"
39 #include "util/util_progress.h"
40 #include "util/util_time.h"
41
42 #include "blender/blender_sync.h"
43 #include "blender/blender_session.h"
44 #include "blender/blender_util.h"
45
46 CCL_NAMESPACE_BEGIN
47
48 bool BlenderSession::headless = false;
49 int BlenderSession::num_resumable_chunks = 0;
50 int BlenderSession::current_resumable_chunk = 0;
51 int BlenderSession::start_resumable_chunk = 0;
52 int BlenderSession::end_resumable_chunk = 0;
53 bool BlenderSession::print_render_stats = false;
54
55 BlenderSession::BlenderSession(BL::RenderEngine& b_engine,
56                                BL::Preferences& b_userpref,
57                                BL::BlendData& b_data,
58                                bool preview_osl)
59 : session(NULL),
60   sync(NULL),
61   b_engine(b_engine),
62   b_userpref(b_userpref),
63   b_data(b_data),
64   b_render(b_engine.render()),
65   b_depsgraph(PointerRNA_NULL),
66   b_scene(PointerRNA_NULL),
67   b_v3d(PointerRNA_NULL),
68   b_rv3d(PointerRNA_NULL),
69   width(0),
70   height(0),
71   preview_osl(preview_osl),
72   python_thread_state(NULL)
73 {
74         /* offline render */
75         background = true;
76         last_redraw_time = 0.0;
77         start_resize_time = 0.0;
78         last_status_time = 0.0;
79 }
80
81 BlenderSession::BlenderSession(BL::RenderEngine& b_engine,
82                                BL::Preferences& b_userpref,
83                                BL::BlendData& b_data,
84                                BL::SpaceView3D& b_v3d,
85                                BL::RegionView3D& b_rv3d,
86                                int width, int height)
87 : session(NULL),
88   sync(NULL),
89   b_engine(b_engine),
90   b_userpref(b_userpref),
91   b_data(b_data),
92   b_render(b_engine.render()),
93   b_depsgraph(PointerRNA_NULL),
94   b_scene(PointerRNA_NULL),
95   b_v3d(b_v3d),
96   b_rv3d(b_rv3d),
97   width(width),
98   height(height),
99   preview_osl(false),
100   python_thread_state(NULL)
101 {
102         /* 3d view render */
103         background = false;
104         last_redraw_time = 0.0;
105         start_resize_time = 0.0;
106         last_status_time = 0.0;
107 }
108
109 BlenderSession::~BlenderSession()
110 {
111         free_session();
112 }
113
114 void BlenderSession::create()
115 {
116         create_session();
117 }
118
119 void BlenderSession::create_session()
120 {
121         SessionParams session_params = BlenderSync::get_session_params(b_engine, b_userpref, b_scene, background);
122         SceneParams scene_params = BlenderSync::get_scene_params(b_scene, background);
123         bool session_pause = BlenderSync::get_session_pause(b_scene, background);
124
125         /* reset status/progress */
126         last_status = "";
127         last_error = "";
128         last_progress = -1.0f;
129         start_resize_time = 0.0;
130
131         /* create session */
132         session = new Session(session_params);
133         session->scene = scene;
134         session->progress.set_update_callback(function_bind(&BlenderSession::tag_redraw, this));
135         session->progress.set_cancel_callback(function_bind(&BlenderSession::test_cancel, this));
136         session->set_pause(session_pause);
137
138         /* create scene */
139         scene = new Scene(scene_params, session->device);
140         scene->name = b_scene.name();
141
142         /* setup callbacks for builtin image support */
143         scene->image_manager->builtin_image_info_cb = function_bind(&BlenderSession::builtin_image_info, this, _1, _2, _3);
144         scene->image_manager->builtin_image_pixels_cb = function_bind(&BlenderSession::builtin_image_pixels, this, _1, _2, _3, _4, _5);
145         scene->image_manager->builtin_image_float_pixels_cb = function_bind(&BlenderSession::builtin_image_float_pixels, this, _1, _2, _3, _4, _5);
146
147         session->scene = scene;
148
149         /* There is no single depsgraph to use for the entire render.
150          * So we need to handle this differently.
151          *
152          * We could loop over the final render result render layers in pipeline and keep Cycles unaware of multiple layers,
153          * or perhaps move syncing further down in the pipeline.
154          */
155         /* create sync */
156         sync = new BlenderSync(b_engine, b_data, b_scene, scene, !background, session->progress);
157         BL::Object b_camera_override(b_engine.camera_override());
158         if(b_v3d) {
159                 sync->sync_view(b_v3d, b_rv3d, width, height);
160         }
161         else {
162                 sync->sync_camera(b_render, b_camera_override, width, height, "");
163         }
164
165         /* set buffer parameters */
166         BufferParams buffer_params = BlenderSync::get_buffer_params(b_render, b_v3d, b_rv3d, scene->camera, width, height);
167         session->reset(buffer_params, session_params.samples);
168
169         b_engine.use_highlight_tiles(session_params.progressive_refine == false);
170
171         update_resumable_tile_manager(session_params.samples);
172 }
173
174 void BlenderSession::reset_session(BL::BlendData& b_data, BL::Depsgraph& b_depsgraph)
175 {
176         this->b_data = b_data;
177         this->b_depsgraph = b_depsgraph;
178         this->b_scene = b_depsgraph.scene_eval();
179
180         if(preview_osl) {
181                 PointerRNA cscene = RNA_pointer_get(&b_scene.ptr, "cycles");
182                 RNA_boolean_set(&cscene, "shading_system", preview_osl);
183         }
184
185         if(b_v3d) {
186                 this->b_render = b_scene.render();
187         }
188         else {
189                 this->b_render = b_engine.render();
190                 width = render_resolution_x(b_render);
191                 height = render_resolution_y(b_render);
192         }
193
194         if(session == NULL) {
195                 create();
196         }
197
198         if(b_v3d) {
199                 /* NOTE: We need to create session, but all the code from below
200                  * will make viewport render to stuck on initialization.
201                  */
202                 return;
203         }
204
205         SessionParams session_params = BlenderSync::get_session_params(b_engine, b_userpref, b_scene, background);
206         SceneParams scene_params = BlenderSync::get_scene_params(b_scene, background);
207
208         if(scene->params.modified(scene_params) ||
209            session->params.modified(session_params) ||
210            !scene_params.persistent_data)
211         {
212                 /* if scene or session parameters changed, it's easier to simply re-create
213                  * them rather than trying to distinguish which settings need to be updated
214                  */
215                 free_session();
216                 create_session();
217                 return;
218         }
219
220         session->progress.reset();
221         scene->reset();
222
223         session->tile_manager.set_tile_order(session_params.tile_order);
224
225         /* peak memory usage should show current render peak, not peak for all renders
226          * made by this render session
227          */
228         session->stats.mem_peak = session->stats.mem_used;
229
230         /* There is no single depsgraph to use for the entire render.
231          * See note on create_session().
232          */
233         /* sync object should be re-created */
234         sync = new BlenderSync(b_engine, b_data, b_scene, scene, !background, session->progress);
235
236         BL::SpaceView3D b_null_space_view3d(PointerRNA_NULL);
237         BL::RegionView3D b_null_region_view3d(PointerRNA_NULL);
238         BufferParams buffer_params = BlenderSync::get_buffer_params(b_render,
239                                                                     b_null_space_view3d,
240                                                                     b_null_region_view3d,
241                                                                     scene->camera,
242                                                                     width, height);
243         session->reset(buffer_params, session_params.samples);
244
245         b_engine.use_highlight_tiles(session_params.progressive_refine == false);
246
247         /* reset time */
248         start_resize_time = 0.0;
249 }
250
251 void BlenderSession::free_session()
252 {
253         if(sync)
254                 delete sync;
255
256         delete session;
257 }
258
259 static ShaderEvalType get_shader_type(const string& pass_type)
260 {
261         const char *shader_type = pass_type.c_str();
262
263         /* data passes */
264         if(strcmp(shader_type, "NORMAL")==0)
265                 return SHADER_EVAL_NORMAL;
266         else if(strcmp(shader_type, "UV")==0)
267                 return SHADER_EVAL_UV;
268         else if(strcmp(shader_type, "ROUGHNESS")==0)
269                 return SHADER_EVAL_ROUGHNESS;
270         else if(strcmp(shader_type, "DIFFUSE_COLOR")==0)
271                 return SHADER_EVAL_DIFFUSE_COLOR;
272         else if(strcmp(shader_type, "GLOSSY_COLOR")==0)
273                 return SHADER_EVAL_GLOSSY_COLOR;
274         else if(strcmp(shader_type, "TRANSMISSION_COLOR")==0)
275                 return SHADER_EVAL_TRANSMISSION_COLOR;
276         else if(strcmp(shader_type, "SUBSURFACE_COLOR")==0)
277                 return SHADER_EVAL_SUBSURFACE_COLOR;
278         else if(strcmp(shader_type, "EMIT")==0)
279                 return SHADER_EVAL_EMISSION;
280
281         /* light passes */
282         else if(strcmp(shader_type, "AO")==0)
283                 return SHADER_EVAL_AO;
284         else if(strcmp(shader_type, "COMBINED")==0)
285                 return SHADER_EVAL_COMBINED;
286         else if(strcmp(shader_type, "SHADOW")==0)
287                 return SHADER_EVAL_SHADOW;
288         else if(strcmp(shader_type, "DIFFUSE")==0)
289                 return SHADER_EVAL_DIFFUSE;
290         else if(strcmp(shader_type, "GLOSSY")==0)
291                 return SHADER_EVAL_GLOSSY;
292         else if(strcmp(shader_type, "TRANSMISSION")==0)
293                 return SHADER_EVAL_TRANSMISSION;
294         else if(strcmp(shader_type, "SUBSURFACE")==0)
295                 return SHADER_EVAL_SUBSURFACE;
296
297         /* extra */
298         else if(strcmp(shader_type, "ENVIRONMENT")==0)
299                 return SHADER_EVAL_ENVIRONMENT;
300
301         else
302                 return SHADER_EVAL_BAKE;
303 }
304
305 static BL::RenderResult begin_render_result(BL::RenderEngine& b_engine,
306                                             int x, int y,
307                                             int w, int h,
308                                             const char *layername,
309                                             const char *viewname)
310 {
311         return b_engine.begin_result(x, y, w, h, layername, viewname);
312 }
313
314 static void end_render_result(BL::RenderEngine& b_engine,
315                               BL::RenderResult& b_rr,
316                               bool cancel,
317                               bool highlight,
318                               bool do_merge_results)
319 {
320         b_engine.end_result(b_rr, (int)cancel, (int) highlight, (int)do_merge_results);
321 }
322
323 void BlenderSession::do_write_update_render_tile(RenderTile& rtile, bool do_update_only, bool highlight)
324 {
325         int x = rtile.x - session->tile_manager.params.full_x;
326         int y = rtile.y - session->tile_manager.params.full_y;
327         int w = rtile.w;
328         int h = rtile.h;
329
330         /* get render result */
331         BL::RenderResult b_rr = begin_render_result(b_engine, x, y, w, h, b_rlay_name.c_str(), b_rview_name.c_str());
332
333         /* can happen if the intersected rectangle gives 0 width or height */
334         if(b_rr.ptr.data == NULL) {
335                 return;
336         }
337
338         BL::RenderResult::layers_iterator b_single_rlay;
339         b_rr.layers.begin(b_single_rlay);
340
341         /* layer will be missing if it was disabled in the UI */
342         if(b_single_rlay == b_rr.layers.end())
343                 return;
344
345         BL::RenderLayer b_rlay = *b_single_rlay;
346
347         if(do_update_only) {
348                 /* Sample would be zero at initial tile update, which is only needed
349                  * to tag tile form blender side as IN PROGRESS for proper highlight
350                  * no buffers should be sent to blender yet. For denoise we also
351                  * keep showing the noisy buffers until denoise is done. */
352                 bool merge = (rtile.sample != 0) && (rtile.task != RenderTile::DENOISE);
353
354                 if(merge) {
355                         update_render_result(b_rr, b_rlay, rtile);
356                 }
357
358                 end_render_result(b_engine, b_rr, true, highlight, merge);
359         }
360         else {
361                 /* Write final render result. */
362                 write_render_result(b_rr, b_rlay, rtile);
363                 end_render_result(b_engine, b_rr, false, false, true);
364         }
365 }
366
367 void BlenderSession::write_render_tile(RenderTile& rtile)
368 {
369         do_write_update_render_tile(rtile, false, false);
370 }
371
372 void BlenderSession::update_render_tile(RenderTile& rtile, bool highlight)
373 {
374         /* use final write for preview renders, otherwise render result wouldn't be
375          * be updated in blender side
376          * would need to be investigated a bit further, but for now shall be fine
377          */
378         if(!b_engine.is_preview())
379                 do_write_update_render_tile(rtile, true, highlight);
380         else
381                 do_write_update_render_tile(rtile, false, false);
382 }
383
384 static void add_cryptomatte_layer(BL::RenderResult& b_rr, string name, string manifest)
385 {
386         string identifier = string_printf("%08x", util_murmur_hash3(name.c_str(), name.length(), 0));
387         string prefix = "cryptomatte/" + identifier.substr(0, 7) + "/";
388
389         render_add_metadata(b_rr, prefix+"name", name);
390         render_add_metadata(b_rr, prefix+"hash", "MurmurHash3_32");
391         render_add_metadata(b_rr, prefix+"conversion", "uint32_to_float32");
392         render_add_metadata(b_rr, prefix+"manifest", manifest);
393 }
394
395 void BlenderSession::render(BL::Depsgraph& b_depsgraph_)
396 {
397         b_depsgraph = b_depsgraph_;
398
399         /* set callback to write out render results */
400         session->write_render_tile_cb = function_bind(&BlenderSession::write_render_tile, this, _1);
401         session->update_render_tile_cb = function_bind(&BlenderSession::update_render_tile, this, _1, _2);
402
403         /* get buffer parameters */
404         SessionParams session_params = BlenderSync::get_session_params(b_engine, b_userpref, b_scene, background);
405         BufferParams buffer_params = BlenderSync::get_buffer_params(b_render, b_v3d, b_rv3d, scene->camera, width, height);
406
407         /* render each layer */
408         BL::ViewLayer b_view_layer = b_depsgraph.view_layer_eval();
409
410         /* We do some special meta attributes when we only have single layer. */
411         const bool is_single_layer = (b_scene.view_layers.length() == 1);
412
413         /* temporary render result to find needed passes and views */
414         BL::RenderResult b_rr = begin_render_result(b_engine, 0, 0, 1, 1, b_view_layer.name().c_str(), NULL);
415         BL::RenderResult::layers_iterator b_single_rlay;
416         b_rr.layers.begin(b_single_rlay);
417         BL::RenderLayer b_rlay = *b_single_rlay;
418         b_rlay_name = b_view_layer.name();
419
420         /* add passes */
421         vector<Pass> passes = sync->sync_render_passes(b_rlay, b_view_layer, session_params);
422         buffer_params.passes = passes;
423
424         PointerRNA crl = RNA_pointer_get(&b_view_layer.ptr, "cycles");
425         bool use_denoising = get_boolean(crl, "use_denoising");
426         bool denoising_passes = use_denoising || get_boolean(crl, "denoising_store_passes");
427
428         session->tile_manager.schedule_denoising = use_denoising;
429         buffer_params.denoising_data_pass = denoising_passes;
430         buffer_params.denoising_clean_pass = (scene->film->denoising_flags & DENOISING_CLEAN_ALL_PASSES);
431
432         session->params.use_denoising = use_denoising;
433         session->params.denoising_passes = denoising_passes;
434         session->params.denoising_radius = get_int(crl, "denoising_radius");
435         session->params.denoising_strength = get_float(crl, "denoising_strength");
436         session->params.denoising_feature_strength = get_float(crl, "denoising_feature_strength");
437         session->params.denoising_relative_pca = get_boolean(crl, "denoising_relative_pca");
438
439         scene->film->denoising_data_pass = buffer_params.denoising_data_pass;
440         scene->film->denoising_clean_pass = buffer_params.denoising_clean_pass;
441         session->params.denoising_radius = get_int(crl, "denoising_radius");
442         session->params.denoising_strength = get_float(crl, "denoising_strength");
443         session->params.denoising_feature_strength = get_float(crl, "denoising_feature_strength");
444         session->params.denoising_relative_pca = get_boolean(crl, "denoising_relative_pca");
445
446         scene->film->pass_alpha_threshold = b_view_layer.pass_alpha_threshold();
447         scene->film->tag_passes_update(scene, passes);
448         scene->film->tag_update(scene);
449         scene->integrator->tag_update(scene);
450
451         BL::RenderResult::views_iterator b_view_iter;
452         int view_index = 0;
453         for(b_rr.views.begin(b_view_iter); b_view_iter != b_rr.views.end(); ++b_view_iter, ++view_index) {
454                 b_rview_name = b_view_iter->name();
455
456                 /* set the current view */
457                 b_engine.active_view_set(b_rview_name.c_str());
458
459                 /* update scene */
460                 BL::Object b_camera_override(b_engine.camera_override());
461                 sync->sync_camera(b_render, b_camera_override, width, height, b_rview_name.c_str());
462                 sync->sync_data(b_render,
463                                 b_depsgraph,
464                                 b_v3d,
465                                 b_camera_override,
466                                 width, height,
467                                 &python_thread_state);
468                 builtin_images_load();
469
470                 /* Attempt to free all data which is held by Blender side, since at this
471                  * point we knwo that we've got everything to render current view layer.
472                  */
473                 free_blender_memory_if_possible();
474
475                 /* Make sure all views have different noise patterns. - hardcoded value just to make it random */
476                 if(view_index != 0) {
477                         scene->integrator->seed += hash_int_2d(scene->integrator->seed, hash_int(view_index * 0xdeadbeef));
478                         scene->integrator->tag_update(scene);
479                 }
480
481                 /* Update number of samples per layer. */
482                 int samples = sync->get_layer_samples();
483                 bool bound_samples = sync->get_layer_bound_samples();
484                 int effective_layer_samples;
485
486                 if(samples != 0 && (!bound_samples || (samples < session_params.samples)))
487                         effective_layer_samples = samples;
488                 else
489                         effective_layer_samples = session_params.samples;
490
491                 /* Update tile manager if we're doing resumable render. */
492                 update_resumable_tile_manager(effective_layer_samples);
493
494                 /* Update session itself. */
495                 session->reset(buffer_params, effective_layer_samples);
496
497                 /* render */
498                 session->start();
499                 session->wait();
500
501                 if(!b_engine.is_preview() && background && print_render_stats) {
502                         RenderStats stats;
503                         session->collect_statistics(&stats);
504                         printf("Render statistics:\n%s\n", stats.full_report().c_str());
505                 }
506
507                 if(session->progress.get_cancel())
508                         break;
509         }
510
511         if(is_single_layer) {
512                 BL::RenderResult b_rr = b_engine.get_result();
513                 string num_aa_samples = string_printf("%d", session->params.samples);
514                 b_rr.stamp_data_add_field("Cycles Samples", num_aa_samples.c_str());
515                 /* TODO(sergey): Report whether we're doing resumable render
516                  * and also start/end sample if so.
517                  */
518         }
519
520         /* Write cryptomatte metadata. */
521         if(scene->film->cryptomatte_passes & CRYPT_OBJECT) {
522                 add_cryptomatte_layer(b_rr, b_rlay_name+".CryptoObject",
523                                                           scene->object_manager->get_cryptomatte_objects(scene));
524         }
525         if(scene->film->cryptomatte_passes & CRYPT_MATERIAL) {
526                 add_cryptomatte_layer(b_rr, b_rlay_name+".CryptoMaterial",
527                                                           scene->shader_manager->get_cryptomatte_materials(scene));
528         }
529         if(scene->film->cryptomatte_passes & CRYPT_ASSET) {
530                 add_cryptomatte_layer(b_rr, b_rlay_name+".CryptoAsset",
531                                                           scene->object_manager->get_cryptomatte_assets(scene));
532         }
533
534         /* free result without merging */
535         end_render_result(b_engine, b_rr, true, true, false);
536
537         double total_time, render_time;
538         session->progress.get_time(total_time, render_time);
539         VLOG(1) << "Total render time: " << total_time;
540         VLOG(1) << "Render time (without synchronization): " << render_time;
541
542         /* clear callback */
543         session->write_render_tile_cb = function_null;
544         session->update_render_tile_cb = function_null;
545
546         /* TODO: find a way to clear this data for persistent data render */
547 #if 0
548         /* free all memory used (host and device), so we wouldn't leave render
549          * engine with extra memory allocated
550          */
551
552         session->device_free();
553
554         delete sync;
555         sync = NULL;
556 #endif
557 }
558
559 static void populate_bake_data(BakeData *data, const
560                                int object_id,
561                                BL::BakePixel& pixel_array,
562                                const int num_pixels)
563 {
564         BL::BakePixel bp = pixel_array;
565
566         int i;
567         for(i = 0; i < num_pixels; i++) {
568                 if(bp.object_id() == object_id) {
569                         data->set(i, bp.primitive_id(), bp.uv(), bp.du_dx(), bp.du_dy(), bp.dv_dx(), bp.dv_dy());
570                 } else {
571                         data->set_null(i);
572                 }
573                 bp = bp.next();
574         }
575 }
576
577 static int bake_pass_filter_get(const int pass_filter)
578 {
579         int flag = BAKE_FILTER_NONE;
580
581         if((pass_filter & BL::BakeSettings::pass_filter_DIRECT) != 0)
582                 flag |= BAKE_FILTER_DIRECT;
583         if((pass_filter & BL::BakeSettings::pass_filter_INDIRECT) != 0)
584                 flag |= BAKE_FILTER_INDIRECT;
585         if((pass_filter & BL::BakeSettings::pass_filter_COLOR) != 0)
586                 flag |= BAKE_FILTER_COLOR;
587
588         if((pass_filter & BL::BakeSettings::pass_filter_DIFFUSE) != 0)
589                 flag |= BAKE_FILTER_DIFFUSE;
590         if((pass_filter & BL::BakeSettings::pass_filter_GLOSSY) != 0)
591                 flag |= BAKE_FILTER_GLOSSY;
592         if((pass_filter & BL::BakeSettings::pass_filter_TRANSMISSION) != 0)
593                 flag |= BAKE_FILTER_TRANSMISSION;
594         if((pass_filter & BL::BakeSettings::pass_filter_SUBSURFACE) != 0)
595                 flag |= BAKE_FILTER_SUBSURFACE;
596
597         if((pass_filter & BL::BakeSettings::pass_filter_EMIT) != 0)
598                 flag |= BAKE_FILTER_EMISSION;
599         if((pass_filter & BL::BakeSettings::pass_filter_AO) != 0)
600                 flag |= BAKE_FILTER_AO;
601
602         return flag;
603 }
604
605 void BlenderSession::bake(BL::Depsgraph& b_depsgraph_,
606                           BL::Object& b_object,
607                           const string& pass_type,
608                           const int pass_filter,
609                           const int object_id,
610                           BL::BakePixel& pixel_array,
611                           const size_t num_pixels,
612                           const int /*depth*/,
613                           float result[])
614 {
615         b_depsgraph = b_depsgraph_;
616
617         ShaderEvalType shader_type = get_shader_type(pass_type);
618
619         /* Set baking flag in advance, so kernel loading can check if we need
620          * any baking capabilities.
621          */
622         scene->bake_manager->set_baking(true);
623
624         /* ensure kernels are loaded before we do any scene updates */
625         session->load_kernels();
626
627         if(shader_type == SHADER_EVAL_UV) {
628                 /* force UV to be available */
629                 Pass::add(PASS_UV, scene->film->passes);
630         }
631
632         int bake_pass_filter = bake_pass_filter_get(pass_filter);
633         bake_pass_filter = BakeManager::shader_type_to_pass_filter(shader_type, bake_pass_filter);
634
635         /* force use_light_pass to be true if we bake more than just colors */
636         if(bake_pass_filter & ~BAKE_FILTER_COLOR) {
637                 Pass::add(PASS_LIGHT, scene->film->passes);
638         }
639
640         /* create device and update scene */
641         scene->film->tag_update(scene);
642         scene->integrator->tag_update(scene);
643
644         if(!session->progress.get_cancel()) {
645                 /* update scene */
646                 BL::Object b_camera_override(b_engine.camera_override());
647                 sync->sync_camera(b_render, b_camera_override, width, height, "");
648                 sync->sync_data(b_render,
649                                 b_depsgraph,
650                                 b_v3d,
651                                 b_camera_override,
652                                 width, height,
653                                 &python_thread_state);
654                 builtin_images_load();
655         }
656
657         BakeData *bake_data = NULL;
658
659         if(!session->progress.get_cancel()) {
660                 /* get buffer parameters */
661                 SessionParams session_params = BlenderSync::get_session_params(b_engine, b_userpref, b_scene, background);
662                 BufferParams buffer_params = BlenderSync::get_buffer_params(b_render, b_v3d, b_rv3d, scene->camera, width, height);
663
664                 scene->bake_manager->set_shader_limit((size_t)b_engine.tile_x(), (size_t)b_engine.tile_y());
665
666                 /* set number of samples */
667                 session->tile_manager.set_samples(session_params.samples);
668                 session->reset(buffer_params, session_params.samples);
669                 session->update_scene();
670
671                 /* find object index. todo: is arbitrary - copied from mesh_displace.cpp */
672                 size_t object_index = OBJECT_NONE;
673                 int tri_offset = 0;
674
675                 for(size_t i = 0; i < scene->objects.size(); i++) {
676                         if(strcmp(scene->objects[i]->name.c_str(), b_object.name().c_str()) == 0) {
677                                 object_index = i;
678                                 tri_offset = scene->objects[i]->mesh->tri_offset;
679                                 break;
680                         }
681                 }
682
683                 int object = object_index;
684
685                 bake_data = scene->bake_manager->init(object, tri_offset, num_pixels);
686                 populate_bake_data(bake_data, object_id, pixel_array, num_pixels);
687
688                 /* set number of samples */
689                 session->tile_manager.set_samples(session_params.samples);
690                 session->reset(buffer_params, session_params.samples);
691                 session->update_scene();
692
693                 session->progress.set_update_callback(function_bind(&BlenderSession::update_bake_progress, this));
694         }
695
696         /* Perform bake. Check cancel to avoid crash with incomplete scene data. */
697         if(!session->progress.get_cancel()) {
698                 scene->bake_manager->bake(scene->device, &scene->dscene, scene, session->progress, shader_type, bake_pass_filter, bake_data, result);
699         }
700
701         /* free all memory used (host and device), so we wouldn't leave render
702          * engine with extra memory allocated
703          */
704
705         session->device_free();
706
707         delete sync;
708         sync = NULL;
709 }
710
711 void BlenderSession::do_write_update_render_result(BL::RenderResult& b_rr,
712                                                    BL::RenderLayer& b_rlay,
713                                                    RenderTile& rtile,
714                                                    bool do_update_only)
715 {
716         RenderBuffers *buffers = rtile.buffers;
717
718         /* copy data from device */
719         if(!buffers->copy_from_device())
720                 return;
721
722         float exposure = scene->film->exposure;
723
724         vector<float> pixels(rtile.w*rtile.h*4);
725
726         /* Adjust absolute sample number to the range. */
727         int sample = rtile.sample;
728         const int range_start_sample = session->tile_manager.range_start_sample;
729         if(range_start_sample != -1) {
730                 sample -= range_start_sample;
731         }
732
733         if(!do_update_only) {
734                 /* copy each pass */
735                 BL::RenderLayer::passes_iterator b_iter;
736
737                 for(b_rlay.passes.begin(b_iter); b_iter != b_rlay.passes.end(); ++b_iter) {
738                         BL::RenderPass b_pass(*b_iter);
739
740                         /* find matching pass type */
741                         PassType pass_type = BlenderSync::get_pass_type(b_pass);
742                         int components = b_pass.channels();
743
744                         bool read = false;
745                         if(pass_type != PASS_NONE) {
746                                 /* copy pixels */
747                                 read = buffers->get_pass_rect(pass_type, exposure, sample, components, &pixels[0], b_pass.name());
748                         }
749                         else {
750                                 int denoising_offset = BlenderSync::get_denoising_pass(b_pass);
751                                 if(denoising_offset >= 0) {
752                                         read = buffers->get_denoising_pass_rect(denoising_offset, exposure, sample, components, &pixels[0]);
753                                 }
754                         }
755
756                         if(!read) {
757                                 memset(&pixels[0], 0, pixels.size()*sizeof(float));
758                         }
759
760                         b_pass.rect(&pixels[0]);
761                 }
762         }
763         else {
764                 /* copy combined pass */
765                 BL::RenderPass b_combined_pass(b_rlay.passes.find_by_name("Combined", b_rview_name.c_str()));
766                 if(buffers->get_pass_rect(PASS_COMBINED, exposure, sample, 4, &pixels[0], "Combined"))
767                         b_combined_pass.rect(&pixels[0]);
768         }
769
770         /* tag result as updated */
771         b_engine.update_result(b_rr);
772 }
773
774 void BlenderSession::write_render_result(BL::RenderResult& b_rr,
775                                          BL::RenderLayer& b_rlay,
776                                          RenderTile& rtile)
777 {
778         do_write_update_render_result(b_rr, b_rlay, rtile, false);
779 }
780
781 void BlenderSession::update_render_result(BL::RenderResult& b_rr,
782                                           BL::RenderLayer& b_rlay,
783                                           RenderTile& rtile)
784 {
785         do_write_update_render_result(b_rr, b_rlay, rtile, true);
786 }
787
788 void BlenderSession::synchronize(BL::Depsgraph& b_depsgraph_)
789 {
790         /* only used for viewport render */
791         if(!b_v3d)
792                 return;
793
794         /* on session/scene parameter changes, we recreate session entirely */
795         SessionParams session_params = BlenderSync::get_session_params(b_engine, b_userpref, b_scene, background);
796         SceneParams scene_params = BlenderSync::get_scene_params(b_scene, background);
797         bool session_pause = BlenderSync::get_session_pause(b_scene, background);
798
799         if(session->params.modified(session_params) ||
800            scene->params.modified(scene_params))
801         {
802                 free_session();
803                 create_session();
804                 return;
805         }
806
807         /* increase samples, but never decrease */
808         session->set_samples(session_params.samples);
809         session->set_pause(session_pause);
810
811         /* copy recalc flags, outside of mutex so we can decide to do the real
812          * synchronization at a later time to not block on running updates */
813         sync->sync_recalc(b_depsgraph_);
814
815         /* don't do synchronization if on pause */
816         if(session_pause) {
817                 tag_update();
818                 return;
819         }
820
821         /* try to acquire mutex. if we don't want to or can't, come back later */
822         if(!session->ready_to_reset() || !session->scene->mutex.try_lock()) {
823                 tag_update();
824                 return;
825         }
826
827         /* data and camera synchronize */
828         b_depsgraph = b_depsgraph_;
829
830         BL::Object b_camera_override(b_engine.camera_override());
831         sync->sync_data(b_render,
832                         b_depsgraph,
833                         b_v3d,
834                         b_camera_override,
835                         width, height,
836                         &python_thread_state);
837
838         if(b_rv3d)
839                 sync->sync_view(b_v3d, b_rv3d, width, height);
840         else
841                 sync->sync_camera(b_render, b_camera_override, width, height, "");
842
843         builtin_images_load();
844
845         /* unlock */
846         session->scene->mutex.unlock();
847
848         /* reset if needed */
849         if(scene->need_reset()) {
850                 BufferParams buffer_params = BlenderSync::get_buffer_params(b_render, b_v3d, b_rv3d, scene->camera, width, height);
851                 session->reset(buffer_params, session_params.samples);
852
853                 /* reset time */
854                 start_resize_time = 0.0;
855         }
856
857         /* Start rendering thread, if it's not running already. Do this
858          * after all scene data has been synced at least once. */
859         session->start();
860 }
861
862 bool BlenderSession::draw(int w, int h)
863 {
864         /* pause in redraw in case update is not being called due to final render */
865         session->set_pause(BlenderSync::get_session_pause(b_scene, background));
866
867         /* before drawing, we verify camera and viewport size changes, because
868          * we do not get update callbacks for those, we must detect them here */
869         if(session->ready_to_reset()) {
870                 bool reset = false;
871
872                 /* if dimensions changed, reset */
873                 if(width != w || height != h) {
874                         if(start_resize_time == 0.0) {
875                                 /* don't react immediately to resizes to avoid flickery resizing
876                                  * of the viewport, and some window managers changing the window
877                                  * size temporarily on unminimize */
878                                 start_resize_time = time_dt();
879                                 tag_redraw();
880                         }
881                         else if(time_dt() - start_resize_time < 0.2) {
882                                 tag_redraw();
883                         }
884                         else {
885                                 width = w;
886                                 height = h;
887                                 reset = true;
888                         }
889                 }
890
891                 /* try to acquire mutex. if we can't, come back later */
892                 if(!session->scene->mutex.try_lock()) {
893                         tag_update();
894                 }
895                 else {
896                         /* update camera from 3d view */
897
898                         sync->sync_view(b_v3d, b_rv3d, width, height);
899
900                         if(scene->camera->need_update)
901                                 reset = true;
902
903                         session->scene->mutex.unlock();
904                 }
905
906                 /* reset if requested */
907                 if(reset) {
908                         SessionParams session_params = BlenderSync::get_session_params(b_engine, b_userpref, b_scene, background);
909                         BufferParams buffer_params = BlenderSync::get_buffer_params(b_render, b_v3d, b_rv3d, scene->camera, width, height);
910                         bool session_pause = BlenderSync::get_session_pause(b_scene, background);
911
912                         if(session_pause == false) {
913                                 session->reset(buffer_params, session_params.samples);
914                                 start_resize_time = 0.0;
915                         }
916                 }
917         }
918         else {
919                 tag_update();
920         }
921
922         /* update status and progress for 3d view draw */
923         update_status_progress();
924
925         /* draw */
926         BufferParams buffer_params = BlenderSync::get_buffer_params(b_render, b_v3d, b_rv3d, scene->camera, width, height);
927         DeviceDrawParams draw_params;
928
929         if(session->params.display_buffer_linear) {
930                 draw_params.bind_display_space_shader_cb = function_bind(&BL::RenderEngine::bind_display_space_shader, &b_engine, b_scene);
931                 draw_params.unbind_display_space_shader_cb = function_bind(&BL::RenderEngine::unbind_display_space_shader, &b_engine);
932         }
933
934         return !session->draw(buffer_params, draw_params);
935 }
936
937 void BlenderSession::get_status(string& status, string& substatus)
938 {
939         session->progress.get_status(status, substatus);
940 }
941
942 void BlenderSession::get_progress(float& progress, double& total_time, double& render_time)
943 {
944         session->progress.get_time(total_time, render_time);
945         progress = session->progress.get_progress();
946 }
947
948 void BlenderSession::update_bake_progress()
949 {
950         float progress = session->progress.get_progress();
951
952         if(progress != last_progress) {
953                 b_engine.update_progress(progress);
954                 last_progress = progress;
955         }
956 }
957
958 void BlenderSession::update_status_progress()
959 {
960         string timestatus, status, substatus;
961         string scene_status = "";
962         float progress;
963         double total_time, remaining_time = 0, render_time;
964         char time_str[128];
965         float mem_used = (float)session->stats.mem_used / 1024.0f / 1024.0f;
966         float mem_peak = (float)session->stats.mem_peak / 1024.0f / 1024.0f;
967
968         get_status(status, substatus);
969         get_progress(progress, total_time, render_time);
970
971         if(progress > 0)
972                 remaining_time = (1.0 - (double)progress) * (render_time / (double)progress);
973
974         if(background) {
975                 scene_status += " | " + scene->name;
976                 if(b_rlay_name != "")
977                         scene_status += ", "  + b_rlay_name;
978
979                 if(b_rview_name != "")
980                         scene_status += ", " + b_rview_name;
981
982                 if(remaining_time > 0) {
983                         BLI_timecode_string_from_time_simple(time_str, sizeof(time_str), remaining_time);
984                         timestatus += "Remaining:" + string(time_str) + " | ";
985                 }
986
987                 timestatus += string_printf("Mem:%.2fM, Peak:%.2fM", (double)mem_used, (double)mem_peak);
988
989                 if(status.size() > 0)
990                         status = " | " + status;
991                 if(substatus.size() > 0)
992                         status += " | " + substatus;
993         }
994
995         double current_time = time_dt();
996         /* When rendering in a window, redraw the status at least once per second to keep the elapsed and remaining time up-to-date.
997          * For headless rendering, only report when something significant changes to keep the console output readable. */
998         if(status != last_status || (!headless && (current_time - last_status_time) > 1.0)) {
999                 b_engine.update_stats("", (timestatus + scene_status + status).c_str());
1000                 b_engine.update_memory_stats(mem_used, mem_peak);
1001                 last_status = status;
1002                 last_status_time = current_time;
1003         }
1004         if(progress != last_progress) {
1005                 b_engine.update_progress(progress);
1006                 last_progress = progress;
1007         }
1008
1009         if(session->progress.get_error()) {
1010                 string error = session->progress.get_error_message();
1011                 if(error != last_error) {
1012                         /* TODO(sergey): Currently C++ RNA API doesn't let us to
1013                          * use mnemonic name for the variable. Would be nice to
1014                          * have this figured out.
1015                          *
1016                          * For until then, 1 << 5 means RPT_ERROR.
1017                          */
1018                         b_engine.report(1 << 5, error.c_str());
1019                         b_engine.error_set(error.c_str());
1020                         last_error = error;
1021                 }
1022         }
1023 }
1024
1025 void BlenderSession::tag_update()
1026 {
1027         /* tell blender that we want to get another update callback */
1028         b_engine.tag_update();
1029 }
1030
1031 void BlenderSession::tag_redraw()
1032 {
1033         if(background) {
1034                 /* update stats and progress, only for background here because
1035                  * in 3d view we do it in draw for thread safety reasons */
1036                 update_status_progress();
1037
1038                 /* offline render, redraw if timeout passed */
1039                 if(time_dt() - last_redraw_time > 1.0) {
1040                         b_engine.tag_redraw();
1041                         last_redraw_time = time_dt();
1042                 }
1043         }
1044         else {
1045                 /* tell blender that we want to redraw */
1046                 b_engine.tag_redraw();
1047         }
1048 }
1049
1050 void BlenderSession::test_cancel()
1051 {
1052         /* test if we need to cancel rendering */
1053         if(background)
1054                 if(b_engine.test_break())
1055                         session->progress.set_cancel("Cancelled");
1056 }
1057
1058 /* builtin image file name is actually an image datablock name with
1059  * absolute sequence frame number concatenated via '@' character
1060  *
1061  * this function splits frame from builtin name
1062  */
1063 int BlenderSession::builtin_image_frame(const string &builtin_name)
1064 {
1065         int last = builtin_name.find_last_of('@');
1066         return atoi(builtin_name.substr(last + 1, builtin_name.size() - last - 1).c_str());
1067 }
1068
1069 void BlenderSession::builtin_image_info(const string &builtin_name,
1070                                         void *builtin_data,
1071                                         ImageMetaData& metadata)
1072 {
1073         /* empty image */
1074         metadata.width = 1;
1075         metadata.height = 1;
1076
1077         if(!builtin_data)
1078                 return;
1079
1080         /* recover ID pointer */
1081         PointerRNA ptr;
1082         RNA_id_pointer_create((ID*)builtin_data, &ptr);
1083         BL::ID b_id(ptr);
1084
1085         if(b_id.is_a(&RNA_Image)) {
1086                 /* image data */
1087                 BL::Image b_image(b_id);
1088
1089                 metadata.builtin_free_cache = !b_image.has_data();
1090                 metadata.is_float = b_image.is_float();
1091                 metadata.width = b_image.size()[0];
1092                 metadata.height = b_image.size()[1];
1093                 metadata.depth = 1;
1094                 metadata.channels = b_image.channels();
1095         }
1096         else if(b_id.is_a(&RNA_Object)) {
1097                 /* smoke volume data */
1098                 BL::Object b_ob(b_id);
1099                 BL::SmokeDomainSettings b_domain = object_smoke_domain_find(b_ob);
1100
1101                 metadata.is_float = true;
1102                 metadata.depth = 1;
1103                 metadata.channels = 1;
1104
1105                 if(!b_domain)
1106                         return;
1107
1108                 if(builtin_name == Attribute::standard_name(ATTR_STD_VOLUME_DENSITY) ||
1109                    builtin_name == Attribute::standard_name(ATTR_STD_VOLUME_FLAME) ||
1110                    builtin_name == Attribute::standard_name(ATTR_STD_VOLUME_HEAT) ||
1111                    builtin_name == Attribute::standard_name(ATTR_STD_VOLUME_TEMPERATURE))
1112                         metadata.channels = 1;
1113                 else if(builtin_name == Attribute::standard_name(ATTR_STD_VOLUME_COLOR))
1114                         metadata.channels = 4;
1115                 else if(builtin_name == Attribute::standard_name(ATTR_STD_VOLUME_VELOCITY))
1116                         metadata.channels = 3;
1117                 else
1118                         return;
1119
1120                 int3 resolution = get_int3(b_domain.domain_resolution());
1121                 int amplify = (b_domain.use_high_resolution())? b_domain.amplify() + 1: 1;
1122
1123                 /* Velocity and heat data is always low-resolution. */
1124                 if(builtin_name == Attribute::standard_name(ATTR_STD_VOLUME_VELOCITY) ||
1125                    builtin_name == Attribute::standard_name(ATTR_STD_VOLUME_HEAT))
1126                 {
1127                         amplify = 1;
1128                 }
1129
1130                 metadata.width = resolution.x * amplify;
1131                 metadata.height = resolution.y * amplify;
1132                 metadata.depth = resolution.z * amplify;
1133         }
1134         else {
1135                 /* TODO(sergey): Check we're indeed in shader node tree. */
1136                 PointerRNA ptr;
1137                 RNA_pointer_create(NULL, &RNA_Node, builtin_data, &ptr);
1138                 BL::Node b_node(ptr);
1139                 if(b_node.is_a(&RNA_ShaderNodeTexPointDensity)) {
1140                         BL::ShaderNodeTexPointDensity b_point_density_node(b_node);
1141                         metadata.channels = 4;
1142                         metadata.width = b_point_density_node.resolution();
1143                         metadata.height = metadata.width;
1144                         metadata.depth = metadata.width;
1145                         metadata.is_float = true;
1146                 }
1147         }
1148 }
1149
1150 bool BlenderSession::builtin_image_pixels(const string &builtin_name,
1151                                           void *builtin_data,
1152                                           unsigned char *pixels,
1153                                           const size_t pixels_size,
1154                                           const bool free_cache)
1155 {
1156         if(!builtin_data) {
1157                 return false;
1158         }
1159
1160         const int frame = builtin_image_frame(builtin_name);
1161
1162         PointerRNA ptr;
1163         RNA_id_pointer_create((ID*)builtin_data, &ptr);
1164         BL::Image b_image(ptr);
1165
1166         const int width = b_image.size()[0];
1167         const int height = b_image.size()[1];
1168         const int channels = b_image.channels();
1169
1170         unsigned char *image_pixels = image_get_pixels_for_frame(b_image, frame);
1171         const size_t num_pixels = ((size_t)width) * height;
1172
1173         if(image_pixels && num_pixels * channels == pixels_size) {
1174                 memcpy(pixels, image_pixels, pixels_size * sizeof(unsigned char));
1175         }
1176         else {
1177                 if(channels == 1) {
1178                         memset(pixels, 0, pixels_size * sizeof(unsigned char));
1179                 }
1180                 else {
1181                         const size_t num_pixels_safe = pixels_size / channels;
1182                         unsigned char *cp = pixels;
1183                         for(size_t i = 0; i < num_pixels_safe; i++, cp += channels) {
1184                                 cp[0] = 255;
1185                                 cp[1] = 0;
1186                                 cp[2] = 255;
1187                                 if(channels == 4) {
1188                                         cp[3] = 255;
1189                                 }
1190                         }
1191                 }
1192         }
1193
1194         if(image_pixels) {
1195                 MEM_freeN(image_pixels);
1196         }
1197
1198         /* Free image buffers to save memory during render. */
1199         if(free_cache) {
1200                 b_image.buffers_free();
1201         }
1202
1203         /* Premultiply, byte images are always straight for Blender. */
1204         unsigned char *cp = pixels;
1205         for(size_t i = 0; i < num_pixels; i++, cp += channels) {
1206                 cp[0] = (cp[0] * cp[3]) >> 8;
1207                 cp[1] = (cp[1] * cp[3]) >> 8;
1208                 cp[2] = (cp[2] * cp[3]) >> 8;
1209         }
1210         return true;
1211 }
1212
1213 bool BlenderSession::builtin_image_float_pixels(const string &builtin_name,
1214                                                 void *builtin_data,
1215                                                 float *pixels,
1216                                                 const size_t pixels_size,
1217                                                 const bool free_cache)
1218 {
1219         if(!builtin_data) {
1220                 return false;
1221         }
1222
1223         PointerRNA ptr;
1224         RNA_id_pointer_create((ID*)builtin_data, &ptr);
1225         BL::ID b_id(ptr);
1226
1227         if(b_id.is_a(&RNA_Image)) {
1228                 /* image data */
1229                 BL::Image b_image(b_id);
1230                 int frame = builtin_image_frame(builtin_name);
1231
1232                 const int width = b_image.size()[0];
1233                 const int height = b_image.size()[1];
1234                 const int channels = b_image.channels();
1235
1236                 float *image_pixels;
1237                 image_pixels = image_get_float_pixels_for_frame(b_image, frame);
1238                 const size_t num_pixels = ((size_t)width) * height;
1239
1240                 if(image_pixels && num_pixels * channels == pixels_size) {
1241                         memcpy(pixels, image_pixels, pixels_size * sizeof(float));
1242                 }
1243                 else {
1244                         if(channels == 1) {
1245                                 memset(pixels, 0, num_pixels * sizeof(float));
1246                         }
1247                         else {
1248                                 const size_t num_pixels_safe = pixels_size / channels;
1249                                 float *fp = pixels;
1250                                 for(int i = 0; i < num_pixels_safe; i++, fp += channels) {
1251                                         fp[0] = 1.0f;
1252                                         fp[1] = 0.0f;
1253                                         fp[2] = 1.0f;
1254                                         if(channels == 4) {
1255                                                 fp[3] = 1.0f;
1256                                         }
1257                                 }
1258                         }
1259                 }
1260
1261                 if(image_pixels) {
1262                         MEM_freeN(image_pixels);
1263                 }
1264
1265                 /* Free image buffers to save memory during render. */
1266                 if(free_cache) {
1267                         b_image.buffers_free();
1268                 }
1269
1270                 return true;
1271         }
1272         else if(b_id.is_a(&RNA_Object)) {
1273                 /* smoke volume data */
1274                 BL::Object b_ob(b_id);
1275                 BL::SmokeDomainSettings b_domain = object_smoke_domain_find(b_ob);
1276
1277                 if(!b_domain) {
1278                         return false;
1279                 }
1280
1281                 int3 resolution = get_int3(b_domain.domain_resolution());
1282                 int length, amplify = (b_domain.use_high_resolution())? b_domain.amplify() + 1: 1;
1283
1284                 /* Velocity and heat data is always low-resolution. */
1285                 if(builtin_name == Attribute::standard_name(ATTR_STD_VOLUME_VELOCITY) ||
1286                    builtin_name == Attribute::standard_name(ATTR_STD_VOLUME_HEAT))
1287                 {
1288                         amplify = 1;
1289                 }
1290
1291                 const int width = resolution.x * amplify;
1292                 const int height = resolution.y * amplify;
1293                 const int depth = resolution.z * amplify;
1294                 const size_t num_pixels = ((size_t)width) * height * depth;
1295
1296                 if(builtin_name == Attribute::standard_name(ATTR_STD_VOLUME_DENSITY)) {
1297                         SmokeDomainSettings_density_grid_get_length(&b_domain.ptr, &length);
1298                         if(length == num_pixels) {
1299                                 SmokeDomainSettings_density_grid_get(&b_domain.ptr, pixels);
1300                                 return true;
1301                         }
1302                 }
1303                 else if(builtin_name == Attribute::standard_name(ATTR_STD_VOLUME_FLAME)) {
1304                         /* this is in range 0..1, and interpreted by the OpenGL smoke viewer
1305                          * as 1500..3000 K with the first part faded to zero density */
1306                         SmokeDomainSettings_flame_grid_get_length(&b_domain.ptr, &length);
1307                         if(length == num_pixels) {
1308                                 SmokeDomainSettings_flame_grid_get(&b_domain.ptr, pixels);
1309                                 return true;
1310                         }
1311                 }
1312                 else if(builtin_name == Attribute::standard_name(ATTR_STD_VOLUME_COLOR)) {
1313                         /* the RGB is "premultiplied" by density for better interpolation results */
1314                         SmokeDomainSettings_color_grid_get_length(&b_domain.ptr, &length);
1315                         if(length == num_pixels*4) {
1316                                 SmokeDomainSettings_color_grid_get(&b_domain.ptr, pixels);
1317                                 return true;
1318                         }
1319                 }
1320                 else if(builtin_name == Attribute::standard_name(ATTR_STD_VOLUME_VELOCITY)) {
1321                         SmokeDomainSettings_velocity_grid_get_length(&b_domain.ptr, &length);
1322                         if(length == num_pixels*3) {
1323                                 SmokeDomainSettings_velocity_grid_get(&b_domain.ptr, pixels);
1324                                 return true;
1325                         }
1326                 }
1327                 else if(builtin_name == Attribute::standard_name(ATTR_STD_VOLUME_HEAT)) {
1328                         SmokeDomainSettings_heat_grid_get_length(&b_domain.ptr, &length);
1329                         if(length == num_pixels) {
1330                                 SmokeDomainSettings_heat_grid_get(&b_domain.ptr, pixels);
1331                                 return true;
1332                         }
1333                 }
1334                 else if(builtin_name == Attribute::standard_name(ATTR_STD_VOLUME_TEMPERATURE)) {
1335                         SmokeDomainSettings_temperature_grid_get_length(&b_domain.ptr, &length);
1336                         if(length == num_pixels) {
1337                                 SmokeDomainSettings_temperature_grid_get(&b_domain.ptr, pixels);
1338                                 return true;
1339                         }
1340                 }
1341                 else {
1342                         fprintf(stderr,
1343                                 "Cycles error: unknown volume attribute %s, skipping\n",
1344                                 builtin_name.c_str());
1345                         pixels[0] = 0.0f;
1346                         return false;
1347                 }
1348
1349                 fprintf(stderr, "Cycles error: unexpected smoke volume resolution, skipping\n");
1350         }
1351         else {
1352                 /* We originally were passing view_layer here but in reality we need a
1353                  * a depsgraph to pass to the RE_point_density_minmax() function.
1354                  */
1355                 /* TODO(sergey): Check we're indeed in shader node tree. */
1356                 PointerRNA ptr;
1357                 RNA_pointer_create(NULL, &RNA_Node, builtin_data, &ptr);
1358                 BL::Node b_node(ptr);
1359                 if(b_node.is_a(&RNA_ShaderNodeTexPointDensity)) {
1360                         BL::ShaderNodeTexPointDensity b_point_density_node(b_node);
1361                         int length;
1362                         b_point_density_node.calc_point_density(b_depsgraph, &length, &pixels);
1363                 }
1364         }
1365
1366         return false;
1367 }
1368
1369 void BlenderSession::builtin_images_load()
1370 {
1371         /* Force builtin images to be loaded along with Blender data sync. This
1372          * is needed because we may be reading from depsgraph evaluated data which
1373          * can be freed by Blender before Cycles reads it. */
1374         ImageManager *manager = session->scene->image_manager;
1375         Device *device = session->device;
1376         manager->device_load_builtin(device, session->scene, session->progress);
1377 }
1378
1379 void BlenderSession::update_resumable_tile_manager(int num_samples)
1380 {
1381         const int num_resumable_chunks = BlenderSession::num_resumable_chunks,
1382                   current_resumable_chunk = BlenderSession::current_resumable_chunk;
1383         if(num_resumable_chunks == 0) {
1384                 return;
1385         }
1386
1387         const int num_samples_per_chunk = (int)ceilf((float)num_samples / num_resumable_chunks);
1388
1389         int range_start_sample, range_num_samples;
1390         if(current_resumable_chunk != 0) {
1391                 /* Single chunk rendering. */
1392                 range_start_sample = num_samples_per_chunk * (current_resumable_chunk - 1);
1393                 range_num_samples = num_samples_per_chunk;
1394         }
1395         else {
1396                 /* Ranged-chunks. */
1397                 const int num_chunks = end_resumable_chunk - start_resumable_chunk + 1;
1398                 range_start_sample = num_samples_per_chunk * (start_resumable_chunk - 1);
1399                 range_num_samples = num_chunks * num_samples_per_chunk;
1400         }
1401         /* Make sure we don't overshoot. */
1402         if(range_start_sample + range_num_samples > num_samples) {
1403                 range_num_samples = num_samples - range_num_samples;
1404         }
1405
1406         VLOG(1) << "Samples range start is " << range_start_sample << ", "
1407                 << "number of samples to render is " << range_num_samples;
1408
1409         scene->integrator->start_sample = range_start_sample;
1410         scene->integrator->tag_update(scene);
1411
1412         session->tile_manager.range_start_sample = range_start_sample;
1413         session->tile_manager.range_num_samples = range_num_samples;
1414 }
1415
1416 void BlenderSession::free_blender_memory_if_possible()
1417 {
1418         if(!background) {
1419                 /* During interactive render we can not free anything: attempts to save
1420                  * memory would cause things to be allocated and evaluated for every
1421                  * updated sample.
1422                  */
1423                 return;
1424         }
1425         b_engine.free_blender_memory();
1426 }
1427
1428 CCL_NAMESPACE_END