#'@title Add Vignette Effect
#'
#'@description Takes an RGB array/filename and adds a camera vignette effect.
#'
#'@param image 3-layer RGB/4-layer RGBA array, `rayimg` class, or filename of an image.
#'@param filename Default `NULL`. Filename which to save the image. If `NULL` and `preview = FALSE`,
#'returns an RGB array.
#'@param vignette Default `1`. A camera vignetting effect will be added to the image.
#'`1` is the darkest vignetting, while `0` is no vignetting. If vignette is a length-2 vector, the second entry will
#'control the blurriness of the vignette effect (`1` is the default, e.g. `2` would double the blurriness but would take
#'much longer to compute).
#'@param radius Default `1.1`. Multiplier for the size of the vignette. If `1`, the vignette touches
#'the edge of the image.
#'@param color Default `"#000000"` (black). Color of the vignette.
#'@param preview Default `FALSE`. If `TRUE`, it will display the image in addition
#'to returning it.
#'
#'@return A `rayimg` RGBA array.
#'@import grDevices
#'@export
#'@examplesIf interactive() || identical(Sys.getenv("IN_PKGDOWN"), "true")
#'#Plot the dragon
#'plot_image(dragon)
#'#Add a vignette effect:
#'render_vignette(dragon, preview = TRUE, vignette = 1, radius=1.1)
#'#Lighten the vignette effect:
#'render_vignette(dragon, preview = TRUE, vignette = 0.5)
#'#Change the radius:
#'render_vignette(dragon, preview = TRUE, vignette = 1, radius=1.5)
#'render_vignette(dragon, preview = TRUE, vignette = 0.1, radius=0.8)
#'#Change the color:
#'render_vignette(dragon, preview = TRUE, vignette = 1, color="white")
#'#Increase the width of the blur by 50%:
#'render_vignette(dragon, preview = TRUE, vignette = c(1,1.5))
render_vignette = function(
  image,
  vignette = 0.5,
  color = "#000000",
  radius = 1.1,
  filename = NULL,
  preview = FALSE
) {
  image = ray_read_image(image, reset_camera_settings = TRUE)
  dimensions = dim(image)

  if (!("magick" %in% rownames(utils::installed.packages()))) {
    stop("`magick` package required for adding overlay")
  }
  if (length(vignette) > 1) {
    if (vignette[2] < 0) {
      stop("vignette[2] must be greater than 0")
    }
    radiusval = min(c(dimensions[1], dimensions[2])) / 2 * vignette[2]
    vignette = vignette[1]
  } else {
    radiusval = min(c(dimensions[1], dimensions[2])) / 2
  }
  if (is.numeric(vignette)) {
    if (vignette[1] > 1 || vignette[1] < 0) {
      stop("vignette value (", vignette[1], ") must be between 0 and 1.")
    }
  } else {
    vignette = 0.4
  }
  image_vignette = make_vignette_overlay(
    width = dimensions[1],
    height = dimensions[2],
    intensity = vignette,
    radius = radiusval,
    radius_multiplier = radius,
    color = color
  )
  temp = render_image_overlay(image, image_vignette)
  handle_image_output(temp, filename = filename, preview = preview)
}
