implemented lookat camera
[csgray] / src / csgray.c
1 #include <stdio.h>
2 #include <stdlib.h>
3 #include <string.h>
4 #include <math.h>
5 #include <float.h>
6 #include <treestore.h>
7 #include "csgimpl.h"
8 #include "matrix.h"
9 #include "geom.h"
10
11 static void calc_primary_ray(struct ray *ray, int x, int y, int w, int h, float aspect);
12 static int ray_trace(struct ray *ray, float *col);
13 static void shade(float *col, struct ray *ray, struct hit *hit);
14 static void background(float *col, struct ray *ray);
15 static int find_intersection(struct ray *ray, struct hit *best);
16 static csg_object *load_object(struct ts_node *node);
17
18 static float ambient[3];
19 static struct camera cam;
20 static csg_object *oblist;
21 static csg_object *plights;
22
23 int csg_init(void)
24 {
25         oblist = 0;
26         plights = 0;
27
28         csg_ambient(0, 0, 0);
29         csg_view(0, 0, 5, 0, 0, 0);
30         csg_fov(50);
31
32         return 0;
33 }
34
35 void csg_destroy(void)
36 {
37         while(oblist) {
38                 csg_object *o = oblist;
39                 oblist = oblist->ob.next;
40                 csg_free_object(o);
41         }
42         oblist = 0;
43 }
44
45 void csg_view(float x, float y, float z, float tx, float ty, float tz)
46 {
47         float dir[3];
48         float len;
49
50         cam.x = x;
51         cam.y = y;
52         cam.z = z;
53         cam.tx = tx;
54         cam.ty = ty;
55         cam.tz = tz;
56
57         dir[0] = tx - x;
58         dir[1] = ty - y;
59         dir[2] = tz - z;
60         len = sqrt(dir[0] * dir[0] + dir[1] * dir[1] + dir[2] * dir[2]);
61
62         if(1.0f - fabs(ty - y) / len < 1e-6f) {
63                 cam.ux = cam.uy = 0.0f;
64                 cam.uz = -1.0f;
65         } else {
66                 cam.ux = cam.uz = 0.0f;
67                 cam.uy = 1.0f;
68         }
69
70         mat4_lookat(cam.xform, x, y, z, tx, ty, tz, cam.ux, cam.uy, cam.uz);
71 }
72
73 void csg_fov(float fov)
74 {
75         cam.fov = M_PI * fov / 180.0f;
76 }
77
78
79 int csg_load(const char *fname)
80 {
81         struct ts_node *root = 0, *c;
82         csg_object *o;
83
84         if(!(root = ts_load(fname))) {
85                 fprintf(stderr, "failed to open %s\n", fname);
86                 return -1;
87         }
88         if(strcmp(root->name, "csgray_scene") != 0) {
89                 fprintf(stderr, "invalid scene file: %s\n", fname);
90                 goto err;
91         }
92
93         c = root->child_list;
94         while(c) {
95                 if(strcmp(c->name, "viewer") == 0) {
96                         static float def_pos[] = {0, 0, 5};
97                         static float def_targ[] = {0, 0, 0};
98
99                         float *p = ts_get_attr_vec(c, "position", def_pos);
100                         float *t = ts_get_attr_vec(c, "target", def_targ);
101
102                         csg_view(p[0], p[1], p[2], t[0], t[1], t[2]);
103                         csg_fov(ts_get_attr_num(c, "fov", 50.0f));
104
105                 } else if((o = load_object(c))) {
106                         csg_add_object(o);
107                 }
108                 c = c->next;
109         }
110
111         ts_free_tree(root);
112         return 0;
113
114 err:
115         if(root) {
116                 ts_free_tree(root);
117         }
118         return -1;
119 }
120
121 int csg_save(const char *fname)
122 {
123         return -1;      /* TODO */
124 }
125
126 void csg_add_object(csg_object *o)
127 {
128         o->ob.next = oblist;
129         oblist = o;
130
131         if(o->ob.type == OB_NULL && (o->ob.emr > 0.0f || o->ob.emg > 0.0f || o->ob.emb > 0.0f)) {
132                 o->ob.plt_next = plights;
133                 plights = o;
134         }
135 }
136
137 int csg_remove_object(csg_object *o)
138 {
139         csg_object dummy, *n;
140
141         dummy.ob.next = oblist;
142         n = &dummy;
143
144         while(n->ob.next) {
145                 if(n->ob.next == o) {
146                         n->ob.next = o->ob.next;
147                         return 1;
148                 }
149                 n = n->ob.next;
150         }
151         return 0;
152 }
153
154 void csg_free_object(csg_object *o)
155 {
156         if(o->ob.destroy) {
157                 o->ob.destroy(o);
158         }
159         free(o);
160 }
161
162 static union csg_object *alloc_object(int type)
163 {
164         csg_object *o;
165
166         if(!(o = calloc(sizeof *o, 1))) {
167                 return 0;
168         }
169         o->ob.type = type;
170         mat4_identity(o->ob.xform);
171         mat4_identity(o->ob.inv_xform);
172
173         csg_emission(o, 0, 0, 0);
174         csg_color(o, 1, 1, 1);
175         csg_roughness(o, 1);
176         csg_opacity(o, 1);
177
178         return o;
179 }
180
181 csg_object *csg_null(float x, float y, float z)
182 {
183         csg_object *o;
184
185         if(!(o = alloc_object(OB_NULL))) {
186                 return 0;
187         }
188
189         mat4_translation(o->ob.xform, x, y, z);
190         return o;
191 }
192
193 csg_object *csg_sphere(float x, float y, float z, float r)
194 {
195         csg_object *o;
196
197         if(!(o = alloc_object(OB_SPHERE))) {
198                 return 0;
199         }
200
201         o->sph.rad = r;
202         mat4_translation(o->ob.xform, x, y, z);
203         mat4_copy(o->ob.inv_xform, o->ob.xform);
204         mat4_inverse(o->ob.inv_xform);
205         return o;
206 }
207
208 csg_object *csg_cylinder(float x0, float y0, float z0, float x1, float y1, float z1, float r)
209 {
210         csg_object *o;
211         float dx, dy, dz;
212         int major;
213
214         if(!(o = alloc_object(OB_CYLINDER))) {
215                 return 0;
216         }
217
218         dx = x1 - x0;
219         dy = y1 - y0;
220         dz = z1 - z0;
221
222         if(fabs(dx) > fabs(dy) && fabs(dx) > fabs(dz)) {
223                 major = 0;
224         } else if(fabs(dy) > fabs(dz)) {
225                 major = 1;
226         } else {
227                 major = 2;
228         }
229
230         o->cyl.rad = r;
231         mat4_lookat(o->ob.xform, x0, y0, z0, x1, y1, z1, 0, major == 2 ? 1 : 0, major == 2 ? 0 : 1);
232         mat4_copy(o->ob.inv_xform, o->ob.xform);
233         mat4_inverse(o->ob.inv_xform);
234         return o;
235 }
236
237 csg_object *csg_plane(float x, float y, float z, float nx, float ny, float nz)
238 {
239         csg_object *o;
240         float len;
241
242         if(!(o = alloc_object(OB_PLANE))) {
243                 return 0;
244         }
245
246         len = sqrt(nx * nx + ny * ny + nz * nz);
247         if(len != 0.0f) {
248                 float s = 1.0f / len;
249                 nx *= s;
250                 ny *= s;
251                 nz *= s;
252         }
253
254         o->plane.nx = nx;
255         o->plane.ny = ny;
256         o->plane.nz = nz;
257         o->plane.d = x * nx + y * ny + z * nz;
258         return o;
259 }
260
261 csg_object *csg_box(float x, float y, float z, float xsz, float ysz, float zsz)
262 {
263         return 0;
264 }
265
266 csg_object *csg_union(csg_object *a, csg_object *b)
267 {
268         csg_object *o;
269
270         if(!(o = alloc_object(OB_UNION))) {
271                 return 0;
272         }
273         o->un.a = a;
274         o->un.b = b;
275         return o;
276 }
277
278 csg_object *csg_intersection(csg_object *a, csg_object *b)
279 {
280         csg_object *o;
281
282         if(!(o = alloc_object(OB_INTERSECTION))) {
283                 return 0;
284         }
285         o->isect.a = a;
286         o->isect.b = b;
287         return o;
288 }
289
290 csg_object *csg_subtraction(csg_object *a, csg_object *b)
291 {
292         csg_object *o;
293
294         if(!(o = alloc_object(OB_SUBTRACTION))) {
295                 return 0;
296         }
297         o->sub.a = a;
298         o->sub.b = b;
299         return o;
300 }
301
302 void csg_ambient(float r, float g, float b)
303 {
304         ambient[0] = r;
305         ambient[1] = g;
306         ambient[2] = b;
307 }
308
309 void csg_emission(csg_object *o, float r, float g, float b)
310 {
311         o->ob.emr = r;
312         o->ob.emg = g;
313         o->ob.emb = b;
314 }
315
316 void csg_color(csg_object *o, float r, float g, float b)
317 {
318         o->ob.r = r;
319         o->ob.g = g;
320         o->ob.b = b;
321 }
322
323 void csg_roughness(csg_object *o, float r)
324 {
325         o->ob.roughness = r;
326 }
327
328 void csg_opacity(csg_object *o, float p)
329 {
330         o->ob.opacity = p;
331 }
332
333 void csg_metallic(csg_object *o, int m)
334 {
335         o->ob.metallic = m;
336 }
337
338 void csg_reset_xform(csg_object *o)
339 {
340         mat4_identity(o->ob.xform);
341         mat4_identity(o->ob.inv_xform);
342 }
343
344 void csg_translate(csg_object *o, float x, float y, float z)
345 {
346         mat4_translate(o->ob.xform, x, y, z);
347         mat4_pre_translate(o->ob.inv_xform, -x, -y, -z);
348 }
349
350 void csg_rotate(csg_object *o, float angle, float x, float y, float z)
351 {
352         mat4_rotate(o->ob.xform, angle, x, y, z);
353         mat4_pre_rotate(o->ob.inv_xform, -angle, x, y, z);
354 }
355
356 void csg_scale(csg_object *o, float x, float y, float z)
357 {
358         mat4_scale(o->ob.xform, x, y, z);
359         mat4_pre_scale(o->ob.inv_xform, 1.0f / x, 1.0f / y, 1.0f / z);
360 }
361
362 void csg_lookat(csg_object *o, float x, float y, float z, float tx, float ty, float tz, float ux, float uy, float uz)
363 {
364         mat4_lookat(o->ob.xform, x, y, z, tx, ty, tz, ux, uy, uz);
365         mat4_inv_lookat(o->ob.inv_xform, x, y, z, tx, ty, tz, ux, uy, uz);
366 }
367
368 void csg_render_pixel(int x, int y, int width, int height, float aspect, float *color)
369 {
370         struct ray ray;
371
372         calc_primary_ray(&ray, x, y, width, height, aspect);
373         ray_trace(&ray, color);
374 }
375
376 void csg_render_image(float *pixels, int width, int height)
377 {
378         int i, j;
379         float aspect = (float)width / (float)height;
380
381         for(i=0; i<height; i++) {
382                 for(j=0; j<width; j++) {
383                         csg_render_pixel(j, i, width, height, aspect, pixels);
384                         pixels += 3;
385                 }
386         }
387 }
388
389 static void calc_primary_ray(struct ray *ray, int x, int y, int w, int h, float aspect)
390 {
391         ray->dx = aspect * ((float)x / (float)w * 2.0f - 1.0f);
392         ray->dy = 1.0f - (float)y / (float)h * 2.0f;
393         ray->dz = -1.0f / tan(cam.fov * 0.5f);
394
395         ray->x = 0;
396         ray->y = 0;
397         ray->z = 0;
398
399         xform_ray(ray, cam.xform);
400 }
401
402 static int ray_trace(struct ray *ray, float *col)
403 {
404         struct hit hit;
405
406         if(!find_intersection(ray, &hit)) {
407                 background(col, ray);
408                 return 0;
409         }
410
411         shade(col, ray, &hit);
412         return 1;
413 }
414
415 #define NULLXPOS(o)     ((o)->ob.xform[12])
416 #define NULLYPOS(o)     ((o)->ob.xform[13])
417 #define NULLZPOS(o)     ((o)->ob.xform[14])
418
419 static void shade(float *col, struct ray *ray, struct hit *hit)
420 {
421         float ndotl, ndoth, len, falloff, spec;
422         csg_object *o, *lt = plights;
423         float dcol[3], scol[3] = {0};
424         float ldir[3], lcol[3], hdir[3];
425         struct ray sray;
426         struct hit tmphit;
427
428         o = hit->o;
429         dcol[0] = ambient[0];
430         dcol[1] = ambient[1];
431         dcol[2] = ambient[2];
432
433         while(lt) {
434                 ldir[0] = NULLXPOS(lt) - hit->x;
435                 ldir[1] = NULLYPOS(lt) - hit->y;
436                 ldir[2] = NULLZPOS(lt) - hit->z;
437
438                 sray.x = hit->x;
439                 sray.y = hit->y;
440                 sray.z = hit->z;
441                 sray.dx = ldir[0];
442                 sray.dy = ldir[1];
443                 sray.dz = ldir[2];
444
445                 if(!find_intersection(&sray, &tmphit) || tmphit.t < 0.000001 || tmphit.t > 1.0f) {
446                         if((len = sqrt(ldir[0] * ldir[0] + ldir[1] * ldir[1] + ldir[2] * ldir[2])) != 0.0f) {
447                                 float s = 1.0f / len;
448                                 ldir[0] *= s;
449                                 ldir[1] *= s;
450                                 ldir[2] *= s;
451                         }
452                         falloff = 1.0f / (len * len);
453
454                         lcol[0] = lt->ob.emr * falloff;
455                         lcol[1] = lt->ob.emg * falloff;
456                         lcol[2] = lt->ob.emb * falloff;
457
458                         if((ndotl = hit->nx * ldir[0] + hit->ny * ldir[1] + hit->nz * ldir[2]) < 0.0f) {
459                                 ndotl = 0.0f;
460                         }
461
462                         dcol[0] += o->ob.r * lcol[0] * ndotl;
463                         dcol[1] += o->ob.g * lcol[1] * ndotl;
464                         dcol[2] += o->ob.b * lcol[2] * ndotl;
465
466                         if(o->ob.roughness < 1.0f) {
467                                 float gloss = 1.0f - o->ob.roughness;
468
469                                 hdir[0] = ldir[0] - ray->dx;
470                                 hdir[1] = ldir[1] - ray->dy;
471                                 hdir[2] = ldir[2] - ray->dz;
472                                 if((len = sqrt(hdir[0] * hdir[0] + hdir[1] * hdir[1] + hdir[2] * hdir[2])) != 0.0f) {
473                                         float s = 1.0f / len;
474                                         hdir[0] *= s;
475                                         hdir[1] *= s;
476                                         hdir[2] *= s;
477                                 }
478
479                                 if((ndoth = hit->nx * hdir[0] + hit->ny * hdir[1] + hit->nz * hdir[2]) < 0.0f) {
480                                         ndoth = 0.0f;
481                                 }
482                                 spec = gloss * pow(ndoth, 100.0f * gloss);
483
484                                 if(o->ob.metallic) {
485                                         lcol[0] *= o->ob.r;
486                                         lcol[1] *= o->ob.g;
487                                         lcol[2] *= o->ob.b;
488                                 }
489                                 scol[0] += lcol[0] * spec;
490                                 scol[1] += lcol[1] * spec;
491                                 scol[2] += lcol[2] * spec;
492                         }
493                 }
494
495                 lt = lt->ob.plt_next;
496         }
497
498         col[0] = dcol[0] + scol[0];
499         col[1] = dcol[1] + scol[1];
500         col[2] = dcol[2] + scol[2];
501 }
502
503 static void background(float *col, struct ray *ray)
504 {
505         col[0] = col[1] = col[2] = 0.0f;
506 }
507
508 static int find_intersection(struct ray *ray, struct hit *best)
509 {
510         int idx = 0;
511         csg_object *o;
512         struct hinterv *hit, *it;
513
514         best->t = FLT_MAX;
515         best->o = 0;
516
517         o = oblist;
518         while(o) {
519                 if((hit = ray_intersect(ray, o))) {
520                         it = hit;
521                         while(it) {
522                                 if(it->end[0].t > 1e-6) {
523                                         idx = 0;
524                                         break;
525                                 }
526                                 if(it->end[1].t > 1e-6) {
527                                         idx = 1;
528                                         break;
529                                 }
530                                 it = it->next;
531                         }
532
533                         if(it && it->end[idx].t < best->t) {
534                                 *best = it->end[idx];
535                         }
536                 }
537                 free_hit_list(hit);
538                 o = o->ob.next;
539         }
540
541         return best->o != 0;
542 }
543
544 static csg_object *load_object(struct ts_node *node)
545 {
546         float *avec;
547         struct ts_node *c;
548         csg_object *sub, *o = 0, *olist = 0, *otail = 0;
549         int num_subobj = 0, is_csgop = 0;
550
551         if(strcmp(node->name, "null") == 0) {
552                 if(!(o = csg_null(0, 0, 0))) {
553                         goto err;
554                 }
555
556         } else if(strcmp(node->name, "sphere") == 0) {
557                 float rad = ts_get_attr_num(node, "radius", 1.0f);
558                 if(!(o = csg_sphere(0, 0, 0, rad))) {
559                         goto err;
560                 }
561
562         } else if(strcmp(node->name, "plane") == 0) {
563                 static float def_norm[] = {0, 1, 0};
564                 float *norm = ts_get_attr_vec(node, "normal", def_norm);
565                 if(!(o = csg_plane(0, 0, 0, norm[0], norm[1], norm[2]))) {
566                         goto err;
567                 }
568
569         } else if(strcmp(node->name, "box") == 0) {
570                 static float def_sz[] = {1, 1, 1};
571                 float *sz = ts_get_attr_vec(node, "size", def_sz);
572                 if(!(o = csg_box(0, 0, 0, sz[0], sz[1], sz[2]))) {
573                         goto err;
574                 }
575
576         } else if(strcmp(node->name, "union") == 0) {
577                 if(!(o = csg_union(0, 0))) {
578                         goto err;
579                 }
580                 is_csgop = 1;
581
582         } else if(strcmp(node->name, "intersect") == 0) {
583                 if(!(o = csg_intersection(0, 0))) {
584                         goto err;
585                 }
586                 is_csgop = 1;
587
588         } else if(strcmp(node->name, "subtract") == 0) {
589                 if(!(o = csg_subtraction(0, 0))) {
590                         goto err;
591                 }
592                 is_csgop = 1;
593
594         } else {
595                 goto err;
596         }
597
598         if(is_csgop) {
599                 c = node->child_list;
600                 while(c) {
601                         if((sub = load_object(c))) {
602                                 if(olist) {
603                                         otail->ob.next = sub;
604                                         otail = sub;
605                                 } else {
606                                         olist = otail = sub;
607                                 }
608                                 ++num_subobj;
609                         }
610                         c = c->next;
611                 }
612
613                 if(num_subobj != 2) {
614                         goto err;
615                 }
616                 o->un.a = olist;
617                 o->un.b = olist->ob.next;
618                 olist->ob.next = 0;
619         }
620
621         if((avec = ts_get_attr_vec(node, "position", 0))) {
622                 csg_translate(o, avec[0], avec[1], avec[2]);
623         }
624         if((avec = ts_get_attr_vec(node, "rotaxis", 0))) {
625                 csg_rotate(o, ts_get_attr_num(node, "rotangle", 0.0f), avec[0], avec[1], avec[2]);
626         }
627         if((avec = ts_get_attr_vec(node, "scaling", 0))) {
628                 csg_scale(o, avec[0], avec[1], avec[2]);
629         }
630         if((avec = ts_get_attr_vec(node, "target", 0))) {
631                 /* don't move this before position */
632                 float def_up[] = {0, 1, 0};
633                 float *up = ts_get_attr_vec(node, "up", def_up);
634                 float x = o->ob.xform[12];
635                 float y = o->ob.xform[13];
636                 float z = o->ob.xform[14];
637                 csg_lookat(o, x, y, z, avec[0], avec[1], avec[2], up[0], up[1], up[2]);
638         }
639
640         if((avec = ts_get_attr_vec(node, "color", 0))) {
641                 csg_color(o, avec[0], avec[1], avec[2]);
642         }
643         if((avec = ts_get_attr_vec(node, "emission", 0))) {
644                 csg_emission(o, avec[0], avec[1], avec[2]);
645         }
646
647         csg_roughness(o, ts_get_attr_num(node, "roughness", o->ob.roughness));
648         csg_opacity(o, ts_get_attr_num(node, "opacity", o->ob.opacity));
649         csg_metallic(o, ts_get_attr_int(node, "metallic", o->ob.metallic));
650
651         return o;
652
653 err:
654         csg_free_object(o);
655         while(olist) {
656                 o = olist;
657                 olist = olist->ob.next;
658                 csg_free_object(o);
659         }
660         return 0;
661 }