summaryrefslogtreecommitdiff
path: root/cl-raytracer.lisp
blob: 0cdfcf596c59a246c08945eec326a91e02c31255 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
;;; Copyright © 2020 Jakob L. Kreuze <zerodaysfordays@sdf.org>
;;;
;;; This program is free software; you can redistribute it and/or
;;; modify it under the terms of the GNU General Public License as
;;; published by the Free Software Foundation; either version 3 of the
;;; License, or (at your option) any later version.
;;;
;;; This program is distributed in the hope that it will be useful,
;;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
;;; General Public License for more details.
;;;
;;; You should have received a copy of the GNU General Public License
;;; along with this program. If not, see
;;; <http://www.gnu.org/licenses/>.

(defun make-some (n) (cons 'some n))
(defun make-none ()  'none)

(defun some-p (n) (and (consp n) (eq 'some (car n))))
(defun none-p (n) (eq 'none n))

(defun unwrap (n)
  (if (some-p n)
      (cdr n)
      (error "Tried to unwrap `none'.")))

(defun map-option (proc n)
  (if (some-p n)
      (make-some (funcall proc (unwrap n)))
      n))


;;;
;;; Image encoding.
;;;

(defun write-ppm (width height pixels)
  "Encode the WIDTH by HEIGHT image given as PIXELS into the portable pixmap
format (PPM), writing the result to `(current-output-port)'."
  (write-line "P3")
  (format t "~a ~a~%" width height)
  (write-line "255")
  (loop for (r g b) across pixels
        do (format t "~a ~a ~a~%" r g b)))


;;;
;;; Are mathematical objects in the room with us right now?
;;;

(defun square (n) (* n n))

(defstruct vec3 x y z)

(defun vec3+ (&rest vecs)
  "Return the sum of VECS, as in vector space addition."
  (if (zerop (length vecs))
      (make-vec3 :x 0 :y 0 :z 0)
      (reduce #'(lambda (a b)
              (with-slots ((x1 x) (y1 y) (z1 z)) a
                (with-slots ((x2 x) (y2 y) (z2 z)) b
                  (make-vec3 :x (+ x1 x2)
                             :y (+ y1 y2)
                             :z (+ z1 z2)))))
          (cdr vecs)
          :initial-value (car vecs))))

(defun vec3- (&rest vecs)
  "Return the difference of VECS, as in vector space subtraction."
  (if (zerop (length vecs))
      (make-vec3 :x 0 :y 0 :z 0)
      (reduce #'(lambda (a b)
              (with-slots ((x1 x) (y1 y) (z1 z)) a
                (with-slots ((x2 x) (y2 y) (z2 z)) b
                  (make-vec3 :x (- x1 x2)
                             :y (- y1 y2)
                             :z (- z1 z2)))))
          (cdr vecs)
          :initial-value (car vecs))))

(defun vec3* (c u)
  "Return the vector U scaled by a constant C, as in vector space scalar
  multiplication."
  (with-slots (x y z) u
    (make-vec3 :x (* c x) :y (* c y) :z (* c z))))

(defun vec3-dot (u v)
  "Return the dot product of the vectors U and V."
  (+ (* (vec3-x u) (vec3-x v))
     (* (vec3-y u) (vec3-y v))
     (* (vec3-z u) (vec3-z v))))

(defun vec3-cross (u v)
  "Return the cross product of the vectors U and V."
  (with-slots ((x1 x) (y1 y) (z1 z)) u
    (with-slots ((x2 x) (y2 y) (z2 z)) v
      (make-vec3 :x (- (* y1 z2) (* z1 y2))
                 :y (- (* z1 x2) (* x1 z2))
                 :z (- (* x1 y2) (* y1 x2))))))

(defun vec3-magnitude (u)
  "Return the magnitude of vector U."
  (with-slots (x y z) u
    (sqrt (+ (square x) (square y) (square z)))))

(defun vec3-normalize (u)
  "Return the normal vector parallel to vector U."
  (vec3* (/ 1 (vec3-magnitude u)) u))

(defstruct ray origin direction)

(defmethod point-at ((r ray) time)
  "Return the position of RAY at time T."
  (with-slots (origin direction) r
    (vec3+ origin (vec3* time direction))))

(defun to-radians (d)
  "Convert D, a value in degrees, to radians."
  (* d (/ PI 360)))


;;;
;;; Shapes and generic procedures for working with them.
;;;

(defstruct plane p0 n material)

(defmethod intersect (ray (p plane) t-min t-max)
  (with-slots (p0 (plane-normal n)) p
    (with-slots (origin direction) ray
      (let* ((normal (vec3-normalize plane-normal))
             (denominator (vec3-dot direction normal)))
        (if (zerop denominator)
            (make-none)
            (let ((time (/ (vec3-dot (vec3- p0 origin) normal)
                           denominator)))
              (if (<= t-min time t-max)
                  (make-some time)
                  (make-none))))))))

(defstruct sphere center radius material)

(defmethod intersect (ray (s sphere) t-min t-max)
  (with-slots (origin direction) ray
    (with-slots (center radius) s
      (let* ((oc (vec3* (- 1) (vec3- center origin)))
             (A  (vec3-dot direction direction))
             (B  (* 2.0 (vec3-dot oc direction)))
             (C  (- (vec3-dot oc oc) (square radius)))

             (discriminant (- (square B) (* 4 A C)))
             (time (if (plusp discriminant)
                       (let ((p (/ (+ (- B) (sqrt discriminant)) (* 2 A)))
                             (m (/ (- (- B) (sqrt discriminant)) (* 2 A))))
                         (if (>= m t-min) m p))
                       (/ (- B) (* 2 A)))))
        (if (and (not (minusp discriminant))
                 (<= t-min time t-max))
            (make-some time)
            (make-none))))))


;;;
;;; Scene graph.
;;;

(defvar image-width  1920)
(defvar image-height 1080)
(defvar image-aspect-ratio (/ image-width image-height))

(defvar camera-position (make-vec3 :x 8.00 :y 5.00 :z 9.00))
(defvar camera-target   (make-vec3 :x 0.25 :y 0.00 :z 0.50))
(defvar camera-up       (make-vec3 :x 0.00 :y 1.00 :z 0.00))
(defvar camera-fov      30)

(defvar shapes (list (make-sphere :center (make-vec3 :x -0.25 :y 0.00 :z 0.25)
                                  :radius 1.25
                                  ;; (phong-material (make-vec3 1.0 0.2 0.2)
                                  ;;                 (make-vec3 1.0 0.2 0.2)
                                  ;;                 (make-vec3 2.0 2.0 2.0)
                                  ;;                 20)
                                  :material nil
                                  )
                     ;; (make-plane :p0 (make-vec3 :x  0.00 :y -1.25 :z  0.00)
                     ;;             :n (make-vec3 :x  0.00 :y  1.00 :z  0.00)
                     ;;             ;; (diffuse-material (make-vec3 1.0 1.0 0.2)
                     ;;             ;;                   (make-vec3 1.0 1.0 0.2))
                     ;;             :material nil
                     ;;             )
                     ))

(defun coord-to-ray (x y)
  "Return the ray corresponding to the point X, Y on the viewport plane."
  (let* ((dist 1.0)
         (top    (* dist (tan (to-radians camera-fov))))
         (right  (* top image-aspect-ratio))
         (bottom (- top))
         (left   (- right))
         (W (vec3-normalize (vec3- camera-position camera-target)))
         (U (vec3-normalize (vec3-cross camera-up W)))
         (V (vec3-cross W U))
         (corner (vec3+ camera-position
                        (vec3* left     U)
                        (vec3* bottom   V)
                        (vec3* (- dist) W)))
         (across (vec3* (* 2 right) U))
         (up     (vec3* (* 2 top)   V)))
    (make-ray :origin camera-position
              :direction (vec3-normalize
                          (vec3+ corner
                                 (vec3* x across)
                                 (vec3* y up)
                                 (vec3* (- 1) camera-position))))))

(defun lerp (a b time)
  "Interpolate between A and B with parameter T."
  (+ (* (- 1.0 time) a) (* time b)))

(defun ray-color (r)
  "Return an arbitrary color for R."
  (let* ((y (vec3-y (ray-direction r)))
         (time (* 0.5 (+ y 1.0))))
    (list (round (* 255 (lerp 1.0 0.5 time)))
          (round (* 255 (lerp 1.0 0.7 time)))
          (round (* 255 (lerp 1.0 1.0 time))))))

(defun ray-intersect-scene (ray)
  "Return the nearest shape with which RAY intersects as (some . (shape .
point)), if any. Otherwise, return 'none."
  (map-option
   #'(lambda (pair)
       (list (car pair) (point-at ray (cadr pair))))
   (reduce #'(lambda (a b)
               (cond ((none-p a) b)
                     ((none-p b) a)
                     (t (let ((t1 (unwrap a))
                              (t2 (unwrap b)))
                          (if (> (cadr t1) (cadr t2)) b a)))))
           (mapcar #'(lambda (shape)
                       (let ((intersection (intersect ray shape 0.001 10000)))
                         (map-option #'(lambda (time) (list shape time)) intersection)))
                   shapes)
           :initial-value (make-none))))

(let ((image (make-array (* image-width image-height) :initial-element '(0 0 0))))
  (flet ((coord-to-index (x y)
           (+ x (* y image-width)))
         (screen-to-viewport (x y)
           (values (coerce (/ x image-width) 'real)
                   (coerce (/ (- image-height 1 y) image-height) 'real))))
    (dotimes (x image-width)
      (dotimes (y image-height)
        (setf (elt image (coord-to-index x y))
              (multiple-value-bind (x y) (screen-to-viewport x y)
                (let ((ray (coord-to-ray x y)))
                  (if (some-p (ray-intersect-scene ray))
                      (list 0 0 0)
                      (ray-color ray))))))))
  (write-ppm image-width image-height image))