Coverage Report

Created: 2026-12-01 06:12

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/postgis/liblwgeom/ptarray.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 (C) 2012-2021 Sandro Santilli <strk@kbt.io>
22
 * Copyright (C) 2001-2006 Refractions Research Inc.
23
 * Copyright (C) 2026 Darafei Praliaskouski <me@komzpa.net>
24
 *
25
 **********************************************************************/
26
27
#include <stdio.h>
28
#include <string.h>
29
#include <stdlib.h>
30
#include <float.h>
31
#include <limits.h>
32
#include <math.h>
33
34
#include "../postgis_config.h"
35
/*#define POSTGIS_DEBUG_LEVEL 4*/
36
#include "liblwgeom_internal.h"
37
#include "lwgeom_log.h"
38
39
0
#define PTARRAY_SIGNED_AREA_EXPANSION_MAX 4096
40
41
typedef struct {
42
  uint32_t nterms;
43
  int overflowed;
44
  double terms[PTARRAY_SIGNED_AREA_EXPANSION_MAX];
45
} ptarray_signed_area_expansion;
46
47
static inline void
48
ptarray_signed_area_add(double *sum, double *compensation, double value)
49
0
{
50
0
  double y, t;
51
52
  /*
53
   * Kahan compensation is only valid in finite arithmetic. When a finite
54
   * ring is so large that the determinant overflows, preserve the IEEE
55
   * infinity instead of manufacturing NaN in the compensation term.
56
   */
57
0
  if (!isfinite(value) || !isfinite(*sum))
58
0
  {
59
0
    *sum += value;
60
0
    *compensation = 0.0;
61
0
    return;
62
0
  }
63
64
0
  y = value - *compensation;
65
0
  t = *sum + y;
66
0
  *compensation = (t - *sum) - y;
67
0
  *sum = t;
68
0
}
69
70
static inline void
71
ptarray_signed_area_add_abs_or_infinite(double *sum, double value)
72
0
{
73
0
  if (isfinite(value))
74
0
    *sum += fabs(value);
75
0
  else
76
0
    *sum = INFINITY;
77
0
}
78
79
/* Error-free transforms require every intermediate to round to double.
80
 * Volatile stores prevent excess x87 precision from discarding residuals. */
81
static inline void
82
ptarray_signed_area_two_sum(double a, double b, double *sum, double *err)
83
0
{
84
0
  volatile double bvirt, avirt, bround, around, rounded;
85
86
0
  rounded = a + b;
87
0
  *sum = rounded;
88
0
  bvirt = rounded - a;
89
0
  avirt = rounded - bvirt;
90
0
  bround = b - bvirt;
91
0
  around = a - avirt;
92
0
  *err = around + bround;
93
0
}
94
95
static inline void
96
ptarray_signed_area_expansion_add(ptarray_signed_area_expansion *expansion, double value)
97
0
{
98
0
  uint32_t i, n = 0;
99
0
  double sum, err;
100
101
0
  if (value == 0.0)
102
0
    return;
103
0
  if (!isfinite(value) || expansion->overflowed)
104
0
  {
105
0
    expansion->overflowed = LW_TRUE;
106
0
    return;
107
0
  }
108
109
0
  for (i = 0; i < expansion->nterms; i++)
110
0
  {
111
0
    ptarray_signed_area_two_sum(value, expansion->terms[i], &sum, &err);
112
0
    if (err != 0.0)
113
0
    {
114
0
      if (n == PTARRAY_SIGNED_AREA_EXPANSION_MAX)
115
0
      {
116
0
        expansion->overflowed = LW_TRUE;
117
0
        return;
118
0
      }
119
0
      expansion->terms[n++] = err;
120
0
    }
121
0
    value = sum;
122
0
  }
123
124
0
  if (value != 0.0)
125
0
  {
126
0
    if (n == PTARRAY_SIGNED_AREA_EXPANSION_MAX)
127
0
    {
128
0
      expansion->overflowed = LW_TRUE;
129
0
      return;
130
0
    }
131
0
    expansion->terms[n++] = value;
132
0
  }
133
0
  expansion->nterms = n;
134
0
}
135
136
static inline void
137
ptarray_signed_area_expansion_add_product(ptarray_signed_area_expansion *expansion, double a, double b, double sign)
138
0
{
139
  /* The fused residual must use the product rounded to double. */
140
0
  volatile double product = a * b;
141
142
0
  ptarray_signed_area_expansion_add(expansion, sign * product);
143
0
  ptarray_signed_area_expansion_add(expansion, sign * fma(a, b, -product));
144
0
}
145
146
static inline double
147
ptarray_signed_area_expansion_sum(ptarray_signed_area_expansion *expansion)
148
0
{
149
0
  double sum = 0.0;
150
0
  double compensation = 0.0;
151
0
  uint32_t i;
152
153
0
  if (expansion->overflowed)
154
0
    return NAN;
155
156
0
  for (i = 0; i < expansion->nterms; i++)
157
0
    ptarray_signed_area_add(&sum, &compensation, expansion->terms[i]);
158
0
  return sum;
159
0
}
160
161
static inline void
162
ptarray_signed_area_two_diff(double a, double b, double *diff, double *err)
163
0
{
164
0
  volatile double bvirt, avirt, bround, around, rounded;
165
166
0
  rounded = a - b;
167
0
  *diff = rounded;
168
0
  bvirt = a - rounded;
169
0
  avirt = rounded + bvirt;
170
0
  bround = bvirt - b;
171
0
  around = a - avirt;
172
0
  *err = around + bround;
173
0
}
174
175
static inline int
176
ptarray_signed_area_product_exponent(double a, double b)
177
0
{
178
0
  int ea, eb;
179
180
0
  if (!isfinite(a) || !isfinite(b))
181
0
    return DBL_MAX_EXP;
182
0
  if (a == 0.0 || b == 0.0)
183
0
    return INT_MIN;
184
185
0
  frexp(fabs(a), &ea);
186
0
  frexp(fabs(b), &eb);
187
0
  return ea + eb;
188
0
}
189
190
static double
191
ptarray_signed_area_exact(const POINTARRAY *pa, int coordinate_scale)
192
0
{
193
0
  const POINT2D *P1 = getPoint2d_cp(pa, 0);
194
0
  const POINT2D *P2 = getPoint2d_cp(pa, 1);
195
0
  const POINT2D *P3;
196
0
  ptarray_signed_area_expansion expansion = {0};
197
0
  double x0 = P1->x;
198
0
  double y0 = P1->y;
199
0
  uint32_t i;
200
201
0
  for (i = 2; i < pa->npoints; i++)
202
0
  {
203
0
    double ax, ay, bx, by, axerr, ayerr, bxerr, byerr;
204
0
    P3 = getPoint2d_cp(pa, i);
205
206
0
    ptarray_signed_area_two_diff(P2->x, x0, &ax, &axerr);
207
0
    ptarray_signed_area_two_diff(P2->y, y0, &ay, &ayerr);
208
0
    ptarray_signed_area_two_diff(P3->x, x0, &bx, &bxerr);
209
0
    ptarray_signed_area_two_diff(P3->y, y0, &by, &byerr);
210
0
    if (coordinate_scale > 0)
211
0
    {
212
0
      ax = ldexp(ax, -coordinate_scale);
213
0
      ay = ldexp(ay, -coordinate_scale);
214
0
      bx = ldexp(bx, -coordinate_scale);
215
0
      by = ldexp(by, -coordinate_scale);
216
0
      axerr = ldexp(axerr, -coordinate_scale);
217
0
      ayerr = ldexp(ayerr, -coordinate_scale);
218
0
      bxerr = ldexp(bxerr, -coordinate_scale);
219
0
      byerr = ldexp(byerr, -coordinate_scale);
220
0
    }
221
222
0
    ptarray_signed_area_expansion_add_product(&expansion, ax, by, 1.0);
223
0
    ptarray_signed_area_expansion_add_product(&expansion, ax, byerr, 1.0);
224
0
    ptarray_signed_area_expansion_add_product(&expansion, axerr, by, 1.0);
225
0
    ptarray_signed_area_expansion_add_product(&expansion, axerr, byerr, 1.0);
226
0
    ptarray_signed_area_expansion_add_product(&expansion, ay, bx, -1.0);
227
0
    ptarray_signed_area_expansion_add_product(&expansion, ay, bxerr, -1.0);
228
0
    ptarray_signed_area_expansion_add_product(&expansion, ayerr, bx, -1.0);
229
0
    ptarray_signed_area_expansion_add_product(&expansion, ayerr, bxerr, -1.0);
230
231
0
    P2 = P3;
232
0
  }
233
234
0
  return -ldexp(ptarray_signed_area_expansion_sum(&expansion), 2 * coordinate_scale) / 2.0;
235
0
}
236
237
int
238
ptarray_has_z(const POINTARRAY *pa)
239
0
{
240
0
  if (!pa)
241
0
    return LW_FALSE;
242
0
  return FLAGS_GET_Z(pa->flags);
243
0
}
244
245
int
246
ptarray_has_m(const POINTARRAY *pa)
247
0
{
248
0
  if (!pa)
249
0
    return LW_FALSE;
250
0
  return FLAGS_GET_M(pa->flags);
251
0
}
252
253
POINTARRAY *
254
ptarray_construct(char hasz, char hasm, uint32_t npoints)
255
0
{
256
0
  POINTARRAY *pa = ptarray_construct_empty(hasz, hasm, npoints);
257
0
  pa->npoints = npoints;
258
0
  return pa;
259
0
}
260
261
POINTARRAY *
262
ptarray_construct_empty(char hasz, char hasm, uint32_t maxpoints)
263
0
{
264
0
  POINTARRAY *pa = lwalloc(sizeof(POINTARRAY));
265
0
  pa->serialized_pointlist = NULL;
266
267
  /* Set our dimensionality info on the bitmap */
268
0
  pa->flags = lwflags(hasz, hasm, 0);
269
270
  /* We will be allocating a bit of room */
271
0
  pa->npoints = 0;
272
0
  pa->maxpoints = maxpoints;
273
274
  /* Allocate the coordinate array */
275
0
  if (maxpoints > 0)
276
0
    pa->serialized_pointlist = lwalloc(maxpoints * ptarray_point_size(pa));
277
0
  else
278
0
    pa->serialized_pointlist = NULL;
279
280
0
  return pa;
281
0
}
282
283
/*
284
 * Add a point into a pointarray. Only adds as many dimensions as the
285
 * pointarray supports.
286
 */
