1 -- Main rendering functions
16 local max_dist2 = 30^2
17 local bg_col = {0.1,0.1,0.1}
19 local function calculate_normal(sdf, l)
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)
26 local function march(start, location, ray_dir, sdf, count)
27 if V.norm2(location-start) > max_dist2 then
31 local p = sdf(location)
33 return p.texture(location, ray_dir,
34 calculate_normal(sdf, location-(ray_dir*eps)),
37 return march(start, location + ray_dir*p.dist,
38 ray_dir, sdf, count+1)
42 local function render(scene, width, height, filename)
43 print("Rendering to file " .. filename .. "...")
45 local f = io.open(filename, "w")
46 f:write("P3 ", width, " ", height, " 255\n")
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;
54 local normalize = V.normalize -- optimization
58 if y % math.floor(height/10) == 0 then
59 print(y/math.floor(height/10) * 10 .. "%")
62 local rayy = cam_dir + up*((0.5 - y/height)*c.fov*aspect)
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)}
71 f:write(math.floor(col[1]), " ", math.floor(col[2]), " ", math.floor(col[3]), " ")
84 max_dist2 = max_dist2,