-
Notifications
You must be signed in to change notification settings - Fork 0
/
gdal.cpp
1217 lines (1008 loc) · 34.3 KB
/
gdal.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
#include "infra/gdal.h"
#include "infra/cast.h"
#include "infra/environmentvariable.h"
#include "infra/exception.h"
#include "infra/filesystem.h"
#include "infra/gdallog.h"
#include "infra/scopeguard.h"
#include "infra/string.h"
#ifdef EMBED_GDAL_DATA
#include "embedgdaldata.h"
#endif
#include <algorithm>
#include <array>
#include <cassert>
#include <gdal_version.h>
#include <ogrsf_frmts.h>
#include <stdexcept>
#include <unordered_map>
#include <utility>
namespace inf::gdal {
using namespace std::string_literals;
namespace {
static const std::unordered_map<RasterType, const char*>
s_rasterDriverLookup{{
{RasterType::Memory, "MEM"},
{RasterType::ArcAscii, "AAIGrid"},
{RasterType::GeoTiff, "GTiff"},
{RasterType::Gif, "GIF"},
{RasterType::Png, "PNG"},
{RasterType::PcRaster, "PCRaster"},
{RasterType::Netcdf, "netCDF"},
{RasterType::TileDB, "TileDB"},
{RasterType::MBTiles, "MBTiles"},
{RasterType::GeoPackage, "GPKG"},
{RasterType::Grib, "GRIB"},
{RasterType::Postgis, "PostGISRaster"},
{RasterType::Vrt, "VRT"},
}};
static const std::unordered_map<std::string, RasterType> s_rasterDriverDescLookup{{
{"MEM", RasterType::Memory},
{"AAIGrid", RasterType::ArcAscii},
{"GTiff", RasterType::GeoTiff},
{"GIF", RasterType::Gif},
{"PNG", RasterType::Png},
{"PCRaster", RasterType::PcRaster},
{"netCDF", RasterType::Netcdf},
{"TileDB", RasterType::TileDB},
{"MBTiles", RasterType::MBTiles},
{"GPKG", RasterType::GeoPackage},
{"GRIB", RasterType::Grib},
{"PostGISRaster", RasterType::Postgis},
{"VRT", RasterType::Vrt},
}};
static const std::unordered_map<VectorType, const char*> s_vectorDriverLookup{{
{VectorType::Memory, "Memory"},
{VectorType::Csv, "CSV"},
{VectorType::Tab, "CSV"},
{VectorType::ShapeFile, "ESRI Shapefile"},
{VectorType::Xlsx, "XLSX"},
{VectorType::GeoJson, "GeoJSON"},
{VectorType::GeoPackage, "GPKG"},
{VectorType::PostgreSQL, "PostgreSQL"},
{VectorType::WFS, "WFS"},
{VectorType::Vrt, "OGR_VRT"},
}};
static const std::unordered_map<std::string, VectorType> s_vectorDriverDescLookup{{
{"Memory", VectorType::Memory},
{"CSV", VectorType::Csv},
{"CSV", VectorType::Tab},
{"ESRI Shapefile", VectorType::ShapeFile},
{"XLSX", VectorType::Xlsx},
{"GeoJSON", VectorType::GeoJson},
{"GPKG", VectorType::GeoPackage},
{"PostgreSQL", VectorType::PostgreSQL},
{"WFS", VectorType::WFS},
{"OGR_VRT", VectorType::Vrt},
}};
static std::string get_extension_lowercase(const fs::path& filepath)
{
return str::lowercase(file::u8string(filepath.extension()));
}
template <typename Unsigned, typename Signed>
Unsigned signedToUnsigned(Signed value, const char* valueDesc)
{
if (value < 0) {
throw RuntimeError("Unexpected negative value for: {}", valueDesc);
}
return static_cast<Unsigned>(value);
}
} // namespace
Registration::Registration()
: Registration(RegistrationConfig())
{
}
Registration::Registration(RegistrationConfig cfg)
{
register_gdal(cfg);
}
Registration::~Registration()
{
unregister_gdal();
}
EmbeddedDataRegistration::EmbeddedDataRegistration()
{
#ifdef EMBED_GDAL_DATA
create_embedded_data();
#endif
}
EmbeddedDataRegistration::~EmbeddedDataRegistration()
{
#ifdef EMBED_GDAL_DATA
destroy_embedded_data();
#endif
}
void register_gdal()
{
register_gdal(RegistrationConfig());
}
void register_gdal(RegistrationConfig cfg)
{
if (cfg.projdbPath.is_relative()) {
cfg.projdbPath = fs::absolute(cfg.projdbPath);
}
#ifdef EMBED_GDAL_DATA
create_embedded_data();
#endif
register_embedded_data(cfg.projdbPath);
#ifdef __EMSCRIPTEN__
GDALRegister_MEM();
GDALRegister_PNG();
GDALRegister_GTiff();
GDALRegister_AAIGrid();
#else
GDALAllRegister();
#endif
if (cfg.setLogHandler) {
set_log_handler();
}
}
void unregister_gdal()
{
unregister_embedded_data();
#ifdef EMBED_GDAL_DATA
destroy_embedded_data();
#endif
GDALDestroy();
}
void register_embedded_data()
{
#ifdef EMBED_GDAL_DATA
register_embedded_data_file_finder();
#endif
}
void register_embedded_data(const fs::path& p)
{
register_embedded_data();
if (!p.empty()) {
#if GDAL_VERSION_MAJOR > 2
const std::string path = file::u8string(p);
std::array<const char*, 2> paths = {
path.c_str(),
nullptr,
};
OSRSetPROJSearchPaths(paths.data());
#endif
// Also set the environment variable
// e.g. Spatialite library does not use gdal settings
env::set("PROJ_LIB", file::u8string(p));
}
}
void unregister_embedded_data()
{
#ifdef EMBED_GDAL_DATA
unregister_embedded_data_file_finder();
#endif
}
std::string get_memory_file_buffer(const fs::path& p, bool remove)
{
std::string result;
vsi_l_offset length;
auto* data = VSIGetMemFileBuffer(str::from_u8(p.u8string()).c_str(), &length, remove ? TRUE : FALSE);
ScopeGuard guard([=]() {
if (remove) {
CPLFree(data);
}
});
if (data) {
result.assign(reinterpret_cast<char*>(data), length);
}
return result;
}
bool RasterDriver::is_supported(RasterType type)
{
if (type == RasterType::Unknown) {
throw InvalidArgument("Invalid raster type specified");
}
return nullptr != GetGDALDriverManager()->GetDriverByName(s_rasterDriverLookup.at(type));
}
RasterDriver RasterDriver::create(RasterType type)
{
if (type == RasterType::Unknown) {
throw InvalidArgument("Invalid raster type specified");
}
auto driverName = s_rasterDriverLookup.at(type);
auto* driverPtr = GetGDALDriverManager()->GetDriverByName(driverName);
if (driverPtr == nullptr) {
throw RuntimeError("Failed to get raster driver: {}", driverName);
}
return RasterDriver(*driverPtr);
}
RasterDriver RasterDriver::create(const fs::path& filename)
{
auto rasterType = guess_rastertype_from_filename(filename);
if (rasterType != RasterType::Unknown) {
return create(rasterType);
}
throw RuntimeError("Failed to determine raster type from filename: {}", filename);
}
RasterDriver::RasterDriver(GDALDriver& driver)
: _driver(driver)
{
}
RasterDataSet RasterDriver::create_dataset(int32_t rows, int32_t cols, int32_t numBands, const fs::path& filename, const std::type_info& dataType)
{
return RasterDataSet(check_pointer(_driver.Create(str::from_u8(filename.u8string()).c_str(), cols, rows, numBands, resolve_type(dataType), nullptr), "Failed to create data set"));
}
RasterDataSet RasterDriver::create_dataset(int32_t rows, int32_t cols, int32_t numBands, const std::type_info& dataType)
{
return RasterDataSet(check_pointer(_driver.Create("", cols, rows, numBands, resolve_type(dataType), nullptr), "Failed to create data set"));
}
RasterDataSet RasterDriver::create_dataset_copy(const RasterDataSet& reference, const fs::path& filename, std::span<const std::string> driverOptions)
{
auto options = create_string_list(driverOptions);
return RasterDataSet(check_pointer(_driver.CreateCopy(
str::from_u8(filename.u8string()).c_str(),
reference.get(),
FALSE,
options.List(),
nullptr,
nullptr),
"Failed to create data set copy"));
}
RasterType RasterDriver::type() const
{
try {
return s_rasterDriverDescLookup.at(_driver.GetDescription());
} catch (const std::out_of_range&) {
throw RuntimeError("Failed to determine raster type for driver: {}", _driver.GetDescription());
}
}
bool VectorDriver::is_supported(VectorType type)
{
if (type == VectorType::Unknown) {
throw InvalidArgument("Invalid vector type specified");
}
return nullptr != GetGDALDriverManager()->GetDriverByName(s_vectorDriverLookup.at(type));
}
VectorDriver VectorDriver::create(const fs::path& filename)
{
auto vectorType = guess_vectortype_from_filename(filename.u8string());
if (vectorType != VectorType::Unknown) {
return create(vectorType);
}
throw RuntimeError("Failed to determine vector type from filename: {}", filename);
}
VectorDriver VectorDriver::create(VectorType type)
{
if (type == VectorType::Unknown) {
throw InvalidArgument("Invalid vector type specified");
}
auto driverName = s_vectorDriverLookup.at(type);
auto* driverPtr = GetGDALDriverManager()->GetDriverByName(driverName);
if (driverPtr == nullptr) {
throw RuntimeError("Failed to get vector driver: {}", driverName);
}
return VectorDriver(*driverPtr);
}
VectorDriver::VectorDriver(GDALDriver& driver)
: _driver(driver)
{
}
VectorDataSet VectorDriver::create_dataset()
{
return create_dataset("");
}
VectorDataSet VectorDriver::create_dataset(const fs::path& filename, const std::vector<std::string>& creationOptions)
{
auto options = create_string_list(creationOptions);
return VectorDataSet(check_pointer(_driver.Create(str::from_u8(filename.u8string()).c_str(), 0, 0, 0, GDT_Unknown, options), "Failed to create vector data set"));
}
void VectorDriver::delete_dataset(const fs::path& filename)
{
_driver.Delete(str::from_u8(filename.u8string()).c_str());
}
VectorType VectorDriver::type() const
{
try {
return s_vectorDriverDescLookup.at(_driver.GetDescription());
} catch (const std::out_of_range&) {
throw RuntimeError("Failed to determine vector type for driver: {}", _driver.GetDescription());
}
}
RasterBand::RasterBand(GDALRasterBand* ptr)
: _band(ptr)
{
}
GDALRasterBand* RasterBand::get()
{
return _band;
}
const GDALRasterBand* RasterBand::get() const
{
return _band;
}
const std::type_info& RasterBand::datatype() const
{
return resolve_type(_band->GetRasterDataType());
}
inf::Size RasterBand::block_size()
{
inf::Size result;
// Fail to compile if the inf::Size datasize type ever gets refactored
static_assert(std::is_same_v<int32_t, decltype(result.width)>);
static_assert(std::is_same_v<int32_t, decltype(result.height)>);
_band->GetBlockSize(&result.width, &result.height);
return result;
}
int32_t RasterBand::overview_count()
{
return _band->GetOverviewCount();
}
RasterBand RasterBand::overview_dataset(int index)
{
return RasterBand(check_pointer(_band->GetOverview(index), "Failed to obtain overview band"));
}
int32_t RasterBand::x_size()
{
return _band->GetXSize();
}
int32_t RasterBand::y_size()
{
return _band->GetYSize();
}
static GDALDataset* create_data_set(const fs::path& filePath,
unsigned int openFlags,
const char* const* drivers,
const std::vector<std::string>& driverOpts)
{
// use generic_u8string otherwise the path contains backslashes on windows
// In memory file paths like /vsimem/file.asc in memory will then be \\vsimem\\file.asc
// which is not recognized by gdal
const auto path = str::from_u8(filePath.generic_u8string());
auto options = create_string_list(driverOpts);
return reinterpret_cast<GDALDataset*>(GDALOpenEx(
path.c_str(),
openFlags,
drivers,
options.List(),
nullptr));
}
static uint32_t open_mode_to_gdal_mode(OpenMode mode)
{
return mode == OpenMode::ReadOnly ? GDAL_OF_READONLY : GDAL_OF_UPDATE;
}
static std::string open_mode_to_string(OpenMode mode)
{
return mode == OpenMode::ReadOnly ? "reading" : "writing";
}
static RasterDataSet raster_open_impl(OpenMode mode, const fs::path& filePath, const std::vector<std::string>& driverOpts)
{
auto* dataSet = create_data_set(filePath, open_mode_to_gdal_mode(mode) | GDAL_OF_RASTER, nullptr, driverOpts);
if (!dataSet) {
throw RuntimeError("Failed to open raster file '{}' for {}", filePath, open_mode_to_string(mode));
}
return RasterDataSet(dataSet);
}
static RasterDataSet raster_open_impl(OpenMode mode, const fs::path& filePath, RasterType type, const std::vector<std::string>& driverOpts)
{
if (type == RasterType::Unknown) {
type = guess_rastertype_from_filename(filePath);
if (type == RasterType::Unknown) {
throw RuntimeError("Failed to determine raster type for file ('{}')", filePath);
}
}
std::array<const char*, 2> allowedDrivers{{
s_rasterDriverLookup.at(type),
nullptr,
}};
return RasterDataSet(check_pointer_msg_cb(create_data_set(filePath,
open_mode_to_gdal_mode(mode) | GDAL_OF_RASTER,
allowedDrivers.data(),
driverOpts),
[&]() { return fmt::format("Failed to open raster file: {}", filePath); }));
}
RasterDataSet RasterDataSet::create(const fs::path& filePath, const std::vector<std::string>& driverOpts)
{
return open(filePath, driverOpts);
}
RasterDataSet RasterDataSet::create(const fs::path& filePath, RasterType type, const std::vector<std::string>& driverOpts)
{
return open(filePath, type, driverOpts);
}
RasterDataSet RasterDataSet::open(const fs::path& filePath, const std::vector<std::string>& driverOpts)
{
return raster_open_impl(OpenMode::ReadOnly, filePath, driverOpts);
}
RasterDataSet RasterDataSet::open(const fs::path& filePath, RasterType type, const std::vector<std::string>& driverOpts)
{
return raster_open_impl(OpenMode::ReadOnly, filePath, type, driverOpts);
}
RasterDataSet RasterDataSet::open_for_writing(const fs::path& filePath, const std::vector<std::string>& driverOpts)
{
return raster_open_impl(OpenMode::ReadWrite, filePath, driverOpts);
}
RasterDataSet RasterDataSet::open_for_writing(const fs::path& filePath, RasterType type, const std::vector<std::string>& driverOpts)
{
return raster_open_impl(OpenMode::ReadWrite, filePath, type, driverOpts);
}
RasterDataSet::RasterDataSet(GDALDataset* ptr) noexcept
: _ptr(ptr)
{
}
RasterDataSet::RasterDataSet(GDALDatasetH ptr) noexcept
: RasterDataSet(GDALDataset::FromHandle(ptr))
{
}
RasterDataSet::RasterDataSet(RasterDataSet&& rhs) noexcept
: _ptr(rhs._ptr)
{
rhs._ptr = nullptr;
}
RasterDataSet::~RasterDataSet() noexcept
{
GDALClose(reinterpret_cast<GDALDatasetH>(_ptr));
}
RasterDataSet& RasterDataSet::operator=(RasterDataSet&& rhs) noexcept
{
if (_ptr) {
GDALClose(reinterpret_cast<GDALDatasetH>(_ptr));
}
_ptr = rhs._ptr;
rhs._ptr = nullptr;
return *this;
}
bool RasterDataSet::is_valid() const noexcept
{
return _ptr != nullptr;
}
int32_t RasterDataSet::raster_count() const
{
assert(_ptr);
return _ptr->GetRasterCount();
}
int32_t RasterDataSet::x_size() const
{
assert(_ptr);
return _ptr->GetRasterXSize();
}
int32_t RasterDataSet::y_size() const
{
assert(_ptr);
return _ptr->GetRasterYSize();
}
bool RasterDataSet::has_valid_geotransform() const
{
assert(_ptr);
std::array<double, 6> trans;
return _ptr->GetGeoTransform(trans.data()) == CE_None;
}
std::array<double, 6> RasterDataSet::geotransform() const
{
assert(_ptr);
std::array<double, 6> trans;
check_error(_ptr->GetGeoTransform(trans.data()), "Failed to get extent metadata");
return trans;
}
void RasterDataSet::set_geotransform(const std::array<double, 6>& trans)
{
assert(_ptr);
check_error(_ptr->SetGeoTransform(const_cast<double*>(trans.data())), "Failed to set geo transform");
}
std::optional<double> RasterDataSet::nodata_value(int bandNr) const
{
assert(bandNr > 0);
auto* band = _ptr->GetRasterBand(bandNr);
if (band == nullptr) {
throw RuntimeError("Invalid dataset band number: {}", bandNr);
}
int success = 0;
auto value = band->GetNoDataValue(&success);
if (success) {
return std::make_optional(value);
}
return std::optional<double>();
}
void RasterDataSet::set_nodata_value(int bandNr, std::optional<double> value) const
{
assert(bandNr > 0);
if (driver().type() == RasterType::TileDB) {
return;
}
auto* band = _ptr->GetRasterBand(bandNr);
if (band == nullptr) {
throw RuntimeError("Invalid dataset band number: {}", bandNr);
}
if (value) {
check_error(band->SetNoDataValue(*value), "Failed to set nodata value");
} else {
if (auto err = band->DeleteNoDataValue(); err != CE_None) {
if (err == CE_Failure && CPLGetLastErrorNo() == CPLE_NotSupported) {
// not supported by the driver
return;
}
check_error(err, "Failed to delete nodata value");
}
}
}
void RasterDataSet::set_colortable(int bandNr, const GDALColorTable* ct)
{
assert(_ptr);
assert(bandNr > 0);
auto* band = check_pointer(_ptr->GetRasterBand(bandNr), "Failed to get raster band");
check_error(band->SetColorTable(const_cast<GDALColorTable*>(ct)), "Failed to set color table");
}
std::string RasterDataSet::projection() const
{
assert(_ptr);
return _ptr->GetProjectionRef();
}
void RasterDataSet::set_projection(const std::string& proj)
{
assert(_ptr);
if (!proj.empty()) {
check_error(_ptr->SetProjection(proj.c_str()), "Failed to set projection");
}
}
std::string RasterDataSet::metadata_item(const std::string& name, const std::string& domain)
{
std::string result;
if (auto* value = _ptr->GetMetadataItem(name.c_str(), domain.c_str()); value != nullptr) {
result.assign(value);
}
return result;
}
std::string RasterDataSet::band_metadata_item(int bandNr, const std::string& name, const std::string& domain)
{
std::string result;
assert(bandNr > 0);
auto* band = check_pointer(_ptr->GetRasterBand(bandNr), "Failed to get raster band");
if (auto* value = band->GetMetadataItem(name.c_str(), domain.c_str()); value != nullptr) {
result.assign(value);
}
return result;
}
std::unordered_map<std::string, std::string> RasterDataSet::metadata(const std::string& domain)
{
std::unordered_map<std::string, std::string> result;
char** data = _ptr->GetMetadata(domain.c_str());
if (data != nullptr) {
int index = 0;
while (data[index] != nullptr) {
auto keyValue = str::split_view(data[index++], '=');
if (keyValue.size() == 2) {
result.emplace(keyValue[0], keyValue[1]);
}
}
}
return result;
}
void RasterDataSet::set_metadata(const std::string& name, const std::string& value, const std::string& domain)
{
check_error(_ptr->SetMetadataItem(name.c_str(), value.c_str(), domain.c_str()), "Failed to set metadata");
}
void RasterDataSet::set_band_metadata(int bandNr, const std::string& name, const std::string& value, const std::string& domain)
{
assert(bandNr > 0);
auto* band = check_pointer(_ptr->GetRasterBand(bandNr), "Failed to get raster band");
check_error(band->SetMetadataItem(name.c_str(), value.c_str(), domain.c_str()), "Failed to set band metadata");
}
void RasterDataSet::set_band_description(int bandNr, const std::string& description)
{
assert(bandNr > 0);
auto* band = check_pointer(_ptr->GetRasterBand(bandNr), "Failed to get raster band");
band->SetDescription(description.c_str());
}
std::vector<std::string> RasterDataSet::metadata_domains() const noexcept
{
std::vector<std::string> result;
char** data = _ptr->GetMetadataDomainList();
if (data) {
int index = 0;
while (data[index] != nullptr) {
result.push_back(data[index++]);
}
CSLDestroy(data);
}
return result;
}
RasterBand RasterDataSet::rasterband(int bandNr) const
{
assert(bandNr > 0);
return RasterBand(check_pointer(_ptr->GetRasterBand(bandNr), "Invalid band index"));
}
RasterType RasterDataSet::type() const
{
return driver().type();
}
const std::type_info& RasterDataSet::band_datatype(int bandNr) const
{
assert(_ptr);
return rasterband(bandNr).datatype();
}
void RasterDataSet::read_rasterdata(int band, int xOff, int yOff, int xSize, int ySize, const std::type_info& type, void* pData, int bufXSize, int bufYSize, int pixelSize, int lineSize) const
{
auto* bandPtr = _ptr->GetRasterBand(band);
check_error(bandPtr->RasterIO(GF_Read, xOff, yOff, xSize, ySize, pData, bufXSize, bufYSize, resolve_type(type), pixelSize, lineSize), "Failed to read raster data");
}
void RasterDataSet::write_rasterdata(int band, int xOff, int yOff, int xSize, int ySize, const std::type_info& type, const void* pData, int bufXSize, int bufYSize) const
{
auto* bandPtr = _ptr->GetRasterBand(band);
check_error(bandPtr->RasterIO(GF_Write, xOff, yOff, xSize, ySize, const_cast<void*>(pData), bufXSize, bufYSize, resolve_type(type), 0, 0), "Failed to write raster data");
}
void RasterDataSet::write_geometadata(const GeoMetadata& meta)
{
set_geotransform(metadata_to_geo_transform(meta));
set_projection(meta.projection);
if (raster_count() > 0) {
set_nodata_value(1, meta.nodata);
}
}
GeoMetadata RasterDataSet::geometadata() const
{
if (raster_count() != 1) {
throw RuntimeError("Multiple raster bands present, specify the band number");
}
return geometadata(1);
}
GeoMetadata RasterDataSet::geometadata(int bandNr) const
{
GeoMetadata meta;
meta.cols = x_size();
meta.rows = y_size();
meta.nodata = nodata_value(bandNr);
meta.projection = projection();
fill_geometadata_from_geo_transform(meta, geotransform());
return meta;
}
void RasterDataSet::flush_cache()
{
_ptr->FlushCache();
}
void RasterDataSet::add_band(GDALDataType type, const void* data)
{
// convert the data pointer to a string
std::array<char, 32> buf;
auto writtenCharacters = CPLPrintPointer(buf.data(), const_cast<void*>(data), truncate<int>(buf.size()));
buf[writtenCharacters] = 0;
auto pointerString = fmt::format("DATAPOINTER={}", buf.data());
std::array<const char*, 2> options{{pointerString.c_str(), nullptr}};
_ptr->AddBand(type, const_cast<char**>(options.data()));
}
RasterStats RasterDataSet::statistics(int bandNr, bool allowApproximation, bool force)
{
auto* band = _ptr->GetRasterBand(bandNr);
if (band == nullptr) {
throw RuntimeError("Invalid dataset band number: {}", bandNr);
}
RasterStats stats;
check_error(band->GetStatistics(allowApproximation ? TRUE : FALSE, force ? TRUE : FALSE, &stats.min, &stats.max, &stats.mean, &stats.stddev), "Failed to obtain raster statistics");
return stats;
}
void RasterDataSet::build_overviews(ResampleAlgorithm resample, std::span<const int32_t> levels)
{
check_error(_ptr->BuildOverviews(resample_algo_to_string(resample).c_str(), truncate<int32_t>(levels.size()), levels.data(), 0, nullptr, GDALDummyProgress, nullptr), "Failed to build raster overviews");
}
GDALDataset* RasterDataSet::get() const
{
return _ptr;
}
RasterDriver RasterDataSet::driver()
{
return RasterDriver(*_ptr->GetDriver());
}
RasterDriver RasterDataSet::driver() const
{
return RasterDriver(*_ptr->GetDriver());
}
VectorDataSet VectorDataSet::create(const fs::path& filePath, const std::vector<std::string>& driverOptions)
{
return open(filePath, driverOptions);
}
VectorDataSet VectorDataSet::create(const fs::path& filePath, VectorType type, const std::vector<std::string>& driverOptions)
{
return open(filePath, type, driverOptions);
}
static VectorDataSet open_vector_impl(OpenMode mode, const fs::path& filePath, const std::vector<std::string>& driverOptions)
{
auto* dsPtr = create_data_set(filePath, open_mode_to_gdal_mode(mode) | GDAL_OF_VECTOR, nullptr, driverOptions);
if (!dsPtr) {
throw RuntimeError("Failed to open vector file '{}'", filePath);
}
return VectorDataSet(dsPtr);
}
static VectorDataSet open_vector_impl(OpenMode mode, const fs::path& filePath, VectorType type, const std::vector<std::string>& driverOptions)
{
if (type == VectorType::Unknown) {
type = guess_vectortype_from_filename(filePath);
if (type == VectorType::Unknown) {
throw RuntimeError("Failed to determine vector type for file ('{}')", filePath);
}
}
std::array<const char*, 2> drivers{{s_vectorDriverLookup.at(type), nullptr}};
auto* dsPtr = create_data_set(filePath, open_mode_to_gdal_mode(mode) | GDAL_OF_VECTOR, drivers.data(), driverOptions);
if (!dsPtr) {
throw RuntimeError("Failed to open vector file '{}'", filePath);
}
return VectorDataSet(dsPtr);
}
VectorDataSet VectorDataSet::open(const fs::path& filePath, const std::vector<std::string>& driverOptions)
{
return open_vector_impl(OpenMode::ReadOnly, filePath, driverOptions);
}
VectorDataSet VectorDataSet::open(const fs::path& filePath, VectorType type, const std::vector<std::string>& driverOptions)
{
return open_vector_impl(OpenMode::ReadOnly, filePath, type, driverOptions);
}
VectorDataSet VectorDataSet::open_for_writing(const fs::path& filePath, const std::vector<std::string>& driverOptions)
{
return open_vector_impl(OpenMode::ReadWrite, filePath, driverOptions);
}
VectorDataSet VectorDataSet::open_for_writing(const fs::path& filePath, VectorType type, const std::vector<std::string>& driverOptions)
{
return open_vector_impl(OpenMode::ReadWrite, filePath, type, driverOptions);
}
VectorDataSet::VectorDataSet(GDALDataset* ptr) noexcept
: _ptr(ptr)
{
}
VectorDataSet::VectorDataSet(VectorDataSet&& rhs) noexcept
: _ptr(rhs._ptr)
{
rhs._ptr = nullptr;
}
VectorDataSet::~VectorDataSet() noexcept
{
GDALClose(reinterpret_cast<GDALDatasetH>(_ptr));
}
VectorDataSet& VectorDataSet::operator=(VectorDataSet&& rhs)
{
if (_ptr) {
GDALClose(reinterpret_cast<GDALDatasetH>(_ptr));
}
_ptr = rhs._ptr;
rhs._ptr = nullptr;
return *this;
}
bool VectorDataSet::is_valid() const
{
return _ptr != nullptr;
}
int32_t VectorDataSet::layer_count() const
{
assert(_ptr);
return _ptr->GetLayerCount();
}
std::string VectorDataSet::projection() const
{
assert(_ptr);
return _ptr->GetProjectionRef();
}
void VectorDataSet::set_projection(const std::string& proj)
{
assert(_ptr);
if (!proj.empty()) {
check_error(_ptr->SetProjection(proj.c_str()), "Failed to set projection");
}
}
void VectorDataSet::set_metadata(const std::string& name, const std::string& value, const std::string& domain)
{
check_error(_ptr->SetMetadataItem(name.c_str(), value.c_str(), domain.c_str()), "Failed to set metadata");
}
Layer VectorDataSet::layer(int index)
{
assert(_ptr);
return Layer(check_pointer(_ptr->GetLayer(index), "Invalid layer index"));
}
Layer VectorDataSet::layer(const std::string& name)
{
assert(_ptr);
return Layer(check_pointer_msg_cb(_ptr->GetLayerByName(name.c_str()), [&]() {
return fmt::format("Invalid layer name: {}", name);
}));
}
bool VectorDataSet::layer_exists(const std::string& name) const noexcept
{
assert(_ptr);
return _ptr->GetLayerByName(name.c_str()) != nullptr;
}
Layer VectorDataSet::create_layer(const std::string& name, const std::vector<std::string>& driverOptions)
{
return create_layer(name, Geometry::Type::Unknown, driverOptions);
}
static OGRwkbGeometryType to_gdal_type(Geometry::Type type)
{
switch (type) {
case Geometry::Type::Point:
return wkbPoint;
case Geometry::Type::Collection:
return wkbGeometryCollection;
case Geometry::Type::Line:
return wkbLineString;
case Geometry::Type::MultiLine:
return wkbMultiLineString;
case Geometry::Type::Polygon:
return wkbPolygon;
case Geometry::Type::MultiPolygon:
return wkbMultiPolygon;
case Geometry::Type::Unknown:
default:
return wkbUnknown;
}
}
Layer VectorDataSet::create_layer(const std::string& name, Geometry::Type type, const std::vector<std::string>& driverOptions)
{