287
int
288
ptarray_insert_point(POINTARRAY *pa, const POINT4D *p, uint32_t where)
289
0
{
290
0
  if (!pa || !p)
291
0
    return LW_FAILURE;
292
0
  size_t point_size = ptarray_point_size(pa);
293
0
  LWDEBUGF(5, "pa = %p; p = %p; where = %d", pa, p, where);
294
0
  LWDEBUGF(5, "pa->npoints = %d; pa->maxpoints = %d", pa->npoints, pa->maxpoints);
295
296
0
  if (FLAGS_GET_READONLY(pa->flags))
297
0
  {
298
0
    lwerror("ptarray_insert_point: called on read-only point array");
299
0
    return LW_FAILURE;
300
0
  }
301
302
  /* Error on invalid offset value */
303
0
  if (where > pa->npoints)
304
0
  {
305
0
    lwerror("ptarray_insert_point: offset out of range (%d)", where);
306
0
    return LW_FAILURE;
307
0
  }
308
309
  /* If we have no storage, let's allocate some */
310
0
  if (pa->maxpoints == 0 || !pa->serialized_pointlist)
311
0
  {
312
0
    pa->maxpoints = 32;
313
0
    pa->npoints = 0;
314
0
    pa->serialized_pointlist = lwalloc(ptarray_point_size(pa) * pa->maxpoints);
315
0
  }
316
317
  /* Error out if we have a bad situation */
318
0
  if (pa->npoints > pa->maxpoints)
319
0
  {
320
0
    lwerror("npoints (%d) is greater than maxpoints (%d)", pa->npoints, pa->maxpoints);
321
0
    return LW_FAILURE;
322
0
  }
323
324
  /* Check if we have enough storage, add more if necessary */
325
0
  if (pa->npoints == pa->maxpoints)
326
0
  {
327
0
    pa->maxpoints *= 2;
328
0
    pa->serialized_pointlist = lwrealloc(pa->serialized_pointlist, ptarray_point_size(pa) * pa->maxpoints);
329
0
  }
330
331
  /* Make space to insert the new point */
332
0
  if (where < pa->npoints)
333
0
  {
334
0
    size_t copy_size = point_size * (pa->npoints - where);
335
0
    memmove(getPoint_internal(pa, where + 1), getPoint_internal(pa, where), copy_size);
336
0
    LWDEBUGF(5, "copying %zu bytes to start vertex %d from start vertex %d", copy_size, where + 1, where);
337
0
  }
338
339
  /* We have one more point */
340
0
  ++pa->npoints;
341
342
  /* Copy the new point into the gap */
343
0
  ptarray_set_point4d(pa, where, p);
344
0
  LWDEBUGF(5, "copying new point to start vertex %zu", point_size);
345
346
0
  return LW_SUCCESS;
347
0
}
348
349
int
350
ptarray_append_point(POINTARRAY *pa, const POINT4D *pt, int repeated_points)
351
0
{
352
  /* Check for pathology */
353
0
  if (!pa || !pt)
354
0
  {
355
0
    lwerror("ptarray_append_point: null input");
356
0
    return LW_FAILURE;
357
0
  }
358
359
  /* Check for duplicate end point */
360
0
  if (repeated_points == LW_FALSE && pa->npoints > 0)
361
0
  {
362
0
    POINT4D tmp;
363
0
    getPoint4d_p(pa, pa->npoints - 1, &tmp);
364
0
    LWDEBUGF(4,
365
0
       "checking for duplicate end point (pt = POINT(%g %g) pa->npoints-q = POINT(%g %g))",
366
0
       pt->x,
367
0
       pt->y,
368
0
       tmp.x,
369
0
       tmp.y);
370
371
    /* Return LW_SUCCESS and do nothing else if previous point in list is equal to this one */
372
0
    if ((pt->x == tmp.x) && (pt->y == tmp.y) && (FLAGS_GET_Z(pa->flags) ? pt->z == tmp.z : 1) &&
373
0
        (FLAGS_GET_M(pa->flags) ? pt->m == tmp.m : 1))
374
0
    {
375
0
      return LW_SUCCESS;
376
0
    }
377
0
  }
378
379
  /* Append is just a special case of insert */
380
0
  return ptarray_insert_point(pa, pt, pa->npoints);
381
0
}
382
383
int
384
ptarray_append_ptarray(POINTARRAY *pa1, POINTARRAY *pa2, double gap_tolerance)
385
0
{
386
0
  unsigned int poff = 0;
387
0
  unsigned int npoints;
388
0
  unsigned int ncap;
389
0
  unsigned int ptsize;
390
391
  /* Check for pathology */
392
0
  if (!pa1 || !pa2)
393
0
  {
394
0
    lwerror("%s: null input", __func__);
395
0
    return LW_FAILURE;
396
0
  }
397
398
0
  npoints = pa2->npoints;
399
400
0
  if (!npoints)
401
0
    return LW_SUCCESS; /* nothing more to do */
402
403
0
  if (FLAGS_GET_READONLY(pa1->flags))
404
0
  {
405
0
    lwerror("%s: target pointarray is read-only", __func__);
406
0
    return LW_FAILURE;
407
0
  }
408
409
0
  if (FLAGS_GET_ZM(pa1->flags) != FLAGS_GET_ZM(pa2->flags))
410
0
  {
411
0
    lwerror("%s: appending mixed dimensionality is not allowed", __func__);
412
0
    return LW_FAILURE;
413
0
  }
414
415
0
  ptsize = ptarray_point_size(pa1);
416
417
  /* Check for duplicate end point */
418
0
  if (pa1->npoints)
419
0
  {
420
0
    const POINT2D *tmp1, *tmp2;
421
0
    tmp1 = getPoint2d_cp(pa1, pa1->npoints - 1);
422
0
    tmp2 = getPoint2d_cp(pa2, 0);
423
424
    /* If the end point and start point are the same, then don't copy start point */
425
0
    if (p2d_same(tmp1, tmp2))
426
0
    {
427
0
      poff = 1;
428
0
      --npoints;
429
0
    }
430
0
    else if ((gap_tolerance == 0) || (gap_tolerance > 0 && distance2d_pt_pt(tmp1, tmp2) > gap_tolerance))
431
0
    {
432
0
      lwerror("Second line start point too far from first line end point");
433
0
      return LW_FAILURE;
434
0
    }
435
0
  }
436
437
  /* Check if we need extra space */
438
0
  ncap = pa1->npoints + npoints;
439
0
  if (pa1->maxpoints < ncap)
440
0
  {
441
0
    if (pa1->maxpoints)
442
0
    {
443
0
      pa1->maxpoints = ncap > pa1->maxpoints * 2 ? ncap : pa1->maxpoints * 2;
444
0
      pa1->serialized_pointlist =
445
0
          lwrealloc(pa1->serialized_pointlist, (size_t)ptsize * pa1->maxpoints);
446
0
    }
447
0
    else
448
0
    {
449
0
      pa1->maxpoints = ncap;
450
0
      pa1->serialized_pointlist = lwalloc((size_t)ptsize * pa1->maxpoints);
451
0
    }
452
0
  }
453
454
0
  memcpy(getPoint_internal(pa1, pa1->npoints), getPoint_internal(pa2, poff), (size_t)ptsize * npoints);
455
456
0
  pa1->npoints = ncap;
457
458
0
  return LW_SUCCESS;
459
0
}
460
461
/*
462
 * Add a point into a pointarray. Only adds as many dimensions as the
463
 * pointarray supports.
464
 */
465
int
466
ptarray_remove_point(POINTARRAY *pa, uint32_t where)
467
0
{
468
  /* Check for pathology */
469
0
  if (!pa)
470
0
  {
471
0
    lwerror("ptarray_remove_point: null input");
472
0
    return LW_FAILURE;
473
0
  }
474
475
  /* Error on invalid offset value */
476
0
  if (where >= pa->npoints)
477
0
  {
478
0
    lwerror("ptarray_remove_point: offset out of range (%d)", where);
479
0
    return LW_FAILURE;
480
0
  }
481
482
  /* If the point is any but the last, we need to copy the data back one point */
483
0
  if (where < pa->npoints - 1)
484
0
    memmove(getPoint_internal(pa, where),
485
0
      getPoint_internal(pa, where + 1),
486
0
      ptarray_point_size(pa) * (pa->npoints - where - 1));
487
488
  /* We have one less point */
489
0
  pa->npoints--;
490
491
0
  return LW_SUCCESS;
492
0
}
493
494
/**
495
 * Build a new #POINTARRAY, but on top of someone else's ordinate array.
496
 * Flag as read-only, so that ptarray_free() does not free the serialized_ptlist
497
 */
498
POINTARRAY *
499
ptarray_construct_reference_data(char hasz, char hasm, uint32_t npoints, uint8_t *ptlist)
500
0
{
501
0
  POINTARRAY *pa = lwalloc(sizeof(POINTARRAY));
502
0
  LWDEBUGF(5, "hasz = %d, hasm = %d, npoints = %d, ptlist = %p", hasz, hasm, npoints, ptlist);
503
0
  pa->flags = lwflags(hasz, hasm, 0);
504
0
  FLAGS_SET_READONLY(pa->flags, 1); /* We don't own this memory, so we can't alter or free it. */
505
0
  pa->npoints = npoints;
506
0
  pa->maxpoints = npoints;
507
0
  pa->serialized_pointlist = ptlist;
508
0
  return pa;
509
0
}
510
511
POINTARRAY *
512
ptarray_construct_copy_data(char hasz, char hasm, uint32_t npoints, const uint8_t *ptlist)
513
0
{
514
0
  POINTARRAY *pa = lwalloc(sizeof(POINTARRAY));
515
516
0
  pa->flags = lwflags(hasz, hasm, 0);
517
0
  pa->npoints = npoints;
518
0
  pa->maxpoints = npoints;
519
520
0
  if (npoints > 0)
521
0
  {
522
0
    pa->serialized_pointlist = lwalloc(ptarray_point_size(pa) * npoints);
523
0
    memcpy(pa->serialized_pointlist, ptlist, ptarray_point_size(pa) * npoints);
524
0
  }
525
0
  else
526
0
  {
527
0
    pa->serialized_pointlist = NULL;
528
0
  }
529
530
0
  return pa;
531
0
}
532
533
void
534
ptarray_free(POINTARRAY *pa)
535
0
{
536
0
  if (pa)
537
0
  {
538
0
    if (pa->serialized_pointlist && (!FLAGS_GET_READONLY(pa->flags)))
539
0
      lwfree(pa->serialized_pointlist);
540
0
    lwfree(pa);
541
0
  }
542
0
}
543
544
void
545
ptarray_reverse_in_place(POINTARRAY *pa)
546
0
{
547
0
  if (!pa->npoints)
548
0
    return;
549
0
  uint32_t i;
550
0
  uint32_t last = pa->npoints - 1;
551
0
  uint32_t mid = pa->npoints / 2;
552
553
0
  double *d = (double *)(pa->serialized_pointlist);
554
0
  int j;
555
0
  int ndims = FLAGS_NDIMS(pa->flags);
556
0
  for (i = 0; i < mid; i++)
557
0
  {
558
0
    for (j = 0; j < ndims; j++)
559
0
    {
560
0
      double buf;
561
0
      buf = d[i * ndims + j];
562
0
      d[i * ndims + j] = d[(last - i) * ndims + j];
563
0
      d[(last - i) * ndims + j] = buf;
564
0
    }
565
0
  }
566
0
  return;
567
0
}
568
569
/**
570
 * Reverse X and Y axis on a given POINTARRAY
571
 */
572
POINTARRAY *
573
ptarray_flip_coordinates(POINTARRAY *pa)
574
0
{
575
0
  uint32_t i;
576
0
  double d;
577
0
  POINT4D p;
578
579
0
  for (i = 0; i < pa->npoints; i++)
580
0
  {
581
0
    getPoint4d_p(pa, i, &p);
582
0
    d = p.y;
583
0
    p.y = p.x;
584
0
    p.x = d;
585
0
    ptarray_set_point4d(pa, i, &p);
586
0
  }
587
588
0
  return pa;
589
0
}
590
591
void
592
ptarray_swap_ordinates(POINTARRAY *pa, LWORD o1, LWORD o2)
593
0
{
594
0
  uint32_t i;
595
0
  double d, *dp1, *dp2;
596
0
  POINT4D p;
597
598
0
  dp1 = ((double *)&p) + (unsigned)o1;
599
0
  dp2 = ((double *)&p) + (unsigned)o2;
600
0
  for (i = 0; i < pa->npoints; i++)
601
0
  {
602
0
    getPoint4d_p(pa, i, &p);
603
0
    d = *dp2;
604
0
    *dp2 = *dp1;
605
0
    *dp1 = d;
606
0
    ptarray_set_point4d(pa, i, &p);
607
0
  }
608
0
}
609
610
/**
611
 * @brief Returns a modified #POINTARRAY so that no segment is
612
 *    longer than the given distance (computed using 2d).
613
 *
614
 * Every input point is kept.
615
 * Z and M values for added points (if needed) are set proportionally.
616
 */
