14 local max_dist2 = 30^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,
32 calculate_normal(sdf, location-(ray_dir*eps)),
35 return march(start, location + ray_dir*p.dist,
36 ray_dir, sdf, count+1)
40 local function render(scene, width, height, filename)
41 print("Rendering to file " .. filename .. "...")
43 local f = io.open(filename, "w")
44 f:write("P3 ", width, " ", height, " 255\n")
46 local c = scene.camera
47 local cam_dir = V.normalize(c.point_at - c.location)
48 local right = V.normalize(c.right)
49 local up = V.cross(right,cam_dir)
50 local aspect = height/width;
52 local normalize = V.normalize -- optimization
56 if y % math.floor(height/10) == 0 then
57 print(y/math.floor(height/10) * 10 .. "%")
60 local rayy = cam_dir + up*((0.5 - y/height)*c.fov*aspect)
63 local ray_dir = normalize(rayy + right*((x/width - 0.5)*c.fov))
64 local col = march(c.location, c.location, ray_dir, scene.sdf, 0)
65 col = {math.min(col[1]*255, 255),
66 math.min(col[2]*255, 255),
67 math.min(col[3]*255, 255)}
69 f:write(math.floor(col[1]), " ", math.floor(col[2]), " ", math.floor(col[3]), " ")
81 local lights = {V.new{3,-3,1}}
89 P.make_sphere(V.new{0,0,0}, 1,
90 T.make_phong_texture(lights,
91 T.make_solid_pigment({0,1,0}),
93 P.make_sphere(V.new{0,0,0}, 0.8)),
94 P.make_pipe(V.new{0,0,0}, 0.5, V.new{0,1,0})),
95 P.make_pipe(V.new{0,0,0}, 0.5, V.new{1,0,0})),
97 P.make_plane(V.new{0,0,-1.0}, V.new{0,0,1},
98 T.make_phong_texture(lights,
99 T.make_checkered_pigment({0.5,0,0.2}, {1,1,1}),
101 -- T.make_flat_texture(T.make_checkered_pigment({0,0,1}, {1,1,1})))),
103 camera = {location = V.new{2,-5,1},
104 point_at = V.new{0,0,0},
108 -- render(scene, 320, 200, "test.ppm")
109 render(scene, 640, 480, "test.ppm")