skymodelr coverage - 56.06%

R/download_sky_data.R 154 80 0 80 0.0 0.00%
src/hosek/hosek.cpp 150 55 0 55 0.0 0.00%
R/get_prague_sky_metadata.R 96 33 0 33 0.0 0.00%
src/math/angle.h 148 19 0 19 0.0 0.00%
src/math/matrix.h 107 4 0 4 0.0 0.00%
src/math/vector.h 143 1 0 1 0.0 0.00%
src/hosek/atmosphere.h 122 1 0 1 0.0 0.00%
src/hosek/hosek.h 66 1 0 1 0.0 0.00%
inst/include/skymodelr/prague_metal.inc 194 1 0 1 0.0 0.00%
src/PragueSkyModel/PragueSkyModel.cpp 1550 655 21 634 <0.1 3.21%
src/PragueSkyModel/PragueSkyModel.h 534 34 7 27 0.5 20.59%
src/prague_api.cpp 181 113 35 78 0.7 30.97%
src/prague_metal_stub.cpp 12 3 1 2 2.0 33.33%
src/hosek/atmosphere.cpp 208 73 26 47 25.8 35.62%
src/makesky.cpp 1028 590 224 366 3241254.8 37.97%
src/math/scalar_function.h 365 84 40 44 562.5 47.62%
R/utils_precision.R 8 4 2 2 1.5 50.00%
R/generate_sky.R 869 325 171 154 3.4 52.62%
R/prague-data.R 106 61 35 26 2.7 57.38%
src/radiometry.cpp 82 51 33 18 5807.7 64.71%
src/ArHosekSkyModel/ArHosekSkyModel.cpp 831 254 174 80 12211455.5 68.50%
R/utils_internal.R 18 10 7 3 3740.2 70.00%
R/exr_metadata.R 370 192 138 54 12.9 71.88%
src/math/scalar.h 310 44 32 12 2445.0 72.73%
R/prague_rgb_correction.R 126 53 39 14 15.0 73.58%
R/sky_data_cache.R 98 47 37 10 2.8 78.72%
src/hosek/cie.cpp 265 179 154 25 12.2 86.03%
R/planets.R 104 37 32 5 0.9 86.49%
R/radiometry.R 120 60 53 7 391.0 88.33%
R/stars.R 206 70 64 6 3634.6 91.43%
R/moon.R 413 243 223 20 5152.8 91.77%
R/stars_radiometry.R 136 74 68 6 1.2 91.89%
src/stars.cpp 368 226 218 8 157160.5 96.46%
R/generate_moon_image_latlong.R 464 249 241 8 16.3 96.79%
R/celestial_disk.R 582 298 293 5 41.2 98.32%
Total 10534 4224 2368 1856 1195930.9 56.06%
1
#' Generate Sun and Moon Disk Radiance Images
2
#'
3
#' Generate a celestial disk directly at texture resolution, independently of
4
#' an environment map. The Sun supports Prague and Hosek radiance profiles. The Moon
5
#' uses the existing lunar surface texture, topocentric phase orientation,
6
#' earthshine, photometry, and atmospheric extinction.
7
#'
8
#' @param datetime A single `POSIXct` instant. Its time zone is respected.
9
#' @param lat Observer latitude in degrees, between -90 and 90.
10
#' @param lon Observer longitude in degrees, between -180 and 180.
11
#' @param altitude Default `0`. Observer altitude in meters, from 0 to 15000.
12
#' @param resolution Default `256` for the Sun and `1024` for the Moon. Target
13
#'   disk width and height in pixels, an integer of at least 16. The Moon is
14
#'   cropped from a padded raster without resampling; edge coverage can add a
15
#'   few pixels to the returned dimensions.
16
#' @param visibility Default `50`. Prague visibility in kilometers, from 20 to
17
#'   131.8.
18
#' @param albedo Default `0.5`. Ground albedo, from 0 to 1.
19
#' @param number_cores Default `1`. Positive integer number of worker threads.
20
#' @param wide_spectrum Default `FALSE`. Use the extended Prague spectral data.
21
#' @param prague_rgb_correction Default `TRUE`. RGB correction passed to
22
#'   [calculate_sky_values()].
23
#' @param prague_rgb_correction_strength Default `1`. Nonnegative correction
24
#'   strength passed to [calculate_sky_values()].
25
#' @param prague_rgb_correction_gain Default `"auto"`. Automatic correction or
26
#'   three positive RGB gains, as in [calculate_sky_values()].
27
#' @param earthshine Default `TRUE`. Include Earth-reflected light on the Moon.
28
#' @param earthshine_albedo Default `0.19`. Nonnegative Earth albedo used for
29
#'   earthshine.
30
#' @param solar_irradiance_w_m2 Default `1300`. Positive solar irradiance in
31
#'   watts per square meter used to illuminate the lunar surface.
32
#' @param hosek Default `FALSE`. Use the Hosek solar radiance profile without
33
#'   Prague data. Only supported for Sun disks with atmospheric attenuation.
34
#' @param turbidity Default `3`. Hosek atmospheric turbidity, from 1.7 to 10.
35
#' @param elevation Default `NULL`. Optional Sun elevation in degrees, from -90
36
#'   to 90. Supply with `azimuth` to override ephemeris placement and attenuation.
37
#' @param azimuth Default `NULL`. Optional Sun azimuth in degrees, from 0 to 360,
38
#'   clockwise from north. Apparent diameter still comes from the ephemeris.
39
#' @param atmospheric_attenuation Default `TRUE`. Include atmospheric extinction
40
#'   and tint for the specified observer. Set `FALSE` to return radiance before
41
#'   it enters Earth's atmosphere; the consuming renderer must apply atmospheric
42
#'   transport and horizon visibility. Lunar phase, surface detail, and earthshine
43
#'   are retained. `moon_extinction_kV` is ignored when this is `FALSE`.
44
#' @param moon_extinction_kV Default `0.172`. Nonnegative lunar atmospheric
45
#'   extinction coefficient in magnitudes per airmass.
46
#'
47
#' @return A list containing:
48
#' * `image`: a numeric array with dimensions `c(height, width, 3)` containing
49
#'   linear sRGB radiance, with no exposure, tone mapping, or alpha channel.
50
#'   Antialiased lunar coverage is already applied: do not multiply by alpha.
51
#'   Out-of-gamut solar RGB values may be negative and should be preserved.
52
#' * `azimuth_deg`: disk-center azimuth, clockwise from true north, in [0, 360).
53
#' * `elevation_deg`: disk-center elevation above the local horizon, in degrees.
54
#' * `angular_diameter_deg`: topocentric apparent angular diameter in degrees.
55
#' * `atmospheric_attenuation`: whether atmospheric filtering is included.
56
#' * `projection`: `"rectilinear"`, using the disk mapping described below.
57
#'
58
#' @details
59
#' Prague disks require data installed with [download_sky_data()]. Hosek Sun
60
#' disks (`hosek = TRUE`) need no external data. They include fixed-observer
61
#' atmospheric attenuation and support finite values at zenith. The atmosphere is
62
#' evaluated for one observer altitude and time when `atmospheric_attenuation`
63
#' is `TRUE`. With `FALSE`, solar radiance comes from the model's intrinsic
64
#' solar spectrum and lunar radiance uses unattenuated photometry without the
65
#' atmospheric tint. Solar texture values are then independent of altitude and
66
#' solar elevation; ephemeris placement and lunar phase still use the requested
67
#' location and time. Neither mode clips the texture to a geometric horizon.
68
#' Pair these images with an atmosphere-only sky and disable the corresponding
69
#' rasterized celestial bodies in that sky to avoid counting their light twice.
70
#'
71
#' The disk is inscribed in the image rectangle. For column `j`, row `i`, width
72
#' `w`, and height `h`, pixel centers have coordinates
73
#' `x = 2 * (j - 0.5) / w - 1` and `y = 1 - 2 * (i - 0.5) / h`.
74
#' Sample only within `x^2 + y^2 <= 1`. The corresponding ray direction is
75
#' `normalize(forward + tan(radius) * (x * right + y * up))`, where
76
#' `radius = angular_diameter_deg * pi / 360`. Image-up is the projection of
77
#' local vertical into the disk plane; image-right points toward increasing
78
#' azimuth. At the zenith or nadir, north replaces the vertical reference axis.
79
#' There is no image reprojection or implicit rotation in the return value.
80
#'
81
#' The solar model has a fixed angular profile, mapped here to the apparent
82
#' ephemeris diameter without changing radiance. Lunar radiance is normalized
83
#' over disk solid angle to the existing phase-dependent irradiance, with the
84
#' solar spectral RGB distribution. With `atmospheric_attenuation = TRUE`,
85
#' lunar attenuation and Prague tint are evaluated at the disk center. At or
86
#' below zero center elevation, their finite horizon values are retained so the
87
#' upper limb does not disappear prematurely. This continuation preserves a full
88
#' disk texture; it is not a model of below-horizon visibility or horizon
89
#' depression at altitude. Geometric horizon clipping is the consumer's
90
#' responsibility; sample the full disk and discard directions below the
91
#' horizon when appropriate.
92
#'
93
#' To save an EXR without changing radiance, tag `image` with
94
#' `rayimage::ray_read_image(image, normalize = FALSE, source_linear = TRUE,
95
#' assume_colorspace = rayimage::CS_SRGB)` and write with `clamp = FALSE`.
96
#'
97
#' @export
98
#' @examplesIf interactive()
99
#' time = as.POSIXct("2026-01-28 21:00:00", tz = "Pacific/Auckland")
100
#' moon = generate_moon_disk(time, lat = -36.87593, lon = 174.7647)
101
#' moon[c("azimuth_deg", "elevation_deg", "angular_diameter_deg")]
102
#' # Let a renderer evaluate Earth's atmosphere at each interaction instead.
103
#' intrinsic_moon = generate_moon_disk(time, lat = -36.87593, lon = 174.7647,
104
#'   atmospheric_attenuation = FALSE)
105
generate_sun_disk = function(
106
  datetime,
107
  lat,
108
  lon,
109
  altitude = 0,
110
  resolution = 256,
111
  visibility = 50,
112
  albedo = 0.5,
113
  number_cores = 1,
114
  wide_spectrum = FALSE,
115
  prague_rgb_correction = TRUE,
116
  prague_rgb_correction_strength = 1,
117
  prague_rgb_correction_gain = "auto",
118
  atmospheric_attenuation = TRUE,
119
  hosek = FALSE,
120
  turbidity = 3,
121
  elevation = NULL,
122
  azimuth = NULL
123
) {
12479x
  validate_disk_logical(atmospheric_attenuation, "atmospheric_attenuation")
12575x
  validate_disk_logical(hosek, "hosek")
12675x
  validate_disk_scalar(turbidity, "turbidity", 1.7, 10)
12774x
  if (hosek && !atmospheric_attenuation) {
1281x
    stop(
1291x
      "Hosek solar disks require atmospheric_attenuation = TRUE.",
1301x
      call. = FALSE
131
    )
132
  }
13373x
  manual = !is.null(elevation) || !is.null(azimuth)
13473x
  if (manual) {
13518x
    validate_disk_scalar(elevation, "elevation", -90, 90)
13616x
    validate_disk_scalar(azimuth, "azimuth", 0, 360)
137
  }
13870x
  settings = celestial_disk_settings(
13970x
    datetime,
14070x
    lat,
14170x
    lon,
14270x
    altitude,
14370x
    resolution,
14470x
    visibility,
14570x
    albedo,
14670x
    number_cores,
14770x
    wide_spectrum,
14870x
    prague_rgb_correction,
14970x
    prague_rgb_correction_strength,
15070x
    prague_rgb_correction_gain
151
  )
15218x
  ephemeris = swe_dirs_topo_moon_sun(datetime, lat, lon, elev_m = altitude)
15318x
  d = ephemeris$sun_dir_topo
15418x
  if (manual) {
155
    # Convert the editor's north-to-east azimuth to Swiss Ephemeris coordinates.
15615x
    e = elevation * pi / 180
15715x
    a = azimuth * pi / 180
15815x
    d = c(-sin(a) * cos(e), -cos(a) * cos(e), sin(e))
159
  }
16018x
  position = celestial_disk_result(
16118x
    array(0, c(1, 1, 3)),
16218x
    d,
16318x
    ephemeris$sun_diameter_degrees
164
  )
16518x
  image = if (hosek) {
16615x
    hosek_sun_disk_rcpp(
16715x
      position$elevation_deg,
16815x
      position$azimuth_deg,
16915x
      albedo,
17015x
      turbidity,
17115x
      resolution,
17215x
      number_cores
173
    )
174
  } else {
1753x
    celestial_sun_pixels(
1763x
      c(d[1], d[3], -d[2]),
1773x
      resolution,
1783x
      settings,
1793x
      atmospheric_attenuation
180
    )
181
  }
18218x
  result = celestial_disk_result(image, d, ephemeris$sun_diameter_degrees)
18318x
  result$atmospheric_attenuation = atmospheric_attenuation
18418x
  result
185
}
186
187
#' @rdname generate_sun_disk
188
#' @export
189
generate_moon_disk = function(
190
  datetime,
191
  lat,
192
  lon,
193
  altitude = 0,
194
  resolution = 1024,
195
  visibility = 50,
196
  albedo = 0.5,
197
  number_cores = 1,
198
  wide_spectrum = FALSE,
199
  prague_rgb_correction = TRUE,
200
  prague_rgb_correction_strength = 1,
201
  prague_rgb_correction_gain = "auto",
202
  earthshine = TRUE,
203
  earthshine_albedo = 0.19,
204
  solar_irradiance_w_m2 = 1300,
205
  moon_extinction_kV = 0.172,
206
  atmospheric_attenuation = TRUE
207
) {
20869x
  validate_disk_logical(atmospheric_attenuation, "atmospheric_attenuation")
20965x
  settings = celestial_disk_settings(
21065x
    datetime,
21165x
    lat,
21265x
    lon,
21365x
    altitude,
21465x
    resolution,
21565x
    visibility,
21665x
    albedo,
21765x
    number_cores,
21865x
    wide_spectrum,
21965x
    prague_rgb_correction,
22065x
    prague_rgb_correction_strength,
22165x
    prague_rgb_correction_gain
222
  )
22313x
  validate_disk_logical(earthshine, "earthshine")
22412x
  validate_disk_scalar(earthshine_albedo, "earthshine_albedo", 0, Inf)
22511x
  validate_disk_scalar(solar_irradiance_w_m2, "solar_irradiance_w_m2", 0, Inf)
22611x
  if (solar_irradiance_w_m2 == 0) {
2271x
    stop("solar_irradiance_w_m2 must be positive.", call. = FALSE)
228
  }
22910x
  validate_disk_scalar(moon_extinction_kV, "moon_extinction_kV", 0, Inf)
2309x
  args = list(
2319x
    earthshine = earthshine,
2329x
    earthshine_albedo = earthshine_albedo,
2339x
    solar_irradiance_w_m2 = solar_irradiance_w_m2,
2349x
    moon_extinction_kV = moon_extinction_kV
235
  )
2369x
  ephemeris = swe_dirs_topo_moon_sun(
2379x
    datetime,
2389x
    lat,
2399x
    lon,
2409x
    elev_m = altitude,
2419x
    moon_extinction_kV = moon_extinction_kV
242
  )
2439x
  image = celestial_moon_pixels(
2449x
    datetime,
2459x
    lat,
2469x
    lon,
2479x
    resolution,
2489x
    args,
2499x
    ephemeris,
2509x
    settings,
2519x
    atmospheric_attenuation
252
  )
2538x
  result = celestial_disk_result(
2548x
    image,
2558x
    ephemeris$moon_dir_topo,
2568x
    ephemeris$moon_diameter_degrees
257
  )
2588x
  result$atmospheric_attenuation = atmospheric_attenuation
2598x
  result
260
}
261
262
#' @keywords internal
263
validate_disk_scalar = function(value, name, lower, upper, integer = FALSE) {
264
  if (
265815x
    !is.numeric(value) ||
266815x
      length(value) != 1L ||
267815x
      !is.finite(value) ||
268815x
      value < lower ||
269815x
      value > upper ||
270815x
      (integer && value != floor(value))
271
  ) {
27292x
    stop(
27392x
      name,
27492x
      " must be a finite ",
27526x
      if (integer) "integer" else "number",
27692x
      " between ",
27792x
      lower,
27892x
      " and ",
27992x
      upper,
280
      ".",
28192x
      call. = FALSE
282
    )
283
  }
284
}
285
286
#' @keywords internal
287
validate_disk_logical = function(value, name) {
288283x
  if (!is.logical(value) || length(value) != 1L || is.na(value)) {
28911x
    stop(name, " must be TRUE or FALSE.", call. = FALSE)
290
  }
291
}
292
293
#' @keywords internal
294
celestial_disk_settings = function(
295
  datetime,
296
  lat,
297
  lon,
298
  altitude,
299
  resolution,
300
  visibility,
301
  albedo,
302
  number_cores,
303
  wide_spectrum,
304
  prague_rgb_correction,
305
  prague_rgb_correction_strength,
306
  prague_rgb_correction_gain
307
) {
308
  if (
309135x
    !inherits(datetime, "POSIXct") ||
310135x
      length(datetime) != 1L ||
311135x
      !is.finite(as.numeric(datetime))
312
  ) {
3132x
    stop("datetime must be a single finite POSIXct instant.", call. = FALSE)
314
  }
315133x
  validate_disk_scalar(lat, "lat", -90, 90)
316121x
  validate_disk_scalar(lon, "lon", -180, 180)
317109x
  validate_disk_scalar(altitude, "altitude", 0, 15000)
31897x
  validate_disk_scalar(
31997x
    resolution,
32097x
    "resolution",
32197x
    16,
32297x
    .Machine$integer.max / 2,
32397x
    TRUE
324
  )
32583x
  validate_disk_scalar(visibility, "visibility", 20, 131.8)
32671x
  validate_disk_scalar(albedo, "albedo", 0, 1)
32759x
  validate_disk_scalar(
32859x
    number_cores,
32959x
    "number_cores",
33059x
    1,
33159x
    .Machine$integer.max,
33259x
    TRUE
333
  )
33447x
  validate_disk_logical(wide_spectrum, "wide_spectrum")
33545x
  normalize_prague_rgb_correction(prague_rgb_correction)
33643x
  prepare_prague_rgb_gain(
33743x
    prague_rgb_correction_gain,
33843x
    prague_rgb_correction_strength
339
  )
34031x
  list(
34131x
    altitude = altitude,
34231x
    visibility = visibility,
34331x
    albedo = albedo,
34431x
    number_cores = number_cores,
34531x
    wide_spectrum = wide_spectrum,
34631x
    prague_rgb_correction = prague_rgb_correction,
34731x
    prague_rgb_correction_strength = prague_rgb_correction_strength,
34831x
    prague_rgb_correction_gain = prague_rgb_correction_gain
349
  )
350
}
351
352
#' @keywords internal
353
celestial_disk_result = function(image, direction, diameter) {
35444x
  if (any(!is.finite(image))) {
355!
    stop(
356!
      "Nonfinite celestial radiance returned by the sky model.",
357!
      call. = FALSE
358
    )
359
  }
360
  # swe_dirs_topo_moon_sun retains Swiss Ephemeris's south-to-west azimuth
361
  # convention. Convert to the public north-to-east convention used by the sky.
36244x
  list(
36344x
    image = image,
36444x
    azimuth_deg = (180 + atan2(direction[1], direction[2]) * 180 / pi) %% 360,
36544x
    elevation_deg = asin(pmax(-1, pmin(1, direction[3]))) * 180 / pi,
36644x
    angular_diameter_deg = diameter,
36744x
    projection = "rectilinear"
368
  )
369
}
370
371
#' @keywords internal
372
celestial_frame = function(direction) {
3732x
  forward = direction / sqrt(sum(direction^2))
3742x
  vertical = if (abs(forward[2]) < 0.999999) c(0, 1, 0) else c(0, 0, 1)
3752x
  right = c(
3762x
    forward[2] * vertical[3] - forward[3] * vertical[2],
3772x
    forward[3] * vertical[1] - forward[1] * vertical[3],
3782x
    forward[1] * vertical[2] - forward[2] * vertical[1]
379
  )
3802x
  right = right / sqrt(sum(right^2))
3812x
  up = c(
3822x
    right[2] * forward[3] - right[3] * forward[2],
3832x
    right[3] * forward[1] - right[1] * forward[3],
3842x
    right[1] * forward[2] - right[2] * forward[1]
385
  )
3862x
  list(forward = forward, right = right, up = up)
387
}
388
389
#' @keywords internal
390
celestial_sun_pixels = function(
391
  direction,
392
  n,
393
  settings,
394
  atmospheric_attenuation = TRUE
395
) {
396
  # The intrinsic solar disk is independent of the terrestrial horizon. Query
397
  # its angular profile at the zenith even when the actual Sun is below it.
3983x
  if (!atmospheric_attenuation) {
3991x
    direction = c(0, 1, 0)
400
  }
4013x
  elevation = asin(direction[2]) * 180 / pi
4023x
  if (elevation < -4.2) {
4031x
    return(array(0, c(n, n, 3)))
404
  }
4052x
  azimuth = (atan2(-direction[1], direction[3]) * 180 / pi) %% 360
4062x
  frame = celestial_frame(direction)
4072x
  grid = expand.grid(
4082x
    y = 1 - 2 * ((seq_len(n) - 0.5) / n),
4092x
    x = 2 * ((seq_len(n) - 0.5) / n) - 1
410
  )
411
  # SUN_RADIUS in src/PragueSkyModel/PragueSkyModel.cpp. Sample its profile
412
  # here; consumers map the resulting image to the ephemeris angular diameter.
4132x
  radius = 0.004654793
4142x
  dirs = outer(grid$x * tan(radius), frame$right) +
4152x
    outer(grid$y * tan(radius), frame$up) +
4162x
    matrix(frame$forward, n * n, 3, byrow = TRUE)
4172x
  dirs = dirs / sqrt(rowSums(dirs^2))
4182x
  phi = (atan2(-dirs[, 1], dirs[, 3]) * 180 / pi) %% 360
4192x
  theta = asin(pmax(-1, pmin(1, dirs[, 2]))) * 180 / pi
4202x
  values = if (atmospheric_attenuation) {
4211x
    do.call(
4221x
      calculate_sky_values,
4231x
      c(
4241x
        list(
4251x
          phi = phi,
4261x
          theta = theta,
4271x
          elevation = elevation,
4281x
          azimuth = azimuth,
4291x
          render_mode = "sun"
430
        ),
4311x
        settings
432
      )
433
    )
434
  } else {
4351x
    filename = resolve_prague_coef_file(
4361x
      altitude = 0,
4371x
      wide_spectrum = settings$wide_spectrum,
4381x
      allow_download = FALSE
439
    )
4401x
    count = length(phi)
4411x
    values = calculate_raw_prague(
4421x
      phi,
4431x
      theta,
4441x
      rep(elevation, count),
4451x
      rep(settings$albedo, count),
4461x
      rep(0, count),
4471x
      rep(settings$visibility, count),
4481x
      rep(azimuth, count),
4491x
      settings$number_cores,
4501x
      filename,
4511x
      "sun",
4521x
      atmospheric_attenuation = FALSE
453
    )
4542x
    if (
4551x
      normalize_prague_rgb_correction(settings$prague_rgb_correction) ==
4561x
        "constant"
457
    ) {
4581x
      values = apply_prague_rgb_gain(
4591x
        values,
4601x
        prepare_prague_rgb_gain(
4611x
          settings$prague_rgb_correction_gain,
4621x
          settings$prague_rgb_correction_strength
463
        )
464
      )
465
    }
4661x
    values
467
  }
4682x
  array(as.numeric(values), c(n, n, 3))
469
}
470
471
#' @keywords internal
472
celestial_moon_pixels = function(
473
  datetime,
474
  lat,
475
  lon,
476
  resolution,
477
  args,
478
  ephemeris,
479
  settings,
480
  atmospheric_attenuation = TRUE
481
) {
482
  # skymodelr rasterizes a padded patch using rayvertex. Scope its thread count;
483
  # preparation happens before the path tracer's worker pool starts.
4849x
  old_options = options(cores = settings$number_cores)
4859x
  on.exit(options(old_options), add = TRUE)
4869x
  patch = do.call(
4879x
    generate_moon_image_latlong,
4889x
    c(
4899x
      list(
4909x
        datetime = datetime,
4919x
        lat = lat,
4929x
        lon = lon,
4939x
        elev_m = settings$altitude,
4949x
        width = 2 * resolution,
4959x
        height = 2 * resolution
496
      ),
4979x
      args
498
    )
4999x
  )$moon_luminance_array
5008x
  mask = patch[,, 4] > 0
5018x
  indices = which(mask, arr.ind = TRUE)
5028x
  if (!nrow(indices)) {
503!
    stop("skymodelr returned an empty Moon texture.", call. = FALSE)
504
  }
5058x
  rows = seq(min(indices[, 1]), max(indices[, 1]))
5068x
  cols = seq(min(indices[, 2]), max(indices[, 2]))
5078x
  patch = patch[rows, cols, , drop = FALSE]
5088x
  pixels = patch[,, 1:3, drop = FALSE]
509
  # The rasterizer's reconstruction filter can undershoot at the silhouette.
510
  # Remove negative coverage/radiance before the physical normalization.
5118x
  coverage = pmax(0, pmin(1, patch[,, 4]))
5128x
  for (c in 1:3) {
51324x
    pixels[,, c] = pmax(0, pixels[,, c]) * coverage
514
  }
515
5168x
  direction = c(
5178x
    ephemeris$moon_dir_topo[1],
5188x
    ephemeris$moon_dir_topo[3],
5198x
    -ephemeris$moon_dir_topo[2]
520
  )
5218x
  elevation = asin(pmax(-1, pmin(1, direction[2]))) * 180 / pi
522
  # Calibrate a complete disk. Its center may be below zero while the upper
523
  # limb remains visible; horizon visibility belongs to the consuming renderer.
5248x
  illuminance = if (atmospheric_attenuation) {
5256x
    apply_airmass_extinction(
5266x
      ephemeris$moon_brightness_lux_unattenuated,
5276x
      elevation,
5286x
      kV = args$moon_extinction_kV,
5296x
      clip_horizon = FALSE
530
    )
531
  } else {
5322x
    ephemeris$moon_brightness_lux_unattenuated
533
  }
5348x
  irradiance = lux_to_radiometric_irradiance(
5358x
    illuminance,
5368x
    compute_K_eff("BB5778")
537
  )
5388x
  rgb = compute_spd_rgb_unit("BB5778")
539
  # Use the same finite horizon limit for color, avoiding a tint discontinuity
540
  # when the center crosses zero. This remains a disk-wide approximation.
5418x
  tint_elevation = max(0, elevation)
5428x
  azimuth = (atan2(-direction[1], direction[3]) * 180 / pi) %% 360
5438x
  if (atmospheric_attenuation) {
5446x
    tint = do.call(
5456x
      calculate_sky_values,
5466x
      c(
5476x
        list(
5486x
          phi = azimuth,
5496x
          theta = tint_elevation,
5506x
          elevation = tint_elevation,
5516x
          azimuth = azimuth,
5526x
          render_mode = "sun"
553
        ),
5546x
        settings
555
      )
556
    )
5576x
    if (all(is.finite(tint)) && sum(tint) > 0) {
5586x
      rgb = rgb * pmax(as.numeric(tint), 0)
559
    }
560
  }
5618x
  rgb = rgb / sum(rgb)
5628x
  n = dim(pixels)
5638x
  xx = matrix(
5648x
    rep(2 * ((seq_len(n[2]) - 0.5) / n[2]) - 1, each = n[1]),
5658x
    n[1],
5668x
    n[2]
567
  )
5688x
  yy = matrix(rep(2 * ((seq_len(n[1]) - 0.5) / n[1]) - 1, n[2]), n[1], n[2])
5698x
  r2 = xx^2 + yy^2
5708x
  t2 = tan(ephemeris$moon_diameter_degrees * pi / 360)^2
5718x
  domega = 4 * t2 / (1 + t2 * r2)^1.5 / (n[1] * n[2])
5728x
  domega[r2 > 1] = 0
5738x
  for (c in 1:3) {
57424x
    integral = sum(pixels[,, c] * domega)
57524x
    pixels[,, c] = if (integral > 0) {
57624x
      pixels[,, c] * irradiance * rgb[c] / integral
577
    } else {
578!
      0
579
    }
580
  }
5818x
  pixels
582
}
1
sun_solid_angle_sr = function(diameter_deg = 0.533) {
23x
  r = (diameter_deg * 0.5) * pi / 180
33x
  2 * pi * (1 - cos(r))
4
}
5
6
#' Generate the atmosphere with the moon
7
#'
8
#' @description Note that this is just a scaled version of `generate_sky()`, scaled down by the luminance
9
#' of the moon as compared to the sun. This function takes the phase of the moon into account,
10
#' along with the increase in luminosity around a full moon (known as opposition surge). Moonlight
11
#' attenuation uses the Rozenberg/Krisciunas-Schaefer airmass approximation with configurable `moon_extinction_kV`.
12
#'
13
#' @details The complete lunar disk is calibrated before directions below the
14
#' horizontal horizon are clipped. The upper limb remains visible after the
15
#' center sets, with the finite horizon attenuation and tint retained below zero
16
#' center elevation. The visible segment is not renormalized to the full Moon's
17
#' brightness. Finite sky-map resolution limits how finely this edge is resolved.
18
#'
19
#' Disk visibility is independent of the atmospheric model's elevation domain:
20
#' the optional atmospheric component requires center elevation at least zero
21
#' for Hosek or -4.2 degrees for Prague. Below that domain it is omitted, while
22
#' any visible lunar limb is still drawn. Horizon depression and refraction are
23
#' not modeled.
24
#'
25
#' @param datetime           POSIX-compatible date-time.
26
#' @param lat                Observer latitude (degrees N).
27
#' @param lon                Observer longitude (degrees E; west < 0).
28
#' @param filename           Default `NA`. Path to the image file to write.
29
#' @param albedo             Default `0.5`. Ground albedo, range 0 to 1.
30
#' @param turbidity          Default `3`. Atmospheric turbidity, range
31
#'   1.7 to 10 (*Hosek only*).
32
#' @param altitude           Default `0`. Observer altitude (m), range
33
#'   0 to 15000 (*Prague only*).
34
#' @param resolution         Default `2048`. Image height in pixels (width = 2 * height).
35
#' @param number_cores        Default `1`. CPU threads to use.
36
#' @param moon_atmosphere    Default `FALSE`. If `TRUE`, this generates atmospheric scattering from light from the moon.
37
#' @param earthshine         Default `TRUE`. If `FALSE`, disable earthshine contribution on the moon.
38
#' @param earthshine_albedo  Default `0.19`. Effective Earth albedo term used
39
#'   in the earthshine irradiance approximation.
40
#' @param solar_irradiance_w_m2 Default `1300`. Reference solar irradiance at
41
#'   1 AU (W/m^2) used to normalize earthshine emission intensity.
42
#' @param moon_extinction_kV Default `0.172`. V-band atmospheric extinction
43
#'   coefficient for direct moonlight attenuation.
44
#' @param hosek              Default `TRUE`. `FALSE` selects the Prague model.
45
#' @param wide_spectrum      Default `FALSE`. 55-channel Prague coefficients (altitude = 0m only).
46
#' @param visibility         Default `50`. Meteorological range (km); *Prague only*.
47
#' @param moon_texture_width Default `801`. Internal moon-texture render width.
48
#' @param moon_texture_height Default `801`. Internal moon-texture render height.
49
#' @param verbose            Default `FALSE`. Whether to print progress bars/diagnostic info.
50
#'
51
#' @return Either the image array, or the array is invisibly returned if a file
52
#'   is written. The array has dimensions `(resolution, 2 * resolution, 4)`.
53
#' @note Writing to non-EXR formats will introduce precision loss because HDR
54
#'   data are quantised to the destination format, and low dynamic range outputs like PNG
55
#'   and JPEG files will not represent the true luminosity values encoded in the array.
56
#' @export
57
#'
58
#' @examplesIf interactive() || identical(Sys.getenv("IN_PKGDOWN"), "true")
59
#' # Moonlit sky (Hosek), mid-evening in DC
60
#' generate_moon_latlong(
61
#'   datetime = as.POSIXct("2025-09-05 19:30:00", tz = "America/New_York"),
62
#'   lat = 38.9072,
63
#'   lon = -77.0369,
64
#'   resolution = 400,
65
#'   turbidity = 3,
66
#'   verbose = TRUE
67
#' ) |>
68
#'   rayimage::render_exposure(15) |>
69
#'   rayimage::plot_image()
70
generate_moon_latlong = function(
71
  datetime,
72
  lat,
73
  lon,
74
  filename = NA,
75
  albedo = 0.5,
76
  turbidity = 3,
77
  altitude = 0,
78
  resolution = 2048,
79
  number_cores = 1,
80
  moon_atmosphere = FALSE,
81
  earthshine = TRUE,
82
  earthshine_albedo = 0.19,
83
  solar_irradiance_w_m2 = 1300,
84
  moon_extinction_kV = 0.172,
85
  hosek = TRUE,
86
  wide_spectrum = FALSE,
87
  visibility = 50,
88
  moon_texture_width = 801,
89
  moon_texture_height = 801,
90
  verbose = FALSE
91
) {
9217x
  moon_sun_data = swe_dirs_topo_moon_sun(
9317x
    datetime = datetime,
9417x
    lat = lat,
9517x
    lon = lon,
9617x
    elev_m = altitude,
9717x
    moon_extinction_kV = moon_extinction_kV
98
  )
9917x
  moon_dir = moon_sun_data$moon_dir_topo
10017x
  moon_elevation = asin(moon_dir[3]) * 180 / pi
10117x
  moon_azimuth = (180 + atan2(moon_dir[1], moon_dir[2]) * 180 / pi + 360) %%
10217x
    360
103
  # Sample sun colour so the moon inherits the same atmospheric tint.
10417x
  sun_rgb_ratio = c(1, 1, 1)
105
  # Disk visibility is evaluated per direction below. Keep a finite tint for
106
  # the visible upper limb even after the center passes the horizon.
10717x
  tint_elevation = max(0, moon_elevation)
10817x
  if (is.finite(moon_elevation)) {
10917x
    sample_resolution = max(256, min(1024, resolution))
11017x
    sun_sample = tryCatch(
111
      {
11217x
        generate_sky(
11317x
          albedo = albedo,
11417x
          turbidity = turbidity,
11517x
          altitude = altitude,
11617x
          elevation = tint_elevation,
11717x
          visibility = visibility,
11817x
          azimuth = moon_azimuth,
11917x
          resolution = sample_resolution,
12017x
          number_cores = number_cores,
12117x
          hosek = hosek,
12217x
          wide_spectrum = wide_spectrum,
12317x
          render_mode = "sun",
12417x
          verbose = FALSE
125
        )
126
      },
12717x
      error = function(e) {
128!
        NULL
129
      }
130
    )
13117x
    if (!is.null(sun_sample)) {
13217x
      sun_lum = sun_sample[,, 1] + sun_sample[,, 2] + sun_sample[,, 3]
13317x
      peak_idx = which.max(sun_lum)
13417x
      sun_rgb = c(
13517x
        sun_sample[,, 1][peak_idx],
13617x
        sun_sample[,, 2][peak_idx],
13717x
        sun_sample[,, 3][peak_idx]
138
      )
13917x
      sun_mean = mean(sun_rgb)
14017x
      if (all(is.finite(sun_rgb)) && sun_mean > 0) {
14117x
        sun_rgb_ratio = sun_rgb / sun_mean
142
      }
143
    }
144
  }
145
14617x
  moon_lux = moon_sun_data$moon_brightness_lux
14717x
  moon_phase = moon_sun_data$moon_phase
14817x
  spd_type = "BB5778"
14917x
  rgb_unit = compute_spd_rgb_unit(spd_type)
15017x
  K_eff = compute_K_eff(spd_type)
15117x
  moon_irradiance = lux_to_radiometric_irradiance(moon_lux, K_eff)
15217x
  if (!is.finite(moon_irradiance)) {
153!
    moon_irradiance = 0
154
  }
155
15617x
  old_options = options(cores = number_cores)
15717x
  on.exit(options(old_options), add = TRUE)
15817x
  moon_info_list = generate_moon_image_latlong(
15917x
    datetime = datetime,
16017x
    lat = lat,
16117x
    lon = lon,
16217x
    elev_m = altitude,
16317x
    width = moon_texture_width,
16417x
    height = moon_texture_height,
16517x
    earthshine = earthshine,
16617x
    earthshine_albedo = earthshine_albedo,
16717x
    solar_irradiance_w_m2 = solar_irradiance_w_m2,
16817x
    moon_extinction_kV = moon_extinction_kV,
16917x
    verbose = verbose
170
  )
17117x
  moon_luminance_array = moon_info_list$moon_luminance_array
17217x
  moon_angular_diameter_deg = moon_info_list$moon_angular_diameter_deg
17317x
  moon_angular_diameter_rad = moon_angular_diameter_deg * pi / 180
174
17517x
  if (verbose) {
176!
    message(sprintf(
177!
      "Moon: %0.1f elevation, %0.1f azimuth, %0.3f phase, %f lux",
178!
      moon_elevation,
179!
      moon_azimuth,
180!
      moon_phase,
181!
      moon_lux
182
    ))
183
  }
184
  # The atmospheric component still follows its model's supported domain;
185
  # this must not determine whether the independent lunar disk is rendered.
18617x
  atmosphere_min_elevation = if (hosek) 0 else -4.2
18717x
  if (moon_atmosphere && moon_elevation >= atmosphere_min_elevation) {
1883x
    coef_file = ""
1893x
    stopifnot(all(altitude >= 0 & altitude <= 15000))
1903x
    if (!hosek) {
1912x
      coef_file = resolve_prague_coef_file(
1922x
        altitude = altitude,
1932x
        wide_spectrum = wide_spectrum,
1942x
        model = "Prague moon-atmosphere model"
195
      )
196
    }
1973x
    moon_array = generate_sky(
1983x
      albedo = albedo,
1993x
      turbidity = turbidity,
2003x
      altitude = altitude,
2013x
      elevation = moon_elevation,
2023x
      azimuth = moon_azimuth,
2033x
      resolution = resolution,
2043x
      number_cores = number_cores,
2053x
      hosek = hosek,
2063x
      wide_spectrum = wide_spectrum,
2073x
      visibility = visibility,
2083x
      verbose = verbose,
2093x
      render_mode = "atmosphere"
210
    )
2113x
    lambda_values = seq(360, 720, by = 40)
2123x
    model = if (hosek) "hosek" else "prague"
2133x
    E_unit = calculate_sun_radiance_band_rcpp(
2143x
      albedo = albedo,
2153x
      turbidity = turbidity,
2163x
      elevation = moon_elevation,
2173x
      azimuth_deg = moon_azimuth,
2183x
      model = model,
2193x
      prg_dataset = coef_file,
2203x
      altitude = altitude,
2213x
      visibility = visibility,
2223x
      lambda_nm = if (hosek) lambda_values else NULL
223
    ) *
2243x
      sun_solid_angle_sr(0.533)
2253x
    scale_sun_to_moon = if (is.finite(E_unit) && E_unit > 0) {
2263x
      moon_irradiance / E_unit
227
    } else {
228!
      0
229
    }
230
    # Apply radiometric scaling and atmospheric tint
2313x
    moon_array[,, 1:3] = sweep(
2323x
      moon_array[,, 1:3] * scale_sun_to_moon,
2333x
      3,
2343x
      sun_rgb_ratio,
235
      "*"
236
    )
237
  } else {
23814x
    moon_array = array(
23914x
      0,
24014x
      dim = c(resolution, resolution * 2, 4)
241
    )
24214x
    moon_array[,, 4] = 1
243
  }
244
24517x
  moon_dir_vec = c(
24617x
    cospi(moon_azimuth / 180) * cospi(moon_elevation / 180),
24717x
    sinpi(moon_elevation / 180),
24817x
    sinpi(moon_azimuth / 180) * cospi(moon_elevation / 180)
249
  )
250
25117x
  moon_diameter_pixels = resolution / 180 * moon_angular_diameter_deg
25217x
  resize_moon_dim = ceiling(moon_diameter_pixels)
25317x
  if (resize_moon_dim %% 2 == 0) {
25417x
    resize_moon_dim = resize_moon_dim + 1
255
  }
25617x
  resized_moon_luminance_array = rayimage::render_resized(
25717x
    moon_luminance_array,
25817x
    dims = c(resize_moon_dim, resize_moon_dim),
25917x
    method = "box"
260
  )
26117x
  patch_mask = resized_moon_luminance_array[,, 4] > 0
26217x
  if (!any(patch_mask)) {
263!
    patch_mask[,] = TRUE
264
  }
26517x
  alpha_mask = resized_moon_luminance_array[,, 4] > 0
26617x
  if (any(alpha_mask)) {
26717x
    alpha_inds = which(alpha_mask, arr.ind = TRUE)
26817x
    min_row = min(alpha_inds[, 1])
26917x
    max_row = max(alpha_inds[, 1])
27017x
    min_col = min(alpha_inds[, 2])
27117x
    max_col = max(alpha_inds[, 2])
27217x
    center_x = (min_col + max_col) / 2
27317x
    center_y = (min_row + max_row) / 2
27417x
    radius_x = max(1, (max_col - min_col + 1) / 2)
27517x
    radius_y = max(1, (max_row - min_row + 1) / 2)
276
  } else {
277!
    half_dim = (resize_moon_dim - 1) / 2
278!
    center_x = half_dim + 1
279!
    center_y = half_dim + 1
280!
    radius_x = half_dim
281!
    radius_y = half_dim
282
  }
28317x
  rgb_target = rgb_unit * sun_rgb_ratio
28417x
  if (sum(rgb_target) > 0) {
28517x
    rgb_target = rgb_target / sum(rgb_target)
286
  } else {
287!
    rgb_target = rgb_unit
288
  }
28917x
  mean_rgb = c(
29017x
    mean(resized_moon_luminance_array[,, 1][patch_mask], na.rm = TRUE),
29117x
    mean(resized_moon_luminance_array[,, 2][patch_mask], na.rm = TRUE),
29217x
    mean(resized_moon_luminance_array[,, 3][patch_mask], na.rm = TRUE)
293
  )
29417x
  mean_rgb[!is.finite(mean_rgb)] = 0
29517x
  rgb_scale = ifelse(mean_rgb > 0, rgb_target / mean_rgb, 0)
29617x
  resized_moon_luminance_array[,, 1:3] = sweep(
29717x
    resized_moon_luminance_array[,, 1:3],
29817x
    3,
29917x
    rgb_scale,
300
    "*"
301
  )
30217x
  mean_sum = mean(
30317x
    rowSums(resized_moon_luminance_array[,, 1:3])[patch_mask],
30417x
    na.rm = TRUE
305
  )
30617x
  if (is.finite(mean_sum) && mean_sum > 0) {
30716x
    resized_moon_luminance_array[,, 1:3] =
30816x
      resized_moon_luminance_array[,, 1:3] / mean_sum
309
  }
310
31117x
  nTheta = resolution
31217x
  nPhi = 2 * resolution
31317x
  disk_mask = matrix(FALSE, nrow = nTheta, ncol = nPhi)
314
31517x
  r = moon_angular_diameter_rad / 2
31617x
  cos_r = cos(r)
317
31817x
  phi_c = moon_elevation * pi / 180
31917x
  j_min = max(1, floor(((pi / 2) - (phi_c + r)) / pi * (nTheta - 1)) + 1)
32017x
  j_max = min(
32117x
    nTheta,
32217x
    ceiling(((pi / 2) - (phi_c - r)) / pi * (nTheta - 1)) + 1
323
  )
324
32517x
  thetas = seq(pi / 2, -pi / 2, length.out = nTheta)
32617x
  phis = seq(0, 2 * pi, length.out = nPhi)
327
32817x
  cos_phi = cos(phis)
32917x
  sin_phi = sin(phis)
33017x
  cos_theta = cos(thetas)
33117x
  sin_theta = sin(thetas)
332
333
  # Tangent frame at moon center (z = moon_dir_vec)
33417x
  lam_c = moon_azimuth * pi / 180
33517x
  z_hat = moon_dir_vec
33617x
  e_hat = c(-sin(lam_c), 0, cos(lam_c))
33717x
  e_hat = e_hat / sqrt(sum(e_hat * e_hat)) # local east
33817x
  n_hat = c(
33917x
    z_hat[2] * e_hat[3] - z_hat[3] * e_hat[2],
34017x
    z_hat[3] * e_hat[1] - z_hat[1] * e_hat[3],
34117x
    z_hat[1] * e_hat[2] - z_hat[2] * e_hat[1]
342
  )
34317x
  n_hat = n_hat / sqrt(sum(n_hat * n_hat)) # local north
344
34517x
  tan_r = tan(r) # r = moon_angular_diameter_rad/2
346
  # Normalize the full projected disk, including its hidden portion. Using only
347
  # visible texels would concentrate the entire Moon's power into its last limb.
34817x
  dphi = 2 * pi / nPhi
34917x
  dtheta = pi / nTheta
35017x
  full_disk_integral = 0
351
35217x
  for (j in seq(j_min, j_max)) {
353357x
    for (i in seq_len(nPhi)) {
354146720x
      sample_dir_vec = c(
355146720x
        cos_phi[i] * cos_theta[j],
356146720x
        sin_theta[j],
357146720x
        sin_phi[i] * cos_theta[j]
358
      )
359146720x
      dot = sum(moon_dir_vec * sample_dir_vec)
360146720x
      if (dot < cos_r) {
361128026x
        next
362
      }
363
364
      # Camera (tangent) components of the sample direction
36518694x
      vx = sum(sample_dir_vec * e_hat)
36618694x
      vy = sum(sample_dir_vec * n_hat)
36718694x
      vz = sum(sample_dir_vec * z_hat) # == dot
368
369
      # Inverse rectilinear mapping (square FOV 2*r):
37018694x
      u_px = center_x + radius_x * (vx / (tan_r * vz))
37118694x
      v_px = center_y + radius_y * (vy / (tan_r * vz))
372
37318694x
      u_i = clamp_value(round(u_px), 1, resize_moon_dim)
37418694x
      v_i = clamp_value(round(v_px), 1, resize_moon_dim)
375
37618694x
      pixel = resized_moon_luminance_array[v_i, u_i, 1:3]
37718694x
      full_disk_integral = full_disk_integral +
37818694x
        sum(pixel) * dphi * dtheta * cos_theta[j]
37918694x
      if (sample_dir_vec[2] < 0) {
3802436x
        next
381
      }
38216258x
      disk_mask[j, i] = TRUE
38316258x
      moon_array[j, i, 1:3] = pixel
384
    }
385
  }
386
38717x
  disk_scale = if (is.finite(full_disk_integral) && full_disk_integral > 0) {
38817x
    moon_irradiance / full_disk_integral
389
  } else {
390!
    0
391
  }
39217x
  for (channel in 1:3) {
39351x
    moon_array[,, channel][disk_mask] = moon_array[,, channel][disk_mask] *
39451x
      disk_scale
395
  }
39617x
  moon_band = attr(moon_array, "L_band")
39717x
  if (is.null(moon_band)) {
39814x
    moon_band = moon_array[,, 1] + moon_array[,, 2] + moon_array[,, 3]
3993x
  } else if (any(disk_mask)) {
4003x
    moon_band[disk_mask] = moon_array[,, 1][disk_mask] +
4013x
      moon_array[,, 2][disk_mask] +
4023x
      moon_array[,, 3][disk_mask]
403
  }
40417x
  moon_array = as_sky_image(moon_array)
40517x
  attr(moon_array, "L_band") = moon_band
40617x
  if (!is.na(filename)) {
407!
    warn_precision_loss(filename)
408!
    write_sky_image(moon_array, filename, clamp = FALSE)
409!
    return(invisible(moon_array))
410
  } else {
41117x
    return(moon_array)
412
  }
413
}
1
#' Convert B-V color index to blackbody temperature
2
#'
3
#' @param bv Numeric vector of B-V values.
4
#' @return Numeric vector of temperatures in Kelvin.
5
#' @keywords internal
6
bv_to_temperature_K = function(bv) {
71x
  bv = pmax(pmin(bv, 2.0), -0.4)
81x
  temp = 4600 * (1 / (0.92 * bv + 1.7) + 1 / (0.92 * bv + 0.62))
91x
  temp[!is.finite(temp)] = NA_real_
101x
  pmax(pmin(temp, 40000), 1000)
11
}
12
13
#' Convert V magnitude to illuminance in lux
14
#'
15
#' @param mV Numeric vector of V magnitudes.
16
#' @param zero_point Optional scalar multiplier for catalog scaling.
17
#' @return Numeric vector of photometric illuminance in lux.
18
#' @keywords internal
19
vmag_to_ev_lux = function(mV, zero_point = 1) {
201x
  zero_point * 10^((-14.18 - mV) / 2.5)
21
}
22
23
#' Compute luminous efficacy for a blackbody SPD
24
#'
25
#' @param temperature_K Numeric vector of blackbody temperatures in Kelvin.
26
#' @param wavelengths_nm Optional wavelength grid in nm.
27
#' @param V_lambda Optional photopic V(lambda) samples matching the grid.
28
#' @return Numeric vector of K_eff values in lm/W.
29
#' @keywords internal
30
luminous_efficacy_blackbody = function(
31
  temperature_K,
32
  wavelengths_nm = NULL,
33
  V_lambda = NULL
34
) {
352x
  if (is.null(wavelengths_nm) || is.null(V_lambda)) {
361x
    cie = cie_1931_2deg()
371x
    wavelengths_nm = cie$lambda_nm
381x
    V_lambda = cie$y_bar
39
  }
402x
  if (length(wavelengths_nm) != length(V_lambda)) {
41!
    stop("wavelengths_nm and V_lambda must have the same length.")
42
  }
432x
  w = trapezoid_weights(wavelengths_nm)
442x
  c2 = 1.4387769e-2
452x
  blackbody_spd = function(T) {
462x
    lambda_m = wavelengths_nm * 1e-9
472x
    denom = exp(c2 / (lambda_m * T)) - 1
482x
    spd = 1 / (lambda_m^5 * denom)
492x
    spd[!is.finite(spd)] = 0
502x
    spd
51
  }
522x
  vapply(
532x
    temperature_K,
542x
    function(T) {
552x
      if (!is.finite(T) || T <= 0) {
56!
        return(NA_real_)
57
      }
582x
      spd = blackbody_spd(T)
592x
      num = sum(spd * V_lambda * w)
602x
      den = sum(spd * w)
612x
      if (!is.finite(num) || !is.finite(den) || den <= 0) {
62!
        return(NA_real_)
63
      }
642x
      683 * num / den
65
    },
662x
    numeric(1)
67
  )
68
}
69
70
#' Compute radiometric star amplitude and RGB unit vector
71
#'
72
#' @param mV Numeric vector of V magnitudes.
73
#' @param bv Numeric vector of B-V values.
74
#' @param wavelengths_nm Optional wavelength grid in nm.
75
#' @param V_lambda Optional photopic V(lambda) samples matching the grid.
76
#' @return List with E_v (lux), E_e (W/m^2), K_eff (lm/W), and rgb_unit.
77
#' @keywords internal
78
star_radiometric_amplitude = function(
79
  mV,
80
  bv,
81
  wavelengths_nm = NULL,
82
  V_lambda = NULL
83
) {
841x
  if (length(mV) != length(bv)) {
85!
    stop("mV and bv must have the same length.")
86
  }
871x
  cie = cie_1931_2deg()
881x
  if (is.null(wavelengths_nm)) {
891x
    wavelengths_nm = cie$lambda_nm
90
  }
911x
  if (is.null(V_lambda)) {
921x
    V_lambda = cie$y_bar
93
  }
941x
  if (length(wavelengths_nm) != length(V_lambda)) {
95!
    stop("wavelengths_nm and V_lambda must have the same length.")
96
  }
971x
  w = trapezoid_weights(wavelengths_nm)
981x
  c2 = 1.4387769e-2
991x
  blackbody_spd = function(T) {
1001x
    lambda_m = wavelengths_nm * 1e-9
1011x
    denom = exp(c2 / (lambda_m * T)) - 1
1021x
    spd = 1 / (lambda_m^5 * denom)
1031x
    spd[!is.finite(spd)] = 0
1041x
    spd
105
  }
1061x
  out = mapply(
1071x
    function(m, b) {
1081x
      T = bv_to_temperature_K(b)
1091x
      E_v = vmag_to_ev_lux(m)
1101x
      K_eff = luminous_efficacy_blackbody(T, wavelengths_nm, V_lambda)
1111x
      E_e = E_v / K_eff
1121x
      spd = blackbody_spd(T)
1131x
      X = sum(spd * cie$x_bar * w)
1141x
      Y = sum(spd * cie$y_bar * w)
1151x
      Z = sum(spd * cie$z_bar * w)
1161x
      rgb = xyz_to_srgb(c(X, Y, Z))
1171x
      rgb[!is.finite(rgb)] = 0
1181x
      rgb = pmax(rgb, 0)
1191x
      sum_rgb = sum(rgb)
1201x
      if (!is.finite(sum_rgb) || sum_rgb <= 0) {
121!
        rgb = c(1, 1, 1) / 3
122
      } else {
1231x
        rgb = rgb / sum_rgb
124
      }
1251x
      list(E_v = E_v, E_e = E_e, K_eff = K_eff, rgb_unit = rgb)
126
    },
1271x
    mV,
1281x
    bv,
1291x
    SIMPLIFY = FALSE
130
  )
1311x
  E_v = vapply(out, function(x) x$E_v, numeric(1))
1321x
  E_e = vapply(out, function(x) x$E_e, numeric(1))
1331x
  K_eff = vapply(out, function(x) x$K_eff, numeric(1))
1341x
  rgb_unit = do.call(rbind, lapply(out, function(x) x$rgb_unit))
1351x
  list(E_v = E_v, E_e = E_e, K_eff = K_eff, rgb_unit = rgb_unit)
136
}
1
normalize_render_mode = function(render_mode) {
228x
  if (is.logical(render_mode)) {
3!
    stopifnot(length(render_mode) == 1)
4!
    return(if (render_mode) "all" else "atmosphere")
5
  }
628x
  render_mode = tolower(as.character(render_mode))
728x
  match.arg(render_mode, c("all", "atmosphere", "sun"))
8
}
9
10
#' Generate a Hosek-Wilkie sky dome array
11
#'
12
#' @description Evaluate either the Hosek-Wilkie or Prague analytic sky models
13
#' and return a high-dynamic-range image array for the given solar
14
#' configuration. An image file is written only when `filename` is supplied.
15
#'
16
#' @param filename           Default `NA`. Path to an image file to write. If not given, the array is returned instead.
17
#' @param albedo             Default `0.1`. 0.0-1.0 ground albedo. Grass has an albedo of about 0.09, while a landscape covered in
18
#' snow will have an albedo of 1.0.
19
#' @param turbidity          Default `3`. 1.7-10 atmospheric turbidity. Only valid for Hosek model.
20
#' @param elevation          Default `10`. Solar elevation above the horizon (degrees).
21
#' @param azimuth            Default `90`, sun directly east. Solar azimuth (degrees). The left edge of the image faces north and the middle faces south.
22
#' @param altitude           Default `0`. Altitude of the viewer in meters. Valid range: 0 to 15000. Only valid for the Prague model.
23
#' @param resolution         Default `2048`. Height of the image. Width is twice this number.
24
#' @param number_cores        Default `1`. Number of threads to use in computation.
25
#' @param hosek              Default `TRUE`. Set to `FALSE` to enable the Prague 2021-22 spectral sky model.
26
#' @param wide_spectrum      Default `FALSE`. Use the 55-channel Prague coefficients (sea level only).
27
#' @param visibility         Default `50`. Meteorological range in kilometres for Prague model.
28
#' @param verbose            Default `FALSE`. Whether to print progress bars/diagnostic info.
29
#' @param render_mode        Default `"all"`. One of `"all"`, `"atmosphere"`, or `"sun"`.
30
#'   Use `"all"` for atmosphere + solar disk, `"atmosphere"` for atmospheric radiance only, or `"sun"` for the solar disk only.
31
#' @param below_horizon      Default `TRUE`. Whether to sample atmospheric scattering below the horizon, which is non-zero when altitude > 0.
32
#' @param prague_rgb_correction Default `TRUE`. Whether to apply the Prague RGB
33
#' tint correction. This correction is only applied when `hosek = FALSE`. Use
34
#' `FALSE` for raw Prague RGB output.
35
#' @param prague_rgb_correction_strength Default `1`. Strength of the Prague RGB
36
#' tint correction. Use `0` for no correction and `1` for the calibrated
37
#' correction.
38
#' @param prague_rgb_correction_gain Default `"auto"`. Multiplicative linear RGB
39
#' gain used by the Prague RGB tint correction. `"auto"` uses the calibrated
40
#' default `c(R = 0.94438727, G = 1.02157200, B = 0.95012063)`.
41
#' @param exr_adopted_white Default `"D60"`. Adopted neutral white to write to
42
#' EXR metadata for generated sky maps. Currently supports `"D60"`, `"D65"`,
43
#' or a numeric XYZ white with Y = 1. This tags the EXR `adoptedNeutral`
44
#' metadata and does not change pixel values.
45
#' @param exr_metadata Default `TRUE`. Whether to attach skymodelr EXR metadata
46
#' before writing EXR output. Metadata includes sRGB/Rec.709 chromaticities and
47
#' the selected adopted neutral white.
48
#'
49
#' @details
50
#' For Prague RGB output, `prague_rgb_correction = TRUE` applies a fixed linear
51
#' RGB gain to reduce the small magenta / negative-green tint observed in the
52
#' RGB projection of Prague sky maps. Set `prague_rgb_correction = FALSE` to
53
#' recover raw Prague RGB output. The correction is not a white balance and is
54
#' not applied to wavelength-specific spectral radiance.
55
#'
56
#' EXR metadata: Generated sky maps are linear RGB. When `exr_metadata = TRUE`,
57
#' skymodelr tags the image with sRGB/Rec.709 chromaticities and an EXR
58
#' `adoptedNeutral` white. The default adopted neutral is D60. This metadata
59
#' does not convert pixel values; it informs downstream readers how to treat the
60
#' scene neutral. Use `exr_adopted_white = "D65"` for D65 adopted neutral, or
61
#' `exr_metadata = FALSE` to omit skymodelr EXR metadata. The RGB encoding
62
#' remains linear sRGB / Rec.709 even when the adopted neutral is D60.
63
#'
64
#' @return Either the image array, or the array is invisibly returned if a file
65
#'   is written. The array has dimensions `(resolution, 2 * resolution, 4)`.
66
#' @note Writing to non-EXR formats will introduce precision loss because HDR
67
#'   data are quantised to the destination format, and low dynamic range outputs like PNG
68
#'   and JPEG files will not represent the true luminosity values encoded in the array.
69
#' @export
70
#' @examples
71
#' sky = generate_sky(
72
#'   resolution = 8,
73
#'   elevation = 30,
74
#'   azimuth = 135,
75
#'   render_mode = "atmosphere"
76
#' )
77
#' dim(sky)
78
#'
79
#' @examplesIf interactive() || identical(Sys.getenv("IN_PKGDOWN"), "true")
80
#' # Hosek model (default): clear morning, Sun SE, with solar disk
81
#' generate_sky(
82
#'   resolution = 400,
83
#'   elevation  = 15,
84
#'   azimuth    = 135,
85
#'   turbidity  = 3,
86
#'   render_mode = "all"
87
#' ) |>
88
#'   rayimage::plot_image()
89
#'
90
#' # Same view but hazier and without the solar disk
91
#' generate_sky(
92
#'   resolution = 400,
93
#'   elevation  = 15,
94
#'   azimuth    = 135,
95
#'   turbidity  = 6,
96
#'   render_mode = "atmosphere"
97
#' ) |>
98
#'   rayimage::plot_image()
99
#'
100
#' # Prague model (requires downloaded coefficients)
101
#' generate_sky(
102
#'   resolution = 400,
103
#'   hosek      = FALSE,
104
#'   altitude   = 0,
105
#'   visibility = 80,
106
#'   albedo     = 0.2,
107
#'   elevation  = 5,
108
#'   azimuth    = 220,
109
#'   number_cores = 2
110
#' ) |>
111
#'   rayimage::plot_image()
112
#'
113
#' generate_sky(
114
#'   "raw_prague.exr",
115
#'   elevation = 60,
116
#'   azimuth = 315,
117
#'   hosek = FALSE,
118
#'   prague_rgb_correction = FALSE
119
#' )
120
generate_sky = function(
121
  filename = NA,
122
  albedo = 0.1,
123
  turbidity = 3,
124
  elevation = 10,
125
  azimuth = 90,
126
  altitude = 0,
127
  resolution = 2048,
128
  number_cores = 1,
129
  hosek = TRUE,
130
  wide_spectrum = FALSE,
131
  visibility = 50,
132
  verbose = FALSE,
133
  render_mode = "all",
134
  below_horizon = TRUE,
135
  prague_rgb_correction = TRUE,
136
  prague_rgb_correction_strength = 1,
137
  prague_rgb_correction_gain = "auto",
138
  exr_adopted_white = "D60",
139
  exr_metadata = TRUE
140
) {
14112x
  render_mode = normalize_render_mode(render_mode)
14212x
  coef_file = ""
14312x
  if (!hosek) {
144!
    stopifnot(altitude >= 0 && altitude <= 15000)
145!
    model = "prague"
146!
    coef_file = resolve_prague_coef_file(
147!
      altitude = altitude,
148!
      wide_spectrum = wide_spectrum
149
    )
150
  } else {
15112x
    model = "hosek"
152
  }
153
  #If sun below valid region, write black image
15412x
  if (model == "hosek") {
15512x
    if (elevation < 0.0) {
1562x
      if (verbose) {
157!
        message(
158!
          "Drawing black image as Hosek model does not produce valid output for elevation < 0."
159
        )
160
      }
1612x
      black_sky = array(0, dim = c(resolution, resolution * 2, 4))
1622x
      black_sky[,, 4] = 1
1632x
      black_sky = as_sky_image(black_sky)
1642x
      black_sky = tag_generated_sky_exr_metadata(
1652x
        black_sky,
1662x
        hosek = hosek,
1672x
        exr_metadata = exr_metadata,
1682x
        exr_adopted_white = exr_adopted_white
169
      )
1702x
      if (!is.na(filename)) {
1711x
        warn_precision_loss(filename)
1721x
        write_sky_image(black_sky, filename)
1731x
        return(invisible(black_sky))
174
      } else {
1751x
        return(black_sky)
176
      }
177
    }
178
  } else {
179!
    if (elevation < -4.2) {
180!
      if (verbose) {
181!
        message(
182!
          "Drawing black image as Prague model does not produce valid output for elevation < -4.2."
183
        )
184
      }
185!
      black_sky = array(0, dim = c(resolution, resolution * 2, 4))
186!
      black_sky[,, 4] = 1
187!
      black_sky = as_sky_image(black_sky)
188!
      black_sky = tag_generated_sky_exr_metadata(
189!
        black_sky,
190!
        hosek = hosek,
191!
        exr_metadata = exr_metadata,
192!
        exr_adopted_white = exr_adopted_white
193
      )
194!
      if (!is.na(filename)) {
195!
        warn_precision_loss(filename)
196!
        write_sky_image(black_sky, filename)
197!
        return(invisible(black_sky))
198
      } else {
199!
        return(black_sky)
200
      }
201
    }
202
  }
203
20410x
  lambda_values = seq(360, 720, by = 40)
205
20610x
  generated_rgb = makesky_rcpp(
20710x
    albedo = albedo,
20810x
    turbidity = turbidity,
20910x
    elevation = elevation,
21010x
    azimuth_deg = azimuth,
21110x
    resolution = resolution,
21210x
    number_cores = number_cores,
21310x
    model = model,
21410x
    prg_dataset = coef_file,
21510x
    altitude = altitude,
21610x
    visibility = visibility,
21710x
    render_mode = render_mode,
21810x
    lambda_nm = lambda_values,
21910x
    below_horizon = below_horizon
220
  )
22110x
  band = attr(generated_rgb, "L_band")
222
22310x
  applied_prague_rgb_gain = NULL
224
22510x
  if (!hosek) {
226!
    prague_rgb_correction = normalize_prague_rgb_correction(
227!
      prague_rgb_correction
228
    )
229
  }
230
23110x
  if (!hosek && prague_rgb_correction == "constant") {
232!
    applied_prague_rgb_gain = prepare_prague_rgb_gain(
233!
      gain = prague_rgb_correction_gain,
234!
      strength = prague_rgb_correction_strength
235
    )
236
237!
    generated_rgb = apply_prague_rgb_gain(
238!
      generated_rgb,
239!
      gain = applied_prague_rgb_gain
240
    )
241
  }
242
24310x
  generated_sky = array(0, dim = c(resolution, resolution * 2, 4))
24410x
  generated_sky[,, 1:3] = generated_rgb
24510x
  generated_sky[,, 4] = 1
24610x
  if (!is.null(band)) {
24710x
    attr(generated_sky, "L_band") = band
248
  }
24910x
  generated_sky = as_sky_image(generated_sky)
25010x
  if (!is.null(applied_prague_rgb_gain)) {
251!
    attr(generated_sky, "prague_rgb_correction") = "constant"
252!
    attr(generated_sky, "prague_rgb_correction_gain") = applied_prague_rgb_gain
253!
    attr(generated_sky, "prague_rgb_correction_strength") =
254!
      prague_rgb_correction_strength
255
  }
25610x
  generated_sky = tag_generated_sky_exr_metadata(
25710x
    generated_sky,
25810x
    hosek = hosek,
25910x
    exr_metadata = exr_metadata,
26010x
    exr_adopted_white = exr_adopted_white
261
  )
262
26310x
  if (!is.na(filename)) {
2641x
    warn_precision_loss(filename)
2651x
    write_sky_image(generated_sky, filename)
2661x
    return(invisible(generated_sky))
267
  } else {
2689x
    return(generated_sky)
269
  }
270
}
271
272
#' Generate a location and time-specific sky dome (optionally with stars)
273
#'
274
#' @description Convenience wrapper around [generate_sky()] that:
275
#' 1. Computes the Sun's apparent position for `datetime`, `lat`, and `lon`
276
#'    (via Swiss Ephemeris / **swephR**).
277
#' 2. Renders the corresponding sky model.
278
#' 3. Optionally overlays a star field using [generate_stars()] or moon with [generate_moon_latlong()].
279
#'
280
#' @param datetime           POSIX-compatible date-time.
281
#' @param lat                Observer latitude (degrees N).
282
#' @param lon                Observer longitude (degrees E; west < 0).
283
#' @param filename            Default `NA`. Path to the `.exr` file to write.
284
#' @param albedo             Default `0.5`. Ground albedo, range 0 to 1.
285
#' @param turbidity          Default `3`. Atmospheric turbidity, range
286
#'   1.7 to 10 (*Hosek only*).
287
#' @param altitude           Default `0`. Observer altitude (m), range
288
#'   0 to 15000 (*Prague only*).
289
#' @param resolution         Default `2048`. Image height in pixels (width = 2 * height).
290
#' @param number_cores        Default `1`. CPU threads to use.
291
#' @param hosek              Default `TRUE`. `FALSE` selects the Prague model.
292
#' @param wide_spectrum      Default `FALSE`. 55-channel Prague coefficients (altitude = 0m only).
293
#' @param visibility         Default `50`. Meteorological range (km); *Prague only*.
294
#' @param stars              Default `FALSE`. If `TRUE`, composite a star field
295
#'   using [generate_stars()]. Automatically falls back to a pure star render
296
#'   when the black-sky condition is met (see *Details*).
297
#' @param star_width         Default `1`. Passed to [generate_stars()] to control stellar point-spread size.
298
#' @param planets            Default `FALSE`. If `TRUE`, composite bright planets via [generate_planets()].
299
#' @param moon               Default `FALSE`. If `TRUE`, overlay a moon render from [generate_moon_latlong()].
300
#' @param moon_atmosphere    Default `FALSE`. If `TRUE`, this generates atmospheric scattering from light from the moon.
301
#' @param moon_hosek         Default `TRUE`. Whether to use the faster (but less accurate) Hosek model for atmospheric scattering from the moon. Note
302
#' that the light scattered from the moon is much less intense than the sun, and thus small inaccuracies are much less likely to be noticable.
303
#' @param render_mode        Default `"all"`. One of `"all"`, `"atmosphere"`, or `"sun"`.
304
#'   Use `"all"` for atmosphere + solar disk, `"atmosphere"` for atmospheric radiance only, or `"sun"` for the solar disk only.
305
#' @param below_horizon      Default `TRUE`. Whether to sample atmospheric scattering below the horizon, which is non-zero when altitude > 0.
306
#' @param prague_rgb_correction Default `TRUE`. Whether to apply the Prague RGB
307
#' tint correction. This correction is only applied when `hosek = FALSE`. Use
308
#' `FALSE` for raw Prague RGB output.
309
#' @param prague_rgb_correction_strength Default `1`. Strength of the Prague RGB
310
#' tint correction. Use `0` for no correction and `1` for the calibrated
311
#' correction.
312
#' @param prague_rgb_correction_gain Default `"auto"`. Multiplicative linear RGB
313
#' gain used by the Prague RGB tint correction. `"auto"` uses the calibrated
314
#' default `c(R = 0.94438727, G = 1.02157200, B = 0.95012063)`.
315
#' @param exr_adopted_white Default `"D60"`. Adopted neutral white to write to
316
#' EXR metadata for generated sky maps. Currently supports `"D60"`, `"D65"`,
317
#' or a numeric XYZ white with Y = 1. This tags the EXR `adoptedNeutral`
318
#' metadata and does not change pixel values.
319
#' @param exr_metadata Default `TRUE`. Whether to attach skymodelr EXR metadata
320
#' before writing EXR output. Metadata includes sRGB/Rec.709 chromaticities and
321
#' the selected adopted neutral white.
322
#' @param stars_exposure     Default `0`. Increases star exposure by `2^exposure`. Non-physical, this just controls adjustments for artistic effect.
323
#' @param verbose            Default `FALSE`. Whether to print progress bars/diagnostic info.
324
#' @param ...                Additional **named** arguments forwarded to [generate_stars()], and when enabled, [generate_planets()] and [generate_moon_latlong()].
325
#'   Unmatched names are ignored.
326
#'
327
#' @details
328
#' *Solar angles* - altitude (degrees above the horizon) and azimuth (degrees clockwise from
329
#' east, so 90 degrees = south) - are derived internally; you never have to supply
330
#' them directly.
331
#'
332
#' *Black-sky rule* - With the Prague model the sky radiance is defined only
333
#' down to -4.2 degrees, and with the Hosek model it is defined only about 0 degrees.
334
#' Below that the function skips the sky render and writes **only stars** when `stars = TRUE`.
335
#'
336
#' @return Either the raw data, or the data is invisibly returned if filename is given. The EXR is written to `filename`.
337
#' @export
338
#'
339
#' @examples
340
#' sky = generate_sky_latlong(
341
#'   datetime = as.POSIXct("2025-03-21 12:00:00", tz = "America/New_York"),
342
#'   lat = 38.9072,
343
#'   lon = -77.0369,
344
#'   resolution = 8
345
#' )
346
#' dim(sky)
347
#'
348
#' @examplesIf interactive() || identical(Sys.getenv("IN_PKGDOWN"), "true")
349
#' # Morning sunrise on spring solstice over Washington, DC with Prague model
350
#' generate_sky_latlong(
351
#'   datetime = as.POSIXct("2025-03-21 06:15:00", tz = "America/New_York"),
352
#'   lat = 38.9072,
353
#'   lon = -77.0369,
354
#'   number_cores = 2,
355
#'   hosek = FALSE
356
#' ) |>
357
#'   rayimage::plot_image()
358
#'
359
#' generate_sky_latlong(
360
#'   datetime = as.POSIXct("2025-03-21 12:00:00", tz = "America/New_York"),
361
#'   lat = 38.9072,
362
#'   lon = -77.0369,
363
#'   number_cores = 2
364
#' ) |>
365
#'   rayimage::plot_image()
366
#'
367
#' generate_sky_latlong(
368
#'   datetime = as.POSIXct("2025-03-21 18:00:00", tz = "America/New_York"),
369
#'   lat = 38.9072,
370
#'   lon = -77.0369,
371
#'   number_cores = 2
372
#' ) |>
373
#'   rayimage::plot_image()
374
#'
375
#' generate_sky_latlong(
376
#'   datetime = as.POSIXct("2025-03-21 18:30:00", tz = "America/New_York"),
377
#'   lat = 38.9072,
378
#'   lon = -77.0369,
379
#'   number_cores = 2,
380
#'   hosek = FALSE,
381
#'   verbose = TRUE
382
#' ) |>
383
#'   rayimage::render_exposure(exposure = 2) |>
384
#'   rayimage::plot_image()
385
generate_sky_latlong = function(
386
  datetime,
387
  lat,
388
  lon,
389
  filename = NA,
390
  albedo = 0.5,
391
  turbidity = 3,
392
  altitude = 0,
393
  resolution = 2048,
394
  number_cores = 1,
395
  hosek = TRUE,
396
  wide_spectrum = FALSE,
397
  visibility = 50,
398
  stars = FALSE,
399
  star_width = 1.0,
400
  planets = FALSE,
401
  moon = FALSE,
402
  moon_atmosphere = FALSE,
403
  moon_hosek = TRUE,
404
  render_mode = "all",
405
  below_horizon = TRUE,
406
  prague_rgb_correction = TRUE,
407
  prague_rgb_correction_strength = 1,
408
  prague_rgb_correction_gain = "auto",
409
  exr_adopted_white = "D60",
410
  exr_metadata = TRUE,
411
  verbose = FALSE,
412
  stars_exposure = 0,
413
  ...
414
) {
4156x
  render_mode = normalize_render_mode(render_mode)
4166x
  extra_args = list(...)
4176x
  filter_extra_args = function(fun, args) {
41818x
    arg_names = names(args)
41918x
    if (length(arg_names) == 0) {
42012x
      return(list())
421
    }
4226x
    valid = names(formals(fun))
4236x
    keep = !is.null(arg_names) & nzchar(arg_names) & (arg_names %in% valid)
4246x
    args[keep]
425
  }
4266x
  merge_call_args = function(base_args, extra_args) {
4272x
    if (length(extra_args) == 0) {
428!
      return(base_args)
429
    }
4302x
    extra_args = extra_args[!(names(extra_args) %in% names(base_args))]
4312x
    c(base_args, extra_args)
432
  }
4336x
  moon_extra = filter_extra_args(generate_moon_latlong, extra_args)
4346x
  stars_extra = filter_extra_args(generate_stars, extra_args)
4356x
  planets_extra = filter_extra_args(generate_planets, extra_args)
436
4376x
  sunmoon_data = swe_dirs_topo_moon_sun(
4386x
    datetime = datetime,
4396x
    lat = lat,
4406x
    lon = lon,
4416x
    elev_m = altitude
442
  )
4436x
  sun_dir = sunmoon_data$sun_dir_topo
4446x
  elevation = asin(sun_dir[3]) * 180 / pi
4456x
  azimuth = (180 + atan2(sun_dir[1], sun_dir[2]) * 180 / pi + 360) %% 360
446
4476x
  if (verbose) {
448!
    message(sprintf(
449!
      "Sun: %0.1f elevation, %0.1f azimuth",
450!
      elevation,
451!
      azimuth
452
    ))
453
  }
454
  # Just add up all three
4556x
  sky_array = generate_sky(
4566x
    albedo = albedo,
4576x
    turbidity = turbidity,
4586x
    altitude = altitude,
4596x
    elevation = elevation,
4606x
    azimuth = azimuth,
4616x
    resolution = resolution,
4626x
    number_cores = number_cores,
4636x
    hosek = hosek,
4646x
    wide_spectrum = wide_spectrum,
4656x
    visibility = visibility,
4666x
    verbose = verbose,
4676x
    render_mode = render_mode,
4686x
    below_horizon = below_horizon,
4696x
    prague_rgb_correction = prague_rgb_correction,
4706x
    prague_rgb_correction_strength = prague_rgb_correction_strength,
4716x
    prague_rgb_correction_gain = prague_rgb_correction_gain,
4726x
    exr_adopted_white = exr_adopted_white,
4736x
    exr_metadata = exr_metadata
474
  )
475
4766x
  if (moon) {
4772x
    moon_call_args = merge_call_args(
4782x
      base_args = list(
4792x
        filename = filename,
4802x
        datetime = datetime,
4812x
        lat = lat,
4822x
        lon = lon,
4832x
        albedo = albedo,
4842x
        turbidity = turbidity,
4852x
        altitude = altitude,
4862x
        resolution = resolution,
4872x
        number_cores = number_cores,
4882x
        hosek = moon_hosek,
4892x
        moon_atmosphere = moon_atmosphere,
4902x
        wide_spectrum = wide_spectrum,
4912x
        visibility = visibility,
4922x
        verbose = verbose
493
      ),
4942x
      extra_args = moon_extra
495
    )
4962x
    moon_array = do.call(generate_moon_latlong, moon_call_args)
4972x
    sky_band = attr(sky_array, "L_band")
4982x
    moon_band = attr(moon_array, "L_band")
4992x
    sky_array = sky_array + moon_array
5002x
    if (!is.null(sky_band) && !is.null(moon_band)) {
5012x
      attr(sky_array, "L_band") = sky_band + moon_band
502
    }
503
  }
5046x
  if (stars) {
505!
    stars_call_args = merge_call_args(
506!
      base_args = list(
507!
        resolution = resolution,
508!
        lon = lon,
509!
        lat = lat,
510!
        datetime = as.POSIXct(datetime),
511!
        turbidity = turbidity,
512!
        altitude = altitude,
513!
        number_cores = number_cores,
514!
        star_width = star_width
515
      ),
516!
      extra_args = stars_extra
517
    )
518!
    stars_array = do.call(generate_stars, stars_call_args) *
519!
      (2^stars_exposure)
520!
    sky_array = sky_array + stars_array
521
  }
5226x
  if (planets) {
523!
    planets_call_args = merge_call_args(
524!
      base_args = list(
525!
        resolution = resolution,
526!
        datetime = as.POSIXct(datetime),
527!
        lon = lon,
528!
        lat = lat,
529!
        turbidity = turbidity,
530!
        altitude = altitude,
531!
        number_cores = number_cores,
532!
        planet_width = star_width,
533!
        verbose = verbose
534
      ),
535!
      extra_args = planets_extra
536
    )
537!
    planets_array = do.call(generate_planets, planets_call_args)
538!
    sky_array = sky_array + planets_array
539
  }
5406x
  sky_array[,, 4] = 1
5416x
  sky_array = as_sky_image(sky_array)
5426x
  sky_array = tag_generated_sky_exr_metadata(
5436x
    sky_array,
5446x
    hosek = hosek,
5456x
    exr_metadata = exr_metadata,
5466x
    exr_adopted_white = exr_adopted_white
547
  )
5486x
  if (!is.na(filename)) {
5491x
    warn_precision_loss(filename)
5501x
    write_sky_image(sky_array, filename, clamp = FALSE)
5511x
    return(invisible(sky_array))
552
  } else {
5535x
    return(sky_array)
554
  }
555
}
556
557
#' Sample a direction from the Prague model.
558
#'
559
#' @description Evaluate the Prague spectral sky model at arbitrary spherical
560
#' directions without writing an image, returning radiance-only samples.
561
#'
562
#' @param phi                Horizontal angle of the sample, degrees. Vectorized. Range 0 to 360.
563
#' @param theta              Vertical angle of the sample, degrees. Vectorized. Range -90 to 90.
564
#' @param altitude 	         Default `0`, vectorized. Altitude of the viewer in meters. Range 0 to 15000.
565
#' @param elevation          Default `10`, vectorized. Solar elevation angle above/below the horizon (degrees). Range -4.2 to 90.
566
#' @param visibility         Default `50`, vectorized. Range 20 to 131.8. Meteorological range in kilometers for Prague model.
567
#' @param albedo             Default `0.5`, vectorized. Range 0 to 1. Ground albedo.
568
#' @param azimuth            Default `90`, single value. Solar azimuth (degrees). Defaults South.
569
#' @param number_cores        Default `1`. Number of threads to use in computation.
570
#' @param wide_spectrum      Default `FALSE`. Whether to use the wide-spectrum (55-channel, polarised) coefficients.
571
#' @param render_mode        Default `"all"`. One of `"all"`, `"atmosphere"`, or `"sun"`.
572
#'   Use `"all"` for atmosphere + solar disk, `"atmosphere"` for atmospheric radiance only, or `"sun"` for the solar disk only.
573
#' @param prague_rgb_correction Default `TRUE`. Whether to apply the Prague RGB
574
#' tint correction to returned RGB values. This correction is only applied to
575
#' Prague RGB output.
576
#' @param prague_rgb_correction_strength Default `1`. Strength of the Prague RGB
577
#' tint correction. Use `0` for no correction and `1` for the calibrated
578
#' correction.
579
#' @param prague_rgb_correction_gain Default `"auto"`. Multiplicative linear RGB
580
#' gain used by the Prague RGB tint correction. `"auto"` uses the calibrated
581
#' default `c(R = 0.94438727, G = 1.02157200, B = 0.95012063)`.
582
#'
583
#' @return 3-column RGB matrix.
584
#' @export
585
#' @examplesIf interactive() || identical(Sys.getenv("IN_PKGDOWN"), "true")
586
#' # Generate a basic atmosphere with the Prague model
587
#' value_grid = expand.grid(
588
#'   phi = seq(0, 360, by = 30),
589
#'   theta = seq(0, 90, by = 10),
590
#'   altitude = c(0, 10000)
591
#' )
592
#' vals = calculate_sky_values(
593
#'   phi = value_grid$phi,
594
#'   theta = value_grid$theta,
595
#'   altitude = value_grid$altitude,
596
#'   elevation = 45,
597
#'   visibility = 120,
598
#'   albedo = 0
599
#' )
600
#' cbind(value_grid, vals)
601
calculate_sky_values = function(
602
  phi,
603
  theta,
604
  altitude = 0,
605
  elevation = 10,
606
  visibility = 50,
607
  albedo = 0.5,
608
  azimuth = 90,
609
  number_cores = 1,
610
  wide_spectrum = FALSE,
611
  render_mode = "all",
612
  prague_rgb_correction = TRUE,
613
  prague_rgb_correction_strength = 1,
614
  prague_rgb_correction_gain = "auto"
615
) {
616!
  render_mode = normalize_render_mode(render_mode)
617!
  stopifnot(all(phi <= 360 & phi >= 0))
618!
  stopifnot(all(theta <= 90 & theta >= -90))
619!
  stopifnot(all(altitude <= 15000 & altitude >= 0))
620!
  stopifnot(all(visibility >= 20 & visibility <= 131.8))
621!
  stopifnot(all(albedo >= 0 & albedo <= 1))
622!
  df_values = as.list(data.frame(
623!
    phi = phi,
624!
    theta = theta,
625!
    altitude = altitude,
626!
    elevation = elevation,
627!
    visibility = visibility,
628!
    albedo = albedo,
629!
    azimuth = azimuth
630
  ))
631!
  stopifnot(all(altitude >= 0 & altitude <= 15000))
632!
  coef_file = resolve_prague_coef_file(
633!
    altitude = altitude,
634!
    wide_spectrum = wide_spectrum
635
  )
636!
  vals = calculate_raw_prague(
637!
    df_values$phi,
638!
    df_values$theta,
639!
    df_values$elevation,
640!
    df_values$albedo,
641!
    df_values$altitude,
642!
    df_values$visibility,
643!
    df_values$azimuth,
644!
    number_cores,
645!
    coef_file,
646!
    render_mode
647
  )
648!
  colnames(vals) = c("r", "g", "b")
649!
  prague_rgb_correction = normalize_prague_rgb_correction(
650!
    prague_rgb_correction
651
  )
652
653!
  if (prague_rgb_correction == "constant") {
654!
    applied_prague_rgb_gain = prepare_prague_rgb_gain(
655!
      gain = prague_rgb_correction_gain,
656!
      strength = prague_rgb_correction_strength
657
    )
658
659!
    vals = apply_prague_rgb_gain(
660!
      vals,
661!
      gain = applied_prague_rgb_gain
662
    )
663
664!
    attr(vals, "prague_rgb_correction") = "constant"
665!
    attr(vals, "prague_rgb_correction_gain") = applied_prague_rgb_gain
666!
    attr(vals, "prague_rgb_correction_strength") =
667!
      prague_rgb_correction_strength
668
  }
669!
  return(vals)
670
}
671
672
#' Sample Prague sky radiance over directions and wavelengths
673
#'
674
#' @description Evaluate the Prague spectral sky model at arbitrary spherical
675
#'   directions and wavelengths, including grids of atmospheric conditions. Use
676
#'   `render_mode = "all"` for atmosphere + solar disk, `"atmosphere"` for
677
#'   atmospheric radiance only, or `"sun"` for the solar disk only.
678
#'
679
#' @param phi                Azimuthal angle of the sample, degrees. Vectorized. Range 0 to 360.
680
#' @param theta              Vertical angle of the sample, degrees. Vectorized. Range -90 to 90.
681
#' @param lambda_nm          Wavelength in nanometers. Vectorized. Must lie within the loaded Prague dataset range.
682
#' @param altitude           Default `0`. Vectorized altitude of the viewer in meters. Range 0 to 15000.
683
#' @param elevation          Default `10`. Vectorized solar elevation angle above/below the horizon (degrees). Range -4.2 to 90.
684
#' @param visibility         Default `50`. Vectorized meteorological range in kilometers. Range 20 to 131.8.
685
#' @param albedo             Default `0.5`. Vectorized ground albedo. Range 0 to 1.
686
#' @param azimuth            Default `90`. Vectorized solar azimuth (degrees). Defaults South.
687
#' @param number_cores       Default `1`. Number of CPU threads. Ignored with `backend = "gpu"`.
688
#' @param wide_spectrum      Default `FALSE`. Whether to use the wide-spectrum (55-channel, polarised) coefficients.
689
#' @param render_mode        Default `"all"`. One of `"all"`, `"atmosphere"`, or `"sun"`.
690
#'   Use `"all"` for atmosphere + solar disk, `"atmosphere"` for atmospheric radiance only, or `"sun"` for the solar disk only.
691
#' @param backend Default `"cpu"`. Use `"cpu"` for CPU evaluation or `"gpu"`
692
#'   for batch evaluation on a macOS Metal device.
693
#'
694
#' @return Numeric vector of spectral radiance values in W m^-2 sr^-1 nm^-1,
695
#'   in input row order.
696
#' @export
697
#' @details Inputs are paired element by element, with shorter vectors recycled
698
#'   by [data.frame()]. Use [expand.grid()] to form all combinations, then pass
699
#'   its columns as the corresponding arguments. The function does not create a
700
#'   Cartesian product automatically.
701
#'
702
#'   The GPU backend evaluates geometry, atmospheric radiance, and solar radiance
703
#'   using the same Prague coefficients as the CPU backend. It uses single
704
#'   precision, so results can differ slightly, especially near the solar limb.
705
#'   Coefficients and compiled shaders are cached across calls; changing datasets
706
#'   replaces the cached GPU coefficients. Large inputs are processed in bounded
707
#'   batches. The initial upload and shader compilation can outweigh the benefit
708
#'   for small inputs. An unavailable Metal device or a GPU failure raises an
709
#'   error; use `backend = "cpu"` to evaluate on the CPU.
710
#' @examplesIf interactive() || identical(Sys.getenv("IN_PKGDOWN"), "true")
711
#' # Compare the same direction and wavelength at two observer altitudes.
712
#' lambda_vals = calculate_sky_radiance(
713
#'   phi = c(90, 90),
714
#'   theta = c(45, 45),
715
#'   lambda_nm = 550,
716
#'   altitude = c(0, 10000),
717
#'   elevation = 20,
718
#'   visibility = 80,
719
#'   albedo = 0.1
720
#' )
721
#' cbind(altitude = c(0, 10000), radiance = lambda_vals)
722
#'
723
#' # Form a direction-by-wavelength grid and preserve its row ordering.
724
#' # On a Mac with Metal, add backend = "gpu" to evaluate the grid on the GPU.
725
#' grid = expand.grid(
726
#'   phi = seq(0, 350, by = 10),
727
#'   theta = seq(0, 90, by = 10),
728
#'   lambda_nm = seq(380, 740, by = 20)
729
#' )
730
#' grid$radiance = calculate_sky_radiance(
731
#'   phi = grid$phi,
732
#'   theta = grid$theta,
733
#'   lambda_nm = grid$lambda_nm,
734
#'   render_mode = "atmosphere"
735
#' )
736
calculate_sky_radiance = function(
737
  phi,
738
  theta,
739
  lambda_nm,
740
  altitude = 0,
741
  elevation = 10,
742
  visibility = 50,
743
  albedo = 0.5,
744
  azimuth = 90,
745
  number_cores = 1,
746
  wide_spectrum = FALSE,
747
  render_mode = "all",
748
  backend = "cpu"
749
) {
75011x
  backend = match.arg(backend, c("cpu", "gpu"))
75110x
  render_mode = normalize_render_mode(render_mode)
75210x
  inputs = list(
75310x
    phi = phi,
75410x
    theta = theta,
75510x
    lambda_nm = lambda_nm,
75610x
    altitude = altitude,
75710x
    elevation = elevation,
75810x
    visibility = visibility,
75910x
    albedo = albedo,
76010x
    azimuth = azimuth
761
  )
76210x
  for (name in names(inputs)) {
76345x
    if (!is.numeric(inputs[[name]]) || any(!is.finite(inputs[[name]]))) {
7649x
      stop(
7659x
        sprintf("`%s` must contain finite numeric values.", name),
7669x
        call. = FALSE
767
      )
768
    }
769
  }
7701x
  stopifnot(all(phi <= 360 & phi >= 0))
7711x
  stopifnot(all(theta <= 90 & theta >= -90))
7721x
  stopifnot(all(altitude <= 15000 & altitude >= 0))
7731x
  stopifnot(all(visibility >= 20 & visibility <= 131.8))
7741x
  stopifnot(all(albedo >= 0 & albedo <= 1))
7751x
  df_values = as.list(data.frame(
7761x
    phi = phi,
7771x
    theta = theta,
7781x
    lambda_nm = lambda_nm,
7791x
    altitude = altitude,
7801x
    elevation = elevation,
7811x
    visibility = visibility,
7821x
    albedo = albedo,
7831x
    azimuth = azimuth
784
  ))
785!
  coef_file = resolve_prague_coef_file(
786!
    altitude = altitude,
787!
    wide_spectrum = wide_spectrum
788
  )
789!
  calculate_raw_prague_radiance(
790!
    df_values$phi,
791!
    df_values$theta,
792!
    df_values$lambda_nm,
793!
    df_values$elevation,
794!
    df_values$albedo,
795!
    df_values$altitude,
796!
    df_values$visibility,
797!
    df_values$azimuth,
798!
    number_cores,
799!
    coef_file,
800!
    render_mode,
801!
    backend
802
  )
803
}
804
805
#' Sample sun luminance at the disk center.
806
#'
807
#' @description Evaluate the Prague or Hosek sky model at the sun center and
808
#' integrate against the CIE Y curve to return a luminance value. This is
809
#' useful for relative attenuation (e.g., comparing zenith sun to a low sun).
810
#'
811
#' @param elevation          Default `10`. Solar elevation angle above/below
812
#'   the horizon (degrees). Range `[-4.2, 90]` for Prague, `[0, 90]` for Hosek.
813
#' @param azimuth            Default `90`. Solar azimuth (degrees).
814
#' @param albedo             Default `0.5`. Ground albedo, range 0 to 1.
815
#' @param turbidity          Default `3`. Atmospheric turbidity, range 1.7 to 10
816
#'   (*Hosek only*).
817
#' @param altitude           Default `0`. Observer altitude (m), range 0 to 15000
818
#'   (*Prague only*).
819
#' @param visibility         Default `50`. Meteorological range (km); *Prague only*.
820
#' @param hosek              Default `TRUE`. `FALSE` selects the Prague model.
821
#' @param wide_spectrum      Default `FALSE`. Use wide-spectrum (55-channel)
822
#'   coefficients for Prague at sea level only.
823
#' @param lambda_nm          Optional vector of wavelengths for Hosek sampling.
824
#'
825
#' @return Numeric scalar of sun luminance (CIE Y, relative scale).
826
#' @export
827
#' @examples
828
#' calculate_sun_brightness(elevation = 45, hosek = TRUE)
829
calculate_sun_brightness = function(
830
  elevation = 10,
831
  azimuth = 90,
832
  albedo = 0.5,
833
  turbidity = 3,
834
  altitude = 0,
835
  visibility = 50,
836
  hosek = TRUE,
837
  wide_spectrum = FALSE,
838
  lambda_nm = NULL
839
) {
840!
  stopifnot(length(elevation) == 1)
841!
  stopifnot(length(azimuth) == 1)
842!
  stopifnot(length(albedo) == 1)
843!
  stopifnot(length(turbidity) == 1)
844!
  stopifnot(length(altitude) == 1)
845!
  stopifnot(length(visibility) == 1)
846!
  stopifnot(altitude >= 0)
847
848!
  model = if (hosek) "hosek" else "prague"
849!
  coef_file = ""
850
851!
  if (!hosek) {
852!
    coef_file = resolve_prague_coef_file(
853!
      altitude = altitude,
854!
      wide_spectrum = wide_spectrum
855
    )
856
  }
857
858!
  calculate_sun_brightness_rcpp(
859!
    albedo = albedo,
860!
    turbidity = turbidity,
861!
    elevation = elevation,
862!
    azimuth_deg = azimuth,
863!
    model = model,
864!
    prg_dataset = coef_file,
865!
    altitude = altitude,
866!
    visibility = visibility,
867!
    lambda_nm = if (hosek) lambda_nm else NULL
868
  )
869
}
1
prague_coef_cache_dir = function() {
25x
  tools::R_user_dir("skymodelr", "data")
3
}
4
5
prague_coef_info = function(
6
  sea_level = TRUE,
7
  wide_spectrum = FALSE,
8
  altitude = NULL
9
) {
106x
  if (!is.null(altitude)) {
116x
    sea_level = all(altitude == 0)
12
  }
136x
  if (wide_spectrum && !sea_level) {
14!
    stop(
15!
      "`wide_spectrum = TRUE` is only valid when `altitude == 0`.",
16!
      call. = FALSE
17
    )
18
  }
19
206x
  if (sea_level && wide_spectrum) {
21!
    list(
22!
      name = "PragueSkyModelDatasetGroundInfra.dat",
23!
      url = "https://skydata.tylermw.com/PragueSkyModelDatasetGroundInfra.dat",
24!
      md5 = "33b97729ce8cd7fbdfc60317ff2805e7",
25!
      size = "574MB",
26!
      sea_level = TRUE,
27!
      wide_spectrum = TRUE
28
    )
296x
  } else if (sea_level) {
304x
    list(
314x
      name = "SkyModelDatasetGround.dat",
324x
      url = "https://skydata.tylermw.com/SkyModelDatasetGround.dat",
334x
      md5 = "953864f62c9434269b7f909cdff6c7cd",
344x
      size = "107MB",
354x
      sea_level = TRUE,
364x
      wide_spectrum = FALSE
37
    )
38
  } else {
392x
    list(
402x
      name = "SkyModelDataset.dat",
412x
      url = "https://skydata.tylermw.com/SkyModelDataset.dat",
422x
      md5 = "dcfa2bd165cf803c1791c469e05d134c",
432x
      size = "2.4GB",
442x
      sea_level = FALSE,
452x
      wide_spectrum = FALSE
46
    )
47
  }
48
}
49
50
prague_download_call = function(info) {
516x
  sprintf(
526x
    "download_sky_data(sea_level = %s, wide_spectrum = %s)",
532x
    if (info$sea_level) "TRUE" else "FALSE",
54!
    if (info$wide_spectrum) "TRUE" else "FALSE"
55
  )
56
}
57
58
stop_missing_prague_coef = function(info, model = "Prague sky model") {
596x
  stop(
606x
    sprintf(
616x
      "The %s coefficient file '%s' is not installed. Run %s explicitly to download it.",
626x
      model,
636x
      info$name,
646x
      prague_download_call(info)
65
    ),
666x
    call. = FALSE
67
  )
68
}
69
70
resolve_prague_coef_file = function(
71
  altitude = 0,
72
  wide_spectrum = FALSE,
73
  allow_download = interactive(),
74
  model = "Prague sky model"
75
) {
766x
  info = prague_coef_info(altitude = altitude, wide_spectrum = wide_spectrum)
776x
  coef_file = file.path(prague_coef_cache_dir(), info$name)
786x
  if (file.exists(coef_file)) {
79!
    return(coef_file)
80
  }
81
826x
  if (!allow_download) {
836x
    stop_missing_prague_coef(info, model = model)
84
  }
85
86!
  answer = readline(
87!
    prompt = sprintf(
88!
      "Coefficient file '%s' for the %s is not installed. This is a large file (%s). Download now? [y/n] ",
89!
      info$name,
90!
      model,
91!
      info$size
92
    )
93
  )
94!
  answer = tolower(trimws(answer))
95
96!
  if (answer %in% c("y", "yes")) {
97!
    return(download_sky_data(
98!
      sea_level = info$sea_level,
99!
      wide_spectrum = info$wide_spectrum
100
    ))
101
  }
102!
  if (answer %in% c("n", "no")) {
103!
    stop_missing_prague_coef(info, model = model)
104
  }
105!
  stop("Input not recognized.", call. = FALSE)
106
}
1
.prague_rgb_correction_gain = c(
2
  R = 0.94438727,
3
  G = 1.02157200,
4
  B = 0.95012063
5
)
6
7
#' Normalize Prague RGB correction option
8
#'
9
#' @param prague_rgb_correction Prague RGB correction option.
10
#' @keywords internal
11
normalize_prague_rgb_correction = function(prague_rgb_correction) {
1247x
  if (is.logical(prague_rgb_correction)) {
1347x
    if (length(prague_rgb_correction) != 1L || is.na(prague_rgb_correction)) {
143x
      stop(
153x
        "prague_rgb_correction must be TRUE, FALSE, \"constant\", or \"none\".",
163x
        call. = FALSE
17
      )
18
    }
19
20!
    return(if (isTRUE(prague_rgb_correction)) "constant" else "none")
21
  }
22
23!
  prague_rgb_correction = tolower(as.character(prague_rgb_correction))
24!
  match.arg(prague_rgb_correction, c("none", "constant"))
25
}
26
27
#' Validate Prague RGB correction gain
28
#'
29
#' @param gain RGB correction gain.
30
#' @keywords internal
31
validate_prague_rgb_gain = function(gain) {
3249x
  if (!is.numeric(gain) || length(gain) != 3L) {
331x
    stop(
341x
      "prague_rgb_correction_gain must be a numeric vector of length 3.",
351x
      call. = FALSE
36
    )
37
  }
38
3948x
  if (is.null(names(gain))) {
404x
    names(gain) = c("R", "G", "B")
41
  }
42
4348x
  if (!all(c("R", "G", "B") %in% names(gain))) {
44!
    stop(
45!
      "prague_rgb_correction_gain must have names R, G, and B.",
46!
      call. = FALSE
47
    )
48
  }
49
5048x
  gain = gain[c("R", "G", "B")]
51
5248x
  if (any(!is.finite(gain)) || any(gain <= 0)) {
533x
    stop(
543x
      "prague_rgb_correction_gain values must be finite and positive.",
553x
      call. = FALSE
56
    )
57
  }
58
5945x
  gain
60
}
61
62
#' Prepare Prague RGB correction gain
63
#'
64
#' @param gain Default `"auto"`. RGB correction gain.
65
#' @param strength Default `1`. Correction strength.
66
#' @keywords internal
67
prepare_prague_rgb_gain = function(
68
  gain = "auto",
69
  strength = 1
70
) {
7148x
  if (identical(gain, "auto")) {
7242x
    gain = .prague_rgb_correction_gain
73
  }
74
7548x
  gain = validate_prague_rgb_gain(gain)
76
77
  if (
7844x
    !is.numeric(strength) ||
7944x
      length(strength) != 1L ||
8044x
      !is.finite(strength) ||
8144x
      strength < 0
82
  ) {
8311x
    stop(
8411x
      "prague_rgb_correction_strength must be a finite non-negative scalar.",
8511x
      call. = FALSE
86
    )
87
  }
88
8933x
  exp(log(gain) * strength)
90
}
91
92
#' Apply Prague RGB correction gain
93
#'
94
#' @param x RGB array or matrix.
95
#' @param gain RGB correction gain.
96
#' @keywords internal
97
apply_prague_rgb_gain = function(x, gain) {
981x
  gain = validate_prague_rgb_gain(gain)
99
1001x
  out = x
1011x
  d = dim(out)
102
1031x
  if (length(d) == 3L) {
104!
    if (d[3] < 3L) {
105!
      stop("RGB array must have at least 3 channels.", call. = FALSE)
106
    }
107
108!
    out[,, 1] = out[,, 1] * gain[["R"]]
109!
    out[,, 2] = out[,, 2] * gain[["G"]]
110!
    out[,, 3] = out[,, 3] * gain[["B"]]
111!
    return(out)
112
  }
113
1141x
  if (is.matrix(out)) {
1151x
    if (ncol(out) < 3L) {
116!
      stop("RGB matrix must have at least 3 columns.", call. = FALSE)
117
    }
118
1191x
    out[, 1] = out[, 1] * gain[["R"]]
1201x
    out[, 2] = out[, 2] * gain[["G"]]
1211x
    out[, 3] = out[, 3] * gain[["B"]]
1221x
    return(out)
123
  }
124
125!
  stop("Expected an RGB array or RGB matrix.", call. = FALSE)
126
}
1
#' Normalize a vector to unit length
2
#'
3
#' @description Scale a numeric vector so it has unit Euclidean length.
4
#' @param v Numeric vector to normalise.
5
#' @keywords internal
6
normalize = function(v) {
7103x
  s = sqrt(sum(v * v))
8103x
  if (s == 0) {
9!
    stop("Zero-length vector")
10
  }
11103x
  return(v / s)
12
}
13
14
#' Convert altitude/azimuth to ENU
15
#'
16
#' @description Map altitude/azimuth angles (north-referenced) to a unit
17
#' East-North-Up direction vector.
18
#' @param alt_rad Altitude in radians.
19
#' @param azN_rad Azimuth in radians measured from north.
20
#' @keywords internal
21
altaz_to_enu = function(alt_rad, azN_rad) {
22100x
  east = sin(azN_rad) * cos(alt_rad)
23100x
  north = cos(azN_rad) * cos(alt_rad)
24100x
  up = sin(alt_rad)
25100x
  normalize(c(east, north, up)) # (E, N, U) matches engine XYZ
26
}
27
28
29
#' Moon V-band magnitude from phase angle
30
#'
31
#' @param phase_deg Phase angle psi in degrees (0 = full Moon, 180 = new).
32
#' @param dist_km   Default `384400`. Current geocentric distance (km).
33
#' @param mean_km   Default `384400`. Mean distance (km).
34
#' @keywords internal
35
#'
36
#' @return Apparent V magnitude `m`.
37
moon_mag = function(
38
  phase_deg,
39
  dist_km = 384400,
40
  mean_km = 384400
41
) {
42
  # Allen-1976 magnitude for a disc at mean distance, no surge (phase_deg in degrees):
4325x
  m0 = -12.73 + 0.026 * abs(phase_deg) + 4e-9 * phase_deg^4
44
45
  # Geometry: inverse-square scaling with distance
4625x
  geom = 5 * log10(dist_km / mean_km)
47
48
  # Opposition surge term (Allen's "extra" brightness near full Moon)
4925x
  S = max(1, 1.35 - 0.05 * abs(phase_deg)) # Allen's empirical fit
5025x
  surge_corr = -2.5 * log10(S)
51
5225x
  m = m0 + geom + surge_corr
5325x
  return(m)
54
}
55
56
57
# Krisciunas & Schaefer (1991) / Rozenberg (1966) airmass approximation:
58
# X(Z) = [cos(Z) + 0.025 * exp(-11 * cos(Z))]^(-1)
59
# where Z is zenith distance in radians; bounded to ~40 at the horizon.
60
airmass_rozenberg1966 = function(zenith_deg) {
6161x
  z = zenith_deg * pi / 180
6261x
  c = cos(z)
6361x
  1 / (c + 0.025 * exp(-11 * c))
64
}
65
66
#' @keywords internal
67
apply_airmass_extinction = function(
68
  lux_top_atm,
69
  alt_deg,
70
  kV = 0.172,
71
  clip_horizon = FALSE
72
) {
73
  if (
7464x
    !is.finite(lux_top_atm) ||
7564x
      !is.finite(alt_deg) ||
7664x
      (clip_horizon && alt_deg <= 0)
77
  ) {
783x
    return(0)
79
  }
80
81
  # Disk consumers clip individual directions. Continue the finite horizon
82
  # value below zero instead of switching off an extended source at its center.
83
  # Rozenberg is only defined over the upper hemisphere.
8461x
  alt_deg = max(0, min(alt_deg, 90))
8561x
  zenith_deg = 90 - alt_deg
86
8761x
  X = airmass_rozenberg1966(zenith_deg)
8861x
  lux_top_atm * 10^(-0.4 * kV * X)
89
}
90
91
#' Compute topocentric moon/sun directions
92
#'
93
#' @description Query Swiss Ephemeris for topocentric sun and moon direction
94
#' vectors and magnitudes for a given observer location.
95
#' @param datetime POSIXct observation time (UTC).
96
#' @param lat Latitude in degrees.
97
#' @param lon Longitude in degrees.
98
#' @param elev_m Observer elevation above sea level in metres.
99
#' @param moon_extinction_kV Default `0.172`. V-band atmospheric extinction
100
#'   coefficient used in the Rozenberg/Krisciunas-Schaefer airmass attenuation
101
#'   model for moonlight.
102
#' @keywords internal
103
swe_dirs_topo_moon_sun = function(
104
  datetime,
105
  lat,
106
  lon,
107
  elev_m = 0,
108
  moon_extinction_kV = 0.172
109
) {
11025x
  swephR::swe_set_topo(lon, lat, elev_m)
11125x
  attr(datetime, "tzone") = "UTC"
11225x
  ts = as.POSIXlt(datetime, tz = "UTC")
11325x
  jd_ut = swephR::swe_utc_to_jd(
11425x
    ts$year + 1900,
11525x
    ts$mon + 1,
11625x
    ts$mday,
11725x
    ts$hour,
11825x
    ts$min,
11925x
    ts$sec,
12025x
    swephR::SE$GREG_CAL
12125x
  )$dret[2] # Swiss Ephemeris returns TT first, then UT1.
122
12325x
  flg_eq_topo = swephR::SE$FLG_SWIEPH +
12425x
    swephR::SE$FLG_EQUATORIAL +
12525x
    swephR::SE$FLG_TOPOCTR
12625x
  long_rad = lon * pi / 180
12725x
  lat_rad = lat * pi / 180
128
12925x
  enu_to_ecef = matrix(
13025x
    c(
13125x
      -sin(long_rad),
13225x
      cos(long_rad),
13325x
      0,
13425x
      -sin(lat_rad) * cos(long_rad),
13525x
      -sin(lat_rad) * sin(long_rad),
13625x
      cos(lat_rad),
13725x
      cos(lat_rad) * cos(long_rad),
13825x
      cos(lat_rad) * sin(long_rad),
13925x
      sin(lat_rad)
140
    ),
14125x
    ncol = 3,
14225x
    nrow = 3,
14325x
    byrow = TRUE
144
  )
14525x
  sun_t = swephR::swe_calc_ut(jd_ut, swephR::SE$SUN, flg_eq_topo)$xx
14625x
  moon_t = swephR::swe_calc_ut(jd_ut, swephR::SE$MOON, flg_eq_topo)$xx
14725x
  moon_size = swephR::swe_pheno_ut(jd_ut, swephR::SE$MOON, flg_eq_topo)$attr
14825x
  sun_size = swephR::swe_pheno_ut(jd_ut, swephR::SE$SUN, flg_eq_topo)$attr
149
15025x
  dist_au = moon_t[3]
15125x
  moon_distance_km = dist_au * 149597870.7
152
15325x
  moon_phase = moon_size[1]
15425x
  moon_diameter_degrees = moon_size[4]
15525x
  moon_brightness_magnitude = moon_size[5]
156
15725x
  m = moon_mag(
15825x
    moon_phase,
15925x
    dist_km = moon_distance_km,
16025x
    mean_km = 384400
161
  )
162
16325x
  ftcnds_to_lux = 10.76
16425x
  moon_brightness_lux_raw = ftcnds_to_lux * 10^(-0.4 * (m + 16.57))
165
16625x
  sun_diameter_degrees = sun_size[4]
16725x
  sun_brightness_magnitude = sun_size[5]
16825x
  sun_brightness_lux = ftcnds_to_lux *
16925x
    10^(-0.4 * (sun_brightness_magnitude + 16.57))
170
17125x
  to_local_horizontal_coordinates = function(ra_dec) {
17250x
    aa = swephR::swe_azalt(
17350x
      jd_ut,
17450x
      swephR::SE$EQU2HOR,
17550x
      c(lon, lat, elev_m),
17650x
      0,
17750x
      0,
17850x
      xin = c(ra_dec[1], ra_dec[2], 1)
17950x
    )$xaz
18050x
    aa
181
  }
18225x
  to_rad = pi / 180
183
18425x
  local_horizon_sun = to_local_horizontal_coordinates(sun_t) * to_rad
18525x
  local_horizon_moon = to_local_horizontal_coordinates(moon_t) * to_rad
186
18725x
  azN_s = local_horizon_sun[1]
18825x
  alt_s = local_horizon_sun[2]
18925x
  azN_mt = local_horizon_moon[1]
19025x
  alt_mt = local_horizon_moon[2]
191
19225x
  moon_elev_deg = alt_mt * 180 / pi
19325x
  moon_brightness_lux = apply_airmass_extinction(
19425x
    lux_top_atm = moon_brightness_lux_raw,
19525x
    alt_deg = moon_elev_deg,
19625x
    kV = moon_extinction_kV
197
  )
198
19925x
  list(
20025x
    sun_dir_topo = altaz_to_enu(alt_s, azN_s),
20125x
    sun_ecef_geo = enu_to_ecef %*% altaz_to_enu(alt_s, azN_s),
20225x
    moon_dir_topo = altaz_to_enu(alt_mt, azN_mt),
20325x
    moon_ecef_geo = enu_to_ecef %*% altaz_to_enu(alt_mt, azN_mt),
20425x
    local_up_geo = enu_to_ecef %*% c(0, 0, 1),
20525x
    moon_diameter_degrees = moon_diameter_degrees,
20625x
    moon_brightness_magnitude = moon_brightness_magnitude,
20725x
    moon_brightness_lux = moon_brightness_lux, #lux for the complete attenuated disk
20825x
    moon_brightness_lux_unattenuated = moon_brightness_lux_raw, #lux, before atmospheric attenuation
20925x
    moon_phase = moon_phase,
21025x
    sun_diameter_degrees = sun_diameter_degrees,
21125x
    sun_brightness_magnitude = sun_brightness_magnitude,
21225x
    sun_brightness_lux = sun_brightness_lux #lux
213
  ) |>
21425x
    lapply(as.numeric)
215
}
216
217
218
#' Convert Swiss ephemeris data to a starfield frame
219
#'
220
#' @description Build a data frame compatible with `make_starfield_rcpp()` from
221
#' Swiss Ephemeris results.
222
#' @param sweph_info List of planetary info objects.
223
#' @keywords internal
224
sweph_info_to_stars_df = function(sweph_info) {
2252x
  sweph_info_df = do.call(rbind, lapply(sweph_info, as.data.frame))
2262x
  planets = rownames(sweph_info_df)
2272x
  data.frame(
2282x
    planet = planets,
2292x
    ra_rad = sweph_info_df$ra_rad,
2302x
    dec_rad = sweph_info_df$dec_rad,
2312x
    ra_deg = sweph_info_df$ra_rad * 180 / pi,
2322x
    dec_deg = sweph_info_df$dec_rad * 180 / pi,
2332x
    v_mag = sweph_info_df$v_mag,
2342x
    r = 1,
2352x
    g = 1,
2362x
    b = 1
237
  )
238
}
239
240
#' Compute sun/moon positions via Swiss Ephemeris
241
#'
242
#' @description Produce a data frame of apparent positions and
243
#' magnitudes for the observer.
244
#' @param datetime POSIXct observation time (UTC).
245
#' @param lat Latitude in degrees.
246
#' @param lon Longitude in degrees.
247
#' @param elev_m Observer elevation above sea level in metres.
248
#' @keywords internal
249
swe_dirs_topo_sunmoon_df = function(datetime, lat, lon, elev_m = 0) {
2501x
  swephR::swe_set_topo(lon, lat, elev_m)
2511x
  attr(datetime, "tzone") = "UTC"
2521x
  ts = as.POSIXlt(datetime, tz = "UTC")
2531x
  jd_ut = swephR::swe_utc_to_jd(
2541x
    ts$year + 1900,
2551x
    ts$mon + 1,
2561x
    ts$mday,
2571x
    ts$hour,
2581x
    ts$min,
2591x
    ts$sec,
2601x
    swephR::SE$GREG_CAL
2611x
  )$dret[2] # Swiss Ephemeris returns TT first, then UT1.
262
2631x
  flg_eq_topo = swephR::SE$FLG_SWIEPH +
2641x
    swephR::SE$FLG_EQUATORIAL +
2651x
    swephR::SE$FLG_TOPOCTR
266
2671x
  to_rad = pi / 180
2681x
  get_enu_magnitude = function(planet_flag) {
2692x
    position_rad = swephR::swe_calc_ut(jd_ut, planet_flag, flg_eq_topo)$xx *
2702x
      to_rad
2712x
    info = swephR::swe_pheno_ut(jd_ut, planet_flag, flg_eq_topo)$attr
2722x
    list(ra_rad = position_rad[1], dec_rad = position_rad[2], v_mag = info[5])
273
  }
2741x
  info = list(
2751x
    sun = get_enu_magnitude(swephR::SE$SUN),
2761x
    moon = get_enu_magnitude(swephR::SE$MOON)
277
  )
2781x
  return(sweph_info_to_stars_df(info))
279
}
280
281
#' Compute bright-planet positions via Swiss Ephemeris
282
#'
283
#' @description Produce a data frame of planetary apparent positions and
284
#' magnitudes for the observer.
285
#' @param datetime POSIXct observation time (UTC).
286
#' @param lat Latitude in degrees.
287
#' @param lon Longitude in degrees.
288
#' @param elev_m Observer elevation above sea level in metres.
289
#' @keywords internal
290
swe_dirs_topo_planets_df = function(datetime, lat, lon, elev_m = 0) {
2911x
  swephR::swe_set_topo(lon, lat, elev_m)
2921x
  attr(datetime, "tzone") = "UTC"
2931x
  ts = as.POSIXlt(datetime, tz = "UTC")
2941x
  jd_ut = swephR::swe_utc_to_jd(
2951x
    ts$year + 1900,
2961x
    ts$mon + 1,
2971x
    ts$mday,
2981x
    ts$hour,
2991x
    ts$min,
3001x
    ts$sec,
3011x
    swephR::SE$GREG_CAL
3021x
  )$dret[2] # Swiss Ephemeris returns TT first, then UT1.
303
3041x
  flg_eq_topo = swephR::SE$FLG_SWIEPH +
3051x
    swephR::SE$FLG_EQUATORIAL +
3061x
    swephR::SE$FLG_TOPOCTR
307
3081x
  to_rad = pi / 180
3091x
  get_enu_magnitude = function(planet_flag) {
3107x
    position_rad = swephR::swe_calc_ut(jd_ut, planet_flag, flg_eq_topo)$xx *
3117x
      to_rad
3127x
    info = swephR::swe_pheno_ut(jd_ut, planet_flag, flg_eq_topo)$attr
3137x
    list(ra_rad = position_rad[1], dec_rad = position_rad[2], v_mag = info[5])
314
  }
3151x
  planet_info = list(
3161x
    mercury = get_enu_magnitude(swephR::SE$MERCURY),
3171x
    venus = get_enu_magnitude(swephR::SE$VENUS),
3181x
    mars = get_enu_magnitude(swephR::SE$MARS),
3191x
    jupiter = get_enu_magnitude(swephR::SE$JUPITER),
3201x
    saturn = get_enu_magnitude(swephR::SE$SATURN),
3211x
    uranus = get_enu_magnitude(swephR::SE$URANUS),
3221x
    neptune = get_enu_magnitude(swephR::SE$NEPTUNE)
323
  )
3241x
  return(sweph_info_to_stars_df(planet_info))
325
}
326
327
328
#' Generate the moon into a lat-long image array patch
329
#'
330
#' @description Produce a rasterised moon texture aligned for composition into
331
#' the sky dome. The Earth phase is inferred from the Sun-Moon geometry, and earthshine is
332
#' implemented as an emissive term scaled relative to solar irradiance.
333
#'
334
#' @param datetime POSIXct observation time (UTC).
335
#' @param lat Latitude in degrees.
336
#' @param lon Longitude in degrees.
337
#' @param elev_m Observer elevation above sea level in metres.
338
#' @param width Output width in pixels.
339
#' @param height Output height in pixels.
340
#' @param earthshine Default `TRUE`. If `FALSE`, skip the earthshine emissive term.
341
#' @param earthshine_albedo Default `0.19`. Effective Earth albedo term used
342
#'   in the earthshine irradiance approximation.
343
#' @param solar_irradiance_w_m2 Default `1300`. Reference solar irradiance at
344
#'   1 AU (W/m^2) used to normalize earthshine emission intensity.
345
#' @param moon_extinction_kV Default `0.172`. V-band atmospheric extinction
346
#'   coefficient for direct moonlight attenuation.
347
#' @param verbose Default `FALSE`. If `TRUE`, print earthshine diagnostics.
348
#' @keywords internal
349
generate_moon_image_latlong = function(
350
  datetime,
351
  lat,
352
  lon,
353
  elev_m = 0,
354
  width = 800,
355
  height = 800,
356
  earthshine = TRUE,
357
  earthshine_albedo = 0.19,
358
  solar_irradiance_w_m2 = 1300,
359
  moon_extinction_kV = 0.172,
360
  verbose = FALSE
361
) {
3621x
  moon_sun_data = swe_dirs_topo_moon_sun(
3631x
    datetime = datetime,
3641x
    lat = lat,
3651x
    lon = lon,
3661x
    elev_m = elev_m,
3671x
    moon_extinction_kV = moon_extinction_kV
368
  )
3691x
  dir_moon = normalize(moon_sun_data$moon_ecef_geo)
3701x
  dir_sun = -normalize(moon_sun_data$sun_ecef_geo)
3711x
  local_up = normalize(moon_sun_data$local_up_geo)
372
3731x
  tex = get_moon_texture()
374
3751x
  cot = function(x) {
3761x
    1 / tan(x)
377
  }
378
3791x
  cos_phi = clamp_value(sum(dir_moon * dir_sun), -1, 1)
3801x
  phi = acos(cos_phi)
381
3821x
  earth_phase = pi - phi
3831x
  earth_phase = clamp_value(earth_phase, 1e-6, pi - 1e-6)
384
385
  # Paper-based earthshine irradiance model:
386
  # E_em = A_e * 0.5 * [1 - sin(phase/2) * tan(phase/2) * ln(cot(phase/4))]
3871x
  E_em = earthshine_albedo *
3881x
    0.5 *
3891x
    (1 -
3901x
      sin(earth_phase / 2) *
3911x
        tan(earth_phase / 2) *
3921x
        log(cot(earth_phase / 4)))
393
3941x
  if (!is.finite(E_em) || E_em < 0) {
395!
    E_em = 0
396
  }
397
3981x
  earth_emissive_intensity = 0
399
  if (
4001x
    earthshine && is.finite(solar_irradiance_w_m2) && solar_irradiance_w_m2 > 0
401
  ) {
4021x
    earth_emissive_intensity = E_em / solar_irradiance_w_m2
403
  }
404
405
  # Build a base mesh transform for the moon pass
4061x
  build_moon_mesh = function(material) {
4071x
    rayvertex::sphere_mesh(material = material, radius = 0.5) |>
4081x
      rayvertex::subdivide_mesh() |>
4091x
      rayvertex::rotate_mesh(c(0, -90, 6.68), order_rotation = c(3, 1, 2)) |>
4101x
      rayvertex::transform_mesh(rayvertex::lookat_transform(
4111x
        pos = -dir_moon,
4121x
        look = c(0, 0, 0),
4131x
        up = c(0, 0, 1)
414
      )) |>
4151x
      rayvertex::translate_mesh(dir_moon * 10)
416
  }
417
418
  # Combined sun + earthshine using emissive intensity
4191x
  moon_material = rayvertex::material_list(
4201x
    texture_location = tex,
4211x
    emissive_texture_location = tex,
4221x
    diffuse = c(1, 1, 1),
4231x
    emission = c(1, 1, 1),
4241x
    diffuse_intensity = 1,
4251x
    emission_intensity = earth_emissive_intensity,
4261x
    sigma = 10
427
  )
428
4291x
  moon_mesh = build_moon_mesh(moon_material)
430
4311x
  moon_image = rayvertex::rasterize_scene(
4321x
    moon_mesh,
4331x
    lookfrom = c(0, 0, 0),
4341x
    lookat = dir_moon * 10,
4351x
    camera_up = local_up,
4361x
    fov = 0,
4371x
    ortho_dimensions = c(2, 2), # Keep edge effects away from the visible disk
4381x
    light_info = rayvertex::directional_light(
4391x
      direction = -dir_sun,
4401x
      intensity = 1
441
    ),
4421x
    transparent_background = TRUE,
4431x
    plot = FALSE,
4441x
    width = width,
4451x
    height = height
446
  )
447
4481x
  if (verbose) {
449!
    message(sprintf(
450!
      "phi=%0.4f, earth_phase=%0.4f, E_em=%0.4g W/m^2, emission_intensity=%0.4g",
451!
      phi,
452!
      earth_phase,
453!
      E_em,
454!
      earth_emissive_intensity
455
    ))
456
  }
457
4581x
  moon_image[,, 4][moon_image[,, 4] > 1] = 1
459
4601x
  list(
4611x
    moon_luminance_array = moon_image,
4621x
    moon_angular_diameter_deg = moon_sun_data$moon_diameter_degrees
463
  )
464
}
1
#' Attach skymodelr RGB color metadata
2
#'
3
#' @param image Image array or rayimage image.
4
#' @keywords internal
5
as_sky_image = function(image) {
635x
  l_band = attr(image, "L_band", exact = TRUE)
735x
  exr_metadata = attr(image, "exr", exact = TRUE)
835x
  colorspace = attr(image, "colorspace", exact = TRUE)
935x
  white_current = attr(image, "white_current", exact = TRUE)
1035x
  prague_rgb_correction = attr(image, "prague_rgb_correction", exact = TRUE)
1135x
  prague_rgb_correction_gain = attr(
1235x
    image,
1335x
    "prague_rgb_correction_gain",
1435x
    exact = TRUE
15
  )
1635x
  prague_rgb_correction_strength = attr(
1735x
    image,
1835x
    "prague_rgb_correction_strength",
1935x
    exact = TRUE
20
  )
2135x
  image = rayimage::ray_read_image(
2235x
    image,
2335x
    normalize = FALSE,
2435x
    assume_white = if (is.null(white_current)) "D65" else white_current,
2535x
    assume_colorspace = rayimage::CS_SRGB
26
  )
2735x
  if (!is.null(l_band)) {
2819x
    attr(image, "L_band") = l_band
29
  }
3035x
  if (!is.null(colorspace)) {
316x
    attr(image, "colorspace") = colorspace
32
  }
3335x
  if (!is.null(white_current)) {
346x
    attr(image, "white_current") = white_current
35
  }
3635x
  if (!is.null(prague_rgb_correction)) {
37!
    attr(image, "prague_rgb_correction") = prague_rgb_correction
38
  }
3935x
  if (!is.null(prague_rgb_correction_gain)) {
40!
    attr(image, "prague_rgb_correction_gain") = prague_rgb_correction_gain
41
  }
4235x
  if (!is.null(prague_rgb_correction_strength)) {
43!
    attr(image, "prague_rgb_correction_strength") =
44!
      prague_rgb_correction_strength
45
  }
4635x
  if (!is.list(exr_metadata)) {
4729x
    exr_metadata = list()
48
  }
4935x
  attr(image, "exr") = utils::modifyList(
5035x
    exr_metadata,
5135x
    list(envmap = "latlong")
52
  )
5335x
  image
54
}
55
56
.skymodelr_d60_xy = c(0.32168, 0.33767)
57
58
.skymodelr_exr_rgb_encoding_label =
59
  "linear sRGB / Rec.709, D65 chromaticities"
60
.skymodelr_exr_adopted_neutral_label = "D60"
61
62
#' Convert xy chromaticity to XYZ with Y equal to 1
63
#'
64
#' @param xy Finite xy chromaticity vector.
65
#' @keywords internal
66
xy_to_xyz_y1 = function(xy) {
6735x
  if (!is.numeric(xy) || length(xy) != 2L || any(!is.finite(xy))) {
68!
    stop("xy must be a finite numeric vector of length 2.", call. = FALSE)
69
  }
70
7135x
  x = xy[1]
7235x
  y = xy[2]
73
7435x
  if (y <= 0) {
75!
    stop("xy y-coordinate must be positive.", call. = FALSE)
76
  }
77
7835x
  c(X = x / y, Y = 1, Z = (1 - x - y) / y)
79
}
80
81
#' Get skymodelr EXR adopted white
82
#'
83
#' @param exr_adopted_white Adopted white name or XYZ vector.
84
#' @keywords internal
85
get_skymodelr_adopted_white = function(exr_adopted_white) {
8616x
  if (is.character(exr_adopted_white) && length(exr_adopted_white) == 1L) {
8716x
    white_name = toupper(exr_adopted_white)
88
8916x
    if (white_name == "D60") {
9016x
      return(list(
9116x
        name = "D60",
9216x
        xy = .skymodelr_d60_xy,
9316x
        xyz = xy_to_xyz_y1(.skymodelr_d60_xy)
94
      ))
95
    }
96
97!
    if (white_name == "D65") {
98!
      xy = c(0.3127, 0.3290)
99!
      return(list(
100!
        name = "D65",
101!
        xy = xy,
102!
        xyz = xy_to_xyz_y1(xy)
103
      ))
104
    }
105
106!
    stop(
107!
      "exr_adopted_white must be \"D60\", \"D65\", or numeric XYZ with Y = 1.",
108!
      call. = FALSE
109
    )
110
  }
111
112!
  if (is.numeric(exr_adopted_white) && length(exr_adopted_white) == 3L) {
113!
    if (any(!is.finite(exr_adopted_white)) || exr_adopted_white[2] <= 0) {
114!
      stop(
115!
        "Numeric exr_adopted_white must be finite XYZ with positive Y.",
116!
        call. = FALSE
117
      )
118
    }
119
120!
    xyz = as.numeric(exr_adopted_white)
121!
    xyz = xyz / xyz[2]
122!
    sum_xyz = sum(xyz)
123
124!
    if (!is.finite(sum_xyz) || sum_xyz <= 0) {
125!
      stop(
126!
        "Numeric exr_adopted_white must have positive XYZ sum.",
127!
        call. = FALSE
128
      )
129
    }
130
131!
    xy = c(xyz[1] / sum_xyz, xyz[2] / sum_xyz)
132
133!
    return(list(
134!
      name = "custom",
135!
      xy = xy,
136!
      xyz = xyz
137
    ))
138
  }
139
140!
  stop(
141!
    "exr_adopted_white must be \"D60\", \"D65\", or numeric XYZ with Y = 1.",
142!
    call. = FALSE
143
  )
144
}
145
146
#' Tag skymodelr EXR metadata
147
#'
148
#' @param sky Sky image array.
149
#' @param adopted_white_xy Default `.skymodelr_d60_xy`. Adopted white xy.
150
#' @param adopted_white_name Default `.skymodelr_exr_adopted_neutral_label`.
151
#'   Adopted white name.
152
#' @param rgb_colorspace Default `rayimage::CS_SRGB`. RGB colorspace.
153
#' @param model_name Default `NULL`. Sky model name.
154
#' @param prague_rgb_correction Default `NULL`. Prague RGB correction label.
155
#' @keywords internal
156
tag_skymodelr_exr_metadata = function(
157
  sky,
158
  adopted_white_xy = .skymodelr_d60_xy,
159
  adopted_white_name = .skymodelr_exr_adopted_neutral_label,
160
  rgb_colorspace = rayimage::CS_SRGB,
161
  model_name = NULL,
162
  prague_rgb_correction = NULL
163
) {
16419x
  l_band = attr(sky, "L_band", exact = TRUE)
16519x
  exr = attr(sky, "exr", exact = TRUE)
16619x
  prague_rgb_correction_attr = attr(
16719x
    sky,
16819x
    "prague_rgb_correction",
16919x
    exact = TRUE
170
  )
17119x
  prague_rgb_correction_gain = attr(
17219x
    sky,
17319x
    "prague_rgb_correction_gain",
17419x
    exact = TRUE
175
  )
17619x
  prague_rgb_correction_strength = attr(
17719x
    sky,
17819x
    "prague_rgb_correction_strength",
17919x
    exact = TRUE
180
  )
181
18219x
  out = rayimage::ray_read_image(
18319x
    sky,
18419x
    normalize = FALSE,
18519x
    assume_colorspace = rgb_colorspace,
18619x
    assume_white = xy_to_xyz_y1(adopted_white_xy)
187
  )
188
18919x
  if (!is.null(l_band)) {
19014x
    attr(out, "L_band") = l_band
191
  }
19219x
  if (!is.null(prague_rgb_correction_attr)) {
193!
    attr(out, "prague_rgb_correction") = prague_rgb_correction_attr
194
  }
19519x
  if (!is.null(prague_rgb_correction_gain)) {
196!
    attr(out, "prague_rgb_correction_gain") = prague_rgb_correction_gain
197
  }
19819x
  if (!is.null(prague_rgb_correction_strength)) {
199!
    attr(out, "prague_rgb_correction_strength") =
200!
      prague_rgb_correction_strength
201
  }
202
20319x
  if (!is.list(exr)) {
2043x
    exr = list()
205
  }
206
20719x
  exr$skymodelr_rgb_encoding = .skymodelr_exr_rgb_encoding_label
20819x
  exr$skymodelr_adopted_neutral = adopted_white_name
20919x
  exr$skymodelr_adopted_neutral_xy = sprintf(
21019x
    "%.8f %.8f",
21119x
    adopted_white_xy[1],
21219x
    adopted_white_xy[2]
213
  )
214
21519x
  if (!is.null(model_name)) {
21616x
    exr$skymodelr_model = as.character(model_name)
217
  }
218
21919x
  if (!is.null(prague_rgb_correction)) {
220!
    exr$skymodelr_prague_rgb_correction =
221!
      as.character(prague_rgb_correction)
222
  }
223
22419x
  attr(out, "exr") = exr
225
22619x
  if (inherits(sky, "sky_image") && !inherits(out, "sky_image")) {
227!
    class(out) = unique(c("sky_image", class(out)))
228
  }
229
23019x
  out
231
}
232
233
#' Tag generated sky EXR metadata
234
#'
235
#' @param sky Sky image array.
236
#' @param hosek Whether the Hosek-Wilkie model was used.
237
#' @param exr_metadata Whether to attach skymodelr EXR metadata.
238
#' @param exr_adopted_white Adopted white name or XYZ vector.
239
#' @keywords internal
240
tag_generated_sky_exr_metadata = function(
241
  sky,
242
  hosek,
243
  exr_metadata,
244
  exr_adopted_white
245
) {
24618x
  if (!isTRUE(exr_metadata)) {
2472x
    return(sky)
248
  }
249
25016x
  adopted_white = get_skymodelr_adopted_white(exr_adopted_white)
251
25216x
  model_name = if (isTRUE(hosek)) {
25316x
    "Hosek-Wilkie"
254
  } else {
255!
    "Prague"
256
  }
257
25816x
  prague_correction_label = NULL
259
26016x
  if (!isTRUE(hosek)) {
261!
    prague_correction_label = attr(
262!
      sky,
263!
      "prague_rgb_correction",
264!
      exact = TRUE
265
    )
266
267!
    if (is.null(prague_correction_label)) {
268!
      prague_correction_label = "none"
269
    }
270
  }
271
27216x
  tag_skymodelr_exr_metadata(
27316x
    sky,
27416x
    adopted_white_xy = adopted_white$xy,
27516x
    adopted_white_name = adopted_white$name,
27616x
    rgb_colorspace = rayimage::CS_SRGB,
27716x
    model_name = model_name,
27816x
    prague_rgb_correction = prague_correction_label
279
  )
280
}
281
282
#' Build EXR metadata for skymodelr RGB output
283
#'
284
#' @param image Default `NULL`. Image to read colorspace and white metadata from.
285
#' @keywords internal
286
sky_exr_metadata = function(image = NULL) {
2876x
  colorspace = attr(image, "colorspace", exact = TRUE)
2886x
  white_current = attr(image, "white_current", exact = TRUE)
2896x
  exr_metadata = attr(image, "exr", exact = TRUE)
290
2916x
  if (is.null(colorspace)) {
292!
    colorspace = rayimage::CS_SRGB
293
  }
2946x
  if (is.null(white_current)) {
295!
    white_current = colorspace$white_xyz
296
  }
2976x
  if (!is.list(exr_metadata)) {
298!
    exr_metadata = list()
299
  }
300
3016x
  colorspace_white_xyz = colorspace$white_xyz
3026x
  colorspace_white_xy = unname(c(
3036x
    colorspace_white_xyz[1] / sum(colorspace_white_xyz),
3046x
    colorspace_white_xyz[2] / sum(colorspace_white_xyz)
305
  ))
3066x
  adopted_white_xy = unname(c(
3076x
    white_current[1] / sum(white_current),
3086x
    white_current[2] / sum(white_current)
309
  ))
310
3116x
  utils::modifyList(
3126x
    exr_metadata,
3136x
    list(
3146x
      chromaticities = list(
3156x
        red = unname(colorspace$primaries$r),
3166x
        green = unname(colorspace$primaries$g),
3176x
        blue = unname(colorspace$primaries$b),
3186x
        white = colorspace_white_xy
319
      ),
3206x
      adoptedNeutral = adopted_white_xy,
3216x
      envmap = "latlong"
322
    )
323
  )
324
}
325
326
#' Keep EXR metadata fields supported by libopenexr
327
#'
328
#' @param metadata EXR metadata list.
329
#' @keywords internal
330
filter_supported_exr_metadata = function(metadata) {
3316x
  metadata[intersect(
3326x
    names(metadata),
3336x
    c("chromaticities", "adoptedNeutral", "whiteLuminance", "envmap")
334
  )]
335
}
336
337
#' Write a skymodelr image with EXR color metadata
338
#'
339
#' @param image Image array or rayimage image.
340
#' @param filename Destination image path.
341
#' @param ... Additional arguments passed to [rayimage::ray_write_image()].
342
#' @keywords internal
343
write_sky_image = function(image, filename, ...) {
3443x
  dots = list(...)
3453x
  image_to_write = image
3463x
  if (tolower(tools::file_ext(filename)) == "exr") {
3473x
    metadata = dots$metadata
3483x
    if (!is.null(metadata) && !is.list(metadata)) {
349!
      stop("EXR metadata must be a list.", call. = FALSE)
350
    }
3513x
    dots$metadata = filter_supported_exr_metadata(
3523x
      if (is.null(metadata)) {
3533x
        sky_exr_metadata(image)
354
      } else {
355!
        utils::modifyList(sky_exr_metadata(image), metadata)
356
      }
357
    )
3583x
    attr(image_to_write, "exr") = filter_supported_exr_metadata(
3593x
      attr(image_to_write, "exr", exact = TRUE)
360
    )
361
  }
362
3633x
  do.call(
3643x
    rayimage::ray_write_image,
3653x
    c(
3663x
      list(image = image_to_write, filename = filename),
3673x
      dots
368
    )
369
  )
370
}
1
#' Generate a bright-planet image array
2
#'
3
#' @description Build a planetary luminance map aligned with the sky dome for
4
#' compositing within [generate_sky_latlong()].
5
#'
6
#' @param datetime POSIXct timestamp used for ephemerides.
7
#' @param lon Observer longitude in degrees (east positive).
8
#' @param lat Observer latitude in degrees.
9
#' @param filename Default `NA`. Destination image path to write. When `NA`, the
10
#'   image array is returned without writing.
11
#' @param resolution Default `2048`. Map half-width (image is `2 * resolution` by `resolution`).
12
#' @param turbidity Atmospheric turbidity for extinction modelling.
13
#' @param ozone_du Column ozone (Dobson Units) for colour shifts.
14
#' @param altitude Observer altitude in metres.
15
#' @param color Render RGB (`TRUE`) stars or monochrome (`FALSE`).
16
#' @param planet_width Approximate point-spread size for planets in pixels.
17
#' @param upper_hemisphere_only If `TRUE`, mask pixels below the horizon.
18
#' @param atmosphere_effects If `TRUE`, apply atmospheric extinction.
19
#' @param number_cores CPU threads used for rendering.
20
#' @param verbose Emit diagnostic output when `TRUE`.
21
#'
22
#' @return Either the image array, or the array is invisibly returned if a file
23
#'   is written. The array has dimensions `(resolution, 2 * resolution, 4)`.
24
#' @note Writing to non-EXR formats will introduce precision loss because HDR
25
#'   data are quantised to the destination format, and low dynamic range outputs like PNG
26
#'   and JPEG files will not represent the true luminosity values encoded in the array.
27
#'
28
#' @export
29
#' @examplesIf interactive() || identical(Sys.getenv("IN_PKGDOWN"), "true")
30
#' # Basic star field over Washington, DC at a fixed time
31
#' generate_planets(
32
#'   datetime = as.POSIXct("2025-03-21 02:20:00", tz = "America/New_York"),
33
#'   lon = -77.0369,
34
#'   lat = 38.9072,
35
#'   resolution = 400,
36
#'   color = TRUE,
37
#'   planet_width = 1,
38
#'   atmosphere_effects = TRUE,
39
#'   upper_hemisphere_only = TRUE,
40
#'   number_cores = 2
41
#' ) |>
42
#'   rayimage::plot_image()
43
generate_planets = function(
44
  datetime,
45
  lon,
46
  lat,
47
  filename = NA,
48
  resolution = 2048,
49
  turbidity = 3.0,
50
  ozone_du = 300.0,
51
  altitude = 0.0,
52
  color = FALSE,
53
  planet_width = 1,
54
  upper_hemisphere_only = TRUE,
55
  atmosphere_effects = TRUE,
56
  number_cores = 1,
57
  verbose = FALSE
58
) {
591x
  if (!inherits(datetime, "POSIXct")) {
60!
    stop("datetime must be POSIXct in UTC")
61
  }
621x
  attr(datetime, "tzone") = "UTC"
631x
  jd = jd_utc(datetime)
64
651x
  planet_temp = swe_dirs_topo_planets_df(
661x
    datetime = datetime,
671x
    lat = lat,
681x
    lon = lon,
691x
    elev_m = altitude
70
  )
711x
  if (verbose) {
72!
    print(planet_temp)
73
  }
741x
  planet_rgb = make_starfield_rcpp(
751x
    stars = planet_temp,
761x
    resolution = resolution,
771x
    lon_deg = lon,
781x
    lat_deg = lat,
791x
    jd = jd,
801x
    use_rgb = color,
811x
    turbidity = turbidity,
821x
    ozone_du = ozone_du,
831x
    altitude = altitude,
841x
    star_width = planet_width,
851x
    atmosphere_effects = atmosphere_effects,
861x
    upper_hemisphere_only = upper_hemisphere_only,
871x
    number_cores = number_cores
88
  )
891x
  planet_array = array(0, dim = c(resolution, resolution * 2, 4))
901x
  planet_array[,, 1:3] = planet_rgb
911x
  planet_array[,, 4] = 1
921x
  planet_array = rayimage::ray_read_image(
931x
    planet_array,
941x
    assume_white = "D65",
951x
    assume_colorspace = rayimage::CS_SRGB
96
  )
971x
  if (!is.na(filename)) {
98!
    warn_precision_loss(filename)
99!
    write_sky_image(planet_array, filename)
100!
    return(invisible(planet_array))
101
  } else {
1021x
    return(planet_array)
103
  }
104
}
1
# ---------------------------------------------------------------------------
2
# Helpers to convert POSIXct to Julian Date (UTC noon 1 Jan 2000 = 2451545).
3
#' Convert POSIXct timestamps to Julian Date
4
#'
5
#' @description Transform a POSIXct time value into an astronomical Julian Date
6
#' (days since noon UTC 1 Jan 4713 BCE).
7
#' @param time_utc POSIXct vector in UTC.
8
#' @keywords internal
9
jd_utc = function(time_utc) {
102x
  unclass(time_utc) / 86400 + 2440587.5 # Unix epoch to JD
11
}
12
13
spec_to_bv = function(spec) {
149110x
  if (is.na(spec) || !nzchar(spec)) {
15!
    return(NA_real_)
16
  }
179110x
  s = toupper(trimws(spec))
189110x
  letter = substr(s, 1, 1)
199110x
  base = c(
209110x
    O = -0.33,
219110x
    B = -0.30,
229110x
    A = 0.00,
239110x
    F = 0.30,
249110x
    G = 0.58,
259110x
    K = 0.81,
269110x
    M = 1.40
27
  )
289110x
  if (!letter %in% names(base)) {
2950x
    return(NA_real_)
30
  }
319060x
  digit = suppressWarnings(as.numeric(substr(s, 2, 2)))
329060x
  if (!is.finite(digit)) {
3361x
    digit = 0
34
  }
359060x
  digit = max(0, min(9, digit))
369060x
  next_letter = switch(
379060x
    letter,
389060x
    O = "B",
399060x
    B = "A",
409060x
    A = "F",
419060x
    F = "G",
429060x
    G = "K",
439060x
    K = "M",
449060x
    M = NA
45
  )
469060x
  next_base = if (!is.na(next_letter)) {
478551x
    base[[next_letter]]
48
  } else {
49509x
    base[["M"]] + 0.35
50
  }
519060x
  b_v = base[[letter]] + (digit / 10) * (next_base - base[[letter]])
529060x
  max(-0.4, min(2.0, b_v))
53
}
54
55
stars_with_bv = local({
56
  cache = NULL
57
  function() {
581x
    if (!is.null(cache)) {
59!
      return(cache)
60
    }
611x
    star_df = skymodelr::stars
621x
    if (!("b_v" %in% names(star_df))) {
631x
      star_df$b_v = vapply(star_df$spec, spec_to_bv, numeric(1))
64
    }
651x
    cache = star_df
661x
    cache
67
  }
68
})
69
70
# ---------------------------------------------------------------------------
71
#' Generate a star-field array aligned with `generate_sky()`
72
#'
73
#' @description Render a star map for a given observer location, time, and atmospheric
74
#' conditions so it can be composited with [generate_sky()]. Returns a
75
#' `(resolution, 2 * resolution, 4)` array with an opaque alpha channel. An
76
#' image file is written only when `filename` is supplied.
77
#'
78
#' @param datetime `POSIXct` timestamp used to compute local sidereal time.
79
#' @param lon Observer longitude in degrees (east positive).
80
#' @param lat Observer latitude in degrees.
81
#' @param filename Default `NA`. Path to an image file to write. If `NA`, the
82
#'   image array is returned without writing.
83
#' @param resolution Default `2048`. Map half-width; the output image is `2 * resolution` by `resolution`.
84
#' @param turbidity Default `3.0`. Atmospheric turbidity controlling aerosol optical depth for extinction/reddening.
85
#' @param ozone_du Default `300.0`. Column ozone in Dobson Units used in atmospheric absorption.
86
#' @param altitude Default `0.0`. Observer altitude above mean sea level in meters.
87
#' @param color Default `TRUE`. If `TRUE`, render RGB star colors; if `FALSE`, render monochrome luminance.
88
#' @param star_width Default `1`. Approximate stellar point-spread size in pixels (controls apparent star sharpness).
89
#' @param upper_hemisphere_only Default `TRUE`. If `TRUE`, pixels below the local horizon are suppressed to match `generate_sky()`'s visible hemisphere.
90
#' @param atmosphere_effects Default `TRUE`. If `TRUE`, apply atmospheric extinction and color shift using `turbidity`, `ozone_du`, and `altitude`.
91
#' @param number_cores Default `1`. Number of CPU threads to use.
92
#'
93
#' @return Either the image array, or the array is invisibly returned if a file
94
#'   is written. The array has dimensions `(resolution, 2 * resolution, 4)`.
95
#' @note Writing to non-EXR formats will introduce precision loss because HDR
96
#'   data are quantised to the destination format, and low dynamic range outputs like PNG
97
#'   and JPEG files will not represent the true luminosity values encoded in the array.
98
#'
99
#' @export
100
#' @examples
101
#' star_map = generate_stars(
102
#'   resolution = 8,
103
#'   lon = -77.0369,
104
#'   lat = 38.9072,
105
#'   datetime = as.POSIXct("2025-03-21 02:20:00", tz = "UTC"),
106
#'   atmosphere_effects = FALSE,
107
#'   number_cores = 1
108
#' )
109
#' dim(star_map)
110
#'
111
#' @examplesIf interactive() || identical(Sys.getenv("IN_PKGDOWN"), "true")
112
#' # Note: exposure has been increased for all examples (via white_point) for
113
#' # ease of visibility in documentation
114
#'
115
#' # Basic star field over Washington, DC at a fixed time
116
#' generate_stars(
117
#'   resolution = 400,
118
#'   lon = -77.0369,
119
#'   lat = 38.9072,
120
#'   datetime = as.POSIXct("2025-03-21 02:20:00", tz = "America/New_York"),
121
#'   color = TRUE,
122
#'   star_width = 1,
123
#'   atmosphere_effects = TRUE,
124
#'   upper_hemisphere_only = TRUE,
125
#'   number_cores = 2
126
#' ) |>
127
#'   rayimage::plot_image()
128
#'
129
#' # Monochrome stars, no atmospheric extinction/reddening, full sphere
130
#' generate_stars(
131
#'   resolution = 400,
132
#'   lon = -122.4194,
133
#'   lat = 37.7749,
134
#'   datetime = as.POSIXct("2025-06-01 08:00:00", tz = "UTC"),
135
#'   color = FALSE,
136
#'   star_width = 1,
137
#'   upper_hemisphere_only = FALSE,
138
#'   atmosphere_effects = FALSE
139
#' ) |>
140
#'   rayimage::plot_image()
141
#'
142
#' # Sharper stars (smaller PSF) with ozone/turbidity and altitude
143
#' generate_stars(
144
#'   resolution = 400,
145
#'   lon = 10,
146
#'   lat = 45,
147
#'   datetime = as.POSIXct("2025-12-01 22:00:00", tz = "UTC"),
148
#'   star_width = 0.5,
149
#'   turbidity = 3.5,
150
#'   ozone_du = 320,
151
#'   altitude = 1000,
152
#'   color = TRUE
153
#' ) |>
154
#'   rayimage::plot_image()
155
generate_stars = function(
156
  lon,
157
  lat,
158
  datetime,
159
  filename = NA,
160
  resolution = 2048,
161
  turbidity = 3.0,
162
  ozone_du = 300.0,
163
  altitude = 0.0,
164
  color = TRUE,
165
  star_width = 1,
166
  upper_hemisphere_only = TRUE,
167
  atmosphere_effects = TRUE,
168
  number_cores = 1
169
) {
1701x
  if (!inherits(datetime, "POSIXct")) {
171!
    stop("datetime must be POSIXct in UTC")
172
  }
1731x
  attr(datetime, "tzone") = "UTC"
1741x
  jd = jd_utc(datetime)
175
1761x
  star_rgb = make_starfield_rcpp(
1771x
    stars = stars_with_bv(),
1781x
    resolution = resolution,
1791x
    lon_deg = lon,
1801x
    lat_deg = lat,
1811x
    jd = jd,
1821x
    use_rgb = color,
1831x
    turbidity = turbidity,
1841x
    ozone_du = ozone_du,
1851x
    altitude = altitude,
1861x
    star_width = star_width,
1871x
    atmosphere_effects = atmosphere_effects,
1881x
    upper_hemisphere_only = upper_hemisphere_only,
1891x
    number_cores = number_cores
190
  )
1911x
  star_array = array(0, dim = c(resolution, resolution * 2, 4))
1921x
  star_array[,, 1:3] = star_rgb
1931x
  star_array[,, 4] = 1
1941x
  star_array = rayimage::ray_read_image(
1951x
    star_array,
1961x
    assume_white = "D65",
1971x
    assume_colorspace = rayimage::CS_SRGB
198
  )
1991x
  if (!is.na(filename)) {
200!
    warn_precision_loss(filename)
201!
    write_sky_image(star_array, filename)
202!
    return(invisible(star_array))
203
  } else {
2041x
    return(star_array)
205
  }
206
}
1
warn_precision_loss = function(path) {
23x
  ext = tools::file_ext(path)
33x
  if (nzchar(ext) && tolower(ext) != "exr") {
4!
    message(
5!
      "Note: writing to non-EXR formats may introduce precision loss and unphysically clamp luminosity values."
6
    )
7
  }
8
}
1
#' Moon disk solid angle in steradians
2
#'
3
#' @param diameter_deg Angular diameter in degrees.
4
#' @return Solid angle in steradians.
5
#' @keywords internal
6
moon_solid_angle_sr = function(diameter_deg = 0.533) {
7!
  r = (diameter_deg * 0.5) * pi / 180
8!
  2 * pi * (1 - cos(r))
9
}
10
11
cie_1931_2deg = local({
12
  cache = NULL
13
  function() {
1446x
    if (is.null(cache)) {
1546x
      cache = cie_1931_2deg_rcpp()
16
    }
1746x
    cache
18
  }
19
})
20
21
trapezoid_weights = function(lambda_nm) {
2247x
  n = length(lambda_nm)
2347x
  if (n == 0) {
24!
    return(numeric(0))
25
  }
2647x
  if (n == 1) {
27!
    return(1)
28
  }
2947x
  w = numeric(n)
3047x
  w[1] = (lambda_nm[2] - lambda_nm[1]) / 2
3147x
  for (i in 2:(n - 1)) {
3222043x
    w[i] = (lambda_nm[i + 1] - lambda_nm[i - 1]) / 2
33
  }
3447x
  w[n] = (lambda_nm[n] - lambda_nm[n - 1]) / 2
3547x
  w
36
}
37
38
xyz_to_srgb = function(XYZ) {
3923x
  M = matrix(
4023x
    c(
4123x
      3.2404542,
4223x
      -1.5371385,
4323x
      -0.4985314,
4423x
      -0.9692660,
4523x
      1.8760108,
4623x
      0.0415560,
4723x
      0.0556434,
4823x
      -0.2040259,
4923x
      1.0572252
50
    ),
5123x
    nrow = 3,
5223x
    byrow = TRUE
53
  )
5423x
  as.numeric(M %*% XYZ)
55
}
56
57
#' Compute a unit RGB vector for a chosen SPD
58
#'
59
#' @param spd_type SPD shape. Either `"D65"` or `"BB5778"`.
60
#' @return Numeric vector length 3, normalized so sum equals 1.
61
#' @keywords internal
62
compute_spd_rgb_unit = function(spd_type = c("D65", "BB5778")) {
6322x
  spd_type = match.arg(spd_type)
6422x
  cie = cie_1931_2deg()
6522x
  lambda_nm = cie$lambda_nm
6622x
  spd = spd_values_rcpp(lambda_nm, spd_type)
6722x
  w = trapezoid_weights(lambda_nm)
6822x
  X = sum(spd * cie$x_bar * w)
6922x
  Y = sum(spd * cie$y_bar * w)
7022x
  Z = sum(spd * cie$z_bar * w)
7122x
  rgb = xyz_to_srgb(c(X, Y, Z))
7222x
  rgb[!is.finite(rgb)] = 0
7322x
  rgb = pmax(rgb, 0)
7422x
  total = sum(rgb)
7522x
  if (!is.finite(total) || total <= 0) {
76!
    return(c(0, 0, 0))
77
  }
7822x
  rgb / total
79
}
80
81
#' Compute effective luminous efficacy for a chosen SPD
82
#'
83
#' @param spd_type SPD shape. Either `"D65"` or `"BB5778"`.
84
#' @param wavelength_grid Optional numeric vector of wavelengths (nm).
85
#' @param V_lambda Optional numeric vector of photopic V(lambda) samples.
86
#' @return Effective luminous efficacy in lm/W.
87
#' @keywords internal
88
compute_K_eff = function(
89
  spd_type = c("D65", "BB5778"),
90
  wavelength_grid = NULL,
91
  V_lambda = NULL
92
) {
9322x
  spd_type = match.arg(spd_type)
9422x
  if (is.null(wavelength_grid) || is.null(V_lambda)) {
9522x
    cie = cie_1931_2deg()
9622x
    wavelength_grid = cie$lambda_nm
9722x
    V_lambda = cie$y_bar
98
  }
9922x
  if (length(wavelength_grid) != length(V_lambda)) {
100!
    stop("wavelength_grid and V_lambda must have the same length.")
101
  }
10222x
  spd = spd_values_rcpp(wavelength_grid, spd_type)
10322x
  w = trapezoid_weights(wavelength_grid)
10422x
  num = sum(spd * V_lambda * w)
10522x
  den = sum(spd * w)
10622x
  if (!is.finite(num) || !is.finite(den) || den <= 0) {
107!
    return(NA_real_)
108
  }
10922x
  683 * num / den
110
}
111
112
#' Convert photometric illuminance to radiometric irradiance
113
#'
114
#' @param E_v_lux Illuminance in lux.
115
#' @param K_eff Effective luminous efficacy in lm/W.
116
#' @return Irradiance in W/m^2.
117
#' @keywords internal
118
lux_to_radiometric_irradiance = function(E_v_lux, K_eff) {
1197x
  E_v_lux / K_eff
120
}
1
#' List cached sky data files
2
#'
3
#' @description
4
#' Lists files cached by [download_sky_data()] under
5
#' `tools::R_user_dir("skymodelr", "data")`.
6
#'
7
#' @returns A data frame with columns `file`, `path`, `size`, and `modified`.
8
#' @export
9
#'
10
#' @examples
11
#' list_sky_data()
12
list_sky_data = function() {
135x
  cache_dir = prague_coef_cache_dir()
145x
  empty = data.frame(
155x
    file = character(),
165x
    path = character(),
175x
    size = numeric(),
185x
    modified = as.POSIXct(character()),
195x
    stringsAsFactors = FALSE
20
  )
21
225x
  if (!dir.exists(cache_dir)) {
23!
    return(empty)
24
  }
25
265x
  paths = list.files(cache_dir, full.names = TRUE, no.. = TRUE)
275x
  if (!length(paths)) {
281x
    return(empty)
29
  }
30
314x
  info = file.info(paths)
324x
  keep = !is.na(info$isdir) & !info$isdir
334x
  if (!any(keep)) {
34!
    return(empty)
35
  }
36
374x
  paths = paths[keep]
384x
  info = info[keep, , drop = FALSE]
39
404x
  data.frame(
414x
    file = basename(paths),
424x
    path = normalizePath(paths, winslash = "/", mustWork = FALSE),
434x
    size = info$size,
444x
    modified = info$mtime,
454x
    stringsAsFactors = FALSE,
464x
    row.names = NULL
47
  )
48
}
49
50
#' Clear cached sky data files
51
#'
52
#' @description
53
#' Removes files cached by [download_sky_data()] under
54
#' `tools::R_user_dir("skymodelr", "data")`.
55
#'
56
#' @param files Default `NULL`. Character vector of cached file basenames to remove.
57
#' @param ask Default `interactive()`. Whether to ask for confirmation before deleting files.
58
#'
59
#' @returns Invisibly, the paths successfully removed.
60
#' @export
61
#'
62
#' @examplesIf interactive()
63
#' clear_sky_data()
64
clear_sky_data = function(files = NULL, ask = interactive()) {
653x
  cache_dir = prague_coef_cache_dir()
663x
  if (!dir.exists(cache_dir)) {
67!
    return(invisible(character()))
68
  }
69
703x
  cached = list_sky_data()
713x
  if (is.null(files)) {
72!
    paths = cached$path
73
  } else {
743x
    requested = unique(basename(files))
753x
    requested = requested[nzchar(requested) & !requested %in% c(".", "..")]
763x
    paths = cached$path[cached$file %in% requested]
77
  }
78
793x
  if (!length(paths)) {
802x
    message("No matching cached sky data files found.")
812x
    return(invisible(character()))
82
  }
83
841x
  if (isTRUE(ask)) {
85!
    prompt = sprintf(
86!
      "Remove %d cached sky data file%s?",
87!
      length(paths),
88!
      if (length(paths) == 1) "" else "s"
89
    )
90!
    if (!isTRUE(utils::askYesNo(prompt, default = FALSE))) {
91!
      return(invisible(character()))
92
    }
93
  }
94
951x
  unlink(paths)
961x
  removed = paths[!file.exists(paths)]
971x
  invisible(removed)
98
}
1
#' Download Prague Sky Model Coefficient Data
2
#'
3
#' This model which allows for sun angles below the horizon,
4
#' wide spectral ranges including infrared, polarization, as well
5
#' rendering at altitude) need to download a coefficient file. There are three versions
6
#' of this dataset, listed here in order of increasing size:
7
#'
8
#' | Argument combination               | File                                 | Size |
9
#' |------------------------------------|--------------------------------------|----------------|
10
#' | `sea_level = TRUE,  wide_spectrum = FALSE` | `SkyModelDatasetGround.dat`            |   107MB |
11
#' | `sea_level = TRUE,  wide_spectrum = TRUE`  | `PragueSkyModelDatasetGroundInfra.dat` |   574MB |
12
#' | `sea_level = FALSE`                          | `SkyModelDataset.dat`                  | 2.4GB |
13
#'
14
#'
15
#' @param sea_level Default `TRUE`. Download the sea-level-only data.
16
#' Set to `FALSE` to download the full-altitude dataset.
17
#' @param wide_spectrum Default `FALSE`. If `TRUE`, downloads the
18
#' wide-spectrum (55-channel, polarised) version. Valid only when `sea_level = TRUE`.
19
#'
20
#' @returns Invisibly, the full path to the data file.
21
#' @export
22
#'
23
#' @examplesIf interactive() || identical(Sys.getenv("IN_PKGDOWN"), "true")
24
#' # Standard (11-channel, sea-level) coefficients
25
#' download_sky_data()
26
#'
27
#' # Wide-spectrum sea-level coefficients
28
#' download_sky_data(wide_spectrum = TRUE)
29
#'
30
#' # Full altitude-range coefficients
31
#' download_sky_data(sea_level = FALSE)
32
download_sky_data = function(sea_level = TRUE, wide_spectrum = FALSE) {
33!
  if (wide_spectrum && !sea_level) {
34!
    stop("`wide_spectrum = TRUE` is only valid when `sea_level = TRUE`.")
35
  }
36
37!
  file_info = prague_coef_info(
38!
    sea_level = sea_level,
39!
    wide_spectrum = wide_spectrum
40
  )
41
42!
  cache_dir = prague_coef_cache_dir()
43!
  if (!dir.exists(cache_dir)) {
44!
    dir.create(cache_dir, recursive = TRUE)
45
  }
46
47!
  tmp_path = tempfile(pattern = paste0(file_info$name, "."), tmpdir = cache_dir)
48!
  on.exit(if (file.exists(tmp_path)) unlink(tmp_path), add = TRUE)
49!
  final_dest_path = file.path(cache_dir, file_info$name)
50
51!
  file_present = FALSE
52!
  if (file.exists(final_dest_path)) {
53!
    message("File exists, comparing checksum.")
54!
    if (identical(unname(tools::md5sum(final_dest_path)), file_info$md5)) {
55!
      file_present = TRUE
56
    } else {
57!
      message(
58!
        "File exists in cache folder but checksum not correct: removing ",
59!
        final_dest_path
60
      )
61!
      file.remove(final_dest_path)
62
    }
63
  }
64
65!
  if (file_present) {
66!
    message(
67!
      "File already present at '",
68!
      final_dest_path,
69!
      "' with correct checksum."
70
    )
71
  } else {
72!
    message("Downloading ", file_info$name)
73!
    old_timeout = getOption("timeout")
74!
    on.exit(options(timeout = old_timeout), add = TRUE)
75!
    options(timeout = 3600)
76!
    download_error = new.env(parent = emptyenv())
77!
    status = tryCatch(
78!
      utils::download.file(
79!
        file_info$url,
80!
        destfile = tmp_path,
81!
        mode = "wb",
82!
        quiet = FALSE
83
      ),
84!
      error = function(e) {
85!
        download_error$message = conditionMessage(e)
86!
        NA_integer_
87
      }
88
    )
89
90!
    if (!identical(status, 0L) && !identical(status, 0)) {
91!
      if (file.exists(tmp_path)) {
92!
        unlink(tmp_path)
93
      }
94!
      detail = if (
95!
        exists("message", envir = download_error, inherits = FALSE)
96
      ) {
97!
        paste0(": ", download_error$message)
98
      } else {
99!
        paste0(" with status ", status)
100
      }
101!
      stop(
102!
        "Failed to download Prague coefficient file '",
103!
        file_info$name,
104
        "'",
105!
        detail,
106
        ".",
107!
        call. = FALSE
108
      )
109
    }
110
111!
    if (!file.exists(tmp_path)) {
112!
      stop(
113!
        "Download reported success but no temporary file was created for '",
114!
        file_info$name,
115
        "'.",
116!
        call. = FALSE
117
      )
118
    }
119
120!
    if (!identical(unname(tools::md5sum(tmp_path)), file_info$md5)) {
121!
      unlink(tmp_path)
122!
      stop(
123!
        "Checksum mismatch after downloading Prague coefficient file '",
124!
        file_info$name,
125!
        "'. The partial file was deleted.",
126!
        call. = FALSE
127
      )
128
    }
129
130!
    if (file.exists(final_dest_path)) {
131!
      unlink(final_dest_path)
132
    }
133!
    moved = file.rename(tmp_path, final_dest_path)
134!
    if (!moved) {
135!
      moved = file.copy(tmp_path, final_dest_path, overwrite = TRUE)
136!
      unlink(tmp_path)
137
    }
138!
    if (!moved) {
139!
      stop("Failed to move Prague coefficient file into place.", call. = FALSE)
140
    }
141
142!
    if (!identical(unname(tools::md5sum(final_dest_path)), file_info$md5)) {
143!
      unlink(final_dest_path)
144!
      stop(
145!
        "Checksum mismatch after installing Prague coefficient file '",
146!
        file_info$name,
147!
        "'. The bad file was deleted.",
148!
        call. = FALSE
149
      )
150
    }
151!
    message("Saved to ", final_dest_path)
152
  }
153!
  invisible(final_dest_path)
154
}
1
clamp_value = function(x, min_value = 0, max_value = 1) {
237390x
  pmin(pmax(x, min_value), max_value)
3
}
4
5
get_moon_texture = function() {
62x
  texture_file = system.file(
72x
    "textures",
82x
    "lroc_color_poles_1k.jpg",
92x
    package = "skymodelr"
10
  )
112x
  if (!nzchar(texture_file)) {
12!
    stop(
13!
      "Moon texture file 'lroc_color_poles_1k.jpg' was not found in the installed package.",
14!
      call. = FALSE
15
    )
16
  }
172x
  texture_file
18
}
1
#' Prepare Location and Time Metadata for Native Prague Sky Queries
2
#'
3
#' Resolve the full-altitude Prague dataset and the Sun's topocentric position
4
#' without loading coefficients or generating an image. This lets rendering
5
#' libraries evaluate the model natively while using skymodelr's ephemeris and
6
#' RGB calibration through a public interface.
7
#'
8
#' @param datetime A single `POSIXct` instant. Its time zone is respected.
9
#' @param lat Observer latitude in degrees, between -90 and 90.
10
#' @param lon Observer longitude in degrees, between -180 and 180.
11
#' @param altitude Default `0`. Reference altitude in meters, from 0 to 15000.
12
#' @param visibility Default `50`. Meteorological visibility in kilometers,
13
#'   from 20 to 131.8.
14
#' @param albedo Default `0.5`. Ground albedo, from 0 to 1.
15
#' @param prague_rgb_correction Default `TRUE`. Apply the Prague RGB calibration,
16
#'   as in [calculate_sky_values()].
17
#' @param prague_rgb_correction_strength Default `1`. Nonnegative calibration
18
#'   strength.
19
#' @param prague_rgb_correction_gain Default `"auto"`. Automatic calibration or
20
#'   three positive RGB gains, as in [calculate_sky_values()].
21
#'
22
#' @return A list with `filename` (the installed full-altitude coefficient file),
23
#'   `elevation_deg`, `azimuth_deg` (clockwise from north),
24
#'   `angular_diameter_deg`, `rgb_gain` (the applied R, G, B gains), and the
25
#'   reference `altitude`, `visibility`, and `albedo`. No native pointers are
26
#'   included; the result can be serialized. The coefficient path is local to
27
#'   this computer and should be resolved again on another machine.
28
#'
29
#' @details Install the data explicitly with
30
#'   `download_sky_data(sea_level = FALSE)`. This function never downloads files
31
#'   or prompts. It supports the visible-spectrum, full-altitude dataset and
32
#'   returns the actual Sun position even below the Prague model's minimum
33
#'   elevation of -4.2 degrees. Native consumers should use zero solar radiance
34
#'   below that limit while retaining transmission for other light sources.
35
#'   This function does not evaluate radiance, attenuation, or atmospheric
36
#'   refraction.
37
#' @export
38
#' @examplesIf interactive()
39
#' info = get_prague_sky_metadata(
40
#'   as.POSIXct("2026-06-21 20:00:00", tz = "America/New_York"),
41
#'   lat = 40.7, lon = -74
42
#' )
43
#' info[c("elevation_deg", "azimuth_deg", "rgb_gain")]
44
get_prague_sky_metadata = function(
45
  datetime,
46
  lat,
47
  lon,
48
  altitude = 0,
49
  visibility = 50,
50
  albedo = 0.5,
51
  prague_rgb_correction = TRUE,
52
  prague_rgb_correction_strength = 1,
53
  prague_rgb_correction_gain = "auto"
54
) {
55!
  celestial_disk_settings(
56!
    datetime,
57!
    lat,
58!
    lon,
59!
    altitude,
60!
    16,
61!
    visibility,
62!
    albedo,
63!
    1,
64!
    FALSE,
65!
    prague_rgb_correction,
66!
    prague_rgb_correction_strength,
67!
    prague_rgb_correction_gain
68
  )
69!
  filename = resolve_prague_coef_file(altitude = 1, allow_download = FALSE)
70!
  ephemeris = swe_dirs_topo_moon_sun(datetime, lat, lon, elev_m = altitude)
71!
  disk = celestial_disk_result(
72!
    NULL,
73!
    ephemeris$sun_dir_topo,
74!
    ephemeris$sun_diameter_degrees
75
  )
76!
  gain = if (
77!
    normalize_prague_rgb_correction(prague_rgb_correction) == "constant"
78
  ) {
79!
    prepare_prague_rgb_gain(
80!
      prague_rgb_correction_gain,
81!
      prague_rgb_correction_strength
82
    )
83
  } else {
84!
    c(R = 1, G = 1, B = 1)
85
  }
86!
  c(
87!
    list(filename = filename),
88!
    disk[c("elevation_deg", "azimuth_deg", "angular_diameter_deg")],
89!
    list(
90!
      rgb_gain = gain,
91!
      altitude = altitude,
92!
      visibility = visibility,
93!
      albedo = albedo
94
    )
95
  )
96
}
1
/*
2
This file is included in the skymodelr package, which is distributed as a
3
whole under GPL-3. The following upstream copyright and provenance notice is
4
preserved for attribution and compliance with upstream notice requirements.
5
*/
6
7
/*
8
This source is published under the following 3-clause BSD license.
9
10
Copyright (c) 2012 - 2013, Lukas Hosek and Alexander Wilkie
11
All rights reserved.
12
13
Redistribution and use in source and binary forms, with or without
14
modification, are permitted provided that the following conditions are met:
15
16
    * Redistributions of source code must retain the above copyright
17
      notice, this list of conditions and the following disclaimer.
18
    * Redistributions in binary form must reproduce the above copyright
19
      notice, this list of conditions and the following disclaimer in the
20
      documentation and/or other materials provided with the distribution.
21
    * None of the names of the contributors may be used to endorse or promote
22
      products derived from this software without specific prior written
23
      permission.
24
25
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
26
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
27
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
28
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY
29
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
30
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
31
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
32
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
33
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
34
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
35
*/
36
37
/* ============================================================================
38
39
This file is part of a sample implementation of the analytical skylight and
40
solar radiance models presented in the SIGGRAPH 2012 paper
41
42
43
           "An Analytic Model for Full Spectral Sky-Dome Radiance"
44
45
and the 2013 IEEE CG&A paper
46
47
       "Adding a Solar Radiance Function to the Hosek Skylight Model"
48
49
                                   both by
50
51
                       Lukas Hosek and Alexander Wilkie
52
                Charles University in Prague, Czech Republic
53
54
55
                        Version: 1.4a, February 22nd, 2013
56
57
Version history:
58
59
1.4a  February 22nd, 2013
60
      Removed unnecessary and counter-intuitive solar radius parameters
61
      from the interface of the colourspace sky dome initialisation functions.
62
63
1.4   February 11th, 2013
64
      Fixed a bug which caused the relative brightness of the solar disc
65
      and the sky dome to be off by a factor of about 6. The sun was too
66
      bright: this affected both normal and alien sun scenarios. The
67
      coefficients of the solar radiance function were changed to fix this.
68
69
1.3   January 21st, 2013 (not released to the public)
70
      Added support for solar discs that are not exactly the same size as
71
      the terrestrial sun. Also added support for suns with a different
72
      emission spectrum ("Alien World" functionality).
73
74
1.2a  December 18th, 2012
75
      Fixed a mistake and some inaccuracies in the solar radiance function
76
      explanations found in ArHosekSkyModel.h. The actual source code is
77
      unchanged compared to version 1.2.
78
79
1.2   December 17th, 2012
80
      Native RGB data and a solar radiance function that matches the turbidity
81
      conditions were added.
82
83
1.1   September 2012
84
      The coefficients of the spectral model are now scaled so that the output
85
      is given in physical units: W / (m^-2 * sr * nm). Also, the output of the
86
      XYZ model is now no longer scaled to the range [0...1]. Instead, it is
87
      the result of a simple conversion from spectral data via the CIE 2 degree
88
      standard observer matching functions. Therefore, after multiplication
89
      with 683 lm / W, the Y channel now corresponds to luminance in lm.
90
91
1.0   May 11th, 2012
92
      Initial release.
93
94
95
Please visit http://cgg.mff.cuni.cz/projects/SkylightModelling/ to check if
96
an updated version of this code has been published!
97
98
============================================================================ */
99
100
/*
101
102
All instructions on how to use this code are in the accompanying header file.
103
104
*/
105
106
#include "ArHosekSkyModel.h"
107
#include "ArHosekSkyModelData_Spectral.h"
108
#include "ArHosekSkyModelData_CIEXYZ.h"
109
#include "ArHosekSkyModelData_RGB.h"
110
#include <assert.h>
111
#include <stdio.h>
112
#include <stdlib.h>
113
#include <math.h>
114
115
116
#ifdef __cplusplus
117
extern "C" {
118
#endif
119
120
//   Some macro definitions that occur elsewhere in ART, and that have to be
121
//   replicated to make this a stand-alone module.
122
123
#ifndef NIL
124
#define NIL                         0
125
#endif
126
127
#ifndef MATH_PI
128
#define MATH_PI                     3.141592653589793
129
#endif
130
131
#ifndef MATH_DEG_TO_RAD
132
#define MATH_DEG_TO_RAD             ( MATH_PI / 180.0 )
133
#endif
134
135
#ifndef MATH_RAD_TO_DEG
136
#define MATH_RAD_TO_DEG             ( 180.0 / MATH_PI )
137
#endif
138
139
#ifndef DEGREES
140
#define DEGREES                     * MATH_DEG_TO_RAD
141
#endif
142
143
#ifndef TERRESTRIAL_SOLAR_RADIUS
144
#define TERRESTRIAL_SOLAR_RADIUS    ( ( 0.51 DEGREES ) / 2.0 )
145
#endif
146
147
#ifndef ALLOC
148
#define ALLOC(_struct)              ((_struct *)malloc(sizeof(_struct)))
149
#endif
150
151
// internal definitions
152
153
typedef double *ArHosekSkyModel_Dataset;
154
typedef double *ArHosekSkyModel_Radiance_Dataset;
155
156
// internal functions
157
158297x
void ArHosekSkyModel_CookConfiguration(
159
        ArHosekSkyModel_Dataset       dataset,
160
        ArHosekSkyModelConfiguration  config,
161
        double                        turbidity,
162
        double                        albedo,
163
        double                        solar_elevation
164
        )
165
{
166
    double  * elev_matrix;
167
168297x
    int     int_turbidity = (int)turbidity;
169297x
    double  turbidity_rem = turbidity - (double)int_turbidity;
170
171297x
    solar_elevation = pow(solar_elevation / (MATH_PI / 2.0), (1.0 / 3.0));
172
173
    // alb 0 low turb
174
175297x
    elev_matrix = dataset + ( 9 * 6 * (int_turbidity-1) );
176
177
1782970x
    for( unsigned int i = 0; i < 9; ++i )
179
    {
180
        //(1-t).^3* A1 + 3*(1-t).^2.*t * A2 + 3*(1-t) .* t .^ 2 * A3 + t.^3 * A4;
1812673x
        config[i] =
1822673x
        (1.0-albedo) * (1.0 - turbidity_rem)
1832673x
        * ( pow(1.0-solar_elevation, 5.0) * elev_matrix[i]  +
1842673x
           5.0  * pow(1.0-solar_elevation, 4.0) * solar_elevation * elev_matrix[i+9] +
1852673x
           10.0*pow(1.0-solar_elevation, 3.0)*pow(solar_elevation, 2.0) * elev_matrix[i+18] +
1862673x
           10.0*pow(1.0-solar_elevation, 2.0)*pow(solar_elevation, 3.0) * elev_matrix[i+27] +
1872673x
           5.0*(1.0-solar_elevation)*pow(solar_elevation, 4.0) * elev_matrix[i+36] +
1882673x
           pow(solar_elevation, 5.0)  * elev_matrix[i+45]);
189
    }
190
191
    // alb 1 low turb
192297x
    elev_matrix = dataset + (9*6*10 + 9*6*(int_turbidity-1));
1932970x
    for(unsigned int i = 0; i < 9; ++i)
194
    {
195
        //(1-t).^3* A1 + 3*(1-t).^2.*t * A2 + 3*(1-t) .* t .^ 2 * A3 + t.^3 * A4;
1962673x
        config[i] +=
1972673x
        (albedo) * (1.0 - turbidity_rem)
1982673x
        * ( pow(1.0-solar_elevation, 5.0) * elev_matrix[i]  +
1992673x
           5.0  * pow(1.0-solar_elevation, 4.0) * solar_elevation * elev_matrix[i+9] +
2002673x
           10.0*pow(1.0-solar_elevation, 3.0)*pow(solar_elevation, 2.0) * elev_matrix[i+18] +
2012673x
           10.0*pow(1.0-solar_elevation, 2.0)*pow(solar_elevation, 3.0) * elev_matrix[i+27] +
2022673x
           5.0*(1.0-solar_elevation)*pow(solar_elevation, 4.0) * elev_matrix[i+36] +
2032673x
           pow(solar_elevation, 5.0)  * elev_matrix[i+45]);
204
    }
205
206297x
    if(int_turbidity == 10)
207!
        return;
208
209
    // alb 0 high turb
210297x
    elev_matrix = dataset + (9*6*(int_turbidity));
2112970x
    for(unsigned int i = 0; i < 9; ++i)
212
    {
213
        //(1-t).^3* A1 + 3*(1-t).^2.*t * A2 + 3*(1-t) .* t .^ 2 * A3 + t.^3 * A4;
2142673x
        config[i] +=
2152673x
        (1.0-albedo) * (turbidity_rem)
2162673x
        * ( pow(1.0-solar_elevation, 5.0) * elev_matrix[i]  +
2172673x
           5.0  * pow(1.0-solar_elevation, 4.0) * solar_elevation * elev_matrix[i+9] +
2182673x
           10.0*pow(1.0-solar_elevation, 3.0)*pow(solar_elevation, 2.0) * elev_matrix[i+18] +
2192673x
           10.0*pow(1.0-solar_elevation, 2.0)*pow(solar_elevation, 3.0) * elev_matrix[i+27] +
2202673x
           5.0*(1.0-solar_elevation)*pow(solar_elevation, 4.0) * elev_matrix[i+36] +
2212673x
           pow(solar_elevation, 5.0)  * elev_matrix[i+45]);
222
    }
223
224
    // alb 1 high turb
225297x
    elev_matrix = dataset + (9*6*10 + 9*6*(int_turbidity));
2262970x
    for(unsigned int i = 0; i < 9; ++i)
227
    {
228
        //(1-t).^3* A1 + 3*(1-t).^2.*t * A2 + 3*(1-t) .* t .^ 2 * A3 + t.^3 * A4;
2292673x
        config[i] +=
2302673x
        (albedo) * (turbidity_rem)
2312673x
        * ( pow(1.0-solar_elevation, 5.0) * elev_matrix[i]  +
2322673x
           5.0  * pow(1.0-solar_elevation, 4.0) * solar_elevation * elev_matrix[i+9] +
2332673x
           10.0*pow(1.0-solar_elevation, 3.0)*pow(solar_elevation, 2.0) * elev_matrix[i+18] +
2342673x
           10.0*pow(1.0-solar_elevation, 2.0)*pow(solar_elevation, 3.0) * elev_matrix[i+27] +
2352673x
           5.0*(1.0-solar_elevation)*pow(solar_elevation, 4.0) * elev_matrix[i+36] +
2362673x
           pow(solar_elevation, 5.0)  * elev_matrix[i+45]);
237
    }
238
}
239
240297x
double ArHosekSkyModel_CookRadianceConfiguration(
241
        ArHosekSkyModel_Radiance_Dataset  dataset,
242
        double                            turbidity,
243
        double                            albedo,
244
        double                            solar_elevation
245
        )
246
{
247
    double* elev_matrix;
248
249297x
    int int_turbidity = (int)turbidity;
250297x
    double turbidity_rem = turbidity - (double)int_turbidity;
251
    double res;
252297x
    solar_elevation = pow(solar_elevation / (MATH_PI / 2.0), (1.0 / 3.0));
253
254
    // alb 0 low turb
255297x
    elev_matrix = dataset + (6*(int_turbidity-1));
256
    //(1-t).^3* A1 + 3*(1-t).^2.*t * A2 + 3*(1-t) .* t .^ 2 * A3 + t.^3 * A4;
257297x
    res = (1.0-albedo) * (1.0 - turbidity_rem) *
258297x
        ( pow(1.0-solar_elevation, 5.0) * elev_matrix[0] +
259297x
         5.0*pow(1.0-solar_elevation, 4.0)*solar_elevation * elev_matrix[1] +
260297x
         10.0*pow(1.0-solar_elevation, 3.0)*pow(solar_elevation, 2.0) * elev_matrix[2] +
261297x
         10.0*pow(1.0-solar_elevation, 2.0)*pow(solar_elevation, 3.0) * elev_matrix[3] +
262297x
         5.0*(1.0-solar_elevation)*pow(solar_elevation, 4.0) * elev_matrix[4] +
263297x
         pow(solar_elevation, 5.0) * elev_matrix[5]);
264
265
    // alb 1 low turb
266297x
    elev_matrix = dataset + (6*10 + 6*(int_turbidity-1));
267
    //(1-t).^3* A1 + 3*(1-t).^2.*t * A2 + 3*(1-t) .* t .^ 2 * A3 + t.^3 * A4;
268297x
    res += (albedo) * (1.0 - turbidity_rem) *
269297x
        ( pow(1.0-solar_elevation, 5.0) * elev_matrix[0] +
270297x
         5.0*pow(1.0-solar_elevation, 4.0)*solar_elevation * elev_matrix[1] +
271297x
         10.0*pow(1.0-solar_elevation, 3.0)*pow(solar_elevation, 2.0) * elev_matrix[2] +
272297x
         10.0*pow(1.0-solar_elevation, 2.0)*pow(solar_elevation, 3.0) * elev_matrix[3] +
273297x
         5.0*(1.0-solar_elevation)*pow(solar_elevation, 4.0) * elev_matrix[4] +
274297x
         pow(solar_elevation, 5.0) * elev_matrix[5]);
275297x
    if(int_turbidity == 10)
276!
        return res;
277
278
    // alb 0 high turb
279297x
    elev_matrix = dataset + (6*(int_turbidity));
280
    //(1-t).^3* A1 + 3*(1-t).^2.*t * A2 + 3*(1-t) .* t .^ 2 * A3 + t.^3 * A4;
281297x
    res += (1.0-albedo) * (turbidity_rem) *
282297x
        ( pow(1.0-solar_elevation, 5.0) * elev_matrix[0] +
283297x
         5.0*pow(1.0-solar_elevation, 4.0)*solar_elevation * elev_matrix[1] +
284297x
         10.0*pow(1.0-solar_elevation, 3.0)*pow(solar_elevation, 2.0) * elev_matrix[2] +
285297x
         10.0*pow(1.0-solar_elevation, 2.0)*pow(solar_elevation, 3.0) * elev_matrix[3] +
286297x
         5.0*(1.0-solar_elevation)*pow(solar_elevation, 4.0) * elev_matrix[4] +
287297x
         pow(solar_elevation, 5.0) * elev_matrix[5]);
288
289
    // alb 1 high turb
290297x
    elev_matrix = dataset + (6*10 + 6*(int_turbidity));
291
    //(1-t).^3* A1 + 3*(1-t).^2.*t * A2 + 3*(1-t) .* t .^ 2 * A3 + t.^3 * A4;
292297x
    res += (albedo) * (turbidity_rem) *
293297x
        ( pow(1.0-solar_elevation, 5.0) * elev_matrix[0] +
294297x
         5.0*pow(1.0-solar_elevation, 4.0)*solar_elevation * elev_matrix[1] +
295297x
         10.0*pow(1.0-solar_elevation, 3.0)*pow(solar_elevation, 2.0) * elev_matrix[2] +
296297x
         10.0*pow(1.0-solar_elevation, 2.0)*pow(solar_elevation, 3.0) * elev_matrix[3] +
297297x
         5.0*(1.0-solar_elevation)*pow(solar_elevation, 4.0) * elev_matrix[4] +
298297x
         pow(solar_elevation, 5.0) * elev_matrix[5]);
299297x
    return res;
300
}
301
302117655440x
double ArHosekSkyModel_GetRadianceInternal(
303
        ArHosekSkyModelConfiguration  configuration,
304
        double                        theta,
305
        double                        gamma
306
        )
307
{
308117655440x
    const double expM = exp(configuration[4] * gamma);
309117655440x
    const double rayM = cos(gamma)*cos(gamma);
310117655440x
    const double mieM = (1.0 + cos(gamma)*cos(gamma)) / pow((1.0 + configuration[8]*configuration[8] - 2.0*configuration[8]*cos(gamma)), 1.5);
311117655440x
    const double zenith = sqrt(cos(theta));
312117655440x
    const double cos_factor = (cos(theta) + 0.01);
313117655440x
    const double factor1 = (1.0 + configuration[0] * exp(configuration[1] / cos_factor));
314117655440x
    const double factor2 =  (configuration[2] + configuration[3] * expM + configuration[5] * rayM + configuration[6] * mieM + configuration[7] * zenith);
315
316117655440x
    return factor1 * factor2;
317
}
318
319
// spectral version
320
32127x
ArHosekSkyModelState  * arhosekskymodelstate_alloc_init(
322
        const double  solar_elevation,
323
        const double  atmospheric_turbidity,
324
        const double  ground_albedo
325
        )
326
{
32727x
    ArHosekSkyModelState  * state = ALLOC(ArHosekSkyModelState);
328
32927x
    state->solar_radius = ( 0.51 DEGREES ) / 2.0;
33027x
    state->turbidity    = atmospheric_turbidity;
33127x
    state->albedo       = ground_albedo;
33227x
    state->elevation    = solar_elevation;
333
334324x
    for( unsigned int wl = 0; wl < 11; ++wl )
335
    {
336297x
        ArHosekSkyModel_CookConfiguration(
337297x
            datasets[wl],
338297x
            state->configs[wl],
339
            atmospheric_turbidity,
340
            ground_albedo,
341
            solar_elevation
342
            );
343
344297x
        state->radiances[wl] =
345594x
            ArHosekSkyModel_CookRadianceConfiguration(
346297x
                datasetsRad[wl],
347
                atmospheric_turbidity,
348
                ground_albedo,
349
                solar_elevation
350
                );
351
352297x
        state->emission_correction_factor_sun[wl] = 1.0;
353297x
        state->emission_correction_factor_sky[wl] = 1.0;
354
    }
355
35627x
    return state;
357
}
358
359
//   'blackbody_scaling_factor'
360
//
361
//   Fudge factor, computed in Mathematica, to scale the results of the
362
//   following function to match the solar radiance spectrum used in the
363
//   original simulation. The scaling is done so their integrals over the
364
//   range from 380.0 to 720.0 nanometers match for a blackbody temperature
365
//   of 5800 K.
366
//   Which leaves the original spectrum being less bright overall than the 5.8k
367
//   blackbody radiation curve if the ultra-violet part of the spectrum is
368
//   also considered. But the visible brightness should be very similar.
369
370
const double blackbody_scaling_factor = 3.19992 * 10E-11;
371
372
//   'art_blackbody_dd_value()' function
373
//
374
//   Blackbody radiance, Planck's formula
375
376!
double art_blackbody_dd_value(
377
        const double  temperature,
378
        const double  lambda
379
        )
380
{
381!
    double  c1 = 3.74177 * 10E-17;
382!
    double  c2 = 0.0143878;
383
    double  value;
384
385!
    value =   ( c1 / ( pow( lambda, 5.0 ) ) )
386!
            * ( 1.0 / ( exp( c2 / ( lambda * temperature ) ) - 1.0 ) );
387
388!
    return value;
389
}
390
391
//   'originalSolarRadianceTable[]'
392
//
393
//   The solar spectrum incident at the top of the atmosphere, as it was used
394
//   in the brute force path tracer that generated the reference results the
395
//   model was fitted to. We need this as the yardstick to compare any altered
396
//   Blackbody emission spectra for alien world stars to.
397
398
//   This is just the data from the Preetham paper, extended into the UV range.
399
400
const double originalSolarRadianceTable[] =
401
{
402
     7500.0,
403
    12500.0,
404
    21127.5,
405
    26760.5,
406
    30663.7,
407
    27825.0,
408
    25503.8,
409
    25134.2,
410
    23212.1,
411
    21526.7,
412
    19870.8
413
};
414
415!
ArHosekSkyModelState  * arhosekskymodelstate_alienworld_alloc_init(
416
        const double  solar_elevation,
417
        const double  solar_intensity,
418
        const double  solar_surface_temperature_kelvin,
419
        const double  atmospheric_turbidity,
420
        const double  ground_albedo
421
        )
422
{
423!
    ArHosekSkyModelState  * state = ALLOC(ArHosekSkyModelState);
424
425!
    state->turbidity    = atmospheric_turbidity;
426!
    state->albedo       = ground_albedo;
427!
    state->elevation    = solar_elevation;
428
429!
    for( unsigned int wl = 0; wl < 11; ++wl )
430
    {
431
        //   Basic init as for the normal scenario
432
433!
        ArHosekSkyModel_CookConfiguration(
434!
            datasets[wl],
435!
            state->configs[wl],
436
            atmospheric_turbidity,
437
            ground_albedo,
438
            solar_elevation
439
            );
440
441!
        state->radiances[wl] =
442!
            ArHosekSkyModel_CookRadianceConfiguration(
443!
                datasetsRad[wl],
444
                atmospheric_turbidity,
445
                ground_albedo,
446
                solar_elevation
447
                );
448
449
        //   The wavelength of this band in nanometers
450
451!
        double  owl = ( 320.0 + 40.0 * wl ) * 10E-10;
452
453
        //   The original intensity we just computed
454
455!
        double  osr = originalSolarRadianceTable[wl];
456
457
        //   The intensity of a blackbody with the desired temperature
458
        //   The fudge factor described above is used to make sure the BB
459
        //   function matches the used radiance data reasonably well
460
        //   in magnitude.
461
462
        double  nsr =
463!
              art_blackbody_dd_value(solar_surface_temperature_kelvin, owl)
464!
            * blackbody_scaling_factor;
465
466
        //   Correction factor for this waveband is simply the ratio of
467
        //   the two.
468
469!
        state->emission_correction_factor_sun[wl] = nsr / osr;
470
    }
471
472
    //   We then compute the average correction factor of all wavebands.
473
474
    //   Theoretically, some weighting to favour wavelengths human vision is
475
    //   more sensitive to could be introduced here - think V(lambda). But
476
    //   given that the whole effort is not *that* accurate to begin with (we
477
    //   are talking about the appearance of alien worlds, after all), simple
478
    //   averaging over the visible wavelenghts (! - this is why we start at
479
    //   WL #2, and only use 2-11) seems like a sane first approximation.
480
481!
    double  correctionFactor = 0.0;
482
483!
    for ( unsigned int i = 2; i < 11; i++ )
484
    {
485!
        correctionFactor +=
486!
            state->emission_correction_factor_sun[i];
487
    }
488
489
    //   This is the average ratio in emitted energy between our sun, and an
490
    //   equally large sun with the blackbody spectrum we requested.
491
492
    //   Division by 9 because we only used 9 of the 11 wavelengths for this
493
    //   (see above).
494
495!
    double  ratio = correctionFactor / 9.0;
496
497
    //   This ratio is then used to determine the radius of the alien sun
498
    //   on the sky dome. The additional factor 'solar_intensity' can be used
499
    //   to make the alien sun brighter or dimmer compared to our sun.
500
501!
    state->solar_radius =
502!
          ( sqrt( solar_intensity ) * TERRESTRIAL_SOLAR_RADIUS )
503!
        / sqrt( ratio );
504
505
    //   Finally, we have to reduce the scaling factor of the sky by the
506
    //   ratio used to scale the solar disc size. The rationale behind this is
507
    //   that the scaling factors apply to the new blackbody spectrum, which
508
    //   can be more or less bright than the one our sun emits. However, we
509
    //   just scaled the size of the alien solar disc so it is roughly as
510
    //   bright (in terms of energy emitted) as the terrestrial sun. So the sky
511
    //   dome has to be reduced in brightness appropriately - but not in an
512
    //   uniform fashion across wavebands. If we did that, the sky colour would
513
    //   be wrong.
514
515!
    for ( unsigned int i = 0; i < 11; i++ )
516
    {
517!
        state->emission_correction_factor_sky[i] =
518
              solar_intensity
519!
            * state->emission_correction_factor_sun[i] / ratio;
520
    }
521
522!
    return state;
523
}
524
52527x
void arhosekskymodelstate_free(
526
        ArHosekSkyModelState  * state
527
        )
528
{
52927x
    free(state);
530
}
531
532117655440x
double arhosekskymodel_radiance(
533
        ArHosekSkyModelState  * state,
534
        double                  theta,
535
        double                  gamma,
536
        double                  wavelength
537
        )
538
{
539117655440x
    int low_wl = (wavelength - 320.0 ) / 40.0;
540
541117655440x
    if ( low_wl < 0 || low_wl >= 11 )
542!
        return 0.0f;
543
544117655440x
    double interp = fmod((wavelength - 320.0 ) / 40.0, 1.0);
545
546
    double val_low =
547235310880x
          ArHosekSkyModel_GetRadianceInternal(
548117655440x
                state->configs[low_wl],
549
                theta,
550
                gamma
551
              )
552117655440x
        * state->radiances[low_wl]
553117655440x
        * state->emission_correction_factor_sky[low_wl];
554
555117655440x
    if ( interp < 1e-6 )
556117655440x
        return val_low;
557
558!
    double result = ( 1.0 - interp ) * val_low;
559
560!
    if ( low_wl+1 < 11 )
561
    {
562!
        result +=
563
              interp
564!
            * ArHosekSkyModel_GetRadianceInternal(
565!
                    state->configs[low_wl+1],
566
                    theta,
567
                    gamma
568
                  )
569!
            * state->radiances[low_wl+1]
570!
            * state->emission_correction_factor_sky[low_wl+1];
571
    }
572
573!
    return result;
574
}
575
576
577
// xyz and rgb versions
578
579!
ArHosekSkyModelState  * arhosek_xyz_skymodelstate_alloc_init(
580
        const double  turbidity,
581
        const double  albedo,
582
        const double  elevation
583
        )
584
{
585!
    ArHosekSkyModelState  * state = ALLOC(ArHosekSkyModelState);
586
587!
    state->solar_radius = TERRESTRIAL_SOLAR_RADIUS;
588!
    state->turbidity    = turbidity;
589!
    state->albedo       = albedo;
590!
    state->elevation    = elevation;
591
592!
    for( unsigned int channel = 0; channel < 3; ++channel )
593
    {
594!
        ArHosekSkyModel_CookConfiguration(
595!
            datasetsXYZ[channel],
596!
            state->configs[channel],
597
            turbidity,
598
            albedo,
599
            elevation
600
            );
601
602!
        state->radiances[channel] =
603!
        ArHosekSkyModel_CookRadianceConfiguration(
604!
            datasetsXYZRad[channel],
605
            turbidity,
606
            albedo,
607
            elevation
608
            );
609
    }
610
611!
    return state;
612
}
613
614
615!
ArHosekSkyModelState  * arhosek_rgb_skymodelstate_alloc_init(
616
        const double  turbidity,
617
        const double  albedo,
618
        const double  elevation
619
        )
620
{
621!
    ArHosekSkyModelState* state = ALLOC(ArHosekSkyModelState);
622
623!
    state->solar_radius = TERRESTRIAL_SOLAR_RADIUS;
624!
    state->turbidity    = turbidity;
625!
    state->albedo       = albedo;
626!
    state->elevation    = elevation;
627
628!
    for( unsigned int channel = 0; channel < 3; ++channel )
629
    {
630!
        ArHosekSkyModel_CookConfiguration(
631!
            datasetsRGB[channel],
632!
            state->configs[channel],
633
            turbidity,
634
            albedo,
635
            elevation
636
            );
637
638!
        state->radiances[channel] =
639!
        ArHosekSkyModel_CookRadianceConfiguration(
640!
            datasetsRGBRad[channel],
641
            turbidity,
642
            albedo,
643
            elevation
644
            );
645
    }
646
647!
    return state;
648
}
649
650!
double arhosek_tristim_skymodel_radiance(
651
    ArHosekSkyModelState  * state,
652
    double                  theta,
653
    double                  gamma,
654
    int                     channel
655
    )
656
{
657
    return
658!
        ArHosekSkyModel_GetRadianceInternal(
659!
            state->configs[channel],
660
            theta,
661
            gamma
662
            )
663!
        * state->radiances[channel];
664
}
665
666
const int pieces = 45;
667
const int order = 4;
668
6691197440x
double arhosekskymodel_sr_internal(
670
        ArHosekSkyModelState  * state,
671
        int                     turbidity,
672
        int                     wl,
673
        double                  elevation
674
        )
675
{
676
    int pos =
6771197440x
        (int) (pow(2.0*elevation / MATH_PI, 1.0/3.0) * pieces); // floor
678
6791197440x
    if ( pos > 44 ) pos = 44;
680
681
    const double break_x =
6821197440x
        pow(((double) pos / (double) pieces), 3.0) * (MATH_PI * 0.5);
683
6841197440x
    const double  * coefs =
6851197440x
        solarDatasets[wl] + (order * pieces * turbidity + order * (pos+1) - 1);
686
6871197440x
    double res = 0.0;
6881197440x
    const double x = elevation - break_x;
6891197440x
    double x_exp = 1.0;
690
6915987200x
    for (int i = 0; i < order; ++i)
692
    {
6934789760x
        res += x_exp * *coefs--;
6944789760x
        x_exp *= x;
695
    }
696
6971197440x
    return res * state->emission_correction_factor_sun[wl];
698
}
699
70058826440x
double arhosekskymodel_solar_radiance_internal2(
701
        ArHosekSkyModelState  * state,
702
        double                  wavelength,
703
        double                  elevation,
704
        double                  gamma
705
        )
706
{
707
    assert(
708
           wavelength >= 320.0
709
        && wavelength <= 720.0
710
        && state->turbidity >= 1.0
711
        && state->turbidity <= 10.0
712
        );
713
714
71558826440x
    const double sol_rad_sin = sin(state->solar_radius);
71658826440x
    const double ar2 = 1 / ( sol_rad_sin * sol_rad_sin );
71758826440x
    const double singamma = sin(gamma);
71858826440x
    double sc2 = 1.0 - ar2 * singamma * singamma;
71958826440x
    if (sc2 < 0.0 ) sc2 = 0.0;
72058826440x
    double sampleCosine = sqrt (sc2);
72158826440x
    if (sampleCosine == 0.) return 0.;
722
723299360x
    int     turb_low  = (int) state->turbidity - 1;
724299360x
    double  turb_frac = state->turbidity - (double) (turb_low + 1);
725
726299360x
    if ( turb_low == 9 )
727
    {
728!
        turb_low  = 8;
729!
        turb_frac = 1.0;
730
    }
731
732299360x
    int    wl_low  = (int) ((wavelength - 320.0) / 40.0);
733299360x
    double wl_frac = fmod(wavelength, 40.0) / 40.0;
734
735299360x
    if ( wl_low == 10 )
736
    {
73729936x
        wl_low = 9;
73829936x
        wl_frac = 1.0;
739
    }
740
741
    double direct_radiance =
742299360x
          ( 1.0 - turb_frac )
743598720x
        * (    (1.0 - wl_frac)
744299360x
             * arhosekskymodel_sr_internal(
745
                     state,
746
                     turb_low,
747
                     wl_low,
748
                     elevation
749
                   )
750299360x
           +   wl_frac
751299360x
             * arhosekskymodel_sr_internal(
752
                     state,
753
                     turb_low,
754
                     wl_low+1,
755
                     elevation
756
                   )
757
          )
758
      +   turb_frac
759598720x
        * (    ( 1.0 - wl_frac )
760299360x
             * arhosekskymodel_sr_internal(
761
                     state,
762
                     turb_low+1,
763
                     wl_low,
764
                     elevation
765
                   )
766299360x
           +   wl_frac
767299360x
             * arhosekskymodel_sr_internal(
768
                     state,
769
                     turb_low+1,
770
                     wl_low+1,
771
                     elevation
772
                   )
773
          );
774
775
    double ldCoefficient[6];
776
7772095520x
    for ( int i = 0; i < 6; i++ )
7781796160x
        ldCoefficient[i] =
7791796160x
              (1.0 - wl_frac) * limbDarkeningDatasets[wl_low  ][i]
7801796160x
            +        wl_frac  * limbDarkeningDatasets[wl_low+1][i];
781
782
    //   The following will be improved in future versions of the model:
783
    //   here, we directly use fitted 5th order polynomials provided by the
784
    //   astronomical community for the limb darkening effect. Astronomers need
785
    //   such accurate fittings for their predictions. However, this sort of
786
    //   accuracy is not really needed for CG purposes, so an approximated
787
    //   dataset based on quadratic polynomials will be provided in a future
788
    //   release.
789
790
    double  darkeningFactor =
791299360x
          ldCoefficient[0]
792299360x
        + ldCoefficient[1] * sampleCosine
793299360x
        + ldCoefficient[2] * pow( sampleCosine, 2.0 )
794299360x
        + ldCoefficient[3] * pow( sampleCosine, 3.0 )
795299360x
        + ldCoefficient[4] * pow( sampleCosine, 4.0 )
796299360x
        + ldCoefficient[5] * pow( sampleCosine, 5.0 );
797
798299360x
    direct_radiance *= darkeningFactor;
799
800299360x
    return direct_radiance;
801
}
802
80358826440x
double arhosekskymodel_solar_radiance(
804
        ArHosekSkyModelState  * state,
805
        double                  theta,
806
        double                  gamma,
807
        double                  wavelength
808
        )
809
{
810
    double  direct_radiance =
81158826440x
        arhosekskymodel_solar_radiance_internal2(
812
            state,
813
            wavelength,
814
            ((MATH_PI/2.0)-theta),
815
            gamma
816
            );
817
818
    double  inscattered_radiance =
81958826440x
        arhosekskymodel_radiance(
820
            state,
821
            theta,
822
            gamma,
823
            wavelength
824
            );
825
82658826440x
    return  direct_radiance + inscattered_radiance;
827
}
828
829
#ifdef __cplusplus
830
}
831
#endif
1
/*
2
This file is included in the skymodelr package, which is distributed as a
3
whole under GPL-3. The following upstream copyright and provenance notice is
4
preserved for attribution and compliance with upstream notice requirements.
5
*/
6
7
/**
8
 Copyright (c) 2015 Eric Bruneton
9
 All rights reserved.
10
11
 Redistribution and use in source and binary forms, with or without
12
 modification, are permitted provided that the following conditions are met:
13
14
 1. Redistributions of source code must retain the above copyright notice, this
15
 list of conditions and the following disclaimer.
16
17
 2. Redistributions in binary form must reproduce the above copyright notice,
18
 this list of conditions and the following disclaimer in the documentation
19
 and/or other materials provided with the distribution.
20
21
 3. Neither the name of the copyright holder nor the names of its contributors
22
 may be used to endorse or promote products derived from this software without
23
 specific prior written permission.
24
25
 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
26
 AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
27
 IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
28
 DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
29
 FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
30
 DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
31
 SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
32
 CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
33
 OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
34
 OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
35
*/
36
#include "atmosphere.h"
37
38
#include <vector>
39
40
namespace {
41
423x
IrradianceSpectrum NewSolarSpectrum() {
43
  // Values from "Reference Solar Spectral Irradiance: ASTM G-173", ETR column
44
  // (see http://rredc.nrel.gov/solar/spectra/am1.5/ASTMG173/ASTMG173.html),
45
  // summed and averaged in each bin (e.g. the value for 360nm is the average of
46
  // the ASTM G-173 values for all wavelengths between 360 and 371.75nm).
47
  static const float kSpectralIrradiance[40] = {
48
    1.13419, 1.09801, 1.03541, 1.45086, 1.72453, 1.654, 1.70536, 1.97393,
49
    2.03543, 2.00643, 1.95531, 1.95426, 1.92438, 1.82092, 1.88517, 1.85545,
50
    1.85083, 1.82758, 1.84475, 1.78771, 1.76683, 1.70858, 1.68278, 1.63849,
51
    1.59608, 1.52211, 1.52468, 1.47836, 1.4485, 1.40522, 1.35526, 1.32788,
52
    1.28834, 1.26938, 1.23241, 1.20345, 1.17087, 1.1344, 1.11012, 1.07147
53
  };
543x
  IrradianceSpectrum result;
55123x
  for (unsigned int i = 0; i < result.size(); ++i) {
56120x
    result[i] = kSpectralIrradiance[i] * watt_per_square_meter_per_nm;
57
  }
583x
  return result;
59
}
60
613x
ScatteringSpectrum NewRayleighScattering() {
62
  // Values from Table III in Penndorf 1957 "Tables of the Refractive Index for
63
  // Standard Air and the Rayleigh Scattering Coefficient for the Spectral
64
  // Region between 0.2 and 20.0 um and Their Application to Atmospheric Optics".
65
  static const float kPenndorf[48] = {
66
    70.45E-6, 62.82E-6, 56.20E-6, 50.43E-6, 45.40E-6, 40.98E-6, 37.08E-6,
67
    33.65E-6, 30.60E-6, 27.89E-6, 25.48E-6, 23.33E-6, 21.40E-6, 19.66E-6,
68
    18.10E-6, 16.69E-6, 15.42E-6, 14.26E-6, 13.21E-6, 12.26E-6, 11.39E-6,
69
    10.60E-6, 9.876E-6, 9.212E-6, 8.604E-6, 8.045E-6, 7.531E-6, 7.057E-6,
70
    6.620E-6, 6.217E-6, 5.844E-6, 5.498E-6, 5.178E-6, 4.881E-6, 4.605E-6,
71
    4.348E-6, 4.109E-6, 3.886E-6, 3.678E-6, 3.484E-6, 3.302E-6, 3.132E-6,
72
    2.973E-6, 2.824E-6, 2.684E-6, 2.583E-6, 2.481E-6, 2.380E-6
73
  };
743x
  std::vector<ScatteringCoefficient> penndorf_samples;
75147x
  for (int i = 0; i < 48; ++i) {
76
    // The above values are for T_0=0 deg C. For T=15 deg C, a correction factor
77
    // T_0 / T must be applied (Eq. (12) in Penndorf paper).
78144x
    constexpr double T_0 = 273.16;
79144x
    constexpr double T = T_0 + 15.0;
80144x
    penndorf_samples.push_back(kPenndorf[i] * (T_0 / T) / m);
81
  }
826x
  return ScatteringSpectrum(360.0 * nm, 830.0 * nm, penndorf_samples);
83
}
84
856x
ScatteringSpectrum NewMieExtinction(double angstrom_alpha,
86
    double angstrom_beta) {
876x
  ScatteringSpectrum mie;
88246x
  for (unsigned int i = 0; i < mie.size(); ++i) {
89240x
    double lambda = mie.GetSample(i).to(1000.0 * nm);
90240x
    mie[i] = angstrom_beta * pow(lambda, -angstrom_alpha) / MieScaleHeight;
91
  }
926x
  return mie;
93
}
94
953x
ScatteringSpectrum NewMieScattering(double angstrom_alpha,
96
    double angstrom_beta) {
973x
  const double kSingleScatteringAlbedo = 0.8;
98
  return
993x
      NewMieExtinction(angstrom_alpha, angstrom_beta) * kSingleScatteringAlbedo;
100
}
101
1023x
DimensionlessSpectrum NewGroundAlbedo() {
103
  // Grass spectral albedo from Uwe Feister and Rolf Grewe, "Spectral albedo
104
  // measurements in the UV and visible region over different types of
105
  // surfaces", Photochemistry and Photobiology, 62, 736-744, 1995.
106
  static const float kGrassAlbedo[45] = {
107
    0.018, 0.019, 0.019, 0.020, 0.022, 0.024, 0.027, 0.029, 0.030, 0.031, 0.032,
108
    0.032, 0.032, 0.033, 0.035, 0.040, 0.055, 0.073, 0.084, 0.089, 0.089, 0.079,
109
    0.069, 0.063, 0.061, 0.057, 0.052, 0.051, 0.048, 0.042, 0.039, 0.035, 0.035,
110
    0.043, 0.087, 0.156, 0.234, 0.334, 0.437, 0.513, 0.553, 0.571, 0.579, 0.581,
111
    0.587
112
  };
1133x
  std::vector<Number> grass_albedo_samples;
114138x
  for (int i = 0; i < 45; ++i) {
115135x
    grass_albedo_samples.push_back(kGrassAlbedo[i]);
116
  }
1176x
  return DimensionlessSpectrum(360.0 * nm, 800.0 * nm, grass_albedo_samples);
118
}
119
120
const IrradianceSpectrum solar_spectrum = NewSolarSpectrum();
121
const ScatteringSpectrum rayleigh_scattering = NewRayleighScattering();
122
const ScatteringSpectrum mie_extinction =
123
    NewMieExtinction(MieAngstromAlpha, MieAngstromBeta);
124
const ScatteringSpectrum mie_scattering =
125
    NewMieScattering(MieAngstromAlpha, MieAngstromBeta);
126
const DimensionlessSpectrum ground_albedo = NewGroundAlbedo();
127
128
}  // anonymous namespace
129
130!
const IrradianceSpectrum& SolarSpectrum() { return solar_spectrum; }
131!
const ScatteringSpectrum& RayleighScattering() { return rayleigh_scattering; }
132!
const ScatteringSpectrum& MieExtinction() { return mie_extinction; }
133!
const ScatteringSpectrum& MieScattering() { return mie_scattering; }
134
135!
ScatteringSpectrum MieExtinction(double angstrom_alpha, double angstrom_beta) {
136!
  return NewMieExtinction(angstrom_alpha, angstrom_beta);
137
}
138
139!
ScatteringSpectrum MieScattering(double angstrom_alpha, double angstrom_beta) {
140!
  return NewMieScattering(angstrom_alpha, angstrom_beta);
141
}
142
143!
InverseSolidAngle RayleighPhaseFunction(Angle scattering_angle) {
144!
  return RayleighPhaseFunction(cos(scattering_angle));
145
}
146
147!
InverseSolidAngle RayleighPhaseFunction(Number scattering_angle_cosine) {
148!
  constexpr InverseSolidAngle kRayleigh =
149
      3.0 / (16.0 * PI) * InverseSolidAngle::Unit();
150!
  return kRayleigh * (1.0 + scattering_angle_cosine * scattering_angle_cosine);
151
}
152
153!
InverseSolidAngle MiePhaseFunction(Angle scattering_angle) {
154!
  return MiePhaseFunction(cos(scattering_angle));
155
}
156
157!
InverseSolidAngle MiePhaseFunction(Number scattering_angle_cosine) {
158!
  constexpr double g = MiePhaseFunctionG;
159!
  constexpr InverseSolidAngle kMie = 3.0 / (8.0 * PI) *
160
      (1.0 - g * g) / (2.0 + g * g) * InverseSolidAngle::Unit();
161!
  return kMie * (1.0 + scattering_angle_cosine * scattering_angle_cosine) /
162!
      pow(1.0 + g * g - 2.0 * g * scattering_angle_cosine, 1.5);
163
}
164
165!
InverseSolidAngle MiePhaseFunction(double g, Number scattering_angle_cosine) {
166!
  const InverseSolidAngle kMie = 3.0 / (8.0 * PI) *
167!
      (1.0 - g * g) / (2.0 + g * g) * InverseSolidAngle::Unit();
168!
  return kMie * (1.0 + scattering_angle_cosine * scattering_angle_cosine) /
169!
      pow(1.0 + g * g - 2.0 * g * scattering_angle_cosine, 1.5);
170
}
171
172!
const DimensionlessSpectrum& GroundAlbedo() { return ground_albedo; }
173
174!
int Atmosphere::GetOriginalNumberOfWavelengths() const {
175!
  return DimensionlessSpectrum::SIZE;
176
}
177
178!
IrradianceSpectrum Atmosphere::GetSkyIrradiance(Length altitude,
179
    Angle sun_zenith) const {
180
  IrradianceSpectrum result =
181!
      IrradianceSpectrum(0.0 * watt_per_square_meter_per_nm);
182!
  const unsigned int N = 100;
183!
  for (unsigned int i = 0; i < N / 2; ++i) {
184!
    Angle view_zenith = (i + 0.5) * pi / N;
185!
    Number cos_view_zenith = cos(view_zenith);
186!
    Number sin_view_zenith = sin(view_zenith);
187!
    for (unsigned int j = 0; j < 2 * N; ++j) {
188!
      Angle view_azimuth = j * pi / N;
189
      RadianceSpectrum incident_spectrum =
190!
          GetSkyRadiance(altitude, sun_zenith, view_zenith, view_azimuth);
191!
      SolidAngle domega = sin_view_zenith * (PI / N) * (PI / N) * sr;
192!
      result = result + incident_spectrum * cos_view_zenith * domega;
193
    }
194
  }
195!
  return result;
196
}
197
198!
RadianceSpectrum Atmosphere::GetSkyRadiance(Length altitude, Angle sun_zenith,
199
    Angle sun_azimuth, Angle view_zenith, Angle view_azimuth) const {
200!
  return GetSkyRadiance(
201!
      altitude, sun_zenith, view_zenith, view_azimuth - sun_azimuth);
202
}
203
204!
Angle Atmosphere::GetViewSunAngle(Angle sun_zenith, Angle view_zenith,
205
      Angle view_sun_azimuth) {
206!
  return acos(cos(view_sun_azimuth) * sin(view_zenith) * sin(sun_zenith) +
207!
      cos(view_zenith) * cos(sun_zenith));
208
}
1
/*
2
This file is included in the skymodelr package, which is distributed as a
3
whole under GPL-3. The following upstream copyright and provenance notice is
4
preserved for attribution and compliance with upstream notice requirements.
5
*/
6
7
/**
8
 * Copyright (c) 2016 Eric Bruneton
9
 * All rights reserved.
10
 *
11
 * Redistribution and use in source and binary forms, with or without
12
 * modification, are permitted provided that the following conditions
13
 * are met:
14
 * 1. Redistributions of source code must retain the above copyright
15
 *    notice, this list of conditions and the following disclaimer.
16
 * 2. Redistributions in binary form must reproduce the above copyright
17
 *    notice, this list of conditions and the following disclaimer in the
18
 *    documentation and/or other materials provided with the distribution.
19
 * 3. Neither the name of the copyright holders nor the names of its
20
 *    contributors may be used to endorse or promote products derived from
21
 *    this software without specific prior written permission.
22
 *
23
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
24
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
25
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
26
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
27
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
28
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
29
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
30
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
31
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
32
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
33
 * THE POSSIBILITY OF SUCH DAMAGE.
34
 */
35
36
#ifndef MATH_SCALAR_H_
37
#define MATH_SCALAR_H_
38
39
#include <algorithm>
40
#include <cmath>
41
42
namespace dimensional {
43
44
// Internal class used to differentiate two Scalar constructors below.
45
struct Double {
46
  const double value;
4719698x
  explicit inline constexpr Double(double value) : value(value) {}
48
};
49
50
// A scalar value with a dimension combining up to five base units (length,
51
// mass, time, etc). The template parameters are the exponents of the base units
52
// in the scalar value dimension. For instance, if U1 corresponds to length and
53
// U3 to time, a speed is a Scalar<1, 0, -1, 0, 0> (length divided by time), an
54
// area is a Scalar<2, 0, 0, 0, 0>, etc. The semantics of the base units is not
55
// defined by this template so that it can be used with various unit systems.
56
// NOTES:
57
// - We intentionally do not provide a constructor from a literal value, except
58
// for dimensionless scalars, in order to force the use of an explicit unit
59
// (e.g. "Length l = 3.0 * m;").
60
// - Likewise, we intentionally do not provide a noarg accessor, except for
61
// dimensionless scalars, in order to force the use of an explicit unit when
62
// accessing a value (e.g. "double value = l.to(km);").
63
template<int U1, int U2, int U3, int U4, int U5>
64
class Scalar {
65
 public:
661440x
  Scalar() {}
671440x
  inline constexpr Scalar(double value) : value_(value) {
68
    static_assert(
69
        U1 == 0 && U2 == 0 && U3 == 0 && U4 == 0 && U5 == 0,
70
        "This constructor is valid only for dimensionless values.");
71
  }
722400x
  static constexpr Scalar Unit() { return Scalar(Double(1.0)); }
73
741878x
  inline constexpr double operator()() const {
75
    static_assert(
76
        U1 == 0 && U2 == 0 && U3 == 0 && U4 == 0 && U5 == 0,
77
        "This operator is valid onlyfor dimensionless values.");
781878x
    return value_;
79
  }
80
81240x
  inline constexpr double to(const Scalar<U1, U2, U3, U4, U5> unit) const {
82240x
    return value_ / unit.value_;
83
  }
84
851440x
  inline Scalar& operator=(const Scalar rhs) {
861440x
    value_ = rhs.value_;
871440x
    return *this;
88
  }
89
90
  inline Scalar& operator+=(const Scalar rhs) {
91
    value_ += rhs.value_;
92
    return *this;
93
  }
94
953723x
  inline constexpr Scalar operator+(const Scalar rhs) const {
963723x
    return Scalar(Double(value_ + rhs.value_));
97
  }
98
99
  inline constexpr Scalar operator-() const {
100
    return Scalar(Double(-value_));
101
  }
102
1031878x
  inline constexpr Scalar operator-(const Scalar rhs) const {
1041878x
    return Scalar(Double(value_ - rhs.value_));
105
  }
106
1077566x
  inline constexpr Scalar operator*(double rhs) const {
1087566x
    return Scalar(Double(value_ * rhs));
109
  }
110
111
  template<int V1, int V2, int V3, int V4, int V5>
112
  inline constexpr
113!
  Scalar<U1 + V1, U2 + V2, U3 + V3, U4 + V4, U5 + V5> operator*(
114
      const Scalar<V1, V2, V3, V4, V5> rhs) const {
115!
    return Scalar<U1 + V1, U2 + V2, U3 + V3, U4 + V4, U5 + V5>(
116!
        Double(value_ * rhs.value_));
117
  }
118
119!
  inline constexpr Scalar operator/(double rhs) const {
120!
    return Scalar(Double(value_ / rhs));
121
  }
122
123
  template<int V1, int V2, int V3, int V4, int V5>
124
  inline constexpr
125939x
  Scalar<U1 - V1, U2 - V2, U3 - V3, U4 - V4, U5 - V5> operator/(
126
      const Scalar<V1, V2, V3, V4, V5> rhs) const {
127939x
    return Scalar<U1 - V1, U2 - V2, U3 - V3, U4 - V4, U5 - V5>(
1281878x
        Double(value_ / rhs.value_));
129
  }
130
131
  inline bool operator==(const Scalar<U1, U2, U3, U4, U5> rhs) const {
132
    return value_ == rhs.value_;
133
  }
134
1355640x
  inline bool operator<(const Scalar<U1, U2, U3, U4, U5> rhs) const {
1365640x
    return value_ < rhs.value_;
137
  }
138
139960x
  inline bool operator<=(const Scalar<U1, U2, U3, U4, U5> rhs) const {
140960x
    return value_ <= rhs.value_;
141
  }
142
143!
  inline bool operator>(const Scalar<U1, U2, U3, U4, U5> rhs) const {
144!
    return value_ > rhs.value_;
145
  }
146
147945x
  inline bool operator>=(const Scalar<U1, U2, U3, U4, U5> rhs) const {
148945x
    return value_ >= rhs.value_;
149
  }
150
151
 private:
152
  // Private constructor, which can construct a value of any dimension from
153
  // a double literal. In order to diffentiate this constructor from the
154
  // implicit constructor above, we use the auxilliary internal class "Double".
15519698x
  explicit inline constexpr Scalar(const Double value) : value_(value.value) {}
156
157
  double value_;
158
159
  template<int V1, int V2, int V3, int V4, int V5>
160
  friend class Scalar;
161
162
  friend constexpr Scalar<0, 0, 0, 0, 0> operator+(
163
      double lhs, const Scalar<0, 0, 0, 0, 0> rhs);
164
165
  friend constexpr Scalar<0, 0, 0, 0, 0> operator+(
166
      const Scalar<0, 0, 0, 0, 0> lhs, double rhs);
167
168
  friend constexpr Scalar<0, 0, 0, 0, 0> operator-(
169
      double lhs, const Scalar<0, 0, 0, 0, 0> rhs);
170
171
  friend constexpr Scalar<0, 0, 0, 0, 0> operator-(
172
      const Scalar<0, 0, 0, 0, 0> lhs, double rhs);
173
174
  template<int V1, int V2, int V3, int V4, int V5>
175
  friend constexpr Scalar<V1, V2, V3, V4, V5> operator*(
176
      double lhs, const Scalar<V1, V2, V3, V4, V5> rhs);
177
178
  template<int V1, int V2, int V3, int V4, int V5>
179
  friend constexpr Scalar<-V1, -V2, -V3, -V4, -V5> operator/(
180
      double lhs, const Scalar<V1, V2, V3, V4, V5> rhs);
181
182
  friend bool operator<(const Scalar<0, 0, 0, 0, 0> lhs, double rhs);
183
  friend bool operator<(double lhs, const Scalar<0, 0, 0, 0, 0> rhs);
184
  friend bool operator<=(const Scalar<0, 0, 0, 0, 0> lhs, double rhs);
185
  friend bool operator<=(double lhs, const Scalar<0, 0, 0, 0, 0> rhs);
186
  friend bool operator>(const Scalar<0, 0, 0, 0, 0> lhs, double rhs);
187
  friend bool operator>(double lhs, const Scalar<0, 0, 0, 0, 0> rhs);
188
  friend bool operator>=(const Scalar<0, 0, 0, 0, 0> lhs, double rhs);
189
  friend bool operator>=(double lhs, const Scalar<0, 0, 0, 0, 0> rhs);
190
191
  friend constexpr Scalar<0, 0, 0, 0, 0> exp(const Scalar<0, 0, 0, 0, 0> x);
192
  friend Scalar<0, 0, 0, 0, 0> floor(const Scalar<0, 0, 0, 0, 0> x);
193
  friend constexpr Scalar<0, 0, 0, 0, 0> log(const Scalar<0, 0, 0, 0, 0> x);
194
  friend Scalar<0, 0, 0, 0, 0> max(const Scalar<0, 0, 0, 0, 0> x, double y);
195
  friend Scalar<0, 0, 0, 0, 0> max(double x, const Scalar<0, 0, 0, 0, 0> y);
196
  friend Scalar<0, 0, 0, 0, 0> min(const Scalar<0, 0, 0, 0, 0> x, double y);
197
  friend Scalar<0, 0, 0, 0, 0> min(double x, const Scalar<0, 0, 0, 0, 0> y);
198
  friend Scalar<0, 0, 0, 0, 0> pow(const Scalar<0, 0, 0, 0, 0> x,
199
      const Scalar<0, 0, 0, 0, 0> y);
200
  friend Scalar<0, 0, 0, 0, 0> pow(double x, const Scalar<0, 0, 0, 0, 0> y);
201
  friend Scalar<0, 0, 0, 0, 0> pow(const Scalar<0, 0, 0, 0, 0> x, double y);
202
  friend Scalar<0, 0, 0, 0, 0> sqrt(const Scalar<0, 0, 0, 0, 0> x);
203
  template<int V1, int V2, int V3, int V4, int V5>
204
  friend constexpr Scalar<V1 / 2, V2 / 2, V3 / 2, V4 / 2, V5 / 2> sqrt(
205
      const Scalar<V1, V2, V3, V4, V5> x);
206
};
207
208
typedef Scalar<0, 0, 0, 0, 0> Dimensionless;
209
typedef Scalar<0, 0, 0, 0, 0> Number;
210
211!
inline constexpr Number operator+(double lhs, const Number rhs) {
212!
  return lhs + rhs.value_;
213
}
214
215
inline constexpr Number operator+(const Number lhs, double rhs) {
216
  return lhs.value_ + rhs;
217
}
218
219!
inline constexpr Number operator-(double lhs, const Number rhs) {
220!
  return lhs - rhs.value_;
221
}
222
223
inline constexpr Number operator-(const Number lhs, double rhs) {
224
  return lhs.value_ - rhs;
225
}
226
227
inline bool operator<(const Number lhs, double rhs) {
228
  return lhs.value_ < rhs;
229
}
230
231
inline bool operator<(double lhs, const Number rhs) {
232
  return lhs < rhs.value_;
233
}
234
235
inline bool operator<=(const Number lhs, double rhs) {
236
  return lhs.value_ <= rhs;
237
}
238
239
inline bool operator<=(double lhs, const Number rhs) {
240
  return lhs <= rhs.value_;
241
}
242
243
inline bool operator>(const Number lhs, double rhs) {
244
  return lhs.value_ > rhs;
245
}
246
247
inline bool operator>(double lhs, const Number rhs) {
248
  return lhs > rhs.value_;
249
}
250
251
inline bool operator>=(const Number lhs, double rhs) {
252
  return lhs.value_ >= rhs;
253
}
254
255
inline bool operator>=(double lhs, const Number rhs) {
256
  return lhs >= rhs.value_;
257
}
258
259
template<int U1, int U2, int U3, int U4, int U5>
2602808x
inline constexpr Scalar<U1, U2, U3, U4, U5> operator*(
261
    double lhs, const Scalar<U1, U2, U3, U4, U5> rhs) {
2622808x
  return Scalar<U1, U2, U3, U4, U5>(Double(lhs * rhs.value_));
263
}
264
265
template<int U1, int U2, int U3, int U4, int U5>
266384x
inline constexpr Scalar<-U1, -U2, -U3, -U4, -U5> operator/(
267
    double lhs, const Scalar<U1, U2, U3, U4, U5> rhs) {
268384x
  return Scalar<-U1, -U2, -U3, -U4, -U5>(Double(lhs / rhs.value_));
269
}
270
271
inline constexpr Number exp(const Number x) { return std::exp(x()); }
272
inline Number floor(const Number x) { return std::floor(x()); }
273
inline constexpr Number log(const Number x) { return std::log(x()); }
274
inline Number max(const Number x, double y) { return std::max(x(), y); }
275
inline Number max(double x, const Number y) { return std::max(x, y()); }
276
inline Number min(const Number x, double y) { return std::min(x(), y); }
277
inline Number min(double x, const Number y) { return std::min(x, y()); }
278
inline Number pow(const Number x, const Number y) { return std::pow(x(), y()); }
279!
inline Number pow(const Number x, double y) { return std::pow(x(), y); }
280
inline Number pow(double x, const Number y) { return std::pow(x, y()); }
281
inline Number sqrt(const Number x) { return std::sqrt(x()); }
282
283
template<int U1, int U2, int U3, int U4, int U5>
284
constexpr Scalar<U1 / 2, U2 / 2, U3 / 2, U4 / 2, U5 / 2> sqrt(
285
    const Scalar<U1, U2, U3, U4, U5> x) {
286
  return Scalar<U1 / 2, U2 / 2, U3 / 2, U4 / 2, U5 / 2>(
287
      Double(std::sqrt(x.value_)));
288
}
289
290
template<typename T>
291
T mod(T x, T y) { return x - y * floor(x / y); }
292
inline double mod(double x, double y) { return x - y * std::floor(x / y); }
293
inline Number mod(Number x, double y) { return x - y * floor(x / y); }
294
inline Number mod(double x, Number y) { return x - y * floor(x / y); }
295
296
template<typename T>
2972784x
T lerp(T a, T b, double x) { return a * (1.0 - x) + b * x; }
298
299
template<typename T>
300
T clamp(T x, T min, T max) { return std::max(min, std::min(max, x)); }
301
302
template<typename T>
303
T smoothstep(T edge0, T edge1, T x) {
304
  x = clamp((x - edge0) / (edge1 - edge0), T(0.0), T(1.0));
305
  return x * x * (3.0 - 2.0 * x);
306
}
307
308
}  // namespace dimensional
309
310
#endif  // MATH_SCALAR_H_
1
/*
2
This file is included in the skymodelr package, which is distributed as a
3
whole under GPL-3. The following upstream copyright and provenance notice is
4
preserved for attribution and compliance with upstream notice requirements.
5
*/
6
7
/**
8
 * Copyright (c) 2016 Eric Bruneton
9
 * All rights reserved.
10
 *
11
 * Redistribution and use in source and binary forms, with or without
12
 * modification, are permitted provided that the following conditions
13
 * are met:
14
 * 1. Redistributions of source code must retain the above copyright
15
 *    notice, this list of conditions and the following disclaimer.
16
 * 2. Redistributions in binary form must reproduce the above copyright
17
 *    notice, this list of conditions and the following disclaimer in the
18
 *    documentation and/or other materials provided with the distribution.
19
 * 3. Neither the name of the copyright holders nor the names of its
20
 *    contributors may be used to endorse or promote products derived from
21
 *    this software without specific prior written permission.
22
 *
23
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
24
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
25
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
26
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
27
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
28
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
29
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
30
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
31
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
32
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
33
 * THE POSSIBILITY OF SUCH DAMAGE.
34
 */
35
36
#ifndef MATH_SCALAR_FUNCTION_H_
37
#define MATH_SCALAR_FUNCTION_H_
38
39
#include <algorithm>
40
#include <cassert>
41
#include <vector>
42
43
#include "../math/scalar.h"
44
45
namespace dimensional {
46
47
// A function from scalars of type Scalar<U1, U2, U3, U4, U5> to scalars of type
48
// Scalar<V1, V2, V3, V4, V5>, represented with N uniformly distributed samples
49
// between MIN and MAX in the input domain, and linearly interpolated in
50
// between.
51
template<
52
    int U1, int U2, int U3, int U4, int U5,
53
    int V1, int V2, int V3, int V4, int V5,
54
    unsigned int N, int MIN, int MAX>
55
class ScalarFunction {
56
 public:
57
  constexpr static unsigned int SIZE = N;
58
  typedef Scalar<U1, U2, U3, U4, U5> input_type;
59
  typedef Scalar<V1, V2, V3, V4, V5> output_type;
60
61492x
  ScalarFunction() {}
62
63!
  explicit ScalarFunction(const output_type& constant_value) {
64!
    for (unsigned int i = 0; i < N; ++i) {
65!
      value_[i] = constant_value;
66
    }
67
  }
68
69
  ScalarFunction(const std::vector<float>& sampled_values, output_type unit) {
70
    for (unsigned int i = 0; i < N; ++i) {
71
      value_[i] = (i < sampled_values.size() ? sampled_values[i] : 0.0) * unit;
72
    }
73
  }
74
75
  ScalarFunction(const ScalarFunction& rhs) {
76
    for (unsigned int i = 0; i < N; ++i) {
77
      value_[i] = rhs.value_[i];
78
    }
79
  }
80
81
  // Creates a new function from the given values, sampled at the given sampling
82
  // points. The given vectors must have the same size n and sampling_points
83
  // must be sorted in increasing order. The input function is supposed constant
84
  // outside the sampling interval (i.e. for x < sampling_points[0] and for
85
  // x > sampling_points[n - 1]) and is linearly interpolated between samples.
86
  ScalarFunction(const std::vector<input_type>& sampling_points,
87
      const std::vector<output_type>& sampled_values) {
88
    Init(sampling_points, sampled_values);
89
  }
90
91
  // Creates a new function from the given values, uniformly sampled from
92
  // 'min_input' and 'max_input' (inclusive). The input function is supposed
93
  // constant outside the sampling interval (i.e. for x < min_input and for
94
  // x > max_input) and is linearly interpolated between samples.
9524x
  ScalarFunction(input_type min_input, input_type max_input,
96984x
      const std::vector<output_type> values) {
9724x
    std::vector<input_type> sampling_points;
981608x
    for (unsigned int i = 0; i < values.size(); ++i) {
991584x
      sampling_points.push_back(
1003168x
          lerp(min_input, max_input, i / (values.size() - 1.0)));
101
    }
10224x
    Init(sampling_points, values);
103
  }
104
105
  std::vector<double> to(output_type unit) {
106
    std::vector<double> result;
107
    for (unsigned int i = 0; i < N; ++i) {
108
      result.push_back(value_[i].to(unit));
109
    }
110
    return result;
111
  }
112
113!
  ScalarFunction& operator=(const ScalarFunction& rhs) {
114!
    for (unsigned int i = 0; i < N; ++i) {
115!
      value_[i] = rhs.value_[i];
116
    }
117!
    return *this;
118
  }
119
120
  ScalarFunction& operator+=(const ScalarFunction& rhs) {
121
    for (unsigned int i = 0; i < N; ++i) {
122
      value_[i] += rhs.value_[i];
123
    }
124
    return *this;
125
  }
126
127!
  ScalarFunction operator+(const ScalarFunction& rhs) const {
128!
    ScalarFunction result;
129!
    for (unsigned int i = 0; i < N; ++i) {
130!
      result.value_[i] = value_[i] + rhs.value_[i];
131
    }
132!
    return result;
133
  }
134
135
  ScalarFunction operator-() const {
136
    ScalarFunction result;
137
    for (unsigned int i = 0; i < N; ++i) {
138
      result.value_[i] = -value_[i];
139
    }
140
    return result;
141
  }
142
143
  ScalarFunction operator-(const ScalarFunction& rhs) const {
144
    ScalarFunction result;
145
    for (unsigned int i = 0; i < N; ++i) {
146
      result.value_[i] = value_[i] - rhs.value_[i];
147
    }
148
    return result;
149
  }
150
1513x
  ScalarFunction operator*(double rhs) const {
1523x
    ScalarFunction result;
153123x
    for (unsigned int i = 0; i < N; ++i) {
154120x
      result.value_[i] = value_[i] * rhs;
155
    }
1563x
    return result;
157
  }
158
159
  template<int W1, int W2, int W3, int W4, int W5>
160
  ScalarFunction<
161
      U1, U2, U3, U4, U5,
162
      V1 + W1, V2 + W2, V3 + W3, V4 + W4, V5 + W5,
163
      N, MIN, MAX>
164!
  operator*(Scalar<W1, W2, W3, W4, W5> rhs) const {
165
    ScalarFunction<
166
        U1, U2, U3, U4, U5,
167
        V1 + W1, V2 + W2, V3 + W3, V4 + W4, V5 + W5,
168!
        N, MIN, MAX> result;
169!
    for (unsigned int i = 0; i < N; ++i) {
170!
      result[i] = value_[i] * rhs;
171
    }
172!
    return result;
173
  }
174
175
  template<int W1, int W2, int W3, int W4, int W5>
176
  ScalarFunction<
177
      U1, U2, U3, U4, U5,
178
      V1 + W1, V2 + W2, V3 + W3, V4 + W4, V5 + W5,
179
      N, MIN, MAX>
180!
  operator*(const ScalarFunction<
181
      U1, U2, U3, U4, U5, W1, W2, W3, W4, W5, N, MIN, MAX>& rhs) const {
182
    ScalarFunction<
183
        U1, U2, U3, U4, U5,
184
        V1 + W1, V2 + W2, V3 + W3, V4 + W4, V5 + W5,
185!
        N, MIN, MAX> result;
186!
    for (unsigned int i = 0; i < N; ++i) {
187!
      result[i] = value_[i] * rhs[i];
188
    }
189!
    return result;
190
  }
191
192
  template<int W1, int W2, int W3, int W4, int W5>
193
  ScalarFunction<
194
      U1, U2, U3, U4, U5,
195
      V1 - W1, V2 - W2, V3 - W3, V4 - W4, V5 - W5,
196
      N, MIN, MAX>
197
  operator/(const ScalarFunction<
198
      U1, U2, U3, U4, U5, W1, W2, W3, W4, W5, N, MIN, MAX>& rhs) const {
199
    ScalarFunction<
200
        U1, U2, U3, U4, U5,
201
        V1 - W1, V2 - W2, V3 - W3, V4 - W4, V5 - W5,
202
        N, MIN, MAX> result;
203
    for (unsigned int i = 0; i < N; ++i) {
204
      result[i] = value_[i] / rhs[i];
205
    }
206
    return result;
207
  }
208
209369x
  inline unsigned int size() const {
210369x
    return N;
211
  }
212
213!
  inline const output_type operator[](int index) const {
214!
    return value_[index];
215
  }
216
217360x
  inline output_type& operator[](int index) {
218360x
    return value_[index];
219
  }
220
2211200x
  inline input_type GetSample(int sample_index) const {
2221200x
    double u = static_cast<double>(sample_index) / N;
2231200x
    return lerp(MIN * input_type::Unit(), MAX * input_type::Unit(), u);
224
  }
225
226!
  const output_type operator()(input_type x) const {
227!
    double u = (x.to(input_type::Unit()) - MIN) / (MAX - MIN) * N;
228!
    int i = std::floor(u);
229!
    u -= i;
230!
    int i0 = std::max(0, std::min(static_cast<int>(N) - 1, i));
231!
    int i1 = std::max(0, std::min(static_cast<int>(N) - 1, i + 1));
232!
    return value_[i0] * (1.0 - u) + value_[i1] * u;
233
  }
234
235
 private:
23624x
  void Init(const std::vector<input_type>& sampling_points,
237
      const std::vector<output_type>& sampled_values) {
238
    assert(sampling_points.size() == sampled_values.size());
239984x
    for (unsigned int i = 0; i < N; ++i) {
240960x
      input_type x = GetSample(i);
241
      // Find the two nearest sampling points around 'x' using binary search and
242
      // return the corresponding sampled values, linearly interpolated.
243960x
      int min_index = 0;
244960x
      int max_index = sampling_points.size() - 1;
245960x
      if (x <= sampling_points[min_index]) {
24615x
        value_[i] = sampled_values[min_index];
24721x
        continue;
248
      }
249945x
      if (x >= sampling_points[max_index]) {
2506x
        value_[i] = sampled_values[max_index];
2516x
        continue;
252
      }
2536579x
      while (max_index - min_index > 1) {
2545640x
        int mid_index = (min_index + max_index) / 2;
2555640x
        if (x < sampling_points[mid_index]) {
2562691x
          max_index = mid_index;
257
        } else {
2582949x
          min_index = mid_index;
259
        }
260
      }
261939x
      Number u = (x - sampling_points[min_index]) /
262939x
          (sampling_points[max_index] - sampling_points[min_index]);
2631878x
      value_[i] = sampled_values[min_index] * (1.0 - u()) +
264939x
          sampled_values[max_index] * u();
265
    }
266
  }
267
268
  output_type value_[N];
269
};
270
271
template<
272
    int U1, int U2, int U3, int U4, int U5,
273
    int V1, int V2, int V3, int V4, int V5,
274
    unsigned int N, int MIN, int MAX>
275
ScalarFunction<U1, U2, U3, U4, U5, V1, V2, V3, V4, V5, N, MIN, MAX>
276
min(const ScalarFunction<
277
        U1, U2, U3, U4, U5, V1, V2, V3, V4, V5, N, MIN, MAX>& a,
278
    const ScalarFunction<
279
        U1, U2, U3, U4, U5, V1, V2, V3, V4, V5, N, MIN, MAX>& b) {
280
  ScalarFunction<U1, U2, U3, U4, U5, V1, V2, V3, V4, V5, N, MIN, MAX> result;
281
  for (unsigned int i = 0; i < result.size(); ++i) {
282
    result[i] = a[i] < b[i] ? a[i] : b[i];
283
  }
284
  return result;
285
}
286
287
template<
288
    int U1, int U2, int U3, int U4, int U5,
289
    unsigned int N, int MIN, int MAX>
290
ScalarFunction<U1, U2, U3, U4, U5, 0, 0, 0, 0, 0, N, MIN, MAX>
291
exp(const ScalarFunction<U1, U2, U3, U4, U5, 0, 0, 0, 0, 0, N, MIN, MAX>& f) {
292
  ScalarFunction<U1, U2, U3, U4, U5, 0, 0, 0, 0, 0, N, MIN, MAX> result;
293
  for (unsigned int i = 0; i < result.size(); ++i) {
294
    result[i] = exp(f[i]);
295
  }
296
  return result;
297
}
298
299
// Returns the integral of the given function over its range,
300
// i.e. integral of function * dx from MIN to MAX.
301
template<
302
    int U1, int U2, int U3, int U4, int U5,
303
    int V1, int V2, int V3, int V4, int V5,
304
    unsigned int N, int MIN, int MAX>
305
Scalar<U1 + V1, U2 + V2, U3 + V3, U4 + V4, U5 + V5>
306!
Integral(const ScalarFunction<
307
    U1, U2, U3, U4, U5, V1, V2, V3, V4, V5, N, MIN, MAX>& f) {
308!
  Scalar<V1, V2, V3, V4, V5> sum = 0.0 * Scalar<V1, V2, V3, V4, V5>::Unit();
309!
  for (unsigned int i = 0; i < f.size(); ++i) {
310!
    sum = sum + f[i];
311
  }
312!
  return sum * ((MAX - MIN) * Scalar<U1, U2, U3, U4, U5>::Unit() / N);
313
}
314
315
// Returns the integral of the given function over a subset of its range,
316
// i.e. integral of function * dx from min_value to max_value, using the
317
// specified number of samples.
318
template<
319
    int U1, int U2, int U3, int U4, int U5,
320
    int V1, int V2, int V3, int V4, int V5,
321
    unsigned int N, int MIN, int MAX>
322
Scalar<U1 + V1, U2 + V2, U3 + V3, U4 + V4, U5 + V5>
323!
Integral(const ScalarFunction<
324
    U1, U2, U3, U4, U5, V1, V2, V3, V4, V5, N, MIN, MAX>& f,
325
    Scalar<U1, U2, U3, U4, U5> min_value, Scalar<U1, U2, U3, U4, U5> max_value,
326
    int number_of_samples) {
327
  const Scalar<U1, U2, U3, U4, U5> dx =
328!
      (max_value - min_value) / number_of_samples;
329!
  Scalar<U1, U2, U3, U4, U5> x = min_value;
330!
  Scalar<V1, V2, V3, V4, V5> sum = 0.0 * Scalar<V1, V2, V3, V4, V5>::Unit();
331!
  for (int i = 0; i < number_of_samples; ++i) {
332!
    sum = sum + f(x);
333!
    x = x + dx;
334
  }
335!
  return sum * dx;
336
}
337
338
// Returns the integral of the given function over a subset of its range,
339
// i.e. integral of function * dx from min_value to max_value.
340
template<
341
    int U1, int U2, int U3, int U4, int U5,
342
    int V1, int V2, int V3, int V4, int V5,
343
    unsigned int N, int MIN, int MAX>
344
Scalar<U1 + V1, U2 + V2, U3 + V3, U4 + V4, U5 + V5>
345
Integral(const ScalarFunction<
346
    U1, U2, U3, U4, U5, V1, V2, V3, V4, V5, N, MIN, MAX>& f,
347
    Scalar<U1, U2, U3, U4, U5> min_value,
348
    Scalar<U1, U2, U3, U4, U5> max_value) {
349
  constexpr auto kUnit = Scalar<U1, U2, U3, U4, U5>::Unit();
350
  assert(min_value >= MIN * kUnit);
351
  assert(max_value <= MAX * kUnit);
352
  Scalar<U1 + V1, U2 + V2, U3 + V3, U4 + V4, U5 + V5> sum =
353
      0.0 * Scalar<U1 + V1, U2 + V2, U3 + V3, U4 + V4, U5 + V5>::Unit();
354
  for (unsigned int i = 0; i < f.size(); ++i) {
355
    Scalar<U1, U2, U3, U4, U5> dx =
356
        std::min(f.GetSample(i + 1), max_value) -
357
        std::max(f.GetSample(i), min_value);
358
    sum = sum + f[i] * std::max(dx, 0.0 * kUnit);
359
  }
360
  return sum;
361
}
362
363
}  // namespace dimensional
364
365
#endif  // MATH_SCALAR_FUNCTION_H_
1
/*
2
This file is included in the skymodelr package, which is distributed as a
3
whole under GPL-3. The following upstream copyright and provenance notice is
4
preserved for attribution and compliance with upstream notice requirements.
5
*/
6
7
/**
8
 * Copyright (c) 2016 Eric Bruneton
9
 * All rights reserved.
10
 *
11
 * Redistribution and use in source and binary forms, with or without
12
 * modification, are permitted provided that the following conditions
13
 * are met:
14
 * 1. Redistributions of source code must retain the above copyright
15
 *    notice, this list of conditions and the following disclaimer.
16
 * 2. Redistributions in binary form must reproduce the above copyright
17
 *    notice, this list of conditions and the following disclaimer in the
18
 *    documentation and/or other materials provided with the distribution.
19
 * 3. Neither the name of the copyright holders nor the names of its
20
 *    contributors may be used to endorse or promote products derived from
21
 *    this software without specific prior written permission.
22
 *
23
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
24
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
25
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
26
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
27
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
28
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
29
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
30
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
31
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
32
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
33
 * THE POSSIBILITY OF SUCH DAMAGE.
34
 */
35
36
#ifndef MATH_ANGLE_H_
37
#define MATH_ANGLE_H_
38
39
#include <cmath>
40
41
#include "../math/scalar.h"
42
43
namespace dimensional {
44
45
// An angle, represented with its own class to make sure it is properly used
46
// (e.g. that degrees are not used when radians are expected or vice versa).
47
// NOTES:
48
// - We intentionally do not provide a constructor from a literal value in order
49
// to force the use of an explicit unit (e.g. "Angle a = 3.0 * deg;").
50
// - Likewise, we intentionally do not provide a noarg accessor, in order to
51
// force the use of an explicit unit when accessing the angle value (e.g.
52
// "double value = a.to(rad);").
53
class Angle {
54
 public:
55!
  Angle() {}
56
  static constexpr Angle Unit() { return Angle(1.0); }
57
58!
  inline constexpr double to(const Angle unit) const {
59!
    return value_ / unit.value_;
60
  }
61
62!
  inline Angle& operator=(const Angle rhs) {
63!
    value_ = rhs.value_;
64!
    return *this;
65
  }
66
67
  inline constexpr Angle operator+(const Angle rhs) const {
68
    return Angle(value_ + rhs.value_);
69
  }
70
71!
  inline constexpr Angle operator-(const Angle rhs) const {
72!
    return Angle(value_ - rhs.value_);
73
  }
74
75
  inline constexpr Angle operator-() const {
76
    return Angle(-value_);
77
  }
78
79
  inline constexpr Angle operator*(const Number rhs) const {
80
    return Angle(value_ * rhs());
81
  }
82
83!
  inline constexpr Angle operator/(const Number rhs) const {
84!
    return Angle(value_ / rhs());
85
  }
86
87
  inline constexpr Number operator/(const Angle rhs) const {
88
    return value_ / rhs.value_;
89
  }
90
91!
  inline bool operator==(const Angle rhs) const {
92!
    return value_ == rhs.value_;
93
  }
94
95
  inline constexpr bool operator<(const Angle rhs) const {
96
    return value_ < rhs.value_;
97
  }
98
99
  inline constexpr bool operator<=(const Angle rhs) const {
100
    return value_ <= rhs.value_;
101
  }
102
103
  inline constexpr bool operator>(const Angle rhs) const {
104
    return value_ > rhs.value_;
105
  }
106
107
  inline constexpr bool operator>=(const Angle rhs) const {
108
    return value_ >= rhs.value_;
109
  }
110
111
 private:
112!
  explicit constexpr Angle(double value) : value_(value) {}
113
114
  double value_;
115
116
  friend constexpr Angle operator*(const Number lhs, const Angle rhs);
117
  friend Number cos(Angle);
118
  friend Number sin(Angle);
119
  friend Number tan(Angle);
120
};
121
122!
inline constexpr Angle operator*(const Number lhs, const Angle rhs) {
123!
  return Angle(lhs() * rhs.value_);
124
}
125
126
constexpr double PI = 3.14159265358979323846;
127
128
constexpr Angle rad = Angle::Unit();
129
constexpr Angle pi = PI * rad;
130
constexpr Angle deg = pi / 180.0;
131
132!
constexpr inline Angle acos(const Number cosine) {
133!
  return std::acos(cosine()) * rad;
134
}
135
constexpr inline Angle asin(const Number sine) {
136
  return std::asin(sine()) * rad;
137
}
138
inline Angle atan(const Number x) { return std::atan(x()) * rad; }
139
inline Angle atan2(const Number y, const Number x) {
140
  return std::atan2(y(), x()) * rad;
141
}
142!
inline Number cos(const Angle angle) { return std::cos(angle.value_); }
143!
inline Number sin(const Angle angle) { return std::sin(angle.value_); }
144
inline Number tan(const Angle angle) { return std::tan(angle.value_); }
145
146
}  // namespace dimensional
147
148
#endif  // MATH_ANGLE_H_
1
/*
2
This file is included in the skymodelr package, which is distributed as a
3
whole under GPL-3. The following upstream copyright and provenance notice is
4
preserved for attribution and compliance with upstream notice requirements.
5
*/
6
7
/**
8
 Copyright (c) 2015 Eric Bruneton
9
 All rights reserved.
10
11
 Redistribution and use in source and binary forms, with or without
12
 modification, are permitted provided that the following conditions are met:
13
14
 1. Redistributions of source code must retain the above copyright notice, this
15
 list of conditions and the following disclaimer.
16
17
 2. Redistributions in binary form must reproduce the above copyright notice,
18
 this list of conditions and the following disclaimer in the documentation
19
 and/or other materials provided with the distribution.
20
21
 3. Neither the name of the copyright holder nor the names of its contributors
22
 may be used to endorse or promote products derived from this software without
23
 specific prior written permission.
24
25
 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
26
 AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
27
 IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
28
 DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
29
 FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
30
 DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
31
 SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
32
 CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
33
 OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
34
 OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
35
*/
36
#include "cie.h"
37
38
#include <algorithm>
39
#include <vector>
40
41
namespace {
42
43
struct Tables {
44
  std::vector<Number> x_bar_samples;
45
  std::vector<Number> y_bar_samples;
46
  std::vector<Number> z_bar_samples;
47
  std::vector<Number> S0_samples;
48
  std::vector<Number> S1_samples;
49
  std::vector<Number> S2_samples;
50
513x
  Tables() {
52
    // Values from "CIE (1931) 2-deg color matching functions", see
53
    // "http://web.archive.org/web/20081228084047/
54
    //    http://www.cvrl.org/database/data/cmfs/ciexyz31.txt".
553x
    Add(0.000000000000, 0.000000000000, 0.000000000000);
563x
    Add(0.000129900000, 0.000003917000, 0.000606100000);
573x
    Add(0.000232100000, 0.000006965000, 0.001086000000);
583x
    Add(0.000414900000, 0.000012390000, 0.001946000000);
593x
    Add(0.000741600000, 0.000022020000, 0.003486000000);
603x
    Add(0.001368000000, 0.000039000000, 0.006450001000);
613x
    Add(0.002236000000, 0.000064000000, 0.010549990000);
623x
    Add(0.004243000000, 0.000120000000, 0.020050010000);
633x
    Add(0.007650000000, 0.000217000000, 0.036210000000);
643x
    Add(0.014310000000, 0.000396000000, 0.067850010000);
653x
    Add(0.023190000000, 0.000640000000, 0.110200000000);
663x
    Add(0.043510000000, 0.001210000000, 0.207400000000);
673x
    Add(0.077630000000, 0.002180000000, 0.371300000000);
683x
    Add(0.134380000000, 0.004000000000, 0.645600000000);
693x
    Add(0.214770000000, 0.007300000000, 1.039050100000);
703x
    Add(0.283900000000, 0.011600000000, 1.385600000000);
713x
    Add(0.328500000000, 0.016840000000, 1.622960000000);
723x
    Add(0.348280000000, 0.023000000000, 1.747060000000);
733x
    Add(0.348060000000, 0.029800000000, 1.782600000000);
743x
    Add(0.336200000000, 0.038000000000, 1.772110000000);
753x
    Add(0.318700000000, 0.048000000000, 1.744100000000);
763x
    Add(0.290800000000, 0.060000000000, 1.669200000000);
773x
    Add(0.251100000000, 0.073900000000, 1.528100000000);
783x
    Add(0.195360000000, 0.090980000000, 1.287640000000);
793x
    Add(0.142100000000, 0.112600000000, 1.041900000000);
803x
    Add(0.095640000000, 0.139020000000, 0.812950100000);
813x
    Add(0.057950010000, 0.169300000000, 0.616200000000);
823x
    Add(0.032010000000, 0.208020000000, 0.465180000000);
833x
    Add(0.014700000000, 0.258600000000, 0.353300000000);
843x
    Add(0.004900000000, 0.323000000000, 0.272000000000);
853x
    Add(0.002400000000, 0.407300000000, 0.212300000000);
863x
    Add(0.009300000000, 0.503000000000, 0.158200000000);
873x
    Add(0.029100000000, 0.608200000000, 0.111700000000);
883x
    Add(0.063270000000, 0.710000000000, 0.078249990000);
893x
    Add(0.109600000000, 0.793200000000, 0.057250010000);
903x
    Add(0.165500000000, 0.862000000000, 0.042160000000);
913x
    Add(0.225749900000, 0.914850100000, 0.029840000000);
923x
    Add(0.290400000000, 0.954000000000, 0.020300000000);
933x
    Add(0.359700000000, 0.980300000000, 0.013400000000);
943x
    Add(0.433449900000, 0.994950100000, 0.008749999000);
953x
    Add(0.512050100000, 1.000000000000, 0.005749999000);
963x
    Add(0.594500000000, 0.995000000000, 0.003900000000);
973x
    Add(0.678400000000, 0.978600000000, 0.002749999000);
983x
    Add(0.762100000000, 0.952000000000, 0.002100000000);
993x
    Add(0.842500000000, 0.915400000000, 0.001800000000);
1003x
    Add(0.916300000000, 0.870000000000, 0.001650001000);
1013x
    Add(0.978600000000, 0.816300000000, 0.001400000000);
1023x
    Add(1.026300000000, 0.757000000000, 0.001100000000);
1033x
    Add(1.056700000000, 0.694900000000, 0.001000000000);
1043x
    Add(1.062200000000, 0.631000000000, 0.000800000000);
1053x
    Add(1.045600000000, 0.566800000000, 0.000600000000);
1063x
    Add(1.002600000000, 0.503000000000, 0.000340000000);
1073x
    Add(0.938400000000, 0.441200000000, 0.000240000000);
1083x
    Add(0.854449900000, 0.381000000000, 0.000190000000);
1093x
    Add(0.751400000000, 0.321000000000, 0.000100000000);
1103x
    Add(0.642400000000, 0.265000000000, 0.000049999990);
1113x
    Add(0.541900000000, 0.217000000000, 0.000030000000);
1123x
    Add(0.447900000000, 0.175000000000, 0.000020000000);
1133x
    Add(0.360800000000, 0.138200000000, 0.000010000000);
1143x
    Add(0.283500000000, 0.107000000000, 0.000000000000);
1153x
    Add(0.218700000000, 0.081600000000, 0.000000000000);
1163x
    Add(0.164900000000, 0.061000000000, 0.000000000000);
1173x
    Add(0.121200000000, 0.044580000000, 0.000000000000);
1183x
    Add(0.087400000000, 0.032000000000, 0.000000000000);
1193x
    Add(0.063600000000, 0.023200000000, 0.000000000000);
1203x
    Add(0.046770000000, 0.017000000000, 0.000000000000);
1213x
    Add(0.032900000000, 0.011920000000, 0.000000000000);
1223x
    Add(0.022700000000, 0.008210000000, 0.000000000000);
1233x
    Add(0.015840000000, 0.005723000000, 0.000000000000);
1243x
    Add(0.011359160000, 0.004102000000, 0.000000000000);
1253x
    Add(0.008110916000, 0.002929000000, 0.000000000000);
1263x
    Add(0.005790346000, 0.002091000000, 0.000000000000);
1273x
    Add(0.004109457000, 0.001484000000, 0.000000000000);
1283x
    Add(0.002899327000, 0.001047000000, 0.000000000000);
1293x
    Add(0.002049190000, 0.000740000000, 0.000000000000);
1303x
    Add(0.001439971000, 0.000520000000, 0.000000000000);
1313x
    Add(0.000999949300, 0.000361100000, 0.000000000000);
1323x
    Add(0.000690078600, 0.000249200000, 0.000000000000);
1333x
    Add(0.000476021300, 0.000171900000, 0.000000000000);
1343x
    Add(0.000332301100, 0.000120000000, 0.000000000000);
1353x
    Add(0.000234826100, 0.000084800000, 0.000000000000);
1363x
    Add(0.000166150500, 0.000060000000, 0.000000000000);
1373x
    Add(0.000117413000, 0.000042400000, 0.000000000000);
1383x
    Add(0.000083075270, 0.000030000000, 0.000000000000);
1393x
    Add(0.000058706520, 0.000021200000, 0.000000000000);
1403x
    Add(0.000041509940, 0.000014990000, 0.000000000000);
1413x
    Add(0.000029353260, 0.000010600000, 0.000000000000);
1423x
    Add(0.000020673830, 0.000007465700, 0.000000000000);
1433x
    Add(0.000014559770, 0.000005257800, 0.000000000000);
1443x
    Add(0.000010253980, 0.000003702900, 0.000000000000);
1453x
    Add(0.000007221456, 0.000002607800, 0.000000000000);
1463x
    Add(0.000005085868, 0.000001836600, 0.000000000000);
1473x
    Add(0.000003581652, 0.000001293400, 0.000000000000);
1483x
    Add(0.000002522525, 0.000000910930, 0.000000000000);
1493x
    Add(0.000001776509, 0.000000641530, 0.000000000000);
1503x
    Add(0.000001251141, 0.000000451810, 0.000000000000);
1513x
    Add(0.000000000000, 0.000000000000, 0.000000000000);
152
153
    // Values from Table T.2 in CIE TR "Colorimetry" 15:2004 Third Edition
154
    // (ISBN 3 901 906 33 9).
1553x
    AddS(+61.5,  38.0,  5.3);
1563x
    AddS(+68.8,  42.4,  6.1);
1573x
    AddS(+63.4,  38.5,  3.0);
1583x
    AddS(+65.8,  35.0,  1.2);
1593x
    AddS(+94.8,  43.4, -1.1);
1603x
    AddS(104.8,  46.3, -0.5);
1613x
    AddS(105.9,  43.9, -0.7);
1623x
    AddS(+96.8,  37.1, -1.2);
1633x
    AddS(113.9,  36.7, -2.6);
1643x
    AddS(125.6,  35.9, -2.9);
1653x
    AddS(125.5,  32.6, -2.8);
1663x
    AddS(121.3,  27.9, -2.6);
1673x
    AddS(121.3,  24.3, -2.6);
1683x
    AddS(113.5,  20.1, -1.8);
1693x
    AddS(113.1,  16.2, -1.5);
1703x
    AddS(110.8,  13.2, -1.3);
1713x
    AddS(106.5,   8.6, -1.2);
1723x
    AddS(108.8,   6.1, -1.0);
1733x
    AddS(105.3,   4.2, -0.5);
1743x
    AddS(104.4,   1.9, -0.3);
1753x
    AddS(100.0,   0.0,  0.0);
1763x
    AddS(+96.0,  -1.6,  0.2);
1773x
    AddS(+95.1,  -3.5,  0.5);
1783x
    AddS(+89.1,  -3.5,  2.1);
1793x
    AddS(+90.5,  -5.8,  3.2);
1803x
    AddS(+90.3,  -7.2,  4.1);
1813x
    AddS(+88.4,  -8.6,  4.7);
1823x
    AddS(+84.0,  -9.5,  5.1);
1833x
    AddS(+85.1, -10.9,  6.7);
1843x
    AddS(+81.9, -10.7,  7.3);
1853x
    AddS(+82.6, -12.0,  8.6);
1863x
    AddS(+84.9, -14.0,  9.8);
1873x
    AddS(+81.3, -13.6, 10.2);
1883x
    AddS(+71.9, -12.0,  8.3);
1893x
    AddS(+74.3, -13.3,  9.6);
1903x
    AddS(+76.4, -12.9,  8.5);
1913x
    AddS(+63.3, -10.6,  7.0);
1923x
    AddS(+71.7, -11.6,  7.6);
1933x
    AddS(+77.0, -12.2,  8.0);
1943x
    AddS(+65.2, -10.2,  6.7);
1953x
    AddS(+47.7,  -7.8,  5.2);
1963x
    AddS(+68.6, -11.2,  7.4);
1973x
    AddS(+65.0, -10.4,  6.8);
1983x
    AddS(+66.0, -10.6,  7.0);
1993x
    AddS(+61.0,  -9.7,  6.4);
2003x
    AddS(+53.3,  -8.3,  5.5);
2013x
    AddS(+58.9,  -9.3,  6.1);
2023x
    AddS(+61.9,  -9.8,  6.5);
203
  }
204
205
 private:
206291x
  void Add(double x_bar_sample, double y_bar_sample, double z_bar_sample) {
207291x
    x_bar_samples.push_back(x_bar_sample);
208291x
    y_bar_samples.push_back(y_bar_sample);
209291x
    z_bar_samples.push_back(z_bar_sample);
210
  }
211
212144x
  void AddS(double s0_sample, double s1_sample, double s2_sample) {
213144x
    S0_samples.push_back(s0_sample);
214144x
    S1_samples.push_back(s1_sample);
215144x
    S2_samples.push_back(s2_sample);
216
  }
217
};
218
219
const Tables tables = Tables();
220
const DimensionlessSpectrum x_bar(355.0 * nm, 835.0 * nm, tables.x_bar_samples);
221
const DimensionlessSpectrum y_bar(355.0 * nm, 835.0 * nm, tables.y_bar_samples);
222
const DimensionlessSpectrum z_bar(355.0 * nm, 835.0 * nm, tables.z_bar_samples);
223
const DimensionlessSpectrum S0(360.0 * nm, 830.0 * nm, tables.S0_samples);
224
const DimensionlessSpectrum S1(360.0 * nm, 830.0 * nm, tables.S1_samples);
225
const DimensionlessSpectrum S2(360.0 * nm, 830.0 * nm, tables.S2_samples);
226
227
}  // anonymous namespace
228
229!
const DimensionlessSpectrum& cie_x_bar_function() { return x_bar; }
230!
const DimensionlessSpectrum& cie_y_bar_function() { return y_bar; }
231!
const DimensionlessSpectrum& cie_z_bar_function() { return z_bar; }
232
233!
const DimensionlessSpectrum& S0_function() { return S0; }
234!
const DimensionlessSpectrum& S1_function() { return S1; }
235!
const DimensionlessSpectrum& S2_function() { return S2; }
236
237!
Luminance GetLuminance(const RadianceSpectrum& spectrum) {
238!
  return MaxLuminousEfficacy * Integral(y_bar * spectrum);
239
}
240
241!
Color GetSrgbColor(const RadianceSpectrum& spectrum) {
242!
  Color RGB = XYZ_to_sRGB * Color(
243!
      MaxLuminousEfficacy * Integral(cie_x_bar_function() * spectrum),
244!
      MaxLuminousEfficacy * Integral(cie_y_bar_function() * spectrum),
245!
      MaxLuminousEfficacy * Integral(cie_z_bar_function() * spectrum));
246
  return Color(
247!
      std::max(RGB.x, 0.0 * cd_per_square_meter),
248!
      std::max(RGB.y, 0.0 * cd_per_square_meter),
249!
      std::max(RGB.z, 0.0 * cd_per_square_meter));
250
}
251
252!
Color GetSrgbColor(const RadianceSpectrum& spectrum, Wavelength min_wavelength,
253
    Wavelength max_wavelength, int number_of_wavelengths) {
254!
  Color RGB = XYZ_to_sRGB * Color(
255!
      MaxLuminousEfficacy * Integral(cie_x_bar_function() * spectrum,
256
          min_wavelength, max_wavelength, number_of_wavelengths),
257!
      MaxLuminousEfficacy * Integral(cie_y_bar_function() * spectrum,
258
          min_wavelength, max_wavelength, number_of_wavelengths),
259!
      MaxLuminousEfficacy * Integral(cie_z_bar_function() * spectrum,
260!
          min_wavelength, max_wavelength, number_of_wavelengths));
261
  return Color(
262!
      std::max(RGB.x, 0.0 * cd_per_square_meter),
263!
      std::max(RGB.y, 0.0 * cd_per_square_meter),
264!
      std::max(RGB.z, 0.0 * cd_per_square_meter));
265
}
1
/*
2
This file is included in the skymodelr package, which is distributed as a
3
whole under GPL-3. The following upstream copyright and provenance notice is
4
preserved for attribution and compliance with upstream notice requirements.
5
*/
6
7
/**
8
 * Copyright (c) 2016 Eric Bruneton
9
 * All rights reserved.
10
 *
11
 * Redistribution and use in source and binary forms, with or without
12
 * modification, are permitted provided that the following conditions
13
 * are met:
14
 * 1. Redistributions of source code must retain the above copyright
15
 *    notice, this list of conditions and the following disclaimer.
16
 * 2. Redistributions in binary form must reproduce the above copyright
17
 *    notice, this list of conditions and the following disclaimer in the
18
 *    documentation and/or other materials provided with the distribution.
19
 * 3. Neither the name of the copyright holders nor the names of its
20
 *    contributors may be used to endorse or promote products derived from
21
 *    this software without specific prior written permission.
22
 *
23
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
24
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
25
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
26
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
27
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
28
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
29
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
30
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
31
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
32
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
33
 * THE POSSIBILITY OF SUCH DAMAGE.
34
 */
35
36
#ifndef MATH_MATRIX_H_
37
#define MATH_MATRIX_H_
38
39
#include "../math/scalar.h"
40
#include "../math/vector.h"
41
42
namespace dimensional {
43
44
template<typename T>
45
struct Matrix3 {
46
  T m00, m01, m02;
47
  T m10, m11, m12;
48
  T m20, m21, m22;
49
  inline Matrix3() {}
50
  constexpr inline Matrix3(T m00, T m01, T m02,
51
                           T m10, T m11, T m12,
52
                           T m20, T m21, T m22)
53
      : m00(m00), m01(m01), m02(m02),
54
        m10(m10), m11(m11), m12(m12),
55
        m20(m20), m21(m21), m22(m22) {}
56
};
57
58
template<int U1, int U2, int U3, int U4, int U5,
59
    int V1, int V2, int V3, int V4, int V5>
60!
Vector3<Scalar<U1 + V1, U2 + V2, U3 + V3, U4 + V4, U5 + V5>> operator*(
61
    const Matrix3<Scalar<U1, U2, U3, U4, U5>>& lhs,
62
    const Vector3<Scalar<V1, V2, V3, V4, V5>>& rhs) {
63
  return Vector3<Scalar<U1 + V1, U2 + V2, U3 + V3, U4 + V4, U5 + V5>>(
64!
      lhs.m00 * rhs.x + lhs.m01 * rhs.y + lhs.m02 * rhs.z,
65!
      lhs.m10 * rhs.x + lhs.m11 * rhs.y + lhs.m12 * rhs.z,
66!
      lhs.m20 * rhs.x + lhs.m21 * rhs.y + lhs.m22 * rhs.z);
67
}
68
69
template<int U1, int U2, int U3, int U4, int U5,
70
    int V1, int V2, int V3, int V4, int V5>
71
Matrix3<Scalar<U1 + V1, U2 + V2, U3 + V3, U4 + V4, U5 + V5>> operator*(
72
    const Matrix3<Scalar<U1, U2, U3, U4, U5>>& lhs,
73
    const Matrix3<Scalar<V1, V2, V3, V4, V5>>& rhs) {
74
  return Matrix3<Scalar<U1 + V1, U2 + V2, U3 + V3, U4 + V4, U5 + V5>>(
75
      lhs.m00 * rhs.m00 + lhs.m01 * rhs.m10 + lhs.m02 * rhs.m20,
76
      lhs.m00 * rhs.m01 + lhs.m01 * rhs.m11 + lhs.m02 * rhs.m21,
77
      lhs.m00 * rhs.m02 + lhs.m01 * rhs.m12 + lhs.m02 * rhs.m22,
78
      lhs.m10 * rhs.m00 + lhs.m11 * rhs.m10 + lhs.m12 * rhs.m20,
79
      lhs.m10 * rhs.m01 + lhs.m11 * rhs.m11 + lhs.m12 * rhs.m21,
80
      lhs.m10 * rhs.m02 + lhs.m11 * rhs.m12 + lhs.m12 * rhs.m22,
81
      lhs.m20 * rhs.m00 + lhs.m21 * rhs.m10 + lhs.m22 * rhs.m20,
82
      lhs.m20 * rhs.m01 + lhs.m21 * rhs.m11 + lhs.m22 * rhs.m21,
83
      lhs.m20 * rhs.m02 + lhs.m21 * rhs.m12 + lhs.m22 * rhs.m22);
84
}
85
86
template<int U1, int U2, int U3, int U4, int U5>
87
Matrix3<Scalar<-U1, -U2, -U3, -U4, -U5>> inverse(
88
    const Matrix3<Scalar<U1, U2, U3, U4, U5>>& mat) {
89
  auto c00 = mat.m11 * mat.m22 - mat.m12 * mat.m21;
90
  auto c01 = mat.m02 * mat.m21 - mat.m01 * mat.m22;
91
  auto c02 = mat.m01 * mat.m12 - mat.m02 * mat.m11;
92
  auto c10 = mat.m12 * mat.m20 - mat.m10 * mat.m22;
93
  auto c11 = mat.m00 * mat.m22 - mat.m02 * mat.m20;
94
  auto c12 = mat.m02 * mat.m10 - mat.m00 * mat.m12;
95
  auto c20 = mat.m10 * mat.m21 - mat.m11 * mat.m20;
96
  auto c21 = mat.m01 * mat.m20 - mat.m00 * mat.m21;
97
  auto c22 = mat.m00 * mat.m11 - mat.m01 * mat.m10;
98
  auto det = mat.m00 * c00 + mat.m01 * c10 + mat.m02 * c20;
99
  return Matrix3<Scalar<-U1, -U2, -U3, -U4, -U5>>(
100
      c00 / det, c01 / det, c02 / det,
101
      c10 / det, c11 / det, c12 / det,
102
      c20 / det, c21 / det, c22 / det);
103
}
104
105
}  // namespace dimensional
106
107
#endif  // MATH_MATRIX_H_
1
/*
2
This file is included in the skymodelr package, which is distributed as a
3
whole under GPL-3. The following upstream copyright and provenance notice is
4
preserved for attribution and compliance with upstream notice requirements.
5
*/
6
7
/**
8
 * Copyright (c) 2016 Eric Bruneton
9
 * All rights reserved.
10
 *
11
 * Redistribution and use in source and binary forms, with or without
12
 * modification, are permitted provided that the following conditions
13
 * are met:
14
 * 1. Redistributions of source code must retain the above copyright
15
 *    notice, this list of conditions and the following disclaimer.
16
 * 2. Redistributions in binary form must reproduce the above copyright
17
 *    notice, this list of conditions and the following disclaimer in the
18
 *    documentation and/or other materials provided with the distribution.
19
 * 3. Neither the name of the copyright holders nor the names of its
20
 *    contributors may be used to endorse or promote products derived from
21
 *    this software without specific prior written permission.
22
 *
23
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
24
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
25
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
26
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
27
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
28
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
29
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
30
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
31
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
32
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
33
 * THE POSSIBILITY OF SUCH DAMAGE.
34
 */
35
36
#ifndef MATH_VECTOR_H_
37
#define MATH_VECTOR_H_
38
39
#include "../math/scalar.h"
40
41
namespace dimensional {
42
43
template<typename T>
44
struct Vector2 {
45
  T x, y;
46
  inline constexpr Vector2() {}
47
  inline constexpr Vector2(T x, T y) : x(x), y(y) {}
48
};
49
50
template<int U1, int U2, int U3, int U4, int U5,
51
    int V1, int V2, int V3, int V4, int V5>
52
inline Vector2<Scalar<U1 - V1, U2 - V2, U3 - V3, U4 - V4, U5 - V5>> operator/(
53
    const Vector2<Scalar<U1, U2, U3, U4, U5>>& lhs,
54
    const Vector2<Scalar<V1, V2, V3, V4, V5>>& rhs) {
55
  return Vector2<Scalar<U1 - V1, U2 - V2, U3 - V3, U4 - V4, U5 - V5>>(
56
      lhs.x / rhs.x, lhs.y / rhs.y);
57
}
58
59
template<typename T>
60
struct Vector3 {
61
  T x, y, z;
62
  inline constexpr Vector3() {}
63!
  inline constexpr Vector3(T x, T y, T z) : x(x), y(y), z(z) {}
64
  inline Vector3 operator+(const Vector3& rhs) const {
65
    return Vector3(x + rhs.x, y + rhs.y, z + rhs.z);
66
  }
67
  inline Vector3& operator+=(const Vector3& rhs) {
68
    x += rhs.x;
69
    y += rhs.y;
70
    z += rhs.z;
71
    return *this;
72
  }
73
  inline Vector3 operator-(const Vector3& rhs) const {
74
    return Vector3(x - rhs.x, y - rhs.y, z - rhs.z);
75
  }
76
  inline Vector3 operator-() const {
77
    return Vector3(-x, -y, -z);
78
  }
79
  inline Vector3 operator*(const double rhs) const {
80
    return Vector3(x * rhs, y * rhs, z * rhs);
81
  }
82
};
83
84
template<int U1, int U2, int U3, int U4, int U5,
85
    int V1, int V2, int V3, int V4, int V5>
86
inline Vector3<Scalar<U1 + V1, U2 + V2, U3 + V3, U4 + V4, U5 + V5>> operator*(
87
    const Vector3<Scalar<U1, U2, U3, U4, U5>>& lhs,
88
    const Scalar<V1, V2, V3, V4, V5> rhs) {
89
  return Vector3<Scalar<U1 + V1, U2 + V2, U3 + V3, U4 + V4, U5 + V5>>(
90
      lhs.x * rhs, lhs.y * rhs, lhs.z * rhs);
91
}
92
93
template<int U1, int U2, int U3, int U4, int U5,
94
    int V1, int V2, int V3, int V4, int V5>
95
inline Vector3<Scalar<U1 - V1, U2 - V2, U3 - V3, U4 - V4, U5 - V5>> operator/(
96
    const Vector3<Scalar<U1, U2, U3, U4, U5>>& lhs,
97
    const Scalar<V1, V2, V3, V4, V5>& rhs) {
98
  return Vector3<Scalar<U1 - V1, U2 - V2, U3 - V3, U4 - V4, U5 - V5>>(
99
      lhs.x / rhs, lhs.y / rhs, lhs.z / rhs);
100
}
101
102
template<int U1, int U2, int U3, int U4, int U5,
103
    int V1, int V2, int V3, int V4, int V5>
104
inline Scalar<U1 + V1, U2 + V2, U3 + V3, U4 + V4, U5 + V5> dot(
105
    const Vector3<Scalar<U1, U2, U3, U4, U5>>& u,
106
    const Vector3<Scalar<V1, V2, V3, V4, V5>>& v) {
107
  return u.x * v.x + u.y * v.y + u.z * v.z;
108
}
109
110
template<typename T>
111
T length(const Vector3<T>& v) {
112
  return sqrt(dot(v, v));
113
}
114
115
template<typename T>
116
Vector3<Number> normalize(const Vector3<T>& v) {
117
  T length = sqrt(dot(v, v));
118
  return Vector3<Number>(v.x / length, v.y / length, v.z / length);
119
}
120
121
template<typename T>
122
struct Vector4 {
123
  T x, y, z, w;
124
  inline constexpr Vector4() {}
125
  inline constexpr Vector4(T x, T y, T z, T w) : x(x), y(y), z(z), w(w) {}
126
};
127
128
template<int U1, int U2, int U3, int U4, int U5,
129
    int V1, int V2, int V3, int V4, int V5>
130
inline Vector4<Scalar<U1 - V1, U2 - V2, U3 - V3, U4 - V4, U5 - V5>> operator/(
131
    const Vector4<Scalar<U1, U2, U3, U4, U5>>& lhs,
132
    const Vector4<Scalar<V1, V2, V3, V4, V5>>& rhs) {
133
  return Vector4<Scalar<U1 - V1, U2 - V2, U3 - V3, U4 - V4, U5 - V5>>(
134
      lhs.x / rhs.x, lhs.y / rhs.y, lhs.z / rhs.z, lhs.w / rhs.w);
135
}
136
137
typedef Vector2<Number> vec2;
138
typedef Vector3<Number> vec3;
139
typedef Vector4<Number> vec4;
140
141
}  // namespace dimensional
142
143
#endif  // MATH_VECTOR_H_
1
/*
2
This file is included in the skymodelr package, which is distributed as a
3
whole under GPL-3. The following upstream copyright and provenance notice is
4
preserved for attribution and compliance with upstream notice requirements.
5
*/
6
7
/**
8
 Copyright (c) 2015 Eric Bruneton
9
 All rights reserved.
10
11
 Redistribution and use in source and binary forms, with or without
12
 modification, are permitted provided that the following conditions are met:
13
14
 1. Redistributions of source code must retain the above copyright notice, this
15
 list of conditions and the following disclaimer.
16
17
 2. Redistributions in binary form must reproduce the above copyright notice,
18
 this list of conditions and the following disclaimer in the documentation
19
 and/or other materials provided with the distribution.
20
21
 3. Neither the name of the copyright holder nor the names of its contributors
22
 may be used to endorse or promote products derived from this software without
23
 specific prior written permission.
24
25
 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
26
 AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
27
 IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
28
 DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
29
 FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
30
 DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
31
 SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
32
 CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
33
 OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
34
 OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
35
*/
36
#include "hosek.h"
37
38
#include <algorithm>
39
40
#include "ArHosekSkyModel.h"
41
42
namespace {
43
44
constexpr SolidAngle kSunSolidAngle = 6.87e-5 * sr;
45
46
// Copied from ArHosekSkyModel.cc.
47
const double originalSolarRadianceTable[] = {
48
  7500.0,
49
  12500.0,
50
  21127.5,
51
  26760.5,
52
  30663.7,
53
  27825.0,
54
  25503.8,
55
  25134.2,
56
  23212.1,
57
  21526.7,
58
  19870.8
59
};
60
61
// The Hosek sky radiance was computed uding 'originalSolarRadianceTable' as
62
// the solar radiance, but we want the result for SolarSpectrum(), used in all
63
// other models. Thus we correct the result for each wavelength by the ratio
64
// between the two spectra at this wavelength (including also the Sun solid
65
// angle to convert radiance to irradiance values).
66!
double SolarSpectrumCorrectionFactor(Wavelength lambda) {
67!
  double x = (lambda.to(nm) - 320.0) / 40.0;
68!
  if (x < 0.0 || x > 10.0) {
69!
    return 1.0;
70
  }
71!
  int i = floor(x);
72!
  double u = x - i;
73!
  SpectralIrradiance new_irradiance = SolarSpectrum()(lambda);
74!
  SpectralRadiance old_radiance = (originalSolarRadianceTable[i] * (1.0 - u) +
75!
      originalSolarRadianceTable[std::min(i + 1, 10)] * u) *
76!
      watt_per_square_meter_per_sr_per_nm;
77!
  return (new_irradiance / (old_radiance * kSunSolidAngle))();
78
}
79
80
}  // anonymous namespace
81
82!
Hosek::Hosek(double turbidity) : turbidity_(turbidity) {
83!
  for (unsigned int i = 0; i < DimensionlessSpectrum::SIZE; ++i) {
84!
    sky_model_state_[i] = NULL;
85
  }
86
}
87
88!
Hosek::~Hosek() {
89!
  for (unsigned int i = 0; i < DimensionlessSpectrum::SIZE; ++i) {
90!
    if (sky_model_state_[i] != NULL) {
91!
      arhosekskymodelstate_free(sky_model_state_[i]);
92
    }
93
  }
94
}
95
96!
IrradianceSpectrum Hosek::GetSunIrradiance(Length altitude,
97
    Angle sun_zenith) const {
98!
  MaybeInitSkyModelState(sun_zenith);
99!
  IrradianceSpectrum result;
100!
  for (unsigned int i = 0; i < result.size(); ++i) {
101!
    Wavelength lambda = result.GetSample(i);
102!
    if (lambda < 320.0 * nm || lambda > 720.0 * nm) {
103
      // arhosekskymodel_solar_radiance does not work for wavelengths outside
104
      // the 320-720nm range.
105!
      result[i] = 0.0 * watt_per_square_meter_per_nm;
106!
      continue;
107
    }
108!
    double sun_and_sky_radiance = arhosekskymodel_solar_radiance(
109!
        sky_model_state_[i], sun_zenith.to(rad), 0.0, lambda.to(nm));
110!
    double sky_radiance = arhosekskymodel_radiance(
111!
        sky_model_state_[i], sun_zenith.to(rad), 0.0, lambda.to(nm));
112!
    double sun_radiance = (sun_and_sky_radiance - sky_radiance) *
113!
        SolarSpectrumCorrectionFactor(lambda);
114!
    result[i] =
115!
        sun_radiance * watt_per_square_meter_per_sr_per_nm * kSunSolidAngle;
116
  }
117!
  return result;
118
}
119
120!
RadianceSpectrum Hosek::GetSkyRadiance(Length altitude, Angle sun_zenith,
121
    Angle view_zenith, Angle view_sun_azimuth) const {
122!
  MaybeInitSkyModelState(sun_zenith);
123
  double gamma =
124!
      GetViewSunAngle(sun_zenith, view_zenith, view_sun_azimuth).to(rad);
125!
  RadianceSpectrum result;
126!
  for (unsigned int i = 0; i < result.size(); ++i) {
127!
    Wavelength lambda = result.GetSample(i);
128!
    result[i] = arhosekskymodel_radiance(sky_model_state_[i],
129
        view_zenith.to(rad), gamma, lambda.to(nm)) *
130!
        SolarSpectrumCorrectionFactor(lambda) *
131!
        watt_per_square_meter_per_sr_per_nm;
132
  }
133!
  return result;
134
}
135
136!
void Hosek::MaybeInitSkyModelState(Angle sun_zenith) const {
137!
  if (sky_model_state_[0] != NULL && sun_zenith == current_sun_zenith_) {
138!
    return;
139
  }
140!
  if (sky_model_state_[0] != NULL) {
141!
    for (unsigned int i = 0; i < DimensionlessSpectrum::SIZE; ++i) {
142!
      arhosekskymodelstate_free(sky_model_state_[i]);
143
    }
144
  }
145!
  for (unsigned int i = 0; i < DimensionlessSpectrum::SIZE; ++i) {
146!
    sky_model_state_[i] = arhosekskymodelstate_alloc_init(
147!
        (pi / 2.0 - sun_zenith).to(rad), turbidity_, GroundAlbedo()[i]());
148
  }
149!
  current_sun_zenith_ = sun_zenith;
150
}
1
/*
2
This file is included in the skymodelr package, which is distributed as a
3
whole under GPL-3. The following upstream copyright and provenance notice is
4
preserved for attribution and compliance with upstream notice requirements.
5
*/
6
7
/**
8
 Copyright (c) 2015 Eric Bruneton
9
 All rights reserved.
10
11
 Redistribution and use in source and binary forms, with or without
12
 modification, are permitted provided that the following conditions are met:
13
14
 1. Redistributions of source code must retain the above copyright notice, this
15
 list of conditions and the following disclaimer.
16
17
 2. Redistributions in binary form must reproduce the above copyright notice,
18
 this list of conditions and the following disclaimer in the documentation
19
 and/or other materials provided with the distribution.
20
21
 3. Neither the name of the copyright holder nor the names of its contributors
22
 may be used to endorse or promote products derived from this software without
23
 specific prior written permission.
24
25
 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
26
 AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
27
 IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
28
 DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
29
 FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
30
 DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
31
 SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
32
 CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
33
 OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
34
 OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
35
*/
36
#ifndef ATMOSPHERE_ATMOSPHERE_H_
37
#define ATMOSPHERE_ATMOSPHERE_H_
38
39
#include "math/angle.h"
40
#include "units.h"
41
42
constexpr Length EarthRadius = 6360.0 * km;
43
constexpr Length AtmosphereRadius = 6420.0 * km;
44
45
// The height of the atmosphere if its density was uniform.
46
constexpr Length RayleighScaleHeight = 8000.0 * m;
47
48
// The height of the Mie particle layer if its density was uniform.
49
constexpr Length MieScaleHeight = 1200.0 * m;
50
51
// The Angstrom alpha coefficient for the Mie optical depth.
52
constexpr double MieAngstromAlpha = 0.8;
53
54
// The Angstrom beta coefficient for the Mie optical depth.
55
constexpr double MieAngstromBeta = 0.04;
56
57
// The g parameter of the Cornette-Shanks phase function used for Mie particles.
58
constexpr double MiePhaseFunctionG = 0.7;
59
60
// The Linke turbidity value, for the Preetham and Hosek models.
61
constexpr double Turbidity = 2.53;
62
63
// Returns the spectral irradiance of the Sun at the top of the atmosphere.
64
const IrradianceSpectrum& SolarSpectrum();
65
66
// Returns the Rayleigh scattering coefficient at sea level.
67
const ScatteringSpectrum& RayleighScattering();
68
69
// Returns the Mie extinction coefficient at sea level.
70
const ScatteringSpectrum& MieExtinction();
71
72
// Returns the Mie scattering coefficient at sea level.
73
const ScatteringSpectrum& MieScattering();
74
75
// Returns the Mie extinction and scattering coefficients at sea level for
76
// the given Angstrom parameters.
77
ScatteringSpectrum MieExtinction(double angstrom_alpha, double angstrom_beta);
78
ScatteringSpectrum MieScattering(double angstrom_alpha, double angstrom_beta);
79
80
// Computes the Rayleigh phase function for the given scattering angle.
81
// The integral of this function over all solid angles is 1.
82
InverseSolidAngle RayleighPhaseFunction(Angle scattering_angle);
83
InverseSolidAngle RayleighPhaseFunction(Number scattering_angle_cosine);
84
85
// Computes the Mie phase function for the given scattering angle (using
86
// the Cornette-Shanks approximation).
87
// The integral of this function over all solid angles is 1.
88
InverseSolidAngle MiePhaseFunction(Angle scattering_angle);
89
InverseSolidAngle MiePhaseFunction(Number scattering_angle_cosine);
90
InverseSolidAngle MiePhaseFunction(double g, Number scattering_angle_cosine);
91
92
const DimensionlessSpectrum& GroundAlbedo();
93
94
// An abstract atmosphere model.
95
class Atmosphere {
96
 public:
97!
  virtual ~Atmosphere() {}
98
99
  // Returns the number of wavelengths originally used by this atmosphere model.
100
  // The default implementation returns spectrum::NUM_WAVELENGTH.
101
  virtual int GetOriginalNumberOfWavelengths() const;
102
103
  // Returns the irradiance on a plane perpendicular to the Sun direction.
104
  virtual IrradianceSpectrum GetSunIrradiance(Length altitude,
105
      Angle sun_zenith) const = 0;
106
107
  virtual RadianceSpectrum GetSkyRadiance(Length altitude, Angle sun_zenith,
108
      Angle view_zenith, Angle view_sun_azimuth) const = 0;
109
110
  virtual RadianceSpectrum GetSkyRadiance(Length altitude, Angle sun_zenith,
111
      Angle sun_azimuth, Angle view_zenith, Angle view_azimuth) const;
112
113
  // Returns the irradiance on a horizontal plane.
114
  virtual IrradianceSpectrum GetSkyIrradiance(Length altitude,
115
      Angle sun_zenith) const;
116
117
 protected:
118
  static Angle GetViewSunAngle(Angle sun_zenith, Angle view_zenith,
119
      Angle view_sun_azimuth);
120
};
121
122
#endif  // ATMOSPHERE_ATMOSPHERE_H_
1
/*
2
This file is included in the skymodelr package, which is distributed as a
3
whole under GPL-3. The following upstream copyright and provenance notice is
4
preserved for attribution and compliance with upstream notice requirements.
5
*/
6
7
/**
8
 Copyright (c) 2015 Eric Bruneton
9
 All rights reserved.
10
11
 Redistribution and use in source and binary forms, with or without
12
 modification, are permitted provided that the following conditions are met:
13
14
 1. Redistributions of source code must retain the above copyright notice, this
15
 list of conditions and the following disclaimer.
16
17
 2. Redistributions in binary form must reproduce the above copyright notice,
18
 this list of conditions and the following disclaimer in the documentation
19
 and/or other materials provided with the distribution.
20
21
 3. Neither the name of the copyright holder nor the names of its contributors
22
 may be used to endorse or promote products derived from this software without
23
 specific prior written permission.
24
25
 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
26
 AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
27
 IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
28
 DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
29
 FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
30
 DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
31
 SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
32
 CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
33
 OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
34
 OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
35
*/
36
#ifndef ATMOSPHERE_MODEL_HOSEK_HOSEK_H_
37
#define ATMOSPHERE_MODEL_HOSEK_HOSEK_H_
38
39
#include "atmosphere.h"
40
#include "math/angle.h"
41
#include "units.h"
42
43
struct ArHosekSkyModelState;
44
45
class Hosek : public Atmosphere {
46
 public:
47
  explicit Hosek(double turbidity);
48
  virtual ~Hosek();
49
50!
  int GetOriginalNumberOfWavelengths() const override { return 11; }
51
52
  IrradianceSpectrum GetSunIrradiance(Length altitude,
53
      Angle sun_zenith) const override;
54
55
  RadianceSpectrum GetSkyRadiance(Length altitude, Angle sun_zenith,
56
      Angle view_zenith, Angle view_sun_azimuth) const override;
57
58
 private:
59
  void MaybeInitSkyModelState(Angle sun_zenith) const;
60
61
  double turbidity_;
62
  mutable Angle current_sun_zenith_;
63
  mutable ArHosekSkyModelState* sky_model_state_[DimensionlessSpectrum::SIZE];
64
};
65
66
#endif  // ATMOSPHERE_MODEL_HOSEK_HOSEK_H_
1
#include <Rcpp.h>
2
#include <RcppThread.h>
3
4
extern "C" {
5
#include "ArHosekSkyModel.h"
6
}
7
8
#include "PragueSkyModel.h"
9
#include "prague_metal_backend.h"
10
11
#include "CIE1931Data.h"
12
#include <Imath/ImathBox.h>
13
#include <Imath/ImathFun.h>
14
#include <Imath/ImathVec.h>
15
16
#include <algorithm>
17
#include <cctype>
18
#include <cmath>
19
#include <iterator>
20
#include <string>
21
#include <vector>
22
23
using namespace Imath;
24
2511750948x
static inline double clamp_double(double x, double a, double b) {
2611750948x
  return (x < a) ? a : (x > b) ? b : x;
27
}
28
2927x
static inline double clamp_sun_elevation_deg(double elevation_deg,
30
                                             double epsilon_deg = 1e-4) {
31
  // Avoid singularities at exactly 90 deg while preserving user-facing limits.
3227x
  const double kMaxSunElevationDeg = 90.0;
3327x
  if (elevation_deg >= kMaxSunElevationDeg) {
344x
    return kMaxSunElevationDeg - epsilon_deg;
35
  }
3623x
  return elevation_deg;
37
}
38
3913x
static inline std::string normalize_render_mode(std::string mode) {
4013x
  std::transform(mode.begin(), mode.end(), mode.begin(), [](unsigned char c) {
4153x
    return static_cast<char>(std::tolower(c));
42
  });
4313x
  if (mode == "true") {
44!
    return "all";
45
  }
4613x
  if (mode == "false") {
47!
    return "atmosphere";
48
  }
4913x
  return mode;
50
}
51
5213x
static inline void resolve_render_mode(const std::string &render_mode,
53
                                       bool &render_atmosphere,
54
                                       bool &render_sun) {
5513x
  const std::string mode = normalize_render_mode(render_mode);
5613x
  if (mode == "all") {
577x
    render_atmosphere = true;
587x
    render_sun = true;
597x
    return;
60
  }
616x
  if (mode == "atmosphere") {
622x
    render_atmosphere = true;
632x
    render_sun = false;
642x
    return;
65
  }
664x
  if (mode == "sun") {
674x
    render_atmosphere = false;
684x
    render_sun = true;
694x
    return;
70
  }
71!
  Rcpp::stop("render_mode must be one of \"all\", \"atmosphere\", or \"sun\"");
72
}
73
74
// Forward conversion to Prague's tiny Vector3 wrapper
75!
static inline PragueSkyModel::Vector3 toPrague(const Vec3<double> &v) {
76!
  return {double(v.x), double(v.y), double(v.z)};
77
}
78
79
// Static instance so the .dat stays in RAM across calls
80
static PragueSkyModel prague_model;
81
static std::string prague_loaded_file;
82
83
static PragueSkyModel::AvailableData
84!
initialize_prague_model(const std::string &prg_dataset) {
85!
  if (prg_dataset.empty()) {
86!
    Rcpp::stop("prg_dataset must be supplied when model=\"prague\"");
87
  }
88
89!
  if (prague_loaded_file != prg_dataset) {
90!
    prague_model.initialize(prg_dataset);
91!
    prague_loaded_file = prg_dataset;
92
  }
93
94!
  return prague_model.getAvailableData();
95
}
96
97
static inline double
98!
prague_lambda_upper_nm(const PragueSkyModel::AvailableData &avail) {
99!
  return avail.channelStart + avail.channels * avail.channelWidth;
100
}
101
102!
static void validate_prague_lambda_nm(
103
    const Rcpp::NumericVector &lambda_nm,
104
    const PragueSkyModel::AvailableData &avail) {
105!
  const double lambda_upper = prague_lambda_upper_nm(avail);
106!
  for (R_xlen_t i = 0; i < lambda_nm.size(); ++i) {
107!
    const double lam = lambda_nm[i];
108!
    if (!std::isfinite(lam) || lam < avail.channelStart || lam >= lambda_upper) {
109!
      Rcpp::stop("lambda_nm entries must be within [%f, %f)",
110!
                 avail.channelStart, lambda_upper);
111
    }
112
  }
113
}
114
11511750948x
static inline void xyz_to_srgb(double X, double Y, double Z, double &R,
116
                               double &G, double &B) {
117
  // IEC 61966-2-1 sRGB (D65), 1931 2
118
  const double M[9] = {3.2404542, -1.5371385, -0.4985314, -0.9692660, 1.8760108,
119
                       0.0415560, 0.0556434,  -0.2040259, 1.0572252};
12011750948x
  R = M[0] * X + M[1] * Y + M[2] * Z;
12111750948x
  G = M[3] * X + M[4] * Y + M[5] * Z;
12211750948x
  B = M[6] * X + M[7] * Y + M[8] * Z;
123
}
124
125
struct CIETristimulus {
126
  double x;
127
  double y;
128
  double z;
129
};
130
13112x
static const std::vector<double> &default_lambda_low() {
132
  static const double lambda_low_arr[] = {360, 380, 400, 420, 440, 460,
133
                                          480, 500, 520, 540, 560, 580,
134
                                          600, 620, 640, 660, 680, 700};
135
  static const std::vector<double> lambda_low(std::begin(lambda_low_arr),
13615x
                                              std::end(lambda_low_arr));
13712x
  return lambda_low;
138
}
139
140270x
static CIETristimulus interpolate_cie_xyz(double lambda_nm_value) {
141270x
  constexpr int n = CIE_N;
142270x
  if (lambda_nm_value < cie_lambda_nm[0] ||
143270x
      lambda_nm_value > cie_lambda_nm[n - 1]) {
144!
    Rcpp::stop("lambda_nm entries must be within [%f, %f]", cie_lambda_nm[0],
145
               cie_lambda_nm[n - 1]);
146
  }
147270x
  const auto begin = std::begin(cie_lambda_nm);
148513x
  const auto end = std::end(cie_lambda_nm);
149
150270x
  auto upper = std::lower_bound(begin, end, lambda_nm_value);
151
152270x
  if (upper == begin) {
15327x
    return {cie_xbar[0], cie_ybar[0], cie_zbar[0]};
154
  }
155243x
  if (upper == end) {
156!
    const int last = n - 1;
157!
    return {cie_xbar[last], cie_ybar[last], cie_zbar[last]};
158
  }
159
160243x
  const int idx_hi = int(upper - begin);
161243x
  const int idx_lo = idx_hi - 1;
162
163243x
  if (*upper == lambda_nm_value) {
164243x
    return {cie_xbar[idx_hi], cie_ybar[idx_hi], cie_zbar[idx_hi]};
165
  }
166
167!
  const double lam_lo = cie_lambda_nm[idx_lo];
168!
  const double lam_hi = cie_lambda_nm[idx_hi];
169!
  const double t = (lambda_nm_value - lam_lo) / (lam_hi - lam_lo);
170!
  const double x = cie_xbar[idx_lo] + t * (cie_xbar[idx_hi] - cie_xbar[idx_lo]);
171!
  const double y = cie_ybar[idx_lo] + t * (cie_ybar[idx_hi] - cie_ybar[idx_lo]);
172!
  const double z = cie_zbar[idx_lo] + t * (cie_zbar[idx_hi] - cie_zbar[idx_lo]);
173!
  return {x, y, z};
174
}
175
176
static std::vector<double>
17727x
trapezoid_weights(const std::vector<double> &lambda_values) {
17827x
  const size_t n = lambda_values.size();
17927x
  std::vector<double> weights(n, 0.0);
18027x
  if (n == 0)
181!
    return weights;
18227x
  if (n == 1) {
183!
    weights[0] = 1.0;
184!
    return weights;
185
  }
186297x
  for (size_t i = 0; i < n; ++i) {
187270x
    if (i == 0) {
18827x
      weights[i] = (lambda_values[1] - lambda_values[0]) / 2.0;
189243x
    } else if (i == n - 1) {
19027x
      weights[i] = (lambda_values[i] - lambda_values[i - 1]) / 2.0;
191
    } else {
192216x
      weights[i] = (lambda_values[i + 1] - lambda_values[i - 1]) / 2.0;
193
    }
194
  }
19527x
  return weights;
196
}
197
198
// Evaluate a Hosek solar disk in its own tangent plane. Its resolution is
199
// independent of the environment map, so preview quality cannot erase the Sun.
200
// [[Rcpp::export]]
20115x
Rcpp::NumericVector hosek_sun_disk_rcpp(double elevation, double azimuth, double albedo,
202
                                        double turbidity, unsigned int resolution,
203
                                        unsigned int number_cores) {
20430x
  if (!std::isfinite(elevation) || elevation < -90 || elevation > 90 ||
20515x
      !std::isfinite(azimuth) || !std::isfinite(albedo) || albedo < 0 || albedo > 1 ||
20615x
      !std::isfinite(turbidity) || turbidity < 1.7 || turbidity > 10 ||
20730x
      resolution < 16 || number_cores < 1) {
208!
    Rcpp::stop("Invalid Hosek solar disk inputs.");
209
  }
21015x
  const size_t count = size_t(resolution) * resolution;
21115x
  Rcpp::NumericVector image(count * 3);
21245x
  image.attr("dim") = Rcpp::IntegerVector::create(resolution, resolution, 3);
213
  // Below the model's daylight domain, retain the horizon profile until the
214
  // upper limb sets. The renderer clips each direction against the horizon.
21515x
  const double safe_elevation = clamp_sun_elevation_deg(std::max(0.0, elevation));
216
  ArHosekSkyModelState* state =
21715x
      arhosekskymodelstate_alloc_init(safe_elevation * M_PI / 180, turbidity, albedo);
21815x
  if (!state) {
219!
    Rcpp::stop("Hosek-Wilkie initialisation failed.");
220
  }
22115x
  if (elevation < -state->solar_radius * 180 / M_PI) {
222!
    arhosekskymodelstate_free(state);
223!
    return image;
224
  }
22515x
  const double elev = elevation * M_PI / 180;
22615x
  const double az = azimuth * M_PI / 180;
227
  Vec3<double> forward(
22815x
      -std::sin(az) * std::cos(elev), std::sin(elev), std::cos(az) * std::cos(elev));
229
  // Match the renderer's frame, including its alternate up axis at the pole.
230
  Vec3<double> vertical =
23115x
      std::abs(forward.y) < 0.999999 ? Vec3<double>(0, 1, 0) : Vec3<double>(0, 0, 1);
23215x
  Vec3<double> right = forward.cross(vertical).normalized();
23315x
  Vec3<double> up = right.cross(forward);
23415x
  const double radius = std::tan(state->solar_radius);
235
  const std::vector<double> wavelengths = {
23630x
      360, 400, 440, 480, 520, 560, 600, 640, 680, 720};
23715x
  const auto weights = trapezoid_weights(wavelengths);
23815x
  std::vector<CIETristimulus> cie;
239180x
  for (double wavelength : wavelengths) {
240150x
    cie.push_back(interpolate_cie_xyz(wavelength));
241
  }
24215x
  RcppThread::parallelFor(
243
      0u,
244
      size_t(resolution),
245512x
      [&](size_t row) {
246512x
        const double y = 1 - 2 * (row + 0.5) / resolution;
24718944x
        for (size_t column = 0; column < resolution; ++column) {
24818432x
          const double x = 2 * (column + 0.5) / resolution - 1;
24918432x
          if (x * x + y * y > 1) {
2503836x
            continue;
251
          }
252
          const Vec3<double> direction =
25314596x
              (forward + radius * (x * right + y * up)).normalized();
254
          // Horizon samples use finite horizon radiance; visibility is not baked
255
          // into the texture. Clamp zenith numerically without shifting disk geometry.
25614596x
          const double theta = std::acos(clamp_double(direction.y, 0.0, 1.0 - 1e-12));
25714596x
          const double gamma = std::atan(radius * std::sqrt(x * x + y * y));
25814596x
          double X = 0, Y = 0, Z = 0;
259160556x
          for (size_t c = 0; c < wavelengths.size(); ++c) {
260
            const double total =
261145960x
                arhosekskymodel_solar_radiance(state, theta, gamma, wavelengths[c]);
262
            const double sky =
263145960x
                arhosekskymodel_radiance(state, theta, gamma, wavelengths[c]);
264145960x
            const double value = std::max(0.0, total - sky) * weights[c];
265145960x
            X += value * cie[c].x;
266145960x
            Y += value * cie[c].y;
267145960x
            Z += value * cie[c].z;
268
          }
269
          double R, G, B;
27014596x
          xyz_to_srgb(X, Y, Z, R, G, B);
27114596x
          const size_t pixel = row + resolution * column;
27214596x
          image[pixel] = R;
27314596x
          image[pixel + count] = G;
27414596x
          image[pixel + 2 * count] = B;
275
        }
276
      },
277
      number_cores);
27815x
  arhosekskymodelstate_free(state);
27915x
  return image;
280
}
281
282
// [[Rcpp::export]]
283
Rcpp::NumericVector
28412x
makesky_rcpp(double albedo = 0.5, double turbidity = 3.0, double elevation = 10.0,
285
             double azimuth_deg = 90, unsigned int resolution = 2048,
286
             unsigned int number_cores = 1,
287
             std::string model = "hosek", // hosek | prague
288
             std::string prg_dataset = "", double altitude = 0.0,
289
             double visibility = 50.0, // Prague only (km)
290
             std::string render_mode = "all",
291
             Rcpp::Nullable<Rcpp::NumericVector> lambda_nm = R_NilValue,
292
             bool below_horizon = true) {
29312x
  bool render_atmosphere = true;
29412x
  bool render_sun = true;
29512x
  resolve_render_mode(render_mode, render_atmosphere, render_sun);
296
29712x
  if (albedo < 0.0 || albedo > 1.0) {
298!
    Rcpp::stop("albedo must be in [0,1]");
299
  }
30012x
  if (resolution == 0) {
301!
    Rcpp::stop("resolution must be >= 1");
302
  }
303
304
  // Nudge zenith by at least half a texel to keep the sun disk sampled at 90
305
  // deg.
306
  const double elev_epsilon_deg =
30712x
      std::max(0.5 * 180.0 / static_cast<double>(resolution), 1e-4);
308
  const double safe_elevation =
30912x
      clamp_sun_elevation_deg(elevation, elev_epsilon_deg);
31012x
  double elev_rad = safe_elevation * M_PI / 180.0;
31112x
  double az_rad = azimuth_deg * M_PI / 180.0;
312
313
  // Prague model initialisation
31412x
  PragueSkyModel::AvailableData avail{};
31512x
  if (model == "prague") {
316!
    if (prg_dataset.empty()) {
317!
      Rcpp::stop("prg_dataset must be supplied when model=\"prague\"");
318
    }
319
320!
    if (prague_loaded_file != prg_dataset) {
321!
      prague_model.initialize(prg_dataset);
322!
      prague_loaded_file = prg_dataset;
323
    }
324!
    avail = prague_model.getAvailableData();
325!
    if (albedo < avail.albedoMin || albedo > avail.albedoMax ||
326!
        visibility < avail.visibilityMin || visibility > avail.visibilityMax) {
327!
      Rcpp::stop("albedo or visibility outside dataset range");
328
    }
32912x
  } else if (model != "hosek") {
330!
    Rcpp::stop("unknown model \"%s\"", model.c_str());
331
  }
332
333
  // Spectral sampling setup
33412x
  std::vector<double> lambda_values;
33512x
  std::vector<double> lambda_weights;
33612x
  std::vector<CIETristimulus> cie_samples;
337
33812x
  if (model == "prague") {
339
    // Prague sampling is locked to dataset channel centers within CIE bounds
340
    // (380-740 nm).
341!
    lambda_values.reserve(avail.channels);
342!
    for (int i = 0; i < avail.channels; ++i) {
343!
      const double lam = avail.channelStart + (i + 0.5) * avail.channelWidth;
344!
      if (lam >= 380.0 && lam <= 740.0) {
345!
        lambda_values.push_back(lam);
346
      }
347
    }
348!
    if (lambda_values.empty()) {
349!
      Rcpp::stop("No Prague spectral channels fall within [380, 740] nm.");
350
    }
351
    // Prague channels are evenly spaced bands.
352!
    lambda_weights.assign(lambda_values.size(), avail.channelWidth);
353!
    cie_samples.reserve(lambda_values.size());
354!
    for (double lam : lambda_values) {
355!
      cie_samples.push_back(interpolate_cie_xyz(lam));
356
    }
357
358
  } else {
359
    // Hosek path (unchanged behavior)
36012x
    const auto &default_values = default_lambda_low();
361
36212x
    if (lambda_nm.isNull()) {
363!
      lambda_values.assign(default_values.begin(), default_values.end());
364
    } else {
36512x
      Rcpp::NumericVector lambda_vec(lambda_nm.get());
36612x
      if (lambda_vec.size() == 0) {
367!
        lambda_values.assign(default_values.begin(), default_values.end());
368
      } else {
36912x
        lambda_values.assign(lambda_vec.begin(), lambda_vec.end());
370
      }
371
    }
372
37312x
    if (lambda_values.size() < 2) {
374!
      Rcpp::stop("lambda_nm must contain at least two wavelengths");
375
    }
376120x
    for (size_t i = 1; i < lambda_values.size(); ++i) {
377108x
      if (!(lambda_values[i] > lambda_values[i - 1])) {
378!
        Rcpp::stop("lambda_nm must be strictly increasing");
379
      }
380
    }
381
38212x
    lambda_weights = trapezoid_weights(lambda_values);
383
38412x
    cie_samples.reserve(lambda_values.size());
385144x
    for (double lam : lambda_values) {
386120x
      cie_samples.push_back(interpolate_cie_xyz(lam));
387
    }
388
  }
389
39012x
  const size_t N_LAMBDA = lambda_values.size();
391
39212x
  ArHosekSkyModelState *hosek = nullptr;
39312x
  if (model == "hosek") {
39412x
    if (elevation < 0.0 || elevation > 90.0) {
395!
      Rcpp::stop("elevation must be in [0,90]");
396
    }
39712x
    if (turbidity < 1.7 || turbidity > 10.0) {
398!
      Rcpp::stop("turbidity must be in [1.7,10]");
399
    }
40012x
    hosek = arhosekskymodelstate_alloc_init(elev_rad, turbidity, albedo);
40112x
    if (!hosek)
402!
      Rcpp::stop("Hosek-Wilkie initialisation failed");
403
404
  } else {
405!
    if (elevation < -4.2 || elevation > 90.0) {
406!
      Rcpp::stop("elevation must be in [-4.2, 90]");
407
    }
408
  }
409
410
  // Initialize image buffer
41112x
  const int nTheta = resolution;   // rows  (latitude)
41212x
  const int nPhi = 2 * resolution; // cols  (longitude)
41312x
  std::vector<double> img(3 * nTheta * nPhi, 0.0);
41412x
  std::vector<double> img_band(nTheta * nPhi, 0.0);
415
416
  //   Vec3<double> sun_dir(0.0, std::sin(elev_rad), std::cos(elev_rad));
41712x
  Vec3<double> sun_dir(std::cos(az_rad) * std::cos(elev_rad),  // +X (South)
418
                       std::sin(elev_rad),                     // +Y (Up)
41912x
                       std::sin(az_rad) * std::cos(elev_rad)); // +Z (West)
420
  // Render loop (parallel over rows)
42112x
  RcppThread::parallelFor(
422
      0u, size_t(nTheta),
4234804x
      [&](size_t t) {
4244804x
        double theta =
4254804x
            (static_cast<double>(t) + 0.5) / static_cast<double>(nTheta) * M_PI;
426
4274804x
        if (!below_horizon && theta > M_PI_2) {
428!
          return;
429
        }
430
43111741156x
        for (int p = 0; p < nPhi; ++p) {
43211736352x
          double phi = (static_cast<double>(p) + 0.5) / nPhi * 2.0 * M_PI;
433
43411736352x
          Vec3<double> v(std::cos(phi) * std::sin(theta),
435
                         std::cos(theta),
43611736352x
                         std::sin(phi) * std::sin(theta));
437
43811736352x
          double X = 0.0, Y = 0.0, Z = 0.0;
43911736352x
          double L_band = 0.0;
44011736352x
          const bool view_above_horizon = theta <= M_PI_2;
441
44211736352x
          if (model == "hosek") {
44311736352x
            double gamma = std::acos(clamp_double(v.dot(sun_dir), -1.0, 1.0));
444129099872x
            for (size_t c = 0; c < N_LAMBDA; ++c) {
445117363520x
              const double lam = lambda_values[c];
446117363520x
              double L = 0.0;
447117363520x
              if (render_atmosphere) {
44885258240x
                if (render_sun && view_above_horizon) {
44942627840x
                  L = arhosekskymodel_solar_radiance(hosek, theta, gamma, lam);
450
                } else {
45142630400x
                  L = arhosekskymodel_radiance(hosek, theta, gamma, lam);
452
                }
45332105280x
              } else if (render_sun && view_above_horizon) {
454
                const double L_total =
45516052640x
                    arhosekskymodel_solar_radiance(hosek, theta, gamma, lam);
456
                const double L_sky =
45716052640x
                    arhosekskymodel_radiance(hosek, theta, gamma, lam);
45816052640x
                L = L_total - L_sky;
45916052640x
                if (L < 0.0) {
460!
                  L = 0.0;
461
                }
462
              }
463
              // Accumulate XYZ
464117363520x
              double Li = static_cast<double>(L);
465117363520x
              const double d_lambda = lambda_weights[c];
466117363520x
              X += Li * cie_samples[c].x * d_lambda;
467117363520x
              Y += Li * cie_samples[c].y * d_lambda;
468117363520x
              Z += Li * cie_samples[c].z * d_lambda;
469117363520x
              L_band += Li * d_lambda;
470
            }
471
          } else {
472
            // Prague uses Z-up vector
473!
            Vec3<double> v_zup(std::cos(phi) * std::sin(theta),
474!
                               std::sin(phi) * std::sin(theta),
475!
                               std::cos(theta));
476!
            auto P = prague_model.computeParameters({0.0, 0.0, altitude},
477!
                                                    toPrague(v_zup), elev_rad,
478
                                                    az_rad, visibility, albedo);
479
480!
            for (size_t i = 0; i < N_LAMBDA; ++i) {
481!
              double Li = 0.0;
482!
              if (render_atmosphere) {
483!
                Li = prague_model.skyRadiance(P, lambda_values[i]);
484
              }
485!
              if (render_sun && view_above_horizon) {
486
                const double sun =
487!
                    prague_model.sunRadiance(P, lambda_values[i]);
488!
                Li = render_atmosphere ? (Li + sun) : sun;
489
              }
490!
              const double d_lambda = lambda_weights[i];
491!
              X += Li * cie_samples[i].x * d_lambda;
492!
              Y += Li * cie_samples[i].y * d_lambda;
493!
              Z += Li * cie_samples[i].z * d_lambda;
494!
              L_band += Li * d_lambda;
495
            }
496
          }
49711736352x
          if (!std::isfinite(X) || !std::isfinite(Y) || !std::isfinite(Z)) {
4984262912x
            X = 0.0;
4994262912x
            Y = 0.0;
5004262912x
            Z = 0.0;
501
          }
502
          double R, G, B;
50311736352x
          xyz_to_srgb(X, Y, Z, R, G, B);
504
50511736352x
          if (!std::isfinite(R) || !std::isfinite(G) || !std::isfinite(B)) {
506!
            R = 0.0;
507!
            G = 0.0;
508!
            B = 0.0;
509
          }
510
51111736352x
          const int idx = 3 * (int(t) * nPhi + p);
51211736352x
          img[idx + 0] = R;
51311736352x
          img[idx + 1] = G;
51411736352x
          img[idx + 2] = B;
51511736352x
          img_band[int(t) * nPhi + p] = L_band;
516
        }
517
      },
518
      number_cores);
519
52012x
  const int width = nPhi;
52112x
  const int height = nTheta;
52212x
  const int nPix = width * height;
523
52412x
  if (model == "hosek") {
52512x
    arhosekskymodelstate_free(hosek);
526
  }
527
52812x
  Rcpp::NumericVector result(nPix * 3);
52936x
  result.attr("dim") = Rcpp::IntegerVector::create(height, width, 3);
530
5314816x
  for (int t = 0; t < height; ++t) {
53211741156x
    for (int p = 0; p < width; ++p) {
53311736352x
      const int pix_index = t * width + p;
53446945408x
      for (int c = 0; c < 3; ++c) {
53535209056x
        const int arr_index = t + height * (p + width * c);
53635209056x
        result[arr_index] = img[3 * pix_index + c];
537
      }
538
    }
539
  }
540
54112x
  Rcpp::NumericVector band(nPix);
54236x
  band.attr("dim") = Rcpp::IntegerVector::create(height, width);
5434816x
  for (int t = 0; t < height; ++t) {
54411741156x
    for (int p = 0; p < width; ++p) {
54511736352x
      const int pix_index = t * width + p;
54611736352x
      band[pix_index] = img_band[pix_index];
547
    }
548
  }
54912x
  result.attr("L_band") = band;
550
55112x
  return result;
552
}
553
554
// [[Rcpp::export]]
555!
double calculate_sun_brightness_rcpp(
556
    double albedo = 0.5, double turbidity = 3.0, double elevation = 10.0,
557
    double azimuth_deg = 90.0, std::string model = "hosek",
558
    std::string prg_dataset = "", double altitude = 0.0,
559
    double visibility = 50.0,
560
    Rcpp::Nullable<Rcpp::NumericVector> lambda_nm = R_NilValue) {
561!
  if (albedo < 0.0 || albedo > 1.0) {
562!
    Rcpp::stop("albedo must be in [0,1]");
563
  }
564
565!
  const double safe_elevation = clamp_sun_elevation_deg(elevation);
566!
  const double elev_rad = safe_elevation * M_PI / 180.0;
567!
  const double az_rad = azimuth_deg * M_PI / 180.0;
568
569
  // Prague model initialisation
570!
  PragueSkyModel::AvailableData avail{};
571!
  if (model == "prague") {
572!
    if (prg_dataset.empty()) {
573!
      Rcpp::stop("prg_dataset must be supplied when model=\"prague\"");
574
    }
575
576!
    if (prague_loaded_file != prg_dataset) {
577!
      prague_model.initialize(prg_dataset);
578!
      prague_loaded_file = prg_dataset;
579
    }
580!
    avail = prague_model.getAvailableData();
581!
    if (albedo < avail.albedoMin || albedo > avail.albedoMax ||
582!
        visibility < avail.visibilityMin || visibility > avail.visibilityMax) {
583!
      Rcpp::stop("albedo or visibility outside dataset range");
584
    }
585!
  } else if (model != "hosek") {
586!
    Rcpp::stop("unknown model \"%s\"", model.c_str());
587
  }
588
589
  // Spectral sampling setup
590!
  std::vector<double> lambda_values;
591!
  std::vector<double> lambda_weights;
592!
  std::vector<double> cie_y_samples;
593
594!
  if (model == "prague") {
595
    // Prague sampling is locked to dataset channel centers within CIE bounds
596
    // (380-740 nm).
597!
    lambda_values.reserve(avail.channels);
598!
    for (int i = 0; i < avail.channels; ++i) {
599!
      const double lam = avail.channelStart + (i + 0.5) * avail.channelWidth;
600!
      if (lam >= 380.0 && lam <= 740.0) {
601!
        lambda_values.push_back(lam);
602
      }
603
    }
604!
    if (lambda_values.empty()) {
605!
      Rcpp::stop("No Prague spectral channels fall within [380, 740] nm.");
606
    }
607
    // Prague channels are evenly spaced bands.
608!
    lambda_weights.assign(lambda_values.size(), avail.channelWidth);
609!
    cie_y_samples.reserve(lambda_values.size());
610!
    for (double lam : lambda_values) {
611!
      cie_y_samples.push_back(interpolate_cie_xyz(lam).y);
612
    }
613
  } else {
614
    // Hosek path (unchanged behavior)
615!
    const auto &default_values = default_lambda_low();
616
617!
    if (lambda_nm.isNull()) {
618!
      lambda_values.assign(default_values.begin(), default_values.end());
619
    } else {
620!
      Rcpp::NumericVector lambda_vec(lambda_nm.get());
621!
      if (lambda_vec.size() == 0) {
622!
        lambda_values.assign(default_values.begin(), default_values.end());
623
      } else {
624!
        lambda_values.assign(lambda_vec.begin(), lambda_vec.end());
625
      }
626
    }
627
628!
    if (lambda_values.size() < 2) {
629!
      Rcpp::stop("lambda_nm must contain at least two wavelengths");
630
    }
631!
    for (size_t i = 1; i < lambda_values.size(); ++i) {
632!
      if (!(lambda_values[i] > lambda_values[i - 1])) {
633!
        Rcpp::stop("lambda_nm must be strictly increasing");
634
      }
635
    }
636
637!
    lambda_weights = trapezoid_weights(lambda_values);
638
639!
    cie_y_samples.reserve(lambda_values.size());
640!
    for (double lam : lambda_values) {
641!
      cie_y_samples.push_back(interpolate_cie_xyz(lam).y);
642
    }
643
  }
644
645!
  const size_t N_LAMBDA = lambda_values.size();
646!
  double Y = 0.0;
647
648!
  if (model == "hosek") {
649!
    if (elevation < 0.0 || elevation > 90.0) {
650!
      Rcpp::stop("elevation must be in [0,90]");
651
    }
652!
    if (turbidity < 1.7 || turbidity > 10.0) {
653!
      Rcpp::stop("turbidity must be in [1.7,10]");
654
    }
655
656
    ArHosekSkyModelState *hosek =
657!
        arhosekskymodelstate_alloc_init(elev_rad, turbidity, albedo);
658!
    if (!hosek) {
659!
      Rcpp::stop("Hosek-Wilkie initialisation failed");
660
    }
661
662!
    const double theta = M_PI_2 - elev_rad;
663!
    const double gamma = 0.0;
664!
    for (size_t c = 0; c < N_LAMBDA; ++c) {
665!
      const double lam = lambda_values[c];
666!
      const double L = arhosekskymodel_solar_radiance(hosek, theta, gamma, lam);
667!
      const double d_lambda = lambda_weights[c];
668!
      Y += L * cie_y_samples[c] * d_lambda;
669
    }
670!
    arhosekskymodelstate_free(hosek);
671
  } else {
672!
    if (elevation < -4.2 || elevation > 90.0) {
673!
      Rcpp::stop("elevation must be in [-4.2, 90]");
674
    }
675
676
    // Sample sun radiance along the sun direction.
677!
    Vec3<double> sun_dir(std::cos(az_rad) * std::cos(elev_rad),
678!
                         std::sin(az_rad) * std::cos(elev_rad),
679!
                         std::sin(elev_rad));
680
    auto P =
681!
        prague_model.computeParameters({0.0, 0.0, altitude}, toPrague(sun_dir),
682
                                       elev_rad, az_rad, visibility, albedo);
683
684!
    for (size_t i = 0; i < N_LAMBDA; ++i) {
685!
      const double Li = prague_model.sunRadiance(P, lambda_values[i]);
686!
      const double d_lambda = lambda_weights[i];
687!
      Y += Li * cie_y_samples[i] * d_lambda;
688
    }
689
  }
690
691!
  if (!std::isfinite(Y)) {
692!
    Y = 0.0;
693
  }
694
695!
  return Y;
696
}
697
698
// [[Rcpp::export]]
699!
double calculate_sun_radiance_band_rcpp(
700
    double albedo = 0.5, double turbidity = 3.0, double elevation = 10.0,
701
    double azimuth_deg = 90.0, std::string model = "hosek",
702
    std::string prg_dataset = "", double altitude = 0.0,
703
    double visibility = 50.0,
704
    Rcpp::Nullable<Rcpp::NumericVector> lambda_nm = R_NilValue) {
705!
  if (albedo < 0.0 || albedo > 1.0) {
706!
    Rcpp::stop("albedo must be in [0,1]");
707
  }
708
709!
  const double safe_elevation = clamp_sun_elevation_deg(elevation);
710!
  const double elev_rad = safe_elevation * M_PI / 180.0;
711!
  const double az_rad = azimuth_deg * M_PI / 180.0;
712
713
  // Prague model initialisation
714!
  PragueSkyModel::AvailableData avail{};
715!
  if (model == "prague") {
716!
    if (prg_dataset.empty()) {
717!
      Rcpp::stop("prg_dataset must be supplied when model=\"prague\"");
718
    }
719
720!
    if (prague_loaded_file != prg_dataset) {
721!
      prague_model.initialize(prg_dataset);
722!
      prague_loaded_file = prg_dataset;
723
    }
724!
    avail = prague_model.getAvailableData();
725!
    if (albedo < avail.albedoMin || albedo > avail.albedoMax ||
726!
        visibility < avail.visibilityMin || visibility > avail.visibilityMax) {
727!
      Rcpp::stop("albedo or visibility outside dataset range");
728
    }
729!
  } else if (model != "hosek") {
730!
    Rcpp::stop("unknown model \"%s\"", model.c_str());
731
  }
732
733
  // Spectral sampling setup
734!
  std::vector<double> lambda_values;
735!
  std::vector<double> lambda_weights;
736
737!
  if (model == "prague") {
738!
    lambda_values.reserve(avail.channels);
739!
    for (int i = 0; i < avail.channels; ++i) {
740!
      const double lam = avail.channelStart + (i + 0.5) * avail.channelWidth;
741!
      if (lam >= 380.0 && lam <= 740.0) {
742!
        lambda_values.push_back(lam);
743
      }
744
    }
745!
    if (lambda_values.empty()) {
746!
      Rcpp::stop("No Prague spectral channels fall within [380, 740] nm.");
747
    }
748!
    lambda_weights.assign(lambda_values.size(), avail.channelWidth);
749
  } else {
750!
    const auto &default_values = default_lambda_low();
751
752!
    if (lambda_nm.isNull()) {
753!
      lambda_values.assign(default_values.begin(), default_values.end());
754
    } else {
755!
      Rcpp::NumericVector lambda_vec(lambda_nm.get());
756!
      if (lambda_vec.size() == 0) {
757!
        lambda_values.assign(default_values.begin(), default_values.end());
758
      } else {
759!
        lambda_values.assign(lambda_vec.begin(), lambda_vec.end());
760
      }
761
    }
762
763!
    if (lambda_values.size() < 2) {
764!
      Rcpp::stop("lambda_nm must contain at least two wavelengths");
765
    }
766!
    for (size_t i = 1; i < lambda_values.size(); ++i) {
767!
      if (!(lambda_values[i] > lambda_values[i - 1])) {
768!
        Rcpp::stop("lambda_nm must be strictly increasing");
769
      }
770
    }
771
772!
    lambda_weights = trapezoid_weights(lambda_values);
773
  }
774
775!
  const size_t N_LAMBDA = lambda_values.size();
776!
  double L_band = 0.0;
777
778!
  if (model == "hosek") {
779!
    if (elevation < 0.0 || elevation > 90.0) {
780!
      Rcpp::stop("elevation must be in [0,90]");
781
    }
782!
    if (turbidity < 1.7 || turbidity > 10.0) {
783!
      Rcpp::stop("turbidity must be in [1.7,10]");
784
    }
785
786
    ArHosekSkyModelState *hosek =
787!
        arhosekskymodelstate_alloc_init(elev_rad, turbidity, albedo);
788!
    if (!hosek) {
789!
      Rcpp::stop("Hosek-Wilkie initialisation failed");
790
    }
791
792!
    const double theta = M_PI_2 - elev_rad;
793!
    const double gamma = 0.0;
794!
    for (size_t c = 0; c < N_LAMBDA; ++c) {
795!
      const double lam = lambda_values[c];
796!
      const double L = arhosekskymodel_solar_radiance(hosek, theta, gamma, lam);
797!
      const double d_lambda = lambda_weights[c];
798!
      L_band += L * d_lambda;
799
    }
800!
    arhosekskymodelstate_free(hosek);
801
  } else {
802!
    if (elevation < -4.2 || elevation > 90.0) {
803!
      Rcpp::stop("elevation must be in [-4.2, 90]");
804
    }
805
806!
    Vec3<double> sun_dir(std::cos(az_rad) * std::cos(elev_rad),
807!
                         std::sin(az_rad) * std::cos(elev_rad),
808!
                         std::sin(elev_rad));
809
    auto P =
810!
        prague_model.computeParameters({0.0, 0.0, altitude}, toPrague(sun_dir),
811
                                       elev_rad, az_rad, visibility, albedo);
812
813!
    for (size_t i = 0; i < N_LAMBDA; ++i) {
814!
      const double Li = prague_model.sunRadiance(P, lambda_values[i]);
815!
      const double d_lambda = lambda_weights[i];
816!
      L_band += Li * d_lambda;
817
    }
818
  }
819
820!
  if (!std::isfinite(L_band)) {
821!
    L_band = 0.0;
822
  }
823
824!
  return L_band;
825
}
826
827
// [[Rcpp::export]]
8285x
bool prague_gpu_available() {
8295x
  return prague_metal_available();
830
}
831
832
// [[Rcpp::export]]
8331x
Rcpp::NumericVector calculate_raw_prague_radiance(
834
    Rcpp::NumericVector phi, Rcpp::NumericVector theta,
835
    Rcpp::NumericVector lambda_nm, Rcpp::NumericVector elevation,
836
    Rcpp::NumericVector albedo, Rcpp::NumericVector altitude,
837
    Rcpp::NumericVector visibility, Rcpp::NumericVector azimuth,
838
    unsigned int number_cores = 1, std::string prg_dataset = "",
839
    std::string render_mode = "all", std::string backend = "cpu") {
8401x
  bool render_atmosphere = true;
8411x
  bool render_sun = true;
8421x
  resolve_render_mode(render_mode, render_atmosphere, render_sun);
843
8441x
  if (backend != "cpu" && backend != "gpu") {
845!
    Rcpp::stop("backend must be one of \"cpu\" or \"gpu\"");
846
  }
8471x
  if (backend == "gpu" && !prague_metal_available()) {
8481x
    Rcpp::stop("backend = \"gpu\" requires macOS with an available Metal device. "
849
               "Use backend = \"cpu\" on this system.");
850
  }
851
  // The native entry point also checks lengths before indexing borrowed columns.
852!
  for (const auto &column : {theta, lambda_nm, elevation, albedo, altitude,
853!
                             visibility, azimuth}) {
854!
    if (column.size() != phi.size()) {
855!
      Rcpp::stop("Radiance input columns must have equal lengths.");
856
    }
857
  }
858!
  const auto avail = initialize_prague_model(prg_dataset);
859!
  validate_prague_lambda_nm(lambda_nm, avail);
860
861!
  if (backend == "gpu") {
862!
    Rcpp::NumericVector radiance(phi.size());
863
    const PragueRadianceColumns columns = {
864!
        phi.begin(), theta.begin(), lambda_nm.begin(), elevation.begin(),
865!
        albedo.begin(), altitude.begin(), visibility.begin(), azimuth.begin()};
866!
    prague_metal_radiance(prague_model, prg_dataset, columns, phi.size(),
867
                          render_atmosphere, render_sun, radiance.begin(),
868
                          &Rcpp::checkUserInterrupt);
869!
    return radiance;
870
  }
871
872!
  std::vector<double> radiance(phi.size(), 0.0);
873
874!
  RcppThread::parallelFor(
875!
      0u, size_t(phi.size()),
876!
      [&](size_t t) {
877!
        const double theta_rad = theta[t] * M_PI / 180.0;
878!
        const double phi_rad = phi[t] * M_PI / 180.0;
879!
        const double lam = lambda_nm[t];
880!
        const double safe_elevation = clamp_sun_elevation_deg(elevation[t]);
881!
        const double elev_rad = safe_elevation * M_PI / 180.0;
882!
        const double az_rad = azimuth[t] * M_PI / 180.0;
883
884!
        if (theta_rad > M_PI_2) {
885!
          return;
886
        }
887
888!
        Vec3<double> v_zup(std::cos(phi_rad) * std::cos(theta_rad),
889!
                           std::sin(phi_rad) * std::cos(theta_rad),
890!
                           std::sin(theta_rad));
891!
        auto P = prague_model.computeParameters(
892!
            /*viewPoint*/ {0.0, 0.0, altitude[t]},
893!
            /*viewDir  */ toPrague(v_zup),
894
            /*sunElev  */ elev_rad,
895
            /*sunAzim  */ az_rad,
896!
            /*visibility*/ visibility[t],
897!
            /*albedo   */ albedo[t]);
898
899!
        double Li = 0.0;
900!
        if (render_atmosphere) {
901!
          Li = prague_model.skyRadiance(P, lam);
902
        }
903!
        if (render_sun) {
904!
          const double sun = prague_model.sunRadiance(P, lam);
905!
          Li = render_atmosphere ? (Li + sun) : sun;
906
        }
907!
        if (!std::isfinite(Li)) {
908!
          Li = 0.0;
909
        }
910!
        radiance[t] = Li;
911
      },
912
      number_cores);
913
914!
  return Rcpp::NumericVector(radiance.begin(), radiance.end());
915
}
916
917
// [[Rcpp::export]]
918!
Rcpp::NumericMatrix calculate_raw_prague(
919
    Rcpp::NumericVector phi, Rcpp::NumericVector theta,
920
    Rcpp::NumericVector elevation, Rcpp::NumericVector albedo,
921
    Rcpp::NumericVector altitude, Rcpp::NumericVector visibility,
922
    Rcpp::NumericVector azimuth, unsigned int number_cores = 1,
923
    std::string prg_dataset = "", std::string render_mode = "all",
924
    bool atmospheric_attenuation = true) {
925!
  bool render_atmosphere = true;
926!
  bool render_sun = true;
927!
  resolve_render_mode(render_mode, render_atmosphere, render_sun);
928
929!
  const auto avail = initialize_prague_model(prg_dataset);
930
931
  // Spectral sampling: lock to Prague dataset channel centers within CIE range
932
  // (380-740 nm).
933!
  std::vector<double> lambda_values;
934!
  lambda_values.reserve(avail.channels);
935!
  for (int i = 0; i < avail.channels; ++i) {
936!
    const double lam = avail.channelStart + (i + 0.5) * avail.channelWidth;
937!
    if (lam >= 380.0 && lam <= 740.0) {
938!
      lambda_values.push_back(lam);
939
    }
940
  }
941!
  if (lambda_values.empty()) {
942!
    Rcpp::stop("No Prague spectral channels fall within [380, 740] nm.");
943
  }
944!
  const size_t N_LAMBDA = lambda_values.size();
945
  // Constant band weights equal to channel width for rectangular integration.
946!
  std::vector<double> lambda_weights(N_LAMBDA, avail.channelWidth);
947!
  std::vector<CIETristimulus> cie_samples;
948!
  cie_samples.reserve(N_LAMBDA);
949!
  for (double lam : lambda_values) {
950!
    cie_samples.push_back(interpolate_cie_xyz(lam));
951
  }
952
953
  // Initialize image buffer
954!
  std::vector<double> img(3 * phi.size(), 0.0);
955!
  std::vector<double> band(phi.size(), 0.0);
956
957
  // Render loop (parallel over rows)
958!
  RcppThread::parallelFor(
959!
      0u, size_t(phi.size()),
960!
      [&](size_t t) {
961!
        double theta_rad = theta[t] * M_PI / 180;
962!
        double phi_rad = phi[t] * M_PI / 180;
963!
        const double safe_elevation = clamp_sun_elevation_deg(elevation[t]);
964!
        double elev_rad = safe_elevation * M_PI / 180;
965!
        double az_rad = azimuth[t] * M_PI / 180;
966
967!
        if (theta_rad > M_PI_2) {
968!
          return;
969
        }
970
971!
        Vec3<double> v_zup(std::cos(phi_rad) * std::cos(theta_rad),
972!
                           std::sin(phi_rad) * std::cos(theta_rad),
973!
                           std::sin(theta_rad));
974!
        auto P = prague_model.computeParameters(
975!
            /*viewPoint*/ {0.0, 0.0, altitude[t]},
976!
            /*viewDir  */ toPrague(v_zup),
977
            /*sunElev  */ elev_rad,
978
            /*sunAzim  */ az_rad,
979!
            /*visibility*/ visibility[t],
980!
            /*albedo   */ albedo[t]);
981!
        double X = 0.0, Y = 0.0, Z = 0.0;
982!
        double L_band = 0.0;
983!
        const bool view_above_horizon = theta_rad <= M_PI_2;
984!
        for (size_t c = 0; c < N_LAMBDA; ++c) {
985!
          const double lam = lambda_values[c];
986!
          double Li = 0.0;
987!
          if (render_atmosphere) {
988!
            Li = prague_model.skyRadiance(P, lam);
989
          }
990!
          if (render_sun && view_above_horizon) {
991!
            const double sun = prague_model.sunRadiance(P, lam, atmospheric_attenuation);
992!
            Li = render_atmosphere ? (Li + sun) : sun;
993
          }
994!
          const double d_lambda = lambda_weights[c];
995!
          X += Li * cie_samples[c].x * d_lambda;
996!
          Y += Li * cie_samples[c].y * d_lambda;
997!
          Z += Li * cie_samples[c].z * d_lambda;
998!
          L_band += Li * d_lambda;
999
        }
1000!
        if (!std::isfinite(X) || !std::isfinite(Y) || !std::isfinite(Z)) {
1001!
          X = 0.0;
1002!
          Y = 0.0;
1003!
          Z = 0.0;
1004
        }
1005
        double R, G, B;
1006!
        xyz_to_srgb(X, Y, Z, R, G, B);
1007!
        if (!std::isfinite(R) || !std::isfinite(G) || !std::isfinite(B)) {
1008!
          R = 0.0;
1009!
          G = 0.0;
1010!
          B = 0.0;
1011
        }
1012!
        img[3 * t + 0] = R;
1013!
        img[3 * t + 1] = G;
1014!
        img[3 * t + 2] = B;
1015!
        band[t] = L_band;
1016
      },
1017
      number_cores);
1018
1019!
  Rcpp::NumericMatrix rgb(phi.size(), 3);
1020!
  for (int p = 0; p < phi.size(); p++) {
1021!
    rgb(p, 0) = img[3 * p];
1022!
    rgb(p, 1) = img[3 * p + 1];
1023!
    rgb(p, 2) = img[3 * p + 2];
1024
  }
1025!
  Rcpp::NumericVector band_vals(band.begin(), band.end());
1026!
  rgb.attr("L_band") = band_vals;
1027!
  return (rgb);
1028
}
1
#ifndef SKYMODELR_PRAGUE_SKY_MODEL_H
2
#define SKYMODELR_PRAGUE_SKY_MODEL_H
3
/*
4
This file is included in the skymodelr package, which is distributed as a
5
whole under GPL-3. The following upstream copyright and provenance notice is
6
preserved for attribution and compliance with upstream notice requirements.
7
*/
8
9
// Copyright 2022 Charles University
10
// SPDX-License-Identifier: Apache-2.0
11
12
#include <array>
13
#include <cmath>
14
#include <cstdio>
15
#include <exception>
16
#include <string>
17
#include <vector>
18
#include "../../inst/include/skymodelr/prague_metal.h"
19
20
21
22
namespace skymodelr_prague {
23
24
double pragueLerp(const double from, const double to, const double factor);
25
26
/// Implementation of the physically-based sky model presented by Wilkie et al. [2021]
27
/// (https://cgg.mff.cuni.cz/publications/skymodel-2021/) and Vevoda et al. [2022]. Improves on previous work
28
/// especially in accuracy of sunset scenarios. Based on reconstruction of radiance from a small dataset
29
/// fitted to a large set of images obtained by brute force atmosphere simulation.
30
///
31
/// Provides evaluation of spectral sky radiance, sun radiance, transmittance and polarisation for observer at
32
/// a specific altitude above ground. The range of configurations depends on supplied dataset. The full
33
/// version models atmosphere of visibility (meteorological range) from 20 km to 131.8 km for sun elevations
34
/// from -4.2 degrees to 90 degrees, observer altitudes from 0 km to 15 km and ground albedo from 0 to 1, and
35
/// provides results for wavelengths from 280 nm to 2480 nm.
36
///
37
/// Usage:
38
/// 1. Create PragueSkyModel object and call its initialize method with a path to the dataset file.
39
/// 2. The model is parametrized by several values that are gathered in PragueSkyModel::Parameters structure.
40
/// You can either fill this structure manually (in that case see its description) or just call
41
/// computeParameters, which will compute it for you based on a few basic parameters.
42
/// 3. Use the Parameters structure when calling skyRadiance, sunRadiance, transmittance, or polarisation
43
/// methods to obtain the respective quantities.
44
///
45
/// Throws:
46
/// - DatasetNotFoundException: if the specified dataset file could not be found
47
/// - DatasetReadException: if an error occurred while reading the dataset file
48
/// - NoPolarisationException: if the polarisation method is called but the model does not contain
49
/// polarisation data
50
/// - NotInitializedException: if the model is used without calling the initialize method first
51
///
52
/// Note:
53
/// The entire model is written in a single class and does not depend on anything except of STL. It defines a
54
/// simple Vector3 class to simplify working with points and directions and expects using this class when
55
/// passing viewing point and direction to the computeParameters method.
56
class PragueSkyModel {
57
58
59
/////////////////////////////////////////////////////////////////////////////////////
60
// Public types
61
/////////////////////////////////////////////////////////////////////////////////////
62
public:
63
    /// Exception thrown by the initialize method if the passed dataset file could not be found.
64
    class DatasetNotFoundException : public std::exception {
65
    private:
66
        const std::string message;
67
68
    public:
691x
        DatasetNotFoundException(const std::string& filename)
705x
            : message(std::string("Dataset file ") + filename + std::string(" not found")) {}
71
721x
        virtual const char* what() const throw() { return message.c_str(); }
73
    };
74
75
    /// Exception thrown by the initialize method if an error occurred while reading the passed dataset file.
76
    class DatasetReadException : public std::exception {
77
    private:
78
        const std::string message;
79
80
    public:
811x
        DatasetReadException(const std::string& parameterName)
823x
            : message(std::string("Dataset reading failed at ") + parameterName) {}
83
841x
        virtual const char* what() const throw() { return message.c_str(); }
85
    };
86
87
    /// Exception thrown by the polarisation method if the dataset passed to the initialize method does not
88
    /// contain polarisation data.
89
    class NoPolarisationException : public std::exception {
90
    private:
91
        const std::string message;
92
93
    public:
94!
        NoPolarisationException()
95!
            : message(std::string("The supplied dataset does not contain polarisation data")) {}
96
97!
        virtual const char* what() const throw() { return message.c_str(); }
98
    };
99
100
    /// Exception thrown when using the model without calling the initialize method first.
101
    class NotInitializedException : public std::exception {
102
    private:
103
        const std::string message;
104
105
    public:
106!
        NotInitializedException()
107!
            : message(std::string("The model is not initialized")) {}
108
109!
        virtual const char* what() const throw() { return message.c_str(); }
110
    };
111
112
    /// A simple 3D vector implementation. Provides some basic operations.
113
    class Vector3 {
114
    public:
115
        double x, y, z;
116
117!
        Vector3() {
118!
            this->x = 0.0;
119!
            this->y = 0.0;
120!
            this->z = 0.0;
121
        }
122
123!
        Vector3(double x, double y, double z) {
124!
            this->x = x;
125!
            this->y = y;
126!
            this->z = z;
127
        }
128
129!
        Vector3 operator+(const Vector3& other) const {
130!
            return Vector3(x + other.x, y + other.y, z + other.z);
131
        }
132!
        Vector3 operator-(const Vector3& other) const {
133!
            return Vector3(x - other.x, y - other.y, z - other.z);
134
        }
135
136!
        Vector3 operator*(const double factor) const { return Vector3(x * factor, y * factor, z * factor); }
137
138!
        Vector3 operator/(const double factor) const { return Vector3(x / factor, y / factor, z / factor); }
139
140
        bool isZero() const { return x == 0.0 && y == 0.0 && z == 0.0; }
141
    };
142
143
    /// Structure holding all parameters necessary for querying the model.
144
    struct Parameters {
145
        /// Angle between view direction and direction to zenith in radians, supported values in range [0,
146
        /// PI].
147
        double theta;
148
149
        /// Angle between view direction and direction to sun in radians, supported values in range [0, PI].
150
        double gamma;
151
152
        /// Altitude-corrected angle between view direction and direction perpendicular to a shadow plane (=
153
        /// direction to sun rotated PI / 2 towards direction to zenith) in radians, used for negative solar
154
        /// elevations only, supported values in range [0, PI]
155
        double shadow;
156
157
        /// Altitude-corrected version of the theta angle in radians, supported values in range [0, PI].
158
        double zero;
159
160
        /// Sun elevation at view point in radians, supported values in range [-0.073, PI/2] (for full
161
        /// dataset). For view points above ground differs from the ground level sun elevation expected by the
162
        /// computeParameters method.
163
        double elevation;
164
165
        /// Altitude of view point in meters, supported values in range [0, 15000] (for full dataset).
166
        double altitude;
167
168
        /// Horizontal visibility (meteorological range) at ground level in kilometers, supported values in
169
        /// range [20, 131.8] (for full dataset).
170
        double visibility;
171
172
        /// Ground albedo, supported values in range [0, 1] (for full dataset).
173
        double albedo;
174
    };
175
176
    /// Structure with parameter ranges available in currently loaded dataset.
177
    struct AvailableData {
178
        double albedoMin;
179
        double albedoMax;
180
        double altitudeMin;
181
        double altitudeMax;
182
        double elevationMin;
183
        double elevationMax;
184
        double visibilityMin;
185
        double visibilityMax;
186
        bool   polarisation;
187
        int    channels;
188
        double channelStart;
189
        double channelWidth;
190
    };
191
192
193
/////////////////////////////////////////////////////////////////////////////////////
194
// Private types
195
/////////////////////////////////////////////////////////////////////////////////////
196
private:
197
    /// Structure holding index and factor for interpolating with respect to two neighboring values of an
198
    /// array.
199
    struct InterpolationParameter {
200
        double factor;
201
        int    index;
202
    };
203
204
    /// Angles converted into interpolation parameters.
205
    struct AngleParameters {
206
        InterpolationParameter gamma, alpha, zero;
207
    };
208
209
    /// Structure controlling interpolation with respect to visibility, albedo, altitude and elevation.
210
    struct ControlParameters {
211
        /// 16 sets of parameters that will be bi-linearly interpolated
212
        std::array<std::vector<float>::const_iterator, 16> coefficients;
213
        std::array<double, 4>                              interpolationFactor;
214
    };
215
216
    /// Structure used for storing radiance and polarisation metadata.
217
    struct Metadata {
218
        int rank;
219
220
        int                 sunOffset;
221
        int                 sunStride;
222
        std::vector<double> sunBreaks;
223
224
        int                 zenithOffset;
225
        int                 zenithStride;
226
        std::vector<double> zenithBreaks;
227
228
        int                 emphOffset; // not used for polarisation
229
        std::vector<double> emphBreaks; // not used for polarisation
230
231
        int totalCoefsSingleConfig;
232
        int totalCoefsAllConfigs;
233
	};
234
235
	/// Transmittance model internal parameters.
236
	struct TransmittanceParameters {
237
		InterpolationParameter altitude;
238
		InterpolationParameter distance;
239
	};
240
241
242
/////////////////////////////////////////////////////////////////////////////////////
243
// Private data
244
/////////////////////////////////////////////////////////////////////////////////////
245
    int    channels;
246
    double channelStart;
247
    double channelWidth;
248
249
    bool initialized;
250
251
    // Exact reuse. A generation changes whenever coefficients load,
252
    // so thread-local caches cannot mistake a reused object address for old data.
253
    unsigned long long cacheGeneration = 0;
254
    bool cacheSky = false;
255
    std::vector<double> expandedTrans;
256
    int expandedVisibilityFirst = 0, expandedVisibilityCount = 0;
257
    void expandTransmission(double singleVisibility, double maxMiB);
258
259
260
	// Total number of configurations
261
	int totalConfigs;
262
263
    // Number of configurations skipped from the beginning of the radiance/polarisation coefficients part 
264
    // of the dataset file (if loading of just one visibility was requested)
265
    int skippedConfigsBegin;
266
267
    // Number of configurations skipped till the end of the radiance/polarisation coefficients part
268
    // of the dataset file (if loading of just one visibility was requested)
269
    int skippedConfigsEnd;
270
271
    // Metadata common for radiance and polarisation
272
273
    std::vector<double> visibilitiesRad;
274
    std::vector<double> albedosRad;
275
    std::vector<double> altitudesRad;
276
    std::vector<double> elevationsRad;
277
278
    // Radiance metadata
279
280
    Metadata metadataRad;
281
282
    // Radiance data
283
    // 
284
	// Structure:
285
	// [[[[[[ sunCoefsRad       (sunBreaksCountRad * float), 
286
	//        zenithCoefsRad (zenithBreaksCountRad * float) ] * rankRad, 
287
	//        emphCoefsRad     (emphBreaksCountRad * float) ]
288
	//  * channels ] * elevationCount ] * altitudeCount ] * albedoCount ] * visibilityCount
289
    
290
    std::vector<float> dataRad;
291
292
	// Polarisation metadata
293
294
    Metadata metadataPol;
295
296
	// Polarisation data
297
    // 
298
	// Struture:
299
	// [[[[[[ sunCoefsPol       (sunBreaksCountPol * float), 
300
	//        zenithCoefsPol (zenithBreaksCountPol * float) ] * rankPol] 
301
	// * channels ] * elevationCount ] * altitudeCount ] * albedoCount ] * visibilityCount
302
303
    std::vector<float> dataPol;
304
305
    // Transmittance metadata
306
307
    int                 aDim;
308
    int                 dDim;
309
    int                 rankTrans;
310
    std::vector<double> altitudesTrans;
311
    std::vector<double> visibilitiesTrans;
312
313
    // Transmittance data
314
315
    std::vector<float> dataTransU;
316
    std::vector<float> dataTransV;
317
318
319
/////////////////////////////////////////////////////////////////////////////////////
320
// Public methods
321
/////////////////////////////////////////////////////////////////////////////////////
322
public:
3235x
    PragueSkyModel() : initialized(false) {};
324
    void exportMetal(skymodelr_prague_gpu_layout &, std::vector<float> &) const;
325
326
    /// Prepares the model and loads the given dataset file into memory.
327
    ///
328
    /// If a positive visibility value is passed, only a portion of the dataset needed for evaluation of that
329
    /// particular visibility is loaded (two nearest visibilities are loaded if the value is included in the
330
    /// dataset or one nearest if not). Otherwise, the entire dataset is loaded.
331
    ///
332
    /// Throws:
333
    /// - DatasetNotFoundException: if the specified dataset file could not be found
334
    /// - DatasetReadException: if an error occurred while reading the dataset file
335
    // Native consumers can opt into exact reuse without changing the legacy
336
    // evaluator's loading policy. Neither option introduces a new model grid.
337
    void initialize(const std::string& filename, const double singleVisibility = 0.0,
338
                    bool cacheSpectra = false, bool transmissionTable = false,
339
                    double transmissionTableMaxMiB = 512);
340
341
    bool isInitialized() const { return initialized; }
342
343
    /// Gets parameter ranges available in currently loaded dataset.
344
    ///
345
    /// Throws NotInitializedException if called without initializing the model first.
346
    AvailableData getAvailableData() const;
347
348
    // skymodelr: report immutable coefficient storage for scene memory accounting.
349
    size_t memoryUsage() const;
350
351
    /// Computes all the parameters in the Parameters structure necessary for querying the model.
352
    ///
353
    /// Expects view point and direction, sun elevation and azimuth at origin, ground level visibility and
354
    /// ground albedo. Assumes origin at [0,0,0] with Z axis pointing up. Thus view point [0, 0, 100] defines
355
    /// observer altitude 100 m. Range of available values depends on the used dataset. The full version
356
    /// supports altitude from [0, 15000] m, elevation from [-0.073, PI/2] rad, azimuth from [0, PI] rad, visibility
357
    /// from [20, 131.8] km, and albedo from [0, 1]. Values outside range of the used dataset are clamped to the
358
    /// nearest supported value.
359
    Parameters computeParameters(const Vector3& viewPoint,
360
                                 const Vector3& viewDirection,
361
                                 const double   groundLevelSolarElevationAtOrigin,
362
                                 const double   groundLevelSolarAzimuthAtOrigin,
363
                                 const double   visibility,
364
                                 const double   albedo) const;
365
366
    /// Computes sky radiance only (without direct sun contribution) for given parameters and wavelength (full
367
    /// dataset supports wavelengths from 280 nm to 2480 nm).
368
    ///
369
    /// Throws NotInitializedException if called without initializing the model first.
370
    double skyRadiance(const Parameters& params, const double wavelength) const;
371
    // skymodelr: exact spectral batch; shares wavelength-independent lookups.
372
    void skyRadianceSpectrum(const Parameters& params, const double* wavelengths,
373
                             size_t count, double* values) const;
374
375
    /// Computes sun radiance only (without radiance inscattered from the sky) for given parameters and
376
    /// wavelength (full dataset supports wavelengths from 280 nm to 2480 nm).
377
    ///
378
    /// Checks whether the parameters correspond to view direction hitting the sun and returns 0 if not.
379
    ///
380
    /// Throws NotInitializedException if called without initializing the model first.
381
    double sunRadiance(const Parameters& params, const double wavelength,
382
                       const bool atmosphericAttenuation = true) const;
383
384
    /// Computes degree of polarisation for given parameters and wavelength (full
385
    /// dataset supports wavelengths from 280 nm to 2480 nm). Can be negative.
386
    ///
387
    /// Throws:
388
    /// - NoPolarisationException: if the polarisation method is called but the model does not contain
389
    /// polarisation data
390
    /// - NotInitializedException: if called without initializing the model first
391
    double polarisation(const Parameters& params, const double wavelength) const;
392
393
    /// Computes transmittance between view point and a point certain distance away from it along view
394
    /// direction.
395
    ///
396
    /// Expects the Parameters structure, wavelength (full dataset supports wavelengths from 280 nm
397
    /// to 2480 nm) and the distance (any positive number, use std::numeric_limits<double>::max() for
398
    /// infinity).
399
    ///
400
    /// Throws NotInitializedException if called without initializing the model first.
401
    double transmittance(const Parameters& params, const double wavelength, const double distance) const;
402
    void transmittanceSpectrum(const Parameters& params, const double* wavelengths,
403
                               size_t count, double distance, double* values) const;
404
405
406
/////////////////////////////////////////////////////////////////////////////////////
407
// Private methods
408
/////////////////////////////////////////////////////////////////////////////////////
409
private:
410
    /// Reads radiance part of the dataset file into memory.
411
    ///
412
    /// If a positive visibility value is passed, only a portion of the dataset needed for evaluation of that
413
    /// particular visibility is loaded (two nearest visibilities are loaded if the value is included in the
414
    /// dataset or one nearest if not). Otherwise, the entire dataset is loaded.
415
    ///
416
    /// Throws DatasetReadException if an error occurred while reading the dataset file.
417
    void readRadiance(FILE* handle, const double singleVisibility);
418
419
    /// Reads transmittance part of the dataset file into memory.
420
    /// Throws DatasetReadException if an error occurred while reading the dataset file.
421
    void readTransmittance(FILE* handle);
422
423
    /// Reads polarisation part of the dataset file into memory.
424
    /// Throws DatasetReadException if an error occurred while reading the dataset file.
425
    void readPolarisation(FILE* handle);
426
427
    // Sky radiance and polarisation
428
429
    /// Gets iterator to coefficients in the dataset array corresponding to the given configuration. Used for
430
    /// sky radiance and polarisation.
431
    std::vector<float>::const_iterator getCoefficients(const std::vector<float>& dataset,
432
                                                       const int                 totalCoefsSingleConfig,
433
                                                       const int                 elevation,
434
                                                       const int                 altitude,
435
                                                       const int                 visibility,
436
                                                       const int                 albedo,
437
                                                       const int                 wavelength) const;  
438
439
    /// Recursive function controlling interpolation of reconstructed radiance between two neighboring visibility,
440
    /// albedo, altitude and elevation values.
441
    template <int TOffset, int TLevel>
442!
    double interpolate(const AngleParameters&   angleParameters,
443
                       const ControlParameters& controlParameters,
444
                       const Metadata&          metadata) const {
445
        /// Starts at level 0 and recursively goes down to level 4 while computing offset to the control
446
        /// parameters array. There it reconstructs radiance. When returning from recursion interpolates
447
        /// according to elevation, altitude, albedo and visibility at level 3, 2, 1 and 0, respectively.
448
        if constexpr (TLevel == 4) {
449!
            return reconstruct(angleParameters, controlParameters.coefficients[TOffset], metadata);
450
        } else {
451
            // Compute the first value
452
            const double resultLow =
453!
                interpolate<TOffset, TLevel + 1>(angleParameters, controlParameters, metadata);
454
455
            // Skip the second value if not useful or not available.
456!
            if (controlParameters.interpolationFactor[TLevel] < 1e-6) {
457!
                return resultLow;
458
            }
459
460
            // Compute the second value
461
            const double resultHigh =
462!
                interpolate<TOffset + (1 << (3 - TLevel)), TLevel + 1>(angleParameters,
463
                                                                       controlParameters,
464
                                                                       metadata);
465
466
            /// Interpolate between the two
467!
            return pragueLerp(resultLow, resultHigh, controlParameters.interpolationFactor[TLevel]);
468
        }
469
    }
470
471
    /// Reconstructs sky radiance or polarisation from the given control parameters by inverse tensor
472
    /// decomposition.
473
    double reconstruct(const AngleParameters&                   angleParameters,
474
                       const std::vector<float>::const_iterator controlParameters,
475
                       const Metadata&                          metadata) const;
476
477
    /// Get interpolation parameter for the given query value, i.e. finds position of the query value between
478
    /// a pair of break values.
479
    ///
480
    /// Used for albedo, elevation, altitude, visibility and angles (theta, alpha, or gamma).
481
    InterpolationParameter getInterpolationParameter(const double               queryVal,
482
                                                     const std::vector<double>& breaks) const;
483
    
484
    /// Evaluates the model. Used for computing sky radiance and polarisation.
485
    double evaluateModel(const Parameters&         params,
486
                         const double              wavelength,
487
                         const std::vector<float>& data,
488
                         const Metadata&           metadata) const;
489
490
    // Transmittance
491
492
    /// Gets iterator to base transmittance coefficients in the dataset array corresponding to the given
493
    /// configuration.
494
    std::vector<float>::const_iterator getCoefficientsTransBase(const int altitude,
495
                                                                const int a,
496
                                                                const int d) const;
497
498
    /// Gets iterator to transmittance coefficients in the dataset array corresponding to the given
499
    /// configuration.
500
    std::vector<float>::const_iterator getCoefficientsTrans(const int visibility,
501
                                                            const int altitude,
502
                                                            const int wavelength) const;
503
504
    /// Interpolates transmittances computed for two nearest altitudes.
505
    double interpolateTrans(const int                     visibilityIndex,
506
                            const InterpolationParameter  altitudeParam,
507
                            const TransmittanceParameters transParams,
508
                            const int                     channelIndex) const;
509
510
    /// For each channel reconstructs transmittances for the four nearest transmittance parameters and
511
    /// interpolates them.
512
    double reconstructTrans(const int                     visibilityIndex,
513
                            const int                     altitudeIndex,
514
                            const TransmittanceParameters transParams,
515
                            const int                     channelIndex) const;
516
517
    /// Converts altitude or distance value used in the transmittance model into interpolation parameter.
518
    InterpolationParameter getInterpolationParameterTrans(const double value,
519
                                                          const int    paramCount,
520
                                                          const int    power) const;
521
522
    /// Transforms the given theta angle, observer altitude and distance along ray into transmittance model
523
    /// internal [altitude, distance] parametrization.
524
    TransmittanceParameters toTransmittanceParams(const double theta,
525
                                                  const double distance,
526
                                                  const double altitude) const;
527
};
528
529
530
} // namespace skymodelr_prague
531
532
// Internal source compatibility for skymodelr's existing R entry points.
533
using PragueSkyModel = skymodelr_prague::PragueSkyModel;
534
#endif
1
// Registered, versioned native interface. GPL-3.
2
#include "../inst/include/skymodelr/prague_api.h"
3
#include "PragueSkyModel/PragueSkyModel.h"
4
#include <R_ext/Rdynload.h>
5
#include <algorithm>
6
#include <cmath>
7
#include <cstring>
8
#include <limits>
9
#include <memory>
10
#include <stdexcept>
11
12
struct skymodelr_prague_handle { PragueSkyModel model; };
13
namespace {
143x
void error_message(char *output, size_t capacity, const char *message) noexcept {
153x
    if (!output || !capacity) return;
163x
    size_t n = std::min(capacity - 1, std::strlen(message));
173x
    std::memcpy(output, message, n); output[n] = '\0';
18
}
193x
template <typename F> int guarded(F fn, char *error, size_t capacity) noexcept {
203x
    try { fn(); return 1; }
213x
    catch (const std::exception &e) { error_message(error, capacity, e.what()); }
22!
    catch (...) { error_message(error, capacity, "Unknown error in skymodelr Prague model."); }
233x
    return 0;
24
}
251x
const PragueSkyModel &model(const skymodelr_prague_handle *handle) {
261x
    if (!handle) throw std::invalid_argument("Prague model is not initialized.");
27!
    return handle->model;
28
}
292x
void validate_finite(double value) {
302x
    if (!std::isfinite(value)) throw std::invalid_argument("Nonfinite Prague query parameter.");
31
}
32!
void atmosphere(double visibility, double albedo) {
33!
    validate_finite(visibility); validate_finite(albedo);
34!
    if (visibility < 0 || albedo < 0 || albedo > 1)
35!
        throw std::invalid_argument("Invalid Prague visibility or ground albedo.");
36
}
37!
PragueSkyModel::Parameters parameters(const skymodelr_prague_parameters *p) {
38!
    if (!p) throw std::invalid_argument("Missing Prague query parameters.");
39!
    for (double angle : {p->theta, p->gamma, p->shadow, p->zero}) {
40!
        validate_finite(angle);
41!
        if (angle < 0 || angle > 3.14159265358979323846)
42!
            throw std::invalid_argument("Prague direction angles must lie between zero and pi.");
43
    }
44!
    validate_finite(p->elevation); validate_finite(p->altitude); atmosphere(p->visibility, p->albedo);
45!
    if (p->altitude < 0) throw std::invalid_argument("Prague altitude must be nonnegative.");
46!
    return {p->theta, p->gamma, p->shadow, p->zero, p->elevation,
47!
            p->altitude, p->visibility, p->albedo};
48
}
49
}
50
51
extern "C" {
522x
static skymodelr_prague_handle *create_model(const char *filename, double visibility,
53
                                                          int cache_spectra, int transmission_table,
54
                                                          double max_mib,
55
                                                          char *error, size_t capacity) noexcept {
562x
    std::unique_ptr<skymodelr_prague_handle> result;
572x
    if (!guarded([&] {
582x
        if (!filename || !*filename) throw std::invalid_argument("Missing Prague coefficient filename.");
592x
        validate_finite(visibility);
602x
        if (visibility < 0) throw std::invalid_argument("Prague visibility must be nonnegative.");
612x
        if ((cache_spectra != 0 && cache_spectra != 1) ||
622x
            (transmission_table != 0 && transmission_table != 1))
63!
            throw std::invalid_argument("Prague cache options must be zero or one.");
642x
        if (std::isnan(max_mib) || max_mib < 0)
65!
            throw std::invalid_argument("Prague transmission table limit must be nonnegative MiB or infinity.");
662x
        result.reset(new skymodelr_prague_handle);
676x
        result->model.initialize(filename, visibility, cache_spectra != 0, transmission_table != 0, max_mib);
682x
    }, error, capacity)) return nullptr;
69!
    return result.release();
70
}
71!
static void destroy_model(skymodelr_prague_handle *handle) noexcept { delete handle; }
72!
static size_t memory_usage(const skymodelr_prague_handle *handle) noexcept {
73!
    return handle ? handle->model.memoryUsage() : 0;
74
}
751x
static int available(const skymodelr_prague_handle *handle, skymodelr_prague_available *out,
76
                      char *error, size_t capacity) noexcept {
771x
    return guarded([&] {
781x
        if (!out) throw std::invalid_argument("Missing Prague metadata output.");
791x
        auto a = model(handle).getAvailableData();
80!
        *out = {a.albedoMin, a.albedoMax, a.altitudeMin, a.altitudeMax,
81!
                a.elevationMin, a.elevationMax, a.visibilityMin, a.visibilityMax,
82!
                a.polarisation ? 1 : 0, a.channels, a.channelStart, a.channelWidth};
831x
    }, error, capacity);
84
}
85!
static int compute_parameters(const skymodelr_prague_handle *handle,
86
                               const double *position, const double *direction,
87
                               double elevation, double azimuth, double visibility, double albedo,
88
                               skymodelr_prague_parameters *out, char *error, size_t capacity) noexcept {
89!
    return guarded([&] {
90!
        if (!position || !direction || !out) throw std::invalid_argument("Missing Prague position, direction, or output.");
91!
        validate_finite(elevation); validate_finite(azimuth); atmosphere(visibility, albedo);
92!
        for (int i = 0; i < 3; ++i) { validate_finite(position[i]); validate_finite(direction[i]); }
93!
        double magnitude = std::hypot(std::hypot(direction[0], direction[1]), direction[2]);
94!
        if (!(magnitude > 0) || !std::isfinite(magnitude))
95!
            throw std::invalid_argument("Prague view direction must have finite nonzero length.");
96!
        double radius = std::hypot(std::hypot(position[0], position[1]), position[2] + 6378000.0);
97!
        if (!std::isfinite(radius) || radius < 6378000.0 - 1e-6)
98!
            throw std::invalid_argument("Prague viewpoint lies inside the Earth.");
99!
        auto p = model(handle).computeParameters({position[0], position[1], position[2]},
100!
            {direction[0], direction[1], direction[2]}, elevation, azimuth, visibility, albedo);
101!
        *out = {p.theta, p.gamma, p.shadow, p.zero, p.elevation, p.altitude, p.visibility, p.albedo};
102!
    }, error, capacity);
103
}
104!
static int spectrum(const skymodelr_prague_handle *handle, int quantity,
105
                     const skymodelr_prague_parameters *input, const double *wavelengths,
106
                     size_t count, double distance, int attenuate_sun, double *out,
107
                     char *error, size_t capacity) noexcept {
108!
    return guarded([&] {
109!
        const auto &m = model(handle);
110!
        auto p = parameters(input);
111!
        if (count && (!wavelengths || !out)) throw std::invalid_argument("Missing Prague spectral input or output.");
112!
        for (size_t i = 0; i < count; ++i) validate_finite(wavelengths[i]);
113!
        switch (quantity) {
114!
        case SKYMODELR_PRAGUE_SKY: m.skyRadianceSpectrum(p, wavelengths, count, out); break;
115!
        case SKYMODELR_PRAGUE_TRANSMITTANCE:
116!
            if (std::isnan(distance) || distance < 0) throw std::invalid_argument("Invalid Prague transmission distance.");
117!
            m.transmittanceSpectrum(p, wavelengths, count,
118!
                std::min(distance, std::numeric_limits<double>::max()), out);
119!
            break;
120!
        case SKYMODELR_PRAGUE_SUN:
121!
            if (attenuate_sun != 0 && attenuate_sun != 1) throw std::invalid_argument("attenuate_sun must be zero or one.");
122!
            for (size_t i = 0; i < count; ++i) out[i] = m.sunRadiance(p, wavelengths[i], attenuate_sun != 0);
123!
            break;
124!
        case SKYMODELR_PRAGUE_POLARISATION:
125!
            for (size_t i = 0; i < count; ++i) out[i] = m.polarisation(p, wavelengths[i]);
126!
            break;
127!
        default: throw std::invalid_argument("Unknown Prague spectral quantity.");
128
        }
129!
    }, error, capacity);
130
}
1312x
static const skymodelr_prague_api *get_api() noexcept {
132
    static const skymodelr_prague_api api = {SKYMODELR_PRAGUE_ABI_VERSION, sizeof(skymodelr_prague_api),
133
        create_model, destroy_model, available, memory_usage, compute_parameters, spectrum};
1342x
    return &api;
135
}
136
}
137
138
// [[Rcpp::init]]
1393x
void skymodelr_register_prague_api(DllInfo *dll) {
140
    (void)dll;
1413x
    R_RegisterCCallable("skymodelr", "prague_get_api", reinterpret_cast<DL_FUNC>(&get_api));
142
}
143
144
struct skymodelr_prague_gpu_handle {
145
    skymodelr_prague_gpu_layout layout;
146
    std::vector<float> data;
147
};
148
namespace {
149!
skymodelr_prague_gpu_handle *gpu_create(const skymodelr_prague_handle *handle,
150
                                        char *error, size_t capacity) noexcept {
151!
    std::unique_ptr<skymodelr_prague_gpu_handle> result;
152!
    if (!guarded([&] {
153!
        result.reset(new skymodelr_prague_gpu_handle);
154!
        model(handle).exportMetal(result->layout,result->data);
155!
    }, error, capacity)) return nullptr;
156!
    return result.release();
157
}
158!
void gpu_destroy(skymodelr_prague_gpu_handle *handle) noexcept { delete handle; }
159!
const skymodelr_prague_gpu_layout *gpu_layout(const skymodelr_prague_gpu_handle *handle) noexcept {
160!
    return handle ? &handle->layout : nullptr;
161
}
162!
const float *gpu_data(const skymodelr_prague_gpu_handle *handle,size_t *count) noexcept {
163!
    if(count) *count=handle ? handle->data.size() : 0;
164!
    return handle ? handle->data.data() : nullptr;
165
}
166!
const char *gpu_source() noexcept {
167
    return
168
#include "../inst/include/skymodelr/prague_metal.inc"
169
    ;
170
}
171!
const skymodelr_prague_gpu_api *gpu_get_api() noexcept {
172
    static const skymodelr_prague_gpu_api api={SKYMODELR_PRAGUE_METAL_ABI_VERSION,
173
        sizeof(skymodelr_prague_gpu_api),gpu_create,gpu_destroy,gpu_layout,gpu_data,gpu_source};
174!
    return &api;
175
}
176
}
177
// [[Rcpp::init]]
1783x
void skymodelr_register_prague_gpu_api(DllInfo *dll) {
179
    (void)dll;
1803x
    R_RegisterCCallable("skymodelr","prague_gpu_get_api",reinterpret_cast<DL_FUNC>(&gpu_get_api));
181
}
1!
R"PRAGUE(
2
// Reconstruction derived from PragueSkyModel (Copyright 2022 Charles
3
// University, Apache-2.0); distributed within the GPL-3 skymodelr package.
4
// Same compressed spectral fit as the CPU evaluator. No RGB/angular LUT.
5
namespace skymodelr_gpu {
6
struct Axis { uint offset, count; };
7
struct Layout {
8
  Axis visibility, albedo, altitude, elevation, gamma, alpha, emphasis;
9
  Axis trans_altitude, trans_visibility, sun;
10
  uint radiance, trans_u, trans_v, rank, sun_offset, sun_stride;
11
  uint zenith_offset, zenith_stride, emphasis_offset, config_stride;
12
  uint trans_rank, a_dim, d_dim, channels;
13
  float channel_start, channel_width;
14
};
15
struct Parameters { float theta, gamma, shadow, zero, elevation, altitude, visibility, albedo; };
16
struct Interpolation { uint index; float factor; };
17
constant float radius = 6378000.f;
18
constant float pi = 3.14159265358979323846f;
19
// Preserve metre/submetre heights: rationalize |p+(0,0,R)|-R instead of
20
// subtracting two approximately 6,378,000 m floats. atan2 preserves small angles.
21
float height(float3 p) {
22
  float n = dot(p,p) + 2*radius*p.z;
23
  return n / (length(p+float3(0,0,radius)) + radius);
24
}
25
float angle(float3 a, float3 b) { return atan2(length(cross(a,b)),dot(a,b)); }
26
Parameters parameters(float3 p, float3 w, float elevation, float azimuth, float visibility, float albedo) {
27
  float3 up = normalize(p+float3(0,0,radius));
28
  w = normalize(w);
29
  float h = max(0.f,height(p)+50.f);
30
  float correction = sqrt(h*(2*radius+h))/(radius+h);
31
  // Algebraic cancellation of the two shifted Earth-space points in the CPU
32
  // formula, before rounding, preserves the one-metre viewing direction.
33
  float3 corrected = normalize(w + up*correction);
34
  float3 sun(cos(azimuth)*cos(elevation),sin(azimuth)*cos(elevation),sin(elevation));
35
  float3 shadow(-sin(elevation)*cos(azimuth),-sin(elevation)*sin(azimuth),cos(elevation));
36
  return {angle(w,up), angle(w,sun), angle(corrected,shadow), angle(corrected,up),
37
          asin(clamp(dot(up,sun),-1.f,1.f)), h, visibility, albedo};
38
}
39
Interpolation lookup(float value, Axis axis, device const float *data) {
40
  float v=clamp(value,data[axis.offset],data[axis.offset+axis.count-1]);
41
  uint lo=1,hi=axis.count;
42
  while(lo<hi) { uint mid=(lo+hi)/2; if(data[axis.offset+mid]<=v) lo=mid+1; else hi=mid; }
43
  uint i=lo-1;
44
  return {i,lo==axis.count ? 0.f : (v-data[axis.offset+i])/(data[axis.offset+lo]-data[axis.offset+i])};
45
}
46
float linear(device const float *data,uint offset,float factor) {
47
  if(factor==0) return data[offset]; // Last knot need not have a successor.
48
  return (data[offset+1]-data[offset])*factor+data[offset];
49
}
50
struct SkyQuery { Interpolation gamma, alpha, emphasis, config[4]; };
51
// Prepare wavelength-independent coordinates once for a spectral integration.
52
SkyQuery prepare_sky(Parameters p,device const Layout &m,device const float *data) {
53
  return {lookup(p.gamma,m.gamma,data),lookup(p.elevation<0 ? p.shadow : p.zero,m.alpha,data),
54
    lookup(p.zero,m.emphasis,data),{lookup(p.visibility,m.visibility,data),lookup(p.albedo,m.albedo,data),
55
    lookup(p.altitude,m.altitude,data),lookup(p.elevation*180/pi,m.elevation,data)}};
56
}
57
float sky_prepared(SkyQuery query,float wavelength,device const Layout &m,device const float *data) {
58
  if(wavelength<m.channel_start || wavelength>=m.channel_start+m.channels*m.channel_width) return 0;
59
  uint channel=uint((wavelength-m.channel_start)/m.channel_width);
60
  auto g=query.gamma,a=query.alpha,e=query.emphasis;
61
  auto config=query.config;
62
  uint counts[4]={m.visibility.count,m.albedo.count,m.altitude.count,m.elevation.count};
63
  // Weighted corner accumulation avoids a dynamically indexed 16-value local
64
  // array. It retains the CPU's zero-weight threshold and per-corner clamping;
65
  // summation order differs, so numerical agreement is tolerance-based.
66
  float result=0;
67
  for(uint i=0;i<16;++i) {
68
    uint index=0; float weight=1;
69
    for(uint j=0;j<4;++j) {
70
      uint high=(i>>(3-j))&1;
71
      float f=config[j].factor<1e-6f ? 0.f : config[j].factor;
72
      weight*=high ? f : 1-f;
73
      index=index*counts[j]+min(config[j].index+high,counts[j]-1);
74
    }
75
    float value=0;
76
    if(weight>0) {
77
      uint base=m.radiance+(index*m.channels+channel)*m.config_stride;
78
      for(uint r=0;r<m.rank;++r)
79
        value+=linear(data,base+m.sun_offset+r*m.sun_stride+g.index,g.factor)*
80
               linear(data,base+m.zenith_offset+r*m.zenith_stride+a.index,a.factor);
81
      value=max(0.f,value*linear(data,base+m.emphasis_offset+e.index,e.factor));
82
    }
83
    result+=weight*value;
84
  }
85
  return result;
86
}
87
float sky(Parameters p,float wavelength,device const Layout &m,device const float *data) {
88
  return sky_prepared(prepare_sky(p,m,data),wavelength,m,data);
89
}
90
// Nearest forward intersection. c is factored to preserve altitude close to
91
// Earth; the near root uses c/(-b+sqrt(discriminant)) to avoid cancellation.
92
float circle(float cosine,float altitude,float shell) {
93
  float r=radius+altitude, b=r*cosine;
94
  float c=(altitude-shell)*(2*radius+altitude+shell);
95
  float discriminant=b*b-c;
96
  if(discriminant<=0) return -1;
97
  float root=sqrt(discriminant), far=-b+root;
98
  float near=c/far;
99
  return near>0 && far>0 ? min(near,far) : max(near,far);
100
}
101
Interpolation trans_lookup(float value,uint n,uint power) {
102
  uint i=min(uint(value*n),n-1); float f=0;
103
  if(i<n-1) {
104
    float a=float(i)/n,b=float(i+1)/n;
105
    float va=pow(a,float(power)),vb=pow(b,float(power));
106
    f=clamp((pow(value,float(power))-va)/(vb-va),0.f,1.f);
107
  }
108
  return {i,f};
109
}
110
struct TransParameters { Interpolation altitude, distance; };
111
TransParameters trans_parameters(Parameters p,float distance,device const Layout &m) {
112
  float cosine=cos(p.theta),sine=sin(p.theta),t,shell=0;
113
  if(p.altitude<.3f) {
114
    if(p.theta<=pi/2) {shell=100000;t=circle(cosine,p.altitude,shell);} else t=0;
115
  } else {
116
    t=circle(cosine,p.altitude,0);
117
    if(t<0) {shell=100000;t=circle(cosine,p.altitude,shell);}
118
  }
119
  bool boundary=t<=distance;
120
  t=min(max(0.f,t),distance);
121
  float x=sine*t,z=p.altitude+cosine*t;
122
  float h=boundary ? shell : clamp(height(float3(x,0,z)),0.f,100000.f);
123
  float a=pow(h/100000.f,1.f/3.f);
124
  // acos(y/length) rounds to zero for short paths. atan2 is equivalent here.
125
  float d=min(1.f,sqrt(sqrt(atan2(abs(x),radius+z)*radius/1571524.413613f)));
126
  return {trans_lookup(a,m.a_dim,3),trans_lookup(d,m.d_dim,4)};
127
}
128
float reconstruct_trans(uint visibility,uint altitude,uint channel,TransParameters p,
129
                        device const Layout &m,device const float *data) {
130
  uint coefficients=m.trans_v+((visibility*m.trans_altitude.count+altitude)*m.channels+channel)*m.trans_rank;
131
  float values[4]={0,0,0,0}; uint index=0;
132
  for(uint a=p.altitude.index;a<=p.altitude.index+1;++a) if(a<m.a_dim)
133
    for(uint d=p.distance.index;d<=p.distance.index+1;++d) if(d<m.d_dim) {
134
      uint base=m.trans_u+((altitude*m.d_dim+d)*m.a_dim+a)*m.trans_rank;
135
      float value=0;
136
      for(uint r=0;r<m.trans_rank;++r) value+=data[base+r]*data[coefficients+r];
137
      values[index++]=value;
138
    }
139
  if(p.distance.factor>0) {
140
    values[0]=mix(values[0],values[1],p.distance.factor);
141
    values[1]=mix(values[2],values[3],p.distance.factor);
142
  }
143
  return p.altitude.factor>0 ? mix(max(0.f,values[0]),max(0.f,values[1]),p.altitude.factor) : max(0.f,values[0]);
144
}
145
struct TransQuery { Interpolation visibility, altitude; TransParameters distance; };
146
TransQuery prepare_transmission(Parameters p,float distance,device const Layout &m,device const float *data) {
147
  return {lookup(p.visibility,m.trans_visibility,data),lookup(p.altitude,m.trans_altitude,data),trans_parameters(p,distance,m)};
148
}
149
float transmission_prepared(TransQuery query,float wavelength,device const Layout &m,device const float *data) {
150
  if(wavelength<m.channel_start || wavelength>=m.channel_start+m.channels*m.channel_width) return 0;
151
  uint channel=uint((wavelength-m.channel_start)/m.channel_width);
152
  auto v=query.visibility,h=query.altitude;auto t=query.distance;
153
  float result[2];
154
  for(uint j=0;j<2;++j) {
155
    uint vi=min(v.index+j,m.trans_visibility.count-1);
156
    float value=reconstruct_trans(vi,h.index,channel,t,m,data);
157
    if(h.factor>0) value=mix(value,reconstruct_trans(vi,h.index+1,channel,t,m,data),h.factor);
158
    result[j]=value;
159
    if(v.factor==0) break;
160
  }
161
  float value=v.factor>0 ? mix(result[0],result[1],v.factor) : result[0];
162
  return value*value;
163
}
164
float transmission(Parameters p,float wavelength,float distance,device const Layout &m,device const float *data) {
165
  return transmission_prepared(prepare_transmission(p,distance,m,data),wavelength,m,data);
166
}
167
float sun(Parameters p,float wavelength,bool attenuate,device const Layout &m,device const float *data) {
168
  if(wavelength<280 || wavelength>=280+m.sun.count-1 || p.gamma>.004654793f) return 0;
169
  float index=wavelength-280;
170
  float value=linear(data,m.sun.offset+uint(index),fract(index));
171
  return attenuate ? value*transmission(p,wavelength,INFINITY,m,data) : value;
172
}
173
// Batch input uses already computed parameters; consumers may also call
174
// parameters() directly inside their own shaders. One thread per wavelength.
175
struct Query { Parameters parameters; float wavelength, distance; uint quantity, attenuate_sun; };
176
struct Geometry { float4 position, direction, settings; };
177
}
178
kernel void prague_parameters_batch(device const skymodelr_gpu::Geometry *input [[buffer(0)]],
179
    device skymodelr_gpu::Parameters *output [[buffer(1)]],constant uint &count [[buffer(2)]],
180
    uint i [[thread_position_in_grid]]) {
181
  if(i>=count) return;
182
  auto q=input[i];
183
  output[i]=skymodelr_gpu::parameters(q.position.xyz,q.direction.xyz,q.settings.x,q.settings.y,q.settings.z,q.settings.w);
184
}
185
kernel void prague_spectrum_batch(device const skymodelr_gpu::Layout &model [[buffer(0)]],
186
    device const float *data [[buffer(1)]], device const skymodelr_gpu::Query *queries [[buffer(2)]],
187
    device float *output [[buffer(3)]],constant uint &count [[buffer(4)]],uint i [[thread_position_in_grid]]) {
188
  if(i>=count) return;
189
  auto q=queries[i];
190
  output[i]=q.quantity==0 ? skymodelr_gpu::sky(q.parameters,q.wavelength,model,data) :
191
    (q.quantity==1 ? skymodelr_gpu::sun(q.parameters,q.wavelength,q.attenuate_sun,model,data) :
192
     skymodelr_gpu::transmission(q.parameters,q.wavelength,q.distance,model,data));
193
}
194
)PRAGUE"
1
#include "prague_metal_backend.h"
2
#include <stdexcept>
3
46x
bool prague_metal_available() { return false; }
5
6!
void prague_metal_radiance(const PragueSkyModel &, const std::string &,
7
                           const PragueRadianceColumns &, size_t, bool, bool,
8
                           double *, void (*)()) {
9
  throw std::runtime_error(
10
      "backend = \"gpu\" requires macOS with an available Metal device. "
11!
      "Use backend = \"cpu\" on this system.");
12
}
1
/*
2
This file is included in the skymodelr package, which is distributed as a
3
whole under GPL-3. The following upstream copyright and provenance notice is
4
preserved for attribution and compliance with upstream notice requirements.
5
*/
6
7
// Copyright 2022 Charles University
8
// SPDX-License-Identifier: Apache-2.0
9
10
#include <algorithm>
11
#include <array>
12
#include <cassert>
13
#include <limits>
14
#include <cstring>
15
#include <tuple>
16
#include <memory>
17
#include <stdexcept>
18
#include <atomic>
19
20
#include "PragueSkyModel.h"
21
22
namespace skymodelr_prague {
23
24
25
26
/////////////////////////////////////////////////////////////////////////////////////
27
// Constants
28
/////////////////////////////////////////////////////////////////////////////////////
29
30
constexpr double PI               = 3.141592653589793;
31
constexpr double RAD_TO_DEG       = 180.0 / PI;
32
constexpr double PLANET_RADIUS    = 6378000.0;
33
constexpr double SAFETY_ALTITUDE  = 50.0;
34
constexpr double SUN_RADIUS       = 0.004654793; // = 0.2667 degrees
35
constexpr double DIST_TO_EDGE     = 1571524.413613; // Maximum distance to the edge of the atmosphere in the transmittance model
36
constexpr double ATMOSPHERE_WIDTH = 100000.0;
37
constexpr double SUN_RAD_START    = 280;
38
constexpr double SUN_RAD_STEP     = 1;
39
constexpr double SUN_RAD_TABLE[]  = {
40
    4022.51,  4592.96,  5058.84,  5552.97,  6024.88,  6443.47,  6836.20,  7175.78,  7380.47,  7437.44,
41
    7391.90,  7266.06,  7121.19,  7034.24,  7024.24,  7082.31,  7209.73,  7384.60,  7563.43,  7739.25,
42
    7905.70,  8025.18,  8096.11,  8202.27,  8337.15,  8602.30,  8965.52,  9316.67,  9565.64,  9814.45,
43
    9829.41,  10184.,   10262.6,  10375.7,  10276.,   10179.3,  10156.6,  10750.7,  11134.,   11463.6,
44
    11860.4,  12246.2,  12524.4,  12780.,   13187.4,  13632.4,  13985.9,  13658.3,  13377.4,  13358.3,
45
    13239.,   13119.8,  13096.2,  13184.,   13243.5,  13018.4,  12990.4,  13159.1,  13230.8,  13258.6,
46
    13209.9,  13343.2,  13404.8,  13305.4,  13496.3,  13979.1,  14153.8,  14188.4,  14122.7,  13825.4,
47
    14033.3,  13914.1,  13837.4,  14117.2,  13982.3,  13864.5,  14118.4,  14545.7,  15029.3,  15615.3,
48
    15923.5,  16134.8,  16574.5,  16509.,   16336.5,  16146.6,  15965.1,  15798.6,  15899.8,  16125.4,
49
    15854.3,  15986.7,  15739.7,  15319.1,  15121.5,  15220.2,  15041.2,  14917.7,  14487.8,  14011.,
50
    14165.7,  14189.5,  14540.7,  14797.5,  14641.5,  14761.6,  15153.7,  14791.8,  14907.6,  15667.4,
51
    16313.5,  16917.,   17570.5,  18758.1,  20250.6,  21048.1,  21626.1,  22811.6,  23577.2,  23982.6,
52
    24062.1,  23917.9,  23914.1,  23923.2,  24052.6,  24228.6,  24360.8,  24629.6,  24774.8,  24648.3,
53
    24666.5,  24938.6,  24926.3,  24693.1,  24613.5,  24631.7,  24569.8,  24391.5,  24245.7,  24084.4,
54
    23713.7,  22985.4,  22766.6,  22818.9,  22834.3,  22737.9,  22791.6,  23086.3,  23377.7,  23461.,
55
    23935.5,  24661.7,  25086.9,  25520.1,  25824.3,  26198.,   26350.2,  26375.4,  26731.2,  27250.4,
56
    27616.,   28145.3,  28405.9,  28406.8,  28466.2,  28521.5,  28783.8,  29025.1,  29082.6,  29081.3,
57
    29043.1,  28918.9,  28871.6,  29049.,   29152.5,  29163.2,  29143.4,  28962.7,  28847.9,  28854.,
58
    28808.7,  28624.1,  28544.2,  28461.4,  28411.1,  28478.,   28469.8,  28513.3,  28586.5,  28628.6,
59
    28751.5,  28948.9,  29051.,   29049.6,  29061.7,  28945.7,  28672.8,  28241.5,  27903.2,  27737.,
60
    27590.9,  27505.6,  27270.2,  27076.2,  26929.1,  27018.2,  27206.8,  27677.2,  27939.9,  27923.9,
61
    27899.2,  27725.4,  27608.4,  27599.4,  27614.6,  27432.4,  27460.4,  27392.4,  27272.,   27299.1,
62
    27266.8,  27386.5,  27595.9,  27586.9,  27504.8,  27480.6,  27329.8,  26968.4,  26676.3,  26344.7,
63
    26182.5,  26026.3,  25900.3,  25842.9,  25885.4,  25986.5,  26034.5,  26063.5,  26216.9,  26511.4,
64
    26672.7,  26828.5,  26901.8,  26861.5,  26865.4,  26774.2,  26855.8,  27087.1,  27181.3,  27183.1,
65
    27059.8,  26834.9,  26724.3,  26759.6,  26725.9,  26724.6,  26634.5,  26618.5,  26560.1,  26518.7,
66
    26595.3,  26703.2,  26712.7,  26733.9,  26744.3,  26764.4,  26753.2,  26692.7,  26682.7,  26588.1,
67
    26478.,   26433.7,  26380.7,  26372.9,  26343.3,  26274.7,  26162.3,  26160.5,  26210.,   26251.2,
68
    26297.9,  26228.9,  26222.3,  26269.7,  26295.6,  26317.9,  26357.5,  26376.1,  26342.4,  26303.5,
69
    26276.7,  26349.2,  26390.,   26371.6,  26346.7,  26327.6,  26274.2,  26247.3,  26228.7,  26152.1,
70
    25910.3,  25833.2,  25746.5,  25654.3,  25562.,   25458.8,  25438.,   25399.1,  25324.3,  25350.,
71
    25514.,   25464.9,  25398.5,  25295.2,  25270.2,  25268.4,  25240.6,  25184.9,  25149.6,  25123.9,
72
    25080.3,  25027.9,  25012.3,  24977.9,  24852.6,  24756.4,  24663.5,  24483.6,  24398.6,  24362.6,
73
    24325.1,  24341.7,  24288.7,  24284.2,  24257.3,  24178.8,  24097.6,  24175.6,  24175.7,  24139.7,
74
    24088.1,  23983.2,  23902.7,  23822.4,  23796.2,  23796.9,  23814.5,  23765.5,  23703.,   23642.,
75
    23592.6,  23552.,   23514.6,  23473.5,  23431.,   23389.3,  23340.,   23275.1,  23187.3,  23069.5,
76
    22967.,   22925.3,  22908.9,  22882.5,  22825.,   22715.4,  22535.5,  22267.1,  22029.4,  21941.6,
77
    21919.5,  21878.8,  21825.6,  21766.,   21728.9,  21743.2,  21827.1,  21998.7,  22159.4,  22210.,
78
    22187.2,  22127.2,  22056.2,  22000.2,  21945.9,  21880.2,  21817.1,  21770.3,  21724.3,  21663.2,
79
    21603.3,  21560.4,  21519.8,  21466.2,  21401.6,  21327.7,  21254.2,  21190.7,  21133.6,  21079.3,
80
    21024.,   20963.7,  20905.5,  20856.6,  20816.6,  20785.2,  20746.7,  20685.3,  20617.8,  20561.1,
81
    20500.4,  20421.2,  20333.4,  20247.,   20175.3,  20131.4,  20103.2,  20078.5,  20046.8,  19997.2,
82
    19952.9,  19937.2,  19930.8,  19914.4,  19880.8,  19823.,   19753.8,  19685.9,  19615.3,  19537.5,
83
    19456.8,  19377.6,  19309.4,  19261.9,  19228.,   19200.5,  19179.5,  19164.8,  19153.1,  19140.6,
84
    19129.2,  19120.6,  19104.5,  19070.6,  19023.9,  18969.3,  18911.4,  18855.,   18798.6,  18740.8,
85
    18672.7,  18585.2,  18501.,   18442.4,  18397.5,  18353.9,  18313.2,  18276.8,  18248.3,  18231.2,
86
    18224.,   18225.4,  18220.1,  18192.6,  18155.1,  18119.8,  18081.6,  18035.6,  17987.4,  17942.8,
87
    17901.7,  17864.2,  17831.1,  17802.9,  17771.5,  17728.6,  17669.7,  17590.1,  17509.5,  17447.4,
88
    17396.,   17347.4,  17300.3,  17253.2,  17206.1,  17159.,   17127.6,  17127.6,  17133.6,  17120.4,
89
    17097.2,  17073.3,  17043.7,  17003.4,  16966.3,  16946.3,  16930.9,  16907.7,  16882.7,  16862.,
90
    16837.8,  16802.1,  16759.2,  16713.6,  16661.8,  16600.8,  16542.6,  16499.4,  16458.7,  16408.,
91
    16360.6,  16329.5,  16307.4,  16286.7,  16264.9,  16239.6,  16207.8,  16166.8,  16118.2,  16064.,
92
    16011.2,  15966.9,  15931.9,  15906.9,  15889.1,  15875.5,  15861.2,  15841.3,  15813.1,  15774.2,
93
    15728.8,  15681.4,  15630.,   15572.9,  15516.5,  15467.2,  15423.,   15381.6,  15354.4,  15353.,
94
    15357.3,  15347.3,  15320.2,  15273.1,  15222.,   15183.1,  15149.6,  15114.6,  15076.8,  15034.6,
95
    14992.9,  14996.74, 14959.93, 14915.18, 14861.86, 14810.61, 14762.06, 14708.42, 14657.64, 14594.65,
96
    14508.80, 14422.96, 14344.89, 14271.90, 14219.06, 14189.07, 14159.08, 14128.61, 14100.36, 14071.01,
97
    14037.85, 13995.16, 13943.43, 13891.38, 13842.35, 13804.11, 13782.37, 13791.10, 13821.57, 13852.98,
98
    13877.58, 13898.05, 13900.43, 13880.75, 13859.81, 13837.43, 13810.93, 13783.01, 13757.62, 13751.43,
99
    13764.60, 13780.79, 13797.29, 13811.41, 13806.49, 13783.01, 13757.30, 13727.31, 13695.73, 13662.41,
100
    13626.87, 13593.54, 13564.51, 13535.31, 13506.11, 13477.71, 13445.66, 13407.57, 13367.90, 13327.28,
101
    13284.91, 13240.17, 13195.42, 13146.70, 13093.39, 13038.49, 12982.63, 12926.46, 12873.94, 12823.00,
102
    12770.64, 12720.02, 12670.51, 12623.06, 12579.74, 12536.11, 12488.98, 12438.84, 12384.73, 12327.60,
103
    12271.91, 12222.88, 12180.03, 12142.74, 12110.06, 12079.91, 12047.06, 12014.05, 11981.53, 11948.36,
104
    11916.63, 11883.94, 11847.76, 11813.48, 11782.22, 11754.14, 11731.61, 11711.45, 11688.29, 11664.01,
105
    11638.46, 11609.90, 11581.50, 11551.82, 11518.98, 11482.16, 11443.13, 11402.98, 11363.15, 11324.44,
106
    11287.62, 11253.98, 11222.41, 11193.68, 11167.03, 11144.34, 11124.34, 11104.67, 11084.51, 11064.36,
107
    11042.31, 11019.77, 10999.14, 10983.28, 10971.69, 10963.44, 10957.09, 10954.56, 10952.97, 10947.89,
108
    10940.27, 10933.45, 10925.52, 10917.11, 10912.66, 10911.24, 10909.49, 10908.54, 10907.75, 10909.01,
109
    10913.30, 10915.20, 10913.62, 10912.35, 10909.49, 10904.41, 10902.51, 10904.57, 10906.79, 10906.48,
110
    10904.25, 10898.07, 10887.12, 10872.36, 10856.49, 10839.20, 10822.53, 10804.45, 10783.98, 10763.03,
111
    10741.93, 10716.85, 10689.88, 10662.86, 10633.89, 10602.97, 10575.14, 10551.62, 10530.56, 10511.96,
112
    10495.82, 10480.23, 10463.32, 10445.07, 10425.49, 10404.57, 10383.53, 10363.57, 10344.69, 10326.89,
113
    10310.16, 10293.63, 10276.39, 10258.46, 10239.83, 10220.51, 10200.89, 10181.41, 10162.05, 10142.82,
114
    10123.71, 10104.16, 10083.60, 10062.02, 10039.42, 10015.81, 9991.44,  9966.56,  9941.17,  9915.27,
115
    9888.87,  9862.37,  9836.19,  9810.32,  9784.77,  9759.55,  9735.05,  9711.69,  9689.47,  9668.40,
116
    9648.47,  9628.83,  9608.61,  9587.82,  9566.46,  9544.54,  9522.70,  9501.63,  9481.32,  9461.77,
117
    9442.98,  9424.13,  9404.39,  9383.76,  9362.24,  9339.84,  9317.15,  9294.77,  9272.72,  9250.98,
118
    9229.56,  9208.10,  9186.27,  9164.05,  9141.46,  9118.48,  9095.66,  9073.54,  9052.12,  9031.40,
119
    9011.37,  8992.33,  8974.56,  8958.06,  8942.82,  8928.86,  8915.56,  8902.33,  8889.16,  8876.05,
120
    8863.01,  8850.03,  8837.11,  8824.26,  8811.47,  8798.74,  8785.76,  8772.21,  8758.09,  8743.40,
121
    8728.13,  8712.52,  8696.78,  8680.91,  8664.91,  8648.79,  8632.61,  8616.42,  8600.24,  8584.05,
122
    8567.87,  8551.78,  8535.88,  8520.17,  8504.65,  8489.32,  8474.06,  8458.73,  8443.34,  8427.88,
123
    8412.36,  8397.03,  8382.15,  8367.71,  8353.71,  8340.16,  8326.52,  8312.23,  8297.32,  8281.77,
124
    8265.58,  8248.95,  8232.07,  8214.93,  8197.54,  8179.90,  8162.35,  8145.24,  8128.58,  8112.36,
125
    8096.59,  8081.04,  8065.49,  8049.94,  8034.39,  8018.84,  8003.29,  7987.74,  7972.19,  7956.64,
126
    7941.08,  7925.95,  7911.63,  7898.15,  7885.48,  7873.65,  7862.06,  7850.16,  7837.94,  7825.41,
127
    7812.56,  7799.29,  7785.52,  7771.24,  7756.45,  7741.15,  7725.73,  7710.56,  7695.64,  7680.98,
128
    7666.57,  7652.29,  7638.01,  7623.73,  7609.45,  7595.17,  7580.95,  7566.86,  7552.89,  7539.06,
129
    7525.35,  7511.22,  7496.15,  7480.12,  7463.14,  7445.21,  7427.19,  7409.92,  7393.42,  7377.68,
130
    7362.70,  7348.26,  7334.14,  7320.33,  7306.85,  7293.68,  7280.92,  7268.67,  7256.93,  7245.69,
131
    7234.96,  7224.14,  7212.62,  7200.40,  7187.49,  7173.87,  7160.26,  7147.34,  7135.12,  7123.60,
132
    7112.78,  7102.47,  7092.47,  7082.79,  7073.43,  7064.38,  7055.31,  7045.85,  7036.01,  7025.79,
133
    7015.19,  7004.69,  6994.76,  6985.39,  6976.60,  6968.38,  6960.29,  6951.88,  6943.15,  6934.11,
134
    6924.75,  6915.54,  6906.97,  6899.04,  6891.74,  6885.08,  6878.54,  6871.62,  6864.32,  6856.64,
135
    6848.58,  6839.38,  6828.27,  6815.26,  6800.34,  6783.52,  6766.16,  6749.63,  6733.92,  6719.04,
136
    6704.98,  6691.36,  6677.81,  6664.32,  6650.90,  6637.54,  6624.56,  6612.28,  6600.69,  6589.81,
137
    6579.62,  6569.43,  6558.55,  6546.96,  6534.68,  6521.70,  6508.44,  6495.30,  6482.29,  6469.40,
138
    6456.64,  6444.46,  6433.29,  6423.13,  6413.99,  6405.87,  6397.87,  6389.11,  6379.59,  6369.31,
139
    6358.26,  6347.19,  6336.81,  6327.13,  6318.15,  6309.87,  6302.25,  6295.27,  6288.92,  6283.21,
140
    6278.13,  6273.24,  6268.10,  6262.71,  6257.06,  6251.15,  6245.00,  6238.59,  6231.92,  6225.00,
141
    6217.83,  6210.09,  6201.46,  6191.94,  6181.53,  6170.23,  6158.90,  6148.39,  6138.71,  6129.86,
142
    6121.83,  6113.96,  6105.58,  6096.70,  6087.30,  6077.40,  6066.93,  6055.82,  6044.08,  6031.70,
143
    6018.69,  6005.42,  5992.29,  5979.27,  5966.39,  5953.63,  5940.81,  5927.74,  5914.41,  5900.82,
144
    5886.99,  5873.09,  5859.31,  5845.67,  5832.15,  5818.75,  5805.58,  5792.73,  5780.20,  5767.98,
145
    5756.08,  5744.30,  5732.47,  5720.56,  5708.60,  5696.57,  5684.26,  5671.44,  5658.11,  5644.27,
146
    5629.93,  5615.46,  5601.24,  5587.27,  5573.56,  5560.11,  5546.94,  5534.08,  5521.55,  5509.33,
147
    5497.43,  5485.72,  5474.07,  5462.49,  5450.97,  5439.51,  5428.15,  5416.92,  5405.81,  5394.83,
148
    5383.97,  5373.12,  5362.14,  5351.03,  5339.80,  5328.44,  5317.20,  5306.35,  5295.88,  5285.78,
149
    5276.07,  5266.58,  5257.16,  5247.80,  5238.50,  5229.26,  5220.09,  5210.98,  5201.94,  5192.96,
150
    5184.04,  5175.28,  5166.78,  5158.52,  5150.53,  5142.78,  5135.13,  5127.42,  5119.65,  5111.81,
151
    5103.91,  5095.97,  5088.04,  5080.10,  5072.17,  5064.24,  5056.59,  5049.51,  5043.01,  5037.07,
152
    5031.71,  5026.28,  5020.16,  5013.33,  5005.81,  4997.59,  4989.02,  4980.45,  4971.89,  4963.32,
153
    4954.75,  4946.08,  4937.23,  4928.19,  4918.95,  4909.52,  4899.85,  4889.85,  4879.53,  4868.90,
154
    4857.95,  4847.10,  4836.75,  4826.92,  4817.59,  4808.76,  4799.81,  4790.10,  4779.63,  4768.40,
155
    4756.40,  4744.40,  4733.17,  4722.70,  4712.99,  4704.04,  4695.31,  4686.26,  4676.90,  4667.22,
156
    4657.23,  4646.91,  4636.28,  4625.33,  4614.06,  4602.48,  4590.96,  4579.89,  4569.25,  4559.07,
157
    4549.32,  4539.87,  4530.54,  4521.33,  4512.26,  4503.31,  4494.39,  4485.41,  4476.36,  4467.26,
158
    4458.08,  4449.32,  4441.45,  4434.47,  4428.38,  4423.17,  4418.16,  4412.64,  4406.61,  4400.07,
159
    4393.03,  4386.11,  4379.95,  4374.55,  4369.92,  4366.05,  4362.21,  4357.67,  4352.43,  4346.50,
160
    4339.87,  4332.92,  4326.03,  4319.21,  4312.45,  4305.75,  4299.09,  4292.42,  4285.76,  4279.09,
161
    4272.43,  4265.76,  4259.10,  4252.44,  4245.77,  4239.11,  4232.70,  4226.79,  4221.40,  4216.51,
162
    4212.13,  4207.91,  4203.50,  4198.90,  4194.11,  4189.12,  4183.63,  4177.32,  4170.18,  4162.21,
163
    4153.42,  4144.34,  4135.52,  4126.95,  4118.64,  4110.58,  4102.74,  4095.09,  4087.63,  4080.36,
164
    4073.29,  4066.31,  4059.32,  4052.34,  4045.36,  4038.38,  4031.52,  4024.92,  4018.57,  4012.48,
165
    4006.64,  4000.83,  3994.84,  3988.65,  3982.27,  3975.70,  3968.97,  3962.12,  3955.13,  3948.03,
166
    3940.79,  3933.27,  3925.30,  3916.89,  3908.04,  3898.74,  3889.44,  3880.59,  3872.18,  3864.21,
167
    3856.69,  3849.52,  3842.60,  3835.94,  3829.52,  3823.37,  3817.21,  3810.80,  3804.14,  3797.22,
168
    3790.05,  3782.59,  3774.81,  3766.72,  3758.31,  3749.58,  3740.73,  3731.94,  3723.21,  3714.55,
169
    3705.95,  3697.44,  3689.06,  3680.81,  3672.69,  3664.69,  3656.69,  3648.57,  3640.32,  3631.94,
170
    3623.43,  3615.12,  3607.31,  3600.01,  3593.22,  3586.94,  3580.97,  3575.13,  3569.42,  3563.83,
171
    3558.37,  3552.92,  3547.33,  3541.62,  3535.78,  3529.81,  3524.04,  3518.77,  3514.01,  3509.75,
172
    3506.01,  3502.52,  3499.03,  3495.54,  3492.05,  3488.56,  3485.13,  3481.83,  3478.65,  3475.61,
173
    3472.69,  3469.74,  3466.59,  3463.26,  3459.74,  3456.03,  3452.22,  3448.41,  3444.60,  3440.79,
174
    3436.98,  3433.30,  3429.88,  3426.70,  3423.78,  3421.12,  3418.51,  3415.79,  3412.93,  3409.95,
175
    3406.84,  3403.66,  3400.49,  3397.32,  3394.14,  3390.97,  3387.76,  3384.49,  3381.16,  3377.77,
176
    3374.31,  3370.66,  3366.69,  3362.41,  3357.80,  3352.88,  3347.65,  3342.09,  3336.22,  3330.04,
177
    3323.53,  3317.02,  3310.84,  3304.96,  3299.41,  3294.17,  3289.13,  3284.15,  3279.23,  3274.37,
178
    3269.58,  3264.79,  3259.93,  3255.01,  3250.03,  3244.98,  3239.78,  3234.32,  3228.61,  3222.64,
179
    3216.42,  3210.17,  3204.11,  3198.24,  3192.56,  3187.07,  3181.54,  3175.77,  3169.74,  3163.45,
180
    3156.92,  3150.09,  3142.95,  3135.49,  3127.72,  3119.63,  3111.69,  3104.39,  3097.73,  3091.70,
181
    3086.30,  3081.26,  3076.28,  3071.36,  3066.50,  3061.71,  3056.63,  3050.92,  3044.57,  3037.59,
182
    3029.97,  3021.91,  3013.60,  3005.03,  2996.21,  2987.13,  2977.89,  2968.60,  2959.23,  2949.81,
183
    2940.32,  2931.02,  2922.17,  2913.76,  2905.79,  2898.27,  2890.69,  2882.53,  2873.80,  2864.50,
184
    2854.63,  2844.70,  2835.21,  2826.17,  2817.57,  2809.41,  2801.82,  2794.94,  2788.75,  2783.26,
185
    2778.47,  2773.58,  2767.80,  2761.14,  2753.59,  2745.14,  2736.42,  2728.01,  2719.91,  2712.14,
186
    2704.68,  2697.51,  2690.59,  2683.93,  2677.52,  2671.36,  2665.39,  2659.55,  2653.84,  2648.26,
187
    2642.80,  2637.37,  2631.88,  2626.33,  2620.71,  2615.03,  2609.22,  2603.22,  2597.03,  2590.66,
188
    2584.09,  2577.58,  2571.39,  2565.52,  2559.97,  2554.73,  2549.72,  2544.83,  2540.07,  2535.43,
189
    2530.93,  2526.29,  2521.28,  2515.89,  2510.11,  2503.95,  2497.73,  2491.77,  2486.05,  2480.60,
190
    2475.39,  2470.12,  2464.47,  2458.44,  2452.03,  2445.24,  2438.42,  2431.91,  2425.72,  2419.85,
191
    2414.30,  2409.00,  2403.89,  2398.97,  2394.24,  2389.70,  2385.23,  2380.69,  2376.09,  2371.42,
192
    2366.70,  2361.97,  2357.30,  2352.70,  2348.16,  2343.69,  2339.09,  2334.17,  2328.93,  2323.38,
193
    2317.51,  2311.44,  2305.32,  2299.13,  2292.88,  2286.56,  2280.28,  2274.12,  2268.09,  2262.19,
194
    2256.41,  2250.64,  2244.74,  2238.71,  2232.55,  2226.26,  2220.08,  2214.21,  2208.65,  2203.42,
195
    2198.50,  2193.67,  2188.72,  2183.64,  2178.44,  2173.11,  2167.74,  2162.44,  2157.21,  2152.03,
196
    2146.93,  2141.69,  2136.14,  2130.26,  2124.08,  2117.57,  2110.91,  2104.24,  2097.58,  2090.91,
197
    2084.25,  2077.93,  2072.31,  2067.40,  2063.17,  2059.65,  2056.32,  2052.67,  2048.70,  2044.42,
198
    2039.82,  2035.09,  2030.42,  2025.82,  2021.28,  2016.81,  2012.49,  2008.43,  2004.62,  2001.07,
199
    1997.77,  1994.53,  1991.17,  1987.68,  1984.06,  1980.31,  1976.66,  1973.33,  1970.32,  1967.62,
200
    1965.24,  1963.08,  1961.05,  1959.14,  1957.37,  1955.72,  1954.32,  1953.31,  1952.67,  1952.42,
201
    1952.54,  1952.80,  1952.92,  1952.92,  1952.80,  1952.54,  1952.00,  1951.02,  1949.59,  1947.72,
202
    1945.40,  1942.93,  1940.58,  1938.36,  1936.26,  1934.30,  1932.39,  1930.49,  1928.58,  1926.68,
203
    1924.77,  1922.78,  1920.59,  1918.21,  1915.64,  1912.87,  1910.11,  1907.54,  1905.16,  1902.97,
204
    1900.97,  1898.94,  1896.66,  1894.12,  1891.33,  1888.28,  1884.91,  1881.17,  1877.04,  1872.54,
205
    1867.65,  1862.76,  1858.26,  1854.13,  1850.39,  1847.02,  1843.88,  1840.80,  1837.79,  1834.84,
206
    1831.95,  1829.16,  1826.49,  1823.95,  1821.54,  1819.25,  1817.16,  1815.32,  1813.73,  1812.40,
207
    1811.32,  1810.27,  1809.03,  1807.61,  1805.99,  1804.18,  1802.27,  1800.37,  1798.47,  1796.56,
208
    1794.66,  1792.75,  1790.85,  1788.95,  1787.04,  1785.14,  1783.33,  1781.71,  1780.28,  1779.04,
209
    1778.00,  1776.95,  1775.71,  1774.28,  1772.67,  1770.86,  1768.76,  1766.29,  1763.43,  1760.19,
210
    1756.58,  1752.77,  1748.96,  1745.15,  1741.34,  1737.53,  1733.63,  1729.54,  1725.25,  1720.78,
211
    1716.11,  1711.13,  1705.70,  1699.83,  1693.52,  1686.76,  1680.14,  1674.25,  1669.10,  1664.67,
212
    1660.97,  1657.64,  1654.31,  1650.97,  1647.64,  1644.31,  1640.95,  1637.52,  1634.03,  1630.47,
213
    1626.86,  1623.21,  1619.56,  1615.91,  1612.26,  1608.61,  1605.01,  1601.50,  1598.09,  1594.77,
214
    1591.55,  1588.38,  1585.20,  1582.03,  1578.85,  1575.68,  1572.43,  1569.02,  1565.45,  1561.72,
215
    1557.83,  1553.86,  1549.90,  1545.93,  1541.96,  1538.00,  1534.06,  1530.19,  1526.38,  1522.64,
216
    1518.95,  1515.30,  1511.65,  1508.00,  1504.36,  1500.71,  1496.99,  1493.15,  1489.19,  1485.09,
217
    1480.87,  1476.59,  1472.30,  1468.02,  1463.73,  1459.45,  1455.30,  1451.41,  1447.79,  1444.43,
218
    1441.33,  1438.37,  1435.41,  1432.45,  1429.49,  1426.52,  1423.56,  1420.60,  1417.64,  1414.68,
219
    1411.71,  1408.74,  1405.75,  1402.73,  1399.70,  1396.64,  1393.57,  1390.50,  1387.44,  1384.37,
220
    1381.30,  1378.23,  1375.16,  1372.10,  1369.03,  1365.96,  1362.91,  1359.91,  1356.95,  1354.03,
221
    1351.15,  1348.29,  1345.44,  1342.58,  1339.73,  1336.87,  1334.01,  1331.16,  1328.30,  1325.44,
222
    1322.59,  1319.71,  1316.79,  1313.83,  1310.83,  1307.78,  1304.71,  1301.64,  1298.58,  1295.51,
223
    1292.44,  1289.37,  1286.30,  1283.24,  1280.17,  1277.10,  1274.05,  1271.05,  1268.09,  1265.17,
224
    1262.29,  1259.43,  1256.58,  1253.72,  1250.87,  1248.01,  1245.15,  1242.30,  1239.44,  1236.58,
225
    1233.73,  1230.88,  1228.06,  1225.25,  1222.47,  1219.71,  1216.96,  1214.21,  1211.46,  1208.71,
226
    1205.96,  1203.21,  1200.46,  1197.71,  1194.96,  1192.21,  1189.49,  1186.83,  1184.24,  1181.71,
227
    1179.25,  1176.82,  1174.38,  1171.95,  1169.52,  1167.08,  1164.65,  1162.22,  1159.78,  1157.35,
228
    1154.92,  1152.51,  1150.14,  1147.81,  1145.52,  1143.28,  1141.06,  1138.84,  1136.62,  1134.40,
229
    1132.17,  1129.95,  1127.73,  1125.51,  1123.29,  1121.07,  1118.90,  1116.83,  1114.88,  1113.03,
230
    1111.28,  1109.59,  1107.90,  1106.20,  1104.51,  1102.82,  1101.13,  1099.43,  1097.74,  1096.05,
231
    1094.36,  1092.66,  1090.97,  1089.28,  1087.59,  1085.89,  1084.20,  1082.51,  1080.81,  1079.12,
232
    1077.43,  1075.74,  1074.04,  1072.35,  1070.66,  1068.97,  1067.28,  1065.62,  1063.98,  1062.37,
233
    1060.77,  1059.18,  1057.59,  1056.01,  1054.42,  1052.83,  1051.25,  1049.66,  1048.07,  1046.49,
234
    1044.90,  1043.26,  1041.50,  1039.64,  1037.66,  1035.58,  1033.44,  1031.29,  1029.15,  1027.01,
235
    1024.87,  1022.73,  1020.58,  1018.44,  1016.30,  1014.16,  1012.01,  1009.87,  1007.73,  1005.59,
236
    1003.45,  1001.34,  999.30,   997.33,   995.43,   993.59,   991.80,   990.00,   988.20,   986.40,
237
    984.60,   982.80,   981.01,   979.21,   977.41,   975.61,   973.93,   972.48,   971.26,   970.28,
238
    969.53,   968.89,   968.26,   967.62,   966.99,   966.35,   965.72,   965.09,   964.45,   963.82,
239
    963.18,   962.55,   961.91,   961.28,   960.64,   960.01,   959.28,   958.36,   957.25,   955.95,
240
    954.45,   952.87,   951.28,   949.69,   948.11,   946.52,   944.93,   943.35,   941.76,   940.17,
241
    938.59,   937.00,   935.41,   933.83,   932.24,   930.65,   929.06,   927.45,   925.82,   924.18,
242
    922.52,   920.85,   919.19,   917.52,   915.85,   914.19,   912.52,   910.86,   909.19,   907.52,
243
    905.86,   904.19,   902.53,   900.86,   899.19,   897.53,   895.91,   894.39,   892.96,   891.62,
244
    890.39,   889.20,   888.01,   886.82,   885.63,   884.44,   883.25,   882.06,   880.87,   879.68,
245
    878.49,   877.30,   876.11,   874.92,   873.73,   872.54,   871.31,   870.00,   868.61,   867.14,
246
    865.59,   864.01,   862.42,   860.83,   859.25,   857.66,   856.07,   854.49,   852.90,   851.31,
247
    849.73,   848.14,   846.55,   844.97,   843.38,   841.79,   840.24,   838.74,   837.32,   835.95,
248
    834.65,   833.38,   832.11,   830.84,   829.57,   828.30,   827.03,   825.76,   824.50,   823.23,
249
    821.96,   820.69,   819.42,   818.15,   816.88,   815.61,   814.37,   813.20,   812.09,   811.04,
250
    810.06,   809.10,   808.15,   807.20,   806.25,   805.30,   804.34,   803.39,   802.44,   801.49,
251
    800.53,   799.58,   798.63,   797.68,   796.73,   795.77,   794.87,   794.06,   793.35,   792.73,
252
    792.20,   791.73,   791.25,   790.78,   790.30,   789.82,   789.35,   788.87,   788.40,   787.92,
253
    787.44,   786.97,   786.49,   786.02,   785.54,   785.06,   784.61,   784.19,   783.81,   783.48,
254
    783.18,   782.90,   782.62,   782.35,   782.07,   781.79,   781.51,   781.24,   780.96,   780.68,
255
    780.40,   780.12,   779.85,   779.57,   779.29,   779.01,   778.68,   778.23,   777.66,   776.98,
256
    776.18,   775.32,   774.46,   773.61,   772.75,   771.89,   771.04,   770.18,   769.32,   768.47,
257
    767.61,   766.75,   765.90,   765.04,   764.18,   763.32,   762.47,   761.61,   760.75,   759.90,
258
    759.04,   758.25,   757.59,   757.07,   756.68,   756.42,   756.23,   756.04,   755.85,   755.66,
259
    755.47,   755.28,   755.09,   754.90,   754.71,   754.52,   754.33,   754.14,   753.95,   753.76,
260
    753.57,   753.38,   753.19,   752.99,   752.80,   752.61,   752.43,   752.25,   752.08,   751.91,
261
    751.76,   751.60,   751.45,   751.30,   751.15,   751.00,   750.84,   750.69,   750.54,   750.39,
262
    750.2
263
};
264
constexpr double SUN_RAD_END = SUN_RAD_START + SUN_RAD_STEP * std::size(SUN_RAD_TABLE);
265
266
267
/////////////////////////////////////////////////////////////////////////////////////
268
// Conversion functions
269
/////////////////////////////////////////////////////////////////////////////////////
270
271!
double radiansToDegrees(const double radians) {
272!
    return radians * RAD_TO_DEG;
273
}
274
275
typedef unsigned short     uint16;
276
typedef unsigned int       uint32;
277
typedef unsigned long long uint64;
278
279!
double doubleFromHalf(const uint16 half) {
280!
    uint32 hi  = uint32(half & 0x8000) << 16;
281!
    uint16 abs = half & 0x7FFF;
282!
    if (abs) {
283!
        hi |= 0x3F000000 << uint16(abs >= 0x7C00);
284!
        for (; abs < 0x400; abs <<= 1, hi -= 0x100000)
285
            ;
286!
        hi += uint32(abs) << 10;
287
    }
288!
    const uint64 dbits = uint64(hi) << 32;
289
    double out;
290!
    std::memcpy(&out, &dbits, sizeof(double));
291!
    return out;
292
}
293
294
295
/////////////////////////////////////////////////////////////////////////////////////
296
// Vector3 operations
297
/////////////////////////////////////////////////////////////////////////////////////
298
299!
double dot(const PragueSkyModel::Vector3& v1, const PragueSkyModel::Vector3& v2) {
300!
    return v1.x * v2.x + v1.y * v2.y + v1.z * v2.z;
301
}
302
303!
double magnitude(const PragueSkyModel::Vector3& vector) {
304!
    return std::sqrt(dot(vector, vector));
305
}
306
307!
PragueSkyModel::Vector3 normalize(const PragueSkyModel::Vector3& vector) {
308!
    return vector / magnitude(vector);
309
}
310
311
312
/////////////////////////////////////////////////////////////////////////////////////
313
// Helper functions
314
/////////////////////////////////////////////////////////////////////////////////////
315
316!
double pragueLerp(const double from, const double to, const double factor) {
317!
    return (1.0 - factor) * from + factor * to;
318
}
319
320!
double nonlerp(const double a, const double b, const double w, const double p) {
321!
    const double c1 = pow(a, p);
322!
    const double c2 = pow(b, p);
323!
    return ((pow(w, p) - c1) / (c2 - c1));
324
}
325
326
327
/////////////////////////////////////////////////////////////////////////////////////
328
// Data reading
329
/////////////////////////////////////////////////////////////////////////////////////
330
331
// skymodelr: full-altitude datasets exceed 2 GB. Windows long/fseek offsets are
332
// only 32 bits; use the platform's 64-bit seek and report a failed skip.
333!
static void skipDatasetBytes(FILE* handle, size_t bytes) {
334
#ifdef _WIN32
335
    int status = _fseeki64(handle, static_cast<__int64>(bytes), SEEK_CUR);
336
#else
337!
    int status = fseeko(handle, static_cast<off_t>(bytes), SEEK_CUR);
338
#endif
339!
    if (status != 0) throw PragueSkyModel::DatasetReadException("coefficient offset");
340
}
341
3421x
void PragueSkyModel::readRadiance(FILE* handle, const double singleVisibility) {
343
    // Read metadata.
344
345
    // Structure of the metadata part of the data file:
346
    // visibilityCount      (1 * int), visibilities         (visibilityCount * double),
347
    // albedoCount          (1 * int), albedos                  (albedoCount * double),
348
    // altitudeCount        (1 * int), altitudes              (altitudeCount * double),
349
    // elevationCount       (1 * int), elevations            (elevationCount * double),
350
    // channels             (1 * int), channelStart                       (1 * double), channelWidth (1 * double), 
351
    // rankRad              (1 * int), 
352
    // sunBreaksCountRad    (1 * int), sunBreaksRad       (sunBreaksCountRad * double), 
353
    // zenithBreaksCountRad (1 * int), zenithBreaksRad (zenithBreaksCountRad * double), 
354
    // emphBreaksCountRad   (1 * int), emphBreaksRad     (emphBreaksCountRad * double)
355
356
    size_t valsRead;
357
3581x
    int visibilityCount = 0;
3591x
    valsRead            = fread(&visibilityCount, sizeof(int), 1, handle);
3601x
    if (valsRead != 1 || visibilityCount < 1)
361!
        throw DatasetReadException("visibilityCountRad");
362
3631x
    std::vector<double> visibilitiesRadInFile;
3641x
    visibilitiesRadInFile.resize(visibilityCount);
3651x
    valsRead = fread(visibilitiesRadInFile.data(), sizeof(double), visibilityCount, handle);
3661x
    if (valsRead != visibilitiesRadInFile.size())
3673x
        throw DatasetReadException("visibilitesRad");
368
369!
    int skippedVisibilities = 0;
370!
    if (singleVisibility <= 0.0 || visibilityCount <= 1) {
371
        // If the given single visibility value is not valid or there is just one visibility present (so there
372
        // is nothing to save), all visibilities present are loaded.
373!
        visibilitiesRad.resize(visibilityCount);
374!
        visibilitiesRad = visibilitiesRadInFile;
375
    } else {
376
        // Otherwise, only the two visibilities closest to the single visibility value are loaded and the rest
377
        // is skipped.
378!
        if (singleVisibility <= visibilitiesRadInFile.front()) {
379!
            visibilitiesRad.resize(1);
380!
            visibilitiesRad[0] = visibilitiesRadInFile.front();
381!
        } else if (singleVisibility >= visibilitiesRadInFile.back()) {
382!
            visibilitiesRad.resize(1);
383!
            visibilitiesRad[0] = visibilitiesRadInFile.back();
384!
            skippedVisibilities = visibilitiesRadInFile.size() - 1;
385
        }
386
        else {
387!
            int visIdx = 0;
388!
            while (singleVisibility >= visibilitiesRadInFile[visIdx]) {
389!
                ++visIdx;
390
            }
391!
            visibilitiesRad.resize(2);
392!
            visibilitiesRad[0] = visibilitiesRadInFile[visIdx - 1];
393!
            visibilitiesRad[1] = visibilitiesRadInFile[visIdx];
394!
            skippedVisibilities = visIdx - 1;
395
        }        
396
    }
397
398!
    int albedoCount = 0;
399!
    valsRead        = fread(&albedoCount, sizeof(int), 1, handle);
400!
    if (valsRead != 1 || albedoCount < 1)
401!
        throw DatasetReadException("albedoCountRad");
402
403!
    albedosRad.resize(albedoCount);
404!
    valsRead = fread(albedosRad.data(), sizeof(double), albedoCount, handle);
405!
    if (valsRead != albedosRad.size())
406!
        throw DatasetReadException("albedosRad");
407
408!
    int altitudeCount = 0;
409!
    valsRead          = fread(&altitudeCount, sizeof(int), 1, handle);
410!
    if (valsRead != 1 || altitudeCount < 1)
411!
        throw DatasetReadException("altitudeCountRad");
412
413!
    altitudesRad.resize(altitudeCount);
414!
    valsRead = fread(altitudesRad.data(), sizeof(double), altitudeCount, handle);
415!
    if (valsRead != altitudesRad.size())
416!
        throw DatasetReadException("altitudesRad");
417
418!
    int elevationCount = 0;
419!
    valsRead           = fread(&elevationCount, sizeof(int), 1, handle);
420!
    if (valsRead != 1 || elevationCount < 1)
421!
        throw DatasetReadException(" elevationCountRad");
422
423!
    elevationsRad.resize(elevationCount);
424!
    valsRead = fread(elevationsRad.data(), sizeof(double), elevationCount, handle);
425!
    if (valsRead != elevationsRad.size())
426!
        throw DatasetReadException("elevationsRad");
427
428!
    valsRead = fread(&channels, sizeof(int), 1, handle);
429!
    if (valsRead != 1 || channels < 1)
430!
        throw DatasetReadException("channels");
431
432!
    valsRead = fread(&channelStart, sizeof(double), 1, handle);
433!
    if (valsRead != 1 || channelStart < 0)
434!
        throw DatasetReadException("channelStart");
435
436!
    valsRead = fread(&channelWidth, sizeof(double), 1, handle);
437!
    if (valsRead != 1 || channelWidth <= 0)
438!
        throw DatasetReadException("channelWidth");
439
440!
    totalConfigs =
441!
        channels * elevationsRad.size() * altitudesRad.size() * albedosRad.size() * visibilitiesRad.size();
442
443!
    skippedConfigsBegin =
444!
        channels * elevationsRad.size() * altitudesRad.size() * albedosRad.size() * skippedVisibilities;
445
446!
    skippedConfigsEnd = channels * elevationsRad.size() * altitudesRad.size() * albedosRad.size() *
447!
                        (visibilitiesRadInFile.size() - skippedVisibilities - visibilitiesRad.size());
448
449!
    valsRead = fread(&metadataRad.rank, sizeof(int), 1, handle);
450!
    if (valsRead != 1 || metadataRad.rank < 1)
451!
        throw DatasetReadException("rankRad");
452
453!
    int sunBreaksCount = 0;
454!
    valsRead           = fread(&sunBreaksCount, sizeof(int), 1, handle);
455!
    if (valsRead != 1 || sunBreaksCount < 2)
456!
        throw DatasetReadException("sunBreaksCountRad");
457
458!
    metadataRad.sunBreaks.resize(sunBreaksCount);
459!
    valsRead = fread(metadataRad.sunBreaks.data(), sizeof(double), sunBreaksCount, handle);
460!
    if (valsRead != metadataRad.sunBreaks.size())
461!
        throw DatasetReadException("sunBreaksRad");
462
463!
    int zenitBreaksCount = 0;
464!
    valsRead             = fread(&zenitBreaksCount, sizeof(int), 1, handle);
465!
    if (valsRead != 1 || zenitBreaksCount < 2)
466!
        throw DatasetReadException("zenitBreaksCountRad");
467
468!
    metadataRad.zenithBreaks.resize(zenitBreaksCount);
469!
    valsRead = fread(metadataRad.zenithBreaks.data(), sizeof(double), zenitBreaksCount, handle);
470!
    if (valsRead != metadataRad.zenithBreaks.size())
471!
        throw DatasetReadException("zenithBreaksRad");
472
473!
    int emphBreaksCount = 0;
474!
    valsRead            = fread(&emphBreaksCount, sizeof(int), 1, handle);
475!
    if (valsRead != 1 || emphBreaksCount < 2)
476!
        throw DatasetReadException("emphBreaksCountRad");
477
478!
    metadataRad.emphBreaks.resize(emphBreaksCount);
479!
    valsRead = fread(metadataRad.emphBreaks.data(), sizeof(double), emphBreaksCount, handle);
480!
    if (valsRead != metadataRad.emphBreaks.size())
481!
        throw DatasetReadException("emphBreaksRad");
482
483
    // Calculate offsets and strides.
484
485!
    metadataRad.sunOffset = 0;
486!
    metadataRad.sunStride = metadataRad.sunBreaks.size() + metadataRad.zenithBreaks.size();
487
488!
    metadataRad.zenithOffset = metadataRad.sunOffset + metadataRad.sunBreaks.size();
489!
    metadataRad.zenithStride = metadataRad.sunStride;
490
491!
    metadataRad.emphOffset = metadataRad.sunOffset + metadataRad.rank * metadataRad.sunStride;
492
493!
    metadataRad.totalCoefsSingleConfig =
494!
        metadataRad.emphOffset + metadataRad.emphBreaks.size(); // this is for one specific configuration
495!
    metadataRad.totalCoefsAllConfigs = metadataRad.totalCoefsSingleConfig * totalConfigs;
496
497
    // Read data.
498
499
    // Structure of the data part of the data file:
500
    // [[[[[[ sunCoefsRad       (sunBreaksCountRad * half), zenithScale (1 * double), 
501
    //        zenithCoefsRad (zenithBreaksCountRad * half) ] * rankRad, 
502
    //        emphCoefsRad     (emphBreaksCountRad * half) ]
503
    //  * channels ] * elevationCount ] * altitudeCount ] * albedoCount ] * visibilityCount
504
505!
    int offset = 0;
506!
    dataRad.resize(metadataRad.totalCoefsAllConfigs);
507
508!
    std::vector<uint16> radianceTemp;
509!
    radianceTemp.resize(std::max(metadataRad.sunBreaks.size(),
510!
                                 std::max(metadataRad.zenithBreaks.size(), metadataRad.emphBreaks.size())));
511
512
    size_t oneConfigByteCount =
513!
        ((metadataRad.sunBreaks.size() + metadataRad.zenithBreaks.size()) * sizeof(uint16) + sizeof(double)) *
514!
            metadataRad.rank +
515!
        metadataRad.emphBreaks.size() * sizeof(uint16);
516
517
    // If a single visibility was requested, skip all configurations from the beginning till those needed for
518
    // the requested visibility.
519!
    skipDatasetBytes(handle, oneConfigByteCount * skippedConfigsBegin);
520
521
    // Read configurations needed for the requested visibility (or all if none requested).
522!
    for (int con = 0; con < totalConfigs; ++con) {
523!
        for (int r = 0; r < metadataRad.rank; ++r) {
524
            // Read sun params.
525!
            valsRead = fread(radianceTemp.data(), sizeof(uint16), metadataRad.sunBreaks.size(), handle);
526!
            if (valsRead != metadataRad.sunBreaks.size())
527!
                throw DatasetReadException("sunCoefsRad");
528
529
            // Unpack sun params from half.
530!
            for (size_t i = 0; i < metadataRad.sunBreaks.size(); ++i) {
531!
                dataRad[offset++] = float(doubleFromHalf(radianceTemp[i]));
532
            }
533
534
            // Read scaling factor for zenith params.
535
            double zenithScale;
536!
            valsRead = fread(&zenithScale, sizeof(double), 1, handle);
537!
            if (valsRead != 1)
538!
                throw DatasetReadException("zenithScaleRad");
539
540
            // Read zenith params.
541!
            valsRead = fread(radianceTemp.data(), sizeof(uint16), metadataRad.zenithBreaks.size(), handle);
542!
            if (valsRead != metadataRad.zenithBreaks.size())
543!
                throw DatasetReadException("zenithCoefsRad");
544
545
            // Unpack zenith params from half (these need additional rescaling).
546!
            for (size_t i = 0; i < metadataRad.zenithBreaks.size(); ++i) {
547!
                dataRad[offset++] = float(doubleFromHalf(radianceTemp[i]) / zenithScale);
548
            }
549
        }
550
551
        // Read emphasize params.
552!
        valsRead = fread(radianceTemp.data(), sizeof(uint16), metadataRad.emphBreaks.size(), handle);
553!
        if (valsRead != metadataRad.emphBreaks.size())
554!
            throw DatasetReadException("emphCoefsRad");
555
556
        // Unpack emphasize params from half.
557!
        for (size_t i = 0; i < metadataRad.emphBreaks.size(); ++i) {
558!
            dataRad[offset++] = float(doubleFromHalf(radianceTemp[i]));
559
        }
560
    }
561
562
    // Skip remaining configurations till the end.
563!
    skipDatasetBytes(handle, oneConfigByteCount * skippedConfigsEnd);
564
}
565
566!
void PragueSkyModel::readTransmittance(FILE* handle) {
567
    // Read metadata
568
569
    size_t valsRead;
570
571!
    valsRead = fread(&dDim, sizeof(int), 1, handle);
572!
    if (valsRead != 1 || dDim < 1)
573!
        throw DatasetReadException("dDim");
574
575!
    valsRead = fread(&aDim, sizeof(int), 1, handle);
576!
	if (valsRead != 1 || aDim < 1)
577!
        throw DatasetReadException("aDim");
578
579!
    int visibilitiesCount = 0;
580!
    valsRead = fread(&visibilitiesCount, sizeof(int), 1, handle);
581!
    if (valsRead != 1 || visibilitiesCount < 1)
582!
        throw DatasetReadException("visibilitiesCountTrans");
583
584!
    int altitudesCount = 0;
585!
    valsRead = fread(&altitudesCount, sizeof(int), 1, handle);
586!
    if (valsRead != 1 || altitudesCount < 1)
587!
        throw DatasetReadException("altitudesCountTrans");
588
589!
    valsRead = fread(&rankTrans, sizeof(int), 1, handle);
590!
    if (valsRead != 1 || rankTrans < 1)
591!
        throw DatasetReadException("rankTrans");
592
593!
    std::vector<float> temp;
594!
    temp.resize(std::max(altitudesCount, visibilitiesCount));
595
596!
    altitudesTrans.resize(altitudesCount);
597!
    valsRead = fread(temp.data(), sizeof(float), altitudesCount, handle);
598!
    if (valsRead != altitudesTrans.size())
599!
        throw DatasetReadException("altitudesTrans");
600!
    for (int i = 0; i < altitudesCount; i++) {
601!
        altitudesTrans[i] = double(temp[i]);
602
    }
603
604!
    visibilitiesTrans.resize(visibilitiesCount);
605!
    valsRead = fread(temp.data(), sizeof(float), visibilitiesCount, handle);
606!
    if (valsRead != visibilitiesTrans.size())
607!
        throw DatasetReadException("visibilitiesTrans");
608!
    for (int i = 0; i < visibilitiesCount; i++) {
609!
        visibilitiesTrans[i] = double(temp[i]);
610
    }
611
612!
    const size_t totalCoefsU = dDim * aDim * rankTrans * altitudesTrans.size();
613!
    const size_t totalCoefsV = visibilitiesTrans.size() * rankTrans * channels * altitudesTrans.size();
614
615
    // Read data
616
617!
    dataTransU.resize(totalCoefsU);
618!
    valsRead = fread(dataTransU.data(), sizeof(float), totalCoefsU, handle);
619!
    if (valsRead != totalCoefsU)
620!
        throw DatasetReadException("datasetTransU");
621
622!
    dataTransV.resize(totalCoefsV);
623!
    valsRead = fread(dataTransV.data(), sizeof(float), totalCoefsV, handle);
624!
    if (valsRead != totalCoefsV)
625!
        throw DatasetReadException("datasetTransV");
626
}
627
628!
void PragueSkyModel::readPolarisation(FILE* handle) {
629
    // Read metadata.
630
631
    // Structure of the metadata part of the data file:
632
    // rankPol              (1 * int), 
633
    // sunBreaksCountPol    (1 * int), sunBreaksPol    (sunBreaksCountPol * double),
634
    // zenithBreaksCountPol (1 * int), zenithBreaksPol (zenithBreaksCountPol * double), 
635
636
    size_t valsRead;
637
638!
    valsRead = fread(&metadataPol.rank, sizeof(int), 1, handle);
639!
    if (valsRead != 1) {
640
        // Polarisation dataset not present
641!
        metadataPol.rank = 0;
642!
        return;
643
    }
644
645!
    int sunBreaksCount = 0;
646!
    valsRead           = fread(&sunBreaksCount, sizeof(int), 1, handle);
647!
    if (valsRead != 1 || sunBreaksCount < 1)
648!
        throw DatasetReadException("sunBreaksCountPol");
649
650!
    metadataPol.sunBreaks.resize(sunBreaksCount);
651!
    valsRead = fread(metadataPol.sunBreaks.data(), sizeof(double), sunBreaksCount, handle);
652!
    if (valsRead != metadataPol.sunBreaks.size())
653!
        throw DatasetReadException("sunBreaksPol");
654
655!
    int zenithBreaksCount = 0;
656!
    valsRead              = fread(&zenithBreaksCount, sizeof(int), 1, handle);
657!
    if (valsRead != 1 || zenithBreaksCount < 1)
658!
        throw DatasetReadException("zenithBreaksCountPol");
659
660!
    metadataPol.zenithBreaks.resize(zenithBreaksCount);
661!
    valsRead = fread(metadataPol.zenithBreaks.data(), sizeof(double), zenithBreaksCount, handle);
662!
    if (valsRead != metadataPol.zenithBreaks.size())
663!
        throw DatasetReadException("zenithBreaksPol");
664
665!
    metadataPol.emphBreaks.clear();
666
667
    // Calculate offsets and strides.
668
669!
    metadataPol.sunOffset = 0;
670!
    metadataPol.sunStride = metadataPol.sunBreaks.size() + metadataPol.zenithBreaks.size();
671
672!
    metadataPol.zenithOffset = metadataPol.sunOffset + metadataPol.sunBreaks.size();
673!
    metadataPol.zenithStride = metadataPol.sunStride;
674
675!
    metadataPol.emphOffset = 0;
676
677!
    metadataPol.totalCoefsSingleConfig =
678!
        metadataPol.sunOffset +
679!
        metadataPol.rank * metadataPol.sunStride; // this is for one specific configuration
680!
    metadataPol.totalCoefsAllConfigs = metadataPol.totalCoefsSingleConfig * totalConfigs;
681
682
    // Read data.
683
684
    // Structure of the data part of the data file:
685
    // [[[[[[ sunCoefsPol       (sunBreaksCountPol * float), 
686
    //        zenithCoefsPol (zenithBreaksCountPol * float) ] * rankPol] 
687
    // * channels ] * elevationCount ] * altitudeCount ] * albedoCount ] * visibilityCount
688
689!
    size_t offset = 0;
690!
    dataPol.resize(metadataPol.totalCoefsAllConfigs);
691
692
    size_t oneConfigByteCount =
693!
        (metadataPol.sunBreaks.size() + metadataPol.zenithBreaks.size()) * sizeof(float) * metadataPol.rank;
694
695
    // If a single visibility was requested, skip all configurations from the beginning till those needed for
696
    // the requested visibility.
697!
    skipDatasetBytes(handle, oneConfigByteCount * skippedConfigsBegin);
698
699!
    for (int con = 0; con < totalConfigs; ++con) {
700!
        for (int r = 0; r < metadataPol.rank; ++r) {
701
            // Read sun params.
702!
            valsRead = fread(dataPol.data() + offset, sizeof(float), metadataPol.sunBreaks.size(), handle);
703!
            if (valsRead != metadataPol.sunBreaks.size())
704!
                throw DatasetReadException("sunCoefsPol");
705!
            offset += metadataPol.sunBreaks.size();
706
707
            // Read zenith params.
708!
            valsRead = fread(dataPol.data() + offset, sizeof(float), metadataPol.zenithBreaks.size(), handle);
709!
            if (valsRead != metadataPol.zenithBreaks.size())
710!
                throw DatasetReadException("zenithCoefsPol");
711!
            offset += metadataPol.zenithBreaks.size();
712
        }
713
    }
714
}
715
716
717
/////////////////////////////////////////////////////////////////////////////////////
718
// Initialization
719
/////////////////////////////////////////////////////////////////////////////////////
720
7212x
void PragueSkyModel::initialize(const std::string& filename, const double singleVisibility,
722
                                bool cacheSpectra, bool transmissionTable, double transmissionTableMaxMiB) {
7232x
    if (std::isnan(transmissionTableMaxMiB) || transmissionTableMaxMiB < 0)
724!
        throw std::invalid_argument("Prague transmission table limit must be nonnegative MiB or infinity.");
7252x
    if (FILE* handle = fopen(filename.c_str(), "rb")) {
726
        // skymodelr: close the file if a truncated dataset throws while loading.
7271x
        auto closeFile = [](FILE* stream) noexcept { fclose(stream); };
7281x
        std::unique_ptr<FILE, decltype(closeFile)> file(handle, closeFile);
7291x
        initialized = false;
730
        static std::atomic<unsigned long long> nextGeneration{1};
7311x
        cacheGeneration = nextGeneration.fetch_add(1, std::memory_order_relaxed);
7321x
        cacheSky = cacheSpectra;
7331x
        std::vector<double>().swap(expandedTrans);
7341x
        expandedVisibilityCount = 0;
735
        // Read data
7361x
        readRadiance(handle, singleVisibility);
737!
        readTransmittance(handle);
738!
        readPolarisation(handle);
739!
        if (transmissionTable) expandTransmission(singleVisibility, transmissionTableMaxMiB);
740!
        initialized = true;
741
    } else {
7421x
        throw DatasetNotFoundException(filename);
743
    }
744
}
745
746!
size_t PragueSkyModel::memoryUsage() const {
747!
    size_t bytes = sizeof(*this) + expandedTrans.capacity() * sizeof(double);
748!
    for (const auto* values : {&dataRad, &dataPol, &dataTransU, &dataTransV})
749!
        bytes += values->capacity() * sizeof(float);
750!
    for (const auto* values : {&visibilitiesRad, &albedosRad, &altitudesRad, &elevationsRad,
751!
                              &altitudesTrans, &visibilitiesTrans, &metadataRad.sunBreaks,
752!
                              &metadataRad.zenithBreaks, &metadataRad.emphBreaks,
753!
                              &metadataPol.sunBreaks, &metadataPol.zenithBreaks, &metadataPol.emphBreaks})
754!
        bytes += values->capacity() * sizeof(double);
755!
    return bytes;
756
}
757
758!
PragueSkyModel::AvailableData PragueSkyModel::getAvailableData() const {
759!
    if (!initialized) {
760!
        throw NotInitializedException();
761
    }
762
763
    AvailableData available;
764!
    available.albedoMin     = albedosRad.front();
765!
    available.albedoMax     = albedosRad.back();
766!
    available.altitudeMin   = altitudesRad.front();
767!
    available.altitudeMax   = altitudesRad.back();
768!
    available.elevationMin  = elevationsRad.front();
769!
    available.elevationMax  = elevationsRad.back();
770!
    available.visibilityMin = visibilitiesRad.front();
771!
    available.visibilityMax = visibilitiesRad.back();
772!
    available.polarisation  = (metadataPol.rank != 0);
773!
    available.channels      = channels;
774!
    available.channelStart  = channelStart;
775!
    available.channelWidth  = channelWidth;
776
777!
    return available;
778
}
779
780
781
/////////////////////////////////////////////////////////////////////////////////////
782
// Filling the Parameters structure
783
/////////////////////////////////////////////////////////////////////////////////////
784
785!
PragueSkyModel::Parameters PragueSkyModel::computeParameters(const Vector3& viewpoint,
786
                                                             const Vector3& viewDirection,
787
                                                             const double   groundLevelSolarElevationAtOrigin,
788
                                                             const double   groundLevelSolarAzimuthAtOrigin,
789
                                                             const double   visibility,
790
                                                             const double   albedo) const {
791
    // The caller validates radial altitude in the planet-centered frame.
792
    assert(magnitude(viewDirection) > 0.0);
793
    assert(visibility >= 0.0);
794
    assert(albedo >= 0.0 && albedo <= 1.0);
795
796
    Parameters params;
797!
    params.visibility = visibility;
798!
    params.albedo     = albedo;
799
800
    // Shift viewpoint about safety altitude up
801
802!
    const Vector3 centerOfTheEarth   = Vector3(0.0, 0.0, -PLANET_RADIUS);
803!
    Vector3       toViewpoint        = viewpoint - centerOfTheEarth;
804!
    Vector3       toViewpointN       = normalize(toViewpoint);
805!
    const double  distanceToView     = magnitude(toViewpoint) + SAFETY_ALTITUDE;
806!
    Vector3       toShiftedViewpoint = toViewpointN * distanceToView;
807!
    Vector3       shiftedViewpoint   = centerOfTheEarth + toShiftedViewpoint;
808
809!
    Vector3 viewDirectionN = normalize(viewDirection);
810
811
    // Compute altitude of viewpoint
812
813!
    params.altitude = distanceToView - PLANET_RADIUS;
814!
    params.altitude = std::max(params.altitude, 0.0);
815
816
    // Direction to sun
817
818!
    Vector3 directionToSunN;
819!
    directionToSunN.x = cos(groundLevelSolarAzimuthAtOrigin) * cos(groundLevelSolarElevationAtOrigin);
820!
    directionToSunN.y = sin(groundLevelSolarAzimuthAtOrigin) * cos(groundLevelSolarElevationAtOrigin);
821!
    directionToSunN.z = sin(groundLevelSolarElevationAtOrigin);
822
823
    // Solar elevation at viewpoint (more precisely, solar elevation at the point
824
    // on the ground directly below viewpoint)
825
826!
    const double dotZenithSun = dot(toViewpointN, directionToSunN);
827!
    params.elevation          = 0.5 * PI - acos(std::clamp(dotZenithSun, -1.0, 1.0));
828
829
    // Altitude-corrected view direction
830
831!
    Vector3 correctViewN;
832!
    if (distanceToView > PLANET_RADIUS) {
833!
        Vector3 lookAt = shiftedViewpoint + viewDirectionN;
834
835
        const double correction =
836!
            sqrt(distanceToView * distanceToView - PLANET_RADIUS * PLANET_RADIUS) / distanceToView;
837
838!
        Vector3 toNewOrigin = toViewpointN * (distanceToView - correction);
839!
        Vector3 newOrigin   = centerOfTheEarth + toNewOrigin;
840!
        Vector3 correctView = lookAt - newOrigin;
841
842!
        correctViewN = normalize(correctView);
843
    } else {
844!
        correctViewN = viewDirectionN;
845
    }
846
847
    // Sun angle (gamma) - no correction
848
849!
    double dotProductSun = dot(viewDirectionN, directionToSunN);
850!
    params.gamma         = acos(std::clamp(dotProductSun, -1.0, 1.0));
851
852
    // Shadow angle - requires correction
853
854!
    const double effectiveElevation = groundLevelSolarElevationAtOrigin;
855!
    const double effectiveAzimuth   = groundLevelSolarAzimuthAtOrigin;
856!
    const double shadowAngle        = effectiveElevation + PI * 0.5;
857
858!
    Vector3 shadowDirectionN = Vector3(cos(shadowAngle) * cos(effectiveAzimuth),
859!
                                       cos(shadowAngle) * sin(effectiveAzimuth),
860!
                                       sin(shadowAngle));
861
862!
    const double dotProductShadow = dot(correctViewN, shadowDirectionN);
863!
    params.shadow                 = acos(std::clamp(dotProductShadow, -1.0, 1.0));
864
865
    // Zenith angle (theta) - corrected version stored in otherwise unused zero
866
    // angle
867
868!
    double cosThetaCor = dot(correctViewN, toViewpointN);
869!
    params.zero        = acos(std::clamp(cosThetaCor, -1.0, 1.0));
870
871
    // Zenith angle (theta) - uncorrected version goes outside
872
873!
    double cosTheta = dot(viewDirectionN, toViewpointN);
874!
    params.theta    = acos(std::clamp(cosTheta, -1.0, 1.0));
875
876!
    return params;
877
}
878
879
880
/////////////////////////////////////////////////////////////////////////////////////
881
// Model evaluation for sky radiance and polarisation
882
/////////////////////////////////////////////////////////////////////////////////////
883
884
/// Evaluates piecewise linear approximation
885!
double evalPL(const std::vector<float>::const_iterator coefs, const double factor) {
886!
    if (factor == 0) return double(coefs[0]); // No successor at the final knot.
887!
    return (double(coefs[1]) - double(coefs[0])) * factor + double(coefs[0]);
888
}
889
890!
std::vector<float>::const_iterator PragueSkyModel::getCoefficients(const std::vector<float>& dataset,
891
                                                                   const int totalCoefsSingleConfig,
892
                                                                   const int elevation,
893
                                                                   const int altitude,
894
                                                                   const int visibility,
895
                                                                   const int albedo,
896
                                                                   const int wavelength) const {
897!
    return dataset.cbegin() +
898!
           (totalCoefsSingleConfig *
899!
            (wavelength + size_t(channels) * elevation + channels * elevationsRad.size() * altitude +
900!
             channels * elevationsRad.size() * altitudesRad.size() * albedo +
901!
             channels * elevationsRad.size() * altitudesRad.size() * albedosRad.size() * visibility));
902
}
903
904!
PragueSkyModel::InterpolationParameter PragueSkyModel::getInterpolationParameter(
905
    const double               queryVal,
906
    const std::vector<double>& breaks) const {
907
    // Clamp the value to the valid range.
908!
    const double clamped = std::clamp(queryVal, breaks.front(), breaks.back());
909
910
    // Get the nearest greater parameter value.
911!
    const auto next = std::upper_bound(breaks.cbegin() + 1, breaks.cend(), clamped);
912
913
    // Compute the index and float factor.
914
    InterpolationParameter parameter;
915!
    parameter.index = int(next - breaks.cbegin()) - 1;
916!
    if (next == breaks.cend()) {
917!
        parameter.factor = 0.0;
918
    } else {
919!
        parameter.factor = (clamped - *(next - 1)) / (*next - *(next - 1));
920
    }
921
922
    assert(0 <= parameter.index && parameter.index < breaks.size() &&
923
           (parameter.index < breaks.size() - 1 || parameter.factor == 0.f));
924
    assert(0 <= parameter.factor && parameter.factor <= 1);
925!
    return parameter;
926
}
927
928!
double PragueSkyModel::reconstruct(const AngleParameters&                   radianceParameters,
929
                                   const std::vector<float>::const_iterator channelParameters,
930
                                   const Metadata&                          metadata) const {
931
    // The original image was emphasized (for radiance only), re-parametrized into gamma-alpha space,
932
    // decomposed into sum of rankRad outer products of 'sun' and 'zenith' vectors and these vectors were
933
    // stored as piece-wise polynomial approximation. Here the process is reversed (for one point).
934
935!
    double result = 0.0;
936!
    for (int r = 0; r < metadata.rank; ++r) {
937
        // Restore the right value in the 'sun' vector
938!
        const double sunParam = evalPL(channelParameters + metadata.sunOffset + r * metadata.sunStride +
939!
                                           radianceParameters.gamma.index,
940!
                                       radianceParameters.gamma.factor);
941
942
        // Restore the right value in the 'zenith' vector
943!
        const double zenithParam = evalPL(channelParameters + metadata.zenithOffset +
944!
                                              r * metadata.zenithStride + radianceParameters.alpha.index,
945!
                                          radianceParameters.alpha.factor);
946
947
        // Accumulate their "outer" product
948!
        result += sunParam * zenithParam;
949
    }
950
951
    // De-emphasize (for radiance only)
952!
    if (!metadata.emphBreaks.empty()) {
953
        const double emphParam =
954!
            evalPL(channelParameters + metadata.emphOffset + radianceParameters.zero.index,
955!
                   radianceParameters.zero.factor);
956!
        result *= emphParam;
957!
        result = std::max(result, 0.0);
958
    }
959
960!
    return result;
961
}
962
963!
double PragueSkyModel::evaluateModel(const Parameters&         params,
964
                                     const double              wavelength,
965
                                     const std::vector<float>& data,
966
                                     const Metadata&           metadata) const {
967
    // Ignore wavelengths outside the dataset range.
968!
    if (wavelength < channelStart || wavelength >= (channelStart + channels * channelWidth)) {
969!
        return 0.0;
970
    }
971
    // Don't interpolate wavelengths inside the dataset range.
972!
    const int channelIndex = int(floor((wavelength - channelStart) / channelWidth));
973
974
    // Translate angle values to indices and interpolation factors.
975
    AngleParameters angleParameters;
976!
    angleParameters.gamma = getInterpolationParameter(params.gamma, metadata.sunBreaks);
977!
    if (!metadata.emphBreaks.empty()) { // for radiance
978
        angleParameters.alpha =
979!
            getInterpolationParameter(params.elevation < 0.0 ? params.shadow : params.zero,
980!
                                      metadata.zenithBreaks);
981!
        angleParameters.zero = getInterpolationParameter(params.zero, metadata.emphBreaks);
982
    } else { // for polarisation
983!
        angleParameters.alpha = getInterpolationParameter(params.zero, metadata.zenithBreaks);
984
    }
985
986
    // Translate configuration values to indices and interpolation factors.
987
    const InterpolationParameter visibilityParam =
988!
        getInterpolationParameter(params.visibility, visibilitiesRad);
989!
    const InterpolationParameter albedoParam   = getInterpolationParameter(params.albedo, albedosRad);
990!
    const InterpolationParameter altitudeParam = getInterpolationParameter(params.altitude, altitudesRad);
991
    const InterpolationParameter elevationParam =
992!
        getInterpolationParameter(radiansToDegrees(params.elevation), elevationsRad);
993
994
    // Prepare parameters controlling the interpolation.
995!
    ControlParameters controlParameters;
996!
    for (int i = 0; i < 16; ++i) {
997!
        const int visibilityIndex = std::min(visibilityParam.index + i / 8, int(visibilitiesRad.size() - 1));
998!
        const int albedoIndex     = std::min(albedoParam.index + (i % 8) / 4, int(albedosRad.size() - 1));
999!
        const int altitudeIndex   = std::min(altitudeParam.index + (i % 4) / 2, int(altitudesRad.size() - 1));
1000!
        const int elevationIndex  = std::min(elevationParam.index + i % 2, int(elevationsRad.size() - 1));
1001
1002!
        controlParameters.coefficients[i] = getCoefficients(data,
1003!
                                                            metadata.totalCoefsSingleConfig,
1004
                                                            elevationIndex,
1005
                                                            altitudeIndex,
1006
                                                            visibilityIndex,
1007
                                                            albedoIndex,
1008
                                                            channelIndex);
1009
    }
1010!
    controlParameters.interpolationFactor[0] = visibilityParam.factor;
1011!
    controlParameters.interpolationFactor[1] = albedoParam.factor;
1012!
    controlParameters.interpolationFactor[2] = altitudeParam.factor;
1013!
    controlParameters.interpolationFactor[3] = elevationParam.factor;
1014
1015
    // Interpolate.
1016!
    const double result = interpolate<0, 0>(angleParameters, controlParameters, metadata);
1017
    assert(metadata.emphBreaks.empty() || result >= 0.0); // polarisation can be negative
1018
1019!
    return result;
1020
}
1021
1022
1023
/////////////////////////////////////////////////////////////////////////////////////
1024
// Sky radiance
1025
/////////////////////////////////////////////////////////////////////////////////////
1026
1027
// skymodelr: reuse wavelength-independent lookup work for a whole spectrum.
1028!
void PragueSkyModel::skyRadianceSpectrum(const Parameters& params, const double* wavelengths,
1029
                                         size_t count, double* values) const {
1030!
    if (!initialized) throw NotInitializedException();
1031
    struct SkyEntry {
1032
        unsigned long long generation = 0;
1033
        Parameters parameters{};
1034
        size_t count = 0;
1035
        std::array<double, 16> wavelengths{}, values{};
1036
    };
1037
    struct SkyCache { std::array<SkyEntry, 16> entries{}; size_t next = 0; };
1038
    static thread_local SkyCache cache;
1039!
    const bool eligible = cacheSky && count > 0 && count <= 16;
1040!
    if (eligible) {
1041!
        for (size_t offset = 0; offset < cache.entries.size(); ++offset) {
1042!
            const auto &entry = cache.entries[(cache.next + 15 - offset) % 16];
1043!
            if (entry.generation == cacheGeneration && entry.count == count &&
1044!
                std::memcmp(&entry.parameters, &params, sizeof(Parameters)) == 0 &&
1045!
                std::equal(wavelengths, wavelengths + count, entry.wavelengths.begin())) {
1046!
                std::copy_n(entry.values.begin(), count, values);
1047!
                return;
1048
            }
1049
        }
1050
    }
1051!
    const auto& metadata = metadataRad;
1052!
    const auto& data = dataRad;
1053
    // Translate angle values to indices and interpolation factors.
1054
    AngleParameters angleParameters;
1055!
    angleParameters.gamma = getInterpolationParameter(params.gamma, metadata.sunBreaks);
1056!
    if (!metadata.emphBreaks.empty()) { // for radiance
1057
        angleParameters.alpha =
1058!
            getInterpolationParameter(params.elevation < 0.0 ? params.shadow : params.zero,
1059!
                                      metadata.zenithBreaks);
1060!
        angleParameters.zero = getInterpolationParameter(params.zero, metadata.emphBreaks);
1061
    } else { // for polarisation
1062!
        angleParameters.alpha = getInterpolationParameter(params.zero, metadata.zenithBreaks);
1063
    }
1064
1065
    // Translate configuration values to indices and interpolation factors.
1066
    const InterpolationParameter visibilityParam =
1067!
        getInterpolationParameter(params.visibility, visibilitiesRad);
1068!
    const InterpolationParameter albedoParam   = getInterpolationParameter(params.albedo, albedosRad);
1069!
    const InterpolationParameter altitudeParam = getInterpolationParameter(params.altitude, altitudesRad);
1070
    const InterpolationParameter elevationParam =
1071!
        getInterpolationParameter(radiansToDegrees(params.elevation), elevationsRad);
1072
1073
    // Prepare parameters controlling the interpolation.
1074!
    ControlParameters controlParameters;
1075!
    for (int i = 0; i < 16; ++i) {
1076!
        const int visibilityIndex = std::min(visibilityParam.index + i / 8, int(visibilitiesRad.size() - 1));
1077!
        const int albedoIndex     = std::min(albedoParam.index + (i % 8) / 4, int(albedosRad.size() - 1));
1078!
        const int altitudeIndex   = std::min(altitudeParam.index + (i % 4) / 2, int(altitudesRad.size() - 1));
1079!
        const int elevationIndex  = std::min(elevationParam.index + i % 2, int(elevationsRad.size() - 1));
1080
1081!
        controlParameters.coefficients[i] = getCoefficients(data,
1082!
                                                            metadata.totalCoefsSingleConfig,
1083
                                                            elevationIndex,
1084
                                                            altitudeIndex,
1085
                                                            visibilityIndex,
1086
                                                            albedoIndex,
1087
                                                            0);
1088
    }
1089!
    controlParameters.interpolationFactor[0] = visibilityParam.factor;
1090!
    controlParameters.interpolationFactor[1] = albedoParam.factor;
1091!
    controlParameters.interpolationFactor[2] = altitudeParam.factor;
1092!
    controlParameters.interpolationFactor[3] = elevationParam.factor;
1093
1094
1095!
    const ControlParameters base = controlParameters;
1096!
    for (size_t channel = 0; channel < count; ++channel) {
1097!
        const double wavelength = wavelengths[channel];
1098!
        if (wavelength < channelStart || wavelength >= channelStart + channels * channelWidth) {
1099!
            values[channel] = 0;
1100!
            continue;
1101
        }
1102!
        const int index = int(floor((wavelength - channelStart) / channelWidth));
1103!
        for (int i = 0; i < 16; ++i)
1104!
            controlParameters.coefficients[i] = base.coefficients[i] + index * metadata.totalCoefsSingleConfig;
1105!
        values[channel] = interpolate<0, 0>(angleParameters, controlParameters, metadata);
1106
    }
1107!
    if (eligible) {
1108!
        auto &entry = cache.entries[cache.next];
1109!
        entry.generation = cacheGeneration;
1110!
        entry.parameters = params;
1111!
        entry.count = count;
1112!
        std::copy_n(wavelengths, count, entry.wavelengths.begin());
1113!
        std::copy_n(values, count, entry.values.begin());
1114!
        cache.next = (cache.next + 1) % cache.entries.size();
1115
    }
1116
}
1117
1118!
double PragueSkyModel::skyRadiance(const Parameters& params, const double wavelength) const {
1119!
    if (!initialized) {
1120!
        throw NotInitializedException();
1121
    }
1122
1123!
	return evaluateModel(params, wavelength, dataRad, metadataRad);
1124
}
1125
1126
1127
/////////////////////////////////////////////////////////////////////////////////////
1128
// Sun radiance
1129
/////////////////////////////////////////////////////////////////////////////////////
1130
1131!
double PragueSkyModel::sunRadiance(const Parameters& params, const double wavelength,
1132
                                   const bool atmosphericAttenuation) const {
1133!
    if (!initialized) {
1134!
        throw NotInitializedException();
1135
    }
1136
1137
    // Ignore wavelengths outside the dataset range.
1138!
    if (wavelength < SUN_RAD_START || wavelength >= SUN_RAD_END) {
1139!
        return 0.0;
1140
    }
1141
1142
    // Return zero for rays not hitting the sun.
1143!
    if (params.gamma > SUN_RADIUS) {
1144!
        return 0.0;
1145
    }
1146
1147
    // Compute index into the sun radiance table.
1148!
    const double idx = (wavelength - SUN_RAD_START) / SUN_RAD_STEP;
1149
    assert(idx >= 0 && idx < std::size(SUN_RAD_TABLE) - 1);
1150!
    const int    idxInt   = int(floor(idx));
1151!
    const double idxFloat = idx - floor(idx);
1152
1153
    // Interpolate between the two closest values in the sun radiance table.
1154!
    const double sunRadiance =
1155!
        SUN_RAD_TABLE[idxInt] * (1.0 - idxFloat) + SUN_RAD_TABLE[idxInt + 1] * idxFloat;
1156
    assert(sunRadiance > 0.0);
1157
1158
    // skymodelr: retain the intrinsic spectrum for unattenuated textured disks.
1159!
    if (!atmosphericAttenuation) return sunRadiance;
1160
1161
    // Compute transmittance towards the sun.
1162!
    const double tau = PragueSkyModel::transmittance(params, wavelength, std::numeric_limits<double>::max());
1163
    assert(tau >= 0.0 && tau <= 1.0);
1164
1165
    // Combine.
1166!
    return sunRadiance * tau;
1167
}
1168
1169
1170
/////////////////////////////////////////////////////////////////////////////////////
1171
// Polarisation
1172
/////////////////////////////////////////////////////////////////////////////////////
1173
1174!
double PragueSkyModel::polarisation(const Parameters& params, const double wavelength) const {
1175!
    if (!initialized) {
1176!
        throw NotInitializedException();
1177
    }
1178
1179
    // If no polarisation data available
1180!
    if (metadataPol.rank == 0) {
1181!
        throw NoPolarisationException();
1182
    }
1183
1184!
    return -evaluateModel(params, wavelength, dataPol, metadataPol);
1185
}
1186
1187
1188
/////////////////////////////////////////////////////////////////////////////////////
1189
// Transmittance
1190
/////////////////////////////////////////////////////////////////////////////////////
1191
1192!
std::vector<float>::const_iterator PragueSkyModel::getCoefficientsTrans(const int visibility,
1193
                                                                        const int altitude,
1194
                                                                        const int wavelength) const {
1195!
    return dataTransV.cbegin() +
1196!
           ((visibility * altitudesTrans.size() + altitude) * channels + wavelength) * rankTrans;
1197
}
1198
1199!
std::vector<float>::const_iterator PragueSkyModel::getCoefficientsTransBase(const int altitude,
1200
                                                                            const int a,
1201
                                                                            const int d) const {
1202!
    return dataTransU.cbegin() + size_t(altitude) * aDim * dDim * rankTrans +
1203!
           (size_t(d) * aDim + a) * rankTrans;
1204
}
1205
1206
/// Intersects the given ray (assuming rayPosX == 0) with a circle at origin with the given radius.
1207
/// \return In the case the ray intersects the circle, distance to the circle is returned, otherwise the
1208
///         function returns negative number.
1209!
double intersectRayWithCircle2D(const double rayDirX,
1210
                                const double rayDirY,
1211
                                const double rayPosY,
1212
                                const double circleRadius) {
1213
    assert(rayPosY > 0.0);
1214
    assert(circleRadius > 0.0);
1215
1216
    // Compute discriminant
1217!
    const double qA      = rayDirX * rayDirX + rayDirY * rayDirY;
1218!
    const double qB      = 2.0 * rayPosY * rayDirY;
1219!
    const double qC      = rayPosY * rayPosY - circleRadius * circleRadius;
1220!
    double       discrim = qB * qB - 4.0 * qA * qC;
1221
1222
    // No intersection or touch only
1223!
    if (discrim <= 0.0) {
1224!
        return -1.0;
1225
    }
1226
1227!
    discrim = std::sqrt(discrim);
1228
1229
    // Compute distances to both intersections
1230!
    const double d1 = (-qB + discrim) / (2.0 * qA);
1231!
    const double d2 = (-qB - discrim) / (2.0 * qA);
1232
1233
    // Try to take the nearest positive one
1234!
    const double distToIsect = (d1 > 0.0 && d2 > 0.0) ? std::min(d1, d2) : std::max(d1, d2);
1235!
    return distToIsect;
1236
}
1237
1238
/// Auxiliary function for \ref toTransmittanceParams. Computes [altitude, distance] parameters from
1239
/// coordinates of intersection of view ray and ground or atmosphere edge. Note: using floats here instead of
1240
/// doubles will cause banding artifacts.
1241!
std::tuple<double, double> isectToAltitudeDistance(const double isectX, const double isectY) {
1242
    // Distance to the intersection from world origin (not along ray as distToIsect in the calling method).
1243!
    const double isectDist = std::sqrt(isectX * isectX + isectY * isectY);
1244
    assert(isectDist > 0.0);
1245
1246
    // Compute normalized and non-linearly scaled position in the atmosphere
1247!
    double altitude = std::clamp(isectDist - PLANET_RADIUS, 0.0, ATMOSPHERE_WIDTH);
1248!
    altitude        = std::pow(altitude / ATMOSPHERE_WIDTH, 1.0 / 3.0);
1249
    // atan2 preserves sub-metre angular distances. acos(y / length) loses
1250
    // them to rounding (and can jump between zero and a ~0.1 m distance).
1251!
    double distance = std::atan2(std::abs(isectX), isectY) * PLANET_RADIUS;
1252!
    distance        = std::sqrt(distance / DIST_TO_EDGE);
1253!
    distance        = std::sqrt(distance); // Calling twice sqrt, since it is faster than pow(...,0.25)
1254!
    distance        = std::min(1.0, distance);
1255
    assert(0.0 <= altitude && altitude <= 1.0);
1256
    assert(0.0 <= distance && distance <= 1.0);
1257
1258!
    return std::make_tuple(altitude, distance);
1259
}
1260
1261!
PragueSkyModel::InterpolationParameter PragueSkyModel::getInterpolationParameterTrans(const double value,
1262
                                                                                      const int    paramCount,
1263
                                                                                      const int power) const {
1264
    InterpolationParameter param;
1265!
    param.index  = std::min(int(value * paramCount), paramCount - 1);
1266!
    param.factor = 0.0;
1267!
    if (param.index < paramCount - 1) {
1268!
        param.factor =
1269!
            nonlerp(double(param.index) / paramCount, double(param.index + 1) / paramCount, value, power);
1270!
        param.factor = std::clamp(param.factor, 0.0, 1.0);
1271
    }
1272!
    return param;
1273
}
1274
1275!
PragueSkyModel::TransmittanceParameters PragueSkyModel::toTransmittanceParams(const double theta,
1276
                                                                              const double distance,
1277
                                                                              const double altitude) const {
1278
    assert(theta >= 0.0 && theta <= PI);
1279
    assert(distance >= 0.0);
1280
    assert(altitude >= 0.0);
1281
1282!
    const double rayDirX = sin(theta);
1283!
    const double rayDirY = cos(theta);
1284!
    const double rayPosY = PLANET_RADIUS + altitude; // rayPosX == 0
1285
1286!
    constexpr double ATMOSPHERE_EDGE = PLANET_RADIUS + ATMOSPHERE_WIDTH;
1287
1288
    // Find intersection of the ground-to-sun ray with edge of the atmosphere (in 2D)
1289!
    double           distToIsect  = -1.0;
1290!
    constexpr double LOW_ALTITUDE = 0.3;
1291!
    if (altitude < LOW_ALTITUDE) {
1292
        // Special handling of almost zero altitude case to avoid numerical issues.
1293!
        if (theta <= 0.5 * PI) {
1294!
            distToIsect = intersectRayWithCircle2D(rayDirX, rayDirY, rayPosY, ATMOSPHERE_EDGE);
1295
        } else {
1296!
            distToIsect = 0.0;
1297
        }
1298
    } else {
1299!
        distToIsect = intersectRayWithCircle2D(rayDirX, rayDirY, rayPosY, PLANET_RADIUS);
1300!
        if (distToIsect < 0.0) {
1301!
            distToIsect = intersectRayWithCircle2D(rayDirX, rayDirY, rayPosY, ATMOSPHERE_EDGE);
1302
        }
1303
    }
1304
    // The ray should always hit either the edge of the atmosphere or the planet (we are starting inside the
1305
    // atmosphere).
1306
    assert(distToIsect >= 0.0);
1307
1308!
    distToIsect = std::min(distToIsect, distance);
1309
1310
    // Compute intersection coordinates
1311!
    const double isectX = rayDirX * distToIsect;
1312!
    const double isectY = rayDirY * distToIsect + rayPosY;
1313
1314
    // Get the internal [altitude, distance] parameters
1315!
    const auto [altitudeParam, distanceParam] = isectToAltitudeDistance(isectX, isectY);
1316
1317
    // Convert to interpolation parameters
1318
    TransmittanceParameters params;
1319!
    params.altitude = getInterpolationParameterTrans(altitudeParam, aDim, 3);
1320!
    params.distance = getInterpolationParameterTrans(distanceParam, dDim, 4);
1321
1322!
    return params;
1323
}
1324
1325
// Spend memory at initialization to remove repeated rank reconstruction.
1326
// A single-visibility model still accepts transmission queries at other
1327
// visibilities: those retain the original compressed evaluator as a fallback.
1328!
void PragueSkyModel::expandTransmission(double singleVisibility, double maxMiB) {
1329!
    expandedVisibilityFirst = 0;
1330!
    expandedVisibilityCount = int(visibilitiesTrans.size());
1331!
    if (singleVisibility > 0) {
1332!
        auto parameter = getInterpolationParameter(singleVisibility, visibilitiesTrans);
1333!
        expandedVisibilityFirst = parameter.index;
1334!
        expandedVisibilityCount = parameter.factor > 0 ? 2 : 1;
1335
    }
1336
    // Check before multiplying, including when the caller requests no cap.
1337
    // Saturate at the addressable vector size before converting to size_t;
1338
    // fractional budgets round down, and zero disables expansion.
1339!
    size_t limit = std::min(expandedTrans.max_size(),
1340!
                            std::numeric_limits<size_t>::max() / sizeof(double));
1341!
    long double requested = static_cast<long double>(maxMiB) * (1024 * 1024 / sizeof(double));
1342!
    if (requested < static_cast<long double>(limit)) limit = static_cast<size_t>(requested);
1343!
    size_t count = 1;
1344!
    for (size_t dimension : {size_t(expandedVisibilityCount), altitudesTrans.size(),
1345!
                             size_t(channels), size_t(aDim), size_t(dDim)}) {
1346!
        if (!dimension || dimension > limit / count) {
1347!
            expandedVisibilityCount = 0;
1348!
            return;
1349
        }
1350!
        count *= dimension;
1351
    }
1352
    try {
1353!
        expandedTrans.resize(count);
1354!
    } catch (const std::bad_alloc &) {
1355!
        expandedVisibilityCount = 0;
1356!
        return;
1357
    }
1358!
    for (int v = 0; v < expandedVisibilityCount; ++v)
1359!
        for (int h = 0; h < int(altitudesTrans.size()); ++h)
1360!
            for (int c = 0; c < channels; ++c) {
1361!
                auto coefficients = getCoefficientsTrans(v + expandedVisibilityFirst, h, c);
1362!
                for (int d = 0; d < dDim; ++d)
1363!
                    for (int a = 0; a < aDim; ++a) {
1364!
                        auto base = getCoefficientsTransBase(h, a, d);
1365!
                        double value = 0;
1366!
                        for (int r = 0; r < rankTrans; ++r)
1367!
                            value += double(base[r]) * double(coefficients[r]);
1368!
                        size_t offset = (((size_t(v) * altitudesTrans.size() + h) * channels + c) *
1369!
                                         dDim + d) * aDim + a;
1370!
                        expandedTrans[offset] = value;
1371
                    }
1372
            }
1373
}
1374
1375!
double PragueSkyModel::reconstructTrans(const int                     visibilityIndex,
1376
                                        const int                     altitudeIndex,
1377
                                        const TransmittanceParameters transParams,
1378
                                        const int                     channelIndex) const {
1379
    const std::vector<float>::const_iterator coefs =
1380!
        getCoefficientsTrans(visibilityIndex, altitudeIndex, channelIndex);
1381
1382
    // Load transmittance values for bi-linear interpolation
1383!
    std::array<double, 4> transmittance = { 0.0, 0.0, 0.0, 0.0 };
1384!
    int                   index         = 0;
1385!
    for (int a = transParams.altitude.index; a <= transParams.altitude.index + 1; ++a) {
1386!
        if (a < aDim) {
1387!
            for (int d = transParams.distance.index; d <= transParams.distance.index + 1; ++d) {
1388!
                if (d < dDim) {
1389
                    const std::vector<float>::const_iterator baseCoefs =
1390!
                        getCoefficientsTransBase(altitudeIndex, a, d);
1391!
                    if (visibilityIndex >= expandedVisibilityFirst &&
1392!
                        visibilityIndex < expandedVisibilityFirst + expandedVisibilityCount) {
1393!
                        size_t offset = (((size_t(visibilityIndex - expandedVisibilityFirst) *
1394!
                            altitudesTrans.size() + altitudeIndex) * channels + channelIndex) *
1395!
                            dDim + d) * aDim + a;
1396!
                        transmittance[index] = expandedTrans[offset];
1397
                    } else {
1398!
                        for (int i = 0; i < rankTrans; ++i) {
1399
                            // Same accumulation order as the pre-expanded knots.
1400!
                            transmittance[index] += double(baseCoefs[i]) * double(coefs[i]);
1401
                        }
1402
                    }
1403!
                    index++;
1404
                }
1405
            }
1406
        }
1407
    }
1408
1409
    // Perform bi-linear interpolation
1410!
    if (transParams.distance.factor > 0.f) {
1411!
        transmittance[0] = pragueLerp(transmittance[0], transmittance[1], transParams.distance.factor);
1412!
        transmittance[1] = pragueLerp(transmittance[2], transmittance[3], transParams.distance.factor);
1413
    }
1414!
    transmittance[0] = std::max(transmittance[0], 0.0);
1415
1416!
    if (transParams.altitude.factor > 0.f) {
1417!
        transmittance[1] = std::max(transmittance[1], 0.0);
1418!
        transmittance[0] = pragueLerp(transmittance[0], transmittance[1], transParams.altitude.factor);
1419
    }
1420
1421
    assert(transmittance[0] >= 0.0);
1422!
    return transmittance[0];
1423
}
1424
1425!
double PragueSkyModel::interpolateTrans(const int                     visibilityIndex,
1426
                                        const InterpolationParameter  altitudeParam,
1427
                                        const TransmittanceParameters transParams,
1428
                                        const int                     channelIndex) const {
1429
    // Get transmittance for the nearest lower altitude.
1430!
    double trans = reconstructTrans(visibilityIndex, altitudeParam.index, transParams, channelIndex);
1431
1432
    // Interpolate with transmittance for the nearest higher altitude if needed.
1433!
    if (altitudeParam.factor > 0.0) {
1434
        const double transHigh =
1435!
            reconstructTrans(visibilityIndex, altitudeParam.index + 1, transParams, channelIndex);
1436!
        trans = pragueLerp(trans, transHigh, altitudeParam.factor);
1437
    }
1438
1439!
    return trans;
1440
}
1441
1442!
double PragueSkyModel::transmittance(const Parameters& params,
1443
                                     const double      wavelength,
1444
                                     const double      distance) const {
1445
    assert(distance > 0.0);
1446
1447!
    if (!initialized) {
1448!
        throw NotInitializedException();
1449
    }
1450
1451
    // Ignore wavelengths outside the dataset range.
1452!
    if (wavelength < channelStart || wavelength >= (channelStart + channels * channelWidth)) {
1453!
        return 0.0;
1454
    }
1455
    // Don't interpolate wavelengths inside the dataset range.
1456!
    const int channelIndex = int(floor((wavelength - channelStart) / channelWidth));
1457
1458
    // Translate configuration values to indices and interpolation factors.
1459
    const InterpolationParameter visibilityParam =
1460!
        getInterpolationParameter(params.visibility, visibilitiesTrans);
1461!
    const InterpolationParameter altitudeParam = getInterpolationParameter(params.altitude, altitudesTrans);
1462
1463
    // Calculate position in the atmosphere.
1464!
    const TransmittanceParameters transParams = toTransmittanceParams(params.theta, distance, params.altitude);
1465
1466
    // Get transmittance for the nearest lower visibility.
1467!
    double trans = interpolateTrans(visibilityParam.index, altitudeParam, transParams, channelIndex);
1468
1469
    // Interpolate with transmittance for the nearest higher visibility if needed.
1470!
    if (visibilityParam.factor > 0.0) {
1471
        const double transHigh =
1472!
            interpolateTrans(visibilityParam.index + 1, altitudeParam, transParams, channelIndex);
1473
1474!
        trans = pragueLerp(trans, transHigh, visibilityParam.factor);
1475
    }
1476
1477
    // Transmittance is stored as a square root. Needs to be restored here.
1478!
    trans = trans * trans;
1479
    assert(trans >= 0.0 && trans <= 1.0);
1480
1481!
    return trans;
1482
}
1483
1484
// skymodelr: the geometry and interpolation coordinates do not depend on wavelength.
1485!
void PragueSkyModel::transmittanceSpectrum(const Parameters& params, const double* wavelengths,
1486
                                           size_t count, double distance, double* values) const {
1487
    assert(distance > 0.0);
1488!
    if (!initialized) throw NotInitializedException();
1489!
    const auto visibilityParam = getInterpolationParameter(params.visibility, visibilitiesTrans);
1490!
    const auto altitudeParam = getInterpolationParameter(params.altitude, altitudesTrans);
1491!
    const auto transParams = toTransmittanceParams(params.theta, distance, params.altitude);
1492!
    for (size_t channel = 0; channel < count; ++channel) {
1493!
        const double wavelength = wavelengths[channel];
1494!
        if (wavelength < channelStart || wavelength >= channelStart + channels * channelWidth) {
1495!
            values[channel] = 0;
1496!
            continue;
1497
        }
1498!
        const int index = int(floor((wavelength - channelStart) / channelWidth));
1499!
        double trans = interpolateTrans(visibilityParam.index, altitudeParam, transParams, index);
1500!
        if (visibilityParam.factor > 0.0) {
1501!
            const double high = interpolateTrans(visibilityParam.index + 1, altitudeParam, transParams, index);
1502!
            trans = pragueLerp(trans, high, visibilityParam.factor);
1503
        }
1504!
        values[channel] = trans * trans;
1505
    }
1506
}
1507
1508
1509
1510
} // namespace skymodelr_prague
1511
1512
// Export the loaded visibility slice, not a second full dataset. Geometry and
1513
// spectral reconstruction remain independent of renderer-specific RGB weights.
1514!
void skymodelr_prague::PragueSkyModel::exportMetal(skymodelr_prague_gpu_layout &out,
1515
                                                  std::vector<float> &packed) const {
1516!
    if (!initialized) throw NotInitializedException();
1517!
    out = {};
1518
    // The radiance slice can exceed a gigabyte. Reserve its exact packed size
1519
    // once rather than briefly holding two copies during vector growth.
1520!
    size_t count = 0;
1521!
    for (size_t size : {visibilitiesRad.size(), albedosRad.size(), altitudesRad.size(),
1522!
                        elevationsRad.size(), metadataRad.sunBreaks.size(), metadataRad.zenithBreaks.size(),
1523!
                        metadataRad.emphBreaks.size(), altitudesTrans.size(), visibilitiesTrans.size(),
1524!
                        std::size(SUN_RAD_TABLE), dataRad.size(), dataTransU.size(), dataTransV.size()}) {
1525!
        if (size > UINT32_MAX - count)
1526!
            throw std::runtime_error("Prague Metal coefficient buffer exceeds 32-bit addressing.");
1527!
        count += size;
1528
    }
1529!
    packed.reserve(count);
1530!
    auto append = [&](const auto &values) {
1531!
        if (values.size() > UINT32_MAX - packed.size())
1532!
            throw std::runtime_error("Prague Metal coefficient buffer exceeds 32-bit addressing.");
1533!
        skymodelr_prague_gpu_axis axis{uint32_t(packed.size()), uint32_t(values.size())};
1534!
        packed.insert(packed.end(), values.begin(), values.end());
1535!
        return axis;
1536
    };
1537!
    out.visibility=append(visibilitiesRad); out.albedo=append(albedosRad);
1538!
    out.altitude=append(altitudesRad); out.elevation=append(elevationsRad);
1539!
    out.gamma=append(metadataRad.sunBreaks); out.alpha=append(metadataRad.zenithBreaks);
1540!
    out.emphasis=append(metadataRad.emphBreaks);
1541!
    out.trans_altitude=append(altitudesTrans); out.trans_visibility=append(visibilitiesTrans);
1542!
    out.sun=append(std::vector<double>(std::begin(SUN_RAD_TABLE),std::end(SUN_RAD_TABLE)));
1543!
    out.radiance=append(dataRad).offset; out.trans_u=append(dataTransU).offset;
1544!
    out.trans_v=append(dataTransV).offset;
1545!
    out.rank=metadataRad.rank; out.sun_offset=metadataRad.sunOffset; out.sun_stride=metadataRad.sunStride;
1546!
    out.zenith_offset=metadataRad.zenithOffset; out.zenith_stride=metadataRad.zenithStride;
1547!
    out.emphasis_offset=metadataRad.emphOffset; out.config_stride=metadataRad.totalCoefsSingleConfig;
1548!
    out.trans_rank=rankTrans; out.a_dim=aDim; out.d_dim=dDim; out.channels=channels;
1549!
    out.channel_start=channelStart; out.channel_width=channelWidth;
1550
}
1
#include <Rcpp.h>
2
3
#include "CIE1931Data.h"
4
#include "hosek/cie.h"
5
#include "math/units.h"
6
7
#include <algorithm>
8
#include <cctype>
9
#include <cmath>
10
#include <string>
11
1244x
static inline std::string to_lower(std::string value) {
1344x
  std::transform(value.begin(), value.end(), value.begin(),
14264x
                 [](unsigned char c) { return static_cast<char>(std::tolower(c)); });
1544x
  return value;
16
}
17
1820724x
static inline double spd_blackbody(double lambda_nm, double temperature_k) {
1920724x
  const double lambda_m = lambda_nm * 1e-9;
2020724x
  const double c2 = 1.4387769e-2; // hc/k
2120724x
  const double expo = c2 / (lambda_m * temperature_k);
2220724x
  const double denom = std::exp(expo) - 1.0;
2320724x
  if (!std::isfinite(denom) || denom <= 0.0) {
24!
    return 0.0;
25
  }
2620724x
  return 1.0 / (std::pow(lambda_m, 5.0) * denom);
27
}
28
29!
static inline double spd_d65(double lambda_nm) {
30!
  constexpr double x_d = 0.31271;
31!
  constexpr double y_d = 0.32902;
32!
  const double denom = 0.0241 + 0.2562 * x_d - 0.7341 * y_d;
33!
  const double m1 = (-1.3515 - 1.7703 * x_d + 5.9114 * y_d) / denom;
34!
  const double m2 = (0.03 - 31.4424 * x_d + 30.0717 * y_d) / denom;
35!
  const auto &s0 = S0_function();
36!
  const auto &s1 = S1_function();
37!
  const auto &s2 = S2_function();
38!
  const auto wl = lambda_nm * nm;
39!
  const double s0_val = s0(wl)();
40!
  const double s1_val = s1(wl)();
41!
  const double s2_val = s2(wl)();
42!
  return s0_val + m1 * s1_val + m2 * s2_val;
43
}
44
45
// [[Rcpp::export]]
4646x
Rcpp::List cie_1931_2deg_rcpp() {
4746x
  Rcpp::NumericVector lambda_nm(CIE_N);
4846x
  Rcpp::NumericVector x_bar(CIE_N);
4946x
  Rcpp::NumericVector y_bar(CIE_N);
5046x
  Rcpp::NumericVector z_bar(CIE_N);
5121712x
  for (int i = 0; i < CIE_N; ++i) {
5221666x
    lambda_nm[i] = cie_lambda_nm[i];
5321666x
    x_bar[i] = cie_xbar[i];
5421666x
    y_bar[i] = cie_ybar[i];
5521666x
    z_bar[i] = cie_zbar[i];
56
  }
57
  return Rcpp::List::create(
5892x
    Rcpp::Named("lambda_nm") = lambda_nm,
5992x
    Rcpp::Named("x_bar") = x_bar,
6092x
    Rcpp::Named("y_bar") = y_bar,
6192x
    Rcpp::Named("z_bar") = z_bar
62
  );
63
}
64
65
// [[Rcpp::export]]
6644x
Rcpp::NumericVector spd_values_rcpp(Rcpp::NumericVector lambda_nm,
67
                                    std::string spd_type = "D65") {
6844x
  const std::string key = to_lower(spd_type);
6944x
  Rcpp::NumericVector spd(lambda_nm.size());
7044x
  if (key == "d65") {
71!
    for (R_xlen_t i = 0; i < lambda_nm.size(); ++i) {
72!
      spd[i] = spd_d65(lambda_nm[i]);
73
    }
7444x
  } else if (key == "bb5778") {
7520768x
    for (R_xlen_t i = 0; i < lambda_nm.size(); ++i) {
7620724x
      spd[i] = spd_blackbody(lambda_nm[i], 5778.0);
77
    }
78
  } else {
79!
    Rcpp::stop("Unknown spd_type \"%s\"", spd_type.c_str());
80
  }
8144x
  return spd;
82
}
1
// [[Rcpp::plugins(cpp17)]]
2
#include <Rcpp.h>
3
#include <RcppThread.h>
4
#include <algorithm>
5
#include <mutex>
6
#include <cmath>
7
#include <vector>
8
9
#include "CIE1931Data.h"
10
11
// Photometric illuminance (lux) from V-band magnitude.
124573x
inline double mag_to_illuminance_lux(double Vmagnitude,
13
                                     double zeroPoint = 1.0) {
144573x
  return zeroPoint * std::pow(10.0, (-14.18 - Vmagnitude)/2.5);
15
}
16
174557x
static inline double bv_to_temperature_K(double bv) {
184557x
  if (!std::isfinite(bv)) return 5778.0;
194557x
  const double bv_clamped = std::clamp(bv, -0.4, 2.0);
204557x
  const double t = 4600.0 * (1.0 / (0.92 * bv_clamped + 1.7) +
214557x
                             1.0 / (0.92 * bv_clamped + 0.62));
224557x
  return std::clamp(t, 1000.0, 40000.0);
23
}
24
252153883x
static inline double blackbody_spd(double lambda_nm, double temperature_k) {
262153883x
  const double lambda_m = lambda_nm * 1e-9;
272153883x
  const double c2 = 1.4387769e-2; // hc/k
282153883x
  const double expo = c2 / (lambda_m * temperature_k);
292153883x
  const double denom = std::exp(expo) - 1.0;
302153883x
  if (!std::isfinite(denom) || denom <= 0.0) return 0.0;
312153883x
  return 1.0 / (std::pow(lambda_m, 5.0) * denom);
32
}
33
344573x
static inline const std::vector<double>& cie_weights() {
354573x
  static std::vector<double> weights;
364573x
  if (!weights.empty()) return weights;
371x
  weights.resize(CIE_N, 0.0);
38472x
  for (int i = 0; i < CIE_N; ++i) {
39471x
    if (i == 0) {
401x
      weights[i] = (cie_lambda_nm[i + 1] - cie_lambda_nm[i]) / 2.0;
41470x
    } else if (i == CIE_N - 1) {
421x
      weights[i] = (cie_lambda_nm[i] - cie_lambda_nm[i - 1]) / 2.0;
43
    } else {
44469x
      weights[i] = (cie_lambda_nm[i + 1] - cie_lambda_nm[i - 1]) / 2.0;
45
    }
46
  }
471x
  return weights;
48
}
49
504573x
static inline void xyz_to_srgb(double X, double Y, double Z,
51
                               double& R, double& G, double& B) {
52
  const double M[9] = {
53
     3.2404542, -1.5371385, -0.4985314,
54
    -0.9692660,  1.8760108,  0.0415560,
55
     0.0556434, -0.2040259,  1.0572252
56
  };
574573x
  R = M[0]*X + M[1]*Y + M[2]*Z;
584573x
  G = M[3]*X + M[4]*Y + M[5]*Z;
594573x
  B = M[6]*X + M[7]*Y + M[8]*Z;
60
}
61
624573x
static inline void blackbody_rgb_unit(double temperature_k,
63
                                      double& K_eff,
64
                                      double& R, double& G, double& B) {
654573x
  const auto& w = cie_weights();
664573x
  double sum_spd = 0.0;
674573x
  double sum_v = 0.0;
684573x
  double X = 0.0;
694573x
  double Y = 0.0;
704573x
  double Z = 0.0;
712158456x
  for (int i = 0; i < CIE_N; ++i) {
722153883x
    const double spd = blackbody_spd(cie_lambda_nm[i], temperature_k);
732153883x
    const double wi = w[i];
742153883x
    sum_spd += spd * wi;
752153883x
    sum_v += spd * cie_ybar[i] * wi;
762153883x
    X += spd * cie_xbar[i] * wi;
772153883x
    Y += spd * cie_ybar[i] * wi;
782153883x
    Z += spd * cie_zbar[i] * wi;
79
  }
804573x
  if (sum_spd > 0.0 && std::isfinite(sum_spd)) {
814573x
    K_eff = 683.0 * sum_v / sum_spd;
82
  } else {
83!
    K_eff = 0.0;
84
  }
854573x
  xyz_to_srgb(X, Y, Z, R, G, B);
864573x
  if (!std::isfinite(R) || !std::isfinite(G) || !std::isfinite(B)) {
87!
    R = 0.0;
88!
    G = 0.0;
89!
    B = 0.0;
90
  }
914573x
  R = std::max(R, 0.0);
924573x
  G = std::max(G, 0.0);
934573x
  B = std::max(B, 0.0);
944573x
  const double sum_rgb = R + G + B;
954573x
  if (sum_rgb > 0.0 && std::isfinite(sum_rgb)) {
964573x
    R /= sum_rgb;
974573x
    G /= sum_rgb;
984573x
    B /= sum_rgb;
99
  } else {
100!
    R = G = B = 1.0 / 3.0;
101
  }
102
}
103
104
105114325x
static inline int wrap_col(int x, int W) {
106114325x
  int r = x % W; return r < 0 ? r + W : r;
107
}
108
1093x
static inline double jd_to_gmst(double jd)
110
{
1113x
    double d  = jd - 2451545.0;                  // days since J2000
1123x
    double t  = d / 36525.0;                     // Julian centuries
1133x
    double gmst =
1143x
        280.46061837 + 360.98564736629 * d +
1153x
        0.000387933 * t * t - t * t * t / 38710000.0; // IAU 2006
1163x
    gmst = fmod(gmst, 360.0);
1173x
    if (gmst < 0) gmst += 360.0;
1183x
    return gmst * M_PI / 180.0;                  // rad
119
}
120
121
// [[Rcpp::export]]
1223x
Rcpp::NumericVector make_starfield_rcpp(Rcpp::DataFrame stars,
123
                         unsigned int    resolution = 2048,
124
                         double          zero_point = 1.0,
125
            						 double          lon_deg   = 0.0,
126
            						 double          lat_deg   = 0.0,
127
            						 double          jd        = 2451545.0, // Julian Date of the frame (UTC noon 1 Jan 2000 = 2451545.0)
128
                         double          turbidity = 3.0,
129
            						 double          ozone_du  = 300.0,
130
            						 double          altitude  = 0.0,
131
            						 double          star_width = 1.0,
132
            						 bool            use_rgb   = true,
133
            						 bool            atmosphere_effects = true,
134
            						 bool            upper_hemisphere_only = true,
135
            						 unsigned int    number_cores  = 1)
136
{
1373x
  if (resolution == 0) Rcpp::stop("resolution must be greater than or equal to 1");
1383x
  if(!upper_hemisphere_only & atmosphere_effects) {
139!
    atmosphere_effects = false;
140!
    Rcpp::message(Rcpp::CharacterVector("When rendering full sphere (`upper_hemisphere_only = false`), atmosphere effects are not rendered (setting `atmosphere_effects = false`)"));
141
  }
1423x
  const int nTheta = resolution;        // rows (latitude)
1433x
  const int nPhi   = 2 * resolution;    // cols (longitude)
1443x
  const int nPix   = nTheta * nPhi;
1453x
  const double dtheta = M_PI / double(nTheta);
1463x
  const double dphi   = 2.0 * M_PI / double(nPhi);
147
14822865x
  auto omega_row = [&](int t) {
14922865x
    double theta_c = (double(t) + 0.5) * dtheta;
15022865x
    double s = std::sin(theta_c);
15122865x
    if (s < 1e-8) s = 1e-8;
15222865x
    return dtheta * dphi * s;
153
  };
154
1553x
  std::vector<double> img(3 * nPix, 0.0);
156
157
  // pull columns out of the data frame
1586x
  Rcpp::NumericVector ra   = stars["ra_rad"];
1596x
  Rcpp::NumericVector dec  = stars["dec_rad"];
1606x
  Rcpp::NumericVector mag  = stars["v_mag"];
1616x
  Rcpp::NumericVector r_vec  = stars["r"];
1626x
  Rcpp::NumericVector g_vec  = stars["g"];
1636x
  Rcpp::NumericVector b_vec  = stars["b"];
1643x
  const bool has_bv = stars.containsElementNamed("b_v");
1653x
  Rcpp::NumericVector bv_vec;
1663x
  if (has_bv) {
1679x
    bv_vec = stars["b_v"];
168
  }
169
1703x
  const std::size_t   N    = ra.size();
171
1723x
  double psf_fwhm_pix = star_width;
1733x
  double psf_trunc_sigma = 3.0;  // truncate at 3 sigma
174
1753x
	double gmst_rad = jd_to_gmst(jd);
1763x
	double lst_rad  = gmst_rad + lon_deg * M_PI / 180.0;
1773x
	double sin_lat  = std::sin(lat_deg * M_PI / 180.0);
1783x
	double cos_lat  = std::cos(lat_deg * M_PI / 180.0);
1793x
	std::vector<std::mutex> row_locks(nTheta);
180
181
  // parallelise over stars
1823x
  RcppThread::parallelFor(0u, (unsigned)N, [&](unsigned i)
183
    {
1849112x
  		double ha = lst_rad - ra[i];
185
1869112x
  		double sin_alt = std::sin(dec[i]) * sin_lat +
1879112x
                   std::cos(dec[i]) * cos_lat * std::cos(ha);
1889112x
  		double alt_rad = std::asin( std::clamp(sin_alt, -1.0, 1.0) );
1899112x
  		double cos_alt = std::cos(alt_rad);
190
1919112x
  		if(cos_alt < 1e-6) cos_alt = 1e-6;
192
1939112x
  		double sin_az  =  std::cos(dec[i]) * std::sin(ha) / cos_alt;
1949112x
  		double cos_az  = (std::sin(dec[i]) * cos_lat -
1959112x
  						std::cos(dec[i]) * std::cos(ha) * sin_lat) / cos_alt;
196
1979112x
  		double x_h =  -cos_alt *  cos_az;
1989112x
  		double y_h =  sin_alt;
1999112x
  		double z_h =  -cos_alt *  sin_az;
200
201
  		//map to lat/long image
2029112x
  		double theta = std::acos(std::clamp(y_h, -1.0, 1.0));
2039112x
  		double phi   = std::atan2(-z_h, x_h);
2049112x
  		if (phi < 0.0) phi += 2.0 * M_PI;
205
2069112x
  		double phi_img = phi + M_PI;
2079112x
  		if (phi_img >= 2.0 * M_PI) phi_img -= 2.0 * M_PI;
208
2099112x
  		double r = 1.0, g = 1.0, b = 1.0;
2109112x
  		if(use_rgb) {
2119112x
  			r = r_vec[i];
2129112x
  			g = g_vec[i];
2139112x
  			b = b_vec[i];
214
  		}
215
2169112x
  		double T_r = 1.0, T_g = 1.0, T_b = 1.0;
2179112x
  		constexpr double tauR[9] = {0.00835,0.00673,0.00595,0.01750,0.01350,
218
  									0.01100,0.02690,0.02050,0.01880};
2199112x
  		constexpr double tauM0[9]= {0.00220,0.00190,0.00175,0.00300,0.00265,
220
  									0.00245,0.00360,0.00320,0.00310};
2219112x
  		constexpr double tauO[9] = {0.0030,0.0048,0.0060,0.0014,0.0010,
222
  									0.0009,0.0006,0.0007,0.0008};
2239112x
  		if (theta < M_PI_2) {           // above horizon only
224
  			// ---------- airmass m(theta) -----------------------------------------
2254573x
  			double secz = 1.0 / std::max(1e-6, std::cos(theta));
226
  			double m    = secz < 12.0
2274573x
  						? secz - 0.001816*pow(secz-1,1)
2284181x
  						 	   - 0.002875*pow(secz-1,2)
2294181x
  							   - 0.000808*pow(secz-1,3)
2304573x
  						: secz;
231
232
  			// density scale with observer altitude
2334573x
  			double rho = std::exp(-altitude / 8000.0);          // rho/rho0  (simple barometric)
234
235
  			// coefficient scalers
2364573x
  			double kR = rho;                                    // Rayleigh air density
2374573x
  			double kM = rho * (turbidity - 1.0);                // Mie 0 at T=1
2384573x
  			double kO = ozone_du / 300.0;                       // 1.0 at 300 DU
239
240
  			double T_band[9];
24145730x
  			for (int c=0; c<9; ++c) {
24241157x
  				T_band[c] = std::exp( -(kR*tauR[c] + kM*tauM0[c] + kO*tauO[c]) * m );
243
  			}
2444573x
  			T_r = (T_band[0] + T_band[1] + T_band[2]) / 3.0;
2454573x
  			T_g = (T_band[3] + T_band[4] + T_band[5]) / 3.0;
2464573x
  			T_b = (T_band[6] + T_band[7] + T_band[8]) / 3.0;
247
  		} else {
2484539x
			  T_r = T_g = T_b = 0.0;      // star is below horizon
249
  		}
250
2519112x
  		if(!upper_hemisphere_only) {
2522x
  		  T_r = T_g = T_b = 1.0;
253
  		}
254
2559112x
  		if (T_r==0.0 && T_g==0.0 && T_b==0.0) return;
256
257
  		// ----- continuous image coords -----
2584573x
  		double u = (phi_img / (2.0 * M_PI)) * nPhi;    // column in [0, nPhi)
2594573x
  		double v = (theta   / M_PI)         * nTheta;  // row    in [0, nTheta)
260
261
  		// avoid rare u == nPhi or v == nTheta due to floating point
2624573x
  		if (u >= nPhi)   u = std::nextafter((double)nPhi, 0.0);
2634573x
  		if (v >= nTheta) v = std::nextafter((double)nTheta, 0.0);
264
265
  		// subpixel center and integer anchors
2664573x
  		int    p0 = (int)std::floor(u);
2674573x
  		int    t0 = (int)std::floor(v);
268
269
  		// PSF parameters
2704573x
        double sigma = psf_fwhm_pix / 2.355;                   // FWHM -> sigma
2714573x
  		int    rad   = (int)std::ceil(psf_trunc_sigma * sigma);
2724573x
  		double inv_2s2 = 1.0 / (2.0 * sigma * sigma);
273
274
  		// Pre-compute 1D weights using distance from the pixel center (p + 0.5, t + 0.5)
27513719x
  		std::vector<double> wx(2*rad + 1), wy(2*rad + 1);
276
27727438x
  		for (int dx = -rad; dx <= rad; ++dx) {
27822865x
 		  double px_center = (p0 + dx) + 0.5;
27922865x
 		  double ddx = px_center - u;                   // subpixel offset in x
28022865x
 		  double w   = std::exp(-ddx*ddx * inv_2s2);
28122865x
		  wx[dx + rad] = w;
282
  		}
28327438x
  		for (int dy = -rad; dy <= rad; ++dy) {
28422865x
 		  int ty = std::clamp(t0 + dy, 0, nTheta - 1);
28522865x
 		  double py_center = ty + 0.5;
28622865x
 		  double ddy = py_center - v;                   // subpixel offset in y
28722865x
 		  double w   = std::exp(-ddy*ddy * inv_2s2);
28822865x
		  wy[dy + rad] = w;
289
  		}
290
291
  		// Previous norm was image-space only; now include solid angle for env-map consistency
2924573x
  		double norm = 0.0;
29327438x
  		for (int dy = -rad; dy <= rad; ++dy) {
29422865x
  		  int t = std::clamp(t0 + dy, 0, nTheta - 1);
29522865x
  		  double wyj = wy[dy + rad];
29622865x
  		  double omega = omega_row(t);
297137190x
  		  for (int dx = -rad; dx <= rad; ++dx) {
298114325x
  		    double w = wyj * wx[dx + rad];
299114325x
  		    norm += w * omega;
300
  		  }
301
  		}
3024573x
  		if (norm <= 0.0) return;
303
304
  		// Star radiance in channels (radiometric; RGB unit sums to 1)
3054573x
  		double temperature_k = 5778.0;
3064573x
  		if (has_bv && std::isfinite(bv_vec[i])) {
3074557x
  		  temperature_k = bv_to_temperature_K(bv_vec[i]);
308
  		}
3094573x
  		double K_eff = 0.0;
3104573x
  		double r_unit = 0.0, g_unit = 0.0, b_unit = 0.0;
3114573x
  		blackbody_rgb_unit(temperature_k, K_eff, r_unit, g_unit, b_unit);
3124573x
  		if (use_rgb && (!has_bv || !std::isfinite(bv_vec[i]))) {
31316x
  		  const double sum_rgb = r + g + b;
31416x
  		  if (sum_rgb > 0.0 && std::isfinite(sum_rgb)) {
31516x
  		    r_unit = r / sum_rgb;
31616x
  		    g_unit = g / sum_rgb;
31716x
  		    b_unit = b / sum_rgb;
318
  		  }
319
  		}
3204573x
  		if (!use_rgb) {
321!
  		  r_unit = g_unit = b_unit = 1.0 / 3.0;
322
  		}
3234573x
  		if (K_eff <= 0.0 || !std::isfinite(K_eff)) return;
3244573x
  		double E_v = mag_to_illuminance_lux(mag[i], double(zero_point));
3254573x
  		double E_e = E_v / K_eff;
3264573x
  		if (E_e <= 0.0 || !std::isfinite(E_e)) return;
3274573x
  		double R0 = E_e * r_unit * T_r / norm;
3284573x
  		double G0 = E_e * g_unit * T_g / norm;
3294573x
  		double B0 = E_e * b_unit * T_b / norm;
330
331
  		// ----- accumulate with row locks (one lock per affected row) -----
33227438x
  		for (int dy = -rad; dy <= rad; ++dy) {
33322865x
  		  int t = std::clamp(t0 + dy, 0, nTheta - 1);
33422865x
  		  double wyj = wy[dy + rad];
335
336
  		  // lock the row once; update all columns for this row
337
  		  {
33822865x
  		    std::scoped_lock lock(row_locks[t]);
33922865x
  		    std::size_t base = 3ULL * ( (std::size_t)t * (std::size_t)nPhi );
340
341137190x
  		    for (int dx = -rad; dx <= rad; ++dx) {
342114325x
  		      int p = wrap_col(p0 + dx, nPhi);
343114325x
  		      double w = wyj * wx[dx + rad];   // separable Gaussian
344
345114325x
  		      std::size_t idx = base + 3ULL * (std::size_t)p;
346114325x
  		      img[idx    ] += double(w * R0);
347114325x
  		      img[idx + 1] += double(w * G0);
348114325x
  		      img[idx + 2] += double(w * B0);
349
  		    }
350
  		  }
351
  		}
3524573x
    }, number_cores);
353
3543x
    Rcpp::NumericVector result(nPix * 3);
3559x
    result.attr("dim") = Rcpp::IntegerVector::create(nTheta, nPhi, 3);
356
357203x
    for (int t = 0; t < nTheta; ++t) {
35841288x
      for (int p = 0; p < nPhi; ++p) {
35941088x
        const int pix_index = t * nPhi + p;
360164352x
        for (int c = 0; c < 3; ++c) {
361123264x
          const int arr_index = t + nTheta * (p + nPhi * c);
362123264x
          result[arr_index] = img[3 * pix_index + c];
363
        }
364
      }
365
    }
366
3673x
    return result;
368
}