617
POINTARRAY *
618
ptarray_segmentize2d(const POINTARRAY *ipa, double dist)
619
0
{
620
0
  double segdist;
621
0
  POINT4D p1, p2;
622
0
  POINT4D pbuf;
623
0
  POINTARRAY *opa;
624
0
  uint32_t i, j, nseg;
625
0
  int hasz = FLAGS_GET_Z(ipa->flags);
626
0
  int hasm = FLAGS_GET_M(ipa->flags);
627
628
0
  pbuf.x = pbuf.y = pbuf.z = pbuf.m = 0;
629
630
  /* Initial storage */
631
0
  opa = ptarray_construct_empty(hasz, hasm, ipa->npoints);
632
633
  /* Add first point */
634
0
  getPoint4d_p(ipa, 0, &p1);
635
0
  ptarray_append_point(opa, &p1, LW_FALSE);
636
637
  /* Loop on all other input points */
638
0
  for (i = 1; i < ipa->npoints; i++)
639
0
  {
640
    /*
641
     * We use these pointers to avoid
642
     * "strict-aliasing rules break" warning raised
643
     * by gcc (3.3 and up).
644
     *
645
     * It looks that casting a variable address (also
646
     * referred to as "type-punned pointer")
647
     * breaks those "strict" rules.
648
     */
649
0
    POINT4D *p1ptr = &p1, *p2ptr = &p2;
650
0
    double segments;
651
652
0
    getPoint4d_p(ipa, i, &p2);
653
654
0
    segdist = distance2d_pt_pt((POINT2D *)p1ptr, (POINT2D *)p2ptr);
655
    /* Split input segment into shorter even chunks */
656
0
    segments = ceil(segdist / dist);
657
658
    /* Uses INT32_MAX instead of UINT32_MAX to be safe that it fits */
659
0
    if (segments >= INT32_MAX)
660
0
    {
661
0
      lwnotice("%s:%d - %s: Too many segments required (%e)", __FILE__, __LINE__, __func__, segments);
662
0
      ptarray_free(opa);
663
0
      return NULL;
664
0
    }
665
0
    nseg = segments;
666
667
0
    for (j = 1; j < nseg; j++)
668
0
    {
669
0
      pbuf.x = p1.x + (p2.x - p1.x) * j / nseg;
670
0
      pbuf.y = p1.y + (p2.y - p1.y) * j / nseg;
671
0
      if (hasz)
672
0
        pbuf.z = p1.z + (p2.z - p1.z) * j / nseg;
673
0
      if (hasm)
674
0
        pbuf.m = p1.m + (p2.m - p1.m) * j / nseg;
675
0
      ptarray_append_point(opa, &pbuf, LW_FALSE);
676
0
      LW_ON_INTERRUPT(ptarray_free(opa); return NULL);
677
0
    }
678
679
0
    ptarray_append_point(opa, &p2, (ipa->npoints == 2) ? LW_TRUE : LW_FALSE);
680
0
    p1 = p2;
681
0
    LW_ON_INTERRUPT(ptarray_free(opa); return NULL);
682
0
  }
683
684
0
  return opa;
685
0
}
686
687
char
688
ptarray_same(const POINTARRAY *pa1, const POINTARRAY *pa2)
689
0
{
690
0
  uint32_t i;
691
0
  size_t ptsize;
692
693
0
  if (FLAGS_GET_ZM(pa1->flags) != FLAGS_GET_ZM(pa2->flags))
694
0
    return LW_FALSE;
695
0
  LWDEBUG(5, "dimensions are the same");
696
697
0
  if (pa1->npoints != pa2->npoints)
698
0
    return LW_FALSE;
699
0
  LWDEBUG(5, "npoints are the same");
700
701
0
  ptsize = ptarray_point_size(pa1);
702
0
  LWDEBUGF(5, "ptsize = %zu", ptsize);
703
704
0
  for (i = 0; i < pa1->npoints; i++)
705
0
  {
706
0
    if (memcmp(getPoint_internal(pa1, i), getPoint_internal(pa2, i), ptsize))
707
0
      return LW_FALSE;
708
0
    LWDEBUGF(5, "point #%d is the same", i);
709
0
  }
710
711
0
  return LW_TRUE;
712
0
}
713
714
char
715
ptarray_same2d(const POINTARRAY *pa1, const POINTARRAY *pa2)
716
0
{
717
0
  uint32_t i;
718
719
0
  if (FLAGS_GET_ZM(pa1->flags) != FLAGS_GET_ZM(pa2->flags))
720
0
    return LW_FALSE;
721
0
  LWDEBUG(5, "dimensions are the same");
722
723
0
  if (pa1->npoints != pa2->npoints)
724
0
    return LW_FALSE;
725
0
  LWDEBUG(5, "npoints are the same");
726
727
0
  for (i = 0; i < pa1->npoints; i++)
728
0
  {
729
0
    if (memcmp(getPoint_internal(pa1, i), getPoint_internal(pa2, i), sizeof(POINT2D)))
730
0
      return LW_FALSE;
731
0
    LWDEBUGF(5, "point #%d is the same", i);
732
0
  }
733
734
0
  return LW_TRUE;
735
0
}
736
737
POINTARRAY *
738
ptarray_addPoint(const POINTARRAY *pa, uint8_t *p, size_t pdims, uint32_t where)
739
0
{
740
0
  POINTARRAY *ret;
741
0
  POINT4D pbuf;
742
0
  size_t ptsize = ptarray_point_size(pa);
743
744
0
  LWDEBUGF(3, "pa %p p %p size %lu where %u", pa, p, (unsigned long)pdims, where);
745
746
0
  if (pdims < 2 || pdims > 4)
747
0
  {
748
0
    lwerror("ptarray_addPoint: point dimension out of range (%lu)", (unsigned long)pdims);
749
0
    return NULL;
750
0
  }
751
752
0
  if (where > pa->npoints)
753
0
  {
754
0
    lwerror("ptarray_addPoint: offset out of range (%d)", where);
755
0
    return NULL;
756
0
  }
757
758
0
  LWDEBUG(3, "called with a point");
759
760
0
  pbuf.x = pbuf.y = pbuf.z = pbuf.m = 0.0;
761
0
  memcpy((uint8_t *)&pbuf, p, pdims * sizeof(double));
762
763
0
  LWDEBUG(3, "initialized point buffer");
764
765
0
  ret = ptarray_construct(FLAGS_GET_Z(pa->flags), FLAGS_GET_M(pa->flags), pa->npoints + 1);
766
767
0
  if (where)
768
0
  {
769
0
    memcpy(getPoint_internal(ret, 0), getPoint_internal(pa, 0), ptsize * where);
770
0
  }
771
772
0
  memcpy(getPoint_internal(ret, where), (uint8_t *)&pbuf, ptsize);
773
774
0
  if (where + 1 != ret->npoints)
775
0
  {
776
0
    memcpy(getPoint_internal(ret, where + 1), getPoint_internal(pa, where), ptsize * (pa->npoints - where));
777
0
  }
778
779
0
  return ret;
780
0
}
781
782
POINTARRAY *
783
ptarray_removePoint(POINTARRAY *pa, uint32_t which)
784
0
{
785
0
  POINTARRAY *ret;
786
0
  size_t ptsize = ptarray_point_size(pa);
787
788
0
  LWDEBUGF(3, "pa %p which %u", pa, which);
789
790
0
  assert(which <= pa->npoints - 1);
791
0
  assert(pa->npoints >= 3);
792
793
0
  ret = ptarray_construct(FLAGS_GET_Z(pa->flags), FLAGS_GET_M(pa->flags), pa->npoints - 1);
794
795
  /* copy initial part */
796
0
  if (which)
797
0
  {
798
0
    memcpy(getPoint_internal(ret, 0), getPoint_internal(pa, 0), ptsize * which);
799
0
  }
800
801
  /* copy final part */
802
0
  if (which < pa->npoints - 1)
803
0
  {
804
0
    memcpy(getPoint_internal(ret, which),
805
0
           getPoint_internal(pa, which + 1),
806
0
           ptsize * (pa->npoints - which - 1));
807
0
  }
808
809
0
  return ret;
810
0
}
811
812
POINTARRAY *
813
ptarray_merge(POINTARRAY *pa1, POINTARRAY *pa2)
814
0
{
815
0
  POINTARRAY *pa;
816
0
  size_t ptsize = ptarray_point_size(pa1);
817
818
0
  if (FLAGS_GET_ZM(pa1->flags) != FLAGS_GET_ZM(pa2->flags))
819
0
    lwerror("ptarray_cat: Mixed dimension");
820
821
0
  pa = ptarray_construct(FLAGS_GET_Z(pa1->flags), FLAGS_GET_M(pa1->flags), pa1->npoints + pa2->npoints);
822
823
0
  memcpy(getPoint_internal(pa, 0), getPoint_internal(pa1, 0), ptsize * (pa1->npoints));
824
825
0
  memcpy(getPoint_internal(pa, pa1->npoints), getPoint_internal(pa2, 0), ptsize * (pa2->npoints));
826
827
0
  ptarray_free(pa1);
828
0
  ptarray_free(pa2);
829
830
0
  return pa;
831
0
}
832
833
/**
834
 * @brief Deep clone a pointarray (also clones serialized pointlist)
835
 */
836
POINTARRAY *
837
ptarray_clone_deep(const POINTARRAY *in)
838
0
{
839
0
  POINTARRAY *out = lwalloc(sizeof(POINTARRAY));
840
841
0
  LWDEBUG(3, "ptarray_clone_deep called.");
842
843
0
  out->flags = in->flags;
844
0
  out->npoints = in->npoints;
845
0
  out->maxpoints = in->npoints;
846
847
0
  FLAGS_SET_READONLY(out->flags, 0);
848
849
0
  if (!in->npoints)
850
0
  {
851
    // Avoid calling lwalloc of 0 bytes
852
0
    out->serialized_pointlist = NULL;
853
0
  }
854
0
  else
855
0
  {
856
0
    size_t size = in->npoints * ptarray_point_size(in);
857
0
    out->serialized_pointlist = lwalloc(size);
858
0
    memcpy(out->serialized_pointlist, in->serialized_pointlist, size);
859
0
  }
860
861
0
  return out;
862
0
}
863
864
/**
865
 * @brief Clone a POINTARRAY object. Serialized pointlist is not copied.
866
 */
867
POINTARRAY *
868
ptarray_clone(const POINTARRAY *in)
869
0
{
870
0
  POINTARRAY *out = lwalloc(sizeof(POINTARRAY));
871
872
0
  LWDEBUG(3, "ptarray_clone called.");
873
874
0
  out->flags = in->flags;
875
0
  out->npoints = in->npoints;
876
0
  out->maxpoints = in->maxpoints;
877
878
0
  FLAGS_SET_READONLY(out->flags, 1);
879
880
0
  out->serialized_pointlist = in->serialized_pointlist;
881
882
0
  return out;
883
0
}
884
885
/**
886
 * Check for ring closure using whatever dimensionality is declared on the
887
 * pointarray.
888
 */
889
int
890
ptarray_is_closed(const POINTARRAY *in)
891
0
{
892
0
  if (!in)
893
0
  {
894
0
    lwerror("ptarray_is_closed: called with null point array");
895
0
    return 0;
896
0
  }
897
0
  if (in->npoints <= 1)
898
0
    return in->npoints; /* single-point are closed, empty not closed */
899
900
0
  return 0 == memcmp(getPoint_internal(in, 0), getPoint_internal(in, in->npoints - 1), ptarray_point_size(in));
901
0
}
902
903
int
904
ptarray_is_closed_2d(const POINTARRAY *in)
905
0
{
906
0
  if (!in)
907
0
  {
908
0
    lwerror("ptarray_is_closed_2d: called with null point array");
909
0
    return 0;
910
0
  }
911
0
  if (in->npoints <= 1)
912
0
    return in->npoints; /* single-point are closed, empty not closed */
913
914
0
  return 0 == memcmp(getPoint_internal(in, 0), getPoint_internal(in, in->npoints - 1), sizeof(POINT2D));
915
0
}
916
917
int
918
ptarray_is_closed_3d(const POINTARRAY *in)
919
0
{
920
0
  if (!in)
921
0
  {
922
0
    lwerror("ptarray_is_closed_3d: called with null point array");
923
0
    return 0;
924
0
  }
925
0
  if (in->npoints <= 1)
926
0
    return in->npoints; /* single-point are closed, empty not closed */
927
928
0
  return 0 == memcmp(getPoint_internal(in, 0), getPoint_internal(in, in->npoints - 1), sizeof(POINT3D));
929
0
}
930
931
int
932
ptarray_is_closed_z(const POINTARRAY *in)
933
0
{
934
0
  if (FLAGS_GET_Z(in->flags))
935
0
    return ptarray_is_closed_3d(in);
936
0
  else
937
0
    return ptarray_is_closed_2d(in);
938
0
}
939
940
/**
941
 * The following is based on the "Fast Winding Number Inclusion of a Point
942
 * in a Polygon" algorithm by Dan Sunday.
943
 * http://softsurfer.com/Archive/algorithm_0103/algorithm_0103.htm#Winding%20Number
944
 *
945
 * Return:
946
 *  - LW_INSIDE (1) if the point is inside the POINTARRAY
947
 *  - LW_BOUNDARY (0) if it is on the boundary.
948
 *  - LW_OUTSIDE (-1) if it is outside
949
 */
950
int
951
ptarray_contains_point(const POINTARRAY *pa, const POINT2D *pt)
952
0
{
953
0
  int wn = 0;
954
0
  return ptarray_contains_point_partial(pa, pt, LW_TRUE, &wn);
955
0
}
956
957
int
958
ptarray_raycast_intersections(const POINTARRAY *pa, const POINT2D *p, int *on_boundary)
959
0
{
960
  // A valid linestring must have at least 2 point
961
0
  if (pa->npoints < 2)
962
0
    lwerror("%s called on invalid linestring", __func__);
963
964
0
  int intersections = 0;
965
0
  double px = p->x;
966
0
  double py = p->y;
967
968
  // Iterate through each edge of the polygon
969
0
  for (uint32_t i = 0; i < pa->npoints - 1; ++i)
970
0
  {
971
0
    const POINT2D *p1 = getPoint2d_cp(pa, i);
972
0
    const POINT2D *p2 = getPoint2d_cp(pa, i + 1);
973
974
    /* Skip zero-length edges */
975
0
    if (p2d_same(p1, p2))
976
0
      continue;
977
978
    /* --- Step 1: Check if the point is ON the boundary edge --- */
979
0
    if (lw_pt_on_segment(p1, p2, p))
980
0
    {
981
0
      *on_boundary = LW_TRUE;
982
0
      return 0;
983
0
    }
984
985
    /* --- Step 2: Perform the Ray Casting intersection test --- */
986
987
    /*
988
     * Check if the horizontal ray from p intersects the edge (p1, p2).
989
     * This is the core condition for handling vertices correctly:
990
     *   - One vertex must be strictly above the ray (py < vertex.y)
991
     *   - The other must be on or below the ray (py >= vertex.y)
992
     */
993
0
    if (((p1->y <= py) && (py < p2->y)) || ((p2->y <= py) && (py < p1->y)))
994
0
    {
995
      /*
996
       * Calculate the x-coordinate where the edge intersects the ray's horizontal line.
997
       * Formula: x = x1 + (y - y1) * (x2 - x1) / (y2 - y1)
998
       */
999
0
      double x_intersection = p1->x + (py - p1->y) * (p2->x - p1->x) / (p2->y - p1->y);
1000
1001
      /*
1002
       * If the intersection point is to the right of our test point,
1003
       * it's a valid "crossing".
1004
       */
1005
0
      if (x_intersection > px)
1006
0
      {
1007
0
        intersections++;
1008
0
      }
1009
0
    }
1010
0
  }
1011
1012
0
  return intersections;
1013
0
}
1014
1015
/**
1016
 * @brief Calculates the intersection points of a circle and a horizontal line.
1017
 *
1018
 * The equation of a circle is (x - cx)^2 + (y - cy)^2 = r^2.
1019
 * The equation of the horizontal line is y = y_line.
1020
 * Substituting y_line into the circle equation gives:
1021
 * (x - cx)^2 = r^2 - (y_line - cy)^2
1022
 * This function solves for x.
1023
 *
1024
 * @param center A pointer to the center point of the circle.
1025
 * @param radius The radius of the circle.
1026
 * @param ray The y-coordinate of the horizontal line.
1027
 * @param i0 A pointer to a POINT2D to store the first intersection point.
1028
 * @param i1 A pointer to a POINT2D to store the second intersection point.
1029
 *
1030
 * @return The number of intersection points found (0, 1, or 2).
1031
 */
