clray

view src/rt.cc @ 4:3c95d568d3c7

wow a ball
author John Tsiombikas <nuclear@member.fsf.org>
date Thu, 15 Jul 2010 07:37:05 +0300
parents 88ac4eb2d18a
children 9f0ddb701882
line source
1 #include <stdio.h>
2 #include <math.h>
3 #include <assert.h>
4 #include "ocl.h"
6 struct RendInfo {
7 int xsz, ysz;
8 int num_sph, num_lights;
9 int max_iter;
10 } __attribute__((packed));
12 struct Sphere {
13 cl_float4 pos;
14 cl_float radius;
16 cl_float4 kd, ks;
17 cl_float spow;
18 cl_float kr, kt;
19 } __attribute__((packed));
21 struct Ray {
22 cl_float4 origin, dir;
23 } __attribute__((packed));
25 struct Light {
26 cl_float4 pos, color;
27 } __attribute__((packed));
30 static Ray get_primary_ray(int x, int y, int w, int h, float vfov_deg);
32 static Ray *prim_rays;
33 static CLProgram *prog;
34 static int global_size;
36 static Sphere sphlist[] = {
37 {{0, 0, 8, 1}, 1.0, {0.7, 0.2, 0.15, 1}, {1, 1, 1, 1}, 60, 0, 0},
38 {{-0.2, 0.4, 5, 1}, 0.25, {0.2, 0.9, 0.3, 1}, {1, 1, 1, 1}, 40, 0, 0}
39 };
41 static Light lightlist[] = {
42 {{-10, 10, -20, 1}, {1, 1, 1, 1}}
43 };
45 static RendInfo rinf;
48 bool init_renderer(int xsz, int ysz, float *fb)
49 {
50 // render info
51 rinf.xsz = xsz;
52 rinf.ysz = ysz;
53 rinf.num_sph = sizeof sphlist / sizeof *sphlist;
54 rinf.num_lights = sizeof lightlist / sizeof *lightlist;
55 rinf.max_iter = 6;
57 /* calculate primary rays */
58 prim_rays = new Ray[xsz * ysz];
60 for(int i=0; i<ysz; i++) {
61 for(int j=0; j<xsz; j++) {
62 prim_rays[i * xsz + j] = get_primary_ray(j, i, xsz, ysz, 45.0);
63 }
64 }
66 /* setup opencl */
67 prog = new CLProgram("render");
68 if(!prog->load("rt.cl")) {
69 return 1;
70 }
72 /* setup argument buffers */
73 prog->set_arg_buffer(0, ARG_WR, xsz * ysz * 4 * sizeof(float), fb);
74 prog->set_arg_buffer(1, ARG_RD, sizeof rinf, &rinf);
75 prog->set_arg_buffer(2, ARG_RD, sizeof sphlist, sphlist);
76 prog->set_arg_buffer(3, ARG_RD, sizeof lightlist, lightlist);
77 prog->set_arg_buffer(4, ARG_RD, xsz * ysz * sizeof *prim_rays, prim_rays);
79 global_size = xsz * ysz;
80 return true;
81 }
83 void destroy_renderer()
84 {
85 delete [] prim_rays;
86 delete prog;
87 }
89 bool render()
90 {
91 if(!prog->run(1, global_size)) {
92 return false;
93 }
95 CLMemBuffer *mbuf = prog->get_arg_buffer(0);
96 map_mem_buffer(mbuf, MAP_RD);
97 /*if(!write_ppm("out.ppm", fb, xsz, ysz)) {
98 return 1;
99 }*/
100 unmap_mem_buffer(mbuf);
101 return true;
102 }
104 static Ray get_primary_ray(int x, int y, int w, int h, float vfov_deg)
105 {
106 float vfov = M_PI * vfov_deg / 180.0;
107 float aspect = (float)w / (float)h;
109 float ysz = 2.0;
110 float xsz = aspect * ysz;
112 float px = ((float)x / (float)w) * xsz - xsz / 2.0;
113 float py = 1.0 - ((float)y / (float)h) * ysz;
114 float pz = 1.0 / tan(0.5 * vfov);
116 px *= 100.0;
117 py *= 100.0;
118 pz *= 100.0;
120 Ray ray = {{0, 0, 0, 1}, {px, py, pz, 1}};
121 return ray;
122 }