• Stars
    star
    502
  • Rank 87,851 (Top 2 %)
  • Language
    C
  • License
    MIT License
  • Created about 1 year ago
  • Updated about 1 year ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Geometry library for C - Fast point-in-polygon

TG

TG is a geometry library for C that is small, fast, and easy to use. I designed it for programs that need real-time geospatial, such as geofencing, monitoring, and streaming analysis.

Features

  • Implements OGC Simple Features including Point, LineString, Polygon, MultiPoint, MultiLineString, MultiPolygon, GeometryCollection.
  • Optimized polygon indexing that introduces two new structures.
  • Reads and writes WKT, WKB, and GeoJSON.
  • Provides a purely functional API that is reentrant and thread-safe.
  • Spatial predicates including "intersects", "covers", "touches", "equals", etc.
  • Test suite with 100% coverage using sanitizers and Valgrind.
  • Self-contained library that is encapsulated in the single tg.c source file.
  • Pretty darn good performance. ๐Ÿš€ [benchmarks]

Goals

The main goal of TG is to provide the fastest, most memory efficent geometry library for the purpose of monitoring spatial relationships, specifically operations like point-in-polygon and geometry intersect.

It's a non-goal for TG to be a full GIS library. Consider GEOS if you need GIS algorithms like generating a convex hull or voronoi diagram.

Performance

TG uses entirely new indexing structures that speed up geometry predicates. It can index more than 10GB per second of point data on modern hardware, while using less than 7% of additional memory, and can perform over 10 million point-in-polygon operations per second, even when using large polygons with over 10K points.

The following benchmark provides an example of the point-in-polygon performance of TG when using a large polygon. In this case of Brazil, which has 39K points.

Brazil              ops/sec    ns/op  points  hits       built      bytes
tg/none              96,944    10315   39914  3257    46.73 ยตs    638,720
tg/natural       10,143,419       99   39914  3257    53.17 ยตs    681,360
tg/ystripes      15,174,761       66   39914  3257   884.06 ยตs  1,059,548
geos/none            29,708    33661   39914  3257   135.18 ยตs    958,104
geos/prepared     7,885,512      127   39914  3257  2059.94 ยตs  3,055,496
  • "built": Column showing how much time the polygon and index took to construct.
  • "bytes": Column showing the final in-memory size of the polygon and index.
  • "none": No indexing was used.
  • "natural": Using TG Natural indexing
  • "ystripes": Using TG YStripes indexing
  • "prepared": Using a GEOS PreparedGeometry

See all benchmarks for more information.

Using

Just drop the "tg.c" and "tg.h" files into your project. Uses standard C11 so most modern C compilers should work.

$ cc -c tg.c

Programmer notes

Check out the complete API for detailed information.

Pure functions

TG library functions are thread-safe, reentrant, and (mostly) without side effects. The exception being with the use of malloc by some functions like geometry constructors. In those cases, it's the programmer's responsibiilty to check the return value before continuing.

struct tg_geom *geom = tg_geom_new_point(-112, 33);
if (!geom) {
    // System is out of memory.
}

Fast cloning

The cloning of geometries, as with tg_geom_clone(), are O(1) operations that use implicit sharing through an atomic reference counter. Geometry constructors like tg_geom_new_polygon() will use this method under the hood to maintain references of its inputs.

While this may only be an implementation detail, it's important for the programmer to understand how TG uses memory and object references.

For example:

struct tg_geom *geom = tg_geom_new_polygon(exterior, holes, nholes);

Above, a new geometry "geom" was created and includes a cloned reference to the tg_ring "exterior" and all of the holes.

Providing TG_NOATOMICS to the compiler will disable the use of atomics and instead use non-atomic reference counters.

cc -DTG_NOATOMICS tg.c ...

Alternatively, the tg_geom_copy() method is available to perform a deep copy of the geometry.

Avoid memory leaks

To avoid memory leaks, call tg_geom_free() on geometries created from geometry constructors, geometry parsers, tg_geom_clone(), and tg_geom_copy()

In other words, for every tg_geom_new_*(), tg_geom_parse_*(), tg_geom_clone(), and tg_geom_copy() there should be (eventually and exactly) one tg_geom_free().

Upcasting

The TG object types tg_line, tg_ring, and tg_poly can be safely upcasted to a tg_geom with no cost at runtime.

struct tg_geom *geom1 = (struct tg_geom*)line; // Cast tg_line to tg_geom
struct tg_geom *geom2 = (struct tg_geom*)ring; // Cast tg_ring to tg_geom
struct tg_geom *geom3 = (struct tg_geom*)poly; // Cast tg_poly to tg_geom

This allows for exposing all tg_geom functions to the other object types.

In addition, the tg_ring type can also cast to a tg_poly.

struct tg_poly *poly = (struct tg_poly*)ring; // Cast tg_ring to tg_poly