1032
static int
1033
circle_raycast_intersections(const POINT2D *center, double radius, double ray, POINT2D *i0, POINT2D *i1)
1034
0
{
1035
  // Calculate the vertical distance from the circle's center to the horizontal line.
1036
0
  double dy = ray - center->y;
1037
1038
  // If the absolute vertical distance is greater than the radius, there are no intersections.
1039
0
  if (fabs(dy) > radius)
1040
0
    return 0;
1041
1042
  // Use the Pythagorean theorem to find the horizontal distance (dx) from the
1043
  // center's x-coordinate to the intersection points.
1044
  // dx^2 + dy^2 = radius^2  =>  dx^2 = radius^2 - dy^2
1045
0
  double dx_squared = radius * radius - dy * dy;
1046
1047
  // Case 1: One intersection (tangent)
1048
  // This occurs when the line just touches the top or bottom of the circle.
1049
  // dx_squared will be zero. We check against a small epsilon for floating-point safety.
1050
0
  if (FP_EQUALS(dx_squared, 0.0))
1051
0
  {
1052
0
    i0->x = center->x;
1053
0
    i0->y = ray;
1054
0
    return 1;
1055
0
  }
1056
1057
  // Case 2: Two intersections
1058
  // The line cuts through the circle.
1059
0
  double dx = sqrt(dx_squared);
1060
1061
  // The first intersection point has the smaller x-value.
1062
0
  i0->x = center->x - dx;
1063
0
  i0->y = ray;
1064
1065
  // The second intersection point has the larger x-value.
1066
0
  i1->x = center->x + dx;
1067
0
  i1->y = ray;
1068
1069
0
  return 2;
1070
0
}
1071
1072
int
1073
ptarrayarc_raycast_intersections(const POINTARRAY *pa, const POINT2D *p, int *on_boundary)
1074
0
{
1075
0
  int intersections = 0;
1076
0
  double px = p->x;
1077
0
  double py = p->y;
1078
1079
0
  assert(on_boundary);
1080
1081
  // A valid circular arc must have at least 3 vertices (circle).
1082
0
  if (pa->npoints < 3)
1083
0
    lwerror("%s called on invalid circularstring", __func__);
1084
1085
0
  if (pa->npoints % 2 == 0)
1086
0
    lwerror("%s called with even number of points", __func__);
1087
1088
  // Iterate through each arc of the circularstring
1089
0
  for (uint32_t i = 1; i < pa->npoints - 1; i += 2)
1090
0
  {
1091
0
    const POINT2D *p0 = getPoint2d_cp(pa, i - 1);
1092
0
    const POINT2D *p1 = getPoint2d_cp(pa, i);
1093
0
    const POINT2D *p2 = getPoint2d_cp(pa, i + 1);
1094
0
    POINT2D center = {0, 0};
1095
0
    double radius, d;
1096
0
    GBOX gbox;
1097
1098
    // Skip zero-length arc
1099
0
    if (lw_arc_is_pt(p0, p1, p2))
1100
0
      continue;
1101
1102
    // --- Step 1: Check if the point is ON the boundary edge ---
1103
0
    if (p2d_same(p0, p) || p2d_same(p1, p) || p2d_same(p2, p))
1104
0
    {
1105
0
      *on_boundary = LW_TRUE;
1106
0
      return 0;
1107
0
    }
1108
1109
    // Calculate some important pieces
1110
0
    radius = lw_arc_center(p0, p1, p2, &center);
1111
1112
0
    d = distance2d_pt_pt(p, &center);
1113
0
    if (FP_EQUALS(d, radius) && lw_pt_in_arc(p, p0, p1, p2))
1114
0
    {
1115
0
      *on_boundary = LW_TRUE;
1116
0
      return 0;
1117
0
    }
1118
1119
    // --- Step 2: Perform the Ray Casting intersection test ---
1120
1121
    // Only process arcs that our ray crosses
1122
0
    lw_arc_calculate_gbox_cartesian_2d(p0, p1, p2, &gbox);
1123
0
    if ((gbox.ymin <= py) && (py < gbox.ymax))
1124
0
    {
1125
      // Point of intersection on the circle that defines the arc
1126
0
      POINT2D i0, i1;
1127
1128
      // How many points of intersection are there
1129
0
      int iCount = circle_raycast_intersections(&center, radius, py, &i0, &i1);
1130
1131
      // Nothing to see here
1132
0
      if (iCount == 0)
1133
0
        continue;
1134
1135
      // Cannot think of a case where a grazing is not a
1136
      // no-op
1137
0
      if (iCount == 1)
1138
0
        continue;
1139
1140
      // So we must have 2 intersections
1141
      // Only increment the counter for intersections to the right
1142
      // of the test point
1143
0
      if (i0.x > px && lw_pt_in_arc(&i0, p0, p1, p2))
1144
0
        intersections++;
1145
1146
0
      if (i1.x > px && lw_pt_in_arc(&i1, p0, p1, p2))
1147
0
        intersections++;
1148
0
    }
1149
0
  }
1150
1151
0
  return intersections;
1152
0
}
1153
1154
/*
1155
 * The following is based on the "Fast Winding Number Inclusion of a Point
1156
 * in a Polygon" algorithm by Dan Sunday.
1157
 * http://softsurfer.com/Archive/algorithm_0103/algorithm_0103.htm#Winding%20Number
1158
 */
1159
int
1160
ptarray_contains_point_partial(const POINTARRAY *pa, const POINT2D *pt, int check_closed, int *winding_number)
1161
0
{
1162
0
  int wn = 0;
1163
0
  uint32_t i;
1164
0
  double side;
1165
0
  const POINT2D *seg1, *seg2;
1166
0
  double ymin, ymax;
1167
1168
0
  if (!pa || !pa->npoints)
1169
0
    lwerror("%s called on empty pointarray", __func__);
1170
1171
0
  seg1 = getPoint2d_cp(pa, 0);
1172
0
  seg2 = getPoint2d_cp(pa, pa->npoints - 1);
1173
0
  if (check_closed && !p2d_same(seg1, seg2))
1174
0
    lwerror("%s called on unclosed ring", __func__);
1175
1176
0
  for (i = 1; i < pa->npoints; i++)
1177
0
  {
1178
0
    seg2 = getPoint2d_cp(pa, i);
1179
1180
    /* Zero length segments are ignored. */
1181
0
    if (seg1->x == seg2->x && seg1->y == seg2->y)
1182
0
    {
1183
0
      seg1 = seg2;
1184
0
      continue;
1185
0
    }
1186
1187
0
    ymin = FP_MIN(seg1->y, seg2->y);
1188
0
    ymax = FP_MAX(seg1->y, seg2->y);
1189
1190
    /* Only test segments in our vertical range */
1191
0
    if (pt->y > ymax || pt->y < ymin)
1192
0
    {
1193
0
      seg1 = seg2;
1194
0
      continue;
1195
0
    }
1196
1197
0
    side = lw_segment_side(seg1, seg2, pt);
1198
1199
    /*
1200
     * A point on the boundary of a ring is not contained.
1201
     * WAS: if (fabs(side) < 1e-12), see #852
1202
     */
1203
0
    if ((side == 0) && lw_pt_in_seg(pt, seg1, seg2))
1204
0
    {
1205
0
      return LW_BOUNDARY;
1206
0
    }
1207
1208
    /*
1209
     * If the point is to the left of the line, and it's rising,
1210
     * then the line is to the right of the point and
1211
     * circling counter-clockwise, so increment.
1212
     */
1213
0
    if ((side < 0) && (seg1->y <= pt->y) && (pt->y < seg2->y))
1214
0
    {
1215
0
      wn++;
1216
0
    }
1217
1218
    /*
1219
     * If the point is to the right of the line, and it's falling,
1220
     * then the line is to the right of the point and circling
1221
     * clockwise, so decrement.
1222
     */
1223
0
    else if ((side > 0) && (seg2->y <= pt->y) && (pt->y < seg1->y))
1224
0
    {
1225
0
      wn--;
1226
0
    }
1227
1228
0
    seg1 = seg2;
1229
0
  }
1230
1231
  /* Sent out the winding number for calls that are building on this as a primitive */
1232
0
  if (winding_number)
1233
0
    *winding_number = wn;
1234
1235
  /* Outside */
1236
0
  if (wn == 0)
1237
0
  {
1238
0
    return LW_OUTSIDE;
1239
0
  }
1240
1241
  /* Inside */
1242
0
  return LW_INSIDE;
1243
0
}
1244
1245
/**
1246
 * For POINTARRAYs representing CIRCULARSTRINGS. That is, linked triples
1247
 * with each triple being control points of a circular arc. Such
1248
 * POINTARRAYs have an odd number of vertices.
1249
 *
1250
 * Return 1 if the point is inside the POINTARRAY, -1 if it is outside,
1251
 * and 0 if it is on the boundary.
1252
 */
1253
1254
int
1255
ptarrayarc_contains_point(const POINTARRAY *pa, const POINT2D *pt)
1256
0
{
1257
0
  int on_boundary = LW_FALSE;
1258
0
  int intersections;
1259
0
  if (!ptarray_is_closed_2d(pa))
1260
0
    lwerror("%s called on unclosed ring", __func__);
1261
1262
0
  intersections = ptarrayarc_raycast_intersections(pa, pt, &on_boundary);
1263
0
  if (on_boundary)
1264
0
    return LW_BOUNDARY;
1265
0
  else
1266
0
    return (intersections % 2) ? LW_INSIDE : LW_OUTSIDE;
1267
0
}
1268
1269
/**
1270
 * Returns the area in cartesian units. Area is negative if ring is oriented CCW,
1271
 * positive if it is oriented CW and zero if the ring is degenerate or flat.
1272
 * http://en.wikipedia.org/wiki/Shoelace_formula
1273
 */
