forked from postgis/postgis
/
mvt.c
1567 lines (1359 loc) · 40.1 KB
/
mvt.c
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
/**********************************************************************
*
* PostGIS - Spatial Types for PostgreSQL
* http://postgis.net
*
* PostGIS is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 2 of the License, or
* (at your option) any later version.
*
* PostGIS is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with PostGIS. If not, see <http://www.gnu.org/licenses/>.
*
**********************************************************************
*
* Copyright (C) 2016-2017 Björn Harrtell <bjorn@wololo.org>
*
**********************************************************************/
#include <string.h>
#include "mvt.h"
#include "lwgeom_geos.h"
#include "pgsql_compat.h"
#ifdef HAVE_LIBPROTOBUF
#include "utils/jsonb.h"
#if POSTGIS_PGSQL_VERSION < 110
/* See trac ticket #3867 */
# define DatumGetJsonbP DatumGetJsonb
#endif
#include "uthash.h"
#define FEATURES_CAPACITY_INITIAL 50
enum mvt_cmd_id
{
CMD_MOVE_TO = 1,
CMD_LINE_TO = 2,
CMD_CLOSE_PATH = 7
};
enum mvt_type
{
MVT_POINT = 1,
MVT_LINE = 2,
MVT_RING = 3
};
struct mvt_kv_key
{
char *name;
uint32_t id;
UT_hash_handle hh;
};
struct mvt_kv_string_value
{
char *string_value;
uint32_t id;
UT_hash_handle hh;
};
struct mvt_kv_float_value
{
float float_value;
uint32_t id;
UT_hash_handle hh;
};
struct mvt_kv_double_value
{
double double_value;
uint32_t id;
UT_hash_handle hh;
};
struct mvt_kv_uint_value
{
uint64_t uint_value;
uint32_t id;
UT_hash_handle hh;
};
struct mvt_kv_sint_value
{
int64_t sint_value;
uint32_t id;
UT_hash_handle hh;
};
struct mvt_kv_bool_value
{
protobuf_c_boolean bool_value;
uint32_t id;
UT_hash_handle hh;
};
static inline uint32_t c_int(enum mvt_cmd_id id, uint32_t count)
{
return (id & 0x7) | (count << 3);
}
static inline uint32_t p_int(int32_t value)
{
return (value << 1) ^ (value >> 31);
}
static uint32_t encode_ptarray(__attribute__((__unused__)) mvt_agg_context *ctx,
enum mvt_type type, POINTARRAY *pa, uint32_t *buffer,
int32_t *px, int32_t *py)
{
uint32_t offset = 0;
uint32_t i, c = 0;
int32_t dx, dy, x, y;
const POINT2D *p;
/* loop points and add to buffer */
for (i = 0; i < pa->npoints; i++)
{
/* move offset for command */
if (i == 0 || (i == 1 && type > MVT_POINT))
offset++;
/* skip closing point for rings */
if (type == MVT_RING && i == pa->npoints - 1)
break;
p = getPoint2d_cp(pa, i);
x = p->x;
y = p->y;
dx = x - *px;
dy = y - *py;
buffer[offset++] = p_int(dx);
buffer[offset++] = p_int(dy);
*px = x;
*py = y;
c++;
}
/* determine initial move and eventual line command */
if (type == MVT_POINT)
{
/* point or multipoint, use actual number of point count */
buffer[0] = c_int(CMD_MOVE_TO, c);
}
else
{
/* line or polygon, assume count 1 */
buffer[0] = c_int(CMD_MOVE_TO, 1);
/* line command with move point subtracted from count */
buffer[3] = c_int(CMD_LINE_TO, c - 1);
}
/* add close command if ring */
if (type == MVT_RING)
buffer[offset++] = c_int(CMD_CLOSE_PATH, 1);
return offset;
}
static uint32_t encode_ptarray_initial(mvt_agg_context *ctx,
enum mvt_type type,
POINTARRAY *pa, uint32_t *buffer)
{
int32_t px = 0, py = 0;
return encode_ptarray(ctx, type, pa, buffer, &px, &py);
}
static void encode_point(mvt_agg_context *ctx, LWPOINT *point)
{
VectorTile__Tile__Feature *feature = ctx->feature;
feature->type = VECTOR_TILE__TILE__GEOM_TYPE__POINT;
feature->has_type = 1;
feature->n_geometry = 3;
feature->geometry = palloc(sizeof(*feature->geometry) * 3);
encode_ptarray_initial(ctx, MVT_POINT, point->point, feature->geometry);
}
static void encode_mpoint(mvt_agg_context *ctx, LWMPOINT *mpoint)
{
size_t c;
VectorTile__Tile__Feature *feature = ctx->feature;
// NOTE: inefficient shortcut LWMPOINT->LWLINE
LWLINE *lwline = lwline_from_lwmpoint(mpoint->srid, mpoint);
feature->type = VECTOR_TILE__TILE__GEOM_TYPE__POINT;
feature->has_type = 1;
c = 1 + lwline->points->npoints * 2;
feature->geometry = palloc(sizeof(*feature->geometry) * c);
feature->n_geometry = encode_ptarray_initial(ctx, MVT_POINT,
lwline->points, feature->geometry);
}
static void encode_line(mvt_agg_context *ctx, LWLINE *lwline)
{
size_t c;
VectorTile__Tile__Feature *feature = ctx->feature;
feature->type = VECTOR_TILE__TILE__GEOM_TYPE__LINESTRING;
feature->has_type = 1;
c = 2 + lwline->points->npoints * 2;
feature->geometry = palloc(sizeof(*feature->geometry) * c);
feature->n_geometry = encode_ptarray_initial(ctx, MVT_LINE,
lwline->points, feature->geometry);
}
static void encode_mline(mvt_agg_context *ctx, LWMLINE *lwmline)
{
uint32_t i;
int32_t px = 0, py = 0;
size_t c = 0, offset = 0;
VectorTile__Tile__Feature *feature = ctx->feature;
feature->type = VECTOR_TILE__TILE__GEOM_TYPE__LINESTRING;
feature->has_type = 1;
for (i = 0; i < lwmline->ngeoms; i++)
c += 2 + lwmline->geoms[i]->points->npoints * 2;
feature->geometry = palloc(sizeof(*feature->geometry) * c);
for (i = 0; i < lwmline->ngeoms; i++)
offset += encode_ptarray(ctx, MVT_LINE,
lwmline->geoms[i]->points,
feature->geometry + offset, &px, &py);
feature->n_geometry = offset;
}
static void encode_poly(mvt_agg_context *ctx, LWPOLY *lwpoly)
{
uint32_t i;
int32_t px = 0, py = 0;
size_t c = 0, offset = 0;
VectorTile__Tile__Feature *feature = ctx->feature;
feature->type = VECTOR_TILE__TILE__GEOM_TYPE__POLYGON;
feature->has_type = 1;
for (i = 0; i < lwpoly->nrings; i++)
c += 3 + ((lwpoly->rings[i]->npoints - 1) * 2);
feature->geometry = palloc(sizeof(*feature->geometry) * c);
for (i = 0; i < lwpoly->nrings; i++)
offset += encode_ptarray(ctx, MVT_RING,
lwpoly->rings[i],
feature->geometry + offset, &px, &py);
feature->n_geometry = offset;
}
static void encode_mpoly(mvt_agg_context *ctx, LWMPOLY *lwmpoly)
{
uint32_t i, j;
int32_t px = 0, py = 0;
size_t c = 0, offset = 0;
LWPOLY *poly;
VectorTile__Tile__Feature *feature = ctx->feature;
feature->type = VECTOR_TILE__TILE__GEOM_TYPE__POLYGON;
feature->has_type = 1;
for (i = 0; i < lwmpoly->ngeoms; i++)
for (j = 0; poly = lwmpoly->geoms[i], j < poly->nrings; j++)
c += 3 + ((poly->rings[j]->npoints - 1) * 2);
feature->geometry = palloc(sizeof(*feature->geometry) * c);
for (i = 0; i < lwmpoly->ngeoms; i++)
for (j = 0; poly = lwmpoly->geoms[i], j < poly->nrings; j++)
offset += encode_ptarray(ctx, MVT_RING,
poly->rings[j], feature->geometry + offset,
&px, &py);
feature->n_geometry = offset;
}
static void encode_geometry(mvt_agg_context *ctx, LWGEOM *lwgeom)
{
int type = lwgeom->type;
switch (type)
{
case POINTTYPE:
return encode_point(ctx, (LWPOINT*)lwgeom);
case LINETYPE:
return encode_line(ctx, (LWLINE*)lwgeom);
case POLYGONTYPE:
return encode_poly(ctx, (LWPOLY*)lwgeom);
case MULTIPOINTTYPE:
return encode_mpoint(ctx, (LWMPOINT*)lwgeom);
case MULTILINETYPE:
return encode_mline(ctx, (LWMLINE*)lwgeom);
case MULTIPOLYGONTYPE:
return encode_mpoly(ctx, (LWMPOLY*)lwgeom);
default: elog(ERROR, "encode_geometry: '%s' geometry type not supported",
lwtype_name(type));
}
}
static TupleDesc get_tuple_desc(mvt_agg_context *ctx)
{
Oid tupType = HeapTupleHeaderGetTypeId(ctx->row);
int32 tupTypmod = HeapTupleHeaderGetTypMod(ctx->row);
TupleDesc tupdesc = lookup_rowtype_tupdesc(tupType, tupTypmod);
return tupdesc;
}
static uint32_t get_key_index_with_size(mvt_agg_context *ctx, const char *name, size_t size)
{
struct mvt_kv_key *kv;
HASH_FIND(hh, ctx->keys_hash, name, size, kv);
if (!kv)
return UINT32_MAX;
return kv->id;
}
static uint32_t add_key(mvt_agg_context *ctx, char *name)
{
struct mvt_kv_key *kv;
size_t size = strlen(name);
kv = palloc(sizeof(*kv));
kv->id = ctx->keys_hash_i++;
kv->name = name;
HASH_ADD_KEYPTR(hh, ctx->keys_hash, name, size, kv);
return kv->id;
}
static void parse_column_keys(mvt_agg_context *ctx)
{
uint32_t i, natts;
bool geom_found = false;
POSTGIS_DEBUG(2, "parse_column_keys called");
ctx->column_cache.tupdesc = get_tuple_desc(ctx);
natts = ctx->column_cache.tupdesc->natts;
ctx->column_cache.column_keys_index = palloc(sizeof(uint32_t) * natts);
ctx->column_cache.column_oid = palloc(sizeof(uint32_t) * natts);
ctx->column_cache.values = palloc(sizeof(Datum) * natts);
ctx->column_cache.nulls = palloc(sizeof(bool) * natts);
for (i = 0; i < natts; i++)
{
Oid typoid = getBaseType(TupleDescAttr(ctx->column_cache.tupdesc, i)->atttypid);
char *tkey = TupleDescAttr(ctx->column_cache.tupdesc, i)->attname.data;
ctx->column_cache.column_oid[i] = typoid;
if (typoid == JSONBOID)
{
ctx->column_cache.column_keys_index[i] = UINT32_MAX;
continue;
}
if (ctx->geom_name == NULL)
{
if (!geom_found && typoid == TypenameGetTypid("geometry"))
{
ctx->geom_index = i;
geom_found = true;
continue;
}
}
else
{
if (!geom_found && strcmp(tkey, ctx->geom_name) == 0)
{
ctx->geom_index = i;
geom_found = true;
continue;
}
}
if (ctx->id_name &&
(ctx->id_index == UINT32_MAX) &&
(strcmp(tkey, ctx->id_name) == 0) &&
(typoid == INT2OID || typoid == INT4OID || typoid == INT8OID))
{
ctx->id_index = i;
}
else
{
ctx->column_cache.column_keys_index[i] = add_key(ctx, pstrdup(tkey));
}
}
if (!geom_found)
elog(ERROR, "parse_column_keys: no geometry column found");
if (ctx->id_name != NULL && ctx->id_index == UINT32_MAX)
elog(ERROR, "mvt_agg_transfn: Could not find column '%s' of integer type", ctx->id_name);
}
static void encode_keys(mvt_agg_context *ctx)
{
struct mvt_kv_key *kv;
size_t n_keys = ctx->keys_hash_i;
char **keys = palloc(n_keys * sizeof(*keys));
for (kv = ctx->keys_hash; kv != NULL; kv=kv->hh.next)
keys[kv->id] = kv->name;
ctx->layer->n_keys = n_keys;
ctx->layer->keys = keys;
HASH_CLEAR(hh, ctx->keys_hash);
}
static VectorTile__Tile__Value *create_value()
{
VectorTile__Tile__Value *value = palloc(sizeof(*value));
vector_tile__tile__value__init(value);
return value;
}
#define MVT_CREATE_VALUES(kvtype, hash, hasfield, valuefield) \
{ \
POSTGIS_DEBUG(2, "MVT_CREATE_VALUES called"); \
{ \
struct kvtype *kv; \
for (kv = ctx->hash; kv != NULL; kv=kv->hh.next) \
{ \
VectorTile__Tile__Value *value = create_value(); \
value->hasfield = 1; \
value->valuefield = kv->valuefield; \
values[kv->id] = value; \
} \
} \
}
static void encode_values(mvt_agg_context *ctx)
{
VectorTile__Tile__Value **values;
struct mvt_kv_string_value *kv;
POSTGIS_DEBUG(2, "encode_values called");
values = palloc(ctx->values_hash_i * sizeof(*values));
for (kv = ctx->string_values_hash; kv != NULL; kv=kv->hh.next)
{
VectorTile__Tile__Value *value = create_value();
value->string_value = kv->string_value;
values[kv->id] = value;
}
MVT_CREATE_VALUES(mvt_kv_float_value,
float_values_hash, has_float_value, float_value);
MVT_CREATE_VALUES(mvt_kv_double_value,
double_values_hash, has_double_value, double_value);
MVT_CREATE_VALUES(mvt_kv_uint_value,
uint_values_hash, has_uint_value, uint_value);
MVT_CREATE_VALUES(mvt_kv_sint_value,
sint_values_hash, has_sint_value, sint_value);
MVT_CREATE_VALUES(mvt_kv_bool_value,
bool_values_hash, has_bool_value, bool_value);
POSTGIS_DEBUGF(3, "encode_values n_values: %d", ctx->values_hash_i);
ctx->layer->n_values = ctx->values_hash_i;
ctx->layer->values = values;
HASH_CLEAR(hh, ctx->string_values_hash);
HASH_CLEAR(hh, ctx->float_values_hash);
HASH_CLEAR(hh, ctx->double_values_hash);
HASH_CLEAR(hh, ctx->uint_values_hash);
HASH_CLEAR(hh, ctx->sint_values_hash);
HASH_CLEAR(hh, ctx->bool_values_hash);
pfree(ctx->column_cache.column_keys_index);
pfree(ctx->column_cache.column_oid);
pfree(ctx->column_cache.values);
pfree(ctx->column_cache.nulls);
ReleaseTupleDesc(ctx->column_cache.tupdesc);
memset(&ctx->column_cache, 0, sizeof(ctx->column_cache));
}
#define MVT_PARSE_VALUE(value, kvtype, hash, valuefield, size) \
{ \
POSTGIS_DEBUG(2, "MVT_PARSE_VALUE called"); \
{ \
struct kvtype *kv; \
HASH_FIND(hh, ctx->hash, &value, size, kv); \
if (!kv) \
{ \
POSTGIS_DEBUG(4, "MVT_PARSE_VALUE value not found"); \
kv = palloc(sizeof(*kv)); \
POSTGIS_DEBUGF(4, "MVT_PARSE_VALUE new hash key: %d", \
ctx->values_hash_i); \
kv->id = ctx->values_hash_i++; \
kv->valuefield = value; \
HASH_ADD(hh, ctx->hash, valuefield, size, kv); \
} \
tags[ctx->row_columns*2] = k; \
tags[ctx->row_columns*2+1] = kv->id; \
} \
}
#define MVT_PARSE_INT_VALUE(value) \
{ \
if (value >= 0) \
{ \
uint64_t cvalue = value; \
MVT_PARSE_VALUE(cvalue, mvt_kv_uint_value, \
uint_values_hash, uint_value, \
sizeof(uint64_t)) \
} \
else \
{ \
int64_t cvalue = value; \
MVT_PARSE_VALUE(cvalue, mvt_kv_sint_value, \
sint_values_hash, sint_value, \
sizeof(int64_t)) \
} \
}
#define MVT_PARSE_DATUM(type, kvtype, hash, valuefield, datumfunc, size) \
{ \
type value = datumfunc(datum); \
MVT_PARSE_VALUE(value, kvtype, hash, valuefield, size); \
}
#define MVT_PARSE_INT_DATUM(type, datumfunc) \
{ \
type value = datumfunc(datum); \
MVT_PARSE_INT_VALUE(value); \
}
static void add_value_as_string_with_size(mvt_agg_context *ctx,
char *value, size_t size, uint32_t *tags, uint32_t k)
{
struct mvt_kv_string_value *kv;
POSTGIS_DEBUG(2, "add_value_as_string called");
HASH_FIND(hh, ctx->string_values_hash, value, size, kv);
if (!kv)
{
POSTGIS_DEBUG(4, "add_value_as_string value not found");
kv = palloc(sizeof(*kv));
POSTGIS_DEBUGF(4, "add_value_as_string new hash key: %d",
ctx->values_hash_i);
kv->id = ctx->values_hash_i++;
kv->string_value = value;
HASH_ADD_KEYPTR(hh, ctx->string_values_hash, kv->string_value,
size, kv);
}
tags[ctx->row_columns*2] = k;
tags[ctx->row_columns*2+1] = kv->id;
}
static void add_value_as_string(mvt_agg_context *ctx,
char *value, uint32_t *tags, uint32_t k)
{
return add_value_as_string_with_size(ctx, value, strlen(value), tags, k);
}
static void parse_datum_as_string(mvt_agg_context *ctx, Oid typoid,
Datum datum, uint32_t *tags, uint32_t k)
{
Oid foutoid;
bool typisvarlena;
char *value;
POSTGIS_DEBUG(2, "parse_value_as_string called");
getTypeOutputInfo(typoid, &foutoid, &typisvarlena);
value = OidOutputFunctionCall(foutoid, datum);
POSTGIS_DEBUGF(4, "parse_value_as_string value: %s", value);
add_value_as_string(ctx, value, tags, k);
}
static uint32_t *parse_jsonb(mvt_agg_context *ctx, Jsonb *jb,
uint32_t *tags)
{
JsonbIterator *it;
JsonbValue v;
bool skipNested = false;
JsonbIteratorToken r;
uint32_t k;
if (!JB_ROOT_IS_OBJECT(jb))
return tags;
it = JsonbIteratorInit(&jb->root);
while ((r = JsonbIteratorNext(&it, &v, skipNested)) != WJB_DONE)
{
skipNested = true;
if (r == WJB_KEY && v.type != jbvNull)
{
k = get_key_index_with_size(ctx, v.val.string.val, v.val.string.len);
if (k == UINT32_MAX)
{
char *key;
uint32_t newSize = ctx->keys_hash_i + 1;
key = palloc(v.val.string.len + 1);
memcpy(key, v.val.string.val, v.val.string.len);
key[v.val.string.len] = '\0';
tags = repalloc(tags, newSize * 2 * sizeof(*tags));
k = add_key(ctx, key);
}
r = JsonbIteratorNext(&it, &v, skipNested);
if (v.type == jbvString)
{
char *value;
value = palloc(v.val.string.len + 1);
memcpy(value, v.val.string.val, v.val.string.len);
value[v.val.string.len] = '\0';
add_value_as_string(ctx, value, tags, k);
ctx->row_columns++;
}
else if (v.type == jbvBool)
{
MVT_PARSE_VALUE(v.val.boolean, mvt_kv_bool_value,
bool_values_hash, bool_value, sizeof(protobuf_c_boolean));
ctx->row_columns++;
}
else if (v.type == jbvNumeric)
{
char *str;
double d;
long l;
str = DatumGetCString(DirectFunctionCall1(numeric_out,
PointerGetDatum(v.val.numeric)));
d = strtod(str, NULL);
l = strtol(str, NULL, 10);
if (FP_NEQUALS(d, (double)l))
{
MVT_PARSE_VALUE(d, mvt_kv_double_value, double_values_hash,
double_value, sizeof(double));
}
else
{
MVT_PARSE_INT_VALUE(l);
}
ctx->row_columns++;
}
}
}
return tags;
}
/**
* Sets the feature id. Ignores Nulls and negative values
*/
static void set_feature_id(mvt_agg_context *ctx, Datum datum, bool isNull)
{
Oid typoid = ctx->column_cache.column_oid[ctx->id_index];
int64_t value = INT64_MIN;
if (isNull)
{
POSTGIS_DEBUG(3, "set_feature_id: Ignored null value");
return;
}
switch (typoid)
{
case INT2OID:
value = DatumGetInt16(datum);
break;
case INT4OID:
value = DatumGetInt32(datum);
break;
case INT8OID:
value = DatumGetInt64(datum);
break;
default:
elog(ERROR, "set_feature_id: Feature id type does not match");
}
if (value < 0)
{
POSTGIS_DEBUG(3, "set_feature_id: Ignored negative value");
return;
}
ctx->feature->has_id = true;
ctx->feature->id = (uint64_t) value;
}
static void parse_values(mvt_agg_context *ctx)
{
uint32_t n_keys = ctx->keys_hash_i;
uint32_t *tags = palloc(n_keys * 2 * sizeof(*tags));
uint32_t i;
mvt_column_cache cc = ctx->column_cache;
uint32_t natts = (uint32_t) cc.tupdesc->natts;
HeapTupleData tuple;
POSTGIS_DEBUG(2, "parse_values called");
ctx->row_columns = 0;
/* Build a temporary HeapTuple control structure */
tuple.t_len = HeapTupleHeaderGetDatumLength(ctx->row);
ItemPointerSetInvalid(&(tuple.t_self));
tuple.t_tableOid = InvalidOid;
tuple.t_data = ctx->row;
/* We use heap_deform_tuple as it costs only O(N) vs O(N^2) of GetAttributeByNum */
heap_deform_tuple(&tuple, cc.tupdesc, cc.values, cc.nulls);
POSTGIS_DEBUGF(3, "parse_values natts: %d", natts);
for (i = 0; i < natts; i++)
{
char *key;
Oid typoid;
uint32_t k;
Datum datum = cc.values[i];
if (i == ctx->geom_index)
continue;
if (i == ctx->id_index)
{
set_feature_id(ctx, datum, cc.nulls[i]);
continue;
}
if (cc.nulls[i])
{
POSTGIS_DEBUG(3, "parse_values isnull detected");
continue;
}
key = TupleDescAttr(cc.tupdesc, i)->attname.data;
k = cc.column_keys_index[i];
typoid = cc.column_oid[i];
if (k == UINT32_MAX && typoid != JSONBOID)
elog(ERROR, "parse_values: unexpectedly could not find parsed key name '%s'", key);
if (typoid == JSONBOID)
{
tags = parse_jsonb(ctx, DatumGetJsonbP(datum), tags);
continue;
}
switch (typoid)
{
case BOOLOID:
MVT_PARSE_DATUM(protobuf_c_boolean, mvt_kv_bool_value,
bool_values_hash, bool_value,
DatumGetBool, sizeof(protobuf_c_boolean));
break;
case INT2OID:
MVT_PARSE_INT_DATUM(int16_t, DatumGetInt16);
break;
case INT4OID:
MVT_PARSE_INT_DATUM(int32_t, DatumGetInt32);
break;
case INT8OID:
MVT_PARSE_INT_DATUM(int64_t, DatumGetInt64);
break;
case FLOAT4OID:
MVT_PARSE_DATUM(float, mvt_kv_float_value,
float_values_hash, float_value,
DatumGetFloat4, sizeof(float));
break;
case FLOAT8OID:
MVT_PARSE_DATUM(double, mvt_kv_double_value,
double_values_hash, double_value,
DatumGetFloat8, sizeof(double));
break;
default:
parse_datum_as_string(ctx, typoid, datum, tags, k);
break;
}
ctx->row_columns++;
}
ctx->feature->n_tags = ctx->row_columns * 2;
ctx->feature->tags = tags;
POSTGIS_DEBUGF(3, "parse_values n_tags %zd", ctx->feature->n_tags);
}
/* For a given geometry, look for the highest dimensional basic type, that is,
* point, line or polygon */
static uint8
lwgeom_get_basic_type(LWGEOM *geom)
{
switch(geom->type)
{
case POINTTYPE:
case LINETYPE:
case POLYGONTYPE:
return geom->type;
case MULTIPOINTTYPE:
case MULTILINETYPE:
case MULTIPOLYGONTYPE:
return geom->type - 3; /* Based on LWTYPE positions */
case COLLECTIONTYPE:
{
uint32_t i;
uint8 type = 0;
LWCOLLECTION *g = (LWCOLLECTION*)geom;
for (i = 0; i < g->ngeoms; i++)
{
LWGEOM *sg = g->geoms[i];
type = Max(type, lwgeom_get_basic_type(sg));
}
return type;
}
default:
elog(ERROR, "%s: Invalid type (%d)", __func__, geom->type);
}
}
/**
* In place process a collection to find a concrete geometry
* object and expose that as the actual object. Will some
* geom be lost? Sure, but your MVT renderer couldn't
* draw it anyways.
*/
static inline LWGEOM *
lwgeom_to_basic_type(LWGEOM *geom, uint8 original_type)
{
LWGEOM *geom_out = geom;
if (lwgeom_get_type(geom) == COLLECTIONTYPE)
{
LWCOLLECTION *g = (LWCOLLECTION*)geom;
geom_out = (LWGEOM *)lwcollection_extract(g, original_type);
}
/* If a collection only contains 1 geometry return than instead */
if (lwgeom_is_collection(geom_out))
{
LWCOLLECTION *g = (LWCOLLECTION *)geom_out;
if (g->ngeoms == 1)
{
geom_out = g->geoms[0];
}
}
geom_out->srid = geom->srid;
return geom_out;
}
static LWGEOM *
mvt_unsafe_clip_by_box(LWGEOM *lwg_in, GBOX *clip_box)
{
LWGEOM *geom_clipped;
GBOX geom_box;
gbox_init(&geom_box);
FLAGS_SET_GEODETIC(geom_box.flags, 0);
lwgeom_calculate_gbox(lwg_in, &geom_box);
if (!gbox_overlaps_2d(&geom_box, clip_box))
{
POSTGIS_DEBUG(3, "mvt_geom: geometry outside clip box");
return NULL;
}
if (gbox_contains_2d(clip_box, &geom_box))
{
POSTGIS_DEBUG(3, "mvt_geom: geometry contained fully inside the box");
return lwg_in;
}
geom_clipped = lwgeom_clip_by_rect(lwg_in, clip_box->xmin, clip_box->ymin, clip_box->xmax, clip_box->ymax);
if (!geom_clipped || lwgeom_is_empty(geom_clipped))
return NULL;
return geom_clipped;
}
/**
* Clips an input geometry using GEOSIntersection
* As you can get invalid output of invalid input, it tries to detect
* if something has gone wrong by checking the bounding box of the input
* and the output. If the output isn't contained in the input geometry and
* *retry* is true, it cleans the input and retries, else it returns NULL
*/
static LWGEOM *
mvt_safe_clip_polygon_by_box(LWGEOM *lwg_in, GBOX *clip_box)
{
LWGEOM *geom_clipped, *envelope;
GBOX geom_box;
GEOSGeometry *geos_input, *geos_box, *geos_result;
gbox_init(&geom_box);
FLAGS_SET_GEODETIC(geom_box.flags, 0);
lwgeom_calculate_gbox(lwg_in, &geom_box);
if (!gbox_overlaps_2d(&geom_box, clip_box))
{
POSTGIS_DEBUG(3, "mvt_geom: geometry outside clip box");
return NULL;
}
if (gbox_contains_2d(clip_box, &geom_box))
{
POSTGIS_DEBUG(3, "mvt_geom: geometry contained fully inside the box");
return lwg_in;
}
initGEOS(lwnotice, lwgeom_geos_error);
if (!(geos_input = LWGEOM2GEOS(lwg_in, 1)))
return NULL;
envelope = (LWGEOM *)lwpoly_construct_envelope(
lwg_in->srid, clip_box->xmin, clip_box->ymin, clip_box->xmax, clip_box->ymax);
geos_box = LWGEOM2GEOS(envelope, 1);
lwgeom_free(envelope);
if (!geos_box)
{
GEOSGeom_destroy(geos_input);
return NULL;
}
geos_result = GEOSIntersection(geos_input, geos_box);
if (!geos_result)
{
POSTGIS_DEBUG(3, "mvt_geom: no geometry after intersection. Retrying after validation");
GEOSGeom_destroy(geos_input);
lwg_in = lwgeom_make_valid(lwg_in);
if (!(geos_input = LWGEOM2GEOS(lwg_in, 1)))
{
GEOSGeom_destroy(geos_box);
return NULL;
}
geos_result = GEOSIntersection(geos_input, geos_box);
if (!geos_result)
{
GEOSGeom_destroy(geos_box);
GEOSGeom_destroy(geos_input);
return NULL;
}
}
GEOSSetSRID(geos_result, lwg_in->srid);
geom_clipped = GEOS2LWGEOM(geos_result, 0);
GEOSGeom_destroy(geos_box);
GEOSGeom_destroy(geos_input);
GEOSGeom_destroy(geos_result);
if (!geom_clipped || lwgeom_is_empty(geom_clipped))
{
POSTGIS_DEBUG(3, "mvt_geom: no geometry after clipping");
return NULL;
}
return geom_clipped;
}
/**
* Clips the geometry using GEOSIntersection in a "safe way", cleaning the input
* if necessary and clipping MULTIPOLYGONs separately to reduce the impact
* of using invalid input in GEOS
*/
static LWGEOM *
mvt_iterate_clip_by_box_geos(LWGEOM *lwgeom, GBOX *clip_gbox, uint8_t basic_type)
{
if (basic_type != POLYGONTYPE)
{
return mvt_unsafe_clip_by_box(lwgeom, clip_gbox);
}
if (lwgeom->type != MULTIPOLYGONTYPE || ((LWMPOLY *)lwgeom)->ngeoms == 1)
{
return mvt_safe_clip_polygon_by_box(lwgeom, clip_gbox);
}
else
{
GBOX geom_box;
uint32_t i;
LWCOLLECTION *lwmg;
LWCOLLECTION *res;
gbox_init(&geom_box);
FLAGS_SET_GEODETIC(geom_box.flags, 0);
lwgeom_calculate_gbox(lwgeom, &geom_box);
lwmg = ((LWCOLLECTION *)lwgeom);
res = lwcollection_construct_empty(
MULTIPOLYGONTYPE, lwgeom->srid, FLAGS_GET_Z(lwgeom->flags), FLAGS_GET_M(lwgeom->flags));
for (i = 0; i < lwmg->ngeoms; i++)
{
LWGEOM *clipped = mvt_safe_clip_polygon_by_box(lwcollection_getsubgeom(lwmg, i), clip_gbox);
if (clipped)
{
clipped = lwgeom_to_basic_type(clipped, POLYGONTYPE);
if (!lwgeom_is_empty(clipped) &&
(clipped->type == POLYGONTYPE || clipped->type == MULTIPOLYGONTYPE))
{
if (!lwgeom_is_collection(clipped))
{
lwcollection_add_lwgeom(res, clipped);
}
else
{
uint32_t j;
for (j = 0; j < ((LWCOLLECTION *)clipped)->ngeoms; j++)
lwcollection_add_lwgeom(
res, lwcollection_getsubgeom((LWCOLLECTION *)clipped, j));
}
}
}
}
return lwcollection_as_lwgeom(res);
}
}