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