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