Fix T54105: random walk SSS missing in branched indirect paths.
[blender-staging.git] / intern / cycles / app / cycles_standalone.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 <stdio.h>
18
19 #include "render/buffers.h"
20 #include "render/camera.h"
21 #include "device/device.h"
22 #include "render/scene.h"
23 #include "render/session.h"
24 #include "render/integrator.h"
25
26 #include "util/util_args.h"
27 #include "util/util_foreach.h"
28 #include "util/util_function.h"
29 #include "util/util_logging.h"
30 #include "util/util_path.h"
31 #include "util/util_progress.h"
32 #include "util/util_string.h"
33 #include "util/util_time.h"
34 #include "util/util_transform.h"
35 #include "util/util_version.h"
36
37 #ifdef WITH_CYCLES_STANDALONE_GUI
38 #include "util/util_view.h"
39 #endif
40
41 #include "app/cycles_xml.h"
42
43 CCL_NAMESPACE_BEGIN
44
45 struct Options {
46         Session *session;
47         Scene *scene;
48         string filepath;
49         int width, height;
50         SceneParams scene_params;
51         SessionParams session_params;
52         bool quiet;
53         bool show_help, interactive, pause;
54 } options;
55
56 static void session_print(const string& str)
57 {
58         /* print with carriage return to overwrite previous */
59         printf("\r%s", str.c_str());
60
61         /* add spaces to overwrite longer previous print */
62         static int maxlen = 0;
63         int len = str.size();
64         maxlen = max(len, maxlen);
65
66         for(int i = len; i < maxlen; i++)
67                 printf(" ");
68
69         /* flush because we don't write an end of line */
70         fflush(stdout);
71 }
72
73 static void session_print_status()
74 {
75         string status, substatus;
76
77         /* get status */
78         float progress = options.session->progress.get_progress();
79         options.session->progress.get_status(status, substatus);
80
81         if(substatus != "")
82                 status += ": " + substatus;
83
84         /* print status */
85         status = string_printf("Progress %05.2f   %s", (double) progress*100, status.c_str());
86         session_print(status);
87 }
88
89 static BufferParams& session_buffer_params()
90 {
91         static BufferParams buffer_params;
92         buffer_params.width = options.width;
93         buffer_params.height = options.height;
94         buffer_params.full_width = options.width;
95         buffer_params.full_height = options.height;
96
97         return buffer_params;
98 }
99
100 static void scene_init()
101 {
102         options.scene = new Scene(options.scene_params, options.session->device);
103
104         /* Read XML */
105         xml_read_file(options.scene, options.filepath.c_str());
106
107         /* Camera width/height override? */
108         if(!(options.width == 0 || options.height == 0)) {
109                 options.scene->camera->width = options.width;
110                 options.scene->camera->height = options.height;
111         }
112         else {
113                 options.width = options.scene->camera->width;
114                 options.height = options.scene->camera->height;
115         }
116
117         /* Calculate Viewplane */
118         options.scene->camera->compute_auto_viewplane();
119 }
120
121 static void session_init()
122 {
123         options.session = new Session(options.session_params);
124
125         if(options.session_params.background && !options.quiet)
126                 options.session->progress.set_update_callback(function_bind(&session_print_status));
127 #ifdef WITH_CYCLES_STANDALONE_GUI
128         else
129                 options.session->progress.set_update_callback(function_bind(&view_redraw));
130 #endif
131
132         /* load scene */
133         scene_init();
134         options.session->scene = options.scene;
135
136         options.session->reset(session_buffer_params(), options.session_params.samples);
137         options.session->start();
138 }
139
140 static void session_exit()
141 {
142         if(options.session) {
143                 delete options.session;
144                 options.session = NULL;
145         }
146
147         if(options.session_params.background && !options.quiet) {
148                 session_print("Finished Rendering.");
149                 printf("\n");
150         }
151 }
152
153 #ifdef WITH_CYCLES_STANDALONE_GUI
154 static void display_info(Progress& progress)
155 {
156         static double latency = 0.0;
157         static double last = 0;
158         double elapsed = time_dt();
159         string str, interactive;
160
161         latency = (elapsed - last);
162         last = elapsed;
163
164         double total_time, sample_time;
165         string status, substatus;
166
167         progress.get_time(total_time, sample_time);
168         progress.get_status(status, substatus);
169         float progress_val = progress.get_progress();
170
171         if(substatus != "")
172                 status += ": " + substatus;
173
174         interactive = options.interactive? "On":"Off";
175
176         str = string_printf(
177                 "%s"
178                 "        Time: %.2f"
179                 "        Latency: %.4f"
180                 "        Progress: %05.2f"
181                 "        Average: %.4f"
182                 "        Interactive: %s",
183                 status.c_str(), total_time, latency, (double) progress_val*100, sample_time, interactive.c_str());
184
185         view_display_info(str.c_str());
186
187         if(options.show_help)
188                 view_display_help();
189 }
190
191 static void display()
192 {
193         static DeviceDrawParams draw_params = DeviceDrawParams();
194
195         options.session->draw(session_buffer_params(), draw_params);
196
197         display_info(options.session->progress);
198 }
199
200 static void motion(int x, int y, int button)
201 {
202         if(options.interactive) {
203                 Transform matrix = options.session->scene->camera->matrix;
204
205                 /* Translate */
206                 if(button == 0) {
207                         float3 translate = make_float3(x * 0.01f, -(y * 0.01f), 0.0f);
208                         matrix = matrix * transform_translate(translate);
209                 }
210
211                 /* Rotate */
212                 else if(button == 2) {
213                         float4 r1 = make_float4((float)x * 0.1f, 0.0f, 1.0f, 0.0f);
214                         matrix = matrix * transform_rotate(DEG2RADF(r1.x), make_float3(r1.y, r1.z, r1.w));
215
216                         float4 r2 = make_float4(y * 0.1f, 1.0f, 0.0f, 0.0f);
217                         matrix = matrix * transform_rotate(DEG2RADF(r2.x), make_float3(r2.y, r2.z, r2.w));
218                 }
219
220                 /* Update and Reset */
221                 options.session->scene->camera->matrix = matrix;
222                 options.session->scene->camera->need_update = true;
223                 options.session->scene->camera->need_device_update = true;
224
225                 options.session->reset(session_buffer_params(), options.session_params.samples);
226         }
227 }
228
229 static void resize(int width, int height)
230 {
231         options.width = width;
232         options.height = height;
233
234         if(options.session) {
235                 /* Update camera */
236                 options.session->scene->camera->width = width;
237                 options.session->scene->camera->height = height;
238                 options.session->scene->camera->compute_auto_viewplane();
239                 options.session->scene->camera->need_update = true;
240                 options.session->scene->camera->need_device_update = true;
241
242                 options.session->reset(session_buffer_params(), options.session_params.samples);
243         }
244 }
245
246 static void keyboard(unsigned char key)
247 {
248         /* Toggle help */
249         if(key == 'h')
250                 options.show_help = !(options.show_help);
251
252         /* Reset */
253         else if(key == 'r')
254                 options.session->reset(session_buffer_params(), options.session_params.samples);
255
256         /* Cancel */
257         else if(key == 27) // escape
258                 options.session->progress.set_cancel("Canceled");
259
260         /* Pause */
261         else if(key == 'p') {
262                 options.pause = !options.pause;
263                 options.session->set_pause(options.pause);
264         }
265
266         /* Interactive Mode */
267         else if(key == 'i')
268                 options.interactive = !(options.interactive);
269
270         /* Navigation */
271         else if(options.interactive && (key == 'w' || key == 'a' || key == 's' || key == 'd')) {
272                 Transform matrix = options.session->scene->camera->matrix;
273                 float3 translate;
274
275                 if(key == 'w')
276                         translate = make_float3(0.0f, 0.0f, 0.1f);
277                 else if(key == 's')
278                         translate = make_float3(0.0f, 0.0f, -0.1f);
279                 else if(key == 'a')
280                         translate = make_float3(-0.1f, 0.0f, 0.0f);
281                 else if(key == 'd')
282                         translate = make_float3(0.1f, 0.0f, 0.0f);
283
284                 matrix = matrix * transform_translate(translate);
285
286                 /* Update and Reset */
287                 options.session->scene->camera->matrix = matrix;
288                 options.session->scene->camera->need_update = true;
289                 options.session->scene->camera->need_device_update = true;
290
291                 options.session->reset(session_buffer_params(), options.session_params.samples);
292         }
293
294         /* Set Max Bounces */
295         else if(options.interactive && (key == '0' || key == '1' || key == '2' || key == '3')) {
296                 int bounce;
297                 switch(key) {
298                         case '0': bounce = 0; break;
299                         case '1': bounce = 1; break;
300                         case '2': bounce = 2; break;
301                         case '3': bounce = 3; break;
302                         default: bounce = 0; break;
303                 }
304
305                 options.session->scene->integrator->max_bounce = bounce;
306
307                 /* Update and Reset */
308                 options.session->scene->integrator->need_update = true;
309
310                 options.session->reset(session_buffer_params(), options.session_params.samples);
311         }
312 }
313 #endif
314
315 static int files_parse(int argc, const char *argv[])
316 {
317         if(argc > 0)
318                 options.filepath = argv[0];
319
320         return 0;
321 }
322
323 static void options_parse(int argc, const char **argv)
324 {
325         options.width = 0;
326         options.height = 0;
327         options.filepath = "";
328         options.session = NULL;
329         options.quiet = false;
330
331         /* device names */
332         string device_names = "";
333         string devicename = "CPU";
334         bool list = false;
335
336         vector<DeviceType>& types = Device::available_types();
337
338         /* TODO(sergey): Here's a feedback loop happens: on the one hand we want
339          * the device list to be printed in help message, on the other hand logging
340          * is not initialized yet so we wouldn't have debug log happening in the
341          * device initialization.
342          */
343         foreach(DeviceType type, types) {
344                 if(device_names != "")
345                         device_names += ", ";
346
347                 device_names += Device::string_from_type(type);
348         }
349
350         /* shading system */
351         string ssname = "svm";
352
353         /* parse options */
354         ArgParse ap;
355         bool help = false, debug = false, version = false;
356         int verbosity = 1;
357
358         ap.options ("Usage: cycles [options] file.xml",
359                 "%*", files_parse, "",
360                 "--device %s", &devicename, ("Devices to use: " + device_names).c_str(),
361 #ifdef WITH_OSL
362                 "--shadingsys %s", &ssname, "Shading system to use: svm, osl",
363 #endif
364                 "--background", &options.session_params.background, "Render in background, without user interface",
365                 "--quiet", &options.quiet, "In background mode, don't print progress messages",
366                 "--samples %d", &options.session_params.samples, "Number of samples to render",
367                 "--output %s", &options.session_params.output_path, "File path to write output image",
368                 "--threads %d", &options.session_params.threads, "CPU Rendering Threads",
369                 "--width  %d", &options.width, "Window width in pixel",
370                 "--height %d", &options.height, "Window height in pixel",
371                 "--tile-width %d", &options.session_params.tile_size.x, "Tile width in pixels",
372                 "--tile-height %d", &options.session_params.tile_size.y, "Tile height in pixels",
373                 "--list-devices", &list, "List information about all available devices",
374 #ifdef WITH_CYCLES_LOGGING
375                 "--debug", &debug, "Enable debug logging",
376                 "--verbose %d", &verbosity, "Set verbosity of the logger",
377 #endif
378                 "--help", &help, "Print help message",
379                 "--version", &version, "Print version number",
380                 NULL);
381
382         if(ap.parse(argc, argv) < 0) {
383                 fprintf(stderr, "%s\n", ap.geterror().c_str());
384                 ap.usage();
385                 exit(EXIT_FAILURE);
386         }
387
388         if(debug) {
389                 util_logging_start();
390                 util_logging_verbosity_set(verbosity);
391         }
392
393         if(list) {
394                 vector<DeviceInfo>& devices = Device::available_devices();
395                 printf("Devices:\n");
396
397                 foreach(DeviceInfo& info, devices) {
398                         printf("    %-10s%s%s\n",
399                                 Device::string_from_type(info.type).c_str(),
400                                 info.description.c_str(),
401                                 (info.display_device)? " (display)": "");
402                 }
403
404                 exit(EXIT_SUCCESS);
405         }
406         else if(version) {
407                 printf("%s\n", CYCLES_VERSION_STRING);
408                 exit(EXIT_SUCCESS);
409         }
410         else if(help || options.filepath == "") {
411                 ap.usage();
412                 exit(EXIT_SUCCESS);
413         }
414
415         if(ssname == "osl")
416                 options.scene_params.shadingsystem = SHADINGSYSTEM_OSL;
417         else if(ssname == "svm")
418                 options.scene_params.shadingsystem = SHADINGSYSTEM_SVM;
419
420 #ifndef WITH_CYCLES_STANDALONE_GUI
421         options.session_params.background = true;
422 #endif
423
424         /* Use progressive rendering */
425         options.session_params.progressive = true;
426
427         /* find matching device */
428         DeviceType device_type = Device::type_from_string(devicename.c_str());
429         vector<DeviceInfo>& devices = Device::available_devices();
430         bool device_available = false;
431
432         foreach(DeviceInfo& device, devices) {
433                 if(device_type == device.type) {
434                         options.session_params.device = device;
435                         device_available = true;
436                         break;
437                 }
438         }
439
440         /* handle invalid configurations */
441         if(options.session_params.device.type == DEVICE_NONE || !device_available) {
442                 fprintf(stderr, "Unknown device: %s\n", devicename.c_str());
443                 exit(EXIT_FAILURE);
444         }
445 #ifdef WITH_OSL
446         else if(!(ssname == "osl" || ssname == "svm")) {
447                 fprintf(stderr, "Unknown shading system: %s\n", ssname.c_str());
448                 exit(EXIT_FAILURE);
449         }
450         else if(options.scene_params.shadingsystem == SHADINGSYSTEM_OSL && options.session_params.device.type != DEVICE_CPU) {
451                 fprintf(stderr, "OSL shading system only works with CPU device\n");
452                 exit(EXIT_FAILURE);
453         }
454 #endif
455         else if(options.session_params.samples < 0) {
456                 fprintf(stderr, "Invalid number of samples: %d\n", options.session_params.samples);
457                 exit(EXIT_FAILURE);
458         }
459         else if(options.filepath == "") {
460                 fprintf(stderr, "No file path specified\n");
461                 exit(EXIT_FAILURE);
462         }
463
464         /* For smoother Viewport */
465         options.session_params.start_resolution = 64;
466 }
467
468 CCL_NAMESPACE_END
469
470 using namespace ccl;
471
472 int main(int argc, const char **argv)
473 {
474         util_logging_init(argv[0]);
475         path_init();
476         options_parse(argc, argv);
477
478 #ifdef WITH_CYCLES_STANDALONE_GUI
479         if(options.session_params.background) {
480 #endif
481                 session_init();
482                 options.session->wait();
483                 session_exit();
484 #ifdef WITH_CYCLES_STANDALONE_GUI
485         }
486         else {
487                 string title = "Cycles: " + path_filename(options.filepath);
488
489                 /* init/exit are callback so they run while GL is initialized */
490                 view_main_loop(title.c_str(), options.width, options.height,
491                         session_init, session_exit, resize, display, keyboard, motion);
492         }
493 #endif
494
495         return 0;
496 }
497