Coverage Report

Created: 2026-12-01 06:12

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/postgis/liblwgeom/lwstroke.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) 2001-2006 Refractions Research Inc.
22
 * Copyright (C) 2017      Sandro Santilli <strk@kbt.io>
23
 * Copyright (C) 2018      Daniel Baston <dbaston@gmail.com>
24
 * Copyright (C) 2026      Darafei Praliaskouski <me@komzpa.net>
25
 *
26
 **********************************************************************/
27
28
#include <stdio.h>
29
#include <stdlib.h>
30
#include <stdarg.h>
31
#include <string.h>
32
#include <limits.h>
33
34
#include "../postgis_config.h"
35
36
/*#define POSTGIS_DEBUG_LEVEL 3*/
37
38
#include "lwgeom_log.h"
39
40
#include "liblwgeom_internal.h"
41
42
LWGEOM *pta_unstroke(const POINTARRAY *points, int32_t srid);
43
LWGEOM *lwline_unstroke(const LWLINE *line);
44
LWGEOM *lwpolygon_unstroke(const LWPOLY *poly);
45
LWGEOM *lwmline_unstroke(const LWMLINE *mline);
46
LWGEOM *lwmpolygon_unstroke(const LWMPOLY *mpoly);
47
LWGEOM *lwcollection_unstroke(const LWCOLLECTION *c);
48
LWGEOM *lwgeom_unstroke(const LWGEOM *geom);
49
static LWLINE *
50
lwnurbscurve_linearize(const LWNURBSCURVE *curve, double tol, LW_LINEARIZE_TOLERANCE_TYPE tolerance_type, int flags);
51
52
0
#define NURBS_MIN_LINEARIZE_SEGMENTS 8
53
0
#define NURBS_MAX_LINEARIZE_SEGMENTS 10000
54
55
/*
56
 * Determines (recursively in the case of collections) whether the geometry
57
 * contains at least on arc geometry or segment.
58
 */
59
int
60
lwgeom_has_arc(const LWGEOM *geom)
61
0
{
62
0
  LWCOLLECTION *col;
63
0
  uint32_t i;
64
65
0
  LWDEBUG(2, "lwgeom_has_arc called.");
66
67
0
  switch (geom->type)
68
0
  {
69
0
  case POINTTYPE:
70
0
  case LINETYPE:
71
0
  case POLYGONTYPE:
72
0
  case TRIANGLETYPE:
73
0
  case MULTIPOINTTYPE:
74
0
  case MULTILINETYPE:
75
0
  case MULTIPOLYGONTYPE:
76
0
  case POLYHEDRALSURFACETYPE:
77
0
  case TINTYPE:
78
0
    return LW_FALSE;
79
0
  case CIRCSTRINGTYPE:
80
0
  case NURBSCURVETYPE:
81
0
    return LW_TRUE;
82
  /* It's a collection that MAY contain an arc */
83
0
  default:
84
0
    col = (LWCOLLECTION *)geom;
85
0
    for (i = 0; i < col->ngeoms; i++)
86
0
    {
87
0
      if (lwgeom_has_arc(col->geoms[i]) == LW_TRUE)
88
0
        return LW_TRUE;
89
0
    }
90
0
    return LW_FALSE;
91
0
  }
92
0
}
93
94
int
95
lwgeom_type_arc(const LWGEOM *geom)
96
0
{
97
0
  switch (geom->type)
98
0
  {
99
0
  case COMPOUNDTYPE:
100
0
  case CIRCSTRINGTYPE:
101
0
  case NURBSCURVETYPE:
102
0
  case CURVEPOLYTYPE:
103
0
  case MULTISURFACETYPE:
104
0
  case MULTICURVETYPE:
105
0
    return LW_TRUE;
106
0
  default:
107
0
    return LW_FALSE;
108
0
  }
109
0
}
110
111
/*******************************************************************************
112
 * Begin curve segmentize functions
113
 ******************************************************************************/
114
115
static double
116
interpolate_arc(double angle, double a1, double a2, double a3, double zm1, double zm2, double zm3)
117
0
{
118
0
  LWDEBUGF(4,
119
0
     "angle %.05g a1 %.05g a2 %.05g a3 %.05g zm1 %.05g zm2 %.05g zm3 %.05g",
120
0
     angle,
121
0
     a1,
122
0
     a2,
123
0
     a3,
124
0
     zm1,
125
0
     zm2,
126
0
     zm3);
127
  /* Counter-clockwise sweep */
128
0
  if (a1 < a2)
129
0
  {
130
0
    if (angle <= a2)
131
0
      return zm1 + (zm2 - zm1) * (angle - a1) / (a2 - a1);
132
0
    else
133
0
      return zm2 + (zm3 - zm2) * (angle - a2) / (a3 - a2);
134
0
  }
135
  /* Clockwise sweep */
136
0
  else
137
0
  {
138
0
    if (angle >= a2)
139
0
      return zm1 + (zm2 - zm1) * (a1 - angle) / (a1 - a2);
140
0
    else
141
0
      return zm2 + (zm3 - zm2) * (a2 - angle) / (a2 - a3);
142
0
  }
143
0
}
144
145
/* Compute the angle covered by a single segment such that
146
 * a given number of segments per quadrant is achieved. */
147
static double
148
angle_increment_using_segments_per_quad(double tol)
149
0
{
150
0
  double increment;
151
0
  int perQuad = rint(tol);
152
  // error out if tol != perQuad ? (not-round)
153
0
  if (perQuad != tol)
154
0
  {
155
0
    lwerror("lwarc_linearize: segments per quadrant must be an integer value, got %.15g", tol);
156
0
    return -1;
157
0
  }
158
0
  if (perQuad < 1)
159
0
  {
160
0
    lwerror("lwarc_linearize: segments per quadrant must be at least 1, got %d", perQuad);
161
0
    return -1;
162
0
  }
163
0
  increment = fabs(M_PI_2 / perQuad);
164
0
  LWDEBUGF(
165
0
      2, "lwarc_linearize: perQuad:%d, increment:%g (%g degrees)", perQuad, increment, increment * 180 / M_PI);
166
167
0
  return increment;
168
0
}
169
170
/* Compute the angle covered by a single quadrant such that
171
 * the segment deviates from the arc by no more than a given
172
 * amount. */
173
static double
174
angle_increment_using_max_deviation(double max_deviation, double radius)
175
0
{
176
0
  double increment, halfAngle, maxErr;
177
0
  if (max_deviation <= 0)
178
0
  {
179
0
    lwerror("lwarc_linearize: max deviation must be bigger than 0, got %.15g", max_deviation);
180
0
    return -1;
181
0
  }
182
183
  /*
184
   * Ref: https://en.wikipedia.org/wiki/Sagitta_(geometry)
185
   *
186
   * An arc "sagitta" (distance between middle point of arc and
187
   * middle point of corresponding chord) is defined as:
188
   *
189
   *   sagitta = radius * ( 1 - cos( angle ) );
190
   *
191
   * We want our sagitta to be at most "tolerance" long,
192
   * and we want to find out angle, so we use the inverse
193
   * formula:
194
   *
195
   *   tol = radius * ( 1 - cos( angle ) );
196
   *   1 - cos( angle ) =  tol/radius
197
   *   - cos( angle ) =  tol/radius - 1
198
   *   cos( angle ) =  - tol/radius + 1
199
   *   angle = acos( 1 - tol/radius )
200
   *
201
   * Constraints: 1.0 - tol/radius must be between -1 and 1
202
   * which means tol must be between 0 and 2 times
203
   * the radius, which makes sense as you cannot have a
204
   * sagitta bigger than twice the radius!
205
   *
206
   */
207
0
  maxErr = max_deviation;
208
0
  if (maxErr > radius * 2)
209
0
  {
210
0
    maxErr = radius * 2;
211
0
    LWDEBUGF(2,
212
0
       "lwarc_linearize: tolerance %g is too big, "
213
0
       "using arc-max 2 * radius == %g",
214
0
       max_deviation,
215
0
       maxErr);
216
0
  }
217
0
  do
218
0
  {
219
0
    halfAngle = acos(1.0 - maxErr / radius);
220
    /* TODO: avoid a loop here, going rather straight to
221
     *       a minimum angle value */
222
0
    if (halfAngle != 0)
223
0
      break;
224
0
    LWDEBUGF(2,
225
0
       "lwarc_linearize: tolerance %g is too small for this arc"
226
0
       " to compute approximation angle, doubling it",
227
0
       maxErr);
228
0
    maxErr *= 2;
229
0
  } while (1);
230
0
  increment = 2 * halfAngle;
231
0
  LWDEBUGF(2,
232
0
     "lwarc_linearize: maxDiff:%g, radius:%g, halfAngle:%g, increment:%g (%g degrees)",
233
0
     max_deviation,
234
0
     radius,
235
0
     halfAngle,
236
0
     increment,
237
0
     increment * 180 / M_PI);
238
239
0
  return increment;
240
0
}
241
242
/* Check that a given angle is positive and, if so, take
243
 * it to be the angle covered by a single segment. */
