static char *version = "$Header: /home/abe/school/manual/ray-project/RCS/c.html,v 1.2 2010/06/05 16:29:47 abe Exp abe $";
#include
#include
typedef struct {
double x,y,z;
} VECTOR;
void vmulti(double, VECTOR *, VECTOR *);
double vminus(VECTOR *, VECTOR *, VECTOR *);
void vnormalize(VECTOR *);
double innerproduct(VECTOR *, VECTOR *);
void write_header(FILE *);
void scan(FILE *);
void back_color(FILE *);
void sphere_color(VECTOR *, VECTOR *, double , FILE *);
int main(void)
{
FILE *fp;
if((fp = fopen("sray.ppm","w")) == NULL)
{
fprintf(stderr, "%s not open !!\n","sray.ppm");
exit(1);
}
write_header(fp);
scan(fp);
fclose(fp);
return 0;
}
void write_header(FILE *fp)
{
fprintf(fp,"P6\n200 200\n255\n");
}
void scan(FILE *fp)
{
double radius,b,c,d,t;
double det;
VECTOR from,to,vector,point;
/* centor point of a sphere */
point.x = 0.0;
point.y = 0.0;
point.z = 0.0;
/* radius of a sphere */
radius = 0.5;
from.z = 3.0;
to.x = 0.0;
to.y = 0.0;
to.z = -1.0;
for(from.y = -1.0; from.y < 1.0; from.y += 2.0/200)
{
for(from.x = -1.0; from.x < 1.0; from.x += 2.0/200)
{
vminus(&from,&point,&vector);
b = innerproduct(&to,&vector);
c = innerproduct(&vector,&vector) - radius*radius;
d = b * b - c;
if(d < 0) /* ray is not intersect */
{
back_color(fp);
continue;
}
det = sqrt(d);
t = -b + det;
if(t < 0) /* object is behind eye */
{
back_color(fp);
continue;
}
sphere_color(&point, &from, t, fp); /* intersect */
}
}
}
void back_color(FILE *fp)
{
putc(100,fp); /* red */
putc(100,fp); /* green */
putc(100,fp); /* blue */
}
void sphere_color(VECTOR *point, VECTOR *to, double t, FILE *fp)
{
int col;
double d;
VECTOR v1, v2;
VECTOR l = {0.5773, -0.5773, 0.5773};
vmulti(t, to, &v1);
vminus(&v1, point, &v2);
vnormalize(&v2);
d = innerproduct(&l, &v2);
col = (int)(255.0*d) + 50;
if(col > 255)
col = 255;
if(col < 0)
col = 0;
putc((char)col, fp); /* red */
putc(0, fp); /* green */
putc(0, fp); /* blue */
}
void vmulti(double t, VECTOR *a, VECTOR *b)
{
b->x = t * a->x;
b->y = t * a->y;
b->z = t * a->z;
}
double vminus(VECTOR *a, VECTOR *b, VECTOR *c)
{
c->x = a->x - b->x;
c->y = a->y - b->y;
c->z = a->z - b->z;
}
void vnormalize(VECTOR *a)
{
double d;
d = sqrt(a->x*a->x + a->y*a->y + a->z*a->z);
a->x /= d;
a->y /= d;
a->z /= d;
}
double innerproduct(VECTOR *a, VECTOR *b)
{
return a->x * b->x + a->y * b->y + a->z * b->z;
}