pgLatLon

annotate latlon-v0008.c @ 42:1b9cd45e9e48

Bugfix for type casts to ecluster; New "fair_distance" function
author jbe
date Tue Oct 25 18:44:43 2016 +0200 (2016-10-25)
parents latlon-v0007.c@bdbec73dc8ff
children 10640afbe2ea
rev   line source
jbe@0 1
jbe@0 2 /*-------------*
jbe@0 3 * C prelude *
jbe@0 4 *-------------*/
jbe@0 5
jbe@0 6 #include "postgres.h"
jbe@0 7 #include "fmgr.h"
jbe@0 8 #include "libpq/pqformat.h"
jbe@0 9 #include "access/gist.h"
jbe@0 10 #include "access/stratnum.h"
jbe@0 11 #include "utils/array.h"
jbe@0 12 #include <math.h>
jbe@0 13
jbe@0 14 #ifdef PG_MODULE_MAGIC
jbe@0 15 PG_MODULE_MAGIC;
jbe@0 16 #endif
jbe@0 17
jbe@0 18 #if INT_MAX < 2147483647
jbe@0 19 #error Expected int type to be at least 32 bit wide
jbe@0 20 #endif
jbe@0 21
jbe@0 22
jbe@0 23 /*---------------------------------*
jbe@0 24 * distance calculation on earth *
jbe@0 25 * (using WGS-84 spheroid) *
jbe@0 26 *---------------------------------*/
jbe@0 27
jbe@0 28 /* WGS-84 spheroid with following parameters:
jbe@0 29 semi-major axis a = 6378137
jbe@0 30 semi-minor axis b = a * (1 - 1/298.257223563)
jbe@0 31 estimated diameter = 2 * (2*a+b)/3
jbe@0 32 */
jbe@0 33 #define PGL_SPHEROID_A 6378137.0 /* semi major axis */
jbe@0 34 #define PGL_SPHEROID_F (1.0/298.257223563) /* flattening */
jbe@0 35 #define PGL_SPHEROID_B (PGL_SPHEROID_A * (1.0-PGL_SPHEROID_F))
jbe@0 36 #define PGL_EPS2 ( ( PGL_SPHEROID_A * PGL_SPHEROID_A - \
jbe@0 37 PGL_SPHEROID_B * PGL_SPHEROID_B ) / \
jbe@0 38 ( PGL_SPHEROID_A * PGL_SPHEROID_A ) )
jbe@0 39 #define PGL_SUBEPS2 (1.0-PGL_EPS2)
jbe@42 40 #define PGL_RADIUS ((2.0*PGL_SPHEROID_A + PGL_SPHEROID_B) / 3.0)
jbe@42 41 #define PGL_DIAMETER (2.0 * PGL_RADIUS)
jbe@0 42 #define PGL_SCALE (PGL_SPHEROID_A / PGL_DIAMETER) /* semi-major ref. */
jbe@42 43 #define PGL_MAXDIST (PGL_RADIUS * M_PI) /* maximum distance */
jbe@42 44 #define PGL_FADELIMIT (PGL_MAXDIST / 3.0) /* 1/6 circumference */
jbe@0 45
jbe@0 46 /* calculate distance between two points on earth (given in degrees) */
jbe@0 47 static inline double pgl_distance(
jbe@0 48 double lat1, double lon1, double lat2, double lon2
jbe@0 49 ) {
jbe@0 50 float8 lat1cos, lat1sin, lat2cos, lat2sin, lon2cos, lon2sin;
jbe@0 51 float8 nphi1, nphi2, x1, z1, x2, y2, z2, g, s, t;
jbe@0 52 /* normalize delta longitude (lon2 > 0 && lon1 = 0) */
jbe@0 53 /* lon1 = 0 (not used anymore) */
jbe@0 54 lon2 = fabs(lon2-lon1);
jbe@0 55 /* convert to radians (first divide, then multiply) */
jbe@0 56 lat1 = (lat1 / 180.0) * M_PI;
jbe@0 57 lat2 = (lat2 / 180.0) * M_PI;
jbe@0 58 lon2 = (lon2 / 180.0) * M_PI;
jbe@0 59 /* make lat2 >= lat1 to ensure reversal-symmetry despite floating point
jbe@0 60 operations (lon2 >= lon1 is already ensured in a previous step) */
jbe@0 61 if (lat2 < lat1) { float8 swap = lat1; lat1 = lat2; lat2 = swap; }
jbe@0 62 /* calculate 3d coordinates on scaled ellipsoid which has an average diameter
jbe@0 63 of 1.0 */
jbe@0 64 lat1cos = cos(lat1); lat1sin = sin(lat1);
jbe@0 65 lat2cos = cos(lat2); lat2sin = sin(lat2);
jbe@0 66 lon2cos = cos(lon2); lon2sin = sin(lon2);
jbe@0 67 nphi1 = PGL_SCALE / sqrt(1 - PGL_EPS2 * lat1sin * lat1sin);
jbe@0 68 nphi2 = PGL_SCALE / sqrt(1 - PGL_EPS2 * lat2sin * lat2sin);
jbe@0 69 x1 = nphi1 * lat1cos;
jbe@0 70 z1 = nphi1 * PGL_SUBEPS2 * lat1sin;
jbe@0 71 x2 = nphi2 * lat2cos * lon2cos;
jbe@0 72 y2 = nphi2 * lat2cos * lon2sin;
jbe@0 73 z2 = nphi2 * PGL_SUBEPS2 * lat2sin;
jbe@0 74 /* calculate tunnel distance through scaled (diameter 1.0) ellipsoid */
jbe@0 75 g = sqrt((x2-x1)*(x2-x1) + y2*y2 + (z2-z1)*(z2-z1));
jbe@0 76 /* convert tunnel distance through scaled ellipsoid to approximated surface
jbe@0 77 distance on original ellipsoid */
jbe@0 78 if (g > 1.0) g = 1.0;
jbe@0 79 s = PGL_DIAMETER * asin(g);
jbe@0 80 /* return result only if small enough to be precise (less than 1/3 of
jbe@0 81 maximum possible distance) */
jbe@0 82 if (s <= PGL_FADELIMIT) return s;
jbe@0 83 /* calculate tunnel distance to antipodal point through scaled ellipsoid */
jbe@3 84 g = sqrt((x2+x1)*(x2+x1) + y2*y2 + (z2+z1)*(z2+z1));
jbe@0 85 /* convert tunnel distance to antipodal point through scaled ellipsoid to
jbe@0 86 approximated surface distance to antipodal point on original ellipsoid */
jbe@0 87 if (g > 1.0) g = 1.0;
jbe@0 88 t = PGL_DIAMETER * asin(g);
jbe@0 89 /* surface distance between original points can now be approximated by
jbe@0 90 substracting antipodal distance from maximum possible distance;
jbe@0 91 return result only if small enough (less than 1/3 of maximum possible
jbe@0 92 distance) */
jbe@0 93 if (t <= PGL_FADELIMIT) return PGL_MAXDIST-t;
jbe@0 94 /* otherwise crossfade direct and antipodal result to ensure monotonicity */
jbe@0 95 return (
jbe@0 96 (s * (t-PGL_FADELIMIT) + (PGL_MAXDIST-t) * (s-PGL_FADELIMIT)) /
jbe@0 97 (s + t - 2*PGL_FADELIMIT)
jbe@0 98 );
jbe@0 99 }
jbe@0 100
jbe@0 101 /* finite distance that can not be reached on earth */
jbe@0 102 #define PGL_ULTRA_DISTANCE (3 * PGL_MAXDIST)
jbe@0 103
jbe@0 104
jbe@0 105 /*--------------------------------*
jbe@0 106 * simple geographic data types *
jbe@0 107 *--------------------------------*/
jbe@0 108
jbe@0 109 /* point on earth given by latitude and longitude in degrees */
jbe@0 110 /* (type "epoint" in SQL) */
jbe@0 111 typedef struct {
jbe@0 112 double lat; /* between -90 and 90 (both inclusive) */
jbe@0 113 double lon; /* between -180 and 180 (both inclusive) */
jbe@0 114 } pgl_point;
jbe@0 115
jbe@0 116 /* box delimited by two parallels and two meridians (all in degrees) */
jbe@0 117 /* (type "ebox" in SQL) */
jbe@0 118 typedef struct {
jbe@0 119 double lat_min; /* between -90 and 90 (both inclusive) */
jbe@0 120 double lat_max; /* between -90 and 90 (both inclusive) */
jbe@0 121 double lon_min; /* between -180 and 180 (both inclusive) */
jbe@0 122 double lon_max; /* between -180 and 180 (both inclusive) */
jbe@0 123 /* if lat_min > lat_max, then box is empty */
jbe@0 124 /* if lon_min > lon_max, then 180th meridian is crossed */
jbe@0 125 } pgl_box;
jbe@0 126
jbe@0 127 /* circle on earth surface (for radial searches with fixed radius) */
jbe@0 128 /* (type "ecircle" in SQL) */
jbe@0 129 typedef struct {
jbe@0 130 pgl_point center;
jbe@0 131 double radius; /* positive (including +0 but excluding -0), or -INFINITY */
jbe@0 132 /* A negative radius (i.e. -INFINITY) denotes nothing (i.e. no point),
jbe@0 133 zero radius (0) denotes a single point,
jbe@0 134 a finite radius (0 < radius < INFINITY) denotes a filled circle, and
jbe@0 135 a radius of INFINITY is valid and means complete coverage of earth. */
jbe@0 136 } pgl_circle;
jbe@0 137
jbe@0 138
jbe@0 139 /*----------------------------------*
jbe@0 140 * geographic "cluster" data type *
jbe@0 141 *----------------------------------*/
jbe@0 142
jbe@0 143 /* A cluster is a collection of points, paths, outlines, and polygons. If two
jbe@0 144 polygons in a cluster overlap, the area covered by both polygons does not
jbe@0 145 belong to the cluster. This way, a cluster can be used to describe complex
jbe@0 146 shapes like polygons with holes. Outlines are non-filled polygons. Paths are
jbe@0 147 open by default (i.e. the last point in the list is not connected with the
jbe@0 148 first point in the list). Note that each outline or polygon in a cluster
jbe@0 149 must cover a longitude range of less than 180 degrees to avoid ambiguities.
jbe@0 150 Areas which are larger may be split into multiple polygons. */
jbe@0 151
jbe@0 152 /* maximum number of points in a cluster */
jbe@0 153 /* (limited to avoid integer overflows, e.g. when allocating memory) */
jbe@0 154 #define PGL_CLUSTER_MAXPOINTS 16777216
jbe@0 155
jbe@0 156 /* types of cluster entries */
jbe@0 157 #define PGL_ENTRY_POINT 1 /* a point */
jbe@0 158 #define PGL_ENTRY_PATH 2 /* a path from first point to last point */
jbe@0 159 #define PGL_ENTRY_OUTLINE 3 /* a non-filled polygon with given vertices */
jbe@0 160 #define PGL_ENTRY_POLYGON 4 /* a filled polygon with given vertices */
jbe@0 161
jbe@0 162 /* Entries of a cluster are described by two different structs: pgl_newentry
jbe@0 163 and pgl_entry. The first is used only during construction of a cluster, the
jbe@0 164 second is used in all other cases (e.g. when reading clusters from the
jbe@0 165 database, performing operations, etc). */
jbe@0 166
jbe@0 167 /* entry for new geographic cluster during construction of that cluster */
jbe@0 168 typedef struct {
jbe@0 169 int32_t entrytype;
jbe@0 170 int32_t npoints;
jbe@0 171 pgl_point *points; /* pointer to an array of points (pgl_point) */
jbe@0 172 } pgl_newentry;
jbe@0 173
jbe@0 174 /* entry of geographic cluster */
jbe@0 175 typedef struct {
jbe@0 176 int32_t entrytype; /* type of entry: point, path, outline, polygon */
jbe@0 177 int32_t npoints; /* number of stored points (set to 1 for point entry) */
jbe@0 178 int32_t offset; /* offset of pgl_point array from cluster base address */
jbe@0 179 /* use macro PGL_ENTRY_POINTS to obtain a pointer to the array of points */
jbe@0 180 } pgl_entry;
jbe@0 181
jbe@0 182 /* geographic cluster which is a collection of points, (open) paths, polygons,
jbe@0 183 and outlines (non-filled polygons) */
jbe@0 184 typedef struct {
jbe@0 185 char header[VARHDRSZ]; /* PostgreSQL header for variable size data types */
jbe@0 186 int32_t nentries; /* number of stored points */
jbe@0 187 pgl_circle bounding; /* bounding circle */
jbe@0 188 /* Note: bounding circle ensures alignment of pgl_cluster for points */
jbe@0 189 pgl_entry entries[FLEXIBLE_ARRAY_MEMBER]; /* var-length data */
jbe@0 190 } pgl_cluster;
jbe@0 191
jbe@0 192 /* macro to determine memory alignment of points */
jbe@0 193 /* (needed to store pgl_point array after entries in pgl_cluster) */
jbe@0 194 typedef struct { char dummy; pgl_point aligned; } pgl_point_alignment;
jbe@0 195 #define PGL_POINT_ALIGNMENT offsetof(pgl_point_alignment, aligned)
jbe@0 196
jbe@0 197 /* macro to extract a pointer to the array of points of a cluster entry */
jbe@0 198 #define PGL_ENTRY_POINTS(cluster, idx) \
jbe@0 199 ((pgl_point *)(((intptr_t)cluster)+(cluster)->entries[idx].offset))
jbe@0 200
jbe@0 201 /* convert pgl_newentry array to pgl_cluster */
jbe@42 202 /* NOTE: requires pgl_finalize_cluster to be called to finalize result */
jbe@0 203 static pgl_cluster *pgl_new_cluster(int nentries, pgl_newentry *entries) {
jbe@0 204 int i; /* index of current entry */
jbe@0 205 int npoints = 0; /* number of points in whole cluster */
jbe@0 206 int entry_npoints; /* number of points in current entry */
jbe@0 207 int points_offset = PGL_POINT_ALIGNMENT * (
jbe@0 208 ( offsetof(pgl_cluster, entries) +
jbe@0 209 nentries * sizeof(pgl_entry) +
jbe@0 210 PGL_POINT_ALIGNMENT - 1
jbe@0 211 ) / PGL_POINT_ALIGNMENT
jbe@0 212 ); /* offset of pgl_point array from base address (considering alignment) */
jbe@0 213 pgl_cluster *cluster; /* new cluster to be returned */
jbe@0 214 /* determine total number of points */
jbe@0 215 for (i=0; i<nentries; i++) npoints += entries[i].npoints;
jbe@0 216 /* allocate memory for cluster (including entries and points) */
jbe@0 217 cluster = palloc(points_offset + npoints * sizeof(pgl_point));
jbe@0 218 /* re-count total number of points to determine offset for each entry */
jbe@0 219 npoints = 0;
jbe@0 220 /* copy entries and points */
jbe@0 221 for (i=0; i<nentries; i++) {
jbe@0 222 /* determine number of points in entry */
jbe@0 223 entry_npoints = entries[i].npoints;
jbe@0 224 /* copy entry */
jbe@0 225 cluster->entries[i].entrytype = entries[i].entrytype;
jbe@0 226 cluster->entries[i].npoints = entry_npoints;
jbe@0 227 /* calculate offset (in bytes) of pgl_point array */
jbe@0 228 cluster->entries[i].offset = points_offset + npoints * sizeof(pgl_point);
jbe@0 229 /* copy points */
jbe@0 230 memcpy(
jbe@0 231 PGL_ENTRY_POINTS(cluster, i),
jbe@0 232 entries[i].points,
jbe@0 233 entry_npoints * sizeof(pgl_point)
jbe@0 234 );
jbe@0 235 /* update total number of points processed */
jbe@0 236 npoints += entry_npoints;
jbe@0 237 }
jbe@0 238 /* set number of entries in cluster */
jbe@0 239 cluster->nentries = nentries;
jbe@0 240 /* set PostgreSQL header for variable sized data */
jbe@0 241 SET_VARSIZE(cluster, points_offset + npoints * sizeof(pgl_point));
jbe@0 242 /* return newly created cluster */
jbe@0 243 return cluster;
jbe@0 244 }
jbe@0 245
jbe@0 246
jbe@0 247 /*----------------------------------------*
jbe@0 248 * C functions on geographic data types *
jbe@0 249 *----------------------------------------*/
jbe@0 250
jbe@0 251 /* round latitude or longitude to 12 digits after decimal point */
jbe@0 252 static inline double pgl_round(double val) {
jbe@0 253 return round(val * 1e12) / 1e12;
jbe@0 254 }
jbe@0 255
jbe@0 256 /* compare two points */
jbe@0 257 /* (equality when same point on earth is described, otherwise an arbitrary
jbe@0 258 linear order) */
jbe@0 259 static int pgl_point_cmp(pgl_point *point1, pgl_point *point2) {
jbe@0 260 double lon1, lon2; /* modified longitudes for special cases */
jbe@0 261 /* use latitude as first ordering criterion */
jbe@0 262 if (point1->lat < point2->lat) return -1;
jbe@0 263 if (point1->lat > point2->lat) return 1;
jbe@0 264 /* determine modified longitudes (considering special case of poles and
jbe@0 265 180th meridian which can be described as W180 or E180) */
jbe@0 266 if (point1->lat == -90 || point1->lat == 90) lon1 = 0;
jbe@0 267 else if (point1->lon == 180) lon1 = -180;
jbe@0 268 else lon1 = point1->lon;
jbe@0 269 if (point2->lat == -90 || point2->lat == 90) lon2 = 0;
jbe@0 270 else if (point2->lon == 180) lon2 = -180;
jbe@0 271 else lon2 = point2->lon;
jbe@0 272 /* use (modified) longitude as secondary ordering criterion */
jbe@0 273 if (lon1 < lon2) return -1;
jbe@0 274 if (lon1 > lon2) return 1;
jbe@0 275 /* no difference found, points are equal */
jbe@0 276 return 0;
jbe@0 277 }
jbe@0 278
jbe@0 279 /* compare two boxes */
jbe@0 280 /* (equality when same box on earth is described, otherwise an arbitrary linear
jbe@0 281 order) */
jbe@0 282 static int pgl_box_cmp(pgl_box *box1, pgl_box *box2) {
jbe@0 283 /* two empty boxes are equal, and an empty box is always considered "less
jbe@0 284 than" a non-empty box */
jbe@0 285 if (box1->lat_min> box1->lat_max && box2->lat_min<=box2->lat_max) return -1;
jbe@0 286 if (box1->lat_min> box1->lat_max && box2->lat_min> box2->lat_max) return 0;
jbe@0 287 if (box1->lat_min<=box1->lat_max && box2->lat_min> box2->lat_max) return 1;
jbe@0 288 /* use southern border as first ordering criterion */
jbe@0 289 if (box1->lat_min < box2->lat_min) return -1;
jbe@0 290 if (box1->lat_min > box2->lat_min) return 1;
jbe@0 291 /* use northern border as second ordering criterion */
jbe@0 292 if (box1->lat_max < box2->lat_max) return -1;
jbe@0 293 if (box1->lat_max > box2->lat_max) return 1;
jbe@0 294 /* use western border as third ordering criterion */
jbe@0 295 if (box1->lon_min < box2->lon_min) return -1;
jbe@0 296 if (box1->lon_min > box2->lon_min) return 1;
jbe@0 297 /* use eastern border as fourth ordering criterion */
jbe@0 298 if (box1->lon_max < box2->lon_max) return -1;
jbe@0 299 if (box1->lon_max > box2->lon_max) return 1;
jbe@0 300 /* no difference found, boxes are equal */
jbe@0 301 return 0;
jbe@0 302 }
jbe@0 303
jbe@0 304 /* compare two circles */
jbe@0 305 /* (equality when same circle on earth is described, otherwise an arbitrary
jbe@0 306 linear order) */
jbe@0 307 static int pgl_circle_cmp(pgl_circle *circle1, pgl_circle *circle2) {
jbe@0 308 /* two circles with same infinite radius (positive or negative infinity) are
jbe@0 309 considered equal independently of center point */
jbe@0 310 if (
jbe@0 311 !isfinite(circle1->radius) && !isfinite(circle2->radius) &&
jbe@0 312 circle1->radius == circle2->radius
jbe@0 313 ) return 0;
jbe@0 314 /* use radius as first ordering criterion */
jbe@0 315 if (circle1->radius < circle2->radius) return -1;
jbe@0 316 if (circle1->radius > circle2->radius) return 1;
jbe@0 317 /* use center point as secondary ordering criterion */
jbe@0 318 return pgl_point_cmp(&(circle1->center), &(circle2->center));
jbe@0 319 }
jbe@0 320
jbe@0 321 /* set box to empty box*/
jbe@0 322 static void pgl_box_set_empty(pgl_box *box) {
jbe@0 323 box->lat_min = INFINITY;
jbe@0 324 box->lat_max = -INFINITY;
jbe@0 325 box->lon_min = 0;
jbe@0 326 box->lon_max = 0;
jbe@0 327 }
jbe@0 328
jbe@0 329 /* check if point is inside a box */
jbe@0 330 static bool pgl_point_in_box(pgl_point *point, pgl_box *box) {
jbe@0 331 return (
jbe@0 332 point->lat >= box->lat_min && point->lat <= box->lat_max && (
jbe@0 333 (box->lon_min > box->lon_max) ? (
jbe@0 334 /* box crosses 180th meridian */
jbe@0 335 point->lon >= box->lon_min || point->lon <= box->lon_max
jbe@0 336 ) : (
jbe@0 337 /* box does not cross the 180th meridian */
jbe@0 338 point->lon >= box->lon_min && point->lon <= box->lon_max
jbe@0 339 )
jbe@0 340 )
jbe@0 341 );
jbe@0 342 }
jbe@0 343
jbe@0 344 /* check if two boxes overlap */
jbe@0 345 static bool pgl_boxes_overlap(pgl_box *box1, pgl_box *box2) {
jbe@0 346 return (
jbe@0 347 box2->lat_max >= box2->lat_min && /* ensure box2 is not empty */
jbe@0 348 ( box2->lat_min >= box1->lat_min || box2->lat_max >= box1->lat_min ) &&
jbe@0 349 ( box2->lat_min <= box1->lat_max || box2->lat_max <= box1->lat_max ) && (
jbe@0 350 (
jbe@0 351 /* check if one and only one box crosses the 180th meridian */
jbe@0 352 ((box1->lon_min > box1->lon_max) ? 1 : 0) ^
jbe@0 353 ((box2->lon_min > box2->lon_max) ? 1 : 0)
jbe@0 354 ) ? (
jbe@0 355 /* exactly one box crosses the 180th meridian */
jbe@0 356 box2->lon_min >= box1->lon_min || box2->lon_max >= box1->lon_min ||
jbe@0 357 box2->lon_min <= box1->lon_max || box2->lon_max <= box1->lon_max
jbe@0 358 ) : (
jbe@0 359 /* no box or both boxes cross the 180th meridian */
jbe@0 360 (
jbe@0 361 (box2->lon_min >= box1->lon_min || box2->lon_max >= box1->lon_min) &&
jbe@0 362 (box2->lon_min <= box1->lon_max || box2->lon_max <= box1->lon_max)
jbe@0 363 ) ||
jbe@0 364 /* handle W180 == E180 */
jbe@0 365 ( box1->lon_min == -180 && box2->lon_max == 180 ) ||
jbe@0 366 ( box2->lon_min == -180 && box1->lon_max == 180 )
jbe@0 367 )
jbe@0 368 )
jbe@0 369 );
jbe@0 370 }
jbe@0 371
jbe@0 372 /* check unambiguousness of east/west orientation of cluster entries and set
jbe@0 373 bounding circle of cluster */
jbe@0 374 static bool pgl_finalize_cluster(pgl_cluster *cluster) {
jbe@0 375 int i, j; /* i: index of entry, j: index of point in entry */
jbe@0 376 int npoints; /* number of points in entry */
jbe@0 377 int total_npoints = 0; /* total number of points in cluster */
jbe@0 378 pgl_point *points; /* points in entry */
jbe@0 379 int lon_dir; /* first point of entry west (-1) or east (+1) */
jbe@0 380 double lon_break = 0; /* antipodal longitude of first point in entry */
jbe@0 381 double lon_min, lon_max; /* covered longitude range of entry */
jbe@0 382 double value; /* temporary variable */
jbe@0 383 /* reset bounding circle center to empty circle at 0/0 coordinates */
jbe@0 384 cluster->bounding.center.lat = 0;
jbe@0 385 cluster->bounding.center.lon = 0;
jbe@0 386 cluster->bounding.radius = -INFINITY;
jbe@0 387 /* if cluster is not empty */
jbe@0 388 if (cluster->nentries != 0) {
jbe@0 389 /* iterate over all cluster entries and ensure they each cover a longitude
jbe@0 390 range less than 180 degrees */
jbe@0 391 for (i=0; i<cluster->nentries; i++) {
jbe@0 392 /* get properties of entry */
jbe@0 393 npoints = cluster->entries[i].npoints;
jbe@0 394 points = PGL_ENTRY_POINTS(cluster, i);
jbe@0 395 /* get longitude of first point of entry */
jbe@0 396 value = points[0].lon;
jbe@0 397 /* initialize lon_min and lon_max with longitude of first point */
jbe@0 398 lon_min = value;
jbe@0 399 lon_max = value;
jbe@0 400 /* determine east/west orientation of first point and calculate antipodal
jbe@0 401 longitude (Note: rounding required here) */
jbe@0 402 if (value < 0) { lon_dir = -1; lon_break = pgl_round(value + 180); }
jbe@0 403 else if (value > 0) { lon_dir = 1; lon_break = pgl_round(value - 180); }
jbe@0 404 else lon_dir = 0;
jbe@0 405 /* iterate over all other points in entry */
jbe@0 406 for (j=1; j<npoints; j++) {
jbe@0 407 /* consider longitude wrap-around */
jbe@0 408 value = points[j].lon;
jbe@0 409 if (lon_dir<0 && value>lon_break) value = pgl_round(value - 360);
jbe@0 410 else if (lon_dir>0 && value<lon_break) value = pgl_round(value + 360);
jbe@0 411 /* update lon_min and lon_max */
jbe@0 412 if (value < lon_min) lon_min = value;
jbe@0 413 else if (value > lon_max) lon_max = value;
jbe@0 414 /* return false if 180 degrees or more are covered */
jbe@0 415 if (lon_max - lon_min >= 180) return false;
jbe@0 416 }
jbe@0 417 }
jbe@0 418 /* iterate over all points of all entries and calculate arbitrary center
jbe@0 419 point for bounding circle (best if center point minimizes the radius,
jbe@0 420 but some error is allowed here) */
jbe@0 421 for (i=0; i<cluster->nentries; i++) {
jbe@0 422 /* get properties of entry */
jbe@0 423 npoints = cluster->entries[i].npoints;
jbe@0 424 points = PGL_ENTRY_POINTS(cluster, i);
jbe@0 425 /* check if first entry */
jbe@0 426 if (i==0) {
jbe@0 427 /* get longitude of first point of first entry in whole cluster */
jbe@0 428 value = points[0].lon;
jbe@0 429 /* initialize lon_min and lon_max with longitude of first point of
jbe@0 430 first entry in whole cluster (used to determine if whole cluster
jbe@0 431 covers a longitude range of 180 degrees or more) */
jbe@0 432 lon_min = value;
jbe@0 433 lon_max = value;
jbe@0 434 /* determine east/west orientation of first point and calculate
jbe@0 435 antipodal longitude (Note: rounding not necessary here) */
jbe@0 436 if (value < 0) { lon_dir = -1; lon_break = value + 180; }
jbe@0 437 else if (value > 0) { lon_dir = 1; lon_break = value - 180; }
jbe@0 438 else lon_dir = 0;
jbe@0 439 }
jbe@0 440 /* iterate over all points in entry */
jbe@0 441 for (j=0; j<npoints; j++) {
jbe@0 442 /* longitude wrap-around (Note: rounding not necessary here) */
jbe@0 443 value = points[j].lon;
jbe@0 444 if (lon_dir < 0 && value > lon_break) value -= 360;
jbe@0 445 else if (lon_dir > 0 && value < lon_break) value += 360;
jbe@0 446 if (value < lon_min) lon_min = value;
jbe@0 447 else if (value > lon_max) lon_max = value;
jbe@0 448 /* set bounding circle to cover whole earth if more than 180 degrees
jbe@0 449 are covered */
jbe@0 450 if (lon_max - lon_min >= 180) {
jbe@0 451 cluster->bounding.center.lat = 0;
jbe@0 452 cluster->bounding.center.lon = 0;
jbe@0 453 cluster->bounding.radius = INFINITY;
jbe@0 454 return true;
jbe@0 455 }
jbe@0 456 /* add point to bounding circle center (for average calculation) */
jbe@0 457 cluster->bounding.center.lat += points[j].lat;
jbe@0 458 cluster->bounding.center.lon += value;
jbe@0 459 }
jbe@0 460 /* count total number of points */
jbe@0 461 total_npoints += npoints;
jbe@0 462 }
jbe@0 463 /* determine average latitude and longitude of cluster */
jbe@0 464 cluster->bounding.center.lat /= total_npoints;
jbe@0 465 cluster->bounding.center.lon /= total_npoints;
jbe@0 466 /* normalize longitude of center of cluster bounding circle */
jbe@0 467 if (cluster->bounding.center.lon < -180) {
jbe@0 468 cluster->bounding.center.lon += 360;
jbe@0 469 }
jbe@0 470 else if (cluster->bounding.center.lon > 180) {
jbe@0 471 cluster->bounding.center.lon -= 360;
jbe@0 472 }
jbe@0 473 /* round bounding circle center (useful if it is used by other functions) */
jbe@0 474 cluster->bounding.center.lat = pgl_round(cluster->bounding.center.lat);
jbe@0 475 cluster->bounding.center.lon = pgl_round(cluster->bounding.center.lon);
jbe@0 476 /* calculate radius of bounding circle */
jbe@0 477 for (i=0; i<cluster->nentries; i++) {
jbe@0 478 npoints = cluster->entries[i].npoints;
jbe@0 479 points = PGL_ENTRY_POINTS(cluster, i);
jbe@0 480 for (j=0; j<npoints; j++) {
jbe@0 481 value = pgl_distance(
jbe@0 482 cluster->bounding.center.lat, cluster->bounding.center.lon,
jbe@0 483 points[j].lat, points[j].lon
jbe@0 484 );
jbe@0 485 if (value > cluster->bounding.radius) cluster->bounding.radius = value;
jbe@0 486 }
jbe@0 487 }
jbe@0 488 }
jbe@0 489 /* return true (east/west orientation is unambiguous) */
jbe@0 490 return true;
jbe@0 491 }
jbe@0 492
jbe@0 493 /* check if point is inside cluster */
jbe@20 494 /* (if point is on perimeter, then true is returned if and only if
jbe@20 495 strict == false) */
jbe@20 496 static bool pgl_point_in_cluster(
jbe@20 497 pgl_point *point,
jbe@20 498 pgl_cluster *cluster,
jbe@20 499 bool strict
jbe@20 500 ) {
jbe@0 501 int i, j, k; /* i: entry, j: point in entry, k: next point in entry */
jbe@0 502 int entrytype; /* type of entry */
jbe@0 503 int npoints; /* number of points in entry */
jbe@0 504 pgl_point *points; /* array of points in entry */
jbe@0 505 int lon_dir = 0; /* first vertex west (-1) or east (+1) */
jbe@0 506 double lon_break = 0; /* antipodal longitude of first vertex */
jbe@0 507 double lat0 = point->lat; /* latitude of point */
jbe@0 508 double lon0; /* (adjusted) longitude of point */
jbe@0 509 double lat1, lon1; /* latitude and (adjusted) longitude of vertex */
jbe@0 510 double lat2, lon2; /* latitude and (adjusted) longitude of next vertex */
jbe@0 511 double lon; /* longitude of intersection */
jbe@0 512 int counter = 0; /* counter for intersections east of point */
jbe@0 513 /* iterate over all entries */
jbe@0 514 for (i=0; i<cluster->nentries; i++) {
jbe@20 515 /* get type of entry */
jbe@0 516 entrytype = cluster->entries[i].entrytype;
jbe@20 517 /* skip all entries but polygons if perimeters are excluded */
jbe@20 518 if (strict && entrytype != PGL_ENTRY_POLYGON) continue;
jbe@20 519 /* get points of entry */
jbe@0 520 npoints = cluster->entries[i].npoints;
jbe@0 521 points = PGL_ENTRY_POINTS(cluster, i);
jbe@0 522 /* determine east/west orientation of first point of entry and calculate
jbe@0 523 antipodal longitude */
jbe@0 524 lon_break = points[0].lon;
jbe@0 525 if (lon_break < 0) { lon_dir = -1; lon_break += 180; }
jbe@0 526 else if (lon_break > 0) { lon_dir = 1; lon_break -= 180; }
jbe@0 527 else lon_dir = 0;
jbe@0 528 /* get longitude of point */
jbe@0 529 lon0 = point->lon;
jbe@0 530 /* consider longitude wrap-around for point */
jbe@0 531 if (lon_dir < 0 && lon0 > lon_break) lon0 = pgl_round(lon0 - 360);
jbe@0 532 else if (lon_dir > 0 && lon0 < lon_break) lon0 = pgl_round(lon0 + 360);
jbe@0 533 /* iterate over all edges and vertices */
jbe@0 534 for (j=0; j<npoints; j++) {
jbe@20 535 /* return if point is on vertex of polygon */
jbe@20 536 if (pgl_point_cmp(point, &(points[j])) == 0) return !strict;
jbe@0 537 /* calculate index of next vertex */
jbe@0 538 k = (j+1) % npoints;
jbe@0 539 /* skip last edge unless entry is (closed) outline or polygon */
jbe@0 540 if (
jbe@0 541 k == 0 &&
jbe@0 542 entrytype != PGL_ENTRY_OUTLINE &&
jbe@0 543 entrytype != PGL_ENTRY_POLYGON
jbe@0 544 ) continue;
jbe@16 545 /* use previously calculated values for lat1 and lon1 if possible */
jbe@16 546 if (j) {
jbe@16 547 lat1 = lat2;
jbe@16 548 lon1 = lon2;
jbe@16 549 } else {
jbe@16 550 /* otherwise get latitude and longitude values of first vertex */
jbe@16 551 lat1 = points[0].lat;
jbe@16 552 lon1 = points[0].lon;
jbe@16 553 /* and consider longitude wrap-around for first vertex */
jbe@16 554 if (lon_dir < 0 && lon1 > lon_break) lon1 = pgl_round(lon1 - 360);
jbe@16 555 else if (lon_dir > 0 && lon1 < lon_break) lon1 = pgl_round(lon1 + 360);
jbe@16 556 }
jbe@16 557 /* get latitude and longitude of next vertex */
jbe@0 558 lat2 = points[k].lat;
jbe@0 559 lon2 = points[k].lon;
jbe@16 560 /* consider longitude wrap-around for next vertex */
jbe@0 561 if (lon_dir < 0 && lon2 > lon_break) lon2 = pgl_round(lon2 - 360);
jbe@0 562 else if (lon_dir > 0 && lon2 < lon_break) lon2 = pgl_round(lon2 + 360);
jbe@20 563 /* return if point is on horizontal (west to east) edge of polygon */
jbe@0 564 if (
jbe@0 565 lat0 == lat1 && lat0 == lat2 &&
jbe@0 566 ( (lon0 >= lon1 && lon0 <= lon2) || (lon0 >= lon2 && lon0 <= lon1) )
jbe@20 567 ) return !strict;
jbe@0 568 /* check if edge crosses east/west line of point */
jbe@0 569 if ((lat1 < lat0 && lat2 >= lat0) || (lat2 < lat0 && lat1 >= lat0)) {
jbe@0 570 /* calculate longitude of intersection */
jbe@0 571 lon = (lon1 * (lat2-lat0) + lon2 * (lat0-lat1)) / (lat2-lat1);
jbe@20 572 /* return if intersection goes (approximately) through point */
jbe@20 573 if (pgl_round(lon) == lon0) return !strict;
jbe@0 574 /* count intersection if east of point and entry is polygon*/
jbe@0 575 if (entrytype == PGL_ENTRY_POLYGON && lon > lon0) counter++;
jbe@0 576 }
jbe@0 577 }
jbe@0 578 }
jbe@0 579 /* return true if number of intersections is odd */
jbe@0 580 return counter & 1;
jbe@0 581 }
jbe@0 582
jbe@20 583 /* check if all points of the second cluster are strictly inside the first
jbe@20 584 cluster */
jbe@20 585 static inline bool pgl_all_cluster_points_strictly_in_cluster(
jbe@16 586 pgl_cluster *outer, pgl_cluster *inner
jbe@16 587 ) {
jbe@16 588 int i, j; /* i: entry, j: point in entry */
jbe@16 589 int npoints; /* number of points in entry */
jbe@16 590 pgl_point *points; /* array of points in entry */
jbe@16 591 /* iterate over all entries of "inner" cluster */
jbe@16 592 for (i=0; i<inner->nentries; i++) {
jbe@16 593 /* get properties of entry */
jbe@16 594 npoints = inner->entries[i].npoints;
jbe@16 595 points = PGL_ENTRY_POINTS(inner, i);
jbe@16 596 /* iterate over all points in entry of "inner" cluster */
jbe@16 597 for (j=0; j<npoints; j++) {
jbe@16 598 /* return false if one point of inner cluster is not in outer cluster */
jbe@20 599 if (!pgl_point_in_cluster(points+j, outer, true)) return false;
jbe@16 600 }
jbe@16 601 }
jbe@16 602 /* otherwise return true */
jbe@16 603 return true;
jbe@16 604 }
jbe@16 605
jbe@16 606 /* check if any point the second cluster is inside the first cluster */
jbe@16 607 static inline bool pgl_any_cluster_points_in_cluster(
jbe@16 608 pgl_cluster *outer, pgl_cluster *inner
jbe@16 609 ) {
jbe@16 610 int i, j; /* i: entry, j: point in entry */
jbe@16 611 int npoints; /* number of points in entry */
jbe@16 612 pgl_point *points; /* array of points in entry */
jbe@16 613 /* iterate over all entries of "inner" cluster */
jbe@16 614 for (i=0; i<inner->nentries; i++) {
jbe@16 615 /* get properties of entry */
jbe@16 616 npoints = inner->entries[i].npoints;
jbe@16 617 points = PGL_ENTRY_POINTS(inner, i);
jbe@16 618 /* iterate over all points in entry of "inner" cluster */
jbe@16 619 for (j=0; j<npoints; j++) {
jbe@16 620 /* return true if one point of inner cluster is in outer cluster */
jbe@20 621 if (pgl_point_in_cluster(points+j, outer, false)) return true;
jbe@16 622 }
jbe@16 623 }
jbe@16 624 /* otherwise return false */
jbe@16 625 return false;
jbe@16 626 }
jbe@16 627
jbe@20 628 /* check if line segment strictly crosses line (not just touching) */
jbe@20 629 static inline bool pgl_lseg_crosses_line(
jbe@16 630 double seg_x1, double seg_y1, double seg_x2, double seg_y2,
jbe@20 631 double line_x1, double line_y1, double line_x2, double line_y2
jbe@16 632 ) {
jbe@20 633 return (
jbe@20 634 (
jbe@20 635 (seg_x1-line_x1) * (line_y2-line_y1) -
jbe@20 636 (seg_y1-line_y1) * (line_x2-line_x1)
jbe@20 637 ) * (
jbe@20 638 (seg_x2-line_x1) * (line_y2-line_y1) -
jbe@20 639 (seg_y2-line_y1) * (line_x2-line_x1)
jbe@20 640 )
jbe@20 641 ) < 0;
jbe@16 642 }
jbe@16 643
jbe@20 644 /* check if paths and outlines of two clusters strictly overlap (not just
jbe@20 645 touching) */
jbe@16 646 static bool pgl_outlines_overlap(
jbe@20 647 pgl_cluster *cluster1, pgl_cluster *cluster2
jbe@16 648 ) {
jbe@16 649 int i1, j1, k1; /* i: entry, j: point in entry, k: next point in entry */
jbe@16 650 int i2, j2, k2;
jbe@16 651 int entrytype1, entrytype2; /* type of entry */
jbe@16 652 int npoints1, npoints2; /* number of points in entry */
jbe@16 653 pgl_point *points1; /* array of points in entry of cluster1 */
jbe@16 654 pgl_point *points2; /* array of points in entry of cluster2 */
jbe@16 655 int lon_dir1, lon_dir2; /* first vertex west (-1) or east (+1) */
jbe@16 656 double lon_break1, lon_break2; /* antipodal longitude of first vertex */
jbe@16 657 double lat11, lon11; /* latitude and (adjusted) longitude of vertex */
jbe@16 658 double lat12, lon12; /* latitude and (adjusted) longitude of next vertex */
jbe@16 659 double lat21, lon21; /* latitude and (adjusted) longitudes for cluster2 */
jbe@16 660 double lat22, lon22;
jbe@16 661 double wrapvalue; /* temporary helper value to adjust wrap-around */
jbe@16 662 /* iterate over all entries of cluster1 */
jbe@16 663 for (i1=0; i1<cluster1->nentries; i1++) {
jbe@16 664 /* get properties of entry in cluster1 and skip points */
jbe@16 665 npoints1 = cluster1->entries[i1].npoints;
jbe@16 666 if (npoints1 < 2) continue;
jbe@16 667 entrytype1 = cluster1->entries[i1].entrytype;
jbe@16 668 points1 = PGL_ENTRY_POINTS(cluster1, i1);
jbe@16 669 /* determine east/west orientation of first point and calculate antipodal
jbe@16 670 longitude */
jbe@16 671 lon_break1 = points1[0].lon;
jbe@16 672 if (lon_break1 < 0) {
jbe@16 673 lon_dir1 = -1;
jbe@16 674 lon_break1 = pgl_round(lon_break1 + 180);
jbe@16 675 } else if (lon_break1 > 0) {
jbe@16 676 lon_dir1 = 1;
jbe@16 677 lon_break1 = pgl_round(lon_break1 - 180);
jbe@16 678 } else lon_dir1 = 0;
jbe@16 679 /* iterate over all edges and vertices in cluster1 */
jbe@16 680 for (j1=0; j1<npoints1; j1++) {
jbe@16 681 /* calculate index of next vertex */
jbe@16 682 k1 = (j1+1) % npoints1;
jbe@16 683 /* skip last edge unless entry is (closed) outline or polygon */
jbe@16 684 if (
jbe@16 685 k1 == 0 &&
jbe@16 686 entrytype1 != PGL_ENTRY_OUTLINE &&
jbe@16 687 entrytype1 != PGL_ENTRY_POLYGON
jbe@16 688 ) continue;
jbe@16 689 /* use previously calculated values for lat1 and lon1 if possible */
jbe@16 690 if (j1) {
jbe@16 691 lat11 = lat12;
jbe@16 692 lon11 = lon12;
jbe@16 693 } else {
jbe@16 694 /* otherwise get latitude and longitude values of first vertex */
jbe@16 695 lat11 = points1[0].lat;
jbe@16 696 lon11 = points1[0].lon;
jbe@16 697 /* and consider longitude wrap-around for first vertex */
jbe@16 698 if (lon_dir1<0 && lon11>lon_break1) lon11 = pgl_round(lon11-360);
jbe@16 699 else if (lon_dir1>0 && lon11<lon_break1) lon11 = pgl_round(lon11+360);
jbe@16 700 }
jbe@16 701 /* get latitude and longitude of next vertex */
jbe@16 702 lat12 = points1[k1].lat;
jbe@16 703 lon12 = points1[k1].lon;
jbe@16 704 /* consider longitude wrap-around for next vertex */
jbe@16 705 if (lon_dir1<0 && lon12>lon_break1) lon12 = pgl_round(lon12-360);
jbe@16 706 else if (lon_dir1>0 && lon12<lon_break1) lon12 = pgl_round(lon12+360);
jbe@16 707 /* skip degenerated edges */
jbe@16 708 if (lat11 == lat12 && lon11 == lon12) continue;
jbe@16 709 /* iterate over all entries of cluster2 */
jbe@16 710 for (i2=0; i2<cluster2->nentries; i2++) {
jbe@16 711 /* get points and number of points of entry in cluster2 */
jbe@16 712 npoints2 = cluster2->entries[i2].npoints;
jbe@16 713 if (npoints2 < 2) continue;
jbe@16 714 entrytype2 = cluster2->entries[i2].entrytype;
jbe@16 715 points2 = PGL_ENTRY_POINTS(cluster2, i2);
jbe@16 716 /* determine east/west orientation of first point and calculate antipodal
jbe@16 717 longitude */
jbe@16 718 lon_break2 = points2[0].lon;
jbe@16 719 if (lon_break2 < 0) {
jbe@16 720 lon_dir2 = -1;
jbe@16 721 lon_break2 = pgl_round(lon_break2 + 180);
jbe@16 722 } else if (lon_break2 > 0) {
jbe@16 723 lon_dir2 = 1;
jbe@16 724 lon_break2 = pgl_round(lon_break2 - 180);
jbe@16 725 } else lon_dir2 = 0;
jbe@16 726 /* iterate over all edges and vertices in cluster2 */
jbe@16 727 for (j2=0; j2<npoints2; j2++) {
jbe@16 728 /* calculate index of next vertex */
jbe@16 729 k2 = (j2+1) % npoints2;
jbe@16 730 /* skip last edge unless entry is (closed) outline or polygon */
jbe@16 731 if (
jbe@16 732 k2 == 0 &&
jbe@16 733 entrytype2 != PGL_ENTRY_OUTLINE &&
jbe@16 734 entrytype2 != PGL_ENTRY_POLYGON
jbe@16 735 ) continue;
jbe@16 736 /* use previously calculated values for lat1 and lon1 if possible */
jbe@16 737 if (j2) {
jbe@16 738 lat21 = lat22;
jbe@16 739 lon21 = lon22;
jbe@16 740 } else {
jbe@16 741 /* otherwise get latitude and longitude values of first vertex */
jbe@16 742 lat21 = points2[0].lat;
jbe@16 743 lon21 = points2[0].lon;
jbe@16 744 /* and consider longitude wrap-around for first vertex */
jbe@16 745 if (lon_dir2<0 && lon21>lon_break2) lon21 = pgl_round(lon21-360);
jbe@16 746 else if (lon_dir2>0 && lon21<lon_break2) lon21 = pgl_round(lon21+360);
jbe@16 747 }
jbe@16 748 /* get latitude and longitude of next vertex */
jbe@16 749 lat22 = points2[k2].lat;
jbe@16 750 lon22 = points2[k2].lon;
jbe@16 751 /* consider longitude wrap-around for next vertex */
jbe@16 752 if (lon_dir2<0 && lon22>lon_break2) lon22 = pgl_round(lon22-360);
jbe@16 753 else if (lon_dir2>0 && lon22<lon_break2) lon22 = pgl_round(lon22+360);
jbe@16 754 /* skip degenerated edges */
jbe@16 755 if (lat21 == lat22 && lon21 == lon22) continue;
jbe@16 756 /* perform another wrap-around where necessary */
jbe@16 757 /* TODO: improve performance of whole wrap-around mechanism */
jbe@16 758 wrapvalue = (lon21 + lon22) - (lon11 + lon12);
jbe@16 759 if (wrapvalue > 360) {
jbe@16 760 lon21 = pgl_round(lon21 - 360);
jbe@16 761 lon22 = pgl_round(lon22 - 360);
jbe@16 762 } else if (wrapvalue < -360) {
jbe@16 763 lon21 = pgl_round(lon21 + 360);
jbe@16 764 lon22 = pgl_round(lon22 + 360);
jbe@16 765 }
jbe@16 766 /* return true if segments overlap */
jbe@16 767 if (
jbe@16 768 pgl_lseg_crosses_line(
jbe@16 769 lat11, lon11, lat12, lon12,
jbe@20 770 lat21, lon21, lat22, lon22
jbe@16 771 ) && pgl_lseg_crosses_line(
jbe@16 772 lat21, lon21, lat22, lon22,
jbe@20 773 lat11, lon11, lat12, lon12
jbe@16 774 )
jbe@16 775 ) {
jbe@16 776 return true;
jbe@16 777 }
jbe@16 778 }
jbe@16 779 }
jbe@16 780 }
jbe@16 781 }
jbe@16 782 /* otherwise return false */
jbe@16 783 return false;
jbe@16 784 }
jbe@16 785
jbe@16 786 /* check if second cluster is completely contained in first cluster */
jbe@16 787 static bool pgl_cluster_in_cluster(pgl_cluster *outer, pgl_cluster *inner) {
jbe@20 788 if (!pgl_all_cluster_points_strictly_in_cluster(outer, inner)) return false;
jbe@20 789 if (pgl_any_cluster_points_in_cluster(inner, outer)) return false;
jbe@20 790 if (pgl_outlines_overlap(outer, inner)) return false;
jbe@16 791 return true;
jbe@16 792 }
jbe@16 793
jbe@16 794 /* check if two clusters overlap */
jbe@16 795 static bool pgl_clusters_overlap(
jbe@16 796 pgl_cluster *cluster1, pgl_cluster *cluster2
jbe@16 797 ) {
jbe@16 798 if (pgl_any_cluster_points_in_cluster(cluster1, cluster2)) return true;
jbe@16 799 if (pgl_any_cluster_points_in_cluster(cluster2, cluster1)) return true;
jbe@20 800 if (pgl_outlines_overlap(cluster1, cluster2)) return true;
jbe@16 801 return false;
jbe@16 802 }
jbe@16 803
jbe@16 804
jbe@0 805 /* calculate (approximate) distance between point and cluster */
jbe@0 806 static double pgl_point_cluster_distance(pgl_point *point, pgl_cluster *cluster) {
jbe@24 807 double comp; /* square of compression of meridians */
jbe@0 808 int i, j, k; /* i: entry, j: point in entry, k: next point in entry */
jbe@0 809 int entrytype; /* type of entry */
jbe@0 810 int npoints; /* number of points in entry */
jbe@0 811 pgl_point *points; /* array of points in entry */
jbe@0 812 int lon_dir = 0; /* first vertex west (-1) or east (+1) */
jbe@0 813 double lon_break = 0; /* antipodal longitude of first vertex */
jbe@0 814 double lon_min = 0; /* minimum (adjusted) longitude of entry vertices */
jbe@0 815 double lon_max = 0; /* maximum (adjusted) longitude of entry vertices */
jbe@0 816 double lat0 = point->lat; /* latitude of point */
jbe@0 817 double lon0; /* (adjusted) longitude of point */
jbe@0 818 double lat1, lon1; /* latitude and (adjusted) longitude of vertex */
jbe@0 819 double lat2, lon2; /* latitude and (adjusted) longitude of next vertex */
jbe@0 820 double s; /* scalar for vector calculations */
jbe@0 821 double dist; /* distance calculated in one step */
jbe@0 822 double min_dist = INFINITY; /* minimum distance */
jbe@0 823 /* distance is zero if point is contained in cluster */
jbe@20 824 if (pgl_point_in_cluster(point, cluster, false)) return 0;
jbe@30 825 /* calculate approximate square compression of meridians */
jbe@24 826 comp = cos((lat0 / 180.0) * M_PI);
jbe@24 827 comp *= comp;
jbe@30 828 /* calculate exact square compression of meridians */
jbe@30 829 comp *= (
jbe@30 830 (1.0 - PGL_EPS2 * (1.0-comp)) *
jbe@30 831 (1.0 - PGL_EPS2 * (1.0-comp)) /
jbe@30 832 (PGL_SUBEPS2 * PGL_SUBEPS2)
jbe@30 833 );
jbe@0 834 /* iterate over all entries */
jbe@0 835 for (i=0; i<cluster->nentries; i++) {
jbe@0 836 /* get properties of entry */
jbe@0 837 entrytype = cluster->entries[i].entrytype;
jbe@0 838 npoints = cluster->entries[i].npoints;
jbe@0 839 points = PGL_ENTRY_POINTS(cluster, i);
jbe@0 840 /* determine east/west orientation of first point of entry and calculate
jbe@0 841 antipodal longitude */
jbe@0 842 lon_break = points[0].lon;
jbe@0 843 if (lon_break < 0) { lon_dir = -1; lon_break += 180; }
jbe@0 844 else if (lon_break > 0) { lon_dir = 1; lon_break -= 180; }
jbe@0 845 else lon_dir = 0;
jbe@0 846 /* determine covered longitude range */
jbe@0 847 for (j=0; j<npoints; j++) {
jbe@0 848 /* get longitude of vertex */
jbe@0 849 lon1 = points[j].lon;
jbe@0 850 /* adjust longitude to fix potential wrap-around */
jbe@0 851 if (lon_dir < 0 && lon1 > lon_break) lon1 -= 360;
jbe@0 852 else if (lon_dir > 0 && lon1 < lon_break) lon1 += 360;
jbe@0 853 /* update minimum and maximum longitude of polygon */
jbe@0 854 if (j == 0 || lon1 < lon_min) lon_min = lon1;
jbe@0 855 if (j == 0 || lon1 > lon_max) lon_max = lon1;
jbe@0 856 }
jbe@0 857 /* adjust longitude wrap-around according to full longitude range */
jbe@0 858 lon_break = (lon_max + lon_min) / 2;
jbe@0 859 if (lon_break < 0) { lon_dir = -1; lon_break += 180; }
jbe@0 860 else if (lon_break > 0) { lon_dir = 1; lon_break -= 180; }
jbe@0 861 /* get longitude of point */
jbe@0 862 lon0 = point->lon;
jbe@0 863 /* consider longitude wrap-around for point */
jbe@0 864 if (lon_dir < 0 && lon0 > lon_break) lon0 -= 360;
jbe@0 865 else if (lon_dir > 0 && lon0 < lon_break) lon0 += 360;
jbe@0 866 /* iterate over all edges and vertices */
jbe@0 867 for (j=0; j<npoints; j++) {
jbe@16 868 /* use previously calculated values for lat1 and lon1 if possible */
jbe@16 869 if (j) {
jbe@16 870 lat1 = lat2;
jbe@16 871 lon1 = lon2;
jbe@16 872 } else {
jbe@16 873 /* otherwise get latitude and longitude values of first vertex */
jbe@16 874 lat1 = points[0].lat;
jbe@16 875 lon1 = points[0].lon;
jbe@16 876 /* and consider longitude wrap-around for first vertex */
jbe@16 877 if (lon_dir < 0 && lon1 > lon_break) lon1 -= 360;
jbe@16 878 else if (lon_dir > 0 && lon1 < lon_break) lon1 += 360;
jbe@16 879 }
jbe@0 880 /* calculate distance to vertex */
jbe@0 881 dist = pgl_distance(lat0, lon0, lat1, lon1);
jbe@0 882 /* store calculated distance if smallest */
jbe@0 883 if (dist < min_dist) min_dist = dist;
jbe@0 884 /* calculate index of next vertex */
jbe@0 885 k = (j+1) % npoints;
jbe@0 886 /* skip last edge unless entry is (closed) outline or polygon */
jbe@0 887 if (
jbe@0 888 k == 0 &&
jbe@0 889 entrytype != PGL_ENTRY_OUTLINE &&
jbe@0 890 entrytype != PGL_ENTRY_POLYGON
jbe@0 891 ) continue;
jbe@16 892 /* get latitude and longitude of next vertex */
jbe@0 893 lat2 = points[k].lat;
jbe@0 894 lon2 = points[k].lon;
jbe@16 895 /* consider longitude wrap-around for next vertex */
jbe@0 896 if (lon_dir < 0 && lon2 > lon_break) lon2 -= 360;
jbe@0 897 else if (lon_dir > 0 && lon2 < lon_break) lon2 += 360;
jbe@0 898 /* go to next vertex and edge if edge is degenerated */
jbe@0 899 if (lat1 == lat2 && lon1 == lon2) continue;
jbe@0 900 /* otherwise test if point can be projected onto edge of polygon */
jbe@0 901 s = (
jbe@24 902 ((lat0-lat1) * (lat2-lat1) + comp * (lon0-lon1) * (lon2-lon1)) /
jbe@24 903 ((lat2-lat1) * (lat2-lat1) + comp * (lon2-lon1) * (lon2-lon1))
jbe@0 904 );
jbe@0 905 /* go to next vertex and edge if point cannot be projected */
jbe@0 906 if (!(s > 0 && s < 1)) continue;
jbe@0 907 /* calculate distance from original point to projected point */
jbe@0 908 dist = pgl_distance(
jbe@0 909 lat0, lon0,
jbe@0 910 lat1 + s * (lat2-lat1),
jbe@0 911 lon1 + s * (lon2-lon1)
jbe@0 912 );
jbe@0 913 /* store calculated distance if smallest */
jbe@0 914 if (dist < min_dist) min_dist = dist;
jbe@0 915 }
jbe@0 916 }
jbe@0 917 /* return minimum distance */
jbe@0 918 return min_dist;
jbe@0 919 }
jbe@0 920
jbe@16 921 /* calculate (approximate) distance between two clusters */
jbe@16 922 static double pgl_cluster_distance(pgl_cluster *cluster1, pgl_cluster *cluster2) {
jbe@16 923 int i, j; /* i: entry, j: point in entry */
jbe@16 924 int npoints; /* number of points in entry */
jbe@16 925 pgl_point *points; /* array of points in entry */
jbe@16 926 double dist; /* distance calculated in one step */
jbe@16 927 double min_dist = INFINITY; /* minimum distance */
jbe@16 928 /* consider distance from each point in one cluster to the whole other */
jbe@16 929 for (i=0; i<cluster1->nentries; i++) {
jbe@16 930 npoints = cluster1->entries[i].npoints;
jbe@16 931 points = PGL_ENTRY_POINTS(cluster1, i);
jbe@16 932 for (j=0; j<npoints; j++) {
jbe@16 933 dist = pgl_point_cluster_distance(points+j, cluster2);
jbe@16 934 if (dist == 0) return dist;
jbe@16 935 if (dist < min_dist) min_dist = dist;
jbe@16 936 }
jbe@16 937 }
jbe@16 938 /* consider distance from each point in other cluster to the first cluster */
jbe@16 939 for (i=0; i<cluster2->nentries; i++) {
jbe@16 940 npoints = cluster2->entries[i].npoints;
jbe@16 941 points = PGL_ENTRY_POINTS(cluster2, i);
jbe@16 942 for (j=0; j<npoints; j++) {
jbe@16 943 dist = pgl_point_cluster_distance(points+j, cluster1);
jbe@16 944 if (dist == 0) return dist;
jbe@16 945 if (dist < min_dist) min_dist = dist;
jbe@16 946 }
jbe@16 947 }
jbe@16 948 return min_dist;
jbe@16 949 }
jbe@16 950
jbe@0 951 /* estimator function for distance between box and point */
jbe@16 952 /* always returns a smaller value than actually correct or zero */
jbe@0 953 static double pgl_estimate_point_box_distance(pgl_point *point, pgl_box *box) {
jbe@16 954 double dlon; /* longitude range of box (delta longitude) */
jbe@16 955 double distance; /* return value */
jbe@16 956 /* return infinity if box is empty */
jbe@0 957 if (box->lat_min > box->lat_max) return INFINITY;
jbe@16 958 /* return zero if point is inside box */
jbe@0 959 if (pgl_point_in_box(point, box)) return 0;
jbe@0 960 /* calculate delta longitude */
jbe@0 961 dlon = box->lon_max - box->lon_min;
jbe@0 962 if (dlon < 0) dlon += 360; /* 180th meridian crossed */
jbe@16 963 /* if delta longitude is greater than 150 degrees, perform safe fall-back */
jbe@16 964 if (dlon > 150) return 0;
jbe@16 965 /* calculate lower limit for distance (formula below requires dlon <= 150) */
jbe@16 966 /* TODO: provide better estimation function to improve performance */
jbe@16 967 distance = (
jbe@16 968 (1.0-1e-14) * pgl_distance(
jbe@16 969 point->lat,
jbe@16 970 point->lon,
jbe@16 971 (box->lat_min + box->lat_max) / 2,
jbe@16 972 box->lon_min + dlon/2
jbe@16 973 ) - pgl_distance(
jbe@16 974 box->lat_min, box->lon_min,
jbe@16 975 box->lat_max, box->lon_max
jbe@16 976 )
jbe@16 977 );
jbe@16 978 /* truncate negative results to zero */
jbe@16 979 if (distance <= 0) distance = 0;
jbe@16 980 /* return result */
jbe@16 981 return distance;
jbe@0 982 }
jbe@0 983
jbe@0 984
jbe@42 985 /*-------------------------------*
jbe@42 986 * Monte Carlo based functions *
jbe@42 987 *-------------------------------*/
jbe@42 988
jbe@42 989 /* half of (spherical) earth's surface area */
jbe@42 990 #define PGL_HALF_SURFACE (PGL_RADIUS * PGL_DIAMETER * M_PI)
jbe@42 991
jbe@42 992 /* golden angle in radians */
jbe@42 993 #define PGL_GOLDEN_ANGLE (M_PI * (sqrt(5) - 1.0))
jbe@42 994
jbe@42 995 /* create a list of sample points covering a bounding circle
jbe@42 996 and return covered area */
jbe@42 997 static double pgl_sample_points(
jbe@42 998 pgl_point *center, /* center of bounding circle */
jbe@42 999 double radius, /* radius of bounding circle */
jbe@42 1000 int samples, /* number of sample points */
jbe@42 1001 pgl_point *result /* pointer to result array */
jbe@42 1002 ) {
jbe@42 1003 double double_share = 2.0; /* double of covered share of earth's surface */
jbe@42 1004 double double_share_div_samples; /* double_share divided by sample count */
jbe@42 1005 int i;
jbe@42 1006 double t; /* parameter of spiral laid on (spherical) earth's surface */
jbe@42 1007 double x, y, z; /* normalized coordinates of point on non-rotated spiral */
jbe@42 1008 double sin_phi; /* sine of sph. coordinate of point of non-rotated spiral */
jbe@42 1009 double lambda; /* other sph. coordinate of point of non-rotated spiral */
jbe@42 1010 double rot = (0.5 - center->lat / 180.0) * M_PI; /* needed rot. (in rad) */
jbe@42 1011 double cos_rot = cos(rot); /* cosine of rotation by latitude */
jbe@42 1012 double sin_rot = sin(rot); /* sine of rotation by latitude */
jbe@42 1013 double x_rot, z_rot; /* normalized coordinates of point on rotated spiral */
jbe@42 1014 double center_lon = center->lon; /* second rotation in degree */
jbe@42 1015 /* add safety margin to bounding circle because of spherical approximation */
jbe@42 1016 radius *= PGL_SPHEROID_A / PGL_RADIUS;
jbe@42 1017 /* if whole earth is covered, use initialized value, otherwise calculate
jbe@42 1018 share of covered area (multiplied by 2) */
jbe@42 1019 if (radius < PGL_MAXDIST) double_share = 1.0 - cos(radius / PGL_RADIUS);
jbe@42 1020 /* divide double_share by sample count for later calculations */
jbe@42 1021 double_share_div_samples = double_share / samples;
jbe@42 1022 /* generate sample points */
jbe@42 1023 for (i=0; i<samples; i++) {
jbe@42 1024 /* use an offset of 1/2 to avoid too dense clustering at spiral center */
jbe@42 1025 t = 0.5 + i;
jbe@42 1026 /* calculate normalized coordinates of point on non-rotated spiral */
jbe@42 1027 z = 1.0 - double_share_div_samples * t;
jbe@42 1028 sin_phi = sqrt(1.0 - z*z);
jbe@42 1029 lambda = t * PGL_GOLDEN_ANGLE;
jbe@42 1030 x = sin_phi * cos(lambda);
jbe@42 1031 y = sin_phi * sin(lambda);
jbe@42 1032 /* rotate spiral by latitude value of bounding circle */
jbe@42 1033 x_rot = cos_rot * x + sin_rot * z;
jbe@42 1034 z_rot = cos_rot * z - sin_rot * x;
jbe@42 1035 /* set resulting sample point in result array */
jbe@42 1036 /* (while performing second rotation by bounding circle longitude) */
jbe@42 1037 result[i].lat = 180.0 * (atan(z_rot / fabs(x_rot)) / M_PI);
jbe@42 1038 result[i].lon = center_lon + 180.0 * (atan2(y, x_rot) / M_PI);
jbe@42 1039 }
jbe@42 1040 /* return covered area */
jbe@42 1041 return PGL_HALF_SURFACE * double_share;
jbe@42 1042 }
jbe@42 1043
jbe@42 1044 /* calculate covered area using Monte Carlo method */
jbe@42 1045 /* TODO: inefficient, should be replaced by different method */
jbe@42 1046 static double pgl_monte_carlo_area(pgl_cluster *cluster, int samples) {
jbe@42 1047 pgl_point *points;
jbe@42 1048 double area;
jbe@42 1049 int i;
jbe@42 1050 int matches = 0;
jbe@42 1051 if (samples > PGL_CLUSTER_MAXPOINTS) {
jbe@42 1052 ereport(ERROR, (
jbe@42 1053 errcode(ERRCODE_DATA_EXCEPTION),
jbe@42 1054 errmsg(
jbe@42 1055 "too many sample points for Monte Carlo method (maximum %i)",
jbe@42 1056 PGL_CLUSTER_MAXPOINTS
jbe@42 1057 )
jbe@42 1058 ));
jbe@42 1059 }
jbe@42 1060 if (!(cluster->bounding.radius > 0)) return 0;
jbe@42 1061 for (i=0; ; i++) {
jbe@42 1062 if (i == cluster->nentries) return 0;
jbe@42 1063 if (cluster->entries[i].entrytype == PGL_ENTRY_POLYGON) break;
jbe@42 1064 }
jbe@42 1065 points = palloc(samples * sizeof(pgl_point));
jbe@42 1066 area = pgl_sample_points(
jbe@42 1067 &cluster->bounding.center,
jbe@42 1068 cluster->bounding.radius,
jbe@42 1069 samples,
jbe@42 1070 points
jbe@42 1071 );
jbe@42 1072 for (i=0; i<samples; i++) {
jbe@42 1073 if (pgl_point_in_cluster(points+i, cluster, true)) matches++;
jbe@42 1074 }
jbe@42 1075 pfree(points);
jbe@42 1076 return area * ((double)matches / samples);
jbe@42 1077 }
jbe@42 1078
jbe@42 1079 /* fair distance between point and cluster (see README file for explanation) */
jbe@42 1080 static double pgl_fair_distance(
jbe@42 1081 pgl_point *point, pgl_cluster *cluster, int samples
jbe@42 1082 ) {
jbe@42 1083 double distance; /* shortest distance from point to cluster */
jbe@42 1084 pgl_point *points; /* sample points for Monte Carlo method */
jbe@42 1085 double area; /* area covered by sample points */
jbe@42 1086 int i;
jbe@42 1087 int matches = 0; /* number of points within enlarged area (multiplied
jbe@42 1088 by two to be able to store half matches) */
jbe@42 1089 double result; /* result determined by Monte Carlo method */
jbe@42 1090 /* limit sample count to avoid integer overflows on memory allocation */
jbe@42 1091 if (samples > PGL_CLUSTER_MAXPOINTS) {
jbe@42 1092 ereport(ERROR, (
jbe@42 1093 errcode(ERRCODE_DATA_EXCEPTION),
jbe@42 1094 errmsg(
jbe@42 1095 "too many sample points for Monte Carlo method (maximum %i)",
jbe@42 1096 PGL_CLUSTER_MAXPOINTS
jbe@42 1097 )
jbe@42 1098 ));
jbe@42 1099 }
jbe@42 1100 /* calculate shortest distance from point to cluster */
jbe@42 1101 distance = pgl_point_cluster_distance(point, cluster);
jbe@42 1102 /* if cluster consists of a single point or has no bounding circle with
jbe@42 1103 positive radius, simply return distance */
jbe@42 1104 if (
jbe@42 1105 (cluster->nentries==1 && cluster->entries[0].entrytype==PGL_ENTRY_POINT) ||
jbe@42 1106 !(cluster->bounding.radius > 0)
jbe@42 1107 ) return distance;
jbe@42 1108 /* if cluster consists of two points which are twice as far apart, return
jbe@42 1109 distance between point and cluster multiplied by square root of two */
jbe@42 1110 if (
jbe@42 1111 cluster->nentries == 2 &&
jbe@42 1112 cluster->entries[0].entrytype == PGL_ENTRY_POINT &&
jbe@42 1113 cluster->entries[1].entrytype == PGL_ENTRY_POINT &&
jbe@42 1114 pgl_distance(
jbe@42 1115 PGL_ENTRY_POINTS(cluster, 0)[0].lat,
jbe@42 1116 PGL_ENTRY_POINTS(cluster, 0)[0].lon,
jbe@42 1117 PGL_ENTRY_POINTS(cluster, 1)[0].lat,
jbe@42 1118 PGL_ENTRY_POINTS(cluster, 1)[0].lon
jbe@42 1119 ) >= 2.0 * distance
jbe@42 1120 ) {
jbe@42 1121 return distance * M_SQRT2;
jbe@42 1122 }
jbe@42 1123 /* otherwise create sample points for Monte Carlo method and determine area
jbe@42 1124 covered by sample points */
jbe@42 1125 points = palloc(samples * sizeof(pgl_point));
jbe@42 1126 area = pgl_sample_points(
jbe@42 1127 &cluster->bounding.center,
jbe@42 1128 cluster->bounding.radius + distance, /* pad bounding circle by distance */
jbe@42 1129 samples,
jbe@42 1130 points
jbe@42 1131 );
jbe@42 1132 /* perform Monte Carlo method */
jbe@42 1133 if (distance > 0) {
jbe@42 1134 /* point is outside cluster */
jbe@42 1135 for (i=0; i<samples; i++) {
jbe@42 1136 /* count sample poitns within cluster as half match */
jbe@42 1137 if (pgl_point_in_cluster(points+i, cluster, true)) matches += 1;
jbe@42 1138 /* count sample points outside of cluster but within cluster grown by
jbe@42 1139 distance as full match */
jbe@42 1140 else if (
jbe@42 1141 pgl_point_cluster_distance(points+i, cluster) < distance
jbe@42 1142 ) matches += 2;
jbe@42 1143 }
jbe@42 1144 } else {
jbe@42 1145 /* if point is within cluster,
jbe@42 1146 just count sample points within cluster as half match */
jbe@42 1147 for (i=0; i<samples; i++) {
jbe@42 1148 if (pgl_point_in_cluster(points+i, cluster, true)) matches += 1;
jbe@42 1149 }
jbe@42 1150 }
jbe@42 1151 /* release memory for sample points needed by Monte Carlo method */
jbe@42 1152 pfree(points);
jbe@42 1153 /* convert area determined by Monte Carlo method into distance
jbe@42 1154 (i.e. radius of circle with the same area) */
jbe@42 1155 result = sqrt(area * ((double)matches / 2.0 / samples) / M_PI);
jbe@42 1156 /* return result only if it is greater than the distance between point and
jbe@42 1157 cluster to avoid unexpected results because of errors due to limited
jbe@42 1158 precision */
jbe@42 1159 if (result > distance) return result;
jbe@42 1160 /* otherwise return distance between point and cluster */
jbe@42 1161 else return distance;
jbe@42 1162 }
jbe@42 1163
jbe@42 1164
jbe@16 1165 /*-------------------------------------------------*
jbe@16 1166 * geographic index based on space-filling curve *
jbe@16 1167 *-------------------------------------------------*/
jbe@0 1168
jbe@0 1169 /* number of bytes used for geographic (center) position in keys */
jbe@0 1170 #define PGL_KEY_LATLON_BYTELEN 7
jbe@0 1171
jbe@0 1172 /* maximum reference value for logarithmic size of geographic objects */
jbe@0 1173 #define PGL_AREAKEY_REFOBJSIZE (PGL_DIAMETER/3.0) /* can be tweaked */
jbe@0 1174
jbe@0 1175 /* pointer to index key (either pgl_pointkey or pgl_areakey) */
jbe@0 1176 typedef unsigned char *pgl_keyptr;
jbe@0 1177
jbe@0 1178 /* index key for points (objects with zero area) on the spheroid */
jbe@0 1179 /* bit 0..55: interspersed bits of latitude and longitude,
jbe@0 1180 bit 56..57: always zero,
jbe@0 1181 bit 58..63: node depth in hypothetic (full) tree from 0 to 56 (incl.) */
jbe@0 1182 typedef unsigned char pgl_pointkey[PGL_KEY_LATLON_BYTELEN+1];
jbe@0 1183
jbe@0 1184 /* index key for geographic objects on spheroid with area greater than zero */
jbe@0 1185 /* bit 0..55: interspersed bits of latitude and longitude of center point,
jbe@0 1186 bit 56: always set to 1,
jbe@0 1187 bit 57..63: node depth in hypothetic (full) tree from 0 to (2*56)+1 (incl.),
jbe@0 1188 bit 64..71: logarithmic object size from 0 to 56+1 = 57 (incl.), but set to
jbe@0 1189 PGL_KEY_OBJSIZE_EMPTY (with interspersed bits = 0 and node depth
jbe@0 1190 = 113) for empty objects, and set to PGL_KEY_OBJSIZE_UNIVERSAL
jbe@0 1191 (with interspersed bits = 0 and node depth = 0) for keys which
jbe@0 1192 cover both empty and non-empty objects */
jbe@0 1193
jbe@0 1194 typedef unsigned char pgl_areakey[PGL_KEY_LATLON_BYTELEN+2];
jbe@0 1195
jbe@0 1196 /* helper macros for reading/writing index keys */
jbe@0 1197 #define PGL_KEY_NODEDEPTH_OFFSET PGL_KEY_LATLON_BYTELEN
jbe@0 1198 #define PGL_KEY_OBJSIZE_OFFSET (PGL_KEY_NODEDEPTH_OFFSET+1)
jbe@0 1199 #define PGL_POINTKEY_MAXDEPTH (PGL_KEY_LATLON_BYTELEN*8)
jbe@0 1200 #define PGL_AREAKEY_MAXDEPTH (2*PGL_POINTKEY_MAXDEPTH+1)
jbe@0 1201 #define PGL_AREAKEY_MAXOBJSIZE (PGL_POINTKEY_MAXDEPTH+1)
jbe@0 1202 #define PGL_AREAKEY_TYPEMASK 0x80
jbe@0 1203 #define PGL_KEY_LATLONBIT(key, n) ((key)[(n)/8] & (0x80 >> ((n)%8)))
jbe@0 1204 #define PGL_KEY_LATLONBIT_DIFF(key1, key2, n) \
jbe@0 1205 ( PGL_KEY_LATLONBIT(key1, n) ^ \
jbe@0 1206 PGL_KEY_LATLONBIT(key2, n) )
jbe@0 1207 #define PGL_KEY_IS_AREAKEY(key) ((key)[PGL_KEY_NODEDEPTH_OFFSET] & \
jbe@0 1208 PGL_AREAKEY_TYPEMASK)
jbe@0 1209 #define PGL_KEY_NODEDEPTH(key) ((key)[PGL_KEY_NODEDEPTH_OFFSET] & \
jbe@0 1210 (PGL_AREAKEY_TYPEMASK-1))
jbe@0 1211 #define PGL_KEY_OBJSIZE(key) ((key)[PGL_KEY_OBJSIZE_OFFSET])
jbe@0 1212 #define PGL_KEY_OBJSIZE_EMPTY 126
jbe@0 1213 #define PGL_KEY_OBJSIZE_UNIVERSAL 127
jbe@0 1214 #define PGL_KEY_IS_EMPTY(key) ( PGL_KEY_IS_AREAKEY(key) && \
jbe@0 1215 (key)[PGL_KEY_OBJSIZE_OFFSET] == \
jbe@0 1216 PGL_KEY_OBJSIZE_EMPTY )
jbe@0 1217 #define PGL_KEY_IS_UNIVERSAL(key) ( PGL_KEY_IS_AREAKEY(key) && \
jbe@0 1218 (key)[PGL_KEY_OBJSIZE_OFFSET] == \
jbe@0 1219 PGL_KEY_OBJSIZE_UNIVERSAL )
jbe@0 1220
jbe@0 1221 /* set area key to match empty objects only */
jbe@0 1222 static void pgl_key_set_empty(pgl_keyptr key) {
jbe@0 1223 memset(key, 0, sizeof(pgl_areakey));
jbe@0 1224 /* Note: setting node depth to maximum is required for picksplit function */
jbe@0 1225 key[PGL_KEY_NODEDEPTH_OFFSET] = PGL_AREAKEY_TYPEMASK | PGL_AREAKEY_MAXDEPTH;
jbe@0 1226 key[PGL_KEY_OBJSIZE_OFFSET] = PGL_KEY_OBJSIZE_EMPTY;
jbe@0 1227 }
jbe@0 1228
jbe@0 1229 /* set area key to match any object (including empty objects) */
jbe@0 1230 static void pgl_key_set_universal(pgl_keyptr key) {
jbe@0 1231 memset(key, 0, sizeof(pgl_areakey));
jbe@0 1232 key[PGL_KEY_NODEDEPTH_OFFSET] = PGL_AREAKEY_TYPEMASK;
jbe@0 1233 key[PGL_KEY_OBJSIZE_OFFSET] = PGL_KEY_OBJSIZE_UNIVERSAL;
jbe@0 1234 }
jbe@0 1235
jbe@0 1236 /* convert a point on earth into a max-depth key to be used in index */
jbe@0 1237 static void pgl_point_to_key(pgl_point *point, pgl_keyptr key) {
jbe@0 1238 double lat = point->lat;
jbe@0 1239 double lon = point->lon;
jbe@0 1240 int i;
jbe@0 1241 /* clear latitude and longitude bits */
jbe@0 1242 memset(key, 0, PGL_KEY_LATLON_BYTELEN);
jbe@0 1243 /* set node depth to maximum and type bit to zero */
jbe@0 1244 key[PGL_KEY_NODEDEPTH_OFFSET] = PGL_POINTKEY_MAXDEPTH;
jbe@0 1245 /* iterate over all latitude/longitude bit pairs */
jbe@0 1246 for (i=0; i<PGL_POINTKEY_MAXDEPTH/2; i++) {
jbe@0 1247 /* determine latitude bit */
jbe@0 1248 if (lat >= 0) {
jbe@0 1249 key[i/4] |= 0x80 >> (2*(i%4));
jbe@0 1250 lat *= 2; lat -= 90;
jbe@0 1251 } else {
jbe@0 1252 lat *= 2; lat += 90;
jbe@0 1253 }
jbe@0 1254 /* determine longitude bit */
jbe@0 1255 if (lon >= 0) {
jbe@0 1256 key[i/4] |= 0x80 >> (2*(i%4)+1);
jbe@0 1257 lon *= 2; lon -= 180;
jbe@0 1258 } else {
jbe@0 1259 lon *= 2; lon += 180;
jbe@0 1260 }
jbe@0 1261 }
jbe@0 1262 }
jbe@0 1263
jbe@0 1264 /* convert a circle on earth into a max-depth key to be used in an index */
jbe@0 1265 static void pgl_circle_to_key(pgl_circle *circle, pgl_keyptr key) {
jbe@0 1266 /* handle special case of empty circle */
jbe@0 1267 if (circle->radius < 0) {
jbe@0 1268 pgl_key_set_empty(key);
jbe@0 1269 return;
jbe@0 1270 }
jbe@0 1271 /* perform same action as for point keys */
jbe@0 1272 pgl_point_to_key(&(circle->center), key);
jbe@0 1273 /* but overwrite type and node depth to fit area index key */
jbe@0 1274 key[PGL_KEY_NODEDEPTH_OFFSET] = PGL_AREAKEY_TYPEMASK | PGL_AREAKEY_MAXDEPTH;
jbe@0 1275 /* check if radius is greater than (or equal to) reference size */
jbe@0 1276 /* (treat equal values as greater values for numerical safety) */
jbe@0 1277 if (circle->radius >= PGL_AREAKEY_REFOBJSIZE) {
jbe@0 1278 /* if yes, set logarithmic size to zero */
jbe@0 1279 key[PGL_KEY_OBJSIZE_OFFSET] = 0;
jbe@0 1280 } else {
jbe@0 1281 /* otherwise, determine logarithmic size iteratively */
jbe@0 1282 /* (one step is equivalent to a factor of sqrt(2)) */
jbe@0 1283 double reference = PGL_AREAKEY_REFOBJSIZE / M_SQRT2;
jbe@0 1284 int objsize = 1;
jbe@0 1285 while (objsize < PGL_AREAKEY_MAXOBJSIZE) {
jbe@0 1286 /* stop when radius is greater than (or equal to) adjusted reference */
jbe@0 1287 /* (treat equal values as greater values for numerical safety) */
jbe@0 1288 if (circle->radius >= reference) break;
jbe@0 1289 reference /= M_SQRT2;
jbe@0 1290 objsize++;
jbe@0 1291 }
jbe@0 1292 /* set logarithmic size to determined value */
jbe@0 1293 key[PGL_KEY_OBJSIZE_OFFSET] = objsize;
jbe@0 1294 }
jbe@0 1295 }
jbe@0 1296
jbe@0 1297 /* check if one key is subkey of another key or vice versa */
jbe@0 1298 static bool pgl_keys_overlap(pgl_keyptr key1, pgl_keyptr key2) {
jbe@0 1299 int i; /* key bit offset (includes both lat/lon and log. obj. size bits) */
jbe@0 1300 /* determine smallest depth */
jbe@0 1301 int depth1 = PGL_KEY_NODEDEPTH(key1);
jbe@0 1302 int depth2 = PGL_KEY_NODEDEPTH(key2);
jbe@0 1303 int depth = (depth1 < depth2) ? depth1 : depth2;
jbe@0 1304 /* check if keys are area keys (assuming that both keys have same type) */
jbe@0 1305 if (PGL_KEY_IS_AREAKEY(key1)) {
jbe@0 1306 int j = 0; /* bit offset for logarithmic object size bits */
jbe@0 1307 int k = 0; /* bit offset for latitude and longitude */
jbe@0 1308 /* fetch logarithmic object size information */
jbe@0 1309 int objsize1 = PGL_KEY_OBJSIZE(key1);
jbe@0 1310 int objsize2 = PGL_KEY_OBJSIZE(key2);
jbe@0 1311 /* handle special cases for empty objects (universal and empty keys) */
jbe@0 1312 if (
jbe@0 1313 objsize1 == PGL_KEY_OBJSIZE_UNIVERSAL ||
jbe@0 1314 objsize2 == PGL_KEY_OBJSIZE_UNIVERSAL
jbe@0 1315 ) return true;
jbe@0 1316 if (
jbe@0 1317 objsize1 == PGL_KEY_OBJSIZE_EMPTY ||
jbe@0 1318 objsize2 == PGL_KEY_OBJSIZE_EMPTY
jbe@0 1319 ) return objsize1 == objsize2;
jbe@0 1320 /* iterate through key bits */
jbe@0 1321 for (i=0; i<depth; i++) {
jbe@0 1322 /* every second bit is a bit describing the object size */
jbe@0 1323 if (i%2 == 0) {
jbe@0 1324 /* check if object size bit is different in both keys (objsize1 and
jbe@0 1325 objsize2 describe the minimum index when object size bit is set) */
jbe@0 1326 if (
jbe@0 1327 (objsize1 <= j && objsize2 > j) ||
jbe@0 1328 (objsize2 <= j && objsize1 > j)
jbe@0 1329 ) {
jbe@0 1330 /* bit differs, therefore keys are in separate branches */
jbe@0 1331 return false;
jbe@0 1332 }
jbe@0 1333 /* increase bit counter for object size bits */
jbe@0 1334 j++;
jbe@0 1335 }
jbe@0 1336 /* all other bits describe latitude and longitude */
jbe@0 1337 else {
jbe@0 1338 /* check if bit differs in both keys */
jbe@0 1339 if (PGL_KEY_LATLONBIT_DIFF(key1, key2, k)) {
jbe@0 1340 /* bit differs, therefore keys are in separate branches */
jbe@0 1341 return false;
jbe@0 1342 }
jbe@0 1343 /* increase bit counter for latitude/longitude bits */
jbe@0 1344 k++;
jbe@0 1345 }
jbe@0 1346 }
jbe@0 1347 }
jbe@0 1348 /* if not, keys are point keys */
jbe@0 1349 else {
jbe@0 1350 /* iterate through key bits */
jbe@0 1351 for (i=0; i<depth; i++) {
jbe@0 1352 /* check if bit differs in both keys */
jbe@0 1353 if (PGL_KEY_LATLONBIT_DIFF(key1, key2, i)) {
jbe@0 1354 /* bit differs, therefore keys are in separate branches */
jbe@0 1355 return false;
jbe@0 1356 }
jbe@0 1357 }
jbe@0 1358 }
jbe@0 1359 /* return true because keys are in the same branch */
jbe@0 1360 return true;
jbe@0 1361 }
jbe@0 1362
jbe@0 1363 /* combine two keys into new key which covers both original keys */
jbe@0 1364 /* (result stored in first argument) */
jbe@0 1365 static void pgl_unite_keys(pgl_keyptr dst, pgl_keyptr src) {
jbe@0 1366 int i; /* key bit offset (includes both lat/lon and log. obj. size bits) */
jbe@0 1367 /* determine smallest depth */
jbe@0 1368 int depth1 = PGL_KEY_NODEDEPTH(dst);
jbe@0 1369 int depth2 = PGL_KEY_NODEDEPTH(src);
jbe@0 1370 int depth = (depth1 < depth2) ? depth1 : depth2;
jbe@0 1371 /* check if keys are area keys (assuming that both keys have same type) */
jbe@0 1372 if (PGL_KEY_IS_AREAKEY(dst)) {
jbe@0 1373 pgl_areakey dstbuf = { 0, }; /* destination buffer (cleared) */
jbe@0 1374 int j = 0; /* bit offset for logarithmic object size bits */
jbe@0 1375 int k = 0; /* bit offset for latitude and longitude */
jbe@0 1376 /* fetch logarithmic object size information */
jbe@0 1377 int objsize1 = PGL_KEY_OBJSIZE(dst);
jbe@0 1378 int objsize2 = PGL_KEY_OBJSIZE(src);
jbe@0 1379 /* handle special cases for empty objects (universal and empty keys) */
jbe@0 1380 if (
jbe@0 1381 objsize1 > PGL_AREAKEY_MAXOBJSIZE ||
jbe@0 1382 objsize2 > PGL_AREAKEY_MAXOBJSIZE
jbe@0 1383 ) {
jbe@0 1384 if (
jbe@0 1385 objsize1 == PGL_KEY_OBJSIZE_EMPTY &&
jbe@0 1386 objsize2 == PGL_KEY_OBJSIZE_EMPTY
jbe@0 1387 ) pgl_key_set_empty(dst);
jbe@0 1388 else pgl_key_set_universal(dst);
jbe@0 1389 return;
jbe@0 1390 }
jbe@0 1391 /* iterate through key bits */
jbe@0 1392 for (i=0; i<depth; i++) {
jbe@0 1393 /* every second bit is a bit describing the object size */
jbe@0 1394 if (i%2 == 0) {
jbe@0 1395 /* increase bit counter for object size bits first */
jbe@0 1396 /* (handy when setting objsize variable) */
jbe@0 1397 j++;
jbe@0 1398 /* check if object size bit is set in neither key */
jbe@0 1399 if (objsize1 >= j && objsize2 >= j) {
jbe@0 1400 /* set objsize in destination buffer to indicate that size bit is
jbe@0 1401 unset in destination buffer at the current bit position */
jbe@0 1402 dstbuf[PGL_KEY_OBJSIZE_OFFSET] = j;
jbe@0 1403 }
jbe@0 1404 /* break if object size bit is set in one key only */
jbe@0 1405 else if (objsize1 >= j || objsize2 >= j) break;
jbe@0 1406 }
jbe@0 1407 /* all other bits describe latitude and longitude */
jbe@0 1408 else {
jbe@0 1409 /* break if bit differs in both keys */
jbe@0 1410 if (PGL_KEY_LATLONBIT(dst, k)) {
jbe@0 1411 if (!PGL_KEY_LATLONBIT(src, k)) break;
jbe@0 1412 /* but set bit in destination buffer if bit is set in both keys */
jbe@0 1413 dstbuf[k/8] |= 0x80 >> (k%8);
jbe@0 1414 } else if (PGL_KEY_LATLONBIT(src, k)) break;
jbe@0 1415 /* increase bit counter for latitude/longitude bits */
jbe@0 1416 k++;
jbe@0 1417 }
jbe@0 1418 }
jbe@0 1419 /* set common node depth and type bit (type bit = 1) */
jbe@0 1420 dstbuf[PGL_KEY_NODEDEPTH_OFFSET] = PGL_AREAKEY_TYPEMASK | i;
jbe@0 1421 /* copy contents of destination buffer to first key */
jbe@0 1422 memcpy(dst, dstbuf, sizeof(pgl_areakey));
jbe@0 1423 }
jbe@0 1424 /* if not, keys are point keys */
jbe@0 1425 else {
jbe@0 1426 pgl_pointkey dstbuf = { 0, }; /* destination buffer (cleared) */
jbe@0 1427 /* iterate through key bits */
jbe@0 1428 for (i=0; i<depth; i++) {
jbe@0 1429 /* break if bit differs in both keys */
jbe@0 1430 if (PGL_KEY_LATLONBIT(dst, i)) {
jbe@0 1431 if (!PGL_KEY_LATLONBIT(src, i)) break;
jbe@0 1432 /* but set bit in destination buffer if bit is set in both keys */
jbe@0 1433 dstbuf[i/8] |= 0x80 >> (i%8);
jbe@0 1434 } else if (PGL_KEY_LATLONBIT(src, i)) break;
jbe@0 1435 }
jbe@0 1436 /* set common node depth (type bit = 0) */
jbe@0 1437 dstbuf[PGL_KEY_NODEDEPTH_OFFSET] = i;
jbe@0 1438 /* copy contents of destination buffer to first key */
jbe@0 1439 memcpy(dst, dstbuf, sizeof(pgl_pointkey));
jbe@0 1440 }
jbe@0 1441 }
jbe@0 1442
jbe@0 1443 /* determine center(!) boundaries and radius estimation of index key */
jbe@0 1444 static double pgl_key_to_box(pgl_keyptr key, pgl_box *box) {
jbe@0 1445 int i;
jbe@0 1446 /* determine node depth */
jbe@0 1447 int depth = PGL_KEY_NODEDEPTH(key);
jbe@0 1448 /* center point of possible result */
jbe@0 1449 double lat = 0;
jbe@0 1450 double lon = 0;
jbe@0 1451 /* maximum distance of real center point from key center */
jbe@0 1452 double dlat = 90;
jbe@0 1453 double dlon = 180;
jbe@0 1454 /* maximum radius of contained objects */
jbe@0 1455 double radius = 0; /* always return zero for point index keys */
jbe@0 1456 /* check if key is area key */
jbe@0 1457 if (PGL_KEY_IS_AREAKEY(key)) {
jbe@0 1458 /* get logarithmic object size */
jbe@0 1459 int objsize = PGL_KEY_OBJSIZE(key);
jbe@0 1460 /* handle special cases for empty objects (universal and empty keys) */
jbe@0 1461 if (objsize == PGL_KEY_OBJSIZE_EMPTY) {
jbe@0 1462 pgl_box_set_empty(box);
jbe@0 1463 return 0;
jbe@0 1464 } else if (objsize == PGL_KEY_OBJSIZE_UNIVERSAL) {
jbe@0 1465 box->lat_min = -90;
jbe@0 1466 box->lat_max = 90;
jbe@0 1467 box->lon_min = -180;
jbe@0 1468 box->lon_max = 180;
jbe@0 1469 return 0; /* any value >= 0 would do */
jbe@0 1470 }
jbe@0 1471 /* calculate maximum possible radius of objects covered by the given key */
jbe@0 1472 if (objsize == 0) radius = INFINITY;
jbe@0 1473 else {
jbe@0 1474 radius = PGL_AREAKEY_REFOBJSIZE;
jbe@0 1475 while (--objsize) radius /= M_SQRT2;
jbe@0 1476 }
jbe@0 1477 /* iterate over latitude and longitude bits in key */
jbe@0 1478 /* (every second bit is a latitude or longitude bit) */
jbe@0 1479 for (i=0; i<depth/2; i++) {
jbe@0 1480 /* check if latitude bit */
jbe@0 1481 if (i%2 == 0) {
jbe@0 1482 /* cut latitude dimension in half */
jbe@0 1483 dlat /= 2;
jbe@0 1484 /* increase center latitude if bit is 1, otherwise decrease */
jbe@0 1485 if (PGL_KEY_LATLONBIT(key, i)) lat += dlat;
jbe@0 1486 else lat -= dlat;
jbe@0 1487 }
jbe@0 1488 /* otherwise longitude bit */
jbe@0 1489 else {
jbe@0 1490 /* cut longitude dimension in half */
jbe@0 1491 dlon /= 2;
jbe@0 1492 /* increase center longitude if bit is 1, otherwise decrease */
jbe@0 1493 if (PGL_KEY_LATLONBIT(key, i)) lon += dlon;
jbe@0 1494 else lon -= dlon;
jbe@0 1495 }
jbe@0 1496 }
jbe@0 1497 }
jbe@0 1498 /* if not, keys are point keys */
jbe@0 1499 else {
jbe@0 1500 /* iterate over all bits in key */
jbe@0 1501 for (i=0; i<depth; i++) {
jbe@0 1502 /* check if latitude bit */
jbe@0 1503 if (i%2 == 0) {
jbe@0 1504 /* cut latitude dimension in half */
jbe@0 1505 dlat /= 2;
jbe@0 1506 /* increase center latitude if bit is 1, otherwise decrease */
jbe@0 1507 if (PGL_KEY_LATLONBIT(key, i)) lat += dlat;
jbe@0 1508 else lat -= dlat;
jbe@0 1509 }
jbe@0 1510 /* otherwise longitude bit */
jbe@0 1511 else {
jbe@0 1512 /* cut longitude dimension in half */
jbe@0 1513 dlon /= 2;
jbe@0 1514 /* increase center longitude if bit is 1, otherwise decrease */
jbe@0 1515 if (PGL_KEY_LATLONBIT(key, i)) lon += dlon;
jbe@0 1516 else lon -= dlon;
jbe@0 1517 }
jbe@0 1518 }
jbe@0 1519 }
jbe@0 1520 /* calculate boundaries from center point and remaining dlat and dlon */
jbe@0 1521 /* (return values through pointer to box) */
jbe@0 1522 box->lat_min = lat - dlat;
jbe@0 1523 box->lat_max = lat + dlat;
jbe@0 1524 box->lon_min = lon - dlon;
jbe@0 1525 box->lon_max = lon + dlon;
jbe@0 1526 /* return radius (as a function return value) */
jbe@0 1527 return radius;
jbe@0 1528 }
jbe@0 1529
jbe@0 1530 /* estimator function for distance between point and index key */
jbe@16 1531 /* always returns a smaller value than actually correct or zero */
jbe@0 1532 static double pgl_estimate_key_distance(pgl_keyptr key, pgl_point *point) {
jbe@0 1533 pgl_box box; /* center(!) bounding box of area index key */
jbe@0 1534 /* calculate center(!) bounding box and maximum radius of objects covered
jbe@0 1535 by area index key (radius is zero for point index keys) */
jbe@0 1536 double distance = pgl_key_to_box(key, &box);
jbe@0 1537 /* calculate estimated distance between bounding box of center point of
jbe@0 1538 indexed object and point passed as second argument, then substract maximum
jbe@0 1539 radius of objects covered by index key */
jbe@16 1540 distance = pgl_estimate_point_box_distance(point, &box) - distance;
jbe@0 1541 /* truncate negative results to zero */
jbe@0 1542 if (distance <= 0) distance = 0;
jbe@0 1543 /* return result */
jbe@0 1544 return distance;
jbe@0 1545 }
jbe@0 1546
jbe@0 1547
jbe@0 1548 /*---------------------------------*
jbe@0 1549 * helper functions for text I/O *
jbe@0 1550 *---------------------------------*/
jbe@0 1551
jbe@0 1552 #define PGL_NUMBUFLEN 64 /* buffer size for number to string conversion */
jbe@0 1553
jbe@0 1554 /* convert floating point number to string (round-trip safe) */
jbe@0 1555 static void pgl_print_float(char *buf, double flt) {
jbe@0 1556 /* check if number is integral */
jbe@0 1557 if (trunc(flt) == flt) {
jbe@0 1558 /* for integral floats use maximum precision */
jbe@0 1559 snprintf(buf, PGL_NUMBUFLEN, "%.17g", flt);
jbe@0 1560 } else {
jbe@0 1561 /* otherwise check if 15, 16, or 17 digits needed (round-trip safety) */
jbe@0 1562 snprintf(buf, PGL_NUMBUFLEN, "%.15g", flt);
jbe@0 1563 if (strtod(buf, NULL) != flt) snprintf(buf, PGL_NUMBUFLEN, "%.16g", flt);
jbe@0 1564 if (strtod(buf, NULL) != flt) snprintf(buf, PGL_NUMBUFLEN, "%.17g", flt);
jbe@0 1565 }
jbe@0 1566 }
jbe@0 1567
jbe@0 1568 /* convert latitude floating point number (in degrees) to string */
jbe@0 1569 static void pgl_print_lat(char *buf, double lat) {
jbe@0 1570 if (signbit(lat)) {
jbe@0 1571 /* treat negative latitudes (including -0) as south */
jbe@0 1572 snprintf(buf, PGL_NUMBUFLEN, "S%015.12f", -lat);
jbe@0 1573 } else {
jbe@0 1574 /* treat positive latitudes (including +0) as north */
jbe@0 1575 snprintf(buf, PGL_NUMBUFLEN, "N%015.12f", lat);
jbe@0 1576 }
jbe@0 1577 }
jbe@0 1578
jbe@0 1579 /* convert longitude floating point number (in degrees) to string */
jbe@0 1580 static void pgl_print_lon(char *buf, double lon) {
jbe@0 1581 if (signbit(lon)) {
jbe@0 1582 /* treat negative longitudes (including -0) as west */
jbe@0 1583 snprintf(buf, PGL_NUMBUFLEN, "W%016.12f", -lon);
jbe@0 1584 } else {
jbe@0 1585 /* treat positive longitudes (including +0) as east */
jbe@0 1586 snprintf(buf, PGL_NUMBUFLEN, "E%016.12f", lon);
jbe@0 1587 }
jbe@0 1588 }
jbe@0 1589
jbe@0 1590 /* bit masks used as return value of pgl_scan() function */
jbe@0 1591 #define PGL_SCAN_NONE 0 /* no value has been parsed */
jbe@0 1592 #define PGL_SCAN_LAT (1<<0) /* latitude has been parsed */
jbe@0 1593 #define PGL_SCAN_LON (1<<1) /* longitude has been parsed */
jbe@0 1594 #define PGL_SCAN_LATLON (PGL_SCAN_LAT | PGL_SCAN_LON) /* bitwise OR of both */
jbe@0 1595
jbe@0 1596 /* parse a coordinate (can be latitude or longitude) */
jbe@0 1597 static int pgl_scan(char **str, double *lat, double *lon) {
jbe@0 1598 double val;
jbe@0 1599 int len;
jbe@0 1600 if (
jbe@0 1601 sscanf(*str, " N %lf %n", &val, &len) ||
jbe@0 1602 sscanf(*str, " n %lf %n", &val, &len)
jbe@0 1603 ) {
jbe@0 1604 *str += len; *lat = val; return PGL_SCAN_LAT;
jbe@0 1605 }
jbe@0 1606 if (
jbe@0 1607 sscanf(*str, " S %lf %n", &val, &len) ||
jbe@0 1608 sscanf(*str, " s %lf %n", &val, &len)
jbe@0 1609 ) {
jbe@0 1610 *str += len; *lat = -val; return PGL_SCAN_LAT;
jbe@0 1611 }
jbe@0 1612 if (
jbe@0 1613 sscanf(*str, " E %lf %n", &val, &len) ||
jbe@0 1614 sscanf(*str, " e %lf %n", &val, &len)
jbe@0 1615 ) {
jbe@0 1616 *str += len; *lon = val; return PGL_SCAN_LON;
jbe@0 1617 }
jbe@0 1618 if (
jbe@0 1619 sscanf(*str, " W %lf %n", &val, &len) ||
jbe@0 1620 sscanf(*str, " w %lf %n", &val, &len)
jbe@0 1621 ) {
jbe@0 1622 *str += len; *lon = -val; return PGL_SCAN_LON;
jbe@0 1623 }
jbe@0 1624 return PGL_SCAN_NONE;
jbe@0 1625 }
jbe@0 1626
jbe@0 1627
jbe@0 1628 /*-----------------*
jbe@0 1629 * SQL functions *
jbe@0 1630 *-----------------*/
jbe@0 1631
jbe@0 1632 /* Note: These function names use "epoint", "ebox", etc. notation here instead
jbe@0 1633 of "point", "box", etc. in order to distinguish them from any previously
jbe@0 1634 defined functions. */
jbe@0 1635
jbe@0 1636 /* function needed for dummy types and/or not implemented features */
jbe@0 1637 PG_FUNCTION_INFO_V1(pgl_notimpl);
jbe@0 1638 Datum pgl_notimpl(PG_FUNCTION_ARGS) {
jbe@0 1639 ereport(ERROR, (errmsg("not implemented by pgLatLon")));
jbe@0 1640 }
jbe@0 1641
jbe@0 1642 /* set point to latitude and longitude (including checks) */
jbe@0 1643 static void pgl_epoint_set_latlon(pgl_point *point, double lat, double lon) {
jbe@0 1644 /* reject infinite or NaN values */
jbe@0 1645 if (!isfinite(lat) || !isfinite(lon)) {
jbe@0 1646 ereport(ERROR, (
jbe@0 1647 errcode(ERRCODE_DATA_EXCEPTION),
jbe@0 1648 errmsg("epoint requires finite coordinates")
jbe@0 1649 ));
jbe@0 1650 }
jbe@0 1651 /* check latitude bounds */
jbe@0 1652 if (lat < -90) {
jbe@0 1653 ereport(WARNING, (errmsg("latitude exceeds south pole")));
jbe@0 1654 lat = -90;
jbe@0 1655 } else if (lat > 90) {
jbe@0 1656 ereport(WARNING, (errmsg("latitude exceeds north pole")));
jbe@0 1657 lat = 90;
jbe@0 1658 }
jbe@0 1659 /* check longitude bounds */
jbe@0 1660 if (lon < -180) {
jbe@0 1661 ereport(NOTICE, (errmsg("longitude west of 180th meridian normalized")));
jbe@0 1662 lon += 360 - trunc(lon / 360) * 360;
jbe@0 1663 } else if (lon > 180) {
jbe@0 1664 ereport(NOTICE, (errmsg("longitude east of 180th meridian normalized")));
jbe@0 1665 lon -= 360 + trunc(lon / 360) * 360;
jbe@0 1666 }
jbe@0 1667 /* store rounded latitude/longitude values for round-trip safety */
jbe@0 1668 point->lat = pgl_round(lat);
jbe@0 1669 point->lon = pgl_round(lon);
jbe@0 1670 }
jbe@0 1671
jbe@0 1672 /* create point ("epoint" in SQL) from latitude and longitude */
jbe@0 1673 PG_FUNCTION_INFO_V1(pgl_create_epoint);
jbe@0 1674 Datum pgl_create_epoint(PG_FUNCTION_ARGS) {
jbe@0 1675 pgl_point *point = (pgl_point *)palloc(sizeof(pgl_point));
jbe@0 1676 pgl_epoint_set_latlon(point, PG_GETARG_FLOAT8(0), PG_GETARG_FLOAT8(1));
jbe@0 1677 PG_RETURN_POINTER(point);
jbe@0 1678 }
jbe@0 1679
jbe@0 1680 /* parse point ("epoint" in SQL) */
jbe@0 1681 /* format: '[NS]<float> [EW]<float>' */
jbe@0 1682 PG_FUNCTION_INFO_V1(pgl_epoint_in);
jbe@0 1683 Datum pgl_epoint_in(PG_FUNCTION_ARGS) {
jbe@0 1684 char *str = PG_GETARG_CSTRING(0); /* input string */
jbe@0 1685 char *strptr = str; /* current position within string */
jbe@0 1686 int done = 0; /* bit mask storing if latitude or longitude was read */
jbe@0 1687 double lat, lon; /* parsed values as double precision floats */
jbe@0 1688 pgl_point *point; /* return value (to be palloc'ed) */
jbe@0 1689 /* parse two floats (each latitude or longitude) separated by white-space */
jbe@0 1690 done |= pgl_scan(&strptr, &lat, &lon);
jbe@0 1691 if (strptr != str && isspace(strptr[-1])) {
jbe@0 1692 done |= pgl_scan(&strptr, &lat, &lon);
jbe@0 1693 }
jbe@0 1694 /* require end of string, and latitude and longitude parsed successfully */
jbe@0 1695 if (strptr[0] || done != PGL_SCAN_LATLON) {
jbe@0 1696 ereport(ERROR, (
jbe@0 1697 errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
jbe@0 1698 errmsg("invalid input syntax for type epoint: \"%s\"", str)
jbe@0 1699 ));
jbe@0 1700 }
jbe@0 1701 /* allocate memory for result */
jbe@0 1702 point = (pgl_point *)palloc(sizeof(pgl_point));
jbe@0 1703 /* set latitude and longitude (and perform checks) */
jbe@0 1704 pgl_epoint_set_latlon(point, lat, lon);
jbe@0 1705 /* return result */
jbe@0 1706 PG_RETURN_POINTER(point);
jbe@0 1707 }
jbe@0 1708
jbe@0 1709 /* create box ("ebox" in SQL) that is empty */
jbe@0 1710 PG_FUNCTION_INFO_V1(pgl_create_empty_ebox);
jbe@0 1711 Datum pgl_create_empty_ebox(PG_FUNCTION_ARGS) {
jbe@0 1712 pgl_box *box = (pgl_box *)palloc(sizeof(pgl_box));
jbe@0 1713 pgl_box_set_empty(box);
jbe@0 1714 PG_RETURN_POINTER(box);
jbe@0 1715 }
jbe@0 1716
jbe@0 1717 /* set box to given boundaries (including checks) */
jbe@0 1718 static void pgl_ebox_set_boundaries(
jbe@0 1719 pgl_box *box,
jbe@0 1720 double lat_min, double lat_max, double lon_min, double lon_max
jbe@0 1721 ) {
jbe@0 1722 /* if minimum latitude is greater than maximum latitude, return empty box */
jbe@0 1723 if (lat_min > lat_max) {
jbe@0 1724 pgl_box_set_empty(box);
jbe@0 1725 return;
jbe@0 1726 }
jbe@0 1727 /* otherwise reject infinite or NaN values */
jbe@0 1728 if (
jbe@0 1729 !isfinite(lat_min) || !isfinite(lat_max) ||
jbe@0 1730 !isfinite(lon_min) || !isfinite(lon_max)
jbe@0 1731 ) {
jbe@0 1732 ereport(ERROR, (
jbe@0 1733 errcode(ERRCODE_DATA_EXCEPTION),
jbe@0 1734 errmsg("ebox requires finite coordinates")
jbe@0 1735 ));
jbe@0 1736 }
jbe@0 1737 /* check latitude bounds */
jbe@0 1738 if (lat_max < -90) {
jbe@0 1739 ereport(WARNING, (errmsg("northern latitude exceeds south pole")));
jbe@0 1740 lat_max = -90;
jbe@0 1741 } else if (lat_max > 90) {
jbe@0 1742 ereport(WARNING, (errmsg("northern latitude exceeds north pole")));
jbe@0 1743 lat_max = 90;
jbe@0 1744 }
jbe@0 1745 if (lat_min < -90) {
jbe@0 1746 ereport(WARNING, (errmsg("southern latitude exceeds south pole")));
jbe@0 1747 lat_min = -90;
jbe@0 1748 } else if (lat_min > 90) {
jbe@0 1749 ereport(WARNING, (errmsg("southern latitude exceeds north pole")));
jbe@0 1750 lat_min = 90;
jbe@0 1751 }
jbe@0 1752 /* check if all longitudes are included */
jbe@0 1753 if (lon_max - lon_min >= 360) {
jbe@0 1754 if (lon_max - lon_min > 360) ereport(WARNING, (
jbe@0 1755 errmsg("longitude coverage greater than 360 degrees")
jbe@0 1756 ));
jbe@0 1757 lon_min = -180;
jbe@0 1758 lon_max = 180;
jbe@0 1759 } else {
jbe@0 1760 /* normalize longitude bounds */
jbe@0 1761 if (lon_min < -180) lon_min += 360 - trunc(lon_min / 360) * 360;
jbe@0 1762 else if (lon_min > 180) lon_min -= 360 + trunc(lon_min / 360) * 360;
jbe@0 1763 if (lon_max < -180) lon_max += 360 - trunc(lon_max / 360) * 360;
jbe@0 1764 else if (lon_max > 180) lon_max -= 360 + trunc(lon_max / 360) * 360;
jbe@0 1765 }
jbe@0 1766 /* store rounded latitude/longitude values for round-trip safety */
jbe@0 1767 box->lat_min = pgl_round(lat_min);
jbe@0 1768 box->lat_max = pgl_round(lat_max);
jbe@0 1769 box->lon_min = pgl_round(lon_min);
jbe@0 1770 box->lon_max = pgl_round(lon_max);
jbe@0 1771 /* ensure that rounding does not change orientation */
jbe@0 1772 if (lon_min > lon_max && box->lon_min == box->lon_max) {
jbe@0 1773 box->lon_min = -180;
jbe@0 1774 box->lon_max = 180;
jbe@0 1775 }
jbe@0 1776 }
jbe@0 1777
jbe@0 1778 /* create box ("ebox" in SQL) from min/max latitude and min/max longitude */
jbe@0 1779 PG_FUNCTION_INFO_V1(pgl_create_ebox);
jbe@0 1780 Datum pgl_create_ebox(PG_FUNCTION_ARGS) {
jbe@0 1781 pgl_box *box = (pgl_box *)palloc(sizeof(pgl_box));
jbe@0 1782 pgl_ebox_set_boundaries(
jbe@0 1783 box,
jbe@0 1784 PG_GETARG_FLOAT8(0), PG_GETARG_FLOAT8(1),
jbe@0 1785 PG_GETARG_FLOAT8(2), PG_GETARG_FLOAT8(3)
jbe@0 1786 );
jbe@0 1787 PG_RETURN_POINTER(box);
jbe@0 1788 }
jbe@0 1789
jbe@0 1790 /* create box ("ebox" in SQL) from two points ("epoint"s) */
jbe@0 1791 /* (can not be used to cover a longitude range of more than 120 degrees) */
jbe@0 1792 PG_FUNCTION_INFO_V1(pgl_create_ebox_from_epoints);
jbe@0 1793 Datum pgl_create_ebox_from_epoints(PG_FUNCTION_ARGS) {
jbe@0 1794 pgl_point *point1 = (pgl_point *)PG_GETARG_POINTER(0);
jbe@0 1795 pgl_point *point2 = (pgl_point *)PG_GETARG_POINTER(1);
jbe@0 1796 pgl_box *box = (pgl_box *)palloc(sizeof(pgl_box));
jbe@0 1797 double lat_min, lat_max, lon_min, lon_max;
jbe@0 1798 double dlon; /* longitude range (delta longitude) */
jbe@0 1799 /* order latitude and longitude boundaries */
jbe@0 1800 if (point2->lat < point1->lat) {
jbe@0 1801 lat_min = point2->lat;
jbe@0 1802 lat_max = point1->lat;
jbe@0 1803 } else {
jbe@0 1804 lat_min = point1->lat;
jbe@0 1805 lat_max = point2->lat;
jbe@0 1806 }
jbe@0 1807 if (point2->lon < point1->lon) {
jbe@0 1808 lon_min = point2->lon;
jbe@0 1809 lon_max = point1->lon;
jbe@0 1810 } else {
jbe@0 1811 lon_min = point1->lon;
jbe@0 1812 lon_max = point2->lon;
jbe@0 1813 }
jbe@0 1814 /* calculate longitude range (round to avoid floating point errors) */
jbe@0 1815 dlon = pgl_round(lon_max - lon_min);
jbe@0 1816 /* determine east-west direction */
jbe@0 1817 if (dlon >= 240) {
jbe@0 1818 /* assume that 180th meridian is crossed and swap min/max longitude */
jbe@0 1819 double swap = lon_min; lon_min = lon_max; lon_max = swap;
jbe@0 1820 } else if (dlon > 120) {
jbe@0 1821 /* unclear orientation since delta longitude > 120 */
jbe@0 1822 ereport(ERROR, (
jbe@0 1823 errcode(ERRCODE_DATA_EXCEPTION),
jbe@0 1824 errmsg("can not determine east/west orientation for ebox")
jbe@0 1825 ));
jbe@0 1826 }
jbe@0 1827 /* use boundaries to setup box (and perform checks) */
jbe@0 1828 pgl_ebox_set_boundaries(box, lat_min, lat_max, lon_min, lon_max);
jbe@0 1829 /* return result */
jbe@0 1830 PG_RETURN_POINTER(box);
jbe@0 1831 }
jbe@0 1832
jbe@0 1833 /* parse box ("ebox" in SQL) */
jbe@0 1834 /* format: '[NS]<float> [EW]<float> [NS]<float> [EW]<float>'
jbe@0 1835 or: '[NS]<float> [NS]<float> [EW]<float> [EW]<float>' */
jbe@0 1836 PG_FUNCTION_INFO_V1(pgl_ebox_in);
jbe@0 1837 Datum pgl_ebox_in(PG_FUNCTION_ARGS) {
jbe@0 1838 char *str = PG_GETARG_CSTRING(0); /* input string */
jbe@0 1839 char *str_lower; /* lower case version of input string */
jbe@0 1840 char *strptr; /* current position within string */
jbe@0 1841 int valid; /* number of valid chars */
jbe@0 1842 int done; /* specifies if latitude or longitude was read */
jbe@0 1843 double val; /* temporary variable */
jbe@0 1844 int lat_count = 0; /* count of latitude values parsed */
jbe@0 1845 int lon_count = 0; /* count of longitufde values parsed */
jbe@0 1846 double lat_min, lat_max, lon_min, lon_max; /* see pgl_box struct */
jbe@0 1847 pgl_box *box; /* return value (to be palloc'ed) */
jbe@0 1848 /* lowercase input */
jbe@0 1849 str_lower = psprintf("%s", str);
jbe@0 1850 for (strptr=str_lower; *strptr; strptr++) {
jbe@0 1851 if (*strptr >= 'A' && *strptr <= 'Z') *strptr += 'a' - 'A';
jbe@0 1852 }
jbe@0 1853 /* reset reading position to start of (lowercase) string */
jbe@0 1854 strptr = str_lower;
jbe@0 1855 /* check if empty box */
jbe@0 1856 valid = 0;
jbe@0 1857 sscanf(strptr, " empty %n", &valid);
jbe@0 1858 if (valid && strptr[valid] == 0) {
jbe@0 1859 /* allocate and return empty box */
jbe@0 1860 box = (pgl_box *)palloc(sizeof(pgl_box));
jbe@0 1861 pgl_box_set_empty(box);
jbe@0 1862 PG_RETURN_POINTER(box);
jbe@0 1863 }
jbe@0 1864 /* demand four blocks separated by whitespace */
jbe@0 1865 valid = 0;
jbe@0 1866 sscanf(strptr, " %*s %*s %*s %*s %n", &valid);
jbe@0 1867 /* if four blocks separated by whitespace exist, parse those blocks */
jbe@0 1868 if (strptr[valid] == 0) while (strptr[0]) {
jbe@0 1869 /* parse either latitude or longitude (whichever found in input string) */
jbe@0 1870 done = pgl_scan(&strptr, &val, &val);
jbe@0 1871 /* store latitude or longitude in lat_min, lat_max, lon_min, or lon_max */
jbe@0 1872 if (done == PGL_SCAN_LAT) {
jbe@0 1873 if (!lat_count) lat_min = val; else lat_max = val;
jbe@0 1874 lat_count++;
jbe@0 1875 } else if (done == PGL_SCAN_LON) {
jbe@0 1876 if (!lon_count) lon_min = val; else lon_max = val;
jbe@0 1877 lon_count++;
jbe@0 1878 } else {
jbe@0 1879 break;
jbe@0 1880 }
jbe@0 1881 }
jbe@0 1882 /* require end of string, and two latitude and two longitude values */
jbe@0 1883 if (strptr[0] || lat_count != 2 || lon_count != 2) {
jbe@0 1884 ereport(ERROR, (
jbe@0 1885 errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
jbe@0 1886 errmsg("invalid input syntax for type ebox: \"%s\"", str)
jbe@0 1887 ));
jbe@0 1888 }
jbe@0 1889 /* free lower case string */
jbe@0 1890 pfree(str_lower);
jbe@0 1891 /* order boundaries (maximum greater than minimum) */
jbe@0 1892 if (lat_min > lat_max) { val = lat_min; lat_min = lat_max; lat_max = val; }
jbe@0 1893 if (lon_min > lon_max) { val = lon_min; lon_min = lon_max; lon_max = val; }
jbe@0 1894 /* allocate memory for result */
jbe@0 1895 box = (pgl_box *)palloc(sizeof(pgl_box));
jbe@0 1896 /* set boundaries (and perform checks) */
jbe@0 1897 pgl_ebox_set_boundaries(box, lat_min, lat_max, lon_min, lon_max);
jbe@0 1898 /* return result */
jbe@0 1899 PG_RETURN_POINTER(box);
jbe@0 1900 }
jbe@0 1901
jbe@0 1902 /* set circle to given latitude, longitude, and radius (including checks) */
jbe@0 1903 static void pgl_ecircle_set_latlon_radius(
jbe@0 1904 pgl_circle *circle, double lat, double lon, double radius
jbe@0 1905 ) {
jbe@0 1906 /* set center point (including checks) */
jbe@0 1907 pgl_epoint_set_latlon(&(circle->center), lat, lon);
jbe@0 1908 /* handle non-positive radius */
jbe@0 1909 if (isnan(radius)) {
jbe@0 1910 ereport(ERROR, (
jbe@0 1911 errcode(ERRCODE_DATA_EXCEPTION),
jbe@0 1912 errmsg("invalid radius for ecircle")
jbe@0 1913 ));
jbe@0 1914 }
jbe@0 1915 if (radius == 0) radius = 0; /* avoids -0 */
jbe@0 1916 else if (radius < 0) {
jbe@0 1917 if (isfinite(radius)) {
jbe@0 1918 ereport(NOTICE, (errmsg("negative radius converted to minus infinity")));
jbe@0 1919 }
jbe@0 1920 radius = -INFINITY;
jbe@0 1921 }
jbe@0 1922 /* store radius (round-trip safety is ensured by pgl_print_float) */
jbe@0 1923 circle->radius = radius;
jbe@0 1924 }
jbe@0 1925
jbe@0 1926 /* create circle ("ecircle" in SQL) from latitude, longitude, and radius */
jbe@0 1927 PG_FUNCTION_INFO_V1(pgl_create_ecircle);
jbe@0 1928 Datum pgl_create_ecircle(PG_FUNCTION_ARGS) {
jbe@0 1929 pgl_circle *circle = (pgl_circle *)palloc(sizeof(pgl_circle));
jbe@0 1930 pgl_ecircle_set_latlon_radius(
jbe@0 1931 circle, PG_GETARG_FLOAT8(0), PG_GETARG_FLOAT8(1), PG_GETARG_FLOAT8(2)
jbe@0 1932 );
jbe@0 1933 PG_RETURN_POINTER(circle);
jbe@0 1934 }
jbe@0 1935
jbe@0 1936 /* create circle ("ecircle" in SQL) from point ("epoint"), and radius */
jbe@0 1937 PG_FUNCTION_INFO_V1(pgl_create_ecircle_from_epoint);
jbe@0 1938 Datum pgl_create_ecircle_from_epoint(PG_FUNCTION_ARGS) {
jbe@0 1939 pgl_point *point = (pgl_point *)PG_GETARG_POINTER(0);
jbe@0 1940 double radius = PG_GETARG_FLOAT8(1);
jbe@0 1941 pgl_circle *circle = (pgl_circle *)palloc(sizeof(pgl_circle));
jbe@0 1942 /* set latitude, longitude, radius (and perform checks) */
jbe@0 1943 pgl_ecircle_set_latlon_radius(circle, point->lat, point->lon, radius);
jbe@0 1944 /* return result */
jbe@0 1945 PG_RETURN_POINTER(circle);
jbe@0 1946 }
jbe@0 1947
jbe@0 1948 /* parse circle ("ecircle" in SQL) */
jbe@0 1949 /* format: '[NS]<float> [EW]<float> <float>' */
jbe@0 1950 PG_FUNCTION_INFO_V1(pgl_ecircle_in);
jbe@0 1951 Datum pgl_ecircle_in(PG_FUNCTION_ARGS) {
jbe@0 1952 char *str = PG_GETARG_CSTRING(0); /* input string */
jbe@0 1953 char *strptr = str; /* current position within string */
jbe@0 1954 double lat, lon, radius; /* parsed values as double precision flaots */
jbe@0 1955 int valid = 0; /* number of valid chars */
jbe@0 1956 int done = 0; /* stores if latitude and/or longitude was read */
jbe@0 1957 pgl_circle *circle; /* return value (to be palloc'ed) */
jbe@0 1958 /* demand three blocks separated by whitespace */
jbe@0 1959 sscanf(strptr, " %*s %*s %*s %n", &valid);
jbe@0 1960 /* if three blocks separated by whitespace exist, parse those blocks */
jbe@0 1961 if (strptr[valid] == 0) {
jbe@0 1962 /* parse latitude and longitude */
jbe@0 1963 done |= pgl_scan(&strptr, &lat, &lon);
jbe@0 1964 done |= pgl_scan(&strptr, &lat, &lon);
jbe@0 1965 /* parse radius (while incrementing strptr by number of bytes parsed) */
jbe@0 1966 valid = 0;
jbe@0 1967 if (sscanf(strptr, " %lf %n", &radius, &valid) == 1) strptr += valid;
jbe@0 1968 }
jbe@0 1969 /* require end of string and both latitude and longitude being parsed */
jbe@0 1970 if (strptr[0] || done != PGL_SCAN_LATLON) {
jbe@0 1971 ereport(ERROR, (
jbe@0 1972 errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
jbe@0 1973 errmsg("invalid input syntax for type ecircle: \"%s\"", str)
jbe@0 1974 ));
jbe@0 1975 }
jbe@0 1976 /* allocate memory for result */
jbe@0 1977 circle = (pgl_circle *)palloc(sizeof(pgl_circle));
jbe@0 1978 /* set latitude, longitude, radius (and perform checks) */
jbe@0 1979 pgl_ecircle_set_latlon_radius(circle, lat, lon, radius);
jbe@0 1980 /* return result */
jbe@0 1981 PG_RETURN_POINTER(circle);
jbe@0 1982 }
jbe@0 1983
jbe@0 1984 /* parse cluster ("ecluster" in SQL) */
jbe@0 1985 PG_FUNCTION_INFO_V1(pgl_ecluster_in);
jbe@0 1986 Datum pgl_ecluster_in(PG_FUNCTION_ARGS) {
jbe@0 1987 int i;
jbe@0 1988 char *str = PG_GETARG_CSTRING(0); /* input string */
jbe@0 1989 char *str_lower; /* lower case version of input string */
jbe@0 1990 char *strptr; /* pointer to current reading position of input */
jbe@0 1991 int npoints_total = 0; /* total number of points in cluster */
jbe@0 1992 int nentries = 0; /* total number of entries */
jbe@0 1993 pgl_newentry *entries; /* array of pgl_newentry to create pgl_cluster */
jbe@0 1994 int entries_buflen = 4; /* maximum number of elements in entries array */
jbe@0 1995 int valid; /* number of valid chars processed */
jbe@0 1996 double lat, lon; /* latitude and longitude of parsed point */
jbe@0 1997 int entrytype; /* current entry type */
jbe@0 1998 int npoints; /* number of points in current entry */
jbe@0 1999 pgl_point *points; /* array of pgl_point for pgl_newentry */
jbe@0 2000 int points_buflen; /* maximum number of elements in points array */
jbe@0 2001 int done; /* return value of pgl_scan function */
jbe@0 2002 pgl_cluster *cluster; /* created cluster */
jbe@0 2003 /* lowercase input */
jbe@0 2004 str_lower = psprintf("%s", str);
jbe@0 2005 for (strptr=str_lower; *strptr; strptr++) {
jbe@0 2006 if (*strptr >= 'A' && *strptr <= 'Z') *strptr += 'a' - 'A';
jbe@0 2007 }
jbe@0 2008 /* reset reading position to start of (lowercase) string */
jbe@0 2009 strptr = str_lower;
jbe@0 2010 /* allocate initial buffer for entries */
jbe@0 2011 entries = palloc(entries_buflen * sizeof(pgl_newentry));
jbe@0 2012 /* parse until end of string */
jbe@0 2013 while (strptr[0]) {
jbe@0 2014 /* require previous white-space or closing parenthesis before next token */
jbe@0 2015 if (strptr != str_lower && !isspace(strptr[-1]) && strptr[-1] != ')') {
jbe@0 2016 goto pgl_ecluster_in_error;
jbe@0 2017 }
jbe@0 2018 /* ignore token "empty" */
jbe@0 2019 valid = 0; sscanf(strptr, " empty %n", &valid);
jbe@0 2020 if (valid) { strptr += valid; continue; }
jbe@0 2021 /* test for "point" token */
jbe@0 2022 valid = 0; sscanf(strptr, " point ( %n", &valid);
jbe@0 2023 if (valid) {
jbe@0 2024 strptr += valid;
jbe@0 2025 entrytype = PGL_ENTRY_POINT;
jbe@0 2026 goto pgl_ecluster_in_type_ok;
jbe@0 2027 }
jbe@0 2028 /* test for "path" token */
jbe@0 2029 valid = 0; sscanf(strptr, " path ( %n", &valid);
jbe@0 2030 if (valid) {
jbe@0 2031 strptr += valid;
jbe@0 2032 entrytype = PGL_ENTRY_PATH;
jbe@0 2033 goto pgl_ecluster_in_type_ok;
jbe@0 2034 }
jbe@0 2035 /* test for "outline" token */
jbe@0 2036 valid = 0; sscanf(strptr, " outline ( %n", &valid);
jbe@0 2037 if (valid) {
jbe@0 2038 strptr += valid;
jbe@0 2039 entrytype = PGL_ENTRY_OUTLINE;
jbe@0 2040 goto pgl_ecluster_in_type_ok;
jbe@0 2041 }
jbe@0 2042 /* test for "polygon" token */
jbe@0 2043 valid = 0; sscanf(strptr, " polygon ( %n", &valid);
jbe@0 2044 if (valid) {
jbe@0 2045 strptr += valid;
jbe@0 2046 entrytype = PGL_ENTRY_POLYGON;
jbe@0 2047 goto pgl_ecluster_in_type_ok;
jbe@0 2048 }
jbe@0 2049 /* error if no valid token found */
jbe@0 2050 goto pgl_ecluster_in_error;
jbe@0 2051 pgl_ecluster_in_type_ok:
jbe@0 2052 /* check if pgl_newentry array needs to grow */
jbe@0 2053 if (nentries == entries_buflen) {
jbe@0 2054 pgl_newentry *newbuf;
jbe@0 2055 entries_buflen *= 2;
jbe@0 2056 newbuf = palloc(entries_buflen * sizeof(pgl_newentry));
jbe@0 2057 memcpy(newbuf, entries, nentries * sizeof(pgl_newentry));
jbe@0 2058 pfree(entries);
jbe@0 2059 entries = newbuf;
jbe@0 2060 }
jbe@0 2061 /* reset number of points for current entry */
jbe@0 2062 npoints = 0;
jbe@0 2063 /* allocate array for points */
jbe@0 2064 points_buflen = 4;
jbe@0 2065 points = palloc(points_buflen * sizeof(pgl_point));
jbe@0 2066 /* parse until closing parenthesis */
jbe@0 2067 while (strptr[0] != ')') {
jbe@0 2068 /* error on unexpected end of string */
jbe@0 2069 if (strptr[0] == 0) goto pgl_ecluster_in_error;
jbe@0 2070 /* mark neither latitude nor longitude as read */
jbe@0 2071 done = PGL_SCAN_NONE;
jbe@0 2072 /* require white-space before second, third, etc. point */
jbe@0 2073 if (npoints != 0 && !isspace(strptr[-1])) goto pgl_ecluster_in_error;
jbe@0 2074 /* scan latitude (or longitude) */
jbe@0 2075 done |= pgl_scan(&strptr, &lat, &lon);
jbe@0 2076 /* require white-space before second coordinate */
jbe@0 2077 if (strptr != str && !isspace(strptr[-1])) goto pgl_ecluster_in_error;
jbe@0 2078 /* scan longitude (or latitude) */
jbe@0 2079 done |= pgl_scan(&strptr, &lat, &lon);
jbe@0 2080 /* error unless both latitude and longitude were parsed */
jbe@0 2081 if (done != PGL_SCAN_LATLON) goto pgl_ecluster_in_error;
jbe@0 2082 /* throw error if number of points is too high */
jbe@0 2083 if (npoints_total == PGL_CLUSTER_MAXPOINTS) {
jbe@0 2084 ereport(ERROR, (
jbe@0 2085 errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
jbe@0 2086 errmsg(
jbe@0 2087 "too many points for ecluster entry (maximum %i)",
jbe@0 2088 PGL_CLUSTER_MAXPOINTS
jbe@0 2089 )
jbe@0 2090 ));
jbe@0 2091 }
jbe@0 2092 /* check if pgl_point array needs to grow */
jbe@0 2093 if (npoints == points_buflen) {
jbe@0 2094 pgl_point *newbuf;
jbe@0 2095 points_buflen *= 2;
jbe@0 2096 newbuf = palloc(points_buflen * sizeof(pgl_point));
jbe@0 2097 memcpy(newbuf, points, npoints * sizeof(pgl_point));
jbe@0 2098 pfree(points);
jbe@0 2099 points = newbuf;
jbe@0 2100 }
jbe@0 2101 /* append point to pgl_point array (includes checks) */
jbe@0 2102 pgl_epoint_set_latlon(&(points[npoints++]), lat, lon);
jbe@0 2103 /* increase total number of points */
jbe@0 2104 npoints_total++;
jbe@0 2105 }
jbe@0 2106 /* error if entry has no points */
jbe@0 2107 if (!npoints) goto pgl_ecluster_in_error;
jbe@0 2108 /* entries with one point are automatically of type "point" */
jbe@0 2109 if (npoints == 1) entrytype = PGL_ENTRY_POINT;
jbe@0 2110 /* if entries have more than one point */
jbe@0 2111 else {
jbe@0 2112 /* throw error if entry type is "point" */
jbe@0 2113 if (entrytype == PGL_ENTRY_POINT) {
jbe@0 2114 ereport(ERROR, (
jbe@0 2115 errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
jbe@0 2116 errmsg("invalid input syntax for type ecluster (point entry with more than one point)")
jbe@0 2117 ));
jbe@0 2118 }
jbe@0 2119 /* coerce outlines and polygons with more than 2 points to be a path */
jbe@0 2120 if (npoints == 2) entrytype = PGL_ENTRY_PATH;
jbe@0 2121 }
jbe@0 2122 /* append entry to pgl_newentry array */
jbe@0 2123 entries[nentries].entrytype = entrytype;
jbe@0 2124 entries[nentries].npoints = npoints;
jbe@0 2125 entries[nentries].points = points;
jbe@0 2126 nentries++;
jbe@0 2127 /* consume closing parenthesis */
jbe@0 2128 strptr++;
jbe@0 2129 /* consume white-space */
jbe@0 2130 while (isspace(strptr[0])) strptr++;
jbe@0 2131 }
jbe@0 2132 /* free lower case string */
jbe@0 2133 pfree(str_lower);
jbe@0 2134 /* create cluster from pgl_newentry array */
jbe@0 2135 cluster = pgl_new_cluster(nentries, entries);
jbe@0 2136 /* free pgl_newentry array */
jbe@0 2137 for (i=0; i<nentries; i++) pfree(entries[i].points);
jbe@0 2138 pfree(entries);
jbe@0 2139 /* set bounding circle of cluster and check east/west orientation */
jbe@0 2140 if (!pgl_finalize_cluster(cluster)) {
jbe@0 2141 ereport(ERROR, (
jbe@0 2142 errcode(ERRCODE_DATA_EXCEPTION),
jbe@0 2143 errmsg("can not determine east/west orientation for ecluster"),
jbe@0 2144 errhint("Ensure that each entry has a longitude span of less than 180 degrees.")
jbe@0 2145 ));
jbe@0 2146 }
jbe@0 2147 /* return cluster */
jbe@0 2148 PG_RETURN_POINTER(cluster);
jbe@0 2149 /* code to throw error */
jbe@0 2150 pgl_ecluster_in_error:
jbe@0 2151 ereport(ERROR, (
jbe@0 2152 errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
jbe@0 2153 errmsg("invalid input syntax for type ecluster: \"%s\"", str)
jbe@0 2154 ));
jbe@0 2155 }
jbe@0 2156
jbe@0 2157 /* convert point ("epoint") to string representation */
jbe@0 2158 PG_FUNCTION_INFO_V1(pgl_epoint_out);
jbe@0 2159 Datum pgl_epoint_out(PG_FUNCTION_ARGS) {
jbe@0 2160 pgl_point *point = (pgl_point *)PG_GETARG_POINTER(0);
jbe@0 2161 char latstr[PGL_NUMBUFLEN];
jbe@0 2162 char lonstr[PGL_NUMBUFLEN];
jbe@0 2163 pgl_print_lat(latstr, point->lat);
jbe@0 2164 pgl_print_lon(lonstr, point->lon);
jbe@0 2165 PG_RETURN_CSTRING(psprintf("%s %s", latstr, lonstr));
jbe@0 2166 }
jbe@0 2167
jbe@0 2168 /* convert box ("ebox") to string representation */
jbe@0 2169 PG_FUNCTION_INFO_V1(pgl_ebox_out);
jbe@0 2170 Datum pgl_ebox_out(PG_FUNCTION_ARGS) {
jbe@0 2171 pgl_box *box = (pgl_box *)PG_GETARG_POINTER(0);
jbe@0 2172 double lon_min = box->lon_min;
jbe@0 2173 double lon_max = box->lon_max;
jbe@0 2174 char lat_min_str[PGL_NUMBUFLEN];
jbe@0 2175 char lat_max_str[PGL_NUMBUFLEN];
jbe@0 2176 char lon_min_str[PGL_NUMBUFLEN];
jbe@0 2177 char lon_max_str[PGL_NUMBUFLEN];
jbe@0 2178 /* return string "empty" if box is set to be empty */
jbe@0 2179 if (box->lat_min > box->lat_max) PG_RETURN_CSTRING("empty");
jbe@0 2180 /* use boundaries exceeding W180 or E180 if 180th meridian is enclosed */
jbe@0 2181 /* (required since pgl_box_in orders the longitude boundaries) */
jbe@0 2182 if (lon_min > lon_max) {
jbe@0 2183 if (lon_min + lon_max >= 0) lon_min -= 360;
jbe@0 2184 else lon_max += 360;
jbe@0 2185 }
jbe@0 2186 /* format and return result */
jbe@0 2187 pgl_print_lat(lat_min_str, box->lat_min);
jbe@0 2188 pgl_print_lat(lat_max_str, box->lat_max);
jbe@0 2189 pgl_print_lon(lon_min_str, lon_min);
jbe@0 2190 pgl_print_lon(lon_max_str, lon_max);
jbe@0 2191 PG_RETURN_CSTRING(psprintf(
jbe@0 2192 "%s %s %s %s",
jbe@0 2193 lat_min_str, lon_min_str, lat_max_str, lon_max_str
jbe@0 2194 ));
jbe@0 2195 }
jbe@0 2196
jbe@0 2197 /* convert circle ("ecircle") to string representation */
jbe@0 2198 PG_FUNCTION_INFO_V1(pgl_ecircle_out);
jbe@0 2199 Datum pgl_ecircle_out(PG_FUNCTION_ARGS) {
jbe@0 2200 pgl_circle *circle = (pgl_circle *)PG_GETARG_POINTER(0);
jbe@0 2201 char latstr[PGL_NUMBUFLEN];
jbe@0 2202 char lonstr[PGL_NUMBUFLEN];
jbe@0 2203 char radstr[PGL_NUMBUFLEN];
jbe@0 2204 pgl_print_lat(latstr, circle->center.lat);
jbe@0 2205 pgl_print_lon(lonstr, circle->center.lon);
jbe@0 2206 pgl_print_float(radstr, circle->radius);
jbe@0 2207 PG_RETURN_CSTRING(psprintf("%s %s %s", latstr, lonstr, radstr));
jbe@0 2208 }
jbe@0 2209
jbe@0 2210 /* convert cluster ("ecluster") to string representation */
jbe@0 2211 PG_FUNCTION_INFO_V1(pgl_ecluster_out);
jbe@0 2212 Datum pgl_ecluster_out(PG_FUNCTION_ARGS) {
jbe@0 2213 pgl_cluster *cluster = (pgl_cluster *)PG_DETOAST_DATUM(PG_GETARG_DATUM(0));
jbe@0 2214 char latstr[PGL_NUMBUFLEN]; /* string buffer for latitude */
jbe@0 2215 char lonstr[PGL_NUMBUFLEN]; /* string buffer for longitude */
jbe@0 2216 char ***strings; /* array of array of strings */
jbe@0 2217 char *string; /* string of current token */
jbe@0 2218 char *res, *resptr; /* result and pointer to current write position */
jbe@0 2219 size_t reslen = 1; /* length of result (init with 1 for terminator) */
jbe@0 2220 int npoints; /* number of points of current entry */
jbe@0 2221 int i, j; /* i: entry, j: point in entry */
jbe@0 2222 /* handle empty clusters */
jbe@0 2223 if (cluster->nentries == 0) {
jbe@0 2224 /* free detoasted cluster (if copy) */
jbe@0 2225 PG_FREE_IF_COPY(cluster, 0);
jbe@0 2226 /* return static result */
jbe@0 2227 PG_RETURN_CSTRING("empty");
jbe@0 2228 }
jbe@0 2229 /* allocate array of array of strings */
jbe@0 2230 strings = palloc(cluster->nentries * sizeof(char **));
jbe@0 2231 /* iterate over all entries in cluster */
jbe@0 2232 for (i=0; i<cluster->nentries; i++) {
jbe@0 2233 /* get number of points in entry */
jbe@0 2234 npoints = cluster->entries[i].npoints;
jbe@0 2235 /* allocate array of strings (one string for each point plus two extra) */
jbe@0 2236 strings[i] = palloc((2 + npoints) * sizeof(char *));
jbe@0 2237 /* determine opening string */
jbe@0 2238 switch (cluster->entries[i].entrytype) {
jbe@0 2239 case PGL_ENTRY_POINT: string = (i==0)?"point (" :" point ("; break;
jbe@0 2240 case PGL_ENTRY_PATH: string = (i==0)?"path (" :" path ("; break;
jbe@0 2241 case PGL_ENTRY_OUTLINE: string = (i==0)?"outline (":" outline ("; break;
jbe@0 2242 case PGL_ENTRY_POLYGON: string = (i==0)?"polygon (":" polygon ("; break;
jbe@0 2243 default: string = (i==0)?"unknown" :" unknown";
jbe@0 2244 }
jbe@0 2245 /* use opening string as first string in array */
jbe@0 2246 strings[i][0] = string;
jbe@0 2247 /* update result length (for allocating result string later) */
jbe@0 2248 reslen += strlen(string);
jbe@0 2249 /* iterate over all points */
jbe@0 2250 for (j=0; j<npoints; j++) {
jbe@0 2251 /* create string representation of point */
jbe@0 2252 pgl_print_lat(latstr, PGL_ENTRY_POINTS(cluster, i)[j].lat);
jbe@0 2253 pgl_print_lon(lonstr, PGL_ENTRY_POINTS(cluster, i)[j].lon);
jbe@0 2254 string = psprintf((j == 0) ? "%s %s" : " %s %s", latstr, lonstr);
jbe@0 2255 /* copy string pointer to string array */
jbe@0 2256 strings[i][j+1] = string;
jbe@0 2257 /* update result length (for allocating result string later) */
jbe@0 2258 reslen += strlen(string);
jbe@0 2259 }
jbe@0 2260 /* use closing parenthesis as last string in array */
jbe@0 2261 strings[i][npoints+1] = ")";
jbe@0 2262 /* update result length (for allocating result string later) */
jbe@0 2263 reslen++;
jbe@0 2264 }
jbe@0 2265 /* allocate result string */
jbe@0 2266 res = palloc(reslen);
jbe@0 2267 /* set write pointer to begin of result string */
jbe@0 2268 resptr = res;
jbe@0 2269 /* copy strings into result string */
jbe@0 2270 for (i=0; i<cluster->nentries; i++) {
jbe@0 2271 npoints = cluster->entries[i].npoints;
jbe@0 2272 for (j=0; j<npoints+2; j++) {
jbe@0 2273 string = strings[i][j];
jbe@0 2274 strcpy(resptr, string);
jbe@0 2275 resptr += strlen(string);
jbe@0 2276 /* free strings allocated by psprintf */
jbe@0 2277 if (j != 0 && j != npoints+1) pfree(string);
jbe@0 2278 }
jbe@0 2279 /* free array of strings */
jbe@0 2280 pfree(strings[i]);
jbe@0 2281 }
jbe@0 2282 /* free array of array of strings */
jbe@0 2283 pfree(strings);
jbe@0 2284 /* free detoasted cluster (if copy) */
jbe@0 2285 PG_FREE_IF_COPY(cluster, 0);
jbe@0 2286 /* return result */
jbe@0 2287 PG_RETURN_CSTRING(res);
jbe@0 2288 }
jbe@0 2289
jbe@0 2290 /* binary input function for point ("epoint") */
jbe@0 2291 PG_FUNCTION_INFO_V1(pgl_epoint_recv);
jbe@0 2292 Datum pgl_epoint_recv(PG_FUNCTION_ARGS) {
jbe@0 2293 StringInfo buf = (StringInfo)PG_GETARG_POINTER(0);
jbe@0 2294 pgl_point *point = (pgl_point *)palloc(sizeof(pgl_point));
jbe@0 2295 point->lat = pq_getmsgfloat8(buf);
jbe@0 2296 point->lon = pq_getmsgfloat8(buf);
jbe@0 2297 PG_RETURN_POINTER(point);
jbe@0 2298 }
jbe@0 2299
jbe@0 2300 /* binary input function for box ("ebox") */
jbe@0 2301 PG_FUNCTION_INFO_V1(pgl_ebox_recv);
jbe@0 2302 Datum pgl_ebox_recv(PG_FUNCTION_ARGS) {
jbe@0 2303 StringInfo buf = (StringInfo)PG_GETARG_POINTER(0);
jbe@0 2304 pgl_box *box = (pgl_box *)palloc(sizeof(pgl_box));
jbe@0 2305 box->lat_min = pq_getmsgfloat8(buf);
jbe@0 2306 box->lat_max = pq_getmsgfloat8(buf);
jbe@0 2307 box->lon_min = pq_getmsgfloat8(buf);
jbe@0 2308 box->lon_max = pq_getmsgfloat8(buf);
jbe@0 2309 PG_RETURN_POINTER(box);
jbe@0 2310 }
jbe@0 2311
jbe@0 2312 /* binary input function for circle ("ecircle") */
jbe@0 2313 PG_FUNCTION_INFO_V1(pgl_ecircle_recv);
jbe@0 2314 Datum pgl_ecircle_recv(PG_FUNCTION_ARGS) {
jbe@0 2315 StringInfo buf = (StringInfo)PG_GETARG_POINTER(0);
jbe@0 2316 pgl_circle *circle = (pgl_circle *)palloc(sizeof(pgl_circle));
jbe@0 2317 circle->center.lat = pq_getmsgfloat8(buf);
jbe@0 2318 circle->center.lon = pq_getmsgfloat8(buf);
jbe@0 2319 circle->radius = pq_getmsgfloat8(buf);
jbe@0 2320 PG_RETURN_POINTER(circle);
jbe@0 2321 }
jbe@0 2322
jbe@0 2323 /* TODO: binary receive function for cluster */
jbe@0 2324
jbe@0 2325 /* binary output function for point ("epoint") */
jbe@0 2326 PG_FUNCTION_INFO_V1(pgl_epoint_send);
jbe@0 2327 Datum pgl_epoint_send(PG_FUNCTION_ARGS) {
jbe@0 2328 pgl_point *point = (pgl_point *)PG_GETARG_POINTER(0);
jbe@0 2329 StringInfoData buf;
jbe@0 2330 pq_begintypsend(&buf);
jbe@0 2331 pq_sendfloat8(&buf, point->lat);
jbe@0 2332 pq_sendfloat8(&buf, point->lon);
jbe@0 2333 PG_RETURN_BYTEA_P(pq_endtypsend(&buf));
jbe@0 2334 }
jbe@0 2335
jbe@0 2336 /* binary output function for box ("ebox") */
jbe@0 2337 PG_FUNCTION_INFO_V1(pgl_ebox_send);
jbe@0 2338 Datum pgl_ebox_send(PG_FUNCTION_ARGS) {
jbe@0 2339 pgl_box *box = (pgl_box *)PG_GETARG_POINTER(0);
jbe@0 2340 StringInfoData buf;
jbe@0 2341 pq_begintypsend(&buf);
jbe@0 2342 pq_sendfloat8(&buf, box->lat_min);
jbe@0 2343 pq_sendfloat8(&buf, box->lat_max);
jbe@0 2344 pq_sendfloat8(&buf, box->lon_min);
jbe@0 2345 pq_sendfloat8(&buf, box->lon_max);
jbe@0 2346 PG_RETURN_BYTEA_P(pq_endtypsend(&buf));
jbe@0 2347 }
jbe@0 2348
jbe@0 2349 /* binary output function for circle ("ecircle") */
jbe@0 2350 PG_FUNCTION_INFO_V1(pgl_ecircle_send);
jbe@0 2351 Datum pgl_ecircle_send(PG_FUNCTION_ARGS) {
jbe@0 2352 pgl_circle *circle = (pgl_circle *)PG_GETARG_POINTER(0);
jbe@0 2353 StringInfoData buf;
jbe@0 2354 pq_begintypsend(&buf);
jbe@0 2355 pq_sendfloat8(&buf, circle->center.lat);
jbe@0 2356 pq_sendfloat8(&buf, circle->center.lon);
jbe@0 2357 pq_sendfloat8(&buf, circle->radius);
jbe@0 2358 PG_RETURN_BYTEA_P(pq_endtypsend(&buf));
jbe@0 2359 }
jbe@0 2360
jbe@0 2361 /* TODO: binary send functions for cluster */
jbe@0 2362
jbe@0 2363 /* cast point ("epoint") to box ("ebox") */
jbe@0 2364 PG_FUNCTION_INFO_V1(pgl_epoint_to_ebox);
jbe@0 2365 Datum pgl_epoint_to_ebox(PG_FUNCTION_ARGS) {
jbe@0 2366 pgl_point *point = (pgl_point *)PG_GETARG_POINTER(0);
jbe@0 2367 pgl_box *box = palloc(sizeof(pgl_box));
jbe@0 2368 box->lat_min = point->lat;
jbe@0 2369 box->lat_max = point->lat;
jbe@0 2370 box->lon_min = point->lon;
jbe@0 2371 box->lon_max = point->lon;
jbe@0 2372 PG_RETURN_POINTER(box);
jbe@0 2373 }
jbe@0 2374
jbe@0 2375 /* cast point ("epoint") to circle ("ecircle") */
jbe@0 2376 PG_FUNCTION_INFO_V1(pgl_epoint_to_ecircle);
jbe@0 2377 Datum pgl_epoint_to_ecircle(PG_FUNCTION_ARGS) {
jbe@0 2378 pgl_point *point = (pgl_point *)PG_GETARG_POINTER(0);
jbe@0 2379 pgl_circle *circle = palloc(sizeof(pgl_box));
jbe@0 2380 circle->center = *point;
jbe@0 2381 circle->radius = 0;
jbe@0 2382 PG_RETURN_POINTER(circle);
jbe@0 2383 }
jbe@0 2384
jbe@0 2385 /* cast point ("epoint") to cluster ("ecluster") */
jbe@0 2386 PG_FUNCTION_INFO_V1(pgl_epoint_to_ecluster);
jbe@0 2387 Datum pgl_epoint_to_ecluster(PG_FUNCTION_ARGS) {
jbe@0 2388 pgl_point *point = (pgl_point *)PG_GETARG_POINTER(0);
jbe@0 2389 pgl_newentry entry;
jbe@42 2390 pgl_cluster *cluster;
jbe@0 2391 entry.entrytype = PGL_ENTRY_POINT;
jbe@0 2392 entry.npoints = 1;
jbe@0 2393 entry.points = point;
jbe@42 2394 cluster = pgl_new_cluster(1, &entry);
jbe@42 2395 pgl_finalize_cluster(cluster); /* NOTE: should not fail */
jbe@42 2396 PG_RETURN_POINTER(cluster);
jbe@0 2397 }
jbe@0 2398
jbe@0 2399 /* cast box ("ebox") to cluster ("ecluster") */
jbe@0 2400 #define pgl_ebox_to_ecluster_macro(i, a, b) \
jbe@0 2401 entries[i].entrytype = PGL_ENTRY_POLYGON; \
jbe@0 2402 entries[i].npoints = 4; \
jbe@0 2403 entries[i].points = points[i]; \
jbe@0 2404 points[i][0].lat = box->lat_min; \
jbe@0 2405 points[i][0].lon = (a); \
jbe@0 2406 points[i][1].lat = box->lat_min; \
jbe@0 2407 points[i][1].lon = (b); \
jbe@0 2408 points[i][2].lat = box->lat_max; \
jbe@0 2409 points[i][2].lon = (b); \
jbe@0 2410 points[i][3].lat = box->lat_max; \
jbe@0 2411 points[i][3].lon = (a);
jbe@0 2412 PG_FUNCTION_INFO_V1(pgl_ebox_to_ecluster);
jbe@0 2413 Datum pgl_ebox_to_ecluster(PG_FUNCTION_ARGS) {
jbe@0 2414 pgl_box *box = (pgl_box *)PG_GETARG_POINTER(0);
jbe@0 2415 double lon, dlon;
jbe@0 2416 int nentries;
jbe@0 2417 pgl_newentry entries[3];
jbe@0 2418 pgl_point points[3][4];
jbe@42 2419 pgl_cluster *cluster;
jbe@0 2420 if (box->lat_min > box->lat_max) {
jbe@0 2421 nentries = 0;
jbe@0 2422 } else if (box->lon_min > box->lon_max) {
jbe@0 2423 if (box->lon_min < 0) {
jbe@0 2424 lon = pgl_round((box->lon_min + 180) / 2.0);
jbe@0 2425 nentries = 3;
jbe@0 2426 pgl_ebox_to_ecluster_macro(0, box->lon_min, lon);
jbe@0 2427 pgl_ebox_to_ecluster_macro(1, lon, 180);
jbe@0 2428 pgl_ebox_to_ecluster_macro(2, -180, box->lon_max);
jbe@0 2429 } else if (box->lon_max > 0) {
jbe@0 2430 lon = pgl_round((box->lon_max - 180) / 2.0);
jbe@0 2431 nentries = 3;
jbe@0 2432 pgl_ebox_to_ecluster_macro(0, box->lon_min, 180);
jbe@0 2433 pgl_ebox_to_ecluster_macro(1, -180, lon);
jbe@0 2434 pgl_ebox_to_ecluster_macro(2, lon, box->lon_max);
jbe@0 2435 } else {
jbe@0 2436 nentries = 2;
jbe@0 2437 pgl_ebox_to_ecluster_macro(0, box->lon_min, 180);
jbe@0 2438 pgl_ebox_to_ecluster_macro(1, -180, box->lon_max);
jbe@0 2439 }
jbe@0 2440 } else {
jbe@0 2441 dlon = pgl_round(box->lon_max - box->lon_min);
jbe@0 2442 if (dlon < 180) {
jbe@0 2443 nentries = 1;
jbe@0 2444 pgl_ebox_to_ecluster_macro(0, box->lon_min, box->lon_max);
jbe@0 2445 } else {
jbe@0 2446 lon = pgl_round((box->lon_min + box->lon_max) / 2.0);
jbe@0 2447 if (
jbe@0 2448 pgl_round(lon - box->lon_min) < 180 &&
jbe@0 2449 pgl_round(box->lon_max - lon) < 180
jbe@0 2450 ) {
jbe@0 2451 nentries = 2;
jbe@0 2452 pgl_ebox_to_ecluster_macro(0, box->lon_min, lon);
jbe@0 2453 pgl_ebox_to_ecluster_macro(1, lon, box->lon_max);
jbe@0 2454 } else {
jbe@0 2455 nentries = 3;
jbe@0 2456 pgl_ebox_to_ecluster_macro(0, box->lon_min, -60);
jbe@0 2457 pgl_ebox_to_ecluster_macro(1, -60, 60);
jbe@0 2458 pgl_ebox_to_ecluster_macro(2, 60, box->lon_max);
jbe@0 2459 }
jbe@0 2460 }
jbe@0 2461 }
jbe@42 2462 cluster = pgl_new_cluster(nentries, entries);
jbe@42 2463 pgl_finalize_cluster(cluster); /* NOTE: should not fail */
jbe@42 2464 PG_RETURN_POINTER(cluster);
jbe@0 2465 }
jbe@0 2466
jbe@0 2467 /* extract latitude from point ("epoint") */
jbe@0 2468 PG_FUNCTION_INFO_V1(pgl_epoint_lat);
jbe@0 2469 Datum pgl_epoint_lat(PG_FUNCTION_ARGS) {
jbe@0 2470 PG_RETURN_FLOAT8(((pgl_point *)PG_GETARG_POINTER(0))->lat);
jbe@0 2471 }
jbe@0 2472
jbe@0 2473 /* extract longitude from point ("epoint") */
jbe@0 2474 PG_FUNCTION_INFO_V1(pgl_epoint_lon);
jbe@0 2475 Datum pgl_epoint_lon(PG_FUNCTION_ARGS) {
jbe@0 2476 PG_RETURN_FLOAT8(((pgl_point *)PG_GETARG_POINTER(0))->lon);
jbe@0 2477 }
jbe@0 2478
jbe@0 2479 /* extract minimum latitude from box ("ebox") */
jbe@0 2480 PG_FUNCTION_INFO_V1(pgl_ebox_lat_min);
jbe@0 2481 Datum pgl_ebox_lat_min(PG_FUNCTION_ARGS) {
jbe@0 2482 PG_RETURN_FLOAT8(((pgl_box *)PG_GETARG_POINTER(0))->lat_min);
jbe@0 2483 }
jbe@0 2484
jbe@0 2485 /* extract maximum latitude from box ("ebox") */
jbe@0 2486 PG_FUNCTION_INFO_V1(pgl_ebox_lat_max);
jbe@0 2487 Datum pgl_ebox_lat_max(PG_FUNCTION_ARGS) {
jbe@0 2488 PG_RETURN_FLOAT8(((pgl_box *)PG_GETARG_POINTER(0))->lat_max);
jbe@0 2489 }
jbe@0 2490
jbe@0 2491 /* extract minimum longitude from box ("ebox") */
jbe@0 2492 PG_FUNCTION_INFO_V1(pgl_ebox_lon_min);
jbe@0 2493 Datum pgl_ebox_lon_min(PG_FUNCTION_ARGS) {
jbe@0 2494 PG_RETURN_FLOAT8(((pgl_box *)PG_GETARG_POINTER(0))->lon_min);
jbe@0 2495 }
jbe@0 2496
jbe@0 2497 /* extract maximum longitude from box ("ebox") */
jbe@0 2498 PG_FUNCTION_INFO_V1(pgl_ebox_lon_max);
jbe@0 2499 Datum pgl_ebox_lon_max(PG_FUNCTION_ARGS) {
jbe@0 2500 PG_RETURN_FLOAT8(((pgl_box *)PG_GETARG_POINTER(0))->lon_max);
jbe@0 2501 }
jbe@0 2502
jbe@0 2503 /* extract center point from circle ("ecircle") */
jbe@0 2504 PG_FUNCTION_INFO_V1(pgl_ecircle_center);
jbe@0 2505 Datum pgl_ecircle_center(PG_FUNCTION_ARGS) {
jbe@0 2506 PG_RETURN_POINTER(&(((pgl_circle *)PG_GETARG_POINTER(0))->center));
jbe@0 2507 }
jbe@0 2508
jbe@0 2509 /* extract radius from circle ("ecircle") */
jbe@0 2510 PG_FUNCTION_INFO_V1(pgl_ecircle_radius);
jbe@0 2511 Datum pgl_ecircle_radius(PG_FUNCTION_ARGS) {
jbe@0 2512 PG_RETURN_FLOAT8(((pgl_circle *)PG_GETARG_POINTER(0))->radius);
jbe@0 2513 }
jbe@0 2514
jbe@0 2515 /* check if point is inside box (overlap operator "&&") in SQL */
jbe@0 2516 PG_FUNCTION_INFO_V1(pgl_epoint_ebox_overlap);
jbe@0 2517 Datum pgl_epoint_ebox_overlap(PG_FUNCTION_ARGS) {
jbe@0 2518 pgl_point *point = (pgl_point *)PG_GETARG_POINTER(0);
jbe@0 2519 pgl_box *box = (pgl_box *)PG_GETARG_POINTER(1);
jbe@0 2520 PG_RETURN_BOOL(pgl_point_in_box(point, box));
jbe@0 2521 }
jbe@0 2522
jbe@0 2523 /* check if point is inside circle (overlap operator "&&") in SQL */
jbe@0 2524 PG_FUNCTION_INFO_V1(pgl_epoint_ecircle_overlap);
jbe@0 2525 Datum pgl_epoint_ecircle_overlap(PG_FUNCTION_ARGS) {
jbe@0 2526 pgl_point *point = (pgl_point *)PG_GETARG_POINTER(0);
jbe@0 2527 pgl_circle *circle = (pgl_circle *)PG_GETARG_POINTER(1);
jbe@0 2528 PG_RETURN_BOOL(
jbe@0 2529 pgl_distance(
jbe@0 2530 point->lat, point->lon,
jbe@0 2531 circle->center.lat, circle->center.lon
jbe@0 2532 ) <= circle->radius
jbe@0 2533 );
jbe@0 2534 }
jbe@0 2535
jbe@0 2536 /* check if point is inside cluster (overlap operator "&&") in SQL */
jbe@0 2537 PG_FUNCTION_INFO_V1(pgl_epoint_ecluster_overlap);
jbe@0 2538 Datum pgl_epoint_ecluster_overlap(PG_FUNCTION_ARGS) {
jbe@0 2539 pgl_point *point = (pgl_point *)PG_GETARG_POINTER(0);
jbe@0 2540 pgl_cluster *cluster = (pgl_cluster *)PG_DETOAST_DATUM(PG_GETARG_DATUM(1));
jbe@16 2541 bool retval;
jbe@16 2542 /* points outside bounding circle are always assumed to be non-overlapping
jbe@16 2543 (necessary for consistent table and index scans) */
jbe@16 2544 if (
jbe@16 2545 pgl_distance(
jbe@16 2546 point->lat, point->lon,
jbe@16 2547 cluster->bounding.center.lat, cluster->bounding.center.lon
jbe@16 2548 ) > cluster->bounding.radius
jbe@16 2549 ) retval = false;
jbe@20 2550 else retval = pgl_point_in_cluster(point, cluster, false);
jbe@0 2551 PG_FREE_IF_COPY(cluster, 1);
jbe@0 2552 PG_RETURN_BOOL(retval);
jbe@0 2553 }
jbe@0 2554
jbe@10 2555 /* check if point may be inside cluster (lossy overl. operator "&&+") in SQL */
jbe@10 2556 PG_FUNCTION_INFO_V1(pgl_epoint_ecluster_may_overlap);
jbe@10 2557 Datum pgl_epoint_ecluster_may_overlap(PG_FUNCTION_ARGS) {
jbe@10 2558 pgl_point *point = (pgl_point *)PG_GETARG_POINTER(0);
jbe@10 2559 pgl_cluster *cluster = (pgl_cluster *)PG_DETOAST_DATUM(PG_GETARG_DATUM(1));
jbe@10 2560 bool retval = pgl_distance(
jbe@10 2561 point->lat, point->lon,
jbe@10 2562 cluster->bounding.center.lat, cluster->bounding.center.lon
jbe@10 2563 ) <= cluster->bounding.radius;
jbe@10 2564 PG_FREE_IF_COPY(cluster, 1);
jbe@10 2565 PG_RETURN_BOOL(retval);
jbe@10 2566 }
jbe@10 2567
jbe@0 2568 /* check if two boxes overlap (overlap operator "&&") in SQL */
jbe@0 2569 PG_FUNCTION_INFO_V1(pgl_ebox_overlap);
jbe@0 2570 Datum pgl_ebox_overlap(PG_FUNCTION_ARGS) {
jbe@0 2571 pgl_box *box1 = (pgl_box *)PG_GETARG_POINTER(0);
jbe@0 2572 pgl_box *box2 = (pgl_box *)PG_GETARG_POINTER(1);
jbe@0 2573 PG_RETURN_BOOL(pgl_boxes_overlap(box1, box2));
jbe@0 2574 }
jbe@0 2575
jbe@10 2576 /* check if box and circle may overlap (lossy overl. operator "&&+") in SQL */
jbe@10 2577 PG_FUNCTION_INFO_V1(pgl_ebox_ecircle_may_overlap);
jbe@10 2578 Datum pgl_ebox_ecircle_may_overlap(PG_FUNCTION_ARGS) {
jbe@10 2579 pgl_box *box = (pgl_box *)PG_GETARG_POINTER(0);
jbe@10 2580 pgl_circle *circle = (pgl_circle *)PG_GETARG_POINTER(1);
jbe@10 2581 PG_RETURN_BOOL(
jbe@10 2582 pgl_estimate_point_box_distance(&circle->center, box) <= circle->radius
jbe@10 2583 );
jbe@10 2584 }
jbe@10 2585
jbe@10 2586 /* check if box and cluster may overlap (lossy overl. operator "&&+") in SQL */
jbe@10 2587 PG_FUNCTION_INFO_V1(pgl_ebox_ecluster_may_overlap);
jbe@10 2588 Datum pgl_ebox_ecluster_may_overlap(PG_FUNCTION_ARGS) {
jbe@10 2589 pgl_box *box = (pgl_box *)PG_GETARG_POINTER(0);
jbe@10 2590 pgl_cluster *cluster = (pgl_cluster *)PG_DETOAST_DATUM(PG_GETARG_DATUM(1));
jbe@10 2591 bool retval = pgl_estimate_point_box_distance(
jbe@10 2592 &cluster->bounding.center,
jbe@10 2593 box
jbe@10 2594 ) <= cluster->bounding.radius;
jbe@10 2595 PG_FREE_IF_COPY(cluster, 1);
jbe@10 2596 PG_RETURN_BOOL(retval);
jbe@10 2597 }
jbe@10 2598
jbe@0 2599 /* check if two circles overlap (overlap operator "&&") in SQL */
jbe@0 2600 PG_FUNCTION_INFO_V1(pgl_ecircle_overlap);
jbe@0 2601 Datum pgl_ecircle_overlap(PG_FUNCTION_ARGS) {
jbe@0 2602 pgl_circle *circle1 = (pgl_circle *)PG_GETARG_POINTER(0);
jbe@0 2603 pgl_circle *circle2 = (pgl_circle *)PG_GETARG_POINTER(1);
jbe@0 2604 PG_RETURN_BOOL(
jbe@0 2605 pgl_distance(
jbe@0 2606 circle1->center.lat, circle1->center.lon,
jbe@0 2607 circle2->center.lat, circle2->center.lon
jbe@0 2608 ) <= circle1->radius + circle2->radius
jbe@0 2609 );
jbe@0 2610 }
jbe@0 2611
jbe@0 2612 /* check if circle and cluster overlap (overlap operator "&&") in SQL */
jbe@0 2613 PG_FUNCTION_INFO_V1(pgl_ecircle_ecluster_overlap);
jbe@0 2614 Datum pgl_ecircle_ecluster_overlap(PG_FUNCTION_ARGS) {
jbe@0 2615 pgl_circle *circle = (pgl_circle *)PG_GETARG_POINTER(0);
jbe@0 2616 pgl_cluster *cluster = (pgl_cluster *)PG_DETOAST_DATUM(PG_GETARG_DATUM(1));
jbe@0 2617 bool retval = (
jbe@0 2618 pgl_point_cluster_distance(&(circle->center), cluster) <= circle->radius
jbe@0 2619 );
jbe@0 2620 PG_FREE_IF_COPY(cluster, 1);
jbe@0 2621 PG_RETURN_BOOL(retval);
jbe@0 2622 }
jbe@0 2623
jbe@17 2624 /* check if circle and cluster may overlap (l. ov. operator "&&+") in SQL */
jbe@10 2625 PG_FUNCTION_INFO_V1(pgl_ecircle_ecluster_may_overlap);
jbe@10 2626 Datum pgl_ecircle_ecluster_may_overlap(PG_FUNCTION_ARGS) {
jbe@10 2627 pgl_circle *circle = (pgl_circle *)PG_GETARG_POINTER(0);
jbe@10 2628 pgl_cluster *cluster = (pgl_cluster *)PG_DETOAST_DATUM(PG_GETARG_DATUM(1));
jbe@10 2629 bool retval = pgl_distance(
jbe@10 2630 circle->center.lat, circle->center.lon,
jbe@10 2631 cluster->bounding.center.lat, cluster->bounding.center.lon
jbe@10 2632 ) <= circle->radius + cluster->bounding.radius;
jbe@10 2633 PG_FREE_IF_COPY(cluster, 1);
jbe@10 2634 PG_RETURN_BOOL(retval);
jbe@10 2635 }
jbe@10 2636
jbe@16 2637 /* check if two clusters overlap (overlap operator "&&") in SQL */
jbe@16 2638 PG_FUNCTION_INFO_V1(pgl_ecluster_overlap);
jbe@16 2639 Datum pgl_ecluster_overlap(PG_FUNCTION_ARGS) {
jbe@16 2640 pgl_cluster *cluster1 = (pgl_cluster *)PG_DETOAST_DATUM(PG_GETARG_DATUM(0));
jbe@16 2641 pgl_cluster *cluster2 = (pgl_cluster *)PG_DETOAST_DATUM(PG_GETARG_DATUM(1));
jbe@16 2642 bool retval;
jbe@16 2643 /* clusters with non-touching bounding circles are always assumed to be
jbe@16 2644 non-overlapping (improves performance and is necessary for consistent
jbe@16 2645 table and index scans) */
jbe@16 2646 if (
jbe@16 2647 pgl_distance(
jbe@16 2648 cluster1->bounding.center.lat, cluster1->bounding.center.lon,
jbe@16 2649 cluster2->bounding.center.lat, cluster2->bounding.center.lon
jbe@16 2650 ) > cluster1->bounding.radius + cluster2->bounding.radius
jbe@16 2651 ) retval = false;
jbe@16 2652 else retval = pgl_clusters_overlap(cluster1, cluster2);
jbe@16 2653 PG_FREE_IF_COPY(cluster1, 0);
jbe@16 2654 PG_FREE_IF_COPY(cluster2, 1);
jbe@16 2655 PG_RETURN_BOOL(retval);
jbe@16 2656 }
jbe@16 2657
jbe@10 2658 /* check if two clusters may overlap (lossy overlap operator "&&+") in SQL */
jbe@10 2659 PG_FUNCTION_INFO_V1(pgl_ecluster_may_overlap);
jbe@10 2660 Datum pgl_ecluster_may_overlap(PG_FUNCTION_ARGS) {
jbe@10 2661 pgl_cluster *cluster1 = (pgl_cluster *)PG_DETOAST_DATUM(PG_GETARG_DATUM(0));
jbe@10 2662 pgl_cluster *cluster2 = (pgl_cluster *)PG_DETOAST_DATUM(PG_GETARG_DATUM(1));
jbe@10 2663 bool retval = pgl_distance(
jbe@10 2664 cluster1->bounding.center.lat, cluster1->bounding.center.lon,
jbe@10 2665 cluster2->bounding.center.lat, cluster2->bounding.center.lon
jbe@10 2666 ) <= cluster1->bounding.radius + cluster2->bounding.radius;
jbe@10 2667 PG_FREE_IF_COPY(cluster1, 0);
jbe@10 2668 PG_FREE_IF_COPY(cluster2, 1);
jbe@10 2669 PG_RETURN_BOOL(retval);
jbe@10 2670 }
jbe@10 2671
jbe@16 2672 /* check if second cluster is in first cluster (cont. operator "@>) in SQL */
jbe@16 2673 PG_FUNCTION_INFO_V1(pgl_ecluster_contains);
jbe@16 2674 Datum pgl_ecluster_contains(PG_FUNCTION_ARGS) {
jbe@16 2675 pgl_cluster *outer = (pgl_cluster *)PG_DETOAST_DATUM(PG_GETARG_DATUM(0));
jbe@16 2676 pgl_cluster *inner = (pgl_cluster *)PG_DETOAST_DATUM(PG_GETARG_DATUM(1));
jbe@16 2677 bool retval;
jbe@16 2678 /* clusters with non-touching bounding circles are always assumed to be
jbe@16 2679 non-overlapping (improves performance and is necessary for consistent
jbe@16 2680 table and index scans) */
jbe@16 2681 if (
jbe@16 2682 pgl_distance(
jbe@16 2683 outer->bounding.center.lat, outer->bounding.center.lon,
jbe@16 2684 inner->bounding.center.lat, inner->bounding.center.lon
jbe@16 2685 ) > outer->bounding.radius + inner->bounding.radius
jbe@16 2686 ) retval = false;
jbe@16 2687 else retval = pgl_cluster_in_cluster(outer, inner);
jbe@16 2688 PG_FREE_IF_COPY(outer, 0);
jbe@16 2689 PG_FREE_IF_COPY(inner, 1);
jbe@16 2690 PG_RETURN_BOOL(retval);
jbe@16 2691 }
jbe@16 2692
jbe@0 2693 /* calculate distance between two points ("<->" operator) in SQL */
jbe@0 2694 PG_FUNCTION_INFO_V1(pgl_epoint_distance);
jbe@0 2695 Datum pgl_epoint_distance(PG_FUNCTION_ARGS) {
jbe@0 2696 pgl_point *point1 = (pgl_point *)PG_GETARG_POINTER(0);
jbe@0 2697 pgl_point *point2 = (pgl_point *)PG_GETARG_POINTER(1);
jbe@0 2698 PG_RETURN_FLOAT8(pgl_distance(
jbe@0 2699 point1->lat, point1->lon, point2->lat, point2->lon
jbe@0 2700 ));
jbe@0 2701 }
jbe@0 2702
jbe@0 2703 /* calculate point to circle distance ("<->" operator) in SQL */
jbe@0 2704 PG_FUNCTION_INFO_V1(pgl_epoint_ecircle_distance);
jbe@0 2705 Datum pgl_epoint_ecircle_distance(PG_FUNCTION_ARGS) {
jbe@0 2706 pgl_point *point = (pgl_point *)PG_GETARG_POINTER(0);
jbe@0 2707 pgl_circle *circle = (pgl_circle *)PG_GETARG_POINTER(1);
jbe@0 2708 double distance = pgl_distance(
jbe@0 2709 point->lat, point->lon, circle->center.lat, circle->center.lon
jbe@0 2710 ) - circle->radius;
jbe@0 2711 PG_RETURN_FLOAT8((distance <= 0) ? 0 : distance);
jbe@0 2712 }
jbe@0 2713
jbe@0 2714 /* calculate point to cluster distance ("<->" operator) in SQL */
jbe@0 2715 PG_FUNCTION_INFO_V1(pgl_epoint_ecluster_distance);
jbe@0 2716 Datum pgl_epoint_ecluster_distance(PG_FUNCTION_ARGS) {
jbe@0 2717 pgl_point *point = (pgl_point *)PG_GETARG_POINTER(0);
jbe@0 2718 pgl_cluster *cluster = (pgl_cluster *)PG_DETOAST_DATUM(PG_GETARG_DATUM(1));
jbe@0 2719 double distance = pgl_point_cluster_distance(point, cluster);
jbe@0 2720 PG_FREE_IF_COPY(cluster, 1);
jbe@0 2721 PG_RETURN_FLOAT8(distance);
jbe@0 2722 }
jbe@0 2723
jbe@0 2724 /* calculate distance between two circles ("<->" operator) in SQL */
jbe@0 2725 PG_FUNCTION_INFO_V1(pgl_ecircle_distance);
jbe@0 2726 Datum pgl_ecircle_distance(PG_FUNCTION_ARGS) {
jbe@0 2727 pgl_circle *circle1 = (pgl_circle *)PG_GETARG_POINTER(0);
jbe@0 2728 pgl_circle *circle2 = (pgl_circle *)PG_GETARG_POINTER(1);
jbe@0 2729 double distance = pgl_distance(
jbe@0 2730 circle1->center.lat, circle1->center.lon,
jbe@0 2731 circle2->center.lat, circle2->center.lon
jbe@0 2732 ) - (circle1->radius + circle2->radius);
jbe@0 2733 PG_RETURN_FLOAT8((distance <= 0) ? 0 : distance);
jbe@0 2734 }
jbe@0 2735
jbe@0 2736 /* calculate circle to cluster distance ("<->" operator) in SQL */
jbe@0 2737 PG_FUNCTION_INFO_V1(pgl_ecircle_ecluster_distance);
jbe@0 2738 Datum pgl_ecircle_ecluster_distance(PG_FUNCTION_ARGS) {
jbe@0 2739 pgl_circle *circle = (pgl_circle *)PG_GETARG_POINTER(0);
jbe@0 2740 pgl_cluster *cluster = (pgl_cluster *)PG_DETOAST_DATUM(PG_GETARG_DATUM(1));
jbe@0 2741 double distance = (
jbe@0 2742 pgl_point_cluster_distance(&(circle->center), cluster) - circle->radius
jbe@0 2743 );
jbe@0 2744 PG_FREE_IF_COPY(cluster, 1);
jbe@0 2745 PG_RETURN_FLOAT8((distance <= 0) ? 0 : distance);
jbe@0 2746 }
jbe@0 2747
jbe@16 2748 /* calculate distance between two clusters ("<->" operator) in SQL */
jbe@16 2749 PG_FUNCTION_INFO_V1(pgl_ecluster_distance);
jbe@16 2750 Datum pgl_ecluster_distance(PG_FUNCTION_ARGS) {
jbe@16 2751 pgl_cluster *cluster1 = (pgl_cluster *)PG_DETOAST_DATUM(PG_GETARG_DATUM(0));
jbe@16 2752 pgl_cluster *cluster2 = (pgl_cluster *)PG_DETOAST_DATUM(PG_GETARG_DATUM(1));
jbe@16 2753 double retval = pgl_cluster_distance(cluster1, cluster2);
jbe@16 2754 PG_FREE_IF_COPY(cluster1, 0);
jbe@16 2755 PG_FREE_IF_COPY(cluster2, 1);
jbe@16 2756 PG_RETURN_FLOAT8(retval);
jbe@16 2757 }
jbe@16 2758
jbe@42 2759 PG_FUNCTION_INFO_V1(pgl_ecluster_monte_carlo_area);
jbe@42 2760 Datum pgl_ecluster_monte_carlo_area(PG_FUNCTION_ARGS) {
jbe@42 2761 pgl_cluster *cluster = (pgl_cluster *)PG_DETOAST_DATUM(PG_GETARG_DATUM(0));
jbe@42 2762 int samples = PG_GETARG_INT32(1);
jbe@42 2763 double retval = pgl_monte_carlo_area(cluster, samples);
jbe@42 2764 PG_FREE_IF_COPY(cluster, 0);
jbe@42 2765 PG_RETURN_FLOAT8(retval);
jbe@42 2766 }
jbe@42 2767
jbe@42 2768 PG_FUNCTION_INFO_V1(pgl_ecluster_epoint_fair_distance);
jbe@42 2769 Datum pgl_ecluster_epoint_fair_distance(PG_FUNCTION_ARGS) {
jbe@42 2770 pgl_cluster *cluster = (pgl_cluster *)PG_DETOAST_DATUM(PG_GETARG_DATUM(0));
jbe@42 2771 pgl_point *point = (pgl_point *)PG_GETARG_POINTER(1);
jbe@42 2772 int samples = PG_GETARG_INT32(2);
jbe@42 2773 double retval = pgl_fair_distance(point, cluster, samples);
jbe@42 2774 PG_FREE_IF_COPY(cluster, 0);
jbe@42 2775 PG_RETURN_FLOAT8(retval);
jbe@42 2776 }
jbe@42 2777
jbe@0 2778
jbe@0 2779 /*-----------------------------------------------------------*
jbe@0 2780 * B-tree comparison operators and index support functions *
jbe@0 2781 *-----------------------------------------------------------*/
jbe@0 2782
jbe@0 2783 /* macro for a B-tree operator (without detoasting) */
jbe@0 2784 #define PGL_BTREE_OPER(func, type, cmpfunc, oper) \
jbe@0 2785 PG_FUNCTION_INFO_V1(func); \
jbe@0 2786 Datum func(PG_FUNCTION_ARGS) { \
jbe@0 2787 type *a = (type *)PG_GETARG_POINTER(0); \
jbe@0 2788 type *b = (type *)PG_GETARG_POINTER(1); \
jbe@0 2789 PG_RETURN_BOOL(cmpfunc(a, b) oper 0); \
jbe@0 2790 }
jbe@0 2791
jbe@0 2792 /* macro for a B-tree comparison function (without detoasting) */
jbe@0 2793 #define PGL_BTREE_CMP(func, type, cmpfunc) \
jbe@0 2794 PG_FUNCTION_INFO_V1(func); \
jbe@0 2795 Datum func(PG_FUNCTION_ARGS) { \
jbe@0 2796 type *a = (type *)PG_GETARG_POINTER(0); \
jbe@0 2797 type *b = (type *)PG_GETARG_POINTER(1); \
jbe@0 2798 PG_RETURN_INT32(cmpfunc(a, b)); \
jbe@0 2799 }
jbe@0 2800
jbe@0 2801 /* macro for a B-tree operator (with detoasting) */
jbe@0 2802 #define PGL_BTREE_OPER_DETOAST(func, type, cmpfunc, oper) \
jbe@0 2803 PG_FUNCTION_INFO_V1(func); \
jbe@0 2804 Datum func(PG_FUNCTION_ARGS) { \
jbe@0 2805 bool res; \
jbe@0 2806 type *a = (type *)PG_DETOAST_DATUM(PG_GETARG_DATUM(0)); \
jbe@0 2807 type *b = (type *)PG_DETOAST_DATUM(PG_GETARG_DATUM(1)); \
jbe@0 2808 res = cmpfunc(a, b) oper 0; \
jbe@0 2809 PG_FREE_IF_COPY(a, 0); \
jbe@0 2810 PG_FREE_IF_COPY(b, 1); \
jbe@0 2811 PG_RETURN_BOOL(res); \
jbe@0 2812 }
jbe@0 2813
jbe@0 2814 /* macro for a B-tree comparison function (with detoasting) */
jbe@0 2815 #define PGL_BTREE_CMP_DETOAST(func, type, cmpfunc) \
jbe@0 2816 PG_FUNCTION_INFO_V1(func); \
jbe@0 2817 Datum func(PG_FUNCTION_ARGS) { \
jbe@0 2818 int32_t res; \
jbe@0 2819 type *a = (type *)PG_DETOAST_DATUM(PG_GETARG_DATUM(0)); \
jbe@0 2820 type *b = (type *)PG_DETOAST_DATUM(PG_GETARG_DATUM(1)); \
jbe@0 2821 res = cmpfunc(a, b); \
jbe@0 2822 PG_FREE_IF_COPY(a, 0); \
jbe@0 2823 PG_FREE_IF_COPY(b, 1); \
jbe@0 2824 PG_RETURN_INT32(res); \
jbe@0 2825 }
jbe@0 2826
jbe@0 2827 /* B-tree operators and comparison function for point */
jbe@0 2828 PGL_BTREE_OPER(pgl_btree_epoint_lt, pgl_point, pgl_point_cmp, <)
jbe@0 2829 PGL_BTREE_OPER(pgl_btree_epoint_le, pgl_point, pgl_point_cmp, <=)
jbe@0 2830 PGL_BTREE_OPER(pgl_btree_epoint_eq, pgl_point, pgl_point_cmp, ==)
jbe@0 2831 PGL_BTREE_OPER(pgl_btree_epoint_ne, pgl_point, pgl_point_cmp, !=)
jbe@0 2832 PGL_BTREE_OPER(pgl_btree_epoint_ge, pgl_point, pgl_point_cmp, >=)
jbe@0 2833 PGL_BTREE_OPER(pgl_btree_epoint_gt, pgl_point, pgl_point_cmp, >)
jbe@0 2834 PGL_BTREE_CMP(pgl_btree_epoint_cmp, pgl_point, pgl_point_cmp)
jbe@0 2835
jbe@0 2836 /* B-tree operators and comparison function for box */
jbe@0 2837 PGL_BTREE_OPER(pgl_btree_ebox_lt, pgl_box, pgl_box_cmp, <)
jbe@0 2838 PGL_BTREE_OPER(pgl_btree_ebox_le, pgl_box, pgl_box_cmp, <=)
jbe@0 2839 PGL_BTREE_OPER(pgl_btree_ebox_eq, pgl_box, pgl_box_cmp, ==)
jbe@0 2840 PGL_BTREE_OPER(pgl_btree_ebox_ne, pgl_box, pgl_box_cmp, !=)
jbe@0 2841 PGL_BTREE_OPER(pgl_btree_ebox_ge, pgl_box, pgl_box_cmp, >=)
jbe@0 2842 PGL_BTREE_OPER(pgl_btree_ebox_gt, pgl_box, pgl_box_cmp, >)
jbe@0 2843 PGL_BTREE_CMP(pgl_btree_ebox_cmp, pgl_box, pgl_box_cmp)
jbe@0 2844
jbe@0 2845 /* B-tree operators and comparison function for circle */
jbe@0 2846 PGL_BTREE_OPER(pgl_btree_ecircle_lt, pgl_circle, pgl_circle_cmp, <)
jbe@0 2847 PGL_BTREE_OPER(pgl_btree_ecircle_le, pgl_circle, pgl_circle_cmp, <=)
jbe@0 2848 PGL_BTREE_OPER(pgl_btree_ecircle_eq, pgl_circle, pgl_circle_cmp, ==)
jbe@0 2849 PGL_BTREE_OPER(pgl_btree_ecircle_ne, pgl_circle, pgl_circle_cmp, !=)
jbe@0 2850 PGL_BTREE_OPER(pgl_btree_ecircle_ge, pgl_circle, pgl_circle_cmp, >=)
jbe@0 2851 PGL_BTREE_OPER(pgl_btree_ecircle_gt, pgl_circle, pgl_circle_cmp, >)
jbe@0 2852 PGL_BTREE_CMP(pgl_btree_ecircle_cmp, pgl_circle, pgl_circle_cmp)
jbe@0 2853
jbe@0 2854
jbe@0 2855 /*--------------------------------*
jbe@0 2856 * GiST index support functions *
jbe@0 2857 *--------------------------------*/
jbe@0 2858
jbe@0 2859 /* GiST "consistent" support function */
jbe@0 2860 PG_FUNCTION_INFO_V1(pgl_gist_consistent);
jbe@0 2861 Datum pgl_gist_consistent(PG_FUNCTION_ARGS) {
jbe@0 2862 GISTENTRY *entry = (GISTENTRY *) PG_GETARG_POINTER(0);
jbe@0 2863 pgl_keyptr key = (pgl_keyptr)DatumGetPointer(entry->key);
jbe@0 2864 StrategyNumber strategy = (StrategyNumber)PG_GETARG_UINT16(2);
jbe@0 2865 bool *recheck = (bool *)PG_GETARG_POINTER(4);
jbe@0 2866 /* demand recheck because index and query methods are lossy */
jbe@0 2867 *recheck = true;
jbe@10 2868 /* strategy number aliases for different operators using the same strategy */
jbe@10 2869 strategy %= 100;
jbe@0 2870 /* strategy number 11: equality of two points */
jbe@0 2871 if (strategy == 11) {
jbe@0 2872 /* query datum is another point */
jbe@0 2873 pgl_point *query = (pgl_point *)PG_GETARG_POINTER(1);
jbe@0 2874 /* convert other point to key */
jbe@0 2875 pgl_pointkey querykey;
jbe@0 2876 pgl_point_to_key(query, querykey);
jbe@0 2877 /* return true if both keys overlap */
jbe@0 2878 PG_RETURN_BOOL(pgl_keys_overlap(key, querykey));
jbe@0 2879 }
jbe@0 2880 /* strategy number 13: equality of two circles */
jbe@0 2881 if (strategy == 13) {
jbe@0 2882 /* query datum is another circle */
jbe@0 2883 pgl_circle *query = (pgl_circle *)PG_GETARG_POINTER(1);
jbe@0 2884 /* convert other circle to key */
jbe@0 2885 pgl_areakey querykey;
jbe@0 2886 pgl_circle_to_key(query, querykey);
jbe@0 2887 /* return true if both keys overlap */
jbe@0 2888 PG_RETURN_BOOL(pgl_keys_overlap(key, querykey));
jbe@0 2889 }
jbe@0 2890 /* for all remaining strategies, keys on empty objects produce no match */
jbe@0 2891 /* (check necessary because query radius may be infinite) */
jbe@0 2892 if (PGL_KEY_IS_EMPTY(key)) PG_RETURN_BOOL(false);
jbe@0 2893 /* strategy number 21: overlapping with point */
jbe@0 2894 if (strategy == 21) {
jbe@0 2895 /* query datum is a point */
jbe@0 2896 pgl_point *query = (pgl_point *)PG_GETARG_POINTER(1);
jbe@0 2897 /* return true if estimated distance (allowed to be smaller than real
jbe@0 2898 distance) between index key and point is zero */
jbe@0 2899 PG_RETURN_BOOL(pgl_estimate_key_distance(key, query) == 0);
jbe@0 2900 }
jbe@0 2901 /* strategy number 22: (point) overlapping with box */
jbe@0 2902 if (strategy == 22) {
jbe@0 2903 /* query datum is a box */
jbe@0 2904 pgl_box *query = (pgl_box *)PG_GETARG_POINTER(1);
jbe@0 2905 /* determine bounding box of indexed key */
jbe@0 2906 pgl_box keybox;
jbe@0 2907 pgl_key_to_box(key, &keybox);
jbe@0 2908 /* return true if query box overlaps with bounding box of indexed key */
jbe@0 2909 PG_RETURN_BOOL(pgl_boxes_overlap(query, &keybox));
jbe@0 2910 }
jbe@0 2911 /* strategy number 23: overlapping with circle */
jbe@0 2912 if (strategy == 23) {
jbe@0 2913 /* query datum is a circle */
jbe@0 2914 pgl_circle *query = (pgl_circle *)PG_GETARG_POINTER(1);
jbe@0 2915 /* return true if estimated distance (allowed to be smaller than real
jbe@0 2916 distance) between index key and circle center is smaller than radius */
jbe@0 2917 PG_RETURN_BOOL(
jbe@0 2918 pgl_estimate_key_distance(key, &(query->center)) <= query->radius
jbe@0 2919 );
jbe@0 2920 }
jbe@0 2921 /* strategy number 24: overlapping with cluster */
jbe@0 2922 if (strategy == 24) {
jbe@0 2923 bool retval; /* return value */
jbe@0 2924 /* query datum is a cluster */
jbe@0 2925 pgl_cluster *query = (pgl_cluster *)PG_DETOAST_DATUM(PG_GETARG_DATUM(1));
jbe@0 2926 /* return true if estimated distance (allowed to be smaller than real
jbe@0 2927 distance) between index key and circle center is smaller than radius */
jbe@0 2928 retval = (
jbe@0 2929 pgl_estimate_key_distance(key, &(query->bounding.center)) <=
jbe@0 2930 query->bounding.radius
jbe@0 2931 );
jbe@0 2932 PG_FREE_IF_COPY(query, 1); /* free detoasted cluster (if copy) */
jbe@0 2933 PG_RETURN_BOOL(retval);
jbe@0 2934 }
jbe@0 2935 /* throw error for any unknown strategy number */
jbe@0 2936 elog(ERROR, "unrecognized strategy number: %d", strategy);
jbe@0 2937 }
jbe@0 2938
jbe@0 2939 /* GiST "union" support function */
jbe@0 2940 PG_FUNCTION_INFO_V1(pgl_gist_union);
jbe@0 2941 Datum pgl_gist_union(PG_FUNCTION_ARGS) {
jbe@0 2942 GistEntryVector *entryvec = (GistEntryVector *)PG_GETARG_POINTER(0);
jbe@0 2943 pgl_keyptr out; /* return value (to be palloc'ed) */
jbe@0 2944 int i;
jbe@0 2945 /* determine key size */
jbe@0 2946 size_t keysize = PGL_KEY_IS_AREAKEY(
jbe@0 2947 (pgl_keyptr)DatumGetPointer(entryvec->vector[0].key)
jbe@0 2948 ) ? sizeof (pgl_areakey) : sizeof(pgl_pointkey);
jbe@0 2949 /* begin with first key as result */
jbe@0 2950 out = palloc(keysize);
jbe@0 2951 memcpy(out, (pgl_keyptr)DatumGetPointer(entryvec->vector[0].key), keysize);
jbe@0 2952 /* unite current result with second, third, etc. key */
jbe@0 2953 for (i=1; i<entryvec->n; i++) {
jbe@0 2954 pgl_unite_keys(out, (pgl_keyptr)DatumGetPointer(entryvec->vector[i].key));
jbe@0 2955 }
jbe@0 2956 /* return result */
jbe@0 2957 PG_RETURN_POINTER(out);
jbe@0 2958 }
jbe@0 2959
jbe@0 2960 /* GiST "compress" support function for indicis on points */
jbe@0 2961 PG_FUNCTION_INFO_V1(pgl_gist_compress_epoint);
jbe@0 2962 Datum pgl_gist_compress_epoint(PG_FUNCTION_ARGS) {
jbe@0 2963 GISTENTRY *entry = (GISTENTRY *) PG_GETARG_POINTER(0);
jbe@0 2964 GISTENTRY *retval; /* return value (to be palloc'ed unless set to entry) */
jbe@0 2965 /* only transform new leaves */
jbe@0 2966 if (entry->leafkey) {
jbe@0 2967 /* get point to be transformed */
jbe@0 2968 pgl_point *point = (pgl_point *)DatumGetPointer(entry->key);
jbe@0 2969 /* allocate memory for key */
jbe@0 2970 pgl_keyptr key = palloc(sizeof(pgl_pointkey));
jbe@0 2971 /* transform point to key */
jbe@0 2972 pgl_point_to_key(point, key);
jbe@0 2973 /* create new GISTENTRY structure as return value */
jbe@0 2974 retval = palloc(sizeof(GISTENTRY));
jbe@0 2975 gistentryinit(
jbe@0 2976 *retval, PointerGetDatum(key),
jbe@0 2977 entry->rel, entry->page, entry->offset, FALSE
jbe@0 2978 );
jbe@0 2979 } else {
jbe@0 2980 /* inner nodes have already been transformed */
jbe@0 2981 retval = entry;
jbe@0 2982 }
jbe@0 2983 /* return pointer to old or new GISTENTRY structure */
jbe@0 2984 PG_RETURN_POINTER(retval);
jbe@0 2985 }
jbe@0 2986
jbe@0 2987 /* GiST "compress" support function for indicis on circles */
jbe@0 2988 PG_FUNCTION_INFO_V1(pgl_gist_compress_ecircle);
jbe@0 2989 Datum pgl_gist_compress_ecircle(PG_FUNCTION_ARGS) {
jbe@0 2990 GISTENTRY *entry = (GISTENTRY *) PG_GETARG_POINTER(0);
jbe@0 2991 GISTENTRY *retval; /* return value (to be palloc'ed unless set to entry) */
jbe@0 2992 /* only transform new leaves */
jbe@0 2993 if (entry->leafkey) {
jbe@0 2994 /* get circle to be transformed */
jbe@0 2995 pgl_circle *circle = (pgl_circle *)DatumGetPointer(entry->key);
jbe@0 2996 /* allocate memory for key */
jbe@0 2997 pgl_keyptr key = palloc(sizeof(pgl_areakey));
jbe@0 2998 /* transform circle to key */
jbe@0 2999 pgl_circle_to_key(circle, key);
jbe@0 3000 /* create new GISTENTRY structure as return value */
jbe@0 3001 retval = palloc(sizeof(GISTENTRY));
jbe@0 3002 gistentryinit(
jbe@0 3003 *retval, PointerGetDatum(key),
jbe@0 3004 entry->rel, entry->page, entry->offset, FALSE
jbe@0 3005 );
jbe@0 3006 } else {
jbe@0 3007 /* inner nodes have already been transformed */
jbe@0 3008 retval = entry;
jbe@0 3009 }
jbe@0 3010 /* return pointer to old or new GISTENTRY structure */
jbe@0 3011 PG_RETURN_POINTER(retval);
jbe@0 3012 }
jbe@0 3013
jbe@0 3014 /* GiST "compress" support function for indices on clusters */
jbe@0 3015 PG_FUNCTION_INFO_V1(pgl_gist_compress_ecluster);
jbe@0 3016 Datum pgl_gist_compress_ecluster(PG_FUNCTION_ARGS) {
jbe@0 3017 GISTENTRY *entry = (GISTENTRY *) PG_GETARG_POINTER(0);
jbe@0 3018 GISTENTRY *retval; /* return value (to be palloc'ed unless set to entry) */
jbe@0 3019 /* only transform new leaves */
jbe@0 3020 if (entry->leafkey) {
jbe@0 3021 /* get cluster to be transformed (detoasting necessary!) */
jbe@0 3022 pgl_cluster *cluster = (pgl_cluster *)PG_DETOAST_DATUM(entry->key);
jbe@0 3023 /* allocate memory for key */
jbe@0 3024 pgl_keyptr key = palloc(sizeof(pgl_areakey));
jbe@0 3025 /* transform cluster to key */
jbe@0 3026 pgl_circle_to_key(&(cluster->bounding), key);
jbe@0 3027 /* create new GISTENTRY structure as return value */
jbe@0 3028 retval = palloc(sizeof(GISTENTRY));
jbe@0 3029 gistentryinit(
jbe@0 3030 *retval, PointerGetDatum(key),
jbe@0 3031 entry->rel, entry->page, entry->offset, FALSE
jbe@0 3032 );
jbe@0 3033 /* free detoasted datum */
jbe@0 3034 if ((void *)cluster != (void *)DatumGetPointer(entry->key)) pfree(cluster);
jbe@0 3035 } else {
jbe@0 3036 /* inner nodes have already been transformed */
jbe@0 3037 retval = entry;
jbe@0 3038 }
jbe@0 3039 /* return pointer to old or new GISTENTRY structure */
jbe@0 3040 PG_RETURN_POINTER(retval);
jbe@0 3041 }
jbe@0 3042
jbe@0 3043 /* GiST "decompress" support function for indices */
jbe@0 3044 PG_FUNCTION_INFO_V1(pgl_gist_decompress);
jbe@0 3045 Datum pgl_gist_decompress(PG_FUNCTION_ARGS) {
jbe@0 3046 /* return passed pointer without transformation */
jbe@0 3047 PG_RETURN_POINTER(PG_GETARG_POINTER(0));
jbe@0 3048 }
jbe@0 3049
jbe@0 3050 /* GiST "penalty" support function */
jbe@0 3051 PG_FUNCTION_INFO_V1(pgl_gist_penalty);
jbe@0 3052 Datum pgl_gist_penalty(PG_FUNCTION_ARGS) {
jbe@0 3053 GISTENTRY *origentry = (GISTENTRY *)PG_GETARG_POINTER(0);
jbe@0 3054 GISTENTRY *newentry = (GISTENTRY *)PG_GETARG_POINTER(1);
jbe@0 3055 float *penalty = (float *)PG_GETARG_POINTER(2);
jbe@0 3056 /* get original key and key to insert */
jbe@0 3057 pgl_keyptr orig = (pgl_keyptr)DatumGetPointer(origentry->key);
jbe@0 3058 pgl_keyptr new = (pgl_keyptr)DatumGetPointer(newentry->key);
jbe@0 3059 /* copy original key */
jbe@0 3060 union { pgl_pointkey pointkey; pgl_areakey areakey; } union_key;
jbe@0 3061 if (PGL_KEY_IS_AREAKEY(orig)) {
jbe@0 3062 memcpy(union_key.areakey, orig, sizeof(union_key.areakey));
jbe@0 3063 } else {
jbe@0 3064 memcpy(union_key.pointkey, orig, sizeof(union_key.pointkey));
jbe@0 3065 }
jbe@0 3066 /* calculate union of both keys */
jbe@0 3067 pgl_unite_keys((pgl_keyptr)&union_key, new);
jbe@0 3068 /* penalty equal to reduction of key length (logarithm of added area) */
jbe@0 3069 /* (return value by setting referenced value and returning pointer) */
jbe@0 3070 *penalty = (
jbe@0 3071 PGL_KEY_NODEDEPTH(orig) - PGL_KEY_NODEDEPTH((pgl_keyptr)&union_key)
jbe@0 3072 );
jbe@0 3073 PG_RETURN_POINTER(penalty);
jbe@0 3074 }
jbe@0 3075
jbe@0 3076 /* GiST "picksplit" support function */
jbe@0 3077 PG_FUNCTION_INFO_V1(pgl_gist_picksplit);
jbe@0 3078 Datum pgl_gist_picksplit(PG_FUNCTION_ARGS) {
jbe@0 3079 GistEntryVector *entryvec = (GistEntryVector *)PG_GETARG_POINTER(0);
jbe@0 3080 GIST_SPLITVEC *v = (GIST_SPLITVEC *)PG_GETARG_POINTER(1);
jbe@0 3081 OffsetNumber i; /* between FirstOffsetNumber and entryvec->n (inclusive) */
jbe@0 3082 union {
jbe@0 3083 pgl_pointkey pointkey;
jbe@0 3084 pgl_areakey areakey;
jbe@0 3085 } union_all; /* union of all keys (to be calculated from scratch)
jbe@0 3086 (later cut in half) */
jbe@0 3087 int is_areakey = PGL_KEY_IS_AREAKEY(
jbe@0 3088 (pgl_keyptr)DatumGetPointer(entryvec->vector[FirstOffsetNumber].key)
jbe@0 3089 );
jbe@0 3090 int keysize = is_areakey ? sizeof(pgl_areakey) : sizeof(pgl_pointkey);
jbe@0 3091 pgl_keyptr unionL = palloc(keysize); /* union of keys that go left */
jbe@0 3092 pgl_keyptr unionR = palloc(keysize); /* union of keys that go right */
jbe@0 3093 pgl_keyptr key; /* current key to be processed */
jbe@0 3094 /* allocate memory for array of left and right keys, set counts to zero */
jbe@0 3095 v->spl_left = (OffsetNumber *)palloc(entryvec->n * sizeof(OffsetNumber));
jbe@0 3096 v->spl_nleft = 0;
jbe@0 3097 v->spl_right = (OffsetNumber *)palloc(entryvec->n * sizeof(OffsetNumber));
jbe@0 3098 v->spl_nright = 0;
jbe@0 3099 /* calculate union of all keys from scratch */
jbe@0 3100 memcpy(
jbe@0 3101 (pgl_keyptr)&union_all,
jbe@0 3102 (pgl_keyptr)DatumGetPointer(entryvec->vector[FirstOffsetNumber].key),
jbe@0 3103 keysize
jbe@0 3104 );
jbe@0 3105 for (i=FirstOffsetNumber+1; i<entryvec->n; i=OffsetNumberNext(i)) {
jbe@0 3106 pgl_unite_keys(
jbe@0 3107 (pgl_keyptr)&union_all,
jbe@0 3108 (pgl_keyptr)DatumGetPointer(entryvec->vector[i].key)
jbe@0 3109 );
jbe@0 3110 }
jbe@0 3111 /* check if trivial split is necessary due to exhausted key length */
jbe@0 3112 /* (Note: keys for empty objects must have node depth set to maximum) */
jbe@0 3113 if (PGL_KEY_NODEDEPTH((pgl_keyptr)&union_all) == (
jbe@0 3114 is_areakey ? PGL_AREAKEY_MAXDEPTH : PGL_POINTKEY_MAXDEPTH
jbe@0 3115 )) {
jbe@0 3116 /* half of all keys go left */
jbe@0 3117 for (
jbe@0 3118 i=FirstOffsetNumber;
jbe@0 3119 i<FirstOffsetNumber+(entryvec->n - FirstOffsetNumber)/2;
jbe@0 3120 i=OffsetNumberNext(i)
jbe@0 3121 ) {
jbe@0 3122 /* pointer to current key */
jbe@0 3123 key = (pgl_keyptr)DatumGetPointer(entryvec->vector[i].key);
jbe@0 3124 /* update unionL */
jbe@0 3125 /* check if key is first key that goes left */
jbe@0 3126 if (!v->spl_nleft) {
jbe@0 3127 /* first key that goes left is just copied to unionL */
jbe@0 3128 memcpy(unionL, key, keysize);
jbe@0 3129 } else {
jbe@0 3130 /* unite current value and next key */
jbe@0 3131 pgl_unite_keys(unionL, key);
jbe@0 3132 }
jbe@0 3133 /* append offset number to list of keys that go left */
jbe@0 3134 v->spl_left[v->spl_nleft++] = i;
jbe@0 3135 }
jbe@0 3136 /* other half goes right */
jbe@0 3137 for (
jbe@0 3138 i=FirstOffsetNumber+(entryvec->n - FirstOffsetNumber)/2;
jbe@0 3139 i<entryvec->n;
jbe@0 3140 i=OffsetNumberNext(i)
jbe@0 3141 ) {
jbe@0 3142 /* pointer to current key */
jbe@0 3143 key = (pgl_keyptr)DatumGetPointer(entryvec->vector[i].key);
jbe@0 3144 /* update unionR */
jbe@0 3145 /* check if key is first key that goes right */
jbe@0 3146 if (!v->spl_nright) {
jbe@0 3147 /* first key that goes right is just copied to unionR */
jbe@0 3148 memcpy(unionR, key, keysize);
jbe@0 3149 } else {
jbe@0 3150 /* unite current value and next key */
jbe@0 3151 pgl_unite_keys(unionR, key);
jbe@0 3152 }
jbe@0 3153 /* append offset number to list of keys that go right */
jbe@0 3154 v->spl_right[v->spl_nright++] = i;
jbe@0 3155 }
jbe@0 3156 }
jbe@0 3157 /* otherwise, a non-trivial split is possible */
jbe@0 3158 else {
jbe@0 3159 /* cut covered area in half */
jbe@0 3160 /* (union_all then refers to area of keys that go left) */
jbe@0 3161 /* check if union of all keys covers empty and non-empty objects */
jbe@0 3162 if (PGL_KEY_IS_UNIVERSAL((pgl_keyptr)&union_all)) {
jbe@0 3163 /* if yes, split into empty and non-empty objects */
jbe@0 3164 pgl_key_set_empty((pgl_keyptr)&union_all);
jbe@0 3165 } else {
jbe@0 3166 /* otherwise split by next bit */
jbe@0 3167 ((pgl_keyptr)&union_all)[PGL_KEY_NODEDEPTH_OFFSET]++;
jbe@0 3168 /* NOTE: type bit conserved */
jbe@0 3169 }
jbe@0 3170 /* determine for each key if it goes left or right */
jbe@0 3171 for (i=FirstOffsetNumber; i<entryvec->n; i=OffsetNumberNext(i)) {
jbe@0 3172 /* pointer to current key */
jbe@0 3173 key = (pgl_keyptr)DatumGetPointer(entryvec->vector[i].key);
jbe@0 3174 /* keys within one half of the area go left */
jbe@0 3175 if (pgl_keys_overlap((pgl_keyptr)&union_all, key)) {
jbe@0 3176 /* update unionL */
jbe@0 3177 /* check if key is first key that goes left */
jbe@0 3178 if (!v->spl_nleft) {
jbe@0 3179 /* first key that goes left is just copied to unionL */
jbe@0 3180 memcpy(unionL, key, keysize);
jbe@0 3181 } else {
jbe@0 3182 /* unite current value of unionL and processed key */
jbe@0 3183 pgl_unite_keys(unionL, key);
jbe@0 3184 }
jbe@0 3185 /* append offset number to list of keys that go left */
jbe@0 3186 v->spl_left[v->spl_nleft++] = i;
jbe@0 3187 }
jbe@0 3188 /* the other keys go right */
jbe@0 3189 else {
jbe@0 3190 /* update unionR */
jbe@0 3191 /* check if key is first key that goes right */
jbe@0 3192 if (!v->spl_nright) {
jbe@0 3193 /* first key that goes right is just copied to unionR */
jbe@0 3194 memcpy(unionR, key, keysize);
jbe@0 3195 } else {
jbe@0 3196 /* unite current value of unionR and processed key */
jbe@0 3197 pgl_unite_keys(unionR, key);
jbe@0 3198 }
jbe@0 3199 /* append offset number to list of keys that go right */
jbe@0 3200 v->spl_right[v->spl_nright++] = i;
jbe@0 3201 }
jbe@0 3202 }
jbe@0 3203 }
jbe@0 3204 /* store unions in return value */
jbe@0 3205 v->spl_ldatum = PointerGetDatum(unionL);
jbe@0 3206 v->spl_rdatum = PointerGetDatum(unionR);
jbe@0 3207 /* return all results */
jbe@0 3208 PG_RETURN_POINTER(v);
jbe@0 3209 }
jbe@0 3210
jbe@0 3211 /* GiST "same"/"equal" support function */
jbe@0 3212 PG_FUNCTION_INFO_V1(pgl_gist_same);
jbe@0 3213 Datum pgl_gist_same(PG_FUNCTION_ARGS) {
jbe@0 3214 pgl_keyptr key1 = (pgl_keyptr)PG_GETARG_POINTER(0);
jbe@0 3215 pgl_keyptr key2 = (pgl_keyptr)PG_GETARG_POINTER(1);
jbe@0 3216 bool *boolptr = (bool *)PG_GETARG_POINTER(2);
jbe@0 3217 /* two keys are equal if they are binary equal */
jbe@0 3218 /* (return result by setting referenced boolean and returning pointer) */
jbe@0 3219 *boolptr = !memcmp(
jbe@0 3220 key1,
jbe@0 3221 key2,
jbe@0 3222 PGL_KEY_IS_AREAKEY(key1) ? sizeof(pgl_areakey) : sizeof(pgl_pointkey)
jbe@0 3223 );
jbe@0 3224 PG_RETURN_POINTER(boolptr);
jbe@0 3225 }
jbe@0 3226
jbe@0 3227 /* GiST "distance" support function */
jbe@0 3228 PG_FUNCTION_INFO_V1(pgl_gist_distance);
jbe@0 3229 Datum pgl_gist_distance(PG_FUNCTION_ARGS) {
jbe@0 3230 GISTENTRY *entry = (GISTENTRY *)PG_GETARG_POINTER(0);
jbe@0 3231 pgl_keyptr key = (pgl_keyptr)DatumGetPointer(entry->key);
jbe@0 3232 StrategyNumber strategy = (StrategyNumber)PG_GETARG_UINT16(2);
jbe@0 3233 bool *recheck = (bool *)PG_GETARG_POINTER(4);
jbe@0 3234 double distance; /* return value */
jbe@0 3235 /* demand recheck because distance is just an estimation */
jbe@0 3236 /* (real distance may be bigger) */
jbe@0 3237 *recheck = true;
jbe@10 3238 /* strategy number aliases for different operators using the same strategy */
jbe@10 3239 strategy %= 100;
jbe@0 3240 /* strategy number 31: distance to point */
jbe@0 3241 if (strategy == 31) {
jbe@0 3242 /* query datum is a point */
jbe@0 3243 pgl_point *query = (pgl_point *)PG_GETARG_POINTER(1);
jbe@0 3244 /* use pgl_estimate_pointkey_distance() function to compute result */
jbe@0 3245 distance = pgl_estimate_key_distance(key, query);
jbe@0 3246 /* avoid infinity (reserved!) */
jbe@0 3247 if (!isfinite(distance)) distance = PGL_ULTRA_DISTANCE;
jbe@0 3248 /* return result */
jbe@0 3249 PG_RETURN_FLOAT8(distance);
jbe@0 3250 }
jbe@0 3251 /* strategy number 33: distance to circle */
jbe@0 3252 if (strategy == 33) {
jbe@0 3253 /* query datum is a circle */
jbe@0 3254 pgl_circle *query = (pgl_circle *)PG_GETARG_POINTER(1);
jbe@0 3255 /* estimate distance to circle center and substract circle radius */
jbe@0 3256 distance = (
jbe@0 3257 pgl_estimate_key_distance(key, &(query->center)) - query->radius
jbe@0 3258 );
jbe@0 3259 /* convert non-positive values to zero and avoid infinity (reserved!) */
jbe@0 3260 if (distance <= 0) distance = 0;
jbe@0 3261 else if (!isfinite(distance)) distance = PGL_ULTRA_DISTANCE;
jbe@0 3262 /* return result */
jbe@0 3263 PG_RETURN_FLOAT8(distance);
jbe@0 3264 }
jbe@0 3265 /* strategy number 34: distance to cluster */
jbe@0 3266 if (strategy == 34) {
jbe@0 3267 /* query datum is a cluster */
jbe@0 3268 pgl_cluster *query = (pgl_cluster *)PG_DETOAST_DATUM(PG_GETARG_DATUM(1));
jbe@0 3269 /* estimate distance to bounding center and substract bounding radius */
jbe@0 3270 distance = (
jbe@0 3271 pgl_estimate_key_distance(key, &(query->bounding.center)) -
jbe@0 3272 query->bounding.radius
jbe@0 3273 );
jbe@0 3274 /* convert non-positive values to zero and avoid infinity (reserved!) */
jbe@0 3275 if (distance <= 0) distance = 0;
jbe@0 3276 else if (!isfinite(distance)) distance = PGL_ULTRA_DISTANCE;
jbe@0 3277 /* free detoasted cluster (if copy) */
jbe@0 3278 PG_FREE_IF_COPY(query, 1);
jbe@0 3279 /* return result */
jbe@0 3280 PG_RETURN_FLOAT8(distance);
jbe@0 3281 }
jbe@0 3282 /* throw error for any unknown strategy number */
jbe@0 3283 elog(ERROR, "unrecognized strategy number: %d", strategy);
jbe@0 3284 }
jbe@0 3285

Impressum / About Us