# HG changeset patch # User John Tsiombikas # Date 1511142782 -7200 # Node ID 03e8b9a5031d210f88c3884f6483dfcf90b47b13 # Parent 436f82447c44b5168919148c3aa7f23aeb6ed075 screenshot function diff -r 436f82447c44 -r 03e8b9a5031d src/main.c --- a/src/main.c Sun Nov 19 00:57:39 2017 +0200 +++ b/src/main.c Mon Nov 20 03:53:02 2017 +0200 @@ -1,6 +1,9 @@ #include #include +#include #include +#include +#include #include #include #include "sdr.h" @@ -13,6 +16,7 @@ void keyup(unsigned char key, int x, int y); void mouse(int bn, int st, int x, int y); void motion(int x, int y); +void screenshot(void); static int win_width = 1280, win_height = 800; static float win_aspect; @@ -127,6 +131,10 @@ } break; + case '`': + screenshot(); + break; + default: break; } @@ -173,3 +181,48 @@ glutPostRedisplay(); } } + +void screenshot(void) +{ + FILE *fp; + DIR *dir; + struct dirent *dent; + unsigned char *img; + static int shotnum = -1; + char fname[128]; + + if(shotnum == -1) { + shotnum = 1; + if((dir = opendir("."))) { + while((dent = readdir(dir))) { + int num; + if(sscanf(dent->d_name, "img%d.ppm", &num) == 1) { + if(num >= shotnum) shotnum = num + 1; + } + } + closedir(dir); + } + } else { + ++shotnum; + } + + sprintf(fname, "img%04d.ppm", shotnum > 0 ? shotnum : 0); + if(!(fp = fopen(fname, "wb"))) { + fprintf(stderr, "failed to open %s for writing: %s\n", fname, strerror(errno)); + return; + } + + if(!(img = malloc(win_width * win_height * 3))) { + fprintf(stderr, "failed to allocate screenshot buffer\n"); + fclose(fp); + return; + } + + glReadPixels(0, 0, win_width, win_height, GL_RGB, GL_UNSIGNED_BYTE, img); + + fprintf(fp, "P6\n%d %d\n255\n", win_width, win_height); + fwrite(img, 1, win_width * win_height * 3, fp); + fclose(fp); + free(img); + return; +}