Coverage Report

Created: 2026-12-01 06:12

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/postgis/liblwgeom/lwalgorithm.c
Line
Count
Source
1
/**********************************************************************
2
 *
3
 * PostGIS - Spatial Types for PostgreSQL
4
 * http://postgis.net
5
 *
6
 * PostGIS is free software: you can redistribute it and/or modify
7
 * it under the terms of the GNU General Public License as published by
8
 * the Free Software Foundation, either version 2 of the License, or
9
 * (at your option) any later version.
10
 *
11
 * PostGIS is distributed in the hope that it will be useful,
12
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14
 * GNU General Public License for more details.
15
 *
16
 * You should have received a copy of the GNU General Public License
17
 * along with PostGIS.  If not, see <http://www.gnu.org/licenses/>.
18
 *
19
 **********************************************************************
20
 *
21
 * Copyright 2008 Paul Ramsey
22
 * Copyright 2026 Darafei Praliaskouski <me@komzpa.net>
23
 *
24
 **********************************************************************/
25
26
#include "liblwgeom_internal.h"
27
#include "lwgeom_log.h"
28
#include "lwascii.h"
29
#include <limits.h>
30
#include <stdbool.h>
31
32
int
33
p4d_same(const POINT4D *p1, const POINT4D *p2)
34
0
{
35
0
  return p1->x == p2->x && p1->y == p2->y && p1->z == p2->z && p1->m == p2->m;
36
0
}
37
38
int
39
p3d_same(const POINT3D *p1, const POINT3D *p2)
40
1.45M
{
41
1.45M
  return p1->x == p2->x && p1->y == p2->y && p1->z == p2->z;
42
1.45M
}
43
44
int
45
p3dz_same(const POINT3DZ *p1, const POINT3DZ *p2)
46
0
{
47
0
  return p1->x == p2->x && p1->y == p2->y && p1->z == p2->z;
48
0
}
49
50
int
51
p2d_same(const POINT2D *p1, const POINT2D *p2)
52
0
{
53
0
  return p1->x == p2->x && p1->y == p2->y;
54
0
}
55
56
/**
57
 * lw_segment_side()
58
 *
59
 * Return -1  if point Q is left of segment P
60
 * Return  1  if point Q is right of segment P
61
 * Return  0  if point Q in on segment P
62
 */
63
int
64
lw_segment_side(const POINT2D *p1, const POINT2D *p2, const POINT2D *q)
65
137k
{
66
137k
  double side = ((q->x - p1->x) * (p2->y - p1->y) - (p2->x - p1->x) * (q->y - p1->y));
67
137k
  return SIGNUM(side);
68
137k
}
69
70
/**
71
 * Returns the length of a linear segment
72
 */
73
double
74
lw_seg_length(const POINT2D *A1, const POINT2D *A2)
75
0
{
76
0
  return sqrt((A1->x - A2->x) * (A1->x - A2->x) + (A1->y - A2->y) * (A1->y - A2->y));
77
0
}
78
79
/**
80
 * Returns true if P is on the same side of the plane partition
81
 * defined by A1/A3 as A2 is. Only makes sense if P has already been
82
 * determined to be on the circle defined by A1/A2/A3.
83
 */
84
int
85
lw_pt_in_arc(const POINT2D *P, const POINT2D *A1, const POINT2D *A2, const POINT2D *A3)
86
0
{
87
0
  int pt_side = lw_segment_side(A1, A3, P);
88
0
  int arc_side = lw_segment_side(A1, A3, A2);
89
0
  return pt_side == 0 || pt_side == arc_side;
90
0
}
91
92
/**
93
 * Returns true if P is between A1/A2. Only makes sense if P has already been
94
 * determined to be on the line defined by A1/A2.
95
 */
96
int
97
lw_pt_in_seg(const POINT2D *P, const POINT2D *A1, const POINT2D *A2)
98
0
{
99
0
  return ((A1->x <= P->x && P->x < A2->x) || (A1->x >= P->x && P->x > A2->x)) ||
100
0
         ((A1->y <= P->y && P->y < A2->y) || (A1->y >= P->y && P->y > A2->y));
101
0
}
102
103
int
104
lw_pt_on_segment(const POINT2D *A1, const POINT2D *A2, const POINT2D *P)
105
0
{
106
0
  int side = lw_segment_side(A1, A2, P);
107
0
  if (side != 0)
108
0
    return LW_FALSE;
109
0
  return lw_pt_in_seg(P, A1, A2);
110
0
}
111
112
/**
113
 * Returns true if arc A is actually a point (all vertices are the same) .
114
 */