244
static double
245
angle_increment_using_max_angle(double tol)
246
0
{
247
0
  if (tol <= 0)
248
0
  {
249
0
    lwerror("lwarc_linearize: max angle must be bigger than 0, got %.15g", tol);
250
0
    return -1;
251
0
  }
252
253
0
  return tol;
254
0
}
255
256
static int
257
lwstroke_checked_segment_count(double count)
258
0
{
259
0
  if (!(count >= 0) || count > INT_MAX - 1)
260
0
  {
261
0
    lwerror("%g segments required to meet the tolerance, at most %d are supported", count, INT_MAX - 1);
262
0
    return -1;
263
0
  }
264
0
  return count;
265
0
}
266
267
static void
268
lwstroke_free_geom_array(LWGEOM **geoms, uint32_t count)
269
0
{
270
0
  for (uint32_t i = 0; i < count; i++)
271
0
    lwgeom_free(geoms[i]);
272
0
  lwfree(geoms);
273
0
}
274
275
static void
276
lwstroke_free_ptarray_array(POINTARRAY **ptarrays, uint32_t count)
277
0
{
278
0
  for (uint32_t i = 0; i < count; i++)
279
0
    ptarray_free(ptarrays[i]);
280
0
  lwfree(ptarrays);
281
0
}
282
283
/**
284
 * Segmentize an arc
285
 *
286
 * Does not add the final vertex
287
 *
288
 * @param to POINTARRAY to append segmentized vertices to
289
 * @param p1 first point defining the arc
290
 * @param p2 second point defining the arc
291
 * @param p3 third point defining the arc
292
 * @param tol tolerance, semantic driven by tolerance_type
293
 * @param tolerance_type see LW_LINEARIZE_TOLERANCE_TYPE
294
 * @param flags LW_LINEARIZE_FLAGS
295
 *
296
 * @return number of points appended (0 if collinear),
297
 *         or -1 on error (lwerror would be called).
298
 *
299
 */
300
static int
301
lwarc_linearize(POINTARRAY *to,
302
    const POINT4D *p1,
303
    const POINT4D *p2,
304
    const POINT4D *p3,
305
    double tol,
306
    LW_LINEARIZE_TOLERANCE_TYPE tolerance_type,
307
    int flags)