1274
double
1275
ptarray_signed_area(const POINTARRAY *pa)
1276
0
{
1277
0
  const POINT2D *P1;
1278
0
  const POINT2D *P2;
1279
0
  const POINT2D *P3;
1280
0
  double sum = 0.0;
1281
0
  double compensation = 0.0;
1282
0
  double tail_sum = 0.0;
1283
0
  double tail_compensation = 0.0;
1284
0
  double scaled_sum = 0.0;
1285
0
  double scaled_compensation = 0.0;
1286
0
  double scaled_tail_sum = 0.0;
1287
0
  double scaled_tail_compensation = 0.0;
1288
0
  double det_abs_sum = 0.0;
1289
0
  double tail_abs_sum = 0.0;
1290
0
  double scaled_det_abs_sum = 0.0;
1291
0
  double scaled_tail_abs_sum = 0.0;
1292
0
  double x0, y0;
1293
0
  int area_scale = 0;
1294
0
  int unscaled_cancelled;
1295
0
  int scaled_cancelled;
1296
0
  uint32_t i;
1297
1298
0
  if (!pa || pa->npoints < 3)
1299
0
    return 0.0;
1300
1301
0
  P1 = getPoint2d_cp(pa, 0);
1302
0
  P2 = getPoint2d_cp(pa, 1);
1303
0
  x0 = P1->x;
1304
0
  y0 = P1->y;
1305
  /*
1306
   * Use one binary area scale for overflowing fan triangles. Some skinny
1307
   * rings have finite total area even though individual fan triangles
1308
   * overflow; scaling each overflowing term independently would preserve
1309
   * those infinities and still lose the final cancellation. Finite raw
1310
   * triangles are kept in the unscaled sum so unrelated tiny determinants do
1311
   * not underflow just because another triangle needed scaling.
1312
   */
1313
0
  for (i = 1; i < pa->npoints; i++)
1314
0
  {
1315
0
    double ax, ay, bx, by, axerr, ayerr, bxerr, byerr;
1316
0
    int product_exponent;
1317
0
    P3 = getPoint2d_cp(pa, i);
1318
0
    ptarray_signed_area_two_diff(P2->x, x0, &ax, &axerr);
1319
0
    ptarray_signed_area_two_diff(P2->y, y0, &ay, &ayerr);
1320
0
    ptarray_signed_area_two_diff(P3->x, x0, &bx, &bxerr);
1321
0
    ptarray_signed_area_two_diff(P3->y, y0, &by, &byerr);
1322
0
    product_exponent =
1323
0
        FP_MAX(ptarray_signed_area_product_exponent(ax, by), ptarray_signed_area_product_exponent(ay, bx));
1324
0
    if (product_exponent > DBL_MAX_EXP - 24)
1325
0
    {
1326
0
      int coordinate_scale = (product_exponent - (DBL_MAX_EXP - 24) + 1) / 2;
1327
0
      area_scale = FP_MAX(area_scale, coordinate_scale);
1328
0
    }
1329
0
    P2 = P3;
1330
0
  }
1331
1332
0
  P2 = getPoint2d_cp(pa, 1);
1333
0
  for (i = 2; i < pa->npoints; i++)
1334
0
  {
1335
0
    double ax, ay, bx, by, axerr, ayerr, bxerr, byerr;
1336
0
    double detleft, detright, det, err = 0.0, b;
1337
0
    double *active_sum = &sum;
1338
0
    double *active_compensation = &compensation;
1339
0
    double *active_tail_sum = &tail_sum;
1340
0
    double *active_tail_compensation = &tail_compensation;
1341
0
    int scaled_term = LW_FALSE;
1342
0
    P3 = getPoint2d_cp(pa, i);
1343
1344
0
    ptarray_signed_area_two_diff(P2->x, x0, &ax, &axerr);
1345
0
    ptarray_signed_area_two_diff(P2->y, y0, &ay, &ayerr);
1346
0
    ptarray_signed_area_two_diff(P3->x, x0, &bx, &bxerr);
1347
0
    ptarray_signed_area_two_diff(P3->y, y0, &by, &byerr);
1348
1349
0
    detleft = ax * by;
1350
0
    detright = ay * bx;
1351
0
    det = detleft - detright;
1352
0
    if (area_scale > 0 && (!isfinite(detleft) || !isfinite(detright) || !isfinite(det)))
1353
0
    {
1354
0
      ax = ldexp(ax, -area_scale);
1355
0
      ay = ldexp(ay, -area_scale);
1356
0
      bx = ldexp(bx, -area_scale);
1357
0
      by = ldexp(by, -area_scale);
1358
0
      axerr = ldexp(axerr, -area_scale);
1359
0
      ayerr = ldexp(ayerr, -area_scale);
1360
0
      bxerr = ldexp(bxerr, -area_scale);
1361
0
      byerr = ldexp(byerr, -area_scale);
1362
0
      active_sum = &scaled_sum;
1363
0
      active_compensation = &scaled_compensation;
1364
0
      active_tail_sum = &scaled_tail_sum;
1365
0
      active_tail_compensation = &scaled_tail_compensation;
1366
0
      scaled_term = LW_TRUE;
1367
0
      detleft = ax * by;
1368
0
      detright = ay * bx;
1369
0
      det = detleft - detright;
1370
0
    }
1371
    /*
1372
     * Keep the determinant rounding error, including the product
1373
     * tails, and sum it with Kahan compensation. Near-collinear
1374
     * large-coordinate rings can otherwise lose the sign in the
1375
     * rounded products before the subtraction tail is recovered.
1376
     * The error tail is meaningful only for finite products; with
1377
     * overflow it can turn an infinite determinant into NaN through
1378
     * Inf-Inf cancellation.
1379
     */
1380
0
    if (isfinite(detleft) && isfinite(detright) && isfinite(det))
1381
0
    {
1382
0
      ptarray_signed_area_expansion residual = {0};
1383
0
      double tail_abs = 0.0;
1384
0
      double subtract_roundoff;
1385
0
      double left_roundoff;
1386
0
      double right_roundoff;
1387
0
      double ax_byerr, axerr_by, axerr_byerr;
1388
0
      double ay_bxerr, ayerr_bx, ayerr_bxerr;
1389
1390
0
      b = det - detleft;
1391
0
      subtract_roundoff = (detleft - (det - b)) - (detright + b);
1392
0
      left_roundoff = fma(ax, by, -detleft);
1393
0
      right_roundoff = fma(ay, bx, -detright);
1394
0
      ptarray_signed_area_expansion_add(&residual, subtract_roundoff);
1395
0
      ptarray_signed_area_expansion_add(&residual, left_roundoff);
1396
0
      ptarray_signed_area_expansion_add(&residual, -right_roundoff);
1397
0
      ptarray_signed_area_add_abs_or_infinite(&tail_abs, subtract_roundoff);
1398
0
      ptarray_signed_area_add_abs_or_infinite(&tail_abs, left_roundoff);
1399
0
      ptarray_signed_area_add_abs_or_infinite(&tail_abs, right_roundoff);
1400
      /*
1401
       * The origin shift itself can round away unit-scale
1402
       * offsets beside 1e16-scale coordinates. Include the
1403
       * low-order subtraction terms in the determinant so the
1404
       * compensated sum still sees their signed area. Use an
1405
       * expansion so opposite large low-order products do not
1406
       * erase a smaller residual before cancellation is tested.
1407
       */
1408
0
      ax_byerr = ax * byerr;
1409
0
      axerr_by = axerr * by;
1410
0
      axerr_byerr = axerr * byerr;
1411
0
      ay_bxerr = ay * bxerr;
1412
0
      ayerr_bx = ayerr * bx;
1413
0
      ayerr_bxerr = ayerr * bxerr;
1414
0
      ptarray_signed_area_expansion_add_product(&residual, ax, byerr, 1.0);
1415
0
      ptarray_signed_area_expansion_add_product(&residual, axerr, by, 1.0);
1416
0
      ptarray_signed_area_expansion_add_product(&residual, axerr, byerr, 1.0);
1417
0
      ptarray_signed_area_expansion_add_product(&residual, ay, bxerr, -1.0);
1418
0
      ptarray_signed_area_expansion_add_product(&residual, ayerr, bx, -1.0);
1419
0
      ptarray_signed_area_expansion_add_product(&residual, ayerr, bxerr, -1.0);
1420
0
      ptarray_signed_area_add_abs_or_infinite(&tail_abs, ax_byerr);
1421
0
      ptarray_signed_area_add_abs_or_infinite(&tail_abs, axerr_by);
1422
0
      ptarray_signed_area_add_abs_or_infinite(&tail_abs, axerr_byerr);
1423
0
      ptarray_signed_area_add_abs_or_infinite(&tail_abs, ay_bxerr);
1424
0
      ptarray_signed_area_add_abs_or_infinite(&tail_abs, ayerr_bx);
1425
0
      ptarray_signed_area_add_abs_or_infinite(&tail_abs, ayerr_bxerr);
1426
0
      err = ptarray_signed_area_expansion_sum(&residual);
1427
0
      if (!isfinite(err))
1428
0
        err = 0.0;
1429
0
      if (scaled_term)
1430
0
        scaled_tail_abs_sum += tail_abs;
1431
0
      else
1432
0
        tail_abs_sum += tail_abs;
1433
0
    }
1434
1435
0
    ptarray_signed_area_add(active_sum, active_compensation, det);
1436
0
    if (isfinite(det))
1437
0
    {
1438
0
      if (scaled_term)
1439
0
        scaled_det_abs_sum += fabs(det);
1440
0
      else
1441
0
        det_abs_sum += fabs(det);
1442
0
    }
1443
    /*
1444
     * Keep determinant tails in a separate compensated stream. If
1445
     * they are folded into the main determinant stream immediately,
1446
     * a later cancellation between large determinants can erase the
1447
     * small residual that fixes the exact double-coordinate sign.
1448
     */
1449
0
    ptarray_signed_area_add(active_tail_sum, active_tail_compensation, err);
1450
1451
    /* Move forwards! */
1452
0
    P2 = P3;
1453
0
  }
1454
0
  if (scaled_sum != 0.0)
1455
0
    ptarray_signed_area_add(&sum, &compensation, ldexp(scaled_sum, 2 * area_scale));
1456
0
  if (scaled_tail_sum != 0.0)
1457
0
  {
1458
0
    double scaled_tail = ldexp(scaled_tail_sum, 2 * area_scale);
1459
0
    if (isfinite(scaled_tail))
1460
0
      ptarray_signed_area_add(&tail_sum, &tail_compensation, scaled_tail);
1461
0
  }
1462
0
  if (tail_sum != 0.0 && isfinite(tail_sum))
1463
0
    ptarray_signed_area_add(&sum, &compensation, tail_sum);
1464
0
  unscaled_cancelled = tail_abs_sum > 0.0 && fabs(sum) < FP_MAX(det_abs_sum, tail_abs_sum) * 1e-12;
1465
0
  scaled_cancelled = scaled_tail_abs_sum > 0.0 &&
1466
0
         fabs(scaled_sum + scaled_tail_sum) < FP_MAX(scaled_det_abs_sum, scaled_tail_abs_sum) * 1e-12;
1467
0
  if (unscaled_cancelled || scaled_cancelled)
1468
0
  {
1469
0
    double exact_area = ptarray_signed_area_exact(pa, scaled_cancelled ? area_scale : 0);
1470
0
    if (isfinite(exact_area))
1471
0
      return exact_area;
1472
0
  }
1473
0
  return -sum / 2.0;
1474
0
}
1475
1476
int
1477
ptarray_has_orientation(const POINTARRAY *pa, int orientation)
1478
0
{
1479
0
  if (ptarray_signed_area(pa) > 0)
1480
0
    return orientation == LW_CLOCKWISE;
1481
0
  else
1482
0
    return orientation == LW_COUNTERCLOCKWISE;
1483
0
}
1484
1485
int
1486
ptarray_isccw(const POINTARRAY *pa)
1487
0
{
1488
0
  return ptarray_has_orientation(pa, LW_COUNTERCLOCKWISE);
1489
0
}
1490
1491
POINTARRAY *
1492
ptarray_force_dims(const POINTARRAY *pa, int hasz, int hasm, double zval, double mval)
1493
0
{
1494
  /* TODO handle zero-length point arrays */
1495
0
  uint32_t i;
1496
0
  int in_hasz = FLAGS_GET_Z(pa->flags);
1497
0
  int in_hasm = FLAGS_GET_M(pa->flags);
1498
0
  POINT4D pt;
1499
0
  POINTARRAY *pa_out = ptarray_construct_empty(hasz, hasm, pa->npoints);
1500
1501
0
  for (i = 0; i < pa->npoints; i++)
1502
0
  {
1503
0
    getPoint4d_p(pa, i, &pt);
1504
0
    if (hasz && !in_hasz)
1505
0
      pt.z = zval;
1506
0
    if (hasm && !in_hasm)
1507
0
      pt.m = mval;
1508
0
    ptarray_append_point(pa_out, &pt, LW_TRUE);
1509
0
  }
1510
1511
0
  return pa_out;
1512
0
}
1513
1514
POINTARRAY *
1515
ptarray_substring(POINTARRAY *ipa, double from, double to, double tolerance)
1516
0
{
1517
0
  POINTARRAY *dpa;
1518
0
  POINT4D pt;
1519
0
  POINT4D p1, p2;
1520
0
  POINT4D *p1ptr = &p1; /* don't break strict-aliasing rule */
1521
0
  POINT4D *p2ptr = &p2;
1522
0
  int nsegs, i;
1523
0
  double length, slength, tlength;
1524
0
  int state = 0; /* 0=before, 1=inside */
1525
1526
  /*
1527
   * Create a dynamic pointarray with an initial capacity
1528
   * equal to full copy of input points
1529
   */
1530
0
  dpa = ptarray_construct_empty(FLAGS_GET_Z(ipa->flags), FLAGS_GET_M(ipa->flags), ipa->npoints);
1531
1532
  /* Compute total line length */
1533
0
  length = ptarray_length_2d(ipa);
1534
1535
0
  LWDEBUGF(3, "Total length: %g", length);
1536
1537
  /* Get 'from' and 'to' lengths */
1538
0
  from = length * from;
1539
0
  to = length * to;
1540
1541
0
  LWDEBUGF(3, "From/To: %g/%g", from, to);
1542
1543
0
  tlength = 0;
1544
0
  getPoint4d_p(ipa, 0, &p1);
1545
0
  nsegs = ipa->npoints - 1;
1546
0
  for (i = 0; i < nsegs; i++)
1547
0
  {
1548
0
    double dseg;
1549
1550
0
    getPoint4d_p(ipa, i + 1, &p2);
1551
1552
0
    LWDEBUGF(
1553
0
        3, "Segment %d: (%g,%g,%g,%g)-(%g,%g,%g,%g)", i, p1.x, p1.y, p1.z, p1.m, p2.x, p2.y, p2.z, p2.m);
1554
1555
    /* Find the length of this segment */
1556
0
    slength = distance2d_pt_pt((POINT2D *)p1ptr, (POINT2D *)p2ptr);
1557
1558
    /*
1559
     * We are before requested start.
1560
     */
1561
0
    if (state == 0) /* before */
1562
0
    {
1563
1564
0
      LWDEBUG(3, " Before start");
1565
1566
0
      if (fabs(from - (tlength + slength)) <= tolerance)
1567
0
      {
1568
1569
0
        LWDEBUG(3, "  Second point is our start");
1570
1571
        /*
1572
         * Second point is our start
1573
         */
1574
0
        ptarray_append_point(dpa, &p2, LW_FALSE);
1575
0
        state = 1; /* we're inside now */
1576
0
        goto END;
1577
0
      }
1578
1579
0
      else if (fabs(from - tlength) <= tolerance)
1580
0
      {
1581
1582
0
        LWDEBUG(3, "  First point is our start");
1583
1584
        /*
1585
         * First point is our start
1586
         */
1587
0
        ptarray_append_point(dpa, &p1, LW_FALSE);
1588
1589
        /*
1590
         * We're inside now, but will check
1591
         * 'to' point as well
1592
         */
1593
0
        state = 1;
1594
0
      }
1595
1596
      /*
1597
       * Didn't reach the 'from' point,
1598
       * nothing to do
1599
       */
1600
0
      else if (from > tlength + slength)
1601
0
        goto END;
1602
1603
0
      else /* tlength < from < tlength+slength */
1604
0
      {
1605
1606
0
        LWDEBUG(3, "  Seg contains first point");
1607
1608
        /*
1609
         * Our start is between first and
1610
         * second point
1611
         */
1612
0
        dseg = (from - tlength) / slength;
1613
1614
0
        interpolate_point4d(&p1, &p2, &pt, dseg);
1615
1616
0
        ptarray_append_point(dpa, &pt, LW_FALSE);
1617
1618
        /*
1619
         * We're inside now, but will check
1620
         * 'to' point as well
1621
         */
1622
0
        state = 1;
1623
0
      }
1624
0
    }
1625
1626
0
    if (state == 1) /* inside */
1627
0
    {
1628
1629
0
      LWDEBUG(3, " Inside");
1630
1631
      /*
1632
       * 'to' point is our second point.
1633
       */
1634
0
      if (fabs(to - (tlength + slength)) <= tolerance)
1635
0
      {
1636
1637
0
        LWDEBUG(3, " Second point is our end");
1638
1639
0
        ptarray_append_point(dpa, &p2, LW_FALSE);
1640
0
        break; /* substring complete */
1641
0
      }
1642
1643
      /*
1644
       * 'to' point is our first point.
1645
       * (should only happen if 'to' is 0)
1646
       */
1647
0
      else if (fabs(to - tlength) <= tolerance)
1648
0
      {
1649
1650
0
        LWDEBUG(3, " First point is our end");
1651
1652
0
        ptarray_append_point(dpa, &p1, LW_FALSE);
1653
1654
0
        break; /* substring complete */
1655
0
      }
1656
1657
      /*
1658
       * Didn't reach the 'end' point,
1659
       * just copy second point
1660
       */
1661
0
      else if (to > tlength + slength)
1662
0
      {
1663
0
        ptarray_append_point(dpa, &p2, LW_FALSE);
1664
0
        goto END;
1665
0
      }
1666
1667
      /*
1668
       * 'to' point falls on this segment
1669
       * Interpolate and break.
1670
       */
1671
0
      else if (to < tlength + slength)
1672
0
      {
1673
1674
0
        LWDEBUG(3, " Seg contains our end");
1675
1676
0
        dseg = (to - tlength) / slength;
1677
0
        interpolate_point4d(&p1, &p2, &pt, dseg);
1678
1679
0
        ptarray_append_point(dpa, &pt, LW_FALSE);
1680
1681
0
        break;
1682
0
      }
1683
1684
0
      else
1685
0
      {
1686
0
        LWDEBUG(3, "Unhandled case");
1687
0
      }
1688
0
    }
1689
1690
0
  END:
1691
1692
0
    tlength += slength;
1693
0
    memcpy(&p1, &p2, sizeof(POINT4D));
1694
0
  }
1695
1696
0
  LWDEBUGF(3, "Out of loop, ptarray has %d points", dpa->npoints);
1697
1698
0
  return dpa;
1699
0
}
1700
1701
/*
1702
 * Write into the *ret argument coordinates of the closes point on
1703
 * the given segment to the reference input point.
1704
 */
