Fixed surface normal calculation bug.
[raymarcher.git] / Textures.lua
1 -- Textures for raymarcher
2 require "Vector"
3 local V = Vector
4
5 local function make_phong_texture(lights, pigment, amb, diff, spec, shiny)
6    local normalize = V.normalize
7    return function (location, ray_dir, normal, count)
8       local colour = pigment(location[1],location[3])
9       local thiscol = {colour[1]*amb, colour[2]*amb, colour[3]*amb}
10
11       local reflected_ray = ray_dir - normal*(ray_dir*normal*2)
12       for _,light in ipairs(lights) do
13          local light_dir = V.normalize(light-location)
14          local Idiff = math.max(normal*light_dir, 0)
15          local Ispec = math.pow(math.max(light_dir*reflected_ray,0),shiny)
16             
17          thiscol[1] = thiscol[1] + colour[1]*Idiff*diff + Ispec*spec
18          thiscol[2] = thiscol[2] + colour[2]*Idiff*diff + Ispec*spec
19          thiscol[3] = thiscol[3] + colour[3]*Idiff*diff + Ispec*spec
20       end
21
22       return thiscol
23    end
24 end
25
26 local function make_count_texture(scale)
27    return function (location, ray_dir, normal, count)
28       return {count*scale, count*scale, count*scale}
29    end
30 end
31
32 local function make_flat_texture(pigment)
33    return function (location, ray_dir, normal, count)
34       return pigment(location[1], location[2])
35    end
36 end
37
38 local function make_solid_pigment(colour)
39    return function (x,y)
40       return colour
41    end
42 end
43
44 local function make_checkered_pigment(colour1, colour2)
45    return function (x,y)
46       if (x%1 < 0.5 and y%1 < 0.5) or (x%1 > 0.5 and y%1 > 0.5) then
47          return colour1
48       else
49          return colour2
50       end
51    end
52 end
53    
54 Textures = {
55    make_phong_texture = make_phong_texture,
56    make_flat_texture = make_flat_texture,
57    make_count_texture = make_count_texture,
58    make_solid_pigment = make_solid_pigment,
59    make_checkered_pigment = make_checkered_pigment
60 }
61
62 return Textures