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