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