1705
void
1706
closest_point_on_segment(const POINT4D *p, const POINT4D *A, const POINT4D *B, POINT4D *ret)
1707
0
{
1708
0
  double r;
1709
1710
0
  if (FP_EQUALS(A->x, B->x) && FP_EQUALS(A->y, B->y))
1711
0
  {
1712
0
    *ret = *A;
1713
0
    return;
1714
0
  }
1715
1716
  /*
1717
   * We use comp.graphics.algorithms Frequently Asked Questions method
1718
   *
1719
   * (1)           AC dot AB
1720
   *           r = ----------
1721
   *                ||AB||^2
1722
   *  r has the following meaning:
1723
   *  r=0 P = A
1724
   *  r=1 P = B
1725
   *  r<0 P is on the backward extension of AB
1726
   *  r>1 P is on the forward extension of AB
1727
   *  0<r<1 P is interior to AB
1728
   *
1729
   */
1730
0
  r = ((p->x - A->x) * (B->x - A->x) + (p->y - A->y) * (B->y - A->y)) /
1731
0
      ((B->x - A->x) * (B->x - A->x) + (B->y - A->y) * (B->y - A->y));
1732
1733
0
  if (r <= 0)
1734
0
  {
1735
0
    *ret = *A;
1736
0
    return;
1737
0
  }
1738
0
  if (r >= 1)
1739
0
  {
1740
0
    *ret = *B;
1741
0
    return;
1742
0
  }
1743
1744
0
  ret->x = A->x + ((B->x - A->x) * r);
1745
0
  ret->y = A->y + ((B->y - A->y) * r);
1746
0
  ret->z = A->z + ((B->z - A->z) * r);
1747
0
  ret->m = A->m + ((B->m - A->m) * r);
1748
0
}
1749
1750
int
1751
ptarray_closest_segment_2d(const POINTARRAY *pa, const POINT2D *qp, double *dist)
1752
0
{
1753
0
  const POINT2D *start = getPoint2d_cp(pa, 0), *end = NULL;
1754
0
  uint32_t t, seg = 0;
1755
0
  double mindist = DBL_MAX;
1756
1757
  /* Loop through pointarray looking for nearest segment */
1758
0
  for (t = 1; t < pa->npoints; t++)
1759
0
  {
1760
0
    double dist_sqr;
1761
0
    end = getPoint2d_cp(pa, t);
1762
0
    dist_sqr = distance2d_sqr_pt_seg(qp, start, end);
1763
1764
0
    if (dist_sqr < mindist)
1765
0
    {
1766
0
      mindist = dist_sqr;
1767
0
      seg = t - 1;
1768
0
      if (mindist == 0)
1769
0
      {
1770
0
        LWDEBUG(3, "Breaking on mindist=0");
1771
0
        break;
1772
0
      }
1773
0
    }
1774
1775
0
    start = end;
1776
0
  }
1777
1778
0
  if (dist)
1779
0
    *dist = sqrt(mindist);
1780
0
  return seg;
1781
0
}
1782
1783
int
1784
ptarray_closest_vertex_2d(const POINTARRAY *pa, const POINT2D *qp, double *dist)
1785
0
{
1786
0
  uint32_t t, pn = 0;
1787
0
  const POINT2D *p;
1788
0
  double mindist = DBL_MAX;
1789
1790
  /* Loop through pointarray looking for nearest segment */
1791
0
  for (t = 0; t < pa->npoints; t++)
1792
0
  {
1793
0
    double dist_sqr;
1794
0
    p = getPoint2d_cp(pa, t);
1795
0
    dist_sqr = distance2d_sqr_pt_pt(p, qp);
1796
1797
0
    if (dist_sqr < mindist)
1798
0
    {
1799
0
      mindist = dist_sqr;
1800
0
      pn = t;
1801
0
      if (mindist == 0)
1802
0
      {
1803
0
        LWDEBUG(3, "Breaking on mindist=0");
1804
0
        break;
1805
0
      }
1806
0
    }
1807
0
  }
1808
0
  if (dist)
1809
0
    *dist = sqrt(mindist);
1810
0
  return pn;
1811
0
}
1812
1813
/*
1814
 * Given a point, returns the location of closest point on pointarray
1815
 * and, optionally, it's actual distance from the point array.
1816
 */
1817
double
1818
ptarray_locate_point(const POINTARRAY *pa, const POINT4D *p4d, double *mindistout, POINT4D *proj4d)
1819
0
{
1820
0
  double mindist = DBL_MAX;
1821
0
  double tlen, plen;
1822
0
  uint32_t t, seg = 0;
1823
0
  POINT4D start4d, end4d, projtmp;
1824
0
  POINT2D proj, p;
1825
0
  const POINT2D *start = NULL, *end = NULL;
1826
1827
  /* Initialize our 2D copy of the input parameter */
1828
0
  p.x = p4d->x;
1829
0
  p.y = p4d->y;
1830
1831
0
  if (!proj4d)
1832
0
    proj4d = &projtmp;
1833
1834
  /* Check for special cases (length 0 and 1) */
1835
0
  if (pa->npoints <= 1)
1836
0
  {
1837
0
    if (pa->npoints == 1)
1838
0
    {
1839
0
      getPoint4d_p(pa, 0, proj4d);
1840
0
      if (mindistout)
1841
0
        *mindistout = distance2d_pt_pt(&p, getPoint2d_cp(pa, 0));
1842
0
    }
1843
0
    return 0.0;
1844
0
  }
1845
1846
0
  start = getPoint2d_cp(pa, 0);
1847
  /* Loop through pointarray looking for nearest segment */
1848
0
  for (t = 1; t < pa->npoints; t++)
1849
0
  {
1850
0
    double dist_sqr;
1851
0
    end = getPoint2d_cp(pa, t);
1852
0
    dist_sqr = distance2d_sqr_pt_seg(&p, start, end);
1853
1854
0
    if (dist_sqr < mindist)
1855
0
    {
1856
0
      mindist = dist_sqr;
1857
0
      seg = t - 1;
1858
0
      if (mindist == 0)
1859
0
      {
1860
0
        LWDEBUG(3, "Breaking on mindist=0");
1861
0
        break;
1862
0
      }
1863
0
    }
1864
1865
0
    start = end;
1866
0
  }
1867
0
  mindist = sqrt(mindist);
1868
1869
0
  if (mindistout)
1870
0
    *mindistout = mindist;
1871
1872
0
  LWDEBUGF(3, "Closest segment: %d", seg);
1873
0
  LWDEBUGF(3, "mindist: %g", mindist);
1874
1875
  /*
1876
   * We need to project the
1877
   * point on the closest segment.
1878
   */
1879
0
  getPoint4d_p(pa, seg, &start4d);
1880
0
  getPoint4d_p(pa, seg + 1, &end4d);
1881
0
  closest_point_on_segment(p4d, &start4d, &end4d, proj4d);
1882
1883
  /* Copy 4D values into 2D holder */
1884
0
  proj.x = proj4d->x;
1885
0
  proj.y = proj4d->y;
1886
1887
0
  LWDEBUGF(3, "Closest segment:%d, npoints:%d", seg, pa->npoints);
1888
1889
  /* For robustness, force 1 when closest point == endpoint */
1890
0
  if ((seg >= (pa->npoints - 2)) && p2d_same(&proj, end))
1891
0
  {
1892
0
    return 1.0;
1893
0
  }
1894
1895
0
  LWDEBUGF(3, "Closest point on segment: %g,%g", proj.x, proj.y);
1896
1897
0
  tlen = ptarray_length_2d(pa);
1898
1899
0
  LWDEBUGF(3, "tlen %g", tlen);
1900
1901
  /* Location of any point on a zero-length line is 0 */
1902
  /* See http://trac.osgeo.org/postgis/ticket/1772#comment:2 */
1903
0
  if (tlen == 0)
1904
0
    return 0;
1905
1906
0
  plen = 0;
1907
0
  start = getPoint2d_cp(pa, 0);
1908
0
  for (t = 0; t < seg; t++, start = end)
1909
0
  {
1910
0
    end = getPoint2d_cp(pa, t + 1);
1911
0
    plen += distance2d_pt_pt(start, end);
1912
1913
0
    LWDEBUGF(4, "Segment %d made plen %g", t, plen);
1914
0
  }
1915
1916
0
  plen += distance2d_pt_pt(&proj, start);
1917
1918
0
  LWDEBUGF(3, "plen %g, tlen %g", plen, tlen);
1919
1920
  /* Floating point arithmetic is not reliable, make sure we return values [0,1] */
1921
0
  double result = plen / tlen;
1922
0
  if (result < 0.0)
1923
0
  {
1924
0
    result = 0.0;
1925
0
  }
1926
0
  else if (result > 1.0)
1927
0
  {
1928
0
    result = 1.0;
1929
0
  }
1930
0
  return result;
1931
0
}
1932
1933
/**
1934
 * @brief Longitude shift for a pointarray.
1935
 *    Y remains the same
1936
 *    X is converted:
1937
 *      from -180..180 to 0..360
1938
 *      from 0..360 to -180..180
1939
 *    X < 0 becomes X + 360
1940
 *    X > 180 becomes X - 360
1941
 */
1942
void
1943
ptarray_longitude_shift(POINTARRAY *pa)
1944
0
{
1945
0
  uint32_t i;
1946
0
  double x;
1947
1948
0
  for (i = 0; i < pa->npoints; i++)
1949
0
  {
1950
0
    memcpy(&x, getPoint_internal(pa, i), sizeof(double));
1951
0
    if (x < 0)
1952
0
      x += 360;
1953
0
    else if (x > 180)
1954
0
      x -= 360;
1955
0
    memcpy(getPoint_internal(pa, i), &x, sizeof(double));
1956
0
  }
1957
0
}
1958
1959
/*
1960
 * Returns a POINTARRAY with consecutive equal points
1961
 * removed. Equality test on all dimensions of input.
1962
 *
1963
 * Always returns a newly allocated object.
1964
 */
1965
static POINTARRAY *
1966
ptarray_remove_repeated_points_minpoints(const POINTARRAY *in, double tolerance, int minpoints)
1967
0
{
1968
0
  POINTARRAY *out = ptarray_clone_deep(in);
1969
0
  ptarray_remove_repeated_points_in_place(out, tolerance, minpoints);
1970
0
  return out;
1971
0
}
1972
1973
POINTARRAY *
1974
ptarray_remove_repeated_points(const POINTARRAY *in, double tolerance)
1975
0
{
1976
0
  return ptarray_remove_repeated_points_minpoints(in, tolerance, 2);
1977
0
}
1978
1979
void
1980
ptarray_remove_repeated_points_in_place(POINTARRAY *pa, double tolerance, uint32_t min_points)
1981
0
{
1982
0
  uint32_t i;
1983
0
  double tolsq = tolerance * tolerance;
1984
0
  const POINT2D *last = NULL;
1985
0
  const POINT2D *pt;
1986
0
  uint32_t n_points = pa->npoints;
1987
0
  uint32_t n_points_out = 1;
1988
0
  size_t pt_size = ptarray_point_size(pa);
1989
1990
0
  double dsq = FLT_MAX;
1991
1992
  /* No-op on short inputs */
1993
0
  if (n_points <= min_points)
1994
0
    return;
1995
1996
0
  last = getPoint2d_cp(pa, 0);
1997
0
  void *p_to = ((char *)last) + pt_size;
1998
0
  for (i = 1; i < n_points; i++)
1999
0
  {
2000
0
    int last_point = (i == n_points - 1);
2001
2002
    /* Look straight into the abyss */
2003
0
    pt = getPoint2d_cp(pa, i);
2004
2005
    /* Don't drop points if we are running short of points */
2006
0
    if (n_points + n_points_out > min_points + i)
2007
0
    {
2008
0
      if (tolerance > 0.0)
2009
0
      {
2010
        /* Only drop points that are within our tolerance */
2011
0
        dsq = distance2d_sqr_pt_pt(last, pt);
2012
        /* Allow any point but the last one to be dropped */
2013
0
        if (!last_point && dsq <= tolsq)
2014
0
        {
2015
0
          continue;
2016
0
        }
2017
0
      }
2018
0
      else
2019
0
      {
2020
        /* At tolerance zero, only skip exact dupes */
2021
0
        if (memcmp((char *)pt, (char *)last, pt_size) == 0)
2022
0
          continue;
2023
0
      }
2024
2025
      /* Got to last point, and it's not very different from */
2026
      /* the point that preceded it. We want to keep the last */
2027
      /* point, not the second-to-last one, so we pull our write */
2028
      /* index back one value */
2029
0
      if (last_point && n_points_out > 1 && tolerance > 0.0 && dsq <= tolsq)
2030
0
      {
2031
0
        n_points_out--;
2032
0
        p_to = (char *)p_to - pt_size;
2033
0
      }
2034
0
    }
2035
2036
    /* Compact all remaining values to front of array */
2037
0
    memcpy(p_to, pt, pt_size);
2038
0
    n_points_out++;
2039
0
    p_to = (char *)p_to + pt_size;
2040
0
    last = pt;
2041
0
  }
2042
  /* Adjust array length */
2043
0
  pa->npoints = n_points_out;
2044
0
  return;
2045
0
}
2046
2047
/* Out of the points in pa [itfist .. itlast], finds the one that's farthest away from
2048
 * the segment determined by pts[itfist] and pts[itlast].
2049
 * Returns itfirst if no point was found further away than max_distance_sqr
2050
 */