308
0
{
309
0
  POINT2D center;
310
0
  POINT2D *t1 = (POINT2D *)p1;
311
0
  POINT2D *t2 = (POINT2D *)p2;
312
0
  POINT2D *t3 = (POINT2D *)p3;
313
0
  POINT4D pt;
314
0
  int p2_side = 0;
315
0
  int clockwise = LW_TRUE;
316
0
  double radius;    /* Arc radius */
317
0
  double increment; /* Angle per segment */
318
0
  double angle_shift = 0;
319
0
  double a1, a2, a3;
320
0
  POINTARRAY *pa;
321
0
  int is_circle = LW_FALSE;
322
0
  int points_added = 0;
323
0
  int reverse = 0;
324
0
  int segments = 0;
325
326
0
  LWDEBUG(2, "lwarc_linearize called.");
327
328
0
  LWDEBUGF(2,
329
0
     " curve is CIRCULARSTRING(%.15g %.15f, %.15f %.15f, %.15f %15f)",
330
0
     t1->x,
331
0
     t1->y,
332
0
     t2->x,
333
0
     t2->y,
334
0
     t3->x,
335
0
     t3->y);
336
337
0
  p2_side = lw_segment_side(t1, t3, t2);
338
339
0
  LWDEBUGF(2, " p2 side is %d", p2_side);
340
341
  /* Force counterclockwise scan if SYMMETRIC operation is requested */
342
0
  if (p2_side == -1 && flags & LW_LINEARIZE_FLAG_SYMMETRIC)
343
0
  {
344
    /* swap p1-p3 */
345
0
    t1 = (POINT2D *)p3;
346
0
    t3 = (POINT2D *)p1;
347
0
    p1 = (POINT4D *)t1;
348
0
    p3 = (POINT4D *)t3;
349
0
    p2_side = 1;
350
0
    reverse = 1;
351
0
  }
352
353
0
  radius = lw_arc_center(t1, t2, t3, &center);
354
0
  LWDEBUGF(2, " center is POINT(%.15g %.15g) - radius:%g", center.x, center.y, radius);
355
356
  /* Matched start/end points imply circle */
357
0
  if (p1->x == p3->x && p1->y == p3->y)
358
0
    is_circle = LW_TRUE;
359
360
  /* Negative radius signals straight line, p1/p2/p3 are collinear */
361
0
  if ((radius < 0.0 || p2_side == 0) && !is_circle)
362
0
    return 0;
363
364
  /* The side of the p1/p3 line that p2 falls on dictates the sweep
365
     direction from p1 to p3. */
366
0
  if (p2_side == -1)
367
0
    clockwise = LW_TRUE;
368
0
  else
369
0
    clockwise = LW_FALSE;
370
371
  /* Compute the increment (angle per segment) depending on
372
   * our tolerance type. */
373
0
  switch (tolerance_type)
374
0
  {
375
0
  case LW_LINEARIZE_TOLERANCE_TYPE_SEGS_PER_QUAD:
376
0
    increment = angle_increment_using_segments_per_quad(tol);
377
0
    break;
378
0
  case LW_LINEARIZE_TOLERANCE_TYPE_MAX_DEVIATION:
379
0
    increment = angle_increment_using_max_deviation(tol, radius);
380
0
    break;
381
0
  case LW_LINEARIZE_TOLERANCE_TYPE_MAX_ANGLE:
382
0
    increment = angle_increment_using_max_angle(tol);
383
0
    break;
384
0
  default:
385
0
    lwerror("lwarc_linearize: unsupported tolerance type %d", tolerance_type);
386
0
    return -1;
387
0
  }
388
389
0
  if (increment < 0)
390
0
  {
391
    /* Error occurred in increment calculation somewhere
392
     * (lwerror already called)
393
     */
394
0
    return -1;
395
0
  }
396
397
  /* Angles of each point that defines the arc section */
398
0
  a1 = atan2(p1->y - center.y, p1->x - center.x);
399
0
  a2 = atan2(p2->y - center.y, p2->x - center.x);
400
0
  a3 = atan2(p3->y - center.y, p3->x - center.x);
401
402
0
  LWDEBUGF(2,
403
0
     "lwarc_linearize A1:%g (%g) A2:%g (%g) A3:%g (%g)",
404
0
     a1,
405
0
     a1 * 180 / M_PI,
406
0
     a2,
407
0
     a2 * 180 / M_PI,
408
0
     a3,
409
0
     a3 * 180 / M_PI);
410
411
  /* Calculate total arc angle, in radians */
412
0
  double total_angle = clockwise ? a1 - a3 : a3 - a1;
413
0
  if (total_angle <= 0)
414
0
    total_angle += M_PI * 2;
415
416
  /* At extreme tolerance values (very low or very high, depending on
417
   * the semantic) we may cause our arc to collapse. In this case,
418
   * we want shrink the increment enough so that we get two segments
419
   * for a standard arc, or three segments for a complete circle. */
420
0
  int min_segs = is_circle ? 3 : 2;
421
0
  double segments_needed = ceil(total_angle / increment);
422
423
  /* Reserve room for endpoint arithmetic and validate each recomputed count. */
424
0
  segments = lwstroke_checked_segment_count(segments_needed);
425
0
  if (segments < 0)
426
0
    return -1;
427
0
  if (segments < min_segs)
428
0
  {
429
0
    segments = min_segs;
430
0
    increment = total_angle / min_segs;
431
0
  }
432
433
0
  if (flags & LW_LINEARIZE_FLAG_SYMMETRIC)
434
0
  {
435
0
    LWDEBUGF(2, "lwarc_linearize SYMMETRIC requested - total angle %g deg", total_angle * 180 / M_PI);
436
437
0
    if (flags & LW_LINEARIZE_FLAG_RETAIN_ANGLE)
438
0
    {
439
      /* Number of complete steps */
440
0
      segments = lwstroke_checked_segment_count(trunc(total_angle / increment));
441
0
      if (segments < 0)
442
0
        return -1;
443
444
      /* Figure out the angle remainder, i.e. the amount of the angle
445
       * that is left after we can take no more complete angle
446
       * increments. */
447
0
      double angle_remainder = total_angle - (increment * segments);
448
449
      /* Shift the starting angle by half of the remainder. This
450
       * will have the effect of evenly distributing the remainder
451
       * among the first and last segments in the arc. */
452
0
      angle_shift = angle_remainder / 2.0;
453
454
0
      LWDEBUGF(2,
455
0
         "lwarc_linearize RETAIN_ANGLE operation requested - "
456
0
         "total angle %g, steps %d, increment %g, remainder %g",
457
0
         total_angle * 180 / M_PI,
458
0
         segments,
459
0
         increment * 180 / M_PI,
460
0
         angle_remainder * 180 / M_PI);
461
0
    }
462
0
    else
463
0
    {
464
      /* Number of segments in output */
465
0
      segments = lwstroke_checked_segment_count(ceil(total_angle / increment));
466
0
      if (segments < 0)
467
0
        return -1;
468
      /* Tweak increment to be regular for all the arc */
469
0
      increment = total_angle / segments;
470
471
0
      LWDEBUGF(2,
472
0
         "lwarc_linearize SYMMETRIC operation requested - "
473
0
         "total angle %g degrees - LINESTRING(%g %g,%g %g,%g %g) - S:%d -   I:%g",
474
0
         total_angle * 180 / M_PI,
475
0
         p1->x,
476
0
         p1->y,
477
0
         center.x,
478
0
         center.y,
479
0
         p3->x,
480
0
         p3->y,
481
0
         segments,
482
0
         increment * 180 / M_PI);
483
0
    }
484
0
  }
485
486
  /* p2 on left side => clockwise sweep */
487
0
  if (clockwise)
488
0
  {
489
0
    LWDEBUG(2, " Clockwise sweep");
490
0
    increment *= -1;
491
0
    angle_shift *= -1;
492
    /* Adjust a3 down so we can decrement from a1 to a3 cleanly */
493
0
    if (a3 > a1)
494
0
      a3 -= 2.0 * M_PI;
495
0
    if (a2 > a1)
496
0
      a2 -= 2.0 * M_PI;
497
0
  }
498
  /* p2 on right side => counter-clockwise sweep */
499
0
  else
500
0
  {
501
0
    LWDEBUG(2, " Counterclockwise sweep");
502
    /* Adjust a3 up so we can increment from a1 to a3 cleanly */
503
0
    if (a3 < a1)
504
0
      a3 += 2.0 * M_PI;
505
0
    if (a2 < a1)
506
0
      a2 += 2.0 * M_PI;
507
0
  }
508
509
  /* Override angles for circle case */
510
0
  if (is_circle)
511
0
  {
512
0
    increment = fabs(increment);
513
0
    segments = ceil(total_angle / increment);
514
0
    if (segments < 3)
515
0
    {
516
0
      segments = 3;
517
0
      increment = total_angle / 3;
518
0
    }
519
0
    a3 = a1 + 2.0 * M_PI;
520
0
    a2 = a1 + M_PI;
521
0
    clockwise = LW_FALSE;
522
0
    angle_shift = 0.0;
523
0
  }
524
525
0
  LWDEBUGF(2, "lwarc_linearize angle_shift:%g, increment:%g", angle_shift * 180 / M_PI, increment * 180 / M_PI);
526
527
0
  if (reverse)
528
0
  {
529
    /* Append points in order to a temporary POINTARRAY and
530
     * reverse them before writing to the output POINTARRAY. */
531
0
    const int capacity = 8; /* TODO: compute exactly ? */
532
0
    pa = ptarray_construct_empty(ptarray_has_z(to), ptarray_has_m(to), capacity);
533
0
  }
534
0
  else
535
0
  {
536
    /* Append points directly to the output POINTARRAY,
537
     * starting with p1. */
538
0
    pa = to;
539
540
0
    ptarray_append_point(pa, p1, LW_FALSE);
541
0
    ++points_added;
542
0
  }
543
544
  /* Sweep from a1 to a3 */
545
0
  int seg_start = 1; /* First point is added manually */
546
0
  int seg_end = segments;
547
0
  if (angle_shift != 0.0)
548
0
  {
549
    /* When we have extra angles we need to add the extra segments at the
550
     * start and end that cover those parts of the arc */
551
0
    seg_start = 0;
552
0
    seg_end = segments + 1;
553
0
  }
554
0
  LWDEBUGF(2,
555
0
     "a1:%g (%g deg), a3:%g (%g deg), inc:%g, shi:%g, cw:%d",
556
0
     a1,
557
0
     a1 * 180 / M_PI,
558
0
     a3,
559
0
     a3 * 180 / M_PI,
560
0
     increment,
561
0
     angle_shift,
562
0
     clockwise);
563
0
  for (int s = seg_start; s < seg_end; s++)
564
0
  {
565
0
    double angle = a1 + increment * s + angle_shift;
566
0
    LWDEBUGF(2, " SA: %g ( %g deg )", angle, angle * 180 / M_PI);
567
0
    pt.x = center.x + radius * cos(angle);
568
0
    pt.y = center.y + radius * sin(angle);
569
0
    pt.z = interpolate_arc(angle, a1, a2, a3, p1->z, p2->z, p3->z);
570
0
    pt.m = interpolate_arc(angle, a1, a2, a3, p1->m, p2->m, p3->m);
571
0
    ptarray_append_point(pa, &pt, LW_FALSE);
572
0
    ++points_added;
573
0
  }
574
575
  /* Ensure the final point is EXACTLY the same as the first for the circular case */
576
0
  if (is_circle)
577
0
  {
578
0
    ptarray_remove_point(pa, pa->npoints - 1);
579
0
    ptarray_append_point(pa, p1, LW_FALSE);
580
0
  }
581
582
0
  if (reverse)
583
0
  {
584
0
    int i;
585
0
    ptarray_append_point(to, p3, LW_FALSE);
586
0
    for (i = pa->npoints; i > 0; i--)
587
0
    {
588
0
      getPoint4d_p(pa, i - 1, &pt);
589
0
      ptarray_append_point(to, &pt, LW_FALSE);
590
0
    }
591
0
    ptarray_free(pa);
592
0
  }
593
594
0
  return points_added;
595
0
}
596
597
/*
598
 * @param icurve input curve
599
 * @param tol tolerance, semantic driven by tolerance_type
600
 * @param tolerance_type see LW_LINEARIZE_TOLERANCE_TYPE
601
 * @param flags see flags in lwarc_linearize
602
 *
603
 * @return a newly allocated LWLINE
604
 */
605
static LWLINE *
606
lwcircstring_linearize(const LWCIRCSTRING *icurve, double tol, LW_LINEARIZE_TOLERANCE_TYPE tolerance_type, int flags)
607
0
{
608
0
  LWLINE *oline;
609
0
  POINTARRAY *ptarray;
610
0
  uint32_t i, j;
611
0
  POINT4D p1, p2, p3, p4;
612
0
  int ret;
613
614
0
  LWDEBUGF(2, "lwcircstring_linearize called., dim = %d", icurve->points->flags);
615
616
0
  ptarray = ptarray_construct_empty(FLAGS_GET_Z(icurve->points->flags), FLAGS_GET_M(icurve->points->flags), 64);
617
618
0
  for (i = 2; i < icurve->points->npoints; i += 2)
619
0
  {
620
0
    LWDEBUGF(3, "lwcircstring_linearize: arc ending at point %d", i);
621
622
0
    getPoint4d_p(icurve->points, i - 2, &p1);
623
0
    getPoint4d_p(icurve->points, i - 1, &p2);
624
0
    getPoint4d_p(icurve->points, i, &p3);
625
626
0
    ret = lwarc_linearize(ptarray, &p1, &p2, &p3, tol, tolerance_type, flags);
627
0
    if (ret > 0)
628
0
    {
629
0
      LWDEBUGF(3, "lwcircstring_linearize: generated %d points", ptarray->npoints);
630
0
    }
631
0
    else if (ret == 0)
632
0
    {
633
0
      LWDEBUG(3, "lwcircstring_linearize: points are colinear, returning curve points as line");
634
635
0
      for (j = i - 2; j < i; j++)
636
0
      {
637
0
        getPoint4d_p(icurve->points, j, &p4);
638
0
        ptarray_append_point(ptarray, &p4, LW_TRUE);
639
0
      }
640
0
    }
641
0
    else
642
0
    {
643
      /* An error occurred, lwerror should have been called by now */
644
0
      ptarray_free(ptarray);
645
0
      return NULL;
646
0
    }
647
0
  }
648
0
  if (icurve->points->npoints > 0)
649
0
  {
650
0
    getPoint4d_p(icurve->points, icurve->points->npoints - 1, &p1);
651
0
    ptarray_append_point(ptarray, &p1, LW_FALSE);
652
0
  }
653
654
0
  oline = lwline_construct(icurve->srid, NULL, ptarray);
655
0
  return oline;
656
0
}
657
658
/*
659
 * @param icompound input compound curve
660
 * @param tol tolerance, semantic driven by tolerance_type
661
 * @param tolerance_type see LW_LINEARIZE_TOLERANCE_TYPE
662
 * @param flags see flags in lwarc_linearize
663
 *
664
 * @return a newly allocated LWLINE
665
 */
