Package 'rayshader'

Title: Create Maps and Visualize Data in 2D and 3D
Description: Uses a combination of raytracing and multiple hill shading methods to produce 2D and 3D data visualizations and maps. Includes water detection and layering functions, programmable color palette generation, several built-in textures for hill shading, 2D and 3D plotting options, a built-in path tracer, 'Wavefront' OBJ file export, and the ability to save 3D visualizations to a 3D printable format.
Authors: Tyler Morgan-Wall [aut, cph, cre] (ORCID: <https://orcid.org/0000-0002-3131-3814>)
Maintainer: Tyler Morgan-Wall <[email protected]>
License: GPL-3
Version: 1.0.0
Built: 2026-11-27 06:01:44 UTC
Source: https://github.com/tylermorganwall/rayshader

Help Index


Add Overlay

Description

Overlays an image (with a transparency layer) on the current map.

Usage

add_overlay(
  hillshade = NULL,
  overlay = NULL,
  alpha_layer = 1,
  alpha_color = NULL,
  alpha_method = "max",
  color_epsilon = 0.001,
  rescale_original = FALSE,
  ...
)

Arguments

hillshade

A three-dimensional RGB array or 2D matrix of shadow intensities.

overlay

A three or four dimensional RGB array, where the 4th dimension represents the alpha (transparency) channel. If the array is 3D, alpha_color should also be passed to indicate transparent regions.

alpha_layer

Default 1. Defines minimum tranparaency of layer. If transparency already exists in overlay, the way add_overlay() combines the two is determined in argument alpha_method.

alpha_color

Default NULL. If overlay is a 3-layer array, this argument tells which color is interpretted as completely transparent.

alpha_method

Default max. Method for dealing with pre-existing transparency with layeralpha. If max, converts all alpha levels higher than layeralpha to the value set in layeralpha. Otherwise, this just sets all transparency to layeralpha.

color_epsilon

Default 1e-3. Tolerance for equality for alpha_color to determine transparency.

rescale_original

Default FALSE. If TRUE, hillshade will be scaled to match the dimensions of overlay (instead of the other way around).

...

Deprecated argument spellings are accepted with a warning and forwarded to their current names.

Value

Hillshade with overlay.

Examples

#Combining base R plotting with rayshader's spherical color mapping and raytracing:
montereybay_spatial |>
  sphere_shade() |>
  add_overlay(height_shade(),alpha_layer = 0.6)  |>
  add_shadow(ray_shade(vertical_exaggeration = 4)) |>
  plot_map()

# Add contours with `generate_contour_overlay()`
montereybay_spatial |>
  height_shade() |>
  add_overlay(generate_contour_overlay(montereybay_spatial))  |>
  add_shadow(ray_shade(vertical_exaggeration = 4)) |>
  plot_map()

Add Shadow

Description

Multiplies a texture array or shadow map by a shadow map.

Usage

add_shadow(
  hillshade,
  shadow_map,
  max_darken = 0.7,
  rescale_original = FALSE,
  ...
)

Arguments

hillshade

A three-dimensional RGB array or 2D matrix of shadow intensities.

shadow_map

A matrix that incidates the intensity of the shadow at that point. 0 is full darkness, 1 is full light.

max_darken

Default 0.7. The lower limit for how much the image will be darkened. 0 is completely black, 1 means the shadow map will have no effect.

rescale_original

Default FALSE. If TRUE, hillshade will be scaled to match the dimensions of shadow_map (instead of the other way around).

...

Deprecated argument spellings are accepted with a warning and forwarded to their current names.

Value

Shaded texture map.

Examples

#First we plot the sphere_shade() hillshade of `montereybay_spatial` with no shadows

montereybay_spatial |>
 sphere_shade(vertical_exaggeration=20) |>
 plot_map()

# Raytrace the elevation map and add shadows to the sphere_shade() hillshade.
montereybay_spatial |>
 sphere_shade(vertical_exaggeration=20) |>
 add_shadow(ray_shade(sun_altitude=20, vertical_exaggeration = 4),max_darken=0.3) |>
 plot_map()

#Increase the intensity of the shadow map with the max_darken argument.
montereybay_spatial |>
 sphere_shade(vertical_exaggeration=20) |>
 add_shadow(ray_shade(sun_altitude=20, vertical_exaggeration = 4),max_darken=0.1) |>
 plot_map()

#Decrease the intensity of the shadow map.
montereybay_spatial |>
 sphere_shade(vertical_exaggeration=20) |>
 add_shadow(ray_shade(sun_altitude=20, vertical_exaggeration = 4),max_darken=0.7) |>
 plot_map()

Add Water

Description

Colors water cells in a shaded map using a matrix or spatial raster mask.

Usage

add_water(hillshade, water_map, color = "imhof1", ...)

Arguments

hillshade

A three-dimensional RGB array.

water_map

A numeric or logical matrix in heightmap orientation, a single-layer terra::SpatRaster or raster::RasterLayer, or a raster file path. Values greater than or equal to 1 (including TRUE) indicate water. Missing values and values below 1 leave the map unchanged. Spatial masks must match the cached terrain's grid, extent, and coordinate reference system when that context is available; masks are not reprojected or resampled.

color

Default imhof1. The water fill color. A hexcode or recognized color string. Also includes built-in colors to match the palettes included in sphere_shade(): (imhof1,imhof2,imhof3,imhof4, desert, bw, and unicorn).

...

Deprecated argument spellings are accepted with a warning and forwarded to their current names.

Value

A three-dimensional RGB array with water cells colored. The result is cached as the current shaded map without changing the cached terrain.

Examples

#Here we even out a portion of the volcano dataset to simulate water:
island_volcano = volcano
island_volcano[island_volcano < mean(island_volcano)] = mean(island_volcano)

#Setting a minimum area avoids classifying small flat areas as water:
island_volcano |>
 sphere_shade(texture="imhof3") |>
 add_water(detect_water(min_area = 400),color="imhof3") |>
 plot_map()

#Color ocean cells directly from the spatial elevation raster:
montereybay_spatial |>
 sphere_shade(texture = "imhof4", vertical_exaggeration = 20) |>
 add_water(montereybay_spatial < 0, color = "imhof4") |>
 plot_map()

Calculate Ambient Occlusion Map

Description

Calculates Ambient Occlusion Shadow Map

Cache fallback messages are disabled by default. Set options(rayshader.verbose_scene_cache = TRUE) to print when cached metadata is reused.

Usage

ambient_shade(
  heightmap,
  angle_breaks = 90 * cospi(seq(5, 85, by = 5)/180),
  sun_breaks = 24,
  max_search = 30,
  multicore = FALSE,
  zscale = 1,
  vertical_exaggeration = 1,
  cache_mask = NULL,
  shadow_cache = NULL,
  progress_bar = interactive(),
  geographic_aspect = TRUE,
  extent = NULL,
  crs = NULL,
  ...
)

Arguments

heightmap

A two-dimensional matrix, where each entry in the matrix is the elevation at that point. All points are assumed to be evenly spaced.

angle_breaks

Default 90*cospi(seq(5, 85,by =5)/180). The angle(s), in degrees, as measured from the horizon from which the light originates.

sun_breaks

Default 24. Number of rays to be sent out in a circle, evenly spaced, around the point being tested.

max_search

Default 30. The maximum horizontal distance that the system should propogate rays to check for surface intersections.

multicore

Default FALSE. If TRUE, multiple cores will be used to compute the shadow matrix. By default, this uses all cores available, unless the user has set options("cores") in which the multicore option will only use that many cores.

zscale

Default 1. The ratio between the x and y spacing (which are assumed to be equal) and the z axis.

vertical_exaggeration

Default 1. One-off multiplier applied to the effective visual relief for this call. Values greater than 1 increase apparent relief and values between 0 and 1 flatten it. This does not update cached zscale metadata.

cache_mask

Default NULL. A matrix of 1 and 0s, indicating which points on which the raytracer will operate.

shadow_cache

Default NULL. The shadow matrix to be updated at the points defined by the argument cache_mask.

progress_bar

Default TRUE if interactive, FALSE otherwise. If FALSE, turns off progress bar.

geographic_aspect

Default TRUE. Correct unequal metric x/y cell spacing using the input extent and CRS.

extent

Default NULL. Spatial extent for a matrix heightmap.

crs

Default NULL. CRS to assign to the input before calculating metric cell spacing.

...

Additional arguments to pass to the makeCluster function when multicore=TRUE. Deprecated argument spellings are accepted with a warning and forwarded to their current names.

Value

Shaded texture map.

Examples

# Here we produce a ambient occlusion map of the `montereybay_spatial` elevation map.
# Increasing vertical exaggeration helps bring out details for landscapes
# that are flat (due to large zscales).
montereybay_spatial |>
 ambient_shade(vertical_exaggeration = 20) |>
 plot_map()

#We can increase the distance to look for surface intersections `max_search`
#and the density of rays sent out around the point `sun_breaks`.
montereybay_spatial |>
 ambient_shade(sun_breaks = 24,max_search = 100, multicore = TRUE,
               vertical_exaggeration = 20) |>
 plot_map()
#Create the Red Relief Image Map (RRIM) technique using a custom texture and ambient_shade(),
#with an addition lambertian layer added with lamb_shade() to improve topographic clarity.
bigmb = resize_spatial(montereybay_spatial, scale=2, method_up="cubic")
bigmb |>
 sphere_shade(texture = create_texture("red","red","red","red","white"),
              vertical_exaggeration = 20) |>
 add_shadow(ambient_shade(max_search = 100, multicore = TRUE,
                          vertical_exaggeration = 20),0) |>
 add_shadow(lamb_shade(),0.5) |>
 plot_map()

Calculate Normal

Description

Calculates the normal unit vector for every point on the grid.

Usage

calculate_normal(
  heightmap,
  zscale = 1,
  progress_bar = FALSE,
  geographic_aspect = TRUE,
  extent = NULL,
  crs = NULL,
  ...
)

Arguments

heightmap

A two-dimensional matrix or spatial raster containing elevation values.

zscale

Default 1. Ratio of horizontal spacing to elevation units.

progress_bar

Default FALSE. If TRUE, turns on progress bar.

geographic_aspect

Default TRUE. Correct unequal metric x/y cell spacing using the input extent and CRS.

extent

Default NULL. Spatial extent for a matrix heightmap.

crs

Default NULL. CRS to assign to the input before calculating metric cell spacing.

...

Deprecated argument spellings are accepted with a warning and forwarded to their current names.

Value

Matrix of light intensities at each point.

Examples

#Here we produce a light intensity map of the `volcano` elevation map.

#Cache the normal vectors of the volcano dataset
volcanocache = calculate_normal(volcano)

#Use the cached vectors to speed up calculation of `sphere_shade()` on a map.
sphere_shade(volcano,normal_vectors = volcanocache) |>
 plot_map()

Cloud Shade

Description

Render shadows from the 3D floating cloud layer on the ground. Use this function to add shadows to the map with the add_shadow() function.

For realistic results, argument should match those passed to render_clouds(). The exception to this is attenuation_coef, which can be used to adjust the darkness of the resulting shadows.

Usage

cloud_shade(
  heightmap,
  start_altitude = 1000,
  end_altitude = 2000,
  sun_altitude = 90,
  sun_angle = 315,
  time = 0,
  cloud_cover = 0.5,
  layers = 10,
  offset_x = 0,
  offset_y = 0,
  scale_x = 1,
  scale_y = 1,
  scale_z = 1,
  frequency = 0.005,
  fractal_levels = 16,
  attenuation_coef = 1,
  seed = 1,
  zscale = 1,
  vertical_exaggeration = 1,
  geographic_aspect = TRUE,
  extent = NULL,
  crs = NULL
)

Arguments

heightmap

A two-dimensional matrix, where each entry in the matrix is the elevation at that point. This is used by render_clouds() to calculate the regions the clouds should be rendered in.

start_altitude

Default 1000. The bottom of the cloud layer.

end_altitude

Default 2000. The top of the cloud layer.

sun_altitude

Default 10. The angle, in degrees (as measured from the horizon) from which the light originates.

sun_angle

Default 315 (NW). The angle, in degrees, around the matrix from which the light originates. Zero degrees is North, increasing clockwise

time

Default 0. Advance this to make the clouds evolve and change in shape.

cloud_cover

Default 0.5. The percentage of cloud cover.

layers

Default 90. The number of layers to render the cloud layer.

offset_x

Default 0. Change this to move the cloud layer sideways.

offset_y

Default 0. Change this to move the cloud layer backwards and forward

scale_x

Default 1. Scale the fractal pattern in the x direction.

scale_y

Default 1. Scale the fractal pattern in the y direction.

scale_z

Default 1. Scale the fractal pattern in the z (altitude) direction. (automatically calculated). Scale the fractal pattern in the z (vertical) direction. s.

frequency

Default 0.005. The base frequency of the noise used to calculate the fractal cloud structure.

fractal_levels

Default 16. The fractal dimension used to calculate the noise. Higher values give more fine structure, but take longer to calculate.

attenuation_coef

Default 1. Amount of attenuation in the cloud (higher numbers give darker shadows). This value is automatically scaled to account for increasing the number of layers.

seed

Default 1. Random seed used to generate clouds.

zscale

Default 1. The ratio between the x and y spacing (which are assumed to be equal) and the z axis. For example, if the elevation levels are in units of 1 meter and the grid values are separated by 10 meters, zscale would be 10.

vertical_exaggeration

Default 1. One-off multiplier applied to the effective visual relief for this call. Values greater than 1 increase apparent relief and values between 0 and 1 flatten it. This does not update cached zscale metadata.

geographic_aspect

Default TRUE. Correct unequal metric x/y cell spacing in the cloud noise and shadow ray march.

extent

Default NULL. Spatial extent for a matrix heightmap.

crs

Default NULL. CRS to assign to the input before calculating metric cell spacing.

Value

A 2D shadow matrix.

Examples

#Render clouds with cloud shadows on the ground
montereybay_spatial  |>
 sphere_shade(vertical_exaggeration = 20)  |>
 add_shadow(cloud_shade(vertical_exaggeration = 4), 0.0) |>
 plot_3d(background="darkred", vertical_exaggeration = 4)
render_camera(theta=-65, phi = 25, zoom = 0.45, fov = 80)
render_clouds()
render_snapshot()
#Adjust the light direction for shadows and increase the attenuation for darker clouds
montereybay_spatial  |>
 sphere_shade(vertical_exaggeration = 20)  |>
 add_shadow(cloud_shade(vertical_exaggeration = 4, sun_altitude=20, attenuation_coef = 3), 0.0) |>
 plot_3d(background="darkred", vertical_exaggeration = 4)
render_camera(theta=-65, phi = 25, zoom = 0.45, fov = 80)
render_clouds()
render_snapshot()

Calculate Constant Color Map

Description

Generates a constant color layer.

Cache fallback messages are disabled by default. Set options(rayshader.verbose_scene_cache = TRUE) to print when cached metadata is reused.

Usage

constant_shade(heightmap, color = "white", alpha = 1)

Arguments

heightmap

A two-dimensional matrix, where each entry in the matrix is the elevation at that point.

color

Default "white". Color for the constant layer, as an R color name, hexadecimal code, rgb(r, g, b) string with channels from 0 to 255, or a numeric RGB vector with intensities between 0 and 1.

alpha

Default 1, the alpha transparency.

Value

RGB array of a single color layer.

Examples

#Shade a red map
montereybay_spatial |>
 constant_shade("red") |>
 add_shadow(lamb_shade(),0) |>
 plot_map()
#Shade a green map
montereybay_spatial |>
 constant_shade("green") |>
 add_shadow(lamb_shade(),0) |>
 plot_map()
#Add a blue tint
montereybay_spatial |>
 height_shade() |>
 add_overlay(constant_shade(color = "dodgerblue", alpha=0.25)) |>
 add_shadow(lamb_shade(vertical_exaggeration = 4),0) |>
 plot_map()
#Use a blank map on which to draw other data
montereybay_spatial |>
 constant_shade() |>
 add_overlay(generate_line_overlay(monterey_roads_sf, linewidth=5, color="black",
                                   width = 1080, height = 1080),
                                   alpha_layer=0.8)  |>
 add_water(detect_water(raster_to_matrix(montereybay_spatial) < 0), "dodgerblue") |>
 plot_map()

Calculate Animation Coordinates from Path

Description

Transforms latitude/longitude/altitude coordinates to the reference system used in render_highquality(), so they can be used to create high quality pathtraced animations by passing the output to the animation_camera_coords argument in render_highquality().

This function converts the path values to rayshader coordinates (by setting return_coords = TRUE in render_path()) and then subtracts out the rgl y-offset, which can be obtained by calling the internal function rayshader:::get_scene_depth().

Usage

convert_path_to_animation_coords(
  lat,
  long = NULL,
  altitude = NULL,
  extent = NULL,
  frames = 360,
  reorder = FALSE,
  reorder_first_index = 1,
  reorder_duplicate_tolerance = 0.1,
  reorder_merge_tolerance = 1,
  simplify_tolerance = 0,
  zscale = 1,
  vertical_exaggeration = 1,
  heightmap = NULL,
  offset = 5,
  type = "bezier",
  offset_look_at = 1,
  constant_step = TRUE,
  curvature_adjust = "none",
  curvature_scale = 30,
  follow_camera = FALSE,
  follow_distance = 100,
  follow_angle = 45,
  follow_rotations = 0,
  follow_fixed = FALSE,
  follow_fixed_offset = c(10, 10, 10),
  distance_units = c("auto", "scene", "meters", "map"),
  damp_motion = FALSE,
  damp_magnitude = 0.1,
  resample_path_evenly = TRUE,
  ...
)

Arguments

lat

Vector of latitudes (or other coordinate in the same coordinate reference system as extent).

long

Vector of longitudes (or other coordinate in the same coordinate reference system as extent).

altitude

Elevation of each point, in units of the elevation matrix (scaled by zscale). If left NULL, this will be just the elevation value at ths surface, offset by offset. If a single value, all data will be rendered at that altitude.

extent

Either an object representing the spatial extent of the scene (either from the raster, terra, sf, or sp packages), a length-4 numeric vector specifying c("xmin", "xmax","ymin","ymax"), or the spatial object (from the previously aforementioned packages) which will be automatically converted to an extent object. If omitted, rayshader will use extent metadata cached by plot_3d() or plot_gg().

frames

Default 360. Total number of animation frames.

reorder

Default TRUE. If TRUE, this will attempt to re-order the rows within an sf object with multiple paths to be one continuous, end-to-end path. This happens in two steps: merging duplicate paths that have end points that match with another object (within reorder_duplicate_tolerance distance), and then merges them (within reorder_merge_tolerance distance) to form a continuous path.

reorder_first_index

Default 1. The index (row) of the sf object in which to begin the reordering process. This merges and reorders paths within reorder_merge_tolerance distance until it cannot merge any more, and then repeats the process in the opposite direction.

reorder_duplicate_tolerance

Default 0.1. Lines that have start and end points (does not matter which) within this tolerance that match a line already processed (order determined by reorder_first_index) will be discarded.

reorder_merge_tolerance

Default 1. Lines that have start points that are within this distance to a previously processed line's end point (order determined by reorder_first_index) will be reordered within the sf object to form a continuous, end-to-end path.

simplify_tolerance

Default 0 (no simplification). If greater than zero, simplifies the path to the tolerance specified. This happens after the data has been merged if reorder = TRUE. If the input data is specified with long-lat coordinates and sf_use_s2() returns TRUE, then the value of simplify_tolerance must be specified in meters.

zscale

Default 1. The ratio between the x and y spacing (which are assumed to be equal) and the z axis in the original heightmap. If omitted, rayshader uses the cached scene value from plot_3d() or plot_gg() when available.

vertical_exaggeration

Default 1. Multiplier applied to the effective visual relief. If omitted, rayshader uses the cached scene value from plot_3d() or plot_gg() when available; pass explicitly to override for this call.

heightmap

Default NULL. Height matrix for the current scene. If omitted, this is taken from the cached scene set by plot_3d() or plot_gg(). Pass explicitly to override the cached value.

offset

Default 5. Offset of the track from the surface, if altitude = NULL.

type

Default cubic. Type of transition between keyframes. Other options are linear, quad, bezier, exp, and manual. manual just returns the values passed in, properly formatted to be passed to render_animation().

offset_look_at

Default 0. Amount to offset the lookat position, either along the path (if constant_step = TRUE) or towards the derivative of the Bezier curve.

constant_step

Default TRUE. This will make the camera travel at a constant speed.

curvature_adjust

Default none. Other options are position, lookat, and both. Whether to slow down the camera at areas of high curvature to prevent fast swings. Only used for curve type = bezier. This does not preserve key frame positions. Note: This feature will likely result in the lookat and position diverging if they do not have similar curvatures at each point. This feature is best used when passing the same set of points to positions and lookats and providing an offset_look_at value, which ensures the curvature will be the same.

curvature_scale

Default 30. Constant dividing factor for curvature. Higher values will subdivide the path more, potentially finding a smoother path, but increasing the calculation time. Only used for curve type = bezier. Increasing this value after a certain point will not increase the quality of the path, but it is scene-dependent.

follow_camera

Default FALSE. If TRUE, this generates a 3rd person view that follows the path specified in lat, long, and altitude. The distance to the camera is specified by follow_distance, and the angle (off the ground) is specified by follow_angle. Make the camera rotate around the point as it moves by setting follow_rotations to a non-zero number. The camera points in the direction of the You can also set the camera to be a fixed distance and angle above the by settings follow_fixed = TRUE and specifying the distance in follow_fixed_offset.

follow_distance

Default 100. Distance for the camera to follow the point when follow_camera = TRUE.

follow_angle

Default 45. Angle (off the ground) of the camera when follow_camera = TRUE.

follow_rotations

Default 0. Number of rotations around the point when follow_camera = TRUE.

follow_fixed

Default FALSE. If TRUE, the camera doesn't look in the direction of the path, but rather sits at a fixed relative location to the path.

follow_fixed_offset

Default c(10,10,10). If follow_fixed = TRUE, the offset from the path to place the camera.

distance_units

Default "auto". Units for offset_look_at, follow_distance, and follow_fixed_offset. "auto" uses metres when spatial distance metadata is cached and scene units otherwise. Other options are "scene", "meters", and "map"; map units require a projected CRS.

damp_motion

Default FALSE. Whether the suppress quick, jerky movements of the camera by linearly interpolating between the current camera position and the goal position. Amount of linear interpolation set in damp_magnitude.

damp_magnitude

Default 0.1. Amount of linear interpolation if damp_motion = TRUE.

resample_path_evenly

Default TRUE. This re-samples points along the path so that the camera moves at a constant speed along the path. This also allows paths with large numbers of points to be used with a smaller number of frames, and improves computation time of the animation path in those instances.

...

Other arguments to pass to rayrender::generate_camera_motion() Deprecated argument spellings are accepted with a warning and forwarded to their current names.

Examples

#Generate a circle in Monterey Bay and fly around on top of it
## Not run: 
tmp = tempdir()

# Recreate your original example but compact, with fewer frames & smaller size.
moss_landing_coord = c(36.806807, -121.793332)
t = seq(0, 2 * pi, length.out = 360) # fewer frames for speed
circle_coords_lat = moss_landing_coord[1] + 0.25 * sin(t)
circle_coords_long = moss_landing_coord[2] + 0.25 * cos(t)

# Minimal 3D render -> frames
montereybay_spatial |>
sphere_shade() |>
plot_3d(
	vertical_exaggeration = 4,
	water = TRUE,
	shadow_color = "#40310a",
	background = "tan",
	theta = 210,
	phi = 22,
	zoom = 0.40,
	fov = 55
)

render_path(
lat = circle_coords_lat,
long = circle_coords_long,
color = "red",
antialias = TRUE,
offset = 500,
linewidth = 2
)

cam = convert_path_to_animation_coords(
lat = circle_coords_lat,
long = circle_coords_long,
type = "bezier",
damp_motion = TRUE,
fovs = 80,
offset = 1000,
frames = length(t)
)

render_highquality(
samples = 4,
animation_camera_coords = cam,
width = 200,
height = 200,
preview = FALSE,
filename = file.path(tmp, "frame"),
use_extruded_paths = TRUE
)

# Assemble frames -> GIF (pkgdown copies from man/figures)
pngs = sprintf("%s/frame%d.png", tmp, seq_along(t))
av::av_encode_video(
pngs,
framerate = 24
)

## End(Not run)

#Now we use a "follow camera" for a third person view:
## Not run: 
follow_cam = convert_path_to_animation_coords(
lat = circle_coords_lat,
long = circle_coords_long,
type = "bezier",
damp_motion = TRUE,
fovs = 80,
follow_camera = TRUE,
offset = 1000,
frames = length(t)
)

render_highquality(
samples = 4,
animation_camera_coords = follow_cam,
width = 200,
height = 200,
preview = FALSE,
filename = file.path(tmp, "frame"),
use_extruded_paths = TRUE
)

# See description for video (if on the documentation website)
pngs = sprintf("%s/frame%d.png", tmp, seq_along(t))
av::av_encode_video(
pngs,
framerate = 24
)

## End(Not run)

Convert rayshader RGL scene to ray_mesh object

Description

Converts the current RGL rayshader scene to a ray_mesh object (see rayvertex package for more information)

Usage

convert_rgl_to_raymesh(
  save_shadow = TRUE,
  water_attenuation = 0,
  water_surface_color = TRUE,
  water_ior = 1.33,
  include_ids = NULL,
  exclude_ids = NULL,
  id_table = NULL
)

Arguments

save_shadow

Default FALSE. If TRUE, this saves a plane with the shadow texture below the model.

water_attenuation

Default 0, no attenuation. Amount that light should be attenuated when traveling through water.

water_surface_color

Default TRUE. Whether the water should have a colored surface or not. This is in contrast to setting a non-zero water attenuation, where the color comes from the attenuation of light in the water itself.

water_ior

Default 1.33. Water index of refraction.

include_ids

Default NULL. Internal use. Optional rgl ids to include when converting.

exclude_ids

Default NULL. Internal use. Optional rgl ids to exclude when converting.

id_table

Default NULL. Internal use. Optional current rgl ID/tag snapshot.

Value

A ray_mesh object

Examples

filename_obj = tempfile(fileext = ".obj")
#Save model of volcano
volcano |>
 sphere_shade() |>
 plot_3d(zscale = 2)

rm_obj = convert_rgl_to_raymesh()

Create Texture

Description

Creates a texture map based on 5 user-supplied colors.

Usage

create_texture(
  light_color,
  shadow_color,
  left_color,
  right_color,
  center_color,
  corner_colors = NULL,
  old_method = FALSE,
  darken = 1,
  ...
)

Arguments

light_color

The main highlight color. Corresponds to the top center of the texture map.

shadow_color

The main shadow color. Corresponds to the bottom center of the texture map. This color represents slopes directed directly opposite to the main highlight color.

left_color

The left fill color. Corresponds to the left center of the texture map. This color represents slopes directed 90 degrees to the left of the main highlight color.

right_color

The right fill color. Corresponds to the right center of the texture map. This color represents slopes directed 90 degrees to the right of the main highlight color.

center_color

The center color. Corresponds to the center of the texture map. This color represents flat areas.

corner_colors

Default NULL. The colors at the corners, in this order: NW, NE, SW, SE. If this vector isn't present (or all corners are specified), the mid-points will just be interpolated from the main colors.

old_method

Default FALSE. Whether to use the original method rayshader used for computing textures, which had non-standard color handling.

darken

Default 1. Amount to darken the colors.

...

Deprecated argument spellings are accepted with a warning and forwarded to their current names.

Examples

#Here is the `imhof1` palette:
create_texture("#fff673","#55967a","#8fb28a","#55967a","#cfe0a9") |>
 plot_map()

#Here is the `unicorn` palette:
create_texture("red","green","blue","yellow","white") |>
 plot_map()

Detect water

Description

Detects bodies of water (of a user-defined minimum size) within an elevation matrix.

Cache fallback messages are disabled by default. Set options(rayshader.verbose_scene_cache = TRUE) to print when cached metadata is reused.

Usage

detect_water(
  heightmap = NULL,
  zscale = 1,
  cutoff = 0.9999999,
  min_area = NULL,
  max_height = NULL,
  normal_vectors = NULL,
  keep_groups = FALSE,
  progress_bar = FALSE,
  geographic_aspect = TRUE,
  extent = NULL,
  crs = NULL,
  ...
)

Arguments

heightmap

Default NULL. A two-dimensional matrix, where each entry in the matrix is the elevation at that point. All grid points are assumed to be evenly spaced. Alternatively, if heightmap is a logical matrix, each entry specifies whether that point is water or not. If omitted, rayshader will use the cached hillshade/scene heightmap.

zscale

Default 1. The ratio between the x and y spacing (which are assumed to be equal) and the z axis. For example, if the elevation levels are in units of 1 meter and the grid values are separated by 10 meters, zscale would be 10. If omitted and a cached or raster-derived zscale is available, rayshader will reuse that value.

cutoff

Default 1-1e-7. The lower limit of the z-component of the unit normal vector to be classified as water.

min_area

Default NULL, equivalent to length(heightmap)/400 after the heightmap is resolved. Minimum area (in grid cells) to be considered a body of water.

max_height

Default NULL. If passed, this number will specify the maximum height a point can be considered to be water.

normal_vectors

Default NULL. Pre-computed array of normal vectors from the calculate_normal() function. Supplying this will speed up water detection.

keep_groups

Default FALSE. If TRUE, the matrix returned will retain the numbered grouping information.

progress_bar

Default FALSE. If TRUE, turns on progress bar.

geographic_aspect

Default TRUE. If TRUE, account for unequal horizontal cell sizes using the supplied or cached spatial metadata.

extent

Default NULL. Spatial extent for a matrix heightmap. If omitted, rayshader uses matching cached metadata when available.

crs

Default NULL. CRS describing the input heightmap. An explicit value overrides embedded metadata on a copy of the input.

...

Deprecated argument spellings are accepted with a warning and forwarded to their current names.

Value

Matrix indicating whether water was detected at that point. 1 indicates water, 0 indicates no water.

Examples

#Here we even out a portion of the volcano dataset to simulate water:
island_volcano = volcano
island_volcano[island_volcano < mean(island_volcano)] = mean(island_volcano)

#Setting a minimum area avoids classifying small flat areas as water:
island_volcano |>
 sphere_shade(texture="imhof3", vertical_exaggeration = 20) |>
 add_water(detect_water(min_area = 400),color="imhof3") |>
 plot_map()

Flag Banner 3D Model

Description

3D obj model of a flag (sans pole), to be used with render_obj(). Use flag_full_obj() to get the complete pole, and flag_banner_obj() and flag_pole_obj() to style them separately.

Usage

flag_banner_obj()

Value

File location of the included flag OBJ file (saved with a .txt extension)

Examples

#Print the location of the flag file
flag_banner_obj()

Flag 3D Model

Description

3D obj model of a flag, to be used with render_obj(). Use flag_full_obj() to get the complete pole, and flag_banner_obj() and flag_pole_obj() to style them separately.

Usage

flag_full_obj()

Value

File location of the included flag OBJ file (saved with a .txt extension)

Examples

#Print the location of the flag file
flag_full_obj()

Flag Pole 3D Model

Description

3D obj model of a flag pole, to be used with render_obj(). Use flag_full_obj() to get the complete pole, and flag_banner_obj() and flag_pole_obj() to style them separately.

Usage

flag_pole_obj()

Value

File location of the included flag OBJ file (saved with a .txt extension)

Examples

#Print the location of the flag file
flag_pole_obj()

Generate Altitude Overlay

Description

Using a hillshade and the height map, generates a semi-transparent hillshade to layer onto an existing map.

Usage

generate_altitude_overlay(
  hillshade,
  heightmap = NULL,
  start_transition,
  end_transition = NULL,
  lower = TRUE,
  relative = FALSE,
  extent = NULL,
  crs = NULL
)

Arguments

hillshade

The hillshade to transition into.

heightmap

Default NULL. A two-dimensional matrix, where each entry in the matrix is the elevation at that point. If omitted, rayshader uses the cached hillshade or scene heightmap.

start_transition

Elevation threshold, or proportion of the height range if relative = TRUE.

end_transition

Default NULL. Elevation threshold, or proportion of the height range if relative = TRUE. By default, this is equal to start_transition.

lower

Default TRUE. If TRUE, the overlay is most opaque at lower elevations. If FALSE, the direction is reversed.

relative

Default FALSE. If TRUE, interpret start_transition and end_transition as proportions of the height range in 0..1.

extent

Default NULL. Spatial extent for a matrix heightmap.

crs

Default NULL. CRS describing the input heightmap. An explicit value overrides embedded metadata on a copy of the input.

Value

4-layer RGB array representing the semi-transparent hillshade.

Examples

#Create a bathymetric hillshade
water_palette = colorRampPalette(c("darkblue", "dodgerblue", "lightblue"))(200)
bathy_hs = height_shade(montereybay_spatial, texture = water_palette)
plot_map(bathy_hs)

#Set everything below 0m to water palette
montereybay_spatial |>
 sphere_shade() |>
 add_overlay(generate_altitude_overlay(bathy_hs, montereybay_spatial, 0, 0))  |>
 add_shadow(ray_shade(vertical_exaggeration = 4),0.3) |>
 plot_map()

#Add snow peaks by setting `lower = FALSE`
snow_palette = "white"
snow_hs = height_shade(montereybay_spatial, texture = snow_palette)

#Set the snow transition region from 500m to 1200m
montereybay_spatial |>
 sphere_shade(texture = "desert") |>
 add_overlay(generate_altitude_overlay(bathy_hs, montereybay_spatial, 0, 0))  |>
 add_overlay(generate_altitude_overlay(snow_hs, montereybay_spatial, 500, 1200, lower=FALSE))  |>
 add_shadow(ambient_shade(vertical_exaggeration = 4,max_search=100),0) |>
 plot_map()

Generate Compass Overlay

Description

This adds the compass

Based on code from "Auxiliary Cartographic Functions in R: North Arrow, Scale Bar, and Label with a Leader Arrow"

Usage

generate_compass_overlay(
  x = 0.85,
  y = 0.15,
  size = 0.05,
  text_size = 1,
  bearing = 0,
  heightmap = NULL,
  width = NA,
  height = NA,
  resolution_multiply = 1,
  color1 = NA,
  color2 = NA,
  text_color = NA,
  border_color = "black",
  border_width = 1,
  compass_type = c("classic", "split_arrow", "triangle_circle", "split_arrow_ring"),
  halo_color = NA,
  halo_expand = 2,
  halo_alpha = 1,
  halo_offset = c(0, 0),
  halo_blur = 0,
  halo_edge_softness = 0.1,
  halo_gap_fill = 2,
  halo_gap_fill_alpha_threshold = 0.25
)

Arguments

x

Default NULL. The horizontal percentage across the map (measured from the bottom-left corner) where the compass is located.

y

Default NULL. The vertical percentage across the map (measured from the bottom-left corner) where the compass is located.

size

Default 0.05. Size of the compass, in percentage of the map size..

text_size

Default 1. Text size.

bearing

Default 0. Angle (in degrees) of north. When omitted, rayshader rotates grid north to true north using cached spatial metadata.

heightmap

Default NULL. The original height map. If omitted, rayshader will reuse the cached heightmap from the active scene or most recent hillshade call.

width

Default NA. Width of the resulting image array. Default the same dimensions as height map.

height

Default NA. Width of the resulting image array. Default the same dimensions as height map.

resolution_multiply

Default 1. If passing in heightmap instead of width/height, amount to increase the resolution of the overlay, which should make lines/polygons finer. Should be combined with add_overlay() with rescale_original = TRUE to ensure those added details are captured in the final map.

color1

Default NA, white except for compass_type == "triangle_circle" . Primary color of the compass.

color2

Default NA, black. Secondary color of the symcompass.

text_color

Default black. Text color.

border_color

Default black. Border color of the scale bar.

border_width

Default 1. Width of the scale bar border.

compass_type

Default "classic". Set to "split_arrow", "triangle_circle", or "split_arrow_ring" to draw simple polygon north arrows that match the styles shown above.

halo_color

Default NA, no halo. If a color is specified, the compass will be surrounded by a halo of this color.

halo_expand

Default 1. Number of pixels to expand the halo.

halo_alpha

Default 1. Transparency of the halo.

halo_offset

Default c(0,0). Horizontal and vertical offset to apply to the halo, in percentage of the image.

halo_blur

Default 1. Amount of blur to apply to the halo. Values greater than 30 won't result in further blurring.

halo_edge_softness

Default 0.1. Width of the softened halo edge transition, in pixels.

halo_gap_fill

Default 2. Maximum alpha gap width, in pixels, to bridge in the halo outline.

halo_gap_fill_alpha_threshold

Default 0.25. Alpha threshold used to protect enclosed interior halo gaps from halo_gap_fill.

Value

Semi-transparent overlay with a compass.

Examples

#Create the water palette
water_palette = colorRampPalette(c("darkblue", "dodgerblue", "lightblue"))(200)
bathy_hs = height_shade(montereybay_spatial, texture = water_palette)

#Generate flat water heightmap
mbay = montereybay_spatial
mbay[mbay < 0] = 0

base_map = mbay |>
 height_shade() |>
 add_overlay(generate_altitude_overlay(bathy_hs, montereybay_spatial, 0, 0))  |>
 add_shadow(lamb_shade(vertical_exaggeration = 4),0.3)

#Plot a compass
base_map |>
 add_overlay(generate_compass_overlay()) |>
 plot_map()

#Change the position to be over the water
base_map |>
 add_overlay(generate_compass_overlay(x = 0.15)) |>
 plot_map()
#Change the type
base_map |>
 add_overlay(generate_compass_overlay(x = 0.15,
                                      compass_type = "split_arrow")) |>
 plot_map()
#Change the type
base_map |>
 add_overlay(generate_compass_overlay(x = 0.15,
                                      compass_type = "split_arrow_ring")) |>
 plot_map()
#Change the type
base_map |>
 add_overlay(generate_compass_overlay(x = 0.15,
                                      compass_type = "triangle_circle")) |>
 plot_map()
#Change the text color for visibility
base_map |>
 add_overlay(generate_compass_overlay(compass_type = "split_arrow",
x = 0.15, text_color="white")) |>
 plot_map()
#Alternatively, add a halo color to improve contrast
base_map |>
 add_overlay(generate_compass_overlay(x = 0.15, y=0.15,
             compass_type = "split_arrow", halo_color="white", halo_expand = 2)) |>
 plot_map()
#Change the color scheme
base_map |>
 add_overlay(generate_compass_overlay(x = 0.15, y=0.15,
             compass_type = "split_arrow", halo_color="white",
             halo_expand = 2, color1 = "purple", color2 = "red")) |>
 plot_map()
#Remove the inner border
base_map |>
 add_overlay(generate_compass_overlay(x = 0.15, y=0.15,
             border_color=NA,compass_type = "split_arrow",
             halo_color="white", halo_expand = 2,
             color1 = "darkolivegreen4", color2 = "burlywood3")) |>
 plot_map()
#Change the size of the compass and text
base_map |>
 add_overlay(generate_compass_overlay(x = 0.75, y=0.75,
             halo_color="white", halo_expand = 2,compass_type = "classic",
             size=0.075*2, text_size = 1.25)) |>
 add_overlay(generate_compass_overlay(x = 0.45, y=0.45,
             halo_color="white", halo_expand = 2,compass_type = "split_arrow_ring",
             size=0.075)) |>
 add_overlay(generate_compass_overlay(x = 0.15, y=0.15,
             halo_color="white", halo_expand = 2,compass_type = "split_arrow",
             size=0.075/2, text_size = 0.75)) |>
 plot_map()
#Change the bearing of the compass
base_map |>
 add_overlay(generate_compass_overlay(x = 0.15, y=0.15,
             halo_color="white", halo_expand = 2, bearing=30, compass_type = "classic",
             size=0.075)) |>
 add_overlay(generate_compass_overlay(x = 0.35, y=0.15,
             halo_color="white", halo_expand = 2, bearing=15, compass_type = "triangle_circle",
             size=0.075)) |>
 add_overlay(generate_compass_overlay(x = 0.15, y=0.35,
             halo_color="white", halo_expand = 2, bearing=-45, compass_type = "split_arrow_ring",
             size=0.075)) |>
 plot_map()
#Create a drop shadow effect
base_map |>
 add_overlay(generate_compass_overlay(x = 0.15, y=0.15,
             text_color="white", halo_alpha=0.7, halo_blur=3,
             halo_color="black", halo_expand = 2, halo_offset = c(0.002,-0.002))) |>
add_overlay(generate_compass_overlay(x = 0.35, y=0.15,
             text_color="white", halo_alpha=0.7, halo_blur=3,
             compass_type = "split_arrow",
             halo_color="black", halo_expand = 2, halo_offset = c(0.002,-0.002))) |>
add_overlay(generate_compass_overlay(x = 0.15, y=0.35,
             text_color="white", halo_alpha=0.2, halo_blur=8,
             compass_type = "split_arrow_ring",
             halo_color="white", halo_expand = 2)) |>
 plot_map()

Generate Contour Overlay

Description

Calculates and returns an overlay of contour lines for the current height map.

Usage

generate_contour_overlay(
  heightmap = NULL,
  levels = NA,
  n_levels = NA,
  zscale = 1,
  width = NA,
  height = NA,
  resolution_multiply = 1,
  color = "black",
  linewidth = 1,
  geographic_aspect = TRUE,
  extent = NULL,
  crs = NULL,
  ...
)

Arguments

heightmap

Default NULL. A two-dimensional matrix, where each entry in the matrix is the elevation at that point. If omitted, rayshader uses the cached hillshade or scene heightmap.

levels

Default NA. Automatically generated with 10 levels. This argument specifies the exact height levels of each contour.

n_levels

Default NA. Controls the auto-generation of levels. If levels is length-2, this will automatically generate n_levels breaks between levels[1] and levels[2].

zscale

Default 1. The ratio between the x and y spacing (which are assumed to be equal) and the z axis. For example, if the elevation levels are in units of 1 meter and the grid values are separated by 10 meters, zscale would be 10. If omitted, rayshader uses raster-derived or matching cached metadata.

width

Default NA. Width of the resulting overlay. Default the same dimensions as heightmap.

height

Default NA. Width of the resulting overlay. Default the same dimensions as heightmap.

resolution_multiply

Default 1. If passing in heightmap instead of width/height, amount to increase the resolution of the overlay, which should make lines/polygons finer. Should be combined with add_overlay() with rescale_original = TRUE to ensure those added details are captured in the final map.

color

Default black. Color.

linewidth

Default 1. Line width.

geographic_aspect

Default TRUE. If TRUE, use supplied or cached spatial metadata when deriving the default horizontal scale.

extent

Default NULL. Spatial extent for a matrix heightmap.

crs

Default NULL. CRS describing the input heightmap. An explicit value overrides embedded metadata on a copy of the input.

...

Deprecated argument spellings are accepted with a warning and forwarded to their current names.

Value

Semi-transparent overlay with contours.

Examples

#Add contours to the montereybay_spatial dataset
montereybay_spatial |>
 height_shade() |>
 add_overlay(generate_contour_overlay(montereybay_spatial))  |>
 add_shadow(ray_shade(vertical_exaggeration = 4),0.3) |>
 plot_map()

#Add a different contour color for above and below water, and specify levels manually
water_palette = colorRampPalette(c("darkblue", "dodgerblue", "lightblue"))(200)
bathy_hs = height_shade(montereybay_spatial, texture = water_palette)
monterey_range = range(raster_to_matrix(montereybay_spatial, verbose = FALSE), na.rm = TRUE)
breaks = seq(monterey_range[1], monterey_range[2], length.out=50)
water_breaks = breaks[breaks < 0]
land_breaks = breaks[breaks > 0]

montereybay_spatial |>
 height_shade() |>
 add_overlay(generate_altitude_overlay(bathy_hs, montereybay_spatial, 0, 0))  |>
 add_shadow(ray_shade(vertical_exaggeration = 4),0.3) |>
 add_overlay(generate_contour_overlay(
   montereybay_spatial, levels = water_breaks, color = "white"
 )) |>
 add_overlay(generate_contour_overlay(
   montereybay_spatial, levels = land_breaks, color = "black"
 )) |>
 plot_map()
#Increase the resolution of the contour to improve the appearance of lines
montereybay_spatial |>
 height_shade() |>
 add_overlay(generate_altitude_overlay(bathy_hs, montereybay_spatial, 0, 0))  |>
 add_shadow(ray_shade(vertical_exaggeration = 4),0.3) |>
 add_overlay(generate_contour_overlay(montereybay_spatial, levels = water_breaks, color="white",
                                      height = nrow(montereybay_spatial)*2,
                                      width  = ncol(montereybay_spatial)*2))  |>
 add_overlay(generate_contour_overlay(montereybay_spatial, levels = land_breaks, color="black",
                                      height = nrow(montereybay_spatial)*2,
                                      width  = ncol(montereybay_spatial)*2))  |>
 plot_map()
#Increase the number of breaks and the transparency (via add_overlay)
montereybay_spatial |>
 height_shade() |>
 add_shadow(ray_shade(vertical_exaggeration = 4),0.3) |>
 add_overlay(generate_contour_overlay(montereybay_spatial, linewidth=2, n_levels=100,
                                      height = nrow(montereybay_spatial)*2, color="black",
                                      width  = ncol(montereybay_spatial)*2), alpha_layer=0.5) |>
 plot_map()
#Manually specify the breaks with levels
montereybay_spatial |>
 height_shade() |>
 add_overlay(generate_contour_overlay(
   montereybay_spatial, linewidth = 2, levels = seq(-2000, 0, 100)
 )) |>
 add_shadow(ray_shade(vertical_exaggeration = 4),0.3) |>
 plot_map()

Generate Label Overlay

Description

This uses the car::placeLabel() function to generate labels for the given scene. Either use an sf object or manually specify the x/y coordinates and label.

Usage

generate_label_overlay(
  labels,
  extent = NULL,
  x = NULL,
  y = NULL,
  heightmap = NULL,
  width = NA,
  height = NA,
  resolution_multiply = 1,
  text_size = 1,
  color = "black",
  font = 1,
  pch = 16,
  point_size = 1,
  point_color = NA,
  offset = c(0, 0),
  data_label_column = NULL,
  halo_color = NA,
  halo_expand = 0,
  halo_alpha = 1,
  halo_offset = c(0, 0),
  halo_blur = 0,
  halo_edge_softness = 0.1,
  halo_gap_fill = 2,
  halo_gap_fill_alpha_threshold = 0.25,
  seed = NA
)

Arguments

labels

A character vector of labels, or an sf object with POINT geometry and a column for labels.

extent

Default NULL. Either an object representing the spatial extent of the scene (either from the raster, terra, sf, or sp packages), a length-4 numeric vector specifying c("xmin", "xmax","ymin","ymax"), or the spatial object (from the previously aforementioned packages) which will be automatically converted to an extent object. If omitted, rayshader will infer the extent from heightmap when possible, otherwise reuse cached extent metadata from the active scene or the most recent raster-backed hillshade call.

x

Default NULL. The x-coordinate, if labels is not an sf object.

y

Default NULL. The y-coordinate, if labels is not an sf object.

heightmap

Default NULL. The original height map. Pass this in to extract the dimensions of the resulting overlay automatically. If omitted, rayshader will reuse the cached heightmap from the active scene or the most recent hillshade call.

width

Default NA. Width of the resulting overlay. Default the same dimensions as height map.

height

Default NA. Width of the resulting overlay. Default the same dimensions as height map.

resolution_multiply

Default 1. If passing in heightmap instead of width/height, amount to increase the resolution of the overlay, which should make lines/polygons/text finer. Should be combined with add_overlay() with rescale_original = TRUE to ensure those added details are captured in the final map.

text_size

Default 1. Text size.

color

Default black. Color of the labels.

font

Default 1. An integer which specifies which font to use for text. If possible, device drivers arrange so that 1 corresponds to plain text (the default), 2 to bold face, 3 to italic and 4 to bold italic.

pch

Default 20, solid. Point symbol. 0 = square, 1 = circle, 2 = triangle point up, 3 = plus, 4 = cross, 5 = diamond, 6 = triangle point down, 7 = square cross, 8 = star, 9 = diamond plus, 10 = circle plus, 11 = triangles up and down, 12 = square plus, 13 = circle cross, 14 = square and triangle down, 15 = filled square, 16 = filled circle, 17 = filled triangle point-up, 18 = filled diamond, 19 = solid circle, 20 = bullet (smaller circle), 21 = filled circle blue, 22 = filled square blue, 23 = filled diamond blue, 24 = filled triangle point-up blue, 25 = filled triangle point down blue

point_size

Default 0, no points. Point size.

point_color

Default NA. Colors of the points. Unless otherwise specified, this defaults to color.

offset

Default c(0,0). Horizontal and vertical offset to apply to the label, in units of geometry.

data_label_column

Default NULL. The column in the sf object that contains the labels.

halo_color

Default NA, no halo. If a color is specified, the text label will be surrounded by a halo of this color.

halo_expand

Default 2. Number of pixels to expand the halo.

halo_alpha

Default 1. Transparency of the halo.

halo_offset

Default c(0,0). Horizontal and vertical offset to apply to the halo, in units of geometry.

halo_blur

Default 0. Amount of blur to apply to the halo. Values greater than 30 won't result in further blurring.

halo_edge_softness

Default 0.1. Width of the softened halo edge transition, in pixels.

halo_gap_fill

Default 2. Maximum alpha gap width, in pixels, to bridge in the halo outline.

halo_gap_fill_alpha_threshold

Default 0.25. Alpha threshold used to protect enclosed interior halo gaps from halo_gap_fill.

seed

Default NA, no seed. Random seed for ensuring the consistent placement of labels around points.

Value

Semi-transparent overlay with labels.

Examples

#Add the included `sf` object with roads to the montereybay_spatial dataset
#Create the water palette
water_palette = colorRampPalette(c("darkblue", "dodgerblue", "lightblue"))(200)
bathy_hs = height_shade(montereybay_spatial, texture = water_palette)
#Set label font
par(family = "Arial")

#We're plotting the polygon data here for counties around Monterey Bay. We'll first
#plot the county names at the polygon centroids.
bathy_hs |>
 add_shadow(lamb_shade(vertical_exaggeration = 4),0.3) |>
 add_overlay(generate_polygon_overlay(monterey_counties_sf, palette = rainbow)) |>
 add_overlay(generate_label_overlay(labels=monterey_counties_sf,
                                    color="black", point_size = 1, text_size = 1,
                                    data_label_column = "NAME",
                                    seed=1))  |>
 plot_map()
#It's hard to read these values, so we'll add a white halo.
bathy_hs |>
 add_shadow(lamb_shade(vertical_exaggeration = 4),0.3) |>
 add_overlay(generate_polygon_overlay(monterey_counties_sf, palette = rainbow)) |>
 add_overlay(generate_label_overlay(labels=monterey_counties_sf,
                                    color="black", point_size = 1, text_size = 1,
                                    data_label_column = "NAME",
                                    halo_color = "white", halo_expand = 3,
                                    seed=1))  |>
 plot_map()
#Plot the actual town locations, using the manual plotting interface instead of the `sf` object
montereybay_spatial |>
 height_shade() |>
 add_overlay(generate_altitude_overlay(bathy_hs, montereybay_spatial, 0, 0)) |>
 add_shadow(lamb_shade(vertical_exaggeration = 4),0.3) |>
 add_overlay(generate_label_overlay(labels=as.character(monterey_counties_sf$NAME),
                                    x=as.numeric(as.character(monterey_counties_sf$INTPTLON)),
                                    y=as.numeric(as.character(monterey_counties_sf$INTPTLAT)),
                                    color="black", point_size = 1, text_size = 1,
                                    halo_color = "white", halo_expand = 3,
                                    seed=1))  |>
 plot_map()
#Adding a softer blurred halo
montereybay_spatial |>
 height_shade() |>
 add_overlay(generate_altitude_overlay(bathy_hs, montereybay_spatial, 0, 0)) |>
 add_shadow(lamb_shade(vertical_exaggeration = 4),0.3) |>
 add_overlay(generate_label_overlay(labels=as.character(monterey_counties_sf$NAME),
                                    x=as.numeric(as.character(monterey_counties_sf$INTPTLON)),
                                    y=as.numeric(as.character(monterey_counties_sf$INTPTLAT)),
                                    color="black", point_size = 1, text_size = 1,
                                    halo_color = "white", halo_expand = 3, halo_blur=10,
                                    seed=1))  |>
 plot_map()
#Changing the seed changes the locations of the labels
montereybay_spatial |>
 height_shade() |>
 add_overlay(generate_altitude_overlay(bathy_hs, montereybay_spatial, 0, 0)) |>
 add_shadow(lamb_shade(vertical_exaggeration = 4),0.3) |>
 add_overlay(generate_label_overlay(labels=as.character(monterey_counties_sf$NAME),
                                    x=as.numeric(as.character(monterey_counties_sf$INTPTLON)),
                                    y=as.numeric(as.character(monterey_counties_sf$INTPTLAT)),
                                    color="black", point_size = 1, text_size = 1,
                                    halo_color = "white", halo_expand = 3, halo_blur=10,
                                    seed=2))  |>
 plot_map()

Generate Line Overlay

Description

Calculates and returns an overlay of lines for the current height map.

Usage

generate_line_overlay(
  geometry,
  extent = NULL,
  heightmap = NULL,
  width = NA,
  height = NA,
  resolution_multiply = 1,
  color = "black",
  linewidth = 1,
  lty = 1,
  data_column_width = NULL,
  offset = c(0, 0)
)

Arguments

geometry

An sf object with LINESTRING geometry.

extent

Default NULL. Either an object representing the spatial extent of the scene (either from the raster, terra, sf, or sp packages), a length-4 numeric vector specifying c("xmin", "xmax","ymin","ymax"), or the spatial object (from the previously aforementioned packages) which will be automatically converted to an extent object. If omitted, rayshader will infer the extent from heightmap when possible, otherwise reuse cached extent metadata from the active scene or the most recent raster-backed hillshade call.

heightmap

Default NULL. The original height map. Pass this in to extract the dimensions of the resulting overlay automatically. If omitted, rayshader will reuse the cached heightmap from the active scene or the most recent hillshade call.

width

Default NA. Width of the resulting overlay. Default the same dimensions as height map.

height

Default NA. Width of the resulting overlay. Default the same dimensions as height map.

resolution_multiply

Default 1. If passing in heightmap instead of width/height, amount to increase the resolution of the overlay, which should make lines/polygons/text finer. Should be combined with add_overlay() with rescale_original = TRUE to ensure those added details are captured in the final map.

color

Default black. Color of the lines.

linewidth

Default 1. Line width.

lty

Default 1. Line type. 1 is solid, 2 is dashed, 3 is dotted,4 is dot-dash, 5 is long dash, and 6 is dash-long-dash.

data_column_width

Default NULL. The numeric column to map the width to. The maximum width will be the value specified in linewidth.

offset

Default c(0,0). Horizontal and vertical offset to apply to the line, in units of geometry.

Value

Semi-transparent overlay with contours.

Examples

#Add the included `sf` object with roads to the montereybay_spatial dataset
water_palette = colorRampPalette(c("darkblue", "dodgerblue", "lightblue"))(200)
bathy_hs = height_shade(montereybay_spatial, texture = water_palette)
montereybay_spatial |>
 height_shade() |>
 add_overlay(generate_altitude_overlay(bathy_hs, montereybay_spatial, 0, 0))  |>
 add_overlay(generate_line_overlay(monterey_roads_sf))  |>
 add_shadow(ray_shade(vertical_exaggeration = 4),0.3) |>
 plot_map()
#Change the line width, color, and transparency
montereybay_spatial |>
 height_shade() |>
 add_overlay(generate_altitude_overlay(bathy_hs, montereybay_spatial, 0, 0))  |>
 add_overlay(generate_line_overlay(monterey_roads_sf, linewidth=3, color="white"),
                                   alpha_layer=0.8)  |>
 add_shadow(ray_shade(vertical_exaggeration = 4),0.3) |>
 plot_map()
#Manually specify the width and height to improve visual quality of the lines
montereybay_spatial |>
 height_shade() |>
 add_overlay(generate_altitude_overlay(bathy_hs, montereybay_spatial, 0, 0))  |>
 add_shadow(ray_shade(vertical_exaggeration = 4),0.3) |>
 add_overlay(generate_line_overlay(monterey_roads_sf, linewidth=3, color="white",
                                   width = 1080, height = 1080),
                                   alpha_layer=0.8)  |>
 plot_map()

Generate Point Overlay

Description

Calculates and returns an overlay of points for the current map.

Usage

generate_point_overlay(
  geometry,
  extent = NULL,
  heightmap = NULL,
  width = NA,
  height = NA,
  resolution_multiply = 1,
  pch = 16,
  color = "black",
  size = 1,
  offset = c(0, 0),
  data_column_width = NULL
)

Arguments

geometry

An sf object with POINT geometry.

extent

Default NULL. Either an object representing the spatial extent of the scene (either from the raster, terra, sf, or sp packages), a length-4 numeric vector specifying c("xmin", "xmax","ymin","ymax"), or the spatial object (from the previously aforementioned packages) which will be automatically converted to an extent object. If omitted, rayshader will infer the extent from heightmap when possible, otherwise reuse cached extent metadata from the active scene or the most recent raster-backed hillshade call.

heightmap

Default NULL. The original height map. Pass this in to extract the dimensions of the resulting overlay automatically. If omitted, rayshader will reuse the cached heightmap from the active scene or the most recent hillshade call.

width

Default NA. Width of the resulting overlay. Default the same dimensions as height map.

height

Default NA. Width of the resulting overlay. Default the same dimensions as height map.

resolution_multiply

Default 1. If passing in heightmap instead of width/height, amount to increase the resolution of the overlay, which should make lines/polygons/points finer. Should be combined with add_overlay() with rescale_original = TRUE to ensure those added details are captured in the final map.

pch

Default 16, solid. Point symbol. 0 = square, 1 = circle, 2 = triangle point up, 3 = plus, 4 = cross, 5 = diamond, 6 = triangle point down, 7 = square cross, 8 = star, 9 = diamond plus, 10 = circle plus, 11 = triangles up and down, 12 = square plus, 13 = circle cross, 14 = square and triangle down, 15 = filled square, 16 = filled circle, 17 = filled triangle point-up, 18 = filled diamond, 19 = solid circle, 20 = bullet (smaller circle), 21 = filled circle blue, 22 = filled square blue, 23 = filled diamond blue, 24 = filled triangle point-up blue, 25 = filled triangle point down blue

color

Default black. Color of the points.

size

Default 1. Point size.

offset

Default c(0,0). Horizontal and vertical offset to apply to the polygon, in units of geometry.

data_column_width

Default NULL. The numeric column to map the width to. The maximum width will be the value specified in linewidth.

Value

Semi-transparent overlay with contours.

Examples

#Add the included `sf` object with roads to the montereybay_spatial dataset
monterey_city = sf::st_sfc(sf::st_point(c(-121.893611, 36.603056)))
sf::st_crs(monterey_city) = sf::st_crs(montereybay_spatial)
montereybay_spatial |>
   height_shade() |>
   add_overlay(generate_point_overlay(monterey_city, color="red", size=2))  |>
   add_shadow(ray_shade(vertical_exaggeration = 4),0.3) |>
   plot_map()

Generate Polygon Overlay

Description

Transforms an input sf object into an image overlay for the current height map.

Usage

generate_polygon_overlay(
  geometry,
  extent = NULL,
  heightmap = NULL,
  width = NA,
  height = NA,
  resolution_multiply = 1,
  offset = c(0, 0),
  data_column_fill = NULL,
  line_color = "black",
  palette = "white",
  linewidth = 1,
  ...
)

Arguments

geometry

An sf object with POLYGON geometry.

extent

Default NULL. Either an object representing the spatial extent of the scene (either from the raster, terra, sf, or sp packages), a length-4 numeric vector specifying c("xmin", "xmax","ymin","ymax"), or the spatial object (from the previously aforementioned packages) which will be automatically converted to an extent object. If omitted, rayshader will infer the extent from heightmap when possible, otherwise reuse cached extent metadata from the active scene or the most recent raster-backed hillshade call.

heightmap

Default NULL. The original height map. Pass this in to extract the dimensions of the resulting overlay automatically. If omitted, rayshader will reuse the cached heightmap from the active scene or the most recent hillshade call.

width

Default NA. Width of the resulting overlay. Default the same dimensions as height map.

height

Default NA. Width of the resulting overlay. Default the same dimensions as height map.

resolution_multiply

Default 1. If passing in heightmap instead of width/height, amount to increase the resolution of the overlay, which should make lines/polygons/text finer. Should be combined with add_overlay() with rescale_original = TRUE to ensure those added details are captured in the final map.

offset

Default c(0,0). Horizontal and vertical offset to apply to the polygon, in units of geometry.

data_column_fill

Default NULL. The column to map the polygon fill color to.

line_color

Default black. Color of the lines.

palette

Default black. Single color, named vector color palette, or palette function. If this is a named vector and data_column_fill is not NULL, it will map the colors in the vector to the names. If data_column_fill is a numeric column, this will give a continuous mapping.

linewidth

Default 1. Line width.

...

Deprecated argument spellings are accepted with a warning and forwarded to their current names.

Value

Image overlay representing the input polygon data.

Examples

#Plot the counties around Monterey Bay, CA
generate_polygon_overlay(monterey_counties_sf, palette = rainbow,
                        heightmap = montereybay_spatial) |>
 plot_map()
#These counties include the water, so we'll plot bathymetry data over the polygon
#data to only include parts of the polygon that fall on land.
water_palette = colorRampPalette(c("darkblue", "dodgerblue", "lightblue"))(200)
bathy_hs = height_shade(montereybay_spatial, texture = water_palette)

generate_polygon_overlay(monterey_counties_sf, palette = rainbow) |>
 add_overlay(generate_altitude_overlay(bathy_hs, montereybay_spatial, start_transition = 0)) |>
 plot_map()
#Add a semi-transparent hillshade and change the palette, and remove the polygon lines
montereybay_spatial |>
 sphere_shade(texture = "bw") |>
 add_overlay(generate_polygon_overlay(monterey_counties_sf,
                        palette = terrain.colors, linewidth=NA),
                        alpha_layer=0.7) |>
 add_overlay(generate_altitude_overlay(bathy_hs, montereybay_spatial, start_transition = 0)) |>
 add_shadow(ray_shade(vertical_exaggeration = 4),0) |>
 plot_map()
#Map one of the variables in the sf object and use an explicitly defined color palette
county_palette = c("087" = "red",    "053" = "blue",   "081" = "green",
                  "069" = "yellow", "085" = "orange", "099" = "purple")
montereybay_spatial |>
 sphere_shade(texture = "bw") |>
 add_shadow(ray_shade(vertical_exaggeration = 4),0) |>
 add_overlay(generate_polygon_overlay(monterey_counties_sf, line_color="white", linewidth=3,
                        palette = county_palette, data_column_fill = "COUNTYFP"),
                        alpha_layer=0.7) |>
 add_overlay(generate_altitude_overlay(bathy_hs, montereybay_spatial, start_transition = 0)) |>
 add_shadow(ray_shade(vertical_exaggeration = 4),0.5) |>
 plot_map()

Generate Raster Overlay

Description

Converts a spatial raster into a semi-transparent RGBA overlay for the current rayshader scene. Raster values can be drawn with a single color or mapped through a color palette.

Usage

generate_raster_overlay(
  raster,
  extent = NULL,
  heightmap = NULL,
  width = NA,
  height = NA,
  resolution_multiply = 1,
  palette = "red",
  alpha = 0.5,
  range = NULL,
  resample_method = "bilinear"
)

Arguments

raster

A raster layer. This can be a terra::SpatRaster, a raster::RasterLayer/RasterBrick/RasterStack, or a raster filename.

extent

Default NULL. Either an object representing the spatial extent of the scene (either from the raster, terra, sf, or sp packages), a length-4 numeric vector specifying c("xmin", "xmax","ymin","ymax"), or the spatial object (from the previously aforementioned packages) which will be automatically converted to an extent object. If omitted, rayshader will infer the extent from heightmap when possible, otherwise reuse cached extent metadata from the active scene or the most recent raster-backed hillshade call.

heightmap

Default NULL. The original height map. Pass this in to extract the dimensions of the resulting overlay automatically. If omitted, rayshader will reuse the cached heightmap from the active scene or the most recent hillshade call.

width

Default NA. Width of the resulting overlay. Default the same dimensions as height map.

height

Default NA. Height of the resulting overlay. Default the same dimensions as height map.

resolution_multiply

Default 1. If passing in heightmap instead of width/height, amount to increase the resolution of the overlay. Should be combined with add_overlay() with rescale_original = TRUE to ensure those added details are captured in the final map.

palette

Default "red". Single color, vector of colors, or palette function. A single color draws every finite raster cell with that color. Multiple colors or a palette function map finite raster values continuously from low to high.

alpha

Default 0.5. Alpha multiplier for finite raster cells. Must be between 0 and 1. Alpha values included in palette colors are multiplied by this value.

range

Default NULL. Numeric length-2 range used to map raster values through palette. Values outside this range are clamped. If NULL, the finite value range of the aligned raster is used.

resample_method

Default "bilinear". Method passed to terra::resample() or terra::project() when aligning raster to the scene grid.

Value

4-layer RGBA array representing the raster overlay.

Examples

if (interactive() || identical(Sys.getenv("IN_PKGDOWN"), "true")) {
  # Create a semi-transparent overlay from low elevations:
  low_elevation = montereybay_spatial
  low_elevation[low_elevation > 0] = NA

  montereybay_spatial |>
    height_shade() |>
    add_overlay(generate_raster_overlay(low_elevation, palette = "dodgerblue3")) |>
    plot_map()
}

Generate Scalebar Overlay

Description

This function creates an overlay with a scale bar. By default, the scale bar spans approximately half of the longer map dimension and uses pretty breaks and units derived from the cached spatial metadata. It uses the coordinates of the map (specified by passing an extent) and then creates a scale bar at a specified x/y proportion across the map. If the map is not projected (i.e. is in lat/long coordinates) this function will use the geosphere package to create a scale bar of the proper length.

Usage

generate_scalebar_overlay(
  extent = NULL,
  length = NULL,
  x = 0.05,
  y = 0.05,
  lat_long = NA,
  thickness = NA,
  bearing = NULL,
  unit = NULL,
  flip_ticks = FALSE,
  labels = NA,
  text_size = 1,
  decimals = 0,
  text_offset = 1,
  adj = 0.5,
  heightmap = NULL,
  width = NA,
  height = NA,
  resolution_multiply = 1,
  color1 = "white",
  color2 = "black",
  text_color = "black",
  font = 1,
  border_color = "black",
  tick_color = "black",
  border_width = 1,
  tick_width = 1,
  halo_color = NA,
  halo_expand = 1,
  halo_alpha = 1,
  halo_offset = c(0, 0),
  halo_blur = 0,
  halo_edge_softness = 0.1,
  halo_gap_fill = 2,
  halo_gap_fill_alpha_threshold = 0.25,
  ...
)

Arguments

extent

Default NULL. Either an object representing the spatial extent of the scene (either from the raster, terra, sf, or sp packages), a length-4 numeric vector specifying c("xmin", "xmax","ymin","ymax"), or the spatial object (from the previously aforementioned packages) which will be automatically converted to an extent object. If this is in lat/long coordinates, rayshader will infer that from the spatial metadata when possible. If omitted, rayshader will infer the extent from heightmap when possible, otherwise from the active scene or cached hillshade metadata.

length

Default NULL. Length of the scale bar in unit. If omitted, rayshader derives a pretty length approximately half of the longer map side.

x

Default 0.05. The x-coordinate of the bottom-left corner of the scale bar, as a proportion of the full map width.

y

Default 0.05. The y-coordinate of the bottom-left corner of the scale bar, as a proportion of the full map height.

lat_long

Default NA. If NA, rayshader infers whether the map is in lat/long coordinates from spatial metadata on extent, heightmap, the active scene, or cached hillshade data. Explicit values are only used as a fallback for matrix heightmaps without cached spatial metadata.

thickness

Default NA, automatically computed as 1/20th the length of the scale bar. Width of the scale bar.

bearing

Default NULL. Direction measured clockwise from grid north. If omitted, the scale bar follows the longer map axis.

unit

Default NULL. Distance unit for length and the displayed label. If omitted, rayshader uses metres or kilometres for longitude/latitude scenes, the CRS linear units for projected scenes, and no suffix for raw matrices.

flip_ticks

Default FALSE. Whether to flip the ticks to the other side of the scale bar.

labels

Default NA. Manually specify the three labels with a length-3 character vector. Use this if you want display units other than meters.

text_size

Default 1. Text size.

decimals

Default 0. Number of decimal places for scale bar labels.

text_offset

Default 1. Amount of offset to apply to the text from the scale bar, as a multiple of thickness.

adj

Default 0.5, centered. Text justification. 0 is left-justified, and 1 is right-justified.

heightmap

Default NULL. The original height map. Pass this in to extract the dimensions of the resulting RGB image array automatically.

width

Default NA. Width of the resulting image array. Default the same dimensions as height map.

height

Default NA. Width of the resulting image array. Default the same dimensions as height map.

resolution_multiply

Default 1. If passing in heightmap instead of width/height, amount to increase the resolution of the overlay, which should make lines/polygons/text finer. Should be combined with add_overlay() with rescale_original = TRUE to ensure those added details are captured in the final map.

color1

Default black. Primary color of the scale bar.

color2

Default white. Secondary color of the scale bar.

text_color

Default black. Text color.

font

Default 1. An integer which specifies which font to use for text. If possible, device drivers arrange so that 1 corresponds to plain text (the default), 2 to bold face, 3 to italic and 4 to bold italic.

border_color

Default black. Border color of the scale bar.

tick_color

Default black. Tick color of the scale bar.

border_width

Default 1. Width of the scale bar border.

tick_width

Default 1. Width of the tick.

halo_color

Default NA, no halo. If a color is specified, the text label will be surrounded by a halo of this color.

halo_expand

Default 1. Number of pixels to expand the halo.

halo_alpha

Default 1. Transparency of the halo.

halo_offset

Default c(0,0). Horizontal and vertical offset to apply to the halo, as a proportion of the full scene.

halo_blur

Default 0. Amount of blur to apply to the halo. Values greater than 30 won't result in further blurring.

halo_edge_softness

Default 0.1. Width of the softened halo edge transition, in pixels.

halo_gap_fill

Default 2. Maximum alpha gap width, in pixels, to bridge in the halo outline.

halo_gap_fill_alpha_threshold

Default 0.25. Alpha threshold used to protect enclosed interior halo gaps from halo_gap_fill.

...

Deprecated argument spellings are accepted with a warning and forwarded to their current names.

Value

Semi-transparent overlay with a scale bar.

Examples

#Create the water palette
water_palette = colorRampPalette(c("darkblue", "dodgerblue", "lightblue"))(200)
bathy_hs = height_shade(montereybay_spatial, texture = water_palette)
#Set scalebar font
par(family = "Arial")

#Generate flat water heightmap
mbay = montereybay_spatial
mbay[mbay < 0] = 0

base_map = mbay |>
height_shade() |>
add_overlay(generate_altitude_overlay(bathy_hs, montereybay_spatial, 0, 0))  |>
add_shadow(lamb_shade(vertical_exaggeration = 4),0.3)

#Add a scalebar
base_map |>
add_overlay(generate_scalebar_overlay(length = 40000,
                                      lat_long=TRUE)) |>
plot_map()
#Change the text color
base_map |>
 add_overlay(generate_scalebar_overlay(length = 40000,
                                       text_color = "white",
                                       lat_long=TRUE)) |>
 plot_map()
#Change the length
base_map |>
 add_overlay(generate_scalebar_overlay(length = 30000,
                                       text_color = "white",
                                       lat_long=TRUE)) |>
 plot_map()
#Change the thickness (default is length/20)
base_map |>
 add_overlay(generate_scalebar_overlay(length = 30000,
                                       text_color = "white", thickness = 30000/10,
                                       lat_long=TRUE)) |>
 plot_map()
#Change the text offset (given in multiples of thickness)
base_map |>
 add_overlay(generate_scalebar_overlay(length = 30000,
                                       text_color = "white", thickness = 30000/10,
                                       text_offset = 0.75,
                                       lat_long=TRUE)) |>
 plot_map()
#Change the primary and secondary colors, along with the border and tick color
base_map |>
 add_overlay(generate_scalebar_overlay(length = 30000,
                                       text_color = "white", border_color = "white",
                                       tick_color = "white",
                                       color1 = "darkolivegreen4", color2 = "burlywood3",
                                       lat_long=TRUE)) |>
 plot_map()
#Add a halo
base_map |>
 add_overlay(generate_scalebar_overlay(length = 40000,
                                       halo_color = "white", halo_expand = 1,
                                       font = 2,
                                       lat_long=TRUE)) |>
 plot_map()
#Change the orientation, position, text alignment, and flip the ticks to the other side
base_map |>
 add_overlay(generate_scalebar_overlay(length = 40000, x = 0.07,
                                       bearing=0, adj = 0, flip_ticks = TRUE,
                                       halo_color = "white", halo_expand = 1.5,
                                       font = 2,
                                       lat_long=TRUE)) |>
 plot_map()
#64373.8 meters in 40 miles
#Create custom labels, change font and text size, remove the border/ticks, and change the color
#Here, we specify a width and height to double the resolution of the image (for sharper text)
base_map |>
 add_overlay(generate_scalebar_overlay(length = 64373.8, x = 0.07,
                                       labels = c("0", "20", "40 miles"), thickness=2500,
                                       text_size=3, font = 2, text_offset = 0,
                                       text_color="white", color2="#bf323b", border_color=NA,
                                       tick_color="red", tick_width=0,
                                       bearing=0, adj = 0, flip_ticks = TRUE,
                                       halo_color="black", halo_blur=3, halo_alpha=0.5,
                                       width = ncol(montereybay_spatial)*2,
                                       height = nrow(montereybay_spatial)*2,
                                       lat_long=TRUE), rescale_original=TRUE) |>
 plot_map()

Generate Waterline Overlay

Description

Using a height map or a boolean matrix, generates a semi-transparent waterline overlay to layer onto an existing map. This uses the method described by P. Felzenszwalb & D. Huttenlocher in "Distance Transforms of Sampled Functions" (Theory of Computing, Vol. 8, No. 19, September 2012) to calculate the distance to the coast. This distance matrix can be returned directly by setting the return_distance_matrix argument to TRUE.

Usage

generate_waterline_overlay(
  heightmap = NULL,
  color = "white",
  linewidth = 1,
  boolean = FALSE,
  min = 0.001,
  max = 0.2,
  breaks = 9,
  smooth = 0,
  fade = TRUE,
  alpha_dist = max,
  alpha = 1,
  falloff = 1.3,
  evenly_spaced = FALSE,
  zscale = 1,
  cutoff = 0.9999999,
  width = NA,
  height = NA,
  resolution_multiply = 1,
  min_area = NULL,
  max_height = NULL,
  return_distance_matrix = FALSE,
  geographic_aspect = TRUE,
  extent = NULL,
  crs = NULL
)

Arguments

heightmap

Default NULL. A two-dimensional matrix, where each entry in the matrix is the elevation at that point. If boolean = TRUE, this will instead be interpreted as a logical matrix indicating areas of water. If omitted, rayshader uses the cached hillshade or scene heightmap.

color

Default white. Color of the lines.

linewidth

Default 1. Line width.

boolean

Default FALSE. If TRUE, this is a boolean matrix (0 and 1) indicating contiguous areas in which the lines are generated (instead of a height matrix, from which the boolean matrix is derived using detect_water())

min

Default 0.001. Percent distance (measured from the furthest point from shore) where the waterlines stop.

max

Default 0.2. Percent distance (measured from the furthest point from shore) where the waterlines begin.

breaks

Default 9. Number of water lines.

smooth

Default 0, no smoothing. Increase this to smooth water lines around corners.

fade

Default TRUE. If FALSE, lines will not fade with distance from shore.

alpha_dist

Default to the value specified in max. Percent distance (measured from the furthest point from shore) where the waterlines fade entirely, when fade = TRUE.

alpha

Default 1. Maximum transparency for waterlines. This scales the transparency for all other levels.

falloff

Default 1.3. Multiplicative decrease in distance between each waterline level.

evenly_spaced

Default FALSE. If TRUE, falloff will be ignored and the lines will be evenly spaced.

zscale

Default 1. Base zscale used for water detection when boolean = FALSE. The ratio between the x and y spacing (which are assumed to be equal) and the z axis. For example, if the elevation levels are in units of 1 meter and the grid values are separated by 10 meters, zscale would be 10. If omitted, rayshader uses raster-derived or matching cached metadata.

cutoff

Default 0.999. Arguments passed to detect_water(). Ignored if boolean = TRUE.The lower limit of the z-component of the unit normal vector to be classified as water.

width

Default NA. Width of the resulting image array. Default the same dimensions as height map.

height

Default NA. Width of the resulting image array. Default the same dimensions as height map.

resolution_multiply

Default 1. If passing in heightmap instead of width/height, amount to increase the resolution of the overlay, which should make lines/polygons/text finer. Should be combined with add_overlay() with rescale_original = TRUE to ensure those added details are captured in the final map.

min_area

Default NULL, equivalent to length(heightmap)/400 after the heightmap is resolved. Arguments passed to detect_water(). Ignored if boolean = TRUE. Minimum area (in grid cells) to be considered water.

max_height

Default NULL. Arguments passed to detect_water(). Ignored if boolean = TRUE. If passed, this number will specify the maximum height a point can be considered to be water.

return_distance_matrix

Default FALSE. If TRUE, this function will return the boolean distance matrix instead of contour lines.

geographic_aspect

Default TRUE. If TRUE, use supplied or cached spatial metadata when detecting water and measuring distance from shore.

extent

Default NULL. Spatial extent for a matrix heightmap.

crs

Default NULL. CRS describing the input heightmap. An explicit value overrides embedded metadata on a copy of the input. FALSE, the direction will be reversed.

Value

4-layer RGB array representing the waterline overlay.

Examples

#Create a flat body of water for Monterey Bay
montbay = raster_to_matrix(montereybay_spatial)
montbay[montbay < 0] = 0

#Generate base map with no lines
basemap = montbay |>
  height_shade() |>
  add_water(detect_water(montbay, zscale=200), color="dodgerblue4") |>
  add_shadow(texture_shade(montbay, detail=1/3, brightness = 15, contrast = 5),0) |>
  add_shadow(lamb_shade(montbay, zscale=200, vertical_exaggeration = 4),0)

plot_map(basemap)
#Add waterlines
basemap |>
  add_overlay(generate_waterline_overlay(montbay)) |>
  plot_map()
#Change minimum line distance:
basemap |>
  add_overlay(generate_waterline_overlay(montbay, min = 0.02)) |>
  plot_map()
#Change maximum line distance
basemap |>
  add_overlay(generate_waterline_overlay(montbay, max = 0.4)) |>
  plot_map()
#Smooth waterlines
basemap |>
  add_overlay(generate_waterline_overlay(montbay, max = 0.4, smooth=2)) |>
  plot_map()
#Increase number of breaks
basemap |>
  add_overlay(generate_waterline_overlay(montbay, breaks = 20, max=0.4)) |>
  plot_map()
#Make lines evenly spaced:
basemap |>
  add_overlay(generate_waterline_overlay(montbay, evenly_spaced = TRUE)) |>
  plot_map()
#Change variable distance between each line
basemap |>
  add_overlay(generate_waterline_overlay(montbay, falloff=1.5)) |>
  plot_map()
#Turn off fading
basemap |>
  add_overlay(generate_waterline_overlay(montbay, fade=FALSE)) |>
  plot_map()
#Fill up the entire body of water with lines and make them all 50% transparent
basemap |>
  add_overlay(generate_waterline_overlay(montbay, fade=FALSE, max=1, alpha = 0.5, color="white",
                                         evenly_spaced = TRUE, breaks=50)) |>
  plot_map()

Get Cached Scene Metadata

Description

Returns the spatial and 3D coordinate metadata cached for the active scene created by plot_3d() or plot_gg(). This provides the information needed to transform user data or size procedural geometry to the rendered terrain without reaching into rayshader's internal cache.

The returned extent_3d uses conventional spatial axes: x, y, and elevation z in the cached heightmap's units. For plot_3d() these are the input elevation units; plot_gg() may use a transformed height scale. scene_bounds uses rgl axes: x, vertical y, and horizontal z. Spatial y increases toward negative scene z. To obtain scene y, divide the source elevation by effective_zscale. In a curved scene, also subtract the local drop below the tangent plane at the center of the extent.

Usage

get_scene_metadata(include_heightmap = FALSE)

Arguments

include_heightmap

Default FALSE. Whether to include the cached height matrix in the returned list. The heightmap can be large; its dimensions and elevation range are always returned.

Value

A named list containing:

  • scene_id: The active rgl scene identifier.

  • plot_type: Either "plot_3d" or "plot_gg".

  • extent: The cached x/y extent, or NULL when there is no single extent.

  • extent_3d: The x/y extent plus zmin and zmax elevation bounds.

  • crs: The scene coordinate reference system, when available.

  • zscale, vertical_exaggeration, and effective_zscale: The cached base elevation scale, relief multiplier, and their effective ratio.

  • heightmap_dimensions, elevation_range, and scene_elevation_range: Terrain matrix dimensions and vertical bounds in input and scene units.

  • scene_bounds, scene_center, and scene_dimensions: Terrain bounds, center, and size in rgl x/y/z coordinates.

  • geographic_aspect: Cached horizontal aspect and physical cell metadata.

  • meters_per_scene_unit and map_units_per_scene_unit: Available physical and coordinate-unit conversions for horizontal scene distances.

  • scene_axis_mapping: Mapping from spatial axes to rgl scene axes.

  • earth_curvature: Whether terrain and spatial layers follow Earth's curvature.

  • triangulate: Whether the terrain used mesh simplification.

  • panel_extents and panel_info: Cached plot_gg() panel metadata, when applicable.

  • sources: Labels describing the expressions that populated core cache values.

  • heightmap: The source elevation matrix when include_heightmap = TRUE, otherwise NULL.

Examples

volcano_spatial() |>
  height_shade() |>
  plot_3d()

scene_info = get_scene_metadata()
scene_info$extent_3d
scene_info$scene_bounds

Calculate Haze Overlay

Description

Generates a semi-transparent constant-color overlay whose opacity follows an exponential atmospheric column model.

Usage

haze_shade(
  heightmap,
  color = "white",
  optical_depth = 0.5,
  scale_height = NULL,
  scale_height_relative = FALSE,
  reference_height = NULL,
  alpha = 1,
  blur = 0
)

Arguments

heightmap

A two-dimensional matrix, where each entry in the matrix is the elevation at that point. If omitted, the function attempts to use the cached heightmap from the current rayshader context.

color

Default "white". Color of the haze overlay.

optical_depth

Default 0.5. Optical depth of the haze layer at reference_height. Larger values make haze more opaque at all elevations.

scale_height

Default NULL. Vertical distance over which haze optical depth decreases by a factor of exp(-1). If scale_height_relative = FALSE, this is in the same elevation units as heightmap. If scale_height_relative = TRUE, this is a proportion of the heightmap elevation range and must be in ⁠(0, 1]⁠. If NULL, defaults to 0.2 of the elevation range, or 1 for a flat heightmap.

scale_height_relative

Default FALSE. If TRUE, interpret scale_height as a fraction of the heightmap elevation range rather than as an absolute elevation distance.

reference_height

Default NULL. Elevation where haze optical depth is equal to optical_depth. Elevations above this height have less haze; elevations below this height have more haze. If NULL, uses the minimum finite elevation in heightmap.

alpha

Default 1. Multiplier applied to the final haze alpha. Must be in ⁠[0, 1]⁠.

blur

Default 0. Gaussian standard deviation in output-image pixels. 0 disables convolution. Positive values use a normalized kernel spanning approximately plus or minus three standard deviations.

Details

haze_shade() creates a haze overlay whose alpha channel is largest near reference_height and decreases exponentially with elevation above that height.

The haze opacity is computed as:

height_rel = heightmap - reference_height
log_tau = log(optical_depth) - height_rel / scale_height
haze_alpha = -expm1(-exp(log_tau))

optical_depth controls the haze strength at reference_height. scale_height controls how quickly haze decreases with elevation. After increasing elevation by one scale_height, optical depth is multiplied by exp(-1).

When scale_height = NULL, the automatic scale height depends on the finite elevation range: it is 20 percent of that range for non-flat terrain and one elevation unit for flat terrain. Consequently, subsetting a heightmap or adding an extreme outlier can change the default haze profile.

The final alpha channel is multiplied by alpha and clamped to ⁠[0, 1]⁠.

Value

A 4-layer RGBA array representing the haze overlay.

Examples

# Prepare a mountain heightmap.
mb_mountains = raster_to_matrix(montereybay_spatial)
mb_mountains[mb_mountains < 0] = 0
mb_mountains = mb_mountains[271:540, 271:540]

# Render terrain without haze.
no_haze = mb_mountains |>
  sphere_shade(
    texture = "imhof2",
    zscale = 200,
    vertical_exaggeration = 4
  ) |>
  add_shadow(
    lamb_shade(
      mb_mountains,
      vertical_exaggeration = 4
    ),
    0
  ) |>
  add_water(
    detect_water(mb_mountains, cutoff = 0.9999999),
    "dodgerblue4"
  )

plot_map(no_haze)

# Add default white haze.
no_haze |>
  add_overlay(
    haze_shade(mb_mountains)
  ) |>
  plot_map()

# Increase optical depth to make the haze denser everywhere.
no_haze |>
  add_overlay(
    haze_shade(
      mb_mountains,
      optical_depth = 1
    )
  ) |>
  plot_map()

# Use a smaller scale height (150 meters) to keep haze concentrated in valleys.
no_haze |>
  add_overlay(
    haze_shade(
      mb_mountains,
      optical_depth = 0.7,
      scale_height = 150
    )
  ) |>
  plot_map()

# Express scale height as a fraction of the elevation range.
no_haze |>
  add_overlay(
    haze_shade(
      mb_mountains,
      optical_depth = 0.7,
      scale_height = 0.02,
      scale_height_relative = TRUE
    )
  ) |>
  plot_map()

# Raise the haze layer by setting the reference height.
no_haze |>
  add_overlay(
    haze_shade(
      mb_mountains,
      optical_depth = 0.6,
      reference_height = as.numeric(quantile(mb_mountains, 0.25))
    )
  ) |>
  plot_map()

# Add bluish atmospheric haze.
no_haze |>
  add_overlay(
    haze_shade(
      mb_mountains,
      color = "#abbbca",
      optical_depth = 1
    )
  ) |>
  plot_map()

# Blur the haze alpha map to soften transitions.
no_haze |>
  add_overlay(
    haze_shade(
      mb_mountains,
      optical_depth = 1,
      blur = 2
    )
  ) |>
  plot_map()

Calculate Terrain Color Map

Description

Calculates a color for each point on the surface using a direct elevation-to-color mapping.

Cache fallback messages are disabled by default. Set options(rayshader.verbose_scene_cache = TRUE) to print when cached metadata is reused.

Usage

height_shade(
  heightmap,
  texture = (grDevices::colorRampPalette(c("#6AA85B", "#D9CC9A", "#FFFFFF")))(256),
  range = NULL
)

Arguments

heightmap

A two-dimensional matrix, where each entry in the matrix is the elevation at that point.

texture

Default terrain.colors(256). A color palette for the plot.

range

Default NULL, the full range of the heightmap. A length-2 vector specifying the maximum and minimum values to map the color palette to.

Value

RGB array of hillshaded texture mappings.

Examples

#Create a direct mapping of elevation to color:
montereybay_spatial |>
 height_shade() |>
 plot_map()

# Add lambertian shadows:
montereybay_spatial |>
 height_shade() |>
 add_shadow(lamb_shade(vertical_exaggeration = 6),0) |>
 plot_map()

# Change the palette:
montereybay_spatial |>
 height_shade(texture = topo.colors(256)) |>
 add_shadow(lamb_shade(vertical_exaggeration = 6),0) |>
 plot_map()

#Really change the palette (shield your eyes: gratuitous use of `rainbow()`):
montereybay_spatial |>
 height_shade(texture = rev(rainbow(256))) |>
 add_shadow(lamb_shade(vertical_exaggeration = 6),0) |>
 plot_map()

Calculate Lambert Shading Map

Description

Calculates local shadow map for a elevation matrix by calculating the dot product between light direction and the surface normal vector at that point. Each point's intensity is proportional to the cosine of the normal vector.

Cache fallback messages are disabled by default. Set options(rayshader.verbose_scene_cache = TRUE) to print when cached metadata is reused.

Usage

lamb_shade(
  heightmap,
  sun_altitude = 45,
  sun_angle = 315,
  zscale = 1,
  vertical_exaggeration = 1,
  zero_negative = TRUE,
  geographic_aspect = TRUE,
  extent = NULL,
  crs = NULL,
  ...
)

Arguments

heightmap

A two-dimensional matrix, where each entry in the matrix is the elevation at that point. All points are assumed to be evenly spaced.

sun_altitude

Default 45. The azimuth angle as measured from the horizon from which the light originates.

sun_angle

Default 315 (NW). The angle around the matrix from which the light originates.

zscale

Default 1. The ratio between the x and y spacing (which are assumed to be equal) and the z axis.

vertical_exaggeration

Default 1. One-off multiplier applied to the effective visual relief for this call. Values greater than 1 increase apparent relief and values between 0 and 1 flatten it. This does not update cached zscale metadata.

zero_negative

Default TRUE. Zeros out all values below 0 (corresponding to surfaces facing away from the light source).

geographic_aspect

Default TRUE. Correct unequal metric x/y cell spacing using the input extent and CRS.

extent

Default NULL. Spatial extent for a matrix heightmap.

crs

Default NULL. CRS to assign to the input before calculating metric cell spacing.

...

Deprecated argument spellings are accepted with a warning and forwarded to their current names.

Value

Matrix of light intensities at each point.

Examples

#Generate a basic hillshade
montereybay_spatial |>
 lamb_shade() |>
 plot_map()

#Increase the intensity by decreasing the vertical exaggeration
montereybay_spatial |>
 lamb_shade(vertical_exaggeration = 4) |>
 plot_map()

#Change the sun direction
montereybay_spatial |>
 lamb_shade(sun_angle=45, vertical_exaggeration = 4) |>
 plot_map()

#Change the sun altitude
montereybay_spatial |>
 lamb_shade(sun_altitude=60, vertical_exaggeration = 4) |>
 plot_map()

#Change the sun to directly overhead, the shading here represents the slope angle
montereybay_spatial |>
 lamb_shade(sun_altitude=90, vertical_exaggeration = 8) |>
 plot_map()

California County Data Around Monterey Bay

Description

This dataset is an sf object containing polygon data from the U.S. Department of Commerce with selected geographic and cartographic information from the U.S. Census Bureau's Master Address File / Topologically Integrated Geographic Encoding and Referencing (MAF/TIGER) Database (MTDB). This data has been trimmed to only include 26 features in the extent of the montereybay dataset.

Usage

monterey_counties_sf

Format

An sf object with MULTIPOLYGON geometry.

Source

https://catalog.data.gov/dataset/tiger-line-shapefile-2016-state-california-current-county-subdivision-state-based

Examples

# This is the full code (commented out) used to generate this dataset from the original data:
#counties = sf::st_read("tl_2016_06_cousub.shp")
#monterey_bbox = sf::st_bbox(c(
#  xmin = terra::xmin(montereybay_spatial),
#  ymin = terra::ymin(montereybay_spatial),
#  xmax = terra::xmax(montereybay_spatial),
#  ymax = terra::ymax(montereybay_spatial)
#), crs = sf::st_crs(terra::crs(montereybay_spatial)))
#monterey_counties_sf = sf::st_crop(counties, monterey_bbox)

Road Data Around Monterey Bay

Description

This dataset is an sf object containing line data from the U.S. Department of Commerce with selected roads, TIGER/Line Shapefile, 2015, state, California, Primary and Secondary Roads State-based Shapefile. This data has been trimmed to only include 330 features in the extent of the montereybay dataset.

Usage

monterey_roads_sf

Format

An sf object with LINESTRING geometry.

Source

https://www2.census.gov/geo/tiger/TIGER2015/PRISECROADS/tl_2015_06_prisecroads.zip

Examples

# This is the full code (commented out) used to generate this dataset from the original data:
#counties = sf::st_read("tl_2015_06_prisecroads.shp")
#monterey_bbox = sf::st_bbox(c(
#  xmin = terra::xmin(montereybay_spatial),
#  ymin = terra::ymin(montereybay_spatial),
#  xmax = terra::xmax(montereybay_spatial),
#  ymax = terra::ymax(montereybay_spatial)
#), crs = sf::st_crs(terra::crs(montereybay_spatial)))
#monterey_roads_sf = sf::st_crop(counties, monterey_bbox)

Monterey Bay combined topographic and bathymetric elevation matrix

Description

This dataset is a downsampled matrix version of a combined topographic and bathymetric elevation raster representing the Monterey Bay, CA region. Original data are from the NOAA National Centers for Environmental Information.

Usage

montereybay

Format

A matrix with 540 rows and 540 columns. Elevation values are in NAVD88 meters. Spatial extent and CRS metadata are stored in the "extent" and "crs" attributes, and the "rayshader_data" attribute is TRUE.

Source

https://www.ncei.noaa.gov/metadata/geoportal/rest/metadata/item/gov.noaa.ngdc.mgg.dem:3544/html

Examples

# This is the full code (commented out) used to generate this dataset from
# the original NOAA data:
#montbay = terra::rast("~/Downloads/monterey_13_navd88_2012.nc")
#bottom_left = c(y = -122.366765, x = 36.179392)
#top_right   = c(y = -121.366765, x = 37.179392)
#extent_latlong = sp::SpatialPoints(rbind(bottom_left, top_right),
#                 proj4string=sp::CRS("+proj=longlat +ellps=WGS84 +datum=WGS84"))
#monterey_cropped = terra::crop(montbay, extent_latlong)
#montereybay_raster = terra::aggregate(monterey_cropped, 20)
#montereybay = raster_to_matrix(montereybay_raster)

Monterey Bay spatial elevation raster

Description

A spatial DEM constructed from montereybay when rayshader is loaded. It contains the same elevation values as the matrix and supplies its extent and CRS metadata directly to spatial operations.

Usage

montereybay_spatial

Format

A one-layer terra::SpatRaster with 540 rows and 540 columns. Elevation values are in NAVD88 meters. The raster uses a WGS84 longitude and latitude CRS (EPSG:4326), has approximately 0.001851852 degree cell spacing, and covers approximately -122.366806 to -121.366806 longitude and 36.179398 to 37.179398 latitude.

Source

https://www.ncei.noaa.gov/metadata/geoportal/rest/metadata/item/gov.noaa.ngdc.mgg.dem:3544/html


Plot 3D

Description

Displays the shaded map in 3D with the rgl package.

Cache fallback messages are disabled by default. Set options(rayshader.verbose_scene_cache = TRUE) to print when cached metadata is reused.

plot_3d() checks the map texture dimensions against options(rayshader.max_texture_size = 4096) and downsamples the temporary rgl texture with rayimage::render_resized() if either dimension exceeds that value. The full-resolution source texture is preserved for render_highquality() and other rayrender conversion paths. This is a conservative OpenGL texture-size guard; set the option to a larger value if your system supports larger textures, or to Inf/FALSE to disable the check.

Note: Calling plot_3d() resets the scene cache for the render_snapshot(), render_depth(), and render_highquality()

Usage

plot_3d(
  hillshade,
  heightmap,
  zscale = 1,
  vertical_exaggeration = 1,
  base_shape = "rectangle",
  solid = TRUE,
  solid_depth = "auto",
  solid_color = "grey20",
  solid_line_color = "grey30",
  shadow = TRUE,
  shadow_depth = "auto",
  shadow_color = "auto",
  shadow_darkness = 0.5,
  shadow_width = "auto",
  shadow_texture_size = getOption("rayshader.max_shadow_texture_size", 1024),
  water = FALSE,
  water_input = 0,
  water_color = "dodgerblue",
  water_alpha = 0.5,
  water_line_color = NULL,
  water_line_alpha = 1,
  linewidth = 2,
  line_antialias = FALSE,
  water_render_method = c("polygon", "raster", "optimized", "legacy"),
  water_edge_extension = 0.5,
  water_polygon_failure = c("raster", "remove"),
  soil = FALSE,
  soil_freq = 0.1,
  soil_levels = 16,
  soil_color_light = "#b39474",
  soil_color_dark = "#8a623b",
  soil_gradient = 2,
  soil_gradient_darken = 4,
  theta = 45,
  phi = 45,
  fov = 0,
  zoom = 1,
  background = "white",
  window_size = 600,
  precomputed_normals = NULL,
  triangulate = FALSE,
  max_error = 0,
  max_tri = 0,
  verbose = FALSE,
  plot_new = TRUE,
  close_previous = TRUE,
  clear_previous = TRUE,
  extent = NULL,
  geographic_aspect = TRUE,
  crs = NULL,
  water_elevation = NULL,
  water_surface_tolerance = NULL,
  normals = TRUE,
  earth_curvature = FALSE,
  ...
)

Arguments

hillshade

Hillshade/image to be added to 3D surface map.

heightmap

Elevation input for the surface. Can be: a two-dimensional matrix (each entry is elevation), a RasterLayer/RasterBrick/RasterStack, a terra::SpatRaster, or a raster filename. Spatial raster inputs are automatically converted to matrix form with raster_to_matrix(). For spatial raster inputs, rayshader also caches the raster extent and CRS for downstream ⁠render_*⁠ calls.

zscale

Default 1. The ratio between the x and y spacing (which are assumed to be equal) and the z axis. For example, if the elevation levels are in units of 1 meter and the grid values are separated by 10 meters, zscale would be 10. Adjust the zscale down to exaggerate elevation features. If zscale is not supplied and heightmap is a spatial raster, rayshader automatically uses the raster cell resolution (mean x/y resolution). Geographic longitude/latitude rasters are converted to an approximate meter-per-cell value at the raster center.

vertical_exaggeration

Default 1. One-off multiplier applied to the effective visual relief for this scene. Values greater than 1 increase apparent relief and values between 0 and 1 flatten it. This does not update cached hillshade zscale metadata.

base_shape

Default rectangle. Shape of the base. Options are c("rectangle","circle","hex").

solid

Default TRUE. If FALSE, just the surface is rendered.

solid_depth

Default auto, which sets it to the lowest elevation in the matrix minus one unit (scaled by zscale). Depth of the solid base. If heightmap is uniform and set on auto, this is automatically set to a slightly lower level than the uniform elevation.

solid_color

Default grey20. Base color.

solid_line_color

Default grey30. Base edge line color.

shadow

Default TRUE. If FALSE, no shadow is rendered.

shadow_depth

Default auto, which sets it to solid_depth - solid_depth/10. Depth of the shadow layer.

shadow_color

Default "auto". Color of the shadow. Automatically darkens the background color by scaling its CIELuv lightness and chroma together by shadow_darkness, preserving the background hue.

shadow_darkness

Default 0.5. Lightness multiplier for the shadow when shadow_color = "auto". Values between 0 and 1 darken the background color; 0 gives a black shadow and 1 matches the background.

shadow_width

Default auto, which sizes it to 1/10th the smallest dimension of heightmap. Width of the shadow in units of the matrix.

shadow_texture_size

Default getOption("rayshader.max_shadow_texture_size", 1024). Maximum width or height, in pixels, of the blurred shadow texture. Set to Inf or FALSE to render the shadow texture at full heightmap resolution.

water

Default FALSE. If TRUE, a water layer is rendered. If water is omitted and water_input is explicitly supplied, a water layer is rendered.

water_input

Default 0. Water level or footprint. A scalar, matrix matching heightmap, spatial raster, or sf/sfc polygon object. Finite raster cells define water coverage. Method "polygon" retains supplied polygon boundaries and holes.

water_color

Default lightblue. Color of the water.

water_alpha

Default 0.5. Water transparency.

water_line_color

Default NULL. Color of the lines around the edges of the water layer.

water_line_alpha

Default 1. Water line tranparency.

linewidth

Default 2. Width of the edge lines in the scene.

line_antialias

Default FALSE. Whether to anti-alias the lines in the scene.

water_render_method

Default "polygon". Water meshing method. "raster" renders water at the supplied elevation and emits sidewalls down to the terrain wherever exposed water floats above the surface; "polygon" preserves polygon footprints and holes, extruding from the lowest terrain beneath each part to a flat water level; "optimized" fits each spatial water component by matching flooded terrain-triangle area to raster footprint area, then clips the fixed-grid terrain triangles; "legacy" uses the previous box/grid renderer.

water_edge_extension

Default 0.5. For spatial water_input inputs, amount in grid cells to expand finite water cells at boundary edges, up to a maximum of half a cell.

water_polygon_failure

Default "raster". Behavior for "optimized" water components that cannot be fit to an admissible terrain-triangle flood. "raster" renders the failed component with the raster method; "remove" omits it.

soil

Default FALSE. Whether to draw the solid base with a textured soil layer.

soil_freq

Default 0.1. Frequency of soil clumps. Higher frequency values give smaller soil clumps.

soil_levels

Default 16. Fractal level of the soil.

soil_color_light

Default "#b39474". Light tint of soil.

soil_color_dark

Default "#8a623b". Dark tint of soil.

soil_gradient

Default 2. Sharpness of the soil darkening gradient. 0 turns off the gradient entirely.

soil_gradient_darken

Default 4. Amount to darken the soil_color_dark value for the deepest soil layers. Higher numbers increase the darkening effect.

theta

Default 45. Rotation around z-axis.

phi

Default 45. Azimuth angle.

fov

Default 0–isometric. Field-of-view angle.

zoom

Default 1. Zoom factor.

background

Default "white". Color of the background.

window_size

Default 600. Position, width, and height of the rgl device displaying the plot. If a single number, viewport will be a square and located in upper left corner. If two numbers, (e.g. c(600,800)), user will specify width and height separately. If four numbers (e.g. c(200,0,600,800)), the first two coordinates specify the location of the x-y coordinates of the bottom-left corner of the viewport on the screen, and the next two (or one, if square) specify the window size. NOTE: The absolute positioning of the window does not currently work on macOS (tested on Mojave), but the size can still be specified.

precomputed_normals

Default NULL. Takes the output of calculate_normal() to save computing normals internally. Ignored when normals = FALSE or earth_curvature = TRUE.

triangulate

Default FALSE. Reduce the size of the 3D model by triangulating the height map. Set this to TRUE if generating the model is slow, or moving it is choppy. Will also reduce the size of 3D models saved to disk.

max_error

Default 0.001. Maximum allowable error when triangulating the height map, when triangulate = TRUE. Increase this if you encounter problems with 3D performance, want to decrease render time with render_highquality(), or need to save a smaller 3D OBJ file to disk with save_obj(),

max_tri

Default 0, which turns this setting off and uses max_error. Maximum number of triangles allowed with triangulating the height map, when triangulate = TRUE. Increase this if you encounter problems with 3D performance, want to decrease render time with render_highquality(), or need to save a smaller 3D OBJ file to disk with save_obj(),

verbose

Default TRUE, if interactive(). Prints information about the mesh triangulation if triangulate = TRUE.

plot_new

Default TRUE, opens new window with each plot_3d() call. If FALSE, the data will be plotted in the same window.

close_previous

Default TRUE. Closes any previously open rgl window. If FALSE, old windows will be kept open.

clear_previous

Default TRUE. Clears the previously open rgl window if plot_new = FALSE.

extent

Default NULL. Optional extent metadata to cache with the scene for later calls (e.g., render_zaxis() without an explicit extent). Accepts any input supported by get_extent() (numeric xmin/xmax/ymin/ymax vector, raster, terra, sf, or sp objects). If omitted, a spatial raster uses its spatial extent and a raw matrix uses its native 1-based extent: c(xmin = 1, xmax = nrow(heightmap), ymin = 1, ymax = ncol(heightmap)).

geographic_aspect

Default TRUE. Correct unequal metric x/y cell spacing in terrain geometry and cache the transform for later render calls.

crs

Default NULL. CRS to assign to the terrain input. An explicit value overrides embedded CRS metadata.

water_elevation

Default NULL. Polygon water elevations; see render_water().

water_surface_tolerance

Default NULL. Polygon water coincidence tolerance in terrain elevation units; see render_water().

normals

Default TRUE. Whether to use smooth vertex normals for the DEM. Set to FALSE to skip rayshader's terrain normal calculation and ignore precomputed_normals. The DEM uses flat shading in rgl, and high-quality renders and OBJ exports use triangle face normals. Normals on other scene objects are unaffected.

earth_curvature

Default FALSE. Bend the terrain away from the tangent plane at the bounding-box center. Supply a georeferenced DEM or a matrix with an extent and CRS so ground distances can be measured.

...

Deprecated argument spellings are accepted with a warning and forwarded to their current names.

Details

With earth_curvature = TRUE, the terrain follows a sphere of mean radius 6,371,008.8 meters. Ground distances use the east-west and north-south cell spacing at the bounding-box center, a local approximation for regional maps. The center retains its elevation. Earth's curvature is always drawn at its true scale, regardless of vertical_exaggeration. At a ground distance of 100 km from the center, sea level lies about 785 m below the tangent plane with either vertical_exaggeration = 1 or vertical_exaggeration = 4. The latter draws terrain relief four times taller above local sea level.

Spatial layers added by the render functions inherit the scene's curvature. Supply water levels and object altitudes in the original elevation datum. Terrain-relative offsets are measured above the local surface. Explicit raw scene coordinates already refer to the rendered coordinate system.

Examples

#Plotting a spherical texture map of the built-in `montereybay_spatial` dataset.
montereybay_spatial |>
 sphere_shade(texture="desert", vertical_exaggeration = 10) |>
 plot_3d(vertical_exaggeration = 4)
render_snapshot()

montereybay_spatial |>
 sphere_shade(texture="desert", vertical_exaggeration = 10) |>
 plot_3d(vertical_exaggeration = 4)
render_zaxis(location = "bottomleft")
render_snapshot()

#With a water layer
montereybay_spatial |>
 sphere_shade(texture="imhof2", vertical_exaggeration = 10) |>
 plot_3d(vertical_exaggeration = 4, water = TRUE, water_color="imhof2",
         water_line_color="white", water_line_alpha=0.5)
render_snapshot()

#With a soil texture to the base
montereybay_spatial |>
 sphere_shade(texture="imhof3", vertical_exaggeration = 10) |>
 plot_3d(vertical_exaggeration = 4, water = TRUE,  water_color="imhof4",
         water_line_color="white", water_line_alpha=0.5, soil=TRUE)
render_camera(theta=225, phi=7, zoom=0.5, fov=67)
render_snapshot()

#We can also change the base by setting "base_shape" to "hex" or "circle"
montereybay_spatial |>
 sphere_shade(texture="imhof1", vertical_exaggeration = 10) |>
 plot_3d(vertical_exaggeration = 4, water = TRUE, water_color="imhof1", theta=-45, zoom=0.7,
         water_line_color="white", water_line_alpha=0.5,base_shape="circle")
render_snapshot()

montereybay_spatial |>
 sphere_shade(texture="imhof1", vertical_exaggeration = 10) |>
 plot_3d(vertical_exaggeration = 4, water = TRUE, water_color="imhof1", theta=-45, zoom=0.7,
         water_line_color="white", water_line_alpha=0.5,base_shape="hex")
render_snapshot()



#Or we can carve out the region of interest ourselves, by setting those entries to NA
#to the elevation map passed into `plot_3d`

#Here, we only include the deep bathymetry data by setting all points greater than -10
#in the copied elevation matrix to NA.

mb_water = montereybay_spatial
mb_water[mb_water > -10] = NA

montereybay_spatial |>
 sphere_shade(texture="imhof1", vertical_exaggeration = 10) |>
 plot_3d(mb_water, vertical_exaggeration = 4, water = TRUE, water_color="imhof1", theta=-45,
         water_line_color="white", water_line_alpha=0.5)
render_snapshot()

Transform ggplot2 objects into 3D

Description

Plots a ggplot2 object in 3D by mapping the color or fill aesthetic to elevation.

Currently, this function does not transform lines mapped to color into 3D.

If there are multiple legends/guides due to multiple aesthetics being mapped (e.g. color and shape), the package author recommends that the user pass the order of the guides manually using the ggplot2 function "guides()'. Otherwise, the order may change when processing the ggplot2 object and result in a mismatch between the 3D mapping and the underlying plot.

Using the shape aesthetic with more than three groups is not recommended, unless the user passes in custom, solid shapes. By default in ggplot2, only the first three shapes are solid, which is a requirement to be projected into 3D.

Usage

plot_gg(
  gg_obj,
  gg_obj_height = NULL,
  width = 3,
  height = 3,
  height_aes = NULL,
  invert = FALSE,
  shadow_intensity = 0.5,
  units = c("in", "cm", "mm"),
  scale = NULL,
  zscale = NULL,
  vertical_exaggeration = NULL,
  point_contract = 0.7,
  offset_edges = FALSE,
  flat_substrate = FALSE,
  flat_plot_render = FALSE,
  flat_distance = "auto",
  flat_transparent_bg = FALSE,
  flat_direction = "-z",
  shadow = TRUE,
  shadow_depth = "auto",
  shadow_color = "auto",
  shadow_darkness = 0.5,
  background = "white",
  preview = FALSE,
  raytrace = TRUE,
  radiance_args = list(),
  sun_angle = 315,
  angle_breaks = seq(30, 40, 0.1),
  multicore = FALSE,
  lambert = TRUE,
  triangulate = FALSE,
  max_error = 0.001,
  max_tri = 0,
  verbose = FALSE,
  emboss_text = 0,
  emboss_grid = 0,
  guide_bar_bleed_px = 3L,
  guide_bar_bleed_target = c("height", "texture", "none"),
  reduce_size = NULL,
  save_height_matrix = FALSE,
  save_shadow_matrix = FALSE,
  saved_shadow_matrix = NULL,
  monitor_gamma = 1.8,
  plot = TRUE,
  ...
)

Arguments

gg_obj

ggplot object to projected into 3D.

gg_obj_height

Default NULL. A ggplot object that can be used to specify the 3D extrusion separately from the gg_obj. If this plot includes a tidyterra::geom_spatraster() height layer, rayshader preserves the mapped raster data scale when building the height map and uses the final rendered scene spacing as the default zscale unless zscale is supplied.

width

Default 3. Width of ggplot, in units.

height

Default 3. Height of ggplot, in units.

height_aes

Default NULL. Whether the fill or color aesthetic should be used for height values, which the user can specify by passing either fill or color to this argument. Automatically detected. If both fill and color aesthetics are present, then fill is default.

invert

Default FALSE. If TRUE, the height mapping is inverted.

shadow_intensity

Default 0.5. The intensity of the calculated shadows. When raytrace = "radiance", this uses the same scale as the default raytraced shadowing: 1 means no additional shading effect, and lower values increase the strength of the radiance overlay.

units

Default ⁠in⁠. One of c("in", "cm", "mm").

scale

Deprecated. Use vertical_exaggeration instead.

zscale

Default NULL. The ratio between the x/y spacing and the z axis for the height surface. If omitted and gg_obj_height includes a spatial raster height layer, rayshader derives zscale from the final rendered ggplot scene extent and output matrix spacing, which accounts for ggplot rasterization and reprojection. Otherwise, the base zscale defaults to 1.

vertical_exaggeration

Default NULL. One-off multiplier applied to the effective relief after resolving zscale. When omitted, rayshader uses 1 for spatial raster height sources and 150 for non-raster ggplot height mappings, which preserves the legacy plot_gg() default appearance.

point_contract

Default 0.7. This multiplies the size of the points and shrinks them around their center in the 3D surface mapping. Decrease this to reduce color bleed on edges, and set to 1 to turn off entirely. Note: If size is passed as an aesthetic to the same geom that is being mapped to elevation, this scaling will not be applied. If alpha varies on the variable being mapped, you may want to set this to 1, since the points now have a non-zero width stroke outline (however, mapping alpha in the same variable you are projecting to height is probably not a good choice. as the alpha variable is ignored when performing the 3D projection).

offset_edges

Default FALSE. If TRUE, inserts a small amount of space between polygons for "geom_sf", "geom_tile", "geom_hex", and "geom_polygon" layers. If you pass in a number, the space between polygons will be a line of that width. You can also specify a number to control the thickness of the offset. Note: this feature may end up removing thin polygons from the plot entirely–use with care.

flat_substrate

Default FALSE. If TRUE, render the captured ggplot texture on flat solid plot panels instead of using the panel aesthetics as the surface height. Guides and legends retain their rendered height mapping, and the resulting scene can be used as a base for later ⁠render_*()⁠ calls.

flat_plot_render

Default FALSE. Whether to render a flat version of the ggplot above (or alongside) the 3D version.

flat_distance

Default "auto". Distance to render the flat version of the plot from the 3D version.

flat_transparent_bg

Default FALSE. Whether to set the background of the flat version of the ggplot to transparent.

flat_direction

Default "-z". Direction to render the flat copy of the plot, if flat_plot_render = TRUE. Other options c("z", "x", "-x", "y", "-y").

shadow

Default TRUE. If FALSE, no shadow is rendered.

shadow_depth

Default auto, which sets it to solid_depth - solid_depth/10. Depth of the shadow layer.

shadow_color

Default "auto". Color of the shadow. Automatically darkens the background color by scaling its CIELuv lightness and chroma together by shadow_darkness, preserving the background hue.

shadow_darkness

Default 0.5. Lightness multiplier for the shadow when shadow_color = "auto". Values between 0 and 1 darken the background color; 0 gives a black shadow and 1 matches the background.

background

Default "white". Background color for the 3D scene. This is independent of the ggplot plot.background fill used for the captured texture.

preview

Default FALSE. If TRUE, the raytraced 2D ggplot will be displayed on the current device.

raytrace

Default TRUE. Controls the additional shading applied to the ggplot texture. Use TRUE/"raytrace" for ray_shade(), FALSE/"none" for no extra shading, or "radiance" for radiance_shade().

radiance_args

Default list(). Additional arguments passed to radiance_shade() when raytrace = "radiance". By default, light_direction is derived from sun_angle and light_altitude from the midpoint of angle_breaks.

sun_angle

Default 315 (NW). If raytracing, the angle (in degrees) around the matrix from which the light originates.

angle_breaks

Default seq(30,40,0.1). The azimuth angle(s), in degrees, as measured from the horizon from which the light originates.

multicore

Default FALSE. If raytracing and TRUE, multiple cores will be used to compute the shadow matrix. By default, this uses all cores available, unless the user has set options("cores") in which the multicore option will only use that many cores.

lambert

Default TRUE. If raytracing, changes the intensity of the light at each point based proportional to the dot product of the ray direction and the surface normal at that point. Zeros out all values directed away from the ray.

triangulate

Default FALSE. Reduce the size of the 3D model by triangulating the height map. Set this to TRUE if generating the model is slow, or moving it is choppy. Will also reduce the size of 3D models saved to disk.

max_error

Default 0.001. Maximum allowable error when triangulating the height map, when triangulate = TRUE. Increase this if you encounter problems with 3D performance, want to decrease render time with render_highquality(), or need to save a smaller 3D OBJ file to disk with save_obj(),

max_tri

Default 0, which turns this setting off and uses max_error. Maximum number of triangles allowed with triangulating the height map, when triangulate = TRUE. Increase this if you encounter problems with 3D performance, want to decrease render time with render_highquality(), or need to save a smaller 3D OBJ file to disk with save_obj(),

verbose

Default FALSE. Prints the computed zscale and horizontal units. Also prints information about the mesh triangulation if triangulate = TRUE.

emboss_text

Default 0, max 1. Amount to emboss the text, where 1 is the tallest feature in the scene.

emboss_grid

Default 0, max 1. Amount to emboss the grid lines, where 1 is the tallest feature in the scene. By default, the minor grid lines will be half the size of the major lines. Pass a length-2 vector to specify them seperately (second value is the minor grid height).

guide_bar_bleed_px

Default 3L. Number of rendered pixels to widen a continuous guide colorbar orthogonally without changing the guide layout. This ensures either the sidewalls of the colorbar are either solid or represent the color ramp.

guide_bar_bleed_target

Default "texture". Which rendered grob should receive the colorbar bleed. Use "height" to keep white side walls, "texture" to color the side walls with the gradient, or "none" to disable it (rayshader's old default).

reduce_size

Default NULL. A number between 0 and 1 that specifies how much to reduce the resolution of the plot, for faster plotting. By default, this just decreases the size of height map, not the image. If you wish the image to be reduced in resolution as well, pass a numeric vector of size 2.

save_height_matrix

Default FALSE. If TRUE, the function will return the height matrix used for the ggplot.

save_shadow_matrix

Default FALSE. If TRUE, the function will return the computed shading layer. For raytrace = TRUE, this is the shadow matrix from ray_shade(). For raytrace = "radiance", this is the RGBA radiance overlay from radiance_shade().

saved_shadow_matrix

Default NULL. A cached shading layer saved by a previous invocation of plot_gg() with save_shadow_matrix = TRUE. For raytrace = TRUE, pass a shadow matrix from ray_shade(). For raytrace = "radiance", pass an RGBA radiance overlay.

monitor_gamma

Default 1.8. Undo the gamma correction applied by the png device. Ignored if ragg is installed or the cairo PNG device is available.

plot

Default TRUE. Whether to plot the image when preview = TRUE, or just return the RGBA rayimg.

...

Additional arguments to be passed to plot_3d(). Deprecated argument spellings are accepted with a warning and forwarded to their current names.

Value

Opens a 3D plot in rgl.

Examples

library(ggplot2)
library(viridis)


ggdiamonds = ggplot(diamonds, aes(x, depth)) +
 stat_density_2d(aes(fill = after_stat(nlevel), color = after_stat(nlevel)),
                 geom = "polygon",
                 n = 200, bins = 50,contour = TRUE) +
 facet_wrap(clarity~.) +
 scale_fill_viridis_c(option = "A") +
 scale_color_viridis_c(option = "A")
plot_gg(ggdiamonds,multicore = TRUE,width=5,height=5,
       vertical_exaggeration=250,window_size=c(1400,866),
       zoom = 0.55, phi = 30)
render_snapshot()
#Change the camera angle and take a snapshot:
render_camera(zoom=0.5,theta=-30,phi=30)
render_snapshot()

#Contours and other lines will automatically be ignored. Here is the volcano dataset:
ggvolcano = volcano |>
 reshape2::melt() |>
 ggplot() +
 geom_tile(aes(x=Var1,y=Var2,fill=value)) +
 geom_contour(aes(x=Var1,y=Var2,z=value),color="black") +
 scale_x_continuous("X",expand = c(0,0)) +
 scale_y_continuous("Y",expand = c(0,0)) +
 scale_fill_gradientn("Z",colours = terrain.colors(10)) +
 coord_fixed() +
 theme(legend.position = "none")
ggvolcano

plot_gg(ggvolcano, multicore = TRUE, raytrace = TRUE, width = 7, height = 4,
       vertical_exaggeration = 300, window_size = c(1400, 866), zoom = 0.6, phi = 30, theta = 30)
render_snapshot()

#You can specify the color and height separately using the `gg_obj_height()` argument.
ggvolcano_surface = volcano |>
reshape2::melt() |>
 ggplot() +
 geom_contour(aes(x=Var1,y=Var2,z=value),color="black") +
 geom_contour_filled(aes(x=Var1,y=Var2,z=value))+
 scale_x_continuous("X",expand = c(0,0)) +
 scale_y_continuous("Y",expand = c(0,0)) +
 coord_fixed() +
 theme(legend.position = "none")

plot_gg(ggvolcano_surface, gg_obj_height = ggvolcano,
      multicore = TRUE, raytrace = TRUE, width = 7, height = 4,
      vertical_exaggeration = 300, window_size = c(1400, 866), zoom = 0.6, phi = 30, theta = 30)
render_snapshot()
#Here, we will create a 3D plot of the mtcars dataset. This automatically detects
#that the user used the `color` aesthetic instead of the `fill`.
mtplot = ggplot(mtcars) +
 geom_point(aes(x=mpg,y=disp,color=cyl)) +
 scale_color_continuous(limits=c(0,8))

#Preview how the plot will look by setting `preview = TRUE`: We also adjust the angle of the light.
plot_gg(mtplot, width=3.5, sun_angle=225, preview = TRUE)
plot_gg(mtplot, width=3.5, multicore = TRUE, window_size = c(1400,866), sun_angle=225,
       zoom = 0.60, phi = 30, theta = 45)
render_snapshot()

#Colorbar side-wall bleed control with a continuous guide:
bleedplot = ggplot(faithfuld, aes(waiting, eruptions, fill = density)) +
 geom_raster(interpolate = TRUE) +
 scale_fill_viridis_c() +
 theme_minimal()
plot_gg(bleedplot, width = 5, height = 4, vertical_exaggeration = 220,
       window_size = c(1400,866), theta = -20, phi = 35, zoom = 0.60,
       guide_bar_bleed_target = "height")
render_snapshot()
plot_gg(bleedplot, width = 5, height = 4, vertical_exaggeration = 220,
       window_size = c(1400,866), theta = -20, phi = 35, zoom = 0.60,
       guide_bar_bleed_target = "texture")
render_snapshot()
plot_gg(mtplot, width=3.5, multicore = TRUE, window_size = c(1400,866), sun_angle=225,
       zoom = 0.60, phi = 30, theta = 45)
render_zaxis(location = "panel_bottomleft")
render_snapshot()
#Now let's plot a density plot in 3D.
mtplot_density = ggplot(mtcars) +
 stat_density_2d(aes(x=mpg,y=disp, fill=after_stat(!!str2lang("density"))),
                 geom = "raster", contour = FALSE) +
 scale_x_continuous(expand=c(0,0)) +
 scale_y_continuous(expand=c(0,0)) +
 scale_fill_gradient(low="pink", high="red")
mtplot_density

plot_gg(mtplot_density, width = 4,zoom = 0.60, theta = -45, phi = 30,
       window_size = c(1400,866))
render_snapshot()
#This also works facetted.
mtplot_density_facet = mtplot_density + facet_wrap(~cyl)

#Preview this plot in 2D:
plot_gg(mtplot_density_facet, preview = TRUE)
plot_gg(mtplot_density_facet, window_size=c(1400,866),
       zoom = 0.55, theta = -10, phi = 25)
render_snapshot()
#That is a little cramped. Specifying a larger width will improve the readability of this plot.
plot_gg(mtplot_density_facet, width = 6, preview = TRUE)

#That's better. Let's plot it in 3D, and increase the vertical exaggeration.
plot_gg(mtplot_density_facet, width = 6, window_size=c(1400,866),
       zoom = 0.55, theta = -10, phi = 25, vertical_exaggeration=300)
render_snapshot()

#We can also render a flat version of the plot alongside (or above/below) the 3D version.
plot_gg(mtplot_density_facet, width = 6, window_size=c(1400,866),
       zoom = 0.65, theta = -25, phi = 35, vertical_exaggeration=300, flat_plot_render=TRUE,
       flat_direction = "x")
render_snapshot()

Plot Map

Description

Displays the map in the current device.

Usage

plot_map(
  hillshade,
  title_text = NA,
  title_offset = c(20, 20),
  title_color = "black",
  title_size = 30,
  title_font = "sans",
  title_style = "normal",
  title_bar_color = NA,
  title_bar_alpha = 0.5,
  title_just = "left",
  ...
)

Arguments

hillshade

Hillshade to be plotted.

title_text

Default NULL. Text. Adds a title to the image, using magick::image_annotate().

title_offset

Default c(20,20). Distance from the top-left (default, gravity direction in image_annotate) corner to offset the title.

title_color

Default black. Font color.

title_size

Default 30. Font size in pixels.

title_font

Default sans. String with font family such as "sans", "mono", "serif", "Times", "Helvetica", "Trebuchet", "Georgia", "Palatino" or "Comic Sans".

title_style

Default normal. Font style (e.g. italic).

title_bar_color

Default NA. If a color, this will create a colored bar under the title.

title_bar_alpha

Default 0.5. Transparency of the title bar.

title_just

Default left. Justification of the title.

...

Additional arguments to pass to the raster::plotRGB function that displays the map.

Examples

#Plotting the Monterey Bay dataset with bathymetry data
water_palette = colorRampPalette(c("darkblue", "dodgerblue", "lightblue"))(200)
bathy_hs = height_shade(montereybay_spatial, texture = water_palette)
#For compass text
par(family = "Arial")

#Set everything below 0m to water palette
montereybay_spatial |>
 sphere_shade() |>
 add_overlay(generate_altitude_overlay(bathy_hs, montereybay_spatial, 0, 0))  |>
 add_shadow(ray_shade(vertical_exaggeration = 4),0.3) |>
 plot_map()

Calculate Radiance Shade Overlay

Description

Renders a top-down orthographic radiance pass of either the current hillshade cache, the current 3D rayshader scene, or a supplied elevation matrix.

Cache fallback messages are disabled by default. Set options(rayshader.verbose_scene_cache = TRUE) to print when cached metadata is reused.

When called with no heightmap, this function uses the cached 2D hillshade heightmap and, when available, the cached hillshade/map texture from the most recent rayshader hillshading chain. Set capture_scene = TRUE to instead render the currently displayed rayshader 3D scene. When a raw matrix is supplied, rayshader builds a temporary surface and applies texture (or a constant color, default "grey50").

This function uses the same lighting controls as render_highquality(), including directional lights and auto-sky generation (lat, long, datetime, sky_sun_elevation, sky_sun_azimuth, sky_altitude, and sky_args), and returns an RGBA array that can be passed to add_overlay(). The render runs in an isolated background R session with RGL_USE_NULL=TRUE in the subprocess environment, and uses the standard rayshader pipeline: plot_3d(..., solid = TRUE, shadow = shadow) followed by render_highquality(plot = FALSE).

Usage

radiance_shade(
  heightmap = NULL,
  texture = NULL,
  color = "grey50",
  zscale = 1,
  vertical_exaggeration = 1,
  filename = NA,
  samples = 128,
  sample_method = "sobol_blue",
  min_variance = 1e-07,
  shadow = TRUE,
  light = TRUE,
  lat = NA,
  long = NA,
  datetime = NA,
  sky_sun_elevation = NA,
  sky_sun_azimuth = NA,
  sky_altitude = NA,
  sky_args = list(),
  light_direction = 315,
  light_altitude = 45,
  light_size = 5,
  light_intensity = 500,
  light_color = "white",
  material = rayrender::diffuse(),
  water_attenuation = 0,
  water_surface_color = TRUE,
  water_ior = 1.33,
  override_material = FALSE,
  cache_scene = FALSE,
  reset_scene_cache = FALSE,
  width = NULL,
  height = NULL,
  clamp_value = 1000,
  auto_exposure = TRUE,
  capture_scene = FALSE,
  scene_elements = NULL,
  plot = FALSE,
  geographic_aspect = TRUE,
  extent = NULL,
  crs = NULL,
  ...
)

Arguments

heightmap

Default NULL. If NULL, uses cached 2D hillshade metadata by default. Set capture_scene = TRUE to use the current rayshader rgl scene. If a matrix (or supported raster input), renders a top-down radiance pass for that data directly.

texture

Default NULL. Texture used only when heightmap is supplied. Can be a rayshader-style RGB(A) array, a built-in sphere_shade() texture name, a color vector (passed to height_shade()), an image filename, or a single color name.

color

Default "grey50". Fallback single-color texture when heightmap is supplied and texture = NULL.

zscale

Default 1. Vertical scale when heightmap is supplied.

vertical_exaggeration

Default 1. Multiplier applied to the effective visual relief. If omitted while rendering from the active scene, rayshader uses the cached scene value from plot_3d() or plot_gg() when available; pass explicitly to override for this call. This does not update cached metadata.

filename

Default NA. Optional output filename. If supplied, the render is also saved to disk.

samples

Default 128. Maximum samples per pixel.

sample_method

Default "sobol_blue", unless samples > 256, in which case it is switched to "sobol".

min_variance

Default 1e-7. Adaptive sampler variance threshold.

shadow

Default TRUE. Whether to build the temporary top-down scene with the rayshader shadow plane underneath the model. Setting this to TRUE can help fill very dark corners in the radiance pass.

light

Default TRUE. Whether to add directional lights.

lat

Default NA. Latitude used for auto sky generation.

long

Default NA. Longitude used for auto sky generation.

datetime

Default NA. Datetime used for auto sky generation.

sky_sun_elevation

Default NA. If supplied, uses skymodelr::generate_sky() and passes this value to its elevation argument.

sky_sun_azimuth

Default NA. If supplied, uses skymodelr::generate_sky() and passes this value to its azimuth argument.

sky_altitude

Default NA. If supplied, uses skymodelr::generate_sky() and passes this value to its altitude argument.

sky_args

Default list(). Extra arguments passed to skymodelr::generate_sky_latlong() (default) or skymodelr::generate_sky() when direct sky arguments are used.

light_direction

Default 315. Light direction angle(s), in degrees.

light_altitude

Default 45. Light altitude angle(s), in degrees.

light_size

Default 5. Full angular diameter of the disk light(s), in degrees, greater than 0 and less than 180. Independent of scene size and camera position.

light_intensity

Default 500. Light intensity value(s).

light_color

Default "white". Light color(s).

material

Default rayrender::diffuse(). Forwarded to render_highquality().

water_attenuation

Default 0. Forwarded to render_highquality().

water_surface_color

Default TRUE. Forwarded to render_highquality().

water_ior

Default 1.33. Forwarded to render_highquality().

override_material

Default FALSE. Forwarded to render_highquality().

cache_scene

Default FALSE. Forwarded to render_highquality().

reset_scene_cache

Default FALSE. Forwarded to render_highquality().

width

Default NULL. Output width in pixels. If omitted, derived from the underlying surface dimensions.

height

Default NULL. Output height in pixels. If omitted, derived from the underlying surface dimensions.

clamp_value

Default 1000. Radiance clamp value. If NA, uses 1000.

auto_exposure

Default TRUE. Whether to use rayrender's automatic exposure adjustment in the radiance pass. Forwarded to rayrender::render_scene() via render_highquality() when supported by the installed rayrender version.

capture_scene

Default FALSE. If TRUE and heightmap = NULL, renders the currently displayed rayshader rgl scene instead of the cached 2D hillshade context.

scene_elements

Default NULL. Extra rayrender objects to add.

plot

Default FALSE. Whether to preview the rendered image.

geographic_aspect

Default TRUE. Correct unequal metric x/y cell spacing in the temporary radiance scene.

extent

Default NULL. Spatial extent for a matrix heightmap.

crs

Default NULL. CRS to assign to the input before calculating metric cell spacing.

...

Additional parameters passed to render_highquality(). Deprecated argument spellings are accepted with a warning and forwarded to their current names.

Value

RGBA array representing the top-down radiance render.

Examples

montereybay_spatial |>
height_shade(texture = topo.colors(256)) |>
add_overlay(radiance_shade(vertical_exaggeration = 10), 1) |>
plot_map()
#Plot using sky args
montereybay_spatial |>
height_shade(texture = topo.colors(256)) |>
add_overlay(radiance_shade(vertical_exaggeration = 20,
                            sky_sun_elevation = 5, sky_sun_azimuth = 315), 1) |>
plot_map()

Raster to Matrix

Description

Turns a raster into a matrix suitable for rayshader.

Usage

raster_to_matrix(raster, verbose = interactive())

Arguments

raster

The input raster. Either a RasterLayer object, a terra SpatRaster object, or a filename.

verbose

Default interactive(). Will print dimensions of the resulting matrix.

Examples

#Save montereybay_spatial as a raster and open using the filename.
temp_raster_filename = paste0(tempfile(),".tif")
terra::writeRaster(montereybay_spatial, temp_raster_filename, overwrite = TRUE)
elmat = raster_to_matrix(temp_raster_filename)
elmat |>
 sphere_shade() |>
 plot_map()

Calculate Raytraced Shadow Map

Description

Calculates shadow map for a elevation matrix by propogating rays from each matrix point to the light source(s), lowering the brightness at each point for each ray that intersects the surface.

Cache fallback messages are disabled by default. Set options(rayshader.verbose_scene_cache = TRUE) to print when cached metadata is reused.

Usage

ray_shade(
  heightmap,
  sun_altitude = 45,
  sun_angle = 315,
  max_search = NULL,
  lambert = TRUE,
  zscale = 1,
  vertical_exaggeration = 1,
  multicore = FALSE,
  cache_mask = NULL,
  shadow_cache = NULL,
  progress_bar = interactive(),
  angle_breaks = NULL,
  geographic_aspect = TRUE,
  extent = NULL,
  crs = NULL,
  ...
)

Arguments

heightmap

A two-dimensional matrix, where each entry in the matrix is the elevation at that point. All points are assumed to be evenly spaced.

sun_altitude

Default 45. The angle, in degrees (as measured from the horizon) from which the light originates. The width of the light is centered on this value and has an angular extent of 0.533 degrees, which is the angular extent of the sun. Use the angle_breaks argument to create a softer (wider) light. This has a hard minimum/maximum of 0/90 degrees.

sun_angle

Default 315 (NW). The angle, in degrees, around the matrix from which the light originates. Zero degrees is North, increasing clockwise.

max_search

Defaults to the longest possible shadow given the sun_altitude and heightmap. Otherwise, this argument specifies the maximum distance that the system should propagate rays to check.

lambert

Default TRUE. Changes the intensity of the light at each point based proportional to the dot product of the ray direction and the surface normal at that point. Zeros out all values directed away from the ray.

zscale

Default 1. The ratio between the x and y spacing (which are assumed to be equal) and the z axis. For example, if the elevation is in units of meters and the grid values are separated by 10 meters, zscale would be 10.

vertical_exaggeration

Default 1. One-off multiplier applied to the effective visual relief for this call. Values greater than 1 increase apparent relief and values between 0 and 1 flatten it. This does not update cached zscale metadata.

multicore

Default FALSE. If TRUE, multiple cores will be used to compute the shadow matrix. By default, this uses all cores available, unless the user has set options("cores") in which the multicore option will only use that many cores.

cache_mask

Default NULL. A matrix of 1 and 0s, indicating which points on which the raytracer will operate.

shadow_cache

Default NULL. The shadow matrix to be updated at the points defined by the argument cache_mask. If present, this will only compute the raytraced shadows for those points with value 1 in the mask.

progress_bar

Default TRUE if interactive, FALSE otherwise. If FALSE, turns off progress bar.

angle_breaks

Default NULL. A vector of angle(s) in degrees (as measured from the horizon) specifying from where the light originates. Use this instead of sun_altitude to create a softer shadow by specifying a wider light. E.g. angle_breaks = seq(40,50,by=0.5) creates a light 10 degrees wide, as opposed to the default

geographic_aspect

Default TRUE. Correct unequal metric x/y cell spacing using the input extent and CRS.

extent

Default NULL. Spatial extent for a matrix heightmap.

crs

Default NULL. CRS to assign to the input before calculating metric cell spacing.

...

Additional arguments to pass to the makeCluster function when multicore=TRUE. Deprecated argument spellings are accepted with a warning and forwarded to their current names.

Value

Matrix of light intensities at each point.

Examples

#First we ray trace the Monterey Bay dataset.
#The default angle is from 40-50 degrees azimuth, from the north east.
montereybay_spatial |>
 ray_shade(vertical_exaggeration = 4) |>
 plot_map()
#Change the altitude of the sun to 25 degrees
montereybay_spatial |>
 ray_shade(vertical_exaggeration = 4, sun_altitude=25) |>
 plot_map()
#Remove the lambertian shading to just calculate shadow intensity.
montereybay_spatial |>
 ray_shade(vertical_exaggeration = 4, sun_altitude=25, lambert=FALSE) |>
 plot_map()

#Change the direction of the sun to the South East
montereybay_spatial |>
 ray_shade(vertical_exaggeration = 4, sun_altitude=25, sun_angle=225) |>
 plot_map()

Reduce Matrix Size (defunct)

Description

Reduce Matrix Size (defunct)

Usage

reduce_matrix_size(...)

Arguments

...

Arguments to pass to resize_matrix() function.

Value

Reduced matrix.

Examples

montereybay_matrix = raster_to_matrix(montereybay_spatial, verbose = FALSE)
montbaysmall = resize_matrix(montereybay_matrix, scale=0.5)
montbaysmall |>
 sphere_shade() |>
 plot_map()

Render Beveled Polygons

Description

Adds beveled polygon to the scene using the raybevel package. See the raybevel::generate_beveled_polygon() function for more information.

Cache fallback messages are disabled by default. Set options(rayshader.verbose_scene_cache = TRUE) to print when cached metadata is reused.

Usage

render_beveled_polygons(
  polygon,
  material = "grey",
  bevel_material = NA,
  angle = 45,
  bevel_width = 5,
  width_raw_units = FALSE,
  bevel = NA,
  bevel_height = 1,
  base_height = 0,
  raw_heights = FALSE,
  raw_offsets = FALSE,
  heights_relative_to_centroid = TRUE,
  set_max_height = FALSE,
  max_height = 10,
  scale_all_max = TRUE,
  data_column_top = NULL,
  data_column_bottom = NULL,
  scale_data = 1,
  holes = 0,
  alpha = 1,
  lit = TRUE,
  flat_shading = FALSE,
  light_altitude = c(45, 30),
  light_direction = c(315, 225),
  light_intensity = 1,
  light_relative = FALSE,
  clear_previous = FALSE,
  crs = NULL,
  filter_to_extent = TRUE,
  extent = NULL,
  panel = NULL,
  zscale = 1,
  vertical_exaggeration = 1,
  heightmap = NULL,
  ...
)

Arguments

polygon

sf object, "SpatialPolygon" sp object, or xy coordinates of polygon represented in a way that can be processed by xy.coords(). If xy-coordinate based polygons are open, they will be closed by adding an edge from the last point to the first.

material

Default "grey80". If a color string, this will specify the color of the sides/base of the polygon. Alternatively (for more customization), this can be a rayvertex::material_list() object to specify the full color/appearance/material options for the resulting ray_mesh mesh.

bevel_material

Default NA, defaults to the material specified in material. If a color string, this will specify the color of the polygon bevel. Alternatively (for more customization), this can be a rayvertex::material_list() object to specify the full color/appearance/material options for the resulting ray_mesh mesh.

angle

Default 45. Angle of the bevel.

bevel_width

Default 5. Width of the bevel.

width_raw_units

Default FALSE. Whether the bevel width should be measured in raw display units, or the actual units of the map.

bevel

Default NULL. A list with x/y components that specify a bevel profile. See raybevel::generate_bevel()

bevel_height

Default 1. Height from the base of the polygon to the start of the beveled top.

base_height

Default 0. Height of the base of the polygon.

raw_heights

Default FALSE. A logical flag indicating whether the bevel_heights are already in raw format and do not need to be multiplied by the maximum time of the skeleton. See the documentation for raybevel::generate_beveled_polygon() for more info.

raw_offsets

Default FALSE. A logical flag indicating whether the bevel_offsets are already in raw format and do not need to be multiplied by the maximum time of the skeleton. See the documentation for raybevel::generate_beveled_polygon() for more info.

heights_relative_to_centroid

Default FALSE. Whether the heights should be measured in absolute terms, or relative to the centroid of the polygon.

set_max_height

Default FALSE. A logical flag that controls whether to set the max height of the roof based on the max_height argument.

max_height

Default 1. The maximum height of the polygon.

scale_all_max

Default FALSE. If passing in a list of multiple skeletons with polygons, whether to scale each polygon to the overall max height, or whether to scale each max height to the maximum internal distance in the polygon.

data_column_top

Default NULL. A string indicating the column in the sf object to use to specify the top of the beveled polygon. Values are coerced to numeric, and rows with missing or non-finite values after coercion are omitted.

data_column_bottom

Default NULL. A string indicating the column in the sf object to use to specify the bottom of the beveled polygon. Values are coerced to numeric, and rows with missing or non-finite values after coercion are omitted.

scale_data

Default 1. If specifying data_column_top or data_column_bottom, how much to scale that value when rendering. If used with vertical_exaggeration, both are applied.

holes

Default 0. If passing in a polygon directly, this specifies which index represents the holes in the polygon. See the earcut function in the decido package for more information.

alpha

Default 1. Transparency of the polygons.

lit

Default TRUE. Whether to light the polygons.

flat_shading

Default FALSE. Set to TRUE to have nicer shading on the 3D polygons. This comes with the slight penalty of increasing the memory use of the scene due to vertex duplication. This will not affect software or high quality renders.

light_altitude

Default c(45, 30). Degree(s) from the horizon from which to light the polygons.

light_direction

Default c(315, 225). Degree(s) from north from which to light the polygons.

light_intensity

Default 1. Intensity of the specular highlight on the polygons.

light_relative

Default FALSE. Whether the light direction should be taken relative to the camera, or absolute.

clear_previous

Default FALSE. If TRUE, clears all existing beveled polygons. A clear-only call returns without rendering a replacement.

crs

Default NULL. CRS of the input numeric x/y coordinates, or CRS to assign to CRS-less spatial data before transforming it into the active scene CRS. If spatial data already carries a CRS, that CRS is used automatically.

filter_to_extent

Default TRUE. If TRUE, polygon data outside the scene extent is omitted. Spatial polygon inputs are cropped to the extent. For scenes created with plot_gg(), filtering uses the ggplot panel extent rather than the full rendered 3D ggplot extent.

extent

Either an object representing the spatial extent of the 3D scene (either from the raster, terra, sf, or sp packages), a length-4 numeric vector specifying c("xmin", "xmax", "ymin", "ymax"), or the spatial object (from the previously aforementioned packages) which will be automatically converted to an extent object. If omitted, rayshader will use extent metadata cached by plot_3d() or plot_gg().

panel

Default NULL. Facet panel identifier for scenes created with plot_gg(). Required to disambiguate faceted ggplot scenes when panel-specific cached metadata is needed. Ignored for non-ggplot scenes.

zscale

Default 1. The ratio between the x and y spacing (which are assumed to be equal) and the z axis in the original heightmap.

vertical_exaggeration

Default 1. Multiplier applied to the effective visual relief. If omitted, rayshader uses the cached scene value from plot_3d() or plot_gg() when available; pass explicitly to override for this call.

heightmap

Default NULL. Height matrix for the current scene. If omitted, this is taken from the cached scene set by plot_3d() or plot_gg(). Pass explicitly to override the cached value. of matrix extent isn't working. A two-dimensional matrix, where each entry in the matrix is the elevation at that point. All points are assumed to be evenly spaced.

...

Additional arguments to pass to rgl::triangles3d().

Examples

# This function can also create fake "terrain" from polygons by visualizing the distance
# to the nearest edge.

#Render the county borders as polygons in Monterey Bay as terrain
montereybay_spatial |>
  sphere_shade(texture = "desert",vertical_exaggeration = 20) |>
  add_shadow(ray_shade(vertical_exaggeration = 4)) |>
  plot_3d(water = TRUE, window_size = 800, water_color = "dodgerblue",
          background = "pink", vertical_exaggeration = 4)

#We will apply a negative buffer to create space between adjacent polygons. You may
#have to call `sf::sf_use_s2(FALSE)` before running this code to get it to run.
sf::sf_use_s2(FALSE)
mont_county_buff = sf::st_simplify(sf::st_buffer(monterey_counties_sf,-0.003), dTolerance=0.001)

render_beveled_polygons(mont_county_buff,  flat_shading  = TRUE, angle = 45 ,
                        bevel_width=300, material = "red", clear_previous = TRUE,
                        bevel_height = 800, base_height=0)
render_camera(theta = 0,  phi = 90, zoom = 0.65, fov = 0)
render_snapshot()
render_camera(theta=194, phi= 35,   zoom = 0.5, fov= 80)
render_snapshot()

# Changing the color of the beveled top and reduce the angle
render_beveled_polygons(mont_county_buff,  flat_shading  = TRUE, angle = 15 ,
                        bevel_width=300, material = "tan",
                        bevel_material = "darkgreen", clear_previous=TRUE,
                        bevel_height = 1000, base_height=0)
render_snapshot()
# We can create a nice curved surface by passing in a bevel generated with the
# `raybevel::generate_bevel()` function.
render_beveled_polygons(mont_county_buff, flat_shading  = TRUE,
                        bevel = raybevel::generate_bevel("exp",bevel_end = 0.4),
                        material = rayvertex::material_list(diffuse="red",
                                                            ambient = "darkred",
                                                            diffuse_intensity = 0.2,
                                                            ambient_intensity = 0.1),
                        light_intensity = 1, light_relative = FALSE,
                        bevel_height = 1000,
                        base_height=0, clear_previous = TRUE)
render_snapshot()

# While the bevels all start at the same point in the above example,
# they rise to different levels due to being scaled by the maximum internal distance
# in the polygon. Setting `scale_all_max = TRUE` ensures the bevels are all scaled to the
# same maximum height (in this case, 1500m above the 1000m bevel start height).
render_beveled_polygons(mont_county_buff, flat_shading  = TRUE,
                 bevel = raybevel::generate_bevel("exp",bevel_end = 0.4),
                 max_height = 1500, scale_all_max = TRUE, set_max_height = TRUE,
                 material = rayvertex::material_list(diffuse="red",
                                                     ambient = "darkred",
                                                     diffuse_intensity = 0.2,
                                                     ambient_intensity = 0.1),
                 light_intensity = 1, light_relative = FALSE,
                 bevel_height = 500,
                 base_height=0, clear_previous = TRUE)
render_snapshot()

# Rendering the polygons with `render_highquality()`
poly_material = rayrender::glossy(color = "#900",gloss=0.4)
render_highquality(rgl_materials =  list("obj_raymesh_beveled_polygon" = poly_material))

# We can scale the size of the polygon to a column in the `sf` object as well:
# raybevel::generate_bevel() function. We can scale this data down using the `scale_data`
# argument. Note that this is applied in scene units, and that you
# must think carefully about your scales and values if trying to represent a meaningful
# data visualization with this object.
render_beveled_polygons(mont_county_buff,  flat_shading  = TRUE, angle = 45, bevel_width=100,
                 data_column_top = "ALAND", scale_data = 2e-6,
                 material = rayvertex::material_list(diffuse="red"),
                 light_intensity = 1, light_relative = FALSE,
                 clear_previous = TRUE)
render_zaxis(data = "beveled_polygon")
render_camera(theta=194, phi= 35,   zoom = 0.7, fov= 80)
render_highquality(rgl_materials = list("obj_raymesh_beveled_polygon" = poly_material))

Render Buildings

Description

Adds 3D polygons with roofs to the current scene, using latitude/longitude or coordinates in the reference system defined by the extent object.

Cache fallback messages are disabled by default. Set options(rayshader.verbose_scene_cache = TRUE) to print when cached metadata is reused.

Usage

render_buildings(
  polygon,
  material = "grey",
  roof_material = NA,
  angle = 45,
  scale_data = 1,
  relative_heights = TRUE,
  heights_relative_to_centroid = FALSE,
  roof_height = 1,
  base_height = 0,
  data_column_top = NULL,
  data_column_bottom = NULL,
  holes = 0,
  alpha = 1,
  lit = TRUE,
  flat_shading = FALSE,
  light_altitude = c(45, 30),
  light_direction = c(315, 225),
  light_intensity = 1,
  light_relative = FALSE,
  clear_previous = FALSE,
  crs = NULL,
  filter_to_extent = TRUE,
  extent = NULL,
  panel = NULL,
  zscale = 1,
  vertical_exaggeration = 1,
  heightmap = NULL,
  ...
)

Arguments

polygon

sf object, "SpatialPolygon" sp object, or xy coordinates of polygon represented in a way that can be processed by xy.coords(). If xy-coordinate based polygons are open, they will be closed by adding an edge from the last point to the first.

material

Default "grey80". If a color string, this will specify the color of the sides/base of the building Alternatively (for more customization), this can be a rayvertex::material_list() object to specify the full color/appearance/material options for the resulting ray_mesh mesh.

roof_material

Default NA, defaults to the material specified in material. If a color string, this will specify the color of the roof of the building. Alternatively (for more customization), this can be a rayvertex::material_list() object to specify the full color/appearance/material options for the resulting ray_mesh mesh.

angle

Default 45. Angle of the roof.

scale_data

Default 1. How much to scale the top/bottom value when rendering. Use zscale to adjust the data to account for x/y grid spacing, and this argument to scale the data for visualization. If used with vertical_exaggeration, both are applied.

relative_heights

Default TRUE. Whether the heights specified in roof_height and base_height should be measured relative to the underlying heightmap.

heights_relative_to_centroid

Default FALSE. Whether the heights should be measured in absolute terms, or relative to the centroid of the polygon.

roof_height

Default 1. Height from the base of the building to the start of the roof.

base_height

Default 0. Height of the base of the roof.

data_column_top

Default NULL. A string indicating the column in the sf object to use to specify the top of the extruded polygon. Values are coerced to numeric, and rows with missing or non-finite values after coercion are omitted.

data_column_bottom

Default NULL. A string indicating the column in the sf object to use to specify the bottom of the extruded polygon. Values are coerced to numeric, and rows with missing or non-finite values after coercion are omitted.

holes

Default 0. If passing in a polygon directly, this specifies which index represents the holes in the polygon. See the earcut function in the decido package for more information.

alpha

Default 1. Transparency of the polygons.

lit

Default TRUE. Whether to light the polygons.

flat_shading

Default FALSE. Set to TRUE to have nicer shading on the 3D polygons. This comes with the slight penalty of increasing the memory use of the scene due to vertex duplication. This will not affect software or high quality renders.

light_altitude

Default c(45, 30). Degree(s) from the horizon from which to light the polygons.

light_direction

Default c(315, 225). Degree(s) from north from which to light the polygons.

light_intensity

Default 1. Intensity of the specular highlight on the polygons.

light_relative

Default FALSE. Whether the light direction should be taken relative to the camera, or absolute.

clear_previous

Default FALSE. If TRUE, clears all existing buildings. A clear-only call returns without rendering a replacement.

crs

Default NULL. CRS of the input numeric x/y coordinates, or CRS to assign to CRS-less spatial data before transforming it into the active scene CRS. If spatial data already carries a CRS, that CRS is used automatically.

filter_to_extent

Default TRUE. If TRUE, building footprint data outside the scene extent is omitted. Spatial polygon inputs are cropped to the extent. For scenes created with plot_gg(), filtering uses the ggplot panel extent rather than the full rendered 3D ggplot extent.

extent

Either an object representing the spatial extent of the 3D scene (either from the raster, terra, sf, or sp packages), a length-4 numeric vector specifying c("xmin", "xmax", "ymin", "ymax"), or the spatial object (from the previously aforementioned packages) which will be automatically converted to an extent object. If omitted, rayshader will use extent metadata cached by plot_3d() or plot_gg().

panel

Default NULL. Facet panel identifier for scenes created with plot_gg(). Required to disambiguate faceted ggplot scenes when panel-specific cached metadata is needed. Ignored for non-ggplot scenes.

zscale

Default 1. The ratio between the x and y spacing (which are assumed to be equal) and the z axis in the original heightmap.

vertical_exaggeration

Default 1. Multiplier applied to the effective visual relief. If omitted, rayshader uses the cached scene value from plot_3d() or plot_gg() when available; pass explicitly to override for this call.

heightmap

Default NULL. Height matrix for the current scene. If omitted, this is taken from the cached scene set by plot_3d() or plot_gg(). Pass explicitly to override the cached value. of matrix extent isn't working. A two-dimensional matrix, where each entry in the matrix is the elevation at that point. All points are assumed to be evenly spaced.

...

Additional arguments to pass to rgl::triangles3d().

Examples

# Load and visualize building footprints from Overture Maps
library(DBI)
library(duckdb)
library(sf)
library(jsonlite)

# Define the WGS84 bounding box for the scene in St. John's, Newfoundland.
overture_bbox = c(-52.718925, 47.552085, -52.666397, 47.586194)
scene_bbox = c(
  xmin = overture_bbox[1],
  ymin = overture_bbox[2],
  xmax = overture_bbox[3],
  ymax = overture_bbox[4]
)

# Query a slightly padded area so roads and buildings that cross the scene
# boundary are included before rayshader crops them to the rendered extent.
query_padding = 0.001

query_bbox = c(
  xmin = scene_bbox[["xmin"]] - query_padding,
  ymin = scene_bbox[["ymin"]] - query_padding,
  xmax = scene_bbox[["xmax"]] + query_padding,
  ymax = scene_bbox[["ymax"]] + query_padding
)

# Keep an sf polygon for DEM retrieval and for documenting the exact render area.
scene_area = sf::st_sf(
  geometry = sf::st_as_sfc(sf::st_bbox(scene_bbox, crs = sf::st_crs(4326)))
)

# Discover the current Overture release and build Parquet paths for the
# building and transportation layers.
overture_release = jsonlite::fromJSON(
  "https://stac.overturemaps.org/catalog.json"
)$latest

base_string = "az://overturemapswestus2.blob.core.windows.net/release"

building_uri = sprintf(
  "%s/%s/theme=buildings/type=building/*.parquet",
  base_string,
  overture_release
)

road_uri = sprintf(
  "%s/%s/theme=transportation/type=segment/*.parquet",
  base_string,
  overture_release
)

# Query the remote Parquet files in memory. The Overture geometry column is
# returned as WKB so sf can reconstruct the features locally.
con = DBI::dbConnect(duckdb::duckdb(), dbdir = ":memory:")

# Select buildings whose feature bounding boxes intersect the padded
# query area, including buildings that cross the boundary.
building_query = sprintf(
  "
SELECT
  id,
  height,
  num_floors,
  ST_AsWKB(geometry)::BLOB AS geometry
FROM read_parquet('%s', filename = false, hive_partitioning = 1)
WHERE
  bbox.xmin <= %.10f
  AND bbox.xmax >= %.10f
  AND bbox.ymin <= %.10f
  AND bbox.ymax >= %.10f
",
  building_uri,
  query_bbox[["xmax"]],
  query_bbox[["xmin"]],
  query_bbox[["ymax"]],
  query_bbox[["ymin"]]
)

building_df = DBI::dbGetQuery(con, building_query)

building_geom = sf::st_as_sfc(
  structure(building_df$geometry, class = "WKB"),
  crs = 4326
)

building_df$geometry = NULL

building_polys = sf::st_sf(
  building_df,
  geometry = building_geom,
  crs = 4326
)

# Select road segments whose feature bounding boxes intersect the padded
# query area, including roads that cross the boundary.
road_query = sprintf(
  "
SELECT
  id,
  names.primary AS name,
  class AS road_class,
  subclass AS road_subclass,
  ST_AsWKB(geometry)::BLOB AS geometry
FROM read_parquet('%s', filename = false, hive_partitioning = 1)
WHERE
  subtype = 'road'
  AND bbox.xmin <= %.10f
  AND bbox.xmax >= %.10f
  AND bbox.ymin <= %.10f
  AND bbox.ymax >= %.10f
",
  road_uri,
  query_bbox[["xmax"]],
  query_bbox[["xmin"]],
  query_bbox[["ymax"]],
  query_bbox[["ymin"]]
)

road_df = DBI::dbGetQuery(con, road_query)

road_geom = sf::st_as_sfc(
  structure(road_df$geometry, class = "WKB"),
  crs = 4326
)

road_df$geometry = NULL

road_lines = sf::st_sf(
  road_df,
  geometry = road_geom,
  crs = 4326
)

# Close the in-memory DuckDB connection after all remote data is loaded.
DBI::dbDisconnect(con, shutdown = TRUE)

# Fetch elevation for the render area, then crop it to the building footprint
# extent. rayshader caches the cropped DEM extent so overlay and render calls
# can omit extent/heightmap.
scene_dem = elevatr::get_elev_raster(scene_area, z = 11, clip = "bbox")
building_extent = sf::st_bbox(building_polys)
terrain_dem = terra::crop(
  terra::rast(scene_dem),
  terra::ext(
    building_extent[["xmin"]],
    building_extent[["xmax"]],
    building_extent[["ymin"]],
    building_extent[["ymax"]]
  )
)

# Create a shaded terrain image, then draw building footprints and roads over
# it before opening the 3D scene.
terrain_dem |>
  sphere_shade(texture = "imhof4", vertical_exaggeration = 20) |>
  add_overlay(
    generate_polygon_overlay(
      building_polys,
      linewidth = 6,
      resolution_multiply = 50
    ),
    rescale_original = TRUE
  ) |>
  add_overlay(
    generate_line_overlay(
      road_lines,
      linewidth = 6,
      resolution_multiply = 50
    ),
    rescale_original = TRUE
  ) |>
  plot_3d(
    water = TRUE,
    water_input = 0.5,
    window_size = 800,
    water_color = "dodgerblue",
    background = "pink"
  )

# Overture building heights are sometimes missing. Fill those gaps before
# using the height column to drive roof elevation.
building_polys |>
  dplyr::mutate(height = dplyr::if_else(is.na(height), mean(height, na.rm = TRUE), height)) ->
building_poly_fixed

# Render buildings
render_buildings(
  building_poly_fixed,
  flat_shading = TRUE,
  lit = FALSE,
  angle = 30,
  material = "white",
  roof_material = "white",
  roof_height = 3,
  base_height = 0,
  data_column_top = "height",
  relative_heights = TRUE
)
#Render a label
render_label(long = c(building_extent[1]+building_extent[3])/2,
             lat =  c(building_extent[2]+building_extent[4])/2,
             text = "St. Johns, Newfoundland",
             text_color = "white",
             altitude = 100
)

render_camera(theta = 220, phi = 45, zoom = 0.55, fov = 0)
render_snapshot()

# Zoom in to show roof details and render with render_highquality()
render_camera(fov = 120,zoom=0.7)

# Generate an evening sky in the winter. The camera location and direction
# were determined using an interactive render_highquality() session by
# hitting the P key with the camera in the desired position.
render_highquality(
camera_location = c(-8.17, 7.70, 15.09),
camera_lookat = c(-1.09, -2.25, -3.63),
samples = 100,
iso = 100 / 30,
datetime = as.POSIXct("2025-01-01 14:00:00", tz = "America/St_Johns"),
sky_args = list(hosek = FALSE)
)

Render Camera

Description

Changes the position and properties of the camera around the scene. location can move the camera's look-at target to scene x/y coordinates or a spatial point. lat and long move it to a geographic point. These inputs use the active scene's cached CRS, extent, heightmap, and effective z-scale as needed. If no values are entered, prints and returns the current camera values.

Usage

render_camera(
  location = NULL,
  theta = NULL,
  phi = NULL,
  zoom = NULL,
  fov = NULL,
  altitude = NULL,
  shift_vertical = 0,
  lat = NULL,
  long = NULL,
  panel = NULL
)

Arguments

location

Default NULL. A numeric c(x, y) pair in the scene's cached extent, or a single spatial POINT to use as the camera's look-at target. Spatial inputs accept sf, sfc, sfg, and sp objects and are transformed to the active scene CRS. If a spatial input contains a Z coordinate or an altitude, alt, elevation, or z column, that value sets the target height; otherwise, the target height is sampled from the cached heightmap. Cannot be combined with lat or long.

theta

Defaults to current value. Rotation angle.

phi

Defaults to current value. Azimuth angle. Maximum 90.

zoom

Defaults to current value. Positive value indicating camera magnification.

fov

Defaults to current value. Field of view of the camera. Maximum 180.

altitude

Default NULL. Elevation of the look-at target in the scene's elevation units. The value is converted to rgl coordinates using the cached effective z-scale. Requires location or both lat and long. When supplied with location, it overrides elevation embedded in the spatial input.

shift_vertical

Default 0. Amount to shift the viewpoint.

lat

Default NULL. Latitude in WGS84 decimal degrees for the camera's look-at target. Must be supplied with long.

long

Default NULL. Longitude in WGS84 decimal degrees for the camera's look-at target. Must be supplied with lat.

panel

Default NULL. Facet panel identifier for scenes created with plot_gg(). Required when the cached scene contains multiple panels.

Examples

montereybay_spatial |>
 sphere_shade(vertical_exaggeration = 10) |>
 plot_3d(vertical_exaggeration = 4, water = TRUE, water_line_color="white")
render_snapshot()

#Shift the camera over and add a title
render_camera(theta = -45, phi = 45)
render_snapshot(title_text = "Monterey Bay, CA",
               title_bar_color = "grey50")

#Move the camera's look-at target to Moss Landing using the cached scene CRS.
if (requireNamespace("sf", quietly = TRUE)) {
 render_camera(lat = 36.806807, long = -121.793332, altitude = 100)
}

#Shift to an overhead view (and change the text/title bar color)
render_camera(theta = 0, phi = 89.9, zoom = 0.9)
render_snapshot(title_text = "Monterey Bay, CA",
               title_color = "white",
               title_bar_color = "darkgreen")

#Shift to an front view and add a vignette effect
render_camera(theta = -90, phi = 30,zoom = 0.8)
render_snapshot(title_text = "Monterey Bay, CA",
               title_color = "white",
               title_bar_color = "blue",
               vignette = TRUE)

#Change the field of view (fov) and make the title bar opaque.
render_camera(theta = -90, phi = 30,zoom = 0.5,fov = 130)
render_snapshot(title_text = "Monterey Bay, CA",
               title_color = "black",
               title_bar_alpha = 1,
               title_bar_color = "lightblue",
               vignette = TRUE)

#Here we render a series of frames to later stitch together into a movie.

phivec = 20 + 70 * 1/(1 + exp(seq(-5, 10, length.out = 180)))
phivecfull = c(phivec, rev(phivec))
thetavec = 270 + 45 * sin(seq(0,359,length.out = 360) * pi/180)
zoomvechalf = 0.5 + 0.5 * 1/(1 + exp(seq(-5, 10, length.out = 180)))
zoomvec = c(zoomvechalf, rev(zoomvechalf))

for(i in 1:360) {
 render_camera(theta = thetavec[i],phi = phivecfull[i],zoom = zoomvec[i])
 #uncomment the next line to save each frame to the working directory
 #render_snapshot(paste0("frame", i, ".png"))
}
#Run this command in the command line using ffmpeg to stitch together a video:
#ffmpeg -framerate 60 -i frame%d.png -vcodec libx264 raymovie.mp4

#And run this command to convert the video to post to the web:
#ffmpeg -i raymovie.mp4 -pix_fmt yuv420p -profile:v baseline -level 3 -vf scale=-2:-2 rayweb.mp4

#Or we can use render_movie() to do this all automatically with type="custom" (uncomment to run):
#render_movie(filename = tempfile(fileext = ".mp4"), type = "custom",
#             theta = thetavec, phi = phivecfull, zoom = zoomvec, fov=0)

Render Clouds

Description

Render a 3D floating cloud layer of the map.

Cache fallback messages are disabled by default. Set options(rayshader.verbose_scene_cache = TRUE) to print when cached metadata is reused.

Note: Underlying layers with transparency can cause rendering issues in rgl.

Usage

render_clouds(
  start_altitude = 1000,
  end_altitude = 2000,
  sun_altitude = 10,
  sun_angle = 315,
  time = 0,
  cloud_cover = 0.5,
  layers = 10,
  offset_x = 0,
  offset_y = 0,
  scale_x = 1,
  scale_y = 1,
  scale_z = 1,
  frequency = 0.005,
  fractal_levels = 16,
  attenuation_coef = 1,
  seed = 1,
  clear_clouds = FALSE,
  zscale = 1,
  vertical_exaggeration = 1,
  heightmap = NULL
)

Arguments

start_altitude

Default 1000. The bottom of the cloud layer.

end_altitude

Default 2000. The top of the cloud layer.

sun_altitude

Default 90. The angle, in degrees (as measured from the horizon) from which the light originates.

sun_angle

Default 315 (NW). The angle, in degrees, around the matrix from which the light originates. Zero degrees is North, increasing clockwise

time

Default 0. Advance this to make the clouds evolve and change in shape.

cloud_cover

Default 0.5. The percentage of cloud cover.

layers

Default 10. The number of layers to render the cloud layer. The default is layers/(start_altitude - end_altitude).

offset_x

Default 0. Change this to move the cloud layer sideways.

offset_y

Default 0. Change this to move the cloud layer backwards and forwards.

scale_x

Default 1. Scale the fractal pattern in the x direction.

scale_y

Default 1. Scale the fractal pattern in the y direction.

scale_z

Default 1. Scale the fractal pattern in the z (vertical) direction. (automatically calculated). Scale the fractal pattern in the z (vertical) direction.

frequency

Default 0.005. The base frequency of the noise used to calculate the fractal cloud structure.

fractal_levels

Default 16. The fractal dimension used to calculate the noise. Higher values give more fine structure, but take longer to calculate.

attenuation_coef

Default 1. Amount of attenuation in the cloud (higher numbers give darker shadows). This value is automatically scaled to account for increasing the number of layers.

seed

Default 1. Random seed used to generate clouds.

clear_clouds

Default FALSE. Clears all existing floating layers on the visualization.

zscale

Default 1. The ratio between the x and y spacing (which are assumed to be equal) and the z axis. For example, if the elevation levels are in units of 1 meter and the grid values are separated by 10 meters, zscale would be 10.

vertical_exaggeration

Default 1. Multiplier applied to the effective visual relief. If omitted, rayshader uses the cached scene value from plot_3d() or plot_gg() when available; pass explicitly to override for this call.

heightmap

Default NULL. Height matrix whose existing NA cells mask the cloud layers. If omitted, this is taken from the cached scene set by plot_3d() or plot_gg(). Pass explicitly to override the cached value.

Value

Adds a 3D floating cloud layer to the map. No return value.

Examples

#Render a cloud layer over Monterey Bay
montereybay_spatial  |>
 sphere_shade(vertical_exaggeration = 10)  |>
 plot_3d(background="brown", vertical_exaggeration = 4)

#Render some clouds
render_clouds()
render_snapshot()
#Change the seed for a different set of clouds and add cloud shadows on the ground
montereybay_spatial  |>
 sphere_shade(vertical_exaggeration = 10)  |>
 add_shadow(cloud_shade(vertical_exaggeration = 4, seed = 2), 0.0) |>
 plot_3d(background="brown", vertical_exaggeration = 4)
render_camera(theta=-65, phi = 25, zoom = 0.45, fov = 80)
render_clouds(seed=2, clear_clouds = T)
render_snapshot()

montereybay_spatial  |>
 sphere_shade(vertical_exaggeration = 10)  |>
 plot_3d(background="brown", vertical_exaggeration = 4)

#Lower the frequency for larger, smoother clouds
render_clouds(frequency = 0.001, clear_clouds = T)
render_snapshot()
#Increase the frequency for more broken clouds
render_clouds(frequency = 0.05, clear_clouds = T)
render_snapshot()
#Increase the fractal level for fluffier, bumpier clouds
render_clouds(fractal_levels = 32, clear_clouds = T)
render_snapshot()
#Decrease the fractal level for more smoother, continuous clouds
render_clouds(fractal_levels = 4, clear_clouds = T)
render_snapshot()
#Increase the cloud cover
render_clouds(cloud_cover=0.8, clear_clouds = T)
render_snapshot()
#Decrease the cloud cover
render_clouds(cloud_cover=0.2, clear_clouds = T)
render_snapshot()
#Change the altitude range of the clouds
render_clouds(start_altitude=2000,end_altitude = 4000, clear_clouds = T)
render_snapshot()
#Increase the number of layers
render_clouds(start_altitude=2000,end_altitude = 4000, layers = 20,
             clear_clouds = T)
render_snapshot()
#Change the sun angle and altitude, and increase the attenuation for darker clouds
render_clouds(sun_angle=45, sun_altitude= 5, attenuation_coef = 5,
             clear_clouds = T)
render_snapshot()
#The cloud layers automatically follow the shaped heightmap's NA mask
montereybay_spatial  |>
 sphere_shade(vertical_exaggeration = 10)  |>
 plot_3d(background="darkred", vertical_exaggeration = 4, base_shape="hex")
render_clouds(seed=3, clear_clouds = T)
render_camera(zoom=0.65)
render_snapshot()

Render Compass Symbol

Description

Places a compass on the map to specify the North direction.

Cache fallback messages are disabled by default. Set options(rayshader.verbose_scene_cache = TRUE) to print when cached metadata is reused.

Usage

render_compass(
  angle = 0,
  position = "SE",
  compass_radius = NULL,
  scale_distance = 1,
  color_n = "darkred",
  color_arrow = "grey90",
  color_background = "grey60",
  color_bevel = "grey20",
  position_circular = FALSE,
  clear_compass = FALSE,
  x = NULL,
  y = NULL,
  z = NULL,
  altitude = NULL,
  zscale = 1,
  vertical_exaggeration = 1
)

Arguments

angle

Default 0. The direction the arrow should be facing. When omitted, rayshader rotates grid north to true north using cached metadata.

position

Default SE. A string representing a cardinal direction. Ignored if x, y, and z are manually specified.

compass_radius

Default NULL. The radius of the compass. If not entered, automatically calculated. Increase or decrease the size of the compass.

scale_distance

Default 1. Multiplier that moves the compass away from the center of the map.

color_n

Default darkred. Color of the letter N.

color_arrow

Default grey90. Color of the arrow.

color_background

Default grey20. Color of the area right under the arrow.

color_bevel

Default grey20. Color of the bevel.

position_circular

Default FALSE. If TRUE, will place compass at a constant radius away from the map, as opposed to directly next to it. Overridden if user manually specifies position.

clear_compass

Default FALSE. Clears the compass symbol(s) on the map.

x

Default NULL. X position. If not entered, automatically calculated using position argument.

y

Default NULL. Y position. If not entered, automatically calculated using position argument.

z

Default NULL. Z position. If not entered, automatically calculated using position argument.

altitude

Default NULL. Altitude of the compass, defaults to maximum height in the map.

zscale

Default 1. The ratio between the x and y spacing (which are assumed to be equal) and the z axis. Only used in combination with altitude.

vertical_exaggeration

Default 1. Multiplier applied to the effective visual relief. If omitted, rayshader uses the cached scene value from plot_3d() or plot_gg() when available; pass explicitly to override for this call.

Value

Adds compass to map. No return value.

Examples

#Add a North arrow to the map, by default in the bottom right (SE)
montereybay_spatial |>
 sphere_shade(vertical_exaggeration = 10) |>
 plot_3d(theta=-45, water=TRUE, vertical_exaggeration = 4)
render_compass()
render_snapshot()
#Remove the existing symbol with `clear_compass = TRUE`
render_compass(clear_compass = TRUE)

#Point the N towards the light, at 315 degrees:
render_compass(angle = 315)
render_snapshot()
render_compass(clear_compass = TRUE)

#We can change the position by specifying a direction (here are three):
render_camera(theta=45,phi=45)
render_compass(position = "NW")
render_compass(position = "E")
render_compass(position = "S")
render_snapshot()
render_compass(clear_compass = TRUE)

#We can also change the distance away from the edge by setting the `scale_distance` argument.
render_compass(position = "NW", scale_distance = 1.4)
render_compass(position = "E", scale_distance = 1.4)
render_compass(position = "S", scale_distance = 1.4)

#Zoom in slightly:
render_camera(theta=45,phi=45,zoom=0.7)
render_snapshot()
render_compass(clear_compass = TRUE)

#We can also specify the radius directly with `compass_radius`:
render_camera(theta=0,phi=45,zoom=1)
render_compass(position = "N", scale_distance = 1.5, compass_radius=200)
render_compass(position = "E", scale_distance = 1.4, compass_radius=50)
render_compass(position = "S", scale_distance = 1.3, compass_radius=25)
render_compass(position = "W", scale_distance = 1.2, compass_radius=10)
render_snapshot()

render_compass(clear_compass = TRUE)
#We can also adjust the position manually, be specifying all x, y and z arguments.
render_camera(theta=-45,phi=45,zoom=0.9)
render_compass(x = 150, y = 50, z = 150)
render_snapshot()
# Compass support is also included in render_highquality()
render_highquality(min_variance = 0, samples = 16)
render_compass(clear_compass = TRUE)

#We can change the colors in the compass, and also set it a constant distance away with
#`position_circular = TRUE`:

render_camera(theta=0,phi=45,zoom=0.75)
render_compass(position = "N", color_n = "#55967a", color_arrow = "#fff673",
            color_background = "#cfe0a9", color_bevel = "#8fb28a", position_circular = TRUE)
render_compass(position = "NE", color_n = "black", color_arrow = "grey90",
            color_background = "grey50", color_bevel = "grey20", position_circular = TRUE)
render_compass(position = "E", color_n = "red", color_arrow = "blue",
            color_background = "yellow", color_bevel = "purple", position_circular = TRUE)
render_compass(position = "SE", color_n = c(0.7,0.5,0.9), color_arrow = c(0.8,0.8,1),
            color_background = c(0.2,0.2,1), color_bevel = c(0.6,0.4,0.6),
            position_circular = TRUE)
render_compass(position = "S", color_n = "#ffe3b3", color_arrow = "#6a463a",
            color_background = "#abaf98", color_bevel = "grey20", position_circular = TRUE)
render_compass(position = "SW", color_n = "#ffe3a3", color_arrow = "#f1c3a9",
            color_background = "#abaf98", color_bevel = "#66615e", position_circular = TRUE)
render_compass(position = "W", color_n = "#e9e671", color_arrow = "#cbb387",
            color_background = "#7c9695", color_bevel = "#cbb387", position_circular = TRUE)
render_compass(position = "NW", color_n = c(0.7,0,0), color_arrow = c(0.3,0,0),
            color_background = c(0.7,0.5,0.5), color_bevel = c(0.2,0,0), position_circular = TRUE)
render_snapshot()

Render Contours

Description

Adds 3D contours to the current scene, using the heightmap of the 3D surface.

Cache fallback messages are disabled by default. Set options(rayshader.verbose_scene_cache = TRUE) to print when cached metadata is reused.

Usage

render_contours(
  levels = NA,
  n_levels = NA,
  linewidth = 1,
  color = "black",
  palette = NULL,
  antialias = FALSE,
  offset = 0,
  clear_previous = FALSE,
  zscale = 1,
  vertical_exaggeration = 1,
  heightmap = NULL,
  ...
)

Arguments

levels

Default NA. Automatically generated with 10 levels. This argument specifies the exact height levels of each contour.

n_levels

Default NA. Controls the auto-generation of levels. If levels is length-2, this will automatically generate n_levels breaks between levels[1] and levels[2].

linewidth

Default 3. The line width.

color

Default black. Color of the line. Use "height" to color contours by the cached plot_gg() height aesthetic palette.

palette

Default NULL. Overrides color. Either a function that returns a color palette of n colors, or a character vector with colors that specifies each color manually.

antialias

Default FALSE. If TRUE, the line with be have anti-aliasing applied. NOTE: anti-aliasing can cause some unpredictable behavior with transparent surfaces.

offset

Default 5. Offset of the track from the surface, if altitude = NULL.

clear_previous

Default FALSE. If TRUE, clears all existing contours. A clear-only call returns without rendering a replacement.

zscale

Default 1. The ratio between the x and y spacing (which are assumed to be equal) and the z axis. For example, if the elevation levels are in units of 1 meter and the grid values are separated by 10 meters, zscale would be 10.

vertical_exaggeration

Default 1. Multiplier applied to the effective visual relief. If omitted, rayshader uses the cached scene value from plot_3d() or plot_gg() when available; pass explicitly to override for this call.

heightmap

Default NULL. Height matrix for the current scene. If omitted, this is taken from the cached scene set by plot_3d() or plot_gg(). Pass explicitly to override the cached value.

...

Additional arguments passed to rgl::lines3d(). Deprecated argument spellings are accepted with a warning and forwarded to their current names.

Examples

#Add contours to the montereybay_spatial dataset
montereybay_spatial |>
 height_shade() |>
 add_shadow(ray_shade(),0.3) |>
 plot_3d(theta = -45,  zoom=0.9, window_size=800, vertical_exaggeration = 4)
render_contours(offset = 100)
render_snapshot()

#Specify the number of levels
render_contours(offset = 100, n_levels = 30,
               clear_previous = TRUE)
render_snapshot()

#Manually specify the breaks with levels
render_contours(linewidth = 2,  offset = 100,
               levels = seq(-2000, 0, 100), clear_previous = TRUE)
render_snapshot()

#Use a color palette for the contours
volcano |>
 constant_shade() |>
 plot_3d(zscale = 2, solid = FALSE, zoom = 0.8)
palette = grDevices::colorRampPalette(c("red", "purple", "pink"))
render_contours(offset = 1, palette = palette, n_levels = 20)
render_snapshot()

#Render using `render_highquality()` for a neon light effect
render_highquality(light = FALSE, samples = 16,
                  line_radius = 0.1,
                  ground_size = 0,
                  rgl_materials = list(contour3d = list(
                    material = rayrender::light,
                    args = list(importance_sample = FALSE,
                                color = "purple", intensity = 2)
                  )))

Render Depth of Field

Description

Adds depth of field to the current RGL scene by simulating a synthetic aperture.

Cache fallback messages are disabled by default. Set options(rayshader.verbose_scene_cache = TRUE) to print when cached metadata is reused.

The size of the circle of confusion is determined by the following formula (z_depth is from the image's depth map).

abs(z_depth-focus)*focal_length^2/(f_stop*z_depth*(focus - focal_length))

Usage

render_depth(
  focus = NULL,
  focal_length = 100,
  f_stop = 4,
  filename = NULL,
  preview_focus = FALSE,
  bokeh_shape = "circle",
  bokeh_intensity = 1,
  bokeh_limit = 0.8,
  rotation = 0,
  aberration = 0,
  transparent_water = FALSE,
  title_text = NULL,
  title_offset = c(20, 20),
  title_color = "black",
  title_size = 30,
  title_font = "sans",
  title_bar_color = NA,
  title_bar_alpha = 0.5,
  title_just = "left",
  image_overlay = NULL,
  vignette = FALSE,
  vignette_color = "black",
  vignette_radius = 1.3,
  progress_bar = interactive(),
  software_render = FALSE,
  width = NULL,
  height = NULL,
  camera_location = NULL,
  camera_lookat = c(0, 0, 0),
  background = "white",
  text_angle = NULL,
  text_size = 10,
  text_offset = c(0, 0, 0),
  point_radius = 0.5,
  line_offset = 1e-07,
  print_scene_info = FALSE,
  verbose = FALSE,
  instant_capture = interactive(),
  clear = FALSE,
  bring_to_front = FALSE,
  heightmap = NULL,
  zscale = NULL,
  cache_scene = FALSE,
  reset_scene_cache = FALSE,
  ...
)

Arguments

focus

Focal point. Defaults to the center of the bounding box. Depth in which to blur, in distance to the camera plane.

focal_length

Default 1. Focal length of the virtual camera.

f_stop

Default 1. F-stop of the virtual camera.

filename

The filename of the image to be saved. If this is not given, the image will be plotted instead.

preview_focus

Default FALSE. If TRUE, a red line will be drawn across the image showing where the camera will be focused.

bokeh_shape

Default circle. Also built-in: hex. The shape of the bokeh.

bokeh_intensity

Default 3. Intensity of the bokeh when the pixel intensity is greater than bokeh_limit.

bokeh_limit

Default 0.8. Limit after which the bokeh intensity is increased by bokeh_intensity.

rotation

Default 0. Number of degrees to rotate the hexagon bokeh shape.

aberration

Default 0. Adds chromatic aberration to the image. Maximum of 1.

transparent_water

Default FALSE. If TRUE, depth is determined without water layer. User will have to re-render the water layer from the active rgl subscene while capturing the depth map, then restores it.

title_text

Default NULL. Text. Adds a title to the image, using magick::image_annotate.

title_offset

Default c(20,20). Distance from the top-left (default, gravity direction in image_annotate) corner to offset the title.

title_color

Default black. Font color.

title_size

Default 30. Font size in pixels.

title_font

Default sans. String with font family such as "sans", "mono", "serif", "Times", "Helvetica", "Trebuchet", "Georgia", "Palatino" or "Comic Sans".

title_bar_color

Default NA. If a color, this will create a colored bar under the title.

title_bar_alpha

Default 0.5. Transparency of the title bar.

title_just

Default left. Justification of the title.

image_overlay

Default NULL. Either a string indicating the location of a png image to overlay over the image (transparency included), or a 4-layer RGBA array. This image will be resized to the dimension of the image if it does not match exactly.

vignette

Default FALSE. If TRUE or numeric, a camera vignetting effect will be added to the image. 1 is the darkest vignetting, while 0 is no vignetting. If vignette is a length-2 vector, the second entry will control the blurriness of the vignette effect.

vignette_color

Default "black". Color of the vignette.

vignette_radius

Default 1.3. Radius of the vignette, as a porportion of the image dimensions.

progress_bar

Default TRUE if in an interactive session. Displays a progress bar.

software_render

Default FALSE. If TRUE, rayshader will use the rayvertex package to render the snapshot, which is not constrained by the screen size or requires OpenGL.

width

Default NULL. Optional argument to pass to rgl::snapshot3d() to specify the width when software_render = TRUE..

height

Default NULL. Optional argument to pass to rgl::snapshot3d() to specify the height when software_render = TRUE.

camera_location

Default NULL. Custom position of the camera. The FOV, width, and height arguments will still be derived from the rgl window.

camera_lookat

Default NULL. Custom point at which the camera is directed. The FOV, width, and height arguments will still be derived from the rgl window.

background

Default "white". Background color when software_render = TRUE.

text_angle

Default NULL, which forces the text always to face the camera. If a single angle (degrees), will specify the absolute angle all the labels are facing. If three angles, this will specify all three orientations (relative to the x,y, and z axes) of the text labels.

text_size

Default 10. Height of the text.

text_offset

Default c(0,0,0). Offset to be applied to all text labels.

point_radius

Default 0.5. Radius of 3D points (rendered with render_points().

line_offset

Default 1e-7. Small number indicating the offset in the scene to apply to lines if using software rendering. Increase this if your lines aren't showing up, or decrease it if lines are appearing through solid objects.

print_scene_info

Default FALSE. If TRUE, it will print the position and lookat point of the camera.

verbose

Default FALSE. If TRUE, prints additional render diagnostics such as the auto-derived focus distance.

instant_capture

Default TRUE if interactive, FALSE otherwise. If FALSE, a slight delay is added before taking the snapshot. This can help stop prevent rendering issues when running scripts.

clear

Default FALSE. If TRUE, the current rgl device will be cleared.

bring_to_front

Default FALSE. Whether to bring the window to the front when rendering the snapshot.

heightmap

Deprecated and ignored. Retained for backward compatibility.

zscale

Deprecated and ignored. Retained for backward compatibility.

cache_scene

Default FALSE. Whether to cache the current scene to memory so it does not have to be converted to a raymesh object each time render_snapshot() is called. If TRUE and a scene has been cached, it will be used when rendering.

reset_scene_cache

Default FALSE. Resets the scene cache before rendering.

...

Additional parameters to pass to rayvertex::rasterize_scene(). Deprecated argument spellings are accepted with a warning and forwarded to their current names.

Value

4-layer RGBA array.

Examples

montereybay_spatial |>
 sphere_shade(vertical_exaggeration = 10) |>
 plot_3d(vertical_exaggeration = 4, water=TRUE, water_line_color="white",
         zoom=0.3,theta=-135,fov=70, phi=20)

#Preview where the focal plane lies
render_depth(preview_focus=TRUE)
#Render the depth of field effect
render_depth(focal_length = 300)
#Add a chromatic aberration effect
render_depth(focal_length = 300, aberration = 0.3)
#Render the depth of field effect, ignoring water in the depth pass
render_depth(preview_focus=TRUE, focal_length=300, transparent_water=TRUE)
render_depth(focal_length=300, transparent_water=TRUE)
render_camera(theta=45,zoom=0.15,phi=20)

#Change the bokeh shape and intensity
render_depth(focus=900, bokeh_shape = "circle",focal_length=500,bokeh_intensity=30,
            title_text = "Circular Bokeh", title_size = 30, title_color = "white",
            title_bar_color = "black")
render_depth(focus=900, bokeh_shape = "hex",focal_length=500,bokeh_intensity=30,
            title_text = "Hexagonal Bokeh", title_size = 30, title_color = "white",
            title_bar_color = "black")

#Add a title and vignette effect.
render_camera(theta=0,zoom=0.7,phi=30)
render_depth(focal_length = 250, title_text = "Monterey Bay, CA",
            title_size = 20, title_color = "white", title_bar_color = "black", vignette = TRUE)

Render Floating overlay

Description

Render a 2D floating overlay over the map.

Cache fallback messages are disabled by default. Set options(rayshader.verbose_scene_cache = TRUE) to print when cached metadata is reused.

Note: Multiple layers with transparency can cause rendering issues in rgl.

Usage

render_floating_overlay(
  overlay = NULL,
  altitude = NULL,
  alpha = 1,
  remove_na = TRUE,
  reorient = TRUE,
  clear_layers = FALSE,
  horizontal_offset = c(0, 0),
  zscale = 1,
  vertical_exaggeration = 1,
  heightmap = NULL,
  ...
)

Arguments

overlay

Overlay (4D RGBA array) to be rendered on the 3D map.

altitude

Altitude to place the overlay.

alpha

Default 1. Multiplies the layer's transparency by this factor. 0 is completely transparent.

remove_na

Default TRUE. Whether to make the overlay transparent above empty spaces represented by NA values in the active heightmap.

reorient

Default TRUE. Whether to transpose the heightmap's NA mask to match the overlay texture orientation.

clear_layers

Default FALSE. Clears all existing floating layers on the visualization.

horizontal_offset

Default c(0,0). Distance (in 3D space) to offset the floating offset in the x/y directions.

zscale

Default 1. The ratio between the x and y spacing (which are assumed to be equal) and the z axis. For example, if the elevation levels are in units of 1 meter and the grid values are separated by 10 meters, zscale would be 10. Adjust the zscale down to exaggerate elevation features.

vertical_exaggeration

Default 1. Multiplier applied to the effective visual relief. If omitted, rayshader uses the cached scene value from plot_3d() or plot_gg() when available; pass explicitly to override for this call.

heightmap

Default NULL. Height matrix whose existing NA cells mask the overlay when remove_na = TRUE. If omitted, this is taken from the cached scene set by plot_3d() or plot_gg(). Pass explicitly to override the cached value.

...

Additional arguments to pass to rgl::triangles3d().

Value

Adds a 3D floating layer to the map. No return value.

Examples

#Render the road network as a floating overlay layer, along with a label annotation and a floating
#point annotation
if(all(length(find.package("sf", quiet = TRUE)) > 0,
      length(find.package("magick", quiet = TRUE)) > 0)) {
 monterey = c(-121.892933,36.603053)
 monterey_city = sf::st_sfc(sf::st_point(monterey))
 sf::st_crs(monterey_city) = sf::st_crs(montereybay_spatial)

 #Generate Overlays
 road_overlay = generate_line_overlay(monterey_roads_sf, heightmap = montereybay_spatial)
 point_overlay = generate_point_overlay(monterey_city, color="red", size=1,
                                        heightmap = montereybay_spatial)

 #Create 3D plot (water transparency set to 1 because multiple transparency layers can interfere)
 montereybay_spatial |>
   height_shade() |>
   add_shadow(ray_shade(vertical_exaggeration = 4),0.3) |>
   plot_3d(water = TRUE, water_alpha = 1, window_size = 800,
           water_color = "lightblue", vertical_exaggeration = 4)
 render_camera(theta=-55,phi=45,zoom=0.8)

 #Render label
 render_label(lat = monterey[2], long = monterey[1], altitude = 9900,
              text = "Monterey", text_color = "black", line_color="darkred")

 #Render Floating Overlays
 render_floating_overlay(road_overlay, altitude = 10000)
 render_floating_overlay(point_overlay, altitude = 100)
 render_snapshot()
}

Render High Quality

Description

Renders a raytraced version of the displayed rgl scene, using the rayrender package. User can specify the light direction, intensity, and color, as well as specify the material of the ground and add additional scene elements.

This function can also generate frames for an animation by passing camera animation information from either convert_path_to_animation_coords() or rayrender::generate_camera_motion() functions.

Usage

render_highquality(
  filename = NA,
  samples = 128,
  sample_method = "sobol_blue",
  min_variance = 1e-07,
  light = TRUE,
  lat = NA,
  long = NA,
  datetime = NA,
  sky_sun_elevation = NA,
  sky_sun_azimuth = NA,
  sky_altitude = NA,
  sky_args = list(),
  sky_haze = FALSE,
  sky_query_altitude = FALSE,
  light_direction = 315,
  light_altitude = 45,
  light_size = 5,
  light_intensity = 500,
  light_color = "white",
  material = rayrender::diffuse(),
  water_attenuation = 0,
  water_surface_color = TRUE,
  water_ior = 1.33,
  water_material = c("glassy", "microfacet"),
  water_roughness = 0.1,
  override_material = FALSE,
  width = NULL,
  height = NULL,
  ortho_dimensions = NULL,
  text_angle = NULL,
  text_size = 16,
  text_offset = c(0, text_size/2, 0),
  text_render = c("screen", "world"),
  text_occlusion = TRUE,
  text_occlusion_mode = "partial",
  text_occlusion_tolerance = 0.001,
  screen_text_args = list(),
  line_radius = 0.5,
  line_render = c("auto", "screen", "world"),
  line_occlusion = TRUE,
  line_occlusion_mode = "partial",
  line_occlusion_tolerance = 0.001,
  screen_line_args = list(),
  point_radius = 0.5,
  smooth_line = FALSE,
  use_extruded_paths = FALSE,
  joined_stream_mesh = FALSE,
  scale_text_angle = NULL,
  scale_text_size = 16,
  scale_text_offset = c(0, scale_text_size/2, 0),
  title_text = NULL,
  title_offset = c(20, 20),
  title_color = "black",
  title_size = 30,
  title_font = "sans",
  title_just = "left",
  title_bar_color = NA,
  title_bar_alpha = 0.5,
  ground_material = rayrender::diffuse(),
  ground_size = 1e+05,
  scene_elements = NULL,
  camera_location = NULL,
  camera_lookat = NULL,
  camera_interpolate = 1,
  clear = FALSE,
  return_scene = FALSE,
  print_scene_info = FALSE,
  clamp_value = 1000,
  calculate_consistent_normals = FALSE,
  load_normals = TRUE,
  rgl_materials = list(),
  animation_camera_coords = NULL,
  plot = is.na(filename),
  verbose = FALSE,
  parallel = TRUE,
  cache_scene = FALSE,
  reset_scene_cache = FALSE,
  fov = NULL,
  panel = NULL,
  ...
)

Arguments

filename

Default NA. Filename of saved image. If missing, will display to current device.

samples

Default 128. The maximum number of samples for each pixel. Increase this to increase the quality of the rendering.

sample_method

Default "sobol_blue", unless samples > 256, in which it defaults to "sobol". The type of sampling method used to generate random numbers. The other options are random (worst quality but fastest), sobol_blue (best option for sample counts below 256), and sobol (slowest but best quality, better than sobol_blue for sample counts greater than 256).

min_variance

Default 1e-6. Minimum acceptable variance for a block of pixels for the adaptive sampler. Smaller numbers give higher quality images, at the expense of longer rendering times. If this is set to zero, the adaptive sampler will be turned off and the renderer will use the maximum number of samples everywhere.

light

Default TRUE. Whether to illuminate the scene with an infinite disk light from rayrender::disk_light(), or a spherical light on older rayrender versions. If not, the scene will be lit with a bluish sky.

lat

Default NA. Latitude (degrees) for automatic sky generation. When latitude, longitude, and datetime are available, uses rayrender::sky_light() with detailed Sun and Moon disks if supported by the installed rayrender and skymodelr. This replaces the default scene light and uses rayrender's default integrator unless an integrator was supplied explicitly. The native model requires Prague data; install it first with skymodelr::download_sky_data(sea_level = FALSE). Older versions, direct Sun angles, and image-only sky_args retain the cached EXR sky generated by skymodelr. If datetime is supplied and lat/long are omitted, rayshader will try to derive them from the center of the cached scene extent, transformed to WGS84. For ggplot maps, uses the selected panel's map extent and display CRS (see panel).

long

Default NA. Longitude (degrees; west < 0) for automatic sky generation.

datetime

Default NA. POSIXct or character date-time used to position the sun. If lat/long are omitted, rayshader will try to derive them from the cached scene extent center (converted to latitude/longitude) before generating the sky.

sky_sun_elevation

Default NA. If supplied, uses skymodelr::generate_sky() and passes this value to its elevation argument.

sky_sun_azimuth

Default NA. If supplied, uses skymodelr::generate_sky() and passes this value to its azimuth argument.

sky_altitude

Default NA. Reference altitude in meters, passed to the selected sky model's altitude argument. With native altitude queries this is the altitude of the original scene's zero-elevation plane; terrain heights are added above it. Without location/time inputs, this selects the direct EXR sky.

sky_args

Default empty list(). Additional arguments to rayrender::sky_light(), including sun, moon, sun_resolution, moon_resolution, visibility, and sampling_resolution. Both celestial disks are enabled by default. The native sky uses cached horizontal meters per scene unit, or one meter when no metric metadata exists; override this with meters_per_unit. The default atmosphere_origin accounts for scene centering and keeps the original zero-elevation plane fixed. An explicit origin uses final rayrender scene coordinates. Altitude queries follow the rendered geometry, including vertical exaggeration. Explicit sky_haze and sky_query_altitude override haze and query_altitude entries in this list. Image-only options such as hosek = TRUE or resolution select the legacy skymodelr::generate_sky_latlong()/skymodelr::generate_sky() EXR path. hosek = FALSE alone permits the native Prague sky. Legacy EXRs are cached in tempdir(); filename is always managed internally.

sky_haze

Default FALSE. Enable finite-distance atmospheric haze with the native sky. Enabling haze also enables altitude queries unless explicitly disabled, which is an error. Image skies do not support this option.

sky_query_altitude

Default FALSE. Evaluate Sun, Moon, and sky lighting at each surface or volume interaction's altitude. This allows high terrain or clouds to receive sunlight while lower areas are dark. With FALSE, lighting uses the fixed sky_altitude (zero by default). Image skies do not support this option.

light_direction

Default 315. Position of the light angle around the scene. When omitted, rayshader interprets the default relative to true north using cached spatial metadata. If this is a vector longer than one, multiple lights will be generated (using values from light_altitude, light_intensity, and light_color)

light_altitude

Default 45. Angle above the horizon that the light is located. If this is a vector longer than one, multiple lights will be generated (using values from light_direction, light_intensity, and light_color)

light_size

Default 5. Full angular diameter of the disk light(s), in degrees, greater than 0 and less than 180. Independent of scene size and camera position. On older rayrender versions without disk lights, this is the spherical light radius in scene units; NULL uses one fifth of the rgl observer radius.

light_intensity

Default 500. Intensity of the light.

light_color

Default white. The color of the light.

material

Default rayrender::diffuse(). The material properties of the object file. Only used if override_material = TRUE

water_attenuation

Default 0, no attenuation. Amount that light should be attenuated when traveling through water. This calculates 1-color

water_surface_color

Default TRUE. Whether the water should have a colored surface or not. This is in contrast to setting a non-zero water attenuation, where the color comes from the attenuation of light in the water itself.

water_ior

Default 1.33. Water index of refraction.

water_material

Default "glassy". Water material used in render_highquality(). "glassy" renders water with rayrender::dielectric(); "microfacet" renders water with rayrender::microfacet(transmission = TRUE).

water_roughness

Default 0.1. Roughness used when water_material = "microfacet".

override_material

Default FALSE. Whether to override the default diffuse material with that in argument material.

width

Defaults to the width of the rgl window. Width of the rendering.

height

Defaults to the height of the rgl window. Height of the rendering.

ortho_dimensions

Default NULL, which uses the orthographic dimensions inferred from the current rgl projection when fov = 0. Supply a numeric length-2 vector to override the inferred orthographic width/height.

text_angle

Default NULL, which forces the text always to face the camera. If a single angle (degrees), will specify the absolute angle all the labels are facing. If three angles, this will specify all three orientations (relative to the x,y, and z axes) of the text labels.

text_size

Default 16. Base height of the text.

text_offset

Default c(0,text_size/2,0). Offset to be applied to all world-space text labels. For screen-space text, no default offset is applied unless this is explicitly supplied.

text_render

Default "screen". Whether labels and z-axis text are rendered as screen-space annotations ("screen") or as 3D text geometry ("world").

text_occlusion

Default TRUE. Whether screen-space text should be hidden when occluded by scene geometry. Only used when text_render = "screen".

text_occlusion_mode

Default "partial". Occlusion mode passed to rayrender::screen_text(). Options are "anchor", which hides text when the anchor point is occluded, "label", which checks the text label area, and "partial", an alias for "label".

text_occlusion_tolerance

Default 0.001. Occlusion tolerance passed to rayrender::screen_text().

screen_text_args

Default empty list(). Additional named arguments passed to rayrender::screen_text() for screen-space labels. Arguments in screen_text_args override values generated by rayshader when names overlap.

line_radius

Default 0.5. Radius of line/path segments.

line_render

Default "auto". Whether rgl line objects are rendered as screen-space annotations or 3D geometry. "auto" renders z-axis lines/ticks and render_label() connector lines in screen space while keeping paths and contours as 3D geometry. Use "screen" for all line/path objects or "world" for the previous 3D behavior.

line_occlusion

Default TRUE. Whether screen-space lines should be hidden when occluded by scene geometry. Only used for lines rendered in screen space.

line_occlusion_mode

Default "partial". Occlusion mode passed to rayrender::screen_line(). Options are "anchor", which hides lines when the anchor point is occluded, "line", which checks the line extent, and "partial", an alias for "line".

line_occlusion_tolerance

Default 0.001. Occlusion tolerance passed to rayrender::screen_line().

screen_line_args

Default empty list(). Additional named arguments passed to rayrender::screen_line() for screen-space lines. Arguments in screen_line_args override values generated by rayshader when names overlap.

point_radius

Default 1. Radius of 3D points (rendered with render_points()). This scales the existing value of size specified in render_points().

smooth_line

Default FALSE. If TRUE, the line will be rendered with a continuous smooth line, rather than straight segments.

use_extruded_paths

Default TRUE. If FALSE, paths will be generated with the rayrender::path() object, instead of rayrender::extruded_path().

joined_stream_mesh

Default FALSE. If TRUE, stream paths from render_streams() are rendered as joined terrain-clipped water meshes in render_highquality() instead of one rectangular extrusion per line.

scale_text_angle

Default NULL. Same as text_angle, but for the scale bar.

scale_text_size

Default 16. Base height of the scale bar text.

scale_text_offset

Default c(0,scale_text_size/2,0). Offset to be applied to all world-space scale bar text labels. For screen-space text, no default offset is applied unless this is explicitly supplied.

title_text

Default NULL. Text. Adds a title to the image, using magick::image_annotate.

title_offset

Default c(20,20). Distance from the top-left (default, gravity direction in image_annotate) corner to offset the title.

title_color

Default black. Font color.

title_size

Default 30. Font size in pixels.

title_font

Default sans. String with font family such as "sans", "mono", "serif", "Times", "Helvetica", "Trebuchet", "Georgia", "Palatino" or "Comic Sans".

title_just

Default left. Justification of the title.

title_bar_color

Default NA. If a color, this will create a colored bar under the title.

title_bar_alpha

Default 0.5. Transparency of the title bar.

ground_material

Default diffuse(). Material defined by the rayrender material functions.

ground_size

Default 100000. The width of the plane representing the ground.

scene_elements

Default NULL. Extra scene elements to add to the scene, created with rayrender.

camera_location

Default NULL. Custom position of the camera. The FOV, width, and height arguments will still be derived from the rgl window. By default, numeric length-3 vectors are interpreted as existing render_highquality scene-camera coordinates. To use spatial coordinates, supply a named vector such as c(long = ..., lat = ..., altitude = ...), an sf/sfc/sfg/sp POINT with altitude stored in a Z coordinate or altitude column, or a list such as list(location = point, altitude = ..., crs = ...).

camera_lookat

Default NULL. Custom point at which the camera is directed. The FOV, width, and height arguments will still be derived from the rgl window. Spatial inputs are accepted using the same formats as camera_location.

camera_interpolate

Default c(0,0). Maximum 1, minimum 0. Sets the camera at a point between the rgl view and the camera_location and camera_lookat vectors.

clear

Default FALSE. If TRUE, the current rgl device will be cleared.

return_scene

Default FALSE. If TRUE, returns a rayrender scene with its resolved camera and render defaults. Asset files are not embedded. Use rayrender::write_usd() for an explicit export that collects referenced assets, then restore it with rayrender::read_usd() in a later session.

print_scene_info

Default FALSE. If TRUE, it will print the position and lookat point of the camera.

clamp_value

Default 1000. Radiance clamp value. If NA, uses 1000.

calculate_consistent_normals

Default FALSE. Whether to calculate consistent vertex normals to prevent energy loss at edges.

load_normals

Default TRUE. Whether to load the vertex normals if they exist in the OBJ file.

rgl_materials

Default empty list(). Named list of material overrides for rgl objects. Names must be rgl tags or rgl ids. Values can be evaluated rayrender materials, rayrender material functions, or lists with a material entry and optional args/material_args entry. When a material function is supplied, the rgl object color is passed to its color argument unless color is already supplied in args.

animation_camera_coords

Default NULL. Expects camera animation output from either convert_path_to_animation_coords() or rayrender::generate_camera_motion() functions.

plot

Default is.na(filename). Whether to plot the scene, or just return the RGBA array.

verbose

Default FALSE. If TRUE, reports scene-conversion phase timings, forwards verbose construction timing to rayrender, and displays progress bars while converting line and stream paths into raytraced scene objects. Road meshes built by render_roads() are reused from the active scene cache.

parallel

Default TRUE. Whether to use multiple threads for raytracing and for legacy uncached road-path conversion.

cache_scene

Default FALSE. Whether to cache the current scene to memory so it does not have to be converted to a raymesh object each time render_snapshot() is called. If TRUE and a scene has been cached, it will be used when rendering.

reset_scene_cache

Default FALSE. Resets the scene cache before rendering.

fov

Default NULL. Vertical field of view in degrees. When NULL, matches the current rgl projection, including zoom. An explicit value overrides rgl's field of view; use 0 for an orthographic camera and ortho_dimensions to control its width and height. Animation camera paths continue to use their per-frame field of view.

panel

Default NULL. ggplot panel ID used to infer the sky location from that panel's map extent and display CRS. Also supplies the default panel for spatial camera inputs; a camera input's own panel takes precedence. When omitted, sky inference uses camera_lookat$panel, then camera_location$panel. Faceted maps require a selection when inferring latitude or longitude. Explicit lat and long bypass this inference.

...

Additional parameters to pass to rayrender::render_scene(). Deprecated argument spellings are accepted with a warning and forwarded to their current names.

Examples

#Render the volcano dataset using pathtracing
volcano |>
 sphere_shade(vertical_exaggeration = 2) |>
 plot_3d(vertical_exaggeration = 1/2, shadow_depth=min(volcano)*0.8)
render_highquality(min_variance = 0, sample_method = "sobol_blue", samples = 16)

#Change position of light
render_highquality(light_direction = 45, min_variance = 0,
                  sample_method = "sobol_blue", samples = 16)

#Change vertical position of light
render_highquality(light_direction = 45, light_altitude = 10,
                  min_variance = 0, samples = 16)

#Change the ground material
render_highquality(light_direction = 45, light_altitude=60,
                  ground_material = rayrender::diffuse(checkerperiod = 30, checkercolor="grey50"),
                  min_variance = 0, samples = 16)

#Add three different color lights and a title
render_highquality(light_direction = c(0,120,240), light_altitude=45,
                  light_color=c("red","green","blue"), title_text = "Red, Green, Blue",
                  title_bar_color="white", title_bar_alpha=0.8,
                  min_variance = 0, samples = 16)

#Change the camera:
render_camera(theta=-45,phi=60,fov=60,zoom=0.8)
render_highquality(light_direction = c(0),
                  title_bar_color="white", title_bar_alpha=0.8,
                  min_variance = 0, samples = 16)
#Add a shiny metal sphere
render_camera(theta=-45,phi=60,fov=60,zoom=0.8)
render_highquality(light_direction = c(0,120,240), light_altitude=45,
                  light_color=c("red","green","blue"),
                  scene_elements = rayrender::sphere(z=-60,y=0,
                                                     radius=20,material=rayrender::metal()),
                  min_variance = 0, samples = 16)

#Add a red light to the volcano and change the ambient light to dusk
render_camera(theta=45,phi=45)
render_highquality(light_direction = c(240), light_altitude=30,
                  light_color=c("#5555ff"),
                  scene_elements = rayrender::sphere(z=0,y=6, x=-18, radius=5,
                                   material=rayrender::light(color="red",intensity=100)),
                  min_variance = 0, samples = 16)
#Manually change the camera location and direction
render_camera(fov=111)
render_highquality(light_direction = c(240), light_altitude=30, light_color=c("#5555ff"),
                  camera_location = c(-8.91, 24.36, 6.96), camera_lookat = c(4.25, 20.86, 2.18),
                  scene_elements = rayrender::sphere(z=0,y=15, x=-18, radius=5,
                                   material=rayrender::light(color="red",intensity=10)),
                  min_variance = 0, samples = 16)
# Render the shadow of the Washington Monument with a realistic sky at that datetime
# using the `skymodelr` package.


library(sf)
#Set location of washington monument
washington_monument_location =  st_point(c(-77.035249, 38.889462))
wm_point = washington_monument_location |>
 st_buffer(0.01) |>
 st_sfc(crs = 4326) |>
 st_transform(st_crs(washington_monument_multipolygonz))

elevation_data = elevatr::get_elev_raster(locations = wm_point, z = 14)

wash_point = washington_monument_location |>
 st_sfc(crs = 4326) |>
 st_transform(st_crs(washington_monument_multipolygonz))
scene_bbox = st_bbox(st_buffer(wash_point,500))
cropped_data = raster::crop(elevation_data, scene_bbox)

#Plot a 3D map of the national mall
cropped_data |>
 sphere_shade(vertical_exaggeration = 30) |>
 plot_3d(water = TRUE, water_input = 1.5,
         solid_depth=-50, window_size = 800)
#Zoom in on the monument
render_camera(theta=115,  phi=25, zoom= 0.25, fov=40)
#Render the national monument at solar noon on the solstice
rgl::par3d(ignoreExtent = TRUE)
render_multipolygonz(washington_monument_multipolygonz,
                    zscale = 4, color = "grey80")
# Render a native Prague sky with detailed Sun and Moon disks when available.
# Haze and altitude-dependent lighting are off by default.
# Set exposure manually with iso to capture the softer morning light.
render_highquality(
min_variance = 0,
samples = 16,
long = -77.035249,
lat = 38.889462,
iso = 8,
clamp_value = 1000,
datetime = as.POSIXct("2025-12-21 08:00:00", tz = "EST")
)

# Enable altitude-dependent illumination and atmospheric haze.
# First install the supplemental Prague data, if needed:
# skymodelr::download_sky_data(sea_level = FALSE)
# The Sun and Moon use separate detailed disks, independent of sky sampling.
# We use auto_exposure to account for the high mid-day radiance.
render_highquality(
min_variance = 0,
samples = 16,
long = -77.035249,
lat = 38.889462,
sky_haze = TRUE,
sky_query_altitude = TRUE,
sky_args = list(visibility = 120, sun_resolution = 512, moon_resolution = 1024),
auto_exposure = TRUE,
clamp_value = 1000,
datetime = as.POSIXct("2025-12-21 11:00:00", tz = "EST")
)

Render Label

Description

Adds a marker and label to the current 3D plot

Cache fallback messages are disabled by default. Set options(rayshader.verbose_scene_cache = TRUE) to print when cached metadata is reused.

Usage

render_label(
  location = NULL,
  text = NULL,
  data_column_text = NULL,
  font = "sans",
  family = "sans",
  font_type = "standard",
  text_size = 1,
  text_color = "black",
  text_alpha = 1,
  freetype = TRUE,
  adjust_vec = NULL,
  line = TRUE,
  line_color = "black",
  linewidth = 3,
  alpha = 1,
  dashed = FALSE,
  dash_length = "auto",
  antialias = FALSE,
  clear_previous = FALSE,
  x = NULL,
  y = NULL,
  z = NULL,
  altitude = NULL,
  data_column_z = NULL,
  scale_data = 1,
  relative_z = FALSE,
  offset = 0,
  lat = NULL,
  long = NULL,
  crs = NULL,
  filter_to_extent = TRUE,
  extent = NULL,
  panel = NULL,
  zscale = 1,
  vertical_exaggeration = 1,
  heightmap = NULL,
  ...
)

Arguments

location

Default NULL. Spatial input used to place the rendered label(s) in the scene. Accepts sf, sfc, sfg, or sp POINT, MULTIPOINT, POLYGON, or MULTIPOLYGON geometries. POLYGON and MULTIPOLYGON inputs are converted to label points with sf::st_centroid(). MULTIPOINT inputs are flattened to point placements internally, and vectorized arguments such as text, z, altitude, data_column_text, and data_column_z values are applied against that flattened point count. If the input carries a CRS, it will be transformed automatically into the active scene CRS. If it has no CRS, supply crs.

text

Default NULL. The label text. If omitted, use data_column_text to read label text from location.

data_column_text

Default NULL. Column name in location to use for text. Requires location to be an sf/spatial object with the named column. Values are applied after polygon centroid conversion and POINT/MULTIPOINT flattening.

font

Default "sans". Font family passed to render_highquality() for this label. This does not change the font used in the rgl preview; use family and font_type to control the preview font.

family

Default "sans". Font family used in the rgl preview. Choices are c("serif", "sans", "mono", "symbol").

font_type

Default "standard". Font type used in the rgl preview. Choices are c("standard", "bold", "italic", "bolditalic"). These require FreeType fonts, which may not be installed on your system. If the selected face is unavailable, rayshader emits a message and uses rgl's bitmap font to preview label placement. See rgl::text3d() for more information.

text_size

Default 1. A numeric character expansion value. If rgl falls back to its fixed-size bitmap font, the requested value is still used by render_highquality().

text_color

Default "black". Color of the text. Use "height" to color label text by the cached plot_gg() height aesthetic palette.

text_alpha

Default 1. Transparency of the label text.

freetype

Default TRUE. Set to FALSE if FreeType is not installed. FreeType enables anti-aliased fonts, but can occasionally cause transparency issues when text is positioned in front of or behind a transparent surface.

adjust_vec

Default NULL. Horizontal and vertical offsets for the text. When omitted, render_highquality() uses c(0.5, -0.5). The rgl preview uses c(0.33, -0.5) when freetype = FALSE on macOS or Linux to center its bitmap font without changing the high-quality justification.

line

Default TRUE. If FALSE, the vertical line connecting the label to the surface is not drawn.

line_color

Default "black". Color of the line. Use "height" to color label lines by the cached plot_gg() height aesthetic palette.

linewidth

Default 3. The line width.

alpha

Default 1. Transparency of the label line.

dashed

Default FALSE. If TRUE, the label line is dashed.

dash_length

Default "auto". Length, in units of the elevation matrix and scaled by zscale, of the dashes when dashed = TRUE.

antialias

Default FALSE. If TRUE, anti-aliasing is applied to the line. Anti-aliasing can cause unpredictable behavior with transparent surfaces.

clear_previous

Default FALSE. If TRUE, clears all existing text and lines rendered with render_label(). A clear-only call returns without rendering a replacement.

x

Default NULL. X coordinate for the label in the same coordinate reference system as extent. If no extent is available and the scene uses a plain matrix heightmap, this defaults to matrix dimensions.

y

Default NULL. Y coordinate for the label in the same coordinate reference system as extent. If no extent is available and the scene uses a plain matrix heightmap, this defaults to matrix dimensions.

z

Default NULL. Elevation of the label, in units of the elevation matrix and scaled by zscale.

altitude

Default NULL. Elevation of the label, in units of the elevation matrix and scaled by zscale. If omitted, this defaults to 10 percent above the maximum altitude in the heightmap.

data_column_z

Default NULL. Column name in location to use for z. Requires location to be an sf/spatial object with values coercible to numeric. Values are applied after polygon centroid conversion and POINT/MULTIPOINT flattening. Rows with missing or non-finite values after coercion are omitted, and retained values are multiplied by scale_data.

scale_data

Default 1. If specifying data_column_z, how much to scale that value when rendering. If used with vertical_exaggeration, both are applied.

relative_z

Default FALSE. Whether z is measured relative to the underlying elevation at that point in the heightmap or set absolutely.

offset

Default 0. Elevation above the surface at the label point at which to start drawing the line.

lat

Default NULL. Alias for y for geographic workflows.

long

Default NULL. Alias for x for geographic workflows.

crs

Default NULL. CRS of the input numeric x/y coordinates, or CRS to assign to CRS-less spatial data before transforming it into the active scene CRS. If spatial data already carries a CRS, that CRS is used automatically.

filter_to_extent

Default TRUE. If TRUE, labels outside the scene extent are omitted. For scenes created with plot_gg(), filtering uses the ggplot panel extent rather than the full rendered 3D ggplot extent.

extent

Default NULL. An object representing the spatial extent of the scene from the raster, terra, sf, or sp packages; a length-4 numeric vector specifying c("xmin", "xmax", "ymin", "ymax"); or a spatial object that can be converted to an extent. If omitted, rayshader uses extent metadata cached by plot_3d() or plot_gg(). If no extent metadata is available for a plain matrix scene, rayshader defaults to c(xmin = 1, xmax = nrow(heightmap), ymin = 1, ymax = ncol(heightmap)).

panel

Default NULL. Facet panel identifier for scenes created with plot_gg(). Required to disambiguate faceted ggplot scenes when panel-specific cached metadata is needed. Ignored for non-ggplot scenes.

zscale

Default 1. Ratio between horizontal spacing and the elevation units in the original heightmap. If omitted, rayshader uses the cached scene value when available.

vertical_exaggeration

Default 1. Multiplier applied to the effective visual relief. If omitted, rayshader uses the cached scene value from plot_3d() or plot_gg() when available; pass explicitly to override it for this call.

heightmap

Default NULL. Height matrix for the current scene. If omitted, rayshader uses the cached scene set by plot_3d() or plot_gg(). Pass explicitly to override the cached value.

...

Deprecated argument spellings are accepted with a warning and forwarded to their current names.

Examples

montereybay_spatial |>
 sphere_shade(vertical_exaggeration = 10) |>
 plot_3d(vertical_exaggeration = 4,water=TRUE, water_color="#233aa1",
         zoom=0.9, window_size = 800)
render_snapshot()

santa_cruz = c(36.962957, -122.021033)
#We want to add a label to Santa Cruz, so we use latitude/longitude coordinates.
render_label(lat = santa_cruz[1], long = santa_cruz[2],
            text_size = 2, altitude=12000, text = "Santa Cruz")
render_snapshot()

monterey = c(36.603053, -121.892933)
#We can also change the linetype to dashed by setting `dashed = TRUE` (additional options allow
#the user to control the dash length). You can clear the existing lines by setting
#`clear_previous = TRUE`.
render_label(lat = monterey[1], long = monterey[2], altitude = 10000,
            text_size = 2, text = "Monterey", text_color = "white", line_color="darkred",
            dashed = TRUE, clear_previous = TRUE)
render_snapshot()

canyon = c(36.621049, -122.333912)
#By default, z specifies the absolute altitude. We can also specify
#an relative height by setting `relative_z=FALSE`.
render_label(lat = canyon[1], long = canyon[2], altitude = 2000,
            text_size = 2, text = "Monterey Canyon", relative_z = TRUE)
render_snapshot()

#Query the fonts installed on this system and select a concrete family,
#preferring commonly available fonts with broad Latin character coverage.
installed_font_families = unique(systemfonts::system_fonts()$family)
preferred_font_families = c("Avenir", "Arial", "Liberation Sans", "DejaVu Sans")
label_font = intersect(preferred_font_families, installed_font_families)
if (length(label_font)) {
 label_font = label_font[1]
} else {
 label_font = systemfonts::font_info("sans")$family[1]
}

#The `font` argument uses that installed family in `render_highquality()`.
#The rgl preview still uses `family` and `font_type` independently.
render_camera(theta=35, phi = 35, zoom = 0.80, fov=60)
#Register its bold face under a dedicated family name for high-quality text.
systemfonts::register_variant(
 name = "rayshader_label_bold",
 family = label_font,
 weight = "bold"
)

render_label(lat = monterey[1], long = monterey[2], altitude = 10000,
            text_size = 2, text = "Monterey", text_color = "black", line_color="darkred",
            dashed = TRUE, clear_previous = TRUE, font_type = "bold",
            family = "sans", font = "rayshader_label_bold")

render_label(lat = canyon[1], long = canyon[2],
            altitude = 2000, text_size = 2,
            text_color = "white", line_color="black",font_type = "bold",
            text = "Monterey Canyon", relative_z=FALSE,
            family = "sans", font = "rayshader_label_bold")

render_highquality(samples = 16)
#We can remove all existing labels by calling `render_label(clear_previous = TRUE)`
render_label(clear_previous = TRUE)
render_snapshot()

Render Movie

Description

Renders a movie using the av or gifski packages. Moves the camera around a 3D visualization using either a standard orbit, or accepts vectors listing user-defined values for each camera parameter. If the latter, the values must be equal in length to frames (or of length 1, in which the value will be fixed).

Additional arguments are forwarded to render_snapshot() for additional customization arguments (like adding titles).

Usage

render_movie(
  filename,
  type = "orbit",
  frames = 360,
  fps = 30,
  phi = 30,
  theta = 0,
  zoom = NULL,
  fov = NULL,
  width = NULL,
  height = NULL,
  audio = NULL,
  progress_bar = interactive(),
  ...
)

Arguments

filename

Filename. If not appended with .mp4, it will be appended automatically. If the file extension is gif, the gifski package will be used to generate the animation.

type

Default orbit, which orbits the 3D object at the user-set camera settings phi, zoom, and fov. Other options are oscillate (sine wave around theta value, covering 90 degrees), or custom (which uses the values from the theta, phi, zoom, and fov vectors passed in by the user).

frames

Default 360. Number of frames to render.

fps

Default 30. Frames per second. Recommmend either 30 or 60 for web.

phi

Defaults to current view. Azimuth values, in degrees.

theta

Default to current view. Theta values, in degrees.

zoom

Defaults to the current view. Zoom value, between 0 and 1.

fov

Defaults to the current view. Field of view values, in degrees.

width

Default NULL, uses the window size by default. Width of the movie. Note that the frames will still be captured at the resolution (and aspect ratio) of the rgl window.

height

Default NULL, uses the window size by default. Height of the movie. Note that the frames will still be captured at the resolution (and aspect ratio) of the rgl window.

audio

Default NULL. Optional file with audio to add to the video.

progress_bar

Default TRUE if interactive, FALSE otherwise. If FALSE, turns off progress bar. Will display a progress bar when adding an overlay or title.

...

Additional parameters to pass to render_snapshot(). Deprecated argument spellings are accepted with a warning and forwarded to their current names.

Examples

if(interactive()) {
filename_movie = tempfile()

#By default, the function produces a 12 second orbit at 30 frames per second, at 30 degrees azimuth.

montereybay_spatial |>
 sphere_shade(texture="imhof1") |>
 plot_3d(vertical_exaggeration = 4, water = TRUE, water_color="imhof1",
         water_line_color="white", water_line_alpha=0.5)
#Un-comment the following to run:
#render_movie(filename = filename_movie)

filename_movie = tempfile()

#You can change to an oscillating orbit. The magnification is increased and azimuth angle set to 30.
#A title has also been added using the title_text argument.

#Un-comment the following to run:
#render_movie(filename = filename_movie, type = "oscillate",
#             frames = 60,  phi = 30, zoom = 0.8, theta = -90,
#             title_text = "Monterey Bay: Oscillating")

filename_movie = tempfile()

#Finally, you can pass your own set of values to the
#camera parameters as a vector with type = "custom".

phivechalf = 30 + 60 * 1/(1 + exp(seq(-7, 20, length.out = 180)/2))
phivecfull = c(phivechalf, rev(phivechalf))
thetavec = -90 + 45 * sin(seq(0,359,length.out = 360) * pi/180)
zoomvec = 0.45 + 0.2 * 1/(1 + exp(seq(-5, 20, length.out = 180)))
zoomvecfull = c(zoomvec, rev(zoomvec))

#Un-comment the following to run
#render_movie(filename = filename_movie, type = "custom",
#             frames = 360,  phi = phivecfull, zoom = zoomvecfull, theta = thetavec)

}

Render High Quality Movie

Description

Renders a high quality movie by extracting the current rayshader scene with render_highquality(), generating camera motion from supplied or saved rayrender interactive keyframes with rayrender::generate_camera_motion(), and passing the result to rayrender::render_animation(). Screen-space text and lines are retained and reprojected for each frame by rayrender.

Usage

render_movie_hq(
  frames = 360,
  type = "linear",
  closed = TRUE,
  damp_motion = TRUE,
  render_highquality_args = list(),
  keyframes = NULL,
  ...
)

Arguments

frames

Default 360. Number of frames in the generated camera motion.

type

Default "linear". Type of transition between saved keyframes. Other options are those supported by rayrender::generate_camera_motion().

closed

Default TRUE. Whether to close the camera path by returning to the first saved keyframe.

damp_motion

Default TRUE. Whether to damp quick camera movements.

render_highquality_args

Default list(). Additional arguments passed to render_highquality() when extracting the scene. return_scene = TRUE is always applied.

keyframes

Default NULL. Keyframes returned by rayrender::get_saved_keyframes(). When supplied, these are passed directly to rayrender::generate_camera_motion() without reading the currently saved interactive keyframes.

...

Additional parameters to pass to rayrender::render_animation().

Value

Invisibly returns the value from rayrender::render_animation().


Render MULTIPOLYGON Z Geometry

Description

Adds MULTIPOLYGONZ will be plotted in the coordinate system set by the user-specified extent argument as-is.

Cache fallback messages are disabled by default. Set options(rayshader.verbose_scene_cache = TRUE) to print when cached metadata is reused.

You can also use save_multipolygonz_to_obj() manually to convert sf objects

Usage

render_multipolygonz(
  sf_obj,
  color = "grey50",
  obj_zscale = TRUE,
  swap_yz = TRUE,
  rgl_tag = "_multipolygon",
  clear_previous = FALSE,
  offset = 0,
  crs = NULL,
  filter_to_extent = TRUE,
  extent = NULL,
  panel = NULL,
  zscale = 1,
  vertical_exaggeration = 1,
  heightmap = NULL,
  verbose = FALSE,
  ...
)

Arguments

sf_obj

An sf object with MULTIPOLYGON Z geometry.

color

Default black. Color of the 3D model, if load_material = FALSE.

obj_zscale

Default TRUE. Whether to scale the size of the OBJ by zscale to have it match the size of the map. If zscale is very big, this will make the model very small.

swap_yz

Default TRUE. Whether to swap and Y and Z axes. (Y axis is vertical in rayshader coordinates, but data is often provided with Z being vertical).

rgl_tag

Default "". Tag to add to the rgl scene id, will be prefixed by "obj"

clear_previous

Default FALSE. If TRUE, clears all existing rendered multipolygons for rgl_tag. A clear-only call returns without rendering a replacement.

offset

Default 5. Offset of the track from the surface, if altitude = NULL.

crs

Default NULL. CRS of the input numeric x/y coordinates, or CRS to assign to CRS-less spatial data before transforming it into the active scene CRS. If spatial data already carries a CRS, that CRS is used automatically.

filter_to_extent

Default TRUE. If TRUE, MULTIPOLYGON Z data outside the scene extent is omitted. Spatial inputs are cropped to the extent. For scenes created with plot_gg(), filtering uses the ggplot panel extent rather than the full rendered 3D ggplot extent.

extent

Either an object representing the spatial extent of the scene (either from the raster, terra, sf, or sp packages), a length-4 numeric vector specifying c("xmin", "xmax","ymin","ymax"), or the spatial object (from the previously aforementioned packages) which will be automatically converted to an extent object. If omitted, rayshader will use extent metadata cached by plot_3d() or plot_gg().

panel

Default NULL. Facet panel identifier for scenes created with plot_gg(). Required to disambiguate faceted ggplot scenes when panel-specific cached metadata is needed. Ignored for non-ggplot scenes.

zscale

Default 1. The ratio between the x and y spacing (which are assumed to be equal) and the z axis in the original heightmap.

vertical_exaggeration

Default 1. Multiplier applied to the effective visual relief. If omitted, rayshader uses the cached scene value from plot_3d() or plot_gg() when available; pass explicitly to override for this call.

heightmap

Default NULL. Height matrix containing the scene terrain and its existing NA cells. If omitted, this is taken from the cached scene set by plot_3d() or plot_gg(). Pass explicitly to override the cached value.

verbose

Default FALSE. Report triangulation and scene-upload stages.

...

Additional arguments to pass to rgl::triangles3d(). Deprecated argument spellings are accepted with a warning and forwarded to their current names.

Details

Faces with more than three vertices or holes require the decido package. Concave boundaries and interior holes are preserved when triangulating horizontal, vertical, and sloping faces. Crossed or overlapping rings are repaired in the face plane, with new intersection vertices interpolated along the original 3D edges. By default, options(rayshader.multipolygonz_repair = TRUE) also repairs ambiguous projected intersections, retaining existing vertices and choosing the nearest projected source edge for new vertex depths (first edge breaks ties). This is a heuristic for nonplanar faces. Set options(rayshader.multipolygonz_repair = FALSE) to drop those faces with a summary warning instead. Unambiguous planar repairs occur in either mode. Zero-area faces and faces that still cannot be triangulated are warned about and skipped in either mode. If no faces remain, nothing is added to the scene. Some touching-hole cases require sf/GEOS constrained triangulation support.

Examples

library(sf)
#Set location of washington monument
washington_monument_location =  st_point(c(-77.035249, 38.889462))
wm_point = washington_monument_location |>
 st_point() |>
 st_sfc(crs = 4326) |>
 st_transform(st_crs(washington_monument_multipolygonz))

elevation_data = elevatr::get_elev_raster(locations = wm_point, z = 14)

scene_bbox = st_bbox(st_buffer(wm_point,300))
cropped_data = raster::crop(elevation_data, scene_bbox)

#Use rayshader to convert that raster data to a matrix
dc_elevation_matrix = raster_to_matrix(cropped_data)

#Remove negative elevation data
dc_elevation_matrix[dc_elevation_matrix < 0] = 0

#Plot a 3D map of the national mall
dc_elevation_matrix |>
 height_shade() |>
 add_shadow(lamb_shade(), 0) |>
 plot_3d(zscale=3.7, water = TRUE, water_input = 1,
         solid_depth=-50, window_size = 800,
         extent = raster::extent(cropped_data))
render_snapshot()
#Zoom in on the monument
render_camera(theta=150,  phi=35, zoom= 0.55, fov=70)
#Render the national monument
rgl::par3d(ignoreExtent = TRUE)
render_multipolygonz(washington_monument_multipolygonz,
                    zscale = 4, color = "grey80")
render_snapshot()
#This works with `render_highquality()`
render_highquality(min_variance = 0, samples = 16)

Render Obj

Description

Adds 3D OBJ model to the current scene, using x/y coordinates in the reference system defined by the extent object. If no altitude is provided, the OBJ will be elevated a constant offset above the heightmap. If the OBJ goes off the edge, the OBJ will be filtered out.

Cache fallback messages are disabled by default. Set options(rayshader.verbose_scene_cache = TRUE) to print when cached metadata is reused.

If no x/y coordinates are passed in, the OBJ will be plotted in the coordinate system set by the user-specified extent argument as-is. Use this alongside save_multipolygonz_to_obj() to plot 3D polygons imported from geospatial sources in the proper location (but for ease of use, use render_multipolygonz() to plot this data directly).

Usage

render_obj(
  filename,
  location = NULL,
  load_material = FALSE,
  load_normals = TRUE,
  color = "grey50",
  obj_zscale = FALSE,
  swap_yz = NULL,
  angle = c(0, 0, 0),
  scale = c(1, 1, 1),
  lit = FALSE,
  light_altitude = c(45, 30),
  light_direction = c(315, 135),
  light_intensity = 0.3,
  light_relative = FALSE,
  rgl_tag = "",
  clear_previous = FALSE,
  x = NULL,
  y = NULL,
  altitude = NULL,
  xyz = NULL,
  offset = 0,
  lat = NULL,
  long = NULL,
  crs = NULL,
  filter_to_extent = TRUE,
  extent = NULL,
  panel = NULL,
  zscale = 1,
  vertical_exaggeration = 1,
  heightmap = NULL,
  ...
)

Arguments

filename

Filename for the OBJ file.

location

Default NULL. Spatial point input used to place the rendered object(s) in the scene. Accepts sf, sfc, sfg, or sp POINT or MULTIPOINT geometries. MULTIPOINT inputs are flattened to point placements internally, and vectorized arguments such as scale, angle, color, and altitude are applied against that flattened point count. If the input carries a CRS, it will be transformed automatically into the active scene CRS. If it has no CRS, supply crs.

load_material

Default TRUE. Whether to load the accompanying MTL file to load materials for the 3D model.

load_normals

Default TRUE. Whether to load normals for the 3D model.

color

Default black. Color of the 3D model, if load_material = FALSE. Use "height" to color placed models by the cached plot_gg() height aesthetic palette.

obj_zscale

Default FALSE. Whether to scale the size of the OBJ by zscale to have it match the size of the map. If zscale is very big, this will make the model very small.

swap_yz

Default NULL, defaults to FALSE unless plotting raw coordinates (no x/y or lat/long passed). Whether to swap and Y and Z axes. (Y axis is vertical in rayshader coordinates, but data is often provided with Z being vertical).

angle

Default c(0,0,0). Angle of rotation around the x, y, and z axes. If this is a matrix or list, each row (or list entry) specifies the rotation of the nth model specified (number of rows/length of list must equal the length of x/y).

scale

Default c(1,1,1). Amount to scale the 3D model in the x, y, and z axes. If this is a matrix or list, each row (or list entry) specifies the scale of the nth model specified (number of rows/length of list must equal the length of x/y).

lit

Default TRUE. Whether to light the polygons.

light_altitude

Default c(45, 60). Degree(s) from the horizon from which to light the polygons.

light_direction

Default c(45, 60). Degree(s) from north from which to light the polygons.

light_intensity

Default 0.3. Intensity of the specular highlight on the polygons.

light_relative

Default FALSE. Whether the light direction should be taken relative to the camera, or absolute.

rgl_tag

Default "". Tag to add to the rgl scene id, will be prefixed by "obj"

clear_previous

Default FALSE. If TRUE, clears all existing objects for rgl_tag. A clear-only call returns without rendering a replacement.

x

Vector of x coordinates (or other coordinate in the same coordinate reference system as extent).

y

Vector of y coordinates (or other coordinate in the same coordinate reference system as extent).

altitude

Default NULL. Elevation of each point, in units of the elevation matrix (scaled by zscale). If left NULL, this will be just the elevation value at ths surface, offset by offset. If a single value, the OBJ will be rendered at that altitude. When one horizontal location is supplied with multiple altitude values, that location is repeated to place one OBJ at each altitude.

xyz

Default NULL, ignored. A 3 column numeric matrix, with each row specifying the x/y/z coordinates of the OBJ model(s). Overrides x/y, lat/long, and altitude and ignores extent to plot the OBJ in raw rgl coordinates.

offset

Default 5. Offset of the model from the surface, if altitude = NULL.

lat

Default NULL. Alias for y for geographic workflows.

long

Default NULL. Alias for x for geographic workflows.

crs

Default NULL. CRS of the input numeric x/y coordinates, or CRS to assign to CRS-less spatial data before transforming it into the active scene CRS. If spatial data already carries a CRS, that CRS is used automatically.

filter_to_extent

Default TRUE. If TRUE, object placements outside the scene extent are omitted. For scenes created with plot_gg(), filtering uses the ggplot panel extent rather than the full rendered 3D ggplot extent.

extent

Either an object representing the spatial extent of the scene (either from the raster, terra, sf, or sp packages), a length-4 numeric vector specifying c("xmin", "xmax","ymin","ymax"), or the spatial object (from the previously aforementioned packages) which will be automatically converted to an extent object. If omitted, rayshader will use extent metadata cached by plot_3d() or plot_gg().

panel

Default NULL. Facet panel identifier for scenes created with plot_gg(). Required to disambiguate faceted ggplot scenes when panel-specific cached metadata is needed. Ignored for non-ggplot scenes.

zscale

Default 1. The ratio between the x and y spacing (which are assumed to be equal) and the z axis in the original heightmap.

vertical_exaggeration

Default 1. Multiplier applied to the effective visual relief. If omitted, rayshader uses the cached scene value from plot_3d() or plot_gg() when available; pass explicitly to override for this call.

heightmap

Default NULL. Height matrix used to determine terrain elevations and existing NA cells. If omitted, this is taken from the cached scene set by plot_3d() or plot_gg(). Pass explicitly to override the cached value.

...

Additional arguments to pass to rgl::triangles3d().

Examples

#Render the 3D map
moss_landing_coord = c(36.806807, -121.793332)
montereybay_spatial |>
 sphere_shade(vertical_exaggeration = 10) |>
 plot_3d(vertical_exaggeration = 4,water=TRUE,
         shadow_color="#40310a", background = "tan",
         theta=210,  phi=22, zoom=0.20, fov=55)

t = seq(0,2*pi,length.out=100)
circle_coords_lat = moss_landing_coord[1] + 0.3 * sin(t)
circle_coords_long = moss_landing_coord[2] + 0.3 * cos(t)

#Create a rainbow spectrum of flags
render_obj(flag_full_obj(),
          lat = unlist(circle_coords_lat), long = unlist(circle_coords_long),
          scale=c(2,2,2), angle=c(0,45,0),
          color=rainbow(100), smooth = FALSE, clear_previous = TRUE)
render_snapshot()
#Rotate the flag to follow the circle
render_obj(flag_full_obj(),
          lat = unlist(circle_coords_lat), long = unlist(circle_coords_long),
          scale=c(2,2,2),
          angle=matrix(c(rep(0,100), seq(0,-360,length.out=101)[-1],rep(0,100)),ncol=3),
          color=rainbow(100), smooth = FALSE, clear_previous = TRUE)
render_snapshot()
#Style the pole with a different color
render_obj(flag_pole_obj(),
          lat = unlist(circle_coords_lat), long = unlist(circle_coords_long),
          scale=c(2,2,2),
          angle=matrix(c(rep(0,100), seq(0,-360,length.out=101)[-1],rep(0,100)),ncol=3),
          color="grey20", smooth = FALSE, clear_previous = TRUE)
render_obj(flag_banner_obj(),
          lat = unlist(circle_coords_lat), long = unlist(circle_coords_long),
          scale=c(2,2,2),
          angle=matrix(c(rep(0,100), seq(0,-360,length.out=101)[-1],rep(0,100)),ncol=3),
          color=rainbow(100), smooth = FALSE)

#And all of these work with `render_highquality()`
render_highquality(samples = 16)

Render Path

Description

Adds a 3D path to the current scene, using x/y coordinates in the reference system defined by the extent object. If no altitude is provided, the path will be elevated a constant offset above the heightmap. If the path goes off the edge, the nearest height on the heightmap will be used.

Cache fallback messages are disabled by default. Set options(rayshader.verbose_scene_cache = TRUE) to print when cached metadata is reused.

Usage

render_path(
  y = NULL,
  x = NULL,
  altitude = NULL,
  groups = NULL,
  resample_evenly = FALSE,
  resample_n = 360,
  reorder = FALSE,
  reorder_first_index = 1,
  reorder_duplicate_tolerance = 0.1,
  reorder_merge_tolerance = 1,
  simplify_tolerance = 0,
  linewidth = 0.5,
  color = "black",
  antialias = FALSE,
  offset = 5,
  clear_previous = FALSE,
  return_coords = FALSE,
  tag = "path3d",
  lat = NULL,
  long = NULL,
  crs = NULL,
  filter_to_extent = TRUE,
  extent = NULL,
  panel = NULL,
  zscale = 1,
  vertical_exaggeration = 1,
  heightmap = NULL
)

Arguments

y

Vector of y coordinates (or other coordinate in the same coordinate reference system as extent). Can also be an sf or SpatialLineDataFrame object.

x

Default NULL. Vector of x coordinates (or other coordinate in the same coordinate reference system as extent). Ignored if y is an sf or SpatialLineDataFrame object.

altitude

Default NULL. Elevation of each point, in units of the elevation matrix (scaled by zscale). If left NULL, this will be just the elevation value at ths surface, offset by offset. If a single value, all data will be rendered at that altitude.

groups

Default NULL. Integer vector specifying the grouping of each x/y path segment, if x/y are specified as numeric vectors (as opposed to sf or SpatialLineDataFrame objects, where this information is built-in to the object).

resample_evenly

Default FALSE. If TRUE, this will re-sample the path evenly from beginning to end, which can help vastly reduce the number of points used to draw it (which can improve the performance of render_highquality() and render_snapshot() when using software_render = TRUE). This function works only if reorder = TRUE, or if the sf object is already ordered from beginning to end.

resample_n

Default 360. Number of breaks in which to evenly resample the line if resample_evenly = TRUE.

reorder

Default FALSE. If TRUE, this will attempt to re-order the rows within an sf object with multiple paths to be one continuous, end-to-end path. This happens in two steps: merging duplicate paths that have end points that match with another object (within reorder_duplicate_tolerance distance), and then merges them (within reorder_merge_tolerance distance) to form a continuous path.

reorder_first_index

Default 1. The index (row) of the sf object in which to begin the reordering process. This merges and reorders paths within reorder_merge_tolerance distance until it cannot merge any more, and then repeats the process in the opposite direction.

reorder_duplicate_tolerance

Default 0.1. Lines that have start and end points (does not matter which) within this tolerance that match a line already processed (order determined by reorder_first_index) will be discarded.

reorder_merge_tolerance

Default 1. Lines that have start points that are within this distance to a previously processed line's end point (order determined by reorder_first_index) will be reordered within the sf object to form a continuous, end-to-end path.

simplify_tolerance

Default 0 (no simplification). If greater than zero, simplifies the path to the tolerance specified. This happens after the data has been merged if reorder = TRUE. If the input data is specified with long-lat coordinates and sf_use_s2() returns TRUE, then the value of simplify_tolerance must be specified in meters.

linewidth

Default 3. The line width.

color

Default black. Color of the line. Use "height" to color the path by the cached plot_gg() height aesthetic palette.

antialias

Default FALSE. If TRUE, the line with be have anti-aliasing applied. NOTE: anti-aliasing can cause some unpredictable behavior with transparent surfaces.

offset

Default 5. Offset of the track from the surface, if altitude = NULL.

clear_previous

Default FALSE. If TRUE, clears all existing paths for tag. A clear-only call returns without rendering a replacement.

return_coords

Default FALSE. If TRUE, this will return the internal rayshader coordinates of the path, instead of plotting the line.

tag

Default "path3d". The rgl tag to use when adding the path to the scene.

lat

Default NULL. Alias for y for geographic workflows.

long

Default NULL. Alias for x for geographic workflows.

crs

Default NULL. CRS of the input numeric x/y coordinates, or CRS to assign to CRS-less spatial data before transforming it into the active scene CRS. If spatial data already carries a CRS, that CRS is used automatically.

filter_to_extent

Default TRUE. If TRUE, path data outside the scene extent is omitted. Spatial line inputs are cropped to the extent. For scenes created with plot_gg(), filtering uses the ggplot panel extent rather than the full rendered 3D ggplot extent.

extent

Either an object representing the spatial extent of the 3D scene (either from the raster, terra, sf, or sp packages), a length-4 numeric vector specifying c("xmin", "xmax","ymin","ymax"), or the spatial object (from the previously aforementioned packages) which will be automatically converted to an extent object. If omitted, rayshader will use extent metadata cached by plot_3d() or plot_gg().

panel

Default NULL. Facet panel identifier for scenes created with plot_gg(). Required to disambiguate faceted ggplot scenes when panel-specific cached metadata is needed. Ignored for non-ggplot scenes.

zscale

Default 1. The ratio between the x and y spacing (which are assumed to be equal) and the z axis in the original heightmap.

vertical_exaggeration

Default 1. Multiplier applied to the effective visual relief. If omitted, rayshader uses the cached scene value from plot_3d() or plot_gg() when available; pass explicitly to override for this call.

heightmap

Default NULL. Height matrix for the current scene. If omitted, this is taken from the cached scene set by plot_3d() or plot_gg(). Pass explicitly to override the cached value. All points are assumed to be evenly spaced.

Examples

#Starting at Moss Landing in Monterey Bay, we are going to simulate a flight of a bird going
#out to sea and diving for food.

#First, create simulated lat/long data
set.seed(2009)
moss_landing_coord = c(36.806807, -121.793332)
x_vel_out = -0.001 + rnorm(1000)[1:300]/1000
y_vel_out = rnorm(1000)[1:300]/200
z_out = c(seq(0,2000,length.out = 180), seq(2000,0,length.out=10),
         seq(0,2000,length.out = 100), seq(2000,0,length.out=10))

bird_track_lat = list()
bird_track_long = list()
bird_track_lat[[1]] = moss_landing_coord[1]
bird_track_long[[1]] = moss_landing_coord[2]
for(i in 2:300) {
bird_track_lat[[i]] = bird_track_lat[[i-1]] + y_vel_out[i]
bird_track_long[[i]] = bird_track_long[[i-1]] + x_vel_out[i]
}


#Render the 3D map
montereybay_spatial |>
 sphere_shade(vertical_exaggeration = 10) |>
 plot_3d(vertical_exaggeration = 4,water=TRUE,
         shadow_color="#40310a", water_color="#233aa1", background = "tan",
         theta=210,  phi=22, zoom=0.20, fov=55)

#Pass in the latitude/longitude coordinates and altitudes of the track.
render_path(lat = unlist(bird_track_lat), long = unlist(bird_track_long),
           altitude = z_out, color="white", antialias=TRUE)
render_snapshot()
#We'll set the altitude to right above the water to give the tracks a "shadow".
render_path(lat = unlist(bird_track_lat), long = unlist(bird_track_long),
           altitude = 10, color="black", antialias=TRUE)
render_camera(theta=30,phi=35,zoom=0.45,fov=70)
render_snapshot()

#Remove the path:
render_path(clear_previous=TRUE)

#Finally, we can also plot just GPS coordinates offset from the surface by leaving altitude `NULL`
# Here we plot a spiral of values surrounding Moss Landing.

t = seq(0,2*pi,length.out=1000)
circle_coords_lat = moss_landing_coord[1] + 0.5 * t/8 * sin(t*6)
circle_coords_long = moss_landing_coord[2] + 0.5 * t/8 *  cos(t*6)
render_path(lat = unlist(circle_coords_lat), long = unlist(circle_coords_long),
           color="red", antialias=TRUE,offset=100, linewidth=5)
render_camera(theta = 160, phi=33, zoom=0.4, fov=55)
render_snapshot()

#And all of these work with `render_highquality()`. Here, I set `use_extruded_paths = TRUE`
#to get thick continuous paths.
render_highquality(line_radius=1, min_variance = 0,
                  use_extruded_paths = TRUE, samples = 16)
#We can also change the material of the objects by setting the `rgl_materials`
#argument in `render_highquality()`
render_highquality(line_radius=1, min_variance = 0, samples = 16,
                  use_extruded_paths = TRUE,
                  rgl_materials = list(path3d = list(
                    material = rayrender::glossy,
                    args = list(gloss = 0.5, reflectance = 0.2)
                  )))
#Render the path with a neon light material
render_highquality(light = FALSE, samples = 16,
                  line_radius = 0.1,
                  ground_size = 0,
                  use_extruded_paths = TRUE,
                  rgl_materials = list(path3d = list(
                    material = rayrender::light,
                    args = list(importance_sample = FALSE,
                                color = "purple", intensity = 2)
                  )))

#For transmissive materials (like `dielectric`), we should specify that the path
#should be rendered with an extruded path. We'll use the `attenuation` argument in
#the `dielectric` function to specify a realistic glass color.
render_path(clear_previous = TRUE,
           lat = unlist(circle_coords_lat), long = unlist(circle_coords_long),
           color="white", offset=200, linewidth=5)
render_highquality(line_radius=1, min_variance = 0, samples = 16,
                  light_size = 60, light_intensity = 10,
                  use_extruded_paths = TRUE,
                  rgl_materials = list(path3d = list(
                    material = rayrender::dielectric,
                    args = list(refraction = 1.5, attenuation = c(0.05,0.2,0.2))
                  )))

Render People

Description

Adds one or more 3D people to an existing rayshader scene. The bundled person models use meter-based coordinates and are scaled using the scene's effective zscale, including vertical_exaggeration, so that their native 1.8-meter standing stature remains correctly sized relative to the terrain. Choose from several bundled poses with pose and select the model variant with sex. The bundled Wavefront OBJ models use .txt file extensions for R package compatibility.

When line is supplied, or location contains line geometry, people are placed along each line component at regular intervals. Their local +Z axes follow the direction of the line. Use line_pattern to repeat male and female variants along the sampled positions.

Cache fallback messages are disabled by default. Set options(rayshader.verbose_scene_cache = TRUE) to print when cached metadata is reused.

Usage

render_people(
  location = NULL,
  pose = "standing",
  sex = "male",
  line = NULL,
  line_spacing = 2,
  line_terrain_spacing = TRUE,
  line_pattern = NULL,
  line_align_terrain = TRUE,
  color = "white",
  angle = c(0, 0, 0),
  lit = TRUE,
  load_normals = TRUE,
  clear_previous = FALSE,
  x = NULL,
  y = NULL,
  altitude = NULL,
  xyz = NULL,
  offset = 0,
  lat = NULL,
  long = NULL,
  crs = NULL,
  filter_to_extent = TRUE,
  extent = NULL,
  panel = NULL,
  zscale = 1,
  vertical_exaggeration = 1,
  heightmap = NULL,
  simple_rgl = FALSE,
  ...
)

Arguments

location

Default NULL. Spatial input used to place people in the scene. Accepts sf, sfc, sfg, or sp POINT, MULTIPOINT, LINESTRING, or MULTILINESTRING geometries. Point inputs place one model at every point. Line inputs generate placements according to line_spacing. If the input carries a CRS, it is transformed automatically into the active scene CRS. If it has no CRS, supply crs.

pose

Default "standing". Bundled pose to render. Supply one value for every person or a single value to use for all people. Options are "clapping", "ironman", "slipping", "stack", "standing", "stop", "stop_one_hand", "stretch", "walking", "rocky", and "yelling".

sex

Default "male". Person model variant. Options are "male" and "female".

line

Default NULL. Spatial line input along which to place people. Accepts sf, sfc, sfg, or sp LINESTRING or MULTILINESTRING geometry. Line geometry may alternatively be supplied through location.

line_spacing

Default 2. Distance in meters between people placed along a spatial line. For CRS-less lines, this is interpreted in the line's coordinate units. Sampling starts at the beginning of every line component.

line_terrain_spacing

Default TRUE. If TRUE, line spacing is measured along the rendered terrain surface using the heightmap and effective zscale. This keeps neighboring models together on slopes. If terrain metadata is not available, spacing falls back to plan-view distance. Set to FALSE to always use plan-view distance.

line_pattern

Default NULL. Repeating male/female line_pattern used for line placement. Supply a single string containing M and F, such as "MF" or "FMF". Overrides sex for line placements.

line_align_terrain

Default TRUE. If TRUE, line placements are tilted so each person's local +Y up vector matches the terrain normal. The local +Z forward vector is lifted along the terrain without changing its plan-view alignment with the line direction.

color

Default "white". Color of the person model. For line placement, supply one color per generated person or one color per entry in line_pattern; pattern colors are repeated with the pattern. Use "height" to color placed models by the cached plot_gg() height aesthetic palette.

angle

Default c(0, 0, 0). Rotation around the x, y, and z axes. A matrix or list can specify a separate rotation for each person. For line placement, these rotations are added to the automatic line orientation.

lit

Default TRUE. Whether to light the model polygons.

load_normals

Default TRUE. Whether to load normals from the model.

clear_previous

Default FALSE. If TRUE, remove previously rendered people before rendering the new ones. A clear-only call returns without rendering a replacement.

x

Default NULL. Vector of x coordinates (or coordinates in the same coordinate reference system as extent).

y

Default NULL. Vector of y coordinates (or coordinates in the same coordinate reference system as extent).

altitude

Default NULL. Elevation of each person, in units of the elevation matrix. If left NULL, each person is placed on the surface plus offset. A single value places every person at that altitude. When one horizontal location is supplied with multiple altitude values, that location is repeated to place one person at each altitude.

xyz

Default NULL. A three-column numeric matrix in which each row specifies the raw rgl x/y/z coordinates of a person. Overrides coordinate placement and altitude.

offset

Default 0. Offset from the surface when altitude = NULL.

lat

Default NULL. Alias for y for geographic workflows.

long

Default NULL. Alias for x for geographic workflows.

crs

Default NULL. CRS of numeric x/y coordinates, or a CRS to assign to CRS-less spatial data before transforming it into the active scene CRS.

filter_to_extent

Default TRUE. If TRUE, placements outside the scene extent are omitted.

extent

Default NULL. Either an object representing the spatial extent of the scene (from the raster, terra, sf, or sp packages), a length-4 numeric vector specifying c("xmin", "xmax", "ymin", "ymax"), or a spatial object that can be converted to an extent. If omitted, rayshader uses extent metadata cached by plot_3d() or plot_gg().

panel

Default NULL. Facet panel identifier for scenes created with plot_gg(). Required to disambiguate faceted ggplot scenes when panel-specific cached metadata is needed. Ignored for non-ggplot scenes.

zscale

Default 1. Ratio between horizontal spacing and the elevation units in the original heightmap. If omitted, rayshader uses the cached scene value when available.

vertical_exaggeration

Default 1. Multiplier applied to the effective visual relief. If omitted, rayshader uses the cached scene value from plot_3d() or plot_gg() when available; pass explicitly to override it for this call.

heightmap

Default NULL. Height matrix for the current scene. If omitted, rayshader uses the cached scene heightmap from plot_3d() or plot_gg(). Terrain elevations and existing NA cells are read directly from this matrix.

simple_rgl

Default FALSE. Show one colored point per person in rgl instead of expanding the person meshes. render_highquality() replaces these points with full instances grouped by model and material. Use this for large crowds; positions, poses, colors, and rotations are retained.

...

Additional arguments passed to render_obj() and then to rgl::triangles3d().

Examples

# Example 1
# Build a stepped pose gallery.
flat_heightmap = matrix(1:16 / 2, nrow = 4, byrow = TRUE) |>
  rayimage::render_reorient(flipy = TRUE, transpose = TRUE) |>
  rayimage::render_resized(mag = 50, method = "box")
scene_zscale = 1 / 25

flat_heightmap |>
  constant_shade("#800") |>
  plot_3d(
    heightmap = flat_heightmap,
    zscale = scene_zscale,
    vertical_exaggeration = 1,
    shadow_depth = 0,
    solid_depth = 0,
    solid_color = "#800",
    window_size = c(800, 800)
  )
render_camera(
  theta = -28,
  phi = 16,
  zoom = 0.70,
  fov = 0,
  shift_vertical = -10
)

# Place every pose on the podium. The ironman model is raised to
# clear its step, and the tenth person will support a second stack model.
# These x/y values use the raw matrix's cached 1-based extent.
gallery_positions = expand.grid(
  x = seq(25, 175, by = 50),
  y = seq(25, 125, by = 50)
)
gallery_poses = c(
  "standing",
  "walking",
  "stop",
  "stop_one_hand",
  "clapping",
  "yelling",
  "stretch",
  "slipping",
  "stack",
  "stack",
  "ironman",
  "rocky"
)
gallery_positions$offset = 0
gallery_positions$offset[gallery_poses == "ironman"] = 1
stack_index = 10L
stack_position = gallery_positions[stack_index, , drop = FALSE]
person_height = 2
label_clearance = 0.1

# Render and label male pose gallery
render_people(
  pose = gallery_poses,
  sex = "male",
  clear_previous = TRUE,
  x = gallery_positions$x,
  y = gallery_positions$y,
  offset = gallery_positions$offset
)
render_people(
  pose = "stack",
  sex = "male",
  x = stack_position$x,
  y = stack_position$y,
  offset = stack_position$offset + person_height
)

# Label the standalone models first, then label the completed tower above
# its upper person without relying on negative indexing.
regular_label_indices = setdiff(seq_along(gallery_poses), stack_index)
render_label(
  text = gallery_poses[regular_label_indices],
  font = "Helvetica",
  family = "serif",
  font_type = "standard",
  text_color = "white",
  line = FALSE,
  clear_previous = TRUE,
  x = gallery_positions$x[regular_label_indices],
  y = gallery_positions$y[regular_label_indices],
  altitude = gallery_positions$offset[regular_label_indices] +
    person_height + label_clearance,
  relative_z = TRUE
)
render_label(
  text = "stack",
  font = "Helvetica",
  family = "serif",
  font_type = "standard",
  text_color = "white",
  line = FALSE,
  x = stack_position$x,
  y = stack_position$y,
  altitude = stack_position$offset + 2 * person_height + label_clearance,
  relative_z = TRUE
)

# Produce an 800-by-800 high-quality image of the male pose variants.
render_highquality(
  width = 800,
  height = 800,
  sky_sun_elevation = 10,
  sky_sun_azimuth = 160,
  iso = 5,
  samples=16
)

# Female models
render_people(
  pose = gallery_poses,
  sex = "female",
  clear_previous = TRUE,
  x = gallery_positions$x,
  y = gallery_positions$y,
  offset = gallery_positions$offset
)
render_people(
  pose = "stack",
  sex = "female",
  x = stack_position$x,
  y = stack_position$y,
  offset = stack_position$offset + person_height
)
render_highquality(
  width = 800,
  height = 800,
  sky_sun_elevation = 10,
  sky_sun_azimuth = 160,
  iso = 5,
  samples=16
)

# Example 2
# Show the scale of the "volcano" 3D dataset
volcano_dem = volcano_spatial()
volcano_dem |>
  height_shade() |>
  plot_3d(
    window_size = c(800, 800)
  )

render_trails(
  volcano_trails,
  color = "grey50",
  width = 2,
  preview = "mesh",
  width_units = "meters"
)

summit_walk = volcano_trails[
  !is.na(volcano_trails$name) &
    volcano_trails$name == "Puhi Huia Road",
]
render_snapshot()
render_people(
  line = summit_walk,
  pose = "walking",
  line_spacing = 5,
  offset=0.2,
  line_pattern = "MF",
  color = c("#F6E8C3", "white"),
  clear_previous = TRUE
)
render_camera(theta = -36, phi = 15, zoom = 0.08, fov=100)
render_snapshot()

# Example 3
# Arrange alternating models around a closed line. Models orient themselves
# according to the local normal and orient the people along the line
bump_heightmap = rayimage::generate_2d_gaussian(dim = c(30,30)) * 1000
bump_heightmap |>
  height_shade() |>
  plot_3d()

circle_r = function(x) {
  theta = seq(0, 2 * pi, length.out = 200)
  sf::st_linestring(cbind(
    15.5 + x * cos(theta),
    15.5 + x * sin(theta)
  ))
}
people_line = sf::st_sfc(
  circle_r(12.5),
  circle_r(10.5),
  circle_r(8.5),
  circle_r(6.5),
  circle_r(4.5),
  circle_r(2.5)
)
render_people(
  line = people_line,
  pose = "stretch",
  line_pattern = "MF",
  line_spacing = 2,
  color = c("dodgerblue", "tomato"),
)
render_people(
  x = c(13.5, 15.5, 17.5),
  y = rep(15.5, 3),
  offset = c(2,0,2),
  angle = list(c(30,45,0),c(0,0,0),c(30,-45,0)),
  pose = c("ironman", "rocky", "ironman"),
  color = "white"
)
render_camera(location = c(15.5,15.5), theta = 0, phi = 10,zoom=0.2,fov=80)
render_highquality(light_direction = 225,samples=16)

Render Points

Description

Adds 3D datapoints to the current scene, using x/y coordinates in the reference system defined by the extent object. If no altitude is provided, the points will be elevated a constant offset above the heightmap. If the points goes off the edge, the nearest height on the heightmap will be used (unless that value is NA, in which the point will be removed).

Cache fallback messages are disabled by default. Set options(rayshader.verbose_scene_cache = TRUE) to print when cached metadata is reused.

Usage

render_points(
  location = NULL,
  size = 0.5,
  color = "black",
  clear_previous = FALSE,
  x = NULL,
  y = NULL,
  altitude = NULL,
  offset = 5,
  lat = NULL,
  long = NULL,
  crs = NULL,
  filter_to_extent = TRUE,
  extent = NULL,
  panel = NULL,
  zscale = 1,
  vertical_exaggeration = 1,
  heightmap = NULL
)

Arguments

location

Default NULL. Spatial point input used to place the rendered point(s) in the scene. Accepts sf, sfc, sfg, or sp POINT or MULTIPOINT geometries. MULTIPOINT inputs are flattened to point placements internally, and vectorized arguments such as size, color, and altitude are applied against that flattened point count. If the input carries a CRS, it will be transformed automatically into the active scene CRS. If it has no CRS, supply crs.

size

Default 3. The point size. This can be a vector (the same length as x and y) specifying a size for each point.

color

Default black. Color of the point. This can also be a vector specifying the color of each point. Use "height" to color points by the cached plot_gg() height aesthetic palette.

clear_previous

Default FALSE. If TRUE, clears all existing points. A clear-only call returns without rendering a replacement.

x

Vector of x coordinates (or other coordinate in the same coordinate reference system as extent).

y

Vector of y coordinates (or other coordinate in the same coordinate reference system as extent).

altitude

Default NULL. Elevation of each point, in units of the elevation matrix (scaled by zscale). If a single value, all data will be rendered at that altitude.

offset

Default 5. Offset of the track from the surface, if altitude = NULL.

lat

Default NULL. Alias for y for geographic workflows.

long

Default NULL. Alias for x for geographic workflows.

crs

Default NULL. CRS of the input numeric x/y coordinates, or CRS to assign to CRS-less spatial data before transforming it into the active scene CRS. If spatial data already carries a CRS, that CRS is used automatically.

filter_to_extent

Default TRUE. If TRUE, points outside the scene extent are omitted. For scenes created with plot_gg(), filtering uses the ggplot panel extent rather than the full rendered 3D ggplot extent.

extent

Either an object representing the spatial extent of the 3D scene (either from the raster, terra, sf, or sp packages), a length-4 numeric vector specifying c("xmin", "xmax","ymin","ymax"), or the spatial object (from the previously aforementioned packages) which will be automatically converted to an extent object. If omitted, rayshader will use extent metadata cached by plot_3d() or plot_gg().

panel

Default NULL. Facet panel identifier for scenes created with plot_gg(). Required to disambiguate faceted ggplot scenes when panel-specific cached metadata is needed. Ignored for non-ggplot scenes.

zscale

Default 1. The ratio between the x and y spacing (which are assumed to be equal) and the z axis in the original heightmap.

vertical_exaggeration

Default 1. Multiplier applied to the effective visual relief. If omitted, rayshader uses the cached scene value from plot_3d() or plot_gg() when available; pass explicitly to override for this call.

heightmap

Default NULL. Height matrix for the current scene. If omitted, this is taken from the cached scene set by plot_3d() or plot_gg(). Pass explicitly to override the cached value. of matrix extent isn't working. A two-dimensional matrix, where each entry in the matrix is the elevation at that point. All points are assumed to be evenly spaced.

Examples

#Starting at Moss Landing in Monterey Bay, we are going to simulate a flight of a bird going
#out to sea and diving for food.

#First, create simulated lat/long data
set.seed(2009)
moss_landing_coord = c(36.806807, -121.793332)
x_vel_out = -0.001 + rnorm(1000)[1:300]/1000
y_vel_out = rnorm(1000)[1:300]/200
z_out = c(seq(0,2000,length.out = 180), seq(2000,0,length.out=10),
         seq(0,2000,length.out = 100), seq(2000,0,length.out=10))

bird_track_lat = list()
bird_track_long = list()
bird_track_lat[[1]] = moss_landing_coord[1]
bird_track_long[[1]] = moss_landing_coord[2]
for(i in 2:300) {
bird_track_lat[[i]] = bird_track_lat[[i-1]] + y_vel_out[i]
bird_track_long[[i]] = bird_track_long[[i-1]] + x_vel_out[i]
}


#Render the 3D map
montereybay_spatial |>
 sphere_shade(vertical_exaggeration = 20) |>
 plot_3d(vertical_exaggeration = 4,water=TRUE,
         shadow_color="#40310a", background = "tan",
         theta=210,  phi=22, zoom=0.20, fov=55)

#Pass in the latitude/longitude coordinates and altitudes of the track.
render_points(lat = unlist(bird_track_lat), long = unlist(bird_track_long),
             altitude = z_out, color="white")
render_snapshot()
#We'll set the altitude to zero to give the tracks a "shadow" over the water.
render_points(lat = unlist(bird_track_lat), long = unlist(bird_track_long),
             offset = 0, color="black")
render_camera(theta=30,phi=35,zoom=0.45,fov=70)
render_snapshot()
#Remove the points:
render_points(clear_previous=TRUE)

# Finally, we can also plot just GPS coordinates offset from the surface by leaving altitude `NULL`
# Here we plot a circle of values surrounding Moss Landing.

t = seq(0,2*pi,length.out=100)
circle_coords_lat = moss_landing_coord[1] + 0.3 * sin(t)
circle_coords_long = moss_landing_coord[2] + 0.3 * cos(t)
render_points(lat = unlist(circle_coords_lat), long = unlist(circle_coords_long),
           color="red", offset=100, size=5)
render_camera(theta = 160, phi=33, zoom=0.4, fov=55)
render_snapshot()
#And all of these work with `render_highquality()`
render_highquality(point_radius = 1, min_variance = 0, samples = 16)

#We can also change the material of the objects by setting the `rgl_materials`
#argument in `render_highquality()`
render_highquality(point_radius = 1, min_variance = 0, samples = 16,
                  rgl_materials = list(points3d = list(
                    material = rayrender::glossy,
                    args = list(gloss = 0.5, reflectance = 0.2)
                  )))
#Render the points with a neon light material
render_highquality(
	light = FALSE,
	samples = 32,
	point_radius = 0.5,
	ground_size = 0,
 min_variance = 0, min_adaptive_size = 1,
	use_extruded_paths = TRUE,
	rgl_materials = list(
		points3d = list(
			material = rayrender::light,
			args = list(importance_sample = FALSE, color = "purple", intensity = 100)
		)
	)
)

Render Polygons

Description

Adds 3D polygons to the current scene, using latitude/longitude or coordinates in the reference system defined by the extent object.

Cache fallback messages are disabled by default. Set options(rayshader.verbose_scene_cache = TRUE) to print when cached metadata is reused.

Usage

render_polygons(
  polygon,
  color = "red",
  top = 1,
  bottom = NA,
  data_column_top = NULL,
  data_column_bottom = NULL,
  scale_data = 1,
  parallel = FALSE,
  holes = 0,
  alpha = 1,
  lit = TRUE,
  light_altitude = c(45, 30),
  light_direction = c(315, 135),
  light_intensity = 0.3,
  light_relative = FALSE,
  clear_previous = FALSE,
  crs = NULL,
  filter_to_extent = TRUE,
  extent = NULL,
  panel = NULL,
  zscale = 1,
  vertical_exaggeration = 1,
  heightmap = NULL,
  ...
)

Arguments

polygon

sf object, "SpatialPolygon" sp object, or xy coordinates of polygon represented in a way that can be processed by xy.coords(). If xy-coordinate based polygons are open, they will be closed by adding an edge from the last point to the first.

color

Default black. Color of the polygon. Use "height" to color polygons by the cached plot_gg() height aesthetic palette using data_column_top, data_column_bottom, or top.

top

Default 1. Extruded top distance. If this equals bottom, the polygon will not be extruded and just the one side will be rendered.

bottom

Default NA. Extruded bottom distance. With NA, places the bottom halfway between the scene's base and lowest surface. If this equals top, the polygon will not be extruded and just the one side will be rendered.

data_column_top

Default NULL. A string indicating the column in the sf object to use to specify the top of the extruded polygon. Values are coerced to numeric, and rows with missing or non-finite values after coercion are omitted.

data_column_bottom

Default NULL. A string indicating the column in the sf object to use to specify the bottom of the extruded polygon. Values are coerced to numeric, and rows with missing or non-finite values after coercion are omitted.

scale_data

Default 1. If specifying data_column_top or data_column_bottom, how much to scale that value when rendering. When omitted in a mapped plot_gg() scene, data-column values use the cached ggplot height scale. Supplying scale_data explicitly uses raw values multiplied by this factor instead. Explicit top and bottom remain in scene height units. If used with vertical_exaggeration, both are applied.

parallel

Default FALSE. If TRUE, polygons will be extruded in parallel, which may be faster (depending on how many geometries are in polygon).

holes

Default 0. If passing in a polygon directly, this specifies which index represents the holes in the polygon. See the earcut function in the decido package for more information.

alpha

Default 1. Transparency of the polygons.

lit

Default TRUE. Whether to light the polygons.

light_altitude

Default c(45, 60). Degree(s) from the horizon from which to light the polygons.

light_direction

Default c(45, 60). Degree(s) from north from which to light the polygons.

light_intensity

Default 0.3. Intensity of the specular highlight on the polygons.

light_relative

Default FALSE. Whether the light direction should be taken relative to the camera, or absolute.

clear_previous

Default FALSE. If TRUE, clears all existing polygons. A clear-only call returns without rendering a replacement.

crs

Default NULL. CRS of the input numeric x/y coordinates, or CRS to assign to CRS-less spatial data before transforming it into the active scene CRS. If spatial data already carries a CRS, that CRS is used automatically.

filter_to_extent

Default TRUE. If TRUE, polygon data outside the scene extent is omitted. Spatial polygon inputs are cropped to the extent. For scenes created with plot_gg(), filtering uses the ggplot panel extent rather than the full rendered 3D ggplot extent.

extent

Either an object representing the spatial extent of the 3D scene (either from the raster, terra, sf, or sp packages), a length-4 numeric vector specifying c("xmin", "xmax", "ymin", "ymax"), or the spatial object (from the previously aforementioned packages) which will be automatically converted to an extent object. If omitted, rayshader will use extent metadata cached by plot_3d() or plot_gg().

panel

Default NULL. Facet panel identifier for scenes created with plot_gg(). Required to disambiguate faceted ggplot scenes when panel-specific cached metadata is needed. Ignored for non-ggplot scenes.

zscale

Default 1. The ratio between the x and y spacing (which are assumed to be equal) and the z axis in the original heightmap.

vertical_exaggeration

Default 1. Multiplier applied to the effective visual relief. If omitted, rayshader uses the cached scene value from plot_3d() or plot_gg() when available; pass explicitly to override for this call.

heightmap

Default NULL. Height matrix for the current scene. If omitted, this is taken from the cached scene set by plot_3d() or plot_gg(). Pass explicitly to override the cached value. of matrix extent isn't working. A two-dimensional matrix, where each entry in the matrix is the elevation at that point. All points are assumed to be evenly spaced.

...

Additional arguments passed to rgl::triangles3d().

Examples

#Render the county borders as polygons in Monterey Bay
montereybay_spatial |>
  sphere_shade(texture = "desert", vertical_exaggeration = 20) |>
  add_shadow(ray_shade(vertical_exaggeration = 4)) |>
  plot_3d(water = TRUE, vertical_exaggeration = 4, window_size = 800, water_color = "dodgerblue")
render_camera(theta = 140,  phi = 55, zoom = 0.85, fov = 30)

#We will apply a negative buffer to create space between adjacent polygons. You may
#have to call `sf::sf_use_s2(FALSE)` before running this code to get it to run.
sf::sf_use_s2(FALSE)
mont_county_buff = sf::st_simplify(sf::st_buffer(monterey_counties_sf,-0.003), dTolerance=0.001)

render_polygons(mont_county_buff, top = 2000,
                parallel = FALSE)
render_snapshot()
#We can specify the bottom of the polygons as well. Here I float the polygons above the surface
#by specifying the bottom argument. We clear the previous polygons with `clear_previous = TRUE`.
render_camera(theta=-60,  phi=20, zoom = 0.85, fov=0)
render_polygons(mont_county_buff, bottom = 24000, top=25000,
                parallel=FALSE,clear_previous=TRUE)
render_snapshot()
#We can set the height of the data to a column in the sf object: we'll use the land area.
#We'll have to scale this value because its max value is 2.6 billion:
render_camera(theta=-60,  phi=40, zoom = 0.85, fov=30)
render_polygons(mont_county_buff, data_column_top = "ALAND",
                scale_data = 300/(5E7), color = "chartreuse4",
                clear_previous = TRUE)
render_zaxis(data = "polygon", location = "topright",
             title_location = "top")
render_snapshot()
#This function also works with `render_highquality()`
render_highquality(samples = 16, min_variance = 0)

Render Raymesh

Description

Adds 3D raymesh model to the current scene, using x/y coordinates in the reference system defined by the extent object. If no altitude is provided, the raymesh will be elevated a constant offset above the heightmap. If the raymesh goes off the edge, the raymesh will be filtered out.

Cache fallback messages are disabled by default. Set options(rayshader.verbose_scene_cache = TRUE) to print when cached metadata is reused.

If no x/y coordinates are passed in, the raymesh will be plotted in the coordinate system set by the user-specified extent argument as-is. Use this alongside save_multipolygonz_to_obj() to plot 3D polygons imported from geospatial sources in the proper location (but for ease of use, use render_multipolygonz() to plot this data directly).

Usage

render_raymesh(
  raymesh,
  location = NULL,
  load_normals = TRUE,
  change_material = TRUE,
  color = "grey50",
  obj_zscale = FALSE,
  swap_yz = NULL,
  angle = c(0, 0, 0),
  scale = c(1, 1, 1),
  flat_shading = FALSE,
  lit = FALSE,
  light_altitude = c(45, 30),
  light_direction = c(315, 135),
  light_intensity = 1,
  light_relative = FALSE,
  rgl_tag = "",
  clear_previous = FALSE,
  x = NULL,
  y = NULL,
  altitude = NULL,
  xyz = NULL,
  offset = 0,
  lat = NULL,
  long = NULL,
  crs = NULL,
  filter_to_extent = TRUE,
  extent = NULL,
  panel = NULL,
  zscale = 1,
  vertical_exaggeration = 1,
  heightmap = NULL,
  ...
)

Arguments

raymesh

raymesh object (see the rayvertex package for a description)

location

Default NULL. Spatial point input used to place the rendered object(s) in the scene. Accepts sf, sfc, sfg, or sp POINT or MULTIPOINT geometries. MULTIPOINT inputs are flattened to point placements internally, and vectorized arguments such as scale, angle, color, and altitude are applied against that flattened point count. If the input carries a CRS, it will be transformed automatically into the active scene CRS. If it has no CRS, supply crs.

load_normals

Default TRUE. Whether to load normals for the 3D model.

change_material

Default TRUE. Whether to change the raymesh material (to customize the color).

color

Default black. Color of the 3D model, if load_material = FALSE. Use "height" to color placed models by the cached plot_gg() height aesthetic palette.

obj_zscale

Default FALSE. Whether to scale the size of the OBJ by zscale to have it match the size of the map. If zscale is very big, this will make the model very small.

swap_yz

Default NULL, defaults to FALSE unless plotting raw coordinates (no x/y or lat/long passed). Whether to swap and Y and Z axes. (Y axis is vertical in rayshader coordinates, but data is often provided with Z being vertical).

angle

Default c(0,0,0). Angle of rotation around the x, y, and z axes. If this is a matrix or list, each row (or list entry) specifies the rotation of the nth model specified (number of rows/length of list must equal the length of x/y).

scale

Default c(1,1,1). Amount to scale the 3D model in the x, y, and z axes. If this is a matrix or list, each row (or list entry) specifies the scale of the nth model specified (number of rows/length of list must equal the length of x/y).

flat_shading

Default FALSE. If TRUE, this will use rgl's flat shading.

lit

Default TRUE. Whether to light the polygons.

light_altitude

Default c(45, 60). Degree(s) from the horizon from which to light the polygons.

light_direction

Default c(45, 60). Degree(s) from north from which to light the polygons.

light_intensity

Default 0.3. Intensity of the specular highlight on the polygons.

light_relative

Default FALSE. Whether the light direction should be taken relative to the camera, or absolute.

rgl_tag

Default "". Tag to add to the rgl scene id, will be prefixed by "objraymsh"

clear_previous

Default FALSE. If TRUE, clears all existing raymesh objects for rgl_tag. A clear-only call returns without rendering a replacement.

x

Vector of x coordinates (or other coordinate in the same coordinate reference system as extent).

y

Vector of y coordinates (or other coordinate in the same coordinate reference system as extent).

altitude

Default NULL. Elevation of each point, in units of the elevation matrix (scaled by zscale). If left NULL, this will be just the elevation value at ths surface, offset by offset. If a single value, the OBJ will be rendered at that altitude.

xyz

Default NULL, ignored. A 3 column numeric matrix, with each row specifying the x/y/z coordinates of the OBJ model(s). Overrides x/y, lat/long, and altitude and ignores extent to plot the OBJ in raw rgl coordinates.

offset

Default 5. Offset of the track from the surface, if altitude = NULL.

lat

Default NULL. Alias for y for geographic workflows.

long

Default NULL. Alias for x for geographic workflows.

crs

Default NULL. CRS of the input numeric x/y coordinates, or CRS to assign to CRS-less spatial data before transforming it into the active scene CRS. If spatial data already carries a CRS, that CRS is used automatically.

filter_to_extent

Default TRUE. If TRUE, raymesh placements outside the scene extent are omitted. For scenes created with plot_gg(), filtering uses the ggplot panel extent rather than the full rendered 3D ggplot extent.

extent

Either an object representing the spatial extent of the scene (either from the raster, terra, sf, or sp packages), a length-4 numeric vector specifying c("xmin", "xmax","ymin","ymax"), or the spatial object (from the previously aforementioned packages) which will be automatically converted to an extent object. If omitted, rayshader will use extent metadata cached by plot_3d() or plot_gg().

panel

Default NULL. Facet panel identifier for scenes created with plot_gg(). Required to disambiguate faceted ggplot scenes when panel-specific cached metadata is needed. Ignored for non-ggplot scenes.

zscale

Default 1. The ratio between the x and y spacing (which are assumed to be equal) and the z axis in the original heightmap.

vertical_exaggeration

Default 1. Multiplier applied to the effective visual relief. If omitted, rayshader uses the cached scene value from plot_3d() or plot_gg() when available; pass explicitly to override for this call.

heightmap

Default NULL. Height matrix used to determine terrain elevations and existing NA cells. If omitted, this is taken from the cached scene set by plot_3d() or plot_gg(). Pass explicitly to override the cached value.

...

Additional arguments to pass to rgl::triangles3d().

Examples

# Load the built-in R logo OBJ from rayvertex as a raymesh.
r_logo_mesh = rayvertex::obj_mesh(rayvertex::r_obj(), center = TRUE, angle=c(0,180,0))

# Render the 3D map.
montereybay_spatial |>
 sphere_shade(vertical_exaggeration = 10) |>
 plot_3d(
   vertical_exaggeration = 4,
   water = TRUE,
   shadow_color = "#40310a",
   background = "tan",
   theta = 210,
   phi = 22,
   zoom = 0.20,
   fov = 55
 )

# Place the R logo mesh at point locations, similar to render_points().
moss_landing_coord = c(36.806807, -121.793332)
t = seq(0, 2 * pi, length.out = 30)
circle_coords_lat = moss_landing_coord[1] + 0.3 * sin(t)
circle_coords_long = moss_landing_coord[2] + 0.3 * cos(t)

#Pass in custom angles for each model
render_raymesh(
 raymesh = r_logo_mesh,
 lat = circle_coords_lat,
 long = circle_coords_long,
 offset = 600,
 scale = c(32, 32, 32),
 angle = matrix(c(rep(0,30),-seq(0,360-12,by=12)-90-180,rep(0,30)),ncol=3),
 change_material = FALSE, clear_previous=TRUE
)
render_camera(theta = 160, phi = 33, zoom = 0.4, fov = 55)
render_snapshot()
#And high quality, with a realistic atmosphere
render_highquality(sky_sun_azimuth=10, sky_sun_elevation=10,iso=5)

Resize the rgl Window

Description

Resize the rgl Window

Usage

render_resize_window(width = NULL, height = NULL)

Arguments

width

Default NULL, no change to the current value. New window width.

height

Default NULL, no change to the current value. New window height

Value

None

Examples

#Resize the rgl window to various sizes
montereybay_spatial |>
 sphere_shade(vertical_exaggeration = 10) |>
 plot_3d(vertical_exaggeration = 4,zoom=0.6,theta=-90,phi=30)
render_resize_window(width = 800, height = 800)
render_snapshot()

render_resize_window(width = 200, height = 200)
render_snapshot()
render_resize_window(width = 800, height = 400)
render_snapshot()

Render Road Paths

Description

Adds road paths to the scene and eagerly builds their reusable high-quality meshes. Roads can be previewed as rgl lines or as the same mesh geometry consumed by render_highquality(). Road chains that cannot be represented by either mesh method are omitted with a warning while the remaining meshes continue rendering. Pavement is raised by 0.055 elevation units (5.5 cm for meter elevations), converted using the effective zscale. A small scene-precision margin prevents coplanar top surfaces in large scenes. Pavement thickness stays at 0.11 elevation units independently of that margin.

Usage

render_roads(
  roads,
  road_color = "#303030",
  width = NULL,
  width_column = NULL,
  densify = TRUE,
  offset = 0,
  offset_transition = 0,
  layer = NULL,
  layer_height = 5.5,
  merge = TRUE,
  lane_texture = TRUE,
  lane_texture_file = NULL,
  lane_dash_length = 3,
  lane_gap_length = 10,
  lane_texture_length = NULL,
  lane_texture_mapping = c("auto", "fixed"),
  lanes = 2,
  lane_width = 3,
  lane_color = "#eeeade",
  centerline_color = "#eeeade",
  edge_line_color = "#d6ad3d",
  lane_line_width = 0.035,
  lane_dash_fraction = NULL,
  clear_previous = TRUE,
  preview = c("line", "mesh"),
  verbose = FALSE,
  parallel = TRUE,
  maximum_grade = 0.15,
  continuation_grade_tolerance = 0.14,
  zscale = 1,
  vertical_exaggeration = 1,
  heightmap = NULL,
  terrain_grading = FALSE,
  bridge = NULL,
  ...
)

Arguments

roads

Spatial line data used to draw road paths. Supports sf, sfc, sfg, SpatialLines, and SpatialLinesDataFrame line inputs.

road_color

Default "#303030". sRGB road surface color.

width

Default NULL, which derives road width from lanes and lane_width. If supplied, road width in scene grid-cell units for render_highquality(). The rgl preview uses the same value as line width.

width_column

Default NULL. Column name in an sf road object used to set per-feature road widths. Values must be positive finite numbers and use the same units as width. When supplied, road merging is disabled to preserve feature attributes.

densify

Default TRUE. Whether to densify road paths and resample them along the terrain before render_highquality() meshing. Set to FALSE to use the vertices returned by render_path() directly.

offset

Default 0. Additional vertical road base offset in elevation units above the sampled surface.

offset_transition

Default 0. Length in scene/world units over which each end of a road transitions between the sampled surface and offset. Positive values use the terrain height at the path midpoint plus offset as a constant deck height, with a quadratic Bezier ramp at each end. If a road is shorter than twice this distance, each ramp is shortened to half the road length.

layer

Default NULL. An unquoted or character column name in an sf road object containing OpenStreetMap-style layer values. When omitted, uses the layer column if present; explicit NULL disables this lookup. Missing values are treated as implicit layer 0, except affirmative bridge or elevated location metadata infer effective layer 1 and affirmative tunnel or underground location metadata infer effective layer -1. Inferred values remain distinguishable from explicit OSM layer tags in diagnostics. tunnel = "building_passage" describes a covered passage through a building; it does not imply a below-ground layer or exemption from terrain clearance. Explicit underground location metadata still takes precedence. Roads are grouped by exact physical events and conservative endpoint continuations. A sparse quadratic profile solve enforces crossing clearance, physical grade and grade-rate limits, junction height continuity, and selected through-road grade compatibility. Surface roads retain a sampled terrain reference, elevated spans use endpoint support chords, and roads with explicit tunnel or underground metadata use a bounded terrain-relative reference. Untagged negative layers are not independently activated as tunnels. Ambiguous endpoint matches that would create a contradictory clearance cycle are excluded. Using layer or bridge disables merge and requires the suggested sf, igraph, Matrix, and osqp packages. Terrain-floor constraints use the unmodified DEM across the road width, independently of the smoothed fitting reference. Curved profiles are tessellated before meshing so rendered decks preserve the solved heights between source road vertices.

layer_height

Default 5.5. Either a single positive spacing in elevation units between locally ordered layers, or an unquoted or character column name containing each feature's positive separation above the lower road at an intersection. Column heights override constant layer spacing.

merge

Default TRUE. Whether to merge connected road linework before rendering. This reduces visible joins between adjacent line features in render_highquality().

lane_texture

Default TRUE. If TRUE, render_highquality() uses a generated repeating texture on the top road surface for lane markings.

lane_texture_file

Default NULL. Optional path to a custom road lane texture. When supplied, it is used instead of the generated texture and lane_texture is treated as TRUE.

lane_dash_length

Default 3. Painted dash length in scene/world units for generated dashed lane markings. The default approximates a 10 foot dash as 3 meters.

lane_gap_length

Default 10. Gap length in scene/world units for generated dashed lane markings. The default approximates a 30 foot gap as 10 meters.

lane_texture_length

Default NULL, which uses lane_dash_length + lane_gap_length. Scene-unit length covered by one repetition of the road lane texture.

lane_texture_mapping

Default "auto". If "auto", each road path is assigned a texture repetition count based on its world-unit length and lane_texture_length. If "fixed", all road paths use lane_texture_length directly.

lanes

Default 2. Number of lanes used when generating the default lane texture and, when width = NULL, deriving the road width. May also be an unquoted or character column name in an sf road object. OSM-style compound values use their first positive integer. Missing values first use lanes:forward plus lanes:backward, then fall back to one lane for links and one-way roads or two lanes for other roads.

lane_width

Default 3. Lane width in scene/world units used when width = NULL. The derived road width is lane_width * (lanes + 2). The generated lane texture leaves one lane width total outside the edge lines, split between both sides.

lane_color

Default "#eeeade". sRGB color for dashed lane divider markings.

centerline_color

Default "#eeeade". sRGB color for the center divider.

edge_line_color

Default "#d6ad3d". sRGB color for solid edge markings.

lane_line_width

Default 0.035. Lane marking width as a fraction of the road width in the generated texture.

lane_dash_fraction

Default NULL, which uses lane_dash_length / (lane_dash_length + lane_gap_length). Fraction of each texture repetition occupied by a dash for dashed lane markings.

clear_previous

Default TRUE. If TRUE, removes the existing road layer before drawing the new one. A clear-only call returns without rendering a replacement.

preview

Default "line". Whether roads are drawn in rgl as lightweight "line" previews or as their cached "mesh" geometry. The mesh is the exact high-quality geometry. Lines are raised slightly above the pavement surface for visibility in rgl; this display offset does not affect rendered or exported road geometry.

verbose

Default FALSE. Whether to display progress during road profile preparation, solving, and mesh construction.

parallel

Default TRUE. Whether to use multiple native threads while sampling road terrain contacts and building the cached road meshes.

maximum_grade

Default 0.15. Maximum absolute longitudinal road grade. Positive infinity removes the grade bound.

continuation_grade_tolerance

Default 0.14. Maximum absolute grade mismatch at selected road continuations. Continuation height remains exact.

zscale

Default 1. The ratio between the x and y spacing and the z axis. If omitted and heightmap is a spatial raster, rayshader uses the raster cell resolution.

vertical_exaggeration

Default 1. Multiplier applied to the effective visual relief. If omitted, rayshader uses the cached scene value from plot_3d() or plot_gg() when available; pass explicitly to override for this call.

heightmap

Default NULL. Height matrix or spatial raster for the current scene. If omitted, this is taken from the cached scene set by plot_3d() or plot_gg(). Pass explicitly to override the cached value.

terrain_grading

Default FALSE. Cut the displayed terrain locally beneath road pavement instead of lifting roads over adjacent DEM banks. With layer, surface junctions are held at or below their sampled ground elevation and their approaches are flattened while retaining crossing clearance and grade limits. Explicit tunnels retain their terrain cover. This replaces the scene surface with a regular terrain grid and updates the cached heightmap; it does not modify the input raster or matrix.

bridge

Default NULL. An unquoted or character column name containing bridge status. When omitted, uses the bridge column if present; explicit NULL disables this lookup. Accepts logical values or OSM tags: missing, empty, "no", "false", and "0" mean no bridge; affirmative tags such as "yes" and "viaduct" identify bridges. Bridge status activates the profile solver even without a layer column or an intersecting road. Explicit layer values retain their ordering; missing bridge layers infer layer 1, while ordinary missing layers remain 0. Pass ⁠layer = NULL, bridge = NULL⁠ to disable automatic structure profiles and use terrain-following roads.

...

Deprecated argument spellings are accepted with a warning and forwarded to their current names.

Value

Invisibly returns the rendered road coordinates. When layer or bridge metadata is used, the result has terrain_following, profile_diagnostics, and mesh_topology attributes describing the sparse profile solve and selected physical mesh continuations. With terrain_grading = TRUE, graded_heightmap contains the modified terrain.


Render Scale Bar

Description

Places a scale bar on the map in 3D.

Usage

render_scalebar(
  limits = NULL,
  position = NULL,
  y = NULL,
  segments = 10,
  scale_length = NULL,
  label_unit = NULL,
  offset = NULL,
  radius = NULL,
  color_first = "darkred",
  color_second = "grey80",
  color_text = "black",
  text_switch_side = FALSE,
  text_x_offset = 0,
  text_y_offset = 0,
  text_z_offset = 0,
  clear_previous = FALSE
)

Arguments

limits

Default NULL. The distances represented by the scale bar. If NULL, rayshader uses cached scene dimensions to generate pretty breaks for a bar approximately half the longer side of the map. Otherwise, the maximum value is the total represented distance. Must be non-negative.

position

Default NULL. Scale-bar side: "N", "E", "S", or "W". If NULL, the scale bar follows the longer map axis, using "S" for wider maps and "W" for taller maps.

y

Default NULL. The height of the scale bar, automatically calculated if NULL.

segments

Default 10. Number of colored segments in the scalebar.

scale_length

Default NULL. Length of the scale bar relative to the side selected by position. If NULL, this is calculated from limits and cached spatial metadata. A scalar starts at the beginning of the side; a length-2 vector specifies the start and end proportions.

label_unit

Default NULL. Distance-unit suffix. If NULL, rayshader uses the projected CRS unit, or kilometres for geographic coordinates and metres when kilometres would be too large for the scene.

offset

Default NULL. The distance away from the edge to place the scale bar. If NULL, automatically calculated.

radius

Default NULL. The radius of the cylinder representing the scale bar. If NULL, automatically calculated.

color_first

Default darkred. Primary color in the scale bar.

color_second

Default grey90. Seconary color in the scale bar.

color_text

Default black. Color of the text.

text_switch_side

Default FALSE. Switches the order of the text.

text_x_offset

Default 0. Distance offset for text in the x direction.

text_y_offset

Default 0. Distance offset for text in the y direction.

text_z_offset

Default 0. Distance offset for text in the z direction.

clear_previous

Default FALSE. Clears any existing scale bars before rendering. A clear-only call returns without rendering a replacement.

Value

The resolved scale-bar specification, invisibly.

Examples

#Add an automatically sized scale bar to the montereybay_spatial dataset
montereybay_spatial |>
 sphere_shade(vertical_exaggeration = 20) |>
 plot_3d(theta=45, vertical_exaggeration = 4, water=TRUE)
render_scalebar()
render_snapshot()
#This function works with `render_highquality()`
render_highquality(light_direction = 250, light_altitude = 40, samples = 16)
render_scalebar(clear_previous = TRUE)
#We can change the position by specifying a cardinal direction to `position`, and the
#color by setting `color_first` and `color_second`

render_scalebar(limits=c(0,80), label_unit = "km", position = "N",
               color_first = "darkgreen", color_second = "lightgreen")
render_snapshot()
render_scalebar(clear_previous = TRUE)
#And switch the orientation by setting `text_switch_side = TRUE`
render_scalebar(limits=c(0,80), label_unit = "km", position = "N", text_switch_side = TRUE,
               color_first = "darkgreen", color_second = "lightgreen")
render_snapshot()
render_scalebar(clear_previous = TRUE)
#We can add additional breaks by specifying additional distances in `limits`

render_scalebar(limits=c(0,40,80), label_unit = "km")
render_snapshot()
render_scalebar(clear_previous = TRUE)
#We can also manually specify the height by setting the `y` argument:

render_scalebar(limits=c(0,40,80), y=-70, label_unit = "km")
render_snapshot()
render_scalebar(clear_previous = TRUE)
#Here we change the total size by specifying a start and end point along the side,
#and set the number of colored `segments`:

render_scalebar(limits=c(0,20, 40), segments = 4, scale_length = c(0.5,1), label_unit = "km")
render_scalebar(limits=c(0,20, 40), segments = 4, position = "N", text_switch_side = TRUE,
               scale_length = c(0.25,0.75), label_unit = "km")
render_snapshot()
render_scalebar(clear_previous = TRUE)
#Change the radius of the scale bar with `radius`. Here, the autopositioning doesn't work well with
#the labels, so we provide additional offsets with `text_y_offset` and `text_x_offset` to fix it.

render_scalebar(limits=c(0,20, 40), segments = 4, scale_length = c(0.5,1),
               label_unit = "km", radius=10,text_y_offset=-20,text_x_offset=20)
render_snapshot()

Render Snapshot of 3D Visualization

Description

Either captures the current rgl view and displays, or saves the current view to disk.

Usage

render_snapshot(
  filename,
  clear = FALSE,
  title_text = NULL,
  title_offset = c(20, 20),
  title_color = "black",
  title_size = 30,
  title_font = "sans",
  title_bar_color = NA,
  title_bar_alpha = 0.5,
  title_just = "left",
  image_overlay = NULL,
  vignette = FALSE,
  vignette_color = "black",
  vignette_radius = 1.3,
  instant_capture = interactive(),
  bring_to_front = FALSE,
  webshot = FALSE,
  width = NULL,
  height = NULL,
  software_render = FALSE,
  camera_location = NULL,
  camera_lookat = c(0, 0, 0),
  background = NULL,
  text_angle = NULL,
  text_size = 30,
  text_offset = c(0, 0, 0),
  point_radius = 0.5,
  line_offset = 1e-07,
  thick_lines = TRUE,
  line_radius = 0.25,
  new_page = TRUE,
  print_scene_info = FALSE,
  fsaa = 1,
  rayvertex_lighting = FALSE,
  rayvertex_lights = NULL,
  rayvertex_shadow_map = FALSE,
  plot = TRUE,
  cache_scene = FALSE,
  reset_scene_cache = FALSE,
  ...
)

Arguments

filename

Filename of snapshot. If missing, will display to current device.

clear

Default FALSE. If TRUE, the current rgl device will be cleared.

title_text

Default NULL. Text. Adds a title to the image, using magick::image_annotate.

title_offset

Default c(20,20). Distance from the top-left (default, gravity direction in image_annotate) corner to offset the title.

title_color

Default black. Font color.

title_size

Default 30. Font size in pixels.

title_font

Default sans. String with font family such as "sans", "mono", "serif", "Times", "Helvetica", "Trebuchet", "Georgia", "Palatino" or "Comic Sans".

title_bar_color

Default NA. If a color, this will create a colored bar under the title.

title_bar_alpha

Default 0.5. Transparency of the title bar.

title_just

Default left. Justification of the title.

image_overlay

Default NULL. Either a string indicating the location of a png image to overlay over the image (transparency included), or a 4-layer RGBA array. This image will be resized to the dimension of the image if it does not match exactly.

vignette

Default FALSE. If TRUE or numeric, a camera vignetting effect will be added to the image. 1 is the darkest vignetting, while 0 is no vignetting. If vignette is a length-2 vector, the second entry will control the blurriness of the vignette effect.

vignette_color

Default "black". Color of the vignette.

vignette_radius

Default 1.3. Radius of the vignette, as a porportion of the image dimensions.

instant_capture

Default TRUE if interactive, FALSE otherwise. If FALSE, a slight delay is added before taking the snapshot. This can help stop prevent rendering issues when running scripts.

bring_to_front

Default FALSE. Whether to bring the window to the front when taking the snapshot.

webshot

Default FALSE. Set to TRUE to have rgl use the webshot2 package to take images, which can be used when rgl.useNULL = TRUE.

width

Default NULL. Optional argument to pass to rgl::snapshot3d() to specify the width when software_render = TRUE..

height

Default NULL. Optional argument to pass to rgl::snapshot3d() to specify the height when software_render = TRUE.

software_render

Default FALSE. If TRUE, rayshader will use the rayvertex package to render the snapshot, which is not constrained by the screen size or requires OpenGL.

camera_location

Default NULL. Custom position of the camera. The FOV, width, and height arguments will still be derived from the rgl window.

camera_lookat

Default NULL. Custom point at which the camera is directed. The FOV, width, and height arguments will still be derived from the rgl window.

background

Default NULL, defaults to device background. Background color when software_render = TRUE.

text_angle

Default NULL, which forces the text always to face the camera. If a single angle (degrees), will specify the absolute angle all the labels are facing. If three angles, this will specify all three orientations (relative to the x,y, and z axes) of the text labels.

text_size

Default 30. Height of the text.

text_offset

Default c(0,0,0). Offset to be applied to all text labels.

point_radius

Default 0.5. Radius of 3D points (rendered with render_points()). This scales the existing value of size specified in render_points().

line_offset

Default 1e-7. Small number indicating the offset in the scene to apply to lines if using software rendering. Increase this if your lines aren't showing up, or decrease it if lines are appearing through solid objects.

thick_lines

Default TRUE. If software_render = TRUE, this will render path segments as thick cylinders. Otherwise, it will render the lines using a single-pixel anti-aliased line algorithm.

line_radius

Default 0.25. The radius of the thick cylinders if thick_lines = TRUE and software_render = TRUE.

new_page

Default TRUE. Whether to call grid::grid.newpage() before plotting the image.

print_scene_info

Default FALSE. If TRUE, it will print the position and lookat point of the camera.

fsaa

Default 1. Integer specifying the amount of anti-aliasing applied software_render = TRUE.

rayvertex_lighting

Default FALSE. If TRUE and software_render = TRUE, the scene will use rayvertex lighting when rendering the scene, using the lights specified in rayvertex_lights. If no lights are specified there, they will be pulled from light objects in the rgl scene.

rayvertex_lights

Default NULL. Use rayvertex::directional_light() and rayvertex::point_light() along with the rayvertex::add_light() function to specify lighting for your scene when rayvertex_lighting = TRUE.

rayvertex_shadow_map

Default FALSE. If TRUE and rayvertex_lighting = TRUE along with software_render = TRUE, shadow mapping will also be applied to the rendered scene.

plot

Default TRUE. Whether to plot the snapshot.

cache_scene

Default FALSE. Whether to cache the current scene to memory so it does not have to be converted to a raymesh object each time render_snapshot() is called. If TRUE and a scene has been cached, it will be used when rendering.

reset_scene_cache

Default FALSE. Resets the scene cache before rendering.

...

Additional parameters to pass to rayvertex::rasterize_scene().

Value

Displays snapshot of current rgl plot (or saves to disk), as well as invisibly returns an RGBA rayimg array.

Examples

montereybay_spatial |>
 sphere_shade(vertical_exaggeration = 20) |>
 plot_3d(vertical_exaggeration = 4,zoom=0.6,theta=-90,phi=30)

render_snapshot()

#Create a title
render_snapshot(title_text = "Monterey Bay, California", title_offset=c(0,20),
               title_color = "white", title_bar_color = "black",
               title_font = "Helvetica", title_position = "north")

#Add a vignette effect
render_camera(zoom=0.8)
render_snapshot(title_text = "Monterey Bay, California",
               title_color = "white", title_bar_color = "darkgreen",
               vignette = TRUE, title_offset=c(0,20),
               title_font = "Helvetica", title_position = "north")
#Use software rendering to render a scene with shadow mapping
montereybay_spatial |>
 height_shade() |>
 plot_3d(shadow=FALSE, solid_line_color = NULL, vertical_exaggeration = 4)
#No shadows
render_snapshot(software_render = TRUE)
#Now with shadow mapped shadows, calculated in rayvertex
render_snapshot(rayvertex_lighting = TRUE,
               rayvertex_lights = rayvertex::directional_light(intensity = 1.2,
                                                               direction = c(-1, 1, -1)),
               rayvertex_shadow_map = TRUE, software_render = TRUE)

Render Stream Paths

Description

Adds stream paths to the scene, removing the previous stream layer if desired.

Usage

render_streams(
  streams,
  water_color = "lightblue",
  width = 1,
  width_column = NULL,
  width_units = c("scene", "meters"),
  densify = TRUE,
  offset = NULL,
  merge = TRUE,
  water_polygons = NULL,
  height = 0.05,
  clear_previous = TRUE,
  verbose = FALSE,
  parallel = TRUE,
  zscale = 1,
  vertical_exaggeration = 1,
  heightmap = NULL,
  ...
)

Arguments

streams

Spatial line data used to draw stream paths. Supports sf, sfc, sfg, SpatialLines, and SpatialLinesDataFrame line inputs.

water_color

Default "lightblue". Stream color.

width

Default 1. Stream width in the units selected by width_units for render_highquality(). The rgl preview uses the converted scene width as its line width.

width_column

Default NULL. Column name in an sf stream object used to set per-feature stream widths. Values must be positive finite numbers and use the same units as width. When supplied, stream merging is disabled to preserve feature attributes.

width_units

Default "scene". Units used by width and width_column. "scene" treats values as scene grid-cell units, preserving the legacy behavior. "meters" converts physical widths to scene units from the cached or supplied spatial extent and CRS.

densify

Default TRUE. Whether to densify stream paths and resample them along the terrain before render_highquality() meshing. Set to FALSE to use the vertices returned by render_path() directly.

offset

Default NULL. Vertical stream centerline offset in elevation units. When NULL, the stream centerline is placed on the sampled surface so the high-quality rectangular stream profile is rendered halfway through the terrain.

merge

Default TRUE. Whether to merge connected stream linework before rendering. This reduces visible caps between adjacent line features in render_highquality().

water_polygons

Default NULL. Optional polygon data defining water areas where streams should not be rendered. Supports sf, sfc, sfg, terra::SpatVector, SpatialPolygons, and SpatialPolygonsDataFrame inputs. Multiple polygons are combined before they are removed from the stream linework. When both inputs have a CRS, the polygons are transformed to the stream CRS before clipping. When only one input has a CRS, an error is returned rather than assuming the coordinate systems match.

height

Default 0.05. Total stream mesh thickness in scene units for render_highquality(). This is independent of width and centered on the sampled stream path, leaving the top surface slightly above the terrain.

clear_previous

Default TRUE. If TRUE, removes the existing stream layer before drawing the new one. A clear-only call returns without rendering a replacement.

verbose

Default FALSE. Whether to show native stream-meshing progress.

parallel

Default TRUE. Whether to build independent stream meshes in parallel with the native job queue.

zscale

Default 1. The ratio between the x and y spacing and the z axis. If omitted and heightmap is a spatial raster, rayshader uses the raster cell resolution.

vertical_exaggeration

Default 1. Multiplier applied to the effective visual relief. If omitted, rayshader uses the cached scene value from plot_3d() or plot_gg() when available; pass explicitly to override for this call.

heightmap

Default NULL. Height matrix or spatial raster for the current scene. If omitted, this is taken from the cached scene set by plot_3d() or plot_gg(). Pass explicitly to override the cached value.

...

Deprecated argument spellings are accepted with a warning and forwarded to their current names.

Value

Invisibly returns the rendered stream coordinates.

Examples

library(sf)
library(terra)
library(dplyr)
library(tigris)
library(elevatr)

options(tigris_use_cache = TRUE)

target_crs = "EPSG:32611"
dem_z = 12
min_water_area_m2 = 5000
min_stream_length_m = 1

# Start with a longitude/latitude bounding box for the Mammoth Lakes,
# June Lake, and Crowley Lake region.
scene_ll = sf::st_as_sfc(
  sf::st_bbox(
    c(
      xmin = -119.12,
      ymin = 37.52,
      xmax = -118.68,
      ymax = 37.86
    ),
    crs = sf::st_crs(4326)
  )
) |>
  sf::st_as_sf()

# Transform to UTM zone 11N so areas, lengths, and stream widths are in
# projected meter-like units.
scene = sf::st_transform(scene_ll, target_crs)

# TIGER/Line area water includes lakes and reservoirs. We crop to the scene,
# keep larger standing-water features, and later sample each water body's
# representative elevation from the DEM.
water_raw = tigris::area_water(
  state = "CA",
  county = "Mono",
  year = 2024,
  class = "sf"
)

water = water_raw |>
  sf::st_make_valid() |>
  sf::st_transform(target_crs) |>
  sf::st_crop(scene) |>
  dplyr::filter(MTFCC %in% c("H2030", "H2040")) |>
  dplyr::mutate(area_m2 = as.numeric(sf::st_area(geometry))) |>
  dplyr::filter(area_m2 >= min_water_area_m2)

water = water[!sf::st_is_empty(water), ]

# Download a DEM from AWS via elevatr and aggregate it to keep the example
# light enough for interactive rendering.
dem_raw = elevatr::get_elev_raster(
  locations = scene,
  z = dem_z,
  src = "aws",
  clip = "bbox",
  tmp_dir = tempdir()
)

dem = terra::rast(dem_raw) |>
  terra::aggregate(4)
names(dem) = "elevation_m"

water = sf::st_transform(water, terra::crs(dem))

water_level = terra::extract(
  dem,
  terra::vect(water),
  fun = median,
  na.rm = TRUE,
  touches = TRUE
)

water$water_level_m = round(water_level$elevation_m, 1)
water = water[is.finite(water$water_level_m), ]

# TIGER/Line linear water gives the stream and canal network. We crop,
# extract line strings, drop empty features, and remove tiny segments.
streams_raw = tigris::linear_water(
  state = "CA",
  county = "Mono",
  year = 2024,
  class = "sf"
)

streams = streams_raw |>
  sf::st_make_valid() |>
  sf::st_transform(target_crs) |>
  sf::st_crop(scene) |>
  sf::st_collection_extract("LINESTRING", warn = FALSE)

streams = streams[!sf::st_is_empty(streams), ]

streams = streams |>
  dplyr::mutate(length_m = as.numeric(sf::st_length(geometry))) |>
  dplyr::filter(length_m >= min_stream_length_m)

streams = sf::st_transform(streams, terra::crs(dem))

# Rasterize per-waterbody elevations for render_water(), then lower the
# terrain under polygon water so the rendered water surface is visible.
water_level_rast = terra::rasterize(
  terra::vect(water),
  dem,
  field = "water_level_m",
  touches = TRUE
)

new_dem = dem |>
  shift_terrain(water, amount = -10)

new_dem |>
  height_shade() |>
  plot_3d(
    phi = 10,
    zoom = 0.15,
    fov = 120
  )

render_water(
  water_input = water_level_rast,
  water_edge_extension = 0.25,
  water_color = "dodgerblue"
)

render_streams(
  streams = streams,
  water_polygons = water,
  water_color = "dodgerblue",
  width = 0.35,
  clear_previous = TRUE
)

render_highquality(
  joined_stream_mesh = TRUE,
  use_extruded_paths = TRUE,
  sky_sun_elevation = 30,
  width = 800,
  height = 800,
  sky_sun_azimuth = -113,
  sky_args = list(hosek = FALSE),
  camera_lookat = c(-183.38, -1.20, -232.91),
  camera_location = c(-279.37, 49.51, -177.42),
  water_ior = 1.2,
  water_material = "microfacet",
  iso = 100 / 2^5
)

Render Trail Paths

Description

Adds trails that follow the terrain surface. Trails use lightweight rgl line previews while caching solid meshes for render_highquality(). Each input line is meshed independently, without road grades, lanes, layer rules, intersection solving, or mesh joining.

Usage

render_trails(
  trails,
  color = "grey50",
  width = 1,
  width_column = NULL,
  width_units = c("scene", "meters"),
  densify = TRUE,
  offset = NULL,
  height = 0.05,
  clear_previous = TRUE,
  preview = c("line", "mesh"),
  verbose = FALSE,
  parallel = TRUE,
  zscale = 1,
  vertical_exaggeration = 1,
  heightmap = NULL
)

Arguments

trails

Spatial line data used to draw trails. Supports sf, sfc, sfg, SpatialLines, and SpatialLinesDataFrame line inputs.

color

Default "grey50". Trail color.

width

Default 1. Trail width in the units selected by width_units.

width_column

Default NULL. Column name in an sf trail object used to set per-feature trail widths. Values must be positive finite numbers and use the same units as width.

width_units

Default "scene". Units used by width and width_column. "scene" uses scene grid-cell units; "meters" converts physical widths using the scene extent and CRS.

densify

Default TRUE. Whether to densify trails and resample them along the terrain before meshing.

offset

Default NULL. Vertical trail centerline offset in elevation units. When NULL, the mesh is centered on the terrain surface.

height

Default 0.05. Total solid mesh thickness in scene units.

clear_previous

Default TRUE. Whether to remove the existing trail layer before drawing the new one. A clear-only call returns without drawing a replacement.

preview

Default "line". Whether trails are drawn in rgl as lightweight "line" previews or as their cached "mesh" geometry. Both options use the solid mesh in render_highquality().

verbose

Default FALSE. Whether to show native meshing progress.

parallel

Default TRUE. Whether to build independent trail meshes in parallel with the native job queue.

zscale

Default 1. Ratio between horizontal spacing and elevation units. If omitted for a spatial raster scene, rayshader uses its resolution.

vertical_exaggeration

Default 1. Multiplier applied to the effective visual relief. If omitted, rayshader uses the active scene value.

heightmap

Default NULL. Height matrix or spatial raster for the current scene. If omitted, rayshader uses the active scene heightmap.

Value

Invisibly returns the independently meshed trail coordinates.

See Also

render_streams(), render_roads()

Examples

volcano_dem = volcano_spatial()
volcano_dem |>
  height_shade() |>
  plot_3d()

render_trails(
  volcano_trails,
  color = "grey50",
  width = 3,
  width_units = "meters"
)
render_camera(theta=-33,phi=40,zoom=0.4)
# RGL render uses lines for speed
render_snapshot()
# High quality render uses mesh trail
render_highquality(samples=16)
# RGL preview can be set to use (potentially slower) mesh preview
render_trails(
  volcano_trails,
  color = "grey50",
  width = 3,
  width_units = "meters",
  preview="mesh",
  clear_previous = TRUE
)
render_snapshot()

Render Tree

Description

Adds a 3D representation of trees to an existing 3D scene generated with rayshader. Users can specify the trees' positions using x/y coordinates or the same coordinate reference system as extent. Different types of tree models can be used, including a basic and a cone-shaped tree. Users can also use their own custom tree model in OBJ format. The function allows customization of various aspects of the tree, including the color of the crown and the trunk, the size of the crown (the leafy part of the tree) and the trunk, the overall scale of the tree, and the rotation angle around the x, y, and z axes. Users can also specify the minimum and maximum height of the trees to be rendered.

Cache fallback messages are disabled by default. Set options(rayshader.verbose_scene_cache = TRUE) to print when cached metadata is reused.

Usage

render_tree(
  location = NULL,
  type = "basic",
  custom_obj_tree = NULL,
  custom_obj_crown = NULL,
  custom_obj_trunk = NULL,
  crown_color = "#22aa22",
  trunk_color = "#964B00",
  absolute_height = FALSE,
  tree_height = NULL,
  tree_height_column = NULL,
  trunk_height_ratio = NULL,
  crown_width_ratio = NULL,
  crown_width = NULL,
  trunk_radius = NULL,
  tree_zscale = TRUE,
  min_height = 0,
  max_height = Inf,
  lit = TRUE,
  preview_simple = FALSE,
  preview_point_size = 1,
  angle = c(0, 0, 0),
  clear_previous = FALSE,
  x = NULL,
  y = NULL,
  lat = NULL,
  long = NULL,
  crs = NULL,
  filter_to_extent = TRUE,
  extent = NULL,
  panel = NULL,
  zscale = 1,
  vertical_exaggeration = 1,
  heightmap = NULL,
  load_normals = FALSE,
  ...
)

Arguments

location

Default NULL. Spatial point input used to place the rendered tree(s) in the scene. Accepts sf, sfc, sfg, or sp POINT or MULTIPOINT geometries. MULTIPOINT inputs are flattened to point placements internally, and vectorized arguments such as tree_height, angle, crown_color, and trunk_color are applied against that flattened point count. If the input carries a CRS, it will be transformed automatically into the active scene CRS. If it has no CRS, supply crs.

type

Default "basic". Type of tree. Other built-in option: "cone".

custom_obj_tree

Default NULL. Instead of using the built-in types, users can also load a custom tree model in OBJ format. This function loads and manipulates the model, assuming the tree model's trunk begins at the origin. Color and specific trunk/crown proportions will be fixed to the model specified, although the overall scale can be changed per-tree via crown_height.

custom_obj_crown

Default NULL. Instead of using the built-in types, users can also load a custom crown model in OBJ format. This function loads a crown model and allows you to control the crown and trunk proportions separately.

custom_obj_trunk

Default NULL. Instead of using the built-in types, users can also load a custom trunk model in OBJ format. This function loads a trunk model and allows you to control the crown and trunk proportions separately.

crown_color

Default "darkgreen". Color(s) of the crown. Use "height" to color crowns by the cached plot_gg() height aesthetic palette using tree_height.

trunk_color

Default "#964B00" (brown). Color(s) of the trunk. Use "height" to color trunks by the cached plot_gg() height aesthetic palette using tree_height.

absolute_height

Default FALSE. Default is specifying the tree height directly, relative to the underlying height map. If TRUE, crown_height will specified by the actual altitude of the top of the tree. Total tree height will be crown_height + trunk_height.

tree_height

Default NULL. Height of the tree, automatically set to 10 if not specified. If absolute_height = TRUE, then this is interpreted as the altitude of the top of the tree in the coordinate reference system used. If absolute_height = FALSE, then this is interpreted as the height of the tree relative to the underlying heightmap. Trees with negative sizes are discarded; absolute elevations are first converted to sizes above the terrain.

tree_height_column

Default NULL. Column name in location to use for tree_height. Requires location to be an sf/spatial point object with attribute data. Cannot be combined with an explicit tree_height.

trunk_height_ratio

Default NULL. The ratio of the height of the trunk to the total height of the tree. Default is 1/3rd the crown height if type = "basic", and 1/6th the crown height if type = "cone".

crown_width_ratio

Default NULL. Ratio of the crown width to the crown height. A value of 1 is spherical.

crown_width

Default NULL. As an alternative to specifying the ratio, you can use this argument to specify the crown width directly.

trunk_radius

Default NULL, automatically computed. Default is 1/5rd the trunk height if type = "basic", and 1/10th the trunk height if type = "cone".

tree_zscale

Default TRUE. Whether to scale the size of the tree by zscale to have it match the size of the map. If zscale is very big, this will make the trees very small.

min_height

Default NULL. Minimum height of a tree. Set to a positive number to filter out trees below that height.

max_height

Default NA. Maximum height of a tree. Set to a positive number to filter out trees above that height.

lit

Default TRUE. Whether to apply lighting to the tree.

preview_simple

Default FALSE. Set to TRUE or "point" to show one green rgl point at each canopy while caching the full tree transforms for render_highquality(). Set to "none" to cache the trees without adding anything to the rgl preview.

preview_point_size

Default 1. Size of the green rgl canopy points when preview_simple = TRUE or "point".

angle

Default c(0,0,0). Angle of rotation around the x, y, and z axes. If this is a matrix or list, each row (or list entry) specifies the rotation of the nth tree specified (number of rows/length of list must equal the length of x/y).

clear_previous

Default FALSE. If TRUE, clears all existing trees. A clear-only call returns without rendering a replacement.

x

Vector of x coordinates (or other coordinate in the same coordinate reference system as extent).

y

Vector of y coordinates (or other coordinate in the same coordinate reference system as extent).

lat

Default NULL. Alias for y for geographic workflows.

long

Default NULL. Alias for x for geographic workflows.

crs

Default NULL. CRS of the input numeric x/y coordinates, or CRS to assign to CRS-less spatial data before transforming it into the active scene CRS. If spatial data already carries a CRS, that CRS is used automatically.

filter_to_extent

Default TRUE. If TRUE, tree placements outside the scene extent are omitted. For scenes created with plot_gg(), filtering uses the ggplot panel extent rather than the full rendered 3D ggplot extent.

extent

Either an object representing the spatial extent of the 3D scene (either from the raster, terra, sf, or sp packages), a length-4 numeric vector specifying c("xmin", "xmax", "ymin", "ymax"), or the spatial object (from the previously aforementioned packages) which will be automatically converted to an extent object. If omitted, rayshader will use extent metadata cached by plot_3d() or plot_gg().

panel

Default NULL. Facet panel identifier for scenes created with plot_gg(). Required to disambiguate faceted ggplot scenes when panel-specific cached metadata is needed. Ignored for non-ggplot scenes.

zscale

Default 1. The ratio between the x and y spacing (which are assumed to be equal) and the z axis in the original heightmap.

vertical_exaggeration

Default 1. Multiplier applied to the effective visual relief. If omitted, rayshader uses the cached scene value from plot_3d() or plot_gg() when available; pass explicitly to override for this call.

heightmap

Default NULL. Height matrix used to determine terrain elevations and existing NA cells. If omitted, this is taken from the cached scene set by plot_3d() or plot_gg(). Pass explicitly to override the cached value.

load_normals

Default FALSE. Whether to load the model's vertex normals for smooth shading. Applies to both full previews and cached tree instances.

...

Additional arguments to pass to rgl::triangles3d().

Examples

#Let's first start by drawing some trees in a circle around Monterey Bay
#We won't scale these to a realistic size (yet)
moss_landing_coord = c(36.806807, -121.793332)
montereybay_spatial |>
 sphere_shade(vertical_exaggeration = 20) |>
 plot_3d(vertical_exaggeration = 4,water=TRUE,
         shadow_color="#40310a", background = "tan",
         theta=210,  phi=22, zoom=0.20, fov=55)

t = seq(0,2*pi,length.out=20)
circle_coords_lat = moss_landing_coord[1] + 0.3 * sin(t)
circle_coords_long = moss_landing_coord[2] + 0.3 * cos(t)

render_tree(tree_zscale = FALSE, tree_height = 30,  lit = TRUE,
           lat = unlist(circle_coords_lat), long = unlist(circle_coords_long))
render_snapshot()
#Change the crown width ratio (compared to the height)
render_tree(tree_zscale = FALSE, tree_height = 60, crown_width_ratio = 0.5,
           clear_previous = TRUE,
           lat = unlist(circle_coords_lat), long = unlist(circle_coords_long))
render_snapshot()
#Change the trunk height and width
render_tree(tree_zscale = FALSE, tree_height = 40, crown_width_ratio = 2,
           clear_previous = TRUE, trunk_height_ratio=1/2, trunk_radius = 1.5,
           lat = unlist(circle_coords_lat), long = unlist(circle_coords_long))
render_snapshot()
#Change the tree type
render_tree(tree_zscale = FALSE, tree_height = 30,
           clear_previous = TRUE, type = "cone",trunk_height_ratio = 1/6,
           lat = unlist(circle_coords_lat), long = unlist(circle_coords_long))
render_snapshot()
#Change the crown color:
render_camera(theta = 150,  phi = 38, zoom = 0.4, fov = 55)
render_tree(tree_zscale = FALSE, tree_height = 30, crown_width_ratio = 0.5 + runif(20),
           crown_color = rainbow(20),  clear_previous = TRUE,
           lat = unlist(circle_coords_lat), long = unlist(circle_coords_long))
render_snapshot()

#We will use the lidR package to generate a DEM and detect the crown tops of trees, and
#then use rayshader to render 3D tree models scaled to those heights on the map.


#Load the example data from the lidR package
LASfile = system.file("extdata", "Topography.laz", package="lidR")
las = lidR::readLAS(LASfile, filter = "-inside 273450 5274350 273550 5274450")

#Convert the lidar point data to a DEM and detect the location of trees from the same data
dem = lidR::rasterize_terrain(las, algorithm = lidR::tin())
tree_top_data = lidR::locate_trees(las, lidR::lmf(ws = 5))
tree_locations = sf::st_coordinates(tree_top_data)

#Plot the ground
dem |>
 height_shade() |>
 add_shadow(texture_shade(),0) |>
 add_shadow(lamb_shade(),0) |>
 plot_3d(window_size = 800, shadow_depth=min(raster_to_matrix(dem),na.rm=TRUE))
render_snapshot()
#The tree locations are given as an absolute height (as opposed to relative to the surface)
#so we set `absolute_height = TRUE`.
render_tree(y = tree_locations[,2],
           x = tree_locations[,1],
           crown_width_ratio = 0.5,
           absolute_height = TRUE,
           tree_height = tree_locations[,3],
           trunk_height_ratio = 0.2 + 0.1*runif(nrow(tree_locations)),
           crown_color = "#007700",
           clear_previous = TRUE)
render_camera(zoom=0.85)
#Remove existing lights and add our own with rgl
invisible(rgl::pop3d("lights"))
invisible(rgl::light3d(phi=35,theta=90, viewpoint.rel=F, diffuse="#ffffff", specular="#000000"))
invisible(rgl::light3d(phi=-45,theta=-40, viewpoint.rel=F, diffuse="#aaaaaa", specular="#000000"))
render_snapshot()
#Render tree also works with `render_highquality()`
render_highquality(sky_sun_elevation = 30, sky_sun_azimuth=225, iso=3)

Render Water Layer

Description

Adds water layer to the scene, removing the previous water layer if desired.

Cache fallback messages are disabled by default. Set options(rayshader.verbose_scene_cache = TRUE) to print when cached metadata is reused.

Usage

render_water(
  water_input = 0,
  water_color = "lightblue",
  water_alpha = 0.5,
  water_line_color = NULL,
  water_line_alpha = 1,
  linewidth = 2,
  water_render_method = c("polygon", "raster", "optimized", "legacy"),
  water_edge_extension = 0.5,
  water_edge_clamp = FALSE,
  water_polygon_failure = c("raster", "remove"),
  clear_previous = TRUE,
  zscale = 1,
  vertical_exaggeration = 1,
  heightmap = NULL,
  water_elevation = NULL,
  water_surface_tolerance = NULL,
  parallel = TRUE,
  ...
)

Arguments

water_input

Default 0. Water level or footprint. Either a scalar, a matrix with the same dimensions as heightmap, a spatial raster that can be projected/resampled to the heightmap grid, or an sf/sfc object containing POLYGON or MULTIPOLYGON geometries. Non-polygon features are ignored; polygon parts within GEOMETRYCOLLECTION features are retained. If no nonempty polygons remain, no water is drawn. For spatial rasters, finite cells define the water footprint. Polygon inputs require known source and heightmap CRSs and a heightmap extent. Method "polygon" retains exact boundaries and holes. Methods "raster" and "optimized" convert polygons to the heightmap grid; features smaller than a cell use touched cells when they contain no cell centers. Polygon input requires sf and terra.

water_color

Default lightblue.

water_alpha

Default 0.5. Water transparency.

water_line_color

Default NULL. Color of the lines around the edges of the water layer.

water_line_alpha

Default 1. Water line tranparency.

linewidth

Default 2. Width of the edge lines in the scene.

water_render_method

Default "polygon". Water meshing method. "raster" renders water at the supplied elevation and emits sidewalls down to the terrain wherever exposed water floats above the surface; "polygon" preserves polygon footprints and holes, extruding from the lowest terrain beneath each part to a flat water level; "optimized" fits each spatial water component by matching flooded terrain-triangle area to raster footprint area, then clips the fixed-grid terrain triangles; "legacy" uses the previous box/grid renderer. With simplified (triangulate = TRUE) terrain, raster caps retain the supplied footprint and the rendered terrain hides buried portions, avoiding holes from clipping against a different terrain triangulation.

water_edge_extension

Default 0.5. For spatial water_input inputs, amount in grid cells to expand finite water cells at boundary edges, up to a maximum of half a cell.

water_edge_clamp

Default FALSE. For spatial water_input inputs, if TRUE, resolves each connected water footprint to a single level, then lowers it by the largest finite exterior sidewall height after edge expansion. Heightmap-boundary and NA-slice edges are ignored when computing the lowering amount.

water_polygon_failure

Default "raster". Behavior for "optimized" water components that cannot be fit to an admissible terrain-triangle flood. "raster" renders the failed component with the raster method; "remove" omits it.

clear_previous

Default TRUE. If TRUE, removes the existing water layer before drawing the new one. A clear-only call returns without rendering a replacement.

zscale

Default 1. The ratio between the x and y spacing (which are assumed to be equal) and the z axis. For example, if the elevation levels are in units of 1 meter and the grid values are separated by 10 meters, zscale would be 10. If zscale is omitted and heightmap is a spatial raster, rayshader uses the raster cell resolution.

vertical_exaggeration

Default 1. Multiplier applied to the effective visual relief. If omitted, rayshader uses the cached scene value from plot_3d() or plot_gg() when available; pass explicitly to override for this call.

heightmap

Default NULL. Height matrix or spatial raster for the current scene. If omitted, this is taken from the cached scene set by plot_3d() or plot_gg(). Pass explicitly to override the cached value.

water_elevation

Default NULL. For polygon water_input only: a finite numeric elevation, one elevation per original feature, or the name of a numeric column in an sf object. Values use the heightmap's elevation units, before zscale and vertical_exaggeration. If NULL, each polygon part uses the median finite terrain elevation sampled along its exterior ring, falling back to its interior cells when no finite shoreline samples are available. Inferred levels receive a small positive lift to avoid coplanar water on flat terrain. The lift is at least max(1e-4, abs(level) * 1e-6) in elevation units and accounts for scene size and zscale so it survives rendering precision. Explicit levels are not lifted by "raster" or "optimized". Exact polygon water checks the actual rendered terrain, infers the shoreline median if needed, and lifts even explicit levels when nearly coincident with a terrain patch. This default is a visualization estimate, not a measured water-surface level. Overlapping raster cells use the highest component level. With method "optimized", the existing area-fit algorithm may replace these levels; they are the supplied levels for raster rendering and polygon-to-raster fallback. water_edge_clamp = TRUE may also lower the supplied levels. Use method "raster" with clamping disabled to retain explicit elevations. With polygon inputs, method "legacy" warns and uses "raster" instead.

water_surface_tolerance

Default NULL. For "polygon", maximum difference in terrain elevation units for treating a nearly horizontal terrain patch as coincident with the water top. NULL uses a tolerance scaled to single-precision scene coordinates. Coincident tops are raised just above the highest matching patch by a scene-scale clearance. 0 tests exact coincidence. The extrusion bottom is the lowest rendered terrain point within each polygon. Polygon footprints are clipped only to valid terrain coverage; buried water is hidden by terrain. Grid edge expansion, clamping, and fitting-failure settings do not alter exact polygon water.

parallel

Default TRUE. Build large exact-polygon water batches in native threads. Uses options(cores = ...), or physical core count when unset. Small batches run sequentially; FALSE always uses one thread. Threads share the terrain snapshot; each has its own geometry scratch space.

...

Deprecated argument spellings are accepted with a warning and forwarded to their current names.

Examples

montereybay_spatial |>
 sphere_shade(vertical_exaggeration = 20) |>
 plot_3d(vertical_exaggeration = 4)
render_snapshot()

#We want to add a layer of water after the initial render.
render_water()
render_snapshot()

#Call it again to change the water depth
render_water(water_input=-1000, water_color = "dodgerblue3")
render_snapshot()

#Slice the water out to the edge
water_levels = matrix(
 0,
 nrow = nrow(montereybay_spatial),
 ncol = ncol(montereybay_spatial)
)
water_levels[col(water_levels) > ncol(water_levels) / 2 + 20 |
col(water_levels) < ncol(water_levels) / 2-20] = -8000
render_water(water_input = water_levels, water_color = "dodgerblue4")
render_snapshot()

#Use a matrix to vary the water level across the scene
water_ramp = matrix(
 seq(-1200, -300, length.out = length(montereybay_spatial)),
 nrow = nrow(montereybay_spatial),
 ncol = ncol(montereybay_spatial)
)
render_water(water_input = water_ramp, water_color = "dodgerblue3")
render_highquality()

#Add waterlines
render_camera(theta=-45)
render_water(water_line_color="white", water_color = "dodgerblue4")
render_snapshot()

Render Z-Axis

Description

Add a standalone z-axis to the active 3D scene.

Cache fallback messages are disabled by default. Set options(rayshader.verbose_scene_cache = TRUE) to print when cached metadata is reused.

Usage

render_zaxis(
  data = "auto",
  location = "auto",
  breaks = NULL,
  labels = NULL,
  title = "auto",
  title_location = "side",
  title_offset = 1.25,
  title_size = NULL,
  color = "black",
  linewidth = 2,
  text_offset = 0,
  label_size = 0.8,
  label_side = "auto",
  title_side = "auto",
  corner_offset = NULL,
  tick_size = NULL,
  extent = NULL,
  panel = NULL,
  zscale = 1,
  vertical_exaggeration = 1,
  heightmap = NULL
)

Arguments

data

Default "auto". Data source used to generate z-axis breaks and labels. Options are "auto", "topographic", "polygon", "point", "path", "obj", "raymesh", "tree", "label", "building", and "cloud". Use "polygon" after render_polygons() or render_beveled_polygons() to label breaks with cached polygon data values (for example data_column_top) while placing ticks at the rendered scaled heights. Use "building" after render_buildings() to refer to building height data, or the matching render type after point/path/object/tree/label and cloud calls to use those cached altitude values.

location

Default "auto". Axis location. Options: "auto", "panel", "panelbottomleft", "panelbottomright", "paneltopleft", "paneltopright", "bottomleft", "bottomright", "topleft", "topright".

breaks

Default NULL. Numeric breaks (in altitude units). If NULL, breaks are generated from the full scene height range (minimum to maximum elevation).

labels

Default NULL. Labels for breaks.

title

Default "auto". Title for the z-axis. If "auto", rayshader uses the cached height aesthetic label from plot_gg() scenes when available. Set to NULL to omit the title, or pass a character string to override it.

title_location

Default "side". Title location. Options are "side" and "top". "side" places the title horizontally opposite the tick-label side by default and centered on the axis.

title_offset

Default 1.25. Title offset multiplier in tick lengths. For title_location = "side", this moves the title away from the axis on the chosen title side, but never closer than one tick length beyond the tick label offset. For "top", this moves the title above the top of the axis using tick-length-scaled spacing.

title_size

Default NULL. Matches label_size when omitted. Title text size passed to rgl::texts3d() as cex.

color

Default "black". Axis/tick/label color.

linewidth

Default 2. Axis line width.

text_offset

Default 0. Label offset multiplier from the axis, applied in the outward corner direction (diagonal for corner placements).

label_size

Default 0.8. Tick label text size passed to rgl::texts3d() as cex.

label_side

Default "auto". Side of the axis where tick labels are placed from the current camera perspective. Options are "auto", "left", and "right". "auto" keeps the inferred outside-corner side.

title_side

Default "auto". Side of the axis where the title is placed from the current camera perspective. Options are "auto", "left", and "right". "auto" places side titles opposite the tick-label side and top titles on the tick-label side.

corner_offset

Default NULL. Corner offset as a proportion of the center-to-corner planar distance. If NULL, this defaults to 0 for ggplot scenes and 0.08 for non-ggplot scenes. 0 places the axis exactly at the corner.

tick_size

Default NULL. Tick marker size. If NULL, auto-sized from line width.

extent

Default NULL. Either an object representing the spatial extent of the scene (either from the raster, terra, sf, or sp packages), a length-4 numeric vector specifying c("xmin", "xmax","ymin","ymax"), or the spatial object (from the previously aforementioned packages) which will be automatically converted to an extent object. If omitted, rayshader will use cached extent metadata from plot_gg() or from plot_3d() (either from an explicitly passed extent argument, or the built-in montereybay_spatial scene metadata).

panel

Default NULL. Facet panel identifier for scenes created with plot_gg(). Required to disambiguate faceted ggplot scenes when panel-specific cached metadata is needed. Ignored for non-ggplot scenes.

zscale

Default 1. The ratio between x/y spacing and z units. If left at 1 with breaks = NULL on non-ggplot terrain scenes, rayshader will attempt to use the cached plot_3d() zscale to generate more meaningful defaults.

vertical_exaggeration

Default 1. Multiplier applied to the effective visual relief. If omitted, rayshader uses the cached scene value from plot_3d() or plot_gg() when available; pass explicitly to override for this call.

heightmap

Default NULL. Height matrix for the current scene. If omitted, this is taken from the cached scene set by plot_3d() or plot_gg(). Pass explicitly to override the cached value.

Examples

# Add a z-axis to a Monterey Bay terrain scene. The spatial extent and zscale
# are cached by sphere_shade()/plot_3d(), so render_zaxis() can infer them.
montereybay_spatial |>
 sphere_shade(texture = "imhof1", vertical_exaggeration = 20) |>
 plot_3d(
   vertical_exaggeration = 4,
   water = TRUE,
   theta = 245,
   phi = 20,
   zoom = 1
 )
render_zaxis(
 location = "bottomleft",
 color = "black",
 corner_offset = 0.2
)
render_snapshot()

#Change the location
render_zaxis(
 location = "topright",
 title = "Elevation (m)",
 title_location = "top",
 color = "red",
 corner_offset = 0.3,
 tick_size = 3
)
render_snapshot()
# Add a z-axis to a ggplot scene.
library(ggplot2)
mtplot = ggplot(mtcars) +
 geom_point(aes(x = mpg, y = disp, color = cyl)) +
 scale_color_continuous(limits = c(0, 8))
plot_gg(
 mtplot,
 width = 3.5,
 window_size = c(1400, 866),
 sun_angle = 225,
 zoom = 0.50,
 phi = 20,
 theta = 45
)
render_zaxis(location = "panel_bottomleft", color = "red",
            label_size = 1.5)
render_snapshot()

# For faceted ggplot scenes, specify the panel whose corner should anchor the axis.
density_plot = ggplot(mtcars) +
 stat_density_2d(
   aes(x = mpg, y = disp, fill = after_stat(density)),
   geom = "raster",
   contour = FALSE
 ) +
 facet_wrap(~cyl) +
 scale_x_continuous(expand = c(0, 0)) +
 scale_y_continuous(expand = c(0, 0)) +
 scale_fill_gradient(low = "pink", high = "red")
plot_gg(
 density_plot,
 width = 6,
 window_size = c(1400, 866),
 zoom = 0.55,
 theta = 45,
 phi = 25,
 vertical_exaggeration = 300
)
render_zaxis(
 panel = 1,
 location = "panel_bottomleft"
)
render_snapshot()
#Move to the second panel, top left
render_camera(theta=-20, phi=20)
render_zaxis(
 panel = 2,
 location = "panel_topleft"
)
render_snapshot()
#Move to corner of the plot
render_camera(theta=-20, phi=20,zoom=0.6)
render_zaxis(
 location = "topleft"
)
render_snapshot()

Resize Matrix

Description

Resizes a matrix (preserving contents) by specifying the desired output dimensions or a scaling factor.

Usage

resize_matrix(
  heightmap,
  scale = 1,
  width = NULL,
  height = NULL,
  method = "bilinear"
)

Arguments

heightmap

The elevation matrix.

scale

Default 0.5. The amount to scale down the matrix. Scales using bilinear interpolation.

width

Default NULL. Alternative to scale argument. The desired output width. If width is less than 1, it will be interpreted as a scaling factor– e.g. 0.5 would halve the resolution for the width.

height

Default NULL. Alternative to scale argument. The desired output width. If height is less than 1, it will be interpreted as a scaling factor– e.g. 0.5 would halve the resolution for the height.

method

Default bilinear. Method of interpolation. Alteratively cubic, which is slightly smoother, although current implementation slightly scales the image.

Examples

#Reduce the size of the monterey bay dataset by half

montereybay_matrix = raster_to_matrix(montereybay_spatial, verbose = FALSE)
montbaysmall = resize_matrix(montereybay_matrix, scale=0.5)
montbaysmall |>
 sphere_shade() |>
 plot_map()
#Reduce the size of the monterey bay dataset from 540x540 to 100x100
montbaysmall = resize_matrix(montereybay_matrix, width = 100, height = 100)
montbaysmall |>
 sphere_shade() |>
 plot_map()
#Increase the size of the volcano dataset 3x
volcanobig = resize_matrix(volcano, scale=3)
volcanobig |>
 sphere_shade() |>
 plot_map()
#Increase the size of the volcano dataset 2x, using cubic interpolation
volcanobig = resize_matrix(volcano, scale=3, method="cubic")
volcanobig |>
 sphere_shade() |>
 plot_map()

Resize a SpatRaster while preserving spatial metadata

Description

resize_spatial() mirrors the ergonomics of rayshader::resize_matrix(), but returns a terra::SpatRaster with extent and CRS intact.

Usage

resize_spatial(
  x,
  scale = 1,
  width = NULL,
  height = NULL,
  method_down = "mean",
  method_up = "bilinear",
  aggregate_if_possible = TRUE,
  tol = 1e-08,
  threads = FALSE,
  filename = "",
  overwrite = FALSE,
  write_args = list(),
  ...
)

Arguments

x

A terra::SpatRaster.

scale

Default 1. Relative output size used only when both width and height are NULL.

width

Default NULL. Target number of columns. When supplied alone, height is derived while preserving the current aspect ratio.

height

Default NULL. Target number of rows. When supplied alone, width is derived while preserving the current aspect ratio.

method_down

Default "mean". Method used when reducing resolution. Integer-factor reductions use terra::aggregate() when possible; other reductions use terra::resample(). The default becomes "modal" when any input layer is categorical.

method_up

Default "bilinear". Method passed to terra::resample() when increasing resolution. The default becomes "near" when any input layer is categorical.

aggregate_if_possible

Default TRUE. If TRUE, use terra::aggregate() for integer-factor downsampling when method_down is an aggregation method.

tol

Default 1e-8. Tolerance for deciding whether an implied aggregation factor is effectively an integer.

threads

Default FALSE. Passed to terra::resample().

filename

Default "". Optional output filename.

overwrite

Default FALSE. Whether to overwrite filename.

write_args

Default list(). Named arguments passed only to terra::writeRaster() when filename is supplied.

...

Arguments passed only to the resize operation that is used: terra::aggregate() for aggregation or terra::resample() for resampling.

Details

Downsampling and upsampling are handled separately because the best visual method is often different in each direction. Integer-factor reductions can use terra::aggregate(); everything else uses terra::resample() onto a template raster with the requested geometry.

Value

A terra::SpatRaster.


Save 3D Print

Description

Writes a stereolithography (STL) file that can be used in 3D printing.

Usage

save_3dprint(filename, max_width = 125, unit = "mm", rotate = FALSE, ...)

Arguments

filename

String with the filename. If .stl is not at the end of the string, it will be appended automatically.

max_width

Default 125. Desired maximum width of the 3D print in millimeters. Uses the units set in unit argument. Can also pass in a string, "125mm" or "5in".

unit

Default mm. Units of the max_width argument. Can also be set to inches with ⁠in⁠.

rotate

Default TRUE. If FALSE, the map will be printing on its side. This may improve resolution for some 3D printing types.

...

Deprecated argument spellings are accepted with a warning and forwarded to their current names.

Value

Writes an STL file to filename. Regardless of the unit displayed, the output STL is in millimeters.

Examples

filename_stl = tempfile()

#Save the STL file into `filename_stl`
volcano |>
 sphere_shade() |>
 plot_3d(vertical_exaggeration = 1/3)
render_snapshot()
save_3dprint(filename_stl)

#Save the STL file into `filename_stl`, setting maximum width to 100 mm
volcano |>
 sphere_shade() |>
 plot_3d(vertical_exaggeration = 1/3)
render_snapshot()
save_3dprint(filename_stl, max_width = 100)

#'#Save the STL file into `filename_stl`, setting maximum width to 4 inches
volcano |>
 sphere_shade() |>
 plot_3d(vertical_exaggeration = 1/3)
render_snapshot()
save_3dprint(filename_stl, max_width = 4, unit = "in")
#'#'#Save the STL file into `filename_stl`, setting maximum width (character) to 120mm
volcano |>
 sphere_shade() |>
 plot_3d(vertical_exaggeration = 1/3)
render_snapshot()
save_3dprint(filename_stl, max_width = "120mm")

Save MULTIPOLYGON Z sf data to OBJ file

Description

Converts MULTIPOLYGON Z features into a triangulated 3D OBJ model, preserving concave boundaries and holes in each face.

Usage

save_multipolygonz_to_obj(sf_obj, filename, swap_yz = FALSE, ...)

Arguments

sf_obj

sf object with MULTIPOLYGON Z geometry,

filename

Filename of the OBJ to save the 3D model to.

swap_yz

Default FALSE. Whether to swap the Y and Z axes. (Y axis is vertical in rayshader coordinates, but data is often provided with Z being vertical).

...

Deprecated argument spellings are accepted with a warning and forwarded to their current names.

Details

Faces with more than three vertices or holes require the decido package. Triangulation uses each face's dominant plane and preserves its original winding. Crossed or overlapping rings are repaired in the face plane; new intersection vertices are interpolated along the original 3D edges. By default, options(rayshader.multipolygonz_repair = TRUE) also repairs ambiguous projected intersections: existing XYZ vertices are retained and new vertices use the nearest projected source edge (the first edge breaks ties). This depth choice is a heuristic for nonplanar faces. Set options(rayshader.multipolygonz_repair = FALSE) to drop these ambiguous faces instead. Unambiguous planar repairs are performed in either mode. Zero-area faces and faces that still cannot be triangulated are skipped with a summary warning in either mode. If no faces remain, an empty OBJ is written. Touching-hole cases may require an sf/GEOS version supporting constrained triangulation. OBJ coordinates are written to four decimal places.

Examples

#Convert the built-in Washington Monument MULTIPOLYGON Z data to an OBJ file
obj_temp = tempfile(fileext=".obj")
save_multipolygonz_to_obj(washington_monument_multipolygonz, obj_temp, swap_yz=TRUE)
#Render with rgl
rgl::open3d()
render_obj(filename=obj_temp, xyz=matrix(c(0,0,0),ncol=3), color="red")
render_camera(theta=30,phi=40)

Save OBJ

Description

Writes the textured 3D rayshader visualization to an OBJ file.

Usage

save_obj(
  filename,
  save_texture = TRUE,
  water_index_refraction = 1,
  manifold_geometry = FALSE,
  all_face_fields = FALSE,
  save_shadow = FALSE
)

Arguments

filename

String with the filename. If .obj is not at the end of the string, it will be appended automatically.

save_texture

Default TRUE. If the texture should be saved along with the geometry.

water_index_refraction

Default 1. The index of refraction for the rendered water.

manifold_geometry

Default FALSE. If TRUE, this will take the additional step of making the mesh manifold.

all_face_fields

Default FALSE. If TRUE, all OBJ face fields (v/vn/vt) will always be written.

save_shadow

Default FALSE. If TRUE, this saves a plane with the shadow texture below the model.

Examples

filename_obj = tempfile(fileext = ".obj")

#Save model of volcano
volcano |>
 sphere_shade() |>
 plot_3d(vertical_exaggeration = 1/2)

save_obj(filename_obj)

#Save model of volcano without texture
save_obj(filename_obj, save_texture = FALSE)

#Make water have realistic index of refraction
montereybay_spatial |>
 sphere_shade() |>
 plot_3d(vertical_exaggeration = 4)

save_obj(filename_obj, water_index_refraction = 1.5)

Save PNG

Description

A wrapper around rayimage::ray_write_image() to write an image to file.

Usage

save_png(
  hillshade,
  filename,
  title_text = NA,
  title_offset = c(20, 20),
  title_color = "black",
  title_size = 30,
  title_font = "sans",
  title_style = "normal",
  title_bar_color = NA,
  title_bar_alpha = 0.5,
  title_just = "left"
)

Arguments

hillshade

Array (or matrix) of hillshade to be written.

filename

String with the filename. If .png is not at the end of the string, it will be appended automatically.

title_text

Default NULL. Text. Adds a title to the image, using magick::image_annotate().

title_offset

Default c(20,20). Distance from the top-left (default, gravity direction in image_annotate) corner to offset the title.

title_color

Default black. Font color.

title_size

Default 30. Font size in pixels.

title_font

Default sans. String with font family such as "sans", "mono", "serif", "Times", "Helvetica", "Trebuchet", "Georgia", "Palatino" or "Comic Sans".

title_style

Default normal. Font style (e.g. italic).

title_bar_color

Default NA. If a color, this will create a colored bar under the title.

title_bar_alpha

Default 0.5. Transparency of the title bar.

title_just

Default left. Position of the title.

Examples

filename_map = tempfile()

#Save the map into `filename_map`
montereybay_spatial |>
 sphere_shade() |>
 save_png(filename_map)

Shift a Heightmap Surface

Description

Shifts a heightmap under spatial geometries by a constant or per-feature amount. This is useful when terrain needs to be lowered below water or raised beneath structures.

Positive amount values raise the surface and negative values lower it.

Usage

shift_terrain(
  heightmap,
  geometry,
  amount = 1,
  transition = 0,
  transition_units = c("map", "cells"),
  extent = NULL,
  crs = NULL,
  touches = TRUE,
  fun = "max"
)

Arguments

heightmap

Height matrix or spatial raster DEM. Matrix inputs require extent or cached or attribute extent metadata. Spatial raster inputs return a spatial raster; matrix inputs return a matrix.

geometry

Spatial geometry used to select the affected cells. Supports sf, sfc, sfg, terra::SpatVector, and sp vector objects.

amount

Default 1. Constant amount to apply, numeric vector with one value per feature, or a single character string naming a numeric column in geometry. Positive values raise terrain, negative values lower terrain, and NA values skip their features.

transition

Default 0. Distance over which amount transitions from the polygon edge to the full shift. 0 applies the full amount abruptly to all selected cells.

transition_units

Default c("map", "cells"). Units for transition. "map" uses meters for longitude and latitude rasters, the CRS linear units for projected rasters, and coordinate units for CRS-less rasters. "cells" measures distance in unit-width and unit-height raster cells, independent of CRS and spatial resolution.

extent

Default NULL. Spatial extent for matrix heightmap inputs. Ignored for spatial raster inputs.

crs

Default NULL. CRS describing the input heightmap. For spatial raster inputs, an explicit value overrides embedded metadata on a copy of the raster before geometry is transformed into that CRS.

touches

Default TRUE. Passed to terra::rasterize(). If TRUE, cells touched by polygons or lines are modified.

fun

Default "max". Rasterization reducer passed to terra::rasterize() for cells intersected by multiple features.

Details

In map mode, transition distance is measured by terra::distance(). The center-to-boundary inset is one-half of the smaller raster resolution. In cell mode, distance is calculated on a temporary unit-resolution raster and uses a half-cell inset of 0.5. A polygon that fills the raster has no internal polygon edge, so the raster boundary does not reduce its shift.

Value

A shifted height matrix or terra::SpatRaster. Legacy ⁠Raster*⁠ inputs are returned as terra::SpatRaster objects.

Examples

water_poly = sf::st_sfc(
  sf::st_polygon(list(rbind(
    c(0.2, 0.2), c(0.8, 0.2), c(0.8, 0.8), c(0.2, 0.8), c(0.2, 0.2)
  ))),
  crs = 4326
)
lowered = shift_terrain(
  matrix(10, 10, 10),
  water_poly,
  amount = -2,
  extent = c(0, 1, 0, 1)
)

Spatialize a Rayshader Image

Description

spatialize_image() converts a rayshader image into a georeferenced terra::SpatRaster. If they are omitted, rayshader reuses cached extent and CRS metadata from the active scene, following the same cache-resolution rules used by the ⁠render_*()⁠ helpers. Cached metadata can come from plot_3d() or plot_gg(), and panel can be used to select a specific facet panel for faceted ggplot scenes. Explicit extent and crs arguments always take precedence.

Usage

spatialize_image(
  image,
  extent = NULL,
  crs = NULL,
  panel = NULL,
  include_alpha = FALSE,
  to_rgb = TRUE,
  flip_vertical = FALSE,
  flip_horizontal = FALSE,
  layer_names = NULL,
  include_height = FALSE,
  heightmap = NULL,
  height_layer_name = "height",
  ...
)

Arguments

image

A matrix, RGB/RGBA array, or any input accepted by rayimage::ray_read_image().

extent

Default NULL. Spatial extent metadata for the output raster. Explicit extent overrides cached metadata. Accepts the same extent-like inputs supported by get_extent(), including numeric c(xmin, xmax, ymin, ymax) vectors, terra::SpatExtent, terra::SpatRaster, raster::Extent, ⁠Raster*⁠, sf/sfc, and sp objects. If omitted, rayshader reuses cached scene extent metadata.

crs

Default NULL. CRS for the output raster. Explicit crs overrides everything else. If omitted, rayshader first tries to inherit CRS from the explicit extent object, then from cached scene metadata.

panel

Default NULL. Facet panel identifier for scenes created with plot_gg(). Required to disambiguate faceted ggplot scenes when panel- specific cached metadata is needed. Ignored for non-faceted/non-ggplot scenes.

include_alpha

Default FALSE. If FALSE and image has four channels, drop alpha. If TRUE, include alpha as a fourth raster layer.

to_rgb

Default TRUE. If TRUE, convert color channels from linear rayshader values to sRGB with rayimage::render_gamma_linear(), then scale to the 0-255 range and clamp. Alpha is not gamma-adjusted, but is scaled and clamped to match.

flip_vertical

Default FALSE. If TRUE, reverse the image row order before rasterization.

flip_horizontal

Default FALSE. If TRUE, reverse the image column order before rasterization.

layer_names

Default NULL. Optional output layer names. Defaults are "value" for a single layer, c("red", "green", "blue") for RGB output, and c("red", "green", "blue", "alpha") for RGBA output.

include_height

Default FALSE. If TRUE, append a final layer with raw height values from heightmap or cached rayshader scene metadata. When the output image resolution differs from the source heightmap, heights are bilinearly resampled onto the output raster grid.

heightmap

Default NULL. Optional source elevation matrix or spatial raster used when include_height = TRUE. Explicit heightmap overrides cached heightmap metadata. If omitted, rayshader reuses cached hillshade or scene heightmap metadata when available. Faceted cached plot_gg() scenes require an explicit heightmap for height export.

height_layer_name

Default "height". Name of the appended height layer when include_height = TRUE.

...

Deprecated argument spellings are accepted with a warning and forwarded to their current names.

Details

If no explicit extent is supplied and no cached extent metadata is available, spatialize_image() errors. CRS is resolved in this order: explicit crs, CRS carried by the explicit extent object, cached scene CRS, then empty CRS if none is available.

Cache fallback messages are disabled by default. Set options(rayshader.verbose_scene_cache = TRUE) to print when cached metadata is reused.

Value

A terra::SpatRaster.

Examples

hillshade_img = montereybay_spatial |>
  sphere_shade() |>
  add_shadow(ray_shade(), 0.5)

hillshade_rast = spatialize_image(
  hillshade_img,
  extent = raster::extent(c(0, 1, 0, 1)),
  crs = "EPSG:4326"
)

Calculate Surface Color Map

Description

Calculates a color for each point on the surface using the surface normals and hemispherical UV mapping. This uses either a texture map provided by the user (as an RGB array), or a built-in color texture.

Cache fallback messages are disabled by default. Set options(rayshader.verbose_scene_cache = TRUE) to print when cached metadata is reused.

Usage

sphere_shade(
  heightmap,
  sun_angle = 315,
  texture = "imhof1",
  normal_vectors = NULL,
  color_intensity = 1,
  zscale = 1,
  vertical_exaggeration = 1,
  na_color = NULL,
  progress_bar = interactive(),
  geographic_aspect = TRUE,
  extent = NULL,
  crs = NULL,
  ...
)

Arguments

heightmap

A two-dimensional matrix, where each entry in the matrix is the elevation at that point. All points are assumed to be evenly spaced.

sun_angle

Default 315 (NW). The direction of the main highlight color (derived from the built-in palettes or the create_texture() function).

texture

Default imhof1. Either a square matrix indicating the spherical texture mapping, or a string indicating one of the built-in palettes (imhof1,imhof2,imhof3,imhof4,desert, bw, and unicorn).

normal_vectors

Default NULL. Cache of the normal vectors (from calculate_normal() function). Supply this to speed up texture mapping.

color_intensity

Deprecated alias for vertical_exaggeration.

zscale

Default 1. The ratio between the x and y spacing (which are assumed to be equal) and the z axis. If omitted and heightmap is a spatial raster, rayshader automatically uses the raster cell resolution. Geographic longitude/latitude rasters are converted to an approximate meter-per-cell value at the raster center. If supplied, this also updates the cached hillshade zscale for downstream rayshader calls.

vertical_exaggeration

Default 1. One-off multiplier applied to the effective visual relief for this call. Values greater than 1 increase apparent relief and values between 0 and 1 flatten it. This does not update cached zscale metadata.

na_color

Default NULL. RGB color stored in the returned image for transparent NA heightmap cells. If NULL, the texture's center/up color is used. This does not affect transparency; NA heightmap cells are always returned with alpha 0.

progress_bar

Default TRUE if interactive, FALSE otherwise. If FALSE, turns off progress bar.

geographic_aspect

Default TRUE. Correct unequal metric x/y cell spacing using the input extent and CRS.

extent

Default NULL. Spatial extent for a matrix heightmap.

crs

Default NULL. CRS to assign to the input before calculating metric cell spacing.

...

Deprecated argument spellings are accepted with a warning and forwarded to their current names.

Value

RGBA array of hillshaded texture mappings.

Examples

#Basic example:
montereybay_spatial |>
 sphere_shade() |>
 plot_map()

#Increase the color intensity:
montereybay_spatial |>
 sphere_shade(vertical_exaggeration=10) |>
 plot_map()

#Change to a built-in color texture:
montereybay_spatial |>
 sphere_shade(texture="desert", vertical_exaggeration=10) |>
 plot_map()

#Change the highlight angle:
montereybay_spatial |>
 sphere_shade(texture="desert", sun_angle = 45, vertical_exaggeration=10) |>
 plot_map()

#Create our own texture using the `create_texture` function:
montereybay_spatial |>
 sphere_shade(texture=create_texture("#E9C68D","#AF7F38",
                                     "#674F30","#494D30",
                                     "#B3BEA3"),
              vertical_exaggeration=10) |>
 plot_map()

Calculate Texture Shading Map

Description

Calculates a shadow for each point on the surface using the method described by Leland Brown in "Texture Shading: A New Technique for Depicting Terrain Relief."

Cache fallback messages are disabled by default. Set options(rayshader.verbose_scene_cache = TRUE) to print when cached metadata is reused.

Usage

texture_shade(
  heightmap,
  detail = 0.5,
  contrast = 1,
  brightness = 0,
  transform = TRUE,
  dx = 1,
  dy = 1,
  pad = 50,
  geographic_aspect = TRUE,
  extent = NULL,
  crs = NULL
)

Arguments

heightmap

A two-dimensional matrix, where each entry in the matrix is the elevation at that point.

detail

Default 0.5. Amount of detail in texture shading algorithm. 0 is the least detail, while 1 is the most.

contrast

Default 1,standard brightness. Amount of contrast in the texture shading. This transforms the resulting darkness using the formula tanh(input * contrast + brightness).

brightness

Default 0, standard brightness. Higher values will brighten the texture hillshade, while lower values will darken it.

transform

Default TRUE. Whether to apply the tanh(input * contrast + brightness) transformation. This transforms the resulting darkness using the formula tanh(input * contrast + brightness).

dx

Default 1. The distance between each row of data (compared to the height axis).

dy

Default 1. The distance between each column of data (compared to the height axis).

pad

Default 50. The amount to pad the heightmap so edge effects don't appear from the fourier transform. Only increase this if you encounter boundary effects.

geographic_aspect

Default TRUE. Correct unequal metric x/y cell spacing using the input extent and CRS. Explicit dx and dy values take precedence.

extent

Default NULL. Spatial extent for a matrix heightmap.

crs

Default NULL. CRS to assign to the input before calculating metric cell spacing.

Value

2D matrix of hillshade values.

Examples

#Create a direct mapping of elevation to color:

#Plut using default values
montereybay_spatial |>
  texture_shade() |>
  plot_map()
#Increase the level of detail
montereybay_spatial |>
  texture_shade(detail=1) |>
  plot_map()
#Decrease the level of detail
montereybay_spatial |>
  texture_shade(detail=0) |>
  plot_map()
#Increase the level of contrast
montereybay_spatial |>
  texture_shade(contrast=3) |>
  plot_map()
#Increase the brightness for this level of contrast
montereybay_spatial |>
  texture_shade(contrast=5, brightness = 2) |>
  plot_map()
#Add a texture_shade() layer into a map
montbay = raster_to_matrix(montereybay_spatial)
montbay[montbay < 0] = 0
montbay |>
  height_shade() |>
  add_water(detect_water(montbay), color="dodgerblue3") |>
  add_shadow(texture_shade(montereybay_spatial, detail=2/3, contrast = 5,
                          brightness = 2),0) |>
  add_shadow(lamb_shade(montereybay_spatial, vertical_exaggeration = 4),0) |>
  plot_map()

Georeferenced Maungawhau Volcano Elevation Raster

Description

Returns the base R datasets::volcano elevation model as a georeferenced, one-layer terra::SpatRaster. Elevation is measured in meters, and horizontal coordinates use EPSG:27200, NZGD49 / New Zealand Map Grid, on a 10-meter grid.

The elevation data were digitized from a topographic map and should not be treated as accurate survey data. A new independent copy of the raster is returned on every call.

Usage

volcano_spatial()

Value

A one-layer terra::SpatRaster containing elevation in meters.

Source

The base R datasets::volcano data and the Geomorphometry.org "Volcano Maungawhau" reconstruction.

See Also

raster_to_matrix()

Examples

volcano_dem = volcano_spatial()
terra::ext(volcano_dem)
terra::res(volcano_dem)

volcano_dem |>
  height_shade() |>
  add_shadow(ray_shade(),0) |>
  plot_3d()

Walking Trails Around Maungawhau

Description

Public walking paths from OpenStreetMap clipped to the extent of volcano_spatial(). Restricted and customer-only paths are omitted.

Usage

volcano_trails

Format

An sf object with 160 LINESTRING features in EPSG:27200, NZGD49 / New Zealand Map Grid. It contains osm_id, highway, name, foot, surface, access, and sac_scale attributes.

Source

© OpenStreetMap contributors, retrieved 2026-08-25 from OpenStreetMap under the Open Data Commons Open Database License.

Examples

if (requireNamespace("sf", quietly = TRUE)) {
  plot(sf::st_geometry(volcano_trails))
}

Washington Monument 3D Model as Multipolygon Z Data

Description

This dataset is an sf object containing MULTIPOLYGON Z 3D data of the Washington Monument in Washington, DC.

Usage

washington_monument_multipolygonz

Format

An sf object with MULTIPOLYGONZ geometry.

Source

https://opendata.dc.gov/documents/DCGIS::buildings-in-3d/

Examples

# See the `render_multipolygonz()` documentation for examples of using this data.