| Title: | One Verb Set for Lattice Meshes: Rasters and Discrete Global Grids |
|---|---|
| Description: | Prototype for the mesh core (working name). A raster (GRID) and a discrete global grid (CELL) are both meshes whose vertex, edge and boundary tables are computed from cell ids, so no coincident vertices are ever merged. The same verbs work on both, and arrays join to either model through a keyed dimension (cell id). Vocabulary follows UGRID, xdggs, uxarray and OGC API DGGS; vertex and segment tables follow wkpool. |
| Authors: | Michael Sumner [aut, cre] |
| Maintainer: | Michael Sumner <[email protected]> |
| License: | MIT + file LICENSE |
| Version: | 0.0.0.9000 |
| Built: | 2026-11-07 22:32:37 UTC |
| Source: | https://github.com/hypertidy/meshcore |
'as_wk()' returns one polygon per cell (wk 'wk_polygon'), built from 'boundaries()' and 'vertices()'. 'as_wkpool()' hands the mesh to wkpool as a pool of the model's vertices and one closed path of segments per cell, with '.vx' renumbered 1..n (the lattice key is kept as '.key'). The pool is already merged: no 'merge_coincident()' needed.
as_wk(x) as_wkpool(x)as_wk(x) as_wkpool(x)
x |
A model. |
Four verbs that keep a mesh joined to the data it came from. None of them warps a raster: data are sampled in their own CRS at mesh vertices.
locate(mesh, x, y) sample_at_vertices( mesh, dsn, band = 1L, name = "value", method = c("bilinear", "simple") ) drape_uv(mesh, image, max_px = 0.25) pick(mesh, face, u, v, links = NULL, rows = NULL)locate(mesh, x, y) sample_at_vertices( mesh, dsn, band = 1L, name = "value", method = c("bilinear", "simple") ) drape_uv(mesh, image, max_px = 0.25) pick(mesh, face, u, v, links = NULL, rows = NULL)
mesh |
A triangle form ('meshcore_tri'), for example from [tri_mesh()]. Its CRS is read from the 'meshspec' attribute. |
x, y
|
Coordinates in the mesh CRS. |
dsn |
A raster any GDAL driver reads (via terra). |
band |
Band number. |
name |
Column name for the sampled values. |
method |
'"bilinear"' or '"simple"' (nearest cell). |
image |
A georeferenced image (via terra); only its grid is read. |
max_px |
Faces with 'uv_err_px' above this are counted in the message, to refine or flag. |
face |
Row of 'mesh$triangles'. |
u, v
|
Barycentric weights of the face's second and third vertex. |
links |
A link table with 'face' and 'point' columns, such as pointcore's 'face_points()'. |
rows |
A data frame that 'links$point' indexes, such as the points table of a pointcore form. |
* 'locate()': the triangle each point falls in (in x and y), with the barycentric weights ‘u' and 'v' of the triangle’s second and third vertex (the first has '1 - u - v'). 'NA' outside the mesh. * ‘sample_at_vertices()': transforms the vertices into a raster’s CRS and reads one band there, adding the values as a vertex column. The source, band and method are recorded in the 'sources' attribute. * 'drape_uv()': texture coordinates into a georeferenced image by inverse projection, as vertex columns 'u' and 'v' (u is 0 at xmin and 1 at xmax, v is 0 at row 0, the image's top, as the drawable form defines). Each triangle gets 'uv_err_px': the largest distance, in source pixels, between the exact image position and the linear blend of its vertices' uv, at the edge midpoints and the centroid. Large values mean the image's CRS bends across that triangle and the drape is wrong there. * 'pick()': one face and its weights in, everything joined to it out: the triangle's row, its three vertex rows, numeric vertex columns blended at the point, the column and row of every draped image, and (with a link table) the source rows that fall in the face.
'locate()': a data frame 'face', 'u', 'v', one row per point. 'sample_at_vertices()' and 'drape_uv()': the mesh with new columns. 'pick()': a list of class 'meshcore_pick'.
if (requireNamespace("cdtr", quietly = TRUE) && requireNamespace("geometry", quietly = TRUE)) { m <- tri_mesh(c(0, 1, 1, 0, 0.5), c(0, 0, 1, 1, 0.5), PA = cbind(z = c(0, 1, 2, 1, 4))) loc <- locate(m, 0.6, 0.4) pick(m, loc$face, loc$u, loc$v) }if (requireNamespace("cdtr", quietly = TRUE) && requireNamespace("geometry", quietly = TRUE)) { m <- tri_mesh(c(0, 1, 1, 0, 0.5), c(0, 0, 1, 1, 0.5), PA = cbind(z = c(0, 1, 2, 1, 4))) loc <- locate(m, 0.6, 0.4) pick(m, loc$face, loc$u, loc$v) }
'GRID()' is a regular raster: a lattice of 'ncol * nrow' square-ish cells over an extent. 'CELL()' is a set of cells of a discrete global grid (DGGS) or other cell lattice, identified by integer cell ids.
GRID(x = NULL, dim = NULL, extent = NULL, crs = NA_character_) CELL( x = NULL, grid_name = c("healpix", "hexlattice"), level = NULL, indexing_scheme = "nested", radius = 1, origin = c(0, 0), ncol = NULL, nrow = NULL, orientation = c("flat", "pointy"), crs = NA_character_ )GRID(x = NULL, dim = NULL, extent = NULL, crs = NA_character_) CELL( x = NULL, grid_name = c("healpix", "hexlattice"), level = NULL, indexing_scheme = "nested", radius = 1, origin = c(0, 0), ncol = NULL, nrow = NULL, orientation = c("flat", "pointy"), crs = NA_character_ )
x |
For 'GRID()', a raster data source readable by GDAL, or 'NULL' to give 'dim' and 'extent'. For 'CELL()', a vector of cell ids, a multidimensional data source (e.g. Zarr) holding a 'cell_ids' array with xdggs attributes, or 'NULL' for every cell at 'level'. |
dim |
'c(ncol, nrow)'. |
extent |
'c(xmin, xmax, ymin, ymax)'. |
crs |
Carried, not interpreted. |
grid_name |
'"healpix"' or '"hexlattice"' (a planar flat-topped hexagon lattice). |
level |
Refinement level (HEALPix 'nside = 2^level'). |
indexing_scheme |
Only '"nested"' for HEALPix. |
radius, origin, ncol, nrow
|
hexlattice parameters: hexagon circumradius, the coordinate of lattice cell (0, 0) centre, and the lattice size in columns and rows (cell id = row * ncol + col). |
orientation |
hexlattice '"flat"' topped, or '"pointy"' topped (the flat lattice with x and y exchanged, as sf::st_make_grid() makes by default; "columns" then run along y). |
Both are meshes whose tables (cells, vertices, edges, boundaries) are computed on demand from cell ids. Vertex identity is by construction: every vertex has an integer lattice key, so coincident vertices are never found by comparing coordinates. This is recorded as 'rung = "lattice"', a rung above "exact" on the vertex identity ladder (exact float, snapped, noded, exact predicates).
Cell ids are 0-based, as in GDAL pixel offsets, HEALPix and xdggs. GRID cell ids run row-major from the top-left cell (GDAL order).
A model object (a list with 'meta' and 'cell').
HEALPix nested id to face and within-face coordinates
hpx_nest2fxy(id, level) hpx_fxy2nest(face, ix, iy, level)hpx_nest2fxy(id, level) hpx_fxy2nest(face, ix, iy, level)
id |
Cell ids (0-based, nested). |
level |
Refinement level, 'nside = 2^level'. |
face, ix, iy
|
Base face (0..11) and within-face coordinates. |
'hpx_nest2fxy()' a list of 'face', 'ix', 'iy'; 'hpx_fxy2nest()' cell ids.
A keyed array is an array plus the name of the dimension(s) that index model cells. For a raster the key is computed from the 'x' and 'y' dimensions (cell id = row * ncol + col). For a DGGS the key is a coordinate variable of cell ids on the 'cells' dimension (the xdggs convention: 'cell_ids' with 'grid_name', 'level', 'indexing_scheme' attributes).
keyed_array(values, dims, key_dim, key = NULL, coords = list()) read_array(dsn, name = NULL) join_array(x, a, ...)keyed_array(values, dims, key_dim, key = NULL, coords = list()) read_array(dsn, name = NULL) join_array(x, a, ...)
values |
An R array, fastest-varying dimension first. |
dims |
Named dimension sizes, in the same order as 'dim(values)'. |
key_dim |
Name(s) of the keyed dimension(s). |
key |
Cell ids along 'key_dim', or 'NULL' when the key is computed. |
coords |
Named list of coordinate values for the other dimensions. |
dsn |
Data source. |
name |
Array name for multidimensional sources. |
x |
A model. |
a |
A keyed array. |
... |
Unused. |
'read_array()' reads a classic raster (e.g. GeoTIFF) or an array from a GDAL multidimensional source (e.g. Zarr) through GDAL, via sf.
‘join_array()' returns the model’s cells in long form, one row per cell and per combination of the array's other dimensions, with a 'value' column. The join is by cell id only: no geometry is involved.
For writing 'join_array()' methods in other packages.
long_join(cl, idx, m, a)long_join(cl, idx, m, a)
cl |
The model's 'cells()' table. |
idx |
For each row of ‘cl', the position along the array’s keyed dimension ('NA' for none). |
m |
The array values as a matrix: one row per position along the keyed dimension, one column per combination of the other dimensions. |
a |
The keyed array (for its other dimensions and coordinates). |
'cl' in long form with the other dimensions and 'value'.
'write_mesh_arrow()' writes each table of a form (and any link tables given in '...') to '<dir>/<table>.arrows', an Arrow IPC stream that any Arrow reader opens (R, Python, JS, DuckDB). 'read_mesh_arrow()' reads the folder back into the same R form.
write_mesh_arrow(x, dir, ..., refs = list()) read_mesh_arrow(dir)write_mesh_arrow(x, dir, ..., refs = list()) read_mesh_arrow(dir)
x |
A form: a named list of data frames with a 'meshspec' attribute, such as a 'meshcore_tri' or a pointcore 'pointcore_points'. |
dir |
Folder to write; created if needed. |
... |
Further named data frames to write beside the form, such as link tables ('face_points') or face summaries ('face_stats'). |
refs |
Named list adding to or overriding the reference columns: 'list(table = c(column = "target table"))'. |
Columns that hold row positions are 0-based on the wire and 1-based in R (spec Conventions), and each table says which they are: the metadata key 'meshspec:refs' holds JSON mapping each such column to the table it points at, for example '"v0":"vertices","v1":"vertices","v2":"vertices"'. A reader in another language needs nothing else to follow the links. Every table also carries 'meshspec:version', 'meshspec:form', 'meshspec:table' and 'crs'; the first table carries the rest of the form's metadata ('meshspec:meta') and its 'sources' record ('meshspec:sources') as JSON.
Factors are written as strings: nanoarrow does not yet write dictionary columns to IPC.
'write_mesh_arrow()': 'dir', invisibly. 'read_mesh_arrow()': a named list of data frames with the 'meshspec' (and 'sources') attributes, classed 'meshcore_tri' for a triangle form.
Counts of cells, vertices and edges
mesh_counts(x)mesh_counts(x)
x |
A model. |
'mesh_viewer()' copies meshview (a self-contained page using three.js and Arrow JS, both bundled) into 'dir', beside the 'mesh/' and 'points/' folders written by 'write_mesh_arrow()'. Hovering the surface picks a face on the GPU and lists its 'face_stats' row, its vertices and the returns 'face_points' links to it, each with its source file and position in that file.
mesh_viewer(dir, open = interactive())mesh_viewer(dir, open = interactive())
dir |
A folder holding 'mesh/' (and optionally 'points/'). |
open |
Open the page with [utils::browseURL()]. |
Browsers do not let a page read files beside it from 'file://', so either serve 'dir' (for example 'python3 -m http.server' in it, then open 'http://localhost:8000') or open 'index.html' and choose the '.arrows' files when it asks.
The path to 'index.html', invisibly.
Number of cells in a model
n_cells(x)n_cells(x)
x |
A model. |
'as_mesh3d()' (rgl) and 'as_ray_mesh()' (rayvertex, and rayrender through it) turn a triangle form into each renderer's mesh. Both subtract a float64 'local_origin' first, because renderers work in float32: a UTM northing near 5,250,000 m has a float32 spacing of 0.5 m, and a site centred on the origin has a spacing well under a millimetre. The origin and every change of frame are recorded in the 'frame' attribute, so a pick can be taken back to map coordinates.
as_mesh3d( mesh, z = "z", texture = NULL, local_origin = NULL, exaggeration = 1, ... ) as_ray_mesh( mesh, z = "z", texture = NULL, local_origin = NULL, exaggeration = 1, material = NULL ) pick_render( mesh, gbuffer, col, row, ray_mesh, lookfrom, lookat = c(0, 0, 0), camera_up = c(0, 1, 0), links = NULL, rows = NULL )as_mesh3d( mesh, z = "z", texture = NULL, local_origin = NULL, exaggeration = 1, ... ) as_ray_mesh( mesh, z = "z", texture = NULL, local_origin = NULL, exaggeration = 1, material = NULL ) pick_render( mesh, gbuffer, col, row, ray_mesh, lookfrom, lookat = c(0, 0, 0), camera_up = c(0, 1, 0), links = NULL, rows = NULL )
mesh |
A triangle form with a height column. |
z |
Name of the vertex column used for height. |
texture |
Path to a PNG or JPEG holding the same pixels as the image given to [drape_uv()], or 'NULL'. |
local_origin |
Numeric length 3 subtracted from x, y and z, or 'NULL' for the centre of the x, y extent and a z of 0. |
exaggeration |
Vertical scale, recorded rather than baked into the coordinates' meaning. |
... |
Passed to [rgl::tmesh3d()] as material. |
material |
For 'as_ray_mesh()', a [rayvertex::material_list()]; one with the texture is made when 'NULL'. |
gbuffer |
The list returned by 'rayvertex::rasterize_scene(..., debug = "all")'. |
col, row
|
A pixel of the render, 1-based from the top left of the image as displayed. |
ray_mesh |
The 'as_ray_mesh()' result that was rendered. |
lookfrom, lookat, camera_up
|
The camera given to 'rasterize_scene()'; its position buffer is in view space. |
links, rows
|
Passed to [pick()]. |
Faces keep the row order of 'mesh$triangles' in both renderers, so a face index from any pick is a triangle row.
'pick_render()' picks from a rayvertex render with no renderer change: it reads the view-space position of a pixel from 'rasterize_scene(debug = "all")', undoes the camera and the frame, and [locate()]s the point in the mesh. It returns the same as [pick()].
'as_mesh3d()': an rgl 'mesh3d'. 'as_ray_mesh()': a rayvertex 'ray_mesh'. 'pick_render()': a 'meshcore_pick', or 'NULL' for a background pixel.
'tri_form()' normalises the output of a triangulation engine to the triangle form of mesh spec v0.1, so neither engine has to change before meshcore can use it. 'tri_mesh()' runs an engine and returns the form in one call.
tri_form(x, erase = NULL, crs = NA_character_) tri_mesh( x, y, s0 = NULL, s1 = NULL, PA = NULL, engine = c("cdtr", "laridae"), max_area = NULL, min_angle = NULL, erase = c("outer", "holes", "hull"), crs = NA_character_, ... )tri_form(x, erase = NULL, crs = NA_character_) tri_mesh( x, y, s0 = NULL, s1 = NULL, PA = NULL, engine = c("cdtr", "laridae"), max_area = NULL, min_angle = NULL, erase = c("outer", "holes", "hull"), crs = NA_character_, ... )
x |
For 'tri_form()', the result of [cdtr::cdt_triangulate()] (or [cdtr::cdt_triangulate_attr()]), of [laridae::lari_triangulate()] or [laridae::lari_tables()], or a laridae mesh handle. For 'tri_mesh()', vertex x coordinates. |
erase |
The erase choice the engine was asked for ("outer", "holes" or "hull"). Taken from the engine output when it records it (laridae); cdtr does not, so give it here, or it is recorded as 'NA'. For a laridae mesh handle, the triangles to return. |
crs |
Carried in the 'meshspec' attribute, not interpreted. |
y |
Vertex y coordinates. |
s0, s1
|
1-based indices into 'x', 'y' of constraint segment ends, or 'NULL'. |
PA |
Optional numeric matrix of per-vertex attributes (one row per input vertex, named columns), interpolated onto new vertices. |
engine |
'"cdtr"' (the default) or '"laridae"'. laridae gives the constraint-to-input map, and refines where the domain is the convex hull. |
max_area, min_angle
|
Refinement targets, or 'NULL' for none. |
... |
Passed to the engine. |
The form is a named list of four data frames:
* 'vertices': 'x', 'y', any attribute columns, 'origin' (a factor with the spec dictionary 'input', 'crossing', 'steiner', 'grid', 'lattice') and, when the engine has stable ids, 'id'. Input vertices come first, in input order (after duplicates are merged). * 'triangles': 'v0', 'v1', 'v2' (1-based rows of 'vertices', wound counter-clockwise in xy), 'depth' (constraint crossings from outside, counting a doubled boundary once per copy) and, when available, 'depth_distinct' (a doubled boundary counted once). * 'constraints': 'v0', 'v1' (1-based rows of 'vertices', 'v0 < v1'), the mesh edges lying on input segments, and, when the engine provides them, 'segment' (the lowest input segment covering the edge) and 'count' (how many input segments cover it). laridae calls this table 'segments' and cdtr calls it 'S'; 'tri_form()' renames both to the spec name (Decision 7). * 'edge_sources' (mesh spec v0.2, when the engine gives it, as 'cdtr::cdt_triangulate(edge_sources = TRUE)' does): one row per constraint edge and covering input segment, 'edge' (row of 'constraints'), 'segment' (the input segment, as given to the engine) and 'forward' (TRUE when the segment runs from 'v0' to 'v1' of its 'constraints' row), sorted by 'edge' then 'segment'. 'tri_form()' remaps 'edge' when it sorts 'constraints' and flips 'forward' where it swaps an edge's ends, and derives 'constraints$segment' and 'constraints$count' from it. The form is then written as spec version 0.2. * 'report': one row recording 'backend', 'package' (engine version), 'erase', 'refined', 'min_edge_length' and the row counts.
Row references are 1-based, as the spec requires in R; they become 0-based only when the form is written to Arrow. The list carries attributes 'meshspec' ('version', 'form', 'crs'), 'input_map' (the vertex row of each input point, so features can be followed into the mesh) and ‘unrefined' (the engine’s own refinement report, unchanged).
A list of class 'meshcore_tri' with 'vertices', 'triangles', 'constraints', 'report' and, when the engine gives it, 'edge_sources'.
if (requireNamespace("cdtr", quietly = TRUE)) { ## a square with a square hole x <- c(0, 1, 1, 0, 0.25, 0.75, 0.75, 0.25) y <- c(0, 0, 1, 1, 0.25, 0.25, 0.75, 0.75) s0 <- 1:8; s1 <- c(2, 3, 4, 1, 6, 7, 8, 5) m <- tri_mesh(x, y, s0, s1, erase = "holes", max_area = 0.01) m ## the same from an engine result tri_form(cdtr::cdt_triangulate(x, y, s0, s1, erase = "holes"), erase = "holes") ## which input segments cover each constraint edge (spec v0.2) head(m$edge_sources) }if (requireNamespace("cdtr", quietly = TRUE)) { ## a square with a square hole x <- c(0, 1, 1, 0, 0.25, 0.75, 0.75, 0.25) y <- c(0, 0, 1, 1, 0.25, 0.25, 0.75, 0.75) s0 <- 1:8; s1 <- c(2, 3, 4, 1, 6, 7, 8, 5) m <- tri_mesh(x, y, s0, s1, erase = "holes", max_area = 0.01) m ## the same from an engine result tri_form(cdtr::cdt_triangulate(x, y, s0, s1, erase = "holes"), erase = "holes") ## which input segments cover each constraint edge (spec v0.2) head(m$edge_sources) }
The same calls work on every model.
cells(x, ...) boundaries(x, ...) vertices(x, ...) face_edge(x, ...) edges(x, ...) neighbours(x, type = c("edge", "vertex"), ...) parent(x, n = 1, ...) children(x, n = 1, ...)cells(x, ...) boundaries(x, ...) vertices(x, ...) face_edge(x, ...) edges(x, ...) neighbours(x, type = c("edge", "vertex"), ...) parent(x, n = 1, ...) children(x, n = 1, ...)
x |
A model from [GRID()] or [CELL()]. |
... |
Unused. |
type |
'"edge"' or '"vertex"' adjacency. |
n |
Number of levels to move. |
* 'cells()': one row per cell: '.cell' id and centre 'x', 'y' (longitude and latitude for HEALPix). xdggs 'cell_centers'; OGC API DGGS zones. * 'boundaries()': one row per cell corner, counter-clockwise: '.cell', '.corner', '.vx'. UGRID 'face_node_connectivity' in long form. * 'vertices()': one row per unique vertex: '.vx' (its lattice key), 'x', ‘y'. UGRID nodes; wkpool’s vertex pool. * 'edges()': one row per unique undirected edge: '.edge', '.vx0', '.vx1'. UGRID 'edge_node_connectivity'; wkpool segments. * 'face_edge()': one row per cell side: '.cell', '.corner', '.edge'. UGRID 'face_edge_connectivity'. * 'neighbours()': pairs of cells sharing an edge ('type = "edge"') or a vertex ('type = "vertex"'). UGRID 'face_face_connectivity'. * 'parent()', 'children()': the hierarchy. OGC API DGGS parent zones and sub-zones; xdggs 'zoom_to'.
'vertices()', 'edges()', 'face_edge()' and 'neighbours()' are derived from 'boundaries()' by integer keys alone, so they are the same code for every model. Only 'cells()' and 'boundaries()' (and the hierarchy) are written per model.
'write_scene()' writes the drawable form of a triangle mesh (spec Form 3) and a scene that draws it, so any scenespec 0.7 renderer opens the folder as it stands: 'scene.json' beside 'mesh_vertices.arrows', 'mesh_indices.arrows' and, when 'faces' is given, 'mesh_faces.arrows'.
write_scene( mesh, dir, faces = NULL, z = "z", local_origin = NULL, fill_by = NULL, palette = "terrain", range = NULL, fill = c(180, 170, 150, 255), stroke = NULL, z_scale = 1, popup = NULL, label = "mesh" )write_scene( mesh, dir, faces = NULL, z = "z", local_origin = NULL, fill_by = NULL, palette = "terrain", range = NULL, fill = c(180, 170, 150, 255), stroke = NULL, z_scale = 1, popup = NULL, label = "mesh" )
mesh |
A triangle form ('meshcore_tri') with a CRS. |
dir |
Folder to write; created if needed. |
faces |
'NULL', or a data frame of face values: one row per triangle, or a 'face' column of 1-based triangle rows. |
z |
Name of the vertex column used for height, or 'NULL' for a flat mesh. |
local_origin |
Numeric length 2 subtracted from x and y, or 'NULL' for the centre of the x, y extent. |
fill_by |
Name of a face column (looked up first) or vertex column to colour by, or 'NULL' for one fill colour. |
palette, range
|
Palette name and value range for 'fill_by'; the range defaults to that of the column. |
fill |
RGBA (0 to 255) used when 'fill_by' is 'NULL'. |
stroke |
RGBA for triangle edges, or 'NULL' for none. |
z_scale |
Vertical exaggeration recorded in the scene. |
popup |
Face columns shown for a picked triangle; defaults to every face column when 'faces' is given. |
label |
Layer label. |
Positions are float32 with the float64 'local_origin' (x and y) subtracted, as the scene's 'view.local_origin' records, so a UTM site keeps sub-millimetre spacing. Height is not shifted. Every other numeric vertex column is written beside 'position' as a value a layer can colour by. Indices are 0-based uint32, three per triangle, in the row order of 'mesh$triangles'. The face table has one row per triangle in that order: a table with a ‘face' column (such as pointcore’s 'face_stats()') is matched on it, with 'NA' for faces it does not list.
The view CRS is the mesh's CRS as an 'AUTHORITY:CODE' string; a CRS given another way is looked up with sf when it has an EPSG code.
The path to 'scene.json', invisibly.