;; CRT effect - old monitor simulation
(require-primitives "image")

(define-effect crt
  :params (
    (line_spacing :type int :default 2 :range [1 10])
    (line_opacity :type float :default 0.3 :range [0 1])
    (vignette_amount :type float :default 0.2)
  )
  (let* ((w (image:width frame))
         (h (image:height frame))
         (cx (/ w 2))
         (cy (/ h 2))
         (max-dist (sqrt (+ (* cx cx) (* cy cy)))))
    (map-pixels frame
      (lambda (x y c)
        (let* (;; Scanline darkening
               (scanline-factor (if (= 0 (mod y line_spacing))
                                    (- 1 line_opacity)
                                    1))
               ;; Vignette
               (dx (- x cx))
               (dy (- y cy))
               (dist (sqrt (+ (* dx dx) (* dy dy))))
               (vignette-factor (- 1 (* (/ dist max-dist) vignette_amount)))
               ;; Combined
               (factor (* scanline-factor vignette-factor)))
          (rgb (* (red c) factor)
               (* (green c) factor)
               (* (blue c) factor)))))))