115
int
116
lw_arc_is_pt(const POINT2D *A1, const POINT2D *A2, const POINT2D *A3)
117
0
{
118
0
  if (A1->x == A2->x && A2->x == A3->x && A1->y == A2->y && A2->y == A3->y)
119
0
    return LW_TRUE;
120
0
  else
121
0
    return LW_FALSE;
122
0
}
123
124
/**
125
 * Returns the length of a circular arc segment
126
 */
127
double
128
lw_arc_length(const POINT2D *A1, const POINT2D *A2, const POINT2D *A3)
129
0
{
130
0
  POINT2D C;
131
0
  double radius_A, circumference_A;
132
0
  int a2_side, clockwise;
133
0
  double a1, a3;
134
0
  double angle;
135
136
0
  if (lw_arc_is_pt(A1, A2, A3))
137
0
    return 0.0;
138
139
0
  radius_A = lw_arc_center(A1, A2, A3, &C);
140
141
  /* Co-linear! Return linear distance! */
142
0
  if (radius_A < 0)
143
0
  {
144
0
    double dx = A1->x - A3->x;
145
0
    double dy = A1->y - A3->y;
146
0
    return sqrt(dx * dx + dy * dy);
147
0
  }
148
149
  /* Closed circle! Return the circumference! */
150
0
  circumference_A = M_PI * 2 * radius_A;
151
0
  if (p2d_same(A1, A3))
152
0
    return circumference_A;
153
154
  /* Determine the orientation of the arc */
155
0
  a2_side = lw_segment_side(A1, A3, A2);
156
157
  /* The side of the A1/A3 line that A2 falls on dictates the sweep
158
     direction from A1 to A3. */
159
0
  if (a2_side == -1)
160
0
    clockwise = LW_TRUE;
161
0
  else
162
0
    clockwise = LW_FALSE;
163
164
  /* Angles of each point that defines the arc section */
165
0
  a1 = atan2(A1->y - C.y, A1->x - C.x);
166
0
  a3 = atan2(A3->y - C.y, A3->x - C.x);
167
168
  /* What's the sweep from A1 to A3? */
169
0
  if (clockwise)
170
0
  {
171
0
    if (a1 > a3)
172
0
      angle = a1 - a3;
173
0
    else
174
0
      angle = 2 * M_PI + a1 - a3;
175
0
  }
176
0
  else
177
0
  {
178
0
    if (a3 > a1)
179
0
      angle = a3 - a1;
180
0
    else
181
0
      angle = 2 * M_PI + a3 - a1;
182
0
  }
183
184
  /* Length as proportion of circumference */
185
0
  return circumference_A * (angle / (2 * M_PI));
186
0
}
187
188
int
189
lw_arc_side(const POINT2D *A1, const POINT2D *A2, const POINT2D *A3, const POINT2D *Q)
190
0
{
191
0
  POINT2D C;
192
0
  double radius_A;
193
0
  double side_Q, side_A2;
194
0
  double d;
195
196
0
  side_Q = lw_segment_side(A1, A3, Q);
197
0
  radius_A = lw_arc_center(A1, A2, A3, &C);
198
0
  side_A2 = lw_segment_side(A1, A3, A2);
199
200
  /* Linear case */
201
0
  if (radius_A < 0)
202
0
    return side_Q;
203
204
0
  d = distance2d_pt_pt(Q, &C);
205
206
  /* Q is on the arc boundary */
207
0
  if (d == radius_A && side_Q == side_A2)
208
0
  {
209
0
    return 0;
210
0
  }
211
212
  /* Q on A1-A3 line, so its on opposite side to A2 */
213
0
  if (side_Q == 0)
214
0
  {
215
0
    return -1 * side_A2;
216
0
  }
217
218
  /*
219
   * Q is inside the arc boundary, so it's not on the side we
220
   * might think from examining only the end points
221
   */
222
0
  if (d < radius_A && side_Q == side_A2)
223
0
  {
224
0
    side_Q *= -1;
225
0
  }
226
227
0
  return side_Q;
228
0
}
229
230
/**
231
 * Determines the center of the circle defined by the three given points.
232
 * In the event the circle is complete, the midpoint of the segment defined
233
 * by the first and second points is returned.  If the points are collinear,
234
 * as determined by equal slopes, then -1.0 is returned.  If the interior
235
 * point is coincident with either end point, they are taken as collinear.
236
 * For non-collinear cases, arc radious is returned.
237
 */
