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