forked from MapServer/MapServer
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmappostgis.cpp
3815 lines (3293 loc) · 111 KB
/
mappostgis.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/******************************************************************************
* $Id$
*
* Project: MapServer
* Purpose: PostGIS CONNECTIONTYPE support.
* Author: Paul Ramsey <pramsey@cleverelephant.ca>
* Dave Blasby <dblasby@gmail.com>
*
******************************************************************************
* Copyright (c) 2010 Paul Ramsey
* Copyright (c) 2002 Refractions Research
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies of this Software or works derived from this Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
****************************************************************************/
/*
** Some theory of operation:
**
** Build SQL from DATA statement and LAYER state. SQL is always of the form:
**
** SELECT [this, that, other], geometry, uid
** FROM [table|(subquery) as sub]
** WHERE [box] AND [filter]
**
** So the geometry always resides at layer->numitems and the uid always
** resides at layer->numitems + 1
**
** Geometry is requested as Hex encoded WKB. The endian is always requested
** as the client endianness.
**
** msPostGISLayerWhichShapes creates SQL based on DATA and LAYER state,
** executes it, and places the un-read PGresult handle in the layerinfo->pgresult,
** setting the layerinfo->rownum to 0.
**
** msPostGISNextShape reads a row, increments layerinfo->rownum, and returns
** MS_SUCCESS, until rownum reaches ntuples, and it returns MS_DONE instead.
**
*/
/* required for MSVC */
#define _USE_MATH_DEFINES
#include <assert.h>
#include <string.h>
#include <math.h>
#include "mapserver.h"
#include "maptime.h"
#include "mappostgis.h"
#include "mapows.h"
#include <vector>
#define FP_EPSILON 1e-12
#define FP_EQ(a, b) (fabs((a)-(b)) < FP_EPSILON)
#define FP_LEFT -1
#define FP_RIGHT 1
#define FP_COLINEAR 0
#define SEGMENT_ANGLE 10.0
#define SEGMENT_MINPOINTS 10
#define WKBZOFFSET_NONISO 0x80000000
#define WKBMOFFSET_NONISO 0x40000000
#define HAS_Z 0x1
#define HAS_M 0x2
#if TRANSFER_ENCODING == 256
#define RESULTSET_TYPE 1
#else
#define RESULTSET_TYPE 0
#endif
#ifdef USE_POSTGIS
static int wkbConvGeometryToShape(wkbObj *w, shapeObj *shape);
static int arcStrokeCircularString(wkbObj *w, double segment_angle, lineObj *line, int nZMFlag);
/*
** msPostGISCloseConnection()
**
** Handler registered witih msConnPoolRegister so that Mapserver
** can clean up open connections during a shutdown.
*/
static void msPostGISCloseConnection(void *pgconn)
{
PQfinish((PGconn*)pgconn);
}
/*
** msPostGISCreateLayerInfo()
*/
static msPostGISLayerInfo *msPostGISCreateLayerInfo(void)
{
msPostGISLayerInfo *layerinfo = new msPostGISLayerInfo;
layerinfo->paging = MS_TRUE;
layerinfo->force2d = MS_FALSE;
return layerinfo;
}
/*
** msPostGISFreeLayerInfo()
*/
static void msPostGISFreeLayerInfo(layerObj *layer)
{
msPostGISLayerInfo *layerinfo = (msPostGISLayerInfo*)layer->layerinfo;
if ( layerinfo->pgresult ) PQclear(layerinfo->pgresult);
if ( layerinfo->pgconn ) msConnPoolRelease(layer, layerinfo->pgconn);
delete layerinfo;
layer->layerinfo = nullptr;
}
/*
** postgresqlNoticeHandler()
**
** Propagate messages from the database to the Mapserver log,
** set in PQsetNoticeProcessor during layer open.
*/
static void postresqlNoticeHandler(void *arg, const char *message)
{
layerObj *lp = (layerObj*)arg;
if (lp->debug) {
msDebug("%s\n", message);
}
}
/*
** Expandable pointObj array. The lineObj unfortunately
** is not useful for this purpose, so we have this one.
*/
static std::vector<pointObj> pointArrayNew(int maxpoints)
{
auto v = std::vector<pointObj>();
v.reserve(maxpoints);
return v;
}
/*
** Add a pointObj to the pointObjArray.
*/
static void
pointArrayAddPoint(std::vector<pointObj>& v, const pointObj& p)
{
v.push_back(p);
}
/*
** Pass an input type number through the PostGIS version
** type map array to handle the pre-2.0 incorrect WKB types
*/
static int
wkbTypeMap(wkbObj *w, int type, int* pnZMFlag)
{
*pnZMFlag = 0;
/* PostGIS >= 2 : ISO SQL/MM style Z types ? */
if( type >= 1000 && type < 2000 )
{
type -= 1000;
*pnZMFlag = HAS_Z;
}
/* PostGIS >= 2 : ISO SQL/MM style M types ? */
else if( type >= 2000 && type < 3000 )
{
type -= 2000;
*pnZMFlag = HAS_M;
}
/* PostGIS >= 2 : ISO SQL/MM style ZM types ? */
else if( type >= 3000 && type < 4000 )
{
type -= 3000;
*pnZMFlag = HAS_Z | HAS_M;
}
/* PostGIS 1.X EWKB : Extended WKB Z or ZM ? */
else if( (type & WKBZOFFSET_NONISO) != 0 )
{
if( (type & WKBMOFFSET_NONISO) != 0 )
*pnZMFlag = HAS_Z | HAS_M;
else
*pnZMFlag = HAS_Z;
type &= 0x00FFFFFF;
}
/* PostGIS 1.X EWKB: Extended WKB M ? */
else if( (type & WKBMOFFSET_NONISO) != 0 )
{
*pnZMFlag = HAS_M;
type &= 0x00FFFFFF;
}
if ( type >= 0 && type < WKB_TYPE_COUNT )
return w->typemap[type];
else
return 0;
}
/*
** Read the WKB type number from a wkbObj without
** advancing the read pointer.
*/
static int
wkbType(wkbObj *w, int* pnZMFlag)
{
int t;
memcpy(&t, (w->ptr + 1), sizeof(int));
return wkbTypeMap(w,t, pnZMFlag);
}
/*
** Read the type number of the first element of a
** collection without advancing the read pointer.
*/
static int
wkbCollectionSubType(wkbObj *w, int* pnZMFlag)
{
int t;
memcpy(&t, (w->ptr + 1 + 4 + 4 + 1), sizeof(int));
return wkbTypeMap(w,t, pnZMFlag);
}
/*
** Read one byte from the WKB and advance the read pointer
*/
static char
wkbReadChar(wkbObj *w)
{
char c;
memcpy(&c, w->ptr, sizeof(char));
w->ptr += sizeof(char);
return c;
}
/*
** Read one integer from the WKB and advance the read pointer.
** We assume the endianess of the WKB is the same as this machine.
*/
static inline int
wkbReadInt(wkbObj *w)
{
int i;
memcpy(&i, w->ptr, sizeof(int));
w->ptr += sizeof(int);
return i;
}
/*
** Read one pointObj (two doubles) from the WKB and advance the read pointer.
** We assume the endianess of the WKB is the same as this machine.
*/
static inline void
wkbReadPointP(wkbObj *w, pointObj *p, int nZMFlag)
{
memcpy(&(p->x), w->ptr, sizeof(double));
w->ptr += sizeof(double);
memcpy(&(p->y), w->ptr, sizeof(double));
w->ptr += sizeof(double);
if( nZMFlag & HAS_Z )
{
memcpy(&(p->z), w->ptr, sizeof(double));
w->ptr += sizeof(double);
}
else
{
p->z = 0;
}
if( nZMFlag & HAS_M )
{
memcpy(&(p->m), w->ptr, sizeof(double));
w->ptr += sizeof(double);
}
else
{
p->m = 0;
}
}
/*
** Read one pointObj (two doubles) from the WKB and advance the read pointer.
** We assume the endianess of the WKB is the same as this machine.
*/
static inline pointObj
wkbReadPoint(wkbObj *w, int nZMFlag)
{
pointObj p;
wkbReadPointP(w, &p, nZMFlag);
return p;
}
/*
** Read a "point array" and return an allocated lineObj.
** A point array is a WKB fragment that starts with a
** point count, which is followed by that number of doubles * 2.
** Linestrings, circular strings, polygon rings, all show this
** form.
*/
static void
wkbReadLine(wkbObj *w, lineObj *line, int nZMFlag)
{
pointObj p;
const int npoints = wkbReadInt(w);
if( npoints > (int)((w->size - (w->ptr - w->wkb)) / 16) )
return;
line->numpoints = npoints;
line->point =(pointObj*) msSmallMalloc(npoints * sizeof(pointObj));
for ( int i = 0; i < npoints; i++ ) {
wkbReadPointP(w, &p, nZMFlag);
line->point[i] = p;
}
}
/*
** Advance the read pointer past a geometry without returning any
** values. Used for skipping un-drawable elements in a collection.
*/
static void
wkbSkipGeometry(wkbObj *w)
{
/*endian = */wkbReadChar(w);
int nZMFlag;
const int type = wkbTypeMap(w,wkbReadInt(w), &nZMFlag);
const int nCoordDim = 2 + (((nZMFlag & HAS_Z) != 0) ? 1 : 0) + (((nZMFlag & HAS_M) != 0) ? 1 : 0);
switch(type) {
case WKB_POINT:
w->ptr += nCoordDim * sizeof(double);
break;
case WKB_CIRCULARSTRING:
case WKB_LINESTRING: {
const int npoints = wkbReadInt(w);
w->ptr += npoints * nCoordDim * sizeof(double);
break;
}
case WKB_POLYGON: {
const int nrings = wkbReadInt(w);
if( nrings > (int)((w->size - (w->ptr - w->wkb)) / 4) )
return;
for ( int i = 0; i < nrings; i++ ) {
const int npoints = wkbReadInt(w);
w->ptr += npoints * nCoordDim * sizeof(double);
}
break;
}
case WKB_MULTIPOINT:
case WKB_MULTILINESTRING:
case WKB_MULTIPOLYGON:
case WKB_GEOMETRYCOLLECTION:
case WKB_COMPOUNDCURVE:
case WKB_CURVEPOLYGON:
case WKB_MULTICURVE:
case WKB_MULTISURFACE: {
const int ngeoms = wkbReadInt(w);
if( ngeoms > (int)((w->size - (w->ptr - w->wkb)) / 4) )
return;
for ( int i = 0; i < ngeoms; i++ ) {
wkbSkipGeometry(w);
}
break;
}
}
}
/*
** Convert a WKB point to a shapeObj, advancing the read pointer as we go.
*/
static int
wkbConvPointToShape(wkbObj *w, shapeObj *shape)
{
/*endian = */wkbReadChar(w);
int nZMFlag;
const int type = wkbTypeMap(w,wkbReadInt(w),&nZMFlag);
if( type != WKB_POINT ) return MS_FAILURE;
if( ! (shape->type == MS_SHAPE_POINT) ) return MS_FAILURE;
lineObj line;
line.numpoints = 1;
line.point = (pointObj*) msSmallMalloc(sizeof(pointObj));
line.point[0] = wkbReadPoint(w, nZMFlag);
msAddLineDirectly(shape, &line);
return MS_SUCCESS;
}
/*
** Convert a WKB line string to a shapeObj, advancing the read pointer as we go.
*/
static int
wkbConvLineStringToShape(wkbObj *w, shapeObj *shape)
{
/*endian = */wkbReadChar(w);
int nZMFlag;
const int type = wkbTypeMap(w,wkbReadInt(w), &nZMFlag);
if( type != WKB_LINESTRING ) return MS_FAILURE;
lineObj line;
wkbReadLine(w,&line, nZMFlag);
msAddLineDirectly(shape, &line);
return MS_SUCCESS;
}
/*
** Convert a WKB polygon to a shapeObj, advancing the read pointer as we go.
*/
static int
wkbConvPolygonToShape(wkbObj *w, shapeObj *shape)
{
/*endian = */wkbReadChar(w);
int nZMFlag;
const int type = wkbTypeMap(w,wkbReadInt(w), &nZMFlag);
if( type != WKB_POLYGON ) return MS_FAILURE;
/* How many rings? */
const int nrings = wkbReadInt(w);
if( nrings > (int)((w->size - (w->ptr - w->wkb)) / 4) )
return MS_FAILURE;
/* Add each ring to the shape */
lineObj line;
for( int i = 0; i < nrings; i++ ) {
wkbReadLine(w,&line, nZMFlag);
msAddLineDirectly(shape, &line);
}
return MS_SUCCESS;
}
/*
** Convert a WKB curve polygon to a shapeObj, advancing the read pointer as we go.
** The arc portions of the rings will be stroked to linestrings as they
** are read by the underlying circular string handling.
*/
static int
wkbConvCurvePolygonToShape(wkbObj *w, shapeObj *shape)
{
const int was_poly = ( shape->type == MS_SHAPE_POLYGON );
/*endian = */wkbReadChar(w);
int nZMFlag;
const int type = wkbTypeMap(w,wkbReadInt(w), &nZMFlag);
if( type != WKB_CURVEPOLYGON ) return MS_FAILURE;
const int ncomponents = wkbReadInt(w);
if( ncomponents > (int)((w->size - (w->ptr - w->wkb)) / 4) )
return MS_FAILURE;
/* Lower the allowed dimensionality so we can
* catch the linear ring components */
shape->type = MS_SHAPE_LINE;
int failures = 0;
for ( int i = 0; i < ncomponents; i++ ) {
if ( wkbConvGeometryToShape(w, shape) == MS_FAILURE ) {
wkbSkipGeometry(w);
failures++;
}
}
/* Go back to expected dimensionality */
if ( was_poly) shape->type = MS_SHAPE_POLYGON;
if ( failures == ncomponents )
return MS_FAILURE;
else
return MS_SUCCESS;
}
/*
** Convert a WKB circular string to a shapeObj, advancing the read pointer as we go.
** Arcs will be stroked to linestrings.
*/
static int
wkbConvCircularStringToShape(wkbObj *w, shapeObj *shape)
{
/*endian = */wkbReadChar(w);
int nZMFlag;
const int type = wkbTypeMap(w,wkbReadInt(w), &nZMFlag);
if( type != WKB_CIRCULARSTRING ) return MS_FAILURE;
lineObj line = {0, nullptr};
/* Stroke the string into a point array */
if ( arcStrokeCircularString(w, SEGMENT_ANGLE, &line, nZMFlag) == MS_FAILURE ) {
if(line.point) free(line.point);
return MS_FAILURE;
}
/* Fill in the lineObj */
if ( line.numpoints > 0 ) {
msAddLine(shape, &line);
if(line.point) free(line.point);
}
return MS_SUCCESS;
}
/*
** Compound curves need special handling. First we load
** each component of the curve on the a lineObj in a shape.
** Then we merge those lineObjs into a single lineObj. This
** allows compound curves to serve as closed rings in
** curve polygons.
*/
static int
wkbConvCompoundCurveToShape(wkbObj *w, shapeObj *shape)
{
/*endian = */wkbReadChar(w);
int nZMFlag;
const int type = wkbTypeMap(w,wkbReadInt(w), &nZMFlag);
/* Init our shape buffer */
shapeObj shapebuf;
msInitShape(&shapebuf);
if( type != WKB_COMPOUNDCURVE ) return MS_FAILURE;
/* How many components in the compound curve? */
const int ncomponents = wkbReadInt(w);
if( ncomponents > (int)((w->size - (w->ptr - w->wkb)) / 4) )
return MS_FAILURE;
/* We'll load each component onto a line in a shape */
for( int i = 0; i < ncomponents; i++ )
wkbConvGeometryToShape(w, &shapebuf);
/* Do nothing on empty */
if ( shapebuf.numlines == 0 )
return MS_FAILURE;
/* Count the total number of points */
int npoints = 0;
for( int i = 0; i < shapebuf.numlines; i++ )
npoints += shapebuf.line[i].numpoints;
/* Do nothing on empty */
if ( npoints == 0 )
return MS_FAILURE;
lineObj line;
line.numpoints = npoints;
line.point = (pointObj*) msSmallMalloc(sizeof(pointObj) * npoints);
/* Copy in the points */
npoints = 0;
for ( int i = 0; i < shapebuf.numlines; i++ ) {
for ( int j = 0; j < shapebuf.line[i].numpoints; j++ ) {
/* Don't add a start point that duplicates an endpoint */
if( j == 0 && i > 0 &&
memcmp(&(line.point[npoints - 1]),&(shapebuf.line[i].point[j]),sizeof(pointObj)) == 0 ) {
continue;
}
line.point[npoints++] = shapebuf.line[i].point[j];
}
}
line.numpoints = npoints;
/* Clean up */
msFreeShape(&shapebuf);
/* Fill in the lineObj */
msAddLineDirectly(shape, &line);
return MS_SUCCESS;
}
/*
** Convert a WKB collection string to a shapeObj, advancing the read pointer as we go.
** Many WKB types (MultiPoint, MultiLineString, MultiPolygon, MultiSurface,
** MultiCurve, GeometryCollection) can be treated identically as collections
** (they start with endian, type number and count of sub-elements, then provide the
** subelements as WKB) so are handled with this one function.
*/
static int
wkbConvCollectionToShape(wkbObj *w, shapeObj *shape)
{
/*endian = */wkbReadChar(w);
int nZMFlag;
/*type = */wkbTypeMap(w,wkbReadInt(w), &nZMFlag);
const int ncomponents = wkbReadInt(w);
if( ncomponents > (int)((w->size - (w->ptr - w->wkb)) / 4) )
return MS_FAILURE;
/*
* If we can draw any portion of the collection, we will,
* but if all the components fail, we will draw nothing.
*/
int failures = 0;
for ( int i = 0; i < ncomponents; i++ ) {
if ( wkbConvGeometryToShape(w, shape) == MS_FAILURE ) {
wkbSkipGeometry(w);
failures++;
}
}
if ( failures == ncomponents || ncomponents == 0)
return MS_FAILURE;
else
return MS_SUCCESS;
}
/*
** Generic handler to switch to the appropriate function for the WKB type.
** Note that we also handle switching here to avoid processing shapes
** we will be unable to draw. Example: we can't draw point features as
** a MS_SHAPE_LINE layer, so if the type is WKB_POINT and the layer is
** MS_SHAPE_LINE, we exit before converting.
*/
static int
wkbConvGeometryToShape(wkbObj *w, shapeObj *shape)
{
int nZMFlag;
const int wkbtype = wkbType(w, &nZMFlag); /* Peak at the type number */
switch(wkbtype) {
/* Recurse into anonymous collections */
case WKB_GEOMETRYCOLLECTION:
return wkbConvCollectionToShape(w, shape);
/* Handle area types */
case WKB_POLYGON:
return wkbConvPolygonToShape(w, shape);
case WKB_MULTIPOLYGON:
return wkbConvCollectionToShape(w, shape);
case WKB_CURVEPOLYGON:
return wkbConvCurvePolygonToShape(w, shape);
case WKB_MULTISURFACE:
return wkbConvCollectionToShape(w, shape);
}
/* We can't convert any of the following types into polygons */
if ( shape->type == MS_SHAPE_POLYGON ) return MS_FAILURE;
/* Handle linear types */
switch(wkbtype) {
case WKB_LINESTRING:
return wkbConvLineStringToShape(w, shape);
case WKB_CIRCULARSTRING:
return wkbConvCircularStringToShape(w, shape);
case WKB_COMPOUNDCURVE:
return wkbConvCompoundCurveToShape(w, shape);
case WKB_MULTILINESTRING:
return wkbConvCollectionToShape(w, shape);
case WKB_MULTICURVE:
return wkbConvCollectionToShape(w, shape);
}
/* We can't convert any of the following types into lines */
if ( shape->type == MS_SHAPE_LINE ) return MS_FAILURE;
/* Handle point types */
switch(wkbtype) {
case WKB_POINT:
return wkbConvPointToShape(w, shape);
case WKB_MULTIPOINT:
return wkbConvCollectionToShape(w, shape);
}
/* This is a WKB type we don't know about! */
return MS_FAILURE;
}
/*
** What side of p1->p2 is q on?
*/
static inline int
arcSegmentSide(const pointObj &p1, const pointObj &p2, const pointObj &q)
{
double side = ( (q.x - p1.x) * (p2.y - p1.y) - (p2.x - p1.x) * (q.y - p1.y) );
if ( FP_EQ(side,0.0) ) {
return FP_COLINEAR;
} else {
if ( side < 0.0 )
return FP_LEFT;
else
return FP_RIGHT;
}
}
/*
** Calculate the center of the circle defined by three points.
** Using matrix approach from http://mathforum.org/library/drmath/view/55239.html
*/
static int
arcCircleCenter(const pointObj& p1, const pointObj& p2, const pointObj& p3, pointObj *center, double *radius)
{
pointObj c = {0,0,0,0}; // initialize
double r;
/* Circle is closed, so p2 must be opposite p1 & p3. */
if ((fabs(p1.x - p3.x) < FP_EPSILON) && (fabs(p1.y-p3.y) < FP_EPSILON)) {
c.x = p1.x + (p2.x - p1.x) / 2.0;
c.y = p1.y + (p2.y - p1.y) / 2.0;
r = sqrt(pow(c.x - p1.x, 2.0) + pow(c.y - p1.y, 2.0));
}
/* There is no circle here, the points are actually co-linear */
else if ( arcSegmentSide(p1, p3, p2) == FP_COLINEAR ) {
return MS_FAILURE;
}
/* Calculate the center and radius. */
else {
/* Radius */
const double dx21 = p2.x - p1.x;
const double dy21 = p2.y - p1.y;
const double dx31 = p3.x - p1.x;
const double dy31 = p3.y - p1.y;
const double h21 = pow(dx21, 2.0) + pow(dy21, 2.0);
const double h31 = pow(dx31, 2.0) + pow(dy31, 2.0);
/* 2 * |Cross product|, d<0 means clockwise and d>0 counterclockwise sweeping angle */
const double d = 2 * (dx21 * dy31 - dx31 * dy21);
c.x = p1.x + (h21 * dy31 - h31 * dy21) / d;
c.y = p1.y - (h21 * dx31 - h31 * dx21) / d;
r = sqrt(pow(c.x - p1.x, 2) + pow(c.y - p1.y, 2));
}
if ( radius ) *radius = r;
if ( center ) *center = c;
return MS_SUCCESS;
}
/*
** Write a stroked version of the circle defined by three points into a
** point buffer. The segment_angle (degrees) is the coverage of each stroke segment,
** and depending on whether this is the first arc in a circularstring,
** you might want to include_first
*/
static int
arcStrokeCircle(const pointObj& p1, const pointObj& p2, const pointObj& p3,
double segment_angle, int include_first, std::vector<pointObj>& pa)
{
const int side = arcSegmentSide(p1, p3, p2); /* What side of p1,p3 is the middle point? */
int is_closed = MS_FALSE;
/* We need to know if we're dealing with a circle early */
if ( FP_EQ(p1.x, p3.x) && FP_EQ(p1.y, p3.y) )
is_closed = MS_TRUE;
/* Check if the "arc" is actually straight */
if ( ! is_closed && side == FP_COLINEAR ) {
/* We just need to write in the end points */
if ( include_first )
pointArrayAddPoint(pa, p1);
pointArrayAddPoint(pa, p3);
return MS_SUCCESS;
}
/* We should always be able to find the center of a non-linear arc */
pointObj center; /* Center of our circular arc */
double radius; /* Radius of our circular arc */
if ( arcCircleCenter(p1, p2, p3, ¢er, &radius) == MS_FAILURE )
return MS_FAILURE;
/* Calculate the angles relative to center that our three points represent */
const double a1 = atan2(p1.y - center.y, p1.x - center.x);
/* UNUSED
a2 = atan2(p2.y - center.y, p2.x - center.x);
*/
const double a3 = atan2(p3.y - center.y, p3.x - center.x);
double segment_angle_r = M_PI * segment_angle / 180.0; /* Segment angle in radians */
double sweep_angle_r; /* Total angular size of our circular arc in radians */
/* Closed-circle case, we sweep the whole circle! */
if ( is_closed ) {
sweep_angle_r = 2.0 * M_PI;
}
/* Clockwise sweep direction */
else if ( side == FP_LEFT ) {
if ( a3 > a1 ) /* Wrapping past 180? */
sweep_angle_r = a1 + (2.0 * M_PI - a3);
else
sweep_angle_r = a1 - a3;
}
/* Counter-clockwise sweep direction */
else if ( side == FP_RIGHT ) {
if ( a3 > a1 ) /* Wrapping past 180? */
sweep_angle_r = a3 - a1;
else
sweep_angle_r = a3 + (2.0 * M_PI - a1);
} else
sweep_angle_r = 0.0;
/* We don't have enough resolution, let's invert our strategy. */
if ( (sweep_angle_r / segment_angle_r) < SEGMENT_MINPOINTS ) {
segment_angle_r = sweep_angle_r / (SEGMENT_MINPOINTS + 1);
}
/* We don't have enough resolution to stroke this arc,
* so just join the start to the end. */
if ( sweep_angle_r < segment_angle_r ) {
if ( include_first )
pointArrayAddPoint(pa, p1);
pointArrayAddPoint(pa, p3);
return MS_SUCCESS;
}
/* How many edges to generate (we add the final edge
* by sticking on the last point */
int num_edges = floor(sweep_angle_r / fabs(segment_angle_r));
/* Go backwards (negative angular steps) if we are stroking clockwise */
if ( side == FP_LEFT )
segment_angle_r *= -1;
/* What point should we start with? */
double current_angle_r; /* What angle are we generating now (radians)? */
if( include_first ) {
current_angle_r = a1;
} else {
current_angle_r = a1 + segment_angle_r;
num_edges--;
}
/* For each edge, increment or decrement by our segment angle */
for( int i = 0; i < num_edges; i++ ) {
if (segment_angle_r > 0.0 && current_angle_r > M_PI)
current_angle_r -= 2*M_PI;
if (segment_angle_r < 0.0 && current_angle_r < -1*M_PI)
current_angle_r -= 2*M_PI;
pointObj p;
p.x = center.x + radius*cos(current_angle_r);
p.y = center.y + radius*sin(current_angle_r);
pointArrayAddPoint(pa, p);
current_angle_r += segment_angle_r;
}
/* Add the last point */
pointArrayAddPoint(pa, p3);
return MS_SUCCESS;
}
/*
** This function does not actually take WKB as input, it takes the
** WKB starting from the numpoints integer. Each three-point edge
** is stroked into a linestring and appended into the lineObj
** argument.
*/
static int
arcStrokeCircularString(wkbObj *w, double segment_angle, lineObj *line, int nZMFlag)
{
if ( ! w || ! line ) return MS_FAILURE;
const int npoints = wkbReadInt(w);
const int nedges = npoints / 2;
/* All CircularStrings have an odd number of points */
if ( npoints < 3 || npoints % 2 != 1 )
return MS_FAILURE;
/* Make a large guess at how much space we'll need */
auto pa = pointArrayNew(nedges * 180 / segment_angle);
pointObj p1, p2, p3;
wkbReadPointP(w,&p3,nZMFlag);
/* Fill out the point array with stroked arcs */
int edge = 0;
while( edge < nedges ) {
p1 = p3;
wkbReadPointP(w,&p2,nZMFlag);
wkbReadPointP(w,&p3,nZMFlag);
if ( arcStrokeCircle(p1, p2, p3, segment_angle, edge ? 0 : 1, pa) == MS_FAILURE ) {
return MS_FAILURE;
}
edge++;
}
/* Copy the point array into the line */
line->numpoints = static_cast<int>(pa.size());
line->point = (pointObj*) msSmallMalloc(line->numpoints * sizeof(pointObj));
memcpy(line->point, pa.data(), line->numpoints * sizeof(pointObj));
return MS_SUCCESS;
}
/*
** For LAYER types that are not the usual ones (charts,
** annotations, etc) we will convert to a shape type
** that "makes sense" given the WKB input. We do this
** by peaking at the type number of the first collection
** sub-element.
*/
static int
msPostGISFindBestType(wkbObj *w, shapeObj *shape)
{
/* What kind of geometry is this? */
int nZMFlag;
int wkbtype = wkbType(w, &nZMFlag);
/* Generic collection, we need to look a little deeper. */
if ( wkbtype == WKB_GEOMETRYCOLLECTION )
wkbtype = wkbCollectionSubType(w, &nZMFlag);
switch ( wkbtype ) {
case WKB_POLYGON:
case WKB_CURVEPOLYGON:
case WKB_MULTIPOLYGON:
shape->type = MS_SHAPE_POLYGON;
break;
case WKB_LINESTRING:
case WKB_CIRCULARSTRING:
case WKB_COMPOUNDCURVE:
case WKB_MULTICURVE:
case WKB_MULTILINESTRING:
shape->type = MS_SHAPE_LINE;
break;
case WKB_POINT:
case WKB_MULTIPOINT:
shape->type = MS_SHAPE_POINT;
break;
default:
return MS_FAILURE;
}
return wkbConvGeometryToShape(w, shape);
}
/*
** Get the PostGIS version number from the database as integer.
** Versions are multiplied out as with PgSQL: 1.5.2 -> 10502, 2.0.0 -> 20000.
*/
static int
msPostGISRetrieveVersion(PGconn *pgconn)
{
static const char* sql = "SELECT postgis_version()";
if ( ! pgconn ) {
msSetError(MS_QUERYERR, "No open connection.", "msPostGISRetrieveVersion()");
return MS_FAILURE;
}
PGresult* pgresult = PQexecParams(pgconn, sql,0, nullptr, nullptr, nullptr, nullptr, 0);
if ( !pgresult || PQresultStatus(pgresult) != PGRES_TUPLES_OK) {
msDebug("Error executing SQL: (%s) in msPostGISRetrieveVersion()", sql);
msSetError(MS_QUERYERR, "Error executing SQL. check server logs.", "msPostGISRetrieveVersion()");
return MS_FAILURE;
}
if (PQgetisnull(pgresult, 0, 0)) {
PQclear(pgresult);
msSetError(MS_QUERYERR,"Null result returned.","msPostGISRetrieveVersion()");
return MS_FAILURE;
}
std::string strVersion = PQgetvalue(pgresult, 0, 0);
PQclear(pgresult);
char* ptr = &strVersion[0];
char *strParts[3] = { nullptr, nullptr, nullptr };
int j = 0;
strParts[j++] = &strVersion[0];
while( *ptr != '\0' && j < 3 ) {
if ( *ptr == '.' ) {
*ptr = '\0';
strParts[j++] = ptr + 1;
}
if ( *ptr == ' ' ) {
*ptr = '\0';
break;
}
ptr++;
}
int version = 0;
int factor = 10000;
for( int i = 0; i < j; i++ ) {
version += factor * atoi(strParts[i]);
factor = factor / 100;
}
return version;
}
/*
** msPostGISRetrievePK()
**
** Find out that the primary key is for this layer.
** The layerinfo->fromsource must already be populated and
** must not be a subquery.