This is a follow-up question to these ones:
- Performant 2D OpenGL graphics in R for fast display of raster image using qtpaint (qt) or rdyncall (SDL/OpenGL) packages?
- Most efficient way of drawing a heatmap from matrix with OpenGL?
I'd like to interactively see the output of spatial discrete simulations of cellular automata in 2D. So I am starting simple and trying to understand how fast I can go with drawing matrices of integer values. I am trying here with the rgl
package, that, to my knowledge, is the package providing the (theoretically) fastest(?) graphics device in R.
I am trying this approach with rgl
but the frame rate is 30 frames per sec which I find rather low (see code below). My example is drawing raster images from R matrices that are 100x100 only. Moreover, I am getting flickering, I don't know why.
Here's my approach (following an answer from @ben-bolker) and now using feedback from @user2554330.
library(viridisLite)
library(rgl)
n_colours <- 100
n_row <- 500
n_col <- 500
vv <- viridis(n_colours)
setup <- function() {
view3d(theta=0, phi=0) ## head-on view
#par3d(zoom=0.65, windowRect = c(0,0, n_col, n_row), viewport = c(0,0, n_col, n_row))
par3d(zoom=0.65, windowRect = c(0,0, n_col, n_row), viewport = c(0,0, n_col, n_row))
}
# draw <- function(m) {
# d <- dim(m)
# surface3d(x = 1:d[1], y = 1:d[2], z = matrix(0, d[1], d[2]),
# color = vv[m],
# smooth=FALSE, lit=FALSE ## turn off smoothing/lights
# )
# }
# draw2 <- function(m) {
# par3d(skipRedraw = TRUE) # but skip blank update
# clear3d()
#
# d <- dim(m)
# surface3d(x = 1:d[1], y = 1:d[2], z = matrix(0, d[1], d[2]),
# color = vv[m],
# smooth=FALSE, lit=FALSE ## turn off smoothing/lights
# )
# par3d(skipRedraw = FALSE) # Make sure image is shown
# }
draw3 <- function(colours) {
par3d(skipRedraw = TRUE) # but skip blank update
clear3d()
d <- dim(m)
surface3d(x = 1:d[1], y = 1:d[2], z = matrix(0, d[1], d[2]),
color = colours,
smooth=FALSE, lit=FALSE ## turn off smoothing/lights
)
par3d(skipRedraw = FALSE) # Make sure image is shown
}
nframes <- 100
n_matrices <- list()
for(i in 1:nframes) {
n_matrices[[i]] <- vv[matrix(sample(1:n_colours, n_row*n_col, replace = TRUE), nrow = n_row)]
}
setup()
# time <- system.time({
# for (i in 1:nframes) {
# draw(n_matrices[[i]])
# par3d(skipRedraw = FALSE) # Make sure image is shown
#
# par3d(skipRedraw = TRUE) # but skip blank update
# pop3d()
# }
# par3d(skipRedraw = FALSE)
# })
time <- system.time({
for (i in 1:nframes) {
draw3(n_matrices[[i]])
}
})
fps <- nframes/time[3]
fps