238
double
239
lw_arc_center(const POINT2D *p1, const POINT2D *p2, const POINT2D *p3, POINT2D *result)
240
2.29M
{
241
2.29M
  POINT2D c;
242
2.29M
  double cx, cy, cr;
243
2.29M
  double dx21, dy21, dx31, dy31, h21, h31, d;
244
245
2.29M
  c.x = c.y = 0.0;
246
247
2.29M
  LWDEBUGF(2,
248
2.29M
     "lw_arc_center called (%.16f,%.16f), (%.16f,%.16f), (%.16f,%.16f).",
249
2.29M
     p1->x,
250
2.29M
     p1->y,
251
2.29M
     p2->x,
252
2.29M
     p2->y,
253
2.29M
     p3->x,
254
2.29M
     p3->y);
255
256
  /* Closed circle */
257
2.29M
  if (fabs(p1->x - p3->x) < EPSILON_SQLMM && fabs(p1->y - p3->y) < EPSILON_SQLMM)
258
2.27M
  {
259
2.27M
    cx = p1->x + (p2->x - p1->x) / 2.0;
260
2.27M
    cy = p1->y + (p2->y - p1->y) / 2.0;
261
2.27M
    c.x = cx;
262
2.27M
    c.y = cy;
263
2.27M
    *result = c;
264
2.27M
    cr = sqrt(pow(cx - p1->x, 2.0) + pow(cy - p1->y, 2.0));
265
2.27M
    return cr;
266
2.27M
  }
267
268
  /* Using cartesian eguations from page https://en.wikipedia.org/wiki/Circumscribed_circle */
269
13.0k
  dx21 = p2->x - p1->x;
270
13.0k
  dy21 = p2->y - p1->y;
271
13.0k
  dx31 = p3->x - p1->x;
272
13.0k
  dy31 = p3->y - p1->y;
273
274
13.0k
  h21 = pow(dx21, 2.0) + pow(dy21, 2.0);
275
13.0k
  h31 = pow(dx31, 2.0) + pow(dy31, 2.0);
276
277
  /* 2 * |Cross product|, d<0 means clockwise and d>0 counterclockwise sweeping angle */
278
13.0k
  d = 2 * (dx21 * dy31 - dx31 * dy21);
279
280
  /* Check colinearity, |Cross product| = 0 */
281
13.0k
  if (fabs(d) < EPSILON_SQLMM)
282
5.58k
    return -1.0;
283
284
  /* Calculate centroid coordinates and radius */
285
7.45k
  cx = p1->x + (h21 * dy31 - h31 * dy21) / d;
286
7.45k
  cy = p1->y - (h21 * dx31 - h31 * dx21) / d;
287
7.45k
  c.x = cx;
288
7.45k
  c.y = cy;
289
7.45k
  *result = c;
290
7.45k
  cr = sqrt(pow(cx - p1->x, 2) + pow(cy - p1->y, 2));
291
292
7.45k
  LWDEBUGF(2, "lw_arc_center center is (%.16f,%.16f)", result->x, result->y);
293
294
7.45k
  return cr;
295
13.0k
}
296
297
static int
298
lw_seg_interact(const POINT2D *p1, const POINT2D *p2, const POINT2D *q1, const POINT2D *q2)
299
0
{
300
0
  double minq = FP_MIN(q1->x, q2->x);
301
0
  double maxq = FP_MAX(q1->x, q2->x);
302
0
  double minp = FP_MIN(p1->x, p2->x);
303
0
  double maxp = FP_MAX(p1->x, p2->x);
304
305
0
  if (FP_GT(minp, maxq) || FP_LT(maxp, minq))
306
0
    return LW_FALSE;
307
308
0
  minq = FP_MIN(q1->y, q2->y);
309
0
  maxq = FP_MAX(q1->y, q2->y);
310
0
  minp = FP_MIN(p1->y, p2->y);
311
0
  maxp = FP_MAX(p1->y, p2->y);
312
313
0
  if (FP_GT(minp, maxq) || FP_LT(maxp, minq))
314
0
    return LW_FALSE;
315
316
0
  return LW_TRUE;
317
0
}
318
319
/**
320
** @brief returns the kind of #CG_SEGMENT_INTERSECTION_TYPE  behavior of lineseg 1 (constructed from p1 and p2) and
321
* lineseg 2 (constructed from q1 and q2) *  @param p1 start point of first straight linesegment * @param p2 end
322
* point of first straight linesegment * @param q1 start point of second line segment *  @param q2 end point of second
323
* line segment *  @return a #CG_SEGMENT_INTERSECTION_TYPE
324
**  Returns one of
325
**    SEG_ERROR = -1,
326
**    SEG_NO_INTERSECTION = 0,
327
**    SEG_COLINEAR = 1,
328
**    SEG_CROSS_LEFT = 2,
329
**    SEG_CROSS_RIGHT = 3,
330
*/
331
int
332
lw_segment_intersects(const POINT2D *p1, const POINT2D *p2, const POINT2D *q1, const POINT2D *q2)
333
0
{
334
335
0
  int pq1, pq2, qp1, qp2;
336
337
  /* No envelope interaction => we are done. */
338
0
  if (!lw_seg_interact(p1, p2, q1, p2))
339
0
  {
340
0
    return SEG_NO_INTERSECTION;
341
0
  }
342
343
  /* Are the start and end points of q on the same side of p? */
344
0
  pq1 = lw_segment_side(p1, p2, q1);
345
0
  pq2 = lw_segment_side(p1, p2, q2);
346
0
  if ((pq1 > 0 && pq2 > 0) || (pq1 < 0 && pq2 < 0))
347
0
  {
348
0
    return SEG_NO_INTERSECTION;
349
0
  }
350
351
  /* Are the start and end points of p on the same side of q? */
352
0
  qp1 = lw_segment_side(q1, q2, p1);
353
0
  qp2 = lw_segment_side(q1, q2, p2);
354
0
  if ((qp1 > 0.0 && qp2 > 0.0) || (qp1 < 0.0 && qp2 < 0.0))
355
0
  {
356
0
    return SEG_NO_INTERSECTION;
357
0
  }
358
359
  /* Nobody is on one side or another? Must be colinear. */
360
0
  if (pq1 == 0.0 && pq2 == 0.0 && qp1 == 0.0 && qp2 == 0.0)
361
0
  {
362
0
    return SEG_COLINEAR;
363
0
  }
364
365
  /*
366
  ** When one end-point touches, the sidedness is determined by the
367
  ** location of the other end-point. Only touches by the first point
368
  ** will be considered "real" to avoid double counting.
369
  */
370
0
  LWDEBUGF(4, "pq1=%d pq2=%d", pq1, pq2);
371
0
  LWDEBUGF(4, "qp1=%d qp2=%d", qp1, qp2);
372
373
  /* Second point of p or q touches, it's not a crossing. */
374
0
  if (pq2 == 0 || qp2 == 0)
375
0
  {
376
0
    return SEG_NO_INTERSECTION;
377
0
  }
378
379
  /* First point of p touches, it's a "crossing". */
380
0
  if (pq1 == 0)
381
0
  {
382
0
    if (pq2 > 0)
383
0
      return SEG_CROSS_RIGHT;
384
0
    else
385
0
      return SEG_CROSS_LEFT;
386
0
  }
387
388
  /* First point of q touches, it's a crossing. */
389
0
  if (qp1 == 0)
390
0
  {
391
0
    if (pq1 < pq2)
392
0
      return SEG_CROSS_RIGHT;
393
0
    else
394
0
      return SEG_CROSS_LEFT;
395
0
  }
396
397
  /* The segments cross, what direction is the crossing? */
398
0
  if (pq1 < pq2)
399
0
    return SEG_CROSS_RIGHT;
400
0
  else
401
0
    return SEG_CROSS_LEFT;
402
403
  /* This should never happen! */
404
0
  return SEG_ERROR;
405
0
}
406
407
/**
408
** @brief lwline_crossing_direction: returns the kind of #CG_LINE_CROSS_TYPE behavior  of 2 linestrings
409
** @param l1 first line string
410
** @param l2 second line string
411
** @return a #CG_LINE_CROSS_TYPE
412
**   LINE_NO_CROSS = 0
413
**   LINE_CROSS_LEFT = -1
414
**   LINE_CROSS_RIGHT = 1
415
**   LINE_MULTICROSS_END_LEFT = -2
416
**   LINE_MULTICROSS_END_RIGHT = 2
417
**   LINE_MULTICROSS_END_SAME_FIRST_LEFT = -3
418
**   LINE_MULTICROSS_END_SAME_FIRST_RIGHT = 3
419
**
420
*/
421
int
422
lwline_crossing_direction(const LWLINE *l1, const LWLINE *l2)
423
0
{
424
0
  uint32_t i = 0, j = 0;
425
0
  const POINT2D *p1, *p2, *q1, *q2;
426
0
  POINTARRAY *pa1 = NULL, *pa2 = NULL;
427
0
  int cross_left = 0;
428
0
  int cross_right = 0;
429
0
  int first_cross = 0;
430
0
  int this_cross = 0;
431
#if POSTGIS_DEBUG_LEVEL >= 4
432
  char *geom_ewkt;
433
#endif
434
435
0
  pa1 = (POINTARRAY *)l1->points;
436
0
  pa2 = (POINTARRAY *)l2->points;
437
438
  /* One-point lines can't intersect (and shouldn't exist). */
439
0
  if (pa1->npoints < 2 || pa2->npoints < 2)
440
0
    return LINE_NO_CROSS;
441
442
  /* Zero length lines don't have a side. */
443
0
  if (ptarray_length_2d(pa1) == 0 || ptarray_length_2d(pa2) == 0)
444
0
    return LINE_NO_CROSS;
445
446
#if POSTGIS_DEBUG_LEVEL >= 4
447
  geom_ewkt = lwgeom_to_ewkt((LWGEOM *)l1);
448
  LWDEBUGF(4, "l1 = %s", geom_ewkt);
449
  lwfree(geom_ewkt);
450
  geom_ewkt = lwgeom_to_ewkt((LWGEOM *)l2);
451
  LWDEBUGF(4, "l2 = %s", geom_ewkt);
452
  lwfree(geom_ewkt);
453
#endif
454
455
  /* Initialize first point of q */
456
0
  q1 = getPoint2d_cp(pa2, 0);
457
458
0
  for (i = 1; i < pa2->npoints; i++)
459
0
  {
460
0
    int segment_first_cross = 0;
461
0
    double segment_first_t = 0.0;
462
463
    /* Update second point of q to next value */
464
0
    q2 = getPoint2d_cp(pa2, i);
465
466
    /* Initialize first point of p */
467
0
    p1 = getPoint2d_cp(pa1, 0);
468
469
0
    for (j = 1; j < pa1->npoints; j++)
470
0
    {
471
472
      /* Update second point of p to next value */
473
0
      p2 = getPoint2d_cp(pa1, j);
474
475
0
      this_cross = lw_segment_intersects(p1, p2, q1, q2);
476
477
0
      LWDEBUGF(4, "i=%d, j=%d (%.8g %.8g, %.8g %.8g)", i, j, p1->x, p1->y, p2->x, p2->y);
478
479
0
      if (this_cross == SEG_CROSS_LEFT)
480
0
      {
481
0
        LWDEBUG(4, "this_cross == SEG_CROSS_LEFT");
482
0
        cross_left++;
483
0
      }
484
485
0
      if (this_cross == SEG_CROSS_RIGHT)
486
0
      {
487
0
        LWDEBUG(4, "this_cross == SEG_CROSS_RIGHT");
488
0
        cross_right++;
489
0
      }
490
491
      /* Crossings on the same q segment need ordering along q. */
492
0
      if (!first_cross && (this_cross == SEG_CROSS_LEFT || this_cross == SEG_CROSS_RIGHT))
493
0
      {
494
0
        const double dx = p2->x - p1->x;
495
0
        const double dy = p2->y - p1->y;
496
0
        const double t = ((p1->x - q1->x) * dy - (p1->y - q1->y) * dx) /
497
0
             ((q2->x - q1->x) * dy - (q2->y - q1->y) * dx);
498
0
        if (!segment_first_cross || t < segment_first_t)
499
0
        {
500
0
          segment_first_cross = this_cross;
501
0
          segment_first_t = t;
502
0
        }
503
0
      }
504
505
      /*
506
      ** Crossing at a co-linearity can be turned handled by extending
507
      ** segment to next vertex and seeing if the end points straddle
508
      ** the co-linear segment.
509
      */
510
0
      if (this_cross == SEG_COLINEAR)
511
0
      {
512
0
        LWDEBUG(4, "this_cross == SEG_COLINEAR");
513
        /* TODO: Add logic here and in segment_intersects()
514
        continue;
515
        */
516
0
      }
517
518
0
      LWDEBUG(4, "this_cross == SEG_NO_INTERSECTION");
519
520
      /* Turn second point of p into first point */
521
0
      p1 = p2;
522
0
    }
523
524
0
    if (!first_cross)
525
0
      first_cross = segment_first_cross;
526
    /* Turn second point of q into first point */
527
0
    q1 = q2;
528
0
  }
529
530
0
  LWDEBUGF(4, "first_cross=%d, cross_left=%d, cross_right=%d", first_cross, cross_left, cross_right);
531
532
0
  if (!cross_left && !cross_right)
533
0
    return LINE_NO_CROSS;
534
535
0
  if (!cross_left && cross_right == 1)
536
0
    return LINE_CROSS_RIGHT;
537
538
0
  if (!cross_right && cross_left == 1)
539
0
    return LINE_CROSS_LEFT;
540
541
0
  if (cross_left - cross_right == 1)
542
0
    return LINE_MULTICROSS_END_LEFT;
543
544
0
  if (cross_left - cross_right == -1)
545
0
    return LINE_MULTICROSS_END_RIGHT;
546
547
0
  if (cross_left - cross_right == 0 && first_cross == SEG_CROSS_LEFT)
548
0
    return LINE_MULTICROSS_END_SAME_FIRST_LEFT;
549
550
0
  if (cross_left - cross_right == 0 && first_cross == SEG_CROSS_RIGHT)
551
0
    return LINE_MULTICROSS_END_SAME_FIRST_RIGHT;
552
553
0
  return LINE_NO_CROSS;
554
0
}
555
556
static char *base32 = "0123456789bcdefghjkmnpqrstuvwxyz";
557
558
0
#define GEOHASH_MAX_DOUBLE_PRECISION_CHARS 20
559
560
/*
561
** Calculate the geohash, iterating downwards and gaining precision.
562
** From geohash-native.c, (c) 2008 David Troy <dave@roundhousetech.com>
563
** Released under the MIT License.
564
*/
565
lwvarlena_t *
566
geohash_point(double longitude, double latitude, int precision)
567
0
{
568
0
  int is_even = 1, i = 0;
569
0
  double lat[2], lon[2], mid;
570
0
  char bits[] = {16, 8, 4, 2, 1};
571
0
  int bit = 0, ch = 0;
572
0
  lwvarlena_t *v;
573
0
  char *geohash;
574
575
  /* precision + LWVARHDRSZ overflows int near INT_MAX and the negative
576
   * result reaches the allocator as an enormous size_t.  Zero is not an
577
   * error: lwgeom_geohash_precision() legitimately returns it for a box
578
   * wider than about 22 degrees in both axes, and the answer is then the
579
   * empty string. */
580
0
  if (precision < 0 || (size_t)precision > LW_MAX_ALLOC_SIZE - LWVARHDRSZ)
581
0
  {
582
0
    lwerror(
583
0
        "Geohash precision is too large: %d (maximum %zu)", precision, LW_MAX_ALLOC_SIZE - LWVARHDRSZ);
584
0
    return NULL;
585
0
  }
586
587
0
  v = lwalloc(precision + LWVARHDRSZ);
588
0
  LWSIZE_SET(v->size, precision + LWVARHDRSZ);
589
0
  geohash = v->data;
590
591
0
  lat[0] = -90.0;
592
0
  lat[1] = 90.0;
593
0
  lon[0] = -180.0;
594
0
  lon[1] = 180.0;
595
596
0
  while (i < precision)
597
0
  {
598
0
    if (is_even)
599
0
    {
600
0
      mid = (lon[0] + lon[1]) / 2;
601
0
      if (longitude >= mid)
602
0
      {
603
0
        ch |= bits[bit];
604
0
        lon[0] = mid;
605
0
      }
606
0
      else
607
0
      {
608
0
        lon[1] = mid;
609
0
      }
610
0
    }
611
0
    else
612
0
    {
613
0
      mid = (lat[0] + lat[1]) / 2;
614
0
      if (latitude >= mid)
615
0
      {
616
0
        ch |= bits[bit];
617
0
        lat[0] = mid;
618
0
      }
619
0
      else
620
0
      {
621
0
        lat[1] = mid;
622
0
      }
623
0
    }
624
625
0
    is_even = !is_even;
626
0
    if (bit < 4)
627
0
    {
628
0
      bit++;
629
0
    }
630
0
    else
631
0
    {
632
0
      geohash[i++] = base32[ch];
633
0
      bit = 0;
634
0
      ch = 0;
635
0
    }
636
0
  }
637
638
0
  return v;
639
0
}
640
641
/*
642
** Calculate the geohash, iterating downwards and gaining precision.
643
** From geohash-native.c, (c) 2008 David Troy <dave@roundhousetech.com>
644
** Released under the MIT License.
645
*/
646
unsigned int
647
geohash_point_as_int(POINT2D *pt)
648
0
{
649
0
  int is_even = 1;
650
0
  double lat[2], lon[2], mid;
651
0
  int bit = 32;
652
0
  unsigned int ch = 0;
653
654
0
  double longitude = pt->x;
655
0
  double latitude = pt->y;
656
657
0
  lat[0] = -90.0;
658
0
  lat[1] = 90.0;
659
0
  lon[0] = -180.0;
660
0
  lon[1] = 180.0;
661
662
0
  while (--bit >= 0)
663
0
  {
664
0
    if (is_even)
665
0
    {
666
0
      mid = (lon[0] + lon[1]) / 2;
667
0
      if (longitude > mid)
668
0
      {
669
0
        ch |= 0x0001u << bit;
670
0
        lon[0] = mid;
671
0
      }
672
0
      else
673
0
      {
674
0
        lon[1] = mid;
675
0
      }
676
0
    }
677
0
    else
678
0
    {
679
0
      mid = (lat[0] + lat[1]) / 2;
680
0
      if (latitude > mid)
681
0
      {
682
0
        ch |= 0x0001 << bit;
683
0
        lat[0] = mid;
684
0
      }
685
0
      else
686
0
      {
687
0
        lat[1] = mid;
688
0
      }
689
0
    }
690
691
0
    is_even = !is_even;
692
0
  }
693
0
  return ch;
694
0
}
695
696
/*
697
** Decode a GeoHash into a bounding box. The lat and lon arguments should
698
** both be passed as double arrays of length 2 at a minimum where the values
699
** set in them will be the southwest and northeast coordinates of the bounding
700
** box accordingly. A precision less than 0 indicates that the entire length
701
** of the GeoHash should be used.
702
** It will call `lwerror` if an invalid character is found
703
*/
704
void
705
decode_geohash_bbox(char *geohash, double *lat, double *lon, int precision)
706
102
{
707
102
  bool is_even = 1;
708
709
102
  lat[0] = -90.0;
710
102
  lat[1] = 90.0;
711
102
  lon[0] = -180.0;
712
102
  lon[1] = 180.0;
713
714
102
  size_t hashlen = strlen(geohash);
715
102
  if (precision < 0 || (size_t)precision > hashlen)
716
70
  {
717
70
    precision = (int)hashlen;
718
70
  }
719
720
8.03k
  for (int i = 0; i < precision; i++)
721
7.97k
  {
722
7.97k
    char c = lw_ascii_tolower(geohash[i]);
723
724
    /* Valid characters are all digits in base32 */
725
7.97k
    char *base32_pos = strchr(base32, c);
726
7.97k
    if (!base32_pos)
727
44
    {
728
44
      lwerror("%s: Invalid character '%c'", __func__, geohash[i]);
729
44
      return;
730
44
    }
731
7.92k
    char cd = base32_pos - base32;
732
733
47.5k
    for (size_t j = 0; j < 5; j++)
734
39.6k
    {
735
39.6k
      const char bits[] = {16, 8, 4, 2, 1};
736
39.6k
      char mask = bits[j];
737
39.6k
      if (is_even)
738
19.8k
      {
739
19.8k
        lon[!(cd & mask)] = (lon[0] + lon[1]) / 2;
740
19.8k
      }
741
19.8k
      else
742
19.8k
      {
743
19.8k
        lat[!(cd & mask)] = (lat[0] + lat[1]) / 2;
744
19.8k
      }
745
39.6k
      is_even = !is_even;
746
39.6k
    }
747
7.92k
  }
748
102
}
749
750
int
751
lwgeom_geohash_precision(GBOX bbox, GBOX *bounds)
752
0
{
753
0
  double minx, miny, maxx, maxy;
754
0
  double latmax, latmin, lonmax, lonmin;
755
0
  double lonwidth, latwidth;
756
0
  double latmaxadjust, lonmaxadjust, latminadjust, lonminadjust;
757
0
  int precision = 0;
758
759
  /* Get the bounding box, return error if things don't work out. */
760
0
  minx = bbox.xmin;
761
0
  miny = bbox.ymin;
762
0
  maxx = bbox.xmax;
763
0
  maxy = bbox.ymax;
764
765
0
  if (minx == maxx && miny == maxy)
766
0
  {
767
    /* It's a point. Doubles have 51 bits of precision.
768
    ** 2 * 51 / 5 == 20 */
769
0
    return GEOHASH_MAX_DOUBLE_PRECISION_CHARS;
770
0
  }
771
772
0
  lonmin = -180.0;
773
0
  latmin = -90.0;
774
0
  lonmax = 180.0;
775
0
  latmax = 90.0;
776
777
  /* Shrink a world bounding box until one of the edges interferes with the
778
  ** bounds of our rectangle. */
779
0
  while (1)
780
0
  {
781
0
    double old_lonmin = lonmin;
782
0
    double old_lonmax = lonmax;
783
0
    double old_latmin = latmin;
784
0
    double old_latmax = latmax;
785
786
0
    lonwidth = lonmax - lonmin;
787
0
    latwidth = latmax - latmin;
788
0
    latmaxadjust = lonmaxadjust = latminadjust = lonminadjust = 0.0;
789
790
0
    if (minx >= lonmin + lonwidth / 2.0)
791
0
    {
792
0
      lonminadjust = lonwidth / 2.0;
793
0
    }
794
0
    else if (maxx <= lonmax - lonwidth / 2.0)
795
0
    {
796
0
      lonmaxadjust = -1 * lonwidth / 2.0;
797
0
    }
798
0
    if (lonminadjust || lonmaxadjust)
799
0
    {
800
0
      lonmin += lonminadjust;
801
0
      lonmax += lonmaxadjust;
802
      /* Stop before counting bits that no longer move the double bounds. */
803
0
      if (lonmin == old_lonmin && lonmax == old_lonmax)
804
0
        break;
805
      /* Each adjustment cycle corresponds to 2 bits of storage in the
806
      ** geohash. */
807
0
      precision++;
808
0
    }
809
0
    else
810
0
    {
811
0
      break;
812
0
    }
813
814
0
    if (miny >= latmin + latwidth / 2.0)
815
0
    {
816
0
      latminadjust = latwidth / 2.0;
817
0
    }
818
0
    else if (maxy <= latmax - latwidth / 2.0)
819
0
    {
820
0
      latmaxadjust = -1 * latwidth / 2.0;
821
0
    }
822
    /* Only adjust if adjustments are legal (we haven't crossed any edges). */
823
0
    if (latminadjust || latmaxadjust)
824
0
    {
825
0
      latmin += latminadjust;
826
0
      latmax += latmaxadjust;
827
      /* Stop before counting bits that no longer move the double bounds. */
828
0
      if (latmin == old_latmin && latmax == old_latmax)
829
0
        break;
830
      /* Each adjustment cycle corresponds to 2 bits of storage in the
831
      ** geohash. */
832
0
      precision++;
833
0
    }
834
0
    else
835
0
    {
836
0
      break;
837
0
    }
838
0
  }
839
840
  /* Save the edges of our bounds, in case someone cares later. */
841
0
  bounds->xmin = lonmin;
842
0
  bounds->xmax = lonmax;
843
0
  bounds->ymin = latmin;
844
0
  bounds->ymax = latmax;
845
846
  /* Each geohash character (base32) can contain 5 bits of information.
847
  ** We are returning the precision in characters, so here we divide. */
848
0
  precision /= 5;
849
0
  return precision > GEOHASH_MAX_DOUBLE_PRECISION_CHARS ? GEOHASH_MAX_DOUBLE_PRECISION_CHARS : precision;
850
0
}
851
852
/*
853
** Return a geohash string for the geometry. <http://geohash.org>
854
** Where the precision is non-positive, calculate a precision based on the
855
** bounds of the feature. Big features have loose precision.
856
** Small features have tight precision.
857
*/
858
lwvarlena_t *
859
lwgeom_geohash(const LWGEOM *lwgeom, int precision)
860
0
{
861
0
  GBOX gbox = {0};
862
0
  GBOX gbox_bounds = {0};
863
0
  double lat, lon;
864
0
  int result;
865
866
0
  gbox_init(&gbox);
867
0
  gbox_init(&gbox_bounds);
868
869
0
  result = lwgeom_calculate_gbox_cartesian(lwgeom, &gbox);
870
0
  if (result == LW_FAILURE)
871
0
    return NULL;
872
873
  /* Return error if we are being fed something outside our working bounds */
874
0
  if (gbox.xmin < -180 || gbox.ymin < -90 || gbox.xmax > 180 || gbox.ymax > 90)
875
0
  {
876
0
    lwerror("Geohash requires inputs in decimal degrees, got (%g %g, %g %g).",
877
0
      gbox.xmin,
878
0
      gbox.ymin,
879
0
      gbox.xmax,
880
0
      gbox.ymax);
881
0
    return NULL;
882
0
  }
883
884
  /* What is the center of our geometry bounds? We'll use that to
885
  ** approximate location. */
886
0
  lon = gbox.xmin + (gbox.xmax - gbox.xmin) / 2;
887
0
  lat = gbox.ymin + (gbox.ymax - gbox.ymin) / 2;
888
889
0
  if (precision <= 0)
890
0
  {
891
0
    precision = lwgeom_geohash_precision(gbox, &gbox_bounds);
892
0
  }
893
0
  else if (precision > 20)
894
0
  {
895
    /* Twenty characters hold the documented full double-precision point. */
896
0
    precision = 20;
897
0
  }
898
899
  /*
900
  ** Return the geohash of the center, with a precision determined by the
901
  ** extent of the bounds.
902
  ** Possible change: return the point at the center of the precision bounds?
903
  */
904
0
  return geohash_point(lon, lat, precision);
905
0
}