Do not downcast. It's not generally safe to cast from a tg_geom to other types.

Example

Create a program that tests if two geometries intersect using WKT as inputs.

#include <stdio.h>
#include <tg.h>

int main(int argc, char **argv) {
    if (argc != 3) {
        fprintf(stderr, "Usage: %s <geom-a> <geom-b>\n", argv[0]);
        return 1;
    }

    // Parse the input geometries and check for errors.
    struct tg_geom *a = tg_parse_wkt(argv[1]);
    if (tg_geom_error(a)) {
        fprintf(stderr, "%s\n", tg_geom_error(a));
        return 1;
    }
    struct tg_geom *b = tg_parse_wkt(argv[2]);
    if (tg_geom_error(b)) {
        fprintf(stderr, "%s\n", tg_geom_error(b));
        return 1;
    }

    // Execute the "intersects" predicate to test if both geometries intersect.
    if (tg_geom_intersects(a, b)) {
        printf("yes\n");
    } else {
        printf("no\n");
    }

    // Free geometries when done.
    tg_geom_free(a);
    tg_geom_free(b);
    return 0;
}

Build and run the example:

$ cc -I. examples/intersects.c tg.c
$ ./a.out 'POINT(15 15)' 'POLYGON((10 10,20 10,20 20,10 20,10 10))'

License

TG source code is available under the MIT License.

More Repositories

1

gjson

Get JSON values quickly - JSON parser for Go
Go
12,768
star
2

tile38

Real-time Geospatial and Geofencing
Go
8,655
star
3

evio

Fast event-loop networking for Go
Go
5,747
star
4

buntdb

BuntDB is an embeddable, in-memory key/value database for Go with custom indexing and geospatial support
Go
4,196
star
5

redcon

Redis compatible server framework for Go
Go
2,005
star
6

sjson

Set JSON values very quickly in Go
Go
1,978
star
7

SwiftWebSocket

Fast Websockets in Swift for iOS and OSX
Swift
1,532
star
8

summitdb

In-memory NoSQL database with ACID transactions, Raft consensus, and Redis API
Go
1,394
star
9

jj

JSON Stream Editor (command line utility)
Go
1,293
star
10

btree

B-tree implementation for Go
Go
937
star
11

hashmap.c

Hash map implementation in C.
C
631
star
12

uhaha

High Availability Raft Framework for Go
Go
579
star
13

pinhole

3D Wireframe Drawing Library for Go
Go
554
star
14

finn

Fast Raft framework using the Redis protocol for Go
Go
541
star
15

wal

Write ahead log for Go.
Go
525
star
16

Safe

Modern Concurrency and Synchronization for Swift.
Swift
417
star
17

pretty

Efficient JSON beautifier and compactor for Go
Go
354
star
18

chanx

A simple interface wrapper around a Go channel.
Go
321
star
19

rtree

An R-tree implementation for Go
Go
285
star
20

btree.c

B-tree implementation in C
C
246
star
21

GoSwift

Go Goodies for Swift. Including goroutines, channels, defer, and panic.
Swift
234
star
22

shardmap

A simple and efficient thread-safe sharded hashmap for Go
Go
211
star
23

hashmap

A simple and efficient hashmap package for Go. Open addressing, robin hood hashing, and xxh3 algorithm. Supports generics.
Go
203
star
24

celltree

A fast in-memory prefix tree that uses uint64 for keys and allows for duplicate entries.
Go
201
star
25

gjson.rs

Get JSON values quickly - JSON parser for Rust
Rust
195
star
26

cities

10,000 Cities with Latitude, Longitude, and Elevation in Go
Go
161
star
27

tinylru

A fast little LRU cache for Go
Go
144
star
28

Avios

Realtime H264 decoding library for iOS.
Swift
129
star
29

jd

Interactive JSON Editor
Go
128
star
30

pinhole-js

3D Wireframe Drawing Library for HTML Canvas
JavaScript
119
star
31

mmap

Load file-backed memory
Go
117
star
32

geojson

GeoJSON for Go. Used by Tile38
Go
116
star
33

doppio

Doppio is a fast LRU cache on top of Ristretto, Redcon, and Evio. Support for the Redis protocol.
Go
115
star
34

rtree.rs

A fast R-tree for Rust
Rust
112
star
35

match

Simple string pattern matcher for Go
Go
97
star
36

rtree.c

An R-tree implementation in C
C
96
star
37

tinybtree

Just an itsy bitsy b-tree in Go
Go
94
star
38

jsonc

Parse json with comments and trailing commas.
Go
79
star
39

rhh

A simple and efficient hashmap package for Go. Uses open addressing, Robin Hood hashing, and xxhash algorithm.
Go
79
star
40

kvnode

key value server. redis api, leveldb storage, raft support
Go
79
star
41

