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