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, *lt;
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 csg_view(0, 0, 5, 0, 0, 0);
33 oa = csg_sphere(0, 0, 0, 1);
34 csg_color(oa, 1, 0, 0);
35 ob = csg_sphere(-0.3, 0.7, 0.7, 0.7);
36 csg_color(ob, 0, 0, 1);
37 oc = csg_union(oa, ob);
40 lt = csg_null(-4, 10, 20);
41 csg_emission(lt, 1, 1, 1);
44 csg_render_image(pixels, width, height);
45 save_image(out_fname, pixels, width, height);
51 static int save_image(const char *fname, float *pix, int xsz, int ysz)
56 if(!(fp = fopen(fname, "wb"))) {
57 fprintf(stderr, "failed to open %s for writing: %s\n", fname, strerror(errno));
61 fprintf(fp, "P6\n%d %d\n65535\n", xsz, ysz);
63 for(i=0; i<xsz * ysz; i++) {
64 unsigned int r = *pix++ * 65535.0f;
65 unsigned int g = *pix++ * 65535.0f;
66 unsigned int b = *pix++ * 65535.0f;
68 if(r > 0xffff) r = 0xffff;
69 if(g > 0xffff) g = 0xffff;
70 if(b > 0xffff) b = 0xffff;
83 static void print_usage(const char *argv0)
85 printf("Usage: %s [options] <csg file>\n", argv0);
87 printf(" -s <WxH> output image resolution\n");
88 printf(" -o <file> output image file\n");
89 printf(" -h print usage information and exit\n");
92 static int parse_opt(int argc, char **argv)
96 for(i=1; i<argc; i++) {
97 if(argv[i][0] == '-') {
101 if(sscanf(argv[++i], "%dx%d", &width, &height) != 2) {
102 fprintf(stderr, "-s must be followed by WIDTHxHEIGHT\n");
108 out_fname = argv[++i];
112 print_usage(argv[0]);
116 fprintf(stderr, "invalid option: %s\n", argv[i]);
120 fprintf(stderr, "invalid option: %s\n", argv[i]);
124 fprintf(stderr, "unexpected argument: %s\n", argv[i]);