-
Notifications
You must be signed in to change notification settings - Fork 30
/
Copy pathgodal.go
4345 lines (3963 loc) · 124 KB
/
godal.go
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
// Copyright 2021 Airbus Defence and Space
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package godal
/*
#include "godal.h"
#include <stdlib.h>
#cgo pkg-config: gdal
#cgo CXXFLAGS: -std=c++11
#cgo LDFLAGS: -ldl
*/
import "C"
import (
"errors"
"fmt"
"io"
"path/filepath"
"strconv"
"strings"
"sync"
"time"
"unsafe"
)
// DataType is a pixel data types
type DataType int
const (
//Unknown / Unset Datatype
Unknown = DataType(C.GDT_Unknown)
//Byte / UInt8
Byte = DataType(C.GDT_Byte)
//UInt16 DataType
UInt16 = DataType(C.GDT_UInt16)
//Int8 DataType (GDAL>=3.7.0)
// [RFC 87]: https://gdal.org/development/rfc/rfc87_signed_int8.html
Int8 = DataType(C.GDT_Int8)
//Int16 DataType
Int16 = DataType(C.GDT_Int16)
//UInt32 DataType
UInt32 = DataType(C.GDT_UInt32)
//Int32 DataType
Int32 = DataType(C.GDT_Int32)
//Float32 DataType
Float32 = DataType(C.GDT_Float32)
//Float64 DataType
Float64 = DataType(C.GDT_Float64)
//CInt16 is a complex Int16
CInt16 = DataType(C.GDT_CInt16)
//CInt32 is a complex Int32
CInt32 = DataType(C.GDT_CInt32)
//CFloat32 is a complex Float32
CFloat32 = DataType(C.GDT_CFloat32)
//CFloat64 is a complex Float64
CFloat64 = DataType(C.GDT_CFloat64)
)
// ErrorCategory wraps GDAL's error types
type ErrorCategory int
const (
// CE_None is not an error
CE_None = ErrorCategory(C.CE_None)
// CE_Debug is a debug level
CE_Debug = ErrorCategory(C.CE_Debug)
// CE_Warning is a warning levele
CE_Warning = ErrorCategory(C.CE_Warning)
// CE_Failure is an error
CE_Failure = ErrorCategory(C.CE_Failure)
// CE_Fatal is an unrecoverable error
CE_Fatal = ErrorCategory(C.CE_Fatal)
)
// String implements Stringer
func (dtype DataType) String() string {
return C.GoString(C.GDALGetDataTypeName(C.GDALDataType(dtype)))
}
// Size retruns the number of bytes needed for one instance of DataType
func (dtype DataType) Size() int {
switch dtype {
case Byte, Int8:
return 1
case Int16, UInt16:
return 2
case Int32, UInt32, Float32, CInt16:
return 4
case CInt32, Float64, CFloat32:
return 8
case CFloat64:
return 16
default:
panic("unsupported type")
}
}
// ColorInterp is a band's color interpretation
type ColorInterp int
const (
//CIUndefined is an undefined ColorInterp
CIUndefined = ColorInterp(C.GCI_Undefined)
//CIGray is a gray level ColorInterp
CIGray = ColorInterp(C.GCI_GrayIndex)
//CIPalette is an undefined ColorInterp
CIPalette = ColorInterp(C.GCI_PaletteIndex)
//CIRed is a paletted ColorInterp
CIRed = ColorInterp(C.GCI_RedBand)
//CIGreen is a Green ColorInterp
CIGreen = ColorInterp(C.GCI_GreenBand)
//CIBlue is a Blue ColorInterp
CIBlue = ColorInterp(C.GCI_BlueBand)
//CIAlpha is an Alpha/Transparency ColorInterp
CIAlpha = ColorInterp(C.GCI_AlphaBand)
//CIHue is an HSL Hue ColorInterp
CIHue = ColorInterp(C.GCI_HueBand)
//CISaturation is an HSL Saturation ColorInterp
CISaturation = ColorInterp(C.GCI_SaturationBand)
//CILightness is an HSL Lightness ColorInterp
CILightness = ColorInterp(C.GCI_LightnessBand)
//CICyan is an CMYK Cyan ColorInterp
CICyan = ColorInterp(C.GCI_CyanBand)
//CIMagenta is an CMYK Magenta ColorInterp
CIMagenta = ColorInterp(C.GCI_MagentaBand)
//CIYellow is an CMYK Yellow ColorInterp
CIYellow = ColorInterp(C.GCI_YellowBand)
//CIBlack is an CMYK Black ColorInterp
CIBlack = ColorInterp(C.GCI_BlackBand)
//CIY is a YCbCr Y ColorInterp
CIY = ColorInterp(C.GCI_YCbCr_YBand)
//CICb is a YCbCr Cb ColorInterp
CICb = ColorInterp(C.GCI_YCbCr_CbBand)
//CICr is a YCbCr Cr ColorInterp
CICr = ColorInterp(C.GCI_YCbCr_CrBand)
//CIMax is an maximum ColorInterp
CIMax = ColorInterp(C.GCI_Max)
)
// Name returns the ColorInterp's name
func (colorInterp ColorInterp) Name() string {
return C.GoString(C.GDALGetColorInterpretationName(C.GDALColorInterp(colorInterp)))
}
// Band is a wrapper around a GDALRasterBandH
type Band struct {
majorObject
}
// handle() returns a pointer to the underlying GDALRasterBandH
func (band Band) handle() C.GDALRasterBandH {
return C.GDALRasterBandH(band.majorObject.cHandle)
}
// Structure returns the dataset's Structure
func (band Band) Structure() BandStructure {
var sx, sy, bsx, bsy, dtype C.int
var scale, offset C.double
C.godalBandStructure(band.handle(), &sx, &sy, &bsx, &bsy, &scale, &offset, &dtype)
return BandStructure{
SizeX: int(sx),
SizeY: int(sy),
BlockSizeX: int(bsx),
BlockSizeY: int(bsy),
Scale: float64(scale),
Offset: float64(offset),
DataType: DataType(int(dtype)),
}
}
// NoData returns the band's nodata value. if ok is false, the band does not
// have a nodata value set
func (band Band) NoData() (nodata float64, ok bool) {
cok := C.int(0)
cn := C.GDALGetRasterNoDataValue(band.handle(), &cok)
if cok != 0 {
return float64(cn), true
}
return 0, false
}
// SetNoData sets the band's nodata value
func (band Band) SetNoData(nd float64, opts ...SetNoDataOption) error {
sndo := &setNodataOpts{}
for _, opt := range opts {
opt.setSetNoDataOpt(sndo)
}
cgc := createCGOContext(nil, sndo.errorHandler)
C.godalSetRasterNoDataValue(cgc.cPointer(), band.handle(), C.double(nd))
return cgc.close()
}
// ClearNoData clears the band's nodata value
func (band Band) ClearNoData(opts ...SetNoDataOption) error {
sndo := &setNodataOpts{}
for _, opt := range opts {
opt.setSetNoDataOpt(sndo)
}
cgc := createCGOContext(nil, sndo.errorHandler)
C.godalDeleteRasterNoDataValue(cgc.cPointer(), band.handle())
return cgc.close()
}
// SetScaleOffset sets the band's scale and offset
func (band Band) SetScaleOffset(scale, offset float64, opts ...SetScaleOffsetOption) error {
setterOpts := &setScaleOffsetOpts{}
for _, opt := range opts {
opt.setSetScaleOffsetOpt(setterOpts)
}
cgc := createCGOContext(nil, setterOpts.errorHandler)
C.godalSetRasterScaleOffset(cgc.cPointer(), band.handle(), C.double(scale), C.double(offset))
return cgc.close()
}
// ClearScaleOffset clears the band's scale and offset
func (band Band) ClearScaleOffset(opts ...SetScaleOffsetOption) error {
return band.SetScaleOffset(1.0, 0.0, opts...)
}
// ColorInterp returns the band's color interpretation (defaults to Gray)
func (band Band) ColorInterp() ColorInterp {
colorInterp := C.GDALGetRasterColorInterpretation(band.handle())
return ColorInterp(colorInterp)
}
// SetColorInterp sets the band's color interpretation
func (band Band) SetColorInterp(colorInterp ColorInterp, opts ...SetColorInterpOption) error {
scio := &setColorInterpOpts{}
for _, opt := range opts {
opt.setSetColorInterpOpt(scio)
}
cgc := createCGOContext(nil, scio.errorHandler)
C.godalSetRasterColorInterpretation(cgc.cPointer(), band.handle(), C.GDALColorInterp(colorInterp))
return cgc.close()
}
// MaskFlags returns the mask flags associated with this band.
//
// See https://gdal.org/development/rfc/rfc15_nodatabitmask.html for how this flag
// should be interpreted
func (band Band) MaskFlags() int {
return int(C.GDALGetMaskFlags(band.handle()))
}
// MaskBand returns the mask (nodata) band for this band. May be generated from nodata values.
func (band Band) MaskBand() Band {
hndl := C.GDALGetMaskBand(band.handle())
return Band{majorObject{C.GDALMajorObjectH(hndl)}}
}
// CreateMask creates a mask (nodata) band for this band.
//
// Any handle returned by a previous call to MaskBand() should not be used after a call to CreateMask
// See https://gdal.org/development/rfc/rfc15_nodatabitmask.html for how flag should be used
func (band Band) CreateMask(flags int, opts ...BandCreateMaskOption) (Band, error) {
gopts := bandCreateMaskOpts{}
for _, opt := range opts {
opt.setBandCreateMaskOpt(&gopts)
}
cgc := createCGOContext(gopts.config, gopts.errorHandler)
hndl := C.godalCreateMaskBand(cgc.cPointer(), band.handle(), C.int(flags))
if err := cgc.close(); err != nil {
return Band{}, err
}
return Band{majorObject{C.GDALMajorObjectH(hndl)}}, nil
}
// Fill sets the whole band uniformely to (real,imag)
func (band Band) Fill(real, imag float64, opts ...FillBandOption) error {
fo := &fillBandOpts{}
for _, o := range opts {
o.setFillBandOpt(fo)
}
cgc := createCGOContext(nil, fo.errorHandler)
C.godalFillRaster(cgc.cPointer(), band.handle(), C.double(real), C.double(imag))
return cgc.close()
}
// Read populates the supplied buffer with the pixels contained in the supplied window
func (band Band) Read(srcX, srcY int, buffer interface{}, bufWidth, bufHeight int, opts ...BandIOOption) error {
return band.IO(IORead, srcX, srcY, buffer, bufWidth, bufHeight, opts...)
}
// Write sets the dataset's pixels contained in the supplied window to the content of the supplied buffer
func (band Band) Write(srcX, srcY int, buffer interface{}, bufWidth, bufHeight int, opts ...BandIOOption) error {
return band.IO(IOWrite, srcX, srcY, buffer, bufWidth, bufHeight, opts...)
}
// IO reads or writes the pixels contained in the supplied window
func (band Band) IO(rw IOOperation, srcX, srcY int, buffer interface{}, bufWidth, bufHeight int, opts ...BandIOOption) error {
ro := bandIOOpts{}
for _, opt := range opts {
opt.setBandIOOpt(&ro)
}
if ro.dsHeight == 0 {
ro.dsHeight = bufHeight
}
if ro.dsWidth == 0 {
ro.dsWidth = bufWidth
}
dtype := bufferType(buffer)
dsize := dtype.Size()
pixelSpacing := dsize
if ro.pixelSpacing > 0 {
pixelSpacing = ro.pixelSpacing
}
if ro.pixelStride > 0 {
pixelSpacing = ro.pixelStride * dsize
}
lineSpacing := bufWidth * pixelSpacing
if ro.lineSpacing > 0 {
lineSpacing = ro.lineSpacing
}
if ro.lineStride > 0 {
lineSpacing = ro.lineStride * dsize
}
minsize := (lineSpacing*(bufHeight-1) + (bufWidth-1)*pixelSpacing + dsize) / dsize
cBuf := cBuffer(buffer, minsize)
//fmt.Fprintf(os.Stderr, "%v %d %d %d\n", ro.bands, pixelSpacing, lineSpacing, bandSpacing)
ralg, err := ro.resampling.rioAlg()
if err != nil {
return err
}
cgc := createCGOContext(ro.config, ro.errorHandler)
C.godalBandRasterIO(cgc.cPointer(), band.handle(), C.GDALRWFlag(rw),
C.int(srcX), C.int(srcY), C.int(ro.dsWidth), C.int(ro.dsHeight),
cBuf,
C.int(bufWidth), C.int(bufHeight), C.GDALDataType(dtype),
C.int(pixelSpacing), C.int(lineSpacing), ralg)
return cgc.close()
}
// Polygonize wraps GDALPolygonize
func (band Band) Polygonize(dstLayer Layer, opts ...PolygonizeOption) error {
popt := polygonizeOpts{
pixFieldIndex: -1,
}
maskBand := band.MaskBand()
popt.mask = &maskBand
for _, opt := range opts {
opt.setPolygonizeOpt(&popt)
}
copts := sliceToCStringArray(popt.options)
defer copts.free()
var cMaskBand C.GDALRasterBandH = nil
if popt.mask != nil {
cMaskBand = popt.mask.handle()
}
cgc := createCGOContext(nil, popt.errorHandler)
C.godalPolygonize(cgc.cPointer(), band.handle(), cMaskBand, dstLayer.handle(), C.int(popt.pixFieldIndex), copts.cPointer())
return cgc.close()
}
// FillNoData wraps GDALFillNodata()
func (band Band) FillNoData(opts ...FillNoDataOption) error {
popt := fillnodataOpts{
maxDistance: 100,
iterations: 0,
}
for _, opt := range opts {
opt.setFillnodataOpt(&popt)
}
//copts := sliceToCStringArray(popt.options)
//defer copts.free()
var cMaskBand C.GDALRasterBandH = nil
if popt.mask != nil {
cMaskBand = popt.mask.handle()
}
cgc := createCGOContext(nil, popt.errorHandler)
C.godalFillNoData(cgc.cPointer(), band.handle(), cMaskBand, C.int(popt.maxDistance), C.int(popt.iterations), nil)
return cgc.close()
}
// SieveFilter wraps GDALSieveFilter
func (band Band) SieveFilter(sizeThreshold int, opts ...SieveFilterOption) error {
sfopt := sieveFilterOpts{
dstBand: &band,
connectedness: 4,
}
maskBand := band.MaskBand()
sfopt.mask = &maskBand
for _, opt := range opts {
opt.setSieveFilterOpt(&sfopt)
}
var cMaskBand C.GDALRasterBandH = nil
if sfopt.mask != nil {
cMaskBand = sfopt.mask.handle()
}
cgc := createCGOContext(nil, sfopt.errorHandler)
C.godalSieveFilter(cgc.cPointer(), band.handle(), cMaskBand, sfopt.dstBand.handle(),
C.int(sizeThreshold), C.int(sfopt.connectedness))
return cgc.close()
}
// Overviews returns all overviews of band
func (band Band) Overviews() []Band {
cbands := C.godalBandOverviews(band.handle())
if cbands == nil {
return nil
}
defer C.free(unsafe.Pointer(cbands))
//https://github.com/golang/go/wiki/cgo#turning-c-arrays-into-go-slices
sBands := (*[1 << 30]C.GDALRasterBandH)(unsafe.Pointer(cbands))
bands := []Band{}
i := 0
for {
if sBands[i] == nil {
return bands
}
bands = append(bands, Band{majorObject{C.GDALMajorObjectH(sBands[i])}})
i++
}
}
// Histogram returns or computes the bands histogram
func (band Band) Histogram(opts ...HistogramOption) (Histogram, error) {
hopt := histogramOpts{}
for _, o := range opts {
o.setHistogramOpt(&hopt)
}
var values *C.ulonglong = nil
defer C.VSIFree(unsafe.Pointer(values))
cgc := createCGOContext(nil, hopt.errorHandler)
C.godalRasterHistogram(cgc.cPointer(), band.handle(), (*C.double)(&hopt.min), (*C.double)(&hopt.max), (*C.int)(&hopt.buckets),
&values, C.int(hopt.includeOutside), C.int(hopt.approx))
if err := cgc.close(); err != nil {
return Histogram{}, err
}
counts := (*[1 << 30]C.ulonglong)(unsafe.Pointer(values))
h := Histogram{
min: hopt.min,
max: hopt.max,
counts: make([]uint64, hopt.buckets),
}
for i := int32(0); i < hopt.buckets; i++ {
h.counts[i] = uint64(counts[i])
}
return h, nil
}
// GetStatistics returns if present and flag as true.
//
// Only cached statistics are returned and no new statistics are computed.
// Return false and no error if no statistics are availables.
// Available options are:
// - Aproximate() to allow the satistics to be computed on overviews or a subset of all tiles.
// - ErrLogger
func (band Band) GetStatistics(opts ...StatisticsOption) (Statistics, bool, error) {
sopt := statisticsOpts{}
for _, s := range opts {
s.setStatisticsOpt(&sopt)
}
var min, max, mean, std C.double
cgc := createCGOContext(nil, sopt.errorHandler)
ret := C.godalGetRasterStatistics(cgc.cPointer(), band.handle(),
(C.int)(sopt.approx), &min, &max, &mean, &std)
if err := cgc.close(); err != nil {
return Statistics{}, false, err
}
if ret == 0 {
return Statistics{}, false, nil
}
var ap bool = sopt.approx != 0
s := Statistics{
Approximate: ap,
Min: float64(min),
Max: float64(max),
Mean: float64(mean),
Std: float64(std),
}
return s, true, nil
}
// ComputeStatistics returns from exact computation or approximation.
//
// Band full scan might be necessary.
// Available options are:
// - Aproximate() to allow the satistics to be computed on overviews or a subset of all tiles.
// - ErrLogger
func (band Band) ComputeStatistics(opts ...StatisticsOption) (Statistics, error) {
sopt := statisticsOpts{}
for _, s := range opts {
s.setStatisticsOpt(&sopt)
}
var min, max, mean, std C.double
cgc := createCGOContext(nil, sopt.errorHandler)
C.godalComputeRasterStatistics(cgc.cPointer(), band.handle(),
(C.int)(sopt.approx), &min, &max, &mean, &std)
if err := cgc.close(); err != nil {
return Statistics{}, err
}
var ap bool = sopt.approx != 0
s := Statistics{
Min: float64(min),
Max: float64(max),
Mean: float64(mean),
Std: float64(std),
Approximate: ap,
}
return s, nil
}
// SetStatistics set statistics (Min, Max, Mean & STD).
//
// Available options are:
//
// -ErrLogger
func (band Band) SetStatistics(min, max, mean, std float64, opts ...SetStatisticsOption) error {
stso := setStatisticsOpt{}
for _, opt := range opts {
opt.setSetStatisticsOpt(&stso)
}
cgc := createCGOContext(nil, stso.errorHandler)
C.godalSetRasterStatistics(cgc.cPointer(), band.handle(), C.double(min),
C.double(max), C.double(mean), C.double(std))
if err := cgc.close(); err != nil {
return err
}
return nil
}
func cIntArray(in []int) *C.int {
var ptr *C.int
if len(in) > 0 {
ret := make([]C.int, len(in))
for i := range in {
ret[i] = C.int(in[i])
}
ptr = (*C.int)(unsafe.Pointer(&ret[0]))
}
return ptr
}
func cLongArray(in []int64) *C.longlong {
var ptr *C.longlong
if len(in) > 0 {
ret := make([]C.longlong, len(in))
for i := range in {
ret[i] = C.longlong(in[i])
}
ptr = (*C.longlong)(unsafe.Pointer(&ret[0]))
}
return ptr
}
func cDoubleArray(in []float64) *C.double {
var ptr *C.double
if len(in) > 0 {
ret := make([]C.double, len(in))
for i := range in {
ret[i] = C.double(in[i])
}
ptr = (*C.double)(unsafe.Pointer(&ret[0]))
}
return ptr
}
type cStringArray struct {
arr **C.char
l int
}
func (ca cStringArray) free() {
if ca.l > 0 {
garr := (*[1 << 30]*C.char)(unsafe.Pointer(ca.arr))[0:ca.l:ca.l]
for i := 0; i < ca.l-1; i++ {
C.free(unsafe.Pointer(garr[i]))
}
C.free(unsafe.Pointer(ca.arr))
}
}
func (ca cStringArray) cPointer() **C.char {
return ca.arr
}
func sliceToCStringArray(in []string) cStringArray {
if len(in) > 0 {
csa := cStringArray{l: len(in) + 1}
csa.arr = (**C.char)(C.malloc(C.size_t(csa.l) * C.size_t(unsafe.Sizeof((*C.char)(nil)))))
garr := (*[1 << 30]*C.char)(unsafe.Pointer(csa.arr))[0:csa.l:csa.l]
for i := range in {
garr[i] = C.CString(in[i])
}
garr[len(in)] = nil
return csa
}
return cStringArray{}
}
func cStringArrayToSlice(in **C.char) []string {
if in == nil {
return nil
}
//https://github.com/golang/go/wiki/cgo#turning-c-arrays-into-go-slices
cStrs := (*[1 << 30]*C.char)(unsafe.Pointer(in))
i := 0
ret := []string{}
for {
if cStrs[i] == nil {
return ret
}
ret = append(ret, C.GoString(cStrs[i]))
i++
}
}
func cIntArrayToSlice(in *C.int, length C.int) []int64 {
if in == nil {
return nil
}
cSlice := (*[1 << 28]C.int)(unsafe.Pointer(in))[:length:length]
slice := make([]int64, length)
for i, cval := range cSlice {
slice[i] = int64(cval)
}
return slice
}
func cLongArrayToSlice(in *C.longlong, length C.int) []int64 {
if in == nil {
return nil
}
cSlice := (*[1 << 28]C.longlong)(unsafe.Pointer(in))[:length:length]
slice := make([]int64, length)
for i, cval := range cSlice {
slice[i] = int64(cval)
}
return slice
}
func cDoubleArrayToSlice(in *C.double, length C.int) []float64 {
if in == nil {
return nil
}
cSlice := (*[1 << 28]C.double)(unsafe.Pointer(in))[:length:length]
slice := make([]float64, length)
for i, cval := range cSlice {
slice[i] = float64(cval)
}
return slice
}
// PaletteInterp defines the color interpretation of a ColorTable
type PaletteInterp C.GDALPaletteInterp
const (
//GrayscalePalette is a grayscale palette with a single component per entry
GrayscalePalette PaletteInterp = C.GPI_Gray
//RGBPalette is a RGBA palette with 4 components per entry
RGBPalette PaletteInterp = C.GPI_RGB
//CMYKPalette is a CMYK palette with 4 components per entry
CMYKPalette PaletteInterp = C.GPI_CMYK
//HLSPalette is a HLS palette with 3 components per entry
HLSPalette PaletteInterp = C.GPI_HLS
)
// ColorTable is a color table associated with a Band
type ColorTable struct {
PaletteInterp PaletteInterp
Entries [][4]int16
}
func cColorTableArray(in [][4]int16) *C.short {
ret := make([]C.short, len(in)*4)
for i := range in {
ret[4*i] = C.short(in[i][0])
ret[4*i+1] = C.short(in[i][1])
ret[4*i+2] = C.short(in[i][2])
ret[4*i+3] = C.short(in[i][3])
}
return (*C.short)(unsafe.Pointer(&ret[0]))
}
func ctEntriesFromCshorts(arr *C.short, nEntries int) [][4]int16 {
int16s := (*[1 << 30]C.short)(unsafe.Pointer(arr))
ret := make([][4]int16, nEntries)
for i := 0; i < nEntries; i++ {
ret[i][0] = int16(int16s[i*4])
ret[i][1] = int16(int16s[i*4+1])
ret[i][2] = int16(int16s[i*4+2])
ret[i][3] = int16(int16s[i*4+3])
}
return ret
}
// ColorTable returns the bands color table. The returned ColorTable will have
// a 0-length Entries if the band has no color table assigned
func (band Band) ColorTable() ColorTable {
var interp C.GDALPaletteInterp
var nEntries C.int
var cEntries *C.short
C.godalGetColorTable(band.handle(), &interp, &nEntries, &cEntries)
if cEntries != nil {
defer C.free(unsafe.Pointer(cEntries))
}
return ColorTable{
PaletteInterp: PaletteInterp(interp),
Entries: ctEntriesFromCshorts(cEntries, int(nEntries)),
}
}
// SetColorTable sets the band's color table. if passing in a 0-length ct.Entries,
// the band's color table will be cleared
func (band Band) SetColorTable(ct ColorTable, opts ...SetColorTableOption) error {
cto := &setColorTableOpts{}
for _, o := range opts {
o.setSetColorTableOpt(cto)
}
var cshorts *C.short
if len(ct.Entries) > 0 {
cshorts = cColorTableArray(ct.Entries)
}
cgc := createCGOContext(nil, cto.errorHandler)
C.godalSetColorTable(cgc.cPointer(), band.handle(), C.GDALPaletteInterp(ct.PaletteInterp), C.int(len(ct.Entries)), cshorts)
return cgc.close()
}
// Bands returns all dataset bands.
func (ds *Dataset) Bands() []Band {
cbands := C.godalRasterBands(ds.handle())
if cbands == nil {
return nil
}
defer C.free(unsafe.Pointer(cbands))
//https://github.com/golang/go/wiki/cgo#turning-c-arrays-into-go-slices
sBands := (*[1 << 30]C.GDALRasterBandH)(unsafe.Pointer(cbands))
bands := []Band{}
i := 0
for {
if sBands[i] == nil {
return bands
}
bands = append(bands, Band{majorObject{C.GDALMajorObjectH(sBands[i])}})
i++
}
}
// Bounds returns the dataset's bounding box in the order
//
// [MinX, MinY, MaxX, MaxY]
func (ds *Dataset) Bounds(opts ...BoundsOption) ([4]float64, error) {
bo := boundsOpts{}
for _, o := range opts {
o.setBoundsOpt(&bo)
}
ret := [4]float64{}
st := ds.Structure()
gt, err := ds.GeoTransform()
if err != nil {
return ret, fmt.Errorf("get geotransform: %w", err)
}
ret[0] = gt[0]
ret[1] = gt[3]
ret[2] = gt[0] + float64(st.SizeX)*gt[1] + float64(st.SizeY)*gt[2]
ret[3] = gt[3] + float64(st.SizeX)*gt[4] + float64(st.SizeY)*gt[5]
if bo.sr != nil {
srcsr := ds.SpatialRef()
defer srcsr.Close()
ret, err = reprojectBounds(ret, srcsr, bo.sr)
if err != nil {
return ret, err
}
}
if ret[0] > ret[2] {
ret[2], ret[0] = ret[0], ret[2]
}
if ret[1] > ret[3] {
ret[3], ret[1] = ret[1], ret[3]
}
return ret, nil
}
// CreateMaskBand creates a mask (nodata) band shared for all bands of this dataset.
//
// Any handle returned by a previous call to Band.MaskBand() should not be used after a call to CreateMaskBand
// See https://gdal.org/development/rfc/rfc15_nodatabitmask.html for how flag should be used
func (ds *Dataset) CreateMaskBand(flags int, opts ...DatasetCreateMaskOption) (Band, error) {
gopts := dsCreateMaskOpts{}
for _, opt := range opts {
opt.setDatasetCreateMaskOpt(&gopts)
}
cgc := createCGOContext(gopts.config, gopts.errorHandler)
hndl := C.godalCreateDatasetMaskBand(cgc.cPointer(), ds.handle(), C.int(flags))
if err := cgc.close(); err != nil {
return Band{}, err
}
return Band{majorObject{C.GDALMajorObjectH(hndl)}}, nil
}
// Driver returns dataset driver.
func (ds *Dataset) Driver() Driver {
return Driver{majorObject{C.GDALMajorObjectH(C.GDALGetDatasetDriver(ds.handle()))}}
}
// Projection returns the WKT projection of the dataset. May be empty.
func (ds *Dataset) Projection() string {
str := C.GDALGetProjectionRef(ds.handle())
return C.GoString(str)
}
// SetProjection sets the WKT projection of the dataset. May be empty.
func (ds *Dataset) SetProjection(wkt string, opts ...SetProjectionOption) error {
po := &setProjectionOpts{}
for _, o := range opts {
o.setSetProjectionOpt(po)
}
var cwkt = (*C.char)(nil)
if len(wkt) > 0 {
cwkt = C.CString(wkt)
defer C.free(unsafe.Pointer(cwkt))
}
cgc := createCGOContext(nil, po.errorHandler)
C.godalSetProjection(cgc.cPointer(), ds.handle(), cwkt)
return cgc.close()
}
// SpatialRef returns dataset projection.
func (ds *Dataset) SpatialRef() *SpatialRef {
hndl := C.GDALGetSpatialRef(ds.handle())
return &SpatialRef{handle: hndl, isOwned: false}
}
// SetSpatialRef sets dataset's projection.
//
// sr can be set to nil to clear an existing projection
func (ds *Dataset) SetSpatialRef(sr *SpatialRef, opts ...SetSpatialRefOption) error {
sro := &setSpatialRefOpts{}
for _, o := range opts {
o.setSetSpatialRefOpt(sro)
}
var hndl C.OGRSpatialReferenceH
if sr == nil {
hndl = nil
} else {
hndl = sr.handle
}
cgc := createCGOContext(nil, sro.errorHandler)
C.godalDatasetSetSpatialRef(cgc.cPointer(), ds.handle(), hndl)
return cgc.close()
}
// GeoTransform returns the affine transformation coefficients
func (ds *Dataset) GeoTransform(opts ...GetGeoTransformOption) ([6]float64, error) {
gto := &getGeoTransformOpts{}
for _, o := range opts {
o.setGetGeoTransformOpt(gto)
}
ret := [6]float64{}
gt := make([]C.double, 6)
cgt := (*C.double)(unsafe.Pointer(>[0]))
cgc := createCGOContext(nil, gto.errorHandler)
C.godalGetGeoTransform(cgc.cPointer(), ds.handle(), cgt)
if err := cgc.close(); err != nil {
return ret, err
}
for i := range ret {
ret[i] = float64(gt[i])
}
return ret, nil
}
// SetGeoTransform sets the affine transformation coefficients
func (ds *Dataset) SetGeoTransform(transform [6]float64, opts ...SetGeoTransformOption) error {
gto := &setGeoTransformOpts{}
for _, o := range opts {
o.setSetGeoTransformOpt(gto)
}
gt := cDoubleArray(transform[:])
cgc := createCGOContext(nil, gto.errorHandler)
C.godalSetGeoTransform(cgc.cPointer(), ds.handle(), gt)
return cgc.close()
}
// SetNoData sets the band's nodata value
func (ds *Dataset) SetNoData(nd float64, opts ...SetNoDataOption) error {
sndo := &setNodataOpts{}
for _, opt := range opts {
opt.setSetNoDataOpt(sndo)
}
cgc := createCGOContext(nil, sndo.errorHandler)
C.godalSetDatasetNoDataValue(cgc.cPointer(), ds.handle(), C.double(nd))
return cgc.close()
}
// SetScaleOffset sets the band's scale and offset
func (ds *Dataset) SetScaleOffset(scale, offset float64, opts ...SetScaleOffsetOption) error {
setterOpts := &setScaleOffsetOpts{}
for _, opt := range opts {
opt.setSetScaleOffsetOpt(setterOpts)
}
cgc := createCGOContext(nil, setterOpts.errorHandler)
C.godalSetDatasetScaleOffset(cgc.cPointer(), ds.handle(), C.double(scale), C.double(offset))
return cgc.close()
}
// Translate runs the library version of gdal_translate.
// See the gdal_translate doc page to determine the valid flags/opts that can be set in switches.
//
// Example switches :
//
// []string{
// "-a_nodata", 0,
// "-a_srs", "epsg:4326"}
//
// Creation options and driver may be set either in the switches slice with
//
// switches:=[]string{"-co","TILED=YES","-of","GTiff"}
//
// or through Options with
//
// ds.Translate(dst, switches, CreationOption("TILED=YES","BLOCKXSIZE=256"), GTiff)
func (ds *Dataset) Translate(dstDS string, switches []string, opts ...DatasetTranslateOption) (*Dataset, error) {
gopts := dsTranslateOpts{}
for _, opt := range opts {
opt.setDatasetTranslateOpt(&gopts)
}
for _, copt := range gopts.creation {
switches = append(switches, "-co", copt)
}
if gopts.driver != "" {
dname := string(gopts.driver)
if dm, ok := driverMappings[gopts.driver]; ok {
dname = dm.rasterName
}
switches = append(switches, "-of", dname)
}
cswitches := sliceToCStringArray(switches)
defer cswitches.free()
cname := unsafe.Pointer(C.CString(dstDS))
defer C.free(cname)
cgc := createCGOContext(gopts.config, gopts.errorHandler)
hndl := C.godalTranslate(cgc.cPointer(), (*C.char)(cname), ds.handle(), cswitches.cPointer())
if err := cgc.close(); err != nil {
return nil, err
}
return &Dataset{majorObject{C.GDALMajorObjectH(hndl)}}, nil
}
// Warp runs the library version of gdalwarp
// See the gdalwarp doc page to determine the valid flags/opts that can be set in switches.
//
// Example switches :
//
// []string{
// "-t_srs","epsg:3857",
// "-dstalpha"}
//
// Creation options and driver may be set either in the switches slice with
//
// switches:=[]string{"-co","TILED=YES","-of","GTiff"}
//
// or through Options with
//
// ds.Warp(dst, switches, CreationOption("TILED=YES","BLOCKXSIZE=256"), GTiff)
func (ds *Dataset) Warp(dstDS string, switches []string, opts ...DatasetWarpOption) (*Dataset, error) {
return Warp(dstDS, []*Dataset{ds}, switches, opts...)
}
// Warp writes provided sourceDS Datasets into new dataset and runs the library version of gdalwarp
// See the gdalwarp doc page to determine the valid flags/opts that can be set in switches.
//
// Example switches :
//
// []string{
// "-t_srs","epsg:3857",
// "-dstalpha"}
//
// Creation options and driver may be set either in the switches slice with
//
// switches:=[]string{"-co","TILED=YES","-of","GTiff"}
//
// or through Options with
//
// ds.Warp(dst, switches, CreationOption("TILED=YES","BLOCKXSIZE=256"), GTiff)
func Warp(dstDS string, sourceDS []*Dataset, switches []string, opts ...DatasetWarpOption) (*Dataset, error) {