666
static LWLINE *
667
lwcompound_linearize(const LWCOMPOUND *icompound, double tol, LW_LINEARIZE_TOLERANCE_TYPE tolerance_type, int flags)
668
0
{
669
0
  LWGEOM *geom;
670
0
  POINTARRAY *ptarray = NULL;
671
0
  LWLINE *tmp = NULL;
672
0
  uint32_t i, j;
673
0
  POINT4D p;
674
675
0
  LWDEBUG(2, "lwcompound_stroke called.");
676
677
0
  ptarray = ptarray_construct_empty(FLAGS_GET_Z(icompound->flags), FLAGS_GET_M(icompound->flags), 64);
678
679
0
  for (i = 0; i < icompound->ngeoms; i++)
680
0
  {
681
0
    geom = icompound->geoms[i];
682
0
    if (geom->type == CIRCSTRINGTYPE)
683
0
    {
684
0
      tmp = lwcircstring_linearize((LWCIRCSTRING *)geom, tol, tolerance_type, flags);
685
0
      if (!tmp)
686
0
      {
687
0
        ptarray_free(ptarray);
688
0
        return NULL;
689
0
      }
690
0
      for (j = 0; j < tmp->points->npoints; j++)
691
0
      {
692
0
        getPoint4d_p(tmp->points, j, &p);
693
0
        ptarray_append_point(ptarray, &p, LW_TRUE);
694
0
      }
695
0
      lwline_free(tmp);
696
0
    }
697
0
    else if (geom->type == LINETYPE)
698
0
    {
699
0
      tmp = (LWLINE *)geom;
700
0
      for (j = 0; j < tmp->points->npoints; j++)
701
0
      {
702
0
        getPoint4d_p(tmp->points, j, &p);
703
0
        ptarray_append_point(ptarray, &p, LW_TRUE);
704
0
      }
705
0
    }
706
0
    else if (geom->type == NURBSCURVETYPE)
707
0
    {
708
0
      tmp = lwnurbscurve_linearize((LWNURBSCURVE *)geom, tol, tolerance_type, flags);
709
0
      if (!tmp)
710
0
      {
711
0
        ptarray_free(ptarray);
712
0
        return NULL;
713
0
      }
714
0
      for (j = 0; j < tmp->points->npoints; j++)
715
0
      {
716
0
        getPoint4d_p(tmp->points, j, &p);
717
0
        ptarray_append_point(ptarray, &p, LW_TRUE);
718
0
      }
719
0
      lwline_free(tmp);
720
0
    }
721
0
    else
722
0
    {
723
0
      lwerror("%s: Unsupported geometry type: %s", __func__, lwtype_name(geom->type));
724
0
      ptarray_free(ptarray);
725
0
      return NULL;
726
0
    }
727
0
  }
728
729
0
  ptarray_remove_repeated_points_in_place(ptarray, 0.0, 2);
730
0
  return lwline_construct(icompound->srid, NULL, ptarray);
731
0
}
732
733
/*
734
 * @param icompound input curve polygon
735
 * @param tol tolerance, semantic driven by tolerance_type
736
 * @param tolerance_type see LW_LINEARIZE_TOLERANCE_TYPE
737
 * @param flags see flags in lwarc_linearize
738
 *
739
 * @return a newly allocated LWPOLY
740
 */
741
static LWPOLY *
742
lwcurvepoly_linearize(const LWCURVEPOLY *curvepoly, double tol, LW_LINEARIZE_TOLERANCE_TYPE tolerance_type, int flags)
743
0
{
744
0
  LWPOLY *ogeom;
745
0
  LWGEOM *tmp;
746
0
  LWLINE *line;
747
0
  POINTARRAY **ptarray;
748
0
  uint32_t i;
749
750
0
  LWDEBUG(2, "lwcurvepoly_linearize called.");
751
752
0
  ptarray = lwalloc(sizeof(POINTARRAY *) * curvepoly->nrings);
753
754
0
  for (i = 0; i < curvepoly->nrings; i++)
755
0
  {
756
0
    tmp = curvepoly->rings[i];
757
0
    if (tmp->type == CIRCSTRINGTYPE)
758
0
    {
759
0
      line = lwcircstring_linearize((LWCIRCSTRING *)tmp, tol, tolerance_type, flags);
760
0
      if (!line)
761
0
      {
762
0
        lwstroke_free_ptarray_array(ptarray, i);
763
0
        return NULL;
764
0
      }
765
0
      ptarray[i] = ptarray_clone_deep(line->points);
766
0
      lwline_free(line);
767
0
    }
768
0
    else if (tmp->type == LINETYPE)
769
0
    {
770
0
      line = (LWLINE *)tmp;
771
0
      ptarray[i] = ptarray_clone_deep(line->points);
772
0
    }
773
0
    else if (tmp->type == COMPOUNDTYPE)
774
0
    {
775
0
      line = lwcompound_linearize((LWCOMPOUND *)tmp, tol, tolerance_type, flags);
776
0
      if (!line)
777
0
      {
778
0
        lwstroke_free_ptarray_array(ptarray, i);
779
0
        return NULL;
780
0
      }
781
0
      ptarray[i] = ptarray_clone_deep(line->points);
782
0
      lwline_free(line);
783
0
    }
784
0
    else if (tmp->type == NURBSCURVETYPE)
785
0
    {
786
0
      line = lwnurbscurve_linearize((LWNURBSCURVE *)tmp, tol, tolerance_type, flags);
787
0
      if (!line)
788
0
      {
789
0
        lwstroke_free_ptarray_array(ptarray, i);
790
0
        return NULL;
791
0
      }
792
0
      ptarray[i] = ptarray_clone_deep(line->points);
793
0
      lwline_free(line);
794
0
    }
795
0
    else
796
0
    {
797
0
      lwerror("Invalid ring type found in CurvePoly.");
798
0
      lwstroke_free_ptarray_array(ptarray, i);
799
0
      return NULL;
800
0
    }
801
0
  }
802
803
0
  ogeom = lwpoly_construct(curvepoly->srid, NULL, curvepoly->nrings, ptarray);
804
0
  return ogeom;
805
0
}
806
807
/* Kept for backward compatibility - TODO: drop */
808
LWPOLY *
809
lwcurvepoly_stroke(const LWCURVEPOLY *curvepoly, uint32_t perQuad)
810
0
{
811
0
  return lwcurvepoly_linearize(curvepoly, perQuad, LW_LINEARIZE_TOLERANCE_TYPE_SEGS_PER_QUAD, 0);
812
0
}
813
814
/**
815
 * @param mcurve input compound curve
816
 * @param tol tolerance, semantic driven by tolerance_type
817
 * @param tolerance_type see LW_LINEARIZE_TOLERANCE_TYPE
818
 * @param flags see flags in lwarc_linearize
819
 *
820
 * @return a newly allocated LWMLINE
821
 */
