7 static int save_image(const char *fname, float *pix, int xsz, int ysz);
8 static int parse_opt(int argc, char **argv);
10 static int width = 800, height = 600;
11 static const char *out_fname = "output.ppm";
13 int main(int argc, char **argv)
15 csg_object *oa, *ob, *oc;
18 if(parse_opt(argc, argv) == -1) {
22 if(csg_init() == -1) {
26 if(!(pixels = malloc(width * height * 3 * sizeof *pixels))) {
27 perror("failed to allocate framebuffer");
31 oa = csg_sphere(0, 0, 0, 1);
32 ob = csg_sphere(0, 1, 0, 0.8);
33 oc = csg_intersection(oa, ob);
37 csg_render_image(pixels, width, height);
38 save_image(out_fname, pixels, width, height);
44 static int save_image(const char *fname, float *pix, int xsz, int ysz)
49 if(!(fp = fopen(fname, "wb"))) {
50 fprintf(stderr, "failed to open %s for writing: %s\n", fname, strerror(errno));
54 fprintf(fp, "P6\n%d %d\n65535\n", xsz, ysz);
56 for(i=0; i<xsz * ysz; i++) {
57 unsigned int r = *pix++ * 65535.0f;
58 unsigned int g = *pix++ * 65535.0f;
59 unsigned int b = *pix++ * 65535.0f;
61 if(r > 0xffff) r = 0xffff;
62 if(g > 0xffff) g = 0xffff;
63 if(b > 0xffff) b = 0xffff;
76 static void print_usage(const char *argv0)
78 printf("Usage: %s [options] <csg file>\n", argv0);
80 printf(" -s <WxH> output image resolution\n");
81 printf(" -o <file> output image file\n");
82 printf(" -h print usage information and exit\n");
85 static int parse_opt(int argc, char **argv)
89 for(i=1; i<argc; i++) {
90 if(argv[i][0] == '-') {
94 if(sscanf(argv[++i], "%dx%d", &width, &height) != 2) {
95 fprintf(stderr, "-s must be followed by WIDTHxHEIGHT\n");
101 out_fname = argv[++i];
105 print_usage(argv[0]);
109 fprintf(stderr, "invalid option: %s\n", argv[i]);
113 fprintf(stderr, "invalid option: %s\n", argv[i]);
117 fprintf(stderr, "unexpected argument: %s\n", argv[i]);