14 local max_dist2 = 20^2
15 local bg_col = {0.1,0.1,0.1}
17 local function calculate_normal(sdf, l)
19 return V.new{sdf(l+V.x*delta).dist-sdf(l-V.x*delta).dist,
20 sdf(l+V.y*delta).dist-sdf(l-V.y*delta).dist,
21 sdf(l+V.z*delta).dist-sdf(l-V.z*delta).dist}/(2*delta)
24 local function march(start, location, ray_dir, sdf, count)
25 if V.norm2(location-start) > max_dist2 then
29 local p = sdf(location)
31 return p.texture(location, ray_dir, calculate_normal(sdf, location-(ray_dir*eps)), count)
33 return march(start, location + ray_dir*p.dist,
34 ray_dir, sdf, count+1)
38 local function render(scene, width, height, filename)
39 print("Rendering to file " .. filename .. "...")
41 local f = io.open(filename, "w")
42 f:write("P3 ", width, " ", height, " 255\n")
44 local c = scene.camera
45 local cam_dir = V.normalize(c.point_at - c.location)
46 local right = V.normalize(c.right)
47 local up = V.cross(right,cam_dir)
48 local aspect = height/width;
50 local normalize = V.normalize -- optimization
54 if y % math.floor(height/10) == 0 then
55 print(y/math.floor(height/10) * 10 .. "%")
58 local rayy = cam_dir + up*((0.5 - y/height)*c.fov*aspect)
61 local ray_dir = normalize(rayy + right*((x/width - 0.5)*c.fov))
62 local col = march(c.location, c.location, ray_dir, scene.sdf, 0)
63 col = {math.min(col[1]*255, 255),
64 math.min(col[2]*255, 255),
65 math.min(col[3]*255, 255)}
67 f:write(math.floor(col[1]), " ", math.floor(col[2]), " ", math.floor(col[3]), " ")
83 P.make_sphere(V.new{0,0,0}, 1,
84 T.make_phong_texture({V.new{2,-3,1}},
85 T.make_solid_pigment({0,1,0}),
87 P.make_plane(V.new{0,0,-3.0}, V.new{0,0,1},
88 T.make_flat_texture(T.make_checkered_pigment({0,0,1}, {1,1,1})))),
90 camera = {location = V.new{0,-5,0},
91 point_at = V.new{0,0,0},
95 render(scene, 640, 480, "test.ppm")