12 local bg_col = {1,0,1}
14 local function calculate_normal(sdf, l)
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)
21 local function march(location, ray_dir, sdf, count)
22 local p = sdf(location)
24 return p.texture(location, ray_dir, calculate_normal(sdf, location-(ray_dir*eps)), count)
25 elseif p.dist > max_dist then
28 return march(location + ray_dir*p.dist,
29 ray_dir, sdf, count+1)
33 local function render(scene, width, height, filename)
34 print("Rendering to file " .. filename .. "...")
36 local f = io.open(filename, "w")
37 f:write("P3 ", width, " ", height, " 255\n")
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;
47 if y % math.floor(height/10) == 0 then
48 print(y/math.floor(height/10) * 10 .. "%")
51 local rayy = cam_dir + up*((y/height - 0.5)*c.fov*aspect)
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)}
60 f:write(math.floor(col[1]), " ", math.floor(col[2]), " ", math.floor(col[3]), " ")
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},
79 render(scene, 640, 480, "test.ppm")