Colours are now Vectors, added rainbow pigment.
[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.001
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 = eps/10
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("P6 ", 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       if y % math.floor(height/10) == 0 then
58          print(y/math.floor(height/10) * 10 .. "%")
59       end
60
61       local rayy = cam_dir + up*((0.5 - y/height)*c.fov*aspect)
62
63       for x=1,width do
64          local ray_dir = normalize(rayy + right*((x/width - 0.5)*c.fov))
65          local col = march(c.location, c.location, ray_dir, scene.sdf, 0)
66          col = {math.floor(math.min(col[1]*255, 255)),
67                 math.floor(math.min(col[2]*255, 255)),
68                 math.floor(math.min(col[3]*255, 255))}
69
70          f:write(string.char(col[1]), string.char(col[2]), string.char(col[3]))
71       end
72    end
73
74    f:close()
75
76    print("done")
77 end
78
79 Render = {
80    eps = eps,
81    max_dist2 = max_dist2,
82    bg_col = bg_col,
83    render = render
84 }
85
86 return Render