erebus
view src/main.cc @ 47:4b91c9a501d8
minor fix of strange code structure in the thread func
author | John Tsiombikas <nuclear@member.fsf.org> |
---|---|
date | Mon, 01 Feb 2016 14:56:15 +0200 |
parents | 9d6368850fe1 |
children |
line source
1 #include <stdio.h>
2 #include <stdlib.h>
3 #include <string.h>
4 #include <assert.h>
5 #include <signal.h>
6 #include <vector>
7 #include <chrono>
8 #include <imago2.h>
9 #include <drawtext.h>
10 #include "opengl.h"
11 #include "erebus.h"
12 #include "console.h"
14 using namespace std::chrono;
16 static bool init();
17 static void cleanup();
18 static void begin_frame(long tm);
19 static void end_frame();
20 static void resize_rtarget(int xsz, int ysz);
21 static void update_rect(int x, int y, int xsz, int ysz, float *pixels);
22 static void idle();
23 static void display();
24 static void display_statusbar(const erb_render_status &status);
25 static void save_image(const char *fname = 0);
26 static void reshape(int x, int y);
27 static void keyb(unsigned char key, int x, int y);
28 static void keyb_up(unsigned char key, int x, int y);
29 static void skeyb(int key, int x, int y);
30 static void mouse(int bn, int st, int x, int y);
31 static void motion(int x, int y);
32 static void sball_button(int bn, int st);
33 static void sball_motion(int x, int y, int z);
34 static int next_pow2(int x);
35 static void sighandler(int s);
36 static bool parse_args(int argc, char **argv);
37 static void con_parse(const char *line);
39 static int win_width, win_height, width, height, rtex_width, rtex_height;
40 static unsigned int rtex;
42 static int opt_samples = -1;
43 static int opt_iter = -1;
44 static int opt_threads = -1;
45 static float opt_imgscale = 2.0f;
47 static erebus *erb;
48 static bool render_pending;
49 static bool show_status = true;
50 static steady_clock::time_point start_time;
52 static std::vector<char*> sfiles;
54 #define FONTSZ 22
55 static dtx_font *font;
56 static Console con;
58 int main(int argc, char **argv)
59 {
60 glutInitWindowSize(1024, 600);
61 glutInit(&argc, argv);
63 if(!parse_args(argc, argv)) {
64 return 1;
65 }
67 glutInitDisplayMode(GLUT_RGB | GLUT_DOUBLE);
68 glutCreateWindow("erebus OpenGL frontend");
70 glutDisplayFunc(display);
71 glutReshapeFunc(reshape);
72 glutKeyboardFunc(keyb);
73 glutKeyboardUpFunc(keyb_up);
74 glutSpecialFunc(skeyb);
75 glutMouseFunc(mouse);
76 glutMotionFunc(motion);
77 glutSpaceballButtonFunc(sball_button);
78 glutSpaceballMotionFunc(sball_motion);
80 if(!init()) {
81 return 1;
82 }
83 atexit(cleanup);
84 signal(SIGINT, sighandler);
85 signal(SIGSEGV, sighandler);
86 signal(SIGILL, sighandler);
87 signal(SIGTERM, sighandler);
88 signal(SIGFPE, sighandler);
90 glutMainLoop();
91 }
93 static bool init()
94 {
95 width = glutGet(GLUT_WINDOW_WIDTH) / opt_imgscale;
96 height = glutGet(GLUT_WINDOW_HEIGHT) / opt_imgscale;
98 //if(!(font = dtx_open_font("/usr/share/fonts/opentype/linux-libertine/LinLibertine_R.otf", FONTSZ))) {
99 if(!(font = dtx_open_font_glyphmap("data/serif.glyphmap"))) {
100 fprintf(stderr, "warning: failed to load font!\n");
101 }
103 //dtx_font *confont = dtx_open_font("/usr/share/fonts/truetype/droid/DroidSansMono.ttf", 14);
104 dtx_font *confont = dtx_open_font_glyphmap("data/mono.glyphmap");
105 if(confont) {
106 con.set_font(confont, 14);
107 } else {
108 con.set_font(font, FONTSZ);
109 }
110 con.set_command_func(con_parse);
112 if(!(erb = erb_init())) {
113 return false;
114 }
115 erb_setopti(erb, ERB_OPT_WIDTH, width);
116 erb_setopti(erb, ERB_OPT_HEIGHT, height);
118 if(opt_samples != -1) {
119 erb_setopti(erb, ERB_OPT_MAX_SAMPLES, opt_samples);
120 }
121 if(opt_iter != -1) {
122 erb_setopti(erb, ERB_OPT_MAX_ITER, opt_iter);
123 }
124 if(opt_threads != -1) {
125 erb_setopti(erb, ERB_OPT_NUM_THREADS, opt_threads);
126 }
128 for(size_t i=0; i<sfiles.size(); i++) {
129 printf("loading scene file: %s\n", sfiles[i]);
130 if(erb_load_scene(erb, sfiles[i]) == -1) {
131 return false;
132 }
133 }
135 if(!sfiles.empty()) {
136 begin_frame(0);
137 }
139 glEnable(GL_TEXTURE_2D);
140 return true;
141 }
143 static void cleanup()
144 {
145 save_image("final.png");
146 erb_destroy(erb);
147 }
149 static void begin_frame(long tm)
150 {
151 printf("rendering frame (t=%ld) ...\n", tm);
153 render_pending = true;
154 glutIdleFunc(idle);
155 erb_begin_frame(erb, 0);
157 start_time = steady_clock::now();
158 }
160 static void end_frame()
161 {
162 if(!render_pending) return;
164 auto dur = steady_clock::now() - start_time;
165 long full_msec = duration_cast<milliseconds>(dur).count();
166 long msec, sec, min, hr, days;
168 msec = full_msec;
169 con.printf("done in ");
170 if((sec = msec / 1000) > 0) {
171 msec %= 1000;
172 if((min = sec / 60) > 0) {
173 sec %= 60;
174 if((hr = min / 60) > 0) {
175 min %= 60;
176 if((days = hr / 24) > 0) {
177 hr %= 24;
178 con.printf("%ld days ", days);
179 }
180 con.printf("%ld hours ", hr);
181 }
182 con.printf("%ld min ", min);
183 }
184 con.printf("%ld sec ", sec);
185 }
186 con.printf("%ld ms (%ld total msec)\n", msec, full_msec);
188 render_pending = false;
189 glutIdleFunc(0);
190 }
192 static void resize_rtarget(int xsz, int ysz)
193 {
194 static unsigned char *defpix;
196 if(render_pending) {
197 erb_end_frame(erb);
198 }
200 win_width = xsz;
201 win_height = ysz;
203 width = xsz / opt_imgscale;
204 height = ysz / opt_imgscale;
206 if(width > rtex_width || height > rtex_height) {
207 rtex_width = next_pow2(width);
208 rtex_height = next_pow2(height);
210 printf("resizing framebuffer texture: %dx%d\n", rtex_width, rtex_height);
212 if(!rtex) {
213 glGenTextures(1, &rtex);
214 }
216 delete [] defpix;
217 defpix = new unsigned char[rtex_width * rtex_height * 4];
218 unsigned char *ptr = defpix;
219 for(int i=0; i<rtex_height; i++) {
220 for(int j=0; j<rtex_width; j++) {
221 bool chess = ((i >> 4) & 1) == ((j >> 4) & 1);
223 int val = chess ? 64 : 48;
225 *ptr++ = val;
226 *ptr++ = val;
227 *ptr++ = val;
228 *ptr++ = 255;
229 }
230 }
232 glBindTexture(GL_TEXTURE_2D, rtex);
233 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
234 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
235 glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA32F_ARB, rtex_width, rtex_height, 0, GL_RGBA, GL_UNSIGNED_BYTE, defpix);
236 }
238 if(render_pending) {
239 begin_frame(0);
240 }
241 }
243 static void update_rect(int x, int y, int xsz, int ysz, float *pixels)
244 {
245 glBindTexture(GL_TEXTURE_2D, rtex);
246 glTexSubImage2D(GL_TEXTURE_2D, 0, x, y, xsz, ysz, GL_RGBA, GL_FLOAT, pixels);
247 }
249 static void idle()
250 {
251 glutPostRedisplay();
252 }
254 static void display()
255 {
256 static struct erb_render_status status;
258 if(render_pending) {
259 if(erb_render(erb, 64) == 0) {
260 end_frame();
261 }
262 update_rect(0, 0, width, height, erb_get_framebuffer(erb));
263 erb_get_status(erb, &status);
264 }
266 float maxu = (float)width / (float)rtex_width;
267 float maxv = (float)height / (float)rtex_height;
269 glEnable(GL_TEXTURE_2D);
270 glBindTexture(GL_TEXTURE_2D, rtex);
272 glBegin(GL_QUADS);
273 glColor4f(1, 1, 1, 1);
274 glTexCoord2f(0, maxv); glVertex2f(-1, -1);
275 glTexCoord2f(maxu, maxv); glVertex2f(1, -1);
276 glTexCoord2f(maxu, 0); glVertex2f(1, 1);
277 glTexCoord2f(0, 0); glVertex2f(-1, 1);
278 glEnd();
280 // draw the console
281 con.update();
282 con.draw();
284 // draw progress information etc...
285 if(show_status) {
286 display_statusbar(status);
287 }
289 glutSwapBuffers();
290 assert(glGetError() == GL_NO_ERROR);
291 }
293 static void display_statusbar(const erb_render_status &status)
294 {
295 if(!font) return;
296 dtx_use_font(font, FONTSZ);
298 bool show_progress = opt_samples > 0;
300 glDisable(GL_TEXTURE_2D);
302 glMatrixMode(GL_PROJECTION);
303 glPushMatrix();
304 glLoadIdentity();
305 glOrtho(0, win_width, 0, win_height, -1, 1);
307 glMatrixMode(GL_MODELVIEW);
308 glPushMatrix();
309 glLoadIdentity();
311 dtx_box bbox;
312 dtx_glyph_box('Q', &bbox);
314 // draw progress/status bar
315 int bar_height = bbox.height + 4;
316 int prog_width = show_progress ? status.progress_percent * win_width / 100 : 0;
318 glBegin(GL_QUADS);
319 glColor4f(0, 0, 0, 1);
320 glVertex2f(prog_width, 0);
321 glVertex2f(win_width, 0);
322 glVertex2f(win_width, bar_height);
323 glVertex2f(prog_width, bar_height);
325 glColor4f(0.25, 0, 0, 1);
326 glVertex2f(0, 0);
327 glVertex2f(prog_width, 0);
328 glVertex2f(prog_width, bar_height);
329 glVertex2f(0, bar_height);
330 glEnd();
332 // draw the text
333 glTranslatef(bbox.x + 2, bbox.y + 2, 0);
335 glColor4f(1, 1, 1, 1);
337 if(opt_samples > 0) {
338 dtx_printf("samples: %ld / %ld", status.samples, status.max_samples);
340 glLoadIdentity();
341 glTranslatef(win_width - dtx_string_width("progress: 100%") - 2, bbox.y + 2, 0);
342 dtx_printf("progress: %ld%%", status.progress_percent);
343 } else {
344 dtx_printf("samples: %ld", status.samples);
345 }
347 // samples/sec display
348 static long paths_per_sec, prev_msec, prev_paths;
350 long msec = duration_cast<milliseconds>(steady_clock::now() - start_time).count();
351 long dt = msec - prev_msec;
353 if(dt >= 1500) { // average over 1.5 seconds
354 long paths = status.samples * width * height;
355 if(prev_msec > 0 && prev_paths <= paths) { // check valid interval (not a restart or whatever)
356 paths_per_sec = 1000 * (paths - prev_paths) / dt;
357 }
358 prev_msec = msec;
359 prev_paths = paths;
360 }
362 glLoadIdentity();
363 glTranslatef((win_width - dtx_string_width("paths/s: 999999")) / 2, bbox.y + 2, 0);
364 if(paths_per_sec) {
365 dtx_printf("paths/s: %ld", paths_per_sec);
366 } else {
367 dtx_printf("paths/s: ???");
368 }
370 glPopMatrix();
371 glMatrixMode(GL_PROJECTION);
372 glPopMatrix();
373 }
375 static void save_image(const char *fname)
376 {
377 float *fb = erb_get_framebuffer(erb);
379 if(img_save_pixels(fname ? fname : "output.png", fb, width, height, IMG_FMT_RGBAF) == -1) {
380 fprintf(stderr, "failed to save image\n");
381 }
382 }
384 static void reshape(int x, int y)
385 {
386 glViewport(0, 0, x, y);
387 resize_rtarget(x, y);
389 erb_setopti(erb, ERB_OPT_WIDTH, width);
390 erb_setopti(erb, ERB_OPT_HEIGHT, height);
391 }
393 static void keyb(unsigned char key, int x, int y)
394 {
395 switch(key) {
396 case 27:
397 if(con.is_visible()) {
398 con.hide();
399 glutPostRedisplay();
400 } else {
401 end_frame();
402 exit(0);
403 }
404 break;
406 case ' ':
407 if(!con.is_visible()) {
408 begin_frame(0);
409 } else {
410 con.input_key(' ');
411 glutPostRedisplay();
412 }
413 break;
415 case '`':
416 con.set_visible(!con.is_visible());
417 glutPostRedisplay();
418 break;
420 case '~':
421 show_status = !show_status;
422 glutPostRedisplay();
423 break;
425 default:
426 // otherwise if the console is visible, let them through
427 if(con.is_visible()) {
428 con.input_key(key);
429 glutPostRedisplay();
430 return; // don't pass anything to the erb input handler
431 }
432 }
434 if(erb_input_keyboard(erb, key, true)) {
435 glutPostRedisplay();
436 }
437 }
439 static void keyb_up(unsigned char key, int x, int y)
440 {
441 if(erb_input_keyboard(erb, key, false)) {
442 glutPostRedisplay();
443 }
444 }
446 static void skeyb(int key, int x, int y)
447 {
448 if(key == GLUT_KEY_F12) {
449 printf("saving image...\n");
450 save_image();
451 return;
452 }
454 if(con.is_visible()) {
455 switch(key) {
456 case GLUT_KEY_F8:
457 con.debug();
458 return;
460 case GLUT_KEY_LEFT:
461 con.input_key(Console::KEY_LEFT);
462 break;
463 case GLUT_KEY_RIGHT:
464 con.input_key(Console::KEY_RIGHT);
465 break;
466 case GLUT_KEY_UP:
467 con.input_key(Console::KEY_UP);
468 break;
469 case GLUT_KEY_DOWN:
470 con.input_key(Console::KEY_DOWN);
471 break;
472 case GLUT_KEY_HOME:
473 con.input_key(Console::KEY_HOME);
474 break;
475 case GLUT_KEY_END:
476 con.input_key(Console::KEY_END);
477 break;
478 case GLUT_KEY_INSERT:
479 con.input_key(Console::KEY_INS);
480 break;
481 case GLUT_KEY_PAGE_UP:
482 con.input_key(Console::KEY_PGUP);
483 break;
484 case GLUT_KEY_PAGE_DOWN:
485 con.input_key(Console::KEY_PGDOWN);
486 break;
488 default:
489 return;
490 }
491 glutPostRedisplay();
492 }
493 }
495 static void mouse(int bn, int st, int x, int y)
496 {
497 if(erb_input_mouse_button(erb, bn - GLUT_LEFT_BUTTON, st == GLUT_DOWN, x, y)) {
498 glutPostRedisplay();
499 }
500 }
502 static void motion(int x, int y)
503 {
504 if(erb_input_mouse_motion(erb, x, y)) {
505 glutPostRedisplay();
506 }
507 }
509 static void sball_button(int bn, int state)
510 {
511 if(erb_input_6dof_button(erb, bn, state == GLUT_DOWN)) {
512 glutPostRedisplay();
513 }
514 }
516 static void sball_motion(int x, int y, int z)
517 {
518 if(erb_input_6dof_motion(erb, x / 65536.0, y / 65536.0, z / 65536.0)) {
519 glutPostRedisplay();
520 }
521 }
523 static int next_pow2(int x)
524 {
525 int res = 2;
526 while(res < x) {
527 res <<= 1;
528 }
529 return res;
530 }
532 static void sighandler(int s)
533 {
534 exit(0);
535 }
537 static bool parse_args(int argc, char **argv)
538 {
539 for(int i=1; i<argc; i++) {
540 if(argv[i][0] == '-') {
541 if(strcmp(argv[i], "-samples") == 0) {
542 opt_samples = atoi(argv[++i]);
543 if(opt_samples <= 0) {
544 fprintf(stderr, "invalid -samples option: %s\n", argv[i]);
545 return false;
546 }
548 } else if(strcmp(argv[i], "-iter") == 0) {
549 opt_iter = atoi(argv[++i]);
550 if(opt_iter <= 0) {
551 fprintf(stderr, "invalid -iter option: %s\n", argv[i]);
552 return false;
553 }
555 } else if(strcmp(argv[i], "-threads") == 0) {
556 opt_threads = atoi(argv[++i]);
557 if(opt_threads <= 0) {
558 fprintf(stderr, "invalid -threads option: %s\n", argv[i]);
559 return false;
560 }
562 } else if(strcmp(argv[i], "-scale") == 0) {
563 opt_imgscale = atof(argv[++i]);
564 if(opt_imgscale <= 0.0f) {
565 fprintf(stderr, "invalid -scale option: %s\n", argv[i]);
566 return false;
567 }
569 } else {
570 fprintf(stderr, "invalid option: %s\n", argv[i]);
571 return false;
572 }
573 } else {
574 sfiles.push_back(argv[i]);
575 }
576 }
578 return true;
579 }
581 static void con_parse(const char *line)
582 {
583 int len = strlen(line);
584 if(!len) return;
586 char *buf = (char*)alloca(len + 1);
587 memcpy(buf, line, len + 1);
589 std::vector<char*> args;
590 char *tok;
592 while((tok = strtok(buf, " \n\r\v\t"))) {
593 buf = 0;
594 args.push_back(tok);
595 }
596 args.push_back(0);
597 int argc = args.size() - 1;
599 if(!args[0]) return;
601 if(strcmp(args[0], "exit") == 0 || strcmp(args[0], "quit") == 0) {
602 exit(0);
604 } else if(strcmp(args[0], "clear") == 0) {
605 erb_clear(erb);
607 } else if(strcmp(args[0], "stop") == 0) {
608 erb_end_frame(erb);
610 } else if(strcmp(args[0], "render") == 0) {
611 long tm = 0;
612 if(args[1]) {
613 char *endp;
614 tm = strtol(args[1], &endp, 10);
615 if(endp == args[1]) {
616 con.printf("the argument to render must be a time value in milliseconds\n");
617 return;
618 }
619 }
620 begin_frame(tm);
622 } else if(strcmp(args[0], "samples") == 0) {
623 if(args[1] && (opt_samples = atoi(args[1]))) {
624 erb_setopti(erb, ERB_OPT_MAX_SAMPLES, opt_samples);
625 con.printf("max samples is now %d\n", opt_samples);
626 } else {
627 con.printf("invalid samples command: %s\n", line);
628 }
630 } else if(strcmp(args[0], "load") == 0) {
631 for(int i=1; i<argc; i++) {
632 if(erb_load_scene(erb, args[i]) == -1) {
633 con.printf("failed to load scene: %s\n", args[1]);
634 } else {
635 begin_frame(0);
636 }
637 }
639 } else if(strcmp(args[0], "add") == 0) {
640 if(erb_proc_cmd(erb, line + 4) == -1) {
641 con.puts("invalid add command\n");
642 } else {
643 begin_frame(0);
644 }
646 } else if(strcmp(args[0], "help") == 0) {
647 con.printf("Available commands:\n");
648 con.printf("render [anim time] begins rendering a frame with the given time (default: 0)\n");
649 con.printf("stop stops rendering\n");
650 con.printf("samples <count> sets the maximum number of samples per pixel\n");
651 con.printf("iter <count> sets the maximum number of ray bounces\n");
652 con.printf("load <filename> loads a scene file\n");
653 con.printf("add <object command> adds another object to the scene. For valid object commands see test/scene\n");
655 } else {
656 con.printf("unrecognized command: %s\n", args[0]);
657 }
658 }