822
static LWMLINE *
823
lwmcurve_linearize(const LWMCURVE *mcurve, double tol, LW_LINEARIZE_TOLERANCE_TYPE type, int flags)
824
0
{
825
0
  LWMLINE *ogeom;
826
0
  LWGEOM **lines;
827
0
  uint32_t i;
828
829
0
  LWDEBUGF(2, "lwmcurve_linearize called, geoms=%d, dim=%d.", mcurve->ngeoms, FLAGS_NDIMS(mcurve->flags));
830
831
0
  lines = lwalloc(sizeof(LWGEOM *) * mcurve->ngeoms);
832
833
0
  for (i = 0; i < mcurve->ngeoms; i++)
834
0
  {
835
0
    const LWGEOM *tmp = mcurve->geoms[i];
836
0
    if (tmp->type == CIRCSTRINGTYPE)
837
0
    {
838
0
      lines[i] = (LWGEOM *)lwcircstring_linearize((LWCIRCSTRING *)tmp, tol, type, flags);
839
0
    }
840
0
    else if (tmp->type == LINETYPE)
841
0
    {
842
0
      lines[i] =
843
0
          (LWGEOM *)lwline_construct(mcurve->srid, NULL, ptarray_clone_deep(((LWLINE *)tmp)->points));
844
0
    }
845
0
    else if (tmp->type == COMPOUNDTYPE)
846
0
    {
847
0
      lines[i] = (LWGEOM *)lwcompound_linearize((LWCOMPOUND *)tmp, tol, type, flags);
848
0
    }
849
0
    else if (tmp->type == NURBSCURVETYPE)
850
0
    {
851
0
      lines[i] = (LWGEOM *)lwnurbscurve_linearize((LWNURBSCURVE *)tmp, tol, type, flags);
852
0
      if (!lines[i])
853
0
      {
854
0
        lwerror("%s: failed to linearize NURBS curve component", __func__);
855
0
        return NULL;
856
0
      }
857
0
    }
858
0
    else
859
0
    {
860
0
      lwerror("Unsupported geometry found in MultiCurve.");
861
0
      return NULL;
862
0
    }
863
0
    if (!lines[i])
864
0
    {
865
0
      lwstroke_free_geom_array(lines, i);
866
0
      return NULL;
867
0
    }
868
0
  }
869
870
0
  ogeom = (LWMLINE *)lwcollection_construct(MULTILINETYPE, mcurve->srid, NULL, mcurve->ngeoms, lines);
871
0
  return ogeom;
872
0
}
873
874
/**
875
 * @param msurface input multi surface
876
 * @param tol tolerance, semantic driven by tolerance_type
877
 * @param tolerance_type see LW_LINEARIZE_TOLERANCE_TYPE
878
 * @param flags see flags in lwarc_linearize
879
 *
880
 * @return a newly allocated LWMPOLY
881
 */
882
static LWMPOLY *
883
lwmsurface_linearize(const LWMSURFACE *msurface, double tol, LW_LINEARIZE_TOLERANCE_TYPE type, int flags)
884
0
{
885
0
  LWMPOLY *ogeom;
886
0
  LWGEOM *tmp;
887
0
  LWPOLY *poly;
888
0
  LWGEOM **polys;
889
0
  POINTARRAY **ptarray;
890
0
  uint32_t i, j;
891
892
0
  LWDEBUG(2, "lwmsurface_linearize called.");
893
894
0
  polys = lwalloc(sizeof(LWGEOM *) * msurface->ngeoms);
895
896
0
  for (i = 0; i < msurface->ngeoms; i++)
897
0
  {
898
0
    tmp = msurface->geoms[i];
899
0
    if (tmp->type == CURVEPOLYTYPE)
900
0
    {
901
0
      polys[i] = (LWGEOM *)lwcurvepoly_linearize((LWCURVEPOLY *)tmp, tol, type, flags);
902
0
      if (!polys[i])
903
0
      {
904
0
        lwstroke_free_geom_array(polys, i);
905
0
        return NULL;
906
0
      }
907
0
    }
908
0
    else if (tmp->type == POLYGONTYPE)
909
0
    {
910
0
      poly = (LWPOLY *)tmp;
911
0
      ptarray = lwalloc(sizeof(POINTARRAY *) * poly->nrings);
912
0
      for (j = 0; j < poly->nrings; j++)
913
0
      {
914
0
        ptarray[j] = ptarray_clone_deep(poly->rings[j]);
915
0
      }
916
0
      polys[i] = (LWGEOM *)lwpoly_construct(msurface->srid, NULL, poly->nrings, ptarray);
917
0
      if (!polys[i])
918
0
      {
919
0
        lwstroke_free_geom_array(polys, i);
920
0
        return NULL;
921
0
      }
922
0
    }
923
0
  }
924
0
  ogeom = (LWMPOLY *)lwcollection_construct(MULTIPOLYGONTYPE, msurface->srid, NULL, msurface->ngeoms, polys);
925
0
  return ogeom;
926
0
}
927
928
/**
929
 * @param collection input geometry collection
930
 * @param tol tolerance, semantic driven by tolerance_type
931
 * @param tolerance_type see LW_LINEARIZE_TOLERANCE_TYPE
932
 * @param flags see flags in lwarc_linearize
933
 *
934
 * @return a newly allocated LWCOLLECTION
935
 */
936
static LWCOLLECTION *
937
lwcollection_linearize(const LWCOLLECTION *collection, double tol, LW_LINEARIZE_TOLERANCE_TYPE type, int flags)
938
0
{
939
0
  LWCOLLECTION *ocol;
940
0
  LWGEOM *tmp;
941
0
  LWGEOM **geoms;
942
0
  uint32_t i;
943
944
0
  LWDEBUG(2, "lwcollection_linearize called.");
945
946
0
  geoms = lwalloc(sizeof(LWGEOM *) * collection->ngeoms);
947
948
0
  for (i = 0; i < collection->ngeoms; i++)
949
0
  {
950
0
    tmp = collection->geoms[i];
951
0
    switch (tmp->type)
952
0
    {
953
0
    case CIRCSTRINGTYPE:
954
0
      geoms[i] = (LWGEOM *)lwcircstring_linearize((LWCIRCSTRING *)tmp, tol, type, flags);
955
0
      break;
956
0
    case NURBSCURVETYPE:
957
0
      geoms[i] = (LWGEOM *)lwnurbscurve_linearize((LWNURBSCURVE *)tmp, tol, type, flags);
958
0
      if (!geoms[i])
959
0
      {
960
0
        lwerror("%s: failed to linearize NURBS curve element", __func__);
961
0
        return NULL;
962
0
      }
963
0
      break;
964
0
    case COMPOUNDTYPE:
965
0
      geoms[i] = (LWGEOM *)lwcompound_linearize((LWCOMPOUND *)tmp, tol, type, flags);
966
0
      break;
967
0
    case CURVEPOLYTYPE:
968
0
      geoms[i] = (LWGEOM *)lwcurvepoly_linearize((LWCURVEPOLY *)tmp, tol, type, flags);
969
0
      break;
970
0
    case MULTICURVETYPE:
971
0
    case MULTISURFACETYPE:
972
0
    case COLLECTIONTYPE:
973
0
      geoms[i] = (LWGEOM *)lwcollection_linearize((LWCOLLECTION *)tmp, tol, type, flags);
974
0
      break;
975
0
    default:
976
0
      geoms[i] = lwgeom_clone_deep(tmp);
977
0
      break;
978
0
    }
979
0
    if (!geoms[i])
980
0
    {
981
0
      lwstroke_free_geom_array(geoms, i);
982
0
      return NULL;
983
0
    }
984
0
  }
985
0
  ocol = lwcollection_construct(COLLECTIONTYPE, collection->srid, NULL, collection->ngeoms, geoms);
986
0
  return ocol;
987
0
}
988
989
/*
990
 * @param curve input NURBS curve
991
 * @param tol tolerance, semantic driven by tolerance_type
992
 * @param tolerance_type see LW_LINEARIZE_TOLERANCE_TYPE
993
 * @param flags see flags in lwarc_linearize
994
 *
995
 * @return a newly allocated LWLINE
996
 */
