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