Initial commit.
[raymarcher.git] / raymarch.lua
1 require "Vector"
2 local V = Vector
3
4 require "Primitives"
5 local P = Primitives
6
7 require "Textures"
8 local T = Textures
9
10 local eps = 0.01
11 local max_dist = 50
12 local bg_col = {1,0,1}
13
14 local function calculate_normal(sdf, l)
15    local delta = 1e-3;
16    return -V.new{sdf(l+V.x*delta).dist-sdf(l-V.x*delta).dist,
17                  sdf(l+V.y*delta).dist-sdf(l-V.y*delta).dist,
18                  sdf(l+V.z*delta).dist-sdf(l-V.z*delta).dist}/(2*delta)
19 end
20
21 local function march(location, ray_dir, sdf, count)
22    local p = sdf(location)
23    if p.dist < eps then
24       return p.texture(location, ray_dir, calculate_normal(sdf, location-(ray_dir*eps)), count)
25    elseif p.dist > max_dist then
26       return bg_col
27    else
28       return march(location + ray_dir*p.dist,
29                    ray_dir, sdf, count+1)
30    end
31 end
32
33 local function render(scene, width, height, filename) 
34    print("Rendering to file " .. filename .. "...")
35    
36    local f = io.open(filename, "w")
37    f:write("P3 ", width, " ", height, " 255\n")
38
39    local c = scene.camera
40    local cam_dir = V.normalize(c.point_at - c.location)
41    local right = V.normalize(c.right)
42    local up = V.cross(right,cam_dir)
43    local aspect = height/width;
44    
45    for y=1,height do
46
47       if y % math.floor(height/10) == 0 then
48          print(y/math.floor(height/10) * 10 .. "%")
49       end
50
51       local rayy = cam_dir + up*((y/height - 0.5)*c.fov*aspect)
52
53       for x=1,width do
54          local ray_dir = V.normalize(rayy + right*((x/width - 0.5)*c.fov))
55          local col = march(c.location, ray_dir, scene.sdf, 0)
56          col = {math.min(col[1]*255, 255),
57                 math.min(col[2]*255, 255),
58                 math.min(col[3]*255, 255)}
59
60          f:write(math.floor(col[1]), " ", math.floor(col[2]), " ", math.floor(col[3]), " ")
61       end
62       f:write("\n")
63    end
64    f:write("\n")
65
66    f:close()
67
68    print("done")
69 end
70
71 local scene = {
72    sdf = P.make_sphere(V.new{0,0,0}, 1,
73                        T.make_phong({V.new{2,0,2}}, {0,1,0}, 1.0, 0.5, 100)),
74    camera = {location = V.new{0,-5,0},
75              point_at = V.new{0,0,0},
76              right = V.new{1,0,0},
77              fov = 1}}
78
79 render(scene, 640, 480, "test.ppm")