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