2051
static uint32_t
2052
ptarray_dp_findsplit_in_place(const POINTARRAY *pts, uint32_t it_first, uint32_t it_last, double max_distance_sqr)
2053
0
{
2054
0
  uint32_t split = it_first;
2055
0
  if ((it_first - it_last) < 2)
2056
0
    return it_first;
2057
2058
0
  const POINT2D *A = getPoint2d_cp(pts, it_first);
2059
0
  const POINT2D *B = getPoint2d_cp(pts, it_last);
2060
2061
0
  if (distance2d_sqr_pt_pt(A, B) < DBL_EPSILON)
2062
0
  {
2063
    /* If p1 == p2, we can just calculate the distance from each point to A */
2064
0
    for (uint32_t itk = it_first + 1; itk < it_last; itk++)
2065
0
    {
2066
0
      const POINT2D *pk = getPoint2d_cp(pts, itk);
2067
0
      double distance_sqr = distance2d_sqr_pt_pt(pk, A);
2068
0
      if (distance_sqr > max_distance_sqr)
2069
0
      {
2070
0
        split = itk;
2071
0
        max_distance_sqr = distance_sqr;
2072
0
      }
2073
0
    }
2074
0
    return split;
2075
0
  }
2076
2077
  /* This is based on distance2d_sqr_pt_seg, but heavily inlined here to avoid recalculations */
2078
0
  double ba_x = (B->x - A->x);
2079
0
  double ba_y = (B->y - A->y);
2080
0
  double ab_length_sqr = (ba_x * ba_x + ba_y * ba_y);
2081
  /* To avoid the division by ab_length_sqr in the 3rd path, we normalize here
2082
   * and multiply in the first two paths [(dot_ac_ab < 0) and (> ab_length_sqr)] */
2083
0
  max_distance_sqr *= ab_length_sqr;
2084
0
  for (uint32_t itk = it_first + 1; itk < it_last; itk++)
2085
0
  {
2086
0
    const POINT2D *C = getPoint2d_cp(pts, itk);
2087
0
    double distance_sqr;
2088
0
    double ca_x = (C->x - A->x);
2089
0
    double ca_y = (C->y - A->y);
2090
0
    double dot_ac_ab = (ca_x * ba_x + ca_y * ba_y);
2091
2092
0
    if (dot_ac_ab <= 0.0)
2093
0
    {
2094
0
      distance_sqr = distance2d_sqr_pt_pt(C, A) * ab_length_sqr;
2095
0
    }
2096
0
    else if (dot_ac_ab >= ab_length_sqr)
2097
0
    {
2098
0
      distance_sqr = distance2d_sqr_pt_pt(C, B) * ab_length_sqr;
2099
0
    }
2100
0
    else
2101
0
    {
2102
0
      double s_numerator = ca_x * ba_y - ca_y * ba_x;
2103
0
      distance_sqr = s_numerator * s_numerator; /* Missing division by ab_length_sqr on purpose */
2104
0
    }
2105
2106
0
    if (distance_sqr > max_distance_sqr)
2107
0
    {
2108
0
      split = itk;
2109
0
      max_distance_sqr = distance_sqr;
2110
0
    }
2111
0
  }
2112
0
  return split;
2113
0
}
2114
2115
/* O(N) simplification for tolerance = 0 */
2116
static void
2117
ptarray_simplify_in_place_tolerance0(POINTARRAY *pa)
2118
0
{
2119
0
  uint32_t kept_it = 0;
2120
0
  uint32_t last_it = pa->npoints - 1;
2121
0
  const POINT2D *kept_pt = getPoint2d_cp(pa, 0);
2122
0
  const size_t pt_size = ptarray_point_size(pa);
2123
2124
0
  for (uint32_t i = 1; i < last_it; i++)
2125
0
  {
2126
0
    const POINT2D *curr_pt = getPoint2d_cp(pa, i);
2127
0
    const POINT2D *next_pt = getPoint2d_cp(pa, i + 1);
2128
2129
0
    double ba_x = next_pt->x - kept_pt->x;
2130
0
    double ba_y = next_pt->y - kept_pt->y;
2131
0
    double ab_length_sqr = ba_x * ba_x + ba_y * ba_y;
2132
2133
0
    double ca_x = curr_pt->x - kept_pt->x;
2134
0
    double ca_y = curr_pt->y - kept_pt->y;
2135
0
    double dot_ac_ab = ca_x * ba_x + ca_y * ba_y;
2136
0
    double s_numerator = ca_x * ba_y - ca_y * ba_x;
2137
2138
0
    if (p2d_same(kept_pt, next_pt) || dot_ac_ab < 0.0 || dot_ac_ab > ab_length_sqr || s_numerator != 0)
2139
2140
0
    {
2141
0
      kept_it++;
2142
0
      kept_pt = curr_pt;
2143
0
      if (kept_it != i)
2144
0
        memcpy(pa->serialized_pointlist + pt_size * kept_it,
2145
0
               pa->serialized_pointlist + pt_size * i,
2146
0
               pt_size);
2147
0
    }
2148
0
  }
2149
2150
  /* Append last point */
2151
0
  kept_it++;
2152
0
  if (kept_it != last_it)
2153
0
    memcpy(pa->serialized_pointlist + pt_size * kept_it,
2154
0
           pa->serialized_pointlist + pt_size * last_it,
2155
0
           pt_size);
2156
0
  pa->npoints = kept_it + 1;
2157
0
}
2158
2159
void
2160
ptarray_simplify_in_place(POINTARRAY *pa, double tolerance, uint32_t minpts)
2161
0
{
2162
  /* Do not try to simplify really short things */
2163
0
  if (pa->npoints < 3 || pa->npoints <= minpts)
2164
0
    return;
2165
2166
0
  if (tolerance == 0 && minpts <= 2)
2167
0
  {
2168
0
    ptarray_simplify_in_place_tolerance0(pa);
2169
0
    return;
2170
0
  }
2171
2172
  /* We use this array to keep track of the points we are keeping, so
2173
   * we store just TRUE / FALSE in their position */
2174
0
  uint8_t *kept_points = lwalloc(sizeof(uint8_t) * pa->npoints);
2175
0
  memset(kept_points, LW_FALSE, sizeof(uint8_t) * pa->npoints);
2176
0
  kept_points[0] = LW_TRUE;
2177
0
  kept_points[pa->npoints - 1] = LW_TRUE;
2178
0
  uint32_t keptn = 2;
2179
2180
  /* We use this array as a stack to store the iterators that we are going to need
2181
   * in the following steps.
2182
   * This is ~10% faster than iterating over @kept_points looking for them
2183
   */
2184
0
  uint32_t *iterator_stack = lwalloc(sizeof(uint32_t) * pa->npoints);
2185
0
  iterator_stack[0] = 0;
2186
0
  uint32_t iterator_stack_size = 1;
2187
2188
0
  uint32_t it_first = 0;
2189
0
  uint32_t it_last = pa->npoints - 1;
2190
2191
0
  const double tolerance_sqr = tolerance * tolerance;
2192
  /* For the first @minpts points we ignore the tolerance */
2193
0
  double it_tol = keptn >= minpts ? tolerance_sqr : -1.0;
2194
2195
0
  while (iterator_stack_size)
2196
0
  {
2197
0
    uint32_t split = ptarray_dp_findsplit_in_place(pa, it_first, it_last, it_tol);
2198
0
    if (split == it_first)
2199
0
    {
2200
0
      it_first = it_last;
2201
0
      it_last = iterator_stack[--iterator_stack_size];
2202
0
    }
2203
0
    else
2204
0
    {
2205
0
      kept_points[split] = LW_TRUE;
2206
0
      keptn++;
2207
2208
0
      iterator_stack[iterator_stack_size++] = it_last;
2209
0
      it_last = split;
2210
0
      it_tol = keptn >= minpts ? tolerance_sqr : -1.0;
2211
0
    }
2212
0
  }
2213
2214
0
  const size_t pt_size = ptarray_point_size(pa);
2215
  /* The first point is already in place, so we don't need to copy it */
2216
0
  size_t kept_it = 1;
2217
0
  if (keptn == 2)
2218
0
  {
2219
    /* If there are 2 points remaining, it has to be first and last as
2220
     * we added those at the start */
2221
0
    memmove(pa->serialized_pointlist + pt_size * kept_it,
2222
0
      pa->serialized_pointlist + pt_size * (pa->npoints - 1),
2223
0
      pt_size);
2224
0
  }
2225
0
  else if (pa->npoints != keptn) /* We don't need to move any points if we are keeping them all */
2226
0
  {
2227
0
    for (uint32_t i = 1; i < pa->npoints; i++)
2228
0
    {
2229
0
      if (kept_points[i])
2230
0
      {
2231
0
        memcpy(pa->serialized_pointlist + pt_size * kept_it,
2232
0
               pa->serialized_pointlist + pt_size * i,
2233
0
               pt_size);
2234
0
        kept_it++;
2235
0
      }
2236
0
    }
2237
0
  }
2238
0
  pa->npoints = keptn;
2239
2240
0
  lwfree(kept_points);
2241
0
  lwfree(iterator_stack);
2242
0
}
2243
2244
/************************************************************************/
2245
2246
/**
2247
 * Find the 2d length of the given #POINTARRAY, using circular
2248
 * arc interpolation between each coordinate triple.
2249
 * Length(A1, A2, A3, A4, A5) = Length(A1, A2, A3)+Length(A3, A4, A5)
2250
 */
2251
double
2252
ptarray_arc_length_2d(const POINTARRAY *pts)
2253
0
{
2254
0
  double dist = 0.0;
2255
0
  uint32_t i;
2256
0
  const POINT2D *a1;
2257
0
  const POINT2D *a2;
2258
0
  const POINT2D *a3;
2259
2260
0
  if (pts->npoints % 2 != 1)
2261
0
    lwerror("arc point array with even number of points");
2262
2263
0
  a1 = getPoint2d_cp(pts, 0);
2264
2265
0
  for (i = 2; i < pts->npoints; i += 2)
2266
0
  {
2267
0
    a2 = getPoint2d_cp(pts, i - 1);
2268
0
    a3 = getPoint2d_cp(pts, i);
2269
0
    dist += lw_arc_length(a1, a2, a3);
2270
0
    a1 = a3;
2271
0
  }
2272
0
  return dist;
2273
0
}
2274
2275
/**
2276
 * Find the 2d length of the given #POINTARRAY (even if it's 3d)
2277
 */
2278
double
2279
ptarray_length_2d(const POINTARRAY *pts)
2280
0
{
2281
0
  double dist = 0.0;
2282
0
  uint32_t i;
2283
0
  const POINT2D *frm;
2284
0
  const POINT2D *to;
2285
2286
0
  if (pts->npoints < 2)
2287
0
    return 0.0;
2288
2289
0
  frm = getPoint2d_cp(pts, 0);
2290
2291
0
  for (i = 1; i < pts->npoints; i++)
2292
0
  {
2293
0
    to = getPoint2d_cp(pts, i);
2294
2295
0
    dist += sqrt(((frm->x - to->x) * (frm->x - to->x)) + ((frm->y - to->y) * (frm->y - to->y)));
2296
2297
0
    frm = to;
2298
0
  }
2299
0
  return dist;
2300
0
}
2301
2302
/**
2303
 * Find the 3d/2d length of the given #POINTARRAY
2304
 * (depending on its dimensionality)
2305
 */
2306
double
2307
ptarray_length(const POINTARRAY *pts)
2308
0
{
2309
0
  double dist = 0.0;
2310
0
  uint32_t i;
2311
0
  POINT3DZ frm;
2312
0
  POINT3DZ to;
2313
2314
0
  if (pts->npoints < 2)
2315
0
    return 0.0;
2316
2317
  /* compute 2d length if 3d is not available */
2318
0
  if (!FLAGS_GET_Z(pts->flags))
2319
0
    return ptarray_length_2d(pts);
2320
2321
0
  getPoint3dz_p(pts, 0, &frm);
2322
0
  for (i = 1; i < pts->npoints; i++)
2323
0
  {
2324
0
    getPoint3dz_p(pts, i, &to);
2325
0
    dist += sqrt(((frm.x - to.x) * (frm.x - to.x)) + ((frm.y - to.y) * (frm.y - to.y)) +
2326
0
           ((frm.z - to.z) * (frm.z - to.z)));
2327
0
    frm = to;
2328
0
  }
2329
0
  return dist;
2330
0
}
2331
2332
/**
2333
 * Affine transform a pointarray.
2334
 */
2335
void
2336
ptarray_affine(POINTARRAY *pa, const AFFINE *a)
2337
0
{
2338
0
  if (FLAGS_GET_Z(pa->flags))
2339
0
  {
2340
0
    for (uint32_t i = 0; i < pa->npoints; i++)
2341
0
    {
2342
0
      POINT4D *p4d = (POINT4D *)(getPoint_internal(pa, i));
2343
0
      double x = p4d->x;
2344
0
      double y = p4d->y;
2345
0
      double z = p4d->z;
2346
0
      p4d->x = a->afac * x + a->bfac * y + a->cfac * z + a->xoff;
2347
0
      p4d->y = a->dfac * x + a->efac * y + a->ffac * z + a->yoff;
2348
0
      p4d->z = a->gfac * x + a->hfac * y + a->ifac * z + a->zoff;
2349
0
    }
2350
0
  }
2351
0
  else
2352
0
  {
2353
0
    for (uint32_t i = 0; i < pa->npoints; i++)
2354
0
    {
2355
0
      POINT2D *pt = (POINT2D *)(getPoint_internal(pa, i));
2356
0
      double x = pt->x;
2357
0
      double y = pt->y;
2358
0
      pt->x = a->afac * x + a->bfac * y + a->xoff;
2359
0
      pt->y = a->dfac * x + a->efac * y + a->yoff;
2360
0
    }
2361
0
  }
2362
0
}
2363
2364
/**
2365
 * WARNING, make sure you send in only 16-member double arrays
2366
 * or obviously things will go pear-shaped fast.
2367
 */
