Giter VIP home page Giter VIP logo

pydelatin's Introduction

pydelatin

A Python wrapper of hmm (of which Delatin is a port) for fast terrain mesh generation.

A screenshot of Glacier National Park taken from the demo. The mesh is created using pydelatin, encoded using quantized-mesh-encoder, served on-demand using dem-tiler, and rendered with deck.gl.

Install

With pip:

pip install pydelatin

or with Conda:

conda install -c conda-forge pydelatin

On Windows, installing via Conda is strongly recommended.

If installing with pip on Windows, glm is a prerequisite for building from source. Open an issue if you'd like to help package binary wheels for Windows.

Using

Example

from pydelatin import Delatin

tin = Delatin(terrain, width, height)
# Mesh vertices
tin.vertices
# Mesh triangles
tin.triangles

API

The API is similar to that of hmm.

Additionally I include a helper function: decode_ele, to decode a Mapbox Terrain RGB or Terrarium PNG array to elevations.

Delatin

Arguments
  • arr (numpy ndarray): data array. If a 2D array, dimensions are expected to be (height, width). If a 1D array, height and width parameters must be passed, and the array is assumed to be in C order.
  • height (int, default: None): height of array; required when arr is not 2D
  • width (int, default: None): width of array; required when arr is not 2D
  • z_scale (float, default: 1): z scale relative to x & y
  • z_exag (float, default: 1): z exaggeration
  • max_error (float, default: 0.001): maximum triangulation error
  • max_triangles (int, default: None): maximum number of triangles
  • max_points (int, default: None): maximum number of vertices
  • base_height (float, default: 0): solid base height
  • level (bool, default: False): auto level input to full grayscale range
  • invert (bool, default: False): invert heightmap
  • blur (int, default: 0): gaussian blur sigma
  • gamma (float, default: 0): gamma curve exponent
  • border_size (int, default: 0): border size in pixels
  • border_height (float, default: 1): border z height
Attributes
  • vertices (ndarray of shape (-1, 3)): the interleaved 3D coordinates of each vertex, e.g. [[x0, y0, z0], [x1, y1, z1], ...].
  • triangles (ndarray of shape (-1, 3)): represents indices within the vertices array. So [0, 1, 3, ...] would use the first, second, and fourth vertices within the vertices array as a single triangle.
  • error (float): the maximum error of the mesh.

util.rescale_positions

A helper function to rescale the vertices output to a new bounding box. Returns an ndarray of shape (-1, 3) with positions rescaled. Each row represents a single 3D point.

Arguments
  • vertices: (np.ndarray) vertices output from Delatin
  • bounds: (Tuple[float]) linearly rescale position values to this extent. Expected to be [minx, miny, maxx, maxy].
  • flip_y: (bool, default False) Flip y coordinates. Can be useful since images' coordinate origin is in the top left.

Saving to mesh formats

Quantized Mesh

A common mesh format for the web is the Quantized Mesh format, which is supported in Cesium and deck.gl (via loaders.gl). You can use quantized-mesh-encoder to save in this format:

import quantized_mesh_encoder
from pydelatin import Delatin
from pydelatin.util import rescale_positions

tin = Delatin(terrain, max_error=30)
vertices, triangles = tin.vertices, tin.triangles

# Rescale vertices linearly from pixel units to world coordinates
rescaled_vertices = rescale_positions(vertices, bounds)

with open('output.terrain', 'wb') as f:
    quantized_mesh_encoder.encode(f, rescaled_vertices, triangles)

Meshio

Alternatively, you can save to a variety of mesh formats using meshio:

from pydelatin import Delatin
import meshio

tin = Delatin(terrain, max_error=30)
vertices, triangles = tin.vertices, tin.triangles

cells = [("triangle", triangles)]
mesh = meshio.Mesh(vertices, cells)
# Example output format
# Refer to meshio documentation
mesh.write('foo.vtk')

Martini or Delatin?

Two popular algorithms for terrain mesh generation are the "Martini" algorithm, found in the JavaScript martini library and the Python pymartini library, and the "Delatin" algorithm, found in the C++ hmm library, this Python pydelatin library, and the JavaScript delatin library.

Which to use?

For most purposes, use pydelatin over pymartini. A good breakdown from a Martini issue:

Martini:

  • Only works on square 2^n+1 x 2^n+1 grids.
  • Generates a hierarchy of meshes (pick arbitrary detail after a single run)
  • Optimized for meshing speed rather than quality.

Delatin:

  • Works on arbitrary raster grids.
  • Generates a single mesh for a particular detail.
  • Optimized for quality (as few triangles as possible for a given error).

Benchmark

The following uses the same dataset as the pymartini benchmarks, a 512x512 pixel heightmap of Mt. Fuji.

For the 30-meter mesh, pydelatin is 25% slower than pymartini, but the mesh is much more efficient: it has 40% fewer vertices and triangles.

pydelatin is 4-5x faster than the JavaScript delatin package.

Python

git clone https://github.com/kylebarron/pydelatin
cd pydelatin
pip install '.[test]'
python bench.py
mesh (max_error=30m): 27.322ms
vertices: 5668, triangles: 11140

mesh (max_error=1m): 282.946ms
mesh (max_error=2m): 215.839ms
mesh (max_error=3m): 163.424ms
mesh (max_error=4m): 127.203ms
mesh (max_error=5m): 106.596ms
mesh (max_error=6m): 91.868ms
mesh (max_error=7m): 82.572ms
mesh (max_error=8m): 74.335ms
mesh (max_error=9m): 65.893ms
mesh (max_error=10m): 60.999ms
mesh (max_error=11m): 55.213ms
mesh (max_error=12m): 54.475ms
mesh (max_error=13m): 48.662ms
mesh (max_error=14m): 47.029ms
mesh (max_error=15m): 44.517ms
mesh (max_error=16m): 42.059ms
mesh (max_error=17m): 39.699ms
mesh (max_error=18m): 37.657ms
mesh (max_error=19m): 36.333ms
mesh (max_error=20m): 34.131ms