997
static LWLINE *
998
lwnurbscurve_linearize(const LWNURBSCURVE *curve, double tol, LW_LINEARIZE_TOLERANCE_TYPE tolerance_type, int flags)
999
0
{
1000
0
  uint32_t num_segments;
1001
0
  const double max_segments = (double)UINT32_MAX - 1.0;
1002
1003
0
  LWDEBUG(2, "lwnurbscurve_linearize called.");
1004
1005
0
  if (!curve)
1006
0
    return NULL;
1007
1008
0
  if (!isfinite(tol) || tol <= 0.0)
1009
0
  {
1010
0
    lwerror("%s: tolerance must be finite and > 0, got %.15g", __func__, tol);
1011
0
    return NULL;
1012
0
  }
1013
1014
0
  if (!curve->points || curve->points->npoints == 0)
1015
0
    return lwnurbscurve_to_linestring(curve, NURBS_MIN_LINEARIZE_SEGMENTS);
1016
1017
0
  switch (tolerance_type)
1018
0
  {
1019
0
  case LW_LINEARIZE_TOLERANCE_TYPE_SEGS_PER_QUAD:
1020
0
    if (tol != rint(tol))
1021
0
    {
1022
0
      lwerror("%s: segs-per-quad must be an integer, got %.15g", __func__, tol);
1023
0
      return NULL;
1024
0
    }
1025
0
    if (tol > ((double)NURBS_MAX_LINEARIZE_SEGMENTS / 4.0))
1026
0
    {
1027
0
      lwerror("%s: segs-per-quad is too large, got %.15g", __func__, tol);
1028
0
      return NULL;
1029
0
    }
1030
0
    num_segments = (uint32_t)(tol * 4);
1031
0
    break;
1032
0
  case LW_LINEARIZE_TOLERANCE_TYPE_MAX_DEVIATION: {
1033
0
    GBOX box;
1034
0
    double width = 0.0;
1035
0
    double height = 0.0;
1036
0
    double depth = 0.0;
1037
0
    double diagonal = 0.0;
1038
0
    double segments_required;
1039
1040
0
    if (ptarray_calculate_gbox_cartesian(curve->points, &box) == LW_SUCCESS)
1041
0
    {
1042
0
      width = box.xmax - box.xmin;
1043
0
      height = box.ymax - box.ymin;
1044
0
      if (FLAGS_GET_Z(curve->flags))
1045
0
        depth = box.zmax - box.zmin;
1046
0
      diagonal = sqrt(width * width + height * height + depth * depth);
1047
0
    }
1048
1049
0
    segments_required = diagonal / tol;
1050
0
    if (!isfinite(segments_required) || segments_required > max_segments)
1051
0
    {
1052
0
      lwerror("%s: max deviation is too small, got %.15g", __func__, tol);
1053
0
      return NULL;
1054
0
    }
1055
0
    num_segments = diagonal > 0.0 ? (uint32_t)ceil(segments_required) : NURBS_MIN_LINEARIZE_SEGMENTS;
1056
0
    break;
1057
0
  }
1058
0
  case LW_LINEARIZE_TOLERANCE_TYPE_MAX_ANGLE:
1059
0
    if (tol < (2.0 * M_PI) / max_segments)
1060
0
    {
1061
0
      lwerror("%s: max angle is too small, got %.15g", __func__, tol);
1062
0
      return NULL;
1063
0
    }
1064
0
    num_segments = (uint32_t)ceil((2.0 * M_PI) / tol);
1065
0
    break;
1066
0
  default:
1067
0
    lwerror("%s: unsupported tolerance type %d", __func__, tolerance_type);
1068
0
    return NULL;
1069
0
  }
1070
1071
0
  if (num_segments < NURBS_MIN_LINEARIZE_SEGMENTS)
1072
0
    num_segments = NURBS_MIN_LINEARIZE_SEGMENTS;
1073
0
  if (num_segments > NURBS_MAX_LINEARIZE_SEGMENTS)
1074
0
  {
1075
0
    lwerror("%s: requested too many segments, got %u", __func__, (unsigned int)num_segments);
1076
0
    return NULL;
1077
0
  }
1078
1079
0
  (void)flags; /* Currently unused for NURBS linearization */
1080
1081
0
  return lwnurbscurve_to_linestring(curve, num_segments);
1082
0
}
1083
1084
LWGEOM *
1085
lwcurve_linearize(const LWGEOM *geom, double tol, LW_LINEARIZE_TOLERANCE_TYPE type, int flags)
1086
0
{
1087
0
  LWGEOM *ogeom = NULL;
1088
0
  switch (geom->type)
1089
0
  {
1090
0
  case CIRCSTRINGTYPE:
1091
0
    ogeom = (LWGEOM *)lwcircstring_linearize((LWCIRCSTRING *)geom, tol, type, flags);
1092
0
    break;
1093
0
  case NURBSCURVETYPE:
1094
0
    ogeom = (LWGEOM *)lwnurbscurve_linearize((LWNURBSCURVE *)geom, tol, type, flags);
1095
0
    break;
1096
0
  case COMPOUNDTYPE:
1097
0
    ogeom = (LWGEOM *)lwcompound_linearize((LWCOMPOUND *)geom, tol, type, flags);
1098
0
    break;
1099
0
  case CURVEPOLYTYPE:
1100
0
    ogeom = (LWGEOM *)lwcurvepoly_linearize((LWCURVEPOLY *)geom, tol, type, flags);
1101
0
    break;
1102
0
  case MULTICURVETYPE:
1103
0
    ogeom = (LWGEOM *)lwmcurve_linearize((LWMCURVE *)geom, tol, type, flags);
1104
0
    break;
1105
0
  case MULTISURFACETYPE:
1106
0
    ogeom = (LWGEOM *)lwmsurface_linearize((LWMSURFACE *)geom, tol, type, flags);
1107
0
    break;
1108
0
  case COLLECTIONTYPE:
1109
0
    ogeom = (LWGEOM *)lwcollection_linearize((LWCOLLECTION *)geom, tol, type, flags);
1110
0
    break;
1111
0
  default:
1112
0
    ogeom = lwgeom_clone_deep(geom);
1113
0
  }
1114
0
  return ogeom;
1115
0
}
1116
1117
/* Kept for backward compatibility - TODO: drop */
1118
LWGEOM *
1119
lwgeom_stroke(const LWGEOM *geom, uint32_t perQuad)
1120
0
{
1121
0
  return lwcurve_linearize(geom, perQuad, LW_LINEARIZE_TOLERANCE_TYPE_SEGS_PER_QUAD, 0);
1122
0
}
1123
1124
/**
1125
 * Return ABC angle in radians
1126
 * TODO: move to lwalgorithm
1127
 */
1128
static double
1129
lw_arc_angle(const POINT2D *a, const POINT2D *b, const POINT2D *c)
1130
0
{
1131
0
  POINT2D ab, cb;
1132
1133
0
  ab.x = b->x - a->x;
1134
0
  ab.y = b->y - a->y;
1135
1136
0
  cb.x = b->x - c->x;
1137
0
  cb.y = b->y - c->y;
1138
1139
0
  double dot = (ab.x * cb.x + ab.y * cb.y);   /* dot product */
1140
0
  double cross = (ab.x * cb.y - ab.y * cb.x); /* cross product */
1141
1142
0
  double alpha = atan2(cross, dot);
1143
1144
0
  return alpha;
1145
0
}
1146
1147
/**
1148
 * Returns LW_TRUE if b is on the arc formed by a1/a2/a3, but not within
1149
 * that portion already described by a1/a2/a3
1150
 */
