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