Fix #36731: border render not updating properly with persistent images
[blender-staging.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 "background.h"
18 #include "buffers.h"
19 #include "camera.h"
20 #include "device.h"
21 #include "integrator.h"
22 #include "film.h"
23 #include "light.h"
24 #include "scene.h"
25 #include "session.h"
26 #include "shader.h"
27
28 #include "util_color.h"
29 #include "util_foreach.h"
30 #include "util_function.h"
31 #include "util_progress.h"
32 #include "util_time.h"
33
34 #include "blender_sync.h"
35 #include "blender_session.h"
36 #include "blender_util.h"
37
38 CCL_NAMESPACE_BEGIN
39
40 BlenderSession::BlenderSession(BL::RenderEngine b_engine_, BL::UserPreferences b_userpref_,
41         BL::BlendData b_data_, BL::Scene b_scene_)
42 : b_engine(b_engine_), b_userpref(b_userpref_), b_data(b_data_), b_render(b_engine_.render()), b_scene(b_scene_),
43   b_v3d(PointerRNA_NULL), b_rv3d(PointerRNA_NULL)
44 {
45         /* offline render */
46
47         width = render_resolution_x(b_render);
48         height = render_resolution_y(b_render);
49
50         background = true;
51         last_redraw_time = 0.0;
52         start_resize_time = 0.0;
53
54         create_session();
55 }
56
57 BlenderSession::BlenderSession(BL::RenderEngine b_engine_, BL::UserPreferences b_userpref_,
58         BL::BlendData b_data_, BL::Scene b_scene_,
59         BL::SpaceView3D b_v3d_, BL::RegionView3D b_rv3d_, int width_, int height_)
60 : b_engine(b_engine_), b_userpref(b_userpref_), b_data(b_data_), b_render(b_scene_.render()), b_scene(b_scene_),
61   b_v3d(b_v3d_), b_rv3d(b_rv3d_)
62 {
63         /* 3d view render */
64
65         width = width_;
66         height = height_;
67         background = false;
68         last_redraw_time = 0.0;
69         start_resize_time = 0.0;
70
71         create_session();
72         session->start();
73 }
74
75 BlenderSession::~BlenderSession()
76 {
77         free_session();
78 }
79
80 void BlenderSession::create_session()
81 {
82         SceneParams scene_params = BlenderSync::get_scene_params(b_scene, background);
83         SessionParams session_params = BlenderSync::get_session_params(b_engine, b_userpref, b_scene, background);
84
85         /* reset status/progress */
86         last_status = "";
87         last_progress = -1.0f;
88         start_resize_time = 0.0;
89
90         /* create scene */
91         scene = new Scene(scene_params, session_params.device);
92
93         /* create session */
94         session = new Session(session_params);
95         session->scene = scene;
96         session->progress.set_update_callback(function_bind(&BlenderSession::tag_redraw, this));
97         session->progress.set_cancel_callback(function_bind(&BlenderSession::test_cancel, this));
98         session->set_pause(BlenderSync::get_session_pause(b_scene, background));
99
100         /* create sync */
101         sync = new BlenderSync(b_engine, b_data, b_scene, scene, !background, session->progress, session_params.device.type == DEVICE_CPU);
102
103         if(b_v3d) {
104                 /* full data sync */
105                 sync->sync_data(b_v3d, b_engine.camera_override());
106                 sync->sync_view(b_v3d, b_rv3d, width, height);
107         }
108         else {
109                 /* for final render we will do full data sync per render layer, only
110                  * do some basic syncing here, no objects or materials for speed */
111                 sync->sync_render_layers(b_v3d, NULL);
112                 sync->sync_integrator();
113                 sync->sync_camera(b_render, b_engine.camera_override(), width, height);
114         }
115
116         /* set buffer parameters */
117         BufferParams buffer_params = BlenderSync::get_buffer_params(b_render, b_scene, b_v3d, b_rv3d, scene->camera, width, height);
118         session->reset(buffer_params, session_params.samples);
119
120         b_engine.use_highlight_tiles(session_params.progressive_refine == false);
121
122         /* setup callbacks for builtin image support */
123         scene->image_manager->builtin_image_info_cb = function_bind(&BlenderSession::builtin_image_info, this, _1, _2, _3, _4, _5, _6);
124         scene->image_manager->builtin_image_pixels_cb = function_bind(&BlenderSession::builtin_image_pixels, this, _1, _2, _3);
125         scene->image_manager->builtin_image_float_pixels_cb = function_bind(&BlenderSession::builtin_image_float_pixels, this, _1, _2, _3);
126 }
127
128 void BlenderSession::reset_session(BL::BlendData b_data_, BL::Scene b_scene_)
129 {
130         b_data = b_data_;
131         b_render = b_engine.render();
132         b_scene = b_scene_;
133
134         SceneParams scene_params = BlenderSync::get_scene_params(b_scene, background);
135         SessionParams session_params = BlenderSync::get_session_params(b_engine, b_userpref, b_scene, background);
136
137         width = render_resolution_x(b_render);
138         height = render_resolution_y(b_render);
139
140         if(scene->params.modified(scene_params) ||
141            session->params.modified(session_params) ||
142            !scene_params.persistent_data)
143         {
144                 /* if scene or session parameters changed, it's easier to simply re-create
145                  * them rather than trying to distinguish which settings need to be updated
146                  */
147
148                 delete session;
149
150                 create_session();
151
152                 return;
153         }
154
155         session->progress.reset();
156         scene->reset();
157
158         session->tile_manager.set_tile_order(session_params.tile_order);
159
160         /* peak memory usage should show current render peak, not peak for all renders
161          * made by this render session
162          */
163         session->stats.mem_peak = session->stats.mem_used;
164
165         /* sync object should be re-created */
166         sync = new BlenderSync(b_engine, b_data, b_scene, scene, !background, session->progress, session_params.device.type == DEVICE_CPU);
167
168         /* for final render we will do full data sync per render layer, only
169          * do some basic syncing here, no objects or materials for speed */
170         sync->sync_render_layers(b_v3d, NULL);
171         sync->sync_integrator();
172         sync->sync_camera(b_render, b_engine.camera_override(), width, height);
173
174         BufferParams buffer_params = BlenderSync::get_buffer_params(b_render, b_scene, PointerRNA_NULL, PointerRNA_NULL, scene->camera, width, height);
175         session->reset(buffer_params, session_params.samples);
176
177         b_engine.use_highlight_tiles(session_params.progressive_refine == false);
178
179         /* reset time */
180         start_resize_time = 0.0;
181 }
182
183 void BlenderSession::free_session()
184 {
185         if(sync)
186                 delete sync;
187
188         delete session;
189 }
190
191 static PassType get_pass_type(BL::RenderPass b_pass)
192 {
193         switch(b_pass.type()) {
194                 case BL::RenderPass::type_COMBINED:
195                         return PASS_COMBINED;
196
197                 case BL::RenderPass::type_Z:
198                         return PASS_DEPTH;
199                 case BL::RenderPass::type_MIST:
200                         return PASS_MIST;
201                 case BL::RenderPass::type_NORMAL:
202                         return PASS_NORMAL;
203                 case BL::RenderPass::type_OBJECT_INDEX:
204                         return PASS_OBJECT_ID;
205                 case BL::RenderPass::type_UV:
206                         return PASS_UV;
207                 case BL::RenderPass::type_VECTOR:
208                         return PASS_MOTION;
209                 case BL::RenderPass::type_MATERIAL_INDEX:
210                         return PASS_MATERIAL_ID;
211
212                 case BL::RenderPass::type_DIFFUSE_DIRECT:
213                         return PASS_DIFFUSE_DIRECT;
214                 case BL::RenderPass::type_GLOSSY_DIRECT:
215                         return PASS_GLOSSY_DIRECT;
216                 case BL::RenderPass::type_TRANSMISSION_DIRECT:
217                         return PASS_TRANSMISSION_DIRECT;
218                 case BL::RenderPass::type_SUBSURFACE_DIRECT:
219                         return PASS_SUBSURFACE_DIRECT;
220
221                 case BL::RenderPass::type_DIFFUSE_INDIRECT:
222                         return PASS_DIFFUSE_INDIRECT;
223                 case BL::RenderPass::type_GLOSSY_INDIRECT:
224                         return PASS_GLOSSY_INDIRECT;
225                 case BL::RenderPass::type_TRANSMISSION_INDIRECT:
226                         return PASS_TRANSMISSION_INDIRECT;
227                 case BL::RenderPass::type_SUBSURFACE_INDIRECT:
228                         return PASS_SUBSURFACE_INDIRECT;
229
230                 case BL::RenderPass::type_DIFFUSE_COLOR:
231                         return PASS_DIFFUSE_COLOR;
232                 case BL::RenderPass::type_GLOSSY_COLOR:
233                         return PASS_GLOSSY_COLOR;
234                 case BL::RenderPass::type_TRANSMISSION_COLOR:
235                         return PASS_TRANSMISSION_COLOR;
236                 case BL::RenderPass::type_SUBSURFACE_COLOR:
237                         return PASS_SUBSURFACE_COLOR;
238
239                 case BL::RenderPass::type_EMIT:
240                         return PASS_EMISSION;
241                 case BL::RenderPass::type_ENVIRONMENT:
242                         return PASS_BACKGROUND;
243                 case BL::RenderPass::type_AO:
244                         return PASS_AO;
245                 case BL::RenderPass::type_SHADOW:
246                         return PASS_SHADOW;
247
248                 case BL::RenderPass::type_DIFFUSE:
249                 case BL::RenderPass::type_COLOR:
250                 case BL::RenderPass::type_REFRACTION:
251                 case BL::RenderPass::type_SPECULAR:
252                 case BL::RenderPass::type_REFLECTION:
253                         return PASS_NONE;
254         }
255         
256         return PASS_NONE;
257 }
258
259 static BL::RenderResult begin_render_result(BL::RenderEngine b_engine, int x, int y, int w, int h, const char *layername)
260 {
261         return b_engine.begin_result(x, y, w, h, layername);
262 }
263
264 static void end_render_result(BL::RenderEngine b_engine, BL::RenderResult b_rr, bool cancel = false)
265 {
266         b_engine.end_result(b_rr, (int)cancel);
267 }
268
269 void BlenderSession::do_write_update_render_tile(RenderTile& rtile, bool do_update_only)
270 {
271         BufferParams& params = rtile.buffers->params;
272         int x = params.full_x - session->tile_manager.params.full_x;
273         int y = params.full_y - session->tile_manager.params.full_y;
274         int w = params.width;
275         int h = params.height;
276
277         /* get render result */
278         BL::RenderResult b_rr = begin_render_result(b_engine, x, y, w, h, b_rlay_name.c_str());
279
280         /* can happen if the intersected rectangle gives 0 width or height */
281         if (b_rr.ptr.data == NULL) {
282                 return;
283         }
284
285         BL::RenderResult::layers_iterator b_single_rlay;
286         b_rr.layers.begin(b_single_rlay);
287
288         /* layer will be missing if it was disabled in the UI */
289         if(b_single_rlay == b_rr.layers.end())
290                 return;
291
292         BL::RenderLayer b_rlay = *b_single_rlay;
293
294         if (do_update_only) {
295                 /* update only needed */
296
297                 if (rtile.sample != 0) {
298                         /* sample would be zero at initial tile update, which is only needed
299                          * to tag tile form blender side as IN PROGRESS for proper highlight
300                          * no buffers should be sent to blender yet
301                          */
302                         update_render_result(b_rr, b_rlay, rtile);
303                 }
304
305                 end_render_result(b_engine, b_rr, true);
306         }
307         else {
308                 /* write result */
309                 write_render_result(b_rr, b_rlay, rtile);
310                 end_render_result(b_engine, b_rr);
311         }
312 }
313
314 void BlenderSession::write_render_tile(RenderTile& rtile)
315 {
316         do_write_update_render_tile(rtile, false);
317 }
318
319 void BlenderSession::update_render_tile(RenderTile& rtile)
320 {
321         /* use final write for preview renders, otherwise render result wouldn't be
322          * be updated in blender side
323          * would need to be investigated a bit further, but for now shall be fine
324          */
325         if (!b_engine.is_preview())
326                 do_write_update_render_tile(rtile, true);
327         else
328                 do_write_update_render_tile(rtile, false);
329 }
330
331 void BlenderSession::render()
332 {
333         /* set callback to write out render results */
334         session->write_render_tile_cb = function_bind(&BlenderSession::write_render_tile, this, _1);
335         session->update_render_tile_cb = function_bind(&BlenderSession::update_render_tile, this, _1);
336
337         /* get buffer parameters */
338         SessionParams session_params = BlenderSync::get_session_params(b_engine, b_userpref, b_scene, background);
339         BufferParams buffer_params = BlenderSync::get_buffer_params(b_render, b_scene, b_v3d, b_rv3d, scene->camera, width, height);
340
341         /* render each layer */
342         BL::RenderSettings r = b_scene.render();
343         BL::RenderSettings::layers_iterator b_iter;
344         
345         for(r.layers.begin(b_iter); b_iter != r.layers.end(); ++b_iter) {
346                 b_rlay_name = b_iter->name();
347
348                 /* temporary render result to find needed passes */
349                 BL::RenderResult b_rr = begin_render_result(b_engine, 0, 0, 1, 1, b_rlay_name.c_str());
350                 BL::RenderResult::layers_iterator b_single_rlay;
351                 b_rr.layers.begin(b_single_rlay);
352
353                 /* layer will be missing if it was disabled in the UI */
354                 if(b_single_rlay == b_rr.layers.end()) {
355                         end_render_result(b_engine, b_rr, true);
356                         continue;
357                 }
358
359                 BL::RenderLayer b_rlay = *b_single_rlay;
360
361                 /* add passes */
362                 vector<Pass> passes;
363                 Pass::add(PASS_COMBINED, passes);
364
365                 if(session_params.device.advanced_shading) {
366
367                         /* loop over passes */
368                         BL::RenderLayer::passes_iterator b_pass_iter;
369
370                         for(b_rlay.passes.begin(b_pass_iter); b_pass_iter != b_rlay.passes.end(); ++b_pass_iter) {
371                                 BL::RenderPass b_pass(*b_pass_iter);
372                                 PassType pass_type = get_pass_type(b_pass);
373
374                                 if(pass_type == PASS_MOTION && scene->integrator->motion_blur)
375                                         continue;
376                                 if(pass_type != PASS_NONE)
377                                         Pass::add(pass_type, passes);
378                         }
379                 }
380
381                 /* free result without merging */
382                 end_render_result(b_engine, b_rr, true);
383
384                 buffer_params.passes = passes;
385                 scene->film->tag_passes_update(scene, passes);
386                 scene->film->tag_update(scene);
387                 scene->integrator->tag_update(scene);
388
389                 /* update scene */
390                 sync->sync_camera(b_render, b_engine.camera_override(), width, height);
391                 sync->sync_data(b_v3d, b_engine.camera_override(), b_rlay_name.c_str());
392
393                 /* update number of samples per layer */
394                 int samples = sync->get_layer_samples();
395                 bool bound_samples = sync->get_layer_bound_samples();
396
397                 if(samples != 0 && (!bound_samples || (samples < session_params.samples)))
398                         session->reset(buffer_params, samples);
399                 else
400                         session->reset(buffer_params, session_params.samples);
401
402                 /* render */
403                 session->start();
404                 session->wait();
405
406                 if(session->progress.get_cancel())
407                         break;
408         }
409
410         /* clear callback */
411         session->write_render_tile_cb = NULL;
412         session->update_render_tile_cb = NULL;
413
414         /* free all memory used (host and device), so we wouldn't leave render
415          * engine with extra memory allocated
416          */
417
418         session->device_free();
419
420         delete sync;
421         sync = NULL;
422 }
423
424 void BlenderSession::do_write_update_render_result(BL::RenderResult b_rr, BL::RenderLayer b_rlay, RenderTile& rtile, bool do_update_only)
425 {
426         RenderBuffers *buffers = rtile.buffers;
427
428         /* copy data from device */
429         if(!buffers->copy_from_device())
430                 return;
431
432         BufferParams& params = buffers->params;
433         float exposure = scene->film->exposure;
434
435         vector<float> pixels(params.width*params.height*4);
436
437         if (!do_update_only) {
438                 /* copy each pass */
439                 BL::RenderLayer::passes_iterator b_iter;
440
441                 for(b_rlay.passes.begin(b_iter); b_iter != b_rlay.passes.end(); ++b_iter) {
442                         BL::RenderPass b_pass(*b_iter);
443
444                         /* find matching pass type */
445                         PassType pass_type = get_pass_type(b_pass);
446                         int components = b_pass.channels();
447
448                         /* copy pixels */
449                         if(!buffers->get_pass_rect(pass_type, exposure, rtile.sample, components, &pixels[0]))
450                                 memset(&pixels[0], 0, pixels.size()*sizeof(float));
451
452                         b_pass.rect(&pixels[0]);
453                 }
454         }
455
456         /* copy combined pass */
457         if(buffers->get_pass_rect(PASS_COMBINED, exposure, rtile.sample, 4, &pixels[0]))
458                 b_rlay.rect(&pixels[0]);
459
460         /* tag result as updated */
461         b_engine.update_result(b_rr);
462 }
463
464 void BlenderSession::write_render_result(BL::RenderResult b_rr, BL::RenderLayer b_rlay, RenderTile& rtile)
465 {
466         do_write_update_render_result(b_rr, b_rlay, rtile, false);
467 }
468
469 void BlenderSession::update_render_result(BL::RenderResult b_rr, BL::RenderLayer b_rlay, RenderTile& rtile)
470 {
471         do_write_update_render_result(b_rr, b_rlay, rtile, true);
472 }
473
474 void BlenderSession::synchronize()
475 {
476         /* only used for viewport render */
477         if(!b_v3d)
478                 return;
479
480         /* on session/scene parameter changes, we recreate session entirely */
481         SceneParams scene_params = BlenderSync::get_scene_params(b_scene, background);
482         SessionParams session_params = BlenderSync::get_session_params(b_engine, b_userpref, b_scene, background);
483
484         if(session->params.modified(session_params) ||
485            scene->params.modified(scene_params))
486         {
487                 free_session();
488                 create_session();
489                 session->start();
490                 return;
491         }
492
493         /* increase samples, but never decrease */
494         session->set_samples(session_params.samples);
495         session->set_pause(BlenderSync::get_session_pause(b_scene, background));
496
497         /* copy recalc flags, outside of mutex so we can decide to do the real
498          * synchronization at a later time to not block on running updates */
499         sync->sync_recalc();
500
501         /* try to acquire mutex. if we don't want to or can't, come back later */
502         if(!session->ready_to_reset() || !session->scene->mutex.try_lock()) {
503                 tag_update();
504                 return;
505         }
506
507         /* data and camera synchronize */
508         sync->sync_data(b_v3d, b_engine.camera_override());
509
510         if(b_rv3d)
511                 sync->sync_view(b_v3d, b_rv3d, width, height);
512         else
513                 sync->sync_camera(b_render, b_engine.camera_override(), width, height);
514
515         /* unlock */
516         session->scene->mutex.unlock();
517
518         /* reset if needed */
519         if(scene->need_reset()) {
520                 BufferParams buffer_params = BlenderSync::get_buffer_params(b_render, b_scene, b_v3d, b_rv3d, scene->camera, width, height);
521                 session->reset(buffer_params, session_params.samples);
522
523                 /* reset time */
524                 start_resize_time = 0.0;
525         }
526 }
527
528 bool BlenderSession::draw(int w, int h)
529 {
530         /* pause in redraw in case update is not being called due to final render */
531         session->set_pause(BlenderSync::get_session_pause(b_scene, background));
532
533         /* before drawing, we verify camera and viewport size changes, because
534          * we do not get update callbacks for those, we must detect them here */
535         if(session->ready_to_reset()) {
536                 bool reset = false;
537
538                 /* if dimensions changed, reset */
539                 if(width != w || height != h) {
540                         if(start_resize_time == 0.0) {
541                                 /* don't react immediately to resizes to avoid flickery resizing
542                                  * of the viewport, and some window managers changing the window
543                                  * size temporarily on unminimize */
544                                 start_resize_time = time_dt();
545                                 tag_redraw();
546                         }
547                         else if(time_dt() - start_resize_time < 0.2) {
548                                 tag_redraw();
549                         }
550                         else {
551                                 width = w;
552                                 height = h;
553                                 reset = true;
554                         }
555                 }
556
557                 /* try to acquire mutex. if we can't, come back later */
558                 if(!session->scene->mutex.try_lock()) {
559                         tag_update();
560                 }
561                 else {
562                         /* update camera from 3d view */
563
564                         sync->sync_view(b_v3d, b_rv3d, width, height);
565
566                         if(scene->camera->need_update)
567                                 reset = true;
568
569                         session->scene->mutex.unlock();
570                 }
571
572                 /* reset if requested */
573                 if(reset) {
574                         SessionParams session_params = BlenderSync::get_session_params(b_engine, b_userpref, b_scene, background);
575                         BufferParams buffer_params = BlenderSync::get_buffer_params(b_render, b_scene, b_v3d, b_rv3d, scene->camera, width, height);
576
577                         session->reset(buffer_params, session_params.samples);
578
579                         start_resize_time = 0.0;
580                 }
581         }
582         else {
583                 tag_update();
584         }
585
586         /* update status and progress for 3d view draw */
587         update_status_progress();
588
589         /* draw */
590         BufferParams buffer_params = BlenderSync::get_buffer_params(b_render, b_scene, b_v3d, b_rv3d, scene->camera, width, height);
591
592         if(session->params.display_buffer_linear)
593                 b_engine.bind_display_space_shader(b_scene);
594
595         bool draw_ok = !session->draw(buffer_params);
596
597         if(session->params.display_buffer_linear)
598                 b_engine.unbind_display_space_shader();
599         
600         return draw_ok;
601 }
602
603 void BlenderSession::get_status(string& status, string& substatus)
604 {
605         session->progress.get_status(status, substatus);
606 }
607
608 void BlenderSession::get_progress(float& progress, double& total_time)
609 {
610         double tile_time;
611         int tile, sample, samples_per_tile;
612         int tile_total = session->tile_manager.state.num_tiles;
613
614         session->progress.get_tile(tile, total_time, tile_time);
615
616         sample = session->progress.get_sample();
617         samples_per_tile = session->tile_manager.num_samples;
618
619         if(samples_per_tile && tile_total)
620                 progress = ((float)sample / (float)(tile_total * samples_per_tile));
621         else
622                 progress = 0.0;
623 }
624
625 void BlenderSession::update_status_progress()
626 {
627         string timestatus, status, substatus;
628         float progress;
629         double total_time;
630         char time_str[128];
631         float mem_used = (float)session->stats.mem_used / 1024.0f / 1024.0f;
632         float mem_peak = (float)session->stats.mem_peak / 1024.0f / 1024.0f;
633
634         get_status(status, substatus);
635         get_progress(progress, total_time);
636
637         timestatus = string_printf("Mem:%.2fM, Peak:%.2fM", mem_used, mem_peak);
638
639         if(background) {
640                 timestatus += " | " + b_scene.name();
641                 if(b_rlay_name != "")
642                         timestatus += ", "  + b_rlay_name;
643         }
644         else {
645                 timestatus += " | ";
646
647                 BLI_timestr(total_time, time_str, sizeof(time_str));
648                 timestatus += "Time:" + string(time_str);
649         }
650
651         if(status.size() > 0)
652                 status = " | " + status;
653         if(substatus.size() > 0)
654                 status += " | " + substatus;
655
656         if(status != last_status) {
657                 b_engine.update_stats("", (timestatus + status).c_str());
658                 b_engine.update_memory_stats(mem_used, mem_peak);
659                 last_status = status;
660         }
661         if(progress != last_progress) {
662                 b_engine.update_progress(progress);
663                 last_progress = progress;
664         }
665 }
666
667 void BlenderSession::tag_update()
668 {
669         /* tell blender that we want to get another update callback */
670         b_engine.tag_update();
671 }
672
673 void BlenderSession::tag_redraw()
674 {
675         if(background) {
676                 /* update stats and progress, only for background here because
677                  * in 3d view we do it in draw for thread safety reasons */
678                 update_status_progress();
679
680                 /* offline render, redraw if timeout passed */
681                 if(time_dt() - last_redraw_time > 1.0) {
682                         b_engine.tag_redraw();
683                         last_redraw_time = time_dt();
684                 }
685         }
686         else {
687                 /* tell blender that we want to redraw */
688                 b_engine.tag_redraw();
689         }
690 }
691
692 void BlenderSession::test_cancel()
693 {
694         /* test if we need to cancel rendering */
695         if(background)
696                 if(b_engine.test_break())
697                         session->progress.set_cancel("Cancelled");
698 }
699
700 /* builtin image file name is actually an image datablock name with
701  * absolute sequence frame number concatenated via '@' character
702  *
703  * this function splits frame from builtin name
704  */
705 int BlenderSession::builtin_image_frame(const string &builtin_name)
706 {
707         int last = builtin_name.find_last_of('@');
708         return atoi(builtin_name.substr(last + 1, builtin_name.size() - last - 1).c_str());
709 }
710
711 void BlenderSession::builtin_image_info(const string &builtin_name, void *builtin_data, bool &is_float, int &width, int &height, int &channels)
712 {
713         PointerRNA ptr;
714         RNA_id_pointer_create((ID*)builtin_data, &ptr);
715         BL::Image b_image(ptr);
716
717         if(b_image) {
718                 is_float = b_image.is_float();
719                 width = b_image.size()[0];
720                 height = b_image.size()[1];
721                 channels = b_image.channels();
722         }
723         else {
724                 is_float = false;
725                 width = 0;
726                 height = 0;
727                 channels = 0;
728         }
729 }
730
731 bool BlenderSession::builtin_image_pixels(const string &builtin_name, void *builtin_data, unsigned char *pixels)
732 {
733         int frame = builtin_image_frame(builtin_name);
734
735         PointerRNA ptr;
736         RNA_id_pointer_create((ID*)builtin_data, &ptr);
737         BL::Image b_image(ptr);
738
739         if(b_image) {
740                 int width = b_image.size()[0];
741                 int height = b_image.size()[1];
742                 int channels = b_image.channels();
743
744                 unsigned char *image_pixels;
745                 image_pixels = image_get_pixels_for_frame(b_image, frame);
746
747                 if(image_pixels) {
748                         memcpy(pixels, image_pixels, width * height * channels * sizeof(unsigned char));
749                         MEM_freeN(image_pixels);
750                 }
751                 else {
752                         if(channels == 1) {
753                                 memset(pixels, 0, width * height * sizeof(unsigned char));
754                         }
755                         else {
756                                 unsigned char *cp = pixels;
757                                 for(int i = 0; i < width * height; i++, cp += channels) {
758                                         cp[0] = 255;
759                                         cp[1] = 0;
760                                         cp[2] = 255;
761                                         if(channels == 4)
762                                                 cp[3] = 255;
763                                 }
764                         }
765                 }
766
767                 /* premultiply, byte images are always straight for blender */
768                 unsigned char *cp = pixels;
769                 for(int i = 0; i < width * height; i++, cp += channels) {
770                         cp[0] = (cp[0] * cp[3]) >> 8;
771                         cp[1] = (cp[1] * cp[3]) >> 8;
772                         cp[2] = (cp[2] * cp[3]) >> 8;
773                 }
774
775                 return true;
776         }
777
778         return false;
779 }
780
781 bool BlenderSession::builtin_image_float_pixels(const string &builtin_name, void *builtin_data, float *pixels)
782 {
783         int frame = builtin_image_frame(builtin_name);
784
785         PointerRNA ptr;
786         RNA_id_pointer_create((ID*)builtin_data, &ptr);
787         BL::Image b_image(ptr);
788
789         if(b_image) {
790                 int width = b_image.size()[0];
791                 int height = b_image.size()[1];
792                 int channels = b_image.channels();
793
794                 float *image_pixels;
795                 image_pixels = image_get_float_pixels_for_frame(b_image, frame);
796
797                 if(image_pixels) {
798                         memcpy(pixels, image_pixels, width * height * channels * sizeof(float));
799                         MEM_freeN(image_pixels);
800                 }
801                 else {
802                         if(channels == 1) {
803                                 memset(pixels, 0, width * height * sizeof(float));
804                         }
805                         else {
806                                 float *fp = pixels;
807                                 for(int i = 0; i < width * height; i++, fp += channels) {
808                                         fp[0] = 1.0f;
809                                         fp[1] = 0.0f;
810                                         fp[2] = 1.0f;
811                                         if(channels == 4)
812                                                 fp[3] = 1.0f;
813                                 }
814                         }
815                 }
816
817                 return true;
818         }
819
820         return false;
821 }
822
823 CCL_NAMESPACE_END
824