## ----include = FALSE----------------------------------------------------------
knitr::opts_chunk$set(
  collapse = TRUE,
  comment = "#>"
)

## ----setup--------------------------------------------------------------------
library(vaster)

## ----vaster-------------------------------------------------------------------
library(vaster)
set.seed(1)
x <- c(sort(runif(2, -20, 160)), sort(runif(2, -80, 10)))
names(x) <- c("xmin", "xmax", "ymin", "ymax")
print(x)
plot(matrix(x, ncol = 2))
grid()


## ----vaster1------------------------------------------------------------------
## all we need is a extent and dimension, we want to align to that grid
v <- vcrop(x,  c(120, 60), extent = c(-180, 180, -90, 90))
plot(NA, xlim = v$extent[1:2], ylim = v$extent[3:4], asp = "")
g_along <- function(x, n) seq(x[1], x[2], length.out = n + 1)
abline(v = v$extent[1:2], h = v$extent[3:4], lwd = 2)
abline(v = g_along(v$extent[1:2], v$dimension[1]), h = g_along(v$extent[3:4], v$dimension[2]), col = "grey")



## these points were used to crop the existing grid, they don't define its alignment
points(x[1:2], x[3:4], pch = "+")

## ----world--------------------------------------------------------------------
ex <- c(-180, 180, -90, 90)
dm <- c(40, 36)

plot_extent(ex, lwd = 5, border = "firebrick")
abline(v = x_corner(dm, ex), h = y_corner(dm, ex))

## ----points-------------------------------------------------------------------
plot_extent(ex)
points(x_centre(dm, ex), rep(y_centre(dm, ex)[1], length.out = dm[1]))

## ----cells--------------------------------------------------------------------
## how many cells?
cells <- seq_len(prod(dm))
plot_extent(ex)
points(xy_from_cell(dm, ex, cells))

## ----query--------------------------------------------------------------------
xy <- cbind(runif(50, -180, 180), runif(50, -90, 90))
cells <- cell_from_xy(dm, ex, xy)
plot_extent(ex)
points(xy_from_cell(dm, ex, cells), col = "red")
points(xy, pch = "+")