JS (Node)

This benchmarks against the delatin JavaScript module.

git clone https://github.com/kylebarron/pydelatin
cd test/bench_js/
yarn
wget https://raw.githubusercontent.com/mapbox/delatin/master/index.js
node -r esm bench.js
mesh (max_error=30m): 143.038ms
vertices: 5668
triangles: 11140

mesh (max_error=0m): 1169.226ms
mesh (max_error=1m): 917.290ms
mesh (max_error=2m): 629.776ms
mesh (max_error=3m): 476.958ms
mesh (max_error=4m): 352.907ms
mesh (max_error=5m): 290.946ms
mesh (max_error=6m): 240.556ms
mesh (max_error=7m): 234.181ms
mesh (max_error=8m): 188.273ms
mesh (max_error=9m): 162.743ms
mesh (max_error=10m): 145.734ms
mesh (max_error=11m): 130.119ms
mesh (max_error=12m): 119.865ms
mesh (max_error=13m): 114.645ms
mesh (max_error=14m): 101.390ms
mesh (max_error=15m): 100.065ms
mesh (max_error=16m): 96.247ms
mesh (max_error=17m): 89.508ms
mesh (max_error=18m): 85.754ms
mesh (max_error=19m): 79.838ms
mesh (max_error=20m): 75.607ms

License

This package wraps @fogleman's hmm, a C++ library that is also MIT-licensed.

pydelatin's People

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar

pydelatin's Issues

Example of generating a quantized mesh from DEM tile

Hey @kylebarron!

I'm exploring stacks to generate a quantized mesh from a DEM and I would like to try your library pydelatin & quantized-mesh-encoder. I would like to know if you could provide a small example of converting the DEM tile (opened with RasterIO) into a quantized mesh. Would be that possible?
I can convert the DEM into a NumPy array using the RasterIO, but I can't understand well the next steps to prepare that array to feed pydelatin.

Thanks!

BTW, great work you have done with your tools and contributions to the COG ecosystem ๐Ÿ˜ƒ

A humble feature request: Insertion of extra points

Thank you for an excellent library!

I have a use case where I would like to add elevation points at specific locations. For example, after having run the simplifier, I would like to insert some extra points (that I select) from the heightmap into the triangulation to have maximum accuracy (ie full resolution) there.

I have had a look at the code (src/triangulator.cpp) but cannot quite find out how to proceed. It seems the triangulation process (in Triangulator::Step()) is triangle-driven, ie it starts with a candidate triangle (the one having the maximum vertical error to a vertex), finds the candidate point for that triangle, inserts it and re-triangulates.

Do you know of a way to start with a point instead? I have thought of somehow marking the triangle containing each extra points with a very high dummy error value, and then proceed from there, but it seems I would then need to find the enclosing triangles for all of those extra points. Is there a simpler way?

It might be sufficient for my use case to use a bounding box to define the extra points, and then the error calculation / candidate finding process could perhaps be overridden with an extra criterion, for example: If a given point is inside that bounding box, then don't calculate the vertex-to-plane distance, instead just set it to some max value - and/or add the point directly to the candidate queue. Do you see other options?

With a little bit of input on how to approach this I could likely implement the solution myself and post it here as a PR.

docs about using meshio

looks as easy as

import meshio

tin = Delatin(terrain, max_error=30)
vertices, triangles = tin.vertices, tin.triangles

cells = [("triangle", triangles)]
mesh = meshio.Mesh(vertices, cells)
mesh.write('foo.vtk')

conda-forge package

I'm trying to make a conda-forge package (again ๐Ÿ˜„) in conda-forge/staged-recipes#12914.
It looks like you vendor hmm, and don't include the source files in the PyPI package. I guess for conda-forge we would first have to package hmm and have it as a dependency of pydelatin.
What do you think?

Inserting a find_location() function

I have the following function that could be inserted into triangulator.cpp and *.h but I am having difficulties updating these files in order to extend your bindings to include this possibility. I was wondering if you could help me achieve this.

Here are the functions,

// Private Function to check if a point is inside a triangle using barycentric coordinates by M.Llobera
bool PointInTriangle(const glm::ivec2 p, const glm::ivec2 a, const glm::ivec2 b, const glm::ivec2 c) const {
    auto sign = [](const glm::ivec2 p1, const glm::ivec2 p2, const glm::ivec2 p3) {
        return (p1.x - p3.x) * (p2.y - p3.y) - (p2.x - p3.x) * (p1.y - p3.y);
    };

    bool d1 = sign(p, a, b) < 0.0f;
    bool d2 = sign(p, b, c) < 0.0f;
    bool d3 = sign(p, c, a) < 0.0f;

    return ((d1 == d2) && (d2 == d3));
}

// Public  function to triangle contianing point pt by M.Llobera

int locatePoint(const glm::ivec2 pt) const {
    for (int i = 0; i < m_Queue.size(); ++i) {
        const int t = m_Queue[i];
        const int e0 = t * 3;
        const int e1 = e0 + 1;
        const int e2 = e0 + 2;

        const int p0 = m_Triangles[e0];
        const int p1 = m_Triangles[e1];
        const int p2 = m_Triangles[e2];

        const glm::ivec2 a = m_Points[p0];
        const glm::ivec2 b = m_Points[p1];
        const glm::ivec2 c = m_Points[p2];

        if (PointInTriangle(pt, a, b, c)) {
            return t;
        }
    }
    return -1;  // Point is not inside any triangle
}

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.