Last active
March 10, 2020 09:14
-
-
Save tim-salabim/9de17804156d1aaf745fe6df8d42a64c to your computer and use it in GitHub Desktop.
use leafgl to visualise mesh3d
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
library(ggplot2) | |
library(leafgl) | |
library(leaflet) | |
library(sf) | |
sfx <- sf::st_transform(sf::st_cast(dplyr::filter(silicate::inlandwaters, Province == "Tasmania"), "POLYGON")[2, ], 4326) | |
topo <- ceramic::cc_elevation(sfx, zoom = 9) | |
mesh <- anglr::as.mesh3d(anglr::copy_down(anglr::DEL(sfx, max_area = .0001), | |
topo)) | |
st_as_sf.mesh3d <- function(x, ...) { | |
idx = if (!is.null(x$it)) x$it else x$ib | |
idx = rbind(idx, idx[1, ]) | |
nc = dim(idx)[2L] | |
idx = as.vector(idx) | |
mat = cbind(x$vb[1L, idx], x$vb[2L, idx]) | |
grp = rep(seq_len(nc), each = 4L) | |
lst = split.data.frame(mat, grp) | |
sf::st_sf( | |
average_z = tapply(x$vb[3L, idx], grp, mean, na.rm = TRUE) | |
, geometry = sf::st_sfc( | |
lapply( | |
lst | |
, function(i) sf::st_polygon(list(i)) | |
) | |
) | |
, ... | |
) | |
} | |
mesh_sf = st_as_sf(mesh, crs = 4326) | |
clr = makeColorMatrix(~average_z, mesh_sf, palette = "inferno") | |
leaflet() %>% | |
addProviderTiles("CartoDB.DarkMatter") %>% | |
addGlPolygons(mesh_sf, color = clr, popup = TRUE) %>% | |
setView(lng = 146.5, lat = -42.5, zoom = 7) |
Yip, it's much faster. I updated the original gist with a much faster version of st_as_sf.mesh3d
, Rcpp still eats it for breakfast!
library(microbenchmark)
microbenchmark(
sf = st_as_sf(mesh)
, md = mapdeck:::mesh_to_sf(mesh, c("vb", "it"))
, times = 10
)
Unit: milliseconds
expr min lq mean median uq max neval
sf 5517.50783 5825.09536 6232.2307 6232.57181 6524.7249 6998.7204 10
md 82.27326 94.87767 107.7158 99.13353 105.7012 166.2793 10
I'll be into this in a few days going riding 👍👍
Have fun!
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I had a go at implementing it in Rcpp in mapdeck a while ago. You could test
mapdeck:::mesh_to_sf()
?