Cycles Bake: use size_t instead of width, height
[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(), bp.du_dx(), bp.du_dy(), bp.dv_dx(), bp.dv_dy());
491                 bp = bp.next();
492         }
493 }
494
495 void BlenderSession::bake(BL::Object b_object, const string& pass_type, BL::BakePixel pixel_array, const size_t num_pixels, const int depth, float result[])
496 {
497         ShaderEvalType shader_type = get_shader_type(pass_type);
498         size_t object_index = OBJECT_NONE;
499         int tri_offset = 0;
500
501         /* ensure kernels are loaded before we do any scene updates */
502         session->load_kernels();
503
504         if(session->progress.get_cancel())
505                 return;
506
507         if(shader_type == SHADER_EVAL_UV) {
508                 /* force UV to be available */
509                 Pass::add(PASS_UV, scene->film->passes);
510         }
511
512         if(BakeManager::is_light_pass(shader_type)) {
513                 /* force use_light_pass to be true */
514                 Pass::add(PASS_LIGHT, scene->film->passes);
515         }
516
517         /* create device and update scene */
518         scene->film->tag_update(scene);
519         scene->integrator->tag_update(scene);
520
521         /* update scene */
522         sync->sync_camera(b_render, b_engine.camera_override(), width, height);
523         sync->sync_data(b_v3d, b_engine.camera_override(), &python_thread_state);
524
525         /* get buffer parameters */
526         SessionParams session_params = BlenderSync::get_session_params(b_engine, b_userpref, b_scene, background);
527         BufferParams buffer_params = BlenderSync::get_buffer_params(b_render, b_scene, b_v3d, b_rv3d, scene->camera, width, height);
528
529         scene->bake_manager->set_baking(true);
530
531         /* set number of samples */
532         session->tile_manager.set_samples(session_params.samples);
533         session->reset(buffer_params, session_params.samples);
534         session->update_scene();
535
536         /* find object index. todo: is arbitrary - copied from mesh_displace.cpp */
537         for(size_t i = 0; i < scene->objects.size(); i++) {
538                 if(strcmp(scene->objects[i]->name.c_str(), b_object.name().c_str()) == 0) {
539                         object_index = i;
540                         tri_offset = scene->objects[i]->mesh->tri_offset;
541                         break;
542                 }
543         }
544
545         /* when used, non-instanced convention: object = ~object */
546         int object = ~object_index;
547
548         BakeData *bake_data = scene->bake_manager->init(object, tri_offset, num_pixels);
549
550         populate_bake_data(bake_data, pixel_array, num_pixels);
551
552         /* set number of samples */
553         session->tile_manager.set_samples(session_params.samples);
554         session->reset(buffer_params, session_params.samples);
555         session->update_scene();
556
557         session->progress.set_update_callback(function_bind(&BlenderSession::update_bake_progress, this));
558
559         scene->bake_manager->bake(scene->device, &scene->dscene, scene, session->progress, shader_type, bake_data, result);
560
561         /* free all memory used (host and device), so we wouldn't leave render
562          * engine with extra memory allocated
563          */
564
565         session->device_free();
566
567         delete sync;
568         sync = NULL;
569 }
570
571 void BlenderSession::do_write_update_render_result(BL::RenderResult b_rr, BL::RenderLayer b_rlay, RenderTile& rtile, bool do_update_only)
572 {
573         RenderBuffers *buffers = rtile.buffers;
574
575         /* copy data from device */
576         if(!buffers->copy_from_device())
577                 return;
578
579         BufferParams& params = buffers->params;
580         float exposure = scene->film->exposure;
581
582         vector<float> pixels(params.width*params.height*4);
583
584         if (!do_update_only) {
585                 /* copy each pass */
586                 BL::RenderLayer::passes_iterator b_iter;
587
588                 for(b_rlay.passes.begin(b_iter); b_iter != b_rlay.passes.end(); ++b_iter) {
589                         BL::RenderPass b_pass(*b_iter);
590
591                         /* find matching pass type */
592                         PassType pass_type = get_pass_type(b_pass);
593                         int components = b_pass.channels();
594
595                         /* copy pixels */
596                         if(!buffers->get_pass_rect(pass_type, exposure, rtile.sample, components, &pixels[0]))
597                                 memset(&pixels[0], 0, pixels.size()*sizeof(float));
598
599                         b_pass.rect(&pixels[0]);
600                 }
601         }
602
603         /* copy combined pass */
604         if(buffers->get_pass_rect(PASS_COMBINED, exposure, rtile.sample, 4, &pixels[0]))
605                 b_rlay.rect(&pixels[0]);
606
607         /* tag result as updated */
608         b_engine.update_result(b_rr);
609 }
610
611 void BlenderSession::write_render_result(BL::RenderResult b_rr, BL::RenderLayer b_rlay, RenderTile& rtile)
612 {
613         do_write_update_render_result(b_rr, b_rlay, rtile, false);
614 }
615
616 void BlenderSession::update_render_result(BL::RenderResult b_rr, BL::RenderLayer b_rlay, RenderTile& rtile)
617 {
618         do_write_update_render_result(b_rr, b_rlay, rtile, true);
619 }
620
621 void BlenderSession::synchronize()
622 {
623         /* only used for viewport render */
624         if(!b_v3d)
625                 return;
626
627         /* on session/scene parameter changes, we recreate session entirely */
628         SceneParams scene_params = BlenderSync::get_scene_params(b_scene, background);
629         SessionParams session_params = BlenderSync::get_session_params(b_engine, b_userpref, b_scene, background);
630
631         if(session->params.modified(session_params) ||
632            scene->params.modified(scene_params))
633         {
634                 free_session();
635                 create_session();
636                 session->start();
637                 return;
638         }
639
640         /* increase samples, but never decrease */
641         session->set_samples(session_params.samples);
642         session->set_pause(BlenderSync::get_session_pause(b_scene, background));
643
644         /* copy recalc flags, outside of mutex so we can decide to do the real
645          * synchronization at a later time to not block on running updates */
646         sync->sync_recalc();
647
648         /* try to acquire mutex. if we don't want to or can't, come back later */
649         if(!session->ready_to_reset() || !session->scene->mutex.try_lock()) {
650                 tag_update();
651                 return;
652         }
653
654         /* data and camera synchronize */
655         sync->sync_data(b_v3d, b_engine.camera_override(), &python_thread_state);
656
657         if(b_rv3d)
658                 sync->sync_view(b_v3d, b_rv3d, width, height);
659         else
660                 sync->sync_camera(b_render, b_engine.camera_override(), width, height);
661
662         /* unlock */
663         session->scene->mutex.unlock();
664
665         /* reset if needed */
666         if(scene->need_reset()) {
667                 BufferParams buffer_params = BlenderSync::get_buffer_params(b_render, b_scene, b_v3d, b_rv3d, scene->camera, width, height);
668                 session->reset(buffer_params, session_params.samples);
669
670                 /* reset time */
671                 start_resize_time = 0.0;
672         }
673 }
674
675 bool BlenderSession::draw(int w, int h)
676 {
677         /* pause in redraw in case update is not being called due to final render */
678         session->set_pause(BlenderSync::get_session_pause(b_scene, background));
679
680         /* before drawing, we verify camera and viewport size changes, because
681          * we do not get update callbacks for those, we must detect them here */
682         if(session->ready_to_reset()) {
683                 bool reset = false;
684
685                 /* if dimensions changed, reset */
686                 if(width != w || height != h) {
687                         if(start_resize_time == 0.0) {
688                                 /* don't react immediately to resizes to avoid flickery resizing
689                                  * of the viewport, and some window managers changing the window
690                                  * size temporarily on unminimize */
691                                 start_resize_time = time_dt();
692                                 tag_redraw();
693                         }
694                         else if(time_dt() - start_resize_time < 0.2) {
695                                 tag_redraw();
696                         }
697                         else {
698                                 width = w;
699                                 height = h;
700                                 reset = true;
701                         }
702                 }
703
704                 /* try to acquire mutex. if we can't, come back later */
705                 if(!session->scene->mutex.try_lock()) {
706                         tag_update();
707                 }
708                 else {
709                         /* update camera from 3d view */
710
711                         sync->sync_view(b_v3d, b_rv3d, width, height);
712
713                         if(scene->camera->need_update)
714                                 reset = true;
715
716                         session->scene->mutex.unlock();
717                 }
718
719                 /* reset if requested */
720                 if(reset) {
721                         SessionParams session_params = BlenderSync::get_session_params(b_engine, b_userpref, b_scene, background);
722                         BufferParams buffer_params = BlenderSync::get_buffer_params(b_render, b_scene, b_v3d, b_rv3d, scene->camera, width, height);
723
724                         session->reset(buffer_params, session_params.samples);
725
726                         start_resize_time = 0.0;
727                 }
728         }
729         else {
730                 tag_update();
731         }
732
733         /* update status and progress for 3d view draw */
734         update_status_progress();
735
736         /* draw */
737         BufferParams buffer_params = BlenderSync::get_buffer_params(b_render, b_scene, b_v3d, b_rv3d, scene->camera, width, height);
738         DeviceDrawParams draw_params;
739
740         if(session->params.display_buffer_linear) {
741                 draw_params.bind_display_space_shader_cb = function_bind(&BL::RenderEngine::bind_display_space_shader, &b_engine, b_scene);
742                 draw_params.unbind_display_space_shader_cb = function_bind(&BL::RenderEngine::unbind_display_space_shader, &b_engine);
743         }
744
745         return !session->draw(buffer_params, draw_params);
746 }
747
748 void BlenderSession::get_status(string& status, string& substatus)
749 {
750         session->progress.get_status(status, substatus);
751 }
752
753 void BlenderSession::get_progress(float& progress, double& total_time)
754 {
755         double tile_time;
756         int tile, sample, samples_per_tile;
757         int tile_total = session->tile_manager.state.num_tiles;
758
759         session->progress.get_tile(tile, total_time, tile_time);
760
761         sample = session->progress.get_sample();
762         samples_per_tile = session->tile_manager.num_samples;
763
764         if(samples_per_tile && tile_total)
765                 progress = ((float)sample / (float)(tile_total * samples_per_tile));
766         else
767                 progress = 0.0;
768 }
769
770 void BlenderSession::update_bake_progress()
771 {
772         float progress;
773         int sample, samples_per_task, parts_total;
774
775         sample = session->progress.get_sample();
776         samples_per_task = scene->bake_manager->num_samples;
777         parts_total = scene->bake_manager->num_parts;
778
779         if(samples_per_task)
780                 progress = ((float)sample / (float)(parts_total * samples_per_task));
781         else
782                 progress = 0.0;
783
784         if(progress != last_progress) {
785                 b_engine.update_progress(progress);
786                 last_progress = progress;
787         }
788 }
789
790 void BlenderSession::update_status_progress()
791 {
792         string timestatus, status, substatus;
793         string scene = "";
794         float progress;
795         double total_time, remaining_time = 0;
796         char time_str[128];
797         float mem_used = (float)session->stats.mem_used / 1024.0f / 1024.0f;
798         float mem_peak = (float)session->stats.mem_peak / 1024.0f / 1024.0f;
799         int samples = session->tile_manager.state.sample + 1;
800         int total_samples = session->tile_manager.num_samples;
801
802         get_status(status, substatus);
803         get_progress(progress, total_time);
804
805         
806
807         if(background) {
808                 if(progress>0)
809                         remaining_time = (1-progress) * (total_time / progress);
810
811                 scene += " | " + b_scene.name();
812                 if(b_rlay_name != "")
813                         scene += ", "  + b_rlay_name;
814         }
815         else {
816                 BLI_timestr(total_time, time_str, sizeof(time_str));
817                 timestatus = "Time:" + string(time_str) + " | ";
818
819                 if(samples > 0 && total_samples != USHRT_MAX)
820                         remaining_time = (total_samples - samples) * (total_time / samples);
821         }
822         
823         if(remaining_time>0) {
824                 BLI_timestr(remaining_time, time_str, sizeof(time_str));
825                 timestatus += "Remaining:" + string(time_str) + " | ";
826         }
827         
828         timestatus += string_printf("Mem:%.2fM, Peak:%.2fM", mem_used, mem_peak);
829
830         if(status.size() > 0)
831                 status = " | " + status;
832         if(substatus.size() > 0)
833                 status += " | " + substatus;
834
835         if(status != last_status) {
836                 b_engine.update_stats("", (timestatus + scene + status).c_str());
837                 b_engine.update_memory_stats(mem_used, mem_peak);
838                 last_status = status;
839         }
840         if(progress != last_progress) {
841                 b_engine.update_progress(progress);
842                 last_progress = progress;
843         }
844 }
845
846 void BlenderSession::tag_update()
847 {
848         /* tell blender that we want to get another update callback */
849         b_engine.tag_update();
850 }
851
852 void BlenderSession::tag_redraw()
853 {
854         if(background) {
855                 /* update stats and progress, only for background here because
856                  * in 3d view we do it in draw for thread safety reasons */
857                 update_status_progress();
858
859                 /* offline render, redraw if timeout passed */
860                 if(time_dt() - last_redraw_time > 1.0) {
861                         b_engine.tag_redraw();
862                         last_redraw_time = time_dt();
863                 }
864         }
865         else {
866                 /* tell blender that we want to redraw */
867                 b_engine.tag_redraw();
868         }
869 }
870
871 void BlenderSession::test_cancel()
872 {
873         /* test if we need to cancel rendering */
874         if(background)
875                 if(b_engine.test_break())
876                         session->progress.set_cancel("Cancelled");
877 }
878
879 /* builtin image file name is actually an image datablock name with
880  * absolute sequence frame number concatenated via '@' character
881  *
882  * this function splits frame from builtin name
883  */
884 int BlenderSession::builtin_image_frame(const string &builtin_name)
885 {
886         int last = builtin_name.find_last_of('@');
887         return atoi(builtin_name.substr(last + 1, builtin_name.size() - last - 1).c_str());
888 }
889
890 void BlenderSession::builtin_image_info(const string &builtin_name, void *builtin_data, bool &is_float, int &width, int &height, int &depth, int &channels)
891 {
892         /* empty image */
893         is_float = false;
894         width = 0;
895         height = 0;
896         depth = 0;
897         channels = 0;
898
899         if(!builtin_data)
900                 return;
901
902         /* recover ID pointer */
903         PointerRNA ptr;
904         RNA_id_pointer_create((ID*)builtin_data, &ptr);
905         BL::ID b_id(ptr);
906
907         if(b_id.is_a(&RNA_Image)) {
908                 /* image data */
909                 BL::Image b_image(b_id);
910
911                 is_float = b_image.is_float();
912                 width = b_image.size()[0];
913                 height = b_image.size()[1];
914                 depth = 1;
915                 channels = b_image.channels();
916         }
917         else if(b_id.is_a(&RNA_Object)) {
918                 /* smoke volume data */
919                 BL::Object b_ob(b_id);
920                 BL::SmokeDomainSettings b_domain = object_smoke_domain_find(b_ob);
921
922                 if(!b_domain)
923                         return;
924
925                 if(builtin_name == Attribute::standard_name(ATTR_STD_VOLUME_DENSITY) ||
926                    builtin_name == Attribute::standard_name(ATTR_STD_VOLUME_FLAME))
927                         channels = 1;
928                 else if(builtin_name == Attribute::standard_name(ATTR_STD_VOLUME_COLOR))
929                         channels = 4;
930                 else
931                         return;
932
933                 int3 resolution = get_int3(b_domain.domain_resolution());
934                 int amplify = (b_domain.use_high_resolution())? b_domain.amplify() + 1: 1;
935
936                 width = resolution.x * amplify;
937                 height = resolution.y * amplify;
938                 depth = resolution.z * amplify;
939
940                 is_float = true;
941         }
942 }
943
944 bool BlenderSession::builtin_image_pixels(const string &builtin_name, void *builtin_data, unsigned char *pixels)
945 {
946         if(!builtin_data)
947                 return false;
948
949         int frame = builtin_image_frame(builtin_name);
950
951         PointerRNA ptr;
952         RNA_id_pointer_create((ID*)builtin_data, &ptr);
953         BL::Image b_image(ptr);
954
955         int width = b_image.size()[0];
956         int height = b_image.size()[1];
957         int channels = b_image.channels();
958
959         unsigned char *image_pixels;
960         image_pixels = image_get_pixels_for_frame(b_image, frame);
961
962         if(image_pixels) {
963                 memcpy(pixels, image_pixels, width * height * channels * sizeof(unsigned char));
964                 MEM_freeN(image_pixels);
965         }
966         else {
967                 if(channels == 1) {
968                         memset(pixels, 0, width * height * sizeof(unsigned char));
969                 }
970                 else {
971                         unsigned char *cp = pixels;
972                         for(int i = 0; i < width * height; i++, cp += channels) {
973                                 cp[0] = 255;
974                                 cp[1] = 0;
975                                 cp[2] = 255;
976                                 if(channels == 4)
977                                         cp[3] = 255;
978                         }
979                 }
980         }
981
982         /* premultiply, byte images are always straight for blender */
983         unsigned char *cp = pixels;
984         for(int i = 0; i < width * height; i++, cp += channels) {
985                 cp[0] = (cp[0] * cp[3]) >> 8;
986                 cp[1] = (cp[1] * cp[3]) >> 8;
987                 cp[2] = (cp[2] * cp[3]) >> 8;
988         }
989
990         return true;
991 }
992
993 bool BlenderSession::builtin_image_float_pixels(const string &builtin_name, void *builtin_data, float *pixels)
994 {
995         if(!builtin_data)
996                 return false;
997
998         PointerRNA ptr;
999         RNA_id_pointer_create((ID*)builtin_data, &ptr);
1000         BL::ID b_id(ptr);
1001
1002         if(b_id.is_a(&RNA_Image)) {
1003                 /* image data */
1004                 BL::Image b_image(b_id);
1005                 int frame = builtin_image_frame(builtin_name);
1006
1007                 int width = b_image.size()[0];
1008                 int height = b_image.size()[1];
1009                 int channels = b_image.channels();
1010
1011                 float *image_pixels;
1012                 image_pixels = image_get_float_pixels_for_frame(b_image, frame);
1013
1014                 if(image_pixels) {
1015                         memcpy(pixels, image_pixels, width * height * channels * sizeof(float));
1016                         MEM_freeN(image_pixels);
1017                 }
1018                 else {
1019                         if(channels == 1) {
1020                                 memset(pixels, 0, width * height * sizeof(float));
1021                         }
1022                         else {
1023                                 float *fp = pixels;
1024                                 for(int i = 0; i < width * height; i++, fp += channels) {
1025                                         fp[0] = 1.0f;
1026                                         fp[1] = 0.0f;
1027                                         fp[2] = 1.0f;
1028                                         if(channels == 4)
1029                                                 fp[3] = 1.0f;
1030                                 }
1031                         }
1032                 }
1033
1034                 return true;
1035         }
1036         else if(b_id.is_a(&RNA_Object)) {
1037                 /* smoke volume data */
1038                 BL::Object b_ob(b_id);
1039                 BL::SmokeDomainSettings b_domain = object_smoke_domain_find(b_ob);
1040
1041                 if(!b_domain)
1042                         return false;
1043
1044                 int3 resolution = get_int3(b_domain.domain_resolution());
1045                 int length, amplify = (b_domain.use_high_resolution())? b_domain.amplify() + 1: 1;
1046
1047                 int width = resolution.x * amplify;
1048                 int height = resolution.y * amplify;
1049                 int depth = resolution.z * amplify;
1050
1051                 if(builtin_name == Attribute::standard_name(ATTR_STD_VOLUME_DENSITY)) {
1052                         SmokeDomainSettings_density_grid_get_length(&b_domain.ptr, &length);
1053
1054                         if(length == width*height*depth) {
1055                                 SmokeDomainSettings_density_grid_get(&b_domain.ptr, pixels);
1056                                 return true;
1057                         }
1058                 }
1059                 else if(builtin_name == Attribute::standard_name(ATTR_STD_VOLUME_FLAME)) {
1060                         /* this is in range 0..1, and interpreted by the OpenGL smoke viewer
1061                          * as 1500..3000 K with the first part faded to zero density */
1062                         SmokeDomainSettings_flame_grid_get_length(&b_domain.ptr, &length);
1063
1064                         if(length == width*height*depth) {
1065                                 SmokeDomainSettings_flame_grid_get(&b_domain.ptr, pixels);
1066                                 return true;
1067                         }
1068                 }
1069                 else if(builtin_name == Attribute::standard_name(ATTR_STD_VOLUME_COLOR)) {
1070                         /* the RGB is "premultiplied" by density for better interpolation results */
1071                         SmokeDomainSettings_color_grid_get_length(&b_domain.ptr, &length);
1072
1073                         if(length == width*height*depth*4) {
1074                                 SmokeDomainSettings_color_grid_get(&b_domain.ptr, pixels);
1075                                 return true;
1076                         }
1077                 }
1078
1079                 fprintf(stderr, "Cycles error: unexpected smoke volume resolution, skipping\n");
1080         }
1081
1082         return false;
1083 }
1084
1085 CCL_NAMESPACE_END
1086