1151
static int
1152
pt_continues_arc(const POINT4D *a1, const POINT4D *a2, const POINT4D *a3, const POINT4D *b)
1153
0
{
1154
0
  POINT2D center;
1155
0
  POINT2D *t1 = (POINT2D *)a1;
1156
0
  POINT2D *t2 = (POINT2D *)a2;
1157
0
  POINT2D *t3 = (POINT2D *)a3;
1158
0
  POINT2D *tb = (POINT2D *)b;
1159
0
  double radius = lw_arc_center(t1, t2, t3, &center);
1160
0
  double b_distance, diff;
1161
1162
  /* Co-linear a1/a2/a3 */
1163
0
  if (radius < 0.0)
1164
0
    return LW_FALSE;
1165
1166
0
  b_distance = distance2d_pt_pt(tb, &center);
1167
0
  diff = fabs(radius - b_distance);
1168
0
  LWDEBUGF(4, "circle_radius=%g, b_distance=%g, diff=%g, percentage=%g", radius, b_distance, diff, diff / radius);
1169
1170
  /* Is the point b on the circle? */
1171
0
  if (diff < EPSILON_SQLMM)
1172
0
  {
1173
0
    int a2_side = lw_segment_side(t1, t3, t2);
1174
0
    int b_side = lw_segment_side(t1, t3, tb);
1175
0
    double angle1 = lw_arc_angle(t1, t2, t3);
1176
0
    double angle2 = lw_arc_angle(t2, t3, tb);
1177
1178
    /* Is the angle similar to the previous one ? */
1179
0
    diff = fabs(angle1 - angle2);
1180
0
    LWDEBUGF(4, " angle1: %g, angle2: %g, diff:%g", angle1, angle2, diff);
1181
0
    if (diff > EPSILON_SQLMM)
1182
0
    {
1183
0
      return LW_FALSE;
1184
0
    }
1185
1186
    /* Is the point b on the same side of a1/a3 as the mid-point a2 is? */
1187
    /* If not, it's in the unbounded part of the circle, so it continues the arc, return true. */
1188
0
    if (b_side != a2_side)
1189
0
      return LW_TRUE;
1190
0
  }
1191
0
  return LW_FALSE;
1192
0
}
1193
1194
static LWGEOM *
1195
linestring_from_pa(const POINTARRAY *pa, int32_t srid, int start, int end)
1196
0
{
1197
0
  int i = 0, j = 0;
1198
0
  POINT4D p;
1199
0
  POINTARRAY *pao = ptarray_construct(ptarray_has_z(pa), ptarray_has_m(pa), end - start + 2);
1200
0
  LWDEBUGF(4, "srid=%d, start=%d, end=%d", srid, start, end);
1201
0
  for (i = start; i < end + 2; i++)
1202
0
  {
1203
0
    getPoint4d_p(pa, i, &p);
1204
0
    ptarray_set_point4d(pao, j++, &p);
1205
0
  }
1206
0
  return lwline_as_lwgeom(lwline_construct(srid, NULL, pao));
1207
0
}
1208
1209
static LWGEOM *
1210
circstring_from_pa(const POINTARRAY *pa, int32_t srid, int start, int end)
1211
0
{
1212
1213
0
  POINT4D p0, p1, p2;
1214
0
  POINTARRAY *pao = ptarray_construct(ptarray_has_z(pa), ptarray_has_m(pa), 3);
1215
0
  LWDEBUGF(4, "srid=%d, start=%d, end=%d", srid, start, end);
1216
0
  getPoint4d_p(pa, start, &p0);
1217
0
  ptarray_set_point4d(pao, 0, &p0);
1218
0
  getPoint4d_p(pa, (start + end + 1) / 2, &p1);
1219
0
  ptarray_set_point4d(pao, 1, &p1);
1220
0
  getPoint4d_p(pa, end + 1, &p2);
1221
0
  ptarray_set_point4d(pao, 2, &p2);
1222
0
  return lwcircstring_as_lwgeom(lwcircstring_construct(srid, NULL, pao));
1223
0
}
1224
1225
static LWGEOM *
1226
geom_from_pa(const POINTARRAY *pa, int32_t srid, int is_arc, int start, int end)
1227
0
{
1228
0
  LWDEBUGF(4, "srid=%d, is_arc=%d, start=%d, end=%d", srid, is_arc, start, end);
1229
0
  if (is_arc)
1230
0
    return circstring_from_pa(pa, srid, start, end);
1231
0
  else
1232
0
    return linestring_from_pa(pa, srid, start, end);
1233
0
}
1234
1235
LWGEOM *
1236
pta_unstroke(const POINTARRAY *points, int32_t srid)
1237
0
{
1238
0
  int i = 0, j, k;
1239
0
  POINT4D a1, a2, a3, b;
1240
0
  POINT4D first, center;
1241
0
  char *edges_in_arcs;
1242
0
  int found_arc = LW_FALSE;
1243
0
  int current_arc = 1;
1244
0
  int num_edges;
1245
0
  int edge_type; /* non-zero if edge is part of an arc */
1246
0
  int start, end;
1247
0
  LWCOLLECTION *outcol;
1248
  /* Minimum number of edges, per quadrant, required to define an arc */
1249
0
  const unsigned int min_quad_edges = 2;
1250
1251
  /* Die on null input */
1252
0
  if (!points)
1253
0
    lwerror("pta_unstroke called with null pointarray");
1254
1255
  /* Null on empty input? */
1256
0
  if (points->npoints == 0)
1257
0
    return NULL;
1258
1259
  /* We can't desegmentize anything shorter than four points */
1260
0
  if (points->npoints < 4)
1261
0
  {
1262
    /* Return a linestring here*/
1263
0
    lwerror("pta_unstroke needs implementation for npoints < 4");
1264
0
  }
1265
1266
  /* Allocate our result array of vertices that are part of arcs */
1267
0
  num_edges = points->npoints - 1;
1268
0
  edges_in_arcs = lwalloc(num_edges + 1);
1269
0
  memset(edges_in_arcs, 0, num_edges + 1);
1270
1271
  /* We make a candidate arc of the first two edges, */
1272
  /* And then see if the next edge follows it */
1273
0
  while (i < num_edges - 2)
1274
0
  {
1275
0
    unsigned int arc_edges;
1276
0
    double num_quadrants;
1277
0
    double angle;
1278
1279
0
    found_arc = LW_FALSE;
1280
    /* Make candidate arc */
1281
0
    getPoint4d_p(points, i, &a1);
1282
0
    getPoint4d_p(points, i + 1, &a2);
1283
0
    getPoint4d_p(points, i + 2, &a3);
1284
0
    memcpy(&first, &a1, sizeof(POINT4D));
1285
1286
0
    for (j = i + 3; j < num_edges + 1; j++)
1287
0
    {
1288
0
      LWDEBUGF(4, "i=%d, j=%d", i, j);
1289
0
      getPoint4d_p(points, j, &b);
1290
      /* Does this point fall on our candidate arc? */
1291
0
      if (pt_continues_arc(&a1, &a2, &a3, &b))
1292
0
      {
1293
        /* Yes. Mark this edge and the two preceding it as arc components */
1294
0
        LWDEBUGF(4, "pt_continues_arc #%d", current_arc);
1295
0
        found_arc = LW_TRUE;
1296
0
        for (k = j - 1; k > j - 4; k--)
1297
0
          edges_in_arcs[k] = current_arc;
1298
0
      }
1299
0
      else
1300
0
      {
1301
        /* No. So we're done with this candidate arc */
1302
0
        LWDEBUG(4, "pt_continues_arc = false");
1303
0
        current_arc++;
1304
0
        break;
1305
0
      }
1306
1307
0
      memcpy(&a1, &a2, sizeof(POINT4D));
1308
0
      memcpy(&a2, &a3, sizeof(POINT4D));
1309
0
      memcpy(&a3, &b, sizeof(POINT4D));
1310
0
    }
1311
    /* Jump past all the edges that were added to the arc */
1312
0
    if (found_arc)
1313
0
    {
1314
      /* Check if an arc was composed by enough edges to be
1315
       * really considered an arc
1316
       * See http://trac.osgeo.org/postgis/ticket/2420
1317
       */
1318
0
      arc_edges = j - 1 - i;
1319
0
      LWDEBUGF(4, "arc defined by %d edges found", arc_edges);
1320
0
      if (first.x == b.x && first.y == b.y)
1321
0
      {
1322
0
        LWDEBUG(4, "arc is a circle");
1323
0
        num_quadrants = 4;
1324
0
      }
1325
0
      else
1326
0
      {
1327
0
        lw_arc_center((POINT2D *)&first, (POINT2D *)&b, (POINT2D *)&a1, (POINT2D *)&center);
1328
0
        angle = lw_arc_angle((POINT2D *)&first, (POINT2D *)&center, (POINT2D *)&b);
1329
0
        int p2_side = lw_segment_side((POINT2D *)&first, (POINT2D *)&a1, (POINT2D *)&b);
1330
0
        if (p2_side >= 0)
1331
0
          angle = -angle;
1332
1333
0
        if (angle < 0)
1334
0
          angle = 2 * M_PI + angle;
1335
0
        num_quadrants = (4 * angle) / (2 * M_PI);
1336
0
        LWDEBUGF(4,
1337
0
           "arc angle (%g %g, %g %g, %g %g) is %g (side is %d), quadrants:%g",
1338
0
           first.x,
1339
0
           first.y,
1340
0
           center.x,
1341
0
           center.y,
1342
0
           b.x,
1343
0
           b.y,
1344
0
           angle,
1345
0
           p2_side,
1346
0
           num_quadrants);
1347
0
      }
1348
      /* a1 is first point, b is last point */
1349
0
      if (arc_edges < min_quad_edges * num_quadrants)
1350
0
      {
1351
0
        LWDEBUGF(4,
1352
0
           "Not enough edges for a %g quadrants arc, %g needed",
1353
0
           num_quadrants,
1354
0
           min_quad_edges * num_quadrants);
1355
0
        for (k = j - 1; k >= i; k--)
1356
0
          edges_in_arcs[k] = 0;
1357
0
      }
1358
1359
0
      i = j - 1;
1360
0
    }
1361
0
    else
1362
0
    {
1363
      /* Mark this edge as a linear edge */
1364
0
      edges_in_arcs[i] = 0;
1365
0
      i = i + 1;
1366
0
    }
1367
0
  }
1368
1369
#if POSTGIS_DEBUG_LEVEL > 3
1370
  {
1371
    char *edgestr = lwalloc(num_edges + 1);
1372
    for (i = 0; i < num_edges; i++)
1373
    {
1374
      if (edges_in_arcs[i])
1375
        edgestr[i] = 48 + edges_in_arcs[i];
1376
      else
1377
        edgestr[i] = '.';
1378
    }
1379
    edgestr[num_edges] = 0;
1380
    LWDEBUGF(3, "edge pattern %s", edgestr);
1381
    lwfree(edgestr);
1382
  }
1383
#endif
1384
1385
0
  start = 0;
1386
0
  edge_type = edges_in_arcs[0];
1387
0
  outcol = lwcollection_construct_empty(COMPOUNDTYPE, srid, ptarray_has_z(points), ptarray_has_m(points));
1388
0
  for (i = 1; i < num_edges; i++)
1389
0
  {
1390
0
    if (edge_type != edges_in_arcs[i])
1391
0
    {
1392
0
      end = i - 1;
1393
0
      lwcollection_add_lwgeom(outcol, geom_from_pa(points, srid, edge_type, start, end));
1394
0
      start = i;
1395
0
      edge_type = edges_in_arcs[i];
1396
0
    }
1397
0
  }
1398
0
  lwfree(edges_in_arcs); /* not needed anymore */
1399
1400
  /* Roll out last item */
1401
0
  end = num_edges - 1;
1402
0
  lwcollection_add_lwgeom(outcol, geom_from_pa(points, srid, edge_type, start, end));
1403
1404
  /* Strip down to singleton if only one entry */
1405
0
  if (outcol->ngeoms == 1)
1406
0
  {
1407
0
    LWGEOM *outgeom = outcol->geoms[0];
1408
0
    outcol->ngeoms = 0;
1409
0
    lwcollection_free(outcol);
1410
0
    return outgeom;
1411
0
  }
1412
0
  return lwcollection_as_lwgeom(outcol);
1413
0
}
1414
1415
LWGEOM *
1416
lwline_unstroke(const LWLINE *line)
1417
0
{
1418
0
  LWDEBUG(2, "lwline_unstroke called.");
1419
1420
0
  if (line->points->npoints < 4)
1421
0
    return lwline_as_lwgeom(lwline_clone_deep(line));
1422
0
  else
1423
0
    return pta_unstroke(line->points, line->srid);
1424
0
}
1425
1426
LWGEOM *
1427
lwpolygon_unstroke(const LWPOLY *poly)
1428
0
{
1429
0
  LWGEOM **geoms;
1430
0
  uint32_t i, hascurve = 0;
1431
1432
0
  LWDEBUG(2, "lwpolygon_unstroke called.");
1433
1434
0
  geoms = lwalloc(sizeof(LWGEOM *) * poly->nrings);
1435
0
  for (i = 0; i < poly->nrings; i++)
1436
0
  {
1437
0
    geoms[i] = pta_unstroke(poly->rings[i], poly->srid);
1438
    /* pta_unstroke returns NULL for an empty (0-point) ring; keep it as an
1439
     * empty linestring so the reconstructed geometry stays well-formed. */
1440
0
    if (!geoms[i])
1441
0
      geoms[i] =
1442
0
          lwline_as_lwgeom(lwline_construct(poly->srid, NULL, ptarray_clone_deep(poly->rings[i])));
1443
0
    if (geoms[i]->type == CIRCSTRINGTYPE || geoms[i]->type == COMPOUNDTYPE)
1444
0
    {
1445
0
      hascurve = 1;
1446
0
    }
1447
0
  }
1448
0
  if (hascurve == 0)
1449
0
  {
1450
0
    for (i = 0; i < poly->nrings; i++)
1451
0
    {
1452
0
      lwgeom_free(geoms[i]);
1453
0
    }
1454
0
    lwfree(geoms);
1455
0
    return lwgeom_clone_deep((LWGEOM *)poly);
1456
0
  }
1457
1458
0
  return (LWGEOM *)lwcollection_construct(CURVEPOLYTYPE, poly->srid, NULL, poly->nrings, geoms);
1459
0
}
1460
1461
LWGEOM *
1462
lwmline_unstroke(const LWMLINE *mline)
1463
0
{
1464
0
  LWGEOM **geoms;
1465
0
  uint32_t i, hascurve = 0;
1466
1467
0
  LWDEBUG(2, "lwmline_unstroke called.");
1468
1469
0
  geoms = lwalloc(sizeof(LWGEOM *) * mline->ngeoms);
1470
0
  for (i = 0; i < mline->ngeoms; i++)
1471
0
  {
1472
0
    geoms[i] = lwline_unstroke((LWLINE *)mline->geoms[i]);
1473
0
    if (geoms[i]->type == CIRCSTRINGTYPE || geoms[i]->type == COMPOUNDTYPE)
1474
0
    {
1475
0
      hascurve = 1;
1476
0
    }
1477
0
  }
1478
0
  if (hascurve == 0)
1479
0
  {
1480
0
    for (i = 0; i < mline->ngeoms; i++)
1481
0
    {
1482
0
      lwfree(geoms[i]); /* TODO: should this be lwgeom_free instead ? */
1483
0
    }
1484
0
    return lwgeom_clone_deep((LWGEOM *)mline);
1485
0
  }
1486
0
  return (LWGEOM *)lwcollection_construct(MULTICURVETYPE, mline->srid, NULL, mline->ngeoms, geoms);
1487
0
}
1488
1489
LWGEOM *
1490
lwmpolygon_unstroke(const LWMPOLY *mpoly)
1491
0
{
1492
0
  LWGEOM **geoms;
1493
0
  uint32_t i, hascurve = 0;
1494
1495
0
  LWDEBUG(2, "lwmpoly_unstroke called.");
1496
1497
0
  geoms = lwalloc(sizeof(LWGEOM *) * mpoly->ngeoms);
1498
0
  for (i = 0; i < mpoly->ngeoms; i++)
1499
0
  {
1500
0
    geoms[i] = lwpolygon_unstroke((LWPOLY *)mpoly->geoms[i]);
1501
0
    if (geoms[i]->type == CURVEPOLYTYPE)
1502
0
    {
1503
0
      hascurve = 1;
1504
0
    }
1505
0
  }
1506
0
  if (hascurve == 0)
1507
0
  {
1508
0
    for (i = 0; i < mpoly->ngeoms; i++)
1509
0
    {
1510
0
      lwfree(geoms[i]); /* TODO: should this be lwgeom_free instead ? */
1511
0
    }
1512
0
    return lwgeom_clone_deep((LWGEOM *)mpoly);
1513
0
  }
1514
0
  return (LWGEOM *)lwcollection_construct(MULTISURFACETYPE, mpoly->srid, NULL, mpoly->ngeoms, geoms);
1515
0
}
1516
1517
LWGEOM *
1518
lwcollection_unstroke(const LWCOLLECTION *c)
1519
0
{
1520
0
  LWCOLLECTION *ret = lwalloc(sizeof(LWCOLLECTION));
1521
0
  memcpy(ret, c, sizeof(LWCOLLECTION));
1522
1523
0
  if (c->ngeoms > 0)
1524
0
  {
1525
0
    uint32_t i;
1526
0
    ret->geoms = lwalloc(sizeof(LWGEOM *) * c->ngeoms);
1527
0
    for (i = 0; i < c->ngeoms; i++)
1528
0
    {
1529
0
      ret->geoms[i] = lwgeom_unstroke(c->geoms[i]);
1530
0
    }
1531
0
    if (c->bbox)
1532
0
    {
1533
0
      ret->bbox = gbox_copy(c->bbox);
1534
0
    }
1535
0
  }
1536
0
  else
1537
0
  {
1538
0
    ret->bbox = NULL;
1539
0
    ret->geoms = NULL;
1540
0
  }
1541
0
  return (LWGEOM *)ret;
1542
0
}
1543
1544
LWGEOM *
1545
lwgeom_unstroke(const LWGEOM *geom)
1546
0
{
1547
0
  LWDEBUG(2, "lwgeom_unstroke called.");
1548
1549
0
  switch (geom->type)
1550
0
  {
1551
0
  case LINETYPE:
1552
0
    return lwline_unstroke((LWLINE *)geom);
1553
0
  case POLYGONTYPE:
1554
0
    return lwpolygon_unstroke((LWPOLY *)geom);
1555
0
  case MULTILINETYPE:
1556
0
    return lwmline_unstroke((LWMLINE *)geom);
1557
0
  case MULTIPOLYGONTYPE:
1558
0
    return lwmpolygon_unstroke((LWMPOLY *)geom);
1559
0
  case COLLECTIONTYPE:
1560
0
    return lwcollection_unstroke((LWCOLLECTION *)geom);
1561
0
  default:
1562
0
    return lwgeom_clone_deep(geom);
1563
0
  }
1564
0
}