出力結果をキャラクターで出力する、JavaScriptによる簡単なレイトレーシングプログラム。
<HTML>
<HEAD>
<TITLE>
simple raytracing
<TITLE>
<SCRIPT LANGUAGE = "JavaScript">
<!--
xres = 10;
yres = 10;
function vector(x, y, z)
{
this.x = x;
this.y = y;
this.z = z;
}
function ray()
{
for(y = 0; y < yres; y++)
{
for(x = 0; x < xres; x++)
{
col = scan(x, y);
red = calc_color(col.x);
green = calc_color(col.y);
blue = calc_color(col.z);
fcol = "#" + red + green + blue;
document.write("<FONT COLOR = " + fcol + ">");
document.write("***");
}
document.write("<BR>");
}
}
function disp_hex(val)
{
return "0123456789abcdef".substring(val,val+1);
}
function calc_color(val)
{
a = val & 0xf;
b = (val & 0xf0) >> 4;
return disp_hex(b) + disp_hex(a);
}
function scan(x, y)
{
// centor point of a sphere
point = new vector(0.0, 0.0, 0.0);
// radius of a sphere
radius = 0.5;
from = new vector(0.0, 0.0, 3.0); // view point
to = new vector(0.0, 0.0, -1.0); // direction of view
from.x = -1.0 + 2.0/xres * x;
from.y = 1.0 - 2.0/yres * y;
vec = new vector(0.0, 0.0, 0.0);
vec.x = from.x - point.x;
vec.y = from.y - point.y;
vec.z = from.z - point.z;
b = innerproduct(to, vec);
c = innerproduct(vec, vec) - radius*radius;
d = b * b - c;
if(d < 0) // ray is not intersect
{
col = new vector(0, 0, 0);
return col;
}
det = Math.sqrt(d);
t = -b + det;
if(t < 0) // object is behind eye
{
col = new vector(0, 0, 0);
return col;
}
col = shading(t, from, to, point)
return col;
}
function innerproduct(a, b)
{
return a.x * b.x + a.y * b.y + a.z * b.z;
}
function vnormarize(v)
{
d = Math.sqrt(v.x*v.x + v.y*v.y + v.z*v.z);
v.x /= d;
v.y /= d;
v.z /= d;
return v;
}
function shading(t, from, to, point)
{
too = new vector(to.x, to.y, to.z);
too.x *= t;
too.y *= t;
too.z *= t;
c = new vector(0.0, 0.0, 0.0);
c.x = from.x - too.x;
c.y = from.y - too.y;
c.z = from.z - too.z;
c.x -= point.x;
c.y -= point.y;
c.z -= point.z;
c = vnormarize(c);
l = new vector(1.0, 1.0, 1.0); // light
l = vnormarize(l);
val = innerproduct(c, l);
if(val < 0.0)
val = 0.0;
color = new vector(255, 0, 0); // color of a sphere
ambient = new vector(20, 20, 20); // color of ambient
c.x = parseInt(color.x * val) + ambient.x;
c.y = parseInt(color.y * val) + ambient.y;
c.z = parseInt(color.z * val) + ambient.z;
c.x = c.x > 255 ? 255: c.x;
c.y = c.y > 255 ? 255: c.y;
c.z = c.z > 255 ? 255: c.z;
return c;
}
// -->
</SCRIPT>
</HEAD>
<BODY>
Simple Raytracing
<P>
<SCRIPT LANGUAGE = "JavaScript">
<!--
ray();
// -->
</SCRIPT>
</BODY>
</HTML>