| 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 |
Overlays an image (with a transparency layer) on the current map.
add_overlay( hillshade = NULL, overlay = NULL, alpha_layer = 1, alpha_color = NULL, alpha_method = "max", color_epsilon = 0.001, rescale_original = FALSE, ... )add_overlay( hillshade = NULL, overlay = NULL, alpha_layer = 1, alpha_color = NULL, alpha_method = "max", color_epsilon = 0.001, rescale_original = FALSE, ... )
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_layer |
Default |
alpha_color |
Default |
alpha_method |
Default |
color_epsilon |
Default |
rescale_original |
Default |
... |
Deprecated argument spellings are accepted with a warning and forwarded to their current names. |
Hillshade with overlay.
#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()#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()
Multiplies a texture array or shadow map by a shadow map.
add_shadow( hillshade, shadow_map, max_darken = 0.7, rescale_original = FALSE, ... )add_shadow( hillshade, shadow_map, max_darken = 0.7, rescale_original = FALSE, ... )
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 |
rescale_original |
Default |
... |
Deprecated argument spellings are accepted with a warning and forwarded to their current names. |
Shaded texture map.
#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()#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()
Colors water cells in a shaded map using a matrix or spatial raster mask.
add_water(hillshade, water_map, color = "imhof1", ...)add_water(hillshade, water_map, color = "imhof1", ...)
hillshade |
A three-dimensional RGB array. |
water_map |
A numeric or logical matrix in heightmap orientation, a
single-layer |
color |
Default |
... |
Deprecated argument spellings are accepted with a warning and forwarded to their current names. |
A three-dimensional RGB array with water cells colored. The result is cached as the current shaded map without changing the cached terrain.
#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()#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()
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.
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, ... )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, ... )
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 |
sun_breaks |
Default |
max_search |
Default |
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 |
zscale |
Default 1. The ratio between the x and y spacing (which are assumed to be equal) and the z axis. |
vertical_exaggeration |
Default |
cache_mask |
Default |
shadow_cache |
Default |
progress_bar |
Default |
geographic_aspect |
Default |
extent |
Default |
crs |
Default |
... |
Additional arguments to pass to the |
Shaded texture map.
# 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()# 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()
Calculates the normal unit vector for every point on the grid.
calculate_normal( heightmap, zscale = 1, progress_bar = FALSE, geographic_aspect = TRUE, extent = NULL, crs = NULL, ... )calculate_normal( heightmap, zscale = 1, progress_bar = FALSE, geographic_aspect = TRUE, extent = NULL, crs = NULL, ... )
heightmap |
A two-dimensional matrix or spatial raster containing elevation values. |
zscale |
Default |
progress_bar |
Default |
geographic_aspect |
Default |
extent |
Default |
crs |
Default |
... |
Deprecated argument spellings are accepted with a warning and forwarded to their current names. |
Matrix of light intensities at each point.
#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()#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()
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.
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 )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 )
heightmap |
A two-dimensional matrix, where each entry in the matrix is the elevation at that point. This is used by |
start_altitude |
Default |
end_altitude |
Default |
sun_altitude |
Default |
sun_angle |
Default |
time |
Default |
cloud_cover |
Default |
layers |
Default |
offset_x |
Default |
offset_y |
Default |
scale_x |
Default |
scale_y |
Default |
scale_z |
Default |
frequency |
Default |
fractal_levels |
Default |
attenuation_coef |
Default |
seed |
Default |
zscale |
Default |
vertical_exaggeration |
Default |
geographic_aspect |
Default |
extent |
Default |
crs |
Default |
A 2D shadow matrix.
#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()#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()
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.
constant_shade(heightmap, color = "white", alpha = 1)constant_shade(heightmap, color = "white", alpha = 1)
heightmap |
A two-dimensional matrix, where each entry in the matrix is the elevation at that point. |
color |
Default |
alpha |
Default |
RGB array of a single color layer.
#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()#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()
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().
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, ... )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, ... )
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 |
extent |
Either an object representing the spatial extent of the scene
(either from the |
frames |
Default |
reorder |
Default |
reorder_first_index |
Default |
reorder_duplicate_tolerance |
Default |
reorder_merge_tolerance |
Default |
simplify_tolerance |
Default |
zscale |
Default |
vertical_exaggeration |
Default |
heightmap |
Default |
offset |
Default |
type |
Default |
offset_look_at |
Default |
constant_step |
Default |
curvature_adjust |
Default |
curvature_scale |
Default |
follow_camera |
Default |
follow_distance |
Default |
follow_angle |
Default |
follow_rotations |
Default |
follow_fixed |
Default |
follow_fixed_offset |
Default |
distance_units |
Default |
damp_motion |
Default |
damp_magnitude |
Default |
resample_path_evenly |
Default |
... |
Other arguments to pass to |
#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)#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)
Converts the current RGL rayshader scene to a ray_mesh object (see rayvertex package for more information)
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 )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 )
save_shadow |
Default |
water_attenuation |
Default |
water_surface_color |
Default |
water_ior |
Default |
include_ids |
Default |
exclude_ids |
Default |
id_table |
Default |
A ray_mesh object
filename_obj = tempfile(fileext = ".obj") #Save model of volcano volcano |> sphere_shade() |> plot_3d(zscale = 2) rm_obj = convert_rgl_to_raymesh()filename_obj = tempfile(fileext = ".obj") #Save model of volcano volcano |> sphere_shade() |> plot_3d(zscale = 2) rm_obj = convert_rgl_to_raymesh()
Creates a texture map based on 5 user-supplied colors.
create_texture( light_color, shadow_color, left_color, right_color, center_color, corner_colors = NULL, old_method = FALSE, darken = 1, ... )create_texture( light_color, shadow_color, left_color, right_color, center_color, corner_colors = NULL, old_method = FALSE, darken = 1, ... )
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 |
old_method |
Default |
darken |
Default |
... |
Deprecated argument spellings are accepted with a warning and forwarded to their current names. |
#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()#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()
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.
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, ... )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, ... )
heightmap |
Default |
zscale |
Default |
cutoff |
Default |
min_area |
Default |
max_height |
Default |
normal_vectors |
Default |
keep_groups |
Default |
progress_bar |
Default |
geographic_aspect |
Default |
extent |
Default |
crs |
Default |
... |
Deprecated argument spellings are accepted with a warning and forwarded to their current names. |
Matrix indicating whether water was detected at that point. 1 indicates water, 0 indicates no water.
#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()#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()
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.
flag_banner_obj()flag_banner_obj()
File location of the included flag OBJ file (saved with a .txt extension)
#Print the location of the flag file flag_banner_obj()#Print the location of the flag file flag_banner_obj()
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.
flag_full_obj()flag_full_obj()
File location of the included flag OBJ file (saved with a .txt extension)
#Print the location of the flag file flag_full_obj()#Print the location of the flag file flag_full_obj()
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.
flag_pole_obj()flag_pole_obj()
File location of the included flag OBJ file (saved with a .txt extension)
#Print the location of the flag file flag_pole_obj()#Print the location of the flag file flag_pole_obj()
Using a hillshade and the height map, generates a semi-transparent hillshade to layer onto an existing map.
generate_altitude_overlay( hillshade, heightmap = NULL, start_transition, end_transition = NULL, lower = TRUE, relative = FALSE, extent = NULL, crs = NULL )generate_altitude_overlay( hillshade, heightmap = NULL, start_transition, end_transition = NULL, lower = TRUE, relative = FALSE, extent = NULL, crs = NULL )
hillshade |
The hillshade to transition into. |
heightmap |
Default |
start_transition |
Elevation threshold, or proportion of the height range if |
end_transition |
Default |
lower |
Default |
relative |
Default |
extent |
Default |
crs |
Default |
4-layer RGB array representing the semi-transparent hillshade.
#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()#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()
This adds the compass
Based on code from "Auxiliary Cartographic Functions in R: North Arrow, Scale Bar, and Label with a Leader Arrow"
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 )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 )
x |
Default |
y |
Default |
size |
Default |
text_size |
Default |
bearing |
Default |
heightmap |
Default |
width |
Default |
height |
Default |
resolution_multiply |
Default |
color1 |
Default |
color2 |
Default |
text_color |
Default |
border_color |
Default |
border_width |
Default |
compass_type |
Default |
halo_color |
Default |
halo_expand |
Default |
halo_alpha |
Default |
halo_offset |
Default |
halo_blur |
Default |
halo_edge_softness |
Default |
halo_gap_fill |
Default |
halo_gap_fill_alpha_threshold |
Default |
Semi-transparent overlay with a compass.
#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()#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()
Calculates and returns an overlay of contour lines for the current height map.
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, ... )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, ... )
heightmap |
Default |
levels |
Default |
n_levels |
Default |
zscale |
Default |
width |
Default |
height |
Default |
resolution_multiply |
Default |
color |
Default |
linewidth |
Default |
geographic_aspect |
Default |
extent |
Default |
crs |
Default |
... |
Deprecated argument spellings are accepted with a warning and forwarded to their current names. |
Semi-transparent overlay with contours.
#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()#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()
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.
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 )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 )
labels |
A character vector of labels, or an |
extent |
Default |
x |
Default |
y |
Default |
heightmap |
Default |
width |
Default |
height |
Default |
resolution_multiply |
Default |
text_size |
Default |
color |
Default |
font |
Default |
pch |
Default |
point_size |
Default |
point_color |
Default |
offset |
Default |
data_label_column |
Default |
halo_color |
Default |
halo_expand |
Default |
halo_alpha |
Default |
halo_offset |
Default |
halo_blur |
Default |
halo_edge_softness |
Default |
halo_gap_fill |
Default |
halo_gap_fill_alpha_threshold |
Default |
seed |
Default |
Semi-transparent overlay with labels.
#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()#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()
Calculates and returns an overlay of lines for the current height map.
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) )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) )
geometry |
An |
extent |
Default |
heightmap |
Default |
width |
Default |
height |
Default |
resolution_multiply |
Default |
color |
Default |
linewidth |
Default |
lty |
Default |
data_column_width |
Default |
offset |
Default |
Semi-transparent overlay with contours.
#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()#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()
Calculates and returns an overlay of points for the current map.
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 )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 )
geometry |
An |
extent |
Default |
heightmap |
Default |
width |
Default |
height |
Default |
resolution_multiply |
Default |
pch |
Default |
color |
Default |
size |
Default |
offset |
Default |
data_column_width |
Default |
Semi-transparent overlay with contours.
#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()#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()
Transforms an input sf object into an image overlay for the current height map.
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, ... )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, ... )
geometry |
An |
extent |
Default |
heightmap |
Default |
width |
Default |
height |
Default |
resolution_multiply |
Default |
offset |
Default |
data_column_fill |
Default |
line_color |
Default |
palette |
Default |
linewidth |
Default |
... |
Deprecated argument spellings are accepted with a warning and forwarded to their current names. |
Image overlay representing the input polygon data.
#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()#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()
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.
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" )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" )
raster |
A raster layer. This can be a |
extent |
Default |
heightmap |
Default |
width |
Default |
height |
Default |
resolution_multiply |
Default |
palette |
Default |
alpha |
Default |
range |
Default |
resample_method |
Default |
4-layer RGBA array representing the raster overlay.
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() }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() }
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.
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, ... )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, ... )
extent |
Default |
length |
Default |
x |
Default |
y |
Default |
lat_long |
Default |
thickness |
Default |
bearing |
Default |
unit |
Default |
flip_ticks |
Default |
labels |
Default |
text_size |
Default |
decimals |
Default |
text_offset |
Default |
adj |
Default |
heightmap |
Default |
width |
Default |
height |
Default |
resolution_multiply |
Default |
color1 |
Default |
color2 |
Default |
text_color |
Default |
font |
Default |
border_color |
Default |
tick_color |
Default |
border_width |
Default |
tick_width |
Default |
halo_color |
Default |
halo_expand |
Default |
halo_alpha |
Default |
halo_offset |
Default |
halo_blur |
Default |
halo_edge_softness |
Default |
halo_gap_fill |
Default |
halo_gap_fill_alpha_threshold |
Default |
... |
Deprecated argument spellings are accepted with a warning and forwarded to their current names. |
Semi-transparent overlay with a scale bar.
#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()#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()
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.
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 )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 )
heightmap |
Default |
color |
Default |
linewidth |
Default |
boolean |
Default |
min |
Default |
max |
Default |
breaks |
Default |
smooth |
Default |
fade |
Default |
alpha_dist |
Default to the value specified in |
alpha |
Default |
falloff |
Default |
evenly_spaced |
Default |
zscale |
Default |
cutoff |
Default |
width |
Default |
height |
Default |
resolution_multiply |
Default |
min_area |
Default |
max_height |
Default |
return_distance_matrix |
Default |
geographic_aspect |
Default |
extent |
Default |
crs |
Default |
4-layer RGB array representing the waterline overlay.
#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()#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()
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.
get_scene_metadata(include_heightmap = FALSE)get_scene_metadata(include_heightmap = FALSE)
include_heightmap |
Default |
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.
volcano_spatial() |> height_shade() |> plot_3d() scene_info = get_scene_metadata() scene_info$extent_3d scene_info$scene_boundsvolcano_spatial() |> height_shade() |> plot_3d() scene_info = get_scene_metadata() scene_info$extent_3d scene_info$scene_bounds
Generates a semi-transparent constant-color overlay whose opacity follows an exponential atmospheric column model.
haze_shade( heightmap, color = "white", optical_depth = 0.5, scale_height = NULL, scale_height_relative = FALSE, reference_height = NULL, alpha = 1, blur = 0 )haze_shade( heightmap, color = "white", optical_depth = 0.5, scale_height = NULL, scale_height_relative = FALSE, reference_height = NULL, alpha = 1, blur = 0 )
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 |
optical_depth |
Default |
scale_height |
Default |
scale_height_relative |
Default |
reference_height |
Default |
alpha |
Default |
blur |
Default |
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].
A 4-layer RGBA array representing the haze overlay.
# 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()# 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()
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.
height_shade( heightmap, texture = (grDevices::colorRampPalette(c("#6AA85B", "#D9CC9A", "#FFFFFF")))(256), range = NULL )height_shade( heightmap, texture = (grDevices::colorRampPalette(c("#6AA85B", "#D9CC9A", "#FFFFFF")))(256), range = NULL )
heightmap |
A two-dimensional matrix, where each entry in the matrix is the elevation at that point. |
texture |
Default |
range |
Default |
RGB array of hillshaded texture mappings.
#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()#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()
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.
lamb_shade( heightmap, sun_altitude = 45, sun_angle = 315, zscale = 1, vertical_exaggeration = 1, zero_negative = TRUE, geographic_aspect = TRUE, extent = NULL, crs = NULL, ... )lamb_shade( heightmap, sun_altitude = 45, sun_angle = 315, zscale = 1, vertical_exaggeration = 1, zero_negative = TRUE, geographic_aspect = TRUE, extent = NULL, crs = NULL, ... )
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 |
sun_angle |
Default |
zscale |
Default |
vertical_exaggeration |
Default |
zero_negative |
Default |
geographic_aspect |
Default |
extent |
Default |
crs |
Default |
... |
Deprecated argument spellings are accepted with a warning and forwarded to their current names. |
Matrix of light intensities at each point.
#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()#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()
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.
monterey_counties_sfmonterey_counties_sf
An sf object with MULTIPOLYGON geometry.
https://catalog.data.gov/dataset/tiger-line-shapefile-2016-state-california-current-county-subdivision-state-based
# 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)# 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)
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.
monterey_roads_sfmonterey_roads_sf
An sf object with LINESTRING geometry.
https://www2.census.gov/geo/tiger/TIGER2015/PRISECROADS/tl_2015_06_prisecroads.zip
# 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)# 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)
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.
montereybaymontereybay
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.
https://www.ncei.noaa.gov/metadata/geoportal/rest/metadata/item/gov.noaa.ngdc.mgg.dem:3544/html
# 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)# 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)
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.
montereybay_spatialmontereybay_spatial
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.
https://www.ncei.noaa.gov/metadata/geoportal/rest/metadata/item/gov.noaa.ngdc.mgg.dem:3544/html
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()
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, ... )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, ... )
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 |
zscale |
Default |
vertical_exaggeration |
Default |
base_shape |
Default |
solid |
Default |
solid_depth |
Default |
solid_color |
Default |
solid_line_color |
Default |
shadow |
Default |
shadow_depth |
Default |
shadow_color |
Default |
shadow_darkness |
Default |
shadow_width |
Default |
shadow_texture_size |
Default |
water |
Default |
water_input |
Default |
water_color |
Default |
water_alpha |
Default |
water_line_color |
Default |
water_line_alpha |
Default |
linewidth |
Default |
line_antialias |
Default |
water_render_method |
Default |
water_edge_extension |
Default |
water_polygon_failure |
Default |
soil |
Default |
soil_freq |
Default |
soil_levels |
Default |
soil_color_light |
Default |
soil_color_dark |
Default |
soil_gradient |
Default |
soil_gradient_darken |
Default |
theta |
Default |
phi |
Default |
fov |
Default |
zoom |
Default |
background |
Default |
window_size |
Default |
precomputed_normals |
Default |
triangulate |
Default |
max_error |
Default |
max_tri |
Default |
verbose |
Default |
plot_new |
Default |
close_previous |
Default |
clear_previous |
Default |
extent |
Default |
geographic_aspect |
Default |
crs |
Default |
water_elevation |
Default |
water_surface_tolerance |
Default |
normals |
Default |
earth_curvature |
Default |
... |
Deprecated argument spellings are accepted with a warning and forwarded to their current names. |
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.
#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()#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()
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.
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, ... )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, ... )
gg_obj |
ggplot object to projected into 3D. |
gg_obj_height |
Default |
width |
Default |
height |
Default |
height_aes |
Default |
invert |
Default |
shadow_intensity |
Default |
units |
Default |
scale |
Deprecated. Use |
zscale |
Default |
vertical_exaggeration |
Default |
point_contract |
Default |
offset_edges |
Default |
flat_substrate |
Default |
flat_plot_render |
Default |
flat_distance |
Default |
flat_transparent_bg |
Default |
flat_direction |
Default |
shadow |
Default |
shadow_depth |
Default |
shadow_color |
Default |
shadow_darkness |
Default |
background |
Default |
preview |
Default |
raytrace |
Default |
radiance_args |
Default |
sun_angle |
Default |
angle_breaks |
Default |
multicore |
Default |
lambert |
Default |
triangulate |
Default |
max_error |
Default |
max_tri |
Default |
verbose |
Default |
emboss_text |
Default |
emboss_grid |
Default |
guide_bar_bleed_px |
Default |
guide_bar_bleed_target |
Default |
reduce_size |
Default |
save_height_matrix |
Default |
save_shadow_matrix |
Default |
saved_shadow_matrix |
Default |
monitor_gamma |
Default |
plot |
Default |
... |
Additional arguments to be passed to |
Opens a 3D plot in rgl.
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()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()
Displays the map in the current device.
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", ... )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", ... )
hillshade |
Hillshade to be plotted. |
title_text |
Default |
title_offset |
Default |
title_color |
Default |
title_size |
Default |
title_font |
Default |
title_style |
Default |
title_bar_color |
Default |
title_bar_alpha |
Default |
title_just |
Default |
... |
Additional arguments to pass to the |
#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()#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()
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).
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, ... )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, ... )
heightmap |
Default |
texture |
Default |
color |
Default |
zscale |
Default |
vertical_exaggeration |
Default |
filename |
Default |
samples |
Default |
sample_method |
Default |
min_variance |
Default |
shadow |
Default |
light |
Default |
lat |
Default |
long |
Default |
datetime |
Default |
sky_sun_elevation |
Default |
sky_sun_azimuth |
Default |
sky_altitude |
Default |
sky_args |
Default |
light_direction |
Default |
light_altitude |
Default |
light_size |
Default |
light_intensity |
Default |
light_color |
Default |
material |
Default |
water_attenuation |
Default |
water_surface_color |
Default |
water_ior |
Default |
override_material |
Default |
cache_scene |
Default |
reset_scene_cache |
Default |
width |
Default |
height |
Default |
clamp_value |
Default |
auto_exposure |
Default |
capture_scene |
Default |
scene_elements |
Default |
plot |
Default |
geographic_aspect |
Default |
extent |
Default |
crs |
Default |
... |
Additional parameters passed to |
RGBA array representing the top-down radiance render.
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()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()
Turns a raster into a matrix suitable for rayshader.
raster_to_matrix(raster, verbose = interactive())raster_to_matrix(raster, verbose = interactive())
raster |
The input raster. Either a RasterLayer object, a terra SpatRaster object, or a filename. |
verbose |
Default |
#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()#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()
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.
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, ... )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, ... )
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 |
sun_angle |
Default |
max_search |
Defaults to the longest possible shadow given the |
lambert |
Default |
zscale |
Default |
vertical_exaggeration |
Default |
multicore |
Default |
cache_mask |
Default |
shadow_cache |
Default |
progress_bar |
Default |
angle_breaks |
Default |
geographic_aspect |
Default |
extent |
Default |
crs |
Default |
... |
Additional arguments to pass to the |
Matrix of light intensities at each point.
#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()#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)
reduce_matrix_size(...)reduce_matrix_size(...)
... |
Arguments to pass to |
Reduced matrix.
montereybay_matrix = raster_to_matrix(montereybay_spatial, verbose = FALSE) montbaysmall = resize_matrix(montereybay_matrix, scale=0.5) montbaysmall |> sphere_shade() |> plot_map()montereybay_matrix = raster_to_matrix(montereybay_spatial, verbose = FALSE) montbaysmall = resize_matrix(montereybay_matrix, scale=0.5) montbaysmall |> sphere_shade() |> plot_map()
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.
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, ... )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, ... )
polygon |
|
material |
Default |
bevel_material |
Default |
angle |
Default |
bevel_width |
Default |
width_raw_units |
Default |
bevel |
Default |
bevel_height |
Default |
base_height |
Default |
raw_heights |
Default |
raw_offsets |
Default |
heights_relative_to_centroid |
Default |
set_max_height |
Default |
max_height |
Default |
scale_all_max |
Default |
data_column_top |
Default |
data_column_bottom |
Default |
scale_data |
Default |
holes |
Default |
alpha |
Default |
lit |
Default |
flat_shading |
Default |
light_altitude |
Default |
light_direction |
Default |
light_intensity |
Default |
light_relative |
Default |
clear_previous |
Default |
crs |
Default |
filter_to_extent |
Default |
extent |
Either an object representing the spatial extent of the 3D scene
(either from the |
panel |
Default |
zscale |
Default |
vertical_exaggeration |
Default |
heightmap |
Default |
... |
Additional arguments to pass to |
# 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))# 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))
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.
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, ... )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, ... )
polygon |
|
material |
Default |
roof_material |
Default |
angle |
Default |
scale_data |
Default |
relative_heights |
Default |
heights_relative_to_centroid |
Default |
roof_height |
Default |
base_height |
Default |
data_column_top |
Default |
data_column_bottom |
Default |
holes |
Default |
alpha |
Default |
lit |
Default |
flat_shading |
Default |
light_altitude |
Default |
light_direction |
Default |
light_intensity |
Default |
light_relative |
Default |
clear_previous |
Default |
crs |
Default |
filter_to_extent |
Default |
extent |
Either an object representing the spatial extent of the 3D scene
(either from the |
panel |
Default |
zscale |
Default |
vertical_exaggeration |
Default |
heightmap |
Default |
... |
Additional arguments to pass to |
# 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) )# 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) )
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.
render_camera( location = NULL, theta = NULL, phi = NULL, zoom = NULL, fov = NULL, altitude = NULL, shift_vertical = 0, lat = NULL, long = NULL, panel = NULL )render_camera( location = NULL, theta = NULL, phi = NULL, zoom = NULL, fov = NULL, altitude = NULL, shift_vertical = 0, lat = NULL, long = NULL, panel = NULL )
location |
Default |
theta |
Defaults to current value. Rotation angle. |
phi |
Defaults to current value. Azimuth angle. Maximum |
zoom |
Defaults to current value. Positive value indicating camera magnification. |
fov |
Defaults to current value. Field of view of the camera. Maximum |
altitude |
Default |
shift_vertical |
Default |
lat |
Default |
long |
Default |
panel |
Default |
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)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 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.
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 )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 )
start_altitude |
Default |
end_altitude |
Default |
sun_altitude |
Default |
sun_angle |
Default |
time |
Default |
cloud_cover |
Default |
layers |
Default |
offset_x |
Default |
offset_y |
Default |
scale_x |
Default |
scale_y |
Default |
scale_z |
Default |
frequency |
Default |
fractal_levels |
Default |
attenuation_coef |
Default |
seed |
Default |
clear_clouds |
Default |
zscale |
Default |
vertical_exaggeration |
Default |
heightmap |
Default |
Adds a 3D floating cloud layer to the map. No return value.
#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 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()
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.
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 )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 )
angle |
Default |
position |
Default |
compass_radius |
Default |
scale_distance |
Default |
color_n |
Default |
color_arrow |
Default |
color_background |
Default |
color_bevel |
Default |
position_circular |
Default |
clear_compass |
Default |
x |
Default |
y |
Default |
z |
Default |
altitude |
Default |
zscale |
Default |
vertical_exaggeration |
Default |
Adds compass to map. No return value.
#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()#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()
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.
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, ... )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, ... )
levels |
Default |
n_levels |
Default |
linewidth |
Default |
color |
Default |
palette |
Default |
antialias |
Default |
offset |
Default |
clear_previous |
Default |
zscale |
Default |
vertical_exaggeration |
Default |
heightmap |
Default |
... |
Additional arguments passed to |
#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) )))#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) )))
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))
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, ... )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, ... )
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 |
f_stop |
Default |
filename |
The filename of the image to be saved. If this is not given, the image will be plotted instead. |
preview_focus |
Default |
bokeh_shape |
Default |
bokeh_intensity |
Default |
bokeh_limit |
Default |
rotation |
Default |
aberration |
Default |
transparent_water |
Default |
title_text |
Default |
title_offset |
Default |
title_color |
Default |
title_size |
Default |
title_font |
Default |
title_bar_color |
Default |
title_bar_alpha |
Default |
title_just |
Default |
image_overlay |
Default |
vignette |
Default |
vignette_color |
Default |
vignette_radius |
Default |
progress_bar |
Default |
software_render |
Default |
width |
Default |
height |
Default |
camera_location |
Default |
camera_lookat |
Default |
background |
Default |
text_angle |
Default |
text_size |
Default |
text_offset |
Default |
point_radius |
Default |
line_offset |
Default |
print_scene_info |
Default |
verbose |
Default |
instant_capture |
Default |
clear |
Default |
bring_to_front |
Default |
heightmap |
Deprecated and ignored. Retained for backward compatibility. |
zscale |
Deprecated and ignored. Retained for backward compatibility. |
cache_scene |
Default |
reset_scene_cache |
Default |
... |
Additional parameters to pass to |
4-layer RGBA array.
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)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 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.
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, ... )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, ... )
overlay |
Overlay (4D RGBA array) to be rendered on the 3D map. |
altitude |
Altitude to place the overlay. |
alpha |
Default |
remove_na |
Default |
reorient |
Default |
clear_layers |
Default |
horizontal_offset |
Default |
zscale |
Default |
vertical_exaggeration |
Default |
heightmap |
Default |
... |
Additional arguments to pass to |
Adds a 3D floating layer to the map. No return value.
#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 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() }
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.
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, ... )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, ... )
filename |
Default |
samples |
Default |
sample_method |
Default |
min_variance |
Default |
light |
Default |
lat |
Default |
long |
Default |
datetime |
Default |
sky_sun_elevation |
Default |
sky_sun_azimuth |
Default |
sky_altitude |
Default |
sky_args |
Default empty |
sky_haze |
Default |
sky_query_altitude |
Default |
light_direction |
Default |
light_altitude |
Default |
light_size |
Default |
light_intensity |
Default |
light_color |
Default |
material |
Default |
water_attenuation |
Default |
water_surface_color |
Default |
water_ior |
Default |
water_material |
Default |
water_roughness |
Default |
override_material |
Default |
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 |
text_angle |
Default |
text_size |
Default |
text_offset |
Default |
text_render |
Default |
text_occlusion |
Default |
text_occlusion_mode |
Default |
text_occlusion_tolerance |
Default |
screen_text_args |
Default empty |
line_radius |
Default |
line_render |
Default |
line_occlusion |
Default |
line_occlusion_mode |
Default |
line_occlusion_tolerance |
Default |
screen_line_args |
Default empty |
point_radius |
Default |
smooth_line |
Default |
use_extruded_paths |
Default |
joined_stream_mesh |
Default |
scale_text_angle |
Default |
scale_text_size |
Default |
scale_text_offset |
Default |
title_text |
Default |
title_offset |
Default |
title_color |
Default |
title_size |
Default |
title_font |
Default |
title_just |
Default |
title_bar_color |
Default |
title_bar_alpha |
Default |
ground_material |
Default |
ground_size |
Default |
scene_elements |
Default |
camera_location |
Default |
camera_lookat |
Default |
camera_interpolate |
Default |
clear |
Default |
return_scene |
Default |
print_scene_info |
Default |
clamp_value |
Default |
calculate_consistent_normals |
Default |
load_normals |
Default |
rgl_materials |
Default empty |
animation_camera_coords |
Default |
plot |
Default |
verbose |
Default |
parallel |
Default |
cache_scene |
Default |
reset_scene_cache |
Default |
fov |
Default |
panel |
Default |
... |
Additional parameters to pass to |
#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 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") )
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.
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, ... )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, ... )
location |
Default |
text |
Default |
data_column_text |
Default |
font |
Default |
family |
Default |
font_type |
Default |
text_size |
Default |
text_color |
Default |
text_alpha |
Default |
freetype |
Default |
adjust_vec |
Default |
line |
Default |
line_color |
Default |
linewidth |
Default |
alpha |
Default |
dashed |
Default |
dash_length |
Default |
antialias |
Default |
clear_previous |
Default |
x |
Default |
y |
Default |
z |
Default |
altitude |
Default |
data_column_z |
Default |
scale_data |
Default |
relative_z |
Default |
offset |
Default |
lat |
Default |
long |
Default |
crs |
Default |
filter_to_extent |
Default |
extent |
Default |
panel |
Default |
zscale |
Default |
vertical_exaggeration |
Default |
heightmap |
Default |
... |
Deprecated argument spellings are accepted with a warning and forwarded to their current names. |
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()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()
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).
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(), ... )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(), ... )
filename |
Filename. If not appended with |
type |
Default |
frames |
Default |
fps |
Default |
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 |
fov |
Defaults to the current view. Field of view values, in degrees. |
width |
Default |
height |
Default |
audio |
Default |
progress_bar |
Default |
... |
Additional parameters to pass to |
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) }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) }
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.
render_movie_hq( frames = 360, type = "linear", closed = TRUE, damp_motion = TRUE, render_highquality_args = list(), keyframes = NULL, ... )render_movie_hq( frames = 360, type = "linear", closed = TRUE, damp_motion = TRUE, render_highquality_args = list(), keyframes = NULL, ... )
frames |
Default |
type |
Default |
closed |
Default |
damp_motion |
Default |
render_highquality_args |
Default |
keyframes |
Default |
... |
Additional parameters to pass to |
Invisibly returns the value from rayrender::render_animation().
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
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, ... )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, ... )
sf_obj |
An sf object with MULTIPOLYGON Z geometry. |
color |
Default |
obj_zscale |
Default |
swap_yz |
Default |
rgl_tag |
Default |
clear_previous |
Default |
offset |
Default |
crs |
Default |
filter_to_extent |
Default |
extent |
Either an object representing the spatial extent of the scene
(either from the |
panel |
Default |
zscale |
Default |
vertical_exaggeration |
Default |
heightmap |
Default |
verbose |
Default |
... |
Additional arguments to pass to |
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.
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)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)
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).
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, ... )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, ... )
filename |
Filename for the OBJ file. |
location |
Default |
load_material |
Default |
load_normals |
Default |
color |
Default |
obj_zscale |
Default |
swap_yz |
Default |
angle |
Default |
scale |
Default |
lit |
Default |
light_altitude |
Default |
light_direction |
Default |
light_intensity |
Default |
light_relative |
Default |
rgl_tag |
Default |
clear_previous |
Default |
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 |
xyz |
Default |
offset |
Default |
lat |
Default |
long |
Default |
crs |
Default |
filter_to_extent |
Default |
extent |
Either an object representing the spatial extent of the scene
(either from the |
panel |
Default |
zscale |
Default |
vertical_exaggeration |
Default |
heightmap |
Default |
... |
Additional arguments to pass to |
#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 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)
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.
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 )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 )
y |
Vector of y coordinates (or other coordinate in the same coordinate reference system as extent).
Can also be an |
x |
Default |
altitude |
Default |
groups |
Default |
resample_evenly |
Default |
resample_n |
Default |
reorder |
Default |
reorder_first_index |
Default |
reorder_duplicate_tolerance |
Default |
reorder_merge_tolerance |
Default |
simplify_tolerance |
Default |
linewidth |
Default |
color |
Default |
antialias |
Default |
offset |
Default |
clear_previous |
Default |
return_coords |
Default |
tag |
Default |
lat |
Default |
long |
Default |
crs |
Default |
filter_to_extent |
Default |
extent |
Either an object representing the spatial extent of the 3D scene
(either from the |
panel |
Default |
zscale |
Default |
vertical_exaggeration |
Default |
heightmap |
Default |
#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)) )))#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)) )))
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.
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, ... )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, ... )
location |
Default |
pose |
Default |
sex |
Default |
line |
Default |
line_spacing |
Default |
line_terrain_spacing |
Default |
line_pattern |
Default |
line_align_terrain |
Default |
color |
Default |
angle |
Default |
lit |
Default |
load_normals |
Default |
clear_previous |
Default |
x |
Default |
y |
Default |
altitude |
Default |
xyz |
Default |
offset |
Default |
lat |
Default |
long |
Default |
crs |
Default |
filter_to_extent |
Default |
extent |
Default |
panel |
Default |
zscale |
Default |
vertical_exaggeration |
Default |
heightmap |
Default |
simple_rgl |
Default |
... |
Additional arguments passed to |
# 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)# 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)
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.
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 )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 )
location |
Default |
size |
Default |
color |
Default |
clear_previous |
Default |
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 |
offset |
Default |
lat |
Default |
long |
Default |
crs |
Default |
filter_to_extent |
Default |
extent |
Either an object representing the spatial extent of the 3D scene
(either from the |
panel |
Default |
zscale |
Default |
vertical_exaggeration |
Default |
heightmap |
Default |
#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) ) ) )#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) ) ) )
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.
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, ... )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, ... )
polygon |
|
color |
Default |
top |
Default |
bottom |
Default |
data_column_top |
Default |
data_column_bottom |
Default |
scale_data |
Default |
parallel |
Default |
holes |
Default |
alpha |
Default |
lit |
Default |
light_altitude |
Default |
light_direction |
Default |
light_intensity |
Default |
light_relative |
Default |
clear_previous |
Default |
crs |
Default |
filter_to_extent |
Default |
extent |
Either an object representing the spatial extent of the 3D scene
(either from the |
panel |
Default |
zscale |
Default |
vertical_exaggeration |
Default |
heightmap |
Default |
... |
Additional arguments passed to |
#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 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)
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).
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, ... )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, ... )
raymesh |
|
location |
Default |
load_normals |
Default |
change_material |
Default |
color |
Default |
obj_zscale |
Default |
swap_yz |
Default |
angle |
Default |
scale |
Default |
flat_shading |
Default |
lit |
Default |
light_altitude |
Default |
light_direction |
Default |
light_intensity |
Default |
light_relative |
Default |
rgl_tag |
Default |
clear_previous |
Default |
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 |
xyz |
Default |
offset |
Default |
lat |
Default |
long |
Default |
crs |
Default |
filter_to_extent |
Default |
extent |
Either an object representing the spatial extent of the scene
(either from the |
panel |
Default |
zscale |
Default |
vertical_exaggeration |
Default |
heightmap |
Default |
... |
Additional arguments to pass to |
# 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)# 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
render_resize_window(width = NULL, height = NULL)render_resize_window(width = NULL, height = NULL)
width |
Default |
height |
Default |
None
#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()#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()
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.
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, ... )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, ... )
roads |
Spatial line data used to draw road paths. Supports |
road_color |
Default |
width |
Default |
width_column |
Default |
densify |
Default |
offset |
Default |
offset_transition |
Default |
layer |
Default |
layer_height |
Default |
merge |
Default |
lane_texture |
Default |
lane_texture_file |
Default |
lane_dash_length |
Default |
lane_gap_length |
Default |
lane_texture_length |
Default |
lane_texture_mapping |
Default |
lanes |
Default |
lane_width |
Default |
lane_color |
Default |
centerline_color |
Default |
edge_line_color |
Default |
lane_line_width |
Default |
lane_dash_fraction |
Default |
clear_previous |
Default |
preview |
Default |
verbose |
Default |
parallel |
Default |
maximum_grade |
Default |
continuation_grade_tolerance |
Default |
zscale |
Default |
vertical_exaggeration |
Default |
heightmap |
Default |
terrain_grading |
Default |
bridge |
Default |
... |
Deprecated argument spellings are accepted with a warning and forwarded to their current names. |
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.
Places a scale bar on the map in 3D.
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 )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 )
limits |
Default |
position |
Default |
y |
Default |
segments |
Default |
scale_length |
Default |
label_unit |
Default |
offset |
Default |
radius |
Default |
color_first |
Default |
color_second |
Default |
color_text |
Default |
text_switch_side |
Default |
text_x_offset |
Default |
text_y_offset |
Default |
text_z_offset |
Default |
clear_previous |
Default |
The resolved scale-bar specification, invisibly.
#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()#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()
Either captures the current rgl view and displays, or saves the current view to disk.
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, ... )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, ... )
filename |
Filename of snapshot. If missing, will display to current device. |
clear |
Default |
title_text |
Default |
title_offset |
Default |
title_color |
Default |
title_size |
Default |
title_font |
Default |
title_bar_color |
Default |
title_bar_alpha |
Default |
title_just |
Default |
image_overlay |
Default |
vignette |
Default |
vignette_color |
Default |
vignette_radius |
Default |
instant_capture |
Default |
bring_to_front |
Default |
webshot |
Default |
width |
Default |
height |
Default |
software_render |
Default |
camera_location |
Default |
camera_lookat |
Default |
background |
Default |
text_angle |
Default |
text_size |
Default |
text_offset |
Default |
point_radius |
Default |
line_offset |
Default |
thick_lines |
Default |
line_radius |
Default |
new_page |
Default |
print_scene_info |
Default |
fsaa |
Default |
rayvertex_lighting |
Default |
rayvertex_lights |
Default |
rayvertex_shadow_map |
Default |
plot |
Default |
cache_scene |
Default |
reset_scene_cache |
Default |
... |
Additional parameters to pass to |
Displays snapshot of current rgl plot (or saves to disk), as well as invisibly returns an RGBA rayimg array.
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)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)
Adds stream paths to the scene, removing the previous stream layer if desired.
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, ... )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, ... )
streams |
Spatial line data used to draw stream paths. Supports |
water_color |
Default |
width |
Default |
width_column |
Default |
width_units |
Default |
densify |
Default |
offset |
Default |
merge |
Default |
water_polygons |
Default |
height |
Default |
clear_previous |
Default |
verbose |
Default |
parallel |
Default |
zscale |
Default |
vertical_exaggeration |
Default |
heightmap |
Default |
... |
Deprecated argument spellings are accepted with a warning and forwarded to their current names. |
Invisibly returns the rendered stream coordinates.
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 )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 )
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.
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 )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 )
trails |
Spatial line data used to draw trails. Supports |
color |
Default |
width |
Default |
width_column |
Default |
width_units |
Default |
densify |
Default |
offset |
Default |
height |
Default |
clear_previous |
Default |
preview |
Default |
verbose |
Default |
parallel |
Default |
zscale |
Default |
vertical_exaggeration |
Default |
heightmap |
Default |
Invisibly returns the independently meshed trail coordinates.
render_streams(), render_roads()
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()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()
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.
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, ... )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, ... )
location |
Default |
type |
Default |
custom_obj_tree |
Default |
custom_obj_crown |
Default |
custom_obj_trunk |
Default |
crown_color |
Default |
trunk_color |
Default |
absolute_height |
Default |
tree_height |
Default |
tree_height_column |
Default |
trunk_height_ratio |
Default |
crown_width_ratio |
Default |
crown_width |
Default |
trunk_radius |
Default |
tree_zscale |
Default |
min_height |
Default |
max_height |
Default |
lit |
Default |
preview_simple |
Default |
preview_point_size |
Default |
angle |
Default |
clear_previous |
Default |
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 |
long |
Default |
crs |
Default |
filter_to_extent |
Default |
extent |
Either an object representing the spatial extent of the 3D scene
(either from the |
panel |
Default |
zscale |
Default |
vertical_exaggeration |
Default |
heightmap |
Default |
load_normals |
Default |
... |
Additional arguments to pass to |
#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)#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)
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.
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, ... )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, ... )
water_input |
Default |
water_color |
Default |
water_alpha |
Default |
water_line_color |
Default |
water_line_alpha |
Default |
linewidth |
Default |
water_render_method |
Default |
water_edge_extension |
Default |
water_edge_clamp |
Default |
water_polygon_failure |
Default |
clear_previous |
Default |
zscale |
Default |
vertical_exaggeration |
Default |
heightmap |
Default |
water_elevation |
Default |
water_surface_tolerance |
Default |
parallel |
Default |
... |
Deprecated argument spellings are accepted with a warning and forwarded to their current names. |
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()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()
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.
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 )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 )
data |
Default |
location |
Default |
breaks |
Default |
labels |
Default |
title |
Default |
title_location |
Default |
title_offset |
Default |
title_size |
Default |
color |
Default |
linewidth |
Default |
text_offset |
Default |
label_size |
Default |
label_side |
Default |
title_side |
Default |
corner_offset |
Default |
tick_size |
Default |
extent |
Default |
panel |
Default |
zscale |
Default |
vertical_exaggeration |
Default |
heightmap |
Default |
# 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()# 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()
Resizes a matrix (preserving contents) by specifying the desired output dimensions or a scaling factor.
resize_matrix( heightmap, scale = 1, width = NULL, height = NULL, method = "bilinear" )resize_matrix( heightmap, scale = 1, width = NULL, height = NULL, method = "bilinear" )
heightmap |
The elevation matrix. |
scale |
Default |
width |
Default |
height |
Default |
method |
Default |
#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()#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_spatial() mirrors the ergonomics of rayshader::resize_matrix(),
but returns a terra::SpatRaster with extent and CRS intact.
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(), ... )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(), ... )
x |
A |
scale |
Default |
width |
Default |
height |
Default |
method_down |
Default |
method_up |
Default |
aggregate_if_possible |
Default |
tol |
Default |
threads |
Default |
filename |
Default |
overwrite |
Default |
write_args |
Default |
... |
Arguments passed only to the resize operation that is used:
|
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.
A terra::SpatRaster.
Writes a stereolithography (STL) file that can be used in 3D printing.
save_3dprint(filename, max_width = 125, unit = "mm", rotate = FALSE, ...)save_3dprint(filename, max_width = 125, unit = "mm", rotate = FALSE, ...)
filename |
String with the filename. If |
max_width |
Default |
unit |
Default |
rotate |
Default |
... |
Deprecated argument spellings are accepted with a warning and forwarded to their current names. |
Writes an STL file to filename. Regardless of the unit displayed, the output STL is in millimeters.
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")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")
Converts MULTIPOLYGON Z features into a triangulated 3D OBJ model, preserving concave boundaries and holes in each face.
save_multipolygonz_to_obj(sf_obj, filename, swap_yz = FALSE, ...)save_multipolygonz_to_obj(sf_obj, filename, swap_yz = FALSE, ...)
sf_obj |
sf object with MULTIPOLYGON Z geometry, |
filename |
Filename of the OBJ to save the 3D model to. |
swap_yz |
Default |
... |
Deprecated argument spellings are accepted with a warning and forwarded to their current names. |
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.
#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)#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)
Writes the textured 3D rayshader visualization to an OBJ file.
save_obj( filename, save_texture = TRUE, water_index_refraction = 1, manifold_geometry = FALSE, all_face_fields = FALSE, save_shadow = FALSE )save_obj( filename, save_texture = TRUE, water_index_refraction = 1, manifold_geometry = FALSE, all_face_fields = FALSE, save_shadow = FALSE )
filename |
String with the filename. If |
save_texture |
Default |
water_index_refraction |
Default |
manifold_geometry |
Default |
all_face_fields |
Default |
save_shadow |
Default |
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)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)
A wrapper around rayimage::ray_write_image() to write an image to file.
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" )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" )
hillshade |
Array (or matrix) of hillshade to be written. |
filename |
String with the filename. If |
title_text |
Default |
title_offset |
Default |
title_color |
Default |
title_size |
Default |
title_font |
Default |
title_style |
Default |
title_bar_color |
Default |
title_bar_alpha |
Default |
title_just |
Default |
filename_map = tempfile() #Save the map into `filename_map` montereybay_spatial |> sphere_shade() |> save_png(filename_map)filename_map = tempfile() #Save the map into `filename_map` montereybay_spatial |> sphere_shade() |> save_png(filename_map)
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.
shift_terrain( heightmap, geometry, amount = 1, transition = 0, transition_units = c("map", "cells"), extent = NULL, crs = NULL, touches = TRUE, fun = "max" )shift_terrain( heightmap, geometry, amount = 1, transition = 0, transition_units = c("map", "cells"), extent = NULL, crs = NULL, touches = TRUE, fun = "max" )
heightmap |
Height matrix or spatial raster DEM. Matrix inputs require
|
geometry |
Spatial geometry used to select the affected cells. Supports
|
amount |
Default |
transition |
Default |
transition_units |
Default |
extent |
Default |
crs |
Default |
touches |
Default |
fun |
Default |
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.
A shifted height matrix or terra::SpatRaster. Legacy Raster*
inputs are returned as terra::SpatRaster objects.
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) )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_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.
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", ... )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", ... )
image |
A matrix, RGB/RGBA array, or any input accepted by
|
extent |
Default |
crs |
Default |
panel |
Default |
include_alpha |
Default |
to_rgb |
Default |
flip_vertical |
Default |
flip_horizontal |
Default |
layer_names |
Default |
include_height |
Default |
heightmap |
Default |
height_layer_name |
Default |
... |
Deprecated argument spellings are accepted with a warning and forwarded to their current names. |
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.
A terra::SpatRaster.
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" )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" )
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.
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, ... )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, ... )
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 |
texture |
Default |
normal_vectors |
Default |
color_intensity |
Deprecated alias for |
zscale |
Default |
vertical_exaggeration |
Default |
na_color |
Default |
progress_bar |
Default |
geographic_aspect |
Default |
extent |
Default |
crs |
Default |
... |
Deprecated argument spellings are accepted with a warning and forwarded to their current names. |
RGBA array of hillshaded texture mappings.
#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()#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()
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.
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 )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 )
heightmap |
A two-dimensional matrix, where each entry in the matrix is the elevation at that point. |
detail |
Default |
contrast |
Default |
brightness |
Default |
transform |
Default |
dx |
Default |
dy |
Default |
pad |
Default |
geographic_aspect |
Default |
extent |
Default |
crs |
Default |
2D matrix of hillshade values.
#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()#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()
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.
volcano_spatial()volcano_spatial()
A one-layer terra::SpatRaster containing elevation in meters.
The base R datasets::volcano data and the Geomorphometry.org "Volcano Maungawhau" reconstruction.
volcano_dem = volcano_spatial() terra::ext(volcano_dem) terra::res(volcano_dem) volcano_dem |> height_shade() |> add_shadow(ray_shade(),0) |> plot_3d()volcano_dem = volcano_spatial() terra::ext(volcano_dem) terra::res(volcano_dem) volcano_dem |> height_shade() |> add_shadow(ray_shade(),0) |> plot_3d()
Public walking paths from OpenStreetMap clipped to the extent of
volcano_spatial(). Restricted and customer-only paths are omitted.
volcano_trailsvolcano_trails
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.
© OpenStreetMap contributors, retrieved 2026-08-25 from OpenStreetMap under the Open Data Commons Open Database License.
if (requireNamespace("sf", quietly = TRUE)) { plot(sf::st_geometry(volcano_trails)) }if (requireNamespace("sf", quietly = TRUE)) { plot(sf::st_geometry(volcano_trails)) }
This dataset is an sf object containing MULTIPOLYGON Z 3D data of the Washington Monument in Washington, DC.
washington_monument_multipolygonzwashington_monument_multipolygonz
An sf object with MULTIPOLYGONZ geometry.
https://opendata.dc.gov/documents/DCGIS::buildings-in-3d/
# See the `render_multipolygonz()` documentation for examples of using this data.# See the `render_multipolygonz()` documentation for examples of using this data.