sqlite
[Ported from github.com/sqlite/sqlite] Fix bugs in and improve the interface to the ".check" command of the CLI.
Brought by drakestapleton
sqlite / ext / rtree / geopoly.c
| 1 | /* |
| 2 | ** 2018-05-25 |
| 3 | ** |
| 4 | ** The author disclaims copyright to this source code. In place of |
| 5 | ** a legal notice, here is a blessing: |
| 6 | ** |
| 7 | ** May you do good and not evil. |
| 8 | ** May you find forgiveness for yourself and forgive others. |
| 9 | ** May you share freely, never taking more than you give. |
| 10 | ** |
| 11 | ****************************************************************************** |
| 12 | ** |
| 13 | ** This file implements an alternative R-Tree virtual table that |
| 14 | ** uses polygons to express the boundaries of 2-dimensional objects. |
| 15 | ** |
| 16 | ** This file is #include-ed onto the end of "rtree.c" so that it has |
| 17 | ** access to all of the R-Tree internals. |
| 18 | */ |
| 19 | #include <stdlib.h> |
| 20 | |
| 21 | /* Enable -DGEOPOLY_ENABLE_DEBUG for debugging facilities */ |
| 22 | #ifdef GEOPOLY_ENABLE_DEBUG |
| 23 | static int geo_debug = 0; |
| 24 | # define GEODEBUG(X) if(geo_debug)printf X |
| 25 | #else |
| 26 | # define GEODEBUG(X) |
| 27 | #endif |
| 28 | |
| 29 | /* Character class routines */ |
| 30 | #ifdef sqlite3Isdigit |
| 31 | /* Use the SQLite core versions if this routine is part of the |
| 32 | ** SQLite amalgamation */ |
| 33 | # define safe_isdigit(x) sqlite3Isdigit(x) |
| 34 | # define safe_isalnum(x) sqlite3Isalnum(x) |
| 35 | # define safe_isxdigit(x) sqlite3Isxdigit(x) |
| 36 | #else |
| 37 | /* Use the standard library for separate compilation */ |
| 38 | #include <ctype.h> /* amalgamator: keep */ |
| 39 | # define safe_isdigit(x) isdigit((unsigned char)(x)) |
| 40 | # define safe_isalnum(x) isalnum((unsigned char)(x)) |
| 41 | # define safe_isxdigit(x) isxdigit((unsigned char)(x)) |
| 42 | #endif |
| 43 | |
| 44 | #ifndef JSON_NULL /* The following stuff repeats things found in json1 */ |
| 45 | /* |
| 46 | ** Growing our own isspace() routine this way is twice as fast as |
| 47 | ** the library isspace() function. |
| 48 | */ |
| 49 | static const char geopolyIsSpace[] = { |
| 50 | 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 0, 0, |
| 51 | 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, |
| 52 | 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, |
| 53 | 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, |
| 54 | 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, |
| 55 | 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, |
| 56 | 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, |
| 57 | 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, |
| 58 | 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, |
| 59 | 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, |
| 60 | 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, |
| 61 | 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, |
| 62 | 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, |
| 63 | 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, |
| 64 | 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, |
| 65 | 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, |
| 66 | }; |
| 67 | #define fast_isspace(x) (geopolyIsSpace[(unsigned char)x]) |
| 68 | #endif /* JSON NULL - back to original code */ |
| 69 | |
| 70 | /* Compiler and version */ |
| 71 | #ifndef GCC_VERSION |
| 72 | #if defined(__GNUC__) && !defined(SQLITE_DISABLE_INTRINSIC) |
| 73 | # define GCC_VERSION (__GNUC__*1000000+__GNUC_MINOR__*1000+__GNUC_PATCHLEVEL__) |
| 74 | #else |
| 75 | # define GCC_VERSION 0 |
| 76 | #endif |
| 77 | #endif |
| 78 | #ifndef MSVC_VERSION |
| 79 | #if defined(_MSC_VER) && !defined(SQLITE_DISABLE_INTRINSIC) |
| 80 | # define MSVC_VERSION _MSC_VER |
| 81 | #else |
| 82 | # define MSVC_VERSION 0 |
| 83 | #endif |
| 84 | #endif |
| 85 | |
| 86 | /* Datatype for coordinates |
| 87 | */ |
| 88 | typedef float GeoCoord; |
| 89 | |
| 90 | /* |
| 91 | ** Internal representation of a polygon. |
| 92 | ** |
| 93 | ** The polygon consists of a sequence of vertexes. There is a line |
| 94 | ** segment between each pair of vertexes, and one final segment from |
| 95 | ** the last vertex back to the first. (This differs from the GeoJSON |
| 96 | ** standard in which the final vertex is a repeat of the first.) |
| 97 | ** |
| 98 | ** The polygon follows the right-hand rule. The area to the right of |
| 99 | ** each segment is "outside" and the area to the left is "inside". |
| 100 | ** |
| 101 | ** The on-disk representation consists of a 4-byte header followed by |
| 102 | ** the values. The 4-byte header is: |
| 103 | ** |
| 104 | ** encoding (1 byte) 0=big-endian, 1=little-endian |
| 105 | ** nvertex (3 bytes) Number of vertexes as a big-endian integer |
| 106 | ** |
| 107 | ** Enough space is allocated for 4 coordinates, to work around over-zealous |
| 108 | ** warnings coming from some compiler (notably, clang). In reality, the size |
| 109 | ** of each GeoPoly memory allocate is adjusted as necessary so that the |
| 110 | ** GeoPoly.a[] array at the end is the appropriate size. |
| 111 | */ |
| 112 | typedef struct GeoPoly GeoPoly; |
| 113 | struct GeoPoly { |
| 114 | int nVertex; /* Number of vertexes */ |
| 115 | unsigned char hdr[4]; /* Header for on-disk representation */ |
| 116 | GeoCoord a[8]; /* 2*nVertex values. X (longitude) first, then Y */ |
| 117 | }; |
| 118 | |
| 119 | /* The size of a memory allocation needed for a GeoPoly object sufficient |
| 120 | ** to hold N coordinate pairs. |
| 121 | */ |
| 122 | #define GEOPOLY_SZ(N) (sizeof(GeoPoly) + sizeof(GeoCoord)*2*((N)-4)) |
| 123 | |
| 124 | /* Macros to access coordinates of a GeoPoly. |
| 125 | ** We have to use these macros, rather than just say p->a[i] in order |
| 126 | ** to silence (incorrect) UBSAN warnings if the array index is too large. |
| 127 | */ |
| 128 | #define GeoX(P,I) (((GeoCoord*)(P)->a)[(I)*2]) |
| 129 | #define GeoY(P,I) (((GeoCoord*)(P)->a)[(I)*2+1]) |
| 130 | |
| 131 | |
| 132 | /* |
| 133 | ** State of a parse of a GeoJSON input. |
| 134 | */ |
| 135 | typedef struct GeoParse GeoParse; |
| 136 | struct GeoParse { |
| 137 | const unsigned char *z; /* Unparsed input */ |
| 138 | int nVertex; /* Number of vertexes in a[] */ |
| 139 | int nAlloc; /* Space allocated to a[] */ |
| 140 | int nErr; /* Number of errors encountered */ |
| 141 | GeoCoord *a; /* Array of vertexes. From sqlite3_malloc64() */ |
| 142 | }; |
| 143 | |
| 144 | /* Do a 4-byte byte swap */ |
| 145 | static void geopolySwab32(unsigned char *a){ |
| 146 | unsigned char t = a[0]; |
| 147 | a[0] = a[3]; |
| 148 | a[3] = t; |
| 149 | t = a[1]; |
| 150 | a[1] = a[2]; |
| 151 | a[2] = t; |
| 152 | } |
| 153 | |
| 154 | /* Skip whitespace. Return the next non-whitespace character. */ |
| 155 | static char geopolySkipSpace(GeoParse *p){ |
| 156 | while( fast_isspace(p->z[0]) ) p->z++; |
| 157 | return p->z[0]; |
| 158 | } |
| 159 | |
| 160 | /* Parse out a number. Write the value into *pVal if pVal!=0. |
| 161 | ** return non-zero on success and zero if the next token is not a number. |
| 162 | */ |
| 163 | static int geopolyParseNumber(GeoParse *p, GeoCoord *pVal){ |
| 164 | char c = geopolySkipSpace(p); |
| 165 | const unsigned char *z = p->z; |
| 166 | int j = 0; |
| 167 | int seenDP = 0; |
| 168 | int seenE = 0; |
| 169 | if( c=='-' ){ |
| 170 | j = 1; |
| 171 | c = z[j]; |
| 172 | } |
| 173 | if( c=='0' && z[j+1]>='0' && z[j+1]<='9' ) return 0; |
| 174 | for(;; j++){ |
| 175 | c = z[j]; |
| 176 | if( safe_isdigit(c) ) continue; |
| 177 | if( c=='.' ){ |
| 178 | if( z[j-1]=='-' ) return 0; |
| 179 | if( seenDP ) return 0; |
| 180 | seenDP = 1; |
| 181 | continue; |
| 182 | } |
| 183 | if( c=='e' || c=='E' ){ |
| 184 | if( z[j-1]<'0' ) return 0; |
| 185 | if( seenE ) return -1; |
| 186 | seenDP = seenE = 1; |
| 187 | c = z[j+1]; |
| 188 | if( c=='+' || c=='-' ){ |
| 189 | j++; |
| 190 | c = z[j+1]; |
| 191 | } |
| 192 | if( c<'0' || c>'9' ) return 0; |
| 193 | continue; |
| 194 | } |
| 195 | break; |
| 196 | } |
| 197 | if( z[j-1]<'0' ) return 0; |
| 198 | if( pVal ){ |
| 199 | #ifdef SQLITE_AMALGAMATION |
| 200 | /* The sqlite3AtoF() routine is much much faster than atof(), if it |
| 201 | ** is available */ |
| 202 | double r; |
| 203 | (void)sqlite3AtoF((const char*)p->z, &r); |
| 204 | *pVal = r; |
| 205 | #else |
| 206 | *pVal = (GeoCoord)atof((const char*)p->z); |
| 207 | #endif |
| 208 | } |
| 209 | p->z += j; |
| 210 | return 1; |
| 211 | } |
| 212 | |
| 213 | /* |
| 214 | ** If the input is a well-formed JSON array of coordinates with at least |
| 215 | ** four coordinates and where each coordinate is itself a two-value array, |
| 216 | ** then convert the JSON into a GeoPoly object and return a pointer to |
| 217 | ** that object. |
| 218 | ** |
| 219 | ** If any error occurs, return NULL. |
| 220 | */ |
| 221 | static GeoPoly *geopolyParseJson(const unsigned char *z, int *pRc){ |
| 222 | GeoParse s; |
| 223 | int rc = SQLITE_OK; |
| 224 | memset(&s, 0, sizeof(s)); |
| 225 | s.z = z; |
| 226 | if( geopolySkipSpace(&s)=='[' ){ |
| 227 | s.z++; |
| 228 | while( geopolySkipSpace(&s)=='[' ){ |
| 229 | int ii = 0; |
| 230 | char c; |
| 231 | s.z++; |
| 232 | if( s.nVertex>=s.nAlloc ){ |
| 233 | GeoCoord *aNew; |
| 234 | s.nAlloc = s.nAlloc*2 + 16; |
| 235 | aNew = sqlite3_realloc64(s.a, s.nAlloc*sizeof(GeoCoord)*2 ); |
| 236 | if( aNew==0 ){ |
| 237 | rc = SQLITE_NOMEM; |
| 238 | s.nErr++; |
| 239 | break; |
| 240 | } |
| 241 | s.a = aNew; |
| 242 | } |
| 243 | while( geopolyParseNumber(&s, ii<=1 ? &s.a[s.nVertex*2+ii] : 0) ){ |
| 244 | ii++; |
| 245 | if( ii==2 ) s.nVertex++; |
| 246 | c = geopolySkipSpace(&s); |
| 247 | s.z++; |
| 248 | if( c==',' ) continue; |
| 249 | if( c==']' && ii>=2 ) break; |
| 250 | s.nErr++; |
| 251 | rc = SQLITE_ERROR; |
| 252 | goto parse_json_err; |
| 253 | } |
| 254 | if( geopolySkipSpace(&s)==',' ){ |
| 255 | s.z++; |
| 256 | continue; |
| 257 | } |
| 258 | break; |
| 259 | } |
| 260 | if( geopolySkipSpace(&s)==']' |
| 261 | && s.nVertex>=4 && s.nVertex<16777216 |
| 262 | && s.a[0]==s.a[s.nVertex*2-2] |
| 263 | && s.a[1]==s.a[s.nVertex*2-1] |
| 264 | && (s.z++, geopolySkipSpace(&s)==0) |
| 265 | ){ |
| 266 | GeoPoly *pOut; |
| 267 | int x = 1; |
| 268 | s.nVertex--; /* Remove the redundant vertex at the end */ |
| 269 | pOut = sqlite3_malloc64( GEOPOLY_SZ((sqlite3_int64)s.nVertex) ); |
| 270 | x = 1; |
| 271 | if( pOut==0 ) goto parse_json_err; |
| 272 | pOut->nVertex = s.nVertex; |
| 273 | memcpy(pOut->a, s.a, s.nVertex*2*sizeof(GeoCoord)); |
| 274 | pOut->hdr[0] = *(unsigned char*)&x; |
| 275 | pOut->hdr[1] = (s.nVertex>>16)&0xff; |
| 276 | pOut->hdr[2] = (s.nVertex>>8)&0xff; |
| 277 | pOut->hdr[3] = s.nVertex&0xff; |
| 278 | sqlite3_free(s.a); |
| 279 | if( pRc ) *pRc = SQLITE_OK; |
| 280 | return pOut; |
| 281 | }else{ |
| 282 | s.nErr++; |
| 283 | rc = SQLITE_ERROR; |
| 284 | } |
| 285 | }else{ |
| 286 | rc = SQLITE_ERROR; |
| 287 | } |
| 288 | parse_json_err: |
| 289 | if( pRc ) *pRc = rc; |
| 290 | sqlite3_free(s.a); |
| 291 | return 0; |
| 292 | } |
| 293 | |
| 294 | /* |
| 295 | ** Given a function parameter, try to interpret it as a polygon, either |
| 296 | ** in the binary format or JSON text. Compute a GeoPoly object and |
| 297 | ** return a pointer to that object. Or if the input is not a well-formed |
| 298 | ** polygon, put an error message in sqlite3_context and return NULL. |
| 299 | */ |
| 300 | static GeoPoly *geopolyFuncParam( |
| 301 | sqlite3_context *pCtx, /* Context for error messages */ |
| 302 | sqlite3_value *pVal, /* The value to decode */ |
| 303 | int *pRc /* Write error here */ |
| 304 | ){ |
| 305 | GeoPoly *p = 0; |
| 306 | int nByte; |
| 307 | testcase( pCtx==0 ); |
| 308 | if( sqlite3_value_type(pVal)==SQLITE_BLOB |
| 309 | && (nByte = sqlite3_value_bytes(pVal))>=(int)(4+6*sizeof(GeoCoord)) |
| 310 | ){ |
| 311 | const unsigned char *a = sqlite3_value_blob(pVal); |
| 312 | int nVertex; |
| 313 | if( a==0 ){ |
| 314 | if( pCtx ) sqlite3_result_error_nomem(pCtx); |
| 315 | return 0; |
| 316 | } |
| 317 | nVertex = (a[1]<<16) + (a[2]<<8) + a[3]; |
| 318 | if( (a[0]==0 || a[0]==1) |
| 319 | && (nVertex*2*sizeof(GeoCoord) + 4)==(unsigned int)nByte |
| 320 | ){ |
| 321 | p = sqlite3_malloc64( sizeof(*p) + (nVertex-1)*2*sizeof(GeoCoord) ); |
| 322 | if( p==0 ){ |
| 323 | if( pRc ) *pRc = SQLITE_NOMEM; |
| 324 | if( pCtx ) sqlite3_result_error_nomem(pCtx); |
| 325 | }else{ |
| 326 | int x = 1; |
| 327 | p->nVertex = nVertex; |
| 328 | memcpy(p->hdr, a, nByte); |
| 329 | if( a[0] != *(unsigned char*)&x ){ |
| 330 | int ii; |
| 331 | for(ii=0; ii<nVertex; ii++){ |
| 332 | geopolySwab32((unsigned char*)&GeoX(p,ii)); |
| 333 | geopolySwab32((unsigned char*)&GeoY(p,ii)); |
| 334 | } |
| 335 | p->hdr[0] ^= 1; |
| 336 | } |
| 337 | if( pRc ) *pRc = SQLITE_OK; |
| 338 | } |
| 339 | }else{ |
| 340 | if( pRc ) *pRc = SQLITE_ERROR; |
| 341 | } |
| 342 | return p; |
| 343 | }else if( sqlite3_value_type(pVal)==SQLITE_TEXT ){ |
| 344 | const unsigned char *zJson = sqlite3_value_text(pVal); |
| 345 | if( zJson==0 ){ |
| 346 | if( pRc ) *pRc = SQLITE_NOMEM; |
| 347 | return 0; |
| 348 | } |
| 349 | return geopolyParseJson(zJson, pRc); |
| 350 | }else{ |
| 351 | if( pRc ) *pRc = SQLITE_ERROR; |
| 352 | return 0; |
| 353 | } |
| 354 | } |
| 355 | |
| 356 | /* |
| 357 | ** Implementation of the geopoly_blob(X) function. |
| 358 | ** |
| 359 | ** If the input is a well-formed Geopoly BLOB or JSON string |
| 360 | ** then return the BLOB representation of the polygon. Otherwise |
| 361 | ** return NULL. |
| 362 | */ |
| 363 | static void geopolyBlobFunc( |
| 364 | sqlite3_context *context, |
| 365 | int argc, |
| 366 | sqlite3_value **argv |
| 367 | ){ |
| 368 | GeoPoly *p = geopolyFuncParam(context, argv[0], 0); |
| 369 | (void)argc; |
| 370 | if( p ){ |
| 371 | sqlite3_result_blob(context, p->hdr, |
| 372 | 4+8*p->nVertex, SQLITE_TRANSIENT); |
| 373 | sqlite3_free(p); |
| 374 | } |
| 375 | } |
| 376 | |
| 377 | /* |
| 378 | ** SQL function: geopoly_json(X) |
| 379 | ** |
| 380 | ** Interpret X as a polygon and render it as a JSON array |
| 381 | ** of coordinates. Or, if X is not a valid polygon, return NULL. |
| 382 | */ |
| 383 | static void geopolyJsonFunc( |
| 384 | sqlite3_context *context, |
| 385 | int argc, |
| 386 | sqlite3_value **argv |
| 387 | ){ |
| 388 | GeoPoly *p = geopolyFuncParam(context, argv[0], 0); |
| 389 | (void)argc; |
| 390 | if( p ){ |
| 391 | sqlite3 *db = sqlite3_context_db_handle(context); |
| 392 | sqlite3_str *x = sqlite3_str_new(db); |
| 393 | int i; |
| 394 | sqlite3_str_append(x, "[", 1); |
| 395 | for(i=0; i<p->nVertex; i++){ |
| 396 | sqlite3_str_appendf(x, "[%!g,%!g],", GeoX(p,i), GeoY(p,i)); |
| 397 | } |
| 398 | sqlite3_str_appendf(x, "[%!g,%!g]]", GeoX(p,0), GeoY(p,0)); |
| 399 | sqlite3_result_str(context, x, SQLITE_FINISH); |
| 400 | sqlite3_free(p); |
| 401 | } |
| 402 | } |
| 403 | |
| 404 | /* |
| 405 | ** SQL function: geopoly_svg(X, ....) |
| 406 | ** |
| 407 | ** Interpret X as a polygon and render it as a SVG <polyline>. |
| 408 | ** Additional arguments are added as attributes to the <polyline>. |
| 409 | */ |
| 410 | static void geopolySvgFunc( |
| 411 | sqlite3_context *context, |
| 412 | int argc, |
| 413 | sqlite3_value **argv |
| 414 | ){ |
| 415 | GeoPoly *p; |
| 416 | if( argc<1 ) return; |
| 417 | p = geopolyFuncParam(context, argv[0], 0); |
| 418 | if( p ){ |
| 419 | sqlite3 *db = sqlite3_context_db_handle(context); |
| 420 | sqlite3_str *x = sqlite3_str_new(db); |
| 421 | int i; |
| 422 | char cSep = '\''; |
| 423 | sqlite3_str_appendf(x, "<polyline points="); |
| 424 | for(i=0; i<p->nVertex; i++){ |
| 425 | sqlite3_str_appendf(x, "%c%g,%g", cSep, GeoX(p,i), GeoY(p,i)); |
| 426 | cSep = ' '; |
| 427 | } |
| 428 | sqlite3_str_appendf(x, " %g,%g'", GeoX(p,0), GeoY(p,0)); |
| 429 | for(i=1; i<argc; i++){ |
| 430 | const char *z = (const char*)sqlite3_value_text(argv[i]); |
| 431 | if( z && z[0] ){ |
| 432 | sqlite3_str_appendf(x, " %s", z); |
| 433 | } |
| 434 | } |
| 435 | sqlite3_str_appendf(x, "></polyline>"); |
| 436 | sqlite3_result_str(context, x, SQLITE_FINISH); |
| 437 | sqlite3_free(p); |
| 438 | } |
| 439 | } |
| 440 | |
| 441 | /* |
| 442 | ** SQL Function: geopoly_xform(poly, A, B, C, D, E, F) |
| 443 | ** |
| 444 | ** Transform and/or translate a polygon as follows: |
| 445 | ** |
| 446 | ** x1 = A*x0 + B*y0 + E |
| 447 | ** y1 = C*x0 + D*y0 + F |
| 448 | ** |
| 449 | ** For a translation: |
| 450 | ** |
| 451 | ** geopoly_xform(poly, 1, 0, 0, 1, x-offset, y-offset) |
| 452 | ** |
| 453 | ** Rotate by R around the point (0,0): |
| 454 | ** |
| 455 | ** geopoly_xform(poly, cos(R), sin(R), -sin(R), cos(R), 0, 0) |
| 456 | */ |
| 457 | static void geopolyXformFunc( |
| 458 | sqlite3_context *context, |
| 459 | int argc, |
| 460 | sqlite3_value **argv |
| 461 | ){ |
| 462 | GeoPoly *p = geopolyFuncParam(context, argv[0], 0); |
| 463 | double A = sqlite3_value_double(argv[1]); |
| 464 | double B = sqlite3_value_double(argv[2]); |
| 465 | double C = sqlite3_value_double(argv[3]); |
| 466 | double D = sqlite3_value_double(argv[4]); |
| 467 | double E = sqlite3_value_double(argv[5]); |
| 468 | double F = sqlite3_value_double(argv[6]); |
| 469 | GeoCoord x1, y1, x0, y0; |
| 470 | int ii; |
| 471 | (void)argc; |
| 472 | if( p ){ |
| 473 | for(ii=0; ii<p->nVertex; ii++){ |
| 474 | x0 = GeoX(p,ii); |
| 475 | y0 = GeoY(p,ii); |
| 476 | x1 = (GeoCoord)(A*x0 + B*y0 + E); |
| 477 | y1 = (GeoCoord)(C*x0 + D*y0 + F); |
| 478 | GeoX(p,ii) = x1; |
| 479 | GeoY(p,ii) = y1; |
| 480 | } |
| 481 | sqlite3_result_blob(context, p->hdr, |
| 482 | 4+8*p->nVertex, SQLITE_TRANSIENT); |
| 483 | sqlite3_free(p); |
| 484 | } |
| 485 | } |
| 486 | |
| 487 | /* |
| 488 | ** Compute the area enclosed by the polygon. |
| 489 | ** |
| 490 | ** This routine can also be used to detect polygons that rotate in |
| 491 | ** the wrong direction. Polygons are suppose to be counter-clockwise (CCW). |
| 492 | ** This routine returns a negative value for clockwise (CW) polygons. |
| 493 | */ |
| 494 | static double geopolyArea(GeoPoly *p){ |
| 495 | double rArea = 0.0; |
| 496 | int ii; |
| 497 | for(ii=0; ii<p->nVertex-1; ii++){ |
| 498 | rArea += (GeoX(p,ii) - GeoX(p,ii+1)) /* (x0 - x1) */ |
| 499 | * (GeoY(p,ii) + GeoY(p,ii+1)) /* (y0 + y1) */ |
| 500 | * 0.5; |
| 501 | } |
| 502 | rArea += (GeoX(p,ii) - GeoX(p,0)) /* (xN - x0) */ |
| 503 | * (GeoY(p,ii) + GeoY(p,0)) /* (yN + y0) */ |
| 504 | * 0.5; |
| 505 | return rArea; |
| 506 | } |
| 507 | |
| 508 | /* |
| 509 | ** Implementation of the geopoly_area(X) function. |
| 510 | ** |
| 511 | ** If the input is a well-formed Geopoly BLOB then return the area |
| 512 | ** enclosed by the polygon. If the polygon circulates clockwise instead |
| 513 | ** of counterclockwise (as it should) then return the negative of the |
| 514 | ** enclosed area. Otherwise return NULL. |
| 515 | */ |
| 516 | static void geopolyAreaFunc( |
| 517 | sqlite3_context *context, |
| 518 | int argc, |
| 519 | sqlite3_value **argv |
| 520 | ){ |
| 521 | GeoPoly *p = geopolyFuncParam(context, argv[0], 0); |
| 522 | (void)argc; |
| 523 | if( p ){ |
| 524 | sqlite3_result_double(context, geopolyArea(p)); |
| 525 | sqlite3_free(p); |
| 526 | } |
| 527 | } |
| 528 | |
| 529 | /* |
| 530 | ** Implementation of the geopoly_ccw(X) function. |
| 531 | ** |
| 532 | ** If the rotation of polygon X is clockwise (incorrect) instead of |
| 533 | ** counter-clockwise (the correct winding order according to RFC7946) |
| 534 | ** then reverse the order of the vertexes in polygon X. |
| 535 | ** |
| 536 | ** In other words, this routine returns a CCW polygon regardless of the |
| 537 | ** winding order of its input. |
| 538 | ** |
| 539 | ** Use this routine to sanitize historical inputs that that sometimes |
| 540 | ** contain polygons that wind in the wrong direction. |
| 541 | */ |
| 542 | static void geopolyCcwFunc( |
| 543 | sqlite3_context *context, |
| 544 | int argc, |
| 545 | sqlite3_value **argv |
| 546 | ){ |
| 547 | GeoPoly *p = geopolyFuncParam(context, argv[0], 0); |
| 548 | (void)argc; |
| 549 | if( p ){ |
| 550 | if( geopolyArea(p)<0.0 ){ |
| 551 | int ii, jj; |
| 552 | for(ii=1, jj=p->nVertex-1; ii<jj; ii++, jj--){ |
| 553 | GeoCoord t = GeoX(p,ii); |
| 554 | GeoX(p,ii) = GeoX(p,jj); |
| 555 | GeoX(p,jj) = t; |
| 556 | t = GeoY(p,ii); |
| 557 | GeoY(p,ii) = GeoY(p,jj); |
| 558 | GeoY(p,jj) = t; |
| 559 | } |
| 560 | } |
| 561 | sqlite3_result_blob(context, p->hdr, |
| 562 | 4+8*p->nVertex, SQLITE_TRANSIENT); |
| 563 | sqlite3_free(p); |
| 564 | } |
| 565 | } |
| 566 | |
| 567 | #define GEOPOLY_PI 3.1415926535897932385 |
| 568 | |
| 569 | /* Fast approximation for sine(X) for X between -0.5*pi and 2*pi |
| 570 | */ |
| 571 | static double geopolySine(double r){ |
| 572 | assert( r>=-0.5*GEOPOLY_PI && r<=2.0*GEOPOLY_PI ); |
| 573 | if( r>=1.5*GEOPOLY_PI ){ |
| 574 | r -= 2.0*GEOPOLY_PI; |
| 575 | } |
| 576 | if( r>=0.5*GEOPOLY_PI ){ |
| 577 | return -geopolySine(r-GEOPOLY_PI); |
| 578 | }else{ |
| 579 | double r2 = r*r; |
| 580 | double r3 = r2*r; |
| 581 | double r5 = r3*r2; |
| 582 | return 0.9996949*r - 0.1656700*r3 + 0.0075134*r5; |
| 583 | } |
| 584 | } |
| 585 | |
| 586 | /* |
| 587 | ** Function: geopoly_regular(X,Y,R,N) |
| 588 | ** |
| 589 | ** Construct a simple, convex, regular polygon centered at X, Y |
| 590 | ** with circumradius R and with N sides. |
| 591 | ** |
| 592 | ** Maximum N is 1000. Maximum R is 1.0e+300. |
| 593 | */ |
| 594 | static void geopolyRegularFunc( |
| 595 | sqlite3_context *context, |
| 596 | int argc, |
| 597 | sqlite3_value **argv |
| 598 | ){ |
| 599 | double x = sqlite3_value_double(argv[0]); |
| 600 | double y = sqlite3_value_double(argv[1]); |
| 601 | double r = sqlite3_value_double(argv[2]); |
| 602 | i64 n = sqlite3_value_int64(argv[3]); |
| 603 | int i; |
| 604 | GeoPoly *p; |
| 605 | (void)argc; |
| 606 | |
| 607 | if( n<3 || r<=0.0 || r>=1e300 ) return; |
| 608 | if( n>1000 ) n = 1000; |
| 609 | p = sqlite3_malloc64( sizeof(*p) + (n-1)*2*sizeof(GeoCoord) ); |
| 610 | if( p==0 ){ |
| 611 | sqlite3_result_error_nomem(context); |
| 612 | return; |
| 613 | } |
| 614 | i = 1; |
| 615 | p->hdr[0] = *(unsigned char*)&i; |
| 616 | p->hdr[1] = 0; |
| 617 | p->hdr[2] = (n>>8)&0xff; |
| 618 | p->hdr[3] = n&0xff; |
| 619 | for(i=0; i<n; i++){ |
| 620 | double rAngle = 2.0*GEOPOLY_PI*i/n; |
| 621 | GeoX(p,i) = x - r*geopolySine(rAngle-0.5*GEOPOLY_PI); |
| 622 | GeoY(p,i) = y + r*geopolySine(rAngle); |
| 623 | } |
| 624 | sqlite3_result_blob(context, p->hdr, 4+8*n, SQLITE_TRANSIENT); |
| 625 | sqlite3_free(p); |
| 626 | } |
| 627 | |
| 628 | /* |
| 629 | ** If pPoly is a polygon, compute its bounding box. Then: |
| 630 | ** |
| 631 | ** (1) if aCoord!=0 store the bounding box in aCoord, returning NULL |
| 632 | ** (2) otherwise, compute a GeoPoly for the bounding box and return the |
| 633 | ** new GeoPoly |
| 634 | ** |
| 635 | ** If pPoly is NULL but aCoord is not NULL, then compute a new GeoPoly from |
| 636 | ** the bounding box in aCoord and return a pointer to that GeoPoly. |
| 637 | */ |
| 638 | static GeoPoly *geopolyBBox( |
| 639 | sqlite3_context *context, /* For recording the error */ |
| 640 | sqlite3_value *pPoly, /* The polygon */ |
| 641 | RtreeCoord *aCoord, /* Results here */ |
| 642 | int *pRc /* Error code here */ |
| 643 | ){ |
| 644 | GeoPoly *pOut = 0; |
| 645 | GeoPoly *p; |
| 646 | float mnX, mxX, mnY, mxY; |
| 647 | if( pPoly==0 && aCoord!=0 ){ |
| 648 | p = 0; |
| 649 | mnX = aCoord[0].f; |
| 650 | mxX = aCoord[1].f; |
| 651 | mnY = aCoord[2].f; |
| 652 | mxY = aCoord[3].f; |
| 653 | goto geopolyBboxFill; |
| 654 | }else{ |
| 655 | p = geopolyFuncParam(context, pPoly, pRc); |
| 656 | } |
| 657 | if( p ){ |
| 658 | int ii; |
| 659 | mnX = mxX = GeoX(p,0); |
| 660 | mnY = mxY = GeoY(p,0); |
| 661 | for(ii=1; ii<p->nVertex; ii++){ |
| 662 | double r = GeoX(p,ii); |
| 663 | if( r<mnX ) mnX = (float)r; |
| 664 | else if( r>mxX ) mxX = (float)r; |
| 665 | r = GeoY(p,ii); |
| 666 | if( r<mnY ) mnY = (float)r; |
| 667 | else if( r>mxY ) mxY = (float)r; |
| 668 | } |
| 669 | if( pRc ) *pRc = SQLITE_OK; |
| 670 | if( aCoord==0 ){ |
| 671 | geopolyBboxFill: |
| 672 | pOut = sqlite3_realloc64(p, GEOPOLY_SZ(4)); |
| 673 | if( pOut==0 ){ |
| 674 | sqlite3_free(p); |
| 675 | if( context ) sqlite3_result_error_nomem(context); |
| 676 | if( pRc ) *pRc = SQLITE_NOMEM; |
| 677 | return 0; |
| 678 | } |
| 679 | pOut->nVertex = 4; |
| 680 | ii = 1; |
| 681 | pOut->hdr[0] = *(unsigned char*)ⅈ |
| 682 | pOut->hdr[1] = 0; |
| 683 | pOut->hdr[2] = 0; |
| 684 | pOut->hdr[3] = 4; |
| 685 | GeoX(pOut,0) = mnX; |
| 686 | GeoY(pOut,0) = mnY; |
| 687 | GeoX(pOut,1) = mxX; |
| 688 | GeoY(pOut,1) = mnY; |
| 689 | GeoX(pOut,2) = mxX; |
| 690 | GeoY(pOut,2) = mxY; |
| 691 | GeoX(pOut,3) = mnX; |
| 692 | GeoY(pOut,3) = mxY; |
| 693 | }else{ |
| 694 | sqlite3_free(p); |
| 695 | aCoord[0].f = mnX; |
| 696 | aCoord[1].f = mxX; |
| 697 | aCoord[2].f = mnY; |
| 698 | aCoord[3].f = mxY; |
| 699 | } |
| 700 | }else if( aCoord ){ |
| 701 | memset(aCoord, 0, sizeof(RtreeCoord)*4); |
| 702 | } |
| 703 | return pOut; |
| 704 | } |
| 705 | |
| 706 | /* |
| 707 | ** Implementation of the geopoly_bbox(X) SQL function. |
| 708 | */ |
| 709 | static void geopolyBBoxFunc( |
| 710 | sqlite3_context *context, |
| 711 | int argc, |
| 712 | sqlite3_value **argv |
| 713 | ){ |
| 714 | GeoPoly *p = geopolyBBox(context, argv[0], 0, 0); |
| 715 | (void)argc; |
| 716 | if( p ){ |
| 717 | sqlite3_result_blob(context, p->hdr, |
| 718 | 4+8*p->nVertex, SQLITE_TRANSIENT); |
| 719 | sqlite3_free(p); |
| 720 | } |
| 721 | } |
| 722 | |
| 723 | /* |
| 724 | ** State vector for the geopoly_group_bbox() aggregate function. |
| 725 | */ |
| 726 | typedef struct GeoBBox GeoBBox; |
| 727 | struct GeoBBox { |
| 728 | int isInit; |
| 729 | RtreeCoord a[4]; |
| 730 | }; |
| 731 | |
| 732 | |
| 733 | /* |
| 734 | ** Implementation of the geopoly_group_bbox(X) aggregate SQL function. |
| 735 | */ |
| 736 | static void geopolyBBoxStep( |
| 737 | sqlite3_context *context, |
| 738 | int argc, |
| 739 | sqlite3_value **argv |
| 740 | ){ |
| 741 | RtreeCoord a[4]; |
| 742 | int rc = SQLITE_OK; |
| 743 | (void)argc; |
| 744 | (void)geopolyBBox(context, argv[0], a, &rc); |
| 745 | if( rc==SQLITE_OK ){ |
| 746 | GeoBBox *pBBox; |
| 747 | pBBox = (GeoBBox*)sqlite3_aggregate_context(context, sizeof(*pBBox)); |
| 748 | if( pBBox==0 ) return; |
| 749 | if( pBBox->isInit==0 ){ |
| 750 | pBBox->isInit = 1; |
| 751 | memcpy(pBBox->a, a, sizeof(RtreeCoord)*4); |
| 752 | }else{ |
| 753 | if( a[0].f < pBBox->a[0].f ) pBBox->a[0] = a[0]; |
| 754 | if( a[1].f > pBBox->a[1].f ) pBBox->a[1] = a[1]; |
| 755 | if( a[2].f < pBBox->a[2].f ) pBBox->a[2] = a[2]; |
| 756 | if( a[3].f > pBBox->a[3].f ) pBBox->a[3] = a[3]; |
| 757 | } |
| 758 | } |
| 759 | } |
| 760 | static void geopolyBBoxFinal( |
| 761 | sqlite3_context *context |
| 762 | ){ |
| 763 | GeoPoly *p; |
| 764 | GeoBBox *pBBox; |
| 765 | pBBox = (GeoBBox*)sqlite3_aggregate_context(context, 0); |
| 766 | if( pBBox==0 ) return; |
| 767 | p = geopolyBBox(context, 0, pBBox->a, 0); |
| 768 | if( p ){ |
| 769 | sqlite3_result_blob(context, p->hdr, |
| 770 | 4+8*p->nVertex, SQLITE_TRANSIENT); |
| 771 | sqlite3_free(p); |
| 772 | } |
| 773 | } |
| 774 | |
| 775 | |
| 776 | /* |
| 777 | ** Determine if point (x0,y0) is beneath line segment (x1,y1)->(x2,y2). |
| 778 | ** Returns: |
| 779 | ** |
| 780 | ** +2 x0,y0 is on the line segment |
| 781 | ** |
| 782 | ** +1 x0,y0 is beneath line segment |
| 783 | ** |
| 784 | ** 0 x0,y0 is not on or beneath the line segment or the line segment |
| 785 | ** is vertical and x0,y0 is not on the line segment |
| 786 | ** |
| 787 | ** The left-most coordinate min(x1,x2) is not considered to be part of |
| 788 | ** the line segment for the purposes of this analysis. |
| 789 | */ |
| 790 | static int pointBeneathLine( |
| 791 | double x0, double y0, |
| 792 | double x1, double y1, |
| 793 | double x2, double y2 |
| 794 | ){ |
| 795 | double y; |
| 796 | if( x0==x1 && y0==y1 ) return 2; |
| 797 | if( x1<x2 ){ |
| 798 | if( x0<=x1 || x0>x2 ) return 0; |
| 799 | }else if( x1>x2 ){ |
| 800 | if( x0<=x2 || x0>x1 ) return 0; |
| 801 | }else{ |
| 802 | /* Vertical line segment */ |
| 803 | if( x0!=x1 ) return 0; |
| 804 | if( y0<y1 && y0<y2 ) return 0; |
| 805 | if( y0>y1 && y0>y2 ) return 0; |
| 806 | return 2; |
| 807 | } |
| 808 | y = y1 + (y2-y1)*(x0-x1)/(x2-x1); |
| 809 | if( y0==y ) return 2; |
| 810 | if( y0<y ) return 1; |
| 811 | return 0; |
| 812 | } |
| 813 | |
| 814 | /* |
| 815 | ** SQL function: geopoly_contains_point(P,X,Y) |
| 816 | ** |
| 817 | ** Return +2 if point X,Y is within polygon P. |
| 818 | ** Return +1 if point X,Y is on the polygon boundary. |
| 819 | ** Return 0 if point X,Y is outside the polygon |
| 820 | */ |
| 821 | static void geopolyContainsPointFunc( |
| 822 | sqlite3_context *context, |
| 823 | int argc, |
| 824 | sqlite3_value **argv |
| 825 | ){ |
| 826 | GeoPoly *p1 = geopolyFuncParam(context, argv[0], 0); |
| 827 | double x0 = sqlite3_value_double(argv[1]); |
| 828 | double y0 = sqlite3_value_double(argv[2]); |
| 829 | int v = 0; |
| 830 | int cnt = 0; |
| 831 | int ii; |
| 832 | (void)argc; |
| 833 | |
| 834 | if( p1==0 ) return; |
| 835 | for(ii=0; ii<p1->nVertex-1; ii++){ |
| 836 | v = pointBeneathLine(x0,y0,GeoX(p1,ii), GeoY(p1,ii), |
| 837 | GeoX(p1,ii+1),GeoY(p1,ii+1)); |
| 838 | if( v==2 ) break; |
| 839 | cnt += v; |
| 840 | } |
| 841 | if( v!=2 ){ |
| 842 | v = pointBeneathLine(x0,y0,GeoX(p1,ii), GeoY(p1,ii), |
| 843 | GeoX(p1,0), GeoY(p1,0)); |
| 844 | } |
| 845 | if( v==2 ){ |
| 846 | sqlite3_result_int(context, 1); |
| 847 | }else if( ((v+cnt)&1)==0 ){ |
| 848 | sqlite3_result_int(context, 0); |
| 849 | }else{ |
| 850 | sqlite3_result_int(context, 2); |
| 851 | } |
| 852 | sqlite3_free(p1); |
| 853 | } |
| 854 | |
| 855 | /* Forward declaration */ |
| 856 | static int geopolyOverlap(GeoPoly *p1, GeoPoly *p2); |
| 857 | |
| 858 | /* |
| 859 | ** SQL function: geopoly_within(P1,P2) |
| 860 | ** |
| 861 | ** Return +2 if P1 and P2 are the same polygon |
| 862 | ** Return +1 if P2 is contained within P1 |
| 863 | ** Return 0 if any part of P2 is on the outside of P1 |
| 864 | ** |
| 865 | */ |
| 866 | static void geopolyWithinFunc( |
| 867 | sqlite3_context *context, |
| 868 | int argc, |
| 869 | sqlite3_value **argv |
| 870 | ){ |
| 871 | GeoPoly *p1 = geopolyFuncParam(context, argv[0], 0); |
| 872 | GeoPoly *p2 = geopolyFuncParam(context, argv[1], 0); |
| 873 | (void)argc; |
| 874 | if( p1 && p2 ){ |
| 875 | int x = geopolyOverlap(p1, p2); |
| 876 | if( x<0 ){ |
| 877 | sqlite3_result_error_nomem(context); |
| 878 | }else{ |
| 879 | sqlite3_result_int(context, x==2 ? 1 : x==4 ? 2 : 0); |
| 880 | } |
| 881 | } |
| 882 | sqlite3_free(p1); |
| 883 | sqlite3_free(p2); |
| 884 | } |
| 885 | |
| 886 | /* Objects used by the overlap algorithm. */ |
| 887 | typedef struct GeoEvent GeoEvent; |
| 888 | typedef struct GeoSegment GeoSegment; |
| 889 | typedef struct GeoOverlap GeoOverlap; |
| 890 | struct GeoEvent { |
| 891 | double x; /* X coordinate at which event occurs */ |
| 892 | int eType; /* 0 for ADD, 1 for REMOVE */ |
| 893 | GeoSegment *pSeg; /* The segment to be added or removed */ |
| 894 | GeoEvent *pNext; /* Next event in the sorted list */ |
| 895 | }; |
| 896 | struct GeoSegment { |
| 897 | double C, B; /* y = C*x + B */ |
| 898 | double y; /* Current y value */ |
| 899 | float y0; /* Initial y value */ |
| 900 | unsigned char side; /* 1 for p1, 2 for p2 */ |
| 901 | unsigned int idx; /* Which segment within the side */ |
| 902 | GeoSegment *pNext; /* Next segment in a list sorted by y */ |
| 903 | }; |
| 904 | struct GeoOverlap { |
| 905 | GeoEvent *aEvent; /* Array of all events */ |
| 906 | GeoSegment *aSegment; /* Array of all segments */ |
| 907 | int nEvent; /* Number of events */ |
| 908 | int nSegment; /* Number of segments */ |
| 909 | }; |
| 910 | |
| 911 | /* |
| 912 | ** Add a single segment and its associated events. |
| 913 | */ |
| 914 | static void geopolyAddOneSegment( |
| 915 | GeoOverlap *p, |
| 916 | GeoCoord x0, |
| 917 | GeoCoord y0, |
| 918 | GeoCoord x1, |
| 919 | GeoCoord y1, |
| 920 | unsigned char side, |
| 921 | unsigned int idx |
| 922 | ){ |
| 923 | GeoSegment *pSeg; |
| 924 | GeoEvent *pEvent; |
| 925 | if( x0==x1 ) return; /* Ignore vertical segments */ |
| 926 | if( x0>x1 ){ |
| 927 | GeoCoord t = x0; |
| 928 | x0 = x1; |
| 929 | x1 = t; |
| 930 | t = y0; |
| 931 | y0 = y1; |
| 932 | y1 = t; |
| 933 | } |
| 934 | pSeg = p->aSegment + p->nSegment; |
| 935 | p->nSegment++; |
| 936 | pSeg->C = (y1-y0)/(x1-x0); |
| 937 | pSeg->B = y1 - x1*pSeg->C; |
| 938 | pSeg->y0 = y0; |
| 939 | pSeg->side = side; |
| 940 | pSeg->idx = idx; |
| 941 | pEvent = p->aEvent + p->nEvent; |
| 942 | p->nEvent++; |
| 943 | pEvent->x = x0; |
| 944 | pEvent->eType = 0; |
| 945 | pEvent->pSeg = pSeg; |
| 946 | pEvent = p->aEvent + p->nEvent; |
| 947 | p->nEvent++; |
| 948 | pEvent->x = x1; |
| 949 | pEvent->eType = 1; |
| 950 | pEvent->pSeg = pSeg; |
| 951 | } |
| 952 | |
| 953 | |
| 954 | |
| 955 | /* |
| 956 | ** Insert all segments and events for polygon pPoly. |
| 957 | */ |
| 958 | static void geopolyAddSegments( |
| 959 | GeoOverlap *p, /* Add segments to this Overlap object */ |
| 960 | GeoPoly *pPoly, /* Take all segments from this polygon */ |
| 961 | unsigned char side /* The side of pPoly */ |
| 962 | ){ |
| 963 | unsigned int i; |
| 964 | GeoCoord *x; |
| 965 | for(i=0; i<(unsigned)pPoly->nVertex-1; i++){ |
| 966 | x = &GeoX(pPoly,i); |
| 967 | geopolyAddOneSegment(p, x[0], x[1], x[2], x[3], side, i); |
| 968 | } |
| 969 | x = &GeoX(pPoly,i); |
| 970 | geopolyAddOneSegment(p, x[0], x[1], pPoly->a[0], pPoly->a[1], side, i); |
| 971 | } |
| 972 | |
| 973 | /* |
| 974 | ** Merge two lists of sorted events by X coordinate |
| 975 | */ |
| 976 | static GeoEvent *geopolyEventMerge(GeoEvent *pLeft, GeoEvent *pRight){ |
| 977 | GeoEvent head, *pLast; |
| 978 | head.pNext = 0; |
| 979 | pLast = &head; |
| 980 | while( pRight && pLeft ){ |
| 981 | if( pRight->x <= pLeft->x ){ |
| 982 | pLast->pNext = pRight; |
| 983 | pLast = pRight; |
| 984 | pRight = pRight->pNext; |
| 985 | }else{ |
| 986 | pLast->pNext = pLeft; |
| 987 | pLast = pLeft; |
| 988 | pLeft = pLeft->pNext; |
| 989 | } |
| 990 | } |
| 991 | pLast->pNext = pRight ? pRight : pLeft; |
| 992 | return head.pNext; |
| 993 | } |
| 994 | |
| 995 | /* |
| 996 | ** Sort an array of nEvent event objects into a list. |
| 997 | */ |
| 998 | static GeoEvent *geopolySortEventsByX(GeoEvent *aEvent, int nEvent){ |
| 999 | int mx = 0; |
| 1000 | int i, j; |
| 1001 | GeoEvent *p; |
| 1002 | GeoEvent *a[50]; |
| 1003 | for(i=0; i<nEvent; i++){ |
| 1004 | p = &aEvent[i]; |
| 1005 | p->pNext = 0; |
| 1006 | for(j=0; j<mx && a[j]; j++){ |
| 1007 | p = geopolyEventMerge(a[j], p); |
| 1008 | a[j] = 0; |
| 1009 | } |
| 1010 | a[j] = p; |
| 1011 | if( j>=mx ) mx = j+1; |
| 1012 | } |
| 1013 | p = 0; |
| 1014 | for(i=0; i<mx; i++){ |
| 1015 | p = geopolyEventMerge(a[i], p); |
| 1016 | } |
| 1017 | return p; |
| 1018 | } |
| 1019 | |
| 1020 | /* |
| 1021 | ** Merge two lists of sorted segments by Y, and then by C. |
| 1022 | */ |
| 1023 | static GeoSegment *geopolySegmentMerge(GeoSegment *pLeft, GeoSegment *pRight){ |
| 1024 | GeoSegment head, *pLast; |
| 1025 | head.pNext = 0; |
| 1026 | pLast = &head; |
| 1027 | while( pRight && pLeft ){ |
| 1028 | double r = pRight->y - pLeft->y; |
| 1029 | if( r==0.0 ) r = pRight->C - pLeft->C; |
| 1030 | if( r<0.0 ){ |
| 1031 | pLast->pNext = pRight; |
| 1032 | pLast = pRight; |
| 1033 | pRight = pRight->pNext; |
| 1034 | }else{ |
| 1035 | pLast->pNext = pLeft; |
| 1036 | pLast = pLeft; |
| 1037 | pLeft = pLeft->pNext; |
| 1038 | } |
| 1039 | } |
| 1040 | pLast->pNext = pRight ? pRight : pLeft; |
| 1041 | return head.pNext; |
| 1042 | } |
| 1043 | |
| 1044 | /* |
| 1045 | ** Sort a list of GeoSegments in order of increasing Y and in the event of |
| 1046 | ** a tie, increasing C (slope). |
| 1047 | */ |
| 1048 | static GeoSegment *geopolySortSegmentsByYAndC(GeoSegment *pList){ |
| 1049 | int mx = 0; |
| 1050 | int i; |
| 1051 | GeoSegment *p; |
| 1052 | GeoSegment *a[50]; |
| 1053 | while( pList ){ |
| 1054 | p = pList; |
| 1055 | pList = pList->pNext; |
| 1056 | p->pNext = 0; |
| 1057 | for(i=0; i<mx && a[i]; i++){ |
| 1058 | p = geopolySegmentMerge(a[i], p); |
| 1059 | a[i] = 0; |
| 1060 | } |
| 1061 | a[i] = p; |
| 1062 | if( i>=mx ) mx = i+1; |
| 1063 | } |
| 1064 | p = 0; |
| 1065 | for(i=0; i<mx; i++){ |
| 1066 | p = geopolySegmentMerge(a[i], p); |
| 1067 | } |
| 1068 | return p; |
| 1069 | } |
| 1070 | |
| 1071 | /* |
| 1072 | ** Determine the overlap between two polygons |
| 1073 | */ |
| 1074 | static int geopolyOverlap(GeoPoly *p1, GeoPoly *p2){ |
| 1075 | sqlite3_int64 nVertex = p1->nVertex + p2->nVertex + 2; |
| 1076 | GeoOverlap *p; |
| 1077 | sqlite3_int64 nByte; |
| 1078 | GeoEvent *pThisEvent; |
| 1079 | double rX; |
| 1080 | int rc = 0; |
| 1081 | int needSort = 0; |
| 1082 | GeoSegment *pActive = 0; |
| 1083 | GeoSegment *pSeg; |
| 1084 | unsigned char aOverlap[4]; |
| 1085 | |
| 1086 | nByte = sizeof(GeoEvent)*nVertex*2 |
| 1087 | + sizeof(GeoSegment)*nVertex |
| 1088 | + sizeof(GeoOverlap); |
| 1089 | p = sqlite3_malloc64( nByte ); |
| 1090 | if( p==0 ) return -1; |
| 1091 | p->aEvent = (GeoEvent*)&p[1]; |
| 1092 | p->aSegment = (GeoSegment*)&p->aEvent[nVertex*2]; |
| 1093 | p->nEvent = p->nSegment = 0; |
| 1094 | geopolyAddSegments(p, p1, 1); |
| 1095 | geopolyAddSegments(p, p2, 2); |
| 1096 | pThisEvent = geopolySortEventsByX(p->aEvent, p->nEvent); |
| 1097 | rX = pThisEvent && pThisEvent->x==0.0 ? -1.0 : 0.0; |
| 1098 | memset(aOverlap, 0, sizeof(aOverlap)); |
| 1099 | while( pThisEvent ){ |
| 1100 | if( pThisEvent->x!=rX ){ |
| 1101 | GeoSegment *pPrev = 0; |
| 1102 | int iMask = 0; |
| 1103 | GEODEBUG(("Distinct X: %g\n", pThisEvent->x)); |
| 1104 | rX = pThisEvent->x; |
| 1105 | if( needSort ){ |
| 1106 | GEODEBUG(("SORT\n")); |
| 1107 | pActive = geopolySortSegmentsByYAndC(pActive); |
| 1108 | needSort = 0; |
| 1109 | } |
| 1110 | for(pSeg=pActive; pSeg; pSeg=pSeg->pNext){ |
| 1111 | if( pPrev ){ |
| 1112 | if( pPrev->y!=pSeg->y ){ |
| 1113 | GEODEBUG(("MASK: %d\n", iMask)); |
| 1114 | aOverlap[iMask] = 1; |
| 1115 | } |
| 1116 | } |
| 1117 | iMask ^= pSeg->side; |
| 1118 | pPrev = pSeg; |
| 1119 | } |
| 1120 | pPrev = 0; |
| 1121 | for(pSeg=pActive; pSeg; pSeg=pSeg->pNext){ |
| 1122 | double y = pSeg->C*rX + pSeg->B; |
| 1123 | GEODEBUG(("Segment %d.%d %g->%g\n", pSeg->side, pSeg->idx, pSeg->y, y)); |
| 1124 | pSeg->y = y; |
| 1125 | if( pPrev ){ |
| 1126 | if( pPrev->y>pSeg->y && pPrev->side!=pSeg->side ){ |
| 1127 | rc = 1; |
| 1128 | GEODEBUG(("Crossing: %d.%d and %d.%d\n", |
| 1129 | pPrev->side, pPrev->idx, |
| 1130 | pSeg->side, pSeg->idx)); |
| 1131 | goto geopolyOverlapDone; |
| 1132 | }else if( pPrev->y!=pSeg->y ){ |
| 1133 | GEODEBUG(("MASK: %d\n", iMask)); |
| 1134 | aOverlap[iMask] = 1; |
| 1135 | } |
| 1136 | } |
| 1137 | iMask ^= pSeg->side; |
| 1138 | pPrev = pSeg; |
| 1139 | } |
| 1140 | } |
| 1141 | GEODEBUG(("%s %d.%d C=%g B=%g\n", |
| 1142 | pThisEvent->eType ? "RM " : "ADD", |
| 1143 | pThisEvent->pSeg->side, pThisEvent->pSeg->idx, |
| 1144 | pThisEvent->pSeg->C, |
| 1145 | pThisEvent->pSeg->B)); |
| 1146 | if( pThisEvent->eType==0 ){ |
| 1147 | /* Add a segment */ |
| 1148 | pSeg = pThisEvent->pSeg; |
| 1149 | pSeg->y = pSeg->y0; |
| 1150 | pSeg->pNext = pActive; |
| 1151 | pActive = pSeg; |
| 1152 | needSort = 1; |
| 1153 | }else{ |
| 1154 | /* Remove a segment */ |
| 1155 | if( pActive==pThisEvent->pSeg ){ |
| 1156 | pActive = ALWAYS(pActive) ? pActive->pNext : 0; |
| 1157 | }else{ |
| 1158 | for(pSeg=pActive; pSeg; pSeg=pSeg->pNext){ |
| 1159 | if( pSeg->pNext==pThisEvent->pSeg ){ |
| 1160 | pSeg->pNext = ALWAYS(pSeg->pNext) ? pSeg->pNext->pNext : 0; |
| 1161 | break; |
| 1162 | } |
| 1163 | } |
| 1164 | } |
| 1165 | } |
| 1166 | pThisEvent = pThisEvent->pNext; |
| 1167 | } |
| 1168 | if( aOverlap[3]==0 ){ |
| 1169 | rc = 0; |
| 1170 | }else if( aOverlap[1]!=0 && aOverlap[2]==0 ){ |
| 1171 | rc = 3; |
| 1172 | }else if( aOverlap[1]==0 && aOverlap[2]!=0 ){ |
| 1173 | rc = 2; |
| 1174 | }else if( aOverlap[1]==0 && aOverlap[2]==0 ){ |
| 1175 | rc = 4; |
| 1176 | }else{ |
| 1177 | rc = 1; |
| 1178 | } |
| 1179 | |
| 1180 | geopolyOverlapDone: |
| 1181 | sqlite3_free(p); |
| 1182 | return rc; |
| 1183 | } |
| 1184 | |
| 1185 | /* |
| 1186 | ** SQL function: geopoly_overlap(P1,P2) |
| 1187 | ** |
| 1188 | ** Determine whether or not P1 and P2 overlap. Return value: |
| 1189 | ** |
| 1190 | ** 0 The two polygons are disjoint |
| 1191 | ** 1 They overlap |
| 1192 | ** 2 P1 is completely contained within P2 |
| 1193 | ** 3 P2 is completely contained within P1 |
| 1194 | ** 4 P1 and P2 are the same polygon |
| 1195 | ** NULL Either P1 or P2 or both are not valid polygons |
| 1196 | */ |
| 1197 | static void geopolyOverlapFunc( |
| 1198 | sqlite3_context *context, |
| 1199 | int argc, |
| 1200 | sqlite3_value **argv |
| 1201 | ){ |
| 1202 | GeoPoly *p1 = geopolyFuncParam(context, argv[0], 0); |
| 1203 | GeoPoly *p2 = geopolyFuncParam(context, argv[1], 0); |
| 1204 | (void)argc; |
| 1205 | if( p1 && p2 ){ |
| 1206 | int x = geopolyOverlap(p1, p2); |
| 1207 | if( x<0 ){ |
| 1208 | sqlite3_result_error_nomem(context); |
| 1209 | }else{ |
| 1210 | sqlite3_result_int(context, x); |
| 1211 | } |
| 1212 | } |
| 1213 | sqlite3_free(p1); |
| 1214 | sqlite3_free(p2); |
| 1215 | } |
| 1216 | |
| 1217 | /* |
| 1218 | ** Enable or disable debugging output |
| 1219 | */ |
| 1220 | static void geopolyDebugFunc( |
| 1221 | sqlite3_context *context, |
| 1222 | int argc, |
| 1223 | sqlite3_value **argv |
| 1224 | ){ |
| 1225 | (void)context; |
| 1226 | (void)argc; |
| 1227 | #ifdef GEOPOLY_ENABLE_DEBUG |
| 1228 | geo_debug = sqlite3_value_int(argv[0]); |
| 1229 | #else |
| 1230 | (void)argv; |
| 1231 | #endif |
| 1232 | } |
| 1233 | |
| 1234 | /* |
| 1235 | ** This function is the implementation of both the xConnect and xCreate |
| 1236 | ** methods of the geopoly virtual table. |
| 1237 | ** |
| 1238 | ** argv[0] -> module name |
| 1239 | ** argv[1] -> database name |
| 1240 | ** argv[2] -> table name |
| 1241 | ** argv[...] -> column names... |
| 1242 | */ |
| 1243 | static int geopolyInit( |
| 1244 | sqlite3 *db, /* Database connection */ |
| 1245 | void *pAux, /* One of the RTREE_COORD_* constants */ |
| 1246 | int argc, const char *const*argv, /* Parameters to CREATE TABLE statement */ |
| 1247 | sqlite3_vtab **ppVtab, /* OUT: New virtual table */ |
| 1248 | char **pzErr, /* OUT: Error message, if any */ |
| 1249 | int isCreate /* True for xCreate, false for xConnect */ |
| 1250 | ){ |
| 1251 | int rc = SQLITE_OK; |
| 1252 | Rtree *pRtree; |
| 1253 | sqlite3_int64 nDb; /* Length of string argv[1] */ |
| 1254 | sqlite3_int64 nName; /* Length of string argv[2] */ |
| 1255 | sqlite3_str *pSql; |
| 1256 | char *zSql; |
| 1257 | int ii; |
| 1258 | (void)pAux; |
| 1259 | |
| 1260 | if( argc>=RTREE_MAX_AUX_COLUMN+4 ){ |
| 1261 | *pzErr = sqlite3_mprintf("Too many columns for a geopoly table"); |
| 1262 | return SQLITE_ERROR; |
| 1263 | } |
| 1264 | |
| 1265 | sqlite3_vtab_config(db, SQLITE_VTAB_CONSTRAINT_SUPPORT, 1); |
| 1266 | sqlite3_vtab_config(db, SQLITE_VTAB_INNOCUOUS); |
| 1267 | |
| 1268 | /* Allocate the sqlite3_vtab structure */ |
| 1269 | nDb = strlen(argv[1]); |
| 1270 | nName = strlen(argv[2]); |
| 1271 | pRtree = (Rtree *)sqlite3_malloc64(sizeof(Rtree)+nDb+nName*2+8); |
| 1272 | if( !pRtree ){ |
| 1273 | return SQLITE_NOMEM; |
| 1274 | } |
| 1275 | memset(pRtree, 0, sizeof(Rtree)+nDb+nName*2+8); |
| 1276 | pRtree->nBusy = 1; |
| 1277 | pRtree->base.pModule = &rtreeModule; |
| 1278 | pRtree->zDb = (char *)&pRtree[1]; |
| 1279 | pRtree->zName = &pRtree->zDb[nDb+1]; |
| 1280 | pRtree->zNodeName = &pRtree->zName[nName+1]; |
| 1281 | pRtree->eCoordType = RTREE_COORD_REAL32; |
| 1282 | pRtree->nDim = 2; |
| 1283 | pRtree->nDim2 = 4; |
| 1284 | memcpy(pRtree->zDb, argv[1], nDb); |
| 1285 | memcpy(pRtree->zName, argv[2], nName); |
| 1286 | memcpy(pRtree->zNodeName, argv[2], nName); |
| 1287 | memcpy(&pRtree->zNodeName[nName], "_node", 6); |
| 1288 | |
| 1289 | |
| 1290 | /* Create/Connect to the underlying relational database schema. If |
| 1291 | ** that is successful, call sqlite3_declare_vtab() to configure |
| 1292 | ** the r-tree table schema. |
| 1293 | */ |
| 1294 | pSql = sqlite3_str_new(db); |
| 1295 | sqlite3_str_appendf(pSql, "CREATE TABLE x(_shape"); |
| 1296 | pRtree->nAux = 1; /* Add one for _shape */ |
| 1297 | pRtree->nAuxNotNull = 1; /* The _shape column is always not-null */ |
| 1298 | for(ii=3; ii<argc; ii++){ |
| 1299 | pRtree->nAux++; |
| 1300 | sqlite3_str_appendf(pSql, ",%s", argv[ii]); |
| 1301 | } |
| 1302 | sqlite3_str_appendf(pSql, ");"); |
| 1303 | zSql = sqlite3_str_finish(pSql); |
| 1304 | if( !zSql ){ |
| 1305 | rc = SQLITE_NOMEM; |
| 1306 | }else if( SQLITE_OK!=(rc = sqlite3_declare_vtab(db, zSql)) ){ |
| 1307 | *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db)); |
| 1308 | } |
| 1309 | sqlite3_free(zSql); |
| 1310 | if( rc ) goto geopolyInit_fail; |
| 1311 | pRtree->nBytesPerCell = 8 + pRtree->nDim2*4; |
| 1312 | |
| 1313 | /* Figure out the node size to use. */ |
| 1314 | rc = getNodeSize(db, pRtree, isCreate, pzErr); |
| 1315 | if( rc ) goto geopolyInit_fail; |
| 1316 | rc = rtreeSqlInit(pRtree, db, argv[1], argv[2], isCreate); |
| 1317 | if( rc ){ |
| 1318 | *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db)); |
| 1319 | goto geopolyInit_fail; |
| 1320 | } |
| 1321 | |
| 1322 | *ppVtab = (sqlite3_vtab *)pRtree; |
| 1323 | return SQLITE_OK; |
| 1324 | |
| 1325 | geopolyInit_fail: |
| 1326 | if( rc==SQLITE_OK ) rc = SQLITE_ERROR; |
| 1327 | assert( *ppVtab==0 ); |
| 1328 | assert( pRtree->nBusy==1 ); |
| 1329 | rtreeRelease(pRtree); |
| 1330 | return rc; |
| 1331 | } |
| 1332 | |
| 1333 | |
| 1334 | /* |
| 1335 | ** GEOPOLY virtual table module xCreate method. |
| 1336 | */ |
| 1337 | static int geopolyCreate( |
| 1338 | sqlite3 *db, |
| 1339 | void *pAux, |
| 1340 | int argc, const char *const*argv, |
| 1341 | sqlite3_vtab **ppVtab, |
| 1342 | char **pzErr |
| 1343 | ){ |
| 1344 | return geopolyInit(db, pAux, argc, argv, ppVtab, pzErr, 1); |
| 1345 | } |
| 1346 | |
| 1347 | /* |
| 1348 | ** GEOPOLY virtual table module xConnect method. |
| 1349 | */ |
| 1350 | static int geopolyConnect( |
| 1351 | sqlite3 *db, |
| 1352 | void *pAux, |
| 1353 | int argc, const char *const*argv, |
| 1354 | sqlite3_vtab **ppVtab, |
| 1355 | char **pzErr |
| 1356 | ){ |
| 1357 | return geopolyInit(db, pAux, argc, argv, ppVtab, pzErr, 0); |
| 1358 | } |
| 1359 | |
| 1360 | |
| 1361 | /* |
| 1362 | ** GEOPOLY virtual table module xFilter method. |
| 1363 | ** |
| 1364 | ** Query plans: |
| 1365 | ** |
| 1366 | ** 1 rowid lookup |
| 1367 | ** 2 search for objects overlapping the same bounding box |
| 1368 | ** that contains polygon argv[0] |
| 1369 | ** 3 search for objects overlapping the same bounding box |
| 1370 | ** that contains polygon argv[0] |
| 1371 | ** 4 full table scan |
| 1372 | */ |
| 1373 | static int geopolyFilter( |
| 1374 | sqlite3_vtab_cursor *pVtabCursor, /* The cursor to initialize */ |
| 1375 | int idxNum, /* Query plan */ |
| 1376 | const char *idxStr, /* Not Used */ |
| 1377 | int argc, sqlite3_value **argv /* Parameters to the query plan */ |
| 1378 | ){ |
| 1379 | Rtree *pRtree = (Rtree *)pVtabCursor->pVtab; |
| 1380 | RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor; |
| 1381 | RtreeNode *pRoot = 0; |
| 1382 | int rc = SQLITE_OK; |
| 1383 | int iCell = 0; |
| 1384 | (void)idxStr; |
| 1385 | |
| 1386 | rtreeReference(pRtree); |
| 1387 | |
| 1388 | /* Reset the cursor to the same state as rtreeOpen() leaves it in. */ |
| 1389 | resetCursor(pCsr); |
| 1390 | |
| 1391 | pCsr->iStrategy = idxNum; |
| 1392 | if( idxNum==1 ){ |
| 1393 | /* Special case - lookup by rowid. */ |
| 1394 | RtreeNode *pLeaf; /* Leaf on which the required cell resides */ |
| 1395 | RtreeSearchPoint *p; /* Search point for the leaf */ |
| 1396 | i64 iRowid; |
| 1397 | i64 iNode = 0; |
| 1398 | if( rtreeRowidEqValue(argv[0], &iRowid) ){ |
| 1399 | rc = findLeafNode(pRtree, iRowid, &pLeaf, &iNode); |
| 1400 | }else{ |
| 1401 | pLeaf = 0; |
| 1402 | } |
| 1403 | if( rc==SQLITE_OK && pLeaf!=0 ){ |
| 1404 | p = rtreeSearchPointNew(pCsr, RTREE_ZERO, 0); |
| 1405 | assert( p!=0 ); /* Always returns pCsr->sPoint */ |
| 1406 | pCsr->aNode[0] = pLeaf; |
| 1407 | p->id = iNode; |
| 1408 | p->eWithin = PARTLY_WITHIN; |
| 1409 | rc = nodeRowidIndex(pRtree, pLeaf, iRowid, &iCell); |
| 1410 | p->iCell = (u8)iCell; |
| 1411 | RTREE_QUEUE_TRACE(pCsr, "PUSH-F1:"); |
| 1412 | }else{ |
| 1413 | pCsr->atEOF = 1; |
| 1414 | } |
| 1415 | }else{ |
| 1416 | /* Normal case - r-tree scan. Set up the RtreeCursor.aConstraint array |
| 1417 | ** with the configured constraints. |
| 1418 | */ |
| 1419 | rc = nodeAcquire(pRtree, 1, 0, &pRoot); |
| 1420 | if( rc==SQLITE_OK && idxNum<=3 ){ |
| 1421 | RtreeCoord bbox[4]; |
| 1422 | RtreeConstraint *p; |
| 1423 | assert( argc==1 ); |
| 1424 | assert( argv[0]!=0 ); |
| 1425 | geopolyBBox(0, argv[0], bbox, &rc); |
| 1426 | if( rc ){ |
| 1427 | goto geopoly_filter_end; |
| 1428 | } |
| 1429 | pCsr->aConstraint = p = sqlite3_malloc(sizeof(RtreeConstraint)*4); |
| 1430 | pCsr->nConstraint = 4; |
| 1431 | if( p==0 ){ |
| 1432 | rc = SQLITE_NOMEM; |
| 1433 | }else{ |
| 1434 | memset(pCsr->aConstraint, 0, sizeof(RtreeConstraint)*4); |
| 1435 | memset(pCsr->anQueue, 0, sizeof(u32)*(pRtree->iDepth + 1)); |
| 1436 | if( idxNum==2 ){ |
| 1437 | /* Overlap query */ |
| 1438 | p->op = 'B'; |
| 1439 | p->iCoord = 0; |
| 1440 | p->u.rValue = bbox[1].f; |
| 1441 | p++; |
| 1442 | p->op = 'D'; |
| 1443 | p->iCoord = 1; |
| 1444 | p->u.rValue = bbox[0].f; |
| 1445 | p++; |
| 1446 | p->op = 'B'; |
| 1447 | p->iCoord = 2; |
| 1448 | p->u.rValue = bbox[3].f; |
| 1449 | p++; |
| 1450 | p->op = 'D'; |
| 1451 | p->iCoord = 3; |
| 1452 | p->u.rValue = bbox[2].f; |
| 1453 | }else{ |
| 1454 | /* Within query */ |
| 1455 | p->op = 'D'; |
| 1456 | p->iCoord = 0; |
| 1457 | p->u.rValue = bbox[0].f; |
| 1458 | p++; |
| 1459 | p->op = 'B'; |
| 1460 | p->iCoord = 1; |
| 1461 | p->u.rValue = bbox[1].f; |
| 1462 | p++; |
| 1463 | p->op = 'D'; |
| 1464 | p->iCoord = 2; |
| 1465 | p->u.rValue = bbox[2].f; |
| 1466 | p++; |
| 1467 | p->op = 'B'; |
| 1468 | p->iCoord = 3; |
| 1469 | p->u.rValue = bbox[3].f; |
| 1470 | } |
| 1471 | } |
| 1472 | } |
| 1473 | if( rc==SQLITE_OK ){ |
| 1474 | RtreeSearchPoint *pNew; |
| 1475 | pNew = rtreeSearchPointNew(pCsr, RTREE_ZERO, (u8)(pRtree->iDepth+1)); |
| 1476 | if( pNew==0 ){ |
| 1477 | rc = SQLITE_NOMEM; |
| 1478 | goto geopoly_filter_end; |
| 1479 | } |
| 1480 | pNew->id = 1; |
| 1481 | pNew->iCell = 0; |
| 1482 | pNew->eWithin = PARTLY_WITHIN; |
| 1483 | assert( pCsr->bPoint==1 ); |
| 1484 | pCsr->aNode[0] = pRoot; |
| 1485 | pRoot = 0; |
| 1486 | RTREE_QUEUE_TRACE(pCsr, "PUSH-Fm:"); |
| 1487 | rc = rtreeStepToLeaf(pCsr); |
| 1488 | } |
| 1489 | } |
| 1490 | |
| 1491 | geopoly_filter_end: |
| 1492 | nodeRelease(pRtree, pRoot); |
| 1493 | rtreeRelease(pRtree); |
| 1494 | return rc; |
| 1495 | } |
| 1496 | |
| 1497 | /* |
| 1498 | ** Rtree virtual table module xBestIndex method. There are three |
| 1499 | ** table scan strategies to choose from (in order from most to |
| 1500 | ** least desirable): |
| 1501 | ** |
| 1502 | ** idxNum idxStr Strategy |
| 1503 | ** ------------------------------------------------ |
| 1504 | ** 1 "rowid" Direct lookup by rowid. |
| 1505 | ** 2 "rtree" R-tree overlap query using geopoly_overlap() |
| 1506 | ** 3 "rtree" R-tree within query using geopoly_within() |
| 1507 | ** 4 "fullscan" full-table scan. |
| 1508 | ** ------------------------------------------------ |
| 1509 | */ |
| 1510 | static int geopolyBestIndex(sqlite3_vtab *tab, sqlite3_index_info *pIdxInfo){ |
| 1511 | int ii; |
| 1512 | int iRowidTerm = -1; |
| 1513 | int iFuncTerm = -1; |
| 1514 | int idxNum = 0; |
| 1515 | (void)tab; |
| 1516 | |
| 1517 | for(ii=0; ii<pIdxInfo->nConstraint; ii++){ |
| 1518 | struct sqlite3_index_constraint *p = &pIdxInfo->aConstraint[ii]; |
| 1519 | if( !p->usable ) continue; |
| 1520 | if( p->iColumn<0 && p->op==SQLITE_INDEX_CONSTRAINT_EQ ){ |
| 1521 | iRowidTerm = ii; |
| 1522 | break; |
| 1523 | } |
| 1524 | if( p->iColumn==0 && p->op>=SQLITE_INDEX_CONSTRAINT_FUNCTION ){ |
| 1525 | /* p->op==SQLITE_INDEX_CONSTRAINT_FUNCTION for geopoly_overlap() |
| 1526 | ** p->op==(SQLITE_INDEX_CONTRAINT_FUNCTION+1) for geopoly_within(). |
| 1527 | ** See geopolyFindFunction() */ |
| 1528 | iFuncTerm = ii; |
| 1529 | idxNum = p->op - SQLITE_INDEX_CONSTRAINT_FUNCTION + 2; |
| 1530 | } |
| 1531 | } |
| 1532 | |
| 1533 | if( iRowidTerm>=0 ){ |
| 1534 | pIdxInfo->idxNum = 1; |
| 1535 | pIdxInfo->idxStr = "rowid"; |
| 1536 | pIdxInfo->aConstraintUsage[iRowidTerm].argvIndex = 1; |
| 1537 | pIdxInfo->aConstraintUsage[iRowidTerm].omit = 1; |
| 1538 | pIdxInfo->estimatedCost = 30.0; |
| 1539 | pIdxInfo->estimatedRows = 1; |
| 1540 | pIdxInfo->idxFlags = SQLITE_INDEX_SCAN_UNIQUE; |
| 1541 | return SQLITE_OK; |
| 1542 | } |
| 1543 | if( iFuncTerm>=0 ){ |
| 1544 | pIdxInfo->idxNum = idxNum; |
| 1545 | pIdxInfo->idxStr = "rtree"; |
| 1546 | pIdxInfo->aConstraintUsage[iFuncTerm].argvIndex = 1; |
| 1547 | pIdxInfo->aConstraintUsage[iFuncTerm].omit = 0; |
| 1548 | pIdxInfo->estimatedCost = 300.0; |
| 1549 | pIdxInfo->estimatedRows = 10; |
| 1550 | return SQLITE_OK; |
| 1551 | } |
| 1552 | pIdxInfo->idxNum = 4; |
| 1553 | pIdxInfo->idxStr = "fullscan"; |
| 1554 | pIdxInfo->estimatedCost = 3000000.0; |
| 1555 | pIdxInfo->estimatedRows = 100000; |
| 1556 | return SQLITE_OK; |
| 1557 | } |
| 1558 | |
| 1559 | |
| 1560 | /* |
| 1561 | ** GEOPOLY virtual table module xColumn method. |
| 1562 | */ |
| 1563 | static int geopolyColumn(sqlite3_vtab_cursor *cur, sqlite3_context *ctx, int i){ |
| 1564 | Rtree *pRtree = (Rtree *)cur->pVtab; |
| 1565 | RtreeCursor *pCsr = (RtreeCursor *)cur; |
| 1566 | RtreeSearchPoint *p = rtreeSearchPointFirst(pCsr); |
| 1567 | int rc = SQLITE_OK; |
| 1568 | RtreeNode *pNode = rtreeNodeOfFirstSearchPoint(pCsr, &rc); |
| 1569 | |
| 1570 | if( rc ) return rc; |
| 1571 | if( p==0 ) return SQLITE_OK; |
| 1572 | if( i==0 && sqlite3_vtab_nochange(ctx) ) return SQLITE_OK; |
| 1573 | if( i<=pRtree->nAux ){ |
| 1574 | if( !pCsr->bAuxValid ){ |
| 1575 | if( pCsr->pReadAux==0 ){ |
| 1576 | rc = sqlite3_prepare_v3(pRtree->db, pRtree->zReadAuxSql, -1, 0, |
| 1577 | &pCsr->pReadAux, 0); |
| 1578 | if( rc ) return rc; |
| 1579 | } |
| 1580 | sqlite3_bind_int64(pCsr->pReadAux, 1, |
| 1581 | nodeGetRowid(pRtree, pNode, p->iCell)); |
| 1582 | rc = sqlite3_step(pCsr->pReadAux); |
| 1583 | if( rc==SQLITE_ROW ){ |
| 1584 | pCsr->bAuxValid = 1; |
| 1585 | }else{ |
| 1586 | sqlite3_reset(pCsr->pReadAux); |
| 1587 | if( rc==SQLITE_DONE ) rc = SQLITE_OK; |
| 1588 | return rc; |
| 1589 | } |
| 1590 | } |
| 1591 | sqlite3_result_value(ctx, sqlite3_column_value(pCsr->pReadAux, i+2)); |
| 1592 | } |
| 1593 | return SQLITE_OK; |
| 1594 | } |
| 1595 | |
| 1596 | |
| 1597 | /* |
| 1598 | ** The xUpdate method for GEOPOLY module virtual tables. |
| 1599 | ** |
| 1600 | ** For DELETE: |
| 1601 | ** |
| 1602 | ** argv[0] = the rowid to be deleted |
| 1603 | ** |
| 1604 | ** For INSERT: |
| 1605 | ** |
| 1606 | ** argv[0] = SQL NULL |
| 1607 | ** argv[1] = rowid to insert, or an SQL NULL to select automatically |
| 1608 | ** argv[2] = _shape column |
| 1609 | ** argv[3] = first application-defined column.... |
| 1610 | ** |
| 1611 | ** For UPDATE: |
| 1612 | ** |
| 1613 | ** argv[0] = rowid to modify. Never NULL |
| 1614 | ** argv[1] = rowid after the change. Never NULL |
| 1615 | ** argv[2] = new value for _shape |
| 1616 | ** argv[3] = new value for first application-defined column.... |
| 1617 | */ |
| 1618 | static int geopolyUpdate( |
| 1619 | sqlite3_vtab *pVtab, |
| 1620 | int nData, |
| 1621 | sqlite3_value **aData, |
| 1622 | sqlite_int64 *pRowid |
| 1623 | ){ |
| 1624 | Rtree *pRtree = (Rtree *)pVtab; |
| 1625 | int rc = SQLITE_OK; |
| 1626 | RtreeCell cell; /* New cell to insert if nData>1 */ |
| 1627 | i64 oldRowid; /* The old rowid */ |
| 1628 | int oldRowidValid; /* True if oldRowid is valid */ |
| 1629 | i64 newRowid; /* The new rowid */ |
| 1630 | int newRowidValid; /* True if newRowid is valid */ |
| 1631 | int coordChange = 0; /* Change in coordinates */ |
| 1632 | sqlite3_value *pShape = 0; /* New _shape value */ |
| 1633 | sqlite3_value *pOldShape = 0; /* Copy of the unchanged _shape */ |
| 1634 | |
| 1635 | if( pRtree->nNodeRef ){ |
| 1636 | /* Unable to write to the btree while another cursor is reading from it, |
| 1637 | ** since the write might do a rebalance which would disrupt the read |
| 1638 | ** cursor. */ |
| 1639 | return SQLITE_LOCKED_VTAB; |
| 1640 | } |
| 1641 | rtreeReference(pRtree); |
| 1642 | assert(nData>=1); |
| 1643 | |
| 1644 | oldRowidValid = sqlite3_value_type(aData[0])!=SQLITE_NULL;; |
| 1645 | oldRowid = oldRowidValid ? sqlite3_value_int64(aData[0]) : 0; |
| 1646 | newRowidValid = nData>1 && sqlite3_value_type(aData[1])!=SQLITE_NULL; |
| 1647 | newRowid = newRowidValid ? sqlite3_value_int64(aData[1]) : 0; |
| 1648 | cell.iRowid = newRowid; |
| 1649 | |
| 1650 | if( nData>1 ){ |
| 1651 | pShape = aData[2]; |
| 1652 | if( oldRowidValid && oldRowid!=newRowid && sqlite3_value_nochange(pShape) ){ |
| 1653 | /* The rowid changes but _shape does not. aData[2] holds no value in |
| 1654 | ** this case, so read the current _shape from the %_rowid table. It |
| 1655 | ** is needed for the bounding box of the new r-tree entry and for the |
| 1656 | ** %_rowid record of the new rowid. */ |
| 1657 | sqlite3_stmt *pRead = 0; |
| 1658 | rc = sqlite3_prepare_v3(pRtree->db, pRtree->zReadAuxSql, -1, 0, |
| 1659 | &pRead, 0); |
| 1660 | if( rc==SQLITE_OK ){ |
| 1661 | int rc2; |
| 1662 | sqlite3_bind_int64(pRead, 1, oldRowid); |
| 1663 | if( sqlite3_step(pRead)==SQLITE_ROW ){ |
| 1664 | pOldShape = sqlite3_value_dup(sqlite3_column_value(pRead, 2)); |
| 1665 | if( pOldShape==0 ) rc = SQLITE_NOMEM; |
| 1666 | pShape = pOldShape; |
| 1667 | } |
| 1668 | rc2 = sqlite3_finalize(pRead); |
| 1669 | if( rc==SQLITE_OK ) rc = rc2; |
| 1670 | } |
| 1671 | if( rc ) goto geopoly_update_end; |
| 1672 | } |
| 1673 | } |
| 1674 | |
| 1675 | if( nData>1 /* not a DELETE */ |
| 1676 | && (!oldRowidValid /* INSERT */ |
| 1677 | || !sqlite3_value_nochange(pShape) /* UPDATE _shape */ |
| 1678 | || oldRowid!=newRowid) /* Rowid change */ |
| 1679 | ){ |
| 1680 | assert( pShape!=0 ); |
| 1681 | geopolyBBox(0, pShape, cell.aCoord, &rc); |
| 1682 | if( rc ){ |
| 1683 | if( rc==SQLITE_ERROR ){ |
| 1684 | pVtab->zErrMsg = |
| 1685 | sqlite3_mprintf("_shape does not contain a valid polygon"); |
| 1686 | } |
| 1687 | goto geopoly_update_end; |
| 1688 | } |
| 1689 | coordChange = 1; |
| 1690 | |
| 1691 | /* If a rowid value was supplied, check if it is already present in |
| 1692 | ** the table. If so, the constraint has failed. */ |
| 1693 | if( newRowidValid && (!oldRowidValid || oldRowid!=newRowid) ){ |
| 1694 | int steprc; |
| 1695 | sqlite3_bind_int64(pRtree->pReadRowid, 1, cell.iRowid); |
| 1696 | steprc = sqlite3_step(pRtree->pReadRowid); |
| 1697 | rc = sqlite3_reset(pRtree->pReadRowid); |
| 1698 | if( SQLITE_ROW==steprc ){ |
| 1699 | if( sqlite3_vtab_on_conflict(pRtree->db)==SQLITE_REPLACE ){ |
| 1700 | rc = rtreeDeleteRowid(pRtree, cell.iRowid); |
| 1701 | }else{ |
| 1702 | rc = rtreeConstraintError(pRtree, 0); |
| 1703 | } |
| 1704 | } |
| 1705 | } |
| 1706 | } |
| 1707 | |
| 1708 | /* If aData[0] is not an SQL NULL value, it is the rowid of a |
| 1709 | ** record to delete from the r-tree table. The following block does |
| 1710 | ** just that. |
| 1711 | */ |
| 1712 | if( rc==SQLITE_OK && (nData==1 || (coordChange && oldRowidValid)) ){ |
| 1713 | rc = rtreeDeleteRowid(pRtree, oldRowid); |
| 1714 | } |
| 1715 | |
| 1716 | /* If the aData[] array contains more than one element, elements |
| 1717 | ** (aData[2]..aData[argc-1]) contain a new record to insert into |
| 1718 | ** the r-tree structure. |
| 1719 | */ |
| 1720 | if( rc==SQLITE_OK && nData>1 && coordChange ){ |
| 1721 | /* Insert the new record into the r-tree */ |
| 1722 | RtreeNode *pLeaf = 0; |
| 1723 | if( !newRowidValid ){ |
| 1724 | rc = rtreeNewRowid(pRtree, &cell.iRowid); |
| 1725 | } |
| 1726 | *pRowid = cell.iRowid; |
| 1727 | if( rc==SQLITE_OK ){ |
| 1728 | rc = ChooseLeaf(pRtree, &cell, 0, &pLeaf); |
| 1729 | } |
| 1730 | if( rc==SQLITE_OK ){ |
| 1731 | int rc2; |
| 1732 | rc = rtreeInsertCell(pRtree, pLeaf, &cell, 0); |
| 1733 | rc2 = nodeRelease(pRtree, pLeaf); |
| 1734 | if( rc==SQLITE_OK ){ |
| 1735 | rc = rc2; |
| 1736 | } |
| 1737 | } |
| 1738 | } |
| 1739 | |
| 1740 | /* Change the data */ |
| 1741 | if( rc==SQLITE_OK && nData>1 ){ |
| 1742 | sqlite3_stmt *pUp = pRtree->pWriteAux; |
| 1743 | int jj; |
| 1744 | int nChange = 0; |
| 1745 | sqlite3_bind_int64(pUp, 1, cell.iRowid); |
| 1746 | assert( pRtree->nAux>=1 ); |
| 1747 | if( sqlite3_value_nochange(pShape) ){ |
| 1748 | sqlite3_bind_null(pUp, 2); |
| 1749 | }else{ |
| 1750 | GeoPoly *p = 0; |
| 1751 | if( sqlite3_value_type(pShape)==SQLITE_TEXT |
| 1752 | && (p = geopolyFuncParam(0, pShape, &rc))!=0 |
| 1753 | && rc==SQLITE_OK |
| 1754 | ){ |
| 1755 | rc = sqlite3_bind_blob(pUp, 2, p->hdr, 4+8*p->nVertex, |
| 1756 | SQLITE_TRANSIENT); |
| 1757 | }else{ |
| 1758 | sqlite3_bind_value(pUp, 2, pShape); |
| 1759 | } |
| 1760 | sqlite3_free(p); |
| 1761 | nChange = 1; |
| 1762 | } |
| 1763 | for(jj=1; jj<nData-2; jj++){ |
| 1764 | nChange++; |
| 1765 | sqlite3_bind_value(pUp, jj+2, aData[jj+2]); |
| 1766 | } |
| 1767 | if( rc==SQLITE_OK && nChange ){ |
| 1768 | sqlite3_step(pUp); |
| 1769 | rc = sqlite3_reset(pUp); |
| 1770 | } |
| 1771 | } |
| 1772 | |
| 1773 | geopoly_update_end: |
| 1774 | sqlite3_value_free(pOldShape); |
| 1775 | rtreeRelease(pRtree); |
| 1776 | return rc; |
| 1777 | } |
| 1778 | |
| 1779 | /* |
| 1780 | ** Report that geopoly_overlap() is an overloaded function suitable |
| 1781 | ** for use in xBestIndex. |
| 1782 | */ |
| 1783 | static int geopolyFindFunction( |
| 1784 | sqlite3_vtab *pVtab, |
| 1785 | int nArg, |
| 1786 | const char *zName, |
| 1787 | void (**pxFunc)(sqlite3_context*,int,sqlite3_value**), |
| 1788 | void **ppArg |
| 1789 | ){ |
| 1790 | (void)pVtab; |
| 1791 | (void)nArg; |
| 1792 | if( sqlite3_stricmp(zName, "geopoly_overlap")==0 ){ |
| 1793 | *pxFunc = geopolyOverlapFunc; |
| 1794 | *ppArg = 0; |
| 1795 | return SQLITE_INDEX_CONSTRAINT_FUNCTION; |
| 1796 | } |
| 1797 | if( sqlite3_stricmp(zName, "geopoly_within")==0 ){ |
| 1798 | *pxFunc = geopolyWithinFunc; |
| 1799 | *ppArg = 0; |
| 1800 | return SQLITE_INDEX_CONSTRAINT_FUNCTION+1; |
| 1801 | } |
| 1802 | return 0; |
| 1803 | } |
| 1804 | |
| 1805 | |
| 1806 | static sqlite3_module geopolyModule = { |
| 1807 | 3, /* iVersion */ |
| 1808 | geopolyCreate, /* xCreate - create a table */ |
| 1809 | geopolyConnect, /* xConnect - connect to an existing table */ |
| 1810 | geopolyBestIndex, /* xBestIndex - Determine search strategy */ |
| 1811 | rtreeDisconnect, /* xDisconnect - Disconnect from a table */ |
| 1812 | rtreeDestroy, /* xDestroy - Drop a table */ |
| 1813 | rtreeOpen, /* xOpen - open a cursor */ |
| 1814 | rtreeClose, /* xClose - close a cursor */ |
| 1815 | geopolyFilter, /* xFilter - configure scan constraints */ |
| 1816 | rtreeNext, /* xNext - advance a cursor */ |
| 1817 | rtreeEof, /* xEof */ |
| 1818 | geopolyColumn, /* xColumn - read data */ |
| 1819 | rtreeRowid, /* xRowid - read data */ |
| 1820 | geopolyUpdate, /* xUpdate - write data */ |
| 1821 | rtreeBeginTransaction, /* xBegin - begin transaction */ |
| 1822 | rtreeEndTransaction, /* xSync - sync transaction */ |
| 1823 | rtreeEndTransaction, /* xCommit - commit transaction */ |
| 1824 | rtreeEndTransaction, /* xRollback - rollback transaction */ |
| 1825 | geopolyFindFunction, /* xFindFunction - function overloading */ |
| 1826 | rtreeRename, /* xRename - rename the table */ |
| 1827 | rtreeSavepoint, /* xSavepoint */ |
| 1828 | 0, /* xRelease */ |
| 1829 | 0, /* xRollbackTo */ |
| 1830 | rtreeShadowName, /* xShadowName */ |
| 1831 | rtreeIntegrity /* xIntegrity */ |
| 1832 | }; |
| 1833 | |
| 1834 | static int sqlite3_geopoly_init(sqlite3 *db){ |
| 1835 | int rc = SQLITE_OK; |
| 1836 | static const struct { |
| 1837 | void (*xFunc)(sqlite3_context*,int,sqlite3_value**); |
| 1838 | signed char nArg; |
| 1839 | unsigned char bPure; |
| 1840 | const char *zName; |
| 1841 | } aFunc[] = { |
| 1842 | { geopolyAreaFunc, 1, 1, "geopoly_area" }, |
| 1843 | { geopolyBlobFunc, 1, 1, "geopoly_blob" }, |
| 1844 | { geopolyJsonFunc, 1, 1, "geopoly_json" }, |
| 1845 | { geopolySvgFunc, -1, 1, "geopoly_svg" }, |
| 1846 | { geopolyWithinFunc, 2, 1, "geopoly_within" }, |
| 1847 | { geopolyContainsPointFunc, 3, 1, "geopoly_contains_point" }, |
| 1848 | { geopolyOverlapFunc, 2, 1, "geopoly_overlap" }, |
| 1849 | { geopolyDebugFunc, 1, 0, "geopoly_debug" }, |
| 1850 | { geopolyBBoxFunc, 1, 1, "geopoly_bbox" }, |
| 1851 | { geopolyXformFunc, 7, 1, "geopoly_xform" }, |
| 1852 | { geopolyRegularFunc, 4, 1, "geopoly_regular" }, |
| 1853 | { geopolyCcwFunc, 1, 1, "geopoly_ccw" }, |
| 1854 | }; |
| 1855 | static const struct { |
| 1856 | void (*xStep)(sqlite3_context*,int,sqlite3_value**); |
| 1857 | void (*xFinal)(sqlite3_context*); |
| 1858 | const char *zName; |
| 1859 | } aAgg[] = { |
| 1860 | { geopolyBBoxStep, geopolyBBoxFinal, "geopoly_group_bbox" }, |
| 1861 | }; |
| 1862 | unsigned int i; |
| 1863 | for(i=0; i<sizeof(aFunc)/sizeof(aFunc[0]) && rc==SQLITE_OK; i++){ |
| 1864 | int enc; |
| 1865 | if( aFunc[i].bPure ){ |
| 1866 | enc = SQLITE_UTF8|SQLITE_DETERMINISTIC|SQLITE_INNOCUOUS; |
| 1867 | }else{ |
| 1868 | enc = SQLITE_UTF8|SQLITE_DIRECTONLY; |
| 1869 | } |
| 1870 | rc = sqlite3_create_function(db, aFunc[i].zName, aFunc[i].nArg, |
| 1871 | enc, 0, |
| 1872 | aFunc[i].xFunc, 0, 0); |
| 1873 | } |
| 1874 | for(i=0; i<sizeof(aAgg)/sizeof(aAgg[0]) && rc==SQLITE_OK; i++){ |
| 1875 | rc = sqlite3_create_function(db, aAgg[i].zName, 1, |
| 1876 | SQLITE_UTF8|SQLITE_DETERMINISTIC|SQLITE_INNOCUOUS, 0, |
| 1877 | 0, aAgg[i].xStep, aAgg[i].xFinal); |
| 1878 | } |
| 1879 | if( rc==SQLITE_OK ){ |
| 1880 | rc = sqlite3_create_module_v2(db, "geopoly", &geopolyModule, 0, 0); |
| 1881 | } |
| 1882 | return rc; |
| 1883 | } |