forked from OSGeo/shapelib
-
Notifications
You must be signed in to change notification settings - Fork 0
/
sbnsearch.c
1015 lines (876 loc) · 36.7 KB
/
sbnsearch.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
/******************************************************************************
*
* Project: Shapelib
* Purpose: Implementation of search in ESRI SBN spatial index.
* Author: Even Rouault, even dot rouault at spatialys.com
*
******************************************************************************
* Copyright (c) 2012-2024, Even Rouault <even dot rouault at spatialys.com>
*
* SPDX-License-Identifier: MIT OR LGPL-2.0-or-later
******************************************************************************/
#include "shapefil_private.h"
#include <assert.h>
#include <math.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#ifndef USE_CPL
#if defined(_MSC_VER)
#if _MSC_VER < 1900
#define snprintf _snprintf
#endif
#elif defined(_WIN32)
#ifndef snprintf
#define snprintf _snprintf
#endif
#endif
#endif
#define CACHED_DEPTH_LIMIT 8
#define READ_MSB_INT(ptr) \
STATIC_CAST(int, (((STATIC_CAST(unsigned, (ptr)[0])) << 24) | \
((ptr)[1] << 16) | ((ptr)[2] << 8) | (ptr)[3]))
typedef int coord;
/*typedef unsigned char coord;*/
typedef struct
{
unsigned char
*pabyShapeDesc; /* Cache of (nShapeCount * 8) bytes of the bins. May
be NULL. */
int nBinStart; /* Index of first bin for this node. */
int nShapeCount; /* Number of shapes attached to this node. */
int nBinCount; /* Number of bins for this node. May be 0 if node is empty.
*/
int nBinOffset; /* Offset in file of the start of the first bin. May be 0 if
node is empty. */
bool bBBoxInit; /* true if the following bounding box has been computed. */
coord
bMinX; /* Bounding box of the shapes directly attached to this node. */
coord bMinY; /* This is *not* the theoretical footprint of the node. */
coord bMaxX;
coord bMaxY;
} SBNNodeDescriptor;
struct SBNSearchInfo
{
SAHooks sHooks;
SAFile fpSBN;
SBNNodeDescriptor *pasNodeDescriptor;
int nShapeCount; /* Total number of shapes */
int nMaxDepth; /* Tree depth */
double dfMinX; /* Bounding box of all shapes */
double dfMaxX;
double dfMinY;
double dfMaxY;
#ifdef DEBUG_IO
int nTotalBytesRead;
#endif
};
typedef struct
{
SBNSearchHandle hSBN;
coord bMinX; /* Search bounding box */
coord bMinY;
coord bMaxX;
coord bMaxY;
int nShapeCount;
int nShapeAlloc;
int *panShapeId; /* 0 based */
unsigned char abyBinShape[8 * 100];
#ifdef DEBUG_IO
int nBytesRead;
#endif
} SearchStruct;
/* Associates a node id with the index of its first bin */
typedef struct
{
int nNodeId;
int nBinStart;
} SBNNodeIdBinStartPair;
/************************************************************************/
/* SBNCompareNodeIdBinStartPairs() */
/************************************************************************/
/* helper for qsort, to sort SBNNodeIdBinStartPair by increasing nBinStart */
static int SBNCompareNodeIdBinStartPairs(const void *a, const void *b)
{
return STATIC_CAST(const SBNNodeIdBinStartPair *, a)->nBinStart -
STATIC_CAST(const SBNNodeIdBinStartPair *, b)->nBinStart;
}
/************************************************************************/
/* SBNOpenDiskTree() */
/************************************************************************/
SBNSearchHandle SBNOpenDiskTree(const char *pszSBNFilename,
const SAHooks *psHooks)
{
/* -------------------------------------------------------------------- */
/* Initialize the handle structure. */
/* -------------------------------------------------------------------- */
SBNSearchHandle hSBN =
STATIC_CAST(SBNSearchHandle, calloc(1, sizeof(struct SBNSearchInfo)));
if (psHooks == SHPLIB_NULLPTR)
SASetupDefaultHooks(&(hSBN->sHooks));
else
memcpy(&(hSBN->sHooks), psHooks, sizeof(SAHooks));
hSBN->fpSBN =
hSBN->sHooks.FOpen(pszSBNFilename, "rb", hSBN->sHooks.pvUserData);
if (hSBN->fpSBN == SHPLIB_NULLPTR)
{
free(hSBN);
return SHPLIB_NULLPTR;
}
/* -------------------------------------------------------------------- */
/* Check file header signature. */
/* -------------------------------------------------------------------- */
unsigned char abyHeader[108];
if (hSBN->sHooks.FRead(abyHeader, 108, 1, hSBN->fpSBN) != 1 ||
abyHeader[0] != 0 || abyHeader[1] != 0 || abyHeader[2] != 0x27 ||
(abyHeader[3] != 0x0A && abyHeader[3] != 0x0D) ||
abyHeader[4] != 0xFF || abyHeader[5] != 0xFF || abyHeader[6] != 0xFE ||
abyHeader[7] != 0x70)
{
hSBN->sHooks.Error(".sbn file is unreadable, or corrupt.");
SBNCloseDiskTree(hSBN);
return SHPLIB_NULLPTR;
}
/* -------------------------------------------------------------------- */
/* Read shapes bounding box. */
/* -------------------------------------------------------------------- */
#if !defined(SHP_BIG_ENDIAN)
SHP_SWAPDOUBLE_CPY(&hSBN->dfMinX, abyHeader + 32);
SHP_SWAPDOUBLE_CPY(&hSBN->dfMinY, abyHeader + 40);
SHP_SWAPDOUBLE_CPY(&hSBN->dfMaxX, abyHeader + 48);
SHP_SWAPDOUBLE_CPY(&hSBN->dfMaxY, abyHeader + 56);
#else
memcpy(&hSBN->dfMinX, abyHeader + 32, 8);
memcpy(&hSBN->dfMinY, abyHeader + 40, 8);
memcpy(&hSBN->dfMaxX, abyHeader + 48, 8);
memcpy(&hSBN->dfMaxY, abyHeader + 56, 8);
#endif
if (hSBN->dfMinX > hSBN->dfMaxX || hSBN->dfMinY > hSBN->dfMaxY)
{
hSBN->sHooks.Error("Invalid extent in .sbn file.");
SBNCloseDiskTree(hSBN);
return SHPLIB_NULLPTR;
}
/* -------------------------------------------------------------------- */
/* Read and check number of shapes. */
/* -------------------------------------------------------------------- */
const int nShapeCount = READ_MSB_INT(abyHeader + 28);
hSBN->nShapeCount = nShapeCount;
if (nShapeCount < 0 || nShapeCount > 256000000)
{
char szErrorMsg[64];
snprintf(szErrorMsg, sizeof(szErrorMsg),
"Invalid shape count in .sbn : %d", nShapeCount);
hSBN->sHooks.Error(szErrorMsg);
SBNCloseDiskTree(hSBN);
return SHPLIB_NULLPTR;
}
/* Empty spatial index */
if (nShapeCount == 0)
{
return hSBN;
}
/* -------------------------------------------------------------------- */
/* Compute tree depth. */
/* It is computed such as in average there are not more than 8 */
/* shapes per node. With a minimum depth of 2, and a maximum of 24 */
/* -------------------------------------------------------------------- */
int nMaxDepth = 2;
while (nMaxDepth < 24 && nShapeCount > ((1 << nMaxDepth) - 1) * 8)
nMaxDepth++;
hSBN->nMaxDepth = nMaxDepth;
const int nMaxNodes = (1 << nMaxDepth) - 1;
/* -------------------------------------------------------------------- */
/* Check that the first bin id is 1. */
/* -------------------------------------------------------------------- */
if (READ_MSB_INT(abyHeader + 100) != 1)
{
hSBN->sHooks.Error("Unexpected bin id");
SBNCloseDiskTree(hSBN);
return SHPLIB_NULLPTR;
}
/* -------------------------------------------------------------------- */
/* Read and check number of node descriptors to be read. */
/* There are at most (2^nMaxDepth) - 1, but all are not necessary */
/* described. Non described nodes are empty. */
/* -------------------------------------------------------------------- */
const int nNodeDescSize = READ_MSB_INT(abyHeader + 104); /* 16-bit words */
/* each bin descriptor is made of 2 ints */
const int nNodeDescCount = nNodeDescSize / 4;
if ((nNodeDescSize % 4) != 0 || nNodeDescCount < 0 ||
nNodeDescCount > nMaxNodes)
{
char szErrorMsg[64];
snprintf(szErrorMsg, sizeof(szErrorMsg),
"Invalid node descriptor size in .sbn : %d",
nNodeDescSize * STATIC_CAST(int, sizeof(uint16_t)));
hSBN->sHooks.Error(szErrorMsg);
SBNCloseDiskTree(hSBN);
return SHPLIB_NULLPTR;
}
const int nNodeDescSizeBytes = nNodeDescCount * 2 * 4;
/* coverity[tainted_data] */
unsigned char *pabyData =
STATIC_CAST(unsigned char *, malloc(nNodeDescSizeBytes));
SBNNodeDescriptor *pasNodeDescriptor = STATIC_CAST(
SBNNodeDescriptor *, calloc(nMaxNodes, sizeof(SBNNodeDescriptor)));
if (pabyData == SHPLIB_NULLPTR || pasNodeDescriptor == SHPLIB_NULLPTR)
{
free(pabyData);
free(pasNodeDescriptor);
hSBN->sHooks.Error("Out of memory error");
SBNCloseDiskTree(hSBN);
return SHPLIB_NULLPTR;
}
/* -------------------------------------------------------------------- */
/* Read node descriptors. */
/* -------------------------------------------------------------------- */
if (hSBN->sHooks.FRead(pabyData, nNodeDescSizeBytes, 1, hSBN->fpSBN) != 1)
{
free(pabyData);
free(pasNodeDescriptor);
hSBN->sHooks.Error("Cannot read node descriptors");
SBNCloseDiskTree(hSBN);
return SHPLIB_NULLPTR;
}
hSBN->pasNodeDescriptor = pasNodeDescriptor;
SBNNodeIdBinStartPair *pasNodeIdBinStartPairs =
STATIC_CAST(SBNNodeIdBinStartPair *,
malloc(nNodeDescCount * sizeof(SBNNodeIdBinStartPair)));
if (pasNodeIdBinStartPairs == SHPLIB_NULLPTR)
{
free(pabyData);
hSBN->sHooks.Error("Out of memory error");
SBNCloseDiskTree(hSBN);
return SHPLIB_NULLPTR;
}
#ifdef ENABLE_SBN_SANITY_CHECKS
int nShapeCountAcc = 0;
#endif
int nEntriesInNodeIdBinStartPairs = 0;
for (int i = 0; i < nNodeDescCount; i++)
{
/* -------------------------------------------------------------------- */
/* Each node descriptor contains the index of the first bin that */
/* described it, and the number of shapes in this first bin and */
/* the following bins (in the relevant case). */
/* -------------------------------------------------------------------- */
const int nBinStart = READ_MSB_INT(pabyData + 8 * i);
const int nNodeShapeCount = READ_MSB_INT(pabyData + 8 * i + 4);
pasNodeDescriptor[i].nBinStart = nBinStart > 0 ? nBinStart : 0;
pasNodeDescriptor[i].nShapeCount = nNodeShapeCount;
#ifdef DEBUG_SBN
fprintf(stderr, "node[%d], nBinStart=%d, nShapeCount=%d\n", i,
nBinStart, nNodeShapeCount);
#endif
if ((nBinStart > 0 && nNodeShapeCount == 0) || nNodeShapeCount < 0 ||
nNodeShapeCount > nShapeCount)
{
hSBN->sHooks.Error("Inconsistent shape count in bin");
free(pabyData);
free(pasNodeIdBinStartPairs);
SBNCloseDiskTree(hSBN);
return SHPLIB_NULLPTR;
}
#ifdef ENABLE_SBN_SANITY_CHECKS
if (nShapeCountAcc > nShapeCount - nNodeShapeCount)
{
hSBN->sHooks.Error("Inconsistent shape count in bin");
free(pabyData);
free(pasNodeIdBinStartPairs);
SBNCloseDiskTree(hSBN);
return SHPLIB_NULLPTR;
}
nShapeCountAcc += nNodeShapeCount;
#endif
if (nBinStart > 0)
{
pasNodeIdBinStartPairs[nEntriesInNodeIdBinStartPairs].nNodeId = i;
pasNodeIdBinStartPairs[nEntriesInNodeIdBinStartPairs].nBinStart =
nBinStart;
++nEntriesInNodeIdBinStartPairs;
}
}
free(pabyData);
/* pabyData = SHPLIB_NULLPTR; */
if (nEntriesInNodeIdBinStartPairs == 0)
{
free(pasNodeIdBinStartPairs);
hSBN->sHooks.Error("All nodes are empty");
SBNCloseDiskTree(hSBN);
return SHPLIB_NULLPTR;
}
#ifdef ENABLE_SBN_SANITY_CHECKS
if (nShapeCountAcc != nShapeCount)
{
/* Not totally sure if the above condition is always true */
/* Not enabled by default, as non-needed for the good working */
/* of our code. */
free(pasNodeIdBinStartPairs);
char szMessage[128];
snprintf(szMessage, sizeof(szMessage),
"Inconsistent shape count read in .sbn header (%d) vs total "
"of shapes over nodes (%d)",
nShapeCount, nShapeCountAcc);
hSBN->sHooks.Error(szMessage);
SBNCloseDiskTree(hSBN);
return SHPLIB_NULLPTR;
}
#endif
/* Sort node descriptors by increasing nBinStart */
/* In most cases, the node descriptors have already an increasing nBinStart,
* but not for https://github.com/OSGeo/gdal/issues/9430 */
qsort(pasNodeIdBinStartPairs, nEntriesInNodeIdBinStartPairs,
sizeof(SBNNodeIdBinStartPair), SBNCompareNodeIdBinStartPairs);
/* Consistency check: the first referenced nBinStart should be 2. */
if (pasNodeIdBinStartPairs[0].nBinStart != 2)
{
char szMessage[128];
snprintf(szMessage, sizeof(szMessage),
"First referenced bin (by node %d) should be 2, but %d found",
pasNodeIdBinStartPairs[0].nNodeId,
pasNodeIdBinStartPairs[0].nBinStart);
hSBN->sHooks.Error(szMessage);
SBNCloseDiskTree(hSBN);
free(pasNodeIdBinStartPairs);
return SHPLIB_NULLPTR;
}
/* And referenced nBinStart should be all distinct. */
for (int i = 1; i < nEntriesInNodeIdBinStartPairs; ++i)
{
if (pasNodeIdBinStartPairs[i].nBinStart ==
pasNodeIdBinStartPairs[i - 1].nBinStart)
{
char szMessage[128];
snprintf(szMessage, sizeof(szMessage),
"Node %d and %d have the same nBinStart=%d",
pasNodeIdBinStartPairs[i - 1].nNodeId,
pasNodeIdBinStartPairs[i].nNodeId,
pasNodeIdBinStartPairs[i].nBinStart);
hSBN->sHooks.Error(szMessage);
SBNCloseDiskTree(hSBN);
free(pasNodeIdBinStartPairs);
return SHPLIB_NULLPTR;
}
}
int nExpectedBinId = 1;
int nIdxInNodeBinPair = 0;
int nCurNode = pasNodeIdBinStartPairs[nIdxInNodeBinPair].nNodeId;
pasNodeDescriptor[nCurNode].nBinOffset =
STATIC_CAST(int, hSBN->sHooks.FTell(hSBN->fpSBN));
/* -------------------------------------------------------------------- */
/* Traverse bins to compute the offset of the first bin of each */
/* node. */
/* Note: we could use the .sbx file to compute the offsets instead.*/
/* -------------------------------------------------------------------- */
unsigned char abyBinHeader[8];
while (hSBN->sHooks.FRead(abyBinHeader, 8, 1, hSBN->fpSBN) == 1)
{
nExpectedBinId++;
const int nBinId = READ_MSB_INT(abyBinHeader);
const int nBinSize = READ_MSB_INT(abyBinHeader + 4); /* 16-bit words */
#ifdef DEBUG_SBN
fprintf(stderr, "bin id=%d, bin size (in features) = %d\n", nBinId,
nBinSize / 4);
#endif
if (nBinId != nExpectedBinId)
{
char szMessage[128];
snprintf(szMessage, sizeof(szMessage),
"Unexpected bin id at bin starting at offset %d. Got %d, "
"expected %d",
STATIC_CAST(int, hSBN->sHooks.FTell(hSBN->fpSBN)) - 8,
nBinId, nExpectedBinId);
hSBN->sHooks.Error(szMessage);
SBNCloseDiskTree(hSBN);
free(pasNodeIdBinStartPairs);
return SHPLIB_NULLPTR;
}
/* Bins are always limited to 100 features */
/* If there are more, then they are located in continuous bins */
if ((nBinSize % 4) != 0 || nBinSize <= 0 || nBinSize > 100 * 4)
{
char szMessage[128];
snprintf(szMessage, sizeof(szMessage),
"Unexpected bin size at bin starting at offset %d. Got %d",
STATIC_CAST(int, hSBN->sHooks.FTell(hSBN->fpSBN)) - 8,
nBinSize);
hSBN->sHooks.Error(szMessage);
SBNCloseDiskTree(hSBN);
free(pasNodeIdBinStartPairs);
return SHPLIB_NULLPTR;
}
if (nIdxInNodeBinPair + 1 < nEntriesInNodeIdBinStartPairs &&
nBinId == pasNodeIdBinStartPairs[nIdxInNodeBinPair + 1].nBinStart)
{
++nIdxInNodeBinPair;
nCurNode = pasNodeIdBinStartPairs[nIdxInNodeBinPair].nNodeId;
pasNodeDescriptor[nCurNode].nBinOffset =
STATIC_CAST(int, hSBN->sHooks.FTell(hSBN->fpSBN)) - 8;
}
pasNodeDescriptor[nCurNode].nBinCount++;
/* Skip shape description */
hSBN->sHooks.FSeek(hSBN->fpSBN, nBinSize * sizeof(uint16_t), SEEK_CUR);
}
if (nIdxInNodeBinPair + 1 != nEntriesInNodeIdBinStartPairs)
{
hSBN->sHooks.Error("Could not determine nBinOffset / nBinCount for all "
"non-empty nodes.");
SBNCloseDiskTree(hSBN);
free(pasNodeIdBinStartPairs);
return SHPLIB_NULLPTR;
}
free(pasNodeIdBinStartPairs);
return hSBN;
}
/***********************************************************************/
/* SBNCloseDiskTree() */
/************************************************************************/
void SBNCloseDiskTree(SBNSearchHandle hSBN)
{
if (hSBN == SHPLIB_NULLPTR)
return;
if (hSBN->pasNodeDescriptor != SHPLIB_NULLPTR)
{
const int nMaxNodes = (1 << hSBN->nMaxDepth) - 1;
for (int i = 0; i < nMaxNodes; i++)
{
if (hSBN->pasNodeDescriptor[i].pabyShapeDesc != SHPLIB_NULLPTR)
free(hSBN->pasNodeDescriptor[i].pabyShapeDesc);
}
}
/* printf("hSBN->nTotalBytesRead = %d\n", hSBN->nTotalBytesRead); */
hSBN->sHooks.FClose(hSBN->fpSBN);
free(hSBN->pasNodeDescriptor);
free(hSBN);
}
/************************************************************************/
/* SBNAddShapeId() */
/************************************************************************/
static bool SBNAddShapeId(SearchStruct *psSearch, int nShapeId)
{
if (psSearch->nShapeCount == psSearch->nShapeAlloc)
{
psSearch->nShapeAlloc =
STATIC_CAST(int, ((psSearch->nShapeCount + 100) * 5) / 4);
int *pNewPtr =
STATIC_CAST(int *, realloc(psSearch->panShapeId,
psSearch->nShapeAlloc * sizeof(int)));
if (pNewPtr == SHPLIB_NULLPTR)
{
psSearch->hSBN->sHooks.Error("Out of memory error");
return false;
}
psSearch->panShapeId = pNewPtr;
}
psSearch->panShapeId[psSearch->nShapeCount] = nShapeId;
psSearch->nShapeCount++;
return true;
}
/************************************************************************/
/* SBNSearchDiskInternal() */
/************************************************************************/
/* Due to the way integer coordinates are rounded, */
/* we can use a strict intersection test, except when the node */
/* bounding box or the search bounding box is degenerated. */
#define SEARCH_BB_INTERSECTS(_bMinX, _bMinY, _bMaxX, _bMaxY) \
(((bSearchMinX < _bMaxX && bSearchMaxX > _bMinX) || \
((_bMinX == _bMaxX || bSearchMinX == bSearchMaxX) && \
bSearchMinX <= _bMaxX && bSearchMaxX >= _bMinX)) && \
((bSearchMinY < _bMaxY && bSearchMaxY > _bMinY) || \
((_bMinY == _bMaxY || bSearchMinY == bSearchMaxY) && \
bSearchMinY <= _bMaxY && bSearchMaxY >= _bMinY)))
static bool SBNSearchDiskInternal(SearchStruct *psSearch, int nDepth,
int nNodeId, coord bNodeMinX, coord bNodeMinY,
coord bNodeMaxX, coord bNodeMaxY)
{
const coord bSearchMinX = psSearch->bMinX;
const coord bSearchMinY = psSearch->bMinY;
const coord bSearchMaxX = psSearch->bMaxX;
const coord bSearchMaxY = psSearch->bMaxY;
SBNSearchHandle hSBN = psSearch->hSBN;
SBNNodeDescriptor *psNode = &(hSBN->pasNodeDescriptor[nNodeId]);
/* -------------------------------------------------------------------- */
/* Check if this node contains shapes that intersect the search */
/* bounding box. */
/* -------------------------------------------------------------------- */
if (psNode->bBBoxInit &&
!(SEARCH_BB_INTERSECTS(psNode->bMinX, psNode->bMinY, psNode->bMaxX,
psNode->bMaxY)))
{
/* No intersection, then don't try to read the shapes attached */
/* to this node */
}
/* -------------------------------------------------------------------- */
/* If this node contains shapes that are cached, then read them. */
/* -------------------------------------------------------------------- */
else if (psNode->pabyShapeDesc != SHPLIB_NULLPTR)
{
unsigned char *pabyShapeDesc = psNode->pabyShapeDesc;
/* printf("nNodeId = %d, nDepth = %d\n", nNodeId, nDepth); */
for (int j = 0; j < psNode->nShapeCount; j++)
{
const coord bMinX = pabyShapeDesc[0];
const coord bMinY = pabyShapeDesc[1];
const coord bMaxX = pabyShapeDesc[2];
const coord bMaxY = pabyShapeDesc[3];
if (SEARCH_BB_INTERSECTS(bMinX, bMinY, bMaxX, bMaxY))
{
int nShapeId = READ_MSB_INT(pabyShapeDesc + 4);
/* Caution : we count shape id starting from 0, and not 1 */
nShapeId--;
/*printf("shape=%d, minx=%d, miny=%d, maxx=%d, maxy=%d\n",
nShapeId, bMinX, bMinY, bMaxX, bMaxY);*/
if (!SBNAddShapeId(psSearch, nShapeId))
return false;
}
pabyShapeDesc += 8;
}
}
/* -------------------------------------------------------------------- */
/* If the node has attached shapes (that are not (yet) cached), */
/* then retrieve them from disk. */
/* -------------------------------------------------------------------- */
else if (psNode->nBinCount > 0)
{
hSBN->sHooks.FSeek(hSBN->fpSBN, psNode->nBinOffset, SEEK_SET);
if (nDepth < CACHED_DEPTH_LIMIT)
psNode->pabyShapeDesc =
STATIC_CAST(unsigned char *, malloc(psNode->nShapeCount * 8));
unsigned char abyBinHeader[8];
int nShapeCountAcc = 0;
for (int i = 0; i < psNode->nBinCount; i++)
{
#ifdef DEBUG_IO
psSearch->nBytesRead += 8;
#endif
if (hSBN->sHooks.FRead(abyBinHeader, 8, 1, hSBN->fpSBN) != 1)
{
hSBN->sHooks.Error("I/O error");
free(psNode->pabyShapeDesc);
psNode->pabyShapeDesc = SHPLIB_NULLPTR;
return false;
}
if (READ_MSB_INT(abyBinHeader + 0) != psNode->nBinStart + i)
{
hSBN->sHooks.Error("Unexpected bin id");
free(psNode->pabyShapeDesc);
psNode->pabyShapeDesc = SHPLIB_NULLPTR;
return false;
}
/* 16-bit words */
const int nBinSize = READ_MSB_INT(abyBinHeader + 4);
const int nShapes = nBinSize / 4;
/* Bins are always limited to 100 features */
if ((nBinSize % 4) != 0 || nShapes <= 0 || nShapes > 100)
{
hSBN->sHooks.Error("Unexpected bin size");
free(psNode->pabyShapeDesc);
psNode->pabyShapeDesc = SHPLIB_NULLPTR;
return false;
}
if (nShapeCountAcc + nShapes > psNode->nShapeCount)
{
free(psNode->pabyShapeDesc);
psNode->pabyShapeDesc = SHPLIB_NULLPTR;
char szMessage[192];
snprintf(
szMessage, sizeof(szMessage),
"Inconsistent shape count for bin idx=%d of node %d. "
"nShapeCountAcc=(%d) + nShapes=(%d) > nShapeCount(=%d)",
i, nNodeId, nShapeCountAcc, nShapes, psNode->nShapeCount);
hSBN->sHooks.Error(szMessage);
return false;
}
unsigned char *pabyBinShape;
if (nDepth < CACHED_DEPTH_LIMIT &&
psNode->pabyShapeDesc != SHPLIB_NULLPTR)
{
pabyBinShape = psNode->pabyShapeDesc + nShapeCountAcc * 8;
}
else
{
pabyBinShape = psSearch->abyBinShape;
}
#ifdef DEBUG_IO
psSearch->nBytesRead += nBinSize * sizeof(uint16_t);
#endif
if (hSBN->sHooks.FRead(pabyBinShape, nBinSize * sizeof(uint16_t), 1,
hSBN->fpSBN) != 1)
{
hSBN->sHooks.Error("I/O error");
free(psNode->pabyShapeDesc);
psNode->pabyShapeDesc = SHPLIB_NULLPTR;
return false;
}
nShapeCountAcc += nShapes;
if (i == 0 && !psNode->bBBoxInit)
{
psNode->bMinX = pabyBinShape[0];
psNode->bMinY = pabyBinShape[1];
psNode->bMaxX = pabyBinShape[2];
psNode->bMaxY = pabyBinShape[3];
}
for (int j = 0; j < nShapes; j++)
{
const coord bMinX = pabyBinShape[0];
const coord bMinY = pabyBinShape[1];
const coord bMaxX = pabyBinShape[2];
const coord bMaxY = pabyBinShape[3];
if (!psNode->bBBoxInit)
{
/* clang-format off */
#ifdef ENABLE_SBN_SANITY_CHECKS
/* -------------------------------------------------------------------- */
/* Those tests only check that the shape bounding box in the bin */
/* are consistent (self-consistent and consistent with the node */
/* they are attached to). They are optional however (as far as */
/* the safety of runtime is concerned at least). */
/* -------------------------------------------------------------------- */
if (!(((bMinX < bMaxX || (bMinX == 0 && bMaxX == 0) ||
(bMinX == 255 && bMaxX == 255))) &&
((bMinY < bMaxY || (bMinY == 0 && bMaxY == 0) ||
(bMinY == 255 && bMaxY == 255)))) ||
bMaxX < bNodeMinX || bMaxY < bNodeMinY ||
bMinX > bNodeMaxX || bMinY > bNodeMaxY)
{
/* printf("shape %d %d %d %d\n", bMinX, bMinY, bMaxX, bMaxY);*/
/* printf("node %d %d %d %d\n", bNodeMinX, bNodeMinY, bNodeMaxX, bNodeMaxY);*/
hSBN->sHooks.Error("Invalid shape bounding box in bin");
free(psNode->pabyShapeDesc);
psNode->pabyShapeDesc = SHPLIB_NULLPTR;
return false;
}
#endif
/* clang-format on */
if (bMinX < psNode->bMinX)
psNode->bMinX = bMinX;
if (bMinY < psNode->bMinY)
psNode->bMinY = bMinY;
if (bMaxX > psNode->bMaxX)
psNode->bMaxX = bMaxX;
if (bMaxY > psNode->bMaxY)
psNode->bMaxY = bMaxY;
}
if (SEARCH_BB_INTERSECTS(bMinX, bMinY, bMaxX, bMaxY))
{
int nShapeId = READ_MSB_INT(pabyBinShape + 4);
/* Caution : we count shape id starting from 0, and not 1 */
nShapeId--;
/*printf("shape=%d, minx=%d, miny=%d, maxx=%d, maxy=%d\n",
nShapeId, bMinX, bMinY, bMaxX, bMaxY);*/
if (!SBNAddShapeId(psSearch, nShapeId))
return false;
}
pabyBinShape += 8;
}
}
if (nShapeCountAcc != psNode->nShapeCount)
{
free(psNode->pabyShapeDesc);
psNode->pabyShapeDesc = SHPLIB_NULLPTR;
char szMessage[96];
snprintf(
szMessage, sizeof(szMessage),
"Inconsistent shape count for node %d. Got %d, expected %d",
nNodeId, nShapeCountAcc, psNode->nShapeCount);
hSBN->sHooks.Error(szMessage);
return false;
}
psNode->bBBoxInit = true;
}
/* -------------------------------------------------------------------- */
/* Look up in child nodes. */
/* -------------------------------------------------------------------- */
if (nDepth + 1 < hSBN->nMaxDepth)
{
nNodeId = nNodeId * 2 + 1;
if ((nDepth % 2) == 0) /* x split */
{
const coord bMid = STATIC_CAST(
coord, 1 + (STATIC_CAST(int, bNodeMinX) + bNodeMaxX) / 2);
if (bSearchMinX <= bMid - 1 &&
!SBNSearchDiskInternal(psSearch, nDepth + 1, nNodeId + 1,
bNodeMinX, bNodeMinY, bMid - 1,
bNodeMaxY))
{
return false;
}
if (bSearchMaxX >= bMid &&
!SBNSearchDiskInternal(psSearch, nDepth + 1, nNodeId, bMid,
bNodeMinY, bNodeMaxX, bNodeMaxY))
{
return false;
}
}
else /* y split */
{
const coord bMid = STATIC_CAST(
coord, 1 + (STATIC_CAST(int, bNodeMinY) + bNodeMaxY) / 2);
if (bSearchMinY <= bMid - 1 &&
!SBNSearchDiskInternal(psSearch, nDepth + 1, nNodeId + 1,
bNodeMinX, bNodeMinY, bNodeMaxX,
bMid - 1))
{
return false;
}
if (bSearchMaxY >= bMid &&
!SBNSearchDiskInternal(psSearch, nDepth + 1, nNodeId, bNodeMinX,
bMid, bNodeMaxX, bNodeMaxY))
{
return false;
}
}
}
return true;
}
/************************************************************************/
/* compare_ints() */
/************************************************************************/
/* helper for qsort */
static int compare_ints(const void *a, const void *b)
{
return *STATIC_CAST(const int *, a) - *STATIC_CAST(const int *, b);
}
/************************************************************************/
/* SBNSearchDiskTree() */
/************************************************************************/
int *SBNSearchDiskTree(const SBNSearchHandle hSBN, const double *padfBoundsMin,
const double *padfBoundsMax, int *pnShapeCount)
{
*pnShapeCount = 0;
const double dfMinX = padfBoundsMin[0];
const double dfMinY = padfBoundsMin[1];
const double dfMaxX = padfBoundsMax[0];
const double dfMaxY = padfBoundsMax[1];
if (dfMinX > dfMaxX || dfMinY > dfMaxY)
return SHPLIB_NULLPTR;
if (dfMaxX < hSBN->dfMinX || dfMaxY < hSBN->dfMinY ||
dfMinX > hSBN->dfMaxX || dfMinY > hSBN->dfMaxY)
return SHPLIB_NULLPTR;
/* -------------------------------------------------------------------- */
/* Compute the search coordinates in [0,255]x[0,255] coord. space */
/* -------------------------------------------------------------------- */
const double dfDiskXExtent = hSBN->dfMaxX - hSBN->dfMinX;
const double dfDiskYExtent = hSBN->dfMaxY - hSBN->dfMinY;
int bMinX;
int bMaxX;
int bMinY;
int bMaxY;
if (dfDiskXExtent == 0.0)
{
bMinX = 0;
bMaxX = 255;
}
else
{
if (dfMinX < hSBN->dfMinX)
bMinX = 0;
else
{
const double dfMinX_255 =
(dfMinX - hSBN->dfMinX) / dfDiskXExtent * 255.0;
bMinX = STATIC_CAST(int, floor(dfMinX_255 - 0.005));
if (bMinX < 0)
bMinX = 0;
}
if (dfMaxX > hSBN->dfMaxX)
bMaxX = 255;
else
{
const double dfMaxX_255 =
(dfMaxX - hSBN->dfMinX) / dfDiskXExtent * 255.0;
bMaxX = STATIC_CAST(int, ceil(dfMaxX_255 + 0.005));
if (bMaxX > 255)
bMaxX = 255;
}
}
if (dfDiskYExtent == 0.0)
{
bMinY = 0;
bMaxY = 255;
}
else
{
if (dfMinY < hSBN->dfMinY)
bMinY = 0;
else
{
const double dfMinY_255 =
(dfMinY - hSBN->dfMinY) / dfDiskYExtent * 255.0;
bMinY = STATIC_CAST(int, floor(dfMinY_255 - 0.005));
if (bMinY < 0)
bMinY = 0;
}
if (dfMaxY > hSBN->dfMaxY)
bMaxY = 255;
else
{
const double dfMaxY_255 =
(dfMaxY - hSBN->dfMinY) / dfDiskYExtent * 255.0;
bMaxY = STATIC_CAST(int, ceil(dfMaxY_255 + 0.005));
if (bMaxY > 255)
bMaxY = 255;
}
}
/* -------------------------------------------------------------------- */
/* Run the search. */
/* -------------------------------------------------------------------- */
return SBNSearchDiskTreeInteger(hSBN, bMinX, bMinY, bMaxX, bMaxY,
pnShapeCount);
}
/************************************************************************/
/* SBNSearchDiskTreeInteger() */
/************************************************************************/
int *SBNSearchDiskTreeInteger(const SBNSearchHandle hSBN, int bMinX, int bMinY,
int bMaxX, int bMaxY, int *pnShapeCount)
{
*pnShapeCount = 0;
if (bMinX > bMaxX || bMinY > bMaxY)
return SHPLIB_NULLPTR;
if (bMaxX < 0 || bMaxY < 0 || bMinX > 255 || bMinY > 255)
return SHPLIB_NULLPTR;
if (hSBN->nShapeCount == 0)
return SHPLIB_NULLPTR;
/* -------------------------------------------------------------------- */
/* Run the search. */
/* -------------------------------------------------------------------- */
SearchStruct sSearch;
memset(&sSearch, 0, sizeof(sSearch));
sSearch.hSBN = hSBN;
sSearch.bMinX = STATIC_CAST(coord, bMinX >= 0 ? bMinX : 0);
sSearch.bMinY = STATIC_CAST(coord, bMinY >= 0 ? bMinY : 0);
sSearch.bMaxX = STATIC_CAST(coord, bMaxX <= 255 ? bMaxX : 255);
sSearch.bMaxY = STATIC_CAST(coord, bMaxY <= 255 ? bMaxY : 255);
sSearch.nShapeCount = 0;
sSearch.nShapeAlloc = 0;
sSearch.panShapeId = STATIC_CAST(int *, calloc(1, sizeof(int)));
#ifdef DEBUG_IO
sSearch.nBytesRead = 0;
#endif
const bool bRet = SBNSearchDiskInternal(&sSearch, 0, 0, 0, 0, 255, 255);
#ifdef DEBUG_IO
hSBN->nTotalBytesRead += sSearch.nBytesRead;
/* printf("nBytesRead = %d\n", sSearch.nBytesRead); */
#endif
if (!bRet)
{
free(sSearch.panShapeId);
*pnShapeCount = 0;
return SHPLIB_NULLPTR;
}
*pnShapeCount = sSearch.nShapeCount;
/* -------------------------------------------------------------------- */