Browse code

Add near and far planes

Robert Cranston authored on 10/07/2024 20:20:28
Showing 2 changed files

1 1
new file mode 100644
2 2
Binary files /dev/null and b/doc/02_near-far.tga differ
... ...
@@ -25,8 +25,9 @@ auto const infinity = std::numeric_limits<float>::infinity();
25 25
 //// Ray
26 26
 struct Ray
27 27
 {
28
-    vec3 origin;
29
-    vec3 direction;
28
+    vec3  origin;
29
+    vec3  direction;
30
+    float range;
30 31
 };
31 32
 
32 33
 //// Trace
... ...
@@ -74,7 +75,7 @@ struct Scene
74 75
         for (auto const & shape : shapes)
75 76
         {
76 77
             auto const trace = shape.trace(ray);
77
-            if (trace.distance < nearest.distance)
78
+            if (trace.distance < min(nearest.distance, ray.range))
78 79
                 nearest = trace;
79 80
         }
80 81
         return nearest;
... ...
@@ -84,6 +85,8 @@ struct Scene
84 85
 //// Camera
85 86
 struct Camera
86 87
 {
88
+    float near;
89
+    float far;
87 90
     uvec2 size;
88 91
     Ray ray(vec4 const & frag_coord) const
89 92
     {
... ...
@@ -91,9 +94,11 @@ struct Camera
91 94
             (2.0F * vec2(frag_coord.xy) - vec2(size)) / float(size.y),
92 95
             -1.0F
93 96
         );
94
-        auto const origin    = vec3(0.0F);
95
-        auto const direction = normalize(point);
96
-        return Ray{origin, direction};
97
+        auto const origin    = near * point;
98
+        auto const stop      = far  * point;
99
+        auto const range     = length(stop - origin);
100
+        auto const direction = (stop - origin) / range;
101
+        return Ray{origin, direction, range};
97 102
     }
98 103
 };
99 104
 
... ...
@@ -159,8 +164,12 @@ int main(int argc, char const * argv[])
159 164
     //// Configure
160 165
     auto size        = uvec2(640, 480);
161 166
     auto framebuffer = Framebuffer(size);
162
-    auto camera      = Camera{size};
163
-    auto scene       = Scene{
167
+    auto camera = Camera{
168
+        1.0F,   // near
169
+        100.0F, // far
170
+        size,   // size
171
+    };
172
+    auto scene = Scene{
164 173
         { // shapes
165 174
             Sphere{{   6.0F,  -4.0F,  -24.0F}, 12.0F},
166 175
             Sphere{{   2.0F,   6.0F,  -16.0F},  8.0F},