Fix T57320: Crash when adding a linked scene, then deleting it.
[blender.git] / intern / cycles / render / 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 <string.h>
18 #include <limits.h>
19
20 #include "render/buffers.h"
21 #include "render/camera.h"
22 #include "device/device.h"
23 #include "render/graph.h"
24 #include "render/integrator.h"
25 #include "render/mesh.h"
26 #include "render/object.h"
27 #include "render/scene.h"
28 #include "render/session.h"
29 #include "render/bake.h"
30
31 #include "util/util_foreach.h"
32 #include "util/util_function.h"
33 #include "util/util_logging.h"
34 #include "util/util_math.h"
35 #include "util/util_opengl.h"
36 #include "util/util_task.h"
37 #include "util/util_time.h"
38
39 CCL_NAMESPACE_BEGIN
40
41 /* Note about  preserve_tile_device option for tile manager:
42  * progressive refine and viewport rendering does requires tiles to
43  * always be allocated for the same device
44  */
45 Session::Session(const SessionParams& params_)
46 : params(params_),
47   tile_manager(params.progressive, params.samples, params.tile_size, params.start_resolution,
48        params.background == false || params.progressive_refine, params.background, params.tile_order,
49        max(params.device.multi_devices.size(), 1), params.pixel_size),
50   stats()
51 {
52         device_use_gl = ((params.device.type != DEVICE_CPU) && !params.background);
53
54         TaskScheduler::init(params.threads);
55
56         device = Device::create(params.device, stats, params.background);
57
58         if(params.background && !params.write_render_cb) {
59                 buffers = NULL;
60                 display = NULL;
61         }
62         else {
63                 buffers = new RenderBuffers(device);
64                 display = new DisplayBuffer(device, params.display_buffer_linear);
65         }
66
67         session_thread = NULL;
68         scene = NULL;
69
70         reset_time = 0.0;
71         last_update_time = 0.0;
72
73         delayed_reset.do_reset = false;
74         delayed_reset.samples = 0;
75
76         display_outdated = false;
77         gpu_draw_ready = false;
78         gpu_need_tonemap = false;
79         pause = false;
80         kernels_loaded = false;
81
82         /* TODO(sergey): Check if it's indeed optimal value for the split kernel. */
83         max_closure_global = 1;
84 }
85
86 Session::~Session()
87 {
88         if(session_thread) {
89                 /* wait for session thread to end */
90                 progress.set_cancel("Exiting");
91
92                 gpu_need_tonemap = false;
93                 gpu_need_tonemap_cond.notify_all();
94
95                 {
96                         thread_scoped_lock pause_lock(pause_mutex);
97                         pause = false;
98                 }
99                 pause_cond.notify_all();
100
101                 wait();
102         }
103
104         if(params.write_render_cb) {
105                 /* tonemap and write out image if requested */
106                 delete display;
107
108                 display = new DisplayBuffer(device, false);
109                 display->reset(buffers->params);
110                 tonemap(params.samples);
111
112                 int w = display->draw_width;
113                 int h = display->draw_height;
114                 uchar4 *pixels = display->rgba_byte.copy_from_device(0, w, h);
115                 params.write_render_cb((uchar*)pixels, w, h, 4);
116         }
117
118         /* clean up */
119         tile_manager.device_free();
120
121         delete buffers;
122         delete display;
123         delete scene;
124         delete device;
125
126         TaskScheduler::exit();
127 }
128
129 void Session::start()
130 {
131         session_thread = new thread(function_bind(&Session::run, this));
132 }
133
134 bool Session::ready_to_reset()
135 {
136         double dt = time_dt() - reset_time;
137
138         if(!display_outdated)
139                 return (dt > params.reset_timeout);
140         else
141                 return (dt > params.cancel_timeout);
142 }
143
144 /* GPU Session */
145
146 void Session::reset_gpu(BufferParams& buffer_params, int samples)
147 {
148         thread_scoped_lock pause_lock(pause_mutex);
149
150         /* block for buffer access and reset immediately. we can't do this
151          * in the thread, because we need to allocate an OpenGL buffer, and
152          * that only works in the main thread */
153         thread_scoped_lock display_lock(display_mutex);
154         thread_scoped_lock buffers_lock(buffers_mutex);
155
156         display_outdated = true;
157         reset_time = time_dt();
158
159         reset_(buffer_params, samples);
160
161         gpu_need_tonemap = false;
162         gpu_need_tonemap_cond.notify_all();
163
164         pause_cond.notify_all();
165 }
166
167 bool Session::draw_gpu(BufferParams& buffer_params, DeviceDrawParams& draw_params)
168 {
169         /* block for buffer access */
170         thread_scoped_lock display_lock(display_mutex);
171
172         /* first check we already rendered something */
173         if(gpu_draw_ready) {
174                 /* then verify the buffers have the expected size, so we don't
175                  * draw previous results in a resized window */
176                 if(!buffer_params.modified(display->params)) {
177                         /* for CUDA we need to do tonemapping still, since we can
178                          * only access GL buffers from the main thread */
179                         if(gpu_need_tonemap) {
180                                 thread_scoped_lock buffers_lock(buffers_mutex);
181                                 tonemap(tile_manager.state.sample);
182                                 gpu_need_tonemap = false;
183                                 gpu_need_tonemap_cond.notify_all();
184                         }
185
186                         display->draw(device, draw_params);
187
188                         if(display_outdated && (time_dt() - reset_time) > params.text_timeout)
189                                 return false;
190
191                         return true;
192                 }
193         }
194
195         return false;
196 }
197
198 void Session::run_gpu()
199 {
200         bool tiles_written = false;
201
202         reset_time = time_dt();
203         last_update_time = time_dt();
204
205         progress.set_render_start_time();
206
207         while(!progress.get_cancel()) {
208                 /* advance to next tile */
209                 bool no_tiles = !tile_manager.next();
210
211                 if(params.background) {
212                         /* if no work left and in background mode, we can stop immediately */
213                         if(no_tiles) {
214                                 progress.set_status("Finished");
215                                 break;
216                         }
217                 }
218                 else {
219                         /* if in interactive mode, and we are either paused or done for now,
220                          * wait for pause condition notify to wake up again */
221                         thread_scoped_lock pause_lock(pause_mutex);
222
223                         if(!pause && !tile_manager.done()) {
224                                 /* reset could have happened after no_tiles was set, before this lock.
225                                  * in this case we shall not wait for pause condition
226                                  */
227                         }
228                         else if(pause || no_tiles) {
229                                 update_status_time(pause, no_tiles);
230
231                                 while(1) {
232                                         scoped_timer pause_timer;
233                                         pause_cond.wait(pause_lock);
234                                         if(pause) {
235                                                 progress.add_skip_time(pause_timer, params.background);
236                                         }
237
238                                         update_status_time(pause, no_tiles);
239                                         progress.set_update();
240
241                                         if(!pause)
242                                                 break;
243                                 }
244                         }
245
246                         if(progress.get_cancel())
247                                 break;
248                 }
249
250                 if(!no_tiles) {
251                         /* update scene */
252                         scoped_timer update_timer;
253                         update_scene();
254                         progress.add_skip_time(update_timer, params.background);
255
256                         if(!device->error_message().empty())
257                                 progress.set_error(device->error_message());
258
259                         if(progress.get_cancel())
260                                 break;
261                 }
262
263                 if(!no_tiles) {
264                         /* buffers mutex is locked entirely while rendering each
265                          * sample, and released/reacquired on each iteration to allow
266                          * reset and draw in between */
267                         thread_scoped_lock buffers_lock(buffers_mutex);
268
269                         /* update status and timing */
270                         update_status_time();
271
272                         /* render */
273                         render();
274
275                         device->task_wait();
276
277                         if(!device->error_message().empty())
278                                 progress.set_cancel(device->error_message());
279
280                         /* update status and timing */
281                         update_status_time();
282
283                         gpu_need_tonemap = true;
284                         gpu_draw_ready = true;
285                         progress.set_update();
286
287                         /* wait for tonemap */
288                         if(!params.background) {
289                                 while(gpu_need_tonemap) {
290                                         if(progress.get_cancel())
291                                                 break;
292
293                                         gpu_need_tonemap_cond.wait(buffers_lock);
294                                 }
295                         }
296
297                         if(!device->error_message().empty())
298                                 progress.set_error(device->error_message());
299
300                         tiles_written = update_progressive_refine(progress.get_cancel());
301
302                         if(progress.get_cancel())
303                                 break;
304                 }
305         }
306
307         if(!tiles_written)
308                 update_progressive_refine(true);
309 }
310
311 /* CPU Session */
312
313 void Session::reset_cpu(BufferParams& buffer_params, int samples)
314 {
315         thread_scoped_lock reset_lock(delayed_reset.mutex);
316         thread_scoped_lock pause_lock(pause_mutex);
317
318         display_outdated = true;
319         reset_time = time_dt();
320
321         delayed_reset.params = buffer_params;
322         delayed_reset.samples = samples;
323         delayed_reset.do_reset = true;
324         device->task_cancel();
325
326         pause_cond.notify_all();
327 }
328
329 bool Session::draw_cpu(BufferParams& buffer_params, DeviceDrawParams& draw_params)
330 {
331         thread_scoped_lock display_lock(display_mutex);
332
333         /* first check we already rendered something */
334         if(display->draw_ready()) {
335                 /* then verify the buffers have the expected size, so we don't
336                  * draw previous results in a resized window */
337                 if(!buffer_params.modified(display->params)) {
338                         display->draw(device, draw_params);
339
340                         if(display_outdated && (time_dt() - reset_time) > params.text_timeout)
341                                 return false;
342
343                         return true;
344                 }
345         }
346
347         return false;
348 }
349
350 bool Session::acquire_tile(Device *tile_device, RenderTile& rtile)
351 {
352         if(progress.get_cancel()) {
353                 if(params.progressive_refine == false) {
354                         /* for progressive refine current sample should be finished for all tiles */
355                         return false;
356                 }
357         }
358
359         thread_scoped_lock tile_lock(tile_mutex);
360
361         /* get next tile from manager */
362         Tile *tile;
363         int device_num = device->device_number(tile_device);
364
365         if(!tile_manager.next_tile(tile, device_num))
366                 return false;
367
368         /* fill render tile */
369         rtile.x = tile_manager.state.buffer.full_x + tile->x;
370         rtile.y = tile_manager.state.buffer.full_y + tile->y;
371         rtile.w = tile->w;
372         rtile.h = tile->h;
373         rtile.start_sample = tile_manager.state.sample;
374         rtile.num_samples = tile_manager.state.num_samples;
375         rtile.resolution = tile_manager.state.resolution_divider;
376         rtile.tile_index = tile->index;
377         rtile.task = (tile->state == Tile::DENOISE)? RenderTile::DENOISE: RenderTile::PATH_TRACE;
378
379         tile_lock.unlock();
380
381         /* in case of a permanent buffer, return it, otherwise we will allocate
382          * a new temporary buffer */
383         if(buffers) {
384                 tile_manager.state.buffer.get_offset_stride(rtile.offset, rtile.stride);
385
386                 rtile.buffer = buffers->buffer.device_pointer;
387                 rtile.buffers = buffers;
388
389                 device->map_tile(tile_device, rtile);
390
391                 return true;
392         }
393
394         if(tile->buffers == NULL) {
395                 /* fill buffer parameters */
396                 BufferParams buffer_params = tile_manager.params;
397                 buffer_params.full_x = rtile.x;
398                 buffer_params.full_y = rtile.y;
399                 buffer_params.width = rtile.w;
400                 buffer_params.height = rtile.h;
401
402                 /* allocate buffers */
403                 tile->buffers = new RenderBuffers(tile_device);
404                 tile->buffers->reset(buffer_params);
405         }
406
407         tile->buffers->params.get_offset_stride(rtile.offset, rtile.stride);
408
409         rtile.buffer = tile->buffers->buffer.device_pointer;
410         rtile.buffers = tile->buffers;
411         rtile.sample = tile_manager.state.sample;
412
413         /* this will tag tile as IN PROGRESS in blender-side render pipeline,
414          * which is needed to highlight currently rendering tile before first
415          * sample was processed for it
416          */
417         update_tile_sample(rtile);
418
419         return true;
420 }
421
422 void Session::update_tile_sample(RenderTile& rtile)
423 {
424         thread_scoped_lock tile_lock(tile_mutex);
425
426         if(update_render_tile_cb) {
427                 if(params.progressive_refine == false) {
428                         /* todo: optimize this by making it thread safe and removing lock */
429
430                         update_render_tile_cb(rtile, true);
431                 }
432         }
433
434         update_status_time();
435 }
436
437 void Session::release_tile(RenderTile& rtile)
438 {
439         thread_scoped_lock tile_lock(tile_mutex);
440
441         progress.add_finished_tile(rtile.task == RenderTile::DENOISE);
442
443         bool delete_tile;
444
445         if(tile_manager.finish_tile(rtile.tile_index, delete_tile)) {
446                 if(write_render_tile_cb && params.progressive_refine == false) {
447                         write_render_tile_cb(rtile);
448                 }
449
450                 if(delete_tile) {
451                         delete rtile.buffers;
452                         tile_manager.state.tiles[rtile.tile_index].buffers = NULL;
453                 }
454         }
455         else {
456                 if(update_render_tile_cb && params.progressive_refine == false) {
457                         update_render_tile_cb(rtile, false);
458                 }
459         }
460
461         update_status_time();
462 }
463
464 void Session::map_neighbor_tiles(RenderTile *tiles, Device *tile_device)
465 {
466         thread_scoped_lock tile_lock(tile_mutex);
467
468         int center_idx = tiles[4].tile_index;
469         assert(tile_manager.state.tiles[center_idx].state == Tile::DENOISE);
470         BufferParams buffer_params = tile_manager.params;
471         int4 image_region = make_int4(buffer_params.full_x, buffer_params.full_y,
472                                       buffer_params.full_x + buffer_params.width, buffer_params.full_y + buffer_params.height);
473
474         for(int dy = -1, i = 0; dy <= 1; dy++) {
475                 for(int dx = -1; dx <= 1; dx++, i++) {
476                         int px = tiles[4].x + dx*params.tile_size.x;
477                         int py = tiles[4].y + dy*params.tile_size.y;
478                         if(px >= image_region.x && py >= image_region.y &&
479                            px <  image_region.z && py <  image_region.w) {
480                                 int tile_index = center_idx + dy*tile_manager.state.tile_stride + dx;
481                                 Tile *tile = &tile_manager.state.tiles[tile_index];
482                                 assert(tile->buffers);
483
484                                 tiles[i].buffer = tile->buffers->buffer.device_pointer;
485                                 tiles[i].x = tile_manager.state.buffer.full_x + tile->x;
486                                 tiles[i].y = tile_manager.state.buffer.full_y + tile->y;
487                                 tiles[i].w = tile->w;
488                                 tiles[i].h = tile->h;
489                                 tiles[i].buffers = tile->buffers;
490
491                                 tile->buffers->params.get_offset_stride(tiles[i].offset, tiles[i].stride);
492                         }
493                         else {
494                                 tiles[i].buffer = (device_ptr)NULL;
495                                 tiles[i].buffers = NULL;
496                                 tiles[i].x = clamp(px, image_region.x, image_region.z);
497                                 tiles[i].y = clamp(py, image_region.y, image_region.w);
498                                 tiles[i].w = tiles[i].h = 0;
499                         }
500                 }
501         }
502
503         assert(tiles[4].buffers);
504         device->map_neighbor_tiles(tile_device, tiles);
505
506         /* The denoised result is written back to the original tile. */
507         tiles[9] = tiles[4];
508 }
509
510 void Session::unmap_neighbor_tiles(RenderTile *tiles, Device *tile_device)
511 {
512         thread_scoped_lock tile_lock(tile_mutex);
513         device->unmap_neighbor_tiles(tile_device, tiles);
514 }
515
516 void Session::run_cpu()
517 {
518         bool tiles_written = false;
519
520         last_update_time = time_dt();
521
522         {
523                 /* reset once to start */
524                 thread_scoped_lock reset_lock(delayed_reset.mutex);
525                 thread_scoped_lock buffers_lock(buffers_mutex);
526                 thread_scoped_lock display_lock(display_mutex);
527
528                 reset_(delayed_reset.params, delayed_reset.samples);
529                 delayed_reset.do_reset = false;
530         }
531
532         while(!progress.get_cancel()) {
533                 /* advance to next tile */
534                 bool no_tiles = !tile_manager.next();
535                 bool need_tonemap = false;
536
537                 if(params.background) {
538                         /* if no work left and in background mode, we can stop immediately */
539                         if(no_tiles) {
540                                 progress.set_status("Finished");
541                                 break;
542                         }
543                 }
544                 else {
545                         /* if in interactive mode, and we are either paused or done for now,
546                          * wait for pause condition notify to wake up again */
547                         thread_scoped_lock pause_lock(pause_mutex);
548
549                         if(!pause && delayed_reset.do_reset) {
550                                 /* reset once to start */
551                                 thread_scoped_lock reset_lock(delayed_reset.mutex);
552                                 thread_scoped_lock buffers_lock(buffers_mutex);
553                                 thread_scoped_lock display_lock(display_mutex);
554
555                                 reset_(delayed_reset.params, delayed_reset.samples);
556                                 delayed_reset.do_reset = false;
557                         }
558                         else if(pause || no_tiles) {
559                                 update_status_time(pause, no_tiles);
560
561                                 while(1) {
562                                         scoped_timer pause_timer;
563                                         pause_cond.wait(pause_lock);
564                                         if(pause) {
565                                                 progress.add_skip_time(pause_timer, params.background);
566                                         }
567
568                                         update_status_time(pause, no_tiles);
569                                         progress.set_update();
570
571                                         if(!pause)
572                                                 break;
573                                 }
574                         }
575
576                         if(progress.get_cancel())
577                                 break;
578                 }
579
580                 if(!no_tiles) {
581                         /* buffers mutex is locked entirely while rendering each
582                          * sample, and released/reacquired on each iteration to allow
583                          * reset and draw in between */
584                         thread_scoped_lock buffers_lock(buffers_mutex);
585
586                         /* update scene */
587                         scoped_timer update_timer;
588                         update_scene();
589                         progress.add_skip_time(update_timer, params.background);
590
591                         if(!device->error_message().empty())
592                                 progress.set_error(device->error_message());
593
594                         if(progress.get_cancel())
595                                 break;
596
597                         /* update status and timing */
598                         update_status_time();
599
600                         /* render */
601                         render();
602
603                         /* update status and timing */
604                         update_status_time();
605
606                         if(!params.background)
607                                 need_tonemap = true;
608
609                         if(!device->error_message().empty())
610                                 progress.set_error(device->error_message());
611                 }
612
613                 device->task_wait();
614
615                 {
616                         thread_scoped_lock reset_lock(delayed_reset.mutex);
617                         thread_scoped_lock buffers_lock(buffers_mutex);
618                         thread_scoped_lock display_lock(display_mutex);
619
620                         if(delayed_reset.do_reset) {
621                                 /* reset rendering if request from main thread */
622                                 delayed_reset.do_reset = false;
623                                 reset_(delayed_reset.params, delayed_reset.samples);
624                         }
625                         else if(need_tonemap) {
626                                 /* tonemap only if we do not reset, we don't we don't
627                                  * want to show the result of an incomplete sample */
628                                 tonemap(tile_manager.state.sample);
629                         }
630
631                         if(!device->error_message().empty())
632                                 progress.set_error(device->error_message());
633
634                         tiles_written = update_progressive_refine(progress.get_cancel());
635                 }
636
637                 progress.set_update();
638         }
639
640         if(!tiles_written)
641                 update_progressive_refine(true);
642 }
643
644 DeviceRequestedFeatures Session::get_requested_device_features()
645 {
646         /* TODO(sergey): Consider moving this to the Scene level. */
647         DeviceRequestedFeatures requested_features;
648         requested_features.experimental = params.experimental;
649
650         scene->shader_manager->get_requested_features(
651                 scene,
652                 &requested_features);
653         if(!params.background) {
654                 /* Avoid too much re-compilations for viewport render. */
655                 requested_features.max_nodes_group = NODE_GROUP_LEVEL_MAX;
656                 requested_features.nodes_features = NODE_FEATURE_ALL;
657         }
658
659         /* This features are not being tweaked as often as shaders,
660          * so could be done selective magic for the viewport as well.
661          */
662         requested_features.use_hair = false;
663         requested_features.use_object_motion = false;
664         requested_features.use_camera_motion = scene->camera->use_motion();
665         foreach(Object *object, scene->objects) {
666                 Mesh *mesh = object->mesh;
667                 if(mesh->num_curves()) {
668                         requested_features.use_hair = true;
669                 }
670                 requested_features.use_object_motion |= object->use_motion() | mesh->use_motion_blur;
671                 requested_features.use_camera_motion |= mesh->use_motion_blur;
672 #ifdef WITH_OPENSUBDIV
673                 if(mesh->subdivision_type != Mesh::SUBDIVISION_NONE) {
674                         requested_features.use_patch_evaluation = true;
675                 }
676 #endif
677                 if(object->is_shadow_catcher) {
678                         requested_features.use_shadow_tricks = true;
679                 }
680         }
681
682         BakeManager *bake_manager = scene->bake_manager;
683         requested_features.use_baking = bake_manager->get_baking();
684         requested_features.use_integrator_branched = (scene->integrator->method == Integrator::BRANCHED_PATH);
685         requested_features.use_denoising = params.use_denoising;
686
687         return requested_features;
688 }
689
690 void Session::load_kernels(bool lock_scene)
691 {
692         thread_scoped_lock scene_lock;
693         if(lock_scene) {
694                 scene_lock = thread_scoped_lock(scene->mutex);
695         }
696
697         DeviceRequestedFeatures requested_features = get_requested_device_features();
698
699         if(!kernels_loaded || loaded_kernel_features.modified(requested_features)) {
700                 progress.set_status("Loading render kernels (may take a few minutes the first time)");
701
702                 scoped_timer timer;
703
704                 VLOG(2) << "Requested features:\n" << requested_features;
705                 if(!device->load_kernels(requested_features)) {
706                         string message = device->error_message();
707                         if(message.empty())
708                                 message = "Failed loading render kernel, see console for errors";
709
710                         progress.set_error(message);
711                         progress.set_status("Error", message);
712                         progress.set_update();
713                         return;
714                 }
715
716                 progress.add_skip_time(timer, false);
717                 VLOG(1) << "Total time spent loading kernels: " << time_dt() - timer.get_start();
718
719                 kernels_loaded = true;
720                 loaded_kernel_features = requested_features;
721         }
722 }
723
724 void Session::run()
725 {
726         /* load kernels */
727         load_kernels();
728
729         /* session thread loop */
730         progress.set_status("Waiting for render to start");
731
732         /* run */
733         if(!progress.get_cancel()) {
734                 /* reset number of rendered samples */
735                 progress.reset_sample();
736
737                 if(device_use_gl)
738                         run_gpu();
739                 else
740                         run_cpu();
741         }
742
743         /* progress update */
744         if(progress.get_cancel())
745                 progress.set_status("Cancel", progress.get_cancel_message());
746         else
747                 progress.set_update();
748 }
749
750 bool Session::draw(BufferParams& buffer_params, DeviceDrawParams &draw_params)
751 {
752         if(device_use_gl)
753                 return draw_gpu(buffer_params, draw_params);
754         else
755                 return draw_cpu(buffer_params, draw_params);
756 }
757
758 void Session::reset_(BufferParams& buffer_params, int samples)
759 {
760         if(buffers && buffer_params.modified(tile_manager.params)) {
761                 gpu_draw_ready = false;
762                 buffers->reset(buffer_params);
763                 if(display) {
764                         display->reset(buffer_params);
765                 }
766         }
767
768         tile_manager.reset(buffer_params, samples);
769         progress.reset_sample();
770
771         bool show_progress = params.background || tile_manager.get_num_effective_samples() != INT_MAX;
772         progress.set_total_pixel_samples(show_progress? tile_manager.state.total_pixel_samples : 0);
773
774         if(!params.background)
775                 progress.set_start_time();
776         progress.set_render_start_time();
777 }
778
779 void Session::reset(BufferParams& buffer_params, int samples)
780 {
781         if(device_use_gl)
782                 reset_gpu(buffer_params, samples);
783         else
784                 reset_cpu(buffer_params, samples);
785 }
786
787 void Session::set_samples(int samples)
788 {
789         if(samples != params.samples) {
790                 params.samples = samples;
791                 tile_manager.set_samples(samples);
792
793                 {
794                         thread_scoped_lock pause_lock(pause_mutex);
795                 }
796                 pause_cond.notify_all();
797         }
798 }
799
800 void Session::set_pause(bool pause_)
801 {
802         bool notify = false;
803
804         {
805                 thread_scoped_lock pause_lock(pause_mutex);
806
807                 if(pause != pause_) {
808                         pause = pause_;
809                         notify = true;
810                 }
811         }
812
813         if(notify)
814                 pause_cond.notify_all();
815 }
816
817 void Session::wait()
818 {
819         session_thread->join();
820         delete session_thread;
821
822         session_thread = NULL;
823 }
824
825 void Session::update_scene()
826 {
827         thread_scoped_lock scene_lock(scene->mutex);
828
829         /* update camera if dimensions changed for progressive render. the camera
830          * knows nothing about progressive or cropped rendering, it just gets the
831          * image dimensions passed in */
832         Camera *cam = scene->camera;
833         int width = tile_manager.state.buffer.full_width;
834         int height = tile_manager.state.buffer.full_height;
835         int resolution = tile_manager.state.resolution_divider;
836
837         if(width != cam->width || height != cam->height) {
838                 cam->width = width;
839                 cam->height = height;
840                 cam->resolution = resolution;
841                 cam->tag_update();
842         }
843
844         /* number of samples is needed by multi jittered
845          * sampling pattern and by baking */
846         Integrator *integrator = scene->integrator;
847         BakeManager *bake_manager = scene->bake_manager;
848
849         if(integrator->sampling_pattern == SAMPLING_PATTERN_CMJ ||
850            bake_manager->get_baking())
851         {
852                 int aa_samples = tile_manager.num_samples;
853
854                 if(aa_samples != integrator->aa_samples) {
855                         integrator->aa_samples = aa_samples;
856                         integrator->tag_update(scene);
857                 }
858         }
859
860         /* update scene */
861         if(scene->need_update()) {
862                 load_kernels(false);
863
864                 /* Update max_closures. */
865                 KernelIntegrator *kintegrator = &scene->dscene.data.integrator;
866                 if(params.background) {
867                         kintegrator->max_closures = get_max_closure_count();
868                 }
869                 else {
870                         /* Currently viewport render is faster with higher max_closures, needs investigating. */
871                         kintegrator->max_closures = 64;
872                 }
873
874                 progress.set_status("Updating Scene");
875                 MEM_GUARDED_CALL(&progress, scene->device_update, device, progress);
876         }
877 }
878
879 void Session::update_status_time(bool show_pause, bool show_done)
880 {
881         int progressive_sample = tile_manager.state.sample;
882         int num_samples = tile_manager.get_num_effective_samples();
883
884         int tile = progress.get_rendered_tiles();
885         int num_tiles = tile_manager.state.num_tiles;
886
887         /* update status */
888         string status, substatus;
889
890         if(!params.progressive) {
891                 const bool is_cpu = params.device.type == DEVICE_CPU;
892                 const bool rendering_finished = (tile == num_tiles);
893                 const bool is_last_tile = (tile + 1) == num_tiles;
894
895                 substatus = string_printf("Rendered %d/%d Tiles", tile, num_tiles);
896
897                 if(!rendering_finished && (device->show_samples() || (is_cpu && is_last_tile))) {
898                         /* Some devices automatically support showing the sample number:
899                          * - CUDADevice
900                          * - OpenCLDevice when using the megakernel (the split kernel renders multiple
901                          *   samples at the same time, so the current sample isn't really defined)
902                          * - CPUDevice when using one thread
903                          * For these devices, the current sample is always shown.
904                          *
905                          * The other option is when the last tile is currently being rendered by the CPU.
906                          */
907                         substatus += string_printf(", Sample %d/%d", progress.get_current_sample(), num_samples);
908                 }
909                 if(params.use_denoising) {
910                         substatus += string_printf(", Denoised %d tiles", progress.get_denoised_tiles());
911                 }
912         }
913         else if(tile_manager.num_samples == INT_MAX)
914                 substatus = string_printf("Path Tracing Sample %d", progressive_sample+1);
915         else
916                 substatus = string_printf("Path Tracing Sample %d/%d",
917                                           progressive_sample+1,
918                                           num_samples);
919
920         if(show_pause) {
921                 status = "Paused";
922         }
923         else if(show_done) {
924                 status = "Done";
925                 progress.set_end_time(); /* Save end time so that further calls to get_time are accurate. */
926         }
927         else {
928                 status = substatus;
929                 substatus.clear();
930         }
931
932         progress.set_status(status, substatus);
933 }
934
935 void Session::render()
936 {
937         /* Clear buffers. */
938         if(buffers && tile_manager.state.sample == tile_manager.range_start_sample) {
939                 buffers->zero();
940         }
941
942         /* Add path trace task. */
943         DeviceTask task(DeviceTask::RENDER);
944
945         task.acquire_tile = function_bind(&Session::acquire_tile, this, _1, _2);
946         task.release_tile = function_bind(&Session::release_tile, this, _1);
947         task.map_neighbor_tiles = function_bind(&Session::map_neighbor_tiles, this, _1, _2);
948         task.unmap_neighbor_tiles = function_bind(&Session::unmap_neighbor_tiles, this, _1, _2);
949         task.get_cancel = function_bind(&Progress::get_cancel, &this->progress);
950         task.update_tile_sample = function_bind(&Session::update_tile_sample, this, _1);
951         task.update_progress_sample = function_bind(&Progress::add_samples, &this->progress, _1, _2);
952         task.need_finish_queue = params.progressive_refine;
953         task.integrator_branched = scene->integrator->method == Integrator::BRANCHED_PATH;
954         task.requested_tile_size = params.tile_size;
955         task.passes_size = tile_manager.params.get_passes_size();
956
957         if(params.use_denoising) {
958                 task.denoising_radius = params.denoising_radius;
959                 task.denoising_strength = params.denoising_strength;
960                 task.denoising_feature_strength = params.denoising_feature_strength;
961                 task.denoising_relative_pca = params.denoising_relative_pca;
962
963                 assert(!scene->film->need_update);
964                 task.pass_stride = scene->film->pass_stride;
965                 task.pass_denoising_data = scene->film->denoising_data_offset;
966                 task.pass_denoising_clean = scene->film->denoising_clean_offset;
967         }
968
969         device->task_add(task);
970 }
971
972 void Session::tonemap(int sample)
973 {
974         /* add tonemap task */
975         DeviceTask task(DeviceTask::FILM_CONVERT);
976
977         task.x = tile_manager.state.buffer.full_x;
978         task.y = tile_manager.state.buffer.full_y;
979         task.w = tile_manager.state.buffer.width;
980         task.h = tile_manager.state.buffer.height;
981         task.rgba_byte = display->rgba_byte.device_pointer;
982         task.rgba_half = display->rgba_half.device_pointer;
983         task.buffer = buffers->buffer.device_pointer;
984         task.sample = sample;
985         tile_manager.state.buffer.get_offset_stride(task.offset, task.stride);
986
987         if(task.w > 0 && task.h > 0) {
988                 device->task_add(task);
989                 device->task_wait();
990
991                 /* set display to new size */
992                 display->draw_set(task.w, task.h);
993         }
994
995         display_outdated = false;
996 }
997
998 bool Session::update_progressive_refine(bool cancel)
999 {
1000         int sample = tile_manager.state.sample + 1;
1001         bool write = sample == tile_manager.num_samples || cancel;
1002
1003         double current_time = time_dt();
1004
1005         if(current_time - last_update_time < params.progressive_update_timeout) {
1006                 /* if last sample was processed, we need to write buffers anyway  */
1007                 if(!write && sample != 1)
1008                         return false;
1009         }
1010
1011         if(params.progressive_refine) {
1012                 foreach(Tile& tile, tile_manager.state.tiles) {
1013                         if(!tile.buffers) {
1014                                 continue;
1015                         }
1016
1017                         RenderTile rtile;
1018                         rtile.x = tile_manager.state.buffer.full_x + tile.x;
1019                         rtile.y = tile_manager.state.buffer.full_y + tile.y;
1020                         rtile.w = tile.w;
1021                         rtile.h = tile.h;
1022                         rtile.sample = sample;
1023                         rtile.buffers = tile.buffers;
1024
1025                         if(write) {
1026                                 if(write_render_tile_cb)
1027                                         write_render_tile_cb(rtile);
1028                         }
1029                         else {
1030                                 if(update_render_tile_cb)
1031                                         update_render_tile_cb(rtile, true);
1032                         }
1033                 }
1034         }
1035
1036         last_update_time = current_time;
1037
1038         return write;
1039 }
1040
1041 void Session::device_free()
1042 {
1043         scene->device_free();
1044
1045         tile_manager.device_free();
1046
1047         /* used from background render only, so no need to
1048          * re-create render/display buffers here
1049          */
1050 }
1051
1052 int Session::get_max_closure_count()
1053 {
1054         int max_closures = 0;
1055         for(int i = 0; i < scene->shaders.size(); i++) {
1056                 int num_closures = scene->shaders[i]->graph->get_num_closures();
1057                 max_closures = max(max_closures, num_closures);
1058         }
1059         max_closure_global = max(max_closure_global, max_closures);
1060         return max_closure_global;
1061 }
1062
1063 CCL_NAMESPACE_END