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