2368
#if 0
2369
static int gluInvertMatrix(const double *m, double *invOut)
2370
{
2371
    double inv[16], det;
2372
    int i;
2373
2374
    inv[0] = m[5]  * m[10] * m[15] -
2375
             m[5]  * m[11] * m[14] -
2376
             m[9]  * m[6]  * m[15] +
2377
             m[9]  * m[7]  * m[14] +
2378
             m[13] * m[6]  * m[11] -
2379
             m[13] * m[7]  * m[10];
2380
2381
    inv[4] = -m[4]  * m[10] * m[15] +
2382
              m[4]  * m[11] * m[14] +
2383
              m[8]  * m[6]  * m[15] -
2384
              m[8]  * m[7]  * m[14] -
2385
              m[12] * m[6]  * m[11] +
2386
              m[12] * m[7]  * m[10];
2387
2388
    inv[8] = m[4]  * m[9] * m[15] -
2389
             m[4]  * m[11] * m[13] -
2390
             m[8]  * m[5] * m[15] +
2391
             m[8]  * m[7] * m[13] +
2392
             m[12] * m[5] * m[11] -
2393
             m[12] * m[7] * m[9];
2394
2395
    inv[12] = -m[4]  * m[9] * m[14] +
2396
               m[4]  * m[10] * m[13] +
2397
               m[8]  * m[5] * m[14] -
2398
               m[8]  * m[6] * m[13] -
2399
               m[12] * m[5] * m[10] +
2400
               m[12] * m[6] * m[9];
2401
2402
    inv[1] = -m[1]  * m[10] * m[15] +
2403
              m[1]  * m[11] * m[14] +
2404
              m[9]  * m[2] * m[15] -
2405
              m[9]  * m[3] * m[14] -
2406
              m[13] * m[2] * m[11] +
2407
              m[13] * m[3] * m[10];
2408
2409
    inv[5] = m[0]  * m[10] * m[15] -
2410
             m[0]  * m[11] * m[14] -
2411
             m[8]  * m[2] * m[15] +
2412
             m[8]  * m[3] * m[14] +
2413
             m[12] * m[2] * m[11] -
2414
             m[12] * m[3] * m[10];
2415
2416
    inv[9] = -m[0]  * m[9] * m[15] +
2417
              m[0]  * m[11] * m[13] +
2418
              m[8]  * m[1] * m[15] -
2419
              m[8]  * m[3] * m[13] -
2420
              m[12] * m[1] * m[11] +
2421
              m[12] * m[3] * m[9];
2422
2423
    inv[13] = m[0]  * m[9] * m[14] -
2424
              m[0]  * m[10] * m[13] -
2425
              m[8]  * m[1] * m[14] +
2426
              m[8]  * m[2] * m[13] +
2427
              m[12] * m[1] * m[10] -
2428
              m[12] * m[2] * m[9];
2429
2430
    inv[2] = m[1]  * m[6] * m[15] -
2431
             m[1]  * m[7] * m[14] -
2432
             m[5]  * m[2] * m[15] +
2433
             m[5]  * m[3] * m[14] +
2434
             m[13] * m[2] * m[7] -
2435
             m[13] * m[3] * m[6];
2436
2437
    inv[6] = -m[0]  * m[6] * m[15] +
2438
              m[0]  * m[7] * m[14] +
2439
              m[4]  * m[2] * m[15] -
2440
              m[4]  * m[3] * m[14] -
2441
              m[12] * m[2] * m[7] +
2442
              m[12] * m[3] * m[6];
2443
2444
    inv[10] = m[0]  * m[5] * m[15] -
2445
              m[0]  * m[7] * m[13] -
2446
              m[4]  * m[1] * m[15] +
2447
              m[4]  * m[3] * m[13] +
2448
              m[12] * m[1] * m[7] -
2449
              m[12] * m[3] * m[5];
2450
2451
    inv[14] = -m[0]  * m[5] * m[14] +
2452
               m[0]  * m[6] * m[13] +
2453
               m[4]  * m[1] * m[14] -
2454
               m[4]  * m[2] * m[13] -
2455
               m[12] * m[1] * m[6] +
2456
               m[12] * m[2] * m[5];
2457
2458
    inv[3] = -m[1] * m[6] * m[11] +
2459
              m[1] * m[7] * m[10] +
2460
              m[5] * m[2] * m[11] -
2461
              m[5] * m[3] * m[10] -
2462
              m[9] * m[2] * m[7] +
2463
              m[9] * m[3] * m[6];
2464
2465
    inv[7] = m[0] * m[6] * m[11] -
2466
             m[0] * m[7] * m[10] -
2467
             m[4] * m[2] * m[11] +
2468
             m[4] * m[3] * m[10] +
2469
             m[8] * m[2] * m[7] -
2470
             m[8] * m[3] * m[6];
2471
2472
    inv[11] = -m[0] * m[5] * m[11] +
2473
               m[0] * m[7] * m[9] +
2474
               m[4] * m[1] * m[11] -
2475
               m[4] * m[3] * m[9] -
2476
               m[8] * m[1] * m[7] +
2477
               m[8] * m[3] * m[5];
2478
2479
    inv[15] = m[0] * m[5] * m[10] -
2480
              m[0] * m[6] * m[9] -
2481
              m[4] * m[1] * m[10] +
2482
              m[4] * m[2] * m[9] +
2483
              m[8] * m[1] * m[6] -
2484
              m[8] * m[2] * m[5];
2485
2486
    det = m[0] * inv[0] + m[1] * inv[4] + m[2] * inv[8] + m[3] * inv[12];
2487
2488
    if (det == 0)
2489
        return LW_FALSE;
2490
2491
    det = 1.0 / det;
2492
2493
    for (i = 0; i < 16; i++)
2494
        invOut[i] = inv[i] * det;
2495
2496
    return LW_TRUE;
2497
}
2498
#endif
2499
2500
/**
2501
 * Scale a pointarray.
2502
 */
2503
void
2504
ptarray_scale(POINTARRAY *pa, const POINT4D *fact)
2505
0
{
2506
0
  uint32_t i;
2507
0
  POINT4D p4d;
2508
0
  LWDEBUG(3, "ptarray_scale start");
2509
0
  for (i = 0; i < pa->npoints; i++)
2510
0
  {
2511
0
    getPoint4d_p(pa, i, &p4d);
2512
0
    p4d.x *= fact->x;
2513
0
    p4d.y *= fact->y;
2514
0
    p4d.z *= fact->z;
2515
0
    p4d.m *= fact->m;
2516
0
    ptarray_set_point4d(pa, i, &p4d);
2517
0
  }
2518
0
  LWDEBUG(3, "ptarray_scale end");
2519
0
}
2520
2521
int
2522
ptarray_startpoint(const POINTARRAY *pa, POINT4D *pt)
2523
0
{
2524
0
  return getPoint4d_p(pa, 0, pt);
2525
0
}
2526
2527
/*
2528
 * Stick an array of points to the given gridspec.
2529
 * Return "gridded" points in *outpts and their number in *outptsn.
2530
 *
2531
 * Two consecutive points falling on the same grid cell are collapsed
2532
 * into one single point.
2533
 *
2534
 */
2535
void
2536
ptarray_grid_in_place(POINTARRAY *pa, gridspec *grid)
2537
0
{
2538
0
  uint32_t j = 0;
2539
0
  POINT4D *p, *p_out = NULL;
2540
0
  double x, y, z = 0, m = 0;
2541
0
  uint32_t ndims = FLAGS_NDIMS(pa->flags);
2542
0
  uint32_t has_z = FLAGS_GET_Z(pa->flags);
2543
0
  uint32_t has_m = FLAGS_GET_M(pa->flags);
2544
2545
0
  for (uint32_t i = 0; i < pa->npoints; i++)
2546
0
  {
2547
    /* Look straight into the abyss */
2548
0
    p = (POINT4D *)(getPoint_internal(pa, i));
2549
0
    x = p->x;
2550
0
    y = p->y;
2551
0
    if (ndims > 2)
2552
0
      z = p->z;
2553
0
    if (ndims > 3)
2554
0
      m = p->m;
2555
2556
    /*
2557
     * See https://github.com/libgeos/geos/pull/956
2558
     * We use scale for rounding when gridsize is < 1 and
2559
     * gridsize for rounding when scale < 1.
2560
     */
2561
0
    if (grid->xsize > 0)
2562
0
    {
2563
0
      if (grid->xsize < 1)
2564
0
        x = rint((x - grid->ipx) * grid->xscale) / grid->xscale + grid->ipx;
2565
0
      else
2566
0
        x = rint((x - grid->ipx) / grid->xsize) * grid->xsize + grid->ipx;
2567
0
    }
2568
2569
0
    if (grid->ysize > 0)
2570
0
    {
2571
0
      if (grid->ysize < 1)
2572
0
        y = rint((y - grid->ipy) * grid->yscale) / grid->yscale + grid->ipy;
2573
0
      else
2574
0
        y = rint((y - grid->ipy) / grid->ysize) * grid->ysize + grid->ipy;
2575
0
    }
2576
2577
    /* Read and round this point */
2578
    /* Z is always in third position */
2579
0
    if (has_z && grid->zsize > 0)
2580
0
      z = rint((z - grid->ipz) / grid->zsize) * grid->zsize + grid->ipz;
2581
2582
    /* M might be in 3rd or 4th position */
2583
0
    if (has_m && grid->msize > 0)
2584
0
    {
2585
      /* In POINT ZM, M is in 4th position, in POINT M, M is in 3rd position which is Z in POINT4D */
2586
0
      if (has_z)
2587
0
        m = rint((m - grid->ipm) / grid->msize) * grid->msize + grid->ipm;
2588
0
      else
2589
0
        z = rint((z - grid->ipm) / grid->msize) * grid->msize + grid->ipm;
2590
0
    }
2591
2592
    /* Skip duplicates */
2593
0
    if (p_out && p_out->x == x && p_out->y == y && (ndims > 2 ? p_out->z == z : 1) &&
2594
0
        (ndims > 3 ? p_out->m == m : 1))
2595
0
    {
2596
0
      continue;
2597
0
    }
2598
2599
    /* Write rounded values into the next available point */
2600
0
    p_out = (POINT4D *)(getPoint_internal(pa, j++));
2601
0
    p_out->x = x;
2602
0
    p_out->y = y;
2603
0
    if (ndims > 2)
2604
0
      p_out->z = z;
2605
0
    if (ndims > 3)
2606
0
      p_out->m = m;
2607
0
  }
2608
2609
  /* Update output ptarray length */
2610
0
  pa->npoints = j;
2611
0
  return;
2612
0
}
2613
2614
int
2615
ptarray_npoints_in_rect(const POINTARRAY *pa, const GBOX *gbox)
2616
0
{
2617
0
  const POINT2D *pt;
2618
0
  int n = 0;
2619
0
  uint32_t i;
2620
0
  for (i = 0; i < pa->npoints; i++)
2621
0
  {
2622
0
    pt = getPoint2d_cp(pa, i);
2623
0
    if (gbox_contains_point2d(gbox, pt))
2624
0
      n++;
2625
0
  }
2626
0
  return n;
2627
0
}
2628
2629
/*
2630
 * Reorder the vertices of a closed pointarray so that the
2631
 * given point is the first/last one.
2632
 *
2633
 * Error out if pointarray is not closed or it does not
2634
 * contain the given point.
2635
 */
2636
int
2637
ptarray_scroll_in_place(POINTARRAY *pa, const POINT4D *pt)
2638
0
{
2639
0
  POINTARRAY *tmp;
2640
0
  int found;
2641
0
  uint32_t it;
2642
0
  int ptsize;
2643
2644
0
  if (!ptarray_is_closed_2d(pa))
2645
0
  {
2646
0
    lwerror("ptarray_scroll_in_place: input POINTARRAY is not closed");
2647
0
    return LW_FAILURE;
2648
0
  }
2649
2650
0
  ptsize = ptarray_point_size(pa);
2651
2652
  /* Find the point in the array */
2653
0
  found = 0;
2654
0
  for (it = 0; it < pa->npoints; ++it)
2655
0
  {
2656
0
    if (!memcmp(getPoint_internal(pa, it), pt, ptsize))
2657
0
    {
2658
0
      found = 1;
2659
0
      break;
2660
0
    }
2661
0
  }
2662
2663
0
  if (!found)
2664
0
  {
2665
0
    lwerror("ptarray_scroll_in_place: input POINTARRAY does not contain the given point");
2666
0
    return LW_FAILURE;
2667
0
  }
2668
2669
0
  if (0 == it)
2670
0
  {
2671
    /* Point is already the start/end point, just clone the input */
2672
0
    return LW_SUCCESS;
2673
0
  }
2674
2675
  /* TODO: reduce allocations */
2676
0
  tmp = ptarray_construct(FLAGS_GET_Z(pa->flags), FLAGS_GET_M(pa->flags), pa->npoints);
2677
2678
0
  memset(getPoint_internal(tmp, 0), 0, (size_t)ptsize * pa->npoints);
2679
  /* Copy the block from found point to last point into the output array */
2680
0
  memcpy(getPoint_internal(tmp, 0), getPoint_internal(pa, it), (size_t)ptsize * (pa->npoints - it));
2681
2682
  /* Copy the block from second point to the found point into the last portion of the
2683
   * return */
2684
0
  memcpy(getPoint_internal(tmp, pa->npoints - it), getPoint_internal(pa, 1), (size_t)ptsize * (it));
2685
2686
  /* Copy the resulting pointarray back to source one */
2687
0
  memcpy(getPoint_internal(pa, 0), getPoint_internal(tmp, 0), (size_t)ptsize * (pa->npoints));
2688
2689
0
  ptarray_free(tmp);
2690
2691
0
  return LW_SUCCESS;
2692
0
}