6f959d426801587ce660039e3f0680e47e08526a
[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 <stdlib.h>
18
19 #include "background.h"
20 #include "buffers.h"
21 #include "camera.h"
22 #include "device.h"
23 #include "integrator.h"
24 #include "film.h"
25 #include "light.h"
26 #include "mesh.h"
27 #include "object.h"
28 #include "scene.h"
29 #include "session.h"
30 #include "shader.h"
31
32 #include "util_color.h"
33 #include "util_foreach.h"
34 #include "util_function.h"
35 #include "util_progress.h"
36 #include "util_time.h"
37
38 #include "blender_sync.h"
39 #include "blender_session.h"
40 #include "blender_util.h"
41
42 CCL_NAMESPACE_BEGIN
43
44 BlenderSession::BlenderSession(BL::RenderEngine b_engine_, BL::UserPreferences b_userpref_,
45         BL::BlendData b_data_, BL::Scene b_scene_)
46 : b_engine(b_engine_), b_userpref(b_userpref_), b_data(b_data_), b_render(b_engine_.render()), b_scene(b_scene_),
47   b_v3d(PointerRNA_NULL), b_rv3d(PointerRNA_NULL), python_thread_state(NULL)
48 {
49         /* offline render */
50
51         width = render_resolution_x(b_render);
52         height = render_resolution_y(b_render);
53
54         background = true;
55         last_redraw_time = 0.0;
56         start_resize_time = 0.0;
57 }
58
59 BlenderSession::BlenderSession(BL::RenderEngine b_engine_, BL::UserPreferences b_userpref_,
60         BL::BlendData b_data_, BL::Scene b_scene_,
61         BL::SpaceView3D b_v3d_, BL::RegionView3D b_rv3d_, int width_, int height_)
62 : b_engine(b_engine_), b_userpref(b_userpref_), b_data(b_data_), b_render(b_scene_.render()), b_scene(b_scene_),
63   b_v3d(b_v3d_), b_rv3d(b_rv3d_), python_thread_state(NULL)
64 {
65         /* 3d view render */
66
67         width = width_;
68         height = height_;
69         background = false;
70         last_redraw_time = 0.0;
71         start_resize_time = 0.0;
72 }
73
74 BlenderSession::~BlenderSession()
75 {
76         free_session();
77 }
78
79 void BlenderSession::create()
80 {
81         create_session();
82
83         if(b_v3d)
84                 session->start();
85 }
86
87 void BlenderSession::create_session()
88 {
89         SceneParams scene_params = BlenderSync::get_scene_params(b_scene, background);
90         SessionParams session_params = BlenderSync::get_session_params(b_engine, b_userpref, b_scene, background);
91
92         /* reset status/progress */
93         last_status = "";
94         last_progress = -1.0f;
95         start_resize_time = 0.0;
96
97         /* create scene */
98         scene = new Scene(scene_params, session_params.device);
99
100         /* setup callbacks for builtin image support */
101         scene->image_manager->builtin_image_info_cb = function_bind(&BlenderSession::builtin_image_info, this, _1, _2, _3, _4, _5, _6, _7);
102         scene->image_manager->builtin_image_pixels_cb = function_bind(&BlenderSession::builtin_image_pixels, this, _1, _2, _3);
103         scene->image_manager->builtin_image_float_pixels_cb = function_bind(&BlenderSession::builtin_image_float_pixels, this, _1, _2, _3);
104
105         /* create session */
106         session = new Session(session_params);
107         session->scene = scene;
108         session->progress.set_update_callback(function_bind(&BlenderSession::tag_redraw, this));
109         session->progress.set_cancel_callback(function_bind(&BlenderSession::test_cancel, this));
110         session->set_pause(BlenderSync::get_session_pause(b_scene, background));
111
112         /* create sync */
113         sync = new BlenderSync(b_engine, b_data, b_scene, scene, !background, session->progress, session_params.device.type == DEVICE_CPU);
114
115         if(b_v3d) {
116                 /* full data sync */
117                 sync->sync_data(b_v3d, b_engine.camera_override(), &python_thread_state);
118                 sync->sync_view(b_v3d, b_rv3d, width, height);
119         }
120         else {
121                 /* for final render we will do full data sync per render layer, only
122                  * do some basic syncing here, no objects or materials for speed */
123                 sync->sync_render_layers(b_v3d, NULL);
124                 sync->sync_integrator();
125                 sync->sync_camera(b_render, b_engine.camera_override(), width, height);
126         }
127
128         /* set buffer parameters */
129         BufferParams buffer_params = BlenderSync::get_buffer_params(b_render, b_scene, b_v3d, b_rv3d, scene->camera, width, height);
130         session->reset(buffer_params, session_params.samples);
131
132         b_engine.use_highlight_tiles(session_params.progressive_refine == false);
133 }
134
135 void BlenderSession::reset_session(BL::BlendData b_data_, BL::Scene b_scene_)
136 {
137         b_data = b_data_;
138         b_render = b_engine.render();
139         b_scene = b_scene_;
140
141         SceneParams scene_params = BlenderSync::get_scene_params(b_scene, background);
142         SessionParams session_params = BlenderSync::get_session_params(b_engine, b_userpref, b_scene, background);
143
144         width = render_resolution_x(b_render);
145         height = render_resolution_y(b_render);
146
147         if(scene->params.modified(scene_params) ||
148            session->params.modified(session_params) ||
149            !scene_params.persistent_data)
150         {
151                 /* if scene or session parameters changed, it's easier to simply re-create
152                  * them rather than trying to distinguish which settings need to be updated
153                  */
154
155                 delete session;
156
157                 create_session();
158
159                 return;
160         }
161
162         session->progress.reset();
163         scene->reset();
164
165         session->tile_manager.set_tile_order(session_params.tile_order);
166
167         /* peak memory usage should show current render peak, not peak for all renders
168          * made by this render session
169          */
170         session->stats.mem_peak = session->stats.mem_used;
171
172         /* sync object should be re-created */
173         sync = new BlenderSync(b_engine, b_data, b_scene, scene, !background, session->progress, session_params.device.type == DEVICE_CPU);
174
175         /* for final render we will do full data sync per render layer, only
176          * do some basic syncing here, no objects or materials for speed */
177         sync->sync_render_layers(b_v3d, NULL);
178         sync->sync_integrator();
179         sync->sync_camera(b_render, b_engine.camera_override(), width, height);
180
181         BufferParams buffer_params = BlenderSync::get_buffer_params(b_render, b_scene, PointerRNA_NULL, PointerRNA_NULL, scene->camera, width, height);
182         session->reset(buffer_params, session_params.samples);
183
184         b_engine.use_highlight_tiles(session_params.progressive_refine == false);
185
186         /* reset time */
187         start_resize_time = 0.0;
188 }
189
190 void BlenderSession::free_session()
191 {
192         if(sync)
193                 delete sync;
194
195         delete session;
196 }
197
198 static PassType get_pass_type(BL::RenderPass b_pass)
199 {
200         switch(b_pass.type()) {
201                 case BL::RenderPass::type_COMBINED:
202                         return PASS_COMBINED;
203
204                 case BL::RenderPass::type_Z:
205                         return PASS_DEPTH;
206                 case BL::RenderPass::type_MIST:
207                         return PASS_MIST;
208                 case BL::RenderPass::type_NORMAL:
209                         return PASS_NORMAL;
210                 case BL::RenderPass::type_OBJECT_INDEX:
211                         return PASS_OBJECT_ID;
212                 case BL::RenderPass::type_UV:
213                         return PASS_UV;
214                 case BL::RenderPass::type_VECTOR:
215                         return PASS_MOTION;
216                 case BL::RenderPass::type_MATERIAL_INDEX:
217                         return PASS_MATERIAL_ID;
218
219                 case BL::RenderPass::type_DIFFUSE_DIRECT:
220                         return PASS_DIFFUSE_DIRECT;
221                 case BL::RenderPass::type_GLOSSY_DIRECT:
222                         return PASS_GLOSSY_DIRECT;
223                 case BL::RenderPass::type_TRANSMISSION_DIRECT:
224                         return PASS_TRANSMISSION_DIRECT;
225                 case BL::RenderPass::type_SUBSURFACE_DIRECT:
226                         return PASS_SUBSURFACE_DIRECT;
227
228                 case BL::RenderPass::type_DIFFUSE_INDIRECT:
229                         return PASS_DIFFUSE_INDIRECT;
230                 case BL::RenderPass::type_GLOSSY_INDIRECT:
231                         return PASS_GLOSSY_INDIRECT;
232                 case BL::RenderPass::type_TRANSMISSION_INDIRECT:
233                         return PASS_TRANSMISSION_INDIRECT;
234                 case BL::RenderPass::type_SUBSURFACE_INDIRECT:
235                         return PASS_SUBSURFACE_INDIRECT;
236
237                 case BL::RenderPass::type_DIFFUSE_COLOR:
238                         return PASS_DIFFUSE_COLOR;
239                 case BL::RenderPass::type_GLOSSY_COLOR:
240                         return PASS_GLOSSY_COLOR;
241                 case BL::RenderPass::type_TRANSMISSION_COLOR:
242                         return PASS_TRANSMISSION_COLOR;
243                 case BL::RenderPass::type_SUBSURFACE_COLOR:
244                         return PASS_SUBSURFACE_COLOR;
245
246                 case BL::RenderPass::type_EMIT:
247                         return PASS_EMISSION;
248                 case BL::RenderPass::type_ENVIRONMENT:
249                         return PASS_BACKGROUND;
250                 case BL::RenderPass::type_AO:
251                         return PASS_AO;
252                 case BL::RenderPass::type_SHADOW:
253                         return PASS_SHADOW;
254
255                 case BL::RenderPass::type_DIFFUSE:
256                 case BL::RenderPass::type_COLOR:
257                 case BL::RenderPass::type_REFRACTION:
258                 case BL::RenderPass::type_SPECULAR:
259                 case BL::RenderPass::type_REFLECTION:
260                         return PASS_NONE;
261         }
262         
263         return PASS_NONE;
264 }
265
266 static ShaderEvalType get_shader_type(const string& pass_type)
267 {
268         const char *shader_type = pass_type.c_str();
269
270         /* data passes */
271         if(strcmp(shader_type, "NORMAL")==0)
272                 return SHADER_EVAL_NORMAL;
273         else if(strcmp(shader_type, "UV")==0)
274                 return SHADER_EVAL_UV;
275         else if(strcmp(shader_type, "DIFFUSE_COLOR")==0)
276                 return SHADER_EVAL_DIFFUSE_COLOR;
277         else if(strcmp(shader_type, "GLOSSY_COLOR")==0)
278                 return SHADER_EVAL_GLOSSY_COLOR;
279         else if(strcmp(shader_type, "TRANSMISSION_COLOR")==0)
280                 return SHADER_EVAL_TRANSMISSION_COLOR;
281         else if(strcmp(shader_type, "SUBSURFACE_COLOR")==0)
282                 return SHADER_EVAL_SUBSURFACE_COLOR;
283         else if(strcmp(shader_type, "EMIT")==0)
284                 return SHADER_EVAL_EMISSION;
285
286         /* light passes */
287         else if(strcmp(shader_type, "AO")==0)
288                 return SHADER_EVAL_AO;
289         else if(strcmp(shader_type, "COMBINED")==0)
290                 return SHADER_EVAL_COMBINED;
291         else if(strcmp(shader_type, "SHADOW")==0)
292                 return SHADER_EVAL_SHADOW;
293         else if(strcmp(shader_type, "DIFFUSE_DIRECT")==0)
294                 return SHADER_EVAL_DIFFUSE_DIRECT;
295         else if(strcmp(shader_type, "GLOSSY_DIRECT")==0)
296                 return SHADER_EVAL_GLOSSY_DIRECT;
297         else if(strcmp(shader_type, "TRANSMISSION_DIRECT")==0)
298                 return SHADER_EVAL_TRANSMISSION_DIRECT;
299         else if(strcmp(shader_type, "SUBSURFACE_DIRECT")==0)
300                 return SHADER_EVAL_SUBSURFACE_DIRECT;
301         else if(strcmp(shader_type, "DIFFUSE_INDIRECT")==0)
302                 return SHADER_EVAL_DIFFUSE_INDIRECT;
303         else if(strcmp(shader_type, "GLOSSY_INDIRECT")==0)
304                 return SHADER_EVAL_GLOSSY_INDIRECT;
305         else if(strcmp(shader_type, "TRANSMISSION_INDIRECT")==0)
306                 return SHADER_EVAL_TRANSMISSION_INDIRECT;
307         else if(strcmp(shader_type, "SUBSURFACE_INDIRECT")==0)
308                 return SHADER_EVAL_SUBSURFACE_INDIRECT;
309
310         /* extra */
311         else if(strcmp(shader_type, "ENVIRONMENT")==0)
312                 return SHADER_EVAL_ENVIRONMENT;
313
314         else
315                 return SHADER_EVAL_BAKE;
316 }
317
318 static BL::RenderResult begin_render_result(BL::RenderEngine b_engine, int x, int y, int w, int h, const char *layername)
319 {
320         return b_engine.begin_result(x, y, w, h, layername);
321 }
322
323 static void end_render_result(BL::RenderEngine b_engine, BL::RenderResult b_rr, bool cancel, bool do_merge_results)
324 {
325         b_engine.end_result(b_rr, (int)cancel, (int)do_merge_results);
326 }
327
328 void BlenderSession::do_write_update_render_tile(RenderTile& rtile, bool do_update_only)
329 {
330         BufferParams& params = rtile.buffers->params;
331         int x = params.full_x - session->tile_manager.params.full_x;
332         int y = params.full_y - session->tile_manager.params.full_y;
333         int w = params.width;
334         int h = params.height;
335
336         /* get render result */
337         BL::RenderResult b_rr = begin_render_result(b_engine, x, y, w, h, b_rlay_name.c_str());
338
339         /* can happen if the intersected rectangle gives 0 width or height */
340         if (b_rr.ptr.data == NULL) {
341                 return;
342         }
343
344         BL::RenderResult::layers_iterator b_single_rlay;
345         b_rr.layers.begin(b_single_rlay);
346
347         /* layer will be missing if it was disabled in the UI */
348         if(b_single_rlay == b_rr.layers.end())
349                 return;
350
351         BL::RenderLayer b_rlay = *b_single_rlay;
352
353         if (do_update_only) {
354                 /* update only needed */
355
356                 if (rtile.sample != 0) {
357                         /* sample would be zero at initial tile update, which is only needed
358                          * to tag tile form blender side as IN PROGRESS for proper highlight
359                          * no buffers should be sent to blender yet
360                          */
361                         update_render_result(b_rr, b_rlay, rtile);
362                 }
363
364                 end_render_result(b_engine, b_rr, true, true);
365         }
366         else {
367                 /* write result */
368                 write_render_result(b_rr, b_rlay, rtile);
369                 end_render_result(b_engine, b_rr, false, true);
370         }
371 }
372
373 void BlenderSession::write_render_tile(RenderTile& rtile)
374 {
375         do_write_update_render_tile(rtile, false);
376 }
377
378 void BlenderSession::update_render_tile(RenderTile& rtile)
379 {
380         /* use final write for preview renders, otherwise render result wouldn't be
381          * be updated in blender side
382          * would need to be investigated a bit further, but for now shall be fine
383          */
384         if (!b_engine.is_preview())
385                 do_write_update_render_tile(rtile, true);
386         else
387                 do_write_update_render_tile(rtile, false);
388 }
389
390 void BlenderSession::render()
391 {
392         /* set callback to write out render results */
393         session->write_render_tile_cb = function_bind(&BlenderSession::write_render_tile, this, _1);
394         session->update_render_tile_cb = function_bind(&BlenderSession::update_render_tile, this, _1);
395
396         /* get buffer parameters */
397         SessionParams session_params = BlenderSync::get_session_params(b_engine, b_userpref, b_scene, background);
398         BufferParams buffer_params = BlenderSync::get_buffer_params(b_render, b_scene, b_v3d, b_rv3d, scene->camera, width, height);
399
400         /* render each layer */
401         BL::RenderSettings r = b_scene.render();
402         BL::RenderSettings::layers_iterator b_iter;
403         
404         for(r.layers.begin(b_iter); b_iter != r.layers.end(); ++b_iter) {
405                 b_rlay_name = b_iter->name();
406
407                 /* temporary render result to find needed passes */
408                 BL::RenderResult b_rr = begin_render_result(b_engine, 0, 0, 1, 1, b_rlay_name.c_str());
409                 BL::RenderResult::layers_iterator b_single_rlay;
410                 b_rr.layers.begin(b_single_rlay);
411
412                 /* layer will be missing if it was disabled in the UI */
413                 if(b_single_rlay == b_rr.layers.end()) {
414                         end_render_result(b_engine, b_rr, true, false);
415                         continue;
416                 }
417
418                 BL::RenderLayer b_rlay = *b_single_rlay;
419
420                 /* add passes */
421                 vector<Pass> passes;
422                 Pass::add(PASS_COMBINED, passes);
423
424                 if(session_params.device.advanced_shading) {
425
426                         /* loop over passes */
427                         BL::RenderLayer::passes_iterator b_pass_iter;
428
429                         for(b_rlay.passes.begin(b_pass_iter); b_pass_iter != b_rlay.passes.end(); ++b_pass_iter) {
430                                 BL::RenderPass b_pass(*b_pass_iter);
431                                 PassType pass_type = get_pass_type(b_pass);
432
433                                 if(pass_type == PASS_MOTION && scene->integrator->motion_blur)
434                                         continue;
435                                 if(pass_type != PASS_NONE)
436                                         Pass::add(pass_type, passes);
437                         }
438                 }
439
440                 /* free result without merging */
441                 end_render_result(b_engine, b_rr, true, false);
442
443                 buffer_params.passes = passes;
444                 scene->film->pass_alpha_threshold = b_iter->pass_alpha_threshold();
445                 scene->film->tag_passes_update(scene, passes);
446                 scene->film->tag_update(scene);
447                 scene->integrator->tag_update(scene);
448
449                 /* update scene */
450                 sync->sync_camera(b_render, b_engine.camera_override(), width, height);
451                 sync->sync_data(b_v3d, b_engine.camera_override(), &python_thread_state, b_rlay_name.c_str());
452
453                 /* update number of samples per layer */
454                 int samples = sync->get_layer_samples();
455                 bool bound_samples = sync->get_layer_bound_samples();
456
457                 if(samples != 0 && (!bound_samples || (samples < session_params.samples)))
458                         session->reset(buffer_params, samples);
459                 else
460                         session->reset(buffer_params, session_params.samples);
461
462                 /* render */
463                 session->start();
464                 session->wait();
465
466                 if(session->progress.get_cancel())
467                         break;
468         }
469
470         /* clear callback */
471         session->write_render_tile_cb = NULL;
472         session->update_render_tile_cb = NULL;
473
474         /* free all memory used (host and device), so we wouldn't leave render
475          * engine with extra memory allocated
476          */
477
478         session->device_free();
479
480         delete sync;
481         sync = NULL;
482 }
483
484 static void populate_bake_data(BakeData *data, BL::BakePixel pixel_array, const int num_pixels)
485 {
486         BL::BakePixel bp = pixel_array;
487
488         int i;
489         for(i=0; i < num_pixels; i++) {
490                 data->set(i, bp.primitive_id(), bp.uv());
491                 bp = bp.next();
492         }
493 }
494
495 static bool is_light_pass(ShaderEvalType type)
496 {
497         switch (type) {
498                 case SHADER_EVAL_AO:
499                 case SHADER_EVAL_COMBINED:
500                 case SHADER_EVAL_SHADOW:
501                 case SHADER_EVAL_DIFFUSE_DIRECT:
502                 case SHADER_EVAL_GLOSSY_DIRECT:
503                 case SHADER_EVAL_TRANSMISSION_DIRECT:
504                 case SHADER_EVAL_SUBSURFACE_DIRECT:
505                 case SHADER_EVAL_DIFFUSE_INDIRECT:
506                 case SHADER_EVAL_GLOSSY_INDIRECT:
507                 case SHADER_EVAL_TRANSMISSION_INDIRECT:
508                 case SHADER_EVAL_SUBSURFACE_INDIRECT:
509                         return true;
510                 default:
511                         return false;
512         }
513 }
514
515 void BlenderSession::bake(BL::Object b_object, const string& pass_type, BL::BakePixel pixel_array, int num_pixels, int depth, float result[])
516 {
517         ShaderEvalType shader_type = get_shader_type(pass_type);
518         size_t object_index = OBJECT_NONE;
519         int tri_offset = 0;
520
521         if(shader_type == SHADER_EVAL_UV) {
522                 /* force UV to be available */
523                 Pass::add(PASS_UV, scene->film->passes);
524         }
525
526         if(is_light_pass(shader_type)) {
527                 /* force use_light_pass to be true */
528                 Pass::add(PASS_LIGHT, scene->film->passes);
529         }
530
531         /* create device and update scene */
532         scene->film->tag_update(scene);
533         scene->integrator->tag_update(scene);
534
535         /* update scene */
536         sync->sync_camera(b_render, b_engine.camera_override(), width, height);
537         sync->sync_data(b_v3d, b_engine.camera_override(), &python_thread_state);
538
539         /* get buffer parameters */
540         SessionParams session_params = BlenderSync::get_session_params(b_engine, b_userpref, b_scene, background);
541         BufferParams buffer_params = BlenderSync::get_buffer_params(b_render, b_scene, b_v3d, b_rv3d, scene->camera, width, height);
542
543         scene->bake_manager->set_baking(true);
544
545         /* set number of samples */
546         session->tile_manager.set_samples(session_params.samples);
547         session->reset(buffer_params, session_params.samples);
548         session->update_scene();
549
550         /* find object index. todo: is arbitrary - copied from mesh_displace.cpp */
551         for(size_t i = 0; i < scene->objects.size(); i++) {
552                 if(strcmp(scene->objects[i]->name.c_str(), b_object.name().c_str()) == 0) {
553                         object_index = i;
554                         tri_offset = scene->objects[i]->mesh->tri_offset;
555                         break;
556                 }
557         }
558
559         /* when used, non-instanced convention: object = ~object */
560         int object = ~object_index;
561
562         BakeData *bake_data = scene->bake_manager->init(object, tri_offset, num_pixels);
563
564         populate_bake_data(bake_data, pixel_array, num_pixels);
565
566         /* set number of samples */
567         session->tile_manager.set_samples(session_params.samples);
568         session->reset(buffer_params, session_params.samples);
569         session->update_scene();
570
571         scene->bake_manager->bake(scene->device, &scene->dscene, scene, session->progress, shader_type, bake_data, result);
572
573         /* free all memory used (host and device), so we wouldn't leave render
574          * engine with extra memory allocated
575          */
576
577         session->device_free();
578
579         delete sync;
580         sync = NULL;
581 }
582
583 void BlenderSession::do_write_update_render_result(BL::RenderResult b_rr, BL::RenderLayer b_rlay, RenderTile& rtile, bool do_update_only)
584 {
585         RenderBuffers *buffers = rtile.buffers;
586
587         /* copy data from device */
588         if(!buffers->copy_from_device())
589                 return;
590
591         BufferParams& params = buffers->params;
592         float exposure = scene->film->exposure;
593
594         vector<float> pixels(params.width*params.height*4);
595
596         if (!do_update_only) {
597                 /* copy each pass */
598                 BL::RenderLayer::passes_iterator b_iter;
599
600                 for(b_rlay.passes.begin(b_iter); b_iter != b_rlay.passes.end(); ++b_iter) {
601                         BL::RenderPass b_pass(*b_iter);
602
603                         /* find matching pass type */
604                         PassType pass_type = get_pass_type(b_pass);
605                         int components = b_pass.channels();
606
607                         /* copy pixels */
608                         if(!buffers->get_pass_rect(pass_type, exposure, rtile.sample, components, &pixels[0]))
609                                 memset(&pixels[0], 0, pixels.size()*sizeof(float));
610
611                         b_pass.rect(&pixels[0]);
612                 }
613         }
614
615         /* copy combined pass */
616         if(buffers->get_pass_rect(PASS_COMBINED, exposure, rtile.sample, 4, &pixels[0]))
617                 b_rlay.rect(&pixels[0]);
618
619         /* tag result as updated */
620         b_engine.update_result(b_rr);
621 }
622
623 void BlenderSession::write_render_result(BL::RenderResult b_rr, BL::RenderLayer b_rlay, RenderTile& rtile)
624 {
625         do_write_update_render_result(b_rr, b_rlay, rtile, false);
626 }
627
628 void BlenderSession::update_render_result(BL::RenderResult b_rr, BL::RenderLayer b_rlay, RenderTile& rtile)
629 {
630         do_write_update_render_result(b_rr, b_rlay, rtile, true);
631 }
632
633 void BlenderSession::synchronize()
634 {
635         /* only used for viewport render */
636         if(!b_v3d)
637                 return;
638
639         /* on session/scene parameter changes, we recreate session entirely */
640         SceneParams scene_params = BlenderSync::get_scene_params(b_scene, background);
641         SessionParams session_params = BlenderSync::get_session_params(b_engine, b_userpref, b_scene, background);
642
643         if(session->params.modified(session_params) ||
644            scene->params.modified(scene_params))
645         {
646                 free_session();
647                 create_session();
648                 session->start();
649                 return;
650         }
651
652         /* increase samples, but never decrease */
653         session->set_samples(session_params.samples);
654         session->set_pause(BlenderSync::get_session_pause(b_scene, background));
655
656         /* copy recalc flags, outside of mutex so we can decide to do the real
657          * synchronization at a later time to not block on running updates */
658         sync->sync_recalc();
659
660         /* try to acquire mutex. if we don't want to or can't, come back later */
661         if(!session->ready_to_reset() || !session->scene->mutex.try_lock()) {
662                 tag_update();
663                 return;
664         }
665
666         /* data and camera synchronize */
667         sync->sync_data(b_v3d, b_engine.camera_override(), &python_thread_state);
668
669         if(b_rv3d)
670                 sync->sync_view(b_v3d, b_rv3d, width, height);
671         else
672                 sync->sync_camera(b_render, b_engine.camera_override(), width, height);
673
674         /* unlock */
675         session->scene->mutex.unlock();
676
677         /* reset if needed */
678         if(scene->need_reset()) {
679                 BufferParams buffer_params = BlenderSync::get_buffer_params(b_render, b_scene, b_v3d, b_rv3d, scene->camera, width, height);
680                 session->reset(buffer_params, session_params.samples);
681
682                 /* reset time */
683                 start_resize_time = 0.0;
684         }
685 }
686
687 bool BlenderSession::draw(int w, int h)
688 {
689         /* pause in redraw in case update is not being called due to final render */
690         session->set_pause(BlenderSync::get_session_pause(b_scene, background));
691
692         /* before drawing, we verify camera and viewport size changes, because
693          * we do not get update callbacks for those, we must detect them here */
694         if(session->ready_to_reset()) {
695                 bool reset = false;
696
697                 /* if dimensions changed, reset */
698                 if(width != w || height != h) {
699                         if(start_resize_time == 0.0) {
700                                 /* don't react immediately to resizes to avoid flickery resizing
701                                  * of the viewport, and some window managers changing the window
702                                  * size temporarily on unminimize */
703                                 start_resize_time = time_dt();
704                                 tag_redraw();
705                         }
706                         else if(time_dt() - start_resize_time < 0.2) {
707                                 tag_redraw();
708                         }
709                         else {
710                                 width = w;
711                                 height = h;
712                                 reset = true;
713                         }
714                 }
715
716                 /* try to acquire mutex. if we can't, come back later */
717                 if(!session->scene->mutex.try_lock()) {
718                         tag_update();
719                 }
720                 else {
721                         /* update camera from 3d view */
722
723                         sync->sync_view(b_v3d, b_rv3d, width, height);
724
725                         if(scene->camera->need_update)
726                                 reset = true;
727
728                         session->scene->mutex.unlock();
729                 }
730
731                 /* reset if requested */
732                 if(reset) {
733                         SessionParams session_params = BlenderSync::get_session_params(b_engine, b_userpref, b_scene, background);
734                         BufferParams buffer_params = BlenderSync::get_buffer_params(b_render, b_scene, b_v3d, b_rv3d, scene->camera, width, height);
735
736                         session->reset(buffer_params, session_params.samples);
737
738                         start_resize_time = 0.0;
739                 }
740         }
741         else {
742                 tag_update();
743         }
744
745         /* update status and progress for 3d view draw */
746         update_status_progress();
747
748         /* draw */
749         BufferParams buffer_params = BlenderSync::get_buffer_params(b_render, b_scene, b_v3d, b_rv3d, scene->camera, width, height);
750         DeviceDrawParams draw_params;
751
752         if(session->params.display_buffer_linear) {
753                 draw_params.bind_display_space_shader_cb = function_bind(&BL::RenderEngine::bind_display_space_shader, &b_engine, b_scene);
754                 draw_params.unbind_display_space_shader_cb = function_bind(&BL::RenderEngine::unbind_display_space_shader, &b_engine);
755         }
756
757         return !session->draw(buffer_params, draw_params);
758 }
759
760 void BlenderSession::get_status(string& status, string& substatus)
761 {
762         session->progress.get_status(status, substatus);
763 }
764
765 void BlenderSession::get_progress(float& progress, double& total_time)
766 {
767         double tile_time;
768         int tile, sample, samples_per_tile;
769         int tile_total = session->tile_manager.state.num_tiles;
770
771         session->progress.get_tile(tile, total_time, tile_time);
772
773         sample = session->progress.get_sample();
774         samples_per_tile = session->tile_manager.num_samples;
775
776         if(samples_per_tile && tile_total)
777                 progress = ((float)sample / (float)(tile_total * samples_per_tile));
778         else
779                 progress = 0.0;
780 }
781
782 void BlenderSession::update_status_progress()
783 {
784         string timestatus, status, substatus;
785         string scene = "";
786         float progress;
787         double total_time, remaining_time = 0;
788         char time_str[128];
789         float mem_used = (float)session->stats.mem_used / 1024.0f / 1024.0f;
790         float mem_peak = (float)session->stats.mem_peak / 1024.0f / 1024.0f;
791         int samples = session->tile_manager.state.sample + 1;
792         int total_samples = session->tile_manager.num_samples;
793
794         get_status(status, substatus);
795         get_progress(progress, total_time);
796
797         
798
799         if(background) {
800                 if(progress>0)
801                         remaining_time = (1-progress) * (total_time / progress);
802
803                 scene += " | " + b_scene.name();
804                 if(b_rlay_name != "")
805                         scene += ", "  + b_rlay_name;
806         }
807         else {
808                 BLI_timestr(total_time, time_str, sizeof(time_str));
809                 timestatus = "Time:" + string(time_str) + " | ";
810
811                 if(samples > 0 && total_samples != USHRT_MAX)
812                         remaining_time = (total_samples - samples) * (total_time / samples);
813         }
814         
815         if(remaining_time>0) {
816                 BLI_timestr(remaining_time, time_str, sizeof(time_str));
817                 timestatus += "Remaining:" + string(time_str) + " | ";
818         }
819         
820         timestatus += string_printf("Mem:%.2fM, Peak:%.2fM", mem_used, mem_peak);
821
822         if(status.size() > 0)
823                 status = " | " + status;
824         if(substatus.size() > 0)
825                 status += " | " + substatus;
826
827         if(status != last_status) {
828                 b_engine.update_stats("", (timestatus + scene + status).c_str());
829                 b_engine.update_memory_stats(mem_used, mem_peak);
830                 last_status = status;
831         }
832         if(progress != last_progress) {
833                 b_engine.update_progress(progress);
834                 last_progress = progress;
835         }
836 }
837
838 void BlenderSession::tag_update()
839 {
840         /* tell blender that we want to get another update callback */
841         b_engine.tag_update();
842 }
843
844 void BlenderSession::tag_redraw()
845 {
846         if(background) {
847                 /* update stats and progress, only for background here because
848                  * in 3d view we do it in draw for thread safety reasons */
849                 update_status_progress();
850
851                 /* offline render, redraw if timeout passed */
852                 if(time_dt() - last_redraw_time > 1.0) {
853                         b_engine.tag_redraw();
854                         last_redraw_time = time_dt();
855                 }
856         }
857         else {
858                 /* tell blender that we want to redraw */
859                 b_engine.tag_redraw();
860         }
861 }
862
863 void BlenderSession::test_cancel()
864 {
865         /* test if we need to cancel rendering */
866         if(background)
867                 if(b_engine.test_break())
868                         session->progress.set_cancel("Cancelled");
869 }
870
871 /* builtin image file name is actually an image datablock name with
872  * absolute sequence frame number concatenated via '@' character
873  *
874  * this function splits frame from builtin name
875  */
876 int BlenderSession::builtin_image_frame(const string &builtin_name)
877 {
878         int last = builtin_name.find_last_of('@');
879         return atoi(builtin_name.substr(last + 1, builtin_name.size() - last - 1).c_str());
880 }
881
882 void BlenderSession::builtin_image_info(const string &builtin_name, void *builtin_data, bool &is_float, int &width, int &height, int &depth, int &channels)
883 {
884         /* empty image */
885         is_float = false;
886         width = 0;
887         height = 0;
888         depth = 0;
889         channels = 0;
890
891         if(!builtin_data)
892                 return;
893
894         /* recover ID pointer */
895         PointerRNA ptr;
896         RNA_id_pointer_create((ID*)builtin_data, &ptr);
897         BL::ID b_id(ptr);
898
899         if(b_id.is_a(&RNA_Image)) {
900                 /* image data */
901                 BL::Image b_image(b_id);
902
903                 is_float = b_image.is_float();
904                 width = b_image.size()[0];
905                 height = b_image.size()[1];
906                 depth = 1;
907                 channels = b_image.channels();
908         }
909         else if(b_id.is_a(&RNA_Object)) {
910                 /* smoke volume data */
911                 BL::Object b_ob(b_id);
912                 BL::SmokeDomainSettings b_domain = object_smoke_domain_find(b_ob);
913
914                 if(!b_domain)
915                         return;
916
917                 if(builtin_name == Attribute::standard_name(ATTR_STD_VOLUME_DENSITY) ||
918                    builtin_name == Attribute::standard_name(ATTR_STD_VOLUME_FLAME))
919                         channels = 1;
920                 else if(builtin_name == Attribute::standard_name(ATTR_STD_VOLUME_COLOR))
921                         channels = 4;
922                 else
923                         return;
924
925                 int3 resolution = get_int3(b_domain.domain_resolution());
926                 int amplify = (b_domain.use_high_resolution())? b_domain.amplify() + 1: 1;
927
928                 width = resolution.x * amplify;
929                 height = resolution.y * amplify;
930                 depth = resolution.z * amplify;
931
932                 is_float = true;
933         }
934 }
935
936 bool BlenderSession::builtin_image_pixels(const string &builtin_name, void *builtin_data, unsigned char *pixels)
937 {
938         if(!builtin_data)
939                 return false;
940
941         int frame = builtin_image_frame(builtin_name);
942
943         PointerRNA ptr;
944         RNA_id_pointer_create((ID*)builtin_data, &ptr);
945         BL::Image b_image(ptr);
946
947         int width = b_image.size()[0];
948         int height = b_image.size()[1];
949         int channels = b_image.channels();
950
951         unsigned char *image_pixels;
952         image_pixels = image_get_pixels_for_frame(b_image, frame);
953
954         if(image_pixels) {
955                 memcpy(pixels, image_pixels, width * height * channels * sizeof(unsigned char));
956                 MEM_freeN(image_pixels);
957         }
958         else {
959                 if(channels == 1) {
960                         memset(pixels, 0, width * height * sizeof(unsigned char));
961                 }
962                 else {
963                         unsigned char *cp = pixels;
964                         for(int i = 0; i < width * height; i++, cp += channels) {
965                                 cp[0] = 255;
966                                 cp[1] = 0;
967                                 cp[2] = 255;
968                                 if(channels == 4)
969                                         cp[3] = 255;
970                         }
971                 }
972         }
973
974         /* premultiply, byte images are always straight for blender */
975         unsigned char *cp = pixels;
976         for(int i = 0; i < width * height; i++, cp += channels) {
977                 cp[0] = (cp[0] * cp[3]) >> 8;
978                 cp[1] = (cp[1] * cp[3]) >> 8;
979                 cp[2] = (cp[2] * cp[3]) >> 8;
980         }
981
982         return true;
983 }
984
985 bool BlenderSession::builtin_image_float_pixels(const string &builtin_name, void *builtin_data, float *pixels)
986 {
987         if(!builtin_data)
988                 return false;
989
990         PointerRNA ptr;
991         RNA_id_pointer_create((ID*)builtin_data, &ptr);
992         BL::ID b_id(ptr);
993
994         if(b_id.is_a(&RNA_Image)) {
995                 /* image data */
996                 BL::Image b_image(b_id);
997                 int frame = builtin_image_frame(builtin_name);
998
999                 int width = b_image.size()[0];
1000                 int height = b_image.size()[1];
1001                 int channels = b_image.channels();
1002
1003                 float *image_pixels;
1004                 image_pixels = image_get_float_pixels_for_frame(b_image, frame);
1005
1006                 if(image_pixels) {
1007                         memcpy(pixels, image_pixels, width * height * channels * sizeof(float));
1008                         MEM_freeN(image_pixels);
1009                 }
1010                 else {
1011                         if(channels == 1) {
1012                                 memset(pixels, 0, width * height * sizeof(float));
1013                         }
1014                         else {
1015                                 float *fp = pixels;
1016                                 for(int i = 0; i < width * height; i++, fp += channels) {
1017                                         fp[0] = 1.0f;
1018                                         fp[1] = 0.0f;
1019                                         fp[2] = 1.0f;
1020                                         if(channels == 4)
1021                                                 fp[3] = 1.0f;
1022                                 }
1023                         }
1024                 }
1025
1026                 return true;
1027         }
1028         else if(b_id.is_a(&RNA_Object)) {
1029                 /* smoke volume data */
1030                 BL::Object b_ob(b_id);
1031                 BL::SmokeDomainSettings b_domain = object_smoke_domain_find(b_ob);
1032
1033                 if(!b_domain)
1034                         return false;
1035
1036                 int3 resolution = get_int3(b_domain.domain_resolution());
1037                 int length, amplify = (b_domain.use_high_resolution())? b_domain.amplify() + 1: 1;
1038
1039                 int width = resolution.x * amplify;
1040                 int height = resolution.y * amplify;
1041                 int depth = resolution.z * amplify;
1042
1043                 if(builtin_name == Attribute::standard_name(ATTR_STD_VOLUME_DENSITY)) {
1044                         SmokeDomainSettings_density_grid_get_length(&b_domain.ptr, &length);
1045
1046                         if(length == width*height*depth) {
1047                                 SmokeDomainSettings_density_grid_get(&b_domain.ptr, pixels);
1048                                 return true;
1049                         }
1050                 }
1051                 else if(builtin_name == Attribute::standard_name(ATTR_STD_VOLUME_FLAME)) {
1052                         /* this is in range 0..1, and interpreted by the OpenGL smoke viewer
1053                          * as 1500..3000 K with the first part faded to zero density */
1054                         SmokeDomainSettings_flame_grid_get_length(&b_domain.ptr, &length);
1055
1056                         if(length == width*height*depth) {
1057                                 SmokeDomainSettings_flame_grid_get(&b_domain.ptr, pixels);
1058                                 return true;
1059                         }
1060                 }
1061                 else if(builtin_name == Attribute::standard_name(ATTR_STD_VOLUME_COLOR)) {
1062                         /* the RGB is "premultiplied" by density for better interpolation results */
1063                         SmokeDomainSettings_color_grid_get_length(&b_domain.ptr, &length);
1064
1065                         if(length == width*height*depth*4) {
1066                                 SmokeDomainSettings_color_grid_get(&b_domain.ptr, pixels);
1067                                 return true;
1068                         }
1069                 }
1070
1071                 fprintf(stderr, "Cycles error: unexpected smoke volume resolution, skipping\n");
1072         }
1073
1074         return false;
1075 }
1076
1077 CCL_NAMESPACE_END
1078