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