raft-fastlog

Raft in-memory backend implementation with persistence
Go
78
star
42

resp

Reader, Writer, and Server implementation for the Redis RESP Protocol.
Go
78
star
43

modern-server

Basic web server framework with HTTP/2 and Let's Encrypt.
Go
76
star
44

limiter

A goroutine limiter for Go
Go
76
star
45

redraft

Redis + Raft server implementation
Go
75
star
46

redcon.rs

Redis compatible server framework for Rust
Rust
72
star
47

rocksdb-server

Fast Redis clone written in C using RocksDB as a backend.
C++
72
star
48

lotsa

Simple Go library for executing lots of operations spread over any number of threads
Go
71
star
49

box

Efficiently box values in Go. Optimized for primitives, strings, and byte slices.
Go
69
star
50

evio-lite

Fast event-loop networking for Go (the lite version)
Go
68
star
51

transform

Using io.Reader for data transformation in Go
Go
67
star
52

uspto-trademark

How to file a USPTO trademark without an attorney for $225
66
star
53

pjson

A JSON stream parser for Go
Go
66
star
54

geodesic

Go package for performing accurate measurements of Earth. Includes the geodesic routines from GeographicLib.
Go
59
star
55

expr

Expression evaluator for Go
Go
58
star
56

json.c

Fast JSON parser for C
C
56
star
57

spinlock

A spinlock implementation for Go.
Go
56
star
58

raft-wal

Write ahead Raft log for Go
Go
55
star
59

rtred

RTree implementation for Go
Go
53
star
60

bfile

A buffer pool file I/O library for Go
Go
53
star
61

mvt

Draw Mapbox Vector Tiles (MVT) in Go
Go
52
star
62

redcon.c

Redis compatible server framework for C
C
47
star
63

cache-server

A minimal key/value server written in Rust with Redis API support.
Rust
46
star
64

spanmap

A fast collection type that uses uint64 for keys.
Go
44
star
65

go-node

Run Javascript in Go using Node.js
Go
42
star
66

ticketd

A distributed service for monotonically increasing tickets.
Go
42
star
67

hexd

Please love the nicely formatted hex.
Go
42
star
68

DeflateSwift

Deflate Compression for Swift
Swift
40
star
69

proximity-chat

Chat app for real-time chats with people within 500 meters.
JavaScript
39
star
70

lru

A simple and efficient LRU cache package for Go
Go
38
star
71

sider

A Redis clone written in Go
Go
36
star
72

xv

An expression evaluator for C
C
34
star
73

geometry

Efficient 2D geometry library for Go.
Go
32
star
74

pkg.sh

A generalized package manager for whatever code.
Shell
32
star
75

rfront

An HTTP protocol frontend for Redis-compatible services.
Go
31
star
76

redis-gis

Redis fork with Geospatial support based on Tile38 commands
C
31
star
77

RetroSwiper

Load classic games from magnetic swipe cards
Rust
31
star
78

uhasql

A high availability Sqlite service
C
30
star
79

redbench

Benchmarking for custom Redis commands and modules
Go
30
star
80

sds

simple data streams for go
Go
29
star
81

spmap

A hashmap for Go that uses crypto random seeds, hash hints, open addressing, and robin hood hashing.
Go
29
star
82

IoniconsSwift

Ionicons for Swift and iOS
Swift
29
star
83

raft-leveldb

Raft backend using LevelDB
Go
28
star
84

evio.c

A framework for building event based networking applications.
C
28
star
85

tinyqueue

Binary heap priority queues in Go
Go
27
star
86

kvbench

Server for benchmarking pure Go key/value databases
Go
26
star
87

gjson-play

A playground for GJSON. Runs in the browser.
JavaScript
25
star
88

randjson

Make random JSON in Go
Go
25
star
89

redlog

Redis style logger for Go
Go
25
star
90

SnapHTTP

An incredibly simple HTTP client library for Swift.
Swift
24
star
91

qtree

jeez it's just a quadtree chill out
Go
24
star
92

rtime

Retrieve the current time from remote servers
Go
21
star
93

fast-spatial-joins

Go vs GPU: Fast Spatial Joins
Go
21
star
94

assert

An assert function for Go that works like the one in C.
Go
20
star
95

pair

create low memory key/value objects in Go
Go
20
star
96

match.c

Simple string pattern matcher for C
C
19
star
97

secret

A simple utility for encrypting and decrypting data in Go (AES-256-CFB)
Go
19
star
98

pony

๐ŸŒˆ ๐Ÿด Turn your terminal text into an absolutely beautiful display of dazzling colors....
Go
19
star
99

btree-benchmark

Benchmark utility for the tidwall/btree Go package
Go
19
star
100

lru-server

A convenient LRU cache server that supports REST API and Let's Encrypt.
Go
18
star